id stringlengths 25 30 | content stringlengths 14 942k | max_stars_repo_path stringlengths 49 55 |
|---|---|---|
crossvul-cpp_data_bad_4005_0 | /*
* Marvell Wireless LAN device driver: WMM
*
* Copyright (C) 2011-2014, Marvell International Ltd.
*
* This software file (the "File") is distributed by Marvell International
* Ltd. under the terms of the GNU General Public License Version 2, June 1991
* (the "License"). You may use, redistribute and/or modify this File in
* accordance with the terms and conditions of the License, a copy of which
* is available by writing to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or on the
* worldwide web at http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND, AND THE
* IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE
* ARE EXPRESSLY DISCLAIMED. The License provides additional details about
* this warranty disclaimer.
*/
#include "decl.h"
#include "ioctl.h"
#include "util.h"
#include "fw.h"
#include "main.h"
#include "wmm.h"
#include "11n.h"
/* Maximum value FW can accept for driver delay in packet transmission */
#define DRV_PKT_DELAY_TO_FW_MAX 512
#define WMM_QUEUED_PACKET_LOWER_LIMIT 180
#define WMM_QUEUED_PACKET_UPPER_LIMIT 200
/* Offset for TOS field in the IP header */
#define IPTOS_OFFSET 5
static bool disable_tx_amsdu;
module_param(disable_tx_amsdu, bool, 0644);
/* WMM information IE */
static const u8 wmm_info_ie[] = { WLAN_EID_VENDOR_SPECIFIC, 0x07,
0x00, 0x50, 0xf2, 0x02,
0x00, 0x01, 0x00
};
static const u8 wmm_aci_to_qidx_map[] = { WMM_AC_BE,
WMM_AC_BK,
WMM_AC_VI,
WMM_AC_VO
};
static u8 tos_to_tid[] = {
/* TID DSCP_P2 DSCP_P1 DSCP_P0 WMM_AC */
0x01, /* 0 1 0 AC_BK */
0x02, /* 0 0 0 AC_BK */
0x00, /* 0 0 1 AC_BE */
0x03, /* 0 1 1 AC_BE */
0x04, /* 1 0 0 AC_VI */
0x05, /* 1 0 1 AC_VI */
0x06, /* 1 1 0 AC_VO */
0x07 /* 1 1 1 AC_VO */
};
static u8 ac_to_tid[4][2] = { {1, 2}, {0, 3}, {4, 5}, {6, 7} };
/*
* This function debug prints the priority parameters for a WMM AC.
*/
static void
mwifiex_wmm_ac_debug_print(const struct ieee_types_wmm_ac_parameters *ac_param)
{
const char *ac_str[] = { "BK", "BE", "VI", "VO" };
pr_debug("info: WMM AC_%s: ACI=%d, ACM=%d, Aifsn=%d, "
"EcwMin=%d, EcwMax=%d, TxopLimit=%d\n",
ac_str[wmm_aci_to_qidx_map[(ac_param->aci_aifsn_bitmap
& MWIFIEX_ACI) >> 5]],
(ac_param->aci_aifsn_bitmap & MWIFIEX_ACI) >> 5,
(ac_param->aci_aifsn_bitmap & MWIFIEX_ACM) >> 4,
ac_param->aci_aifsn_bitmap & MWIFIEX_AIFSN,
ac_param->ecw_bitmap & MWIFIEX_ECW_MIN,
(ac_param->ecw_bitmap & MWIFIEX_ECW_MAX) >> 4,
le16_to_cpu(ac_param->tx_op_limit));
}
/*
* This function allocates a route address list.
*
* The function also initializes the list with the provided RA.
*/
static struct mwifiex_ra_list_tbl *
mwifiex_wmm_allocate_ralist_node(struct mwifiex_adapter *adapter, const u8 *ra)
{
struct mwifiex_ra_list_tbl *ra_list;
ra_list = kzalloc(sizeof(struct mwifiex_ra_list_tbl), GFP_ATOMIC);
if (!ra_list)
return NULL;
INIT_LIST_HEAD(&ra_list->list);
skb_queue_head_init(&ra_list->skb_head);
memcpy(ra_list->ra, ra, ETH_ALEN);
ra_list->total_pkt_count = 0;
mwifiex_dbg(adapter, INFO, "info: allocated ra_list %p\n", ra_list);
return ra_list;
}
/* This function returns random no between 16 and 32 to be used as threshold
* for no of packets after which BA setup is initiated.
*/
static u8 mwifiex_get_random_ba_threshold(void)
{
u64 ns;
/* setup ba_packet_threshold here random number between
* [BA_SETUP_PACKET_OFFSET,
* BA_SETUP_PACKET_OFFSET+BA_SETUP_MAX_PACKET_THRESHOLD-1]
*/
ns = ktime_get_ns();
ns += (ns >> 32) + (ns >> 16);
return ((u8)ns % BA_SETUP_MAX_PACKET_THRESHOLD) + BA_SETUP_PACKET_OFFSET;
}
/*
* This function allocates and adds a RA list for all TIDs
* with the given RA.
*/
void mwifiex_ralist_add(struct mwifiex_private *priv, const u8 *ra)
{
int i;
struct mwifiex_ra_list_tbl *ra_list;
struct mwifiex_adapter *adapter = priv->adapter;
struct mwifiex_sta_node *node;
for (i = 0; i < MAX_NUM_TID; ++i) {
ra_list = mwifiex_wmm_allocate_ralist_node(adapter, ra);
mwifiex_dbg(adapter, INFO,
"info: created ra_list %p\n", ra_list);
if (!ra_list)
break;
ra_list->is_11n_enabled = 0;
ra_list->tdls_link = false;
ra_list->ba_status = BA_SETUP_NONE;
ra_list->amsdu_in_ampdu = false;
if (!mwifiex_queuing_ra_based(priv)) {
if (mwifiex_is_tdls_link_setup
(mwifiex_get_tdls_link_status(priv, ra))) {
ra_list->tdls_link = true;
ra_list->is_11n_enabled =
mwifiex_tdls_peer_11n_enabled(priv, ra);
} else {
ra_list->is_11n_enabled = IS_11N_ENABLED(priv);
}
} else {
spin_lock_bh(&priv->sta_list_spinlock);
node = mwifiex_get_sta_entry(priv, ra);
if (node)
ra_list->tx_paused = node->tx_pause;
ra_list->is_11n_enabled =
mwifiex_is_sta_11n_enabled(priv, node);
if (ra_list->is_11n_enabled)
ra_list->max_amsdu = node->max_amsdu;
spin_unlock_bh(&priv->sta_list_spinlock);
}
mwifiex_dbg(adapter, DATA, "data: ralist %p: is_11n_enabled=%d\n",
ra_list, ra_list->is_11n_enabled);
if (ra_list->is_11n_enabled) {
ra_list->ba_pkt_count = 0;
ra_list->ba_packet_thr =
mwifiex_get_random_ba_threshold();
}
list_add_tail(&ra_list->list,
&priv->wmm.tid_tbl_ptr[i].ra_list);
}
}
/*
* This function sets the WMM queue priorities to their default values.
*/
static void mwifiex_wmm_default_queue_priorities(struct mwifiex_private *priv)
{
/* Default queue priorities: VO->VI->BE->BK */
priv->wmm.queue_priority[0] = WMM_AC_VO;
priv->wmm.queue_priority[1] = WMM_AC_VI;
priv->wmm.queue_priority[2] = WMM_AC_BE;
priv->wmm.queue_priority[3] = WMM_AC_BK;
}
/*
* This function map ACs to TIDs.
*/
static void
mwifiex_wmm_queue_priorities_tid(struct mwifiex_private *priv)
{
struct mwifiex_wmm_desc *wmm = &priv->wmm;
u8 *queue_priority = wmm->queue_priority;
int i;
for (i = 0; i < 4; ++i) {
tos_to_tid[7 - (i * 2)] = ac_to_tid[queue_priority[i]][1];
tos_to_tid[6 - (i * 2)] = ac_to_tid[queue_priority[i]][0];
}
for (i = 0; i < MAX_NUM_TID; ++i)
priv->tos_to_tid_inv[tos_to_tid[i]] = (u8)i;
atomic_set(&wmm->highest_queued_prio, HIGH_PRIO_TID);
}
/*
* This function initializes WMM priority queues.
*/
void
mwifiex_wmm_setup_queue_priorities(struct mwifiex_private *priv,
struct ieee_types_wmm_parameter *wmm_ie)
{
u16 cw_min, avg_back_off, tmp[4];
u32 i, j, num_ac;
u8 ac_idx;
if (!wmm_ie || !priv->wmm_enabled) {
/* WMM is not enabled, just set the defaults and return */
mwifiex_wmm_default_queue_priorities(priv);
return;
}
mwifiex_dbg(priv->adapter, INFO,
"info: WMM Parameter IE: version=%d,\t"
"qos_info Parameter Set Count=%d, Reserved=%#x\n",
wmm_ie->version, wmm_ie->qos_info_bitmap &
IEEE80211_WMM_IE_AP_QOSINFO_PARAM_SET_CNT_MASK,
wmm_ie->reserved);
for (num_ac = 0; num_ac < ARRAY_SIZE(wmm_ie->ac_params); num_ac++) {
u8 ecw = wmm_ie->ac_params[num_ac].ecw_bitmap;
u8 aci_aifsn = wmm_ie->ac_params[num_ac].aci_aifsn_bitmap;
cw_min = (1 << (ecw & MWIFIEX_ECW_MIN)) - 1;
avg_back_off = (cw_min >> 1) + (aci_aifsn & MWIFIEX_AIFSN);
ac_idx = wmm_aci_to_qidx_map[(aci_aifsn & MWIFIEX_ACI) >> 5];
priv->wmm.queue_priority[ac_idx] = ac_idx;
tmp[ac_idx] = avg_back_off;
mwifiex_dbg(priv->adapter, INFO,
"info: WMM: CWmax=%d CWmin=%d Avg Back-off=%d\n",
(1 << ((ecw & MWIFIEX_ECW_MAX) >> 4)) - 1,
cw_min, avg_back_off);
mwifiex_wmm_ac_debug_print(&wmm_ie->ac_params[num_ac]);
}
/* Bubble sort */
for (i = 0; i < num_ac; i++) {
for (j = 1; j < num_ac - i; j++) {
if (tmp[j - 1] > tmp[j]) {
swap(tmp[j - 1], tmp[j]);
swap(priv->wmm.queue_priority[j - 1],
priv->wmm.queue_priority[j]);
} else if (tmp[j - 1] == tmp[j]) {
if (priv->wmm.queue_priority[j - 1]
< priv->wmm.queue_priority[j])
swap(priv->wmm.queue_priority[j - 1],
priv->wmm.queue_priority[j]);
}
}
}
mwifiex_wmm_queue_priorities_tid(priv);
}
/*
* This function evaluates whether or not an AC is to be downgraded.
*
* In case the AC is not enabled, the highest AC is returned that is
* enabled and does not require admission control.
*/
static enum mwifiex_wmm_ac_e
mwifiex_wmm_eval_downgrade_ac(struct mwifiex_private *priv,
enum mwifiex_wmm_ac_e eval_ac)
{
int down_ac;
enum mwifiex_wmm_ac_e ret_ac;
struct mwifiex_wmm_ac_status *ac_status;
ac_status = &priv->wmm.ac_status[eval_ac];
if (!ac_status->disabled)
/* Okay to use this AC, its enabled */
return eval_ac;
/* Setup a default return value of the lowest priority */
ret_ac = WMM_AC_BK;
/*
* Find the highest AC that is enabled and does not require
* admission control. The spec disallows downgrading to an AC,
* which is enabled due to a completed admission control.
* Unadmitted traffic is not to be sent on an AC with admitted
* traffic.
*/
for (down_ac = WMM_AC_BK; down_ac < eval_ac; down_ac++) {
ac_status = &priv->wmm.ac_status[down_ac];
if (!ac_status->disabled && !ac_status->flow_required)
/* AC is enabled and does not require admission
control */
ret_ac = (enum mwifiex_wmm_ac_e) down_ac;
}
return ret_ac;
}
/*
* This function downgrades WMM priority queue.
*/
void
mwifiex_wmm_setup_ac_downgrade(struct mwifiex_private *priv)
{
int ac_val;
mwifiex_dbg(priv->adapter, INFO, "info: WMM: AC Priorities:\t"
"BK(0), BE(1), VI(2), VO(3)\n");
if (!priv->wmm_enabled) {
/* WMM is not enabled, default priorities */
for (ac_val = WMM_AC_BK; ac_val <= WMM_AC_VO; ac_val++)
priv->wmm.ac_down_graded_vals[ac_val] =
(enum mwifiex_wmm_ac_e) ac_val;
} else {
for (ac_val = WMM_AC_BK; ac_val <= WMM_AC_VO; ac_val++) {
priv->wmm.ac_down_graded_vals[ac_val]
= mwifiex_wmm_eval_downgrade_ac(priv,
(enum mwifiex_wmm_ac_e) ac_val);
mwifiex_dbg(priv->adapter, INFO,
"info: WMM: AC PRIO %d maps to %d\n",
ac_val,
priv->wmm.ac_down_graded_vals[ac_val]);
}
}
}
/*
* This function converts the IP TOS field to an WMM AC
* Queue assignment.
*/
static enum mwifiex_wmm_ac_e
mwifiex_wmm_convert_tos_to_ac(struct mwifiex_adapter *adapter, u32 tos)
{
/* Map of TOS UP values to WMM AC */
static const enum mwifiex_wmm_ac_e tos_to_ac[] = {
WMM_AC_BE,
WMM_AC_BK,
WMM_AC_BK,
WMM_AC_BE,
WMM_AC_VI,
WMM_AC_VI,
WMM_AC_VO,
WMM_AC_VO
};
if (tos >= ARRAY_SIZE(tos_to_ac))
return WMM_AC_BE;
return tos_to_ac[tos];
}
/*
* This function evaluates a given TID and downgrades it to a lower
* TID if the WMM Parameter IE received from the AP indicates that the
* AP is disabled (due to call admission control (ACM bit). Mapping
* of TID to AC is taken care of internally.
*/
u8 mwifiex_wmm_downgrade_tid(struct mwifiex_private *priv, u32 tid)
{
enum mwifiex_wmm_ac_e ac, ac_down;
u8 new_tid;
ac = mwifiex_wmm_convert_tos_to_ac(priv->adapter, tid);
ac_down = priv->wmm.ac_down_graded_vals[ac];
/* Send the index to tid array, picking from the array will be
* taken care by dequeuing function
*/
new_tid = ac_to_tid[ac_down][tid % 2];
return new_tid;
}
/*
* This function initializes the WMM state information and the
* WMM data path queues.
*/
void
mwifiex_wmm_init(struct mwifiex_adapter *adapter)
{
int i, j;
struct mwifiex_private *priv;
for (j = 0; j < adapter->priv_num; ++j) {
priv = adapter->priv[j];
if (!priv)
continue;
for (i = 0; i < MAX_NUM_TID; ++i) {
if (!disable_tx_amsdu &&
adapter->tx_buf_size > MWIFIEX_TX_DATA_BUF_SIZE_2K)
priv->aggr_prio_tbl[i].amsdu =
priv->tos_to_tid_inv[i];
else
priv->aggr_prio_tbl[i].amsdu =
BA_STREAM_NOT_ALLOWED;
priv->aggr_prio_tbl[i].ampdu_ap =
priv->tos_to_tid_inv[i];
priv->aggr_prio_tbl[i].ampdu_user =
priv->tos_to_tid_inv[i];
}
priv->aggr_prio_tbl[6].amsdu
= priv->aggr_prio_tbl[6].ampdu_ap
= priv->aggr_prio_tbl[6].ampdu_user
= BA_STREAM_NOT_ALLOWED;
priv->aggr_prio_tbl[7].amsdu = priv->aggr_prio_tbl[7].ampdu_ap
= priv->aggr_prio_tbl[7].ampdu_user
= BA_STREAM_NOT_ALLOWED;
mwifiex_set_ba_params(priv);
mwifiex_reset_11n_rx_seq_num(priv);
priv->wmm.drv_pkt_delay_max = MWIFIEX_WMM_DRV_DELAY_MAX;
atomic_set(&priv->wmm.tx_pkts_queued, 0);
atomic_set(&priv->wmm.highest_queued_prio, HIGH_PRIO_TID);
}
}
int mwifiex_bypass_txlist_empty(struct mwifiex_adapter *adapter)
{
struct mwifiex_private *priv;
int i;
for (i = 0; i < adapter->priv_num; i++) {
priv = adapter->priv[i];
if (!priv)
continue;
if (adapter->if_ops.is_port_ready &&
!adapter->if_ops.is_port_ready(priv))
continue;
if (!skb_queue_empty(&priv->bypass_txq))
return false;
}
return true;
}
/*
* This function checks if WMM Tx queue is empty.
*/
int
mwifiex_wmm_lists_empty(struct mwifiex_adapter *adapter)
{
int i;
struct mwifiex_private *priv;
for (i = 0; i < adapter->priv_num; ++i) {
priv = adapter->priv[i];
if (!priv)
continue;
if (!priv->port_open &&
(priv->bss_mode != NL80211_IFTYPE_ADHOC))
continue;
if (adapter->if_ops.is_port_ready &&
!adapter->if_ops.is_port_ready(priv))
continue;
if (atomic_read(&priv->wmm.tx_pkts_queued))
return false;
}
return true;
}
/*
* This function deletes all packets in an RA list node.
*
* The packet sent completion callback handler are called with
* status failure, after they are dequeued to ensure proper
* cleanup. The RA list node itself is freed at the end.
*/
static void
mwifiex_wmm_del_pkts_in_ralist_node(struct mwifiex_private *priv,
struct mwifiex_ra_list_tbl *ra_list)
{
struct mwifiex_adapter *adapter = priv->adapter;
struct sk_buff *skb, *tmp;
skb_queue_walk_safe(&ra_list->skb_head, skb, tmp) {
skb_unlink(skb, &ra_list->skb_head);
mwifiex_write_data_complete(adapter, skb, 0, -1);
}
}
/*
* This function deletes all packets in an RA list.
*
* Each nodes in the RA list are freed individually first, and then
* the RA list itself is freed.
*/
static void
mwifiex_wmm_del_pkts_in_ralist(struct mwifiex_private *priv,
struct list_head *ra_list_head)
{
struct mwifiex_ra_list_tbl *ra_list;
list_for_each_entry(ra_list, ra_list_head, list)
mwifiex_wmm_del_pkts_in_ralist_node(priv, ra_list);
}
/*
* This function deletes all packets in all RA lists.
*/
static void mwifiex_wmm_cleanup_queues(struct mwifiex_private *priv)
{
int i;
for (i = 0; i < MAX_NUM_TID; i++)
mwifiex_wmm_del_pkts_in_ralist(priv, &priv->wmm.tid_tbl_ptr[i].
ra_list);
atomic_set(&priv->wmm.tx_pkts_queued, 0);
atomic_set(&priv->wmm.highest_queued_prio, HIGH_PRIO_TID);
}
/*
* This function deletes all route addresses from all RA lists.
*/
static void mwifiex_wmm_delete_all_ralist(struct mwifiex_private *priv)
{
struct mwifiex_ra_list_tbl *ra_list, *tmp_node;
int i;
for (i = 0; i < MAX_NUM_TID; ++i) {
mwifiex_dbg(priv->adapter, INFO,
"info: ra_list: freeing buf for tid %d\n", i);
list_for_each_entry_safe(ra_list, tmp_node,
&priv->wmm.tid_tbl_ptr[i].ra_list,
list) {
list_del(&ra_list->list);
kfree(ra_list);
}
INIT_LIST_HEAD(&priv->wmm.tid_tbl_ptr[i].ra_list);
}
}
static int mwifiex_free_ack_frame(int id, void *p, void *data)
{
pr_warn("Have pending ack frames!\n");
kfree_skb(p);
return 0;
}
/*
* This function cleans up the Tx and Rx queues.
*
* Cleanup includes -
* - All packets in RA lists
* - All entries in Rx reorder table
* - All entries in Tx BA stream table
* - MPA buffer (if required)
* - All RA lists
*/
void
mwifiex_clean_txrx(struct mwifiex_private *priv)
{
struct sk_buff *skb, *tmp;
mwifiex_11n_cleanup_reorder_tbl(priv);
spin_lock_bh(&priv->wmm.ra_list_spinlock);
mwifiex_wmm_cleanup_queues(priv);
mwifiex_11n_delete_all_tx_ba_stream_tbl(priv);
if (priv->adapter->if_ops.cleanup_mpa_buf)
priv->adapter->if_ops.cleanup_mpa_buf(priv->adapter);
mwifiex_wmm_delete_all_ralist(priv);
memcpy(tos_to_tid, ac_to_tid, sizeof(tos_to_tid));
if (priv->adapter->if_ops.clean_pcie_ring &&
!test_bit(MWIFIEX_SURPRISE_REMOVED, &priv->adapter->work_flags))
priv->adapter->if_ops.clean_pcie_ring(priv->adapter);
spin_unlock_bh(&priv->wmm.ra_list_spinlock);
skb_queue_walk_safe(&priv->tdls_txq, skb, tmp) {
skb_unlink(skb, &priv->tdls_txq);
mwifiex_write_data_complete(priv->adapter, skb, 0, -1);
}
skb_queue_walk_safe(&priv->bypass_txq, skb, tmp) {
skb_unlink(skb, &priv->bypass_txq);
mwifiex_write_data_complete(priv->adapter, skb, 0, -1);
}
atomic_set(&priv->adapter->bypass_tx_pending, 0);
idr_for_each(&priv->ack_status_frames, mwifiex_free_ack_frame, NULL);
idr_destroy(&priv->ack_status_frames);
}
/*
* This function retrieves a particular RA list node, matching with the
* given TID and RA address.
*/
struct mwifiex_ra_list_tbl *
mwifiex_wmm_get_ralist_node(struct mwifiex_private *priv, u8 tid,
const u8 *ra_addr)
{
struct mwifiex_ra_list_tbl *ra_list;
list_for_each_entry(ra_list, &priv->wmm.tid_tbl_ptr[tid].ra_list,
list) {
if (!memcmp(ra_list->ra, ra_addr, ETH_ALEN))
return ra_list;
}
return NULL;
}
void mwifiex_update_ralist_tx_pause(struct mwifiex_private *priv, u8 *mac,
u8 tx_pause)
{
struct mwifiex_ra_list_tbl *ra_list;
u32 pkt_cnt = 0, tx_pkts_queued;
int i;
spin_lock_bh(&priv->wmm.ra_list_spinlock);
for (i = 0; i < MAX_NUM_TID; ++i) {
ra_list = mwifiex_wmm_get_ralist_node(priv, i, mac);
if (ra_list && ra_list->tx_paused != tx_pause) {
pkt_cnt += ra_list->total_pkt_count;
ra_list->tx_paused = tx_pause;
if (tx_pause)
priv->wmm.pkts_paused[i] +=
ra_list->total_pkt_count;
else
priv->wmm.pkts_paused[i] -=
ra_list->total_pkt_count;
}
}
if (pkt_cnt) {
tx_pkts_queued = atomic_read(&priv->wmm.tx_pkts_queued);
if (tx_pause)
tx_pkts_queued -= pkt_cnt;
else
tx_pkts_queued += pkt_cnt;
atomic_set(&priv->wmm.tx_pkts_queued, tx_pkts_queued);
atomic_set(&priv->wmm.highest_queued_prio, HIGH_PRIO_TID);
}
spin_unlock_bh(&priv->wmm.ra_list_spinlock);
}
/* This function updates non-tdls peer ralist tx_pause while
* tdls channel switching
*/
void mwifiex_update_ralist_tx_pause_in_tdls_cs(struct mwifiex_private *priv,
u8 *mac, u8 tx_pause)
{
struct mwifiex_ra_list_tbl *ra_list;
u32 pkt_cnt = 0, tx_pkts_queued;
int i;
spin_lock_bh(&priv->wmm.ra_list_spinlock);
for (i = 0; i < MAX_NUM_TID; ++i) {
list_for_each_entry(ra_list, &priv->wmm.tid_tbl_ptr[i].ra_list,
list) {
if (!memcmp(ra_list->ra, mac, ETH_ALEN))
continue;
if (ra_list->tx_paused != tx_pause) {
pkt_cnt += ra_list->total_pkt_count;
ra_list->tx_paused = tx_pause;
if (tx_pause)
priv->wmm.pkts_paused[i] +=
ra_list->total_pkt_count;
else
priv->wmm.pkts_paused[i] -=
ra_list->total_pkt_count;
}
}
}
if (pkt_cnt) {
tx_pkts_queued = atomic_read(&priv->wmm.tx_pkts_queued);
if (tx_pause)
tx_pkts_queued -= pkt_cnt;
else
tx_pkts_queued += pkt_cnt;
atomic_set(&priv->wmm.tx_pkts_queued, tx_pkts_queued);
atomic_set(&priv->wmm.highest_queued_prio, HIGH_PRIO_TID);
}
spin_unlock_bh(&priv->wmm.ra_list_spinlock);
}
/*
* This function retrieves an RA list node for a given TID and
* RA address pair.
*
* If no such node is found, a new node is added first and then
* retrieved.
*/
struct mwifiex_ra_list_tbl *
mwifiex_wmm_get_queue_raptr(struct mwifiex_private *priv, u8 tid,
const u8 *ra_addr)
{
struct mwifiex_ra_list_tbl *ra_list;
ra_list = mwifiex_wmm_get_ralist_node(priv, tid, ra_addr);
if (ra_list)
return ra_list;
mwifiex_ralist_add(priv, ra_addr);
return mwifiex_wmm_get_ralist_node(priv, tid, ra_addr);
}
/*
* This function deletes RA list nodes for given mac for all TIDs.
* Function also decrements TX pending count accordingly.
*/
void
mwifiex_wmm_del_peer_ra_list(struct mwifiex_private *priv, const u8 *ra_addr)
{
struct mwifiex_ra_list_tbl *ra_list;
int i;
spin_lock_bh(&priv->wmm.ra_list_spinlock);
for (i = 0; i < MAX_NUM_TID; ++i) {
ra_list = mwifiex_wmm_get_ralist_node(priv, i, ra_addr);
if (!ra_list)
continue;
mwifiex_wmm_del_pkts_in_ralist_node(priv, ra_list);
if (ra_list->tx_paused)
priv->wmm.pkts_paused[i] -= ra_list->total_pkt_count;
else
atomic_sub(ra_list->total_pkt_count,
&priv->wmm.tx_pkts_queued);
list_del(&ra_list->list);
kfree(ra_list);
}
spin_unlock_bh(&priv->wmm.ra_list_spinlock);
}
/*
* This function checks if a particular RA list node exists in a given TID
* table index.
*/
int
mwifiex_is_ralist_valid(struct mwifiex_private *priv,
struct mwifiex_ra_list_tbl *ra_list, int ptr_index)
{
struct mwifiex_ra_list_tbl *rlist;
list_for_each_entry(rlist, &priv->wmm.tid_tbl_ptr[ptr_index].ra_list,
list) {
if (rlist == ra_list)
return true;
}
return false;
}
/*
* This function adds a packet to bypass TX queue.
* This is special TX queue for packets which can be sent even when port_open
* is false.
*/
void
mwifiex_wmm_add_buf_bypass_txqueue(struct mwifiex_private *priv,
struct sk_buff *skb)
{
skb_queue_tail(&priv->bypass_txq, skb);
}
/*
* This function adds a packet to WMM queue.
*
* In disconnected state the packet is immediately dropped and the
* packet send completion callback is called with status failure.
*
* Otherwise, the correct RA list node is located and the packet
* is queued at the list tail.
*/
void
mwifiex_wmm_add_buf_txqueue(struct mwifiex_private *priv,
struct sk_buff *skb)
{
struct mwifiex_adapter *adapter = priv->adapter;
u32 tid;
struct mwifiex_ra_list_tbl *ra_list;
u8 ra[ETH_ALEN], tid_down;
struct list_head list_head;
int tdls_status = TDLS_NOT_SETUP;
struct ethhdr *eth_hdr = (struct ethhdr *)skb->data;
struct mwifiex_txinfo *tx_info = MWIFIEX_SKB_TXCB(skb);
memcpy(ra, eth_hdr->h_dest, ETH_ALEN);
if (GET_BSS_ROLE(priv) == MWIFIEX_BSS_ROLE_STA &&
ISSUPP_TDLS_ENABLED(adapter->fw_cap_info)) {
if (ntohs(eth_hdr->h_proto) == ETH_P_TDLS)
mwifiex_dbg(adapter, DATA,
"TDLS setup packet for %pM.\t"
"Don't block\n", ra);
else if (memcmp(priv->cfg_bssid, ra, ETH_ALEN))
tdls_status = mwifiex_get_tdls_link_status(priv, ra);
}
if (!priv->media_connected && !mwifiex_is_skb_mgmt_frame(skb)) {
mwifiex_dbg(adapter, DATA, "data: drop packet in disconnect\n");
mwifiex_write_data_complete(adapter, skb, 0, -1);
return;
}
tid = skb->priority;
spin_lock_bh(&priv->wmm.ra_list_spinlock);
tid_down = mwifiex_wmm_downgrade_tid(priv, tid);
/* In case of infra as we have already created the list during
association we just don't have to call get_queue_raptr, we will
have only 1 raptr for a tid in case of infra */
if (!mwifiex_queuing_ra_based(priv) &&
!mwifiex_is_skb_mgmt_frame(skb)) {
switch (tdls_status) {
case TDLS_SETUP_COMPLETE:
case TDLS_CHAN_SWITCHING:
case TDLS_IN_BASE_CHAN:
case TDLS_IN_OFF_CHAN:
ra_list = mwifiex_wmm_get_queue_raptr(priv, tid_down,
ra);
tx_info->flags |= MWIFIEX_BUF_FLAG_TDLS_PKT;
break;
case TDLS_SETUP_INPROGRESS:
skb_queue_tail(&priv->tdls_txq, skb);
spin_unlock_bh(&priv->wmm.ra_list_spinlock);
return;
default:
list_head = priv->wmm.tid_tbl_ptr[tid_down].ra_list;
ra_list = list_first_entry_or_null(&list_head,
struct mwifiex_ra_list_tbl, list);
break;
}
} else {
memcpy(ra, skb->data, ETH_ALEN);
if (ra[0] & 0x01 || mwifiex_is_skb_mgmt_frame(skb))
eth_broadcast_addr(ra);
ra_list = mwifiex_wmm_get_queue_raptr(priv, tid_down, ra);
}
if (!ra_list) {
spin_unlock_bh(&priv->wmm.ra_list_spinlock);
mwifiex_write_data_complete(adapter, skb, 0, -1);
return;
}
skb_queue_tail(&ra_list->skb_head, skb);
ra_list->ba_pkt_count++;
ra_list->total_pkt_count++;
if (atomic_read(&priv->wmm.highest_queued_prio) <
priv->tos_to_tid_inv[tid_down])
atomic_set(&priv->wmm.highest_queued_prio,
priv->tos_to_tid_inv[tid_down]);
if (ra_list->tx_paused)
priv->wmm.pkts_paused[tid_down]++;
else
atomic_inc(&priv->wmm.tx_pkts_queued);
spin_unlock_bh(&priv->wmm.ra_list_spinlock);
}
/*
* This function processes the get WMM status command response from firmware.
*
* The response may contain multiple TLVs -
* - AC Queue status TLVs
* - Current WMM Parameter IE TLV
* - Admission Control action frame TLVs
*
* This function parses the TLVs and then calls further specific functions
* to process any changes in the queue prioritize or state.
*/
int mwifiex_ret_wmm_get_status(struct mwifiex_private *priv,
const struct host_cmd_ds_command *resp)
{
u8 *curr = (u8 *) &resp->params.get_wmm_status;
uint16_t resp_len = le16_to_cpu(resp->size), tlv_len;
int mask = IEEE80211_WMM_IE_AP_QOSINFO_PARAM_SET_CNT_MASK;
bool valid = true;
struct mwifiex_ie_types_data *tlv_hdr;
struct mwifiex_ie_types_wmm_queue_status *tlv_wmm_qstatus;
struct ieee_types_wmm_parameter *wmm_param_ie = NULL;
struct mwifiex_wmm_ac_status *ac_status;
mwifiex_dbg(priv->adapter, INFO,
"info: WMM: WMM_GET_STATUS cmdresp received: %d\n",
resp_len);
while ((resp_len >= sizeof(tlv_hdr->header)) && valid) {
tlv_hdr = (struct mwifiex_ie_types_data *) curr;
tlv_len = le16_to_cpu(tlv_hdr->header.len);
if (resp_len < tlv_len + sizeof(tlv_hdr->header))
break;
switch (le16_to_cpu(tlv_hdr->header.type)) {
case TLV_TYPE_WMMQSTATUS:
tlv_wmm_qstatus =
(struct mwifiex_ie_types_wmm_queue_status *)
tlv_hdr;
mwifiex_dbg(priv->adapter, CMD,
"info: CMD_RESP: WMM_GET_STATUS:\t"
"QSTATUS TLV: %d, %d, %d\n",
tlv_wmm_qstatus->queue_index,
tlv_wmm_qstatus->flow_required,
tlv_wmm_qstatus->disabled);
ac_status = &priv->wmm.ac_status[tlv_wmm_qstatus->
queue_index];
ac_status->disabled = tlv_wmm_qstatus->disabled;
ac_status->flow_required =
tlv_wmm_qstatus->flow_required;
ac_status->flow_created = tlv_wmm_qstatus->flow_created;
break;
case WLAN_EID_VENDOR_SPECIFIC:
/*
* Point the regular IEEE IE 2 bytes into the Marvell IE
* and setup the IEEE IE type and length byte fields
*/
wmm_param_ie =
(struct ieee_types_wmm_parameter *) (curr +
2);
wmm_param_ie->vend_hdr.len = (u8) tlv_len;
wmm_param_ie->vend_hdr.element_id =
WLAN_EID_VENDOR_SPECIFIC;
mwifiex_dbg(priv->adapter, CMD,
"info: CMD_RESP: WMM_GET_STATUS:\t"
"WMM Parameter Set Count: %d\n",
wmm_param_ie->qos_info_bitmap & mask);
memcpy((u8 *) &priv->curr_bss_params.bss_descriptor.
wmm_ie, wmm_param_ie,
wmm_param_ie->vend_hdr.len + 2);
break;
default:
valid = false;
break;
}
curr += (tlv_len + sizeof(tlv_hdr->header));
resp_len -= (tlv_len + sizeof(tlv_hdr->header));
}
mwifiex_wmm_setup_queue_priorities(priv, wmm_param_ie);
mwifiex_wmm_setup_ac_downgrade(priv);
return 0;
}
/*
* Callback handler from the command module to allow insertion of a WMM TLV.
*
* If the BSS we are associating to supports WMM, this function adds the
* required WMM Information IE to the association request command buffer in
* the form of a Marvell extended IEEE IE.
*/
u32
mwifiex_wmm_process_association_req(struct mwifiex_private *priv,
u8 **assoc_buf,
struct ieee_types_wmm_parameter *wmm_ie,
struct ieee80211_ht_cap *ht_cap)
{
struct mwifiex_ie_types_wmm_param_set *wmm_tlv;
u32 ret_len = 0;
/* Null checks */
if (!assoc_buf)
return 0;
if (!(*assoc_buf))
return 0;
if (!wmm_ie)
return 0;
mwifiex_dbg(priv->adapter, INFO,
"info: WMM: process assoc req: bss->wmm_ie=%#x\n",
wmm_ie->vend_hdr.element_id);
if ((priv->wmm_required ||
(ht_cap && (priv->adapter->config_bands & BAND_GN ||
priv->adapter->config_bands & BAND_AN))) &&
wmm_ie->vend_hdr.element_id == WLAN_EID_VENDOR_SPECIFIC) {
wmm_tlv = (struct mwifiex_ie_types_wmm_param_set *) *assoc_buf;
wmm_tlv->header.type = cpu_to_le16((u16) wmm_info_ie[0]);
wmm_tlv->header.len = cpu_to_le16((u16) wmm_info_ie[1]);
memcpy(wmm_tlv->wmm_ie, &wmm_info_ie[2],
le16_to_cpu(wmm_tlv->header.len));
if (wmm_ie->qos_info_bitmap & IEEE80211_WMM_IE_AP_QOSINFO_UAPSD)
memcpy((u8 *) (wmm_tlv->wmm_ie
+ le16_to_cpu(wmm_tlv->header.len)
- sizeof(priv->wmm_qosinfo)),
&priv->wmm_qosinfo, sizeof(priv->wmm_qosinfo));
ret_len = sizeof(wmm_tlv->header)
+ le16_to_cpu(wmm_tlv->header.len);
*assoc_buf += ret_len;
}
return ret_len;
}
/*
* This function computes the time delay in the driver queues for a
* given packet.
*
* When the packet is received at the OS/Driver interface, the current
* time is set in the packet structure. The difference between the present
* time and that received time is computed in this function and limited
* based on pre-compiled limits in the driver.
*/
u8
mwifiex_wmm_compute_drv_pkt_delay(struct mwifiex_private *priv,
const struct sk_buff *skb)
{
u32 queue_delay = ktime_to_ms(net_timedelta(skb->tstamp));
u8 ret_val;
/*
* Queue delay is passed as a uint8 in units of 2ms (ms shifted
* by 1). Min value (other than 0) is therefore 2ms, max is 510ms.
*
* Pass max value if queue_delay is beyond the uint8 range
*/
ret_val = (u8) (min(queue_delay, priv->wmm.drv_pkt_delay_max) >> 1);
mwifiex_dbg(priv->adapter, DATA, "data: WMM: Pkt Delay: %d ms,\t"
"%d ms sent to FW\n", queue_delay, ret_val);
return ret_val;
}
/*
* This function retrieves the highest priority RA list table pointer.
*/
static struct mwifiex_ra_list_tbl *
mwifiex_wmm_get_highest_priolist_ptr(struct mwifiex_adapter *adapter,
struct mwifiex_private **priv, int *tid)
{
struct mwifiex_private *priv_tmp;
struct mwifiex_ra_list_tbl *ptr;
struct mwifiex_tid_tbl *tid_ptr;
atomic_t *hqp;
int i, j;
/* check the BSS with highest priority first */
for (j = adapter->priv_num - 1; j >= 0; --j) {
/* iterate over BSS with the equal priority */
list_for_each_entry(adapter->bss_prio_tbl[j].bss_prio_cur,
&adapter->bss_prio_tbl[j].bss_prio_head,
list) {
try_again:
priv_tmp = adapter->bss_prio_tbl[j].bss_prio_cur->priv;
if (((priv_tmp->bss_mode != NL80211_IFTYPE_ADHOC) &&
!priv_tmp->port_open) ||
(atomic_read(&priv_tmp->wmm.tx_pkts_queued) == 0))
continue;
if (adapter->if_ops.is_port_ready &&
!adapter->if_ops.is_port_ready(priv_tmp))
continue;
/* iterate over the WMM queues of the BSS */
hqp = &priv_tmp->wmm.highest_queued_prio;
for (i = atomic_read(hqp); i >= LOW_PRIO_TID; --i) {
spin_lock_bh(&priv_tmp->wmm.ra_list_spinlock);
tid_ptr = &(priv_tmp)->wmm.
tid_tbl_ptr[tos_to_tid[i]];
/* iterate over receiver addresses */
list_for_each_entry(ptr, &tid_ptr->ra_list,
list) {
if (!ptr->tx_paused &&
!skb_queue_empty(&ptr->skb_head))
/* holds both locks */
goto found;
}
spin_unlock_bh(&priv_tmp->wmm.ra_list_spinlock);
}
if (atomic_read(&priv_tmp->wmm.tx_pkts_queued) != 0) {
atomic_set(&priv_tmp->wmm.highest_queued_prio,
HIGH_PRIO_TID);
/* Iterate current private once more, since
* there still exist packets in data queue
*/
goto try_again;
} else
atomic_set(&priv_tmp->wmm.highest_queued_prio,
NO_PKT_PRIO_TID);
}
}
return NULL;
found:
/* holds ra_list_spinlock */
if (atomic_read(hqp) > i)
atomic_set(hqp, i);
spin_unlock_bh(&priv_tmp->wmm.ra_list_spinlock);
*priv = priv_tmp;
*tid = tos_to_tid[i];
return ptr;
}
/* This functions rotates ra and bss lists so packets are picked round robin.
*
* After a packet is successfully transmitted, rotate the ra list, so the ra
* next to the one transmitted, will come first in the list. This way we pick
* the ra' in a round robin fashion. Same applies to bss nodes of equal
* priority.
*
* Function also increments wmm.packets_out counter.
*/
void mwifiex_rotate_priolists(struct mwifiex_private *priv,
struct mwifiex_ra_list_tbl *ra,
int tid)
{
struct mwifiex_adapter *adapter = priv->adapter;
struct mwifiex_bss_prio_tbl *tbl = adapter->bss_prio_tbl;
struct mwifiex_tid_tbl *tid_ptr = &priv->wmm.tid_tbl_ptr[tid];
spin_lock_bh(&tbl[priv->bss_priority].bss_prio_lock);
/*
* dirty trick: we remove 'head' temporarily and reinsert it after
* curr bss node. imagine list to stay fixed while head is moved
*/
list_move(&tbl[priv->bss_priority].bss_prio_head,
&tbl[priv->bss_priority].bss_prio_cur->list);
spin_unlock_bh(&tbl[priv->bss_priority].bss_prio_lock);
spin_lock_bh(&priv->wmm.ra_list_spinlock);
if (mwifiex_is_ralist_valid(priv, ra, tid)) {
priv->wmm.packets_out[tid]++;
/* same as above */
list_move(&tid_ptr->ra_list, &ra->list);
}
spin_unlock_bh(&priv->wmm.ra_list_spinlock);
}
/*
* This function checks if 11n aggregation is possible.
*/
static int
mwifiex_is_11n_aggragation_possible(struct mwifiex_private *priv,
struct mwifiex_ra_list_tbl *ptr,
int max_buf_size)
{
int count = 0, total_size = 0;
struct sk_buff *skb, *tmp;
int max_amsdu_size;
if (priv->bss_role == MWIFIEX_BSS_ROLE_UAP && priv->ap_11n_enabled &&
ptr->is_11n_enabled)
max_amsdu_size = min_t(int, ptr->max_amsdu, max_buf_size);
else
max_amsdu_size = max_buf_size;
skb_queue_walk_safe(&ptr->skb_head, skb, tmp) {
total_size += skb->len;
if (total_size >= max_amsdu_size)
break;
if (++count >= MIN_NUM_AMSDU)
return true;
}
return false;
}
/*
* This function sends a single packet to firmware for transmission.
*/
static void
mwifiex_send_single_packet(struct mwifiex_private *priv,
struct mwifiex_ra_list_tbl *ptr, int ptr_index)
__releases(&priv->wmm.ra_list_spinlock)
{
struct sk_buff *skb, *skb_next;
struct mwifiex_tx_param tx_param;
struct mwifiex_adapter *adapter = priv->adapter;
struct mwifiex_txinfo *tx_info;
if (skb_queue_empty(&ptr->skb_head)) {
spin_unlock_bh(&priv->wmm.ra_list_spinlock);
mwifiex_dbg(adapter, DATA, "data: nothing to send\n");
return;
}
skb = skb_dequeue(&ptr->skb_head);
tx_info = MWIFIEX_SKB_TXCB(skb);
mwifiex_dbg(adapter, DATA,
"data: dequeuing the packet %p %p\n", ptr, skb);
ptr->total_pkt_count--;
if (!skb_queue_empty(&ptr->skb_head))
skb_next = skb_peek(&ptr->skb_head);
else
skb_next = NULL;
spin_unlock_bh(&priv->wmm.ra_list_spinlock);
tx_param.next_pkt_len = ((skb_next) ? skb_next->len +
sizeof(struct txpd) : 0);
if (mwifiex_process_tx(priv, skb, &tx_param) == -EBUSY) {
/* Queue the packet back at the head */
spin_lock_bh(&priv->wmm.ra_list_spinlock);
if (!mwifiex_is_ralist_valid(priv, ptr, ptr_index)) {
spin_unlock_bh(&priv->wmm.ra_list_spinlock);
mwifiex_write_data_complete(adapter, skb, 0, -1);
return;
}
skb_queue_tail(&ptr->skb_head, skb);
ptr->total_pkt_count++;
ptr->ba_pkt_count++;
tx_info->flags |= MWIFIEX_BUF_FLAG_REQUEUED_PKT;
spin_unlock_bh(&priv->wmm.ra_list_spinlock);
} else {
mwifiex_rotate_priolists(priv, ptr, ptr_index);
atomic_dec(&priv->wmm.tx_pkts_queued);
}
}
/*
* This function checks if the first packet in the given RA list
* is already processed or not.
*/
static int
mwifiex_is_ptr_processed(struct mwifiex_private *priv,
struct mwifiex_ra_list_tbl *ptr)
{
struct sk_buff *skb;
struct mwifiex_txinfo *tx_info;
if (skb_queue_empty(&ptr->skb_head))
return false;
skb = skb_peek(&ptr->skb_head);
tx_info = MWIFIEX_SKB_TXCB(skb);
if (tx_info->flags & MWIFIEX_BUF_FLAG_REQUEUED_PKT)
return true;
return false;
}
/*
* This function sends a single processed packet to firmware for
* transmission.
*/
static void
mwifiex_send_processed_packet(struct mwifiex_private *priv,
struct mwifiex_ra_list_tbl *ptr, int ptr_index)
__releases(&priv->wmm.ra_list_spinlock)
{
struct mwifiex_tx_param tx_param;
struct mwifiex_adapter *adapter = priv->adapter;
int ret = -1;
struct sk_buff *skb, *skb_next;
struct mwifiex_txinfo *tx_info;
if (skb_queue_empty(&ptr->skb_head)) {
spin_unlock_bh(&priv->wmm.ra_list_spinlock);
return;
}
skb = skb_dequeue(&ptr->skb_head);
if (adapter->data_sent || adapter->tx_lock_flag) {
ptr->total_pkt_count--;
spin_unlock_bh(&priv->wmm.ra_list_spinlock);
skb_queue_tail(&adapter->tx_data_q, skb);
atomic_dec(&priv->wmm.tx_pkts_queued);
atomic_inc(&adapter->tx_queued);
return;
}
if (!skb_queue_empty(&ptr->skb_head))
skb_next = skb_peek(&ptr->skb_head);
else
skb_next = NULL;
tx_info = MWIFIEX_SKB_TXCB(skb);
spin_unlock_bh(&priv->wmm.ra_list_spinlock);
tx_param.next_pkt_len =
((skb_next) ? skb_next->len +
sizeof(struct txpd) : 0);
if (adapter->iface_type == MWIFIEX_USB) {
ret = adapter->if_ops.host_to_card(adapter, priv->usb_port,
skb, &tx_param);
} else {
ret = adapter->if_ops.host_to_card(adapter, MWIFIEX_TYPE_DATA,
skb, &tx_param);
}
switch (ret) {
case -EBUSY:
mwifiex_dbg(adapter, ERROR, "data: -EBUSY is returned\n");
spin_lock_bh(&priv->wmm.ra_list_spinlock);
if (!mwifiex_is_ralist_valid(priv, ptr, ptr_index)) {
spin_unlock_bh(&priv->wmm.ra_list_spinlock);
mwifiex_write_data_complete(adapter, skb, 0, -1);
return;
}
skb_queue_tail(&ptr->skb_head, skb);
tx_info->flags |= MWIFIEX_BUF_FLAG_REQUEUED_PKT;
spin_unlock_bh(&priv->wmm.ra_list_spinlock);
break;
case -1:
mwifiex_dbg(adapter, ERROR, "host_to_card failed: %#x\n", ret);
adapter->dbg.num_tx_host_to_card_failure++;
mwifiex_write_data_complete(adapter, skb, 0, ret);
break;
case -EINPROGRESS:
break;
case 0:
mwifiex_write_data_complete(adapter, skb, 0, ret);
default:
break;
}
if (ret != -EBUSY) {
mwifiex_rotate_priolists(priv, ptr, ptr_index);
atomic_dec(&priv->wmm.tx_pkts_queued);
spin_lock_bh(&priv->wmm.ra_list_spinlock);
ptr->total_pkt_count--;
spin_unlock_bh(&priv->wmm.ra_list_spinlock);
}
}
/*
* This function dequeues a packet from the highest priority list
* and transmits it.
*/
static int
mwifiex_dequeue_tx_packet(struct mwifiex_adapter *adapter)
{
struct mwifiex_ra_list_tbl *ptr;
struct mwifiex_private *priv = NULL;
int ptr_index = 0;
u8 ra[ETH_ALEN];
int tid_del = 0, tid = 0;
ptr = mwifiex_wmm_get_highest_priolist_ptr(adapter, &priv, &ptr_index);
if (!ptr)
return -1;
tid = mwifiex_get_tid(ptr);
mwifiex_dbg(adapter, DATA, "data: tid=%d\n", tid);
spin_lock_bh(&priv->wmm.ra_list_spinlock);
if (!mwifiex_is_ralist_valid(priv, ptr, ptr_index)) {
spin_unlock_bh(&priv->wmm.ra_list_spinlock);
return -1;
}
if (mwifiex_is_ptr_processed(priv, ptr)) {
mwifiex_send_processed_packet(priv, ptr, ptr_index);
/* ra_list_spinlock has been freed in
mwifiex_send_processed_packet() */
return 0;
}
if (!ptr->is_11n_enabled ||
ptr->ba_status ||
priv->wps.session_enable) {
if (ptr->is_11n_enabled &&
ptr->ba_status &&
ptr->amsdu_in_ampdu &&
mwifiex_is_amsdu_allowed(priv, tid) &&
mwifiex_is_11n_aggragation_possible(priv, ptr,
adapter->tx_buf_size))
mwifiex_11n_aggregate_pkt(priv, ptr, ptr_index);
/* ra_list_spinlock has been freed in
* mwifiex_11n_aggregate_pkt()
*/
else
mwifiex_send_single_packet(priv, ptr, ptr_index);
/* ra_list_spinlock has been freed in
* mwifiex_send_single_packet()
*/
} else {
if (mwifiex_is_ampdu_allowed(priv, ptr, tid) &&
ptr->ba_pkt_count > ptr->ba_packet_thr) {
if (mwifiex_space_avail_for_new_ba_stream(adapter)) {
mwifiex_create_ba_tbl(priv, ptr->ra, tid,
BA_SETUP_INPROGRESS);
mwifiex_send_addba(priv, tid, ptr->ra);
} else if (mwifiex_find_stream_to_delete
(priv, tid, &tid_del, ra)) {
mwifiex_create_ba_tbl(priv, ptr->ra, tid,
BA_SETUP_INPROGRESS);
mwifiex_send_delba(priv, tid_del, ra, 1);
}
}
if (mwifiex_is_amsdu_allowed(priv, tid) &&
mwifiex_is_11n_aggragation_possible(priv, ptr,
adapter->tx_buf_size))
mwifiex_11n_aggregate_pkt(priv, ptr, ptr_index);
/* ra_list_spinlock has been freed in
mwifiex_11n_aggregate_pkt() */
else
mwifiex_send_single_packet(priv, ptr, ptr_index);
/* ra_list_spinlock has been freed in
mwifiex_send_single_packet() */
}
return 0;
}
void mwifiex_process_bypass_tx(struct mwifiex_adapter *adapter)
{
struct mwifiex_tx_param tx_param;
struct sk_buff *skb;
struct mwifiex_txinfo *tx_info;
struct mwifiex_private *priv;
int i;
if (adapter->data_sent || adapter->tx_lock_flag)
return;
for (i = 0; i < adapter->priv_num; ++i) {
priv = adapter->priv[i];
if (!priv)
continue;
if (adapter->if_ops.is_port_ready &&
!adapter->if_ops.is_port_ready(priv))
continue;
if (skb_queue_empty(&priv->bypass_txq))
continue;
skb = skb_dequeue(&priv->bypass_txq);
tx_info = MWIFIEX_SKB_TXCB(skb);
/* no aggregation for bypass packets */
tx_param.next_pkt_len = 0;
if (mwifiex_process_tx(priv, skb, &tx_param) == -EBUSY) {
skb_queue_head(&priv->bypass_txq, skb);
tx_info->flags |= MWIFIEX_BUF_FLAG_REQUEUED_PKT;
} else {
atomic_dec(&adapter->bypass_tx_pending);
}
}
}
/*
* This function transmits the highest priority packet awaiting in the
* WMM Queues.
*/
void
mwifiex_wmm_process_tx(struct mwifiex_adapter *adapter)
{
do {
if (mwifiex_dequeue_tx_packet(adapter))
break;
if (adapter->iface_type != MWIFIEX_SDIO) {
if (adapter->data_sent ||
adapter->tx_lock_flag)
break;
} else {
if (atomic_read(&adapter->tx_queued) >=
MWIFIEX_MAX_PKTS_TXQ)
break;
}
} while (!mwifiex_wmm_lists_empty(adapter));
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_4005_0 |
crossvul-cpp_data_good_5478_1 | /* $Id$ */
/*
* Copyright (c) 1996-1997 Sam Leffler
* Copyright (c) 1996 Pixar
*
* 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
* Pixar, 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 Pixar, 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 PIXAR, 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 "tiffiop.h"
#ifdef PIXARLOG_SUPPORT
/*
* TIFF Library.
* PixarLog Compression Support
*
* Contributed by Dan McCoy.
*
* PixarLog film support uses the TIFF library to store companded
* 11 bit values into a tiff file, which are compressed using the
* zip compressor.
*
* The codec can take as input and produce as output 32-bit IEEE float values
* as well as 16-bit or 8-bit unsigned integer values.
*
* On writing any of the above are converted into the internal
* 11-bit log format. In the case of 8 and 16 bit values, the
* input is assumed to be unsigned linear color values that represent
* the range 0-1. In the case of IEEE values, the 0-1 range is assumed to
* be the normal linear color range, in addition over 1 values are
* accepted up to a value of about 25.0 to encode "hot" highlights and such.
* The encoding is lossless for 8-bit values, slightly lossy for the
* other bit depths. The actual color precision should be better
* than the human eye can perceive with extra room to allow for
* error introduced by further image computation. As with any quantized
* color format, it is possible to perform image calculations which
* expose the quantization error. This format should certainly be less
* susceptible to such errors than standard 8-bit encodings, but more
* susceptible than straight 16-bit or 32-bit encodings.
*
* On reading the internal format is converted to the desired output format.
* The program can request which format it desires by setting the internal
* pseudo tag TIFFTAG_PIXARLOGDATAFMT to one of these possible values:
* PIXARLOGDATAFMT_FLOAT = provide IEEE float values.
* PIXARLOGDATAFMT_16BIT = provide unsigned 16-bit integer values
* PIXARLOGDATAFMT_8BIT = provide unsigned 8-bit integer values
*
* alternately PIXARLOGDATAFMT_8BITABGR provides unsigned 8-bit integer
* values with the difference that if there are exactly three or four channels
* (rgb or rgba) it swaps the channel order (bgr or abgr).
*
* PIXARLOGDATAFMT_11BITLOG provides the internal encoding directly
* packed in 16-bit values. However no tools are supplied for interpreting
* these values.
*
* "hot" (over 1.0) areas written in floating point get clamped to
* 1.0 in the integer data types.
*
* When the file is closed after writing, the bit depth and sample format
* are set always to appear as if 8-bit data has been written into it.
* That way a naive program unaware of the particulars of the encoding
* gets the format it is most likely able to handle.
*
* The codec does it's own horizontal differencing step on the coded
* values so the libraries predictor stuff should be turned off.
* The codec also handle byte swapping the encoded values as necessary
* since the library does not have the information necessary
* to know the bit depth of the raw unencoded buffer.
*
* NOTE: This decoder does not appear to update tif_rawcp, and tif_rawcc.
* This can cause problems with the implementation of CHUNKY_STRIP_READ_SUPPORT
* as noted in http://trac.osgeo.org/gdal/ticket/3894. FrankW - Jan'11
*/
#include "tif_predict.h"
#include "zlib.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* Tables for converting to/from 11 bit coded values */
#define TSIZE 2048 /* decode table size (11-bit tokens) */
#define TSIZEP1 2049 /* Plus one for slop */
#define ONE 1250 /* token value of 1.0 exactly */
#define RATIO 1.004 /* nominal ratio for log part */
#define CODE_MASK 0x7ff /* 11 bits. */
static float Fltsize;
static float LogK1, LogK2;
#define REPEAT(n, op) { int i; i=n; do { i--; op; } while (i>0); }
static void
horizontalAccumulateF(uint16 *wp, int n, int stride, float *op,
float *ToLinearF)
{
register unsigned int cr, cg, cb, ca, mask;
register float t0, t1, t2, t3;
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
t0 = ToLinearF[cr = (wp[0] & mask)];
t1 = ToLinearF[cg = (wp[1] & mask)];
t2 = ToLinearF[cb = (wp[2] & mask)];
op[0] = t0;
op[1] = t1;
op[2] = t2;
n -= 3;
while (n > 0) {
wp += 3;
op += 3;
n -= 3;
t0 = ToLinearF[(cr += wp[0]) & mask];
t1 = ToLinearF[(cg += wp[1]) & mask];
t2 = ToLinearF[(cb += wp[2]) & mask];
op[0] = t0;
op[1] = t1;
op[2] = t2;
}
} else if (stride == 4) {
t0 = ToLinearF[cr = (wp[0] & mask)];
t1 = ToLinearF[cg = (wp[1] & mask)];
t2 = ToLinearF[cb = (wp[2] & mask)];
t3 = ToLinearF[ca = (wp[3] & mask)];
op[0] = t0;
op[1] = t1;
op[2] = t2;
op[3] = t3;
n -= 4;
while (n > 0) {
wp += 4;
op += 4;
n -= 4;
t0 = ToLinearF[(cr += wp[0]) & mask];
t1 = ToLinearF[(cg += wp[1]) & mask];
t2 = ToLinearF[(cb += wp[2]) & mask];
t3 = ToLinearF[(ca += wp[3]) & mask];
op[0] = t0;
op[1] = t1;
op[2] = t2;
op[3] = t3;
}
} else {
REPEAT(stride, *op = ToLinearF[*wp&mask]; wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; *op = ToLinearF[*wp&mask]; wp++; op++)
n -= stride;
}
}
}
}
static void
horizontalAccumulate12(uint16 *wp, int n, int stride, int16 *op,
float *ToLinearF)
{
register unsigned int cr, cg, cb, ca, mask;
register float t0, t1, t2, t3;
#define SCALE12 2048.0F
#define CLAMP12(t) (((t) < 3071) ? (uint16) (t) : 3071)
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
t0 = ToLinearF[cr = (wp[0] & mask)] * SCALE12;
t1 = ToLinearF[cg = (wp[1] & mask)] * SCALE12;
t2 = ToLinearF[cb = (wp[2] & mask)] * SCALE12;
op[0] = CLAMP12(t0);
op[1] = CLAMP12(t1);
op[2] = CLAMP12(t2);
n -= 3;
while (n > 0) {
wp += 3;
op += 3;
n -= 3;
t0 = ToLinearF[(cr += wp[0]) & mask] * SCALE12;
t1 = ToLinearF[(cg += wp[1]) & mask] * SCALE12;
t2 = ToLinearF[(cb += wp[2]) & mask] * SCALE12;
op[0] = CLAMP12(t0);
op[1] = CLAMP12(t1);
op[2] = CLAMP12(t2);
}
} else if (stride == 4) {
t0 = ToLinearF[cr = (wp[0] & mask)] * SCALE12;
t1 = ToLinearF[cg = (wp[1] & mask)] * SCALE12;
t2 = ToLinearF[cb = (wp[2] & mask)] * SCALE12;
t3 = ToLinearF[ca = (wp[3] & mask)] * SCALE12;
op[0] = CLAMP12(t0);
op[1] = CLAMP12(t1);
op[2] = CLAMP12(t2);
op[3] = CLAMP12(t3);
n -= 4;
while (n > 0) {
wp += 4;
op += 4;
n -= 4;
t0 = ToLinearF[(cr += wp[0]) & mask] * SCALE12;
t1 = ToLinearF[(cg += wp[1]) & mask] * SCALE12;
t2 = ToLinearF[(cb += wp[2]) & mask] * SCALE12;
t3 = ToLinearF[(ca += wp[3]) & mask] * SCALE12;
op[0] = CLAMP12(t0);
op[1] = CLAMP12(t1);
op[2] = CLAMP12(t2);
op[3] = CLAMP12(t3);
}
} else {
REPEAT(stride, t0 = ToLinearF[*wp&mask] * SCALE12;
*op = CLAMP12(t0); wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; t0 = ToLinearF[wp[stride]&mask]*SCALE12;
*op = CLAMP12(t0); wp++; op++)
n -= stride;
}
}
}
}
static void
horizontalAccumulate16(uint16 *wp, int n, int stride, uint16 *op,
uint16 *ToLinear16)
{
register unsigned int cr, cg, cb, ca, mask;
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
op[0] = ToLinear16[cr = (wp[0] & mask)];
op[1] = ToLinear16[cg = (wp[1] & mask)];
op[2] = ToLinear16[cb = (wp[2] & mask)];
n -= 3;
while (n > 0) {
wp += 3;
op += 3;
n -= 3;
op[0] = ToLinear16[(cr += wp[0]) & mask];
op[1] = ToLinear16[(cg += wp[1]) & mask];
op[2] = ToLinear16[(cb += wp[2]) & mask];
}
} else if (stride == 4) {
op[0] = ToLinear16[cr = (wp[0] & mask)];
op[1] = ToLinear16[cg = (wp[1] & mask)];
op[2] = ToLinear16[cb = (wp[2] & mask)];
op[3] = ToLinear16[ca = (wp[3] & mask)];
n -= 4;
while (n > 0) {
wp += 4;
op += 4;
n -= 4;
op[0] = ToLinear16[(cr += wp[0]) & mask];
op[1] = ToLinear16[(cg += wp[1]) & mask];
op[2] = ToLinear16[(cb += wp[2]) & mask];
op[3] = ToLinear16[(ca += wp[3]) & mask];
}
} else {
REPEAT(stride, *op = ToLinear16[*wp&mask]; wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; *op = ToLinear16[*wp&mask]; wp++; op++)
n -= stride;
}
}
}
}
/*
* Returns the log encoded 11-bit values with the horizontal
* differencing undone.
*/
static void
horizontalAccumulate11(uint16 *wp, int n, int stride, uint16 *op)
{
register unsigned int cr, cg, cb, ca, mask;
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
op[0] = wp[0]; op[1] = wp[1]; op[2] = wp[2];
cr = wp[0]; cg = wp[1]; cb = wp[2];
n -= 3;
while (n > 0) {
wp += 3;
op += 3;
n -= 3;
op[0] = (uint16)((cr += wp[0]) & mask);
op[1] = (uint16)((cg += wp[1]) & mask);
op[2] = (uint16)((cb += wp[2]) & mask);
}
} else if (stride == 4) {
op[0] = wp[0]; op[1] = wp[1];
op[2] = wp[2]; op[3] = wp[3];
cr = wp[0]; cg = wp[1]; cb = wp[2]; ca = wp[3];
n -= 4;
while (n > 0) {
wp += 4;
op += 4;
n -= 4;
op[0] = (uint16)((cr += wp[0]) & mask);
op[1] = (uint16)((cg += wp[1]) & mask);
op[2] = (uint16)((cb += wp[2]) & mask);
op[3] = (uint16)((ca += wp[3]) & mask);
}
} else {
REPEAT(stride, *op = *wp&mask; wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; *op = *wp&mask; wp++; op++)
n -= stride;
}
}
}
}
static void
horizontalAccumulate8(uint16 *wp, int n, int stride, unsigned char *op,
unsigned char *ToLinear8)
{
register unsigned int cr, cg, cb, ca, mask;
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
op[0] = ToLinear8[cr = (wp[0] & mask)];
op[1] = ToLinear8[cg = (wp[1] & mask)];
op[2] = ToLinear8[cb = (wp[2] & mask)];
n -= 3;
while (n > 0) {
n -= 3;
wp += 3;
op += 3;
op[0] = ToLinear8[(cr += wp[0]) & mask];
op[1] = ToLinear8[(cg += wp[1]) & mask];
op[2] = ToLinear8[(cb += wp[2]) & mask];
}
} else if (stride == 4) {
op[0] = ToLinear8[cr = (wp[0] & mask)];
op[1] = ToLinear8[cg = (wp[1] & mask)];
op[2] = ToLinear8[cb = (wp[2] & mask)];
op[3] = ToLinear8[ca = (wp[3] & mask)];
n -= 4;
while (n > 0) {
n -= 4;
wp += 4;
op += 4;
op[0] = ToLinear8[(cr += wp[0]) & mask];
op[1] = ToLinear8[(cg += wp[1]) & mask];
op[2] = ToLinear8[(cb += wp[2]) & mask];
op[3] = ToLinear8[(ca += wp[3]) & mask];
}
} else {
REPEAT(stride, *op = ToLinear8[*wp&mask]; wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; *op = ToLinear8[*wp&mask]; wp++; op++)
n -= stride;
}
}
}
}
static void
horizontalAccumulate8abgr(uint16 *wp, int n, int stride, unsigned char *op,
unsigned char *ToLinear8)
{
register unsigned int cr, cg, cb, ca, mask;
register unsigned char t0, t1, t2, t3;
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
op[0] = 0;
t1 = ToLinear8[cb = (wp[2] & mask)];
t2 = ToLinear8[cg = (wp[1] & mask)];
t3 = ToLinear8[cr = (wp[0] & mask)];
op[1] = t1;
op[2] = t2;
op[3] = t3;
n -= 3;
while (n > 0) {
n -= 3;
wp += 3;
op += 4;
op[0] = 0;
t1 = ToLinear8[(cb += wp[2]) & mask];
t2 = ToLinear8[(cg += wp[1]) & mask];
t3 = ToLinear8[(cr += wp[0]) & mask];
op[1] = t1;
op[2] = t2;
op[3] = t3;
}
} else if (stride == 4) {
t0 = ToLinear8[ca = (wp[3] & mask)];
t1 = ToLinear8[cb = (wp[2] & mask)];
t2 = ToLinear8[cg = (wp[1] & mask)];
t3 = ToLinear8[cr = (wp[0] & mask)];
op[0] = t0;
op[1] = t1;
op[2] = t2;
op[3] = t3;
n -= 4;
while (n > 0) {
n -= 4;
wp += 4;
op += 4;
t0 = ToLinear8[(ca += wp[3]) & mask];
t1 = ToLinear8[(cb += wp[2]) & mask];
t2 = ToLinear8[(cg += wp[1]) & mask];
t3 = ToLinear8[(cr += wp[0]) & mask];
op[0] = t0;
op[1] = t1;
op[2] = t2;
op[3] = t3;
}
} else {
REPEAT(stride, *op = ToLinear8[*wp&mask]; wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; *op = ToLinear8[*wp&mask]; wp++; op++)
n -= stride;
}
}
}
}
/*
* State block for each open TIFF
* file using PixarLog compression/decompression.
*/
typedef struct {
TIFFPredictorState predict;
z_stream stream;
tmsize_t tbuf_size; /* only set/used on reading for now */
uint16 *tbuf;
uint16 stride;
int state;
int user_datafmt;
int quality;
#define PLSTATE_INIT 1
TIFFVSetMethod vgetparent; /* super-class method */
TIFFVSetMethod vsetparent; /* super-class method */
float *ToLinearF;
uint16 *ToLinear16;
unsigned char *ToLinear8;
uint16 *FromLT2;
uint16 *From14; /* Really for 16-bit data, but we shift down 2 */
uint16 *From8;
} PixarLogState;
static int
PixarLogMakeTables(PixarLogState *sp)
{
/*
* We make several tables here to convert between various external
* representations (float, 16-bit, and 8-bit) and the internal
* 11-bit companded representation. The 11-bit representation has two
* distinct regions. A linear bottom end up through .018316 in steps
* of about .000073, and a region of constant ratio up to about 25.
* These floating point numbers are stored in the main table ToLinearF.
* All other tables are derived from this one. The tables (and the
* ratios) are continuous at the internal seam.
*/
int nlin, lt2size;
int i, j;
double b, c, linstep, v;
float *ToLinearF;
uint16 *ToLinear16;
unsigned char *ToLinear8;
uint16 *FromLT2;
uint16 *From14; /* Really for 16-bit data, but we shift down 2 */
uint16 *From8;
c = log(RATIO);
nlin = (int)(1./c); /* nlin must be an integer */
c = 1./nlin;
b = exp(-c*ONE); /* multiplicative scale factor [b*exp(c*ONE) = 1] */
linstep = b*c*exp(1.);
LogK1 = (float)(1./c); /* if (v >= 2) token = k1*log(v*k2) */
LogK2 = (float)(1./b);
lt2size = (int)(2./linstep) + 1;
FromLT2 = (uint16 *)_TIFFmalloc(lt2size*sizeof(uint16));
From14 = (uint16 *)_TIFFmalloc(16384*sizeof(uint16));
From8 = (uint16 *)_TIFFmalloc(256*sizeof(uint16));
ToLinearF = (float *)_TIFFmalloc(TSIZEP1 * sizeof(float));
ToLinear16 = (uint16 *)_TIFFmalloc(TSIZEP1 * sizeof(uint16));
ToLinear8 = (unsigned char *)_TIFFmalloc(TSIZEP1 * sizeof(unsigned char));
if (FromLT2 == NULL || From14 == NULL || From8 == NULL ||
ToLinearF == NULL || ToLinear16 == NULL || ToLinear8 == NULL) {
if (FromLT2) _TIFFfree(FromLT2);
if (From14) _TIFFfree(From14);
if (From8) _TIFFfree(From8);
if (ToLinearF) _TIFFfree(ToLinearF);
if (ToLinear16) _TIFFfree(ToLinear16);
if (ToLinear8) _TIFFfree(ToLinear8);
sp->FromLT2 = NULL;
sp->From14 = NULL;
sp->From8 = NULL;
sp->ToLinearF = NULL;
sp->ToLinear16 = NULL;
sp->ToLinear8 = NULL;
return 0;
}
j = 0;
for (i = 0; i < nlin; i++) {
v = i * linstep;
ToLinearF[j++] = (float)v;
}
for (i = nlin; i < TSIZE; i++)
ToLinearF[j++] = (float)(b*exp(c*i));
ToLinearF[2048] = ToLinearF[2047];
for (i = 0; i < TSIZEP1; i++) {
v = ToLinearF[i]*65535.0 + 0.5;
ToLinear16[i] = (v > 65535.0) ? 65535 : (uint16)v;
v = ToLinearF[i]*255.0 + 0.5;
ToLinear8[i] = (v > 255.0) ? 255 : (unsigned char)v;
}
j = 0;
for (i = 0; i < lt2size; i++) {
if ((i*linstep)*(i*linstep) > ToLinearF[j]*ToLinearF[j+1])
j++;
FromLT2[i] = (uint16)j;
}
/*
* Since we lose info anyway on 16-bit data, we set up a 14-bit
* table and shift 16-bit values down two bits on input.
* saves a little table space.
*/
j = 0;
for (i = 0; i < 16384; i++) {
while ((i/16383.)*(i/16383.) > ToLinearF[j]*ToLinearF[j+1])
j++;
From14[i] = (uint16)j;
}
j = 0;
for (i = 0; i < 256; i++) {
while ((i/255.)*(i/255.) > ToLinearF[j]*ToLinearF[j+1])
j++;
From8[i] = (uint16)j;
}
Fltsize = (float)(lt2size/2);
sp->ToLinearF = ToLinearF;
sp->ToLinear16 = ToLinear16;
sp->ToLinear8 = ToLinear8;
sp->FromLT2 = FromLT2;
sp->From14 = From14;
sp->From8 = From8;
return 1;
}
#define DecoderState(tif) ((PixarLogState*) (tif)->tif_data)
#define EncoderState(tif) ((PixarLogState*) (tif)->tif_data)
static int PixarLogEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s);
static int PixarLogDecode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s);
#define PIXARLOGDATAFMT_UNKNOWN -1
static int
PixarLogGuessDataFmt(TIFFDirectory *td)
{
int guess = PIXARLOGDATAFMT_UNKNOWN;
int format = td->td_sampleformat;
/* If the user didn't tell us his datafmt,
* take our best guess from the bitspersample.
*/
switch (td->td_bitspersample) {
case 32:
if (format == SAMPLEFORMAT_IEEEFP)
guess = PIXARLOGDATAFMT_FLOAT;
break;
case 16:
if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT)
guess = PIXARLOGDATAFMT_16BIT;
break;
case 12:
if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_INT)
guess = PIXARLOGDATAFMT_12BITPICIO;
break;
case 11:
if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT)
guess = PIXARLOGDATAFMT_11BITLOG;
break;
case 8:
if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT)
guess = PIXARLOGDATAFMT_8BIT;
break;
}
return guess;
}
static tmsize_t
multiply_ms(tmsize_t m1, tmsize_t m2)
{
tmsize_t bytes = m1 * m2;
if (m1 && bytes / m1 != m2)
bytes = 0;
return bytes;
}
static tmsize_t
add_ms(tmsize_t m1, tmsize_t m2)
{
tmsize_t bytes = m1 + m2;
/* if either input is zero, assume overflow already occurred */
if (m1 == 0 || m2 == 0)
bytes = 0;
else if (bytes <= m1 || bytes <= m2)
bytes = 0;
return bytes;
}
static int
PixarLogFixupTags(TIFF* tif)
{
(void) tif;
return (1);
}
static int
PixarLogSetupDecode(TIFF* tif)
{
static const char module[] = "PixarLogSetupDecode";
TIFFDirectory *td = &tif->tif_dir;
PixarLogState* sp = DecoderState(tif);
tmsize_t tbuf_size;
assert(sp != NULL);
/* Make sure no byte swapping happens on the data
* after decompression. */
tif->tif_postdecode = _TIFFNoPostDecode;
/* for some reason, we can't do this in TIFFInitPixarLog */
sp->stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ?
td->td_samplesperpixel : 1);
tbuf_size = multiply_ms(multiply_ms(multiply_ms(sp->stride, td->td_imagewidth),
td->td_rowsperstrip), sizeof(uint16));
/* add one more stride in case input ends mid-stride */
tbuf_size = add_ms(tbuf_size, sizeof(uint16) * sp->stride);
if (tbuf_size == 0)
return (0); /* TODO: this is an error return without error report through TIFFErrorExt */
sp->tbuf = (uint16 *) _TIFFmalloc(tbuf_size);
if (sp->tbuf == NULL)
return (0);
sp->tbuf_size = tbuf_size;
if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN)
sp->user_datafmt = PixarLogGuessDataFmt(td);
if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) {
TIFFErrorExt(tif->tif_clientdata, module,
"PixarLog compression can't handle bits depth/data format combination (depth: %d)",
td->td_bitspersample);
return (0);
}
if (inflateInit(&sp->stream) != Z_OK) {
TIFFErrorExt(tif->tif_clientdata, module, "%s", sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
} else {
sp->state |= PLSTATE_INIT;
return (1);
}
}
/*
* Setup state for decoding a strip.
*/
static int
PixarLogPreDecode(TIFF* tif, uint16 s)
{
static const char module[] = "PixarLogPreDecode";
PixarLogState* sp = DecoderState(tif);
(void) s;
assert(sp != NULL);
sp->stream.next_in = tif->tif_rawdata;
assert(sizeof(sp->stream.avail_in)==4); /* if this assert gets raised,
we need to simplify this code to reflect a ZLib that is likely updated
to deal with 8byte memory sizes, though this code will respond
appropriately even before we simplify it */
sp->stream.avail_in = (uInt) tif->tif_rawcc;
if ((tmsize_t)sp->stream.avail_in != tif->tif_rawcc)
{
TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size");
return (0);
}
return (inflateReset(&sp->stream) == Z_OK);
}
static int
PixarLogDecode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s)
{
static const char module[] = "PixarLogDecode";
TIFFDirectory *td = &tif->tif_dir;
PixarLogState* sp = DecoderState(tif);
tmsize_t i;
tmsize_t nsamples;
int llen;
uint16 *up;
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_FLOAT:
nsamples = occ / sizeof(float); /* XXX float == 32 bits */
break;
case PIXARLOGDATAFMT_16BIT:
case PIXARLOGDATAFMT_12BITPICIO:
case PIXARLOGDATAFMT_11BITLOG:
nsamples = occ / sizeof(uint16); /* XXX uint16 == 16 bits */
break;
case PIXARLOGDATAFMT_8BIT:
case PIXARLOGDATAFMT_8BITABGR:
nsamples = occ;
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"%d bit input not supported in PixarLog",
td->td_bitspersample);
return 0;
}
llen = sp->stride * td->td_imagewidth;
(void) s;
assert(sp != NULL);
sp->stream.next_out = (unsigned char *) sp->tbuf;
assert(sizeof(sp->stream.avail_out)==4); /* if this assert gets raised,
we need to simplify this code to reflect a ZLib that is likely updated
to deal with 8byte memory sizes, though this code will respond
appropriately even before we simplify it */
sp->stream.avail_out = (uInt) (nsamples * sizeof(uint16));
if (sp->stream.avail_out != nsamples * sizeof(uint16))
{
TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size");
return (0);
}
/* Check that we will not fill more than what was allocated */
if ((tmsize_t)sp->stream.avail_out > sp->tbuf_size)
{
TIFFErrorExt(tif->tif_clientdata, module, "sp->stream.avail_out > sp->tbuf_size");
return (0);
}
do {
int state = inflate(&sp->stream, Z_PARTIAL_FLUSH);
if (state == Z_STREAM_END) {
break; /* XXX */
}
if (state == Z_DATA_ERROR) {
TIFFErrorExt(tif->tif_clientdata, module,
"Decoding error at scanline %lu, %s",
(unsigned long) tif->tif_row, sp->stream.msg ? sp->stream.msg : "(null)");
if (inflateSync(&sp->stream) != Z_OK)
return (0);
continue;
}
if (state != Z_OK) {
TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s",
sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
}
} while (sp->stream.avail_out > 0);
/* hopefully, we got all the bytes we needed */
if (sp->stream.avail_out != 0) {
TIFFErrorExt(tif->tif_clientdata, module,
"Not enough data at scanline %lu (short " TIFF_UINT64_FORMAT " bytes)",
(unsigned long) tif->tif_row, (TIFF_UINT64_T) sp->stream.avail_out);
return (0);
}
up = sp->tbuf;
/* Swap bytes in the data if from a different endian machine. */
if (tif->tif_flags & TIFF_SWAB)
TIFFSwabArrayOfShort(up, nsamples);
/*
* if llen is not an exact multiple of nsamples, the decode operation
* may overflow the output buffer, so truncate it enough to prevent
* that but still salvage as much data as possible.
*/
if (nsamples % llen) {
TIFFWarningExt(tif->tif_clientdata, module,
"stride %lu is not a multiple of sample count, "
"%lu, data truncated.", (unsigned long) llen, (unsigned long) nsamples);
nsamples -= nsamples % llen;
}
for (i = 0; i < nsamples; i += llen, up += llen) {
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_FLOAT:
horizontalAccumulateF(up, llen, sp->stride,
(float *)op, sp->ToLinearF);
op += llen * sizeof(float);
break;
case PIXARLOGDATAFMT_16BIT:
horizontalAccumulate16(up, llen, sp->stride,
(uint16 *)op, sp->ToLinear16);
op += llen * sizeof(uint16);
break;
case PIXARLOGDATAFMT_12BITPICIO:
horizontalAccumulate12(up, llen, sp->stride,
(int16 *)op, sp->ToLinearF);
op += llen * sizeof(int16);
break;
case PIXARLOGDATAFMT_11BITLOG:
horizontalAccumulate11(up, llen, sp->stride,
(uint16 *)op);
op += llen * sizeof(uint16);
break;
case PIXARLOGDATAFMT_8BIT:
horizontalAccumulate8(up, llen, sp->stride,
(unsigned char *)op, sp->ToLinear8);
op += llen * sizeof(unsigned char);
break;
case PIXARLOGDATAFMT_8BITABGR:
horizontalAccumulate8abgr(up, llen, sp->stride,
(unsigned char *)op, sp->ToLinear8);
op += llen * sizeof(unsigned char);
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"Unsupported bits/sample: %d",
td->td_bitspersample);
return (0);
}
}
return (1);
}
static int
PixarLogSetupEncode(TIFF* tif)
{
static const char module[] = "PixarLogSetupEncode";
TIFFDirectory *td = &tif->tif_dir;
PixarLogState* sp = EncoderState(tif);
tmsize_t tbuf_size;
assert(sp != NULL);
/* for some reason, we can't do this in TIFFInitPixarLog */
sp->stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ?
td->td_samplesperpixel : 1);
tbuf_size = multiply_ms(multiply_ms(multiply_ms(sp->stride, td->td_imagewidth),
td->td_rowsperstrip), sizeof(uint16));
if (tbuf_size == 0)
return (0); /* TODO: this is an error return without error report through TIFFErrorExt */
sp->tbuf = (uint16 *) _TIFFmalloc(tbuf_size);
if (sp->tbuf == NULL)
return (0);
if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN)
sp->user_datafmt = PixarLogGuessDataFmt(td);
if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) {
TIFFErrorExt(tif->tif_clientdata, module, "PixarLog compression can't handle %d bit linear encodings", td->td_bitspersample);
return (0);
}
if (deflateInit(&sp->stream, sp->quality) != Z_OK) {
TIFFErrorExt(tif->tif_clientdata, module, "%s", sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
} else {
sp->state |= PLSTATE_INIT;
return (1);
}
}
/*
* Reset encoding state at the start of a strip.
*/
static int
PixarLogPreEncode(TIFF* tif, uint16 s)
{
static const char module[] = "PixarLogPreEncode";
PixarLogState *sp = EncoderState(tif);
(void) s;
assert(sp != NULL);
sp->stream.next_out = tif->tif_rawdata;
assert(sizeof(sp->stream.avail_out)==4); /* if this assert gets raised,
we need to simplify this code to reflect a ZLib that is likely updated
to deal with 8byte memory sizes, though this code will respond
appropriately even before we simplify it */
sp->stream.avail_out = (uInt)tif->tif_rawdatasize;
if ((tmsize_t)sp->stream.avail_out != tif->tif_rawdatasize)
{
TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size");
return (0);
}
return (deflateReset(&sp->stream) == Z_OK);
}
static void
horizontalDifferenceF(float *ip, int n, int stride, uint16 *wp, uint16 *FromLT2)
{
int32 r1, g1, b1, a1, r2, g2, b2, a2, mask;
float fltsize = Fltsize;
#define CLAMP(v) ( (v<(float)0.) ? 0 \
: (v<(float)2.) ? FromLT2[(int)(v*fltsize)] \
: (v>(float)24.2) ? 2047 \
: LogK1*log(v*LogK2) + 0.5 )
mask = CODE_MASK;
if (n >= stride) {
if (stride == 3) {
r2 = wp[0] = (uint16) CLAMP(ip[0]);
g2 = wp[1] = (uint16) CLAMP(ip[1]);
b2 = wp[2] = (uint16) CLAMP(ip[2]);
n -= 3;
while (n > 0) {
n -= 3;
wp += 3;
ip += 3;
r1 = (int32) CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = (int32) CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = (int32) CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
}
} else if (stride == 4) {
r2 = wp[0] = (uint16) CLAMP(ip[0]);
g2 = wp[1] = (uint16) CLAMP(ip[1]);
b2 = wp[2] = (uint16) CLAMP(ip[2]);
a2 = wp[3] = (uint16) CLAMP(ip[3]);
n -= 4;
while (n > 0) {
n -= 4;
wp += 4;
ip += 4;
r1 = (int32) CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = (int32) CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = (int32) CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
a1 = (int32) CLAMP(ip[3]); wp[3] = (uint16)((a1-a2) & mask); a2 = a1;
}
} else {
REPEAT(stride, wp[0] = (uint16) CLAMP(ip[0]); wp++; ip++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[0] = (uint16)(((int32)CLAMP(ip[0])-(int32)CLAMP(ip[-stride])) & mask);
wp++; ip++)
n -= stride;
}
}
}
}
static void
horizontalDifference16(unsigned short *ip, int n, int stride,
unsigned short *wp, uint16 *From14)
{
register int r1, g1, b1, a1, r2, g2, b2, a2, mask;
/* assumption is unsigned pixel values */
#undef CLAMP
#define CLAMP(v) From14[(v) >> 2]
mask = CODE_MASK;
if (n >= stride) {
if (stride == 3) {
r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);
b2 = wp[2] = CLAMP(ip[2]);
n -= 3;
while (n > 0) {
n -= 3;
wp += 3;
ip += 3;
r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
}
} else if (stride == 4) {
r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);
b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]);
n -= 4;
while (n > 0) {
n -= 4;
wp += 4;
ip += 4;
r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
a1 = CLAMP(ip[3]); wp[3] = (uint16)((a1-a2) & mask); a2 = a1;
}
} else {
REPEAT(stride, wp[0] = CLAMP(ip[0]); wp++; ip++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[0] = (uint16)((CLAMP(ip[0])-CLAMP(ip[-stride])) & mask);
wp++; ip++)
n -= stride;
}
}
}
}
static void
horizontalDifference8(unsigned char *ip, int n, int stride,
unsigned short *wp, uint16 *From8)
{
register int r1, g1, b1, a1, r2, g2, b2, a2, mask;
#undef CLAMP
#define CLAMP(v) (From8[(v)])
mask = CODE_MASK;
if (n >= stride) {
if (stride == 3) {
r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);
b2 = wp[2] = CLAMP(ip[2]);
n -= 3;
while (n > 0) {
n -= 3;
r1 = CLAMP(ip[3]); wp[3] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = CLAMP(ip[4]); wp[4] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = CLAMP(ip[5]); wp[5] = (uint16)((b1-b2) & mask); b2 = b1;
wp += 3;
ip += 3;
}
} else if (stride == 4) {
r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);
b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]);
n -= 4;
while (n > 0) {
n -= 4;
r1 = CLAMP(ip[4]); wp[4] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = CLAMP(ip[5]); wp[5] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = CLAMP(ip[6]); wp[6] = (uint16)((b1-b2) & mask); b2 = b1;
a1 = CLAMP(ip[7]); wp[7] = (uint16)((a1-a2) & mask); a2 = a1;
wp += 4;
ip += 4;
}
} else {
REPEAT(stride, wp[0] = CLAMP(ip[0]); wp++; ip++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[0] = (uint16)((CLAMP(ip[0])-CLAMP(ip[-stride])) & mask);
wp++; ip++)
n -= stride;
}
}
}
}
/*
* Encode a chunk of pixels.
*/
static int
PixarLogEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
{
static const char module[] = "PixarLogEncode";
TIFFDirectory *td = &tif->tif_dir;
PixarLogState *sp = EncoderState(tif);
tmsize_t i;
tmsize_t n;
int llen;
unsigned short * up;
(void) s;
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_FLOAT:
n = cc / sizeof(float); /* XXX float == 32 bits */
break;
case PIXARLOGDATAFMT_16BIT:
case PIXARLOGDATAFMT_12BITPICIO:
case PIXARLOGDATAFMT_11BITLOG:
n = cc / sizeof(uint16); /* XXX uint16 == 16 bits */
break;
case PIXARLOGDATAFMT_8BIT:
case PIXARLOGDATAFMT_8BITABGR:
n = cc;
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"%d bit input not supported in PixarLog",
td->td_bitspersample);
return 0;
}
llen = sp->stride * td->td_imagewidth;
/* Check against the number of elements (of size uint16) of sp->tbuf */
if( n > (tmsize_t)(td->td_rowsperstrip * llen) )
{
TIFFErrorExt(tif->tif_clientdata, module,
"Too many input bytes provided");
return 0;
}
for (i = 0, up = sp->tbuf; i < n; i += llen, up += llen) {
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_FLOAT:
horizontalDifferenceF((float *)bp, llen,
sp->stride, up, sp->FromLT2);
bp += llen * sizeof(float);
break;
case PIXARLOGDATAFMT_16BIT:
horizontalDifference16((uint16 *)bp, llen,
sp->stride, up, sp->From14);
bp += llen * sizeof(uint16);
break;
case PIXARLOGDATAFMT_8BIT:
horizontalDifference8((unsigned char *)bp, llen,
sp->stride, up, sp->From8);
bp += llen * sizeof(unsigned char);
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"%d bit input not supported in PixarLog",
td->td_bitspersample);
return 0;
}
}
sp->stream.next_in = (unsigned char *) sp->tbuf;
assert(sizeof(sp->stream.avail_in)==4); /* if this assert gets raised,
we need to simplify this code to reflect a ZLib that is likely updated
to deal with 8byte memory sizes, though this code will respond
appropriately even before we simplify it */
sp->stream.avail_in = (uInt) (n * sizeof(uint16));
if ((sp->stream.avail_in / sizeof(uint16)) != (uInt) n)
{
TIFFErrorExt(tif->tif_clientdata, module,
"ZLib cannot deal with buffers this size");
return (0);
}
do {
if (deflate(&sp->stream, Z_NO_FLUSH) != Z_OK) {
TIFFErrorExt(tif->tif_clientdata, module, "Encoder error: %s",
sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
}
if (sp->stream.avail_out == 0) {
tif->tif_rawcc = tif->tif_rawdatasize;
TIFFFlushData1(tif);
sp->stream.next_out = tif->tif_rawdata;
sp->stream.avail_out = (uInt) tif->tif_rawdatasize; /* this is a safe typecast, as check is made already in PixarLogPreEncode */
}
} while (sp->stream.avail_in > 0);
return (1);
}
/*
* Finish off an encoded strip by flushing the last
* string and tacking on an End Of Information code.
*/
static int
PixarLogPostEncode(TIFF* tif)
{
static const char module[] = "PixarLogPostEncode";
PixarLogState *sp = EncoderState(tif);
int state;
sp->stream.avail_in = 0;
do {
state = deflate(&sp->stream, Z_FINISH);
switch (state) {
case Z_STREAM_END:
case Z_OK:
if ((tmsize_t)sp->stream.avail_out != tif->tif_rawdatasize) {
tif->tif_rawcc =
tif->tif_rawdatasize - sp->stream.avail_out;
TIFFFlushData1(tif);
sp->stream.next_out = tif->tif_rawdata;
sp->stream.avail_out = (uInt) tif->tif_rawdatasize; /* this is a safe typecast, as check is made already in PixarLogPreEncode */
}
break;
default:
TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s",
sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
}
} while (state != Z_STREAM_END);
return (1);
}
static void
PixarLogClose(TIFF* tif)
{
TIFFDirectory *td = &tif->tif_dir;
/* In a really sneaky (and really incorrect, and untruthful, and
* troublesome, and error-prone) maneuver that completely goes against
* the spirit of TIFF, and breaks TIFF, on close, we covertly
* modify both bitspersample and sampleformat in the directory to
* indicate 8-bit linear. This way, the decode "just works" even for
* readers that don't know about PixarLog, or how to set
* the PIXARLOGDATFMT pseudo-tag.
*/
td->td_bitspersample = 8;
td->td_sampleformat = SAMPLEFORMAT_UINT;
}
static void
PixarLogCleanup(TIFF* tif)
{
PixarLogState* sp = (PixarLogState*) tif->tif_data;
assert(sp != 0);
(void)TIFFPredictorCleanup(tif);
tif->tif_tagmethods.vgetfield = sp->vgetparent;
tif->tif_tagmethods.vsetfield = sp->vsetparent;
if (sp->FromLT2) _TIFFfree(sp->FromLT2);
if (sp->From14) _TIFFfree(sp->From14);
if (sp->From8) _TIFFfree(sp->From8);
if (sp->ToLinearF) _TIFFfree(sp->ToLinearF);
if (sp->ToLinear16) _TIFFfree(sp->ToLinear16);
if (sp->ToLinear8) _TIFFfree(sp->ToLinear8);
if (sp->state&PLSTATE_INIT) {
if (tif->tif_mode == O_RDONLY)
inflateEnd(&sp->stream);
else
deflateEnd(&sp->stream);
}
if (sp->tbuf)
_TIFFfree(sp->tbuf);
_TIFFfree(sp);
tif->tif_data = NULL;
_TIFFSetDefaultCompressionState(tif);
}
static int
PixarLogVSetField(TIFF* tif, uint32 tag, va_list ap)
{
static const char module[] = "PixarLogVSetField";
PixarLogState *sp = (PixarLogState *)tif->tif_data;
int result;
switch (tag) {
case TIFFTAG_PIXARLOGQUALITY:
sp->quality = (int) va_arg(ap, int);
if (tif->tif_mode != O_RDONLY && (sp->state&PLSTATE_INIT)) {
if (deflateParams(&sp->stream,
sp->quality, Z_DEFAULT_STRATEGY) != Z_OK) {
TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s",
sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
}
}
return (1);
case TIFFTAG_PIXARLOGDATAFMT:
sp->user_datafmt = (int) va_arg(ap, int);
/* Tweak the TIFF header so that the rest of libtiff knows what
* size of data will be passed between app and library, and
* assume that the app knows what it is doing and is not
* confused by these header manipulations...
*/
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_8BIT:
case PIXARLOGDATAFMT_8BITABGR:
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 8);
TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
break;
case PIXARLOGDATAFMT_11BITLOG:
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16);
TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
break;
case PIXARLOGDATAFMT_12BITPICIO:
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16);
TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_INT);
break;
case PIXARLOGDATAFMT_16BIT:
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16);
TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
break;
case PIXARLOGDATAFMT_FLOAT:
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 32);
TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP);
break;
}
/*
* Must recalculate sizes should bits/sample change.
*/
tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tmsize_t)(-1);
tif->tif_scanlinesize = TIFFScanlineSize(tif);
result = 1; /* NB: pseudo tag */
break;
default:
result = (*sp->vsetparent)(tif, tag, ap);
}
return (result);
}
static int
PixarLogVGetField(TIFF* tif, uint32 tag, va_list ap)
{
PixarLogState *sp = (PixarLogState *)tif->tif_data;
switch (tag) {
case TIFFTAG_PIXARLOGQUALITY:
*va_arg(ap, int*) = sp->quality;
break;
case TIFFTAG_PIXARLOGDATAFMT:
*va_arg(ap, int*) = sp->user_datafmt;
break;
default:
return (*sp->vgetparent)(tif, tag, ap);
}
return (1);
}
static const TIFFField pixarlogFields[] = {
{TIFFTAG_PIXARLOGDATAFMT, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL},
{TIFFTAG_PIXARLOGQUALITY, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL}
};
int
TIFFInitPixarLog(TIFF* tif, int scheme)
{
static const char module[] = "TIFFInitPixarLog";
PixarLogState* sp;
assert(scheme == COMPRESSION_PIXARLOG);
/*
* Merge codec-specific tag information.
*/
if (!_TIFFMergeFields(tif, pixarlogFields,
TIFFArrayCount(pixarlogFields))) {
TIFFErrorExt(tif->tif_clientdata, module,
"Merging PixarLog codec-specific tags failed");
return 0;
}
/*
* Allocate state block so tag methods have storage to record values.
*/
tif->tif_data = (uint8*) _TIFFmalloc(sizeof (PixarLogState));
if (tif->tif_data == NULL)
goto bad;
sp = (PixarLogState*) tif->tif_data;
_TIFFmemset(sp, 0, sizeof (*sp));
sp->stream.data_type = Z_BINARY;
sp->user_datafmt = PIXARLOGDATAFMT_UNKNOWN;
/*
* Install codec methods.
*/
tif->tif_fixuptags = PixarLogFixupTags;
tif->tif_setupdecode = PixarLogSetupDecode;
tif->tif_predecode = PixarLogPreDecode;
tif->tif_decoderow = PixarLogDecode;
tif->tif_decodestrip = PixarLogDecode;
tif->tif_decodetile = PixarLogDecode;
tif->tif_setupencode = PixarLogSetupEncode;
tif->tif_preencode = PixarLogPreEncode;
tif->tif_postencode = PixarLogPostEncode;
tif->tif_encoderow = PixarLogEncode;
tif->tif_encodestrip = PixarLogEncode;
tif->tif_encodetile = PixarLogEncode;
tif->tif_close = PixarLogClose;
tif->tif_cleanup = PixarLogCleanup;
/* Override SetField so we can handle our private pseudo-tag */
sp->vgetparent = tif->tif_tagmethods.vgetfield;
tif->tif_tagmethods.vgetfield = PixarLogVGetField; /* hook for codec tags */
sp->vsetparent = tif->tif_tagmethods.vsetfield;
tif->tif_tagmethods.vsetfield = PixarLogVSetField; /* hook for codec tags */
/* Default values for codec-specific fields */
sp->quality = Z_DEFAULT_COMPRESSION; /* default comp. level */
sp->state = 0;
/* we don't wish to use the predictor,
* the default is none, which predictor value 1
*/
(void) TIFFPredictorInit(tif);
/*
* build the companding tables
*/
PixarLogMakeTables(sp);
return (1);
bad:
TIFFErrorExt(tif->tif_clientdata, module,
"No space for PixarLog state block");
return (0);
}
#endif /* PIXARLOG_SUPPORT */
/* 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-787/c/good_5478_1 |
crossvul-cpp_data_good_5272_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 maximum precision for all the bands of the tile
* @param p_max_res pointer that will hold the maximum number of resolutions for all the poc inside the tile.
* @param p_dx_min pointer that will hold the minimum dx of all the components of all the resolutions for the tile.
* @param p_dy_min pointer that will hold 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 maximum precision for all the bands of the tile
* @param p_max_res pointer that will hold the maximum number of resolutions for all the poc inside the tile.
* @param p_dx_min pointer that will hold the minimum dx of all the components of all the resolutions for the tile.
* @param p_dy_min pointer that will hold 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
*/
static 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
==========================================================
*/
static 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;
}
static 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;
}
static 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;
}
static 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;
}
static 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;
}
static 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;
}
}
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 )
{
/* 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;
/* non-corrected (in regard to image offset) tile offset */
OPJ_UINT32 l_tx0, l_ty0;
/* 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 */
l_tx0 = p_cp->tx0 + p * p_cp->tdx; /* can't be greater than p_image->x1 so won't overflow */
*p_tx0 = (OPJ_INT32)opj_uint_max(l_tx0, p_image->x0);
*p_tx1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_tx0, p_cp->tdx), p_image->x1);
l_ty0 = p_cp->ty0 + q * p_cp->tdy; /* can't be greater than p_image->y1 so won't overflow */
*p_ty0 = (OPJ_INT32)opj_uint_max(l_ty0, p_image->y0);
*p_ty1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_ty0, p_cp->tdy), 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;
for (resno = 0; resno < l_tccp->numresolutions; ++resno) {
OPJ_UINT32 l_dx, l_dy;
--l_level_no;
/* 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_tccp;
++l_img_comp;
}
}
static 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;
}
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)
{
/* 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;
}
}
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)
{
/* 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;
}
}
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)
{
/* 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;
}
}
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)
{
/* 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;
}
}
static 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 */
/* prevent an integer overflow issue */
l_current_pi->include = 00;
if (l_step_l <= (SIZE_MAX / (l_tcp->numlayers + 1U)))
{
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 = (OPJ_BYTE)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-787/c/good_5272_0 |
crossvul-cpp_data_bad_1005_2 | /******************************************************************************
* pdf.c
*
* pdfresurrect - PDF history extraction tool
*
* Copyright (C) 2008-2010, 2012-2013, 2017-19, Matt Davis (enferex).
*
* Special thanks to all of the contributors: See AUTHORS.
*
* Special thanks to 757labs (757 crew), they are a great group
* of people to hack on projects and brainstorm with.
*
* pdf.c is part of pdfresurrect.
* pdfresurrect 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 3 of the License, or
* (at your option) any later version.
*
* pdfresurrect 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 pdfresurrect. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "pdf.h"
#include "main.h"
/*
* Macros
*/
/* SAFE_F
*
* Safe file read: use for fgetc() calls, this is really ugly looking.
* _fp: FILE * handle
* _expr: The expression with fgetc() in it:
*
* example: If we get a character from the file and it is ascii character 'a'
* This assumes the coder wants to store the 'a' in variable ch
* Kinda pointless if you already know that you have 'a', but for
* illustrative purposes.
*
* if (SAFE_F(my_fp, ((c=fgetc(my_fp)) == 'a')))
* do_way_cool_stuff();
*/
#define SAFE_F(_fp, _expr) \
((!ferror(_fp) && !feof(_fp) && (_expr)))
/* SAFE_E
*
* Safe expression handling. This macro is a wrapper
* that compares the result of an expression (_expr) to the expected
* value (_cmp).
*
* _expr: Expression to test.
* _cmp: Expected value, error if this returns false.
* _msg: What to say when an error occurs.
*/
#define SAFE_E(_expr, _cmp, _msg) \
do { \
if ((_expr) != (_cmp)) { \
ERR(_msg); \
exit(EXIT_FAILURE); \
} \
} while (0)
/*
* Forwards
*/
static int is_valid_xref(FILE *fp, pdf_t *pdf, xref_t *xref);
static void load_xref_entries(FILE *fp, xref_t *xref);
static void load_xref_from_plaintext(FILE *fp, xref_t *xref);
static void load_xref_from_stream(FILE *fp, xref_t *xref);
static void get_xref_linear_skipped(FILE *fp, xref_t *xref);
static void resolve_linearized_pdf(pdf_t *pdf);
static pdf_creator_t *new_creator(int *n_elements);
static void load_creator(FILE *fp, pdf_t *pdf);
static void load_creator_from_buf(FILE *fp, xref_t *xref, const char *buf);
static void load_creator_from_xml(xref_t *xref, const char *buf);
static void load_creator_from_old_format(
FILE *fp,
xref_t *xref,
const char *buf);
static char *get_object_from_here(FILE *fp, size_t *size, int *is_stream);
static char *get_object(
FILE *fp,
int obj_id,
const xref_t *xref,
size_t *size,
int *is_stream);
static void add_kid(int id, xref_t *xref);
static void load_kids(FILE *fp, int pages_id, xref_t *xref);
static const char *get_type(FILE *fp, int obj_id, const xref_t *xref);
/* static int get_page(int obj_id, const xref_t *xref); */
static char *get_header(FILE *fp);
static char *decode_text_string(const char *str, size_t str_len);
static int get_next_eof(FILE *fp);
/*
* Defined
*/
pdf_t *pdf_new(const char *name)
{
const char *n;
pdf_t *pdf;
pdf = calloc(1, sizeof(pdf_t));
if (name)
{
/* Just get the file name (not path) */
if ((n = strrchr(name, '/')))
++n;
else
n = name;
pdf->name = malloc(strlen(n) + 1);
strcpy(pdf->name, n);
}
else /* !name */
{
pdf->name = malloc(strlen("Unknown") + 1);
strcpy(pdf->name, "Unknown");
}
return pdf;
}
void pdf_delete(pdf_t *pdf)
{
int i;
for (i=0; i<pdf->n_xrefs; i++)
{
free(pdf->xrefs[i].creator);
free(pdf->xrefs[i].entries);
free(pdf->xrefs[i].kids);
}
free(pdf->name);
free(pdf->xrefs);
free(pdf);
}
int pdf_is_pdf(FILE *fp)
{
int is_pdf;
char *header;
header = get_header(fp);
if (header && strstr(header, "%PDF-"))
is_pdf = 1;
else
is_pdf = 0;
free(header);
return is_pdf;
}
void pdf_get_version(FILE *fp, pdf_t *pdf)
{
char *header, *c;
header = get_header(fp);
/* Locate version string start and make sure we dont go past header */
if ((c = strstr(header, "%PDF-")) &&
(c + strlen("%PDF-M.m") + 2))
{
pdf->pdf_major_version = atoi(c + strlen("%PDF-"));
pdf->pdf_minor_version = atoi(c + strlen("%PDF-M."));
}
free(header);
}
int pdf_load_xrefs(FILE *fp, pdf_t *pdf)
{
int i, ver, is_linear;
long pos, pos_count;
char x, *c, buf[256];
c = NULL;
/* Count number of xrefs */
pdf->n_xrefs = 0;
fseek(fp, 0, SEEK_SET);
while (get_next_eof(fp) >= 0)
++pdf->n_xrefs;
if (!pdf->n_xrefs)
return 0;
/* Load in the start/end positions */
fseek(fp, 0, SEEK_SET);
pdf->xrefs = calloc(1, sizeof(xref_t) * pdf->n_xrefs);
ver = 1;
for (i=0; i<pdf->n_xrefs; i++)
{
/* Seek to %%EOF */
if ((pos = get_next_eof(fp)) < 0)
break;
/* Set and increment the version */
pdf->xrefs[i].version = ver++;
/* Rewind until we find end of "startxref" */
pos_count = 0;
while (SAFE_F(fp, ((x = fgetc(fp)) != 'f')))
fseek(fp, pos - (++pos_count), SEEK_SET);
/* Suck in end of "startxref" to start of %%EOF */
if (pos_count >= sizeof(buf)) {
ERR("Failed to locate the startxref token. "
"This might be a corrupt PDF.\n");
return -1;
}
memset(buf, 0, sizeof(buf));
SAFE_E(fread(buf, 1, pos_count, fp), pos_count,
"Failed to read startxref.\n");
c = buf;
while (*c == ' ' || *c == '\n' || *c == '\r')
++c;
/* xref start position */
pdf->xrefs[i].start = atol(c);
/* If xref is 0 handle linear xref table */
if (pdf->xrefs[i].start == 0)
get_xref_linear_skipped(fp, &pdf->xrefs[i]);
/* Non-linear, normal operation, so just find the end of the xref */
else
{
/* xref end position */
pos = ftell(fp);
fseek(fp, pdf->xrefs[i].start, SEEK_SET);
pdf->xrefs[i].end = get_next_eof(fp);
/* Look for next EOF and xref data */
fseek(fp, pos, SEEK_SET);
}
/* Check validity */
if (!is_valid_xref(fp, pdf, &pdf->xrefs[i]))
{
is_linear = pdf->xrefs[i].is_linear;
memset(&pdf->xrefs[i], 0, sizeof(xref_t));
pdf->xrefs[i].is_linear = is_linear;
rewind(fp);
get_next_eof(fp);
continue;
}
/* Load the entries from the xref */
load_xref_entries(fp, &pdf->xrefs[i]);
}
/* Now we have all xref tables, if this is linearized, we need
* to make adjustments so that things spit out properly
*/
if (pdf->xrefs[0].is_linear)
resolve_linearized_pdf(pdf);
/* Ok now we have all xref data. Go through those versions of the
* PDF and try to obtain creator information
*/
load_creator(fp, pdf);
return pdf->n_xrefs;
}
/* Load page information */
void pdf_load_pages_kids(FILE *fp, pdf_t *pdf)
{
int i, id, dummy;
char *buf, *c;
long start, sz;
start = ftell(fp);
/* Load all kids for all xref tables (versions) */
for (i=0; i<pdf->n_xrefs; i++)
{
if (pdf->xrefs[i].version && (pdf->xrefs[i].end != 0))
{
fseek(fp, pdf->xrefs[i].start, SEEK_SET);
while (SAFE_F(fp, (fgetc(fp) != 't')))
; /* Iterate to trailer */
/* Get root catalog */
sz = pdf->xrefs[i].end - ftell(fp);
buf = malloc(sz + 1);
SAFE_E(fread(buf, 1, sz, fp), sz, "Failed to load /Root.\n");
buf[sz] = '\0';
if (!(c = strstr(buf, "/Root")))
{
free(buf);
continue;
}
/* Jump to catalog (root) */
id = atoi(c + strlen("/Root") + 1);
free(buf);
buf = get_object(fp, id, &pdf->xrefs[i], NULL, &dummy);
if (!buf || !(c = strstr(buf, "/Pages")))
{
free(buf);
continue;
}
/* Start at the first Pages obj and get kids */
id = atoi(c + strlen("/Pages") + 1);
load_kids(fp, id, &pdf->xrefs[i]);
free(buf);
}
}
fseek(fp, start, SEEK_SET);
}
char pdf_get_object_status(
const pdf_t *pdf,
int xref_idx,
int entry_idx)
{
int i, curr_ver;
const xref_t *prev_xref;
const xref_entry_t *prev, *curr;
curr = &pdf->xrefs[xref_idx].entries[entry_idx];
curr_ver = pdf->xrefs[xref_idx].version;
if (curr_ver == 1)
return 'A';
/* Deleted (freed) */
if (curr->f_or_n == 'f')
return 'D';
/* Get previous version */
prev_xref = NULL;
for (i=xref_idx; i>-1; --i)
if (pdf->xrefs[i].version < curr_ver)
{
prev_xref = &pdf->xrefs[i];
break;
}
if (!prev_xref)
return '?';
/* Locate the object in the previous one that matches current one */
prev = NULL;
for (i=0; i<prev_xref->n_entries; ++i)
if (prev_xref->entries[i].obj_id == curr->obj_id)
{
prev = &prev_xref->entries[i];
break;
}
/* Added in place of a previously freed id */
if (!prev || ((prev->f_or_n == 'f') && (curr->f_or_n == 'n')))
return 'A';
/* Modified */
else if (prev->offset != curr->offset)
return 'M';
return '?';
}
void pdf_zero_object(
FILE *fp,
const pdf_t *pdf,
int xref_idx,
int entry_idx)
{
int i;
char *obj;
size_t obj_sz;
xref_entry_t *entry;
entry = &pdf->xrefs[xref_idx].entries[entry_idx];
fseek(fp, entry->offset, SEEK_SET);
/* Get object and size */
obj = get_object(fp, entry->obj_id, &pdf->xrefs[xref_idx], NULL, NULL);
i = obj_sz = 0;
while (strncmp((++i)+obj, "endobj", 6))
++obj_sz;
if (obj_sz)
obj_sz += strlen("endobj") + 1;
/* Zero object */
for (i=0; i<obj_sz; i++)
fputc('0', fp);
printf("Zeroed object %d\n", entry->obj_id);
free(obj);
}
/* Output information per version */
void pdf_summarize(
FILE *fp,
const pdf_t *pdf,
const char *name,
pdf_flag_t flags)
{
int i, j, page, n_versions, n_entries;
FILE *dst, *out;
char *dst_name, *c;
dst = NULL;
dst_name = NULL;
if (name)
{
dst_name = malloc(strlen(name) * 2 + 16);
sprintf(dst_name, "%s/%s", name, name);
if ((c = strrchr(dst_name, '.')) && (strncmp(c, ".pdf", 4) == 0))
*c = '\0';
strcat(dst_name, ".summary");
if (!(dst = fopen(dst_name, "w")))
{
ERR("Could not open file '%s' for writing\n", dst_name);
return;
}
}
/* Send output to file or stdout */
out = (dst) ? dst : stdout;
/* Count versions */
n_versions = pdf->n_xrefs;
if (n_versions && pdf->xrefs[0].is_linear)
--n_versions;
/* Ignore bad xref entry */
for (i=1; i<pdf->n_xrefs; ++i)
if (pdf->xrefs[i].end == 0)
--n_versions;
/* If we have no valid versions but linear, count that */
if (!pdf->n_xrefs || (!n_versions && pdf->xrefs[0].is_linear))
n_versions = 1;
/* Compare each object (if we dont have xref streams) */
n_entries = 0;
for (i=0; !(const int)pdf->has_xref_streams && i<pdf->n_xrefs; i++)
{
if (flags & PDF_FLAG_QUIET)
continue;
for (j=0; j<pdf->xrefs[i].n_entries; j++)
{
++n_entries;
fprintf(out,
"%s: --%c-- Version %d -- Object %d (%s)",
pdf->name,
pdf_get_object_status(pdf, i, j),
pdf->xrefs[i].version,
pdf->xrefs[i].entries[j].obj_id,
get_type(fp, pdf->xrefs[i].entries[j].obj_id,
&pdf->xrefs[i]));
/* TODO
page = get_page(pdf->xrefs[i].entries[j].obj_id, &pdf->xrefs[i]);
*/
if (0 /*page*/)
fprintf(out, " Page(%d)\n", page);
else
fprintf(out, "\n");
}
}
/* Trailing summary */
if (!(flags & PDF_FLAG_QUIET))
{
/* Let the user know that we cannot we print a per-object summary.
* If we have a 1.5 PDF using streams for xref, we have not objects
* to display, so let the user know whats up.
*/
if (pdf->has_xref_streams || !n_entries)
fprintf(out,
"%s: This PDF contains potential cross reference streams.\n"
"%s: An object summary is not available.\n",
pdf->name,
pdf->name);
fprintf(out,
"---------- %s ----------\n"
"Versions: %d\n",
pdf->name,
n_versions);
/* Count entries for summary */
if (!pdf->has_xref_streams)
for (i=0; i<pdf->n_xrefs; i++)
{
if (pdf->xrefs[i].is_linear)
continue;
n_entries = pdf->xrefs[i].n_entries;
/* If we are a linearized PDF, all versions are made from those
* objects too. So count em'
*/
if (pdf->xrefs[0].is_linear)
n_entries += pdf->xrefs[0].n_entries;
if (pdf->xrefs[i].version && n_entries)
fprintf(out,
"Version %d -- %d objects\n",
pdf->xrefs[i].version,
n_entries);
}
}
else /* Quiet output */
fprintf(out, "%s: %d\n", pdf->name, n_versions);
if (dst)
{
fclose(dst);
free(dst_name);
}
}
/* Returns '1' if we successfully display data (means its probably not xml) */
int pdf_display_creator(const pdf_t *pdf, int xref_idx)
{
int i;
if (!pdf->xrefs[xref_idx].creator)
return 0;
for (i=0; i<pdf->xrefs[xref_idx].n_creator_entries; ++i)
printf("%s: %s\n",
pdf->xrefs[xref_idx].creator[i].key,
pdf->xrefs[xref_idx].creator[i].value);
return (i > 0);
}
/* Checks if the xref is valid and sets 'is_stream' flag if the xref is a
* stream (PDF 1.5 or higher)
*/
static int is_valid_xref(FILE *fp, pdf_t *pdf, xref_t *xref)
{
int is_valid;
long start;
char *c, buf[16];
memset(buf, 0, sizeof(buf));
is_valid = 0;
start = ftell(fp);
fseek(fp, xref->start, SEEK_SET);
if (fgets(buf, 16, fp) == NULL) {
ERR("Failed to load xref string.");
exit(EXIT_FAILURE);
}
if (strncmp(buf, "xref", strlen("xref")) == 0)
is_valid = 1;
else
{
/* PDFv1.5+ allows for xref data to be stored in streams vs plaintext */
fseek(fp, xref->start, SEEK_SET);
c = get_object_from_here(fp, NULL, &xref->is_stream);
if (c && xref->is_stream)
{
free(c);
pdf->has_xref_streams = 1;
is_valid = 1;
}
}
fseek(fp, start, SEEK_SET);
return is_valid;
}
static void load_xref_entries(FILE *fp, xref_t *xref)
{
if (xref->is_stream)
load_xref_from_stream(fp, xref);
else
load_xref_from_plaintext(fp, xref);
}
static void load_xref_from_plaintext(FILE *fp, xref_t *xref)
{
int i, buf_idx, obj_id, added_entries;
char c, buf[32] = {0};
long start, pos;
start = ftell(fp);
/* Get number of entries */
pos = xref->end;
fseek(fp, pos, SEEK_SET);
while (ftell(fp) != 0)
if (SAFE_F(fp, (fgetc(fp) == '/' && fgetc(fp) == 'S')))
break;
else
SAFE_E(fseek(fp, --pos, SEEK_SET), 0, "Failed seek to xref /Size.\n");
SAFE_E(fread(buf, 1, 21, fp), 21, "Failed to load entry Size string.\n");
xref->n_entries = atoi(buf + strlen("ize "));
xref->entries = calloc(1, xref->n_entries * sizeof(struct _xref_entry));
/* Load entry data */
obj_id = 0;
fseek(fp, xref->start + strlen("xref"), SEEK_SET);
added_entries = 0;
for (i=0; i<xref->n_entries; i++)
{
/* Advance past newlines. */
c = fgetc(fp);
while (c == '\n' || c == '\r')
c = fgetc(fp);
/* Collect data up until the following newline. */
buf_idx = 0;
while (c != '\n' && c != '\r' && !feof(fp) &&
!ferror(fp) && buf_idx < sizeof(buf))
{
buf[buf_idx++] = c;
c = fgetc(fp);
}
if (buf_idx >= sizeof(buf))
{
ERR("Failed to locate newline character. "
"This might be a corrupt PDF.\n");
exit(EXIT_FAILURE);
}
buf[buf_idx] = '\0';
/* Went to far and hit start of trailer */
if (strchr(buf, 't'))
break;
/* Entry or object id */
if (strlen(buf) > 17)
{
xref->entries[i].obj_id = obj_id++;
xref->entries[i].offset = atol(strtok(buf, " "));
xref->entries[i].gen_num = atoi(strtok(NULL, " "));
xref->entries[i].f_or_n = buf[17];
++added_entries;
}
else
{
obj_id = atoi(buf);
--i;
}
}
xref->n_entries = added_entries;
fseek(fp, start, SEEK_SET);
}
/* Load an xref table from a stream (PDF v1.5 +) */
static void load_xref_from_stream(FILE *fp, xref_t *xref)
{
long start;
int is_stream;
char *stream;
size_t size;
start = ftell(fp);
fseek(fp, xref->start, SEEK_SET);
stream = NULL;
stream = get_object_from_here(fp, &size, &is_stream);
fseek(fp, start, SEEK_SET);
/* TODO: decode and analyize stream */
free(stream);
return;
}
static void get_xref_linear_skipped(FILE *fp, xref_t *xref)
{
int err;
char ch, buf[256];
if (xref->start != 0)
return;
/* Special case (Linearized PDF with initial startxref at 0) */
xref->is_linear = 1;
/* Seek to %%EOF */
if ((xref->end = get_next_eof(fp)) < 0)
return;
/* Locate the trailer */
err = 0;
while (!(err = ferror(fp)) && fread(buf, 1, 8, fp))
{
if (strncmp(buf, "trailer", strlen("trailer")) == 0)
break;
else if ((ftell(fp) - 9) < 0)
return;
fseek(fp, -9, SEEK_CUR);
}
if (err)
return;
/* If we found 'trailer' look backwards for 'xref' */
ch = 0;
while (SAFE_F(fp, ((ch = fgetc(fp)) != 'x')))
fseek(fp, -2, SEEK_CUR);
if (ch == 'x')
{
xref->start = ftell(fp) - 1;
fseek(fp, -1, SEEK_CUR);
}
/* Now continue to next eof ... */
fseek(fp, xref->start, SEEK_SET);
}
/* This must only be called after all xref and entries have been acquired */
static void resolve_linearized_pdf(pdf_t *pdf)
{
int i;
xref_t buf;
if (pdf->n_xrefs < 2)
return;
if (!pdf->xrefs[0].is_linear)
return;
/* Swap Linear with Version 1 */
buf = pdf->xrefs[0];
pdf->xrefs[0] = pdf->xrefs[1];
pdf->xrefs[1] = buf;
/* Resolve is_linear flag and version */
pdf->xrefs[0].is_linear = 1;
pdf->xrefs[0].version = 1;
pdf->xrefs[1].is_linear = 0;
pdf->xrefs[1].version = 1;
/* Adjust the other version values now */
for (i=2; i<pdf->n_xrefs; ++i)
--pdf->xrefs[i].version;
}
static pdf_creator_t *new_creator(int *n_elements)
{
pdf_creator_t *daddy;
static const pdf_creator_t creator_template[] =
{
{"Title", ""},
{"Author", ""},
{"Subject", ""},
{"Keywords", ""},
{"Creator", ""},
{"Producer", ""},
{"CreationDate", ""},
{"ModDate", ""},
{"Trapped", ""},
};
daddy = malloc(sizeof(creator_template));
memcpy(daddy, creator_template, sizeof(creator_template));
if (n_elements)
*n_elements = sizeof(creator_template) / sizeof(creator_template[0]);
return daddy;
}
#define END_OF_TRAILER(_c, _st, _fp) \
{ \
if (_c == '>') \
{ \
fseek(_fp, _st, SEEK_SET); \
continue; \
} \
}
static void load_creator(FILE *fp, pdf_t *pdf)
{
int i, buf_idx;
char c, *buf, obj_id_buf[32] = {0};
long start;
size_t sz;
start = ftell(fp);
/* For each PDF version */
for (i=0; i<pdf->n_xrefs; ++i)
{
if (!pdf->xrefs[i].version)
continue;
/* Find trailer */
fseek(fp, pdf->xrefs[i].start, SEEK_SET);
while (SAFE_F(fp, (fgetc(fp) != 't')))
; /* Iterate to "trailer" */
/* Look for "<< ....... /Info ......" */
c = '\0';
while (SAFE_F(fp, ((c = fgetc(fp)) != '>')))
if (SAFE_F(fp, ((c == '/') &&
(fgetc(fp) == 'I') && ((fgetc(fp) == 'n')))))
break;
/* Could not find /Info in trailer */
END_OF_TRAILER(c, start, fp);
while (SAFE_F(fp, (!isspace(c = fgetc(fp)) && (c != '>'))))
; /* Iterate to first white space /Info<space><data> */
/* No space between /Info and it's data */
END_OF_TRAILER(c, start, fp);
while (SAFE_F(fp, (isspace(c = fgetc(fp)) && (c != '>'))))
; /* Iterate right on top of first non-whitespace /Info data */
/* No data for /Info */
END_OF_TRAILER(c, start, fp);
/* Get obj id as number */
buf_idx = 0;
obj_id_buf[buf_idx++] = c;
while ((buf_idx < (sizeof(obj_id_buf) - 1)) &&
SAFE_F(fp, (!isspace(c = fgetc(fp)) && (c != '>'))))
obj_id_buf[buf_idx++] = c;
END_OF_TRAILER(c, start, fp);
/* Get the object for the creator data. If linear, try both xrefs */
buf = get_object(fp, atoll(obj_id_buf), &pdf->xrefs[i], &sz, NULL);
if (!buf && pdf->xrefs[i].is_linear && (i+1 < pdf->n_xrefs))
buf = get_object(fp, atoll(obj_id_buf), &pdf->xrefs[i+1], &sz, NULL);
load_creator_from_buf(fp, &pdf->xrefs[i], buf);
free(buf);
}
fseek(fp, start, SEEK_SET);
}
static void load_creator_from_buf(FILE *fp, xref_t *xref, const char *buf)
{
int is_xml;
char *c;
if (!buf)
return;
/* Check to see if this is xml or old-school */
if ((c = strstr(buf, "/Type")))
while (*c && !isspace(*c))
++c;
/* Probably "Metadata" */
is_xml = 0;
if (c && (*c == 'M'))
is_xml = 1;
/* Is the buffer XML(PDF 1.4+) or old format? */
if (is_xml)
load_creator_from_xml(xref, buf);
else
load_creator_from_old_format(fp, xref, buf);
}
static void load_creator_from_xml(xref_t *xref, const char *buf)
{
/* TODO */
}
static void load_creator_from_old_format(
FILE *fp,
xref_t *xref,
const char *buf)
{
int i, n_eles, length, is_escaped, obj_id;
char *c, *ascii, *start, *s, *saved_buf_search, *obj;
pdf_creator_t *info;
info = new_creator(&n_eles);
for (i=0; i<n_eles; ++i)
{
if (!(c = strstr(buf, info[i].key)))
continue;
/* Find the value (skipping whitespace) */
c += strlen(info[i].key);
while (isspace(*c))
++c;
/* If looking at the start of a pdf token, we have gone too far */
if (*c == '/')
continue;
/* If the value is a number and not a '(' then the data is located in
* an object we need to fetch, and not inline
*/
obj = saved_buf_search = NULL;
if (isdigit(*c))
{
obj_id = atoi(c);
saved_buf_search = c;
s = saved_buf_search;
obj = get_object(fp, obj_id, xref, NULL, NULL);
c = obj;
/* Iterate to '(' */
while (c && (*c != '('))
++c;
/* Advance the search to the next token */
while (s && (*s == '/'))
++s;
saved_buf_search = s;
}
/* Find the end of the value */
start = c;
length = is_escaped = 0;
while (c && ((*c != '\r') && (*c != '\n') && (*c != '<')))
{
/* Bail out if we see an un-escaped ')' closing character */
if (!is_escaped && (*c == ')'))
break;
else if (*c == '\\')
is_escaped = 1;
else
is_escaped = 0;
++c;
++length;
}
if (length == 0)
continue;
/* Add 1 to length so it gets the closing ')' when we copy */
if (length)
length += 1;
length = (length > KV_MAX_VALUE_LENGTH) ? KV_MAX_VALUE_LENGTH : length;
strncpy(info[i].value, start, length);
info[i].value[KV_MAX_VALUE_LENGTH - 1] = '\0';
/* Restore where we were searching from */
if (saved_buf_search)
{
/* Release memory from get_object() called earlier */
free(obj);
c = saved_buf_search;
}
} /* For all creation information tags */
/* Go through the values and convert if encoded */
for (i=0; i<n_eles; ++i)
if ((ascii = decode_text_string(info[i].value, strlen(info[i].value))))
{
strncpy(info[i].value, ascii, strlen(info[i].value));
free(ascii);
}
xref->creator = info;
xref->n_creator_entries = n_eles;
}
/* Returns object data at the start of the file pointer
* This interfaces to 'get_object'
*/
static char *get_object_from_here(FILE *fp, size_t *size, int *is_stream)
{
long start;
char buf[256];
int obj_id;
xref_t xref;
xref_entry_t entry;
start = ftell(fp);
/* Object ID */
memset(buf, 0, 256);
SAFE_E(fread(buf, 1, 255, fp), 255, "Failed to load object ID.\n");
if (!(obj_id = atoi(buf)))
{
fseek(fp, start, SEEK_SET);
return NULL;
}
/* Create xref entry to pass to the get_object routine */
memset(&entry, 0, sizeof(xref_entry_t));
entry.obj_id = obj_id;
entry.offset = start;
/* Xref and single entry for the object we want data from */
memset(&xref, 0, sizeof(xref_t));
xref.n_entries = 1;
xref.entries = &entry;
fseek(fp, start, SEEK_SET);
return get_object(fp, obj_id, &xref, size, is_stream);
}
static char *get_object(
FILE *fp,
int obj_id,
const xref_t *xref,
size_t *size,
int *is_stream)
{
static const int blk_sz = 256;
int i, total_sz, read_sz, n_blks, search, stream;
size_t obj_sz;
char *c, *data;
long start;
const xref_entry_t *entry;
if (size)
*size = 0;
if (is_stream)
*is_stream = 0;
start = ftell(fp);
/* Find object */
entry = NULL;
for (i=0; i<xref->n_entries; i++)
if (xref->entries[i].obj_id == obj_id)
{
entry = &xref->entries[i];
break;
}
if (!entry)
return NULL;
/* Jump to object start */
fseek(fp, entry->offset, SEEK_SET);
/* Initial allocate */
obj_sz = 0; /* Bytes in object */
total_sz = 0; /* Bytes read in */
n_blks = 1;
data = malloc(blk_sz * n_blks);
memset(data, 0, blk_sz * n_blks);
/* Suck in data */
stream = 0;
while ((read_sz = fread(data+total_sz, 1, blk_sz-1, fp)) && !ferror(fp))
{
total_sz += read_sz;
*(data + total_sz) = '\0';
if (total_sz + blk_sz >= (blk_sz * n_blks))
data = realloc(data, blk_sz * (++n_blks));
search = total_sz - read_sz;
if (search < 0)
search = 0;
if ((c = strstr(data + search, "endobj")))
{
*(c + strlen("endobj") + 1) = '\0';
obj_sz = (void *)strstr(data + search, "endobj") - (void *)data;
obj_sz += strlen("endobj") + 1;
break;
}
else if (strstr(data, "stream"))
stream = 1;
}
clearerr(fp);
fseek(fp, start, SEEK_SET);
if (size)
*size = obj_sz;
if (is_stream)
*is_stream = stream;
return data;
}
static void add_kid(int id, xref_t *xref)
{
/* Make some space */
if (((xref->n_kids + 1) * KID_SIZE) > (xref->n_kids_allocs*KIDS_PER_ALLOC))
xref->kids = realloc(
xref->kids, (++xref->n_kids_allocs)*(KIDS_PER_ALLOC * KID_SIZE));
xref->kids[xref->n_kids++] = id;
}
/* Recursive */
static void load_kids(FILE *fp, int pages_id, xref_t *xref)
{
int dummy, buf_idx, kid_id;
char *data, *c, buf[32];
/* Get kids */
data = get_object(fp, pages_id, xref, NULL, &dummy);
if (!data || !(c = strstr(data, "/Kids")))
{
free(data);
return;
}
c = strchr(c, '[');
buf_idx = 0;
memset(buf, 0, sizeof(buf));
while (*(++c) != ']')
{
if (isdigit(*c) || (*c == ' '))
buf[buf_idx++] = *c;
else if (isalpha(*c))
{
kid_id = atoi(buf);
add_kid(kid_id, xref);
buf_idx = 0;
memset(buf, 0, sizeof(buf));
/* Check kids of kid */
load_kids(fp, kid_id, xref);
}
else if (*c == ']')
break;
}
free(data);
}
static const char *get_type(FILE *fp, int obj_id, const xref_t *xref)
{
int is_stream;
char *c, *obj, *endobj;
static char buf[32];
long start;
start = ftell(fp);
if (!(obj = get_object(fp, obj_id, xref, NULL, &is_stream)) ||
is_stream ||
!(endobj = strstr(obj, "endobj")))
{
free(obj);
fseek(fp, start, SEEK_SET);
if (is_stream)
return "Stream";
else
return "Unknown";
}
/* Get the Type value (avoiding font names like Type1) */
c = obj;
while ((c = strstr(c, "/Type")) && (c < endobj))
if (isdigit(*(c + strlen("/Type"))))
{
++c;
continue;
}
else
break;
if (!c || (c && (c > endobj)))
{
free(obj);
fseek(fp, start, SEEK_SET);
return "Unknown";
}
/* Skip to first blank/whitespace */
c += strlen("/Type");
while (isspace(*c) || *c == '/')
++c;
/* Return the value by storing it in static mem */
memcpy(buf, c, (((c - obj) < sizeof(buf)) ? c - obj : sizeof(buf)));
c = buf;
while (!(isspace(*c) || *c=='/' || *c=='>'))
++c;
*c = '\0';
free(obj);
fseek(fp, start, SEEK_SET);
return buf;
}
/* TODO
static int get_page(int obj_id, const xref_t *xref)
{
int i;
for (i=0; i<xref->n_kids; i++)
if (xref->kids[i] == obj_id)
break;
return i;
}
*/
static char *get_header(FILE *fp)
{
long start;
/* First 1024 bytes of doc must be header (1.7 spec pg 1102) */
char *header;
header = calloc(1, 1024);
start = ftell(fp);
fseek(fp, 0, SEEK_SET);
SAFE_E(fread(header, 1, 1023, fp), 1023, "Failed to load PDF header.\n");
fseek(fp, start, SEEK_SET);
return header;
}
static char *decode_text_string(const char *str, size_t str_len)
{
int idx, is_hex, is_utf16be, ascii_idx;
char *ascii, hex_buf[5] = {0};
is_hex = is_utf16be = idx = ascii_idx = 0;
/* Regular encoding */
if (str[0] == '(')
{
ascii = malloc(strlen(str) + 1);
strncpy(ascii, str, strlen(str) + 1);
return ascii;
}
else if (str[0] == '<')
{
is_hex = 1;
++idx;
}
/* Text strings can be either PDFDocEncoding or UTF-16BE */
if (is_hex && (str_len > 5) &&
(str[idx] == 'F') && (str[idx+1] == 'E') &&
(str[idx+2] == 'F') && (str[idx+3] == 'F'))
{
is_utf16be = 1;
idx += 4;
}
else
return NULL;
/* Now decode as hex */
ascii = malloc(str_len);
for ( ; idx<str_len; ++idx)
{
hex_buf[0] = str[idx++];
hex_buf[1] = str[idx++];
hex_buf[2] = str[idx++];
hex_buf[3] = str[idx];
ascii[ascii_idx++] = strtol(hex_buf, NULL, 16);
}
return ascii;
}
/* Return the offset to the beginning of the %%EOF string.
* A negative value is returned when done scanning.
*/
static int get_next_eof(FILE *fp)
{
int match, c;
const char buf[] = "%%EOF";
match = 0;
while ((c = fgetc(fp)) != EOF)
{
if (c == buf[match])
++match;
else
match = 0;
if (match == 5) /* strlen("%%EOF") */
return ftell(fp) - 5;
}
return -1;
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_1005_2 |
crossvul-cpp_data_bad_519_0 | /*
* Copyright (C) 2000-2002 Constantin Kaplinsky. All Rights Reserved.
* Copyright (C) 2000 Tridia Corporation. All Rights Reserved.
* Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved.
*
* This 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 software 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 software; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
* USA.
*/
/*
* rfbproto.c - functions to deal with client side of RFB protocol.
*/
#ifdef __STRICT_ANSI__
#define _BSD_SOURCE
#define _POSIX_SOURCE
#define _XOPEN_SOURCE 600
#endif
#ifndef WIN32
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <pwd.h>
#endif
#include <errno.h>
#include <rfb/rfbclient.h>
#ifdef WIN32
#undef SOCKET
#undef socklen_t
#endif
#ifdef LIBVNCSERVER_HAVE_LIBZ
#include <zlib.h>
#ifdef __CHECKER__
#undef Z_NULL
#define Z_NULL NULL
#endif
#endif
#ifndef _MSC_VER
/* Strings.h is not available in MSVC */
#include <strings.h>
#endif
#include <stdarg.h>
#include <time.h>
#ifdef LIBVNCSERVER_WITH_CLIENT_GCRYPT
#include <gcrypt.h>
#endif
#include "sasl.h"
#ifdef LIBVNCSERVER_HAVE_LZO
#include <lzo/lzo1x.h>
#else
#include "minilzo.h"
#endif
#include "tls.h"
#ifdef _MSC_VER
# define snprintf _snprintf /* MSVC went straight to the underscored syntax */
#endif
/*
* rfbClientLog prints a time-stamped message to the log file (stderr).
*/
rfbBool rfbEnableClientLogging=TRUE;
static void
rfbDefaultClientLog(const char *format, ...)
{
va_list args;
char buf[256];
time_t log_clock;
if(!rfbEnableClientLogging)
return;
va_start(args, format);
time(&log_clock);
strftime(buf, 255, "%d/%m/%Y %X ", localtime(&log_clock));
fprintf(stderr, "%s", buf);
vfprintf(stderr, format, args);
fflush(stderr);
va_end(args);
}
rfbClientLogProc rfbClientLog=rfbDefaultClientLog;
rfbClientLogProc rfbClientErr=rfbDefaultClientLog;
/* extensions */
rfbClientProtocolExtension* rfbClientExtensions = NULL;
void rfbClientRegisterExtension(rfbClientProtocolExtension* e)
{
e->next = rfbClientExtensions;
rfbClientExtensions = e;
}
/* client data */
void rfbClientSetClientData(rfbClient* client, void* tag, void* data)
{
rfbClientData* clientData = client->clientData;
while(clientData && clientData->tag != tag)
clientData = clientData->next;
if(clientData == NULL) {
clientData = calloc(sizeof(rfbClientData), 1);
clientData->next = client->clientData;
client->clientData = clientData;
clientData->tag = tag;
}
clientData->data = data;
}
void* rfbClientGetClientData(rfbClient* client, void* tag)
{
rfbClientData* clientData = client->clientData;
while(clientData) {
if(clientData->tag == tag)
return clientData->data;
clientData = clientData->next;
}
return NULL;
}
static rfbBool HandleRRE8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleRRE16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleRRE32(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleCoRRE8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleCoRRE16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleCoRRE32(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleHextile8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleHextile16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleHextile32(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleUltra8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleUltra16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleUltra32(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleUltraZip8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleUltraZip16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleUltraZip32(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTRLE8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTRLE15(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTRLE16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTRLE24(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTRLE24Up(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTRLE24Down(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTRLE32(rfbClient* client, int rx, int ry, int rw, int rh);
#ifdef LIBVNCSERVER_HAVE_LIBZ
static rfbBool HandleZlib8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZlib16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZlib32(rfbClient* client, int rx, int ry, int rw, int rh);
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
static rfbBool HandleTight8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTight16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTight32(rfbClient* client, int rx, int ry, int rw, int rh);
static long ReadCompactLen (rfbClient* client);
#endif
static rfbBool HandleZRLE8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZRLE15(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZRLE16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZRLE24(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZRLE24Up(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZRLE24Down(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZRLE32(rfbClient* client, int rx, int ry, int rw, int rh);
#endif
/*
* Server Capability Functions
*/
rfbBool
SupportsClient2Server(rfbClient* client, int messageType)
{
return (client->supportedMessages.client2server[((messageType & 0xFF)/8)] & (1<<(messageType % 8)) ? TRUE : FALSE);
}
rfbBool
SupportsServer2Client(rfbClient* client, int messageType)
{
return (client->supportedMessages.server2client[((messageType & 0xFF)/8)] & (1<<(messageType % 8)) ? TRUE : FALSE);
}
void
SetClient2Server(rfbClient* client, int messageType)
{
client->supportedMessages.client2server[((messageType & 0xFF)/8)] |= (1<<(messageType % 8));
}
void
SetServer2Client(rfbClient* client, int messageType)
{
client->supportedMessages.server2client[((messageType & 0xFF)/8)] |= (1<<(messageType % 8));
}
void
ClearClient2Server(rfbClient* client, int messageType)
{
client->supportedMessages.client2server[((messageType & 0xFF)/8)] &= (!(1<<(messageType % 8)));
}
void
ClearServer2Client(rfbClient* client, int messageType)
{
client->supportedMessages.server2client[((messageType & 0xFF)/8)] &= (!(1<<(messageType % 8)));
}
void
DefaultSupportedMessages(rfbClient* client)
{
memset((char *)&client->supportedMessages,0,sizeof(client->supportedMessages));
/* Default client supported messages (universal RFB 3.3 protocol) */
SetClient2Server(client, rfbSetPixelFormat);
/* SetClient2Server(client, rfbFixColourMapEntries); Not currently supported */
SetClient2Server(client, rfbSetEncodings);
SetClient2Server(client, rfbFramebufferUpdateRequest);
SetClient2Server(client, rfbKeyEvent);
SetClient2Server(client, rfbPointerEvent);
SetClient2Server(client, rfbClientCutText);
/* technically, we only care what we can *send* to the server
* but, we set Server2Client Just in case it ever becomes useful
*/
SetServer2Client(client, rfbFramebufferUpdate);
SetServer2Client(client, rfbSetColourMapEntries);
SetServer2Client(client, rfbBell);
SetServer2Client(client, rfbServerCutText);
}
void
DefaultSupportedMessagesUltraVNC(rfbClient* client)
{
DefaultSupportedMessages(client);
SetClient2Server(client, rfbFileTransfer);
SetClient2Server(client, rfbSetScale);
SetClient2Server(client, rfbSetServerInput);
SetClient2Server(client, rfbSetSW);
SetClient2Server(client, rfbTextChat);
SetClient2Server(client, rfbPalmVNCSetScaleFactor);
/* technically, we only care what we can *send* to the server */
SetServer2Client(client, rfbResizeFrameBuffer);
SetServer2Client(client, rfbPalmVNCReSizeFrameBuffer);
SetServer2Client(client, rfbFileTransfer);
SetServer2Client(client, rfbTextChat);
}
void
DefaultSupportedMessagesTightVNC(rfbClient* client)
{
DefaultSupportedMessages(client);
SetClient2Server(client, rfbFileTransfer);
SetClient2Server(client, rfbSetServerInput);
SetClient2Server(client, rfbSetSW);
/* SetClient2Server(client, rfbTextChat); */
/* technically, we only care what we can *send* to the server */
SetServer2Client(client, rfbFileTransfer);
SetServer2Client(client, rfbTextChat);
}
#ifndef WIN32
static rfbBool
IsUnixSocket(const char *name)
{
struct stat sb;
if(stat(name, &sb) == 0 && (sb.st_mode & S_IFMT) == S_IFSOCK)
return TRUE;
return FALSE;
}
#endif
/*
* ConnectToRFBServer.
*/
rfbBool
ConnectToRFBServer(rfbClient* client,const char *hostname, int port)
{
if (client->serverPort==-1) {
/* serverHost is a file recorded by vncrec. */
const char* magic="vncLog0.0";
char buffer[10];
rfbVNCRec* rec = (rfbVNCRec*)malloc(sizeof(rfbVNCRec));
client->vncRec = rec;
rec->file = fopen(client->serverHost,"rb");
rec->tv.tv_sec = 0;
rec->readTimestamp = FALSE;
rec->doNotSleep = FALSE;
if (!rec->file) {
rfbClientLog("Could not open %s.\n",client->serverHost);
return FALSE;
}
setbuf(rec->file,NULL);
if (fread(buffer,1,strlen(magic),rec->file) != strlen(magic) || strncmp(buffer,magic,strlen(magic))) {
rfbClientLog("File %s was not recorded by vncrec.\n",client->serverHost);
fclose(rec->file);
return FALSE;
}
client->sock = -1;
return TRUE;
}
#ifndef WIN32
if(IsUnixSocket(hostname))
/* serverHost is a UNIX socket. */
client->sock = ConnectClientToUnixSock(hostname);
else
#endif
{
#ifdef LIBVNCSERVER_IPv6
client->sock = ConnectClientToTcpAddr6(hostname, port);
if (client->sock == -1)
#endif
{
unsigned int host;
/* serverHost is a hostname */
if (!StringToIPAddr(hostname, &host)) {
rfbClientLog("Couldn't convert '%s' to host address\n", hostname);
return FALSE;
}
client->sock = ConnectClientToTcpAddr(host, port);
}
}
if (client->sock < 0) {
rfbClientLog("Unable to connect to VNC server\n");
return FALSE;
}
if(client->QoS_DSCP && !SetDSCP(client->sock, client->QoS_DSCP))
return FALSE;
return SetNonBlocking(client->sock);
}
/*
* ConnectToRFBRepeater.
*/
rfbBool ConnectToRFBRepeater(rfbClient* client,const char *repeaterHost, int repeaterPort, const char *destHost, int destPort)
{
rfbProtocolVersionMsg pv;
int major,minor;
char tmphost[250];
int tmphostlen;
#ifdef LIBVNCSERVER_IPv6
client->sock = ConnectClientToTcpAddr6(repeaterHost, repeaterPort);
if (client->sock == -1)
#endif
{
unsigned int host;
if (!StringToIPAddr(repeaterHost, &host)) {
rfbClientLog("Couldn't convert '%s' to host address\n", repeaterHost);
return FALSE;
}
client->sock = ConnectClientToTcpAddr(host, repeaterPort);
}
if (client->sock < 0) {
rfbClientLog("Unable to connect to VNC repeater\n");
return FALSE;
}
if (!SetNonBlocking(client->sock))
return FALSE;
if (!ReadFromRFBServer(client, pv, sz_rfbProtocolVersionMsg))
return FALSE;
pv[sz_rfbProtocolVersionMsg] = 0;
/* UltraVNC repeater always report version 000.000 to identify itself */
if (sscanf(pv,rfbProtocolVersionFormat,&major,&minor) != 2 || major != 0 || minor != 0) {
rfbClientLog("Not a valid VNC repeater (%s)\n",pv);
return FALSE;
}
rfbClientLog("Connected to VNC repeater, using protocol version %d.%d\n", major, minor);
tmphostlen = snprintf(tmphost, sizeof(tmphost), "%s:%d", destHost, destPort);
if(tmphostlen < 0 || tmphostlen >= (int)sizeof(tmphost))
return FALSE; /* snprintf error or output truncated */
if (!WriteToRFBServer(client, tmphost, tmphostlen + 1))
return FALSE;
return TRUE;
}
extern void rfbClientEncryptBytes(unsigned char* bytes, char* passwd);
extern void rfbClientEncryptBytes2(unsigned char *where, const int length, unsigned char *key);
static void
ReadReason(rfbClient* client)
{
uint32_t reasonLen;
char *reason;
if (!ReadFromRFBServer(client, (char *)&reasonLen, 4)) return;
reasonLen = rfbClientSwap32IfLE(reasonLen);
if(reasonLen > 1<<20) {
rfbClientLog("VNC connection failed, but sent reason length of %u exceeds limit of 1MB",(unsigned int)reasonLen);
return;
}
reason = malloc(reasonLen+1);
if (!ReadFromRFBServer(client, reason, reasonLen)) { free(reason); return; }
reason[reasonLen]=0;
rfbClientLog("VNC connection failed: %s\n",reason);
free(reason);
}
rfbBool
rfbHandleAuthResult(rfbClient* client)
{
uint32_t authResult=0;
if (!ReadFromRFBServer(client, (char *)&authResult, 4)) return FALSE;
authResult = rfbClientSwap32IfLE(authResult);
switch (authResult) {
case rfbVncAuthOK:
rfbClientLog("VNC authentication succeeded\n");
return TRUE;
break;
case rfbVncAuthFailed:
if (client->major==3 && client->minor>7)
{
/* we have an error following */
ReadReason(client);
return FALSE;
}
rfbClientLog("VNC authentication failed\n");
return FALSE;
case rfbVncAuthTooMany:
rfbClientLog("VNC authentication failed - too many tries\n");
return FALSE;
}
rfbClientLog("Unknown VNC authentication result: %d\n",
(int)authResult);
return FALSE;
}
static rfbBool
ReadSupportedSecurityType(rfbClient* client, uint32_t *result, rfbBool subAuth)
{
uint8_t count=0;
uint8_t loop=0;
uint8_t flag=0;
rfbBool extAuthHandler;
uint8_t tAuth[256];
char buf1[500],buf2[10];
uint32_t authScheme;
rfbClientProtocolExtension* e;
if (!ReadFromRFBServer(client, (char *)&count, 1)) return FALSE;
if (count==0)
{
rfbClientLog("List of security types is ZERO, expecting an error to follow\n");
ReadReason(client);
return FALSE;
}
rfbClientLog("We have %d security types to read\n", count);
authScheme=0;
/* now, we have a list of available security types to read ( uint8_t[] ) */
for (loop=0;loop<count;loop++)
{
if (!ReadFromRFBServer(client, (char *)&tAuth[loop], 1)) return FALSE;
rfbClientLog("%d) Received security type %d\n", loop, tAuth[loop]);
if (flag) continue;
extAuthHandler=FALSE;
for (e = rfbClientExtensions; e; e = e->next) {
if (!e->handleAuthentication) continue;
uint32_t const* secType;
for (secType = e->securityTypes; secType && *secType; secType++) {
if (tAuth[loop]==*secType) {
extAuthHandler=TRUE;
}
}
}
if (tAuth[loop]==rfbVncAuth || tAuth[loop]==rfbNoAuth ||
extAuthHandler ||
#if defined(LIBVNCSERVER_HAVE_GNUTLS) || defined(LIBVNCSERVER_HAVE_LIBSSL)
tAuth[loop]==rfbVeNCrypt ||
#endif
#ifdef LIBVNCSERVER_HAVE_SASL
tAuth[loop]==rfbSASL ||
#endif /* LIBVNCSERVER_HAVE_SASL */
(tAuth[loop]==rfbARD && client->GetCredential) ||
(!subAuth && (tAuth[loop]==rfbTLS || (tAuth[loop]==rfbVeNCrypt && client->GetCredential))))
{
if (!subAuth && client->clientAuthSchemes)
{
int i;
for (i=0;client->clientAuthSchemes[i];i++)
{
if (client->clientAuthSchemes[i]==(uint32_t)tAuth[loop])
{
flag++;
authScheme=tAuth[loop];
break;
}
}
}
else
{
flag++;
authScheme=tAuth[loop];
}
if (flag)
{
rfbClientLog("Selecting security type %d (%d/%d in the list)\n", authScheme, loop, count);
/* send back a single byte indicating which security type to use */
if (!WriteToRFBServer(client, (char *)&tAuth[loop], 1)) return FALSE;
}
}
}
if (authScheme==0)
{
memset(buf1, 0, sizeof(buf1));
for (loop=0;loop<count;loop++)
{
if (strlen(buf1)>=sizeof(buf1)-1) break;
snprintf(buf2, sizeof(buf2), (loop>0 ? ", %d" : "%d"), (int)tAuth[loop]);
strncat(buf1, buf2, sizeof(buf1)-strlen(buf1)-1);
}
rfbClientLog("Unknown authentication scheme from VNC server: %s\n",
buf1);
return FALSE;
}
*result = authScheme;
return TRUE;
}
static rfbBool
HandleVncAuth(rfbClient *client)
{
uint8_t challenge[CHALLENGESIZE];
char *passwd=NULL;
int i;
if (!ReadFromRFBServer(client, (char *)challenge, CHALLENGESIZE)) return FALSE;
if (client->serverPort!=-1) { /* if not playing a vncrec file */
if (client->GetPassword)
passwd = client->GetPassword(client);
if ((!passwd) || (strlen(passwd) == 0)) {
rfbClientLog("Reading password failed\n");
return FALSE;
}
if (strlen(passwd) > 8) {
passwd[8] = '\0';
}
rfbClientEncryptBytes(challenge, passwd);
/* Lose the password from memory */
for (i = strlen(passwd); i >= 0; i--) {
passwd[i] = '\0';
}
free(passwd);
if (!WriteToRFBServer(client, (char *)challenge, CHALLENGESIZE)) return FALSE;
}
/* Handle the SecurityResult message */
if (!rfbHandleAuthResult(client)) return FALSE;
return TRUE;
}
static void
FreeUserCredential(rfbCredential *cred)
{
if (cred->userCredential.username) free(cred->userCredential.username);
if (cred->userCredential.password) free(cred->userCredential.password);
free(cred);
}
static rfbBool
HandlePlainAuth(rfbClient *client)
{
uint32_t ulen, ulensw;
uint32_t plen, plensw;
rfbCredential *cred;
if (!client->GetCredential)
{
rfbClientLog("GetCredential callback is not set.\n");
return FALSE;
}
cred = client->GetCredential(client, rfbCredentialTypeUser);
if (!cred)
{
rfbClientLog("Reading credential failed\n");
return FALSE;
}
ulen = (cred->userCredential.username ? strlen(cred->userCredential.username) : 0);
ulensw = rfbClientSwap32IfLE(ulen);
plen = (cred->userCredential.password ? strlen(cred->userCredential.password) : 0);
plensw = rfbClientSwap32IfLE(plen);
if (!WriteToRFBServer(client, (char *)&ulensw, 4) ||
!WriteToRFBServer(client, (char *)&plensw, 4))
{
FreeUserCredential(cred);
return FALSE;
}
if (ulen > 0)
{
if (!WriteToRFBServer(client, cred->userCredential.username, ulen))
{
FreeUserCredential(cred);
return FALSE;
}
}
if (plen > 0)
{
if (!WriteToRFBServer(client, cred->userCredential.password, plen))
{
FreeUserCredential(cred);
return FALSE;
}
}
FreeUserCredential(cred);
/* Handle the SecurityResult message */
if (!rfbHandleAuthResult(client)) return FALSE;
return TRUE;
}
/* Simple 64bit big integer arithmetic implementation */
/* (x + y) % m, works even if (x + y) > 64bit */
#define rfbAddM64(x,y,m) ((x+y)%m+(x+y<x?(((uint64_t)-1)%m+1)%m:0))
/* (x * y) % m */
static uint64_t
rfbMulM64(uint64_t x, uint64_t y, uint64_t m)
{
uint64_t r;
for(r=0;x>0;x>>=1)
{
if (x&1) r=rfbAddM64(r,y,m);
y=rfbAddM64(y,y,m);
}
return r;
}
/* (x ^ y) % m */
static uint64_t
rfbPowM64(uint64_t b, uint64_t e, uint64_t m)
{
uint64_t r;
for(r=1;e>0;e>>=1)
{
if(e&1) r=rfbMulM64(r,b,m);
b=rfbMulM64(b,b,m);
}
return r;
}
static rfbBool
HandleMSLogonAuth(rfbClient *client)
{
uint64_t gen, mod, resp, priv, pub, key;
uint8_t username[256], password[64];
rfbCredential *cred;
if (!ReadFromRFBServer(client, (char *)&gen, 8)) return FALSE;
if (!ReadFromRFBServer(client, (char *)&mod, 8)) return FALSE;
if (!ReadFromRFBServer(client, (char *)&resp, 8)) return FALSE;
gen = rfbClientSwap64IfLE(gen);
mod = rfbClientSwap64IfLE(mod);
resp = rfbClientSwap64IfLE(resp);
if (!client->GetCredential)
{
rfbClientLog("GetCredential callback is not set.\n");
return FALSE;
}
rfbClientLog("WARNING! MSLogon security type has very low password encryption! "\
"Use it only with SSH tunnel or trusted network.\n");
cred = client->GetCredential(client, rfbCredentialTypeUser);
if (!cred)
{
rfbClientLog("Reading credential failed\n");
return FALSE;
}
memset(username, 0, sizeof(username));
strncpy((char *)username, cred->userCredential.username, sizeof(username));
memset(password, 0, sizeof(password));
strncpy((char *)password, cred->userCredential.password, sizeof(password));
FreeUserCredential(cred);
srand(time(NULL));
priv = ((uint64_t)rand())<<32;
priv |= (uint64_t)rand();
pub = rfbPowM64(gen, priv, mod);
key = rfbPowM64(resp, priv, mod);
pub = rfbClientSwap64IfLE(pub);
key = rfbClientSwap64IfLE(key);
rfbClientEncryptBytes2(username, sizeof(username), (unsigned char *)&key);
rfbClientEncryptBytes2(password, sizeof(password), (unsigned char *)&key);
if (!WriteToRFBServer(client, (char *)&pub, 8)) return FALSE;
if (!WriteToRFBServer(client, (char *)username, sizeof(username))) return FALSE;
if (!WriteToRFBServer(client, (char *)password, sizeof(password))) return FALSE;
/* Handle the SecurityResult message */
if (!rfbHandleAuthResult(client)) return FALSE;
return TRUE;
}
#ifdef LIBVNCSERVER_WITH_CLIENT_GCRYPT
static rfbBool
rfbMpiToBytes(const gcry_mpi_t value, uint8_t *result, size_t size)
{
gcry_error_t error;
size_t len;
int i;
error = gcry_mpi_print(GCRYMPI_FMT_USG, result, size, &len, value);
if (gcry_err_code(error) != GPG_ERR_NO_ERROR)
{
rfbClientLog("gcry_mpi_print error: %s\n", gcry_strerror(error));
return FALSE;
}
for (i=size-1;i>(int)size-1-(int)len;--i)
result[i] = result[i-size+len];
for (;i>=0;--i)
result[i] = 0;
return TRUE;
}
static rfbBool
HandleARDAuth(rfbClient *client)
{
uint8_t gen[2], len[2];
size_t keylen;
uint8_t *mod = NULL, *resp, *pub, *key, *shared;
gcry_mpi_t genmpi = NULL, modmpi = NULL, respmpi = NULL;
gcry_mpi_t privmpi = NULL, pubmpi = NULL, keympi = NULL;
gcry_md_hd_t md5 = NULL;
gcry_cipher_hd_t aes = NULL;
gcry_error_t error;
uint8_t userpass[128], ciphertext[128];
int passwordLen, usernameLen;
rfbCredential *cred = NULL;
rfbBool result = FALSE;
if (!gcry_control(GCRYCTL_INITIALIZATION_FINISHED_P))
{
/* Application did not initialize gcrypt, so we should */
if (!gcry_check_version(GCRYPT_VERSION))
{
/* Older version of libgcrypt is installed on system than compiled against */
rfbClientLog("libgcrypt version mismatch.\n");
}
}
while (1)
{
if (!ReadFromRFBServer(client, (char *)gen, 2))
break;
if (!ReadFromRFBServer(client, (char *)len, 2))
break;
if (!client->GetCredential)
{
rfbClientLog("GetCredential callback is not set.\n");
break;
}
cred = client->GetCredential(client, rfbCredentialTypeUser);
if (!cred)
{
rfbClientLog("Reading credential failed\n");
break;
}
keylen = 256*len[0]+len[1];
mod = (uint8_t*)malloc(keylen*4);
if (!mod)
{
rfbClientLog("malloc out of memory\n");
break;
}
resp = mod+keylen;
pub = resp+keylen;
key = pub+keylen;
if (!ReadFromRFBServer(client, (char *)mod, keylen))
break;
if (!ReadFromRFBServer(client, (char *)resp, keylen))
break;
error = gcry_mpi_scan(&genmpi, GCRYMPI_FMT_USG, gen, 2, NULL);
if (gcry_err_code(error) != GPG_ERR_NO_ERROR)
{
rfbClientLog("gcry_mpi_scan error: %s\n", gcry_strerror(error));
break;
}
error = gcry_mpi_scan(&modmpi, GCRYMPI_FMT_USG, mod, keylen, NULL);
if (gcry_err_code(error) != GPG_ERR_NO_ERROR)
{
rfbClientLog("gcry_mpi_scan error: %s\n", gcry_strerror(error));
break;
}
error = gcry_mpi_scan(&respmpi, GCRYMPI_FMT_USG, resp, keylen, NULL);
if (gcry_err_code(error) != GPG_ERR_NO_ERROR)
{
rfbClientLog("gcry_mpi_scan error: %s\n", gcry_strerror(error));
break;
}
privmpi = gcry_mpi_new(keylen);
if (!privmpi)
{
rfbClientLog("gcry_mpi_new out of memory\n");
break;
}
gcry_mpi_randomize(privmpi, (keylen/8)*8, GCRY_STRONG_RANDOM);
pubmpi = gcry_mpi_new(keylen);
if (!pubmpi)
{
rfbClientLog("gcry_mpi_new out of memory\n");
break;
}
gcry_mpi_powm(pubmpi, genmpi, privmpi, modmpi);
keympi = gcry_mpi_new(keylen);
if (!keympi)
{
rfbClientLog("gcry_mpi_new out of memory\n");
break;
}
gcry_mpi_powm(keympi, respmpi, privmpi, modmpi);
if (!rfbMpiToBytes(pubmpi, pub, keylen))
break;
if (!rfbMpiToBytes(keympi, key, keylen))
break;
error = gcry_md_open(&md5, GCRY_MD_MD5, 0);
if (gcry_err_code(error) != GPG_ERR_NO_ERROR)
{
rfbClientLog("gcry_md_open error: %s\n", gcry_strerror(error));
break;
}
gcry_md_write(md5, key, keylen);
error = gcry_md_final(md5);
if (gcry_err_code(error) != GPG_ERR_NO_ERROR)
{
rfbClientLog("gcry_md_final error: %s\n", gcry_strerror(error));
break;
}
shared = gcry_md_read(md5, GCRY_MD_MD5);
passwordLen = strlen(cred->userCredential.password)+1;
usernameLen = strlen(cred->userCredential.username)+1;
if (passwordLen > sizeof(userpass)/2)
passwordLen = sizeof(userpass)/2;
if (usernameLen > sizeof(userpass)/2)
usernameLen = sizeof(userpass)/2;
gcry_randomize(userpass, sizeof(userpass), GCRY_STRONG_RANDOM);
memcpy(userpass, cred->userCredential.username, usernameLen);
memcpy(userpass+sizeof(userpass)/2, cred->userCredential.password, passwordLen);
error = gcry_cipher_open(&aes, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_ECB, 0);
if (gcry_err_code(error) != GPG_ERR_NO_ERROR)
{
rfbClientLog("gcry_cipher_open error: %s\n", gcry_strerror(error));
break;
}
error = gcry_cipher_setkey(aes, shared, 16);
if (gcry_err_code(error) != GPG_ERR_NO_ERROR)
{
rfbClientLog("gcry_cipher_setkey error: %s\n", gcry_strerror(error));
break;
}
error = gcry_cipher_encrypt(aes, ciphertext, sizeof(ciphertext), userpass, sizeof(userpass));
if (gcry_err_code(error) != GPG_ERR_NO_ERROR)
{
rfbClientLog("gcry_cipher_encrypt error: %s\n", gcry_strerror(error));
break;
}
if (!WriteToRFBServer(client, (char *)ciphertext, sizeof(ciphertext)))
break;
if (!WriteToRFBServer(client, (char *)pub, keylen))
break;
/* Handle the SecurityResult message */
if (!rfbHandleAuthResult(client))
break;
result = TRUE;
break;
}
if (cred)
FreeUserCredential(cred);
if (mod)
free(mod);
if (genmpi)
gcry_mpi_release(genmpi);
if (modmpi)
gcry_mpi_release(modmpi);
if (respmpi)
gcry_mpi_release(respmpi);
if (privmpi)
gcry_mpi_release(privmpi);
if (pubmpi)
gcry_mpi_release(pubmpi);
if (keympi)
gcry_mpi_release(keympi);
if (md5)
gcry_md_close(md5);
if (aes)
gcry_cipher_close(aes);
return result;
}
#endif
/*
* SetClientAuthSchemes.
*/
void
SetClientAuthSchemes(rfbClient* client,const uint32_t *authSchemes, int size)
{
int i;
if (client->clientAuthSchemes)
{
free(client->clientAuthSchemes);
client->clientAuthSchemes = NULL;
}
if (authSchemes)
{
if (size<0)
{
/* If size<0 we assume the passed-in list is also 0-terminate, so we
* calculate the size here */
for (size=0;authSchemes[size];size++) ;
}
client->clientAuthSchemes = (uint32_t*)malloc(sizeof(uint32_t)*(size+1));
for (i=0;i<size;i++)
client->clientAuthSchemes[i] = authSchemes[i];
client->clientAuthSchemes[size] = 0;
}
}
/*
* InitialiseRFBConnection.
*/
rfbBool
InitialiseRFBConnection(rfbClient* client)
{
rfbProtocolVersionMsg pv;
int major,minor;
uint32_t authScheme;
uint32_t subAuthScheme;
rfbClientInitMsg ci;
/* if the connection is immediately closed, don't report anything, so
that pmw's monitor can make test connections */
if (client->listenSpecified)
errorMessageOnReadFailure = FALSE;
if (!ReadFromRFBServer(client, pv, sz_rfbProtocolVersionMsg)) return FALSE;
pv[sz_rfbProtocolVersionMsg]=0;
errorMessageOnReadFailure = TRUE;
pv[sz_rfbProtocolVersionMsg] = 0;
if (sscanf(pv,rfbProtocolVersionFormat,&major,&minor) != 2) {
rfbClientLog("Not a valid VNC server (%s)\n",pv);
return FALSE;
}
DefaultSupportedMessages(client);
client->major = major;
client->minor = minor;
/* fall back to viewer supported version */
if ((major==rfbProtocolMajorVersion) && (minor>rfbProtocolMinorVersion))
client->minor = rfbProtocolMinorVersion;
/* UltraVNC uses minor codes 4 and 6 for the server */
if (major==3 && (minor==4 || minor==6)) {
rfbClientLog("UltraVNC server detected, enabling UltraVNC specific messages\n",pv);
DefaultSupportedMessagesUltraVNC(client);
}
/* UltraVNC Single Click uses minor codes 14 and 16 for the server */
if (major==3 && (minor==14 || minor==16)) {
minor = minor - 10;
client->minor = minor;
rfbClientLog("UltraVNC Single Click server detected, enabling UltraVNC specific messages\n",pv);
DefaultSupportedMessagesUltraVNC(client);
}
/* TightVNC uses minor codes 5 for the server */
if (major==3 && minor==5) {
rfbClientLog("TightVNC server detected, enabling TightVNC specific messages\n",pv);
DefaultSupportedMessagesTightVNC(client);
}
/* we do not support > RFB3.8 */
if ((major==3 && minor>8) || major>3)
{
client->major=3;
client->minor=8;
}
rfbClientLog("VNC server supports protocol version %d.%d (viewer %d.%d)\n",
major, minor, rfbProtocolMajorVersion, rfbProtocolMinorVersion);
sprintf(pv,rfbProtocolVersionFormat,client->major,client->minor);
if (!WriteToRFBServer(client, pv, sz_rfbProtocolVersionMsg)) return FALSE;
/* 3.7 and onwards sends a # of security types first */
if (client->major==3 && client->minor > 6)
{
if (!ReadSupportedSecurityType(client, &authScheme, FALSE)) return FALSE;
}
else
{
if (!ReadFromRFBServer(client, (char *)&authScheme, 4)) return FALSE;
authScheme = rfbClientSwap32IfLE(authScheme);
}
rfbClientLog("Selected Security Scheme %d\n", authScheme);
client->authScheme = authScheme;
switch (authScheme) {
case rfbConnFailed:
ReadReason(client);
return FALSE;
case rfbNoAuth:
rfbClientLog("No authentication needed\n");
/* 3.8 and upwards sends a Security Result for rfbNoAuth */
if ((client->major==3 && client->minor > 7) || client->major>3)
if (!rfbHandleAuthResult(client)) return FALSE;
break;
case rfbVncAuth:
if (!HandleVncAuth(client)) return FALSE;
break;
#ifdef LIBVNCSERVER_HAVE_SASL
case rfbSASL:
if (!HandleSASLAuth(client)) return FALSE;
break;
#endif /* LIBVNCSERVER_HAVE_SASL */
case rfbMSLogon:
if (!HandleMSLogonAuth(client)) return FALSE;
break;
case rfbARD:
#ifndef LIBVNCSERVER_WITH_CLIENT_GCRYPT
rfbClientLog("GCrypt support was not compiled in\n");
return FALSE;
#else
if (!HandleARDAuth(client)) return FALSE;
#endif
break;
case rfbTLS:
if (!HandleAnonTLSAuth(client)) return FALSE;
/* After the TLS session is established, sub auth types are expected.
* Note that all following reading/writing are through the TLS session from here.
*/
if (!ReadSupportedSecurityType(client, &subAuthScheme, TRUE)) return FALSE;
client->subAuthScheme = subAuthScheme;
switch (subAuthScheme) {
case rfbConnFailed:
ReadReason(client);
return FALSE;
case rfbNoAuth:
rfbClientLog("No sub authentication needed\n");
/* 3.8 and upwards sends a Security Result for rfbNoAuth */
if ((client->major==3 && client->minor > 7) || client->major>3)
if (!rfbHandleAuthResult(client)) return FALSE;
break;
case rfbVncAuth:
if (!HandleVncAuth(client)) return FALSE;
break;
#ifdef LIBVNCSERVER_HAVE_SASL
case rfbSASL:
if (!HandleSASLAuth(client)) return FALSE;
break;
#endif /* LIBVNCSERVER_HAVE_SASL */
default:
rfbClientLog("Unknown sub authentication scheme from VNC server: %d\n",
(int)subAuthScheme);
return FALSE;
}
break;
case rfbVeNCrypt:
if (!HandleVeNCryptAuth(client)) return FALSE;
switch (client->subAuthScheme) {
case rfbVeNCryptTLSNone:
case rfbVeNCryptX509None:
rfbClientLog("No sub authentication needed\n");
if (!rfbHandleAuthResult(client)) return FALSE;
break;
case rfbVeNCryptTLSVNC:
case rfbVeNCryptX509VNC:
if (!HandleVncAuth(client)) return FALSE;
break;
case rfbVeNCryptTLSPlain:
case rfbVeNCryptX509Plain:
if (!HandlePlainAuth(client)) return FALSE;
break;
#ifdef LIBVNCSERVER_HAVE_SASL
case rfbVeNCryptX509SASL:
case rfbVeNCryptTLSSASL:
if (!HandleSASLAuth(client)) return FALSE;
break;
#endif /* LIBVNCSERVER_HAVE_SASL */
default:
rfbClientLog("Unknown sub authentication scheme from VNC server: %d\n",
client->subAuthScheme);
return FALSE;
}
break;
default:
{
rfbBool authHandled=FALSE;
rfbClientProtocolExtension* e;
for (e = rfbClientExtensions; e; e = e->next) {
uint32_t const* secType;
if (!e->handleAuthentication) continue;
for (secType = e->securityTypes; secType && *secType; secType++) {
if (authScheme==*secType) {
if (!e->handleAuthentication(client, authScheme)) return FALSE;
if (!rfbHandleAuthResult(client)) return FALSE;
authHandled=TRUE;
}
}
}
if (authHandled) break;
}
rfbClientLog("Unknown authentication scheme from VNC server: %d\n",
(int)authScheme);
return FALSE;
}
ci.shared = (client->appData.shareDesktop ? 1 : 0);
if (!WriteToRFBServer(client, (char *)&ci, sz_rfbClientInitMsg)) return FALSE;
if (!ReadFromRFBServer(client, (char *)&client->si, sz_rfbServerInitMsg)) return FALSE;
client->si.framebufferWidth = rfbClientSwap16IfLE(client->si.framebufferWidth);
client->si.framebufferHeight = rfbClientSwap16IfLE(client->si.framebufferHeight);
client->si.format.redMax = rfbClientSwap16IfLE(client->si.format.redMax);
client->si.format.greenMax = rfbClientSwap16IfLE(client->si.format.greenMax);
client->si.format.blueMax = rfbClientSwap16IfLE(client->si.format.blueMax);
client->si.nameLength = rfbClientSwap32IfLE(client->si.nameLength);
/* To guard against integer wrap-around, si.nameLength is cast to 64 bit */
client->desktopName = malloc((uint64_t)client->si.nameLength + 1);
if (!client->desktopName) {
rfbClientLog("Error allocating memory for desktop name, %lu bytes\n",
(unsigned long)client->si.nameLength);
return FALSE;
}
if (!ReadFromRFBServer(client, client->desktopName, client->si.nameLength)) return FALSE;
client->desktopName[client->si.nameLength] = 0;
rfbClientLog("Desktop name \"%s\"\n",client->desktopName);
rfbClientLog("Connected to VNC server, using protocol version %d.%d\n",
client->major, client->minor);
rfbClientLog("VNC server default format:\n");
PrintPixelFormat(&client->si.format);
return TRUE;
}
/*
* SetFormatAndEncodings.
*/
rfbBool
SetFormatAndEncodings(rfbClient* client)
{
rfbSetPixelFormatMsg spf;
char buf[sz_rfbSetEncodingsMsg + MAX_ENCODINGS * 4];
rfbSetEncodingsMsg *se = (rfbSetEncodingsMsg *)buf;
uint32_t *encs = (uint32_t *)(&buf[sz_rfbSetEncodingsMsg]);
int len = 0;
rfbBool requestCompressLevel = FALSE;
rfbBool requestQualityLevel = FALSE;
rfbBool requestLastRectEncoding = FALSE;
rfbClientProtocolExtension* e;
if (!SupportsClient2Server(client, rfbSetPixelFormat)) return TRUE;
spf.type = rfbSetPixelFormat;
spf.pad1 = 0;
spf.pad2 = 0;
spf.format = client->format;
spf.format.redMax = rfbClientSwap16IfLE(spf.format.redMax);
spf.format.greenMax = rfbClientSwap16IfLE(spf.format.greenMax);
spf.format.blueMax = rfbClientSwap16IfLE(spf.format.blueMax);
if (!WriteToRFBServer(client, (char *)&spf, sz_rfbSetPixelFormatMsg))
return FALSE;
if (!SupportsClient2Server(client, rfbSetEncodings)) return TRUE;
se->type = rfbSetEncodings;
se->pad = 0;
se->nEncodings = 0;
if (client->appData.encodingsString) {
const char *encStr = client->appData.encodingsString;
int encStrLen;
do {
const char *nextEncStr = strchr(encStr, ' ');
if (nextEncStr) {
encStrLen = nextEncStr - encStr;
nextEncStr++;
} else {
encStrLen = strlen(encStr);
}
if (strncasecmp(encStr,"raw",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRaw);
} else if (strncasecmp(encStr,"copyrect",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCopyRect);
#ifdef LIBVNCSERVER_HAVE_LIBZ
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
} else if (strncasecmp(encStr,"tight",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingTight);
requestLastRectEncoding = TRUE;
if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9)
requestCompressLevel = TRUE;
if (client->appData.enableJPEG)
requestQualityLevel = TRUE;
#endif
#endif
} else if (strncasecmp(encStr,"hextile",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingHextile);
#ifdef LIBVNCSERVER_HAVE_LIBZ
} else if (strncasecmp(encStr,"zlib",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZlib);
if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9)
requestCompressLevel = TRUE;
} else if (strncasecmp(encStr,"zlibhex",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZlibHex);
if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9)
requestCompressLevel = TRUE;
} else if (strncasecmp(encStr,"trle",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingTRLE);
} else if (strncasecmp(encStr,"zrle",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZRLE);
} else if (strncasecmp(encStr,"zywrle",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZYWRLE);
requestQualityLevel = TRUE;
#endif
} else if ((strncasecmp(encStr,"ultra",encStrLen) == 0) || (strncasecmp(encStr,"ultrazip",encStrLen) == 0)) {
/* There are 2 encodings used in 'ultra' */
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltra);
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltraZip);
} else if (strncasecmp(encStr,"corre",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCoRRE);
} else if (strncasecmp(encStr,"rre",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRRE);
} else {
rfbClientLog("Unknown encoding '%.*s'\n",encStrLen,encStr);
}
encStr = nextEncStr;
} while (encStr && se->nEncodings < MAX_ENCODINGS);
if (se->nEncodings < MAX_ENCODINGS && requestCompressLevel) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.compressLevel +
rfbEncodingCompressLevel0);
}
if (se->nEncodings < MAX_ENCODINGS && requestQualityLevel) {
if (client->appData.qualityLevel < 0 || client->appData.qualityLevel > 9)
client->appData.qualityLevel = 5;
encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.qualityLevel +
rfbEncodingQualityLevel0);
}
}
else {
if (SameMachine(client->sock)) {
/* TODO:
if (!tunnelSpecified) {
*/
rfbClientLog("Same machine: preferring raw encoding\n");
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRaw);
/*
} else {
rfbClientLog("Tunneling active: preferring tight encoding\n");
}
*/
}
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCopyRect);
#ifdef LIBVNCSERVER_HAVE_LIBZ
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingTight);
requestLastRectEncoding = TRUE;
#endif
#endif
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingHextile);
#ifdef LIBVNCSERVER_HAVE_LIBZ
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZlib);
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZRLE);
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZYWRLE);
#endif
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltra);
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltraZip);
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCoRRE);
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRRE);
if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.compressLevel +
rfbEncodingCompressLevel0);
} else /* if (!tunnelSpecified) */ {
/* If -tunnel option was provided, we assume that server machine is
not in the local network so we use default compression level for
tight encoding instead of fast compression. Thus we are
requesting level 1 compression only if tunneling is not used. */
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCompressLevel1);
}
if (client->appData.enableJPEG) {
if (client->appData.qualityLevel < 0 || client->appData.qualityLevel > 9)
client->appData.qualityLevel = 5;
encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.qualityLevel +
rfbEncodingQualityLevel0);
}
}
/* Remote Cursor Support (local to viewer) */
if (client->appData.useRemoteCursor) {
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingXCursor);
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRichCursor);
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingPointerPos);
}
/* Keyboard State Encodings */
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingKeyboardLedState);
/* New Frame Buffer Size */
if (se->nEncodings < MAX_ENCODINGS && client->canHandleNewFBSize)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingNewFBSize);
/* Last Rect */
if (se->nEncodings < MAX_ENCODINGS && requestLastRectEncoding)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingLastRect);
/* Server Capabilities */
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingSupportedMessages);
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingSupportedEncodings);
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingServerIdentity);
/* xvp */
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingXvp);
/* client extensions */
for(e = rfbClientExtensions; e; e = e->next)
if(e->encodings) {
int* enc;
for(enc = e->encodings; *enc; enc++)
if(se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(*enc);
}
len = sz_rfbSetEncodingsMsg + se->nEncodings * 4;
se->nEncodings = rfbClientSwap16IfLE(se->nEncodings);
if (!WriteToRFBServer(client, buf, len)) return FALSE;
return TRUE;
}
/*
* SendIncrementalFramebufferUpdateRequest.
*/
rfbBool
SendIncrementalFramebufferUpdateRequest(rfbClient* client)
{
return SendFramebufferUpdateRequest(client,
client->updateRect.x, client->updateRect.y,
client->updateRect.w, client->updateRect.h, TRUE);
}
/*
* SendFramebufferUpdateRequest.
*/
rfbBool
SendFramebufferUpdateRequest(rfbClient* client, int x, int y, int w, int h, rfbBool incremental)
{
rfbFramebufferUpdateRequestMsg fur;
if (!SupportsClient2Server(client, rfbFramebufferUpdateRequest)) return TRUE;
fur.type = rfbFramebufferUpdateRequest;
fur.incremental = incremental ? 1 : 0;
fur.x = rfbClientSwap16IfLE(x);
fur.y = rfbClientSwap16IfLE(y);
fur.w = rfbClientSwap16IfLE(w);
fur.h = rfbClientSwap16IfLE(h);
if (!WriteToRFBServer(client, (char *)&fur, sz_rfbFramebufferUpdateRequestMsg))
return FALSE;
return TRUE;
}
/*
* SendScaleSetting.
*/
rfbBool
SendScaleSetting(rfbClient* client,int scaleSetting)
{
rfbSetScaleMsg ssm;
ssm.scale = scaleSetting;
ssm.pad = 0;
/* favor UltraVNC SetScale if both are supported */
if (SupportsClient2Server(client, rfbSetScale)) {
ssm.type = rfbSetScale;
if (!WriteToRFBServer(client, (char *)&ssm, sz_rfbSetScaleMsg))
return FALSE;
}
if (SupportsClient2Server(client, rfbPalmVNCSetScaleFactor)) {
ssm.type = rfbPalmVNCSetScaleFactor;
if (!WriteToRFBServer(client, (char *)&ssm, sz_rfbSetScaleMsg))
return FALSE;
}
return TRUE;
}
/*
* TextChatFunctions (UltraVNC)
* Extremely bandwidth friendly method of communicating with a user
* (Think HelpDesk type applications)
*/
rfbBool TextChatSend(rfbClient* client, char *text)
{
rfbTextChatMsg chat;
int count = strlen(text);
if (!SupportsClient2Server(client, rfbTextChat)) return TRUE;
chat.type = rfbTextChat;
chat.pad1 = 0;
chat.pad2 = 0;
chat.length = (uint32_t)count;
chat.length = rfbClientSwap32IfLE(chat.length);
if (!WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg))
return FALSE;
if (count>0) {
if (!WriteToRFBServer(client, text, count))
return FALSE;
}
return TRUE;
}
rfbBool TextChatOpen(rfbClient* client)
{
rfbTextChatMsg chat;
if (!SupportsClient2Server(client, rfbTextChat)) return TRUE;
chat.type = rfbTextChat;
chat.pad1 = 0;
chat.pad2 = 0;
chat.length = rfbClientSwap32IfLE(rfbTextChatOpen);
return (WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg) ? TRUE : FALSE);
}
rfbBool TextChatClose(rfbClient* client)
{
rfbTextChatMsg chat;
if (!SupportsClient2Server(client, rfbTextChat)) return TRUE;
chat.type = rfbTextChat;
chat.pad1 = 0;
chat.pad2 = 0;
chat.length = rfbClientSwap32IfLE(rfbTextChatClose);
return (WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg) ? TRUE : FALSE);
}
rfbBool TextChatFinish(rfbClient* client)
{
rfbTextChatMsg chat;
if (!SupportsClient2Server(client, rfbTextChat)) return TRUE;
chat.type = rfbTextChat;
chat.pad1 = 0;
chat.pad2 = 0;
chat.length = rfbClientSwap32IfLE(rfbTextChatFinished);
return (WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg) ? TRUE : FALSE);
}
/*
* UltraVNC Server Input Disable
* Apparently, the remote client can *prevent* the local user from interacting with the display
* I would think this is extremely helpful when used in a HelpDesk situation
*/
rfbBool PermitServerInput(rfbClient* client, int enabled)
{
rfbSetServerInputMsg msg;
if (!SupportsClient2Server(client, rfbSetServerInput)) return TRUE;
/* enabled==1, then server input from local keyboard is disabled */
msg.type = rfbSetServerInput;
msg.status = (enabled ? 1 : 0);
msg.pad = 0;
return (WriteToRFBServer(client, (char *)&msg, sz_rfbSetServerInputMsg) ? TRUE : FALSE);
}
/*
* send xvp client message
* A client supporting the xvp extension sends this to request that the server initiate
* a clean shutdown, clean reboot or abrupt reset of the system whose framebuffer the
* client is displaying.
*
* only version 1 is defined in the protocol specs
*
* possible values for code are:
* rfbXvp_Shutdown
* rfbXvp_Reboot
* rfbXvp_Reset
*/
rfbBool SendXvpMsg(rfbClient* client, uint8_t version, uint8_t code)
{
rfbXvpMsg xvp;
if (!SupportsClient2Server(client, rfbXvp)) return TRUE;
xvp.type = rfbXvp;
xvp.pad = 0;
xvp.version = version;
xvp.code = code;
if (!WriteToRFBServer(client, (char *)&xvp, sz_rfbXvpMsg))
return FALSE;
return TRUE;
}
/*
* SendPointerEvent.
*/
rfbBool
SendPointerEvent(rfbClient* client,int x, int y, int buttonMask)
{
rfbPointerEventMsg pe;
if (!SupportsClient2Server(client, rfbPointerEvent)) return TRUE;
pe.type = rfbPointerEvent;
pe.buttonMask = buttonMask;
if (x < 0) x = 0;
if (y < 0) y = 0;
pe.x = rfbClientSwap16IfLE(x);
pe.y = rfbClientSwap16IfLE(y);
return WriteToRFBServer(client, (char *)&pe, sz_rfbPointerEventMsg);
}
/*
* SendKeyEvent.
*/
rfbBool
SendKeyEvent(rfbClient* client, uint32_t key, rfbBool down)
{
rfbKeyEventMsg ke;
if (!SupportsClient2Server(client, rfbKeyEvent)) return TRUE;
memset(&ke, 0, sizeof(ke));
ke.type = rfbKeyEvent;
ke.down = down ? 1 : 0;
ke.key = rfbClientSwap32IfLE(key);
return WriteToRFBServer(client, (char *)&ke, sz_rfbKeyEventMsg);
}
/*
* SendClientCutText.
*/
rfbBool
SendClientCutText(rfbClient* client, char *str, int len)
{
rfbClientCutTextMsg cct;
if (!SupportsClient2Server(client, rfbClientCutText)) return TRUE;
memset(&cct, 0, sizeof(cct));
cct.type = rfbClientCutText;
cct.length = rfbClientSwap32IfLE(len);
return (WriteToRFBServer(client, (char *)&cct, sz_rfbClientCutTextMsg) &&
WriteToRFBServer(client, str, len));
}
/*
* HandleRFBServerMessage.
*/
rfbBool
HandleRFBServerMessage(rfbClient* client)
{
rfbServerToClientMsg msg;
if (client->serverPort==-1)
client->vncRec->readTimestamp = TRUE;
if (!ReadFromRFBServer(client, (char *)&msg, 1))
return FALSE;
switch (msg.type) {
case rfbSetColourMapEntries:
{
/* TODO:
int i;
uint16_t rgb[3];
XColor xc;
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbSetColourMapEntriesMsg - 1))
return FALSE;
msg.scme.firstColour = rfbClientSwap16IfLE(msg.scme.firstColour);
msg.scme.nColours = rfbClientSwap16IfLE(msg.scme.nColours);
for (i = 0; i < msg.scme.nColours; i++) {
if (!ReadFromRFBServer(client, (char *)rgb, 6))
return FALSE;
xc.pixel = msg.scme.firstColour + i;
xc.red = rfbClientSwap16IfLE(rgb[0]);
xc.green = rfbClientSwap16IfLE(rgb[1]);
xc.blue = rfbClientSwap16IfLE(rgb[2]);
xc.flags = DoRed|DoGreen|DoBlue;
XStoreColor(dpy, cmap, &xc);
}
*/
break;
}
case rfbFramebufferUpdate:
{
rfbFramebufferUpdateRectHeader rect;
int linesToRead;
int bytesPerLine;
int i;
if (!ReadFromRFBServer(client, ((char *)&msg.fu) + 1,
sz_rfbFramebufferUpdateMsg - 1))
return FALSE;
msg.fu.nRects = rfbClientSwap16IfLE(msg.fu.nRects);
for (i = 0; i < msg.fu.nRects; i++) {
if (!ReadFromRFBServer(client, (char *)&rect, sz_rfbFramebufferUpdateRectHeader))
return FALSE;
rect.encoding = rfbClientSwap32IfLE(rect.encoding);
if (rect.encoding == rfbEncodingLastRect)
break;
rect.r.x = rfbClientSwap16IfLE(rect.r.x);
rect.r.y = rfbClientSwap16IfLE(rect.r.y);
rect.r.w = rfbClientSwap16IfLE(rect.r.w);
rect.r.h = rfbClientSwap16IfLE(rect.r.h);
if (rect.encoding == rfbEncodingXCursor ||
rect.encoding == rfbEncodingRichCursor) {
if (!HandleCursorShape(client,
rect.r.x, rect.r.y, rect.r.w, rect.r.h,
rect.encoding)) {
return FALSE;
}
continue;
}
if (rect.encoding == rfbEncodingPointerPos) {
if (!client->HandleCursorPos(client,rect.r.x, rect.r.y)) {
return FALSE;
}
continue;
}
if (rect.encoding == rfbEncodingKeyboardLedState) {
/* OK! We have received a keyboard state message!!! */
client->KeyboardLedStateEnabled = 1;
if (client->HandleKeyboardLedState!=NULL)
client->HandleKeyboardLedState(client, rect.r.x, 0);
/* stash it for the future */
client->CurrentKeyboardLedState = rect.r.x;
continue;
}
if (rect.encoding == rfbEncodingNewFBSize) {
client->width = rect.r.w;
client->height = rect.r.h;
client->updateRect.x = client->updateRect.y = 0;
client->updateRect.w = client->width;
client->updateRect.h = client->height;
if (!client->MallocFrameBuffer(client))
return FALSE;
SendFramebufferUpdateRequest(client, 0, 0, rect.r.w, rect.r.h, FALSE);
rfbClientLog("Got new framebuffer size: %dx%d\n", rect.r.w, rect.r.h);
continue;
}
/* rect.r.w=byte count */
if (rect.encoding == rfbEncodingSupportedMessages) {
int loop;
if (!ReadFromRFBServer(client, (char *)&client->supportedMessages, sz_rfbSupportedMessages))
return FALSE;
/* msgs is two sets of bit flags of supported messages client2server[] and server2client[] */
/* currently ignored by this library */
rfbClientLog("client2server supported messages (bit flags)\n");
for (loop=0;loop<32;loop+=8)
rfbClientLog("%02X: %04x %04x %04x %04x - %04x %04x %04x %04x\n", loop,
client->supportedMessages.client2server[loop], client->supportedMessages.client2server[loop+1],
client->supportedMessages.client2server[loop+2], client->supportedMessages.client2server[loop+3],
client->supportedMessages.client2server[loop+4], client->supportedMessages.client2server[loop+5],
client->supportedMessages.client2server[loop+6], client->supportedMessages.client2server[loop+7]);
rfbClientLog("server2client supported messages (bit flags)\n");
for (loop=0;loop<32;loop+=8)
rfbClientLog("%02X: %04x %04x %04x %04x - %04x %04x %04x %04x\n", loop,
client->supportedMessages.server2client[loop], client->supportedMessages.server2client[loop+1],
client->supportedMessages.server2client[loop+2], client->supportedMessages.server2client[loop+3],
client->supportedMessages.server2client[loop+4], client->supportedMessages.server2client[loop+5],
client->supportedMessages.server2client[loop+6], client->supportedMessages.server2client[loop+7]);
continue;
}
/* rect.r.w=byte count, rect.r.h=# of encodings */
if (rect.encoding == rfbEncodingSupportedEncodings) {
char *buffer;
buffer = malloc(rect.r.w);
if (!ReadFromRFBServer(client, buffer, rect.r.w))
{
free(buffer);
return FALSE;
}
/* buffer now contains rect.r.h # of uint32_t encodings that the server supports */
/* currently ignored by this library */
free(buffer);
continue;
}
/* rect.r.w=byte count */
if (rect.encoding == rfbEncodingServerIdentity) {
char *buffer;
buffer = malloc(rect.r.w+1);
if (!ReadFromRFBServer(client, buffer, rect.r.w))
{
free(buffer);
return FALSE;
}
buffer[rect.r.w]=0; /* null terminate, just in case */
rfbClientLog("Connected to Server \"%s\"\n", buffer);
free(buffer);
continue;
}
/* rfbEncodingUltraZip is a collection of subrects. x = # of subrects, and h is always 0 */
if (rect.encoding != rfbEncodingUltraZip)
{
if ((rect.r.x + rect.r.w > client->width) ||
(rect.r.y + rect.r.h > client->height))
{
rfbClientLog("Rect too large: %dx%d at (%d, %d)\n",
rect.r.w, rect.r.h, rect.r.x, rect.r.y);
return FALSE;
}
/* UltraVNC with scaling, will send rectangles with a zero W or H
*
if ((rect.encoding != rfbEncodingTight) &&
(rect.r.h * rect.r.w == 0))
{
rfbClientLog("Zero size rect - ignoring (encoding=%d (0x%08x) %dx, %dy, %dw, %dh)\n", rect.encoding, rect.encoding, rect.r.x, rect.r.y, rect.r.w, rect.r.h);
continue;
}
*/
/* If RichCursor encoding is used, we should prevent collisions
between framebuffer updates and cursor drawing operations. */
client->SoftCursorLockArea(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h);
}
switch (rect.encoding) {
case rfbEncodingRaw: {
int y=rect.r.y, h=rect.r.h;
bytesPerLine = rect.r.w * client->format.bitsPerPixel / 8;
/* RealVNC 4.x-5.x on OSX can induce bytesPerLine==0,
usually during GPU accel. */
/* Regardless of cause, do not divide by zero. */
linesToRead = bytesPerLine ? (RFB_BUFFER_SIZE / bytesPerLine) : 0;
while (linesToRead && h > 0) {
if (linesToRead > h)
linesToRead = h;
if (!ReadFromRFBServer(client, client->buffer,bytesPerLine * linesToRead))
return FALSE;
client->GotBitmap(client, (uint8_t *)client->buffer,
rect.r.x, y, rect.r.w,linesToRead);
h -= linesToRead;
y += linesToRead;
}
break;
}
case rfbEncodingCopyRect:
{
rfbCopyRect cr;
if (!ReadFromRFBServer(client, (char *)&cr, sz_rfbCopyRect))
return FALSE;
cr.srcX = rfbClientSwap16IfLE(cr.srcX);
cr.srcY = rfbClientSwap16IfLE(cr.srcY);
/* If RichCursor encoding is used, we should extend our
"cursor lock area" (previously set to destination
rectangle) to the source rectangle as well. */
client->SoftCursorLockArea(client,
cr.srcX, cr.srcY, rect.r.w, rect.r.h);
client->GotCopyRect(client, cr.srcX, cr.srcY, rect.r.w, rect.r.h,
rect.r.x, rect.r.y);
break;
}
case rfbEncodingRRE:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleRRE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleRRE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleRRE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingCoRRE:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleCoRRE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleCoRRE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleCoRRE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingHextile:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleHextile8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleHextile16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleHextile32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingUltra:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleUltra8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleUltra16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleUltra32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingUltraZip:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleUltraZip8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleUltraZip16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleUltraZip32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingTRLE:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleTRLE8(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
break;
case 16:
if (client->si.format.greenMax > 0x1F) {
if (!HandleTRLE16(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
} else {
if (!HandleTRLE15(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
}
break;
case 32: {
uint32_t maxColor =
(client->format.redMax << client->format.redShift) |
(client->format.greenMax << client->format.greenShift) |
(client->format.blueMax << client->format.blueShift);
if ((client->format.bigEndian && (maxColor & 0xff) == 0) ||
(!client->format.bigEndian && (maxColor & 0xff000000) == 0)) {
if (!HandleTRLE24(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
} else if (!client->format.bigEndian && (maxColor & 0xff) == 0) {
if (!HandleTRLE24Up(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
} else if (client->format.bigEndian && (maxColor & 0xff000000) == 0) {
if (!HandleTRLE24Down(client, rect.r.x, rect.r.y, rect.r.w,
rect.r.h))
return FALSE;
} else if (!HandleTRLE32(client, rect.r.x, rect.r.y, rect.r.w,
rect.r.h))
return FALSE;
break;
}
}
break;
}
#ifdef LIBVNCSERVER_HAVE_LIBZ
case rfbEncodingZlib:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleZlib8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleZlib16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleZlib32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
case rfbEncodingTight:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleTight8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleTight16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleTight32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
#endif
case rfbEncodingZRLE:
/* Fail safe for ZYWRLE unsupport VNC server. */
client->appData.qualityLevel = 9;
/* fall through */
case rfbEncodingZYWRLE:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleZRLE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (client->si.format.greenMax > 0x1F) {
if (!HandleZRLE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else {
if (!HandleZRLE15(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
}
break;
case 32:
{
uint32_t maxColor=(client->format.redMax<<client->format.redShift)|
(client->format.greenMax<<client->format.greenShift)|
(client->format.blueMax<<client->format.blueShift);
if ((client->format.bigEndian && (maxColor&0xff)==0) ||
(!client->format.bigEndian && (maxColor&0xff000000)==0)) {
if (!HandleZRLE24(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else if (!client->format.bigEndian && (maxColor&0xff)==0) {
if (!HandleZRLE24Up(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else if (client->format.bigEndian && (maxColor&0xff000000)==0) {
if (!HandleZRLE24Down(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else if (!HandleZRLE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
}
break;
}
#endif
default:
{
rfbBool handled = FALSE;
rfbClientProtocolExtension* e;
for(e = rfbClientExtensions; !handled && e; e = e->next)
if(e->handleEncoding && e->handleEncoding(client, &rect))
handled = TRUE;
if(!handled) {
rfbClientLog("Unknown rect encoding %d\n",
(int)rect.encoding);
return FALSE;
}
}
}
/* Now we may discard "soft cursor locks". */
client->SoftCursorUnlockScreen(client);
client->GotFrameBufferUpdate(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h);
}
if (!SendIncrementalFramebufferUpdateRequest(client))
return FALSE;
if (client->FinishedFrameBufferUpdate)
client->FinishedFrameBufferUpdate(client);
break;
}
case rfbBell:
{
client->Bell(client);
break;
}
case rfbServerCutText:
{
char *buffer;
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbServerCutTextMsg - 1))
return FALSE;
msg.sct.length = rfbClientSwap32IfLE(msg.sct.length);
if (msg.sct.length > 1<<20) {
rfbClientErr("Ignoring too big cut text length sent by server: %u B > 1 MB\n", (unsigned int)msg.sct.length);
return FALSE;
}
buffer = malloc((uint64_t)msg.sct.length+1);
if (!ReadFromRFBServer(client, buffer, msg.sct.length)) {
free(buffer);
return FALSE;
}
buffer[msg.sct.length] = 0;
if (client->GotXCutText)
client->GotXCutText(client, buffer, msg.sct.length);
free(buffer);
break;
}
case rfbTextChat:
{
char *buffer=NULL;
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbTextChatMsg- 1))
return FALSE;
msg.tc.length = rfbClientSwap32IfLE(msg.sct.length);
switch(msg.tc.length) {
case rfbTextChatOpen:
rfbClientLog("Received TextChat Open\n");
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)rfbTextChatOpen, NULL);
break;
case rfbTextChatClose:
rfbClientLog("Received TextChat Close\n");
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)rfbTextChatClose, NULL);
break;
case rfbTextChatFinished:
rfbClientLog("Received TextChat Finished\n");
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)rfbTextChatFinished, NULL);
break;
default:
buffer=malloc(msg.tc.length+1);
if (!ReadFromRFBServer(client, buffer, msg.tc.length))
{
free(buffer);
return FALSE;
}
/* Null Terminate <just in case> */
buffer[msg.tc.length]=0;
rfbClientLog("Received TextChat \"%s\"\n", buffer);
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)msg.tc.length, buffer);
free(buffer);
break;
}
break;
}
case rfbXvp:
{
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbXvpMsg -1))
return FALSE;
SetClient2Server(client, rfbXvp);
/* technically, we only care what we can *send* to the server
* but, we set Server2Client Just in case it ever becomes useful
*/
SetServer2Client(client, rfbXvp);
if(client->HandleXvpMsg)
client->HandleXvpMsg(client, msg.xvp.version, msg.xvp.code);
break;
}
case rfbResizeFrameBuffer:
{
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbResizeFrameBufferMsg -1))
return FALSE;
client->width = rfbClientSwap16IfLE(msg.rsfb.framebufferWidth);
client->height = rfbClientSwap16IfLE(msg.rsfb.framebufferHeigth);
client->updateRect.x = client->updateRect.y = 0;
client->updateRect.w = client->width;
client->updateRect.h = client->height;
if (!client->MallocFrameBuffer(client))
return FALSE;
SendFramebufferUpdateRequest(client, 0, 0, client->width, client->height, FALSE);
rfbClientLog("Got new framebuffer size: %dx%d\n", client->width, client->height);
break;
}
case rfbPalmVNCReSizeFrameBuffer:
{
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbPalmVNCReSizeFrameBufferMsg -1))
return FALSE;
client->width = rfbClientSwap16IfLE(msg.prsfb.buffer_w);
client->height = rfbClientSwap16IfLE(msg.prsfb.buffer_h);
client->updateRect.x = client->updateRect.y = 0;
client->updateRect.w = client->width;
client->updateRect.h = client->height;
if (!client->MallocFrameBuffer(client))
return FALSE;
SendFramebufferUpdateRequest(client, 0, 0, client->width, client->height, FALSE);
rfbClientLog("Got new framebuffer size: %dx%d\n", client->width, client->height);
break;
}
default:
{
rfbBool handled = FALSE;
rfbClientProtocolExtension* e;
for(e = rfbClientExtensions; !handled && e; e = e->next)
if(e->handleMessage && e->handleMessage(client, &msg))
handled = TRUE;
if(!handled) {
char buffer[256];
rfbClientLog("Unknown message type %d from VNC server\n",msg.type);
ReadFromRFBServer(client, buffer, 256);
return FALSE;
}
}
}
return TRUE;
}
#define GET_PIXEL8(pix, ptr) ((pix) = *(ptr)++)
#define GET_PIXEL16(pix, ptr) (((uint8_t*)&(pix))[0] = *(ptr)++, \
((uint8_t*)&(pix))[1] = *(ptr)++)
#define GET_PIXEL32(pix, ptr) (((uint8_t*)&(pix))[0] = *(ptr)++, \
((uint8_t*)&(pix))[1] = *(ptr)++, \
((uint8_t*)&(pix))[2] = *(ptr)++, \
((uint8_t*)&(pix))[3] = *(ptr)++)
/* CONCAT2 concatenates its two arguments. CONCAT2E does the same but also
expands its arguments if they are macros */
#define CONCAT2(a,b) a##b
#define CONCAT2E(a,b) CONCAT2(a,b)
#define CONCAT3(a,b,c) a##b##c
#define CONCAT3E(a,b,c) CONCAT3(a,b,c)
#define BPP 8
#include "rre.c"
#include "corre.c"
#include "hextile.c"
#include "ultra.c"
#include "zlib.c"
#include "tight.c"
#include "trle.c"
#include "zrle.c"
#undef BPP
#define BPP 16
#include "rre.c"
#include "corre.c"
#include "hextile.c"
#include "ultra.c"
#include "zlib.c"
#include "tight.c"
#include "trle.c"
#include "zrle.c"
#define REALBPP 15
#include "trle.c"
#define REALBPP 15
#include "zrle.c"
#undef BPP
#define BPP 32
#include "rre.c"
#include "corre.c"
#include "hextile.c"
#include "ultra.c"
#include "zlib.c"
#include "tight.c"
#include "trle.c"
#include "zrle.c"
#define REALBPP 24
#include "trle.c"
#define REALBPP 24
#include "zrle.c"
#define REALBPP 24
#define UNCOMP 8
#include "trle.c"
#define REALBPP 24
#define UNCOMP 8
#include "zrle.c"
#define REALBPP 24
#define UNCOMP -8
#include "trle.c"
#define REALBPP 24
#define UNCOMP -8
#include "zrle.c"
#undef BPP
/*
* PrintPixelFormat.
*/
void
PrintPixelFormat(rfbPixelFormat *format)
{
if (format->bitsPerPixel == 1) {
rfbClientLog(" Single bit per pixel.\n");
rfbClientLog(
" %s significant bit in each byte is leftmost on the screen.\n",
(format->bigEndian ? "Most" : "Least"));
} else {
rfbClientLog(" %d bits per pixel.\n",format->bitsPerPixel);
if (format->bitsPerPixel != 8) {
rfbClientLog(" %s significant byte first in each pixel.\n",
(format->bigEndian ? "Most" : "Least"));
}
if (format->trueColour) {
rfbClientLog(" TRUE colour: max red %d green %d blue %d"
", shift red %d green %d blue %d\n",
format->redMax, format->greenMax, format->blueMax,
format->redShift, format->greenShift, format->blueShift);
} else {
rfbClientLog(" Colour map (not true colour).\n");
}
}
}
/* avoid name clashes with LibVNCServer */
#define rfbEncryptBytes rfbClientEncryptBytes
#define rfbEncryptBytes2 rfbClientEncryptBytes2
#define rfbDes rfbClientDes
#define rfbDesKey rfbClientDesKey
#define rfbUseKey rfbClientUseKey
#include "vncauth.c"
#include "d3des.c"
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_519_0 |
crossvul-cpp_data_good_158_0 | /*
* 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/.
*
* ----------------------------------------------------------------------------
* Lexer (convert JsVar strings into a series of tokens)
* ----------------------------------------------------------------------------
*/
#include "jslex.h"
JsLex *lex;
JsLex *jslSetLex(JsLex *l) {
JsLex *old = lex;
lex = l;
return old;
}
void jslCharPosFree(JslCharPos *pos) {
jsvStringIteratorFree(&pos->it);
}
JslCharPos jslCharPosClone(JslCharPos *pos) {
JslCharPos p;
p.it = jsvStringIteratorClone(&pos->it);
p.currCh = pos->currCh;
return p;
}
/// Return the next character (do not move to the next character)
static ALWAYS_INLINE char jslNextCh() {
return (char)(lex->it.ptr ? READ_FLASH_UINT8(&lex->it.ptr[lex->it.charIdx]) : 0);
}
/// Move on to the next character
static void NO_INLINE jslGetNextCh() {
lex->currCh = jslNextCh();
/** NOTE: In this next bit, we DON'T LOCK OR UNLOCK.
* The String iterator we're basing on does, so every
* time we touch the iterator we have to re-lock it
*/
lex->it.charIdx++;
if (lex->it.charIdx >= lex->it.charsInVar) {
lex->it.charIdx -= lex->it.charsInVar;
if (lex->it.var && jsvGetLastChild(lex->it.var)) {
lex->it.var = _jsvGetAddressOf(jsvGetLastChild(lex->it.var));
lex->it.ptr = &lex->it.var->varData.str[0];
lex->it.varIndex += lex->it.charsInVar;
lex->it.charsInVar = jsvGetCharactersInVar(lex->it.var);
} else {
lex->it.var = 0;
lex->it.ptr = 0;
lex->it.varIndex += lex->it.charsInVar;
lex->it.charsInVar = 0;
}
}
}
static ALWAYS_INLINE void jslTokenAppendChar(char ch) {
/* Add character to buffer but check it isn't too big.
* Also Leave ONE character at the end for null termination */
if (lex->tokenl < JSLEX_MAX_TOKEN_LENGTH-1) {
lex->token[lex->tokenl++] = ch;
}
}
static bool jslIsToken(const char *token, int startOffset) {
int i;
for (i=startOffset;i<lex->tokenl;i++) {
if (lex->token[i]!=token[i]) return false;
// if token is smaller than lex->token, there will be a null char
// which will be different from the token
}
return token[lex->tokenl] == 0; // only match if token ends now
}
typedef enum {
JSLJT_ID,
JSLJT_NUMBER,
JSLJT_STRING,
JSLJT_SINGLECHAR,
JSLJT_EXCLAMATION,
JSLJT_PLUS,
JSLJT_MINUS,
JSLJT_AND,
JSLJT_OR,
JSLJT_PERCENT,
JSLJT_STAR,
JSLJT_TOPHAT,
JSLJT_FORWARDSLASH,
JSLJT_LESSTHAN,
JSLJT_EQUAL,
JSLJT_GREATERTHAN,
} PACKED_FLAGS jslJumpTableEnum;
#define jslJumpTableStart 33 // '!' - the first handled character
#define jslJumpTableEnd 124 // '|' - the last handled character
const jslJumpTableEnum jslJumpTable[jslJumpTableEnd+1-jslJumpTableStart] = {
// 33
JSLJT_EXCLAMATION, // !
JSLJT_STRING, // "
JSLJT_SINGLECHAR, // #
JSLJT_ID, // $
JSLJT_PERCENT, // %
JSLJT_AND, // &
JSLJT_STRING, // '
JSLJT_SINGLECHAR, // (
JSLJT_SINGLECHAR, // )
JSLJT_STAR, // *
JSLJT_PLUS, // +
JSLJT_SINGLECHAR, // ,
JSLJT_MINUS, // -
JSLJT_NUMBER, // . - special :/
JSLJT_FORWARDSLASH, // /
// 48
JSLJT_NUMBER, // 0
JSLJT_NUMBER, // 1
JSLJT_NUMBER, // 2
JSLJT_NUMBER, // 3
JSLJT_NUMBER, // 4
JSLJT_NUMBER, // 5
JSLJT_NUMBER, // 6
JSLJT_NUMBER, // 7
JSLJT_NUMBER, // 8
JSLJT_NUMBER, // 9
JSLJT_SINGLECHAR, // :
JSLJT_SINGLECHAR, // ;
JSLJT_LESSTHAN, // <
JSLJT_EQUAL, // =
JSLJT_GREATERTHAN, // >
JSLJT_SINGLECHAR, // ?
// 64
JSLJT_SINGLECHAR, // @
JSLJT_ID, // A
JSLJT_ID, // B
JSLJT_ID, // C
JSLJT_ID, // D
JSLJT_ID, // E
JSLJT_ID, // F
JSLJT_ID, // G
JSLJT_ID, // H
JSLJT_ID, // I
JSLJT_ID, // J
JSLJT_ID, // K
JSLJT_ID, // L
JSLJT_ID, // M
JSLJT_ID, // N
JSLJT_ID, // O
JSLJT_ID, // P
JSLJT_ID, // Q
JSLJT_ID, // R
JSLJT_ID, // S
JSLJT_ID, // T
JSLJT_ID, // U
JSLJT_ID, // V
JSLJT_ID, // W
JSLJT_ID, // X
JSLJT_ID, // Y
JSLJT_ID, // Z
JSLJT_SINGLECHAR, // [
JSLJT_SINGLECHAR, // \ char
JSLJT_SINGLECHAR, // ]
JSLJT_TOPHAT, // ^
JSLJT_ID, // _
// 96
JSLJT_STRING, // `
JSLJT_ID, // A lowercase
JSLJT_ID, // B lowercase
JSLJT_ID, // C lowercase
JSLJT_ID, // D lowercase
JSLJT_ID, // E lowercase
JSLJT_ID, // F lowercase
JSLJT_ID, // G lowercase
JSLJT_ID, // H lowercase
JSLJT_ID, // I lowercase
JSLJT_ID, // J lowercase
JSLJT_ID, // K lowercase
JSLJT_ID, // L lowercase
JSLJT_ID, // M lowercase
JSLJT_ID, // N lowercase
JSLJT_ID, // O lowercase
JSLJT_ID, // P lowercase
JSLJT_ID, // Q lowercase
JSLJT_ID, // R lowercase
JSLJT_ID, // S lowercase
JSLJT_ID, // T lowercase
JSLJT_ID, // U lowercase
JSLJT_ID, // V lowercase
JSLJT_ID, // W lowercase
JSLJT_ID, // X lowercase
JSLJT_ID, // Y lowercase
JSLJT_ID, // Z lowercase
JSLJT_SINGLECHAR, // {
JSLJT_OR, // |
// everything past here is handled as a single char
// JSLJT_SINGLECHAR, // }
// JSLJT_SINGLECHAR, // ~
};
// handle a single char
static ALWAYS_INLINE void jslSingleChar() {
lex->tk = (unsigned char)lex->currCh;
jslGetNextCh();
}
static void jslLexString() {
char delim = lex->currCh;
lex->tokenValue = jsvNewFromEmptyString();
if (!lex->tokenValue) {
lex->tk = LEX_EOF;
return;
}
JsvStringIterator it;
jsvStringIteratorNew(&it, lex->tokenValue, 0);
// strings...
jslGetNextCh();
while (lex->currCh && lex->currCh!=delim) {
if (lex->currCh == '\\') {
jslGetNextCh();
char ch = lex->currCh;
switch (lex->currCh) {
case 'n' : ch = 0x0A; jslGetNextCh(); break;
case 'b' : ch = 0x08; jslGetNextCh(); break;
case 'f' : ch = 0x0C; jslGetNextCh(); break;
case 'r' : ch = 0x0D; jslGetNextCh(); break;
case 't' : ch = 0x09; jslGetNextCh(); break;
case 'v' : ch = 0x0B; jslGetNextCh(); break;
case 'u' :
case 'x' : { // hex digits
char buf[5] = "0x??";
if (lex->currCh == 'u') {
// We don't support unicode, so we just take the bottom 8 bits
// of the unicode character
jslGetNextCh();
jslGetNextCh();
}
jslGetNextCh();
buf[2] = lex->currCh; jslGetNextCh();
buf[3] = lex->currCh; jslGetNextCh();
ch = (char)stringToInt(buf);
} break;
default:
if (lex->currCh>='0' && lex->currCh<='7') {
// octal digits
char buf[5] = "0";
buf[1] = lex->currCh;
int n=2;
jslGetNextCh();
if (lex->currCh>='0' && lex->currCh<='7') {
buf[n++] = lex->currCh; jslGetNextCh();
if (lex->currCh>='0' && lex->currCh<='7') {
buf[n++] = lex->currCh; jslGetNextCh();
}
}
buf[n]=0;
ch = (char)stringToInt(buf);
} else {
// for anything else, just push the character through
jslGetNextCh();
}
break;
}
jslTokenAppendChar(ch);
jsvStringIteratorAppend(&it, ch);
} else if (lex->currCh=='\n' && delim!='`') {
/* Was a newline - this is now allowed
* unless we're a template string */
break;
} else {
jslTokenAppendChar(lex->currCh);
jsvStringIteratorAppend(&it, lex->currCh);
jslGetNextCh();
}
}
jsvStringIteratorFree(&it);
if (delim=='`')
lex->tk = LEX_TEMPLATE_LITERAL;
else lex->tk = LEX_STR;
// unfinished strings
if (lex->currCh!=delim)
lex->tk++; // +1 gets you to 'unfinished X'
jslGetNextCh();
}
static void jslLexRegex() {
lex->tokenValue = jsvNewFromEmptyString();
if (!lex->tokenValue) {
lex->tk = LEX_EOF;
return;
}
JsvStringIterator it;
jsvStringIteratorNew(&it, lex->tokenValue, 0);
jsvStringIteratorAppend(&it, '/');
// strings...
jslGetNextCh();
while (lex->currCh && lex->currCh!='/') {
if (lex->currCh == '\\') {
jsvStringIteratorAppend(&it, lex->currCh);
jslGetNextCh();
} else if (lex->currCh=='\n') {
/* Was a newline - this is now allowed
* unless we're a template string */
break;
}
jsvStringIteratorAppend(&it, lex->currCh);
jslGetNextCh();
}
lex->tk = LEX_REGEX;
if (lex->currCh!='/') {
lex->tk++; // +1 gets you to 'unfinished X'
} else {
jsvStringIteratorAppend(&it, '/');
jslGetNextCh();
// regex modifiers
while (lex->currCh=='g' ||
lex->currCh=='i' ||
lex->currCh=='m' ||
lex->currCh=='y' ||
lex->currCh=='u') {
jslTokenAppendChar(lex->currCh);
jsvStringIteratorAppend(&it, lex->currCh);
jslGetNextCh();
}
}
jsvStringIteratorFree(&it);
}
void jslGetNextToken() {
jslGetNextToken_start:
// Skip whitespace
while (isWhitespace(lex->currCh))
jslGetNextCh();
// Search for comments
if (lex->currCh=='/') {
// newline comments
if (jslNextCh()=='/') {
while (lex->currCh && lex->currCh!='\n') jslGetNextCh();
jslGetNextCh();
goto jslGetNextToken_start;
}
// block comments
if (jslNextCh()=='*') {
jslGetNextCh();
jslGetNextCh();
while (lex->currCh && !(lex->currCh=='*' && jslNextCh()=='/'))
jslGetNextCh();
if (!lex->currCh) {
lex->tk = LEX_UNFINISHED_COMMENT;
return; /* an unfinished multi-line comment. When in interactive console,
detect this and make sure we accept new lines */
}
jslGetNextCh();
jslGetNextCh();
goto jslGetNextToken_start;
}
}
int lastToken = lex->tk;
lex->tk = LEX_EOF;
lex->tokenl = 0; // clear token string
if (lex->tokenValue) {
jsvUnLock(lex->tokenValue);
lex->tokenValue = 0;
}
// record beginning of this token
lex->tokenLastStart = jsvStringIteratorGetIndex(&lex->tokenStart.it) - 1;
/* we don't lock here, because we know that the string itself will be locked
* because of lex->sourceVar */
lex->tokenStart.it = lex->it;
lex->tokenStart.currCh = lex->currCh;
// tokens
if (((unsigned char)lex->currCh) < jslJumpTableStart ||
((unsigned char)lex->currCh) > jslJumpTableEnd) {
// if unhandled by the jump table, just pass it through as a single character
jslSingleChar();
} else {
switch(jslJumpTable[((unsigned char)lex->currCh) - jslJumpTableStart]) {
case JSLJT_ID: {
while (isAlpha(lex->currCh) || isNumeric(lex->currCh) || lex->currCh=='$') {
jslTokenAppendChar(lex->currCh);
jslGetNextCh();
}
lex->tk = LEX_ID;
// We do fancy stuff here to reduce number of compares (hopefully GCC creates a jump table)
switch (lex->token[0]) {
case 'b': if (jslIsToken("break", 1)) lex->tk = LEX_R_BREAK;
break;
case 'c': if (jslIsToken("case", 1)) lex->tk = LEX_R_CASE;
else if (jslIsToken("catch", 1)) lex->tk = LEX_R_CATCH;
else if (jslIsToken("class", 1)) lex->tk = LEX_R_CLASS;
else if (jslIsToken("const", 1)) lex->tk = LEX_R_CONST;
else if (jslIsToken("continue", 1)) lex->tk = LEX_R_CONTINUE;
break;
case 'd': if (jslIsToken("default", 1)) lex->tk = LEX_R_DEFAULT;
else if (jslIsToken("delete", 1)) lex->tk = LEX_R_DELETE;
else if (jslIsToken("do", 1)) lex->tk = LEX_R_DO;
else if (jslIsToken("debugger", 1)) lex->tk = LEX_R_DEBUGGER;
break;
case 'e': if (jslIsToken("else", 1)) lex->tk = LEX_R_ELSE;
else if (jslIsToken("extends", 1)) lex->tk = LEX_R_EXTENDS;
break;
case 'f': if (jslIsToken("false", 1)) lex->tk = LEX_R_FALSE;
else if (jslIsToken("finally", 1)) lex->tk = LEX_R_FINALLY;
else if (jslIsToken("for", 1)) lex->tk = LEX_R_FOR;
else if (jslIsToken("function", 1)) lex->tk = LEX_R_FUNCTION;
break;
case 'i': if (jslIsToken("if", 1)) lex->tk = LEX_R_IF;
else if (jslIsToken("in", 1)) lex->tk = LEX_R_IN;
else if (jslIsToken("instanceof", 1)) lex->tk = LEX_R_INSTANCEOF;
break;
case 'l': if (jslIsToken("let", 1)) lex->tk = LEX_R_LET;
break;
case 'n': if (jslIsToken("new", 1)) lex->tk = LEX_R_NEW;
else if (jslIsToken("null", 1)) lex->tk = LEX_R_NULL;
break;
case 'r': if (jslIsToken("return", 1)) lex->tk = LEX_R_RETURN;
break;
case 's': if (jslIsToken("static", 1)) lex->tk = LEX_R_STATIC;
else if (jslIsToken("super", 1)) lex->tk = LEX_R_SUPER;
else if (jslIsToken("switch", 1)) lex->tk = LEX_R_SWITCH;
break;
case 't': if (jslIsToken("this", 1)) lex->tk = LEX_R_THIS;
else if (jslIsToken("throw", 1)) lex->tk = LEX_R_THROW;
else if (jslIsToken("true", 1)) lex->tk = LEX_R_TRUE;
else if (jslIsToken("try", 1)) lex->tk = LEX_R_TRY;
else if (jslIsToken("typeof", 1)) lex->tk = LEX_R_TYPEOF;
break;
case 'u': if (jslIsToken("undefined", 1)) lex->tk = LEX_R_UNDEFINED;
break;
case 'w': if (jslIsToken("while", 1)) lex->tk = LEX_R_WHILE;
break;
case 'v': if (jslIsToken("var", 1)) lex->tk = LEX_R_VAR;
else if (jslIsToken("void", 1)) lex->tk = LEX_R_VOID;
break;
default: break;
} break;
case JSLJT_NUMBER: {
// TODO: check numbers aren't the wrong format
bool canBeFloating = true;
if (lex->currCh=='.') {
jslGetNextCh();
if (isNumeric(lex->currCh)) {
// it is a float
lex->tk = LEX_FLOAT;
jslTokenAppendChar('.');
} else {
// it wasn't a number after all
lex->tk = '.';
break;
}
} else {
if (lex->currCh=='0') {
jslTokenAppendChar(lex->currCh);
jslGetNextCh();
if ((lex->currCh=='x' || lex->currCh=='X') ||
(lex->currCh=='b' || lex->currCh=='B') ||
(lex->currCh=='o' || lex->currCh=='O')) {
canBeFloating = false;
jslTokenAppendChar(lex->currCh); jslGetNextCh();
}
}
lex->tk = LEX_INT;
while (isNumeric(lex->currCh) || (!canBeFloating && isHexadecimal(lex->currCh))) {
jslTokenAppendChar(lex->currCh);
jslGetNextCh();
}
if (canBeFloating && lex->currCh=='.') {
lex->tk = LEX_FLOAT;
jslTokenAppendChar('.');
jslGetNextCh();
}
}
// parse fractional part
if (lex->tk == LEX_FLOAT) {
while (isNumeric(lex->currCh)) {
jslTokenAppendChar(lex->currCh);
jslGetNextCh();
}
}
// do fancy e-style floating point
if (canBeFloating && (lex->currCh=='e'||lex->currCh=='E')) {
lex->tk = LEX_FLOAT;
jslTokenAppendChar(lex->currCh); jslGetNextCh();
if (lex->currCh=='-' || lex->currCh=='+') { jslTokenAppendChar(lex->currCh); jslGetNextCh(); }
while (isNumeric(lex->currCh)) {
jslTokenAppendChar(lex->currCh); jslGetNextCh();
}
}
} break;
case JSLJT_STRING: jslLexString(); break;
case JSLJT_EXCLAMATION: jslSingleChar();
if (lex->currCh=='=') { // !=
lex->tk = LEX_NEQUAL;
jslGetNextCh();
if (lex->currCh=='=') { // !==
lex->tk = LEX_NTYPEEQUAL;
jslGetNextCh();
}
} break;
case JSLJT_PLUS: jslSingleChar();
if (lex->currCh=='=') {
lex->tk = LEX_PLUSEQUAL;
jslGetNextCh();
} else if (lex->currCh=='+') {
lex->tk = LEX_PLUSPLUS;
jslGetNextCh();
} break;
case JSLJT_MINUS: jslSingleChar();
if (lex->currCh=='=') {
lex->tk = LEX_MINUSEQUAL;
jslGetNextCh();
} else if (lex->currCh=='-') {
lex->tk = LEX_MINUSMINUS;
jslGetNextCh();
} break;
case JSLJT_AND: jslSingleChar();
if (lex->currCh=='=') {
lex->tk = LEX_ANDEQUAL;
jslGetNextCh();
} else if (lex->currCh=='&') {
lex->tk = LEX_ANDAND;
jslGetNextCh();
} break;
case JSLJT_OR: jslSingleChar();
if (lex->currCh=='=') {
lex->tk = LEX_OREQUAL;
jslGetNextCh();
} else if (lex->currCh=='|') {
lex->tk = LEX_OROR;
jslGetNextCh();
} break;
case JSLJT_TOPHAT: jslSingleChar();
if (lex->currCh=='=') {
lex->tk = LEX_XOREQUAL;
jslGetNextCh();
} break;
case JSLJT_STAR: jslSingleChar();
if (lex->currCh=='=') {
lex->tk = LEX_MULEQUAL;
jslGetNextCh();
} break;
case JSLJT_FORWARDSLASH:
// yay! JS is so awesome.
if (lastToken==LEX_EOF ||
lastToken=='!' ||
lastToken=='%' ||
lastToken=='&' ||
lastToken=='*' ||
lastToken=='+' ||
lastToken=='-' ||
lastToken=='/' ||
lastToken=='<' ||
lastToken=='=' ||
lastToken=='>' ||
lastToken=='?' ||
(lastToken>=_LEX_OPERATOR_START && lastToken<=_LEX_OPERATOR_END) ||
(lastToken>=_LEX_R_LIST_START && lastToken<=_LEX_R_LIST_END) || // keywords
lastToken==LEX_R_CASE ||
lastToken==LEX_R_NEW ||
lastToken=='[' ||
lastToken=='{' ||
lastToken=='}' ||
lastToken=='(' ||
lastToken==',' ||
lastToken==';' ||
lastToken==':' ||
lastToken==LEX_ARROW_FUNCTION) {
// EOF operator keyword case new [ { } ( , ; : =>
// phew. We're a regex
jslLexRegex();
} else {
jslSingleChar();
if (lex->currCh=='=') {
lex->tk = LEX_DIVEQUAL;
jslGetNextCh();
}
} break;
case JSLJT_PERCENT: jslSingleChar();
if (lex->currCh=='=') {
lex->tk = LEX_MODEQUAL;
jslGetNextCh();
} break;
case JSLJT_EQUAL: jslSingleChar();
if (lex->currCh=='=') { // ==
lex->tk = LEX_EQUAL;
jslGetNextCh();
if (lex->currCh=='=') { // ===
lex->tk = LEX_TYPEEQUAL;
jslGetNextCh();
}
} else if (lex->currCh=='>') { // =>
lex->tk = LEX_ARROW_FUNCTION;
jslGetNextCh();
} break;
case JSLJT_LESSTHAN: jslSingleChar();
if (lex->currCh=='=') { // <=
lex->tk = LEX_LEQUAL;
jslGetNextCh();
} else if (lex->currCh=='<') { // <<
lex->tk = LEX_LSHIFT;
jslGetNextCh();
if (lex->currCh=='=') { // <<=
lex->tk = LEX_LSHIFTEQUAL;
jslGetNextCh();
}
} break;
case JSLJT_GREATERTHAN: jslSingleChar();
if (lex->currCh=='=') { // >=
lex->tk = LEX_GEQUAL;
jslGetNextCh();
} else if (lex->currCh=='>') { // >>
lex->tk = LEX_RSHIFT;
jslGetNextCh();
if (lex->currCh=='=') { // >>=
lex->tk = LEX_RSHIFTEQUAL;
jslGetNextCh();
} else if (lex->currCh=='>') { // >>>
jslGetNextCh();
if (lex->currCh=='=') { // >>>=
lex->tk = LEX_RSHIFTUNSIGNEDEQUAL;
jslGetNextCh();
} else {
lex->tk = LEX_RSHIFTUNSIGNED;
}
}
} break;
case JSLJT_SINGLECHAR: jslSingleChar(); break;
default: assert(0);break;
}
}
}
}
static ALWAYS_INLINE void jslPreload() {
// set up..
jslGetNextCh();
jslGetNextToken();
}
void jslInit(JsVar *var) {
lex->sourceVar = jsvLockAgain(var);
// reset stuff
lex->tk = 0;
lex->tokenStart.it.var = 0;
lex->tokenStart.currCh = 0;
lex->tokenLastStart = 0;
lex->tokenl = 0;
lex->tokenValue = 0;
lex->lineNumberOffset = 0;
// set up iterator
jsvStringIteratorNew(&lex->it, lex->sourceVar, 0);
jsvUnLock(lex->it.var); // see jslGetNextCh
jslPreload();
}
void jslKill() {
lex->tk = LEX_EOF; // safety ;)
if (lex->it.var) jsvLockAgain(lex->it.var); // see jslGetNextCh
jsvStringIteratorFree(&lex->it);
if (lex->tokenValue) {
jsvUnLock(lex->tokenValue);
lex->tokenValue = 0;
}
jsvUnLock(lex->sourceVar);
lex->tokenStart.it.var = 0;
lex->tokenStart.currCh = 0;
}
void jslSeekTo(size_t seekToChar) {
if (lex->it.var) jsvLockAgain(lex->it.var); // see jslGetNextCh
jsvStringIteratorFree(&lex->it);
jsvStringIteratorNew(&lex->it, lex->sourceVar, seekToChar);
jsvUnLock(lex->it.var); // see jslGetNextCh
lex->tokenStart.it.var = 0;
lex->tokenStart.currCh = 0;
jslPreload();
}
void jslSeekToP(JslCharPos *seekToChar) {
if (lex->it.var) jsvLockAgain(lex->it.var); // see jslGetNextCh
jsvStringIteratorFree(&lex->it);
lex->it = jsvStringIteratorClone(&seekToChar->it);
jsvUnLock(lex->it.var); // see jslGetNextCh
lex->currCh = seekToChar->currCh;
lex->tokenStart.it.var = 0;
lex->tokenStart.currCh = 0;
jslGetNextToken();
}
void jslReset() {
jslSeekTo(0);
}
/** When printing out a function, with pretokenise a
* character could end up being a special token. This
* handles that case. */
void jslFunctionCharAsString(unsigned char ch, char *str, size_t len) {
if (ch >= LEX_TOKEN_START) {
jslTokenAsString(ch, str, len);
} else {
str[0] = (char)ch;
str[1] = 0;
}
}
void jslTokenAsString(int token, char *str, size_t len) {
assert(len>28); // size of largest string
// see JS_ERROR_TOKEN_BUF_SIZE
if (token>32 && token<128) {
assert(len>=4);
str[0] = '\'';
str[1] = (char)token;
str[2] = '\'';
str[3] = 0;
return;
}
switch (token) {
case LEX_EOF : strcpy(str, "EOF"); return;
case LEX_ID : strcpy(str, "ID"); return;
case LEX_INT : strcpy(str, "INT"); return;
case LEX_FLOAT : strcpy(str, "FLOAT"); return;
case LEX_STR : strcpy(str, "STRING"); return;
case LEX_UNFINISHED_STR : strcpy(str, "UNFINISHED STRING"); return;
case LEX_TEMPLATE_LITERAL : strcpy(str, "TEMPLATE LITERAL"); return;
case LEX_UNFINISHED_TEMPLATE_LITERAL : strcpy(str, "UNFINISHED TEMPLATE LITERAL"); return;
case LEX_REGEX : strcpy(str, "REGEX"); return;
case LEX_UNFINISHED_REGEX : strcpy(str, "UNFINISHED REGEX"); return;
case LEX_UNFINISHED_COMMENT : strcpy(str, "UNFINISHED COMMENT"); return;
}
if (token>=_LEX_OPERATOR_START && token<_LEX_R_LIST_END) {
const char tokenNames[] =
/* LEX_EQUAL : */ "==\0"
/* LEX_TYPEEQUAL : */ "===\0"
/* LEX_NEQUAL : */ "!=\0"
/* LEX_NTYPEEQUAL : */ "!==\0"
/* LEX_LEQUAL : */ "<=\0"
/* LEX_LSHIFT : */ "<<\0"
/* LEX_LSHIFTEQUAL : */ "<<=\0"
/* LEX_GEQUAL : */ ">=\0"
/* LEX_RSHIFT : */ ">>\0"
/* LEX_RSHIFTUNSIGNED */ ">>>\0"
/* LEX_RSHIFTEQUAL : */ ">>=\0"
/* LEX_RSHIFTUNSIGNEDEQUAL */ ">>>=\0"
/* LEX_PLUSEQUAL : */ "+=\0"
/* LEX_MINUSEQUAL : */ "-=\0"
/* LEX_PLUSPLUS : */ "++\0"
/* LEX_MINUSMINUS */ "--\0"
/* LEX_MULEQUAL : */ "*=\0"
/* LEX_DIVEQUAL : */ "/=\0"
/* LEX_MODEQUAL : */ "%=\0"
/* LEX_ANDEQUAL : */ "&=\0"
/* LEX_ANDAND : */ "&&\0"
/* LEX_OREQUAL : */ "|=\0"
/* LEX_OROR : */ "||\0"
/* LEX_XOREQUAL : */ "^=\0"
/* LEX_ARROW_FUNCTION */ "=>\0"
// reserved words
/*LEX_R_IF : */ "if\0"
/*LEX_R_ELSE : */ "else\0"
/*LEX_R_DO : */ "do\0"
/*LEX_R_WHILE : */ "while\0"
/*LEX_R_FOR : */ "for\0"
/*LEX_R_BREAK : */ "return\0"
/*LEX_R_CONTINUE */ "continue\0"
/*LEX_R_FUNCTION */ "function\0"
/*LEX_R_RETURN */ "return\0"
/*LEX_R_VAR : */ "var\0"
/*LEX_R_LET : */ "let\0"
/*LEX_R_CONST : */ "const\0"
/*LEX_R_THIS : */ "this\0"
/*LEX_R_THROW : */ "throw\0"
/*LEX_R_TRY : */ "try\0"
/*LEX_R_CATCH : */ "catch\0"
/*LEX_R_FINALLY : */ "finally\0"
/*LEX_R_TRUE : */ "true\0"
/*LEX_R_FALSE : */ "false\0"
/*LEX_R_NULL : */ "null\0"
/*LEX_R_UNDEFINED */ "undefined\0"
/*LEX_R_NEW : */ "new\0"
/*LEX_R_IN : */ "in\0"
/*LEX_R_INSTANCEOF */ "instanceof\0"
/*LEX_R_SWITCH */ "switch\0"
/*LEX_R_CASE */ "case\0"
/*LEX_R_DEFAULT */ "default\0"
/*LEX_R_DELETE */ "delete\0"
/*LEX_R_TYPEOF : */ "typeof\0"
/*LEX_R_VOID : */ "void\0"
/*LEX_R_DEBUGGER : */ "debugger\0"
/*LEX_R_CLASS : */ "class\0"
/*LEX_R_EXTENDS : */ "extends\0"
/*LEX_R_SUPER : */ "super\0"
/*LEX_R_STATIC : */ "static\0"
;
unsigned int p = 0;
int n = token-_LEX_OPERATOR_START;
while (n>0 && p<sizeof(tokenNames)) {
while (tokenNames[p] && p<sizeof(tokenNames)) p++;
p++; // skip the zero
n--; // next token
}
assert(n==0);
strcpy(str, &tokenNames[p]);
return;
}
espruino_snprintf(str, len, "?[%d]", token);
}
void jslGetTokenString(char *str, size_t len) {
if (lex->tk == LEX_ID) {
espruino_snprintf(str, len, "ID:%s", jslGetTokenValueAsString());
} else if (lex->tk == LEX_STR) {
espruino_snprintf(str, len, "String:'%s'", jslGetTokenValueAsString());
} else
jslTokenAsString(lex->tk, str, len);
}
char *jslGetTokenValueAsString() {
assert(lex->tokenl < JSLEX_MAX_TOKEN_LENGTH);
lex->token[lex->tokenl] = 0; // add final null
return lex->token;
}
int jslGetTokenLength() {
return lex->tokenl;
}
JsVar *jslGetTokenValueAsVar() {
if (lex->tokenValue) {
return jsvLockAgain(lex->tokenValue);
} else {
assert(lex->tokenl < JSLEX_MAX_TOKEN_LENGTH);
lex->token[lex->tokenl] = 0; // add final null
return jsvNewFromString(lex->token);
}
}
bool jslIsIDOrReservedWord() {
return lex->tk == LEX_ID ||
(lex->tk >= _LEX_R_LIST_START && lex->tk <= _LEX_R_LIST_END);
}
/* Match failed - report error message */
static void jslMatchError(int expected_tk) {
char gotStr[30];
char expStr[30];
jslGetTokenString(gotStr, sizeof(gotStr));
jslTokenAsString(expected_tk, expStr, sizeof(expStr));
size_t oldPos = lex->tokenLastStart;
lex->tokenLastStart = jsvStringIteratorGetIndex(&lex->tokenStart.it)-1;
jsExceptionHere(JSET_SYNTAXERROR, "Got %s expected %s", gotStr, expStr);
lex->tokenLastStart = oldPos;
// Sod it, skip this token anyway - stops us looping
jslGetNextToken();
}
/// Match, and return true on success, false on failure
bool jslMatch(int expected_tk) {
if (lex->tk != expected_tk) {
jslMatchError(expected_tk);
return false;
}
jslGetNextToken();
return true;
}
JsVar *jslNewTokenisedStringFromLexer(JslCharPos *charFrom, size_t charTo) {
// New method - tokenise functions
// save old lex
JsLex *oldLex = lex;
JsLex newLex;
lex = &newLex;
// work out length
size_t length = 0;
jslInit(oldLex->sourceVar);
jslSeekToP(charFrom);
int lastTk = LEX_EOF;
while (lex->tk!=LEX_EOF && jsvStringIteratorGetIndex(&lex->it)<=charTo+1) {
if ((lex->tk==LEX_ID || lex->tk==LEX_FLOAT || lex->tk==LEX_INT) &&
( lastTk==LEX_ID || lastTk==LEX_FLOAT || lastTk==LEX_INT)) {
jsExceptionHere(JSET_SYNTAXERROR, "ID/number following ID/number isn't valid JS");
length = 0;
break;
}
if (lex->tk==LEX_ID ||
lex->tk==LEX_INT ||
lex->tk==LEX_FLOAT ||
lex->tk==LEX_STR ||
lex->tk==LEX_TEMPLATE_LITERAL) {
length += jsvStringIteratorGetIndex(&lex->it)-jsvStringIteratorGetIndex(&lex->tokenStart.it);
} else {
length++;
}
lastTk = lex->tk;
jslGetNextToken();
}
// Try and create a flat string first
JsVar *var = jsvNewStringOfLength((unsigned int)length, NULL);
if (var) { // out of memory
JsvStringIterator dstit;
jsvStringIteratorNew(&dstit, var, 0);
// now start appending
jslSeekToP(charFrom);
while (lex->tk!=LEX_EOF && jsvStringIteratorGetIndex(&lex->it)<=charTo+1) {
if (lex->tk==LEX_ID ||
lex->tk==LEX_INT ||
lex->tk==LEX_FLOAT ||
lex->tk==LEX_STR ||
lex->tk==LEX_TEMPLATE_LITERAL) {
jsvStringIteratorSetCharAndNext(&dstit, lex->tokenStart.currCh);
JsvStringIterator it = jsvStringIteratorClone(&lex->tokenStart.it);
while (jsvStringIteratorGetIndex(&it)+1 < jsvStringIteratorGetIndex(&lex->it)) {
jsvStringIteratorSetCharAndNext(&dstit, jsvStringIteratorGetChar(&it));
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
} else {
jsvStringIteratorSetCharAndNext(&dstit, (char)lex->tk);
}
lastTk = lex->tk;
jslGetNextToken();
}
jsvStringIteratorFree(&dstit);
}
// restore lex
jslKill();
lex = oldLex;
return var;
}
JsVar *jslNewStringFromLexer(JslCharPos *charFrom, size_t charTo) {
// Original method - just copy it verbatim
size_t maxLength = charTo + 1 - jsvStringIteratorGetIndex(&charFrom->it);
assert(maxLength>0); // will fail if 0
// Try and create a flat string first
JsVar *var = 0;
if (maxLength > JSV_FLAT_STRING_BREAK_EVEN) {
var = jsvNewFlatStringOfLength((unsigned int)maxLength);
if (var) {
// Flat string
char *flatPtr = jsvGetFlatStringPointer(var);
*(flatPtr++) = charFrom->currCh;
JsvStringIterator it = jsvStringIteratorClone(&charFrom->it);
while (jsvStringIteratorHasChar(&it) && (--maxLength>0)) {
*(flatPtr++) = jsvStringIteratorGetChar(&it);
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
return var;
}
}
// Non-flat string...
var = jsvNewFromEmptyString();
if (!var) { // out of memory
return 0;
}
//jsvAppendStringVar(var, lex->sourceVar, charFrom->it->index, (int)(charTo-charFrom));
JsVar *block = jsvLockAgain(var);
block->varData.str[0] = charFrom->currCh;
size_t blockChars = 1;
size_t l = maxLength;
// now start appending
JsvStringIterator it = jsvStringIteratorClone(&charFrom->it);
while (jsvStringIteratorHasChar(&it) && (--maxLength>0)) {
char ch = jsvStringIteratorGetChar(&it);
if (blockChars >= jsvGetMaxCharactersInVar(block)) {
jsvSetCharactersInVar(block, blockChars);
JsVar *next = jsvNewWithFlags(JSV_STRING_EXT_0);
if (!next) break; // out of memory
// we don't ref, because StringExts are never reffed as they only have one owner (and ALWAYS have an owner)
jsvSetLastChild(block, jsvGetRef(next));
jsvUnLock(block);
block = next;
blockChars=0; // it's new, so empty
}
block->varData.str[blockChars++] = ch;
jsvStringIteratorNext(&it);
}
jsvSetCharactersInVar(block, blockChars);
jsvUnLock(block);
// Just make sure we only assert if there's a bug here. If we just ran out of memory or at end of string it's ok
assert((l == jsvGetStringLength(var)) || (jsErrorFlags&JSERR_MEMORY) || !jsvStringIteratorHasChar(&it));
jsvStringIteratorFree(&it);
return var;
}
/// Return the line number at the current character position (this isn't fast as it searches the string)
unsigned int jslGetLineNumber() {
size_t line;
size_t col;
jsvGetLineAndCol(lex->sourceVar, jsvStringIteratorGetIndex(&lex->tokenStart.it)-1, &line, &col);
return (unsigned int)line;
}
/// Do we need a space between these two characters when printing a function's text?
bool jslNeedSpaceBetween(unsigned char lastch, unsigned char ch) {
return (lastch>=_LEX_R_LIST_START || ch>=_LEX_R_LIST_START) &&
(lastch>=_LEX_R_LIST_START || isAlpha((char)lastch) || isNumeric((char)lastch)) &&
(ch>=_LEX_R_LIST_START || isAlpha((char)ch) || isNumeric((char)ch));
}
void jslPrintPosition(vcbprintf_callback user_callback, void *user_data, size_t tokenPos) {
size_t line,col;
jsvGetLineAndCol(lex->sourceVar, tokenPos, &line, &col);
if (lex->lineNumberOffset)
line += (size_t)lex->lineNumberOffset - 1;
cbprintf(user_callback, user_data, "line %d col %d\n", line, col);
}
void jslPrintTokenLineMarker(vcbprintf_callback user_callback, void *user_data, size_t tokenPos, char *prefix) {
size_t line = 1,col = 1;
jsvGetLineAndCol(lex->sourceVar, tokenPos, &line, &col);
size_t startOfLine = jsvGetIndexFromLineAndCol(lex->sourceVar, line, 1);
size_t lineLength = jsvGetCharsOnLine(lex->sourceVar, line);
size_t prefixLength = 0;
if (prefix) {
user_callback(prefix, user_data);
prefixLength = strlen(prefix);
}
if (lineLength>60 && tokenPos-startOfLine>30) {
cbprintf(user_callback, user_data, "...");
size_t skipChars = tokenPos-30 - startOfLine;
startOfLine += 3+skipChars;
if (skipChars<=col)
col -= skipChars;
else
col = 0;
lineLength -= skipChars;
}
// print the string until the end of the line, or 60 chars (whichever is less)
int chars = 0;
JsvStringIterator it;
jsvStringIteratorNew(&it, lex->sourceVar, startOfLine);
unsigned char lastch = 0;
while (jsvStringIteratorHasChar(&it) && chars<60) {
unsigned char ch = (unsigned char)jsvStringIteratorGetChar(&it);
if (ch == '\n') break;
if (jslNeedSpaceBetween(lastch, ch)) {
col++;
user_callback(" ", user_data);
}
char buf[32];
jslFunctionCharAsString(ch, buf, sizeof(buf));
size_t len = strlen(buf);
col += len-1;
user_callback(buf, user_data);
chars++;
lastch = ch;
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
if (lineLength > 60)
user_callback("...", user_data);
user_callback("\n", user_data);
col += prefixLength;
while (col-- > 1) user_callback(" ", user_data);
user_callback("^\n", user_data);
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_158_0 |
crossvul-cpp_data_bad_3105_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP SSSSS DDDD %
% P P SS D D %
% PPPP SSS D D %
% P SS D D %
% P SSSSS DDDD %
% %
% %
% Read/Write Adobe Photoshop Image Format %
% %
% Software Design %
% Cristy %
% Leonard Rosenthol %
% July 1992 %
% Dirk Lemstra %
% December 2013 %
% %
% %
% Copyright 1999-2017 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 "magick/studio.h"
#include "magick/artifact.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/channel.h"
#include "magick/colormap.h"
#include "magick/colormap-private.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/constitute.h"
#include "magick/enhance.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/log.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/module.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/pixel.h"
#include "magick/pixel-accessor.h"
#include "magick/profile.h"
#include "magick/property.h"
#include "magick/registry.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/thread-private.h"
#ifdef MAGICKCORE_ZLIB_DELEGATE
#include <zlib.h>
#endif
#include "psd-private.h"
/*
Define declaractions.
*/
#define MaxPSDChannels 56
#define PSDQuantum(x) (((ssize_t) (x)+1) & -2)
/*
Enumerated declaractions.
*/
typedef enum
{
Raw = 0,
RLE = 1,
ZipWithoutPrediction = 2,
ZipWithPrediction = 3
} PSDCompressionType;
typedef enum
{
BitmapMode = 0,
GrayscaleMode = 1,
IndexedMode = 2,
RGBMode = 3,
CMYKMode = 4,
MultichannelMode = 7,
DuotoneMode = 8,
LabMode = 9
} PSDImageType;
/*
Typedef declaractions.
*/
typedef struct _ChannelInfo
{
short int
type;
size_t
size;
} ChannelInfo;
typedef struct _MaskInfo
{
Image
*image;
RectangleInfo
page;
unsigned char
background,
flags;
} MaskInfo;
typedef struct _LayerInfo
{
ChannelInfo
channel_info[MaxPSDChannels];
char
blendkey[4];
Image
*image;
MaskInfo
mask;
Quantum
opacity;
RectangleInfo
page;
size_t
offset_x,
offset_y;
unsigned char
clipping,
flags,
name[256],
visible;
unsigned short
channels;
StringInfo
*info;
} LayerInfo;
/*
Forward declarations.
*/
static MagickBooleanType
WritePSDImage(const ImageInfo *,Image *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s P S D %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsPSD()() returns MagickTrue if the image format type, identified by the
% magick string, is PSD.
%
% The format of the IsPSD method is:
%
% MagickBooleanType IsPSD(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsPSD(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (LocaleNCompare((const char *) magick,"8BPS",4) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadPSDImage() reads an Adobe Photoshop 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 ReadPSDImage method is:
%
% Image *ReadPSDImage(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 const char *CompositeOperatorToPSDBlendMode(CompositeOperator op)
{
const char
*blend_mode;
switch (op)
{
case ColorBurnCompositeOp: blend_mode = "idiv"; break;
case ColorDodgeCompositeOp: blend_mode = "div "; break;
case ColorizeCompositeOp: blend_mode = "colr"; break;
case DarkenCompositeOp: blend_mode = "dark"; break;
case DifferenceCompositeOp: blend_mode = "diff"; break;
case DissolveCompositeOp: blend_mode = "diss"; break;
case ExclusionCompositeOp: blend_mode = "smud"; break;
case HardLightCompositeOp: blend_mode = "hLit"; break;
case HardMixCompositeOp: blend_mode = "hMix"; break;
case HueCompositeOp: blend_mode = "hue "; break;
case LightenCompositeOp: blend_mode = "lite"; break;
case LinearBurnCompositeOp: blend_mode = "lbrn"; break;
case LinearDodgeCompositeOp:blend_mode = "lddg"; break;
case LinearLightCompositeOp:blend_mode = "lLit"; break;
case LuminizeCompositeOp: blend_mode = "lum "; break;
case MultiplyCompositeOp: blend_mode = "mul "; break;
case OverCompositeOp: blend_mode = "norm"; break;
case OverlayCompositeOp: blend_mode = "over"; break;
case PinLightCompositeOp: blend_mode = "pLit"; break;
case SaturateCompositeOp: blend_mode = "sat "; break;
case ScreenCompositeOp: blend_mode = "scrn"; break;
case SoftLightCompositeOp: blend_mode = "sLit"; break;
case VividLightCompositeOp: blend_mode = "vLit"; break;
default: blend_mode = "norm"; break;
}
return(blend_mode);
}
/*
For some reason Photoshop seems to blend semi-transparent pixels with white.
This method reverts the blending. This can be disabled by setting the
option 'psd:alpha-unblend' to off.
*/
static MagickBooleanType CorrectPSDAlphaBlend(const ImageInfo *image_info,
Image *image, ExceptionInfo* exception)
{
const char
*option;
MagickBooleanType
status;
ssize_t
y;
if (image->matte == MagickFalse || image->colorspace != sRGBColorspace)
return(MagickTrue);
option=GetImageOption(image_info,"psd:alpha-unblend");
if (IsStringNotFalse(option) == MagickFalse)
return(MagickTrue);
status=MagickTrue;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
gamma;
gamma=QuantumScale*GetPixelAlpha(q);
if (gamma != 0.0 && gamma != 1.0)
{
SetPixelRed(q,(GetPixelRed(q)-((1.0-gamma)*QuantumRange))/gamma);
SetPixelGreen(q,(GetPixelGreen(q)-((1.0-gamma)*QuantumRange))/gamma);
SetPixelBlue(q,(GetPixelBlue(q)-((1.0-gamma)*QuantumRange))/gamma);
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
status=MagickFalse;
}
return(status);
}
static inline CompressionType ConvertPSDCompression(
PSDCompressionType compression)
{
switch (compression)
{
case RLE:
return RLECompression;
case ZipWithPrediction:
case ZipWithoutPrediction:
return ZipCompression;
default:
return NoCompression;
}
}
static MagickBooleanType ApplyPSDLayerOpacity(Image *image,Quantum opacity,
MagickBooleanType revert,ExceptionInfo *exception)
{
MagickBooleanType
status;
ssize_t
y;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" applying layer opacity %.20g", (double) opacity);
if (opacity == QuantumRange)
return(MagickTrue);
image->matte=MagickTrue;
status=MagickTrue;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (revert == MagickFalse)
SetPixelAlpha(q,(Quantum) (QuantumScale*(GetPixelAlpha(q)*opacity)));
else if (opacity > 0)
SetPixelAlpha(q,(Quantum) (QuantumRange*(GetPixelAlpha(q)/
(MagickRealType) opacity)));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
status=MagickFalse;
}
return(status);
}
static MagickBooleanType ApplyPSDOpacityMask(Image *image,const Image *mask,
Quantum background,MagickBooleanType revert,ExceptionInfo *exception)
{
Image
*complete_mask;
MagickBooleanType
status;
MagickPixelPacket
color;
ssize_t
y;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" applying opacity mask");
complete_mask=CloneImage(image,image->columns,image->rows,MagickTrue,
exception);
complete_mask->matte=MagickTrue;
GetMagickPixelPacket(complete_mask,&color);
color.red=background;
SetImageColor(complete_mask,&color);
status=CompositeImage(complete_mask,OverCompositeOp,mask,
mask->page.x-image->page.x,mask->page.y-image->page.y);
if (status == MagickFalse)
{
complete_mask=DestroyImage(complete_mask);
return(status);
}
image->matte=MagickTrue;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*magick_restrict q;
register PixelPacket
*p;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
p=GetAuthenticPixels(complete_mask,0,y,complete_mask->columns,1,exception);
if ((q == (PixelPacket *) NULL) || (p == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
MagickRealType
alpha,
intensity;
alpha=GetPixelAlpha(q);
intensity=GetPixelIntensity(complete_mask,p);
if (revert == MagickFalse)
SetPixelAlpha(q,ClampToQuantum(intensity*(QuantumScale*alpha)));
else if (intensity > 0)
SetPixelAlpha(q,ClampToQuantum((alpha/intensity)*QuantumRange));
q++;
p++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
status=MagickFalse;
}
complete_mask=DestroyImage(complete_mask);
return(status);
}
static void PreservePSDOpacityMask(Image *image,LayerInfo* layer_info,
ExceptionInfo *exception)
{
char
*key;
RandomInfo
*random_info;
StringInfo
*key_info;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" preserving opacity mask");
random_info=AcquireRandomInfo();
key_info=GetRandomKey(random_info,2+1);
key=(char *) GetStringInfoDatum(key_info);
key[8]=layer_info->mask.background;
key[9]='\0';
layer_info->mask.image->page.x+=layer_info->page.x;
layer_info->mask.image->page.y+=layer_info->page.y;
(void) SetImageRegistry(ImageRegistryType,(const char *) key,
layer_info->mask.image,exception);
(void) SetImageArtifact(layer_info->image,"psd:opacity-mask",
(const char *) key);
key_info=DestroyStringInfo(key_info);
random_info=DestroyRandomInfo(random_info);
}
static ssize_t DecodePSDPixels(const size_t number_compact_pixels,
const unsigned char *compact_pixels,const ssize_t depth,
const size_t number_pixels,unsigned char *pixels)
{
#define CheckNumberCompactPixels \
if (packets == 0) \
return(i); \
packets--
#define CheckNumberPixels(count) \
if (((ssize_t) i + count) > (ssize_t) number_pixels) \
return(i); \
i+=count
int
pixel;
register ssize_t
i,
j;
size_t
length;
ssize_t
packets;
packets=(ssize_t) number_compact_pixels;
for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); )
{
packets--;
length=(size_t) (*compact_pixels++);
if (length == 128)
continue;
if (length > 128)
{
length=256-length+1;
CheckNumberCompactPixels;
pixel=(*compact_pixels++);
for (j=0; j < (ssize_t) length; j++)
{
switch (depth)
{
case 1:
{
CheckNumberPixels(8);
*pixels++=(pixel >> 7) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 6) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 5) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 4) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 3) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 2) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 1) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 0) & 0x01 ? 0U : 255U;
break;
}
case 2:
{
CheckNumberPixels(4);
*pixels++=(unsigned char) ((pixel >> 6) & 0x03);
*pixels++=(unsigned char) ((pixel >> 4) & 0x03);
*pixels++=(unsigned char) ((pixel >> 2) & 0x03);
*pixels++=(unsigned char) ((pixel & 0x03) & 0x03);
break;
}
case 4:
{
CheckNumberPixels(2);
*pixels++=(unsigned char) ((pixel >> 4) & 0xff);
*pixels++=(unsigned char) ((pixel & 0x0f) & 0xff);
break;
}
default:
{
CheckNumberPixels(1);
*pixels++=(unsigned char) pixel;
break;
}
}
}
continue;
}
length++;
for (j=0; j < (ssize_t) length; j++)
{
CheckNumberCompactPixels;
switch (depth)
{
case 1:
{
CheckNumberPixels(8);
*pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U;
break;
}
case 2:
{
CheckNumberPixels(4);
*pixels++=(*compact_pixels >> 6) & 0x03;
*pixels++=(*compact_pixels >> 4) & 0x03;
*pixels++=(*compact_pixels >> 2) & 0x03;
*pixels++=(*compact_pixels & 0x03) & 0x03;
break;
}
case 4:
{
CheckNumberPixels(2);
*pixels++=(*compact_pixels >> 4) & 0xff;
*pixels++=(*compact_pixels & 0x0f) & 0xff;
break;
}
default:
{
CheckNumberPixels(1);
*pixels++=(*compact_pixels);
break;
}
}
compact_pixels++;
}
}
return(i);
}
static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info,
const ssize_t number_layers)
{
ssize_t
i;
for (i=0; i<number_layers; i++)
{
if (layer_info[i].image != (Image *) NULL)
layer_info[i].image=DestroyImage(layer_info[i].image);
if (layer_info[i].mask.image != (Image *) NULL)
layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image);
if (layer_info[i].info != (StringInfo *) NULL)
layer_info[i].info=DestroyStringInfo(layer_info[i].info);
}
return (LayerInfo *) RelinquishMagickMemory(layer_info);
}
static inline size_t GetPSDPacketSize(Image *image)
{
if (image->storage_class == PseudoClass)
{
if (image->colors > 256)
return(2);
else if (image->depth > 8)
return(2);
}
else
if (image->depth > 8)
return(2);
return(1);
}
static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image)
{
if (psd_info->version == 1)
return((MagickSizeType) ReadBlobLong(image));
return((MagickSizeType) ReadBlobLongLong(image));
}
static inline size_t GetPSDRowSize(Image *image)
{
if (image->depth == 1)
return(((image->columns+7)/8)*GetPSDPacketSize(image));
else
return(image->columns*GetPSDPacketSize(image));
}
static const char *ModeToString(PSDImageType type)
{
switch (type)
{
case BitmapMode: return "Bitmap";
case GrayscaleMode: return "Grayscale";
case IndexedMode: return "Indexed";
case RGBMode: return "RGB";
case CMYKMode: return "CMYK";
case MultichannelMode: return "Multichannel";
case DuotoneMode: return "Duotone";
case LabMode: return "L*A*B";
default: return "unknown";
}
}
static void ParseImageResourceBlocks(Image *image,
const unsigned char *blocks,size_t length,
MagickBooleanType *has_merged_image)
{
const unsigned char
*p;
StringInfo
*profile;
unsigned int
count,
long_sans;
unsigned short
id,
short_sans;
if (length < 16)
return;
profile=BlobToStringInfo((const void *) NULL,length);
SetStringInfoDatum(profile,blocks);
(void) SetImageProfile(image,"8bim",profile);
profile=DestroyStringInfo(profile);
for (p=blocks; (p >= blocks) && (p < (blocks+length-16)); )
{
if (LocaleNCompare((const char *) p,"8BIM",4) != 0)
break;
p=PushLongPixel(MSBEndian,p,&long_sans);
p=PushShortPixel(MSBEndian,p,&id);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushLongPixel(MSBEndian,p,&count);
if ((p+count) > (blocks+length-16))
return;
switch (id)
{
case 0x03ed:
{
char
value[MaxTextExtent];
unsigned short
resolution;
/*
Resolution info.
*/
p=PushShortPixel(MSBEndian,p,&resolution);
image->x_resolution=(double) resolution;
(void) FormatLocaleString(value,MaxTextExtent,"%g",
image->x_resolution);
(void) SetImageProperty(image,"tiff:XResolution",value);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&resolution);
image->y_resolution=(double) resolution;
(void) FormatLocaleString(value,MaxTextExtent,"%g",
image->y_resolution);
(void) SetImageProperty(image,"tiff:YResolution",value);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
image->units=PixelsPerInchResolution;
break;
}
case 0x0421:
{
if (*(p+4) == 0)
*has_merged_image=MagickFalse;
p+=count;
break;
}
default:
{
p+=count;
break;
}
}
if ((count & 0x01) != 0)
p++;
}
return;
}
static CompositeOperator PSDBlendModeToCompositeOperator(const char *mode)
{
if (mode == (const char *) NULL)
return(OverCompositeOp);
if (LocaleNCompare(mode,"norm",4) == 0)
return(OverCompositeOp);
if (LocaleNCompare(mode,"mul ",4) == 0)
return(MultiplyCompositeOp);
if (LocaleNCompare(mode,"diss",4) == 0)
return(DissolveCompositeOp);
if (LocaleNCompare(mode,"diff",4) == 0)
return(DifferenceCompositeOp);
if (LocaleNCompare(mode,"dark",4) == 0)
return(DarkenCompositeOp);
if (LocaleNCompare(mode,"lite",4) == 0)
return(LightenCompositeOp);
if (LocaleNCompare(mode,"hue ",4) == 0)
return(HueCompositeOp);
if (LocaleNCompare(mode,"sat ",4) == 0)
return(SaturateCompositeOp);
if (LocaleNCompare(mode,"colr",4) == 0)
return(ColorizeCompositeOp);
if (LocaleNCompare(mode,"lum ",4) == 0)
return(LuminizeCompositeOp);
if (LocaleNCompare(mode,"scrn",4) == 0)
return(ScreenCompositeOp);
if (LocaleNCompare(mode,"over",4) == 0)
return(OverlayCompositeOp);
if (LocaleNCompare(mode,"hLit",4) == 0)
return(HardLightCompositeOp);
if (LocaleNCompare(mode,"sLit",4) == 0)
return(SoftLightCompositeOp);
if (LocaleNCompare(mode,"smud",4) == 0)
return(ExclusionCompositeOp);
if (LocaleNCompare(mode,"div ",4) == 0)
return(ColorDodgeCompositeOp);
if (LocaleNCompare(mode,"idiv",4) == 0)
return(ColorBurnCompositeOp);
if (LocaleNCompare(mode,"lbrn",4) == 0)
return(LinearBurnCompositeOp);
if (LocaleNCompare(mode,"lddg",4) == 0)
return(LinearDodgeCompositeOp);
if (LocaleNCompare(mode,"lLit",4) == 0)
return(LinearLightCompositeOp);
if (LocaleNCompare(mode,"vLit",4) == 0)
return(VividLightCompositeOp);
if (LocaleNCompare(mode,"pLit",4) == 0)
return(PinLightCompositeOp);
if (LocaleNCompare(mode,"hMix",4) == 0)
return(HardMixCompositeOp);
return(OverCompositeOp);
}
static inline void ReversePSDString(Image *image,char *p,size_t length)
{
char
*q;
if (image->endian == MSBEndian)
return;
q=p+length;
for(--q; p < q; ++p, --q)
{
*p = *p ^ *q,
*q = *p ^ *q,
*p = *p ^ *q;
}
}
static inline void SetPSDPixel(Image *image,const size_t channels,
const ssize_t type,const size_t packet_size,const Quantum pixel,
PixelPacket *q,IndexPacket *indexes,ssize_t x)
{
if (image->storage_class == PseudoClass)
{
if (packet_size == 1)
SetPixelIndex(indexes+x,ScaleQuantumToChar(pixel));
else
SetPixelIndex(indexes+x,ScaleQuantumToShort(pixel));
SetPixelRGBO(q,image->colormap+(ssize_t)
ConstrainColormapIndex(image,GetPixelIndex(indexes+x)));
return;
}
switch (type)
{
case -1:
{
SetPixelAlpha(q,pixel);
break;
}
case -2:
case 0:
{
SetPixelRed(q,pixel);
if (channels == 1 || type == -2)
{
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
}
break;
}
case 1:
{
if (image->storage_class == PseudoClass)
SetPixelAlpha(q,pixel);
else
SetPixelGreen(q,pixel);
break;
}
case 2:
{
if (image->storage_class == PseudoClass)
SetPixelAlpha(q,pixel);
else
SetPixelBlue(q,pixel);
break;
}
case 3:
{
if (image->colorspace == CMYKColorspace)
SetPixelIndex(indexes+x,pixel);
else
if (image->matte != MagickFalse)
SetPixelAlpha(q,pixel);
break;
}
case 4:
{
if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) &&
(channels > 3))
break;
if (image->matte != MagickFalse)
SetPixelAlpha(q,pixel);
break;
}
}
}
static MagickBooleanType ReadPSDChannelPixels(Image *image,const size_t channels,
const size_t row,const ssize_t type,const unsigned char *pixels,
ExceptionInfo *exception)
{
Quantum
pixel;
register const unsigned char
*p;
register IndexPacket
*indexes;
register PixelPacket
*q;
register ssize_t
x;
size_t
packet_size;
unsigned short
nibble;
p=pixels;
q=GetAuthenticPixels(image,0,row,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
indexes=GetAuthenticIndexQueue(image);
packet_size=GetPSDPacketSize(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (packet_size == 1)
pixel=ScaleCharToQuantum(*p++);
else
{
p=PushShortPixel(MSBEndian,p,&nibble);
pixel=ScaleShortToQuantum(nibble);
}
if (image->depth > 1)
{
SetPSDPixel(image,channels,type,packet_size,pixel,q++,indexes,x);
}
else
{
ssize_t
bit,
number_bits;
number_bits=image->columns-x;
if (number_bits > 8)
number_bits=8;
for (bit=0; bit < number_bits; bit++)
{
SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel)
& (0x01 << (7-bit))) != 0 ? 0 : QuantumRange,q++,indexes,x++);
}
if (x != (ssize_t) image->columns)
x--;
continue;
}
}
return(SyncAuthenticPixels(image,exception));
}
static MagickBooleanType ReadPSDChannelRaw(Image *image,const size_t channels,
const ssize_t type,ExceptionInfo *exception)
{
MagickBooleanType
status;
size_t
count,
row_size;
ssize_t
y;
unsigned char
*pixels;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is RAW");
row_size=GetPSDRowSize(image);
pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=MagickTrue;
for (y=0; y < (ssize_t) image->rows; y++)
{
status=MagickFalse;
count=ReadBlob(image,row_size,pixels);
if (count != row_size)
break;
status=ReadPSDChannelPixels(image,channels,y,type,pixels,exception);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(status);
}
static inline MagickOffsetType *ReadPSDRLESizes(Image *image,
const PSDInfo *psd_info,const size_t size)
{
MagickOffsetType
*sizes;
ssize_t
y;
sizes=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*sizes));
if(sizes != (MagickOffsetType *) NULL)
{
for (y=0; y < (ssize_t) size; y++)
{
if (psd_info->version == 1)
sizes[y]=(MagickOffsetType) ReadBlobShort(image);
else
sizes[y]=(MagickOffsetType) ReadBlobLong(image);
}
}
return sizes;
}
static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info,
const ssize_t type,MagickOffsetType *sizes,ExceptionInfo *exception)
{
MagickBooleanType
status;
size_t
length,
row_size;
ssize_t
count,
y;
unsigned char
*compact_pixels,
*pixels;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is RLE compressed");
row_size=GetPSDRowSize(image);
pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
length=0;
for (y=0; y < (ssize_t) image->rows; y++)
if ((MagickOffsetType) length < sizes[y])
length=(size_t) sizes[y];
compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels));
if (compact_pixels == (unsigned char *) NULL)
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
(void) ResetMagickMemory(compact_pixels,0,length*sizeof(*compact_pixels));
status=MagickTrue;
for (y=0; y < (ssize_t) image->rows; y++)
{
status=MagickFalse;
count=ReadBlob(image,(size_t) sizes[y],compact_pixels);
if (count != (ssize_t) sizes[y])
break;
count=DecodePSDPixels((size_t) sizes[y],compact_pixels,
(ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels);
if (count != (ssize_t) row_size)
break;
status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels,
exception);
if (status == MagickFalse)
break;
}
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(status);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels,
const ssize_t type,const PSDCompressionType compression,
const size_t compact_size,ExceptionInfo *exception)
{
MagickBooleanType
status;
register unsigned char
*p;
size_t
count,
length,
packet_size,
row_size;
ssize_t
y;
unsigned char
*compact_pixels,
*pixels;
z_stream
stream;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is ZIP compressed");
compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size,
sizeof(*compact_pixels));
if (compact_pixels == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
packet_size=GetPSDPacketSize(image);
row_size=image->columns*packet_size;
count=image->rows*row_size;
pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
{
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
ResetMagickMemory(&stream,0,sizeof(stream));
stream.data_type=Z_BINARY;
(void) ReadBlob(image,compact_size,compact_pixels);
stream.next_in=(Bytef *)compact_pixels;
stream.avail_in=(uInt) compact_size;
stream.next_out=(Bytef *)pixels;
stream.avail_out=(uInt) count;
if (inflateInit(&stream) == Z_OK)
{
int
ret;
while (stream.avail_out > 0)
{
ret=inflate(&stream, Z_SYNC_FLUSH);
if ((ret != Z_OK) && (ret != Z_STREAM_END))
{
compact_pixels=(unsigned char *) RelinquishMagickMemory(
compact_pixels);
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(MagickFalse);
}
}
}
if (compression == ZipWithPrediction)
{
p=pixels;
while (count > 0)
{
length=image->columns;
while (--length)
{
if (packet_size == 2)
{
p[2]+=p[0]+((p[1]+p[3]) >> 8);
p[3]+=p[1];
}
else
*(p+1)+=*p;
p+=packet_size;
}
p+=packet_size;
count-=row_size;
}
}
status=MagickTrue;
p=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
status=ReadPSDChannelPixels(image,channels,y,type,p,exception);
if (status == MagickFalse)
break;
p+=row_size;
}
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(status);
}
#endif
static MagickBooleanType ReadPSDChannel(Image *image,
const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info,
const size_t channel,const PSDCompressionType compression,
ExceptionInfo *exception)
{
Image
*channel_image,
*mask;
MagickOffsetType
offset;
MagickBooleanType
status;
channel_image=image;
mask=(Image *) NULL;
if (layer_info->channel_info[channel].type < -1)
{
const char
*option;
/*
Ignore mask that is not a user supplied layer mask, if the mask is
disabled or if the flags have unsupported values.
*/
option=GetImageOption(image_info,"psd:preserve-opacity-mask");
if ((layer_info->channel_info[channel].type != -2) ||
(layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) &&
(IsStringTrue(option) == MagickFalse)))
{
SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR);
return(MagickTrue);
}
mask=CloneImage(image,layer_info->mask.page.width,
layer_info->mask.page.height,MagickFalse,exception);
mask->matte=MagickFalse;
channel_image=mask;
}
offset=TellBlob(image);
status=MagickTrue;
switch(compression)
{
case Raw:
status=ReadPSDChannelRaw(channel_image,psd_info->channels,
layer_info->channel_info[channel].type,exception);
break;
case RLE:
{
MagickOffsetType
*sizes;
sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows);
if (sizes == (MagickOffsetType *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=ReadPSDChannelRLE(channel_image,psd_info,
layer_info->channel_info[channel].type,sizes,exception);
sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes);
}
break;
case ZipWithPrediction:
case ZipWithoutPrediction:
#ifdef MAGICKCORE_ZLIB_DELEGATE
status=ReadPSDChannelZip(channel_image,layer_info->channels,
layer_info->channel_info[channel].type,compression,
layer_info->channel_info[channel].size-2,exception);
#else
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn",
"'%s' (ZLIB)",image->filename);
#endif
break;
default:
(void) ThrowMagickException(exception,GetMagickModule(),TypeWarning,
"CompressionNotSupported","'%.20g'",(double) compression);
break;
}
SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET);
if (status == MagickFalse)
{
if (mask != (Image *) NULL)
DestroyImage(mask);
ThrowBinaryException(CoderError,"UnableToDecompressImage",
image->filename);
}
layer_info->mask.image=mask;
return(status);
}
static MagickBooleanType ReadPSDLayer(Image *image,const ImageInfo *image_info,
const PSDInfo *psd_info,LayerInfo* layer_info,ExceptionInfo *exception)
{
char
message[MaxTextExtent];
MagickBooleanType
status;
PSDCompressionType
compression;
ssize_t
j;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" setting up new layer image");
if (psd_info->mode != IndexedMode)
(void) SetImageBackgroundColor(layer_info->image);
layer_info->image->compose=PSDBlendModeToCompositeOperator(
layer_info->blendkey);
if (layer_info->visible == MagickFalse)
{
layer_info->image->compose=NoCompositeOp;
(void) SetImageArtifact(layer_info->image,"psd:layer.invisible","true");
}
if (psd_info->mode == CMYKMode)
SetImageColorspace(layer_info->image,CMYKColorspace);
else if ((psd_info->mode == BitmapMode) || (psd_info->mode == DuotoneMode) ||
(psd_info->mode == GrayscaleMode))
SetImageColorspace(layer_info->image,GRAYColorspace);
/*
Set up some hidden attributes for folks that need them.
*/
(void) FormatLocaleString(message,MaxTextExtent,"%.20g",
(double) layer_info->page.x);
(void) SetImageArtifact(layer_info->image,"psd:layer.x",message);
(void) FormatLocaleString(message,MaxTextExtent,"%.20g",
(double) layer_info->page.y);
(void) SetImageArtifact(layer_info->image,"psd:layer.y",message);
(void) FormatLocaleString(message,MaxTextExtent,"%.20g",(double)
layer_info->opacity);
(void) SetImageArtifact(layer_info->image,"psd:layer.opacity",message);
(void) SetImageProperty(layer_info->image,"label",(char *) layer_info->name);
status=MagickTrue;
for (j=0; j < (ssize_t) layer_info->channels; j++)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading data for channel %.20g",(double) j);
compression=(PSDCompressionType) ReadBlobShort(layer_info->image);
layer_info->image->compression=ConvertPSDCompression(compression);
if (layer_info->channel_info[j].type == -1)
layer_info->image->matte=MagickTrue;
status=ReadPSDChannel(layer_info->image,image_info,psd_info,layer_info,j,
compression,exception);
InheritException(exception,&layer_info->image->exception);
if (status == MagickFalse)
break;
}
if (status != MagickFalse)
status=ApplyPSDLayerOpacity(layer_info->image,layer_info->opacity,
MagickFalse,exception);
if ((status != MagickFalse) &&
(layer_info->image->colorspace == CMYKColorspace))
status=NegateImage(layer_info->image,MagickFalse);
if (status != MagickFalse && layer_info->mask.image != (Image *) NULL)
{
const char
*option;
layer_info->mask.image->page.x=layer_info->mask.page.x;
layer_info->mask.image->page.y=layer_info->mask.page.y;
/* Do not composite the mask when it is disabled */
if ((layer_info->mask.flags & 0x02) == 0x02)
layer_info->mask.image->compose=NoCompositeOp;
else
status=ApplyPSDOpacityMask(layer_info->image,layer_info->mask.image,
layer_info->mask.background == 0 ? 0 : QuantumRange,MagickFalse,
exception);
option=GetImageOption(image_info,"psd:preserve-opacity-mask");
if (IsStringTrue(option) != MagickFalse)
PreservePSDOpacityMask(image,layer_info,exception);
layer_info->mask.image=DestroyImage(layer_info->mask.image);
}
return(status);
}
ModuleExport MagickBooleanType ReadPSDLayers(Image *image,
const ImageInfo *image_info,const PSDInfo *psd_info,
const MagickBooleanType skip_layers,ExceptionInfo *exception)
{
char
type[4];
LayerInfo
*layer_info;
MagickSizeType
size;
MagickBooleanType
status;
register ssize_t
i;
ssize_t
count,
j,
number_layers;
size=GetPSDSize(psd_info,image);
if (size == 0)
{
/*
Skip layers & masks.
*/
(void) ReadBlobLong(image);
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
status=MagickFalse;
if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0))
return(MagickTrue);
else
{
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
if ((count != 0) && (LocaleNCompare(type,"Lr16",4) == 0))
size=GetPSDSize(psd_info,image);
else
return(MagickTrue);
}
}
status=MagickTrue;
if (size != 0)
{
layer_info=(LayerInfo *) NULL;
number_layers=(short) ReadBlobShort(image);
if (number_layers < 0)
{
/*
The first alpha channel in the merged result contains the
transparency data for the merged result.
*/
number_layers=MagickAbsoluteValue(number_layers);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" negative layer count corrected for");
image->matte=MagickTrue;
}
/*
We only need to know if the image has an alpha channel
*/
if (skip_layers != MagickFalse)
return(MagickTrue);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image contains %.20g layers",(double) number_layers);
if (number_layers == 0)
ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers",
image->filename);
layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers,
sizeof(*layer_info));
if (layer_info == (LayerInfo *) NULL)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" allocation of LayerInfo failed");
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
(void) ResetMagickMemory(layer_info,0,(size_t) number_layers*
sizeof(*layer_info));
for (i=0; i < number_layers; i++)
{
ssize_t
x,
y;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading layer #%.20g",(double) i+1);
layer_info[i].page.y=ReadBlobSignedLong(image);
layer_info[i].page.x=ReadBlobSignedLong(image);
y=ReadBlobSignedLong(image);
x=ReadBlobSignedLong(image);
layer_info[i].page.width=(size_t) (x-layer_info[i].page.x);
layer_info[i].page.height=(size_t) (y-layer_info[i].page.y);
layer_info[i].channels=ReadBlobShort(image);
if (layer_info[i].channels > MaxPSDChannels)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded",
image->filename);
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g",
(double) layer_info[i].page.x,(double) layer_info[i].page.y,
(double) layer_info[i].page.height,(double)
layer_info[i].page.width,(double) layer_info[i].channels);
for (j=0; j < (ssize_t) layer_info[i].channels; j++)
{
layer_info[i].channel_info[j].type=(short) ReadBlobShort(image);
layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info,
image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" channel[%.20g]: type=%.20g, size=%.20g",(double) j,
(double) layer_info[i].channel_info[j].type,
(double) layer_info[i].channel_info[j].size);
}
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer type was %.4s instead of 8BIM", type);
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"ImproperImageHeader",
image->filename);
}
(void) ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey);
ReversePSDString(image,layer_info[i].blendkey,4);
layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
layer_info[i].clipping=(unsigned char) ReadBlobByte(image);
layer_info[i].flags=(unsigned char) ReadBlobByte(image);
layer_info[i].visible=!(layer_info[i].flags & 0x02);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s",
layer_info[i].blendkey,(double) layer_info[i].opacity,
layer_info[i].clipping ? "true" : "false",layer_info[i].flags,
layer_info[i].visible ? "true" : "false");
(void) ReadBlobByte(image); /* filler */
size=ReadBlobLong(image);
if (size != 0)
{
MagickSizeType
combined_length,
length;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer contains additional info");
length=ReadBlobLong(image);
combined_length=length+4;
if (length != 0)
{
/*
Layer mask info.
*/
layer_info[i].mask.page.y=ReadBlobSignedLong(image);
layer_info[i].mask.page.x=ReadBlobSignedLong(image);
layer_info[i].mask.page.height=(size_t) (ReadBlobLong(image)-
layer_info[i].mask.page.y);
layer_info[i].mask.page.width=(size_t) (ReadBlobLong(image)-
layer_info[i].mask.page.x);
layer_info[i].mask.background=(unsigned char) ReadBlobByte(
image);
layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image);
if (!(layer_info[i].mask.flags & 0x01))
{
layer_info[i].mask.page.y=layer_info[i].mask.page.y-
layer_info[i].page.y;
layer_info[i].mask.page.x=layer_info[i].mask.page.x-
layer_info[i].page.x;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g",
(double) layer_info[i].mask.page.x,(double)
layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width,
(double) layer_info[i].mask.page.height,(double)
((MagickOffsetType) length)-18);
/*
Skip over the rest of the layer mask information.
*/
if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile",
image->filename);
}
}
length=ReadBlobLong(image);
combined_length+=length+4;
if (length != 0)
{
/*
Layer blending ranges info.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer blending ranges: length=%.20g",(double)
((MagickOffsetType) length));
/*
We read it, but don't use it...
*/
for (j=0; j < (ssize_t) length; j+=8)
{
size_t blend_source=ReadBlobLong(image);
size_t blend_dest=ReadBlobLong(image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" source(%x), dest(%x)",(unsigned int)
blend_source,(unsigned int) blend_dest);
}
}
/*
Layer name.
*/
length=(MagickSizeType) (unsigned char) ReadBlobByte(image);
combined_length+=length+1;
if (length > 0)
(void) ReadBlob(image,(size_t) length++,layer_info[i].name);
layer_info[i].name[length]='\0';
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer name: %s",layer_info[i].name);
if ((length % 4) != 0)
{
length=4-(length % 4);
combined_length+=length;
/* Skip over the padding of the layer name */
if (DiscardBlobBytes(image,length) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
}
length=(MagickSizeType) size-combined_length;
if (length > 0)
{
unsigned char
*info;
layer_info[i].info=AcquireStringInfo((const size_t) length);
info=GetStringInfoDatum(layer_info[i].info);
(void) ReadBlob(image,(const size_t) length,info);
}
}
}
for (i=0; i < number_layers; i++)
{
if ((layer_info[i].page.width == 0) ||
(layer_info[i].page.height == 0))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is empty");
if (layer_info[i].info != (StringInfo *) NULL)
layer_info[i].info=DestroyStringInfo(layer_info[i].info);
continue;
}
/*
Allocate layered image.
*/
layer_info[i].image=CloneImage(image,layer_info[i].page.width,
layer_info[i].page.height,MagickFalse,exception);
if (layer_info[i].image == (Image *) NULL)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" allocation of image for layer %.20g failed",(double) i);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
if (layer_info[i].info != (StringInfo *) NULL)
{
(void) SetImageProfile(layer_info[i].image,"psd:additional-info",
layer_info[i].info);
layer_info[i].info=DestroyStringInfo(layer_info[i].info);
}
}
if (image_info->ping == MagickFalse)
{
for (i=0; i < number_layers; i++)
{
if (layer_info[i].image == (Image *) NULL)
{
for (j=0; j < layer_info[i].channels; j++)
{
if (DiscardBlobBytes(image,(MagickSizeType)
layer_info[i].channel_info[j].size) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
}
continue;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading data for layer %.20g",(double) i);
status=ReadPSDLayer(image,image_info,psd_info,&layer_info[i],
exception);
if (status == MagickFalse)
break;
status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType)
number_layers);
if (status == MagickFalse)
break;
}
}
if (status != MagickFalse)
{
for (i=0; i < number_layers; i++)
{
if (layer_info[i].image == (Image *) NULL)
{
for (j=i; j < number_layers - 1; j++)
layer_info[j] = layer_info[j+1];
number_layers--;
i--;
}
}
if (number_layers > 0)
{
for (i=0; i < number_layers; i++)
{
if (i > 0)
layer_info[i].image->previous=layer_info[i-1].image;
if (i < (number_layers-1))
layer_info[i].image->next=layer_info[i+1].image;
layer_info[i].image->page=layer_info[i].page;
}
image->next=layer_info[0].image;
layer_info[0].image->previous=image;
}
layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info);
}
else
layer_info=DestroyLayerInfo(layer_info,number_layers);
}
return(status);
}
static MagickBooleanType ReadPSDMergedImage(const ImageInfo *image_info,
Image* image,const PSDInfo* psd_info,ExceptionInfo *exception)
{
MagickOffsetType
*sizes;
MagickBooleanType
status;
PSDCompressionType
compression;
register ssize_t
i;
compression=(PSDCompressionType) ReadBlobMSBShort(image);
image->compression=ConvertPSDCompression(compression);
if (compression != Raw && compression != RLE)
{
(void) ThrowMagickException(exception,GetMagickModule(),
TypeWarning,"CompressionNotSupported","'%.20g'",(double) compression);
return(MagickFalse);
}
sizes=(MagickOffsetType *) NULL;
if (compression == RLE)
{
sizes=ReadPSDRLESizes(image,psd_info,image->rows*psd_info->channels);
if (sizes == (MagickOffsetType *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
status=MagickTrue;
for (i=0; i < (ssize_t) psd_info->channels; i++)
{
if (compression == RLE)
status=ReadPSDChannelRLE(image,psd_info,i,sizes+(i*image->rows),
exception);
else
status=ReadPSDChannelRaw(image,psd_info->channels,i,exception);
if (status != MagickFalse)
status=SetImageProgress(image,LoadImagesTag,i,psd_info->channels);
if (status == MagickFalse)
break;
}
if ((status != MagickFalse) && (image->colorspace == CMYKColorspace))
status=NegateImage(image,MagickFalse);
if (status != MagickFalse)
status=CorrectPSDAlphaBlend(image_info,image,exception);
sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes);
return(status);
}
static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
has_merged_image,
skip_layers;
MagickOffsetType
offset;
MagickSizeType
length;
MagickBooleanType
status;
PSDInfo
psd_info;
register ssize_t
i;
ssize_t
count;
unsigned char
*data;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read image header.
*/
image->endian=MSBEndian;
count=ReadBlob(image,4,(unsigned char *) psd_info.signature);
psd_info.version=ReadBlobMSBShort(image);
if ((count == 0) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) ||
((psd_info.version != 1) && (psd_info.version != 2)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
(void) ReadBlob(image,6,psd_info.reserved);
psd_info.channels=ReadBlobMSBShort(image);
if (psd_info.channels > MaxPSDChannels)
ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded");
psd_info.rows=ReadBlobMSBLong(image);
psd_info.columns=ReadBlobMSBLong(image);
if ((psd_info.version == 1) && ((psd_info.rows > 30000) ||
(psd_info.columns > 30000)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
psd_info.depth=ReadBlobMSBShort(image);
if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
psd_info.mode=ReadBlobMSBShort(image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s",
(double) psd_info.columns,(double) psd_info.rows,(double)
psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType)
psd_info.mode));
/*
Initialize image.
*/
image->depth=psd_info.depth;
image->columns=psd_info.columns;
image->rows=psd_info.rows;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if (SetImageBackgroundColor(image) == MagickFalse)
{
InheritException(exception,&image->exception);
image=DestroyImageList(image);
return((Image *) NULL);
}
if (psd_info.mode == LabMode)
SetImageColorspace(image,LabColorspace);
if (psd_info.mode == CMYKMode)
{
SetImageColorspace(image,CMYKColorspace);
image->matte=psd_info.channels > 4 ? MagickTrue : MagickFalse;
}
else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) ||
(psd_info.mode == DuotoneMode))
{
status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536);
if (status == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image colormap allocated");
SetImageColorspace(image,GRAYColorspace);
image->matte=psd_info.channels > 1 ? MagickTrue : MagickFalse;
}
else
image->matte=psd_info.channels > 3 ? MagickTrue : MagickFalse;
/*
Read PSD raster colormap only present for indexed and duotone images.
*/
length=ReadBlobMSBLong(image);
if (length != 0)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading colormap");
if (psd_info.mode == DuotoneMode)
{
/*
Duotone image data; the format of this data is undocumented.
*/
data=(unsigned char *) AcquireQuantumMemory((size_t) length,
sizeof(*data));
if (data == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ReadBlob(image,(size_t) length,data);
data=(unsigned char *) RelinquishMagickMemory(data);
}
else
{
size_t
number_colors;
/*
Read PSD raster colormap.
*/
number_colors=length/3;
if (number_colors > 65536)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (AcquireImageColormap(image,number_colors) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].red=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].green=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].blue=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->matte=MagickFalse;
}
}
if ((image->depth == 1) && (image->storage_class != PseudoClass))
ThrowReaderException(CorruptImageError, "ImproperImageHeader");
has_merged_image=MagickTrue;
length=ReadBlobMSBLong(image);
if (length != 0)
{
unsigned char
*blocks;
/*
Image resources block.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading image resource blocks - %.20g bytes",(double)
((MagickOffsetType) length));
blocks=(unsigned char *) AcquireQuantumMemory((size_t) length,
sizeof(*blocks));
if (blocks == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,(size_t) length,blocks);
if ((count != (ssize_t) length) || (length < 4) ||
(LocaleNCompare((char *) blocks,"8BIM",4) != 0))
{
blocks=(unsigned char *) RelinquishMagickMemory(blocks);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image);
blocks=(unsigned char *) RelinquishMagickMemory(blocks);
}
/*
Layer and mask block.
*/
length=GetPSDSize(&psd_info,image);
if (length == 8)
{
length=ReadBlobMSBLong(image);
length=ReadBlobMSBLong(image);
}
offset=TellBlob(image);
skip_layers=MagickFalse;
if ((image_info->number_scenes == 1) && (image_info->scene == 0) &&
(has_merged_image != MagickFalse))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" read composite only");
skip_layers=MagickTrue;
}
if (length == 0)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image has no layers");
}
else
{
if (ReadPSDLayers(image,image_info,&psd_info,skip_layers,exception) !=
MagickTrue)
{
(void) CloseBlob(image);
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Skip the rest of the layer and mask information.
*/
SeekBlob(image,offset+length,SEEK_SET);
}
/*
If we are only "pinging" the image, then we're done - so return.
*/
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
Read the precombined layer, present for PSD < 4 compatibility.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading the precombined layer");
if (has_merged_image != MagickFalse || GetImageListLength(image) == 1)
has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image,
&psd_info,exception);
if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) &&
(length != 0))
{
SeekBlob(image,offset,SEEK_SET);
status=ReadPSDLayers(image,image_info,&psd_info,MagickFalse,exception);
if (status != MagickTrue)
{
(void) CloseBlob(image);
image=DestroyImageList(image);
return((Image *) NULL);
}
}
if (has_merged_image == MagickFalse)
{
Image
*merged;
if (GetImageListLength(image) == 1)
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
SetImageAlphaChannel(image,TransparentAlphaChannel);
image->background_color.opacity=TransparentOpacity;
merged=MergeImageLayers(image,FlattenLayer,exception);
ReplaceImageInList(&image,merged);
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterPSDImage() adds properties for the PSD image format to
% the list of supported formats. The properties 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 RegisterPSDImage method is:
%
% size_t RegisterPSDImage(void)
%
*/
ModuleExport size_t RegisterPSDImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("PSB");
entry->decoder=(DecodeImageHandler *) ReadPSDImage;
entry->encoder=(EncodeImageHandler *) WritePSDImage;
entry->magick=(IsImageFormatHandler *) IsPSD;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString("Adobe Large Document Format");
entry->module=ConstantString("PSD");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PSD");
entry->decoder=(DecodeImageHandler *) ReadPSDImage;
entry->encoder=(EncodeImageHandler *) WritePSDImage;
entry->magick=(IsImageFormatHandler *) IsPSD;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString("Adobe Photoshop bitmap");
entry->module=ConstantString("PSD");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterPSDImage() removes format registrations made by the
% PSD module from the list of supported formats.
%
% The format of the UnregisterPSDImage method is:
%
% UnregisterPSDImage(void)
%
*/
ModuleExport void UnregisterPSDImage(void)
{
(void) UnregisterMagickInfo("PSB");
(void) UnregisterMagickInfo("PSD");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WritePSDImage() writes an image in the Adobe Photoshop encoded image format.
%
% The format of the WritePSDImage method is:
%
% MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static inline ssize_t SetPSDOffset(const PSDInfo *psd_info,Image *image,
const size_t offset)
{
if (psd_info->version == 1)
return(WriteBlobMSBShort(image,(unsigned short) offset));
return(WriteBlobMSBLong(image,(unsigned short) offset));
}
static inline ssize_t WritePSDOffset(const PSDInfo *psd_info,Image *image,
const MagickSizeType size,const MagickSizeType offset)
{
MagickSizeType
current_offset;
ssize_t
result;
current_offset=TellBlob(image);
SeekBlob(image,offset,SEEK_SET);
if (psd_info->version == 1)
result=WriteBlobMSBShort(image,(unsigned short) size);
else
result=(WriteBlobMSBLong(image,(unsigned short) size));
SeekBlob(image,current_offset,SEEK_SET);
return(result);
}
static inline ssize_t SetPSDSize(const PSDInfo *psd_info,Image *image,
const MagickSizeType size)
{
if (psd_info->version == 1)
return(WriteBlobMSBLong(image,(unsigned int) size));
return(WriteBlobMSBLongLong(image,size));
}
static inline ssize_t WritePSDSize(const PSDInfo *psd_info,Image *image,
const MagickSizeType size,const MagickSizeType offset)
{
MagickSizeType
current_offset;
ssize_t
result;
current_offset=TellBlob(image);
SeekBlob(image,offset,SEEK_SET);
if (psd_info->version == 1)
result=WriteBlobMSBLong(image,(unsigned int) size);
else
result=WriteBlobMSBLongLong(image,size);
SeekBlob(image,current_offset,SEEK_SET);
return(result);
}
static size_t PSDPackbitsEncodeImage(Image *image,const size_t length,
const unsigned char *pixels,unsigned char *compact_pixels)
{
int
count;
register ssize_t
i,
j;
register unsigned char
*q;
unsigned char
*packbits;
/*
Compress pixels with Packbits encoding.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(pixels != (unsigned char *) NULL);
assert(compact_pixels != (unsigned char *) NULL);
packbits=(unsigned char *) AcquireQuantumMemory(128UL,sizeof(*packbits));
if (packbits == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
q=compact_pixels;
for (i=(ssize_t) length; i != 0; )
{
switch (i)
{
case 1:
{
i--;
*q++=(unsigned char) 0;
*q++=(*pixels);
break;
}
case 2:
{
i-=2;
*q++=(unsigned char) 1;
*q++=(*pixels);
*q++=pixels[1];
break;
}
case 3:
{
i-=3;
if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2)))
{
*q++=(unsigned char) ((256-3)+1);
*q++=(*pixels);
break;
}
*q++=(unsigned char) 2;
*q++=(*pixels);
*q++=pixels[1];
*q++=pixels[2];
break;
}
default:
{
if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2)))
{
/*
Packed run.
*/
count=3;
while (((ssize_t) count < i) && (*pixels == *(pixels+count)))
{
count++;
if (count >= 127)
break;
}
i-=count;
*q++=(unsigned char) ((256-count)+1);
*q++=(*pixels);
pixels+=count;
break;
}
/*
Literal run.
*/
count=0;
while ((*(pixels+count) != *(pixels+count+1)) ||
(*(pixels+count+1) != *(pixels+count+2)))
{
packbits[count+1]=pixels[count];
count++;
if (((ssize_t) count >= (i-3)) || (count >= 127))
break;
}
i-=count;
*packbits=(unsigned char) (count-1);
for (j=0; j <= (ssize_t) count; j++)
*q++=packbits[j];
pixels+=count;
break;
}
}
}
*q++=(unsigned char) 128; /* EOD marker */
packbits=(unsigned char *) RelinquishMagickMemory(packbits);
return((size_t) (q-compact_pixels));
}
static size_t WriteCompressionStart(const PSDInfo *psd_info,Image *image,
const Image *next_image,const ssize_t channels)
{
size_t
length;
ssize_t
i,
y;
if (next_image->compression == RLECompression)
{
length=WriteBlobMSBShort(image,RLE);
for (i=0; i < channels; i++)
for (y=0; y < (ssize_t) next_image->rows; y++)
length+=SetPSDOffset(psd_info,image,0);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
else if (next_image->compression == ZipCompression)
length=WriteBlobMSBShort(image,ZipWithoutPrediction);
#endif
else
length=WriteBlobMSBShort(image,Raw);
return(length);
}
static size_t WritePSDChannel(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
const QuantumType quantum_type, unsigned char *compact_pixels,
MagickOffsetType size_offset,const MagickBooleanType separate)
{
int
y;
MagickBooleanType
monochrome;
QuantumInfo
*quantum_info;
register const PixelPacket
*p;
register ssize_t
i;
size_t
count,
length;
unsigned char
*pixels;
#ifdef MAGICKCORE_ZLIB_DELEGATE
#define CHUNK 16384
int
flush,
level;
unsigned char
*compressed_pixels;
z_stream
stream;
compressed_pixels=(unsigned char *) NULL;
flush=Z_NO_FLUSH;
#endif
count=0;
if (separate != MagickFalse)
{
size_offset=TellBlob(image)+2;
count+=WriteCompressionStart(psd_info,image,next_image,1);
}
if (next_image->depth > 8)
next_image->depth=16;
monochrome=IsMonochromeImage(image,&image->exception) && (image->depth == 1)
? MagickTrue : MagickFalse;
quantum_info=AcquireQuantumInfo(image_info,next_image);
if (quantum_info == (QuantumInfo *) NULL)
return(0);
pixels=GetQuantumPixels(quantum_info);
#ifdef MAGICKCORE_ZLIB_DELEGATE
if (next_image->compression == ZipCompression)
{
compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK,
sizeof(*compressed_pixels));
if (compressed_pixels == (unsigned char *) NULL)
{
quantum_info=DestroyQuantumInfo(quantum_info);
return(0);
}
ResetMagickMemory(&stream,0,sizeof(stream));
stream.data_type=Z_BINARY;
level=Z_DEFAULT_COMPRESSION;
if ((image_info->quality > 0 && image_info->quality < 10))
level=(int) image_info->quality;
if (deflateInit(&stream,level) != Z_OK)
{
quantum_info=DestroyQuantumInfo(quantum_info);
return(0);
}
}
#endif
for (y=0; y < (ssize_t) next_image->rows; y++)
{
p=GetVirtualPixels(next_image,0,y,next_image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,&image->exception);
if (monochrome != MagickFalse)
for (i=0; i < (ssize_t) length; i++)
pixels[i]=(~pixels[i]);
if (next_image->compression == RLECompression)
{
length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels);
count+=WriteBlob(image,length,compact_pixels);
size_offset+=WritePSDOffset(psd_info,image,length,size_offset);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
else if (next_image->compression == ZipCompression)
{
stream.avail_in=(uInt) length;
stream.next_in=(Bytef *) pixels;
if (y == (ssize_t) next_image->rows-1)
flush=Z_FINISH;
do {
stream.avail_out=(uInt) CHUNK;
stream.next_out=(Bytef *) compressed_pixels;
if (deflate(&stream,flush) == Z_STREAM_ERROR)
break;
length=(size_t) CHUNK-stream.avail_out;
if (length > 0)
count+=WriteBlob(image,length,compressed_pixels);
} while (stream.avail_out == 0);
}
#endif
else
count+=WriteBlob(image,length,pixels);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
if (next_image->compression == ZipCompression)
{
(void) deflateEnd(&stream);
compressed_pixels=(unsigned char *) RelinquishMagickMemory(
compressed_pixels);
}
#endif
quantum_info=DestroyQuantumInfo(quantum_info);
return(count);
}
static unsigned char *AcquireCompactPixels(Image *image)
{
size_t
packet_size;
unsigned char
*compact_pixels;
packet_size=image->depth > 8UL ? 2UL : 1UL;
compact_pixels=(unsigned char *) AcquireQuantumMemory((9*
image->columns)+1,packet_size*sizeof(*compact_pixels));
if (compact_pixels == (unsigned char *) NULL)
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
image->filename);
}
return(compact_pixels);
}
static ssize_t WritePSDChannels(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
MagickOffsetType size_offset,const MagickBooleanType separate)
{
Image
*mask;
MagickOffsetType
rows_offset;
size_t
channels,
count,
length,
offset_length;
unsigned char
*compact_pixels;
count=0;
offset_length=0;
rows_offset=0;
compact_pixels=(unsigned char *) NULL;
if (next_image->compression == RLECompression)
{
compact_pixels=AcquireCompactPixels(image);
if (compact_pixels == (unsigned char *) NULL)
return(0);
}
channels=1;
if (separate == MagickFalse)
{
if (next_image->storage_class != PseudoClass)
{
if (IsGrayImage(next_image,&next_image->exception) == MagickFalse)
channels=next_image->colorspace == CMYKColorspace ? 4 : 3;
if (next_image->matte != MagickFalse)
channels++;
}
rows_offset=TellBlob(image)+2;
count+=WriteCompressionStart(psd_info,image,next_image,channels);
offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4));
}
size_offset+=2;
if (next_image->storage_class == PseudoClass)
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
IndexQuantum,compact_pixels,rows_offset,separate);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
else
{
if (IsGrayImage(next_image,&next_image->exception) != MagickFalse)
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
GrayQuantum,compact_pixels,rows_offset,separate);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
else
{
if (next_image->colorspace == CMYKColorspace)
(void) NegateImage(next_image,MagickFalse);
length=WritePSDChannel(psd_info,image_info,image,next_image,
RedQuantum,compact_pixels,rows_offset,separate);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
length=WritePSDChannel(psd_info,image_info,image,next_image,
GreenQuantum,compact_pixels,rows_offset,separate);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
length=WritePSDChannel(psd_info,image_info,image,next_image,
BlueQuantum,compact_pixels,rows_offset,separate);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
if (next_image->colorspace == CMYKColorspace)
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
BlackQuantum,compact_pixels,rows_offset,separate);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
}
if (next_image->matte != MagickFalse)
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
AlphaQuantum,compact_pixels,rows_offset,separate);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
}
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
if (next_image->colorspace == CMYKColorspace)
(void) NegateImage(next_image,MagickFalse);
if (separate != MagickFalse)
{
const char
*property;
property=GetImageArtifact(next_image,"psd:opacity-mask");
if (property != (const char *) NULL)
{
mask=(Image *) GetImageRegistry(ImageRegistryType,property,
&image->exception);
if (mask != (Image *) NULL)
{
if (mask->compression == RLECompression)
{
compact_pixels=AcquireCompactPixels(mask);
if (compact_pixels == (unsigned char *) NULL)
return(0);
}
length=WritePSDChannel(psd_info,image_info,image,mask,
RedQuantum,compact_pixels,rows_offset,MagickTrue);
(void) WritePSDSize(psd_info,image,length,size_offset);
count+=length;
compact_pixels=(unsigned char *) RelinquishMagickMemory(
compact_pixels);
}
}
}
return(count);
}
static size_t WritePascalString(Image *image,const char *value,size_t padding)
{
size_t
count,
length;
register ssize_t
i;
/*
Max length is 255.
*/
count=0;
length=(strlen(value) > 255UL ) ? 255UL : strlen(value);
if (length == 0)
count+=WriteBlobByte(image,0);
else
{
count+=WriteBlobByte(image,(unsigned char) length);
count+=WriteBlob(image,length,(const unsigned char *) value);
}
length++;
if ((length % padding) == 0)
return(count);
for (i=0; i < (ssize_t) (padding-(length % padding)); i++)
count+=WriteBlobByte(image,0);
return(count);
}
static void WriteResolutionResourceBlock(Image *image)
{
double
x_resolution,
y_resolution;
unsigned short
units;
if (image->units == PixelsPerCentimeterResolution)
{
x_resolution=2.54*65536.0*image->x_resolution+0.5;
y_resolution=2.54*65536.0*image->y_resolution+0.5;
units=2;
}
else
{
x_resolution=65536.0*image->x_resolution+0.5;
y_resolution=65536.0*image->y_resolution+0.5;
units=1;
}
(void) WriteBlob(image,4,(const unsigned char *) "8BIM");
(void) WriteBlobMSBShort(image,0x03ED);
(void) WriteBlobMSBShort(image,0);
(void) WriteBlobMSBLong(image,16); /* resource size */
(void) WriteBlobMSBLong(image,(unsigned int) (x_resolution+0.5));
(void) WriteBlobMSBShort(image,units); /* horizontal resolution unit */
(void) WriteBlobMSBShort(image,units); /* width unit */
(void) WriteBlobMSBLong(image,(unsigned int) (y_resolution+0.5));
(void) WriteBlobMSBShort(image,units); /* vertical resolution unit */
(void) WriteBlobMSBShort(image,units); /* height unit */
}
static inline size_t WriteChannelSize(const PSDInfo *psd_info,Image *image,
const signed short channel)
{
size_t
count;
count=WriteBlobMSBSignedShort(image,channel);
count+=SetPSDSize(psd_info,image,0);
return(count);
}
static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile)
{
register const unsigned char
*p;
size_t
length;
unsigned char
*datum;
unsigned int
count,
long_sans;
unsigned short
id,
short_sans;
length=GetStringInfoLength(bim_profile);
if (length < 16)
return;
datum=GetStringInfoDatum(bim_profile);
for (p=datum; (p >= datum) && (p < (datum+length-16)); )
{
register unsigned char
*q;
q=(unsigned char *) p;
if (LocaleNCompare((const char *) p,"8BIM",4) != 0)
break;
p=PushLongPixel(MSBEndian,p,&long_sans);
p=PushShortPixel(MSBEndian,p,&id);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushLongPixel(MSBEndian,p,&count);
if (id == 0x0000040f)
{
ssize_t
quantum;
quantum=PSDQuantum(count)+12;
if ((quantum >= 12) && (quantum < (ssize_t) length))
{
if ((q+quantum < (datum+length-16)))
(void) CopyMagickMemory(q,q+quantum,length-quantum-(q-datum));
SetStringInfoLength(bim_profile,length-quantum);
}
break;
}
p+=count;
if ((count & 0x01) != 0)
p++;
}
}
static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile)
{
register const unsigned char
*p;
size_t
length;
unsigned char
*datum;
unsigned int
count,
long_sans;
unsigned short
id,
short_sans;
length=GetStringInfoLength(bim_profile);
if (length < 16)
return;
datum=GetStringInfoDatum(bim_profile);
for (p=datum; (p >= datum) && (p < (datum+length-16)); )
{
register unsigned char
*q;
ssize_t
cnt;
q=(unsigned char *) p;
if (LocaleNCompare((const char *) p,"8BIM",4) != 0)
return;
p=PushLongPixel(MSBEndian,p,&long_sans);
p=PushShortPixel(MSBEndian,p,&id);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushLongPixel(MSBEndian,p,&count);
cnt=PSDQuantum(count);
if (cnt < 0)
return;
if ((id == 0x000003ed) && (cnt < (ssize_t) (length-12)))
{
(void) CopyMagickMemory(q,q+cnt+12,length-(cnt+12)-(q-datum));
SetStringInfoLength(bim_profile,length-(cnt+12));
break;
}
p+=count;
if ((count & 0x01) != 0)
p++;
}
}
static const StringInfo *GetAdditionalInformation(const ImageInfo *image_info,
Image *image)
{
#define PSDKeySize 5
#define PSDAllowedLength 36
char
key[PSDKeySize];
/* Whitelist of keys from: https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/ */
const char
allowed[PSDAllowedLength][PSDKeySize] = {
"blnc", "blwh", "brit", "brst", "clbl", "clrL", "curv", "expA", "FMsk",
"GdFl", "grdm", "hue ", "hue2", "infx", "knko", "lclr", "levl", "lnsr",
"lfx2", "luni", "lrFX", "lspf", "lyid", "lyvr", "mixr", "nvrt", "phfl",
"post", "PtFl", "selc", "shpa", "sn2P", "SoCo", "thrs", "tsly", "vibA"
},
*option;
const StringInfo
*info;
MagickBooleanType
found;
register size_t
i;
size_t
remaining_length,
length;
StringInfo
*profile;
unsigned char
*p;
unsigned int
size;
info=GetImageProfile(image,"psd:additional-info");
if (info == (const StringInfo *) NULL)
return((const StringInfo *) NULL);
option=GetImageOption(image_info,"psd:additional-info");
if (LocaleCompare(option,"all") == 0)
return(info);
if (LocaleCompare(option,"selective") != 0)
{
profile=RemoveImageProfile(image,"psd:additional-info");
return(DestroyStringInfo(profile));
}
length=GetStringInfoLength(info);
p=GetStringInfoDatum(info);
remaining_length=length;
length=0;
while (remaining_length >= 12)
{
/* skip over signature */
p+=4;
key[0]=(*p++);
key[1]=(*p++);
key[2]=(*p++);
key[3]=(*p++);
key[4]='\0';
size=(unsigned int) (*p++) << 24;
size|=(unsigned int) (*p++) << 16;
size|=(unsigned int) (*p++) << 8;
size|=(unsigned int) (*p++);
size=size & 0xffffffff;
remaining_length-=12;
if ((size_t) size > remaining_length)
return((const StringInfo *) NULL);
found=MagickFalse;
for (i=0; i < PSDAllowedLength; i++)
{
if (LocaleNCompare(key,allowed[i],PSDKeySize) != 0)
continue;
found=MagickTrue;
break;
}
remaining_length-=(size_t) size;
if (found == MagickFalse)
{
if (remaining_length > 0)
p=(unsigned char *) CopyMagickMemory(p-12,p+size,remaining_length);
continue;
}
length+=(size_t) size+12;
p+=size;
}
profile=RemoveImageProfile(image,"psd:additional-info");
if (length == 0)
return(DestroyStringInfo(profile));
SetStringInfoLength(profile,(const size_t) length);
SetImageProfile(image,"psd:additional-info",info);
return(profile);
}
static MagickBooleanType WritePSDImage(const ImageInfo *image_info,
Image *image)
{
char
layer_name[MaxTextExtent];
const char
*property;
const StringInfo
*icc_profile,
*info;
Image
*base_image,
*next_image;
MagickBooleanType
status;
MagickOffsetType
*layer_size_offsets,
size_offset;
PSDInfo
psd_info;
register ssize_t
i;
size_t
layer_count,
layer_index,
length,
name_length,
num_channels,
packet_size,
rounded_size,
size;
StringInfo
*bim_profile;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
packet_size=(size_t) (image->depth > 8 ? 6 : 3);
if (image->matte != MagickFalse)
packet_size+=image->depth > 8 ? 2 : 1;
psd_info.version=1;
if ((LocaleCompare(image_info->magick,"PSB") == 0) ||
(image->columns > 30000) || (image->rows > 30000))
psd_info.version=2;
(void) WriteBlob(image,4,(const unsigned char *) "8BPS");
(void) WriteBlobMSBShort(image,psd_info.version); /* version */
for (i=1; i <= 6; i++)
(void) WriteBlobByte(image, 0); /* 6 bytes of reserved */
if (SetImageGray(image,&image->exception) != MagickFalse)
num_channels=(image->matte != MagickFalse ? 2UL : 1UL);
else
if ((image_info->type != TrueColorType) && (image_info->type !=
TrueColorMatteType) && (image->storage_class == PseudoClass))
num_channels=(image->matte != MagickFalse ? 2UL : 1UL);
else
{
if (image->storage_class == PseudoClass)
(void) SetImageStorageClass(image,DirectClass);
if (image->colorspace != CMYKColorspace)
num_channels=(image->matte != MagickFalse ? 4UL : 3UL);
else
num_channels=(image->matte != MagickFalse ? 5UL : 4UL);
}
(void) WriteBlobMSBShort(image,(unsigned short) num_channels);
(void) WriteBlobMSBLong(image,(unsigned int) image->rows);
(void) WriteBlobMSBLong(image,(unsigned int) image->columns);
if (IsGrayImage(image,&image->exception) != MagickFalse)
{
MagickBooleanType
monochrome;
/*
Write depth & mode.
*/
monochrome=IsMonochromeImage(image,&image->exception) &&
(image->depth == 1) ? MagickTrue : MagickFalse;
(void) WriteBlobMSBShort(image,(unsigned short)
(monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8));
(void) WriteBlobMSBShort(image,(unsigned short)
(monochrome != MagickFalse ? BitmapMode : GrayscaleMode));
}
else
{
(void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class ==
PseudoClass ? 8 : image->depth > 8 ? 16 : 8));
if (((image_info->colorspace != UndefinedColorspace) ||
(image->colorspace != CMYKColorspace)) &&
(image_info->colorspace != CMYKColorspace))
{
(void) TransformImageColorspace(image,sRGBColorspace);
(void) WriteBlobMSBShort(image,(unsigned short)
(image->storage_class == PseudoClass ? IndexedMode : RGBMode));
}
else
{
if (image->colorspace != CMYKColorspace)
(void) TransformImageColorspace(image,CMYKColorspace);
(void) WriteBlobMSBShort(image,CMYKMode);
}
}
if ((IsGrayImage(image,&image->exception) != MagickFalse) ||
(image->storage_class == DirectClass) || (image->colors > 256))
(void) WriteBlobMSBLong(image,0);
else
{
/*
Write PSD raster colormap.
*/
(void) WriteBlobMSBLong(image,768);
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].red));
for ( ; i < 256; i++)
(void) WriteBlobByte(image,0);
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(
image->colormap[i].green));
for ( ; i < 256; i++)
(void) WriteBlobByte(image,0);
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].blue));
for ( ; i < 256; i++)
(void) WriteBlobByte(image,0);
}
/*
Image resource block.
*/
length=28; /* 0x03EB */
bim_profile=(StringInfo *) GetImageProfile(image,"8bim");
icc_profile=GetImageProfile(image,"icc");
if (bim_profile != (StringInfo *) NULL)
{
bim_profile=CloneStringInfo(bim_profile);
if (icc_profile != (StringInfo *) NULL)
RemoveICCProfileFromResourceBlock(bim_profile);
RemoveResolutionFromResourceBlock(bim_profile);
length+=PSDQuantum(GetStringInfoLength(bim_profile));
}
if (icc_profile != (const StringInfo *) NULL)
length+=PSDQuantum(GetStringInfoLength(icc_profile))+12;
(void) WriteBlobMSBLong(image,(unsigned int) length);
WriteResolutionResourceBlock(image);
if (bim_profile != (StringInfo *) NULL)
{
(void) WriteBlob(image,GetStringInfoLength(bim_profile),
GetStringInfoDatum(bim_profile));
bim_profile=DestroyStringInfo(bim_profile);
}
if (icc_profile != (StringInfo *) NULL)
{
(void) WriteBlob(image,4,(const unsigned char *) "8BIM");
(void) WriteBlobMSBShort(image,0x0000040F);
(void) WriteBlobMSBShort(image,0);
(void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength(
icc_profile));
(void) WriteBlob(image,GetStringInfoLength(icc_profile),
GetStringInfoDatum(icc_profile));
if ((MagickOffsetType) GetStringInfoLength(icc_profile) !=
PSDQuantum(GetStringInfoLength(icc_profile)))
(void) WriteBlobByte(image,0);
}
base_image=GetNextImageInList(image);
if (base_image == (Image *)NULL)
base_image=image;
size=0;
size_offset=TellBlob(image);
SetPSDSize(&psd_info,image,0);
SetPSDSize(&psd_info,image,0);
layer_count=0;
for (next_image=base_image; next_image != NULL; )
{
layer_count++;
next_image=GetNextImageInList(next_image);
}
if (image->matte != MagickFalse)
size+=WriteBlobMSBShort(image,-(unsigned short) layer_count);
else
size+=WriteBlobMSBShort(image,(unsigned short) layer_count);
layer_size_offsets=(MagickOffsetType *) AcquireQuantumMemory(
(size_t) layer_count,sizeof(MagickOffsetType));
if (layer_size_offsets == (MagickOffsetType *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
layer_index=0;
for (next_image=base_image; next_image != NULL; )
{
Image
*mask;
unsigned char
default_color;
unsigned short
channels,
total_channels;
mask=(Image *) NULL;
property=GetImageArtifact(next_image,"psd:opacity-mask");
default_color=0;
if (property != (const char *) NULL)
{
mask=(Image *) GetImageRegistry(ImageRegistryType,property,
&image->exception);
default_color=strlen(property) == 9 ? 255 : 0;
}
size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.y);
size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.x);
size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.y+
next_image->rows));
size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.x+
next_image->columns));
channels=1U;
if ((next_image->storage_class != PseudoClass) &&
(IsGrayImage(next_image,&next_image->exception) == MagickFalse))
channels=next_image->colorspace == CMYKColorspace ? 4U : 3U;
total_channels=channels;
if (next_image->matte != MagickFalse)
total_channels++;
if (mask != (Image *) NULL)
total_channels++;
size+=WriteBlobMSBShort(image,total_channels);
layer_size_offsets[layer_index++]=TellBlob(image);
for (i=0; i < (ssize_t) channels; i++)
size+=WriteChannelSize(&psd_info,image,(signed short) i);
if (next_image->matte != MagickFalse)
size+=WriteChannelSize(&psd_info,image,-1);
if (mask != (Image *) NULL)
size+=WriteChannelSize(&psd_info,image,-2);
size+=WriteBlob(image,4,(const unsigned char *) "8BIM");
size+=WriteBlob(image,4,(const unsigned char *)
CompositeOperatorToPSDBlendMode(next_image->compose));
property=GetImageArtifact(next_image,"psd:layer.opacity");
if (property != (const char *) NULL)
{
Quantum
opacity;
opacity=(Quantum) StringToInteger(property);
size+=WriteBlobByte(image,ScaleQuantumToChar(opacity));
(void) ApplyPSDLayerOpacity(next_image,opacity,MagickTrue,
&image->exception);
}
else
size+=WriteBlobByte(image,255);
size+=WriteBlobByte(image,0);
size+=WriteBlobByte(image,next_image->compose==NoCompositeOp ?
1 << 0x02 : 1); /* layer properties - visible, etc. */
size+=WriteBlobByte(image,0);
info=GetAdditionalInformation(image_info,next_image);
property=(const char *) GetImageProperty(next_image,"label");
if (property == (const char *) NULL)
{
(void) FormatLocaleString(layer_name,MaxTextExtent,"L%.20g",
(double) layer_index);
property=layer_name;
}
name_length=strlen(property)+1;
if ((name_length % 4) != 0)
name_length+=(4-(name_length % 4));
if (info != (const StringInfo *) NULL)
name_length+=GetStringInfoLength(info);
name_length+=8;
if (mask != (Image *) NULL)
name_length+=20;
size+=WriteBlobMSBLong(image,(unsigned int) name_length);
if (mask == (Image *) NULL)
size+=WriteBlobMSBLong(image,0);
else
{
if (mask->compose != NoCompositeOp)
(void) ApplyPSDOpacityMask(next_image,mask,ScaleCharToQuantum(
default_color),MagickTrue,&image->exception);
mask->page.y+=image->page.y;
mask->page.x+=image->page.x;
size+=WriteBlobMSBLong(image,20);
size+=WriteBlobMSBSignedLong(image,mask->page.y);
size+=WriteBlobMSBSignedLong(image,mask->page.x);
size+=WriteBlobMSBLong(image,mask->rows+mask->page.y);
size+=WriteBlobMSBLong(image,mask->columns+mask->page.x);
size+=WriteBlobByte(image,default_color);
size+=WriteBlobByte(image,mask->compose == NoCompositeOp ? 2 : 0);
size+=WriteBlobMSBShort(image,0);
}
size+=WriteBlobMSBLong(image,0);
size+=WritePascalString(image,property,4);
if (info != (const StringInfo *) NULL)
size+=WriteBlob(image,GetStringInfoLength(info),
GetStringInfoDatum(info));
next_image=GetNextImageInList(next_image);
}
/*
Now the image data!
*/
next_image=base_image;
layer_index=0;
while (next_image != NULL)
{
length=WritePSDChannels(&psd_info,image_info,image,next_image,
layer_size_offsets[layer_index++],MagickTrue);
if (length == 0)
{
status=MagickFalse;
break;
}
size+=length;
next_image=GetNextImageInList(next_image);
}
(void) WriteBlobMSBLong(image,0); /* user mask data */
/*
Remove the opacity mask from the registry
*/
next_image=base_image;
while (next_image != (Image *) NULL)
{
property=GetImageArtifact(next_image,"psd:opacity-mask");
if (property != (const char *) NULL)
DeleteImageRegistry(property);
next_image=GetNextImageInList(next_image);
}
/*
Write the total size
*/
size_offset+=WritePSDSize(&psd_info,image,size+
(psd_info.version == 1 ? 8 : 16),size_offset);
if ((size/2) != ((size+1)/2))
rounded_size=size+1;
else
rounded_size=size;
(void) WritePSDSize(&psd_info,image,rounded_size,size_offset);
layer_size_offsets=(MagickOffsetType *) RelinquishMagickMemory(
layer_size_offsets);
/*
Write composite image.
*/
if (status != MagickFalse)
{
CompressionType
compression;
compression=image->compression;
if (image->compression == ZipCompression)
image->compression=RLECompression;
if (WritePSDChannels(&psd_info,image_info,image,image,0,
MagickFalse) == 0)
status=MagickFalse;
image->compression=compression;
}
(void) CloseBlob(image);
return(status);
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_3105_0 |
crossvul-cpp_data_good_3297_0 | /*
* utils for libavcodec
* Copyright (c) 2001 Fabrice Bellard
* Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
*
* This file is part of FFmpeg.
*
* FFmpeg 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.
*
* FFmpeg 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 FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* utils.
*/
#include "config.h"
#include "libavutil/atomic.h"
#include "libavutil/attributes.h"
#include "libavutil/avassert.h"
#include "libavutil/avstring.h"
#include "libavutil/bprint.h"
#include "libavutil/channel_layout.h"
#include "libavutil/crc.h"
#include "libavutil/frame.h"
#include "libavutil/hwcontext.h"
#include "libavutil/internal.h"
#include "libavutil/mathematics.h"
#include "libavutil/mem_internal.h"
#include "libavutil/pixdesc.h"
#include "libavutil/imgutils.h"
#include "libavutil/samplefmt.h"
#include "libavutil/dict.h"
#include "libavutil/thread.h"
#include "avcodec.h"
#include "libavutil/opt.h"
#include "me_cmp.h"
#include "mpegvideo.h"
#include "thread.h"
#include "frame_thread_encoder.h"
#include "internal.h"
#include "raw.h"
#include "bytestream.h"
#include "version.h"
#include <stdlib.h>
#include <stdarg.h>
#include <limits.h>
#include <float.h>
#if CONFIG_ICONV
# include <iconv.h>
#endif
#include "libavutil/ffversion.h"
const char av_codec_ffversion[] = "FFmpeg version " FFMPEG_VERSION;
#if HAVE_PTHREADS || HAVE_W32THREADS || HAVE_OS2THREADS
static int default_lockmgr_cb(void **arg, enum AVLockOp op)
{
void * volatile * mutex = arg;
int err;
switch (op) {
case AV_LOCK_CREATE:
return 0;
case AV_LOCK_OBTAIN:
if (!*mutex) {
pthread_mutex_t *tmp = av_malloc(sizeof(pthread_mutex_t));
if (!tmp)
return AVERROR(ENOMEM);
if ((err = pthread_mutex_init(tmp, NULL))) {
av_free(tmp);
return AVERROR(err);
}
if (avpriv_atomic_ptr_cas(mutex, NULL, tmp)) {
pthread_mutex_destroy(tmp);
av_free(tmp);
}
}
if ((err = pthread_mutex_lock(*mutex)))
return AVERROR(err);
return 0;
case AV_LOCK_RELEASE:
if ((err = pthread_mutex_unlock(*mutex)))
return AVERROR(err);
return 0;
case AV_LOCK_DESTROY:
if (*mutex)
pthread_mutex_destroy(*mutex);
av_free(*mutex);
avpriv_atomic_ptr_cas(mutex, *mutex, NULL);
return 0;
}
return 1;
}
static int (*lockmgr_cb)(void **mutex, enum AVLockOp op) = default_lockmgr_cb;
#else
static int (*lockmgr_cb)(void **mutex, enum AVLockOp op) = NULL;
#endif
volatile int ff_avcodec_locked;
static int volatile entangled_thread_counter = 0;
static void *codec_mutex;
static void *avformat_mutex;
void av_fast_padded_malloc(void *ptr, unsigned int *size, size_t min_size)
{
uint8_t **p = ptr;
if (min_size > SIZE_MAX - AV_INPUT_BUFFER_PADDING_SIZE) {
av_freep(p);
*size = 0;
return;
}
if (!ff_fast_malloc(p, size, min_size + AV_INPUT_BUFFER_PADDING_SIZE, 1))
memset(*p + min_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
}
void av_fast_padded_mallocz(void *ptr, unsigned int *size, size_t min_size)
{
uint8_t **p = ptr;
if (min_size > SIZE_MAX - AV_INPUT_BUFFER_PADDING_SIZE) {
av_freep(p);
*size = 0;
return;
}
if (!ff_fast_malloc(p, size, min_size + AV_INPUT_BUFFER_PADDING_SIZE, 1))
memset(*p, 0, min_size + AV_INPUT_BUFFER_PADDING_SIZE);
}
/* encoder management */
static AVCodec *first_avcodec = NULL;
static AVCodec **last_avcodec = &first_avcodec;
AVCodec *av_codec_next(const AVCodec *c)
{
if (c)
return c->next;
else
return first_avcodec;
}
static av_cold void avcodec_init(void)
{
static int initialized = 0;
if (initialized != 0)
return;
initialized = 1;
if (CONFIG_ME_CMP)
ff_me_cmp_init_static();
}
int av_codec_is_encoder(const AVCodec *codec)
{
return codec && (codec->encode_sub || codec->encode2 ||codec->send_frame);
}
int av_codec_is_decoder(const AVCodec *codec)
{
return codec && (codec->decode || codec->send_packet);
}
av_cold void avcodec_register(AVCodec *codec)
{
AVCodec **p;
avcodec_init();
p = last_avcodec;
codec->next = NULL;
while(*p || avpriv_atomic_ptr_cas((void * volatile *)p, NULL, codec))
p = &(*p)->next;
last_avcodec = &codec->next;
if (codec->init_static_data)
codec->init_static_data(codec);
}
#if FF_API_EMU_EDGE
unsigned avcodec_get_edge_width(void)
{
return EDGE_WIDTH;
}
#endif
#if FF_API_SET_DIMENSIONS
void avcodec_set_dimensions(AVCodecContext *s, int width, int height)
{
int ret = ff_set_dimensions(s, width, height);
if (ret < 0) {
av_log(s, AV_LOG_WARNING, "Failed to set dimensions %d %d\n", width, height);
}
}
#endif
int ff_set_dimensions(AVCodecContext *s, int width, int height)
{
int ret = av_image_check_size2(width, height, s->max_pixels, AV_PIX_FMT_NONE, 0, s);
if (ret < 0)
width = height = 0;
s->coded_width = width;
s->coded_height = height;
s->width = AV_CEIL_RSHIFT(width, s->lowres);
s->height = AV_CEIL_RSHIFT(height, s->lowres);
return ret;
}
int ff_set_sar(AVCodecContext *avctx, AVRational sar)
{
int ret = av_image_check_sar(avctx->width, avctx->height, sar);
if (ret < 0) {
av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %d/%d\n",
sar.num, sar.den);
avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
return ret;
} else {
avctx->sample_aspect_ratio = sar;
}
return 0;
}
int ff_side_data_update_matrix_encoding(AVFrame *frame,
enum AVMatrixEncoding matrix_encoding)
{
AVFrameSideData *side_data;
enum AVMatrixEncoding *data;
side_data = av_frame_get_side_data(frame, AV_FRAME_DATA_MATRIXENCODING);
if (!side_data)
side_data = av_frame_new_side_data(frame, AV_FRAME_DATA_MATRIXENCODING,
sizeof(enum AVMatrixEncoding));
if (!side_data)
return AVERROR(ENOMEM);
data = (enum AVMatrixEncoding*)side_data->data;
*data = matrix_encoding;
return 0;
}
void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height,
int linesize_align[AV_NUM_DATA_POINTERS])
{
int i;
int w_align = 1;
int h_align = 1;
AVPixFmtDescriptor const *desc = av_pix_fmt_desc_get(s->pix_fmt);
if (desc) {
w_align = 1 << desc->log2_chroma_w;
h_align = 1 << desc->log2_chroma_h;
}
switch (s->pix_fmt) {
case AV_PIX_FMT_YUV420P:
case AV_PIX_FMT_YUYV422:
case AV_PIX_FMT_YVYU422:
case AV_PIX_FMT_UYVY422:
case AV_PIX_FMT_YUV422P:
case AV_PIX_FMT_YUV440P:
case AV_PIX_FMT_YUV444P:
case AV_PIX_FMT_GBRP:
case AV_PIX_FMT_GBRAP:
case AV_PIX_FMT_GRAY8:
case AV_PIX_FMT_GRAY16BE:
case AV_PIX_FMT_GRAY16LE:
case AV_PIX_FMT_YUVJ420P:
case AV_PIX_FMT_YUVJ422P:
case AV_PIX_FMT_YUVJ440P:
case AV_PIX_FMT_YUVJ444P:
case AV_PIX_FMT_YUVA420P:
case AV_PIX_FMT_YUVA422P:
case AV_PIX_FMT_YUVA444P:
case AV_PIX_FMT_YUV420P9LE:
case AV_PIX_FMT_YUV420P9BE:
case AV_PIX_FMT_YUV420P10LE:
case AV_PIX_FMT_YUV420P10BE:
case AV_PIX_FMT_YUV420P12LE:
case AV_PIX_FMT_YUV420P12BE:
case AV_PIX_FMT_YUV420P14LE:
case AV_PIX_FMT_YUV420P14BE:
case AV_PIX_FMT_YUV420P16LE:
case AV_PIX_FMT_YUV420P16BE:
case AV_PIX_FMT_YUVA420P9LE:
case AV_PIX_FMT_YUVA420P9BE:
case AV_PIX_FMT_YUVA420P10LE:
case AV_PIX_FMT_YUVA420P10BE:
case AV_PIX_FMT_YUVA420P16LE:
case AV_PIX_FMT_YUVA420P16BE:
case AV_PIX_FMT_YUV422P9LE:
case AV_PIX_FMT_YUV422P9BE:
case AV_PIX_FMT_YUV422P10LE:
case AV_PIX_FMT_YUV422P10BE:
case AV_PIX_FMT_YUV422P12LE:
case AV_PIX_FMT_YUV422P12BE:
case AV_PIX_FMT_YUV422P14LE:
case AV_PIX_FMT_YUV422P14BE:
case AV_PIX_FMT_YUV422P16LE:
case AV_PIX_FMT_YUV422P16BE:
case AV_PIX_FMT_YUVA422P9LE:
case AV_PIX_FMT_YUVA422P9BE:
case AV_PIX_FMT_YUVA422P10LE:
case AV_PIX_FMT_YUVA422P10BE:
case AV_PIX_FMT_YUVA422P16LE:
case AV_PIX_FMT_YUVA422P16BE:
case AV_PIX_FMT_YUV440P10LE:
case AV_PIX_FMT_YUV440P10BE:
case AV_PIX_FMT_YUV440P12LE:
case AV_PIX_FMT_YUV440P12BE:
case AV_PIX_FMT_YUV444P9LE:
case AV_PIX_FMT_YUV444P9BE:
case AV_PIX_FMT_YUV444P10LE:
case AV_PIX_FMT_YUV444P10BE:
case AV_PIX_FMT_YUV444P12LE:
case AV_PIX_FMT_YUV444P12BE:
case AV_PIX_FMT_YUV444P14LE:
case AV_PIX_FMT_YUV444P14BE:
case AV_PIX_FMT_YUV444P16LE:
case AV_PIX_FMT_YUV444P16BE:
case AV_PIX_FMT_YUVA444P9LE:
case AV_PIX_FMT_YUVA444P9BE:
case AV_PIX_FMT_YUVA444P10LE:
case AV_PIX_FMT_YUVA444P10BE:
case AV_PIX_FMT_YUVA444P16LE:
case AV_PIX_FMT_YUVA444P16BE:
case AV_PIX_FMT_GBRP9LE:
case AV_PIX_FMT_GBRP9BE:
case AV_PIX_FMT_GBRP10LE:
case AV_PIX_FMT_GBRP10BE:
case AV_PIX_FMT_GBRP12LE:
case AV_PIX_FMT_GBRP12BE:
case AV_PIX_FMT_GBRP14LE:
case AV_PIX_FMT_GBRP14BE:
case AV_PIX_FMT_GBRP16LE:
case AV_PIX_FMT_GBRP16BE:
case AV_PIX_FMT_GBRAP12LE:
case AV_PIX_FMT_GBRAP12BE:
case AV_PIX_FMT_GBRAP16LE:
case AV_PIX_FMT_GBRAP16BE:
w_align = 16; //FIXME assume 16 pixel per macroblock
h_align = 16 * 2; // interlaced needs 2 macroblocks height
break;
case AV_PIX_FMT_YUV411P:
case AV_PIX_FMT_YUVJ411P:
case AV_PIX_FMT_UYYVYY411:
w_align = 32;
h_align = 16 * 2;
break;
case AV_PIX_FMT_YUV410P:
if (s->codec_id == AV_CODEC_ID_SVQ1) {
w_align = 64;
h_align = 64;
}
break;
case AV_PIX_FMT_RGB555:
if (s->codec_id == AV_CODEC_ID_RPZA) {
w_align = 4;
h_align = 4;
}
if (s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO) {
w_align = 8;
h_align = 8;
}
break;
case AV_PIX_FMT_PAL8:
case AV_PIX_FMT_BGR8:
case AV_PIX_FMT_RGB8:
if (s->codec_id == AV_CODEC_ID_SMC ||
s->codec_id == AV_CODEC_ID_CINEPAK) {
w_align = 4;
h_align = 4;
}
if (s->codec_id == AV_CODEC_ID_JV ||
s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO) {
w_align = 8;
h_align = 8;
}
break;
case AV_PIX_FMT_BGR24:
if ((s->codec_id == AV_CODEC_ID_MSZH) ||
(s->codec_id == AV_CODEC_ID_ZLIB)) {
w_align = 4;
h_align = 4;
}
break;
case AV_PIX_FMT_RGB24:
if (s->codec_id == AV_CODEC_ID_CINEPAK) {
w_align = 4;
h_align = 4;
}
break;
default:
break;
}
if (s->codec_id == AV_CODEC_ID_IFF_ILBM) {
w_align = FFMAX(w_align, 8);
}
*width = FFALIGN(*width, w_align);
*height = FFALIGN(*height, h_align);
if (s->codec_id == AV_CODEC_ID_H264 || s->lowres) {
// some of the optimized chroma MC reads one line too much
// which is also done in mpeg decoders with lowres > 0
*height += 2;
// H.264 uses edge emulation for out of frame motion vectors, for this
// it requires a temporary area large enough to hold a 21x21 block,
// increasing witdth ensure that the temporary area is large enough,
// the next rounded up width is 32
*width = FFMAX(*width, 32);
}
for (i = 0; i < 4; i++)
linesize_align[i] = STRIDE_ALIGN;
}
void avcodec_align_dimensions(AVCodecContext *s, int *width, int *height)
{
const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->pix_fmt);
int chroma_shift = desc->log2_chroma_w;
int linesize_align[AV_NUM_DATA_POINTERS];
int align;
avcodec_align_dimensions2(s, width, height, linesize_align);
align = FFMAX(linesize_align[0], linesize_align[3]);
linesize_align[1] <<= chroma_shift;
linesize_align[2] <<= chroma_shift;
align = FFMAX3(align, linesize_align[1], linesize_align[2]);
*width = FFALIGN(*width, align);
}
int avcodec_enum_to_chroma_pos(int *xpos, int *ypos, enum AVChromaLocation pos)
{
if (pos <= AVCHROMA_LOC_UNSPECIFIED || pos >= AVCHROMA_LOC_NB)
return AVERROR(EINVAL);
pos--;
*xpos = (pos&1) * 128;
*ypos = ((pos>>1)^(pos<4)) * 128;
return 0;
}
enum AVChromaLocation avcodec_chroma_pos_to_enum(int xpos, int ypos)
{
int pos, xout, yout;
for (pos = AVCHROMA_LOC_UNSPECIFIED + 1; pos < AVCHROMA_LOC_NB; pos++) {
if (avcodec_enum_to_chroma_pos(&xout, &yout, pos) == 0 && xout == xpos && yout == ypos)
return pos;
}
return AVCHROMA_LOC_UNSPECIFIED;
}
int avcodec_fill_audio_frame(AVFrame *frame, int nb_channels,
enum AVSampleFormat sample_fmt, const uint8_t *buf,
int buf_size, int align)
{
int ch, planar, needed_size, ret = 0;
needed_size = av_samples_get_buffer_size(NULL, nb_channels,
frame->nb_samples, sample_fmt,
align);
if (buf_size < needed_size)
return AVERROR(EINVAL);
planar = av_sample_fmt_is_planar(sample_fmt);
if (planar && nb_channels > AV_NUM_DATA_POINTERS) {
if (!(frame->extended_data = av_mallocz_array(nb_channels,
sizeof(*frame->extended_data))))
return AVERROR(ENOMEM);
} else {
frame->extended_data = frame->data;
}
if ((ret = av_samples_fill_arrays(frame->extended_data, &frame->linesize[0],
(uint8_t *)(intptr_t)buf, nb_channels, frame->nb_samples,
sample_fmt, align)) < 0) {
if (frame->extended_data != frame->data)
av_freep(&frame->extended_data);
return ret;
}
if (frame->extended_data != frame->data) {
for (ch = 0; ch < AV_NUM_DATA_POINTERS; ch++)
frame->data[ch] = frame->extended_data[ch];
}
return ret;
}
static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)
{
FramePool *pool = avctx->internal->pool;
int i, ret;
switch (avctx->codec_type) {
case AVMEDIA_TYPE_VIDEO: {
uint8_t *data[4];
int linesize[4];
int size[4] = { 0 };
int w = frame->width;
int h = frame->height;
int tmpsize, unaligned;
if (pool->format == frame->format &&
pool->width == frame->width && pool->height == frame->height)
return 0;
avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);
do {
// NOTE: do not align linesizes individually, this breaks e.g. assumptions
// that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
ret = av_image_fill_linesizes(linesize, avctx->pix_fmt, w);
if (ret < 0)
return ret;
// increase alignment of w for next try (rhs gives the lowest bit set in w)
w += w & ~(w - 1);
unaligned = 0;
for (i = 0; i < 4; i++)
unaligned |= linesize[i] % pool->stride_align[i];
} while (unaligned);
tmpsize = av_image_fill_pointers(data, avctx->pix_fmt, h,
NULL, linesize);
if (tmpsize < 0)
return -1;
for (i = 0; i < 3 && data[i + 1]; i++)
size[i] = data[i + 1] - data[i];
size[i] = tmpsize - (data[i] - data[0]);
for (i = 0; i < 4; i++) {
av_buffer_pool_uninit(&pool->pools[i]);
pool->linesize[i] = linesize[i];
if (size[i]) {
pool->pools[i] = av_buffer_pool_init(size[i] + 16 + STRIDE_ALIGN - 1,
CONFIG_MEMORY_POISONING ?
NULL :
av_buffer_allocz);
if (!pool->pools[i]) {
ret = AVERROR(ENOMEM);
goto fail;
}
}
}
pool->format = frame->format;
pool->width = frame->width;
pool->height = frame->height;
break;
}
case AVMEDIA_TYPE_AUDIO: {
int ch = av_frame_get_channels(frame); //av_get_channel_layout_nb_channels(frame->channel_layout);
int planar = av_sample_fmt_is_planar(frame->format);
int planes = planar ? ch : 1;
if (pool->format == frame->format && pool->planes == planes &&
pool->channels == ch && frame->nb_samples == pool->samples)
return 0;
av_buffer_pool_uninit(&pool->pools[0]);
ret = av_samples_get_buffer_size(&pool->linesize[0], ch,
frame->nb_samples, frame->format, 0);
if (ret < 0)
goto fail;
pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);
if (!pool->pools[0]) {
ret = AVERROR(ENOMEM);
goto fail;
}
pool->format = frame->format;
pool->planes = planes;
pool->channels = ch;
pool->samples = frame->nb_samples;
break;
}
default: av_assert0(0);
}
return 0;
fail:
for (i = 0; i < 4; i++)
av_buffer_pool_uninit(&pool->pools[i]);
pool->format = -1;
pool->planes = pool->channels = pool->samples = 0;
pool->width = pool->height = 0;
return ret;
}
static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
{
FramePool *pool = avctx->internal->pool;
int planes = pool->planes;
int i;
frame->linesize[0] = pool->linesize[0];
if (planes > AV_NUM_DATA_POINTERS) {
frame->extended_data = av_mallocz_array(planes, sizeof(*frame->extended_data));
frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
frame->extended_buf = av_mallocz_array(frame->nb_extended_buf,
sizeof(*frame->extended_buf));
if (!frame->extended_data || !frame->extended_buf) {
av_freep(&frame->extended_data);
av_freep(&frame->extended_buf);
return AVERROR(ENOMEM);
}
} else {
frame->extended_data = frame->data;
av_assert0(frame->nb_extended_buf == 0);
}
for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
frame->buf[i] = av_buffer_pool_get(pool->pools[0]);
if (!frame->buf[i])
goto fail;
frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
}
for (i = 0; i < frame->nb_extended_buf; i++) {
frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]);
if (!frame->extended_buf[i])
goto fail;
frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
}
if (avctx->debug & FF_DEBUG_BUFFERS)
av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame);
return 0;
fail:
av_frame_unref(frame);
return AVERROR(ENOMEM);
}
static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
{
FramePool *pool = s->internal->pool;
const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pic->format);
int i;
if (pic->data[0] || pic->data[1] || pic->data[2] || pic->data[3]) {
av_log(s, AV_LOG_ERROR, "pic->data[*]!=NULL in avcodec_default_get_buffer\n");
return -1;
}
if (!desc) {
av_log(s, AV_LOG_ERROR,
"Unable to get pixel format descriptor for format %s\n",
av_get_pix_fmt_name(pic->format));
return AVERROR(EINVAL);
}
memset(pic->data, 0, sizeof(pic->data));
pic->extended_data = pic->data;
for (i = 0; i < 4 && pool->pools[i]; i++) {
pic->linesize[i] = pool->linesize[i];
pic->buf[i] = av_buffer_pool_get(pool->pools[i]);
if (!pic->buf[i])
goto fail;
pic->data[i] = pic->buf[i]->data;
}
for (; i < AV_NUM_DATA_POINTERS; i++) {
pic->data[i] = NULL;
pic->linesize[i] = 0;
}
if (desc->flags & AV_PIX_FMT_FLAG_PAL ||
desc->flags & AV_PIX_FMT_FLAG_PSEUDOPAL)
avpriv_set_systematic_pal2((uint32_t *)pic->data[1], pic->format);
if (s->debug & FF_DEBUG_BUFFERS)
av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic);
return 0;
fail:
av_frame_unref(pic);
return AVERROR(ENOMEM);
}
void ff_color_frame(AVFrame *frame, const int c[4])
{
const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
int p, y, x;
av_assert0(desc->flags & AV_PIX_FMT_FLAG_PLANAR);
for (p = 0; p<desc->nb_components; p++) {
uint8_t *dst = frame->data[p];
int is_chroma = p == 1 || p == 2;
int bytes = is_chroma ? AV_CEIL_RSHIFT(frame->width, desc->log2_chroma_w) : frame->width;
int height = is_chroma ? AV_CEIL_RSHIFT(frame->height, desc->log2_chroma_h) : frame->height;
for (y = 0; y < height; y++) {
if (desc->comp[0].depth >= 9) {
for (x = 0; x<bytes; x++)
((uint16_t*)dst)[x] = c[p];
}else
memset(dst, c[p], bytes);
dst += frame->linesize[p];
}
}
}
int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags)
{
int ret;
if (avctx->hw_frames_ctx)
return av_hwframe_get_buffer(avctx->hw_frames_ctx, frame, 0);
if ((ret = update_frame_pool(avctx, frame)) < 0)
return ret;
switch (avctx->codec_type) {
case AVMEDIA_TYPE_VIDEO:
return video_get_buffer(avctx, frame);
case AVMEDIA_TYPE_AUDIO:
return audio_get_buffer(avctx, frame);
default:
return -1;
}
}
static int add_metadata_from_side_data(AVPacket *avpkt, AVFrame *frame)
{
int size;
const uint8_t *side_metadata;
AVDictionary **frame_md = avpriv_frame_get_metadatap(frame);
side_metadata = av_packet_get_side_data(avpkt,
AV_PKT_DATA_STRINGS_METADATA, &size);
return av_packet_unpack_dictionary(side_metadata, size, frame_md);
}
int ff_init_buffer_info(AVCodecContext *avctx, AVFrame *frame)
{
AVPacket *pkt = avctx->internal->pkt;
int i;
static const struct {
enum AVPacketSideDataType packet;
enum AVFrameSideDataType frame;
} sd[] = {
{ AV_PKT_DATA_REPLAYGAIN , AV_FRAME_DATA_REPLAYGAIN },
{ AV_PKT_DATA_DISPLAYMATRIX, AV_FRAME_DATA_DISPLAYMATRIX },
{ AV_PKT_DATA_SPHERICAL, AV_FRAME_DATA_SPHERICAL },
{ AV_PKT_DATA_STEREO3D, AV_FRAME_DATA_STEREO3D },
{ AV_PKT_DATA_AUDIO_SERVICE_TYPE, AV_FRAME_DATA_AUDIO_SERVICE_TYPE },
{ AV_PKT_DATA_MASTERING_DISPLAY_METADATA, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA },
};
if (pkt) {
frame->pts = pkt->pts;
#if FF_API_PKT_PTS
FF_DISABLE_DEPRECATION_WARNINGS
frame->pkt_pts = pkt->pts;
FF_ENABLE_DEPRECATION_WARNINGS
#endif
av_frame_set_pkt_pos (frame, pkt->pos);
av_frame_set_pkt_duration(frame, pkt->duration);
av_frame_set_pkt_size (frame, pkt->size);
for (i = 0; i < FF_ARRAY_ELEMS(sd); i++) {
int size;
uint8_t *packet_sd = av_packet_get_side_data(pkt, sd[i].packet, &size);
if (packet_sd) {
AVFrameSideData *frame_sd = av_frame_new_side_data(frame,
sd[i].frame,
size);
if (!frame_sd)
return AVERROR(ENOMEM);
memcpy(frame_sd->data, packet_sd, size);
}
}
add_metadata_from_side_data(pkt, frame);
if (pkt->flags & AV_PKT_FLAG_DISCARD) {
frame->flags |= AV_FRAME_FLAG_DISCARD;
} else {
frame->flags = (frame->flags & ~AV_FRAME_FLAG_DISCARD);
}
} else {
frame->pts = AV_NOPTS_VALUE;
#if FF_API_PKT_PTS
FF_DISABLE_DEPRECATION_WARNINGS
frame->pkt_pts = AV_NOPTS_VALUE;
FF_ENABLE_DEPRECATION_WARNINGS
#endif
av_frame_set_pkt_pos (frame, -1);
av_frame_set_pkt_duration(frame, 0);
av_frame_set_pkt_size (frame, -1);
}
frame->reordered_opaque = avctx->reordered_opaque;
if (frame->color_primaries == AVCOL_PRI_UNSPECIFIED)
frame->color_primaries = avctx->color_primaries;
if (frame->color_trc == AVCOL_TRC_UNSPECIFIED)
frame->color_trc = avctx->color_trc;
if (av_frame_get_colorspace(frame) == AVCOL_SPC_UNSPECIFIED)
av_frame_set_colorspace(frame, avctx->colorspace);
if (av_frame_get_color_range(frame) == AVCOL_RANGE_UNSPECIFIED)
av_frame_set_color_range(frame, avctx->color_range);
if (frame->chroma_location == AVCHROMA_LOC_UNSPECIFIED)
frame->chroma_location = avctx->chroma_sample_location;
switch (avctx->codec->type) {
case AVMEDIA_TYPE_VIDEO:
frame->format = avctx->pix_fmt;
if (!frame->sample_aspect_ratio.num)
frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
if (frame->width && frame->height &&
av_image_check_sar(frame->width, frame->height,
frame->sample_aspect_ratio) < 0) {
av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
frame->sample_aspect_ratio.num,
frame->sample_aspect_ratio.den);
frame->sample_aspect_ratio = (AVRational){ 0, 1 };
}
break;
case AVMEDIA_TYPE_AUDIO:
if (!frame->sample_rate)
frame->sample_rate = avctx->sample_rate;
if (frame->format < 0)
frame->format = avctx->sample_fmt;
if (!frame->channel_layout) {
if (avctx->channel_layout) {
if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=
avctx->channels) {
av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "
"configuration.\n");
return AVERROR(EINVAL);
}
frame->channel_layout = avctx->channel_layout;
} else {
if (avctx->channels > FF_SANE_NB_CHANNELS) {
av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",
avctx->channels);
return AVERROR(ENOSYS);
}
}
}
av_frame_set_channels(frame, avctx->channels);
break;
}
return 0;
}
int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame)
{
return ff_init_buffer_info(avctx, frame);
}
static void validate_avframe_allocation(AVCodecContext *avctx, AVFrame *frame)
{
if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
int i;
int num_planes = av_pix_fmt_count_planes(frame->format);
const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
int flags = desc ? desc->flags : 0;
if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PAL))
num_planes = 2;
for (i = 0; i < num_planes; i++) {
av_assert0(frame->data[i]);
}
// For now do not enforce anything for palette of pseudopal formats
if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PSEUDOPAL))
num_planes = 2;
// For formats without data like hwaccel allow unused pointers to be non-NULL.
for (i = num_planes; num_planes > 0 && i < FF_ARRAY_ELEMS(frame->data); i++) {
if (frame->data[i])
av_log(avctx, AV_LOG_ERROR, "Buffer returned by get_buffer2() did not zero unused plane pointers\n");
frame->data[i] = NULL;
}
}
}
static int get_buffer_internal(AVCodecContext *avctx, AVFrame *frame, int flags)
{
const AVHWAccel *hwaccel = avctx->hwaccel;
int override_dimensions = 1;
int ret;
if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
if ((ret = av_image_check_size2(avctx->width, avctx->height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx)) < 0 || avctx->pix_fmt<0) {
av_log(avctx, AV_LOG_ERROR, "video_get_buffer: image parameters invalid\n");
return AVERROR(EINVAL);
}
if (frame->width <= 0 || frame->height <= 0) {
frame->width = FFMAX(avctx->width, AV_CEIL_RSHIFT(avctx->coded_width, avctx->lowres));
frame->height = FFMAX(avctx->height, AV_CEIL_RSHIFT(avctx->coded_height, avctx->lowres));
override_dimensions = 0;
}
if (frame->data[0] || frame->data[1] || frame->data[2] || frame->data[3]) {
av_log(avctx, AV_LOG_ERROR, "pic->data[*]!=NULL in get_buffer_internal\n");
return AVERROR(EINVAL);
}
}
ret = ff_decode_frame_props(avctx, frame);
if (ret < 0)
return ret;
if (hwaccel) {
if (hwaccel->alloc_frame) {
ret = hwaccel->alloc_frame(avctx, frame);
goto end;
}
} else
avctx->sw_pix_fmt = avctx->pix_fmt;
ret = avctx->get_buffer2(avctx, frame, flags);
if (ret >= 0)
validate_avframe_allocation(avctx, frame);
end:
if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions) {
frame->width = avctx->width;
frame->height = avctx->height;
}
return ret;
}
int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
{
int ret = get_buffer_internal(avctx, frame, flags);
if (ret < 0) {
av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
frame->width = frame->height = 0;
}
return ret;
}
static int reget_buffer_internal(AVCodecContext *avctx, AVFrame *frame)
{
AVFrame *tmp;
int ret;
av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
if (frame->data[0] && (frame->width != avctx->width || frame->height != avctx->height || frame->format != avctx->pix_fmt)) {
av_log(avctx, AV_LOG_WARNING, "Picture changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s in reget buffer()\n",
frame->width, frame->height, av_get_pix_fmt_name(frame->format), avctx->width, avctx->height, av_get_pix_fmt_name(avctx->pix_fmt));
av_frame_unref(frame);
}
ff_init_buffer_info(avctx, frame);
if (!frame->data[0])
return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
if (av_frame_is_writable(frame))
return ff_decode_frame_props(avctx, frame);
tmp = av_frame_alloc();
if (!tmp)
return AVERROR(ENOMEM);
av_frame_move_ref(tmp, frame);
ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
if (ret < 0) {
av_frame_free(&tmp);
return ret;
}
av_frame_copy(frame, tmp);
av_frame_free(&tmp);
return 0;
}
int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame)
{
int ret = reget_buffer_internal(avctx, frame);
if (ret < 0)
av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
return ret;
}
int avcodec_default_execute(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2), void *arg, int *ret, int count, int size)
{
int i;
for (i = 0; i < count; i++) {
int r = func(c, (char *)arg + i * size);
if (ret)
ret[i] = r;
}
emms_c();
return 0;
}
int avcodec_default_execute2(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2, int jobnr, int threadnr), void *arg, int *ret, int count)
{
int i;
for (i = 0; i < count; i++) {
int r = func(c, arg, i, 0);
if (ret)
ret[i] = r;
}
emms_c();
return 0;
}
enum AVPixelFormat avpriv_find_pix_fmt(const PixelFormatTag *tags,
unsigned int fourcc)
{
while (tags->pix_fmt >= 0) {
if (tags->fourcc == fourcc)
return tags->pix_fmt;
tags++;
}
return AV_PIX_FMT_NONE;
}
static int is_hwaccel_pix_fmt(enum AVPixelFormat pix_fmt)
{
const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
return desc->flags & AV_PIX_FMT_FLAG_HWACCEL;
}
enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
{
while (*fmt != AV_PIX_FMT_NONE && is_hwaccel_pix_fmt(*fmt))
++fmt;
return fmt[0];
}
static AVHWAccel *find_hwaccel(enum AVCodecID codec_id,
enum AVPixelFormat pix_fmt)
{
AVHWAccel *hwaccel = NULL;
while ((hwaccel = av_hwaccel_next(hwaccel)))
if (hwaccel->id == codec_id
&& hwaccel->pix_fmt == pix_fmt)
return hwaccel;
return NULL;
}
static int setup_hwaccel(AVCodecContext *avctx,
const enum AVPixelFormat fmt,
const char *name)
{
AVHWAccel *hwa = find_hwaccel(avctx->codec_id, fmt);
int ret = 0;
if (avctx->active_thread_type & FF_THREAD_FRAME) {
av_log(avctx, AV_LOG_WARNING,
"Hardware accelerated decoding with frame threading is known to be unstable and its use is discouraged.\n");
}
if (!hwa) {
av_log(avctx, AV_LOG_ERROR,
"Could not find an AVHWAccel for the pixel format: %s",
name);
return AVERROR(ENOENT);
}
if (hwa->capabilities & HWACCEL_CODEC_CAP_EXPERIMENTAL &&
avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
av_log(avctx, AV_LOG_WARNING, "Ignoring experimental hwaccel: %s\n",
hwa->name);
return AVERROR_PATCHWELCOME;
}
if (hwa->priv_data_size) {
avctx->internal->hwaccel_priv_data = av_mallocz(hwa->priv_data_size);
if (!avctx->internal->hwaccel_priv_data)
return AVERROR(ENOMEM);
}
if (hwa->init) {
ret = hwa->init(avctx);
if (ret < 0) {
av_freep(&avctx->internal->hwaccel_priv_data);
return ret;
}
}
avctx->hwaccel = hwa;
return 0;
}
int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
{
const AVPixFmtDescriptor *desc;
enum AVPixelFormat *choices;
enum AVPixelFormat ret;
unsigned n = 0;
while (fmt[n] != AV_PIX_FMT_NONE)
++n;
av_assert0(n >= 1);
avctx->sw_pix_fmt = fmt[n - 1];
av_assert2(!is_hwaccel_pix_fmt(avctx->sw_pix_fmt));
choices = av_malloc_array(n + 1, sizeof(*choices));
if (!choices)
return AV_PIX_FMT_NONE;
memcpy(choices, fmt, (n + 1) * sizeof(*choices));
for (;;) {
if (avctx->hwaccel && avctx->hwaccel->uninit)
avctx->hwaccel->uninit(avctx);
av_freep(&avctx->internal->hwaccel_priv_data);
avctx->hwaccel = NULL;
av_buffer_unref(&avctx->hw_frames_ctx);
ret = avctx->get_format(avctx, choices);
desc = av_pix_fmt_desc_get(ret);
if (!desc) {
ret = AV_PIX_FMT_NONE;
break;
}
if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
break;
#if FF_API_CAP_VDPAU
if (avctx->codec->capabilities&AV_CODEC_CAP_HWACCEL_VDPAU)
break;
#endif
if (avctx->hw_frames_ctx) {
AVHWFramesContext *hw_frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
if (hw_frames_ctx->format != ret) {
av_log(avctx, AV_LOG_ERROR, "Format returned from get_buffer() "
"does not match the format of provided AVHWFramesContext\n");
ret = AV_PIX_FMT_NONE;
break;
}
}
if (!setup_hwaccel(avctx, ret, desc->name))
break;
/* Remove failed hwaccel from choices */
for (n = 0; choices[n] != ret; n++)
av_assert0(choices[n] != AV_PIX_FMT_NONE);
do
choices[n] = choices[n + 1];
while (choices[n++] != AV_PIX_FMT_NONE);
}
av_freep(&choices);
return ret;
}
MAKE_ACCESSORS(AVCodecContext, codec, AVRational, pkt_timebase)
MAKE_ACCESSORS(AVCodecContext, codec, const AVCodecDescriptor *, codec_descriptor)
MAKE_ACCESSORS(AVCodecContext, codec, int, lowres)
MAKE_ACCESSORS(AVCodecContext, codec, int, seek_preroll)
MAKE_ACCESSORS(AVCodecContext, codec, uint16_t*, chroma_intra_matrix)
unsigned av_codec_get_codec_properties(const AVCodecContext *codec)
{
return codec->properties;
}
int av_codec_get_max_lowres(const AVCodec *codec)
{
return codec->max_lowres;
}
int avpriv_codec_get_cap_skip_frame_fill_param(const AVCodec *codec){
return !!(codec->caps_internal & FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM);
}
static void get_subtitle_defaults(AVSubtitle *sub)
{
memset(sub, 0, sizeof(*sub));
sub->pts = AV_NOPTS_VALUE;
}
static int64_t get_bit_rate(AVCodecContext *ctx)
{
int64_t bit_rate;
int bits_per_sample;
switch (ctx->codec_type) {
case AVMEDIA_TYPE_VIDEO:
case AVMEDIA_TYPE_DATA:
case AVMEDIA_TYPE_SUBTITLE:
case AVMEDIA_TYPE_ATTACHMENT:
bit_rate = ctx->bit_rate;
break;
case AVMEDIA_TYPE_AUDIO:
bits_per_sample = av_get_bits_per_sample(ctx->codec_id);
bit_rate = bits_per_sample ? ctx->sample_rate * (int64_t)ctx->channels * bits_per_sample : ctx->bit_rate;
break;
default:
bit_rate = 0;
break;
}
return bit_rate;
}
int attribute_align_arg ff_codec_open2_recursive(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
{
int ret = 0;
ff_unlock_avcodec(codec);
ret = avcodec_open2(avctx, codec, options);
ff_lock_avcodec(avctx, codec);
return ret;
}
int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
{
int ret = 0;
AVDictionary *tmp = NULL;
const AVPixFmtDescriptor *pixdesc;
if (avcodec_is_open(avctx))
return 0;
if ((!codec && !avctx->codec)) {
av_log(avctx, AV_LOG_ERROR, "No codec provided to avcodec_open2()\n");
return AVERROR(EINVAL);
}
if ((codec && avctx->codec && codec != avctx->codec)) {
av_log(avctx, AV_LOG_ERROR, "This AVCodecContext was allocated for %s, "
"but %s passed to avcodec_open2()\n", avctx->codec->name, codec->name);
return AVERROR(EINVAL);
}
if (!codec)
codec = avctx->codec;
if (avctx->extradata_size < 0 || avctx->extradata_size >= FF_MAX_EXTRADATA_SIZE)
return AVERROR(EINVAL);
if (options)
av_dict_copy(&tmp, *options, 0);
ret = ff_lock_avcodec(avctx, codec);
if (ret < 0)
return ret;
avctx->internal = av_mallocz(sizeof(AVCodecInternal));
if (!avctx->internal) {
ret = AVERROR(ENOMEM);
goto end;
}
avctx->internal->pool = av_mallocz(sizeof(*avctx->internal->pool));
if (!avctx->internal->pool) {
ret = AVERROR(ENOMEM);
goto free_and_end;
}
avctx->internal->to_free = av_frame_alloc();
if (!avctx->internal->to_free) {
ret = AVERROR(ENOMEM);
goto free_and_end;
}
avctx->internal->buffer_frame = av_frame_alloc();
if (!avctx->internal->buffer_frame) {
ret = AVERROR(ENOMEM);
goto free_and_end;
}
avctx->internal->buffer_pkt = av_packet_alloc();
if (!avctx->internal->buffer_pkt) {
ret = AVERROR(ENOMEM);
goto free_and_end;
}
if (codec->priv_data_size > 0) {
if (!avctx->priv_data) {
avctx->priv_data = av_mallocz(codec->priv_data_size);
if (!avctx->priv_data) {
ret = AVERROR(ENOMEM);
goto end;
}
if (codec->priv_class) {
*(const AVClass **)avctx->priv_data = codec->priv_class;
av_opt_set_defaults(avctx->priv_data);
}
}
if (codec->priv_class && (ret = av_opt_set_dict(avctx->priv_data, &tmp)) < 0)
goto free_and_end;
} else {
avctx->priv_data = NULL;
}
if ((ret = av_opt_set_dict(avctx, &tmp)) < 0)
goto free_and_end;
if (avctx->codec_whitelist && av_match_list(codec->name, avctx->codec_whitelist, ',') <= 0) {
av_log(avctx, AV_LOG_ERROR, "Codec (%s) not on whitelist \'%s\'\n", codec->name, avctx->codec_whitelist);
ret = AVERROR(EINVAL);
goto free_and_end;
}
// only call ff_set_dimensions() for non H.264/VP6F/DXV codecs so as not to overwrite previously setup dimensions
if (!(avctx->coded_width && avctx->coded_height && avctx->width && avctx->height &&
(avctx->codec_id == AV_CODEC_ID_H264 || avctx->codec_id == AV_CODEC_ID_VP6F || avctx->codec_id == AV_CODEC_ID_DXV))) {
if (avctx->coded_width && avctx->coded_height)
ret = ff_set_dimensions(avctx, avctx->coded_width, avctx->coded_height);
else if (avctx->width && avctx->height)
ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
if (ret < 0)
goto free_and_end;
}
if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height)
&& ( av_image_check_size2(avctx->coded_width, avctx->coded_height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx) < 0
|| av_image_check_size2(avctx->width, avctx->height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx) < 0)) {
av_log(avctx, AV_LOG_WARNING, "Ignoring invalid width/height values\n");
ff_set_dimensions(avctx, 0, 0);
}
if (avctx->width > 0 && avctx->height > 0) {
if (av_image_check_sar(avctx->width, avctx->height,
avctx->sample_aspect_ratio) < 0) {
av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
avctx->sample_aspect_ratio.num,
avctx->sample_aspect_ratio.den);
avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
}
}
/* if the decoder init function was already called previously,
* free the already allocated subtitle_header before overwriting it */
if (av_codec_is_decoder(codec))
av_freep(&avctx->subtitle_header);
if (avctx->channels > FF_SANE_NB_CHANNELS) {
ret = AVERROR(EINVAL);
goto free_and_end;
}
avctx->codec = codec;
if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) &&
avctx->codec_id == AV_CODEC_ID_NONE) {
avctx->codec_type = codec->type;
avctx->codec_id = codec->id;
}
if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type
&& avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) {
av_log(avctx, AV_LOG_ERROR, "Codec type or id mismatches\n");
ret = AVERROR(EINVAL);
goto free_and_end;
}
avctx->frame_number = 0;
avctx->codec_descriptor = avcodec_descriptor_get(avctx->codec_id);
if ((avctx->codec->capabilities & AV_CODEC_CAP_EXPERIMENTAL) &&
avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
const char *codec_string = av_codec_is_encoder(codec) ? "encoder" : "decoder";
AVCodec *codec2;
av_log(avctx, AV_LOG_ERROR,
"The %s '%s' is experimental but experimental codecs are not enabled, "
"add '-strict %d' if you want to use it.\n",
codec_string, codec->name, FF_COMPLIANCE_EXPERIMENTAL);
codec2 = av_codec_is_encoder(codec) ? avcodec_find_encoder(codec->id) : avcodec_find_decoder(codec->id);
if (!(codec2->capabilities & AV_CODEC_CAP_EXPERIMENTAL))
av_log(avctx, AV_LOG_ERROR, "Alternatively use the non experimental %s '%s'.\n",
codec_string, codec2->name);
ret = AVERROR_EXPERIMENTAL;
goto free_and_end;
}
if (avctx->codec_type == AVMEDIA_TYPE_AUDIO &&
(!avctx->time_base.num || !avctx->time_base.den)) {
avctx->time_base.num = 1;
avctx->time_base.den = avctx->sample_rate;
}
if (!HAVE_THREADS)
av_log(avctx, AV_LOG_WARNING, "Warning: not compiled with thread support, using thread emulation\n");
if (CONFIG_FRAME_THREAD_ENCODER && av_codec_is_encoder(avctx->codec)) {
ff_unlock_avcodec(codec); //we will instantiate a few encoders thus kick the counter to prevent false detection of a problem
ret = ff_frame_thread_encoder_init(avctx, options ? *options : NULL);
ff_lock_avcodec(avctx, codec);
if (ret < 0)
goto free_and_end;
}
if (HAVE_THREADS
&& !(avctx->internal->frame_thread_encoder && (avctx->active_thread_type&FF_THREAD_FRAME))) {
ret = ff_thread_init(avctx);
if (ret < 0) {
goto free_and_end;
}
}
if (!HAVE_THREADS && !(codec->capabilities & AV_CODEC_CAP_AUTO_THREADS))
avctx->thread_count = 1;
if (avctx->codec->max_lowres < avctx->lowres || avctx->lowres < 0) {
av_log(avctx, AV_LOG_WARNING, "The maximum value for lowres supported by the decoder is %d\n",
avctx->codec->max_lowres);
avctx->lowres = avctx->codec->max_lowres;
}
#if FF_API_VISMV
if (avctx->debug_mv)
av_log(avctx, AV_LOG_WARNING, "The 'vismv' option is deprecated, "
"see the codecview filter instead.\n");
#endif
if (av_codec_is_encoder(avctx->codec)) {
int i;
#if FF_API_CODED_FRAME
FF_DISABLE_DEPRECATION_WARNINGS
avctx->coded_frame = av_frame_alloc();
if (!avctx->coded_frame) {
ret = AVERROR(ENOMEM);
goto free_and_end;
}
FF_ENABLE_DEPRECATION_WARNINGS
#endif
if (avctx->time_base.num <= 0 || avctx->time_base.den <= 0) {
av_log(avctx, AV_LOG_ERROR, "The encoder timebase is not set.\n");
ret = AVERROR(EINVAL);
goto free_and_end;
}
if (avctx->codec->sample_fmts) {
for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++) {
if (avctx->sample_fmt == avctx->codec->sample_fmts[i])
break;
if (avctx->channels == 1 &&
av_get_planar_sample_fmt(avctx->sample_fmt) ==
av_get_planar_sample_fmt(avctx->codec->sample_fmts[i])) {
avctx->sample_fmt = avctx->codec->sample_fmts[i];
break;
}
}
if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) {
char buf[128];
snprintf(buf, sizeof(buf), "%d", avctx->sample_fmt);
av_log(avctx, AV_LOG_ERROR, "Specified sample format %s is invalid or not supported\n",
(char *)av_x_if_null(av_get_sample_fmt_name(avctx->sample_fmt), buf));
ret = AVERROR(EINVAL);
goto free_and_end;
}
}
if (avctx->codec->pix_fmts) {
for (i = 0; avctx->codec->pix_fmts[i] != AV_PIX_FMT_NONE; i++)
if (avctx->pix_fmt == avctx->codec->pix_fmts[i])
break;
if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_NONE
&& !((avctx->codec_id == AV_CODEC_ID_MJPEG || avctx->codec_id == AV_CODEC_ID_LJPEG)
&& avctx->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL)) {
char buf[128];
snprintf(buf, sizeof(buf), "%d", avctx->pix_fmt);
av_log(avctx, AV_LOG_ERROR, "Specified pixel format %s is invalid or not supported\n",
(char *)av_x_if_null(av_get_pix_fmt_name(avctx->pix_fmt), buf));
ret = AVERROR(EINVAL);
goto free_and_end;
}
if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ420P ||
avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ411P ||
avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ422P ||
avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ440P ||
avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ444P)
avctx->color_range = AVCOL_RANGE_JPEG;
}
if (avctx->codec->supported_samplerates) {
for (i = 0; avctx->codec->supported_samplerates[i] != 0; i++)
if (avctx->sample_rate == avctx->codec->supported_samplerates[i])
break;
if (avctx->codec->supported_samplerates[i] == 0) {
av_log(avctx, AV_LOG_ERROR, "Specified sample rate %d is not supported\n",
avctx->sample_rate);
ret = AVERROR(EINVAL);
goto free_and_end;
}
}
if (avctx->sample_rate < 0) {
av_log(avctx, AV_LOG_ERROR, "Specified sample rate %d is not supported\n",
avctx->sample_rate);
ret = AVERROR(EINVAL);
goto free_and_end;
}
if (avctx->codec->channel_layouts) {
if (!avctx->channel_layout) {
av_log(avctx, AV_LOG_WARNING, "Channel layout not specified\n");
} else {
for (i = 0; avctx->codec->channel_layouts[i] != 0; i++)
if (avctx->channel_layout == avctx->codec->channel_layouts[i])
break;
if (avctx->codec->channel_layouts[i] == 0) {
char buf[512];
av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout);
av_log(avctx, AV_LOG_ERROR, "Specified channel layout '%s' is not supported\n", buf);
ret = AVERROR(EINVAL);
goto free_and_end;
}
}
}
if (avctx->channel_layout && avctx->channels) {
int channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
if (channels != avctx->channels) {
char buf[512];
av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout);
av_log(avctx, AV_LOG_ERROR,
"Channel layout '%s' with %d channels does not match number of specified channels %d\n",
buf, channels, avctx->channels);
ret = AVERROR(EINVAL);
goto free_and_end;
}
} else if (avctx->channel_layout) {
avctx->channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
}
if (avctx->channels < 0) {
av_log(avctx, AV_LOG_ERROR, "Specified number of channels %d is not supported\n",
avctx->channels);
ret = AVERROR(EINVAL);
goto free_and_end;
}
if(avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
pixdesc = av_pix_fmt_desc_get(avctx->pix_fmt);
if ( avctx->bits_per_raw_sample < 0
|| (avctx->bits_per_raw_sample > 8 && pixdesc->comp[0].depth <= 8)) {
av_log(avctx, AV_LOG_WARNING, "Specified bit depth %d not possible with the specified pixel formats depth %d\n",
avctx->bits_per_raw_sample, pixdesc->comp[0].depth);
avctx->bits_per_raw_sample = pixdesc->comp[0].depth;
}
if (avctx->width <= 0 || avctx->height <= 0) {
av_log(avctx, AV_LOG_ERROR, "dimensions not set\n");
ret = AVERROR(EINVAL);
goto free_and_end;
}
}
if ( (avctx->codec_type == AVMEDIA_TYPE_VIDEO || avctx->codec_type == AVMEDIA_TYPE_AUDIO)
&& avctx->bit_rate>0 && avctx->bit_rate<1000) {
av_log(avctx, AV_LOG_WARNING, "Bitrate %"PRId64" is extremely low, maybe you mean %"PRId64"k\n", (int64_t)avctx->bit_rate, (int64_t)avctx->bit_rate);
}
if (!avctx->rc_initial_buffer_occupancy)
avctx->rc_initial_buffer_occupancy = avctx->rc_buffer_size * 3 / 4;
if (avctx->ticks_per_frame && avctx->time_base.num &&
avctx->ticks_per_frame > INT_MAX / avctx->time_base.num) {
av_log(avctx, AV_LOG_ERROR,
"ticks_per_frame %d too large for the timebase %d/%d.",
avctx->ticks_per_frame,
avctx->time_base.num,
avctx->time_base.den);
goto free_and_end;
}
if (avctx->hw_frames_ctx) {
AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
if (frames_ctx->format != avctx->pix_fmt) {
av_log(avctx, AV_LOG_ERROR,
"Mismatching AVCodecContext.pix_fmt and AVHWFramesContext.format\n");
ret = AVERROR(EINVAL);
goto free_and_end;
}
}
}
avctx->pts_correction_num_faulty_pts =
avctx->pts_correction_num_faulty_dts = 0;
avctx->pts_correction_last_pts =
avctx->pts_correction_last_dts = INT64_MIN;
if ( !CONFIG_GRAY && avctx->flags & AV_CODEC_FLAG_GRAY
&& avctx->codec_descriptor->type == AVMEDIA_TYPE_VIDEO)
av_log(avctx, AV_LOG_WARNING,
"gray decoding requested but not enabled at configuration time\n");
if ( avctx->codec->init && (!(avctx->active_thread_type&FF_THREAD_FRAME)
|| avctx->internal->frame_thread_encoder)) {
ret = avctx->codec->init(avctx);
if (ret < 0) {
goto free_and_end;
}
}
ret=0;
#if FF_API_AUDIOENC_DELAY
if (av_codec_is_encoder(avctx->codec))
avctx->delay = avctx->initial_padding;
#endif
if (av_codec_is_decoder(avctx->codec)) {
if (!avctx->bit_rate)
avctx->bit_rate = get_bit_rate(avctx);
/* validate channel layout from the decoder */
if (avctx->channel_layout) {
int channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
if (!avctx->channels)
avctx->channels = channels;
else if (channels != avctx->channels) {
char buf[512];
av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout);
av_log(avctx, AV_LOG_WARNING,
"Channel layout '%s' with %d channels does not match specified number of channels %d: "
"ignoring specified channel layout\n",
buf, channels, avctx->channels);
avctx->channel_layout = 0;
}
}
if (avctx->channels && avctx->channels < 0 ||
avctx->channels > FF_SANE_NB_CHANNELS) {
ret = AVERROR(EINVAL);
goto free_and_end;
}
if (avctx->sub_charenc) {
if (avctx->codec_type != AVMEDIA_TYPE_SUBTITLE) {
av_log(avctx, AV_LOG_ERROR, "Character encoding is only "
"supported with subtitles codecs\n");
ret = AVERROR(EINVAL);
goto free_and_end;
} else if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB) {
av_log(avctx, AV_LOG_WARNING, "Codec '%s' is bitmap-based, "
"subtitles character encoding will be ignored\n",
avctx->codec_descriptor->name);
avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_DO_NOTHING;
} else {
/* input character encoding is set for a text based subtitle
* codec at this point */
if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_AUTOMATIC)
avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_PRE_DECODER;
if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_PRE_DECODER) {
#if CONFIG_ICONV
iconv_t cd = iconv_open("UTF-8", avctx->sub_charenc);
if (cd == (iconv_t)-1) {
ret = AVERROR(errno);
av_log(avctx, AV_LOG_ERROR, "Unable to open iconv context "
"with input character encoding \"%s\"\n", avctx->sub_charenc);
goto free_and_end;
}
iconv_close(cd);
#else
av_log(avctx, AV_LOG_ERROR, "Character encoding subtitles "
"conversion needs a libavcodec built with iconv support "
"for this codec\n");
ret = AVERROR(ENOSYS);
goto free_and_end;
#endif
}
}
}
#if FF_API_AVCTX_TIMEBASE
if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1}));
#endif
}
if (codec->priv_data_size > 0 && avctx->priv_data && codec->priv_class) {
av_assert0(*(const AVClass **)avctx->priv_data == codec->priv_class);
}
end:
ff_unlock_avcodec(codec);
if (options) {
av_dict_free(options);
*options = tmp;
}
return ret;
free_and_end:
if (avctx->codec &&
(avctx->codec->caps_internal & FF_CODEC_CAP_INIT_CLEANUP))
avctx->codec->close(avctx);
if (codec->priv_class && codec->priv_data_size)
av_opt_free(avctx->priv_data);
av_opt_free(avctx);
#if FF_API_CODED_FRAME
FF_DISABLE_DEPRECATION_WARNINGS
av_frame_free(&avctx->coded_frame);
FF_ENABLE_DEPRECATION_WARNINGS
#endif
av_dict_free(&tmp);
av_freep(&avctx->priv_data);
if (avctx->internal) {
av_packet_free(&avctx->internal->buffer_pkt);
av_frame_free(&avctx->internal->buffer_frame);
av_frame_free(&avctx->internal->to_free);
av_freep(&avctx->internal->pool);
}
av_freep(&avctx->internal);
avctx->codec = NULL;
goto end;
}
int ff_alloc_packet2(AVCodecContext *avctx, AVPacket *avpkt, int64_t size, int64_t min_size)
{
if (avpkt->size < 0) {
av_log(avctx, AV_LOG_ERROR, "Invalid negative user packet size %d\n", avpkt->size);
return AVERROR(EINVAL);
}
if (size < 0 || size > INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE) {
av_log(avctx, AV_LOG_ERROR, "Invalid minimum required packet size %"PRId64" (max allowed is %d)\n",
size, INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE);
return AVERROR(EINVAL);
}
if (avctx && 2*min_size < size) { // FIXME The factor needs to be finetuned
av_assert0(!avpkt->data || avpkt->data != avctx->internal->byte_buffer);
if (!avpkt->data || avpkt->size < size) {
av_fast_padded_malloc(&avctx->internal->byte_buffer, &avctx->internal->byte_buffer_size, size);
avpkt->data = avctx->internal->byte_buffer;
avpkt->size = avctx->internal->byte_buffer_size;
}
}
if (avpkt->data) {
AVBufferRef *buf = avpkt->buf;
if (avpkt->size < size) {
av_log(avctx, AV_LOG_ERROR, "User packet is too small (%d < %"PRId64")\n", avpkt->size, size);
return AVERROR(EINVAL);
}
av_init_packet(avpkt);
avpkt->buf = buf;
avpkt->size = size;
return 0;
} else {
int ret = av_new_packet(avpkt, size);
if (ret < 0)
av_log(avctx, AV_LOG_ERROR, "Failed to allocate packet of size %"PRId64"\n", size);
return ret;
}
}
int ff_alloc_packet(AVPacket *avpkt, int size)
{
return ff_alloc_packet2(NULL, avpkt, size, 0);
}
/**
* Pad last frame with silence.
*/
static int pad_last_frame(AVCodecContext *s, AVFrame **dst, const AVFrame *src)
{
AVFrame *frame = NULL;
int ret;
if (!(frame = av_frame_alloc()))
return AVERROR(ENOMEM);
frame->format = src->format;
frame->channel_layout = src->channel_layout;
av_frame_set_channels(frame, av_frame_get_channels(src));
frame->nb_samples = s->frame_size;
ret = av_frame_get_buffer(frame, 32);
if (ret < 0)
goto fail;
ret = av_frame_copy_props(frame, src);
if (ret < 0)
goto fail;
if ((ret = av_samples_copy(frame->extended_data, src->extended_data, 0, 0,
src->nb_samples, s->channels, s->sample_fmt)) < 0)
goto fail;
if ((ret = av_samples_set_silence(frame->extended_data, src->nb_samples,
frame->nb_samples - src->nb_samples,
s->channels, s->sample_fmt)) < 0)
goto fail;
*dst = frame;
return 0;
fail:
av_frame_free(&frame);
return ret;
}
int attribute_align_arg avcodec_encode_audio2(AVCodecContext *avctx,
AVPacket *avpkt,
const AVFrame *frame,
int *got_packet_ptr)
{
AVFrame *extended_frame = NULL;
AVFrame *padded_frame = NULL;
int ret;
AVPacket user_pkt = *avpkt;
int needs_realloc = !user_pkt.data;
*got_packet_ptr = 0;
if (!avctx->codec->encode2) {
av_log(avctx, AV_LOG_ERROR, "This encoder requires using the avcodec_send_frame() API.\n");
return AVERROR(ENOSYS);
}
if (!(avctx->codec->capabilities & AV_CODEC_CAP_DELAY) && !frame) {
av_packet_unref(avpkt);
av_init_packet(avpkt);
return 0;
}
/* ensure that extended_data is properly set */
if (frame && !frame->extended_data) {
if (av_sample_fmt_is_planar(avctx->sample_fmt) &&
avctx->channels > AV_NUM_DATA_POINTERS) {
av_log(avctx, AV_LOG_ERROR, "Encoding to a planar sample format, "
"with more than %d channels, but extended_data is not set.\n",
AV_NUM_DATA_POINTERS);
return AVERROR(EINVAL);
}
av_log(avctx, AV_LOG_WARNING, "extended_data is not set.\n");
extended_frame = av_frame_alloc();
if (!extended_frame)
return AVERROR(ENOMEM);
memcpy(extended_frame, frame, sizeof(AVFrame));
extended_frame->extended_data = extended_frame->data;
frame = extended_frame;
}
/* extract audio service type metadata */
if (frame) {
AVFrameSideData *sd = av_frame_get_side_data(frame, AV_FRAME_DATA_AUDIO_SERVICE_TYPE);
if (sd && sd->size >= sizeof(enum AVAudioServiceType))
avctx->audio_service_type = *(enum AVAudioServiceType*)sd->data;
}
/* check for valid frame size */
if (frame) {
if (avctx->codec->capabilities & AV_CODEC_CAP_SMALL_LAST_FRAME) {
if (frame->nb_samples > avctx->frame_size) {
av_log(avctx, AV_LOG_ERROR, "more samples than frame size (avcodec_encode_audio2)\n");
ret = AVERROR(EINVAL);
goto end;
}
} else if (!(avctx->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE)) {
if (frame->nb_samples < avctx->frame_size &&
!avctx->internal->last_audio_frame) {
ret = pad_last_frame(avctx, &padded_frame, frame);
if (ret < 0)
goto end;
frame = padded_frame;
avctx->internal->last_audio_frame = 1;
}
if (frame->nb_samples != avctx->frame_size) {
av_log(avctx, AV_LOG_ERROR, "nb_samples (%d) != frame_size (%d) (avcodec_encode_audio2)\n", frame->nb_samples, avctx->frame_size);
ret = AVERROR(EINVAL);
goto end;
}
}
}
av_assert0(avctx->codec->encode2);
ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
if (!ret) {
if (*got_packet_ptr) {
if (!(avctx->codec->capabilities & AV_CODEC_CAP_DELAY)) {
if (avpkt->pts == AV_NOPTS_VALUE)
avpkt->pts = frame->pts;
if (!avpkt->duration)
avpkt->duration = ff_samples_to_time_base(avctx,
frame->nb_samples);
}
avpkt->dts = avpkt->pts;
} else {
avpkt->size = 0;
}
}
if (avpkt->data && avpkt->data == avctx->internal->byte_buffer) {
needs_realloc = 0;
if (user_pkt.data) {
if (user_pkt.size >= avpkt->size) {
memcpy(user_pkt.data, avpkt->data, avpkt->size);
} else {
av_log(avctx, AV_LOG_ERROR, "Provided packet is too small, needs to be %d\n", avpkt->size);
avpkt->size = user_pkt.size;
ret = -1;
}
avpkt->buf = user_pkt.buf;
avpkt->data = user_pkt.data;
} else {
if (av_dup_packet(avpkt) < 0) {
ret = AVERROR(ENOMEM);
}
}
}
if (!ret) {
if (needs_realloc && avpkt->data) {
ret = av_buffer_realloc(&avpkt->buf, avpkt->size + AV_INPUT_BUFFER_PADDING_SIZE);
if (ret >= 0)
avpkt->data = avpkt->buf->data;
}
avctx->frame_number++;
}
if (ret < 0 || !*got_packet_ptr) {
av_packet_unref(avpkt);
av_init_packet(avpkt);
goto end;
}
/* NOTE: if we add any audio encoders which output non-keyframe packets,
* this needs to be moved to the encoders, but for now we can do it
* here to simplify things */
avpkt->flags |= AV_PKT_FLAG_KEY;
end:
av_frame_free(&padded_frame);
av_free(extended_frame);
#if FF_API_AUDIOENC_DELAY
avctx->delay = avctx->initial_padding;
#endif
return ret;
}
int attribute_align_arg avcodec_encode_video2(AVCodecContext *avctx,
AVPacket *avpkt,
const AVFrame *frame,
int *got_packet_ptr)
{
int ret;
AVPacket user_pkt = *avpkt;
int needs_realloc = !user_pkt.data;
*got_packet_ptr = 0;
if (!avctx->codec->encode2) {
av_log(avctx, AV_LOG_ERROR, "This encoder requires using the avcodec_send_frame() API.\n");
return AVERROR(ENOSYS);
}
if(CONFIG_FRAME_THREAD_ENCODER &&
avctx->internal->frame_thread_encoder && (avctx->active_thread_type&FF_THREAD_FRAME))
return ff_thread_video_encode_frame(avctx, avpkt, frame, got_packet_ptr);
if ((avctx->flags&AV_CODEC_FLAG_PASS1) && avctx->stats_out)
avctx->stats_out[0] = '\0';
if (!(avctx->codec->capabilities & AV_CODEC_CAP_DELAY) && !frame) {
av_packet_unref(avpkt);
av_init_packet(avpkt);
avpkt->size = 0;
return 0;
}
if (av_image_check_size2(avctx->width, avctx->height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx))
return AVERROR(EINVAL);
if (frame && frame->format == AV_PIX_FMT_NONE)
av_log(avctx, AV_LOG_WARNING, "AVFrame.format is not set\n");
if (frame && (frame->width == 0 || frame->height == 0))
av_log(avctx, AV_LOG_WARNING, "AVFrame.width or height is not set\n");
av_assert0(avctx->codec->encode2);
ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
av_assert0(ret <= 0);
emms_c();
if (avpkt->data && avpkt->data == avctx->internal->byte_buffer) {
needs_realloc = 0;
if (user_pkt.data) {
if (user_pkt.size >= avpkt->size) {
memcpy(user_pkt.data, avpkt->data, avpkt->size);
} else {
av_log(avctx, AV_LOG_ERROR, "Provided packet is too small, needs to be %d\n", avpkt->size);
avpkt->size = user_pkt.size;
ret = -1;
}
avpkt->buf = user_pkt.buf;
avpkt->data = user_pkt.data;
} else {
if (av_dup_packet(avpkt) < 0) {
ret = AVERROR(ENOMEM);
}
}
}
if (!ret) {
if (!*got_packet_ptr)
avpkt->size = 0;
else if (!(avctx->codec->capabilities & AV_CODEC_CAP_DELAY))
avpkt->pts = avpkt->dts = frame->pts;
if (needs_realloc && avpkt->data) {
ret = av_buffer_realloc(&avpkt->buf, avpkt->size + AV_INPUT_BUFFER_PADDING_SIZE);
if (ret >= 0)
avpkt->data = avpkt->buf->data;
}
avctx->frame_number++;
}
if (ret < 0 || !*got_packet_ptr)
av_packet_unref(avpkt);
return ret;
}
int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size,
const AVSubtitle *sub)
{
int ret;
if (sub->start_display_time) {
av_log(avctx, AV_LOG_ERROR, "start_display_time must be 0.\n");
return -1;
}
ret = avctx->codec->encode_sub(avctx, buf, buf_size, sub);
avctx->frame_number++;
return ret;
}
/**
* Attempt to guess proper monotonic timestamps for decoded video frames
* which might have incorrect times. Input timestamps may wrap around, in
* which case the output will as well.
*
* @param pts the pts field of the decoded AVPacket, as passed through
* AVFrame.pts
* @param dts the dts field of the decoded AVPacket
* @return one of the input values, may be AV_NOPTS_VALUE
*/
static int64_t guess_correct_pts(AVCodecContext *ctx,
int64_t reordered_pts, int64_t dts)
{
int64_t pts = AV_NOPTS_VALUE;
if (dts != AV_NOPTS_VALUE) {
ctx->pts_correction_num_faulty_dts += dts <= ctx->pts_correction_last_dts;
ctx->pts_correction_last_dts = dts;
} else if (reordered_pts != AV_NOPTS_VALUE)
ctx->pts_correction_last_dts = reordered_pts;
if (reordered_pts != AV_NOPTS_VALUE) {
ctx->pts_correction_num_faulty_pts += reordered_pts <= ctx->pts_correction_last_pts;
ctx->pts_correction_last_pts = reordered_pts;
} else if(dts != AV_NOPTS_VALUE)
ctx->pts_correction_last_pts = dts;
if ((ctx->pts_correction_num_faulty_pts<=ctx->pts_correction_num_faulty_dts || dts == AV_NOPTS_VALUE)
&& reordered_pts != AV_NOPTS_VALUE)
pts = reordered_pts;
else
pts = dts;
return pts;
}
static int apply_param_change(AVCodecContext *avctx, AVPacket *avpkt)
{
int size = 0, ret;
const uint8_t *data;
uint32_t flags;
int64_t val;
data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
if (!data)
return 0;
if (!(avctx->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE)) {
av_log(avctx, AV_LOG_ERROR, "This decoder does not support parameter "
"changes, but PARAM_CHANGE side data was sent to it.\n");
ret = AVERROR(EINVAL);
goto fail2;
}
if (size < 4)
goto fail;
flags = bytestream_get_le32(&data);
size -= 4;
if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
if (size < 4)
goto fail;
val = bytestream_get_le32(&data);
if (val <= 0 || val > INT_MAX) {
av_log(avctx, AV_LOG_ERROR, "Invalid channel count");
ret = AVERROR_INVALIDDATA;
goto fail2;
}
avctx->channels = val;
size -= 4;
}
if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
if (size < 8)
goto fail;
avctx->channel_layout = bytestream_get_le64(&data);
size -= 8;
}
if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
if (size < 4)
goto fail;
val = bytestream_get_le32(&data);
if (val <= 0 || val > INT_MAX) {
av_log(avctx, AV_LOG_ERROR, "Invalid sample rate");
ret = AVERROR_INVALIDDATA;
goto fail2;
}
avctx->sample_rate = val;
size -= 4;
}
if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
if (size < 8)
goto fail;
avctx->width = bytestream_get_le32(&data);
avctx->height = bytestream_get_le32(&data);
size -= 8;
ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
if (ret < 0)
goto fail2;
}
return 0;
fail:
av_log(avctx, AV_LOG_ERROR, "PARAM_CHANGE side data too small.\n");
ret = AVERROR_INVALIDDATA;
fail2:
if (ret < 0) {
av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");
if (avctx->err_recognition & AV_EF_EXPLODE)
return ret;
}
return 0;
}
static int unrefcount_frame(AVCodecInternal *avci, AVFrame *frame)
{
int ret;
/* move the original frame to our backup */
av_frame_unref(avci->to_free);
av_frame_move_ref(avci->to_free, frame);
/* now copy everything except the AVBufferRefs back
* note that we make a COPY of the side data, so calling av_frame_free() on
* the caller's frame will work properly */
ret = av_frame_copy_props(frame, avci->to_free);
if (ret < 0)
return ret;
memcpy(frame->data, avci->to_free->data, sizeof(frame->data));
memcpy(frame->linesize, avci->to_free->linesize, sizeof(frame->linesize));
if (avci->to_free->extended_data != avci->to_free->data) {
int planes = av_frame_get_channels(avci->to_free);
int size = planes * sizeof(*frame->extended_data);
if (!size) {
av_frame_unref(frame);
return AVERROR_BUG;
}
frame->extended_data = av_malloc(size);
if (!frame->extended_data) {
av_frame_unref(frame);
return AVERROR(ENOMEM);
}
memcpy(frame->extended_data, avci->to_free->extended_data,
size);
} else
frame->extended_data = frame->data;
frame->format = avci->to_free->format;
frame->width = avci->to_free->width;
frame->height = avci->to_free->height;
frame->channel_layout = avci->to_free->channel_layout;
frame->nb_samples = avci->to_free->nb_samples;
av_frame_set_channels(frame, av_frame_get_channels(avci->to_free));
return 0;
}
int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
int *got_picture_ptr,
const AVPacket *avpkt)
{
AVCodecInternal *avci = avctx->internal;
int ret;
// copy to ensure we do not change avpkt
AVPacket tmp = *avpkt;
if (!avctx->codec)
return AVERROR(EINVAL);
if (avctx->codec->type != AVMEDIA_TYPE_VIDEO) {
av_log(avctx, AV_LOG_ERROR, "Invalid media type for video\n");
return AVERROR(EINVAL);
}
if (!avctx->codec->decode) {
av_log(avctx, AV_LOG_ERROR, "This decoder requires using the avcodec_send_packet() API.\n");
return AVERROR(ENOSYS);
}
*got_picture_ptr = 0;
if ((avctx->coded_width || avctx->coded_height) && av_image_check_size2(avctx->coded_width, avctx->coded_height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx))
return AVERROR(EINVAL);
avctx->internal->pkt = avpkt;
ret = apply_param_change(avctx, avpkt);
if (ret < 0)
return ret;
av_frame_unref(picture);
if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size ||
(avctx->active_thread_type & FF_THREAD_FRAME)) {
int did_split = av_packet_split_side_data(&tmp);
ret = apply_param_change(avctx, &tmp);
if (ret < 0)
goto fail;
avctx->internal->pkt = &tmp;
if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
ret = ff_thread_decode_frame(avctx, picture, got_picture_ptr,
&tmp);
else {
ret = avctx->codec->decode(avctx, picture, got_picture_ptr,
&tmp);
if (!(avctx->codec->caps_internal & FF_CODEC_CAP_SETS_PKT_DTS))
picture->pkt_dts = avpkt->dts;
if(!avctx->has_b_frames){
av_frame_set_pkt_pos(picture, avpkt->pos);
}
//FIXME these should be under if(!avctx->has_b_frames)
/* get_buffer is supposed to set frame parameters */
if (!(avctx->codec->capabilities & AV_CODEC_CAP_DR1)) {
if (!picture->sample_aspect_ratio.num) picture->sample_aspect_ratio = avctx->sample_aspect_ratio;
if (!picture->width) picture->width = avctx->width;
if (!picture->height) picture->height = avctx->height;
if (picture->format == AV_PIX_FMT_NONE) picture->format = avctx->pix_fmt;
}
}
fail:
emms_c(); //needed to avoid an emms_c() call before every return;
avctx->internal->pkt = NULL;
if (did_split) {
av_packet_free_side_data(&tmp);
if(ret == tmp.size)
ret = avpkt->size;
}
if (picture->flags & AV_FRAME_FLAG_DISCARD) {
*got_picture_ptr = 0;
}
if (*got_picture_ptr) {
if (!avctx->refcounted_frames) {
int err = unrefcount_frame(avci, picture);
if (err < 0)
return err;
}
avctx->frame_number++;
av_frame_set_best_effort_timestamp(picture,
guess_correct_pts(avctx,
picture->pts,
picture->pkt_dts));
} else
av_frame_unref(picture);
} else
ret = 0;
/* many decoders assign whole AVFrames, thus overwriting extended_data;
* make sure it's set correctly */
av_assert0(!picture->extended_data || picture->extended_data == picture->data);
#if FF_API_AVCTX_TIMEBASE
if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1}));
#endif
return ret;
}
int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
AVFrame *frame,
int *got_frame_ptr,
const AVPacket *avpkt)
{
AVCodecInternal *avci = avctx->internal;
int ret = 0;
*got_frame_ptr = 0;
if (!avctx->codec)
return AVERROR(EINVAL);
if (!avctx->codec->decode) {
av_log(avctx, AV_LOG_ERROR, "This decoder requires using the avcodec_send_packet() API.\n");
return AVERROR(ENOSYS);
}
if (!avpkt->data && avpkt->size) {
av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
return AVERROR(EINVAL);
}
if (avctx->codec->type != AVMEDIA_TYPE_AUDIO) {
av_log(avctx, AV_LOG_ERROR, "Invalid media type for audio\n");
return AVERROR(EINVAL);
}
av_frame_unref(frame);
if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type & FF_THREAD_FRAME)) {
uint8_t *side;
int side_size;
uint32_t discard_padding = 0;
uint8_t skip_reason = 0;
uint8_t discard_reason = 0;
// copy to ensure we do not change avpkt
AVPacket tmp = *avpkt;
int did_split = av_packet_split_side_data(&tmp);
ret = apply_param_change(avctx, &tmp);
if (ret < 0)
goto fail;
avctx->internal->pkt = &tmp;
if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
ret = ff_thread_decode_frame(avctx, frame, got_frame_ptr, &tmp);
else {
ret = avctx->codec->decode(avctx, frame, got_frame_ptr, &tmp);
av_assert0(ret <= tmp.size);
frame->pkt_dts = avpkt->dts;
}
if (ret >= 0 && *got_frame_ptr) {
avctx->frame_number++;
av_frame_set_best_effort_timestamp(frame,
guess_correct_pts(avctx,
frame->pts,
frame->pkt_dts));
if (frame->format == AV_SAMPLE_FMT_NONE)
frame->format = avctx->sample_fmt;
if (!frame->channel_layout)
frame->channel_layout = avctx->channel_layout;
if (!av_frame_get_channels(frame))
av_frame_set_channels(frame, avctx->channels);
if (!frame->sample_rate)
frame->sample_rate = avctx->sample_rate;
}
side= av_packet_get_side_data(avctx->internal->pkt, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
if(side && side_size>=10) {
avctx->internal->skip_samples = AV_RL32(side);
discard_padding = AV_RL32(side + 4);
av_log(avctx, AV_LOG_DEBUG, "skip %d / discard %d samples due to side data\n",
avctx->internal->skip_samples, (int)discard_padding);
skip_reason = AV_RL8(side + 8);
discard_reason = AV_RL8(side + 9);
}
if ((frame->flags & AV_FRAME_FLAG_DISCARD) && *got_frame_ptr &&
!(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
avctx->internal->skip_samples = FFMAX(0, avctx->internal->skip_samples - frame->nb_samples);
*got_frame_ptr = 0;
}
if (avctx->internal->skip_samples > 0 && *got_frame_ptr &&
!(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
if(frame->nb_samples <= avctx->internal->skip_samples){
*got_frame_ptr = 0;
avctx->internal->skip_samples -= frame->nb_samples;
av_log(avctx, AV_LOG_DEBUG, "skip whole frame, skip left: %d\n",
avctx->internal->skip_samples);
} else {
av_samples_copy(frame->extended_data, frame->extended_data, 0, avctx->internal->skip_samples,
frame->nb_samples - avctx->internal->skip_samples, avctx->channels, frame->format);
if(avctx->pkt_timebase.num && avctx->sample_rate) {
int64_t diff_ts = av_rescale_q(avctx->internal->skip_samples,
(AVRational){1, avctx->sample_rate},
avctx->pkt_timebase);
if(frame->pts!=AV_NOPTS_VALUE)
frame->pts += diff_ts;
#if FF_API_PKT_PTS
FF_DISABLE_DEPRECATION_WARNINGS
if(frame->pkt_pts!=AV_NOPTS_VALUE)
frame->pkt_pts += diff_ts;
FF_ENABLE_DEPRECATION_WARNINGS
#endif
if(frame->pkt_dts!=AV_NOPTS_VALUE)
frame->pkt_dts += diff_ts;
if (av_frame_get_pkt_duration(frame) >= diff_ts)
av_frame_set_pkt_duration(frame, av_frame_get_pkt_duration(frame) - diff_ts);
} else {
av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for skipped samples.\n");
}
av_log(avctx, AV_LOG_DEBUG, "skip %d/%d samples\n",
avctx->internal->skip_samples, frame->nb_samples);
frame->nb_samples -= avctx->internal->skip_samples;
avctx->internal->skip_samples = 0;
}
}
if (discard_padding > 0 && discard_padding <= frame->nb_samples && *got_frame_ptr &&
!(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
if (discard_padding == frame->nb_samples) {
*got_frame_ptr = 0;
} else {
if(avctx->pkt_timebase.num && avctx->sample_rate) {
int64_t diff_ts = av_rescale_q(frame->nb_samples - discard_padding,
(AVRational){1, avctx->sample_rate},
avctx->pkt_timebase);
av_frame_set_pkt_duration(frame, diff_ts);
} else {
av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for discarded samples.\n");
}
av_log(avctx, AV_LOG_DEBUG, "discard %d/%d samples\n",
(int)discard_padding, frame->nb_samples);
frame->nb_samples -= discard_padding;
}
}
if ((avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL) && *got_frame_ptr) {
AVFrameSideData *fside = av_frame_new_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES, 10);
if (fside) {
AV_WL32(fside->data, avctx->internal->skip_samples);
AV_WL32(fside->data + 4, discard_padding);
AV_WL8(fside->data + 8, skip_reason);
AV_WL8(fside->data + 9, discard_reason);
avctx->internal->skip_samples = 0;
}
}
fail:
avctx->internal->pkt = NULL;
if (did_split) {
av_packet_free_side_data(&tmp);
if(ret == tmp.size)
ret = avpkt->size;
}
if (ret >= 0 && *got_frame_ptr) {
if (!avctx->refcounted_frames) {
int err = unrefcount_frame(avci, frame);
if (err < 0)
return err;
}
} else
av_frame_unref(frame);
}
av_assert0(ret <= avpkt->size);
if (!avci->showed_multi_packet_warning &&
ret >= 0 && ret != avpkt->size && !(avctx->codec->capabilities & AV_CODEC_CAP_SUBFRAMES)) {
av_log(avctx, AV_LOG_WARNING, "Multiple frames in a packet.\n");
avci->showed_multi_packet_warning = 1;
}
return ret;
}
#define UTF8_MAX_BYTES 4 /* 5 and 6 bytes sequences should not be used */
static int recode_subtitle(AVCodecContext *avctx,
AVPacket *outpkt, const AVPacket *inpkt)
{
#if CONFIG_ICONV
iconv_t cd = (iconv_t)-1;
int ret = 0;
char *inb, *outb;
size_t inl, outl;
AVPacket tmp;
#endif
if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_PRE_DECODER || inpkt->size == 0)
return 0;
#if CONFIG_ICONV
cd = iconv_open("UTF-8", avctx->sub_charenc);
av_assert0(cd != (iconv_t)-1);
inb = inpkt->data;
inl = inpkt->size;
if (inl >= INT_MAX / UTF8_MAX_BYTES - AV_INPUT_BUFFER_PADDING_SIZE) {
av_log(avctx, AV_LOG_ERROR, "Subtitles packet is too big for recoding\n");
ret = AVERROR(ENOMEM);
goto end;
}
ret = av_new_packet(&tmp, inl * UTF8_MAX_BYTES);
if (ret < 0)
goto end;
outpkt->buf = tmp.buf;
outpkt->data = tmp.data;
outpkt->size = tmp.size;
outb = outpkt->data;
outl = outpkt->size;
if (iconv(cd, &inb, &inl, &outb, &outl) == (size_t)-1 ||
iconv(cd, NULL, NULL, &outb, &outl) == (size_t)-1 ||
outl >= outpkt->size || inl != 0) {
ret = FFMIN(AVERROR(errno), -1);
av_log(avctx, AV_LOG_ERROR, "Unable to recode subtitle event \"%s\" "
"from %s to UTF-8\n", inpkt->data, avctx->sub_charenc);
av_packet_unref(&tmp);
goto end;
}
outpkt->size -= outl;
memset(outpkt->data + outpkt->size, 0, outl);
end:
if (cd != (iconv_t)-1)
iconv_close(cd);
return ret;
#else
av_log(avctx, AV_LOG_ERROR, "requesting subtitles recoding without iconv");
return AVERROR(EINVAL);
#endif
}
static int utf8_check(const uint8_t *str)
{
const uint8_t *byte;
uint32_t codepoint, min;
while (*str) {
byte = str;
GET_UTF8(codepoint, *(byte++), return 0;);
min = byte - str == 1 ? 0 : byte - str == 2 ? 0x80 :
1 << (5 * (byte - str) - 4);
if (codepoint < min || codepoint >= 0x110000 ||
codepoint == 0xFFFE /* BOM */ ||
codepoint >= 0xD800 && codepoint <= 0xDFFF /* surrogates */)
return 0;
str = byte;
}
return 1;
}
#if FF_API_ASS_TIMING
static void insert_ts(AVBPrint *buf, int ts)
{
if (ts == -1) {
av_bprintf(buf, "9:59:59.99,");
} else {
int h, m, s;
h = ts/360000; ts -= 360000*h;
m = ts/ 6000; ts -= 6000*m;
s = ts/ 100; ts -= 100*s;
av_bprintf(buf, "%d:%02d:%02d.%02d,", h, m, s, ts);
}
}
static int convert_sub_to_old_ass_form(AVSubtitle *sub, const AVPacket *pkt, AVRational tb)
{
int i;
AVBPrint buf;
av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
for (i = 0; i < sub->num_rects; i++) {
char *final_dialog;
const char *dialog;
AVSubtitleRect *rect = sub->rects[i];
int ts_start, ts_duration = -1;
long int layer;
if (rect->type != SUBTITLE_ASS || !strncmp(rect->ass, "Dialogue: ", 10))
continue;
av_bprint_clear(&buf);
/* skip ReadOrder */
dialog = strchr(rect->ass, ',');
if (!dialog)
continue;
dialog++;
/* extract Layer or Marked */
layer = strtol(dialog, (char**)&dialog, 10);
if (*dialog != ',')
continue;
dialog++;
/* rescale timing to ASS time base (ms) */
ts_start = av_rescale_q(pkt->pts, tb, av_make_q(1, 100));
if (pkt->duration != -1)
ts_duration = av_rescale_q(pkt->duration, tb, av_make_q(1, 100));
sub->end_display_time = FFMAX(sub->end_display_time, 10 * ts_duration);
/* construct ASS (standalone file form with timestamps) string */
av_bprintf(&buf, "Dialogue: %ld,", layer);
insert_ts(&buf, ts_start);
insert_ts(&buf, ts_duration == -1 ? -1 : ts_start + ts_duration);
av_bprintf(&buf, "%s\r\n", dialog);
final_dialog = av_strdup(buf.str);
if (!av_bprint_is_complete(&buf) || !final_dialog) {
av_freep(&final_dialog);
av_bprint_finalize(&buf, NULL);
return AVERROR(ENOMEM);
}
av_freep(&rect->ass);
rect->ass = final_dialog;
}
av_bprint_finalize(&buf, NULL);
return 0;
}
#endif
int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
int *got_sub_ptr,
AVPacket *avpkt)
{
int i, ret = 0;
if (!avpkt->data && avpkt->size) {
av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
return AVERROR(EINVAL);
}
if (!avctx->codec)
return AVERROR(EINVAL);
if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) {
av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n");
return AVERROR(EINVAL);
}
*got_sub_ptr = 0;
get_subtitle_defaults(sub);
if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size) {
AVPacket pkt_recoded;
AVPacket tmp = *avpkt;
int did_split = av_packet_split_side_data(&tmp);
//apply_param_change(avctx, &tmp);
if (did_split) {
/* FFMIN() prevents overflow in case the packet wasn't allocated with
* proper padding.
* If the side data is smaller than the buffer padding size, the
* remaining bytes should have already been filled with zeros by the
* original packet allocation anyway. */
memset(tmp.data + tmp.size, 0,
FFMIN(avpkt->size - tmp.size, AV_INPUT_BUFFER_PADDING_SIZE));
}
pkt_recoded = tmp;
ret = recode_subtitle(avctx, &pkt_recoded, &tmp);
if (ret < 0) {
*got_sub_ptr = 0;
} else {
avctx->internal->pkt = &pkt_recoded;
if (avctx->pkt_timebase.num && avpkt->pts != AV_NOPTS_VALUE)
sub->pts = av_rescale_q(avpkt->pts,
avctx->pkt_timebase, AV_TIME_BASE_Q);
ret = avctx->codec->decode(avctx, sub, got_sub_ptr, &pkt_recoded);
av_assert1((ret >= 0) >= !!*got_sub_ptr &&
!!*got_sub_ptr >= !!sub->num_rects);
#if FF_API_ASS_TIMING
if (avctx->sub_text_format == FF_SUB_TEXT_FMT_ASS_WITH_TIMINGS
&& *got_sub_ptr && sub->num_rects) {
const AVRational tb = avctx->pkt_timebase.num ? avctx->pkt_timebase
: avctx->time_base;
int err = convert_sub_to_old_ass_form(sub, avpkt, tb);
if (err < 0)
ret = err;
}
#endif
if (sub->num_rects && !sub->end_display_time && avpkt->duration &&
avctx->pkt_timebase.num) {
AVRational ms = { 1, 1000 };
sub->end_display_time = av_rescale_q(avpkt->duration,
avctx->pkt_timebase, ms);
}
for (i = 0; i < sub->num_rects; i++) {
if (sub->rects[i]->ass && !utf8_check(sub->rects[i]->ass)) {
av_log(avctx, AV_LOG_ERROR,
"Invalid UTF-8 in decoded subtitles text; "
"maybe missing -sub_charenc option\n");
avsubtitle_free(sub);
return AVERROR_INVALIDDATA;
}
}
if (tmp.data != pkt_recoded.data) { // did we recode?
/* prevent from destroying side data from original packet */
pkt_recoded.side_data = NULL;
pkt_recoded.side_data_elems = 0;
av_packet_unref(&pkt_recoded);
}
if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB)
sub->format = 0;
else if (avctx->codec_descriptor->props & AV_CODEC_PROP_TEXT_SUB)
sub->format = 1;
avctx->internal->pkt = NULL;
}
if (did_split) {
av_packet_free_side_data(&tmp);
if(ret == tmp.size)
ret = avpkt->size;
}
if (*got_sub_ptr)
avctx->frame_number++;
}
return ret;
}
void avsubtitle_free(AVSubtitle *sub)
{
int i;
for (i = 0; i < sub->num_rects; i++) {
av_freep(&sub->rects[i]->data[0]);
av_freep(&sub->rects[i]->data[1]);
av_freep(&sub->rects[i]->data[2]);
av_freep(&sub->rects[i]->data[3]);
av_freep(&sub->rects[i]->text);
av_freep(&sub->rects[i]->ass);
av_freep(&sub->rects[i]);
}
av_freep(&sub->rects);
memset(sub, 0, sizeof(AVSubtitle));
}
static int do_decode(AVCodecContext *avctx, AVPacket *pkt)
{
int got_frame;
int ret;
av_assert0(!avctx->internal->buffer_frame->buf[0]);
if (!pkt)
pkt = avctx->internal->buffer_pkt;
// This is the lesser evil. The field is for compatibility with legacy users
// of the legacy API, and users using the new API should not be forced to
// even know about this field.
avctx->refcounted_frames = 1;
// Some codecs (at least wma lossless) will crash when feeding drain packets
// after EOF was signaled.
if (avctx->internal->draining_done)
return AVERROR_EOF;
if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
ret = avcodec_decode_video2(avctx, avctx->internal->buffer_frame,
&got_frame, pkt);
if (ret >= 0 && !(avctx->flags & AV_CODEC_FLAG_TRUNCATED))
ret = pkt->size;
} else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
ret = avcodec_decode_audio4(avctx, avctx->internal->buffer_frame,
&got_frame, pkt);
} else {
ret = AVERROR(EINVAL);
}
if (ret == AVERROR(EAGAIN))
ret = pkt->size;
if (ret < 0)
return ret;
if (avctx->internal->draining && !got_frame)
avctx->internal->draining_done = 1;
if (ret >= pkt->size) {
av_packet_unref(avctx->internal->buffer_pkt);
} else {
int consumed = ret;
if (pkt != avctx->internal->buffer_pkt) {
av_packet_unref(avctx->internal->buffer_pkt);
if ((ret = av_packet_ref(avctx->internal->buffer_pkt, pkt)) < 0)
return ret;
}
avctx->internal->buffer_pkt->data += consumed;
avctx->internal->buffer_pkt->size -= consumed;
avctx->internal->buffer_pkt->pts = AV_NOPTS_VALUE;
avctx->internal->buffer_pkt->dts = AV_NOPTS_VALUE;
}
if (got_frame)
av_assert0(avctx->internal->buffer_frame->buf[0]);
return 0;
}
int attribute_align_arg avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
{
int ret;
if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
return AVERROR(EINVAL);
if (avctx->internal->draining)
return AVERROR_EOF;
if (avpkt && !avpkt->size && avpkt->data)
return AVERROR(EINVAL);
if (!avpkt || !avpkt->size) {
avctx->internal->draining = 1;
avpkt = NULL;
if (!(avctx->codec->capabilities & AV_CODEC_CAP_DELAY))
return 0;
}
if (avctx->codec->send_packet) {
if (avpkt) {
AVPacket tmp = *avpkt;
int did_split = av_packet_split_side_data(&tmp);
ret = apply_param_change(avctx, &tmp);
if (ret >= 0)
ret = avctx->codec->send_packet(avctx, &tmp);
if (did_split)
av_packet_free_side_data(&tmp);
return ret;
} else {
return avctx->codec->send_packet(avctx, NULL);
}
}
// Emulation via old API. Assume avpkt is likely not refcounted, while
// decoder output is always refcounted, and avoid copying.
if (avctx->internal->buffer_pkt->size || avctx->internal->buffer_frame->buf[0])
return AVERROR(EAGAIN);
// The goal is decoding the first frame of the packet without using memcpy,
// because the common case is having only 1 frame per packet (especially
// with video, but audio too). In other cases, it can't be avoided, unless
// the user is feeding refcounted packets.
return do_decode(avctx, (AVPacket *)avpkt);
}
int attribute_align_arg avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
{
int ret;
av_frame_unref(frame);
if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
return AVERROR(EINVAL);
if (avctx->codec->receive_frame) {
if (avctx->internal->draining && !(avctx->codec->capabilities & AV_CODEC_CAP_DELAY))
return AVERROR_EOF;
ret = avctx->codec->receive_frame(avctx, frame);
if (ret >= 0) {
if (av_frame_get_best_effort_timestamp(frame) == AV_NOPTS_VALUE) {
av_frame_set_best_effort_timestamp(frame,
guess_correct_pts(avctx, frame->pts, frame->pkt_dts));
}
}
return ret;
}
// Emulation via old API.
if (!avctx->internal->buffer_frame->buf[0]) {
if (!avctx->internal->buffer_pkt->size && !avctx->internal->draining)
return AVERROR(EAGAIN);
while (1) {
if ((ret = do_decode(avctx, avctx->internal->buffer_pkt)) < 0) {
av_packet_unref(avctx->internal->buffer_pkt);
return ret;
}
// Some audio decoders may consume partial data without returning
// a frame (fate-wmapro-2ch). There is no way to make the caller
// call avcodec_receive_frame() again without returning a frame,
// so try to decode more in these cases.
if (avctx->internal->buffer_frame->buf[0] ||
!avctx->internal->buffer_pkt->size)
break;
}
}
if (!avctx->internal->buffer_frame->buf[0])
return avctx->internal->draining ? AVERROR_EOF : AVERROR(EAGAIN);
av_frame_move_ref(frame, avctx->internal->buffer_frame);
return 0;
}
static int do_encode(AVCodecContext *avctx, const AVFrame *frame, int *got_packet)
{
int ret;
*got_packet = 0;
av_packet_unref(avctx->internal->buffer_pkt);
avctx->internal->buffer_pkt_valid = 0;
if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
ret = avcodec_encode_video2(avctx, avctx->internal->buffer_pkt,
frame, got_packet);
} else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
ret = avcodec_encode_audio2(avctx, avctx->internal->buffer_pkt,
frame, got_packet);
} else {
ret = AVERROR(EINVAL);
}
if (ret >= 0 && *got_packet) {
// Encoders must always return ref-counted buffers.
// Side-data only packets have no data and can be not ref-counted.
av_assert0(!avctx->internal->buffer_pkt->data || avctx->internal->buffer_pkt->buf);
avctx->internal->buffer_pkt_valid = 1;
ret = 0;
} else {
av_packet_unref(avctx->internal->buffer_pkt);
}
return ret;
}
int attribute_align_arg avcodec_send_frame(AVCodecContext *avctx, const AVFrame *frame)
{
if (!avcodec_is_open(avctx) || !av_codec_is_encoder(avctx->codec))
return AVERROR(EINVAL);
if (avctx->internal->draining)
return AVERROR_EOF;
if (!frame) {
avctx->internal->draining = 1;
if (!(avctx->codec->capabilities & AV_CODEC_CAP_DELAY))
return 0;
}
if (avctx->codec->send_frame)
return avctx->codec->send_frame(avctx, frame);
// Emulation via old API. Do it here instead of avcodec_receive_packet, because:
// 1. if the AVFrame is not refcounted, the copying will be much more
// expensive than copying the packet data
// 2. assume few users use non-refcounted AVPackets, so usually no copy is
// needed
if (avctx->internal->buffer_pkt_valid)
return AVERROR(EAGAIN);
return do_encode(avctx, frame, &(int){0});
}
int attribute_align_arg avcodec_receive_packet(AVCodecContext *avctx, AVPacket *avpkt)
{
av_packet_unref(avpkt);
if (!avcodec_is_open(avctx) || !av_codec_is_encoder(avctx->codec))
return AVERROR(EINVAL);
if (avctx->codec->receive_packet) {
if (avctx->internal->draining && !(avctx->codec->capabilities & AV_CODEC_CAP_DELAY))
return AVERROR_EOF;
return avctx->codec->receive_packet(avctx, avpkt);
}
// Emulation via old API.
if (!avctx->internal->buffer_pkt_valid) {
int got_packet;
int ret;
if (!avctx->internal->draining)
return AVERROR(EAGAIN);
ret = do_encode(avctx, NULL, &got_packet);
if (ret < 0)
return ret;
if (ret >= 0 && !got_packet)
return AVERROR_EOF;
}
av_packet_move_ref(avpkt, avctx->internal->buffer_pkt);
avctx->internal->buffer_pkt_valid = 0;
return 0;
}
av_cold int avcodec_close(AVCodecContext *avctx)
{
int i;
if (!avctx)
return 0;
if (avcodec_is_open(avctx)) {
FramePool *pool = avctx->internal->pool;
if (CONFIG_FRAME_THREAD_ENCODER &&
avctx->internal->frame_thread_encoder && avctx->thread_count > 1) {
ff_frame_thread_encoder_free(avctx);
}
if (HAVE_THREADS && avctx->internal->thread_ctx)
ff_thread_free(avctx);
if (avctx->codec && avctx->codec->close)
avctx->codec->close(avctx);
avctx->internal->byte_buffer_size = 0;
av_freep(&avctx->internal->byte_buffer);
av_frame_free(&avctx->internal->to_free);
av_frame_free(&avctx->internal->buffer_frame);
av_packet_free(&avctx->internal->buffer_pkt);
for (i = 0; i < FF_ARRAY_ELEMS(pool->pools); i++)
av_buffer_pool_uninit(&pool->pools[i]);
av_freep(&avctx->internal->pool);
if (avctx->hwaccel && avctx->hwaccel->uninit)
avctx->hwaccel->uninit(avctx);
av_freep(&avctx->internal->hwaccel_priv_data);
av_freep(&avctx->internal);
}
for (i = 0; i < avctx->nb_coded_side_data; i++)
av_freep(&avctx->coded_side_data[i].data);
av_freep(&avctx->coded_side_data);
avctx->nb_coded_side_data = 0;
av_buffer_unref(&avctx->hw_frames_ctx);
if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
av_opt_free(avctx->priv_data);
av_opt_free(avctx);
av_freep(&avctx->priv_data);
if (av_codec_is_encoder(avctx->codec)) {
av_freep(&avctx->extradata);
#if FF_API_CODED_FRAME
FF_DISABLE_DEPRECATION_WARNINGS
av_frame_free(&avctx->coded_frame);
FF_ENABLE_DEPRECATION_WARNINGS
#endif
}
avctx->codec = NULL;
avctx->active_thread_type = 0;
return 0;
}
static enum AVCodecID remap_deprecated_codec_id(enum AVCodecID id)
{
switch(id){
//This is for future deprecatec codec ids, its empty since
//last major bump but will fill up again over time, please don't remove it
default : return id;
}
}
static AVCodec *find_encdec(enum AVCodecID id, int encoder)
{
AVCodec *p, *experimental = NULL;
p = first_avcodec;
id= remap_deprecated_codec_id(id);
while (p) {
if ((encoder ? av_codec_is_encoder(p) : av_codec_is_decoder(p)) &&
p->id == id) {
if (p->capabilities & AV_CODEC_CAP_EXPERIMENTAL && !experimental) {
experimental = p;
} else
return p;
}
p = p->next;
}
return experimental;
}
AVCodec *avcodec_find_encoder(enum AVCodecID id)
{
return find_encdec(id, 1);
}
AVCodec *avcodec_find_encoder_by_name(const char *name)
{
AVCodec *p;
if (!name)
return NULL;
p = first_avcodec;
while (p) {
if (av_codec_is_encoder(p) && strcmp(name, p->name) == 0)
return p;
p = p->next;
}
return NULL;
}
AVCodec *avcodec_find_decoder(enum AVCodecID id)
{
return find_encdec(id, 0);
}
AVCodec *avcodec_find_decoder_by_name(const char *name)
{
AVCodec *p;
if (!name)
return NULL;
p = first_avcodec;
while (p) {
if (av_codec_is_decoder(p) && strcmp(name, p->name) == 0)
return p;
p = p->next;
}
return NULL;
}
const char *avcodec_get_name(enum AVCodecID id)
{
const AVCodecDescriptor *cd;
AVCodec *codec;
if (id == AV_CODEC_ID_NONE)
return "none";
cd = avcodec_descriptor_get(id);
if (cd)
return cd->name;
av_log(NULL, AV_LOG_WARNING, "Codec 0x%x is not in the full list.\n", id);
codec = avcodec_find_decoder(id);
if (codec)
return codec->name;
codec = avcodec_find_encoder(id);
if (codec)
return codec->name;
return "unknown_codec";
}
size_t av_get_codec_tag_string(char *buf, size_t buf_size, unsigned int codec_tag)
{
int i, len, ret = 0;
#define TAG_PRINT(x) \
(((x) >= '0' && (x) <= '9') || \
((x) >= 'a' && (x) <= 'z') || ((x) >= 'A' && (x) <= 'Z') || \
((x) == '.' || (x) == ' ' || (x) == '-' || (x) == '_'))
for (i = 0; i < 4; i++) {
len = snprintf(buf, buf_size,
TAG_PRINT(codec_tag & 0xFF) ? "%c" : "[%d]", codec_tag & 0xFF);
buf += len;
buf_size = buf_size > len ? buf_size - len : 0;
ret += len;
codec_tag >>= 8;
}
return ret;
}
void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
{
const char *codec_type;
const char *codec_name;
const char *profile = NULL;
int64_t bitrate;
int new_line = 0;
AVRational display_aspect_ratio;
const char *separator = enc->dump_separator ? (const char *)enc->dump_separator : ", ";
if (!buf || buf_size <= 0)
return;
codec_type = av_get_media_type_string(enc->codec_type);
codec_name = avcodec_get_name(enc->codec_id);
profile = avcodec_profile_name(enc->codec_id, enc->profile);
snprintf(buf, buf_size, "%s: %s", codec_type ? codec_type : "unknown",
codec_name);
buf[0] ^= 'a' ^ 'A'; /* first letter in uppercase */
if (enc->codec && strcmp(enc->codec->name, codec_name))
snprintf(buf + strlen(buf), buf_size - strlen(buf), " (%s)", enc->codec->name);
if (profile)
snprintf(buf + strlen(buf), buf_size - strlen(buf), " (%s)", profile);
if ( enc->codec_type == AVMEDIA_TYPE_VIDEO
&& av_log_get_level() >= AV_LOG_VERBOSE
&& enc->refs)
snprintf(buf + strlen(buf), buf_size - strlen(buf),
", %d reference frame%s",
enc->refs, enc->refs > 1 ? "s" : "");
if (enc->codec_tag) {
char tag_buf[32];
av_get_codec_tag_string(tag_buf, sizeof(tag_buf), enc->codec_tag);
snprintf(buf + strlen(buf), buf_size - strlen(buf),
" (%s / 0x%04X)", tag_buf, enc->codec_tag);
}
switch (enc->codec_type) {
case AVMEDIA_TYPE_VIDEO:
{
char detail[256] = "(";
av_strlcat(buf, separator, buf_size);
snprintf(buf + strlen(buf), buf_size - strlen(buf),
"%s", enc->pix_fmt == AV_PIX_FMT_NONE ? "none" :
av_get_pix_fmt_name(enc->pix_fmt));
if (enc->bits_per_raw_sample && enc->pix_fmt != AV_PIX_FMT_NONE &&
enc->bits_per_raw_sample < av_pix_fmt_desc_get(enc->pix_fmt)->comp[0].depth)
av_strlcatf(detail, sizeof(detail), "%d bpc, ", enc->bits_per_raw_sample);
if (enc->color_range != AVCOL_RANGE_UNSPECIFIED)
av_strlcatf(detail, sizeof(detail), "%s, ",
av_color_range_name(enc->color_range));
if (enc->colorspace != AVCOL_SPC_UNSPECIFIED ||
enc->color_primaries != AVCOL_PRI_UNSPECIFIED ||
enc->color_trc != AVCOL_TRC_UNSPECIFIED) {
if (enc->colorspace != (int)enc->color_primaries ||
enc->colorspace != (int)enc->color_trc) {
new_line = 1;
av_strlcatf(detail, sizeof(detail), "%s/%s/%s, ",
av_color_space_name(enc->colorspace),
av_color_primaries_name(enc->color_primaries),
av_color_transfer_name(enc->color_trc));
} else
av_strlcatf(detail, sizeof(detail), "%s, ",
av_get_colorspace_name(enc->colorspace));
}
if (enc->field_order != AV_FIELD_UNKNOWN) {
const char *field_order = "progressive";
if (enc->field_order == AV_FIELD_TT)
field_order = "top first";
else if (enc->field_order == AV_FIELD_BB)
field_order = "bottom first";
else if (enc->field_order == AV_FIELD_TB)
field_order = "top coded first (swapped)";
else if (enc->field_order == AV_FIELD_BT)
field_order = "bottom coded first (swapped)";
av_strlcatf(detail, sizeof(detail), "%s, ", field_order);
}
if (av_log_get_level() >= AV_LOG_VERBOSE &&
enc->chroma_sample_location != AVCHROMA_LOC_UNSPECIFIED)
av_strlcatf(detail, sizeof(detail), "%s, ",
av_chroma_location_name(enc->chroma_sample_location));
if (strlen(detail) > 1) {
detail[strlen(detail) - 2] = 0;
av_strlcatf(buf, buf_size, "%s)", detail);
}
}
if (enc->width) {
av_strlcat(buf, new_line ? separator : ", ", buf_size);
snprintf(buf + strlen(buf), buf_size - strlen(buf),
"%dx%d",
enc->width, enc->height);
if (av_log_get_level() >= AV_LOG_VERBOSE &&
(enc->width != enc->coded_width ||
enc->height != enc->coded_height))
snprintf(buf + strlen(buf), buf_size - strlen(buf),
" (%dx%d)", enc->coded_width, enc->coded_height);
if (enc->sample_aspect_ratio.num) {
av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
enc->width * (int64_t)enc->sample_aspect_ratio.num,
enc->height * (int64_t)enc->sample_aspect_ratio.den,
1024 * 1024);
snprintf(buf + strlen(buf), buf_size - strlen(buf),
" [SAR %d:%d DAR %d:%d]",
enc->sample_aspect_ratio.num, enc->sample_aspect_ratio.den,
display_aspect_ratio.num, display_aspect_ratio.den);
}
if (av_log_get_level() >= AV_LOG_DEBUG) {
int g = av_gcd(enc->time_base.num, enc->time_base.den);
snprintf(buf + strlen(buf), buf_size - strlen(buf),
", %d/%d",
enc->time_base.num / g, enc->time_base.den / g);
}
}
if (encode) {
snprintf(buf + strlen(buf), buf_size - strlen(buf),
", q=%d-%d", enc->qmin, enc->qmax);
} else {
if (enc->properties & FF_CODEC_PROPERTY_CLOSED_CAPTIONS)
snprintf(buf + strlen(buf), buf_size - strlen(buf),
", Closed Captions");
if (enc->properties & FF_CODEC_PROPERTY_LOSSLESS)
snprintf(buf + strlen(buf), buf_size - strlen(buf),
", lossless");
}
break;
case AVMEDIA_TYPE_AUDIO:
av_strlcat(buf, separator, buf_size);
if (enc->sample_rate) {
snprintf(buf + strlen(buf), buf_size - strlen(buf),
"%d Hz, ", enc->sample_rate);
}
av_get_channel_layout_string(buf + strlen(buf), buf_size - strlen(buf), enc->channels, enc->channel_layout);
if (enc->sample_fmt != AV_SAMPLE_FMT_NONE) {
snprintf(buf + strlen(buf), buf_size - strlen(buf),
", %s", av_get_sample_fmt_name(enc->sample_fmt));
}
if ( enc->bits_per_raw_sample > 0
&& enc->bits_per_raw_sample != av_get_bytes_per_sample(enc->sample_fmt) * 8)
snprintf(buf + strlen(buf), buf_size - strlen(buf),
" (%d bit)", enc->bits_per_raw_sample);
if (av_log_get_level() >= AV_LOG_VERBOSE) {
if (enc->initial_padding)
snprintf(buf + strlen(buf), buf_size - strlen(buf),
", delay %d", enc->initial_padding);
if (enc->trailing_padding)
snprintf(buf + strlen(buf), buf_size - strlen(buf),
", padding %d", enc->trailing_padding);
}
break;
case AVMEDIA_TYPE_DATA:
if (av_log_get_level() >= AV_LOG_DEBUG) {
int g = av_gcd(enc->time_base.num, enc->time_base.den);
if (g)
snprintf(buf + strlen(buf), buf_size - strlen(buf),
", %d/%d",
enc->time_base.num / g, enc->time_base.den / g);
}
break;
case AVMEDIA_TYPE_SUBTITLE:
if (enc->width)
snprintf(buf + strlen(buf), buf_size - strlen(buf),
", %dx%d", enc->width, enc->height);
break;
default:
return;
}
if (encode) {
if (enc->flags & AV_CODEC_FLAG_PASS1)
snprintf(buf + strlen(buf), buf_size - strlen(buf),
", pass 1");
if (enc->flags & AV_CODEC_FLAG_PASS2)
snprintf(buf + strlen(buf), buf_size - strlen(buf),
", pass 2");
}
bitrate = get_bit_rate(enc);
if (bitrate != 0) {
snprintf(buf + strlen(buf), buf_size - strlen(buf),
", %"PRId64" kb/s", bitrate / 1000);
} else if (enc->rc_max_rate > 0) {
snprintf(buf + strlen(buf), buf_size - strlen(buf),
", max. %"PRId64" kb/s", (int64_t)enc->rc_max_rate / 1000);
}
}
const char *av_get_profile_name(const AVCodec *codec, int profile)
{
const AVProfile *p;
if (profile == FF_PROFILE_UNKNOWN || !codec->profiles)
return NULL;
for (p = codec->profiles; p->profile != FF_PROFILE_UNKNOWN; p++)
if (p->profile == profile)
return p->name;
return NULL;
}
const char *avcodec_profile_name(enum AVCodecID codec_id, int profile)
{
const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
const AVProfile *p;
if (profile == FF_PROFILE_UNKNOWN || !desc || !desc->profiles)
return NULL;
for (p = desc->profiles; p->profile != FF_PROFILE_UNKNOWN; p++)
if (p->profile == profile)
return p->name;
return NULL;
}
unsigned avcodec_version(void)
{
// av_assert0(AV_CODEC_ID_V410==164);
av_assert0(AV_CODEC_ID_PCM_S8_PLANAR==65563);
av_assert0(AV_CODEC_ID_ADPCM_G722==69660);
// av_assert0(AV_CODEC_ID_BMV_AUDIO==86071);
av_assert0(AV_CODEC_ID_SRT==94216);
av_assert0(LIBAVCODEC_VERSION_MICRO >= 100);
return LIBAVCODEC_VERSION_INT;
}
const char *avcodec_configuration(void)
{
return FFMPEG_CONFIGURATION;
}
const char *avcodec_license(void)
{
#define LICENSE_PREFIX "libavcodec license: "
return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
}
void avcodec_flush_buffers(AVCodecContext *avctx)
{
avctx->internal->draining = 0;
avctx->internal->draining_done = 0;
av_frame_unref(avctx->internal->buffer_frame);
av_packet_unref(avctx->internal->buffer_pkt);
avctx->internal->buffer_pkt_valid = 0;
if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
ff_thread_flush(avctx);
else if (avctx->codec->flush)
avctx->codec->flush(avctx);
avctx->pts_correction_last_pts =
avctx->pts_correction_last_dts = INT64_MIN;
if (!avctx->refcounted_frames)
av_frame_unref(avctx->internal->to_free);
}
int av_get_exact_bits_per_sample(enum AVCodecID codec_id)
{
switch (codec_id) {
case AV_CODEC_ID_8SVX_EXP:
case AV_CODEC_ID_8SVX_FIB:
case AV_CODEC_ID_ADPCM_CT:
case AV_CODEC_ID_ADPCM_IMA_APC:
case AV_CODEC_ID_ADPCM_IMA_EA_SEAD:
case AV_CODEC_ID_ADPCM_IMA_OKI:
case AV_CODEC_ID_ADPCM_IMA_WS:
case AV_CODEC_ID_ADPCM_G722:
case AV_CODEC_ID_ADPCM_YAMAHA:
case AV_CODEC_ID_ADPCM_AICA:
return 4;
case AV_CODEC_ID_DSD_LSBF:
case AV_CODEC_ID_DSD_MSBF:
case AV_CODEC_ID_DSD_LSBF_PLANAR:
case AV_CODEC_ID_DSD_MSBF_PLANAR:
case AV_CODEC_ID_PCM_ALAW:
case AV_CODEC_ID_PCM_MULAW:
case AV_CODEC_ID_PCM_S8:
case AV_CODEC_ID_PCM_S8_PLANAR:
case AV_CODEC_ID_PCM_U8:
case AV_CODEC_ID_PCM_ZORK:
case AV_CODEC_ID_SDX2_DPCM:
return 8;
case AV_CODEC_ID_PCM_S16BE:
case AV_CODEC_ID_PCM_S16BE_PLANAR:
case AV_CODEC_ID_PCM_S16LE:
case AV_CODEC_ID_PCM_S16LE_PLANAR:
case AV_CODEC_ID_PCM_U16BE:
case AV_CODEC_ID_PCM_U16LE:
return 16;
case AV_CODEC_ID_PCM_S24DAUD:
case AV_CODEC_ID_PCM_S24BE:
case AV_CODEC_ID_PCM_S24LE:
case AV_CODEC_ID_PCM_S24LE_PLANAR:
case AV_CODEC_ID_PCM_U24BE:
case AV_CODEC_ID_PCM_U24LE:
return 24;
case AV_CODEC_ID_PCM_S32BE:
case AV_CODEC_ID_PCM_S32LE:
case AV_CODEC_ID_PCM_S32LE_PLANAR:
case AV_CODEC_ID_PCM_U32BE:
case AV_CODEC_ID_PCM_U32LE:
case AV_CODEC_ID_PCM_F32BE:
case AV_CODEC_ID_PCM_F32LE:
case AV_CODEC_ID_PCM_F24LE:
case AV_CODEC_ID_PCM_F16LE:
return 32;
case AV_CODEC_ID_PCM_F64BE:
case AV_CODEC_ID_PCM_F64LE:
case AV_CODEC_ID_PCM_S64BE:
case AV_CODEC_ID_PCM_S64LE:
return 64;
default:
return 0;
}
}
enum AVCodecID av_get_pcm_codec(enum AVSampleFormat fmt, int be)
{
static const enum AVCodecID map[AV_SAMPLE_FMT_NB][2] = {
[AV_SAMPLE_FMT_U8 ] = { AV_CODEC_ID_PCM_U8, AV_CODEC_ID_PCM_U8 },
[AV_SAMPLE_FMT_S16 ] = { AV_CODEC_ID_PCM_S16LE, AV_CODEC_ID_PCM_S16BE },
[AV_SAMPLE_FMT_S32 ] = { AV_CODEC_ID_PCM_S32LE, AV_CODEC_ID_PCM_S32BE },
[AV_SAMPLE_FMT_FLT ] = { AV_CODEC_ID_PCM_F32LE, AV_CODEC_ID_PCM_F32BE },
[AV_SAMPLE_FMT_DBL ] = { AV_CODEC_ID_PCM_F64LE, AV_CODEC_ID_PCM_F64BE },
[AV_SAMPLE_FMT_U8P ] = { AV_CODEC_ID_PCM_U8, AV_CODEC_ID_PCM_U8 },
[AV_SAMPLE_FMT_S16P] = { AV_CODEC_ID_PCM_S16LE, AV_CODEC_ID_PCM_S16BE },
[AV_SAMPLE_FMT_S32P] = { AV_CODEC_ID_PCM_S32LE, AV_CODEC_ID_PCM_S32BE },
[AV_SAMPLE_FMT_S64P] = { AV_CODEC_ID_PCM_S64LE, AV_CODEC_ID_PCM_S64BE },
[AV_SAMPLE_FMT_FLTP] = { AV_CODEC_ID_PCM_F32LE, AV_CODEC_ID_PCM_F32BE },
[AV_SAMPLE_FMT_DBLP] = { AV_CODEC_ID_PCM_F64LE, AV_CODEC_ID_PCM_F64BE },
};
if (fmt < 0 || fmt >= AV_SAMPLE_FMT_NB)
return AV_CODEC_ID_NONE;
if (be < 0 || be > 1)
be = AV_NE(1, 0);
return map[fmt][be];
}
int av_get_bits_per_sample(enum AVCodecID codec_id)
{
switch (codec_id) {
case AV_CODEC_ID_ADPCM_SBPRO_2:
return 2;
case AV_CODEC_ID_ADPCM_SBPRO_3:
return 3;
case AV_CODEC_ID_ADPCM_SBPRO_4:
case AV_CODEC_ID_ADPCM_IMA_WAV:
case AV_CODEC_ID_ADPCM_IMA_QT:
case AV_CODEC_ID_ADPCM_SWF:
case AV_CODEC_ID_ADPCM_MS:
return 4;
default:
return av_get_exact_bits_per_sample(codec_id);
}
}
static int get_audio_frame_duration(enum AVCodecID id, int sr, int ch, int ba,
uint32_t tag, int bits_per_coded_sample, int64_t bitrate,
uint8_t * extradata, int frame_size, int frame_bytes)
{
int bps = av_get_exact_bits_per_sample(id);
int framecount = (ba > 0 && frame_bytes / ba > 0) ? frame_bytes / ba : 1;
/* codecs with an exact constant bits per sample */
if (bps > 0 && ch > 0 && frame_bytes > 0 && ch < 32768 && bps < 32768)
return (frame_bytes * 8LL) / (bps * ch);
bps = bits_per_coded_sample;
/* codecs with a fixed packet duration */
switch (id) {
case AV_CODEC_ID_ADPCM_ADX: return 32;
case AV_CODEC_ID_ADPCM_IMA_QT: return 64;
case AV_CODEC_ID_ADPCM_EA_XAS: return 128;
case AV_CODEC_ID_AMR_NB:
case AV_CODEC_ID_EVRC:
case AV_CODEC_ID_GSM:
case AV_CODEC_ID_QCELP:
case AV_CODEC_ID_RA_288: return 160;
case AV_CODEC_ID_AMR_WB:
case AV_CODEC_ID_GSM_MS: return 320;
case AV_CODEC_ID_MP1: return 384;
case AV_CODEC_ID_ATRAC1: return 512;
case AV_CODEC_ID_ATRAC3: return 1024 * framecount;
case AV_CODEC_ID_ATRAC3P: return 2048;
case AV_CODEC_ID_MP2:
case AV_CODEC_ID_MUSEPACK7: return 1152;
case AV_CODEC_ID_AC3: return 1536;
}
if (sr > 0) {
/* calc from sample rate */
if (id == AV_CODEC_ID_TTA)
return 256 * sr / 245;
else if (id == AV_CODEC_ID_DST)
return 588 * sr / 44100;
if (ch > 0) {
/* calc from sample rate and channels */
if (id == AV_CODEC_ID_BINKAUDIO_DCT)
return (480 << (sr / 22050)) / ch;
}
}
if (ba > 0) {
/* calc from block_align */
if (id == AV_CODEC_ID_SIPR) {
switch (ba) {
case 20: return 160;
case 19: return 144;
case 29: return 288;
case 37: return 480;
}
} else if (id == AV_CODEC_ID_ILBC) {
switch (ba) {
case 38: return 160;
case 50: return 240;
}
}
}
if (frame_bytes > 0) {
/* calc from frame_bytes only */
if (id == AV_CODEC_ID_TRUESPEECH)
return 240 * (frame_bytes / 32);
if (id == AV_CODEC_ID_NELLYMOSER)
return 256 * (frame_bytes / 64);
if (id == AV_CODEC_ID_RA_144)
return 160 * (frame_bytes / 20);
if (id == AV_CODEC_ID_G723_1)
return 240 * (frame_bytes / 24);
if (bps > 0) {
/* calc from frame_bytes and bits_per_coded_sample */
if (id == AV_CODEC_ID_ADPCM_G726)
return frame_bytes * 8 / bps;
}
if (ch > 0 && ch < INT_MAX/16) {
/* calc from frame_bytes and channels */
switch (id) {
case AV_CODEC_ID_ADPCM_AFC:
return frame_bytes / (9 * ch) * 16;
case AV_CODEC_ID_ADPCM_PSX:
case AV_CODEC_ID_ADPCM_DTK:
return frame_bytes / (16 * ch) * 28;
case AV_CODEC_ID_ADPCM_4XM:
case AV_CODEC_ID_ADPCM_IMA_DAT4:
case AV_CODEC_ID_ADPCM_IMA_ISS:
return (frame_bytes - 4 * ch) * 2 / ch;
case AV_CODEC_ID_ADPCM_IMA_SMJPEG:
return (frame_bytes - 4) * 2 / ch;
case AV_CODEC_ID_ADPCM_IMA_AMV:
return (frame_bytes - 8) * 2 / ch;
case AV_CODEC_ID_ADPCM_THP:
case AV_CODEC_ID_ADPCM_THP_LE:
if (extradata)
return frame_bytes * 14 / (8 * ch);
break;
case AV_CODEC_ID_ADPCM_XA:
return (frame_bytes / 128) * 224 / ch;
case AV_CODEC_ID_INTERPLAY_DPCM:
return (frame_bytes - 6 - ch) / ch;
case AV_CODEC_ID_ROQ_DPCM:
return (frame_bytes - 8) / ch;
case AV_CODEC_ID_XAN_DPCM:
return (frame_bytes - 2 * ch) / ch;
case AV_CODEC_ID_MACE3:
return 3 * frame_bytes / ch;
case AV_CODEC_ID_MACE6:
return 6 * frame_bytes / ch;
case AV_CODEC_ID_PCM_LXF:
return 2 * (frame_bytes / (5 * ch));
case AV_CODEC_ID_IAC:
case AV_CODEC_ID_IMC:
return 4 * frame_bytes / ch;
}
if (tag) {
/* calc from frame_bytes, channels, and codec_tag */
if (id == AV_CODEC_ID_SOL_DPCM) {
if (tag == 3)
return frame_bytes / ch;
else
return frame_bytes * 2 / ch;
}
}
if (ba > 0) {
/* calc from frame_bytes, channels, and block_align */
int blocks = frame_bytes / ba;
switch (id) {
case AV_CODEC_ID_ADPCM_IMA_WAV:
if (bps < 2 || bps > 5)
return 0;
return blocks * (1 + (ba - 4 * ch) / (bps * ch) * 8);
case AV_CODEC_ID_ADPCM_IMA_DK3:
return blocks * (((ba - 16) * 2 / 3 * 4) / ch);
case AV_CODEC_ID_ADPCM_IMA_DK4:
return blocks * (1 + (ba - 4 * ch) * 2 / ch);
case AV_CODEC_ID_ADPCM_IMA_RAD:
return blocks * ((ba - 4 * ch) * 2 / ch);
case AV_CODEC_ID_ADPCM_MS:
return blocks * (2 + (ba - 7 * ch) * 2 / ch);
case AV_CODEC_ID_ADPCM_MTAF:
return blocks * (ba - 16) * 2 / ch;
}
}
if (bps > 0) {
/* calc from frame_bytes, channels, and bits_per_coded_sample */
switch (id) {
case AV_CODEC_ID_PCM_DVD:
if(bps<4)
return 0;
return 2 * (frame_bytes / ((bps * 2 / 8) * ch));
case AV_CODEC_ID_PCM_BLURAY:
if(bps<4)
return 0;
return frame_bytes / ((FFALIGN(ch, 2) * bps) / 8);
case AV_CODEC_ID_S302M:
return 2 * (frame_bytes / ((bps + 4) / 4)) / ch;
}
}
}
}
/* Fall back on using frame_size */
if (frame_size > 1 && frame_bytes)
return frame_size;
//For WMA we currently have no other means to calculate duration thus we
//do it here by assuming CBR, which is true for all known cases.
if (bitrate > 0 && frame_bytes > 0 && sr > 0 && ba > 1) {
if (id == AV_CODEC_ID_WMAV1 || id == AV_CODEC_ID_WMAV2)
return (frame_bytes * 8LL * sr) / bitrate;
}
return 0;
}
int av_get_audio_frame_duration(AVCodecContext *avctx, int frame_bytes)
{
return get_audio_frame_duration(avctx->codec_id, avctx->sample_rate,
avctx->channels, avctx->block_align,
avctx->codec_tag, avctx->bits_per_coded_sample,
avctx->bit_rate, avctx->extradata, avctx->frame_size,
frame_bytes);
}
int av_get_audio_frame_duration2(AVCodecParameters *par, int frame_bytes)
{
return get_audio_frame_duration(par->codec_id, par->sample_rate,
par->channels, par->block_align,
par->codec_tag, par->bits_per_coded_sample,
par->bit_rate, par->extradata, par->frame_size,
frame_bytes);
}
#if !HAVE_THREADS
int ff_thread_init(AVCodecContext *s)
{
return -1;
}
#endif
unsigned int av_xiphlacing(unsigned char *s, unsigned int v)
{
unsigned int n = 0;
while (v >= 0xff) {
*s++ = 0xff;
v -= 0xff;
n++;
}
*s = v;
n++;
return n;
}
int ff_match_2uint16(const uint16_t(*tab)[2], int size, int a, int b)
{
int i;
for (i = 0; i < size && !(tab[i][0] == a && tab[i][1] == b); i++) ;
return i;
}
#if FF_API_MISSING_SAMPLE
FF_DISABLE_DEPRECATION_WARNINGS
void av_log_missing_feature(void *avc, const char *feature, int want_sample)
{
av_log(avc, AV_LOG_WARNING, "%s is not implemented. Update your FFmpeg "
"version to the newest one from Git. If the problem still "
"occurs, it means that your file has a feature which has not "
"been implemented.\n", feature);
if(want_sample)
av_log_ask_for_sample(avc, NULL);
}
void av_log_ask_for_sample(void *avc, const char *msg, ...)
{
va_list argument_list;
va_start(argument_list, msg);
if (msg)
av_vlog(avc, AV_LOG_WARNING, msg, argument_list);
av_log(avc, AV_LOG_WARNING, "If you want to help, upload a sample "
"of this file to ftp://upload.ffmpeg.org/incoming/ "
"and contact the ffmpeg-devel mailing list. (ffmpeg-devel@ffmpeg.org)\n");
va_end(argument_list);
}
FF_ENABLE_DEPRECATION_WARNINGS
#endif /* FF_API_MISSING_SAMPLE */
static AVHWAccel *first_hwaccel = NULL;
static AVHWAccel **last_hwaccel = &first_hwaccel;
void av_register_hwaccel(AVHWAccel *hwaccel)
{
AVHWAccel **p = last_hwaccel;
hwaccel->next = NULL;
while(*p || avpriv_atomic_ptr_cas((void * volatile *)p, NULL, hwaccel))
p = &(*p)->next;
last_hwaccel = &hwaccel->next;
}
AVHWAccel *av_hwaccel_next(const AVHWAccel *hwaccel)
{
return hwaccel ? hwaccel->next : first_hwaccel;
}
int av_lockmgr_register(int (*cb)(void **mutex, enum AVLockOp op))
{
if (lockmgr_cb) {
// There is no good way to rollback a failure to destroy the
// mutex, so we ignore failures.
lockmgr_cb(&codec_mutex, AV_LOCK_DESTROY);
lockmgr_cb(&avformat_mutex, AV_LOCK_DESTROY);
lockmgr_cb = NULL;
codec_mutex = NULL;
avformat_mutex = NULL;
}
if (cb) {
void *new_codec_mutex = NULL;
void *new_avformat_mutex = NULL;
int err;
if (err = cb(&new_codec_mutex, AV_LOCK_CREATE)) {
return err > 0 ? AVERROR_UNKNOWN : err;
}
if (err = cb(&new_avformat_mutex, AV_LOCK_CREATE)) {
// Ignore failures to destroy the newly created mutex.
cb(&new_codec_mutex, AV_LOCK_DESTROY);
return err > 0 ? AVERROR_UNKNOWN : err;
}
lockmgr_cb = cb;
codec_mutex = new_codec_mutex;
avformat_mutex = new_avformat_mutex;
}
return 0;
}
int ff_lock_avcodec(AVCodecContext *log_ctx, const AVCodec *codec)
{
if (codec->caps_internal & FF_CODEC_CAP_INIT_THREADSAFE || !codec->init)
return 0;
if (lockmgr_cb) {
if ((*lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
return -1;
}
if (avpriv_atomic_int_add_and_fetch(&entangled_thread_counter, 1) != 1) {
av_log(log_ctx, AV_LOG_ERROR,
"Insufficient thread locking. At least %d threads are "
"calling avcodec_open2() at the same time right now.\n",
entangled_thread_counter);
if (!lockmgr_cb)
av_log(log_ctx, AV_LOG_ERROR, "No lock manager is set, please see av_lockmgr_register()\n");
ff_avcodec_locked = 1;
ff_unlock_avcodec(codec);
return AVERROR(EINVAL);
}
av_assert0(!ff_avcodec_locked);
ff_avcodec_locked = 1;
return 0;
}
int ff_unlock_avcodec(const AVCodec *codec)
{
if (codec->caps_internal & FF_CODEC_CAP_INIT_THREADSAFE || !codec->init)
return 0;
av_assert0(ff_avcodec_locked);
ff_avcodec_locked = 0;
avpriv_atomic_int_add_and_fetch(&entangled_thread_counter, -1);
if (lockmgr_cb) {
if ((*lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE))
return -1;
}
return 0;
}
int avpriv_lock_avformat(void)
{
if (lockmgr_cb) {
if ((*lockmgr_cb)(&avformat_mutex, AV_LOCK_OBTAIN))
return -1;
}
return 0;
}
int avpriv_unlock_avformat(void)
{
if (lockmgr_cb) {
if ((*lockmgr_cb)(&avformat_mutex, AV_LOCK_RELEASE))
return -1;
}
return 0;
}
unsigned int avpriv_toupper4(unsigned int x)
{
return av_toupper(x & 0xFF) +
(av_toupper((x >> 8) & 0xFF) << 8) +
(av_toupper((x >> 16) & 0xFF) << 16) +
((unsigned)av_toupper((x >> 24) & 0xFF) << 24);
}
int ff_thread_ref_frame(ThreadFrame *dst, ThreadFrame *src)
{
int ret;
dst->owner = src->owner;
ret = av_frame_ref(dst->f, src->f);
if (ret < 0)
return ret;
av_assert0(!dst->progress);
if (src->progress &&
!(dst->progress = av_buffer_ref(src->progress))) {
ff_thread_release_buffer(dst->owner, dst);
return AVERROR(ENOMEM);
}
return 0;
}
#if !HAVE_THREADS
enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
{
return ff_get_format(avctx, fmt);
}
int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
{
f->owner = avctx;
return ff_get_buffer(avctx, f->f, flags);
}
void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
{
if (f->f)
av_frame_unref(f->f);
}
void ff_thread_finish_setup(AVCodecContext *avctx)
{
}
void ff_thread_report_progress(ThreadFrame *f, int progress, int field)
{
}
void ff_thread_await_progress(ThreadFrame *f, int progress, int field)
{
}
int ff_thread_can_start_frame(AVCodecContext *avctx)
{
return 1;
}
int ff_alloc_entries(AVCodecContext *avctx, int count)
{
return 0;
}
void ff_reset_entries(AVCodecContext *avctx)
{
}
void ff_thread_await_progress2(AVCodecContext *avctx, int field, int thread, int shift)
{
}
void ff_thread_report_progress2(AVCodecContext *avctx, int field, int thread, int n)
{
}
#endif
int avcodec_is_open(AVCodecContext *s)
{
return !!s->internal;
}
int avpriv_bprint_to_extradata(AVCodecContext *avctx, struct AVBPrint *buf)
{
int ret;
char *str;
ret = av_bprint_finalize(buf, &str);
if (ret < 0)
return ret;
if (!av_bprint_is_complete(buf)) {
av_free(str);
return AVERROR(ENOMEM);
}
avctx->extradata = str;
/* Note: the string is NUL terminated (so extradata can be read as a
* string), but the ending character is not accounted in the size (in
* binary formats you are likely not supposed to mux that character). When
* extradata is copied, it is also padded with AV_INPUT_BUFFER_PADDING_SIZE
* zeros. */
avctx->extradata_size = buf->len;
return 0;
}
const uint8_t *avpriv_find_start_code(const uint8_t *av_restrict p,
const uint8_t *end,
uint32_t *av_restrict state)
{
int i;
av_assert0(p <= end);
if (p >= end)
return end;
for (i = 0; i < 3; i++) {
uint32_t tmp = *state << 8;
*state = tmp + *(p++);
if (tmp == 0x100 || p == end)
return p;
}
while (p < end) {
if (p[-1] > 1 ) p += 3;
else if (p[-2] ) p += 2;
else if (p[-3]|(p[-1]-1)) p++;
else {
p++;
break;
}
}
p = FFMIN(p, end) - 4;
*state = AV_RB32(p);
return p + 4;
}
AVCPBProperties *av_cpb_properties_alloc(size_t *size)
{
AVCPBProperties *props = av_mallocz(sizeof(AVCPBProperties));
if (!props)
return NULL;
if (size)
*size = sizeof(*props);
props->vbv_delay = UINT64_MAX;
return props;
}
AVCPBProperties *ff_add_cpb_side_data(AVCodecContext *avctx)
{
AVPacketSideData *tmp;
AVCPBProperties *props;
size_t size;
props = av_cpb_properties_alloc(&size);
if (!props)
return NULL;
tmp = av_realloc_array(avctx->coded_side_data, avctx->nb_coded_side_data + 1, sizeof(*tmp));
if (!tmp) {
av_freep(&props);
return NULL;
}
avctx->coded_side_data = tmp;
avctx->nb_coded_side_data++;
avctx->coded_side_data[avctx->nb_coded_side_data - 1].type = AV_PKT_DATA_CPB_PROPERTIES;
avctx->coded_side_data[avctx->nb_coded_side_data - 1].data = (uint8_t*)props;
avctx->coded_side_data[avctx->nb_coded_side_data - 1].size = size;
return props;
}
static void codec_parameters_reset(AVCodecParameters *par)
{
av_freep(&par->extradata);
memset(par, 0, sizeof(*par));
par->codec_type = AVMEDIA_TYPE_UNKNOWN;
par->codec_id = AV_CODEC_ID_NONE;
par->format = -1;
par->field_order = AV_FIELD_UNKNOWN;
par->color_range = AVCOL_RANGE_UNSPECIFIED;
par->color_primaries = AVCOL_PRI_UNSPECIFIED;
par->color_trc = AVCOL_TRC_UNSPECIFIED;
par->color_space = AVCOL_SPC_UNSPECIFIED;
par->chroma_location = AVCHROMA_LOC_UNSPECIFIED;
par->sample_aspect_ratio = (AVRational){ 0, 1 };
par->profile = FF_PROFILE_UNKNOWN;
par->level = FF_LEVEL_UNKNOWN;
}
AVCodecParameters *avcodec_parameters_alloc(void)
{
AVCodecParameters *par = av_mallocz(sizeof(*par));
if (!par)
return NULL;
codec_parameters_reset(par);
return par;
}
void avcodec_parameters_free(AVCodecParameters **ppar)
{
AVCodecParameters *par = *ppar;
if (!par)
return;
codec_parameters_reset(par);
av_freep(ppar);
}
int avcodec_parameters_copy(AVCodecParameters *dst, const AVCodecParameters *src)
{
codec_parameters_reset(dst);
memcpy(dst, src, sizeof(*dst));
dst->extradata = NULL;
dst->extradata_size = 0;
if (src->extradata) {
dst->extradata = av_mallocz(src->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
if (!dst->extradata)
return AVERROR(ENOMEM);
memcpy(dst->extradata, src->extradata, src->extradata_size);
dst->extradata_size = src->extradata_size;
}
return 0;
}
int avcodec_parameters_from_context(AVCodecParameters *par,
const AVCodecContext *codec)
{
codec_parameters_reset(par);
par->codec_type = codec->codec_type;
par->codec_id = codec->codec_id;
par->codec_tag = codec->codec_tag;
par->bit_rate = codec->bit_rate;
par->bits_per_coded_sample = codec->bits_per_coded_sample;
par->bits_per_raw_sample = codec->bits_per_raw_sample;
par->profile = codec->profile;
par->level = codec->level;
switch (par->codec_type) {
case AVMEDIA_TYPE_VIDEO:
par->format = codec->pix_fmt;
par->width = codec->width;
par->height = codec->height;
par->field_order = codec->field_order;
par->color_range = codec->color_range;
par->color_primaries = codec->color_primaries;
par->color_trc = codec->color_trc;
par->color_space = codec->colorspace;
par->chroma_location = codec->chroma_sample_location;
par->sample_aspect_ratio = codec->sample_aspect_ratio;
par->video_delay = codec->has_b_frames;
break;
case AVMEDIA_TYPE_AUDIO:
par->format = codec->sample_fmt;
par->channel_layout = codec->channel_layout;
par->channels = codec->channels;
par->sample_rate = codec->sample_rate;
par->block_align = codec->block_align;
par->frame_size = codec->frame_size;
par->initial_padding = codec->initial_padding;
par->trailing_padding = codec->trailing_padding;
par->seek_preroll = codec->seek_preroll;
break;
case AVMEDIA_TYPE_SUBTITLE:
par->width = codec->width;
par->height = codec->height;
break;
}
if (codec->extradata) {
par->extradata = av_mallocz(codec->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
if (!par->extradata)
return AVERROR(ENOMEM);
memcpy(par->extradata, codec->extradata, codec->extradata_size);
par->extradata_size = codec->extradata_size;
}
return 0;
}
int avcodec_parameters_to_context(AVCodecContext *codec,
const AVCodecParameters *par)
{
codec->codec_type = par->codec_type;
codec->codec_id = par->codec_id;
codec->codec_tag = par->codec_tag;
codec->bit_rate = par->bit_rate;
codec->bits_per_coded_sample = par->bits_per_coded_sample;
codec->bits_per_raw_sample = par->bits_per_raw_sample;
codec->profile = par->profile;
codec->level = par->level;
switch (par->codec_type) {
case AVMEDIA_TYPE_VIDEO:
codec->pix_fmt = par->format;
codec->width = par->width;
codec->height = par->height;
codec->field_order = par->field_order;
codec->color_range = par->color_range;
codec->color_primaries = par->color_primaries;
codec->color_trc = par->color_trc;
codec->colorspace = par->color_space;
codec->chroma_sample_location = par->chroma_location;
codec->sample_aspect_ratio = par->sample_aspect_ratio;
codec->has_b_frames = par->video_delay;
break;
case AVMEDIA_TYPE_AUDIO:
codec->sample_fmt = par->format;
codec->channel_layout = par->channel_layout;
codec->channels = par->channels;
codec->sample_rate = par->sample_rate;
codec->block_align = par->block_align;
codec->frame_size = par->frame_size;
codec->delay =
codec->initial_padding = par->initial_padding;
codec->trailing_padding = par->trailing_padding;
codec->seek_preroll = par->seek_preroll;
break;
case AVMEDIA_TYPE_SUBTITLE:
codec->width = par->width;
codec->height = par->height;
break;
}
if (par->extradata) {
av_freep(&codec->extradata);
codec->extradata = av_mallocz(par->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
if (!codec->extradata)
return AVERROR(ENOMEM);
memcpy(codec->extradata, par->extradata, par->extradata_size);
codec->extradata_size = par->extradata_size;
}
return 0;
}
int ff_alloc_a53_sei(const AVFrame *frame, size_t prefix_len,
void **data, size_t *sei_size)
{
AVFrameSideData *side_data = NULL;
uint8_t *sei_data;
if (frame)
side_data = av_frame_get_side_data(frame, AV_FRAME_DATA_A53_CC);
if (!side_data) {
*data = NULL;
return 0;
}
*sei_size = side_data->size + 11;
*data = av_mallocz(*sei_size + prefix_len);
if (!*data)
return AVERROR(ENOMEM);
sei_data = (uint8_t*)*data + prefix_len;
// country code
sei_data[0] = 181;
sei_data[1] = 0;
sei_data[2] = 49;
/**
* 'GA94' is standard in North America for ATSC, but hard coding
* this style may not be the right thing to do -- other formats
* do exist. This information is not available in the side_data
* so we are going with this right now.
*/
AV_WL32(sei_data + 3, MKTAG('G', 'A', '9', '4'));
sei_data[7] = 3;
sei_data[8] = ((side_data->size/3) & 0x1f) | 0x40;
sei_data[9] = 0;
memcpy(sei_data + 10, side_data->data, side_data->size);
sei_data[side_data->size+10] = 255;
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_3297_0 |
crossvul-cpp_data_bad_2760_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_apps_config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include "openjpeg.h"
#include "convert.h"
/*
* Get logarithm of an integer and round downwards.
*
* log2(a)
*/
static int int_floorlog2(int a)
{
int l;
for (l = 0; a > 1; l++) {
a >>= 1;
}
return l;
}
/* Component precision scaling */
void clip_component(opj_image_comp_t* component, OPJ_UINT32 precision)
{
OPJ_SIZE_T i;
OPJ_SIZE_T len;
OPJ_UINT32 umax = (OPJ_UINT32)((OPJ_INT32) - 1);
len = (OPJ_SIZE_T)component->w * (OPJ_SIZE_T)component->h;
if (precision < 32) {
umax = (1U << precision) - 1U;
}
if (component->sgnd) {
OPJ_INT32* l_data = component->data;
OPJ_INT32 max = (OPJ_INT32)(umax / 2U);
OPJ_INT32 min = -max - 1;
for (i = 0; i < len; ++i) {
if (l_data[i] > max) {
l_data[i] = max;
} else if (l_data[i] < min) {
l_data[i] = min;
}
}
} else {
OPJ_UINT32* l_data = (OPJ_UINT32*)component->data;
for (i = 0; i < len; ++i) {
if (l_data[i] > umax) {
l_data[i] = umax;
}
}
}
component->prec = precision;
}
/* Component precision scaling */
static void scale_component_up(opj_image_comp_t* component,
OPJ_UINT32 precision)
{
OPJ_SIZE_T i, len;
len = (OPJ_SIZE_T)component->w * (OPJ_SIZE_T)component->h;
if (component->sgnd) {
OPJ_INT64 newMax = (OPJ_INT64)(1U << (precision - 1));
OPJ_INT64 oldMax = (OPJ_INT64)(1U << (component->prec - 1));
OPJ_INT32* l_data = component->data;
for (i = 0; i < len; ++i) {
l_data[i] = (OPJ_INT32)(((OPJ_INT64)l_data[i] * newMax) / oldMax);
}
} else {
OPJ_UINT64 newMax = (OPJ_UINT64)((1U << precision) - 1U);
OPJ_UINT64 oldMax = (OPJ_UINT64)((1U << component->prec) - 1U);
OPJ_UINT32* l_data = (OPJ_UINT32*)component->data;
for (i = 0; i < len; ++i) {
l_data[i] = (OPJ_UINT32)(((OPJ_UINT64)l_data[i] * newMax) / oldMax);
}
}
component->prec = precision;
component->bpp = precision;
}
void scale_component(opj_image_comp_t* component, OPJ_UINT32 precision)
{
int shift;
OPJ_SIZE_T i, len;
if (component->prec == precision) {
return;
}
if (component->prec < precision) {
scale_component_up(component, precision);
return;
}
shift = (int)(component->prec - precision);
len = (OPJ_SIZE_T)component->w * (OPJ_SIZE_T)component->h;
if (component->sgnd) {
OPJ_INT32* l_data = component->data;
for (i = 0; i < len; ++i) {
l_data[i] >>= shift;
}
} else {
OPJ_UINT32* l_data = (OPJ_UINT32*)component->data;
for (i = 0; i < len; ++i) {
l_data[i] >>= shift;
}
}
component->bpp = precision;
component->prec = precision;
}
/* planar / interleaved conversions */
/* used by PNG/TIFF */
static void convert_32s_C1P1(const OPJ_INT32* pSrc, OPJ_INT32* const* pDst,
OPJ_SIZE_T length)
{
memcpy(pDst[0], pSrc, length * sizeof(OPJ_INT32));
}
static void convert_32s_C2P2(const OPJ_INT32* pSrc, OPJ_INT32* const* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
OPJ_INT32* pDst0 = pDst[0];
OPJ_INT32* pDst1 = pDst[1];
for (i = 0; i < length; i++) {
pDst0[i] = pSrc[2 * i + 0];
pDst1[i] = pSrc[2 * i + 1];
}
}
static void convert_32s_C3P3(const OPJ_INT32* pSrc, OPJ_INT32* const* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
OPJ_INT32* pDst0 = pDst[0];
OPJ_INT32* pDst1 = pDst[1];
OPJ_INT32* pDst2 = pDst[2];
for (i = 0; i < length; i++) {
pDst0[i] = pSrc[3 * i + 0];
pDst1[i] = pSrc[3 * i + 1];
pDst2[i] = pSrc[3 * i + 2];
}
}
static void convert_32s_C4P4(const OPJ_INT32* pSrc, OPJ_INT32* const* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
OPJ_INT32* pDst0 = pDst[0];
OPJ_INT32* pDst1 = pDst[1];
OPJ_INT32* pDst2 = pDst[2];
OPJ_INT32* pDst3 = pDst[3];
for (i = 0; i < length; i++) {
pDst0[i] = pSrc[4 * i + 0];
pDst1[i] = pSrc[4 * i + 1];
pDst2[i] = pSrc[4 * i + 2];
pDst3[i] = pSrc[4 * i + 3];
}
}
const convert_32s_CXPX convert_32s_CXPX_LUT[5] = {
NULL,
convert_32s_C1P1,
convert_32s_C2P2,
convert_32s_C3P3,
convert_32s_C4P4
};
static void convert_32s_P1C1(OPJ_INT32 const* const* pSrc, OPJ_INT32* pDst,
OPJ_SIZE_T length, OPJ_INT32 adjust)
{
OPJ_SIZE_T i;
const OPJ_INT32* pSrc0 = pSrc[0];
for (i = 0; i < length; i++) {
pDst[i] = pSrc0[i] + adjust;
}
}
static void convert_32s_P2C2(OPJ_INT32 const* const* pSrc, OPJ_INT32* pDst,
OPJ_SIZE_T length, OPJ_INT32 adjust)
{
OPJ_SIZE_T i;
const OPJ_INT32* pSrc0 = pSrc[0];
const OPJ_INT32* pSrc1 = pSrc[1];
for (i = 0; i < length; i++) {
pDst[2 * i + 0] = pSrc0[i] + adjust;
pDst[2 * i + 1] = pSrc1[i] + adjust;
}
}
static void convert_32s_P3C3(OPJ_INT32 const* const* pSrc, OPJ_INT32* pDst,
OPJ_SIZE_T length, OPJ_INT32 adjust)
{
OPJ_SIZE_T i;
const OPJ_INT32* pSrc0 = pSrc[0];
const OPJ_INT32* pSrc1 = pSrc[1];
const OPJ_INT32* pSrc2 = pSrc[2];
for (i = 0; i < length; i++) {
pDst[3 * i + 0] = pSrc0[i] + adjust;
pDst[3 * i + 1] = pSrc1[i] + adjust;
pDst[3 * i + 2] = pSrc2[i] + adjust;
}
}
static void convert_32s_P4C4(OPJ_INT32 const* const* pSrc, OPJ_INT32* pDst,
OPJ_SIZE_T length, OPJ_INT32 adjust)
{
OPJ_SIZE_T i;
const OPJ_INT32* pSrc0 = pSrc[0];
const OPJ_INT32* pSrc1 = pSrc[1];
const OPJ_INT32* pSrc2 = pSrc[2];
const OPJ_INT32* pSrc3 = pSrc[3];
for (i = 0; i < length; i++) {
pDst[4 * i + 0] = pSrc0[i] + adjust;
pDst[4 * i + 1] = pSrc1[i] + adjust;
pDst[4 * i + 2] = pSrc2[i] + adjust;
pDst[4 * i + 3] = pSrc3[i] + adjust;
}
}
const convert_32s_PXCX convert_32s_PXCX_LUT[5] = {
NULL,
convert_32s_P1C1,
convert_32s_P2C2,
convert_32s_P3C3,
convert_32s_P4C4
};
/* bit depth conversions */
/* used by PNG/TIFF up to 8bpp */
static void convert_1u32s_C1R(const OPJ_BYTE* pSrc, OPJ_INT32* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
for (i = 0; i < (length & ~(OPJ_SIZE_T)7U); i += 8U) {
OPJ_UINT32 val = *pSrc++;
pDst[i + 0] = (OPJ_INT32)(val >> 7);
pDst[i + 1] = (OPJ_INT32)((val >> 6) & 0x1U);
pDst[i + 2] = (OPJ_INT32)((val >> 5) & 0x1U);
pDst[i + 3] = (OPJ_INT32)((val >> 4) & 0x1U);
pDst[i + 4] = (OPJ_INT32)((val >> 3) & 0x1U);
pDst[i + 5] = (OPJ_INT32)((val >> 2) & 0x1U);
pDst[i + 6] = (OPJ_INT32)((val >> 1) & 0x1U);
pDst[i + 7] = (OPJ_INT32)(val & 0x1U);
}
if (length & 7U) {
OPJ_UINT32 val = *pSrc++;
length = length & 7U;
pDst[i + 0] = (OPJ_INT32)(val >> 7);
if (length > 1U) {
pDst[i + 1] = (OPJ_INT32)((val >> 6) & 0x1U);
if (length > 2U) {
pDst[i + 2] = (OPJ_INT32)((val >> 5) & 0x1U);
if (length > 3U) {
pDst[i + 3] = (OPJ_INT32)((val >> 4) & 0x1U);
if (length > 4U) {
pDst[i + 4] = (OPJ_INT32)((val >> 3) & 0x1U);
if (length > 5U) {
pDst[i + 5] = (OPJ_INT32)((val >> 2) & 0x1U);
if (length > 6U) {
pDst[i + 6] = (OPJ_INT32)((val >> 1) & 0x1U);
}
}
}
}
}
}
}
}
static void convert_2u32s_C1R(const OPJ_BYTE* pSrc, OPJ_INT32* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
for (i = 0; i < (length & ~(OPJ_SIZE_T)3U); i += 4U) {
OPJ_UINT32 val = *pSrc++;
pDst[i + 0] = (OPJ_INT32)(val >> 6);
pDst[i + 1] = (OPJ_INT32)((val >> 4) & 0x3U);
pDst[i + 2] = (OPJ_INT32)((val >> 2) & 0x3U);
pDst[i + 3] = (OPJ_INT32)(val & 0x3U);
}
if (length & 3U) {
OPJ_UINT32 val = *pSrc++;
length = length & 3U;
pDst[i + 0] = (OPJ_INT32)(val >> 6);
if (length > 1U) {
pDst[i + 1] = (OPJ_INT32)((val >> 4) & 0x3U);
if (length > 2U) {
pDst[i + 2] = (OPJ_INT32)((val >> 2) & 0x3U);
}
}
}
}
static void convert_4u32s_C1R(const OPJ_BYTE* pSrc, OPJ_INT32* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
for (i = 0; i < (length & ~(OPJ_SIZE_T)1U); i += 2U) {
OPJ_UINT32 val = *pSrc++;
pDst[i + 0] = (OPJ_INT32)(val >> 4);
pDst[i + 1] = (OPJ_INT32)(val & 0xFU);
}
if (length & 1U) {
OPJ_UINT8 val = *pSrc++;
pDst[i + 0] = (OPJ_INT32)(val >> 4);
}
}
static void convert_6u32s_C1R(const OPJ_BYTE* pSrc, OPJ_INT32* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
for (i = 0; i < (length & ~(OPJ_SIZE_T)3U); i += 4U) {
OPJ_UINT32 val0 = *pSrc++;
OPJ_UINT32 val1 = *pSrc++;
OPJ_UINT32 val2 = *pSrc++;
pDst[i + 0] = (OPJ_INT32)(val0 >> 2);
pDst[i + 1] = (OPJ_INT32)(((val0 & 0x3U) << 4) | (val1 >> 4));
pDst[i + 2] = (OPJ_INT32)(((val1 & 0xFU) << 2) | (val2 >> 6));
pDst[i + 3] = (OPJ_INT32)(val2 & 0x3FU);
}
if (length & 3U) {
OPJ_UINT32 val0 = *pSrc++;
length = length & 3U;
pDst[i + 0] = (OPJ_INT32)(val0 >> 2);
if (length > 1U) {
OPJ_UINT32 val1 = *pSrc++;
pDst[i + 1] = (OPJ_INT32)(((val0 & 0x3U) << 4) | (val1 >> 4));
if (length > 2U) {
OPJ_UINT32 val2 = *pSrc++;
pDst[i + 2] = (OPJ_INT32)(((val1 & 0xFU) << 2) | (val2 >> 6));
}
}
}
}
static void convert_8u32s_C1R(const OPJ_BYTE* pSrc, OPJ_INT32* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
for (i = 0; i < length; i++) {
pDst[i] = pSrc[i];
}
}
const convert_XXx32s_C1R convert_XXu32s_C1R_LUT[9] = {
NULL,
convert_1u32s_C1R,
convert_2u32s_C1R,
NULL,
convert_4u32s_C1R,
NULL,
convert_6u32s_C1R,
NULL,
convert_8u32s_C1R
};
static void convert_32s1u_C1R(const OPJ_INT32* pSrc, OPJ_BYTE* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
for (i = 0; i < (length & ~(OPJ_SIZE_T)7U); i += 8U) {
OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i + 0];
OPJ_UINT32 src1 = (OPJ_UINT32)pSrc[i + 1];
OPJ_UINT32 src2 = (OPJ_UINT32)pSrc[i + 2];
OPJ_UINT32 src3 = (OPJ_UINT32)pSrc[i + 3];
OPJ_UINT32 src4 = (OPJ_UINT32)pSrc[i + 4];
OPJ_UINT32 src5 = (OPJ_UINT32)pSrc[i + 5];
OPJ_UINT32 src6 = (OPJ_UINT32)pSrc[i + 6];
OPJ_UINT32 src7 = (OPJ_UINT32)pSrc[i + 7];
*pDst++ = (OPJ_BYTE)((src0 << 7) | (src1 << 6) | (src2 << 5) | (src3 << 4) |
(src4 << 3) | (src5 << 2) | (src6 << 1) | src7);
}
if (length & 7U) {
OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i + 0];
OPJ_UINT32 src1 = 0U;
OPJ_UINT32 src2 = 0U;
OPJ_UINT32 src3 = 0U;
OPJ_UINT32 src4 = 0U;
OPJ_UINT32 src5 = 0U;
OPJ_UINT32 src6 = 0U;
length = length & 7U;
if (length > 1U) {
src1 = (OPJ_UINT32)pSrc[i + 1];
if (length > 2U) {
src2 = (OPJ_UINT32)pSrc[i + 2];
if (length > 3U) {
src3 = (OPJ_UINT32)pSrc[i + 3];
if (length > 4U) {
src4 = (OPJ_UINT32)pSrc[i + 4];
if (length > 5U) {
src5 = (OPJ_UINT32)pSrc[i + 5];
if (length > 6U) {
src6 = (OPJ_UINT32)pSrc[i + 6];
}
}
}
}
}
}
*pDst++ = (OPJ_BYTE)((src0 << 7) | (src1 << 6) | (src2 << 5) | (src3 << 4) |
(src4 << 3) | (src5 << 2) | (src6 << 1));
}
}
static void convert_32s2u_C1R(const OPJ_INT32* pSrc, OPJ_BYTE* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
for (i = 0; i < (length & ~(OPJ_SIZE_T)3U); i += 4U) {
OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i + 0];
OPJ_UINT32 src1 = (OPJ_UINT32)pSrc[i + 1];
OPJ_UINT32 src2 = (OPJ_UINT32)pSrc[i + 2];
OPJ_UINT32 src3 = (OPJ_UINT32)pSrc[i + 3];
*pDst++ = (OPJ_BYTE)((src0 << 6) | (src1 << 4) | (src2 << 2) | src3);
}
if (length & 3U) {
OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i + 0];
OPJ_UINT32 src1 = 0U;
OPJ_UINT32 src2 = 0U;
length = length & 3U;
if (length > 1U) {
src1 = (OPJ_UINT32)pSrc[i + 1];
if (length > 2U) {
src2 = (OPJ_UINT32)pSrc[i + 2];
}
}
*pDst++ = (OPJ_BYTE)((src0 << 6) | (src1 << 4) | (src2 << 2));
}
}
static void convert_32s4u_C1R(const OPJ_INT32* pSrc, OPJ_BYTE* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
for (i = 0; i < (length & ~(OPJ_SIZE_T)1U); i += 2U) {
OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i + 0];
OPJ_UINT32 src1 = (OPJ_UINT32)pSrc[i + 1];
*pDst++ = (OPJ_BYTE)((src0 << 4) | src1);
}
if (length & 1U) {
OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i + 0];
*pDst++ = (OPJ_BYTE)((src0 << 4));
}
}
static void convert_32s6u_C1R(const OPJ_INT32* pSrc, OPJ_BYTE* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
for (i = 0; i < (length & ~(OPJ_SIZE_T)3U); i += 4U) {
OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i + 0];
OPJ_UINT32 src1 = (OPJ_UINT32)pSrc[i + 1];
OPJ_UINT32 src2 = (OPJ_UINT32)pSrc[i + 2];
OPJ_UINT32 src3 = (OPJ_UINT32)pSrc[i + 3];
*pDst++ = (OPJ_BYTE)((src0 << 2) | (src1 >> 4));
*pDst++ = (OPJ_BYTE)(((src1 & 0xFU) << 4) | (src2 >> 2));
*pDst++ = (OPJ_BYTE)(((src2 & 0x3U) << 6) | src3);
}
if (length & 3U) {
OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i + 0];
OPJ_UINT32 src1 = 0U;
OPJ_UINT32 src2 = 0U;
length = length & 3U;
if (length > 1U) {
src1 = (OPJ_UINT32)pSrc[i + 1];
if (length > 2U) {
src2 = (OPJ_UINT32)pSrc[i + 2];
}
}
*pDst++ = (OPJ_BYTE)((src0 << 2) | (src1 >> 4));
if (length > 1U) {
*pDst++ = (OPJ_BYTE)(((src1 & 0xFU) << 4) | (src2 >> 2));
if (length > 2U) {
*pDst++ = (OPJ_BYTE)(((src2 & 0x3U) << 6));
}
}
}
}
static void convert_32s8u_C1R(const OPJ_INT32* pSrc, OPJ_BYTE* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
for (i = 0; i < length; ++i) {
pDst[i] = (OPJ_BYTE)pSrc[i];
}
}
const convert_32sXXx_C1R convert_32sXXu_C1R_LUT[9] = {
NULL,
convert_32s1u_C1R,
convert_32s2u_C1R,
NULL,
convert_32s4u_C1R,
NULL,
convert_32s6u_C1R,
NULL,
convert_32s8u_C1R
};
/* -->> -->> -->> -->>
TGA IMAGE FORMAT
<<-- <<-- <<-- <<-- */
#ifdef INFORMATION_ONLY
/* TGA header definition. */
struct tga_header {
unsigned char id_length; /* Image id field length */
unsigned char colour_map_type; /* Colour map type */
unsigned char image_type; /* Image type */
/*
** Colour map specification
*/
unsigned short colour_map_index; /* First entry index */
unsigned short colour_map_length; /* Colour map length */
unsigned char colour_map_entry_size; /* Colour map entry size */
/*
** Image specification
*/
unsigned short x_origin; /* x origin of image */
unsigned short y_origin; /* u origin of image */
unsigned short image_width; /* Image width */
unsigned short image_height; /* Image height */
unsigned char pixel_depth; /* Pixel depth */
unsigned char image_desc; /* Image descriptor */
};
#endif /* INFORMATION_ONLY */
/* Returns a ushort from a little-endian serialized value */
static unsigned short get_tga_ushort(const unsigned char *data)
{
return (unsigned short)(data[0] | (data[1] << 8));
}
#define TGA_HEADER_SIZE 18
static int tga_readheader(FILE *fp, unsigned int *bits_per_pixel,
unsigned int *width, unsigned int *height, int *flip_image)
{
int palette_size;
unsigned char tga[TGA_HEADER_SIZE];
unsigned char id_len, /*cmap_type,*/ image_type;
unsigned char pixel_depth, image_desc;
unsigned short /*cmap_index,*/ cmap_len, cmap_entry_size;
unsigned short /*x_origin, y_origin,*/ image_w, image_h;
if (!bits_per_pixel || !width || !height || !flip_image) {
return 0;
}
if (fread(tga, TGA_HEADER_SIZE, 1, fp) != 1) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
return 0 ;
}
id_len = tga[0];
/*cmap_type = tga[1];*/
image_type = tga[2];
/*cmap_index = get_tga_ushort(&tga[3]);*/
cmap_len = get_tga_ushort(&tga[5]);
cmap_entry_size = tga[7];
#if 0
x_origin = get_tga_ushort(&tga[8]);
y_origin = get_tga_ushort(&tga[10]);
#endif
image_w = get_tga_ushort(&tga[12]);
image_h = get_tga_ushort(&tga[14]);
pixel_depth = tga[16];
image_desc = tga[17];
*bits_per_pixel = (unsigned int)pixel_depth;
*width = (unsigned int)image_w;
*height = (unsigned int)image_h;
/* Ignore tga identifier, if present ... */
if (id_len) {
unsigned char *id = (unsigned char *) malloc(id_len);
if (id == 0) {
fprintf(stderr, "tga_readheader: memory out\n");
return 0;
}
if (!fread(id, id_len, 1, fp)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
free(id);
return 0 ;
}
free(id);
}
/* Test for compressed formats ... not yet supported ...
// Note :- 9 - RLE encoded palettized.
// 10 - RLE encoded RGB. */
if (image_type > 8) {
fprintf(stderr, "Sorry, compressed tga files are not currently supported.\n");
return 0 ;
}
*flip_image = !(image_desc & 32);
/* Palettized formats are not yet supported, skip over the palette, if present ... */
palette_size = cmap_len * (cmap_entry_size / 8);
if (palette_size > 0) {
fprintf(stderr, "File contains a palette - not yet supported.");
fseek(fp, palette_size, SEEK_CUR);
}
return 1;
}
#ifdef OPJ_BIG_ENDIAN
static INLINE OPJ_UINT16 swap16(OPJ_UINT16 x)
{
return (OPJ_UINT16)(((x & 0x00ffU) << 8) | ((x & 0xff00U) >> 8));
}
#endif
static int tga_writeheader(FILE *fp, int bits_per_pixel, int width, int height,
OPJ_BOOL flip_image)
{
OPJ_UINT16 image_w, image_h, us0;
unsigned char uc0, image_type;
unsigned char pixel_depth, image_desc;
if (!bits_per_pixel || !width || !height) {
return 0;
}
pixel_depth = 0;
if (bits_per_pixel < 256) {
pixel_depth = (unsigned char)bits_per_pixel;
} else {
fprintf(stderr, "ERROR: Wrong bits per pixel inside tga_header");
return 0;
}
uc0 = 0;
if (fwrite(&uc0, 1, 1, fp) != 1) {
goto fails; /* id_length */
}
if (fwrite(&uc0, 1, 1, fp) != 1) {
goto fails; /* colour_map_type */
}
image_type = 2; /* Uncompressed. */
if (fwrite(&image_type, 1, 1, fp) != 1) {
goto fails;
}
us0 = 0;
if (fwrite(&us0, 2, 1, fp) != 1) {
goto fails; /* colour_map_index */
}
if (fwrite(&us0, 2, 1, fp) != 1) {
goto fails; /* colour_map_length */
}
if (fwrite(&uc0, 1, 1, fp) != 1) {
goto fails; /* colour_map_entry_size */
}
if (fwrite(&us0, 2, 1, fp) != 1) {
goto fails; /* x_origin */
}
if (fwrite(&us0, 2, 1, fp) != 1) {
goto fails; /* y_origin */
}
image_w = (unsigned short)width;
image_h = (unsigned short) height;
#ifndef OPJ_BIG_ENDIAN
if (fwrite(&image_w, 2, 1, fp) != 1) {
goto fails;
}
if (fwrite(&image_h, 2, 1, fp) != 1) {
goto fails;
}
#else
image_w = swap16(image_w);
image_h = swap16(image_h);
if (fwrite(&image_w, 2, 1, fp) != 1) {
goto fails;
}
if (fwrite(&image_h, 2, 1, fp) != 1) {
goto fails;
}
#endif
if (fwrite(&pixel_depth, 1, 1, fp) != 1) {
goto fails;
}
image_desc = 8; /* 8 bits per component. */
if (flip_image) {
image_desc |= 32;
}
if (fwrite(&image_desc, 1, 1, fp) != 1) {
goto fails;
}
return 1;
fails:
fputs("\nwrite_tgaheader: write ERROR\n", stderr);
return 0;
}
opj_image_t* tgatoimage(const char *filename, opj_cparameters_t *parameters)
{
FILE *f;
opj_image_t *image;
unsigned int image_width, image_height, pixel_bit_depth;
unsigned int x, y;
int flip_image = 0;
opj_image_cmptparm_t cmptparm[4]; /* maximum 4 components */
int numcomps;
OPJ_COLOR_SPACE color_space;
OPJ_BOOL mono ;
OPJ_BOOL save_alpha;
int subsampling_dx, subsampling_dy;
int i;
f = fopen(filename, "rb");
if (!f) {
fprintf(stderr, "Failed to open %s for reading !!\n", filename);
return 0;
}
if (!tga_readheader(f, &pixel_bit_depth, &image_width, &image_height,
&flip_image)) {
fclose(f);
return NULL;
}
/* We currently only support 24 & 32 bit tga's ... */
if (!((pixel_bit_depth == 24) || (pixel_bit_depth == 32))) {
fclose(f);
return NULL;
}
/* initialize image components */
memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));
mono = (pixel_bit_depth == 8) ||
(pixel_bit_depth == 16); /* Mono with & without alpha. */
save_alpha = (pixel_bit_depth == 16) ||
(pixel_bit_depth == 32); /* Mono with alpha, or RGB with alpha */
if (mono) {
color_space = OPJ_CLRSPC_GRAY;
numcomps = save_alpha ? 2 : 1;
} else {
numcomps = save_alpha ? 4 : 3;
color_space = OPJ_CLRSPC_SRGB;
}
/* If the declared file size is > 10 MB, check that the file is big */
/* enough to avoid excessive memory allocations */
if (image_height != 0 &&
image_width > 10000000U / image_height / (OPJ_UINT32)numcomps) {
char ch;
OPJ_UINT64 expected_file_size =
(OPJ_UINT64)image_width * image_height * (OPJ_UINT32)numcomps;
long curpos = ftell(f);
if (expected_file_size > (OPJ_UINT64)INT_MAX) {
expected_file_size = (OPJ_UINT64)INT_MAX;
}
fseek(f, (long)expected_file_size - 1, SEEK_SET);
if (fread(&ch, 1, 1, f) != 1) {
fclose(f);
return NULL;
}
fseek(f, curpos, SEEK_SET);
}
subsampling_dx = parameters->subsampling_dx;
subsampling_dy = parameters->subsampling_dy;
for (i = 0; i < numcomps; i++) {
cmptparm[i].prec = 8;
cmptparm[i].bpp = 8;
cmptparm[i].sgnd = 0;
cmptparm[i].dx = (OPJ_UINT32)subsampling_dx;
cmptparm[i].dy = (OPJ_UINT32)subsampling_dy;
cmptparm[i].w = image_width;
cmptparm[i].h = image_height;
}
/* create the image */
image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
if (!image) {
fclose(f);
return NULL;
}
/* set image offset and reference grid */
image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
image->x1 = !image->x0 ? (OPJ_UINT32)(image_width - 1) *
(OPJ_UINT32)subsampling_dx + 1 : image->x0 + (OPJ_UINT32)(image_width - 1) *
(OPJ_UINT32)subsampling_dx + 1;
image->y1 = !image->y0 ? (OPJ_UINT32)(image_height - 1) *
(OPJ_UINT32)subsampling_dy + 1 : image->y0 + (OPJ_UINT32)(image_height - 1) *
(OPJ_UINT32)subsampling_dy + 1;
/* set image data */
for (y = 0; y < image_height; y++) {
int index;
if (flip_image) {
index = (int)((image_height - y - 1) * image_width);
} else {
index = (int)(y * image_width);
}
if (numcomps == 3) {
for (x = 0; x < image_width; x++) {
unsigned char r, g, b;
if (!fread(&b, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&g, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&r, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
image->comps[0].data[index] = r;
image->comps[1].data[index] = g;
image->comps[2].data[index] = b;
index++;
}
} else if (numcomps == 4) {
for (x = 0; x < image_width; x++) {
unsigned char r, g, b, a;
if (!fread(&b, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&g, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&r, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&a, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
image->comps[0].data[index] = r;
image->comps[1].data[index] = g;
image->comps[2].data[index] = b;
image->comps[3].data[index] = a;
index++;
}
} else {
fprintf(stderr, "Currently unsupported bit depth : %s\n", filename);
}
}
fclose(f);
return image;
}
int imagetotga(opj_image_t * image, const char *outfile)
{
int width, height, bpp, x, y;
OPJ_BOOL write_alpha;
unsigned int i;
int adjustR, adjustG = 0, adjustB = 0, fails;
unsigned int alpha_channel;
float r, g, b, a;
unsigned char value;
float scale;
FILE *fdest;
size_t res;
fails = 1;
fdest = fopen(outfile, "wb");
if (!fdest) {
fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
return 1;
}
for (i = 0; i < image->numcomps - 1; i++) {
if ((image->comps[0].dx != image->comps[i + 1].dx)
|| (image->comps[0].dy != image->comps[i + 1].dy)
|| (image->comps[0].prec != image->comps[i + 1].prec)
|| (image->comps[0].sgnd != image->comps[i + 1].sgnd)) {
fclose(fdest);
fprintf(stderr,
"Unable to create a tga file with such J2K image charateristics.\n");
return 1;
}
}
width = (int)image->comps[0].w;
height = (int)image->comps[0].h;
/* Mono with alpha, or RGB with alpha. */
write_alpha = (image->numcomps == 2) || (image->numcomps == 4);
/* Write TGA header */
bpp = write_alpha ? 32 : 24;
if (!tga_writeheader(fdest, bpp, width, height, OPJ_TRUE)) {
goto fin;
}
alpha_channel = image->numcomps - 1;
scale = 255.0f / (float)((1 << image->comps[0].prec) - 1);
adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
if (image->numcomps >= 3) {
adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
}
for (y = 0; y < height; y++) {
unsigned int index = (unsigned int)(y * width);
for (x = 0; x < width; x++, index++) {
r = (float)(image->comps[0].data[index] + adjustR);
if (image->numcomps > 2) {
g = (float)(image->comps[1].data[index] + adjustG);
b = (float)(image->comps[2].data[index] + adjustB);
} else {
/* Greyscale ... */
g = r;
b = r;
}
/* TGA format writes BGR ... */
if (b > 255.) {
b = 255.;
} else if (b < 0.) {
b = 0.;
}
value = (unsigned char)(b * scale);
res = fwrite(&value, 1, 1, fdest);
if (res < 1) {
fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
goto fin;
}
if (g > 255.) {
g = 255.;
} else if (g < 0.) {
g = 0.;
}
value = (unsigned char)(g * scale);
res = fwrite(&value, 1, 1, fdest);
if (res < 1) {
fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
goto fin;
}
if (r > 255.) {
r = 255.;
} else if (r < 0.) {
r = 0.;
}
value = (unsigned char)(r * scale);
res = fwrite(&value, 1, 1, fdest);
if (res < 1) {
fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
goto fin;
}
if (write_alpha) {
a = (float)(image->comps[alpha_channel].data[index]);
if (a > 255.) {
a = 255.;
} else if (a < 0.) {
a = 0.;
}
value = (unsigned char)(a * scale);
res = fwrite(&value, 1, 1, fdest);
if (res < 1) {
fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
goto fin;
}
}
}
}
fails = 0;
fin:
fclose(fdest);
return fails;
}
/* -->> -->> -->> -->>
PGX IMAGE FORMAT
<<-- <<-- <<-- <<-- */
static unsigned char readuchar(FILE * f)
{
unsigned char c1;
if (!fread(&c1, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
return 0;
}
return c1;
}
static unsigned short readushort(FILE * f, int bigendian)
{
unsigned char c1, c2;
if (!fread(&c1, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
return 0;
}
if (!fread(&c2, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
return 0;
}
if (bigendian) {
return (unsigned short)((c1 << 8) + c2);
} else {
return (unsigned short)((c2 << 8) + c1);
}
}
static unsigned int readuint(FILE * f, int bigendian)
{
unsigned char c1, c2, c3, c4;
if (!fread(&c1, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
return 0;
}
if (!fread(&c2, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
return 0;
}
if (!fread(&c3, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
return 0;
}
if (!fread(&c4, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
return 0;
}
if (bigendian) {
return (unsigned int)(c1 << 24) + (unsigned int)(c2 << 16) + (unsigned int)(
c3 << 8) + c4;
} else {
return (unsigned int)(c4 << 24) + (unsigned int)(c3 << 16) + (unsigned int)(
c2 << 8) + c1;
}
}
opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters)
{
FILE *f = NULL;
int w, h, prec;
int i, numcomps, max;
OPJ_COLOR_SPACE color_space;
opj_image_cmptparm_t cmptparm; /* maximum of 1 component */
opj_image_t * image = NULL;
int adjustS, ushift, dshift, force8;
char endian1, endian2, sign;
char signtmp[32];
char temp[32];
int bigendian;
opj_image_comp_t *comp = NULL;
numcomps = 1;
color_space = OPJ_CLRSPC_GRAY;
memset(&cmptparm, 0, sizeof(opj_image_cmptparm_t));
max = 0;
f = fopen(filename, "rb");
if (!f) {
fprintf(stderr, "Failed to open %s for reading !\n", filename);
return NULL;
}
fseek(f, 0, SEEK_SET);
if (fscanf(f, "PG%[ \t]%c%c%[ \t+-]%d%[ \t]%d%[ \t]%d", temp, &endian1,
&endian2, signtmp, &prec, temp, &w, temp, &h) != 9) {
fclose(f);
fprintf(stderr,
"ERROR: Failed to read the right number of element from the fscanf() function!\n");
return NULL;
}
i = 0;
sign = '+';
while (signtmp[i] != '\0') {
if (signtmp[i] == '-') {
sign = '-';
}
i++;
}
fgetc(f);
if (endian1 == 'M' && endian2 == 'L') {
bigendian = 1;
} else if (endian2 == 'M' && endian1 == 'L') {
bigendian = 0;
} else {
fclose(f);
fprintf(stderr, "Bad pgx header, please check input file\n");
return NULL;
}
/* initialize image component */
cmptparm.x0 = (OPJ_UINT32)parameters->image_offset_x0;
cmptparm.y0 = (OPJ_UINT32)parameters->image_offset_y0;
cmptparm.w = !cmptparm.x0 ? (OPJ_UINT32)((w - 1) * parameters->subsampling_dx +
1) : cmptparm.x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)parameters->subsampling_dx
+ 1;
cmptparm.h = !cmptparm.y0 ? (OPJ_UINT32)((h - 1) * parameters->subsampling_dy +
1) : cmptparm.y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)parameters->subsampling_dy
+ 1;
if (sign == '-') {
cmptparm.sgnd = 1;
} else {
cmptparm.sgnd = 0;
}
if (prec < 8) {
force8 = 1;
ushift = 8 - prec;
dshift = prec - ushift;
if (cmptparm.sgnd) {
adjustS = (1 << (prec - 1));
} else {
adjustS = 0;
}
cmptparm.sgnd = 0;
prec = 8;
} else {
ushift = dshift = force8 = adjustS = 0;
}
cmptparm.prec = (OPJ_UINT32)prec;
cmptparm.bpp = (OPJ_UINT32)prec;
cmptparm.dx = (OPJ_UINT32)parameters->subsampling_dx;
cmptparm.dy = (OPJ_UINT32)parameters->subsampling_dy;
/* create the image */
image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm, color_space);
if (!image) {
fclose(f);
return NULL;
}
/* set image offset and reference grid */
image->x0 = cmptparm.x0;
image->y0 = cmptparm.x0;
image->x1 = cmptparm.w;
image->y1 = cmptparm.h;
/* set image data */
comp = &image->comps[0];
for (i = 0; i < w * h; i++) {
int v;
if (force8) {
v = readuchar(f) + adjustS;
v = (v << ushift) + (v >> dshift);
comp->data[i] = (unsigned char)v;
if (v > max) {
max = v;
}
continue;
}
if (comp->prec == 8) {
if (!comp->sgnd) {
v = readuchar(f);
} else {
v = (char) readuchar(f);
}
} else if (comp->prec <= 16) {
if (!comp->sgnd) {
v = readushort(f, bigendian);
} else {
v = (short) readushort(f, bigendian);
}
} else {
if (!comp->sgnd) {
v = (int)readuint(f, bigendian);
} else {
v = (int) readuint(f, bigendian);
}
}
if (v > max) {
max = v;
}
comp->data[i] = v;
}
fclose(f);
comp->bpp = (OPJ_UINT32)int_floorlog2(max) + 1;
return image;
}
#define CLAMP(x,a,b) x < a ? a : (x > b ? b : x)
static INLINE int clamp(const int value, const int prec, const int sgnd)
{
if (sgnd) {
if (prec <= 8) {
return CLAMP(value, -128, 127);
} else if (prec <= 16) {
return CLAMP(value, -32768, 32767);
} else {
return CLAMP(value, -2147483647 - 1, 2147483647);
}
} else {
if (prec <= 8) {
return CLAMP(value, 0, 255);
} else if (prec <= 16) {
return CLAMP(value, 0, 65535);
} else {
return value; /*CLAMP(value,0,4294967295);*/
}
}
}
int imagetopgx(opj_image_t * image, const char *outfile)
{
int w, h;
int i, j, fails = 1;
unsigned int compno;
FILE *fdest = NULL;
for (compno = 0; compno < image->numcomps; compno++) {
opj_image_comp_t *comp = &image->comps[compno];
char bname[256]; /* buffer for name */
char *name = bname; /* pointer */
int nbytes = 0;
size_t res;
const size_t olen = strlen(outfile);
const size_t dotpos = olen - 4;
const size_t total = dotpos + 1 + 1 + 4; /* '-' + '[1-3]' + '.pgx' */
if (outfile[dotpos] != '.') {
/* `pgx` was recognized but there is no dot at expected position */
fprintf(stderr, "ERROR -> Impossible happen.");
goto fin;
}
if (total > 256) {
name = (char*)malloc(total + 1);
if (name == NULL) {
fprintf(stderr, "imagetopgx: memory out\n");
goto fin;
}
}
strncpy(name, outfile, dotpos);
sprintf(name + dotpos, "_%u.pgx", compno);
fdest = fopen(name, "wb");
/* don't need name anymore */
if (!fdest) {
fprintf(stderr, "ERROR -> failed to open %s for writing\n", name);
if (total > 256) {
free(name);
}
goto fin;
}
w = (int)image->comps[compno].w;
h = (int)image->comps[compno].h;
fprintf(fdest, "PG ML %c %d %d %d\n", comp->sgnd ? '-' : '+', comp->prec,
w, h);
if (comp->prec <= 8) {
nbytes = 1;
} else if (comp->prec <= 16) {
nbytes = 2;
} else {
nbytes = 4;
}
for (i = 0; i < w * h; i++) {
/* FIXME: clamp func is being called within a loop */
const int val = clamp(image->comps[compno].data[i],
(int)comp->prec, (int)comp->sgnd);
for (j = nbytes - 1; j >= 0; j--) {
int v = (int)(val >> (j * 8));
unsigned char byte = (unsigned char)v;
res = fwrite(&byte, 1, 1, fdest);
if (res < 1) {
fprintf(stderr, "failed to write 1 byte for %s\n", name);
if (total > 256) {
free(name);
}
goto fin;
}
}
}
if (total > 256) {
free(name);
}
fclose(fdest);
fdest = NULL;
}
fails = 0;
fin:
if (fdest) {
fclose(fdest);
}
return fails;
}
/* -->> -->> -->> -->>
PNM IMAGE FORMAT
<<-- <<-- <<-- <<-- */
struct pnm_header {
int width, height, maxval, depth, format;
char rgb, rgba, gray, graya, bw;
char ok;
};
static char *skip_white(char *s)
{
if (s != NULL) {
while (*s) {
if (*s == '\n' || *s == '\r') {
return NULL;
}
if (isspace(*s)) {
++s;
continue;
}
return s;
}
}
return NULL;
}
static char *skip_int(char *start, int *out_n)
{
char *s;
char c;
*out_n = 0;
s = skip_white(start);
if (s == NULL) {
return NULL;
}
start = s;
while (*s) {
if (!isdigit(*s)) {
break;
}
++s;
}
c = *s;
*s = 0;
*out_n = atoi(start);
*s = c;
return s;
}
static char *skip_idf(char *start, char out_idf[256])
{
char *s;
char c;
s = skip_white(start);
if (s == NULL) {
return NULL;
}
start = s;
while (*s) {
if (isalpha(*s) || *s == '_') {
++s;
continue;
}
break;
}
c = *s;
*s = 0;
strncpy(out_idf, start, 255);
*s = c;
return s;
}
static void read_pnm_header(FILE *reader, struct pnm_header *ph)
{
int format, end, ttype;
char idf[256], type[256];
char line[256];
if (fgets(line, 250, reader) == NULL) {
fprintf(stderr, "\nWARNING: fgets return a NULL value");
return;
}
if (line[0] != 'P') {
fprintf(stderr, "read_pnm_header:PNM:magic P missing\n");
return;
}
format = atoi(line + 1);
if (format < 1 || format > 7) {
fprintf(stderr, "read_pnm_header:magic format %d invalid\n", format);
return;
}
ph->format = format;
ttype = end = 0;
while (fgets(line, 250, reader)) {
char *s;
int allow_null = 0;
if (*line == '#') {
continue;
}
s = line;
if (format == 7) {
s = skip_idf(s, idf);
if (s == NULL || *s == 0) {
return;
}
if (strcmp(idf, "ENDHDR") == 0) {
end = 1;
break;
}
if (strcmp(idf, "WIDTH") == 0) {
s = skip_int(s, &ph->width);
if (s == NULL || *s == 0) {
return;
}
continue;
}
if (strcmp(idf, "HEIGHT") == 0) {
s = skip_int(s, &ph->height);
if (s == NULL || *s == 0) {
return;
}
continue;
}
if (strcmp(idf, "DEPTH") == 0) {
s = skip_int(s, &ph->depth);
if (s == NULL || *s == 0) {
return;
}
continue;
}
if (strcmp(idf, "MAXVAL") == 0) {
s = skip_int(s, &ph->maxval);
if (s == NULL || *s == 0) {
return;
}
continue;
}
if (strcmp(idf, "TUPLTYPE") == 0) {
s = skip_idf(s, type);
if (s == NULL || *s == 0) {
return;
}
if (strcmp(type, "BLACKANDWHITE") == 0) {
ph->bw = 1;
ttype = 1;
continue;
}
if (strcmp(type, "GRAYSCALE") == 0) {
ph->gray = 1;
ttype = 1;
continue;
}
if (strcmp(type, "GRAYSCALE_ALPHA") == 0) {
ph->graya = 1;
ttype = 1;
continue;
}
if (strcmp(type, "RGB") == 0) {
ph->rgb = 1;
ttype = 1;
continue;
}
if (strcmp(type, "RGB_ALPHA") == 0) {
ph->rgba = 1;
ttype = 1;
continue;
}
fprintf(stderr, "read_pnm_header:unknown P7 TUPLTYPE %s\n", type);
return;
}
fprintf(stderr, "read_pnm_header:unknown P7 idf %s\n", idf);
return;
} /* if(format == 7) */
/* Here format is in range [1,6] */
if (ph->width == 0) {
s = skip_int(s, &ph->width);
if ((s == NULL) || (*s == 0) || (ph->width < 1)) {
return;
}
allow_null = 1;
}
if (ph->height == 0) {
s = skip_int(s, &ph->height);
if ((s == NULL) && allow_null) {
continue;
}
if ((s == NULL) || (*s == 0) || (ph->height < 1)) {
return;
}
if (format == 1 || format == 4) {
break;
}
allow_null = 1;
}
/* here, format is in P2, P3, P5, P6 */
s = skip_int(s, &ph->maxval);
if ((s == NULL) && allow_null) {
continue;
}
if ((s == NULL) || (*s == 0)) {
return;
}
break;
}/* while(fgets( ) */
if (format == 2 || format == 3 || format > 4) {
if (ph->maxval < 1 || ph->maxval > 65535) {
return;
}
}
if (ph->width < 1 || ph->height < 1) {
return;
}
if (format == 7) {
if (!end) {
fprintf(stderr, "read_pnm_header:P7 without ENDHDR\n");
return;
}
if (ph->depth < 1 || ph->depth > 4) {
return;
}
if (ttype) {
ph->ok = 1;
}
} else {
ph->ok = 1;
if (format == 1 || format == 4) {
ph->maxval = 255;
}
}
}
static int has_prec(int val)
{
if (val < 2) {
return 1;
}
if (val < 4) {
return 2;
}
if (val < 8) {
return 3;
}
if (val < 16) {
return 4;
}
if (val < 32) {
return 5;
}
if (val < 64) {
return 6;
}
if (val < 128) {
return 7;
}
if (val < 256) {
return 8;
}
if (val < 512) {
return 9;
}
if (val < 1024) {
return 10;
}
if (val < 2048) {
return 11;
}
if (val < 4096) {
return 12;
}
if (val < 8192) {
return 13;
}
if (val < 16384) {
return 14;
}
if (val < 32768) {
return 15;
}
return 16;
}
opj_image_t* pnmtoimage(const char *filename, opj_cparameters_t *parameters)
{
int subsampling_dx = parameters->subsampling_dx;
int subsampling_dy = parameters->subsampling_dy;
FILE *fp = NULL;
int i, compno, numcomps, w, h, prec, format;
OPJ_COLOR_SPACE color_space;
opj_image_cmptparm_t cmptparm[4]; /* RGBA: max. 4 components */
opj_image_t * image = NULL;
struct pnm_header header_info;
if ((fp = fopen(filename, "rb")) == NULL) {
fprintf(stderr, "pnmtoimage:Failed to open %s for reading!\n", filename);
return NULL;
}
memset(&header_info, 0, sizeof(struct pnm_header));
read_pnm_header(fp, &header_info);
if (!header_info.ok) {
fclose(fp);
return NULL;
}
/* This limitation could be removed by making sure to use size_t below */
if (header_info.height != 0 &&
header_info.width > INT_MAX / header_info.height) {
fprintf(stderr, "pnmtoimage:Image %dx%d too big!\n",
header_info.width, header_info.height);
fclose(fp);
return NULL;
}
format = header_info.format;
switch (format) {
case 1: /* ascii bitmap */
case 4: /* raw bitmap */
numcomps = 1;
break;
case 2: /* ascii greymap */
case 5: /* raw greymap */
numcomps = 1;
break;
case 3: /* ascii pixmap */
case 6: /* raw pixmap */
numcomps = 3;
break;
case 7: /* arbitrary map */
numcomps = header_info.depth;
break;
default:
fclose(fp);
return NULL;
}
if (numcomps < 3) {
color_space = OPJ_CLRSPC_GRAY; /* GRAY, GRAYA */
} else {
color_space = OPJ_CLRSPC_SRGB; /* RGB, RGBA */
}
prec = has_prec(header_info.maxval);
if (prec < 8) {
prec = 8;
}
w = header_info.width;
h = header_info.height;
subsampling_dx = parameters->subsampling_dx;
subsampling_dy = parameters->subsampling_dy;
memset(&cmptparm[0], 0, (size_t)numcomps * sizeof(opj_image_cmptparm_t));
for (i = 0; i < numcomps; i++) {
cmptparm[i].prec = (OPJ_UINT32)prec;
cmptparm[i].bpp = (OPJ_UINT32)prec;
cmptparm[i].sgnd = 0;
cmptparm[i].dx = (OPJ_UINT32)subsampling_dx;
cmptparm[i].dy = (OPJ_UINT32)subsampling_dy;
cmptparm[i].w = (OPJ_UINT32)w;
cmptparm[i].h = (OPJ_UINT32)h;
}
image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
if (!image) {
fclose(fp);
return NULL;
}
/* set image offset and reference grid */
image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
image->x1 = (OPJ_UINT32)(parameters->image_offset_x0 + (w - 1) * subsampling_dx
+ 1);
image->y1 = (OPJ_UINT32)(parameters->image_offset_y0 + (h - 1) * subsampling_dy
+ 1);
if ((format == 2) || (format == 3)) { /* ascii pixmap */
unsigned int index;
for (i = 0; i < w * h; i++) {
for (compno = 0; compno < numcomps; compno++) {
index = 0;
if (fscanf(fp, "%u", &index) != 1) {
fprintf(stderr,
"\nWARNING: fscanf return a number of element different from the expected.\n");
}
image->comps[compno].data[i] = (OPJ_INT32)(index * 255) / header_info.maxval;
}
}
} else if ((format == 5)
|| (format == 6)
|| ((format == 7)
&& (header_info.gray || header_info.graya
|| header_info.rgb || header_info.rgba))) { /* binary pixmap */
unsigned char c0, c1, one;
one = (prec < 9);
for (i = 0; i < w * h; i++) {
for (compno = 0; compno < numcomps; compno++) {
if (!fread(&c0, 1, 1, fp)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(fp);
return NULL;
}
if (one) {
image->comps[compno].data[i] = c0;
} else {
if (!fread(&c1, 1, 1, fp)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
}
/* netpbm: */
image->comps[compno].data[i] = ((c0 << 8) | c1);
}
}
}
} else if (format == 1) { /* ascii bitmap */
for (i = 0; i < w * h; i++) {
unsigned int index;
if (fscanf(fp, "%u", &index) != 1) {
fprintf(stderr,
"\nWARNING: fscanf return a number of element different from the expected.\n");
}
image->comps[0].data[i] = (index ? 0 : 255);
}
} else if (format == 4) {
int x, y, bit;
unsigned char uc;
i = 0;
for (y = 0; y < h; ++y) {
bit = -1;
uc = 0;
for (x = 0; x < w; ++x) {
if (bit == -1) {
bit = 7;
uc = (unsigned char)getc(fp);
}
image->comps[0].data[i] = (((uc >> bit) & 1) ? 0 : 255);
--bit;
++i;
}
}
} else if ((format == 7 && header_info.bw)) { /*MONO*/
unsigned char uc;
for (i = 0; i < w * h; ++i) {
if (!fread(&uc, 1, 1, fp)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
}
image->comps[0].data[i] = (uc & 1) ? 0 : 255;
}
}
fclose(fp);
return image;
}/* pnmtoimage() */
static int are_comps_similar(opj_image_t * image)
{
unsigned int i;
for (i = 1; i < image->numcomps; i++) {
if (image->comps[0].dx != image->comps[i].dx ||
image->comps[0].dy != image->comps[i].dy ||
(i <= 2 &&
(image->comps[0].prec != image->comps[i].prec ||
image->comps[0].sgnd != image->comps[i].sgnd))) {
return OPJ_FALSE;
}
}
return OPJ_TRUE;
}
int imagetopnm(opj_image_t * image, const char *outfile, int force_split)
{
int *red, *green, *blue, *alpha;
int wr, hr, max;
int i;
unsigned int compno, ncomp;
int adjustR, adjustG, adjustB, adjustA;
int fails, two, want_gray, has_alpha, triple;
int prec, v;
FILE *fdest = NULL;
const char *tmp = outfile;
char *destname;
alpha = NULL;
if ((prec = (int)image->comps[0].prec) > 16) {
fprintf(stderr, "%s:%d:imagetopnm\n\tprecision %d is larger than 16"
"\n\t: refused.\n", __FILE__, __LINE__, prec);
return 1;
}
two = has_alpha = 0;
fails = 1;
ncomp = image->numcomps;
while (*tmp) {
++tmp;
}
tmp -= 2;
want_gray = (*tmp == 'g' || *tmp == 'G');
ncomp = image->numcomps;
if (want_gray) {
ncomp = 1;
}
if ((force_split == 0) && ncomp >= 2 &&
are_comps_similar(image)) {
fdest = fopen(outfile, "wb");
if (!fdest) {
fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
return fails;
}
two = (prec > 8);
triple = (ncomp > 2);
wr = (int)image->comps[0].w;
hr = (int)image->comps[0].h;
max = (1 << prec) - 1;
has_alpha = (ncomp == 4 || ncomp == 2);
red = image->comps[0].data;
if (triple) {
green = image->comps[1].data;
blue = image->comps[2].data;
} else {
green = blue = NULL;
}
if (has_alpha) {
const char *tt = (triple ? "RGB_ALPHA" : "GRAYSCALE_ALPHA");
fprintf(fdest, "P7\n# OpenJPEG-%s\nWIDTH %d\nHEIGHT %d\nDEPTH %u\n"
"MAXVAL %d\nTUPLTYPE %s\nENDHDR\n", opj_version(),
wr, hr, ncomp, max, tt);
alpha = image->comps[ncomp - 1].data;
adjustA = (image->comps[ncomp - 1].sgnd ?
1 << (image->comps[ncomp - 1].prec - 1) : 0);
} else {
fprintf(fdest, "P6\n# OpenJPEG-%s\n%d %d\n%d\n",
opj_version(), wr, hr, max);
adjustA = 0;
}
adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
if (triple) {
adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
} else {
adjustG = adjustB = 0;
}
for (i = 0; i < wr * hr; ++i) {
if (two) {
v = *red + adjustR;
++red;
if (v > 65535) {
v = 65535;
} else if (v < 0) {
v = 0;
}
/* netpbm: */
fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);
if (triple) {
v = *green + adjustG;
++green;
if (v > 65535) {
v = 65535;
} else if (v < 0) {
v = 0;
}
/* netpbm: */
fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);
v = *blue + adjustB;
++blue;
if (v > 65535) {
v = 65535;
} else if (v < 0) {
v = 0;
}
/* netpbm: */
fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);
}/* if(triple) */
if (has_alpha) {
v = *alpha + adjustA;
++alpha;
if (v > 65535) {
v = 65535;
} else if (v < 0) {
v = 0;
}
/* netpbm: */
fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);
}
continue;
} /* if(two) */
/* prec <= 8: */
v = *red++;
if (v > 255) {
v = 255;
} else if (v < 0) {
v = 0;
}
fprintf(fdest, "%c", (unsigned char)v);
if (triple) {
v = *green++;
if (v > 255) {
v = 255;
} else if (v < 0) {
v = 0;
}
fprintf(fdest, "%c", (unsigned char)v);
v = *blue++;
if (v > 255) {
v = 255;
} else if (v < 0) {
v = 0;
}
fprintf(fdest, "%c", (unsigned char)v);
}
if (has_alpha) {
v = *alpha++;
if (v > 255) {
v = 255;
} else if (v < 0) {
v = 0;
}
fprintf(fdest, "%c", (unsigned char)v);
}
} /* for(i */
fclose(fdest);
return 0;
}
/* YUV or MONO: */
if (image->numcomps > ncomp) {
fprintf(stderr, "WARNING -> [PGM file] Only the first component\n");
fprintf(stderr, " is written to the file\n");
}
destname = (char*)malloc(strlen(outfile) + 8);
if (destname == NULL) {
fprintf(stderr, "imagetopnm: memory out\n");
return 1;
}
for (compno = 0; compno < ncomp; compno++) {
if (ncomp > 1) {
/*sprintf(destname, "%d.%s", compno, outfile);*/
const size_t olen = strlen(outfile);
const size_t dotpos = olen - 4;
strncpy(destname, outfile, dotpos);
sprintf(destname + dotpos, "_%u.pgm", compno);
} else {
sprintf(destname, "%s", outfile);
}
fdest = fopen(destname, "wb");
if (!fdest) {
fprintf(stderr, "ERROR -> failed to open %s for writing\n", destname);
free(destname);
return 1;
}
wr = (int)image->comps[compno].w;
hr = (int)image->comps[compno].h;
prec = (int)image->comps[compno].prec;
max = (1 << prec) - 1;
fprintf(fdest, "P5\n#OpenJPEG-%s\n%d %d\n%d\n",
opj_version(), wr, hr, max);
red = image->comps[compno].data;
adjustR =
(image->comps[compno].sgnd ? 1 << (image->comps[compno].prec - 1) : 0);
if (prec > 8) {
for (i = 0; i < wr * hr; i++) {
v = *red + adjustR;
++red;
if (v > 65535) {
v = 65535;
} else if (v < 0) {
v = 0;
}
/* netpbm: */
fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);
if (has_alpha) {
v = *alpha++;
if (v > 65535) {
v = 65535;
} else if (v < 0) {
v = 0;
}
/* netpbm: */
fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);
}
}/* for(i */
} else { /* prec <= 8 */
for (i = 0; i < wr * hr; ++i) {
v = *red + adjustR;
++red;
if (v > 255) {
v = 255;
} else if (v < 0) {
v = 0;
}
fprintf(fdest, "%c", (unsigned char)v);
}
}
fclose(fdest);
} /* for (compno */
free(destname);
return 0;
}/* imagetopnm() */
/* -->> -->> -->> -->>
RAW IMAGE FORMAT
<<-- <<-- <<-- <<-- */
static opj_image_t* rawtoimage_common(const char *filename,
opj_cparameters_t *parameters, raw_cparameters_t *raw_cp, OPJ_BOOL big_endian)
{
int subsampling_dx = parameters->subsampling_dx;
int subsampling_dy = parameters->subsampling_dy;
FILE *f = NULL;
int i, compno, numcomps, w, h;
OPJ_COLOR_SPACE color_space;
opj_image_cmptparm_t *cmptparm;
opj_image_t * image = NULL;
unsigned short ch;
if ((!(raw_cp->rawWidth & raw_cp->rawHeight & raw_cp->rawComp &
raw_cp->rawBitDepth)) == 0) {
fprintf(stderr, "\nError: invalid raw image parameters\n");
fprintf(stderr, "Please use the Format option -F:\n");
fprintf(stderr,
"-F <width>,<height>,<ncomp>,<bitdepth>,{s,u}@<dx1>x<dy1>:...:<dxn>x<dyn>\n");
fprintf(stderr,
"If subsampling is omitted, 1x1 is assumed for all components\n");
fprintf(stderr,
"Example: -i image.raw -o image.j2k -F 512,512,3,8,u@1x1:2x2:2x2\n");
fprintf(stderr, " for raw 512x512 image with 4:2:0 subsampling\n");
fprintf(stderr, "Aborting.\n");
return NULL;
}
f = fopen(filename, "rb");
if (!f) {
fprintf(stderr, "Failed to open %s for reading !!\n", filename);
fprintf(stderr, "Aborting\n");
return NULL;
}
numcomps = raw_cp->rawComp;
/* FIXME ADE at this point, tcp_mct has not been properly set in calling function */
if (numcomps == 1) {
color_space = OPJ_CLRSPC_GRAY;
} else if ((numcomps >= 3) && (parameters->tcp_mct == 0)) {
color_space = OPJ_CLRSPC_SYCC;
} else if ((numcomps >= 3) && (parameters->tcp_mct != 2)) {
color_space = OPJ_CLRSPC_SRGB;
} else {
color_space = OPJ_CLRSPC_UNKNOWN;
}
w = raw_cp->rawWidth;
h = raw_cp->rawHeight;
cmptparm = (opj_image_cmptparm_t*) calloc((OPJ_UINT32)numcomps,
sizeof(opj_image_cmptparm_t));
if (!cmptparm) {
fprintf(stderr, "Failed to allocate image components parameters !!\n");
fprintf(stderr, "Aborting\n");
fclose(f);
return NULL;
}
/* initialize image components */
for (i = 0; i < numcomps; i++) {
cmptparm[i].prec = (OPJ_UINT32)raw_cp->rawBitDepth;
cmptparm[i].bpp = (OPJ_UINT32)raw_cp->rawBitDepth;
cmptparm[i].sgnd = (OPJ_UINT32)raw_cp->rawSigned;
cmptparm[i].dx = (OPJ_UINT32)(subsampling_dx * raw_cp->rawComps[i].dx);
cmptparm[i].dy = (OPJ_UINT32)(subsampling_dy * raw_cp->rawComps[i].dy);
cmptparm[i].w = (OPJ_UINT32)w;
cmptparm[i].h = (OPJ_UINT32)h;
}
/* create the image */
image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
free(cmptparm);
if (!image) {
fclose(f);
return NULL;
}
/* set image offset and reference grid */
image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
image->x1 = (OPJ_UINT32)parameters->image_offset_x0 + (OPJ_UINT32)(w - 1) *
(OPJ_UINT32)subsampling_dx + 1;
image->y1 = (OPJ_UINT32)parameters->image_offset_y0 + (OPJ_UINT32)(h - 1) *
(OPJ_UINT32)subsampling_dy + 1;
if (raw_cp->rawBitDepth <= 8) {
unsigned char value = 0;
for (compno = 0; compno < numcomps; compno++) {
int nloop = (w * h) / (raw_cp->rawComps[compno].dx *
raw_cp->rawComps[compno].dy);
for (i = 0; i < nloop; i++) {
if (!fread(&value, 1, 1, f)) {
fprintf(stderr, "Error reading raw file. End of file probably reached.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
image->comps[compno].data[i] = raw_cp->rawSigned ? (char)value : value;
}
}
} else if (raw_cp->rawBitDepth <= 16) {
unsigned short value;
for (compno = 0; compno < numcomps; compno++) {
int nloop = (w * h) / (raw_cp->rawComps[compno].dx *
raw_cp->rawComps[compno].dy);
for (i = 0; i < nloop; i++) {
unsigned char temp1;
unsigned char temp2;
if (!fread(&temp1, 1, 1, f)) {
fprintf(stderr, "Error reading raw file. End of file probably reached.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&temp2, 1, 1, f)) {
fprintf(stderr, "Error reading raw file. End of file probably reached.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (big_endian) {
value = (unsigned short)((temp1 << 8) + temp2);
} else {
value = (unsigned short)((temp2 << 8) + temp1);
}
image->comps[compno].data[i] = raw_cp->rawSigned ? (short)value : value;
}
}
} else {
fprintf(stderr,
"OpenJPEG cannot encode raw components with bit depth higher than 16 bits.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (fread(&ch, 1, 1, f)) {
fprintf(stderr, "Warning. End of raw file not reached... processing anyway\n");
}
fclose(f);
return image;
}
opj_image_t* rawltoimage(const char *filename, opj_cparameters_t *parameters,
raw_cparameters_t *raw_cp)
{
return rawtoimage_common(filename, parameters, raw_cp, OPJ_FALSE);
}
opj_image_t* rawtoimage(const char *filename, opj_cparameters_t *parameters,
raw_cparameters_t *raw_cp)
{
return rawtoimage_common(filename, parameters, raw_cp, OPJ_TRUE);
}
static int imagetoraw_common(opj_image_t * image, const char *outfile,
OPJ_BOOL big_endian)
{
FILE *rawFile = NULL;
size_t res;
unsigned int compno, numcomps;
int w, h, fails;
int line, row, curr, mask;
int *ptr;
unsigned char uc;
(void)big_endian;
if ((image->numcomps * image->x1 * image->y1) == 0) {
fprintf(stderr, "\nError: invalid raw image parameters\n");
return 1;
}
numcomps = image->numcomps;
if (numcomps > 4) {
numcomps = 4;
}
for (compno = 1; compno < numcomps; ++compno) {
if (image->comps[0].dx != image->comps[compno].dx) {
break;
}
if (image->comps[0].dy != image->comps[compno].dy) {
break;
}
if (image->comps[0].prec != image->comps[compno].prec) {
break;
}
if (image->comps[0].sgnd != image->comps[compno].sgnd) {
break;
}
}
if (compno != numcomps) {
fprintf(stderr,
"imagetoraw_common: All components shall have the same subsampling, same bit depth, same sign.\n");
fprintf(stderr, "\tAborting\n");
return 1;
}
rawFile = fopen(outfile, "wb");
if (!rawFile) {
fprintf(stderr, "Failed to open %s for writing !!\n", outfile);
return 1;
}
fails = 1;
fprintf(stdout, "Raw image characteristics: %d components\n", image->numcomps);
for (compno = 0; compno < image->numcomps; compno++) {
fprintf(stdout, "Component %u characteristics: %dx%dx%d %s\n", compno,
image->comps[compno].w,
image->comps[compno].h, image->comps[compno].prec,
image->comps[compno].sgnd == 1 ? "signed" : "unsigned");
w = (int)image->comps[compno].w;
h = (int)image->comps[compno].h;
if (image->comps[compno].prec <= 8) {
if (image->comps[compno].sgnd == 1) {
mask = (1 << image->comps[compno].prec) - 1;
ptr = image->comps[compno].data;
for (line = 0; line < h; line++) {
for (row = 0; row < w; row++) {
curr = *ptr;
if (curr > 127) {
curr = 127;
} else if (curr < -128) {
curr = -128;
}
uc = (unsigned char)(curr & mask);
res = fwrite(&uc, 1, 1, rawFile);
if (res < 1) {
fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
goto fin;
}
ptr++;
}
}
} else if (image->comps[compno].sgnd == 0) {
mask = (1 << image->comps[compno].prec) - 1;
ptr = image->comps[compno].data;
for (line = 0; line < h; line++) {
for (row = 0; row < w; row++) {
curr = *ptr;
if (curr > 255) {
curr = 255;
} else if (curr < 0) {
curr = 0;
}
uc = (unsigned char)(curr & mask);
res = fwrite(&uc, 1, 1, rawFile);
if (res < 1) {
fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
goto fin;
}
ptr++;
}
}
}
} else if (image->comps[compno].prec <= 16) {
if (image->comps[compno].sgnd == 1) {
union {
signed short val;
signed char vals[2];
} uc16;
mask = (1 << image->comps[compno].prec) - 1;
ptr = image->comps[compno].data;
for (line = 0; line < h; line++) {
for (row = 0; row < w; row++) {
curr = *ptr;
if (curr > 32767) {
curr = 32767;
} else if (curr < -32768) {
curr = -32768;
}
uc16.val = (signed short)(curr & mask);
res = fwrite(uc16.vals, 1, 2, rawFile);
if (res < 2) {
fprintf(stderr, "failed to write 2 byte for %s\n", outfile);
goto fin;
}
ptr++;
}
}
} else if (image->comps[compno].sgnd == 0) {
union {
unsigned short val;
unsigned char vals[2];
} uc16;
mask = (1 << image->comps[compno].prec) - 1;
ptr = image->comps[compno].data;
for (line = 0; line < h; line++) {
for (row = 0; row < w; row++) {
curr = *ptr;
if (curr > 65535) {
curr = 65535;
} else if (curr < 0) {
curr = 0;
}
uc16.val = (unsigned short)(curr & mask);
res = fwrite(uc16.vals, 1, 2, rawFile);
if (res < 2) {
fprintf(stderr, "failed to write 2 byte for %s\n", outfile);
goto fin;
}
ptr++;
}
}
}
} else if (image->comps[compno].prec <= 32) {
fprintf(stderr, "More than 16 bits per component not handled yet\n");
goto fin;
} else {
fprintf(stderr, "Error: invalid precision: %d\n", image->comps[compno].prec);
goto fin;
}
}
fails = 0;
fin:
fclose(rawFile);
return fails;
}
int imagetoraw(opj_image_t * image, const char *outfile)
{
return imagetoraw_common(image, outfile, OPJ_TRUE);
}
int imagetorawl(opj_image_t * image, const char *outfile)
{
return imagetoraw_common(image, outfile, OPJ_FALSE);
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_2760_0 |
crossvul-cpp_data_good_674_2 | /**
* FreeRDP: A Remote Desktop Protocol Implementation
* NSCodec Encoder
*
* Copyright 2012 Vic Lee
* 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winpr/crt.h>
#include <freerdp/codec/nsc.h>
#include <freerdp/codec/color.h>
#include "nsc_types.h"
#include "nsc_encode.h"
static BOOL nsc_context_initialize_encode(NSC_CONTEXT* context)
{
int i;
UINT32 length;
UINT32 tempWidth;
UINT32 tempHeight;
tempWidth = ROUND_UP_TO(context->width, 8);
tempHeight = ROUND_UP_TO(context->height, 2);
/* The maximum length a decoded plane can reach in all cases */
length = tempWidth * tempHeight + 16;
if (length > context->priv->PlaneBuffersLength)
{
for (i = 0; i < 5; i++)
{
BYTE* tmp = (BYTE*) realloc(context->priv->PlaneBuffers[i], length);
if (!tmp)
goto fail;
context->priv->PlaneBuffers[i] = tmp;
}
context->priv->PlaneBuffersLength = length;
}
if (context->ChromaSubsamplingLevel)
{
context->OrgByteCount[0] = tempWidth * context->height;
context->OrgByteCount[1] = tempWidth * tempHeight / 4;
context->OrgByteCount[2] = tempWidth * tempHeight / 4;
context->OrgByteCount[3] = context->width * context->height;
}
else
{
context->OrgByteCount[0] = context->width * context->height;
context->OrgByteCount[1] = context->width * context->height;
context->OrgByteCount[2] = context->width * context->height;
context->OrgByteCount[3] = context->width * context->height;
}
return TRUE;
fail:
if (length > context->priv->PlaneBuffersLength)
{
for (i = 0; i < 5; i++)
free(context->priv->PlaneBuffers[i]);
}
return FALSE;
}
static BOOL nsc_encode_argb_to_aycocg(NSC_CONTEXT* context, const BYTE* data,
UINT32 scanline)
{
UINT16 x;
UINT16 y;
UINT16 rw;
BYTE ccl;
const BYTE* src;
BYTE* yplane = NULL;
BYTE* coplane = NULL;
BYTE* cgplane = NULL;
BYTE* aplane = NULL;
INT16 r_val;
INT16 g_val;
INT16 b_val;
BYTE a_val;
UINT32 tempWidth;
if (!context || data || (scanline == 0))
return FALSE;
tempWidth = ROUND_UP_TO(context->width, 8);
rw = (context->ChromaSubsamplingLevel ? tempWidth : context->width);
ccl = context->ColorLossLevel;
if (context->priv->PlaneBuffersLength < rw * scanline)
return FALSE;
if (rw < scanline * 2)
return FALSE;
for (y = 0; y < context->height; y++)
{
src = data + (context->height - 1 - y) * scanline;
yplane = context->priv->PlaneBuffers[0] + y * rw;
coplane = context->priv->PlaneBuffers[1] + y * rw;
cgplane = context->priv->PlaneBuffers[2] + y * rw;
aplane = context->priv->PlaneBuffers[3] + y * context->width;
for (x = 0; x < context->width; x++)
{
switch (context->format)
{
case PIXEL_FORMAT_BGRX32:
b_val = *src++;
g_val = *src++;
r_val = *src++;
src++;
a_val = 0xFF;
break;
case PIXEL_FORMAT_BGRA32:
b_val = *src++;
g_val = *src++;
r_val = *src++;
a_val = *src++;
break;
case PIXEL_FORMAT_RGBX32:
r_val = *src++;
g_val = *src++;
b_val = *src++;
src++;
a_val = 0xFF;
break;
case PIXEL_FORMAT_RGBA32:
r_val = *src++;
g_val = *src++;
b_val = *src++;
a_val = *src++;
break;
case PIXEL_FORMAT_BGR24:
b_val = *src++;
g_val = *src++;
r_val = *src++;
a_val = 0xFF;
break;
case PIXEL_FORMAT_RGB24:
r_val = *src++;
g_val = *src++;
b_val = *src++;
a_val = 0xFF;
break;
case PIXEL_FORMAT_BGR16:
b_val = (INT16)(((*(src + 1)) & 0xF8) | ((*(src + 1)) >> 5));
g_val = (INT16)((((*(src + 1)) & 0x07) << 5) | (((*src) & 0xE0) >> 3));
r_val = (INT16)((((*src) & 0x1F) << 3) | (((*src) >> 2) & 0x07));
a_val = 0xFF;
src += 2;
break;
case PIXEL_FORMAT_RGB16:
r_val = (INT16)(((*(src + 1)) & 0xF8) | ((*(src + 1)) >> 5));
g_val = (INT16)((((*(src + 1)) & 0x07) << 5) | (((*src) & 0xE0) >> 3));
b_val = (INT16)((((*src) & 0x1F) << 3) | (((*src) >> 2) & 0x07));
a_val = 0xFF;
src += 2;
break;
case PIXEL_FORMAT_A4:
{
int shift;
BYTE idx;
shift = (7 - (x % 8));
idx = ((*src) >> shift) & 1;
idx |= (((*(src + 1)) >> shift) & 1) << 1;
idx |= (((*(src + 2)) >> shift) & 1) << 2;
idx |= (((*(src + 3)) >> shift) & 1) << 3;
idx *= 3;
r_val = (INT16) context->palette[idx];
g_val = (INT16) context->palette[idx + 1];
b_val = (INT16) context->palette[idx + 2];
if (shift == 0)
src += 4;
}
a_val = 0xFF;
break;
case PIXEL_FORMAT_RGB8:
{
int idx = (*src) * 3;
r_val = (INT16) context->palette[idx];
g_val = (INT16) context->palette[idx + 1];
b_val = (INT16) context->palette[idx + 2];
src++;
}
a_val = 0xFF;
break;
default:
r_val = g_val = b_val = a_val = 0;
break;
}
*yplane++ = (BYTE)((r_val >> 2) + (g_val >> 1) + (b_val >> 2));
/* Perform color loss reduction here */
*coplane++ = (BYTE)((r_val - b_val) >> ccl);
*cgplane++ = (BYTE)((-(r_val >> 1) + g_val - (b_val >> 1)) >> ccl);
*aplane++ = a_val;
}
if (context->ChromaSubsamplingLevel && (x % 2) == 1)
{
*yplane = *(yplane - 1);
*coplane = *(coplane - 1);
*cgplane = *(cgplane - 1);
}
}
if (context->ChromaSubsamplingLevel && (y % 2) == 1)
{
yplane = context->priv->PlaneBuffers[0] + y * rw;
coplane = context->priv->PlaneBuffers[1] + y * rw;
cgplane = context->priv->PlaneBuffers[2] + y * rw;
CopyMemory(yplane, yplane - rw, rw);
CopyMemory(coplane, coplane - rw, rw);
CopyMemory(cgplane, cgplane - rw, rw);
}
return TRUE;
}
static BOOL nsc_encode_subsampling(NSC_CONTEXT* context)
{
UINT16 x;
UINT16 y;
UINT32 tempWidth;
UINT32 tempHeight;
if (!context)
return FALSE;
tempWidth = ROUND_UP_TO(context->width, 8);
tempHeight = ROUND_UP_TO(context->height, 2);
if (tempHeight == 0)
return FALSE;
if (tempWidth > context->priv->PlaneBuffersLength / tempHeight)
return FALSE;
for (y = 0; y < tempHeight >> 1; y++)
{
BYTE* co_dst = context->priv->PlaneBuffers[1] + y * (tempWidth >> 1);
BYTE* cg_dst = context->priv->PlaneBuffers[2] + y * (tempWidth >> 1);
const INT8* co_src0 = (INT8*) context->priv->PlaneBuffers[1] + (y << 1) * tempWidth;
const INT8* co_src1 = co_src0 + tempWidth;
const INT8* cg_src0 = (INT8*) context->priv->PlaneBuffers[2] + (y << 1) * tempWidth;
const INT8* cg_src1 = cg_src0 + tempWidth;
for (x = 0; x < tempWidth >> 1; x++)
{
*co_dst++ = (BYTE)(((INT16) * co_src0 + (INT16) * (co_src0 + 1) +
(INT16) * co_src1 + (INT16) * (co_src1 + 1)) >> 2);
*cg_dst++ = (BYTE)(((INT16) * cg_src0 + (INT16) * (cg_src0 + 1) +
(INT16) * cg_src1 + (INT16) * (cg_src1 + 1)) >> 2);
co_src0 += 2;
co_src1 += 2;
cg_src0 += 2;
cg_src1 += 2;
}
}
return TRUE;
}
BOOL nsc_encode(NSC_CONTEXT* context, const BYTE* bmpdata, UINT32 rowstride)
{
if (!context || !bmpdata || (rowstride == 0))
return FALSE;
if (!nsc_encode_argb_to_aycocg(context, bmpdata, rowstride))
return FALSE;
if (context->ChromaSubsamplingLevel)
{
if (!nsc_encode_subsampling(context))
return FALSE;
}
return TRUE;
}
static UINT32 nsc_rle_encode(const BYTE* in, BYTE* out, UINT32 originalSize)
{
UINT32 left;
UINT32 runlength = 1;
UINT32 planeSize = 0;
left = originalSize;
/**
* We quit the loop if the running compressed size is larger than the original.
* In such cases data will be sent uncompressed.
*/
while (left > 4 && planeSize < originalSize - 4)
{
if (left > 5 && *in == *(in + 1))
{
runlength++;
}
else if (runlength == 1)
{
*out++ = *in;
planeSize++;
}
else if (runlength < 256)
{
*out++ = *in;
*out++ = *in;
*out++ = runlength - 2;
runlength = 1;
planeSize += 3;
}
else
{
*out++ = *in;
*out++ = *in;
*out++ = 0xFF;
*out++ = (runlength & 0x000000FF);
*out++ = (runlength & 0x0000FF00) >> 8;
*out++ = (runlength & 0x00FF0000) >> 16;
*out++ = (runlength & 0xFF000000) >> 24;
runlength = 1;
planeSize += 7;
}
in++;
left--;
}
if (planeSize < originalSize - 4)
CopyMemory(out, in, 4);
planeSize += 4;
return planeSize;
}
static void nsc_rle_compress_data(NSC_CONTEXT* context)
{
UINT16 i;
UINT32 planeSize;
UINT32 originalSize;
for (i = 0; i < 4; i++)
{
originalSize = context->OrgByteCount[i];
if (originalSize == 0)
{
planeSize = 0;
}
else
{
planeSize = nsc_rle_encode(context->priv->PlaneBuffers[i],
context->priv->PlaneBuffers[4], originalSize);
if (planeSize < originalSize)
CopyMemory(context->priv->PlaneBuffers[i], context->priv->PlaneBuffers[4],
planeSize);
else
planeSize = originalSize;
}
context->PlaneByteCount[i] = planeSize;
}
}
UINT32 nsc_compute_byte_count(NSC_CONTEXT* context, UINT32* ByteCount,
UINT32 width, UINT32 height)
{
UINT32 tempWidth;
UINT32 tempHeight;
UINT32 maxPlaneSize;
tempWidth = ROUND_UP_TO(width, 8);
tempHeight = ROUND_UP_TO(height, 2);
maxPlaneSize = tempWidth * tempHeight + 16;
if (context->ChromaSubsamplingLevel)
{
ByteCount[0] = tempWidth * height;
ByteCount[1] = tempWidth * tempHeight / 4;
ByteCount[2] = tempWidth * tempHeight / 4;
ByteCount[3] = width * height;
}
else
{
ByteCount[0] = width * height;
ByteCount[1] = width * height;
ByteCount[2] = width * height;
ByteCount[3] = width * height;
}
return maxPlaneSize;
}
NSC_MESSAGE* nsc_encode_messages(NSC_CONTEXT* context, const BYTE* data,
UINT32 x, UINT32 y, UINT32 width, UINT32 height,
UINT32 scanline, UINT32* numMessages,
UINT32 maxDataSize)
{
UINT32 i, j, k;
UINT32 dataOffset;
UINT32 rows, cols;
UINT32 BytesPerPixel;
UINT32 MaxRegionWidth;
UINT32 MaxRegionHeight;
UINT32 ByteCount[4];
UINT32 MaxPlaneSize;
UINT32 MaxMessageSize;
NSC_MESSAGE* messages;
UINT32 PaddedMaxPlaneSize;
k = 0;
MaxRegionWidth = 64 * 4;
MaxRegionHeight = 64 * 2;
BytesPerPixel = GetBytesPerPixel(context->format);
rows = (width + (MaxRegionWidth - (width % MaxRegionWidth))) / MaxRegionWidth;
cols = (height + (MaxRegionHeight - (height % MaxRegionHeight))) /
MaxRegionHeight;
*numMessages = rows * cols;
MaxPlaneSize = nsc_compute_byte_count(context, (UINT32*) ByteCount, width,
height);
MaxMessageSize = ByteCount[0] + ByteCount[1] + ByteCount[2] + ByteCount[3] + 20;
maxDataSize -= 1024; /* reserve enough space for headers */
messages = (NSC_MESSAGE*) calloc(*numMessages, sizeof(NSC_MESSAGE));
if (!messages)
return NULL;
for (i = 0; i < rows; i++)
{
for (j = 0; j < cols; j++)
{
messages[k].x = x + (i * MaxRegionWidth);
messages[k].y = y + (j * MaxRegionHeight);
messages[k].width = (i < (rows - 1)) ? MaxRegionWidth : width -
(i * MaxRegionWidth);
messages[k].height = (j < (cols - 1)) ? MaxRegionHeight : height -
(j * MaxRegionHeight);
messages[k].data = data;
messages[k].scanline = scanline;
messages[k].MaxPlaneSize = nsc_compute_byte_count(context,
(UINT32*) messages[k].OrgByteCount, messages[k].width, messages[k].height);
k++;
}
}
*numMessages = k;
for (i = 0; i < *numMessages; i++)
{
PaddedMaxPlaneSize = messages[i].MaxPlaneSize + 32;
messages[i].PlaneBuffer = (BYTE*) BufferPool_Take(context->priv->PlanePool,
PaddedMaxPlaneSize * 5);
if (!messages[i].PlaneBuffer)
goto fail;
messages[i].PlaneBuffers[0] = (BYTE*) &
(messages[i].PlaneBuffer[(PaddedMaxPlaneSize * 0) + 16]);
messages[i].PlaneBuffers[1] = (BYTE*) &
(messages[i].PlaneBuffer[(PaddedMaxPlaneSize * 1) + 16]);
messages[i].PlaneBuffers[2] = (BYTE*) &
(messages[i].PlaneBuffer[(PaddedMaxPlaneSize * 2) + 16]);
messages[i].PlaneBuffers[3] = (BYTE*) &
(messages[i].PlaneBuffer[(PaddedMaxPlaneSize * 3) + 16]);
messages[i].PlaneBuffers[4] = (BYTE*) &
(messages[i].PlaneBuffer[(PaddedMaxPlaneSize * 4) + 16]);
}
for (i = 0; i < *numMessages; i++)
{
context->width = messages[i].width;
context->height = messages[i].height;
context->OrgByteCount[0] = messages[i].OrgByteCount[0];
context->OrgByteCount[1] = messages[i].OrgByteCount[1];
context->OrgByteCount[2] = messages[i].OrgByteCount[2];
context->OrgByteCount[3] = messages[i].OrgByteCount[3];
context->priv->PlaneBuffersLength = messages[i].MaxPlaneSize;
context->priv->PlaneBuffers[0] = messages[i].PlaneBuffers[0];
context->priv->PlaneBuffers[1] = messages[i].PlaneBuffers[1];
context->priv->PlaneBuffers[2] = messages[i].PlaneBuffers[2];
context->priv->PlaneBuffers[3] = messages[i].PlaneBuffers[3];
context->priv->PlaneBuffers[4] = messages[i].PlaneBuffers[4];
dataOffset = (messages[i].y * messages[i].scanline) + (messages[i].x *
BytesPerPixel);
PROFILER_ENTER(context->priv->prof_nsc_encode)
context->encode(context, &data[dataOffset], scanline);
PROFILER_EXIT(context->priv->prof_nsc_encode)
PROFILER_ENTER(context->priv->prof_nsc_rle_compress_data)
nsc_rle_compress_data(context);
PROFILER_EXIT(context->priv->prof_nsc_rle_compress_data)
messages[i].LumaPlaneByteCount = context->PlaneByteCount[0];
messages[i].OrangeChromaPlaneByteCount = context->PlaneByteCount[1];
messages[i].GreenChromaPlaneByteCount = context->PlaneByteCount[2];
messages[i].AlphaPlaneByteCount = context->PlaneByteCount[3];
messages[i].ColorLossLevel = context->ColorLossLevel;
messages[i].ChromaSubsamplingLevel = context->ChromaSubsamplingLevel;
}
context->priv->PlaneBuffers[0] = NULL;
context->priv->PlaneBuffers[1] = NULL;
context->priv->PlaneBuffers[2] = NULL;
context->priv->PlaneBuffers[3] = NULL;
context->priv->PlaneBuffers[4] = NULL;
return messages;
fail:
for (i = 0; i < *numMessages; i++)
BufferPool_Return(context->priv->PlanePool, messages[i].PlaneBuffer);
free(messages);
return NULL;
}
BOOL nsc_write_message(NSC_CONTEXT* context, wStream* s, NSC_MESSAGE* message)
{
UINT32 totalPlaneByteCount;
totalPlaneByteCount = message->LumaPlaneByteCount +
message->OrangeChromaPlaneByteCount +
message->GreenChromaPlaneByteCount + message->AlphaPlaneByteCount;
if (!Stream_EnsureRemainingCapacity(s, 20 + totalPlaneByteCount))
return -1;
Stream_Write_UINT32(s,
message->LumaPlaneByteCount); /* LumaPlaneByteCount (4 bytes) */
Stream_Write_UINT32(s,
message->OrangeChromaPlaneByteCount); /* OrangeChromaPlaneByteCount (4 bytes) */
Stream_Write_UINT32(s,
message->GreenChromaPlaneByteCount); /* GreenChromaPlaneByteCount (4 bytes) */
Stream_Write_UINT32(s,
message->AlphaPlaneByteCount); /* AlphaPlaneByteCount (4 bytes) */
Stream_Write_UINT8(s, message->ColorLossLevel); /* ColorLossLevel (1 byte) */
Stream_Write_UINT8(s,
message->ChromaSubsamplingLevel); /* ChromaSubsamplingLevel (1 byte) */
Stream_Write_UINT16(s, 0); /* Reserved (2 bytes) */
if (message->LumaPlaneByteCount)
Stream_Write(s, message->PlaneBuffers[0],
message->LumaPlaneByteCount); /* LumaPlane */
if (message->OrangeChromaPlaneByteCount)
Stream_Write(s, message->PlaneBuffers[1],
message->OrangeChromaPlaneByteCount); /* OrangeChromaPlane */
if (message->GreenChromaPlaneByteCount)
Stream_Write(s, message->PlaneBuffers[2],
message->GreenChromaPlaneByteCount); /* GreenChromaPlane */
if (message->AlphaPlaneByteCount)
Stream_Write(s, message->PlaneBuffers[3],
message->AlphaPlaneByteCount); /* AlphaPlane */
return TRUE;
}
void nsc_message_free(NSC_CONTEXT* context, NSC_MESSAGE* message)
{
BufferPool_Return(context->priv->PlanePool, message->PlaneBuffer);
}
BOOL nsc_compose_message(NSC_CONTEXT* context, wStream* s, const BYTE* data,
UINT32 width, UINT32 height, UINT32 scanline)
{
NSC_MESSAGE s_message = { 0 };
NSC_MESSAGE* message = &s_message;
context->width = width;
context->height = height;
if (!nsc_context_initialize_encode(context))
return FALSE;
/* ARGB to AYCoCg conversion, chroma subsampling and colorloss reduction */
PROFILER_ENTER(context->priv->prof_nsc_encode)
context->encode(context, data, scanline);
PROFILER_EXIT(context->priv->prof_nsc_encode)
/* RLE encode */
PROFILER_ENTER(context->priv->prof_nsc_rle_compress_data)
nsc_rle_compress_data(context);
PROFILER_EXIT(context->priv->prof_nsc_rle_compress_data)
message->PlaneBuffers[0] = context->priv->PlaneBuffers[0];
message->PlaneBuffers[1] = context->priv->PlaneBuffers[1];
message->PlaneBuffers[2] = context->priv->PlaneBuffers[2];
message->PlaneBuffers[3] = context->priv->PlaneBuffers[3];
message->LumaPlaneByteCount = context->PlaneByteCount[0];
message->OrangeChromaPlaneByteCount = context->PlaneByteCount[1];
message->GreenChromaPlaneByteCount = context->PlaneByteCount[2];
message->AlphaPlaneByteCount = context->PlaneByteCount[3];
message->ColorLossLevel = context->ColorLossLevel;
message->ChromaSubsamplingLevel = context->ChromaSubsamplingLevel;
return nsc_write_message(context, s, message);
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_674_2 |
crossvul-cpp_data_good_518_0 | /*
* Copyright (C) 2000-2002 Constantin Kaplinsky. All Rights Reserved.
* Copyright (C) 2000 Tridia Corporation. All Rights Reserved.
* Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved.
*
* This 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 software 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 software; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
* USA.
*/
/*
* rfbproto.c - functions to deal with client side of RFB protocol.
*/
#ifdef __STRICT_ANSI__
#define _BSD_SOURCE
#define _POSIX_SOURCE
#define _XOPEN_SOURCE 600
#endif
#ifndef WIN32
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <pwd.h>
#endif
#include <errno.h>
#include <rfb/rfbclient.h>
#ifdef WIN32
#undef SOCKET
#undef socklen_t
#endif
#ifdef LIBVNCSERVER_HAVE_LIBZ
#include <zlib.h>
#ifdef __CHECKER__
#undef Z_NULL
#define Z_NULL NULL
#endif
#endif
#ifndef _MSC_VER
/* Strings.h is not available in MSVC */
#include <strings.h>
#endif
#include <stdarg.h>
#include <time.h>
#ifdef LIBVNCSERVER_WITH_CLIENT_GCRYPT
#include <gcrypt.h>
#endif
#include "sasl.h"
#ifdef LIBVNCSERVER_HAVE_LZO
#include <lzo/lzo1x.h>
#else
#include "minilzo.h"
#endif
#include "tls.h"
#ifdef _MSC_VER
# define snprintf _snprintf /* MSVC went straight to the underscored syntax */
#endif
/*
* rfbClientLog prints a time-stamped message to the log file (stderr).
*/
rfbBool rfbEnableClientLogging=TRUE;
static void
rfbDefaultClientLog(const char *format, ...)
{
va_list args;
char buf[256];
time_t log_clock;
if(!rfbEnableClientLogging)
return;
va_start(args, format);
time(&log_clock);
strftime(buf, 255, "%d/%m/%Y %X ", localtime(&log_clock));
fprintf(stderr, "%s", buf);
vfprintf(stderr, format, args);
fflush(stderr);
va_end(args);
}
rfbClientLogProc rfbClientLog=rfbDefaultClientLog;
rfbClientLogProc rfbClientErr=rfbDefaultClientLog;
/* extensions */
rfbClientProtocolExtension* rfbClientExtensions = NULL;
void rfbClientRegisterExtension(rfbClientProtocolExtension* e)
{
e->next = rfbClientExtensions;
rfbClientExtensions = e;
}
/* client data */
void rfbClientSetClientData(rfbClient* client, void* tag, void* data)
{
rfbClientData* clientData = client->clientData;
while(clientData && clientData->tag != tag)
clientData = clientData->next;
if(clientData == NULL) {
clientData = calloc(sizeof(rfbClientData), 1);
clientData->next = client->clientData;
client->clientData = clientData;
clientData->tag = tag;
}
clientData->data = data;
}
void* rfbClientGetClientData(rfbClient* client, void* tag)
{
rfbClientData* clientData = client->clientData;
while(clientData) {
if(clientData->tag == tag)
return clientData->data;
clientData = clientData->next;
}
return NULL;
}
static rfbBool HandleRRE8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleRRE16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleRRE32(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleCoRRE8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleCoRRE16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleCoRRE32(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleHextile8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleHextile16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleHextile32(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleUltra8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleUltra16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleUltra32(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleUltraZip8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleUltraZip16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleUltraZip32(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTRLE8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTRLE15(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTRLE16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTRLE24(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTRLE24Up(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTRLE24Down(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTRLE32(rfbClient* client, int rx, int ry, int rw, int rh);
#ifdef LIBVNCSERVER_HAVE_LIBZ
static rfbBool HandleZlib8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZlib16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZlib32(rfbClient* client, int rx, int ry, int rw, int rh);
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
static rfbBool HandleTight8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTight16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTight32(rfbClient* client, int rx, int ry, int rw, int rh);
static long ReadCompactLen (rfbClient* client);
#endif
static rfbBool HandleZRLE8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZRLE15(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZRLE16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZRLE24(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZRLE24Up(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZRLE24Down(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZRLE32(rfbClient* client, int rx, int ry, int rw, int rh);
#endif
/*
* Server Capability Functions
*/
rfbBool
SupportsClient2Server(rfbClient* client, int messageType)
{
return (client->supportedMessages.client2server[((messageType & 0xFF)/8)] & (1<<(messageType % 8)) ? TRUE : FALSE);
}
rfbBool
SupportsServer2Client(rfbClient* client, int messageType)
{
return (client->supportedMessages.server2client[((messageType & 0xFF)/8)] & (1<<(messageType % 8)) ? TRUE : FALSE);
}
void
SetClient2Server(rfbClient* client, int messageType)
{
client->supportedMessages.client2server[((messageType & 0xFF)/8)] |= (1<<(messageType % 8));
}
void
SetServer2Client(rfbClient* client, int messageType)
{
client->supportedMessages.server2client[((messageType & 0xFF)/8)] |= (1<<(messageType % 8));
}
void
ClearClient2Server(rfbClient* client, int messageType)
{
client->supportedMessages.client2server[((messageType & 0xFF)/8)] &= (!(1<<(messageType % 8)));
}
void
ClearServer2Client(rfbClient* client, int messageType)
{
client->supportedMessages.server2client[((messageType & 0xFF)/8)] &= (!(1<<(messageType % 8)));
}
void
DefaultSupportedMessages(rfbClient* client)
{
memset((char *)&client->supportedMessages,0,sizeof(client->supportedMessages));
/* Default client supported messages (universal RFB 3.3 protocol) */
SetClient2Server(client, rfbSetPixelFormat);
/* SetClient2Server(client, rfbFixColourMapEntries); Not currently supported */
SetClient2Server(client, rfbSetEncodings);
SetClient2Server(client, rfbFramebufferUpdateRequest);
SetClient2Server(client, rfbKeyEvent);
SetClient2Server(client, rfbPointerEvent);
SetClient2Server(client, rfbClientCutText);
/* technically, we only care what we can *send* to the server
* but, we set Server2Client Just in case it ever becomes useful
*/
SetServer2Client(client, rfbFramebufferUpdate);
SetServer2Client(client, rfbSetColourMapEntries);
SetServer2Client(client, rfbBell);
SetServer2Client(client, rfbServerCutText);
}
void
DefaultSupportedMessagesUltraVNC(rfbClient* client)
{
DefaultSupportedMessages(client);
SetClient2Server(client, rfbFileTransfer);
SetClient2Server(client, rfbSetScale);
SetClient2Server(client, rfbSetServerInput);
SetClient2Server(client, rfbSetSW);
SetClient2Server(client, rfbTextChat);
SetClient2Server(client, rfbPalmVNCSetScaleFactor);
/* technically, we only care what we can *send* to the server */
SetServer2Client(client, rfbResizeFrameBuffer);
SetServer2Client(client, rfbPalmVNCReSizeFrameBuffer);
SetServer2Client(client, rfbFileTransfer);
SetServer2Client(client, rfbTextChat);
}
void
DefaultSupportedMessagesTightVNC(rfbClient* client)
{
DefaultSupportedMessages(client);
SetClient2Server(client, rfbFileTransfer);
SetClient2Server(client, rfbSetServerInput);
SetClient2Server(client, rfbSetSW);
/* SetClient2Server(client, rfbTextChat); */
/* technically, we only care what we can *send* to the server */
SetServer2Client(client, rfbFileTransfer);
SetServer2Client(client, rfbTextChat);
}
#ifndef WIN32
static rfbBool
IsUnixSocket(const char *name)
{
struct stat sb;
if(stat(name, &sb) == 0 && (sb.st_mode & S_IFMT) == S_IFSOCK)
return TRUE;
return FALSE;
}
#endif
/*
* ConnectToRFBServer.
*/
rfbBool
ConnectToRFBServer(rfbClient* client,const char *hostname, int port)
{
if (client->serverPort==-1) {
/* serverHost is a file recorded by vncrec. */
const char* magic="vncLog0.0";
char buffer[10];
rfbVNCRec* rec = (rfbVNCRec*)malloc(sizeof(rfbVNCRec));
client->vncRec = rec;
rec->file = fopen(client->serverHost,"rb");
rec->tv.tv_sec = 0;
rec->readTimestamp = FALSE;
rec->doNotSleep = FALSE;
if (!rec->file) {
rfbClientLog("Could not open %s.\n",client->serverHost);
return FALSE;
}
setbuf(rec->file,NULL);
if (fread(buffer,1,strlen(magic),rec->file) != strlen(magic) || strncmp(buffer,magic,strlen(magic))) {
rfbClientLog("File %s was not recorded by vncrec.\n",client->serverHost);
fclose(rec->file);
return FALSE;
}
client->sock = -1;
return TRUE;
}
#ifndef WIN32
if(IsUnixSocket(hostname))
/* serverHost is a UNIX socket. */
client->sock = ConnectClientToUnixSock(hostname);
else
#endif
{
#ifdef LIBVNCSERVER_IPv6
client->sock = ConnectClientToTcpAddr6(hostname, port);
if (client->sock == -1)
#endif
{
unsigned int host;
/* serverHost is a hostname */
if (!StringToIPAddr(hostname, &host)) {
rfbClientLog("Couldn't convert '%s' to host address\n", hostname);
return FALSE;
}
client->sock = ConnectClientToTcpAddr(host, port);
}
}
if (client->sock < 0) {
rfbClientLog("Unable to connect to VNC server\n");
return FALSE;
}
if(client->QoS_DSCP && !SetDSCP(client->sock, client->QoS_DSCP))
return FALSE;
return SetNonBlocking(client->sock);
}
/*
* ConnectToRFBRepeater.
*/
rfbBool ConnectToRFBRepeater(rfbClient* client,const char *repeaterHost, int repeaterPort, const char *destHost, int destPort)
{
rfbProtocolVersionMsg pv;
int major,minor;
char tmphost[250];
int tmphostlen;
#ifdef LIBVNCSERVER_IPv6
client->sock = ConnectClientToTcpAddr6(repeaterHost, repeaterPort);
if (client->sock == -1)
#endif
{
unsigned int host;
if (!StringToIPAddr(repeaterHost, &host)) {
rfbClientLog("Couldn't convert '%s' to host address\n", repeaterHost);
return FALSE;
}
client->sock = ConnectClientToTcpAddr(host, repeaterPort);
}
if (client->sock < 0) {
rfbClientLog("Unable to connect to VNC repeater\n");
return FALSE;
}
if (!SetNonBlocking(client->sock))
return FALSE;
if (!ReadFromRFBServer(client, pv, sz_rfbProtocolVersionMsg))
return FALSE;
pv[sz_rfbProtocolVersionMsg] = 0;
/* UltraVNC repeater always report version 000.000 to identify itself */
if (sscanf(pv,rfbProtocolVersionFormat,&major,&minor) != 2 || major != 0 || minor != 0) {
rfbClientLog("Not a valid VNC repeater (%s)\n",pv);
return FALSE;
}
rfbClientLog("Connected to VNC repeater, using protocol version %d.%d\n", major, minor);
tmphostlen = snprintf(tmphost, sizeof(tmphost), "%s:%d", destHost, destPort);
if(tmphostlen < 0 || tmphostlen >= (int)sizeof(tmphost))
return FALSE; /* snprintf error or output truncated */
if (!WriteToRFBServer(client, tmphost, tmphostlen + 1))
return FALSE;
return TRUE;
}
extern void rfbClientEncryptBytes(unsigned char* bytes, char* passwd);
extern void rfbClientEncryptBytes2(unsigned char *where, const int length, unsigned char *key);
static void
ReadReason(rfbClient* client)
{
uint32_t reasonLen;
char *reason;
if (!ReadFromRFBServer(client, (char *)&reasonLen, 4)) return;
reasonLen = rfbClientSwap32IfLE(reasonLen);
if(reasonLen > 1<<20) {
rfbClientLog("VNC connection failed, but sent reason length of %u exceeds limit of 1MB",(unsigned int)reasonLen);
return;
}
reason = malloc(reasonLen+1);
if (!ReadFromRFBServer(client, reason, reasonLen)) { free(reason); return; }
reason[reasonLen]=0;
rfbClientLog("VNC connection failed: %s\n",reason);
free(reason);
}
rfbBool
rfbHandleAuthResult(rfbClient* client)
{
uint32_t authResult=0;
if (!ReadFromRFBServer(client, (char *)&authResult, 4)) return FALSE;
authResult = rfbClientSwap32IfLE(authResult);
switch (authResult) {
case rfbVncAuthOK:
rfbClientLog("VNC authentication succeeded\n");
return TRUE;
break;
case rfbVncAuthFailed:
if (client->major==3 && client->minor>7)
{
/* we have an error following */
ReadReason(client);
return FALSE;
}
rfbClientLog("VNC authentication failed\n");
return FALSE;
case rfbVncAuthTooMany:
rfbClientLog("VNC authentication failed - too many tries\n");
return FALSE;
}
rfbClientLog("Unknown VNC authentication result: %d\n",
(int)authResult);
return FALSE;
}
static rfbBool
ReadSupportedSecurityType(rfbClient* client, uint32_t *result, rfbBool subAuth)
{
uint8_t count=0;
uint8_t loop=0;
uint8_t flag=0;
rfbBool extAuthHandler;
uint8_t tAuth[256];
char buf1[500],buf2[10];
uint32_t authScheme;
rfbClientProtocolExtension* e;
if (!ReadFromRFBServer(client, (char *)&count, 1)) return FALSE;
if (count==0)
{
rfbClientLog("List of security types is ZERO, expecting an error to follow\n");
ReadReason(client);
return FALSE;
}
rfbClientLog("We have %d security types to read\n", count);
authScheme=0;
/* now, we have a list of available security types to read ( uint8_t[] ) */
for (loop=0;loop<count;loop++)
{
if (!ReadFromRFBServer(client, (char *)&tAuth[loop], 1)) return FALSE;
rfbClientLog("%d) Received security type %d\n", loop, tAuth[loop]);
if (flag) continue;
extAuthHandler=FALSE;
for (e = rfbClientExtensions; e; e = e->next) {
if (!e->handleAuthentication) continue;
uint32_t const* secType;
for (secType = e->securityTypes; secType && *secType; secType++) {
if (tAuth[loop]==*secType) {
extAuthHandler=TRUE;
}
}
}
if (tAuth[loop]==rfbVncAuth || tAuth[loop]==rfbNoAuth ||
extAuthHandler ||
#if defined(LIBVNCSERVER_HAVE_GNUTLS) || defined(LIBVNCSERVER_HAVE_LIBSSL)
tAuth[loop]==rfbVeNCrypt ||
#endif
#ifdef LIBVNCSERVER_HAVE_SASL
tAuth[loop]==rfbSASL ||
#endif /* LIBVNCSERVER_HAVE_SASL */
(tAuth[loop]==rfbARD && client->GetCredential) ||
(!subAuth && (tAuth[loop]==rfbTLS || (tAuth[loop]==rfbVeNCrypt && client->GetCredential))))
{
if (!subAuth && client->clientAuthSchemes)
{
int i;
for (i=0;client->clientAuthSchemes[i];i++)
{
if (client->clientAuthSchemes[i]==(uint32_t)tAuth[loop])
{
flag++;
authScheme=tAuth[loop];
break;
}
}
}
else
{
flag++;
authScheme=tAuth[loop];
}
if (flag)
{
rfbClientLog("Selecting security type %d (%d/%d in the list)\n", authScheme, loop, count);
/* send back a single byte indicating which security type to use */
if (!WriteToRFBServer(client, (char *)&tAuth[loop], 1)) return FALSE;
}
}
}
if (authScheme==0)
{
memset(buf1, 0, sizeof(buf1));
for (loop=0;loop<count;loop++)
{
if (strlen(buf1)>=sizeof(buf1)-1) break;
snprintf(buf2, sizeof(buf2), (loop>0 ? ", %d" : "%d"), (int)tAuth[loop]);
strncat(buf1, buf2, sizeof(buf1)-strlen(buf1)-1);
}
rfbClientLog("Unknown authentication scheme from VNC server: %s\n",
buf1);
return FALSE;
}
*result = authScheme;
return TRUE;
}
static rfbBool
HandleVncAuth(rfbClient *client)
{
uint8_t challenge[CHALLENGESIZE];
char *passwd=NULL;
int i;
if (!ReadFromRFBServer(client, (char *)challenge, CHALLENGESIZE)) return FALSE;
if (client->serverPort!=-1) { /* if not playing a vncrec file */
if (client->GetPassword)
passwd = client->GetPassword(client);
if ((!passwd) || (strlen(passwd) == 0)) {
rfbClientLog("Reading password failed\n");
return FALSE;
}
if (strlen(passwd) > 8) {
passwd[8] = '\0';
}
rfbClientEncryptBytes(challenge, passwd);
/* Lose the password from memory */
for (i = strlen(passwd); i >= 0; i--) {
passwd[i] = '\0';
}
free(passwd);
if (!WriteToRFBServer(client, (char *)challenge, CHALLENGESIZE)) return FALSE;
}
/* Handle the SecurityResult message */
if (!rfbHandleAuthResult(client)) return FALSE;
return TRUE;
}
static void
FreeUserCredential(rfbCredential *cred)
{
if (cred->userCredential.username) free(cred->userCredential.username);
if (cred->userCredential.password) free(cred->userCredential.password);
free(cred);
}
static rfbBool
HandlePlainAuth(rfbClient *client)
{
uint32_t ulen, ulensw;
uint32_t plen, plensw;
rfbCredential *cred;
if (!client->GetCredential)
{
rfbClientLog("GetCredential callback is not set.\n");
return FALSE;
}
cred = client->GetCredential(client, rfbCredentialTypeUser);
if (!cred)
{
rfbClientLog("Reading credential failed\n");
return FALSE;
}
ulen = (cred->userCredential.username ? strlen(cred->userCredential.username) : 0);
ulensw = rfbClientSwap32IfLE(ulen);
plen = (cred->userCredential.password ? strlen(cred->userCredential.password) : 0);
plensw = rfbClientSwap32IfLE(plen);
if (!WriteToRFBServer(client, (char *)&ulensw, 4) ||
!WriteToRFBServer(client, (char *)&plensw, 4))
{
FreeUserCredential(cred);
return FALSE;
}
if (ulen > 0)
{
if (!WriteToRFBServer(client, cred->userCredential.username, ulen))
{
FreeUserCredential(cred);
return FALSE;
}
}
if (plen > 0)
{
if (!WriteToRFBServer(client, cred->userCredential.password, plen))
{
FreeUserCredential(cred);
return FALSE;
}
}
FreeUserCredential(cred);
/* Handle the SecurityResult message */
if (!rfbHandleAuthResult(client)) return FALSE;
return TRUE;
}
/* Simple 64bit big integer arithmetic implementation */
/* (x + y) % m, works even if (x + y) > 64bit */
#define rfbAddM64(x,y,m) ((x+y)%m+(x+y<x?(((uint64_t)-1)%m+1)%m:0))
/* (x * y) % m */
static uint64_t
rfbMulM64(uint64_t x, uint64_t y, uint64_t m)
{
uint64_t r;
for(r=0;x>0;x>>=1)
{
if (x&1) r=rfbAddM64(r,y,m);
y=rfbAddM64(y,y,m);
}
return r;
}
/* (x ^ y) % m */
static uint64_t
rfbPowM64(uint64_t b, uint64_t e, uint64_t m)
{
uint64_t r;
for(r=1;e>0;e>>=1)
{
if(e&1) r=rfbMulM64(r,b,m);
b=rfbMulM64(b,b,m);
}
return r;
}
static rfbBool
HandleMSLogonAuth(rfbClient *client)
{
uint64_t gen, mod, resp, priv, pub, key;
uint8_t username[256], password[64];
rfbCredential *cred;
if (!ReadFromRFBServer(client, (char *)&gen, 8)) return FALSE;
if (!ReadFromRFBServer(client, (char *)&mod, 8)) return FALSE;
if (!ReadFromRFBServer(client, (char *)&resp, 8)) return FALSE;
gen = rfbClientSwap64IfLE(gen);
mod = rfbClientSwap64IfLE(mod);
resp = rfbClientSwap64IfLE(resp);
if (!client->GetCredential)
{
rfbClientLog("GetCredential callback is not set.\n");
return FALSE;
}
rfbClientLog("WARNING! MSLogon security type has very low password encryption! "\
"Use it only with SSH tunnel or trusted network.\n");
cred = client->GetCredential(client, rfbCredentialTypeUser);
if (!cred)
{
rfbClientLog("Reading credential failed\n");
return FALSE;
}
memset(username, 0, sizeof(username));
strncpy((char *)username, cred->userCredential.username, sizeof(username));
memset(password, 0, sizeof(password));
strncpy((char *)password, cred->userCredential.password, sizeof(password));
FreeUserCredential(cred);
srand(time(NULL));
priv = ((uint64_t)rand())<<32;
priv |= (uint64_t)rand();
pub = rfbPowM64(gen, priv, mod);
key = rfbPowM64(resp, priv, mod);
pub = rfbClientSwap64IfLE(pub);
key = rfbClientSwap64IfLE(key);
rfbClientEncryptBytes2(username, sizeof(username), (unsigned char *)&key);
rfbClientEncryptBytes2(password, sizeof(password), (unsigned char *)&key);
if (!WriteToRFBServer(client, (char *)&pub, 8)) return FALSE;
if (!WriteToRFBServer(client, (char *)username, sizeof(username))) return FALSE;
if (!WriteToRFBServer(client, (char *)password, sizeof(password))) return FALSE;
/* Handle the SecurityResult message */
if (!rfbHandleAuthResult(client)) return FALSE;
return TRUE;
}
#ifdef LIBVNCSERVER_WITH_CLIENT_GCRYPT
static rfbBool
rfbMpiToBytes(const gcry_mpi_t value, uint8_t *result, size_t size)
{
gcry_error_t error;
size_t len;
int i;
error = gcry_mpi_print(GCRYMPI_FMT_USG, result, size, &len, value);
if (gcry_err_code(error) != GPG_ERR_NO_ERROR)
{
rfbClientLog("gcry_mpi_print error: %s\n", gcry_strerror(error));
return FALSE;
}
for (i=size-1;i>(int)size-1-(int)len;--i)
result[i] = result[i-size+len];
for (;i>=0;--i)
result[i] = 0;
return TRUE;
}
static rfbBool
HandleARDAuth(rfbClient *client)
{
uint8_t gen[2], len[2];
size_t keylen;
uint8_t *mod = NULL, *resp, *pub, *key, *shared;
gcry_mpi_t genmpi = NULL, modmpi = NULL, respmpi = NULL;
gcry_mpi_t privmpi = NULL, pubmpi = NULL, keympi = NULL;
gcry_md_hd_t md5 = NULL;
gcry_cipher_hd_t aes = NULL;
gcry_error_t error;
uint8_t userpass[128], ciphertext[128];
int passwordLen, usernameLen;
rfbCredential *cred = NULL;
rfbBool result = FALSE;
if (!gcry_control(GCRYCTL_INITIALIZATION_FINISHED_P))
{
/* Application did not initialize gcrypt, so we should */
if (!gcry_check_version(GCRYPT_VERSION))
{
/* Older version of libgcrypt is installed on system than compiled against */
rfbClientLog("libgcrypt version mismatch.\n");
}
}
while (1)
{
if (!ReadFromRFBServer(client, (char *)gen, 2))
break;
if (!ReadFromRFBServer(client, (char *)len, 2))
break;
if (!client->GetCredential)
{
rfbClientLog("GetCredential callback is not set.\n");
break;
}
cred = client->GetCredential(client, rfbCredentialTypeUser);
if (!cred)
{
rfbClientLog("Reading credential failed\n");
break;
}
keylen = 256*len[0]+len[1];
mod = (uint8_t*)malloc(keylen*4);
if (!mod)
{
rfbClientLog("malloc out of memory\n");
break;
}
resp = mod+keylen;
pub = resp+keylen;
key = pub+keylen;
if (!ReadFromRFBServer(client, (char *)mod, keylen))
break;
if (!ReadFromRFBServer(client, (char *)resp, keylen))
break;
error = gcry_mpi_scan(&genmpi, GCRYMPI_FMT_USG, gen, 2, NULL);
if (gcry_err_code(error) != GPG_ERR_NO_ERROR)
{
rfbClientLog("gcry_mpi_scan error: %s\n", gcry_strerror(error));
break;
}
error = gcry_mpi_scan(&modmpi, GCRYMPI_FMT_USG, mod, keylen, NULL);
if (gcry_err_code(error) != GPG_ERR_NO_ERROR)
{
rfbClientLog("gcry_mpi_scan error: %s\n", gcry_strerror(error));
break;
}
error = gcry_mpi_scan(&respmpi, GCRYMPI_FMT_USG, resp, keylen, NULL);
if (gcry_err_code(error) != GPG_ERR_NO_ERROR)
{
rfbClientLog("gcry_mpi_scan error: %s\n", gcry_strerror(error));
break;
}
privmpi = gcry_mpi_new(keylen);
if (!privmpi)
{
rfbClientLog("gcry_mpi_new out of memory\n");
break;
}
gcry_mpi_randomize(privmpi, (keylen/8)*8, GCRY_STRONG_RANDOM);
pubmpi = gcry_mpi_new(keylen);
if (!pubmpi)
{
rfbClientLog("gcry_mpi_new out of memory\n");
break;
}
gcry_mpi_powm(pubmpi, genmpi, privmpi, modmpi);
keympi = gcry_mpi_new(keylen);
if (!keympi)
{
rfbClientLog("gcry_mpi_new out of memory\n");
break;
}
gcry_mpi_powm(keympi, respmpi, privmpi, modmpi);
if (!rfbMpiToBytes(pubmpi, pub, keylen))
break;
if (!rfbMpiToBytes(keympi, key, keylen))
break;
error = gcry_md_open(&md5, GCRY_MD_MD5, 0);
if (gcry_err_code(error) != GPG_ERR_NO_ERROR)
{
rfbClientLog("gcry_md_open error: %s\n", gcry_strerror(error));
break;
}
gcry_md_write(md5, key, keylen);
error = gcry_md_final(md5);
if (gcry_err_code(error) != GPG_ERR_NO_ERROR)
{
rfbClientLog("gcry_md_final error: %s\n", gcry_strerror(error));
break;
}
shared = gcry_md_read(md5, GCRY_MD_MD5);
passwordLen = strlen(cred->userCredential.password)+1;
usernameLen = strlen(cred->userCredential.username)+1;
if (passwordLen > sizeof(userpass)/2)
passwordLen = sizeof(userpass)/2;
if (usernameLen > sizeof(userpass)/2)
usernameLen = sizeof(userpass)/2;
gcry_randomize(userpass, sizeof(userpass), GCRY_STRONG_RANDOM);
memcpy(userpass, cred->userCredential.username, usernameLen);
memcpy(userpass+sizeof(userpass)/2, cred->userCredential.password, passwordLen);
error = gcry_cipher_open(&aes, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_ECB, 0);
if (gcry_err_code(error) != GPG_ERR_NO_ERROR)
{
rfbClientLog("gcry_cipher_open error: %s\n", gcry_strerror(error));
break;
}
error = gcry_cipher_setkey(aes, shared, 16);
if (gcry_err_code(error) != GPG_ERR_NO_ERROR)
{
rfbClientLog("gcry_cipher_setkey error: %s\n", gcry_strerror(error));
break;
}
error = gcry_cipher_encrypt(aes, ciphertext, sizeof(ciphertext), userpass, sizeof(userpass));
if (gcry_err_code(error) != GPG_ERR_NO_ERROR)
{
rfbClientLog("gcry_cipher_encrypt error: %s\n", gcry_strerror(error));
break;
}
if (!WriteToRFBServer(client, (char *)ciphertext, sizeof(ciphertext)))
break;
if (!WriteToRFBServer(client, (char *)pub, keylen))
break;
/* Handle the SecurityResult message */
if (!rfbHandleAuthResult(client))
break;
result = TRUE;
break;
}
if (cred)
FreeUserCredential(cred);
if (mod)
free(mod);
if (genmpi)
gcry_mpi_release(genmpi);
if (modmpi)
gcry_mpi_release(modmpi);
if (respmpi)
gcry_mpi_release(respmpi);
if (privmpi)
gcry_mpi_release(privmpi);
if (pubmpi)
gcry_mpi_release(pubmpi);
if (keympi)
gcry_mpi_release(keympi);
if (md5)
gcry_md_close(md5);
if (aes)
gcry_cipher_close(aes);
return result;
}
#endif
/*
* SetClientAuthSchemes.
*/
void
SetClientAuthSchemes(rfbClient* client,const uint32_t *authSchemes, int size)
{
int i;
if (client->clientAuthSchemes)
{
free(client->clientAuthSchemes);
client->clientAuthSchemes = NULL;
}
if (authSchemes)
{
if (size<0)
{
/* If size<0 we assume the passed-in list is also 0-terminate, so we
* calculate the size here */
for (size=0;authSchemes[size];size++) ;
}
client->clientAuthSchemes = (uint32_t*)malloc(sizeof(uint32_t)*(size+1));
for (i=0;i<size;i++)
client->clientAuthSchemes[i] = authSchemes[i];
client->clientAuthSchemes[size] = 0;
}
}
/*
* InitialiseRFBConnection.
*/
rfbBool
InitialiseRFBConnection(rfbClient* client)
{
rfbProtocolVersionMsg pv;
int major,minor;
uint32_t authScheme;
uint32_t subAuthScheme;
rfbClientInitMsg ci;
/* if the connection is immediately closed, don't report anything, so
that pmw's monitor can make test connections */
if (client->listenSpecified)
errorMessageOnReadFailure = FALSE;
if (!ReadFromRFBServer(client, pv, sz_rfbProtocolVersionMsg)) return FALSE;
pv[sz_rfbProtocolVersionMsg]=0;
errorMessageOnReadFailure = TRUE;
pv[sz_rfbProtocolVersionMsg] = 0;
if (sscanf(pv,rfbProtocolVersionFormat,&major,&minor) != 2) {
rfbClientLog("Not a valid VNC server (%s)\n",pv);
return FALSE;
}
DefaultSupportedMessages(client);
client->major = major;
client->minor = minor;
/* fall back to viewer supported version */
if ((major==rfbProtocolMajorVersion) && (minor>rfbProtocolMinorVersion))
client->minor = rfbProtocolMinorVersion;
/* UltraVNC uses minor codes 4 and 6 for the server */
if (major==3 && (minor==4 || minor==6)) {
rfbClientLog("UltraVNC server detected, enabling UltraVNC specific messages\n",pv);
DefaultSupportedMessagesUltraVNC(client);
}
/* UltraVNC Single Click uses minor codes 14 and 16 for the server */
if (major==3 && (minor==14 || minor==16)) {
minor = minor - 10;
client->minor = minor;
rfbClientLog("UltraVNC Single Click server detected, enabling UltraVNC specific messages\n",pv);
DefaultSupportedMessagesUltraVNC(client);
}
/* TightVNC uses minor codes 5 for the server */
if (major==3 && minor==5) {
rfbClientLog("TightVNC server detected, enabling TightVNC specific messages\n",pv);
DefaultSupportedMessagesTightVNC(client);
}
/* we do not support > RFB3.8 */
if ((major==3 && minor>8) || major>3)
{
client->major=3;
client->minor=8;
}
rfbClientLog("VNC server supports protocol version %d.%d (viewer %d.%d)\n",
major, minor, rfbProtocolMajorVersion, rfbProtocolMinorVersion);
sprintf(pv,rfbProtocolVersionFormat,client->major,client->minor);
if (!WriteToRFBServer(client, pv, sz_rfbProtocolVersionMsg)) return FALSE;
/* 3.7 and onwards sends a # of security types first */
if (client->major==3 && client->minor > 6)
{
if (!ReadSupportedSecurityType(client, &authScheme, FALSE)) return FALSE;
}
else
{
if (!ReadFromRFBServer(client, (char *)&authScheme, 4)) return FALSE;
authScheme = rfbClientSwap32IfLE(authScheme);
}
rfbClientLog("Selected Security Scheme %d\n", authScheme);
client->authScheme = authScheme;
switch (authScheme) {
case rfbConnFailed:
ReadReason(client);
return FALSE;
case rfbNoAuth:
rfbClientLog("No authentication needed\n");
/* 3.8 and upwards sends a Security Result for rfbNoAuth */
if ((client->major==3 && client->minor > 7) || client->major>3)
if (!rfbHandleAuthResult(client)) return FALSE;
break;
case rfbVncAuth:
if (!HandleVncAuth(client)) return FALSE;
break;
#ifdef LIBVNCSERVER_HAVE_SASL
case rfbSASL:
if (!HandleSASLAuth(client)) return FALSE;
break;
#endif /* LIBVNCSERVER_HAVE_SASL */
case rfbMSLogon:
if (!HandleMSLogonAuth(client)) return FALSE;
break;
case rfbARD:
#ifndef LIBVNCSERVER_WITH_CLIENT_GCRYPT
rfbClientLog("GCrypt support was not compiled in\n");
return FALSE;
#else
if (!HandleARDAuth(client)) return FALSE;
#endif
break;
case rfbTLS:
if (!HandleAnonTLSAuth(client)) return FALSE;
/* After the TLS session is established, sub auth types are expected.
* Note that all following reading/writing are through the TLS session from here.
*/
if (!ReadSupportedSecurityType(client, &subAuthScheme, TRUE)) return FALSE;
client->subAuthScheme = subAuthScheme;
switch (subAuthScheme) {
case rfbConnFailed:
ReadReason(client);
return FALSE;
case rfbNoAuth:
rfbClientLog("No sub authentication needed\n");
/* 3.8 and upwards sends a Security Result for rfbNoAuth */
if ((client->major==3 && client->minor > 7) || client->major>3)
if (!rfbHandleAuthResult(client)) return FALSE;
break;
case rfbVncAuth:
if (!HandleVncAuth(client)) return FALSE;
break;
#ifdef LIBVNCSERVER_HAVE_SASL
case rfbSASL:
if (!HandleSASLAuth(client)) return FALSE;
break;
#endif /* LIBVNCSERVER_HAVE_SASL */
default:
rfbClientLog("Unknown sub authentication scheme from VNC server: %d\n",
(int)subAuthScheme);
return FALSE;
}
break;
case rfbVeNCrypt:
if (!HandleVeNCryptAuth(client)) return FALSE;
switch (client->subAuthScheme) {
case rfbVeNCryptTLSNone:
case rfbVeNCryptX509None:
rfbClientLog("No sub authentication needed\n");
if (!rfbHandleAuthResult(client)) return FALSE;
break;
case rfbVeNCryptTLSVNC:
case rfbVeNCryptX509VNC:
if (!HandleVncAuth(client)) return FALSE;
break;
case rfbVeNCryptTLSPlain:
case rfbVeNCryptX509Plain:
if (!HandlePlainAuth(client)) return FALSE;
break;
#ifdef LIBVNCSERVER_HAVE_SASL
case rfbVeNCryptX509SASL:
case rfbVeNCryptTLSSASL:
if (!HandleSASLAuth(client)) return FALSE;
break;
#endif /* LIBVNCSERVER_HAVE_SASL */
default:
rfbClientLog("Unknown sub authentication scheme from VNC server: %d\n",
client->subAuthScheme);
return FALSE;
}
break;
default:
{
rfbBool authHandled=FALSE;
rfbClientProtocolExtension* e;
for (e = rfbClientExtensions; e; e = e->next) {
uint32_t const* secType;
if (!e->handleAuthentication) continue;
for (secType = e->securityTypes; secType && *secType; secType++) {
if (authScheme==*secType) {
if (!e->handleAuthentication(client, authScheme)) return FALSE;
if (!rfbHandleAuthResult(client)) return FALSE;
authHandled=TRUE;
}
}
}
if (authHandled) break;
}
rfbClientLog("Unknown authentication scheme from VNC server: %d\n",
(int)authScheme);
return FALSE;
}
ci.shared = (client->appData.shareDesktop ? 1 : 0);
if (!WriteToRFBServer(client, (char *)&ci, sz_rfbClientInitMsg)) return FALSE;
if (!ReadFromRFBServer(client, (char *)&client->si, sz_rfbServerInitMsg)) return FALSE;
client->si.framebufferWidth = rfbClientSwap16IfLE(client->si.framebufferWidth);
client->si.framebufferHeight = rfbClientSwap16IfLE(client->si.framebufferHeight);
client->si.format.redMax = rfbClientSwap16IfLE(client->si.format.redMax);
client->si.format.greenMax = rfbClientSwap16IfLE(client->si.format.greenMax);
client->si.format.blueMax = rfbClientSwap16IfLE(client->si.format.blueMax);
client->si.nameLength = rfbClientSwap32IfLE(client->si.nameLength);
if (client->si.nameLength > 1<<20) {
rfbClientErr("Too big desktop name length sent by server: %u B > 1 MB\n", (unsigned int)client->si.nameLength);
return FALSE;
}
client->desktopName = malloc(client->si.nameLength + 1);
if (!client->desktopName) {
rfbClientLog("Error allocating memory for desktop name, %lu bytes\n",
(unsigned long)client->si.nameLength);
return FALSE;
}
if (!ReadFromRFBServer(client, client->desktopName, client->si.nameLength)) return FALSE;
client->desktopName[client->si.nameLength] = 0;
rfbClientLog("Desktop name \"%s\"\n",client->desktopName);
rfbClientLog("Connected to VNC server, using protocol version %d.%d\n",
client->major, client->minor);
rfbClientLog("VNC server default format:\n");
PrintPixelFormat(&client->si.format);
return TRUE;
}
/*
* SetFormatAndEncodings.
*/
rfbBool
SetFormatAndEncodings(rfbClient* client)
{
rfbSetPixelFormatMsg spf;
char buf[sz_rfbSetEncodingsMsg + MAX_ENCODINGS * 4];
rfbSetEncodingsMsg *se = (rfbSetEncodingsMsg *)buf;
uint32_t *encs = (uint32_t *)(&buf[sz_rfbSetEncodingsMsg]);
int len = 0;
rfbBool requestCompressLevel = FALSE;
rfbBool requestQualityLevel = FALSE;
rfbBool requestLastRectEncoding = FALSE;
rfbClientProtocolExtension* e;
if (!SupportsClient2Server(client, rfbSetPixelFormat)) return TRUE;
spf.type = rfbSetPixelFormat;
spf.pad1 = 0;
spf.pad2 = 0;
spf.format = client->format;
spf.format.redMax = rfbClientSwap16IfLE(spf.format.redMax);
spf.format.greenMax = rfbClientSwap16IfLE(spf.format.greenMax);
spf.format.blueMax = rfbClientSwap16IfLE(spf.format.blueMax);
if (!WriteToRFBServer(client, (char *)&spf, sz_rfbSetPixelFormatMsg))
return FALSE;
if (!SupportsClient2Server(client, rfbSetEncodings)) return TRUE;
se->type = rfbSetEncodings;
se->pad = 0;
se->nEncodings = 0;
if (client->appData.encodingsString) {
const char *encStr = client->appData.encodingsString;
int encStrLen;
do {
const char *nextEncStr = strchr(encStr, ' ');
if (nextEncStr) {
encStrLen = nextEncStr - encStr;
nextEncStr++;
} else {
encStrLen = strlen(encStr);
}
if (strncasecmp(encStr,"raw",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRaw);
} else if (strncasecmp(encStr,"copyrect",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCopyRect);
#ifdef LIBVNCSERVER_HAVE_LIBZ
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
} else if (strncasecmp(encStr,"tight",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingTight);
requestLastRectEncoding = TRUE;
if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9)
requestCompressLevel = TRUE;
if (client->appData.enableJPEG)
requestQualityLevel = TRUE;
#endif
#endif
} else if (strncasecmp(encStr,"hextile",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingHextile);
#ifdef LIBVNCSERVER_HAVE_LIBZ
} else if (strncasecmp(encStr,"zlib",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZlib);
if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9)
requestCompressLevel = TRUE;
} else if (strncasecmp(encStr,"zlibhex",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZlibHex);
if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9)
requestCompressLevel = TRUE;
} else if (strncasecmp(encStr,"trle",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingTRLE);
} else if (strncasecmp(encStr,"zrle",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZRLE);
} else if (strncasecmp(encStr,"zywrle",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZYWRLE);
requestQualityLevel = TRUE;
#endif
} else if ((strncasecmp(encStr,"ultra",encStrLen) == 0) || (strncasecmp(encStr,"ultrazip",encStrLen) == 0)) {
/* There are 2 encodings used in 'ultra' */
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltra);
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltraZip);
} else if (strncasecmp(encStr,"corre",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCoRRE);
} else if (strncasecmp(encStr,"rre",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRRE);
} else {
rfbClientLog("Unknown encoding '%.*s'\n",encStrLen,encStr);
}
encStr = nextEncStr;
} while (encStr && se->nEncodings < MAX_ENCODINGS);
if (se->nEncodings < MAX_ENCODINGS && requestCompressLevel) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.compressLevel +
rfbEncodingCompressLevel0);
}
if (se->nEncodings < MAX_ENCODINGS && requestQualityLevel) {
if (client->appData.qualityLevel < 0 || client->appData.qualityLevel > 9)
client->appData.qualityLevel = 5;
encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.qualityLevel +
rfbEncodingQualityLevel0);
}
}
else {
if (SameMachine(client->sock)) {
/* TODO:
if (!tunnelSpecified) {
*/
rfbClientLog("Same machine: preferring raw encoding\n");
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRaw);
/*
} else {
rfbClientLog("Tunneling active: preferring tight encoding\n");
}
*/
}
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCopyRect);
#ifdef LIBVNCSERVER_HAVE_LIBZ
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingTight);
requestLastRectEncoding = TRUE;
#endif
#endif
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingHextile);
#ifdef LIBVNCSERVER_HAVE_LIBZ
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZlib);
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZRLE);
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZYWRLE);
#endif
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltra);
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltraZip);
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCoRRE);
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRRE);
if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.compressLevel +
rfbEncodingCompressLevel0);
} else /* if (!tunnelSpecified) */ {
/* If -tunnel option was provided, we assume that server machine is
not in the local network so we use default compression level for
tight encoding instead of fast compression. Thus we are
requesting level 1 compression only if tunneling is not used. */
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCompressLevel1);
}
if (client->appData.enableJPEG) {
if (client->appData.qualityLevel < 0 || client->appData.qualityLevel > 9)
client->appData.qualityLevel = 5;
encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.qualityLevel +
rfbEncodingQualityLevel0);
}
}
/* Remote Cursor Support (local to viewer) */
if (client->appData.useRemoteCursor) {
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingXCursor);
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRichCursor);
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingPointerPos);
}
/* Keyboard State Encodings */
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingKeyboardLedState);
/* New Frame Buffer Size */
if (se->nEncodings < MAX_ENCODINGS && client->canHandleNewFBSize)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingNewFBSize);
/* Last Rect */
if (se->nEncodings < MAX_ENCODINGS && requestLastRectEncoding)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingLastRect);
/* Server Capabilities */
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingSupportedMessages);
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingSupportedEncodings);
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingServerIdentity);
/* xvp */
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingXvp);
/* client extensions */
for(e = rfbClientExtensions; e; e = e->next)
if(e->encodings) {
int* enc;
for(enc = e->encodings; *enc; enc++)
if(se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(*enc);
}
len = sz_rfbSetEncodingsMsg + se->nEncodings * 4;
se->nEncodings = rfbClientSwap16IfLE(se->nEncodings);
if (!WriteToRFBServer(client, buf, len)) return FALSE;
return TRUE;
}
/*
* SendIncrementalFramebufferUpdateRequest.
*/
rfbBool
SendIncrementalFramebufferUpdateRequest(rfbClient* client)
{
return SendFramebufferUpdateRequest(client,
client->updateRect.x, client->updateRect.y,
client->updateRect.w, client->updateRect.h, TRUE);
}
/*
* SendFramebufferUpdateRequest.
*/
rfbBool
SendFramebufferUpdateRequest(rfbClient* client, int x, int y, int w, int h, rfbBool incremental)
{
rfbFramebufferUpdateRequestMsg fur;
if (!SupportsClient2Server(client, rfbFramebufferUpdateRequest)) return TRUE;
fur.type = rfbFramebufferUpdateRequest;
fur.incremental = incremental ? 1 : 0;
fur.x = rfbClientSwap16IfLE(x);
fur.y = rfbClientSwap16IfLE(y);
fur.w = rfbClientSwap16IfLE(w);
fur.h = rfbClientSwap16IfLE(h);
if (!WriteToRFBServer(client, (char *)&fur, sz_rfbFramebufferUpdateRequestMsg))
return FALSE;
return TRUE;
}
/*
* SendScaleSetting.
*/
rfbBool
SendScaleSetting(rfbClient* client,int scaleSetting)
{
rfbSetScaleMsg ssm;
ssm.scale = scaleSetting;
ssm.pad = 0;
/* favor UltraVNC SetScale if both are supported */
if (SupportsClient2Server(client, rfbSetScale)) {
ssm.type = rfbSetScale;
if (!WriteToRFBServer(client, (char *)&ssm, sz_rfbSetScaleMsg))
return FALSE;
}
if (SupportsClient2Server(client, rfbPalmVNCSetScaleFactor)) {
ssm.type = rfbPalmVNCSetScaleFactor;
if (!WriteToRFBServer(client, (char *)&ssm, sz_rfbSetScaleMsg))
return FALSE;
}
return TRUE;
}
/*
* TextChatFunctions (UltraVNC)
* Extremely bandwidth friendly method of communicating with a user
* (Think HelpDesk type applications)
*/
rfbBool TextChatSend(rfbClient* client, char *text)
{
rfbTextChatMsg chat;
int count = strlen(text);
if (!SupportsClient2Server(client, rfbTextChat)) return TRUE;
chat.type = rfbTextChat;
chat.pad1 = 0;
chat.pad2 = 0;
chat.length = (uint32_t)count;
chat.length = rfbClientSwap32IfLE(chat.length);
if (!WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg))
return FALSE;
if (count>0) {
if (!WriteToRFBServer(client, text, count))
return FALSE;
}
return TRUE;
}
rfbBool TextChatOpen(rfbClient* client)
{
rfbTextChatMsg chat;
if (!SupportsClient2Server(client, rfbTextChat)) return TRUE;
chat.type = rfbTextChat;
chat.pad1 = 0;
chat.pad2 = 0;
chat.length = rfbClientSwap32IfLE(rfbTextChatOpen);
return (WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg) ? TRUE : FALSE);
}
rfbBool TextChatClose(rfbClient* client)
{
rfbTextChatMsg chat;
if (!SupportsClient2Server(client, rfbTextChat)) return TRUE;
chat.type = rfbTextChat;
chat.pad1 = 0;
chat.pad2 = 0;
chat.length = rfbClientSwap32IfLE(rfbTextChatClose);
return (WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg) ? TRUE : FALSE);
}
rfbBool TextChatFinish(rfbClient* client)
{
rfbTextChatMsg chat;
if (!SupportsClient2Server(client, rfbTextChat)) return TRUE;
chat.type = rfbTextChat;
chat.pad1 = 0;
chat.pad2 = 0;
chat.length = rfbClientSwap32IfLE(rfbTextChatFinished);
return (WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg) ? TRUE : FALSE);
}
/*
* UltraVNC Server Input Disable
* Apparently, the remote client can *prevent* the local user from interacting with the display
* I would think this is extremely helpful when used in a HelpDesk situation
*/
rfbBool PermitServerInput(rfbClient* client, int enabled)
{
rfbSetServerInputMsg msg;
if (!SupportsClient2Server(client, rfbSetServerInput)) return TRUE;
/* enabled==1, then server input from local keyboard is disabled */
msg.type = rfbSetServerInput;
msg.status = (enabled ? 1 : 0);
msg.pad = 0;
return (WriteToRFBServer(client, (char *)&msg, sz_rfbSetServerInputMsg) ? TRUE : FALSE);
}
/*
* send xvp client message
* A client supporting the xvp extension sends this to request that the server initiate
* a clean shutdown, clean reboot or abrupt reset of the system whose framebuffer the
* client is displaying.
*
* only version 1 is defined in the protocol specs
*
* possible values for code are:
* rfbXvp_Shutdown
* rfbXvp_Reboot
* rfbXvp_Reset
*/
rfbBool SendXvpMsg(rfbClient* client, uint8_t version, uint8_t code)
{
rfbXvpMsg xvp;
if (!SupportsClient2Server(client, rfbXvp)) return TRUE;
xvp.type = rfbXvp;
xvp.pad = 0;
xvp.version = version;
xvp.code = code;
if (!WriteToRFBServer(client, (char *)&xvp, sz_rfbXvpMsg))
return FALSE;
return TRUE;
}
/*
* SendPointerEvent.
*/
rfbBool
SendPointerEvent(rfbClient* client,int x, int y, int buttonMask)
{
rfbPointerEventMsg pe;
if (!SupportsClient2Server(client, rfbPointerEvent)) return TRUE;
pe.type = rfbPointerEvent;
pe.buttonMask = buttonMask;
if (x < 0) x = 0;
if (y < 0) y = 0;
pe.x = rfbClientSwap16IfLE(x);
pe.y = rfbClientSwap16IfLE(y);
return WriteToRFBServer(client, (char *)&pe, sz_rfbPointerEventMsg);
}
/*
* SendKeyEvent.
*/
rfbBool
SendKeyEvent(rfbClient* client, uint32_t key, rfbBool down)
{
rfbKeyEventMsg ke;
if (!SupportsClient2Server(client, rfbKeyEvent)) return TRUE;
memset(&ke, 0, sizeof(ke));
ke.type = rfbKeyEvent;
ke.down = down ? 1 : 0;
ke.key = rfbClientSwap32IfLE(key);
return WriteToRFBServer(client, (char *)&ke, sz_rfbKeyEventMsg);
}
/*
* SendClientCutText.
*/
rfbBool
SendClientCutText(rfbClient* client, char *str, int len)
{
rfbClientCutTextMsg cct;
if (!SupportsClient2Server(client, rfbClientCutText)) return TRUE;
memset(&cct, 0, sizeof(cct));
cct.type = rfbClientCutText;
cct.length = rfbClientSwap32IfLE(len);
return (WriteToRFBServer(client, (char *)&cct, sz_rfbClientCutTextMsg) &&
WriteToRFBServer(client, str, len));
}
/*
* HandleRFBServerMessage.
*/
rfbBool
HandleRFBServerMessage(rfbClient* client)
{
rfbServerToClientMsg msg;
if (client->serverPort==-1)
client->vncRec->readTimestamp = TRUE;
if (!ReadFromRFBServer(client, (char *)&msg, 1))
return FALSE;
switch (msg.type) {
case rfbSetColourMapEntries:
{
/* TODO:
int i;
uint16_t rgb[3];
XColor xc;
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbSetColourMapEntriesMsg - 1))
return FALSE;
msg.scme.firstColour = rfbClientSwap16IfLE(msg.scme.firstColour);
msg.scme.nColours = rfbClientSwap16IfLE(msg.scme.nColours);
for (i = 0; i < msg.scme.nColours; i++) {
if (!ReadFromRFBServer(client, (char *)rgb, 6))
return FALSE;
xc.pixel = msg.scme.firstColour + i;
xc.red = rfbClientSwap16IfLE(rgb[0]);
xc.green = rfbClientSwap16IfLE(rgb[1]);
xc.blue = rfbClientSwap16IfLE(rgb[2]);
xc.flags = DoRed|DoGreen|DoBlue;
XStoreColor(dpy, cmap, &xc);
}
*/
break;
}
case rfbFramebufferUpdate:
{
rfbFramebufferUpdateRectHeader rect;
int linesToRead;
int bytesPerLine;
int i;
if (!ReadFromRFBServer(client, ((char *)&msg.fu) + 1,
sz_rfbFramebufferUpdateMsg - 1))
return FALSE;
msg.fu.nRects = rfbClientSwap16IfLE(msg.fu.nRects);
for (i = 0; i < msg.fu.nRects; i++) {
if (!ReadFromRFBServer(client, (char *)&rect, sz_rfbFramebufferUpdateRectHeader))
return FALSE;
rect.encoding = rfbClientSwap32IfLE(rect.encoding);
if (rect.encoding == rfbEncodingLastRect)
break;
rect.r.x = rfbClientSwap16IfLE(rect.r.x);
rect.r.y = rfbClientSwap16IfLE(rect.r.y);
rect.r.w = rfbClientSwap16IfLE(rect.r.w);
rect.r.h = rfbClientSwap16IfLE(rect.r.h);
if (rect.encoding == rfbEncodingXCursor ||
rect.encoding == rfbEncodingRichCursor) {
if (!HandleCursorShape(client,
rect.r.x, rect.r.y, rect.r.w, rect.r.h,
rect.encoding)) {
return FALSE;
}
continue;
}
if (rect.encoding == rfbEncodingPointerPos) {
if (!client->HandleCursorPos(client,rect.r.x, rect.r.y)) {
return FALSE;
}
continue;
}
if (rect.encoding == rfbEncodingKeyboardLedState) {
/* OK! We have received a keyboard state message!!! */
client->KeyboardLedStateEnabled = 1;
if (client->HandleKeyboardLedState!=NULL)
client->HandleKeyboardLedState(client, rect.r.x, 0);
/* stash it for the future */
client->CurrentKeyboardLedState = rect.r.x;
continue;
}
if (rect.encoding == rfbEncodingNewFBSize) {
client->width = rect.r.w;
client->height = rect.r.h;
client->updateRect.x = client->updateRect.y = 0;
client->updateRect.w = client->width;
client->updateRect.h = client->height;
if (!client->MallocFrameBuffer(client))
return FALSE;
SendFramebufferUpdateRequest(client, 0, 0, rect.r.w, rect.r.h, FALSE);
rfbClientLog("Got new framebuffer size: %dx%d\n", rect.r.w, rect.r.h);
continue;
}
/* rect.r.w=byte count */
if (rect.encoding == rfbEncodingSupportedMessages) {
int loop;
if (!ReadFromRFBServer(client, (char *)&client->supportedMessages, sz_rfbSupportedMessages))
return FALSE;
/* msgs is two sets of bit flags of supported messages client2server[] and server2client[] */
/* currently ignored by this library */
rfbClientLog("client2server supported messages (bit flags)\n");
for (loop=0;loop<32;loop+=8)
rfbClientLog("%02X: %04x %04x %04x %04x - %04x %04x %04x %04x\n", loop,
client->supportedMessages.client2server[loop], client->supportedMessages.client2server[loop+1],
client->supportedMessages.client2server[loop+2], client->supportedMessages.client2server[loop+3],
client->supportedMessages.client2server[loop+4], client->supportedMessages.client2server[loop+5],
client->supportedMessages.client2server[loop+6], client->supportedMessages.client2server[loop+7]);
rfbClientLog("server2client supported messages (bit flags)\n");
for (loop=0;loop<32;loop+=8)
rfbClientLog("%02X: %04x %04x %04x %04x - %04x %04x %04x %04x\n", loop,
client->supportedMessages.server2client[loop], client->supportedMessages.server2client[loop+1],
client->supportedMessages.server2client[loop+2], client->supportedMessages.server2client[loop+3],
client->supportedMessages.server2client[loop+4], client->supportedMessages.server2client[loop+5],
client->supportedMessages.server2client[loop+6], client->supportedMessages.server2client[loop+7]);
continue;
}
/* rect.r.w=byte count, rect.r.h=# of encodings */
if (rect.encoding == rfbEncodingSupportedEncodings) {
char *buffer;
buffer = malloc(rect.r.w);
if (!ReadFromRFBServer(client, buffer, rect.r.w))
{
free(buffer);
return FALSE;
}
/* buffer now contains rect.r.h # of uint32_t encodings that the server supports */
/* currently ignored by this library */
free(buffer);
continue;
}
/* rect.r.w=byte count */
if (rect.encoding == rfbEncodingServerIdentity) {
char *buffer;
buffer = malloc(rect.r.w+1);
if (!ReadFromRFBServer(client, buffer, rect.r.w))
{
free(buffer);
return FALSE;
}
buffer[rect.r.w]=0; /* null terminate, just in case */
rfbClientLog("Connected to Server \"%s\"\n", buffer);
free(buffer);
continue;
}
/* rfbEncodingUltraZip is a collection of subrects. x = # of subrects, and h is always 0 */
if (rect.encoding != rfbEncodingUltraZip)
{
if ((rect.r.x + rect.r.w > client->width) ||
(rect.r.y + rect.r.h > client->height))
{
rfbClientLog("Rect too large: %dx%d at (%d, %d)\n",
rect.r.w, rect.r.h, rect.r.x, rect.r.y);
return FALSE;
}
/* UltraVNC with scaling, will send rectangles with a zero W or H
*
if ((rect.encoding != rfbEncodingTight) &&
(rect.r.h * rect.r.w == 0))
{
rfbClientLog("Zero size rect - ignoring (encoding=%d (0x%08x) %dx, %dy, %dw, %dh)\n", rect.encoding, rect.encoding, rect.r.x, rect.r.y, rect.r.w, rect.r.h);
continue;
}
*/
/* If RichCursor encoding is used, we should prevent collisions
between framebuffer updates and cursor drawing operations. */
client->SoftCursorLockArea(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h);
}
switch (rect.encoding) {
case rfbEncodingRaw: {
int y=rect.r.y, h=rect.r.h;
bytesPerLine = rect.r.w * client->format.bitsPerPixel / 8;
/* RealVNC 4.x-5.x on OSX can induce bytesPerLine==0,
usually during GPU accel. */
/* Regardless of cause, do not divide by zero. */
linesToRead = bytesPerLine ? (RFB_BUFFER_SIZE / bytesPerLine) : 0;
while (linesToRead && h > 0) {
if (linesToRead > h)
linesToRead = h;
if (!ReadFromRFBServer(client, client->buffer,bytesPerLine * linesToRead))
return FALSE;
client->GotBitmap(client, (uint8_t *)client->buffer,
rect.r.x, y, rect.r.w,linesToRead);
h -= linesToRead;
y += linesToRead;
}
break;
}
case rfbEncodingCopyRect:
{
rfbCopyRect cr;
if (!ReadFromRFBServer(client, (char *)&cr, sz_rfbCopyRect))
return FALSE;
cr.srcX = rfbClientSwap16IfLE(cr.srcX);
cr.srcY = rfbClientSwap16IfLE(cr.srcY);
/* If RichCursor encoding is used, we should extend our
"cursor lock area" (previously set to destination
rectangle) to the source rectangle as well. */
client->SoftCursorLockArea(client,
cr.srcX, cr.srcY, rect.r.w, rect.r.h);
client->GotCopyRect(client, cr.srcX, cr.srcY, rect.r.w, rect.r.h,
rect.r.x, rect.r.y);
break;
}
case rfbEncodingRRE:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleRRE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleRRE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleRRE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingCoRRE:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleCoRRE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleCoRRE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleCoRRE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingHextile:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleHextile8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleHextile16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleHextile32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingUltra:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleUltra8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleUltra16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleUltra32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingUltraZip:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleUltraZip8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleUltraZip16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleUltraZip32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingTRLE:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleTRLE8(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
break;
case 16:
if (client->si.format.greenMax > 0x1F) {
if (!HandleTRLE16(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
} else {
if (!HandleTRLE15(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
}
break;
case 32: {
uint32_t maxColor =
(client->format.redMax << client->format.redShift) |
(client->format.greenMax << client->format.greenShift) |
(client->format.blueMax << client->format.blueShift);
if ((client->format.bigEndian && (maxColor & 0xff) == 0) ||
(!client->format.bigEndian && (maxColor & 0xff000000) == 0)) {
if (!HandleTRLE24(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
} else if (!client->format.bigEndian && (maxColor & 0xff) == 0) {
if (!HandleTRLE24Up(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
} else if (client->format.bigEndian && (maxColor & 0xff000000) == 0) {
if (!HandleTRLE24Down(client, rect.r.x, rect.r.y, rect.r.w,
rect.r.h))
return FALSE;
} else if (!HandleTRLE32(client, rect.r.x, rect.r.y, rect.r.w,
rect.r.h))
return FALSE;
break;
}
}
break;
}
#ifdef LIBVNCSERVER_HAVE_LIBZ
case rfbEncodingZlib:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleZlib8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleZlib16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleZlib32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
case rfbEncodingTight:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleTight8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleTight16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleTight32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
#endif
case rfbEncodingZRLE:
/* Fail safe for ZYWRLE unsupport VNC server. */
client->appData.qualityLevel = 9;
/* fall through */
case rfbEncodingZYWRLE:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleZRLE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (client->si.format.greenMax > 0x1F) {
if (!HandleZRLE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else {
if (!HandleZRLE15(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
}
break;
case 32:
{
uint32_t maxColor=(client->format.redMax<<client->format.redShift)|
(client->format.greenMax<<client->format.greenShift)|
(client->format.blueMax<<client->format.blueShift);
if ((client->format.bigEndian && (maxColor&0xff)==0) ||
(!client->format.bigEndian && (maxColor&0xff000000)==0)) {
if (!HandleZRLE24(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else if (!client->format.bigEndian && (maxColor&0xff)==0) {
if (!HandleZRLE24Up(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else if (client->format.bigEndian && (maxColor&0xff000000)==0) {
if (!HandleZRLE24Down(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else if (!HandleZRLE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
}
break;
}
#endif
default:
{
rfbBool handled = FALSE;
rfbClientProtocolExtension* e;
for(e = rfbClientExtensions; !handled && e; e = e->next)
if(e->handleEncoding && e->handleEncoding(client, &rect))
handled = TRUE;
if(!handled) {
rfbClientLog("Unknown rect encoding %d\n",
(int)rect.encoding);
return FALSE;
}
}
}
/* Now we may discard "soft cursor locks". */
client->SoftCursorUnlockScreen(client);
client->GotFrameBufferUpdate(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h);
}
if (!SendIncrementalFramebufferUpdateRequest(client))
return FALSE;
if (client->FinishedFrameBufferUpdate)
client->FinishedFrameBufferUpdate(client);
break;
}
case rfbBell:
{
client->Bell(client);
break;
}
case rfbServerCutText:
{
char *buffer;
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbServerCutTextMsg - 1))
return FALSE;
msg.sct.length = rfbClientSwap32IfLE(msg.sct.length);
if (msg.sct.length > 1<<20) {
rfbClientErr("Ignoring too big cut text length sent by server: %u B > 1 MB\n", (unsigned int)msg.sct.length);
return FALSE;
}
buffer = malloc(msg.sct.length+1);
if (!ReadFromRFBServer(client, buffer, msg.sct.length)) {
free(buffer);
return FALSE;
}
buffer[msg.sct.length] = 0;
if (client->GotXCutText)
client->GotXCutText(client, buffer, msg.sct.length);
free(buffer);
break;
}
case rfbTextChat:
{
char *buffer=NULL;
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbTextChatMsg- 1))
return FALSE;
msg.tc.length = rfbClientSwap32IfLE(msg.sct.length);
switch(msg.tc.length) {
case rfbTextChatOpen:
rfbClientLog("Received TextChat Open\n");
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)rfbTextChatOpen, NULL);
break;
case rfbTextChatClose:
rfbClientLog("Received TextChat Close\n");
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)rfbTextChatClose, NULL);
break;
case rfbTextChatFinished:
rfbClientLog("Received TextChat Finished\n");
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)rfbTextChatFinished, NULL);
break;
default:
buffer=malloc(msg.tc.length+1);
if (!ReadFromRFBServer(client, buffer, msg.tc.length))
{
free(buffer);
return FALSE;
}
/* Null Terminate <just in case> */
buffer[msg.tc.length]=0;
rfbClientLog("Received TextChat \"%s\"\n", buffer);
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)msg.tc.length, buffer);
free(buffer);
break;
}
break;
}
case rfbXvp:
{
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbXvpMsg -1))
return FALSE;
SetClient2Server(client, rfbXvp);
/* technically, we only care what we can *send* to the server
* but, we set Server2Client Just in case it ever becomes useful
*/
SetServer2Client(client, rfbXvp);
if(client->HandleXvpMsg)
client->HandleXvpMsg(client, msg.xvp.version, msg.xvp.code);
break;
}
case rfbResizeFrameBuffer:
{
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbResizeFrameBufferMsg -1))
return FALSE;
client->width = rfbClientSwap16IfLE(msg.rsfb.framebufferWidth);
client->height = rfbClientSwap16IfLE(msg.rsfb.framebufferHeigth);
client->updateRect.x = client->updateRect.y = 0;
client->updateRect.w = client->width;
client->updateRect.h = client->height;
if (!client->MallocFrameBuffer(client))
return FALSE;
SendFramebufferUpdateRequest(client, 0, 0, client->width, client->height, FALSE);
rfbClientLog("Got new framebuffer size: %dx%d\n", client->width, client->height);
break;
}
case rfbPalmVNCReSizeFrameBuffer:
{
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbPalmVNCReSizeFrameBufferMsg -1))
return FALSE;
client->width = rfbClientSwap16IfLE(msg.prsfb.buffer_w);
client->height = rfbClientSwap16IfLE(msg.prsfb.buffer_h);
client->updateRect.x = client->updateRect.y = 0;
client->updateRect.w = client->width;
client->updateRect.h = client->height;
if (!client->MallocFrameBuffer(client))
return FALSE;
SendFramebufferUpdateRequest(client, 0, 0, client->width, client->height, FALSE);
rfbClientLog("Got new framebuffer size: %dx%d\n", client->width, client->height);
break;
}
default:
{
rfbBool handled = FALSE;
rfbClientProtocolExtension* e;
for(e = rfbClientExtensions; !handled && e; e = e->next)
if(e->handleMessage && e->handleMessage(client, &msg))
handled = TRUE;
if(!handled) {
char buffer[256];
rfbClientLog("Unknown message type %d from VNC server\n",msg.type);
ReadFromRFBServer(client, buffer, 256);
return FALSE;
}
}
}
return TRUE;
}
#define GET_PIXEL8(pix, ptr) ((pix) = *(ptr)++)
#define GET_PIXEL16(pix, ptr) (((uint8_t*)&(pix))[0] = *(ptr)++, \
((uint8_t*)&(pix))[1] = *(ptr)++)
#define GET_PIXEL32(pix, ptr) (((uint8_t*)&(pix))[0] = *(ptr)++, \
((uint8_t*)&(pix))[1] = *(ptr)++, \
((uint8_t*)&(pix))[2] = *(ptr)++, \
((uint8_t*)&(pix))[3] = *(ptr)++)
/* CONCAT2 concatenates its two arguments. CONCAT2E does the same but also
expands its arguments if they are macros */
#define CONCAT2(a,b) a##b
#define CONCAT2E(a,b) CONCAT2(a,b)
#define CONCAT3(a,b,c) a##b##c
#define CONCAT3E(a,b,c) CONCAT3(a,b,c)
#define BPP 8
#include "rre.c"
#include "corre.c"
#include "hextile.c"
#include "ultra.c"
#include "zlib.c"
#include "tight.c"
#include "trle.c"
#include "zrle.c"
#undef BPP
#define BPP 16
#include "rre.c"
#include "corre.c"
#include "hextile.c"
#include "ultra.c"
#include "zlib.c"
#include "tight.c"
#include "trle.c"
#include "zrle.c"
#define REALBPP 15
#include "trle.c"
#define REALBPP 15
#include "zrle.c"
#undef BPP
#define BPP 32
#include "rre.c"
#include "corre.c"
#include "hextile.c"
#include "ultra.c"
#include "zlib.c"
#include "tight.c"
#include "trle.c"
#include "zrle.c"
#define REALBPP 24
#include "trle.c"
#define REALBPP 24
#include "zrle.c"
#define REALBPP 24
#define UNCOMP 8
#include "trle.c"
#define REALBPP 24
#define UNCOMP 8
#include "zrle.c"
#define REALBPP 24
#define UNCOMP -8
#include "trle.c"
#define REALBPP 24
#define UNCOMP -8
#include "zrle.c"
#undef BPP
/*
* PrintPixelFormat.
*/
void
PrintPixelFormat(rfbPixelFormat *format)
{
if (format->bitsPerPixel == 1) {
rfbClientLog(" Single bit per pixel.\n");
rfbClientLog(
" %s significant bit in each byte is leftmost on the screen.\n",
(format->bigEndian ? "Most" : "Least"));
} else {
rfbClientLog(" %d bits per pixel.\n",format->bitsPerPixel);
if (format->bitsPerPixel != 8) {
rfbClientLog(" %s significant byte first in each pixel.\n",
(format->bigEndian ? "Most" : "Least"));
}
if (format->trueColour) {
rfbClientLog(" TRUE colour: max red %d green %d blue %d"
", shift red %d green %d blue %d\n",
format->redMax, format->greenMax, format->blueMax,
format->redShift, format->greenShift, format->blueShift);
} else {
rfbClientLog(" Colour map (not true colour).\n");
}
}
}
/* avoid name clashes with LibVNCServer */
#define rfbEncryptBytes rfbClientEncryptBytes
#define rfbEncryptBytes2 rfbClientEncryptBytes2
#define rfbDes rfbClientDes
#define rfbDesKey rfbClientDesKey
#define rfbUseKey rfbClientUseKey
#include "vncauth.c"
#include "d3des.c"
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_518_0 |
crossvul-cpp_data_bad_978_0 | /*
3APA3A simpliest proxy server
(c) 2002-2008 by ZARAZA <3APA3A@security.nnov.ru>
please read License Agreement
*/
#include "proxy.h"
#define RETURN(xxx) { param->res = xxx; goto CLEANRET; }
#define LINESIZE 2048
extern FILE *writable;
FILE * confopen();
extern void decodeurl(unsigned char *s, int filter);
struct printparam {
char buf[1024];
int inbuf;
struct clientparam *cp;
};
static void stdpr(struct printparam* pp, char *buf, int inbuf){
if((pp->inbuf + inbuf > 1024) || !buf) {
socksend(pp->cp->clisock, (unsigned char *)pp->buf, pp->inbuf, conf.timeouts[STRING_S]);
pp->inbuf = 0;
if(!buf) return;
}
if(inbuf >= 1000){
socksend(pp->cp->clisock, (unsigned char *)buf, inbuf, conf.timeouts[STRING_S]);
}
else {
memcpy(pp->buf + pp->inbuf, buf, inbuf);
pp->inbuf += inbuf;
}
}
static void stdcbf(void *cb, char *buf, int inbuf){
int delay = 0;
int i;
for(i = 0; i < inbuf; i++){
switch(buf[i]){
case '&':
if(delay){
stdpr((struct printparam*)cb, buf+i-delay, delay);
delay = 0;
}
stdpr((struct printparam*)cb, "&", 5);
break;
case '<':
if(delay){
stdpr((struct printparam*)cb, buf+i-delay, delay);
delay = 0;
}
stdpr((struct printparam*)cb, "<", 4);
break;
case '>':
if(delay){
stdpr((struct printparam*)cb, buf+i-delay, delay);
delay = 0;
}
stdpr((struct printparam*)cb, ">", 4);
break;
default:
delay++;
break;
}
}
if(delay){
stdpr((struct printparam*)cb, buf+i-delay, delay);
}
}
/*
static char * templateprint(struct printparam* pp, int *level, struct dictionary *dict, char * template){
char *s, *s2;
for(; template && *template; ){
if(!( s = strchr(template, '<'))){
stdpr(pp, template, (int)strlen(template));
return template + strlen(template);
}
if(s[1] != '%' || s[2] == '%'){
stdpr(pp, template, (int)(s - template) + 1);
template = s + 1;
continue;
}
if(s[2] == '/' && (s2 = strchr(s + 2, '>')) && *(s2 - 1) == '%'){
if(--*level < 0) return NULL;
return s2 + 1;
}
}
return template;
}
*/
static void printstr(struct printparam* pp, char* str){
stdpr(pp, str, str?(int)strlen(str):0);
}
static void printval(void *value, int type, int level, struct printparam* pp){
struct node pn, cn;
struct property *p;
int i;
pn.iteration = NULL;
pn.parent = NULL;
pn.type = type;
pn.value = value;
printstr(pp, "<item>");
for(p = datatypes[type].properties; p; ) {
cn.iteration = NULL;
cn.parent = &pn;
cn.type = p->type;
cn.value = (*p->e_f)(&pn);
if(cn.value){
for(i = 0; i < level; i++) printstr(pp, "\t");
if(strcmp(p->name, "next")){
printstr(pp, "<parameter>");
printstr(pp, "<name>");
printstr(pp, p->name);
printstr(pp, "</name>");
printstr(pp, "<type>");
printstr(pp, datatypes[p->type].type);
printstr(pp, "</type>");
printstr(pp, "<description>");
printstr(pp, p->description);
printstr(pp, "</description>");
}
if(datatypes[p->type].p_f){
printstr(pp, "<value><![CDATA[");
(*datatypes[p->type].p_f)(&cn, stdcbf, pp);
printstr(pp, "]]></value>\n");
printstr(pp, "</parameter>");
}
else {
if(!strcmp(p->name, "next")){
/* printstr(pp, "<!-- -------------------- -->\n"); */
printstr(pp, "</item>\n<item>");
p = datatypes[type].properties;
pn.value = value = cn.value;
continue;
}
else {
printstr(pp, "\n");
printval(cn.value, cn.type, level+1, pp);
printstr(pp, "</parameter>");
}
}
}
p=p->next;
}
printstr(pp, "</item>");
}
char * admin_stringtable[]={
"HTTP/1.0 401 Authentication Required\r\n"
"WWW-Authenticate: Basic realm=\"proxy\"\r\n"
"Connection: close\r\n"
"Content-type: text/html; charset=us-ascii\r\n"
"\r\n"
"<html><head><title>401 Authentication Required</title></head>\r\n"
"<body><h2>401 Authentication Required</h2><h3>Access to requested resource disallowed by administrator or you need valid username/password to use this resource</h3></body></html>\r\n",
"HTTP/1.0 200 OK\r\n"
"Connection: close\r\n"
"Expires: Thu, 01 Dec 1994 16:00:00 GMT\r\n"
"Cache-Control: no-cache\r\n"
"Content-type: text/html\r\n"
"\r\n"
"<http><head><title>%s configuration page</title></head>\r\n"
"<table width=\'100%%\' border=\'0\'>\r\n"
"<tr><td width=\'150\' valign=\'top\'>\r\n"
"<h2> "
" </h2>\r\n"
"<A HREF=\'/C'>Counters</A><br>\r\n"
"<A HREF=\'/R'>Reload</A><br>\r\n"
"<A HREF=\'/S'>Running Services</A><br>\r\n"
"<A HREF=\'/F'>Config</A>\r\n"
"</td><td>"
"<h2>%s %s configuration</h2>",
"HTTP/1.0 200 OK\r\n"
"Connection: close\r\n"
"Cache-Control: no-cache\r\n"
"Content-type: text/xml\r\n"
"\r\n"
"<?xml version=\"1.0\"?>\r\n"
"<?xml-stylesheet href=\"/SX\" type=\"text/css\"?>\r\n"
"<services>\r\n"
"<description>Services currently running and connected clients</description>\r\n",
"</services>\r\n",
"HTTP/1.0 200 OK\r\n"
"Connection: close\r\n"
"Cache-Control: no-cache\r\n"
"Content-type: text/css\r\n"
"\r\n"
"services {\r\n"
" display: block;\r\n"
" margin: 10px auto 10px auto;\r\n"
" width: 80%;\r\n"
" background: black;\r\n"
" font-family: sans-serif;\r\n"
" font-size: small;\r\n"
" color: silver;\r\n"
" }\r\n"
"item {\r\n"
" display: block;\r\n"
" margin-bottom: 10px;\r\n"
" border: 2px solid #CCC;\r\n"
" padding: 10px;\r\n"
" spacing: 2px;\r\n"
" }\r\n"
"parameter {\r\n"
" display: block;\r\n"
" padding: 2px;\r\n"
" margin-top: 10px;\r\n"
" border: 1px solid grey;\r\n"
" background: #EEE;\r\n"
" color: black;\r\n"
" }\r\n"
"name {\r\n"
" display: inline;\r\n"
" float: left;\r\n"
" margin-right: 5px;\r\n"
" font-weight: bold;\r\n"
" }\r\n"
"type {\r\n"
" display: inline;\r\n"
" font-size: x-small;\r\n"
" margin-right: 5px;\r\n"
" color: #666;\r\n"
" white-space: nowrap;\r\n"
" font-style: italic;\r\n"
" }\r\n"
"description {\r\n"
" display: inline;\r\n"
" margin-right: 5px;\r\n"
" white-space: nowrap;\r\n"
" }\r\n"
"value {\r\n"
" display: block;\r\n"
" margin-right: 5px;\r\n"
" }\r\n",
"<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />\r\n"
"<pre><font size=\'-2\'><b>"
COPYRIGHT
"</b></font>\r\n"
"</td></tr></table></body></html>",
"<h3>Counters</h3>\r\n"
"<table border = \'1\'>\r\n"
"<tr align=\'center\'><td>Description</td><td>Active</td>"
"<td>Users</td><td>Source Address</td><td>Destination Address</td>"
"<td>Port</td>"
"<td>Limit</td><td>Units</td><td>Value</td>"
"<td>Reset</td><td>Updated</td><td>Num</td></tr>\r\n",
"</table>\r\n",
NULL
};
#define authreq admin_stringtable[0]
#define ok admin_stringtable[1]
#define xml admin_stringtable[2]
#define postxml admin_stringtable[3]
#define style admin_stringtable[4]
#define tail admin_stringtable[5]
#define counters admin_stringtable[6]
#define counterstail admin_stringtable[7]
static int printportlist(char *buf, int bufsize, struct portlist* pl, char * delim){
int printed = 0;
for(; pl; pl = pl->next){
if(printed > (bufsize - 64)) break;
if(pl->startport != pl->endport)
printed += sprintf(buf+printed, "%hu-%hu%s", pl->startport, pl->endport, pl->next?delim:"");
else {
/*
struct servent *se=NULL;
if(pl->startport)se = getservbyport((int)ntohs(pl->startport), NULL);
printed += sprintf(buf+printed, "%hu(%s)%s", pl->startport, se?se->s_name:"unknown", pl->next?delim:"");
*/
printed += sprintf(buf+printed, "%hu%s", pl->startport, pl->next?delim:"");
}
if(printed > (bufsize - 64)) {
printed += sprintf(buf+printed, "...");
break;
}
}
return printed;
}
static int printuserlist(char *buf, int bufsize, struct userlist* ul, char * delim){
int printed = 0;
for(; ul; ul = ul->next){
if(printed > (bufsize - 64)) break;
printed += sprintf(buf+printed, "%s%s", ul->user, ul->next?delim:"");
if(printed > (bufsize - 64)) {
printed += sprintf(buf+printed, "...");
break;
}
}
return printed;
}
int printiple(char *buf, struct iplist* ipl);
static int printiplist(char *buf, int bufsize, struct iplist* ipl, char * delim){
int printed = 0;
for(; ipl; ipl = ipl->next){
if(printed > (bufsize - 128)) break;
printed += printiple(buf+printed, ipl);
if(printed > (bufsize - 128)) {
printed += sprintf(buf+printed, "...");
break;
}
}
return printed;
}
void * adminchild(struct clientparam* param) {
int i, res;
char * buf;
char username[256];
char *sb;
char *req = NULL;
struct printparam pp;
int contentlen = 0;
int isform = 0;
pp.inbuf = 0;
pp.cp = param;
buf = myalloc(LINESIZE);
if(!buf) {RETURN(555);}
i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, LINESIZE - 1, '\n', conf.timeouts[STRING_S]);
if(i<5 || ((buf[0]!='G' || buf[1]!='E' || buf[2]!='T' || buf[3]!=' ' || buf[4]!='/') &&
(buf[0]!='P' || buf[1]!='O' || buf[2]!='S' || buf[3]!='T' || buf[4]!=' ' || buf[5]!='/')))
{
RETURN(701);
}
buf[i] = 0;
sb = strchr(buf+5, ' ');
if(!sb){
RETURN(702);
}
*sb = 0;
req = mystrdup(buf + ((*buf == 'P')? 6 : 5));
while((i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, LINESIZE - 1, '\n', conf.timeouts[STRING_S])) > 2){
buf[i] = 0;
if(i > 19 && (!strncasecmp(buf, "authorization", 13))){
sb = strchr(buf, ':');
if(!sb)continue;
++sb;
while(isspace(*sb))sb++;
if(!*sb || strncasecmp(sb, "basic", 5)){
continue;
}
sb+=5;
while(isspace(*sb))sb++;
i = de64((unsigned char *)sb, (unsigned char *)username, 255);
if(i<=0)continue;
username[i] = 0;
sb = strchr((char *)username, ':');
if(sb){
*sb = 0;
if(param->password)myfree(param->password);
param->password = (unsigned char *)mystrdup(sb+1);
}
if(param->username) myfree(param->username);
param->username = (unsigned char *)mystrdup(username);
continue;
}
else if(i > 15 && (!strncasecmp(buf, "content-length:", 15))){
sb = buf + 15;
while(isspace(*sb))sb++;
contentlen = atoi(sb);
}
else if(i > 13 && (!strncasecmp(buf, "content-type:", 13))){
sb = buf + 13;
while(isspace(*sb))sb++;
if(!strncasecmp(sb, "x-www-form-urlencoded", 21)) isform = 1;
}
}
param->operation = ADMIN;
if(isform && contentlen) {
printstr(&pp, "HTTP/1.0 100 Continue\r\n\r\n");
stdpr(&pp, NULL, 0);
}
res = (*param->srv->authfunc)(param);
if(res && res != 10) {
printstr(&pp, authreq);
RETURN(res);
}
if(param->srv->singlepacket || param->redirected){
if(*req == 'C') req[1] = 0;
else *req = 0;
}
sprintf(buf, ok, conf.stringtable?(char *)conf.stringtable[2]:"3proxy", conf.stringtable?(char *)conf.stringtable[2]:"3[APA3A] tiny proxy", conf.stringtable?(char *)conf.stringtable[3]:"");
if(*req != 'S') printstr(&pp, buf);
switch(*req){
case 'C':
printstr(&pp, counters);
{
struct trafcount *cp;
int num = 0;
for(cp = conf.trafcounter; cp; cp = cp->next, num++){
int inbuf = 0;
if(cp->ace && (param->srv->singlepacket || param->redirected)){
if(!ACLmatches(cp->ace, param))continue;
}
if(req[1] == 'S' && atoi(req+2) == num) cp->disabled=0;
if(req[1] == 'D' && atoi(req+2) == num) cp->disabled=1;
inbuf += sprintf(buf, "<tr>"
"<td>%s</td><td><A HREF=\'/C%c%d\'>%s</A></td><td>",
(cp->comment)?cp->comment:" ",
(cp->disabled)?'S':'D',
num,
(cp->disabled)?"NO":"YES"
);
if(!cp->ace || !cp->ace->users){
inbuf += sprintf(buf+inbuf, "<center>ANY</center>");
}
else {
inbuf += printuserlist(buf+inbuf, LINESIZE-800, cp->ace->users, ",<br />\r\n");
}
inbuf += sprintf(buf+inbuf, "</td><td>");
if(!cp->ace || !cp->ace->src){
inbuf += sprintf(buf+inbuf, "<center>ANY</center>");
}
else {
inbuf += printiplist(buf+inbuf, LINESIZE-512, cp->ace->src, ",<br />\r\n");
}
inbuf += sprintf(buf+inbuf, "</td><td>");
if(!cp->ace || !cp->ace->dst){
inbuf += sprintf(buf+inbuf, "<center>ANY</center>");
}
else {
inbuf += printiplist(buf+inbuf, LINESIZE-512, cp->ace->dst, ",<br />\r\n");
}
inbuf += sprintf(buf+inbuf, "</td><td>");
if(!cp->ace || !cp->ace->ports){
inbuf += sprintf(buf+inbuf, "<center>ANY</center>");
}
else {
inbuf += printportlist(buf+inbuf, LINESIZE-128, cp->ace->ports, ",<br />\r\n");
}
if(cp->type == NONE) {
inbuf += sprintf(buf+inbuf,
"</td><td colspan=\'6\' align=\'center\'>exclude from limitation</td></tr>\r\n"
);
}
else {
inbuf += sprintf(buf+inbuf,
"</td><td>%"PRINTF_INT64_MODIFIER"u</td>"
"<td>MB%s</td>"
"<td>%"PRINTF_INT64_MODIFIER"u</td>"
"<td>%s</td>",
cp->traflim64 / (1024 * 1024),
rotations[cp->type],
cp->traf64,
cp->cleared?ctime(&cp->cleared):"never"
);
inbuf += sprintf(buf + inbuf,
"<td>%s</td>"
"<td>%i</td>"
"</tr>\r\n",
cp->updated?ctime(&cp->updated):"never",
cp->number
);
}
printstr(&pp, buf);
}
}
printstr(&pp, counterstail);
break;
case 'R':
conf.needreload = 1;
printstr(&pp, "<h3>Reload scheduled</h3>");
break;
case 'S':
{
if(req[1] == 'X'){
printstr(&pp, style);
break;
}
printstr(&pp, xml);
printval(conf.services, TYPE_SERVER, 0, &pp);
printstr(&pp, postxml);
}
break;
case 'F':
{
FILE *fp;
char buf[256];
fp = confopen();
if(!fp){
printstr(&pp, "<h3><font color=\"red\">Failed to open config file</font></h3>");
break;
}
printstr(&pp, "<h3>Please be careful editing config file remotely</h3>");
printstr(&pp, "<form method=\"POST\" action=\"/U\"><textarea cols=\"80\" rows=\"30\" name=\"conffile\">");
while(fgets(buf, 256, fp)){
printstr(&pp, buf);
}
if(!writable) fclose(fp);
printstr(&pp, "</textarea><br><input type=\"Submit\"></form>");
break;
}
case 'U':
{
int l=0;
int error = 0;
if(!writable || fseek(writable, 0, 0)){
error = 1;
}
while((i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, LINESIZE - 1, '+', conf.timeouts[STRING_S])) > 0){
if(i > (contentlen - l)) i = (contentlen - l);
buf[i] = 0;
if(!l){
if(strncasecmp(buf, "conffile=", 9)) error = 1;
}
if(!error){
decodeurl((unsigned char *)buf, 1);
fprintf(writable, "%s", l? buf : buf + 9);
}
l += i;
if(l >= contentlen) break;
}
if(writable && !error){
fflush(writable);
#ifndef _WINCE
ftruncate(fileno(writable), ftell(writable));
#endif
}
printstr(&pp, error? "<h3><font color=\"red\">Config file is not writable</font></h3>Make sure you have \"writable\" command in configuration file":
"<h3>Configuration updated</h3>");
}
break;
default:
printstr(&pp, (char *)conf.stringtable[WEBBANNERS]);
break;
}
if(*req != 'S') printstr(&pp, tail);
CLEANRET:
printstr(&pp, NULL);
if(buf) myfree(buf);
(*param->srv->logfunc)(param, (unsigned char *)req);
if(req)myfree(req);
freeparam(param);
return (NULL);
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_978_0 |
crossvul-cpp_data_bad_1040_1 | /*
* rfbserver.c - deal with server-side of the RFB protocol.
*/
/*
* Copyright (C) 2009-2019 D. R. Commander. All Rights Reserved.
* Copyright (C) 2010 University Corporation for Atmospheric Research.
* All Rights Reserved.
* Copyright (C) 2005-2008 Sun Microsystems, Inc. All Rights Reserved.
* Copyright (C) 2004 Landmark Graphics Corporation. All Rights Reserved.
* Copyright (C) 2000-2006 Constantin Kaplinsky. All Rights Reserved.
* Copyright (C) 2000 Tridia Corporation. All Rights Reserved.
* Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved.
*
* This 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 software 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 software; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*/
#ifdef HAVE_DIX_CONFIG_H
#include <dix-config.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pwd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <arpa/inet.h>
#include "windowstr.h"
#include "rfb.h"
#include "sprite.h"
/* #define GII_DEBUG */
char updateBuf[UPDATE_BUF_SIZE];
int ublen;
rfbClientPtr rfbClientHead = NULL;
rfbClientPtr pointerClient = NULL; /* Mutex for pointer events */
Bool rfbAlwaysShared = FALSE;
Bool rfbNeverShared = FALSE;
Bool rfbDontDisconnect = TRUE;
Bool rfbViewOnly = FALSE; /* run server in view only mode - Ehud Karni SW */
Bool rfbSyncCutBuffer = TRUE;
Bool rfbCongestionControl = TRUE;
double rfbAutoLosslessRefresh = 0.0;
int rfbALRQualityLevel = -1;
int rfbALRSubsampLevel = TVNC_1X;
int rfbCombineRect = 100;
int rfbICEBlockSize = 256;
Bool rfbInterframeDebug = FALSE;
int rfbMaxWidth = MAXSHORT, rfbMaxHeight = MAXSHORT;
int rfbMaxClipboard = MAX_CUTTEXT_LEN;
Bool rfbVirtualTablet = FALSE;
Bool rfbMT = TRUE;
int rfbNumThreads = 0;
static rfbClientPtr rfbNewClient(int sock);
static void rfbProcessClientProtocolVersion(rfbClientPtr cl);
static void rfbProcessClientInitMessage(rfbClientPtr cl);
static void rfbSendInteractionCaps(rfbClientPtr cl);
static void rfbProcessClientNormalMessage(rfbClientPtr cl);
static Bool rfbSendCopyRegion(rfbClientPtr cl, RegionPtr reg, int dx, int dy);
static Bool rfbSendLastRectMarker(rfbClientPtr cl);
Bool rfbSendDesktopSize(rfbClientPtr cl);
Bool rfbSendExtDesktopSize(rfbClientPtr cl);
/*
* Session capture
*/
char *captureFile = NULL;
static void WriteCapture(int captureFD, char *buf, int len)
{
if (write(captureFD, buf, len) < len)
rfbLogPerror("WriteCapture: Could not write to capture file");
}
/*
* Idle timeout
*/
CARD32 rfbMaxIdleTimeout = 0;
CARD32 rfbIdleTimeout = 0;
static double idleTimeout = -1.0;
void IdleTimerSet(void)
{
idleTimeout = gettime() + (double)rfbIdleTimeout;
}
static void IdleTimerCancel(void)
{
idleTimeout = -1.0;
}
void IdleTimerCheck(void)
{
if (idleTimeout >= 0.0 && gettime() >= idleTimeout)
FatalError("TurboVNC session has been idle for %u seconds. Exiting.",
(unsigned int)rfbIdleTimeout);
}
/*
* Profiling stuff
*/
static BOOL rfbProfile = FALSE;
static double tUpdate = 0., tStart = -1., tElapsed, mpixels = 0.,
idmpixels = 0.;
static unsigned long iter = 0;
unsigned long long sendBytes = 0;
double gettime(void)
{
struct timeval __tv;
gettimeofday(&__tv, (struct timezone *)NULL);
return (double)__tv.tv_sec + (double)__tv.tv_usec * 0.000001;
}
/*
* Auto Lossless Refresh
*/
static Bool putImageOnly = TRUE, alrCopyRect = TRUE;
static CARD32 alrCallback(OsTimerPtr timer, CARD32 time, pointer arg)
{
RegionRec copyRegionSave, modifiedRegionSave, requestedRegionSave,
ifRegionSave;
rfbClientPtr cl = (rfbClientPtr)arg;
int tightCompressLevelSave, tightQualityLevelSave, copyDXSave, copyDYSave,
tightSubsampLevelSave;
RegionRec tmpRegion;
REGION_INIT(pScreen, &tmpRegion, NullBox, 0);
if (putImageOnly && !cl->firstUpdate)
REGION_INTERSECT(pScreen, &tmpRegion, &cl->alrRegion, &cl->lossyRegion);
else
REGION_COPY(pScreen, &tmpRegion, &cl->lossyRegion);
if (cl->firstUpdate) cl->firstUpdate = FALSE;
if (REGION_NOTEMPTY(pScreen, &tmpRegion)) {
tightCompressLevelSave = cl->tightCompressLevel;
tightQualityLevelSave = cl->tightQualityLevel;
tightSubsampLevelSave = cl->tightSubsampLevel;
copyDXSave = cl->copyDX;
copyDYSave = cl->copyDY;
REGION_INIT(pScreen, ©RegionSave, NullBox, 0);
REGION_COPY(pScreen, ©RegionSave, &cl->copyRegion);
REGION_INIT(pScreen, &modifiedRegionSave, NullBox, 0);
REGION_COPY(pScreen, &modifiedRegionSave, &cl->modifiedRegion);
REGION_INIT(pScreen, &requestedRegionSave, NullBox, 0);
REGION_COPY(pScreen, &requestedRegionSave, &cl->requestedRegion);
REGION_INIT(pScreen, &ifRegionSave, NullBox, 0);
REGION_COPY(pScreen, &ifRegionSave, &cl->ifRegion);
cl->tightCompressLevel = 1;
cl->tightQualityLevel = rfbALRQualityLevel;
cl->tightSubsampLevel = rfbALRSubsampLevel;
cl->copyDX = cl->copyDY = 0;
REGION_EMPTY(pScreen, &cl->copyRegion);
REGION_EMPTY(pScreen, &cl->modifiedRegion);
REGION_UNION(pScreen, &cl->modifiedRegion, &cl->modifiedRegion,
&tmpRegion);
REGION_EMPTY(pScreen, &cl->requestedRegion);
REGION_UNION(pScreen, &cl->requestedRegion, &cl->requestedRegion,
&tmpRegion);
if (cl->compareFB) {
REGION_EMPTY(pScreen, &cl->ifRegion);
REGION_UNION(pScreen, &cl->ifRegion, &cl->ifRegion, &tmpRegion);
}
if (!rfbSendFramebufferUpdate(cl)) return 0;
REGION_EMPTY(pScreen, &cl->lossyRegion);
REGION_EMPTY(pScreen, &cl->alrRegion);
cl->tightCompressLevel = tightCompressLevelSave;
cl->tightQualityLevel = tightQualityLevelSave;
cl->tightSubsampLevel = tightSubsampLevelSave;
cl->copyDX = copyDXSave;
cl->copyDY = copyDYSave;
REGION_COPY(pScreen, &cl->copyRegion, ©RegionSave);
REGION_COPY(pScreen, &cl->modifiedRegion, &modifiedRegionSave);
REGION_COPY(pScreen, &cl->requestedRegion, &requestedRegionSave);
REGION_UNINIT(pScreen, ©RegionSave);
REGION_UNINIT(pScreen, &modifiedRegionSave);
REGION_UNINIT(pScreen, &requestedRegionSave);
if (cl->compareFB) {
REGION_COPY(pScreen, &cl->ifRegion, &ifRegionSave);
REGION_UNINIT(pScreen, &ifRegionSave);
}
}
REGION_UNINIT(pScreen, &tmpRegion);
return 0;
}
static CARD32 updateCallback(OsTimerPtr timer, CARD32 time, pointer arg)
{
rfbClientPtr cl = (rfbClientPtr)arg;
rfbSendFramebufferUpdate(cl);
return 0;
}
/*
* Interframe comparison
*/
int rfbInterframe = -1; /* -1 = auto (determined by compression level) */
Bool InterframeOn(rfbClientPtr cl)
{
if (!cl->compareFB) {
if (!(cl->compareFB =
(char *)malloc(rfbFB.paddedWidthInBytes * rfbFB.height))) {
rfbLogPerror("InterframeOn: couldn't allocate comparison buffer");
return FALSE;
}
memset(cl->compareFB, 0, rfbFB.paddedWidthInBytes * rfbFB.height);
REGION_INIT(pScreen, &cl->ifRegion, NullBox, 0);
cl->firstCompare = TRUE;
rfbLog("Interframe comparison enabled\n");
}
cl->fb = cl->compareFB;
return TRUE;
}
void InterframeOff(rfbClientPtr cl)
{
if (cl->compareFB) {
free(cl->compareFB);
REGION_UNINIT(pScreen, &cl->ifRegion);
rfbLog("Interframe comparison disabled\n");
}
cl->compareFB = NULL;
cl->fb = rfbFB.pfbMemory;
}
/*
* Map of quality levels to provide compatibility with TightVNC/TigerVNC
* clients
*/
static int JPEG_QUAL[10] = {
15, 29, 41, 42, 62, 77, 79, 86, 92, 100
};
static int JPEG_SUBSAMP[10] = {
1, 1, 1, 2, 2, 2, 0, 0, 0, 0
};
/*
* rfbNewClientConnection is called from sockets.c when a new connection
* comes in.
*/
void rfbNewClientConnection(int sock)
{
rfbNewClient(sock);
}
/*
* rfbReverseConnection is called to make an outward connection to a
* "listening" RFB client.
*/
rfbClientPtr rfbReverseConnection(char *host, int port, int id)
{
int sock;
rfbClientPtr cl;
if (rfbAuthDisableRevCon) {
rfbLog("Reverse connections disabled\n");
return (rfbClientPtr)NULL;
}
if ((sock = rfbConnect(host, port)) < 0)
return (rfbClientPtr)NULL;
if (id > 0) {
rfbClientRec cl;
char temps[250];
memset(temps, 0, 250);
snprintf(temps, 250, "ID:%d", id);
rfbLog("UltraVNC Repeater Mode II ID is %d\n", id);
cl.sock = sock;
if (WriteExact(&cl, temps, 250) < 0) {
rfbLogPerror("rfbReverseConnection: write");
rfbCloseSock(sock);
return NULL;
}
}
cl = rfbNewClient(sock);
if (cl)
cl->reverseConnection = TRUE;
return cl;
}
/*
* rfbNewClient is called when a new connection has been made by whatever
* means.
*/
static rfbClientPtr rfbNewClient(int sock)
{
rfbProtocolVersionMsg pv;
rfbClientPtr cl;
BoxRec box;
rfbSockAddr addr;
socklen_t addrlen = sizeof(struct sockaddr_storage);
char addrStr[INET6_ADDRSTRLEN];
char *env = NULL;
int np = sysconf(_SC_NPROCESSORS_CONF);
if (rfbClientHead == NULL)
/* no other clients - make sure we don't think any keys are pressed */
KbdReleaseAllKeys();
cl = (rfbClientPtr)rfbAlloc0(sizeof(rfbClientRec));
if (rfbClientHead == NULL && captureFile) {
cl->captureFD = open(captureFile, O_CREAT | O_EXCL | O_WRONLY,
S_IRUSR | S_IWUSR);
if (cl->captureFD < 0)
rfbLogPerror("Could not open capture file");
else
rfbLog("Opened capture file %s\n", captureFile);
} else
cl->captureFD = -1;
cl->sock = sock;
getpeername(sock, &addr.u.sa, &addrlen);
cl->host = strdup(sockaddr_string(&addr, addrStr, INET6_ADDRSTRLEN));
/* Dispatch client input to rfbProcessClientProtocolVersion(). */
cl->state = RFB_PROTOCOL_VERSION;
cl->preferredEncoding = rfbEncodingTight;
cl->correMaxWidth = 48;
cl->correMaxHeight = 48;
REGION_INIT(pScreen, &cl->copyRegion, NullBox, 0);
box.x1 = box.y1 = 0;
box.x2 = rfbFB.width;
box.y2 = rfbFB.height;
REGION_INIT(pScreen, &cl->modifiedRegion, &box, 0);
REGION_INIT(pScreen, &cl->requestedRegion, NullBox, 0);
cl->deferredUpdateStart = gettime();
cl->format = rfbServerFormat;
cl->translateFn = rfbTranslateNone;
cl->tightCompressLevel = TIGHT_DEFAULT_COMPRESSION;
cl->tightSubsampLevel = TIGHT_DEFAULT_SUBSAMP;
cl->tightQualityLevel = -1;
cl->imageQualityLevel = -1;
cl->next = rfbClientHead;
cl->prev = NULL;
if (rfbClientHead)
rfbClientHead->prev = cl;
rfbClientHead = cl;
rfbResetStats(cl);
cl->zlibCompressLevel = 5;
sprintf(pv, rfbProtocolVersionFormat, 3, 8);
if (WriteExact(cl, pv, sz_rfbProtocolVersionMsg) < 0) {
rfbLogPerror("rfbNewClient: write");
rfbCloseClient(cl);
return NULL;
}
if ((env = getenv("TVNC_PROFILE")) != NULL && !strcmp(env, "1"))
rfbProfile = TRUE;
if ((env = getenv("TVNC_ICEDEBUG")) != NULL && !strcmp(env, "1"))
rfbInterframeDebug = TRUE;
if ((env = getenv("TVNC_ICEBLOCKSIZE")) != NULL) {
int iceBlockSize = atoi(env);
if (iceBlockSize >= 0) rfbICEBlockSize = iceBlockSize;
}
if ((env = getenv("TVNC_COMBINERECT")) != NULL) {
int combine = atoi(env);
if (combine > 0 && combine <= 65000) rfbCombineRect = combine;
}
cl->firstUpdate = TRUE;
/* The TigerVNC Viewer won't enable remote desktop resize until it receives
a desktop resize message from the server, so we give it one with the
first FBU. */
cl->reason = rfbEDSReasonServer;
cl->result = rfbEDSResultSuccess;
if (rfbAutoLosslessRefresh > 0.0) {
REGION_INIT(pScreen, &cl->lossyRegion, NullBox, 0);
if ((env = getenv("TVNC_ALRALL")) != NULL && !strcmp(env, "1"))
putImageOnly = FALSE;
if ((env = getenv("TVNC_ALRCOPYRECT")) != NULL && !strcmp(env, "0"))
alrCopyRect = FALSE;
REGION_INIT(pScreen, &cl->alrRegion, NullBox, 0);
REGION_INIT(pScreen, &cl->alrEligibleRegion, NullBox, 0);
}
if ((env = getenv("TVNC_MT")) != NULL && !strcmp(env, "0"))
rfbMT = FALSE;
if ((env = getenv("TVNC_NTHREADS")) != NULL && strlen(env) >= 1) {
int temp = atoi(env);
if (temp >= 1 && temp <= MAX_ENCODING_THREADS)
rfbNumThreads = temp;
else
rfbLog("WARNING: Invalid value of TVNC_NTHREADS (%s) ignored\n", env);
}
if (np == -1 && rfbMT) {
rfbLog("WARNING: Could not determine CPU count. Multithreaded encoding disabled.\n");
rfbMT = FALSE;
}
if (!rfbMT) rfbNumThreads = 1;
else if (rfbNumThreads < 1) rfbNumThreads = min(np, 4);
if (rfbNumThreads > np) {
rfbLog("NOTICE: Encoding thread count has been clamped to CPU count\n");
rfbNumThreads = np;
}
if (rfbIdleTimeout > 0)
IdleTimerCancel();
cl->baseRTT = cl->minRTT = (unsigned)-1;
gettimeofday(&cl->lastWrite, NULL);
REGION_INIT(pScreen, &cl->cuRegion, NullBox, 0);
if (rfbInterframe == 1) {
if (!InterframeOn(cl)) {
rfbCloseClient(cl);
return NULL;
}
} else
InterframeOff(cl);
return cl;
}
/*
* rfbClientConnectionGone is called from sockets.c just after a connection
* has gone away.
*/
void rfbClientConnectionGone(rfbClientPtr cl)
{
int i;
if (cl->prev)
cl->prev->next = cl->next;
else
rfbClientHead = cl->next;
if (cl->next)
cl->next->prev = cl->prev;
TimerFree(cl->alrTimer);
TimerFree(cl->deferredUpdateTimer);
TimerFree(cl->updateTimer);
TimerFree(cl->congestionTimer);
#ifdef XVNC_AuthPAM
rfbPAMEnd(cl);
#endif
if (cl->login != NULL) {
rfbLog("Client %s (%s) gone\n", cl->login, cl->host);
free(cl->login);
} else {
rfbLog("Client %s gone\n", cl->host);
}
free(cl->host);
ShutdownTightThreads();
if (rfbAutoLosslessRefresh > 0.0) {
REGION_UNINIT(pScreen, &cl->lossyRegion);
REGION_UNINIT(pScreen, &cl->alrRegion);
REGION_UNINIT(pScreen, &cl->alrEligibleRegion);
}
/* Release the compression state structures if any. */
if (cl->compStreamInited == TRUE)
deflateEnd(&(cl->compStream));
for (i = 0; i < 4; i++) {
if (cl->zsActive[i])
deflateEnd(&cl->zsStruct[i]);
}
if (pointerClient == cl)
pointerClient = NULL;
REGION_UNINIT(pScreen, &cl->copyRegion);
REGION_UNINIT(pScreen, &cl->modifiedRegion);
rfbPrintStats(cl);
if (cl->translateLookupTable) free(cl->translateLookupTable);
rfbFreeZrleData(cl);
if (cl->cutText)
free(cl->cutText);
InterframeOff(cl);
i = cl->numDevices;
while (i-- > 0)
RemoveExtInputDevice(cl, 0);
if (cl->captureFD >= 0)
close(cl->captureFD);
free(cl);
if (rfbClientHead == NULL && rfbIdleTimeout > 0)
IdleTimerSet();
}
/*
* rfbProcessClientMessage is called when there is data to read from a client.
*/
void rfbProcessClientMessage(rfbClientPtr cl)
{
rfbCorkSock(cl->sock);
if (cl->pendingSyncFence) {
cl->syncFence = TRUE;
cl->pendingSyncFence = FALSE;
}
switch (cl->state) {
case RFB_PROTOCOL_VERSION:
rfbProcessClientProtocolVersion(cl);
break;
case RFB_SECURITY_TYPE: /* protocol versions 3.7 and above */
rfbProcessClientSecurityType(cl);
break;
case RFB_TUNNELING_TYPE: /* protocol versions 3.7t, 3.8t */
rfbProcessClientTunnelingType(cl);
break;
case RFB_AUTH_TYPE: /* protocol versions 3.7t, 3.8t */
rfbProcessClientAuthType(cl);
break;
#if USETLS
case RFB_TLS_HANDSHAKE:
rfbAuthTLSHandshake(cl);
break;
#endif
case RFB_AUTHENTICATION:
rfbAuthProcessResponse(cl);
break;
case RFB_INITIALISATION:
rfbInitFlowControl(cl);
rfbProcessClientInitMessage(cl);
break;
default:
rfbProcessClientNormalMessage(cl);
}
CHECK_CLIENT_PTR(cl, return)
if (cl->syncFence) {
if (!rfbSendFence(cl, cl->fenceFlags, cl->fenceDataLen, cl->fenceData))
return;
cl->syncFence = FALSE;
}
rfbUncorkSock(cl->sock);
}
/*
* rfbProcessClientProtocolVersion is called when the client sends its
* protocol version.
*/
static void rfbProcessClientProtocolVersion(rfbClientPtr cl)
{
rfbProtocolVersionMsg pv;
int n, major, minor;
if ((n = ReadExact(cl, pv, sz_rfbProtocolVersionMsg)) <= 0) {
if (n == 0)
rfbLog("rfbProcessClientProtocolVersion: client gone\n");
else
rfbLogPerror("rfbProcessClientProtocolVersion: read");
rfbCloseClient(cl);
return;
}
pv[sz_rfbProtocolVersionMsg] = 0;
if (sscanf(pv, rfbProtocolVersionFormat, &major, &minor) != 2) {
rfbLog("rfbProcessClientProtocolVersion: not a valid RFB client\n");
rfbCloseClient(cl);
return;
}
if (major != 3) {
rfbLog("Unsupported protocol version %d.%d\n", major, minor);
rfbCloseClient(cl);
return;
}
/* Always use one of the three standard versions of the RFB protocol. */
cl->protocol_minor_ver = minor;
if (minor > 8) /* buggy client */
cl->protocol_minor_ver = 8;
else if (minor > 3 && minor < 7) /* non-standard client */
cl->protocol_minor_ver = 3;
else if (minor < 3) /* ancient client */
cl->protocol_minor_ver = 3;
if (cl->protocol_minor_ver != minor)
rfbLog("Non-standard protocol version 3.%d, using 3.%d instead\n", minor,
cl->protocol_minor_ver);
else
rfbLog("Using protocol version 3.%d\n", cl->protocol_minor_ver);
/* TightVNC protocol extensions are not enabled yet. */
cl->protocol_tightvnc = FALSE;
rfbAuthNewClient(cl);
}
/*
* rfbProcessClientInitMessage is called when the client sends its
* initialisation message.
*/
static void rfbProcessClientInitMessage(rfbClientPtr cl)
{
rfbClientInitMsg ci;
char buf[256];
rfbServerInitMsg *si = (rfbServerInitMsg *)buf;
int len, n;
rfbClientPtr otherCl, nextCl;
if ((n = ReadExact(cl, (char *)&ci, sz_rfbClientInitMsg)) <= 0) {
if (n == 0)
rfbLog("rfbProcessClientInitMessage: client gone\n");
else
rfbLogPerror("rfbProcessClientInitMessage: read");
rfbCloseClient(cl);
return;
}
si->framebufferWidth = Swap16IfLE(rfbFB.width);
si->framebufferHeight = Swap16IfLE(rfbFB.height);
si->format = rfbServerFormat;
si->format.redMax = Swap16IfLE(si->format.redMax);
si->format.greenMax = Swap16IfLE(si->format.greenMax);
si->format.blueMax = Swap16IfLE(si->format.blueMax);
if (strlen(desktopName) > 128) /* sanity check on desktop name len */
desktopName[128] = 0;
sprintf(buf + sz_rfbServerInitMsg, "%s", desktopName);
len = strlen(buf + sz_rfbServerInitMsg);
si->nameLength = Swap32IfLE(len);
if (WriteExact(cl, buf, sz_rfbServerInitMsg + len) < 0) {
rfbLogPerror("rfbProcessClientInitMessage: write");
rfbCloseClient(cl);
return;
}
if (cl->protocol_tightvnc)
rfbSendInteractionCaps(cl); /* protocol 3.7t */
/* Dispatch client input to rfbProcessClientNormalMessage(). */
cl->state = RFB_NORMAL;
if (!cl->reverseConnection &&
(rfbNeverShared || (!rfbAlwaysShared && !ci.shared))) {
if (rfbDontDisconnect) {
for (otherCl = rfbClientHead; otherCl; otherCl = otherCl->next) {
if ((otherCl != cl) && (otherCl->state == RFB_NORMAL)) {
rfbLog("-dontdisconnect: Not shared & existing client\n");
rfbLog(" refusing new client %s\n", cl->host);
rfbCloseClient(cl);
return;
}
}
} else {
for (otherCl = rfbClientHead; otherCl; otherCl = nextCl) {
nextCl = otherCl->next;
if ((otherCl != cl) && (otherCl->state == RFB_NORMAL)) {
rfbLog("Not shared - closing connection to client %s\n",
otherCl->host);
rfbCloseClient(otherCl);
}
}
}
}
}
/*
* rfbSendInteractionCaps is called after sending the server
* initialisation message, only if TightVNC protocol extensions were
* enabled (protocol versions 3.7t, 3.8t). In this function, we send
* the lists of supported protocol messages and encodings.
*/
/* Update these constants on changing capability lists below! */
#define N_SMSG_CAPS 0
#define N_CMSG_CAPS 0
#define N_ENC_CAPS 17
void rfbSendInteractionCaps(rfbClientPtr cl)
{
rfbInteractionCapsMsg intr_caps;
rfbCapabilityInfo enc_list[N_ENC_CAPS];
int i;
/* Fill in the header structure sent prior to capability lists. */
intr_caps.nServerMessageTypes = Swap16IfLE(N_SMSG_CAPS);
intr_caps.nClientMessageTypes = Swap16IfLE(N_CMSG_CAPS);
intr_caps.nEncodingTypes = Swap16IfLE(N_ENC_CAPS);
intr_caps.pad = 0;
/* Supported server->client message types. */
/* For future file transfer support:
i = 0;
SetCapInfo(&smsg_list[i++], rfbFileListData, rfbTightVncVendor);
SetCapInfo(&smsg_list[i++], rfbFileDownloadData, rfbTightVncVendor);
SetCapInfo(&smsg_list[i++], rfbFileUploadCancel, rfbTightVncVendor);
SetCapInfo(&smsg_list[i++], rfbFileDownloadFailed, rfbTightVncVendor);
if (i != N_SMSG_CAPS) {
rfbLog("rfbSendInteractionCaps: assertion failed, i != N_SMSG_CAPS\n");
rfbCloseClient(cl);
return;
}
*/
/* Supported client->server message types. */
/* For future file transfer support:
i = 0;
SetCapInfo(&cmsg_list[i++], rfbFileListRequest, rfbTightVncVendor);
SetCapInfo(&cmsg_list[i++], rfbFileDownloadRequest, rfbTightVncVendor);
SetCapInfo(&cmsg_list[i++], rfbFileUploadRequest, rfbTightVncVendor);
SetCapInfo(&cmsg_list[i++], rfbFileUploadData, rfbTightVncVendor);
SetCapInfo(&cmsg_list[i++], rfbFileDownloadCancel, rfbTightVncVendor);
SetCapInfo(&cmsg_list[i++], rfbFileUploadFailed, rfbTightVncVendor);
if (i != N_CMSG_CAPS) {
rfbLog("rfbSendInteractionCaps: assertion failed, i != N_CMSG_CAPS\n");
rfbCloseClient(cl);
return;
}
*/
/* Encoding types. */
i = 0;
SetCapInfo(&enc_list[i++], rfbEncodingCopyRect, rfbStandardVendor);
SetCapInfo(&enc_list[i++], rfbEncodingRRE, rfbStandardVendor);
SetCapInfo(&enc_list[i++], rfbEncodingCoRRE, rfbStandardVendor);
SetCapInfo(&enc_list[i++], rfbEncodingHextile, rfbStandardVendor);
SetCapInfo(&enc_list[i++], rfbEncodingZlib, rfbTridiaVncVendor);
SetCapInfo(&enc_list[i++], rfbEncodingZRLE, rfbTridiaVncVendor);
SetCapInfo(&enc_list[i++], rfbEncodingZYWRLE, rfbTridiaVncVendor);
SetCapInfo(&enc_list[i++], rfbEncodingTight, rfbTightVncVendor);
SetCapInfo(&enc_list[i++], rfbEncodingCompressLevel0, rfbTightVncVendor);
SetCapInfo(&enc_list[i++], rfbEncodingQualityLevel0, rfbTightVncVendor);
SetCapInfo(&enc_list[i++], rfbEncodingFineQualityLevel0, rfbTurboVncVendor);
SetCapInfo(&enc_list[i++], rfbEncodingSubsamp1X, rfbTurboVncVendor);
SetCapInfo(&enc_list[i++], rfbEncodingXCursor, rfbTightVncVendor);
SetCapInfo(&enc_list[i++], rfbEncodingRichCursor, rfbTightVncVendor);
SetCapInfo(&enc_list[i++], rfbEncodingPointerPos, rfbTightVncVendor);
SetCapInfo(&enc_list[i++], rfbEncodingLastRect, rfbTightVncVendor);
SetCapInfo(&enc_list[i++], rfbGIIServer, rfbGIIVendor);
if (i != N_ENC_CAPS) {
rfbLog("rfbSendInteractionCaps: assertion failed, i != N_ENC_CAPS\n");
rfbCloseClient(cl);
return;
}
/* Send header and capability lists */
if (WriteExact(cl, (char *)&intr_caps,
sz_rfbInteractionCapsMsg) < 0 ||
WriteExact(cl, (char *)&enc_list[0],
sz_rfbCapabilityInfo * N_ENC_CAPS) < 0) {
rfbLogPerror("rfbSendInteractionCaps: write");
rfbCloseClient(cl);
return;
}
/* Dispatch client input to rfbProcessClientNormalMessage(). */
cl->state = RFB_NORMAL;
}
/*
* rfbProcessClientNormalMessage is called when the client has sent a normal
* protocol message.
*/
#define READ(addr, numBytes) \
if ((n = ReadExact(cl, addr, numBytes)) <= 0) { \
if (n != 0) \
rfbLogPerror("rfbProcessClientNormalMessage: read"); \
rfbCloseClient(cl); \
return; \
}
#define SKIP(numBytes) \
if ((n = SkipExact(cl, numBytes)) <= 0) { \
if (n != 0) \
rfbLogPerror("rfbProcessClientNormalMessage: skip"); \
rfbCloseClient(cl); \
return; \
}
static void rfbProcessClientNormalMessage(rfbClientPtr cl)
{
int n;
rfbClientToServerMsg msg;
char *str;
READ((char *)&msg, 1)
switch (msg.type) {
case rfbSetPixelFormat:
READ(((char *)&msg) + 1, sz_rfbSetPixelFormatMsg - 1)
cl->format.bitsPerPixel = msg.spf.format.bitsPerPixel;
cl->format.depth = msg.spf.format.depth;
cl->format.bigEndian = (msg.spf.format.bigEndian ? 1 : 0);
cl->format.trueColour = (msg.spf.format.trueColour ? 1 : 0);
cl->format.redMax = Swap16IfLE(msg.spf.format.redMax);
cl->format.greenMax = Swap16IfLE(msg.spf.format.greenMax);
cl->format.blueMax = Swap16IfLE(msg.spf.format.blueMax);
cl->format.redShift = msg.spf.format.redShift;
cl->format.greenShift = msg.spf.format.greenShift;
cl->format.blueShift = msg.spf.format.blueShift;
cl->readyForSetColourMapEntries = TRUE;
rfbSetTranslateFunction(cl);
return;
case rfbFixColourMapEntries:
READ(((char *)&msg) + 1, sz_rfbFixColourMapEntriesMsg - 1)
rfbLog("rfbProcessClientNormalMessage: FixColourMapEntries unsupported\n");
rfbCloseClient(cl);
return;
case rfbSetEncodings:
{
int i;
CARD32 enc;
Bool firstFence = !cl->enableFence;
Bool firstCU = !cl->enableCU;
Bool firstGII = !cl->enableGII;
Bool logTightCompressLevel = FALSE;
READ(((char *)&msg) + 1, sz_rfbSetEncodingsMsg - 1)
msg.se.nEncodings = Swap16IfLE(msg.se.nEncodings);
cl->preferredEncoding = -1;
cl->useCopyRect = FALSE;
cl->enableCursorShapeUpdates = FALSE;
cl->enableCursorPosUpdates = FALSE;
cl->enableLastRectEncoding = FALSE;
cl->tightCompressLevel = TIGHT_DEFAULT_COMPRESSION;
cl->tightSubsampLevel = TIGHT_DEFAULT_SUBSAMP;
cl->tightQualityLevel = -1;
cl->imageQualityLevel = -1;
for (i = 0; i < msg.se.nEncodings; i++) {
READ((char *)&enc, 4)
enc = Swap32IfLE(enc);
switch (enc) {
case rfbEncodingCopyRect:
cl->useCopyRect = TRUE;
break;
case rfbEncodingRaw:
if (cl->preferredEncoding == -1) {
cl->preferredEncoding = enc;
rfbLog("Using raw encoding for client %s\n", cl->host);
}
break;
case rfbEncodingRRE:
if (cl->preferredEncoding == -1) {
cl->preferredEncoding = enc;
rfbLog("Using rre encoding for client %s\n", cl->host);
}
break;
case rfbEncodingCoRRE:
if (cl->preferredEncoding == -1) {
cl->preferredEncoding = enc;
rfbLog("Using CoRRE encoding for client %s\n", cl->host);
}
break;
case rfbEncodingHextile:
if (cl->preferredEncoding == -1) {
cl->preferredEncoding = enc;
rfbLog("Using hextile encoding for client %s\n", cl->host);
}
break;
case rfbEncodingZlib:
if (cl->preferredEncoding == -1) {
cl->preferredEncoding = enc;
rfbLog("Using zlib encoding for client %s\n", cl->host);
}
break;
case rfbEncodingZRLE:
if (cl->preferredEncoding == -1) {
cl->preferredEncoding = enc;
rfbLog("Using ZRLE encoding for client %s\n", cl->host);
}
break;
case rfbEncodingZYWRLE:
if (cl->preferredEncoding == -1) {
cl->preferredEncoding = enc;
rfbLog("Using ZYWRLE encoding for client %s\n", cl->host);
}
break;
case rfbEncodingTight:
if (cl->preferredEncoding == -1) {
cl->preferredEncoding = enc;
rfbLog("Using tight encoding for client %s\n", cl->host);
}
break;
case rfbEncodingXCursor:
if (!cl->enableCursorShapeUpdates) {
rfbLog("Enabling X-style cursor updates for client %s\n",
cl->host);
cl->enableCursorShapeUpdates = TRUE;
cl->useRichCursorEncoding = FALSE;
cl->cursorWasChanged = TRUE;
}
break;
case rfbEncodingRichCursor:
if (!cl->enableCursorShapeUpdates) {
rfbLog("Enabling full-color cursor updates for client %s\n",
cl->host);
cl->enableCursorShapeUpdates = TRUE;
cl->useRichCursorEncoding = TRUE;
cl->cursorWasChanged = TRUE;
}
break;
case rfbEncodingPointerPos:
if (!cl->enableCursorPosUpdates) {
rfbLog("Enabling cursor position updates for client %s\n",
cl->host);
cl->enableCursorPosUpdates = TRUE;
cl->cursorWasMoved = TRUE;
cl->cursorX = -1;
cl->cursorY = -1;
}
break;
case rfbEncodingLastRect:
if (!cl->enableLastRectEncoding) {
rfbLog("Enabling LastRect protocol extension for client %s\n",
cl->host);
cl->enableLastRectEncoding = TRUE;
}
break;
case rfbEncodingFence:
if (!cl->enableFence) {
rfbLog("Enabling Fence protocol extension for client %s\n",
cl->host);
cl->enableFence = TRUE;
}
break;
case rfbEncodingContinuousUpdates:
if (!cl->enableCU) {
rfbLog("Enabling Continuous Updates protocol extension for client %s\n",
cl->host);
cl->enableCU = TRUE;
}
break;
case rfbEncodingNewFBSize:
if (!cl->enableDesktopSize) {
if (!rfbAuthDisableRemoteResize) {
rfbLog("Enabling Desktop Size protocol extension for client %s\n",
cl->host);
cl->enableDesktopSize = TRUE;
} else
rfbLog("WARNING: Remote desktop resizing disabled per system policy.\n");
}
break;
case rfbEncodingExtendedDesktopSize:
if (!cl->enableExtDesktopSize) {
if (!rfbAuthDisableRemoteResize) {
rfbLog("Enabling Extended Desktop Size protocol extension for client %s\n",
cl->host);
cl->enableExtDesktopSize = TRUE;
} else
rfbLog("WARNING: Remote desktop resizing disabled per system policy.\n");
}
break;
case rfbEncodingGII:
if (!cl->enableGII) {
rfbLog("Enabling GII extension for client %s\n", cl->host);
cl->enableGII = TRUE;
}
break;
default:
if (enc >= (CARD32)rfbEncodingCompressLevel0 &&
enc <= (CARD32)rfbEncodingCompressLevel9) {
cl->zlibCompressLevel = enc & 0x0F;
cl->tightCompressLevel = enc & 0x0F;
if (cl->preferredEncoding == rfbEncodingTight)
logTightCompressLevel = TRUE;
else
rfbLog("Using compression level %d for client %s\n",
cl->tightCompressLevel, cl->host);
if (rfbInterframe == -1) {
if (cl->tightCompressLevel >= 5) {
if (!InterframeOn(cl)) {
rfbCloseClient(cl);
return;
}
} else
InterframeOff(cl);
}
} else if (enc >= (CARD32)rfbEncodingSubsamp1X &&
enc <= (CARD32)rfbEncodingSubsampGray) {
cl->tightSubsampLevel = enc & 0xFF;
rfbLog("Using JPEG subsampling %d for client %s\n",
cl->tightSubsampLevel, cl->host);
} else if (enc >= (CARD32)rfbEncodingQualityLevel0 &&
enc <= (CARD32)rfbEncodingQualityLevel9) {
cl->tightQualityLevel = JPEG_QUAL[enc & 0x0F];
cl->tightSubsampLevel = JPEG_SUBSAMP[enc & 0x0F];
cl->imageQualityLevel = enc & 0x0F;
if (cl->preferredEncoding == rfbEncodingTight)
rfbLog("Using JPEG subsampling %d, Q%d for client %s\n",
cl->tightSubsampLevel, cl->tightQualityLevel, cl->host);
else
rfbLog("Using image quality level %d for client %s\n",
cl->imageQualityLevel, cl->host);
} else if (enc >= (CARD32)rfbEncodingFineQualityLevel0 + 1 &&
enc <= (CARD32)rfbEncodingFineQualityLevel100) {
cl->tightQualityLevel = enc & 0xFF;
rfbLog("Using JPEG quality %d for client %s\n",
cl->tightQualityLevel, cl->host);
} else {
rfbLog("rfbProcessClientNormalMessage: ignoring unknown encoding %d (%x)\n",
(int)enc, (int)enc);
}
} /* switch (enc) */
} /* for (i = 0; i < msg.se.nEncodings; i++) */
if (cl->preferredEncoding == -1)
cl->preferredEncoding = rfbEncodingTight;
if (cl->preferredEncoding == rfbEncodingTight && logTightCompressLevel)
rfbLog("Using Tight compression level %d for client %s\n",
rfbTightCompressLevel(cl), cl->host);
if (cl->enableCursorPosUpdates && !cl->enableCursorShapeUpdates) {
rfbLog("Disabling cursor position updates for client %s\n", cl->host);
cl->enableCursorPosUpdates = FALSE;
}
if (cl->enableFence && firstFence) {
if (!rfbSendFence(cl, rfbFenceFlagRequest, 0, NULL))
return;
}
if (cl->enableCU && cl->enableFence && firstCU) {
if (!rfbSendEndOfCU(cl))
return;
}
if (cl->enableGII && firstGII) {
/* Send GII server version message to all clients */
rfbGIIServerVersionMsg msg;
msg.type = rfbGIIServer;
/* We always send as big endian to make things easier on the Java
viewer. */
msg.endianAndSubType = rfbGIIVersion | rfbGIIBE;
msg.length = Swap16IfLE(sz_rfbGIIServerVersionMsg - 4);
msg.maximumVersion = msg.minimumVersion = Swap16IfLE(1);
if (WriteExact(cl, (char *)&msg, sz_rfbGIIServerVersionMsg) < 0) {
rfbLogPerror("rfbProcessClientNormalMessage: write");
rfbCloseClient(cl);
return;
}
}
return;
} /* rfbSetEncodings */
case rfbFramebufferUpdateRequest:
{
RegionRec tmpRegion;
BoxRec box;
READ(((char *)&msg) + 1, sz_rfbFramebufferUpdateRequestMsg - 1)
box.x1 = Swap16IfLE(msg.fur.x);
box.y1 = Swap16IfLE(msg.fur.y);
box.x2 = box.x1 + Swap16IfLE(msg.fur.w);
box.y2 = box.y1 + Swap16IfLE(msg.fur.h);
SAFE_REGION_INIT(pScreen, &tmpRegion, &box, 0);
if (!msg.fur.incremental || !cl->continuousUpdates)
REGION_UNION(pScreen, &cl->requestedRegion, &cl->requestedRegion,
&tmpRegion);
if (!cl->readyForSetColourMapEntries) {
/* client hasn't sent a SetPixelFormat so is using server's */
cl->readyForSetColourMapEntries = TRUE;
if (!cl->format.trueColour) {
if (!rfbSetClientColourMap(cl, 0, 0)) {
REGION_UNINIT(pScreen, &tmpRegion);
return;
}
}
}
if (!msg.fur.incremental) {
REGION_UNION(pScreen, &cl->modifiedRegion, &cl->modifiedRegion,
&tmpRegion);
REGION_SUBTRACT(pScreen, &cl->copyRegion, &cl->copyRegion, &tmpRegion);
REGION_UNION(pScreen, &cl->ifRegion, &cl->ifRegion, &tmpRegion);
cl->pendingExtDesktopResize = TRUE;
}
if (FB_UPDATE_PENDING(cl) &&
(!cl->deferredUpdateScheduled || rfbDeferUpdateTime == 0 ||
gettime() - cl->deferredUpdateStart >=
(double)rfbDeferUpdateTime)) {
if (rfbSendFramebufferUpdate(cl))
cl->deferredUpdateScheduled = FALSE;
}
REGION_UNINIT(pScreen, &tmpRegion);
return;
}
case rfbKeyEvent:
cl->rfbKeyEventsRcvd++;
READ(((char *)&msg) + 1, sz_rfbKeyEventMsg - 1)
if (!rfbViewOnly && !cl->viewOnly)
KeyEvent((KeySym)Swap32IfLE(msg.ke.key), msg.ke.down);
return;
case rfbPointerEvent:
cl->rfbPointerEventsRcvd++;
READ(((char *)&msg) + 1, sz_rfbPointerEventMsg - 1)
if (pointerClient && (pointerClient != cl))
return;
if (msg.pe.buttonMask == 0)
pointerClient = NULL;
else
pointerClient = cl;
if (!rfbViewOnly && !cl->viewOnly) {
cl->cursorX = (int)Swap16IfLE(msg.pe.x);
cl->cursorY = (int)Swap16IfLE(msg.pe.y);
PtrAddEvent(msg.pe.buttonMask, cl->cursorX, cl->cursorY, cl);
}
return;
case rfbClientCutText:
{
int ignoredBytes = 0;
READ(((char *)&msg) + 1, sz_rfbClientCutTextMsg - 1)
msg.cct.length = Swap32IfLE(msg.cct.length);
if (msg.cct.length > rfbMaxClipboard) {
rfbLog("Truncating %d-byte clipboard update to %d bytes.\n",
msg.cct.length, rfbMaxClipboard);
ignoredBytes = msg.cct.length - rfbMaxClipboard;
msg.cct.length = rfbMaxClipboard;
}
if (msg.cct.length <= 0) return;
str = (char *)malloc(msg.cct.length);
if (str == NULL) {
rfbLogPerror("rfbProcessClientNormalMessage: rfbClientCutText out of memory");
rfbCloseClient(cl);
return;
}
if ((n = ReadExact(cl, str, msg.cct.length)) <= 0) {
if (n != 0)
rfbLogPerror("rfbProcessClientNormalMessage: read");
free(str);
rfbCloseClient(cl);
return;
}
if (ignoredBytes > 0) {
if ((n = SkipExact(cl, ignoredBytes)) <= 0) {
if (n != 0)
rfbLogPerror("rfbProcessClientNormalMessage: read");
free(str);
rfbCloseClient(cl);
return;
}
}
/* NOTE: We do not accept cut text from a view-only client */
if (!rfbViewOnly && !cl->viewOnly && !rfbAuthDisableCBRecv) {
vncClientCutText(str, msg.cct.length);
if (rfbSyncCutBuffer) rfbSetXCutText(str, msg.cct.length);
}
free(str);
return;
}
case rfbEnableContinuousUpdates:
{
BoxRec box;
READ(((char *)&msg) + 1, sz_rfbEnableContinuousUpdatesMsg - 1)
if (!cl->enableFence || !cl->enableCU) {
rfbLog("Ignoring request to enable continuous updates because the client does not\n");
rfbLog("support the flow control extensions.\n");
return;
}
box.x1 = Swap16IfLE(msg.ecu.x);
box.y1 = Swap16IfLE(msg.ecu.y);
box.x2 = box.x1 + Swap16IfLE(msg.ecu.w);
box.y2 = box.y1 + Swap16IfLE(msg.ecu.h);
SAFE_REGION_INIT(pScreen, &cl->cuRegion, &box, 0);
cl->continuousUpdates = msg.ecu.enable;
if (cl->continuousUpdates) {
REGION_EMPTY(pScreen, &cl->requestedRegion);
if (!rfbSendFramebufferUpdate(cl))
return;
} else {
if (!rfbSendEndOfCU(cl))
return;
}
rfbLog("Continuous updates %s\n",
cl->continuousUpdates ? "enabled" : "disabled");
return;
}
case rfbFence:
{
CARD32 flags;
char data[64];
READ(((char *)&msg) + 1, sz_rfbFenceMsg - 1)
flags = Swap32IfLE(msg.f.flags);
READ(data, msg.f.length)
if (msg.f.length > sizeof(data))
rfbLog("Ignoring fence. Payload of %d bytes is too large.\n",
msg.f.length);
else
HandleFence(cl, flags, msg.f.length, data);
return;
}
#define EDSERROR(format, args...) { \
if (!strlen(errMsg)) \
snprintf(errMsg, 256, "Desktop resize ERROR: "format"\n", args); \
result = rfbEDSResultInvalid; \
}
case rfbSetDesktopSize:
{
int i;
struct xorg_list newScreens;
rfbClientPtr cl2;
int result = rfbEDSResultSuccess;
char errMsg[256] = "\0";
ScreenPtr pScreen = screenInfo.screens[0];
READ(((char *)&msg) + 1, sz_rfbSetDesktopSizeMsg - 1)
if (msg.sds.numScreens < 1)
EDSERROR("Requested number of screens %d is invalid",
msg.sds.numScreens);
msg.sds.w = Swap16IfLE(msg.sds.w);
msg.sds.h = Swap16IfLE(msg.sds.h);
if (msg.sds.w < 1 || msg.sds.h < 1)
EDSERROR("Requested framebuffer dimensions %dx%d are invalid",
msg.sds.w, msg.sds.h);
xorg_list_init(&newScreens);
for (i = 0; i < msg.sds.numScreens; i++) {
rfbScreenInfo *screen = rfbNewScreen(0, 0, 0, 0, 0, 0);
READ((char *)&screen->s, sizeof(rfbScreenDesc))
screen->s.id = Swap32IfLE(screen->s.id);
screen->s.x = Swap16IfLE(screen->s.x);
screen->s.y = Swap16IfLE(screen->s.y);
screen->s.w = Swap16IfLE(screen->s.w);
screen->s.h = Swap16IfLE(screen->s.h);
screen->s.flags = Swap32IfLE(screen->s.flags);
if (screen->s.w < 1 || screen->s.h < 1)
EDSERROR("Screen 0x%.8x requested dimensions %dx%d are invalid",
(unsigned int)screen->s.id, screen->s.w, screen->s.h);
if (screen->s.x >= msg.sds.w || screen->s.y >= msg.sds.h ||
screen->s.x + screen->s.w > msg.sds.w ||
screen->s.y + screen->s.h > msg.sds.h)
EDSERROR("Screen 0x%.8x requested geometry %dx%d+%d+%d exceeds requested framebuffer dimensions",
(unsigned int)screen->s.id, screen->s.w, screen->s.h,
screen->s.x, screen->s.y);
if (rfbFindScreenID(&newScreens, screen->s.id)) {
EDSERROR("Screen 0x%.8x duplicate ID", (unsigned int)screen->s.id);
free(screen);
} else
rfbAddScreen(&newScreens, screen);
}
if (cl->viewOnly) {
rfbLog("NOTICE: Ignoring remote desktop resize request from a view-only client.\n");
result = rfbEDSResultProhibited;
} else if (result == rfbEDSResultSuccess) {
result = ResizeDesktop(pScreen, cl, msg.sds.w, msg.sds.h, &newScreens);
if (result == rfbEDSResultSuccess)
return;
} else
rfbLog(errMsg);
rfbRemoveScreens(&newScreens);
/* Send back the error only to the requesting client. This loop is
necessary because the client may have been shut down as a result of
an error in ResizeDesktop(). */
for (cl2 = rfbClientHead; cl2; cl2 = cl2->next) {
if (cl2 == cl) {
cl2->pendingExtDesktopResize = TRUE;
cl2->reason = rfbEDSReasonClient;
cl2->result = result;
rfbSendFramebufferUpdate(cl2);
break;
}
}
return;
}
case rfbGIIClient:
{
CARD8 endianAndSubType, littleEndian, subType;
READ((char *)&endianAndSubType, 1);
littleEndian = (endianAndSubType & rfbGIIBE) ? 0 : 1;
subType = endianAndSubType & ~rfbGIIBE;
switch (subType) {
case rfbGIIVersion:
READ((char *)&msg.giicv.length, sz_rfbGIIClientVersionMsg - 2);
if (littleEndian != *(const char *)&rfbEndianTest) {
msg.giicv.length = Swap16(msg.giicv.length);
msg.giicv.version = Swap16(msg.giicv.version);
}
if (msg.giicv.length != sz_rfbGIIClientVersionMsg - 4 ||
msg.giicv.version < 1) {
rfbLog("ERROR: Malformed GII client version message\n");
rfbCloseClient(cl);
return;
}
rfbLog("Client supports GII version %d\n", msg.giicv.version);
break;
case rfbGIIDeviceCreate:
{
int i;
rfbDevInfo dev;
rfbGIIDeviceCreatedMsg dcmsg;
memset(&dev, 0, sizeof(dev));
dcmsg.deviceOrigin = 0;
READ((char *)&msg.giidc.length, sz_rfbGIIDeviceCreateMsg - 2);
if (littleEndian != *(const char *)&rfbEndianTest) {
msg.giidc.length = Swap16(msg.giidc.length);
msg.giidc.vendorID = Swap32(msg.giidc.vendorID);
msg.giidc.productID = Swap32(msg.giidc.productID);
msg.giidc.canGenerate = Swap32(msg.giidc.canGenerate);
msg.giidc.numRegisters = Swap32(msg.giidc.numRegisters);
msg.giidc.numValuators = Swap32(msg.giidc.numValuators);
msg.giidc.numButtons = Swap32(msg.giidc.numButtons);
}
rfbLog("GII Device Create: %s\n", msg.giidc.deviceName);
#ifdef GII_DEBUG
rfbLog(" Vendor ID: %d\n", msg.giidc.vendorID);
rfbLog(" Product ID: %d\n", msg.giidc.productID);
rfbLog(" Event mask: %.8x\n", msg.giidc.canGenerate);
rfbLog(" Registers: %d\n", msg.giidc.numRegisters);
rfbLog(" Valuators: %d\n", msg.giidc.numValuators);
rfbLog(" Buttons: %d\n", msg.giidc.numButtons);
#endif
if (msg.giidc.length != sz_rfbGIIDeviceCreateMsg - 4 +
msg.giidc.numValuators * sz_rfbGIIValuator) {
rfbLog("ERROR: Malformed GII device create message\n");
rfbCloseClient(cl);
return;
}
if (msg.giidc.numButtons > MAX_BUTTONS) {
rfbLog("GII device create ERROR: %d buttons exceeds max of %d\n",
msg.giidc.numButtons, MAX_BUTTONS);
SKIP(msg.giidc.numValuators * sz_rfbGIIValuator);
goto sendMessage;
}
if (msg.giidc.numValuators > MAX_VALUATORS) {
rfbLog("GII device create ERROR: %d valuators exceeds max of %d\n",
msg.giidc.numValuators, MAX_VALUATORS);
SKIP(msg.giidc.numValuators * sz_rfbGIIValuator);
goto sendMessage;
}
memcpy(&dev.name, msg.giidc.deviceName, 32);
dev.numButtons = msg.giidc.numButtons;
dev.numValuators = msg.giidc.numValuators;
dev.eventMask = msg.giidc.canGenerate;
dev.mode =
(dev.eventMask & rfbGIIValuatorAbsoluteMask) ? Absolute : Relative;
dev.productID = msg.giidc.productID;
if (dev.mode == Relative) {
rfbLog("GII device create ERROR: relative valuators not supported (yet)\n");
SKIP(msg.giidc.numValuators * sz_rfbGIIValuator);
goto sendMessage;
}
for (i = 0; i < dev.numValuators; i++) {
rfbGIIValuator *v = &dev.valuators[i];
READ((char *)v, sz_rfbGIIValuator);
if (littleEndian != *(const char *)&rfbEndianTest) {
v->index = Swap32(v->index);
v->rangeMin = Swap32((CARD32)v->rangeMin);
v->rangeCenter = Swap32((CARD32)v->rangeCenter);
v->rangeMax = Swap32((CARD32)v->rangeMax);
v->siUnit = Swap32(v->siUnit);
v->siAdd = Swap32((CARD32)v->siAdd);
v->siMul = Swap32((CARD32)v->siMul);
v->siDiv = Swap32((CARD32)v->siDiv);
v->siShift = Swap32((CARD32)v->siShift);
}
#ifdef GII_DEBUG
rfbLog(" Valuator: %s (%s)\n", v->longName, v->shortName);
rfbLog(" Index: %d\n", v->index);
rfbLog(" Range: min = %d, center = %d, max = %d\n",
v->rangeMin, v->rangeCenter, v->rangeMax);
rfbLog(" SI unit: %d\n", v->siUnit);
rfbLog(" SI add: %d\n", v->siAdd);
rfbLog(" SI multiply: %d\n", v->siMul);
rfbLog(" SI divide: %d\n", v->siDiv);
rfbLog(" SI shift: %d\n", v->siShift);
#endif
}
for (i = 0; i < cl->numDevices; i++) {
if (!strcmp(dev.name, cl->devices[i].name)) {
rfbLog("Device \'%s\' already exists with GII device ID %d\n",
dev.name, i + 1);
dcmsg.deviceOrigin = Swap32IfLE(i + 1);
goto sendMessage;
}
}
if (rfbVirtualTablet || AddExtInputDevice(&dev)) {
memcpy(&cl->devices[cl->numDevices], &dev, sizeof(dev));
cl->numDevices++;
dcmsg.deviceOrigin = Swap32IfLE(cl->numDevices);
}
rfbLog("GII device ID = %d\n", cl->numDevices);
sendMessage:
/* Send back a GII device created message */
dcmsg.type = rfbGIIServer;
/* We always send as big endian to make things easier on the Java
viewer. */
dcmsg.endianAndSubType = rfbGIIDeviceCreate | rfbGIIBE;
dcmsg.length = Swap16IfLE(sz_rfbGIIDeviceCreatedMsg - 4);
if (WriteExact(cl, (char *)&dcmsg, sz_rfbGIIDeviceCreatedMsg) < 0) {
rfbLogPerror("rfbProcessClientNormalMessage: write");
rfbCloseClient(cl);
return;
}
break;
}
case rfbGIIDeviceDestroy:
READ((char *)&msg.giidd.length, sz_rfbGIIDeviceDestroyMsg - 2);
if (littleEndian != *(const char *)&rfbEndianTest) {
msg.giidd.length = Swap16(msg.giidd.length);
msg.giidd.deviceOrigin = Swap32(msg.giidd.deviceOrigin);
}
if (msg.giidd.length != sz_rfbGIIDeviceDestroyMsg - 4) {
rfbLog("ERROR: Malformed GII device create message\n");
rfbCloseClient(cl);
return;
}
RemoveExtInputDevice(cl, msg.giidd.deviceOrigin - 1);
break;
case rfbGIIEvent:
{
CARD16 length;
READ((char *)&length, sizeof(CARD16));
if (littleEndian != *(const char *)&rfbEndianTest)
length = Swap16(length);
while (length > 0) {
CARD8 eventSize, eventType;
READ((char *)&eventSize, 1);
READ((char *)&eventType, 1);
switch (eventType) {
case rfbGIIButtonPress:
case rfbGIIButtonRelease:
{
rfbGIIButtonEvent b;
rfbDevInfo *dev;
READ((char *)&b.pad, sz_rfbGIIButtonEvent - 2);
if (littleEndian != *(const char *)&rfbEndianTest) {
b.deviceOrigin = Swap32(b.deviceOrigin);
b.buttonNumber = Swap32(b.buttonNumber);
}
if (eventSize != sz_rfbGIIButtonEvent || b.deviceOrigin <= 0 ||
b.buttonNumber < 1) {
rfbLog("ERROR: Malformed GII button event\n");
rfbCloseClient(cl);
return;
}
if (eventSize > length) {
rfbLog("ERROR: Malformed GII event message\n");
rfbCloseClient(cl);
return;
}
length -= eventSize;
if (b.deviceOrigin < 1 || b.deviceOrigin > cl->numDevices) {
rfbLog("ERROR: GII button event from non-existent device %d\n",
b.deviceOrigin);
rfbCloseClient(cl);
return;
}
dev = &cl->devices[b.deviceOrigin - 1];
if ((eventType == rfbGIIButtonPress &&
(dev->eventMask & rfbGIIButtonPressMask) == 0) ||
(eventType == rfbGIIButtonRelease &&
(dev->eventMask & rfbGIIButtonReleaseMask) == 0)) {
rfbLog("ERROR: Device %d can't generate GII button events\n",
b.deviceOrigin);
rfbCloseClient(cl);
return;
}
if (b.buttonNumber > dev->numButtons) {
rfbLog("ERROR: GII button %d event for device %d exceeds button count (%d)\n",
b.buttonNumber, b.deviceOrigin, dev->numButtons);
rfbCloseClient(cl);
return;
}
#ifdef GII_DEBUG
rfbLog("Device %d button %d %s\n", b.deviceOrigin,
b.buttonNumber,
eventType == rfbGIIButtonPress ? "PRESS" : "release");
fflush(stderr);
#endif
ExtInputAddEvent(dev, eventType == rfbGIIButtonPress ?
ButtonPress : ButtonRelease, b.buttonNumber);
break;
}
case rfbGIIValuatorRelative:
case rfbGIIValuatorAbsolute:
{
rfbGIIValuatorEvent v;
int i;
rfbDevInfo *dev;
READ((char *)&v.pad, sz_rfbGIIValuatorEvent - 2);
if (littleEndian != *(const char *)&rfbEndianTest) {
v.deviceOrigin = Swap32(v.deviceOrigin);
v.first = Swap32(v.first);
v.count = Swap32(v.count);
}
if (eventSize !=
sz_rfbGIIValuatorEvent + sizeof(int) * v.count) {
rfbLog("ERROR: Malformed GII valuator event\n");
rfbCloseClient(cl);
return;
}
if (eventSize > length) {
rfbLog("ERROR: Malformed GII event message\n");
rfbCloseClient(cl);
return;
}
length -= eventSize;
if (v.deviceOrigin < 1 || v.deviceOrigin > cl->numDevices) {
rfbLog("ERROR: GII valuator event from non-existent device %d\n",
v.deviceOrigin);
rfbCloseClient(cl);
return;
}
dev = &cl->devices[v.deviceOrigin - 1];
if ((eventType == rfbGIIValuatorRelative &&
(dev->eventMask & rfbGIIValuatorRelativeMask) == 0) ||
(eventType == rfbGIIValuatorAbsolute &&
(dev->eventMask & rfbGIIValuatorAbsoluteMask) == 0)) {
rfbLog("ERROR: Device %d cannot generate GII valuator events\n",
v.deviceOrigin);
rfbCloseClient(cl);
return;
}
if (v.first + v.count > dev->numValuators) {
rfbLog("ERROR: GII valuator event for device %d exceeds valuator count (%d)\n",
v.deviceOrigin, dev->numValuators);
rfbCloseClient(cl);
return;
}
#ifdef GII_DEBUG
rfbLog("Device %d Valuator %s first=%d count=%d:\n",
v.deviceOrigin,
eventType == rfbGIIValuatorRelative ? "rel" : "ABS",
v.first, v.count);
#endif
for (i = v.first; i < v.first + v.count; i++) {
READ((char *)&dev->values[i], sizeof(int));
if (littleEndian != *(const char *)&rfbEndianTest)
dev->values[i] = Swap32((CARD32)dev->values[i]);
#ifdef GII_DEBUG
fprintf(stderr, "v[%d]=%d ", i, dev->values[i]);
#endif
}
#ifdef GII_DEBUG
fprintf(stderr, "\n");
#endif
if (v.count > 0) {
dev->valFirst = v.first;
dev->valCount = v.count;
dev->mode = eventType == rfbGIIValuatorAbsolute ?
Absolute : Relative;
ExtInputAddEvent(dev, MotionNotify, 0);
}
break;
}
default:
rfbLog("ERROR: This server cannot handle GII event type %d\n",
eventType);
rfbCloseClient(cl);
return;
} /* switch (eventType) */
} /* while (length > 0) */
if (length != 0) {
rfbLog("ERROR: Malformed GII event message\n");
rfbCloseClient(cl);
return;
}
break;
} /* rfbGIIEvent */
} /* switch (subType) */
return;
} /* rfbGIIClient */
default:
rfbLog("rfbProcessClientNormalMessage: unknown message type %d\n",
msg.type);
rfbLog(" ... closing connection\n");
rfbCloseClient(cl);
return;
} /* switch (msg.type) */
}
/*
* rfbSendFramebufferUpdate - send the currently pending framebuffer update to
* the RFB client.
*/
Bool rfbSendFramebufferUpdate(rfbClientPtr cl)
{
ScreenPtr pScreen = screenInfo.screens[0];
int i;
int nUpdateRegionRects;
rfbFramebufferUpdateMsg *fu = (rfbFramebufferUpdateMsg *)updateBuf;
RegionRec _updateRegion, *updateRegion = &_updateRegion, updateCopyRegion,
idRegion;
Bool emptyUpdateRegion = FALSE;
rfbClientPtr cl2;
int dx, dy;
Bool sendCursorShape = FALSE;
Bool sendCursorPos = FALSE;
double tUpdateStart = 0.0;
TimerCancel(cl->updateTimer);
/*
* We're in the middle of processing a command that's supposed to be
* synchronised. Allowing an update to slip out right now might violate
* that synchronisation.
*/
if (cl->syncFence) return TRUE;
if (cl->state != RFB_NORMAL) return TRUE;
if (rfbProfile) {
tUpdateStart = gettime();
if (tStart < 0.) tStart = tUpdateStart;
}
/* Check that we actually have some space on the link and retry in a
bit if things are congested. */
if (rfbCongestionControl && rfbIsCongested(cl)) {
cl->updateTimer = TimerSet(cl->updateTimer, 0, 50, updateCallback, cl);
return TRUE;
}
/* In continuous mode, we will be outputting at least three distinct
messages. We need to aggregate these in order to not clog up TCP's
congestion window. */
rfbCorkSock(cl->sock);
if (cl->pendingExtDesktopResize) {
if (!rfbSendExtDesktopSize(cl)) return FALSE;
cl->pendingExtDesktopResize = FALSE;
}
if (cl->pendingDesktopResize) {
if (!rfbSendDesktopSize(cl)) return FALSE;
cl->pendingDesktopResize = FALSE;
}
if (rfbFB.blockUpdates) {
rfbUncorkSock(cl->sock);
return TRUE;
}
/*
* If this client understands cursor shape updates, cursor should be
* removed from the framebuffer. Otherwise, make sure it's put up.
*/
if (cl->enableCursorShapeUpdates) {
if (rfbFB.cursorIsDrawn)
rfbSpriteRemoveCursorAllDev(pScreen);
if (!rfbFB.cursorIsDrawn && cl->cursorWasChanged)
sendCursorShape = TRUE;
} else {
if (!rfbFB.cursorIsDrawn)
rfbSpriteRestoreCursorAllDev(pScreen);
}
/*
* Do we plan to send cursor position update?
*/
if (cl->enableCursorPosUpdates && cl->cursorWasMoved)
sendCursorPos = TRUE;
/*
* The modifiedRegion may overlap the destination copyRegion. We remove
* any overlapping bits from the copyRegion (since they'd only be
* overwritten anyway).
*/
REGION_SUBTRACT(pScreen, &cl->copyRegion, &cl->copyRegion,
&cl->modifiedRegion);
/*
* The client is interested in the region requestedRegion. The region
* which should be updated now is the intersection of requestedRegion
* and the union of modifiedRegion and copyRegion. If it's empty then
* no update is needed.
*/
REGION_INIT(pScreen, updateRegion, NullBox, 0);
REGION_UNION(pScreen, updateRegion, &cl->copyRegion, &cl->modifiedRegion);
if (cl->continuousUpdates)
REGION_UNION(pScreen, &cl->requestedRegion, &cl->requestedRegion,
&cl->cuRegion);
REGION_INTERSECT(pScreen, updateRegion, &cl->requestedRegion, updateRegion);
if (!REGION_NOTEMPTY(pScreen, updateRegion) && !sendCursorShape &&
!sendCursorPos) {
REGION_UNINIT(pScreen, updateRegion);
return TRUE;
}
/*
* We assume that the client doesn't have any pixel data outside the
* requestedRegion. In other words, both the source and destination of a
* copy must lie within requestedRegion. So the region we can send as a
* copy is the intersection of the copyRegion with both the requestedRegion
* and the requestedRegion translated by the amount of the copy. We set
* updateCopyRegion to this.
*/
REGION_INIT(pScreen, &updateCopyRegion, NullBox, 0);
REGION_INTERSECT(pScreen, &updateCopyRegion, &cl->copyRegion,
&cl->requestedRegion);
REGION_TRANSLATE(pScreen, &cl->requestedRegion, cl->copyDX, cl->copyDY);
REGION_INTERSECT(pScreen, &updateCopyRegion, &updateCopyRegion,
&cl->requestedRegion);
dx = cl->copyDX;
dy = cl->copyDY;
/*
* Next we remove updateCopyRegion from updateRegion so that updateRegion
* is the part of this update which is sent as ordinary pixel data (i.e not
* a copy).
*/
REGION_SUBTRACT(pScreen, updateRegion, updateRegion, &updateCopyRegion);
/*
* Finally we leave modifiedRegion to be the remainder (if any) of parts of
* the screen which are modified but outside the requestedRegion. We also
* empty both the requestedRegion and the copyRegion - note that we never
* carry over a copyRegion for a future update.
*/
REGION_UNION(pScreen, &cl->modifiedRegion, &cl->modifiedRegion,
&cl->copyRegion);
REGION_SUBTRACT(pScreen, &cl->modifiedRegion, &cl->modifiedRegion,
updateRegion);
REGION_SUBTRACT(pScreen, &cl->modifiedRegion, &cl->modifiedRegion,
&updateCopyRegion);
REGION_EMPTY(pScreen, &cl->requestedRegion);
REGION_EMPTY(pScreen, &cl->copyRegion);
cl->copyDX = 0;
cl->copyDY = 0;
/*
* Now send the update.
*/
if (REGION_NUM_RECTS(updateRegion) > rfbCombineRect) {
RegionRec combinedUpdateRegion;
REGION_INIT(pScreen, &combinedUpdateRegion,
REGION_EXTENTS(pScreen, updateRegion), 1);
REGION_UNINIT(pScreen, updateRegion);
REGION_INIT(pScreen, updateRegion,
REGION_EXTENTS(pScreen, &combinedUpdateRegion), 1);
REGION_UNINIT(pScreen, &combinedUpdateRegion);
}
if ((updateRegion->extents.x2 > pScreen->width ||
updateRegion->extents.y2 > pScreen->height) &&
REGION_NUM_RECTS(updateRegion) > 0) {
rfbLog("WARNING: Framebuffer update at %d,%d with dimensions %dx%d has been clipped to the screen boundaries\n",
updateRegion->extents.x1, updateRegion->extents.y1,
updateRegion->extents.x2 - updateRegion->extents.x1,
updateRegion->extents.y2 - updateRegion->extents.y1);
ClipToScreen(pScreen, updateRegion);
}
if (cl->compareFB) {
if ((cl->ifRegion.extents.x2 > pScreen->width ||
cl->ifRegion.extents.y2 > pScreen->height) &&
REGION_NUM_RECTS(&cl->ifRegion) > 0)
ClipToScreen(pScreen, &cl->ifRegion);
updateRegion = &cl->ifRegion;
emptyUpdateRegion = TRUE;
if (rfbInterframeDebug)
REGION_INIT(pScreen, &idRegion, NullBox, 0);
for (i = 0; i < REGION_NUM_RECTS(&_updateRegion); i++) {
int x = REGION_RECTS(&_updateRegion)[i].x1;
int y = REGION_RECTS(&_updateRegion)[i].y1;
int w = REGION_RECTS(&_updateRegion)[i].x2 - x;
int h = REGION_RECTS(&_updateRegion)[i].y2 - y;
int pitch = rfbFB.paddedWidthInBytes;
int ps = rfbServerFormat.bitsPerPixel / 8;
char *src = &rfbFB.pfbMemory[y * pitch + x * ps];
char *dst = &cl->compareFB[y * pitch + x * ps];
int row, col;
int hBlockSize = rfbICEBlockSize == 0 ? w : rfbICEBlockSize;
int vBlockSize = rfbICEBlockSize == 0 ? h : rfbICEBlockSize;
for (row = 0; row < h; row += vBlockSize) {
for (col = 0; col < w; col += hBlockSize) {
Bool different = FALSE;
int compareWidth = min(hBlockSize, w - col);
int compareHeight = min(vBlockSize, h - row);
int rows = compareHeight;
char *srcPtr = &src[row * pitch + col * ps];
char *dstPtr = &dst[row * pitch + col * ps];
while (rows--) {
if (cl->firstCompare ||
memcmp(srcPtr, dstPtr, compareWidth * ps)) {
memcpy(dstPtr, srcPtr, compareWidth * ps);
different = TRUE;
}
srcPtr += pitch;
dstPtr += pitch;
}
if (different || rfbInterframeDebug) {
RegionRec tmpRegion;
BoxRec box;
box.x1 = x + col;
box.y1 = y + row;
box.x2 = box.x1 + compareWidth;
box.y2 = box.y1 + compareHeight;
REGION_INIT(pScreen, &tmpRegion, &box, 1);
if (!different && rfbInterframeDebug &&
!RECT_IN_REGION(pScreen, &cl->ifRegion, &box)) {
int pad = pitch - compareWidth * ps;
dstPtr = &dst[row * pitch + col * ps];
REGION_UNION(pScreen, &idRegion, &idRegion, &tmpRegion);
rows = compareHeight;
while (rows--) {
char *endOfRow = &dstPtr[compareWidth * ps];
while (dstPtr < endOfRow)
*dstPtr++ ^= 0xFF;
dstPtr += pad;
}
}
REGION_UNION(pScreen, &cl->ifRegion, &cl->ifRegion, &tmpRegion);
REGION_UNINIT(pScreen, &tmpRegion);
}
if (!different && rfbProfile) {
idmpixels += (double)(compareWidth * compareHeight) / 1000000.;
if (!rfbInterframeDebug)
mpixels += (double)(compareWidth * compareHeight) / 1000000.;
}
}
}
}
REGION_UNINIT(pScreen, &_updateRegion);
REGION_NULL(pScreen, &_updateRegion);
cl->firstCompare = FALSE;
/* The Windows TurboVNC Viewer (and probably some other VNC viewers as
well) will ignore any empty FBUs and stop sending FBURs when it
receives one. If CU is not active, then this causes the viewer to
stop receiving updates until something else, such as a mouse cursor
change, triggers a new FBUR. Thus, if the ICE culls all of the
pixels in this update, we send a 1-pixel FBU rather than an empty
one. */
if (REGION_NUM_RECTS(updateRegion) == 0) {
BoxRec box;
box.x1 = box.y1 = 0;
box.x2 = box.y2 = 1;
REGION_UNINIT(pScreen, updateRegion);
REGION_INIT(pScreen, updateRegion, &box, 1);
}
}
if (!rfbSendRTTPing(cl))
goto abort;
cl->rfbFramebufferUpdateMessagesSent++;
if (cl->preferredEncoding == rfbEncodingCoRRE) {
nUpdateRegionRects = 0;
for (i = 0; i < REGION_NUM_RECTS(updateRegion); i++) {
int x = REGION_RECTS(updateRegion)[i].x1;
int y = REGION_RECTS(updateRegion)[i].y1;
int w = REGION_RECTS(updateRegion)[i].x2 - x;
int h = REGION_RECTS(updateRegion)[i].y2 - y;
nUpdateRegionRects += (((w - 1) / cl->correMaxWidth + 1) *
((h - 1) / cl->correMaxHeight + 1));
}
} else if (cl->preferredEncoding == rfbEncodingZlib) {
nUpdateRegionRects = 0;
for (i = 0; i < REGION_NUM_RECTS(updateRegion); i++) {
int x = REGION_RECTS(updateRegion)[i].x1;
int y = REGION_RECTS(updateRegion)[i].y1;
int w = REGION_RECTS(updateRegion)[i].x2 - x;
int h = REGION_RECTS(updateRegion)[i].y2 - y;
nUpdateRegionRects += (((h - 1) / (ZLIB_MAX_SIZE(w) / w)) + 1);
}
} else if (cl->preferredEncoding == rfbEncodingTight) {
nUpdateRegionRects = 0;
for (i = 0; i < REGION_NUM_RECTS(updateRegion); i++) {
int x = REGION_RECTS(updateRegion)[i].x1;
int y = REGION_RECTS(updateRegion)[i].y1;
int w = REGION_RECTS(updateRegion)[i].x2 - x;
int h = REGION_RECTS(updateRegion)[i].y2 - y;
int n = rfbNumCodedRectsTight(cl, x, y, w, h);
if (n == 0) {
nUpdateRegionRects = 0xFFFF;
break;
}
nUpdateRegionRects += n;
}
} else {
nUpdateRegionRects = REGION_NUM_RECTS(updateRegion);
}
fu->type = rfbFramebufferUpdate;
if (nUpdateRegionRects != 0xFFFF) {
fu->nRects = Swap16IfLE(REGION_NUM_RECTS(&updateCopyRegion) +
nUpdateRegionRects +
!!sendCursorShape + !!sendCursorPos);
} else {
fu->nRects = 0xFFFF;
}
ublen = sz_rfbFramebufferUpdateMsg;
cl->captureEnable = TRUE;
if (sendCursorShape) {
cl->cursorWasChanged = FALSE;
if (!rfbSendCursorShape(cl, pScreen))
goto abort;
}
if (sendCursorPos) {
cl->cursorWasMoved = FALSE;
if (!rfbSendCursorPos(cl, pScreen))
goto abort;
}
if (REGION_NOTEMPTY(pScreen, &updateCopyRegion)) {
if (!rfbSendCopyRegion(cl, &updateCopyRegion, dx, dy))
goto abort;
}
REGION_UNINIT(pScreen, &updateCopyRegion);
REGION_NULL(pScreen, &updateCopyRegion);
for (i = 0; i < REGION_NUM_RECTS(updateRegion); i++) {
int x = REGION_RECTS(updateRegion)[i].x1;
int y = REGION_RECTS(updateRegion)[i].y1;
int w = REGION_RECTS(updateRegion)[i].x2 - x;
int h = REGION_RECTS(updateRegion)[i].y2 - y;
cl->rfbRawBytesEquivalent += (sz_rfbFramebufferUpdateRectHeader +
w * (cl->format.bitsPerPixel / 8) * h);
if (rfbProfile) mpixels += (double)w * (double)h / 1000000.;
switch (cl->preferredEncoding) {
case rfbEncodingRaw:
if (!rfbSendRectEncodingRaw(cl, x, y, w, h))
goto abort;
break;
case rfbEncodingRRE:
if (!rfbSendRectEncodingRRE(cl, x, y, w, h))
goto abort;
break;
case rfbEncodingCoRRE:
if (!rfbSendRectEncodingCoRRE(cl, x, y, w, h))
goto abort;
break;
case rfbEncodingHextile:
if (!rfbSendRectEncodingHextile(cl, x, y, w, h))
goto abort;
break;
case rfbEncodingZlib:
if (!rfbSendRectEncodingZlib(cl, x, y, w, h))
goto abort;
break;
case rfbEncodingZRLE:
case rfbEncodingZYWRLE:
if (!rfbSendRectEncodingZRLE(cl, x, y, w, h))
goto abort;
break;
case rfbEncodingTight:
if (!rfbSendRectEncodingTight(cl, x, y, w, h))
goto abort;
break;
}
}
if (cl->compareFB) {
if (rfbInterframeDebug) {
for (i = 0; i < REGION_NUM_RECTS(&idRegion); i++) {
int x = REGION_RECTS(&idRegion)[i].x1;
int y = REGION_RECTS(&idRegion)[i].y1;
int w = REGION_RECTS(&idRegion)[i].x2 - x;
int h = REGION_RECTS(&idRegion)[i].y2 - y, rows;
int pitch = rfbFB.paddedWidthInBytes;
int ps = rfbServerFormat.bitsPerPixel / 8;
char *src = &rfbFB.pfbMemory[y * pitch + x * ps];
char *dst = &cl->compareFB[y * pitch + x * ps];
rows = h;
while (rows--) {
memcpy(dst, src, w * ps);
src += pitch;
dst += pitch;
}
}
REGION_UNINIT(pScreen, &idRegion);
REGION_NULL(pScreen, &idRegion);
}
REGION_EMPTY(pScreen, updateRegion);
} else {
REGION_UNINIT(pScreen, updateRegion);
REGION_NULL(pScreen, updateRegion);
}
if (nUpdateRegionRects == 0xFFFF && !rfbSendLastRectMarker(cl))
goto abort;
if (!rfbSendUpdateBuf(cl))
goto abort;
cl->captureEnable = FALSE;
if (!rfbSendRTTPing(cl))
goto abort;
if (rfbProfile) {
tUpdate += gettime() - tUpdateStart;
tElapsed = gettime() - tStart;
iter++;
if (tElapsed > 5.) {
rfbLog("%.2f updates/sec, %.2f Mpixels/sec, %.3f Mbits/sec\n",
(double)iter / tElapsed, mpixels / tElapsed,
(double)sendBytes / 125000. / tElapsed);
rfbLog("Time/update: Encode = %.3f ms, Other = %.3f ms\n",
tUpdate / (double)iter * 1000.,
(tElapsed - tUpdate) / (double)iter * 1000.);
if (cl->compareFB) {
rfbLog("Identical Mpixels/sec: %.2f (%f %%)\n",
(double)idmpixels / tElapsed, idmpixels / mpixels * 100.0);
idmpixels = 0.;
}
tUpdate = 0.;
iter = 0;
mpixels = 0.;
sendBytes = 0;
tStart = gettime();
}
}
if (rfbAutoLosslessRefresh > 0.0 &&
(!putImageOnly || REGION_NOTEMPTY(pScreen, &cl->alrEligibleRegion) ||
cl->firstUpdate)) {
if (putImageOnly)
REGION_UNION(pScreen, &cl->alrRegion, &cl->alrRegion,
&cl->alrEligibleRegion);
REGION_EMPTY(pScreen, &cl->alrEligibleRegion);
cl->alrTimer = TimerSet(cl->alrTimer, 0,
(CARD32)(rfbAutoLosslessRefresh * 1000.0),
alrCallback, cl);
}
rfbUncorkSock(cl->sock);
return TRUE;
abort:
if (!REGION_NIL(&updateCopyRegion))
REGION_UNINIT(pScreen, &updateCopyRegion);
if (rfbInterframeDebug && !REGION_NIL(&idRegion))
REGION_UNINIT(pScreen, &idRegion);
if (emptyUpdateRegion) {
/* Make sure cl hasn't been freed */
for (cl2 = rfbClientHead; cl2; cl2 = cl2->next) {
if (cl2 == cl) {
REGION_EMPTY(pScreen, updateRegion);
break;
}
}
} else if (!REGION_NIL(&_updateRegion)) {
REGION_UNINIT(pScreen, &_updateRegion);
}
return FALSE;
}
/*
* Send the copy region as a string of CopyRect encoded rectangles.
* The only slightly tricky thing is that we should send the messages in
* the correct order so that an earlier CopyRect will not corrupt the source
* of a later one.
*/
static Bool rfbSendCopyRegion(rfbClientPtr cl, RegionPtr reg, int dx, int dy)
{
int nrects, nrectsInBand, x_inc, y_inc, thisRect, firstInNextBand;
int x, y, w, h;
rfbFramebufferUpdateRectHeader rect;
rfbCopyRect cr;
ScreenPtr pScreen = screenInfo.screens[0];
nrects = REGION_NUM_RECTS(reg);
if (dx <= 0)
x_inc = 1;
else
x_inc = -1;
if (dy <= 0) {
thisRect = 0;
y_inc = 1;
} else {
thisRect = nrects - 1;
y_inc = -1;
}
/* If the source region intersects the lossy region, then we know that the
destination region is about to become lossy, so we add it to the lossy
region. */
if (rfbAutoLosslessRefresh > 0.0 && alrCopyRect &&
REGION_NOTEMPTY(pScreen, reg)) {
RegionRec tmpRegion;
REGION_INIT(pScreen, &tmpRegion, NullBox, 0);
REGION_COPY(pScreen, &tmpRegion, reg);
REGION_TRANSLATE(pScreen, &tmpRegion, -dx, -dy);
REGION_INTERSECT(pScreen, &tmpRegion, &cl->lossyRegion, &tmpRegion);
if (REGION_NOTEMPTY(pScreen, &tmpRegion)) {
REGION_UNION(pScreen, &cl->lossyRegion, &cl->lossyRegion, reg);
REGION_UNION(pScreen, &cl->alrEligibleRegion, &cl->alrEligibleRegion,
reg);
}
REGION_UNINIT(pScreen, &tmpRegion);
}
if (reg->extents.x2 > pScreen->width || reg->extents.y2 > pScreen->height)
rfbLog("WARNING: CopyRect dest at %d,%d with dimensions %dx%d exceeds screen boundaries\n",
reg->extents.x1, reg->extents.y1,
reg->extents.x2 - reg->extents.x1,
reg->extents.y2 - reg->extents.y1);
while (nrects > 0) {
firstInNextBand = thisRect;
nrectsInBand = 0;
while ((nrects > 0) &&
(REGION_RECTS(reg)[firstInNextBand].y1 ==
REGION_RECTS(reg)[thisRect].y1)) {
firstInNextBand += y_inc;
nrects--;
nrectsInBand++;
}
if (x_inc != y_inc)
thisRect = firstInNextBand - y_inc;
while (nrectsInBand > 0) {
if ((ublen + sz_rfbFramebufferUpdateRectHeader + sz_rfbCopyRect) >
UPDATE_BUF_SIZE) {
if (!rfbSendUpdateBuf(cl))
return FALSE;
}
x = REGION_RECTS(reg)[thisRect].x1;
y = REGION_RECTS(reg)[thisRect].y1;
w = REGION_RECTS(reg)[thisRect].x2 - x;
h = REGION_RECTS(reg)[thisRect].y2 - y;
if (cl->compareFB) {
int pitch = rfbFB.paddedWidthInBytes;
int ps = rfbServerFormat.bitsPerPixel / 8, rows = h;
char *src = &rfbFB.pfbMemory[y * pitch + x * ps];
char *dst = &cl->compareFB[y * pitch + x * ps];
while (rows--) {
memcpy(dst, src, w * ps);
src += pitch;
dst += pitch;
}
src = &rfbFB.pfbMemory[(y - dy) * pitch + (x - dx) * ps];
dst = &cl->compareFB[(y - dy) * pitch + (x - dx) * ps];
rows = h;
while (rows--) {
memcpy(dst, src, w * ps);
src += pitch;
dst += pitch;
}
}
rect.r.x = Swap16IfLE(x);
rect.r.y = Swap16IfLE(y);
rect.r.w = Swap16IfLE(w);
rect.r.h = Swap16IfLE(h);
rect.encoding = Swap32IfLE(rfbEncodingCopyRect);
memcpy(&updateBuf[ublen], (char *)&rect,
sz_rfbFramebufferUpdateRectHeader);
ublen += sz_rfbFramebufferUpdateRectHeader;
cr.srcX = Swap16IfLE(x - dx);
cr.srcY = Swap16IfLE(y - dy);
memcpy(&updateBuf[ublen], (char *)&cr, sz_rfbCopyRect);
ublen += sz_rfbCopyRect;
cl->rfbRectanglesSent[rfbEncodingCopyRect]++;
cl->rfbBytesSent[rfbEncodingCopyRect] +=
sz_rfbFramebufferUpdateRectHeader + sz_rfbCopyRect;
thisRect += x_inc;
nrectsInBand--;
}
thisRect = firstInNextBand;
}
return TRUE;
}
/*
* Send a given rectangle in raw encoding (rfbEncodingRaw).
*/
Bool rfbSendRectEncodingRaw(rfbClientPtr cl, int x, int y, int w, int h)
{
rfbFramebufferUpdateRectHeader rect;
int nlines;
int bytesPerLine = w * (cl->format.bitsPerPixel / 8);
char *fbptr =
(cl->fb + (rfbFB.paddedWidthInBytes * y) + (x * (rfbFB.bitsPerPixel / 8)));
/* Flush the buffer to guarantee correct alignment for translateFn(). */
if (ublen > 0) {
if (!rfbSendUpdateBuf(cl))
return FALSE;
}
rect.r.x = Swap16IfLE(x);
rect.r.y = Swap16IfLE(y);
rect.r.w = Swap16IfLE(w);
rect.r.h = Swap16IfLE(h);
rect.encoding = Swap32IfLE(rfbEncodingRaw);
memcpy(&updateBuf[ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader);
ublen += sz_rfbFramebufferUpdateRectHeader;
cl->rfbRectanglesSent[rfbEncodingRaw]++;
cl->rfbBytesSent[rfbEncodingRaw] +=
sz_rfbFramebufferUpdateRectHeader + bytesPerLine * h;
nlines = (UPDATE_BUF_SIZE - ublen) / bytesPerLine;
while (TRUE) {
if (nlines > h)
nlines = h;
(*cl->translateFn) (cl->translateLookupTable, &rfbServerFormat,
&cl->format, fbptr, &updateBuf[ublen],
rfbFB.paddedWidthInBytes, w, nlines);
ublen += nlines * bytesPerLine;
h -= nlines;
if (h == 0) /* rect fitted in buffer, do next one */
return TRUE;
/* buffer full - flush partial rect and do another nlines */
if (!rfbSendUpdateBuf(cl))
return FALSE;
fbptr += (rfbFB.paddedWidthInBytes * nlines);
nlines = (UPDATE_BUF_SIZE - ublen) / bytesPerLine;
if (nlines == 0) {
rfbLog("rfbSendRectEncodingRaw: send buffer too small for %d bytes per line\n",
bytesPerLine);
rfbCloseClient(cl);
return FALSE;
}
}
}
/*
* Send an empty rectangle with encoding field set to value of
* rfbEncodingLastRect to notify client that this is the last
* rectangle in framebuffer update ("LastRect" extension of RFB
* protocol).
*/
static Bool rfbSendLastRectMarker(rfbClientPtr cl)
{
rfbFramebufferUpdateRectHeader rect;
if (ublen + sz_rfbFramebufferUpdateRectHeader > UPDATE_BUF_SIZE) {
if (!rfbSendUpdateBuf(cl))
return FALSE;
}
rect.encoding = Swap32IfLE(rfbEncodingLastRect);
rect.r.x = 0;
rect.r.y = 0;
rect.r.w = 0;
rect.r.h = 0;
memcpy(&updateBuf[ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader);
ublen += sz_rfbFramebufferUpdateRectHeader;
cl->rfbLastRectMarkersSent++;
cl->rfbLastRectBytesSent += sz_rfbFramebufferUpdateRectHeader;
return TRUE;
}
/*
* Send the contents of updateBuf. Returns 1 if successful, -1 if
* not (errno should be set).
*/
Bool rfbSendUpdateBuf(rfbClientPtr cl)
{
/*
int i;
for (i = 0; i < ublen; i++) {
fprintf(stderr, "%02x ", ((unsigned char *)updateBuf)[i]);
}
fprintf(stderr, "\n");
*/
if (ublen > 0 && WriteExact(cl, updateBuf, ublen) < 0) {
rfbLogPerror("rfbSendUpdateBuf: write");
rfbCloseClient(cl);
return FALSE;
}
if (cl->captureEnable && cl->captureFD >= 0 && ublen > 0)
WriteCapture(cl->captureFD, updateBuf, ublen);
ublen = 0;
return TRUE;
}
/*
* rfbSendSetColourMapEntries sends a SetColourMapEntries message to the
* client, using values from the currently installed colormap.
*/
Bool rfbSendSetColourMapEntries(rfbClientPtr cl, int firstColour, int nColours)
{
char buf[sz_rfbSetColourMapEntriesMsg + 256 * 3 * 2];
rfbSetColourMapEntriesMsg *scme = (rfbSetColourMapEntriesMsg *)buf;
CARD16 *rgb = (CARD16 *)(&buf[sz_rfbSetColourMapEntriesMsg]);
EntryPtr pent;
int i, len;
scme->type = rfbSetColourMapEntries;
scme->firstColour = Swap16IfLE(firstColour);
scme->nColours = Swap16IfLE(nColours);
len = sz_rfbSetColourMapEntriesMsg;
pent = (EntryPtr)&rfbInstalledColormap->red[firstColour];
for (i = 0; i < nColours; i++) {
if (pent->fShared) {
rgb[i * 3] = Swap16IfLE(pent->co.shco.red->color);
rgb[i * 3 + 1] = Swap16IfLE(pent->co.shco.green->color);
rgb[i * 3 + 2] = Swap16IfLE(pent->co.shco.blue->color);
} else {
rgb[i * 3] = Swap16IfLE(pent->co.local.red);
rgb[i * 3 + 1] = Swap16IfLE(pent->co.local.green);
rgb[i * 3 + 2] = Swap16IfLE(pent->co.local.blue);
}
pent++;
}
len += nColours * 3 * 2;
if (WriteExact(cl, buf, len) < 0) {
rfbLogPerror("rfbSendSetColourMapEntries: write");
rfbCloseClient(cl);
return FALSE;
}
if (cl->captureFD >= 0)
WriteCapture(cl->captureFD, buf, len);
return TRUE;
}
/*
* rfbSendBell sends a Bell message to all the clients.
*/
void rfbSendBell(void)
{
rfbClientPtr cl, nextCl;
rfbBellMsg b;
for (cl = rfbClientHead; cl; cl = nextCl) {
nextCl = cl->next;
if (cl->state != RFB_NORMAL)
continue;
b.type = rfbBell;
if (WriteExact(cl, (char *)&b, sz_rfbBellMsg) < 0) {
rfbLogPerror("rfbSendBell: write");
rfbCloseClient(cl);
continue;
}
if (cl->captureFD >= 0)
WriteCapture(cl->captureFD, (char *)&b, sz_rfbBellMsg);
}
}
/*
* rfbSendServerCutText sends a ServerCutText message to all the clients.
*/
void rfbSendServerCutText(char *str, int len)
{
rfbClientPtr cl, nextCl;
rfbServerCutTextMsg sct;
if (rfbViewOnly || rfbAuthDisableCBSend || !str || len <= 0)
return;
for (cl = rfbClientHead; cl; cl = nextCl) {
nextCl = cl->next;
if (cl->state != RFB_NORMAL || cl->viewOnly)
continue;
if (cl->cutTextLen == len && cl->cutText && !memcmp(cl->cutText, str, len))
continue;
if (cl->cutText)
free(cl->cutText);
cl->cutText = rfbAlloc(len);
memcpy(cl->cutText, str, len);
cl->cutTextLen = len;
memset(&sct, 0, sz_rfbServerCutTextMsg);
sct.type = rfbServerCutText;
sct.length = Swap32IfLE(len);
if (WriteExact(cl, (char *)&sct, sz_rfbServerCutTextMsg) < 0) {
rfbLogPerror("rfbSendServerCutText: write");
rfbCloseClient(cl);
continue;
}
if (WriteExact(cl, str, len) < 0) {
rfbLogPerror("rfbSendServerCutText: write");
rfbCloseClient(cl);
continue;
}
if (cl->captureFD >= 0)
WriteCapture(cl->captureFD, str, len);
}
LogMessage(X_DEBUG, "Sent server clipboard: '%.*s%s' (%d bytes)\n",
len <= 20 ? len : 20, str, len <= 20 ? "" : "...", len);
}
/*
* rfbSendDesktopSize sends a DesktopSize message to a specific client.
*/
Bool rfbSendDesktopSize(rfbClientPtr cl)
{
rfbFramebufferUpdateRectHeader rh;
rfbFramebufferUpdateMsg fu;
if (!cl->enableDesktopSize)
return TRUE;
memset(&fu, 0, sz_rfbFramebufferUpdateMsg);
fu.type = rfbFramebufferUpdate;
fu.nRects = Swap16IfLE(1);
if (WriteExact(cl, (char *)&fu, sz_rfbFramebufferUpdateMsg) < 0) {
rfbLogPerror("rfbSendDesktopSize: write");
rfbCloseClient(cl);
return FALSE;
}
rh.encoding = Swap32IfLE(rfbEncodingNewFBSize);
rh.r.x = rh.r.y = 0;
rh.r.w = Swap16IfLE(rfbFB.width);
rh.r.h = Swap16IfLE(rfbFB.height);
if (WriteExact(cl, (char *)&rh, sz_rfbFramebufferUpdateRectHeader) < 0) {
rfbLogPerror("rfbSendDesktopSize: write");
rfbCloseClient(cl);
return FALSE;
}
return TRUE;
}
/*
* rfbSendExtDesktopSize sends an extended desktop size message to a specific
* client.
*/
Bool rfbSendExtDesktopSize(rfbClientPtr cl)
{
rfbFramebufferUpdateRectHeader rh;
rfbFramebufferUpdateMsg fu;
CARD8 numScreens[4] = { 0, 0, 0, 0 };
rfbScreenInfo *iter;
BOOL fakeScreen = FALSE;
if (!cl->enableExtDesktopSize)
return TRUE;
/* Error messages can only be sent with the EDS extension */
if (!cl->enableExtDesktopSize && cl->result != rfbEDSResultSuccess)
return TRUE;
memset(&fu, 0, sz_rfbFramebufferUpdateMsg);
fu.type = rfbFramebufferUpdate;
fu.nRects = Swap16IfLE(1);
if (WriteExact(cl, (char *)&fu, sz_rfbFramebufferUpdateMsg) < 0) {
rfbLogPerror("rfbSendExtDesktopSize: write");
rfbCloseClient(cl);
return FALSE;
}
/* Send the ExtendedDesktopSize message, if the client supports it.
The TigerVNC Viewer, in particular, requires this, or it won't
enable remote desktop resize. */
rh.encoding = Swap32IfLE(rfbEncodingExtendedDesktopSize);
rh.r.x = Swap16IfLE(cl->reason);
rh.r.y = Swap16IfLE(cl->result);
rh.r.w = Swap16IfLE(rfbFB.width);
rh.r.h = Swap16IfLE(rfbFB.height);
if (WriteExact(cl, (char *)&rh, sz_rfbFramebufferUpdateRectHeader) < 0) {
rfbLogPerror("rfbSendExtDesktopSize: write");
rfbCloseClient(cl);
return FALSE;
}
xorg_list_for_each_entry(iter, &rfbScreens, entry) {
if (iter->output->crtc && iter->output->crtc->mode)
numScreens[0]++;
}
if (numScreens[0] < 1) {
numScreens[0] = 1;
fakeScreen = TRUE;
}
if (WriteExact(cl, (char *)numScreens, 4) < 0) {
rfbLogPerror("rfbSendExtDesktopSize: write");
rfbCloseClient(cl);
return FALSE;
}
if (fakeScreen) {
rfbScreenInfo screen = *xorg_list_first_entry(&rfbScreens, rfbScreenInfo,
entry);
screen.s.id = Swap32IfLE(screen.s.id);
screen.s.x = screen.s.y = 0;
screen.s.w = Swap16IfLE(rfbFB.width);
screen.s.h = Swap16IfLE(rfbFB.height);
screen.s.flags = Swap32IfLE(screen.s.flags);
if (WriteExact(cl, (char *)&screen.s, sz_rfbScreenDesc) < 0) {
rfbLogPerror("rfbSendExtDesktopSize: write");
rfbCloseClient(cl);
return FALSE;
}
} else {
xorg_list_for_each_entry(iter, &rfbScreens, entry) {
rfbScreenInfo screen = *iter;
if (screen.output->crtc && screen.output->crtc->mode) {
screen.s.id = Swap32IfLE(screen.s.id);
screen.s.x = Swap16IfLE(screen.s.x);
screen.s.y = Swap16IfLE(screen.s.y);
screen.s.w = Swap16IfLE(screen.s.w);
screen.s.h = Swap16IfLE(screen.s.h);
screen.s.flags = Swap32IfLE(screen.s.flags);
if (WriteExact(cl, (char *)&screen.s, sz_rfbScreenDesc) < 0) {
rfbLogPerror("rfbSendExtDesktopSize: write");
rfbCloseClient(cl);
return FALSE;
}
}
}
}
return TRUE;
}
/*****************************************************************************
*
* UDP can be used for keyboard and pointer events when the underlying
* network is highly reliable. This is really here to support ORL's
* videotile, whose TCP implementation doesn't like sending lots of small
* packets (such as 100s of pen readings per second!).
*/
void rfbNewUDPConnection(int sock)
{
if (write(sock, &ptrAcceleration, 1) < 0)
rfbLogPerror("rfbNewUDPConnection: write");
}
/*
* Because UDP is a message based service, we can't read the first byte and
* then the rest of the packet separately like we do with TCP. We will always
* get a whole packet delivered in one go, so we ask read() for the maximum
* number of bytes we can possibly get.
*/
void rfbProcessUDPInput(int sock)
{
int n;
rfbClientToServerMsg msg;
if ((n = read(sock, (char *)&msg, sizeof(msg))) <= 0) {
if (n < 0)
rfbLogPerror("rfbProcessUDPInput: read");
rfbDisconnectUDPSock();
return;
}
switch (msg.type) {
case rfbKeyEvent:
if (n != sz_rfbKeyEventMsg) {
rfbLog("rfbProcessUDPInput: key event incorrect length\n");
rfbDisconnectUDPSock();
return;
}
if (!rfbViewOnly)
KeyEvent((KeySym)Swap32IfLE(msg.ke.key), msg.ke.down);
break;
case rfbPointerEvent:
if (n != sz_rfbPointerEventMsg) {
rfbLog("rfbProcessUDPInput: ptr event incorrect length\n");
rfbDisconnectUDPSock();
return;
}
if (!rfbViewOnly)
PtrAddEvent(msg.pe.buttonMask, Swap16IfLE(msg.pe.x),
Swap16IfLE(msg.pe.y), 0);
break;
default:
rfbLog("rfbProcessUDPInput: unknown message type %d\n", msg.type);
rfbDisconnectUDPSock();
}
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_1040_1 |
crossvul-cpp_data_bad_518_0 | /*
* Copyright (C) 2000-2002 Constantin Kaplinsky. All Rights Reserved.
* Copyright (C) 2000 Tridia Corporation. All Rights Reserved.
* Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved.
*
* This 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 software 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 software; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
* USA.
*/
/*
* rfbproto.c - functions to deal with client side of RFB protocol.
*/
#ifdef __STRICT_ANSI__
#define _BSD_SOURCE
#define _POSIX_SOURCE
#define _XOPEN_SOURCE 600
#endif
#ifndef WIN32
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <pwd.h>
#endif
#include <errno.h>
#include <rfb/rfbclient.h>
#ifdef WIN32
#undef SOCKET
#undef socklen_t
#endif
#ifdef LIBVNCSERVER_HAVE_LIBZ
#include <zlib.h>
#ifdef __CHECKER__
#undef Z_NULL
#define Z_NULL NULL
#endif
#endif
#ifndef _MSC_VER
/* Strings.h is not available in MSVC */
#include <strings.h>
#endif
#include <stdarg.h>
#include <time.h>
#ifdef LIBVNCSERVER_WITH_CLIENT_GCRYPT
#include <gcrypt.h>
#endif
#include "sasl.h"
#ifdef LIBVNCSERVER_HAVE_LZO
#include <lzo/lzo1x.h>
#else
#include "minilzo.h"
#endif
#include "tls.h"
#ifdef _MSC_VER
# define snprintf _snprintf /* MSVC went straight to the underscored syntax */
#endif
/*
* rfbClientLog prints a time-stamped message to the log file (stderr).
*/
rfbBool rfbEnableClientLogging=TRUE;
static void
rfbDefaultClientLog(const char *format, ...)
{
va_list args;
char buf[256];
time_t log_clock;
if(!rfbEnableClientLogging)
return;
va_start(args, format);
time(&log_clock);
strftime(buf, 255, "%d/%m/%Y %X ", localtime(&log_clock));
fprintf(stderr, "%s", buf);
vfprintf(stderr, format, args);
fflush(stderr);
va_end(args);
}
rfbClientLogProc rfbClientLog=rfbDefaultClientLog;
rfbClientLogProc rfbClientErr=rfbDefaultClientLog;
/* extensions */
rfbClientProtocolExtension* rfbClientExtensions = NULL;
void rfbClientRegisterExtension(rfbClientProtocolExtension* e)
{
e->next = rfbClientExtensions;
rfbClientExtensions = e;
}
/* client data */
void rfbClientSetClientData(rfbClient* client, void* tag, void* data)
{
rfbClientData* clientData = client->clientData;
while(clientData && clientData->tag != tag)
clientData = clientData->next;
if(clientData == NULL) {
clientData = calloc(sizeof(rfbClientData), 1);
clientData->next = client->clientData;
client->clientData = clientData;
clientData->tag = tag;
}
clientData->data = data;
}
void* rfbClientGetClientData(rfbClient* client, void* tag)
{
rfbClientData* clientData = client->clientData;
while(clientData) {
if(clientData->tag == tag)
return clientData->data;
clientData = clientData->next;
}
return NULL;
}
static rfbBool HandleRRE8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleRRE16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleRRE32(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleCoRRE8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleCoRRE16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleCoRRE32(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleHextile8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleHextile16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleHextile32(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleUltra8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleUltra16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleUltra32(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleUltraZip8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleUltraZip16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleUltraZip32(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTRLE8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTRLE15(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTRLE16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTRLE24(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTRLE24Up(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTRLE24Down(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTRLE32(rfbClient* client, int rx, int ry, int rw, int rh);
#ifdef LIBVNCSERVER_HAVE_LIBZ
static rfbBool HandleZlib8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZlib16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZlib32(rfbClient* client, int rx, int ry, int rw, int rh);
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
static rfbBool HandleTight8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTight16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTight32(rfbClient* client, int rx, int ry, int rw, int rh);
static long ReadCompactLen (rfbClient* client);
#endif
static rfbBool HandleZRLE8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZRLE15(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZRLE16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZRLE24(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZRLE24Up(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZRLE24Down(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZRLE32(rfbClient* client, int rx, int ry, int rw, int rh);
#endif
/*
* Server Capability Functions
*/
rfbBool
SupportsClient2Server(rfbClient* client, int messageType)
{
return (client->supportedMessages.client2server[((messageType & 0xFF)/8)] & (1<<(messageType % 8)) ? TRUE : FALSE);
}
rfbBool
SupportsServer2Client(rfbClient* client, int messageType)
{
return (client->supportedMessages.server2client[((messageType & 0xFF)/8)] & (1<<(messageType % 8)) ? TRUE : FALSE);
}
void
SetClient2Server(rfbClient* client, int messageType)
{
client->supportedMessages.client2server[((messageType & 0xFF)/8)] |= (1<<(messageType % 8));
}
void
SetServer2Client(rfbClient* client, int messageType)
{
client->supportedMessages.server2client[((messageType & 0xFF)/8)] |= (1<<(messageType % 8));
}
void
ClearClient2Server(rfbClient* client, int messageType)
{
client->supportedMessages.client2server[((messageType & 0xFF)/8)] &= (!(1<<(messageType % 8)));
}
void
ClearServer2Client(rfbClient* client, int messageType)
{
client->supportedMessages.server2client[((messageType & 0xFF)/8)] &= (!(1<<(messageType % 8)));
}
void
DefaultSupportedMessages(rfbClient* client)
{
memset((char *)&client->supportedMessages,0,sizeof(client->supportedMessages));
/* Default client supported messages (universal RFB 3.3 protocol) */
SetClient2Server(client, rfbSetPixelFormat);
/* SetClient2Server(client, rfbFixColourMapEntries); Not currently supported */
SetClient2Server(client, rfbSetEncodings);
SetClient2Server(client, rfbFramebufferUpdateRequest);
SetClient2Server(client, rfbKeyEvent);
SetClient2Server(client, rfbPointerEvent);
SetClient2Server(client, rfbClientCutText);
/* technically, we only care what we can *send* to the server
* but, we set Server2Client Just in case it ever becomes useful
*/
SetServer2Client(client, rfbFramebufferUpdate);
SetServer2Client(client, rfbSetColourMapEntries);
SetServer2Client(client, rfbBell);
SetServer2Client(client, rfbServerCutText);
}
void
DefaultSupportedMessagesUltraVNC(rfbClient* client)
{
DefaultSupportedMessages(client);
SetClient2Server(client, rfbFileTransfer);
SetClient2Server(client, rfbSetScale);
SetClient2Server(client, rfbSetServerInput);
SetClient2Server(client, rfbSetSW);
SetClient2Server(client, rfbTextChat);
SetClient2Server(client, rfbPalmVNCSetScaleFactor);
/* technically, we only care what we can *send* to the server */
SetServer2Client(client, rfbResizeFrameBuffer);
SetServer2Client(client, rfbPalmVNCReSizeFrameBuffer);
SetServer2Client(client, rfbFileTransfer);
SetServer2Client(client, rfbTextChat);
}
void
DefaultSupportedMessagesTightVNC(rfbClient* client)
{
DefaultSupportedMessages(client);
SetClient2Server(client, rfbFileTransfer);
SetClient2Server(client, rfbSetServerInput);
SetClient2Server(client, rfbSetSW);
/* SetClient2Server(client, rfbTextChat); */
/* technically, we only care what we can *send* to the server */
SetServer2Client(client, rfbFileTransfer);
SetServer2Client(client, rfbTextChat);
}
#ifndef WIN32
static rfbBool
IsUnixSocket(const char *name)
{
struct stat sb;
if(stat(name, &sb) == 0 && (sb.st_mode & S_IFMT) == S_IFSOCK)
return TRUE;
return FALSE;
}
#endif
/*
* ConnectToRFBServer.
*/
rfbBool
ConnectToRFBServer(rfbClient* client,const char *hostname, int port)
{
if (client->serverPort==-1) {
/* serverHost is a file recorded by vncrec. */
const char* magic="vncLog0.0";
char buffer[10];
rfbVNCRec* rec = (rfbVNCRec*)malloc(sizeof(rfbVNCRec));
client->vncRec = rec;
rec->file = fopen(client->serverHost,"rb");
rec->tv.tv_sec = 0;
rec->readTimestamp = FALSE;
rec->doNotSleep = FALSE;
if (!rec->file) {
rfbClientLog("Could not open %s.\n",client->serverHost);
return FALSE;
}
setbuf(rec->file,NULL);
if (fread(buffer,1,strlen(magic),rec->file) != strlen(magic) || strncmp(buffer,magic,strlen(magic))) {
rfbClientLog("File %s was not recorded by vncrec.\n",client->serverHost);
fclose(rec->file);
return FALSE;
}
client->sock = -1;
return TRUE;
}
#ifndef WIN32
if(IsUnixSocket(hostname))
/* serverHost is a UNIX socket. */
client->sock = ConnectClientToUnixSock(hostname);
else
#endif
{
#ifdef LIBVNCSERVER_IPv6
client->sock = ConnectClientToTcpAddr6(hostname, port);
if (client->sock == -1)
#endif
{
unsigned int host;
/* serverHost is a hostname */
if (!StringToIPAddr(hostname, &host)) {
rfbClientLog("Couldn't convert '%s' to host address\n", hostname);
return FALSE;
}
client->sock = ConnectClientToTcpAddr(host, port);
}
}
if (client->sock < 0) {
rfbClientLog("Unable to connect to VNC server\n");
return FALSE;
}
if(client->QoS_DSCP && !SetDSCP(client->sock, client->QoS_DSCP))
return FALSE;
return SetNonBlocking(client->sock);
}
/*
* ConnectToRFBRepeater.
*/
rfbBool ConnectToRFBRepeater(rfbClient* client,const char *repeaterHost, int repeaterPort, const char *destHost, int destPort)
{
rfbProtocolVersionMsg pv;
int major,minor;
char tmphost[250];
int tmphostlen;
#ifdef LIBVNCSERVER_IPv6
client->sock = ConnectClientToTcpAddr6(repeaterHost, repeaterPort);
if (client->sock == -1)
#endif
{
unsigned int host;
if (!StringToIPAddr(repeaterHost, &host)) {
rfbClientLog("Couldn't convert '%s' to host address\n", repeaterHost);
return FALSE;
}
client->sock = ConnectClientToTcpAddr(host, repeaterPort);
}
if (client->sock < 0) {
rfbClientLog("Unable to connect to VNC repeater\n");
return FALSE;
}
if (!SetNonBlocking(client->sock))
return FALSE;
if (!ReadFromRFBServer(client, pv, sz_rfbProtocolVersionMsg))
return FALSE;
pv[sz_rfbProtocolVersionMsg] = 0;
/* UltraVNC repeater always report version 000.000 to identify itself */
if (sscanf(pv,rfbProtocolVersionFormat,&major,&minor) != 2 || major != 0 || minor != 0) {
rfbClientLog("Not a valid VNC repeater (%s)\n",pv);
return FALSE;
}
rfbClientLog("Connected to VNC repeater, using protocol version %d.%d\n", major, minor);
tmphostlen = snprintf(tmphost, sizeof(tmphost), "%s:%d", destHost, destPort);
if(tmphostlen < 0 || tmphostlen >= (int)sizeof(tmphost))
return FALSE; /* snprintf error or output truncated */
if (!WriteToRFBServer(client, tmphost, tmphostlen + 1))
return FALSE;
return TRUE;
}
extern void rfbClientEncryptBytes(unsigned char* bytes, char* passwd);
extern void rfbClientEncryptBytes2(unsigned char *where, const int length, unsigned char *key);
static void
ReadReason(rfbClient* client)
{
uint32_t reasonLen;
char *reason;
if (!ReadFromRFBServer(client, (char *)&reasonLen, 4)) return;
reasonLen = rfbClientSwap32IfLE(reasonLen);
if(reasonLen > 1<<20) {
rfbClientLog("VNC connection failed, but sent reason length of %u exceeds limit of 1MB",(unsigned int)reasonLen);
return;
}
reason = malloc(reasonLen+1);
if (!ReadFromRFBServer(client, reason, reasonLen)) { free(reason); return; }
reason[reasonLen]=0;
rfbClientLog("VNC connection failed: %s\n",reason);
free(reason);
}
rfbBool
rfbHandleAuthResult(rfbClient* client)
{
uint32_t authResult=0;
if (!ReadFromRFBServer(client, (char *)&authResult, 4)) return FALSE;
authResult = rfbClientSwap32IfLE(authResult);
switch (authResult) {
case rfbVncAuthOK:
rfbClientLog("VNC authentication succeeded\n");
return TRUE;
break;
case rfbVncAuthFailed:
if (client->major==3 && client->minor>7)
{
/* we have an error following */
ReadReason(client);
return FALSE;
}
rfbClientLog("VNC authentication failed\n");
return FALSE;
case rfbVncAuthTooMany:
rfbClientLog("VNC authentication failed - too many tries\n");
return FALSE;
}
rfbClientLog("Unknown VNC authentication result: %d\n",
(int)authResult);
return FALSE;
}
static rfbBool
ReadSupportedSecurityType(rfbClient* client, uint32_t *result, rfbBool subAuth)
{
uint8_t count=0;
uint8_t loop=0;
uint8_t flag=0;
rfbBool extAuthHandler;
uint8_t tAuth[256];
char buf1[500],buf2[10];
uint32_t authScheme;
rfbClientProtocolExtension* e;
if (!ReadFromRFBServer(client, (char *)&count, 1)) return FALSE;
if (count==0)
{
rfbClientLog("List of security types is ZERO, expecting an error to follow\n");
ReadReason(client);
return FALSE;
}
rfbClientLog("We have %d security types to read\n", count);
authScheme=0;
/* now, we have a list of available security types to read ( uint8_t[] ) */
for (loop=0;loop<count;loop++)
{
if (!ReadFromRFBServer(client, (char *)&tAuth[loop], 1)) return FALSE;
rfbClientLog("%d) Received security type %d\n", loop, tAuth[loop]);
if (flag) continue;
extAuthHandler=FALSE;
for (e = rfbClientExtensions; e; e = e->next) {
if (!e->handleAuthentication) continue;
uint32_t const* secType;
for (secType = e->securityTypes; secType && *secType; secType++) {
if (tAuth[loop]==*secType) {
extAuthHandler=TRUE;
}
}
}
if (tAuth[loop]==rfbVncAuth || tAuth[loop]==rfbNoAuth ||
extAuthHandler ||
#if defined(LIBVNCSERVER_HAVE_GNUTLS) || defined(LIBVNCSERVER_HAVE_LIBSSL)
tAuth[loop]==rfbVeNCrypt ||
#endif
#ifdef LIBVNCSERVER_HAVE_SASL
tAuth[loop]==rfbSASL ||
#endif /* LIBVNCSERVER_HAVE_SASL */
(tAuth[loop]==rfbARD && client->GetCredential) ||
(!subAuth && (tAuth[loop]==rfbTLS || (tAuth[loop]==rfbVeNCrypt && client->GetCredential))))
{
if (!subAuth && client->clientAuthSchemes)
{
int i;
for (i=0;client->clientAuthSchemes[i];i++)
{
if (client->clientAuthSchemes[i]==(uint32_t)tAuth[loop])
{
flag++;
authScheme=tAuth[loop];
break;
}
}
}
else
{
flag++;
authScheme=tAuth[loop];
}
if (flag)
{
rfbClientLog("Selecting security type %d (%d/%d in the list)\n", authScheme, loop, count);
/* send back a single byte indicating which security type to use */
if (!WriteToRFBServer(client, (char *)&tAuth[loop], 1)) return FALSE;
}
}
}
if (authScheme==0)
{
memset(buf1, 0, sizeof(buf1));
for (loop=0;loop<count;loop++)
{
if (strlen(buf1)>=sizeof(buf1)-1) break;
snprintf(buf2, sizeof(buf2), (loop>0 ? ", %d" : "%d"), (int)tAuth[loop]);
strncat(buf1, buf2, sizeof(buf1)-strlen(buf1)-1);
}
rfbClientLog("Unknown authentication scheme from VNC server: %s\n",
buf1);
return FALSE;
}
*result = authScheme;
return TRUE;
}
static rfbBool
HandleVncAuth(rfbClient *client)
{
uint8_t challenge[CHALLENGESIZE];
char *passwd=NULL;
int i;
if (!ReadFromRFBServer(client, (char *)challenge, CHALLENGESIZE)) return FALSE;
if (client->serverPort!=-1) { /* if not playing a vncrec file */
if (client->GetPassword)
passwd = client->GetPassword(client);
if ((!passwd) || (strlen(passwd) == 0)) {
rfbClientLog("Reading password failed\n");
return FALSE;
}
if (strlen(passwd) > 8) {
passwd[8] = '\0';
}
rfbClientEncryptBytes(challenge, passwd);
/* Lose the password from memory */
for (i = strlen(passwd); i >= 0; i--) {
passwd[i] = '\0';
}
free(passwd);
if (!WriteToRFBServer(client, (char *)challenge, CHALLENGESIZE)) return FALSE;
}
/* Handle the SecurityResult message */
if (!rfbHandleAuthResult(client)) return FALSE;
return TRUE;
}
static void
FreeUserCredential(rfbCredential *cred)
{
if (cred->userCredential.username) free(cred->userCredential.username);
if (cred->userCredential.password) free(cred->userCredential.password);
free(cred);
}
static rfbBool
HandlePlainAuth(rfbClient *client)
{
uint32_t ulen, ulensw;
uint32_t plen, plensw;
rfbCredential *cred;
if (!client->GetCredential)
{
rfbClientLog("GetCredential callback is not set.\n");
return FALSE;
}
cred = client->GetCredential(client, rfbCredentialTypeUser);
if (!cred)
{
rfbClientLog("Reading credential failed\n");
return FALSE;
}
ulen = (cred->userCredential.username ? strlen(cred->userCredential.username) : 0);
ulensw = rfbClientSwap32IfLE(ulen);
plen = (cred->userCredential.password ? strlen(cred->userCredential.password) : 0);
plensw = rfbClientSwap32IfLE(plen);
if (!WriteToRFBServer(client, (char *)&ulensw, 4) ||
!WriteToRFBServer(client, (char *)&plensw, 4))
{
FreeUserCredential(cred);
return FALSE;
}
if (ulen > 0)
{
if (!WriteToRFBServer(client, cred->userCredential.username, ulen))
{
FreeUserCredential(cred);
return FALSE;
}
}
if (plen > 0)
{
if (!WriteToRFBServer(client, cred->userCredential.password, plen))
{
FreeUserCredential(cred);
return FALSE;
}
}
FreeUserCredential(cred);
/* Handle the SecurityResult message */
if (!rfbHandleAuthResult(client)) return FALSE;
return TRUE;
}
/* Simple 64bit big integer arithmetic implementation */
/* (x + y) % m, works even if (x + y) > 64bit */
#define rfbAddM64(x,y,m) ((x+y)%m+(x+y<x?(((uint64_t)-1)%m+1)%m:0))
/* (x * y) % m */
static uint64_t
rfbMulM64(uint64_t x, uint64_t y, uint64_t m)
{
uint64_t r;
for(r=0;x>0;x>>=1)
{
if (x&1) r=rfbAddM64(r,y,m);
y=rfbAddM64(y,y,m);
}
return r;
}
/* (x ^ y) % m */
static uint64_t
rfbPowM64(uint64_t b, uint64_t e, uint64_t m)
{
uint64_t r;
for(r=1;e>0;e>>=1)
{
if(e&1) r=rfbMulM64(r,b,m);
b=rfbMulM64(b,b,m);
}
return r;
}
static rfbBool
HandleMSLogonAuth(rfbClient *client)
{
uint64_t gen, mod, resp, priv, pub, key;
uint8_t username[256], password[64];
rfbCredential *cred;
if (!ReadFromRFBServer(client, (char *)&gen, 8)) return FALSE;
if (!ReadFromRFBServer(client, (char *)&mod, 8)) return FALSE;
if (!ReadFromRFBServer(client, (char *)&resp, 8)) return FALSE;
gen = rfbClientSwap64IfLE(gen);
mod = rfbClientSwap64IfLE(mod);
resp = rfbClientSwap64IfLE(resp);
if (!client->GetCredential)
{
rfbClientLog("GetCredential callback is not set.\n");
return FALSE;
}
rfbClientLog("WARNING! MSLogon security type has very low password encryption! "\
"Use it only with SSH tunnel or trusted network.\n");
cred = client->GetCredential(client, rfbCredentialTypeUser);
if (!cred)
{
rfbClientLog("Reading credential failed\n");
return FALSE;
}
memset(username, 0, sizeof(username));
strncpy((char *)username, cred->userCredential.username, sizeof(username));
memset(password, 0, sizeof(password));
strncpy((char *)password, cred->userCredential.password, sizeof(password));
FreeUserCredential(cred);
srand(time(NULL));
priv = ((uint64_t)rand())<<32;
priv |= (uint64_t)rand();
pub = rfbPowM64(gen, priv, mod);
key = rfbPowM64(resp, priv, mod);
pub = rfbClientSwap64IfLE(pub);
key = rfbClientSwap64IfLE(key);
rfbClientEncryptBytes2(username, sizeof(username), (unsigned char *)&key);
rfbClientEncryptBytes2(password, sizeof(password), (unsigned char *)&key);
if (!WriteToRFBServer(client, (char *)&pub, 8)) return FALSE;
if (!WriteToRFBServer(client, (char *)username, sizeof(username))) return FALSE;
if (!WriteToRFBServer(client, (char *)password, sizeof(password))) return FALSE;
/* Handle the SecurityResult message */
if (!rfbHandleAuthResult(client)) return FALSE;
return TRUE;
}
#ifdef LIBVNCSERVER_WITH_CLIENT_GCRYPT
static rfbBool
rfbMpiToBytes(const gcry_mpi_t value, uint8_t *result, size_t size)
{
gcry_error_t error;
size_t len;
int i;
error = gcry_mpi_print(GCRYMPI_FMT_USG, result, size, &len, value);
if (gcry_err_code(error) != GPG_ERR_NO_ERROR)
{
rfbClientLog("gcry_mpi_print error: %s\n", gcry_strerror(error));
return FALSE;
}
for (i=size-1;i>(int)size-1-(int)len;--i)
result[i] = result[i-size+len];
for (;i>=0;--i)
result[i] = 0;
return TRUE;
}
static rfbBool
HandleARDAuth(rfbClient *client)
{
uint8_t gen[2], len[2];
size_t keylen;
uint8_t *mod = NULL, *resp, *pub, *key, *shared;
gcry_mpi_t genmpi = NULL, modmpi = NULL, respmpi = NULL;
gcry_mpi_t privmpi = NULL, pubmpi = NULL, keympi = NULL;
gcry_md_hd_t md5 = NULL;
gcry_cipher_hd_t aes = NULL;
gcry_error_t error;
uint8_t userpass[128], ciphertext[128];
int passwordLen, usernameLen;
rfbCredential *cred = NULL;
rfbBool result = FALSE;
if (!gcry_control(GCRYCTL_INITIALIZATION_FINISHED_P))
{
/* Application did not initialize gcrypt, so we should */
if (!gcry_check_version(GCRYPT_VERSION))
{
/* Older version of libgcrypt is installed on system than compiled against */
rfbClientLog("libgcrypt version mismatch.\n");
}
}
while (1)
{
if (!ReadFromRFBServer(client, (char *)gen, 2))
break;
if (!ReadFromRFBServer(client, (char *)len, 2))
break;
if (!client->GetCredential)
{
rfbClientLog("GetCredential callback is not set.\n");
break;
}
cred = client->GetCredential(client, rfbCredentialTypeUser);
if (!cred)
{
rfbClientLog("Reading credential failed\n");
break;
}
keylen = 256*len[0]+len[1];
mod = (uint8_t*)malloc(keylen*4);
if (!mod)
{
rfbClientLog("malloc out of memory\n");
break;
}
resp = mod+keylen;
pub = resp+keylen;
key = pub+keylen;
if (!ReadFromRFBServer(client, (char *)mod, keylen))
break;
if (!ReadFromRFBServer(client, (char *)resp, keylen))
break;
error = gcry_mpi_scan(&genmpi, GCRYMPI_FMT_USG, gen, 2, NULL);
if (gcry_err_code(error) != GPG_ERR_NO_ERROR)
{
rfbClientLog("gcry_mpi_scan error: %s\n", gcry_strerror(error));
break;
}
error = gcry_mpi_scan(&modmpi, GCRYMPI_FMT_USG, mod, keylen, NULL);
if (gcry_err_code(error) != GPG_ERR_NO_ERROR)
{
rfbClientLog("gcry_mpi_scan error: %s\n", gcry_strerror(error));
break;
}
error = gcry_mpi_scan(&respmpi, GCRYMPI_FMT_USG, resp, keylen, NULL);
if (gcry_err_code(error) != GPG_ERR_NO_ERROR)
{
rfbClientLog("gcry_mpi_scan error: %s\n", gcry_strerror(error));
break;
}
privmpi = gcry_mpi_new(keylen);
if (!privmpi)
{
rfbClientLog("gcry_mpi_new out of memory\n");
break;
}
gcry_mpi_randomize(privmpi, (keylen/8)*8, GCRY_STRONG_RANDOM);
pubmpi = gcry_mpi_new(keylen);
if (!pubmpi)
{
rfbClientLog("gcry_mpi_new out of memory\n");
break;
}
gcry_mpi_powm(pubmpi, genmpi, privmpi, modmpi);
keympi = gcry_mpi_new(keylen);
if (!keympi)
{
rfbClientLog("gcry_mpi_new out of memory\n");
break;
}
gcry_mpi_powm(keympi, respmpi, privmpi, modmpi);
if (!rfbMpiToBytes(pubmpi, pub, keylen))
break;
if (!rfbMpiToBytes(keympi, key, keylen))
break;
error = gcry_md_open(&md5, GCRY_MD_MD5, 0);
if (gcry_err_code(error) != GPG_ERR_NO_ERROR)
{
rfbClientLog("gcry_md_open error: %s\n", gcry_strerror(error));
break;
}
gcry_md_write(md5, key, keylen);
error = gcry_md_final(md5);
if (gcry_err_code(error) != GPG_ERR_NO_ERROR)
{
rfbClientLog("gcry_md_final error: %s\n", gcry_strerror(error));
break;
}
shared = gcry_md_read(md5, GCRY_MD_MD5);
passwordLen = strlen(cred->userCredential.password)+1;
usernameLen = strlen(cred->userCredential.username)+1;
if (passwordLen > sizeof(userpass)/2)
passwordLen = sizeof(userpass)/2;
if (usernameLen > sizeof(userpass)/2)
usernameLen = sizeof(userpass)/2;
gcry_randomize(userpass, sizeof(userpass), GCRY_STRONG_RANDOM);
memcpy(userpass, cred->userCredential.username, usernameLen);
memcpy(userpass+sizeof(userpass)/2, cred->userCredential.password, passwordLen);
error = gcry_cipher_open(&aes, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_ECB, 0);
if (gcry_err_code(error) != GPG_ERR_NO_ERROR)
{
rfbClientLog("gcry_cipher_open error: %s\n", gcry_strerror(error));
break;
}
error = gcry_cipher_setkey(aes, shared, 16);
if (gcry_err_code(error) != GPG_ERR_NO_ERROR)
{
rfbClientLog("gcry_cipher_setkey error: %s\n", gcry_strerror(error));
break;
}
error = gcry_cipher_encrypt(aes, ciphertext, sizeof(ciphertext), userpass, sizeof(userpass));
if (gcry_err_code(error) != GPG_ERR_NO_ERROR)
{
rfbClientLog("gcry_cipher_encrypt error: %s\n", gcry_strerror(error));
break;
}
if (!WriteToRFBServer(client, (char *)ciphertext, sizeof(ciphertext)))
break;
if (!WriteToRFBServer(client, (char *)pub, keylen))
break;
/* Handle the SecurityResult message */
if (!rfbHandleAuthResult(client))
break;
result = TRUE;
break;
}
if (cred)
FreeUserCredential(cred);
if (mod)
free(mod);
if (genmpi)
gcry_mpi_release(genmpi);
if (modmpi)
gcry_mpi_release(modmpi);
if (respmpi)
gcry_mpi_release(respmpi);
if (privmpi)
gcry_mpi_release(privmpi);
if (pubmpi)
gcry_mpi_release(pubmpi);
if (keympi)
gcry_mpi_release(keympi);
if (md5)
gcry_md_close(md5);
if (aes)
gcry_cipher_close(aes);
return result;
}
#endif
/*
* SetClientAuthSchemes.
*/
void
SetClientAuthSchemes(rfbClient* client,const uint32_t *authSchemes, int size)
{
int i;
if (client->clientAuthSchemes)
{
free(client->clientAuthSchemes);
client->clientAuthSchemes = NULL;
}
if (authSchemes)
{
if (size<0)
{
/* If size<0 we assume the passed-in list is also 0-terminate, so we
* calculate the size here */
for (size=0;authSchemes[size];size++) ;
}
client->clientAuthSchemes = (uint32_t*)malloc(sizeof(uint32_t)*(size+1));
for (i=0;i<size;i++)
client->clientAuthSchemes[i] = authSchemes[i];
client->clientAuthSchemes[size] = 0;
}
}
/*
* InitialiseRFBConnection.
*/
rfbBool
InitialiseRFBConnection(rfbClient* client)
{
rfbProtocolVersionMsg pv;
int major,minor;
uint32_t authScheme;
uint32_t subAuthScheme;
rfbClientInitMsg ci;
/* if the connection is immediately closed, don't report anything, so
that pmw's monitor can make test connections */
if (client->listenSpecified)
errorMessageOnReadFailure = FALSE;
if (!ReadFromRFBServer(client, pv, sz_rfbProtocolVersionMsg)) return FALSE;
pv[sz_rfbProtocolVersionMsg]=0;
errorMessageOnReadFailure = TRUE;
pv[sz_rfbProtocolVersionMsg] = 0;
if (sscanf(pv,rfbProtocolVersionFormat,&major,&minor) != 2) {
rfbClientLog("Not a valid VNC server (%s)\n",pv);
return FALSE;
}
DefaultSupportedMessages(client);
client->major = major;
client->minor = minor;
/* fall back to viewer supported version */
if ((major==rfbProtocolMajorVersion) && (minor>rfbProtocolMinorVersion))
client->minor = rfbProtocolMinorVersion;
/* UltraVNC uses minor codes 4 and 6 for the server */
if (major==3 && (minor==4 || minor==6)) {
rfbClientLog("UltraVNC server detected, enabling UltraVNC specific messages\n",pv);
DefaultSupportedMessagesUltraVNC(client);
}
/* UltraVNC Single Click uses minor codes 14 and 16 for the server */
if (major==3 && (minor==14 || minor==16)) {
minor = minor - 10;
client->minor = minor;
rfbClientLog("UltraVNC Single Click server detected, enabling UltraVNC specific messages\n",pv);
DefaultSupportedMessagesUltraVNC(client);
}
/* TightVNC uses minor codes 5 for the server */
if (major==3 && minor==5) {
rfbClientLog("TightVNC server detected, enabling TightVNC specific messages\n",pv);
DefaultSupportedMessagesTightVNC(client);
}
/* we do not support > RFB3.8 */
if ((major==3 && minor>8) || major>3)
{
client->major=3;
client->minor=8;
}
rfbClientLog("VNC server supports protocol version %d.%d (viewer %d.%d)\n",
major, minor, rfbProtocolMajorVersion, rfbProtocolMinorVersion);
sprintf(pv,rfbProtocolVersionFormat,client->major,client->minor);
if (!WriteToRFBServer(client, pv, sz_rfbProtocolVersionMsg)) return FALSE;
/* 3.7 and onwards sends a # of security types first */
if (client->major==3 && client->minor > 6)
{
if (!ReadSupportedSecurityType(client, &authScheme, FALSE)) return FALSE;
}
else
{
if (!ReadFromRFBServer(client, (char *)&authScheme, 4)) return FALSE;
authScheme = rfbClientSwap32IfLE(authScheme);
}
rfbClientLog("Selected Security Scheme %d\n", authScheme);
client->authScheme = authScheme;
switch (authScheme) {
case rfbConnFailed:
ReadReason(client);
return FALSE;
case rfbNoAuth:
rfbClientLog("No authentication needed\n");
/* 3.8 and upwards sends a Security Result for rfbNoAuth */
if ((client->major==3 && client->minor > 7) || client->major>3)
if (!rfbHandleAuthResult(client)) return FALSE;
break;
case rfbVncAuth:
if (!HandleVncAuth(client)) return FALSE;
break;
#ifdef LIBVNCSERVER_HAVE_SASL
case rfbSASL:
if (!HandleSASLAuth(client)) return FALSE;
break;
#endif /* LIBVNCSERVER_HAVE_SASL */
case rfbMSLogon:
if (!HandleMSLogonAuth(client)) return FALSE;
break;
case rfbARD:
#ifndef LIBVNCSERVER_WITH_CLIENT_GCRYPT
rfbClientLog("GCrypt support was not compiled in\n");
return FALSE;
#else
if (!HandleARDAuth(client)) return FALSE;
#endif
break;
case rfbTLS:
if (!HandleAnonTLSAuth(client)) return FALSE;
/* After the TLS session is established, sub auth types are expected.
* Note that all following reading/writing are through the TLS session from here.
*/
if (!ReadSupportedSecurityType(client, &subAuthScheme, TRUE)) return FALSE;
client->subAuthScheme = subAuthScheme;
switch (subAuthScheme) {
case rfbConnFailed:
ReadReason(client);
return FALSE;
case rfbNoAuth:
rfbClientLog("No sub authentication needed\n");
/* 3.8 and upwards sends a Security Result for rfbNoAuth */
if ((client->major==3 && client->minor > 7) || client->major>3)
if (!rfbHandleAuthResult(client)) return FALSE;
break;
case rfbVncAuth:
if (!HandleVncAuth(client)) return FALSE;
break;
#ifdef LIBVNCSERVER_HAVE_SASL
case rfbSASL:
if (!HandleSASLAuth(client)) return FALSE;
break;
#endif /* LIBVNCSERVER_HAVE_SASL */
default:
rfbClientLog("Unknown sub authentication scheme from VNC server: %d\n",
(int)subAuthScheme);
return FALSE;
}
break;
case rfbVeNCrypt:
if (!HandleVeNCryptAuth(client)) return FALSE;
switch (client->subAuthScheme) {
case rfbVeNCryptTLSNone:
case rfbVeNCryptX509None:
rfbClientLog("No sub authentication needed\n");
if (!rfbHandleAuthResult(client)) return FALSE;
break;
case rfbVeNCryptTLSVNC:
case rfbVeNCryptX509VNC:
if (!HandleVncAuth(client)) return FALSE;
break;
case rfbVeNCryptTLSPlain:
case rfbVeNCryptX509Plain:
if (!HandlePlainAuth(client)) return FALSE;
break;
#ifdef LIBVNCSERVER_HAVE_SASL
case rfbVeNCryptX509SASL:
case rfbVeNCryptTLSSASL:
if (!HandleSASLAuth(client)) return FALSE;
break;
#endif /* LIBVNCSERVER_HAVE_SASL */
default:
rfbClientLog("Unknown sub authentication scheme from VNC server: %d\n",
client->subAuthScheme);
return FALSE;
}
break;
default:
{
rfbBool authHandled=FALSE;
rfbClientProtocolExtension* e;
for (e = rfbClientExtensions; e; e = e->next) {
uint32_t const* secType;
if (!e->handleAuthentication) continue;
for (secType = e->securityTypes; secType && *secType; secType++) {
if (authScheme==*secType) {
if (!e->handleAuthentication(client, authScheme)) return FALSE;
if (!rfbHandleAuthResult(client)) return FALSE;
authHandled=TRUE;
}
}
}
if (authHandled) break;
}
rfbClientLog("Unknown authentication scheme from VNC server: %d\n",
(int)authScheme);
return FALSE;
}
ci.shared = (client->appData.shareDesktop ? 1 : 0);
if (!WriteToRFBServer(client, (char *)&ci, sz_rfbClientInitMsg)) return FALSE;
if (!ReadFromRFBServer(client, (char *)&client->si, sz_rfbServerInitMsg)) return FALSE;
client->si.framebufferWidth = rfbClientSwap16IfLE(client->si.framebufferWidth);
client->si.framebufferHeight = rfbClientSwap16IfLE(client->si.framebufferHeight);
client->si.format.redMax = rfbClientSwap16IfLE(client->si.format.redMax);
client->si.format.greenMax = rfbClientSwap16IfLE(client->si.format.greenMax);
client->si.format.blueMax = rfbClientSwap16IfLE(client->si.format.blueMax);
client->si.nameLength = rfbClientSwap32IfLE(client->si.nameLength);
if (client->si.nameLength > 1<<20) {
rfbClientErr("Too big desktop name length sent by server: %u B > 1 MB\n", (unsigned int)client->si.nameLength);
return FALSE;
}
client->desktopName = malloc(client->si.nameLength + 1);
if (!client->desktopName) {
rfbClientLog("Error allocating memory for desktop name, %lu bytes\n",
(unsigned long)client->si.nameLength);
return FALSE;
}
if (!ReadFromRFBServer(client, client->desktopName, client->si.nameLength)) return FALSE;
client->desktopName[client->si.nameLength] = 0;
rfbClientLog("Desktop name \"%s\"\n",client->desktopName);
rfbClientLog("Connected to VNC server, using protocol version %d.%d\n",
client->major, client->minor);
rfbClientLog("VNC server default format:\n");
PrintPixelFormat(&client->si.format);
return TRUE;
}
/*
* SetFormatAndEncodings.
*/
rfbBool
SetFormatAndEncodings(rfbClient* client)
{
rfbSetPixelFormatMsg spf;
char buf[sz_rfbSetEncodingsMsg + MAX_ENCODINGS * 4];
rfbSetEncodingsMsg *se = (rfbSetEncodingsMsg *)buf;
uint32_t *encs = (uint32_t *)(&buf[sz_rfbSetEncodingsMsg]);
int len = 0;
rfbBool requestCompressLevel = FALSE;
rfbBool requestQualityLevel = FALSE;
rfbBool requestLastRectEncoding = FALSE;
rfbClientProtocolExtension* e;
if (!SupportsClient2Server(client, rfbSetPixelFormat)) return TRUE;
spf.type = rfbSetPixelFormat;
spf.pad1 = 0;
spf.pad2 = 0;
spf.format = client->format;
spf.format.redMax = rfbClientSwap16IfLE(spf.format.redMax);
spf.format.greenMax = rfbClientSwap16IfLE(spf.format.greenMax);
spf.format.blueMax = rfbClientSwap16IfLE(spf.format.blueMax);
if (!WriteToRFBServer(client, (char *)&spf, sz_rfbSetPixelFormatMsg))
return FALSE;
if (!SupportsClient2Server(client, rfbSetEncodings)) return TRUE;
se->type = rfbSetEncodings;
se->pad = 0;
se->nEncodings = 0;
if (client->appData.encodingsString) {
const char *encStr = client->appData.encodingsString;
int encStrLen;
do {
const char *nextEncStr = strchr(encStr, ' ');
if (nextEncStr) {
encStrLen = nextEncStr - encStr;
nextEncStr++;
} else {
encStrLen = strlen(encStr);
}
if (strncasecmp(encStr,"raw",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRaw);
} else if (strncasecmp(encStr,"copyrect",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCopyRect);
#ifdef LIBVNCSERVER_HAVE_LIBZ
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
} else if (strncasecmp(encStr,"tight",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingTight);
requestLastRectEncoding = TRUE;
if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9)
requestCompressLevel = TRUE;
if (client->appData.enableJPEG)
requestQualityLevel = TRUE;
#endif
#endif
} else if (strncasecmp(encStr,"hextile",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingHextile);
#ifdef LIBVNCSERVER_HAVE_LIBZ
} else if (strncasecmp(encStr,"zlib",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZlib);
if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9)
requestCompressLevel = TRUE;
} else if (strncasecmp(encStr,"zlibhex",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZlibHex);
if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9)
requestCompressLevel = TRUE;
} else if (strncasecmp(encStr,"trle",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingTRLE);
} else if (strncasecmp(encStr,"zrle",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZRLE);
} else if (strncasecmp(encStr,"zywrle",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZYWRLE);
requestQualityLevel = TRUE;
#endif
} else if ((strncasecmp(encStr,"ultra",encStrLen) == 0) || (strncasecmp(encStr,"ultrazip",encStrLen) == 0)) {
/* There are 2 encodings used in 'ultra' */
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltra);
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltraZip);
} else if (strncasecmp(encStr,"corre",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCoRRE);
} else if (strncasecmp(encStr,"rre",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRRE);
} else {
rfbClientLog("Unknown encoding '%.*s'\n",encStrLen,encStr);
}
encStr = nextEncStr;
} while (encStr && se->nEncodings < MAX_ENCODINGS);
if (se->nEncodings < MAX_ENCODINGS && requestCompressLevel) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.compressLevel +
rfbEncodingCompressLevel0);
}
if (se->nEncodings < MAX_ENCODINGS && requestQualityLevel) {
if (client->appData.qualityLevel < 0 || client->appData.qualityLevel > 9)
client->appData.qualityLevel = 5;
encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.qualityLevel +
rfbEncodingQualityLevel0);
}
}
else {
if (SameMachine(client->sock)) {
/* TODO:
if (!tunnelSpecified) {
*/
rfbClientLog("Same machine: preferring raw encoding\n");
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRaw);
/*
} else {
rfbClientLog("Tunneling active: preferring tight encoding\n");
}
*/
}
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCopyRect);
#ifdef LIBVNCSERVER_HAVE_LIBZ
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingTight);
requestLastRectEncoding = TRUE;
#endif
#endif
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingHextile);
#ifdef LIBVNCSERVER_HAVE_LIBZ
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZlib);
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZRLE);
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZYWRLE);
#endif
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltra);
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltraZip);
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCoRRE);
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRRE);
if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.compressLevel +
rfbEncodingCompressLevel0);
} else /* if (!tunnelSpecified) */ {
/* If -tunnel option was provided, we assume that server machine is
not in the local network so we use default compression level for
tight encoding instead of fast compression. Thus we are
requesting level 1 compression only if tunneling is not used. */
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCompressLevel1);
}
if (client->appData.enableJPEG) {
if (client->appData.qualityLevel < 0 || client->appData.qualityLevel > 9)
client->appData.qualityLevel = 5;
encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.qualityLevel +
rfbEncodingQualityLevel0);
}
}
/* Remote Cursor Support (local to viewer) */
if (client->appData.useRemoteCursor) {
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingXCursor);
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRichCursor);
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingPointerPos);
}
/* Keyboard State Encodings */
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingKeyboardLedState);
/* New Frame Buffer Size */
if (se->nEncodings < MAX_ENCODINGS && client->canHandleNewFBSize)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingNewFBSize);
/* Last Rect */
if (se->nEncodings < MAX_ENCODINGS && requestLastRectEncoding)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingLastRect);
/* Server Capabilities */
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingSupportedMessages);
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingSupportedEncodings);
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingServerIdentity);
/* xvp */
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingXvp);
/* client extensions */
for(e = rfbClientExtensions; e; e = e->next)
if(e->encodings) {
int* enc;
for(enc = e->encodings; *enc; enc++)
if(se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(*enc);
}
len = sz_rfbSetEncodingsMsg + se->nEncodings * 4;
se->nEncodings = rfbClientSwap16IfLE(se->nEncodings);
if (!WriteToRFBServer(client, buf, len)) return FALSE;
return TRUE;
}
/*
* SendIncrementalFramebufferUpdateRequest.
*/
rfbBool
SendIncrementalFramebufferUpdateRequest(rfbClient* client)
{
return SendFramebufferUpdateRequest(client,
client->updateRect.x, client->updateRect.y,
client->updateRect.w, client->updateRect.h, TRUE);
}
/*
* SendFramebufferUpdateRequest.
*/
rfbBool
SendFramebufferUpdateRequest(rfbClient* client, int x, int y, int w, int h, rfbBool incremental)
{
rfbFramebufferUpdateRequestMsg fur;
if (!SupportsClient2Server(client, rfbFramebufferUpdateRequest)) return TRUE;
fur.type = rfbFramebufferUpdateRequest;
fur.incremental = incremental ? 1 : 0;
fur.x = rfbClientSwap16IfLE(x);
fur.y = rfbClientSwap16IfLE(y);
fur.w = rfbClientSwap16IfLE(w);
fur.h = rfbClientSwap16IfLE(h);
if (!WriteToRFBServer(client, (char *)&fur, sz_rfbFramebufferUpdateRequestMsg))
return FALSE;
return TRUE;
}
/*
* SendScaleSetting.
*/
rfbBool
SendScaleSetting(rfbClient* client,int scaleSetting)
{
rfbSetScaleMsg ssm;
ssm.scale = scaleSetting;
ssm.pad = 0;
/* favor UltraVNC SetScale if both are supported */
if (SupportsClient2Server(client, rfbSetScale)) {
ssm.type = rfbSetScale;
if (!WriteToRFBServer(client, (char *)&ssm, sz_rfbSetScaleMsg))
return FALSE;
}
if (SupportsClient2Server(client, rfbPalmVNCSetScaleFactor)) {
ssm.type = rfbPalmVNCSetScaleFactor;
if (!WriteToRFBServer(client, (char *)&ssm, sz_rfbSetScaleMsg))
return FALSE;
}
return TRUE;
}
/*
* TextChatFunctions (UltraVNC)
* Extremely bandwidth friendly method of communicating with a user
* (Think HelpDesk type applications)
*/
rfbBool TextChatSend(rfbClient* client, char *text)
{
rfbTextChatMsg chat;
int count = strlen(text);
if (!SupportsClient2Server(client, rfbTextChat)) return TRUE;
chat.type = rfbTextChat;
chat.pad1 = 0;
chat.pad2 = 0;
chat.length = (uint32_t)count;
chat.length = rfbClientSwap32IfLE(chat.length);
if (!WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg))
return FALSE;
if (count>0) {
if (!WriteToRFBServer(client, text, count))
return FALSE;
}
return TRUE;
}
rfbBool TextChatOpen(rfbClient* client)
{
rfbTextChatMsg chat;
if (!SupportsClient2Server(client, rfbTextChat)) return TRUE;
chat.type = rfbTextChat;
chat.pad1 = 0;
chat.pad2 = 0;
chat.length = rfbClientSwap32IfLE(rfbTextChatOpen);
return (WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg) ? TRUE : FALSE);
}
rfbBool TextChatClose(rfbClient* client)
{
rfbTextChatMsg chat;
if (!SupportsClient2Server(client, rfbTextChat)) return TRUE;
chat.type = rfbTextChat;
chat.pad1 = 0;
chat.pad2 = 0;
chat.length = rfbClientSwap32IfLE(rfbTextChatClose);
return (WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg) ? TRUE : FALSE);
}
rfbBool TextChatFinish(rfbClient* client)
{
rfbTextChatMsg chat;
if (!SupportsClient2Server(client, rfbTextChat)) return TRUE;
chat.type = rfbTextChat;
chat.pad1 = 0;
chat.pad2 = 0;
chat.length = rfbClientSwap32IfLE(rfbTextChatFinished);
return (WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg) ? TRUE : FALSE);
}
/*
* UltraVNC Server Input Disable
* Apparently, the remote client can *prevent* the local user from interacting with the display
* I would think this is extremely helpful when used in a HelpDesk situation
*/
rfbBool PermitServerInput(rfbClient* client, int enabled)
{
rfbSetServerInputMsg msg;
if (!SupportsClient2Server(client, rfbSetServerInput)) return TRUE;
/* enabled==1, then server input from local keyboard is disabled */
msg.type = rfbSetServerInput;
msg.status = (enabled ? 1 : 0);
msg.pad = 0;
return (WriteToRFBServer(client, (char *)&msg, sz_rfbSetServerInputMsg) ? TRUE : FALSE);
}
/*
* send xvp client message
* A client supporting the xvp extension sends this to request that the server initiate
* a clean shutdown, clean reboot or abrupt reset of the system whose framebuffer the
* client is displaying.
*
* only version 1 is defined in the protocol specs
*
* possible values for code are:
* rfbXvp_Shutdown
* rfbXvp_Reboot
* rfbXvp_Reset
*/
rfbBool SendXvpMsg(rfbClient* client, uint8_t version, uint8_t code)
{
rfbXvpMsg xvp;
if (!SupportsClient2Server(client, rfbXvp)) return TRUE;
xvp.type = rfbXvp;
xvp.pad = 0;
xvp.version = version;
xvp.code = code;
if (!WriteToRFBServer(client, (char *)&xvp, sz_rfbXvpMsg))
return FALSE;
return TRUE;
}
/*
* SendPointerEvent.
*/
rfbBool
SendPointerEvent(rfbClient* client,int x, int y, int buttonMask)
{
rfbPointerEventMsg pe;
if (!SupportsClient2Server(client, rfbPointerEvent)) return TRUE;
pe.type = rfbPointerEvent;
pe.buttonMask = buttonMask;
if (x < 0) x = 0;
if (y < 0) y = 0;
pe.x = rfbClientSwap16IfLE(x);
pe.y = rfbClientSwap16IfLE(y);
return WriteToRFBServer(client, (char *)&pe, sz_rfbPointerEventMsg);
}
/*
* SendKeyEvent.
*/
rfbBool
SendKeyEvent(rfbClient* client, uint32_t key, rfbBool down)
{
rfbKeyEventMsg ke;
if (!SupportsClient2Server(client, rfbKeyEvent)) return TRUE;
memset(&ke, 0, sizeof(ke));
ke.type = rfbKeyEvent;
ke.down = down ? 1 : 0;
ke.key = rfbClientSwap32IfLE(key);
return WriteToRFBServer(client, (char *)&ke, sz_rfbKeyEventMsg);
}
/*
* SendClientCutText.
*/
rfbBool
SendClientCutText(rfbClient* client, char *str, int len)
{
rfbClientCutTextMsg cct;
if (!SupportsClient2Server(client, rfbClientCutText)) return TRUE;
memset(&cct, 0, sizeof(cct));
cct.type = rfbClientCutText;
cct.length = rfbClientSwap32IfLE(len);
return (WriteToRFBServer(client, (char *)&cct, sz_rfbClientCutTextMsg) &&
WriteToRFBServer(client, str, len));
}
/*
* HandleRFBServerMessage.
*/
rfbBool
HandleRFBServerMessage(rfbClient* client)
{
rfbServerToClientMsg msg;
if (client->serverPort==-1)
client->vncRec->readTimestamp = TRUE;
if (!ReadFromRFBServer(client, (char *)&msg, 1))
return FALSE;
switch (msg.type) {
case rfbSetColourMapEntries:
{
/* TODO:
int i;
uint16_t rgb[3];
XColor xc;
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbSetColourMapEntriesMsg - 1))
return FALSE;
msg.scme.firstColour = rfbClientSwap16IfLE(msg.scme.firstColour);
msg.scme.nColours = rfbClientSwap16IfLE(msg.scme.nColours);
for (i = 0; i < msg.scme.nColours; i++) {
if (!ReadFromRFBServer(client, (char *)rgb, 6))
return FALSE;
xc.pixel = msg.scme.firstColour + i;
xc.red = rfbClientSwap16IfLE(rgb[0]);
xc.green = rfbClientSwap16IfLE(rgb[1]);
xc.blue = rfbClientSwap16IfLE(rgb[2]);
xc.flags = DoRed|DoGreen|DoBlue;
XStoreColor(dpy, cmap, &xc);
}
*/
break;
}
case rfbFramebufferUpdate:
{
rfbFramebufferUpdateRectHeader rect;
int linesToRead;
int bytesPerLine;
int i;
if (!ReadFromRFBServer(client, ((char *)&msg.fu) + 1,
sz_rfbFramebufferUpdateMsg - 1))
return FALSE;
msg.fu.nRects = rfbClientSwap16IfLE(msg.fu.nRects);
for (i = 0; i < msg.fu.nRects; i++) {
if (!ReadFromRFBServer(client, (char *)&rect, sz_rfbFramebufferUpdateRectHeader))
return FALSE;
rect.encoding = rfbClientSwap32IfLE(rect.encoding);
if (rect.encoding == rfbEncodingLastRect)
break;
rect.r.x = rfbClientSwap16IfLE(rect.r.x);
rect.r.y = rfbClientSwap16IfLE(rect.r.y);
rect.r.w = rfbClientSwap16IfLE(rect.r.w);
rect.r.h = rfbClientSwap16IfLE(rect.r.h);
if (rect.encoding == rfbEncodingXCursor ||
rect.encoding == rfbEncodingRichCursor) {
if (!HandleCursorShape(client,
rect.r.x, rect.r.y, rect.r.w, rect.r.h,
rect.encoding)) {
return FALSE;
}
continue;
}
if (rect.encoding == rfbEncodingPointerPos) {
if (!client->HandleCursorPos(client,rect.r.x, rect.r.y)) {
return FALSE;
}
continue;
}
if (rect.encoding == rfbEncodingKeyboardLedState) {
/* OK! We have received a keyboard state message!!! */
client->KeyboardLedStateEnabled = 1;
if (client->HandleKeyboardLedState!=NULL)
client->HandleKeyboardLedState(client, rect.r.x, 0);
/* stash it for the future */
client->CurrentKeyboardLedState = rect.r.x;
continue;
}
if (rect.encoding == rfbEncodingNewFBSize) {
client->width = rect.r.w;
client->height = rect.r.h;
client->updateRect.x = client->updateRect.y = 0;
client->updateRect.w = client->width;
client->updateRect.h = client->height;
if (!client->MallocFrameBuffer(client))
return FALSE;
SendFramebufferUpdateRequest(client, 0, 0, rect.r.w, rect.r.h, FALSE);
rfbClientLog("Got new framebuffer size: %dx%d\n", rect.r.w, rect.r.h);
continue;
}
/* rect.r.w=byte count */
if (rect.encoding == rfbEncodingSupportedMessages) {
int loop;
if (!ReadFromRFBServer(client, (char *)&client->supportedMessages, sz_rfbSupportedMessages))
return FALSE;
/* msgs is two sets of bit flags of supported messages client2server[] and server2client[] */
/* currently ignored by this library */
rfbClientLog("client2server supported messages (bit flags)\n");
for (loop=0;loop<32;loop+=8)
rfbClientLog("%02X: %04x %04x %04x %04x - %04x %04x %04x %04x\n", loop,
client->supportedMessages.client2server[loop], client->supportedMessages.client2server[loop+1],
client->supportedMessages.client2server[loop+2], client->supportedMessages.client2server[loop+3],
client->supportedMessages.client2server[loop+4], client->supportedMessages.client2server[loop+5],
client->supportedMessages.client2server[loop+6], client->supportedMessages.client2server[loop+7]);
rfbClientLog("server2client supported messages (bit flags)\n");
for (loop=0;loop<32;loop+=8)
rfbClientLog("%02X: %04x %04x %04x %04x - %04x %04x %04x %04x\n", loop,
client->supportedMessages.server2client[loop], client->supportedMessages.server2client[loop+1],
client->supportedMessages.server2client[loop+2], client->supportedMessages.server2client[loop+3],
client->supportedMessages.server2client[loop+4], client->supportedMessages.server2client[loop+5],
client->supportedMessages.server2client[loop+6], client->supportedMessages.server2client[loop+7]);
continue;
}
/* rect.r.w=byte count, rect.r.h=# of encodings */
if (rect.encoding == rfbEncodingSupportedEncodings) {
char *buffer;
buffer = malloc(rect.r.w);
if (!ReadFromRFBServer(client, buffer, rect.r.w))
{
free(buffer);
return FALSE;
}
/* buffer now contains rect.r.h # of uint32_t encodings that the server supports */
/* currently ignored by this library */
free(buffer);
continue;
}
/* rect.r.w=byte count */
if (rect.encoding == rfbEncodingServerIdentity) {
char *buffer;
buffer = malloc(rect.r.w+1);
if (!ReadFromRFBServer(client, buffer, rect.r.w))
{
free(buffer);
return FALSE;
}
buffer[rect.r.w]=0; /* null terminate, just in case */
rfbClientLog("Connected to Server \"%s\"\n", buffer);
free(buffer);
continue;
}
/* rfbEncodingUltraZip is a collection of subrects. x = # of subrects, and h is always 0 */
if (rect.encoding != rfbEncodingUltraZip)
{
if ((rect.r.x + rect.r.w > client->width) ||
(rect.r.y + rect.r.h > client->height))
{
rfbClientLog("Rect too large: %dx%d at (%d, %d)\n",
rect.r.w, rect.r.h, rect.r.x, rect.r.y);
return FALSE;
}
/* UltraVNC with scaling, will send rectangles with a zero W or H
*
if ((rect.encoding != rfbEncodingTight) &&
(rect.r.h * rect.r.w == 0))
{
rfbClientLog("Zero size rect - ignoring (encoding=%d (0x%08x) %dx, %dy, %dw, %dh)\n", rect.encoding, rect.encoding, rect.r.x, rect.r.y, rect.r.w, rect.r.h);
continue;
}
*/
/* If RichCursor encoding is used, we should prevent collisions
between framebuffer updates and cursor drawing operations. */
client->SoftCursorLockArea(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h);
}
switch (rect.encoding) {
case rfbEncodingRaw: {
int y=rect.r.y, h=rect.r.h;
bytesPerLine = rect.r.w * client->format.bitsPerPixel / 8;
/* RealVNC 4.x-5.x on OSX can induce bytesPerLine==0,
usually during GPU accel. */
/* Regardless of cause, do not divide by zero. */
linesToRead = bytesPerLine ? (RFB_BUFFER_SIZE / bytesPerLine) : 0;
while (linesToRead && h > 0) {
if (linesToRead > h)
linesToRead = h;
if (!ReadFromRFBServer(client, client->buffer,bytesPerLine * linesToRead))
return FALSE;
client->GotBitmap(client, (uint8_t *)client->buffer,
rect.r.x, y, rect.r.w,linesToRead);
h -= linesToRead;
y += linesToRead;
}
break;
}
case rfbEncodingCopyRect:
{
rfbCopyRect cr;
if (!ReadFromRFBServer(client, (char *)&cr, sz_rfbCopyRect))
return FALSE;
cr.srcX = rfbClientSwap16IfLE(cr.srcX);
cr.srcY = rfbClientSwap16IfLE(cr.srcY);
/* If RichCursor encoding is used, we should extend our
"cursor lock area" (previously set to destination
rectangle) to the source rectangle as well. */
client->SoftCursorLockArea(client,
cr.srcX, cr.srcY, rect.r.w, rect.r.h);
client->GotCopyRect(client, cr.srcX, cr.srcY, rect.r.w, rect.r.h,
rect.r.x, rect.r.y);
break;
}
case rfbEncodingRRE:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleRRE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleRRE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleRRE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingCoRRE:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleCoRRE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleCoRRE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleCoRRE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingHextile:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleHextile8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleHextile16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleHextile32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingUltra:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleUltra8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleUltra16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleUltra32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingUltraZip:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleUltraZip8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleUltraZip16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleUltraZip32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingTRLE:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleTRLE8(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
break;
case 16:
if (client->si.format.greenMax > 0x1F) {
if (!HandleTRLE16(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
} else {
if (!HandleTRLE15(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
}
break;
case 32: {
uint32_t maxColor =
(client->format.redMax << client->format.redShift) |
(client->format.greenMax << client->format.greenShift) |
(client->format.blueMax << client->format.blueShift);
if ((client->format.bigEndian && (maxColor & 0xff) == 0) ||
(!client->format.bigEndian && (maxColor & 0xff000000) == 0)) {
if (!HandleTRLE24(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
} else if (!client->format.bigEndian && (maxColor & 0xff) == 0) {
if (!HandleTRLE24Up(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
} else if (client->format.bigEndian && (maxColor & 0xff000000) == 0) {
if (!HandleTRLE24Down(client, rect.r.x, rect.r.y, rect.r.w,
rect.r.h))
return FALSE;
} else if (!HandleTRLE32(client, rect.r.x, rect.r.y, rect.r.w,
rect.r.h))
return FALSE;
break;
}
}
break;
}
#ifdef LIBVNCSERVER_HAVE_LIBZ
case rfbEncodingZlib:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleZlib8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleZlib16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleZlib32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
case rfbEncodingTight:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleTight8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleTight16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleTight32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
#endif
case rfbEncodingZRLE:
/* Fail safe for ZYWRLE unsupport VNC server. */
client->appData.qualityLevel = 9;
/* fall through */
case rfbEncodingZYWRLE:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleZRLE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (client->si.format.greenMax > 0x1F) {
if (!HandleZRLE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else {
if (!HandleZRLE15(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
}
break;
case 32:
{
uint32_t maxColor=(client->format.redMax<<client->format.redShift)|
(client->format.greenMax<<client->format.greenShift)|
(client->format.blueMax<<client->format.blueShift);
if ((client->format.bigEndian && (maxColor&0xff)==0) ||
(!client->format.bigEndian && (maxColor&0xff000000)==0)) {
if (!HandleZRLE24(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else if (!client->format.bigEndian && (maxColor&0xff)==0) {
if (!HandleZRLE24Up(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else if (client->format.bigEndian && (maxColor&0xff000000)==0) {
if (!HandleZRLE24Down(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else if (!HandleZRLE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
}
break;
}
#endif
default:
{
rfbBool handled = FALSE;
rfbClientProtocolExtension* e;
for(e = rfbClientExtensions; !handled && e; e = e->next)
if(e->handleEncoding && e->handleEncoding(client, &rect))
handled = TRUE;
if(!handled) {
rfbClientLog("Unknown rect encoding %d\n",
(int)rect.encoding);
return FALSE;
}
}
}
/* Now we may discard "soft cursor locks". */
client->SoftCursorUnlockScreen(client);
client->GotFrameBufferUpdate(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h);
}
if (!SendIncrementalFramebufferUpdateRequest(client))
return FALSE;
if (client->FinishedFrameBufferUpdate)
client->FinishedFrameBufferUpdate(client);
break;
}
case rfbBell:
{
client->Bell(client);
break;
}
case rfbServerCutText:
{
char *buffer;
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbServerCutTextMsg - 1))
return FALSE;
msg.sct.length = rfbClientSwap32IfLE(msg.sct.length);
if (msg.sct.length > 1<<20) {
rfbClientErr("Ignoring too big cut text length sent by server: %u B > 1 MB\n", (unsigned int)msg.sct.length);
return FALSE;
}
buffer = malloc((uint64_t)msg.sct.length+1);
if (!ReadFromRFBServer(client, buffer, msg.sct.length)) {
free(buffer);
return FALSE;
}
buffer[msg.sct.length] = 0;
if (client->GotXCutText)
client->GotXCutText(client, buffer, msg.sct.length);
free(buffer);
break;
}
case rfbTextChat:
{
char *buffer=NULL;
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbTextChatMsg- 1))
return FALSE;
msg.tc.length = rfbClientSwap32IfLE(msg.sct.length);
switch(msg.tc.length) {
case rfbTextChatOpen:
rfbClientLog("Received TextChat Open\n");
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)rfbTextChatOpen, NULL);
break;
case rfbTextChatClose:
rfbClientLog("Received TextChat Close\n");
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)rfbTextChatClose, NULL);
break;
case rfbTextChatFinished:
rfbClientLog("Received TextChat Finished\n");
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)rfbTextChatFinished, NULL);
break;
default:
buffer=malloc(msg.tc.length+1);
if (!ReadFromRFBServer(client, buffer, msg.tc.length))
{
free(buffer);
return FALSE;
}
/* Null Terminate <just in case> */
buffer[msg.tc.length]=0;
rfbClientLog("Received TextChat \"%s\"\n", buffer);
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)msg.tc.length, buffer);
free(buffer);
break;
}
break;
}
case rfbXvp:
{
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbXvpMsg -1))
return FALSE;
SetClient2Server(client, rfbXvp);
/* technically, we only care what we can *send* to the server
* but, we set Server2Client Just in case it ever becomes useful
*/
SetServer2Client(client, rfbXvp);
if(client->HandleXvpMsg)
client->HandleXvpMsg(client, msg.xvp.version, msg.xvp.code);
break;
}
case rfbResizeFrameBuffer:
{
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbResizeFrameBufferMsg -1))
return FALSE;
client->width = rfbClientSwap16IfLE(msg.rsfb.framebufferWidth);
client->height = rfbClientSwap16IfLE(msg.rsfb.framebufferHeigth);
client->updateRect.x = client->updateRect.y = 0;
client->updateRect.w = client->width;
client->updateRect.h = client->height;
if (!client->MallocFrameBuffer(client))
return FALSE;
SendFramebufferUpdateRequest(client, 0, 0, client->width, client->height, FALSE);
rfbClientLog("Got new framebuffer size: %dx%d\n", client->width, client->height);
break;
}
case rfbPalmVNCReSizeFrameBuffer:
{
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbPalmVNCReSizeFrameBufferMsg -1))
return FALSE;
client->width = rfbClientSwap16IfLE(msg.prsfb.buffer_w);
client->height = rfbClientSwap16IfLE(msg.prsfb.buffer_h);
client->updateRect.x = client->updateRect.y = 0;
client->updateRect.w = client->width;
client->updateRect.h = client->height;
if (!client->MallocFrameBuffer(client))
return FALSE;
SendFramebufferUpdateRequest(client, 0, 0, client->width, client->height, FALSE);
rfbClientLog("Got new framebuffer size: %dx%d\n", client->width, client->height);
break;
}
default:
{
rfbBool handled = FALSE;
rfbClientProtocolExtension* e;
for(e = rfbClientExtensions; !handled && e; e = e->next)
if(e->handleMessage && e->handleMessage(client, &msg))
handled = TRUE;
if(!handled) {
char buffer[256];
rfbClientLog("Unknown message type %d from VNC server\n",msg.type);
ReadFromRFBServer(client, buffer, 256);
return FALSE;
}
}
}
return TRUE;
}
#define GET_PIXEL8(pix, ptr) ((pix) = *(ptr)++)
#define GET_PIXEL16(pix, ptr) (((uint8_t*)&(pix))[0] = *(ptr)++, \
((uint8_t*)&(pix))[1] = *(ptr)++)
#define GET_PIXEL32(pix, ptr) (((uint8_t*)&(pix))[0] = *(ptr)++, \
((uint8_t*)&(pix))[1] = *(ptr)++, \
((uint8_t*)&(pix))[2] = *(ptr)++, \
((uint8_t*)&(pix))[3] = *(ptr)++)
/* CONCAT2 concatenates its two arguments. CONCAT2E does the same but also
expands its arguments if they are macros */
#define CONCAT2(a,b) a##b
#define CONCAT2E(a,b) CONCAT2(a,b)
#define CONCAT3(a,b,c) a##b##c
#define CONCAT3E(a,b,c) CONCAT3(a,b,c)
#define BPP 8
#include "rre.c"
#include "corre.c"
#include "hextile.c"
#include "ultra.c"
#include "zlib.c"
#include "tight.c"
#include "trle.c"
#include "zrle.c"
#undef BPP
#define BPP 16
#include "rre.c"
#include "corre.c"
#include "hextile.c"
#include "ultra.c"
#include "zlib.c"
#include "tight.c"
#include "trle.c"
#include "zrle.c"
#define REALBPP 15
#include "trle.c"
#define REALBPP 15
#include "zrle.c"
#undef BPP
#define BPP 32
#include "rre.c"
#include "corre.c"
#include "hextile.c"
#include "ultra.c"
#include "zlib.c"
#include "tight.c"
#include "trle.c"
#include "zrle.c"
#define REALBPP 24
#include "trle.c"
#define REALBPP 24
#include "zrle.c"
#define REALBPP 24
#define UNCOMP 8
#include "trle.c"
#define REALBPP 24
#define UNCOMP 8
#include "zrle.c"
#define REALBPP 24
#define UNCOMP -8
#include "trle.c"
#define REALBPP 24
#define UNCOMP -8
#include "zrle.c"
#undef BPP
/*
* PrintPixelFormat.
*/
void
PrintPixelFormat(rfbPixelFormat *format)
{
if (format->bitsPerPixel == 1) {
rfbClientLog(" Single bit per pixel.\n");
rfbClientLog(
" %s significant bit in each byte is leftmost on the screen.\n",
(format->bigEndian ? "Most" : "Least"));
} else {
rfbClientLog(" %d bits per pixel.\n",format->bitsPerPixel);
if (format->bitsPerPixel != 8) {
rfbClientLog(" %s significant byte first in each pixel.\n",
(format->bigEndian ? "Most" : "Least"));
}
if (format->trueColour) {
rfbClientLog(" TRUE colour: max red %d green %d blue %d"
", shift red %d green %d blue %d\n",
format->redMax, format->greenMax, format->blueMax,
format->redShift, format->greenShift, format->blueShift);
} else {
rfbClientLog(" Colour map (not true colour).\n");
}
}
}
/* avoid name clashes with LibVNCServer */
#define rfbEncryptBytes rfbClientEncryptBytes
#define rfbEncryptBytes2 rfbClientEncryptBytes2
#define rfbDes rfbClientDes
#define rfbDesKey rfbClientDesKey
#define rfbUseKey rfbClientUseKey
#include "vncauth.c"
#include "d3des.c"
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_518_0 |
crossvul-cpp_data_good_96_1 | ////////////////////////////////////////////////////////////////////////////
// **** WAVPACK **** //
// Hybrid Lossless Wavefile Compressor //
// Copyright (c) 1998 - 2016 David Bryant. //
// All Rights Reserved. //
// Distributed under the BSD Software License (see license.txt) //
////////////////////////////////////////////////////////////////////////////
// riff.c
// This module is a helper to the WavPack command-line programs to support WAV files
// (both MS standard and rf64 varients).
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <math.h>
#include <stdio.h>
#include <ctype.h>
#include "wavpack.h"
#include "utils.h"
#include "md5.h"
#pragma pack(push,4)
typedef struct {
char ckID [4];
uint64_t chunkSize64;
} CS64Chunk;
typedef struct {
uint64_t riffSize64, dataSize64, sampleCount64;
uint32_t tableLength;
} DS64Chunk;
typedef struct {
char ckID [4];
uint32_t ckSize;
char junk [28];
} JunkChunk;
#pragma pack(pop)
#define CS64ChunkFormat "4D"
#define DS64ChunkFormat "DDDL"
#define WAVPACK_NO_ERROR 0
#define WAVPACK_SOFT_ERROR 1
#define WAVPACK_HARD_ERROR 2
extern int debug_logging_mode;
int ParseRiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config)
{
int is_rf64 = !strncmp (fourcc, "RF64", 4), got_ds64 = 0;
int64_t total_samples = 0, infilesize;
RiffChunkHeader riff_chunk_header;
ChunkHeader chunk_header;
WaveHeader WaveHeader;
DS64Chunk ds64_chunk;
uint32_t bcount;
CLEAR (WaveHeader);
CLEAR (ds64_chunk);
infilesize = DoGetFileSize (infile);
if (!is_rf64 && infilesize >= 4294967296LL && !(config->qmode & QMODE_IGNORE_LENGTH)) {
error_line ("can't handle .WAV files larger than 4 GB (non-standard)!");
return WAVPACK_SOFT_ERROR;
}
memcpy (&riff_chunk_header, fourcc, 4);
if ((!DoReadFile (infile, ((char *) &riff_chunk_header) + 4, sizeof (RiffChunkHeader) - 4, &bcount) ||
bcount != sizeof (RiffChunkHeader) - 4 || strncmp (riff_chunk_header.formType, "WAVE", 4))) {
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &riff_chunk_header, sizeof (RiffChunkHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
// loop through all elements of the RIFF wav header
// (until the data chuck) and copy them to the output file
while (1) {
if (!DoReadFile (infile, &chunk_header, sizeof (ChunkHeader), &bcount) ||
bcount != sizeof (ChunkHeader)) {
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &chunk_header, sizeof (ChunkHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackLittleEndianToNative (&chunk_header, ChunkHeaderFormat);
if (!strncmp (chunk_header.ckID, "ds64", 4)) {
if (chunk_header.ckSize < sizeof (DS64Chunk) ||
!DoReadFile (infile, &ds64_chunk, sizeof (DS64Chunk), &bcount) ||
bcount != sizeof (DS64Chunk)) {
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &ds64_chunk, sizeof (DS64Chunk))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
got_ds64 = 1;
WavpackLittleEndianToNative (&ds64_chunk, DS64ChunkFormat);
if (debug_logging_mode)
error_line ("DS64: riffSize = %lld, dataSize = %lld, sampleCount = %lld, table_length = %d",
(long long) ds64_chunk.riffSize64, (long long) ds64_chunk.dataSize64,
(long long) ds64_chunk.sampleCount64, ds64_chunk.tableLength);
if (ds64_chunk.tableLength * sizeof (CS64Chunk) != chunk_header.ckSize - sizeof (DS64Chunk)) {
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
while (ds64_chunk.tableLength--) {
CS64Chunk cs64_chunk;
if (!DoReadFile (infile, &cs64_chunk, sizeof (CS64Chunk), &bcount) ||
bcount != sizeof (CS64Chunk) ||
(!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &cs64_chunk, sizeof (CS64Chunk)))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
}
}
else if (!strncmp (chunk_header.ckID, "fmt ", 4)) { // if it's the format chunk, we want to get some info out of there and
int supported = TRUE, format; // make sure it's a .wav file we can handle
if (chunk_header.ckSize < 16 || chunk_header.ckSize > sizeof (WaveHeader) ||
!DoReadFile (infile, &WaveHeader, chunk_header.ckSize, &bcount) ||
bcount != chunk_header.ckSize) {
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &WaveHeader, chunk_header.ckSize)) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackLittleEndianToNative (&WaveHeader, WaveHeaderFormat);
if (debug_logging_mode) {
error_line ("format tag size = %d", chunk_header.ckSize);
error_line ("FormatTag = %x, NumChannels = %d, BitsPerSample = %d",
WaveHeader.FormatTag, WaveHeader.NumChannels, WaveHeader.BitsPerSample);
error_line ("BlockAlign = %d, SampleRate = %d, BytesPerSecond = %d",
WaveHeader.BlockAlign, WaveHeader.SampleRate, WaveHeader.BytesPerSecond);
if (chunk_header.ckSize > 16)
error_line ("cbSize = %d, ValidBitsPerSample = %d", WaveHeader.cbSize,
WaveHeader.ValidBitsPerSample);
if (chunk_header.ckSize > 20)
error_line ("ChannelMask = %x, SubFormat = %d",
WaveHeader.ChannelMask, WaveHeader.SubFormat);
}
if (chunk_header.ckSize > 16 && WaveHeader.cbSize == 2)
config->qmode |= QMODE_ADOBE_MODE;
format = (WaveHeader.FormatTag == 0xfffe && chunk_header.ckSize == 40) ?
WaveHeader.SubFormat : WaveHeader.FormatTag;
config->bits_per_sample = (chunk_header.ckSize == 40 && WaveHeader.ValidBitsPerSample) ?
WaveHeader.ValidBitsPerSample : WaveHeader.BitsPerSample;
if (format != 1 && format != 3)
supported = FALSE;
if (format == 3 && config->bits_per_sample != 32)
supported = FALSE;
if (!WaveHeader.NumChannels || WaveHeader.NumChannels > 256 ||
WaveHeader.BlockAlign / WaveHeader.NumChannels < (config->bits_per_sample + 7) / 8 ||
WaveHeader.BlockAlign / WaveHeader.NumChannels > 4 ||
WaveHeader.BlockAlign % WaveHeader.NumChannels)
supported = FALSE;
if (config->bits_per_sample < 1 || config->bits_per_sample > 32)
supported = FALSE;
if (!supported) {
error_line ("%s is an unsupported .WAV format!", infilename);
return WAVPACK_SOFT_ERROR;
}
if (chunk_header.ckSize < 40) {
if (!config->channel_mask && !(config->qmode & QMODE_CHANS_UNASSIGNED)) {
if (WaveHeader.NumChannels <= 2)
config->channel_mask = 0x5 - WaveHeader.NumChannels;
else if (WaveHeader.NumChannels <= 18)
config->channel_mask = (1 << WaveHeader.NumChannels) - 1;
else
config->channel_mask = 0x3ffff;
}
}
else if (WaveHeader.ChannelMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) {
error_line ("this WAV file already has channel order information!");
return WAVPACK_SOFT_ERROR;
}
else if (WaveHeader.ChannelMask)
config->channel_mask = WaveHeader.ChannelMask;
if (format == 3)
config->float_norm_exp = 127;
else if ((config->qmode & QMODE_ADOBE_MODE) &&
WaveHeader.BlockAlign / WaveHeader.NumChannels == 4) {
if (WaveHeader.BitsPerSample == 24)
config->float_norm_exp = 127 + 23;
else if (WaveHeader.BitsPerSample == 32)
config->float_norm_exp = 127 + 15;
}
if (debug_logging_mode) {
if (config->float_norm_exp == 127)
error_line ("data format: normalized 32-bit floating point");
else if (config->float_norm_exp)
error_line ("data format: 32-bit floating point (Audition %d:%d float type 1)",
config->float_norm_exp - 126, 150 - config->float_norm_exp);
else
error_line ("data format: %d-bit integers stored in %d byte(s)",
config->bits_per_sample, WaveHeader.BlockAlign / WaveHeader.NumChannels);
}
}
else if (!strncmp (chunk_header.ckID, "data", 4)) { // on the data chunk, get size and exit loop
int64_t data_chunk_size = (got_ds64 && chunk_header.ckSize == (uint32_t) -1) ?
ds64_chunk.dataSize64 : chunk_header.ckSize;
if (!WaveHeader.NumChannels || (is_rf64 && !got_ds64)) { // make sure we saw "fmt" and "ds64" chunks (if required)
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && infilesize - data_chunk_size > 16777216) {
error_line ("this .WAV file has over 16 MB of extra RIFF data, probably is corrupt!");
return WAVPACK_SOFT_ERROR;
}
if (config->qmode & QMODE_IGNORE_LENGTH) {
if (infilesize && DoGetFilePosition (infile) != -1)
total_samples = (infilesize - DoGetFilePosition (infile)) / WaveHeader.BlockAlign;
else
total_samples = -1;
}
else {
total_samples = data_chunk_size / WaveHeader.BlockAlign;
if (got_ds64 && total_samples != ds64_chunk.sampleCount64) {
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
if (!total_samples) {
error_line ("this .WAV file has no audio samples, probably is corrupt!");
return WAVPACK_SOFT_ERROR;
}
if (total_samples > MAX_WAVPACK_SAMPLES) {
error_line ("%s has too many samples for WavPack!", infilename);
return WAVPACK_SOFT_ERROR;
}
}
config->bytes_per_sample = WaveHeader.BlockAlign / WaveHeader.NumChannels;
config->num_channels = WaveHeader.NumChannels;
config->sample_rate = WaveHeader.SampleRate;
break;
}
else { // just copy unknown chunks to output file
int bytes_to_copy = (chunk_header.ckSize + 1) & ~1L;
char *buff;
if (bytes_to_copy < 0 || bytes_to_copy > 4194304) {
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
buff = malloc (bytes_to_copy);
if (debug_logging_mode)
error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes",
chunk_header.ckID [0], chunk_header.ckID [1], chunk_header.ckID [2],
chunk_header.ckID [3], chunk_header.ckSize);
if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) ||
bcount != bytes_to_copy ||
(!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, buff, bytes_to_copy))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
free (buff);
return WAVPACK_SOFT_ERROR;
}
free (buff);
}
}
if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) {
error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
return WAVPACK_NO_ERROR;
}
int WriteRiffHeader (FILE *outfile, WavpackContext *wpc, int64_t total_samples, int qmode)
{
int do_rf64 = 0, write_junk = 1, table_length = 0;
ChunkHeader ds64hdr, datahdr, fmthdr;
RiffChunkHeader riffhdr;
DS64Chunk ds64_chunk;
CS64Chunk cs64_chunk;
JunkChunk junkchunk;
WaveHeader wavhdr;
uint32_t bcount;
int64_t total_data_bytes, total_riff_bytes;
int num_channels = WavpackGetNumChannels (wpc);
int32_t channel_mask = WavpackGetChannelMask (wpc);
int32_t sample_rate = WavpackGetSampleRate (wpc);
int bytes_per_sample = WavpackGetBytesPerSample (wpc);
int bits_per_sample = WavpackGetBitsPerSample (wpc);
int format = WavpackGetFloatNormExp (wpc) ? 3 : 1;
int wavhdrsize = 16;
if (format == 3 && WavpackGetFloatNormExp (wpc) != 127) {
error_line ("can't create valid RIFF wav header for non-normalized floating data!");
return FALSE;
}
if (total_samples == -1)
total_samples = 0x7ffff000 / (bytes_per_sample * num_channels);
total_data_bytes = total_samples * bytes_per_sample * num_channels;
if (total_data_bytes > 0xff000000) {
if (debug_logging_mode)
error_line ("total_data_bytes = %lld, so rf64", total_data_bytes);
write_junk = 0;
do_rf64 = 1;
}
else if (debug_logging_mode)
error_line ("total_data_bytes = %lld, so riff", total_data_bytes);
CLEAR (wavhdr);
wavhdr.FormatTag = format;
wavhdr.NumChannels = num_channels;
wavhdr.SampleRate = sample_rate;
wavhdr.BytesPerSecond = sample_rate * num_channels * bytes_per_sample;
wavhdr.BlockAlign = bytes_per_sample * num_channels;
wavhdr.BitsPerSample = bits_per_sample;
if (num_channels > 2 || channel_mask != 0x5 - num_channels) {
wavhdrsize = sizeof (wavhdr);
wavhdr.cbSize = 22;
wavhdr.ValidBitsPerSample = bits_per_sample;
wavhdr.SubFormat = format;
wavhdr.ChannelMask = channel_mask;
wavhdr.FormatTag = 0xfffe;
wavhdr.BitsPerSample = bytes_per_sample * 8;
wavhdr.GUID [4] = 0x10;
wavhdr.GUID [6] = 0x80;
wavhdr.GUID [9] = 0xaa;
wavhdr.GUID [11] = 0x38;
wavhdr.GUID [12] = 0x9b;
wavhdr.GUID [13] = 0x71;
}
strncpy (riffhdr.ckID, do_rf64 ? "RF64" : "RIFF", sizeof (riffhdr.ckID));
strncpy (riffhdr.formType, "WAVE", sizeof (riffhdr.formType));
total_riff_bytes = sizeof (riffhdr) + wavhdrsize + sizeof (datahdr) + ((total_data_bytes + 1) & ~(int64_t)1);
if (do_rf64) total_riff_bytes += sizeof (ds64hdr) + sizeof (ds64_chunk);
total_riff_bytes += table_length * sizeof (CS64Chunk);
if (write_junk) total_riff_bytes += sizeof (junkchunk);
strncpy (fmthdr.ckID, "fmt ", sizeof (fmthdr.ckID));
strncpy (datahdr.ckID, "data", sizeof (datahdr.ckID));
fmthdr.ckSize = wavhdrsize;
if (write_junk) {
CLEAR (junkchunk);
strncpy (junkchunk.ckID, "junk", sizeof (junkchunk.ckID));
junkchunk.ckSize = sizeof (junkchunk) - 8;
WavpackNativeToLittleEndian (&junkchunk, ChunkHeaderFormat);
}
if (do_rf64) {
strncpy (ds64hdr.ckID, "ds64", sizeof (ds64hdr.ckID));
ds64hdr.ckSize = sizeof (ds64_chunk) + (table_length * sizeof (CS64Chunk));
CLEAR (ds64_chunk);
ds64_chunk.riffSize64 = total_riff_bytes;
ds64_chunk.dataSize64 = total_data_bytes;
ds64_chunk.sampleCount64 = total_samples;
ds64_chunk.tableLength = table_length;
riffhdr.ckSize = (uint32_t) -1;
datahdr.ckSize = (uint32_t) -1;
WavpackNativeToLittleEndian (&ds64hdr, ChunkHeaderFormat);
WavpackNativeToLittleEndian (&ds64_chunk, DS64ChunkFormat);
}
else {
riffhdr.ckSize = (uint32_t) total_riff_bytes;
datahdr.ckSize = (uint32_t) total_data_bytes;
}
// this "table" is just a dummy placeholder for testing (normally not written)
if (table_length) {
strncpy (cs64_chunk.ckID, "dmmy", sizeof (cs64_chunk.ckID));
cs64_chunk.chunkSize64 = 12345678;
WavpackNativeToLittleEndian (&cs64_chunk, CS64ChunkFormat);
}
// write the RIFF chunks up to just before the data starts
WavpackNativeToLittleEndian (&riffhdr, ChunkHeaderFormat);
WavpackNativeToLittleEndian (&fmthdr, ChunkHeaderFormat);
WavpackNativeToLittleEndian (&wavhdr, WaveHeaderFormat);
WavpackNativeToLittleEndian (&datahdr, ChunkHeaderFormat);
if (!DoWriteFile (outfile, &riffhdr, sizeof (riffhdr), &bcount) || bcount != sizeof (riffhdr) ||
(do_rf64 && (!DoWriteFile (outfile, &ds64hdr, sizeof (ds64hdr), &bcount) || bcount != sizeof (ds64hdr))) ||
(do_rf64 && (!DoWriteFile (outfile, &ds64_chunk, sizeof (ds64_chunk), &bcount) || bcount != sizeof (ds64_chunk)))) {
error_line ("can't write .WAV data, disk probably full!");
return FALSE;
}
// again, this is normally not written except for testing
while (table_length--)
if (!DoWriteFile (outfile, &cs64_chunk, sizeof (cs64_chunk), &bcount) || bcount != sizeof (cs64_chunk)) {
error_line ("can't write .WAV data, disk probably full!");
return FALSE;
}
if ((write_junk && (!DoWriteFile (outfile, &junkchunk, sizeof (junkchunk), &bcount) || bcount != sizeof (junkchunk))) ||
!DoWriteFile (outfile, &fmthdr, sizeof (fmthdr), &bcount) || bcount != sizeof (fmthdr) ||
!DoWriteFile (outfile, &wavhdr, wavhdrsize, &bcount) || bcount != wavhdrsize ||
!DoWriteFile (outfile, &datahdr, sizeof (datahdr), &bcount) || bcount != sizeof (datahdr)) {
error_line ("can't write .WAV data, disk probably full!");
return FALSE;
}
return TRUE;
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_96_1 |
crossvul-cpp_data_good_4410_0 | /* $OpenBSD$ */
/*
* Copyright (c) 2007 Nicholas Marriott <nicholas.marriott@gmail.com>
*
* 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 MIND, 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/types.h>
#include <netinet/in.h>
#include <ctype.h>
#include <resolv.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "tmux.h"
/*
* Based on the description by Paul Williams at:
*
* https://vt100.net/emu/dec_ansi_parser
*
* With the following changes:
*
* - 7-bit only.
*
* - Support for UTF-8.
*
* - OSC (but not APC) may be terminated by \007 as well as ST.
*
* - A state for APC similar to OSC. Some terminals appear to use this to set
* the title.
*
* - A state for the screen \033k...\033\\ sequence to rename a window. This is
* pretty stupid but not supporting it is more trouble than it is worth.
*
* - Special handling for ESC inside a DCS to allow arbitrary byte sequences to
* be passed to the underlying terminals.
*/
/* Input parser cell. */
struct input_cell {
struct grid_cell cell;
int set;
int g0set; /* 1 if ACS */
int g1set; /* 1 if ACS */
};
/* Input parser argument. */
struct input_param {
enum {
INPUT_MISSING,
INPUT_NUMBER,
INPUT_STRING
} type;
union {
int num;
char *str;
};
};
/* Input parser context. */
struct input_ctx {
struct window_pane *wp;
struct bufferevent *event;
struct screen_write_ctx ctx;
struct input_cell cell;
struct input_cell old_cell;
u_int old_cx;
u_int old_cy;
int old_mode;
u_char interm_buf[4];
size_t interm_len;
u_char param_buf[64];
size_t param_len;
#define INPUT_BUF_START 32
#define INPUT_BUF_LIMIT 1048576
u_char *input_buf;
size_t input_len;
size_t input_space;
enum {
INPUT_END_ST,
INPUT_END_BEL
} input_end;
struct input_param param_list[24];
u_int param_list_len;
struct utf8_data utf8data;
int utf8started;
int ch;
int last;
int flags;
#define INPUT_DISCARD 0x1
const struct input_state *state;
struct event timer;
/*
* All input received since we were last in the ground state. Sent to
* control clients on connection.
*/
struct evbuffer *since_ground;
};
/* Helper functions. */
struct input_transition;
static int input_split(struct input_ctx *);
static int input_get(struct input_ctx *, u_int, int, int);
static void printflike(2, 3) input_reply(struct input_ctx *, const char *, ...);
static void input_set_state(struct input_ctx *,
const struct input_transition *);
static void input_reset_cell(struct input_ctx *);
static void input_osc_4(struct input_ctx *, const char *);
static void input_osc_10(struct input_ctx *, const char *);
static void input_osc_11(struct input_ctx *, const char *);
static void input_osc_52(struct input_ctx *, const char *);
static void input_osc_104(struct input_ctx *, const char *);
/* Transition entry/exit handlers. */
static void input_clear(struct input_ctx *);
static void input_ground(struct input_ctx *);
static void input_enter_dcs(struct input_ctx *);
static void input_enter_osc(struct input_ctx *);
static void input_exit_osc(struct input_ctx *);
static void input_enter_apc(struct input_ctx *);
static void input_exit_apc(struct input_ctx *);
static void input_enter_rename(struct input_ctx *);
static void input_exit_rename(struct input_ctx *);
/* Input state handlers. */
static int input_print(struct input_ctx *);
static int input_intermediate(struct input_ctx *);
static int input_parameter(struct input_ctx *);
static int input_input(struct input_ctx *);
static int input_c0_dispatch(struct input_ctx *);
static int input_esc_dispatch(struct input_ctx *);
static int input_csi_dispatch(struct input_ctx *);
static void input_csi_dispatch_rm(struct input_ctx *);
static void input_csi_dispatch_rm_private(struct input_ctx *);
static void input_csi_dispatch_sm(struct input_ctx *);
static void input_csi_dispatch_sm_private(struct input_ctx *);
static void input_csi_dispatch_winops(struct input_ctx *);
static void input_csi_dispatch_sgr_256(struct input_ctx *, int, u_int *);
static void input_csi_dispatch_sgr_rgb(struct input_ctx *, int, u_int *);
static void input_csi_dispatch_sgr(struct input_ctx *);
static int input_dcs_dispatch(struct input_ctx *);
static int input_top_bit_set(struct input_ctx *);
static int input_end_bel(struct input_ctx *);
/* Command table comparison function. */
static int input_table_compare(const void *, const void *);
/* Command table entry. */
struct input_table_entry {
int ch;
const char *interm;
int type;
};
/* Escape commands. */
enum input_esc_type {
INPUT_ESC_DECALN,
INPUT_ESC_DECKPAM,
INPUT_ESC_DECKPNM,
INPUT_ESC_DECRC,
INPUT_ESC_DECSC,
INPUT_ESC_HTS,
INPUT_ESC_IND,
INPUT_ESC_NEL,
INPUT_ESC_RI,
INPUT_ESC_RIS,
INPUT_ESC_SCSG0_OFF,
INPUT_ESC_SCSG0_ON,
INPUT_ESC_SCSG1_OFF,
INPUT_ESC_SCSG1_ON,
INPUT_ESC_ST,
};
/* Escape command table. */
static const struct input_table_entry input_esc_table[] = {
{ '0', "(", INPUT_ESC_SCSG0_ON },
{ '0', ")", INPUT_ESC_SCSG1_ON },
{ '7', "", INPUT_ESC_DECSC },
{ '8', "", INPUT_ESC_DECRC },
{ '8', "#", INPUT_ESC_DECALN },
{ '=', "", INPUT_ESC_DECKPAM },
{ '>', "", INPUT_ESC_DECKPNM },
{ 'B', "(", INPUT_ESC_SCSG0_OFF },
{ 'B', ")", INPUT_ESC_SCSG1_OFF },
{ 'D', "", INPUT_ESC_IND },
{ 'E', "", INPUT_ESC_NEL },
{ 'H', "", INPUT_ESC_HTS },
{ 'M', "", INPUT_ESC_RI },
{ '\\', "", INPUT_ESC_ST },
{ 'c', "", INPUT_ESC_RIS },
};
/* Control (CSI) commands. */
enum input_csi_type {
INPUT_CSI_CBT,
INPUT_CSI_CNL,
INPUT_CSI_CPL,
INPUT_CSI_CUB,
INPUT_CSI_CUD,
INPUT_CSI_CUF,
INPUT_CSI_CUP,
INPUT_CSI_CUU,
INPUT_CSI_DA,
INPUT_CSI_DA_TWO,
INPUT_CSI_DCH,
INPUT_CSI_DECSCUSR,
INPUT_CSI_DECSTBM,
INPUT_CSI_DL,
INPUT_CSI_DSR,
INPUT_CSI_ECH,
INPUT_CSI_ED,
INPUT_CSI_EL,
INPUT_CSI_HPA,
INPUT_CSI_ICH,
INPUT_CSI_IL,
INPUT_CSI_MODOFF,
INPUT_CSI_MODSET,
INPUT_CSI_RCP,
INPUT_CSI_REP,
INPUT_CSI_RM,
INPUT_CSI_RM_PRIVATE,
INPUT_CSI_SCP,
INPUT_CSI_SD,
INPUT_CSI_SGR,
INPUT_CSI_SM,
INPUT_CSI_SM_PRIVATE,
INPUT_CSI_SU,
INPUT_CSI_TBC,
INPUT_CSI_VPA,
INPUT_CSI_WINOPS,
INPUT_CSI_XDA,
};
/* Control (CSI) command table. */
static const struct input_table_entry input_csi_table[] = {
{ '@', "", INPUT_CSI_ICH },
{ 'A', "", INPUT_CSI_CUU },
{ 'B', "", INPUT_CSI_CUD },
{ 'C', "", INPUT_CSI_CUF },
{ 'D', "", INPUT_CSI_CUB },
{ 'E', "", INPUT_CSI_CNL },
{ 'F', "", INPUT_CSI_CPL },
{ 'G', "", INPUT_CSI_HPA },
{ 'H', "", INPUT_CSI_CUP },
{ 'J', "", INPUT_CSI_ED },
{ 'K', "", INPUT_CSI_EL },
{ 'L', "", INPUT_CSI_IL },
{ 'M', "", INPUT_CSI_DL },
{ 'P', "", INPUT_CSI_DCH },
{ 'S', "", INPUT_CSI_SU },
{ 'T', "", INPUT_CSI_SD },
{ 'X', "", INPUT_CSI_ECH },
{ 'Z', "", INPUT_CSI_CBT },
{ '`', "", INPUT_CSI_HPA },
{ 'b', "", INPUT_CSI_REP },
{ 'c', "", INPUT_CSI_DA },
{ 'c', ">", INPUT_CSI_DA_TWO },
{ 'd', "", INPUT_CSI_VPA },
{ 'f', "", INPUT_CSI_CUP },
{ 'g', "", INPUT_CSI_TBC },
{ 'h', "", INPUT_CSI_SM },
{ 'h', "?", INPUT_CSI_SM_PRIVATE },
{ 'l', "", INPUT_CSI_RM },
{ 'l', "?", INPUT_CSI_RM_PRIVATE },
{ 'm', "", INPUT_CSI_SGR },
{ 'm', ">", INPUT_CSI_MODSET },
{ 'n', "", INPUT_CSI_DSR },
{ 'n', ">", INPUT_CSI_MODOFF },
{ 'q', " ", INPUT_CSI_DECSCUSR },
{ 'q', ">", INPUT_CSI_XDA },
{ 'r', "", INPUT_CSI_DECSTBM },
{ 's', "", INPUT_CSI_SCP },
{ 't', "", INPUT_CSI_WINOPS },
{ 'u', "", INPUT_CSI_RCP },
};
/* Input transition. */
struct input_transition {
int first;
int last;
int (*handler)(struct input_ctx *);
const struct input_state *state;
};
/* Input state. */
struct input_state {
const char *name;
void (*enter)(struct input_ctx *);
void (*exit)(struct input_ctx *);
const struct input_transition *transitions;
};
/* State transitions available from all states. */
#define INPUT_STATE_ANYWHERE \
{ 0x18, 0x18, input_c0_dispatch, &input_state_ground }, \
{ 0x1a, 0x1a, input_c0_dispatch, &input_state_ground }, \
{ 0x1b, 0x1b, NULL, &input_state_esc_enter }
/* Forward declarations of state tables. */
static const struct input_transition input_state_ground_table[];
static const struct input_transition input_state_esc_enter_table[];
static const struct input_transition input_state_esc_intermediate_table[];
static const struct input_transition input_state_csi_enter_table[];
static const struct input_transition input_state_csi_parameter_table[];
static const struct input_transition input_state_csi_intermediate_table[];
static const struct input_transition input_state_csi_ignore_table[];
static const struct input_transition input_state_dcs_enter_table[];
static const struct input_transition input_state_dcs_parameter_table[];
static const struct input_transition input_state_dcs_intermediate_table[];
static const struct input_transition input_state_dcs_handler_table[];
static const struct input_transition input_state_dcs_escape_table[];
static const struct input_transition input_state_dcs_ignore_table[];
static const struct input_transition input_state_osc_string_table[];
static const struct input_transition input_state_apc_string_table[];
static const struct input_transition input_state_rename_string_table[];
static const struct input_transition input_state_consume_st_table[];
/* ground state definition. */
static const struct input_state input_state_ground = {
"ground",
input_ground, NULL,
input_state_ground_table
};
/* esc_enter state definition. */
static const struct input_state input_state_esc_enter = {
"esc_enter",
input_clear, NULL,
input_state_esc_enter_table
};
/* esc_intermediate state definition. */
static const struct input_state input_state_esc_intermediate = {
"esc_intermediate",
NULL, NULL,
input_state_esc_intermediate_table
};
/* csi_enter state definition. */
static const struct input_state input_state_csi_enter = {
"csi_enter",
input_clear, NULL,
input_state_csi_enter_table
};
/* csi_parameter state definition. */
static const struct input_state input_state_csi_parameter = {
"csi_parameter",
NULL, NULL,
input_state_csi_parameter_table
};
/* csi_intermediate state definition. */
static const struct input_state input_state_csi_intermediate = {
"csi_intermediate",
NULL, NULL,
input_state_csi_intermediate_table
};
/* csi_ignore state definition. */
static const struct input_state input_state_csi_ignore = {
"csi_ignore",
NULL, NULL,
input_state_csi_ignore_table
};
/* dcs_enter state definition. */
static const struct input_state input_state_dcs_enter = {
"dcs_enter",
input_enter_dcs, NULL,
input_state_dcs_enter_table
};
/* dcs_parameter state definition. */
static const struct input_state input_state_dcs_parameter = {
"dcs_parameter",
NULL, NULL,
input_state_dcs_parameter_table
};
/* dcs_intermediate state definition. */
static const struct input_state input_state_dcs_intermediate = {
"dcs_intermediate",
NULL, NULL,
input_state_dcs_intermediate_table
};
/* dcs_handler state definition. */
static const struct input_state input_state_dcs_handler = {
"dcs_handler",
NULL, NULL,
input_state_dcs_handler_table
};
/* dcs_escape state definition. */
static const struct input_state input_state_dcs_escape = {
"dcs_escape",
NULL, NULL,
input_state_dcs_escape_table
};
/* dcs_ignore state definition. */
static const struct input_state input_state_dcs_ignore = {
"dcs_ignore",
NULL, NULL,
input_state_dcs_ignore_table
};
/* osc_string state definition. */
static const struct input_state input_state_osc_string = {
"osc_string",
input_enter_osc, input_exit_osc,
input_state_osc_string_table
};
/* apc_string state definition. */
static const struct input_state input_state_apc_string = {
"apc_string",
input_enter_apc, input_exit_apc,
input_state_apc_string_table
};
/* rename_string state definition. */
static const struct input_state input_state_rename_string = {
"rename_string",
input_enter_rename, input_exit_rename,
input_state_rename_string_table
};
/* consume_st state definition. */
static const struct input_state input_state_consume_st = {
"consume_st",
input_enter_rename, NULL, /* rename also waits for ST */
input_state_consume_st_table
};
/* ground state table. */
static const struct input_transition input_state_ground_table[] = {
INPUT_STATE_ANYWHERE,
{ 0x00, 0x17, input_c0_dispatch, NULL },
{ 0x19, 0x19, input_c0_dispatch, NULL },
{ 0x1c, 0x1f, input_c0_dispatch, NULL },
{ 0x20, 0x7e, input_print, NULL },
{ 0x7f, 0x7f, NULL, NULL },
{ 0x80, 0xff, input_top_bit_set, NULL },
{ -1, -1, NULL, NULL }
};
/* esc_enter state table. */
static const struct input_transition input_state_esc_enter_table[] = {
INPUT_STATE_ANYWHERE,
{ 0x00, 0x17, input_c0_dispatch, NULL },
{ 0x19, 0x19, input_c0_dispatch, NULL },
{ 0x1c, 0x1f, input_c0_dispatch, NULL },
{ 0x20, 0x2f, input_intermediate, &input_state_esc_intermediate },
{ 0x30, 0x4f, input_esc_dispatch, &input_state_ground },
{ 0x50, 0x50, NULL, &input_state_dcs_enter },
{ 0x51, 0x57, input_esc_dispatch, &input_state_ground },
{ 0x58, 0x58, NULL, &input_state_consume_st },
{ 0x59, 0x59, input_esc_dispatch, &input_state_ground },
{ 0x5a, 0x5a, input_esc_dispatch, &input_state_ground },
{ 0x5b, 0x5b, NULL, &input_state_csi_enter },
{ 0x5c, 0x5c, input_esc_dispatch, &input_state_ground },
{ 0x5d, 0x5d, NULL, &input_state_osc_string },
{ 0x5e, 0x5e, NULL, &input_state_consume_st },
{ 0x5f, 0x5f, NULL, &input_state_apc_string },
{ 0x60, 0x6a, input_esc_dispatch, &input_state_ground },
{ 0x6b, 0x6b, NULL, &input_state_rename_string },
{ 0x6c, 0x7e, input_esc_dispatch, &input_state_ground },
{ 0x7f, 0xff, NULL, NULL },
{ -1, -1, NULL, NULL }
};
/* esc_intermediate state table. */
static const struct input_transition input_state_esc_intermediate_table[] = {
INPUT_STATE_ANYWHERE,
{ 0x00, 0x17, input_c0_dispatch, NULL },
{ 0x19, 0x19, input_c0_dispatch, NULL },
{ 0x1c, 0x1f, input_c0_dispatch, NULL },
{ 0x20, 0x2f, input_intermediate, NULL },
{ 0x30, 0x7e, input_esc_dispatch, &input_state_ground },
{ 0x7f, 0xff, NULL, NULL },
{ -1, -1, NULL, NULL }
};
/* csi_enter state table. */
static const struct input_transition input_state_csi_enter_table[] = {
INPUT_STATE_ANYWHERE,
{ 0x00, 0x17, input_c0_dispatch, NULL },
{ 0x19, 0x19, input_c0_dispatch, NULL },
{ 0x1c, 0x1f, input_c0_dispatch, NULL },
{ 0x20, 0x2f, input_intermediate, &input_state_csi_intermediate },
{ 0x30, 0x39, input_parameter, &input_state_csi_parameter },
{ 0x3a, 0x3a, input_parameter, &input_state_csi_parameter },
{ 0x3b, 0x3b, input_parameter, &input_state_csi_parameter },
{ 0x3c, 0x3f, input_intermediate, &input_state_csi_parameter },
{ 0x40, 0x7e, input_csi_dispatch, &input_state_ground },
{ 0x7f, 0xff, NULL, NULL },
{ -1, -1, NULL, NULL }
};
/* csi_parameter state table. */
static const struct input_transition input_state_csi_parameter_table[] = {
INPUT_STATE_ANYWHERE,
{ 0x00, 0x17, input_c0_dispatch, NULL },
{ 0x19, 0x19, input_c0_dispatch, NULL },
{ 0x1c, 0x1f, input_c0_dispatch, NULL },
{ 0x20, 0x2f, input_intermediate, &input_state_csi_intermediate },
{ 0x30, 0x39, input_parameter, NULL },
{ 0x3a, 0x3a, input_parameter, NULL },
{ 0x3b, 0x3b, input_parameter, NULL },
{ 0x3c, 0x3f, NULL, &input_state_csi_ignore },
{ 0x40, 0x7e, input_csi_dispatch, &input_state_ground },
{ 0x7f, 0xff, NULL, NULL },
{ -1, -1, NULL, NULL }
};
/* csi_intermediate state table. */
static const struct input_transition input_state_csi_intermediate_table[] = {
INPUT_STATE_ANYWHERE,
{ 0x00, 0x17, input_c0_dispatch, NULL },
{ 0x19, 0x19, input_c0_dispatch, NULL },
{ 0x1c, 0x1f, input_c0_dispatch, NULL },
{ 0x20, 0x2f, input_intermediate, NULL },
{ 0x30, 0x3f, NULL, &input_state_csi_ignore },
{ 0x40, 0x7e, input_csi_dispatch, &input_state_ground },
{ 0x7f, 0xff, NULL, NULL },
{ -1, -1, NULL, NULL }
};
/* csi_ignore state table. */
static const struct input_transition input_state_csi_ignore_table[] = {
INPUT_STATE_ANYWHERE,
{ 0x00, 0x17, input_c0_dispatch, NULL },
{ 0x19, 0x19, input_c0_dispatch, NULL },
{ 0x1c, 0x1f, input_c0_dispatch, NULL },
{ 0x20, 0x3f, NULL, NULL },
{ 0x40, 0x7e, NULL, &input_state_ground },
{ 0x7f, 0xff, NULL, NULL },
{ -1, -1, NULL, NULL }
};
/* dcs_enter state table. */
static const struct input_transition input_state_dcs_enter_table[] = {
INPUT_STATE_ANYWHERE,
{ 0x00, 0x17, NULL, NULL },
{ 0x19, 0x19, NULL, NULL },
{ 0x1c, 0x1f, NULL, NULL },
{ 0x20, 0x2f, input_intermediate, &input_state_dcs_intermediate },
{ 0x30, 0x39, input_parameter, &input_state_dcs_parameter },
{ 0x3a, 0x3a, NULL, &input_state_dcs_ignore },
{ 0x3b, 0x3b, input_parameter, &input_state_dcs_parameter },
{ 0x3c, 0x3f, input_intermediate, &input_state_dcs_parameter },
{ 0x40, 0x7e, input_input, &input_state_dcs_handler },
{ 0x7f, 0xff, NULL, NULL },
{ -1, -1, NULL, NULL }
};
/* dcs_parameter state table. */
static const struct input_transition input_state_dcs_parameter_table[] = {
INPUT_STATE_ANYWHERE,
{ 0x00, 0x17, NULL, NULL },
{ 0x19, 0x19, NULL, NULL },
{ 0x1c, 0x1f, NULL, NULL },
{ 0x20, 0x2f, input_intermediate, &input_state_dcs_intermediate },
{ 0x30, 0x39, input_parameter, NULL },
{ 0x3a, 0x3a, NULL, &input_state_dcs_ignore },
{ 0x3b, 0x3b, input_parameter, NULL },
{ 0x3c, 0x3f, NULL, &input_state_dcs_ignore },
{ 0x40, 0x7e, input_input, &input_state_dcs_handler },
{ 0x7f, 0xff, NULL, NULL },
{ -1, -1, NULL, NULL }
};
/* dcs_intermediate state table. */
static const struct input_transition input_state_dcs_intermediate_table[] = {
INPUT_STATE_ANYWHERE,
{ 0x00, 0x17, NULL, NULL },
{ 0x19, 0x19, NULL, NULL },
{ 0x1c, 0x1f, NULL, NULL },
{ 0x20, 0x2f, input_intermediate, NULL },
{ 0x30, 0x3f, NULL, &input_state_dcs_ignore },
{ 0x40, 0x7e, input_input, &input_state_dcs_handler },
{ 0x7f, 0xff, NULL, NULL },
{ -1, -1, NULL, NULL }
};
/* dcs_handler state table. */
static const struct input_transition input_state_dcs_handler_table[] = {
/* No INPUT_STATE_ANYWHERE */
{ 0x00, 0x1a, input_input, NULL },
{ 0x1b, 0x1b, NULL, &input_state_dcs_escape },
{ 0x1c, 0xff, input_input, NULL },
{ -1, -1, NULL, NULL }
};
/* dcs_escape state table. */
static const struct input_transition input_state_dcs_escape_table[] = {
/* No INPUT_STATE_ANYWHERE */
{ 0x00, 0x5b, input_input, &input_state_dcs_handler },
{ 0x5c, 0x5c, input_dcs_dispatch, &input_state_ground },
{ 0x5d, 0xff, input_input, &input_state_dcs_handler },
{ -1, -1, NULL, NULL }
};
/* dcs_ignore state table. */
static const struct input_transition input_state_dcs_ignore_table[] = {
INPUT_STATE_ANYWHERE,
{ 0x00, 0x17, NULL, NULL },
{ 0x19, 0x19, NULL, NULL },
{ 0x1c, 0x1f, NULL, NULL },
{ 0x20, 0xff, NULL, NULL },
{ -1, -1, NULL, NULL }
};
/* osc_string state table. */
static const struct input_transition input_state_osc_string_table[] = {
INPUT_STATE_ANYWHERE,
{ 0x00, 0x06, NULL, NULL },
{ 0x07, 0x07, input_end_bel, &input_state_ground },
{ 0x08, 0x17, NULL, NULL },
{ 0x19, 0x19, NULL, NULL },
{ 0x1c, 0x1f, NULL, NULL },
{ 0x20, 0xff, input_input, NULL },
{ -1, -1, NULL, NULL }
};
/* apc_string state table. */
static const struct input_transition input_state_apc_string_table[] = {
INPUT_STATE_ANYWHERE,
{ 0x00, 0x17, NULL, NULL },
{ 0x19, 0x19, NULL, NULL },
{ 0x1c, 0x1f, NULL, NULL },
{ 0x20, 0xff, input_input, NULL },
{ -1, -1, NULL, NULL }
};
/* rename_string state table. */
static const struct input_transition input_state_rename_string_table[] = {
INPUT_STATE_ANYWHERE,
{ 0x00, 0x17, NULL, NULL },
{ 0x19, 0x19, NULL, NULL },
{ 0x1c, 0x1f, NULL, NULL },
{ 0x20, 0xff, input_input, NULL },
{ -1, -1, NULL, NULL }
};
/* consume_st state table. */
static const struct input_transition input_state_consume_st_table[] = {
INPUT_STATE_ANYWHERE,
{ 0x00, 0x17, NULL, NULL },
{ 0x19, 0x19, NULL, NULL },
{ 0x1c, 0x1f, NULL, NULL },
{ 0x20, 0xff, NULL, NULL },
{ -1, -1, NULL, NULL }
};
/* Input table compare. */
static int
input_table_compare(const void *key, const void *value)
{
const struct input_ctx *ictx = key;
const struct input_table_entry *entry = value;
if (ictx->ch != entry->ch)
return (ictx->ch - entry->ch);
return (strcmp(ictx->interm_buf, entry->interm));
}
/*
* Timer - if this expires then have been waiting for a terminator for too
* long, so reset to ground.
*/
static void
input_timer_callback(__unused int fd, __unused short events, void *arg)
{
struct input_ctx *ictx = arg;
log_debug("%s: %s expired" , __func__, ictx->state->name);
input_reset(ictx, 0);
}
/* Start the timer. */
static void
input_start_timer(struct input_ctx *ictx)
{
struct timeval tv = { .tv_sec = 5, .tv_usec = 0 };
event_del(&ictx->timer);
event_add(&ictx->timer, &tv);
}
/* Reset cell state to default. */
static void
input_reset_cell(struct input_ctx *ictx)
{
memcpy(&ictx->cell.cell, &grid_default_cell, sizeof ictx->cell.cell);
ictx->cell.set = 0;
ictx->cell.g0set = ictx->cell.g1set = 0;
memcpy(&ictx->old_cell, &ictx->cell, sizeof ictx->old_cell);
ictx->old_cx = 0;
ictx->old_cy = 0;
}
/* Save screen state. */
static void
input_save_state(struct input_ctx *ictx)
{
struct screen_write_ctx *sctx = &ictx->ctx;
struct screen *s = sctx->s;
memcpy(&ictx->old_cell, &ictx->cell, sizeof ictx->old_cell);
ictx->old_cx = s->cx;
ictx->old_cy = s->cy;
ictx->old_mode = s->mode;
}
/* Restore screen state. */
static void
input_restore_state(struct input_ctx *ictx)
{
struct screen_write_ctx *sctx = &ictx->ctx;
memcpy(&ictx->cell, &ictx->old_cell, sizeof ictx->cell);
if (ictx->old_mode & MODE_ORIGIN)
screen_write_mode_set(sctx, MODE_ORIGIN);
else
screen_write_mode_clear(sctx, MODE_ORIGIN);
screen_write_cursormove(sctx, ictx->old_cx, ictx->old_cy, 0);
}
/* Initialise input parser. */
struct input_ctx *
input_init(struct window_pane *wp, struct bufferevent *bev)
{
struct input_ctx *ictx;
ictx = xcalloc(1, sizeof *ictx);
ictx->wp = wp;
ictx->event = bev;
ictx->input_space = INPUT_BUF_START;
ictx->input_buf = xmalloc(INPUT_BUF_START);
ictx->since_ground = evbuffer_new();
if (ictx->since_ground == NULL)
fatalx("out of memory");
evtimer_set(&ictx->timer, input_timer_callback, ictx);
input_reset(ictx, 0);
return (ictx);
}
/* Destroy input parser. */
void
input_free(struct input_ctx *ictx)
{
u_int i;
for (i = 0; i < ictx->param_list_len; i++) {
if (ictx->param_list[i].type == INPUT_STRING)
free(ictx->param_list[i].str);
}
event_del(&ictx->timer);
free(ictx->input_buf);
evbuffer_free(ictx->since_ground);
free(ictx);
}
/* Reset input state and clear screen. */
void
input_reset(struct input_ctx *ictx, int clear)
{
struct screen_write_ctx *sctx = &ictx->ctx;
struct window_pane *wp = ictx->wp;
input_reset_cell(ictx);
if (clear && wp != NULL) {
if (TAILQ_EMPTY(&wp->modes))
screen_write_start_pane(sctx, wp, &wp->base);
else
screen_write_start(sctx, &wp->base);
screen_write_reset(sctx);
screen_write_stop(sctx);
}
input_clear(ictx);
ictx->last = -1;
ictx->state = &input_state_ground;
ictx->flags = 0;
}
/* Return pending data. */
struct evbuffer *
input_pending(struct input_ctx *ictx)
{
return (ictx->since_ground);
}
/* Change input state. */
static void
input_set_state(struct input_ctx *ictx, const struct input_transition *itr)
{
if (ictx->state->exit != NULL)
ictx->state->exit(ictx);
ictx->state = itr->state;
if (ictx->state->enter != NULL)
ictx->state->enter(ictx);
}
/* Parse data. */
static void
input_parse(struct input_ctx *ictx, u_char *buf, size_t len)
{
struct screen_write_ctx *sctx = &ictx->ctx;
const struct input_state *state = NULL;
const struct input_transition *itr = NULL;
size_t off = 0;
/* Parse the input. */
while (off < len) {
ictx->ch = buf[off++];
/* Find the transition. */
if (ictx->state != state ||
itr == NULL ||
ictx->ch < itr->first ||
ictx->ch > itr->last) {
itr = ictx->state->transitions;
while (itr->first != -1 && itr->last != -1) {
if (ictx->ch >= itr->first &&
ictx->ch <= itr->last)
break;
itr++;
}
if (itr->first == -1 || itr->last == -1) {
/* No transition? Eh? */
fatalx("no transition from state");
}
}
state = ictx->state;
/*
* Any state except print stops the current collection. This is
* an optimization to avoid checking if the attributes have
* changed for every character. It will stop unnecessarily for
* sequences that don't make a terminal change, but they should
* be the minority.
*/
if (itr->handler != input_print)
screen_write_collect_end(sctx);
/*
* Execute the handler, if any. Don't switch state if it
* returns non-zero.
*/
if (itr->handler != NULL && itr->handler(ictx) != 0)
continue;
/* And switch state, if necessary. */
if (itr->state != NULL)
input_set_state(ictx, itr);
/* If not in ground state, save input. */
if (ictx->state != &input_state_ground)
evbuffer_add(ictx->since_ground, &ictx->ch, 1);
}
}
/* Parse input from pane. */
void
input_parse_pane(struct window_pane *wp)
{
void *new_data;
size_t new_size;
new_data = window_pane_get_new_data(wp, &wp->offset, &new_size);
input_parse_buffer(wp, new_data, new_size);
window_pane_update_used_data(wp, &wp->offset, new_size);
}
/* Parse given input. */
void
input_parse_buffer(struct window_pane *wp, u_char *buf, size_t len)
{
struct input_ctx *ictx = wp->ictx;
struct screen_write_ctx *sctx = &ictx->ctx;
if (len == 0)
return;
window_update_activity(wp->window);
wp->flags |= PANE_CHANGED;
/* NULL wp if there is a mode set as don't want to update the tty. */
if (TAILQ_EMPTY(&wp->modes))
screen_write_start_pane(sctx, wp, &wp->base);
else
screen_write_start(sctx, &wp->base);
log_debug("%s: %%%u %s, %zu bytes: %.*s", __func__, wp->id,
ictx->state->name, len, (int)len, buf);
input_parse(ictx, buf, len);
screen_write_stop(sctx);
}
/* Parse given input for screen. */
void
input_parse_screen(struct input_ctx *ictx, struct screen *s,
screen_write_init_ctx_cb cb, void *arg, u_char *buf, size_t len)
{
struct screen_write_ctx *sctx = &ictx->ctx;
if (len == 0)
return;
screen_write_start_callback(sctx, s, cb, arg);
input_parse(ictx, buf, len);
screen_write_stop(sctx);
}
/* Split the parameter list (if any). */
static int
input_split(struct input_ctx *ictx)
{
const char *errstr;
char *ptr, *out;
struct input_param *ip;
u_int i;
for (i = 0; i < ictx->param_list_len; i++) {
if (ictx->param_list[i].type == INPUT_STRING)
free(ictx->param_list[i].str);
}
ictx->param_list_len = 0;
if (ictx->param_len == 0)
return (0);
ip = &ictx->param_list[0];
ptr = ictx->param_buf;
while ((out = strsep(&ptr, ";")) != NULL) {
if (*out == '\0')
ip->type = INPUT_MISSING;
else {
if (strchr(out, ':') != NULL) {
ip->type = INPUT_STRING;
ip->str = xstrdup(out);
} else {
ip->type = INPUT_NUMBER;
ip->num = strtonum(out, 0, INT_MAX, &errstr);
if (errstr != NULL)
return (-1);
}
}
ip = &ictx->param_list[++ictx->param_list_len];
if (ictx->param_list_len == nitems(ictx->param_list))
return (-1);
}
for (i = 0; i < ictx->param_list_len; i++) {
ip = &ictx->param_list[i];
if (ip->type == INPUT_MISSING)
log_debug("parameter %u: missing", i);
else if (ip->type == INPUT_STRING)
log_debug("parameter %u: string %s", i, ip->str);
else if (ip->type == INPUT_NUMBER)
log_debug("parameter %u: number %d", i, ip->num);
}
return (0);
}
/* Get an argument or return default value. */
static int
input_get(struct input_ctx *ictx, u_int validx, int minval, int defval)
{
struct input_param *ip;
int retval;
if (validx >= ictx->param_list_len)
return (defval);
ip = &ictx->param_list[validx];
if (ip->type == INPUT_MISSING)
return (defval);
if (ip->type == INPUT_STRING)
return (-1);
retval = ip->num;
if (retval < minval)
return (minval);
return (retval);
}
/* Reply to terminal query. */
static void
input_reply(struct input_ctx *ictx, const char *fmt, ...)
{
struct bufferevent *bev = ictx->event;
va_list ap;
char *reply;
va_start(ap, fmt);
xvasprintf(&reply, fmt, ap);
va_end(ap);
bufferevent_write(bev, reply, strlen(reply));
free(reply);
}
/* Clear saved state. */
static void
input_clear(struct input_ctx *ictx)
{
event_del(&ictx->timer);
*ictx->interm_buf = '\0';
ictx->interm_len = 0;
*ictx->param_buf = '\0';
ictx->param_len = 0;
*ictx->input_buf = '\0';
ictx->input_len = 0;
ictx->input_end = INPUT_END_ST;
ictx->flags &= ~INPUT_DISCARD;
}
/* Reset for ground state. */
static void
input_ground(struct input_ctx *ictx)
{
event_del(&ictx->timer);
evbuffer_drain(ictx->since_ground, EVBUFFER_LENGTH(ictx->since_ground));
if (ictx->input_space > INPUT_BUF_START) {
ictx->input_space = INPUT_BUF_START;
ictx->input_buf = xrealloc(ictx->input_buf, INPUT_BUF_START);
}
}
/* Output this character to the screen. */
static int
input_print(struct input_ctx *ictx)
{
struct screen_write_ctx *sctx = &ictx->ctx;
int set;
ictx->utf8started = 0; /* can't be valid UTF-8 */
set = ictx->cell.set == 0 ? ictx->cell.g0set : ictx->cell.g1set;
if (set == 1)
ictx->cell.cell.attr |= GRID_ATTR_CHARSET;
else
ictx->cell.cell.attr &= ~GRID_ATTR_CHARSET;
utf8_set(&ictx->cell.cell.data, ictx->ch);
screen_write_collect_add(sctx, &ictx->cell.cell);
ictx->last = ictx->ch;
ictx->cell.cell.attr &= ~GRID_ATTR_CHARSET;
return (0);
}
/* Collect intermediate string. */
static int
input_intermediate(struct input_ctx *ictx)
{
if (ictx->interm_len == (sizeof ictx->interm_buf) - 1)
ictx->flags |= INPUT_DISCARD;
else {
ictx->interm_buf[ictx->interm_len++] = ictx->ch;
ictx->interm_buf[ictx->interm_len] = '\0';
}
return (0);
}
/* Collect parameter string. */
static int
input_parameter(struct input_ctx *ictx)
{
if (ictx->param_len == (sizeof ictx->param_buf) - 1)
ictx->flags |= INPUT_DISCARD;
else {
ictx->param_buf[ictx->param_len++] = ictx->ch;
ictx->param_buf[ictx->param_len] = '\0';
}
return (0);
}
/* Collect input string. */
static int
input_input(struct input_ctx *ictx)
{
size_t available;
available = ictx->input_space;
while (ictx->input_len + 1 >= available) {
available *= 2;
if (available > INPUT_BUF_LIMIT) {
ictx->flags |= INPUT_DISCARD;
return (0);
}
ictx->input_buf = xrealloc(ictx->input_buf, available);
ictx->input_space = available;
}
ictx->input_buf[ictx->input_len++] = ictx->ch;
ictx->input_buf[ictx->input_len] = '\0';
return (0);
}
/* Execute C0 control sequence. */
static int
input_c0_dispatch(struct input_ctx *ictx)
{
struct screen_write_ctx *sctx = &ictx->ctx;
struct window_pane *wp = ictx->wp;
struct screen *s = sctx->s;
ictx->utf8started = 0; /* can't be valid UTF-8 */
log_debug("%s: '%c'", __func__, ictx->ch);
switch (ictx->ch) {
case '\000': /* NUL */
break;
case '\007': /* BEL */
if (wp != NULL)
alerts_queue(wp->window, WINDOW_BELL);
break;
case '\010': /* BS */
screen_write_backspace(sctx);
break;
case '\011': /* HT */
/* Don't tab beyond the end of the line. */
if (s->cx >= screen_size_x(s) - 1)
break;
/* Find the next tab point, or use the last column if none. */
do {
s->cx++;
if (bit_test(s->tabs, s->cx))
break;
} while (s->cx < screen_size_x(s) - 1);
break;
case '\012': /* LF */
case '\013': /* VT */
case '\014': /* FF */
screen_write_linefeed(sctx, 0, ictx->cell.cell.bg);
if (s->mode & MODE_CRLF)
screen_write_carriagereturn(sctx);
break;
case '\015': /* CR */
screen_write_carriagereturn(sctx);
break;
case '\016': /* SO */
ictx->cell.set = 1;
break;
case '\017': /* SI */
ictx->cell.set = 0;
break;
default:
log_debug("%s: unknown '%c'", __func__, ictx->ch);
break;
}
ictx->last = -1;
return (0);
}
/* Execute escape sequence. */
static int
input_esc_dispatch(struct input_ctx *ictx)
{
struct screen_write_ctx *sctx = &ictx->ctx;
struct window_pane *wp = ictx->wp;
struct screen *s = sctx->s;
struct input_table_entry *entry;
if (ictx->flags & INPUT_DISCARD)
return (0);
log_debug("%s: '%c', %s", __func__, ictx->ch, ictx->interm_buf);
entry = bsearch(ictx, input_esc_table, nitems(input_esc_table),
sizeof input_esc_table[0], input_table_compare);
if (entry == NULL) {
log_debug("%s: unknown '%c'", __func__, ictx->ch);
return (0);
}
switch (entry->type) {
case INPUT_ESC_RIS:
if (wp != NULL)
window_pane_reset_palette(wp);
input_reset_cell(ictx);
screen_write_reset(sctx);
break;
case INPUT_ESC_IND:
screen_write_linefeed(sctx, 0, ictx->cell.cell.bg);
break;
case INPUT_ESC_NEL:
screen_write_carriagereturn(sctx);
screen_write_linefeed(sctx, 0, ictx->cell.cell.bg);
break;
case INPUT_ESC_HTS:
if (s->cx < screen_size_x(s))
bit_set(s->tabs, s->cx);
break;
case INPUT_ESC_RI:
screen_write_reverseindex(sctx, ictx->cell.cell.bg);
break;
case INPUT_ESC_DECKPAM:
screen_write_mode_set(sctx, MODE_KKEYPAD);
break;
case INPUT_ESC_DECKPNM:
screen_write_mode_clear(sctx, MODE_KKEYPAD);
break;
case INPUT_ESC_DECSC:
input_save_state(ictx);
break;
case INPUT_ESC_DECRC:
input_restore_state(ictx);
break;
case INPUT_ESC_DECALN:
screen_write_alignmenttest(sctx);
break;
case INPUT_ESC_SCSG0_ON:
ictx->cell.g0set = 1;
break;
case INPUT_ESC_SCSG0_OFF:
ictx->cell.g0set = 0;
break;
case INPUT_ESC_SCSG1_ON:
ictx->cell.g1set = 1;
break;
case INPUT_ESC_SCSG1_OFF:
ictx->cell.g1set = 0;
break;
case INPUT_ESC_ST:
/* ST terminates OSC but the state transition already did it. */
break;
}
ictx->last = -1;
return (0);
}
/* Execute control sequence. */
static int
input_csi_dispatch(struct input_ctx *ictx)
{
struct screen_write_ctx *sctx = &ictx->ctx;
struct screen *s = sctx->s;
struct input_table_entry *entry;
int i, n, m;
u_int cx, bg = ictx->cell.cell.bg;
if (ictx->flags & INPUT_DISCARD)
return (0);
log_debug("%s: '%c' \"%s\" \"%s\"",
__func__, ictx->ch, ictx->interm_buf, ictx->param_buf);
if (input_split(ictx) != 0)
return (0);
entry = bsearch(ictx, input_csi_table, nitems(input_csi_table),
sizeof input_csi_table[0], input_table_compare);
if (entry == NULL) {
log_debug("%s: unknown '%c'", __func__, ictx->ch);
return (0);
}
switch (entry->type) {
case INPUT_CSI_CBT:
/* Find the previous tab point, n times. */
cx = s->cx;
if (cx > screen_size_x(s) - 1)
cx = screen_size_x(s) - 1;
n = input_get(ictx, 0, 1, 1);
if (n == -1)
break;
while (cx > 0 && n-- > 0) {
do
cx--;
while (cx > 0 && !bit_test(s->tabs, cx));
}
s->cx = cx;
break;
case INPUT_CSI_CUB:
n = input_get(ictx, 0, 1, 1);
if (n != -1)
screen_write_cursorleft(sctx, n);
break;
case INPUT_CSI_CUD:
n = input_get(ictx, 0, 1, 1);
if (n != -1)
screen_write_cursordown(sctx, n);
break;
case INPUT_CSI_CUF:
n = input_get(ictx, 0, 1, 1);
if (n != -1)
screen_write_cursorright(sctx, n);
break;
case INPUT_CSI_CUP:
n = input_get(ictx, 0, 1, 1);
m = input_get(ictx, 1, 1, 1);
if (n != -1 && m != -1)
screen_write_cursormove(sctx, m - 1, n - 1, 1);
break;
case INPUT_CSI_MODSET:
n = input_get(ictx, 0, 0, 0);
m = input_get(ictx, 1, 0, 0);
if (n == 0 || (n == 4 && m == 0))
screen_write_mode_clear(sctx, MODE_KEXTENDED);
else if (n == 4 && (m == 1 || m == 2))
screen_write_mode_set(sctx, MODE_KEXTENDED);
break;
case INPUT_CSI_MODOFF:
n = input_get(ictx, 0, 0, 0);
if (n == 4)
screen_write_mode_clear(sctx, MODE_KEXTENDED);
break;
case INPUT_CSI_WINOPS:
input_csi_dispatch_winops(ictx);
break;
case INPUT_CSI_CUU:
n = input_get(ictx, 0, 1, 1);
if (n != -1)
screen_write_cursorup(sctx, n);
break;
case INPUT_CSI_CNL:
n = input_get(ictx, 0, 1, 1);
if (n != -1) {
screen_write_carriagereturn(sctx);
screen_write_cursordown(sctx, n);
}
break;
case INPUT_CSI_CPL:
n = input_get(ictx, 0, 1, 1);
if (n != -1) {
screen_write_carriagereturn(sctx);
screen_write_cursorup(sctx, n);
}
break;
case INPUT_CSI_DA:
switch (input_get(ictx, 0, 0, 0)) {
case -1:
break;
case 0:
input_reply(ictx, "\033[?1;2c");
break;
default:
log_debug("%s: unknown '%c'", __func__, ictx->ch);
break;
}
break;
case INPUT_CSI_DA_TWO:
switch (input_get(ictx, 0, 0, 0)) {
case -1:
break;
case 0:
input_reply(ictx, "\033[>84;0;0c");
break;
default:
log_debug("%s: unknown '%c'", __func__, ictx->ch);
break;
}
break;
case INPUT_CSI_ECH:
n = input_get(ictx, 0, 1, 1);
if (n != -1)
screen_write_clearcharacter(sctx, n, bg);
break;
case INPUT_CSI_DCH:
n = input_get(ictx, 0, 1, 1);
if (n != -1)
screen_write_deletecharacter(sctx, n, bg);
break;
case INPUT_CSI_DECSTBM:
n = input_get(ictx, 0, 1, 1);
m = input_get(ictx, 1, 1, screen_size_y(s));
if (n != -1 && m != -1)
screen_write_scrollregion(sctx, n - 1, m - 1);
break;
case INPUT_CSI_DL:
n = input_get(ictx, 0, 1, 1);
if (n != -1)
screen_write_deleteline(sctx, n, bg);
break;
case INPUT_CSI_DSR:
switch (input_get(ictx, 0, 0, 0)) {
case -1:
break;
case 5:
input_reply(ictx, "\033[0n");
break;
case 6:
input_reply(ictx, "\033[%u;%uR", s->cy + 1, s->cx + 1);
break;
default:
log_debug("%s: unknown '%c'", __func__, ictx->ch);
break;
}
break;
case INPUT_CSI_ED:
switch (input_get(ictx, 0, 0, 0)) {
case -1:
break;
case 0:
screen_write_clearendofscreen(sctx, bg);
break;
case 1:
screen_write_clearstartofscreen(sctx, bg);
break;
case 2:
screen_write_clearscreen(sctx, bg);
break;
case 3:
if (input_get(ictx, 1, 0, 0) == 0) {
/*
* Linux console extension to clear history
* (for example before locking the screen).
*/
screen_write_clearhistory(sctx);
}
break;
default:
log_debug("%s: unknown '%c'", __func__, ictx->ch);
break;
}
break;
case INPUT_CSI_EL:
switch (input_get(ictx, 0, 0, 0)) {
case -1:
break;
case 0:
screen_write_clearendofline(sctx, bg);
break;
case 1:
screen_write_clearstartofline(sctx, bg);
break;
case 2:
screen_write_clearline(sctx, bg);
break;
default:
log_debug("%s: unknown '%c'", __func__, ictx->ch);
break;
}
break;
case INPUT_CSI_HPA:
n = input_get(ictx, 0, 1, 1);
if (n != -1)
screen_write_cursormove(sctx, n - 1, -1, 1);
break;
case INPUT_CSI_ICH:
n = input_get(ictx, 0, 1, 1);
if (n != -1)
screen_write_insertcharacter(sctx, n, bg);
break;
case INPUT_CSI_IL:
n = input_get(ictx, 0, 1, 1);
if (n != -1)
screen_write_insertline(sctx, n, bg);
break;
case INPUT_CSI_REP:
n = input_get(ictx, 0, 1, 1);
if (n == -1)
break;
if (ictx->last == -1)
break;
ictx->ch = ictx->last;
for (i = 0; i < n; i++)
input_print(ictx);
break;
case INPUT_CSI_RCP:
input_restore_state(ictx);
break;
case INPUT_CSI_RM:
input_csi_dispatch_rm(ictx);
break;
case INPUT_CSI_RM_PRIVATE:
input_csi_dispatch_rm_private(ictx);
break;
case INPUT_CSI_SCP:
input_save_state(ictx);
break;
case INPUT_CSI_SGR:
input_csi_dispatch_sgr(ictx);
break;
case INPUT_CSI_SM:
input_csi_dispatch_sm(ictx);
break;
case INPUT_CSI_SM_PRIVATE:
input_csi_dispatch_sm_private(ictx);
break;
case INPUT_CSI_SU:
n = input_get(ictx, 0, 1, 1);
if (n != -1)
screen_write_scrollup(sctx, n, bg);
break;
case INPUT_CSI_SD:
n = input_get(ictx, 0, 1, 1);
if (n != -1)
screen_write_scrolldown(sctx, n, bg);
break;
case INPUT_CSI_TBC:
switch (input_get(ictx, 0, 0, 0)) {
case -1:
break;
case 0:
if (s->cx < screen_size_x(s))
bit_clear(s->tabs, s->cx);
break;
case 3:
bit_nclear(s->tabs, 0, screen_size_x(s) - 1);
break;
default:
log_debug("%s: unknown '%c'", __func__, ictx->ch);
break;
}
break;
case INPUT_CSI_VPA:
n = input_get(ictx, 0, 1, 1);
if (n != -1)
screen_write_cursormove(sctx, -1, n - 1, 1);
break;
case INPUT_CSI_DECSCUSR:
n = input_get(ictx, 0, 0, 0);
if (n != -1)
screen_set_cursor_style(s, n);
break;
case INPUT_CSI_XDA:
n = input_get(ictx, 0, 0, 0);
if (n == 0)
input_reply(ictx, "\033P>|tmux %s\033\\", getversion());
break;
}
ictx->last = -1;
return (0);
}
/* Handle CSI RM. */
static void
input_csi_dispatch_rm(struct input_ctx *ictx)
{
struct screen_write_ctx *sctx = &ictx->ctx;
u_int i;
for (i = 0; i < ictx->param_list_len; i++) {
switch (input_get(ictx, i, 0, -1)) {
case -1:
break;
case 4: /* IRM */
screen_write_mode_clear(sctx, MODE_INSERT);
break;
case 34:
screen_write_mode_set(sctx, MODE_BLINKING);
break;
default:
log_debug("%s: unknown '%c'", __func__, ictx->ch);
break;
}
}
}
/* Handle CSI private RM. */
static void
input_csi_dispatch_rm_private(struct input_ctx *ictx)
{
struct screen_write_ctx *sctx = &ictx->ctx;
struct grid_cell *gc = &ictx->cell.cell;
u_int i;
for (i = 0; i < ictx->param_list_len; i++) {
switch (input_get(ictx, i, 0, -1)) {
case -1:
break;
case 1: /* DECCKM */
screen_write_mode_clear(sctx, MODE_KCURSOR);
break;
case 3: /* DECCOLM */
screen_write_cursormove(sctx, 0, 0, 1);
screen_write_clearscreen(sctx, gc->bg);
break;
case 6: /* DECOM */
screen_write_mode_clear(sctx, MODE_ORIGIN);
screen_write_cursormove(sctx, 0, 0, 1);
break;
case 7: /* DECAWM */
screen_write_mode_clear(sctx, MODE_WRAP);
break;
case 12:
screen_write_mode_clear(sctx, MODE_BLINKING);
break;
case 25: /* TCEM */
screen_write_mode_clear(sctx, MODE_CURSOR);
break;
case 1000:
case 1001:
case 1002:
case 1003:
screen_write_mode_clear(sctx, ALL_MOUSE_MODES);
break;
case 1004:
screen_write_mode_clear(sctx, MODE_FOCUSON);
break;
case 1005:
screen_write_mode_clear(sctx, MODE_MOUSE_UTF8);
break;
case 1006:
screen_write_mode_clear(sctx, MODE_MOUSE_SGR);
break;
case 47:
case 1047:
screen_write_alternateoff(sctx, gc, 0);
break;
case 1049:
screen_write_alternateoff(sctx, gc, 1);
break;
case 2004:
screen_write_mode_clear(sctx, MODE_BRACKETPASTE);
break;
default:
log_debug("%s: unknown '%c'", __func__, ictx->ch);
break;
}
}
}
/* Handle CSI SM. */
static void
input_csi_dispatch_sm(struct input_ctx *ictx)
{
struct screen_write_ctx *sctx = &ictx->ctx;
u_int i;
for (i = 0; i < ictx->param_list_len; i++) {
switch (input_get(ictx, i, 0, -1)) {
case -1:
break;
case 4: /* IRM */
screen_write_mode_set(sctx, MODE_INSERT);
break;
case 34:
screen_write_mode_clear(sctx, MODE_BLINKING);
break;
default:
log_debug("%s: unknown '%c'", __func__, ictx->ch);
break;
}
}
}
/* Handle CSI private SM. */
static void
input_csi_dispatch_sm_private(struct input_ctx *ictx)
{
struct screen_write_ctx *sctx = &ictx->ctx;
struct window_pane *wp = ictx->wp;
struct grid_cell *gc = &ictx->cell.cell;
u_int i;
for (i = 0; i < ictx->param_list_len; i++) {
switch (input_get(ictx, i, 0, -1)) {
case -1:
break;
case 1: /* DECCKM */
screen_write_mode_set(sctx, MODE_KCURSOR);
break;
case 3: /* DECCOLM */
screen_write_cursormove(sctx, 0, 0, 1);
screen_write_clearscreen(sctx, ictx->cell.cell.bg);
break;
case 6: /* DECOM */
screen_write_mode_set(sctx, MODE_ORIGIN);
screen_write_cursormove(sctx, 0, 0, 1);
break;
case 7: /* DECAWM */
screen_write_mode_set(sctx, MODE_WRAP);
break;
case 12:
screen_write_mode_set(sctx, MODE_BLINKING);
break;
case 25: /* TCEM */
screen_write_mode_set(sctx, MODE_CURSOR);
break;
case 1000:
screen_write_mode_clear(sctx, ALL_MOUSE_MODES);
screen_write_mode_set(sctx, MODE_MOUSE_STANDARD);
break;
case 1002:
screen_write_mode_clear(sctx, ALL_MOUSE_MODES);
screen_write_mode_set(sctx, MODE_MOUSE_BUTTON);
break;
case 1003:
screen_write_mode_clear(sctx, ALL_MOUSE_MODES);
screen_write_mode_set(sctx, MODE_MOUSE_ALL);
break;
case 1004:
if (sctx->s->mode & MODE_FOCUSON)
break;
screen_write_mode_set(sctx, MODE_FOCUSON);
if (wp != NULL)
wp->flags |= PANE_FOCUSPUSH; /* force update */
break;
case 1005:
screen_write_mode_set(sctx, MODE_MOUSE_UTF8);
break;
case 1006:
screen_write_mode_set(sctx, MODE_MOUSE_SGR);
break;
case 47:
case 1047:
screen_write_alternateon(sctx, gc, 0);
break;
case 1049:
screen_write_alternateon(sctx, gc, 1);
break;
case 2004:
screen_write_mode_set(sctx, MODE_BRACKETPASTE);
break;
default:
log_debug("%s: unknown '%c'", __func__, ictx->ch);
break;
}
}
}
/* Handle CSI window operations. */
static void
input_csi_dispatch_winops(struct input_ctx *ictx)
{
struct screen_write_ctx *sctx = &ictx->ctx;
struct screen *s = sctx->s;
struct window_pane *wp = ictx->wp;
u_int x = screen_size_x(s), y = screen_size_y(s);
int n, m;
m = 0;
while ((n = input_get(ictx, m, 0, -1)) != -1) {
switch (n) {
case 1:
case 2:
case 5:
case 6:
case 7:
case 11:
case 13:
case 14:
case 19:
case 20:
case 21:
case 24:
break;
case 3:
case 4:
case 8:
m++;
if (input_get(ictx, m, 0, -1) == -1)
return;
/* FALLTHROUGH */
case 9:
case 10:
m++;
if (input_get(ictx, m, 0, -1) == -1)
return;
break;
case 22:
m++;
switch (input_get(ictx, m, 0, -1)) {
case -1:
return;
case 0:
case 2:
screen_push_title(sctx->s);
break;
}
break;
case 23:
m++;
switch (input_get(ictx, m, 0, -1)) {
case -1:
return;
case 0:
case 2:
screen_pop_title(sctx->s);
if (wp != NULL) {
notify_pane("pane-title-changed", wp);
server_redraw_window_borders(wp->window);
server_status_window(wp->window);
}
break;
}
break;
case 18:
input_reply(ictx, "\033[8;%u;%ut", x, y);
break;
default:
log_debug("%s: unknown '%c'", __func__, ictx->ch);
break;
}
m++;
}
}
/* Helper for 256 colour SGR. */
static int
input_csi_dispatch_sgr_256_do(struct input_ctx *ictx, int fgbg, int c)
{
struct grid_cell *gc = &ictx->cell.cell;
if (c == -1 || c > 255) {
if (fgbg == 38)
gc->fg = 8;
else if (fgbg == 48)
gc->bg = 8;
} else {
if (fgbg == 38)
gc->fg = c | COLOUR_FLAG_256;
else if (fgbg == 48)
gc->bg = c | COLOUR_FLAG_256;
else if (fgbg == 58)
gc->us = c | COLOUR_FLAG_256;
}
return (1);
}
/* Handle CSI SGR for 256 colours. */
static void
input_csi_dispatch_sgr_256(struct input_ctx *ictx, int fgbg, u_int *i)
{
int c;
c = input_get(ictx, (*i) + 1, 0, -1);
if (input_csi_dispatch_sgr_256_do(ictx, fgbg, c))
(*i)++;
}
/* Helper for RGB colour SGR. */
static int
input_csi_dispatch_sgr_rgb_do(struct input_ctx *ictx, int fgbg, int r, int g,
int b)
{
struct grid_cell *gc = &ictx->cell.cell;
if (r == -1 || r > 255)
return (0);
if (g == -1 || g > 255)
return (0);
if (b == -1 || b > 255)
return (0);
if (fgbg == 38)
gc->fg = colour_join_rgb(r, g, b);
else if (fgbg == 48)
gc->bg = colour_join_rgb(r, g, b);
else if (fgbg == 58)
gc->us = colour_join_rgb(r, g, b);
return (1);
}
/* Handle CSI SGR for RGB colours. */
static void
input_csi_dispatch_sgr_rgb(struct input_ctx *ictx, int fgbg, u_int *i)
{
int r, g, b;
r = input_get(ictx, (*i) + 1, 0, -1);
g = input_get(ictx, (*i) + 2, 0, -1);
b = input_get(ictx, (*i) + 3, 0, -1);
if (input_csi_dispatch_sgr_rgb_do(ictx, fgbg, r, g, b))
(*i) += 3;
}
/* Handle CSI SGR with a ISO parameter. */
static void
input_csi_dispatch_sgr_colon(struct input_ctx *ictx, u_int i)
{
struct grid_cell *gc = &ictx->cell.cell;
char *s = ictx->param_list[i].str, *copy, *ptr, *out;
int p[8];
u_int n;
const char *errstr;
for (n = 0; n < nitems(p); n++)
p[n] = -1;
n = 0;
ptr = copy = xstrdup(s);
while ((out = strsep(&ptr, ":")) != NULL) {
if (*out != '\0') {
p[n++] = strtonum(out, 0, INT_MAX, &errstr);
if (errstr != NULL || n == nitems(p)) {
free(copy);
return;
}
} else {
n++;
if (n == nitems(p)) {
free(copy);
return;
}
}
log_debug("%s: %u = %d", __func__, n - 1, p[n - 1]);
}
free(copy);
if (n == 0)
return;
if (p[0] == 4) {
if (n != 2)
return;
switch (p[1]) {
case 0:
gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;
break;
case 1:
gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;
gc->attr |= GRID_ATTR_UNDERSCORE;
break;
case 2:
gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;
gc->attr |= GRID_ATTR_UNDERSCORE_2;
break;
case 3:
gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;
gc->attr |= GRID_ATTR_UNDERSCORE_3;
break;
case 4:
gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;
gc->attr |= GRID_ATTR_UNDERSCORE_4;
break;
case 5:
gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;
gc->attr |= GRID_ATTR_UNDERSCORE_5;
break;
}
return;
}
if (n < 2 || (p[0] != 38 && p[0] != 48 && p[0] != 58))
return;
switch (p[1]) {
case 2:
if (n < 3)
break;
if (n == 5)
i = 2;
else
i = 3;
if (n < i + 3)
break;
input_csi_dispatch_sgr_rgb_do(ictx, p[0], p[i], p[i + 1],
p[i + 2]);
break;
case 5:
if (n < 3)
break;
input_csi_dispatch_sgr_256_do(ictx, p[0], p[2]);
break;
}
}
/* Handle CSI SGR. */
static void
input_csi_dispatch_sgr(struct input_ctx *ictx)
{
struct grid_cell *gc = &ictx->cell.cell;
u_int i;
int n;
if (ictx->param_list_len == 0) {
memcpy(gc, &grid_default_cell, sizeof *gc);
return;
}
for (i = 0; i < ictx->param_list_len; i++) {
if (ictx->param_list[i].type == INPUT_STRING) {
input_csi_dispatch_sgr_colon(ictx, i);
continue;
}
n = input_get(ictx, i, 0, 0);
if (n == -1)
continue;
if (n == 38 || n == 48 || n == 58) {
i++;
switch (input_get(ictx, i, 0, -1)) {
case 2:
input_csi_dispatch_sgr_rgb(ictx, n, &i);
break;
case 5:
input_csi_dispatch_sgr_256(ictx, n, &i);
break;
}
continue;
}
switch (n) {
case 0:
memcpy(gc, &grid_default_cell, sizeof *gc);
break;
case 1:
gc->attr |= GRID_ATTR_BRIGHT;
break;
case 2:
gc->attr |= GRID_ATTR_DIM;
break;
case 3:
gc->attr |= GRID_ATTR_ITALICS;
break;
case 4:
gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;
gc->attr |= GRID_ATTR_UNDERSCORE;
break;
case 5:
gc->attr |= GRID_ATTR_BLINK;
break;
case 7:
gc->attr |= GRID_ATTR_REVERSE;
break;
case 8:
gc->attr |= GRID_ATTR_HIDDEN;
break;
case 9:
gc->attr |= GRID_ATTR_STRIKETHROUGH;
break;
case 22:
gc->attr &= ~(GRID_ATTR_BRIGHT|GRID_ATTR_DIM);
break;
case 23:
gc->attr &= ~GRID_ATTR_ITALICS;
break;
case 24:
gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;
break;
case 25:
gc->attr &= ~GRID_ATTR_BLINK;
break;
case 27:
gc->attr &= ~GRID_ATTR_REVERSE;
break;
case 28:
gc->attr &= ~GRID_ATTR_HIDDEN;
break;
case 29:
gc->attr &= ~GRID_ATTR_STRIKETHROUGH;
break;
case 30:
case 31:
case 32:
case 33:
case 34:
case 35:
case 36:
case 37:
gc->fg = n - 30;
break;
case 39:
gc->fg = 8;
break;
case 40:
case 41:
case 42:
case 43:
case 44:
case 45:
case 46:
case 47:
gc->bg = n - 40;
break;
case 49:
gc->bg = 8;
break;
case 53:
gc->attr |= GRID_ATTR_OVERLINE;
break;
case 55:
gc->attr &= ~GRID_ATTR_OVERLINE;
break;
case 59:
gc->us = 0;
break;
case 90:
case 91:
case 92:
case 93:
case 94:
case 95:
case 96:
case 97:
gc->fg = n;
break;
case 100:
case 101:
case 102:
case 103:
case 104:
case 105:
case 106:
case 107:
gc->bg = n - 10;
break;
}
}
}
/* End of input with BEL. */
static int
input_end_bel(struct input_ctx *ictx)
{
log_debug("%s", __func__);
ictx->input_end = INPUT_END_BEL;
return (0);
}
/* DCS string started. */
static void
input_enter_dcs(struct input_ctx *ictx)
{
log_debug("%s", __func__);
input_clear(ictx);
input_start_timer(ictx);
ictx->last = -1;
}
/* DCS terminator (ST) received. */
static int
input_dcs_dispatch(struct input_ctx *ictx)
{
struct screen_write_ctx *sctx = &ictx->ctx;
u_char *buf = ictx->input_buf;
size_t len = ictx->input_len;
const char prefix[] = "tmux;";
const u_int prefixlen = (sizeof prefix) - 1;
if (ictx->flags & INPUT_DISCARD)
return (0);
log_debug("%s: \"%s\"", __func__, buf);
if (len >= prefixlen && strncmp(buf, prefix, prefixlen) == 0)
screen_write_rawstring(sctx, buf + prefixlen, len - prefixlen);
return (0);
}
/* OSC string started. */
static void
input_enter_osc(struct input_ctx *ictx)
{
log_debug("%s", __func__);
input_clear(ictx);
input_start_timer(ictx);
ictx->last = -1;
}
/* OSC terminator (ST) received. */
static void
input_exit_osc(struct input_ctx *ictx)
{
struct screen_write_ctx *sctx = &ictx->ctx;
struct window_pane *wp = ictx->wp;
u_char *p = ictx->input_buf;
u_int option;
if (ictx->flags & INPUT_DISCARD)
return;
if (ictx->input_len < 1 || *p < '0' || *p > '9')
return;
log_debug("%s: \"%s\" (end %s)", __func__, p,
ictx->input_end == INPUT_END_ST ? "ST" : "BEL");
option = 0;
while (*p >= '0' && *p <= '9')
option = option * 10 + *p++ - '0';
if (*p == ';')
p++;
switch (option) {
case 0:
case 2:
if (screen_set_title(sctx->s, p) && wp != NULL) {
notify_pane("pane-title-changed", wp);
server_redraw_window_borders(wp->window);
server_status_window(wp->window);
}
break;
case 4:
input_osc_4(ictx, p);
break;
case 7:
if (utf8_isvalid(p)) {
screen_set_path(sctx->s, p);
if (wp != NULL) {
server_redraw_window_borders(wp->window);
server_status_window(wp->window);
}
}
break;
case 10:
input_osc_10(ictx, p);
break;
case 11:
input_osc_11(ictx, p);
break;
case 12:
if (utf8_isvalid(p) && *p != '?') /* ? is colour request */
screen_set_cursor_colour(sctx->s, p);
break;
case 52:
input_osc_52(ictx, p);
break;
case 104:
input_osc_104(ictx, p);
break;
case 112:
if (*p == '\0') /* no arguments allowed */
screen_set_cursor_colour(sctx->s, "");
break;
default:
log_debug("%s: unknown '%u'", __func__, option);
break;
}
}
/* APC string started. */
static void
input_enter_apc(struct input_ctx *ictx)
{
log_debug("%s", __func__);
input_clear(ictx);
input_start_timer(ictx);
ictx->last = -1;
}
/* APC terminator (ST) received. */
static void
input_exit_apc(struct input_ctx *ictx)
{
struct screen_write_ctx *sctx = &ictx->ctx;
struct window_pane *wp = ictx->wp;
if (ictx->flags & INPUT_DISCARD)
return;
log_debug("%s: \"%s\"", __func__, ictx->input_buf);
if (screen_set_title(sctx->s, ictx->input_buf) && wp != NULL) {
notify_pane("pane-title-changed", wp);
server_redraw_window_borders(wp->window);
server_status_window(wp->window);
}
}
/* Rename string started. */
static void
input_enter_rename(struct input_ctx *ictx)
{
log_debug("%s", __func__);
input_clear(ictx);
input_start_timer(ictx);
ictx->last = -1;
}
/* Rename terminator (ST) received. */
static void
input_exit_rename(struct input_ctx *ictx)
{
struct window_pane *wp = ictx->wp;
struct options_entry *o;
if (wp == NULL)
return;
if (ictx->flags & INPUT_DISCARD)
return;
if (!options_get_number(ictx->wp->options, "allow-rename"))
return;
log_debug("%s: \"%s\"", __func__, ictx->input_buf);
if (!utf8_isvalid(ictx->input_buf))
return;
if (ictx->input_len == 0) {
o = options_get_only(wp->window->options, "automatic-rename");
if (o != NULL)
options_remove_or_default(o, -1, NULL);
return;
}
window_set_name(wp->window, ictx->input_buf);
options_set_number(wp->window->options, "automatic-rename", 0);
server_redraw_window_borders(wp->window);
server_status_window(wp->window);
}
/* Open UTF-8 character. */
static int
input_top_bit_set(struct input_ctx *ictx)
{
struct screen_write_ctx *sctx = &ictx->ctx;
struct utf8_data *ud = &ictx->utf8data;
ictx->last = -1;
if (!ictx->utf8started) {
if (utf8_open(ud, ictx->ch) != UTF8_MORE)
return (0);
ictx->utf8started = 1;
return (0);
}
switch (utf8_append(ud, ictx->ch)) {
case UTF8_MORE:
return (0);
case UTF8_ERROR:
ictx->utf8started = 0;
return (0);
case UTF8_DONE:
break;
}
ictx->utf8started = 0;
log_debug("%s %hhu '%*s' (width %hhu)", __func__, ud->size,
(int)ud->size, ud->data, ud->width);
utf8_copy(&ictx->cell.cell.data, ud);
screen_write_collect_add(sctx, &ictx->cell.cell);
return (0);
}
/* Parse colour from OSC. */
static int
input_osc_parse_colour(const char *p, u_int *r, u_int *g, u_int *b)
{
u_int rsize, gsize, bsize;
const char *cp, *s = p;
if (sscanf(p, "rgb:%x/%x/%x", r, g, b) != 3)
return (0);
p += 4;
cp = strchr(p, '/');
rsize = cp - p;
if (rsize == 1)
(*r) = (*r) | ((*r) << 4);
else if (rsize == 3)
(*r) >>= 4;
else if (rsize == 4)
(*r) >>= 8;
else if (rsize != 2)
return (0);
p = cp + 1;
cp = strchr(p, '/');
gsize = cp - p;
if (gsize == 1)
(*g) = (*g) | ((*g) << 4);
else if (gsize == 3)
(*g) >>= 4;
else if (gsize == 4)
(*g) >>= 8;
else if (gsize != 2)
return (0);
bsize = strlen(cp + 1);
if (bsize == 1)
(*b) = (*b) | ((*b) << 4);
else if (bsize == 3)
(*b) >>= 4;
else if (bsize == 4)
(*b) >>= 8;
else if (bsize != 2)
return (0);
log_debug("%s: %s = %02x%02x%02x", __func__, s, *r, *g, *b);
return (1);
}
/* Reply to a colour request. */
static void
input_osc_colour_reply(struct input_ctx *ictx, u_int n, int c)
{
u_char r, g, b;
const char *end;
if (c == 8 || (~c & COLOUR_FLAG_RGB))
return;
colour_split_rgb(c, &r, &g, &b);
if (ictx->input_end == INPUT_END_BEL)
end = "\007";
else
end = "\033\\";
input_reply(ictx, "\033]%u;rgb:%02hhx/%02hhx/%02hhx%s", n, r, g, b, end);
}
/* Handle the OSC 4 sequence for setting (multiple) palette entries. */
static void
input_osc_4(struct input_ctx *ictx, const char *p)
{
struct window_pane *wp = ictx->wp;
char *copy, *s, *next = NULL;
long idx;
u_int r, g, b;
if (wp == NULL)
return;
copy = s = xstrdup(p);
while (s != NULL && *s != '\0') {
idx = strtol(s, &next, 10);
if (*next++ != ';')
goto bad;
if (idx < 0 || idx >= 0x100)
goto bad;
s = strsep(&next, ";");
if (!input_osc_parse_colour(s, &r, &g, &b)) {
s = next;
continue;
}
window_pane_set_palette(wp, idx, colour_join_rgb(r, g, b));
s = next;
}
free(copy);
return;
bad:
log_debug("bad OSC 4: %s", p);
free(copy);
}
/* Handle the OSC 10 sequence for setting and querying foreground colour. */
static void
input_osc_10(struct input_ctx *ictx, const char *p)
{
struct window_pane *wp = ictx->wp;
struct grid_cell defaults;
u_int r, g, b;
if (wp == NULL)
return;
if (strcmp(p, "?") == 0) {
tty_default_colours(&defaults, wp);
input_osc_colour_reply(ictx, 10, defaults.fg);
return;
}
if (!input_osc_parse_colour(p, &r, &g, &b))
goto bad;
wp->fg = colour_join_rgb(r, g, b);
wp->flags |= (PANE_REDRAW|PANE_STYLECHANGED);
return;
bad:
log_debug("bad OSC 10: %s", p);
}
/* Handle the OSC 11 sequence for setting and querying background colour. */
static void
input_osc_11(struct input_ctx *ictx, const char *p)
{
struct window_pane *wp = ictx->wp;
struct grid_cell defaults;
u_int r, g, b;
if (wp == NULL)
return;
if (strcmp(p, "?") == 0) {
tty_default_colours(&defaults, wp);
input_osc_colour_reply(ictx, 11, defaults.bg);
return;
}
if (!input_osc_parse_colour(p, &r, &g, &b))
goto bad;
wp->bg = colour_join_rgb(r, g, b);
wp->flags |= (PANE_REDRAW|PANE_STYLECHANGED);
return;
bad:
log_debug("bad OSC 11: %s", p);
}
/* Handle the OSC 52 sequence for setting the clipboard. */
static void
input_osc_52(struct input_ctx *ictx, const char *p)
{
struct window_pane *wp = ictx->wp;
char *end;
const char *buf;
size_t len;
u_char *out;
int outlen, state;
struct screen_write_ctx ctx;
struct paste_buffer *pb;
if (wp == NULL)
return;
state = options_get_number(global_options, "set-clipboard");
if (state != 2)
return;
if ((end = strchr(p, ';')) == NULL)
return;
end++;
if (*end == '\0')
return;
log_debug("%s: %s", __func__, end);
if (strcmp(end, "?") == 0) {
if ((pb = paste_get_top(NULL)) != NULL) {
buf = paste_buffer_data(pb, &len);
outlen = 4 * ((len + 2) / 3) + 1;
out = xmalloc(outlen);
if ((outlen = b64_ntop(buf, len, out, outlen)) == -1) {
free(out);
return;
}
} else {
outlen = 0;
out = NULL;
}
bufferevent_write(ictx->event, "\033]52;;", 6);
if (outlen != 0)
bufferevent_write(ictx->event, out, outlen);
if (ictx->input_end == INPUT_END_BEL)
bufferevent_write(ictx->event, "\007", 1);
else
bufferevent_write(ictx->event, "\033\\", 2);
free(out);
return;
}
len = (strlen(end) / 4) * 3;
if (len == 0)
return;
out = xmalloc(len);
if ((outlen = b64_pton(end, out, len)) == -1) {
free(out);
return;
}
screen_write_start_pane(&ctx, wp, NULL);
screen_write_setselection(&ctx, out, outlen);
screen_write_stop(&ctx);
notify_pane("pane-set-clipboard", wp);
paste_add(NULL, out, outlen);
}
/* Handle the OSC 104 sequence for unsetting (multiple) palette entries. */
static void
input_osc_104(struct input_ctx *ictx, const char *p)
{
struct window_pane *wp = ictx->wp;
char *copy, *s;
long idx;
if (wp == NULL)
return;
if (*p == '\0') {
window_pane_reset_palette(wp);
return;
}
copy = s = xstrdup(p);
while (*s != '\0') {
idx = strtol(s, &s, 10);
if (*s != '\0' && *s != ';')
goto bad;
if (idx < 0 || idx >= 0x100)
goto bad;
window_pane_unset_palette(wp, idx);
if (*s == ';')
s++;
}
free(copy);
return;
bad:
log_debug("bad OSC 104: %s", p);
free(copy);
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_4410_0 |
crossvul-cpp_data_good_5478_2 | /* $Id$ */
/*
* Copyright (c) 1988-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.
*
* Scanline-oriented Write Support
*/
#include "tiffiop.h"
#include <stdio.h>
#define STRIPINCR 20 /* expansion factor on strip array */
#define WRITECHECKSTRIPS(tif, module) \
(((tif)->tif_flags&TIFF_BEENWRITING) || TIFFWriteCheck((tif),0,module))
#define WRITECHECKTILES(tif, module) \
(((tif)->tif_flags&TIFF_BEENWRITING) || TIFFWriteCheck((tif),1,module))
#define BUFFERCHECK(tif) \
((((tif)->tif_flags & TIFF_BUFFERSETUP) && tif->tif_rawdata) || \
TIFFWriteBufferSetup((tif), NULL, (tmsize_t) -1))
static int TIFFGrowStrips(TIFF* tif, uint32 delta, const char* module);
static int TIFFAppendToStrip(TIFF* tif, uint32 strip, uint8* data, tmsize_t cc);
int
TIFFWriteScanline(TIFF* tif, void* buf, uint32 row, uint16 sample)
{
static const char module[] = "TIFFWriteScanline";
register TIFFDirectory *td;
int status, imagegrew = 0;
uint32 strip;
if (!WRITECHECKSTRIPS(tif, module))
return (-1);
/*
* Handle delayed allocation of data buffer. This
* permits it to be sized more intelligently (using
* directory information).
*/
if (!BUFFERCHECK(tif))
return (-1);
tif->tif_flags |= TIFF_BUF4WRITE; /* not strictly sure this is right*/
td = &tif->tif_dir;
/*
* Extend image length if needed
* (but only for PlanarConfig=1).
*/
if (row >= td->td_imagelength) { /* extend image */
if (td->td_planarconfig == PLANARCONFIG_SEPARATE) {
TIFFErrorExt(tif->tif_clientdata, module,
"Can not change \"ImageLength\" when using separate planes");
return (-1);
}
td->td_imagelength = row+1;
imagegrew = 1;
}
/*
* Calculate strip and check for crossings.
*/
if (td->td_planarconfig == PLANARCONFIG_SEPARATE) {
if (sample >= td->td_samplesperpixel) {
TIFFErrorExt(tif->tif_clientdata, module,
"%lu: Sample out of range, max %lu",
(unsigned long) sample, (unsigned long) td->td_samplesperpixel);
return (-1);
}
strip = sample*td->td_stripsperimage + row/td->td_rowsperstrip;
} else
strip = row / td->td_rowsperstrip;
/*
* Check strip array to make sure there's space. We don't support
* dynamically growing files that have data organized in separate
* bitplanes because it's too painful. In that case we require that
* the imagelength be set properly before the first write (so that the
* strips array will be fully allocated above).
*/
if (strip >= td->td_nstrips && !TIFFGrowStrips(tif, 1, module))
return (-1);
if (strip != tif->tif_curstrip) {
/*
* Changing strips -- flush any data present.
*/
if (!TIFFFlushData(tif))
return (-1);
tif->tif_curstrip = strip;
/*
* Watch out for a growing image. The value of strips/image
* will initially be 1 (since it can't be deduced until the
* imagelength is known).
*/
if (strip >= td->td_stripsperimage && imagegrew)
td->td_stripsperimage =
TIFFhowmany_32(td->td_imagelength,td->td_rowsperstrip);
if (td->td_stripsperimage == 0) {
TIFFErrorExt(tif->tif_clientdata, module, "Zero strips per image");
return (-1);
}
tif->tif_row =
(strip % td->td_stripsperimage) * td->td_rowsperstrip;
if ((tif->tif_flags & TIFF_CODERSETUP) == 0) {
if (!(*tif->tif_setupencode)(tif))
return (-1);
tif->tif_flags |= TIFF_CODERSETUP;
}
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
if( td->td_stripbytecount[strip] > 0 )
{
/* if we are writing over existing tiles, zero length */
td->td_stripbytecount[strip] = 0;
/* this forces TIFFAppendToStrip() to do a seek */
tif->tif_curoff = 0;
}
if (!(*tif->tif_preencode)(tif, sample))
return (-1);
tif->tif_flags |= TIFF_POSTENCODE;
}
/*
* Ensure the write is either sequential or at the
* beginning of a strip (or that we can randomly
* access the data -- i.e. no encoding).
*/
if (row != tif->tif_row) {
if (row < tif->tif_row) {
/*
* Moving backwards within the same strip:
* backup to the start and then decode
* forward (below).
*/
tif->tif_row = (strip % td->td_stripsperimage) *
td->td_rowsperstrip;
tif->tif_rawcp = tif->tif_rawdata;
}
/*
* Seek forward to the desired row.
*/
if (!(*tif->tif_seek)(tif, row - tif->tif_row))
return (-1);
tif->tif_row = row;
}
/* swab if needed - note that source buffer will be altered */
tif->tif_postdecode( tif, (uint8*) buf, tif->tif_scanlinesize );
status = (*tif->tif_encoderow)(tif, (uint8*) buf,
tif->tif_scanlinesize, sample);
/* we are now poised at the beginning of the next row */
tif->tif_row = row + 1;
return (status);
}
/*
* Encode the supplied data and write it to the
* specified strip.
*
* NB: Image length must be setup before writing.
*/
tmsize_t
TIFFWriteEncodedStrip(TIFF* tif, uint32 strip, void* data, tmsize_t cc)
{
static const char module[] = "TIFFWriteEncodedStrip";
TIFFDirectory *td = &tif->tif_dir;
uint16 sample;
if (!WRITECHECKSTRIPS(tif, module))
return ((tmsize_t) -1);
/*
* Check strip array to make sure there's space.
* We don't support dynamically growing files that
* have data organized in separate bitplanes because
* it's too painful. In that case we require that
* the imagelength be set properly before the first
* write (so that the strips array will be fully
* allocated above).
*/
if (strip >= td->td_nstrips) {
if (td->td_planarconfig == PLANARCONFIG_SEPARATE) {
TIFFErrorExt(tif->tif_clientdata, module,
"Can not grow image by strips when using separate planes");
return ((tmsize_t) -1);
}
if (!TIFFGrowStrips(tif, 1, module))
return ((tmsize_t) -1);
td->td_stripsperimage =
TIFFhowmany_32(td->td_imagelength, td->td_rowsperstrip);
}
/*
* Handle delayed allocation of data buffer. This
* permits it to be sized according to the directory
* info.
*/
if (!BUFFERCHECK(tif))
return ((tmsize_t) -1);
tif->tif_flags |= TIFF_BUF4WRITE;
tif->tif_curstrip = strip;
if (td->td_stripsperimage == 0) {
TIFFErrorExt(tif->tif_clientdata, module, "Zero strips per image");
return ((tmsize_t) -1);
}
tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip;
if ((tif->tif_flags & TIFF_CODERSETUP) == 0) {
if (!(*tif->tif_setupencode)(tif))
return ((tmsize_t) -1);
tif->tif_flags |= TIFF_CODERSETUP;
}
if( td->td_stripbytecount[strip] > 0 )
{
/* Make sure that at the first attempt of rewriting the tile, we will have */
/* more bytes available in the output buffer than the previous byte count, */
/* so that TIFFAppendToStrip() will detect the overflow when it is called the first */
/* time if the new compressed tile is bigger than the older one. (GDAL #4771) */
if( tif->tif_rawdatasize <= (tmsize_t)td->td_stripbytecount[strip] )
{
if( !(TIFFWriteBufferSetup(tif, NULL,
(tmsize_t)TIFFroundup_64((uint64)(td->td_stripbytecount[strip] + 1), 1024))) )
return ((tmsize_t)(-1));
}
/* Force TIFFAppendToStrip() to consider placing data at end
of file. */
tif->tif_curoff = 0;
}
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
tif->tif_flags &= ~TIFF_POSTENCODE;
/* shortcut to avoid an extra memcpy() */
if( td->td_compression == COMPRESSION_NONE )
{
/* swab if needed - note that source buffer will be altered */
tif->tif_postdecode( tif, (uint8*) data, cc );
if (!isFillOrder(tif, td->td_fillorder) &&
(tif->tif_flags & TIFF_NOBITREV) == 0)
TIFFReverseBits((uint8*) data, cc);
if (cc > 0 &&
!TIFFAppendToStrip(tif, strip, (uint8*) data, cc))
return ((tmsize_t) -1);
return (cc);
}
sample = (uint16)(strip / td->td_stripsperimage);
if (!(*tif->tif_preencode)(tif, sample))
return ((tmsize_t) -1);
/* swab if needed - note that source buffer will be altered */
tif->tif_postdecode( tif, (uint8*) data, cc );
if (!(*tif->tif_encodestrip)(tif, (uint8*) data, cc, sample))
return ((tmsize_t) -1);
if (!(*tif->tif_postencode)(tif))
return ((tmsize_t) -1);
if (!isFillOrder(tif, td->td_fillorder) &&
(tif->tif_flags & TIFF_NOBITREV) == 0)
TIFFReverseBits(tif->tif_rawdata, tif->tif_rawcc);
if (tif->tif_rawcc > 0 &&
!TIFFAppendToStrip(tif, strip, tif->tif_rawdata, tif->tif_rawcc))
return ((tmsize_t) -1);
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
return (cc);
}
/*
* Write the supplied data to the specified strip.
*
* NB: Image length must be setup before writing.
*/
tmsize_t
TIFFWriteRawStrip(TIFF* tif, uint32 strip, void* data, tmsize_t cc)
{
static const char module[] = "TIFFWriteRawStrip";
TIFFDirectory *td = &tif->tif_dir;
if (!WRITECHECKSTRIPS(tif, module))
return ((tmsize_t) -1);
/*
* Check strip array to make sure there's space.
* We don't support dynamically growing files that
* have data organized in separate bitplanes because
* it's too painful. In that case we require that
* the imagelength be set properly before the first
* write (so that the strips array will be fully
* allocated above).
*/
if (strip >= td->td_nstrips) {
if (td->td_planarconfig == PLANARCONFIG_SEPARATE) {
TIFFErrorExt(tif->tif_clientdata, module,
"Can not grow image by strips when using separate planes");
return ((tmsize_t) -1);
}
/*
* Watch out for a growing image. The value of
* strips/image will initially be 1 (since it
* can't be deduced until the imagelength is known).
*/
if (strip >= td->td_stripsperimage)
td->td_stripsperimage =
TIFFhowmany_32(td->td_imagelength,td->td_rowsperstrip);
if (!TIFFGrowStrips(tif, 1, module))
return ((tmsize_t) -1);
}
tif->tif_curstrip = strip;
if (td->td_stripsperimage == 0) {
TIFFErrorExt(tif->tif_clientdata, module,"Zero strips per image");
return ((tmsize_t) -1);
}
tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip;
return (TIFFAppendToStrip(tif, strip, (uint8*) data, cc) ?
cc : (tmsize_t) -1);
}
/*
* Write and compress a tile of data. The
* tile is selected by the (x,y,z,s) coordinates.
*/
tmsize_t
TIFFWriteTile(TIFF* tif, void* buf, uint32 x, uint32 y, uint32 z, uint16 s)
{
if (!TIFFCheckTile(tif, x, y, z, s))
return ((tmsize_t)(-1));
/*
* NB: A tile size of -1 is used instead of tif_tilesize knowing
* that TIFFWriteEncodedTile will clamp this to the tile size.
* This is done because the tile size may not be defined until
* after the output buffer is setup in TIFFWriteBufferSetup.
*/
return (TIFFWriteEncodedTile(tif,
TIFFComputeTile(tif, x, y, z, s), buf, (tmsize_t)(-1)));
}
/*
* Encode the supplied data and write it to the
* specified tile. There must be space for the
* data. The function clamps individual writes
* to a tile to the tile size, but does not (and
* can not) check that multiple writes to the same
* tile do not write more than tile size data.
*
* NB: Image length must be setup before writing; this
* interface does not support automatically growing
* the image on each write (as TIFFWriteScanline does).
*/
tmsize_t
TIFFWriteEncodedTile(TIFF* tif, uint32 tile, void* data, tmsize_t cc)
{
static const char module[] = "TIFFWriteEncodedTile";
TIFFDirectory *td;
uint16 sample;
uint32 howmany32;
if (!WRITECHECKTILES(tif, module))
return ((tmsize_t)(-1));
td = &tif->tif_dir;
if (tile >= td->td_nstrips) {
TIFFErrorExt(tif->tif_clientdata, module, "Tile %lu out of range, max %lu",
(unsigned long) tile, (unsigned long) td->td_nstrips);
return ((tmsize_t)(-1));
}
/*
* Handle delayed allocation of data buffer. This
* permits it to be sized more intelligently (using
* directory information).
*/
if (!BUFFERCHECK(tif))
return ((tmsize_t)(-1));
tif->tif_flags |= TIFF_BUF4WRITE;
tif->tif_curtile = tile;
if( td->td_stripbytecount[tile] > 0 )
{
/* Make sure that at the first attempt of rewriting the tile, we will have */
/* more bytes available in the output buffer than the previous byte count, */
/* so that TIFFAppendToStrip() will detect the overflow when it is called the first */
/* time if the new compressed tile is bigger than the older one. (GDAL #4771) */
if( tif->tif_rawdatasize <= (tmsize_t) td->td_stripbytecount[tile] )
{
if( !(TIFFWriteBufferSetup(tif, NULL,
(tmsize_t)TIFFroundup_64((uint64)(td->td_stripbytecount[tile] + 1), 1024))) )
return ((tmsize_t)(-1));
}
/* Force TIFFAppendToStrip() to consider placing data at end
of file. */
tif->tif_curoff = 0;
}
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
/*
* Compute tiles per row & per column to compute
* current row and column
*/
howmany32=TIFFhowmany_32(td->td_imagelength, td->td_tilelength);
if (howmany32 == 0) {
TIFFErrorExt(tif->tif_clientdata,module,"Zero tiles");
return ((tmsize_t)(-1));
}
tif->tif_row = (tile % howmany32) * td->td_tilelength;
howmany32=TIFFhowmany_32(td->td_imagewidth, td->td_tilewidth);
if (howmany32 == 0) {
TIFFErrorExt(tif->tif_clientdata,module,"Zero tiles");
return ((tmsize_t)(-1));
}
tif->tif_col = (tile % howmany32) * td->td_tilewidth;
if ((tif->tif_flags & TIFF_CODERSETUP) == 0) {
if (!(*tif->tif_setupencode)(tif))
return ((tmsize_t)(-1));
tif->tif_flags |= TIFF_CODERSETUP;
}
tif->tif_flags &= ~TIFF_POSTENCODE;
/*
* Clamp write amount to the tile size. This is mostly
* done so that callers can pass in some large number
* (e.g. -1) and have the tile size used instead.
*/
if ( cc < 1 || cc > tif->tif_tilesize)
cc = tif->tif_tilesize;
/* shortcut to avoid an extra memcpy() */
if( td->td_compression == COMPRESSION_NONE )
{
/* swab if needed - note that source buffer will be altered */
tif->tif_postdecode( tif, (uint8*) data, cc );
if (!isFillOrder(tif, td->td_fillorder) &&
(tif->tif_flags & TIFF_NOBITREV) == 0)
TIFFReverseBits((uint8*) data, cc);
if (cc > 0 &&
!TIFFAppendToStrip(tif, tile, (uint8*) data, cc))
return ((tmsize_t) -1);
return (cc);
}
sample = (uint16)(tile/td->td_stripsperimage);
if (!(*tif->tif_preencode)(tif, sample))
return ((tmsize_t)(-1));
/* swab if needed - note that source buffer will be altered */
tif->tif_postdecode( tif, (uint8*) data, cc );
if (!(*tif->tif_encodetile)(tif, (uint8*) data, cc, sample))
return ((tmsize_t) -1);
if (!(*tif->tif_postencode)(tif))
return ((tmsize_t)(-1));
if (!isFillOrder(tif, td->td_fillorder) &&
(tif->tif_flags & TIFF_NOBITREV) == 0)
TIFFReverseBits((uint8*)tif->tif_rawdata, tif->tif_rawcc);
if (tif->tif_rawcc > 0 && !TIFFAppendToStrip(tif, tile,
tif->tif_rawdata, tif->tif_rawcc))
return ((tmsize_t)(-1));
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
return (cc);
}
/*
* Write the supplied data to the specified strip.
* There must be space for the data; we don't check
* if strips overlap!
*
* NB: Image length must be setup before writing; this
* interface does not support automatically growing
* the image on each write (as TIFFWriteScanline does).
*/
tmsize_t
TIFFWriteRawTile(TIFF* tif, uint32 tile, void* data, tmsize_t cc)
{
static const char module[] = "TIFFWriteRawTile";
if (!WRITECHECKTILES(tif, module))
return ((tmsize_t)(-1));
if (tile >= tif->tif_dir.td_nstrips) {
TIFFErrorExt(tif->tif_clientdata, module, "Tile %lu out of range, max %lu",
(unsigned long) tile,
(unsigned long) tif->tif_dir.td_nstrips);
return ((tmsize_t)(-1));
}
return (TIFFAppendToStrip(tif, tile, (uint8*) data, cc) ?
cc : (tmsize_t)(-1));
}
#define isUnspecified(tif, f) \
(TIFFFieldSet(tif,f) && (tif)->tif_dir.td_imagelength == 0)
int
TIFFSetupStrips(TIFF* tif)
{
TIFFDirectory* td = &tif->tif_dir;
if (isTiled(tif))
td->td_stripsperimage =
isUnspecified(tif, FIELD_TILEDIMENSIONS) ?
td->td_samplesperpixel : TIFFNumberOfTiles(tif);
else
td->td_stripsperimage =
isUnspecified(tif, FIELD_ROWSPERSTRIP) ?
td->td_samplesperpixel : TIFFNumberOfStrips(tif);
td->td_nstrips = td->td_stripsperimage;
if (td->td_planarconfig == PLANARCONFIG_SEPARATE)
td->td_stripsperimage /= td->td_samplesperpixel;
td->td_stripoffset = (uint64 *)
_TIFFmalloc(td->td_nstrips * sizeof (uint64));
td->td_stripbytecount = (uint64 *)
_TIFFmalloc(td->td_nstrips * sizeof (uint64));
if (td->td_stripoffset == NULL || td->td_stripbytecount == NULL)
return (0);
/*
* Place data at the end-of-file
* (by setting offsets to zero).
*/
_TIFFmemset(td->td_stripoffset, 0, td->td_nstrips*sizeof (uint64));
_TIFFmemset(td->td_stripbytecount, 0, td->td_nstrips*sizeof (uint64));
TIFFSetFieldBit(tif, FIELD_STRIPOFFSETS);
TIFFSetFieldBit(tif, FIELD_STRIPBYTECOUNTS);
return (1);
}
#undef isUnspecified
/*
* Verify file is writable and that the directory
* information is setup properly. In doing the latter
* we also "freeze" the state of the directory so
* that important information is not changed.
*/
int
TIFFWriteCheck(TIFF* tif, int tiles, const char* module)
{
if (tif->tif_mode == O_RDONLY) {
TIFFErrorExt(tif->tif_clientdata, module, "File not open for writing");
return (0);
}
if (tiles ^ isTiled(tif)) {
TIFFErrorExt(tif->tif_clientdata, module, tiles ?
"Can not write tiles to a stripped image" :
"Can not write scanlines to a tiled image");
return (0);
}
_TIFFFillStriles( tif );
/*
* On the first write verify all the required information
* has been setup and initialize any data structures that
* had to wait until directory information was set.
* Note that a lot of our work is assumed to remain valid
* because we disallow any of the important parameters
* from changing after we start writing (i.e. once
* TIFF_BEENWRITING is set, TIFFSetField will only allow
* the image's length to be changed).
*/
if (!TIFFFieldSet(tif, FIELD_IMAGEDIMENSIONS)) {
TIFFErrorExt(tif->tif_clientdata, module,
"Must set \"ImageWidth\" before writing data");
return (0);
}
if (tif->tif_dir.td_samplesperpixel == 1) {
/*
* Planarconfiguration is irrelevant in case of single band
* images and need not be included. We will set it anyway,
* because this field is used in other parts of library even
* in the single band case.
*/
if (!TIFFFieldSet(tif, FIELD_PLANARCONFIG))
tif->tif_dir.td_planarconfig = PLANARCONFIG_CONTIG;
} else {
if (!TIFFFieldSet(tif, FIELD_PLANARCONFIG)) {
TIFFErrorExt(tif->tif_clientdata, module,
"Must set \"PlanarConfiguration\" before writing data");
return (0);
}
}
if (tif->tif_dir.td_stripoffset == NULL && !TIFFSetupStrips(tif)) {
tif->tif_dir.td_nstrips = 0;
TIFFErrorExt(tif->tif_clientdata, module, "No space for %s arrays",
isTiled(tif) ? "tile" : "strip");
return (0);
}
if (isTiled(tif))
{
tif->tif_tilesize = TIFFTileSize(tif);
if (tif->tif_tilesize == 0)
return (0);
}
else
tif->tif_tilesize = (tmsize_t)(-1);
tif->tif_scanlinesize = TIFFScanlineSize(tif);
if (tif->tif_scanlinesize == 0)
return (0);
tif->tif_flags |= TIFF_BEENWRITING;
return (1);
}
/*
* Setup the raw data buffer used for encoding.
*/
int
TIFFWriteBufferSetup(TIFF* tif, void* bp, tmsize_t size)
{
static const char module[] = "TIFFWriteBufferSetup";
if (tif->tif_rawdata) {
if (tif->tif_flags & TIFF_MYBUFFER) {
_TIFFfree(tif->tif_rawdata);
tif->tif_flags &= ~TIFF_MYBUFFER;
}
tif->tif_rawdata = NULL;
}
if (size == (tmsize_t)(-1)) {
size = (isTiled(tif) ?
tif->tif_tilesize : TIFFStripSize(tif));
/*
* Make raw data buffer at least 8K
*/
if (size < 8*1024)
size = 8*1024;
bp = NULL; /* NB: force malloc */
}
if (bp == NULL) {
bp = _TIFFmalloc(size);
if (bp == NULL) {
TIFFErrorExt(tif->tif_clientdata, module, "No space for output buffer");
return (0);
}
tif->tif_flags |= TIFF_MYBUFFER;
} else
tif->tif_flags &= ~TIFF_MYBUFFER;
tif->tif_rawdata = (uint8*) bp;
tif->tif_rawdatasize = size;
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
tif->tif_flags |= TIFF_BUFFERSETUP;
return (1);
}
/*
* Grow the strip data structures by delta strips.
*/
static int
TIFFGrowStrips(TIFF* tif, uint32 delta, const char* module)
{
TIFFDirectory *td = &tif->tif_dir;
uint64* new_stripoffset;
uint64* new_stripbytecount;
assert(td->td_planarconfig == PLANARCONFIG_CONTIG);
new_stripoffset = (uint64*)_TIFFrealloc(td->td_stripoffset,
(td->td_nstrips + delta) * sizeof (uint64));
new_stripbytecount = (uint64*)_TIFFrealloc(td->td_stripbytecount,
(td->td_nstrips + delta) * sizeof (uint64));
if (new_stripoffset == NULL || new_stripbytecount == NULL) {
if (new_stripoffset)
_TIFFfree(new_stripoffset);
if (new_stripbytecount)
_TIFFfree(new_stripbytecount);
td->td_nstrips = 0;
TIFFErrorExt(tif->tif_clientdata, module, "No space to expand strip arrays");
return (0);
}
td->td_stripoffset = new_stripoffset;
td->td_stripbytecount = new_stripbytecount;
_TIFFmemset(td->td_stripoffset + td->td_nstrips,
0, delta*sizeof (uint64));
_TIFFmemset(td->td_stripbytecount + td->td_nstrips,
0, delta*sizeof (uint64));
td->td_nstrips += delta;
tif->tif_flags |= TIFF_DIRTYDIRECT;
return (1);
}
/*
* Append the data to the specified strip.
*/
static int
TIFFAppendToStrip(TIFF* tif, uint32 strip, uint8* data, tmsize_t cc)
{
static const char module[] = "TIFFAppendToStrip";
TIFFDirectory *td = &tif->tif_dir;
uint64 m;
int64 old_byte_count = -1;
if (td->td_stripoffset[strip] == 0 || tif->tif_curoff == 0) {
assert(td->td_nstrips > 0);
if( td->td_stripbytecount[strip] != 0
&& td->td_stripoffset[strip] != 0
&& td->td_stripbytecount[strip] >= (uint64) cc )
{
/*
* There is already tile data on disk, and the new tile
* data we have will fit in the same space. The only
* aspect of this that is risky is that there could be
* more data to append to this strip before we are done
* depending on how we are getting called.
*/
if (!SeekOK(tif, td->td_stripoffset[strip])) {
TIFFErrorExt(tif->tif_clientdata, module,
"Seek error at scanline %lu",
(unsigned long)tif->tif_row);
return (0);
}
}
else
{
/*
* Seek to end of file, and set that as our location to
* write this strip.
*/
td->td_stripoffset[strip] = TIFFSeekFile(tif, 0, SEEK_END);
tif->tif_flags |= TIFF_DIRTYSTRIP;
}
tif->tif_curoff = td->td_stripoffset[strip];
/*
* We are starting a fresh strip/tile, so set the size to zero.
*/
old_byte_count = td->td_stripbytecount[strip];
td->td_stripbytecount[strip] = 0;
}
m = tif->tif_curoff+cc;
if (!(tif->tif_flags&TIFF_BIGTIFF))
m = (uint32)m;
if ((m<tif->tif_curoff)||(m<(uint64)cc))
{
TIFFErrorExt(tif->tif_clientdata, module, "Maximum TIFF file size exceeded");
return (0);
}
if (!WriteOK(tif, data, cc)) {
TIFFErrorExt(tif->tif_clientdata, module, "Write error at scanline %lu",
(unsigned long) tif->tif_row);
return (0);
}
tif->tif_curoff = m;
td->td_stripbytecount[strip] += cc;
if( (int64) td->td_stripbytecount[strip] != old_byte_count )
tif->tif_flags |= TIFF_DIRTYSTRIP;
return (1);
}
/*
* Internal version of TIFFFlushData that can be
* called by ``encodestrip routines'' w/o concern
* for infinite recursion.
*/
int
TIFFFlushData1(TIFF* tif)
{
if (tif->tif_rawcc > 0 && tif->tif_flags & TIFF_BUF4WRITE ) {
if (!isFillOrder(tif, tif->tif_dir.td_fillorder) &&
(tif->tif_flags & TIFF_NOBITREV) == 0)
TIFFReverseBits((uint8*)tif->tif_rawdata,
tif->tif_rawcc);
if (!TIFFAppendToStrip(tif,
isTiled(tif) ? tif->tif_curtile : tif->tif_curstrip,
tif->tif_rawdata, tif->tif_rawcc))
{
/* We update those variables even in case of error since there's */
/* code that doesn't really check the return code of this */
/* function */
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
return (0);
}
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
}
return (1);
}
/*
* Set the current write offset. This should only be
* used to set the offset to a known previous location
* (very carefully), or to 0 so that the next write gets
* appended to the end of the file.
*/
void
TIFFSetWriteOffset(TIFF* tif, toff_t off)
{
tif->tif_curoff = off;
}
/* 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-787/c/good_5478_2 |
crossvul-cpp_data_good_4234_0 | /*
The code below is mostly derived from cx_bsdiff (written by Anthony
Tuininga, http://cx-bsdiff.sourceforge.net/). The cx_bsdiff code in
turn was derived from bsdiff, the standalone utility produced for BSD
which can be found at http://www.daemonology.net/bsdiff.
*/
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#if PY_MAJOR_VERSION >= 3
#define IS_PY3K
#endif
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
static void split(off_t *I, off_t *V, off_t start, off_t len, off_t h)
{
off_t i, j, k, x, tmp, jj, kk;
if (len < 16) {
for (k = start; k < start + len; k += j) {
j = 1;
x = V[I[k] + h];
for (i = 1; k + i < start + len; i++) {
if (V[I[k + i] + h] < x) {
x = V[I[k + i] + h];
j = 0;
}
if (V[I[k + i] + h] == x) {
tmp = I[k + j];
I[k + j] = I[k + i];
I[k + i] = tmp;
j++;
}
}
for (i = 0; i < j; i++)
V[I[k + i]] = k + j - 1;
if (j == 1)
I[k] = -1;
}
} else {
jj = 0;
kk = 0;
x = V[I[start + len / 2] + h];
for (i = start; i < start + len; i++) {
if (V[I[i] + h] < x)
jj++;
if (V[I[i] + h] == x)
kk++;
}
jj += start;
kk += jj;
j = 0;
k = 0;
i = start;
while (i < jj) {
if (V[I[i] + h] < x) {
i++;
} else if (V[I[i] + h] == x) {
tmp = I[i];
I[i] = I[jj + j];
I[jj + j] = tmp;
j++;
} else {
tmp = I[i];
I[i] = I[kk + k];
I[kk + k] = tmp;
k++;
}
}
while (jj + j < kk) {
if (V[I[jj + j] + h] == x) {
j++;
} else {
tmp = I[jj + j];
I[jj + j] = I[kk + k];
I[kk + k] = tmp;
k++;
}
}
if (jj > start)
split(I, V, start, jj - start, h);
for (i = 0; i < kk - jj; i++)
V[I[jj + i]] = kk - 1;
if (jj == kk - 1)
I[jj] = -1;
if (start + len > kk)
split(I, V, kk, start + len - kk, h);
}
}
static void qsufsort(off_t *I, off_t *V, unsigned char *old, off_t oldsize)
{
off_t buckets[256], i, h, len;
for (i = 0; i < 256; i++)
buckets[i] = 0;
for (i = 0; i < oldsize; i++)
buckets[old[i]]++;
for (i = 1; i < 256; i++)
buckets[i] += buckets[i - 1];
for (i = 255; i > 0; i--)
buckets[i] = buckets[i - 1];
buckets[0] = 0;
for (i = 0; i < oldsize; i++)
I[++buckets[old[i]]] = i;
I[0] = oldsize;
for (i = 0; i < oldsize; i++)
V[i] = buckets[old[i]];
V[oldsize] = 0;
for (i = 1; i < 256; i++)
if (buckets[i] == buckets[i - 1] + 1)
I[buckets[i]] = -1;
I[0] = -1;
for (h = 1; I[0] != -(oldsize + 1); h += h) {
len = 0;
for (i = 0; i < oldsize + 1;) {
if (I[i] < 0) {
len -= I[i];
i -= I[i];
} else {
if (len)
I[i - len] = -len;
len = V[I[i]] + 1 - i;
split(I, V, i, len, h);
i += len;
len=0;
}
}
if (len)
I[i - len] = -len;
}
for (i = 0; i < oldsize + 1; i++)
I[V[i]] = i;
}
static off_t matchlen(unsigned char *old, off_t oldsize,
unsigned char *new, off_t newsize)
{
off_t i;
for (i = 0; (i < oldsize) && (i < newsize); i++)
if (old[i] != new[i])
break;
return i;
}
static off_t search(off_t *I,
unsigned char *old, off_t oldsize,
unsigned char *new, off_t newsize,
off_t st, off_t en, off_t *pos)
{
off_t x, y;
if (en - st < 2) {
x = matchlen(old + I[st], oldsize - I[st], new, newsize);
y = matchlen(old + I[en], oldsize - I[en], new, newsize);
if (x > y) {
*pos = I[st];
return x;
} else {
*pos = I[en];
return y;
}
}
x = st + (en - st) / 2;
if (memcmp(old + I[x], new, MIN(oldsize - I[x], newsize)) < 0) {
return search(I, old, oldsize, new, newsize, x, en, pos);
} else {
return search(I, old, oldsize, new, newsize, st, x, pos);
}
}
/* performs a diff between the two data streams and returns a tuple
containing the control, diff and extra blocks that bsdiff produces
*/
static PyObject* diff(PyObject* self, PyObject* args)
{
off_t lastscan, lastpos, lastoffset, oldscore, scsc, overlap, Ss, lens;
off_t *I, *V, dblen, eblen, scan, pos, len, s, Sf, lenf, Sb, lenb, i;
PyObject *controlTuples, *tuple, *results, *temp;
Py_ssize_t origDataLength, newDataLength;
char *origData, *newData;
unsigned char *db, *eb;
if (!PyArg_ParseTuple(args, "s#s#",
&origData, &origDataLength,
&newData, &newDataLength))
return NULL;
/* create the control tuple */
controlTuples = PyList_New(0);
if (!controlTuples)
return NULL;
/* perform sort on original data */
I = PyMem_Malloc((origDataLength + 1) * sizeof(off_t));
if (!I) {
Py_DECREF(controlTuples);
return PyErr_NoMemory();
}
V = PyMem_Malloc((origDataLength + 1) * sizeof(off_t));
if (!V) {
Py_DECREF(controlTuples);
PyMem_Free(I);
return PyErr_NoMemory();
}
Py_BEGIN_ALLOW_THREADS /* release GIL */
qsufsort(I, V, (unsigned char *) origData, origDataLength);
Py_END_ALLOW_THREADS
PyMem_Free(V);
/* allocate memory for the diff and extra blocks */
db = PyMem_Malloc(newDataLength + 1);
if (!db) {
Py_DECREF(controlTuples);
PyMem_Free(I);
return PyErr_NoMemory();
}
eb = PyMem_Malloc(newDataLength + 1);
if (!eb) {
Py_DECREF(controlTuples);
PyMem_Free(I);
PyMem_Free(db);
return PyErr_NoMemory();
}
dblen = 0;
eblen = 0;
/* perform the diff */
len = 0;
scan = 0;
lastscan = 0;
lastpos = 0;
lastoffset = 0;
pos = 0;
while (scan < newDataLength) {
oldscore = 0;
Py_BEGIN_ALLOW_THREADS /* release GIL */
for (scsc = scan += len; scan < newDataLength; scan++) {
len = search(I, (unsigned char *) origData, origDataLength,
(unsigned char *) newData + scan,
newDataLength - scan, 0, origDataLength, &pos);
for (; scsc < scan + len; scsc++)
if ((scsc + lastoffset < origDataLength) &&
(origData[scsc + lastoffset] == newData[scsc]))
oldscore++;
if (((len == oldscore) && (len != 0)) || (len > oldscore + 8))
break;
if ((scan + lastoffset < origDataLength) &&
(origData[scan + lastoffset] == newData[scan]))
oldscore--;
}
Py_END_ALLOW_THREADS
if ((len != oldscore) || (scan == newDataLength)) {
s = 0;
Sf = 0;
lenf = 0;
for (i = 0; (lastscan + i < scan) &&
(lastpos + i < origDataLength);) {
if (origData[lastpos + i] == newData[lastscan + i])
s++;
i++;
if (s * 2 - i > Sf * 2 - lenf) {
Sf = s;
lenf = i;
}
}
lenb = 0;
if (scan < newDataLength) {
s = 0;
Sb = 0;
for (i = 1; (scan >= lastscan + i) && (pos >= i); i++) {
if (origData[pos - i] == newData[scan - i])
s++;
if (s * 2 - i > Sb * 2 - lenb) {
Sb = s;
lenb = i;
}
}
}
if (lastscan + lenf > scan - lenb) {
overlap = (lastscan + lenf) - (scan - lenb);
s = 0;
Ss = 0;
lens = 0;
for (i = 0; i < overlap; i++) {
if (newData[lastscan + lenf - overlap + i] ==
origData[lastpos + lenf - overlap + i])
s++;
if (newData[scan - lenb + i]== origData[pos - lenb + i])
s--;
if (s > Ss) {
Ss = s;
lens = i + 1;
}
}
lenf += lens - overlap;
lenb -= lens;
}
for (i = 0; i < lenf; i++)
db[dblen + i] = newData[lastscan + i] - origData[lastpos + i];
for (i = 0; i < (scan - lenb) - (lastscan + lenf); i++)
eb[eblen + i] = newData[lastscan + lenf + i];
dblen += lenf;
eblen += (scan - lenb) - (lastscan + lenf);
tuple = PyTuple_New(3);
if (!tuple) {
Py_DECREF(controlTuples);
PyMem_Free(I);
PyMem_Free(db);
PyMem_Free(eb);
return NULL;
}
PyTuple_SET_ITEM(tuple, 0, PyLong_FromLong(lenf));
PyTuple_SET_ITEM(tuple, 1,
PyLong_FromLong((scan - lenb) - (lastscan + lenf)));
PyTuple_SET_ITEM(tuple, 2,
PyLong_FromLong((pos - lenb) - (lastpos + lenf)));
if (PyList_Append(controlTuples, tuple) < 0) {
Py_DECREF(controlTuples);
Py_DECREF(tuple);
PyMem_Free(I);
PyMem_Free(db);
PyMem_Free(eb);
return NULL;
}
Py_DECREF(tuple);
lastscan = scan - lenb;
lastpos = pos - lenb;
lastoffset = pos - scan;
}
}
PyMem_Free(I);
results = PyTuple_New(3);
if (!results) {
PyMem_Free(db);
PyMem_Free(eb);
return NULL;
}
PyTuple_SET_ITEM(results, 0, controlTuples);
temp = PyBytes_FromStringAndSize((char *) db, dblen);
PyMem_Free(db);
if (!temp) {
PyMem_Free(eb);
Py_DECREF(results);
return NULL;
}
PyTuple_SET_ITEM(results, 1, temp);
temp = PyBytes_FromStringAndSize((char *) eb, eblen);
PyMem_Free(eb);
if (!temp) {
Py_DECREF(results);
return NULL;
}
PyTuple_SET_ITEM(results, 2, temp);
return results;
}
/* takes the original data and the control, diff and extra blocks produced
by bsdiff and returns the new data
*/
static PyObject* patch(PyObject* self, PyObject* args)
{
char *origData, *newData, *diffBlock, *extraBlock, *diffPtr, *extraPtr;
Py_ssize_t origDataLength, newDataLength, diffBlockLength, extraBlockLength;
PyObject *controlTuples, *tuple, *results;
off_t oldpos, newpos, x, y, z;
int i, j, numTuples;
if (!PyArg_ParseTuple(args, "s#nO!s#s#",
&origData, &origDataLength, &newDataLength,
&PyList_Type, &controlTuples,
&diffBlock, &diffBlockLength,
&extraBlock, &extraBlockLength))
return NULL;
/* allocate the memory for the new data */
newData = PyMem_Malloc(newDataLength + 1);
if (!newData)
return PyErr_NoMemory();
oldpos = 0;
newpos = 0;
diffPtr = diffBlock;
extraPtr = extraBlock;
numTuples = PyList_GET_SIZE(controlTuples);
for (i = 0; i < numTuples; i++) {
tuple = PyList_GET_ITEM(controlTuples, i);
if (!PyTuple_Check(tuple)) {
PyMem_Free(newData);
PyErr_SetString(PyExc_TypeError, "expecting tuple");
return NULL;
}
if (PyTuple_GET_SIZE(tuple) != 3) {
PyMem_Free(newData);
PyErr_SetString(PyExc_TypeError, "expecting tuple of size 3");
return NULL;
}
x = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 0));
y = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 1));
z = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 2));
if (newpos + x > newDataLength ||
diffPtr + x > diffBlock + diffBlockLength) {
PyMem_Free(newData);
PyErr_SetString(PyExc_ValueError, "corrupt patch (overflow)");
return NULL;
}
memcpy(newData + newpos, diffPtr, x);
diffPtr += x;
for (j = 0; j < x; j++)
if ((oldpos + j >= 0) && (oldpos + j < origDataLength))
newData[newpos + j] += origData[oldpos + j];
newpos += x;
oldpos += x;
if (newpos + y > newDataLength ||
extraPtr + y > extraBlock + extraBlockLength) {
PyMem_Free(newData);
PyErr_SetString(PyExc_ValueError, "corrupt patch (overflow)");
return NULL;
}
memcpy(newData + newpos, extraPtr, y);
extraPtr += y;
newpos += y;
oldpos += z;
}
/* confirm that a valid patch was applied */
if (newpos != newDataLength ||
diffPtr != diffBlock + diffBlockLength ||
extraPtr != extraBlock + extraBlockLength) {
PyMem_Free(newData);
PyErr_SetString(PyExc_ValueError, "corrupt patch (underflow)");
return NULL;
}
results = PyBytes_FromStringAndSize(newData, newDataLength);
PyMem_Free(newData);
return results;
}
/* encode an integer value as 8 bytes */
static PyObject *encode_int64(PyObject *self, PyObject *value)
{
long long x;
char bs[8], sign = 0x00;
int i;
if (!PyArg_Parse(value, "L", &x))
return NULL;
if (x < 0) {
x = -x;
sign = 0x80;
}
for (i = 0; i < 8; i++) {
bs[i] = x & 0xff;
x >>= 8; /* x /= 256 */
}
bs[7] |= sign;
return PyBytes_FromStringAndSize(bs, 8);
}
/* decode an off_t value from 8 bytes */
static PyObject *decode_int64(PyObject *self, PyObject *string)
{
long long x;
char *bs;
int i;
if (!PyBytes_Check(string)) {
PyErr_SetString(PyExc_TypeError, "bytes expected");
return NULL;
}
if (PyBytes_Size(string) != 8) {
PyErr_SetString(PyExc_ValueError, "8 bytes expected");
return NULL;
}
bs = PyBytes_AsString(string);
x = bs[7] & 0x7F;
for (i = 6; i >= 0; i--) {
x <<= 8; /* x = x * 256 + (unsigned char) bs[i]; */
x |= (unsigned char) bs[i];
}
if (bs[7] & 0x80)
x = -x;
return PyLong_FromLongLong(x);
}
/* declaration of methods supported by this module */
static PyMethodDef module_functions[] = {
{"diff", diff, METH_VARARGS},
{"patch", patch, METH_VARARGS},
{"encode_int64", encode_int64, METH_O},
{"decode_int64", decode_int64, METH_O},
{NULL, NULL, 0, NULL} /* Sentinel */
};
/* initialization routine for the shared libary */
#ifdef IS_PY3K
static PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT, "core", 0, -1, module_functions,
};
PyMODINIT_FUNC
PyInit_core(void)
{
PyObject *m;
m = PyModule_Create(&moduledef);
if (m == NULL)
return NULL;
return m;
}
#else
PyMODINIT_FUNC
initcore(void)
{
Py_InitModule("core", module_functions);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_4234_0 |
crossvul-cpp_data_good_4485_0 | /*
* OpenEXR (.exr) image decoder
* Copyright (c) 2006 Industrial Light & Magic, a division of Lucas Digital Ltd. LLC
* Copyright (c) 2009 Jimmy Christensen
*
* B44/B44A, Tile, UINT32 added by Jokyo Images support by CNC - French National Center for Cinema
*
* This file is part of FFmpeg.
*
* FFmpeg 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.
*
* FFmpeg 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 FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* OpenEXR decoder
* @author Jimmy Christensen
*
* For more information on the OpenEXR format, visit:
* http://openexr.com/
*
* exr_half2float() is credited to Aaftab Munshi, Dan Ginsburg, Dave Shreiner.
*/
#include <float.h>
#include <zlib.h>
#include "libavutil/avassert.h"
#include "libavutil/common.h"
#include "libavutil/imgutils.h"
#include "libavutil/intfloat.h"
#include "libavutil/avstring.h"
#include "libavutil/opt.h"
#include "libavutil/color_utils.h"
#include "avcodec.h"
#include "bytestream.h"
#if HAVE_BIGENDIAN
#include "bswapdsp.h"
#endif
#include "exrdsp.h"
#include "get_bits.h"
#include "internal.h"
#include "mathops.h"
#include "thread.h"
enum ExrCompr {
EXR_RAW,
EXR_RLE,
EXR_ZIP1,
EXR_ZIP16,
EXR_PIZ,
EXR_PXR24,
EXR_B44,
EXR_B44A,
EXR_DWA,
EXR_DWB,
EXR_UNKN,
};
enum ExrPixelType {
EXR_UINT,
EXR_HALF,
EXR_FLOAT,
EXR_UNKNOWN,
};
enum ExrTileLevelMode {
EXR_TILE_LEVEL_ONE,
EXR_TILE_LEVEL_MIPMAP,
EXR_TILE_LEVEL_RIPMAP,
EXR_TILE_LEVEL_UNKNOWN,
};
enum ExrTileLevelRound {
EXR_TILE_ROUND_UP,
EXR_TILE_ROUND_DOWN,
EXR_TILE_ROUND_UNKNOWN,
};
typedef struct EXRChannel {
int xsub, ysub;
enum ExrPixelType pixel_type;
} EXRChannel;
typedef struct EXRTileAttribute {
int32_t xSize;
int32_t ySize;
enum ExrTileLevelMode level_mode;
enum ExrTileLevelRound level_round;
} EXRTileAttribute;
typedef struct EXRThreadData {
uint8_t *uncompressed_data;
int uncompressed_size;
uint8_t *tmp;
int tmp_size;
uint8_t *bitmap;
uint16_t *lut;
int ysize, xsize;
int channel_line_size;
} EXRThreadData;
typedef struct EXRContext {
AVClass *class;
AVFrame *picture;
AVCodecContext *avctx;
ExrDSPContext dsp;
#if HAVE_BIGENDIAN
BswapDSPContext bbdsp;
#endif
enum ExrCompr compression;
enum ExrPixelType pixel_type;
int channel_offsets[4]; // 0 = red, 1 = green, 2 = blue and 3 = alpha
const AVPixFmtDescriptor *desc;
int w, h;
int32_t xmax, xmin;
int32_t ymax, ymin;
uint32_t xdelta, ydelta;
int scan_lines_per_block;
EXRTileAttribute tile_attr; /* header data attribute of tile */
int is_tile; /* 0 if scanline, 1 if tile */
int is_luma;/* 1 if there is an Y plane */
GetByteContext gb;
const uint8_t *buf;
int buf_size;
EXRChannel *channels;
int nb_channels;
int current_channel_offset;
EXRThreadData *thread_data;
const char *layer;
enum AVColorTransferCharacteristic apply_trc_type;
float gamma;
union av_intfloat32 gamma_table[65536];
} EXRContext;
/* -15 stored using a single precision bias of 127 */
#define HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP 0x38000000
/* max exponent value in single precision that will be converted
* to Inf or Nan when stored as a half-float */
#define HALF_FLOAT_MAX_BIASED_EXP_AS_SINGLE_FP_EXP 0x47800000
/* 255 is the max exponent biased value */
#define FLOAT_MAX_BIASED_EXP (0xFF << 23)
#define HALF_FLOAT_MAX_BIASED_EXP (0x1F << 10)
/**
* Convert a half float as a uint16_t into a full float.
*
* @param hf half float as uint16_t
*
* @return float value
*/
static union av_intfloat32 exr_half2float(uint16_t hf)
{
unsigned int sign = (unsigned int) (hf >> 15);
unsigned int mantissa = (unsigned int) (hf & ((1 << 10) - 1));
unsigned int exp = (unsigned int) (hf & HALF_FLOAT_MAX_BIASED_EXP);
union av_intfloat32 f;
if (exp == HALF_FLOAT_MAX_BIASED_EXP) {
// we have a half-float NaN or Inf
// half-float NaNs will be converted to a single precision NaN
// half-float Infs will be converted to a single precision Inf
exp = FLOAT_MAX_BIASED_EXP;
if (mantissa)
mantissa = (1 << 23) - 1; // set all bits to indicate a NaN
} else if (exp == 0x0) {
// convert half-float zero/denorm to single precision value
if (mantissa) {
mantissa <<= 1;
exp = HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP;
// check for leading 1 in denorm mantissa
while (!(mantissa & (1 << 10))) {
// for every leading 0, decrement single precision exponent by 1
// and shift half-float mantissa value to the left
mantissa <<= 1;
exp -= (1 << 23);
}
// clamp the mantissa to 10 bits
mantissa &= ((1 << 10) - 1);
// shift left to generate single-precision mantissa of 23 bits
mantissa <<= 13;
}
} else {
// shift left to generate single-precision mantissa of 23 bits
mantissa <<= 13;
// generate single precision biased exponent value
exp = (exp << 13) + HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP;
}
f.i = (sign << 31) | exp | mantissa;
return f;
}
static int zip_uncompress(EXRContext *s, const uint8_t *src, int compressed_size,
int uncompressed_size, EXRThreadData *td)
{
unsigned long dest_len = uncompressed_size;
if (uncompress(td->tmp, &dest_len, src, compressed_size) != Z_OK ||
dest_len != uncompressed_size)
return AVERROR_INVALIDDATA;
av_assert1(uncompressed_size % 2 == 0);
s->dsp.predictor(td->tmp, uncompressed_size);
s->dsp.reorder_pixels(td->uncompressed_data, td->tmp, uncompressed_size);
return 0;
}
static int rle_uncompress(EXRContext *ctx, const uint8_t *src, int compressed_size,
int uncompressed_size, EXRThreadData *td)
{
uint8_t *d = td->tmp;
const int8_t *s = src;
int ssize = compressed_size;
int dsize = uncompressed_size;
uint8_t *dend = d + dsize;
int count;
while (ssize > 0) {
count = *s++;
if (count < 0) {
count = -count;
if ((dsize -= count) < 0 ||
(ssize -= count + 1) < 0)
return AVERROR_INVALIDDATA;
while (count--)
*d++ = *s++;
} else {
count++;
if ((dsize -= count) < 0 ||
(ssize -= 2) < 0)
return AVERROR_INVALIDDATA;
while (count--)
*d++ = *s;
s++;
}
}
if (dend != d)
return AVERROR_INVALIDDATA;
av_assert1(uncompressed_size % 2 == 0);
ctx->dsp.predictor(td->tmp, uncompressed_size);
ctx->dsp.reorder_pixels(td->uncompressed_data, td->tmp, uncompressed_size);
return 0;
}
#define USHORT_RANGE (1 << 16)
#define BITMAP_SIZE (1 << 13)
static uint16_t reverse_lut(const uint8_t *bitmap, uint16_t *lut)
{
int i, k = 0;
for (i = 0; i < USHORT_RANGE; i++)
if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7))))
lut[k++] = i;
i = k - 1;
memset(lut + k, 0, (USHORT_RANGE - k) * 2);
return i;
}
static void apply_lut(const uint16_t *lut, uint16_t *dst, int dsize)
{
int i;
for (i = 0; i < dsize; ++i)
dst[i] = lut[dst[i]];
}
#define HUF_ENCBITS 16 // literal (value) bit length
#define HUF_DECBITS 14 // decoding bit size (>= 8)
#define HUF_ENCSIZE ((1 << HUF_ENCBITS) + 1) // encoding table size
#define HUF_DECSIZE (1 << HUF_DECBITS) // decoding table size
#define HUF_DECMASK (HUF_DECSIZE - 1)
typedef struct HufDec {
int len;
int lit;
int *p;
} HufDec;
static void huf_canonical_code_table(uint64_t *hcode)
{
uint64_t c, n[59] = { 0 };
int i;
for (i = 0; i < HUF_ENCSIZE; ++i)
n[hcode[i]] += 1;
c = 0;
for (i = 58; i > 0; --i) {
uint64_t nc = ((c + n[i]) >> 1);
n[i] = c;
c = nc;
}
for (i = 0; i < HUF_ENCSIZE; ++i) {
int l = hcode[i];
if (l > 0)
hcode[i] = l | (n[l]++ << 6);
}
}
#define SHORT_ZEROCODE_RUN 59
#define LONG_ZEROCODE_RUN 63
#define SHORTEST_LONG_RUN (2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN)
#define LONGEST_LONG_RUN (255 + SHORTEST_LONG_RUN)
static int huf_unpack_enc_table(GetByteContext *gb,
int32_t im, int32_t iM, uint64_t *hcode)
{
GetBitContext gbit;
int ret = init_get_bits8(&gbit, gb->buffer, bytestream2_get_bytes_left(gb));
if (ret < 0)
return ret;
for (; im <= iM; im++) {
uint64_t l = hcode[im] = get_bits(&gbit, 6);
if (l == LONG_ZEROCODE_RUN) {
int zerun = get_bits(&gbit, 8) + SHORTEST_LONG_RUN;
if (im + zerun > iM + 1)
return AVERROR_INVALIDDATA;
while (zerun--)
hcode[im++] = 0;
im--;
} else if (l >= SHORT_ZEROCODE_RUN) {
int zerun = l - SHORT_ZEROCODE_RUN + 2;
if (im + zerun > iM + 1)
return AVERROR_INVALIDDATA;
while (zerun--)
hcode[im++] = 0;
im--;
}
}
bytestream2_skip(gb, (get_bits_count(&gbit) + 7) / 8);
huf_canonical_code_table(hcode);
return 0;
}
static int huf_build_dec_table(const uint64_t *hcode, int im,
int iM, HufDec *hdecod)
{
for (; im <= iM; im++) {
uint64_t c = hcode[im] >> 6;
int i, l = hcode[im] & 63;
if (c >> l)
return AVERROR_INVALIDDATA;
if (l > HUF_DECBITS) {
HufDec *pl = hdecod + (c >> (l - HUF_DECBITS));
if (pl->len)
return AVERROR_INVALIDDATA;
pl->lit++;
pl->p = av_realloc(pl->p, pl->lit * sizeof(int));
if (!pl->p)
return AVERROR(ENOMEM);
pl->p[pl->lit - 1] = im;
} else if (l) {
HufDec *pl = hdecod + (c << (HUF_DECBITS - l));
for (i = 1 << (HUF_DECBITS - l); i > 0; i--, pl++) {
if (pl->len || pl->p)
return AVERROR_INVALIDDATA;
pl->len = l;
pl->lit = im;
}
}
}
return 0;
}
#define get_char(c, lc, gb) \
{ \
c = (c << 8) | bytestream2_get_byte(gb); \
lc += 8; \
}
#define get_code(po, rlc, c, lc, gb, out, oe, outb) \
{ \
if (po == rlc) { \
if (lc < 8) \
get_char(c, lc, gb); \
lc -= 8; \
\
cs = c >> lc; \
\
if (out + cs > oe || out == outb) \
return AVERROR_INVALIDDATA; \
\
s = out[-1]; \
\
while (cs-- > 0) \
*out++ = s; \
} else if (out < oe) { \
*out++ = po; \
} else { \
return AVERROR_INVALIDDATA; \
} \
}
static int huf_decode(const uint64_t *hcode, const HufDec *hdecod,
GetByteContext *gb, int nbits,
int rlc, int no, uint16_t *out)
{
uint64_t c = 0;
uint16_t *outb = out;
uint16_t *oe = out + no;
const uint8_t *ie = gb->buffer + (nbits + 7) / 8; // input byte size
uint8_t cs;
uint16_t s;
int i, lc = 0;
while (gb->buffer < ie) {
get_char(c, lc, gb);
while (lc >= HUF_DECBITS) {
const HufDec pl = hdecod[(c >> (lc - HUF_DECBITS)) & HUF_DECMASK];
if (pl.len) {
lc -= pl.len;
get_code(pl.lit, rlc, c, lc, gb, out, oe, outb);
} else {
int j;
if (!pl.p)
return AVERROR_INVALIDDATA;
for (j = 0; j < pl.lit; j++) {
int l = hcode[pl.p[j]] & 63;
while (lc < l && bytestream2_get_bytes_left(gb) > 0)
get_char(c, lc, gb);
if (lc >= l) {
if ((hcode[pl.p[j]] >> 6) ==
((c >> (lc - l)) & ((1LL << l) - 1))) {
lc -= l;
get_code(pl.p[j], rlc, c, lc, gb, out, oe, outb);
break;
}
}
}
if (j == pl.lit)
return AVERROR_INVALIDDATA;
}
}
}
i = (8 - nbits) & 7;
c >>= i;
lc -= i;
while (lc > 0) {
const HufDec pl = hdecod[(c << (HUF_DECBITS - lc)) & HUF_DECMASK];
if (pl.len && lc >= pl.len) {
lc -= pl.len;
get_code(pl.lit, rlc, c, lc, gb, out, oe, outb);
} else {
return AVERROR_INVALIDDATA;
}
}
if (out - outb != no)
return AVERROR_INVALIDDATA;
return 0;
}
static int huf_uncompress(GetByteContext *gb,
uint16_t *dst, int dst_size)
{
int32_t src_size, im, iM;
uint32_t nBits;
uint64_t *freq;
HufDec *hdec;
int ret, i;
src_size = bytestream2_get_le32(gb);
im = bytestream2_get_le32(gb);
iM = bytestream2_get_le32(gb);
bytestream2_skip(gb, 4);
nBits = bytestream2_get_le32(gb);
if (im < 0 || im >= HUF_ENCSIZE ||
iM < 0 || iM >= HUF_ENCSIZE ||
src_size < 0)
return AVERROR_INVALIDDATA;
bytestream2_skip(gb, 4);
freq = av_mallocz_array(HUF_ENCSIZE, sizeof(*freq));
hdec = av_mallocz_array(HUF_DECSIZE, sizeof(*hdec));
if (!freq || !hdec) {
ret = AVERROR(ENOMEM);
goto fail;
}
if ((ret = huf_unpack_enc_table(gb, im, iM, freq)) < 0)
goto fail;
if (nBits > 8 * bytestream2_get_bytes_left(gb)) {
ret = AVERROR_INVALIDDATA;
goto fail;
}
if ((ret = huf_build_dec_table(freq, im, iM, hdec)) < 0)
goto fail;
ret = huf_decode(freq, hdec, gb, nBits, iM, dst_size, dst);
fail:
for (i = 0; i < HUF_DECSIZE; i++)
if (hdec)
av_freep(&hdec[i].p);
av_free(freq);
av_free(hdec);
return ret;
}
static inline void wdec14(uint16_t l, uint16_t h, uint16_t *a, uint16_t *b)
{
int16_t ls = l;
int16_t hs = h;
int hi = hs;
int ai = ls + (hi & 1) + (hi >> 1);
int16_t as = ai;
int16_t bs = ai - hi;
*a = as;
*b = bs;
}
#define NBITS 16
#define A_OFFSET (1 << (NBITS - 1))
#define MOD_MASK ((1 << NBITS) - 1)
static inline void wdec16(uint16_t l, uint16_t h, uint16_t *a, uint16_t *b)
{
int m = l;
int d = h;
int bb = (m - (d >> 1)) & MOD_MASK;
int aa = (d + bb - A_OFFSET) & MOD_MASK;
*b = bb;
*a = aa;
}
static void wav_decode(uint16_t *in, int nx, int ox,
int ny, int oy, uint16_t mx)
{
int w14 = (mx < (1 << 14));
int n = (nx > ny) ? ny : nx;
int p = 1;
int p2;
while (p <= n)
p <<= 1;
p >>= 1;
p2 = p;
p >>= 1;
while (p >= 1) {
uint16_t *py = in;
uint16_t *ey = in + oy * (ny - p2);
uint16_t i00, i01, i10, i11;
int oy1 = oy * p;
int oy2 = oy * p2;
int ox1 = ox * p;
int ox2 = ox * p2;
for (; py <= ey; py += oy2) {
uint16_t *px = py;
uint16_t *ex = py + ox * (nx - p2);
for (; px <= ex; px += ox2) {
uint16_t *p01 = px + ox1;
uint16_t *p10 = px + oy1;
uint16_t *p11 = p10 + ox1;
if (w14) {
wdec14(*px, *p10, &i00, &i10);
wdec14(*p01, *p11, &i01, &i11);
wdec14(i00, i01, px, p01);
wdec14(i10, i11, p10, p11);
} else {
wdec16(*px, *p10, &i00, &i10);
wdec16(*p01, *p11, &i01, &i11);
wdec16(i00, i01, px, p01);
wdec16(i10, i11, p10, p11);
}
}
if (nx & p) {
uint16_t *p10 = px + oy1;
if (w14)
wdec14(*px, *p10, &i00, p10);
else
wdec16(*px, *p10, &i00, p10);
*px = i00;
}
}
if (ny & p) {
uint16_t *px = py;
uint16_t *ex = py + ox * (nx - p2);
for (; px <= ex; px += ox2) {
uint16_t *p01 = px + ox1;
if (w14)
wdec14(*px, *p01, &i00, p01);
else
wdec16(*px, *p01, &i00, p01);
*px = i00;
}
}
p2 = p;
p >>= 1;
}
}
static int piz_uncompress(EXRContext *s, const uint8_t *src, int ssize,
int dsize, EXRThreadData *td)
{
GetByteContext gb;
uint16_t maxval, min_non_zero, max_non_zero;
uint16_t *ptr;
uint16_t *tmp = (uint16_t *)td->tmp;
uint16_t *out;
uint16_t *in;
int ret, i, j;
int pixel_half_size;/* 1 for half, 2 for float and uint32 */
EXRChannel *channel;
int tmp_offset;
if (!td->bitmap)
td->bitmap = av_malloc(BITMAP_SIZE);
if (!td->lut)
td->lut = av_malloc(1 << 17);
if (!td->bitmap || !td->lut) {
av_freep(&td->bitmap);
av_freep(&td->lut);
return AVERROR(ENOMEM);
}
bytestream2_init(&gb, src, ssize);
min_non_zero = bytestream2_get_le16(&gb);
max_non_zero = bytestream2_get_le16(&gb);
if (max_non_zero >= BITMAP_SIZE)
return AVERROR_INVALIDDATA;
memset(td->bitmap, 0, FFMIN(min_non_zero, BITMAP_SIZE));
if (min_non_zero <= max_non_zero)
bytestream2_get_buffer(&gb, td->bitmap + min_non_zero,
max_non_zero - min_non_zero + 1);
memset(td->bitmap + max_non_zero + 1, 0, BITMAP_SIZE - max_non_zero - 1);
maxval = reverse_lut(td->bitmap, td->lut);
ret = huf_uncompress(&gb, tmp, dsize / sizeof(uint16_t));
if (ret)
return ret;
ptr = tmp;
for (i = 0; i < s->nb_channels; i++) {
channel = &s->channels[i];
if (channel->pixel_type == EXR_HALF)
pixel_half_size = 1;
else
pixel_half_size = 2;
for (j = 0; j < pixel_half_size; j++)
wav_decode(ptr + j, td->xsize, pixel_half_size, td->ysize,
td->xsize * pixel_half_size, maxval);
ptr += td->xsize * td->ysize * pixel_half_size;
}
apply_lut(td->lut, tmp, dsize / sizeof(uint16_t));
out = (uint16_t *)td->uncompressed_data;
for (i = 0; i < td->ysize; i++) {
tmp_offset = 0;
for (j = 0; j < s->nb_channels; j++) {
channel = &s->channels[j];
if (channel->pixel_type == EXR_HALF)
pixel_half_size = 1;
else
pixel_half_size = 2;
in = tmp + tmp_offset * td->xsize * td->ysize + i * td->xsize * pixel_half_size;
tmp_offset += pixel_half_size;
#if HAVE_BIGENDIAN
s->bbdsp.bswap16_buf(out, in, td->xsize * pixel_half_size);
#else
memcpy(out, in, td->xsize * 2 * pixel_half_size);
#endif
out += td->xsize * pixel_half_size;
}
}
return 0;
}
static int pxr24_uncompress(EXRContext *s, const uint8_t *src,
int compressed_size, int uncompressed_size,
EXRThreadData *td)
{
unsigned long dest_len, expected_len = 0;
const uint8_t *in = td->tmp;
uint8_t *out;
int c, i, j;
for (i = 0; i < s->nb_channels; i++) {
if (s->channels[i].pixel_type == EXR_FLOAT) {
expected_len += (td->xsize * td->ysize * 3);/* PRX 24 store float in 24 bit instead of 32 */
} else if (s->channels[i].pixel_type == EXR_HALF) {
expected_len += (td->xsize * td->ysize * 2);
} else {//UINT 32
expected_len += (td->xsize * td->ysize * 4);
}
}
dest_len = expected_len;
if (uncompress(td->tmp, &dest_len, src, compressed_size) != Z_OK) {
return AVERROR_INVALIDDATA;
} else if (dest_len != expected_len) {
return AVERROR_INVALIDDATA;
}
out = td->uncompressed_data;
for (i = 0; i < td->ysize; i++)
for (c = 0; c < s->nb_channels; c++) {
EXRChannel *channel = &s->channels[c];
const uint8_t *ptr[4];
uint32_t pixel = 0;
switch (channel->pixel_type) {
case EXR_FLOAT:
ptr[0] = in;
ptr[1] = ptr[0] + td->xsize;
ptr[2] = ptr[1] + td->xsize;
in = ptr[2] + td->xsize;
for (j = 0; j < td->xsize; ++j) {
uint32_t diff = ((unsigned)*(ptr[0]++) << 24) |
(*(ptr[1]++) << 16) |
(*(ptr[2]++) << 8);
pixel += diff;
bytestream_put_le32(&out, pixel);
}
break;
case EXR_HALF:
ptr[0] = in;
ptr[1] = ptr[0] + td->xsize;
in = ptr[1] + td->xsize;
for (j = 0; j < td->xsize; j++) {
uint32_t diff = (*(ptr[0]++) << 8) | *(ptr[1]++);
pixel += diff;
bytestream_put_le16(&out, pixel);
}
break;
case EXR_UINT:
ptr[0] = in;
ptr[1] = ptr[0] + s->xdelta;
ptr[2] = ptr[1] + s->xdelta;
ptr[3] = ptr[2] + s->xdelta;
in = ptr[3] + s->xdelta;
for (j = 0; j < s->xdelta; ++j) {
uint32_t diff = ((uint32_t)*(ptr[0]++) << 24) |
(*(ptr[1]++) << 16) |
(*(ptr[2]++) << 8 ) |
(*(ptr[3]++));
pixel += diff;
bytestream_put_le32(&out, pixel);
}
break;
default:
return AVERROR_INVALIDDATA;
}
}
return 0;
}
static void unpack_14(const uint8_t b[14], uint16_t s[16])
{
unsigned short shift = (b[ 2] >> 2) & 15;
unsigned short bias = (0x20 << shift);
int i;
s[ 0] = (b[0] << 8) | b[1];
s[ 4] = s[ 0] + ((((b[ 2] << 4) | (b[ 3] >> 4)) & 0x3f) << shift) - bias;
s[ 8] = s[ 4] + ((((b[ 3] << 2) | (b[ 4] >> 6)) & 0x3f) << shift) - bias;
s[12] = s[ 8] + ((b[ 4] & 0x3f) << shift) - bias;
s[ 1] = s[ 0] + ((b[ 5] >> 2) << shift) - bias;
s[ 5] = s[ 4] + ((((b[ 5] << 4) | (b[ 6] >> 4)) & 0x3f) << shift) - bias;
s[ 9] = s[ 8] + ((((b[ 6] << 2) | (b[ 7] >> 6)) & 0x3f) << shift) - bias;
s[13] = s[12] + ((b[ 7] & 0x3f) << shift) - bias;
s[ 2] = s[ 1] + ((b[ 8] >> 2) << shift) - bias;
s[ 6] = s[ 5] + ((((b[ 8] << 4) | (b[ 9] >> 4)) & 0x3f) << shift) - bias;
s[10] = s[ 9] + ((((b[ 9] << 2) | (b[10] >> 6)) & 0x3f) << shift) - bias;
s[14] = s[13] + ((b[10] & 0x3f) << shift) - bias;
s[ 3] = s[ 2] + ((b[11] >> 2) << shift) - bias;
s[ 7] = s[ 6] + ((((b[11] << 4) | (b[12] >> 4)) & 0x3f) << shift) - bias;
s[11] = s[10] + ((((b[12] << 2) | (b[13] >> 6)) & 0x3f) << shift) - bias;
s[15] = s[14] + ((b[13] & 0x3f) << shift) - bias;
for (i = 0; i < 16; ++i) {
if (s[i] & 0x8000)
s[i] &= 0x7fff;
else
s[i] = ~s[i];
}
}
static void unpack_3(const uint8_t b[3], uint16_t s[16])
{
int i;
s[0] = (b[0] << 8) | b[1];
if (s[0] & 0x8000)
s[0] &= 0x7fff;
else
s[0] = ~s[0];
for (i = 1; i < 16; i++)
s[i] = s[0];
}
static int b44_uncompress(EXRContext *s, const uint8_t *src, int compressed_size,
int uncompressed_size, EXRThreadData *td) {
const int8_t *sr = src;
int stay_to_uncompress = compressed_size;
int nb_b44_block_w, nb_b44_block_h;
int index_tl_x, index_tl_y, index_out, index_tmp;
uint16_t tmp_buffer[16]; /* B44 use 4x4 half float pixel */
int c, iY, iX, y, x;
int target_channel_offset = 0;
/* calc B44 block count */
nb_b44_block_w = td->xsize / 4;
if ((td->xsize % 4) != 0)
nb_b44_block_w++;
nb_b44_block_h = td->ysize / 4;
if ((td->ysize % 4) != 0)
nb_b44_block_h++;
for (c = 0; c < s->nb_channels; c++) {
if (s->channels[c].pixel_type == EXR_HALF) {/* B44 only compress half float data */
for (iY = 0; iY < nb_b44_block_h; iY++) {
for (iX = 0; iX < nb_b44_block_w; iX++) {/* For each B44 block */
if (stay_to_uncompress < 3) {
av_log(s, AV_LOG_ERROR, "Not enough data for B44A block: %d", stay_to_uncompress);
return AVERROR_INVALIDDATA;
}
if (src[compressed_size - stay_to_uncompress + 2] == 0xfc) { /* B44A block */
unpack_3(sr, tmp_buffer);
sr += 3;
stay_to_uncompress -= 3;
} else {/* B44 Block */
if (stay_to_uncompress < 14) {
av_log(s, AV_LOG_ERROR, "Not enough data for B44 block: %d", stay_to_uncompress);
return AVERROR_INVALIDDATA;
}
unpack_14(sr, tmp_buffer);
sr += 14;
stay_to_uncompress -= 14;
}
/* copy data to uncompress buffer (B44 block can exceed target resolution)*/
index_tl_x = iX * 4;
index_tl_y = iY * 4;
for (y = index_tl_y; y < FFMIN(index_tl_y + 4, td->ysize); y++) {
for (x = index_tl_x; x < FFMIN(index_tl_x + 4, td->xsize); x++) {
index_out = target_channel_offset * td->xsize + y * td->channel_line_size + 2 * x;
index_tmp = (y-index_tl_y) * 4 + (x-index_tl_x);
td->uncompressed_data[index_out] = tmp_buffer[index_tmp] & 0xff;
td->uncompressed_data[index_out + 1] = tmp_buffer[index_tmp] >> 8;
}
}
}
}
target_channel_offset += 2;
} else {/* Float or UINT 32 channel */
if (stay_to_uncompress < td->ysize * td->xsize * 4) {
av_log(s, AV_LOG_ERROR, "Not enough data for uncompress channel: %d", stay_to_uncompress);
return AVERROR_INVALIDDATA;
}
for (y = 0; y < td->ysize; y++) {
index_out = target_channel_offset * td->xsize + y * td->channel_line_size;
memcpy(&td->uncompressed_data[index_out], sr, td->xsize * 4);
sr += td->xsize * 4;
}
target_channel_offset += 4;
stay_to_uncompress -= td->ysize * td->xsize * 4;
}
}
return 0;
}
static int decode_block(AVCodecContext *avctx, void *tdata,
int jobnr, int threadnr)
{
EXRContext *s = avctx->priv_data;
AVFrame *const p = s->picture;
EXRThreadData *td = &s->thread_data[threadnr];
const uint8_t *channel_buffer[4] = { 0 };
const uint8_t *buf = s->buf;
uint64_t line_offset, uncompressed_size;
uint8_t *ptr;
uint32_t data_size;
int line, col = 0;
uint64_t tile_x, tile_y, tile_level_x, tile_level_y;
const uint8_t *src;
int step = s->desc->flags & AV_PIX_FMT_FLAG_FLOAT ? 4 : 2 * s->desc->nb_components;
int bxmin = 0, axmax = 0, window_xoffset = 0;
int window_xmin, window_xmax, window_ymin, window_ymax;
int data_xoffset, data_yoffset, data_window_offset, xsize, ysize;
int i, x, buf_size = s->buf_size;
int c, rgb_channel_count;
float one_gamma = 1.0f / s->gamma;
avpriv_trc_function trc_func = avpriv_get_trc_function_from_trc(s->apply_trc_type);
int ret;
line_offset = AV_RL64(s->gb.buffer + jobnr * 8);
if (s->is_tile) {
if (buf_size < 20 || line_offset > buf_size - 20)
return AVERROR_INVALIDDATA;
src = buf + line_offset + 20;
tile_x = AV_RL32(src - 20);
tile_y = AV_RL32(src - 16);
tile_level_x = AV_RL32(src - 12);
tile_level_y = AV_RL32(src - 8);
data_size = AV_RL32(src - 4);
if (data_size <= 0 || data_size > buf_size - line_offset - 20)
return AVERROR_INVALIDDATA;
if (tile_level_x || tile_level_y) { /* tile level, is not the full res level */
avpriv_report_missing_feature(s->avctx, "Subres tile before full res tile");
return AVERROR_PATCHWELCOME;
}
line = s->ymin + s->tile_attr.ySize * tile_y;
col = s->tile_attr.xSize * tile_x;
if (line < s->ymin || line > s->ymax ||
s->xmin + col < s->xmin || s->xmin + col > s->xmax)
return AVERROR_INVALIDDATA;
td->ysize = FFMIN(s->tile_attr.ySize, s->ydelta - tile_y * s->tile_attr.ySize);
td->xsize = FFMIN(s->tile_attr.xSize, s->xdelta - tile_x * s->tile_attr.xSize);
if (td->xsize * (uint64_t)s->current_channel_offset > INT_MAX)
return AVERROR_INVALIDDATA;
td->channel_line_size = td->xsize * s->current_channel_offset;/* uncompress size of one line */
uncompressed_size = td->channel_line_size * (uint64_t)td->ysize;/* uncompress size of the block */
} else {
if (buf_size < 8 || line_offset > buf_size - 8)
return AVERROR_INVALIDDATA;
src = buf + line_offset + 8;
line = AV_RL32(src - 8);
if (line < s->ymin || line > s->ymax)
return AVERROR_INVALIDDATA;
data_size = AV_RL32(src - 4);
if (data_size <= 0 || data_size > buf_size - line_offset - 8)
return AVERROR_INVALIDDATA;
td->ysize = FFMIN(s->scan_lines_per_block, s->ymax - line + 1); /* s->ydelta - line ?? */
td->xsize = s->xdelta;
if (td->xsize * (uint64_t)s->current_channel_offset > INT_MAX)
return AVERROR_INVALIDDATA;
td->channel_line_size = td->xsize * s->current_channel_offset;/* uncompress size of one line */
uncompressed_size = td->channel_line_size * (uint64_t)td->ysize;/* uncompress size of the block */
if ((s->compression == EXR_RAW && (data_size != uncompressed_size ||
line_offset > buf_size - uncompressed_size)) ||
(s->compression != EXR_RAW && (data_size > uncompressed_size ||
line_offset > buf_size - data_size))) {
return AVERROR_INVALIDDATA;
}
}
window_xmin = FFMIN(avctx->width, FFMAX(0, s->xmin + col));
window_xmax = FFMIN(avctx->width, FFMAX(0, s->xmin + col + td->xsize));
window_ymin = FFMIN(avctx->height, FFMAX(0, line ));
window_ymax = FFMIN(avctx->height, FFMAX(0, line + td->ysize));
xsize = window_xmax - window_xmin;
ysize = window_ymax - window_ymin;
/* tile or scanline not visible skip decoding */
if (xsize <= 0 || ysize <= 0)
return 0;
/* is the first tile or is a scanline */
if(col == 0) {
window_xmin = 0;
/* pixels to add at the left of the display window */
window_xoffset = FFMAX(0, s->xmin);
/* bytes to add at the left of the display window */
bxmin = window_xoffset * step;
}
/* is the last tile or is a scanline */
if(col + td->xsize == s->xdelta) {
window_xmax = avctx->width;
/* bytes to add at the right of the display window */
axmax = FFMAX(0, (avctx->width - (s->xmax + 1))) * step;
}
if (data_size < uncompressed_size || s->is_tile) { /* td->tmp is use for tile reorganization */
av_fast_padded_malloc(&td->tmp, &td->tmp_size, uncompressed_size);
if (!td->tmp)
return AVERROR(ENOMEM);
}
if (data_size < uncompressed_size) {
av_fast_padded_malloc(&td->uncompressed_data,
&td->uncompressed_size, uncompressed_size + 64);/* Force 64 padding for AVX2 reorder_pixels dst */
if (!td->uncompressed_data)
return AVERROR(ENOMEM);
ret = AVERROR_INVALIDDATA;
switch (s->compression) {
case EXR_ZIP1:
case EXR_ZIP16:
ret = zip_uncompress(s, src, data_size, uncompressed_size, td);
break;
case EXR_PIZ:
ret = piz_uncompress(s, src, data_size, uncompressed_size, td);
break;
case EXR_PXR24:
ret = pxr24_uncompress(s, src, data_size, uncompressed_size, td);
break;
case EXR_RLE:
ret = rle_uncompress(s, src, data_size, uncompressed_size, td);
break;
case EXR_B44:
case EXR_B44A:
ret = b44_uncompress(s, src, data_size, uncompressed_size, td);
break;
}
if (ret < 0) {
av_log(avctx, AV_LOG_ERROR, "decode_block() failed.\n");
return ret;
}
src = td->uncompressed_data;
}
/* offsets to crop data outside display window */
data_xoffset = FFABS(FFMIN(0, s->xmin + col)) * (s->pixel_type == EXR_HALF ? 2 : 4);
data_yoffset = FFABS(FFMIN(0, line));
data_window_offset = (data_yoffset * td->channel_line_size) + data_xoffset;
if (!s->is_luma) {
channel_buffer[0] = src + (td->xsize * s->channel_offsets[0]) + data_window_offset;
channel_buffer[1] = src + (td->xsize * s->channel_offsets[1]) + data_window_offset;
channel_buffer[2] = src + (td->xsize * s->channel_offsets[2]) + data_window_offset;
rgb_channel_count = 3;
} else { /* put y data in the first channel_buffer */
channel_buffer[0] = src + (td->xsize * s->channel_offsets[1]) + data_window_offset;
rgb_channel_count = 1;
}
if (s->channel_offsets[3] >= 0)
channel_buffer[3] = src + (td->xsize * s->channel_offsets[3]) + data_window_offset;
if (s->desc->flags & AV_PIX_FMT_FLAG_FLOAT) {
/* todo: change this when a floating point pixel format with luma with alpha is implemented */
int channel_count = s->channel_offsets[3] >= 0 ? 4 : rgb_channel_count;
if (s->is_luma) {
channel_buffer[1] = channel_buffer[0];
channel_buffer[2] = channel_buffer[0];
}
for (c = 0; c < channel_count; c++) {
int plane = s->desc->comp[c].plane;
ptr = p->data[plane] + window_ymin * p->linesize[plane] + (window_xmin * 4);
for (i = 0; i < ysize; i++, ptr += p->linesize[plane]) {
const uint8_t *src;
union av_intfloat32 *ptr_x;
src = channel_buffer[c];
ptr_x = (union av_intfloat32 *)ptr;
// Zero out the start if xmin is not 0
memset(ptr_x, 0, bxmin);
ptr_x += window_xoffset;
if (s->pixel_type == EXR_FLOAT) {
// 32-bit
union av_intfloat32 t;
if (trc_func && c < 3) {
for (x = 0; x < xsize; x++) {
t.i = bytestream_get_le32(&src);
t.f = trc_func(t.f);
*ptr_x++ = t;
}
} else {
for (x = 0; x < xsize; x++) {
t.i = bytestream_get_le32(&src);
if (t.f > 0.0f && c < 3) /* avoid negative values */
t.f = powf(t.f, one_gamma);
*ptr_x++ = t;
}
}
} else if (s->pixel_type == EXR_HALF) {
// 16-bit
if (c < 3 || !trc_func) {
for (x = 0; x < xsize; x++) {
*ptr_x++ = s->gamma_table[bytestream_get_le16(&src)];
}
} else {
for (x = 0; x < xsize; x++) {
*ptr_x++ = exr_half2float(bytestream_get_le16(&src));;
}
}
}
// Zero out the end if xmax+1 is not w
memset(ptr_x, 0, axmax);
channel_buffer[c] += td->channel_line_size;
}
}
} else {
av_assert1(s->pixel_type == EXR_UINT);
ptr = p->data[0] + window_ymin * p->linesize[0] + (window_xmin * s->desc->nb_components * 2);
for (i = 0; i < ysize; i++, ptr += p->linesize[0]) {
const uint8_t * a;
const uint8_t *rgb[3];
uint16_t *ptr_x;
for (c = 0; c < rgb_channel_count; c++) {
rgb[c] = channel_buffer[c];
}
if (channel_buffer[3])
a = channel_buffer[3];
ptr_x = (uint16_t *) ptr;
// Zero out the start if xmin is not 0
memset(ptr_x, 0, bxmin);
ptr_x += window_xoffset * s->desc->nb_components;
for (x = 0; x < xsize; x++) {
for (c = 0; c < rgb_channel_count; c++) {
*ptr_x++ = bytestream_get_le32(&rgb[c]) >> 16;
}
if (channel_buffer[3])
*ptr_x++ = bytestream_get_le32(&a) >> 16;
}
// Zero out the end if xmax+1 is not w
memset(ptr_x, 0, axmax);
channel_buffer[0] += td->channel_line_size;
channel_buffer[1] += td->channel_line_size;
channel_buffer[2] += td->channel_line_size;
if (channel_buffer[3])
channel_buffer[3] += td->channel_line_size;
}
}
return 0;
}
/**
* Check if the variable name corresponds to its data type.
*
* @param s the EXRContext
* @param value_name name of the variable to check
* @param value_type type of the variable to check
* @param minimum_length minimum length of the variable data
*
* @return bytes to read containing variable data
* -1 if variable is not found
* 0 if buffer ended prematurely
*/
static int check_header_variable(EXRContext *s,
const char *value_name,
const char *value_type,
unsigned int minimum_length)
{
int var_size = -1;
if (bytestream2_get_bytes_left(&s->gb) >= minimum_length &&
!strcmp(s->gb.buffer, value_name)) {
// found value_name, jump to value_type (null terminated strings)
s->gb.buffer += strlen(value_name) + 1;
if (!strcmp(s->gb.buffer, value_type)) {
s->gb.buffer += strlen(value_type) + 1;
var_size = bytestream2_get_le32(&s->gb);
// don't go read past boundaries
if (var_size > bytestream2_get_bytes_left(&s->gb))
var_size = 0;
} else {
// value_type not found, reset the buffer
s->gb.buffer -= strlen(value_name) + 1;
av_log(s->avctx, AV_LOG_WARNING,
"Unknown data type %s for header variable %s.\n",
value_type, value_name);
}
}
return var_size;
}
static int decode_header(EXRContext *s, AVFrame *frame)
{
AVDictionary *metadata = NULL;
int magic_number, version, i, flags, sar = 0;
int layer_match = 0;
int ret;
int dup_channels = 0;
s->current_channel_offset = 0;
s->xmin = ~0;
s->xmax = ~0;
s->ymin = ~0;
s->ymax = ~0;
s->xdelta = ~0;
s->ydelta = ~0;
s->channel_offsets[0] = -1;
s->channel_offsets[1] = -1;
s->channel_offsets[2] = -1;
s->channel_offsets[3] = -1;
s->pixel_type = EXR_UNKNOWN;
s->compression = EXR_UNKN;
s->nb_channels = 0;
s->w = 0;
s->h = 0;
s->tile_attr.xSize = -1;
s->tile_attr.ySize = -1;
s->is_tile = 0;
s->is_luma = 0;
if (bytestream2_get_bytes_left(&s->gb) < 10) {
av_log(s->avctx, AV_LOG_ERROR, "Header too short to parse.\n");
return AVERROR_INVALIDDATA;
}
magic_number = bytestream2_get_le32(&s->gb);
if (magic_number != 20000630) {
/* As per documentation of OpenEXR, it is supposed to be
* int 20000630 little-endian */
av_log(s->avctx, AV_LOG_ERROR, "Wrong magic number %d.\n", magic_number);
return AVERROR_INVALIDDATA;
}
version = bytestream2_get_byte(&s->gb);
if (version != 2) {
avpriv_report_missing_feature(s->avctx, "Version %d", version);
return AVERROR_PATCHWELCOME;
}
flags = bytestream2_get_le24(&s->gb);
if (flags & 0x02)
s->is_tile = 1;
if (flags & 0x08) {
avpriv_report_missing_feature(s->avctx, "deep data");
return AVERROR_PATCHWELCOME;
}
if (flags & 0x10) {
avpriv_report_missing_feature(s->avctx, "multipart");
return AVERROR_PATCHWELCOME;
}
// Parse the header
while (bytestream2_get_bytes_left(&s->gb) > 0 && *s->gb.buffer) {
int var_size;
if ((var_size = check_header_variable(s, "channels",
"chlist", 38)) >= 0) {
GetByteContext ch_gb;
if (!var_size) {
ret = AVERROR_INVALIDDATA;
goto fail;
}
bytestream2_init(&ch_gb, s->gb.buffer, var_size);
while (bytestream2_get_bytes_left(&ch_gb) >= 19) {
EXRChannel *channel;
enum ExrPixelType current_pixel_type;
int channel_index = -1;
int xsub, ysub;
if (strcmp(s->layer, "") != 0) {
if (strncmp(ch_gb.buffer, s->layer, strlen(s->layer)) == 0) {
layer_match = 1;
av_log(s->avctx, AV_LOG_INFO,
"Channel match layer : %s.\n", ch_gb.buffer);
ch_gb.buffer += strlen(s->layer);
if (*ch_gb.buffer == '.')
ch_gb.buffer++; /* skip dot if not given */
} else {
layer_match = 0;
av_log(s->avctx, AV_LOG_INFO,
"Channel doesn't match layer : %s.\n", ch_gb.buffer);
}
} else {
layer_match = 1;
}
if (layer_match) { /* only search channel if the layer match is valid */
if (!av_strcasecmp(ch_gb.buffer, "R") ||
!av_strcasecmp(ch_gb.buffer, "X") ||
!av_strcasecmp(ch_gb.buffer, "U")) {
channel_index = 0;
s->is_luma = 0;
} else if (!av_strcasecmp(ch_gb.buffer, "G") ||
!av_strcasecmp(ch_gb.buffer, "V")) {
channel_index = 1;
s->is_luma = 0;
} else if (!av_strcasecmp(ch_gb.buffer, "Y")) {
channel_index = 1;
s->is_luma = 1;
} else if (!av_strcasecmp(ch_gb.buffer, "B") ||
!av_strcasecmp(ch_gb.buffer, "Z") ||
!av_strcasecmp(ch_gb.buffer, "W")) {
channel_index = 2;
s->is_luma = 0;
} else if (!av_strcasecmp(ch_gb.buffer, "A")) {
channel_index = 3;
} else {
av_log(s->avctx, AV_LOG_WARNING,
"Unsupported channel %.256s.\n", ch_gb.buffer);
}
}
/* skip until you get a 0 */
while (bytestream2_get_bytes_left(&ch_gb) > 0 &&
bytestream2_get_byte(&ch_gb))
continue;
if (bytestream2_get_bytes_left(&ch_gb) < 4) {
av_log(s->avctx, AV_LOG_ERROR, "Incomplete header.\n");
ret = AVERROR_INVALIDDATA;
goto fail;
}
current_pixel_type = bytestream2_get_le32(&ch_gb);
if (current_pixel_type >= EXR_UNKNOWN) {
avpriv_report_missing_feature(s->avctx, "Pixel type %d",
current_pixel_type);
ret = AVERROR_PATCHWELCOME;
goto fail;
}
bytestream2_skip(&ch_gb, 4);
xsub = bytestream2_get_le32(&ch_gb);
ysub = bytestream2_get_le32(&ch_gb);
if (xsub != 1 || ysub != 1) {
avpriv_report_missing_feature(s->avctx,
"Subsampling %dx%d",
xsub, ysub);
ret = AVERROR_PATCHWELCOME;
goto fail;
}
if (channel_index >= 0 && s->channel_offsets[channel_index] == -1) { /* channel has not been previously assigned */
if (s->pixel_type != EXR_UNKNOWN &&
s->pixel_type != current_pixel_type) {
av_log(s->avctx, AV_LOG_ERROR,
"RGB channels not of the same depth.\n");
ret = AVERROR_INVALIDDATA;
goto fail;
}
s->pixel_type = current_pixel_type;
s->channel_offsets[channel_index] = s->current_channel_offset;
} else if (channel_index >= 0) {
av_log(s->avctx, AV_LOG_WARNING,
"Multiple channels with index %d.\n", channel_index);
if (++dup_channels > 10) {
ret = AVERROR_INVALIDDATA;
goto fail;
}
}
s->channels = av_realloc(s->channels,
++s->nb_channels * sizeof(EXRChannel));
if (!s->channels) {
ret = AVERROR(ENOMEM);
goto fail;
}
channel = &s->channels[s->nb_channels - 1];
channel->pixel_type = current_pixel_type;
channel->xsub = xsub;
channel->ysub = ysub;
if (current_pixel_type == EXR_HALF) {
s->current_channel_offset += 2;
} else {/* Float or UINT32 */
s->current_channel_offset += 4;
}
}
/* Check if all channels are set with an offset or if the channels
* are causing an overflow */
if (!s->is_luma) {/* if we expected to have at least 3 channels */
if (FFMIN3(s->channel_offsets[0],
s->channel_offsets[1],
s->channel_offsets[2]) < 0) {
if (s->channel_offsets[0] < 0)
av_log(s->avctx, AV_LOG_ERROR, "Missing red channel.\n");
if (s->channel_offsets[1] < 0)
av_log(s->avctx, AV_LOG_ERROR, "Missing green channel.\n");
if (s->channel_offsets[2] < 0)
av_log(s->avctx, AV_LOG_ERROR, "Missing blue channel.\n");
ret = AVERROR_INVALIDDATA;
goto fail;
}
}
// skip one last byte and update main gb
s->gb.buffer = ch_gb.buffer + 1;
continue;
} else if ((var_size = check_header_variable(s, "dataWindow", "box2i",
31)) >= 0) {
int xmin, ymin, xmax, ymax;
if (!var_size) {
ret = AVERROR_INVALIDDATA;
goto fail;
}
xmin = bytestream2_get_le32(&s->gb);
ymin = bytestream2_get_le32(&s->gb);
xmax = bytestream2_get_le32(&s->gb);
ymax = bytestream2_get_le32(&s->gb);
if (xmin > xmax || ymin > ymax ||
(unsigned)xmax - xmin >= INT_MAX ||
(unsigned)ymax - ymin >= INT_MAX) {
ret = AVERROR_INVALIDDATA;
goto fail;
}
s->xmin = xmin;
s->xmax = xmax;
s->ymin = ymin;
s->ymax = ymax;
s->xdelta = (s->xmax - s->xmin) + 1;
s->ydelta = (s->ymax - s->ymin) + 1;
continue;
} else if ((var_size = check_header_variable(s, "displayWindow",
"box2i", 34)) >= 0) {
if (!var_size) {
ret = AVERROR_INVALIDDATA;
goto fail;
}
bytestream2_skip(&s->gb, 8);
s->w = bytestream2_get_le32(&s->gb) + 1;
s->h = bytestream2_get_le32(&s->gb) + 1;
continue;
} else if ((var_size = check_header_variable(s, "lineOrder",
"lineOrder", 25)) >= 0) {
int line_order;
if (!var_size) {
ret = AVERROR_INVALIDDATA;
goto fail;
}
line_order = bytestream2_get_byte(&s->gb);
av_log(s->avctx, AV_LOG_DEBUG, "line order: %d.\n", line_order);
if (line_order > 2) {
av_log(s->avctx, AV_LOG_ERROR, "Unknown line order.\n");
ret = AVERROR_INVALIDDATA;
goto fail;
}
continue;
} else if ((var_size = check_header_variable(s, "pixelAspectRatio",
"float", 31)) >= 0) {
if (!var_size) {
ret = AVERROR_INVALIDDATA;
goto fail;
}
sar = bytestream2_get_le32(&s->gb);
continue;
} else if ((var_size = check_header_variable(s, "compression",
"compression", 29)) >= 0) {
if (!var_size) {
ret = AVERROR_INVALIDDATA;
goto fail;
}
if (s->compression == EXR_UNKN)
s->compression = bytestream2_get_byte(&s->gb);
else
av_log(s->avctx, AV_LOG_WARNING,
"Found more than one compression attribute.\n");
continue;
} else if ((var_size = check_header_variable(s, "tiles",
"tiledesc", 22)) >= 0) {
char tileLevel;
if (!s->is_tile)
av_log(s->avctx, AV_LOG_WARNING,
"Found tile attribute and scanline flags. Exr will be interpreted as scanline.\n");
s->tile_attr.xSize = bytestream2_get_le32(&s->gb);
s->tile_attr.ySize = bytestream2_get_le32(&s->gb);
tileLevel = bytestream2_get_byte(&s->gb);
s->tile_attr.level_mode = tileLevel & 0x0f;
s->tile_attr.level_round = (tileLevel >> 4) & 0x0f;
if (s->tile_attr.level_mode >= EXR_TILE_LEVEL_UNKNOWN) {
avpriv_report_missing_feature(s->avctx, "Tile level mode %d",
s->tile_attr.level_mode);
ret = AVERROR_PATCHWELCOME;
goto fail;
}
if (s->tile_attr.level_round >= EXR_TILE_ROUND_UNKNOWN) {
avpriv_report_missing_feature(s->avctx, "Tile level round %d",
s->tile_attr.level_round);
ret = AVERROR_PATCHWELCOME;
goto fail;
}
continue;
} else if ((var_size = check_header_variable(s, "writer",
"string", 1)) >= 0) {
uint8_t key[256] = { 0 };
bytestream2_get_buffer(&s->gb, key, FFMIN(sizeof(key) - 1, var_size));
av_dict_set(&metadata, "writer", key, 0);
continue;
}
// Check if there are enough bytes for a header
if (bytestream2_get_bytes_left(&s->gb) <= 9) {
av_log(s->avctx, AV_LOG_ERROR, "Incomplete header\n");
ret = AVERROR_INVALIDDATA;
goto fail;
}
// Process unknown variables
for (i = 0; i < 2; i++) // value_name and value_type
while (bytestream2_get_byte(&s->gb) != 0);
// Skip variable length
bytestream2_skip(&s->gb, bytestream2_get_le32(&s->gb));
}
ff_set_sar(s->avctx, av_d2q(av_int2float(sar), 255));
if (s->compression == EXR_UNKN) {
av_log(s->avctx, AV_LOG_ERROR, "Missing compression attribute.\n");
ret = AVERROR_INVALIDDATA;
goto fail;
}
if (s->is_tile) {
if (s->tile_attr.xSize < 1 || s->tile_attr.ySize < 1) {
av_log(s->avctx, AV_LOG_ERROR, "Invalid tile attribute.\n");
ret = AVERROR_INVALIDDATA;
goto fail;
}
}
if (bytestream2_get_bytes_left(&s->gb) <= 0) {
av_log(s->avctx, AV_LOG_ERROR, "Incomplete frame.\n");
ret = AVERROR_INVALIDDATA;
goto fail;
}
frame->metadata = metadata;
// aaand we are done
bytestream2_skip(&s->gb, 1);
return 0;
fail:
av_dict_free(&metadata);
return ret;
}
static int decode_frame(AVCodecContext *avctx, void *data,
int *got_frame, AVPacket *avpkt)
{
EXRContext *s = avctx->priv_data;
ThreadFrame frame = { .f = data };
AVFrame *picture = data;
uint8_t *ptr;
int i, y, ret, ymax;
int planes;
int out_line_size;
int nb_blocks; /* nb scanline or nb tile */
uint64_t start_offset_table;
uint64_t start_next_scanline;
PutByteContext offset_table_writer;
bytestream2_init(&s->gb, avpkt->data, avpkt->size);
if ((ret = decode_header(s, picture)) < 0)
return ret;
switch (s->pixel_type) {
case EXR_FLOAT:
case EXR_HALF:
if (s->channel_offsets[3] >= 0) {
if (!s->is_luma) {
avctx->pix_fmt = AV_PIX_FMT_GBRAPF32;
} else {
/* todo: change this when a floating point pixel format with luma with alpha is implemented */
avctx->pix_fmt = AV_PIX_FMT_GBRAPF32;
}
} else {
if (!s->is_luma) {
avctx->pix_fmt = AV_PIX_FMT_GBRPF32;
} else {
avctx->pix_fmt = AV_PIX_FMT_GRAYF32;
}
}
break;
case EXR_UINT:
if (s->channel_offsets[3] >= 0) {
if (!s->is_luma) {
avctx->pix_fmt = AV_PIX_FMT_RGBA64;
} else {
avctx->pix_fmt = AV_PIX_FMT_YA16;
}
} else {
if (!s->is_luma) {
avctx->pix_fmt = AV_PIX_FMT_RGB48;
} else {
avctx->pix_fmt = AV_PIX_FMT_GRAY16;
}
}
break;
default:
av_log(avctx, AV_LOG_ERROR, "Missing channel list.\n");
return AVERROR_INVALIDDATA;
}
if (s->apply_trc_type != AVCOL_TRC_UNSPECIFIED)
avctx->color_trc = s->apply_trc_type;
switch (s->compression) {
case EXR_RAW:
case EXR_RLE:
case EXR_ZIP1:
s->scan_lines_per_block = 1;
break;
case EXR_PXR24:
case EXR_ZIP16:
s->scan_lines_per_block = 16;
break;
case EXR_PIZ:
case EXR_B44:
case EXR_B44A:
s->scan_lines_per_block = 32;
break;
default:
avpriv_report_missing_feature(avctx, "Compression %d", s->compression);
return AVERROR_PATCHWELCOME;
}
/* Verify the xmin, xmax, ymin and ymax before setting the actual image size.
* It's possible for the data window can larger or outside the display window */
if (s->xmin > s->xmax || s->ymin > s->ymax ||
s->ydelta == 0xFFFFFFFF || s->xdelta == 0xFFFFFFFF) {
av_log(avctx, AV_LOG_ERROR, "Wrong or missing size information.\n");
return AVERROR_INVALIDDATA;
}
if ((ret = ff_set_dimensions(avctx, s->w, s->h)) < 0)
return ret;
s->desc = av_pix_fmt_desc_get(avctx->pix_fmt);
if (!s->desc)
return AVERROR_INVALIDDATA;
if (s->desc->flags & AV_PIX_FMT_FLAG_FLOAT) {
planes = s->desc->nb_components;
out_line_size = avctx->width * 4;
} else {
planes = 1;
out_line_size = avctx->width * 2 * s->desc->nb_components;
}
if (s->is_tile) {
nb_blocks = ((s->xdelta + s->tile_attr.xSize - 1) / s->tile_attr.xSize) *
((s->ydelta + s->tile_attr.ySize - 1) / s->tile_attr.ySize);
} else { /* scanline */
nb_blocks = (s->ydelta + s->scan_lines_per_block - 1) /
s->scan_lines_per_block;
}
if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0)
return ret;
if (bytestream2_get_bytes_left(&s->gb)/8 < nb_blocks)
return AVERROR_INVALIDDATA;
// check offset table and recreate it if need
if (!s->is_tile && bytestream2_peek_le64(&s->gb) == 0) {
av_log(s->avctx, AV_LOG_DEBUG, "recreating invalid scanline offset table\n");
start_offset_table = bytestream2_tell(&s->gb);
start_next_scanline = start_offset_table + nb_blocks * 8;
bytestream2_init_writer(&offset_table_writer, &avpkt->data[start_offset_table], nb_blocks * 8);
for (y = 0; y < nb_blocks; y++) {
/* write offset of prev scanline in offset table */
bytestream2_put_le64(&offset_table_writer, start_next_scanline);
/* get len of next scanline */
bytestream2_seek(&s->gb, start_next_scanline + 4, SEEK_SET);/* skip line number */
start_next_scanline += (bytestream2_get_le32(&s->gb) + 8);
}
bytestream2_seek(&s->gb, start_offset_table, SEEK_SET);
}
// save pointer we are going to use in decode_block
s->buf = avpkt->data;
s->buf_size = avpkt->size;
// Zero out the start if ymin is not 0
for (i = 0; i < planes; i++) {
ptr = picture->data[i];
for (y = 0; y < FFMIN(s->ymin, s->h); y++) {
memset(ptr, 0, out_line_size);
ptr += picture->linesize[i];
}
}
s->picture = picture;
avctx->execute2(avctx, decode_block, s->thread_data, NULL, nb_blocks);
ymax = FFMAX(0, s->ymax + 1);
// Zero out the end if ymax+1 is not h
for (i = 0; i < planes; i++) {
ptr = picture->data[i] + (ymax * picture->linesize[i]);
for (y = ymax; y < avctx->height; y++) {
memset(ptr, 0, out_line_size);
ptr += picture->linesize[i];
}
}
picture->pict_type = AV_PICTURE_TYPE_I;
*got_frame = 1;
return avpkt->size;
}
static av_cold int decode_init(AVCodecContext *avctx)
{
EXRContext *s = avctx->priv_data;
uint32_t i;
union av_intfloat32 t;
float one_gamma = 1.0f / s->gamma;
avpriv_trc_function trc_func = NULL;
s->avctx = avctx;
ff_exrdsp_init(&s->dsp);
#if HAVE_BIGENDIAN
ff_bswapdsp_init(&s->bbdsp);
#endif
trc_func = avpriv_get_trc_function_from_trc(s->apply_trc_type);
if (trc_func) {
for (i = 0; i < 65536; ++i) {
t = exr_half2float(i);
t.f = trc_func(t.f);
s->gamma_table[i] = t;
}
} else {
if (one_gamma > 0.9999f && one_gamma < 1.0001f) {
for (i = 0; i < 65536; ++i) {
s->gamma_table[i] = exr_half2float(i);
}
} else {
for (i = 0; i < 65536; ++i) {
t = exr_half2float(i);
/* If negative value we reuse half value */
if (t.f <= 0.0f) {
s->gamma_table[i] = t;
} else {
t.f = powf(t.f, one_gamma);
s->gamma_table[i] = t;
}
}
}
}
// allocate thread data, used for non EXR_RAW compression types
s->thread_data = av_mallocz_array(avctx->thread_count, sizeof(EXRThreadData));
if (!s->thread_data)
return AVERROR_INVALIDDATA;
return 0;
}
static av_cold int decode_end(AVCodecContext *avctx)
{
EXRContext *s = avctx->priv_data;
int i;
for (i = 0; i < avctx->thread_count; i++) {
EXRThreadData *td = &s->thread_data[i];
av_freep(&td->uncompressed_data);
av_freep(&td->tmp);
av_freep(&td->bitmap);
av_freep(&td->lut);
}
av_freep(&s->thread_data);
av_freep(&s->channels);
return 0;
}
#define OFFSET(x) offsetof(EXRContext, x)
#define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
static const AVOption options[] = {
{ "layer", "Set the decoding layer", OFFSET(layer),
AV_OPT_TYPE_STRING, { .str = "" }, 0, 0, VD },
{ "gamma", "Set the float gamma value when decoding", OFFSET(gamma),
AV_OPT_TYPE_FLOAT, { .dbl = 1.0f }, 0.001, FLT_MAX, VD },
// XXX: Note the abuse of the enum using AVCOL_TRC_UNSPECIFIED to subsume the existing gamma option
{ "apply_trc", "color transfer characteristics to apply to EXR linear input", OFFSET(apply_trc_type),
AV_OPT_TYPE_INT, {.i64 = AVCOL_TRC_UNSPECIFIED }, 1, AVCOL_TRC_NB-1, VD, "apply_trc_type"},
{ "bt709", "BT.709", 0,
AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT709 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
{ "gamma", "gamma", 0,
AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_UNSPECIFIED }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
{ "gamma22", "BT.470 M", 0,
AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_GAMMA22 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
{ "gamma28", "BT.470 BG", 0,
AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_GAMMA28 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
{ "smpte170m", "SMPTE 170 M", 0,
AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTE170M }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
{ "smpte240m", "SMPTE 240 M", 0,
AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTE240M }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
{ "linear", "Linear", 0,
AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LINEAR }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
{ "log", "Log", 0,
AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LOG }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
{ "log_sqrt", "Log square root", 0,
AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LOG_SQRT }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
{ "iec61966_2_4", "IEC 61966-2-4", 0,
AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_IEC61966_2_4 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
{ "bt1361", "BT.1361", 0,
AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT1361_ECG }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
{ "iec61966_2_1", "IEC 61966-2-1", 0,
AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_IEC61966_2_1 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
{ "bt2020_10bit", "BT.2020 - 10 bit", 0,
AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT2020_10 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
{ "bt2020_12bit", "BT.2020 - 12 bit", 0,
AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT2020_12 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
{ "smpte2084", "SMPTE ST 2084", 0,
AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTEST2084 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
{ "smpte428_1", "SMPTE ST 428-1", 0,
AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTEST428_1 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
{ NULL },
};
static const AVClass exr_class = {
.class_name = "EXR",
.item_name = av_default_item_name,
.option = options,
.version = LIBAVUTIL_VERSION_INT,
};
AVCodec ff_exr_decoder = {
.name = "exr",
.long_name = NULL_IF_CONFIG_SMALL("OpenEXR image"),
.type = AVMEDIA_TYPE_VIDEO,
.id = AV_CODEC_ID_EXR,
.priv_data_size = sizeof(EXRContext),
.init = decode_init,
.close = decode_end,
.decode = decode_frame,
.capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS |
AV_CODEC_CAP_SLICE_THREADS,
.priv_class = &exr_class,
};
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_4485_0 |
crossvul-cpp_data_good_3295_0 | /*
* Pictor/PC Paint decoder
* Copyright (c) 2010 Peter Ross <pross@xvid.org>
*
* This file is part of FFmpeg.
*
* FFmpeg 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.
*
* FFmpeg 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 FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* Pictor/PC Paint decoder
*/
#include "libavutil/imgutils.h"
#include "avcodec.h"
#include "bytestream.h"
#include "cga_data.h"
#include "internal.h"
typedef struct PicContext {
int width, height;
int nb_planes;
GetByteContext g;
} PicContext;
static void picmemset_8bpp(PicContext *s, AVFrame *frame, int value, int run,
int *x, int *y)
{
while (run > 0) {
uint8_t *d = frame->data[0] + *y * frame->linesize[0];
if (*x + run >= s->width) {
int n = s->width - *x;
memset(d + *x, value, n);
run -= n;
*x = 0;
*y -= 1;
if (*y < 0)
break;
} else {
memset(d + *x, value, run);
*x += run;
break;
}
}
}
static void picmemset(PicContext *s, AVFrame *frame, int value, int run,
int *x, int *y, int *plane, int bits_per_plane)
{
uint8_t *d;
int shift = *plane * bits_per_plane;
int mask = ((1 << bits_per_plane) - 1) << shift;
value <<= shift;
while (run > 0) {
int j;
for (j = 8-bits_per_plane; j >= 0; j -= bits_per_plane) {
d = frame->data[0] + *y * frame->linesize[0];
d[*x] |= (value >> j) & mask;
*x += 1;
if (*x == s->width) {
*y -= 1;
*x = 0;
if (*y < 0) {
*y = s->height - 1;
*plane += 1;
value <<= bits_per_plane;
mask <<= bits_per_plane;
if (*plane >= s->nb_planes)
break;
}
}
}
run--;
}
}
static const uint8_t cga_mode45_index[6][4] = {
[0] = { 0, 3, 5, 7 }, // mode4, palette#1, low intensity
[1] = { 0, 2, 4, 6 }, // mode4, palette#2, low intensity
[2] = { 0, 3, 4, 7 }, // mode5, low intensity
[3] = { 0, 11, 13, 15 }, // mode4, palette#1, high intensity
[4] = { 0, 10, 12, 14 }, // mode4, palette#2, high intensity
[5] = { 0, 11, 12, 15 }, // mode5, high intensity
};
static int decode_frame(AVCodecContext *avctx,
void *data, int *got_frame,
AVPacket *avpkt)
{
PicContext *s = avctx->priv_data;
AVFrame *frame = data;
uint32_t *palette;
int bits_per_plane, bpp, etype, esize, npal, pos_after_pal;
int i, x, y, plane, tmp, ret, val;
bytestream2_init(&s->g, avpkt->data, avpkt->size);
if (bytestream2_get_bytes_left(&s->g) < 11)
return AVERROR_INVALIDDATA;
if (bytestream2_get_le16u(&s->g) != 0x1234)
return AVERROR_INVALIDDATA;
s->width = bytestream2_get_le16u(&s->g);
s->height = bytestream2_get_le16u(&s->g);
bytestream2_skip(&s->g, 4);
tmp = bytestream2_get_byteu(&s->g);
bits_per_plane = tmp & 0xF;
s->nb_planes = (tmp >> 4) + 1;
bpp = bits_per_plane * s->nb_planes;
if (bits_per_plane > 8 || bpp < 1 || bpp > 32) {
avpriv_request_sample(avctx, "Unsupported bit depth");
return AVERROR_PATCHWELCOME;
}
if (bytestream2_peek_byte(&s->g) == 0xFF || bpp == 1 || bpp == 4 || bpp == 8) {
bytestream2_skip(&s->g, 2);
etype = bytestream2_get_le16(&s->g);
esize = bytestream2_get_le16(&s->g);
if (bytestream2_get_bytes_left(&s->g) < esize)
return AVERROR_INVALIDDATA;
} else {
etype = -1;
esize = 0;
}
avctx->pix_fmt = AV_PIX_FMT_PAL8;
if (av_image_check_size(s->width, s->height, 0, avctx) < 0)
return -1;
if (s->width != avctx->width || s->height != avctx->height) {
ret = ff_set_dimensions(avctx, s->width, s->height);
if (ret < 0)
return ret;
}
if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
return ret;
memset(frame->data[0], 0, s->height * frame->linesize[0]);
frame->pict_type = AV_PICTURE_TYPE_I;
frame->palette_has_changed = 1;
pos_after_pal = bytestream2_tell(&s->g) + esize;
palette = (uint32_t*)frame->data[1];
if (etype == 1 && esize > 1 && bytestream2_peek_byte(&s->g) < 6) {
int idx = bytestream2_get_byte(&s->g);
npal = 4;
for (i = 0; i < npal; i++)
palette[i] = ff_cga_palette[ cga_mode45_index[idx][i] ];
} else if (etype == 2) {
npal = FFMIN(esize, 16);
for (i = 0; i < npal; i++) {
int pal_idx = bytestream2_get_byte(&s->g);
palette[i] = ff_cga_palette[FFMIN(pal_idx, 15)];
}
} else if (etype == 3) {
npal = FFMIN(esize, 16);
for (i = 0; i < npal; i++) {
int pal_idx = bytestream2_get_byte(&s->g);
palette[i] = ff_ega_palette[FFMIN(pal_idx, 63)];
}
} else if (etype == 4 || etype == 5) {
npal = FFMIN(esize / 3, 256);
for (i = 0; i < npal; i++) {
palette[i] = bytestream2_get_be24(&s->g) << 2;
palette[i] |= 0xFFU << 24 | palette[i] >> 6 & 0x30303;
}
} else {
if (bpp == 1) {
npal = 2;
palette[0] = 0xFF000000;
palette[1] = 0xFFFFFFFF;
} else if (bpp == 2) {
npal = 4;
for (i = 0; i < npal; i++)
palette[i] = ff_cga_palette[ cga_mode45_index[0][i] ];
} else {
npal = 16;
memcpy(palette, ff_cga_palette, npal * 4);
}
}
// fill remaining palette entries
memset(palette + npal, 0, AVPALETTE_SIZE - npal * 4);
// skip remaining palette bytes
bytestream2_seek(&s->g, pos_after_pal, SEEK_SET);
val = 0;
y = s->height - 1;
if (bytestream2_get_le16(&s->g)) {
x = 0;
plane = 0;
while (bytestream2_get_bytes_left(&s->g) >= 6) {
int stop_size, marker, t1, t2;
t1 = bytestream2_get_bytes_left(&s->g);
t2 = bytestream2_get_le16(&s->g);
stop_size = t1 - FFMIN(t1, t2);
// ignore uncompressed block size
bytestream2_skip(&s->g, 2);
marker = bytestream2_get_byte(&s->g);
while (plane < s->nb_planes &&
bytestream2_get_bytes_left(&s->g) > stop_size) {
int run = 1;
val = bytestream2_get_byte(&s->g);
if (val == marker) {
run = bytestream2_get_byte(&s->g);
if (run == 0)
run = bytestream2_get_le16(&s->g);
val = bytestream2_get_byte(&s->g);
}
if (!bytestream2_get_bytes_left(&s->g))
break;
if (bits_per_plane == 8) {
picmemset_8bpp(s, frame, val, run, &x, &y);
if (y < 0)
goto finish;
} else {
picmemset(s, frame, val, run, &x, &y, &plane, bits_per_plane);
}
}
}
if (x < avctx->width) {
int run = (y + 1) * avctx->width - x;
if (bits_per_plane == 8)
picmemset_8bpp(s, frame, val, run, &x, &y);
else
picmemset(s, frame, val, run / (8 / bits_per_plane), &x, &y, &plane, bits_per_plane);
}
} else {
while (y >= 0 && bytestream2_get_bytes_left(&s->g) > 0) {
memcpy(frame->data[0] + y * frame->linesize[0], s->g.buffer, FFMIN(avctx->width, bytestream2_get_bytes_left(&s->g)));
bytestream2_skip(&s->g, avctx->width);
y--;
}
}
finish:
*got_frame = 1;
return avpkt->size;
}
AVCodec ff_pictor_decoder = {
.name = "pictor",
.long_name = NULL_IF_CONFIG_SMALL("Pictor/PC Paint"),
.type = AVMEDIA_TYPE_VIDEO,
.id = AV_CODEC_ID_PICTOR,
.priv_data_size = sizeof(PicContext),
.decode = decode_frame,
.capabilities = AV_CODEC_CAP_DR1,
};
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_3295_0 |
crossvul-cpp_data_good_1288_0 | /**
* @file parser.c
* @author Radek Krejci <rkrejci@cesnet.cz>
* @brief common libyang parsers routines implementations
*
* Copyright (c) 2015-2017 CESNET, z.s.p.o.
*
* This source code is licensed under BSD 3-Clause License (the "License").
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*/
#define _GNU_SOURCE
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <pcre.h>
#include <time.h>
#include "common.h"
#include "context.h"
#include "libyang.h"
#include "parser.h"
#include "resolve.h"
#include "tree_internal.h"
#include "parser_yang.h"
#include "xpath.h"
#define LYP_URANGE_LEN 19
static char *lyp_ublock2urange[][2] = {
{"BasicLatin", "[\\x{0000}-\\x{007F}]"},
{"Latin-1Supplement", "[\\x{0080}-\\x{00FF}]"},
{"LatinExtended-A", "[\\x{0100}-\\x{017F}]"},
{"LatinExtended-B", "[\\x{0180}-\\x{024F}]"},
{"IPAExtensions", "[\\x{0250}-\\x{02AF}]"},
{"SpacingModifierLetters", "[\\x{02B0}-\\x{02FF}]"},
{"CombiningDiacriticalMarks", "[\\x{0300}-\\x{036F}]"},
{"Greek", "[\\x{0370}-\\x{03FF}]"},
{"Cyrillic", "[\\x{0400}-\\x{04FF}]"},
{"Armenian", "[\\x{0530}-\\x{058F}]"},
{"Hebrew", "[\\x{0590}-\\x{05FF}]"},
{"Arabic", "[\\x{0600}-\\x{06FF}]"},
{"Syriac", "[\\x{0700}-\\x{074F}]"},
{"Thaana", "[\\x{0780}-\\x{07BF}]"},
{"Devanagari", "[\\x{0900}-\\x{097F}]"},
{"Bengali", "[\\x{0980}-\\x{09FF}]"},
{"Gurmukhi", "[\\x{0A00}-\\x{0A7F}]"},
{"Gujarati", "[\\x{0A80}-\\x{0AFF}]"},
{"Oriya", "[\\x{0B00}-\\x{0B7F}]"},
{"Tamil", "[\\x{0B80}-\\x{0BFF}]"},
{"Telugu", "[\\x{0C00}-\\x{0C7F}]"},
{"Kannada", "[\\x{0C80}-\\x{0CFF}]"},
{"Malayalam", "[\\x{0D00}-\\x{0D7F}]"},
{"Sinhala", "[\\x{0D80}-\\x{0DFF}]"},
{"Thai", "[\\x{0E00}-\\x{0E7F}]"},
{"Lao", "[\\x{0E80}-\\x{0EFF}]"},
{"Tibetan", "[\\x{0F00}-\\x{0FFF}]"},
{"Myanmar", "[\\x{1000}-\\x{109F}]"},
{"Georgian", "[\\x{10A0}-\\x{10FF}]"},
{"HangulJamo", "[\\x{1100}-\\x{11FF}]"},
{"Ethiopic", "[\\x{1200}-\\x{137F}]"},
{"Cherokee", "[\\x{13A0}-\\x{13FF}]"},
{"UnifiedCanadianAboriginalSyllabics", "[\\x{1400}-\\x{167F}]"},
{"Ogham", "[\\x{1680}-\\x{169F}]"},
{"Runic", "[\\x{16A0}-\\x{16FF}]"},
{"Khmer", "[\\x{1780}-\\x{17FF}]"},
{"Mongolian", "[\\x{1800}-\\x{18AF}]"},
{"LatinExtendedAdditional", "[\\x{1E00}-\\x{1EFF}]"},
{"GreekExtended", "[\\x{1F00}-\\x{1FFF}]"},
{"GeneralPunctuation", "[\\x{2000}-\\x{206F}]"},
{"SuperscriptsandSubscripts", "[\\x{2070}-\\x{209F}]"},
{"CurrencySymbols", "[\\x{20A0}-\\x{20CF}]"},
{"CombiningMarksforSymbols", "[\\x{20D0}-\\x{20FF}]"},
{"LetterlikeSymbols", "[\\x{2100}-\\x{214F}]"},
{"NumberForms", "[\\x{2150}-\\x{218F}]"},
{"Arrows", "[\\x{2190}-\\x{21FF}]"},
{"MathematicalOperators", "[\\x{2200}-\\x{22FF}]"},
{"MiscellaneousTechnical", "[\\x{2300}-\\x{23FF}]"},
{"ControlPictures", "[\\x{2400}-\\x{243F}]"},
{"OpticalCharacterRecognition", "[\\x{2440}-\\x{245F}]"},
{"EnclosedAlphanumerics", "[\\x{2460}-\\x{24FF}]"},
{"BoxDrawing", "[\\x{2500}-\\x{257F}]"},
{"BlockElements", "[\\x{2580}-\\x{259F}]"},
{"GeometricShapes", "[\\x{25A0}-\\x{25FF}]"},
{"MiscellaneousSymbols", "[\\x{2600}-\\x{26FF}]"},
{"Dingbats", "[\\x{2700}-\\x{27BF}]"},
{"BraillePatterns", "[\\x{2800}-\\x{28FF}]"},
{"CJKRadicalsSupplement", "[\\x{2E80}-\\x{2EFF}]"},
{"KangxiRadicals", "[\\x{2F00}-\\x{2FDF}]"},
{"IdeographicDescriptionCharacters", "[\\x{2FF0}-\\x{2FFF}]"},
{"CJKSymbolsandPunctuation", "[\\x{3000}-\\x{303F}]"},
{"Hiragana", "[\\x{3040}-\\x{309F}]"},
{"Katakana", "[\\x{30A0}-\\x{30FF}]"},
{"Bopomofo", "[\\x{3100}-\\x{312F}]"},
{"HangulCompatibilityJamo", "[\\x{3130}-\\x{318F}]"},
{"Kanbun", "[\\x{3190}-\\x{319F}]"},
{"BopomofoExtended", "[\\x{31A0}-\\x{31BF}]"},
{"EnclosedCJKLettersandMonths", "[\\x{3200}-\\x{32FF}]"},
{"CJKCompatibility", "[\\x{3300}-\\x{33FF}]"},
{"CJKUnifiedIdeographsExtensionA", "[\\x{3400}-\\x{4DB5}]"},
{"CJKUnifiedIdeographs", "[\\x{4E00}-\\x{9FFF}]"},
{"YiSyllables", "[\\x{A000}-\\x{A48F}]"},
{"YiRadicals", "[\\x{A490}-\\x{A4CF}]"},
{"HangulSyllables", "[\\x{AC00}-\\x{D7A3}]"},
{"PrivateUse", "[\\x{E000}-\\x{F8FF}]"},
{"CJKCompatibilityIdeographs", "[\\x{F900}-\\x{FAFF}]"},
{"AlphabeticPresentationForms", "[\\x{FB00}-\\x{FB4F}]"},
{"ArabicPresentationForms-A", "[\\x{FB50}-\\x{FDFF}]"},
{"CombiningHalfMarks", "[\\x{FE20}-\\x{FE2F}]"},
{"CJKCompatibilityForms", "[\\x{FE30}-\\x{FE4F}]"},
{"SmallFormVariants", "[\\x{FE50}-\\x{FE6F}]"},
{"ArabicPresentationForms-B", "[\\x{FE70}-\\x{FEFE}]"},
{"HalfwidthandFullwidthForms", "[\\x{FF00}-\\x{FFEF}]"},
{NULL, NULL}
};
const char *ly_stmt_str[] = {
[LY_STMT_UNKNOWN] = "",
[LY_STMT_ARGUMENT] = "argument",
[LY_STMT_BASE] = "base",
[LY_STMT_BELONGSTO] = "belongs-to",
[LY_STMT_CONTACT] = "contact",
[LY_STMT_DEFAULT] = "default",
[LY_STMT_DESCRIPTION] = "description",
[LY_STMT_ERRTAG] = "error-app-tag",
[LY_STMT_ERRMSG] = "error-message",
[LY_STMT_KEY] = "key",
[LY_STMT_NAMESPACE] = "namespace",
[LY_STMT_ORGANIZATION] = "organization",
[LY_STMT_PATH] = "path",
[LY_STMT_PREFIX] = "prefix",
[LY_STMT_PRESENCE] = "presence",
[LY_STMT_REFERENCE] = "reference",
[LY_STMT_REVISIONDATE] = "revision-date",
[LY_STMT_UNITS] = "units",
[LY_STMT_VALUE] = "value",
[LY_STMT_VERSION] = "yang-version",
[LY_STMT_MODIFIER] = "modifier",
[LY_STMT_REQINSTANCE] = "require-instance",
[LY_STMT_YINELEM] = "yin-element",
[LY_STMT_CONFIG] = "config",
[LY_STMT_MANDATORY] = "mandatory",
[LY_STMT_ORDEREDBY] = "ordered-by",
[LY_STMT_STATUS] = "status",
[LY_STMT_DIGITS] = "fraction-digits",
[LY_STMT_MAX] = "max-elements",
[LY_STMT_MIN] = "min-elements",
[LY_STMT_POSITION] = "position",
[LY_STMT_UNIQUE] = "unique",
[LY_STMT_MODULE] = "module",
[LY_STMT_SUBMODULE] = "submodule",
[LY_STMT_ACTION] = "action",
[LY_STMT_ANYDATA] = "anydata",
[LY_STMT_ANYXML] = "anyxml",
[LY_STMT_CASE] = "case",
[LY_STMT_CHOICE] = "choice",
[LY_STMT_CONTAINER] = "container",
[LY_STMT_GROUPING] = "grouping",
[LY_STMT_INPUT] = "input",
[LY_STMT_LEAF] = "leaf",
[LY_STMT_LEAFLIST] = "leaf-list",
[LY_STMT_LIST] = "list",
[LY_STMT_NOTIFICATION] = "notification",
[LY_STMT_OUTPUT] = "output",
[LY_STMT_RPC] = "rpc",
[LY_STMT_USES] = "uses",
[LY_STMT_TYPEDEF] = "typedef",
[LY_STMT_TYPE] = "type",
[LY_STMT_BIT] = "bit",
[LY_STMT_ENUM] = "enum",
[LY_STMT_REFINE] = "refine",
[LY_STMT_AUGMENT] = "augment",
[LY_STMT_DEVIATE] = "deviate",
[LY_STMT_DEVIATION] = "deviation",
[LY_STMT_EXTENSION] = "extension",
[LY_STMT_FEATURE] = "feature",
[LY_STMT_IDENTITY] = "identity",
[LY_STMT_IFFEATURE] = "if-feature",
[LY_STMT_IMPORT] = "import",
[LY_STMT_INCLUDE] = "include",
[LY_STMT_LENGTH] = "length",
[LY_STMT_MUST] = "must",
[LY_STMT_PATTERN] = "pattern",
[LY_STMT_RANGE] = "range",
[LY_STMT_WHEN] = "when",
[LY_STMT_REVISION] = "revision"
};
int
lyp_is_rpc_action(struct lys_node *node)
{
assert(node);
while (lys_parent(node)) {
node = lys_parent(node);
if (node->nodetype == LYS_ACTION) {
break;
}
}
if (node->nodetype & (LYS_RPC | LYS_ACTION)) {
return 1;
} else {
return 0;
}
}
int
lyp_data_check_options(struct ly_ctx *ctx, int options, const char *func)
{
int x = options & LYD_OPT_TYPEMASK;
/* LYD_OPT_WHENAUTODEL can be used only with LYD_OPT_DATA or LYD_OPT_CONFIG */
if (options & LYD_OPT_WHENAUTODEL) {
if ((x == LYD_OPT_EDIT) || (x == LYD_OPT_NOTIF_FILTER)) {
LOGERR(ctx, LY_EINVAL, "%s: Invalid options 0x%x (LYD_OPT_DATA_WHENAUTODEL can be used only with LYD_OPT_DATA or LYD_OPT_CONFIG)",
func, options);
return 1;
}
}
if (options & (LYD_OPT_DATA_ADD_YANGLIB | LYD_OPT_DATA_NO_YANGLIB)) {
if (x != LYD_OPT_DATA) {
LOGERR(ctx, LY_EINVAL, "%s: Invalid options 0x%x (LYD_OPT_DATA_*_YANGLIB can be used only with LYD_OPT_DATA)",
func, options);
return 1;
}
}
/* "is power of 2" algorithm, with 0 exception */
if (x && !(x && !(x & (x - 1)))) {
LOGERR(ctx, LY_EINVAL, "%s: Invalid options 0x%x (multiple data type flags set).", func, options);
return 1;
}
return 0;
}
int
lyp_mmap(struct ly_ctx *ctx, int fd, size_t addsize, size_t *length, void **addr)
{
struct stat sb;
long pagesize;
size_t m;
assert(fd >= 0);
if (fstat(fd, &sb) == -1) {
LOGERR(ctx, LY_ESYS, "Failed to stat the file descriptor (%s) for the mmap().", strerror(errno));
return 1;
}
if (!S_ISREG(sb.st_mode)) {
LOGERR(ctx, LY_EINVAL, "File to mmap() is not a regular file.");
return 1;
}
if (!sb.st_size) {
*addr = NULL;
return 0;
}
pagesize = sysconf(_SC_PAGESIZE);
++addsize; /* at least one additional byte for terminating NULL byte */
m = sb.st_size % pagesize;
if (m && pagesize - m >= addsize) {
/* there will be enough space after the file content mapping to provide zeroed additional bytes */
*length = sb.st_size + addsize;
*addr = mmap(NULL, *length, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
} else {
/* there will not be enough bytes after the file content mapping for the additional bytes and some of them
* would overflow into another page that would not be zeroed and any access into it would generate SIGBUS.
* Therefore we have to do the following hack with double mapping. First, the required number of bytes
* (including the additional bytes) is required as anonymous and thus they will be really provided (actually more
* because of using whole pages) and also initialized by zeros. Then, the file is mapped to the same address
* where the anonymous mapping starts. */
*length = sb.st_size + pagesize;
*addr = mmap(NULL, *length, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
*addr = mmap(*addr, sb.st_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED, fd, 0);
}
if (*addr == MAP_FAILED) {
LOGERR(ctx, LY_ESYS, "mmap() failed (%s).", strerror(errno));
return 1;
}
return 0;
}
int
lyp_munmap(void *addr, size_t length)
{
return munmap(addr, length);
}
int
lyp_add_ietf_netconf_annotations_config(struct lys_module *mod)
{
void *reallocated;
struct lys_ext_instance_complex *op;
struct lys_type **type;
struct lys_node_anydata *anyxml;
int i;
struct ly_ctx *ctx = mod->ctx; /* shortcut */
reallocated = realloc(mod->ext, (mod->ext_size + 3) * sizeof *mod->ext);
LY_CHECK_ERR_RETURN(!reallocated, LOGMEM(ctx), EXIT_FAILURE);
mod->ext = reallocated;
/* 1) edit-config's operation */
op = calloc(1, (sizeof(struct lys_ext_instance_complex) - 1) + 5 * sizeof(void*) + sizeof(uint16_t));
LY_CHECK_ERR_RETURN(!op, LOGMEM(ctx), EXIT_FAILURE);
mod->ext[mod->ext_size] = (struct lys_ext_instance *)op;
op->arg_value = lydict_insert(ctx, "operation", 9);
op->def = &ctx->models.list[0]->extensions[0];
op->ext_type = LYEXT_COMPLEX;
op->module = op->parent = mod;
op->parent_type = LYEXT_PAR_MODULE;
op->substmt = ((struct lyext_plugin_complex *)op->def->plugin)->substmt;
op->nodetype = LYS_EXT;
type = (struct lys_type**)&op->content; /* type is stored at offset 0 */
*type = calloc(1, sizeof(struct lys_type));
LY_CHECK_ERR_RETURN(!*type, LOGMEM(ctx), EXIT_FAILURE);
(*type)->base = LY_TYPE_ENUM;
(*type)->der = ly_types[LY_TYPE_ENUM];
(*type)->parent = (struct lys_tpdf *)op;
(*type)->info.enums.count = 5;
(*type)->info.enums.enm = calloc(5, sizeof *(*type)->info.enums.enm);
LY_CHECK_ERR_RETURN(!(*type)->info.enums.enm, LOGMEM(ctx), EXIT_FAILURE);
(*type)->info.enums.enm[0].value = 0;
(*type)->info.enums.enm[0].name = lydict_insert(ctx, "merge", 5);
(*type)->info.enums.enm[1].value = 1;
(*type)->info.enums.enm[1].name = lydict_insert(ctx, "replace", 7);
(*type)->info.enums.enm[2].value = 2;
(*type)->info.enums.enm[2].name = lydict_insert(ctx, "create", 6);
(*type)->info.enums.enm[3].value = 3;
(*type)->info.enums.enm[3].name = lydict_insert(ctx, "delete", 6);
(*type)->info.enums.enm[4].value = 4;
(*type)->info.enums.enm[4].name = lydict_insert(ctx, "remove", 6);
mod->ext_size++;
/* 2) filter's type */
op = calloc(1, (sizeof(struct lys_ext_instance_complex) - 1) + 5 * sizeof(void*) + sizeof(uint16_t));
LY_CHECK_ERR_RETURN(!op, LOGMEM(ctx), EXIT_FAILURE);
mod->ext[mod->ext_size] = (struct lys_ext_instance *)op;
op->arg_value = lydict_insert(ctx, "type", 4);
op->def = &ctx->models.list[0]->extensions[0];
op->ext_type = LYEXT_COMPLEX;
op->module = op->parent = mod;
op->parent_type = LYEXT_PAR_MODULE;
op->substmt = ((struct lyext_plugin_complex *)op->def->plugin)->substmt;
op->nodetype = LYS_EXT;
type = (struct lys_type**)&op->content; /* type is stored at offset 0 */
*type = calloc(1, sizeof(struct lys_type));
LY_CHECK_ERR_RETURN(!*type, LOGMEM(ctx), EXIT_FAILURE);
(*type)->base = LY_TYPE_ENUM;
(*type)->der = ly_types[LY_TYPE_ENUM];
(*type)->parent = (struct lys_tpdf *)op;
(*type)->info.enums.count = 2;
(*type)->info.enums.enm = calloc(2, sizeof *(*type)->info.enums.enm);
LY_CHECK_ERR_RETURN(!(*type)->info.enums.enm, LOGMEM(ctx), EXIT_FAILURE);
(*type)->info.enums.enm[0].value = 0;
(*type)->info.enums.enm[0].name = lydict_insert(ctx, "subtree", 7);
(*type)->info.enums.enm[1].value = 1;
(*type)->info.enums.enm[1].name = lydict_insert(ctx, "xpath", 5);
for (i = mod->features_size; i > 0; i--) {
if (!strcmp(mod->features[i - 1].name, "xpath")) {
(*type)->info.enums.enm[1].iffeature_size = 1;
(*type)->info.enums.enm[1].iffeature = calloc(1, sizeof(struct lys_feature));
LY_CHECK_ERR_RETURN(!(*type)->info.enums.enm[1].iffeature, LOGMEM(ctx), EXIT_FAILURE);
(*type)->info.enums.enm[1].iffeature[0].expr = malloc(sizeof(uint8_t));
LY_CHECK_ERR_RETURN(!(*type)->info.enums.enm[1].iffeature[0].expr, LOGMEM(ctx), EXIT_FAILURE);
*(*type)->info.enums.enm[1].iffeature[0].expr = 3; /* LYS_IFF_F */
(*type)->info.enums.enm[1].iffeature[0].features = malloc(sizeof(struct lys_feature*));
LY_CHECK_ERR_RETURN(!(*type)->info.enums.enm[1].iffeature[0].features, LOGMEM(ctx), EXIT_FAILURE);
(*type)->info.enums.enm[1].iffeature[0].features[0] = &mod->features[i - 1];
break;
}
}
mod->ext_size++;
/* 3) filter's select */
op = calloc(1, (sizeof(struct lys_ext_instance_complex) - 1) + 5 * sizeof(void*) + sizeof(uint16_t));
LY_CHECK_ERR_RETURN(!op, LOGMEM(ctx), EXIT_FAILURE);
mod->ext[mod->ext_size] = (struct lys_ext_instance *)op;
op->arg_value = lydict_insert(ctx, "select", 6);
op->def = &ctx->models.list[0]->extensions[0];
op->ext_type = LYEXT_COMPLEX;
op->module = op->parent = mod;
op->parent_type = LYEXT_PAR_MODULE;
op->substmt = ((struct lyext_plugin_complex *)op->def->plugin)->substmt;
op->nodetype = LYS_EXT;
type = (struct lys_type**)&op->content; /* type is stored at offset 0 */
*type = calloc(1, sizeof(struct lys_type));
LY_CHECK_ERR_RETURN(!*type, LOGMEM(ctx), EXIT_FAILURE);
(*type)->base = LY_TYPE_STRING;
(*type)->der = ly_types[LY_TYPE_STRING];
(*type)->parent = (struct lys_tpdf *)op;
mod->ext_size++;
/* 4) URL config */
anyxml = calloc(1, sizeof *anyxml);
LY_CHECK_ERR_RETURN(!anyxml, LOGMEM(ctx), EXIT_FAILURE);
anyxml->nodetype = LYS_ANYXML;
anyxml->prev = (struct lys_node *)anyxml;
anyxml->name = lydict_insert(ctx, "config", 0);
anyxml->module = mod;
anyxml->flags = LYS_CONFIG_W;
if (lys_node_addchild(NULL, mod, (struct lys_node *)anyxml, 0)) {
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
/* logs directly
* base: 0 - to accept decimal, octal, hexadecimal (in default value)
* 10 - to accept only decimal (instance value)
*/
static int
parse_int(const char *val_str, int64_t min, int64_t max, int base, int64_t *ret, struct lyd_node *node)
{
char *strptr;
assert(node);
if (!val_str || !val_str[0]) {
goto error;
}
/* convert to 64-bit integer, all the redundant characters are handled */
errno = 0;
strptr = NULL;
/* parse the value */
*ret = strtoll(val_str, &strptr, base);
if (errno || (*ret < min) || (*ret > max)) {
goto error;
} else if (strptr && *strptr) {
while (isspace(*strptr)) {
++strptr;
}
if (*strptr) {
goto error;
}
}
return EXIT_SUCCESS;
error:
LOGVAL(node->schema->module->ctx, LYE_INVAL, LY_VLOG_LYD, node, val_str ? val_str : "", node->schema->name);
return EXIT_FAILURE;
}
/* logs directly
* base: 0 - to accept decimal, octal, hexadecimal (in default value)
* 10 - to accept only decimal (instance value)
*/
static int
parse_uint(const char *val_str, uint64_t max, int base, uint64_t *ret, struct lyd_node *node)
{
char *strptr;
uint64_t u;
assert(node);
if (!val_str || !val_str[0]) {
goto error;
}
errno = 0;
strptr = NULL;
u = strtoull(val_str, &strptr, base);
if (errno || (u > max)) {
goto error;
} else if (strptr && *strptr) {
while (isspace(*strptr)) {
++strptr;
}
if (*strptr) {
goto error;
}
} else if (u != 0 && val_str[0] == '-') {
goto error;
}
*ret = u;
return EXIT_SUCCESS;
error:
LOGVAL(node->schema->module->ctx, LYE_INVAL, LY_VLOG_LYD, node, val_str ? val_str : "", node->schema->name);
return EXIT_FAILURE;
}
/* logs directly
*
* kind == 0 - unsigned (unum used), 1 - signed (snum used), 2 - floating point (fnum used)
*/
static int
validate_length_range(uint8_t kind, uint64_t unum, int64_t snum, int64_t fnum, uint8_t fnum_dig, struct lys_type *type,
const char *val_str, struct lyd_node *node)
{
struct lys_restr *restr = NULL;
struct len_ran_intv *intv = NULL, *tmp_intv;
struct lys_type *cur_type;
struct ly_ctx *ctx = type->parent->module->ctx;
int match;
if (resolve_len_ran_interval(ctx, NULL, type, &intv)) {
/* already done during schema parsing */
LOGINT(ctx);
return EXIT_FAILURE;
}
if (!intv) {
return EXIT_SUCCESS;
}
/* I know that all intervals belonging to a single restriction share one type pointer */
tmp_intv = intv;
cur_type = intv->type;
do {
match = 0;
for (; tmp_intv && (tmp_intv->type == cur_type); tmp_intv = tmp_intv->next) {
if (match) {
/* just iterate through the rest of this restriction intervals */
continue;
}
if (((kind == 0) && (unum < tmp_intv->value.uval.min))
|| ((kind == 1) && (snum < tmp_intv->value.sval.min))
|| ((kind == 2) && (dec64cmp(fnum, fnum_dig, tmp_intv->value.fval.min, cur_type->info.dec64.dig) < 0))) {
break;
}
if (((kind == 0) && (unum >= tmp_intv->value.uval.min) && (unum <= tmp_intv->value.uval.max))
|| ((kind == 1) && (snum >= tmp_intv->value.sval.min) && (snum <= tmp_intv->value.sval.max))
|| ((kind == 2) && (dec64cmp(fnum, fnum_dig, tmp_intv->value.fval.min, cur_type->info.dec64.dig) > -1)
&& (dec64cmp(fnum, fnum_dig, tmp_intv->value.fval.max, cur_type->info.dec64.dig) < 1))) {
match = 1;
}
}
if (!match) {
break;
} else if (tmp_intv) {
cur_type = tmp_intv->type;
}
} while (tmp_intv);
while (intv) {
tmp_intv = intv->next;
free(intv);
intv = tmp_intv;
}
if (!match) {
switch (cur_type->base) {
case LY_TYPE_BINARY:
restr = cur_type->info.binary.length;
break;
case LY_TYPE_DEC64:
restr = cur_type->info.dec64.range;
break;
case LY_TYPE_INT8:
case LY_TYPE_INT16:
case LY_TYPE_INT32:
case LY_TYPE_INT64:
case LY_TYPE_UINT8:
case LY_TYPE_UINT16:
case LY_TYPE_UINT32:
case LY_TYPE_UINT64:
restr = cur_type->info.num.range;
break;
case LY_TYPE_STRING:
restr = cur_type->info.str.length;
break;
default:
LOGINT(ctx);
return EXIT_FAILURE;
}
LOGVAL(ctx, LYE_NOCONSTR, LY_VLOG_LYD, node, (val_str ? val_str : ""), restr ? restr->expr : "");
if (restr && restr->emsg) {
ly_vlog_str(ctx, LY_VLOG_PREV, restr->emsg);
}
if (restr && restr->eapptag) {
ly_err_last_set_apptag(ctx, restr->eapptag);
}
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
/* logs directly */
static int
validate_pattern(struct ly_ctx *ctx, const char *val_str, struct lys_type *type, struct lyd_node *node)
{
int rc;
unsigned int i;
#ifndef LY_ENABLED_CACHE
pcre *precomp;
#endif
assert(ctx && (type->base == LY_TYPE_STRING));
if (!val_str) {
val_str = "";
}
if (type->der && validate_pattern(ctx, val_str, &type->der->type, node)) {
return EXIT_FAILURE;
}
#ifdef LY_ENABLED_CACHE
/* there is no cache, build it */
if (!type->info.str.patterns_pcre && type->info.str.pat_count) {
type->info.str.patterns_pcre = malloc(2 * type->info.str.pat_count * sizeof *type->info.str.patterns_pcre);
LY_CHECK_ERR_RETURN(!type->info.str.patterns_pcre, LOGMEM(ctx), -1);
for (i = 0; i < type->info.str.pat_count; ++i) {
if (lyp_precompile_pattern(ctx, &type->info.str.patterns[i].expr[1],
(pcre**)&type->info.str.patterns_pcre[i * 2],
(pcre_extra**)&type->info.str.patterns_pcre[i * 2 + 1])) {
return EXIT_FAILURE;
}
}
}
#endif
for (i = 0; i < type->info.str.pat_count; ++i) {
#ifdef LY_ENABLED_CACHE
rc = pcre_exec((pcre *)type->info.str.patterns_pcre[2 * i], (pcre_extra *)type->info.str.patterns_pcre[2 * i + 1],
val_str, strlen(val_str), 0, 0, NULL, 0);
#else
if (lyp_check_pattern(ctx, &type->info.str.patterns[i].expr[1], &precomp)) {
return EXIT_FAILURE;
}
rc = pcre_exec(precomp, NULL, val_str, strlen(val_str), 0, 0, NULL, 0);
free(precomp);
#endif
if ((rc && type->info.str.patterns[i].expr[0] == 0x06) || (!rc && type->info.str.patterns[i].expr[0] == 0x15)) {
LOGVAL(ctx, LYE_NOCONSTR, LY_VLOG_LYD, node, val_str, &type->info.str.patterns[i].expr[1]);
if (type->info.str.patterns[i].emsg) {
ly_vlog_str(ctx, LY_VLOG_PREV, type->info.str.patterns[i].emsg);
}
if (type->info.str.patterns[i].eapptag) {
ly_err_last_set_apptag(ctx, type->info.str.patterns[i].eapptag);
}
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
static void
check_number(const char *str_num, const char **num_end, LY_DATA_TYPE base)
{
if (!isdigit(str_num[0]) && (str_num[0] != '-') && (str_num[0] != '+')) {
*num_end = str_num;
return;
}
if ((str_num[0] == '-') || (str_num[0] == '+')) {
++str_num;
}
while (isdigit(str_num[0])) {
++str_num;
}
if ((base != LY_TYPE_DEC64) || (str_num[0] != '.') || !isdigit(str_num[1])) {
*num_end = str_num;
return;
}
++str_num;
while (isdigit(str_num[0])) {
++str_num;
}
*num_end = str_num;
}
/**
* @brief Checks the syntax of length or range statement,
* on success checks the semantics as well. Does not log.
*
* @param[in] expr Length or range expression.
* @param[in] type Type with the restriction.
*
* @return EXIT_SUCCESS on success, EXIT_FAILURE otherwise.
*/
int
lyp_check_length_range(struct ly_ctx *ctx, const char *expr, struct lys_type *type)
{
struct len_ran_intv *intv = NULL, *tmp_intv;
const char *c = expr, *tail;
int ret = EXIT_FAILURE, flg = 1; /* first run flag */
assert(expr);
lengthpart:
while (isspace(*c)) {
c++;
}
/* lower boundary or explicit number */
if (!strncmp(c, "max", 3)) {
max:
c += 3;
while (isspace(*c)) {
c++;
}
if (*c != '\0') {
goto error;
}
goto syntax_ok;
} else if (!strncmp(c, "min", 3)) {
if (!flg) {
/* min cannot be used elsewhere than in the first length-part */
goto error;
} else {
flg = 0;
}
c += 3;
while (isspace(*c)) {
c++;
}
if (*c == '|') {
c++;
/* process next length-part */
goto lengthpart;
} else if (*c == '\0') {
goto syntax_ok;
} else if (!strncmp(c, "..", 2)) {
upper:
c += 2;
while (isspace(*c)) {
c++;
}
if (*c == '\0') {
goto error;
}
/* upper boundary */
if (!strncmp(c, "max", 3)) {
goto max;
}
check_number(c, &tail, type->base);
if (c == tail) {
goto error;
}
c = tail;
while (isspace(*c)) {
c++;
}
if (*c == '\0') {
goto syntax_ok;
} else if (*c == '|') {
c++;
/* process next length-part */
goto lengthpart;
} else {
goto error;
}
} else {
goto error;
}
} else if (isdigit(*c) || (*c == '-') || (*c == '+')) {
/* number */
check_number(c, &tail, type->base);
if (c == tail) {
goto error;
}
c = tail;
while (isspace(*c)) {
c++;
}
if (*c == '|') {
c++;
/* process next length-part */
goto lengthpart;
} else if (*c == '\0') {
goto syntax_ok;
} else if (!strncmp(c, "..", 2)) {
goto upper;
}
} else {
goto error;
}
syntax_ok:
if (resolve_len_ran_interval(ctx, expr, type, &intv)) {
goto error;
}
ret = EXIT_SUCCESS;
error:
while (intv) {
tmp_intv = intv->next;
free(intv);
intv = tmp_intv;
}
return ret;
}
/**
* @brief Checks pattern syntax. Logs directly.
*
* @param[in] pattern Pattern to check.
* @param[out] pcre_precomp Precompiled PCRE pattern. Can be NULL.
* @return EXIT_SUCCESS on success, EXIT_FAILURE otherwise.
*/
int
lyp_check_pattern(struct ly_ctx *ctx, const char *pattern, pcre **pcre_precomp)
{
int idx, idx2, start, end, err_offset, count;
char *perl_regex, *ptr;
const char *err_msg, *orig_ptr;
pcre *precomp;
/*
* adjust the expression to a Perl equivalent
*
* http://www.w3.org/TR/2004/REC-xmlschema-2-20041028/#regexs
*/
/* we need to replace all "$" with "\$", count them now */
for (count = 0, ptr = strchr(pattern, '$'); ptr; ++count, ptr = strchr(ptr + 1, '$'));
perl_regex = malloc((strlen(pattern) + 4 + count) * sizeof(char));
LY_CHECK_ERR_RETURN(!perl_regex, LOGMEM(ctx), EXIT_FAILURE);
perl_regex[0] = '\0';
ptr = perl_regex;
if (strncmp(pattern + strlen(pattern) - 2, ".*", 2)) {
/* we wil add line-end anchoring */
ptr[0] = '(';
++ptr;
}
for (orig_ptr = pattern; orig_ptr[0]; ++orig_ptr) {
if (orig_ptr[0] == '$') {
ptr += sprintf(ptr, "\\$");
} else {
ptr[0] = orig_ptr[0];
++ptr;
}
}
if (strncmp(pattern + strlen(pattern) - 2, ".*", 2)) {
ptr += sprintf(ptr, ")$");
} else {
ptr[0] = '\0';
++ptr;
}
/* substitute Unicode Character Blocks with exact Character Ranges */
while ((ptr = strstr(perl_regex, "\\p{Is"))) {
start = ptr - perl_regex;
ptr = strchr(ptr, '}');
if (!ptr) {
LOGVAL(ctx, LYE_INREGEX, LY_VLOG_NONE, NULL, pattern, perl_regex + start + 2, "unterminated character property");
free(perl_regex);
return EXIT_FAILURE;
}
end = (ptr - perl_regex) + 1;
/* need more space */
if (end - start < LYP_URANGE_LEN) {
perl_regex = ly_realloc(perl_regex, strlen(perl_regex) + (LYP_URANGE_LEN - (end - start)) + 1);
LY_CHECK_ERR_RETURN(!perl_regex, LOGMEM(ctx); free(perl_regex), EXIT_FAILURE);
}
/* find our range */
for (idx = 0; lyp_ublock2urange[idx][0]; ++idx) {
if (!strncmp(perl_regex + start + 5, lyp_ublock2urange[idx][0], strlen(lyp_ublock2urange[idx][0]))) {
break;
}
}
if (!lyp_ublock2urange[idx][0]) {
LOGVAL(ctx, LYE_INREGEX, LY_VLOG_NONE, NULL, pattern, perl_regex + start + 5, "unknown block name");
free(perl_regex);
return EXIT_FAILURE;
}
/* make the space in the string and replace the block (but we cannot include brackets if it was already enclosed in them) */
for (idx2 = 0, count = 0; idx2 < start; ++idx2) {
if ((perl_regex[idx2] == '[') && (!idx2 || (perl_regex[idx2 - 1] != '\\'))) {
++count;
}
if ((perl_regex[idx2] == ']') && (!idx2 || (perl_regex[idx2 - 1] != '\\'))) {
--count;
}
}
if (count) {
/* skip brackets */
memmove(perl_regex + start + (LYP_URANGE_LEN - 2), perl_regex + end, strlen(perl_regex + end) + 1);
memcpy(perl_regex + start, lyp_ublock2urange[idx][1] + 1, LYP_URANGE_LEN - 2);
} else {
memmove(perl_regex + start + LYP_URANGE_LEN, perl_regex + end, strlen(perl_regex + end) + 1);
memcpy(perl_regex + start, lyp_ublock2urange[idx][1], LYP_URANGE_LEN);
}
}
/* must return 0, already checked during parsing */
precomp = pcre_compile(perl_regex, PCRE_ANCHORED | PCRE_DOLLAR_ENDONLY | PCRE_NO_AUTO_CAPTURE,
&err_msg, &err_offset, NULL);
if (!precomp) {
LOGVAL(ctx, LYE_INREGEX, LY_VLOG_NONE, NULL, pattern, perl_regex + err_offset, err_msg);
free(perl_regex);
return EXIT_FAILURE;
}
free(perl_regex);
if (pcre_precomp) {
*pcre_precomp = precomp;
} else {
free(precomp);
}
return EXIT_SUCCESS;
}
int
lyp_precompile_pattern(struct ly_ctx *ctx, const char *pattern, pcre** pcre_cmp, pcre_extra **pcre_std)
{
const char *err_msg = NULL;
if (lyp_check_pattern(ctx, pattern, pcre_cmp)) {
return EXIT_FAILURE;
}
if (pcre_std && pcre_cmp) {
(*pcre_std) = pcre_study(*pcre_cmp, 0, &err_msg);
if (err_msg) {
LOGWRN(ctx, "Studying pattern \"%s\" failed (%s).", pattern, err_msg);
}
}
return EXIT_SUCCESS;
}
/**
* @brief Change the value into its canonical form. In libyang, additionally to the RFC,
* all identities have their module as a prefix in their canonical form.
*
* @param[in] ctx
* @param[in] type Type of the value.
* @param[in,out] value Original and then canonical value.
* @param[in] data1 If \p type is #LY_TYPE_BITS: (struct lys_type_bit **) type bit field,
* #LY_TYPE_DEC64: (int64_t *) parsed digits of the number itself without floating point,
* #LY_TYPE_IDENT: (const char *) local module name (identityref node module),
* #LY_TYPE_INT*: (int64_t *) parsed int number itself,
* #LY_TYPE_UINT*: (uint64_t *) parsed uint number itself,
* otherwise ignored.
* @param[in] data2 If \p type is #LY_TYPE_BITS: (int *) type bit field length,
* #LY_TYPE_DEC64: (uint8_t *) number of fraction digits (position of the floating point),
* otherwise ignored.
* @return 1 if a conversion took place, 0 if the value was kept the same, -1 on error.
*/
static int
make_canonical(struct ly_ctx *ctx, int type, const char **value, void *data1, void *data2)
{
const uint16_t buf_len = 511;
char buf[buf_len + 1];
struct lys_type_bit **bits = NULL;
struct lyxp_expr *exp;
const char *module_name, *cur_expr, *end;
int i, j, count;
int64_t num;
uint64_t unum;
uint8_t c;
#define LOGBUF(str) LOGERR(ctx, LY_EINVAL, "Value \"%s\" is too long.", str)
switch (type) {
case LY_TYPE_BITS:
bits = (struct lys_type_bit **)data1;
count = *((int *)data2);
/* in canonical form, the bits are ordered by their position */
buf[0] = '\0';
for (i = 0; i < count; i++) {
if (!bits[i]) {
/* bit not set */
continue;
}
if (buf[0]) {
LY_CHECK_ERR_RETURN(strlen(buf) + 1 + strlen(bits[i]->name) > buf_len, LOGBUF(bits[i]->name), -1);
sprintf(buf + strlen(buf), " %s", bits[i]->name);
} else {
LY_CHECK_ERR_RETURN(strlen(bits[i]->name) > buf_len, LOGBUF(bits[i]->name), -1);
strcpy(buf, bits[i]->name);
}
}
break;
case LY_TYPE_IDENT:
module_name = (const char *)data1;
/* identity must always have a prefix */
if (!strchr(*value, ':')) {
LY_CHECK_ERR_RETURN(strlen(module_name) + 1 + strlen(*value) > buf_len, LOGBUF(*value), -1);
sprintf(buf, "%s:%s", module_name, *value);
} else {
LY_CHECK_ERR_RETURN(strlen(*value) > buf_len, LOGBUF(*value), -1);
strcpy(buf, *value);
}
break;
case LY_TYPE_INST:
exp = lyxp_parse_expr(ctx, *value);
LY_CHECK_ERR_RETURN(!exp, LOGINT(ctx), -1);
module_name = NULL;
count = 0;
for (i = 0; (unsigned)i < exp->used; ++i) {
cur_expr = &exp->expr[exp->expr_pos[i]];
/* copy WS */
if (i && ((end = exp->expr + exp->expr_pos[i - 1] + exp->tok_len[i - 1]) != cur_expr)) {
if (count + (cur_expr - end) > buf_len) {
lyxp_expr_free(exp);
LOGBUF(end);
return -1;
}
strncpy(&buf[count], end, cur_expr - end);
count += cur_expr - end;
}
if ((exp->tokens[i] == LYXP_TOKEN_NAMETEST) && (end = strnchr(cur_expr, ':', exp->tok_len[i]))) {
/* get the module name with ":" */
++end;
j = end - cur_expr;
if (!module_name || strncmp(cur_expr, module_name, j)) {
/* print module name with colon, it does not equal to the parent one */
if (count + j > buf_len) {
lyxp_expr_free(exp);
LOGBUF(cur_expr);
return -1;
}
strncpy(&buf[count], cur_expr, j);
count += j;
}
module_name = cur_expr;
/* copy the rest */
if (count + (exp->tok_len[i] - j) > buf_len) {
lyxp_expr_free(exp);
LOGBUF(end);
return -1;
}
strncpy(&buf[count], end, exp->tok_len[i] - j);
count += exp->tok_len[i] - j;
} else {
if (count + exp->tok_len[i] > buf_len) {
lyxp_expr_free(exp);
LOGBUF(&exp->expr[exp->expr_pos[i]]);
return -1;
}
strncpy(&buf[count], &exp->expr[exp->expr_pos[i]], exp->tok_len[i]);
count += exp->tok_len[i];
}
}
if (count > buf_len) {
LOGINT(ctx);
lyxp_expr_free(exp);
return -1;
}
buf[count] = '\0';
lyxp_expr_free(exp);
break;
case LY_TYPE_DEC64:
num = *((int64_t *)data1);
c = *((uint8_t *)data2);
if (num) {
count = sprintf(buf, "%"PRId64" ", num);
if ( (num > 0 && (count - 1) <= c)
|| (count - 2) <= c ) {
/* we have 0. value, print the value with the leading zeros
* (one for 0. and also keep the correct with of num according
* to fraction-digits value)
* for (num<0) - extra character for '-' sign */
count = sprintf(buf, "%0*"PRId64" ", (num > 0) ? (c + 1) : (c + 2), num);
}
for (i = c, j = 1; i > 0 ; i--) {
if (j && i > 1 && buf[count - 2] == '0') {
/* we have trailing zero to skip */
buf[count - 1] = '\0';
} else {
j = 0;
buf[count - 1] = buf[count - 2];
}
count--;
}
buf[count - 1] = '.';
} else {
/* zero */
sprintf(buf, "0.0");
}
break;
case LY_TYPE_INT8:
case LY_TYPE_INT16:
case LY_TYPE_INT32:
case LY_TYPE_INT64:
num = *((int64_t *)data1);
sprintf(buf, "%"PRId64, num);
break;
case LY_TYPE_UINT8:
case LY_TYPE_UINT16:
case LY_TYPE_UINT32:
case LY_TYPE_UINT64:
unum = *((uint64_t *)data1);
sprintf(buf, "%"PRIu64, unum);
break;
default:
/* should not be even called - just do nothing */
return 0;
}
if (strcmp(buf, *value)) {
lydict_remove(ctx, *value);
*value = lydict_insert(ctx, buf, 0);
return 1;
}
return 0;
#undef LOGBUF
}
static const char *
ident_val_add_module_prefix(const char *value, const struct lyxml_elem *xml, struct ly_ctx *ctx)
{
const struct lyxml_ns *ns;
const struct lys_module *mod;
char *str;
do {
LY_TREE_FOR((struct lyxml_ns *)xml->attr, ns) {
if ((ns->type == LYXML_ATTR_NS) && !ns->prefix) {
/* match */
break;
}
}
if (!ns) {
xml = xml->parent;
}
} while (!ns && xml);
if (!ns) {
/* no default namespace */
LOGINT(ctx);
return NULL;
}
/* find module */
mod = ly_ctx_get_module_by_ns(ctx, ns->value, NULL, 1);
if (!mod) {
LOGINT(ctx);
return NULL;
}
if (asprintf(&str, "%s:%s", mod->name, value) == -1) {
LOGMEM(ctx);
return NULL;
}
lydict_remove(ctx, value);
return lydict_insert_zc(ctx, str);
}
/*
* xml - optional for converting instance-identifier and identityref into JSON format
* leaf - mandatory to know the context (necessary e.g. for prefixes in idenitytref values)
* attr - alternative to leaf in case of parsing value in annotations (attributes)
* local_mod - optional if the local module dos not match the module of leaf/attr
* store - flag for union resolution - we do not want to store the result, we are just learning the type
* dflt - whether the value is a default value from the schema
* trusted - whether the value is trusted to be valid (but may not be canonical, so it is canonized)
*/
struct lys_type *
lyp_parse_value(struct lys_type *type, const char **value_, struct lyxml_elem *xml,
struct lyd_node_leaf_list *leaf, struct lyd_attr *attr, struct lys_module *local_mod,
int store, int dflt, int trusted)
{
struct lys_type *ret = NULL, *t;
struct lys_tpdf *tpdf;
enum int_log_opts prev_ilo;
int c, len, found = 0;
unsigned int i, j;
int64_t num;
uint64_t unum, uind, u = 0;
const char *ptr, *value = *value_, *itemname, *old_val_str = NULL;
struct lys_type_bit **bits = NULL;
struct lys_ident *ident;
lyd_val *val, old_val;
LY_DATA_TYPE *val_type, old_val_type;
uint8_t *val_flags, old_val_flags;
struct lyd_node *contextnode;
struct ly_ctx *ctx = type->parent->module->ctx;
assert(leaf || attr);
if (leaf) {
assert(!attr);
if (!local_mod) {
local_mod = leaf->schema->module;
}
val = &leaf->value;
val_type = &leaf->value_type;
val_flags = &leaf->value_flags;
contextnode = (struct lyd_node *)leaf;
itemname = leaf->schema->name;
} else {
assert(!leaf);
if (!local_mod) {
local_mod = attr->annotation->module;
}
val = &attr->value;
val_type = &attr->value_type;
val_flags = &attr->value_flags;
contextnode = attr->parent;
itemname = attr->name;
}
/* fully clear the value */
if (store) {
old_val_str = lydict_insert(ctx, *value_, 0);
lyd_free_value(*val, *val_type, *val_flags, type, old_val_str, &old_val, &old_val_type, &old_val_flags);
*val_flags &= ~LY_VALUE_UNRES;
}
switch (type->base) {
case LY_TYPE_BINARY:
/* get number of octets for length validation */
unum = 0;
ptr = NULL;
if (value) {
/* silently skip leading/trailing whitespaces */
for (uind = 0; isspace(value[uind]); ++uind);
ptr = &value[uind];
u = strlen(ptr);
while (u && isspace(ptr[u - 1])) {
--u;
}
unum = u;
for (uind = 0; uind < u; ++uind) {
if (ptr[uind] == '\n') {
unum--;
} else if ((ptr[uind] < '/' && ptr[uind] != '+') ||
(ptr[uind] > '9' && ptr[uind] < 'A') ||
(ptr[uind] > 'Z' && ptr[uind] < 'a') || ptr[uind] > 'z') {
if (ptr[uind] == '=') {
/* padding */
if (uind == u - 2 && ptr[uind + 1] == '=') {
found = 2;
uind++;
} else if (uind == u - 1) {
found = 1;
}
}
if (!found) {
/* error */
LOGVAL(ctx, LYE_INCHAR, LY_VLOG_LYD, contextnode, ptr[uind], &ptr[uind]);
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Invalid Base64 character.");
goto error;
}
}
}
}
if (unum & 3) {
/* base64 length must be multiple of 4 chars */
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value);
}
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Base64 encoded value length must be divisible by 4.");
goto error;
}
/* length of the encoded string */
len = ((unum / 4) * 3) - found;
if (!trusted && validate_length_range(0, len, 0, 0, 0, type, value, contextnode)) {
goto error;
}
if (value && (ptr != value || ptr[u] != '\0')) {
/* update the changed value */
ptr = lydict_insert(ctx, ptr, u);
lydict_remove(ctx, *value_);
*value_ = ptr;
}
if (store) {
/* store the result */
val->binary = value;
*val_type = LY_TYPE_BINARY;
}
break;
case LY_TYPE_BITS:
/* locate bits structure with the bits definitions
* since YANG 1.1 allows restricted bits, it is the first
* bits type with some explicit bit specification */
for (; !type->info.bits.count; type = &type->der->type);
if (value || store) {
/* allocate the array of pointers to bits definition */
bits = calloc(type->info.bits.count, sizeof *bits);
LY_CHECK_ERR_GOTO(!bits, LOGMEM(ctx), error);
}
if (!value) {
/* no bits set */
if (store) {
/* store empty array */
val->bit = bits;
*val_type = LY_TYPE_BITS;
}
break;
}
c = 0;
i = 0;
while (value[c]) {
/* skip leading whitespaces */
while (isspace(value[c])) {
c++;
}
if (!value[c]) {
/* trailing white spaces */
break;
}
/* get the length of the bit identifier */
for (len = 0; value[c] && !isspace(value[c]); c++, len++);
/* go back to the beginning of the identifier */
c = c - len;
/* find bit definition, identifiers appear ordered by their position */
for (found = i = 0; i < type->info.bits.count; i++) {
if (!strncmp(type->info.bits.bit[i].name, &value[c], len) && !type->info.bits.bit[i].name[len]) {
/* we have match, check if the value is enabled ... */
for (j = 0; !trusted && (j < type->info.bits.bit[i].iffeature_size); j++) {
if (!resolve_iffeature(&type->info.bits.bit[i].iffeature[j])) {
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value);
}
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL,
"Bit \"%s\" is disabled by its %d. if-feature condition.",
type->info.bits.bit[i].name, j + 1);
free(bits);
goto error;
}
}
/* check that the value was not already set */
if (bits[i]) {
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value);
}
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Bit \"%s\" used multiple times.",
type->info.bits.bit[i].name);
free(bits);
goto error;
}
/* ... and then store the pointer */
bits[i] = &type->info.bits.bit[i];
/* stop searching */
found = 1;
break;
}
}
if (!found) {
/* referenced bit value does not exist */
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value);
}
free(bits);
goto error;
}
c = c + len;
}
if (make_canonical(ctx, LY_TYPE_BITS, value_, bits, &type->info.bits.count) == -1) {
free(bits);
goto error;
}
if (store) {
/* store the result */
val->bit = bits;
*val_type = LY_TYPE_BITS;
} else {
free(bits);
}
break;
case LY_TYPE_BOOL:
if (value && !strcmp(value, "true")) {
if (store) {
val->bln = 1;
}
} else if (!value || strcmp(value, "false")) {
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value ? value : "", itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value ? value : "");
}
goto error;
} else {
if (store) {
val->bln = 0;
}
}
if (store) {
*val_type = LY_TYPE_BOOL;
}
break;
case LY_TYPE_DEC64:
if (!value || !value[0]) {
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, "", itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, "");
}
goto error;
}
ptr = value;
if (parse_range_dec64(&ptr, type->info.dec64.dig, &num) || ptr[0]) {
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value);
}
goto error;
}
if (!trusted && validate_length_range(2, 0, 0, num, type->info.dec64.dig, type, value, contextnode)) {
goto error;
}
if (make_canonical(ctx, LY_TYPE_DEC64, value_, &num, &type->info.dec64.dig) == -1) {
goto error;
}
if (store) {
/* store the result */
val->dec64 = num;
*val_type = LY_TYPE_DEC64;
}
break;
case LY_TYPE_EMPTY:
if (value && value[0]) {
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value);
}
goto error;
}
if (store) {
*val_type = LY_TYPE_EMPTY;
}
break;
case LY_TYPE_ENUM:
/* locate enums structure with the enumeration definitions,
* since YANG 1.1 allows restricted enums, it is the first
* enum type with some explicit enum specification */
for (; !type->info.enums.count; type = &type->der->type);
/* find matching enumeration value */
for (i = found = 0; i < type->info.enums.count; i++) {
if (value && !strcmp(value, type->info.enums.enm[i].name)) {
/* we have match, check if the value is enabled ... */
for (j = 0; !trusted && (j < type->info.enums.enm[i].iffeature_size); j++) {
if (!resolve_iffeature(&type->info.enums.enm[i].iffeature[j])) {
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value);
}
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Enum \"%s\" is disabled by its %d. if-feature condition.",
value, j + 1);
goto error;
}
}
/* ... and store pointer to the definition */
if (store) {
val->enm = &type->info.enums.enm[i];
*val_type = LY_TYPE_ENUM;
}
found = 1;
break;
}
}
if (!found) {
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value ? value : "", itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value ? value : "");
}
goto error;
}
break;
case LY_TYPE_IDENT:
if (!value) {
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, "", itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, "");
}
goto error;
}
if (xml) {
ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL);
/* first, convert value into the json format, silently */
value = transform_xml2json(ctx, value, xml, 0, 0);
ly_ilo_restore(NULL, prev_ilo, NULL, 0);
if (!value) {
/* invalid identityref format */
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, *value_, itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, *value_);
}
goto error;
}
/* the value has no prefix (default namespace), but the element's namespace has a prefix, find default namespace */
if (!strchr(value, ':') && xml->ns->prefix) {
value = ident_val_add_module_prefix(value, xml, ctx);
if (!value) {
goto error;
}
}
} else if (dflt) {
ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL);
/* the value actually uses module's prefixes instead of the module names as in JSON format,
* we have to convert it */
value = transform_schema2json(local_mod, value);
ly_ilo_restore(NULL, prev_ilo, NULL, 0);
if (!value) {
/* invalid identityref format or it was already transformed, so ignore the error here */
value = lydict_insert(ctx, *value_, 0);
}
} else {
value = lydict_insert(ctx, *value_, 0);
}
/* value is now in the dictionary, whether it differs from *value_ or not */
ident = resolve_identref(type, value, contextnode, local_mod, dflt);
if (!ident) {
lydict_remove(ctx, value);
goto error;
} else if (store) {
/* store the result */
val->ident = ident;
*val_type = LY_TYPE_IDENT;
}
/* the value is always changed and includes prefix */
if (dflt) {
type->parent->flags |= LYS_DFLTJSON;
}
if (make_canonical(ctx, LY_TYPE_IDENT, &value, (void*)lys_main_module(local_mod)->name, NULL) == -1) {
lydict_remove(ctx, value);
goto error;
}
/* replace the old value with the new one (even if they may be the same) */
lydict_remove(ctx, *value_);
*value_ = value;
break;
case LY_TYPE_INST:
if (!value) {
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, "", itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, "");
}
goto error;
}
if (xml) {
ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL);
/* first, convert value into the json format, silently */
value = transform_xml2json(ctx, value, xml, 1, 1);
ly_ilo_restore(NULL, prev_ilo, NULL, 0);
if (!value) {
/* invalid instance-identifier format */
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, *value_, itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, *value_);
}
goto error;
} else if (ly_strequal(value, *value_, 1)) {
/* we have actually created the same expression (prefixes are the same as the module names)
* so we have just increased dictionary's refcount - fix it */
lydict_remove(ctx, value);
}
} else if (dflt) {
/* turn logging off */
ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL);
/* the value actually uses module's prefixes instead of the module names as in JSON format,
* we have to convert it */
value = transform_schema2json(local_mod, value);
if (!value) {
/* invalid identityref format or it was already transformed, so ignore the error here */
value = *value_;
} else if (ly_strequal(value, *value_, 1)) {
/* we have actually created the same expression (prefixes are the same as the module names)
* so we have just increased dictionary's refcount - fix it */
lydict_remove(ctx, value);
}
/* turn logging back on */
ly_ilo_restore(NULL, prev_ilo, NULL, 0);
} else {
if ((c = make_canonical(ctx, LY_TYPE_INST, &value, NULL, NULL))) {
if (c == -1) {
goto error;
}
/* if a change occurred, value was removed from the dictionary so fix the pointers */
*value_ = value;
}
}
if (store) {
/* note that the data node is an unresolved instance-identifier */
val->instance = NULL;
*val_type = LY_TYPE_INST;
*val_flags |= LY_VALUE_UNRES;
}
if (!ly_strequal(value, *value_, 1)) {
/* update the changed value */
lydict_remove(ctx, *value_);
*value_ = value;
/* we have to remember the conversion into JSON format to be able to print it in correct form */
if (dflt) {
type->parent->flags |= LYS_DFLTJSON;
}
}
break;
case LY_TYPE_LEAFREF:
if (!value) {
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, "", itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, "");
}
goto error;
}
/* it is called not only to get the final type, but mainly to update value to canonical or JSON form
* if needed */
t = lyp_parse_value(&type->info.lref.target->type, value_, xml, leaf, attr, NULL, store, dflt, trusted);
value = *value_; /* refresh possibly changed value */
if (!t) {
/* already logged */
goto error;
}
if (store) {
/* make the note that the data node is an unresolved leafref (value union was already filled) */
*val_flags |= LY_VALUE_UNRES;
}
type = t;
break;
case LY_TYPE_STRING:
if (!trusted && validate_length_range(0, (value ? ly_strlen_utf8(value) : 0), 0, 0, 0, type, value, contextnode)) {
goto error;
}
if (!trusted && validate_pattern(ctx, value, type, contextnode)) {
goto error;
}
/* special handling of ietf-yang-types xpath1.0 */
for (tpdf = type->der;
tpdf->module && (strcmp(tpdf->name, "xpath1.0") || strcmp(tpdf->module->name, "ietf-yang-types"));
tpdf = tpdf->type.der);
if (tpdf->module && xml) {
/* convert value into the json format */
value = transform_xml2json(ctx, value ? value : "", xml, 1, 1);
if (!value) {
/* invalid instance-identifier format */
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, *value_, itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, *value_);
}
goto error;
}
if (!ly_strequal(value, *value_, 1)) {
/* update the changed value */
lydict_remove(ctx, *value_);
*value_ = value;
}
}
if (store) {
/* store the result */
val->string = value;
*val_type = LY_TYPE_STRING;
}
break;
case LY_TYPE_INT8:
if (parse_int(value, __INT64_C(-128), __INT64_C(127), dflt ? 0 : 10, &num, contextnode)
|| (!trusted && validate_length_range(1, 0, num, 0, 0, type, value, contextnode))) {
goto error;
}
if (make_canonical(ctx, LY_TYPE_INT8, value_, &num, NULL) == -1) {
goto error;
}
if (store) {
/* store the result */
val->int8 = (int8_t)num;
*val_type = LY_TYPE_INT8;
}
break;
case LY_TYPE_INT16:
if (parse_int(value, __INT64_C(-32768), __INT64_C(32767), dflt ? 0 : 10, &num, contextnode)
|| (!trusted && validate_length_range(1, 0, num, 0, 0, type, value, contextnode))) {
goto error;
}
if (make_canonical(ctx, LY_TYPE_INT16, value_, &num, NULL) == -1) {
goto error;
}
if (store) {
/* store the result */
val->int16 = (int16_t)num;
*val_type = LY_TYPE_INT16;
}
break;
case LY_TYPE_INT32:
if (parse_int(value, __INT64_C(-2147483648), __INT64_C(2147483647), dflt ? 0 : 10, &num, contextnode)
|| (!trusted && validate_length_range(1, 0, num, 0, 0, type, value, contextnode))) {
goto error;
}
if (make_canonical(ctx, LY_TYPE_INT32, value_, &num, NULL) == -1) {
goto error;
}
if (store) {
/* store the result */
val->int32 = (int32_t)num;
*val_type = LY_TYPE_INT32;
}
break;
case LY_TYPE_INT64:
if (parse_int(value, __INT64_C(-9223372036854775807) - __INT64_C(1), __INT64_C(9223372036854775807),
dflt ? 0 : 10, &num, contextnode)
|| (!trusted && validate_length_range(1, 0, num, 0, 0, type, value, contextnode))) {
goto error;
}
if (make_canonical(ctx, LY_TYPE_INT64, value_, &num, NULL) == -1) {
goto error;
}
if (store) {
/* store the result */
val->int64 = num;
*val_type = LY_TYPE_INT64;
}
break;
case LY_TYPE_UINT8:
if (parse_uint(value, __UINT64_C(255), dflt ? 0 : 10, &unum, contextnode)
|| (!trusted && validate_length_range(0, unum, 0, 0, 0, type, value, contextnode))) {
goto error;
}
if (make_canonical(ctx, LY_TYPE_UINT8, value_, &unum, NULL) == -1) {
goto error;
}
if (store) {
/* store the result */
val->uint8 = (uint8_t)unum;
*val_type = LY_TYPE_UINT8;
}
break;
case LY_TYPE_UINT16:
if (parse_uint(value, __UINT64_C(65535), dflt ? 0 : 10, &unum, contextnode)
|| (!trusted && validate_length_range(0, unum, 0, 0, 0, type, value, contextnode))) {
goto error;
}
if (make_canonical(ctx, LY_TYPE_UINT16, value_, &unum, NULL) == -1) {
goto error;
}
if (store) {
/* store the result */
val->uint16 = (uint16_t)unum;
*val_type = LY_TYPE_UINT16;
}
break;
case LY_TYPE_UINT32:
if (parse_uint(value, __UINT64_C(4294967295), dflt ? 0 : 10, &unum, contextnode)
|| (!trusted && validate_length_range(0, unum, 0, 0, 0, type, value, contextnode))) {
goto error;
}
if (make_canonical(ctx, LY_TYPE_UINT32, value_, &unum, NULL) == -1) {
goto error;
}
if (store) {
/* store the result */
val->uint32 = (uint32_t)unum;
*val_type = LY_TYPE_UINT32;
}
break;
case LY_TYPE_UINT64:
if (parse_uint(value, __UINT64_C(18446744073709551615), dflt ? 0 : 10, &unum, contextnode)
|| (!trusted && validate_length_range(0, unum, 0, 0, 0, type, value, contextnode))) {
goto error;
}
if (make_canonical(ctx, LY_TYPE_UINT64, value_, &unum, NULL) == -1) {
goto error;
}
if (store) {
/* store the result */
val->uint64 = unum;
*val_type = LY_TYPE_UINT64;
}
break;
case LY_TYPE_UNION:
if (store) {
/* unresolved union type */
memset(val, 0, sizeof(lyd_val));
*val_type = LY_TYPE_UNION;
}
if (type->info.uni.has_ptr_type) {
/* we are not resolving anything here, only parsing, and in this case we cannot decide
* the type without resolving it -> we return the union type (resolve it with resolve_union()) */
if (xml) {
/* in case it should resolve into a instance-identifier, we can only do the JSON conversion here */
ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL);
val->string = transform_xml2json(ctx, value, xml, 1, 1);
ly_ilo_restore(NULL, prev_ilo, NULL, 0);
if (!val->string) {
/* invalid instance-identifier format, likely some other type */
val->string = lydict_insert(ctx, value, 0);
}
}
break;
}
t = NULL;
found = 0;
/* turn logging off, we are going to try to validate the value with all the types in order */
ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL);
while ((t = lyp_get_next_union_type(type, t, &found))) {
found = 0;
ret = lyp_parse_value(t, value_, xml, leaf, attr, NULL, store, dflt, 0);
if (ret) {
/* we have the result */
type = ret;
break;
}
if (store) {
/* erase possible present and invalid value data */
lyd_free_value(*val, *val_type, *val_flags, t, *value_, NULL, NULL, NULL);
memset(val, 0, sizeof(lyd_val));
}
}
/* turn logging back on */
ly_ilo_restore(NULL, prev_ilo, NULL, 0);
if (!t) {
/* not found */
if (store) {
*val_type = 0;
}
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, *value_ ? *value_ : "", itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, *value_);
}
goto error;
}
break;
default:
LOGINT(ctx);
goto error;
}
/* search user types in case this value is supposed to be stored in a custom way */
if (store && type->der && type->der->module) {
c = lytype_store(type->der->module, type->der->name, value_, val);
if (c == -1) {
goto error;
} else if (!c) {
*val_flags |= LY_VALUE_USER;
}
}
/* free backup */
if (store) {
lyd_free_value(old_val, old_val_type, old_val_flags, type, old_val_str, NULL, NULL, NULL);
lydict_remove(ctx, old_val_str);
}
return type;
error:
/* restore the backup */
if (store) {
*val = old_val;
*val_type = old_val_type;
*val_flags = old_val_flags;
lydict_remove(ctx, old_val_str);
}
return NULL;
}
/* does not log, cannot fail */
struct lys_type *
lyp_get_next_union_type(struct lys_type *type, struct lys_type *prev_type, int *found)
{
unsigned int i;
struct lys_type *ret = NULL;
while (!type->info.uni.count) {
assert(type->der); /* at least the direct union type has to have type specified */
type = &type->der->type;
}
for (i = 0; i < type->info.uni.count; ++i) {
if (type->info.uni.types[i].base == LY_TYPE_UNION) {
ret = lyp_get_next_union_type(&type->info.uni.types[i], prev_type, found);
if (ret) {
break;
}
continue;
}
if (!prev_type || *found) {
ret = &type->info.uni.types[i];
break;
}
if (&type->info.uni.types[i] == prev_type) {
*found = 1;
}
}
return ret;
}
/* ret 0 - ret set, ret 1 - ret not set, no log, ret -1 - ret not set, fatal error */
int
lyp_fill_attr(struct ly_ctx *ctx, struct lyd_node *parent, const char *module_ns, const char *module_name,
const char *attr_name, const char *attr_value, struct lyxml_elem *xml, int options, struct lyd_attr **ret)
{
const struct lys_module *mod = NULL;
const struct lys_submodule *submod = NULL;
struct lys_type **type;
struct lyd_attr *dattr;
int pos, i, j, k;
/* first, get module where the annotation should be defined */
if (module_ns) {
mod = (struct lys_module *)ly_ctx_get_module_by_ns(ctx, module_ns, NULL, 0);
} else if (module_name) {
mod = (struct lys_module *)ly_ctx_get_module(ctx, module_name, NULL, 0);
} else {
LOGINT(ctx);
return -1;
}
if (!mod) {
return 1;
}
/* then, find the appropriate annotation definition */
pos = -1;
for (i = 0, j = 0; i < mod->ext_size; i = i + j + 1) {
j = lys_ext_instance_presence(&ctx->models.list[0]->extensions[0], &mod->ext[i], mod->ext_size - i);
if (j == -1) {
break;
}
if (ly_strequal(mod->ext[i + j]->arg_value, attr_name, 0)) {
pos = i + j;
break;
}
}
/* try submodules */
if (pos == -1) {
for (k = 0; k < mod->inc_size; ++k) {
submod = mod->inc[k].submodule;
for (i = 0, j = 0; i < submod->ext_size; i = i + j + 1) {
j = lys_ext_instance_presence(&ctx->models.list[0]->extensions[0], &submod->ext[i], submod->ext_size - i);
if (j == -1) {
break;
}
if (ly_strequal(submod->ext[i + j]->arg_value, attr_name, 0)) {
pos = i + j;
break;
}
}
}
}
if (pos == -1) {
return 1;
}
/* allocate and fill the data attribute structure */
dattr = calloc(1, sizeof *dattr);
LY_CHECK_ERR_RETURN(!dattr, LOGMEM(ctx), -1);
dattr->parent = parent;
dattr->next = NULL;
dattr->annotation = submod ? (struct lys_ext_instance_complex *)submod->ext[pos] :
(struct lys_ext_instance_complex *)mod->ext[pos];
dattr->name = lydict_insert(ctx, attr_name, 0);
dattr->value_str = lydict_insert(ctx, attr_value, 0);
/* the value is here converted to a JSON format if needed in case of LY_TYPE_IDENT and LY_TYPE_INST or to a
* canonical form of the value */
type = lys_ext_complex_get_substmt(LY_STMT_TYPE, dattr->annotation, NULL);
if (!type || !lyp_parse_value(*type, &dattr->value_str, xml, NULL, dattr, NULL, 1, 0, options & LYD_OPT_TRUSTED)) {
lydict_remove(ctx, dattr->name);
lydict_remove(ctx, dattr->value_str);
free(dattr);
return -1;
}
*ret = dattr;
return 0;
}
int
lyp_check_edit_attr(struct ly_ctx *ctx, struct lyd_attr *attr, struct lyd_node *parent, int *editbits)
{
struct lyd_attr *last = NULL;
int bits = 0;
/* 0x01 - insert attribute present
* 0x02 - insert is relative (before or after)
* 0x04 - value attribute present
* 0x08 - key attribute present
* 0x10 - operation attribute present
* 0x20 - operation not allowing insert attribute (delete or remove)
*/
LY_TREE_FOR(attr, attr) {
last = NULL;
if (!strcmp(attr->annotation->arg_value, "operation") &&
!strcmp(attr->annotation->module->name, "ietf-netconf")) {
if (bits & 0x10) {
LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYD, parent, "operation attributes", parent->schema->name);
return -1;
}
bits |= 0x10;
if (attr->value.enm->value >= 3) {
/* delete or remove */
bits |= 0x20;
}
} else if (attr->annotation->module == ctx->models.list[1] && /* internal YANG schema */
!strcmp(attr->annotation->arg_value, "insert")) {
/* 'insert' attribute present */
if (!(parent->schema->flags & LYS_USERORDERED)) {
/* ... but it is not expected */
LOGVAL(ctx, LYE_INATTR, LY_VLOG_LYD, parent, "insert");
return -1;
}
if (bits & 0x01) {
LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYD, parent, "insert attributes", parent->schema->name);
return -1;
}
bits |= 0x01;
if (attr->value.enm->value >= 2) {
/* before or after */
bits |= 0x02;
}
last = attr;
} else if (attr->annotation->module == ctx->models.list[1] && /* internal YANG schema */
!strcmp(attr->annotation->arg_value, "value")) {
if (bits & 0x04) {
LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYD, parent, "value attributes", parent->schema->name);
return -1;
} else if (parent->schema->nodetype & LYS_LIST) {
LOGVAL(ctx, LYE_INATTR, LY_VLOG_LYD, parent, attr->name);
return -1;
}
bits |= 0x04;
last = attr;
} else if (attr->annotation->module == ctx->models.list[1] && /* internal YANG schema */
!strcmp(attr->annotation->arg_value, "key")) {
if (bits & 0x08) {
LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYD, parent, "key attributes", parent->schema->name);
return -1;
} else if (parent->schema->nodetype & LYS_LEAFLIST) {
LOGVAL(ctx, LYE_INATTR, LY_VLOG_LYD, parent, attr->name);
return -1;
}
bits |= 0x08;
last = attr;
}
}
/* report errors */
if (last && (!(parent->schema->nodetype & (LYS_LEAFLIST | LYS_LIST)) || !(parent->schema->flags & LYS_USERORDERED))) {
/* moving attributes in wrong elements (not an user ordered list or not a list at all) */
LOGVAL(ctx, LYE_INATTR, LY_VLOG_LYD, parent, last->name);
return -1;
} else if (bits == 3) {
/* 0x01 | 0x02 - relative position, but value/key is missing */
if (parent->schema->nodetype & LYS_LIST) {
LOGVAL(ctx, LYE_MISSATTR, LY_VLOG_LYD, parent, "key", parent->schema->name);
} else { /* LYS_LEAFLIST */
LOGVAL(ctx, LYE_MISSATTR, LY_VLOG_LYD, parent, "value", parent->schema->name);
}
return -1;
} else if ((bits & (0x04 | 0x08)) && !(bits & 0x02)) {
/* key/value without relative position */
LOGVAL(ctx, LYE_INATTR, LY_VLOG_LYD, parent, (bits & 0x04) ? "value" : "key");
return -1;
} else if ((bits & 0x21) == 0x21) {
/* insert in delete/remove */
LOGVAL(ctx, LYE_INATTR, LY_VLOG_LYD, parent, "insert");
return -1;
}
if (editbits) {
*editbits = bits;
}
return 0;
}
/* does not log */
static int
dup_identity_check(const char *id, struct lys_ident *ident, uint32_t size)
{
uint32_t i;
for (i = 0; i < size; i++) {
if (ly_strequal(id, ident[i].name, 1)) {
/* name collision */
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
int
dup_identities_check(const char *id, struct lys_module *module)
{
struct lys_module *mainmod;
int i;
if (dup_identity_check(id, module->ident, module->ident_size)) {
LOGVAL(module->ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "identity", id);
return EXIT_FAILURE;
}
/* check identity in submodules */
mainmod = lys_main_module(module);
for (i = 0; i < mainmod->inc_size && mainmod->inc[i].submodule; ++i) {
if (dup_identity_check(id, mainmod->inc[i].submodule->ident, mainmod->inc[i].submodule->ident_size)) {
LOGVAL(module->ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "identity", id);
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
/* does not log */
int
dup_typedef_check(const char *type, struct lys_tpdf *tpdf, int size)
{
int i;
for (i = 0; i < size; i++) {
if (!strcmp(type, tpdf[i].name)) {
/* name collision */
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
/* does not log */
static int
dup_feature_check(const char *id, struct lys_module *module)
{
int i;
for (i = 0; i < module->features_size; i++) {
if (!strcmp(id, module->features[i].name)) {
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
/* does not log */
static int
dup_prefix_check(const char *prefix, struct lys_module *module)
{
int i;
if (module->prefix && !strcmp(module->prefix, prefix)) {
return EXIT_FAILURE;
}
for (i = 0; i < module->imp_size; i++) {
if (!strcmp(module->imp[i].prefix, prefix)) {
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
/* logs directly */
int
lyp_check_identifier(struct ly_ctx *ctx, const char *id, enum LY_IDENT type, struct lys_module *module,
struct lys_node *parent)
{
int i, j;
int size;
struct lys_tpdf *tpdf;
struct lys_node *node;
struct lys_module *mainmod;
struct lys_submodule *submod;
assert(ctx && id);
/* check id syntax */
if (!(id[0] >= 'A' && id[0] <= 'Z') && !(id[0] >= 'a' && id[0] <= 'z') && id[0] != '_') {
LOGVAL(ctx, LYE_INID, LY_VLOG_NONE, NULL, id, "invalid start character");
return EXIT_FAILURE;
}
for (i = 1; id[i]; i++) {
if (!(id[i] >= 'A' && id[i] <= 'Z') && !(id[i] >= 'a' && id[i] <= 'z')
&& !(id[i] >= '0' && id[i] <= '9') && id[i] != '_' && id[i] != '-' && id[i] != '.') {
LOGVAL(ctx, LYE_INID, LY_VLOG_NONE, NULL, id, "invalid character");
return EXIT_FAILURE;
}
}
if (i > 64) {
LOGWRN(ctx, "Identifier \"%s\" is long, you should use something shorter.", id);
}
switch (type) {
case LY_IDENT_NAME:
/* check uniqueness of the node within its siblings */
if (!parent) {
break;
}
LY_TREE_FOR(parent->child, node) {
if (ly_strequal(node->name, id, 1)) {
LOGVAL(ctx, LYE_INID, LY_VLOG_NONE, NULL, id, "name duplication");
return EXIT_FAILURE;
}
}
break;
case LY_IDENT_TYPE:
assert(module);
mainmod = lys_main_module(module);
/* check collision with the built-in types */
if (!strcmp(id, "binary") || !strcmp(id, "bits") ||
!strcmp(id, "boolean") || !strcmp(id, "decimal64") ||
!strcmp(id, "empty") || !strcmp(id, "enumeration") ||
!strcmp(id, "identityref") || !strcmp(id, "instance-identifier") ||
!strcmp(id, "int8") || !strcmp(id, "int16") ||
!strcmp(id, "int32") || !strcmp(id, "int64") ||
!strcmp(id, "leafref") || !strcmp(id, "string") ||
!strcmp(id, "uint8") || !strcmp(id, "uint16") ||
!strcmp(id, "uint32") || !strcmp(id, "uint64") || !strcmp(id, "union")) {
LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, id, "typedef");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Typedef name duplicates a built-in type.");
return EXIT_FAILURE;
}
/* check locally scoped typedefs (avoid name shadowing) */
for (; parent; parent = lys_parent(parent)) {
switch (parent->nodetype) {
case LYS_CONTAINER:
size = ((struct lys_node_container *)parent)->tpdf_size;
tpdf = ((struct lys_node_container *)parent)->tpdf;
break;
case LYS_LIST:
size = ((struct lys_node_list *)parent)->tpdf_size;
tpdf = ((struct lys_node_list *)parent)->tpdf;
break;
case LYS_GROUPING:
size = ((struct lys_node_grp *)parent)->tpdf_size;
tpdf = ((struct lys_node_grp *)parent)->tpdf;
break;
default:
continue;
}
if (dup_typedef_check(id, tpdf, size)) {
LOGVAL(ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "typedef", id);
return EXIT_FAILURE;
}
}
/* check top-level names */
if (dup_typedef_check(id, module->tpdf, module->tpdf_size)) {
LOGVAL(ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "typedef", id);
return EXIT_FAILURE;
}
/* check submodule's top-level names */
for (i = 0; i < mainmod->inc_size && mainmod->inc[i].submodule; i++) {
if (dup_typedef_check(id, mainmod->inc[i].submodule->tpdf, mainmod->inc[i].submodule->tpdf_size)) {
LOGVAL(ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "typedef", id);
return EXIT_FAILURE;
}
}
break;
case LY_IDENT_PREFIX:
assert(module);
/* check the module itself */
if (dup_prefix_check(id, module)) {
LOGVAL(ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "prefix", id);
return EXIT_FAILURE;
}
break;
case LY_IDENT_FEATURE:
assert(module);
mainmod = lys_main_module(module);
/* check feature name uniqueness*/
/* check features in the current module */
if (dup_feature_check(id, module)) {
LOGVAL(ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "feature", id);
return EXIT_FAILURE;
}
/* and all its submodules */
for (i = 0; i < mainmod->inc_size && mainmod->inc[i].submodule; i++) {
if (dup_feature_check(id, (struct lys_module *)mainmod->inc[i].submodule)) {
LOGVAL(ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "feature", id);
return EXIT_FAILURE;
}
}
break;
case LY_IDENT_EXTENSION:
assert(module);
mainmod = lys_main_module(module);
/* check extension name uniqueness in the main module ... */
for (i = 0; i < mainmod->extensions_size; i++) {
if (ly_strequal(id, mainmod->extensions[i].name, 1)) {
LOGVAL(ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "extension", id);
return EXIT_FAILURE;
}
}
/* ... and all its submodules */
for (j = 0; j < mainmod->inc_size && mainmod->inc[j].submodule; j++) {
submod = mainmod->inc[j].submodule; /* shortcut */
for (i = 0; i < submod->extensions_size; i++) {
if (ly_strequal(id, submod->extensions[i].name, 1)) {
LOGVAL(ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "extension", id);
return EXIT_FAILURE;
}
}
}
break;
default:
/* no check required */
break;
}
return EXIT_SUCCESS;
}
/* logs directly */
int
lyp_check_date(struct ly_ctx *ctx, const char *date)
{
int i;
struct tm tm, tm_;
char *r;
assert(date);
/* check format */
for (i = 0; i < LY_REV_SIZE - 1; i++) {
if (i == 4 || i == 7) {
if (date[i] != '-') {
goto error;
}
} else if (!isdigit(date[i])) {
goto error;
}
}
/* check content, e.g. 2018-02-31 */
memset(&tm, 0, sizeof tm);
r = strptime(date, "%Y-%m-%d", &tm);
if (!r || r != &date[LY_REV_SIZE - 1]) {
goto error;
}
/* set some arbitrary non-0 value in case DST changes, it could move the day otherwise */
tm.tm_hour = 12;
memcpy(&tm_, &tm, sizeof tm);
mktime(&tm_); /* mktime modifies tm_ if it refers invalid date */
if (tm.tm_mday != tm_.tm_mday) { /* e.g 2018-02-29 -> 2018-03-01 */
/* checking days is enough, since other errors
* have been checked by strptime() */
goto error;
}
return EXIT_SUCCESS;
error:
LOGVAL(ctx, LYE_INDATE, LY_VLOG_NONE, NULL, date);
return EXIT_FAILURE;
}
/**
* @return
* NULL - success
* root - not yet resolvable
* other node - mandatory node under the root
*/
static const struct lys_node *
lyp_check_mandatory_(const struct lys_node *root)
{
int mand_flag = 0;
const struct lys_node *iter = NULL;
while ((iter = lys_getnext(iter, root, NULL, LYS_GETNEXT_WITHCHOICE | LYS_GETNEXT_WITHUSES | LYS_GETNEXT_INTOUSES
| LYS_GETNEXT_INTONPCONT | LYS_GETNEXT_NOSTATECHECK))) {
if (iter->nodetype == LYS_USES) {
if (!((struct lys_node_uses *)iter)->grp) {
/* not yet resolved uses */
return root;
} else {
/* go into uses */
continue;
}
}
if (iter->nodetype == LYS_CHOICE) {
/* skip it, it was already checked for direct mandatory node in default */
continue;
}
if (iter->nodetype == LYS_LIST) {
if (((struct lys_node_list *)iter)->min) {
mand_flag = 1;
}
} else if (iter->nodetype == LYS_LEAFLIST) {
if (((struct lys_node_leaflist *)iter)->min) {
mand_flag = 1;
}
} else if (iter->flags & LYS_MAND_TRUE) {
mand_flag = 1;
}
if (mand_flag) {
return iter;
}
}
return NULL;
}
/* logs directly */
int
lyp_check_mandatory_augment(struct lys_node_augment *aug, const struct lys_node *target)
{
const struct lys_node *node;
if (aug->when || target->nodetype == LYS_CHOICE) {
/* - mandatory nodes in new cases are ok;
* clarification from YANG 1.1 - augmentation can add mandatory nodes when it is
* conditional with a when statement */
return EXIT_SUCCESS;
}
if ((node = lyp_check_mandatory_((struct lys_node *)aug))) {
if (node != (struct lys_node *)aug) {
LOGVAL(target->module->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "mandatory");
LOGVAL(target->module->ctx, LYE_SPEC, LY_VLOG_NONE, NULL,
"Mandatory node \"%s\" appears in augment of \"%s\" without when condition.",
node->name, aug->target_name);
return -1;
}
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
/**
* @brief check that a mandatory node is not directly under the default case.
* @param[in] node choice with default node
* @return EXIT_SUCCESS if the constraint is fulfilled, EXIT_FAILURE otherwise
*/
int
lyp_check_mandatory_choice(struct lys_node *node)
{
const struct lys_node *mand, *dflt = ((struct lys_node_choice *)node)->dflt;
if ((mand = lyp_check_mandatory_(dflt))) {
if (mand != dflt) {
LOGVAL(node->module->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "mandatory");
LOGVAL(node->module->ctx, LYE_SPEC, LY_VLOG_NONE, NULL,
"Mandatory node \"%s\" is directly under the default case \"%s\" of the \"%s\" choice.",
mand->name, dflt->name, node->name);
return -1;
}
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
/**
* @brief Check status for invalid combination.
*
* @param[in] flags1 Flags of the referencing node.
* @param[in] mod1 Module of the referencing node,
* @param[in] name1 Schema node name of the referencing node.
* @param[in] flags2 Flags of the referenced node.
* @param[in] mod2 Module of the referenced node,
* @param[in] name2 Schema node name of the referenced node.
* @return EXIT_SUCCES on success, EXIT_FAILURE on invalid reference.
*/
int
lyp_check_status(uint16_t flags1, struct lys_module *mod1, const char *name1,
uint16_t flags2, struct lys_module *mod2, const char *name2,
const struct lys_node *node)
{
uint16_t flg1, flg2;
flg1 = (flags1 & LYS_STATUS_MASK) ? (flags1 & LYS_STATUS_MASK) : LYS_STATUS_CURR;
flg2 = (flags2 & LYS_STATUS_MASK) ? (flags2 & LYS_STATUS_MASK) : LYS_STATUS_CURR;
if ((flg1 < flg2) && (lys_main_module(mod1) == lys_main_module(mod2))) {
LOGVAL(mod1->ctx, LYE_INSTATUS, node ? LY_VLOG_LYS : LY_VLOG_NONE, node,
flg1 == LYS_STATUS_CURR ? "current" : "deprecated", name1, "references",
flg2 == LYS_STATUS_OBSLT ? "obsolete" : "deprecated", name2);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
void
lyp_del_includedup(struct lys_module *mod, int free_subs)
{
struct ly_modules_list *models = &mod->ctx->models;
uint8_t i;
assert(mod && !mod->type);
if (models->parsed_submodules_count) {
for (i = models->parsed_submodules_count - 1; models->parsed_submodules[i]->type; --i);
if (models->parsed_submodules[i] == mod) {
if (free_subs) {
for (i = models->parsed_submodules_count - 1; models->parsed_submodules[i]->type; --i) {
lys_sub_module_remove_devs_augs((struct lys_module *)models->parsed_submodules[i]);
lys_submodule_module_data_free((struct lys_submodule *)models->parsed_submodules[i]);
lys_submodule_free((struct lys_submodule *)models->parsed_submodules[i], NULL);
}
}
models->parsed_submodules_count = i;
if (!models->parsed_submodules_count) {
free(models->parsed_submodules);
models->parsed_submodules = NULL;
}
}
}
}
static void
lyp_add_includedup(struct lys_module *sub_mod, struct lys_submodule *parsed_submod)
{
struct ly_modules_list *models = &sub_mod->ctx->models;
int16_t i;
/* store main module if first include */
if (models->parsed_submodules_count) {
for (i = models->parsed_submodules_count - 1; models->parsed_submodules[i]->type; --i);
} else {
i = -1;
}
if ((i == -1) || (models->parsed_submodules[i] != lys_main_module(sub_mod))) {
++models->parsed_submodules_count;
models->parsed_submodules = ly_realloc(models->parsed_submodules,
models->parsed_submodules_count * sizeof *models->parsed_submodules);
LY_CHECK_ERR_RETURN(!models->parsed_submodules, LOGMEM(sub_mod->ctx), );
models->parsed_submodules[models->parsed_submodules_count - 1] = lys_main_module(sub_mod);
}
/* store parsed submodule */
++models->parsed_submodules_count;
models->parsed_submodules = ly_realloc(models->parsed_submodules,
models->parsed_submodules_count * sizeof *models->parsed_submodules);
LY_CHECK_ERR_RETURN(!models->parsed_submodules, LOGMEM(sub_mod->ctx), );
models->parsed_submodules[models->parsed_submodules_count - 1] = (struct lys_module *)parsed_submod;
}
/*
* types: 0 - include, 1 - import
*/
static int
lyp_check_circmod(struct lys_module *module, const char *value, int type)
{
LY_ECODE code = type ? LYE_CIRC_IMPORTS : LYE_CIRC_INCLUDES;
struct ly_modules_list *models = &module->ctx->models;
uint8_t i;
/* include/import itself */
if (ly_strequal(module->name, value, 1)) {
LOGVAL(module->ctx, code, LY_VLOG_NONE, NULL, value);
return -1;
}
/* currently parsed modules */
for (i = 0; i < models->parsing_sub_modules_count; i++) {
if (ly_strequal(models->parsing_sub_modules[i]->name, value, 1)) {
LOGVAL(module->ctx, code, LY_VLOG_NONE, NULL, value);
return -1;
}
}
return 0;
}
int
lyp_check_circmod_add(struct lys_module *module)
{
struct ly_modules_list *models = &module->ctx->models;
/* storing - enlarge the list of modules being currently parsed */
++models->parsing_sub_modules_count;
models->parsing_sub_modules = ly_realloc(models->parsing_sub_modules,
models->parsing_sub_modules_count * sizeof *models->parsing_sub_modules);
LY_CHECK_ERR_RETURN(!models->parsing_sub_modules, LOGMEM(module->ctx), -1);
models->parsing_sub_modules[models->parsing_sub_modules_count - 1] = module;
return 0;
}
void
lyp_check_circmod_pop(struct ly_ctx *ctx)
{
if (!ctx->models.parsing_sub_modules_count) {
LOGINT(ctx);
return;
}
/* update the list of currently being parsed modules */
ctx->models.parsing_sub_modules_count--;
if (!ctx->models.parsing_sub_modules_count) {
free(ctx->models.parsing_sub_modules);
ctx->models.parsing_sub_modules = NULL;
}
}
/*
* -1 - error - invalid duplicities)
* 0 - success, no duplicity
* 1 - success, valid duplicity found and stored in *sub
*/
static int
lyp_check_includedup(struct lys_module *mod, const char *name, struct lys_include *inc, struct lys_submodule **sub)
{
struct lys_module **parsed_sub = mod->ctx->models.parsed_submodules;
uint8_t i, parsed_sub_count = mod->ctx->models.parsed_submodules_count;
assert(sub);
for (i = 0; i < mod->inc_size; ++i) {
if (ly_strequal(mod->inc[i].submodule->name, name, 1)) {
/* the same module is already included in the same module - error */
LOGVAL(mod->ctx, LYE_INARG, LY_VLOG_NONE, NULL, name, "include");
LOGVAL(mod->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Submodule \"%s\" included twice in the same module \"%s\".",
name, mod->name);
return -1;
}
}
if (parsed_sub_count) {
assert(!parsed_sub[0]->type);
for (i = parsed_sub_count - 1; parsed_sub[i]->type; --i) {
if (ly_strequal(parsed_sub[i]->name, name, 1)) {
/* check revisions, including multiple revisions of a single module is error */
if (inc->rev[0] && (!parsed_sub[i]->rev_size || strcmp(parsed_sub[i]->rev[0].date, inc->rev))) {
/* the already included submodule has
* - no revision, but here we require some
* - different revision than the one required here */
LOGVAL(mod->ctx, LYE_INARG, LY_VLOG_NONE, NULL, name, "include");
LOGVAL(mod->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Including multiple revisions of submodule \"%s\".", name);
return -1;
}
/* the same module is already included in some other submodule, return it */
(*sub) = (struct lys_submodule *)parsed_sub[i];
return 1;
}
}
}
/* no duplicity found */
return 0;
}
/* returns:
* 0 - inc successfully filled
* -1 - error
*/
int
lyp_check_include(struct lys_module *module, const char *value, struct lys_include *inc, struct unres_schema *unres)
{
int i;
/* check that the submodule was not included yet */
i = lyp_check_includedup(module, value, inc, &inc->submodule);
if (i == -1) {
return -1;
} else if (i == 1) {
return 0;
}
/* submodule is not yet loaded */
/* circular include check */
if (lyp_check_circmod(module, value, 0)) {
return -1;
}
/* try to load the submodule */
inc->submodule = (struct lys_submodule *)ly_ctx_load_sub_module(module->ctx, module, value,
inc->rev[0] ? inc->rev : NULL, 1, unres);
/* check the result */
if (!inc->submodule) {
if (ly_errno != LY_EVALID) {
LOGVAL(module->ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "include");
}
LOGERR(module->ctx, LY_EVALID, "Including \"%s\" module into \"%s\" failed.", value, module->name);
return -1;
}
/* check the revision */
if (inc->rev[0] && inc->submodule->rev_size && strcmp(inc->rev, inc->submodule->rev[0].date)) {
LOGERR(module->ctx, LY_EVALID, "\"%s\" include of submodule \"%s\" in revision \"%s\" not found.",
module->name, value, inc->rev);
unres_schema_free((struct lys_module *)inc->submodule, &unres, 0);
lys_sub_module_remove_devs_augs((struct lys_module *)inc->submodule);
lys_submodule_module_data_free((struct lys_submodule *)inc->submodule);
lys_submodule_free(inc->submodule, NULL);
inc->submodule = NULL;
return -1;
}
/* store the submodule as successfully parsed */
lyp_add_includedup(module, inc->submodule);
return 0;
}
static int
lyp_check_include_missing_recursive(struct lys_module *main_module, struct lys_submodule *sub)
{
uint8_t i, j;
void *reallocated;
int ret = 0, tmp;
struct ly_ctx *ctx = main_module->ctx;
for (i = 0; i < sub->inc_size; i++) {
/* check that the include is also present in the main module */
for (j = 0; j < main_module->inc_size; j++) {
if (main_module->inc[j].submodule == sub->inc[i].submodule) {
break;
}
}
if (j == main_module->inc_size) {
/* match not found */
if (main_module->version >= LYS_VERSION_1_1) {
LOGVAL(ctx, LYE_MISSSTMT, LY_VLOG_NONE, NULL, "include");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL,
"The main module \"%s\" misses include of the \"%s\" submodule used in another submodule \"%s\".",
main_module->name, sub->inc[i].submodule->name, sub->name);
/* now we should return error, but due to the issues with freeing the module, we actually have
* to go through the all includes and, as in case of 1.0, add them into the main module and fail
* at the end when all the includes are in the main module and we can free them */
ret = 1;
} else {
/* not strictly an error in YANG 1.0 */
LOGWRN(ctx, "The main module \"%s\" misses include of the \"%s\" submodule used in another submodule \"%s\".",
main_module->name, sub->inc[i].submodule->name, sub->name);
LOGWRN(ctx, "To avoid further issues, adding submodule \"%s\" into the main module \"%s\".",
sub->inc[i].submodule->name, main_module->name);
/* but since it is a good practise and because we expect all the includes in the main module
* when searching it and also when freeing the module, put it into it */
}
main_module->inc_size++;
reallocated = realloc(main_module->inc, main_module->inc_size * sizeof *main_module->inc);
LY_CHECK_ERR_RETURN(!reallocated, LOGMEM(ctx), 1);
main_module->inc = reallocated;
memset(&main_module->inc[main_module->inc_size - 1], 0, sizeof *main_module->inc);
/* to avoid unexpected consequences, copy just a link to the submodule and the revision,
* all other substatements of the include are ignored */
memcpy(&main_module->inc[main_module->inc_size - 1].rev, sub->inc[i].rev, LY_REV_SIZE - 1);
main_module->inc[main_module->inc_size - 1].submodule = sub->inc[i].submodule;
}
/* recursion */
tmp = lyp_check_include_missing_recursive(main_module, sub->inc[i].submodule);
if (!ret && tmp) {
ret = 1;
}
}
return ret;
}
int
lyp_check_include_missing(struct lys_module *main_module)
{
int ret = 0;
uint8_t i;
/* in YANG 1.1, all the submodules must be in the main module, check it even for
* 1.0 where it will be printed as warning and the include will be added into the main module */
for (i = 0; i < main_module->inc_size; i++) {
if (lyp_check_include_missing_recursive(main_module, main_module->inc[i].submodule)) {
ret = 1;
}
}
return ret;
}
/* returns:
* 0 - imp successfully filled
* -1 - error, imp not cleaned
*/
int
lyp_check_import(struct lys_module *module, const char *value, struct lys_import *imp)
{
int i;
struct lys_module *dup = NULL;
struct ly_ctx *ctx = module->ctx;
/* check for importing a single module in multiple revisions */
for (i = 0; i < module->imp_size; i++) {
if (!module->imp[i].module) {
/* skip the not yet filled records */
continue;
}
if (ly_strequal(module->imp[i].module->name, value, 1)) {
/* check revisions, including multiple revisions of a single module is error */
if (imp->rev[0] && (!module->imp[i].module->rev_size || strcmp(module->imp[i].module->rev[0].date, imp->rev))) {
/* the already imported module has
* - no revision, but here we require some
* - different revision than the one required here */
LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "import");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Importing multiple revisions of module \"%s\".", value);
return -1;
} else if (!imp->rev[0]) {
/* no revision, remember the duplication, but check revisions after loading the module
* because the current revision can be the same (then it is ok) or it can differ (then it
* is error */
dup = module->imp[i].module;
break;
}
/* there is duplication, but since prefixes differs (checked in caller of this function),
* it is ok */
imp->module = module->imp[i].module;
return 0;
}
}
/* circular import check */
if (lyp_check_circmod(module, value, 1)) {
return -1;
}
/* load module - in specific situations it tries to get the module from the context */
imp->module = (struct lys_module *)ly_ctx_load_sub_module(module->ctx, NULL, value, imp->rev[0] ? imp->rev : NULL,
module->ctx->models.flags & LY_CTX_ALLIMPLEMENTED ? 1 : 0,
NULL);
/* check the result */
if (!imp->module) {
LOGERR(ctx, LY_EVALID, "Importing \"%s\" module into \"%s\" failed.", value, module->name);
return -1;
}
if (imp->rev[0] && imp->module->rev_size && strcmp(imp->rev, imp->module->rev[0].date)) {
LOGERR(ctx, LY_EVALID, "\"%s\" import of module \"%s\" in revision \"%s\" not found.",
module->name, value, imp->rev);
return -1;
}
if (dup) {
/* check the revisions */
if ((dup != imp->module) ||
(dup->rev_size != imp->module->rev_size && (!dup->rev_size || imp->module->rev_size)) ||
(dup->rev_size && strcmp(dup->rev[0].date, imp->module->rev[0].date))) {
/* - modules are not the same
* - one of modules has no revision (except they both has no revision)
* - revisions of the modules are not the same */
LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "import");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Importing multiple revisions of module \"%s\".", value);
return -1;
} else {
LOGWRN(ctx, "Module \"%s\" is imported by \"%s\" multiple times with different prefixes.", dup->name, module->name);
}
}
return 0;
}
/*
* put the newest revision to the first position
*/
void
lyp_sort_revisions(struct lys_module *module)
{
uint8_t i, r;
struct lys_revision rev;
for (i = 1, r = 0; i < module->rev_size; i++) {
if (strcmp(module->rev[i].date, module->rev[r].date) > 0) {
r = i;
}
}
if (r) {
/* the newest revision is not on position 0, switch them */
memcpy(&rev, &module->rev[0], sizeof rev);
memcpy(&module->rev[0], &module->rev[r], sizeof rev);
memcpy(&module->rev[r], &rev, sizeof rev);
}
}
void
lyp_ext_instance_rm(struct ly_ctx *ctx, struct lys_ext_instance ***ext, uint8_t *size, uint8_t index)
{
uint8_t i;
lys_extension_instances_free(ctx, (*ext)[index]->ext, (*ext)[index]->ext_size, NULL);
lydict_remove(ctx, (*ext)[index]->arg_value);
free((*ext)[index]);
/* move the rest of the array */
for (i = index + 1; i < (*size); i++) {
(*ext)[i - 1] = (*ext)[i];
}
/* clean the last cell in the array structure */
(*ext)[(*size) - 1] = NULL;
/* the array is not reallocated here, just change its size */
(*size) = (*size) - 1;
if (!(*size)) {
/* ext array is empty */
free((*ext));
ext = NULL;
}
}
static int
lyp_rfn_apply_ext_(struct lys_refine *rfn, struct lys_node *target, LYEXT_SUBSTMT substmt, struct lys_ext *extdef)
{
struct ly_ctx *ctx;
int m, n;
struct lys_ext_instance *new;
void *reallocated;
ctx = target->module->ctx; /* shortcut */
m = n = -1;
while ((m = lys_ext_iter(rfn->ext, rfn->ext_size, m + 1, substmt)) != -1) {
/* refine's substatement includes extensions, copy them to the target, replacing the previous
* substatement's extensions if any. In case of refining the extension itself, we are going to
* replace only the same extension (pointing to the same definition) */
if (substmt == LYEXT_SUBSTMT_SELF && rfn->ext[m]->def != extdef) {
continue;
}
/* get the index of the extension to replace in the target node */
do {
n = lys_ext_iter(target->ext, target->ext_size, n + 1, substmt);
} while (n != -1 && substmt == LYEXT_SUBSTMT_SELF && target->ext[n]->def != extdef);
/* TODO cover complex extension instances */
if (n == -1) {
/* nothing to replace, we are going to add it - reallocate */
new = malloc(sizeof **target->ext);
LY_CHECK_ERR_RETURN(!new, LOGMEM(ctx), EXIT_FAILURE);
reallocated = realloc(target->ext, (target->ext_size + 1) * sizeof *target->ext);
LY_CHECK_ERR_RETURN(!reallocated, LOGMEM(ctx); free(new), EXIT_FAILURE);
target->ext = reallocated;
target->ext_size++;
/* init */
n = target->ext_size - 1;
target->ext[n] = new;
target->ext[n]->parent = target;
target->ext[n]->parent_type = LYEXT_PAR_NODE;
target->ext[n]->flags = 0;
target->ext[n]->insubstmt = substmt;
target->ext[n]->priv = NULL;
target->ext[n]->nodetype = LYS_EXT;
target->ext[n]->module = target->module;
} else {
/* replacing - first remove the allocated data from target */
lys_extension_instances_free(ctx, target->ext[n]->ext, target->ext[n]->ext_size, NULL);
lydict_remove(ctx, target->ext[n]->arg_value);
}
/* common part for adding and replacing */
target->ext[n]->def = rfn->ext[m]->def;
/* parent and parent_type do not change */
target->ext[n]->arg_value = lydict_insert(ctx, rfn->ext[m]->arg_value, 0);
/* flags do not change */
target->ext[n]->ext_size = rfn->ext[m]->ext_size;
lys_ext_dup(ctx, target->module, rfn->ext[m]->ext, rfn->ext[m]->ext_size, target, LYEXT_PAR_NODE,
&target->ext[n]->ext, 0, NULL);
/* substmt does not change, but the index must be taken from the refine */
target->ext[n]->insubstmt_index = rfn->ext[m]->insubstmt_index;
}
/* remove the rest of extensions belonging to the original substatement in the target node */
while ((n = lys_ext_iter(target->ext, target->ext_size, n + 1, substmt)) != -1) {
if (substmt == LYEXT_SUBSTMT_SELF && target->ext[n]->def != extdef) {
/* keep this extension */
continue;
}
/* remove the item */
lyp_ext_instance_rm(ctx, &target->ext, &target->ext_size, n);
--n;
}
return EXIT_SUCCESS;
}
/*
* apply extension instances defined under refine's substatements.
* It cannot be done immediately when applying the refine because there can be
* still unresolved data (e.g. type) and mainly the targeted extension instances.
*/
int
lyp_rfn_apply_ext(struct lys_module *module)
{
int i, k, a = 0;
struct lys_node *root, *nextroot, *next, *node;
struct lys_node *target;
struct lys_node_uses *uses;
struct lys_refine *rfn;
struct ly_set *extset;
/* refines in uses */
LY_TREE_FOR_SAFE(module->data, nextroot, root) {
/* go through the data tree of the module and all the defined augments */
LY_TREE_DFS_BEGIN(root, next, node) {
if (node->nodetype == LYS_USES) {
uses = (struct lys_node_uses *)node;
for (i = 0; i < uses->refine_size; i++) {
if (!uses->refine[i].ext_size) {
/* no extensions in refine */
continue;
}
rfn = &uses->refine[i]; /* shortcut */
/* get the target node */
target = NULL;
resolve_descendant_schema_nodeid(rfn->target_name, uses->child,
LYS_NO_RPC_NOTIF_NODE | LYS_ACTION | LYS_NOTIF,
0, (const struct lys_node **)&target);
if (!target) {
/* it should always succeed since the target_name was already resolved at least
* once when the refine itself was being resolved */
LOGINT(module->ctx);;
return EXIT_FAILURE;
}
/* extensions */
extset = ly_set_new();
k = -1;
while ((k = lys_ext_iter(rfn->ext, rfn->ext_size, k + 1, LYEXT_SUBSTMT_SELF)) != -1) {
ly_set_add(extset, rfn->ext[k]->def, 0);
}
for (k = 0; (unsigned int)k < extset->number; k++) {
if (lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_SELF, (struct lys_ext *)extset->set.g[k])) {
ly_set_free(extset);
return EXIT_FAILURE;
}
}
ly_set_free(extset);
/* description */
if (rfn->dsc && lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_DESCRIPTION, NULL)) {
return EXIT_FAILURE;
}
/* reference */
if (rfn->ref && lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_REFERENCE, NULL)) {
return EXIT_FAILURE;
}
/* config, in case of notification or rpc/action{notif, the config is not applicable
* (there is no config status) */
if ((rfn->flags & LYS_CONFIG_MASK) && (target->flags & LYS_CONFIG_MASK)) {
if (lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_CONFIG, NULL)) {
return EXIT_FAILURE;
}
}
/* default value */
if (rfn->dflt_size && lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_DEFAULT, NULL)) {
return EXIT_FAILURE;
}
/* mandatory */
if (rfn->flags & LYS_MAND_MASK) {
if (lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_MANDATORY, NULL)) {
return EXIT_FAILURE;
}
}
/* presence */
if ((target->nodetype & LYS_CONTAINER) && rfn->mod.presence) {
if (lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_PRESENCE, NULL)) {
return EXIT_FAILURE;
}
}
/* min/max */
if (rfn->flags & LYS_RFN_MINSET) {
if (lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_MIN, NULL)) {
return EXIT_FAILURE;
}
}
if (rfn->flags & LYS_RFN_MAXSET) {
if (lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_MAX, NULL)) {
return EXIT_FAILURE;
}
}
/* must and if-feature contain extensions on their own, not needed to be solved here */
if (target->ext_size) {
/* the allocated target's extension array can be now longer than needed in case
* there is less refine substatement's extensions than in original. Since we are
* going to reduce or keep the same memory, it is not necessary to test realloc's result */
target->ext = realloc(target->ext, target->ext_size * sizeof *target->ext);
}
}
}
LY_TREE_DFS_END(root, next, node)
}
if (!nextroot && a < module->augment_size) {
nextroot = module->augment[a].child;
a++;
}
}
return EXIT_SUCCESS;
}
/*
* check mandatory substatements defined under extension instances.
*/
int
lyp_mand_check_ext(struct lys_ext_instance_complex *ext, const char *ext_name)
{
void *p;
int i;
struct ly_ctx *ctx = ext->module->ctx;
/* check for mandatory substatements */
for (i = 0; ext->substmt[i].stmt; i++) {
if (ext->substmt[i].cardinality == LY_STMT_CARD_OPT || ext->substmt[i].cardinality == LY_STMT_CARD_ANY) {
/* not a mandatory */
continue;
} else if (ext->substmt[i].cardinality == LY_STMT_CARD_SOME) {
goto array;
}
/*
* LY_STMT_ORDEREDBY - not checked, has a default value which is the same as explicit system order
* LY_STMT_MODIFIER, LY_STMT_STATUS, LY_STMT_MANDATORY, LY_STMT_CONFIG - checked, but mandatory requirement
* does not make sense since there is also a default value specified
*/
switch(ext->substmt[i].stmt) {
case LY_STMT_ORDEREDBY:
/* always ok */
break;
case LY_STMT_REQINSTANCE:
case LY_STMT_DIGITS:
case LY_STMT_MODIFIER:
p = lys_ext_complex_get_substmt(ext->substmt[i].stmt, ext, NULL);
if (!*(uint8_t*)p) {
LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, ly_stmt_str[ext->substmt[i].stmt], ext_name);
goto error;
}
break;
case LY_STMT_STATUS:
p = lys_ext_complex_get_substmt(ext->substmt[i].stmt, ext, NULL);
if (!(*(uint16_t*)p & LYS_STATUS_MASK)) {
LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, ly_stmt_str[ext->substmt[i].stmt], ext_name);
goto error;
}
break;
case LY_STMT_MANDATORY:
p = lys_ext_complex_get_substmt(ext->substmt[i].stmt, ext, NULL);
if (!(*(uint16_t*)p & LYS_MAND_MASK)) {
LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, ly_stmt_str[ext->substmt[i].stmt], ext_name);
goto error;
}
break;
case LY_STMT_CONFIG:
p = lys_ext_complex_get_substmt(ext->substmt[i].stmt, ext, NULL);
if (!(*(uint16_t*)p & LYS_CONFIG_MASK)) {
LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, ly_stmt_str[ext->substmt[i].stmt], ext_name);
goto error;
}
break;
default:
array:
/* stored as a pointer */
p = lys_ext_complex_get_substmt(ext->substmt[i].stmt, ext, NULL);
if (!(*(void**)p)) {
LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, ly_stmt_str[ext->substmt[i].stmt], ext_name);
goto error;
}
break;
}
}
return EXIT_SUCCESS;
error:
return EXIT_FAILURE;
}
static int
lyp_deviate_del_ext(struct lys_node *target, struct lys_ext_instance *ext)
{
int n = -1, found = 0;
char *path;
while ((n = lys_ext_iter(target->ext, target->ext_size, n + 1, ext->insubstmt)) != -1) {
if (target->ext[n]->def != ext->def) {
continue;
}
if (ext->def->argument) {
/* check matching arguments */
if (!ly_strequal(target->ext[n]->arg_value, ext->arg_value, 1)) {
continue;
}
}
/* we have the matching extension - remove it */
++found;
lyp_ext_instance_rm(target->module->ctx, &target->ext, &target->ext_size, n);
--n;
}
if (!found) {
path = lys_path(target, LYS_PATH_FIRST_PREFIX);
LOGERR(target->module->ctx, LY_EVALID, "Extension deviation: extension \"%s\" to delete not found in \"%s\".",
ext->def->name, path)
free(path);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
static int
lyp_deviate_apply_ext(struct lys_deviate *dev, struct lys_node *target, LYEXT_SUBSTMT substmt, struct lys_ext *extdef)
{
struct ly_ctx *ctx;
int m, n;
struct lys_ext_instance *new;
void *reallocated;
/* LY_DEVIATE_ADD and LY_DEVIATE_RPL are very similar so they are implement the same way - in replacing,
* there can be some extension instances in the target, in case of adding, there should not be any so we
* will be just adding. */
ctx = target->module->ctx; /* shortcut */
m = n = -1;
while ((m = lys_ext_iter(dev->ext, dev->ext_size, m + 1, substmt)) != -1) {
/* deviate and its substatements include extensions, copy them to the target, replacing the previous
* extensions if any. In case of deviating extension itself, we have to deviate only the same type
* of the extension as specified in the deviation */
if (substmt == LYEXT_SUBSTMT_SELF && dev->ext[m]->def != extdef) {
continue;
}
if (substmt == LYEXT_SUBSTMT_SELF && dev->mod == LY_DEVIATE_ADD) {
/* in case of adding extension, we will be replacing only the inherited extensions */
do {
n = lys_ext_iter(target->ext, target->ext_size, n + 1, substmt);
} while (n != -1 && (target->ext[n]->def != extdef || !(target->ext[n]->flags & LYEXT_OPT_INHERIT)));
} else {
/* get the index of the extension to replace in the target node */
do {
n = lys_ext_iter(target->ext, target->ext_size, n + 1, substmt);
/* if we are applying extension deviation, we have to deviate only the same type of the extension */
} while (n != -1 && substmt == LYEXT_SUBSTMT_SELF && target->ext[n]->def != extdef);
}
if (n == -1) {
/* nothing to replace, we are going to add it - reallocate */
new = malloc(sizeof **target->ext);
LY_CHECK_ERR_RETURN(!new, LOGMEM(ctx), EXIT_FAILURE);
reallocated = realloc(target->ext, (target->ext_size + 1) * sizeof *target->ext);
LY_CHECK_ERR_RETURN(!reallocated, LOGMEM(ctx); free(new), EXIT_FAILURE);
target->ext = reallocated;
target->ext_size++;
n = target->ext_size - 1;
} else {
/* replacing - the original set of extensions is actually backuped together with the
* node itself, so we are supposed only to free the allocated data here ... */
lys_extension_instances_free(ctx, target->ext[n]->ext, target->ext[n]->ext_size, NULL);
lydict_remove(ctx, target->ext[n]->arg_value);
free(target->ext[n]);
/* and prepare the new structure */
new = malloc(sizeof **target->ext);
LY_CHECK_ERR_RETURN(!new, LOGMEM(ctx), EXIT_FAILURE);
}
/* common part for adding and replacing - fill the newly created / replaced cell */
target->ext[n] = new;
target->ext[n]->def = dev->ext[m]->def;
target->ext[n]->arg_value = lydict_insert(ctx, dev->ext[m]->arg_value, 0);
target->ext[n]->flags = 0;
target->ext[n]->parent = target;
target->ext[n]->parent_type = LYEXT_PAR_NODE;
target->ext[n]->insubstmt = substmt;
target->ext[n]->insubstmt_index = dev->ext[m]->insubstmt_index;
target->ext[n]->ext_size = dev->ext[m]->ext_size;
lys_ext_dup(ctx, target->module, dev->ext[m]->ext, dev->ext[m]->ext_size, target, LYEXT_PAR_NODE,
&target->ext[n]->ext, 1, NULL);
target->ext[n]->nodetype = LYS_EXT;
target->ext[n]->module = target->module;
target->ext[n]->priv = NULL;
/* TODO cover complex extension instances */
}
/* remove the rest of extensions belonging to the original substatement in the target node,
* due to possible reverting of the deviation effect, they are actually not removed, just moved
* to the backup of the original node when the original node is backuped, here we just have to
* free the replaced / deleted originals */
while ((n = lys_ext_iter(target->ext, target->ext_size, n + 1, substmt)) != -1) {
if (substmt == LYEXT_SUBSTMT_SELF) {
/* if we are applying extension deviation, we are going to remove only
* - the same type of the extension in case of replacing
* - the same type of the extension which was inherited in case of adding
* note - delete deviation is covered in lyp_deviate_del_ext */
if (target->ext[n]->def != extdef ||
(dev->mod == LY_DEVIATE_ADD && !(target->ext[n]->flags & LYEXT_OPT_INHERIT))) {
/* keep this extension */
continue;
}
}
/* remove the item */
lyp_ext_instance_rm(ctx, &target->ext, &target->ext_size, n);
--n;
}
return EXIT_SUCCESS;
}
/*
* not-supported deviations are not processed since they affect the complete node, not just their substatements
*/
int
lyp_deviation_apply_ext(struct lys_module *module)
{
int i, j, k;
struct lys_deviate *dev;
struct lys_node *target;
struct ly_set *extset;
for (i = 0; i < module->deviation_size; i++) {
target = NULL;
extset = NULL;
j = resolve_schema_nodeid(module->deviation[i].target_name, NULL, module, &extset, 0, 0);
if (j == -1) {
return EXIT_FAILURE;
} else if (!extset) {
/* LY_DEVIATE_NO */
ly_set_free(extset);
continue;
}
target = extset->set.s[0];
ly_set_free(extset);
for (j = 0; j < module->deviation[i].deviate_size; j++) {
dev = &module->deviation[i].deviate[j];
if (!dev->ext_size) {
/* no extensions in deviate and its substatement, nothing to do here */
continue;
}
/* extensions */
if (dev->mod == LY_DEVIATE_DEL) {
k = -1;
while ((k = lys_ext_iter(dev->ext, dev->ext_size, k + 1, LYEXT_SUBSTMT_SELF)) != -1) {
if (lyp_deviate_del_ext(target, dev->ext[k])) {
return EXIT_FAILURE;
}
}
/* In case of LY_DEVIATE_DEL, we are applying only extension deviation, removing
* of the substatement's extensions was already done when the substatement was applied.
* Extension deviation could not be applied by the parser since the extension could be unresolved,
* which is not the issue of the other substatements. */
continue;
} else {
extset = ly_set_new();
k = -1;
while ((k = lys_ext_iter(dev->ext, dev->ext_size, k + 1, LYEXT_SUBSTMT_SELF)) != -1) {
ly_set_add(extset, dev->ext[k]->def, 0);
}
for (k = 0; (unsigned int)k < extset->number; k++) {
if (lyp_deviate_apply_ext(dev, target, LYEXT_SUBSTMT_SELF, (struct lys_ext *)extset->set.g[k])) {
ly_set_free(extset);
return EXIT_FAILURE;
}
}
ly_set_free(extset);
}
/* unique */
if (dev->unique_size && lyp_deviate_apply_ext(dev, target, LYEXT_SUBSTMT_UNIQUE, NULL)) {
return EXIT_FAILURE;
}
/* units */
if (dev->units && lyp_deviate_apply_ext(dev, target, LYEXT_SUBSTMT_UNITS, NULL)) {
return EXIT_FAILURE;
}
/* default */
if (dev->dflt_size && lyp_deviate_apply_ext(dev, target, LYEXT_SUBSTMT_DEFAULT, NULL)) {
return EXIT_FAILURE;
}
/* config */
if ((dev->flags & LYS_CONFIG_MASK) && lyp_deviate_apply_ext(dev, target, LYEXT_SUBSTMT_CONFIG, NULL)) {
return EXIT_FAILURE;
}
/* mandatory */
if ((dev->flags & LYS_MAND_MASK) && lyp_deviate_apply_ext(dev, target, LYEXT_SUBSTMT_MANDATORY, NULL)) {
return EXIT_FAILURE;
}
/* min/max */
if (dev->min_set && lyp_deviate_apply_ext(dev, target, LYEXT_SUBSTMT_MIN, NULL)) {
return EXIT_FAILURE;
}
if (dev->min_set && lyp_deviate_apply_ext(dev, target, LYEXT_SUBSTMT_MAX, NULL)) {
return EXIT_FAILURE;
}
/* type and must contain extension instances in their structures */
}
}
return EXIT_SUCCESS;
}
int
lyp_ctx_check_module(struct lys_module *module)
{
struct ly_ctx *ctx;
int i, match_i = -1, to_implement;
const char *last_rev = NULL;
assert(module);
to_implement = 0;
ctx = module->ctx;
/* find latest revision */
for (i = 0; i < module->rev_size; ++i) {
if (!last_rev || (strcmp(last_rev, module->rev[i].date) < 0)) {
last_rev = module->rev[i].date;
}
}
for (i = 0; i < ctx->models.used; i++) {
/* check name (name/revision) and namespace uniqueness */
if (!strcmp(ctx->models.list[i]->name, module->name)) {
if (to_implement) {
if (i == match_i) {
continue;
}
LOGERR(ctx, LY_EINVAL, "Module \"%s@%s\" in another revision \"%s\" already implemented.",
module->name, last_rev ? last_rev : "<latest>", ctx->models.list[i]->rev[0].date);
return -1;
} else if (!ctx->models.list[i]->rev_size && module->rev_size) {
LOGERR(ctx, LY_EINVAL, "Module \"%s\" without revision already in context.", module->name);
return -1;
} else if (ctx->models.list[i]->rev_size && !module->rev_size) {
LOGERR(ctx, LY_EINVAL, "Module \"%s\" with revision \"%s\" already in context.",
module->name, ctx->models.list[i]->rev[0].date);
return -1;
} else if ((!module->rev_size && !ctx->models.list[i]->rev_size)
|| !strcmp(ctx->models.list[i]->rev[0].date, last_rev)) {
LOGVRB("Module \"%s@%s\" already in context.", module->name, last_rev ? last_rev : "<latest>");
/* if disabled, enable first */
if (ctx->models.list[i]->disabled) {
lys_set_enabled(ctx->models.list[i]);
}
to_implement = module->implemented;
match_i = i;
if (to_implement && !ctx->models.list[i]->implemented) {
/* check first that it is okay to change it to implemented */
i = -1;
continue;
}
return 1;
} else if (module->implemented && ctx->models.list[i]->implemented) {
LOGERR(ctx, LY_EINVAL, "Module \"%s@%s\" in another revision \"%s\" already implemented.",
module->name, last_rev ? last_rev : "<latest>", ctx->models.list[i]->rev[0].date);
return -1;
}
/* else keep searching, for now the caller is just adding
* another revision of an already present schema
*/
} else if (!strcmp(ctx->models.list[i]->ns, module->ns)) {
LOGERR(ctx, LY_EINVAL, "Two different modules (\"%s\" and \"%s\") have the same namespace \"%s\".",
ctx->models.list[i]->name, module->name, module->ns);
return -1;
}
}
if (to_implement) {
if (lys_set_implemented(ctx->models.list[match_i])) {
return -1;
}
return 1;
}
return 0;
}
int
lyp_ctx_add_module(struct lys_module *module)
{
struct lys_module **newlist = NULL;
int i;
assert(!lyp_ctx_check_module(module));
#ifndef NDEBUG
int j;
/* check that all augments are resolved */
for (i = 0; i < module->augment_size; ++i) {
assert(module->augment[i].target);
}
for (i = 0; i < module->inc_size; ++i) {
for (j = 0; j < module->inc[i].submodule->augment_size; ++j) {
assert(module->inc[i].submodule->augment[j].target);
}
}
#endif
/* add to the context's list of modules */
if (module->ctx->models.used == module->ctx->models.size) {
newlist = realloc(module->ctx->models.list, (2 * module->ctx->models.size) * sizeof *newlist);
LY_CHECK_ERR_RETURN(!newlist, LOGMEM(module->ctx), -1);
for (i = module->ctx->models.size; i < module->ctx->models.size * 2; i++) {
newlist[i] = NULL;
}
module->ctx->models.size *= 2;
module->ctx->models.list = newlist;
}
module->ctx->models.list[module->ctx->models.used++] = module;
module->ctx->models.module_set_id++;
return 0;
}
/**
* Store UTF-8 character specified as 4byte integer into the dst buffer.
* Returns number of written bytes (4 max), expects that dst has enough space.
*
* UTF-8 mapping:
* 00000000 -- 0000007F: 0xxxxxxx
* 00000080 -- 000007FF: 110xxxxx 10xxxxxx
* 00000800 -- 0000FFFF: 1110xxxx 10xxxxxx 10xxxxxx
* 00010000 -- 001FFFFF: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
*
* Includes checking for valid characters (following RFC 7950, sec 9.4)
*/
unsigned int
pututf8(struct ly_ctx *ctx, char *dst, int32_t value)
{
if (value < 0x80) {
/* one byte character */
if (value < 0x20 &&
value != 0x09 &&
value != 0x0a &&
value != 0x0d) {
goto error;
}
dst[0] = value;
return 1;
} else if (value < 0x800) {
/* two bytes character */
dst[0] = 0xc0 | (value >> 6);
dst[1] = 0x80 | (value & 0x3f);
return 2;
} else if (value < 0xfffe) {
/* three bytes character */
if (((value & 0xf800) == 0xd800) ||
(value >= 0xfdd0 && value <= 0xfdef)) {
/* exclude surrogate blocks %xD800-DFFF */
/* exclude noncharacters %xFDD0-FDEF */
goto error;
}
dst[0] = 0xe0 | (value >> 12);
dst[1] = 0x80 | ((value >> 6) & 0x3f);
dst[2] = 0x80 | (value & 0x3f);
return 3;
} else if (value < 0x10fffe) {
if ((value & 0xffe) == 0xffe) {
/* exclude noncharacters %xFFFE-FFFF, %x1FFFE-1FFFF, %x2FFFE-2FFFF, %x3FFFE-3FFFF, %x4FFFE-4FFFF,
* %x5FFFE-5FFFF, %x6FFFE-6FFFF, %x7FFFE-7FFFF, %x8FFFE-8FFFF, %x9FFFE-9FFFF, %xAFFFE-AFFFF,
* %xBFFFE-BFFFF, %xCFFFE-CFFFF, %xDFFFE-DFFFF, %xEFFFE-EFFFF, %xFFFFE-FFFFF, %x10FFFE-10FFFF */
goto error;
}
/* four bytes character */
dst[0] = 0xf0 | (value >> 18);
dst[1] = 0x80 | ((value >> 12) & 0x3f);
dst[2] = 0x80 | ((value >> 6) & 0x3f);
dst[3] = 0x80 | (value & 0x3f);
return 4;
}
error:
/* out of range */
LOGVAL(ctx, LYE_XML_INCHAR, LY_VLOG_NONE, NULL, NULL);
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid UTF-8 value 0x%08x", value);
return 0;
}
unsigned int
copyutf8(struct ly_ctx *ctx, char *dst, const char *src)
{
uint32_t value;
/* unicode characters */
if (!(src[0] & 0x80)) {
/* one byte character */
if (src[0] < 0x20 &&
src[0] != 0x09 &&
src[0] != 0x0a &&
src[0] != 0x0d) {
LOGVAL(ctx, LYE_XML_INCHAR, LY_VLOG_NONE, NULL, src);
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid UTF-8 value 0x%02x", src[0]);
return 0;
}
dst[0] = src[0];
return 1;
} else if (!(src[0] & 0x20)) {
/* two bytes character */
dst[0] = src[0];
dst[1] = src[1];
return 2;
} else if (!(src[0] & 0x10)) {
/* three bytes character */
value = ((uint32_t)(src[0] & 0xf) << 12) | ((uint32_t)(src[1] & 0x3f) << 6) | (src[2] & 0x3f);
if (((value & 0xf800) == 0xd800) ||
(value >= 0xfdd0 && value <= 0xfdef) ||
(value & 0xffe) == 0xffe) {
/* exclude surrogate blocks %xD800-DFFF */
/* exclude noncharacters %xFDD0-FDEF */
/* exclude noncharacters %xFFFE-FFFF */
LOGVAL(ctx, LYE_XML_INCHAR, LY_VLOG_NONE, NULL, src);
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid UTF-8 value 0x%08x", value);
return 0;
}
dst[0] = src[0];
dst[1] = src[1];
dst[2] = src[2];
return 3;
} else if (!(src[0] & 0x08)) {
/* four bytes character */
value = ((uint32_t)(src[0] & 0x7) << 18) | ((uint32_t)(src[1] & 0x3f) << 12) | ((uint32_t)(src[2] & 0x3f) << 6) | (src[3] & 0x3f);
if ((value & 0xffe) == 0xffe) {
/* exclude noncharacters %x1FFFE-1FFFF, %x2FFFE-2FFFF, %x3FFFE-3FFFF, %x4FFFE-4FFFF,
* %x5FFFE-5FFFF, %x6FFFE-6FFFF, %x7FFFE-7FFFF, %x8FFFE-8FFFF, %x9FFFE-9FFFF, %xAFFFE-AFFFF,
* %xBFFFE-BFFFF, %xCFFFE-CFFFF, %xDFFFE-DFFFF, %xEFFFE-EFFFF, %xFFFFE-FFFFF, %x10FFFE-10FFFF */
LOGVAL(ctx, LYE_XML_INCHAR, LY_VLOG_NONE, NULL, src);
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid UTF-8 value 0x%08x", value);
return 0;
}
dst[0] = src[0];
dst[1] = src[1];
dst[2] = src[2];
dst[3] = src[3];
return 4;
} else {
LOGVAL(ctx, LYE_XML_INCHAR, LY_VLOG_NONE, NULL, src);
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid UTF-8 leading byte 0x%02x", src[0]);
return 0;
}
}
const struct lys_module *
lyp_get_module(const struct lys_module *module, const char *prefix, int pref_len, const char *name, int name_len, int in_data)
{
const struct lys_module *main_module;
char *str;
int i;
assert(!prefix || !name);
if (prefix && !pref_len) {
pref_len = strlen(prefix);
}
if (name && !name_len) {
name_len = strlen(name);
}
main_module = lys_main_module(module);
/* module own prefix, submodule own prefix, (sub)module own name */
if ((!prefix || (!module->type && !strncmp(main_module->prefix, prefix, pref_len) && !main_module->prefix[pref_len])
|| (module->type && !strncmp(module->prefix, prefix, pref_len) && !module->prefix[pref_len]))
&& (!name || (!strncmp(main_module->name, name, name_len) && !main_module->name[name_len]))) {
return main_module;
}
/* standard import */
for (i = 0; i < module->imp_size; ++i) {
if ((!prefix || (!strncmp(module->imp[i].prefix, prefix, pref_len) && !module->imp[i].prefix[pref_len]))
&& (!name || (!strncmp(module->imp[i].module->name, name, name_len) && !module->imp[i].module->name[name_len]))) {
return module->imp[i].module;
}
}
/* module required by a foreign grouping, deviation, or submodule */
if (name) {
str = strndup(name, name_len);
if (!str) {
LOGMEM(module->ctx);
return NULL;
}
main_module = ly_ctx_get_module(module->ctx, str, NULL, 0);
/* try data callback */
if (!main_module && in_data && module->ctx->data_clb) {
main_module = module->ctx->data_clb(module->ctx, str, NULL, 0, module->ctx->data_clb_data);
}
free(str);
return main_module;
}
return NULL;
}
const struct lys_module *
lyp_get_import_module_ns(const struct lys_module *module, const char *ns)
{
int i;
const struct lys_module *mod = NULL;
assert(module && ns);
if (module->type) {
/* the module is actually submodule and to get the namespace, we need the main module */
if (ly_strequal(((struct lys_submodule *)module)->belongsto->ns, ns, 0)) {
return ((struct lys_submodule *)module)->belongsto;
}
} else {
/* module's own namespace */
if (ly_strequal(module->ns, ns, 0)) {
return module;
}
}
/* imported modules */
for (i = 0; i < module->imp_size; ++i) {
if (ly_strequal(module->imp[i].module->ns, ns, 0)) {
return module->imp[i].module;
}
}
return mod;
}
const char *
lyp_get_yang_data_template_name(const struct lyd_node *node)
{
struct lys_node *snode;
snode = lys_parent(node->schema);
while (snode && snode->nodetype & (LYS_USES | LYS_CASE | LYS_CHOICE)) {
snode = lys_parent(snode);
}
if (snode && snode->nodetype == LYS_EXT && strcmp(((struct lys_ext_instance_complex *)snode)->def->name, "yang-data") == 0) {
return ((struct lys_ext_instance_complex *)snode)->arg_value;
} else {
return NULL;
}
}
const struct lys_node *
lyp_get_yang_data_template(const struct lys_module *module, const char *yang_data_name, int yang_data_name_len)
{
int i, j;
const struct lys_node *ret = NULL;
const struct lys_submodule *submodule;
for(i = 0; i < module->ext_size; ++i) {
if (!strcmp(module->ext[i]->def->name, "yang-data") && !strncmp(module->ext[i]->arg_value, yang_data_name, yang_data_name_len)
&& !module->ext[i]->arg_value[yang_data_name_len]) {
ret = (struct lys_node *)module->ext[i];
break;
}
}
for(j = 0; !ret && j < module->inc_size; ++j) {
submodule = module->inc[j].submodule;
for(i = 0; i < submodule->ext_size; ++i) {
if (!strcmp(submodule->ext[i]->def->name, "yang-data") && !strncmp(submodule->ext[i]->arg_value, yang_data_name, yang_data_name_len)
&& !submodule->ext[i]->arg_value[yang_data_name_len]) {
ret = (struct lys_node *)submodule->ext[i];
break;
}
}
}
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_1288_0 |
crossvul-cpp_data_good_3172_0 | /*
* file.c -- functions for dealing with file output
*
* Copyright (C)1999-2006 Mark Simpson <damned@theworld.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"
#include "date.h"
#include "debug.h"
#include "file.h"
#include "mapi_attr.h"
#include "options.h"
#include "path.h"
#define TNEF_DEFAULT_FILENAME "tnef-tmp"
/* ask user for confirmation of the action */
static int
confirm_action (const char *prompt, ...)
{
if (INTERACTIVE)
{
int confirmed = 0;
char buf[BUFSIZ + 1];
va_list args;
va_start (args, prompt);
VPRINTF(stdout, prompt, args);
fgets (buf, BUFSIZ, stdin);
if (buf[0] == 'y' || buf[0] == 'Y') confirmed = 1;
va_end (args);
return confirmed;
}
return 1;
}
void
file_write (File *file, const char* directory)
{
char *path = NULL;
assert (file);
if (!file) return;
if (file->name == NULL)
{
file->name = strdup( TNEF_DEFAULT_FILENAME );
debug_print ("No file name specified, using default %s.\n", TNEF_DEFAULT_FILENAME);
}
if ( file->path == NULL )
{
file->path = munge_fname( file->name );
if (file->path == NULL)
{
file->path = strdup( TNEF_DEFAULT_FILENAME );
debug_print ("No path name available, using default %s.\n", TNEF_DEFAULT_FILENAME);
}
}
path = concat_fname( directory, file->path );
if (path == NULL)
{
path = strdup( TNEF_DEFAULT_FILENAME );
debug_print ("No path generated, using default %s.\n", TNEF_DEFAULT_FILENAME);
}
debug_print ("%sWRITING\t|\t%s\t|\t%s\n",
((LIST_ONLY==0)?"":"NOT "), file->name, path);
if (!LIST_ONLY)
{
FILE *fp = NULL;
if (!confirm_action ("extract %s?", file->name)) return;
if (!OVERWRITE_FILES)
{
if (file_exists (path))
{
if (!NUMBER_FILES)
{
fprintf (stderr,
"tnef: %s: Could not create file: File exists\n",
path);
return;
}
else
{
char *tmp = find_free_number (path);
debug_print ("Renaming %s to %s\n", path, tmp);
XFREE (path);
path = tmp;
}
}
}
fp = fopen (path, "wb");
if (fp == NULL)
{
perror (path);
exit (1);
}
if (fwrite (file->data, 1, file->len, fp) != file->len)
{
perror (path);
exit (1);
}
fclose (fp);
}
if (LIST_ONLY || VERBOSE_ON)
{
if (LIST_ONLY && VERBOSE_ON)
{
/* FIXME: print out date and stuff */
const char *date_str = date_to_str(&file->dt);
fprintf (stdout, "%11lu\t|\t%s\t|\t%s\t|\t%s",
(unsigned long)file->len,
date_str+4, /* skip the day of week */
file->name,
path);
}
else
{
fprintf (stdout, "%s\t|\t%s", file->name, path);
}
if ( SHOW_MIME )
{
fprintf (stdout, "\t|\t%s", file->mime_type ? file->mime_type : "unknown");
fprintf (stdout, "\t|\t%s", file->content_id ? file->content_id : "");
}
fprintf (stdout, "\n");
}
XFREE(path);
}
static void
file_add_mapi_attrs (File* file, MAPI_Attr** attrs)
{
int i;
for (i = 0; attrs[i]; i++)
{
MAPI_Attr* a = attrs[i];
if (a->num_values)
{
switch (a->name)
{
case MAPI_ATTACH_LONG_FILENAME:
assert(a->type == szMAPI_STRING);
if (file->name) XFREE(file->name);
file->name = strdup( (char*)a->values[0].data.buf );
break;
case MAPI_ATTACH_DATA_OBJ:
assert((a->type == szMAPI_BINARY) || (a->type == szMAPI_OBJECT));
file->len = a->values[0].len;
if (file->data) XFREE (file->data);
file->data = CHECKED_XMALLOC (unsigned char, file->len);
memmove (file->data, a->values[0].data.buf, file->len);
break;
case MAPI_ATTACH_MIME_TAG:
assert(a->type == szMAPI_STRING);
if (file->mime_type) XFREE (file->mime_type);
file->mime_type = CHECKED_XMALLOC (char, a->values[0].len);
memmove (file->mime_type, a->values[0].data.buf, a->values[0].len);
break;
case MAPI_ATTACH_CONTENT_ID:
assert(a->type == szMAPI_STRING);
if (file->content_id) XFREE(file->content_id);
file->content_id = CHECKED_XMALLOC (char, a->values[0].len);
memmove (file->content_id, a->values[0].data.buf, a->values[0].len);
break;
default:
break;
}
}
}
}
void
file_add_attr (File* file, Attr* attr)
{
assert (file && attr);
if (!(file && attr)) return;
/* we only care about some things... we will skip most attributes */
switch (attr->name)
{
case attATTACHMODIFYDATE:
copy_date_from_attr (attr, &file->dt);
break;
case attATTACHMENT:
{
MAPI_Attr **mapi_attrs = mapi_attr_read (attr->len, attr->buf);
if (mapi_attrs)
{
file_add_mapi_attrs (file, mapi_attrs);
mapi_attr_free_list (mapi_attrs);
XFREE (mapi_attrs);
}
}
break;
case attATTACHTITLE:
file->name = strdup( (char*)attr->buf );
break;
case attATTACHDATA:
file->len = attr->len;
file->data = CHECKED_XMALLOC(unsigned char, attr->len);
memmove (file->data, attr->buf, attr->len);
break;
default:
break;
}
}
void
file_free (File *file)
{
if (file)
{
XFREE (file->name);
XFREE (file->data);
XFREE (file->mime_type);
XFREE (file->content_id);
XFREE (file->path);
memset (file, '\0', sizeof (File));
}
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_3172_0 |
crossvul-cpp_data_good_5474_2 | /* $Id$ */
/*
* Copyright (c) 1988-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.
*
* Scanline-oriented Write Support
*/
#include "tiffiop.h"
#include <stdio.h>
#define STRIPINCR 20 /* expansion factor on strip array */
#define WRITECHECKSTRIPS(tif, module) \
(((tif)->tif_flags&TIFF_BEENWRITING) || TIFFWriteCheck((tif),0,module))
#define WRITECHECKTILES(tif, module) \
(((tif)->tif_flags&TIFF_BEENWRITING) || TIFFWriteCheck((tif),1,module))
#define BUFFERCHECK(tif) \
((((tif)->tif_flags & TIFF_BUFFERSETUP) && tif->tif_rawdata) || \
TIFFWriteBufferSetup((tif), NULL, (tmsize_t) -1))
static int TIFFGrowStrips(TIFF* tif, uint32 delta, const char* module);
static int TIFFAppendToStrip(TIFF* tif, uint32 strip, uint8* data, tmsize_t cc);
int
TIFFWriteScanline(TIFF* tif, void* buf, uint32 row, uint16 sample)
{
static const char module[] = "TIFFWriteScanline";
register TIFFDirectory *td;
int status, imagegrew = 0;
uint32 strip;
if (!WRITECHECKSTRIPS(tif, module))
return (-1);
/*
* Handle delayed allocation of data buffer. This
* permits it to be sized more intelligently (using
* directory information).
*/
if (!BUFFERCHECK(tif))
return (-1);
tif->tif_flags |= TIFF_BUF4WRITE; /* not strictly sure this is right*/
td = &tif->tif_dir;
/*
* Extend image length if needed
* (but only for PlanarConfig=1).
*/
if (row >= td->td_imagelength) { /* extend image */
if (td->td_planarconfig == PLANARCONFIG_SEPARATE) {
TIFFErrorExt(tif->tif_clientdata, module,
"Can not change \"ImageLength\" when using separate planes");
return (-1);
}
td->td_imagelength = row+1;
imagegrew = 1;
}
/*
* Calculate strip and check for crossings.
*/
if (td->td_planarconfig == PLANARCONFIG_SEPARATE) {
if (sample >= td->td_samplesperpixel) {
TIFFErrorExt(tif->tif_clientdata, module,
"%lu: Sample out of range, max %lu",
(unsigned long) sample, (unsigned long) td->td_samplesperpixel);
return (-1);
}
strip = sample*td->td_stripsperimage + row/td->td_rowsperstrip;
} else
strip = row / td->td_rowsperstrip;
/*
* Check strip array to make sure there's space. We don't support
* dynamically growing files that have data organized in separate
* bitplanes because it's too painful. In that case we require that
* the imagelength be set properly before the first write (so that the
* strips array will be fully allocated above).
*/
if (strip >= td->td_nstrips && !TIFFGrowStrips(tif, 1, module))
return (-1);
if (strip != tif->tif_curstrip) {
/*
* Changing strips -- flush any data present.
*/
if (!TIFFFlushData(tif))
return (-1);
tif->tif_curstrip = strip;
/*
* Watch out for a growing image. The value of strips/image
* will initially be 1 (since it can't be deduced until the
* imagelength is known).
*/
if (strip >= td->td_stripsperimage && imagegrew)
td->td_stripsperimage =
TIFFhowmany_32(td->td_imagelength,td->td_rowsperstrip);
if (td->td_stripsperimage == 0) {
TIFFErrorExt(tif->tif_clientdata, module, "Zero strips per image");
return (-1);
}
tif->tif_row =
(strip % td->td_stripsperimage) * td->td_rowsperstrip;
if ((tif->tif_flags & TIFF_CODERSETUP) == 0) {
if (!(*tif->tif_setupencode)(tif))
return (-1);
tif->tif_flags |= TIFF_CODERSETUP;
}
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
if( td->td_stripbytecount[strip] > 0 )
{
/* if we are writing over existing tiles, zero length */
td->td_stripbytecount[strip] = 0;
/* this forces TIFFAppendToStrip() to do a seek */
tif->tif_curoff = 0;
}
if (!(*tif->tif_preencode)(tif, sample))
return (-1);
tif->tif_flags |= TIFF_POSTENCODE;
}
/*
* Ensure the write is either sequential or at the
* beginning of a strip (or that we can randomly
* access the data -- i.e. no encoding).
*/
if (row != tif->tif_row) {
if (row < tif->tif_row) {
/*
* Moving backwards within the same strip:
* backup to the start and then decode
* forward (below).
*/
tif->tif_row = (strip % td->td_stripsperimage) *
td->td_rowsperstrip;
tif->tif_rawcp = tif->tif_rawdata;
}
/*
* Seek forward to the desired row.
*/
if (!(*tif->tif_seek)(tif, row - tif->tif_row))
return (-1);
tif->tif_row = row;
}
/* swab if needed - note that source buffer will be altered */
tif->tif_postdecode( tif, (uint8*) buf, tif->tif_scanlinesize );
status = (*tif->tif_encoderow)(tif, (uint8*) buf,
tif->tif_scanlinesize, sample);
/* we are now poised at the beginning of the next row */
tif->tif_row = row + 1;
return (status);
}
/*
* Encode the supplied data and write it to the
* specified strip.
*
* NB: Image length must be setup before writing.
*/
tmsize_t
TIFFWriteEncodedStrip(TIFF* tif, uint32 strip, void* data, tmsize_t cc)
{
static const char module[] = "TIFFWriteEncodedStrip";
TIFFDirectory *td = &tif->tif_dir;
uint16 sample;
if (!WRITECHECKSTRIPS(tif, module))
return ((tmsize_t) -1);
/*
* Check strip array to make sure there's space.
* We don't support dynamically growing files that
* have data organized in separate bitplanes because
* it's too painful. In that case we require that
* the imagelength be set properly before the first
* write (so that the strips array will be fully
* allocated above).
*/
if (strip >= td->td_nstrips) {
if (td->td_planarconfig == PLANARCONFIG_SEPARATE) {
TIFFErrorExt(tif->tif_clientdata, module,
"Can not grow image by strips when using separate planes");
return ((tmsize_t) -1);
}
if (!TIFFGrowStrips(tif, 1, module))
return ((tmsize_t) -1);
td->td_stripsperimage =
TIFFhowmany_32(td->td_imagelength, td->td_rowsperstrip);
}
/*
* Handle delayed allocation of data buffer. This
* permits it to be sized according to the directory
* info.
*/
if (!BUFFERCHECK(tif))
return ((tmsize_t) -1);
tif->tif_flags |= TIFF_BUF4WRITE;
tif->tif_curstrip = strip;
if (td->td_stripsperimage == 0) {
TIFFErrorExt(tif->tif_clientdata, module, "Zero strips per image");
return ((tmsize_t) -1);
}
tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip;
if ((tif->tif_flags & TIFF_CODERSETUP) == 0) {
if (!(*tif->tif_setupencode)(tif))
return ((tmsize_t) -1);
tif->tif_flags |= TIFF_CODERSETUP;
}
if( td->td_stripbytecount[strip] > 0 )
{
/* Make sure that at the first attempt of rewriting the tile, we will have */
/* more bytes available in the output buffer than the previous byte count, */
/* so that TIFFAppendToStrip() will detect the overflow when it is called the first */
/* time if the new compressed tile is bigger than the older one. (GDAL #4771) */
if( tif->tif_rawdatasize <= (tmsize_t)td->td_stripbytecount[strip] )
{
if( !(TIFFWriteBufferSetup(tif, NULL,
(tmsize_t)TIFFroundup_64((uint64)(td->td_stripbytecount[strip] + 1), 1024))) )
return ((tmsize_t)(-1));
}
/* Force TIFFAppendToStrip() to consider placing data at end
of file. */
tif->tif_curoff = 0;
}
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
tif->tif_flags &= ~TIFF_POSTENCODE;
/* shortcut to avoid an extra memcpy() */
if( td->td_compression == COMPRESSION_NONE )
{
/* swab if needed - note that source buffer will be altered */
tif->tif_postdecode( tif, (uint8*) data, cc );
if (!isFillOrder(tif, td->td_fillorder) &&
(tif->tif_flags & TIFF_NOBITREV) == 0)
TIFFReverseBits((uint8*) data, cc);
if (cc > 0 &&
!TIFFAppendToStrip(tif, strip, (uint8*) data, cc))
return ((tmsize_t) -1);
return (cc);
}
sample = (uint16)(strip / td->td_stripsperimage);
if (!(*tif->tif_preencode)(tif, sample))
return ((tmsize_t) -1);
/* swab if needed - note that source buffer will be altered */
tif->tif_postdecode( tif, (uint8*) data, cc );
if (!(*tif->tif_encodestrip)(tif, (uint8*) data, cc, sample))
return ((tmsize_t) -1);
if (!(*tif->tif_postencode)(tif))
return ((tmsize_t) -1);
if (!isFillOrder(tif, td->td_fillorder) &&
(tif->tif_flags & TIFF_NOBITREV) == 0)
TIFFReverseBits(tif->tif_rawdata, tif->tif_rawcc);
if (tif->tif_rawcc > 0 &&
!TIFFAppendToStrip(tif, strip, tif->tif_rawdata, tif->tif_rawcc))
return ((tmsize_t) -1);
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
return (cc);
}
/*
* Write the supplied data to the specified strip.
*
* NB: Image length must be setup before writing.
*/
tmsize_t
TIFFWriteRawStrip(TIFF* tif, uint32 strip, void* data, tmsize_t cc)
{
static const char module[] = "TIFFWriteRawStrip";
TIFFDirectory *td = &tif->tif_dir;
if (!WRITECHECKSTRIPS(tif, module))
return ((tmsize_t) -1);
/*
* Check strip array to make sure there's space.
* We don't support dynamically growing files that
* have data organized in separate bitplanes because
* it's too painful. In that case we require that
* the imagelength be set properly before the first
* write (so that the strips array will be fully
* allocated above).
*/
if (strip >= td->td_nstrips) {
if (td->td_planarconfig == PLANARCONFIG_SEPARATE) {
TIFFErrorExt(tif->tif_clientdata, module,
"Can not grow image by strips when using separate planes");
return ((tmsize_t) -1);
}
/*
* Watch out for a growing image. The value of
* strips/image will initially be 1 (since it
* can't be deduced until the imagelength is known).
*/
if (strip >= td->td_stripsperimage)
td->td_stripsperimage =
TIFFhowmany_32(td->td_imagelength,td->td_rowsperstrip);
if (!TIFFGrowStrips(tif, 1, module))
return ((tmsize_t) -1);
}
tif->tif_curstrip = strip;
if (td->td_stripsperimage == 0) {
TIFFErrorExt(tif->tif_clientdata, module,"Zero strips per image");
return ((tmsize_t) -1);
}
tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip;
return (TIFFAppendToStrip(tif, strip, (uint8*) data, cc) ?
cc : (tmsize_t) -1);
}
/*
* Write and compress a tile of data. The
* tile is selected by the (x,y,z,s) coordinates.
*/
tmsize_t
TIFFWriteTile(TIFF* tif, void* buf, uint32 x, uint32 y, uint32 z, uint16 s)
{
if (!TIFFCheckTile(tif, x, y, z, s))
return ((tmsize_t)(-1));
/*
* NB: A tile size of -1 is used instead of tif_tilesize knowing
* that TIFFWriteEncodedTile will clamp this to the tile size.
* This is done because the tile size may not be defined until
* after the output buffer is setup in TIFFWriteBufferSetup.
*/
return (TIFFWriteEncodedTile(tif,
TIFFComputeTile(tif, x, y, z, s), buf, (tmsize_t)(-1)));
}
/*
* Encode the supplied data and write it to the
* specified tile. There must be space for the
* data. The function clamps individual writes
* to a tile to the tile size, but does not (and
* can not) check that multiple writes to the same
* tile do not write more than tile size data.
*
* NB: Image length must be setup before writing; this
* interface does not support automatically growing
* the image on each write (as TIFFWriteScanline does).
*/
tmsize_t
TIFFWriteEncodedTile(TIFF* tif, uint32 tile, void* data, tmsize_t cc)
{
static const char module[] = "TIFFWriteEncodedTile";
TIFFDirectory *td;
uint16 sample;
uint32 howmany32;
if (!WRITECHECKTILES(tif, module))
return ((tmsize_t)(-1));
td = &tif->tif_dir;
if (tile >= td->td_nstrips) {
TIFFErrorExt(tif->tif_clientdata, module, "Tile %lu out of range, max %lu",
(unsigned long) tile, (unsigned long) td->td_nstrips);
return ((tmsize_t)(-1));
}
/*
* Handle delayed allocation of data buffer. This
* permits it to be sized more intelligently (using
* directory information).
*/
if (!BUFFERCHECK(tif))
return ((tmsize_t)(-1));
tif->tif_flags |= TIFF_BUF4WRITE;
tif->tif_curtile = tile;
if( td->td_stripbytecount[tile] > 0 )
{
/* Make sure that at the first attempt of rewriting the tile, we will have */
/* more bytes available in the output buffer than the previous byte count, */
/* so that TIFFAppendToStrip() will detect the overflow when it is called the first */
/* time if the new compressed tile is bigger than the older one. (GDAL #4771) */
if( tif->tif_rawdatasize <= (tmsize_t) td->td_stripbytecount[tile] )
{
if( !(TIFFWriteBufferSetup(tif, NULL,
(tmsize_t)TIFFroundup_64((uint64)(td->td_stripbytecount[tile] + 1), 1024))) )
return ((tmsize_t)(-1));
}
/* Force TIFFAppendToStrip() to consider placing data at end
of file. */
tif->tif_curoff = 0;
}
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
/*
* Compute tiles per row & per column to compute
* current row and column
*/
howmany32=TIFFhowmany_32(td->td_imagelength, td->td_tilelength);
if (howmany32 == 0) {
TIFFErrorExt(tif->tif_clientdata,module,"Zero tiles");
return ((tmsize_t)(-1));
}
tif->tif_row = (tile % howmany32) * td->td_tilelength;
howmany32=TIFFhowmany_32(td->td_imagewidth, td->td_tilewidth);
if (howmany32 == 0) {
TIFFErrorExt(tif->tif_clientdata,module,"Zero tiles");
return ((tmsize_t)(-1));
}
tif->tif_col = (tile % howmany32) * td->td_tilewidth;
if ((tif->tif_flags & TIFF_CODERSETUP) == 0) {
if (!(*tif->tif_setupencode)(tif))
return ((tmsize_t)(-1));
tif->tif_flags |= TIFF_CODERSETUP;
}
tif->tif_flags &= ~TIFF_POSTENCODE;
/*
* Clamp write amount to the tile size. This is mostly
* done so that callers can pass in some large number
* (e.g. -1) and have the tile size used instead.
*/
if ( cc < 1 || cc > tif->tif_tilesize)
cc = tif->tif_tilesize;
/* shortcut to avoid an extra memcpy() */
if( td->td_compression == COMPRESSION_NONE )
{
/* swab if needed - note that source buffer will be altered */
tif->tif_postdecode( tif, (uint8*) data, cc );
if (!isFillOrder(tif, td->td_fillorder) &&
(tif->tif_flags & TIFF_NOBITREV) == 0)
TIFFReverseBits((uint8*) data, cc);
if (cc > 0 &&
!TIFFAppendToStrip(tif, tile, (uint8*) data, cc))
return ((tmsize_t) -1);
return (cc);
}
sample = (uint16)(tile/td->td_stripsperimage);
if (!(*tif->tif_preencode)(tif, sample))
return ((tmsize_t)(-1));
/* swab if needed - note that source buffer will be altered */
tif->tif_postdecode( tif, (uint8*) data, cc );
if (!(*tif->tif_encodetile)(tif, (uint8*) data, cc, sample))
return ((tmsize_t) -1);
if (!(*tif->tif_postencode)(tif))
return ((tmsize_t)(-1));
if (!isFillOrder(tif, td->td_fillorder) &&
(tif->tif_flags & TIFF_NOBITREV) == 0)
TIFFReverseBits((uint8*)tif->tif_rawdata, tif->tif_rawcc);
if (tif->tif_rawcc > 0 && !TIFFAppendToStrip(tif, tile,
tif->tif_rawdata, tif->tif_rawcc))
return ((tmsize_t)(-1));
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
return (cc);
}
/*
* Write the supplied data to the specified strip.
* There must be space for the data; we don't check
* if strips overlap!
*
* NB: Image length must be setup before writing; this
* interface does not support automatically growing
* the image on each write (as TIFFWriteScanline does).
*/
tmsize_t
TIFFWriteRawTile(TIFF* tif, uint32 tile, void* data, tmsize_t cc)
{
static const char module[] = "TIFFWriteRawTile";
if (!WRITECHECKTILES(tif, module))
return ((tmsize_t)(-1));
if (tile >= tif->tif_dir.td_nstrips) {
TIFFErrorExt(tif->tif_clientdata, module, "Tile %lu out of range, max %lu",
(unsigned long) tile,
(unsigned long) tif->tif_dir.td_nstrips);
return ((tmsize_t)(-1));
}
return (TIFFAppendToStrip(tif, tile, (uint8*) data, cc) ?
cc : (tmsize_t)(-1));
}
#define isUnspecified(tif, f) \
(TIFFFieldSet(tif,f) && (tif)->tif_dir.td_imagelength == 0)
int
TIFFSetupStrips(TIFF* tif)
{
TIFFDirectory* td = &tif->tif_dir;
if (isTiled(tif))
td->td_stripsperimage =
isUnspecified(tif, FIELD_TILEDIMENSIONS) ?
td->td_samplesperpixel : TIFFNumberOfTiles(tif);
else
td->td_stripsperimage =
isUnspecified(tif, FIELD_ROWSPERSTRIP) ?
td->td_samplesperpixel : TIFFNumberOfStrips(tif);
td->td_nstrips = td->td_stripsperimage;
if (td->td_planarconfig == PLANARCONFIG_SEPARATE)
td->td_stripsperimage /= td->td_samplesperpixel;
td->td_stripoffset = (uint64 *)
_TIFFmalloc(td->td_nstrips * sizeof (uint64));
td->td_stripbytecount = (uint64 *)
_TIFFmalloc(td->td_nstrips * sizeof (uint64));
if (td->td_stripoffset == NULL || td->td_stripbytecount == NULL)
return (0);
/*
* Place data at the end-of-file
* (by setting offsets to zero).
*/
_TIFFmemset(td->td_stripoffset, 0, td->td_nstrips*sizeof (uint64));
_TIFFmemset(td->td_stripbytecount, 0, td->td_nstrips*sizeof (uint64));
TIFFSetFieldBit(tif, FIELD_STRIPOFFSETS);
TIFFSetFieldBit(tif, FIELD_STRIPBYTECOUNTS);
return (1);
}
#undef isUnspecified
/*
* Verify file is writable and that the directory
* information is setup properly. In doing the latter
* we also "freeze" the state of the directory so
* that important information is not changed.
*/
int
TIFFWriteCheck(TIFF* tif, int tiles, const char* module)
{
if (tif->tif_mode == O_RDONLY) {
TIFFErrorExt(tif->tif_clientdata, module, "File not open for writing");
return (0);
}
if (tiles ^ isTiled(tif)) {
TIFFErrorExt(tif->tif_clientdata, module, tiles ?
"Can not write tiles to a stripped image" :
"Can not write scanlines to a tiled image");
return (0);
}
_TIFFFillStriles( tif );
/*
* On the first write verify all the required information
* has been setup and initialize any data structures that
* had to wait until directory information was set.
* Note that a lot of our work is assumed to remain valid
* because we disallow any of the important parameters
* from changing after we start writing (i.e. once
* TIFF_BEENWRITING is set, TIFFSetField will only allow
* the image's length to be changed).
*/
if (!TIFFFieldSet(tif, FIELD_IMAGEDIMENSIONS)) {
TIFFErrorExt(tif->tif_clientdata, module,
"Must set \"ImageWidth\" before writing data");
return (0);
}
if (tif->tif_dir.td_samplesperpixel == 1) {
/*
* Planarconfiguration is irrelevant in case of single band
* images and need not be included. We will set it anyway,
* because this field is used in other parts of library even
* in the single band case.
*/
if (!TIFFFieldSet(tif, FIELD_PLANARCONFIG))
tif->tif_dir.td_planarconfig = PLANARCONFIG_CONTIG;
} else {
if (!TIFFFieldSet(tif, FIELD_PLANARCONFIG)) {
TIFFErrorExt(tif->tif_clientdata, module,
"Must set \"PlanarConfiguration\" before writing data");
return (0);
}
}
if (tif->tif_dir.td_stripoffset == NULL && !TIFFSetupStrips(tif)) {
tif->tif_dir.td_nstrips = 0;
TIFFErrorExt(tif->tif_clientdata, module, "No space for %s arrays",
isTiled(tif) ? "tile" : "strip");
return (0);
}
if (isTiled(tif))
{
tif->tif_tilesize = TIFFTileSize(tif);
if (tif->tif_tilesize == 0)
return (0);
}
else
tif->tif_tilesize = (tmsize_t)(-1);
tif->tif_scanlinesize = TIFFScanlineSize(tif);
if (tif->tif_scanlinesize == 0)
return (0);
tif->tif_flags |= TIFF_BEENWRITING;
return (1);
}
/*
* Setup the raw data buffer used for encoding.
*/
int
TIFFWriteBufferSetup(TIFF* tif, void* bp, tmsize_t size)
{
static const char module[] = "TIFFWriteBufferSetup";
if (tif->tif_rawdata) {
if (tif->tif_flags & TIFF_MYBUFFER) {
_TIFFfree(tif->tif_rawdata);
tif->tif_flags &= ~TIFF_MYBUFFER;
}
tif->tif_rawdata = NULL;
}
if (size == (tmsize_t)(-1)) {
size = (isTiled(tif) ?
tif->tif_tilesize : TIFFStripSize(tif));
/*
* Make raw data buffer at least 8K
*/
if (size < 8*1024)
size = 8*1024;
bp = NULL; /* NB: force malloc */
}
if (bp == NULL) {
bp = _TIFFmalloc(size);
if (bp == NULL) {
TIFFErrorExt(tif->tif_clientdata, module, "No space for output buffer");
return (0);
}
tif->tif_flags |= TIFF_MYBUFFER;
} else
tif->tif_flags &= ~TIFF_MYBUFFER;
tif->tif_rawdata = (uint8*) bp;
tif->tif_rawdatasize = size;
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
tif->tif_flags |= TIFF_BUFFERSETUP;
return (1);
}
/*
* Grow the strip data structures by delta strips.
*/
static int
TIFFGrowStrips(TIFF* tif, uint32 delta, const char* module)
{
TIFFDirectory *td = &tif->tif_dir;
uint64* new_stripoffset;
uint64* new_stripbytecount;
assert(td->td_planarconfig == PLANARCONFIG_CONTIG);
new_stripoffset = (uint64*)_TIFFrealloc(td->td_stripoffset,
(td->td_nstrips + delta) * sizeof (uint64));
new_stripbytecount = (uint64*)_TIFFrealloc(td->td_stripbytecount,
(td->td_nstrips + delta) * sizeof (uint64));
if (new_stripoffset == NULL || new_stripbytecount == NULL) {
if (new_stripoffset)
_TIFFfree(new_stripoffset);
if (new_stripbytecount)
_TIFFfree(new_stripbytecount);
td->td_nstrips = 0;
TIFFErrorExt(tif->tif_clientdata, module, "No space to expand strip arrays");
return (0);
}
td->td_stripoffset = new_stripoffset;
td->td_stripbytecount = new_stripbytecount;
_TIFFmemset(td->td_stripoffset + td->td_nstrips,
0, delta*sizeof (uint64));
_TIFFmemset(td->td_stripbytecount + td->td_nstrips,
0, delta*sizeof (uint64));
td->td_nstrips += delta;
tif->tif_flags |= TIFF_DIRTYDIRECT;
return (1);
}
/*
* Append the data to the specified strip.
*/
static int
TIFFAppendToStrip(TIFF* tif, uint32 strip, uint8* data, tmsize_t cc)
{
static const char module[] = "TIFFAppendToStrip";
TIFFDirectory *td = &tif->tif_dir;
uint64 m;
int64 old_byte_count = -1;
if (td->td_stripoffset[strip] == 0 || tif->tif_curoff == 0) {
assert(td->td_nstrips > 0);
if( td->td_stripbytecount[strip] != 0
&& td->td_stripoffset[strip] != 0
&& td->td_stripbytecount[strip] >= (uint64) cc )
{
/*
* There is already tile data on disk, and the new tile
* data we have will fit in the same space. The only
* aspect of this that is risky is that there could be
* more data to append to this strip before we are done
* depending on how we are getting called.
*/
if (!SeekOK(tif, td->td_stripoffset[strip])) {
TIFFErrorExt(tif->tif_clientdata, module,
"Seek error at scanline %lu",
(unsigned long)tif->tif_row);
return (0);
}
}
else
{
/*
* Seek to end of file, and set that as our location to
* write this strip.
*/
td->td_stripoffset[strip] = TIFFSeekFile(tif, 0, SEEK_END);
tif->tif_flags |= TIFF_DIRTYSTRIP;
}
tif->tif_curoff = td->td_stripoffset[strip];
/*
* We are starting a fresh strip/tile, so set the size to zero.
*/
old_byte_count = td->td_stripbytecount[strip];
td->td_stripbytecount[strip] = 0;
}
m = tif->tif_curoff+cc;
if (!(tif->tif_flags&TIFF_BIGTIFF))
m = (uint32)m;
if ((m<tif->tif_curoff)||(m<(uint64)cc))
{
TIFFErrorExt(tif->tif_clientdata, module, "Maximum TIFF file size exceeded");
return (0);
}
if (!WriteOK(tif, data, cc)) {
TIFFErrorExt(tif->tif_clientdata, module, "Write error at scanline %lu",
(unsigned long) tif->tif_row);
return (0);
}
tif->tif_curoff = m;
td->td_stripbytecount[strip] += cc;
if( (int64) td->td_stripbytecount[strip] != old_byte_count )
tif->tif_flags |= TIFF_DIRTYSTRIP;
return (1);
}
/*
* Internal version of TIFFFlushData that can be
* called by ``encodestrip routines'' w/o concern
* for infinite recursion.
*/
int
TIFFFlushData1(TIFF* tif)
{
if (tif->tif_rawcc > 0 && tif->tif_flags & TIFF_BUF4WRITE ) {
if (!isFillOrder(tif, tif->tif_dir.td_fillorder) &&
(tif->tif_flags & TIFF_NOBITREV) == 0)
TIFFReverseBits((uint8*)tif->tif_rawdata,
tif->tif_rawcc);
if (!TIFFAppendToStrip(tif,
isTiled(tif) ? tif->tif_curtile : tif->tif_curstrip,
tif->tif_rawdata, tif->tif_rawcc))
{
/* We update those variables even in case of error since there's */
/* code that doesn't really check the return code of this */
/* function */
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
return (0);
}
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
}
return (1);
}
/*
* Set the current write offset. This should only be
* used to set the offset to a known previous location
* (very carefully), or to 0 so that the next write gets
* appended to the end of the file.
*/
void
TIFFSetWriteOffset(TIFF* tif, toff_t off)
{
tif->tif_curoff = off;
}
/* 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-787/c/good_5474_2 |
crossvul-cpp_data_good_2758_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) 2008, Jerome Fimes, Communications & Systemes <jerome.fimes@c-s.fr>
* Copyright (c) 2006-2007, Parvatha Elangovan
* Copyright (c) 2010-2011, Kaori Hagihara
* Copyright (c) 2011-2012, Centre National d'Etudes Spatiales (CNES), France
* 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"
/** @defgroup J2K J2K - JPEG-2000 codestream reader/writer */
/*@{*/
/** @name Local static functions */
/*@{*/
#define OPJ_UNUSED(x) (void)x
/**
* Sets up the procedures to do on reading header. Developpers wanting to extend the library can add their own reading procedures.
*/
static OPJ_BOOL opj_j2k_setup_header_reading(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager);
/**
* The read header procedure.
*/
static OPJ_BOOL opj_j2k_read_header_procedure(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* The default encoding validation procedure without any extension.
*
* @param p_j2k the jpeg2000 codec to validate.
* @param p_stream the input stream to validate.
* @param p_manager the user event manager.
*
* @return true if the parameters are correct.
*/
static OPJ_BOOL opj_j2k_encoding_validation(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* The default decoding validation procedure without any extension.
*
* @param p_j2k the jpeg2000 codec to validate.
* @param p_stream the input stream to validate.
* @param p_manager the user event manager.
*
* @return true if the parameters are correct.
*/
static OPJ_BOOL opj_j2k_decoding_validation(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Sets up the validation ,i.e. adds the procedures to lauch to make sure the codec parameters
* are valid. Developpers wanting to extend the library can add their own validation procedures.
*/
static OPJ_BOOL opj_j2k_setup_encoding_validation(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager);
/**
* Sets up the validation ,i.e. adds the procedures to lauch to make sure the codec parameters
* are valid. Developpers wanting to extend the library can add their own validation procedures.
*/
static OPJ_BOOL opj_j2k_setup_decoding_validation(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager);
/**
* Sets up the validation ,i.e. adds the procedures to lauch to make sure the codec parameters
* are valid. Developpers wanting to extend the library can add their own validation procedures.
*/
static OPJ_BOOL opj_j2k_setup_end_compress(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager);
/**
* The mct encoding validation procedure.
*
* @param p_j2k the jpeg2000 codec to validate.
* @param p_stream the input stream to validate.
* @param p_manager the user event manager.
*
* @return true if the parameters are correct.
*/
static OPJ_BOOL opj_j2k_mct_validation(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Builds the tcd decoder to use to decode tile.
*/
static OPJ_BOOL opj_j2k_build_decoder(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Builds the tcd encoder to use to encode tile.
*/
static OPJ_BOOL opj_j2k_build_encoder(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Creates a tile-coder decoder.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_create_tcd(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Excutes the given procedures on the given codec.
*
* @param p_procedure_list the list of procedures to execute
* @param p_j2k the jpeg2000 codec to execute the procedures on.
* @param p_stream the stream to execute the procedures on.
* @param p_manager the user manager.
*
* @return true if all the procedures were successfully executed.
*/
static OPJ_BOOL opj_j2k_exec(opj_j2k_t * p_j2k,
opj_procedure_list_t * p_procedure_list,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Updates the rates of the tcp.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_update_rates(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Copies the decoding tile parameters onto all the tile parameters.
* Creates also the tile decoder.
*/
static OPJ_BOOL opj_j2k_copy_default_tcp_and_create_tcd(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Destroys the memory associated with the decoding of headers.
*/
static OPJ_BOOL opj_j2k_destroy_header_memory(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads the lookup table containing all the marker, status and action, and returns the handler associated
* with the marker value.
* @param p_id Marker value to look up
*
* @return the handler associated with the id.
*/
static const struct opj_dec_memory_marker_handler * opj_j2k_get_marker_handler(
OPJ_UINT32 p_id);
/**
* Destroys a tile coding parameter structure.
*
* @param p_tcp the tile coding parameter to destroy.
*/
static void opj_j2k_tcp_destroy(opj_tcp_t *p_tcp);
/**
* Destroys the data inside a tile coding parameter structure.
*
* @param p_tcp the tile coding parameter which contain data to destroy.
*/
static void opj_j2k_tcp_data_destroy(opj_tcp_t *p_tcp);
/**
* Destroys a coding parameter structure.
*
* @param p_cp the coding parameter to destroy.
*/
static void opj_j2k_cp_destroy(opj_cp_t *p_cp);
/**
* Compare 2 a SPCod/ SPCoc elements, i.e. the coding style of a given component of a tile.
*
* @param p_j2k J2K codec.
* @param p_tile_no Tile number
* @param p_first_comp_no The 1st component number to compare.
* @param p_second_comp_no The 1st component number to compare.
*
* @return OPJ_TRUE if SPCdod are equals.
*/
static OPJ_BOOL opj_j2k_compare_SPCod_SPCoc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no);
/**
* Writes a SPCod or SPCoc element, i.e. the coding style of a given component of a tile.
*
* @param p_j2k J2K codec.
* @param p_tile_no FIXME DOC
* @param p_comp_no the component number to output.
* @param p_data FIXME DOC
* @param p_header_size FIXME DOC
* @param p_manager the user event manager.
*
* @return FIXME DOC
*/
static OPJ_BOOL opj_j2k_write_SPCod_SPCoc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_header_size,
opj_event_mgr_t * p_manager);
/**
* Gets the size taken by writing a SPCod or SPCoc for the given tile and component.
*
* @param p_j2k the J2K codec.
* @param p_tile_no the tile index.
* @param p_comp_no the component being outputted.
*
* @return the number of bytes taken by the SPCod element.
*/
static OPJ_UINT32 opj_j2k_get_SPCod_SPCoc_size(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no);
/**
* Reads a SPCod or SPCoc element, i.e. the coding style of a given component of a tile.
* @param p_j2k the jpeg2000 codec.
* @param compno FIXME DOC
* @param p_header_data the data contained in the COM box.
* @param p_header_size the size of the data contained in the COM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_SPCod_SPCoc(opj_j2k_t *p_j2k,
OPJ_UINT32 compno,
OPJ_BYTE * p_header_data,
OPJ_UINT32 * p_header_size,
opj_event_mgr_t * p_manager);
/**
* Gets the size taken by writing SQcd or SQcc element, i.e. the quantization values of a band in the QCD or QCC.
*
* @param p_tile_no the tile index.
* @param p_comp_no the component being outputted.
* @param p_j2k the J2K codec.
*
* @return the number of bytes taken by the SPCod element.
*/
static OPJ_UINT32 opj_j2k_get_SQcd_SQcc_size(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no);
/**
* Compares 2 SQcd or SQcc element, i.e. the quantization values of a band in the QCD or QCC.
*
* @param p_j2k J2K codec.
* @param p_tile_no the tile to output.
* @param p_first_comp_no the first component number to compare.
* @param p_second_comp_no the second component number to compare.
*
* @return OPJ_TRUE if equals.
*/
static OPJ_BOOL opj_j2k_compare_SQcd_SQcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no);
/**
* Writes a SQcd or SQcc element, i.e. the quantization values of a band in the QCD or QCC.
*
* @param p_tile_no the tile to output.
* @param p_comp_no the component number to output.
* @param p_data the data buffer.
* @param p_header_size pointer to the size of the data buffer, it is changed by the function.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*
*/
static OPJ_BOOL opj_j2k_write_SQcd_SQcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_header_size,
opj_event_mgr_t * p_manager);
/**
* Updates the Tile Length Marker.
*/
static void opj_j2k_update_tlm(opj_j2k_t * p_j2k, OPJ_UINT32 p_tile_part_size);
/**
* Reads a SQcd or SQcc element, i.e. the quantization values of a band in the QCD or QCC.
*
* @param p_j2k J2K codec.
* @param compno the component number to output.
* @param p_header_data the data buffer.
* @param p_header_size pointer to the size of the data buffer, it is changed by the function.
* @param p_manager the user event manager.
*
*/
static OPJ_BOOL opj_j2k_read_SQcd_SQcc(opj_j2k_t *p_j2k,
OPJ_UINT32 compno,
OPJ_BYTE * p_header_data,
OPJ_UINT32 * p_header_size,
opj_event_mgr_t * p_manager);
/**
* Copies the tile component parameters of all the component from the first tile component.
*
* @param p_j2k the J2k codec.
*/
static void opj_j2k_copy_tile_component_parameters(opj_j2k_t *p_j2k);
/**
* Copies the tile quantization parameters of all the component from the first tile component.
*
* @param p_j2k the J2k codec.
*/
static void opj_j2k_copy_tile_quantization_parameters(opj_j2k_t *p_j2k);
/**
* Reads the tiles.
*/
static OPJ_BOOL opj_j2k_decode_tiles(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
static OPJ_BOOL opj_j2k_pre_write_tile(opj_j2k_t * p_j2k,
OPJ_UINT32 p_tile_index,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
static OPJ_BOOL opj_j2k_update_image_data(opj_tcd_t * p_tcd, OPJ_BYTE * p_data,
opj_image_t* p_output_image);
static void opj_get_tile_dimensions(opj_image_t * l_image,
opj_tcd_tilecomp_t * l_tilec,
opj_image_comp_t * l_img_comp,
OPJ_UINT32* l_size_comp,
OPJ_UINT32* l_width,
OPJ_UINT32* l_height,
OPJ_UINT32* l_offset_x,
OPJ_UINT32* l_offset_y,
OPJ_UINT32* l_image_width,
OPJ_UINT32* l_stride,
OPJ_UINT32* l_tile_offset);
static void opj_j2k_get_tile_data(opj_tcd_t * p_tcd, OPJ_BYTE * p_data);
static OPJ_BOOL opj_j2k_post_write_tile(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Sets up the procedures to do on writing header.
* Developers wanting to extend the library can add their own writing procedures.
*/
static OPJ_BOOL opj_j2k_setup_header_writing(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager);
static OPJ_BOOL opj_j2k_write_first_tile_part(opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_total_data_size,
opj_stream_private_t *p_stream,
struct opj_event_mgr * p_manager);
static OPJ_BOOL opj_j2k_write_all_tile_parts(opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_total_data_size,
opj_stream_private_t *p_stream,
struct opj_event_mgr * p_manager);
/**
* Gets the offset of the header.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_get_end_header(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
static OPJ_BOOL opj_j2k_allocate_tile_element_cstr_index(opj_j2k_t *p_j2k);
/*
* -----------------------------------------------------------------------
* -----------------------------------------------------------------------
* -----------------------------------------------------------------------
*/
/**
* Writes the SOC marker (Start Of Codestream)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_soc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a SOC marker (Start of Codestream)
* @param p_j2k the jpeg2000 file codec.
* @param p_stream XXX needs data
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_soc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes the SIZ marker (image and tile size)
*
* @param p_j2k J2K codec.
* @param p_stream the stream to write data to.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_siz(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a SIZ marker (image and tile size)
* @param p_j2k the jpeg2000 file codec.
* @param p_header_data the data contained in the SIZ box.
* @param p_header_size the size of the data contained in the SIZ marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_siz(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the COM marker (comment)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_com(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a COM marker (comments)
* @param p_j2k the jpeg2000 file codec.
* @param p_header_data the data contained in the COM box.
* @param p_header_size the size of the data contained in the COM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_com(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the COD marker (Coding style default)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_cod(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a COD marker (Coding Styke defaults)
* @param p_header_data the data contained in the COD box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the COD marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_cod(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Compares 2 COC markers (Coding style component)
*
* @param p_j2k J2K codec.
* @param p_first_comp_no the index of the first component to compare.
* @param p_second_comp_no the index of the second component to compare.
*
* @return OPJ_TRUE if equals
*/
static OPJ_BOOL opj_j2k_compare_coc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no);
/**
* Writes the COC marker (Coding style component)
*
* @param p_j2k J2K codec.
* @param p_comp_no the index of the component to output.
* @param p_stream the stream to write data to.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_coc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes the COC marker (Coding style component)
*
* @param p_j2k J2K codec.
* @param p_comp_no the index of the component to output.
* @param p_data FIXME DOC
* @param p_data_written FIXME DOC
* @param p_manager the user event manager.
*/
static void opj_j2k_write_coc_in_memory(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
opj_event_mgr_t * p_manager);
/**
* Gets the maximum size taken by a coc.
*
* @param p_j2k the jpeg2000 codec to use.
*/
static OPJ_UINT32 opj_j2k_get_max_coc_size(opj_j2k_t *p_j2k);
/**
* Reads a COC marker (Coding Style Component)
* @param p_header_data the data contained in the COC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the COC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_coc(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the QCD marker (quantization default)
*
* @param p_j2k J2K codec.
* @param p_stream the stream to write data to.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_qcd(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a QCD marker (Quantization defaults)
* @param p_header_data the data contained in the QCD box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the QCD marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_qcd(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Compare QCC markers (quantization component)
*
* @param p_j2k J2K codec.
* @param p_first_comp_no the index of the first component to compare.
* @param p_second_comp_no the index of the second component to compare.
*
* @return OPJ_TRUE if equals.
*/
static OPJ_BOOL opj_j2k_compare_qcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no);
/**
* Writes the QCC marker (quantization component)
*
* @param p_comp_no the index of the component to output.
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_qcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes the QCC marker (quantization component)
*
* @param p_j2k J2K codec.
* @param p_comp_no the index of the component to output.
* @param p_data FIXME DOC
* @param p_data_written the stream to write data to.
* @param p_manager the user event manager.
*/
static void opj_j2k_write_qcc_in_memory(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
opj_event_mgr_t * p_manager);
/**
* Gets the maximum size taken by a qcc.
*/
static OPJ_UINT32 opj_j2k_get_max_qcc_size(opj_j2k_t *p_j2k);
/**
* Reads a QCC marker (Quantization component)
* @param p_header_data the data contained in the QCC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the QCC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_qcc(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the POC marker (Progression Order Change)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_poc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes the POC marker (Progression Order Change)
*
* @param p_j2k J2K codec.
* @param p_data FIXME DOC
* @param p_data_written the stream to write data to.
* @param p_manager the user event manager.
*/
static void opj_j2k_write_poc_in_memory(opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
opj_event_mgr_t * p_manager);
/**
* Gets the maximum size taken by the writing of a POC.
*/
static OPJ_UINT32 opj_j2k_get_max_poc_size(opj_j2k_t *p_j2k);
/**
* Reads a POC marker (Progression Order Change)
*
* @param p_header_data the data contained in the POC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the POC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_poc(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Gets the maximum size taken by the toc headers of all the tile parts of any given tile.
*/
static OPJ_UINT32 opj_j2k_get_max_toc_size(opj_j2k_t *p_j2k);
/**
* Gets the maximum size taken by the headers of the SOT.
*
* @param p_j2k the jpeg2000 codec to use.
*/
static OPJ_UINT32 opj_j2k_get_specific_header_sizes(opj_j2k_t *p_j2k);
/**
* Reads a CRG marker (Component registration)
*
* @param p_header_data the data contained in the TLM box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the TLM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_crg(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Reads a TLM marker (Tile Length Marker)
*
* @param p_header_data the data contained in the TLM box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the TLM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_tlm(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the updated tlm.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_updated_tlm(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a PLM marker (Packet length, main header marker)
*
* @param p_header_data the data contained in the TLM box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the TLM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_plm(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Reads a PLT marker (Packet length, tile-part header)
*
* @param p_header_data the data contained in the PLT box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the PLT marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_plt(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Reads a PPM marker (Packed headers, main header)
*
* @param p_header_data the data contained in the POC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the POC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_ppm(
opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Merges all PPM markers read (Packed headers, main header)
*
* @param p_cp main coding parameters.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_merge_ppm(opj_cp_t *p_cp, opj_event_mgr_t * p_manager);
/**
* Reads a PPT marker (Packed packet headers, tile-part header)
*
* @param p_header_data the data contained in the PPT box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the PPT marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_ppt(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Merges all PPT markers read (Packed headers, tile-part header)
*
* @param p_tcp the tile.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_merge_ppt(opj_tcp_t *p_tcp,
opj_event_mgr_t * p_manager);
/**
* Writes the TLM marker (Tile Length Marker)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_tlm(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes the SOT marker (Start of tile-part)
*
* @param p_j2k J2K codec.
* @param p_data Output buffer
* @param p_total_data_size Output buffer size
* @param p_data_written Number of bytes written into stream
* @param p_stream the stream to write data to.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_sot(opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 p_total_data_size,
OPJ_UINT32 * p_data_written,
const opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads values from a SOT marker (Start of tile-part)
*
* the j2k decoder state is not affected. No side effects, no checks except for p_header_size.
*
* @param p_header_data the data contained in the SOT marker.
* @param p_header_size the size of the data contained in the SOT marker.
* @param p_tile_no Isot.
* @param p_tot_len Psot.
* @param p_current_part TPsot.
* @param p_num_parts TNsot.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_get_sot_values(OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
OPJ_UINT32* p_tile_no,
OPJ_UINT32* p_tot_len,
OPJ_UINT32* p_current_part,
OPJ_UINT32* p_num_parts,
opj_event_mgr_t * p_manager);
/**
* Reads a SOT marker (Start of tile-part)
*
* @param p_header_data the data contained in the SOT marker.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the PPT marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_sot(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the SOD marker (Start of data)
*
* @param p_j2k J2K codec.
* @param p_tile_coder FIXME DOC
* @param p_data FIXME DOC
* @param p_data_written FIXME DOC
* @param p_total_data_size FIXME DOC
* @param p_stream the stream to write data to.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_sod(opj_j2k_t *p_j2k,
opj_tcd_t * p_tile_coder,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_total_data_size,
const opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a SOD marker (Start Of Data)
*
* @param p_j2k the jpeg2000 codec.
* @param p_stream FIXME DOC
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_sod(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
static void opj_j2k_update_tlm(opj_j2k_t * p_j2k, OPJ_UINT32 p_tile_part_size)
{
opj_write_bytes(p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current,
p_j2k->m_current_tile_number, 1); /* PSOT */
++p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current;
opj_write_bytes(p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current,
p_tile_part_size, 4); /* PSOT */
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current += 4;
}
/**
* Writes the RGN marker (Region Of Interest)
*
* @param p_tile_no the tile to output
* @param p_comp_no the component to output
* @param nb_comps the number of components
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_rgn(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no,
OPJ_UINT32 nb_comps,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a RGN marker (Region Of Interest)
*
* @param p_header_data the data contained in the POC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the POC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_rgn(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the EOC marker (End of Codestream)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_eoc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
#if 0
/**
* Reads a EOC marker (End Of Codestream)
*
* @param p_j2k the jpeg2000 codec.
* @param p_stream FIXME DOC
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_eoc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
#endif
/**
* Writes the CBD-MCT-MCC-MCO markers (Multi components transform)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_mct_data_group(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Inits the Info
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_init_info(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
Add main header marker information
@param cstr_index Codestream information structure
@param type marker type
@param pos byte offset of marker segment
@param len length of marker segment
*/
static OPJ_BOOL opj_j2k_add_mhmarker(opj_codestream_index_t *cstr_index,
OPJ_UINT32 type, OPJ_OFF_T pos, OPJ_UINT32 len) ;
/**
Add tile header marker information
@param tileno tile index number
@param cstr_index Codestream information structure
@param type marker type
@param pos byte offset of marker segment
@param len length of marker segment
*/
static OPJ_BOOL opj_j2k_add_tlmarker(OPJ_UINT32 tileno,
opj_codestream_index_t *cstr_index, OPJ_UINT32 type, OPJ_OFF_T pos,
OPJ_UINT32 len);
/**
* Reads an unknown marker
*
* @param p_j2k the jpeg2000 codec.
* @param p_stream the stream object to read from.
* @param output_marker FIXME DOC
* @param p_manager the user event manager.
*
* @return true if the marker could be deduced.
*/
static OPJ_BOOL opj_j2k_read_unk(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
OPJ_UINT32 *output_marker,
opj_event_mgr_t * p_manager);
/**
* Writes the MCT marker (Multiple Component Transform)
*
* @param p_j2k J2K codec.
* @param p_mct_record FIXME DOC
* @param p_stream the stream to write data to.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_mct_record(opj_j2k_t *p_j2k,
opj_mct_data_t * p_mct_record,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a MCT marker (Multiple Component Transform)
*
* @param p_header_data the data contained in the MCT box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the MCT marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_mct(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the MCC marker (Multiple Component Collection)
*
* @param p_j2k J2K codec.
* @param p_mcc_record FIXME DOC
* @param p_stream the stream to write data to.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_mcc_record(opj_j2k_t *p_j2k,
opj_simple_mcc_decorrelation_data_t * p_mcc_record,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a MCC marker (Multiple Component Collection)
*
* @param p_header_data the data contained in the MCC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the MCC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_mcc(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the MCO marker (Multiple component transformation ordering)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_mco(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a MCO marker (Multiple Component Transform Ordering)
*
* @param p_header_data the data contained in the MCO box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the MCO marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_mco(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
static OPJ_BOOL opj_j2k_add_mct(opj_tcp_t * p_tcp, opj_image_t * p_image,
OPJ_UINT32 p_index);
static void opj_j2k_read_int16_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_read_int32_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_read_float32_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_read_float64_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_read_int16_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_read_int32_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_read_float32_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_read_float64_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_write_float_to_int16(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_write_float_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_write_float_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_write_float_to_float64(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
/**
* Ends the encoding, i.e. frees memory.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_end_encoding(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes the CBD marker (Component bit depth definition)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_cbd(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a CBD marker (Component bit depth definition)
* @param p_header_data the data contained in the CBD box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the CBD marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_cbd(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes COC marker for each component.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_all_coc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes QCC marker for each component.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_all_qcc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes regions of interests.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_regions(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes EPC ????
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_epc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Checks the progression order changes values. Tells of the poc given as input are valid.
* A nice message is outputted at errors.
*
* @param p_pocs the progression order changes.
* @param p_nb_pocs the number of progression order changes.
* @param p_nb_resolutions the number of resolutions.
* @param numcomps the number of components
* @param numlayers the number of layers.
* @param p_manager the user event manager.
*
* @return true if the pocs are valid.
*/
static OPJ_BOOL opj_j2k_check_poc_val(const opj_poc_t *p_pocs,
OPJ_UINT32 p_nb_pocs,
OPJ_UINT32 p_nb_resolutions,
OPJ_UINT32 numcomps,
OPJ_UINT32 numlayers,
opj_event_mgr_t * p_manager);
/**
* Gets the number of tile parts used for the given change of progression (if any) and the given tile.
*
* @param cp the coding parameters.
* @param pino the offset of the given poc (i.e. its position in the coding parameter).
* @param tileno the given tile.
*
* @return the number of tile parts.
*/
static OPJ_UINT32 opj_j2k_get_num_tp(opj_cp_t *cp, OPJ_UINT32 pino,
OPJ_UINT32 tileno);
/**
* Calculates the total number of tile parts needed by the encoder to
* encode such an image. If not enough memory is available, then the function return false.
*
* @param p_nb_tiles pointer that will hold the number of tile parts.
* @param cp the coding parameters for the image.
* @param image the image to encode.
* @param p_j2k the p_j2k encoder.
* @param p_manager the user event manager.
*
* @return true if the function was successful, false else.
*/
static OPJ_BOOL opj_j2k_calculate_tp(opj_j2k_t *p_j2k,
opj_cp_t *cp,
OPJ_UINT32 * p_nb_tiles,
opj_image_t *image,
opj_event_mgr_t * p_manager);
static void opj_j2k_dump_MH_info(opj_j2k_t* p_j2k, FILE* out_stream);
static void opj_j2k_dump_MH_index(opj_j2k_t* p_j2k, FILE* out_stream);
static opj_codestream_index_t* opj_j2k_create_cstr_index(void);
static OPJ_FLOAT32 opj_j2k_get_tp_stride(opj_tcp_t * p_tcp);
static OPJ_FLOAT32 opj_j2k_get_default_stride(opj_tcp_t * p_tcp);
static int opj_j2k_initialise_4K_poc(opj_poc_t *POC, int numres);
static void opj_j2k_set_cinema_parameters(opj_cparameters_t *parameters,
opj_image_t *image, opj_event_mgr_t *p_manager);
static OPJ_BOOL opj_j2k_is_cinema_compliant(opj_image_t *image, OPJ_UINT16 rsiz,
opj_event_mgr_t *p_manager);
/**
* Checks for invalid number of tile-parts in SOT marker (TPsot==TNsot). See issue 254.
*
* @param p_stream the stream to read data from.
* @param tile_no tile number we're looking for.
* @param p_correction_needed output value. if true, non conformant codestream needs TNsot correction.
* @param p_manager the user event manager.
*
* @return true if the function was successful, false else.
*/
static OPJ_BOOL opj_j2k_need_nb_tile_parts_correction(opj_stream_private_t
*p_stream, OPJ_UINT32 tile_no, OPJ_BOOL* p_correction_needed,
opj_event_mgr_t * p_manager);
/*@}*/
/*@}*/
/* ----------------------------------------------------------------------- */
typedef struct j2k_prog_order {
OPJ_PROG_ORDER enum_prog;
char str_prog[5];
} j2k_prog_order_t;
static const j2k_prog_order_t j2k_prog_order_list[] = {
{OPJ_CPRL, "CPRL"},
{OPJ_LRCP, "LRCP"},
{OPJ_PCRL, "PCRL"},
{OPJ_RLCP, "RLCP"},
{OPJ_RPCL, "RPCL"},
{(OPJ_PROG_ORDER) - 1, ""}
};
/**
* FIXME DOC
*/
static const OPJ_UINT32 MCT_ELEMENT_SIZE [] = {
2,
4,
4,
8
};
typedef void (* opj_j2k_mct_function)(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static const opj_j2k_mct_function j2k_mct_read_functions_to_float [] = {
opj_j2k_read_int16_to_float,
opj_j2k_read_int32_to_float,
opj_j2k_read_float32_to_float,
opj_j2k_read_float64_to_float
};
static const opj_j2k_mct_function j2k_mct_read_functions_to_int32 [] = {
opj_j2k_read_int16_to_int32,
opj_j2k_read_int32_to_int32,
opj_j2k_read_float32_to_int32,
opj_j2k_read_float64_to_int32
};
static const opj_j2k_mct_function j2k_mct_write_functions_from_float [] = {
opj_j2k_write_float_to_int16,
opj_j2k_write_float_to_int32,
opj_j2k_write_float_to_float,
opj_j2k_write_float_to_float64
};
typedef struct opj_dec_memory_marker_handler {
/** marker value */
OPJ_UINT32 id;
/** value of the state when the marker can appear */
OPJ_UINT32 states;
/** action linked to the marker */
OPJ_BOOL(*handler)(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
}
opj_dec_memory_marker_handler_t;
static const opj_dec_memory_marker_handler_t j2k_memory_marker_handler_tab [] =
{
{J2K_MS_SOT, J2K_STATE_MH | J2K_STATE_TPHSOT, opj_j2k_read_sot},
{J2K_MS_COD, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_cod},
{J2K_MS_COC, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_coc},
{J2K_MS_RGN, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_rgn},
{J2K_MS_QCD, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_qcd},
{J2K_MS_QCC, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_qcc},
{J2K_MS_POC, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_poc},
{J2K_MS_SIZ, J2K_STATE_MHSIZ, opj_j2k_read_siz},
{J2K_MS_TLM, J2K_STATE_MH, opj_j2k_read_tlm},
{J2K_MS_PLM, J2K_STATE_MH, opj_j2k_read_plm},
{J2K_MS_PLT, J2K_STATE_TPH, opj_j2k_read_plt},
{J2K_MS_PPM, J2K_STATE_MH, opj_j2k_read_ppm},
{J2K_MS_PPT, J2K_STATE_TPH, opj_j2k_read_ppt},
{J2K_MS_SOP, 0, 0},
{J2K_MS_CRG, J2K_STATE_MH, opj_j2k_read_crg},
{J2K_MS_COM, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_com},
{J2K_MS_MCT, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_mct},
{J2K_MS_CBD, J2K_STATE_MH, opj_j2k_read_cbd},
{J2K_MS_MCC, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_mcc},
{J2K_MS_MCO, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_mco},
#ifdef USE_JPWL
#ifdef TODO_MS /* remove these functions which are not commpatible with the v2 API */
{J2K_MS_EPC, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_epc},
{J2K_MS_EPB, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_epb},
{J2K_MS_ESD, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_esd},
{J2K_MS_RED, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_red},
#endif
#endif /* USE_JPWL */
#ifdef USE_JPSEC
{J2K_MS_SEC, J2K_DEC_STATE_MH, j2k_read_sec},
{J2K_MS_INSEC, 0, j2k_read_insec}
#endif /* USE_JPSEC */
{J2K_MS_UNK, J2K_STATE_MH | J2K_STATE_TPH, 0}/*opj_j2k_read_unk is directly used*/
};
static void opj_j2k_read_int16_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_FLOAT32 * l_dest_data = (OPJ_FLOAT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_UINT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
opj_read_bytes(l_src_data, &l_temp, 2);
l_src_data += sizeof(OPJ_INT16);
*(l_dest_data++) = (OPJ_FLOAT32) l_temp;
}
}
static void opj_j2k_read_int32_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_FLOAT32 * l_dest_data = (OPJ_FLOAT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_UINT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
opj_read_bytes(l_src_data, &l_temp, 4);
l_src_data += sizeof(OPJ_INT32);
*(l_dest_data++) = (OPJ_FLOAT32) l_temp;
}
}
static void opj_j2k_read_float32_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_FLOAT32 * l_dest_data = (OPJ_FLOAT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_FLOAT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
opj_read_float(l_src_data, &l_temp);
l_src_data += sizeof(OPJ_FLOAT32);
*(l_dest_data++) = l_temp;
}
}
static void opj_j2k_read_float64_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_FLOAT32 * l_dest_data = (OPJ_FLOAT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_FLOAT64 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
opj_read_double(l_src_data, &l_temp);
l_src_data += sizeof(OPJ_FLOAT64);
*(l_dest_data++) = (OPJ_FLOAT32) l_temp;
}
}
static void opj_j2k_read_int16_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_INT32 * l_dest_data = (OPJ_INT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_UINT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
opj_read_bytes(l_src_data, &l_temp, 2);
l_src_data += sizeof(OPJ_INT16);
*(l_dest_data++) = (OPJ_INT32) l_temp;
}
}
static void opj_j2k_read_int32_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_INT32 * l_dest_data = (OPJ_INT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_UINT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
opj_read_bytes(l_src_data, &l_temp, 4);
l_src_data += sizeof(OPJ_INT32);
*(l_dest_data++) = (OPJ_INT32) l_temp;
}
}
static void opj_j2k_read_float32_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_INT32 * l_dest_data = (OPJ_INT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_FLOAT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
opj_read_float(l_src_data, &l_temp);
l_src_data += sizeof(OPJ_FLOAT32);
*(l_dest_data++) = (OPJ_INT32) l_temp;
}
}
static void opj_j2k_read_float64_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_INT32 * l_dest_data = (OPJ_INT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_FLOAT64 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
opj_read_double(l_src_data, &l_temp);
l_src_data += sizeof(OPJ_FLOAT64);
*(l_dest_data++) = (OPJ_INT32) l_temp;
}
}
static void opj_j2k_write_float_to_int16(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_dest_data = (OPJ_BYTE *) p_dest_data;
OPJ_FLOAT32 * l_src_data = (OPJ_FLOAT32 *) p_src_data;
OPJ_UINT32 i;
OPJ_UINT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
l_temp = (OPJ_UINT32) * (l_src_data++);
opj_write_bytes(l_dest_data, l_temp, sizeof(OPJ_INT16));
l_dest_data += sizeof(OPJ_INT16);
}
}
static void opj_j2k_write_float_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_dest_data = (OPJ_BYTE *) p_dest_data;
OPJ_FLOAT32 * l_src_data = (OPJ_FLOAT32 *) p_src_data;
OPJ_UINT32 i;
OPJ_UINT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
l_temp = (OPJ_UINT32) * (l_src_data++);
opj_write_bytes(l_dest_data, l_temp, sizeof(OPJ_INT32));
l_dest_data += sizeof(OPJ_INT32);
}
}
static void opj_j2k_write_float_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_dest_data = (OPJ_BYTE *) p_dest_data;
OPJ_FLOAT32 * l_src_data = (OPJ_FLOAT32 *) p_src_data;
OPJ_UINT32 i;
OPJ_FLOAT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
l_temp = (OPJ_FLOAT32) * (l_src_data++);
opj_write_float(l_dest_data, l_temp);
l_dest_data += sizeof(OPJ_FLOAT32);
}
}
static void opj_j2k_write_float_to_float64(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_dest_data = (OPJ_BYTE *) p_dest_data;
OPJ_FLOAT32 * l_src_data = (OPJ_FLOAT32 *) p_src_data;
OPJ_UINT32 i;
OPJ_FLOAT64 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
l_temp = (OPJ_FLOAT64) * (l_src_data++);
opj_write_double(l_dest_data, l_temp);
l_dest_data += sizeof(OPJ_FLOAT64);
}
}
const char *opj_j2k_convert_progression_order(OPJ_PROG_ORDER prg_order)
{
const j2k_prog_order_t *po;
for (po = j2k_prog_order_list; po->enum_prog != -1; po++) {
if (po->enum_prog == prg_order) {
return po->str_prog;
}
}
return po->str_prog;
}
static OPJ_BOOL opj_j2k_check_poc_val(const opj_poc_t *p_pocs,
OPJ_UINT32 p_nb_pocs,
OPJ_UINT32 p_nb_resolutions,
OPJ_UINT32 p_num_comps,
OPJ_UINT32 p_num_layers,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32* packet_array;
OPJ_UINT32 index, resno, compno, layno;
OPJ_UINT32 i;
OPJ_UINT32 step_c = 1;
OPJ_UINT32 step_r = p_num_comps * step_c;
OPJ_UINT32 step_l = p_nb_resolutions * step_r;
OPJ_BOOL loss = OPJ_FALSE;
OPJ_UINT32 layno0 = 0;
packet_array = (OPJ_UINT32*) opj_calloc(step_l * p_num_layers,
sizeof(OPJ_UINT32));
if (packet_array == 00) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory for checking the poc values.\n");
return OPJ_FALSE;
}
if (p_nb_pocs == 0) {
opj_free(packet_array);
return OPJ_TRUE;
}
index = step_r * p_pocs->resno0;
/* take each resolution for each poc */
for (resno = p_pocs->resno0 ; resno < p_pocs->resno1 ; ++resno) {
OPJ_UINT32 res_index = index + p_pocs->compno0 * step_c;
/* take each comp of each resolution for each poc */
for (compno = p_pocs->compno0 ; compno < p_pocs->compno1 ; ++compno) {
OPJ_UINT32 comp_index = res_index + layno0 * step_l;
/* and finally take each layer of each res of ... */
for (layno = layno0; layno < p_pocs->layno1 ; ++layno) {
/*index = step_r * resno + step_c * compno + step_l * layno;*/
packet_array[comp_index] = 1;
comp_index += step_l;
}
res_index += step_c;
}
index += step_r;
}
++p_pocs;
/* iterate through all the pocs */
for (i = 1; i < p_nb_pocs ; ++i) {
OPJ_UINT32 l_last_layno1 = (p_pocs - 1)->layno1 ;
layno0 = (p_pocs->layno1 > l_last_layno1) ? l_last_layno1 : 0;
index = step_r * p_pocs->resno0;
/* take each resolution for each poc */
for (resno = p_pocs->resno0 ; resno < p_pocs->resno1 ; ++resno) {
OPJ_UINT32 res_index = index + p_pocs->compno0 * step_c;
/* take each comp of each resolution for each poc */
for (compno = p_pocs->compno0 ; compno < p_pocs->compno1 ; ++compno) {
OPJ_UINT32 comp_index = res_index + layno0 * step_l;
/* and finally take each layer of each res of ... */
for (layno = layno0; layno < p_pocs->layno1 ; ++layno) {
/*index = step_r * resno + step_c * compno + step_l * layno;*/
packet_array[comp_index] = 1;
comp_index += step_l;
}
res_index += step_c;
}
index += step_r;
}
++p_pocs;
}
index = 0;
for (layno = 0; layno < p_num_layers ; ++layno) {
for (resno = 0; resno < p_nb_resolutions; ++resno) {
for (compno = 0; compno < p_num_comps; ++compno) {
loss |= (packet_array[index] != 1);
/*index = step_r * resno + step_c * compno + step_l * layno;*/
index += step_c;
}
}
}
if (loss) {
opj_event_msg(p_manager, EVT_ERROR, "Missing packets possible loss of data\n");
}
opj_free(packet_array);
return !loss;
}
/* ----------------------------------------------------------------------- */
static OPJ_UINT32 opj_j2k_get_num_tp(opj_cp_t *cp, OPJ_UINT32 pino,
OPJ_UINT32 tileno)
{
const OPJ_CHAR *prog = 00;
OPJ_INT32 i;
OPJ_UINT32 tpnum = 1;
opj_tcp_t *tcp = 00;
opj_poc_t * l_current_poc = 00;
/* preconditions */
assert(tileno < (cp->tw * cp->th));
assert(pino < (cp->tcps[tileno].numpocs + 1));
/* get the given tile coding parameter */
tcp = &cp->tcps[tileno];
assert(tcp != 00);
l_current_poc = &(tcp->pocs[pino]);
assert(l_current_poc != 0);
/* get the progression order as a character string */
prog = opj_j2k_convert_progression_order(tcp->prg);
assert(strlen(prog) > 0);
if (cp->m_specific_param.m_enc.m_tp_on == 1) {
for (i = 0; i < 4; ++i) {
switch (prog[i]) {
/* component wise */
case 'C':
tpnum *= l_current_poc->compE;
break;
/* resolution wise */
case 'R':
tpnum *= l_current_poc->resE;
break;
/* precinct wise */
case 'P':
tpnum *= l_current_poc->prcE;
break;
/* layer wise */
case 'L':
tpnum *= l_current_poc->layE;
break;
}
/* whould we split here ? */
if (cp->m_specific_param.m_enc.m_tp_flag == prog[i]) {
cp->m_specific_param.m_enc.m_tp_pos = i;
break;
}
}
} else {
tpnum = 1;
}
return tpnum;
}
static OPJ_BOOL opj_j2k_calculate_tp(opj_j2k_t *p_j2k,
opj_cp_t *cp,
OPJ_UINT32 * p_nb_tiles,
opj_image_t *image,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 pino, tileno;
OPJ_UINT32 l_nb_tiles;
opj_tcp_t *tcp;
/* preconditions */
assert(p_nb_tiles != 00);
assert(cp != 00);
assert(image != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_j2k);
OPJ_UNUSED(p_manager);
l_nb_tiles = cp->tw * cp->th;
* p_nb_tiles = 0;
tcp = cp->tcps;
/* INDEX >> */
/* TODO mergeV2: check this part which use cstr_info */
/*if (p_j2k->cstr_info) {
opj_tile_info_t * l_info_tile_ptr = p_j2k->cstr_info->tile;
for (tileno = 0; tileno < l_nb_tiles; ++tileno) {
OPJ_UINT32 cur_totnum_tp = 0;
opj_pi_update_encoding_parameters(image,cp,tileno);
for (pino = 0; pino <= tcp->numpocs; ++pino)
{
OPJ_UINT32 tp_num = opj_j2k_get_num_tp(cp,pino,tileno);
*p_nb_tiles = *p_nb_tiles + tp_num;
cur_totnum_tp += tp_num;
}
tcp->m_nb_tile_parts = cur_totnum_tp;
l_info_tile_ptr->tp = (opj_tp_info_t *) opj_malloc(cur_totnum_tp * sizeof(opj_tp_info_t));
if (l_info_tile_ptr->tp == 00) {
return OPJ_FALSE;
}
memset(l_info_tile_ptr->tp,0,cur_totnum_tp * sizeof(opj_tp_info_t));
l_info_tile_ptr->num_tps = cur_totnum_tp;
++l_info_tile_ptr;
++tcp;
}
}
else */{
for (tileno = 0; tileno < l_nb_tiles; ++tileno) {
OPJ_UINT32 cur_totnum_tp = 0;
opj_pi_update_encoding_parameters(image, cp, tileno);
for (pino = 0; pino <= tcp->numpocs; ++pino) {
OPJ_UINT32 tp_num = opj_j2k_get_num_tp(cp, pino, tileno);
*p_nb_tiles = *p_nb_tiles + tp_num;
cur_totnum_tp += tp_num;
}
tcp->m_nb_tile_parts = cur_totnum_tp;
++tcp;
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_soc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
/* 2 bytes will be written */
OPJ_BYTE * l_start_stream = 00;
/* preconditions */
assert(p_stream != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_start_stream = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
/* write SOC identifier */
opj_write_bytes(l_start_stream, J2K_MS_SOC, 2);
if (opj_stream_write_data(p_stream, l_start_stream, 2, p_manager) != 2) {
return OPJ_FALSE;
}
/* UniPG>> */
#ifdef USE_JPWL
/* update markers struct */
/*
OPJ_BOOL res = j2k_add_marker(p_j2k->cstr_info, J2K_MS_SOC, p_stream_tell(p_stream) - 2, 2);
*/
assert(0 && "TODO");
#endif /* USE_JPWL */
/* <<UniPG */
return OPJ_TRUE;
}
/**
* Reads a SOC marker (Start of Codestream)
* @param p_j2k the jpeg2000 file codec.
* @param p_stream FIXME DOC
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_soc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_BYTE l_data [2];
OPJ_UINT32 l_marker;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
if (opj_stream_read_data(p_stream, l_data, 2, p_manager) != 2) {
return OPJ_FALSE;
}
opj_read_bytes(l_data, &l_marker, 2);
if (l_marker != J2K_MS_SOC) {
return OPJ_FALSE;
}
/* Next marker should be a SIZ marker in the main header */
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_MHSIZ;
/* FIXME move it in a index structure included in p_j2k*/
p_j2k->cstr_index->main_head_start = opj_stream_tell(p_stream) - 2;
opj_event_msg(p_manager, EVT_INFO, "Start to read j2k main header (%d).\n",
p_j2k->cstr_index->main_head_start);
/* Add the marker to the codestream index*/
if (OPJ_FALSE == opj_j2k_add_mhmarker(p_j2k->cstr_index, J2K_MS_SOC,
p_j2k->cstr_index->main_head_start, 2)) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add mh marker\n");
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_siz(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 i;
OPJ_UINT32 l_size_len;
OPJ_BYTE * l_current_ptr;
opj_image_t * l_image = 00;
opj_cp_t *cp = 00;
opj_image_comp_t * l_img_comp = 00;
/* preconditions */
assert(p_stream != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_image = p_j2k->m_private_image;
cp = &(p_j2k->m_cp);
l_size_len = 40 + 3 * l_image->numcomps;
l_img_comp = l_image->comps;
if (l_size_len > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_size_len);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory for the SIZ marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_size_len;
}
l_current_ptr = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
/* write SOC identifier */
opj_write_bytes(l_current_ptr, J2K_MS_SIZ, 2); /* SIZ */
l_current_ptr += 2;
opj_write_bytes(l_current_ptr, l_size_len - 2, 2); /* L_SIZ */
l_current_ptr += 2;
opj_write_bytes(l_current_ptr, cp->rsiz, 2); /* Rsiz (capabilities) */
l_current_ptr += 2;
opj_write_bytes(l_current_ptr, l_image->x1, 4); /* Xsiz */
l_current_ptr += 4;
opj_write_bytes(l_current_ptr, l_image->y1, 4); /* Ysiz */
l_current_ptr += 4;
opj_write_bytes(l_current_ptr, l_image->x0, 4); /* X0siz */
l_current_ptr += 4;
opj_write_bytes(l_current_ptr, l_image->y0, 4); /* Y0siz */
l_current_ptr += 4;
opj_write_bytes(l_current_ptr, cp->tdx, 4); /* XTsiz */
l_current_ptr += 4;
opj_write_bytes(l_current_ptr, cp->tdy, 4); /* YTsiz */
l_current_ptr += 4;
opj_write_bytes(l_current_ptr, cp->tx0, 4); /* XT0siz */
l_current_ptr += 4;
opj_write_bytes(l_current_ptr, cp->ty0, 4); /* YT0siz */
l_current_ptr += 4;
opj_write_bytes(l_current_ptr, l_image->numcomps, 2); /* Csiz */
l_current_ptr += 2;
for (i = 0; i < l_image->numcomps; ++i) {
/* TODO here with MCT ? */
opj_write_bytes(l_current_ptr, l_img_comp->prec - 1 + (l_img_comp->sgnd << 7),
1); /* Ssiz_i */
++l_current_ptr;
opj_write_bytes(l_current_ptr, l_img_comp->dx, 1); /* XRsiz_i */
++l_current_ptr;
opj_write_bytes(l_current_ptr, l_img_comp->dy, 1); /* YRsiz_i */
++l_current_ptr;
++l_img_comp;
}
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_size_len,
p_manager) != l_size_len) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a SIZ marker (image and tile size)
* @param p_j2k the jpeg2000 file codec.
* @param p_header_data the data contained in the SIZ box.
* @param p_header_size the size of the data contained in the SIZ marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_siz(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 i;
OPJ_UINT32 l_nb_comp;
OPJ_UINT32 l_nb_comp_remain;
OPJ_UINT32 l_remaining_size;
OPJ_UINT32 l_nb_tiles;
OPJ_UINT32 l_tmp, l_tx1, l_ty1;
OPJ_UINT32 l_prec0, l_sgnd0;
opj_image_t *l_image = 00;
opj_cp_t *l_cp = 00;
opj_image_comp_t * l_img_comp = 00;
opj_tcp_t * l_current_tile_param = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_header_data != 00);
l_image = p_j2k->m_private_image;
l_cp = &(p_j2k->m_cp);
/* minimum size == 39 - 3 (= minimum component parameter) */
if (p_header_size < 36) {
opj_event_msg(p_manager, EVT_ERROR, "Error with SIZ marker size\n");
return OPJ_FALSE;
}
l_remaining_size = p_header_size - 36;
l_nb_comp = l_remaining_size / 3;
l_nb_comp_remain = l_remaining_size % 3;
if (l_nb_comp_remain != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error with SIZ marker size\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_tmp,
2); /* Rsiz (capabilities) */
p_header_data += 2;
l_cp->rsiz = (OPJ_UINT16) l_tmp;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_image->x1, 4); /* Xsiz */
p_header_data += 4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_image->y1, 4); /* Ysiz */
p_header_data += 4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_image->x0, 4); /* X0siz */
p_header_data += 4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_image->y0, 4); /* Y0siz */
p_header_data += 4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_cp->tdx,
4); /* XTsiz */
p_header_data += 4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_cp->tdy,
4); /* YTsiz */
p_header_data += 4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_cp->tx0,
4); /* XT0siz */
p_header_data += 4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_cp->ty0,
4); /* YT0siz */
p_header_data += 4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_tmp,
2); /* Csiz */
p_header_data += 2;
if (l_tmp < 16385) {
l_image->numcomps = (OPJ_UINT16) l_tmp;
} else {
opj_event_msg(p_manager, EVT_ERROR,
"Error with SIZ marker: number of component is illegal -> %d\n", l_tmp);
return OPJ_FALSE;
}
if (l_image->numcomps != l_nb_comp) {
opj_event_msg(p_manager, EVT_ERROR,
"Error with SIZ marker: number of component is not compatible with the remaining number of parameters ( %d vs %d)\n",
l_image->numcomps, l_nb_comp);
return OPJ_FALSE;
}
/* testcase 4035.pdf.SIGSEGV.d8b.3375 */
/* testcase issue427-null-image-size.jp2 */
if ((l_image->x0 >= l_image->x1) || (l_image->y0 >= l_image->y1)) {
opj_event_msg(p_manager, EVT_ERROR,
"Error with SIZ marker: negative or zero image size (%" PRId64 " x %" PRId64
")\n", (OPJ_INT64)l_image->x1 - l_image->x0,
(OPJ_INT64)l_image->y1 - l_image->y0);
return OPJ_FALSE;
}
/* testcase 2539.pdf.SIGFPE.706.1712 (also 3622.pdf.SIGFPE.706.2916 and 4008.pdf.SIGFPE.706.3345 and maybe more) */
if ((l_cp->tdx == 0U) || (l_cp->tdy == 0U)) {
opj_event_msg(p_manager, EVT_ERROR,
"Error with SIZ marker: invalid tile size (tdx: %d, tdy: %d)\n", l_cp->tdx,
l_cp->tdy);
return OPJ_FALSE;
}
/* testcase 1610.pdf.SIGSEGV.59c.681 */
if ((0xFFFFFFFFU / l_image->x1) < l_image->y1) {
opj_event_msg(p_manager, EVT_ERROR,
"Prevent buffer overflow (x1: %d, y1: %d)\n", l_image->x1, l_image->y1);
return OPJ_FALSE;
}
/* testcase issue427-illegal-tile-offset.jp2 */
l_tx1 = opj_uint_adds(l_cp->tx0, l_cp->tdx); /* manage overflow */
l_ty1 = opj_uint_adds(l_cp->ty0, l_cp->tdy); /* manage overflow */
if ((l_cp->tx0 > l_image->x0) || (l_cp->ty0 > l_image->y0) ||
(l_tx1 <= l_image->x0) || (l_ty1 <= l_image->y0)) {
opj_event_msg(p_manager, EVT_ERROR,
"Error with SIZ marker: illegal tile offset\n");
return OPJ_FALSE;
}
if (!p_j2k->dump_state) {
OPJ_UINT32 siz_w, siz_h;
siz_w = l_image->x1 - l_image->x0;
siz_h = l_image->y1 - l_image->y0;
if (p_j2k->ihdr_w > 0 && p_j2k->ihdr_h > 0
&& (p_j2k->ihdr_w != siz_w || p_j2k->ihdr_h != siz_h)) {
opj_event_msg(p_manager, EVT_ERROR,
"Error with SIZ marker: IHDR w(%u) h(%u) vs. SIZ w(%u) h(%u)\n", p_j2k->ihdr_w,
p_j2k->ihdr_h, siz_w, siz_h);
return OPJ_FALSE;
}
}
#ifdef USE_JPWL
if (l_cp->correct) {
/* if JPWL is on, we check whether TX errors have damaged
too much the SIZ parameters */
if (!(l_image->x1 * l_image->y1)) {
opj_event_msg(p_manager, EVT_ERROR,
"JPWL: bad image size (%d x %d)\n",
l_image->x1, l_image->y1);
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
}
/* FIXME check previously in the function so why keep this piece of code ? Need by the norm ?
if (l_image->numcomps != ((len - 38) / 3)) {
opj_event_msg(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
"JPWL: Csiz is %d => space in SIZ only for %d comps.!!!\n",
l_image->numcomps, ((len - 38) / 3));
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
*/ /* we try to correct */
/* opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust this\n");
if (l_image->numcomps < ((len - 38) / 3)) {
len = 38 + 3 * l_image->numcomps;
opj_event_msg(p_manager, EVT_WARNING, "- setting Lsiz to %d => HYPOTHESIS!!!\n",
len);
} else {
l_image->numcomps = ((len - 38) / 3);
opj_event_msg(p_manager, EVT_WARNING, "- setting Csiz to %d => HYPOTHESIS!!!\n",
l_image->numcomps);
}
}
*/
/* update components number in the jpwl_exp_comps filed */
l_cp->exp_comps = l_image->numcomps;
}
#endif /* USE_JPWL */
/* Allocate the resulting image components */
l_image->comps = (opj_image_comp_t*) opj_calloc(l_image->numcomps,
sizeof(opj_image_comp_t));
if (l_image->comps == 00) {
l_image->numcomps = 0;
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to take in charge SIZ marker\n");
return OPJ_FALSE;
}
l_img_comp = l_image->comps;
l_prec0 = 0;
l_sgnd0 = 0;
/* Read the component information */
for (i = 0; i < l_image->numcomps; ++i) {
OPJ_UINT32 tmp;
opj_read_bytes(p_header_data, &tmp, 1); /* Ssiz_i */
++p_header_data;
l_img_comp->prec = (tmp & 0x7f) + 1;
l_img_comp->sgnd = tmp >> 7;
if (p_j2k->dump_state == 0) {
if (i == 0) {
l_prec0 = l_img_comp->prec;
l_sgnd0 = l_img_comp->sgnd;
} else if (!l_cp->allow_different_bit_depth_sign
&& (l_img_comp->prec != l_prec0 || l_img_comp->sgnd != l_sgnd0)) {
opj_event_msg(p_manager, EVT_WARNING,
"Despite JP2 BPC!=255, precision and/or sgnd values for comp[%d] is different than comp[0]:\n"
" [0] prec(%d) sgnd(%d) [%d] prec(%d) sgnd(%d)\n", i, l_prec0, l_sgnd0,
i, l_img_comp->prec, l_img_comp->sgnd);
}
/* TODO: we should perhaps also check against JP2 BPCC values */
}
opj_read_bytes(p_header_data, &tmp, 1); /* XRsiz_i */
++p_header_data;
l_img_comp->dx = (OPJ_UINT32)tmp; /* should be between 1 and 255 */
opj_read_bytes(p_header_data, &tmp, 1); /* YRsiz_i */
++p_header_data;
l_img_comp->dy = (OPJ_UINT32)tmp; /* should be between 1 and 255 */
if (l_img_comp->dx < 1 || l_img_comp->dx > 255 ||
l_img_comp->dy < 1 || l_img_comp->dy > 255) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid values for comp = %d : dx=%u dy=%u (should be between 1 and 255 according to the JPEG2000 norm)\n",
i, l_img_comp->dx, l_img_comp->dy);
return OPJ_FALSE;
}
/* Avoids later undefined shift in computation of */
/* p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps[i].m_dc_level_shift = 1
<< (l_image->comps[i].prec - 1); */
if (l_img_comp->prec > 31) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid values for comp = %d : prec=%u (should be between 1 and 38 according to the JPEG2000 norm. OpenJpeg only supports up to 31)\n",
i, l_img_comp->prec);
return OPJ_FALSE;
}
#ifdef USE_JPWL
if (l_cp->correct) {
/* if JPWL is on, we check whether TX errors have damaged
too much the SIZ parameters, again */
if (!(l_image->comps[i].dx * l_image->comps[i].dy)) {
opj_event_msg(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
"JPWL: bad XRsiz_%d/YRsiz_%d (%d x %d)\n",
i, i, l_image->comps[i].dx, l_image->comps[i].dy);
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
/* we try to correct */
opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust them\n");
if (!l_image->comps[i].dx) {
l_image->comps[i].dx = 1;
opj_event_msg(p_manager, EVT_WARNING,
"- setting XRsiz_%d to %d => HYPOTHESIS!!!\n",
i, l_image->comps[i].dx);
}
if (!l_image->comps[i].dy) {
l_image->comps[i].dy = 1;
opj_event_msg(p_manager, EVT_WARNING,
"- setting YRsiz_%d to %d => HYPOTHESIS!!!\n",
i, l_image->comps[i].dy);
}
}
}
#endif /* USE_JPWL */
l_img_comp->resno_decoded =
0; /* number of resolution decoded */
l_img_comp->factor =
l_cp->m_specific_param.m_dec.m_reduce; /* reducing factor per component */
++l_img_comp;
}
if (l_cp->tdx == 0 || l_cp->tdy == 0) {
return OPJ_FALSE;
}
/* Compute the number of tiles */
l_cp->tw = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)(l_image->x1 - l_cp->tx0),
(OPJ_INT32)l_cp->tdx);
l_cp->th = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)(l_image->y1 - l_cp->ty0),
(OPJ_INT32)l_cp->tdy);
/* Check that the number of tiles is valid */
if (l_cp->tw == 0 || l_cp->th == 0 || l_cp->tw > 65535 / l_cp->th) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid number of tiles : %u x %u (maximum fixed by jpeg2000 norm is 65535 tiles)\n",
l_cp->tw, l_cp->th);
return OPJ_FALSE;
}
l_nb_tiles = l_cp->tw * l_cp->th;
/* Define the tiles which will be decoded */
if (p_j2k->m_specific_param.m_decoder.m_discard_tiles) {
p_j2k->m_specific_param.m_decoder.m_start_tile_x =
(p_j2k->m_specific_param.m_decoder.m_start_tile_x - l_cp->tx0) / l_cp->tdx;
p_j2k->m_specific_param.m_decoder.m_start_tile_y =
(p_j2k->m_specific_param.m_decoder.m_start_tile_y - l_cp->ty0) / l_cp->tdy;
p_j2k->m_specific_param.m_decoder.m_end_tile_x = (OPJ_UINT32)opj_int_ceildiv((
OPJ_INT32)(p_j2k->m_specific_param.m_decoder.m_end_tile_x - l_cp->tx0),
(OPJ_INT32)l_cp->tdx);
p_j2k->m_specific_param.m_decoder.m_end_tile_y = (OPJ_UINT32)opj_int_ceildiv((
OPJ_INT32)(p_j2k->m_specific_param.m_decoder.m_end_tile_y - l_cp->ty0),
(OPJ_INT32)l_cp->tdy);
} else {
p_j2k->m_specific_param.m_decoder.m_start_tile_x = 0;
p_j2k->m_specific_param.m_decoder.m_start_tile_y = 0;
p_j2k->m_specific_param.m_decoder.m_end_tile_x = l_cp->tw;
p_j2k->m_specific_param.m_decoder.m_end_tile_y = l_cp->th;
}
#ifdef USE_JPWL
if (l_cp->correct) {
/* if JPWL is on, we check whether TX errors have damaged
too much the SIZ parameters */
if ((l_cp->tw < 1) || (l_cp->th < 1) || (l_cp->tw > l_cp->max_tiles) ||
(l_cp->th > l_cp->max_tiles)) {
opj_event_msg(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
"JPWL: bad number of tiles (%d x %d)\n",
l_cp->tw, l_cp->th);
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
/* we try to correct */
opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust them\n");
if (l_cp->tw < 1) {
l_cp->tw = 1;
opj_event_msg(p_manager, EVT_WARNING,
"- setting %d tiles in x => HYPOTHESIS!!!\n",
l_cp->tw);
}
if (l_cp->tw > l_cp->max_tiles) {
l_cp->tw = 1;
opj_event_msg(p_manager, EVT_WARNING,
"- too large x, increase expectance of %d\n"
"- setting %d tiles in x => HYPOTHESIS!!!\n",
l_cp->max_tiles, l_cp->tw);
}
if (l_cp->th < 1) {
l_cp->th = 1;
opj_event_msg(p_manager, EVT_WARNING,
"- setting %d tiles in y => HYPOTHESIS!!!\n",
l_cp->th);
}
if (l_cp->th > l_cp->max_tiles) {
l_cp->th = 1;
opj_event_msg(p_manager, EVT_WARNING,
"- too large y, increase expectance of %d to continue\n",
"- setting %d tiles in y => HYPOTHESIS!!!\n",
l_cp->max_tiles, l_cp->th);
}
}
}
#endif /* USE_JPWL */
/* memory allocations */
l_cp->tcps = (opj_tcp_t*) opj_calloc(l_nb_tiles, sizeof(opj_tcp_t));
if (l_cp->tcps == 00) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to take in charge SIZ marker\n");
return OPJ_FALSE;
}
#ifdef USE_JPWL
if (l_cp->correct) {
if (!l_cp->tcps) {
opj_event_msg(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
"JPWL: could not alloc tcps field of cp\n");
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
}
}
#endif /* USE_JPWL */
p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps =
(opj_tccp_t*) opj_calloc(l_image->numcomps, sizeof(opj_tccp_t));
if (p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps == 00) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to take in charge SIZ marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mct_records =
(opj_mct_data_t*)opj_calloc(OPJ_J2K_MCT_DEFAULT_NB_RECORDS,
sizeof(opj_mct_data_t));
if (! p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mct_records) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to take in charge SIZ marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_decoder.m_default_tcp->m_nb_max_mct_records =
OPJ_J2K_MCT_DEFAULT_NB_RECORDS;
p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mcc_records =
(opj_simple_mcc_decorrelation_data_t*)
opj_calloc(OPJ_J2K_MCC_DEFAULT_NB_RECORDS,
sizeof(opj_simple_mcc_decorrelation_data_t));
if (! p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mcc_records) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to take in charge SIZ marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_decoder.m_default_tcp->m_nb_max_mcc_records =
OPJ_J2K_MCC_DEFAULT_NB_RECORDS;
/* set up default dc level shift */
for (i = 0; i < l_image->numcomps; ++i) {
if (! l_image->comps[i].sgnd) {
p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps[i].m_dc_level_shift = 1
<< (l_image->comps[i].prec - 1);
}
}
l_current_tile_param = l_cp->tcps;
for (i = 0; i < l_nb_tiles; ++i) {
l_current_tile_param->tccps = (opj_tccp_t*) opj_calloc(l_image->numcomps,
sizeof(opj_tccp_t));
if (l_current_tile_param->tccps == 00) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to take in charge SIZ marker\n");
return OPJ_FALSE;
}
++l_current_tile_param;
}
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_MH;
opj_image_comp_header_update(l_image, l_cp);
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_com(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_comment_size;
OPJ_UINT32 l_total_com_size;
const OPJ_CHAR *l_comment;
OPJ_BYTE * l_current_ptr = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
l_comment = p_j2k->m_cp.comment;
l_comment_size = (OPJ_UINT32)strlen(l_comment);
l_total_com_size = l_comment_size + 6;
if (l_total_com_size >
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_total_com_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to write the COM marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_total_com_size;
}
l_current_ptr = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_ptr, J2K_MS_COM, 2); /* COM */
l_current_ptr += 2;
opj_write_bytes(l_current_ptr, l_total_com_size - 2, 2); /* L_COM */
l_current_ptr += 2;
opj_write_bytes(l_current_ptr, 1,
2); /* General use (IS 8859-15:1999 (Latin) values) */
l_current_ptr += 2;
memcpy(l_current_ptr, l_comment, l_comment_size);
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_total_com_size,
p_manager) != l_total_com_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a COM marker (comments)
* @param p_j2k the jpeg2000 file codec.
* @param p_header_data the data contained in the COM box.
* @param p_header_size the size of the data contained in the COM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_com(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_header_data != 00);
OPJ_UNUSED(p_j2k);
OPJ_UNUSED(p_header_data);
OPJ_UNUSED(p_header_size);
OPJ_UNUSED(p_manager);
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_cod(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
OPJ_UINT32 l_code_size, l_remaining_size;
OPJ_BYTE * l_current_data = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_j2k->m_current_tile_number];
l_code_size = 9 + opj_j2k_get_SPCod_SPCoc_size(p_j2k,
p_j2k->m_current_tile_number, 0);
l_remaining_size = l_code_size;
if (l_code_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_code_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write COD marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_code_size;
}
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_data, J2K_MS_COD, 2); /* COD */
l_current_data += 2;
opj_write_bytes(l_current_data, l_code_size - 2, 2); /* L_COD */
l_current_data += 2;
opj_write_bytes(l_current_data, l_tcp->csty, 1); /* Scod */
++l_current_data;
opj_write_bytes(l_current_data, (OPJ_UINT32)l_tcp->prg, 1); /* SGcod (A) */
++l_current_data;
opj_write_bytes(l_current_data, l_tcp->numlayers, 2); /* SGcod (B) */
l_current_data += 2;
opj_write_bytes(l_current_data, l_tcp->mct, 1); /* SGcod (C) */
++l_current_data;
l_remaining_size -= 9;
if (! opj_j2k_write_SPCod_SPCoc(p_j2k, p_j2k->m_current_tile_number, 0,
l_current_data, &l_remaining_size, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing COD marker\n");
return OPJ_FALSE;
}
if (l_remaining_size != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing COD marker\n");
return OPJ_FALSE;
}
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_code_size,
p_manager) != l_code_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a COD marker (Coding Styke defaults)
* @param p_header_data the data contained in the COD box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the COD marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_cod(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
/* loop */
OPJ_UINT32 i;
OPJ_UINT32 l_tmp;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_image_t *l_image = 00;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_image = p_j2k->m_private_image;
l_cp = &(p_j2k->m_cp);
/* If we are in the first tile-part header of the current tile */
l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
/* Only one COD per tile */
if (l_tcp->cod) {
opj_event_msg(p_manager, EVT_ERROR,
"COD marker already read. No more than one COD marker per tile.\n");
return OPJ_FALSE;
}
l_tcp->cod = 1;
/* Make sure room is sufficient */
if (p_header_size < 5) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading COD marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_tcp->csty, 1); /* Scod */
++p_header_data;
/* Make sure we know how to decode this */
if ((l_tcp->csty & ~(OPJ_UINT32)(J2K_CP_CSTY_PRT | J2K_CP_CSTY_SOP |
J2K_CP_CSTY_EPH)) != 0U) {
opj_event_msg(p_manager, EVT_ERROR, "Unknown Scod value in COD marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_tmp, 1); /* SGcod (A) */
++p_header_data;
l_tcp->prg = (OPJ_PROG_ORDER) l_tmp;
/* Make sure progression order is valid */
if (l_tcp->prg > OPJ_CPRL) {
opj_event_msg(p_manager, EVT_ERROR,
"Unknown progression order in COD marker\n");
l_tcp->prg = OPJ_PROG_UNKNOWN;
}
opj_read_bytes(p_header_data, &l_tcp->numlayers, 2); /* SGcod (B) */
p_header_data += 2;
if ((l_tcp->numlayers < 1U) || (l_tcp->numlayers > 65535U)) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid number of layers in COD marker : %d not in range [1-65535]\n",
l_tcp->numlayers);
return OPJ_FALSE;
}
/* If user didn't set a number layer to decode take the max specify in the codestream. */
if (l_cp->m_specific_param.m_dec.m_layer) {
l_tcp->num_layers_to_decode = l_cp->m_specific_param.m_dec.m_layer;
} else {
l_tcp->num_layers_to_decode = l_tcp->numlayers;
}
opj_read_bytes(p_header_data, &l_tcp->mct, 1); /* SGcod (C) */
++p_header_data;
p_header_size -= 5;
for (i = 0; i < l_image->numcomps; ++i) {
l_tcp->tccps[i].csty = l_tcp->csty & J2K_CCP_CSTY_PRT;
}
if (! opj_j2k_read_SPCod_SPCoc(p_j2k, 0, p_header_data, &p_header_size,
p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading COD marker\n");
return OPJ_FALSE;
}
if (p_header_size != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading COD marker\n");
return OPJ_FALSE;
}
/* Apply the coding style to other components of the current tile or the m_default_tcp*/
opj_j2k_copy_tile_component_parameters(p_j2k);
/* Index */
#ifdef WIP_REMOVE_MSD
if (p_j2k->cstr_info) {
/*opj_codestream_info_t *l_cstr_info = p_j2k->cstr_info;*/
p_j2k->cstr_info->prog = l_tcp->prg;
p_j2k->cstr_info->numlayers = l_tcp->numlayers;
p_j2k->cstr_info->numdecompos = (OPJ_INT32*) opj_malloc(
l_image->numcomps * sizeof(OPJ_UINT32));
if (!p_j2k->cstr_info->numdecompos) {
return OPJ_FALSE;
}
for (i = 0; i < l_image->numcomps; ++i) {
p_j2k->cstr_info->numdecompos[i] = l_tcp->tccps[i].numresolutions - 1;
}
}
#endif
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_coc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 l_coc_size, l_remaining_size;
OPJ_UINT32 l_comp_room;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_comp_room = (p_j2k->m_private_image->numcomps <= 256) ? 1 : 2;
l_coc_size = 5 + l_comp_room + opj_j2k_get_SPCod_SPCoc_size(p_j2k,
p_j2k->m_current_tile_number, p_comp_no);
if (l_coc_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data;
/*p_j2k->m_specific_param.m_encoder.m_header_tile_data
= (OPJ_BYTE*)opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data,
l_coc_size);*/
new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_coc_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write COC marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_coc_size;
}
opj_j2k_write_coc_in_memory(p_j2k, p_comp_no,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, &l_remaining_size,
p_manager);
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_coc_size,
p_manager) != l_coc_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_compare_coc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no)
{
opj_cp_t *l_cp = NULL;
opj_tcp_t *l_tcp = NULL;
/* preconditions */
assert(p_j2k != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_j2k->m_current_tile_number];
if (l_tcp->tccps[p_first_comp_no].csty != l_tcp->tccps[p_second_comp_no].csty) {
return OPJ_FALSE;
}
return opj_j2k_compare_SPCod_SPCoc(p_j2k, p_j2k->m_current_tile_number,
p_first_comp_no, p_second_comp_no);
}
static void opj_j2k_write_coc_in_memory(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
opj_event_mgr_t * p_manager
)
{
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
OPJ_UINT32 l_coc_size, l_remaining_size;
OPJ_BYTE * l_current_data = 00;
opj_image_t *l_image = 00;
OPJ_UINT32 l_comp_room;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_j2k->m_current_tile_number];
l_image = p_j2k->m_private_image;
l_comp_room = (l_image->numcomps <= 256) ? 1 : 2;
l_coc_size = 5 + l_comp_room + opj_j2k_get_SPCod_SPCoc_size(p_j2k,
p_j2k->m_current_tile_number, p_comp_no);
l_remaining_size = l_coc_size;
l_current_data = p_data;
opj_write_bytes(l_current_data, J2K_MS_COC,
2); /* COC */
l_current_data += 2;
opj_write_bytes(l_current_data, l_coc_size - 2,
2); /* L_COC */
l_current_data += 2;
opj_write_bytes(l_current_data, p_comp_no, l_comp_room); /* Ccoc */
l_current_data += l_comp_room;
opj_write_bytes(l_current_data, l_tcp->tccps[p_comp_no].csty,
1); /* Scoc */
++l_current_data;
l_remaining_size -= (5 + l_comp_room);
opj_j2k_write_SPCod_SPCoc(p_j2k, p_j2k->m_current_tile_number, 0,
l_current_data, &l_remaining_size, p_manager);
* p_data_written = l_coc_size;
}
static OPJ_UINT32 opj_j2k_get_max_coc_size(opj_j2k_t *p_j2k)
{
OPJ_UINT32 i, j;
OPJ_UINT32 l_nb_comp;
OPJ_UINT32 l_nb_tiles;
OPJ_UINT32 l_max = 0;
/* preconditions */
l_nb_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th ;
l_nb_comp = p_j2k->m_private_image->numcomps;
for (i = 0; i < l_nb_tiles; ++i) {
for (j = 0; j < l_nb_comp; ++j) {
l_max = opj_uint_max(l_max, opj_j2k_get_SPCod_SPCoc_size(p_j2k, i, j));
}
}
return 6 + l_max;
}
/**
* Reads a COC marker (Coding Style Component)
* @param p_header_data the data contained in the COC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the COC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_coc(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
opj_cp_t *l_cp = NULL;
opj_tcp_t *l_tcp = NULL;
opj_image_t *l_image = NULL;
OPJ_UINT32 l_comp_room;
OPJ_UINT32 l_comp_no;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH)
?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
l_image = p_j2k->m_private_image;
l_comp_room = l_image->numcomps <= 256 ? 1 : 2;
/* make sure room is sufficient*/
if (p_header_size < l_comp_room + 1) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading COC marker\n");
return OPJ_FALSE;
}
p_header_size -= l_comp_room + 1;
opj_read_bytes(p_header_data, &l_comp_no,
l_comp_room); /* Ccoc */
p_header_data += l_comp_room;
if (l_comp_no >= l_image->numcomps) {
opj_event_msg(p_manager, EVT_ERROR,
"Error reading COC marker (bad number of components)\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_tcp->tccps[l_comp_no].csty,
1); /* Scoc */
++p_header_data ;
if (! opj_j2k_read_SPCod_SPCoc(p_j2k, l_comp_no, p_header_data, &p_header_size,
p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading COC marker\n");
return OPJ_FALSE;
}
if (p_header_size != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading COC marker\n");
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_qcd(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_qcd_size, l_remaining_size;
OPJ_BYTE * l_current_data = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_qcd_size = 4 + opj_j2k_get_SQcd_SQcc_size(p_j2k, p_j2k->m_current_tile_number,
0);
l_remaining_size = l_qcd_size;
if (l_qcd_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_qcd_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write QCD marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_qcd_size;
}
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_data, J2K_MS_QCD, 2); /* QCD */
l_current_data += 2;
opj_write_bytes(l_current_data, l_qcd_size - 2, 2); /* L_QCD */
l_current_data += 2;
l_remaining_size -= 4;
if (! opj_j2k_write_SQcd_SQcc(p_j2k, p_j2k->m_current_tile_number, 0,
l_current_data, &l_remaining_size, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing QCD marker\n");
return OPJ_FALSE;
}
if (l_remaining_size != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing QCD marker\n");
return OPJ_FALSE;
}
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_qcd_size,
p_manager) != l_qcd_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a QCD marker (Quantization defaults)
* @param p_header_data the data contained in the QCD box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the QCD marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_qcd(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_j2k_read_SQcd_SQcc(p_j2k, 0, p_header_data, &p_header_size,
p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading QCD marker\n");
return OPJ_FALSE;
}
if (p_header_size != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading QCD marker\n");
return OPJ_FALSE;
}
/* Apply the quantization parameters to other components of the current tile or the m_default_tcp */
opj_j2k_copy_tile_quantization_parameters(p_j2k);
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_qcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_qcc_size, l_remaining_size;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_qcc_size = 5 + opj_j2k_get_SQcd_SQcc_size(p_j2k, p_j2k->m_current_tile_number,
p_comp_no);
l_qcc_size += p_j2k->m_private_image->numcomps <= 256 ? 0 : 1;
l_remaining_size = l_qcc_size;
if (l_qcc_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_qcc_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write QCC marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_qcc_size;
}
opj_j2k_write_qcc_in_memory(p_j2k, p_comp_no,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, &l_remaining_size,
p_manager);
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_qcc_size,
p_manager) != l_qcc_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_compare_qcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no)
{
return opj_j2k_compare_SQcd_SQcc(p_j2k, p_j2k->m_current_tile_number,
p_first_comp_no, p_second_comp_no);
}
static void opj_j2k_write_qcc_in_memory(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_qcc_size, l_remaining_size;
OPJ_BYTE * l_current_data = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
l_qcc_size = 6 + opj_j2k_get_SQcd_SQcc_size(p_j2k, p_j2k->m_current_tile_number,
p_comp_no);
l_remaining_size = l_qcc_size;
l_current_data = p_data;
opj_write_bytes(l_current_data, J2K_MS_QCC, 2); /* QCC */
l_current_data += 2;
if (p_j2k->m_private_image->numcomps <= 256) {
--l_qcc_size;
opj_write_bytes(l_current_data, l_qcc_size - 2, 2); /* L_QCC */
l_current_data += 2;
opj_write_bytes(l_current_data, p_comp_no, 1); /* Cqcc */
++l_current_data;
/* in the case only one byte is sufficient the last byte allocated is useless -> still do -6 for available */
l_remaining_size -= 6;
} else {
opj_write_bytes(l_current_data, l_qcc_size - 2, 2); /* L_QCC */
l_current_data += 2;
opj_write_bytes(l_current_data, p_comp_no, 2); /* Cqcc */
l_current_data += 2;
l_remaining_size -= 6;
}
opj_j2k_write_SQcd_SQcc(p_j2k, p_j2k->m_current_tile_number, p_comp_no,
l_current_data, &l_remaining_size, p_manager);
*p_data_written = l_qcc_size;
}
static OPJ_UINT32 opj_j2k_get_max_qcc_size(opj_j2k_t *p_j2k)
{
return opj_j2k_get_max_coc_size(p_j2k);
}
/**
* Reads a QCC marker (Quantization component)
* @param p_header_data the data contained in the QCC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the QCC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_qcc(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_num_comp, l_comp_no;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_num_comp = p_j2k->m_private_image->numcomps;
if (l_num_comp <= 256) {
if (p_header_size < 1) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading QCC marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_comp_no, 1);
++p_header_data;
--p_header_size;
} else {
if (p_header_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading QCC marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_comp_no, 2);
p_header_data += 2;
p_header_size -= 2;
}
#ifdef USE_JPWL
if (p_j2k->m_cp.correct) {
static OPJ_UINT32 backup_compno = 0;
/* compno is negative or larger than the number of components!!! */
if (/*(l_comp_no < 0) ||*/ (l_comp_no >= l_num_comp)) {
opj_event_msg(p_manager, EVT_ERROR,
"JPWL: bad component number in QCC (%d out of a maximum of %d)\n",
l_comp_no, l_num_comp);
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
/* we try to correct */
l_comp_no = backup_compno % l_num_comp;
opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust this\n"
"- setting component number to %d\n",
l_comp_no);
}
/* keep your private count of tiles */
backup_compno++;
};
#endif /* USE_JPWL */
if (l_comp_no >= p_j2k->m_private_image->numcomps) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid component number: %d, regarding the number of components %d\n",
l_comp_no, p_j2k->m_private_image->numcomps);
return OPJ_FALSE;
}
if (! opj_j2k_read_SQcd_SQcc(p_j2k, l_comp_no, p_header_data, &p_header_size,
p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading QCC marker\n");
return OPJ_FALSE;
}
if (p_header_size != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading QCC marker\n");
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_poc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_nb_comp;
OPJ_UINT32 l_nb_poc;
OPJ_UINT32 l_poc_size;
OPJ_UINT32 l_written_size = 0;
opj_tcp_t *l_tcp = 00;
OPJ_UINT32 l_poc_room;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_tcp = &p_j2k->m_cp.tcps[p_j2k->m_current_tile_number];
l_nb_comp = p_j2k->m_private_image->numcomps;
l_nb_poc = 1 + l_tcp->numpocs;
if (l_nb_comp <= 256) {
l_poc_room = 1;
} else {
l_poc_room = 2;
}
l_poc_size = 4 + (5 + 2 * l_poc_room) * l_nb_poc;
if (l_poc_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_poc_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write POC marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_poc_size;
}
opj_j2k_write_poc_in_memory(p_j2k,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, &l_written_size,
p_manager);
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_poc_size,
p_manager) != l_poc_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static void opj_j2k_write_poc_in_memory(opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 i;
OPJ_BYTE * l_current_data = 00;
OPJ_UINT32 l_nb_comp;
OPJ_UINT32 l_nb_poc;
OPJ_UINT32 l_poc_size;
opj_image_t *l_image = 00;
opj_tcp_t *l_tcp = 00;
opj_tccp_t *l_tccp = 00;
opj_poc_t *l_current_poc = 00;
OPJ_UINT32 l_poc_room;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_manager);
l_tcp = &p_j2k->m_cp.tcps[p_j2k->m_current_tile_number];
l_tccp = &l_tcp->tccps[0];
l_image = p_j2k->m_private_image;
l_nb_comp = l_image->numcomps;
l_nb_poc = 1 + l_tcp->numpocs;
if (l_nb_comp <= 256) {
l_poc_room = 1;
} else {
l_poc_room = 2;
}
l_poc_size = 4 + (5 + 2 * l_poc_room) * l_nb_poc;
l_current_data = p_data;
opj_write_bytes(l_current_data, J2K_MS_POC,
2); /* POC */
l_current_data += 2;
opj_write_bytes(l_current_data, l_poc_size - 2,
2); /* Lpoc */
l_current_data += 2;
l_current_poc = l_tcp->pocs;
for (i = 0; i < l_nb_poc; ++i) {
opj_write_bytes(l_current_data, l_current_poc->resno0,
1); /* RSpoc_i */
++l_current_data;
opj_write_bytes(l_current_data, l_current_poc->compno0,
l_poc_room); /* CSpoc_i */
l_current_data += l_poc_room;
opj_write_bytes(l_current_data, l_current_poc->layno1,
2); /* LYEpoc_i */
l_current_data += 2;
opj_write_bytes(l_current_data, l_current_poc->resno1,
1); /* REpoc_i */
++l_current_data;
opj_write_bytes(l_current_data, l_current_poc->compno1,
l_poc_room); /* CEpoc_i */
l_current_data += l_poc_room;
opj_write_bytes(l_current_data, (OPJ_UINT32)l_current_poc->prg,
1); /* Ppoc_i */
++l_current_data;
/* change the value of the max layer according to the actual number of layers in the file, components and resolutions*/
l_current_poc->layno1 = (OPJ_UINT32)opj_int_min((OPJ_INT32)
l_current_poc->layno1, (OPJ_INT32)l_tcp->numlayers);
l_current_poc->resno1 = (OPJ_UINT32)opj_int_min((OPJ_INT32)
l_current_poc->resno1, (OPJ_INT32)l_tccp->numresolutions);
l_current_poc->compno1 = (OPJ_UINT32)opj_int_min((OPJ_INT32)
l_current_poc->compno1, (OPJ_INT32)l_nb_comp);
++l_current_poc;
}
*p_data_written = l_poc_size;
}
static OPJ_UINT32 opj_j2k_get_max_poc_size(opj_j2k_t *p_j2k)
{
opj_tcp_t * l_tcp = 00;
OPJ_UINT32 l_nb_tiles = 0;
OPJ_UINT32 l_max_poc = 0;
OPJ_UINT32 i;
l_tcp = p_j2k->m_cp.tcps;
l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
for (i = 0; i < l_nb_tiles; ++i) {
l_max_poc = opj_uint_max(l_max_poc, l_tcp->numpocs);
++l_tcp;
}
++l_max_poc;
return 4 + 9 * l_max_poc;
}
static OPJ_UINT32 opj_j2k_get_max_toc_size(opj_j2k_t *p_j2k)
{
OPJ_UINT32 i;
OPJ_UINT32 l_nb_tiles;
OPJ_UINT32 l_max = 0;
opj_tcp_t * l_tcp = 00;
l_tcp = p_j2k->m_cp.tcps;
l_nb_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th ;
for (i = 0; i < l_nb_tiles; ++i) {
l_max = opj_uint_max(l_max, l_tcp->m_nb_tile_parts);
++l_tcp;
}
return 12 * l_max;
}
static OPJ_UINT32 opj_j2k_get_specific_header_sizes(opj_j2k_t *p_j2k)
{
OPJ_UINT32 l_nb_bytes = 0;
OPJ_UINT32 l_nb_comps;
OPJ_UINT32 l_coc_bytes, l_qcc_bytes;
l_nb_comps = p_j2k->m_private_image->numcomps - 1;
l_nb_bytes += opj_j2k_get_max_toc_size(p_j2k);
if (!(OPJ_IS_CINEMA(p_j2k->m_cp.rsiz))) {
l_coc_bytes = opj_j2k_get_max_coc_size(p_j2k);
l_nb_bytes += l_nb_comps * l_coc_bytes;
l_qcc_bytes = opj_j2k_get_max_qcc_size(p_j2k);
l_nb_bytes += l_nb_comps * l_qcc_bytes;
}
l_nb_bytes += opj_j2k_get_max_poc_size(p_j2k);
/*** DEVELOPER CORNER, Add room for your headers ***/
return l_nb_bytes;
}
/**
* Reads a POC marker (Progression Order Change)
*
* @param p_header_data the data contained in the POC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the POC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_poc(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 i, l_nb_comp, l_tmp;
opj_image_t * l_image = 00;
OPJ_UINT32 l_old_poc_nb, l_current_poc_nb, l_current_poc_remaining;
OPJ_UINT32 l_chunk_size, l_comp_room;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_poc_t *l_current_poc = 00;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_image = p_j2k->m_private_image;
l_nb_comp = l_image->numcomps;
if (l_nb_comp <= 256) {
l_comp_room = 1;
} else {
l_comp_room = 2;
}
l_chunk_size = 5 + 2 * l_comp_room;
l_current_poc_nb = p_header_size / l_chunk_size;
l_current_poc_remaining = p_header_size % l_chunk_size;
if ((l_current_poc_nb <= 0) || (l_current_poc_remaining != 0)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading POC marker\n");
return OPJ_FALSE;
}
l_cp = &(p_j2k->m_cp);
l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
l_old_poc_nb = l_tcp->POC ? l_tcp->numpocs + 1 : 0;
l_current_poc_nb += l_old_poc_nb;
if (l_current_poc_nb >= 32) {
opj_event_msg(p_manager, EVT_ERROR, "Too many POCs %d\n", l_current_poc_nb);
return OPJ_FALSE;
}
assert(l_current_poc_nb < 32);
/* now poc is in use.*/
l_tcp->POC = 1;
l_current_poc = &l_tcp->pocs[l_old_poc_nb];
for (i = l_old_poc_nb; i < l_current_poc_nb; ++i) {
opj_read_bytes(p_header_data, &(l_current_poc->resno0),
1); /* RSpoc_i */
++p_header_data;
opj_read_bytes(p_header_data, &(l_current_poc->compno0),
l_comp_room); /* CSpoc_i */
p_header_data += l_comp_room;
opj_read_bytes(p_header_data, &(l_current_poc->layno1),
2); /* LYEpoc_i */
/* make sure layer end is in acceptable bounds */
l_current_poc->layno1 = opj_uint_min(l_current_poc->layno1, l_tcp->numlayers);
p_header_data += 2;
opj_read_bytes(p_header_data, &(l_current_poc->resno1),
1); /* REpoc_i */
++p_header_data;
opj_read_bytes(p_header_data, &(l_current_poc->compno1),
l_comp_room); /* CEpoc_i */
p_header_data += l_comp_room;
opj_read_bytes(p_header_data, &l_tmp,
1); /* Ppoc_i */
++p_header_data;
l_current_poc->prg = (OPJ_PROG_ORDER) l_tmp;
/* make sure comp is in acceptable bounds */
l_current_poc->compno1 = opj_uint_min(l_current_poc->compno1, l_nb_comp);
++l_current_poc;
}
l_tcp->numpocs = l_current_poc_nb - 1;
return OPJ_TRUE;
}
/**
* Reads a CRG marker (Component registration)
*
* @param p_header_data the data contained in the TLM box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the TLM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_crg(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_nb_comp;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_header_data);
l_nb_comp = p_j2k->m_private_image->numcomps;
if (p_header_size != l_nb_comp * 4) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading CRG marker\n");
return OPJ_FALSE;
}
/* Do not care of this at the moment since only local variables are set here */
/*
for
(i = 0; i < l_nb_comp; ++i)
{
opj_read_bytes(p_header_data,&l_Xcrg_i,2); // Xcrg_i
p_header_data+=2;
opj_read_bytes(p_header_data,&l_Ycrg_i,2); // Xcrg_i
p_header_data+=2;
}
*/
return OPJ_TRUE;
}
/**
* Reads a TLM marker (Tile Length Marker)
*
* @param p_header_data the data contained in the TLM box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the TLM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_tlm(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_Ztlm, l_Stlm, l_ST, l_SP, l_tot_num_tp_remaining, l_quotient,
l_Ptlm_size;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_j2k);
if (p_header_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading TLM marker\n");
return OPJ_FALSE;
}
p_header_size -= 2;
opj_read_bytes(p_header_data, &l_Ztlm,
1); /* Ztlm */
++p_header_data;
opj_read_bytes(p_header_data, &l_Stlm,
1); /* Stlm */
++p_header_data;
l_ST = ((l_Stlm >> 4) & 0x3);
l_SP = (l_Stlm >> 6) & 0x1;
l_Ptlm_size = (l_SP + 1) * 2;
l_quotient = l_Ptlm_size + l_ST;
l_tot_num_tp_remaining = p_header_size % l_quotient;
if (l_tot_num_tp_remaining != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading TLM marker\n");
return OPJ_FALSE;
}
/* FIXME Do not care of this at the moment since only local variables are set here */
/*
for
(i = 0; i < l_tot_num_tp; ++i)
{
opj_read_bytes(p_header_data,&l_Ttlm_i,l_ST); // Ttlm_i
p_header_data += l_ST;
opj_read_bytes(p_header_data,&l_Ptlm_i,l_Ptlm_size); // Ptlm_i
p_header_data += l_Ptlm_size;
}*/
return OPJ_TRUE;
}
/**
* Reads a PLM marker (Packet length, main header marker)
*
* @param p_header_data the data contained in the TLM box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the TLM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_plm(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_j2k);
OPJ_UNUSED(p_header_data);
if (p_header_size < 1) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading PLM marker\n");
return OPJ_FALSE;
}
/* Do not care of this at the moment since only local variables are set here */
/*
opj_read_bytes(p_header_data,&l_Zplm,1); // Zplm
++p_header_data;
--p_header_size;
while
(p_header_size > 0)
{
opj_read_bytes(p_header_data,&l_Nplm,1); // Nplm
++p_header_data;
p_header_size -= (1+l_Nplm);
if
(p_header_size < 0)
{
opj_event_msg(p_manager, EVT_ERROR, "Error reading PLM marker\n");
return false;
}
for
(i = 0; i < l_Nplm; ++i)
{
opj_read_bytes(p_header_data,&l_tmp,1); // Iplm_ij
++p_header_data;
// take only the last seven bytes
l_packet_len |= (l_tmp & 0x7f);
if
(l_tmp & 0x80)
{
l_packet_len <<= 7;
}
else
{
// store packet length and proceed to next packet
l_packet_len = 0;
}
}
if
(l_packet_len != 0)
{
opj_event_msg(p_manager, EVT_ERROR, "Error reading PLM marker\n");
return false;
}
}
*/
return OPJ_TRUE;
}
/**
* Reads a PLT marker (Packet length, tile-part header)
*
* @param p_header_data the data contained in the PLT box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the PLT marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_plt(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_Zplt, l_tmp, l_packet_len = 0, i;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_j2k);
if (p_header_size < 1) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading PLT marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_Zplt, 1); /* Zplt */
++p_header_data;
--p_header_size;
for (i = 0; i < p_header_size; ++i) {
opj_read_bytes(p_header_data, &l_tmp, 1); /* Iplt_ij */
++p_header_data;
/* take only the last seven bytes */
l_packet_len |= (l_tmp & 0x7f);
if (l_tmp & 0x80) {
l_packet_len <<= 7;
} else {
/* store packet length and proceed to next packet */
l_packet_len = 0;
}
}
if (l_packet_len != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading PLT marker\n");
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a PPM marker (Packed packet headers, main header)
*
* @param p_header_data the data contained in the POC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the POC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_ppm(
opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager)
{
opj_cp_t *l_cp = 00;
OPJ_UINT32 l_Z_ppm;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
/* We need to have the Z_ppm element + 1 byte of Nppm/Ippm at minimum */
if (p_header_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading PPM marker\n");
return OPJ_FALSE;
}
l_cp = &(p_j2k->m_cp);
l_cp->ppm = 1;
opj_read_bytes(p_header_data, &l_Z_ppm, 1); /* Z_ppm */
++p_header_data;
--p_header_size;
/* check allocation needed */
if (l_cp->ppm_markers == NULL) { /* first PPM marker */
OPJ_UINT32 l_newCount = l_Z_ppm + 1U; /* can't overflow, l_Z_ppm is UINT8 */
assert(l_cp->ppm_markers_count == 0U);
l_cp->ppm_markers = (opj_ppx *) opj_calloc(l_newCount, sizeof(opj_ppx));
if (l_cp->ppm_markers == NULL) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPM marker\n");
return OPJ_FALSE;
}
l_cp->ppm_markers_count = l_newCount;
} else if (l_cp->ppm_markers_count <= l_Z_ppm) {
OPJ_UINT32 l_newCount = l_Z_ppm + 1U; /* can't overflow, l_Z_ppm is UINT8 */
opj_ppx *new_ppm_markers;
new_ppm_markers = (opj_ppx *) opj_realloc(l_cp->ppm_markers,
l_newCount * sizeof(opj_ppx));
if (new_ppm_markers == NULL) {
/* clean up to be done on l_cp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPM marker\n");
return OPJ_FALSE;
}
l_cp->ppm_markers = new_ppm_markers;
memset(l_cp->ppm_markers + l_cp->ppm_markers_count, 0,
(l_newCount - l_cp->ppm_markers_count) * sizeof(opj_ppx));
l_cp->ppm_markers_count = l_newCount;
}
if (l_cp->ppm_markers[l_Z_ppm].m_data != NULL) {
/* clean up to be done on l_cp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Zppm %u already read\n", l_Z_ppm);
return OPJ_FALSE;
}
l_cp->ppm_markers[l_Z_ppm].m_data = (OPJ_BYTE *) opj_malloc(p_header_size);
if (l_cp->ppm_markers[l_Z_ppm].m_data == NULL) {
/* clean up to be done on l_cp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPM marker\n");
return OPJ_FALSE;
}
l_cp->ppm_markers[l_Z_ppm].m_data_size = p_header_size;
memcpy(l_cp->ppm_markers[l_Z_ppm].m_data, p_header_data, p_header_size);
return OPJ_TRUE;
}
/**
* Merges all PPM markers read (Packed headers, main header)
*
* @param p_cp main coding parameters.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_merge_ppm(opj_cp_t *p_cp, opj_event_mgr_t * p_manager)
{
OPJ_UINT32 i, l_ppm_data_size, l_N_ppm_remaining;
/* preconditions */
assert(p_cp != 00);
assert(p_manager != 00);
assert(p_cp->ppm_buffer == NULL);
if (p_cp->ppm == 0U) {
return OPJ_TRUE;
}
l_ppm_data_size = 0U;
l_N_ppm_remaining = 0U;
for (i = 0U; i < p_cp->ppm_markers_count; ++i) {
if (p_cp->ppm_markers[i].m_data !=
NULL) { /* standard doesn't seem to require contiguous Zppm */
OPJ_UINT32 l_N_ppm;
OPJ_UINT32 l_data_size = p_cp->ppm_markers[i].m_data_size;
const OPJ_BYTE* l_data = p_cp->ppm_markers[i].m_data;
if (l_N_ppm_remaining >= l_data_size) {
l_N_ppm_remaining -= l_data_size;
l_data_size = 0U;
} else {
l_data += l_N_ppm_remaining;
l_data_size -= l_N_ppm_remaining;
l_N_ppm_remaining = 0U;
}
if (l_data_size > 0U) {
do {
/* read Nppm */
if (l_data_size < 4U) {
/* clean up to be done on l_cp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Not enough bytes to read Nppm\n");
return OPJ_FALSE;
}
opj_read_bytes(l_data, &l_N_ppm, 4);
l_data += 4;
l_data_size -= 4;
l_ppm_data_size +=
l_N_ppm; /* can't overflow, max 256 markers of max 65536 bytes, that is when PPM markers are not corrupted which is checked elsewhere */
if (l_data_size >= l_N_ppm) {
l_data_size -= l_N_ppm;
l_data += l_N_ppm;
} else {
l_N_ppm_remaining = l_N_ppm - l_data_size;
l_data_size = 0U;
}
} while (l_data_size > 0U);
}
}
}
if (l_N_ppm_remaining != 0U) {
/* clean up to be done on l_cp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Corrupted PPM markers\n");
return OPJ_FALSE;
}
p_cp->ppm_buffer = (OPJ_BYTE *) opj_malloc(l_ppm_data_size);
if (p_cp->ppm_buffer == 00) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPM marker\n");
return OPJ_FALSE;
}
p_cp->ppm_len = l_ppm_data_size;
l_ppm_data_size = 0U;
l_N_ppm_remaining = 0U;
for (i = 0U; i < p_cp->ppm_markers_count; ++i) {
if (p_cp->ppm_markers[i].m_data !=
NULL) { /* standard doesn't seem to require contiguous Zppm */
OPJ_UINT32 l_N_ppm;
OPJ_UINT32 l_data_size = p_cp->ppm_markers[i].m_data_size;
const OPJ_BYTE* l_data = p_cp->ppm_markers[i].m_data;
if (l_N_ppm_remaining >= l_data_size) {
memcpy(p_cp->ppm_buffer + l_ppm_data_size, l_data, l_data_size);
l_ppm_data_size += l_data_size;
l_N_ppm_remaining -= l_data_size;
l_data_size = 0U;
} else {
memcpy(p_cp->ppm_buffer + l_ppm_data_size, l_data, l_N_ppm_remaining);
l_ppm_data_size += l_N_ppm_remaining;
l_data += l_N_ppm_remaining;
l_data_size -= l_N_ppm_remaining;
l_N_ppm_remaining = 0U;
}
if (l_data_size > 0U) {
do {
/* read Nppm */
if (l_data_size < 4U) {
/* clean up to be done on l_cp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Not enough bytes to read Nppm\n");
return OPJ_FALSE;
}
opj_read_bytes(l_data, &l_N_ppm, 4);
l_data += 4;
l_data_size -= 4;
if (l_data_size >= l_N_ppm) {
memcpy(p_cp->ppm_buffer + l_ppm_data_size, l_data, l_N_ppm);
l_ppm_data_size += l_N_ppm;
l_data_size -= l_N_ppm;
l_data += l_N_ppm;
} else {
memcpy(p_cp->ppm_buffer + l_ppm_data_size, l_data, l_data_size);
l_ppm_data_size += l_data_size;
l_N_ppm_remaining = l_N_ppm - l_data_size;
l_data_size = 0U;
}
} while (l_data_size > 0U);
}
opj_free(p_cp->ppm_markers[i].m_data);
p_cp->ppm_markers[i].m_data = NULL;
p_cp->ppm_markers[i].m_data_size = 0U;
}
}
p_cp->ppm_data = p_cp->ppm_buffer;
p_cp->ppm_data_size = p_cp->ppm_len;
p_cp->ppm_markers_count = 0U;
opj_free(p_cp->ppm_markers);
p_cp->ppm_markers = NULL;
return OPJ_TRUE;
}
/**
* Reads a PPT marker (Packed packet headers, tile-part header)
*
* @param p_header_data the data contained in the PPT box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the PPT marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_ppt(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
OPJ_UINT32 l_Z_ppt;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
/* We need to have the Z_ppt element + 1 byte of Ippt at minimum */
if (p_header_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading PPT marker\n");
return OPJ_FALSE;
}
l_cp = &(p_j2k->m_cp);
if (l_cp->ppm) {
opj_event_msg(p_manager, EVT_ERROR,
"Error reading PPT marker: packet header have been previously found in the main header (PPM marker).\n");
return OPJ_FALSE;
}
l_tcp = &(l_cp->tcps[p_j2k->m_current_tile_number]);
l_tcp->ppt = 1;
opj_read_bytes(p_header_data, &l_Z_ppt, 1); /* Z_ppt */
++p_header_data;
--p_header_size;
/* check allocation needed */
if (l_tcp->ppt_markers == NULL) { /* first PPT marker */
OPJ_UINT32 l_newCount = l_Z_ppt + 1U; /* can't overflow, l_Z_ppt is UINT8 */
assert(l_tcp->ppt_markers_count == 0U);
l_tcp->ppt_markers = (opj_ppx *) opj_calloc(l_newCount, sizeof(opj_ppx));
if (l_tcp->ppt_markers == NULL) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPT marker\n");
return OPJ_FALSE;
}
l_tcp->ppt_markers_count = l_newCount;
} else if (l_tcp->ppt_markers_count <= l_Z_ppt) {
OPJ_UINT32 l_newCount = l_Z_ppt + 1U; /* can't overflow, l_Z_ppt is UINT8 */
opj_ppx *new_ppt_markers;
new_ppt_markers = (opj_ppx *) opj_realloc(l_tcp->ppt_markers,
l_newCount * sizeof(opj_ppx));
if (new_ppt_markers == NULL) {
/* clean up to be done on l_tcp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPT marker\n");
return OPJ_FALSE;
}
l_tcp->ppt_markers = new_ppt_markers;
memset(l_tcp->ppt_markers + l_tcp->ppt_markers_count, 0,
(l_newCount - l_tcp->ppt_markers_count) * sizeof(opj_ppx));
l_tcp->ppt_markers_count = l_newCount;
}
if (l_tcp->ppt_markers[l_Z_ppt].m_data != NULL) {
/* clean up to be done on l_tcp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Zppt %u already read\n", l_Z_ppt);
return OPJ_FALSE;
}
l_tcp->ppt_markers[l_Z_ppt].m_data = (OPJ_BYTE *) opj_malloc(p_header_size);
if (l_tcp->ppt_markers[l_Z_ppt].m_data == NULL) {
/* clean up to be done on l_tcp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPT marker\n");
return OPJ_FALSE;
}
l_tcp->ppt_markers[l_Z_ppt].m_data_size = p_header_size;
memcpy(l_tcp->ppt_markers[l_Z_ppt].m_data, p_header_data, p_header_size);
return OPJ_TRUE;
}
/**
* Merges all PPT markers read (Packed packet headers, tile-part header)
*
* @param p_tcp the tile.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_merge_ppt(opj_tcp_t *p_tcp, opj_event_mgr_t * p_manager)
{
OPJ_UINT32 i, l_ppt_data_size;
/* preconditions */
assert(p_tcp != 00);
assert(p_manager != 00);
assert(p_tcp->ppt_buffer == NULL);
if (p_tcp->ppt == 0U) {
return OPJ_TRUE;
}
l_ppt_data_size = 0U;
for (i = 0U; i < p_tcp->ppt_markers_count; ++i) {
l_ppt_data_size +=
p_tcp->ppt_markers[i].m_data_size; /* can't overflow, max 256 markers of max 65536 bytes */
}
p_tcp->ppt_buffer = (OPJ_BYTE *) opj_malloc(l_ppt_data_size);
if (p_tcp->ppt_buffer == 00) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPT marker\n");
return OPJ_FALSE;
}
p_tcp->ppt_len = l_ppt_data_size;
l_ppt_data_size = 0U;
for (i = 0U; i < p_tcp->ppt_markers_count; ++i) {
if (p_tcp->ppt_markers[i].m_data !=
NULL) { /* standard doesn't seem to require contiguous Zppt */
memcpy(p_tcp->ppt_buffer + l_ppt_data_size, p_tcp->ppt_markers[i].m_data,
p_tcp->ppt_markers[i].m_data_size);
l_ppt_data_size +=
p_tcp->ppt_markers[i].m_data_size; /* can't overflow, max 256 markers of max 65536 bytes */
opj_free(p_tcp->ppt_markers[i].m_data);
p_tcp->ppt_markers[i].m_data = NULL;
p_tcp->ppt_markers[i].m_data_size = 0U;
}
}
p_tcp->ppt_markers_count = 0U;
opj_free(p_tcp->ppt_markers);
p_tcp->ppt_markers = NULL;
p_tcp->ppt_data = p_tcp->ppt_buffer;
p_tcp->ppt_data_size = p_tcp->ppt_len;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_tlm(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_BYTE * l_current_data = 00;
OPJ_UINT32 l_tlm_size;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_tlm_size = 6 + (5 * p_j2k->m_specific_param.m_encoder.m_total_tile_parts);
if (l_tlm_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_tlm_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write TLM marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_tlm_size;
}
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
/* change the way data is written to avoid seeking if possible */
/* TODO */
p_j2k->m_specific_param.m_encoder.m_tlm_start = opj_stream_tell(p_stream);
opj_write_bytes(l_current_data, J2K_MS_TLM,
2); /* TLM */
l_current_data += 2;
opj_write_bytes(l_current_data, l_tlm_size - 2,
2); /* Lpoc */
l_current_data += 2;
opj_write_bytes(l_current_data, 0,
1); /* Ztlm=0*/
++l_current_data;
opj_write_bytes(l_current_data, 0x50,
1); /* Stlm ST=1(8bits-255 tiles max),SP=1(Ptlm=32bits) */
++l_current_data;
/* do nothing on the 5 * l_j2k->m_specific_param.m_encoder.m_total_tile_parts remaining data */
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_tlm_size,
p_manager) != l_tlm_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_sot(opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 p_total_data_size,
OPJ_UINT32 * p_data_written,
const opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
OPJ_UNUSED(p_stream);
if (p_total_data_size < 12) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough bytes in output buffer to write SOT marker\n");
return OPJ_FALSE;
}
opj_write_bytes(p_data, J2K_MS_SOT,
2); /* SOT */
p_data += 2;
opj_write_bytes(p_data, 10,
2); /* Lsot */
p_data += 2;
opj_write_bytes(p_data, p_j2k->m_current_tile_number,
2); /* Isot */
p_data += 2;
/* Psot */
p_data += 4;
opj_write_bytes(p_data,
p_j2k->m_specific_param.m_encoder.m_current_tile_part_number,
1); /* TPsot */
++p_data;
opj_write_bytes(p_data,
p_j2k->m_cp.tcps[p_j2k->m_current_tile_number].m_nb_tile_parts,
1); /* TNsot */
++p_data;
/* UniPG>> */
#ifdef USE_JPWL
/* update markers struct */
/*
OPJ_BOOL res = j2k_add_marker(p_j2k->cstr_info, J2K_MS_SOT, p_j2k->sot_start, len + 2);
*/
assert(0 && "TODO");
#endif /* USE_JPWL */
* p_data_written = 12;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_get_sot_values(OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
OPJ_UINT32* p_tile_no,
OPJ_UINT32* p_tot_len,
OPJ_UINT32* p_current_part,
OPJ_UINT32* p_num_parts,
opj_event_mgr_t * p_manager)
{
/* preconditions */
assert(p_header_data != 00);
assert(p_manager != 00);
/* Size of this marker is fixed = 12 (we have already read marker and its size)*/
if (p_header_size != 8) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading SOT marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, p_tile_no, 2); /* Isot */
p_header_data += 2;
opj_read_bytes(p_header_data, p_tot_len, 4); /* Psot */
p_header_data += 4;
opj_read_bytes(p_header_data, p_current_part, 1); /* TPsot */
++p_header_data;
opj_read_bytes(p_header_data, p_num_parts, 1); /* TNsot */
++p_header_data;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_read_sot(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager)
{
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
OPJ_UINT32 l_tot_len, l_num_parts = 0;
OPJ_UINT32 l_current_part;
OPJ_UINT32 l_tile_x, l_tile_y;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_j2k_get_sot_values(p_header_data, p_header_size,
&(p_j2k->m_current_tile_number), &l_tot_len, &l_current_part, &l_num_parts,
p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading SOT marker\n");
return OPJ_FALSE;
}
l_cp = &(p_j2k->m_cp);
/* testcase 2.pdf.SIGFPE.706.1112 */
if (p_j2k->m_current_tile_number >= l_cp->tw * l_cp->th) {
opj_event_msg(p_manager, EVT_ERROR, "Invalid tile number %d\n",
p_j2k->m_current_tile_number);
return OPJ_FALSE;
}
l_tcp = &l_cp->tcps[p_j2k->m_current_tile_number];
l_tile_x = p_j2k->m_current_tile_number % l_cp->tw;
l_tile_y = p_j2k->m_current_tile_number / l_cp->tw;
/* Fixes issue with id_000020,sig_06,src_001958,op_flip4,pos_149 */
/* of https://github.com/uclouvain/openjpeg/issues/939 */
/* We must avoid reading twice the same tile part number for a given tile */
/* so as to avoid various issues, like opj_j2k_merge_ppt being called */
/* several times. */
/* ISO 15444-1 A.4.2 Start of tile-part (SOT) mandates that tile parts */
/* should appear in increasing order. */
if (l_tcp->m_current_tile_part_number + 1 != (OPJ_INT32)l_current_part) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid tile part index for tile number %d. "
"Got %d, expected %d\n",
p_j2k->m_current_tile_number,
l_current_part,
l_tcp->m_current_tile_part_number + 1);
return OPJ_FALSE;
}
++ l_tcp->m_current_tile_part_number;
#ifdef USE_JPWL
if (l_cp->correct) {
OPJ_UINT32 tileno = p_j2k->m_current_tile_number;
static OPJ_UINT32 backup_tileno = 0;
/* tileno is negative or larger than the number of tiles!!! */
if (tileno > (l_cp->tw * l_cp->th)) {
opj_event_msg(p_manager, EVT_ERROR,
"JPWL: bad tile number (%d out of a maximum of %d)\n",
tileno, (l_cp->tw * l_cp->th));
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
/* we try to correct */
tileno = backup_tileno;
opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust this\n"
"- setting tile number to %d\n",
tileno);
}
/* keep your private count of tiles */
backup_tileno++;
};
#endif /* USE_JPWL */
/* look for the tile in the list of already processed tile (in parts). */
/* Optimization possible here with a more complex data structure and with the removing of tiles */
/* since the time taken by this function can only grow at the time */
/* PSot should be equal to zero or >=14 or <= 2^32-1 */
if ((l_tot_len != 0) && (l_tot_len < 14)) {
if (l_tot_len ==
12) { /* MSD: Special case for the PHR data which are read by kakadu*/
opj_event_msg(p_manager, EVT_WARNING, "Empty SOT marker detected: Psot=%d.\n",
l_tot_len);
} else {
opj_event_msg(p_manager, EVT_ERROR,
"Psot value is not correct regards to the JPEG2000 norm: %d.\n", l_tot_len);
return OPJ_FALSE;
}
}
#ifdef USE_JPWL
if (l_cp->correct) {
/* totlen is negative or larger than the bytes left!!! */
if (/*(l_tot_len < 0) ||*/ (l_tot_len >
p_header_size)) { /* FIXME it seems correct; for info in V1 -> (p_stream_numbytesleft(p_stream) + 8))) { */
opj_event_msg(p_manager, EVT_ERROR,
"JPWL: bad tile byte size (%d bytes against %d bytes left)\n",
l_tot_len,
p_header_size); /* FIXME it seems correct; for info in V1 -> p_stream_numbytesleft(p_stream) + 8); */
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
/* we try to correct */
l_tot_len = 0;
opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust this\n"
"- setting Psot to %d => assuming it is the last tile\n",
l_tot_len);
}
};
#endif /* USE_JPWL */
/* Ref A.4.2: Psot could be equal zero if it is the last tile-part of the codestream.*/
if (!l_tot_len) {
opj_event_msg(p_manager, EVT_INFO,
"Psot value of the current tile-part is equal to zero, "
"we assuming it is the last tile-part of the codestream.\n");
p_j2k->m_specific_param.m_decoder.m_last_tile_part = 1;
}
if (l_tcp->m_nb_tile_parts != 0 && l_current_part >= l_tcp->m_nb_tile_parts) {
/* Fixes https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=2851 */
opj_event_msg(p_manager, EVT_ERROR,
"In SOT marker, TPSot (%d) is not valid regards to the previous "
"number of tile-part (%d), giving up\n", l_current_part,
l_tcp->m_nb_tile_parts);
p_j2k->m_specific_param.m_decoder.m_last_tile_part = 1;
return OPJ_FALSE;
}
if (l_num_parts !=
0) { /* Number of tile-part header is provided by this tile-part header */
l_num_parts += p_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction;
/* Useful to manage the case of textGBR.jp2 file because two values of TNSot are allowed: the correct numbers of
* tile-parts for that tile and zero (A.4.2 of 15444-1 : 2002). */
if (l_tcp->m_nb_tile_parts) {
if (l_current_part >= l_tcp->m_nb_tile_parts) {
opj_event_msg(p_manager, EVT_ERROR,
"In SOT marker, TPSot (%d) is not valid regards to the current "
"number of tile-part (%d), giving up\n", l_current_part,
l_tcp->m_nb_tile_parts);
p_j2k->m_specific_param.m_decoder.m_last_tile_part = 1;
return OPJ_FALSE;
}
}
if (l_current_part >= l_num_parts) {
/* testcase 451.pdf.SIGSEGV.ce9.3723 */
opj_event_msg(p_manager, EVT_ERROR,
"In SOT marker, TPSot (%d) is not valid regards to the current "
"number of tile-part (header) (%d), giving up\n", l_current_part, l_num_parts);
p_j2k->m_specific_param.m_decoder.m_last_tile_part = 1;
return OPJ_FALSE;
}
l_tcp->m_nb_tile_parts = l_num_parts;
}
/* If know the number of tile part header we will check if we didn't read the last*/
if (l_tcp->m_nb_tile_parts) {
if (l_tcp->m_nb_tile_parts == (l_current_part + 1)) {
p_j2k->m_specific_param.m_decoder.m_can_decode =
1; /* Process the last tile-part header*/
}
}
if (!p_j2k->m_specific_param.m_decoder.m_last_tile_part) {
/* Keep the size of data to skip after this marker */
p_j2k->m_specific_param.m_decoder.m_sot_length = l_tot_len -
12; /* SOT_marker_size = 12 */
} else {
/* FIXME: need to be computed from the number of bytes remaining in the codestream */
p_j2k->m_specific_param.m_decoder.m_sot_length = 0;
}
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPH;
/* Check if the current tile is outside the area we want decode or not corresponding to the tile index*/
if (p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec == -1) {
p_j2k->m_specific_param.m_decoder.m_skip_data =
(l_tile_x < p_j2k->m_specific_param.m_decoder.m_start_tile_x)
|| (l_tile_x >= p_j2k->m_specific_param.m_decoder.m_end_tile_x)
|| (l_tile_y < p_j2k->m_specific_param.m_decoder.m_start_tile_y)
|| (l_tile_y >= p_j2k->m_specific_param.m_decoder.m_end_tile_y);
} else {
assert(p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec >= 0);
p_j2k->m_specific_param.m_decoder.m_skip_data =
(p_j2k->m_current_tile_number != (OPJ_UINT32)
p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec);
}
/* Index */
if (p_j2k->cstr_index) {
assert(p_j2k->cstr_index->tile_index != 00);
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tileno =
p_j2k->m_current_tile_number;
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_tpsno =
l_current_part;
if (l_num_parts != 0) {
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].nb_tps =
l_num_parts;
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps =
l_num_parts;
if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index) {
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index =
(opj_tp_index_t*)opj_calloc(l_num_parts, sizeof(opj_tp_index_t));
if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to read SOT marker. Tile index allocation failed\n");
return OPJ_FALSE;
}
} else {
opj_tp_index_t *new_tp_index = (opj_tp_index_t *) opj_realloc(
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index,
l_num_parts * sizeof(opj_tp_index_t));
if (! new_tp_index) {
opj_free(p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index);
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index = NULL;
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to read SOT marker. Tile index allocation failed\n");
return OPJ_FALSE;
}
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index =
new_tp_index;
}
} else {
/*if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index)*/ {
if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index) {
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps = 10;
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index =
(opj_tp_index_t*)opj_calloc(
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps,
sizeof(opj_tp_index_t));
if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index) {
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps = 0;
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to read SOT marker. Tile index allocation failed\n");
return OPJ_FALSE;
}
}
if (l_current_part >=
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps) {
opj_tp_index_t *new_tp_index;
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps =
l_current_part + 1;
new_tp_index = (opj_tp_index_t *) opj_realloc(
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index,
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps *
sizeof(opj_tp_index_t));
if (! new_tp_index) {
opj_free(p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index);
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index = NULL;
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps = 0;
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to read SOT marker. Tile index allocation failed\n");
return OPJ_FALSE;
}
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index =
new_tp_index;
}
}
}
}
/* FIXME move this onto a separate method to call before reading any SOT, remove part about main_end header, use a index struct inside p_j2k */
/* if (p_j2k->cstr_info) {
if (l_tcp->first) {
if (tileno == 0) {
p_j2k->cstr_info->main_head_end = p_stream_tell(p_stream) - 13;
}
p_j2k->cstr_info->tile[tileno].tileno = tileno;
p_j2k->cstr_info->tile[tileno].start_pos = p_stream_tell(p_stream) - 12;
p_j2k->cstr_info->tile[tileno].end_pos = p_j2k->cstr_info->tile[tileno].start_pos + totlen - 1;
p_j2k->cstr_info->tile[tileno].num_tps = numparts;
if (numparts) {
p_j2k->cstr_info->tile[tileno].tp = (opj_tp_info_t *) opj_malloc(numparts * sizeof(opj_tp_info_t));
}
else {
p_j2k->cstr_info->tile[tileno].tp = (opj_tp_info_t *) opj_malloc(10 * sizeof(opj_tp_info_t)); // Fixme (10)
}
}
else {
p_j2k->cstr_info->tile[tileno].end_pos += totlen;
}
p_j2k->cstr_info->tile[tileno].tp[partno].tp_start_pos = p_stream_tell(p_stream) - 12;
p_j2k->cstr_info->tile[tileno].tp[partno].tp_end_pos =
p_j2k->cstr_info->tile[tileno].tp[partno].tp_start_pos + totlen - 1;
}*/
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_sod(opj_j2k_t *p_j2k,
opj_tcd_t * p_tile_coder,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_total_data_size,
const opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
opj_codestream_info_t *l_cstr_info = 00;
OPJ_UINT32 l_remaining_data;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
OPJ_UNUSED(p_stream);
if (p_total_data_size < 4) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough bytes in output buffer to write SOD marker\n");
return OPJ_FALSE;
}
opj_write_bytes(p_data, J2K_MS_SOD,
2); /* SOD */
p_data += 2;
/* make room for the EOF marker */
l_remaining_data = p_total_data_size - 4;
/* update tile coder */
p_tile_coder->tp_num =
p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number ;
p_tile_coder->cur_tp_num =
p_j2k->m_specific_param.m_encoder.m_current_tile_part_number;
/* INDEX >> */
/* TODO mergeV2: check this part which use cstr_info */
/*l_cstr_info = p_j2k->cstr_info;
if (l_cstr_info) {
if (!p_j2k->m_specific_param.m_encoder.m_current_tile_part_number ) {
//TODO cstr_info->tile[p_j2k->m_current_tile_number].end_header = p_stream_tell(p_stream) + p_j2k->pos_correction - 1;
l_cstr_info->tile[p_j2k->m_current_tile_number].tileno = p_j2k->m_current_tile_number;
}
else {*/
/*
TODO
if
(cstr_info->tile[p_j2k->m_current_tile_number].packet[cstr_info->packno - 1].end_pos < p_stream_tell(p_stream))
{
cstr_info->tile[p_j2k->m_current_tile_number].packet[cstr_info->packno].start_pos = p_stream_tell(p_stream);
}*/
/*}*/
/* UniPG>> */
#ifdef USE_JPWL
/* update markers struct */
/*OPJ_BOOL res = j2k_add_marker(p_j2k->cstr_info, J2K_MS_SOD, p_j2k->sod_start, 2);
*/
assert(0 && "TODO");
#endif /* USE_JPWL */
/* <<UniPG */
/*}*/
/* << INDEX */
if (p_j2k->m_specific_param.m_encoder.m_current_tile_part_number == 0) {
p_tile_coder->tcd_image->tiles->packno = 0;
if (l_cstr_info) {
l_cstr_info->packno = 0;
}
}
*p_data_written = 0;
if (! opj_tcd_encode_tile(p_tile_coder, p_j2k->m_current_tile_number, p_data,
p_data_written, l_remaining_data, l_cstr_info,
p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Cannot encode tile\n");
return OPJ_FALSE;
}
*p_data_written += 2;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_read_sod(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_SIZE_T l_current_read_size;
opj_codestream_index_t * l_cstr_index = 00;
OPJ_BYTE ** l_current_data = 00;
opj_tcp_t * l_tcp = 00;
OPJ_UINT32 * l_tile_len = 00;
OPJ_BOOL l_sot_length_pb_detected = OPJ_FALSE;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_tcp = &(p_j2k->m_cp.tcps[p_j2k->m_current_tile_number]);
if (p_j2k->m_specific_param.m_decoder.m_last_tile_part) {
/* opj_stream_get_number_byte_left returns OPJ_OFF_T
// but we are in the last tile part,
// so its result will fit on OPJ_UINT32 unless we find
// a file with a single tile part of more than 4 GB...*/
p_j2k->m_specific_param.m_decoder.m_sot_length = (OPJ_UINT32)(
opj_stream_get_number_byte_left(p_stream) - 2);
} else {
/* Check to avoid pass the limit of OPJ_UINT32 */
if (p_j2k->m_specific_param.m_decoder.m_sot_length >= 2) {
p_j2k->m_specific_param.m_decoder.m_sot_length -= 2;
} else {
/* MSD: case commented to support empty SOT marker (PHR data) */
}
}
l_current_data = &(l_tcp->m_data);
l_tile_len = &l_tcp->m_data_size;
/* Patch to support new PHR data */
if (p_j2k->m_specific_param.m_decoder.m_sot_length) {
/* If we are here, we'll try to read the data after allocation */
/* Check enough bytes left in stream before allocation */
if ((OPJ_OFF_T)p_j2k->m_specific_param.m_decoder.m_sot_length >
opj_stream_get_number_byte_left(p_stream)) {
opj_event_msg(p_manager, EVT_ERROR,
"Tile part length size inconsistent with stream length\n");
return OPJ_FALSE;
}
if (p_j2k->m_specific_param.m_decoder.m_sot_length >
UINT_MAX - OPJ_COMMON_CBLK_DATA_EXTRA) {
opj_event_msg(p_manager, EVT_ERROR,
"p_j2k->m_specific_param.m_decoder.m_sot_length > "
"UINT_MAX - OPJ_COMMON_CBLK_DATA_EXTRA");
return OPJ_FALSE;
}
/* Add a margin of OPJ_COMMON_CBLK_DATA_EXTRA to the allocation we */
/* do so that opj_mqc_init_dec_common() can safely add a synthetic */
/* 0xFFFF marker. */
if (! *l_current_data) {
/* LH: oddly enough, in this path, l_tile_len!=0.
* TODO: If this was consistent, we could simplify the code to only use realloc(), as realloc(0,...) default to malloc(0,...).
*/
*l_current_data = (OPJ_BYTE*) opj_malloc(
p_j2k->m_specific_param.m_decoder.m_sot_length + OPJ_COMMON_CBLK_DATA_EXTRA);
} else {
OPJ_BYTE *l_new_current_data;
if (*l_tile_len > UINT_MAX - OPJ_COMMON_CBLK_DATA_EXTRA -
p_j2k->m_specific_param.m_decoder.m_sot_length) {
opj_event_msg(p_manager, EVT_ERROR,
"*l_tile_len > UINT_MAX - OPJ_COMMON_CBLK_DATA_EXTRA - "
"p_j2k->m_specific_param.m_decoder.m_sot_length");
return OPJ_FALSE;
}
l_new_current_data = (OPJ_BYTE *) opj_realloc(*l_current_data,
*l_tile_len + p_j2k->m_specific_param.m_decoder.m_sot_length +
OPJ_COMMON_CBLK_DATA_EXTRA);
if (! l_new_current_data) {
opj_free(*l_current_data);
/*nothing more is done as l_current_data will be set to null, and just
afterward we enter in the error path
and the actual tile_len is updated (committed) at the end of the
function. */
}
*l_current_data = l_new_current_data;
}
if (*l_current_data == 00) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to decode tile\n");
return OPJ_FALSE;
}
} else {
l_sot_length_pb_detected = OPJ_TRUE;
}
/* Index */
l_cstr_index = p_j2k->cstr_index;
if (l_cstr_index) {
OPJ_OFF_T l_current_pos = opj_stream_tell(p_stream) - 2;
OPJ_UINT32 l_current_tile_part =
l_cstr_index->tile_index[p_j2k->m_current_tile_number].current_tpsno;
l_cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index[l_current_tile_part].end_header
=
l_current_pos;
l_cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index[l_current_tile_part].end_pos
=
l_current_pos + p_j2k->m_specific_param.m_decoder.m_sot_length + 2;
if (OPJ_FALSE == opj_j2k_add_tlmarker(p_j2k->m_current_tile_number,
l_cstr_index,
J2K_MS_SOD,
l_current_pos,
p_j2k->m_specific_param.m_decoder.m_sot_length + 2)) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add tl marker\n");
return OPJ_FALSE;
}
/*l_cstr_index->packno = 0;*/
}
/* Patch to support new PHR data */
if (!l_sot_length_pb_detected) {
l_current_read_size = opj_stream_read_data(
p_stream,
*l_current_data + *l_tile_len,
p_j2k->m_specific_param.m_decoder.m_sot_length,
p_manager);
} else {
l_current_read_size = 0;
}
if (l_current_read_size != p_j2k->m_specific_param.m_decoder.m_sot_length) {
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_NEOC;
} else {
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPHSOT;
}
*l_tile_len += (OPJ_UINT32)l_current_read_size;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_rgn(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no,
OPJ_UINT32 nb_comps,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_BYTE * l_current_data = 00;
OPJ_UINT32 l_rgn_size;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_tccp_t *l_tccp = 00;
OPJ_UINT32 l_comp_room;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_tile_no];
l_tccp = &l_tcp->tccps[p_comp_no];
if (nb_comps <= 256) {
l_comp_room = 1;
} else {
l_comp_room = 2;
}
l_rgn_size = 6 + l_comp_room;
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_data, J2K_MS_RGN,
2); /* RGN */
l_current_data += 2;
opj_write_bytes(l_current_data, l_rgn_size - 2,
2); /* Lrgn */
l_current_data += 2;
opj_write_bytes(l_current_data, p_comp_no,
l_comp_room); /* Crgn */
l_current_data += l_comp_room;
opj_write_bytes(l_current_data, 0,
1); /* Srgn */
++l_current_data;
opj_write_bytes(l_current_data, (OPJ_UINT32)l_tccp->roishift,
1); /* SPrgn */
++l_current_data;
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_rgn_size,
p_manager) != l_rgn_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_eoc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
opj_write_bytes(p_j2k->m_specific_param.m_encoder.m_header_tile_data,
J2K_MS_EOC, 2); /* EOC */
/* UniPG>> */
#ifdef USE_JPWL
/* update markers struct */
/*
OPJ_BOOL res = j2k_add_marker(p_j2k->cstr_info, J2K_MS_EOC, p_stream_tell(p_stream) - 2, 2);
*/
#endif /* USE_JPWL */
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, 2, p_manager) != 2) {
return OPJ_FALSE;
}
if (! opj_stream_flush(p_stream, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a RGN marker (Region Of Interest)
*
* @param p_header_data the data contained in the POC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the POC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_rgn(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_nb_comp;
opj_image_t * l_image = 00;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
OPJ_UINT32 l_comp_room, l_comp_no, l_roi_sty;
/* preconditions*/
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_image = p_j2k->m_private_image;
l_nb_comp = l_image->numcomps;
if (l_nb_comp <= 256) {
l_comp_room = 1;
} else {
l_comp_room = 2;
}
if (p_header_size != 2 + l_comp_room) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading RGN marker\n");
return OPJ_FALSE;
}
l_cp = &(p_j2k->m_cp);
l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
opj_read_bytes(p_header_data, &l_comp_no, l_comp_room); /* Crgn */
p_header_data += l_comp_room;
opj_read_bytes(p_header_data, &l_roi_sty,
1); /* Srgn */
++p_header_data;
#ifdef USE_JPWL
if (l_cp->correct) {
/* totlen is negative or larger than the bytes left!!! */
if (l_comp_room >= l_nb_comp) {
opj_event_msg(p_manager, EVT_ERROR,
"JPWL: bad component number in RGN (%d when there are only %d)\n",
l_comp_room, l_nb_comp);
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
}
};
#endif /* USE_JPWL */
/* testcase 3635.pdf.asan.77.2930 */
if (l_comp_no >= l_nb_comp) {
opj_event_msg(p_manager, EVT_ERROR,
"bad component number in RGN (%d when there are only %d)\n",
l_comp_no, l_nb_comp);
return OPJ_FALSE;
}
opj_read_bytes(p_header_data,
(OPJ_UINT32 *)(&(l_tcp->tccps[l_comp_no].roishift)), 1); /* SPrgn */
++p_header_data;
return OPJ_TRUE;
}
static OPJ_FLOAT32 opj_j2k_get_tp_stride(opj_tcp_t * p_tcp)
{
return (OPJ_FLOAT32)((p_tcp->m_nb_tile_parts - 1) * 14);
}
static OPJ_FLOAT32 opj_j2k_get_default_stride(opj_tcp_t * p_tcp)
{
(void)p_tcp;
return 0;
}
static OPJ_BOOL opj_j2k_update_rates(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
opj_cp_t * l_cp = 00;
opj_image_t * l_image = 00;
opj_tcp_t * l_tcp = 00;
opj_image_comp_t * l_img_comp = 00;
OPJ_UINT32 i, j, k;
OPJ_INT32 l_x0, l_y0, l_x1, l_y1;
OPJ_FLOAT32 * l_rates = 0;
OPJ_FLOAT32 l_sot_remove;
OPJ_UINT32 l_bits_empty, l_size_pixel;
OPJ_UINT32 l_tile_size = 0;
OPJ_UINT32 l_last_res;
OPJ_FLOAT32(* l_tp_stride_func)(opj_tcp_t *) = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
OPJ_UNUSED(p_manager);
l_cp = &(p_j2k->m_cp);
l_image = p_j2k->m_private_image;
l_tcp = l_cp->tcps;
l_bits_empty = 8 * l_image->comps->dx * l_image->comps->dy;
l_size_pixel = l_image->numcomps * l_image->comps->prec;
l_sot_remove = (OPJ_FLOAT32) opj_stream_tell(p_stream) / (OPJ_FLOAT32)(
l_cp->th * l_cp->tw);
if (l_cp->m_specific_param.m_enc.m_tp_on) {
l_tp_stride_func = opj_j2k_get_tp_stride;
} else {
l_tp_stride_func = opj_j2k_get_default_stride;
}
for (i = 0; i < l_cp->th; ++i) {
for (j = 0; j < l_cp->tw; ++j) {
OPJ_FLOAT32 l_offset = (OPJ_FLOAT32)(*l_tp_stride_func)(l_tcp) /
(OPJ_FLOAT32)l_tcp->numlayers;
/* 4 borders of the tile rescale on the image if necessary */
l_x0 = opj_int_max((OPJ_INT32)(l_cp->tx0 + j * l_cp->tdx),
(OPJ_INT32)l_image->x0);
l_y0 = opj_int_max((OPJ_INT32)(l_cp->ty0 + i * l_cp->tdy),
(OPJ_INT32)l_image->y0);
l_x1 = opj_int_min((OPJ_INT32)(l_cp->tx0 + (j + 1) * l_cp->tdx),
(OPJ_INT32)l_image->x1);
l_y1 = opj_int_min((OPJ_INT32)(l_cp->ty0 + (i + 1) * l_cp->tdy),
(OPJ_INT32)l_image->y1);
l_rates = l_tcp->rates;
/* Modification of the RATE >> */
if (*l_rates > 0.0f) {
*l_rates = (((OPJ_FLOAT32)(l_size_pixel * (OPJ_UINT32)(l_x1 - l_x0) *
(OPJ_UINT32)(l_y1 - l_y0)))
/
((*l_rates) * (OPJ_FLOAT32)l_bits_empty)
)
-
l_offset;
}
++l_rates;
for (k = 1; k < l_tcp->numlayers; ++k) {
if (*l_rates > 0.0f) {
*l_rates = (((OPJ_FLOAT32)(l_size_pixel * (OPJ_UINT32)(l_x1 - l_x0) *
(OPJ_UINT32)(l_y1 - l_y0)))
/
((*l_rates) * (OPJ_FLOAT32)l_bits_empty)
)
-
l_offset;
}
++l_rates;
}
++l_tcp;
}
}
l_tcp = l_cp->tcps;
for (i = 0; i < l_cp->th; ++i) {
for (j = 0; j < l_cp->tw; ++j) {
l_rates = l_tcp->rates;
if (*l_rates > 0.0f) {
*l_rates -= l_sot_remove;
if (*l_rates < 30.0f) {
*l_rates = 30.0f;
}
}
++l_rates;
l_last_res = l_tcp->numlayers - 1;
for (k = 1; k < l_last_res; ++k) {
if (*l_rates > 0.0f) {
*l_rates -= l_sot_remove;
if (*l_rates < * (l_rates - 1) + 10.0f) {
*l_rates = (*(l_rates - 1)) + 20.0f;
}
}
++l_rates;
}
if (*l_rates > 0.0f) {
*l_rates -= (l_sot_remove + 2.f);
if (*l_rates < * (l_rates - 1) + 10.0f) {
*l_rates = (*(l_rates - 1)) + 20.0f;
}
}
++l_tcp;
}
}
l_img_comp = l_image->comps;
l_tile_size = 0;
for (i = 0; i < l_image->numcomps; ++i) {
l_tile_size += (opj_uint_ceildiv(l_cp->tdx, l_img_comp->dx)
*
opj_uint_ceildiv(l_cp->tdy, l_img_comp->dy)
*
l_img_comp->prec
);
++l_img_comp;
}
l_tile_size = (OPJ_UINT32)(l_tile_size * 0.1625); /* 1.3/8 = 0.1625 */
l_tile_size += opj_j2k_get_specific_header_sizes(p_j2k);
p_j2k->m_specific_param.m_encoder.m_encoded_tile_size = l_tile_size;
p_j2k->m_specific_param.m_encoder.m_encoded_tile_data =
(OPJ_BYTE *) opj_malloc(p_j2k->m_specific_param.m_encoder.m_encoded_tile_size);
if (p_j2k->m_specific_param.m_encoder.m_encoded_tile_data == 00) {
return OPJ_FALSE;
}
if (OPJ_IS_CINEMA(l_cp->rsiz)) {
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer =
(OPJ_BYTE *) opj_malloc(5 *
p_j2k->m_specific_param.m_encoder.m_total_tile_parts);
if (! p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer) {
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current =
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer;
}
return OPJ_TRUE;
}
#if 0
static OPJ_BOOL opj_j2k_read_eoc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 i;
opj_tcd_t * l_tcd = 00;
OPJ_UINT32 l_nb_tiles;
opj_tcp_t * l_tcp = 00;
OPJ_BOOL l_success;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
l_tcp = p_j2k->m_cp.tcps;
l_tcd = opj_tcd_create(OPJ_TRUE);
if (l_tcd == 00) {
opj_event_msg(p_manager, EVT_ERROR, "Cannot decode tile, memory error\n");
return OPJ_FALSE;
}
for (i = 0; i < l_nb_tiles; ++i) {
if (l_tcp->m_data) {
if (! opj_tcd_init_decode_tile(l_tcd, i)) {
opj_tcd_destroy(l_tcd);
opj_event_msg(p_manager, EVT_ERROR, "Cannot decode tile, memory error\n");
return OPJ_FALSE;
}
l_success = opj_tcd_decode_tile(l_tcd, l_tcp->m_data, l_tcp->m_data_size, i,
p_j2k->cstr_index);
/* cleanup */
if (! l_success) {
p_j2k->m_specific_param.m_decoder.m_state |= J2K_STATE_ERR;
break;
}
}
opj_j2k_tcp_destroy(l_tcp);
++l_tcp;
}
opj_tcd_destroy(l_tcd);
return OPJ_TRUE;
}
#endif
static OPJ_BOOL opj_j2k_get_end_header(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
OPJ_UNUSED(p_manager);
p_j2k->cstr_index->main_head_end = opj_stream_tell(p_stream);
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_mct_data_group(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 i;
opj_simple_mcc_decorrelation_data_t * l_mcc_record;
opj_mct_data_t * l_mct_record;
opj_tcp_t * l_tcp;
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
if (! opj_j2k_write_cbd(p_j2k, p_stream, p_manager)) {
return OPJ_FALSE;
}
l_tcp = &(p_j2k->m_cp.tcps[p_j2k->m_current_tile_number]);
l_mct_record = l_tcp->m_mct_records;
for (i = 0; i < l_tcp->m_nb_mct_records; ++i) {
if (! opj_j2k_write_mct_record(p_j2k, l_mct_record, p_stream, p_manager)) {
return OPJ_FALSE;
}
++l_mct_record;
}
l_mcc_record = l_tcp->m_mcc_records;
for (i = 0; i < l_tcp->m_nb_mcc_records; ++i) {
if (! opj_j2k_write_mcc_record(p_j2k, l_mcc_record, p_stream, p_manager)) {
return OPJ_FALSE;
}
++l_mcc_record;
}
if (! opj_j2k_write_mco(p_j2k, p_stream, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_all_coc(
opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 compno;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
for (compno = 1; compno < p_j2k->m_private_image->numcomps; ++compno) {
/* cod is first component of first tile */
if (! opj_j2k_compare_coc(p_j2k, 0, compno)) {
if (! opj_j2k_write_coc(p_j2k, compno, p_stream, p_manager)) {
return OPJ_FALSE;
}
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_all_qcc(
opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 compno;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
for (compno = 1; compno < p_j2k->m_private_image->numcomps; ++compno) {
/* qcd is first component of first tile */
if (! opj_j2k_compare_qcc(p_j2k, 0, compno)) {
if (! opj_j2k_write_qcc(p_j2k, compno, p_stream, p_manager)) {
return OPJ_FALSE;
}
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_regions(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 compno;
const opj_tccp_t *l_tccp = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_tccp = p_j2k->m_cp.tcps->tccps;
for (compno = 0; compno < p_j2k->m_private_image->numcomps; ++compno) {
if (l_tccp->roishift) {
if (! opj_j2k_write_rgn(p_j2k, 0, compno, p_j2k->m_private_image->numcomps,
p_stream, p_manager)) {
return OPJ_FALSE;
}
}
++l_tccp;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_epc(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
opj_codestream_index_t * l_cstr_index = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
OPJ_UNUSED(p_manager);
l_cstr_index = p_j2k->cstr_index;
if (l_cstr_index) {
l_cstr_index->codestream_size = (OPJ_UINT64)opj_stream_tell(p_stream);
/* UniPG>> */
/* The following adjustment is done to adjust the codestream size */
/* if SOD is not at 0 in the buffer. Useful in case of JP2, where */
/* the first bunch of bytes is not in the codestream */
l_cstr_index->codestream_size -= (OPJ_UINT64)l_cstr_index->main_head_start;
/* <<UniPG */
}
#ifdef USE_JPWL
/* preparation of JPWL marker segments */
#if 0
if (cp->epc_on) {
/* encode according to JPWL */
jpwl_encode(p_j2k, p_stream, image);
}
#endif
assert(0 && "TODO");
#endif /* USE_JPWL */
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_read_unk(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
OPJ_UINT32 *output_marker,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_unknown_marker;
const opj_dec_memory_marker_handler_t * l_marker_handler;
OPJ_UINT32 l_size_unk = 2;
/* preconditions*/
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
opj_event_msg(p_manager, EVT_WARNING, "Unknown marker\n");
for (;;) {
/* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer*/
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* read 2 bytes as the new marker ID*/
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,
&l_unknown_marker, 2);
if (!(l_unknown_marker < 0xff00)) {
/* Get the marker handler from the marker ID*/
l_marker_handler = opj_j2k_get_marker_handler(l_unknown_marker);
if (!(p_j2k->m_specific_param.m_decoder.m_state & l_marker_handler->states)) {
opj_event_msg(p_manager, EVT_ERROR,
"Marker is not compliant with its position\n");
return OPJ_FALSE;
} else {
if (l_marker_handler->id != J2K_MS_UNK) {
/* Add the marker to the codestream index*/
if (l_marker_handler->id != J2K_MS_SOT) {
OPJ_BOOL res = opj_j2k_add_mhmarker(p_j2k->cstr_index, J2K_MS_UNK,
(OPJ_UINT32) opj_stream_tell(p_stream) - l_size_unk,
l_size_unk);
if (res == OPJ_FALSE) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add mh marker\n");
return OPJ_FALSE;
}
}
break; /* next marker is known and well located */
} else {
l_size_unk += 2;
}
}
}
}
*output_marker = l_marker_handler->id ;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_mct_record(opj_j2k_t *p_j2k,
opj_mct_data_t * p_mct_record,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 l_mct_size;
OPJ_BYTE * l_current_data = 00;
OPJ_UINT32 l_tmp;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_mct_size = 10 + p_mct_record->m_data_size;
if (l_mct_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mct_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write MCT marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_mct_size;
}
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_data, J2K_MS_MCT,
2); /* MCT */
l_current_data += 2;
opj_write_bytes(l_current_data, l_mct_size - 2,
2); /* Lmct */
l_current_data += 2;
opj_write_bytes(l_current_data, 0,
2); /* Zmct */
l_current_data += 2;
/* only one marker atm */
l_tmp = (p_mct_record->m_index & 0xff) | (p_mct_record->m_array_type << 8) |
(p_mct_record->m_element_type << 10);
opj_write_bytes(l_current_data, l_tmp, 2);
l_current_data += 2;
opj_write_bytes(l_current_data, 0,
2); /* Ymct */
l_current_data += 2;
memcpy(l_current_data, p_mct_record->m_data, p_mct_record->m_data_size);
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mct_size,
p_manager) != l_mct_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a MCT marker (Multiple Component Transform)
*
* @param p_header_data the data contained in the MCT box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the MCT marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_mct(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 i;
opj_tcp_t *l_tcp = 00;
OPJ_UINT32 l_tmp;
OPJ_UINT32 l_indix;
opj_mct_data_t * l_mct_data;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
l_tcp = p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH ?
&p_j2k->m_cp.tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
if (p_header_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCT marker\n");
return OPJ_FALSE;
}
/* first marker */
opj_read_bytes(p_header_data, &l_tmp, 2); /* Zmct */
p_header_data += 2;
if (l_tmp != 0) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge mct data within multiple MCT records\n");
return OPJ_TRUE;
}
if (p_header_size <= 6) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCT marker\n");
return OPJ_FALSE;
}
/* Imct -> no need for other values, take the first, type is double with decorrelation x0000 1101 0000 0000*/
opj_read_bytes(p_header_data, &l_tmp, 2); /* Imct */
p_header_data += 2;
l_indix = l_tmp & 0xff;
l_mct_data = l_tcp->m_mct_records;
for (i = 0; i < l_tcp->m_nb_mct_records; ++i) {
if (l_mct_data->m_index == l_indix) {
break;
}
++l_mct_data;
}
/* NOT FOUND */
if (i == l_tcp->m_nb_mct_records) {
if (l_tcp->m_nb_mct_records == l_tcp->m_nb_max_mct_records) {
opj_mct_data_t *new_mct_records;
l_tcp->m_nb_max_mct_records += OPJ_J2K_MCT_DEFAULT_NB_RECORDS;
new_mct_records = (opj_mct_data_t *) opj_realloc(l_tcp->m_mct_records,
l_tcp->m_nb_max_mct_records * sizeof(opj_mct_data_t));
if (! new_mct_records) {
opj_free(l_tcp->m_mct_records);
l_tcp->m_mct_records = NULL;
l_tcp->m_nb_max_mct_records = 0;
l_tcp->m_nb_mct_records = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read MCT marker\n");
return OPJ_FALSE;
}
/* Update m_mcc_records[].m_offset_array and m_decorrelation_array
* to point to the new addresses */
if (new_mct_records != l_tcp->m_mct_records) {
for (i = 0; i < l_tcp->m_nb_mcc_records; ++i) {
opj_simple_mcc_decorrelation_data_t* l_mcc_record =
&(l_tcp->m_mcc_records[i]);
if (l_mcc_record->m_decorrelation_array) {
l_mcc_record->m_decorrelation_array =
new_mct_records +
(l_mcc_record->m_decorrelation_array -
l_tcp->m_mct_records);
}
if (l_mcc_record->m_offset_array) {
l_mcc_record->m_offset_array =
new_mct_records +
(l_mcc_record->m_offset_array -
l_tcp->m_mct_records);
}
}
}
l_tcp->m_mct_records = new_mct_records;
l_mct_data = l_tcp->m_mct_records + l_tcp->m_nb_mct_records;
memset(l_mct_data, 0, (l_tcp->m_nb_max_mct_records - l_tcp->m_nb_mct_records) *
sizeof(opj_mct_data_t));
}
l_mct_data = l_tcp->m_mct_records + l_tcp->m_nb_mct_records;
++l_tcp->m_nb_mct_records;
}
if (l_mct_data->m_data) {
opj_free(l_mct_data->m_data);
l_mct_data->m_data = 00;
l_mct_data->m_data_size = 0;
}
l_mct_data->m_index = l_indix;
l_mct_data->m_array_type = (J2K_MCT_ARRAY_TYPE)((l_tmp >> 8) & 3);
l_mct_data->m_element_type = (J2K_MCT_ELEMENT_TYPE)((l_tmp >> 10) & 3);
opj_read_bytes(p_header_data, &l_tmp, 2); /* Ymct */
p_header_data += 2;
if (l_tmp != 0) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge multiple MCT markers\n");
return OPJ_TRUE;
}
p_header_size -= 6;
l_mct_data->m_data = (OPJ_BYTE*)opj_malloc(p_header_size);
if (! l_mct_data->m_data) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCT marker\n");
return OPJ_FALSE;
}
memcpy(l_mct_data->m_data, p_header_data, p_header_size);
l_mct_data->m_data_size = p_header_size;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_mcc_record(opj_j2k_t *p_j2k,
struct opj_simple_mcc_decorrelation_data * p_mcc_record,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 i;
OPJ_UINT32 l_mcc_size;
OPJ_BYTE * l_current_data = 00;
OPJ_UINT32 l_nb_bytes_for_comp;
OPJ_UINT32 l_mask;
OPJ_UINT32 l_tmcc;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
if (p_mcc_record->m_nb_comps > 255) {
l_nb_bytes_for_comp = 2;
l_mask = 0x8000;
} else {
l_nb_bytes_for_comp = 1;
l_mask = 0;
}
l_mcc_size = p_mcc_record->m_nb_comps * 2 * l_nb_bytes_for_comp + 19;
if (l_mcc_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mcc_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write MCC marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_mcc_size;
}
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_data, J2K_MS_MCC,
2); /* MCC */
l_current_data += 2;
opj_write_bytes(l_current_data, l_mcc_size - 2,
2); /* Lmcc */
l_current_data += 2;
/* first marker */
opj_write_bytes(l_current_data, 0,
2); /* Zmcc */
l_current_data += 2;
opj_write_bytes(l_current_data, p_mcc_record->m_index,
1); /* Imcc -> no need for other values, take the first */
++l_current_data;
/* only one marker atm */
opj_write_bytes(l_current_data, 0,
2); /* Ymcc */
l_current_data += 2;
opj_write_bytes(l_current_data, 1,
2); /* Qmcc -> number of collections -> 1 */
l_current_data += 2;
opj_write_bytes(l_current_data, 0x1,
1); /* Xmcci type of component transformation -> array based decorrelation */
++l_current_data;
opj_write_bytes(l_current_data, p_mcc_record->m_nb_comps | l_mask,
2); /* Nmcci number of input components involved and size for each component offset = 8 bits */
l_current_data += 2;
for (i = 0; i < p_mcc_record->m_nb_comps; ++i) {
opj_write_bytes(l_current_data, i,
l_nb_bytes_for_comp); /* Cmccij Component offset*/
l_current_data += l_nb_bytes_for_comp;
}
opj_write_bytes(l_current_data, p_mcc_record->m_nb_comps | l_mask,
2); /* Mmcci number of output components involved and size for each component offset = 8 bits */
l_current_data += 2;
for (i = 0; i < p_mcc_record->m_nb_comps; ++i) {
opj_write_bytes(l_current_data, i,
l_nb_bytes_for_comp); /* Wmccij Component offset*/
l_current_data += l_nb_bytes_for_comp;
}
l_tmcc = ((!p_mcc_record->m_is_irreversible) & 1U) << 16;
if (p_mcc_record->m_decorrelation_array) {
l_tmcc |= p_mcc_record->m_decorrelation_array->m_index;
}
if (p_mcc_record->m_offset_array) {
l_tmcc |= ((p_mcc_record->m_offset_array->m_index) << 8);
}
opj_write_bytes(l_current_data, l_tmcc,
3); /* Tmcci : use MCT defined as number 1 and irreversible array based. */
l_current_data += 3;
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mcc_size,
p_manager) != l_mcc_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_read_mcc(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 i, j;
OPJ_UINT32 l_tmp;
OPJ_UINT32 l_indix;
opj_tcp_t * l_tcp;
opj_simple_mcc_decorrelation_data_t * l_mcc_record;
opj_mct_data_t * l_mct_data;
OPJ_UINT32 l_nb_collections;
OPJ_UINT32 l_nb_comps;
OPJ_UINT32 l_nb_bytes_by_comp;
OPJ_BOOL l_new_mcc = OPJ_FALSE;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_tcp = p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH ?
&p_j2k->m_cp.tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
if (p_header_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
/* first marker */
opj_read_bytes(p_header_data, &l_tmp, 2); /* Zmcc */
p_header_data += 2;
if (l_tmp != 0) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge multiple data spanning\n");
return OPJ_TRUE;
}
if (p_header_size < 7) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_indix,
1); /* Imcc -> no need for other values, take the first */
++p_header_data;
l_mcc_record = l_tcp->m_mcc_records;
for (i = 0; i < l_tcp->m_nb_mcc_records; ++i) {
if (l_mcc_record->m_index == l_indix) {
break;
}
++l_mcc_record;
}
/** NOT FOUND */
if (i == l_tcp->m_nb_mcc_records) {
if (l_tcp->m_nb_mcc_records == l_tcp->m_nb_max_mcc_records) {
opj_simple_mcc_decorrelation_data_t *new_mcc_records;
l_tcp->m_nb_max_mcc_records += OPJ_J2K_MCC_DEFAULT_NB_RECORDS;
new_mcc_records = (opj_simple_mcc_decorrelation_data_t *) opj_realloc(
l_tcp->m_mcc_records, l_tcp->m_nb_max_mcc_records * sizeof(
opj_simple_mcc_decorrelation_data_t));
if (! new_mcc_records) {
opj_free(l_tcp->m_mcc_records);
l_tcp->m_mcc_records = NULL;
l_tcp->m_nb_max_mcc_records = 0;
l_tcp->m_nb_mcc_records = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read MCC marker\n");
return OPJ_FALSE;
}
l_tcp->m_mcc_records = new_mcc_records;
l_mcc_record = l_tcp->m_mcc_records + l_tcp->m_nb_mcc_records;
memset(l_mcc_record, 0, (l_tcp->m_nb_max_mcc_records - l_tcp->m_nb_mcc_records)
* sizeof(opj_simple_mcc_decorrelation_data_t));
}
l_mcc_record = l_tcp->m_mcc_records + l_tcp->m_nb_mcc_records;
l_new_mcc = OPJ_TRUE;
}
l_mcc_record->m_index = l_indix;
/* only one marker atm */
opj_read_bytes(p_header_data, &l_tmp, 2); /* Ymcc */
p_header_data += 2;
if (l_tmp != 0) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge multiple data spanning\n");
return OPJ_TRUE;
}
opj_read_bytes(p_header_data, &l_nb_collections,
2); /* Qmcc -> number of collections -> 1 */
p_header_data += 2;
if (l_nb_collections > 1) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge multiple collections\n");
return OPJ_TRUE;
}
p_header_size -= 7;
for (i = 0; i < l_nb_collections; ++i) {
if (p_header_size < 3) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_tmp,
1); /* Xmcci type of component transformation -> array based decorrelation */
++p_header_data;
if (l_tmp != 1) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge collections other than array decorrelation\n");
return OPJ_TRUE;
}
opj_read_bytes(p_header_data, &l_nb_comps, 2);
p_header_data += 2;
p_header_size -= 3;
l_nb_bytes_by_comp = 1 + (l_nb_comps >> 15);
l_mcc_record->m_nb_comps = l_nb_comps & 0x7fff;
if (p_header_size < (l_nb_bytes_by_comp * l_mcc_record->m_nb_comps + 2)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
p_header_size -= (l_nb_bytes_by_comp * l_mcc_record->m_nb_comps + 2);
for (j = 0; j < l_mcc_record->m_nb_comps; ++j) {
opj_read_bytes(p_header_data, &l_tmp,
l_nb_bytes_by_comp); /* Cmccij Component offset*/
p_header_data += l_nb_bytes_by_comp;
if (l_tmp != j) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge collections with indix shuffle\n");
return OPJ_TRUE;
}
}
opj_read_bytes(p_header_data, &l_nb_comps, 2);
p_header_data += 2;
l_nb_bytes_by_comp = 1 + (l_nb_comps >> 15);
l_nb_comps &= 0x7fff;
if (l_nb_comps != l_mcc_record->m_nb_comps) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge collections without same number of indixes\n");
return OPJ_TRUE;
}
if (p_header_size < (l_nb_bytes_by_comp * l_mcc_record->m_nb_comps + 3)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
p_header_size -= (l_nb_bytes_by_comp * l_mcc_record->m_nb_comps + 3);
for (j = 0; j < l_mcc_record->m_nb_comps; ++j) {
opj_read_bytes(p_header_data, &l_tmp,
l_nb_bytes_by_comp); /* Wmccij Component offset*/
p_header_data += l_nb_bytes_by_comp;
if (l_tmp != j) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge collections with indix shuffle\n");
return OPJ_TRUE;
}
}
opj_read_bytes(p_header_data, &l_tmp, 3); /* Wmccij Component offset*/
p_header_data += 3;
l_mcc_record->m_is_irreversible = !((l_tmp >> 16) & 1);
l_mcc_record->m_decorrelation_array = 00;
l_mcc_record->m_offset_array = 00;
l_indix = l_tmp & 0xff;
if (l_indix != 0) {
l_mct_data = l_tcp->m_mct_records;
for (j = 0; j < l_tcp->m_nb_mct_records; ++j) {
if (l_mct_data->m_index == l_indix) {
l_mcc_record->m_decorrelation_array = l_mct_data;
break;
}
++l_mct_data;
}
if (l_mcc_record->m_decorrelation_array == 00) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
}
l_indix = (l_tmp >> 8) & 0xff;
if (l_indix != 0) {
l_mct_data = l_tcp->m_mct_records;
for (j = 0; j < l_tcp->m_nb_mct_records; ++j) {
if (l_mct_data->m_index == l_indix) {
l_mcc_record->m_offset_array = l_mct_data;
break;
}
++l_mct_data;
}
if (l_mcc_record->m_offset_array == 00) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
}
}
if (p_header_size != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
if (l_new_mcc) {
++l_tcp->m_nb_mcc_records;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_mco(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager
)
{
OPJ_BYTE * l_current_data = 00;
OPJ_UINT32 l_mco_size;
opj_tcp_t * l_tcp = 00;
opj_simple_mcc_decorrelation_data_t * l_mcc_record;
OPJ_UINT32 i;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_tcp = &(p_j2k->m_cp.tcps[p_j2k->m_current_tile_number]);
l_mco_size = 5 + l_tcp->m_nb_mcc_records;
if (l_mco_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mco_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write MCO marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_mco_size;
}
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_data, J2K_MS_MCO, 2); /* MCO */
l_current_data += 2;
opj_write_bytes(l_current_data, l_mco_size - 2, 2); /* Lmco */
l_current_data += 2;
opj_write_bytes(l_current_data, l_tcp->m_nb_mcc_records,
1); /* Nmco : only one transform stage*/
++l_current_data;
l_mcc_record = l_tcp->m_mcc_records;
for (i = 0; i < l_tcp->m_nb_mcc_records; ++i) {
opj_write_bytes(l_current_data, l_mcc_record->m_index,
1); /* Imco -> use the mcc indicated by 1*/
++l_current_data;
++l_mcc_record;
}
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mco_size,
p_manager) != l_mco_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a MCO marker (Multiple Component Transform Ordering)
*
* @param p_header_data the data contained in the MCO box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the MCO marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_mco(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_tmp, i;
OPJ_UINT32 l_nb_stages;
opj_tcp_t * l_tcp;
opj_tccp_t * l_tccp;
opj_image_t * l_image;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_image = p_j2k->m_private_image;
l_tcp = p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH ?
&p_j2k->m_cp.tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
if (p_header_size < 1) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCO marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_nb_stages,
1); /* Nmco : only one transform stage*/
++p_header_data;
if (l_nb_stages > 1) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge multiple transformation stages.\n");
return OPJ_TRUE;
}
if (p_header_size != l_nb_stages + 1) {
opj_event_msg(p_manager, EVT_WARNING, "Error reading MCO marker\n");
return OPJ_FALSE;
}
l_tccp = l_tcp->tccps;
for (i = 0; i < l_image->numcomps; ++i) {
l_tccp->m_dc_level_shift = 0;
++l_tccp;
}
if (l_tcp->m_mct_decoding_matrix) {
opj_free(l_tcp->m_mct_decoding_matrix);
l_tcp->m_mct_decoding_matrix = 00;
}
for (i = 0; i < l_nb_stages; ++i) {
opj_read_bytes(p_header_data, &l_tmp, 1);
++p_header_data;
if (! opj_j2k_add_mct(l_tcp, p_j2k->m_private_image, l_tmp)) {
return OPJ_FALSE;
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_add_mct(opj_tcp_t * p_tcp, opj_image_t * p_image,
OPJ_UINT32 p_index)
{
OPJ_UINT32 i;
opj_simple_mcc_decorrelation_data_t * l_mcc_record;
opj_mct_data_t * l_deco_array, * l_offset_array;
OPJ_UINT32 l_data_size, l_mct_size, l_offset_size;
OPJ_UINT32 l_nb_elem;
OPJ_UINT32 * l_offset_data, * l_current_offset_data;
opj_tccp_t * l_tccp;
/* preconditions */
assert(p_tcp != 00);
l_mcc_record = p_tcp->m_mcc_records;
for (i = 0; i < p_tcp->m_nb_mcc_records; ++i) {
if (l_mcc_record->m_index == p_index) {
break;
}
}
if (i == p_tcp->m_nb_mcc_records) {
/** element discarded **/
return OPJ_TRUE;
}
if (l_mcc_record->m_nb_comps != p_image->numcomps) {
/** do not support number of comps != image */
return OPJ_TRUE;
}
l_deco_array = l_mcc_record->m_decorrelation_array;
if (l_deco_array) {
l_data_size = MCT_ELEMENT_SIZE[l_deco_array->m_element_type] * p_image->numcomps
* p_image->numcomps;
if (l_deco_array->m_data_size != l_data_size) {
return OPJ_FALSE;
}
l_nb_elem = p_image->numcomps * p_image->numcomps;
l_mct_size = l_nb_elem * (OPJ_UINT32)sizeof(OPJ_FLOAT32);
p_tcp->m_mct_decoding_matrix = (OPJ_FLOAT32*)opj_malloc(l_mct_size);
if (! p_tcp->m_mct_decoding_matrix) {
return OPJ_FALSE;
}
j2k_mct_read_functions_to_float[l_deco_array->m_element_type](
l_deco_array->m_data, p_tcp->m_mct_decoding_matrix, l_nb_elem);
}
l_offset_array = l_mcc_record->m_offset_array;
if (l_offset_array) {
l_data_size = MCT_ELEMENT_SIZE[l_offset_array->m_element_type] *
p_image->numcomps;
if (l_offset_array->m_data_size != l_data_size) {
return OPJ_FALSE;
}
l_nb_elem = p_image->numcomps;
l_offset_size = l_nb_elem * (OPJ_UINT32)sizeof(OPJ_UINT32);
l_offset_data = (OPJ_UINT32*)opj_malloc(l_offset_size);
if (! l_offset_data) {
return OPJ_FALSE;
}
j2k_mct_read_functions_to_int32[l_offset_array->m_element_type](
l_offset_array->m_data, l_offset_data, l_nb_elem);
l_tccp = p_tcp->tccps;
l_current_offset_data = l_offset_data;
for (i = 0; i < p_image->numcomps; ++i) {
l_tccp->m_dc_level_shift = (OPJ_INT32) * (l_current_offset_data++);
++l_tccp;
}
opj_free(l_offset_data);
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_cbd(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 i;
OPJ_UINT32 l_cbd_size;
OPJ_BYTE * l_current_data = 00;
opj_image_t *l_image = 00;
opj_image_comp_t * l_comp = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_image = p_j2k->m_private_image;
l_cbd_size = 6 + p_j2k->m_private_image->numcomps;
if (l_cbd_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_cbd_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write CBD marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_cbd_size;
}
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_data, J2K_MS_CBD, 2); /* CBD */
l_current_data += 2;
opj_write_bytes(l_current_data, l_cbd_size - 2, 2); /* L_CBD */
l_current_data += 2;
opj_write_bytes(l_current_data, l_image->numcomps, 2); /* Ncbd */
l_current_data += 2;
l_comp = l_image->comps;
for (i = 0; i < l_image->numcomps; ++i) {
opj_write_bytes(l_current_data, (l_comp->sgnd << 7) | (l_comp->prec - 1),
1); /* Component bit depth */
++l_current_data;
++l_comp;
}
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_cbd_size,
p_manager) != l_cbd_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a CBD marker (Component bit depth definition)
* @param p_header_data the data contained in the CBD box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the CBD marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_cbd(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_nb_comp, l_num_comp;
OPJ_UINT32 l_comp_def;
OPJ_UINT32 i;
opj_image_comp_t * l_comp = 00;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_num_comp = p_j2k->m_private_image->numcomps;
if (p_header_size != (p_j2k->m_private_image->numcomps + 2)) {
opj_event_msg(p_manager, EVT_ERROR, "Crror reading CBD marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_nb_comp,
2); /* Ncbd */
p_header_data += 2;
if (l_nb_comp != l_num_comp) {
opj_event_msg(p_manager, EVT_ERROR, "Crror reading CBD marker\n");
return OPJ_FALSE;
}
l_comp = p_j2k->m_private_image->comps;
for (i = 0; i < l_num_comp; ++i) {
opj_read_bytes(p_header_data, &l_comp_def,
1); /* Component bit depth */
++p_header_data;
l_comp->sgnd = (l_comp_def >> 7) & 1;
l_comp->prec = (l_comp_def & 0x7f) + 1;
if (l_comp->prec > 31) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid values for comp = %d : prec=%u (should be between 1 and 38 according to the JPEG2000 norm. OpenJpeg only supports up to 31)\n",
i, l_comp->prec);
return OPJ_FALSE;
}
++l_comp;
}
return OPJ_TRUE;
}
/* ----------------------------------------------------------------------- */
/* J2K / JPT decoder interface */
/* ----------------------------------------------------------------------- */
void opj_j2k_setup_decoder(opj_j2k_t *j2k, opj_dparameters_t *parameters)
{
if (j2k && parameters) {
j2k->m_cp.m_specific_param.m_dec.m_layer = parameters->cp_layer;
j2k->m_cp.m_specific_param.m_dec.m_reduce = parameters->cp_reduce;
j2k->dump_state = (parameters->flags & OPJ_DPARAMETERS_DUMP_FLAG);
#ifdef USE_JPWL
j2k->m_cp.correct = parameters->jpwl_correct;
j2k->m_cp.exp_comps = parameters->jpwl_exp_comps;
j2k->m_cp.max_tiles = parameters->jpwl_max_tiles;
#endif /* USE_JPWL */
}
}
OPJ_BOOL opj_j2k_set_threads(opj_j2k_t *j2k, OPJ_UINT32 num_threads)
{
if (opj_has_thread_support()) {
opj_thread_pool_destroy(j2k->m_tp);
j2k->m_tp = NULL;
if (num_threads <= (OPJ_UINT32)INT_MAX) {
j2k->m_tp = opj_thread_pool_create((int)num_threads);
}
if (j2k->m_tp == NULL) {
j2k->m_tp = opj_thread_pool_create(0);
return OPJ_FALSE;
}
return OPJ_TRUE;
}
return OPJ_FALSE;
}
static int opj_j2k_get_default_thread_count()
{
const char* num_threads = getenv("OPJ_NUM_THREADS");
if (num_threads == NULL || !opj_has_thread_support()) {
return 0;
}
if (strcmp(num_threads, "ALL_CPUS") == 0) {
return opj_get_num_cpus();
}
return atoi(num_threads);
}
/* ----------------------------------------------------------------------- */
/* J2K encoder interface */
/* ----------------------------------------------------------------------- */
opj_j2k_t* opj_j2k_create_compress(void)
{
opj_j2k_t *l_j2k = (opj_j2k_t*) opj_calloc(1, sizeof(opj_j2k_t));
if (!l_j2k) {
return NULL;
}
l_j2k->m_is_decoder = 0;
l_j2k->m_cp.m_is_decoder = 0;
l_j2k->m_specific_param.m_encoder.m_header_tile_data = (OPJ_BYTE *) opj_malloc(
OPJ_J2K_DEFAULT_HEADER_SIZE);
if (! l_j2k->m_specific_param.m_encoder.m_header_tile_data) {
opj_j2k_destroy(l_j2k);
return NULL;
}
l_j2k->m_specific_param.m_encoder.m_header_tile_data_size =
OPJ_J2K_DEFAULT_HEADER_SIZE;
/* validation list creation*/
l_j2k->m_validation_list = opj_procedure_list_create();
if (! l_j2k->m_validation_list) {
opj_j2k_destroy(l_j2k);
return NULL;
}
/* execution list creation*/
l_j2k->m_procedure_list = opj_procedure_list_create();
if (! l_j2k->m_procedure_list) {
opj_j2k_destroy(l_j2k);
return NULL;
}
l_j2k->m_tp = opj_thread_pool_create(opj_j2k_get_default_thread_count());
if (!l_j2k->m_tp) {
l_j2k->m_tp = opj_thread_pool_create(0);
}
if (!l_j2k->m_tp) {
opj_j2k_destroy(l_j2k);
return NULL;
}
return l_j2k;
}
static int opj_j2k_initialise_4K_poc(opj_poc_t *POC, int numres)
{
POC[0].tile = 1;
POC[0].resno0 = 0;
POC[0].compno0 = 0;
POC[0].layno1 = 1;
POC[0].resno1 = (OPJ_UINT32)(numres - 1);
POC[0].compno1 = 3;
POC[0].prg1 = OPJ_CPRL;
POC[1].tile = 1;
POC[1].resno0 = (OPJ_UINT32)(numres - 1);
POC[1].compno0 = 0;
POC[1].layno1 = 1;
POC[1].resno1 = (OPJ_UINT32)numres;
POC[1].compno1 = 3;
POC[1].prg1 = OPJ_CPRL;
return 2;
}
static void opj_j2k_set_cinema_parameters(opj_cparameters_t *parameters,
opj_image_t *image, opj_event_mgr_t *p_manager)
{
/* Configure cinema parameters */
int i;
/* No tiling */
parameters->tile_size_on = OPJ_FALSE;
parameters->cp_tdx = 1;
parameters->cp_tdy = 1;
/* One tile part for each component */
parameters->tp_flag = 'C';
parameters->tp_on = 1;
/* Tile and Image shall be at (0,0) */
parameters->cp_tx0 = 0;
parameters->cp_ty0 = 0;
parameters->image_offset_x0 = 0;
parameters->image_offset_y0 = 0;
/* Codeblock size= 32*32 */
parameters->cblockw_init = 32;
parameters->cblockh_init = 32;
/* Codeblock style: no mode switch enabled */
parameters->mode = 0;
/* No ROI */
parameters->roi_compno = -1;
/* No subsampling */
parameters->subsampling_dx = 1;
parameters->subsampling_dy = 1;
/* 9-7 transform */
parameters->irreversible = 1;
/* Number of layers */
if (parameters->tcp_numlayers > 1) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
"1 single quality layer"
"-> Number of layers forced to 1 (rather than %d)\n"
"-> Rate of the last layer (%3.1f) will be used",
parameters->tcp_numlayers,
parameters->tcp_rates[parameters->tcp_numlayers - 1]);
parameters->tcp_rates[0] = parameters->tcp_rates[parameters->tcp_numlayers - 1];
parameters->tcp_numlayers = 1;
}
/* Resolution levels */
switch (parameters->rsiz) {
case OPJ_PROFILE_CINEMA_2K:
if (parameters->numresolution > 6) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 (2k dc profile) requires:\n"
"Number of decomposition levels <= 5\n"
"-> Number of decomposition levels forced to 5 (rather than %d)\n",
parameters->numresolution + 1);
parameters->numresolution = 6;
}
break;
case OPJ_PROFILE_CINEMA_4K:
if (parameters->numresolution < 2) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-4 (4k dc profile) requires:\n"
"Number of decomposition levels >= 1 && <= 6\n"
"-> Number of decomposition levels forced to 1 (rather than %d)\n",
parameters->numresolution + 1);
parameters->numresolution = 1;
} else if (parameters->numresolution > 7) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-4 (4k dc profile) requires:\n"
"Number of decomposition levels >= 1 && <= 6\n"
"-> Number of decomposition levels forced to 6 (rather than %d)\n",
parameters->numresolution + 1);
parameters->numresolution = 7;
}
break;
default :
break;
}
/* Precincts */
parameters->csty |= 0x01;
if (parameters->numresolution == 1) {
parameters->res_spec = 1;
parameters->prcw_init[0] = 128;
parameters->prch_init[0] = 128;
} else {
parameters->res_spec = parameters->numresolution - 1;
for (i = 0; i < parameters->res_spec; i++) {
parameters->prcw_init[i] = 256;
parameters->prch_init[i] = 256;
}
}
/* The progression order shall be CPRL */
parameters->prog_order = OPJ_CPRL;
/* Progression order changes for 4K, disallowed for 2K */
if (parameters->rsiz == OPJ_PROFILE_CINEMA_4K) {
parameters->numpocs = (OPJ_UINT32)opj_j2k_initialise_4K_poc(parameters->POC,
parameters->numresolution);
} else {
parameters->numpocs = 0;
}
/* Limited bit-rate */
parameters->cp_disto_alloc = 1;
if (parameters->max_cs_size <= 0) {
/* No rate has been introduced, 24 fps is assumed */
parameters->max_cs_size = OPJ_CINEMA_24_CS;
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
"Maximum 1302083 compressed bytes @ 24fps\n"
"As no rate has been given, this limit will be used.\n");
} else if (parameters->max_cs_size > OPJ_CINEMA_24_CS) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
"Maximum 1302083 compressed bytes @ 24fps\n"
"-> Specified rate exceeds this limit. Rate will be forced to 1302083 bytes.\n");
parameters->max_cs_size = OPJ_CINEMA_24_CS;
}
if (parameters->max_comp_size <= 0) {
/* No rate has been introduced, 24 fps is assumed */
parameters->max_comp_size = OPJ_CINEMA_24_COMP;
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
"Maximum 1041666 compressed bytes @ 24fps\n"
"As no rate has been given, this limit will be used.\n");
} else if (parameters->max_comp_size > OPJ_CINEMA_24_COMP) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
"Maximum 1041666 compressed bytes @ 24fps\n"
"-> Specified rate exceeds this limit. Rate will be forced to 1041666 bytes.\n");
parameters->max_comp_size = OPJ_CINEMA_24_COMP;
}
parameters->tcp_rates[0] = (OPJ_FLOAT32)(image->numcomps * image->comps[0].w *
image->comps[0].h * image->comps[0].prec) /
(OPJ_FLOAT32)(((OPJ_UINT32)parameters->max_cs_size) * 8 * image->comps[0].dx *
image->comps[0].dy);
}
static OPJ_BOOL opj_j2k_is_cinema_compliant(opj_image_t *image, OPJ_UINT16 rsiz,
opj_event_mgr_t *p_manager)
{
OPJ_UINT32 i;
/* Number of components */
if (image->numcomps != 3) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 (2k dc profile) requires:\n"
"3 components"
"-> Number of components of input image (%d) is not compliant\n"
"-> Non-profile-3 codestream will be generated\n",
image->numcomps);
return OPJ_FALSE;
}
/* Bitdepth */
for (i = 0; i < image->numcomps; i++) {
if ((image->comps[i].bpp != 12) | (image->comps[i].sgnd)) {
char signed_str[] = "signed";
char unsigned_str[] = "unsigned";
char *tmp_str = image->comps[i].sgnd ? signed_str : unsigned_str;
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 (2k dc profile) requires:\n"
"Precision of each component shall be 12 bits unsigned"
"-> At least component %d of input image (%d bits, %s) is not compliant\n"
"-> Non-profile-3 codestream will be generated\n",
i, image->comps[i].bpp, tmp_str);
return OPJ_FALSE;
}
}
/* Image size */
switch (rsiz) {
case OPJ_PROFILE_CINEMA_2K:
if (((image->comps[0].w > 2048) | (image->comps[0].h > 1080))) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 (2k dc profile) requires:\n"
"width <= 2048 and height <= 1080\n"
"-> Input image size %d x %d is not compliant\n"
"-> Non-profile-3 codestream will be generated\n",
image->comps[0].w, image->comps[0].h);
return OPJ_FALSE;
}
break;
case OPJ_PROFILE_CINEMA_4K:
if (((image->comps[0].w > 4096) | (image->comps[0].h > 2160))) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-4 (4k dc profile) requires:\n"
"width <= 4096 and height <= 2160\n"
"-> Image size %d x %d is not compliant\n"
"-> Non-profile-4 codestream will be generated\n",
image->comps[0].w, image->comps[0].h);
return OPJ_FALSE;
}
break;
default :
break;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_setup_encoder(opj_j2k_t *p_j2k,
opj_cparameters_t *parameters,
opj_image_t *image,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 i, j, tileno, numpocs_tile;
opj_cp_t *cp = 00;
if (!p_j2k || !parameters || ! image) {
return OPJ_FALSE;
}
if ((parameters->numresolution <= 0) ||
(parameters->numresolution > OPJ_J2K_MAXRLVLS)) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid number of resolutions : %d not in range [1,%d]\n",
parameters->numresolution, OPJ_J2K_MAXRLVLS);
return OPJ_FALSE;
}
/* keep a link to cp so that we can destroy it later in j2k_destroy_compress */
cp = &(p_j2k->m_cp);
/* set default values for cp */
cp->tw = 1;
cp->th = 1;
/* FIXME ADE: to be removed once deprecated cp_cinema and cp_rsiz have been removed */
if (parameters->rsiz ==
OPJ_PROFILE_NONE) { /* consider deprecated fields only if RSIZ has not been set */
OPJ_BOOL deprecated_used = OPJ_FALSE;
switch (parameters->cp_cinema) {
case OPJ_CINEMA2K_24:
parameters->rsiz = OPJ_PROFILE_CINEMA_2K;
parameters->max_cs_size = OPJ_CINEMA_24_CS;
parameters->max_comp_size = OPJ_CINEMA_24_COMP;
deprecated_used = OPJ_TRUE;
break;
case OPJ_CINEMA2K_48:
parameters->rsiz = OPJ_PROFILE_CINEMA_2K;
parameters->max_cs_size = OPJ_CINEMA_48_CS;
parameters->max_comp_size = OPJ_CINEMA_48_COMP;
deprecated_used = OPJ_TRUE;
break;
case OPJ_CINEMA4K_24:
parameters->rsiz = OPJ_PROFILE_CINEMA_4K;
parameters->max_cs_size = OPJ_CINEMA_24_CS;
parameters->max_comp_size = OPJ_CINEMA_24_COMP;
deprecated_used = OPJ_TRUE;
break;
case OPJ_OFF:
default:
break;
}
switch (parameters->cp_rsiz) {
case OPJ_CINEMA2K:
parameters->rsiz = OPJ_PROFILE_CINEMA_2K;
deprecated_used = OPJ_TRUE;
break;
case OPJ_CINEMA4K:
parameters->rsiz = OPJ_PROFILE_CINEMA_4K;
deprecated_used = OPJ_TRUE;
break;
case OPJ_MCT:
parameters->rsiz = OPJ_PROFILE_PART2 | OPJ_EXTENSION_MCT;
deprecated_used = OPJ_TRUE;
case OPJ_STD_RSIZ:
default:
break;
}
if (deprecated_used) {
opj_event_msg(p_manager, EVT_WARNING,
"Deprecated fields cp_cinema or cp_rsiz are used\n"
"Please consider using only the rsiz field\n"
"See openjpeg.h documentation for more details\n");
}
}
/* If no explicit layers are provided, use lossless settings */
if (parameters->tcp_numlayers == 0) {
parameters->tcp_numlayers = 1;
parameters->cp_disto_alloc = 1;
parameters->tcp_rates[0] = 0;
}
/* see if max_codestream_size does limit input rate */
if (parameters->max_cs_size <= 0) {
if (parameters->tcp_rates[parameters->tcp_numlayers - 1] > 0) {
OPJ_FLOAT32 temp_size;
temp_size = (OPJ_FLOAT32)(image->numcomps * image->comps[0].w *
image->comps[0].h * image->comps[0].prec) /
(parameters->tcp_rates[parameters->tcp_numlayers - 1] * 8 *
(OPJ_FLOAT32)image->comps[0].dx * (OPJ_FLOAT32)image->comps[0].dy);
parameters->max_cs_size = (int) floor(temp_size);
} else {
parameters->max_cs_size = 0;
}
} else {
OPJ_FLOAT32 temp_rate;
OPJ_BOOL cap = OPJ_FALSE;
temp_rate = (OPJ_FLOAT32)(image->numcomps * image->comps[0].w *
image->comps[0].h * image->comps[0].prec) /
(OPJ_FLOAT32)(((OPJ_UINT32)parameters->max_cs_size) * 8 * image->comps[0].dx *
image->comps[0].dy);
for (i = 0; i < (OPJ_UINT32) parameters->tcp_numlayers; i++) {
if (parameters->tcp_rates[i] < temp_rate) {
parameters->tcp_rates[i] = temp_rate;
cap = OPJ_TRUE;
}
}
if (cap) {
opj_event_msg(p_manager, EVT_WARNING,
"The desired maximum codestream size has limited\n"
"at least one of the desired quality layers\n");
}
}
/* Manage profiles and applications and set RSIZ */
/* set cinema parameters if required */
if (OPJ_IS_CINEMA(parameters->rsiz)) {
if ((parameters->rsiz == OPJ_PROFILE_CINEMA_S2K)
|| (parameters->rsiz == OPJ_PROFILE_CINEMA_S4K)) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Scalable Digital Cinema profiles not yet supported\n");
parameters->rsiz = OPJ_PROFILE_NONE;
} else {
opj_j2k_set_cinema_parameters(parameters, image, p_manager);
if (!opj_j2k_is_cinema_compliant(image, parameters->rsiz, p_manager)) {
parameters->rsiz = OPJ_PROFILE_NONE;
}
}
} else if (OPJ_IS_STORAGE(parameters->rsiz)) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Long Term Storage profile not yet supported\n");
parameters->rsiz = OPJ_PROFILE_NONE;
} else if (OPJ_IS_BROADCAST(parameters->rsiz)) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Broadcast profiles not yet supported\n");
parameters->rsiz = OPJ_PROFILE_NONE;
} else if (OPJ_IS_IMF(parameters->rsiz)) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 IMF profiles not yet supported\n");
parameters->rsiz = OPJ_PROFILE_NONE;
} else if (OPJ_IS_PART2(parameters->rsiz)) {
if (parameters->rsiz == ((OPJ_PROFILE_PART2) | (OPJ_EXTENSION_NONE))) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Part-2 profile defined\n"
"but no Part-2 extension enabled.\n"
"Profile set to NONE.\n");
parameters->rsiz = OPJ_PROFILE_NONE;
} else if (parameters->rsiz != ((OPJ_PROFILE_PART2) | (OPJ_EXTENSION_MCT))) {
opj_event_msg(p_manager, EVT_WARNING,
"Unsupported Part-2 extension enabled\n"
"Profile set to NONE.\n");
parameters->rsiz = OPJ_PROFILE_NONE;
}
}
/*
copy user encoding parameters
*/
cp->m_specific_param.m_enc.m_max_comp_size = (OPJ_UINT32)
parameters->max_comp_size;
cp->rsiz = parameters->rsiz;
cp->m_specific_param.m_enc.m_disto_alloc = (OPJ_UINT32)
parameters->cp_disto_alloc & 1u;
cp->m_specific_param.m_enc.m_fixed_alloc = (OPJ_UINT32)
parameters->cp_fixed_alloc & 1u;
cp->m_specific_param.m_enc.m_fixed_quality = (OPJ_UINT32)
parameters->cp_fixed_quality & 1u;
/* mod fixed_quality */
if (parameters->cp_fixed_alloc && parameters->cp_matrice) {
size_t array_size = (size_t)parameters->tcp_numlayers *
(size_t)parameters->numresolution * 3 * sizeof(OPJ_INT32);
cp->m_specific_param.m_enc.m_matrice = (OPJ_INT32 *) opj_malloc(array_size);
if (!cp->m_specific_param.m_enc.m_matrice) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate copy of user encoding parameters matrix \n");
return OPJ_FALSE;
}
memcpy(cp->m_specific_param.m_enc.m_matrice, parameters->cp_matrice,
array_size);
}
/* tiles */
cp->tdx = (OPJ_UINT32)parameters->cp_tdx;
cp->tdy = (OPJ_UINT32)parameters->cp_tdy;
/* tile offset */
cp->tx0 = (OPJ_UINT32)parameters->cp_tx0;
cp->ty0 = (OPJ_UINT32)parameters->cp_ty0;
/* comment string */
if (parameters->cp_comment) {
cp->comment = (char*)opj_malloc(strlen(parameters->cp_comment) + 1U);
if (!cp->comment) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate copy of comment string\n");
return OPJ_FALSE;
}
strcpy(cp->comment, parameters->cp_comment);
} else {
/* Create default comment for codestream */
const char comment[] = "Created by OpenJPEG version ";
const size_t clen = strlen(comment);
const char *version = opj_version();
/* UniPG>> */
#ifdef USE_JPWL
cp->comment = (char*)opj_malloc(clen + strlen(version) + 11);
if (!cp->comment) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate comment string\n");
return OPJ_FALSE;
}
sprintf(cp->comment, "%s%s with JPWL", comment, version);
#else
cp->comment = (char*)opj_malloc(clen + strlen(version) + 1);
if (!cp->comment) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate comment string\n");
return OPJ_FALSE;
}
sprintf(cp->comment, "%s%s", comment, version);
#endif
/* <<UniPG */
}
/*
calculate other encoding parameters
*/
if (parameters->tile_size_on) {
cp->tw = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)(image->x1 - cp->tx0),
(OPJ_INT32)cp->tdx);
cp->th = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)(image->y1 - cp->ty0),
(OPJ_INT32)cp->tdy);
} else {
cp->tdx = image->x1 - cp->tx0;
cp->tdy = image->y1 - cp->ty0;
}
if (parameters->tp_on) {
cp->m_specific_param.m_enc.m_tp_flag = (OPJ_BYTE)parameters->tp_flag;
cp->m_specific_param.m_enc.m_tp_on = 1;
}
#ifdef USE_JPWL
/*
calculate JPWL encoding parameters
*/
if (parameters->jpwl_epc_on) {
OPJ_INT32 i;
/* set JPWL on */
cp->epc_on = OPJ_TRUE;
cp->info_on = OPJ_FALSE; /* no informative technique */
/* set EPB on */
if ((parameters->jpwl_hprot_MH > 0) || (parameters->jpwl_hprot_TPH[0] > 0)) {
cp->epb_on = OPJ_TRUE;
cp->hprot_MH = parameters->jpwl_hprot_MH;
for (i = 0; i < JPWL_MAX_NO_TILESPECS; i++) {
cp->hprot_TPH_tileno[i] = parameters->jpwl_hprot_TPH_tileno[i];
cp->hprot_TPH[i] = parameters->jpwl_hprot_TPH[i];
}
/* if tile specs are not specified, copy MH specs */
if (cp->hprot_TPH[0] == -1) {
cp->hprot_TPH_tileno[0] = 0;
cp->hprot_TPH[0] = parameters->jpwl_hprot_MH;
}
for (i = 0; i < JPWL_MAX_NO_PACKSPECS; i++) {
cp->pprot_tileno[i] = parameters->jpwl_pprot_tileno[i];
cp->pprot_packno[i] = parameters->jpwl_pprot_packno[i];
cp->pprot[i] = parameters->jpwl_pprot[i];
}
}
/* set ESD writing */
if ((parameters->jpwl_sens_size == 1) || (parameters->jpwl_sens_size == 2)) {
cp->esd_on = OPJ_TRUE;
cp->sens_size = parameters->jpwl_sens_size;
cp->sens_addr = parameters->jpwl_sens_addr;
cp->sens_range = parameters->jpwl_sens_range;
cp->sens_MH = parameters->jpwl_sens_MH;
for (i = 0; i < JPWL_MAX_NO_TILESPECS; i++) {
cp->sens_TPH_tileno[i] = parameters->jpwl_sens_TPH_tileno[i];
cp->sens_TPH[i] = parameters->jpwl_sens_TPH[i];
}
}
/* always set RED writing to false: we are at the encoder */
cp->red_on = OPJ_FALSE;
} else {
cp->epc_on = OPJ_FALSE;
}
#endif /* USE_JPWL */
/* initialize the mutiple tiles */
/* ---------------------------- */
cp->tcps = (opj_tcp_t*) opj_calloc(cp->tw * cp->th, sizeof(opj_tcp_t));
if (!cp->tcps) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate tile coding parameters\n");
return OPJ_FALSE;
}
if (parameters->numpocs) {
/* initialisation of POC */
opj_j2k_check_poc_val(parameters->POC, parameters->numpocs,
(OPJ_UINT32)parameters->numresolution, image->numcomps,
(OPJ_UINT32)parameters->tcp_numlayers, p_manager);
/* TODO MSD use the return value*/
}
for (tileno = 0; tileno < cp->tw * cp->th; tileno++) {
opj_tcp_t *tcp = &cp->tcps[tileno];
tcp->numlayers = (OPJ_UINT32)parameters->tcp_numlayers;
for (j = 0; j < tcp->numlayers; j++) {
if (OPJ_IS_CINEMA(cp->rsiz)) {
if (cp->m_specific_param.m_enc.m_fixed_quality) {
tcp->distoratio[j] = parameters->tcp_distoratio[j];
}
tcp->rates[j] = parameters->tcp_rates[j];
} else {
if (cp->m_specific_param.m_enc.m_fixed_quality) { /* add fixed_quality */
tcp->distoratio[j] = parameters->tcp_distoratio[j];
} else {
tcp->rates[j] = parameters->tcp_rates[j];
}
}
}
tcp->csty = (OPJ_UINT32)parameters->csty;
tcp->prg = parameters->prog_order;
tcp->mct = (OPJ_UINT32)parameters->tcp_mct;
numpocs_tile = 0;
tcp->POC = 0;
if (parameters->numpocs) {
/* initialisation of POC */
tcp->POC = 1;
for (i = 0; i < parameters->numpocs; i++) {
if (tileno + 1 == parameters->POC[i].tile) {
opj_poc_t *tcp_poc = &tcp->pocs[numpocs_tile];
tcp_poc->resno0 = parameters->POC[numpocs_tile].resno0;
tcp_poc->compno0 = parameters->POC[numpocs_tile].compno0;
tcp_poc->layno1 = parameters->POC[numpocs_tile].layno1;
tcp_poc->resno1 = parameters->POC[numpocs_tile].resno1;
tcp_poc->compno1 = parameters->POC[numpocs_tile].compno1;
tcp_poc->prg1 = parameters->POC[numpocs_tile].prg1;
tcp_poc->tile = parameters->POC[numpocs_tile].tile;
numpocs_tile++;
}
}
tcp->numpocs = numpocs_tile - 1 ;
} else {
tcp->numpocs = 0;
}
tcp->tccps = (opj_tccp_t*) opj_calloc(image->numcomps, sizeof(opj_tccp_t));
if (!tcp->tccps) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate tile component coding parameters\n");
return OPJ_FALSE;
}
if (parameters->mct_data) {
OPJ_UINT32 lMctSize = image->numcomps * image->numcomps * (OPJ_UINT32)sizeof(
OPJ_FLOAT32);
OPJ_FLOAT32 * lTmpBuf = (OPJ_FLOAT32*)opj_malloc(lMctSize);
OPJ_INT32 * l_dc_shift = (OPJ_INT32 *)((OPJ_BYTE *) parameters->mct_data +
lMctSize);
if (!lTmpBuf) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate temp buffer\n");
return OPJ_FALSE;
}
tcp->mct = 2;
tcp->m_mct_coding_matrix = (OPJ_FLOAT32*)opj_malloc(lMctSize);
if (! tcp->m_mct_coding_matrix) {
opj_free(lTmpBuf);
lTmpBuf = NULL;
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate encoder MCT coding matrix \n");
return OPJ_FALSE;
}
memcpy(tcp->m_mct_coding_matrix, parameters->mct_data, lMctSize);
memcpy(lTmpBuf, parameters->mct_data, lMctSize);
tcp->m_mct_decoding_matrix = (OPJ_FLOAT32*)opj_malloc(lMctSize);
if (! tcp->m_mct_decoding_matrix) {
opj_free(lTmpBuf);
lTmpBuf = NULL;
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate encoder MCT decoding matrix \n");
return OPJ_FALSE;
}
if (opj_matrix_inversion_f(lTmpBuf, (tcp->m_mct_decoding_matrix),
image->numcomps) == OPJ_FALSE) {
opj_free(lTmpBuf);
lTmpBuf = NULL;
opj_event_msg(p_manager, EVT_ERROR,
"Failed to inverse encoder MCT decoding matrix \n");
return OPJ_FALSE;
}
tcp->mct_norms = (OPJ_FLOAT64*)
opj_malloc(image->numcomps * sizeof(OPJ_FLOAT64));
if (! tcp->mct_norms) {
opj_free(lTmpBuf);
lTmpBuf = NULL;
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate encoder MCT norms \n");
return OPJ_FALSE;
}
opj_calculate_norms(tcp->mct_norms, image->numcomps,
tcp->m_mct_decoding_matrix);
opj_free(lTmpBuf);
for (i = 0; i < image->numcomps; i++) {
opj_tccp_t *tccp = &tcp->tccps[i];
tccp->m_dc_level_shift = l_dc_shift[i];
}
if (opj_j2k_setup_mct_encoding(tcp, image) == OPJ_FALSE) {
/* free will be handled by opj_j2k_destroy */
opj_event_msg(p_manager, EVT_ERROR, "Failed to setup j2k mct encoding\n");
return OPJ_FALSE;
}
} else {
if (tcp->mct == 1 && image->numcomps >= 3) { /* RGB->YCC MCT is enabled */
if ((image->comps[0].dx != image->comps[1].dx) ||
(image->comps[0].dx != image->comps[2].dx) ||
(image->comps[0].dy != image->comps[1].dy) ||
(image->comps[0].dy != image->comps[2].dy)) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot perform MCT on components with different sizes. Disabling MCT.\n");
tcp->mct = 0;
}
}
for (i = 0; i < image->numcomps; i++) {
opj_tccp_t *tccp = &tcp->tccps[i];
opj_image_comp_t * l_comp = &(image->comps[i]);
if (! l_comp->sgnd) {
tccp->m_dc_level_shift = 1 << (l_comp->prec - 1);
}
}
}
for (i = 0; i < image->numcomps; i++) {
opj_tccp_t *tccp = &tcp->tccps[i];
tccp->csty = parameters->csty &
0x01; /* 0 => one precinct || 1 => custom precinct */
tccp->numresolutions = (OPJ_UINT32)parameters->numresolution;
tccp->cblkw = (OPJ_UINT32)opj_int_floorlog2(parameters->cblockw_init);
tccp->cblkh = (OPJ_UINT32)opj_int_floorlog2(parameters->cblockh_init);
tccp->cblksty = (OPJ_UINT32)parameters->mode;
tccp->qmfbid = parameters->irreversible ? 0 : 1;
tccp->qntsty = parameters->irreversible ? J2K_CCP_QNTSTY_SEQNT :
J2K_CCP_QNTSTY_NOQNT;
tccp->numgbits = 2;
if ((OPJ_INT32)i == parameters->roi_compno) {
tccp->roishift = parameters->roi_shift;
} else {
tccp->roishift = 0;
}
if (parameters->csty & J2K_CCP_CSTY_PRT) {
OPJ_INT32 p = 0, it_res;
assert(tccp->numresolutions > 0);
for (it_res = (OPJ_INT32)tccp->numresolutions - 1; it_res >= 0; it_res--) {
if (p < parameters->res_spec) {
if (parameters->prcw_init[p] < 1) {
tccp->prcw[it_res] = 1;
} else {
tccp->prcw[it_res] = (OPJ_UINT32)opj_int_floorlog2(parameters->prcw_init[p]);
}
if (parameters->prch_init[p] < 1) {
tccp->prch[it_res] = 1;
} else {
tccp->prch[it_res] = (OPJ_UINT32)opj_int_floorlog2(parameters->prch_init[p]);
}
} else {
OPJ_INT32 res_spec = parameters->res_spec;
OPJ_INT32 size_prcw = 0;
OPJ_INT32 size_prch = 0;
assert(res_spec > 0); /* issue 189 */
size_prcw = parameters->prcw_init[res_spec - 1] >> (p - (res_spec - 1));
size_prch = parameters->prch_init[res_spec - 1] >> (p - (res_spec - 1));
if (size_prcw < 1) {
tccp->prcw[it_res] = 1;
} else {
tccp->prcw[it_res] = (OPJ_UINT32)opj_int_floorlog2(size_prcw);
}
if (size_prch < 1) {
tccp->prch[it_res] = 1;
} else {
tccp->prch[it_res] = (OPJ_UINT32)opj_int_floorlog2(size_prch);
}
}
p++;
/*printf("\nsize precinct for level %d : %d,%d\n", it_res,tccp->prcw[it_res], tccp->prch[it_res]); */
} /*end for*/
} else {
for (j = 0; j < tccp->numresolutions; j++) {
tccp->prcw[j] = 15;
tccp->prch[j] = 15;
}
}
opj_dwt_calc_explicit_stepsizes(tccp, image->comps[i].prec);
}
}
if (parameters->mct_data) {
opj_free(parameters->mct_data);
parameters->mct_data = 00;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_add_mhmarker(opj_codestream_index_t *cstr_index,
OPJ_UINT32 type, OPJ_OFF_T pos, OPJ_UINT32 len)
{
assert(cstr_index != 00);
/* expand the list? */
if ((cstr_index->marknum + 1) > cstr_index->maxmarknum) {
opj_marker_info_t *new_marker;
cstr_index->maxmarknum = (OPJ_UINT32)(100 + (OPJ_FLOAT32)
cstr_index->maxmarknum);
new_marker = (opj_marker_info_t *) opj_realloc(cstr_index->marker,
cstr_index->maxmarknum * sizeof(opj_marker_info_t));
if (! new_marker) {
opj_free(cstr_index->marker);
cstr_index->marker = NULL;
cstr_index->maxmarknum = 0;
cstr_index->marknum = 0;
/* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add mh marker\n"); */
return OPJ_FALSE;
}
cstr_index->marker = new_marker;
}
/* add the marker */
cstr_index->marker[cstr_index->marknum].type = (OPJ_UINT16)type;
cstr_index->marker[cstr_index->marknum].pos = (OPJ_INT32)pos;
cstr_index->marker[cstr_index->marknum].len = (OPJ_INT32)len;
cstr_index->marknum++;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_add_tlmarker(OPJ_UINT32 tileno,
opj_codestream_index_t *cstr_index, OPJ_UINT32 type, OPJ_OFF_T pos,
OPJ_UINT32 len)
{
assert(cstr_index != 00);
assert(cstr_index->tile_index != 00);
/* expand the list? */
if ((cstr_index->tile_index[tileno].marknum + 1) >
cstr_index->tile_index[tileno].maxmarknum) {
opj_marker_info_t *new_marker;
cstr_index->tile_index[tileno].maxmarknum = (OPJ_UINT32)(100 +
(OPJ_FLOAT32) cstr_index->tile_index[tileno].maxmarknum);
new_marker = (opj_marker_info_t *) opj_realloc(
cstr_index->tile_index[tileno].marker,
cstr_index->tile_index[tileno].maxmarknum * sizeof(opj_marker_info_t));
if (! new_marker) {
opj_free(cstr_index->tile_index[tileno].marker);
cstr_index->tile_index[tileno].marker = NULL;
cstr_index->tile_index[tileno].maxmarknum = 0;
cstr_index->tile_index[tileno].marknum = 0;
/* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add tl marker\n"); */
return OPJ_FALSE;
}
cstr_index->tile_index[tileno].marker = new_marker;
}
/* add the marker */
cstr_index->tile_index[tileno].marker[cstr_index->tile_index[tileno].marknum].type
= (OPJ_UINT16)type;
cstr_index->tile_index[tileno].marker[cstr_index->tile_index[tileno].marknum].pos
= (OPJ_INT32)pos;
cstr_index->tile_index[tileno].marker[cstr_index->tile_index[tileno].marknum].len
= (OPJ_INT32)len;
cstr_index->tile_index[tileno].marknum++;
if (type == J2K_MS_SOT) {
OPJ_UINT32 l_current_tile_part = cstr_index->tile_index[tileno].current_tpsno;
if (cstr_index->tile_index[tileno].tp_index) {
cstr_index->tile_index[tileno].tp_index[l_current_tile_part].start_pos = pos;
}
}
return OPJ_TRUE;
}
/*
* -----------------------------------------------------------------------
* -----------------------------------------------------------------------
* -----------------------------------------------------------------------
*/
OPJ_BOOL opj_j2k_end_decompress(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
(void)p_j2k;
(void)p_stream;
(void)p_manager;
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_read_header(opj_stream_private_t *p_stream,
opj_j2k_t* p_j2k,
opj_image_t** p_image,
opj_event_mgr_t* p_manager)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
/* create an empty image header */
p_j2k->m_private_image = opj_image_create0();
if (! p_j2k->m_private_image) {
return OPJ_FALSE;
}
/* customization of the validation */
if (! opj_j2k_setup_decoding_validation(p_j2k, p_manager)) {
opj_image_destroy(p_j2k->m_private_image);
p_j2k->m_private_image = NULL;
return OPJ_FALSE;
}
/* validation of the parameters codec */
if (! opj_j2k_exec(p_j2k, p_j2k->m_validation_list, p_stream, p_manager)) {
opj_image_destroy(p_j2k->m_private_image);
p_j2k->m_private_image = NULL;
return OPJ_FALSE;
}
/* customization of the encoding */
if (! opj_j2k_setup_header_reading(p_j2k, p_manager)) {
opj_image_destroy(p_j2k->m_private_image);
p_j2k->m_private_image = NULL;
return OPJ_FALSE;
}
/* read header */
if (! opj_j2k_exec(p_j2k, p_j2k->m_procedure_list, p_stream, p_manager)) {
opj_image_destroy(p_j2k->m_private_image);
p_j2k->m_private_image = NULL;
return OPJ_FALSE;
}
*p_image = opj_image_create0();
if (!(*p_image)) {
return OPJ_FALSE;
}
/* Copy codestream image information to the output image */
opj_copy_image_header(p_j2k->m_private_image, *p_image);
/*Allocate and initialize some elements of codestrem index*/
if (!opj_j2k_allocate_tile_element_cstr_index(p_j2k)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_setup_header_reading(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager)
{
/* preconditions*/
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_read_header_procedure, p_manager)) {
return OPJ_FALSE;
}
/* DEVELOPER CORNER, add your custom procedures */
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_copy_default_tcp_and_create_tcd, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_setup_decoding_validation(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager)
{
/* preconditions*/
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list,
(opj_procedure)opj_j2k_build_decoder, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list,
(opj_procedure)opj_j2k_decoding_validation, p_manager)) {
return OPJ_FALSE;
}
/* DEVELOPER CORNER, add your custom validation procedure */
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_mct_validation(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_BOOL l_is_valid = OPJ_TRUE;
OPJ_UINT32 i, j;
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_stream);
OPJ_UNUSED(p_manager);
if ((p_j2k->m_cp.rsiz & 0x8200) == 0x8200) {
OPJ_UINT32 l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
opj_tcp_t * l_tcp = p_j2k->m_cp.tcps;
for (i = 0; i < l_nb_tiles; ++i) {
if (l_tcp->mct == 2) {
opj_tccp_t * l_tccp = l_tcp->tccps;
l_is_valid &= (l_tcp->m_mct_coding_matrix != 00);
for (j = 0; j < p_j2k->m_private_image->numcomps; ++j) {
l_is_valid &= !(l_tccp->qmfbid & 1);
++l_tccp;
}
}
++l_tcp;
}
}
return l_is_valid;
}
OPJ_BOOL opj_j2k_setup_mct_encoding(opj_tcp_t * p_tcp, opj_image_t * p_image)
{
OPJ_UINT32 i;
OPJ_UINT32 l_indix = 1;
opj_mct_data_t * l_mct_deco_data = 00, * l_mct_offset_data = 00;
opj_simple_mcc_decorrelation_data_t * l_mcc_data;
OPJ_UINT32 l_mct_size, l_nb_elem;
OPJ_FLOAT32 * l_data, * l_current_data;
opj_tccp_t * l_tccp;
/* preconditions */
assert(p_tcp != 00);
if (p_tcp->mct != 2) {
return OPJ_TRUE;
}
if (p_tcp->m_mct_decoding_matrix) {
if (p_tcp->m_nb_mct_records == p_tcp->m_nb_max_mct_records) {
opj_mct_data_t *new_mct_records;
p_tcp->m_nb_max_mct_records += OPJ_J2K_MCT_DEFAULT_NB_RECORDS;
new_mct_records = (opj_mct_data_t *) opj_realloc(p_tcp->m_mct_records,
p_tcp->m_nb_max_mct_records * sizeof(opj_mct_data_t));
if (! new_mct_records) {
opj_free(p_tcp->m_mct_records);
p_tcp->m_mct_records = NULL;
p_tcp->m_nb_max_mct_records = 0;
p_tcp->m_nb_mct_records = 0;
/* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to setup mct encoding\n"); */
return OPJ_FALSE;
}
p_tcp->m_mct_records = new_mct_records;
l_mct_deco_data = p_tcp->m_mct_records + p_tcp->m_nb_mct_records;
memset(l_mct_deco_data, 0,
(p_tcp->m_nb_max_mct_records - p_tcp->m_nb_mct_records) * sizeof(
opj_mct_data_t));
}
l_mct_deco_data = p_tcp->m_mct_records + p_tcp->m_nb_mct_records;
if (l_mct_deco_data->m_data) {
opj_free(l_mct_deco_data->m_data);
l_mct_deco_data->m_data = 00;
}
l_mct_deco_data->m_index = l_indix++;
l_mct_deco_data->m_array_type = MCT_TYPE_DECORRELATION;
l_mct_deco_data->m_element_type = MCT_TYPE_FLOAT;
l_nb_elem = p_image->numcomps * p_image->numcomps;
l_mct_size = l_nb_elem * MCT_ELEMENT_SIZE[l_mct_deco_data->m_element_type];
l_mct_deco_data->m_data = (OPJ_BYTE*)opj_malloc(l_mct_size);
if (! l_mct_deco_data->m_data) {
return OPJ_FALSE;
}
j2k_mct_write_functions_from_float[l_mct_deco_data->m_element_type](
p_tcp->m_mct_decoding_matrix, l_mct_deco_data->m_data, l_nb_elem);
l_mct_deco_data->m_data_size = l_mct_size;
++p_tcp->m_nb_mct_records;
}
if (p_tcp->m_nb_mct_records == p_tcp->m_nb_max_mct_records) {
opj_mct_data_t *new_mct_records;
p_tcp->m_nb_max_mct_records += OPJ_J2K_MCT_DEFAULT_NB_RECORDS;
new_mct_records = (opj_mct_data_t *) opj_realloc(p_tcp->m_mct_records,
p_tcp->m_nb_max_mct_records * sizeof(opj_mct_data_t));
if (! new_mct_records) {
opj_free(p_tcp->m_mct_records);
p_tcp->m_mct_records = NULL;
p_tcp->m_nb_max_mct_records = 0;
p_tcp->m_nb_mct_records = 0;
/* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to setup mct encoding\n"); */
return OPJ_FALSE;
}
p_tcp->m_mct_records = new_mct_records;
l_mct_offset_data = p_tcp->m_mct_records + p_tcp->m_nb_mct_records;
memset(l_mct_offset_data, 0,
(p_tcp->m_nb_max_mct_records - p_tcp->m_nb_mct_records) * sizeof(
opj_mct_data_t));
if (l_mct_deco_data) {
l_mct_deco_data = l_mct_offset_data - 1;
}
}
l_mct_offset_data = p_tcp->m_mct_records + p_tcp->m_nb_mct_records;
if (l_mct_offset_data->m_data) {
opj_free(l_mct_offset_data->m_data);
l_mct_offset_data->m_data = 00;
}
l_mct_offset_data->m_index = l_indix++;
l_mct_offset_data->m_array_type = MCT_TYPE_OFFSET;
l_mct_offset_data->m_element_type = MCT_TYPE_FLOAT;
l_nb_elem = p_image->numcomps;
l_mct_size = l_nb_elem * MCT_ELEMENT_SIZE[l_mct_offset_data->m_element_type];
l_mct_offset_data->m_data = (OPJ_BYTE*)opj_malloc(l_mct_size);
if (! l_mct_offset_data->m_data) {
return OPJ_FALSE;
}
l_data = (OPJ_FLOAT32*)opj_malloc(l_nb_elem * sizeof(OPJ_FLOAT32));
if (! l_data) {
opj_free(l_mct_offset_data->m_data);
l_mct_offset_data->m_data = 00;
return OPJ_FALSE;
}
l_tccp = p_tcp->tccps;
l_current_data = l_data;
for (i = 0; i < l_nb_elem; ++i) {
*(l_current_data++) = (OPJ_FLOAT32)(l_tccp->m_dc_level_shift);
++l_tccp;
}
j2k_mct_write_functions_from_float[l_mct_offset_data->m_element_type](l_data,
l_mct_offset_data->m_data, l_nb_elem);
opj_free(l_data);
l_mct_offset_data->m_data_size = l_mct_size;
++p_tcp->m_nb_mct_records;
if (p_tcp->m_nb_mcc_records == p_tcp->m_nb_max_mcc_records) {
opj_simple_mcc_decorrelation_data_t *new_mcc_records;
p_tcp->m_nb_max_mcc_records += OPJ_J2K_MCT_DEFAULT_NB_RECORDS;
new_mcc_records = (opj_simple_mcc_decorrelation_data_t *) opj_realloc(
p_tcp->m_mcc_records, p_tcp->m_nb_max_mcc_records * sizeof(
opj_simple_mcc_decorrelation_data_t));
if (! new_mcc_records) {
opj_free(p_tcp->m_mcc_records);
p_tcp->m_mcc_records = NULL;
p_tcp->m_nb_max_mcc_records = 0;
p_tcp->m_nb_mcc_records = 0;
/* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to setup mct encoding\n"); */
return OPJ_FALSE;
}
p_tcp->m_mcc_records = new_mcc_records;
l_mcc_data = p_tcp->m_mcc_records + p_tcp->m_nb_mcc_records;
memset(l_mcc_data, 0, (p_tcp->m_nb_max_mcc_records - p_tcp->m_nb_mcc_records) *
sizeof(opj_simple_mcc_decorrelation_data_t));
}
l_mcc_data = p_tcp->m_mcc_records + p_tcp->m_nb_mcc_records;
l_mcc_data->m_decorrelation_array = l_mct_deco_data;
l_mcc_data->m_is_irreversible = 1;
l_mcc_data->m_nb_comps = p_image->numcomps;
l_mcc_data->m_index = l_indix++;
l_mcc_data->m_offset_array = l_mct_offset_data;
++p_tcp->m_nb_mcc_records;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_build_decoder(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
/* add here initialization of cp
copy paste of setup_decoder */
(void)p_j2k;
(void)p_stream;
(void)p_manager;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_build_encoder(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
/* add here initialization of cp
copy paste of setup_encoder */
(void)p_j2k;
(void)p_stream;
(void)p_manager;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_encoding_validation(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_BOOL l_is_valid = OPJ_TRUE;
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_stream);
/* STATE checking */
/* make sure the state is at 0 */
l_is_valid &= (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_NONE);
/* POINTER validation */
/* make sure a p_j2k codec is present */
l_is_valid &= (p_j2k->m_procedure_list != 00);
/* make sure a validation list is present */
l_is_valid &= (p_j2k->m_validation_list != 00);
/* ISO 15444-1:2004 states between 1 & 33 (0 -> 32) */
/* 33 (32) would always fail the check below (if a cast to 64bits was done) */
/* FIXME Shall we change OPJ_J2K_MAXRLVLS to 32 ? */
if ((p_j2k->m_cp.tcps->tccps->numresolutions <= 0) ||
(p_j2k->m_cp.tcps->tccps->numresolutions > 32)) {
opj_event_msg(p_manager, EVT_ERROR,
"Number of resolutions is too high in comparison to the size of tiles\n");
return OPJ_FALSE;
}
if ((p_j2k->m_cp.tdx) < (OPJ_UINT32)(1 <<
(p_j2k->m_cp.tcps->tccps->numresolutions - 1U))) {
opj_event_msg(p_manager, EVT_ERROR,
"Number of resolutions is too high in comparison to the size of tiles\n");
return OPJ_FALSE;
}
if ((p_j2k->m_cp.tdy) < (OPJ_UINT32)(1 <<
(p_j2k->m_cp.tcps->tccps->numresolutions - 1U))) {
opj_event_msg(p_manager, EVT_ERROR,
"Number of resolutions is too high in comparison to the size of tiles\n");
return OPJ_FALSE;
}
/* PARAMETER VALIDATION */
return l_is_valid;
}
static OPJ_BOOL opj_j2k_decoding_validation(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_BOOL l_is_valid = OPJ_TRUE;
/* preconditions*/
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_stream);
OPJ_UNUSED(p_manager);
/* STATE checking */
/* make sure the state is at 0 */
#ifdef TODO_MSD
l_is_valid &= (p_j2k->m_specific_param.m_decoder.m_state == J2K_DEC_STATE_NONE);
#endif
l_is_valid &= (p_j2k->m_specific_param.m_decoder.m_state == 0x0000);
/* POINTER validation */
/* make sure a p_j2k codec is present */
/* make sure a procedure list is present */
l_is_valid &= (p_j2k->m_procedure_list != 00);
/* make sure a validation list is present */
l_is_valid &= (p_j2k->m_validation_list != 00);
/* PARAMETER VALIDATION */
return l_is_valid;
}
static OPJ_BOOL opj_j2k_read_header_procedure(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 l_current_marker;
OPJ_UINT32 l_marker_size;
const opj_dec_memory_marker_handler_t * l_marker_handler = 00;
OPJ_BOOL l_has_siz = 0;
OPJ_BOOL l_has_cod = 0;
OPJ_BOOL l_has_qcd = 0;
/* preconditions */
assert(p_stream != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
/* We enter in the main header */
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_MHSOC;
/* Try to read the SOC marker, the codestream must begin with SOC marker */
if (! opj_j2k_read_soc(p_j2k, p_stream, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Expected a SOC marker \n");
return OPJ_FALSE;
}
/* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* Read 2 bytes as the new marker ID */
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,
&l_current_marker, 2);
/* Try to read until the SOT is detected */
while (l_current_marker != J2K_MS_SOT) {
/* Check if the current marker ID is valid */
if (l_current_marker < 0xff00) {
opj_event_msg(p_manager, EVT_ERROR,
"A marker ID was expected (0xff--) instead of %.8x\n", l_current_marker);
return OPJ_FALSE;
}
/* Get the marker handler from the marker ID */
l_marker_handler = opj_j2k_get_marker_handler(l_current_marker);
/* Manage case where marker is unknown */
if (l_marker_handler->id == J2K_MS_UNK) {
if (! opj_j2k_read_unk(p_j2k, p_stream, &l_current_marker, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR,
"Unknow marker have been detected and generated error.\n");
return OPJ_FALSE;
}
if (l_current_marker == J2K_MS_SOT) {
break; /* SOT marker is detected main header is completely read */
} else { /* Get the marker handler from the marker ID */
l_marker_handler = opj_j2k_get_marker_handler(l_current_marker);
}
}
if (l_marker_handler->id == J2K_MS_SIZ) {
/* Mark required SIZ marker as found */
l_has_siz = 1;
}
if (l_marker_handler->id == J2K_MS_COD) {
/* Mark required COD marker as found */
l_has_cod = 1;
}
if (l_marker_handler->id == J2K_MS_QCD) {
/* Mark required QCD marker as found */
l_has_qcd = 1;
}
/* Check if the marker is known and if it is the right place to find it */
if (!(p_j2k->m_specific_param.m_decoder.m_state & l_marker_handler->states)) {
opj_event_msg(p_manager, EVT_ERROR,
"Marker is not compliant with its position\n");
return OPJ_FALSE;
}
/* Try to read 2 bytes (the marker size) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* read 2 bytes as the marker size */
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data, &l_marker_size,
2);
if (l_marker_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Invalid marker size\n");
return OPJ_FALSE;
}
l_marker_size -= 2; /* Subtract the size of the marker ID already read */
/* Check if the marker size is compatible with the header data size */
if (l_marker_size > p_j2k->m_specific_param.m_decoder.m_header_data_size) {
OPJ_BYTE *new_header_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size);
if (! new_header_data) {
opj_free(p_j2k->m_specific_param.m_decoder.m_header_data);
p_j2k->m_specific_param.m_decoder.m_header_data = NULL;
p_j2k->m_specific_param.m_decoder.m_header_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read header\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_decoder.m_header_data = new_header_data;
p_j2k->m_specific_param.m_decoder.m_header_data_size = l_marker_size;
}
/* Try to read the rest of the marker segment from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size,
p_manager) != l_marker_size) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* Read the marker segment with the correct marker handler */
if (!(*(l_marker_handler->handler))(p_j2k,
p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR,
"Marker handler function failed to read the marker segment\n");
return OPJ_FALSE;
}
/* Add the marker to the codestream index*/
if (OPJ_FALSE == opj_j2k_add_mhmarker(
p_j2k->cstr_index,
l_marker_handler->id,
(OPJ_UINT32) opj_stream_tell(p_stream) - l_marker_size - 4,
l_marker_size + 4)) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add mh marker\n");
return OPJ_FALSE;
}
/* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* read 2 bytes as the new marker ID */
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,
&l_current_marker, 2);
}
if (l_has_siz == 0) {
opj_event_msg(p_manager, EVT_ERROR,
"required SIZ marker not found in main header\n");
return OPJ_FALSE;
}
if (l_has_cod == 0) {
opj_event_msg(p_manager, EVT_ERROR,
"required COD marker not found in main header\n");
return OPJ_FALSE;
}
if (l_has_qcd == 0) {
opj_event_msg(p_manager, EVT_ERROR,
"required QCD marker not found in main header\n");
return OPJ_FALSE;
}
if (! opj_j2k_merge_ppm(&(p_j2k->m_cp), p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Failed to merge PPM data\n");
return OPJ_FALSE;
}
opj_event_msg(p_manager, EVT_INFO, "Main header has been correctly decoded.\n");
/* Position of the last element if the main header */
p_j2k->cstr_index->main_head_end = (OPJ_UINT32) opj_stream_tell(p_stream) - 2;
/* Next step: read a tile-part header */
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPHSOT;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_exec(opj_j2k_t * p_j2k,
opj_procedure_list_t * p_procedure_list,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_BOOL(** l_procedure)(opj_j2k_t *, opj_stream_private_t *,
opj_event_mgr_t *) = 00;
OPJ_BOOL l_result = OPJ_TRUE;
OPJ_UINT32 l_nb_proc, i;
/* preconditions*/
assert(p_procedure_list != 00);
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
l_nb_proc = opj_procedure_list_get_nb_procedures(p_procedure_list);
l_procedure = (OPJ_BOOL(**)(opj_j2k_t *, opj_stream_private_t *,
opj_event_mgr_t *)) opj_procedure_list_get_first_procedure(p_procedure_list);
for (i = 0; i < l_nb_proc; ++i) {
l_result = l_result && ((*l_procedure)(p_j2k, p_stream, p_manager));
++l_procedure;
}
/* and clear the procedure list at the end.*/
opj_procedure_list_clear(p_procedure_list);
return l_result;
}
/* FIXME DOC*/
static OPJ_BOOL opj_j2k_copy_default_tcp_and_create_tcd(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
opj_tcp_t * l_tcp = 00;
opj_tcp_t * l_default_tcp = 00;
OPJ_UINT32 l_nb_tiles;
OPJ_UINT32 i, j;
opj_tccp_t *l_current_tccp = 00;
OPJ_UINT32 l_tccp_size;
OPJ_UINT32 l_mct_size;
opj_image_t * l_image;
OPJ_UINT32 l_mcc_records_size, l_mct_records_size;
opj_mct_data_t * l_src_mct_rec, *l_dest_mct_rec;
opj_simple_mcc_decorrelation_data_t * l_src_mcc_rec, *l_dest_mcc_rec;
OPJ_UINT32 l_offset;
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_stream);
l_image = p_j2k->m_private_image;
l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
l_tcp = p_j2k->m_cp.tcps;
l_tccp_size = l_image->numcomps * (OPJ_UINT32)sizeof(opj_tccp_t);
l_default_tcp = p_j2k->m_specific_param.m_decoder.m_default_tcp;
l_mct_size = l_image->numcomps * l_image->numcomps * (OPJ_UINT32)sizeof(
OPJ_FLOAT32);
/* For each tile */
for (i = 0; i < l_nb_tiles; ++i) {
/* keep the tile-compo coding parameters pointer of the current tile coding parameters*/
l_current_tccp = l_tcp->tccps;
/*Copy default coding parameters into the current tile coding parameters*/
memcpy(l_tcp, l_default_tcp, sizeof(opj_tcp_t));
/* Initialize some values of the current tile coding parameters*/
l_tcp->cod = 0;
l_tcp->ppt = 0;
l_tcp->ppt_data = 00;
l_tcp->m_current_tile_part_number = -1;
/* Remove memory not owned by this tile in case of early error return. */
l_tcp->m_mct_decoding_matrix = 00;
l_tcp->m_nb_max_mct_records = 0;
l_tcp->m_mct_records = 00;
l_tcp->m_nb_max_mcc_records = 0;
l_tcp->m_mcc_records = 00;
/* Reconnect the tile-compo coding parameters pointer to the current tile coding parameters*/
l_tcp->tccps = l_current_tccp;
/* Get the mct_decoding_matrix of the dflt_tile_cp and copy them into the current tile cp*/
if (l_default_tcp->m_mct_decoding_matrix) {
l_tcp->m_mct_decoding_matrix = (OPJ_FLOAT32*)opj_malloc(l_mct_size);
if (! l_tcp->m_mct_decoding_matrix) {
return OPJ_FALSE;
}
memcpy(l_tcp->m_mct_decoding_matrix, l_default_tcp->m_mct_decoding_matrix,
l_mct_size);
}
/* Get the mct_record of the dflt_tile_cp and copy them into the current tile cp*/
l_mct_records_size = l_default_tcp->m_nb_max_mct_records * (OPJ_UINT32)sizeof(
opj_mct_data_t);
l_tcp->m_mct_records = (opj_mct_data_t*)opj_malloc(l_mct_records_size);
if (! l_tcp->m_mct_records) {
return OPJ_FALSE;
}
memcpy(l_tcp->m_mct_records, l_default_tcp->m_mct_records, l_mct_records_size);
/* Copy the mct record data from dflt_tile_cp to the current tile*/
l_src_mct_rec = l_default_tcp->m_mct_records;
l_dest_mct_rec = l_tcp->m_mct_records;
for (j = 0; j < l_default_tcp->m_nb_mct_records; ++j) {
if (l_src_mct_rec->m_data) {
l_dest_mct_rec->m_data = (OPJ_BYTE*) opj_malloc(l_src_mct_rec->m_data_size);
if (! l_dest_mct_rec->m_data) {
return OPJ_FALSE;
}
memcpy(l_dest_mct_rec->m_data, l_src_mct_rec->m_data,
l_src_mct_rec->m_data_size);
}
++l_src_mct_rec;
++l_dest_mct_rec;
/* Update with each pass to free exactly what has been allocated on early return. */
l_tcp->m_nb_max_mct_records += 1;
}
/* Get the mcc_record of the dflt_tile_cp and copy them into the current tile cp*/
l_mcc_records_size = l_default_tcp->m_nb_max_mcc_records * (OPJ_UINT32)sizeof(
opj_simple_mcc_decorrelation_data_t);
l_tcp->m_mcc_records = (opj_simple_mcc_decorrelation_data_t*) opj_malloc(
l_mcc_records_size);
if (! l_tcp->m_mcc_records) {
return OPJ_FALSE;
}
memcpy(l_tcp->m_mcc_records, l_default_tcp->m_mcc_records, l_mcc_records_size);
l_tcp->m_nb_max_mcc_records = l_default_tcp->m_nb_max_mcc_records;
/* Copy the mcc record data from dflt_tile_cp to the current tile*/
l_src_mcc_rec = l_default_tcp->m_mcc_records;
l_dest_mcc_rec = l_tcp->m_mcc_records;
for (j = 0; j < l_default_tcp->m_nb_max_mcc_records; ++j) {
if (l_src_mcc_rec->m_decorrelation_array) {
l_offset = (OPJ_UINT32)(l_src_mcc_rec->m_decorrelation_array -
l_default_tcp->m_mct_records);
l_dest_mcc_rec->m_decorrelation_array = l_tcp->m_mct_records + l_offset;
}
if (l_src_mcc_rec->m_offset_array) {
l_offset = (OPJ_UINT32)(l_src_mcc_rec->m_offset_array -
l_default_tcp->m_mct_records);
l_dest_mcc_rec->m_offset_array = l_tcp->m_mct_records + l_offset;
}
++l_src_mcc_rec;
++l_dest_mcc_rec;
}
/* Copy all the dflt_tile_compo_cp to the current tile cp */
memcpy(l_current_tccp, l_default_tcp->tccps, l_tccp_size);
/* Move to next tile cp*/
++l_tcp;
}
/* Create the current tile decoder*/
p_j2k->m_tcd = (opj_tcd_t*)opj_tcd_create(OPJ_TRUE); /* FIXME why a cast ? */
if (! p_j2k->m_tcd) {
return OPJ_FALSE;
}
if (!opj_tcd_init(p_j2k->m_tcd, l_image, &(p_j2k->m_cp), p_j2k->m_tp)) {
opj_tcd_destroy(p_j2k->m_tcd);
p_j2k->m_tcd = 00;
opj_event_msg(p_manager, EVT_ERROR, "Cannot decode tile, memory error\n");
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static const opj_dec_memory_marker_handler_t * opj_j2k_get_marker_handler(
OPJ_UINT32 p_id)
{
const opj_dec_memory_marker_handler_t *e;
for (e = j2k_memory_marker_handler_tab; e->id != 0; ++e) {
if (e->id == p_id) {
break; /* we find a handler corresponding to the marker ID*/
}
}
return e;
}
void opj_j2k_destroy(opj_j2k_t *p_j2k)
{
if (p_j2k == 00) {
return;
}
if (p_j2k->m_is_decoder) {
if (p_j2k->m_specific_param.m_decoder.m_default_tcp != 00) {
opj_j2k_tcp_destroy(p_j2k->m_specific_param.m_decoder.m_default_tcp);
opj_free(p_j2k->m_specific_param.m_decoder.m_default_tcp);
p_j2k->m_specific_param.m_decoder.m_default_tcp = 00;
}
if (p_j2k->m_specific_param.m_decoder.m_header_data != 00) {
opj_free(p_j2k->m_specific_param.m_decoder.m_header_data);
p_j2k->m_specific_param.m_decoder.m_header_data = 00;
p_j2k->m_specific_param.m_decoder.m_header_data_size = 0;
}
} else {
if (p_j2k->m_specific_param.m_encoder.m_encoded_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_encoded_tile_data);
p_j2k->m_specific_param.m_encoder.m_encoded_tile_data = 00;
}
if (p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer) {
opj_free(p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer);
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer = 00;
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current = 00;
}
if (p_j2k->m_specific_param.m_encoder.m_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = 00;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
}
}
opj_tcd_destroy(p_j2k->m_tcd);
opj_j2k_cp_destroy(&(p_j2k->m_cp));
memset(&(p_j2k->m_cp), 0, sizeof(opj_cp_t));
opj_procedure_list_destroy(p_j2k->m_procedure_list);
p_j2k->m_procedure_list = 00;
opj_procedure_list_destroy(p_j2k->m_validation_list);
p_j2k->m_procedure_list = 00;
j2k_destroy_cstr_index(p_j2k->cstr_index);
p_j2k->cstr_index = NULL;
opj_image_destroy(p_j2k->m_private_image);
p_j2k->m_private_image = NULL;
opj_image_destroy(p_j2k->m_output_image);
p_j2k->m_output_image = NULL;
opj_thread_pool_destroy(p_j2k->m_tp);
p_j2k->m_tp = NULL;
opj_free(p_j2k);
}
void j2k_destroy_cstr_index(opj_codestream_index_t *p_cstr_ind)
{
if (p_cstr_ind) {
if (p_cstr_ind->marker) {
opj_free(p_cstr_ind->marker);
p_cstr_ind->marker = NULL;
}
if (p_cstr_ind->tile_index) {
OPJ_UINT32 it_tile = 0;
for (it_tile = 0; it_tile < p_cstr_ind->nb_of_tiles; it_tile++) {
if (p_cstr_ind->tile_index[it_tile].packet_index) {
opj_free(p_cstr_ind->tile_index[it_tile].packet_index);
p_cstr_ind->tile_index[it_tile].packet_index = NULL;
}
if (p_cstr_ind->tile_index[it_tile].tp_index) {
opj_free(p_cstr_ind->tile_index[it_tile].tp_index);
p_cstr_ind->tile_index[it_tile].tp_index = NULL;
}
if (p_cstr_ind->tile_index[it_tile].marker) {
opj_free(p_cstr_ind->tile_index[it_tile].marker);
p_cstr_ind->tile_index[it_tile].marker = NULL;
}
}
opj_free(p_cstr_ind->tile_index);
p_cstr_ind->tile_index = NULL;
}
opj_free(p_cstr_ind);
}
}
static void opj_j2k_tcp_destroy(opj_tcp_t *p_tcp)
{
if (p_tcp == 00) {
return;
}
if (p_tcp->ppt_markers != 00) {
OPJ_UINT32 i;
for (i = 0U; i < p_tcp->ppt_markers_count; ++i) {
if (p_tcp->ppt_markers[i].m_data != NULL) {
opj_free(p_tcp->ppt_markers[i].m_data);
}
}
p_tcp->ppt_markers_count = 0U;
opj_free(p_tcp->ppt_markers);
p_tcp->ppt_markers = NULL;
}
if (p_tcp->ppt_buffer != 00) {
opj_free(p_tcp->ppt_buffer);
p_tcp->ppt_buffer = 00;
}
if (p_tcp->tccps != 00) {
opj_free(p_tcp->tccps);
p_tcp->tccps = 00;
}
if (p_tcp->m_mct_coding_matrix != 00) {
opj_free(p_tcp->m_mct_coding_matrix);
p_tcp->m_mct_coding_matrix = 00;
}
if (p_tcp->m_mct_decoding_matrix != 00) {
opj_free(p_tcp->m_mct_decoding_matrix);
p_tcp->m_mct_decoding_matrix = 00;
}
if (p_tcp->m_mcc_records) {
opj_free(p_tcp->m_mcc_records);
p_tcp->m_mcc_records = 00;
p_tcp->m_nb_max_mcc_records = 0;
p_tcp->m_nb_mcc_records = 0;
}
if (p_tcp->m_mct_records) {
opj_mct_data_t * l_mct_data = p_tcp->m_mct_records;
OPJ_UINT32 i;
for (i = 0; i < p_tcp->m_nb_mct_records; ++i) {
if (l_mct_data->m_data) {
opj_free(l_mct_data->m_data);
l_mct_data->m_data = 00;
}
++l_mct_data;
}
opj_free(p_tcp->m_mct_records);
p_tcp->m_mct_records = 00;
}
if (p_tcp->mct_norms != 00) {
opj_free(p_tcp->mct_norms);
p_tcp->mct_norms = 00;
}
opj_j2k_tcp_data_destroy(p_tcp);
}
static void opj_j2k_tcp_data_destroy(opj_tcp_t *p_tcp)
{
if (p_tcp->m_data) {
opj_free(p_tcp->m_data);
p_tcp->m_data = NULL;
p_tcp->m_data_size = 0;
}
}
static void opj_j2k_cp_destroy(opj_cp_t *p_cp)
{
OPJ_UINT32 l_nb_tiles;
opj_tcp_t * l_current_tile = 00;
if (p_cp == 00) {
return;
}
if (p_cp->tcps != 00) {
OPJ_UINT32 i;
l_current_tile = p_cp->tcps;
l_nb_tiles = p_cp->th * p_cp->tw;
for (i = 0U; i < l_nb_tiles; ++i) {
opj_j2k_tcp_destroy(l_current_tile);
++l_current_tile;
}
opj_free(p_cp->tcps);
p_cp->tcps = 00;
}
if (p_cp->ppm_markers != 00) {
OPJ_UINT32 i;
for (i = 0U; i < p_cp->ppm_markers_count; ++i) {
if (p_cp->ppm_markers[i].m_data != NULL) {
opj_free(p_cp->ppm_markers[i].m_data);
}
}
p_cp->ppm_markers_count = 0U;
opj_free(p_cp->ppm_markers);
p_cp->ppm_markers = NULL;
}
opj_free(p_cp->ppm_buffer);
p_cp->ppm_buffer = 00;
p_cp->ppm_data =
NULL; /* ppm_data belongs to the allocated buffer pointed by ppm_buffer */
opj_free(p_cp->comment);
p_cp->comment = 00;
if (! p_cp->m_is_decoder) {
opj_free(p_cp->m_specific_param.m_enc.m_matrice);
p_cp->m_specific_param.m_enc.m_matrice = 00;
}
}
static OPJ_BOOL opj_j2k_need_nb_tile_parts_correction(opj_stream_private_t
*p_stream, OPJ_UINT32 tile_no, OPJ_BOOL* p_correction_needed,
opj_event_mgr_t * p_manager)
{
OPJ_BYTE l_header_data[10];
OPJ_OFF_T l_stream_pos_backup;
OPJ_UINT32 l_current_marker;
OPJ_UINT32 l_marker_size;
OPJ_UINT32 l_tile_no, l_tot_len, l_current_part, l_num_parts;
/* initialize to no correction needed */
*p_correction_needed = OPJ_FALSE;
if (!opj_stream_has_seek(p_stream)) {
/* We can't do much in this case, seek is needed */
return OPJ_TRUE;
}
l_stream_pos_backup = opj_stream_tell(p_stream);
if (l_stream_pos_backup == -1) {
/* let's do nothing */
return OPJ_TRUE;
}
for (;;) {
/* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream, l_header_data, 2, p_manager) != 2) {
/* assume all is OK */
if (! opj_stream_seek(p_stream, l_stream_pos_backup, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/* Read 2 bytes from buffer as the new marker ID */
opj_read_bytes(l_header_data, &l_current_marker, 2);
if (l_current_marker != J2K_MS_SOT) {
/* assume all is OK */
if (! opj_stream_seek(p_stream, l_stream_pos_backup, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/* Try to read 2 bytes (the marker size) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream, l_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* Read 2 bytes from the buffer as the marker size */
opj_read_bytes(l_header_data, &l_marker_size, 2);
/* Check marker size for SOT Marker */
if (l_marker_size != 10) {
opj_event_msg(p_manager, EVT_ERROR, "Inconsistent marker size\n");
return OPJ_FALSE;
}
l_marker_size -= 2;
if (opj_stream_read_data(p_stream, l_header_data, l_marker_size,
p_manager) != l_marker_size) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
if (! opj_j2k_get_sot_values(l_header_data, l_marker_size, &l_tile_no,
&l_tot_len, &l_current_part, &l_num_parts, p_manager)) {
return OPJ_FALSE;
}
if (l_tile_no == tile_no) {
/* we found what we were looking for */
break;
}
if ((l_tot_len == 0U) || (l_tot_len < 14U)) {
/* last SOT until EOC or invalid Psot value */
/* assume all is OK */
if (! opj_stream_seek(p_stream, l_stream_pos_backup, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
l_tot_len -= 12U;
/* look for next SOT marker */
if (opj_stream_skip(p_stream, (OPJ_OFF_T)(l_tot_len),
p_manager) != (OPJ_OFF_T)(l_tot_len)) {
/* assume all is OK */
if (! opj_stream_seek(p_stream, l_stream_pos_backup, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
}
/* check for correction */
if (l_current_part == l_num_parts) {
*p_correction_needed = OPJ_TRUE;
}
if (! opj_stream_seek(p_stream, l_stream_pos_backup, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_read_tile_header(opj_j2k_t * p_j2k,
OPJ_UINT32 * p_tile_index,
OPJ_UINT32 * p_data_size,
OPJ_INT32 * p_tile_x0, OPJ_INT32 * p_tile_y0,
OPJ_INT32 * p_tile_x1, OPJ_INT32 * p_tile_y1,
OPJ_UINT32 * p_nb_comps,
OPJ_BOOL * p_go_on,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 l_current_marker = J2K_MS_SOT;
OPJ_UINT32 l_marker_size;
const opj_dec_memory_marker_handler_t * l_marker_handler = 00;
opj_tcp_t * l_tcp = NULL;
/* preconditions */
assert(p_stream != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
/* Reach the End Of Codestream ?*/
if (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_EOC) {
l_current_marker = J2K_MS_EOC;
}
/* We need to encounter a SOT marker (a new tile-part header) */
else if (p_j2k->m_specific_param.m_decoder.m_state != J2K_STATE_TPHSOT) {
return OPJ_FALSE;
}
/* Read into the codestream until reach the EOC or ! can_decode ??? FIXME */
while ((!p_j2k->m_specific_param.m_decoder.m_can_decode) &&
(l_current_marker != J2K_MS_EOC)) {
/* Try to read until the Start Of Data is detected */
while (l_current_marker != J2K_MS_SOD) {
if (opj_stream_get_number_byte_left(p_stream) == 0) {
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_NEOC;
break;
}
/* Try to read 2 bytes (the marker size) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* Read 2 bytes from the buffer as the marker size */
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data, &l_marker_size,
2);
/* Check marker size (does not include marker ID but includes marker size) */
if (l_marker_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Inconsistent marker size\n");
return OPJ_FALSE;
}
/* cf. https://code.google.com/p/openjpeg/issues/detail?id=226 */
if (l_current_marker == 0x8080 &&
opj_stream_get_number_byte_left(p_stream) == 0) {
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_NEOC;
break;
}
/* Why this condition? FIXME */
if (p_j2k->m_specific_param.m_decoder.m_state & J2K_STATE_TPH) {
p_j2k->m_specific_param.m_decoder.m_sot_length -= (l_marker_size + 2);
}
l_marker_size -= 2; /* Subtract the size of the marker ID already read */
/* Get the marker handler from the marker ID */
l_marker_handler = opj_j2k_get_marker_handler(l_current_marker);
/* Check if the marker is known and if it is the right place to find it */
if (!(p_j2k->m_specific_param.m_decoder.m_state & l_marker_handler->states)) {
opj_event_msg(p_manager, EVT_ERROR,
"Marker is not compliant with its position\n");
return OPJ_FALSE;
}
/* FIXME manage case of unknown marker as in the main header ? */
/* Check if the marker size is compatible with the header data size */
if (l_marker_size > p_j2k->m_specific_param.m_decoder.m_header_data_size) {
OPJ_BYTE *new_header_data = NULL;
/* If we are here, this means we consider this marker as known & we will read it */
/* Check enough bytes left in stream before allocation */
if ((OPJ_OFF_T)l_marker_size > opj_stream_get_number_byte_left(p_stream)) {
opj_event_msg(p_manager, EVT_ERROR,
"Marker size inconsistent with stream length\n");
return OPJ_FALSE;
}
new_header_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size);
if (! new_header_data) {
opj_free(p_j2k->m_specific_param.m_decoder.m_header_data);
p_j2k->m_specific_param.m_decoder.m_header_data = NULL;
p_j2k->m_specific_param.m_decoder.m_header_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read header\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_decoder.m_header_data = new_header_data;
p_j2k->m_specific_param.m_decoder.m_header_data_size = l_marker_size;
}
/* Try to read the rest of the marker segment from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size,
p_manager) != l_marker_size) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
if (!l_marker_handler->handler) {
/* See issue #175 */
opj_event_msg(p_manager, EVT_ERROR, "Not sure how that happened.\n");
return OPJ_FALSE;
}
/* Read the marker segment with the correct marker handler */
if (!(*(l_marker_handler->handler))(p_j2k,
p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR,
"Fail to read the current marker segment (%#x)\n", l_current_marker);
return OPJ_FALSE;
}
/* Add the marker to the codestream index*/
if (OPJ_FALSE == opj_j2k_add_tlmarker(p_j2k->m_current_tile_number,
p_j2k->cstr_index,
l_marker_handler->id,
(OPJ_UINT32) opj_stream_tell(p_stream) - l_marker_size - 4,
l_marker_size + 4)) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add tl marker\n");
return OPJ_FALSE;
}
/* Keep the position of the last SOT marker read */
if (l_marker_handler->id == J2K_MS_SOT) {
OPJ_UINT32 sot_pos = (OPJ_UINT32) opj_stream_tell(p_stream) - l_marker_size - 4
;
if (sot_pos > p_j2k->m_specific_param.m_decoder.m_last_sot_read_pos) {
p_j2k->m_specific_param.m_decoder.m_last_sot_read_pos = sot_pos;
}
}
if (p_j2k->m_specific_param.m_decoder.m_skip_data) {
/* Skip the rest of the tile part header*/
if (opj_stream_skip(p_stream, p_j2k->m_specific_param.m_decoder.m_sot_length,
p_manager) != p_j2k->m_specific_param.m_decoder.m_sot_length) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
l_current_marker = J2K_MS_SOD; /* Normally we reached a SOD */
} else {
/* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer*/
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* Read 2 bytes from the buffer as the new marker ID */
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,
&l_current_marker, 2);
}
}
if (opj_stream_get_number_byte_left(p_stream) == 0
&& p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_NEOC) {
break;
}
/* If we didn't skip data before, we need to read the SOD marker*/
if (! p_j2k->m_specific_param.m_decoder.m_skip_data) {
/* Try to read the SOD marker and skip data ? FIXME */
if (! opj_j2k_read_sod(p_j2k, p_stream, p_manager)) {
return OPJ_FALSE;
}
if (p_j2k->m_specific_param.m_decoder.m_can_decode &&
!p_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction_checked) {
/* Issue 254 */
OPJ_BOOL l_correction_needed;
p_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction_checked = 1;
if (!opj_j2k_need_nb_tile_parts_correction(p_stream,
p_j2k->m_current_tile_number, &l_correction_needed, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR,
"opj_j2k_apply_nb_tile_parts_correction error\n");
return OPJ_FALSE;
}
if (l_correction_needed) {
OPJ_UINT32 l_nb_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th;
OPJ_UINT32 l_tile_no;
p_j2k->m_specific_param.m_decoder.m_can_decode = 0;
p_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction = 1;
/* correct tiles */
for (l_tile_no = 0U; l_tile_no < l_nb_tiles; ++l_tile_no) {
if (p_j2k->m_cp.tcps[l_tile_no].m_nb_tile_parts != 0U) {
p_j2k->m_cp.tcps[l_tile_no].m_nb_tile_parts += 1;
}
}
opj_event_msg(p_manager, EVT_WARNING,
"Non conformant codestream TPsot==TNsot.\n");
}
}
if (! p_j2k->m_specific_param.m_decoder.m_can_decode) {
/* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* Read 2 bytes from buffer as the new marker ID */
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,
&l_current_marker, 2);
}
} else {
/* Indicate we will try to read a new tile-part header*/
p_j2k->m_specific_param.m_decoder.m_skip_data = 0;
p_j2k->m_specific_param.m_decoder.m_can_decode = 0;
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPHSOT;
/* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* Read 2 bytes from buffer as the new marker ID */
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,
&l_current_marker, 2);
}
}
/* Current marker is the EOC marker ?*/
if (l_current_marker == J2K_MS_EOC) {
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_EOC;
}
/* FIXME DOC ???*/
if (! p_j2k->m_specific_param.m_decoder.m_can_decode) {
OPJ_UINT32 l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
l_tcp = p_j2k->m_cp.tcps + p_j2k->m_current_tile_number;
while ((p_j2k->m_current_tile_number < l_nb_tiles) && (l_tcp->m_data == 00)) {
++p_j2k->m_current_tile_number;
++l_tcp;
}
if (p_j2k->m_current_tile_number == l_nb_tiles) {
*p_go_on = OPJ_FALSE;
return OPJ_TRUE;
}
}
if (! opj_j2k_merge_ppt(p_j2k->m_cp.tcps + p_j2k->m_current_tile_number,
p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Failed to merge PPT data\n");
return OPJ_FALSE;
}
/*FIXME ???*/
if (! opj_tcd_init_decode_tile(p_j2k->m_tcd, p_j2k->m_current_tile_number,
p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Cannot decode tile, memory error\n");
return OPJ_FALSE;
}
opj_event_msg(p_manager, EVT_INFO, "Header of tile %d / %d has been read.\n",
p_j2k->m_current_tile_number + 1, (p_j2k->m_cp.th * p_j2k->m_cp.tw));
*p_tile_index = p_j2k->m_current_tile_number;
*p_go_on = OPJ_TRUE;
*p_data_size = opj_tcd_get_decoded_tile_size(p_j2k->m_tcd);
if (*p_data_size == UINT_MAX) {
return OPJ_FALSE;
}
*p_tile_x0 = p_j2k->m_tcd->tcd_image->tiles->x0;
*p_tile_y0 = p_j2k->m_tcd->tcd_image->tiles->y0;
*p_tile_x1 = p_j2k->m_tcd->tcd_image->tiles->x1;
*p_tile_y1 = p_j2k->m_tcd->tcd_image->tiles->y1;
*p_nb_comps = p_j2k->m_tcd->tcd_image->tiles->numcomps;
p_j2k->m_specific_param.m_decoder.m_state |= J2K_STATE_DATA;
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_decode_tile(opj_j2k_t * p_j2k,
OPJ_UINT32 p_tile_index,
OPJ_BYTE * p_data,
OPJ_UINT32 p_data_size,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 l_current_marker;
OPJ_BYTE l_data [2];
opj_tcp_t * l_tcp;
/* preconditions */
assert(p_stream != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
if (!(p_j2k->m_specific_param.m_decoder.m_state & J2K_STATE_DATA)
|| (p_tile_index != p_j2k->m_current_tile_number)) {
return OPJ_FALSE;
}
l_tcp = &(p_j2k->m_cp.tcps[p_tile_index]);
if (! l_tcp->m_data) {
opj_j2k_tcp_destroy(l_tcp);
return OPJ_FALSE;
}
if (! opj_tcd_decode_tile(p_j2k->m_tcd,
l_tcp->m_data,
l_tcp->m_data_size,
p_tile_index,
p_j2k->cstr_index, p_manager)) {
opj_j2k_tcp_destroy(l_tcp);
p_j2k->m_specific_param.m_decoder.m_state |= J2K_STATE_ERR;
opj_event_msg(p_manager, EVT_ERROR, "Failed to decode.\n");
return OPJ_FALSE;
}
/* p_data can be set to NULL when the call will take care of using */
/* itself the TCD data. This is typically the case for whole single */
/* tile decoding optimization. */
if (p_data != NULL) {
if (! opj_tcd_update_tile_data(p_j2k->m_tcd, p_data, p_data_size)) {
return OPJ_FALSE;
}
/* To avoid to destroy the tcp which can be useful when we try to decode a tile decoded before (cf j2k_random_tile_access)
* we destroy just the data which will be re-read in read_tile_header*/
/*opj_j2k_tcp_destroy(l_tcp);
p_j2k->m_tcd->tcp = 0;*/
opj_j2k_tcp_data_destroy(l_tcp);
}
p_j2k->m_specific_param.m_decoder.m_can_decode = 0;
p_j2k->m_specific_param.m_decoder.m_state &= (~(OPJ_UINT32)J2K_STATE_DATA);
if (opj_stream_get_number_byte_left(p_stream) == 0
&& p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_NEOC) {
return OPJ_TRUE;
}
if (p_j2k->m_specific_param.m_decoder.m_state != J2K_STATE_EOC) {
if (opj_stream_read_data(p_stream, l_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
opj_read_bytes(l_data, &l_current_marker, 2);
if (l_current_marker == J2K_MS_EOC) {
p_j2k->m_current_tile_number = 0;
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_EOC;
} else if (l_current_marker != J2K_MS_SOT) {
if (opj_stream_get_number_byte_left(p_stream) == 0) {
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_NEOC;
opj_event_msg(p_manager, EVT_WARNING, "Stream does not end with EOC\n");
return OPJ_TRUE;
}
opj_event_msg(p_manager, EVT_ERROR, "Stream too short, expected SOT\n");
return OPJ_FALSE;
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_update_image_data(opj_tcd_t * p_tcd, OPJ_BYTE * p_data,
opj_image_t* p_output_image)
{
OPJ_UINT32 i, j, k = 0;
OPJ_UINT32 l_width_src, l_height_src;
OPJ_UINT32 l_width_dest, l_height_dest;
OPJ_INT32 l_offset_x0_src, l_offset_y0_src, l_offset_x1_src, l_offset_y1_src;
OPJ_SIZE_T l_start_offset_src, l_line_offset_src, l_end_offset_src ;
OPJ_UINT32 l_start_x_dest, l_start_y_dest;
OPJ_UINT32 l_x0_dest, l_y0_dest, l_x1_dest, l_y1_dest;
OPJ_SIZE_T l_start_offset_dest, l_line_offset_dest;
opj_image_comp_t * l_img_comp_src = 00;
opj_image_comp_t * l_img_comp_dest = 00;
opj_tcd_tilecomp_t * l_tilec = 00;
opj_image_t * l_image_src = 00;
OPJ_UINT32 l_size_comp, l_remaining;
OPJ_INT32 * l_dest_ptr;
opj_tcd_resolution_t* l_res = 00;
l_tilec = p_tcd->tcd_image->tiles->comps;
l_image_src = p_tcd->image;
l_img_comp_src = l_image_src->comps;
l_img_comp_dest = p_output_image->comps;
for (i = 0; i < l_image_src->numcomps; i++) {
/* Allocate output component buffer if necessary */
if (!l_img_comp_dest->data) {
OPJ_SIZE_T l_width = l_img_comp_dest->w;
OPJ_SIZE_T l_height = l_img_comp_dest->h;
if ((l_height == 0U) || (l_width > (SIZE_MAX / l_height)) ||
l_width * l_height > SIZE_MAX / sizeof(OPJ_INT32)) {
/* would overflow */
return OPJ_FALSE;
}
l_img_comp_dest->data = (OPJ_INT32*) opj_image_data_alloc(l_width * l_height *
sizeof(OPJ_INT32));
if (! l_img_comp_dest->data) {
return OPJ_FALSE;
}
/* Do we really need this memset ? */
memset(l_img_comp_dest->data, 0, l_width * l_height * sizeof(OPJ_INT32));
}
/* Copy info from decoded comp image to output image */
l_img_comp_dest->resno_decoded = l_img_comp_src->resno_decoded;
/*-----*/
/* Compute the precision of the output buffer */
l_size_comp = l_img_comp_src->prec >> 3; /*(/ 8)*/
l_remaining = l_img_comp_src->prec & 7; /* (%8) */
l_res = l_tilec->resolutions + l_img_comp_src->resno_decoded;
if (l_remaining) {
++l_size_comp;
}
if (l_size_comp == 3) {
l_size_comp = 4;
}
/*-----*/
/* Current tile component size*/
/*if (i == 0) {
fprintf(stdout, "SRC: l_res_x0=%d, l_res_x1=%d, l_res_y0=%d, l_res_y1=%d\n",
l_res->x0, l_res->x1, l_res->y0, l_res->y1);
}*/
l_width_src = (OPJ_UINT32)(l_res->x1 - l_res->x0);
l_height_src = (OPJ_UINT32)(l_res->y1 - l_res->y0);
/* Border of the current output component*/
l_x0_dest = opj_uint_ceildivpow2(l_img_comp_dest->x0, l_img_comp_dest->factor);
l_y0_dest = opj_uint_ceildivpow2(l_img_comp_dest->y0, l_img_comp_dest->factor);
l_x1_dest = l_x0_dest +
l_img_comp_dest->w; /* can't overflow given that image->x1 is uint32 */
l_y1_dest = l_y0_dest + l_img_comp_dest->h;
/*if (i == 0) {
fprintf(stdout, "DEST: l_x0_dest=%d, l_x1_dest=%d, l_y0_dest=%d, l_y1_dest=%d (%d)\n",
l_x0_dest, l_x1_dest, l_y0_dest, l_y1_dest, l_img_comp_dest->factor );
}*/
/*-----*/
/* Compute the area (l_offset_x0_src, l_offset_y0_src, l_offset_x1_src, l_offset_y1_src)
* of the input buffer (decoded tile component) which will be move
* in the output buffer. Compute the area of the output buffer (l_start_x_dest,
* l_start_y_dest, l_width_dest, l_height_dest) which will be modified
* by this input area.
* */
assert(l_res->x0 >= 0);
assert(l_res->x1 >= 0);
if (l_x0_dest < (OPJ_UINT32)l_res->x0) {
l_start_x_dest = (OPJ_UINT32)l_res->x0 - l_x0_dest;
l_offset_x0_src = 0;
if (l_x1_dest >= (OPJ_UINT32)l_res->x1) {
l_width_dest = l_width_src;
l_offset_x1_src = 0;
} else {
l_width_dest = l_x1_dest - (OPJ_UINT32)l_res->x0 ;
l_offset_x1_src = (OPJ_INT32)(l_width_src - l_width_dest);
}
} else {
l_start_x_dest = 0U;
l_offset_x0_src = (OPJ_INT32)l_x0_dest - l_res->x0;
if (l_x1_dest >= (OPJ_UINT32)l_res->x1) {
l_width_dest = l_width_src - (OPJ_UINT32)l_offset_x0_src;
l_offset_x1_src = 0;
} else {
l_width_dest = l_img_comp_dest->w ;
l_offset_x1_src = l_res->x1 - (OPJ_INT32)l_x1_dest;
}
}
if (l_y0_dest < (OPJ_UINT32)l_res->y0) {
l_start_y_dest = (OPJ_UINT32)l_res->y0 - l_y0_dest;
l_offset_y0_src = 0;
if (l_y1_dest >= (OPJ_UINT32)l_res->y1) {
l_height_dest = l_height_src;
l_offset_y1_src = 0;
} else {
l_height_dest = l_y1_dest - (OPJ_UINT32)l_res->y0 ;
l_offset_y1_src = (OPJ_INT32)(l_height_src - l_height_dest);
}
} else {
l_start_y_dest = 0U;
l_offset_y0_src = (OPJ_INT32)l_y0_dest - l_res->y0;
if (l_y1_dest >= (OPJ_UINT32)l_res->y1) {
l_height_dest = l_height_src - (OPJ_UINT32)l_offset_y0_src;
l_offset_y1_src = 0;
} else {
l_height_dest = l_img_comp_dest->h ;
l_offset_y1_src = l_res->y1 - (OPJ_INT32)l_y1_dest;
}
}
if ((l_offset_x0_src < 0) || (l_offset_y0_src < 0) || (l_offset_x1_src < 0) ||
(l_offset_y1_src < 0)) {
return OPJ_FALSE;
}
/* testcase 2977.pdf.asan.67.2198 */
if ((OPJ_INT32)l_width_dest < 0 || (OPJ_INT32)l_height_dest < 0) {
return OPJ_FALSE;
}
/*-----*/
/* Compute the input buffer offset */
l_start_offset_src = (OPJ_SIZE_T)l_offset_x0_src + (OPJ_SIZE_T)l_offset_y0_src
* (OPJ_SIZE_T)l_width_src;
l_line_offset_src = (OPJ_SIZE_T)l_offset_x1_src + (OPJ_SIZE_T)l_offset_x0_src;
l_end_offset_src = (OPJ_SIZE_T)l_offset_y1_src * (OPJ_SIZE_T)l_width_src -
(OPJ_SIZE_T)l_offset_x0_src;
/* Compute the output buffer offset */
l_start_offset_dest = (OPJ_SIZE_T)l_start_x_dest + (OPJ_SIZE_T)l_start_y_dest
* (OPJ_SIZE_T)l_img_comp_dest->w;
l_line_offset_dest = (OPJ_SIZE_T)l_img_comp_dest->w - (OPJ_SIZE_T)l_width_dest;
/* Move the output buffer to the first place where we will write*/
l_dest_ptr = l_img_comp_dest->data + l_start_offset_dest;
/*if (i == 0) {
fprintf(stdout, "COMPO[%d]:\n",i);
fprintf(stdout, "SRC: l_start_x_src=%d, l_start_y_src=%d, l_width_src=%d, l_height_src=%d\n"
"\t tile offset:%d, %d, %d, %d\n"
"\t buffer offset: %d; %d, %d\n",
l_res->x0, l_res->y0, l_width_src, l_height_src,
l_offset_x0_src, l_offset_y0_src, l_offset_x1_src, l_offset_y1_src,
l_start_offset_src, l_line_offset_src, l_end_offset_src);
fprintf(stdout, "DEST: l_start_x_dest=%d, l_start_y_dest=%d, l_width_dest=%d, l_height_dest=%d\n"
"\t start offset: %d, line offset= %d\n",
l_start_x_dest, l_start_y_dest, l_width_dest, l_height_dest, l_start_offset_dest, l_line_offset_dest);
}*/
switch (l_size_comp) {
case 1: {
OPJ_CHAR * l_src_ptr = (OPJ_CHAR*) p_data;
l_src_ptr += l_start_offset_src; /* Move to the first place where we will read*/
if (l_img_comp_src->sgnd) {
for (j = 0 ; j < l_height_dest ; ++j) {
for (k = 0 ; k < l_width_dest ; ++k) {
*(l_dest_ptr++) = (OPJ_INT32)(*
(l_src_ptr++)); /* Copy only the data needed for the output image */
}
l_dest_ptr +=
l_line_offset_dest; /* Move to the next place where we will write */
l_src_ptr += l_line_offset_src ; /* Move to the next place where we will read */
}
} else {
for (j = 0 ; j < l_height_dest ; ++j) {
for (k = 0 ; k < l_width_dest ; ++k) {
*(l_dest_ptr++) = (OPJ_INT32)((*(l_src_ptr++)) & 0xff);
}
l_dest_ptr += l_line_offset_dest;
l_src_ptr += l_line_offset_src;
}
}
l_src_ptr +=
l_end_offset_src; /* Move to the end of this component-part of the input buffer */
p_data = (OPJ_BYTE*)
l_src_ptr; /* Keep the current position for the next component-part */
}
break;
case 2: {
OPJ_INT16 * l_src_ptr = (OPJ_INT16 *) p_data;
l_src_ptr += l_start_offset_src;
if (l_img_comp_src->sgnd) {
for (j = 0; j < l_height_dest; ++j) {
for (k = 0; k < l_width_dest; ++k) {
OPJ_INT16 val;
memcpy(&val, l_src_ptr, sizeof(val));
l_src_ptr ++;
*(l_dest_ptr++) = val;
}
l_dest_ptr += l_line_offset_dest;
l_src_ptr += l_line_offset_src ;
}
} else {
for (j = 0; j < l_height_dest; ++j) {
for (k = 0; k < l_width_dest; ++k) {
OPJ_INT16 val;
memcpy(&val, l_src_ptr, sizeof(val));
l_src_ptr ++;
*(l_dest_ptr++) = val & 0xffff;
}
l_dest_ptr += l_line_offset_dest;
l_src_ptr += l_line_offset_src ;
}
}
l_src_ptr += l_end_offset_src;
p_data = (OPJ_BYTE*) l_src_ptr;
}
break;
case 4: {
OPJ_INT32 * l_src_ptr = (OPJ_INT32 *) p_data;
l_src_ptr += l_start_offset_src;
for (j = 0; j < l_height_dest; ++j) {
memcpy(l_dest_ptr, l_src_ptr, l_width_dest * sizeof(OPJ_INT32));
l_dest_ptr += l_width_dest + l_line_offset_dest;
l_src_ptr += l_width_dest + l_line_offset_src ;
}
l_src_ptr += l_end_offset_src;
p_data = (OPJ_BYTE*) l_src_ptr;
}
break;
}
++l_img_comp_dest;
++l_img_comp_src;
++l_tilec;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_set_decode_area(opj_j2k_t *p_j2k,
opj_image_t* p_image,
OPJ_INT32 p_start_x, OPJ_INT32 p_start_y,
OPJ_INT32 p_end_x, OPJ_INT32 p_end_y,
opj_event_mgr_t * p_manager)
{
opj_cp_t * l_cp = &(p_j2k->m_cp);
opj_image_t * l_image = p_j2k->m_private_image;
OPJ_UINT32 it_comp;
OPJ_INT32 l_comp_x1, l_comp_y1;
opj_image_comp_t* l_img_comp = NULL;
/* Check if we are read the main header */
if (p_j2k->m_specific_param.m_decoder.m_state != J2K_STATE_TPHSOT) {
opj_event_msg(p_manager, EVT_ERROR,
"Need to decode the main header before begin to decode the remaining codestream");
return OPJ_FALSE;
}
if (!p_start_x && !p_start_y && !p_end_x && !p_end_y) {
opj_event_msg(p_manager, EVT_INFO,
"No decoded area parameters, set the decoded area to the whole image\n");
p_j2k->m_specific_param.m_decoder.m_start_tile_x = 0;
p_j2k->m_specific_param.m_decoder.m_start_tile_y = 0;
p_j2k->m_specific_param.m_decoder.m_end_tile_x = l_cp->tw;
p_j2k->m_specific_param.m_decoder.m_end_tile_y = l_cp->th;
return OPJ_TRUE;
}
/* ----- */
/* Check if the positions provided by the user are correct */
/* Left */
if (p_start_x < 0) {
opj_event_msg(p_manager, EVT_ERROR,
"Left position of the decoded area (region_x0=%d) should be >= 0.\n",
p_start_x);
return OPJ_FALSE;
} else if ((OPJ_UINT32)p_start_x > l_image->x1) {
opj_event_msg(p_manager, EVT_ERROR,
"Left position of the decoded area (region_x0=%d) is outside the image area (Xsiz=%d).\n",
p_start_x, l_image->x1);
return OPJ_FALSE;
} else if ((OPJ_UINT32)p_start_x < l_image->x0) {
opj_event_msg(p_manager, EVT_WARNING,
"Left position of the decoded area (region_x0=%d) is outside the image area (XOsiz=%d).\n",
p_start_x, l_image->x0);
p_j2k->m_specific_param.m_decoder.m_start_tile_x = 0;
p_image->x0 = l_image->x0;
} else {
p_j2k->m_specific_param.m_decoder.m_start_tile_x = ((OPJ_UINT32)p_start_x -
l_cp->tx0) / l_cp->tdx;
p_image->x0 = (OPJ_UINT32)p_start_x;
}
/* Up */
if (p_start_x < 0) {
opj_event_msg(p_manager, EVT_ERROR,
"Up position of the decoded area (region_y0=%d) should be >= 0.\n",
p_start_y);
return OPJ_FALSE;
} else if ((OPJ_UINT32)p_start_y > l_image->y1) {
opj_event_msg(p_manager, EVT_ERROR,
"Up position of the decoded area (region_y0=%d) is outside the image area (Ysiz=%d).\n",
p_start_y, l_image->y1);
return OPJ_FALSE;
} else if ((OPJ_UINT32)p_start_y < l_image->y0) {
opj_event_msg(p_manager, EVT_WARNING,
"Up position of the decoded area (region_y0=%d) is outside the image area (YOsiz=%d).\n",
p_start_y, l_image->y0);
p_j2k->m_specific_param.m_decoder.m_start_tile_y = 0;
p_image->y0 = l_image->y0;
} else {
p_j2k->m_specific_param.m_decoder.m_start_tile_y = ((OPJ_UINT32)p_start_y -
l_cp->ty0) / l_cp->tdy;
p_image->y0 = (OPJ_UINT32)p_start_y;
}
/* Right */
if (p_end_x <= 0) {
opj_event_msg(p_manager, EVT_ERROR,
"Right position of the decoded area (region_x1=%d) should be > 0.\n",
p_end_x);
return OPJ_FALSE;
} else if ((OPJ_UINT32)p_end_x < l_image->x0) {
opj_event_msg(p_manager, EVT_ERROR,
"Right position of the decoded area (region_x1=%d) is outside the image area (XOsiz=%d).\n",
p_end_x, l_image->x0);
return OPJ_FALSE;
} else if ((OPJ_UINT32)p_end_x > l_image->x1) {
opj_event_msg(p_manager, EVT_WARNING,
"Right position of the decoded area (region_x1=%d) is outside the image area (Xsiz=%d).\n",
p_end_x, l_image->x1);
p_j2k->m_specific_param.m_decoder.m_end_tile_x = l_cp->tw;
p_image->x1 = l_image->x1;
} else {
p_j2k->m_specific_param.m_decoder.m_end_tile_x = (OPJ_UINT32)opj_int_ceildiv(
p_end_x - (OPJ_INT32)l_cp->tx0, (OPJ_INT32)l_cp->tdx);
p_image->x1 = (OPJ_UINT32)p_end_x;
}
/* Bottom */
if (p_end_y <= 0) {
opj_event_msg(p_manager, EVT_ERROR,
"Bottom position of the decoded area (region_y1=%d) should be > 0.\n",
p_end_y);
return OPJ_FALSE;
} else if ((OPJ_UINT32)p_end_y < l_image->y0) {
opj_event_msg(p_manager, EVT_ERROR,
"Bottom position of the decoded area (region_y1=%d) is outside the image area (YOsiz=%d).\n",
p_end_y, l_image->y0);
return OPJ_FALSE;
}
if ((OPJ_UINT32)p_end_y > l_image->y1) {
opj_event_msg(p_manager, EVT_WARNING,
"Bottom position of the decoded area (region_y1=%d) is outside the image area (Ysiz=%d).\n",
p_end_y, l_image->y1);
p_j2k->m_specific_param.m_decoder.m_end_tile_y = l_cp->th;
p_image->y1 = l_image->y1;
} else {
p_j2k->m_specific_param.m_decoder.m_end_tile_y = (OPJ_UINT32)opj_int_ceildiv(
p_end_y - (OPJ_INT32)l_cp->ty0, (OPJ_INT32)l_cp->tdy);
p_image->y1 = (OPJ_UINT32)p_end_y;
}
/* ----- */
p_j2k->m_specific_param.m_decoder.m_discard_tiles = 1;
l_img_comp = p_image->comps;
for (it_comp = 0; it_comp < p_image->numcomps; ++it_comp) {
OPJ_INT32 l_h, l_w;
l_img_comp->x0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->x0,
(OPJ_INT32)l_img_comp->dx);
l_img_comp->y0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->y0,
(OPJ_INT32)l_img_comp->dy);
l_comp_x1 = opj_int_ceildiv((OPJ_INT32)p_image->x1, (OPJ_INT32)l_img_comp->dx);
l_comp_y1 = opj_int_ceildiv((OPJ_INT32)p_image->y1, (OPJ_INT32)l_img_comp->dy);
l_w = opj_int_ceildivpow2(l_comp_x1, (OPJ_INT32)l_img_comp->factor)
- opj_int_ceildivpow2((OPJ_INT32)l_img_comp->x0, (OPJ_INT32)l_img_comp->factor);
if (l_w < 0) {
opj_event_msg(p_manager, EVT_ERROR,
"Size x of the decoded component image is incorrect (comp[%d].w=%d).\n",
it_comp, l_w);
return OPJ_FALSE;
}
l_img_comp->w = (OPJ_UINT32)l_w;
l_h = opj_int_ceildivpow2(l_comp_y1, (OPJ_INT32)l_img_comp->factor)
- opj_int_ceildivpow2((OPJ_INT32)l_img_comp->y0, (OPJ_INT32)l_img_comp->factor);
if (l_h < 0) {
opj_event_msg(p_manager, EVT_ERROR,
"Size y of the decoded component image is incorrect (comp[%d].h=%d).\n",
it_comp, l_h);
return OPJ_FALSE;
}
l_img_comp->h = (OPJ_UINT32)l_h;
l_img_comp++;
}
opj_event_msg(p_manager, EVT_INFO, "Setting decoding area to %d,%d,%d,%d\n",
p_image->x0, p_image->y0, p_image->x1, p_image->y1);
return OPJ_TRUE;
}
opj_j2k_t* opj_j2k_create_decompress(void)
{
opj_j2k_t *l_j2k = (opj_j2k_t*) opj_calloc(1, sizeof(opj_j2k_t));
if (!l_j2k) {
return 00;
}
l_j2k->m_is_decoder = 1;
l_j2k->m_cp.m_is_decoder = 1;
/* in the absence of JP2 boxes, consider different bit depth / sign */
/* per component is allowed */
l_j2k->m_cp.allow_different_bit_depth_sign = 1;
#ifdef OPJ_DISABLE_TPSOT_FIX
l_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction_checked = 1;
#endif
l_j2k->m_specific_param.m_decoder.m_default_tcp = (opj_tcp_t*) opj_calloc(1,
sizeof(opj_tcp_t));
if (!l_j2k->m_specific_param.m_decoder.m_default_tcp) {
opj_j2k_destroy(l_j2k);
return 00;
}
l_j2k->m_specific_param.m_decoder.m_header_data = (OPJ_BYTE *) opj_calloc(1,
OPJ_J2K_DEFAULT_HEADER_SIZE);
if (! l_j2k->m_specific_param.m_decoder.m_header_data) {
opj_j2k_destroy(l_j2k);
return 00;
}
l_j2k->m_specific_param.m_decoder.m_header_data_size =
OPJ_J2K_DEFAULT_HEADER_SIZE;
l_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec = -1 ;
l_j2k->m_specific_param.m_decoder.m_last_sot_read_pos = 0 ;
/* codestream index creation */
l_j2k->cstr_index = opj_j2k_create_cstr_index();
if (!l_j2k->cstr_index) {
opj_j2k_destroy(l_j2k);
return 00;
}
/* validation list creation */
l_j2k->m_validation_list = opj_procedure_list_create();
if (! l_j2k->m_validation_list) {
opj_j2k_destroy(l_j2k);
return 00;
}
/* execution list creation */
l_j2k->m_procedure_list = opj_procedure_list_create();
if (! l_j2k->m_procedure_list) {
opj_j2k_destroy(l_j2k);
return 00;
}
l_j2k->m_tp = opj_thread_pool_create(opj_j2k_get_default_thread_count());
if (!l_j2k->m_tp) {
l_j2k->m_tp = opj_thread_pool_create(0);
}
if (!l_j2k->m_tp) {
opj_j2k_destroy(l_j2k);
return NULL;
}
return l_j2k;
}
static opj_codestream_index_t* opj_j2k_create_cstr_index(void)
{
opj_codestream_index_t* cstr_index = (opj_codestream_index_t*)
opj_calloc(1, sizeof(opj_codestream_index_t));
if (!cstr_index) {
return NULL;
}
cstr_index->maxmarknum = 100;
cstr_index->marknum = 0;
cstr_index->marker = (opj_marker_info_t*)
opj_calloc(cstr_index->maxmarknum, sizeof(opj_marker_info_t));
if (!cstr_index-> marker) {
opj_free(cstr_index);
return NULL;
}
cstr_index->tile_index = NULL;
return cstr_index;
}
static OPJ_UINT32 opj_j2k_get_SPCod_SPCoc_size(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no)
{
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_tccp_t *l_tccp = 00;
/* preconditions */
assert(p_j2k != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_tile_no];
l_tccp = &l_tcp->tccps[p_comp_no];
/* preconditions again */
assert(p_tile_no < (l_cp->tw * l_cp->th));
assert(p_comp_no < p_j2k->m_private_image->numcomps);
if (l_tccp->csty & J2K_CCP_CSTY_PRT) {
return 5 + l_tccp->numresolutions;
} else {
return 5;
}
}
static OPJ_BOOL opj_j2k_compare_SPCod_SPCoc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no)
{
OPJ_UINT32 i;
opj_cp_t *l_cp = NULL;
opj_tcp_t *l_tcp = NULL;
opj_tccp_t *l_tccp0 = NULL;
opj_tccp_t *l_tccp1 = NULL;
/* preconditions */
assert(p_j2k != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_tile_no];
l_tccp0 = &l_tcp->tccps[p_first_comp_no];
l_tccp1 = &l_tcp->tccps[p_second_comp_no];
if (l_tccp0->numresolutions != l_tccp1->numresolutions) {
return OPJ_FALSE;
}
if (l_tccp0->cblkw != l_tccp1->cblkw) {
return OPJ_FALSE;
}
if (l_tccp0->cblkh != l_tccp1->cblkh) {
return OPJ_FALSE;
}
if (l_tccp0->cblksty != l_tccp1->cblksty) {
return OPJ_FALSE;
}
if (l_tccp0->qmfbid != l_tccp1->qmfbid) {
return OPJ_FALSE;
}
if ((l_tccp0->csty & J2K_CCP_CSTY_PRT) != (l_tccp1->csty & J2K_CCP_CSTY_PRT)) {
return OPJ_FALSE;
}
for (i = 0U; i < l_tccp0->numresolutions; ++i) {
if (l_tccp0->prcw[i] != l_tccp1->prcw[i]) {
return OPJ_FALSE;
}
if (l_tccp0->prch[i] != l_tccp1->prch[i]) {
return OPJ_FALSE;
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_SPCod_SPCoc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_header_size,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 i;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_tccp_t *l_tccp = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_header_size != 00);
assert(p_manager != 00);
assert(p_data != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_tile_no];
l_tccp = &l_tcp->tccps[p_comp_no];
/* preconditions again */
assert(p_tile_no < (l_cp->tw * l_cp->th));
assert(p_comp_no < (p_j2k->m_private_image->numcomps));
if (*p_header_size < 5) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing SPCod SPCoc element\n");
return OPJ_FALSE;
}
opj_write_bytes(p_data, l_tccp->numresolutions - 1, 1); /* SPcoc (D) */
++p_data;
opj_write_bytes(p_data, l_tccp->cblkw - 2, 1); /* SPcoc (E) */
++p_data;
opj_write_bytes(p_data, l_tccp->cblkh - 2, 1); /* SPcoc (F) */
++p_data;
opj_write_bytes(p_data, l_tccp->cblksty,
1); /* SPcoc (G) */
++p_data;
opj_write_bytes(p_data, l_tccp->qmfbid,
1); /* SPcoc (H) */
++p_data;
*p_header_size = *p_header_size - 5;
if (l_tccp->csty & J2K_CCP_CSTY_PRT) {
if (*p_header_size < l_tccp->numresolutions) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing SPCod SPCoc element\n");
return OPJ_FALSE;
}
for (i = 0; i < l_tccp->numresolutions; ++i) {
opj_write_bytes(p_data, l_tccp->prcw[i] + (l_tccp->prch[i] << 4),
1); /* SPcoc (I_i) */
++p_data;
}
*p_header_size = *p_header_size - l_tccp->numresolutions;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_read_SPCod_SPCoc(opj_j2k_t *p_j2k,
OPJ_UINT32 compno,
OPJ_BYTE * p_header_data,
OPJ_UINT32 * p_header_size,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 i, l_tmp;
opj_cp_t *l_cp = NULL;
opj_tcp_t *l_tcp = NULL;
opj_tccp_t *l_tccp = NULL;
OPJ_BYTE * l_current_ptr = NULL;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_header_data != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
/* precondition again */
assert(compno < p_j2k->m_private_image->numcomps);
l_tccp = &l_tcp->tccps[compno];
l_current_ptr = p_header_data;
/* make sure room is sufficient */
if (*p_header_size < 5) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading SPCod SPCoc element\n");
return OPJ_FALSE;
}
opj_read_bytes(l_current_ptr, &l_tccp->numresolutions,
1); /* SPcox (D) */
++l_tccp->numresolutions; /* tccp->numresolutions = read() + 1 */
if (l_tccp->numresolutions > OPJ_J2K_MAXRLVLS) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid value for numresolutions : %d, max value is set in openjpeg.h at %d\n",
l_tccp->numresolutions, OPJ_J2K_MAXRLVLS);
return OPJ_FALSE;
}
++l_current_ptr;
/* If user wants to remove more resolutions than the codestream contains, return error */
if (l_cp->m_specific_param.m_dec.m_reduce >= l_tccp->numresolutions) {
opj_event_msg(p_manager, EVT_ERROR,
"Error decoding component %d.\nThe number of resolutions to remove is higher than the number "
"of resolutions of this component\nModify the cp_reduce parameter.\n\n",
compno);
p_j2k->m_specific_param.m_decoder.m_state |=
0x8000;/* FIXME J2K_DEC_STATE_ERR;*/
return OPJ_FALSE;
}
opj_read_bytes(l_current_ptr, &l_tccp->cblkw, 1); /* SPcoc (E) */
++l_current_ptr;
l_tccp->cblkw += 2;
opj_read_bytes(l_current_ptr, &l_tccp->cblkh, 1); /* SPcoc (F) */
++l_current_ptr;
l_tccp->cblkh += 2;
if ((l_tccp->cblkw > 10) || (l_tccp->cblkh > 10) ||
((l_tccp->cblkw + l_tccp->cblkh) > 12)) {
opj_event_msg(p_manager, EVT_ERROR,
"Error reading SPCod SPCoc element, Invalid cblkw/cblkh combination\n");
return OPJ_FALSE;
}
opj_read_bytes(l_current_ptr, &l_tccp->cblksty, 1); /* SPcoc (G) */
++l_current_ptr;
if (l_tccp->cblksty & 0xC0U) { /* 2 msb are reserved, assume we can't read */
opj_event_msg(p_manager, EVT_ERROR,
"Error reading SPCod SPCoc element, Invalid code-block style found\n");
return OPJ_FALSE;
}
opj_read_bytes(l_current_ptr, &l_tccp->qmfbid, 1); /* SPcoc (H) */
++l_current_ptr;
*p_header_size = *p_header_size - 5;
/* use custom precinct size ? */
if (l_tccp->csty & J2K_CCP_CSTY_PRT) {
if (*p_header_size < l_tccp->numresolutions) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading SPCod SPCoc element\n");
return OPJ_FALSE;
}
for (i = 0; i < l_tccp->numresolutions; ++i) {
opj_read_bytes(l_current_ptr, &l_tmp, 1); /* SPcoc (I_i) */
++l_current_ptr;
/* Precinct exponent 0 is only allowed for lowest resolution level (Table A.21) */
if ((i != 0) && (((l_tmp & 0xf) == 0) || ((l_tmp >> 4) == 0))) {
opj_event_msg(p_manager, EVT_ERROR, "Invalid precinct size\n");
return OPJ_FALSE;
}
l_tccp->prcw[i] = l_tmp & 0xf;
l_tccp->prch[i] = l_tmp >> 4;
}
*p_header_size = *p_header_size - l_tccp->numresolutions;
} else {
/* set default size for the precinct width and height */
for (i = 0; i < l_tccp->numresolutions; ++i) {
l_tccp->prcw[i] = 15;
l_tccp->prch[i] = 15;
}
}
#ifdef WIP_REMOVE_MSD
/* INDEX >> */
if (p_j2k->cstr_info && compno == 0) {
OPJ_UINT32 l_data_size = l_tccp->numresolutions * sizeof(OPJ_UINT32);
p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].cblkh =
l_tccp->cblkh;
p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].cblkw =
l_tccp->cblkw;
p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].numresolutions
= l_tccp->numresolutions;
p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].cblksty =
l_tccp->cblksty;
p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].qmfbid =
l_tccp->qmfbid;
memcpy(p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].pdx, l_tccp->prcw,
l_data_size);
memcpy(p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].pdy, l_tccp->prch,
l_data_size);
}
/* << INDEX */
#endif
return OPJ_TRUE;
}
static void opj_j2k_copy_tile_component_parameters(opj_j2k_t *p_j2k)
{
/* loop */
OPJ_UINT32 i;
opj_cp_t *l_cp = NULL;
opj_tcp_t *l_tcp = NULL;
opj_tccp_t *l_ref_tccp = NULL, *l_copied_tccp = NULL;
OPJ_UINT32 l_prc_size;
/* preconditions */
assert(p_j2k != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH)
?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
l_ref_tccp = &l_tcp->tccps[0];
l_copied_tccp = l_ref_tccp + 1;
l_prc_size = l_ref_tccp->numresolutions * (OPJ_UINT32)sizeof(OPJ_UINT32);
for (i = 1; i < p_j2k->m_private_image->numcomps; ++i) {
l_copied_tccp->numresolutions = l_ref_tccp->numresolutions;
l_copied_tccp->cblkw = l_ref_tccp->cblkw;
l_copied_tccp->cblkh = l_ref_tccp->cblkh;
l_copied_tccp->cblksty = l_ref_tccp->cblksty;
l_copied_tccp->qmfbid = l_ref_tccp->qmfbid;
memcpy(l_copied_tccp->prcw, l_ref_tccp->prcw, l_prc_size);
memcpy(l_copied_tccp->prch, l_ref_tccp->prch, l_prc_size);
++l_copied_tccp;
}
}
static OPJ_UINT32 opj_j2k_get_SQcd_SQcc_size(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no)
{
OPJ_UINT32 l_num_bands;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_tccp_t *l_tccp = 00;
/* preconditions */
assert(p_j2k != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_tile_no];
l_tccp = &l_tcp->tccps[p_comp_no];
/* preconditions again */
assert(p_tile_no < l_cp->tw * l_cp->th);
assert(p_comp_no < p_j2k->m_private_image->numcomps);
l_num_bands = (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 1 :
(l_tccp->numresolutions * 3 - 2);
if (l_tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) {
return 1 + l_num_bands;
} else {
return 1 + 2 * l_num_bands;
}
}
static OPJ_BOOL opj_j2k_compare_SQcd_SQcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no)
{
opj_cp_t *l_cp = NULL;
opj_tcp_t *l_tcp = NULL;
opj_tccp_t *l_tccp0 = NULL;
opj_tccp_t *l_tccp1 = NULL;
OPJ_UINT32 l_band_no, l_num_bands;
/* preconditions */
assert(p_j2k != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_tile_no];
l_tccp0 = &l_tcp->tccps[p_first_comp_no];
l_tccp1 = &l_tcp->tccps[p_second_comp_no];
if (l_tccp0->qntsty != l_tccp1->qntsty) {
return OPJ_FALSE;
}
if (l_tccp0->numgbits != l_tccp1->numgbits) {
return OPJ_FALSE;
}
if (l_tccp0->qntsty == J2K_CCP_QNTSTY_SIQNT) {
l_num_bands = 1U;
} else {
l_num_bands = l_tccp0->numresolutions * 3U - 2U;
if (l_num_bands != (l_tccp1->numresolutions * 3U - 2U)) {
return OPJ_FALSE;
}
}
for (l_band_no = 0; l_band_no < l_num_bands; ++l_band_no) {
if (l_tccp0->stepsizes[l_band_no].expn != l_tccp1->stepsizes[l_band_no].expn) {
return OPJ_FALSE;
}
}
if (l_tccp0->qntsty != J2K_CCP_QNTSTY_NOQNT) {
for (l_band_no = 0; l_band_no < l_num_bands; ++l_band_no) {
if (l_tccp0->stepsizes[l_band_no].mant != l_tccp1->stepsizes[l_band_no].mant) {
return OPJ_FALSE;
}
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_SQcd_SQcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_header_size,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 l_header_size;
OPJ_UINT32 l_band_no, l_num_bands;
OPJ_UINT32 l_expn, l_mant;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_tccp_t *l_tccp = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_header_size != 00);
assert(p_manager != 00);
assert(p_data != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_tile_no];
l_tccp = &l_tcp->tccps[p_comp_no];
/* preconditions again */
assert(p_tile_no < l_cp->tw * l_cp->th);
assert(p_comp_no < p_j2k->m_private_image->numcomps);
l_num_bands = (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 1 :
(l_tccp->numresolutions * 3 - 2);
if (l_tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) {
l_header_size = 1 + l_num_bands;
if (*p_header_size < l_header_size) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing SQcd SQcc element\n");
return OPJ_FALSE;
}
opj_write_bytes(p_data, l_tccp->qntsty + (l_tccp->numgbits << 5),
1); /* Sqcx */
++p_data;
for (l_band_no = 0; l_band_no < l_num_bands; ++l_band_no) {
l_expn = (OPJ_UINT32)l_tccp->stepsizes[l_band_no].expn;
opj_write_bytes(p_data, l_expn << 3, 1); /* SPqcx_i */
++p_data;
}
} else {
l_header_size = 1 + 2 * l_num_bands;
if (*p_header_size < l_header_size) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing SQcd SQcc element\n");
return OPJ_FALSE;
}
opj_write_bytes(p_data, l_tccp->qntsty + (l_tccp->numgbits << 5),
1); /* Sqcx */
++p_data;
for (l_band_no = 0; l_band_no < l_num_bands; ++l_band_no) {
l_expn = (OPJ_UINT32)l_tccp->stepsizes[l_band_no].expn;
l_mant = (OPJ_UINT32)l_tccp->stepsizes[l_band_no].mant;
opj_write_bytes(p_data, (l_expn << 11) + l_mant, 2); /* SPqcx_i */
p_data += 2;
}
}
*p_header_size = *p_header_size - l_header_size;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_read_SQcd_SQcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
OPJ_BYTE* p_header_data,
OPJ_UINT32 * p_header_size,
opj_event_mgr_t * p_manager
)
{
/* loop*/
OPJ_UINT32 l_band_no;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_tccp_t *l_tccp = 00;
OPJ_BYTE * l_current_ptr = 00;
OPJ_UINT32 l_tmp, l_num_band;
/* preconditions*/
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_header_data != 00);
l_cp = &(p_j2k->m_cp);
/* come from tile part header or main header ?*/
l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH)
?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
/* precondition again*/
assert(p_comp_no < p_j2k->m_private_image->numcomps);
l_tccp = &l_tcp->tccps[p_comp_no];
l_current_ptr = p_header_data;
if (*p_header_size < 1) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading SQcd or SQcc element\n");
return OPJ_FALSE;
}
*p_header_size -= 1;
opj_read_bytes(l_current_ptr, &l_tmp, 1); /* Sqcx */
++l_current_ptr;
l_tccp->qntsty = l_tmp & 0x1f;
l_tccp->numgbits = l_tmp >> 5;
if (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) {
l_num_band = 1;
} else {
l_num_band = (l_tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) ?
(*p_header_size) :
(*p_header_size) / 2;
if (l_num_band > OPJ_J2K_MAXBANDS) {
opj_event_msg(p_manager, EVT_WARNING,
"While reading CCP_QNTSTY element inside QCD or QCC marker segment, "
"number of subbands (%d) is greater to OPJ_J2K_MAXBANDS (%d). So we limit the number of elements stored to "
"OPJ_J2K_MAXBANDS (%d) and skip the rest. \n", l_num_band, OPJ_J2K_MAXBANDS,
OPJ_J2K_MAXBANDS);
/*return OPJ_FALSE;*/
}
}
#ifdef USE_JPWL
if (l_cp->correct) {
/* if JPWL is on, we check whether there are too many subbands */
if (/*(l_num_band < 0) ||*/ (l_num_band >= OPJ_J2K_MAXBANDS)) {
opj_event_msg(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
"JPWL: bad number of subbands in Sqcx (%d)\n",
l_num_band);
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
/* we try to correct */
l_num_band = 1;
opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust them\n"
"- setting number of bands to %d => HYPOTHESIS!!!\n",
l_num_band);
};
};
#endif /* USE_JPWL */
if (l_tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) {
for (l_band_no = 0; l_band_no < l_num_band; l_band_no++) {
opj_read_bytes(l_current_ptr, &l_tmp, 1); /* SPqcx_i */
++l_current_ptr;
if (l_band_no < OPJ_J2K_MAXBANDS) {
l_tccp->stepsizes[l_band_no].expn = (OPJ_INT32)(l_tmp >> 3);
l_tccp->stepsizes[l_band_no].mant = 0;
}
}
*p_header_size = *p_header_size - l_num_band;
} else {
for (l_band_no = 0; l_band_no < l_num_band; l_band_no++) {
opj_read_bytes(l_current_ptr, &l_tmp, 2); /* SPqcx_i */
l_current_ptr += 2;
if (l_band_no < OPJ_J2K_MAXBANDS) {
l_tccp->stepsizes[l_band_no].expn = (OPJ_INT32)(l_tmp >> 11);
l_tccp->stepsizes[l_band_no].mant = l_tmp & 0x7ff;
}
}
*p_header_size = *p_header_size - 2 * l_num_band;
}
/* Add Antonin : if scalar_derived -> compute other stepsizes */
if (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) {
for (l_band_no = 1; l_band_no < OPJ_J2K_MAXBANDS; l_band_no++) {
l_tccp->stepsizes[l_band_no].expn =
((OPJ_INT32)(l_tccp->stepsizes[0].expn) - (OPJ_INT32)((l_band_no - 1) / 3) > 0)
?
(OPJ_INT32)(l_tccp->stepsizes[0].expn) - (OPJ_INT32)((l_band_no - 1) / 3) : 0;
l_tccp->stepsizes[l_band_no].mant = l_tccp->stepsizes[0].mant;
}
}
return OPJ_TRUE;
}
static void opj_j2k_copy_tile_quantization_parameters(opj_j2k_t *p_j2k)
{
OPJ_UINT32 i;
opj_cp_t *l_cp = NULL;
opj_tcp_t *l_tcp = NULL;
opj_tccp_t *l_ref_tccp = NULL;
opj_tccp_t *l_copied_tccp = NULL;
OPJ_UINT32 l_size;
/* preconditions */
assert(p_j2k != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH ?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
l_ref_tccp = &l_tcp->tccps[0];
l_copied_tccp = l_ref_tccp + 1;
l_size = OPJ_J2K_MAXBANDS * sizeof(opj_stepsize_t);
for (i = 1; i < p_j2k->m_private_image->numcomps; ++i) {
l_copied_tccp->qntsty = l_ref_tccp->qntsty;
l_copied_tccp->numgbits = l_ref_tccp->numgbits;
memcpy(l_copied_tccp->stepsizes, l_ref_tccp->stepsizes, l_size);
++l_copied_tccp;
}
}
static void opj_j2k_dump_tile_info(opj_tcp_t * l_default_tile,
OPJ_INT32 numcomps, FILE* out_stream)
{
if (l_default_tile) {
OPJ_INT32 compno;
fprintf(out_stream, "\t default tile {\n");
fprintf(out_stream, "\t\t csty=%#x\n", l_default_tile->csty);
fprintf(out_stream, "\t\t prg=%#x\n", l_default_tile->prg);
fprintf(out_stream, "\t\t numlayers=%d\n", l_default_tile->numlayers);
fprintf(out_stream, "\t\t mct=%x\n", l_default_tile->mct);
for (compno = 0; compno < numcomps; compno++) {
opj_tccp_t *l_tccp = &(l_default_tile->tccps[compno]);
OPJ_UINT32 resno;
OPJ_INT32 bandno, numbands;
/* coding style*/
fprintf(out_stream, "\t\t comp %d {\n", compno);
fprintf(out_stream, "\t\t\t csty=%#x\n", l_tccp->csty);
fprintf(out_stream, "\t\t\t numresolutions=%d\n", l_tccp->numresolutions);
fprintf(out_stream, "\t\t\t cblkw=2^%d\n", l_tccp->cblkw);
fprintf(out_stream, "\t\t\t cblkh=2^%d\n", l_tccp->cblkh);
fprintf(out_stream, "\t\t\t cblksty=%#x\n", l_tccp->cblksty);
fprintf(out_stream, "\t\t\t qmfbid=%d\n", l_tccp->qmfbid);
fprintf(out_stream, "\t\t\t preccintsize (w,h)=");
for (resno = 0; resno < l_tccp->numresolutions; resno++) {
fprintf(out_stream, "(%d,%d) ", l_tccp->prcw[resno], l_tccp->prch[resno]);
}
fprintf(out_stream, "\n");
/* quantization style*/
fprintf(out_stream, "\t\t\t qntsty=%d\n", l_tccp->qntsty);
fprintf(out_stream, "\t\t\t numgbits=%d\n", l_tccp->numgbits);
fprintf(out_stream, "\t\t\t stepsizes (m,e)=");
numbands = (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 1 :
(OPJ_INT32)l_tccp->numresolutions * 3 - 2;
for (bandno = 0; bandno < numbands; bandno++) {
fprintf(out_stream, "(%d,%d) ", l_tccp->stepsizes[bandno].mant,
l_tccp->stepsizes[bandno].expn);
}
fprintf(out_stream, "\n");
/* RGN value*/
fprintf(out_stream, "\t\t\t roishift=%d\n", l_tccp->roishift);
fprintf(out_stream, "\t\t }\n");
} /*end of component of default tile*/
fprintf(out_stream, "\t }\n"); /*end of default tile*/
}
}
void j2k_dump(opj_j2k_t* p_j2k, OPJ_INT32 flag, FILE* out_stream)
{
/* Check if the flag is compatible with j2k file*/
if ((flag & OPJ_JP2_INFO) || (flag & OPJ_JP2_IND)) {
fprintf(out_stream, "Wrong flag\n");
return;
}
/* Dump the image_header */
if (flag & OPJ_IMG_INFO) {
if (p_j2k->m_private_image) {
j2k_dump_image_header(p_j2k->m_private_image, 0, out_stream);
}
}
/* Dump the codestream info from main header */
if (flag & OPJ_J2K_MH_INFO) {
if (p_j2k->m_private_image) {
opj_j2k_dump_MH_info(p_j2k, out_stream);
}
}
/* Dump all tile/codestream info */
if (flag & OPJ_J2K_TCH_INFO) {
OPJ_UINT32 l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
OPJ_UINT32 i;
opj_tcp_t * l_tcp = p_j2k->m_cp.tcps;
if (p_j2k->m_private_image) {
for (i = 0; i < l_nb_tiles; ++i) {
opj_j2k_dump_tile_info(l_tcp, (OPJ_INT32)p_j2k->m_private_image->numcomps,
out_stream);
++l_tcp;
}
}
}
/* Dump the codestream info of the current tile */
if (flag & OPJ_J2K_TH_INFO) {
}
/* Dump the codestream index from main header */
if (flag & OPJ_J2K_MH_IND) {
opj_j2k_dump_MH_index(p_j2k, out_stream);
}
/* Dump the codestream index of the current tile */
if (flag & OPJ_J2K_TH_IND) {
}
}
static void opj_j2k_dump_MH_index(opj_j2k_t* p_j2k, FILE* out_stream)
{
opj_codestream_index_t* cstr_index = p_j2k->cstr_index;
OPJ_UINT32 it_marker, it_tile, it_tile_part;
fprintf(out_stream, "Codestream index from main header: {\n");
fprintf(out_stream, "\t Main header start position=%" PRIi64 "\n"
"\t Main header end position=%" PRIi64 "\n",
cstr_index->main_head_start, cstr_index->main_head_end);
fprintf(out_stream, "\t Marker list: {\n");
if (cstr_index->marker) {
for (it_marker = 0; it_marker < cstr_index->marknum ; it_marker++) {
fprintf(out_stream, "\t\t type=%#x, pos=%" PRIi64 ", len=%d\n",
cstr_index->marker[it_marker].type,
cstr_index->marker[it_marker].pos,
cstr_index->marker[it_marker].len);
}
}
fprintf(out_stream, "\t }\n");
if (cstr_index->tile_index) {
/* Simple test to avoid to write empty information*/
OPJ_UINT32 l_acc_nb_of_tile_part = 0;
for (it_tile = 0; it_tile < cstr_index->nb_of_tiles ; it_tile++) {
l_acc_nb_of_tile_part += cstr_index->tile_index[it_tile].nb_tps;
}
if (l_acc_nb_of_tile_part) {
fprintf(out_stream, "\t Tile index: {\n");
for (it_tile = 0; it_tile < cstr_index->nb_of_tiles ; it_tile++) {
OPJ_UINT32 nb_of_tile_part = cstr_index->tile_index[it_tile].nb_tps;
fprintf(out_stream, "\t\t nb of tile-part in tile [%d]=%d\n", it_tile,
nb_of_tile_part);
if (cstr_index->tile_index[it_tile].tp_index) {
for (it_tile_part = 0; it_tile_part < nb_of_tile_part; it_tile_part++) {
fprintf(out_stream, "\t\t\t tile-part[%d]: star_pos=%" PRIi64 ", end_header=%"
PRIi64 ", end_pos=%" PRIi64 ".\n",
it_tile_part,
cstr_index->tile_index[it_tile].tp_index[it_tile_part].start_pos,
cstr_index->tile_index[it_tile].tp_index[it_tile_part].end_header,
cstr_index->tile_index[it_tile].tp_index[it_tile_part].end_pos);
}
}
if (cstr_index->tile_index[it_tile].marker) {
for (it_marker = 0; it_marker < cstr_index->tile_index[it_tile].marknum ;
it_marker++) {
fprintf(out_stream, "\t\t type=%#x, pos=%" PRIi64 ", len=%d\n",
cstr_index->tile_index[it_tile].marker[it_marker].type,
cstr_index->tile_index[it_tile].marker[it_marker].pos,
cstr_index->tile_index[it_tile].marker[it_marker].len);
}
}
}
fprintf(out_stream, "\t }\n");
}
}
fprintf(out_stream, "}\n");
}
static void opj_j2k_dump_MH_info(opj_j2k_t* p_j2k, FILE* out_stream)
{
fprintf(out_stream, "Codestream info from main header: {\n");
fprintf(out_stream, "\t tx0=%d, ty0=%d\n", p_j2k->m_cp.tx0, p_j2k->m_cp.ty0);
fprintf(out_stream, "\t tdx=%d, tdy=%d\n", p_j2k->m_cp.tdx, p_j2k->m_cp.tdy);
fprintf(out_stream, "\t tw=%d, th=%d\n", p_j2k->m_cp.tw, p_j2k->m_cp.th);
opj_j2k_dump_tile_info(p_j2k->m_specific_param.m_decoder.m_default_tcp,
(OPJ_INT32)p_j2k->m_private_image->numcomps, out_stream);
fprintf(out_stream, "}\n");
}
void j2k_dump_image_header(opj_image_t* img_header, OPJ_BOOL dev_dump_flag,
FILE* out_stream)
{
char tab[2];
if (dev_dump_flag) {
fprintf(stdout, "[DEV] Dump an image_header struct {\n");
tab[0] = '\0';
} else {
fprintf(out_stream, "Image info {\n");
tab[0] = '\t';
tab[1] = '\0';
}
fprintf(out_stream, "%s x0=%d, y0=%d\n", tab, img_header->x0, img_header->y0);
fprintf(out_stream, "%s x1=%d, y1=%d\n", tab, img_header->x1,
img_header->y1);
fprintf(out_stream, "%s numcomps=%d\n", tab, img_header->numcomps);
if (img_header->comps) {
OPJ_UINT32 compno;
for (compno = 0; compno < img_header->numcomps; compno++) {
fprintf(out_stream, "%s\t component %d {\n", tab, compno);
j2k_dump_image_comp_header(&(img_header->comps[compno]), dev_dump_flag,
out_stream);
fprintf(out_stream, "%s}\n", tab);
}
}
fprintf(out_stream, "}\n");
}
void j2k_dump_image_comp_header(opj_image_comp_t* comp_header,
OPJ_BOOL dev_dump_flag, FILE* out_stream)
{
char tab[3];
if (dev_dump_flag) {
fprintf(stdout, "[DEV] Dump an image_comp_header struct {\n");
tab[0] = '\0';
} else {
tab[0] = '\t';
tab[1] = '\t';
tab[2] = '\0';
}
fprintf(out_stream, "%s dx=%d, dy=%d\n", tab, comp_header->dx, comp_header->dy);
fprintf(out_stream, "%s prec=%d\n", tab, comp_header->prec);
fprintf(out_stream, "%s sgnd=%d\n", tab, comp_header->sgnd);
if (dev_dump_flag) {
fprintf(out_stream, "}\n");
}
}
opj_codestream_info_v2_t* j2k_get_cstr_info(opj_j2k_t* p_j2k)
{
OPJ_UINT32 compno;
OPJ_UINT32 numcomps = p_j2k->m_private_image->numcomps;
opj_tcp_t *l_default_tile;
opj_codestream_info_v2_t* cstr_info = (opj_codestream_info_v2_t*) opj_calloc(1,
sizeof(opj_codestream_info_v2_t));
if (!cstr_info) {
return NULL;
}
cstr_info->nbcomps = p_j2k->m_private_image->numcomps;
cstr_info->tx0 = p_j2k->m_cp.tx0;
cstr_info->ty0 = p_j2k->m_cp.ty0;
cstr_info->tdx = p_j2k->m_cp.tdx;
cstr_info->tdy = p_j2k->m_cp.tdy;
cstr_info->tw = p_j2k->m_cp.tw;
cstr_info->th = p_j2k->m_cp.th;
cstr_info->tile_info = NULL; /* Not fill from the main header*/
l_default_tile = p_j2k->m_specific_param.m_decoder.m_default_tcp;
cstr_info->m_default_tile_info.csty = l_default_tile->csty;
cstr_info->m_default_tile_info.prg = l_default_tile->prg;
cstr_info->m_default_tile_info.numlayers = l_default_tile->numlayers;
cstr_info->m_default_tile_info.mct = l_default_tile->mct;
cstr_info->m_default_tile_info.tccp_info = (opj_tccp_info_t*) opj_calloc(
cstr_info->nbcomps, sizeof(opj_tccp_info_t));
if (!cstr_info->m_default_tile_info.tccp_info) {
opj_destroy_cstr_info(&cstr_info);
return NULL;
}
for (compno = 0; compno < numcomps; compno++) {
opj_tccp_t *l_tccp = &(l_default_tile->tccps[compno]);
opj_tccp_info_t *l_tccp_info = &
(cstr_info->m_default_tile_info.tccp_info[compno]);
OPJ_INT32 bandno, numbands;
/* coding style*/
l_tccp_info->csty = l_tccp->csty;
l_tccp_info->numresolutions = l_tccp->numresolutions;
l_tccp_info->cblkw = l_tccp->cblkw;
l_tccp_info->cblkh = l_tccp->cblkh;
l_tccp_info->cblksty = l_tccp->cblksty;
l_tccp_info->qmfbid = l_tccp->qmfbid;
if (l_tccp->numresolutions < OPJ_J2K_MAXRLVLS) {
memcpy(l_tccp_info->prch, l_tccp->prch, l_tccp->numresolutions);
memcpy(l_tccp_info->prcw, l_tccp->prcw, l_tccp->numresolutions);
}
/* quantization style*/
l_tccp_info->qntsty = l_tccp->qntsty;
l_tccp_info->numgbits = l_tccp->numgbits;
numbands = (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 1 :
(OPJ_INT32)l_tccp->numresolutions * 3 - 2;
if (numbands < OPJ_J2K_MAXBANDS) {
for (bandno = 0; bandno < numbands; bandno++) {
l_tccp_info->stepsizes_mant[bandno] = (OPJ_UINT32)
l_tccp->stepsizes[bandno].mant;
l_tccp_info->stepsizes_expn[bandno] = (OPJ_UINT32)
l_tccp->stepsizes[bandno].expn;
}
}
/* RGN value*/
l_tccp_info->roishift = l_tccp->roishift;
}
return cstr_info;
}
opj_codestream_index_t* j2k_get_cstr_index(opj_j2k_t* p_j2k)
{
opj_codestream_index_t* l_cstr_index = (opj_codestream_index_t*)
opj_calloc(1, sizeof(opj_codestream_index_t));
if (!l_cstr_index) {
return NULL;
}
l_cstr_index->main_head_start = p_j2k->cstr_index->main_head_start;
l_cstr_index->main_head_end = p_j2k->cstr_index->main_head_end;
l_cstr_index->codestream_size = p_j2k->cstr_index->codestream_size;
l_cstr_index->marknum = p_j2k->cstr_index->marknum;
l_cstr_index->marker = (opj_marker_info_t*)opj_malloc(l_cstr_index->marknum *
sizeof(opj_marker_info_t));
if (!l_cstr_index->marker) {
opj_free(l_cstr_index);
return NULL;
}
if (p_j2k->cstr_index->marker) {
memcpy(l_cstr_index->marker, p_j2k->cstr_index->marker,
l_cstr_index->marknum * sizeof(opj_marker_info_t));
} else {
opj_free(l_cstr_index->marker);
l_cstr_index->marker = NULL;
}
l_cstr_index->nb_of_tiles = p_j2k->cstr_index->nb_of_tiles;
l_cstr_index->tile_index = (opj_tile_index_t*)opj_calloc(
l_cstr_index->nb_of_tiles, sizeof(opj_tile_index_t));
if (!l_cstr_index->tile_index) {
opj_free(l_cstr_index->marker);
opj_free(l_cstr_index);
return NULL;
}
if (!p_j2k->cstr_index->tile_index) {
opj_free(l_cstr_index->tile_index);
l_cstr_index->tile_index = NULL;
} else {
OPJ_UINT32 it_tile = 0;
for (it_tile = 0; it_tile < l_cstr_index->nb_of_tiles; it_tile++) {
/* Tile Marker*/
l_cstr_index->tile_index[it_tile].marknum =
p_j2k->cstr_index->tile_index[it_tile].marknum;
l_cstr_index->tile_index[it_tile].marker =
(opj_marker_info_t*)opj_malloc(l_cstr_index->tile_index[it_tile].marknum *
sizeof(opj_marker_info_t));
if (!l_cstr_index->tile_index[it_tile].marker) {
OPJ_UINT32 it_tile_free;
for (it_tile_free = 0; it_tile_free < it_tile; it_tile_free++) {
opj_free(l_cstr_index->tile_index[it_tile_free].marker);
}
opj_free(l_cstr_index->tile_index);
opj_free(l_cstr_index->marker);
opj_free(l_cstr_index);
return NULL;
}
if (p_j2k->cstr_index->tile_index[it_tile].marker)
memcpy(l_cstr_index->tile_index[it_tile].marker,
p_j2k->cstr_index->tile_index[it_tile].marker,
l_cstr_index->tile_index[it_tile].marknum * sizeof(opj_marker_info_t));
else {
opj_free(l_cstr_index->tile_index[it_tile].marker);
l_cstr_index->tile_index[it_tile].marker = NULL;
}
/* Tile part index*/
l_cstr_index->tile_index[it_tile].nb_tps =
p_j2k->cstr_index->tile_index[it_tile].nb_tps;
l_cstr_index->tile_index[it_tile].tp_index =
(opj_tp_index_t*)opj_malloc(l_cstr_index->tile_index[it_tile].nb_tps * sizeof(
opj_tp_index_t));
if (!l_cstr_index->tile_index[it_tile].tp_index) {
OPJ_UINT32 it_tile_free;
for (it_tile_free = 0; it_tile_free < it_tile; it_tile_free++) {
opj_free(l_cstr_index->tile_index[it_tile_free].marker);
opj_free(l_cstr_index->tile_index[it_tile_free].tp_index);
}
opj_free(l_cstr_index->tile_index);
opj_free(l_cstr_index->marker);
opj_free(l_cstr_index);
return NULL;
}
if (p_j2k->cstr_index->tile_index[it_tile].tp_index) {
memcpy(l_cstr_index->tile_index[it_tile].tp_index,
p_j2k->cstr_index->tile_index[it_tile].tp_index,
l_cstr_index->tile_index[it_tile].nb_tps * sizeof(opj_tp_index_t));
} else {
opj_free(l_cstr_index->tile_index[it_tile].tp_index);
l_cstr_index->tile_index[it_tile].tp_index = NULL;
}
/* Packet index (NOT USED)*/
l_cstr_index->tile_index[it_tile].nb_packet = 0;
l_cstr_index->tile_index[it_tile].packet_index = NULL;
}
}
return l_cstr_index;
}
static OPJ_BOOL opj_j2k_allocate_tile_element_cstr_index(opj_j2k_t *p_j2k)
{
OPJ_UINT32 it_tile = 0;
p_j2k->cstr_index->nb_of_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th;
p_j2k->cstr_index->tile_index = (opj_tile_index_t*)opj_calloc(
p_j2k->cstr_index->nb_of_tiles, sizeof(opj_tile_index_t));
if (!p_j2k->cstr_index->tile_index) {
return OPJ_FALSE;
}
for (it_tile = 0; it_tile < p_j2k->cstr_index->nb_of_tiles; it_tile++) {
p_j2k->cstr_index->tile_index[it_tile].maxmarknum = 100;
p_j2k->cstr_index->tile_index[it_tile].marknum = 0;
p_j2k->cstr_index->tile_index[it_tile].marker = (opj_marker_info_t*)
opj_calloc(p_j2k->cstr_index->tile_index[it_tile].maxmarknum,
sizeof(opj_marker_info_t));
if (!p_j2k->cstr_index->tile_index[it_tile].marker) {
return OPJ_FALSE;
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_decode_tiles(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_BOOL l_go_on = OPJ_TRUE;
OPJ_UINT32 l_current_tile_no;
OPJ_UINT32 l_data_size, l_max_data_size;
OPJ_INT32 l_tile_x0, l_tile_y0, l_tile_x1, l_tile_y1;
OPJ_UINT32 l_nb_comps;
OPJ_BYTE * l_current_data;
OPJ_UINT32 nr_tiles = 0;
/* Particular case for whole single tile decoding */
/* We can avoid allocating intermediate tile buffers */
if (p_j2k->m_cp.tw == 1 && p_j2k->m_cp.th == 1 &&
p_j2k->m_cp.tx0 == 0 && p_j2k->m_cp.ty0 == 0 &&
p_j2k->m_output_image->x0 == 0 &&
p_j2k->m_output_image->y0 == 0 &&
p_j2k->m_output_image->x1 == p_j2k->m_cp.tdx &&
p_j2k->m_output_image->y1 == p_j2k->m_cp.tdy &&
p_j2k->m_output_image->comps[0].factor == 0) {
OPJ_UINT32 i;
if (! opj_j2k_read_tile_header(p_j2k,
&l_current_tile_no,
&l_data_size,
&l_tile_x0, &l_tile_y0,
&l_tile_x1, &l_tile_y1,
&l_nb_comps,
&l_go_on,
p_stream,
p_manager)) {
return OPJ_FALSE;
}
if (! opj_j2k_decode_tile(p_j2k, l_current_tile_no, NULL, 0,
p_stream, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Failed to decode tile 1/1\n");
return OPJ_FALSE;
}
/* Transfer TCD data to output image data */
for (i = 0; i < p_j2k->m_output_image->numcomps; i++) {
opj_image_data_free(p_j2k->m_output_image->comps[i].data);
p_j2k->m_output_image->comps[i].data =
p_j2k->m_tcd->tcd_image->tiles->comps[i].data;
p_j2k->m_output_image->comps[i].resno_decoded =
p_j2k->m_tcd->image->comps[i].resno_decoded;
p_j2k->m_tcd->tcd_image->tiles->comps[i].data = NULL;
}
return OPJ_TRUE;
}
l_current_data = (OPJ_BYTE*)opj_malloc(1000);
if (! l_current_data) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to decode tiles\n");
return OPJ_FALSE;
}
l_max_data_size = 1000;
for (;;) {
if (! opj_j2k_read_tile_header(p_j2k,
&l_current_tile_no,
&l_data_size,
&l_tile_x0, &l_tile_y0,
&l_tile_x1, &l_tile_y1,
&l_nb_comps,
&l_go_on,
p_stream,
p_manager)) {
opj_free(l_current_data);
return OPJ_FALSE;
}
if (! l_go_on) {
break;
}
if (l_data_size > l_max_data_size) {
OPJ_BYTE *l_new_current_data = (OPJ_BYTE *) opj_realloc(l_current_data,
l_data_size);
if (! l_new_current_data) {
opj_free(l_current_data);
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to decode tile %d/%d\n",
l_current_tile_no + 1, p_j2k->m_cp.th * p_j2k->m_cp.tw);
return OPJ_FALSE;
}
l_current_data = l_new_current_data;
l_max_data_size = l_data_size;
}
if (! opj_j2k_decode_tile(p_j2k, l_current_tile_no, l_current_data, l_data_size,
p_stream, p_manager)) {
opj_free(l_current_data);
opj_event_msg(p_manager, EVT_ERROR, "Failed to decode tile %d/%d\n",
l_current_tile_no + 1, p_j2k->m_cp.th * p_j2k->m_cp.tw);
return OPJ_FALSE;
}
opj_event_msg(p_manager, EVT_INFO, "Tile %d/%d has been decoded.\n",
l_current_tile_no + 1, p_j2k->m_cp.th * p_j2k->m_cp.tw);
if (! opj_j2k_update_image_data(p_j2k->m_tcd, l_current_data,
p_j2k->m_output_image)) {
opj_free(l_current_data);
return OPJ_FALSE;
}
opj_event_msg(p_manager, EVT_INFO,
"Image data has been updated with tile %d.\n\n", l_current_tile_no + 1);
if (opj_stream_get_number_byte_left(p_stream) == 0
&& p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_NEOC) {
break;
}
if (++nr_tiles == p_j2k->m_cp.th * p_j2k->m_cp.tw) {
break;
}
}
opj_free(l_current_data);
return OPJ_TRUE;
}
/**
* Sets up the procedures to do on decoding data. Developpers wanting to extend the library can add their own reading procedures.
*/
static OPJ_BOOL opj_j2k_setup_decoding(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager)
{
/* preconditions*/
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_decode_tiles, p_manager)) {
return OPJ_FALSE;
}
/* DEVELOPER CORNER, add your custom procedures */
return OPJ_TRUE;
}
/*
* Read and decode one tile.
*/
static OPJ_BOOL opj_j2k_decode_one_tile(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_BOOL l_go_on = OPJ_TRUE;
OPJ_UINT32 l_current_tile_no;
OPJ_UINT32 l_tile_no_to_dec;
OPJ_UINT32 l_data_size, l_max_data_size;
OPJ_INT32 l_tile_x0, l_tile_y0, l_tile_x1, l_tile_y1;
OPJ_UINT32 l_nb_comps;
OPJ_BYTE * l_current_data;
OPJ_UINT32 l_nb_tiles;
OPJ_UINT32 i;
l_current_data = (OPJ_BYTE*)opj_malloc(1000);
if (! l_current_data) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to decode one tile\n");
return OPJ_FALSE;
}
l_max_data_size = 1000;
/*Allocate and initialize some elements of codestrem index if not already done*/
if (!p_j2k->cstr_index->tile_index) {
if (!opj_j2k_allocate_tile_element_cstr_index(p_j2k)) {
opj_free(l_current_data);
return OPJ_FALSE;
}
}
/* Move into the codestream to the first SOT used to decode the desired tile */
l_tile_no_to_dec = (OPJ_UINT32)
p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec;
if (p_j2k->cstr_index->tile_index)
if (p_j2k->cstr_index->tile_index->tp_index) {
if (! p_j2k->cstr_index->tile_index[l_tile_no_to_dec].nb_tps) {
/* the index for this tile has not been built,
* so move to the last SOT read */
if (!(opj_stream_read_seek(p_stream,
p_j2k->m_specific_param.m_decoder.m_last_sot_read_pos + 2, p_manager))) {
opj_event_msg(p_manager, EVT_ERROR, "Problem with seek function\n");
opj_free(l_current_data);
return OPJ_FALSE;
}
} else {
if (!(opj_stream_read_seek(p_stream,
p_j2k->cstr_index->tile_index[l_tile_no_to_dec].tp_index[0].start_pos + 2,
p_manager))) {
opj_event_msg(p_manager, EVT_ERROR, "Problem with seek function\n");
opj_free(l_current_data);
return OPJ_FALSE;
}
}
/* Special case if we have previously read the EOC marker (if the previous tile getted is the last ) */
if (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_EOC) {
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPHSOT;
}
}
/* Reset current tile part number for all tiles, and not only the one */
/* of interest. */
/* Not completely sure this is always correct but required for */
/* ./build/bin/j2k_random_tile_access ./build/tests/tte1.j2k */
l_nb_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th;
for (i = 0; i < l_nb_tiles; ++i) {
p_j2k->m_cp.tcps[i].m_current_tile_part_number = -1;
}
for (;;) {
if (! opj_j2k_read_tile_header(p_j2k,
&l_current_tile_no,
&l_data_size,
&l_tile_x0, &l_tile_y0,
&l_tile_x1, &l_tile_y1,
&l_nb_comps,
&l_go_on,
p_stream,
p_manager)) {
opj_free(l_current_data);
return OPJ_FALSE;
}
if (! l_go_on) {
break;
}
if (l_data_size > l_max_data_size) {
OPJ_BYTE *l_new_current_data = (OPJ_BYTE *) opj_realloc(l_current_data,
l_data_size);
if (! l_new_current_data) {
opj_free(l_current_data);
l_current_data = NULL;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to decode tile %d/%d\n",
l_current_tile_no + 1, p_j2k->m_cp.th * p_j2k->m_cp.tw);
return OPJ_FALSE;
}
l_current_data = l_new_current_data;
l_max_data_size = l_data_size;
}
if (! opj_j2k_decode_tile(p_j2k, l_current_tile_no, l_current_data, l_data_size,
p_stream, p_manager)) {
opj_free(l_current_data);
return OPJ_FALSE;
}
opj_event_msg(p_manager, EVT_INFO, "Tile %d/%d has been decoded.\n",
l_current_tile_no + 1, p_j2k->m_cp.th * p_j2k->m_cp.tw);
if (! opj_j2k_update_image_data(p_j2k->m_tcd, l_current_data,
p_j2k->m_output_image)) {
opj_free(l_current_data);
return OPJ_FALSE;
}
opj_event_msg(p_manager, EVT_INFO,
"Image data has been updated with tile %d.\n\n", l_current_tile_no + 1);
if (l_current_tile_no == l_tile_no_to_dec) {
/* move into the codestream to the first SOT (FIXME or not move?)*/
if (!(opj_stream_read_seek(p_stream, p_j2k->cstr_index->main_head_end + 2,
p_manager))) {
opj_event_msg(p_manager, EVT_ERROR, "Problem with seek function\n");
opj_free(l_current_data);
return OPJ_FALSE;
}
break;
} else {
opj_event_msg(p_manager, EVT_WARNING,
"Tile read, decoded and updated is not the desired one (%d vs %d).\n",
l_current_tile_no + 1, l_tile_no_to_dec + 1);
}
}
opj_free(l_current_data);
return OPJ_TRUE;
}
/**
* Sets up the procedures to do on decoding one tile. Developpers wanting to extend the library can add their own reading procedures.
*/
static OPJ_BOOL opj_j2k_setup_decoding_tile(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager)
{
/* preconditions*/
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_decode_one_tile, p_manager)) {
return OPJ_FALSE;
}
/* DEVELOPER CORNER, add your custom procedures */
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_decode(opj_j2k_t * p_j2k,
opj_stream_private_t * p_stream,
opj_image_t * p_image,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 compno;
if (!p_image) {
return OPJ_FALSE;
}
p_j2k->m_output_image = opj_image_create0();
if (!(p_j2k->m_output_image)) {
return OPJ_FALSE;
}
opj_copy_image_header(p_image, p_j2k->m_output_image);
/* customization of the decoding */
if (!opj_j2k_setup_decoding(p_j2k, p_manager)) {
return OPJ_FALSE;
}
/* Decode the codestream */
if (! opj_j2k_exec(p_j2k, p_j2k->m_procedure_list, p_stream, p_manager)) {
opj_image_destroy(p_j2k->m_private_image);
p_j2k->m_private_image = NULL;
return OPJ_FALSE;
}
/* Move data and copy one information from codec to output image*/
for (compno = 0; compno < p_image->numcomps; compno++) {
p_image->comps[compno].resno_decoded =
p_j2k->m_output_image->comps[compno].resno_decoded;
p_image->comps[compno].data = p_j2k->m_output_image->comps[compno].data;
#if 0
char fn[256];
sprintf(fn, "/tmp/%d.raw", compno);
FILE *debug = fopen(fn, "wb");
fwrite(p_image->comps[compno].data, sizeof(OPJ_INT32),
p_image->comps[compno].w * p_image->comps[compno].h, debug);
fclose(debug);
#endif
p_j2k->m_output_image->comps[compno].data = NULL;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_get_tile(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_image_t* p_image,
opj_event_mgr_t * p_manager,
OPJ_UINT32 tile_index)
{
OPJ_UINT32 compno;
OPJ_UINT32 l_tile_x, l_tile_y;
opj_image_comp_t* l_img_comp;
if (!p_image) {
opj_event_msg(p_manager, EVT_ERROR, "We need an image previously created.\n");
return OPJ_FALSE;
}
if (/*(tile_index < 0) &&*/ (tile_index >= p_j2k->m_cp.tw * p_j2k->m_cp.th)) {
opj_event_msg(p_manager, EVT_ERROR,
"Tile index provided by the user is incorrect %d (max = %d) \n", tile_index,
(p_j2k->m_cp.tw * p_j2k->m_cp.th) - 1);
return OPJ_FALSE;
}
/* Compute the dimension of the desired tile*/
l_tile_x = tile_index % p_j2k->m_cp.tw;
l_tile_y = tile_index / p_j2k->m_cp.tw;
p_image->x0 = l_tile_x * p_j2k->m_cp.tdx + p_j2k->m_cp.tx0;
if (p_image->x0 < p_j2k->m_private_image->x0) {
p_image->x0 = p_j2k->m_private_image->x0;
}
p_image->x1 = (l_tile_x + 1) * p_j2k->m_cp.tdx + p_j2k->m_cp.tx0;
if (p_image->x1 > p_j2k->m_private_image->x1) {
p_image->x1 = p_j2k->m_private_image->x1;
}
p_image->y0 = l_tile_y * p_j2k->m_cp.tdy + p_j2k->m_cp.ty0;
if (p_image->y0 < p_j2k->m_private_image->y0) {
p_image->y0 = p_j2k->m_private_image->y0;
}
p_image->y1 = (l_tile_y + 1) * p_j2k->m_cp.tdy + p_j2k->m_cp.ty0;
if (p_image->y1 > p_j2k->m_private_image->y1) {
p_image->y1 = p_j2k->m_private_image->y1;
}
l_img_comp = p_image->comps;
for (compno = 0; compno < p_image->numcomps; ++compno) {
OPJ_INT32 l_comp_x1, l_comp_y1;
l_img_comp->factor = p_j2k->m_private_image->comps[compno].factor;
l_img_comp->x0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->x0,
(OPJ_INT32)l_img_comp->dx);
l_img_comp->y0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->y0,
(OPJ_INT32)l_img_comp->dy);
l_comp_x1 = opj_int_ceildiv((OPJ_INT32)p_image->x1, (OPJ_INT32)l_img_comp->dx);
l_comp_y1 = opj_int_ceildiv((OPJ_INT32)p_image->y1, (OPJ_INT32)l_img_comp->dy);
l_img_comp->w = (OPJ_UINT32)(opj_int_ceildivpow2(l_comp_x1,
(OPJ_INT32)l_img_comp->factor) - opj_int_ceildivpow2((OPJ_INT32)l_img_comp->x0,
(OPJ_INT32)l_img_comp->factor));
l_img_comp->h = (OPJ_UINT32)(opj_int_ceildivpow2(l_comp_y1,
(OPJ_INT32)l_img_comp->factor) - opj_int_ceildivpow2((OPJ_INT32)l_img_comp->y0,
(OPJ_INT32)l_img_comp->factor));
l_img_comp++;
}
/* Destroy the previous output image*/
if (p_j2k->m_output_image) {
opj_image_destroy(p_j2k->m_output_image);
}
/* Create the ouput image from the information previously computed*/
p_j2k->m_output_image = opj_image_create0();
if (!(p_j2k->m_output_image)) {
return OPJ_FALSE;
}
opj_copy_image_header(p_image, p_j2k->m_output_image);
p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec = (OPJ_INT32)tile_index;
/* customization of the decoding */
if (!opj_j2k_setup_decoding_tile(p_j2k, p_manager)) {
return OPJ_FALSE;
}
/* Decode the codestream */
if (! opj_j2k_exec(p_j2k, p_j2k->m_procedure_list, p_stream, p_manager)) {
opj_image_destroy(p_j2k->m_private_image);
p_j2k->m_private_image = NULL;
return OPJ_FALSE;
}
/* Move data and copy one information from codec to output image*/
for (compno = 0; compno < p_image->numcomps; compno++) {
p_image->comps[compno].resno_decoded =
p_j2k->m_output_image->comps[compno].resno_decoded;
if (p_image->comps[compno].data) {
opj_image_data_free(p_image->comps[compno].data);
}
p_image->comps[compno].data = p_j2k->m_output_image->comps[compno].data;
p_j2k->m_output_image->comps[compno].data = NULL;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_set_decoded_resolution_factor(opj_j2k_t *p_j2k,
OPJ_UINT32 res_factor,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 it_comp;
p_j2k->m_cp.m_specific_param.m_dec.m_reduce = res_factor;
if (p_j2k->m_private_image) {
if (p_j2k->m_private_image->comps) {
if (p_j2k->m_specific_param.m_decoder.m_default_tcp) {
if (p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps) {
for (it_comp = 0 ; it_comp < p_j2k->m_private_image->numcomps; it_comp++) {
OPJ_UINT32 max_res =
p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps[it_comp].numresolutions;
if (res_factor >= max_res) {
opj_event_msg(p_manager, EVT_ERROR,
"Resolution factor is greater than the maximum resolution in the component.\n");
return OPJ_FALSE;
}
p_j2k->m_private_image->comps[it_comp].factor = res_factor;
}
return OPJ_TRUE;
}
}
}
}
return OPJ_FALSE;
}
OPJ_BOOL opj_j2k_encode(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 i, j;
OPJ_UINT32 l_nb_tiles;
OPJ_UINT32 l_max_tile_size = 0, l_current_tile_size;
OPJ_BYTE * l_current_data = 00;
OPJ_BOOL l_reuse_data = OPJ_FALSE;
opj_tcd_t* p_tcd = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
p_tcd = p_j2k->m_tcd;
l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
if (l_nb_tiles == 1) {
l_reuse_data = OPJ_TRUE;
#ifdef __SSE__
for (j = 0; j < p_j2k->m_tcd->image->numcomps; ++j) {
opj_image_comp_t * l_img_comp = p_tcd->image->comps + j;
if (((size_t)l_img_comp->data & 0xFU) !=
0U) { /* tile data shall be aligned on 16 bytes */
l_reuse_data = OPJ_FALSE;
}
}
#endif
}
for (i = 0; i < l_nb_tiles; ++i) {
if (! opj_j2k_pre_write_tile(p_j2k, i, p_stream, p_manager)) {
if (l_current_data) {
opj_free(l_current_data);
}
return OPJ_FALSE;
}
/* if we only have one tile, then simply set tile component data equal to image component data */
/* otherwise, allocate the data */
for (j = 0; j < p_j2k->m_tcd->image->numcomps; ++j) {
opj_tcd_tilecomp_t* l_tilec = p_tcd->tcd_image->tiles->comps + j;
if (l_reuse_data) {
opj_image_comp_t * l_img_comp = p_tcd->image->comps + j;
l_tilec->data = l_img_comp->data;
l_tilec->ownsData = OPJ_FALSE;
} else {
if (! opj_alloc_tile_component_data(l_tilec)) {
opj_event_msg(p_manager, EVT_ERROR, "Error allocating tile component data.");
if (l_current_data) {
opj_free(l_current_data);
}
return OPJ_FALSE;
}
}
}
l_current_tile_size = opj_tcd_get_encoded_tile_size(p_j2k->m_tcd);
if (!l_reuse_data) {
if (l_current_tile_size > l_max_tile_size) {
OPJ_BYTE *l_new_current_data = (OPJ_BYTE *) opj_realloc(l_current_data,
l_current_tile_size);
if (! l_new_current_data) {
if (l_current_data) {
opj_free(l_current_data);
}
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to encode all tiles\n");
return OPJ_FALSE;
}
l_current_data = l_new_current_data;
l_max_tile_size = l_current_tile_size;
}
/* copy image data (32 bit) to l_current_data as contiguous, all-component, zero offset buffer */
/* 32 bit components @ 8 bit precision get converted to 8 bit */
/* 32 bit components @ 16 bit precision get converted to 16 bit */
opj_j2k_get_tile_data(p_j2k->m_tcd, l_current_data);
/* now copy this data into the tile component */
if (! opj_tcd_copy_tile_data(p_j2k->m_tcd, l_current_data,
l_current_tile_size)) {
opj_event_msg(p_manager, EVT_ERROR,
"Size mismatch between tile data and sent data.");
opj_free(l_current_data);
return OPJ_FALSE;
}
}
if (! opj_j2k_post_write_tile(p_j2k, p_stream, p_manager)) {
if (l_current_data) {
opj_free(l_current_data);
}
return OPJ_FALSE;
}
}
if (l_current_data) {
opj_free(l_current_data);
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_end_compress(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
/* customization of the encoding */
if (! opj_j2k_setup_end_compress(p_j2k, p_manager)) {
return OPJ_FALSE;
}
if (! opj_j2k_exec(p_j2k, p_j2k->m_procedure_list, p_stream, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_start_compress(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_image_t * p_image,
opj_event_mgr_t * p_manager)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
p_j2k->m_private_image = opj_image_create0();
if (! p_j2k->m_private_image) {
opj_event_msg(p_manager, EVT_ERROR, "Failed to allocate image header.");
return OPJ_FALSE;
}
opj_copy_image_header(p_image, p_j2k->m_private_image);
/* TODO_MSD: Find a better way */
if (p_image->comps) {
OPJ_UINT32 it_comp;
for (it_comp = 0 ; it_comp < p_image->numcomps; it_comp++) {
if (p_image->comps[it_comp].data) {
p_j2k->m_private_image->comps[it_comp].data = p_image->comps[it_comp].data;
p_image->comps[it_comp].data = NULL;
}
}
}
/* customization of the validation */
if (! opj_j2k_setup_encoding_validation(p_j2k, p_manager)) {
return OPJ_FALSE;
}
/* validation of the parameters codec */
if (! opj_j2k_exec(p_j2k, p_j2k->m_validation_list, p_stream, p_manager)) {
return OPJ_FALSE;
}
/* customization of the encoding */
if (! opj_j2k_setup_header_writing(p_j2k, p_manager)) {
return OPJ_FALSE;
}
/* write header */
if (! opj_j2k_exec(p_j2k, p_j2k->m_procedure_list, p_stream, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_pre_write_tile(opj_j2k_t * p_j2k,
OPJ_UINT32 p_tile_index,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
(void)p_stream;
if (p_tile_index != p_j2k->m_current_tile_number) {
opj_event_msg(p_manager, EVT_ERROR, "The given tile index does not match.");
return OPJ_FALSE;
}
opj_event_msg(p_manager, EVT_INFO, "tile number %d / %d\n",
p_j2k->m_current_tile_number + 1, p_j2k->m_cp.tw * p_j2k->m_cp.th);
p_j2k->m_specific_param.m_encoder.m_current_tile_part_number = 0;
p_j2k->m_tcd->cur_totnum_tp = p_j2k->m_cp.tcps[p_tile_index].m_nb_tile_parts;
p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = 0;
/* initialisation before tile encoding */
if (! opj_tcd_init_encode_tile(p_j2k->m_tcd, p_j2k->m_current_tile_number,
p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static void opj_get_tile_dimensions(opj_image_t * l_image,
opj_tcd_tilecomp_t * l_tilec,
opj_image_comp_t * l_img_comp,
OPJ_UINT32* l_size_comp,
OPJ_UINT32* l_width,
OPJ_UINT32* l_height,
OPJ_UINT32* l_offset_x,
OPJ_UINT32* l_offset_y,
OPJ_UINT32* l_image_width,
OPJ_UINT32* l_stride,
OPJ_UINT32* l_tile_offset)
{
OPJ_UINT32 l_remaining;
*l_size_comp = l_img_comp->prec >> 3; /* (/8) */
l_remaining = l_img_comp->prec & 7; /* (%8) */
if (l_remaining) {
*l_size_comp += 1;
}
if (*l_size_comp == 3) {
*l_size_comp = 4;
}
*l_width = (OPJ_UINT32)(l_tilec->x1 - l_tilec->x0);
*l_height = (OPJ_UINT32)(l_tilec->y1 - l_tilec->y0);
*l_offset_x = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)l_image->x0,
(OPJ_INT32)l_img_comp->dx);
*l_offset_y = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)l_image->y0,
(OPJ_INT32)l_img_comp->dy);
*l_image_width = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)l_image->x1 -
(OPJ_INT32)l_image->x0, (OPJ_INT32)l_img_comp->dx);
*l_stride = *l_image_width - *l_width;
*l_tile_offset = ((OPJ_UINT32)l_tilec->x0 - *l_offset_x) + ((
OPJ_UINT32)l_tilec->y0 - *l_offset_y) * *l_image_width;
}
static void opj_j2k_get_tile_data(opj_tcd_t * p_tcd, OPJ_BYTE * p_data)
{
OPJ_UINT32 i, j, k = 0;
for (i = 0; i < p_tcd->image->numcomps; ++i) {
opj_image_t * l_image = p_tcd->image;
OPJ_INT32 * l_src_ptr;
opj_tcd_tilecomp_t * l_tilec = p_tcd->tcd_image->tiles->comps + i;
opj_image_comp_t * l_img_comp = l_image->comps + i;
OPJ_UINT32 l_size_comp, l_width, l_height, l_offset_x, l_offset_y,
l_image_width, l_stride, l_tile_offset;
opj_get_tile_dimensions(l_image,
l_tilec,
l_img_comp,
&l_size_comp,
&l_width,
&l_height,
&l_offset_x,
&l_offset_y,
&l_image_width,
&l_stride,
&l_tile_offset);
l_src_ptr = l_img_comp->data + l_tile_offset;
switch (l_size_comp) {
case 1: {
OPJ_CHAR * l_dest_ptr = (OPJ_CHAR*) p_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_dest_ptr;
++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_dest_ptr;
++l_src_ptr;
}
l_src_ptr += l_stride;
}
}
p_data = (OPJ_BYTE*) l_dest_ptr;
}
break;
case 2: {
OPJ_INT16 * l_dest_ptr = (OPJ_INT16 *) p_data;
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_data = (OPJ_BYTE*) l_dest_ptr;
}
break;
case 4: {
OPJ_INT32 * l_dest_ptr = (OPJ_INT32 *) p_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_data = (OPJ_BYTE*) l_dest_ptr;
}
break;
}
}
}
static OPJ_BOOL opj_j2k_post_write_tile(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 l_nb_bytes_written;
OPJ_BYTE * l_current_data = 00;
OPJ_UINT32 l_tile_size = 0;
OPJ_UINT32 l_available_data;
/* preconditions */
assert(p_j2k->m_specific_param.m_encoder.m_encoded_tile_data);
l_tile_size = p_j2k->m_specific_param.m_encoder.m_encoded_tile_size;
l_available_data = l_tile_size;
l_current_data = p_j2k->m_specific_param.m_encoder.m_encoded_tile_data;
l_nb_bytes_written = 0;
if (! opj_j2k_write_first_tile_part(p_j2k, l_current_data, &l_nb_bytes_written,
l_available_data, p_stream, p_manager)) {
return OPJ_FALSE;
}
l_current_data += l_nb_bytes_written;
l_available_data -= l_nb_bytes_written;
l_nb_bytes_written = 0;
if (! opj_j2k_write_all_tile_parts(p_j2k, l_current_data, &l_nb_bytes_written,
l_available_data, p_stream, p_manager)) {
return OPJ_FALSE;
}
l_available_data -= l_nb_bytes_written;
l_nb_bytes_written = l_tile_size - l_available_data;
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_encoded_tile_data,
l_nb_bytes_written, p_manager) != l_nb_bytes_written) {
return OPJ_FALSE;
}
++p_j2k->m_current_tile_number;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_setup_end_compress(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
/* DEVELOPER CORNER, insert your custom procedures */
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_eoc, p_manager)) {
return OPJ_FALSE;
}
if (OPJ_IS_CINEMA(p_j2k->m_cp.rsiz)) {
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_updated_tlm, p_manager)) {
return OPJ_FALSE;
}
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_epc, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_end_encoding, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_destroy_header_memory, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_setup_encoding_validation(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list,
(opj_procedure)opj_j2k_build_encoder, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list,
(opj_procedure)opj_j2k_encoding_validation, p_manager)) {
return OPJ_FALSE;
}
/* DEVELOPER CORNER, add your custom validation procedure */
if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list,
(opj_procedure)opj_j2k_mct_validation, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_setup_header_writing(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_init_info, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_soc, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_siz, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_cod, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_qcd, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_all_coc, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_all_qcc, p_manager)) {
return OPJ_FALSE;
}
if (OPJ_IS_CINEMA(p_j2k->m_cp.rsiz)) {
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_tlm, p_manager)) {
return OPJ_FALSE;
}
if (p_j2k->m_cp.rsiz == OPJ_PROFILE_CINEMA_4K) {
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_poc, p_manager)) {
return OPJ_FALSE;
}
}
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_regions, p_manager)) {
return OPJ_FALSE;
}
if (p_j2k->m_cp.comment != 00) {
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_com, p_manager)) {
return OPJ_FALSE;
}
}
/* DEVELOPER CORNER, insert your custom procedures */
if (p_j2k->m_cp.rsiz & OPJ_EXTENSION_MCT) {
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_mct_data_group, p_manager)) {
return OPJ_FALSE;
}
}
/* End of Developer Corner */
if (p_j2k->cstr_index) {
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_get_end_header, p_manager)) {
return OPJ_FALSE;
}
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_create_tcd, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_update_rates, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_first_tile_part(opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_total_data_size,
opj_stream_private_t *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 l_nb_bytes_written = 0;
OPJ_UINT32 l_current_nb_bytes_written;
OPJ_BYTE * l_begin_data = 00;
opj_tcd_t * l_tcd = 00;
opj_cp_t * l_cp = 00;
l_tcd = p_j2k->m_tcd;
l_cp = &(p_j2k->m_cp);
l_tcd->cur_pino = 0;
/*Get number of tile parts*/
p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = 0;
/* INDEX >> */
/* << INDEX */
l_current_nb_bytes_written = 0;
l_begin_data = p_data;
if (! opj_j2k_write_sot(p_j2k, p_data, p_total_data_size,
&l_current_nb_bytes_written, p_stream,
p_manager)) {
return OPJ_FALSE;
}
l_nb_bytes_written += l_current_nb_bytes_written;
p_data += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
if (!OPJ_IS_CINEMA(l_cp->rsiz)) {
#if 0
for (compno = 1; compno < p_j2k->m_private_image->numcomps; compno++) {
l_current_nb_bytes_written = 0;
opj_j2k_write_coc_in_memory(p_j2k, compno, p_data, &l_current_nb_bytes_written,
p_manager);
l_nb_bytes_written += l_current_nb_bytes_written;
p_data += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
l_current_nb_bytes_written = 0;
opj_j2k_write_qcc_in_memory(p_j2k, compno, p_data, &l_current_nb_bytes_written,
p_manager);
l_nb_bytes_written += l_current_nb_bytes_written;
p_data += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
}
#endif
if (l_cp->tcps[p_j2k->m_current_tile_number].numpocs) {
l_current_nb_bytes_written = 0;
opj_j2k_write_poc_in_memory(p_j2k, p_data, &l_current_nb_bytes_written,
p_manager);
l_nb_bytes_written += l_current_nb_bytes_written;
p_data += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
}
}
l_current_nb_bytes_written = 0;
if (! opj_j2k_write_sod(p_j2k, l_tcd, p_data, &l_current_nb_bytes_written,
p_total_data_size, p_stream, p_manager)) {
return OPJ_FALSE;
}
l_nb_bytes_written += l_current_nb_bytes_written;
* p_data_written = l_nb_bytes_written;
/* Writing Psot in SOT marker */
opj_write_bytes(l_begin_data + 6, l_nb_bytes_written,
4); /* PSOT */
if (OPJ_IS_CINEMA(l_cp->rsiz)) {
opj_j2k_update_tlm(p_j2k, l_nb_bytes_written);
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_all_tile_parts(opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_total_data_size,
opj_stream_private_t *p_stream,
struct opj_event_mgr * p_manager
)
{
OPJ_UINT32 tilepartno = 0;
OPJ_UINT32 l_nb_bytes_written = 0;
OPJ_UINT32 l_current_nb_bytes_written;
OPJ_UINT32 l_part_tile_size;
OPJ_UINT32 tot_num_tp;
OPJ_UINT32 pino;
OPJ_BYTE * l_begin_data;
opj_tcp_t *l_tcp = 00;
opj_tcd_t * l_tcd = 00;
opj_cp_t * l_cp = 00;
l_tcd = p_j2k->m_tcd;
l_cp = &(p_j2k->m_cp);
l_tcp = l_cp->tcps + p_j2k->m_current_tile_number;
/*Get number of tile parts*/
tot_num_tp = opj_j2k_get_num_tp(l_cp, 0, p_j2k->m_current_tile_number);
/* start writing remaining tile parts */
++p_j2k->m_specific_param.m_encoder.m_current_tile_part_number;
for (tilepartno = 1; tilepartno < tot_num_tp ; ++tilepartno) {
p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = tilepartno;
l_current_nb_bytes_written = 0;
l_part_tile_size = 0;
l_begin_data = p_data;
if (! opj_j2k_write_sot(p_j2k, p_data,
p_total_data_size,
&l_current_nb_bytes_written,
p_stream,
p_manager)) {
return OPJ_FALSE;
}
l_nb_bytes_written += l_current_nb_bytes_written;
p_data += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
l_part_tile_size += l_current_nb_bytes_written;
l_current_nb_bytes_written = 0;
if (! opj_j2k_write_sod(p_j2k, l_tcd, p_data, &l_current_nb_bytes_written,
p_total_data_size, p_stream, p_manager)) {
return OPJ_FALSE;
}
p_data += l_current_nb_bytes_written;
l_nb_bytes_written += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
l_part_tile_size += l_current_nb_bytes_written;
/* Writing Psot in SOT marker */
opj_write_bytes(l_begin_data + 6, l_part_tile_size,
4); /* PSOT */
if (OPJ_IS_CINEMA(l_cp->rsiz)) {
opj_j2k_update_tlm(p_j2k, l_part_tile_size);
}
++p_j2k->m_specific_param.m_encoder.m_current_tile_part_number;
}
for (pino = 1; pino <= l_tcp->numpocs; ++pino) {
l_tcd->cur_pino = pino;
/*Get number of tile parts*/
tot_num_tp = opj_j2k_get_num_tp(l_cp, pino, p_j2k->m_current_tile_number);
for (tilepartno = 0; tilepartno < tot_num_tp ; ++tilepartno) {
p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = tilepartno;
l_current_nb_bytes_written = 0;
l_part_tile_size = 0;
l_begin_data = p_data;
if (! opj_j2k_write_sot(p_j2k, p_data,
p_total_data_size,
&l_current_nb_bytes_written, p_stream,
p_manager)) {
return OPJ_FALSE;
}
l_nb_bytes_written += l_current_nb_bytes_written;
p_data += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
l_part_tile_size += l_current_nb_bytes_written;
l_current_nb_bytes_written = 0;
if (! opj_j2k_write_sod(p_j2k, l_tcd, p_data, &l_current_nb_bytes_written,
p_total_data_size, p_stream, p_manager)) {
return OPJ_FALSE;
}
l_nb_bytes_written += l_current_nb_bytes_written;
p_data += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
l_part_tile_size += l_current_nb_bytes_written;
/* Writing Psot in SOT marker */
opj_write_bytes(l_begin_data + 6, l_part_tile_size,
4); /* PSOT */
if (OPJ_IS_CINEMA(l_cp->rsiz)) {
opj_j2k_update_tlm(p_j2k, l_part_tile_size);
}
++p_j2k->m_specific_param.m_encoder.m_current_tile_part_number;
}
}
*p_data_written = l_nb_bytes_written;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_updated_tlm(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 l_tlm_size;
OPJ_OFF_T l_tlm_position, l_current_position;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_tlm_size = 5 * p_j2k->m_specific_param.m_encoder.m_total_tile_parts;
l_tlm_position = 6 + p_j2k->m_specific_param.m_encoder.m_tlm_start;
l_current_position = opj_stream_tell(p_stream);
if (! opj_stream_seek(p_stream, l_tlm_position, p_manager)) {
return OPJ_FALSE;
}
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer, l_tlm_size,
p_manager) != l_tlm_size) {
return OPJ_FALSE;
}
if (! opj_stream_seek(p_stream, l_current_position, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_end_encoding(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
OPJ_UNUSED(p_stream);
OPJ_UNUSED(p_manager);
opj_tcd_destroy(p_j2k->m_tcd);
p_j2k->m_tcd = 00;
if (p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer) {
opj_free(p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer);
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer = 0;
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current = 0;
}
if (p_j2k->m_specific_param.m_encoder.m_encoded_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_encoded_tile_data);
p_j2k->m_specific_param.m_encoder.m_encoded_tile_data = 0;
}
p_j2k->m_specific_param.m_encoder.m_encoded_tile_size = 0;
return OPJ_TRUE;
}
/**
* Destroys the memory associated with the decoding of headers.
*/
static OPJ_BOOL opj_j2k_destroy_header_memory(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_stream);
OPJ_UNUSED(p_manager);
if (p_j2k->m_specific_param.m_encoder.m_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = 0;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_init_info(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
opj_codestream_info_t * l_cstr_info = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
(void)l_cstr_info;
OPJ_UNUSED(p_stream);
/* TODO mergeV2: check this part which use cstr_info */
/*l_cstr_info = p_j2k->cstr_info;
if (l_cstr_info) {
OPJ_UINT32 compno;
l_cstr_info->tile = (opj_tile_info_t *) opj_malloc(p_j2k->m_cp.tw * p_j2k->m_cp.th * sizeof(opj_tile_info_t));
l_cstr_info->image_w = p_j2k->m_image->x1 - p_j2k->m_image->x0;
l_cstr_info->image_h = p_j2k->m_image->y1 - p_j2k->m_image->y0;
l_cstr_info->prog = (&p_j2k->m_cp.tcps[0])->prg;
l_cstr_info->tw = p_j2k->m_cp.tw;
l_cstr_info->th = p_j2k->m_cp.th;
l_cstr_info->tile_x = p_j2k->m_cp.tdx;*/ /* new version parser */
/*l_cstr_info->tile_y = p_j2k->m_cp.tdy;*/ /* new version parser */
/*l_cstr_info->tile_Ox = p_j2k->m_cp.tx0;*/ /* new version parser */
/*l_cstr_info->tile_Oy = p_j2k->m_cp.ty0;*/ /* new version parser */
/*l_cstr_info->numcomps = p_j2k->m_image->numcomps;
l_cstr_info->numlayers = (&p_j2k->m_cp.tcps[0])->numlayers;
l_cstr_info->numdecompos = (OPJ_INT32*) opj_malloc(p_j2k->m_image->numcomps * sizeof(OPJ_INT32));
for (compno=0; compno < p_j2k->m_image->numcomps; compno++) {
l_cstr_info->numdecompos[compno] = (&p_j2k->m_cp.tcps[0])->tccps->numresolutions - 1;
}
l_cstr_info->D_max = 0.0; */ /* ADD Marcela */
/*l_cstr_info->main_head_start = opj_stream_tell(p_stream);*/ /* position of SOC */
/*l_cstr_info->maxmarknum = 100;
l_cstr_info->marker = (opj_marker_info_t *) opj_malloc(l_cstr_info->maxmarknum * sizeof(opj_marker_info_t));
l_cstr_info->marknum = 0;
}*/
return opj_j2k_calculate_tp(p_j2k, &(p_j2k->m_cp),
&p_j2k->m_specific_param.m_encoder.m_total_tile_parts, p_j2k->m_private_image,
p_manager);
}
/**
* Creates a tile-coder decoder.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_create_tcd(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
OPJ_UNUSED(p_stream);
p_j2k->m_tcd = opj_tcd_create(OPJ_FALSE);
if (! p_j2k->m_tcd) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to create Tile Coder\n");
return OPJ_FALSE;
}
if (!opj_tcd_init(p_j2k->m_tcd, p_j2k->m_private_image, &p_j2k->m_cp,
p_j2k->m_tp)) {
opj_tcd_destroy(p_j2k->m_tcd);
p_j2k->m_tcd = 00;
return OPJ_FALSE;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_write_tile(opj_j2k_t * p_j2k,
OPJ_UINT32 p_tile_index,
OPJ_BYTE * p_data,
OPJ_UINT32 p_data_size,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
if (! opj_j2k_pre_write_tile(p_j2k, p_tile_index, p_stream, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR,
"Error while opj_j2k_pre_write_tile with tile index = %d\n", p_tile_index);
return OPJ_FALSE;
} else {
OPJ_UINT32 j;
/* Allocate data */
for (j = 0; j < p_j2k->m_tcd->image->numcomps; ++j) {
opj_tcd_tilecomp_t* l_tilec = p_j2k->m_tcd->tcd_image->tiles->comps + j;
if (! opj_alloc_tile_component_data(l_tilec)) {
opj_event_msg(p_manager, EVT_ERROR, "Error allocating tile component data.");
return OPJ_FALSE;
}
}
/* now copy data into the tile component */
if (! opj_tcd_copy_tile_data(p_j2k->m_tcd, p_data, p_data_size)) {
opj_event_msg(p_manager, EVT_ERROR,
"Size mismatch between tile data and sent data.");
return OPJ_FALSE;
}
if (! opj_j2k_post_write_tile(p_j2k, p_stream, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR,
"Error while opj_j2k_post_write_tile with tile index = %d\n", p_tile_index);
return OPJ_FALSE;
}
}
return OPJ_TRUE;
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_2758_0 |
crossvul-cpp_data_good_2457_0 | // SPDX-License-Identifier: GPL-2.0-only
/*
* Simple NUMA memory policy for the Linux kernel.
*
* Copyright 2003,2004 Andi Kleen, SuSE Labs.
* (C) Copyright 2005 Christoph Lameter, Silicon Graphics, Inc.
*
* NUMA policy allows the user to give hints in which node(s) memory should
* be allocated.
*
* Support four policies per VMA and per process:
*
* The VMA policy has priority over the process policy for a page fault.
*
* interleave Allocate memory interleaved over a set of nodes,
* with normal fallback if it fails.
* For VMA based allocations this interleaves based on the
* offset into the backing object or offset into the mapping
* for anonymous memory. For process policy an process counter
* is used.
*
* bind Only allocate memory on a specific set of nodes,
* no fallback.
* FIXME: memory is allocated starting with the first node
* to the last. It would be better if bind would truly restrict
* the allocation to memory nodes instead
*
* preferred Try a specific node first before normal fallback.
* As a special case NUMA_NO_NODE here means do the allocation
* on the local CPU. This is normally identical to default,
* but useful to set in a VMA when you have a non default
* process policy.
*
* default Allocate on the local node first, or when on a VMA
* use the process policy. This is what Linux always did
* in a NUMA aware kernel and still does by, ahem, default.
*
* The process policy is applied for most non interrupt memory allocations
* in that process' context. Interrupts ignore the policies and always
* try to allocate on the local CPU. The VMA policy is only applied for memory
* allocations for a VMA in the VM.
*
* Currently there are a few corner cases in swapping where the policy
* is not applied, but the majority should be handled. When process policy
* is used it is not remembered over swap outs/swap ins.
*
* Only the highest zone in the zone hierarchy gets policied. Allocations
* requesting a lower zone just use default policy. This implies that
* on systems with highmem kernel lowmem allocation don't get policied.
* Same with GFP_DMA allocations.
*
* For shmfs/tmpfs/hugetlbfs shared memory the policy is shared between
* all users and remembered even when nobody has memory mapped.
*/
/* Notebook:
fix mmap readahead to honour policy and enable policy for any page cache
object
statistics for bigpages
global policy for page cache? currently it uses process policy. Requires
first item above.
handle mremap for shared memory (currently ignored for the policy)
grows down?
make bind policy root only? It can trigger oom much faster and the
kernel is not always grateful with that.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/mempolicy.h>
#include <linux/pagewalk.h>
#include <linux/highmem.h>
#include <linux/hugetlb.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/sched/mm.h>
#include <linux/sched/numa_balancing.h>
#include <linux/sched/task.h>
#include <linux/nodemask.h>
#include <linux/cpuset.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/export.h>
#include <linux/nsproxy.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/compat.h>
#include <linux/ptrace.h>
#include <linux/swap.h>
#include <linux/seq_file.h>
#include <linux/proc_fs.h>
#include <linux/migrate.h>
#include <linux/ksm.h>
#include <linux/rmap.h>
#include <linux/security.h>
#include <linux/syscalls.h>
#include <linux/ctype.h>
#include <linux/mm_inline.h>
#include <linux/mmu_notifier.h>
#include <linux/printk.h>
#include <linux/swapops.h>
#include <asm/tlbflush.h>
#include <linux/uaccess.h>
#include "internal.h"
/* Internal flags */
#define MPOL_MF_DISCONTIG_OK (MPOL_MF_INTERNAL << 0) /* Skip checks for continuous vmas */
#define MPOL_MF_INVERT (MPOL_MF_INTERNAL << 1) /* Invert check for nodemask */
static struct kmem_cache *policy_cache;
static struct kmem_cache *sn_cache;
/* Highest zone. An specific allocation for a zone below that is not
policied. */
enum zone_type policy_zone = 0;
/*
* run-time system-wide default policy => local allocation
*/
static struct mempolicy default_policy = {
.refcnt = ATOMIC_INIT(1), /* never free it */
.mode = MPOL_PREFERRED,
.flags = MPOL_F_LOCAL,
};
static struct mempolicy preferred_node_policy[MAX_NUMNODES];
struct mempolicy *get_task_policy(struct task_struct *p)
{
struct mempolicy *pol = p->mempolicy;
int node;
if (pol)
return pol;
node = numa_node_id();
if (node != NUMA_NO_NODE) {
pol = &preferred_node_policy[node];
/* preferred_node_policy is not initialised early in boot */
if (pol->mode)
return pol;
}
return &default_policy;
}
static const struct mempolicy_operations {
int (*create)(struct mempolicy *pol, const nodemask_t *nodes);
void (*rebind)(struct mempolicy *pol, const nodemask_t *nodes);
} mpol_ops[MPOL_MAX];
static inline int mpol_store_user_nodemask(const struct mempolicy *pol)
{
return pol->flags & MPOL_MODE_FLAGS;
}
static void mpol_relative_nodemask(nodemask_t *ret, const nodemask_t *orig,
const nodemask_t *rel)
{
nodemask_t tmp;
nodes_fold(tmp, *orig, nodes_weight(*rel));
nodes_onto(*ret, tmp, *rel);
}
static int mpol_new_interleave(struct mempolicy *pol, const nodemask_t *nodes)
{
if (nodes_empty(*nodes))
return -EINVAL;
pol->v.nodes = *nodes;
return 0;
}
static int mpol_new_preferred(struct mempolicy *pol, const nodemask_t *nodes)
{
if (!nodes)
pol->flags |= MPOL_F_LOCAL; /* local allocation */
else if (nodes_empty(*nodes))
return -EINVAL; /* no allowed nodes */
else
pol->v.preferred_node = first_node(*nodes);
return 0;
}
static int mpol_new_bind(struct mempolicy *pol, const nodemask_t *nodes)
{
if (nodes_empty(*nodes))
return -EINVAL;
pol->v.nodes = *nodes;
return 0;
}
/*
* mpol_set_nodemask is called after mpol_new() to set up the nodemask, if
* any, for the new policy. mpol_new() has already validated the nodes
* parameter with respect to the policy mode and flags. But, we need to
* handle an empty nodemask with MPOL_PREFERRED here.
*
* Must be called holding task's alloc_lock to protect task's mems_allowed
* and mempolicy. May also be called holding the mmap_semaphore for write.
*/
static int mpol_set_nodemask(struct mempolicy *pol,
const nodemask_t *nodes, struct nodemask_scratch *nsc)
{
int ret;
/* if mode is MPOL_DEFAULT, pol is NULL. This is right. */
if (pol == NULL)
return 0;
/* Check N_MEMORY */
nodes_and(nsc->mask1,
cpuset_current_mems_allowed, node_states[N_MEMORY]);
VM_BUG_ON(!nodes);
if (pol->mode == MPOL_PREFERRED && nodes_empty(*nodes))
nodes = NULL; /* explicit local allocation */
else {
if (pol->flags & MPOL_F_RELATIVE_NODES)
mpol_relative_nodemask(&nsc->mask2, nodes, &nsc->mask1);
else
nodes_and(nsc->mask2, *nodes, nsc->mask1);
if (mpol_store_user_nodemask(pol))
pol->w.user_nodemask = *nodes;
else
pol->w.cpuset_mems_allowed =
cpuset_current_mems_allowed;
}
if (nodes)
ret = mpol_ops[pol->mode].create(pol, &nsc->mask2);
else
ret = mpol_ops[pol->mode].create(pol, NULL);
return ret;
}
/*
* This function just creates a new policy, does some check and simple
* initialization. You must invoke mpol_set_nodemask() to set nodes.
*/
static struct mempolicy *mpol_new(unsigned short mode, unsigned short flags,
nodemask_t *nodes)
{
struct mempolicy *policy;
pr_debug("setting mode %d flags %d nodes[0] %lx\n",
mode, flags, nodes ? nodes_addr(*nodes)[0] : NUMA_NO_NODE);
if (mode == MPOL_DEFAULT) {
if (nodes && !nodes_empty(*nodes))
return ERR_PTR(-EINVAL);
return NULL;
}
VM_BUG_ON(!nodes);
/*
* MPOL_PREFERRED cannot be used with MPOL_F_STATIC_NODES or
* MPOL_F_RELATIVE_NODES if the nodemask is empty (local allocation).
* All other modes require a valid pointer to a non-empty nodemask.
*/
if (mode == MPOL_PREFERRED) {
if (nodes_empty(*nodes)) {
if (((flags & MPOL_F_STATIC_NODES) ||
(flags & MPOL_F_RELATIVE_NODES)))
return ERR_PTR(-EINVAL);
}
} else if (mode == MPOL_LOCAL) {
if (!nodes_empty(*nodes) ||
(flags & MPOL_F_STATIC_NODES) ||
(flags & MPOL_F_RELATIVE_NODES))
return ERR_PTR(-EINVAL);
mode = MPOL_PREFERRED;
} else if (nodes_empty(*nodes))
return ERR_PTR(-EINVAL);
policy = kmem_cache_alloc(policy_cache, GFP_KERNEL);
if (!policy)
return ERR_PTR(-ENOMEM);
atomic_set(&policy->refcnt, 1);
policy->mode = mode;
policy->flags = flags;
return policy;
}
/* Slow path of a mpol destructor. */
void __mpol_put(struct mempolicy *p)
{
if (!atomic_dec_and_test(&p->refcnt))
return;
kmem_cache_free(policy_cache, p);
}
static void mpol_rebind_default(struct mempolicy *pol, const nodemask_t *nodes)
{
}
static void mpol_rebind_nodemask(struct mempolicy *pol, const nodemask_t *nodes)
{
nodemask_t tmp;
if (pol->flags & MPOL_F_STATIC_NODES)
nodes_and(tmp, pol->w.user_nodemask, *nodes);
else if (pol->flags & MPOL_F_RELATIVE_NODES)
mpol_relative_nodemask(&tmp, &pol->w.user_nodemask, nodes);
else {
nodes_remap(tmp, pol->v.nodes,pol->w.cpuset_mems_allowed,
*nodes);
pol->w.cpuset_mems_allowed = *nodes;
}
if (nodes_empty(tmp))
tmp = *nodes;
pol->v.nodes = tmp;
}
static void mpol_rebind_preferred(struct mempolicy *pol,
const nodemask_t *nodes)
{
nodemask_t tmp;
if (pol->flags & MPOL_F_STATIC_NODES) {
int node = first_node(pol->w.user_nodemask);
if (node_isset(node, *nodes)) {
pol->v.preferred_node = node;
pol->flags &= ~MPOL_F_LOCAL;
} else
pol->flags |= MPOL_F_LOCAL;
} else if (pol->flags & MPOL_F_RELATIVE_NODES) {
mpol_relative_nodemask(&tmp, &pol->w.user_nodemask, nodes);
pol->v.preferred_node = first_node(tmp);
} else if (!(pol->flags & MPOL_F_LOCAL)) {
pol->v.preferred_node = node_remap(pol->v.preferred_node,
pol->w.cpuset_mems_allowed,
*nodes);
pol->w.cpuset_mems_allowed = *nodes;
}
}
/*
* mpol_rebind_policy - Migrate a policy to a different set of nodes
*
* Per-vma policies are protected by mmap_sem. Allocations using per-task
* policies are protected by task->mems_allowed_seq to prevent a premature
* OOM/allocation failure due to parallel nodemask modification.
*/
static void mpol_rebind_policy(struct mempolicy *pol, const nodemask_t *newmask)
{
if (!pol)
return;
if (!mpol_store_user_nodemask(pol) && !(pol->flags & MPOL_F_LOCAL) &&
nodes_equal(pol->w.cpuset_mems_allowed, *newmask))
return;
mpol_ops[pol->mode].rebind(pol, newmask);
}
/*
* Wrapper for mpol_rebind_policy() that just requires task
* pointer, and updates task mempolicy.
*
* Called with task's alloc_lock held.
*/
void mpol_rebind_task(struct task_struct *tsk, const nodemask_t *new)
{
mpol_rebind_policy(tsk->mempolicy, new);
}
/*
* Rebind each vma in mm to new nodemask.
*
* Call holding a reference to mm. Takes mm->mmap_sem during call.
*/
void mpol_rebind_mm(struct mm_struct *mm, nodemask_t *new)
{
struct vm_area_struct *vma;
down_write(&mm->mmap_sem);
for (vma = mm->mmap; vma; vma = vma->vm_next)
mpol_rebind_policy(vma->vm_policy, new);
up_write(&mm->mmap_sem);
}
static const struct mempolicy_operations mpol_ops[MPOL_MAX] = {
[MPOL_DEFAULT] = {
.rebind = mpol_rebind_default,
},
[MPOL_INTERLEAVE] = {
.create = mpol_new_interleave,
.rebind = mpol_rebind_nodemask,
},
[MPOL_PREFERRED] = {
.create = mpol_new_preferred,
.rebind = mpol_rebind_preferred,
},
[MPOL_BIND] = {
.create = mpol_new_bind,
.rebind = mpol_rebind_nodemask,
},
};
static int migrate_page_add(struct page *page, struct list_head *pagelist,
unsigned long flags);
struct queue_pages {
struct list_head *pagelist;
unsigned long flags;
nodemask_t *nmask;
unsigned long start;
unsigned long end;
struct vm_area_struct *first;
};
/*
* Check if the page's nid is in qp->nmask.
*
* If MPOL_MF_INVERT is set in qp->flags, check if the nid is
* in the invert of qp->nmask.
*/
static inline bool queue_pages_required(struct page *page,
struct queue_pages *qp)
{
int nid = page_to_nid(page);
unsigned long flags = qp->flags;
return node_isset(nid, *qp->nmask) == !(flags & MPOL_MF_INVERT);
}
/*
* queue_pages_pmd() has four possible return values:
* 0 - pages are placed on the right node or queued successfully.
* 1 - there is unmovable page, and MPOL_MF_MOVE* & MPOL_MF_STRICT were
* specified.
* 2 - THP was split.
* -EIO - is migration entry or only MPOL_MF_STRICT was specified and an
* existing page was already on a node that does not follow the
* policy.
*/
static int queue_pages_pmd(pmd_t *pmd, spinlock_t *ptl, unsigned long addr,
unsigned long end, struct mm_walk *walk)
{
int ret = 0;
struct page *page;
struct queue_pages *qp = walk->private;
unsigned long flags;
if (unlikely(is_pmd_migration_entry(*pmd))) {
ret = -EIO;
goto unlock;
}
page = pmd_page(*pmd);
if (is_huge_zero_page(page)) {
spin_unlock(ptl);
__split_huge_pmd(walk->vma, pmd, addr, false, NULL);
ret = 2;
goto out;
}
if (!queue_pages_required(page, qp))
goto unlock;
flags = qp->flags;
/* go to thp migration */
if (flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL)) {
if (!vma_migratable(walk->vma) ||
migrate_page_add(page, qp->pagelist, flags)) {
ret = 1;
goto unlock;
}
} else
ret = -EIO;
unlock:
spin_unlock(ptl);
out:
return ret;
}
/*
* Scan through pages checking if pages follow certain conditions,
* and move them to the pagelist if they do.
*
* queue_pages_pte_range() has three possible return values:
* 0 - pages are placed on the right node or queued successfully.
* 1 - there is unmovable page, and MPOL_MF_MOVE* & MPOL_MF_STRICT were
* specified.
* -EIO - only MPOL_MF_STRICT was specified and an existing page was already
* on a node that does not follow the policy.
*/
static int queue_pages_pte_range(pmd_t *pmd, unsigned long addr,
unsigned long end, struct mm_walk *walk)
{
struct vm_area_struct *vma = walk->vma;
struct page *page;
struct queue_pages *qp = walk->private;
unsigned long flags = qp->flags;
int ret;
bool has_unmovable = false;
pte_t *pte;
spinlock_t *ptl;
ptl = pmd_trans_huge_lock(pmd, vma);
if (ptl) {
ret = queue_pages_pmd(pmd, ptl, addr, end, walk);
if (ret != 2)
return ret;
}
/* THP was split, fall through to pte walk */
if (pmd_trans_unstable(pmd))
return 0;
pte = pte_offset_map_lock(walk->mm, pmd, addr, &ptl);
for (; addr != end; pte++, addr += PAGE_SIZE) {
if (!pte_present(*pte))
continue;
page = vm_normal_page(vma, addr, *pte);
if (!page)
continue;
/*
* vm_normal_page() filters out zero pages, but there might
* still be PageReserved pages to skip, perhaps in a VDSO.
*/
if (PageReserved(page))
continue;
if (!queue_pages_required(page, qp))
continue;
if (flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL)) {
/* MPOL_MF_STRICT must be specified if we get here */
if (!vma_migratable(vma)) {
has_unmovable = true;
break;
}
/*
* Do not abort immediately since there may be
* temporary off LRU pages in the range. Still
* need migrate other LRU pages.
*/
if (migrate_page_add(page, qp->pagelist, flags))
has_unmovable = true;
} else
break;
}
pte_unmap_unlock(pte - 1, ptl);
cond_resched();
if (has_unmovable)
return 1;
return addr != end ? -EIO : 0;
}
static int queue_pages_hugetlb(pte_t *pte, unsigned long hmask,
unsigned long addr, unsigned long end,
struct mm_walk *walk)
{
int ret = 0;
#ifdef CONFIG_HUGETLB_PAGE
struct queue_pages *qp = walk->private;
unsigned long flags = (qp->flags & MPOL_MF_VALID);
struct page *page;
spinlock_t *ptl;
pte_t entry;
ptl = huge_pte_lock(hstate_vma(walk->vma), walk->mm, pte);
entry = huge_ptep_get(pte);
if (!pte_present(entry))
goto unlock;
page = pte_page(entry);
if (!queue_pages_required(page, qp))
goto unlock;
if (flags == MPOL_MF_STRICT) {
/*
* STRICT alone means only detecting misplaced page and no
* need to further check other vma.
*/
ret = -EIO;
goto unlock;
}
if (!vma_migratable(walk->vma)) {
/*
* Must be STRICT with MOVE*, otherwise .test_walk() have
* stopped walking current vma.
* Detecting misplaced page but allow migrating pages which
* have been queued.
*/
ret = 1;
goto unlock;
}
/* With MPOL_MF_MOVE, we migrate only unshared hugepage. */
if (flags & (MPOL_MF_MOVE_ALL) ||
(flags & MPOL_MF_MOVE && page_mapcount(page) == 1)) {
if (!isolate_huge_page(page, qp->pagelist) &&
(flags & MPOL_MF_STRICT))
/*
* Failed to isolate page but allow migrating pages
* which have been queued.
*/
ret = 1;
}
unlock:
spin_unlock(ptl);
#else
BUG();
#endif
return ret;
}
#ifdef CONFIG_NUMA_BALANCING
/*
* This is used to mark a range of virtual addresses to be inaccessible.
* These are later cleared by a NUMA hinting fault. Depending on these
* faults, pages may be migrated for better NUMA placement.
*
* This is assuming that NUMA faults are handled using PROT_NONE. If
* an architecture makes a different choice, it will need further
* changes to the core.
*/
unsigned long change_prot_numa(struct vm_area_struct *vma,
unsigned long addr, unsigned long end)
{
int nr_updated;
nr_updated = change_protection(vma, addr, end, PAGE_NONE, 0, 1);
if (nr_updated)
count_vm_numa_events(NUMA_PTE_UPDATES, nr_updated);
return nr_updated;
}
#else
static unsigned long change_prot_numa(struct vm_area_struct *vma,
unsigned long addr, unsigned long end)
{
return 0;
}
#endif /* CONFIG_NUMA_BALANCING */
static int queue_pages_test_walk(unsigned long start, unsigned long end,
struct mm_walk *walk)
{
struct vm_area_struct *vma = walk->vma;
struct queue_pages *qp = walk->private;
unsigned long endvma = vma->vm_end;
unsigned long flags = qp->flags;
/* range check first */
VM_BUG_ON_VMA((vma->vm_start > start) || (vma->vm_end < end), vma);
if (!qp->first) {
qp->first = vma;
if (!(flags & MPOL_MF_DISCONTIG_OK) &&
(qp->start < vma->vm_start))
/* hole at head side of range */
return -EFAULT;
}
if (!(flags & MPOL_MF_DISCONTIG_OK) &&
((vma->vm_end < qp->end) &&
(!vma->vm_next || vma->vm_end < vma->vm_next->vm_start)))
/* hole at middle or tail of range */
return -EFAULT;
/*
* Need check MPOL_MF_STRICT to return -EIO if possible
* regardless of vma_migratable
*/
if (!vma_migratable(vma) &&
!(flags & MPOL_MF_STRICT))
return 1;
if (endvma > end)
endvma = end;
if (flags & MPOL_MF_LAZY) {
/* Similar to task_numa_work, skip inaccessible VMAs */
if (!is_vm_hugetlb_page(vma) &&
(vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE)) &&
!(vma->vm_flags & VM_MIXEDMAP))
change_prot_numa(vma, start, endvma);
return 1;
}
/* queue pages from current vma */
if (flags & MPOL_MF_VALID)
return 0;
return 1;
}
static const struct mm_walk_ops queue_pages_walk_ops = {
.hugetlb_entry = queue_pages_hugetlb,
.pmd_entry = queue_pages_pte_range,
.test_walk = queue_pages_test_walk,
};
/*
* Walk through page tables and collect pages to be migrated.
*
* If pages found in a given range are on a set of nodes (determined by
* @nodes and @flags,) it's isolated and queued to the pagelist which is
* passed via @private.
*
* queue_pages_range() has three possible return values:
* 1 - there is unmovable page, but MPOL_MF_MOVE* & MPOL_MF_STRICT were
* specified.
* 0 - queue pages successfully or no misplaced page.
* errno - i.e. misplaced pages with MPOL_MF_STRICT specified (-EIO) or
* memory range specified by nodemask and maxnode points outside
* your accessible address space (-EFAULT)
*/
static int
queue_pages_range(struct mm_struct *mm, unsigned long start, unsigned long end,
nodemask_t *nodes, unsigned long flags,
struct list_head *pagelist)
{
int err;
struct queue_pages qp = {
.pagelist = pagelist,
.flags = flags,
.nmask = nodes,
.start = start,
.end = end,
.first = NULL,
};
err = walk_page_range(mm, start, end, &queue_pages_walk_ops, &qp);
if (!qp.first)
/* whole range in hole */
err = -EFAULT;
return err;
}
/*
* Apply policy to a single VMA
* This must be called with the mmap_sem held for writing.
*/
static int vma_replace_policy(struct vm_area_struct *vma,
struct mempolicy *pol)
{
int err;
struct mempolicy *old;
struct mempolicy *new;
pr_debug("vma %lx-%lx/%lx vm_ops %p vm_file %p set_policy %p\n",
vma->vm_start, vma->vm_end, vma->vm_pgoff,
vma->vm_ops, vma->vm_file,
vma->vm_ops ? vma->vm_ops->set_policy : NULL);
new = mpol_dup(pol);
if (IS_ERR(new))
return PTR_ERR(new);
if (vma->vm_ops && vma->vm_ops->set_policy) {
err = vma->vm_ops->set_policy(vma, new);
if (err)
goto err_out;
}
old = vma->vm_policy;
vma->vm_policy = new; /* protected by mmap_sem */
mpol_put(old);
return 0;
err_out:
mpol_put(new);
return err;
}
/* Step 2: apply policy to a range and do splits. */
static int mbind_range(struct mm_struct *mm, unsigned long start,
unsigned long end, struct mempolicy *new_pol)
{
struct vm_area_struct *next;
struct vm_area_struct *prev;
struct vm_area_struct *vma;
int err = 0;
pgoff_t pgoff;
unsigned long vmstart;
unsigned long vmend;
vma = find_vma(mm, start);
VM_BUG_ON(!vma);
prev = vma->vm_prev;
if (start > vma->vm_start)
prev = vma;
for (; vma && vma->vm_start < end; prev = vma, vma = next) {
next = vma->vm_next;
vmstart = max(start, vma->vm_start);
vmend = min(end, vma->vm_end);
if (mpol_equal(vma_policy(vma), new_pol))
continue;
pgoff = vma->vm_pgoff +
((vmstart - vma->vm_start) >> PAGE_SHIFT);
prev = vma_merge(mm, prev, vmstart, vmend, vma->vm_flags,
vma->anon_vma, vma->vm_file, pgoff,
new_pol, vma->vm_userfaultfd_ctx);
if (prev) {
vma = prev;
next = vma->vm_next;
if (mpol_equal(vma_policy(vma), new_pol))
continue;
/* vma_merge() joined vma && vma->next, case 8 */
goto replace;
}
if (vma->vm_start != vmstart) {
err = split_vma(vma->vm_mm, vma, vmstart, 1);
if (err)
goto out;
}
if (vma->vm_end != vmend) {
err = split_vma(vma->vm_mm, vma, vmend, 0);
if (err)
goto out;
}
replace:
err = vma_replace_policy(vma, new_pol);
if (err)
goto out;
}
out:
return err;
}
/* Set the process memory policy */
static long do_set_mempolicy(unsigned short mode, unsigned short flags,
nodemask_t *nodes)
{
struct mempolicy *new, *old;
NODEMASK_SCRATCH(scratch);
int ret;
if (!scratch)
return -ENOMEM;
new = mpol_new(mode, flags, nodes);
if (IS_ERR(new)) {
ret = PTR_ERR(new);
goto out;
}
task_lock(current);
ret = mpol_set_nodemask(new, nodes, scratch);
if (ret) {
task_unlock(current);
mpol_put(new);
goto out;
}
old = current->mempolicy;
current->mempolicy = new;
if (new && new->mode == MPOL_INTERLEAVE)
current->il_prev = MAX_NUMNODES-1;
task_unlock(current);
mpol_put(old);
ret = 0;
out:
NODEMASK_SCRATCH_FREE(scratch);
return ret;
}
/*
* Return nodemask for policy for get_mempolicy() query
*
* Called with task's alloc_lock held
*/
static void get_policy_nodemask(struct mempolicy *p, nodemask_t *nodes)
{
nodes_clear(*nodes);
if (p == &default_policy)
return;
switch (p->mode) {
case MPOL_BIND:
/* Fall through */
case MPOL_INTERLEAVE:
*nodes = p->v.nodes;
break;
case MPOL_PREFERRED:
if (!(p->flags & MPOL_F_LOCAL))
node_set(p->v.preferred_node, *nodes);
/* else return empty node mask for local allocation */
break;
default:
BUG();
}
}
static int lookup_node(struct mm_struct *mm, unsigned long addr)
{
struct page *p;
int err;
int locked = 1;
err = get_user_pages_locked(addr & PAGE_MASK, 1, 0, &p, &locked);
if (err >= 0) {
err = page_to_nid(p);
put_page(p);
}
if (locked)
up_read(&mm->mmap_sem);
return err;
}
/* Retrieve NUMA policy */
static long do_get_mempolicy(int *policy, nodemask_t *nmask,
unsigned long addr, unsigned long flags)
{
int err;
struct mm_struct *mm = current->mm;
struct vm_area_struct *vma = NULL;
struct mempolicy *pol = current->mempolicy, *pol_refcount = NULL;
if (flags &
~(unsigned long)(MPOL_F_NODE|MPOL_F_ADDR|MPOL_F_MEMS_ALLOWED))
return -EINVAL;
if (flags & MPOL_F_MEMS_ALLOWED) {
if (flags & (MPOL_F_NODE|MPOL_F_ADDR))
return -EINVAL;
*policy = 0; /* just so it's initialized */
task_lock(current);
*nmask = cpuset_current_mems_allowed;
task_unlock(current);
return 0;
}
if (flags & MPOL_F_ADDR) {
/*
* Do NOT fall back to task policy if the
* vma/shared policy at addr is NULL. We
* want to return MPOL_DEFAULT in this case.
*/
down_read(&mm->mmap_sem);
vma = find_vma_intersection(mm, addr, addr+1);
if (!vma) {
up_read(&mm->mmap_sem);
return -EFAULT;
}
if (vma->vm_ops && vma->vm_ops->get_policy)
pol = vma->vm_ops->get_policy(vma, addr);
else
pol = vma->vm_policy;
} else if (addr)
return -EINVAL;
if (!pol)
pol = &default_policy; /* indicates default behavior */
if (flags & MPOL_F_NODE) {
if (flags & MPOL_F_ADDR) {
/*
* Take a refcount on the mpol, lookup_node()
* wil drop the mmap_sem, so after calling
* lookup_node() only "pol" remains valid, "vma"
* is stale.
*/
pol_refcount = pol;
vma = NULL;
mpol_get(pol);
err = lookup_node(mm, addr);
if (err < 0)
goto out;
*policy = err;
} else if (pol == current->mempolicy &&
pol->mode == MPOL_INTERLEAVE) {
*policy = next_node_in(current->il_prev, pol->v.nodes);
} else {
err = -EINVAL;
goto out;
}
} else {
*policy = pol == &default_policy ? MPOL_DEFAULT :
pol->mode;
/*
* Internal mempolicy flags must be masked off before exposing
* the policy to userspace.
*/
*policy |= (pol->flags & MPOL_MODE_FLAGS);
}
err = 0;
if (nmask) {
if (mpol_store_user_nodemask(pol)) {
*nmask = pol->w.user_nodemask;
} else {
task_lock(current);
get_policy_nodemask(pol, nmask);
task_unlock(current);
}
}
out:
mpol_cond_put(pol);
if (vma)
up_read(&mm->mmap_sem);
if (pol_refcount)
mpol_put(pol_refcount);
return err;
}
#ifdef CONFIG_MIGRATION
/*
* page migration, thp tail pages can be passed.
*/
static int migrate_page_add(struct page *page, struct list_head *pagelist,
unsigned long flags)
{
struct page *head = compound_head(page);
/*
* Avoid migrating a page that is shared with others.
*/
if ((flags & MPOL_MF_MOVE_ALL) || page_mapcount(head) == 1) {
if (!isolate_lru_page(head)) {
list_add_tail(&head->lru, pagelist);
mod_node_page_state(page_pgdat(head),
NR_ISOLATED_ANON + page_is_file_cache(head),
hpage_nr_pages(head));
} else if (flags & MPOL_MF_STRICT) {
/*
* Non-movable page may reach here. And, there may be
* temporary off LRU pages or non-LRU movable pages.
* Treat them as unmovable pages since they can't be
* isolated, so they can't be moved at the moment. It
* should return -EIO for this case too.
*/
return -EIO;
}
}
return 0;
}
/* page allocation callback for NUMA node migration */
struct page *alloc_new_node_page(struct page *page, unsigned long node)
{
if (PageHuge(page))
return alloc_huge_page_node(page_hstate(compound_head(page)),
node);
else if (PageTransHuge(page)) {
struct page *thp;
thp = alloc_pages_node(node,
(GFP_TRANSHUGE | __GFP_THISNODE),
HPAGE_PMD_ORDER);
if (!thp)
return NULL;
prep_transhuge_page(thp);
return thp;
} else
return __alloc_pages_node(node, GFP_HIGHUSER_MOVABLE |
__GFP_THISNODE, 0);
}
/*
* Migrate pages from one node to a target node.
* Returns error or the number of pages not migrated.
*/
static int migrate_to_node(struct mm_struct *mm, int source, int dest,
int flags)
{
nodemask_t nmask;
LIST_HEAD(pagelist);
int err = 0;
nodes_clear(nmask);
node_set(source, nmask);
/*
* This does not "check" the range but isolates all pages that
* need migration. Between passing in the full user address
* space range and MPOL_MF_DISCONTIG_OK, this call can not fail.
*/
VM_BUG_ON(!(flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL)));
queue_pages_range(mm, mm->mmap->vm_start, mm->task_size, &nmask,
flags | MPOL_MF_DISCONTIG_OK, &pagelist);
if (!list_empty(&pagelist)) {
err = migrate_pages(&pagelist, alloc_new_node_page, NULL, dest,
MIGRATE_SYNC, MR_SYSCALL);
if (err)
putback_movable_pages(&pagelist);
}
return err;
}
/*
* Move pages between the two nodesets so as to preserve the physical
* layout as much as possible.
*
* Returns the number of page that could not be moved.
*/
int do_migrate_pages(struct mm_struct *mm, const nodemask_t *from,
const nodemask_t *to, int flags)
{
int busy = 0;
int err;
nodemask_t tmp;
err = migrate_prep();
if (err)
return err;
down_read(&mm->mmap_sem);
/*
* Find a 'source' bit set in 'tmp' whose corresponding 'dest'
* bit in 'to' is not also set in 'tmp'. Clear the found 'source'
* bit in 'tmp', and return that <source, dest> pair for migration.
* The pair of nodemasks 'to' and 'from' define the map.
*
* If no pair of bits is found that way, fallback to picking some
* pair of 'source' and 'dest' bits that are not the same. If the
* 'source' and 'dest' bits are the same, this represents a node
* that will be migrating to itself, so no pages need move.
*
* If no bits are left in 'tmp', or if all remaining bits left
* in 'tmp' correspond to the same bit in 'to', return false
* (nothing left to migrate).
*
* This lets us pick a pair of nodes to migrate between, such that
* if possible the dest node is not already occupied by some other
* source node, minimizing the risk of overloading the memory on a
* node that would happen if we migrated incoming memory to a node
* before migrating outgoing memory source that same node.
*
* A single scan of tmp is sufficient. As we go, we remember the
* most recent <s, d> pair that moved (s != d). If we find a pair
* that not only moved, but what's better, moved to an empty slot
* (d is not set in tmp), then we break out then, with that pair.
* Otherwise when we finish scanning from_tmp, we at least have the
* most recent <s, d> pair that moved. If we get all the way through
* the scan of tmp without finding any node that moved, much less
* moved to an empty node, then there is nothing left worth migrating.
*/
tmp = *from;
while (!nodes_empty(tmp)) {
int s,d;
int source = NUMA_NO_NODE;
int dest = 0;
for_each_node_mask(s, tmp) {
/*
* do_migrate_pages() tries to maintain the relative
* node relationship of the pages established between
* threads and memory areas.
*
* However if the number of source nodes is not equal to
* the number of destination nodes we can not preserve
* this node relative relationship. In that case, skip
* copying memory from a node that is in the destination
* mask.
*
* Example: [2,3,4] -> [3,4,5] moves everything.
* [0-7] - > [3,4,5] moves only 0,1,2,6,7.
*/
if ((nodes_weight(*from) != nodes_weight(*to)) &&
(node_isset(s, *to)))
continue;
d = node_remap(s, *from, *to);
if (s == d)
continue;
source = s; /* Node moved. Memorize */
dest = d;
/* dest not in remaining from nodes? */
if (!node_isset(dest, tmp))
break;
}
if (source == NUMA_NO_NODE)
break;
node_clear(source, tmp);
err = migrate_to_node(mm, source, dest, flags);
if (err > 0)
busy += err;
if (err < 0)
break;
}
up_read(&mm->mmap_sem);
if (err < 0)
return err;
return busy;
}
/*
* Allocate a new page for page migration based on vma policy.
* Start by assuming the page is mapped by the same vma as contains @start.
* Search forward from there, if not. N.B., this assumes that the
* list of pages handed to migrate_pages()--which is how we get here--
* is in virtual address order.
*/
static struct page *new_page(struct page *page, unsigned long start)
{
struct vm_area_struct *vma;
unsigned long uninitialized_var(address);
vma = find_vma(current->mm, start);
while (vma) {
address = page_address_in_vma(page, vma);
if (address != -EFAULT)
break;
vma = vma->vm_next;
}
if (PageHuge(page)) {
return alloc_huge_page_vma(page_hstate(compound_head(page)),
vma, address);
} else if (PageTransHuge(page)) {
struct page *thp;
thp = alloc_hugepage_vma(GFP_TRANSHUGE, vma, address,
HPAGE_PMD_ORDER);
if (!thp)
return NULL;
prep_transhuge_page(thp);
return thp;
}
/*
* if !vma, alloc_page_vma() will use task or system default policy
*/
return alloc_page_vma(GFP_HIGHUSER_MOVABLE | __GFP_RETRY_MAYFAIL,
vma, address);
}
#else
static int migrate_page_add(struct page *page, struct list_head *pagelist,
unsigned long flags)
{
return -EIO;
}
int do_migrate_pages(struct mm_struct *mm, const nodemask_t *from,
const nodemask_t *to, int flags)
{
return -ENOSYS;
}
static struct page *new_page(struct page *page, unsigned long start)
{
return NULL;
}
#endif
static long do_mbind(unsigned long start, unsigned long len,
unsigned short mode, unsigned short mode_flags,
nodemask_t *nmask, unsigned long flags)
{
struct mm_struct *mm = current->mm;
struct mempolicy *new;
unsigned long end;
int err;
int ret;
LIST_HEAD(pagelist);
if (flags & ~(unsigned long)MPOL_MF_VALID)
return -EINVAL;
if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
return -EPERM;
if (start & ~PAGE_MASK)
return -EINVAL;
if (mode == MPOL_DEFAULT)
flags &= ~MPOL_MF_STRICT;
len = (len + PAGE_SIZE - 1) & PAGE_MASK;
end = start + len;
if (end < start)
return -EINVAL;
if (end == start)
return 0;
new = mpol_new(mode, mode_flags, nmask);
if (IS_ERR(new))
return PTR_ERR(new);
if (flags & MPOL_MF_LAZY)
new->flags |= MPOL_F_MOF;
/*
* If we are using the default policy then operation
* on discontinuous address spaces is okay after all
*/
if (!new)
flags |= MPOL_MF_DISCONTIG_OK;
pr_debug("mbind %lx-%lx mode:%d flags:%d nodes:%lx\n",
start, start + len, mode, mode_flags,
nmask ? nodes_addr(*nmask)[0] : NUMA_NO_NODE);
if (flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL)) {
err = migrate_prep();
if (err)
goto mpol_out;
}
{
NODEMASK_SCRATCH(scratch);
if (scratch) {
down_write(&mm->mmap_sem);
task_lock(current);
err = mpol_set_nodemask(new, nmask, scratch);
task_unlock(current);
if (err)
up_write(&mm->mmap_sem);
} else
err = -ENOMEM;
NODEMASK_SCRATCH_FREE(scratch);
}
if (err)
goto mpol_out;
ret = queue_pages_range(mm, start, end, nmask,
flags | MPOL_MF_INVERT, &pagelist);
if (ret < 0) {
err = ret;
goto up_out;
}
err = mbind_range(mm, start, end, new);
if (!err) {
int nr_failed = 0;
if (!list_empty(&pagelist)) {
WARN_ON_ONCE(flags & MPOL_MF_LAZY);
nr_failed = migrate_pages(&pagelist, new_page, NULL,
start, MIGRATE_SYNC, MR_MEMPOLICY_MBIND);
if (nr_failed)
putback_movable_pages(&pagelist);
}
if ((ret > 0) || (nr_failed && (flags & MPOL_MF_STRICT)))
err = -EIO;
} else {
up_out:
if (!list_empty(&pagelist))
putback_movable_pages(&pagelist);
}
up_write(&mm->mmap_sem);
mpol_out:
mpol_put(new);
return err;
}
/*
* User space interface with variable sized bitmaps for nodelists.
*/
/* Copy a node mask from user space. */
static int get_nodes(nodemask_t *nodes, const unsigned long __user *nmask,
unsigned long maxnode)
{
unsigned long k;
unsigned long t;
unsigned long nlongs;
unsigned long endmask;
--maxnode;
nodes_clear(*nodes);
if (maxnode == 0 || !nmask)
return 0;
if (maxnode > PAGE_SIZE*BITS_PER_BYTE)
return -EINVAL;
nlongs = BITS_TO_LONGS(maxnode);
if ((maxnode % BITS_PER_LONG) == 0)
endmask = ~0UL;
else
endmask = (1UL << (maxnode % BITS_PER_LONG)) - 1;
/*
* When the user specified more nodes than supported just check
* if the non supported part is all zero.
*
* If maxnode have more longs than MAX_NUMNODES, check
* the bits in that area first. And then go through to
* check the rest bits which equal or bigger than MAX_NUMNODES.
* Otherwise, just check bits [MAX_NUMNODES, maxnode).
*/
if (nlongs > BITS_TO_LONGS(MAX_NUMNODES)) {
for (k = BITS_TO_LONGS(MAX_NUMNODES); k < nlongs; k++) {
if (get_user(t, nmask + k))
return -EFAULT;
if (k == nlongs - 1) {
if (t & endmask)
return -EINVAL;
} else if (t)
return -EINVAL;
}
nlongs = BITS_TO_LONGS(MAX_NUMNODES);
endmask = ~0UL;
}
if (maxnode > MAX_NUMNODES && MAX_NUMNODES % BITS_PER_LONG != 0) {
unsigned long valid_mask = endmask;
valid_mask &= ~((1UL << (MAX_NUMNODES % BITS_PER_LONG)) - 1);
if (get_user(t, nmask + nlongs - 1))
return -EFAULT;
if (t & valid_mask)
return -EINVAL;
}
if (copy_from_user(nodes_addr(*nodes), nmask, nlongs*sizeof(unsigned long)))
return -EFAULT;
nodes_addr(*nodes)[nlongs-1] &= endmask;
return 0;
}
/* Copy a kernel node mask to user space */
static int copy_nodes_to_user(unsigned long __user *mask, unsigned long maxnode,
nodemask_t *nodes)
{
unsigned long copy = ALIGN(maxnode-1, 64) / 8;
unsigned int nbytes = BITS_TO_LONGS(nr_node_ids) * sizeof(long);
if (copy > nbytes) {
if (copy > PAGE_SIZE)
return -EINVAL;
if (clear_user((char __user *)mask + nbytes, copy - nbytes))
return -EFAULT;
copy = nbytes;
}
return copy_to_user(mask, nodes_addr(*nodes), copy) ? -EFAULT : 0;
}
static long kernel_mbind(unsigned long start, unsigned long len,
unsigned long mode, const unsigned long __user *nmask,
unsigned long maxnode, unsigned int flags)
{
nodemask_t nodes;
int err;
unsigned short mode_flags;
start = untagged_addr(start);
mode_flags = mode & MPOL_MODE_FLAGS;
mode &= ~MPOL_MODE_FLAGS;
if (mode >= MPOL_MAX)
return -EINVAL;
if ((mode_flags & MPOL_F_STATIC_NODES) &&
(mode_flags & MPOL_F_RELATIVE_NODES))
return -EINVAL;
err = get_nodes(&nodes, nmask, maxnode);
if (err)
return err;
return do_mbind(start, len, mode, mode_flags, &nodes, flags);
}
SYSCALL_DEFINE6(mbind, unsigned long, start, unsigned long, len,
unsigned long, mode, const unsigned long __user *, nmask,
unsigned long, maxnode, unsigned int, flags)
{
return kernel_mbind(start, len, mode, nmask, maxnode, flags);
}
/* Set the process memory policy */
static long kernel_set_mempolicy(int mode, const unsigned long __user *nmask,
unsigned long maxnode)
{
int err;
nodemask_t nodes;
unsigned short flags;
flags = mode & MPOL_MODE_FLAGS;
mode &= ~MPOL_MODE_FLAGS;
if ((unsigned int)mode >= MPOL_MAX)
return -EINVAL;
if ((flags & MPOL_F_STATIC_NODES) && (flags & MPOL_F_RELATIVE_NODES))
return -EINVAL;
err = get_nodes(&nodes, nmask, maxnode);
if (err)
return err;
return do_set_mempolicy(mode, flags, &nodes);
}
SYSCALL_DEFINE3(set_mempolicy, int, mode, const unsigned long __user *, nmask,
unsigned long, maxnode)
{
return kernel_set_mempolicy(mode, nmask, maxnode);
}
static int kernel_migrate_pages(pid_t pid, unsigned long maxnode,
const unsigned long __user *old_nodes,
const unsigned long __user *new_nodes)
{
struct mm_struct *mm = NULL;
struct task_struct *task;
nodemask_t task_nodes;
int err;
nodemask_t *old;
nodemask_t *new;
NODEMASK_SCRATCH(scratch);
if (!scratch)
return -ENOMEM;
old = &scratch->mask1;
new = &scratch->mask2;
err = get_nodes(old, old_nodes, maxnode);
if (err)
goto out;
err = get_nodes(new, new_nodes, maxnode);
if (err)
goto out;
/* Find the mm_struct */
rcu_read_lock();
task = pid ? find_task_by_vpid(pid) : current;
if (!task) {
rcu_read_unlock();
err = -ESRCH;
goto out;
}
get_task_struct(task);
err = -EINVAL;
/*
* Check if this process has the right to modify the specified process.
* Use the regular "ptrace_may_access()" checks.
*/
if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) {
rcu_read_unlock();
err = -EPERM;
goto out_put;
}
rcu_read_unlock();
task_nodes = cpuset_mems_allowed(task);
/* Is the user allowed to access the target nodes? */
if (!nodes_subset(*new, task_nodes) && !capable(CAP_SYS_NICE)) {
err = -EPERM;
goto out_put;
}
task_nodes = cpuset_mems_allowed(current);
nodes_and(*new, *new, task_nodes);
if (nodes_empty(*new))
goto out_put;
err = security_task_movememory(task);
if (err)
goto out_put;
mm = get_task_mm(task);
put_task_struct(task);
if (!mm) {
err = -EINVAL;
goto out;
}
err = do_migrate_pages(mm, old, new,
capable(CAP_SYS_NICE) ? MPOL_MF_MOVE_ALL : MPOL_MF_MOVE);
mmput(mm);
out:
NODEMASK_SCRATCH_FREE(scratch);
return err;
out_put:
put_task_struct(task);
goto out;
}
SYSCALL_DEFINE4(migrate_pages, pid_t, pid, unsigned long, maxnode,
const unsigned long __user *, old_nodes,
const unsigned long __user *, new_nodes)
{
return kernel_migrate_pages(pid, maxnode, old_nodes, new_nodes);
}
/* Retrieve NUMA policy */
static int kernel_get_mempolicy(int __user *policy,
unsigned long __user *nmask,
unsigned long maxnode,
unsigned long addr,
unsigned long flags)
{
int err;
int uninitialized_var(pval);
nodemask_t nodes;
addr = untagged_addr(addr);
if (nmask != NULL && maxnode < nr_node_ids)
return -EINVAL;
err = do_get_mempolicy(&pval, &nodes, addr, flags);
if (err)
return err;
if (policy && put_user(pval, policy))
return -EFAULT;
if (nmask)
err = copy_nodes_to_user(nmask, maxnode, &nodes);
return err;
}
SYSCALL_DEFINE5(get_mempolicy, int __user *, policy,
unsigned long __user *, nmask, unsigned long, maxnode,
unsigned long, addr, unsigned long, flags)
{
return kernel_get_mempolicy(policy, nmask, maxnode, addr, flags);
}
#ifdef CONFIG_COMPAT
COMPAT_SYSCALL_DEFINE5(get_mempolicy, int __user *, policy,
compat_ulong_t __user *, nmask,
compat_ulong_t, maxnode,
compat_ulong_t, addr, compat_ulong_t, flags)
{
long err;
unsigned long __user *nm = NULL;
unsigned long nr_bits, alloc_size;
DECLARE_BITMAP(bm, MAX_NUMNODES);
nr_bits = min_t(unsigned long, maxnode-1, nr_node_ids);
alloc_size = ALIGN(nr_bits, BITS_PER_LONG) / 8;
if (nmask)
nm = compat_alloc_user_space(alloc_size);
err = kernel_get_mempolicy(policy, nm, nr_bits+1, addr, flags);
if (!err && nmask) {
unsigned long copy_size;
copy_size = min_t(unsigned long, sizeof(bm), alloc_size);
err = copy_from_user(bm, nm, copy_size);
/* ensure entire bitmap is zeroed */
err |= clear_user(nmask, ALIGN(maxnode-1, 8) / 8);
err |= compat_put_bitmap(nmask, bm, nr_bits);
}
return err;
}
COMPAT_SYSCALL_DEFINE3(set_mempolicy, int, mode, compat_ulong_t __user *, nmask,
compat_ulong_t, maxnode)
{
unsigned long __user *nm = NULL;
unsigned long nr_bits, alloc_size;
DECLARE_BITMAP(bm, MAX_NUMNODES);
nr_bits = min_t(unsigned long, maxnode-1, MAX_NUMNODES);
alloc_size = ALIGN(nr_bits, BITS_PER_LONG) / 8;
if (nmask) {
if (compat_get_bitmap(bm, nmask, nr_bits))
return -EFAULT;
nm = compat_alloc_user_space(alloc_size);
if (copy_to_user(nm, bm, alloc_size))
return -EFAULT;
}
return kernel_set_mempolicy(mode, nm, nr_bits+1);
}
COMPAT_SYSCALL_DEFINE6(mbind, compat_ulong_t, start, compat_ulong_t, len,
compat_ulong_t, mode, compat_ulong_t __user *, nmask,
compat_ulong_t, maxnode, compat_ulong_t, flags)
{
unsigned long __user *nm = NULL;
unsigned long nr_bits, alloc_size;
nodemask_t bm;
nr_bits = min_t(unsigned long, maxnode-1, MAX_NUMNODES);
alloc_size = ALIGN(nr_bits, BITS_PER_LONG) / 8;
if (nmask) {
if (compat_get_bitmap(nodes_addr(bm), nmask, nr_bits))
return -EFAULT;
nm = compat_alloc_user_space(alloc_size);
if (copy_to_user(nm, nodes_addr(bm), alloc_size))
return -EFAULT;
}
return kernel_mbind(start, len, mode, nm, nr_bits+1, flags);
}
COMPAT_SYSCALL_DEFINE4(migrate_pages, compat_pid_t, pid,
compat_ulong_t, maxnode,
const compat_ulong_t __user *, old_nodes,
const compat_ulong_t __user *, new_nodes)
{
unsigned long __user *old = NULL;
unsigned long __user *new = NULL;
nodemask_t tmp_mask;
unsigned long nr_bits;
unsigned long size;
nr_bits = min_t(unsigned long, maxnode - 1, MAX_NUMNODES);
size = ALIGN(nr_bits, BITS_PER_LONG) / 8;
if (old_nodes) {
if (compat_get_bitmap(nodes_addr(tmp_mask), old_nodes, nr_bits))
return -EFAULT;
old = compat_alloc_user_space(new_nodes ? size * 2 : size);
if (new_nodes)
new = old + size / sizeof(unsigned long);
if (copy_to_user(old, nodes_addr(tmp_mask), size))
return -EFAULT;
}
if (new_nodes) {
if (compat_get_bitmap(nodes_addr(tmp_mask), new_nodes, nr_bits))
return -EFAULT;
if (new == NULL)
new = compat_alloc_user_space(size);
if (copy_to_user(new, nodes_addr(tmp_mask), size))
return -EFAULT;
}
return kernel_migrate_pages(pid, nr_bits + 1, old, new);
}
#endif /* CONFIG_COMPAT */
bool vma_migratable(struct vm_area_struct *vma)
{
if (vma->vm_flags & (VM_IO | VM_PFNMAP))
return false;
/*
* DAX device mappings require predictable access latency, so avoid
* incurring periodic faults.
*/
if (vma_is_dax(vma))
return false;
if (is_vm_hugetlb_page(vma) &&
!hugepage_migration_supported(hstate_vma(vma)))
return false;
/*
* Migration allocates pages in the highest zone. If we cannot
* do so then migration (at least from node to node) is not
* possible.
*/
if (vma->vm_file &&
gfp_zone(mapping_gfp_mask(vma->vm_file->f_mapping))
< policy_zone)
return false;
return true;
}
struct mempolicy *__get_vma_policy(struct vm_area_struct *vma,
unsigned long addr)
{
struct mempolicy *pol = NULL;
if (vma) {
if (vma->vm_ops && vma->vm_ops->get_policy) {
pol = vma->vm_ops->get_policy(vma, addr);
} else if (vma->vm_policy) {
pol = vma->vm_policy;
/*
* shmem_alloc_page() passes MPOL_F_SHARED policy with
* a pseudo vma whose vma->vm_ops=NULL. Take a reference
* count on these policies which will be dropped by
* mpol_cond_put() later
*/
if (mpol_needs_cond_ref(pol))
mpol_get(pol);
}
}
return pol;
}
/*
* get_vma_policy(@vma, @addr)
* @vma: virtual memory area whose policy is sought
* @addr: address in @vma for shared policy lookup
*
* Returns effective policy for a VMA at specified address.
* Falls back to current->mempolicy or system default policy, as necessary.
* Shared policies [those marked as MPOL_F_SHARED] require an extra reference
* count--added by the get_policy() vm_op, as appropriate--to protect against
* freeing by another task. It is the caller's responsibility to free the
* extra reference for shared policies.
*/
static struct mempolicy *get_vma_policy(struct vm_area_struct *vma,
unsigned long addr)
{
struct mempolicy *pol = __get_vma_policy(vma, addr);
if (!pol)
pol = get_task_policy(current);
return pol;
}
bool vma_policy_mof(struct vm_area_struct *vma)
{
struct mempolicy *pol;
if (vma->vm_ops && vma->vm_ops->get_policy) {
bool ret = false;
pol = vma->vm_ops->get_policy(vma, vma->vm_start);
if (pol && (pol->flags & MPOL_F_MOF))
ret = true;
mpol_cond_put(pol);
return ret;
}
pol = vma->vm_policy;
if (!pol)
pol = get_task_policy(current);
return pol->flags & MPOL_F_MOF;
}
static int apply_policy_zone(struct mempolicy *policy, enum zone_type zone)
{
enum zone_type dynamic_policy_zone = policy_zone;
BUG_ON(dynamic_policy_zone == ZONE_MOVABLE);
/*
* if policy->v.nodes has movable memory only,
* we apply policy when gfp_zone(gfp) = ZONE_MOVABLE only.
*
* policy->v.nodes is intersect with node_states[N_MEMORY].
* so if the following test faile, it implies
* policy->v.nodes has movable memory only.
*/
if (!nodes_intersects(policy->v.nodes, node_states[N_HIGH_MEMORY]))
dynamic_policy_zone = ZONE_MOVABLE;
return zone >= dynamic_policy_zone;
}
/*
* Return a nodemask representing a mempolicy for filtering nodes for
* page allocation
*/
static nodemask_t *policy_nodemask(gfp_t gfp, struct mempolicy *policy)
{
/* Lower zones don't get a nodemask applied for MPOL_BIND */
if (unlikely(policy->mode == MPOL_BIND) &&
apply_policy_zone(policy, gfp_zone(gfp)) &&
cpuset_nodemask_valid_mems_allowed(&policy->v.nodes))
return &policy->v.nodes;
return NULL;
}
/* Return the node id preferred by the given mempolicy, or the given id */
static int policy_node(gfp_t gfp, struct mempolicy *policy,
int nd)
{
if (policy->mode == MPOL_PREFERRED && !(policy->flags & MPOL_F_LOCAL))
nd = policy->v.preferred_node;
else {
/*
* __GFP_THISNODE shouldn't even be used with the bind policy
* because we might easily break the expectation to stay on the
* requested node and not break the policy.
*/
WARN_ON_ONCE(policy->mode == MPOL_BIND && (gfp & __GFP_THISNODE));
}
return nd;
}
/* Do dynamic interleaving for a process */
static unsigned interleave_nodes(struct mempolicy *policy)
{
unsigned next;
struct task_struct *me = current;
next = next_node_in(me->il_prev, policy->v.nodes);
if (next < MAX_NUMNODES)
me->il_prev = next;
return next;
}
/*
* Depending on the memory policy provide a node from which to allocate the
* next slab entry.
*/
unsigned int mempolicy_slab_node(void)
{
struct mempolicy *policy;
int node = numa_mem_id();
if (in_interrupt())
return node;
policy = current->mempolicy;
if (!policy || policy->flags & MPOL_F_LOCAL)
return node;
switch (policy->mode) {
case MPOL_PREFERRED:
/*
* handled MPOL_F_LOCAL above
*/
return policy->v.preferred_node;
case MPOL_INTERLEAVE:
return interleave_nodes(policy);
case MPOL_BIND: {
struct zoneref *z;
/*
* Follow bind policy behavior and start allocation at the
* first node.
*/
struct zonelist *zonelist;
enum zone_type highest_zoneidx = gfp_zone(GFP_KERNEL);
zonelist = &NODE_DATA(node)->node_zonelists[ZONELIST_FALLBACK];
z = first_zones_zonelist(zonelist, highest_zoneidx,
&policy->v.nodes);
return z->zone ? zone_to_nid(z->zone) : node;
}
default:
BUG();
}
}
/*
* Do static interleaving for a VMA with known offset @n. Returns the n'th
* node in pol->v.nodes (starting from n=0), wrapping around if n exceeds the
* number of present nodes.
*/
static unsigned offset_il_node(struct mempolicy *pol, unsigned long n)
{
unsigned nnodes = nodes_weight(pol->v.nodes);
unsigned target;
int i;
int nid;
if (!nnodes)
return numa_node_id();
target = (unsigned int)n % nnodes;
nid = first_node(pol->v.nodes);
for (i = 0; i < target; i++)
nid = next_node(nid, pol->v.nodes);
return nid;
}
/* Determine a node number for interleave */
static inline unsigned interleave_nid(struct mempolicy *pol,
struct vm_area_struct *vma, unsigned long addr, int shift)
{
if (vma) {
unsigned long off;
/*
* for small pages, there is no difference between
* shift and PAGE_SHIFT, so the bit-shift is safe.
* for huge pages, since vm_pgoff is in units of small
* pages, we need to shift off the always 0 bits to get
* a useful offset.
*/
BUG_ON(shift < PAGE_SHIFT);
off = vma->vm_pgoff >> (shift - PAGE_SHIFT);
off += (addr - vma->vm_start) >> shift;
return offset_il_node(pol, off);
} else
return interleave_nodes(pol);
}
#ifdef CONFIG_HUGETLBFS
/*
* huge_node(@vma, @addr, @gfp_flags, @mpol)
* @vma: virtual memory area whose policy is sought
* @addr: address in @vma for shared policy lookup and interleave policy
* @gfp_flags: for requested zone
* @mpol: pointer to mempolicy pointer for reference counted mempolicy
* @nodemask: pointer to nodemask pointer for MPOL_BIND nodemask
*
* Returns a nid suitable for a huge page allocation and a pointer
* to the struct mempolicy for conditional unref after allocation.
* If the effective policy is 'BIND, returns a pointer to the mempolicy's
* @nodemask for filtering the zonelist.
*
* Must be protected by read_mems_allowed_begin()
*/
int huge_node(struct vm_area_struct *vma, unsigned long addr, gfp_t gfp_flags,
struct mempolicy **mpol, nodemask_t **nodemask)
{
int nid;
*mpol = get_vma_policy(vma, addr);
*nodemask = NULL; /* assume !MPOL_BIND */
if (unlikely((*mpol)->mode == MPOL_INTERLEAVE)) {
nid = interleave_nid(*mpol, vma, addr,
huge_page_shift(hstate_vma(vma)));
} else {
nid = policy_node(gfp_flags, *mpol, numa_node_id());
if ((*mpol)->mode == MPOL_BIND)
*nodemask = &(*mpol)->v.nodes;
}
return nid;
}
/*
* init_nodemask_of_mempolicy
*
* If the current task's mempolicy is "default" [NULL], return 'false'
* to indicate default policy. Otherwise, extract the policy nodemask
* for 'bind' or 'interleave' policy into the argument nodemask, or
* initialize the argument nodemask to contain the single node for
* 'preferred' or 'local' policy and return 'true' to indicate presence
* of non-default mempolicy.
*
* We don't bother with reference counting the mempolicy [mpol_get/put]
* because the current task is examining it's own mempolicy and a task's
* mempolicy is only ever changed by the task itself.
*
* N.B., it is the caller's responsibility to free a returned nodemask.
*/
bool init_nodemask_of_mempolicy(nodemask_t *mask)
{
struct mempolicy *mempolicy;
int nid;
if (!(mask && current->mempolicy))
return false;
task_lock(current);
mempolicy = current->mempolicy;
switch (mempolicy->mode) {
case MPOL_PREFERRED:
if (mempolicy->flags & MPOL_F_LOCAL)
nid = numa_node_id();
else
nid = mempolicy->v.preferred_node;
init_nodemask_of_node(mask, nid);
break;
case MPOL_BIND:
/* Fall through */
case MPOL_INTERLEAVE:
*mask = mempolicy->v.nodes;
break;
default:
BUG();
}
task_unlock(current);
return true;
}
#endif
/*
* mempolicy_nodemask_intersects
*
* If tsk's mempolicy is "default" [NULL], return 'true' to indicate default
* policy. Otherwise, check for intersection between mask and the policy
* nodemask for 'bind' or 'interleave' policy. For 'perferred' or 'local'
* policy, always return true since it may allocate elsewhere on fallback.
*
* Takes task_lock(tsk) to prevent freeing of its mempolicy.
*/
bool mempolicy_nodemask_intersects(struct task_struct *tsk,
const nodemask_t *mask)
{
struct mempolicy *mempolicy;
bool ret = true;
if (!mask)
return ret;
task_lock(tsk);
mempolicy = tsk->mempolicy;
if (!mempolicy)
goto out;
switch (mempolicy->mode) {
case MPOL_PREFERRED:
/*
* MPOL_PREFERRED and MPOL_F_LOCAL are only preferred nodes to
* allocate from, they may fallback to other nodes when oom.
* Thus, it's possible for tsk to have allocated memory from
* nodes in mask.
*/
break;
case MPOL_BIND:
case MPOL_INTERLEAVE:
ret = nodes_intersects(mempolicy->v.nodes, *mask);
break;
default:
BUG();
}
out:
task_unlock(tsk);
return ret;
}
/* Allocate a page in interleaved policy.
Own path because it needs to do special accounting. */
static struct page *alloc_page_interleave(gfp_t gfp, unsigned order,
unsigned nid)
{
struct page *page;
page = __alloc_pages(gfp, order, nid);
/* skip NUMA_INTERLEAVE_HIT counter update if numa stats is disabled */
if (!static_branch_likely(&vm_numa_stat_key))
return page;
if (page && page_to_nid(page) == nid) {
preempt_disable();
__inc_numa_state(page_zone(page), NUMA_INTERLEAVE_HIT);
preempt_enable();
}
return page;
}
/**
* alloc_pages_vma - Allocate a page for a VMA.
*
* @gfp:
* %GFP_USER user allocation.
* %GFP_KERNEL kernel allocations,
* %GFP_HIGHMEM highmem/user allocations,
* %GFP_FS allocation should not call back into a file system.
* %GFP_ATOMIC don't sleep.
*
* @order:Order of the GFP allocation.
* @vma: Pointer to VMA or NULL if not available.
* @addr: Virtual Address of the allocation. Must be inside the VMA.
* @node: Which node to prefer for allocation (modulo policy).
* @hugepage: for hugepages try only the preferred node if possible
*
* This function allocates a page from the kernel page pool and applies
* a NUMA policy associated with the VMA or the current process.
* When VMA is not NULL caller must hold down_read on the mmap_sem of the
* mm_struct of the VMA to prevent it from going away. Should be used for
* all allocations for pages that will be mapped into user space. Returns
* NULL when no page can be allocated.
*/
struct page *
alloc_pages_vma(gfp_t gfp, int order, struct vm_area_struct *vma,
unsigned long addr, int node, bool hugepage)
{
struct mempolicy *pol;
struct page *page;
int preferred_nid;
nodemask_t *nmask;
pol = get_vma_policy(vma, addr);
if (pol->mode == MPOL_INTERLEAVE) {
unsigned nid;
nid = interleave_nid(pol, vma, addr, PAGE_SHIFT + order);
mpol_cond_put(pol);
page = alloc_page_interleave(gfp, order, nid);
goto out;
}
if (unlikely(IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) && hugepage)) {
int hpage_node = node;
/*
* For hugepage allocation and non-interleave policy which
* allows the current node (or other explicitly preferred
* node) we only try to allocate from the current/preferred
* node and don't fall back to other nodes, as the cost of
* remote accesses would likely offset THP benefits.
*
* If the policy is interleave, or does not allow the current
* node in its nodemask, we allocate the standard way.
*/
if (pol->mode == MPOL_PREFERRED && !(pol->flags & MPOL_F_LOCAL))
hpage_node = pol->v.preferred_node;
nmask = policy_nodemask(gfp, pol);
if (!nmask || node_isset(hpage_node, *nmask)) {
mpol_cond_put(pol);
/*
* First, try to allocate THP only on local node, but
* don't reclaim unnecessarily, just compact.
*/
page = __alloc_pages_node(hpage_node,
gfp | __GFP_THISNODE | __GFP_NORETRY, order);
/*
* If hugepage allocations are configured to always
* synchronous compact or the vma has been madvised
* to prefer hugepage backing, retry allowing remote
* memory with both reclaim and compact as well.
*/
if (!page && (gfp & __GFP_DIRECT_RECLAIM))
page = __alloc_pages_node(hpage_node,
gfp, order);
goto out;
}
}
nmask = policy_nodemask(gfp, pol);
preferred_nid = policy_node(gfp, pol, node);
page = __alloc_pages_nodemask(gfp, order, preferred_nid, nmask);
mpol_cond_put(pol);
out:
return page;
}
EXPORT_SYMBOL(alloc_pages_vma);
/**
* alloc_pages_current - Allocate pages.
*
* @gfp:
* %GFP_USER user allocation,
* %GFP_KERNEL kernel allocation,
* %GFP_HIGHMEM highmem allocation,
* %GFP_FS don't call back into a file system.
* %GFP_ATOMIC don't sleep.
* @order: Power of two of allocation size in pages. 0 is a single page.
*
* Allocate a page from the kernel page pool. When not in
* interrupt context and apply the current process NUMA policy.
* Returns NULL when no page can be allocated.
*/
struct page *alloc_pages_current(gfp_t gfp, unsigned order)
{
struct mempolicy *pol = &default_policy;
struct page *page;
if (!in_interrupt() && !(gfp & __GFP_THISNODE))
pol = get_task_policy(current);
/*
* No reference counting needed for current->mempolicy
* nor system default_policy
*/
if (pol->mode == MPOL_INTERLEAVE)
page = alloc_page_interleave(gfp, order, interleave_nodes(pol));
else
page = __alloc_pages_nodemask(gfp, order,
policy_node(gfp, pol, numa_node_id()),
policy_nodemask(gfp, pol));
return page;
}
EXPORT_SYMBOL(alloc_pages_current);
int vma_dup_policy(struct vm_area_struct *src, struct vm_area_struct *dst)
{
struct mempolicy *pol = mpol_dup(vma_policy(src));
if (IS_ERR(pol))
return PTR_ERR(pol);
dst->vm_policy = pol;
return 0;
}
/*
* If mpol_dup() sees current->cpuset == cpuset_being_rebound, then it
* rebinds the mempolicy its copying by calling mpol_rebind_policy()
* with the mems_allowed returned by cpuset_mems_allowed(). This
* keeps mempolicies cpuset relative after its cpuset moves. See
* further kernel/cpuset.c update_nodemask().
*
* current's mempolicy may be rebinded by the other task(the task that changes
* cpuset's mems), so we needn't do rebind work for current task.
*/
/* Slow path of a mempolicy duplicate */
struct mempolicy *__mpol_dup(struct mempolicy *old)
{
struct mempolicy *new = kmem_cache_alloc(policy_cache, GFP_KERNEL);
if (!new)
return ERR_PTR(-ENOMEM);
/* task's mempolicy is protected by alloc_lock */
if (old == current->mempolicy) {
task_lock(current);
*new = *old;
task_unlock(current);
} else
*new = *old;
if (current_cpuset_is_being_rebound()) {
nodemask_t mems = cpuset_mems_allowed(current);
mpol_rebind_policy(new, &mems);
}
atomic_set(&new->refcnt, 1);
return new;
}
/* Slow path of a mempolicy comparison */
bool __mpol_equal(struct mempolicy *a, struct mempolicy *b)
{
if (!a || !b)
return false;
if (a->mode != b->mode)
return false;
if (a->flags != b->flags)
return false;
if (mpol_store_user_nodemask(a))
if (!nodes_equal(a->w.user_nodemask, b->w.user_nodemask))
return false;
switch (a->mode) {
case MPOL_BIND:
/* Fall through */
case MPOL_INTERLEAVE:
return !!nodes_equal(a->v.nodes, b->v.nodes);
case MPOL_PREFERRED:
/* a's ->flags is the same as b's */
if (a->flags & MPOL_F_LOCAL)
return true;
return a->v.preferred_node == b->v.preferred_node;
default:
BUG();
return false;
}
}
/*
* Shared memory backing store policy support.
*
* Remember policies even when nobody has shared memory mapped.
* The policies are kept in Red-Black tree linked from the inode.
* They are protected by the sp->lock rwlock, which should be held
* for any accesses to the tree.
*/
/*
* lookup first element intersecting start-end. Caller holds sp->lock for
* reading or for writing
*/
static struct sp_node *
sp_lookup(struct shared_policy *sp, unsigned long start, unsigned long end)
{
struct rb_node *n = sp->root.rb_node;
while (n) {
struct sp_node *p = rb_entry(n, struct sp_node, nd);
if (start >= p->end)
n = n->rb_right;
else if (end <= p->start)
n = n->rb_left;
else
break;
}
if (!n)
return NULL;
for (;;) {
struct sp_node *w = NULL;
struct rb_node *prev = rb_prev(n);
if (!prev)
break;
w = rb_entry(prev, struct sp_node, nd);
if (w->end <= start)
break;
n = prev;
}
return rb_entry(n, struct sp_node, nd);
}
/*
* Insert a new shared policy into the list. Caller holds sp->lock for
* writing.
*/
static void sp_insert(struct shared_policy *sp, struct sp_node *new)
{
struct rb_node **p = &sp->root.rb_node;
struct rb_node *parent = NULL;
struct sp_node *nd;
while (*p) {
parent = *p;
nd = rb_entry(parent, struct sp_node, nd);
if (new->start < nd->start)
p = &(*p)->rb_left;
else if (new->end > nd->end)
p = &(*p)->rb_right;
else
BUG();
}
rb_link_node(&new->nd, parent, p);
rb_insert_color(&new->nd, &sp->root);
pr_debug("inserting %lx-%lx: %d\n", new->start, new->end,
new->policy ? new->policy->mode : 0);
}
/* Find shared policy intersecting idx */
struct mempolicy *
mpol_shared_policy_lookup(struct shared_policy *sp, unsigned long idx)
{
struct mempolicy *pol = NULL;
struct sp_node *sn;
if (!sp->root.rb_node)
return NULL;
read_lock(&sp->lock);
sn = sp_lookup(sp, idx, idx+1);
if (sn) {
mpol_get(sn->policy);
pol = sn->policy;
}
read_unlock(&sp->lock);
return pol;
}
static void sp_free(struct sp_node *n)
{
mpol_put(n->policy);
kmem_cache_free(sn_cache, n);
}
/**
* mpol_misplaced - check whether current page node is valid in policy
*
* @page: page to be checked
* @vma: vm area where page mapped
* @addr: virtual address where page mapped
*
* Lookup current policy node id for vma,addr and "compare to" page's
* node id.
*
* Returns:
* -1 - not misplaced, page is in the right node
* node - node id where the page should be
*
* Policy determination "mimics" alloc_page_vma().
* Called from fault path where we know the vma and faulting address.
*/
int mpol_misplaced(struct page *page, struct vm_area_struct *vma, unsigned long addr)
{
struct mempolicy *pol;
struct zoneref *z;
int curnid = page_to_nid(page);
unsigned long pgoff;
int thiscpu = raw_smp_processor_id();
int thisnid = cpu_to_node(thiscpu);
int polnid = NUMA_NO_NODE;
int ret = -1;
pol = get_vma_policy(vma, addr);
if (!(pol->flags & MPOL_F_MOF))
goto out;
switch (pol->mode) {
case MPOL_INTERLEAVE:
pgoff = vma->vm_pgoff;
pgoff += (addr - vma->vm_start) >> PAGE_SHIFT;
polnid = offset_il_node(pol, pgoff);
break;
case MPOL_PREFERRED:
if (pol->flags & MPOL_F_LOCAL)
polnid = numa_node_id();
else
polnid = pol->v.preferred_node;
break;
case MPOL_BIND:
/*
* allows binding to multiple nodes.
* use current page if in policy nodemask,
* else select nearest allowed node, if any.
* If no allowed nodes, use current [!misplaced].
*/
if (node_isset(curnid, pol->v.nodes))
goto out;
z = first_zones_zonelist(
node_zonelist(numa_node_id(), GFP_HIGHUSER),
gfp_zone(GFP_HIGHUSER),
&pol->v.nodes);
polnid = zone_to_nid(z->zone);
break;
default:
BUG();
}
/* Migrate the page towards the node whose CPU is referencing it */
if (pol->flags & MPOL_F_MORON) {
polnid = thisnid;
if (!should_numa_migrate_memory(current, page, curnid, thiscpu))
goto out;
}
if (curnid != polnid)
ret = polnid;
out:
mpol_cond_put(pol);
return ret;
}
/*
* Drop the (possibly final) reference to task->mempolicy. It needs to be
* dropped after task->mempolicy is set to NULL so that any allocation done as
* part of its kmem_cache_free(), such as by KASAN, doesn't reference a freed
* policy.
*/
void mpol_put_task_policy(struct task_struct *task)
{
struct mempolicy *pol;
task_lock(task);
pol = task->mempolicy;
task->mempolicy = NULL;
task_unlock(task);
mpol_put(pol);
}
static void sp_delete(struct shared_policy *sp, struct sp_node *n)
{
pr_debug("deleting %lx-l%lx\n", n->start, n->end);
rb_erase(&n->nd, &sp->root);
sp_free(n);
}
static void sp_node_init(struct sp_node *node, unsigned long start,
unsigned long end, struct mempolicy *pol)
{
node->start = start;
node->end = end;
node->policy = pol;
}
static struct sp_node *sp_alloc(unsigned long start, unsigned long end,
struct mempolicy *pol)
{
struct sp_node *n;
struct mempolicy *newpol;
n = kmem_cache_alloc(sn_cache, GFP_KERNEL);
if (!n)
return NULL;
newpol = mpol_dup(pol);
if (IS_ERR(newpol)) {
kmem_cache_free(sn_cache, n);
return NULL;
}
newpol->flags |= MPOL_F_SHARED;
sp_node_init(n, start, end, newpol);
return n;
}
/* Replace a policy range. */
static int shared_policy_replace(struct shared_policy *sp, unsigned long start,
unsigned long end, struct sp_node *new)
{
struct sp_node *n;
struct sp_node *n_new = NULL;
struct mempolicy *mpol_new = NULL;
int ret = 0;
restart:
write_lock(&sp->lock);
n = sp_lookup(sp, start, end);
/* Take care of old policies in the same range. */
while (n && n->start < end) {
struct rb_node *next = rb_next(&n->nd);
if (n->start >= start) {
if (n->end <= end)
sp_delete(sp, n);
else
n->start = end;
} else {
/* Old policy spanning whole new range. */
if (n->end > end) {
if (!n_new)
goto alloc_new;
*mpol_new = *n->policy;
atomic_set(&mpol_new->refcnt, 1);
sp_node_init(n_new, end, n->end, mpol_new);
n->end = start;
sp_insert(sp, n_new);
n_new = NULL;
mpol_new = NULL;
break;
} else
n->end = start;
}
if (!next)
break;
n = rb_entry(next, struct sp_node, nd);
}
if (new)
sp_insert(sp, new);
write_unlock(&sp->lock);
ret = 0;
err_out:
if (mpol_new)
mpol_put(mpol_new);
if (n_new)
kmem_cache_free(sn_cache, n_new);
return ret;
alloc_new:
write_unlock(&sp->lock);
ret = -ENOMEM;
n_new = kmem_cache_alloc(sn_cache, GFP_KERNEL);
if (!n_new)
goto err_out;
mpol_new = kmem_cache_alloc(policy_cache, GFP_KERNEL);
if (!mpol_new)
goto err_out;
goto restart;
}
/**
* mpol_shared_policy_init - initialize shared policy for inode
* @sp: pointer to inode shared policy
* @mpol: struct mempolicy to install
*
* Install non-NULL @mpol in inode's shared policy rb-tree.
* On entry, the current task has a reference on a non-NULL @mpol.
* This must be released on exit.
* This is called at get_inode() calls and we can use GFP_KERNEL.
*/
void mpol_shared_policy_init(struct shared_policy *sp, struct mempolicy *mpol)
{
int ret;
sp->root = RB_ROOT; /* empty tree == default mempolicy */
rwlock_init(&sp->lock);
if (mpol) {
struct vm_area_struct pvma;
struct mempolicy *new;
NODEMASK_SCRATCH(scratch);
if (!scratch)
goto put_mpol;
/* contextualize the tmpfs mount point mempolicy */
new = mpol_new(mpol->mode, mpol->flags, &mpol->w.user_nodemask);
if (IS_ERR(new))
goto free_scratch; /* no valid nodemask intersection */
task_lock(current);
ret = mpol_set_nodemask(new, &mpol->w.user_nodemask, scratch);
task_unlock(current);
if (ret)
goto put_new;
/* Create pseudo-vma that contains just the policy */
vma_init(&pvma, NULL);
pvma.vm_end = TASK_SIZE; /* policy covers entire file */
mpol_set_shared_policy(sp, &pvma, new); /* adds ref */
put_new:
mpol_put(new); /* drop initial ref */
free_scratch:
NODEMASK_SCRATCH_FREE(scratch);
put_mpol:
mpol_put(mpol); /* drop our incoming ref on sb mpol */
}
}
int mpol_set_shared_policy(struct shared_policy *info,
struct vm_area_struct *vma, struct mempolicy *npol)
{
int err;
struct sp_node *new = NULL;
unsigned long sz = vma_pages(vma);
pr_debug("set_shared_policy %lx sz %lu %d %d %lx\n",
vma->vm_pgoff,
sz, npol ? npol->mode : -1,
npol ? npol->flags : -1,
npol ? nodes_addr(npol->v.nodes)[0] : NUMA_NO_NODE);
if (npol) {
new = sp_alloc(vma->vm_pgoff, vma->vm_pgoff + sz, npol);
if (!new)
return -ENOMEM;
}
err = shared_policy_replace(info, vma->vm_pgoff, vma->vm_pgoff+sz, new);
if (err && new)
sp_free(new);
return err;
}
/* Free a backing policy store on inode delete. */
void mpol_free_shared_policy(struct shared_policy *p)
{
struct sp_node *n;
struct rb_node *next;
if (!p->root.rb_node)
return;
write_lock(&p->lock);
next = rb_first(&p->root);
while (next) {
n = rb_entry(next, struct sp_node, nd);
next = rb_next(&n->nd);
sp_delete(p, n);
}
write_unlock(&p->lock);
}
#ifdef CONFIG_NUMA_BALANCING
static int __initdata numabalancing_override;
static void __init check_numabalancing_enable(void)
{
bool numabalancing_default = false;
if (IS_ENABLED(CONFIG_NUMA_BALANCING_DEFAULT_ENABLED))
numabalancing_default = true;
/* Parsed by setup_numabalancing. override == 1 enables, -1 disables */
if (numabalancing_override)
set_numabalancing_state(numabalancing_override == 1);
if (num_online_nodes() > 1 && !numabalancing_override) {
pr_info("%s automatic NUMA balancing. Configure with numa_balancing= or the kernel.numa_balancing sysctl\n",
numabalancing_default ? "Enabling" : "Disabling");
set_numabalancing_state(numabalancing_default);
}
}
static int __init setup_numabalancing(char *str)
{
int ret = 0;
if (!str)
goto out;
if (!strcmp(str, "enable")) {
numabalancing_override = 1;
ret = 1;
} else if (!strcmp(str, "disable")) {
numabalancing_override = -1;
ret = 1;
}
out:
if (!ret)
pr_warn("Unable to parse numa_balancing=\n");
return ret;
}
__setup("numa_balancing=", setup_numabalancing);
#else
static inline void __init check_numabalancing_enable(void)
{
}
#endif /* CONFIG_NUMA_BALANCING */
/* assumes fs == KERNEL_DS */
void __init numa_policy_init(void)
{
nodemask_t interleave_nodes;
unsigned long largest = 0;
int nid, prefer = 0;
policy_cache = kmem_cache_create("numa_policy",
sizeof(struct mempolicy),
0, SLAB_PANIC, NULL);
sn_cache = kmem_cache_create("shared_policy_node",
sizeof(struct sp_node),
0, SLAB_PANIC, NULL);
for_each_node(nid) {
preferred_node_policy[nid] = (struct mempolicy) {
.refcnt = ATOMIC_INIT(1),
.mode = MPOL_PREFERRED,
.flags = MPOL_F_MOF | MPOL_F_MORON,
.v = { .preferred_node = nid, },
};
}
/*
* Set interleaving policy for system init. Interleaving is only
* enabled across suitably sized nodes (default is >= 16MB), or
* fall back to the largest node if they're all smaller.
*/
nodes_clear(interleave_nodes);
for_each_node_state(nid, N_MEMORY) {
unsigned long total_pages = node_present_pages(nid);
/* Preserve the largest node */
if (largest < total_pages) {
largest = total_pages;
prefer = nid;
}
/* Interleave this node? */
if ((total_pages << PAGE_SHIFT) >= (16 << 20))
node_set(nid, interleave_nodes);
}
/* All too small, use the largest */
if (unlikely(nodes_empty(interleave_nodes)))
node_set(prefer, interleave_nodes);
if (do_set_mempolicy(MPOL_INTERLEAVE, 0, &interleave_nodes))
pr_err("%s: interleaving failed\n", __func__);
check_numabalancing_enable();
}
/* Reset policy of current process to default */
void numa_default_policy(void)
{
do_set_mempolicy(MPOL_DEFAULT, 0, NULL);
}
/*
* Parse and format mempolicy from/to strings
*/
/*
* "local" is implemented internally by MPOL_PREFERRED with MPOL_F_LOCAL flag.
*/
static const char * const policy_modes[] =
{
[MPOL_DEFAULT] = "default",
[MPOL_PREFERRED] = "prefer",
[MPOL_BIND] = "bind",
[MPOL_INTERLEAVE] = "interleave",
[MPOL_LOCAL] = "local",
};
#ifdef CONFIG_TMPFS
/**
* mpol_parse_str - parse string to mempolicy, for tmpfs mpol mount option.
* @str: string containing mempolicy to parse
* @mpol: pointer to struct mempolicy pointer, returned on success.
*
* Format of input:
* <mode>[=<flags>][:<nodelist>]
*
* On success, returns 0, else 1
*/
int mpol_parse_str(char *str, struct mempolicy **mpol)
{
struct mempolicy *new = NULL;
unsigned short mode_flags;
nodemask_t nodes;
char *nodelist = strchr(str, ':');
char *flags = strchr(str, '=');
int err = 1, mode;
if (flags)
*flags++ = '\0'; /* terminate mode string */
if (nodelist) {
/* NUL-terminate mode or flags string */
*nodelist++ = '\0';
if (nodelist_parse(nodelist, nodes))
goto out;
if (!nodes_subset(nodes, node_states[N_MEMORY]))
goto out;
} else
nodes_clear(nodes);
mode = match_string(policy_modes, MPOL_MAX, str);
if (mode < 0)
goto out;
switch (mode) {
case MPOL_PREFERRED:
/*
* Insist on a nodelist of one node only, although later
* we use first_node(nodes) to grab a single node, so here
* nodelist (or nodes) cannot be empty.
*/
if (nodelist) {
char *rest = nodelist;
while (isdigit(*rest))
rest++;
if (*rest)
goto out;
if (nodes_empty(nodes))
goto out;
}
break;
case MPOL_INTERLEAVE:
/*
* Default to online nodes with memory if no nodelist
*/
if (!nodelist)
nodes = node_states[N_MEMORY];
break;
case MPOL_LOCAL:
/*
* Don't allow a nodelist; mpol_new() checks flags
*/
if (nodelist)
goto out;
mode = MPOL_PREFERRED;
break;
case MPOL_DEFAULT:
/*
* Insist on a empty nodelist
*/
if (!nodelist)
err = 0;
goto out;
case MPOL_BIND:
/*
* Insist on a nodelist
*/
if (!nodelist)
goto out;
}
mode_flags = 0;
if (flags) {
/*
* Currently, we only support two mutually exclusive
* mode flags.
*/
if (!strcmp(flags, "static"))
mode_flags |= MPOL_F_STATIC_NODES;
else if (!strcmp(flags, "relative"))
mode_flags |= MPOL_F_RELATIVE_NODES;
else
goto out;
}
new = mpol_new(mode, mode_flags, &nodes);
if (IS_ERR(new))
goto out;
/*
* Save nodes for mpol_to_str() to show the tmpfs mount options
* for /proc/mounts, /proc/pid/mounts and /proc/pid/mountinfo.
*/
if (mode != MPOL_PREFERRED)
new->v.nodes = nodes;
else if (nodelist)
new->v.preferred_node = first_node(nodes);
else
new->flags |= MPOL_F_LOCAL;
/*
* Save nodes for contextualization: this will be used to "clone"
* the mempolicy in a specific context [cpuset] at a later time.
*/
new->w.user_nodemask = nodes;
err = 0;
out:
/* Restore string for error message */
if (nodelist)
*--nodelist = ':';
if (flags)
*--flags = '=';
if (!err)
*mpol = new;
return err;
}
#endif /* CONFIG_TMPFS */
/**
* mpol_to_str - format a mempolicy structure for printing
* @buffer: to contain formatted mempolicy string
* @maxlen: length of @buffer
* @pol: pointer to mempolicy to be formatted
*
* Convert @pol into a string. If @buffer is too short, truncate the string.
* Recommend a @maxlen of at least 32 for the longest mode, "interleave", the
* longest flag, "relative", and to display at least a few node ids.
*/
void mpol_to_str(char *buffer, int maxlen, struct mempolicy *pol)
{
char *p = buffer;
nodemask_t nodes = NODE_MASK_NONE;
unsigned short mode = MPOL_DEFAULT;
unsigned short flags = 0;
if (pol && pol != &default_policy && !(pol->flags & MPOL_F_MORON)) {
mode = pol->mode;
flags = pol->flags;
}
switch (mode) {
case MPOL_DEFAULT:
break;
case MPOL_PREFERRED:
if (flags & MPOL_F_LOCAL)
mode = MPOL_LOCAL;
else
node_set(pol->v.preferred_node, nodes);
break;
case MPOL_BIND:
case MPOL_INTERLEAVE:
nodes = pol->v.nodes;
break;
default:
WARN_ON_ONCE(1);
snprintf(p, maxlen, "unknown");
return;
}
p += snprintf(p, maxlen, "%s", policy_modes[mode]);
if (flags & MPOL_MODE_FLAGS) {
p += snprintf(p, buffer + maxlen - p, "=");
/*
* Currently, the only defined flags are mutually exclusive
*/
if (flags & MPOL_F_STATIC_NODES)
p += snprintf(p, buffer + maxlen - p, "static");
else if (flags & MPOL_F_RELATIVE_NODES)
p += snprintf(p, buffer + maxlen - p, "relative");
}
if (!nodes_empty(nodes))
p += scnprintf(p, buffer + maxlen - p, ":%*pbl",
nodemask_pr_args(&nodes));
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_2457_0 |
crossvul-cpp_data_bad_4036_0 | /*
* QEMU Executable loader
*
* Copyright (c) 2006 Fabrice Bellard
*
* 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.
*
* Gunzip functionality in this file is derived from u-boot:
*
* (C) Copyright 2008 Semihalf
*
* (C) Copyright 2000-2005
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include "qemu/osdep.h"
#include "qapi/error.h"
#include "hw/hw.h"
#include "disas/disas.h"
#include "monitor/monitor.h"
#include "sysemu/sysemu.h"
#include "uboot_image.h"
#include "hw/loader.h"
#include "hw/nvram/fw_cfg.h"
#include "exec/memory.h"
#include "exec/address-spaces.h"
#include "hw/boards.h"
#include "qemu/cutils.h"
#include <zlib.h>
static int roms_loaded;
/* return the size or -1 if error */
int64_t get_image_size(const char *filename)
{
int fd;
int64_t size;
fd = open(filename, O_RDONLY | O_BINARY);
if (fd < 0)
return -1;
size = lseek(fd, 0, SEEK_END);
close(fd);
return size;
}
/* return the size or -1 if error */
ssize_t load_image_size(const char *filename, void *addr, size_t size)
{
int fd;
ssize_t actsize, l = 0;
fd = open(filename, O_RDONLY | O_BINARY);
if (fd < 0) {
return -1;
}
while ((actsize = read(fd, addr + l, size - l)) > 0) {
l += actsize;
}
close(fd);
return actsize < 0 ? -1 : l;
}
/* read()-like version */
ssize_t read_targphys(const char *name,
int fd, hwaddr dst_addr, size_t nbytes)
{
uint8_t *buf;
ssize_t did;
buf = g_malloc(nbytes);
did = read(fd, buf, nbytes);
if (did > 0)
rom_add_blob_fixed("read", buf, did, dst_addr);
g_free(buf);
return did;
}
int load_image_targphys(const char *filename,
hwaddr addr, uint64_t max_sz)
{
return load_image_targphys_as(filename, addr, max_sz, NULL);
}
/* return the size or -1 if error */
int load_image_targphys_as(const char *filename,
hwaddr addr, uint64_t max_sz, AddressSpace *as)
{
int size;
size = get_image_size(filename);
if (size < 0 || size > max_sz) {
return -1;
}
if (size > 0) {
if (rom_add_file_fixed_as(filename, addr, -1, as) < 0) {
return -1;
}
}
return size;
}
int load_image_mr(const char *filename, MemoryRegion *mr)
{
int size;
if (!memory_access_is_direct(mr, false)) {
/* Can only load an image into RAM or ROM */
return -1;
}
size = get_image_size(filename);
if (size < 0 || size > memory_region_size(mr)) {
return -1;
}
if (size > 0) {
if (rom_add_file_mr(filename, mr, -1) < 0) {
return -1;
}
}
return size;
}
void pstrcpy_targphys(const char *name, hwaddr dest, int buf_size,
const char *source)
{
const char *nulp;
char *ptr;
if (buf_size <= 0) return;
nulp = memchr(source, 0, buf_size);
if (nulp) {
rom_add_blob_fixed(name, source, (nulp - source) + 1, dest);
} else {
rom_add_blob_fixed(name, source, buf_size, dest);
ptr = rom_ptr(dest + buf_size - 1, sizeof(*ptr));
*ptr = 0;
}
}
/* A.OUT loader */
struct exec
{
uint32_t a_info; /* Use macros N_MAGIC, etc for access */
uint32_t a_text; /* length of text, in bytes */
uint32_t a_data; /* length of data, in bytes */
uint32_t a_bss; /* length of uninitialized data area, in bytes */
uint32_t a_syms; /* length of symbol table data in file, in bytes */
uint32_t a_entry; /* start address */
uint32_t a_trsize; /* length of relocation info for text, in bytes */
uint32_t a_drsize; /* length of relocation info for data, in bytes */
};
static void bswap_ahdr(struct exec *e)
{
bswap32s(&e->a_info);
bswap32s(&e->a_text);
bswap32s(&e->a_data);
bswap32s(&e->a_bss);
bswap32s(&e->a_syms);
bswap32s(&e->a_entry);
bswap32s(&e->a_trsize);
bswap32s(&e->a_drsize);
}
#define N_MAGIC(exec) ((exec).a_info & 0xffff)
#define OMAGIC 0407
#define NMAGIC 0410
#define ZMAGIC 0413
#define QMAGIC 0314
#define _N_HDROFF(x) (1024 - sizeof (struct exec))
#define N_TXTOFF(x) \
(N_MAGIC(x) == ZMAGIC ? _N_HDROFF((x)) + sizeof (struct exec) : \
(N_MAGIC(x) == QMAGIC ? 0 : sizeof (struct exec)))
#define N_TXTADDR(x, target_page_size) (N_MAGIC(x) == QMAGIC ? target_page_size : 0)
#define _N_SEGMENT_ROUND(x, target_page_size) (((x) + target_page_size - 1) & ~(target_page_size - 1))
#define _N_TXTENDADDR(x, target_page_size) (N_TXTADDR(x, target_page_size)+(x).a_text)
#define N_DATADDR(x, target_page_size) \
(N_MAGIC(x)==OMAGIC? (_N_TXTENDADDR(x, target_page_size)) \
: (_N_SEGMENT_ROUND (_N_TXTENDADDR(x, target_page_size), target_page_size)))
int load_aout(const char *filename, hwaddr addr, int max_sz,
int bswap_needed, hwaddr target_page_size)
{
int fd;
ssize_t size, ret;
struct exec e;
uint32_t magic;
fd = open(filename, O_RDONLY | O_BINARY);
if (fd < 0)
return -1;
size = read(fd, &e, sizeof(e));
if (size < 0)
goto fail;
if (bswap_needed) {
bswap_ahdr(&e);
}
magic = N_MAGIC(e);
switch (magic) {
case ZMAGIC:
case QMAGIC:
case OMAGIC:
if (e.a_text + e.a_data > max_sz)
goto fail;
lseek(fd, N_TXTOFF(e), SEEK_SET);
size = read_targphys(filename, fd, addr, e.a_text + e.a_data);
if (size < 0)
goto fail;
break;
case NMAGIC:
if (N_DATADDR(e, target_page_size) + e.a_data > max_sz)
goto fail;
lseek(fd, N_TXTOFF(e), SEEK_SET);
size = read_targphys(filename, fd, addr, e.a_text);
if (size < 0)
goto fail;
ret = read_targphys(filename, fd, addr + N_DATADDR(e, target_page_size),
e.a_data);
if (ret < 0)
goto fail;
size += ret;
break;
default:
goto fail;
}
close(fd);
return size;
fail:
close(fd);
return -1;
}
/* ELF loader */
static void *load_at(int fd, off_t offset, size_t size)
{
void *ptr;
if (lseek(fd, offset, SEEK_SET) < 0)
return NULL;
ptr = g_malloc(size);
if (read(fd, ptr, size) != size) {
g_free(ptr);
return NULL;
}
return ptr;
}
#ifdef ELF_CLASS
#undef ELF_CLASS
#endif
#define ELF_CLASS ELFCLASS32
#include "elf.h"
#define SZ 32
#define elf_word uint32_t
#define elf_sword int32_t
#define bswapSZs bswap32s
#include "hw/elf_ops.h"
#undef elfhdr
#undef elf_phdr
#undef elf_shdr
#undef elf_sym
#undef elf_rela
#undef elf_note
#undef elf_word
#undef elf_sword
#undef bswapSZs
#undef SZ
#define elfhdr elf64_hdr
#define elf_phdr elf64_phdr
#define elf_note elf64_note
#define elf_shdr elf64_shdr
#define elf_sym elf64_sym
#define elf_rela elf64_rela
#define elf_word uint64_t
#define elf_sword int64_t
#define bswapSZs bswap64s
#define SZ 64
#include "hw/elf_ops.h"
const char *load_elf_strerror(int error)
{
switch (error) {
case 0:
return "No error";
case ELF_LOAD_FAILED:
return "Failed to load ELF";
case ELF_LOAD_NOT_ELF:
return "The image is not ELF";
case ELF_LOAD_WRONG_ARCH:
return "The image is from incompatible architecture";
case ELF_LOAD_WRONG_ENDIAN:
return "The image has incorrect endianness";
default:
return "Unknown error";
}
}
void load_elf_hdr(const char *filename, void *hdr, bool *is64, Error **errp)
{
int fd;
uint8_t e_ident_local[EI_NIDENT];
uint8_t *e_ident;
size_t hdr_size, off;
bool is64l;
if (!hdr) {
hdr = e_ident_local;
}
e_ident = hdr;
fd = open(filename, O_RDONLY | O_BINARY);
if (fd < 0) {
error_setg_errno(errp, errno, "Failed to open file: %s", filename);
return;
}
if (read(fd, hdr, EI_NIDENT) != EI_NIDENT) {
error_setg_errno(errp, errno, "Failed to read file: %s", filename);
goto fail;
}
if (e_ident[0] != ELFMAG0 ||
e_ident[1] != ELFMAG1 ||
e_ident[2] != ELFMAG2 ||
e_ident[3] != ELFMAG3) {
error_setg(errp, "Bad ELF magic");
goto fail;
}
is64l = e_ident[EI_CLASS] == ELFCLASS64;
hdr_size = is64l ? sizeof(Elf64_Ehdr) : sizeof(Elf32_Ehdr);
if (is64) {
*is64 = is64l;
}
off = EI_NIDENT;
while (hdr != e_ident_local && off < hdr_size) {
size_t br = read(fd, hdr + off, hdr_size - off);
switch (br) {
case 0:
error_setg(errp, "File too short: %s", filename);
goto fail;
case -1:
error_setg_errno(errp, errno, "Failed to read file: %s",
filename);
goto fail;
}
off += br;
}
fail:
close(fd);
}
/* return < 0 if error, otherwise the number of bytes loaded in memory */
int load_elf(const char *filename,
uint64_t (*elf_note_fn)(void *, void *, bool),
uint64_t (*translate_fn)(void *, uint64_t),
void *translate_opaque, uint64_t *pentry, uint64_t *lowaddr,
uint64_t *highaddr, int big_endian, int elf_machine,
int clear_lsb, int data_swab)
{
return load_elf_as(filename, elf_note_fn, translate_fn, translate_opaque,
pentry, lowaddr, highaddr, big_endian, elf_machine,
clear_lsb, data_swab, NULL);
}
/* return < 0 if error, otherwise the number of bytes loaded in memory */
int load_elf_as(const char *filename,
uint64_t (*elf_note_fn)(void *, void *, bool),
uint64_t (*translate_fn)(void *, uint64_t),
void *translate_opaque, uint64_t *pentry, uint64_t *lowaddr,
uint64_t *highaddr, int big_endian, int elf_machine,
int clear_lsb, int data_swab, AddressSpace *as)
{
return load_elf_ram(filename, elf_note_fn, translate_fn, translate_opaque,
pentry, lowaddr, highaddr, big_endian, elf_machine,
clear_lsb, data_swab, as, true);
}
/* return < 0 if error, otherwise the number of bytes loaded in memory */
int load_elf_ram(const char *filename,
uint64_t (*elf_note_fn)(void *, void *, bool),
uint64_t (*translate_fn)(void *, uint64_t),
void *translate_opaque, uint64_t *pentry, uint64_t *lowaddr,
uint64_t *highaddr, int big_endian, int elf_machine,
int clear_lsb, int data_swab, AddressSpace *as,
bool load_rom)
{
return load_elf_ram_sym(filename, elf_note_fn,
translate_fn, translate_opaque,
pentry, lowaddr, highaddr, big_endian,
elf_machine, clear_lsb, data_swab, as,
load_rom, NULL);
}
/* return < 0 if error, otherwise the number of bytes loaded in memory */
int load_elf_ram_sym(const char *filename,
uint64_t (*elf_note_fn)(void *, void *, bool),
uint64_t (*translate_fn)(void *, uint64_t),
void *translate_opaque, uint64_t *pentry,
uint64_t *lowaddr, uint64_t *highaddr, int big_endian,
int elf_machine, int clear_lsb, int data_swab,
AddressSpace *as, bool load_rom, symbol_fn_t sym_cb)
{
int fd, data_order, target_data_order, must_swab, ret = ELF_LOAD_FAILED;
uint8_t e_ident[EI_NIDENT];
fd = open(filename, O_RDONLY | O_BINARY);
if (fd < 0) {
perror(filename);
return -1;
}
if (read(fd, e_ident, sizeof(e_ident)) != sizeof(e_ident))
goto fail;
if (e_ident[0] != ELFMAG0 ||
e_ident[1] != ELFMAG1 ||
e_ident[2] != ELFMAG2 ||
e_ident[3] != ELFMAG3) {
ret = ELF_LOAD_NOT_ELF;
goto fail;
}
#ifdef HOST_WORDS_BIGENDIAN
data_order = ELFDATA2MSB;
#else
data_order = ELFDATA2LSB;
#endif
must_swab = data_order != e_ident[EI_DATA];
if (big_endian) {
target_data_order = ELFDATA2MSB;
} else {
target_data_order = ELFDATA2LSB;
}
if (target_data_order != e_ident[EI_DATA]) {
ret = ELF_LOAD_WRONG_ENDIAN;
goto fail;
}
lseek(fd, 0, SEEK_SET);
if (e_ident[EI_CLASS] == ELFCLASS64) {
ret = load_elf64(filename, fd, elf_note_fn,
translate_fn, translate_opaque, must_swab,
pentry, lowaddr, highaddr, elf_machine, clear_lsb,
data_swab, as, load_rom, sym_cb);
} else {
ret = load_elf32(filename, fd, elf_note_fn,
translate_fn, translate_opaque, must_swab,
pentry, lowaddr, highaddr, elf_machine, clear_lsb,
data_swab, as, load_rom, sym_cb);
}
fail:
close(fd);
return ret;
}
static void bswap_uboot_header(uboot_image_header_t *hdr)
{
#ifndef HOST_WORDS_BIGENDIAN
bswap32s(&hdr->ih_magic);
bswap32s(&hdr->ih_hcrc);
bswap32s(&hdr->ih_time);
bswap32s(&hdr->ih_size);
bswap32s(&hdr->ih_load);
bswap32s(&hdr->ih_ep);
bswap32s(&hdr->ih_dcrc);
#endif
}
#define ZALLOC_ALIGNMENT 16
static void *zalloc(void *x, unsigned items, unsigned size)
{
void *p;
size *= items;
size = (size + ZALLOC_ALIGNMENT - 1) & ~(ZALLOC_ALIGNMENT - 1);
p = g_malloc(size);
return (p);
}
static void zfree(void *x, void *addr)
{
g_free(addr);
}
#define HEAD_CRC 2
#define EXTRA_FIELD 4
#define ORIG_NAME 8
#define COMMENT 0x10
#define RESERVED 0xe0
#define DEFLATED 8
ssize_t gunzip(void *dst, size_t dstlen, uint8_t *src, size_t srclen)
{
z_stream s;
ssize_t dstbytes;
int r, i, flags;
/* skip header */
i = 10;
flags = src[3];
if (src[2] != DEFLATED || (flags & RESERVED) != 0) {
puts ("Error: Bad gzipped data\n");
return -1;
}
if ((flags & EXTRA_FIELD) != 0)
i = 12 + src[10] + (src[11] << 8);
if ((flags & ORIG_NAME) != 0)
while (src[i++] != 0)
;
if ((flags & COMMENT) != 0)
while (src[i++] != 0)
;
if ((flags & HEAD_CRC) != 0)
i += 2;
if (i >= srclen) {
puts ("Error: gunzip out of data in header\n");
return -1;
}
s.zalloc = zalloc;
s.zfree = zfree;
r = inflateInit2(&s, -MAX_WBITS);
if (r != Z_OK) {
printf ("Error: inflateInit2() returned %d\n", r);
return (-1);
}
s.next_in = src + i;
s.avail_in = srclen - i;
s.next_out = dst;
s.avail_out = dstlen;
r = inflate(&s, Z_FINISH);
if (r != Z_OK && r != Z_STREAM_END) {
printf ("Error: inflate() returned %d\n", r);
return -1;
}
dstbytes = s.next_out - (unsigned char *) dst;
inflateEnd(&s);
return dstbytes;
}
/* Load a U-Boot image. */
static int load_uboot_image(const char *filename, hwaddr *ep, hwaddr *loadaddr,
int *is_linux, uint8_t image_type,
uint64_t (*translate_fn)(void *, uint64_t),
void *translate_opaque, AddressSpace *as)
{
int fd;
int size;
hwaddr address;
uboot_image_header_t h;
uboot_image_header_t *hdr = &h;
uint8_t *data = NULL;
int ret = -1;
int do_uncompress = 0;
fd = open(filename, O_RDONLY | O_BINARY);
if (fd < 0)
return -1;
size = read(fd, hdr, sizeof(uboot_image_header_t));
if (size < sizeof(uboot_image_header_t)) {
goto out;
}
bswap_uboot_header(hdr);
if (hdr->ih_magic != IH_MAGIC)
goto out;
if (hdr->ih_type != image_type) {
if (!(image_type == IH_TYPE_KERNEL &&
hdr->ih_type == IH_TYPE_KERNEL_NOLOAD)) {
fprintf(stderr, "Wrong image type %d, expected %d\n", hdr->ih_type,
image_type);
goto out;
}
}
/* TODO: Implement other image types. */
switch (hdr->ih_type) {
case IH_TYPE_KERNEL_NOLOAD:
if (!loadaddr || *loadaddr == LOAD_UIMAGE_LOADADDR_INVALID) {
fprintf(stderr, "this image format (kernel_noload) cannot be "
"loaded on this machine type");
goto out;
}
hdr->ih_load = *loadaddr + sizeof(*hdr);
hdr->ih_ep += hdr->ih_load;
/* fall through */
case IH_TYPE_KERNEL:
address = hdr->ih_load;
if (translate_fn) {
address = translate_fn(translate_opaque, address);
}
if (loadaddr) {
*loadaddr = hdr->ih_load;
}
switch (hdr->ih_comp) {
case IH_COMP_NONE:
break;
case IH_COMP_GZIP:
do_uncompress = 1;
break;
default:
fprintf(stderr,
"Unable to load u-boot images with compression type %d\n",
hdr->ih_comp);
goto out;
}
if (ep) {
*ep = hdr->ih_ep;
}
/* TODO: Check CPU type. */
if (is_linux) {
if (hdr->ih_os == IH_OS_LINUX) {
*is_linux = 1;
} else {
*is_linux = 0;
}
}
break;
case IH_TYPE_RAMDISK:
address = *loadaddr;
break;
default:
fprintf(stderr, "Unsupported u-boot image type %d\n", hdr->ih_type);
goto out;
}
data = g_malloc(hdr->ih_size);
if (read(fd, data, hdr->ih_size) != hdr->ih_size) {
fprintf(stderr, "Error reading file\n");
goto out;
}
if (do_uncompress) {
uint8_t *compressed_data;
size_t max_bytes;
ssize_t bytes;
compressed_data = data;
max_bytes = UBOOT_MAX_GUNZIP_BYTES;
data = g_malloc(max_bytes);
bytes = gunzip(data, max_bytes, compressed_data, hdr->ih_size);
g_free(compressed_data);
if (bytes < 0) {
fprintf(stderr, "Unable to decompress gzipped image!\n");
goto out;
}
hdr->ih_size = bytes;
}
rom_add_blob_fixed_as(filename, data, hdr->ih_size, address, as);
ret = hdr->ih_size;
out:
g_free(data);
close(fd);
return ret;
}
int load_uimage(const char *filename, hwaddr *ep, hwaddr *loadaddr,
int *is_linux,
uint64_t (*translate_fn)(void *, uint64_t),
void *translate_opaque)
{
return load_uboot_image(filename, ep, loadaddr, is_linux, IH_TYPE_KERNEL,
translate_fn, translate_opaque, NULL);
}
int load_uimage_as(const char *filename, hwaddr *ep, hwaddr *loadaddr,
int *is_linux,
uint64_t (*translate_fn)(void *, uint64_t),
void *translate_opaque, AddressSpace *as)
{
return load_uboot_image(filename, ep, loadaddr, is_linux, IH_TYPE_KERNEL,
translate_fn, translate_opaque, as);
}
/* Load a ramdisk. */
int load_ramdisk(const char *filename, hwaddr addr, uint64_t max_sz)
{
return load_ramdisk_as(filename, addr, max_sz, NULL);
}
int load_ramdisk_as(const char *filename, hwaddr addr, uint64_t max_sz,
AddressSpace *as)
{
return load_uboot_image(filename, NULL, &addr, NULL, IH_TYPE_RAMDISK,
NULL, NULL, as);
}
/* Load a gzip-compressed kernel to a dynamically allocated buffer. */
int load_image_gzipped_buffer(const char *filename, uint64_t max_sz,
uint8_t **buffer)
{
uint8_t *compressed_data = NULL;
uint8_t *data = NULL;
gsize len;
ssize_t bytes;
int ret = -1;
if (!g_file_get_contents(filename, (char **) &compressed_data, &len,
NULL)) {
goto out;
}
/* Is it a gzip-compressed file? */
if (len < 2 ||
compressed_data[0] != 0x1f ||
compressed_data[1] != 0x8b) {
goto out;
}
if (max_sz > LOAD_IMAGE_MAX_GUNZIP_BYTES) {
max_sz = LOAD_IMAGE_MAX_GUNZIP_BYTES;
}
data = g_malloc(max_sz);
bytes = gunzip(data, max_sz, compressed_data, len);
if (bytes < 0) {
fprintf(stderr, "%s: unable to decompress gzipped kernel file\n",
filename);
goto out;
}
/* trim to actual size and return to caller */
*buffer = g_realloc(data, bytes);
ret = bytes;
/* ownership has been transferred to caller */
data = NULL;
out:
g_free(compressed_data);
g_free(data);
return ret;
}
/* Load a gzip-compressed kernel. */
int load_image_gzipped(const char *filename, hwaddr addr, uint64_t max_sz)
{
int bytes;
uint8_t *data;
bytes = load_image_gzipped_buffer(filename, max_sz, &data);
if (bytes != -1) {
rom_add_blob_fixed(filename, data, bytes, addr);
g_free(data);
}
return bytes;
}
/*
* Functions for reboot-persistent memory regions.
* - used for vga bios and option roms.
* - also linux kernel (-kernel / -initrd).
*/
typedef struct Rom Rom;
struct Rom {
char *name;
char *path;
/* datasize is the amount of memory allocated in "data". If datasize is less
* than romsize, it means that the area from datasize to romsize is filled
* with zeros.
*/
size_t romsize;
size_t datasize;
uint8_t *data;
MemoryRegion *mr;
AddressSpace *as;
int isrom;
char *fw_dir;
char *fw_file;
bool committed;
hwaddr addr;
QTAILQ_ENTRY(Rom) next;
};
static FWCfgState *fw_cfg;
static QTAILQ_HEAD(, Rom) roms = QTAILQ_HEAD_INITIALIZER(roms);
/* rom->data must be heap-allocated (do not use with rom_add_elf_program()) */
static void rom_free(Rom *rom)
{
g_free(rom->data);
g_free(rom->path);
g_free(rom->name);
g_free(rom->fw_dir);
g_free(rom->fw_file);
g_free(rom);
}
static inline bool rom_order_compare(Rom *rom, Rom *item)
{
return ((uintptr_t)(void *)rom->as > (uintptr_t)(void *)item->as) ||
(rom->as == item->as && rom->addr >= item->addr);
}
static void rom_insert(Rom *rom)
{
Rom *item;
if (roms_loaded) {
hw_error ("ROM images must be loaded at startup\n");
}
/* The user didn't specify an address space, this is the default */
if (!rom->as) {
rom->as = &address_space_memory;
}
rom->committed = false;
/* List is ordered by load address in the same address space */
QTAILQ_FOREACH(item, &roms, next) {
if (rom_order_compare(rom, item)) {
continue;
}
QTAILQ_INSERT_BEFORE(item, rom, next);
return;
}
QTAILQ_INSERT_TAIL(&roms, rom, next);
}
static void fw_cfg_resized(const char *id, uint64_t length, void *host)
{
if (fw_cfg) {
fw_cfg_modify_file(fw_cfg, id + strlen("/rom@"), host, length);
}
}
static void *rom_set_mr(Rom *rom, Object *owner, const char *name, bool ro)
{
void *data;
rom->mr = g_malloc(sizeof(*rom->mr));
memory_region_init_resizeable_ram(rom->mr, owner, name,
rom->datasize, rom->romsize,
fw_cfg_resized,
&error_fatal);
memory_region_set_readonly(rom->mr, ro);
vmstate_register_ram_global(rom->mr);
data = memory_region_get_ram_ptr(rom->mr);
memcpy(data, rom->data, rom->datasize);
return data;
}
int rom_add_file(const char *file, const char *fw_dir,
hwaddr addr, int32_t bootindex,
bool option_rom, MemoryRegion *mr,
AddressSpace *as)
{
MachineClass *mc = MACHINE_GET_CLASS(qdev_get_machine());
Rom *rom;
int rc, fd = -1;
char devpath[100];
if (as && mr) {
fprintf(stderr, "Specifying an Address Space and Memory Region is " \
"not valid when loading a rom\n");
/* We haven't allocated anything so we don't need any cleanup */
return -1;
}
rom = g_malloc0(sizeof(*rom));
rom->name = g_strdup(file);
rom->path = qemu_find_file(QEMU_FILE_TYPE_BIOS, rom->name);
rom->as = as;
if (rom->path == NULL) {
rom->path = g_strdup(file);
}
fd = open(rom->path, O_RDONLY | O_BINARY);
if (fd == -1) {
fprintf(stderr, "Could not open option rom '%s': %s\n",
rom->path, strerror(errno));
goto err;
}
if (fw_dir) {
rom->fw_dir = g_strdup(fw_dir);
rom->fw_file = g_strdup(file);
}
rom->addr = addr;
rom->romsize = lseek(fd, 0, SEEK_END);
if (rom->romsize == -1) {
fprintf(stderr, "rom: file %-20s: get size error: %s\n",
rom->name, strerror(errno));
goto err;
}
rom->datasize = rom->romsize;
rom->data = g_malloc0(rom->datasize);
lseek(fd, 0, SEEK_SET);
rc = read(fd, rom->data, rom->datasize);
if (rc != rom->datasize) {
fprintf(stderr, "rom: file %-20s: read error: rc=%d (expected %zd)\n",
rom->name, rc, rom->datasize);
goto err;
}
close(fd);
rom_insert(rom);
if (rom->fw_file && fw_cfg) {
const char *basename;
char fw_file_name[FW_CFG_MAX_FILE_PATH];
void *data;
basename = strrchr(rom->fw_file, '/');
if (basename) {
basename++;
} else {
basename = rom->fw_file;
}
snprintf(fw_file_name, sizeof(fw_file_name), "%s/%s", rom->fw_dir,
basename);
snprintf(devpath, sizeof(devpath), "/rom@%s", fw_file_name);
if ((!option_rom || mc->option_rom_has_mr) && mc->rom_file_has_mr) {
data = rom_set_mr(rom, OBJECT(fw_cfg), devpath, true);
} else {
data = rom->data;
}
fw_cfg_add_file(fw_cfg, fw_file_name, data, rom->romsize);
} else {
if (mr) {
rom->mr = mr;
snprintf(devpath, sizeof(devpath), "/rom@%s", file);
} else {
snprintf(devpath, sizeof(devpath), "/rom@" TARGET_FMT_plx, addr);
}
}
add_boot_device_path(bootindex, NULL, devpath);
return 0;
err:
if (fd != -1)
close(fd);
rom_free(rom);
return -1;
}
MemoryRegion *rom_add_blob(const char *name, const void *blob, size_t len,
size_t max_len, hwaddr addr, const char *fw_file_name,
FWCfgCallback fw_callback, void *callback_opaque,
AddressSpace *as, bool read_only)
{
MachineClass *mc = MACHINE_GET_CLASS(qdev_get_machine());
Rom *rom;
MemoryRegion *mr = NULL;
rom = g_malloc0(sizeof(*rom));
rom->name = g_strdup(name);
rom->as = as;
rom->addr = addr;
rom->romsize = max_len ? max_len : len;
rom->datasize = len;
rom->data = g_malloc0(rom->datasize);
memcpy(rom->data, blob, len);
rom_insert(rom);
if (fw_file_name && fw_cfg) {
char devpath[100];
void *data;
if (read_only) {
snprintf(devpath, sizeof(devpath), "/rom@%s", fw_file_name);
} else {
snprintf(devpath, sizeof(devpath), "/ram@%s", fw_file_name);
}
if (mc->rom_file_has_mr) {
data = rom_set_mr(rom, OBJECT(fw_cfg), devpath, read_only);
mr = rom->mr;
} else {
data = rom->data;
}
fw_cfg_add_file_callback(fw_cfg, fw_file_name,
fw_callback, NULL, callback_opaque,
data, rom->datasize, read_only);
}
return mr;
}
/* This function is specific for elf program because we don't need to allocate
* all the rom. We just allocate the first part and the rest is just zeros. This
* is why romsize and datasize are different. Also, this function seize the
* memory ownership of "data", so we don't have to allocate and copy the buffer.
*/
int rom_add_elf_program(const char *name, void *data, size_t datasize,
size_t romsize, hwaddr addr, AddressSpace *as)
{
Rom *rom;
rom = g_malloc0(sizeof(*rom));
rom->name = g_strdup(name);
rom->addr = addr;
rom->datasize = datasize;
rom->romsize = romsize;
rom->data = data;
rom->as = as;
rom_insert(rom);
return 0;
}
int rom_add_vga(const char *file)
{
return rom_add_file(file, "vgaroms", 0, -1, true, NULL, NULL);
}
int rom_add_option(const char *file, int32_t bootindex)
{
return rom_add_file(file, "genroms", 0, bootindex, true, NULL, NULL);
}
static void rom_reset(void *unused)
{
Rom *rom;
QTAILQ_FOREACH(rom, &roms, next) {
if (rom->fw_file) {
continue;
}
if (rom->data == NULL) {
continue;
}
if (rom->mr) {
void *host = memory_region_get_ram_ptr(rom->mr);
memcpy(host, rom->data, rom->datasize);
} else {
address_space_write_rom(rom->as, rom->addr, MEMTXATTRS_UNSPECIFIED,
rom->data, rom->datasize);
}
if (rom->isrom) {
/* rom needs to be written only once */
g_free(rom->data);
rom->data = NULL;
}
/*
* The rom loader is really on the same level as firmware in the guest
* shadowing a ROM into RAM. Such a shadowing mechanism needs to ensure
* that the instruction cache for that new region is clear, so that the
* CPU definitely fetches its instructions from the just written data.
*/
cpu_flush_icache_range(rom->addr, rom->datasize);
}
}
int rom_check_and_register_reset(void)
{
hwaddr addr = 0;
MemoryRegionSection section;
Rom *rom;
AddressSpace *as = NULL;
QTAILQ_FOREACH(rom, &roms, next) {
if (rom->fw_file) {
continue;
}
if (!rom->mr) {
if ((addr > rom->addr) && (as == rom->as)) {
fprintf(stderr, "rom: requested regions overlap "
"(rom %s. free=0x" TARGET_FMT_plx
", addr=0x" TARGET_FMT_plx ")\n",
rom->name, addr, rom->addr);
return -1;
}
addr = rom->addr;
addr += rom->romsize;
as = rom->as;
}
section = memory_region_find(rom->mr ? rom->mr : get_system_memory(),
rom->addr, 1);
rom->isrom = int128_nz(section.size) && memory_region_is_rom(section.mr);
memory_region_unref(section.mr);
}
qemu_register_reset(rom_reset, NULL);
roms_loaded = 1;
return 0;
}
void rom_set_fw(FWCfgState *f)
{
fw_cfg = f;
}
void rom_set_order_override(int order)
{
if (!fw_cfg)
return;
fw_cfg_set_order_override(fw_cfg, order);
}
void rom_reset_order_override(void)
{
if (!fw_cfg)
return;
fw_cfg_reset_order_override(fw_cfg);
}
void rom_transaction_begin(void)
{
Rom *rom;
/* Ignore ROMs added without the transaction API */
QTAILQ_FOREACH(rom, &roms, next) {
rom->committed = true;
}
}
void rom_transaction_end(bool commit)
{
Rom *rom;
Rom *tmp;
QTAILQ_FOREACH_SAFE(rom, &roms, next, tmp) {
if (rom->committed) {
continue;
}
if (commit) {
rom->committed = true;
} else {
QTAILQ_REMOVE(&roms, rom, next);
rom_free(rom);
}
}
}
static Rom *find_rom(hwaddr addr, size_t size)
{
Rom *rom;
QTAILQ_FOREACH(rom, &roms, next) {
if (rom->fw_file) {
continue;
}
if (rom->mr) {
continue;
}
if (rom->addr > addr) {
continue;
}
if (rom->addr + rom->romsize < addr + size) {
continue;
}
return rom;
}
return NULL;
}
/*
* Copies memory from registered ROMs to dest. Any memory that is contained in
* a ROM between addr and addr + size is copied. Note that this can involve
* multiple ROMs, which need not start at addr and need not end at addr + size.
*/
int rom_copy(uint8_t *dest, hwaddr addr, size_t size)
{
hwaddr end = addr + size;
uint8_t *s, *d = dest;
size_t l = 0;
Rom *rom;
QTAILQ_FOREACH(rom, &roms, next) {
if (rom->fw_file) {
continue;
}
if (rom->mr) {
continue;
}
if (rom->addr + rom->romsize < addr) {
continue;
}
if (rom->addr > end) {
break;
}
d = dest + (rom->addr - addr);
s = rom->data;
l = rom->datasize;
if ((d + l) > (dest + size)) {
l = dest - d;
}
if (l > 0) {
memcpy(d, s, l);
}
if (rom->romsize > rom->datasize) {
/* If datasize is less than romsize, it means that we didn't
* allocate all the ROM because the trailing data are only zeros.
*/
d += l;
l = rom->romsize - rom->datasize;
if ((d + l) > (dest + size)) {
/* Rom size doesn't fit in the destination area. Adjust to avoid
* overflow.
*/
l = dest - d;
}
if (l > 0) {
memset(d, 0x0, l);
}
}
}
return (d + l) - dest;
}
void *rom_ptr(hwaddr addr, size_t size)
{
Rom *rom;
rom = find_rom(addr, size);
if (!rom || !rom->data)
return NULL;
return rom->data + (addr - rom->addr);
}
void hmp_info_roms(Monitor *mon, const QDict *qdict)
{
Rom *rom;
QTAILQ_FOREACH(rom, &roms, next) {
if (rom->mr) {
monitor_printf(mon, "%s"
" size=0x%06zx name=\"%s\"\n",
memory_region_name(rom->mr),
rom->romsize,
rom->name);
} else if (!rom->fw_file) {
monitor_printf(mon, "addr=" TARGET_FMT_plx
" size=0x%06zx mem=%s name=\"%s\"\n",
rom->addr, rom->romsize,
rom->isrom ? "rom" : "ram",
rom->name);
} else {
monitor_printf(mon, "fw=%s/%s"
" size=0x%06zx name=\"%s\"\n",
rom->fw_dir,
rom->fw_file,
rom->romsize,
rom->name);
}
}
}
typedef enum HexRecord HexRecord;
enum HexRecord {
DATA_RECORD = 0,
EOF_RECORD,
EXT_SEG_ADDR_RECORD,
START_SEG_ADDR_RECORD,
EXT_LINEAR_ADDR_RECORD,
START_LINEAR_ADDR_RECORD,
};
/* Each record contains a 16-bit address which is combined with the upper 16
* bits of the implicit "next address" to form a 32-bit address.
*/
#define NEXT_ADDR_MASK 0xffff0000
#define DATA_FIELD_MAX_LEN 0xff
#define LEN_EXCEPT_DATA 0x5
/* 0x5 = sizeof(byte_count) + sizeof(address) + sizeof(record_type) +
* sizeof(checksum) */
typedef struct {
uint8_t byte_count;
uint16_t address;
uint8_t record_type;
uint8_t data[DATA_FIELD_MAX_LEN];
uint8_t checksum;
} HexLine;
/* return 0 or -1 if error */
static bool parse_record(HexLine *line, uint8_t *our_checksum, const uint8_t c,
uint32_t *index, const bool in_process)
{
/* +-------+---------------+-------+---------------------+--------+
* | byte | |record | | |
* | count | address | type | data |checksum|
* +-------+---------------+-------+---------------------+--------+
* ^ ^ ^ ^ ^ ^
* |1 byte | 2 bytes |1 byte | 0-255 bytes | 1 byte |
*/
uint8_t value = 0;
uint32_t idx = *index;
/* ignore space */
if (g_ascii_isspace(c)) {
return true;
}
if (!g_ascii_isxdigit(c) || !in_process) {
return false;
}
value = g_ascii_xdigit_value(c);
value = (idx & 0x1) ? (value & 0xf) : (value << 4);
if (idx < 2) {
line->byte_count |= value;
} else if (2 <= idx && idx < 6) {
line->address <<= 4;
line->address += g_ascii_xdigit_value(c);
} else if (6 <= idx && idx < 8) {
line->record_type |= value;
} else if (8 <= idx && idx < 8 + 2 * line->byte_count) {
line->data[(idx - 8) >> 1] |= value;
} else if (8 + 2 * line->byte_count <= idx &&
idx < 10 + 2 * line->byte_count) {
line->checksum |= value;
} else {
return false;
}
*our_checksum += value;
++(*index);
return true;
}
typedef struct {
const char *filename;
HexLine line;
uint8_t *bin_buf;
hwaddr *start_addr;
int total_size;
uint32_t next_address_to_write;
uint32_t current_address;
uint32_t current_rom_index;
uint32_t rom_start_address;
AddressSpace *as;
} HexParser;
/* return size or -1 if error */
static int handle_record_type(HexParser *parser)
{
HexLine *line = &(parser->line);
switch (line->record_type) {
case DATA_RECORD:
parser->current_address =
(parser->next_address_to_write & NEXT_ADDR_MASK) | line->address;
/* verify this is a contiguous block of memory */
if (parser->current_address != parser->next_address_to_write) {
if (parser->current_rom_index != 0) {
rom_add_blob_fixed_as(parser->filename, parser->bin_buf,
parser->current_rom_index,
parser->rom_start_address, parser->as);
}
parser->rom_start_address = parser->current_address;
parser->current_rom_index = 0;
}
/* copy from line buffer to output bin_buf */
memcpy(parser->bin_buf + parser->current_rom_index, line->data,
line->byte_count);
parser->current_rom_index += line->byte_count;
parser->total_size += line->byte_count;
/* save next address to write */
parser->next_address_to_write =
parser->current_address + line->byte_count;
break;
case EOF_RECORD:
if (parser->current_rom_index != 0) {
rom_add_blob_fixed_as(parser->filename, parser->bin_buf,
parser->current_rom_index,
parser->rom_start_address, parser->as);
}
return parser->total_size;
case EXT_SEG_ADDR_RECORD:
case EXT_LINEAR_ADDR_RECORD:
if (line->byte_count != 2 && line->address != 0) {
return -1;
}
if (parser->current_rom_index != 0) {
rom_add_blob_fixed_as(parser->filename, parser->bin_buf,
parser->current_rom_index,
parser->rom_start_address, parser->as);
}
/* save next address to write,
* in case of non-contiguous block of memory */
parser->next_address_to_write = (line->data[0] << 12) |
(line->data[1] << 4);
if (line->record_type == EXT_LINEAR_ADDR_RECORD) {
parser->next_address_to_write <<= 12;
}
parser->rom_start_address = parser->next_address_to_write;
parser->current_rom_index = 0;
break;
case START_SEG_ADDR_RECORD:
if (line->byte_count != 4 && line->address != 0) {
return -1;
}
/* x86 16-bit CS:IP segmented addressing */
*(parser->start_addr) = (((line->data[0] << 8) | line->data[1]) << 4) +
((line->data[2] << 8) | line->data[3]);
break;
case START_LINEAR_ADDR_RECORD:
if (line->byte_count != 4 && line->address != 0) {
return -1;
}
*(parser->start_addr) = ldl_be_p(line->data);
break;
default:
return -1;
}
return parser->total_size;
}
/* return size or -1 if error */
static int parse_hex_blob(const char *filename, hwaddr *addr, uint8_t *hex_blob,
size_t hex_blob_size, AddressSpace *as)
{
bool in_process = false; /* avoid re-enter and
* check whether record begin with ':' */
uint8_t *end = hex_blob + hex_blob_size;
uint8_t our_checksum = 0;
uint32_t record_index = 0;
HexParser parser = {
.filename = filename,
.bin_buf = g_malloc(hex_blob_size),
.start_addr = addr,
.as = as,
};
rom_transaction_begin();
for (; hex_blob < end; ++hex_blob) {
switch (*hex_blob) {
case '\r':
case '\n':
if (!in_process) {
break;
}
in_process = false;
if ((LEN_EXCEPT_DATA + parser.line.byte_count) * 2 !=
record_index ||
our_checksum != 0) {
parser.total_size = -1;
goto out;
}
if (handle_record_type(&parser) == -1) {
parser.total_size = -1;
goto out;
}
break;
/* start of a new record. */
case ':':
memset(&parser.line, 0, sizeof(HexLine));
in_process = true;
record_index = 0;
break;
/* decoding lines */
default:
if (!parse_record(&parser.line, &our_checksum, *hex_blob,
&record_index, in_process)) {
parser.total_size = -1;
goto out;
}
break;
}
}
out:
g_free(parser.bin_buf);
rom_transaction_end(parser.total_size != -1);
return parser.total_size;
}
/* return size or -1 if error */
int load_targphys_hex_as(const char *filename, hwaddr *entry, AddressSpace *as)
{
gsize hex_blob_size;
gchar *hex_blob;
int total_size = 0;
if (!g_file_get_contents(filename, &hex_blob, &hex_blob_size, NULL)) {
return -1;
}
total_size = parse_hex_blob(filename, entry, (uint8_t *)hex_blob,
hex_blob_size, as);
g_free(hex_blob);
return total_size;
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_4036_0 |
crossvul-cpp_data_bad_522_0 | /*
* rfbserver.c - deal with server-side of the RFB protocol.
*/
/*
* Copyright (C) 2011-2012 D. R. Commander
* Copyright (C) 2005 Rohit Kumar, Johannes E. Schindelin
* Copyright (C) 2002 RealVNC Ltd.
* OSXvnc Copyright (C) 2001 Dan McGuirk <mcguirk@incompleteness.net>.
* Original Xvnc code Copyright (C) 1999 AT&T Laboratories Cambridge.
* All Rights Reserved.
*
* This 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 software 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 software; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
* USA.
*/
#ifdef __STRICT_ANSI__
#define _BSD_SOURCE
#define _POSIX_SOURCE
#define _XOPEN_SOURCE 600
#endif
#include <stdio.h>
#include <string.h>
#include <rfb/rfb.h>
#include <rfb/rfbregion.h>
#include "private.h"
#include "rfb/rfbconfig.h"
#ifdef LIBVNCSERVER_HAVE_FCNTL_H
#include <fcntl.h>
#endif
#ifdef WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#include <io.h>
#define write(sock,buf,len) send(sock,buf,len,0)
#else
#ifdef LIBVNCSERVER_HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <pwd.h>
#ifdef LIBVNCSERVER_HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef LIBVNCSERVER_HAVE_NETINET_IN_H
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>
#include <arpa/inet.h>
#endif
#endif
#ifdef DEBUGPROTO
#undef DEBUGPROTO
#define DEBUGPROTO(x) x
#else
#define DEBUGPROTO(x)
#endif
#include <stdarg.h>
#include <scale.h>
/* stst() */
#include <sys/types.h>
#include <sys/stat.h>
#if LIBVNCSERVER_HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifndef WIN32
/* readdir() */
#include <dirent.h>
#endif
/* errno */
#include <errno.h>
/* strftime() */
#include <time.h>
#ifdef LIBVNCSERVER_WITH_WEBSOCKETS
#include "rfbssl.h"
#endif
#ifdef _MSC_VER
#define snprintf _snprintf /* Missing in MSVC */
/* Prevent POSIX deprecation warnings */
#define close _close
#define strdup _strdup
#endif
#ifdef WIN32
#include <direct.h>
#ifdef __MINGW32__
#define mkdir(path, perms) mkdir(path) /* Omit the perms argument to match POSIX signature */
#else /* MSVC and other windows compilers */
#define mkdir(path, perms) _mkdir(path) /* Omit the perms argument to match POSIX signature */
#endif /* __MINGW32__ else... */
#ifndef S_ISDIR
#define S_ISDIR(m) (((m) & S_IFDIR) == S_IFDIR)
#endif
#endif
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
/*
* Map of quality levels to provide compatibility with TightVNC/TigerVNC
* clients. This emulates the behavior of the TigerVNC Server.
*/
static const int tight2turbo_qual[10] = {
15, 29, 41, 42, 62, 77, 79, 86, 92, 100
};
static const int tight2turbo_subsamp[10] = {
1, 1, 1, 2, 2, 2, 0, 0, 0, 0
};
#endif
static void rfbProcessClientProtocolVersion(rfbClientPtr cl);
static void rfbProcessClientNormalMessage(rfbClientPtr cl);
static void rfbProcessClientInitMessage(rfbClientPtr cl);
#ifdef LIBVNCSERVER_HAVE_LIBPTHREAD
void rfbIncrClientRef(rfbClientPtr cl)
{
LOCK(cl->refCountMutex);
cl->refCount++;
UNLOCK(cl->refCountMutex);
}
void rfbDecrClientRef(rfbClientPtr cl)
{
LOCK(cl->refCountMutex);
cl->refCount--;
if(cl->refCount<=0) /* just to be sure also < 0 */
TSIGNAL(cl->deleteCond);
UNLOCK(cl->refCountMutex);
}
#else
void rfbIncrClientRef(rfbClientPtr cl) {}
void rfbDecrClientRef(rfbClientPtr cl) {}
#endif
#ifdef LIBVNCSERVER_HAVE_LIBPTHREAD
static MUTEX(rfbClientListMutex);
#endif
struct rfbClientIterator {
rfbClientPtr next;
rfbScreenInfoPtr screen;
rfbBool closedToo;
};
void
rfbClientListInit(rfbScreenInfoPtr rfbScreen)
{
if(sizeof(rfbBool)!=1) {
/* a sanity check */
fprintf(stderr,"rfbBool's size is not 1 (%d)!\n",(int)sizeof(rfbBool));
/* we cannot continue, because rfbBool is supposed to be char everywhere */
exit(1);
}
rfbScreen->clientHead = NULL;
INIT_MUTEX(rfbClientListMutex);
}
rfbClientIteratorPtr
rfbGetClientIterator(rfbScreenInfoPtr rfbScreen)
{
rfbClientIteratorPtr i =
(rfbClientIteratorPtr)malloc(sizeof(struct rfbClientIterator));
i->next = NULL;
i->screen = rfbScreen;
i->closedToo = FALSE;
return i;
}
rfbClientIteratorPtr
rfbGetClientIteratorWithClosed(rfbScreenInfoPtr rfbScreen)
{
rfbClientIteratorPtr i =
(rfbClientIteratorPtr)malloc(sizeof(struct rfbClientIterator));
i->next = NULL;
i->screen = rfbScreen;
i->closedToo = TRUE;
return i;
}
rfbClientPtr
rfbClientIteratorHead(rfbClientIteratorPtr i)
{
#ifdef LIBVNCSERVER_HAVE_LIBPTHREAD
if(i->next != 0) {
rfbDecrClientRef(i->next);
rfbIncrClientRef(i->screen->clientHead);
}
#endif
LOCK(rfbClientListMutex);
i->next = i->screen->clientHead;
UNLOCK(rfbClientListMutex);
return i->next;
}
rfbClientPtr
rfbClientIteratorNext(rfbClientIteratorPtr i)
{
if(i->next == 0) {
LOCK(rfbClientListMutex);
i->next = i->screen->clientHead;
UNLOCK(rfbClientListMutex);
} else {
IF_PTHREADS(rfbClientPtr cl = i->next);
i->next = i->next->next;
IF_PTHREADS(rfbDecrClientRef(cl));
}
#ifdef LIBVNCSERVER_HAVE_LIBPTHREAD
if(!i->closedToo)
while(i->next && i->next->sock<0)
i->next = i->next->next;
if(i->next)
rfbIncrClientRef(i->next);
#endif
return i->next;
}
void
rfbReleaseClientIterator(rfbClientIteratorPtr iterator)
{
IF_PTHREADS(if(iterator->next) rfbDecrClientRef(iterator->next));
free(iterator);
}
/*
* rfbNewClientConnection is called from sockets.c when a new connection
* comes in.
*/
void
rfbNewClientConnection(rfbScreenInfoPtr rfbScreen,
int sock)
{
rfbNewClient(rfbScreen,sock);
}
/*
* rfbReverseConnection is called to make an outward
* connection to a "listening" RFB client.
*/
rfbClientPtr
rfbReverseConnection(rfbScreenInfoPtr rfbScreen,
char *host,
int port)
{
int sock;
rfbClientPtr cl;
if ((sock = rfbConnect(rfbScreen, host, port)) < 0)
return (rfbClientPtr)NULL;
cl = rfbNewClient(rfbScreen, sock);
if (cl) {
cl->reverseConnection = TRUE;
}
return cl;
}
void
rfbSetProtocolVersion(rfbScreenInfoPtr rfbScreen, int major_, int minor_)
{
/* Permit the server to set the version to report */
/* TODO: sanity checking */
if ((major_==3) && (minor_ > 2 && minor_ < 9))
{
rfbScreen->protocolMajorVersion = major_;
rfbScreen->protocolMinorVersion = minor_;
}
else
rfbLog("rfbSetProtocolVersion(%d,%d) set to invalid values\n", major_, minor_);
}
/*
* rfbNewClient is called when a new connection has been made by whatever
* means.
*/
static rfbClientPtr
rfbNewTCPOrUDPClient(rfbScreenInfoPtr rfbScreen,
int sock,
rfbBool isUDP)
{
rfbProtocolVersionMsg pv;
rfbClientIteratorPtr iterator;
rfbClientPtr cl,cl_;
#ifdef LIBVNCSERVER_IPv6
struct sockaddr_storage addr;
#else
struct sockaddr_in addr;
#endif
socklen_t addrlen = sizeof(addr);
rfbProtocolExtension* extension;
cl = (rfbClientPtr)calloc(sizeof(rfbClientRec),1);
cl->screen = rfbScreen;
cl->sock = sock;
cl->viewOnly = FALSE;
/* setup pseudo scaling */
cl->scaledScreen = rfbScreen;
cl->scaledScreen->scaledScreenRefCount++;
rfbResetStats(cl);
cl->clientData = NULL;
cl->clientGoneHook = rfbDoNothingWithClient;
if(isUDP) {
rfbLog(" accepted UDP client\n");
} else {
#ifdef LIBVNCSERVER_IPv6
char host[1024];
#endif
int one=1;
getpeername(sock, (struct sockaddr *)&addr, &addrlen);
#ifdef LIBVNCSERVER_IPv6
if(getnameinfo((struct sockaddr*)&addr, addrlen, host, sizeof(host), NULL, 0, NI_NUMERICHOST) != 0) {
rfbLogPerror("rfbNewClient: error in getnameinfo");
cl->host = strdup("");
}
else
cl->host = strdup(host);
#else
cl->host = strdup(inet_ntoa(addr.sin_addr));
#endif
rfbLog(" other clients:\n");
iterator = rfbGetClientIterator(rfbScreen);
while ((cl_ = rfbClientIteratorNext(iterator)) != NULL) {
rfbLog(" %s\n",cl_->host);
}
rfbReleaseClientIterator(iterator);
if(!rfbSetNonBlocking(sock)) {
close(sock);
return NULL;
}
if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
(char *)&one, sizeof(one)) < 0) {
rfbLogPerror("setsockopt failed: can't set TCP_NODELAY flag, non TCP socket?");
}
FD_SET(sock,&(rfbScreen->allFds));
rfbScreen->maxFd = rfbMax(sock,rfbScreen->maxFd);
INIT_MUTEX(cl->outputMutex);
INIT_MUTEX(cl->refCountMutex);
INIT_MUTEX(cl->sendMutex);
INIT_COND(cl->deleteCond);
cl->state = RFB_PROTOCOL_VERSION;
cl->reverseConnection = FALSE;
cl->readyForSetColourMapEntries = FALSE;
cl->useCopyRect = FALSE;
cl->preferredEncoding = -1;
cl->correMaxWidth = 48;
cl->correMaxHeight = 48;
#ifdef LIBVNCSERVER_HAVE_LIBZ
cl->zrleData = NULL;
#endif
cl->copyRegion = sraRgnCreate();
cl->copyDX = 0;
cl->copyDY = 0;
cl->modifiedRegion =
sraRgnCreateRect(0,0,rfbScreen->width,rfbScreen->height);
INIT_MUTEX(cl->updateMutex);
INIT_COND(cl->updateCond);
cl->requestedRegion = sraRgnCreate();
cl->format = cl->screen->serverFormat;
cl->translateFn = rfbTranslateNone;
cl->translateLookupTable = NULL;
LOCK(rfbClientListMutex);
IF_PTHREADS(cl->refCount = 0);
cl->next = rfbScreen->clientHead;
cl->prev = NULL;
if (rfbScreen->clientHead)
rfbScreen->clientHead->prev = cl;
rfbScreen->clientHead = cl;
UNLOCK(rfbClientListMutex);
#if defined(LIBVNCSERVER_HAVE_LIBZ) || defined(LIBVNCSERVER_HAVE_LIBPNG)
cl->tightQualityLevel = -1;
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
cl->tightCompressLevel = TIGHT_DEFAULT_COMPRESSION;
cl->turboSubsampLevel = TURBO_DEFAULT_SUBSAMP;
{
int i;
for (i = 0; i < 4; i++)
cl->zsActive[i] = FALSE;
}
#endif
#endif
cl->fileTransfer.fd = -1;
cl->enableCursorShapeUpdates = FALSE;
cl->enableCursorPosUpdates = FALSE;
cl->useRichCursorEncoding = FALSE;
cl->enableLastRectEncoding = FALSE;
cl->enableKeyboardLedState = FALSE;
cl->enableSupportedMessages = FALSE;
cl->enableSupportedEncodings = FALSE;
cl->enableServerIdentity = FALSE;
cl->lastKeyboardLedState = -1;
cl->cursorX = rfbScreen->cursorX;
cl->cursorY = rfbScreen->cursorY;
cl->useNewFBSize = FALSE;
#ifdef LIBVNCSERVER_HAVE_LIBZ
cl->compStreamInited = FALSE;
cl->compStream.total_in = 0;
cl->compStream.total_out = 0;
cl->compStream.zalloc = Z_NULL;
cl->compStream.zfree = Z_NULL;
cl->compStream.opaque = Z_NULL;
cl->zlibCompressLevel = 5;
#endif
cl->progressiveSliceY = 0;
cl->extensions = NULL;
cl->lastPtrX = -1;
#ifdef LIBVNCSERVER_WITH_WEBSOCKETS
/*
* Wait a few ms for the client to send WebSockets connection (TLS/SSL or plain)
*/
if (!webSocketsCheck(cl)) {
/* Error reporting handled in webSocketsHandshake */
rfbCloseClient(cl);
rfbClientConnectionGone(cl);
return NULL;
}
#endif
sprintf(pv,rfbProtocolVersionFormat,rfbScreen->protocolMajorVersion,
rfbScreen->protocolMinorVersion);
if (rfbWriteExact(cl, pv, sz_rfbProtocolVersionMsg) < 0) {
rfbLogPerror("rfbNewClient: write");
rfbCloseClient(cl);
rfbClientConnectionGone(cl);
return NULL;
}
}
for(extension = rfbGetExtensionIterator(); extension;
extension=extension->next) {
void* data = NULL;
/* if the extension does not have a newClient method, it wants
* to be initialized later. */
if(extension->newClient && extension->newClient(cl, &data))
rfbEnableExtension(cl, extension, data);
}
rfbReleaseExtensionIterator();
switch (cl->screen->newClientHook(cl)) {
case RFB_CLIENT_ON_HOLD:
cl->onHold = TRUE;
break;
case RFB_CLIENT_ACCEPT:
cl->onHold = FALSE;
break;
case RFB_CLIENT_REFUSE:
rfbCloseClient(cl);
rfbClientConnectionGone(cl);
cl = NULL;
break;
}
return cl;
}
rfbClientPtr
rfbNewClient(rfbScreenInfoPtr rfbScreen,
int sock)
{
return(rfbNewTCPOrUDPClient(rfbScreen,sock,FALSE));
}
rfbClientPtr
rfbNewUDPClient(rfbScreenInfoPtr rfbScreen)
{
return((rfbScreen->udpClient=
rfbNewTCPOrUDPClient(rfbScreen,rfbScreen->udpSock,TRUE)));
}
/*
* rfbClientConnectionGone is called from sockets.c just after a connection
* has gone away.
*/
void
rfbClientConnectionGone(rfbClientPtr cl)
{
#if defined(LIBVNCSERVER_HAVE_LIBZ) && defined(LIBVNCSERVER_HAVE_LIBJPEG)
int i;
#endif
LOCK(rfbClientListMutex);
if (cl->prev)
cl->prev->next = cl->next;
else
cl->screen->clientHead = cl->next;
if (cl->next)
cl->next->prev = cl->prev;
UNLOCK(rfbClientListMutex);
#ifdef LIBVNCSERVER_HAVE_LIBPTHREAD
if(cl->screen->backgroundLoop != FALSE) {
int i;
do {
LOCK(cl->refCountMutex);
i=cl->refCount;
if(i>0)
WAIT(cl->deleteCond,cl->refCountMutex);
UNLOCK(cl->refCountMutex);
} while(i>0);
}
#endif
if(cl->sock>=0)
close(cl->sock);
if (cl->scaledScreen!=NULL)
cl->scaledScreen->scaledScreenRefCount--;
#ifdef LIBVNCSERVER_HAVE_LIBZ
rfbFreeZrleData(cl);
#endif
rfbFreeUltraData(cl);
/* free buffers holding pixel data before and after encoding */
free(cl->beforeEncBuf);
free(cl->afterEncBuf);
if(cl->sock>=0)
FD_CLR(cl->sock,&(cl->screen->allFds));
cl->clientGoneHook(cl);
rfbLog("Client %s gone\n",cl->host);
free(cl->host);
#ifdef LIBVNCSERVER_HAVE_LIBZ
/* Release the compression state structures if any. */
if ( cl->compStreamInited ) {
deflateEnd( &(cl->compStream) );
}
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
for (i = 0; i < 4; i++) {
if (cl->zsActive[i])
deflateEnd(&cl->zsStruct[i]);
}
#endif
#endif
if (cl->screen->pointerClient == cl)
cl->screen->pointerClient = NULL;
sraRgnDestroy(cl->modifiedRegion);
sraRgnDestroy(cl->requestedRegion);
sraRgnDestroy(cl->copyRegion);
if (cl->translateLookupTable) free(cl->translateLookupTable);
TINI_COND(cl->updateCond);
TINI_MUTEX(cl->updateMutex);
/* make sure outputMutex is unlocked before destroying */
LOCK(cl->outputMutex);
UNLOCK(cl->outputMutex);
TINI_MUTEX(cl->outputMutex);
LOCK(cl->sendMutex);
UNLOCK(cl->sendMutex);
TINI_MUTEX(cl->sendMutex);
rfbPrintStats(cl);
rfbResetStats(cl);
free(cl);
}
/*
* rfbProcessClientMessage is called when there is data to read from a client.
*/
void
rfbProcessClientMessage(rfbClientPtr cl)
{
switch (cl->state) {
case RFB_PROTOCOL_VERSION:
rfbProcessClientProtocolVersion(cl);
return;
case RFB_SECURITY_TYPE:
rfbProcessClientSecurityType(cl);
return;
case RFB_AUTHENTICATION:
rfbAuthProcessClientMessage(cl);
return;
case RFB_INITIALISATION:
case RFB_INITIALISATION_SHARED:
rfbProcessClientInitMessage(cl);
return;
default:
rfbProcessClientNormalMessage(cl);
return;
}
}
/*
* rfbProcessClientProtocolVersion is called when the client sends its
* protocol version.
*/
static void
rfbProcessClientProtocolVersion(rfbClientPtr cl)
{
rfbProtocolVersionMsg pv;
int n, major_, minor_;
if ((n = rfbReadExact(cl, pv, sz_rfbProtocolVersionMsg)) <= 0) {
if (n == 0)
rfbLog("rfbProcessClientProtocolVersion: client gone\n");
else
rfbLogPerror("rfbProcessClientProtocolVersion: read");
rfbCloseClient(cl);
return;
}
pv[sz_rfbProtocolVersionMsg] = 0;
if (sscanf(pv,rfbProtocolVersionFormat,&major_,&minor_) != 2) {
rfbErr("rfbProcessClientProtocolVersion: not a valid RFB client: %s\n", pv);
rfbCloseClient(cl);
return;
}
rfbLog("Client Protocol Version %d.%d\n", major_, minor_);
if (major_ != rfbProtocolMajorVersion) {
rfbErr("RFB protocol version mismatch - server %d.%d, client %d.%d",
cl->screen->protocolMajorVersion, cl->screen->protocolMinorVersion,
major_,minor_);
rfbCloseClient(cl);
return;
}
/* Check for the minor version use either of the two standard version of RFB */
/*
* UltraVNC Viewer detects FileTransfer compatible servers via rfb versions
* 3.4, 3.6, 3.14, 3.16
* It's a bad method, but it is what they use to enable features...
* maintaining RFB version compatibility across multiple servers is a pain
* Should use something like ServerIdentity encoding
*/
cl->protocolMajorVersion = major_;
cl->protocolMinorVersion = minor_;
rfbLog("Protocol version sent %d.%d, using %d.%d\n",
major_, minor_, rfbProtocolMajorVersion, cl->protocolMinorVersion);
rfbAuthNewClient(cl);
}
void
rfbClientSendString(rfbClientPtr cl, const char *reason)
{
char *buf;
int len = strlen(reason);
rfbLog("rfbClientSendString(\"%s\")\n", reason);
buf = (char *)malloc(4 + len);
((uint32_t *)buf)[0] = Swap32IfLE(len);
memcpy(buf + 4, reason, len);
if (rfbWriteExact(cl, buf, 4 + len) < 0)
rfbLogPerror("rfbClientSendString: write");
free(buf);
rfbCloseClient(cl);
}
/*
* rfbClientConnFailed is called when a client connection has failed either
* because it talks the wrong protocol or it has failed authentication.
*/
void
rfbClientConnFailed(rfbClientPtr cl,
const char *reason)
{
char *buf;
int len = strlen(reason);
rfbLog("rfbClientConnFailed(\"%s\")\n", reason);
buf = (char *)malloc(8 + len);
((uint32_t *)buf)[0] = Swap32IfLE(rfbConnFailed);
((uint32_t *)buf)[1] = Swap32IfLE(len);
memcpy(buf + 8, reason, len);
if (rfbWriteExact(cl, buf, 8 + len) < 0)
rfbLogPerror("rfbClientConnFailed: write");
free(buf);
rfbCloseClient(cl);
}
/*
* rfbProcessClientInitMessage is called when the client sends its
* initialisation message.
*/
static void
rfbProcessClientInitMessage(rfbClientPtr cl)
{
rfbClientInitMsg ci;
union {
char buf[256];
rfbServerInitMsg si;
} u;
int len, n;
rfbClientIteratorPtr iterator;
rfbClientPtr otherCl;
rfbExtensionData* extension;
if (cl->state == RFB_INITIALISATION_SHARED) {
/* In this case behave as though an implicit ClientInit message has
* already been received with a shared-flag of true. */
ci.shared = 1;
/* Avoid the possibility of exposing the RFB_INITIALISATION_SHARED
* state to calling software. */
cl->state = RFB_INITIALISATION;
} else {
if ((n = rfbReadExact(cl, (char *)&ci,sz_rfbClientInitMsg)) <= 0) {
if (n == 0)
rfbLog("rfbProcessClientInitMessage: client gone\n");
else
rfbLogPerror("rfbProcessClientInitMessage: read");
rfbCloseClient(cl);
return;
}
}
memset(u.buf,0,sizeof(u.buf));
u.si.framebufferWidth = Swap16IfLE(cl->screen->width);
u.si.framebufferHeight = Swap16IfLE(cl->screen->height);
u.si.format = cl->screen->serverFormat;
u.si.format.redMax = Swap16IfLE(u.si.format.redMax);
u.si.format.greenMax = Swap16IfLE(u.si.format.greenMax);
u.si.format.blueMax = Swap16IfLE(u.si.format.blueMax);
strncpy(u.buf + sz_rfbServerInitMsg, cl->screen->desktopName, 127);
len = strlen(u.buf + sz_rfbServerInitMsg);
u.si.nameLength = Swap32IfLE(len);
if (rfbWriteExact(cl, u.buf, sz_rfbServerInitMsg + len) < 0) {
rfbLogPerror("rfbProcessClientInitMessage: write");
rfbCloseClient(cl);
return;
}
for(extension = cl->extensions; extension;) {
rfbExtensionData* next = extension->next;
if(extension->extension->init &&
!extension->extension->init(cl, extension->data))
/* extension requested that it be removed */
rfbDisableExtension(cl, extension->extension);
extension = next;
}
cl->state = RFB_NORMAL;
if (!cl->reverseConnection &&
(cl->screen->neverShared || (!cl->screen->alwaysShared && !ci.shared))) {
if (cl->screen->dontDisconnect) {
iterator = rfbGetClientIterator(cl->screen);
while ((otherCl = rfbClientIteratorNext(iterator)) != NULL) {
if ((otherCl != cl) && (otherCl->state == RFB_NORMAL)) {
rfbLog("-dontdisconnect: Not shared & existing client\n");
rfbLog(" refusing new client %s\n", cl->host);
rfbCloseClient(cl);
rfbReleaseClientIterator(iterator);
return;
}
}
rfbReleaseClientIterator(iterator);
} else {
iterator = rfbGetClientIterator(cl->screen);
while ((otherCl = rfbClientIteratorNext(iterator)) != NULL) {
if ((otherCl != cl) && (otherCl->state == RFB_NORMAL)) {
rfbLog("Not shared - closing connection to client %s\n",
otherCl->host);
rfbCloseClient(otherCl);
}
}
rfbReleaseClientIterator(iterator);
}
}
}
/* The values come in based on the scaled screen, we need to convert them to
* values based on the man screen's coordinate system
*/
static rfbBool rectSwapIfLEAndClip(uint16_t* x,uint16_t* y,uint16_t* w,uint16_t* h,
rfbClientPtr cl)
{
int x1=Swap16IfLE(*x);
int y1=Swap16IfLE(*y);
int w1=Swap16IfLE(*w);
int h1=Swap16IfLE(*h);
rfbScaledCorrection(cl->scaledScreen, cl->screen, &x1, &y1, &w1, &h1, "rectSwapIfLEAndClip");
*x = x1;
*y = y1;
*w = w1;
*h = h1;
if(*w>cl->screen->width-*x)
*w=cl->screen->width-*x;
/* possible underflow */
if(*w>cl->screen->width-*x)
return FALSE;
if(*h>cl->screen->height-*y)
*h=cl->screen->height-*y;
if(*h>cl->screen->height-*y)
return FALSE;
return TRUE;
}
/*
* Send keyboard state (PointerPos pseudo-encoding).
*/
rfbBool
rfbSendKeyboardLedState(rfbClientPtr cl)
{
rfbFramebufferUpdateRectHeader rect;
if (cl->ublen + sz_rfbFramebufferUpdateRectHeader > UPDATE_BUF_SIZE) {
if (!rfbSendUpdateBuf(cl))
return FALSE;
}
rect.encoding = Swap32IfLE(rfbEncodingKeyboardLedState);
rect.r.x = Swap16IfLE(cl->lastKeyboardLedState);
rect.r.y = 0;
rect.r.w = 0;
rect.r.h = 0;
memcpy(&cl->updateBuf[cl->ublen], (char *)&rect,
sz_rfbFramebufferUpdateRectHeader);
cl->ublen += sz_rfbFramebufferUpdateRectHeader;
rfbStatRecordEncodingSent(cl, rfbEncodingKeyboardLedState, sz_rfbFramebufferUpdateRectHeader, sz_rfbFramebufferUpdateRectHeader);
if (!rfbSendUpdateBuf(cl))
return FALSE;
return TRUE;
}
#define rfbSetBit(buffer, position) (buffer[(position & 255) / 8] |= (1 << (position % 8)))
/*
* Send rfbEncodingSupportedMessages.
*/
rfbBool
rfbSendSupportedMessages(rfbClientPtr cl)
{
rfbFramebufferUpdateRectHeader rect;
rfbSupportedMessages msgs;
if (cl->ublen + sz_rfbFramebufferUpdateRectHeader
+ sz_rfbSupportedMessages > UPDATE_BUF_SIZE) {
if (!rfbSendUpdateBuf(cl))
return FALSE;
}
rect.encoding = Swap32IfLE(rfbEncodingSupportedMessages);
rect.r.x = 0;
rect.r.y = 0;
rect.r.w = Swap16IfLE(sz_rfbSupportedMessages);
rect.r.h = 0;
memcpy(&cl->updateBuf[cl->ublen], (char *)&rect,
sz_rfbFramebufferUpdateRectHeader);
cl->ublen += sz_rfbFramebufferUpdateRectHeader;
memset((char *)&msgs, 0, sz_rfbSupportedMessages);
rfbSetBit(msgs.client2server, rfbSetPixelFormat);
rfbSetBit(msgs.client2server, rfbFixColourMapEntries);
rfbSetBit(msgs.client2server, rfbSetEncodings);
rfbSetBit(msgs.client2server, rfbFramebufferUpdateRequest);
rfbSetBit(msgs.client2server, rfbKeyEvent);
rfbSetBit(msgs.client2server, rfbPointerEvent);
rfbSetBit(msgs.client2server, rfbClientCutText);
rfbSetBit(msgs.client2server, rfbFileTransfer);
rfbSetBit(msgs.client2server, rfbSetScale);
/*rfbSetBit(msgs.client2server, rfbSetServerInput); */
/*rfbSetBit(msgs.client2server, rfbSetSW); */
/*rfbSetBit(msgs.client2server, rfbTextChat); */
rfbSetBit(msgs.client2server, rfbPalmVNCSetScaleFactor);
rfbSetBit(msgs.server2client, rfbFramebufferUpdate);
rfbSetBit(msgs.server2client, rfbSetColourMapEntries);
rfbSetBit(msgs.server2client, rfbBell);
rfbSetBit(msgs.server2client, rfbServerCutText);
rfbSetBit(msgs.server2client, rfbResizeFrameBuffer);
rfbSetBit(msgs.server2client, rfbPalmVNCReSizeFrameBuffer);
if (cl->screen->xvpHook) {
rfbSetBit(msgs.client2server, rfbXvp);
rfbSetBit(msgs.server2client, rfbXvp);
}
memcpy(&cl->updateBuf[cl->ublen], (char *)&msgs, sz_rfbSupportedMessages);
cl->ublen += sz_rfbSupportedMessages;
rfbStatRecordEncodingSent(cl, rfbEncodingSupportedMessages,
sz_rfbFramebufferUpdateRectHeader+sz_rfbSupportedMessages,
sz_rfbFramebufferUpdateRectHeader+sz_rfbSupportedMessages);
if (!rfbSendUpdateBuf(cl))
return FALSE;
return TRUE;
}
/*
* Send rfbEncodingSupportedEncodings.
*/
rfbBool
rfbSendSupportedEncodings(rfbClientPtr cl)
{
rfbFramebufferUpdateRectHeader rect;
static uint32_t supported[] = {
rfbEncodingRaw,
rfbEncodingCopyRect,
rfbEncodingRRE,
rfbEncodingCoRRE,
rfbEncodingHextile,
#ifdef LIBVNCSERVER_HAVE_LIBZ
rfbEncodingZlib,
rfbEncodingZRLE,
rfbEncodingZYWRLE,
#endif
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
rfbEncodingTight,
#endif
#ifdef LIBVNCSERVER_HAVE_LIBPNG
rfbEncodingTightPng,
#endif
rfbEncodingUltra,
rfbEncodingUltraZip,
rfbEncodingXCursor,
rfbEncodingRichCursor,
rfbEncodingPointerPos,
rfbEncodingLastRect,
rfbEncodingNewFBSize,
rfbEncodingKeyboardLedState,
rfbEncodingSupportedMessages,
rfbEncodingSupportedEncodings,
rfbEncodingServerIdentity,
};
uint32_t nEncodings = sizeof(supported) / sizeof(supported[0]), i;
/* think rfbSetEncodingsMsg */
if (cl->ublen + sz_rfbFramebufferUpdateRectHeader
+ (nEncodings * sizeof(uint32_t)) > UPDATE_BUF_SIZE) {
if (!rfbSendUpdateBuf(cl))
return FALSE;
}
rect.encoding = Swap32IfLE(rfbEncodingSupportedEncodings);
rect.r.x = 0;
rect.r.y = 0;
rect.r.w = Swap16IfLE(nEncodings * sizeof(uint32_t));
rect.r.h = Swap16IfLE(nEncodings);
memcpy(&cl->updateBuf[cl->ublen], (char *)&rect,
sz_rfbFramebufferUpdateRectHeader);
cl->ublen += sz_rfbFramebufferUpdateRectHeader;
for (i = 0; i < nEncodings; i++) {
uint32_t encoding = Swap32IfLE(supported[i]);
memcpy(&cl->updateBuf[cl->ublen], (char *)&encoding, sizeof(encoding));
cl->ublen += sizeof(encoding);
}
rfbStatRecordEncodingSent(cl, rfbEncodingSupportedEncodings,
sz_rfbFramebufferUpdateRectHeader+(nEncodings * sizeof(uint32_t)),
sz_rfbFramebufferUpdateRectHeader+(nEncodings * sizeof(uint32_t)));
if (!rfbSendUpdateBuf(cl))
return FALSE;
return TRUE;
}
void
rfbSetServerVersionIdentity(rfbScreenInfoPtr screen, char *fmt, ...)
{
char buffer[256];
va_list ap;
va_start(ap, fmt);
vsnprintf(buffer, sizeof(buffer)-1, fmt, ap);
va_end(ap);
if (screen->versionString!=NULL) free(screen->versionString);
screen->versionString = strdup(buffer);
}
/*
* Send rfbEncodingServerIdentity.
*/
rfbBool
rfbSendServerIdentity(rfbClientPtr cl)
{
rfbFramebufferUpdateRectHeader rect;
char buffer[512];
/* tack on our library version */
snprintf(buffer,sizeof(buffer)-1, "%s (%s)",
(cl->screen->versionString==NULL ? "unknown" : cl->screen->versionString),
LIBVNCSERVER_PACKAGE_STRING);
if (cl->ublen + sz_rfbFramebufferUpdateRectHeader
+ (strlen(buffer)+1) > UPDATE_BUF_SIZE) {
if (!rfbSendUpdateBuf(cl))
return FALSE;
}
rect.encoding = Swap32IfLE(rfbEncodingServerIdentity);
rect.r.x = 0;
rect.r.y = 0;
rect.r.w = Swap16IfLE(strlen(buffer)+1);
rect.r.h = 0;
memcpy(&cl->updateBuf[cl->ublen], (char *)&rect,
sz_rfbFramebufferUpdateRectHeader);
cl->ublen += sz_rfbFramebufferUpdateRectHeader;
memcpy(&cl->updateBuf[cl->ublen], buffer, strlen(buffer)+1);
cl->ublen += strlen(buffer)+1;
rfbStatRecordEncodingSent(cl, rfbEncodingServerIdentity,
sz_rfbFramebufferUpdateRectHeader+strlen(buffer)+1,
sz_rfbFramebufferUpdateRectHeader+strlen(buffer)+1);
if (!rfbSendUpdateBuf(cl))
return FALSE;
return TRUE;
}
/*
* Send an xvp server message
*/
rfbBool
rfbSendXvp(rfbClientPtr cl, uint8_t version, uint8_t code)
{
rfbXvpMsg xvp;
xvp.type = rfbXvp;
xvp.pad = 0;
xvp.version = version;
xvp.code = code;
LOCK(cl->sendMutex);
if (rfbWriteExact(cl, (char *)&xvp, sz_rfbXvpMsg) < 0) {
rfbLogPerror("rfbSendXvp: write");
rfbCloseClient(cl);
}
UNLOCK(cl->sendMutex);
rfbStatRecordMessageSent(cl, rfbXvp, sz_rfbXvpMsg, sz_rfbXvpMsg);
return TRUE;
}
rfbBool rfbSendTextChatMessage(rfbClientPtr cl, uint32_t length, char *buffer)
{
rfbTextChatMsg tc;
int bytesToSend=0;
memset((char *)&tc, 0, sizeof(tc));
tc.type = rfbTextChat;
tc.length = Swap32IfLE(length);
switch(length) {
case rfbTextChatOpen:
case rfbTextChatClose:
case rfbTextChatFinished:
bytesToSend=0;
break;
default:
bytesToSend=length;
if (bytesToSend>rfbTextMaxSize)
bytesToSend=rfbTextMaxSize;
}
if (cl->ublen + sz_rfbTextChatMsg + bytesToSend > UPDATE_BUF_SIZE) {
if (!rfbSendUpdateBuf(cl))
return FALSE;
}
memcpy(&cl->updateBuf[cl->ublen], (char *)&tc, sz_rfbTextChatMsg);
cl->ublen += sz_rfbTextChatMsg;
if (bytesToSend>0) {
memcpy(&cl->updateBuf[cl->ublen], buffer, bytesToSend);
cl->ublen += bytesToSend;
}
rfbStatRecordMessageSent(cl, rfbTextChat, sz_rfbTextChatMsg+bytesToSend, sz_rfbTextChatMsg+bytesToSend);
if (!rfbSendUpdateBuf(cl))
return FALSE;
return TRUE;
}
#define FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN(msg, cl, ret) \
if ((cl->screen->getFileTransferPermission != NULL \
&& cl->screen->getFileTransferPermission(cl) != TRUE) \
|| cl->screen->permitFileTransfer != TRUE) { \
rfbLog("%sUltra File Transfer is disabled, dropping client: %s\n", msg, cl->host); \
rfbCloseClient(cl); \
return ret; \
}
int DB = 1;
rfbBool rfbSendFileTransferMessage(rfbClientPtr cl, uint8_t contentType, uint8_t contentParam, uint32_t size, uint32_t length, const char *buffer)
{
rfbFileTransferMsg ft;
ft.type = rfbFileTransfer;
ft.contentType = contentType;
ft.contentParam = contentParam;
ft.pad = 0; /* UltraVNC did not Swap16LE(ft.contentParam) (Looks like it might be BigEndian) */
ft.size = Swap32IfLE(size);
ft.length = Swap32IfLE(length);
FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, FALSE);
/*
rfbLog("rfbSendFileTransferMessage( %dtype, %dparam, %dsize, %dlen, %p)\n", contentType, contentParam, size, length, buffer);
*/
LOCK(cl->sendMutex);
if (rfbWriteExact(cl, (char *)&ft, sz_rfbFileTransferMsg) < 0) {
rfbLogPerror("rfbSendFileTransferMessage: write");
rfbCloseClient(cl);
UNLOCK(cl->sendMutex);
return FALSE;
}
if (length>0)
{
if (rfbWriteExact(cl, buffer, length) < 0) {
rfbLogPerror("rfbSendFileTransferMessage: write");
rfbCloseClient(cl);
UNLOCK(cl->sendMutex);
return FALSE;
}
}
UNLOCK(cl->sendMutex);
rfbStatRecordMessageSent(cl, rfbFileTransfer, sz_rfbFileTransferMsg+length, sz_rfbFileTransferMsg+length);
return TRUE;
}
/*
* UltraVNC uses Windows Structures
*/
#define MAX_PATH 260
typedef struct {
uint32_t dwLowDateTime;
uint32_t dwHighDateTime;
} RFB_FILETIME;
typedef struct {
uint32_t dwFileAttributes;
RFB_FILETIME ftCreationTime;
RFB_FILETIME ftLastAccessTime;
RFB_FILETIME ftLastWriteTime;
uint32_t nFileSizeHigh;
uint32_t nFileSizeLow;
uint32_t dwReserved0;
uint32_t dwReserved1;
uint8_t cFileName[ MAX_PATH ];
uint8_t cAlternateFileName[ 14 ];
} RFB_FIND_DATA;
#define RFB_FILE_ATTRIBUTE_READONLY 0x1
#define RFB_FILE_ATTRIBUTE_HIDDEN 0x2
#define RFB_FILE_ATTRIBUTE_SYSTEM 0x4
#define RFB_FILE_ATTRIBUTE_DIRECTORY 0x10
#define RFB_FILE_ATTRIBUTE_ARCHIVE 0x20
#define RFB_FILE_ATTRIBUTE_NORMAL 0x80
#define RFB_FILE_ATTRIBUTE_TEMPORARY 0x100
#define RFB_FILE_ATTRIBUTE_COMPRESSED 0x800
rfbBool rfbFilenameTranslate2UNIX(rfbClientPtr cl, /* in */ char *path, /* out */ char *unixPath, size_t unixPathMaxLen)
{
int x;
char *home=NULL;
FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, FALSE);
/*
* Do not use strncpy() - truncating the file name would probably have undesirable side effects
* Instead check if destination buffer is big enough
*/
if (strlen(path) >= unixPathMaxLen)
return FALSE;
/* C: */
if (path[0]=='C' && path[1]==':')
strcpy(unixPath, &path[2]);
else
{
home = getenv("HOME");
if (home!=NULL)
{
/* Re-check buffer size */
if ((strlen(path) + strlen(home) + 1) >= unixPathMaxLen)
return FALSE;
strcpy(unixPath, home);
strcat(unixPath,"/");
strcat(unixPath, path);
}
else
strcpy(unixPath, path);
}
for (x=0;x<strlen(unixPath);x++)
if (unixPath[x]=='\\') unixPath[x]='/';
return TRUE;
}
rfbBool rfbFilenameTranslate2DOS(rfbClientPtr cl, char *unixPath, char *path)
{
int x;
FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, FALSE);
sprintf(path,"C:%s", unixPath);
for (x=2;x<strlen(path);x++)
if (path[x]=='/') path[x]='\\';
return TRUE;
}
rfbBool rfbSendDirContent(rfbClientPtr cl, int length, char *buffer)
{
char retfilename[MAX_PATH];
char path[MAX_PATH];
struct stat statbuf;
RFB_FIND_DATA win32filename;
int nOptLen = 0, retval=0;
#ifdef WIN32
WIN32_FIND_DATAA winFindData;
HANDLE findHandle;
int pathLen, basePathLength;
char *basePath;
#else
DIR *dirp=NULL;
struct dirent *direntp=NULL;
#endif
FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, FALSE);
/* Client thinks we are Winblows */
if (!rfbFilenameTranslate2UNIX(cl, buffer, path, sizeof(path)))
return FALSE;
if (DB) rfbLog("rfbProcessFileTransfer() rfbDirContentRequest: rfbRDirContent: \"%s\"->\"%s\"\n",buffer, path);
#ifdef WIN32
// Create a search string, like C:\folder\*
pathLen = strlen(path);
basePath = malloc(pathLen + 3);
memcpy(basePath, path, pathLen);
basePathLength = pathLen;
basePath[basePathLength] = '\\';
basePath[basePathLength + 1] = '*';
basePath[basePathLength + 2] = '\0';
// Start a search
memset(&winFindData, 0, sizeof(winFindData));
findHandle = FindFirstFileA(path, &winFindData);
free(basePath);
if (findHandle == INVALID_HANDLE_VALUE)
#else
dirp=opendir(path);
if (dirp==NULL)
#endif
return rfbSendFileTransferMessage(cl, rfbDirPacket, rfbADirectory, 0, 0, NULL);
/* send back the path name (necessary for links) */
if (rfbSendFileTransferMessage(cl, rfbDirPacket, rfbADirectory, 0, length, buffer)==FALSE) return FALSE;
#ifdef WIN32
while (findHandle != INVALID_HANDLE_VALUE)
#else
for (direntp=readdir(dirp); direntp!=NULL; direntp=readdir(dirp))
#endif
{
/* get stats */
#ifdef WIN32
snprintf(retfilename,sizeof(retfilename),"%s/%s", path, winFindData.cFileName);
#else
snprintf(retfilename,sizeof(retfilename),"%s/%s", path, direntp->d_name);
#endif
retval = stat(retfilename, &statbuf);
if (retval==0)
{
memset((char *)&win32filename, 0, sizeof(win32filename));
#ifdef WIN32
win32filename.dwFileAttributes = winFindData.dwFileAttributes;
win32filename.ftCreationTime.dwLowDateTime = winFindData.ftCreationTime.dwLowDateTime;
win32filename.ftCreationTime.dwHighDateTime = winFindData.ftCreationTime.dwHighDateTime;
win32filename.ftLastAccessTime.dwLowDateTime = winFindData.ftLastAccessTime.dwLowDateTime;
win32filename.ftLastAccessTime.dwHighDateTime = winFindData.ftLastAccessTime.dwHighDateTime;
win32filename.ftLastWriteTime.dwLowDateTime = winFindData.ftLastWriteTime.dwLowDateTime;
win32filename.ftLastWriteTime.dwHighDateTime = winFindData.ftLastWriteTime.dwHighDateTime;
win32filename.nFileSizeLow = winFindData.nFileSizeLow;
win32filename.nFileSizeHigh = winFindData.nFileSizeHigh;
win32filename.dwReserved0 = winFindData.dwReserved0;
win32filename.dwReserved1 = winFindData.dwReserved1;
strcpy((char *)win32filename.cFileName, winFindData.cFileName);
strcpy((char *)win32filename.cAlternateFileName, winFindData.cAlternateFileName);
#else
win32filename.dwFileAttributes = Swap32IfBE(RFB_FILE_ATTRIBUTE_NORMAL);
if (S_ISDIR(statbuf.st_mode))
win32filename.dwFileAttributes = Swap32IfBE(RFB_FILE_ATTRIBUTE_DIRECTORY);
win32filename.ftCreationTime.dwLowDateTime = Swap32IfBE(statbuf.st_ctime); /* Intel Order */
win32filename.ftCreationTime.dwHighDateTime = 0;
win32filename.ftLastAccessTime.dwLowDateTime = Swap32IfBE(statbuf.st_atime); /* Intel Order */
win32filename.ftLastAccessTime.dwHighDateTime = 0;
win32filename.ftLastWriteTime.dwLowDateTime = Swap32IfBE(statbuf.st_mtime); /* Intel Order */
win32filename.ftLastWriteTime.dwHighDateTime = 0;
win32filename.nFileSizeLow = Swap32IfBE(statbuf.st_size); /* Intel Order */
win32filename.nFileSizeHigh = 0;
win32filename.dwReserved0 = 0;
win32filename.dwReserved1 = 0;
/* If this had the full path, we would need to translate to DOS format ("C:\") */
/* rfbFilenameTranslate2DOS(cl, retfilename, win32filename.cFileName); */
strcpy((char *)win32filename.cFileName, direntp->d_name);
#endif
/* Do not show hidden files (but show how to move up the tree) */
if ((strcmp((char *)win32filename.cFileName, "..")==0) || (win32filename.cFileName[0]!='.'))
{
nOptLen = sizeof(RFB_FIND_DATA) - MAX_PATH - 14 + strlen((char *)win32filename.cFileName);
/*
rfbLog("rfbProcessFileTransfer() rfbDirContentRequest: rfbRDirContent: Sending \"%s\"\n", (char *)win32filename.cFileName);
*/
if (rfbSendFileTransferMessage(cl, rfbDirPacket, rfbADirectory, 0, nOptLen, (char *)&win32filename)==FALSE)
{
#ifdef WIN32
FindClose(findHandle);
#else
closedir(dirp);
#endif
return FALSE;
}
}
}
#ifdef WIN32
if (FindNextFileA(findHandle, &winFindData) == 0)
{
FindClose(findHandle);
findHandle = INVALID_HANDLE_VALUE;
}
#endif
}
#ifdef WIN32
if (findHandle != INVALID_HANDLE_VALUE)
{
FindClose(findHandle);
}
#else
closedir(dirp);
#endif
/* End of the transfer */
return rfbSendFileTransferMessage(cl, rfbDirPacket, 0, 0, 0, NULL);
}
char *rfbProcessFileTransferReadBuffer(rfbClientPtr cl, uint32_t length)
{
char *buffer=NULL;
int n=0;
FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, NULL);
/*
rfbLog("rfbProcessFileTransferReadBuffer(%dlen)\n", length);
*/
if (length>0) {
buffer=malloc((uint64_t)length+1);
if (buffer!=NULL) {
if ((n = rfbReadExact(cl, (char *)buffer, length)) <= 0) {
if (n != 0)
rfbLogPerror("rfbProcessFileTransferReadBuffer: read");
rfbCloseClient(cl);
/* NOTE: don't forget to free(buffer) if you return early! */
if (buffer!=NULL) free(buffer);
return NULL;
}
/* Null Terminate */
buffer[length]=0;
}
}
return buffer;
}
rfbBool rfbSendFileTransferChunk(rfbClientPtr cl)
{
/* Allocate buffer for compression */
unsigned char readBuf[sz_rfbBlockSize];
int bytesRead=0;
int retval=0;
fd_set wfds;
struct timeval tv;
int n;
#ifdef LIBVNCSERVER_HAVE_LIBZ
unsigned char compBuf[sz_rfbBlockSize + 1024];
unsigned long nMaxCompSize = sizeof(compBuf);
int nRetC = 0;
#endif
/*
* Don't close the client if we get into this one because
* it is called from many places to service file transfers.
* Note that permitFileTransfer is checked first.
*/
if (cl->screen->permitFileTransfer != TRUE ||
(cl->screen->getFileTransferPermission != NULL
&& cl->screen->getFileTransferPermission(cl) != TRUE)) {
return TRUE;
}
/* If not sending, or no file open... Return as if we sent something! */
if ((cl->fileTransfer.fd!=-1) && (cl->fileTransfer.sending==1))
{
FD_ZERO(&wfds);
FD_SET(cl->sock, &wfds);
/* return immediately */
tv.tv_sec = 0;
tv.tv_usec = 0;
n = select(cl->sock + 1, NULL, &wfds, NULL, &tv);
if (n<0) {
#ifdef WIN32
errno=WSAGetLastError();
#endif
rfbLog("rfbSendFileTransferChunk() select failed: %s\n", strerror(errno));
}
/* We have space on the transmit queue */
if (n > 0)
{
bytesRead = read(cl->fileTransfer.fd, readBuf, sz_rfbBlockSize);
switch (bytesRead) {
case 0:
/*
rfbLog("rfbSendFileTransferChunk(): End-Of-File Encountered\n");
*/
retval = rfbSendFileTransferMessage(cl, rfbEndOfFile, 0, 0, 0, NULL);
close(cl->fileTransfer.fd);
cl->fileTransfer.fd = -1;
cl->fileTransfer.sending = 0;
cl->fileTransfer.receiving = 0;
return retval;
case -1:
/* TODO : send an error msg to the client... */
#ifdef WIN32
errno=WSAGetLastError();
#endif
rfbLog("rfbSendFileTransferChunk(): %s\n",strerror(errno));
retval = rfbSendFileTransferMessage(cl, rfbAbortFileTransfer, 0, 0, 0, NULL);
close(cl->fileTransfer.fd);
cl->fileTransfer.fd = -1;
cl->fileTransfer.sending = 0;
cl->fileTransfer.receiving = 0;
return retval;
default:
/*
rfbLog("rfbSendFileTransferChunk(): Read %d bytes\n", bytesRead);
*/
if (!cl->fileTransfer.compressionEnabled)
return rfbSendFileTransferMessage(cl, rfbFilePacket, 0, 0, bytesRead, (char *)readBuf);
else
{
#ifdef LIBVNCSERVER_HAVE_LIBZ
nRetC = compress(compBuf, &nMaxCompSize, readBuf, bytesRead);
/*
rfbLog("Compressed the packet from %d -> %d bytes\n", nMaxCompSize, bytesRead);
*/
if ((nRetC==0) && (nMaxCompSize<bytesRead))
return rfbSendFileTransferMessage(cl, rfbFilePacket, 0, 1, nMaxCompSize, (char *)compBuf);
else
return rfbSendFileTransferMessage(cl, rfbFilePacket, 0, 0, bytesRead, (char *)readBuf);
#else
/* We do not support compression of the data stream */
return rfbSendFileTransferMessage(cl, rfbFilePacket, 0, 0, bytesRead, (char *)readBuf);
#endif
}
}
}
}
return TRUE;
}
rfbBool rfbProcessFileTransfer(rfbClientPtr cl, uint8_t contentType, uint8_t contentParam, uint32_t size, uint32_t length)
{
char *buffer=NULL, *p=NULL;
int retval=0;
char filename1[MAX_PATH];
char filename2[MAX_PATH];
char szFileTime[MAX_PATH];
struct stat statbuf;
uint32_t sizeHtmp=0;
int n=0;
char timespec[64];
#ifdef LIBVNCSERVER_HAVE_LIBZ
unsigned char compBuff[sz_rfbBlockSize];
unsigned long nRawBytes = sz_rfbBlockSize;
int nRet = 0;
#endif
FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, FALSE);
/*
rfbLog("rfbProcessFileTransfer(%dtype, %dparam, %dsize, %dlen)\n", contentType, contentParam, size, length);
*/
switch (contentType) {
case rfbDirContentRequest:
switch (contentParam) {
case rfbRDrivesList: /* Client requests the List of Local Drives */
/*
rfbLog("rfbProcessFileTransfer() rfbDirContentRequest: rfbRDrivesList:\n");
*/
/* Format when filled : "C:\<NULL>D:\<NULL>....Z:\<NULL><NULL>
*
* We replace the "\" char following the drive letter and ":"
* with a char corresponding to the type of drive
* We obtain something like "C:l<NULL>D:c<NULL>....Z:n\<NULL><NULL>"
* Isn't it ugly ?
* DRIVE_FIXED = 'l' (local?)
* DRIVE_REMOVABLE = 'f' (floppy?)
* DRIVE_CDROM = 'c'
* DRIVE_REMOTE = 'n'
*/
/* in unix, there are no 'drives' (We could list mount points though)
* We fake the root as a "C:" for the Winblows users
*/
filename2[0]='C';
filename2[1]=':';
filename2[2]='l';
filename2[3]=0;
filename2[4]=0;
retval = rfbSendFileTransferMessage(cl, rfbDirPacket, rfbADrivesList, 0, 5, filename2);
if (buffer!=NULL) free(buffer);
return retval;
break;
case rfbRDirContent: /* Client requests the content of a directory */
/*
rfbLog("rfbProcessFileTransfer() rfbDirContentRequest: rfbRDirContent\n");
*/
if ((buffer = rfbProcessFileTransferReadBuffer(cl, length))==NULL) return FALSE;
retval = rfbSendDirContent(cl, length, buffer);
if (buffer!=NULL) free(buffer);
return retval;
}
break;
case rfbDirPacket:
rfbLog("rfbProcessFileTransfer() rfbDirPacket\n");
break;
case rfbFileAcceptHeader:
rfbLog("rfbProcessFileTransfer() rfbFileAcceptHeader\n");
break;
case rfbCommandReturn:
rfbLog("rfbProcessFileTransfer() rfbCommandReturn\n");
break;
case rfbFileChecksums:
/* Destination file already exists - the viewer sends the checksums */
rfbLog("rfbProcessFileTransfer() rfbFileChecksums\n");
break;
case rfbFileTransferAccess:
rfbLog("rfbProcessFileTransfer() rfbFileTransferAccess\n");
break;
/*
* sending from the server to the viewer
*/
case rfbFileTransferRequest:
/*
rfbLog("rfbProcessFileTransfer() rfbFileTransferRequest:\n");
*/
/* add some space to the end of the buffer as we will be adding a timespec to it */
if ((buffer = rfbProcessFileTransferReadBuffer(cl, length))==NULL) return FALSE;
/* The client requests a File */
if (!rfbFilenameTranslate2UNIX(cl, buffer, filename1, sizeof(filename1)))
goto fail;
cl->fileTransfer.fd=open(filename1, O_RDONLY, 0744);
/*
*/
if (DB) rfbLog("rfbProcessFileTransfer() rfbFileTransferRequest(\"%s\"->\"%s\") Open: %s fd=%d\n", buffer, filename1, (cl->fileTransfer.fd==-1?"Failed":"Success"), cl->fileTransfer.fd);
if (cl->fileTransfer.fd!=-1) {
if (fstat(cl->fileTransfer.fd, &statbuf)!=0) {
close(cl->fileTransfer.fd);
cl->fileTransfer.fd=-1;
}
else
{
/* Add the File Time Stamp to the filename */
strftime(timespec, sizeof(timespec), "%m/%d/%Y %H:%M",gmtime(&statbuf.st_ctime));
buffer=realloc(buffer, length + strlen(timespec) + 2); /* comma, and Null term */
if (buffer==NULL) {
rfbLog("rfbProcessFileTransfer() rfbFileTransferRequest: Failed to malloc %d bytes\n", length + strlen(timespec) + 2);
return FALSE;
}
strcat(buffer,",");
strcat(buffer, timespec);
length = strlen(buffer);
if (DB) rfbLog("rfbProcessFileTransfer() buffer is now: \"%s\"\n", buffer);
}
}
/* The viewer supports compression if size==1 */
cl->fileTransfer.compressionEnabled = (size==1);
/*
rfbLog("rfbProcessFileTransfer() rfbFileTransferRequest(\"%s\"->\"%s\")%s\n", buffer, filename1, (size==1?" <Compression Enabled>":""));
*/
/* File Size in bytes, 0xFFFFFFFF (-1) means error */
retval = rfbSendFileTransferMessage(cl, rfbFileHeader, 0, (cl->fileTransfer.fd==-1 ? -1 : statbuf.st_size), length, buffer);
if (cl->fileTransfer.fd==-1)
{
if (buffer!=NULL) free(buffer);
return retval;
}
/* setup filetransfer stuff */
cl->fileTransfer.fileSize = statbuf.st_size;
cl->fileTransfer.numPackets = statbuf.st_size / sz_rfbBlockSize;
cl->fileTransfer.receiving = 0;
cl->fileTransfer.sending = 0; /* set when we receive a rfbFileHeader: */
/* TODO: finish 64-bit file size support */
sizeHtmp = 0;
LOCK(cl->sendMutex);
if (rfbWriteExact(cl, (char *)&sizeHtmp, 4) < 0) {
rfbLogPerror("rfbProcessFileTransfer: write");
rfbCloseClient(cl);
UNLOCK(cl->sendMutex);
if (buffer!=NULL) free(buffer);
return FALSE;
}
UNLOCK(cl->sendMutex);
break;
case rfbFileHeader:
/* Destination file (viewer side) is ready for reception (size > 0) or not (size = -1) */
if (size==-1) {
rfbLog("rfbProcessFileTransfer() rfbFileHeader (error, aborting)\n");
close(cl->fileTransfer.fd);
cl->fileTransfer.fd=-1;
return TRUE;
}
/*
rfbLog("rfbProcessFileTransfer() rfbFileHeader (%d bytes of a file)\n", size);
*/
/* Starts the transfer! */
cl->fileTransfer.sending=1;
return rfbSendFileTransferChunk(cl);
break;
/*
* sending from the viewer to the server
*/
case rfbFileTransferOffer:
/* client is sending a file to us */
/* buffer contains full path name (plus FileTime) */
/* size contains size of the file */
/*
rfbLog("rfbProcessFileTransfer() rfbFileTransferOffer:\n");
*/
if ((buffer = rfbProcessFileTransferReadBuffer(cl, length))==NULL) return FALSE;
/* Parse the FileTime */
p = strrchr(buffer, ',');
if (p!=NULL) {
*p = '\0';
strncpy(szFileTime, p+1, sizeof(szFileTime));
szFileTime[sizeof(szFileTime)-1] = '\x00'; /* ensure NULL terminating byte is present, even if copy overflowed */
} else
szFileTime[0]=0;
/* Need to read in sizeHtmp */
if ((n = rfbReadExact(cl, (char *)&sizeHtmp, 4)) <= 0) {
if (n != 0)
rfbLogPerror("rfbProcessFileTransfer: read sizeHtmp");
rfbCloseClient(cl);
/* NOTE: don't forget to free(buffer) if you return early! */
if (buffer!=NULL) free(buffer);
return FALSE;
}
sizeHtmp = Swap32IfLE(sizeHtmp);
if (!rfbFilenameTranslate2UNIX(cl, buffer, filename1, sizeof(filename1)))
goto fail;
/* If the file exists... We can send a rfbFileChecksums back to the client before we send an rfbFileAcceptHeader */
/* TODO: Delta Transfer */
cl->fileTransfer.fd=open(filename1, O_CREAT|O_WRONLY|O_TRUNC, 0744);
if (DB) rfbLog("rfbProcessFileTransfer() rfbFileTransferOffer(\"%s\"->\"%s\") %s %s fd=%d\n", buffer, filename1, (cl->fileTransfer.fd==-1?"Failed":"Success"), (cl->fileTransfer.fd==-1?strerror(errno):""), cl->fileTransfer.fd);
/*
*/
/* File Size in bytes, 0xFFFFFFFF (-1) means error */
retval = rfbSendFileTransferMessage(cl, rfbFileAcceptHeader, 0, (cl->fileTransfer.fd==-1 ? -1 : 0), length, buffer);
if (cl->fileTransfer.fd==-1) {
free(buffer);
return retval;
}
/* setup filetransfer stuff */
cl->fileTransfer.fileSize = size;
cl->fileTransfer.numPackets = size / sz_rfbBlockSize;
cl->fileTransfer.receiving = 1;
cl->fileTransfer.sending = 0;
break;
case rfbFilePacket:
/*
rfbLog("rfbProcessFileTransfer() rfbFilePacket:\n");
*/
if ((buffer = rfbProcessFileTransferReadBuffer(cl, length))==NULL) return FALSE;
if (cl->fileTransfer.fd!=-1) {
/* buffer contains the contents of the file */
if (size==0)
retval=write(cl->fileTransfer.fd, buffer, length);
else
{
#ifdef LIBVNCSERVER_HAVE_LIBZ
/* compressed packet */
nRet = uncompress(compBuff,&nRawBytes,(const unsigned char*)buffer, length);
if(nRet == Z_OK)
retval=write(cl->fileTransfer.fd, (char*)compBuff, nRawBytes);
else
retval = -1;
#else
/* Write the file out as received... */
retval=write(cl->fileTransfer.fd, buffer, length);
#endif
}
if (retval==-1)
{
close(cl->fileTransfer.fd);
cl->fileTransfer.fd=-1;
cl->fileTransfer.sending = 0;
cl->fileTransfer.receiving = 0;
}
}
break;
case rfbEndOfFile:
if (DB) rfbLog("rfbProcessFileTransfer() rfbEndOfFile\n");
/*
*/
if (cl->fileTransfer.fd!=-1)
close(cl->fileTransfer.fd);
cl->fileTransfer.fd=-1;
cl->fileTransfer.sending = 0;
cl->fileTransfer.receiving = 0;
break;
case rfbAbortFileTransfer:
if (DB) rfbLog("rfbProcessFileTransfer() rfbAbortFileTransfer\n");
/*
*/
if (cl->fileTransfer.fd!=-1)
{
close(cl->fileTransfer.fd);
cl->fileTransfer.fd=-1;
cl->fileTransfer.sending = 0;
cl->fileTransfer.receiving = 0;
}
else
{
/* We use this message for FileTransfer rights (<=RC18 versions)
* The client asks for FileTransfer permission
*/
if (contentParam == 0)
{
rfbLog("rfbProcessFileTransfer() File Transfer Permission DENIED! (Client Version <=RC18)\n");
/* Old method for FileTransfer handshake perimssion (<=RC18) (Deny it)*/
return rfbSendFileTransferMessage(cl, rfbAbortFileTransfer, 0, -1, 0, "");
}
/* New method is allowed */
if (cl->screen->getFileTransferPermission!=NULL)
{
if (cl->screen->getFileTransferPermission(cl)==TRUE)
{
rfbLog("rfbProcessFileTransfer() File Transfer Permission Granted!\n");
return rfbSendFileTransferMessage(cl, rfbFileTransferAccess, 0, 1 , 0, ""); /* Permit */
}
else
{
rfbLog("rfbProcessFileTransfer() File Transfer Permission DENIED!\n");
return rfbSendFileTransferMessage(cl, rfbFileTransferAccess, 0, -1 , 0, ""); /* Deny */
}
}
else
{
if (cl->screen->permitFileTransfer)
{
rfbLog("rfbProcessFileTransfer() File Transfer Permission Granted!\n");
return rfbSendFileTransferMessage(cl, rfbFileTransferAccess, 0, 1 , 0, ""); /* Permit */
}
else
{
rfbLog("rfbProcessFileTransfer() File Transfer Permission DENIED by default!\n");
return rfbSendFileTransferMessage(cl, rfbFileTransferAccess, 0, -1 , 0, ""); /* DEFAULT: DENY (for security) */
}
}
}
break;
case rfbCommand:
/*
rfbLog("rfbProcessFileTransfer() rfbCommand:\n");
*/
if ((buffer = rfbProcessFileTransferReadBuffer(cl, length))==NULL) return FALSE;
switch (contentParam) {
case rfbCDirCreate: /* Client requests the creation of a directory */
if (!rfbFilenameTranslate2UNIX(cl, buffer, filename1, sizeof(filename1)))
goto fail;
retval = mkdir(filename1, 0755);
if (DB) rfbLog("rfbProcessFileTransfer() rfbCommand: rfbCDirCreate(\"%s\"->\"%s\") %s\n", buffer, filename1, (retval==-1?"Failed":"Success"));
/*
*/
retval = rfbSendFileTransferMessage(cl, rfbCommandReturn, rfbADirCreate, retval, length, buffer);
if (buffer!=NULL) free(buffer);
return retval;
case rfbCFileDelete: /* Client requests the deletion of a file */
if (!rfbFilenameTranslate2UNIX(cl, buffer, filename1, sizeof(filename1)))
goto fail;
if (stat(filename1,&statbuf)==0)
{
if (S_ISDIR(statbuf.st_mode))
retval = rmdir(filename1);
else
retval = unlink(filename1);
}
else retval=-1;
retval = rfbSendFileTransferMessage(cl, rfbCommandReturn, rfbAFileDelete, retval, length, buffer);
if (buffer!=NULL) free(buffer);
return retval;
case rfbCFileRename: /* Client requests the Renaming of a file/directory */
p = strrchr(buffer, '*');
if (p != NULL)
{
/* Split into 2 filenames ('*' is a seperator) */
*p = '\0';
if (!rfbFilenameTranslate2UNIX(cl, buffer, filename1, sizeof(filename1)))
goto fail;
if (!rfbFilenameTranslate2UNIX(cl, p+1, filename2, sizeof(filename2)))
goto fail;
retval = rename(filename1,filename2);
if (DB) rfbLog("rfbProcessFileTransfer() rfbCommand: rfbCFileRename(\"%s\"->\"%s\" -->> \"%s\"->\"%s\") %s\n", buffer, filename1, p+1, filename2, (retval==-1?"Failed":"Success"));
/*
*/
/* Restore the buffer so the reply is good */
*p = '*';
retval = rfbSendFileTransferMessage(cl, rfbCommandReturn, rfbAFileRename, retval, length, buffer);
if (buffer!=NULL) free(buffer);
return retval;
}
break;
}
break;
}
/* NOTE: don't forget to free(buffer) if you return early! */
if (buffer!=NULL) free(buffer);
return TRUE;
fail:
if (buffer!=NULL) free(buffer);
return FALSE;
}
/*
* rfbProcessClientNormalMessage is called when the client has sent a normal
* protocol message.
*/
static void
rfbProcessClientNormalMessage(rfbClientPtr cl)
{
int n=0;
rfbClientToServerMsg msg;
char *str;
int i;
uint32_t enc=0;
uint32_t lastPreferredEncoding = -1;
char encBuf[64];
char encBuf2[64];
if ((n = rfbReadExact(cl, (char *)&msg, 1)) <= 0) {
if (n != 0)
rfbLogPerror("rfbProcessClientNormalMessage: read");
rfbCloseClient(cl);
return;
}
switch (msg.type) {
case rfbSetPixelFormat:
if ((n = rfbReadExact(cl, ((char *)&msg) + 1,
sz_rfbSetPixelFormatMsg - 1)) <= 0) {
if (n != 0)
rfbLogPerror("rfbProcessClientNormalMessage: read");
rfbCloseClient(cl);
return;
}
cl->format.bitsPerPixel = msg.spf.format.bitsPerPixel;
cl->format.depth = msg.spf.format.depth;
cl->format.bigEndian = (msg.spf.format.bigEndian ? TRUE : FALSE);
cl->format.trueColour = (msg.spf.format.trueColour ? TRUE : FALSE);
cl->format.redMax = Swap16IfLE(msg.spf.format.redMax);
cl->format.greenMax = Swap16IfLE(msg.spf.format.greenMax);
cl->format.blueMax = Swap16IfLE(msg.spf.format.blueMax);
cl->format.redShift = msg.spf.format.redShift;
cl->format.greenShift = msg.spf.format.greenShift;
cl->format.blueShift = msg.spf.format.blueShift;
cl->readyForSetColourMapEntries = TRUE;
cl->screen->setTranslateFunction(cl);
rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetPixelFormatMsg, sz_rfbSetPixelFormatMsg);
return;
case rfbFixColourMapEntries:
if ((n = rfbReadExact(cl, ((char *)&msg) + 1,
sz_rfbFixColourMapEntriesMsg - 1)) <= 0) {
if (n != 0)
rfbLogPerror("rfbProcessClientNormalMessage: read");
rfbCloseClient(cl);
return;
}
rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetPixelFormatMsg, sz_rfbSetPixelFormatMsg);
rfbLog("rfbProcessClientNormalMessage: %s",
"FixColourMapEntries unsupported\n");
rfbCloseClient(cl);
return;
/* NOTE: Some clients send us a set of encodings (ie: PointerPos) designed to enable/disable features...
* We may want to look into this...
* Example:
* case rfbEncodingXCursor:
* cl->enableCursorShapeUpdates = TRUE;
*
* Currently: cl->enableCursorShapeUpdates can *never* be turned off...
*/
case rfbSetEncodings:
{
if ((n = rfbReadExact(cl, ((char *)&msg) + 1,
sz_rfbSetEncodingsMsg - 1)) <= 0) {
if (n != 0)
rfbLogPerror("rfbProcessClientNormalMessage: read");
rfbCloseClient(cl);
return;
}
msg.se.nEncodings = Swap16IfLE(msg.se.nEncodings);
rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetEncodingsMsg+(msg.se.nEncodings*4),sz_rfbSetEncodingsMsg+(msg.se.nEncodings*4));
/*
* UltraVNC Client has the ability to adapt to changing network environments
* So, let's give it a change to tell us what it wants now!
*/
if (cl->preferredEncoding!=-1)
lastPreferredEncoding = cl->preferredEncoding;
/* Reset all flags to defaults (allows us to switch between PointerPos and Server Drawn Cursors) */
cl->preferredEncoding=-1;
cl->useCopyRect = FALSE;
cl->useNewFBSize = FALSE;
cl->cursorWasChanged = FALSE;
cl->useRichCursorEncoding = FALSE;
cl->enableCursorPosUpdates = FALSE;
cl->enableCursorShapeUpdates = FALSE;
cl->enableCursorShapeUpdates = FALSE;
cl->enableLastRectEncoding = FALSE;
cl->enableKeyboardLedState = FALSE;
cl->enableSupportedMessages = FALSE;
cl->enableSupportedEncodings = FALSE;
cl->enableServerIdentity = FALSE;
#if defined(LIBVNCSERVER_HAVE_LIBZ) || defined(LIBVNCSERVER_HAVE_LIBPNG)
cl->tightQualityLevel = -1;
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
cl->tightCompressLevel = TIGHT_DEFAULT_COMPRESSION;
cl->turboSubsampLevel = TURBO_DEFAULT_SUBSAMP;
cl->turboQualityLevel = -1;
#endif
#endif
for (i = 0; i < msg.se.nEncodings; i++) {
if ((n = rfbReadExact(cl, (char *)&enc, 4)) <= 0) {
if (n != 0)
rfbLogPerror("rfbProcessClientNormalMessage: read");
rfbCloseClient(cl);
return;
}
enc = Swap32IfLE(enc);
switch (enc) {
case rfbEncodingCopyRect:
cl->useCopyRect = TRUE;
break;
case rfbEncodingRaw:
case rfbEncodingRRE:
case rfbEncodingCoRRE:
case rfbEncodingHextile:
case rfbEncodingUltra:
#ifdef LIBVNCSERVER_HAVE_LIBZ
case rfbEncodingZlib:
case rfbEncodingZRLE:
case rfbEncodingZYWRLE:
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
case rfbEncodingTight:
#endif
#endif
#ifdef LIBVNCSERVER_HAVE_LIBPNG
case rfbEncodingTightPng:
#endif
/* The first supported encoding is the 'preferred' encoding */
if (cl->preferredEncoding == -1)
cl->preferredEncoding = enc;
break;
case rfbEncodingXCursor:
if(!cl->screen->dontConvertRichCursorToXCursor) {
rfbLog("Enabling X-style cursor updates for client %s\n",
cl->host);
/* if cursor was drawn, hide the cursor */
if(!cl->enableCursorShapeUpdates)
rfbRedrawAfterHideCursor(cl,NULL);
cl->enableCursorShapeUpdates = TRUE;
cl->cursorWasChanged = TRUE;
}
break;
case rfbEncodingRichCursor:
rfbLog("Enabling full-color cursor updates for client %s\n",
cl->host);
/* if cursor was drawn, hide the cursor */
if(!cl->enableCursorShapeUpdates)
rfbRedrawAfterHideCursor(cl,NULL);
cl->enableCursorShapeUpdates = TRUE;
cl->useRichCursorEncoding = TRUE;
cl->cursorWasChanged = TRUE;
break;
case rfbEncodingPointerPos:
if (!cl->enableCursorPosUpdates) {
rfbLog("Enabling cursor position updates for client %s\n",
cl->host);
cl->enableCursorPosUpdates = TRUE;
cl->cursorWasMoved = TRUE;
}
break;
case rfbEncodingLastRect:
if (!cl->enableLastRectEncoding) {
rfbLog("Enabling LastRect protocol extension for client "
"%s\n", cl->host);
cl->enableLastRectEncoding = TRUE;
}
break;
case rfbEncodingNewFBSize:
if (!cl->useNewFBSize) {
rfbLog("Enabling NewFBSize protocol extension for client "
"%s\n", cl->host);
cl->useNewFBSize = TRUE;
}
break;
case rfbEncodingKeyboardLedState:
if (!cl->enableKeyboardLedState) {
rfbLog("Enabling KeyboardLedState protocol extension for client "
"%s\n", cl->host);
cl->enableKeyboardLedState = TRUE;
}
break;
case rfbEncodingSupportedMessages:
if (!cl->enableSupportedMessages) {
rfbLog("Enabling SupportedMessages protocol extension for client "
"%s\n", cl->host);
cl->enableSupportedMessages = TRUE;
}
break;
case rfbEncodingSupportedEncodings:
if (!cl->enableSupportedEncodings) {
rfbLog("Enabling SupportedEncodings protocol extension for client "
"%s\n", cl->host);
cl->enableSupportedEncodings = TRUE;
}
break;
case rfbEncodingServerIdentity:
if (!cl->enableServerIdentity) {
rfbLog("Enabling ServerIdentity protocol extension for client "
"%s\n", cl->host);
cl->enableServerIdentity = TRUE;
}
break;
case rfbEncodingXvp:
if (cl->screen->xvpHook) {
rfbLog("Enabling Xvp protocol extension for client "
"%s\n", cl->host);
if (!rfbSendXvp(cl, 1, rfbXvp_Init)) {
rfbCloseClient(cl);
return;
}
}
break;
default:
#if defined(LIBVNCSERVER_HAVE_LIBZ) || defined(LIBVNCSERVER_HAVE_LIBPNG)
if ( enc >= (uint32_t)rfbEncodingCompressLevel0 &&
enc <= (uint32_t)rfbEncodingCompressLevel9 ) {
cl->zlibCompressLevel = enc & 0x0F;
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
cl->tightCompressLevel = enc & 0x0F;
rfbLog("Using compression level %d for client %s\n",
cl->tightCompressLevel, cl->host);
#endif
} else if ( enc >= (uint32_t)rfbEncodingQualityLevel0 &&
enc <= (uint32_t)rfbEncodingQualityLevel9 ) {
cl->tightQualityLevel = enc & 0x0F;
rfbLog("Using image quality level %d for client %s\n",
cl->tightQualityLevel, cl->host);
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
cl->turboQualityLevel = tight2turbo_qual[enc & 0x0F];
cl->turboSubsampLevel = tight2turbo_subsamp[enc & 0x0F];
rfbLog("Using JPEG subsampling %d, Q%d for client %s\n",
cl->turboSubsampLevel, cl->turboQualityLevel, cl->host);
} else if ( enc >= (uint32_t)rfbEncodingFineQualityLevel0 + 1 &&
enc <= (uint32_t)rfbEncodingFineQualityLevel100 ) {
cl->turboQualityLevel = enc & 0xFF;
rfbLog("Using fine quality level %d for client %s\n",
cl->turboQualityLevel, cl->host);
} else if ( enc >= (uint32_t)rfbEncodingSubsamp1X &&
enc <= (uint32_t)rfbEncodingSubsampGray ) {
cl->turboSubsampLevel = enc & 0xFF;
rfbLog("Using subsampling level %d for client %s\n",
cl->turboSubsampLevel, cl->host);
#endif
} else
#endif
{
rfbExtensionData* e;
for(e = cl->extensions; e;) {
rfbExtensionData* next = e->next;
if(e->extension->enablePseudoEncoding &&
e->extension->enablePseudoEncoding(cl,
&e->data, (int)enc))
/* ext handles this encoding */
break;
e = next;
}
if(e == NULL) {
rfbBool handled = FALSE;
/* if the pseudo encoding is not handled by the
enabled extensions, search through all
extensions. */
rfbProtocolExtension* e;
for(e = rfbGetExtensionIterator(); e;) {
int* encs = e->pseudoEncodings;
while(encs && *encs!=0) {
if(*encs==(int)enc) {
void* data = NULL;
if(!e->enablePseudoEncoding(cl, &data, (int)enc)) {
rfbLog("Installed extension pretends to handle pseudo encoding 0x%x, but does not!\n",(int)enc);
} else {
rfbEnableExtension(cl, e, data);
handled = TRUE;
e = NULL;
break;
}
}
encs++;
}
if(e)
e = e->next;
}
rfbReleaseExtensionIterator();
if(!handled)
rfbLog("rfbProcessClientNormalMessage: "
"ignoring unsupported encoding type %s\n",
encodingName(enc,encBuf,sizeof(encBuf)));
}
}
}
}
if (cl->preferredEncoding == -1) {
if (lastPreferredEncoding==-1) {
cl->preferredEncoding = rfbEncodingRaw;
rfbLog("Defaulting to %s encoding for client %s\n", encodingName(cl->preferredEncoding,encBuf,sizeof(encBuf)),cl->host);
}
else {
cl->preferredEncoding = lastPreferredEncoding;
rfbLog("Sticking with %s encoding for client %s\n", encodingName(cl->preferredEncoding,encBuf,sizeof(encBuf)),cl->host);
}
}
else
{
if (lastPreferredEncoding==-1) {
rfbLog("Using %s encoding for client %s\n", encodingName(cl->preferredEncoding,encBuf,sizeof(encBuf)),cl->host);
} else {
rfbLog("Switching from %s to %s Encoding for client %s\n",
encodingName(lastPreferredEncoding,encBuf2,sizeof(encBuf2)),
encodingName(cl->preferredEncoding,encBuf,sizeof(encBuf)), cl->host);
}
}
if (cl->enableCursorPosUpdates && !cl->enableCursorShapeUpdates) {
rfbLog("Disabling cursor position updates for client %s\n",
cl->host);
cl->enableCursorPosUpdates = FALSE;
}
return;
}
case rfbFramebufferUpdateRequest:
{
sraRegionPtr tmpRegion;
if ((n = rfbReadExact(cl, ((char *)&msg) + 1,
sz_rfbFramebufferUpdateRequestMsg-1)) <= 0) {
if (n != 0)
rfbLogPerror("rfbProcessClientNormalMessage: read");
rfbCloseClient(cl);
return;
}
rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbFramebufferUpdateRequestMsg,sz_rfbFramebufferUpdateRequestMsg);
/* The values come in based on the scaled screen, we need to convert them to
* values based on the main screen's coordinate system
*/
if(!rectSwapIfLEAndClip(&msg.fur.x,&msg.fur.y,&msg.fur.w,&msg.fur.h,cl))
{
rfbLog("Warning, ignoring rfbFramebufferUpdateRequest: %dXx%dY-%dWx%dH\n",msg.fur.x, msg.fur.y, msg.fur.w, msg.fur.h);
return;
}
tmpRegion =
sraRgnCreateRect(msg.fur.x,
msg.fur.y,
msg.fur.x+msg.fur.w,
msg.fur.y+msg.fur.h);
LOCK(cl->updateMutex);
sraRgnOr(cl->requestedRegion,tmpRegion);
if (!cl->readyForSetColourMapEntries) {
/* client hasn't sent a SetPixelFormat so is using server's */
cl->readyForSetColourMapEntries = TRUE;
if (!cl->format.trueColour) {
if (!rfbSetClientColourMap(cl, 0, 0)) {
sraRgnDestroy(tmpRegion);
TSIGNAL(cl->updateCond);
UNLOCK(cl->updateMutex);
return;
}
}
}
if (!msg.fur.incremental) {
sraRgnOr(cl->modifiedRegion,tmpRegion);
sraRgnSubtract(cl->copyRegion,tmpRegion);
}
TSIGNAL(cl->updateCond);
UNLOCK(cl->updateMutex);
sraRgnDestroy(tmpRegion);
return;
}
case rfbKeyEvent:
if ((n = rfbReadExact(cl, ((char *)&msg) + 1,
sz_rfbKeyEventMsg - 1)) <= 0) {
if (n != 0)
rfbLogPerror("rfbProcessClientNormalMessage: read");
rfbCloseClient(cl);
return;
}
rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbKeyEventMsg, sz_rfbKeyEventMsg);
if(!cl->viewOnly) {
cl->screen->kbdAddEvent(msg.ke.down, (rfbKeySym)Swap32IfLE(msg.ke.key), cl);
}
return;
case rfbPointerEvent:
if ((n = rfbReadExact(cl, ((char *)&msg) + 1,
sz_rfbPointerEventMsg - 1)) <= 0) {
if (n != 0)
rfbLogPerror("rfbProcessClientNormalMessage: read");
rfbCloseClient(cl);
return;
}
rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbPointerEventMsg, sz_rfbPointerEventMsg);
if (cl->screen->pointerClient && cl->screen->pointerClient != cl)
return;
if (msg.pe.buttonMask == 0)
cl->screen->pointerClient = NULL;
else
cl->screen->pointerClient = cl;
if(!cl->viewOnly) {
if (msg.pe.buttonMask != cl->lastPtrButtons ||
cl->screen->deferPtrUpdateTime == 0) {
cl->screen->ptrAddEvent(msg.pe.buttonMask,
ScaleX(cl->scaledScreen, cl->screen, Swap16IfLE(msg.pe.x)),
ScaleY(cl->scaledScreen, cl->screen, Swap16IfLE(msg.pe.y)),
cl);
cl->lastPtrButtons = msg.pe.buttonMask;
} else {
cl->lastPtrX = ScaleX(cl->scaledScreen, cl->screen, Swap16IfLE(msg.pe.x));
cl->lastPtrY = ScaleY(cl->scaledScreen, cl->screen, Swap16IfLE(msg.pe.y));
cl->lastPtrButtons = msg.pe.buttonMask;
}
}
return;
case rfbFileTransfer:
if ((n = rfbReadExact(cl, ((char *)&msg) + 1,
sz_rfbFileTransferMsg - 1)) <= 0) {
if (n != 0)
rfbLogPerror("rfbProcessClientNormalMessage: read");
rfbCloseClient(cl);
return;
}
msg.ft.size = Swap32IfLE(msg.ft.size);
msg.ft.length = Swap32IfLE(msg.ft.length);
/* record statistics in rfbProcessFileTransfer as length is filled with garbage when it is not valid */
rfbProcessFileTransfer(cl, msg.ft.contentType, msg.ft.contentParam, msg.ft.size, msg.ft.length);
return;
case rfbSetSW:
if ((n = rfbReadExact(cl, ((char *)&msg) + 1,
sz_rfbSetSWMsg - 1)) <= 0) {
if (n != 0)
rfbLogPerror("rfbProcessClientNormalMessage: read");
rfbCloseClient(cl);
return;
}
msg.sw.x = Swap16IfLE(msg.sw.x);
msg.sw.y = Swap16IfLE(msg.sw.y);
rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetSWMsg, sz_rfbSetSWMsg);
/* msg.sw.status is not initialized in the ultraVNC viewer and contains random numbers (why???) */
rfbLog("Received a rfbSetSingleWindow(%d x, %d y)\n", msg.sw.x, msg.sw.y);
if (cl->screen->setSingleWindow!=NULL)
cl->screen->setSingleWindow(cl, msg.sw.x, msg.sw.y);
return;
case rfbSetServerInput:
if ((n = rfbReadExact(cl, ((char *)&msg) + 1,
sz_rfbSetServerInputMsg - 1)) <= 0) {
if (n != 0)
rfbLogPerror("rfbProcessClientNormalMessage: read");
rfbCloseClient(cl);
return;
}
rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetServerInputMsg, sz_rfbSetServerInputMsg);
/* msg.sim.pad is not initialized in the ultraVNC viewer and contains random numbers (why???) */
/* msg.sim.pad = Swap16IfLE(msg.sim.pad); */
rfbLog("Received a rfbSetServerInput(%d status)\n", msg.sim.status);
if (cl->screen->setServerInput!=NULL)
cl->screen->setServerInput(cl, msg.sim.status);
return;
case rfbTextChat:
if ((n = rfbReadExact(cl, ((char *)&msg) + 1,
sz_rfbTextChatMsg - 1)) <= 0) {
if (n != 0)
rfbLogPerror("rfbProcessClientNormalMessage: read");
rfbCloseClient(cl);
return;
}
msg.tc.pad2 = Swap16IfLE(msg.tc.pad2);
msg.tc.length = Swap32IfLE(msg.tc.length);
switch (msg.tc.length) {
case rfbTextChatOpen:
case rfbTextChatClose:
case rfbTextChatFinished:
/* commands do not have text following */
/* Why couldn't they have used the pad byte??? */
str=NULL;
rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbTextChatMsg, sz_rfbTextChatMsg);
break;
default:
if ((msg.tc.length>0) && (msg.tc.length<rfbTextMaxSize))
{
str = (char *)malloc(msg.tc.length);
if (str==NULL)
{
rfbLog("Unable to malloc %d bytes for a TextChat Message\n", msg.tc.length);
rfbCloseClient(cl);
return;
}
if ((n = rfbReadExact(cl, str, msg.tc.length)) <= 0) {
if (n != 0)
rfbLogPerror("rfbProcessClientNormalMessage: read");
free(str);
rfbCloseClient(cl);
return;
}
rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbTextChatMsg+msg.tc.length, sz_rfbTextChatMsg+msg.tc.length);
}
else
{
/* This should never happen */
rfbLog("client sent us a Text Message that is too big %d>%d\n", msg.tc.length, rfbTextMaxSize);
rfbCloseClient(cl);
return;
}
}
/* Note: length can be commands: rfbTextChatOpen, rfbTextChatClose, and rfbTextChatFinished
* at which point, the str is NULL (as it is not sent)
*/
if (cl->screen->setTextChat!=NULL)
cl->screen->setTextChat(cl, msg.tc.length, str);
free(str);
return;
case rfbClientCutText:
if ((n = rfbReadExact(cl, ((char *)&msg) + 1,
sz_rfbClientCutTextMsg - 1)) <= 0) {
if (n != 0)
rfbLogPerror("rfbProcessClientNormalMessage: read");
rfbCloseClient(cl);
return;
}
msg.cct.length = Swap32IfLE(msg.cct.length);
/* uint32_t input is passed to malloc()'s size_t argument,
* to rfbReadExact()'s int argument, to rfbStatRecordMessageRcvd()'s int
* argument increased of sz_rfbClientCutTextMsg, and to setXCutText()'s int
* argument. Here we impose a limit of 1 MB so that the value fits
* into all of the types to prevent from misinterpretation and thus
* from accessing uninitialized memory (CVE-2018-7225) and also to
* prevent from a denial-of-service by allocating too much memory in
* the server. */
if (msg.cct.length > 1<<20) {
rfbLog("rfbClientCutText: too big cut text length requested: %u B > 1 MB\n", (unsigned int)msg.cct.length);
rfbCloseClient(cl);
return;
}
/* Allow zero-length client cut text. */
str = (char *)calloc(msg.cct.length ? msg.cct.length : 1, 1);
if (str == NULL) {
rfbLogPerror("rfbProcessClientNormalMessage: not enough memory");
rfbCloseClient(cl);
return;
}
if ((n = rfbReadExact(cl, str, msg.cct.length)) <= 0) {
if (n != 0)
rfbLogPerror("rfbProcessClientNormalMessage: read");
free(str);
rfbCloseClient(cl);
return;
}
rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbClientCutTextMsg+msg.cct.length, sz_rfbClientCutTextMsg+msg.cct.length);
if(!cl->viewOnly) {
cl->screen->setXCutText(str, msg.cct.length, cl);
}
free(str);
return;
case rfbPalmVNCSetScaleFactor:
cl->PalmVNC = TRUE;
if ((n = rfbReadExact(cl, ((char *)&msg) + 1,
sz_rfbSetScaleMsg - 1)) <= 0) {
if (n != 0)
rfbLogPerror("rfbProcessClientNormalMessage: read");
rfbCloseClient(cl);
return;
}
if (msg.ssc.scale == 0) {
rfbLogPerror("rfbProcessClientNormalMessage: will not accept a scale factor of zero");
rfbCloseClient(cl);
return;
}
rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetScaleMsg, sz_rfbSetScaleMsg);
rfbLog("rfbSetScale(%d)\n", msg.ssc.scale);
rfbScalingSetup(cl,cl->screen->width/msg.ssc.scale, cl->screen->height/msg.ssc.scale);
rfbSendNewScaleSize(cl);
return;
case rfbSetScale:
if ((n = rfbReadExact(cl, ((char *)&msg) + 1,
sz_rfbSetScaleMsg - 1)) <= 0) {
if (n != 0)
rfbLogPerror("rfbProcessClientNormalMessage: read");
rfbCloseClient(cl);
return;
}
if (msg.ssc.scale == 0) {
rfbLogPerror("rfbProcessClientNormalMessage: will not accept a scale factor of zero");
rfbCloseClient(cl);
return;
}
rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetScaleMsg, sz_rfbSetScaleMsg);
rfbLog("rfbSetScale(%d)\n", msg.ssc.scale);
rfbScalingSetup(cl,cl->screen->width/msg.ssc.scale, cl->screen->height/msg.ssc.scale);
rfbSendNewScaleSize(cl);
return;
case rfbXvp:
if ((n = rfbReadExact(cl, ((char *)&msg) + 1,
sz_rfbXvpMsg - 1)) <= 0) {
if (n != 0)
rfbLogPerror("rfbProcessClientNormalMessage: read");
rfbCloseClient(cl);
return;
}
rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbXvpMsg, sz_rfbXvpMsg);
/* only version when is defined, so echo back a fail */
if(msg.xvp.version != 1) {
rfbSendXvp(cl, msg.xvp.version, rfbXvp_Fail);
}
else {
/* if the hook exists and fails, send a fail msg */
if(cl->screen->xvpHook && !cl->screen->xvpHook(cl, msg.xvp.version, msg.xvp.code))
rfbSendXvp(cl, 1, rfbXvp_Fail);
}
return;
default:
{
rfbExtensionData *e,*next;
for(e=cl->extensions; e;) {
next = e->next;
if(e->extension->handleMessage &&
e->extension->handleMessage(cl, e->data, &msg))
{
rfbStatRecordMessageRcvd(cl, msg.type, 0, 0); /* Extension should handle this */
return;
}
e = next;
}
rfbLog("rfbProcessClientNormalMessage: unknown message type %d\n",
msg.type);
rfbLog(" ... closing connection\n");
rfbCloseClient(cl);
return;
}
}
}
/*
* rfbSendFramebufferUpdate - send the currently pending framebuffer update to
* the RFB client.
* givenUpdateRegion is not changed.
*/
rfbBool
rfbSendFramebufferUpdate(rfbClientPtr cl,
sraRegionPtr givenUpdateRegion)
{
sraRectangleIterator* i=NULL;
sraRect rect;
int nUpdateRegionRects;
rfbFramebufferUpdateMsg *fu = (rfbFramebufferUpdateMsg *)cl->updateBuf;
sraRegionPtr updateRegion,updateCopyRegion,tmpRegion;
int dx, dy;
rfbBool sendCursorShape = FALSE;
rfbBool sendCursorPos = FALSE;
rfbBool sendKeyboardLedState = FALSE;
rfbBool sendSupportedMessages = FALSE;
rfbBool sendSupportedEncodings = FALSE;
rfbBool sendServerIdentity = FALSE;
rfbBool result = TRUE;
if(cl->screen->displayHook)
cl->screen->displayHook(cl);
/*
* If framebuffer size was changed and the client supports NewFBSize
* encoding, just send NewFBSize marker and return.
*/
if (cl->useNewFBSize && cl->newFBSizePending) {
LOCK(cl->updateMutex);
cl->newFBSizePending = FALSE;
UNLOCK(cl->updateMutex);
fu->type = rfbFramebufferUpdate;
fu->nRects = Swap16IfLE(1);
cl->ublen = sz_rfbFramebufferUpdateMsg;
if (!rfbSendNewFBSize(cl, cl->scaledScreen->width, cl->scaledScreen->height)) {
if(cl->screen->displayFinishedHook)
cl->screen->displayFinishedHook(cl, FALSE);
return FALSE;
}
result = rfbSendUpdateBuf(cl);
if(cl->screen->displayFinishedHook)
cl->screen->displayFinishedHook(cl, result);
return result;
}
/*
* If this client understands cursor shape updates, cursor should be
* removed from the framebuffer. Otherwise, make sure it's put up.
*/
if (cl->enableCursorShapeUpdates) {
if (cl->cursorWasChanged && cl->readyForSetColourMapEntries)
sendCursorShape = TRUE;
}
/*
* Do we plan to send cursor position update?
*/
if (cl->enableCursorPosUpdates && cl->cursorWasMoved)
sendCursorPos = TRUE;
/*
* Do we plan to send a keyboard state update?
*/
if ((cl->enableKeyboardLedState) &&
(cl->screen->getKeyboardLedStateHook!=NULL))
{
int x;
x=cl->screen->getKeyboardLedStateHook(cl->screen);
if (x!=cl->lastKeyboardLedState)
{
sendKeyboardLedState = TRUE;
cl->lastKeyboardLedState=x;
}
}
/*
* Do we plan to send a rfbEncodingSupportedMessages?
*/
if (cl->enableSupportedMessages)
{
sendSupportedMessages = TRUE;
/* We only send this message ONCE <per setEncodings message received>
* (We disable it here)
*/
cl->enableSupportedMessages = FALSE;
}
/*
* Do we plan to send a rfbEncodingSupportedEncodings?
*/
if (cl->enableSupportedEncodings)
{
sendSupportedEncodings = TRUE;
/* We only send this message ONCE <per setEncodings message received>
* (We disable it here)
*/
cl->enableSupportedEncodings = FALSE;
}
/*
* Do we plan to send a rfbEncodingServerIdentity?
*/
if (cl->enableServerIdentity)
{
sendServerIdentity = TRUE;
/* We only send this message ONCE <per setEncodings message received>
* (We disable it here)
*/
cl->enableServerIdentity = FALSE;
}
LOCK(cl->updateMutex);
/*
* The modifiedRegion may overlap the destination copyRegion. We remove
* any overlapping bits from the copyRegion (since they'd only be
* overwritten anyway).
*/
sraRgnSubtract(cl->copyRegion,cl->modifiedRegion);
/*
* The client is interested in the region requestedRegion. The region
* which should be updated now is the intersection of requestedRegion
* and the union of modifiedRegion and copyRegion. If it's empty then
* no update is needed.
*/
updateRegion = sraRgnCreateRgn(givenUpdateRegion);
if(cl->screen->progressiveSliceHeight>0) {
int height=cl->screen->progressiveSliceHeight,
y=cl->progressiveSliceY;
sraRegionPtr bbox=sraRgnBBox(updateRegion);
sraRect rect;
if(sraRgnPopRect(bbox,&rect,0)) {
sraRegionPtr slice;
if(y<rect.y1 || y>=rect.y2)
y=rect.y1;
slice=sraRgnCreateRect(0,y,cl->screen->width,y+height);
sraRgnAnd(updateRegion,slice);
sraRgnDestroy(slice);
}
sraRgnDestroy(bbox);
y+=height;
if(y>=cl->screen->height)
y=0;
cl->progressiveSliceY=y;
}
sraRgnOr(updateRegion,cl->copyRegion);
if(!sraRgnAnd(updateRegion,cl->requestedRegion) &&
sraRgnEmpty(updateRegion) &&
(cl->enableCursorShapeUpdates ||
(cl->cursorX == cl->screen->cursorX && cl->cursorY == cl->screen->cursorY)) &&
!sendCursorShape && !sendCursorPos && !sendKeyboardLedState &&
!sendSupportedMessages && !sendSupportedEncodings && !sendServerIdentity) {
sraRgnDestroy(updateRegion);
UNLOCK(cl->updateMutex);
if(cl->screen->displayFinishedHook)
cl->screen->displayFinishedHook(cl, TRUE);
return TRUE;
}
/*
* We assume that the client doesn't have any pixel data outside the
* requestedRegion. In other words, both the source and destination of a
* copy must lie within requestedRegion. So the region we can send as a
* copy is the intersection of the copyRegion with both the requestedRegion
* and the requestedRegion translated by the amount of the copy. We set
* updateCopyRegion to this.
*/
updateCopyRegion = sraRgnCreateRgn(cl->copyRegion);
sraRgnAnd(updateCopyRegion,cl->requestedRegion);
tmpRegion = sraRgnCreateRgn(cl->requestedRegion);
sraRgnOffset(tmpRegion,cl->copyDX,cl->copyDY);
sraRgnAnd(updateCopyRegion,tmpRegion);
sraRgnDestroy(tmpRegion);
dx = cl->copyDX;
dy = cl->copyDY;
/*
* Next we remove updateCopyRegion from updateRegion so that updateRegion
* is the part of this update which is sent as ordinary pixel data (i.e not
* a copy).
*/
sraRgnSubtract(updateRegion,updateCopyRegion);
/*
* Finally we leave modifiedRegion to be the remainder (if any) of parts of
* the screen which are modified but outside the requestedRegion. We also
* empty both the requestedRegion and the copyRegion - note that we never
* carry over a copyRegion for a future update.
*/
sraRgnOr(cl->modifiedRegion,cl->copyRegion);
sraRgnSubtract(cl->modifiedRegion,updateRegion);
sraRgnSubtract(cl->modifiedRegion,updateCopyRegion);
sraRgnMakeEmpty(cl->requestedRegion);
sraRgnMakeEmpty(cl->copyRegion);
cl->copyDX = 0;
cl->copyDY = 0;
UNLOCK(cl->updateMutex);
if (!cl->enableCursorShapeUpdates) {
if(cl->cursorX != cl->screen->cursorX || cl->cursorY != cl->screen->cursorY) {
rfbRedrawAfterHideCursor(cl,updateRegion);
LOCK(cl->screen->cursorMutex);
cl->cursorX = cl->screen->cursorX;
cl->cursorY = cl->screen->cursorY;
UNLOCK(cl->screen->cursorMutex);
rfbRedrawAfterHideCursor(cl,updateRegion);
}
rfbShowCursor(cl);
}
/*
* Now send the update.
*/
rfbStatRecordMessageSent(cl, rfbFramebufferUpdate, 0, 0);
if (cl->preferredEncoding == rfbEncodingCoRRE) {
nUpdateRegionRects = 0;
for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){
int x = rect.x1;
int y = rect.y1;
int w = rect.x2 - x;
int h = rect.y2 - y;
int rectsPerRow, rows;
/* We need to count the number of rects in the scaled screen */
if (cl->screen!=cl->scaledScreen)
rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate");
rectsPerRow = (w-1)/cl->correMaxWidth+1;
rows = (h-1)/cl->correMaxHeight+1;
nUpdateRegionRects += rectsPerRow*rows;
}
sraRgnReleaseIterator(i); i=NULL;
} else if (cl->preferredEncoding == rfbEncodingUltra) {
nUpdateRegionRects = 0;
for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){
int x = rect.x1;
int y = rect.y1;
int w = rect.x2 - x;
int h = rect.y2 - y;
/* We need to count the number of rects in the scaled screen */
if (cl->screen!=cl->scaledScreen)
rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate");
nUpdateRegionRects += (((h-1) / (ULTRA_MAX_SIZE( w ) / w)) + 1);
}
sraRgnReleaseIterator(i); i=NULL;
#ifdef LIBVNCSERVER_HAVE_LIBZ
} else if (cl->preferredEncoding == rfbEncodingZlib) {
nUpdateRegionRects = 0;
for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){
int x = rect.x1;
int y = rect.y1;
int w = rect.x2 - x;
int h = rect.y2 - y;
/* We need to count the number of rects in the scaled screen */
if (cl->screen!=cl->scaledScreen)
rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate");
nUpdateRegionRects += (((h-1) / (ZLIB_MAX_SIZE( w ) / w)) + 1);
}
sraRgnReleaseIterator(i); i=NULL;
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
} else if (cl->preferredEncoding == rfbEncodingTight) {
nUpdateRegionRects = 0;
for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){
int x = rect.x1;
int y = rect.y1;
int w = rect.x2 - x;
int h = rect.y2 - y;
int n;
/* We need to count the number of rects in the scaled screen */
if (cl->screen!=cl->scaledScreen)
rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate");
n = rfbNumCodedRectsTight(cl, x, y, w, h);
if (n == 0) {
nUpdateRegionRects = 0xFFFF;
break;
}
nUpdateRegionRects += n;
}
sraRgnReleaseIterator(i); i=NULL;
#endif
#endif
#if defined(LIBVNCSERVER_HAVE_LIBJPEG) && defined(LIBVNCSERVER_HAVE_LIBPNG)
} else if (cl->preferredEncoding == rfbEncodingTightPng) {
nUpdateRegionRects = 0;
for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){
int x = rect.x1;
int y = rect.y1;
int w = rect.x2 - x;
int h = rect.y2 - y;
int n;
/* We need to count the number of rects in the scaled screen */
if (cl->screen!=cl->scaledScreen)
rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate");
n = rfbNumCodedRectsTight(cl, x, y, w, h);
if (n == 0) {
nUpdateRegionRects = 0xFFFF;
break;
}
nUpdateRegionRects += n;
}
sraRgnReleaseIterator(i); i=NULL;
#endif
} else {
nUpdateRegionRects = sraRgnCountRects(updateRegion);
}
fu->type = rfbFramebufferUpdate;
if (nUpdateRegionRects != 0xFFFF) {
if(cl->screen->maxRectsPerUpdate>0
/* CoRRE splits the screen into smaller squares */
&& cl->preferredEncoding != rfbEncodingCoRRE
/* Ultra encoding splits rectangles up into smaller chunks */
&& cl->preferredEncoding != rfbEncodingUltra
#ifdef LIBVNCSERVER_HAVE_LIBZ
/* Zlib encoding splits rectangles up into smaller chunks */
&& cl->preferredEncoding != rfbEncodingZlib
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
/* Tight encoding counts the rectangles differently */
&& cl->preferredEncoding != rfbEncodingTight
#endif
#endif
#ifdef LIBVNCSERVER_HAVE_LIBPNG
/* Tight encoding counts the rectangles differently */
&& cl->preferredEncoding != rfbEncodingTightPng
#endif
&& nUpdateRegionRects>cl->screen->maxRectsPerUpdate) {
sraRegion* newUpdateRegion = sraRgnBBox(updateRegion);
sraRgnDestroy(updateRegion);
updateRegion = newUpdateRegion;
nUpdateRegionRects = sraRgnCountRects(updateRegion);
}
fu->nRects = Swap16IfLE((uint16_t)(sraRgnCountRects(updateCopyRegion) +
nUpdateRegionRects +
!!sendCursorShape + !!sendCursorPos + !!sendKeyboardLedState +
!!sendSupportedMessages + !!sendSupportedEncodings + !!sendServerIdentity));
} else {
fu->nRects = 0xFFFF;
}
cl->ublen = sz_rfbFramebufferUpdateMsg;
if (sendCursorShape) {
cl->cursorWasChanged = FALSE;
if (!rfbSendCursorShape(cl))
goto updateFailed;
}
if (sendCursorPos) {
cl->cursorWasMoved = FALSE;
if (!rfbSendCursorPos(cl))
goto updateFailed;
}
if (sendKeyboardLedState) {
if (!rfbSendKeyboardLedState(cl))
goto updateFailed;
}
if (sendSupportedMessages) {
if (!rfbSendSupportedMessages(cl))
goto updateFailed;
}
if (sendSupportedEncodings) {
if (!rfbSendSupportedEncodings(cl))
goto updateFailed;
}
if (sendServerIdentity) {
if (!rfbSendServerIdentity(cl))
goto updateFailed;
}
if (!sraRgnEmpty(updateCopyRegion)) {
if (!rfbSendCopyRegion(cl,updateCopyRegion,dx,dy))
goto updateFailed;
}
for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){
int x = rect.x1;
int y = rect.y1;
int w = rect.x2 - x;
int h = rect.y2 - y;
/* We need to count the number of rects in the scaled screen */
if (cl->screen!=cl->scaledScreen)
rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate");
switch (cl->preferredEncoding) {
case -1:
case rfbEncodingRaw:
if (!rfbSendRectEncodingRaw(cl, x, y, w, h))
goto updateFailed;
break;
case rfbEncodingRRE:
if (!rfbSendRectEncodingRRE(cl, x, y, w, h))
goto updateFailed;
break;
case rfbEncodingCoRRE:
if (!rfbSendRectEncodingCoRRE(cl, x, y, w, h))
goto updateFailed;
break;
case rfbEncodingHextile:
if (!rfbSendRectEncodingHextile(cl, x, y, w, h))
goto updateFailed;
break;
case rfbEncodingUltra:
if (!rfbSendRectEncodingUltra(cl, x, y, w, h))
goto updateFailed;
break;
#ifdef LIBVNCSERVER_HAVE_LIBZ
case rfbEncodingZlib:
if (!rfbSendRectEncodingZlib(cl, x, y, w, h))
goto updateFailed;
break;
case rfbEncodingZRLE:
case rfbEncodingZYWRLE:
if (!rfbSendRectEncodingZRLE(cl, x, y, w, h))
goto updateFailed;
break;
#endif
#if defined(LIBVNCSERVER_HAVE_LIBJPEG) && (defined(LIBVNCSERVER_HAVE_LIBZ) || defined(LIBVNCSERVER_HAVE_LIBPNG))
case rfbEncodingTight:
if (!rfbSendRectEncodingTight(cl, x, y, w, h))
goto updateFailed;
break;
#ifdef LIBVNCSERVER_HAVE_LIBPNG
case rfbEncodingTightPng:
if (!rfbSendRectEncodingTightPng(cl, x, y, w, h))
goto updateFailed;
break;
#endif
#endif
}
}
if (i) {
sraRgnReleaseIterator(i);
i = NULL;
}
if ( nUpdateRegionRects == 0xFFFF &&
!rfbSendLastRectMarker(cl) )
goto updateFailed;
if (!rfbSendUpdateBuf(cl)) {
updateFailed:
result = FALSE;
}
if (!cl->enableCursorShapeUpdates) {
rfbHideCursor(cl);
}
if(i)
sraRgnReleaseIterator(i);
sraRgnDestroy(updateRegion);
sraRgnDestroy(updateCopyRegion);
if(cl->screen->displayFinishedHook)
cl->screen->displayFinishedHook(cl, result);
return result;
}
/*
* Send the copy region as a string of CopyRect encoded rectangles.
* The only slightly tricky thing is that we should send the messages in
* the correct order so that an earlier CopyRect will not corrupt the source
* of a later one.
*/
rfbBool
rfbSendCopyRegion(rfbClientPtr cl,
sraRegionPtr reg,
int dx,
int dy)
{
int x, y, w, h;
rfbFramebufferUpdateRectHeader rect;
rfbCopyRect cr;
sraRectangleIterator* i;
sraRect rect1;
/* printf("copyrect: "); sraRgnPrint(reg); putchar('\n');fflush(stdout); */
i = sraRgnGetReverseIterator(reg,dx>0,dy>0);
/* correct for the scale of the screen */
dx = ScaleX(cl->screen, cl->scaledScreen, dx);
dy = ScaleX(cl->screen, cl->scaledScreen, dy);
while(sraRgnIteratorNext(i,&rect1)) {
x = rect1.x1;
y = rect1.y1;
w = rect1.x2 - x;
h = rect1.y2 - y;
/* correct for scaling (if necessary) */
rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "copyrect");
rect.r.x = Swap16IfLE(x);
rect.r.y = Swap16IfLE(y);
rect.r.w = Swap16IfLE(w);
rect.r.h = Swap16IfLE(h);
rect.encoding = Swap32IfLE(rfbEncodingCopyRect);
memcpy(&cl->updateBuf[cl->ublen], (char *)&rect,
sz_rfbFramebufferUpdateRectHeader);
cl->ublen += sz_rfbFramebufferUpdateRectHeader;
cr.srcX = Swap16IfLE(x - dx);
cr.srcY = Swap16IfLE(y - dy);
memcpy(&cl->updateBuf[cl->ublen], (char *)&cr, sz_rfbCopyRect);
cl->ublen += sz_rfbCopyRect;
rfbStatRecordEncodingSent(cl, rfbEncodingCopyRect, sz_rfbFramebufferUpdateRectHeader + sz_rfbCopyRect,
w * h * (cl->scaledScreen->bitsPerPixel / 8));
}
sraRgnReleaseIterator(i);
return TRUE;
}
/*
* Send a given rectangle in raw encoding (rfbEncodingRaw).
*/
rfbBool
rfbSendRectEncodingRaw(rfbClientPtr cl,
int x,
int y,
int w,
int h)
{
rfbFramebufferUpdateRectHeader rect;
int nlines;
int bytesPerLine = w * (cl->format.bitsPerPixel / 8);
char *fbptr = (cl->scaledScreen->frameBuffer + (cl->scaledScreen->paddedWidthInBytes * y)
+ (x * (cl->scaledScreen->bitsPerPixel / 8)));
/* Flush the buffer to guarantee correct alignment for translateFn(). */
if (cl->ublen > 0) {
if (!rfbSendUpdateBuf(cl))
return FALSE;
}
rect.r.x = Swap16IfLE(x);
rect.r.y = Swap16IfLE(y);
rect.r.w = Swap16IfLE(w);
rect.r.h = Swap16IfLE(h);
rect.encoding = Swap32IfLE(rfbEncodingRaw);
memcpy(&cl->updateBuf[cl->ublen], (char *)&rect,sz_rfbFramebufferUpdateRectHeader);
cl->ublen += sz_rfbFramebufferUpdateRectHeader;
rfbStatRecordEncodingSent(cl, rfbEncodingRaw, sz_rfbFramebufferUpdateRectHeader + bytesPerLine * h,
sz_rfbFramebufferUpdateRectHeader + bytesPerLine * h);
nlines = (UPDATE_BUF_SIZE - cl->ublen) / bytesPerLine;
while (TRUE) {
if (nlines > h)
nlines = h;
(*cl->translateFn)(cl->translateLookupTable,
&(cl->screen->serverFormat),
&cl->format, fbptr, &cl->updateBuf[cl->ublen],
cl->scaledScreen->paddedWidthInBytes, w, nlines);
cl->ublen += nlines * bytesPerLine;
h -= nlines;
if (h == 0) /* rect fitted in buffer, do next one */
return TRUE;
/* buffer full - flush partial rect and do another nlines */
if (!rfbSendUpdateBuf(cl))
return FALSE;
fbptr += (cl->scaledScreen->paddedWidthInBytes * nlines);
nlines = (UPDATE_BUF_SIZE - cl->ublen) / bytesPerLine;
if (nlines == 0) {
rfbErr("rfbSendRectEncodingRaw: send buffer too small for %d "
"bytes per line\n", bytesPerLine);
rfbCloseClient(cl);
return FALSE;
}
}
}
/*
* Send an empty rectangle with encoding field set to value of
* rfbEncodingLastRect to notify client that this is the last
* rectangle in framebuffer update ("LastRect" extension of RFB
* protocol).
*/
rfbBool
rfbSendLastRectMarker(rfbClientPtr cl)
{
rfbFramebufferUpdateRectHeader rect;
if (cl->ublen + sz_rfbFramebufferUpdateRectHeader > UPDATE_BUF_SIZE) {
if (!rfbSendUpdateBuf(cl))
return FALSE;
}
rect.encoding = Swap32IfLE(rfbEncodingLastRect);
rect.r.x = 0;
rect.r.y = 0;
rect.r.w = 0;
rect.r.h = 0;
memcpy(&cl->updateBuf[cl->ublen], (char *)&rect,sz_rfbFramebufferUpdateRectHeader);
cl->ublen += sz_rfbFramebufferUpdateRectHeader;
rfbStatRecordEncodingSent(cl, rfbEncodingLastRect, sz_rfbFramebufferUpdateRectHeader, sz_rfbFramebufferUpdateRectHeader);
return TRUE;
}
/*
* Send NewFBSize pseudo-rectangle. This tells the client to change
* its framebuffer size.
*/
rfbBool
rfbSendNewFBSize(rfbClientPtr cl,
int w,
int h)
{
rfbFramebufferUpdateRectHeader rect;
if (cl->ublen + sz_rfbFramebufferUpdateRectHeader > UPDATE_BUF_SIZE) {
if (!rfbSendUpdateBuf(cl))
return FALSE;
}
if (cl->PalmVNC==TRUE)
rfbLog("Sending rfbEncodingNewFBSize in response to a PalmVNC style framebuffer resize (%dx%d)\n", w, h);
else
rfbLog("Sending rfbEncodingNewFBSize for resize to (%dx%d)\n", w, h);
rect.encoding = Swap32IfLE(rfbEncodingNewFBSize);
rect.r.x = 0;
rect.r.y = 0;
rect.r.w = Swap16IfLE(w);
rect.r.h = Swap16IfLE(h);
memcpy(&cl->updateBuf[cl->ublen], (char *)&rect,
sz_rfbFramebufferUpdateRectHeader);
cl->ublen += sz_rfbFramebufferUpdateRectHeader;
rfbStatRecordEncodingSent(cl, rfbEncodingNewFBSize, sz_rfbFramebufferUpdateRectHeader, sz_rfbFramebufferUpdateRectHeader);
return TRUE;
}
/*
* Send the contents of cl->updateBuf. Returns 1 if successful, -1 if
* not (errno should be set).
*/
rfbBool
rfbSendUpdateBuf(rfbClientPtr cl)
{
if(cl->sock<0)
return FALSE;
if (rfbWriteExact(cl, cl->updateBuf, cl->ublen) < 0) {
rfbLogPerror("rfbSendUpdateBuf: write");
rfbCloseClient(cl);
return FALSE;
}
cl->ublen = 0;
return TRUE;
}
/*
* rfbSendSetColourMapEntries sends a SetColourMapEntries message to the
* client, using values from the currently installed colormap.
*/
rfbBool
rfbSendSetColourMapEntries(rfbClientPtr cl,
int firstColour,
int nColours)
{
char buf[sz_rfbSetColourMapEntriesMsg + 256 * 3 * 2];
char *wbuf = buf;
rfbSetColourMapEntriesMsg *scme;
uint16_t *rgb;
rfbColourMap* cm = &cl->screen->colourMap;
int i, len;
if (nColours > 256) {
/* some rare hardware has, e.g., 4096 colors cells: PseudoColor:12 */
wbuf = (char *) malloc(sz_rfbSetColourMapEntriesMsg + nColours * 3 * 2);
}
scme = (rfbSetColourMapEntriesMsg *)wbuf;
rgb = (uint16_t *)(&wbuf[sz_rfbSetColourMapEntriesMsg]);
scme->type = rfbSetColourMapEntries;
scme->firstColour = Swap16IfLE(firstColour);
scme->nColours = Swap16IfLE(nColours);
len = sz_rfbSetColourMapEntriesMsg;
for (i = 0; i < nColours; i++) {
if(i<(int)cm->count) {
if(cm->is16) {
rgb[i*3] = Swap16IfLE(cm->data.shorts[i*3]);
rgb[i*3+1] = Swap16IfLE(cm->data.shorts[i*3+1]);
rgb[i*3+2] = Swap16IfLE(cm->data.shorts[i*3+2]);
} else {
rgb[i*3] = Swap16IfLE((unsigned short)cm->data.bytes[i*3]);
rgb[i*3+1] = Swap16IfLE((unsigned short)cm->data.bytes[i*3+1]);
rgb[i*3+2] = Swap16IfLE((unsigned short)cm->data.bytes[i*3+2]);
}
}
}
len += nColours * 3 * 2;
LOCK(cl->sendMutex);
if (rfbWriteExact(cl, wbuf, len) < 0) {
rfbLogPerror("rfbSendSetColourMapEntries: write");
rfbCloseClient(cl);
if (wbuf != buf) free(wbuf);
UNLOCK(cl->sendMutex);
return FALSE;
}
UNLOCK(cl->sendMutex);
rfbStatRecordMessageSent(cl, rfbSetColourMapEntries, len, len);
if (wbuf != buf) free(wbuf);
return TRUE;
}
/*
* rfbSendBell sends a Bell message to all the clients.
*/
void
rfbSendBell(rfbScreenInfoPtr rfbScreen)
{
rfbClientIteratorPtr i;
rfbClientPtr cl;
rfbBellMsg b;
i = rfbGetClientIterator(rfbScreen);
while((cl=rfbClientIteratorNext(i))) {
b.type = rfbBell;
LOCK(cl->sendMutex);
if (rfbWriteExact(cl, (char *)&b, sz_rfbBellMsg) < 0) {
rfbLogPerror("rfbSendBell: write");
rfbCloseClient(cl);
}
UNLOCK(cl->sendMutex);
}
rfbStatRecordMessageSent(cl, rfbBell, sz_rfbBellMsg, sz_rfbBellMsg);
rfbReleaseClientIterator(i);
}
/*
* rfbSendServerCutText sends a ServerCutText message to all the clients.
*/
void
rfbSendServerCutText(rfbScreenInfoPtr rfbScreen,char *str, int len)
{
rfbClientPtr cl;
rfbServerCutTextMsg sct;
rfbClientIteratorPtr iterator;
iterator = rfbGetClientIterator(rfbScreen);
while ((cl = rfbClientIteratorNext(iterator)) != NULL) {
sct.type = rfbServerCutText;
sct.length = Swap32IfLE(len);
LOCK(cl->sendMutex);
if (rfbWriteExact(cl, (char *)&sct,
sz_rfbServerCutTextMsg) < 0) {
rfbLogPerror("rfbSendServerCutText: write");
rfbCloseClient(cl);
UNLOCK(cl->sendMutex);
continue;
}
if (rfbWriteExact(cl, str, len) < 0) {
rfbLogPerror("rfbSendServerCutText: write");
rfbCloseClient(cl);
}
UNLOCK(cl->sendMutex);
rfbStatRecordMessageSent(cl, rfbServerCutText, sz_rfbServerCutTextMsg+len, sz_rfbServerCutTextMsg+len);
}
rfbReleaseClientIterator(iterator);
}
/*****************************************************************************
*
* UDP can be used for keyboard and pointer events when the underlying
* network is highly reliable. This is really here to support ORL's
* videotile, whose TCP implementation doesn't like sending lots of small
* packets (such as 100s of pen readings per second!).
*/
static unsigned char ptrAcceleration = 50;
void
rfbNewUDPConnection(rfbScreenInfoPtr rfbScreen,
int sock)
{
if (write(sock, (char*) &ptrAcceleration, 1) < 0) {
rfbLogPerror("rfbNewUDPConnection: write");
}
}
/*
* Because UDP is a message based service, we can't read the first byte and
* then the rest of the packet separately like we do with TCP. We will always
* get a whole packet delivered in one go, so we ask read() for the maximum
* number of bytes we can possibly get.
*/
void
rfbProcessUDPInput(rfbScreenInfoPtr rfbScreen)
{
int n;
rfbClientPtr cl=rfbScreen->udpClient;
rfbClientToServerMsg msg;
if((!cl) || cl->onHold)
return;
if ((n = read(rfbScreen->udpSock, (char *)&msg, sizeof(msg))) <= 0) {
if (n < 0) {
rfbLogPerror("rfbProcessUDPInput: read");
}
rfbDisconnectUDPSock(rfbScreen);
return;
}
switch (msg.type) {
case rfbKeyEvent:
if (n != sz_rfbKeyEventMsg) {
rfbErr("rfbProcessUDPInput: key event incorrect length\n");
rfbDisconnectUDPSock(rfbScreen);
return;
}
cl->screen->kbdAddEvent(msg.ke.down, (rfbKeySym)Swap32IfLE(msg.ke.key), cl);
break;
case rfbPointerEvent:
if (n != sz_rfbPointerEventMsg) {
rfbErr("rfbProcessUDPInput: ptr event incorrect length\n");
rfbDisconnectUDPSock(rfbScreen);
return;
}
cl->screen->ptrAddEvent(msg.pe.buttonMask,
Swap16IfLE(msg.pe.x), Swap16IfLE(msg.pe.y), cl);
break;
default:
rfbErr("rfbProcessUDPInput: unknown message type %d\n",
msg.type);
rfbDisconnectUDPSock(rfbScreen);
}
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_522_0 |
crossvul-cpp_data_good_1005_0 | /******************************************************************************
* main.c
*
* pdfresurrect - PDF history extraction tool
*
* Copyright (C) 2008-2010, 2012, 2017, 2019 Matt Davis (enferex).
*
* Special thanks to all of the contributors: See AUTHORS.
*
* Special thanks to 757labs (757 crew), they are a great group
* of people to hack on projects and brainstorm with.
*
* main.c is part of pdfresurrect.
* pdfresurrect 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 3 of the License, or
* (at your option) any later version.
*
* pdfresurrect 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 pdfresurrect. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "main.h"
#include "pdf.h"
static void usage(void)
{
printf(EXEC_NAME " Copyright (C) 2008-2010, 2012, 2013, 2017, 2019"
"Matt Davis (enferex)\n"
"Special thanks to all contributors and the 757 crew.\n"
"This program comes with ABSOLUTELY NO WARRANTY\n"
"This is free software, and you are welcome to redistribute it\n"
"under certain conditions. For details see the file 'LICENSE'\n"
"that came with this software or visit:\n"
"<http://www.gnu.org/licenses/gpl-3.0.txt>\n\n");
printf("-- " EXEC_NAME " v" VER" --\n"
"Usage: ./" EXEC_NAME " <file.pdf> [-i] [-w] [-q] [-s]\n"
"\t -i Display PDF creator information\n"
"\t -w Write the PDF versions and summary to disk\n"
"\t -q Display only the number of versions contained in the PDF\n"
"\t -s Scrub the previous history data from the specified PDF\n");
exit(0);
}
static void write_version(
FILE *fp,
const char *fname,
const char *dirname,
xref_t *xref)
{
long start;
char *c, *new_fname, data;
FILE *new_fp;
start = ftell(fp);
/* Create file */
if ((c = strstr(fname, ".pdf")))
*c = '\0';
new_fname = safe_calloc(strlen(fname) + strlen(dirname) + 16);
snprintf(new_fname, strlen(fname) + strlen(dirname) + 16,
"%s/%s-version-%d.pdf", dirname, fname, xref->version);
if (!(new_fp = fopen(new_fname, "w")))
{
ERR("Could not create file '%s'\n", new_fname);
fseek(fp, start, SEEK_SET);
free(new_fname);
return;
}
/* Copy original PDF */
fseek(fp, 0, SEEK_SET);
while (fread(&data, 1, 1, fp))
fwrite(&data, 1, 1, new_fp);
/* Emit an older startxref, refering to an older version. */
fprintf(new_fp, "\r\nstartxref\r\n%ld\r\n%%%%EOF", xref->start);
/* Clean */
fclose(new_fp);
free(new_fname);
fseek(fp, start, SEEK_SET);
}
static void scrub_document(FILE *fp, const pdf_t *pdf)
{
FILE *new_fp;
int ch, i, j, last_version ;
char *new_name, *c;
const char *suffix = "-scrubbed.pdf";
/* Create a new name */
if (!(new_name = malloc(strlen(pdf->name) + strlen(suffix) + 1)))
{
ERR("Insufficient memory to create scrubbed file name\n");
return;
}
strcpy(new_name, pdf->name);
if ((c = strrchr(new_name, '.')))
*c = '\0';
strcat(new_name, suffix);
if ((new_fp = fopen(new_name, "r")))
{
ERR("File name already exists for saving scrubbed document\n");
free(new_name);
fclose(new_fp);
return;
}
if (!(new_fp = fopen(new_name, "w+")))
{
ERR("Could not create file for saving scrubbed document\n");
free(new_name);
fclose(new_fp);
return;
}
/* Copy */
fseek(fp, SEEK_SET, 0);
while ((ch = fgetc(fp)) != EOF)
fputc(ch, new_fp);
/* Find last version (dont zero these baddies) */
last_version = 0;
for (i=0; i<pdf->n_xrefs; i++)
if (pdf->xrefs[i].version)
last_version = pdf->xrefs[i].version;
/* Zero mod objects from all but the most recent version
* Zero del objects from all versions
*/
fseek(new_fp, 0, SEEK_SET);
for (i=0; i<pdf->n_xrefs; i++)
{
for (j=0; j<pdf->xrefs[i].n_entries; j++)
if (!pdf->xrefs[i].entries[j].obj_id)
continue;
else
{
switch (pdf_get_object_status(pdf, i, j))
{
case 'M':
if (pdf->xrefs[i].version != last_version)
pdf_zero_object(new_fp, pdf, i, j);
break;
case 'D':
pdf_zero_object(new_fp, pdf, i, j);
break;
default:
break;
}
}
}
/* Clean */
free(new_name);
fclose(new_fp);
}
static void display_creator(FILE *fp, const pdf_t *pdf)
{
int i;
printf("PDF Version: %d.%d\n",
pdf->pdf_major_version, pdf->pdf_minor_version);
for (i=0; i<pdf->n_xrefs; ++i)
{
if (!pdf->xrefs[i].version)
continue;
if (pdf_display_creator(pdf, i))
printf("\n");
}
}
static pdf_t *init_pdf(FILE *fp, const char *name)
{
pdf_t *pdf;
pdf = pdf_new(name);
pdf_get_version(fp, pdf);
if (pdf_load_xrefs(fp, pdf) == -1) {
pdf_delete(pdf);
return NULL;
}
pdf_load_pages_kids(fp, pdf);
return pdf;
}
void *safe_calloc(size_t size) {
void *addr;
if (!size)
{
ERR("Invalid allocation size.\n");
exit(EXIT_FAILURE);
}
if (!(addr = calloc(1, size)))
{
ERR("Failed to allocate requested number of bytes, out of memory?\n");
exit(EXIT_FAILURE);
}
return addr;
}
int main(int argc, char **argv)
{
int i, n_valid, do_write, do_scrub;
char *c, *dname, *name;
DIR *dir;
FILE *fp;
pdf_t *pdf;
pdf_flag_t flags;
if (argc < 2)
usage();
/* Args */
do_write = do_scrub = flags = 0;
name = NULL;
for (i=1; i<argc; i++)
{
if (strncmp(argv[i], "-w", 2) == 0)
do_write = 1;
else if (strncmp(argv[i], "-i", 2) == 0)
flags |= PDF_FLAG_DISP_CREATOR;
else if (strncmp(argv[i], "-q", 2) == 0)
flags |= PDF_FLAG_QUIET;
else if (strncmp(argv[i], "-s", 2) == 0)
do_scrub = 1;
else if (argv[i][0] != '-')
name = argv[i];
else if (argv[i][0] == '-')
usage();
}
if (!name)
usage();
if (!(fp = fopen(name, "r")))
{
ERR("Could not open file '%s'\n", argv[1]);
return -1;
}
else if (!pdf_is_pdf(fp))
{
ERR("'%s' specified is not a valid PDF\n", name);
fclose(fp);
return -1;
}
/* Load PDF */
if (!(pdf = init_pdf(fp, name)))
{
fclose(fp);
return -1;
}
/* Count valid xrefs */
for (i=0, n_valid=0; i<pdf->n_xrefs; i++)
if (pdf->xrefs[i].version)
++n_valid;
/* Bail if we only have 1 valid */
if (n_valid < 2)
{
if (!(flags & (PDF_FLAG_QUIET | PDF_FLAG_DISP_CREATOR)))
printf("%s: There is only one version of this PDF\n", pdf->name);
if (do_write)
{
fclose(fp);
pdf_delete(pdf);
return 0;
}
}
dname = NULL;
if (do_write)
{
/* Create directory to place the various versions in */
if ((c = strrchr(name, '/')))
name = c + 1;
if ((c = strrchr(name, '.')))
*c = '\0';
dname = safe_calloc(strlen(name) + 16);
sprintf(dname, "%s-versions", name);
if (!(dir = opendir(dname)))
mkdir(dname, S_IRWXU);
else
{
ERR("This directory already exists, PDF version extraction will "
"not occur.\n");
fclose(fp);
closedir(dir);
free(dname);
pdf_delete(pdf);
return -1;
}
/* Write the pdf as a pervious version */
for (i=0; i<pdf->n_xrefs; i++)
if (pdf->xrefs[i].version)
write_version(fp, name, dname, &pdf->xrefs[i]);
}
/* Generate a per-object summary */
pdf_summarize(fp, pdf, dname, flags);
/* Have we been summoned to scrub history from this PDF */
if (do_scrub)
scrub_document(fp, pdf);
/* Display extra information */
if (flags & PDF_FLAG_DISP_CREATOR)
display_creator(fp, pdf);
fclose(fp);
free(dname);
pdf_delete(pdf);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_1005_0 |
crossvul-cpp_data_good_3107_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP SSSSS DDDD %
% P P SS D D %
% PPPP SSS D D %
% P SS D D %
% P SSSSS DDDD %
% %
% %
% Read/Write Adobe Photoshop Image Format %
% %
% Software Design %
% Cristy %
% Leonard Rosenthol %
% July 1992 %
% Dirk Lemstra %
% December 2013 %
% %
% %
% Copyright 1999-2017 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/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/channel.h"
#include "MagickCore/colormap.h"
#include "MagickCore/colormap-private.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/constitute.h"
#include "MagickCore/enhance.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/module.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/profile.h"
#include "MagickCore/property.h"
#include "MagickCore/registry.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
#ifdef MAGICKCORE_ZLIB_DELEGATE
#include <zlib.h>
#endif
#include "psd-private.h"
/*
Define declaractions.
*/
#define MaxPSDChannels 56
#define PSDQuantum(x) (((ssize_t) (x)+1) & -2)
/*
Enumerated declaractions.
*/
typedef enum
{
Raw = 0,
RLE = 1,
ZipWithoutPrediction = 2,
ZipWithPrediction = 3
} PSDCompressionType;
typedef enum
{
BitmapMode = 0,
GrayscaleMode = 1,
IndexedMode = 2,
RGBMode = 3,
CMYKMode = 4,
MultichannelMode = 7,
DuotoneMode = 8,
LabMode = 9
} PSDImageType;
/*
Typedef declaractions.
*/
typedef struct _ChannelInfo
{
short int
type;
size_t
size;
} ChannelInfo;
typedef struct _MaskInfo
{
Image
*image;
RectangleInfo
page;
unsigned char
background,
flags;
} MaskInfo;
typedef struct _LayerInfo
{
ChannelInfo
channel_info[MaxPSDChannels];
char
blendkey[4];
Image
*image;
MaskInfo
mask;
Quantum
opacity;
RectangleInfo
page;
size_t
offset_x,
offset_y;
unsigned char
clipping,
flags,
name[256],
visible;
unsigned short
channels;
StringInfo
*info;
} LayerInfo;
/*
Forward declarations.
*/
static MagickBooleanType
WritePSDImage(const ImageInfo *,Image *,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s P S D %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsPSD()() returns MagickTrue if the image format type, identified by the
% magick string, is PSD.
%
% The format of the IsPSD method is:
%
% MagickBooleanType IsPSD(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsPSD(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (LocaleNCompare((const char *) magick,"8BPS",4) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadPSDImage() reads an Adobe Photoshop 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 ReadPSDImage method is:
%
% Image *ReadPSDImage(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 const char *CompositeOperatorToPSDBlendMode(CompositeOperator op)
{
const char
*blend_mode;
switch (op)
{
case ColorBurnCompositeOp: blend_mode = "idiv"; break;
case ColorDodgeCompositeOp: blend_mode = "div "; break;
case ColorizeCompositeOp: blend_mode = "colr"; break;
case DarkenCompositeOp: blend_mode = "dark"; break;
case DifferenceCompositeOp: blend_mode = "diff"; break;
case DissolveCompositeOp: blend_mode = "diss"; break;
case ExclusionCompositeOp: blend_mode = "smud"; break;
case HardLightCompositeOp: blend_mode = "hLit"; break;
case HardMixCompositeOp: blend_mode = "hMix"; break;
case HueCompositeOp: blend_mode = "hue "; break;
case LightenCompositeOp: blend_mode = "lite"; break;
case LinearBurnCompositeOp: blend_mode = "lbrn"; break;
case LinearDodgeCompositeOp:blend_mode = "lddg"; break;
case LinearLightCompositeOp:blend_mode = "lLit"; break;
case LuminizeCompositeOp: blend_mode = "lum "; break;
case MultiplyCompositeOp: blend_mode = "mul "; break;
case OverCompositeOp: blend_mode = "norm"; break;
case OverlayCompositeOp: blend_mode = "over"; break;
case PinLightCompositeOp: blend_mode = "pLit"; break;
case SaturateCompositeOp: blend_mode = "sat "; break;
case ScreenCompositeOp: blend_mode = "scrn"; break;
case SoftLightCompositeOp: blend_mode = "sLit"; break;
case VividLightCompositeOp: blend_mode = "vLit"; break;
default: blend_mode = "norm";
}
return(blend_mode);
}
/*
For some reason Photoshop seems to blend semi-transparent pixels with white.
This method reverts the blending. This can be disabled by setting the
option 'psd:alpha-unblend' to off.
*/
static MagickBooleanType CorrectPSDAlphaBlend(const ImageInfo *image_info,
Image *image,ExceptionInfo* exception)
{
const char
*option;
MagickBooleanType
status;
ssize_t
y;
if (image->alpha_trait != BlendPixelTrait || image->colorspace != sRGBColorspace)
return(MagickTrue);
option=GetImageOption(image_info,"psd:alpha-unblend");
if (IsStringFalse(option) != MagickFalse)
return(MagickTrue);
status=MagickTrue;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
gamma;
register ssize_t
i;
gamma=QuantumScale*GetPixelAlpha(image, q);
if (gamma != 0.0 && gamma != 1.0)
{
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
if (channel != AlphaPixelChannel)
q[i]=ClampToQuantum((q[i]-((1.0-gamma)*QuantumRange))/gamma);
}
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
status=MagickFalse;
}
return(status);
}
static inline CompressionType ConvertPSDCompression(
PSDCompressionType compression)
{
switch (compression)
{
case RLE:
return RLECompression;
case ZipWithPrediction:
case ZipWithoutPrediction:
return ZipCompression;
default:
return NoCompression;
}
}
static MagickBooleanType ApplyPSDLayerOpacity(Image *image,Quantum opacity,
MagickBooleanType revert,ExceptionInfo *exception)
{
MagickBooleanType
status;
ssize_t
y;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" applying layer opacity %.20g", (double) opacity);
if (opacity == OpaqueAlpha)
return(MagickTrue);
image->alpha_trait=BlendPixelTrait;
status=MagickTrue;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (revert == MagickFalse)
SetPixelAlpha(image,(Quantum) (QuantumScale*(GetPixelAlpha(image,q))*
opacity),q);
else if (opacity > 0)
SetPixelAlpha(image,(Quantum) (QuantumRange*(GetPixelAlpha(image,q)/
(MagickRealType) opacity)),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
status=MagickFalse;
}
return(status);
}
static MagickBooleanType ApplyPSDOpacityMask(Image *image,const Image *mask,
Quantum background,MagickBooleanType revert,ExceptionInfo *exception)
{
Image
*complete_mask;
MagickBooleanType
status;
PixelInfo
color;
ssize_t
y;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" applying opacity mask");
complete_mask=CloneImage(image,image->columns,image->rows,MagickTrue,
exception);
complete_mask->alpha_trait=BlendPixelTrait;
GetPixelInfo(complete_mask,&color);
color.red=background;
SetImageColor(complete_mask,&color,exception);
status=CompositeImage(complete_mask,mask,OverCompositeOp,MagickTrue,
mask->page.x-image->page.x,mask->page.y-image->page.y,exception);
if (status == MagickFalse)
{
complete_mask=DestroyImage(complete_mask);
return(status);
}
image->alpha_trait=BlendPixelTrait;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register Quantum
*p;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
p=GetAuthenticPixels(complete_mask,0,y,complete_mask->columns,1,exception);
if ((q == (Quantum *) NULL) || (p == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
MagickRealType
alpha,
intensity;
alpha=GetPixelAlpha(image,q);
intensity=GetPixelIntensity(complete_mask,p);
if (revert == MagickFalse)
SetPixelAlpha(image,ClampToQuantum(intensity*(QuantumScale*alpha)),q);
else if (intensity > 0)
SetPixelAlpha(image,ClampToQuantum((alpha/intensity)*QuantumRange),q);
q+=GetPixelChannels(image);
p+=GetPixelChannels(complete_mask);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
status=MagickFalse;
}
complete_mask=DestroyImage(complete_mask);
return(status);
}
static void PreservePSDOpacityMask(Image *image,LayerInfo* layer_info,
ExceptionInfo *exception)
{
char
*key;
RandomInfo
*random_info;
StringInfo
*key_info;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" preserving opacity mask");
random_info=AcquireRandomInfo();
key_info=GetRandomKey(random_info,2+1);
key=(char *) GetStringInfoDatum(key_info);
key[8]=layer_info->mask.background;
key[9]='\0';
layer_info->mask.image->page.x+=layer_info->page.x;
layer_info->mask.image->page.y+=layer_info->page.y;
(void) SetImageRegistry(ImageRegistryType,(const char *) key,
layer_info->mask.image,exception);
(void) SetImageArtifact(layer_info->image,"psd:opacity-mask",
(const char *) key);
key_info=DestroyStringInfo(key_info);
random_info=DestroyRandomInfo(random_info);
}
static ssize_t DecodePSDPixels(const size_t number_compact_pixels,
const unsigned char *compact_pixels,const ssize_t depth,
const size_t number_pixels,unsigned char *pixels)
{
#define CheckNumberCompactPixels \
if (packets == 0) \
return(i); \
packets--
#define CheckNumberPixels(count) \
if (((ssize_t) i + count) > (ssize_t) number_pixels) \
return(i); \
i+=count
int
pixel;
register ssize_t
i,
j;
size_t
length;
ssize_t
packets;
packets=(ssize_t) number_compact_pixels;
for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); )
{
packets--;
length=(size_t) (*compact_pixels++);
if (length == 128)
continue;
if (length > 128)
{
length=256-length+1;
CheckNumberCompactPixels;
pixel=(*compact_pixels++);
for (j=0; j < (ssize_t) length; j++)
{
switch (depth)
{
case 1:
{
CheckNumberPixels(8);
*pixels++=(pixel >> 7) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 6) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 5) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 4) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 3) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 2) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 1) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 0) & 0x01 ? 0U : 255U;
break;
}
case 2:
{
CheckNumberPixels(4);
*pixels++=(unsigned char) ((pixel >> 6) & 0x03);
*pixels++=(unsigned char) ((pixel >> 4) & 0x03);
*pixels++=(unsigned char) ((pixel >> 2) & 0x03);
*pixels++=(unsigned char) ((pixel & 0x03) & 0x03);
break;
}
case 4:
{
CheckNumberPixels(2);
*pixels++=(unsigned char) ((pixel >> 4) & 0xff);
*pixels++=(unsigned char) ((pixel & 0x0f) & 0xff);
break;
}
default:
{
CheckNumberPixels(1);
*pixels++=(unsigned char) pixel;
break;
}
}
}
continue;
}
length++;
for (j=0; j < (ssize_t) length; j++)
{
CheckNumberCompactPixels;
switch (depth)
{
case 1:
{
CheckNumberPixels(8);
*pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U;
break;
}
case 2:
{
CheckNumberPixels(4);
*pixels++=(*compact_pixels >> 6) & 0x03;
*pixels++=(*compact_pixels >> 4) & 0x03;
*pixels++=(*compact_pixels >> 2) & 0x03;
*pixels++=(*compact_pixels & 0x03) & 0x03;
break;
}
case 4:
{
CheckNumberPixels(2);
*pixels++=(*compact_pixels >> 4) & 0xff;
*pixels++=(*compact_pixels & 0x0f) & 0xff;
break;
}
default:
{
CheckNumberPixels(1);
*pixels++=(*compact_pixels);
break;
}
}
compact_pixels++;
}
}
return(i);
}
static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info,
const ssize_t number_layers)
{
ssize_t
i;
for (i=0; i<number_layers; i++)
{
if (layer_info[i].image != (Image *) NULL)
layer_info[i].image=DestroyImage(layer_info[i].image);
if (layer_info[i].mask.image != (Image *) NULL)
layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image);
if (layer_info[i].info != (StringInfo *) NULL)
layer_info[i].info=DestroyStringInfo(layer_info[i].info);
}
return (LayerInfo *) RelinquishMagickMemory(layer_info);
}
static inline size_t GetPSDPacketSize(Image *image)
{
if (image->storage_class == PseudoClass)
{
if (image->colors > 256)
return(2);
else if (image->depth > 8)
return(2);
}
else
if (image->depth > 8)
return(2);
return(1);
}
static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image)
{
if (psd_info->version == 1)
return((MagickSizeType) ReadBlobLong(image));
return((MagickSizeType) ReadBlobLongLong(image));
}
static inline size_t GetPSDRowSize(Image *image)
{
if (image->depth == 1)
return(((image->columns+7)/8)*GetPSDPacketSize(image));
else
return(image->columns*GetPSDPacketSize(image));
}
static const char *ModeToString(PSDImageType type)
{
switch (type)
{
case BitmapMode: return "Bitmap";
case GrayscaleMode: return "Grayscale";
case IndexedMode: return "Indexed";
case RGBMode: return "RGB";
case CMYKMode: return "CMYK";
case MultichannelMode: return "Multichannel";
case DuotoneMode: return "Duotone";
case LabMode: return "L*A*B";
default: return "unknown";
}
}
static MagickBooleanType NegateCMYK(Image *image,ExceptionInfo *exception)
{
ChannelType
channel_mask;
MagickBooleanType
status;
channel_mask=SetImageChannelMask(image,(ChannelType)(AllChannels &~
AlphaChannel));
status=NegateImage(image,MagickFalse,exception);
(void) SetImageChannelMask(image,channel_mask);
return(status);
}
static void ParseImageResourceBlocks(Image *image,
const unsigned char *blocks,size_t length,
MagickBooleanType *has_merged_image,ExceptionInfo *exception)
{
const unsigned char
*p;
StringInfo
*profile;
unsigned int
count,
long_sans;
unsigned short
id,
short_sans;
if (length < 16)
return;
profile=BlobToStringInfo((const unsigned char *) NULL,length);
SetStringInfoDatum(profile,blocks);
(void) SetImageProfile(image,"8bim",profile,exception);
profile=DestroyStringInfo(profile);
for (p=blocks; (p >= blocks) && (p < (blocks+length-16)); )
{
if (LocaleNCompare((const char *) p,"8BIM",4) != 0)
break;
p=PushLongPixel(MSBEndian,p,&long_sans);
p=PushShortPixel(MSBEndian,p,&id);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushLongPixel(MSBEndian,p,&count);
if ((p+count) > (blocks+length-16))
return;
switch (id)
{
case 0x03ed:
{
char
value[MagickPathExtent];
unsigned short
resolution;
/*
Resolution info.
*/
p=PushShortPixel(MSBEndian,p,&resolution);
image->resolution.x=(double) resolution;
(void) FormatLocaleString(value,MagickPathExtent,"%g",image->resolution.x);
(void) SetImageProperty(image,"tiff:XResolution",value,exception);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&resolution);
image->resolution.y=(double) resolution;
(void) FormatLocaleString(value,MagickPathExtent,"%g",image->resolution.y);
(void) SetImageProperty(image,"tiff:YResolution",value,exception);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
image->units=PixelsPerInchResolution;
break;
}
case 0x0421:
{
if (*(p+4) == 0)
*has_merged_image=MagickFalse;
p+=count;
break;
}
default:
{
p+=count;
break;
}
}
if ((count & 0x01) != 0)
p++;
}
return;
}
static CompositeOperator PSDBlendModeToCompositeOperator(const char *mode)
{
if (mode == (const char *) NULL)
return(OverCompositeOp);
if (LocaleNCompare(mode,"norm",4) == 0)
return(OverCompositeOp);
if (LocaleNCompare(mode,"mul ",4) == 0)
return(MultiplyCompositeOp);
if (LocaleNCompare(mode,"diss",4) == 0)
return(DissolveCompositeOp);
if (LocaleNCompare(mode,"diff",4) == 0)
return(DifferenceCompositeOp);
if (LocaleNCompare(mode,"dark",4) == 0)
return(DarkenCompositeOp);
if (LocaleNCompare(mode,"lite",4) == 0)
return(LightenCompositeOp);
if (LocaleNCompare(mode,"hue ",4) == 0)
return(HueCompositeOp);
if (LocaleNCompare(mode,"sat ",4) == 0)
return(SaturateCompositeOp);
if (LocaleNCompare(mode,"colr",4) == 0)
return(ColorizeCompositeOp);
if (LocaleNCompare(mode,"lum ",4) == 0)
return(LuminizeCompositeOp);
if (LocaleNCompare(mode,"scrn",4) == 0)
return(ScreenCompositeOp);
if (LocaleNCompare(mode,"over",4) == 0)
return(OverlayCompositeOp);
if (LocaleNCompare(mode,"hLit",4) == 0)
return(HardLightCompositeOp);
if (LocaleNCompare(mode,"sLit",4) == 0)
return(SoftLightCompositeOp);
if (LocaleNCompare(mode,"smud",4) == 0)
return(ExclusionCompositeOp);
if (LocaleNCompare(mode,"div ",4) == 0)
return(ColorDodgeCompositeOp);
if (LocaleNCompare(mode,"idiv",4) == 0)
return(ColorBurnCompositeOp);
if (LocaleNCompare(mode,"lbrn",4) == 0)
return(LinearBurnCompositeOp);
if (LocaleNCompare(mode,"lddg",4) == 0)
return(LinearDodgeCompositeOp);
if (LocaleNCompare(mode,"lLit",4) == 0)
return(LinearLightCompositeOp);
if (LocaleNCompare(mode,"vLit",4) == 0)
return(VividLightCompositeOp);
if (LocaleNCompare(mode,"pLit",4) == 0)
return(PinLightCompositeOp);
if (LocaleNCompare(mode,"hMix",4) == 0)
return(HardMixCompositeOp);
return(OverCompositeOp);
}
static inline void ReversePSDString(Image *image,char *p,size_t length)
{
char
*q;
if (image->endian == MSBEndian)
return;
q=p+length;
for(--q; p < q; ++p, --q)
{
*p = *p ^ *q,
*q = *p ^ *q,
*p = *p ^ *q;
}
}
static inline void SetPSDPixel(Image *image,const size_t channels,
const ssize_t type,const size_t packet_size,const Quantum pixel,Quantum *q,
ExceptionInfo *exception)
{
if (image->storage_class == PseudoClass)
{
if (packet_size == 1)
SetPixelIndex(image,ScaleQuantumToChar(pixel),q);
else
SetPixelIndex(image,ScaleQuantumToShort(pixel),q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
ConstrainColormapIndex(image,GetPixelIndex(image,q),exception),q);
return;
}
switch (type)
{
case -1:
{
SetPixelAlpha(image, pixel,q);
break;
}
case -2:
case 0:
{
SetPixelRed(image,pixel,q);
if (channels == 1 || type == -2)
SetPixelGray(image,pixel,q);
break;
}
case 1:
{
if (image->storage_class == PseudoClass)
SetPixelAlpha(image,pixel,q);
else
SetPixelGreen(image,pixel,q);
break;
}
case 2:
{
if (image->storage_class == PseudoClass)
SetPixelAlpha(image,pixel,q);
else
SetPixelBlue(image,pixel,q);
break;
}
case 3:
{
if (image->colorspace == CMYKColorspace)
SetPixelBlack(image,pixel,q);
else
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,pixel,q);
break;
}
case 4:
{
if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) &&
(channels > 3))
break;
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,pixel,q);
break;
}
}
}
static MagickBooleanType ReadPSDChannelPixels(Image *image,
const size_t channels,const size_t row,const ssize_t type,
const unsigned char *pixels,ExceptionInfo *exception)
{
Quantum
pixel;
register const unsigned char
*p;
register Quantum
*q;
register ssize_t
x;
size_t
packet_size;
unsigned short
nibble;
p=pixels;
q=GetAuthenticPixels(image,0,row,image->columns,1,exception);
if (q == (Quantum *) NULL)
return MagickFalse;
packet_size=GetPSDPacketSize(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (packet_size == 1)
pixel=ScaleCharToQuantum(*p++);
else
{
p=PushShortPixel(MSBEndian,p,&nibble);
pixel=ScaleShortToQuantum(nibble);
}
if (image->depth > 1)
{
SetPSDPixel(image,channels,type,packet_size,pixel,q,exception);
q+=GetPixelChannels(image);
}
else
{
ssize_t
bit,
number_bits;
number_bits=image->columns-x;
if (number_bits > 8)
number_bits=8;
for (bit = 0; bit < number_bits; bit++)
{
SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel)
& (0x01 << (7-bit))) != 0 ? 0 : QuantumRange,q,exception);
q+=GetPixelChannels(image);
x++;
}
if (x != (ssize_t) image->columns)
x--;
continue;
}
}
return(SyncAuthenticPixels(image,exception));
}
static MagickBooleanType ReadPSDChannelRaw(Image *image,const size_t channels,
const ssize_t type,ExceptionInfo *exception)
{
MagickBooleanType
status;
size_t
count,
row_size;
ssize_t
y;
unsigned char
*pixels;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is RAW");
row_size=GetPSDRowSize(image);
pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=MagickTrue;
for (y=0; y < (ssize_t) image->rows; y++)
{
status=MagickFalse;
count=ReadBlob(image,row_size,pixels);
if (count != row_size)
break;
status=ReadPSDChannelPixels(image,channels,y,type,pixels,exception);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(status);
}
static inline MagickOffsetType *ReadPSDRLESizes(Image *image,
const PSDInfo *psd_info,const size_t size)
{
MagickOffsetType
*sizes;
ssize_t
y;
sizes=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*sizes));
if(sizes != (MagickOffsetType *) NULL)
{
for (y=0; y < (ssize_t) size; y++)
{
if (psd_info->version == 1)
sizes[y]=(MagickOffsetType) ReadBlobShort(image);
else
sizes[y]=(MagickOffsetType) ReadBlobLong(image);
}
}
return sizes;
}
static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info,
const ssize_t type,MagickOffsetType *sizes,ExceptionInfo *exception)
{
MagickBooleanType
status;
size_t
length,
row_size;
ssize_t
count,
y;
unsigned char
*compact_pixels,
*pixels;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is RLE compressed");
row_size=GetPSDRowSize(image);
pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
length=0;
for (y=0; y < (ssize_t) image->rows; y++)
if ((MagickOffsetType) length < sizes[y])
length=(size_t) sizes[y];
if (length > row_size + 256) // arbitrary number
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
ThrowBinaryException(ResourceLimitError,"InvalidLength",
image->filename);
}
compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels));
if (compact_pixels == (unsigned char *) NULL)
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
(void) ResetMagickMemory(compact_pixels,0,length*sizeof(*compact_pixels));
status=MagickTrue;
for (y=0; y < (ssize_t) image->rows; y++)
{
status=MagickFalse;
count=ReadBlob(image,(size_t) sizes[y],compact_pixels);
if (count != (ssize_t) sizes[y])
break;
count=DecodePSDPixels((size_t) sizes[y],compact_pixels,
(ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels);
if (count != (ssize_t) row_size)
break;
status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels,
exception);
if (status == MagickFalse)
break;
}
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(status);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels,
const ssize_t type,const PSDCompressionType compression,
const size_t compact_size,ExceptionInfo *exception)
{
MagickBooleanType
status;
register unsigned char
*p;
size_t
count,
length,
packet_size,
row_size;
ssize_t
y;
unsigned char
*compact_pixels,
*pixels;
z_stream
stream;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is ZIP compressed");
compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size,
sizeof(*compact_pixels));
if (compact_pixels == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
packet_size=GetPSDPacketSize(image);
row_size=image->columns*packet_size;
count=image->rows*row_size;
pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
{
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
ResetMagickMemory(&stream,0,sizeof(stream));
stream.data_type=Z_BINARY;
(void) ReadBlob(image,compact_size,compact_pixels);
stream.next_in=(Bytef *)compact_pixels;
stream.avail_in=(uInt) compact_size;
stream.next_out=(Bytef *)pixels;
stream.avail_out=(uInt) count;
if (inflateInit(&stream) == Z_OK)
{
int
ret;
while (stream.avail_out > 0)
{
ret=inflate(&stream,Z_SYNC_FLUSH);
if ((ret != Z_OK) && (ret != Z_STREAM_END))
{
compact_pixels=(unsigned char *) RelinquishMagickMemory(
compact_pixels);
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(MagickFalse);
}
}
}
if (compression == ZipWithPrediction)
{
p=pixels;
while (count > 0)
{
length=image->columns;
while (--length)
{
if (packet_size == 2)
{
p[2]+=p[0]+((p[1]+p[3]) >> 8);
p[3]+=p[1];
}
else
*(p+1)+=*p;
p+=packet_size;
}
p+=packet_size;
count-=row_size;
}
}
status=MagickTrue;
p=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
status=ReadPSDChannelPixels(image,channels,y,type,p,exception);
if (status == MagickFalse)
break;
p+=row_size;
}
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(status);
}
#endif
static MagickBooleanType ReadPSDChannel(Image *image,
const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info,
const size_t channel,const PSDCompressionType compression,
ExceptionInfo *exception)
{
Image
*channel_image,
*mask;
MagickOffsetType
offset;
MagickBooleanType
status;
channel_image=image;
mask=(Image *) NULL;
if (layer_info->channel_info[channel].type < -1)
{
const char
*option;
/*
Ignore mask that is not a user supplied layer mask, if the mask is
disabled or if the flags have unsupported values.
*/
option=GetImageOption(image_info,"psd:preserve-opacity-mask");
if ((layer_info->channel_info[channel].type != -2) ||
(layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) &&
(IsStringTrue(option) == MagickFalse)))
{
SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR);
return(MagickTrue);
}
mask=CloneImage(image,layer_info->mask.page.width,
layer_info->mask.page.height,MagickFalse,exception);
SetImageType(mask,GrayscaleType,exception);
channel_image=mask;
}
offset=TellBlob(image);
status=MagickTrue;
switch(compression)
{
case Raw:
status=ReadPSDChannelRaw(channel_image,psd_info->channels,
layer_info->channel_info[channel].type,exception);
break;
case RLE:
{
MagickOffsetType
*sizes;
sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows);
if (sizes == (MagickOffsetType *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=ReadPSDChannelRLE(channel_image,psd_info,
layer_info->channel_info[channel].type,sizes,exception);
sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes);
}
break;
case ZipWithPrediction:
case ZipWithoutPrediction:
#ifdef MAGICKCORE_ZLIB_DELEGATE
status=ReadPSDChannelZip(channel_image,layer_info->channels,
layer_info->channel_info[channel].type,compression,
layer_info->channel_info[channel].size-2,exception);
#else
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn",
"'%s' (ZLIB)",image->filename);
#endif
break;
default:
(void) ThrowMagickException(exception,GetMagickModule(),TypeWarning,
"CompressionNotSupported","'%.20g'",(double) compression);
break;
}
SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET);
if (status == MagickFalse)
{
if (mask != (Image *) NULL)
DestroyImage(mask);
ThrowBinaryException(CoderError,"UnableToDecompressImage",
image->filename);
}
layer_info->mask.image=mask;
return(status);
}
static MagickBooleanType ReadPSDLayer(Image *image,const ImageInfo *image_info,
const PSDInfo *psd_info,LayerInfo* layer_info,ExceptionInfo *exception)
{
char
message[MagickPathExtent];
MagickBooleanType
status;
PSDCompressionType
compression;
ssize_t
j;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" setting up new layer image");
if (psd_info->mode != IndexedMode)
(void) SetImageBackgroundColor(layer_info->image,exception);
layer_info->image->compose=PSDBlendModeToCompositeOperator(
layer_info->blendkey);
if (layer_info->visible == MagickFalse)
layer_info->image->compose=NoCompositeOp;
if (psd_info->mode == CMYKMode)
SetImageColorspace(layer_info->image,CMYKColorspace,exception);
else if ((psd_info->mode == BitmapMode) || (psd_info->mode == DuotoneMode) ||
(psd_info->mode == GrayscaleMode))
SetImageColorspace(layer_info->image,GRAYColorspace,exception);
/*
Set up some hidden attributes for folks that need them.
*/
(void) FormatLocaleString(message,MagickPathExtent,"%.20g",
(double) layer_info->page.x);
(void) SetImageArtifact(layer_info->image,"psd:layer.x",message);
(void) FormatLocaleString(message,MagickPathExtent,"%.20g",
(double) layer_info->page.y);
(void) SetImageArtifact(layer_info->image,"psd:layer.y",message);
(void) FormatLocaleString(message,MagickPathExtent,"%.20g",(double)
layer_info->opacity);
(void) SetImageArtifact(layer_info->image,"psd:layer.opacity",message);
(void) SetImageProperty(layer_info->image,"label",(char *) layer_info->name,
exception);
status=MagickTrue;
for (j=0; j < (ssize_t) layer_info->channels; j++)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading data for channel %.20g",(double) j);
compression=(PSDCompressionType) ReadBlobShort(layer_info->image);
layer_info->image->compression=ConvertPSDCompression(compression);
if (layer_info->channel_info[j].type == -1)
layer_info->image->alpha_trait=BlendPixelTrait;
status=ReadPSDChannel(layer_info->image,image_info,psd_info,layer_info,j,
compression,exception);
if (status == MagickFalse)
break;
}
if (status != MagickFalse)
status=ApplyPSDLayerOpacity(layer_info->image,layer_info->opacity,
MagickFalse,exception);
if ((status != MagickFalse) &&
(layer_info->image->colorspace == CMYKColorspace))
status=NegateCMYK(layer_info->image,exception);
if ((status != MagickFalse) && (layer_info->mask.image != (Image *) NULL))
{
const char
*option;
layer_info->mask.image->page.x=layer_info->mask.page.x;
layer_info->mask.image->page.y=layer_info->mask.page.y;
/* Do not composite the mask when it is disabled */
if ((layer_info->mask.flags & 0x02) == 0x02)
layer_info->mask.image->compose=NoCompositeOp;
else
status=ApplyPSDOpacityMask(layer_info->image,layer_info->mask.image,
layer_info->mask.background == 0 ? 0 : QuantumRange,MagickFalse,
exception);
option=GetImageOption(image_info,"psd:preserve-opacity-mask");
if (IsStringTrue(option) != MagickFalse)
PreservePSDOpacityMask(image,layer_info,exception);
layer_info->mask.image=DestroyImage(layer_info->mask.image);
}
return(status);
}
ModuleExport MagickBooleanType ReadPSDLayers(Image *image,
const ImageInfo *image_info,const PSDInfo *psd_info,
const MagickBooleanType skip_layers,ExceptionInfo *exception)
{
char
type[4];
LayerInfo
*layer_info;
MagickSizeType
size;
MagickBooleanType
status;
register ssize_t
i;
ssize_t
count,
j,
number_layers;
size=GetPSDSize(psd_info,image);
if (size == 0)
{
/*
Skip layers & masks.
*/
(void) ReadBlobLong(image);
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
status=MagickFalse;
if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0))
return(MagickTrue);
else
{
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
if ((count != 0) && (LocaleNCompare(type,"Lr16",4) == 0))
size=GetPSDSize(psd_info,image);
else
return(MagickTrue);
}
}
status=MagickTrue;
if (size != 0)
{
layer_info=(LayerInfo *) NULL;
number_layers=(short) ReadBlobShort(image);
if (number_layers < 0)
{
/*
The first alpha channel in the merged result contains the
transparency data for the merged result.
*/
number_layers=MagickAbsoluteValue(number_layers);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" negative layer count corrected for");
image->alpha_trait=BlendPixelTrait;
}
/*
We only need to know if the image has an alpha channel
*/
if (skip_layers != MagickFalse)
return(MagickTrue);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image contains %.20g layers",(double) number_layers);
if (number_layers == 0)
ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers",
image->filename);
layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers,
sizeof(*layer_info));
if (layer_info == (LayerInfo *) NULL)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" allocation of LayerInfo failed");
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
(void) ResetMagickMemory(layer_info,0,(size_t) number_layers*
sizeof(*layer_info));
for (i=0; i < number_layers; i++)
{
ssize_t
x,
y;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading layer #%.20g",(double) i+1);
layer_info[i].page.y=ReadBlobSignedLong(image);
layer_info[i].page.x=ReadBlobSignedLong(image);
y=ReadBlobSignedLong(image);
x=ReadBlobSignedLong(image);
layer_info[i].page.width=(size_t) (x-layer_info[i].page.x);
layer_info[i].page.height=(size_t) (y-layer_info[i].page.y);
layer_info[i].channels=ReadBlobShort(image);
if (layer_info[i].channels > MaxPSDChannels)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded",
image->filename);
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g",
(double) layer_info[i].page.x,(double) layer_info[i].page.y,
(double) layer_info[i].page.height,(double)
layer_info[i].page.width,(double) layer_info[i].channels);
for (j=0; j < (ssize_t) layer_info[i].channels; j++)
{
layer_info[i].channel_info[j].type=(short) ReadBlobShort(image);
layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info,
image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" channel[%.20g]: type=%.20g, size=%.20g",(double) j,
(double) layer_info[i].channel_info[j].type,
(double) layer_info[i].channel_info[j].size);
}
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer type was %.4s instead of 8BIM", type);
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"ImproperImageHeader",
image->filename);
}
count=ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey);
ReversePSDString(image,layer_info[i].blendkey,4);
layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
layer_info[i].clipping=(unsigned char) ReadBlobByte(image);
layer_info[i].flags=(unsigned char) ReadBlobByte(image);
layer_info[i].visible=!(layer_info[i].flags & 0x02);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s",
layer_info[i].blendkey,(double) layer_info[i].opacity,
layer_info[i].clipping ? "true" : "false",layer_info[i].flags,
layer_info[i].visible ? "true" : "false");
(void) ReadBlobByte(image); /* filler */
size=ReadBlobLong(image);
if (size != 0)
{
MagickSizeType
combined_length,
length;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer contains additional info");
length=ReadBlobLong(image);
combined_length=length+4;
if (length != 0)
{
/*
Layer mask info.
*/
layer_info[i].mask.page.y=ReadBlobSignedLong(image);
layer_info[i].mask.page.x=ReadBlobSignedLong(image);
layer_info[i].mask.page.height=(size_t) (ReadBlobLong(image)-
layer_info[i].mask.page.y);
layer_info[i].mask.page.width=(size_t) (ReadBlobLong(image)-
layer_info[i].mask.page.x);
layer_info[i].mask.background=(unsigned char) ReadBlobByte(
image);
layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image);
if (!(layer_info[i].mask.flags & 0x01))
{
layer_info[i].mask.page.y=layer_info[i].mask.page.y-
layer_info[i].page.y;
layer_info[i].mask.page.x=layer_info[i].mask.page.x-
layer_info[i].page.x;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g",
(double) layer_info[i].mask.page.x,(double)
layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width,
(double) layer_info[i].mask.page.height,(double)
((MagickOffsetType) length)-18);
/*
Skip over the rest of the layer mask information.
*/
if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile",
image->filename);
}
}
length=ReadBlobLong(image);
combined_length+=length+4;
if (length != 0)
{
/*
Layer blending ranges info.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer blending ranges: length=%.20g",(double)
((MagickOffsetType) length));
/*
We read it, but don't use it...
*/
for (j=0; j < (ssize_t) length; j+=8)
{
size_t blend_source=ReadBlobLong(image);
size_t blend_dest=ReadBlobLong(image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" source(%x), dest(%x)",(unsigned int)
blend_source,(unsigned int) blend_dest);
}
}
/*
Layer name.
*/
length=(MagickSizeType) (unsigned char) ReadBlobByte(image);
combined_length+=length+1;
if (length > 0)
(void) ReadBlob(image,(size_t) length++,layer_info[i].name);
layer_info[i].name[length]='\0';
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer name: %s",layer_info[i].name);
if ((length % 4) != 0)
{
length=4-(length % 4);
combined_length+=length;
/* Skip over the padding of the layer name */
if (DiscardBlobBytes(image,length) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
}
length=(MagickSizeType) size-combined_length;
if (length > 0)
{
unsigned char
*info;
layer_info[i].info=AcquireStringInfo((const size_t) length);
info=GetStringInfoDatum(layer_info[i].info);
(void) ReadBlob(image,(const size_t) length,info);
}
}
}
for (i=0; i < number_layers; i++)
{
if ((layer_info[i].page.width == 0) ||
(layer_info[i].page.height == 0))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is empty");
if (layer_info[i].info != (StringInfo *) NULL)
layer_info[i].info=DestroyStringInfo(layer_info[i].info);
continue;
}
/*
Allocate layered image.
*/
layer_info[i].image=CloneImage(image,layer_info[i].page.width,
layer_info[i].page.height,MagickFalse,exception);
if (layer_info[i].image == (Image *) NULL)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" allocation of image for layer %.20g failed",(double) i);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
if (layer_info[i].info != (StringInfo *) NULL)
{
(void) SetImageProfile(layer_info[i].image,"psd:additional-info",
layer_info[i].info,exception);
layer_info[i].info=DestroyStringInfo(layer_info[i].info);
}
}
if (image_info->ping == MagickFalse)
{
for (i=0; i < number_layers; i++)
{
if (layer_info[i].image == (Image *) NULL)
{
for (j=0; j < layer_info[i].channels; j++)
{
if (DiscardBlobBytes(image,(MagickSizeType)
layer_info[i].channel_info[j].size) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
}
continue;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading data for layer %.20g",(double) i);
status=ReadPSDLayer(image,image_info,psd_info,&layer_info[i],
exception);
if (status == MagickFalse)
break;
status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType)
number_layers);
if (status == MagickFalse)
break;
}
}
if (status != MagickFalse)
{
for (i=0; i < number_layers; i++)
{
if (layer_info[i].image == (Image *) NULL)
{
for (j=i; j < number_layers - 1; j++)
layer_info[j] = layer_info[j+1];
number_layers--;
i--;
}
}
if (number_layers > 0)
{
for (i=0; i < number_layers; i++)
{
if (i > 0)
layer_info[i].image->previous=layer_info[i-1].image;
if (i < (number_layers-1))
layer_info[i].image->next=layer_info[i+1].image;
layer_info[i].image->page=layer_info[i].page;
}
image->next=layer_info[0].image;
layer_info[0].image->previous=image;
}
layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info);
}
else
layer_info=DestroyLayerInfo(layer_info,number_layers);
}
return(status);
}
static MagickBooleanType ReadPSDMergedImage(const ImageInfo *image_info,
Image *image,const PSDInfo *psd_info,ExceptionInfo *exception)
{
MagickOffsetType
*sizes;
MagickBooleanType
status;
PSDCompressionType
compression;
register ssize_t
i;
compression=(PSDCompressionType) ReadBlobMSBShort(image);
image->compression=ConvertPSDCompression(compression);
if (compression != Raw && compression != RLE)
{
(void) ThrowMagickException(exception,GetMagickModule(),
TypeWarning,"CompressionNotSupported","'%.20g'",(double) compression);
return(MagickFalse);
}
sizes=(MagickOffsetType *) NULL;
if (compression == RLE)
{
sizes=ReadPSDRLESizes(image,psd_info,image->rows*psd_info->channels);
if (sizes == (MagickOffsetType *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
status=MagickTrue;
for (i=0; i < (ssize_t) psd_info->channels; i++)
{
if (compression == RLE)
status=ReadPSDChannelRLE(image,psd_info,i,sizes+(i*image->rows),
exception);
else
status=ReadPSDChannelRaw(image,psd_info->channels,i,exception);
if (status != MagickFalse)
status=SetImageProgress(image,LoadImagesTag,i,psd_info->channels);
if (status == MagickFalse)
break;
}
if ((status != MagickFalse) && (image->colorspace == CMYKColorspace))
status=NegateCMYK(image,exception);
if (status != MagickFalse)
status=CorrectPSDAlphaBlend(image_info,image,exception);
sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes);
return(status);
}
static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
has_merged_image,
skip_layers;
MagickOffsetType
offset;
MagickSizeType
length;
MagickBooleanType
status;
PSDInfo
psd_info;
register ssize_t
i;
ssize_t
count;
unsigned char
*data;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read image header.
*/
image->endian=MSBEndian;
count=ReadBlob(image,4,(unsigned char *) psd_info.signature);
psd_info.version=ReadBlobMSBShort(image);
if ((count == 0) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) ||
((psd_info.version != 1) && (psd_info.version != 2)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
(void) ReadBlob(image,6,psd_info.reserved);
psd_info.channels=ReadBlobMSBShort(image);
if (psd_info.channels > MaxPSDChannels)
ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded");
psd_info.rows=ReadBlobMSBLong(image);
psd_info.columns=ReadBlobMSBLong(image);
if ((psd_info.version == 1) && ((psd_info.rows > 30000) ||
(psd_info.columns > 30000)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
psd_info.depth=ReadBlobMSBShort(image);
if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
psd_info.mode=ReadBlobMSBShort(image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s",
(double) psd_info.columns,(double) psd_info.rows,(double)
psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType)
psd_info.mode));
/*
Initialize image.
*/
image->depth=psd_info.depth;
image->columns=psd_info.columns;
image->rows=psd_info.rows;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
if (SetImageBackgroundColor(image,exception) == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
if (psd_info.mode == LabMode)
SetImageColorspace(image,LabColorspace,exception);
if (psd_info.mode == CMYKMode)
{
SetImageColorspace(image,CMYKColorspace,exception);
if (psd_info.channels > 4)
SetImageAlphaChannel(image,ActivateAlphaChannel,exception);
}
else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) ||
(psd_info.mode == DuotoneMode))
{
status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536,
exception);
if (status == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image colormap allocated");
SetImageColorspace(image,GRAYColorspace,exception);
if (psd_info.channels > 1)
SetImageAlphaChannel(image,ActivateAlphaChannel,exception);
}
else
if (psd_info.channels > 3)
SetImageAlphaChannel(image,ActivateAlphaChannel,exception);
/*
Read PSD raster colormap only present for indexed and duotone images.
*/
length=ReadBlobMSBLong(image);
if (length != 0)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading colormap");
if (psd_info.mode == DuotoneMode)
{
/*
Duotone image data; the format of this data is undocumented.
*/
data=(unsigned char *) AcquireQuantumMemory((size_t) length,
sizeof(*data));
if (data == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ReadBlob(image,(size_t) length,data);
data=(unsigned char *) RelinquishMagickMemory(data);
}
else
{
size_t
number_colors;
/*
Read PSD raster colormap.
*/
number_colors=length/3;
if (number_colors > 65536)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (AcquireImageColormap(image,number_colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].red=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].green=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].blue=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->alpha_trait=UndefinedPixelTrait;
}
}
if ((image->depth == 1) && (image->storage_class != PseudoClass))
ThrowReaderException(CorruptImageError, "ImproperImageHeader");
has_merged_image=MagickTrue;
length=ReadBlobMSBLong(image);
if (length != 0)
{
unsigned char
*blocks;
/*
Image resources block.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading image resource blocks - %.20g bytes",(double)
((MagickOffsetType) length));
blocks=(unsigned char *) AcquireQuantumMemory((size_t) length,
sizeof(*blocks));
if (blocks == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,(size_t) length,blocks);
if ((count != (ssize_t) length) || (length < 4) ||
(LocaleNCompare((char *) blocks,"8BIM",4) != 0))
{
blocks=(unsigned char *) RelinquishMagickMemory(blocks);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image,
exception);
blocks=(unsigned char *) RelinquishMagickMemory(blocks);
}
/*
Layer and mask block.
*/
length=GetPSDSize(&psd_info,image);
if (length == 8)
{
length=ReadBlobMSBLong(image);
length=ReadBlobMSBLong(image);
}
offset=TellBlob(image);
skip_layers=MagickFalse;
if ((image_info->number_scenes == 1) && (image_info->scene == 0) &&
(has_merged_image != MagickFalse))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" read composite only");
skip_layers=MagickTrue;
}
if (length == 0)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image has no layers");
}
else
{
if (ReadPSDLayers(image,image_info,&psd_info,skip_layers,exception) !=
MagickTrue)
{
(void) CloseBlob(image);
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Skip the rest of the layer and mask information.
*/
SeekBlob(image,offset+length,SEEK_SET);
}
/*
If we are only "pinging" the image, then we're done - so return.
*/
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
Read the precombined layer, present for PSD < 4 compatibility.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading the precombined layer");
if ((has_merged_image != MagickFalse) || (GetImageListLength(image) == 1))
has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image,
&psd_info,exception);
if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) &&
(length != 0))
{
SeekBlob(image,offset,SEEK_SET);
status=ReadPSDLayers(image,image_info,&psd_info,MagickFalse,exception);
if (status != MagickTrue)
{
(void) CloseBlob(image);
image=DestroyImageList(image);
return((Image *) NULL);
}
}
if (has_merged_image == MagickFalse)
{
Image
*merged;
if (GetImageListLength(image) == 1)
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
SetImageAlphaChannel(image,TransparentAlphaChannel,exception);
image->background_color.alpha=TransparentAlpha;
image->background_color.alpha_trait=BlendPixelTrait;
merged=MergeImageLayers(image,FlattenLayer,exception);
ReplaceImageInList(&image,merged);
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterPSDImage() adds properties for the PSD image format to
% the list of supported formats. The properties 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 RegisterPSDImage method is:
%
% size_t RegisterPSDImage(void)
%
*/
ModuleExport size_t RegisterPSDImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("PSD","PSB","Adobe Large Document Format");
entry->decoder=(DecodeImageHandler *) ReadPSDImage;
entry->encoder=(EncodeImageHandler *) WritePSDImage;
entry->magick=(IsImageFormatHandler *) IsPSD;
entry->flags|=CoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("PSD","PSD","Adobe Photoshop bitmap");
entry->decoder=(DecodeImageHandler *) ReadPSDImage;
entry->encoder=(EncodeImageHandler *) WritePSDImage;
entry->magick=(IsImageFormatHandler *) IsPSD;
entry->flags|=CoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterPSDImage() removes format registrations made by the
% PSD module from the list of supported formats.
%
% The format of the UnregisterPSDImage method is:
%
% UnregisterPSDImage(void)
%
*/
ModuleExport void UnregisterPSDImage(void)
{
(void) UnregisterMagickInfo("PSB");
(void) UnregisterMagickInfo("PSD");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WritePSDImage() writes an image in the Adobe Photoshop encoded image format.
%
% The format of the WritePSDImage method is:
%
% MagickBooleanType WritePSDImage(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 inline ssize_t SetPSDOffset(const PSDInfo *psd_info,Image *image,
const size_t offset)
{
if (psd_info->version == 1)
return(WriteBlobMSBShort(image,(unsigned short) offset));
return(WriteBlobMSBLong(image,(unsigned short) offset));
}
static inline ssize_t WritePSDOffset(const PSDInfo *psd_info,Image *image,
const MagickSizeType size,const MagickSizeType offset)
{
MagickSizeType
current_offset;
ssize_t
result;
current_offset=TellBlob(image);
SeekBlob(image,offset,SEEK_SET);
if (psd_info->version == 1)
result=WriteBlobMSBShort(image,(unsigned short) size);
else
result=(WriteBlobMSBLong(image,(unsigned short) size));
SeekBlob(image,current_offset,SEEK_SET);
return(result);
}
static inline ssize_t SetPSDSize(const PSDInfo *psd_info,Image *image,
const MagickSizeType size)
{
if (psd_info->version == 1)
return(WriteBlobMSBLong(image,(unsigned int) size));
return(WriteBlobMSBLongLong(image,size));
}
static inline ssize_t WritePSDSize(const PSDInfo *psd_info,Image *image,
const MagickSizeType size,const MagickSizeType offset)
{
MagickSizeType
current_offset;
ssize_t
result;
current_offset=TellBlob(image);
SeekBlob(image,offset,SEEK_SET);
if (psd_info->version == 1)
result=WriteBlobMSBLong(image,(unsigned int) size);
else
result=WriteBlobMSBLongLong(image,size);
SeekBlob(image,current_offset,SEEK_SET);
return(result);
}
static size_t PSDPackbitsEncodeImage(Image *image,const size_t length,
const unsigned char *pixels,unsigned char *compact_pixels,
ExceptionInfo *exception)
{
int
count;
register ssize_t
i,
j;
register unsigned char
*q;
unsigned char
*packbits;
/*
Compress pixels with Packbits encoding.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(pixels != (unsigned char *) NULL);
assert(compact_pixels != (unsigned char *) NULL);
packbits=(unsigned char *) AcquireQuantumMemory(128UL,sizeof(*packbits));
if (packbits == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
q=compact_pixels;
for (i=(ssize_t) length; i != 0; )
{
switch (i)
{
case 1:
{
i--;
*q++=(unsigned char) 0;
*q++=(*pixels);
break;
}
case 2:
{
i-=2;
*q++=(unsigned char) 1;
*q++=(*pixels);
*q++=pixels[1];
break;
}
case 3:
{
i-=3;
if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2)))
{
*q++=(unsigned char) ((256-3)+1);
*q++=(*pixels);
break;
}
*q++=(unsigned char) 2;
*q++=(*pixels);
*q++=pixels[1];
*q++=pixels[2];
break;
}
default:
{
if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2)))
{
/*
Packed run.
*/
count=3;
while (((ssize_t) count < i) && (*pixels == *(pixels+count)))
{
count++;
if (count >= 127)
break;
}
i-=count;
*q++=(unsigned char) ((256-count)+1);
*q++=(*pixels);
pixels+=count;
break;
}
/*
Literal run.
*/
count=0;
while ((*(pixels+count) != *(pixels+count+1)) ||
(*(pixels+count+1) != *(pixels+count+2)))
{
packbits[count+1]=pixels[count];
count++;
if (((ssize_t) count >= (i-3)) || (count >= 127))
break;
}
i-=count;
*packbits=(unsigned char) (count-1);
for (j=0; j <= (ssize_t) count; j++)
*q++=packbits[j];
pixels+=count;
break;
}
}
}
*q++=(unsigned char) 128; /* EOD marker */
packbits=(unsigned char *) RelinquishMagickMemory(packbits);
return((size_t) (q-compact_pixels));
}
static size_t WriteCompressionStart(const PSDInfo *psd_info,Image *image,
const Image *next_image,const ssize_t channels)
{
size_t
length;
ssize_t
i,
y;
if (next_image->compression == RLECompression)
{
length=WriteBlobMSBShort(image,RLE);
for (i=0; i < channels; i++)
for (y=0; y < (ssize_t) next_image->rows; y++)
length+=SetPSDOffset(psd_info,image,0);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
else if (next_image->compression == ZipCompression)
length=WriteBlobMSBShort(image,ZipWithoutPrediction);
#endif
else
length=WriteBlobMSBShort(image,Raw);
return(length);
}
static size_t WritePSDChannel(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
const QuantumType quantum_type, unsigned char *compact_pixels,
MagickOffsetType size_offset,const MagickBooleanType separate,
ExceptionInfo *exception)
{
int
y;
MagickBooleanType
monochrome;
QuantumInfo
*quantum_info;
register const Quantum
*p;
register ssize_t
i;
size_t
count,
length;
unsigned char
*pixels;
#ifdef MAGICKCORE_ZLIB_DELEGATE
#define CHUNK 16384
int
flush,
level;
unsigned char
*compressed_pixels;
z_stream
stream;
compressed_pixels=(unsigned char *) NULL;
flush=Z_NO_FLUSH;
#endif
count=0;
if (separate != MagickFalse)
{
size_offset=TellBlob(image)+2;
count+=WriteCompressionStart(psd_info,image,next_image,1);
}
if (next_image->depth > 8)
next_image->depth=16;
monochrome=IsImageMonochrome(image) && (image->depth == 1) ?
MagickTrue : MagickFalse;
quantum_info=AcquireQuantumInfo(image_info,next_image);
if (quantum_info == (QuantumInfo *) NULL)
return(0);
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
#ifdef MAGICKCORE_ZLIB_DELEGATE
if (next_image->compression == ZipCompression)
{
compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK,
sizeof(*compressed_pixels));
if (compressed_pixels == (unsigned char *) NULL)
{
quantum_info=DestroyQuantumInfo(quantum_info);
return(0);
}
ResetMagickMemory(&stream,0,sizeof(stream));
stream.data_type=Z_BINARY;
level=Z_DEFAULT_COMPRESSION;
if ((image_info->quality > 0 && image_info->quality < 10))
level=(int) image_info->quality;
if (deflateInit(&stream,level) != Z_OK)
{
quantum_info=DestroyQuantumInfo(quantum_info);
return(0);
}
}
#endif
for (y=0; y < (ssize_t) next_image->rows; y++)
{
p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (monochrome != MagickFalse)
for (i=0; i < (ssize_t) length; i++)
pixels[i]=(~pixels[i]);
if (next_image->compression == RLECompression)
{
length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels,
exception);
count+=WriteBlob(image,length,compact_pixels);
size_offset+=WritePSDOffset(psd_info,image,length,size_offset);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
else if (next_image->compression == ZipCompression)
{
stream.avail_in=(uInt) length;
stream.next_in=(Bytef *) pixels;
if (y == (ssize_t) next_image->rows-1)
flush=Z_FINISH;
do {
stream.avail_out=(uInt) CHUNK;
stream.next_out=(Bytef *) compressed_pixels;
if (deflate(&stream,flush) == Z_STREAM_ERROR)
break;
length=(size_t) CHUNK-stream.avail_out;
if (length > 0)
count+=WriteBlob(image,length,compressed_pixels);
} while (stream.avail_out == 0);
}
#endif
else
count+=WriteBlob(image,length,pixels);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
if (next_image->compression == ZipCompression)
{
(void) deflateEnd(&stream);
compressed_pixels=(unsigned char *) RelinquishMagickMemory(
compressed_pixels);
}
#endif
quantum_info=DestroyQuantumInfo(quantum_info);
return(count);
}
static unsigned char *AcquireCompactPixels(const Image *image,
ExceptionInfo *exception)
{
size_t
packet_size;
unsigned char
*compact_pixels;
packet_size=image->depth > 8UL ? 2UL : 1UL;
compact_pixels=(unsigned char *) AcquireQuantumMemory((9*
image->columns)+1,packet_size*sizeof(*compact_pixels));
if (compact_pixels == (unsigned char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
image->filename);
}
return(compact_pixels);
}
static size_t WritePSDChannels(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
MagickOffsetType size_offset,const MagickBooleanType separate,
ExceptionInfo *exception)
{
Image
*mask;
MagickOffsetType
rows_offset;
size_t
channels,
count,
length,
offset_length;
unsigned char
*compact_pixels;
count=0;
offset_length=0;
rows_offset=0;
compact_pixels=(unsigned char *) NULL;
if (next_image->compression == RLECompression)
{
compact_pixels=AcquireCompactPixels(image,exception);
if (compact_pixels == (unsigned char *) NULL)
return(0);
}
channels=1;
if (separate == MagickFalse)
{
if (next_image->storage_class != PseudoClass)
{
if (IsImageGray(next_image) == MagickFalse)
channels=next_image->colorspace == CMYKColorspace ? 4 : 3;
if (next_image->alpha_trait != UndefinedPixelTrait)
channels++;
}
rows_offset=TellBlob(image)+2;
count+=WriteCompressionStart(psd_info,image,next_image,channels);
offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4));
}
size_offset+=2;
if (next_image->storage_class == PseudoClass)
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
IndexQuantum,compact_pixels,rows_offset,separate,exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
else
{
if (IsImageGray(next_image) != MagickFalse)
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
GrayQuantum,compact_pixels,rows_offset,separate,exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
else
{
if (next_image->colorspace == CMYKColorspace)
(void) NegateCMYK(next_image,exception);
length=WritePSDChannel(psd_info,image_info,image,next_image,
RedQuantum,compact_pixels,rows_offset,separate,exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
length=WritePSDChannel(psd_info,image_info,image,next_image,
GreenQuantum,compact_pixels,rows_offset,separate,exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
length=WritePSDChannel(psd_info,image_info,image,next_image,
BlueQuantum,compact_pixels,rows_offset,separate,exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
if (next_image->colorspace == CMYKColorspace)
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
BlackQuantum,compact_pixels,rows_offset,separate,exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
}
if (next_image->alpha_trait != UndefinedPixelTrait)
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
AlphaQuantum,compact_pixels,rows_offset,separate,exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
}
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
if (next_image->colorspace == CMYKColorspace)
(void) NegateCMYK(next_image,exception);
if (separate != MagickFalse)
{
const char
*property;
property=GetImageArtifact(next_image,"psd:opacity-mask");
if (property != (const char *) NULL)
{
mask=(Image *) GetImageRegistry(ImageRegistryType,property,
exception);
if (mask != (Image *) NULL)
{
if (mask->compression == RLECompression)
{
compact_pixels=AcquireCompactPixels(mask,exception);
if (compact_pixels == (unsigned char *) NULL)
return(0);
}
length=WritePSDChannel(psd_info,image_info,image,mask,
RedQuantum,compact_pixels,rows_offset,MagickTrue,exception);
(void) WritePSDSize(psd_info,image,length,size_offset);
count+=length;
compact_pixels=(unsigned char *) RelinquishMagickMemory(
compact_pixels);
}
}
}
return(count);
}
static size_t WritePascalString(Image *image,const char *value,size_t padding)
{
size_t
count,
length;
register ssize_t
i;
/*
Max length is 255.
*/
count=0;
length=(strlen(value) > 255UL ) ? 255UL : strlen(value);
if (length == 0)
count+=WriteBlobByte(image,0);
else
{
count+=WriteBlobByte(image,(unsigned char) length);
count+=WriteBlob(image,length,(const unsigned char *) value);
}
length++;
if ((length % padding) == 0)
return(count);
for (i=0; i < (ssize_t) (padding-(length % padding)); i++)
count+=WriteBlobByte(image,0);
return(count);
}
static void WriteResolutionResourceBlock(Image *image)
{
double
x_resolution,
y_resolution;
unsigned short
units;
if (image->units == PixelsPerCentimeterResolution)
{
x_resolution=2.54*65536.0*image->resolution.x+0.5;
y_resolution=2.54*65536.0*image->resolution.y+0.5;
units=2;
}
else
{
x_resolution=65536.0*image->resolution.x+0.5;
y_resolution=65536.0*image->resolution.y+0.5;
units=1;
}
(void) WriteBlob(image,4,(const unsigned char *) "8BIM");
(void) WriteBlobMSBShort(image,0x03ED);
(void) WriteBlobMSBShort(image,0);
(void) WriteBlobMSBLong(image,16); /* resource size */
(void) WriteBlobMSBLong(image,(unsigned int) (x_resolution+0.5));
(void) WriteBlobMSBShort(image,units); /* horizontal resolution unit */
(void) WriteBlobMSBShort(image,units); /* width unit */
(void) WriteBlobMSBLong(image,(unsigned int) (y_resolution+0.5));
(void) WriteBlobMSBShort(image,units); /* vertical resolution unit */
(void) WriteBlobMSBShort(image,units); /* height unit */
}
static inline size_t WriteChannelSize(const PSDInfo *psd_info,Image *image,
const signed short channel)
{
size_t
count;
count=WriteBlobMSBSignedShort(image,channel);
count+=SetPSDSize(psd_info,image,0);
return(count);
}
static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile)
{
register const unsigned char
*p;
size_t
length;
unsigned char
*datum;
unsigned int
count,
long_sans;
unsigned short
id,
short_sans;
length=GetStringInfoLength(bim_profile);
if (length < 16)
return;
datum=GetStringInfoDatum(bim_profile);
for (p=datum; (p >= datum) && (p < (datum+length-16)); )
{
register unsigned char
*q;
q=(unsigned char *) p;
if (LocaleNCompare((const char *) p,"8BIM",4) != 0)
break;
p=PushLongPixel(MSBEndian,p,&long_sans);
p=PushShortPixel(MSBEndian,p,&id);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushLongPixel(MSBEndian,p,&count);
if (id == 0x0000040f)
{
ssize_t
quantum;
quantum=PSDQuantum(count)+12;
if ((quantum >= 12) && (quantum < (ssize_t) length))
{
if ((q+quantum < (datum+length-16)))
(void) CopyMagickMemory(q,q+quantum,length-quantum-(q-datum));
SetStringInfoLength(bim_profile,length-quantum);
}
break;
}
p+=count;
if ((count & 0x01) != 0)
p++;
}
}
static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile)
{
register const unsigned char
*p;
size_t
length;
unsigned char
*datum;
unsigned int
count,
long_sans;
unsigned short
id,
short_sans;
length=GetStringInfoLength(bim_profile);
if (length < 16)
return;
datum=GetStringInfoDatum(bim_profile);
for (p=datum; (p >= datum) && (p < (datum+length-16)); )
{
register unsigned char
*q;
ssize_t
cnt;
q=(unsigned char *) p;
if (LocaleNCompare((const char *) p,"8BIM",4) != 0)
return;
p=PushLongPixel(MSBEndian,p,&long_sans);
p=PushShortPixel(MSBEndian,p,&id);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushLongPixel(MSBEndian,p,&count);
cnt=PSDQuantum(count);
if (cnt < 0)
return;
if ((id == 0x000003ed) && (cnt < (ssize_t) (length-12)))
{
(void) CopyMagickMemory(q,q+cnt+12,length-(cnt+12)-(q-datum));
SetStringInfoLength(bim_profile,length-(cnt+12));
break;
}
p+=count;
if ((count & 0x01) != 0)
p++;
}
}
static const StringInfo *GetAdditionalInformation(const ImageInfo *image_info,
Image *image,ExceptionInfo *exception)
{
#define PSDKeySize 5
#define PSDAllowedLength 36
char
key[PSDKeySize];
/* Whitelist of keys from: https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/ */
const char
allowed[PSDAllowedLength][PSDKeySize] = {
"blnc", "blwh", "brit", "brst", "clbl", "clrL", "curv", "expA", "FMsk",
"GdFl", "grdm", "hue ", "hue2", "infx", "knko", "lclr", "levl", "lnsr",
"lfx2", "luni", "lrFX", "lspf", "lyid", "lyvr", "mixr", "nvrt", "phfl",
"post", "PtFl", "selc", "shpa", "sn2P", "SoCo", "thrs", "tsly", "vibA"
},
*option;
const StringInfo
*info;
MagickBooleanType
found;
register size_t
i;
size_t
remaining_length,
length;
StringInfo
*profile;
unsigned char
*p;
unsigned int
size;
info=GetImageProfile(image,"psd:additional-info");
if (info == (const StringInfo *) NULL)
return((const StringInfo *) NULL);
option=GetImageOption(image_info,"psd:additional-info");
if (LocaleCompare(option,"all") == 0)
return(info);
if (LocaleCompare(option,"selective") != 0)
{
profile=RemoveImageProfile(image,"psd:additional-info");
return(DestroyStringInfo(profile));
}
length=GetStringInfoLength(info);
p=GetStringInfoDatum(info);
remaining_length=length;
length=0;
while (remaining_length >= 12)
{
/* skip over signature */
p+=4;
key[0]=(*p++);
key[1]=(*p++);
key[2]=(*p++);
key[3]=(*p++);
key[4]='\0';
size=(unsigned int) (*p++) << 24;
size|=(unsigned int) (*p++) << 16;
size|=(unsigned int) (*p++) << 8;
size|=(unsigned int) (*p++);
size=size & 0xffffffff;
remaining_length-=12;
if ((size_t) size > remaining_length)
return((const StringInfo *) NULL);
found=MagickFalse;
for (i=0; i < PSDAllowedLength; i++)
{
if (LocaleNCompare(key,allowed[i],PSDKeySize) != 0)
continue;
found=MagickTrue;
break;
}
remaining_length-=(size_t) size;
if (found == MagickFalse)
{
if (remaining_length > 0)
p=(unsigned char *) CopyMagickMemory(p-12,p+size,remaining_length);
continue;
}
length+=(size_t) size+12;
p+=size;
}
profile=RemoveImageProfile(image,"psd:additional-info");
if (length == 0)
return(DestroyStringInfo(profile));
SetStringInfoLength(profile,(const size_t) length);
SetImageProfile(image,"psd:additional-info",info,exception);
return(profile);
}
static MagickBooleanType WritePSDImage(const ImageInfo *image_info,
Image *image,ExceptionInfo *exception)
{
char
layer_name[MagickPathExtent];
const char
*property;
const StringInfo
*icc_profile,
*info;
Image
*base_image,
*next_image;
MagickBooleanType
status;
MagickOffsetType
*layer_size_offsets,
size_offset;
PSDInfo
psd_info;
register ssize_t
i;
size_t
layer_count,
layer_index,
length,
name_length,
num_channels,
packet_size,
rounded_size,
size;
StringInfo
*bim_profile;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
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);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
packet_size=(size_t) (image->depth > 8 ? 6 : 3);
if (image->alpha_trait != UndefinedPixelTrait)
packet_size+=image->depth > 8 ? 2 : 1;
psd_info.version=1;
if ((LocaleCompare(image_info->magick,"PSB") == 0) ||
(image->columns > 30000) || (image->rows > 30000))
psd_info.version=2;
(void) WriteBlob(image,4,(const unsigned char *) "8BPS");
(void) WriteBlobMSBShort(image,psd_info.version); /* version */
for (i=1; i <= 6; i++)
(void) WriteBlobByte(image, 0); /* 6 bytes of reserved */
if (SetImageGray(image,exception) != MagickFalse)
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL);
else
if ((image_info->type != TrueColorType) && (image_info->type !=
TrueColorAlphaType) && (image->storage_class == PseudoClass))
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL);
else
{
if (image->storage_class == PseudoClass)
(void) SetImageStorageClass(image,DirectClass,exception);
if (image->colorspace != CMYKColorspace)
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL);
else
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL);
}
(void) WriteBlobMSBShort(image,(unsigned short) num_channels);
(void) WriteBlobMSBLong(image,(unsigned int) image->rows);
(void) WriteBlobMSBLong(image,(unsigned int) image->columns);
if (IsImageGray(image) != MagickFalse)
{
MagickBooleanType
monochrome;
/*
Write depth & mode.
*/
monochrome=IsImageMonochrome(image) && (image->depth == 1) ?
MagickTrue : MagickFalse;
(void) WriteBlobMSBShort(image,(unsigned short)
(monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8));
(void) WriteBlobMSBShort(image,(unsigned short)
(monochrome != MagickFalse ? BitmapMode : GrayscaleMode));
}
else
{
(void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class ==
PseudoClass ? 8 : image->depth > 8 ? 16 : 8));
if (((image_info->colorspace != UndefinedColorspace) ||
(image->colorspace != CMYKColorspace)) &&
(image_info->colorspace != CMYKColorspace))
{
(void) TransformImageColorspace(image,sRGBColorspace,exception);
(void) WriteBlobMSBShort(image,(unsigned short)
(image->storage_class == PseudoClass ? IndexedMode : RGBMode));
}
else
{
if (image->colorspace != CMYKColorspace)
(void) TransformImageColorspace(image,CMYKColorspace,exception);
(void) WriteBlobMSBShort(image,CMYKMode);
}
}
if ((IsImageGray(image) != MagickFalse) ||
(image->storage_class == DirectClass) || (image->colors > 256))
(void) WriteBlobMSBLong(image,0);
else
{
/*
Write PSD raster colormap.
*/
(void) WriteBlobMSBLong(image,768);
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].red));
for ( ; i < 256; i++)
(void) WriteBlobByte(image,0);
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(
image->colormap[i].green));
for ( ; i < 256; i++)
(void) WriteBlobByte(image,0);
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].blue));
for ( ; i < 256; i++)
(void) WriteBlobByte(image,0);
}
/*
Image resource block.
*/
length=28; /* 0x03EB */
bim_profile=(StringInfo *) GetImageProfile(image,"8bim");
icc_profile=GetImageProfile(image,"icc");
if (bim_profile != (StringInfo *) NULL)
{
bim_profile=CloneStringInfo(bim_profile);
if (icc_profile != (StringInfo *) NULL)
RemoveICCProfileFromResourceBlock(bim_profile);
RemoveResolutionFromResourceBlock(bim_profile);
length+=PSDQuantum(GetStringInfoLength(bim_profile));
}
if (icc_profile != (const StringInfo *) NULL)
length+=PSDQuantum(GetStringInfoLength(icc_profile))+12;
(void) WriteBlobMSBLong(image,(unsigned int) length);
WriteResolutionResourceBlock(image);
if (bim_profile != (StringInfo *) NULL)
{
(void) WriteBlob(image,GetStringInfoLength(bim_profile),
GetStringInfoDatum(bim_profile));
bim_profile=DestroyStringInfo(bim_profile);
}
if (icc_profile != (StringInfo *) NULL)
{
(void) WriteBlob(image,4,(const unsigned char *) "8BIM");
(void) WriteBlobMSBShort(image,0x0000040F);
(void) WriteBlobMSBShort(image,0);
(void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength(
icc_profile));
(void) WriteBlob(image,GetStringInfoLength(icc_profile),
GetStringInfoDatum(icc_profile));
if ((MagickOffsetType) GetStringInfoLength(icc_profile) !=
PSDQuantum(GetStringInfoLength(icc_profile)))
(void) WriteBlobByte(image,0);
}
base_image=GetNextImageInList(image);
if (base_image == (Image *) NULL)
base_image=image;
size=0;
size_offset=TellBlob(image);
SetPSDSize(&psd_info,image,0);
SetPSDSize(&psd_info,image,0);
layer_count=0;
for (next_image=base_image; next_image != NULL; )
{
layer_count++;
next_image=GetNextImageInList(next_image);
}
if (image->alpha_trait != UndefinedPixelTrait)
size+=WriteBlobMSBShort(image,-(unsigned short) layer_count);
else
size+=WriteBlobMSBShort(image,(unsigned short) layer_count);
layer_size_offsets=(MagickOffsetType *) AcquireQuantumMemory(
(size_t) layer_count,sizeof(MagickOffsetType));
if (layer_size_offsets == (MagickOffsetType *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
layer_index=0;
for (next_image=base_image; next_image != NULL; )
{
Image
*mask;
unsigned char
default_color;
unsigned short
channels,
total_channels;
mask=(Image *) NULL;
property=GetImageArtifact(next_image,"psd:opacity-mask");
default_color=0;
if (property != (const char *) NULL)
{
mask=(Image *) GetImageRegistry(ImageRegistryType,property,exception);
default_color=strlen(property) == 9 ? 255 : 0;
}
size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.y);
size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.x);
size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.y+
next_image->rows));
size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.x+
next_image->columns));
channels=1U;
if ((next_image->storage_class != PseudoClass) &&
(IsImageGray(next_image) == MagickFalse))
channels=next_image->colorspace == CMYKColorspace ? 4U : 3U;
total_channels=channels;
if (next_image->alpha_trait != UndefinedPixelTrait)
total_channels++;
if (mask != (Image *) NULL)
total_channels++;
size+=WriteBlobMSBShort(image,total_channels);
layer_size_offsets[layer_index++]=TellBlob(image);
for (i=0; i < (ssize_t) channels; i++)
size+=WriteChannelSize(&psd_info,image,(signed short) i);
if (next_image->alpha_trait != UndefinedPixelTrait)
size+=WriteChannelSize(&psd_info,image,-1);
if (mask != (Image *) NULL)
size+=WriteChannelSize(&psd_info,image,-2);
size+=WriteBlob(image,4,(const unsigned char *) "8BIM");
size+=WriteBlob(image,4,(const unsigned char *)
CompositeOperatorToPSDBlendMode(next_image->compose));
property=GetImageArtifact(next_image,"psd:layer.opacity");
if (property != (const char *) NULL)
{
Quantum
opacity;
opacity=(Quantum) StringToInteger(property);
size+=WriteBlobByte(image,ScaleQuantumToChar(opacity));
(void) ApplyPSDLayerOpacity(next_image,opacity,MagickTrue,exception);
}
else
size+=WriteBlobByte(image,255);
size+=WriteBlobByte(image,0);
size+=WriteBlobByte(image,next_image->compose==NoCompositeOp ?
1 << 0x02 : 1); /* layer properties - visible, etc. */
size+=WriteBlobByte(image,0);
info=GetAdditionalInformation(image_info,next_image,exception);
property=(const char *) GetImageProperty(next_image,"label",exception);
if (property == (const char *) NULL)
{
(void) FormatLocaleString(layer_name,MagickPathExtent,"L%.20g",
(double) layer_index);
property=layer_name;
}
name_length=strlen(property)+1;
if ((name_length % 4) != 0)
name_length+=(4-(name_length % 4));
if (info != (const StringInfo *) NULL)
name_length+=GetStringInfoLength(info);
name_length+=8;
if (mask != (Image *) NULL)
name_length+=20;
size+=WriteBlobMSBLong(image,(unsigned int) name_length);
if (mask == (Image *) NULL)
size+=WriteBlobMSBLong(image,0);
else
{
if (mask->compose != NoCompositeOp)
(void) ApplyPSDOpacityMask(next_image,mask,ScaleCharToQuantum(
default_color),MagickTrue,exception);
mask->page.y+=image->page.y;
mask->page.x+=image->page.x;
size+=WriteBlobMSBLong(image,20);
size+=WriteBlobMSBSignedLong(image,mask->page.y);
size+=WriteBlobMSBSignedLong(image,mask->page.x);
size+=WriteBlobMSBLong(image,(const unsigned int) mask->rows+
mask->page.y);
size+=WriteBlobMSBLong(image,(const unsigned int) mask->columns+
mask->page.x);
size+=WriteBlobByte(image,default_color);
size+=WriteBlobByte(image,mask->compose == NoCompositeOp ? 2 : 0);
size+=WriteBlobMSBShort(image,0);
}
size+=WriteBlobMSBLong(image,0);
size+=WritePascalString(image,property,4);
if (info != (const StringInfo *) NULL)
size+=WriteBlob(image,GetStringInfoLength(info),
GetStringInfoDatum(info));
next_image=GetNextImageInList(next_image);
}
/*
Now the image data!
*/
next_image=base_image;
layer_index=0;
while (next_image != NULL)
{
length=WritePSDChannels(&psd_info,image_info,image,next_image,
layer_size_offsets[layer_index++],MagickTrue,exception);
if (length == 0)
{
status=MagickFalse;
break;
}
size+=length;
next_image=GetNextImageInList(next_image);
}
(void) WriteBlobMSBLong(image,0); /* user mask data */
/*
Write the total size
*/
size_offset+=WritePSDSize(&psd_info,image,size+
(psd_info.version == 1 ? 8 : 16),size_offset);
if ((size/2) != ((size+1)/2))
rounded_size=size+1;
else
rounded_size=size;
(void) WritePSDSize(&psd_info,image,rounded_size,size_offset);
layer_size_offsets=(MagickOffsetType *) RelinquishMagickMemory(
layer_size_offsets);
/*
Remove the opacity mask from the registry
*/
next_image=base_image;
while (next_image != (Image *) NULL)
{
property=GetImageArtifact(next_image,"psd:opacity-mask");
if (property != (const char *) NULL)
DeleteImageRegistry(property);
next_image=GetNextImageInList(next_image);
}
/*
Write composite image.
*/
if (status != MagickFalse)
{
CompressionType
compression;
compression=image->compression;
if (image->compression == ZipCompression)
image->compression=RLECompression;
if (WritePSDChannels(&psd_info,image_info,image,image,0,MagickFalse,
exception) == 0)
status=MagickFalse;
image->compression=compression;
}
(void) CloseBlob(image);
return(status);
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_3107_0 |
crossvul-cpp_data_good_4402_0 | /*
* card-tcos.c: Support for TCOS cards
*
* Copyright (C) 2011 Peter Koch <pk@opensc-project.org>
* Copyright (C) 2002 g10 Code GmbH
* Copyright (C) 2001 Juha Yrjölä <juha.yrjola@iki.fi>
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <stdlib.h>
#include "internal.h"
#include "asn1.h"
#include "cardctl.h"
static const struct sc_atr_table tcos_atrs[] = {
/* Infineon SLE44 */
{ "3B:BA:13:00:81:31:86:5D:00:64:05:0A:02:01:31:80:90:00:8B", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL },
/* Infineon SLE66S */
{ "3B:BA:14:00:81:31:86:5D:00:64:05:14:02:02:31:80:90:00:91", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL },
/* Infineon SLE66CX320P */
{ "3B:BA:96:00:81:31:86:5D:00:64:05:60:02:03:31:80:90:00:66", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL },
/* Infineon SLE66CX322P */
{ "3B:BA:96:00:81:31:86:5D:00:64:05:7B:02:03:31:80:90:00:7D", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL },
/* Philips P5CT072 */
{ "3B:BF:96:00:81:31:FE:5D:00:64:04:11:03:01:31:C0:73:F7:01:D0:00:90:00:7D", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL },
{ "3B:BF:96:00:81:31:FE:5D:00:64:04:11:04:0F:31:C0:73:F7:01:D0:00:90:00:74", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL },
/* Philips P5CT080 */
{ "3B:BF:B6:00:81:31:FE:5D:00:64:04:28:03:02:31:C0:73:F7:01:D0:00:90:00:67", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL },
{ NULL, NULL, NULL, 0, 0, NULL }
};
static struct sc_card_operations tcos_ops;
static struct sc_card_driver tcos_drv = {
"TCOS 3.0",
"tcos",
&tcos_ops,
NULL, 0, NULL
};
static const struct sc_card_operations *iso_ops = NULL;
typedef struct tcos_data_st {
unsigned int pad_flags;
unsigned int next_sign;
} tcos_data;
static int tcos_finish(sc_card_t *card)
{
free(card->drv_data);
return 0;
}
static int tcos_match_card(sc_card_t *card)
{
int i;
i = _sc_match_atr(card, tcos_atrs, &card->type);
if (i < 0)
return 0;
return 1;
}
static int tcos_init(sc_card_t *card)
{
unsigned long flags;
tcos_data *data = malloc(sizeof(tcos_data));
if (!data) return SC_ERROR_OUT_OF_MEMORY;
card->name = "TCOS";
card->drv_data = (void *)data;
card->cla = 0x00;
flags = SC_ALGORITHM_RSA_RAW;
flags |= SC_ALGORITHM_RSA_PAD_PKCS1;
flags |= SC_ALGORITHM_RSA_HASH_NONE;
_sc_card_add_rsa_alg(card, 512, flags, 0);
_sc_card_add_rsa_alg(card, 768, flags, 0);
_sc_card_add_rsa_alg(card, 1024, flags, 0);
if (card->type == SC_CARD_TYPE_TCOS_V3) {
card->caps |= SC_CARD_CAP_APDU_EXT;
_sc_card_add_rsa_alg(card, 1280, flags, 0);
_sc_card_add_rsa_alg(card, 1536, flags, 0);
_sc_card_add_rsa_alg(card, 1792, flags, 0);
_sc_card_add_rsa_alg(card, 2048, flags, 0);
}
return 0;
}
/* Hmmm, I don't know what to do. It seems that the ACL design of
OpenSC should be enhanced to allow for the command based security
attributes of TCOS. FIXME: This just allows to create a very basic
file. */
static int tcos_construct_fci(const sc_file_t *file,
u8 *out, size_t *outlen)
{
u8 *p = out;
u8 buf[64];
size_t n;
/* FIXME: possible buffer overflow */
*p++ = 0x6F; /* FCI */
p++;
/* File size */
buf[0] = (file->size >> 8) & 0xFF;
buf[1] = file->size & 0xFF;
sc_asn1_put_tag(0x81, buf, 2, p, 16, &p);
/* File descriptor */
n = 0;
buf[n] = file->shareable ? 0x40 : 0;
switch (file->type) {
case SC_FILE_TYPE_WORKING_EF:
break;
case SC_FILE_TYPE_DF:
buf[0] |= 0x38;
break;
default:
return SC_ERROR_NOT_SUPPORTED;
}
buf[n++] |= file->ef_structure & 7;
if ( (file->ef_structure & 7) > 1) {
/* record structured file */
buf[n++] = 0x41; /* indicate 3rd byte */
buf[n++] = file->record_length;
}
sc_asn1_put_tag(0x82, buf, n, p, 8, &p);
/* File identifier */
buf[0] = (file->id >> 8) & 0xFF;
buf[1] = file->id & 0xFF;
sc_asn1_put_tag(0x83, buf, 2, p, 16, &p);
/* Directory name */
if (file->type == SC_FILE_TYPE_DF) {
if (file->namelen) {
sc_asn1_put_tag(0x84, file->name, file->namelen,
p, 16, &p);
} else {
/* TCOS needs one, so we use a faked one */
snprintf ((char *) buf, sizeof(buf)-1, "foo-%lu",
(unsigned long) time (NULL));
sc_asn1_put_tag(0x84, buf, strlen ((char *) buf), p, 16, &p);
}
}
/* File descriptor extension */
if (file->prop_attr_len && file->prop_attr) {
n = file->prop_attr_len;
memcpy(buf, file->prop_attr, n);
} else {
n = 0;
buf[n++] = 0x01; /* not invalidated, permanent */
if (file->type == SC_FILE_TYPE_WORKING_EF)
buf[n++] = 0x00; /* generic data file */
}
sc_asn1_put_tag(0x85, buf, n, p, 16, &p);
/* Security attributes */
if (file->sec_attr_len && file->sec_attr) {
memcpy(buf, file->sec_attr, file->sec_attr_len);
n = file->sec_attr_len;
} else {
/* no attributes given - fall back to default one */
memcpy (buf+ 0, "\xa4\x00\x00\x00\xff\xff", 6); /* select */
memcpy (buf+ 6, "\xb0\x00\x00\x00\xff\xff", 6); /* read bin */
memcpy (buf+12, "\xd6\x00\x00\x00\xff\xff", 6); /* upd bin */
memcpy (buf+18, "\x60\x00\x00\x00\xff\xff", 6); /* admin grp*/
n = 24;
}
sc_asn1_put_tag(0x86, buf, n, p, sizeof (buf), &p);
/* fixup length of FCI */
out[1] = p - out - 2;
*outlen = p - out;
return 0;
}
static int tcos_create_file(sc_card_t *card, sc_file_t *file)
{
int r;
size_t len;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE];
sc_apdu_t apdu;
len = SC_MAX_APDU_BUFFER_SIZE;
r = tcos_construct_fci(file, sbuf, &len);
LOG_TEST_RET(card->ctx, r, "tcos_construct_fci() failed");
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0x00, 0x00);
apdu.cla |= 0x80; /* this is an proprietary extension */
apdu.lc = len;
apdu.datalen = len;
apdu.data = sbuf;
r = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
}
static unsigned int map_operations (int commandbyte)
{
unsigned int op = (unsigned int)-1;
switch ( (commandbyte & 0xfe) ) {
case 0xe2: /* append record */ op = SC_AC_OP_UPDATE; break;
case 0x24: /* change password */ op = SC_AC_OP_UPDATE; break;
case 0xe0: /* create */ op = SC_AC_OP_CREATE; break;
case 0xe4: /* delete */ op = SC_AC_OP_DELETE; break;
case 0xe8: /* exclude sfi */ op = SC_AC_OP_WRITE; break;
case 0x82: /* external auth */ op = SC_AC_OP_READ; break;
case 0xe6: /* include sfi */ op = SC_AC_OP_WRITE; break;
case 0x88: /* internal auth */ op = SC_AC_OP_READ; break;
case 0x04: /* invalidate */ op = SC_AC_OP_INVALIDATE; break;
case 0x2a: /* perform sec. op */ op = SC_AC_OP_SELECT; break;
case 0xb0: /* read binary */ op = SC_AC_OP_READ; break;
case 0xb2: /* read record */ op = SC_AC_OP_READ; break;
case 0x44: /* rehabilitate */ op = SC_AC_OP_REHABILITATE; break;
case 0xa4: /* select */ op = SC_AC_OP_SELECT; break;
case 0xee: /* set permanent */ op = SC_AC_OP_CREATE; break;
case 0x2c: /* unblock password */op = SC_AC_OP_WRITE; break;
case 0xd6: /* update binary */ op = SC_AC_OP_WRITE; break;
case 0xdc: /* update record */ op = SC_AC_OP_WRITE; break;
case 0x20: /* verify password */ op = SC_AC_OP_SELECT; break;
case 0x60: /* admin group */ op = SC_AC_OP_CREATE; break;
}
return op;
}
/* Hmmm, I don't know what to do. It seems that the ACL design of
OpenSC should be enhanced to allow for the command based security
attributes of TCOS. FIXME: This just allows to create a very basic
file. */
static void parse_sec_attr(sc_card_t *card,
sc_file_t *file, const u8 *buf, size_t len)
{
unsigned int op;
/* list directory is not covered by ACLs - so always add an entry */
sc_file_add_acl_entry (file, SC_AC_OP_LIST_FILES,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
/* FIXME: check for what LOCK is used */
sc_file_add_acl_entry (file, SC_AC_OP_LOCK,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
for (; len >= 6; len -= 6, buf += 6) {
/* FIXME: temporary hacks */
if (!memcmp(buf, "\xa4\x00\x00\x00\xff\xff", 6)) {/* select */
sc_file_add_acl_entry (file, SC_AC_OP_SELECT,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
} else if (!memcmp(buf, "\xb0\x00\x00\x00\xff\xff", 6)) {/*read*/
sc_file_add_acl_entry (file, SC_AC_OP_READ,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
} else if (!memcmp(buf, "\xd6\x00\x00\x00\xff\xff", 6)) {/*upd*/
sc_file_add_acl_entry (file, SC_AC_OP_UPDATE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
} else if (!memcmp(buf, "\x60\x00\x00\x00\xff\xff", 6)) {/*adm */
sc_file_add_acl_entry (file, SC_AC_OP_WRITE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry (file, SC_AC_OP_CREATE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry (file, SC_AC_OP_INVALIDATE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry (file, SC_AC_OP_REHABILITATE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
} else {
/* the first byte tells use the command or the
command group. We have to mask bit 0
because this one distinguish between AND/OR
combination of PINs*/
op = map_operations (buf[0]);
if (op == (unsigned int)-1) {
sc_log(card->ctx,
"Unknown security command byte %02x\n",
buf[0]);
continue;
}
if (!buf[1])
sc_file_add_acl_entry (file, op,
SC_AC_NONE,
SC_AC_KEY_REF_NONE);
else
sc_file_add_acl_entry (file, op,
SC_AC_CHV, buf[1]);
if (!buf[2] && !buf[3])
sc_file_add_acl_entry (file, op,
SC_AC_NONE,
SC_AC_KEY_REF_NONE);
else
sc_file_add_acl_entry (file, op,
SC_AC_TERM,
(buf[2]<<8)|buf[3]);
}
}
}
static int tcos_select_file(sc_card_t *card,
const sc_path_t *in_path,
sc_file_t **file_out)
{
sc_context_t *ctx;
sc_apdu_t apdu;
sc_file_t *file=NULL;
u8 buf[SC_MAX_APDU_BUFFER_SIZE], pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf;
int r, pathlen;
assert(card != NULL && in_path != NULL);
ctx=card->ctx;
memcpy(path, in_path->value, in_path->len);
pathlen = in_path->len;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0x04);
switch (in_path->type) {
case SC_PATH_TYPE_FILE_ID:
if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS;
/* fall through */
case SC_PATH_TYPE_FROM_CURRENT:
apdu.p1 = 9;
break;
case SC_PATH_TYPE_DF_NAME:
apdu.p1 = 4;
break;
case SC_PATH_TYPE_PATH:
apdu.p1 = 8;
if (pathlen >= 2 && memcmp(path, "\x3F\x00", 2) == 0) path += 2, pathlen -= 2;
if (pathlen == 0) apdu.p1 = 0;
break;
case SC_PATH_TYPE_PARENT:
apdu.p1 = 3;
pathlen = 0;
break;
default:
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
}
if( pathlen == 0 ) apdu.cse = SC_APDU_CASE_2_SHORT;
apdu.lc = pathlen;
apdu.data = path;
apdu.datalen = pathlen;
if (file_out != NULL) {
apdu.resp = buf;
apdu.resplen = sizeof(buf);
apdu.le = 256;
} else {
apdu.resplen = 0;
apdu.le = 0;
apdu.p2 = 0x0C;
apdu.cse = (pathlen == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT;
}
r = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r || file_out == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, r);
if (apdu.resplen < 1 || apdu.resp[0] != 0x62) {
sc_log(ctx, "received invalid template %02X\n", apdu.resp[0]);
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
file = sc_file_new();
if (file == NULL) LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
*file_out = file;
file->path = *in_path;
iso_ops->process_fci(card, file, apdu.resp, apdu.resplen);
parse_sec_attr(card, file, file->sec_attr, file->sec_attr_len);
return 0;
}
static int tcos_list_files(sc_card_t *card, u8 *buf, size_t buflen)
{
sc_context_t *ctx;
sc_apdu_t apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE], p1;
int r, count = 0;
assert(card != NULL);
ctx = card->ctx;
for (p1=1; p1<=2; p1++) {
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xAA, p1, 0);
apdu.cla = 0x80;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 256;
r = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, r, "APDU transmit failed");
if (apdu.sw1==0x6A && (apdu.sw2==0x82 || apdu.sw2==0x88)) continue;
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, r, "List Dir failed");
if (apdu.resplen > buflen) return SC_ERROR_BUFFER_TOO_SMALL;
sc_log(ctx,
"got %"SC_FORMAT_LEN_SIZE_T"u %s-FileIDs\n",
apdu.resplen / 2, p1 == 1 ? "DF" : "EF");
memcpy(buf, apdu.resp, apdu.resplen);
buf += apdu.resplen;
buflen -= apdu.resplen;
count += apdu.resplen;
}
return count;
}
static int tcos_delete_file(sc_card_t *card, const sc_path_t *path)
{
int r;
u8 sbuf[2];
sc_apdu_t apdu;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
if (path->type != SC_PATH_TYPE_FILE_ID && path->len != 2) {
sc_log(card->ctx, "File type has to be SC_PATH_TYPE_FILE_ID\n");
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
}
sbuf[0] = path->value[0];
sbuf[1] = path->value[1];
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE4, 0x00, 0x00);
apdu.cla |= 0x80;
apdu.lc = 2;
apdu.datalen = 2;
apdu.data = sbuf;
r = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
}
static int tcos_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num)
{
sc_context_t *ctx;
sc_apdu_t apdu;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE], *p;
int r, default_key, tcos3;
tcos_data *data;
assert(card != NULL && env != NULL);
ctx = card->ctx;
tcos3=(card->type==SC_CARD_TYPE_TCOS_V3);
data=(tcos_data *)card->drv_data;
if (se_num || (env->operation!=SC_SEC_OPERATION_DECIPHER && env->operation!=SC_SEC_OPERATION_SIGN)) {
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
}
if(!(env->flags & SC_SEC_ENV_KEY_REF_PRESENT))
sc_log(ctx,
"No Key-Reference in SecEnvironment\n");
else
sc_log(ctx,
"Key-Reference %02X (len=%"SC_FORMAT_LEN_SIZE_T"u)\n",
env->key_ref[0], env->key_ref_len);
/* Key-Reference 0x80 ?? */
default_key= !(env->flags & SC_SEC_ENV_KEY_REF_PRESENT) || (env->key_ref_len==1 && env->key_ref[0]==0x80);
sc_log(ctx,
"TCOS3:%d PKCS1:%d\n", tcos3,
!!(env->algorithm_flags & SC_ALGORITHM_RSA_PAD_PKCS1));
data->pad_flags = env->algorithm_flags;
data->next_sign = default_key;
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, tcos3 ? 0x41 : 0xC1, 0xB8);
p = sbuf;
if (env->flags & SC_SEC_ENV_KEY_REF_PRESENT) {
*p++ = (env->flags & SC_SEC_ENV_KEY_REF_SYMMETRIC) ? 0x83 : 0x84;
*p++ = env->key_ref_len;
memcpy(p, env->key_ref, env->key_ref_len);
p += env->key_ref_len;
}
apdu.data = sbuf;
apdu.lc = apdu.datalen = (p - sbuf);
r=sc_transmit_apdu(card, &apdu);
if (r) {
sc_log(ctx,
"%s: APDU transmit failed", sc_strerror(r));
return r;
}
if (apdu.sw1==0x6A && (apdu.sw2==0x81 || apdu.sw2==0x88)) {
sc_log(ctx,
"Detected Signature-Only key\n");
if (env->operation==SC_SEC_OPERATION_SIGN && default_key) return SC_SUCCESS;
}
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
static int tcos_restore_security_env(sc_card_t *card, int se_num)
{
return 0;
}
static int tcos_compute_signature(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen)
{
size_t i, dlen=datalen;
sc_apdu_t apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE];
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE];
int tcos3, r;
assert(card != NULL && data != NULL && out != NULL);
tcos3=(card->type==SC_CARD_TYPE_TCOS_V3);
// We can sign (key length / 8) bytes
if (datalen > 256) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
if(((tcos_data *)card->drv_data)->next_sign) {
if(datalen>48) {
sc_log(card->ctx, "Data to be signed is too long (TCOS supports max. 48 bytes)\n");
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A, 0x9E, 0x9A);
memcpy(sbuf, data, datalen);
dlen=datalen;
} else {
int keylen= tcos3 ? 256 : 128;
sc_format_apdu(card, &apdu, keylen>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A,0x80,0x86);
for(i=0; i<sizeof(sbuf);++i) sbuf[i]=0xff;
sbuf[0]=0x02; sbuf[1]=0x00; sbuf[2]=0x01; sbuf[keylen-datalen]=0x00;
memcpy(sbuf+keylen-datalen+1, data, datalen);
dlen=keylen+1;
}
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = tcos3 ? 256 : 128;
apdu.data = sbuf;
apdu.lc = apdu.datalen = dlen;
r = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
if (tcos3 && apdu.p1==0x80 && apdu.sw1==0x6A && apdu.sw2==0x87) {
int keylen=128;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A,0x80,0x86);
for(i=0; i<sizeof(sbuf);++i) sbuf[i]=0xff;
sbuf[0]=0x02; sbuf[1]=0x00; sbuf[2]=0x01; sbuf[keylen-datalen]=0x00;
memcpy(sbuf+keylen-datalen+1, data, datalen);
dlen=keylen+1;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 128;
apdu.data = sbuf;
apdu.lc = apdu.datalen = dlen;
r = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
}
if (apdu.sw1==0x90 && apdu.sw2==0x00) {
size_t len = apdu.resplen>outlen ? outlen : apdu.resplen;
memcpy(out, apdu.resp, len);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, len);
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
static int tcos_decipher(sc_card_t *card, const u8 * crgram, size_t crgram_len, u8 * out, size_t outlen)
{
sc_context_t *ctx;
sc_apdu_t apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE];
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE];
tcos_data *data;
int tcos3, r;
assert(card != NULL && crgram != NULL && out != NULL);
ctx = card->ctx;
tcos3=(card->type==SC_CARD_TYPE_TCOS_V3);
data=(tcos_data *)card->drv_data;
LOG_FUNC_CALLED(ctx);
sc_log(ctx,
"TCOS3:%d PKCS1:%d\n",tcos3,
!!(data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1));
sc_format_apdu(card, &apdu, crgram_len>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A, 0x80, 0x86);
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = crgram_len;
apdu.data = sbuf;
apdu.lc = apdu.datalen = crgram_len+1;
sbuf[0] = tcos3 ? 0x00 : ((data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) ? 0x81 : 0x02);
if (sizeof sbuf - 1 < crgram_len)
return SC_ERROR_INVALID_ARGUMENTS;
memcpy(sbuf+1, crgram, crgram_len);
r = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
if (apdu.sw1==0x90 && apdu.sw2==0x00) {
size_t len= (apdu.resplen>outlen) ? outlen : apdu.resplen;
unsigned int offset=0;
if(tcos3 && (data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) && apdu.resp[0]==0 && apdu.resp[1]==2) {
offset=2; while(offset<len && apdu.resp[offset]!=0) ++offset;
offset=(offset<len-1) ? offset+1 : 0;
}
memcpy(out, apdu.resp+offset, len-offset);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, len-offset);
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
/* Issue the SET PERMANENT command. With ENABLE_NULLPIN set the
NullPIN method will be activated, otherwise the permanent operation
will be done on the active file. */
static int tcos_setperm(sc_card_t *card, int enable_nullpin)
{
int r;
sc_apdu_t apdu;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0xEE, 0x00, 0x00);
apdu.cla |= 0x80;
apdu.lc = 0;
apdu.datalen = 0;
apdu.data = NULL;
r = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
}
static int tcos_get_serialnr(sc_card_t *card, sc_serial_number_t *serial)
{
int r;
if (!serial)
return SC_ERROR_INVALID_ARGUMENTS;
/* see if we have cached serial number */
if (card->serialnr.len) {
memcpy(serial, &card->serialnr, sizeof(*serial));
return SC_SUCCESS;
}
card->serialnr.len = sizeof card->serialnr.value;
r = sc_parse_ef_gdo(card, card->serialnr.value, &card->serialnr.len, NULL, 0);
if (r < 0) {
card->serialnr.len = 0;
return r;
}
/* copy and return serial number */
memcpy(serial, &card->serialnr, sizeof(*serial));
return SC_SUCCESS;
}
static int tcos_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr)
{
switch (cmd) {
case SC_CARDCTL_TCOS_SETPERM:
return tcos_setperm(card, !!ptr);
case SC_CARDCTL_GET_SERIALNR:
return tcos_get_serialnr(card, (sc_serial_number_t *)ptr);
}
return SC_ERROR_NOT_SUPPORTED;
}
struct sc_card_driver * sc_get_tcos_driver(void)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
if (iso_ops == NULL) iso_ops = iso_drv->ops;
tcos_ops = *iso_drv->ops;
tcos_ops.match_card = tcos_match_card;
tcos_ops.init = tcos_init;
tcos_ops.finish = tcos_finish;
tcos_ops.create_file = tcos_create_file;
tcos_ops.set_security_env = tcos_set_security_env;
tcos_ops.select_file = tcos_select_file;
tcos_ops.list_files = tcos_list_files;
tcos_ops.delete_file = tcos_delete_file;
tcos_ops.compute_signature = tcos_compute_signature;
tcos_ops.decipher = tcos_decipher;
tcos_ops.restore_security_env = tcos_restore_security_env;
tcos_ops.card_ctl = tcos_card_ctl;
return &tcos_drv;
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_4402_0 |
crossvul-cpp_data_bad_674_1 | /**
* FreeRDP: A Remote Desktop Protocol Implementation
* NSCodec Codec
*
* Copyright 2011 Samsung, Author Jiten Pathy
* Copyright 2012 Vic Lee
* 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winpr/crt.h>
#include <freerdp/codec/nsc.h>
#include <freerdp/codec/color.h>
#include "nsc_types.h"
#include "nsc_encode.h"
#include "nsc_sse2.h"
#ifndef NSC_INIT_SIMD
#define NSC_INIT_SIMD(_nsc_context) do { } while (0)
#endif
static void nsc_decode(NSC_CONTEXT* context)
{
UINT16 x;
UINT16 y;
UINT16 rw = ROUND_UP_TO(context->width, 8);
BYTE shift = context->ColorLossLevel - 1; /* colorloss recovery + YCoCg shift */
BYTE* bmpdata = context->BitmapData;
for (y = 0; y < context->height; y++)
{
const BYTE* yplane;
const BYTE* coplane;
const BYTE* cgplane;
const BYTE* aplane = context->priv->PlaneBuffers[3] + y * context->width; /* A */
if (context->ChromaSubsamplingLevel)
{
yplane = context->priv->PlaneBuffers[0] + y * rw; /* Y */
coplane = context->priv->PlaneBuffers[1] + (y >> 1) * (rw >>
1); /* Co, supersampled */
cgplane = context->priv->PlaneBuffers[2] + (y >> 1) * (rw >>
1); /* Cg, supersampled */
}
else
{
yplane = context->priv->PlaneBuffers[0] + y * context->width; /* Y */
coplane = context->priv->PlaneBuffers[1] + y * context->width; /* Co */
cgplane = context->priv->PlaneBuffers[2] + y * context->width; /* Cg */
}
for (x = 0; x < context->width; x++)
{
INT16 y_val = (INT16) * yplane;
INT16 co_val = (INT16)(INT8)(*coplane << shift);
INT16 cg_val = (INT16)(INT8)(*cgplane << shift);
INT16 r_val = y_val + co_val - cg_val;
INT16 g_val = y_val + cg_val;
INT16 b_val = y_val - co_val - cg_val;
*bmpdata++ = MINMAX(b_val, 0, 0xFF);
*bmpdata++ = MINMAX(g_val, 0, 0xFF);
*bmpdata++ = MINMAX(r_val, 0, 0xFF);
*bmpdata++ = *aplane;
yplane++;
coplane += (context->ChromaSubsamplingLevel ? x % 2 : 1);
cgplane += (context->ChromaSubsamplingLevel ? x % 2 : 1);
aplane++;
}
}
}
static void nsc_rle_decode(BYTE* in, BYTE* out, UINT32 originalSize)
{
UINT32 len;
UINT32 left;
BYTE value;
left = originalSize;
while (left > 4)
{
value = *in++;
if (left == 5)
{
*out++ = value;
left--;
}
else if (value == *in)
{
in++;
if (*in < 0xFF)
{
len = (UINT32) * in++;
len += 2;
}
else
{
in++;
len = *((UINT32*) in);
in += 4;
}
FillMemory(out, len, value);
out += len;
left -= len;
}
else
{
*out++ = value;
left--;
}
}
*((UINT32*)out) = *((UINT32*)in);
}
static void nsc_rle_decompress_data(NSC_CONTEXT* context)
{
UINT16 i;
BYTE* rle;
UINT32 planeSize;
UINT32 originalSize;
rle = context->Planes;
for (i = 0; i < 4; i++)
{
originalSize = context->OrgByteCount[i];
planeSize = context->PlaneByteCount[i];
if (planeSize == 0)
FillMemory(context->priv->PlaneBuffers[i], originalSize, 0xFF);
else if (planeSize < originalSize)
nsc_rle_decode(rle, context->priv->PlaneBuffers[i], originalSize);
else
CopyMemory(context->priv->PlaneBuffers[i], rle, originalSize);
rle += planeSize;
}
}
static BOOL nsc_stream_initialize(NSC_CONTEXT* context, wStream* s)
{
int i;
if (Stream_GetRemainingLength(s) < 20)
return FALSE;
for (i = 0; i < 4; i++)
Stream_Read_UINT32(s, context->PlaneByteCount[i]);
Stream_Read_UINT8(s, context->ColorLossLevel); /* ColorLossLevel (1 byte) */
Stream_Read_UINT8(s,
context->ChromaSubsamplingLevel); /* ChromaSubsamplingLevel (1 byte) */
Stream_Seek(s, 2); /* Reserved (2 bytes) */
context->Planes = Stream_Pointer(s);
return TRUE;
}
static BOOL nsc_context_initialize(NSC_CONTEXT* context, wStream* s)
{
int i;
UINT32 length;
UINT32 tempWidth;
UINT32 tempHeight;
if (!nsc_stream_initialize(context, s))
return FALSE;
length = context->width * context->height * 4;
if (!context->BitmapData)
{
context->BitmapData = calloc(1, length + 16);
if (!context->BitmapData)
return FALSE;
context->BitmapDataLength = length;
}
else if (length > context->BitmapDataLength)
{
void* tmp;
tmp = realloc(context->BitmapData, length + 16);
if (!tmp)
return FALSE;
context->BitmapData = tmp;
context->BitmapDataLength = length;
}
tempWidth = ROUND_UP_TO(context->width, 8);
tempHeight = ROUND_UP_TO(context->height, 2);
/* The maximum length a decoded plane can reach in all cases */
length = tempWidth * tempHeight;
if (length > context->priv->PlaneBuffersLength)
{
for (i = 0; i < 4; i++)
{
void* tmp = (BYTE*) realloc(context->priv->PlaneBuffers[i], length);
if (!tmp)
return FALSE;
context->priv->PlaneBuffers[i] = tmp;
}
context->priv->PlaneBuffersLength = length;
}
for (i = 0; i < 4; i++)
{
context->OrgByteCount[i] = context->width * context->height;
}
if (context->ChromaSubsamplingLevel)
{
context->OrgByteCount[0] = tempWidth * context->height;
context->OrgByteCount[1] = (tempWidth >> 1) * (tempHeight >> 1);
context->OrgByteCount[2] = context->OrgByteCount[1];
}
return TRUE;
}
static void nsc_profiler_print(NSC_CONTEXT_PRIV* priv)
{
PROFILER_PRINT_HEADER
PROFILER_PRINT(priv->prof_nsc_rle_decompress_data)
PROFILER_PRINT(priv->prof_nsc_decode)
PROFILER_PRINT(priv->prof_nsc_rle_compress_data)
PROFILER_PRINT(priv->prof_nsc_encode)
PROFILER_PRINT_FOOTER
}
BOOL nsc_context_reset(NSC_CONTEXT* context, UINT32 width, UINT32 height)
{
if (!context)
return FALSE;
context->width = width;
context->height = height;
return TRUE;
}
NSC_CONTEXT* nsc_context_new(void)
{
NSC_CONTEXT* context;
context = (NSC_CONTEXT*) calloc(1, sizeof(NSC_CONTEXT));
if (!context)
return NULL;
context->priv = (NSC_CONTEXT_PRIV*) calloc(1, sizeof(NSC_CONTEXT_PRIV));
if (!context->priv)
goto error;
context->priv->log = WLog_Get("com.freerdp.codec.nsc");
WLog_OpenAppender(context->priv->log);
context->BitmapData = NULL;
context->decode = nsc_decode;
context->encode = nsc_encode;
context->priv->PlanePool = BufferPool_New(TRUE, 0, 16);
if (!context->priv->PlanePool)
goto error;
PROFILER_CREATE(context->priv->prof_nsc_rle_decompress_data,
"nsc_rle_decompress_data")
PROFILER_CREATE(context->priv->prof_nsc_decode, "nsc_decode")
PROFILER_CREATE(context->priv->prof_nsc_rle_compress_data,
"nsc_rle_compress_data")
PROFILER_CREATE(context->priv->prof_nsc_encode, "nsc_encode")
/* Default encoding parameters */
context->ColorLossLevel = 3;
context->ChromaSubsamplingLevel = 1;
/* init optimized methods */
NSC_INIT_SIMD(context);
return context;
error:
nsc_context_free(context);
return NULL;
}
void nsc_context_free(NSC_CONTEXT* context)
{
size_t i;
if (!context)
return;
if (context->priv)
{
for (i = 0; i < 4; i++)
free(context->priv->PlaneBuffers[i]);
BufferPool_Free(context->priv->PlanePool);
nsc_profiler_print(context->priv);
PROFILER_FREE(context->priv->prof_nsc_rle_decompress_data)
PROFILER_FREE(context->priv->prof_nsc_decode)
PROFILER_FREE(context->priv->prof_nsc_rle_compress_data)
PROFILER_FREE(context->priv->prof_nsc_encode)
free(context->priv);
}
free(context->BitmapData);
free(context);
}
BOOL nsc_context_set_pixel_format(NSC_CONTEXT* context, UINT32 pixel_format)
{
if (!context)
return FALSE;
context->format = pixel_format;
return TRUE;
}
BOOL nsc_process_message(NSC_CONTEXT* context, UINT16 bpp,
UINT32 width, UINT32 height,
const BYTE* data, UINT32 length,
BYTE* pDstData, UINT32 DstFormat,
UINT32 nDstStride,
UINT32 nXDst, UINT32 nYDst, UINT32 nWidth,
UINT32 nHeight, UINT32 flip)
{
wStream* s;
BOOL ret;
s = Stream_New((BYTE*)data, length);
if (!s)
return FALSE;
if (nDstStride == 0)
nDstStride = nWidth * GetBytesPerPixel(DstFormat);
switch (bpp)
{
case 32:
context->format = PIXEL_FORMAT_BGRA32;
break;
case 24:
context->format = PIXEL_FORMAT_BGR24;
break;
case 16:
context->format = PIXEL_FORMAT_BGR16;
break;
case 8:
context->format = PIXEL_FORMAT_RGB8;
break;
case 4:
context->format = PIXEL_FORMAT_A4;
break;
default:
Stream_Free(s, TRUE);
return FALSE;
}
context->width = width;
context->height = height;
ret = nsc_context_initialize(context, s);
Stream_Free(s, FALSE);
if (!ret)
return FALSE;
/* RLE decode */
PROFILER_ENTER(context->priv->prof_nsc_rle_decompress_data)
nsc_rle_decompress_data(context);
PROFILER_EXIT(context->priv->prof_nsc_rle_decompress_data)
/* Colorloss recover, Chroma supersample and AYCoCg to ARGB Conversion in one step */
PROFILER_ENTER(context->priv->prof_nsc_decode)
context->decode(context);
PROFILER_EXIT(context->priv->prof_nsc_decode)
if (!freerdp_image_copy(pDstData, DstFormat, nDstStride, nXDst, nYDst,
width, height, context->BitmapData,
PIXEL_FORMAT_BGRA32, 0, 0, 0, NULL, flip))
return FALSE;
return TRUE;
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_674_1 |
crossvul-cpp_data_good_3301_0 | /* wallpaper.c
Copyright (C) 1999-2003 Tom Gilbert.
Copyright (C) 2010-2011 Daniel Friesel.
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 of the Software and its documentation and acknowledgment shall be
given in the documentation and software packages that this Software was
used.
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 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 "feh.h"
#include "filelist.h"
#include "options.h"
#include "wallpaper.h"
#include <limits.h>
#include <sys/stat.h>
Window ipc_win = None;
Window my_ipc_win = None;
Atom ipc_atom = None;
static unsigned char timeout = 0;
/*
* This is a boolean indicating
* That while we seem to see E16 IPC
* it's actually E17 faking it
* -- richlowe 2005-06-22
*/
static char e17_fake_ipc = 0;
void feh_wm_set_bg_filelist(unsigned char bgmode)
{
if (filelist_len == 0)
eprintf("No files specified for background setting");
switch (bgmode) {
case BG_MODE_TILE:
feh_wm_set_bg(NULL, NULL, 0, 0, 0, 0, 1);
break;
case BG_MODE_SCALE:
feh_wm_set_bg(NULL, NULL, 0, 1, 0, 0, 1);
break;
case BG_MODE_FILL:
feh_wm_set_bg(NULL, NULL, 0, 0, 1, 0, 1);
break;
case BG_MODE_MAX:
feh_wm_set_bg(NULL, NULL, 0, 0, 2, 0, 1);
break;
default:
feh_wm_set_bg(NULL, NULL, 1, 0, 0, 0, 1);
break;
}
}
static void feh_wm_load_next(Imlib_Image *im)
{
static gib_list *wpfile = NULL;
if (wpfile == NULL)
wpfile = filelist;
if (feh_load_image(im, FEH_FILE(wpfile->data)) == 0)
eprintf("Unable to load image %s", FEH_FILE(wpfile->data)->filename);
if (wpfile->next)
wpfile = wpfile->next;
return;
}
static void feh_wm_set_bg_scaled(Pixmap pmap, Imlib_Image im, int use_filelist,
int x, int y, int w, int h)
{
if (use_filelist)
feh_wm_load_next(&im);
gib_imlib_render_image_on_drawable_at_size(pmap, im, x, y, w, h,
1, 0, !opt.force_aliasing);
if (use_filelist)
gib_imlib_free_image_and_decache(im);
return;
}
static void feh_wm_set_bg_centered(Pixmap pmap, Imlib_Image im, int use_filelist,
int x, int y, int w, int h)
{
int offset_x, offset_y;
if (use_filelist)
feh_wm_load_next(&im);
if(opt.geom_flags & XValue)
if(opt.geom_flags & XNegative)
offset_x = (w - gib_imlib_image_get_width(im)) + opt.geom_x;
else
offset_x = opt.geom_x;
else
offset_x = (w - gib_imlib_image_get_width(im)) >> 1;
if(opt.geom_flags & YValue)
if(opt.geom_flags & YNegative)
offset_y = (h - gib_imlib_image_get_height(im)) + opt.geom_y;
else
offset_y = opt.geom_y;
else
offset_y = (h - gib_imlib_image_get_height(im)) >> 1;
gib_imlib_render_image_part_on_drawable_at_size(pmap, im,
((offset_x < 0) ? -offset_x : 0),
((offset_y < 0) ? -offset_y : 0),
w,
h,
x + ((offset_x > 0) ? offset_x : 0),
y + ((offset_y > 0) ? offset_y : 0),
w,
h,
1, 0, 0);
if (use_filelist)
gib_imlib_free_image_and_decache(im);
return;
}
static void feh_wm_set_bg_filled(Pixmap pmap, Imlib_Image im, int use_filelist,
int x, int y, int w, int h)
{
int img_w, img_h, cut_x;
int render_w, render_h, render_x, render_y;
if (use_filelist)
feh_wm_load_next(&im);
img_w = gib_imlib_image_get_width(im);
img_h = gib_imlib_image_get_height(im);
cut_x = (((img_w * h) > (img_h * w)) ? 1 : 0);
render_w = ( cut_x ? ((img_h * w) / h) : img_w);
render_h = ( !cut_x ? ((img_w * h) / w) : img_h);
render_x = ( cut_x ? ((img_w - render_w) >> 1) : 0);
render_y = ( !cut_x ? ((img_h - render_h) >> 1) : 0);
gib_imlib_render_image_part_on_drawable_at_size(pmap, im,
render_x, render_y,
render_w, render_h,
x, y, w, h,
1, 0, !opt.force_aliasing);
if (use_filelist)
gib_imlib_free_image_and_decache(im);
return;
}
static void feh_wm_set_bg_maxed(Pixmap pmap, Imlib_Image im, int use_filelist,
int x, int y, int w, int h)
{
int img_w, img_h, border_x;
int render_w, render_h, render_x, render_y;
int margin_x, margin_y;
if (use_filelist)
feh_wm_load_next(&im);
img_w = gib_imlib_image_get_width(im);
img_h = gib_imlib_image_get_height(im);
border_x = (((img_w * h) > (img_h * w)) ? 0 : 1);
render_w = ( border_x ? ((img_w * h) / img_h) : w);
render_h = ( !border_x ? ((img_h * w) / img_w) : h);
if(opt.geom_flags & XValue)
if(opt.geom_flags & XNegative)
margin_x = (w - render_w) + opt.geom_x;
else
margin_x = opt.geom_x;
else
margin_x = (w - render_w) >> 1;
if(opt.geom_flags & YValue)
if(opt.geom_flags & YNegative)
margin_y = (h - render_h) + opt.geom_y;
else
margin_y = opt.geom_y;
else
margin_y = (h - render_h) >> 1;
render_x = x + ( border_x ? margin_x : 0);
render_y = y + ( !border_x ? margin_y : 0);
gib_imlib_render_image_on_drawable_at_size(pmap, im,
render_x, render_y,
render_w, render_h,
1, 0, !opt.force_aliasing);
if (use_filelist)
gib_imlib_free_image_and_decache(im);
return;
}
void feh_wm_set_bg(char *fil, Imlib_Image im, int centered, int scaled,
int filled, int desktop, int use_filelist)
{
XGCValues gcvalues;
XGCValues gcval;
GC gc;
char bgname[20];
int num = (int) rand();
char bgfil[4096];
char sendbuf[4096];
/*
* TODO this re-implements mkstemp (badly). However, it is only needed
* for non-file images and enlightenment. Might be easier to just remove
* it.
*/
snprintf(bgname, sizeof(bgname), "FEHBG_%d", num);
if (!fil && im) {
if (getenv("HOME") == NULL) {
weprintf("Cannot save wallpaper to temporary file: You have no HOME");
return;
}
snprintf(bgfil, sizeof(bgfil), "%s/.%s.png", getenv("HOME"), bgname);
imlib_context_set_image(im);
imlib_image_set_format("png");
gib_imlib_save_image(im, bgfil);
D(("bg saved as %s\n", bgfil));
fil = bgfil;
}
if (feh_wm_get_wm_is_e() && (enl_ipc_get_win() != None)) {
if (use_filelist) {
feh_wm_load_next(&im);
fil = FEH_FILE(filelist->data)->filename;
}
snprintf(sendbuf, sizeof(sendbuf), "background %s bg.file %s", bgname, fil);
enl_ipc_send(sendbuf);
if (scaled) {
snprintf(sendbuf, sizeof(sendbuf), "background %s bg.solid 0 0 0", bgname);
enl_ipc_send(sendbuf);
snprintf(sendbuf, sizeof(sendbuf), "background %s bg.tile 0", bgname);
enl_ipc_send(sendbuf);
snprintf(sendbuf, sizeof(sendbuf), "background %s bg.xjust 512", bgname);
enl_ipc_send(sendbuf);
snprintf(sendbuf, sizeof(sendbuf), "background %s bg.yjust 512", bgname);
enl_ipc_send(sendbuf);
snprintf(sendbuf, sizeof(sendbuf), "background %s bg.xperc 1024", bgname);
enl_ipc_send(sendbuf);
snprintf(sendbuf, sizeof(sendbuf), "background %s bg.yperc 1024", bgname);
enl_ipc_send(sendbuf);
} else if (centered) {
snprintf(sendbuf, sizeof(sendbuf), "background %s bg.solid 0 0 0", bgname);
enl_ipc_send(sendbuf);
snprintf(sendbuf, sizeof(sendbuf), "background %s bg.tile 0", bgname);
enl_ipc_send(sendbuf);
snprintf(sendbuf, sizeof(sendbuf), "background %s bg.xjust 512", bgname);
enl_ipc_send(sendbuf);
snprintf(sendbuf, sizeof(sendbuf), "background %s bg.yjust 512", bgname);
enl_ipc_send(sendbuf);
} else {
snprintf(sendbuf, sizeof(sendbuf), "background %s bg.tile 1", bgname);
enl_ipc_send(sendbuf);
}
snprintf(sendbuf, sizeof(sendbuf), "use_bg %s %d", bgname, desktop);
enl_ipc_send(sendbuf);
enl_ipc_sync();
} else {
Atom prop_root, prop_esetroot, type;
int format, i;
unsigned long length, after;
unsigned char *data_root = NULL, *data_esetroot = NULL;
Pixmap pmap_d1, pmap_d2;
gib_list *l;
/* string for sticking in ~/.fehbg */
char *fehbg = NULL;
char fehbg_args[512];
fehbg_args[0] = '\0';
char *home;
char filbuf[4096];
char *bgfill = NULL;
bgfill = opt.image_bg == IMAGE_BG_WHITE ? "--image-bg white" : "--image-bg black" ;
#ifdef HAVE_LIBXINERAMA
if (opt.xinerama) {
if (opt.xinerama_index >= 0) {
snprintf(fehbg_args, sizeof(fehbg_args),
"--xinerama-index %d", opt.xinerama_index);
}
}
else
snprintf(fehbg_args, sizeof(fehbg_args), "--no-xinerama");
#endif /* HAVE_LIBXINERAMA */
/* local display to set closedownmode on */
Display *disp2;
Window root2;
int depth2;
int in, out, w, h;
D(("Falling back to XSetRootWindowPixmap\n"));
/* Put the filename in filbuf between ' and escape ' in the filename */
out = 0;
if (fil && !use_filelist) {
filbuf[out++] = '\'';
fil = feh_absolute_path(fil);
for (in = 0; fil[in] && out < 4092; in++) {
if (fil[in] == '\'')
filbuf[out++] = '\\';
filbuf[out++] = fil[in];
}
filbuf[out++] = '\'';
free(fil);
} else {
for (l = filelist; l && out < 4092; l = l->next) {
filbuf[out++] = '\'';
fil = feh_absolute_path(FEH_FILE(l->data)->filename);
for (in = 0; fil[in] && out < 4092; in++) {
if (fil[in] == '\'')
filbuf[out++] = '\\';
filbuf[out++] = fil[in];
}
filbuf[out++] = '\'';
filbuf[out++] = ' ';
free(fil);
}
}
filbuf[out++] = 0;
if (scaled) {
pmap_d1 = XCreatePixmap(disp, root, scr->width, scr->height, depth);
#ifdef HAVE_LIBXINERAMA
if (opt.xinerama_index >= 0) {
if (opt.image_bg == IMAGE_BG_WHITE)
gcval.foreground = WhitePixel(disp, DefaultScreen(disp));
else
gcval.foreground = BlackPixel(disp, DefaultScreen(disp));
gc = XCreateGC(disp, root, GCForeground, &gcval);
XFillRectangle(disp, pmap_d1, gc, 0, 0, scr->width, scr->height);
XFreeGC(disp, gc);
}
if (opt.xinerama && xinerama_screens) {
for (i = 0; i < num_xinerama_screens; i++) {
if (opt.xinerama_index < 0 || opt.xinerama_index == i) {
feh_wm_set_bg_scaled(pmap_d1, im, use_filelist,
xinerama_screens[i].x_org, xinerama_screens[i].y_org,
xinerama_screens[i].width, xinerama_screens[i].height);
}
}
}
else
#endif /* HAVE_LIBXINERAMA */
feh_wm_set_bg_scaled(pmap_d1, im, use_filelist,
0, 0, scr->width, scr->height);
fehbg = estrjoin(" ", "feh", fehbg_args, "--bg-scale", filbuf, NULL);
} else if (centered) {
D(("centering\n"));
pmap_d1 = XCreatePixmap(disp, root, scr->width, scr->height, depth);
if (opt.image_bg == IMAGE_BG_WHITE)
gcval.foreground = WhitePixel(disp, DefaultScreen(disp));
else
gcval.foreground = BlackPixel(disp, DefaultScreen(disp));
gc = XCreateGC(disp, root, GCForeground, &gcval);
XFillRectangle(disp, pmap_d1, gc, 0, 0, scr->width, scr->height);
#ifdef HAVE_LIBXINERAMA
if (opt.xinerama && xinerama_screens) {
for (i = 0; i < num_xinerama_screens; i++) {
if (opt.xinerama_index < 0 || opt.xinerama_index == i) {
feh_wm_set_bg_centered(pmap_d1, im, use_filelist,
xinerama_screens[i].x_org, xinerama_screens[i].y_org,
xinerama_screens[i].width, xinerama_screens[i].height);
}
}
}
else
#endif /* HAVE_LIBXINERAMA */
feh_wm_set_bg_centered(pmap_d1, im, use_filelist,
0, 0, scr->width, scr->height);
XFreeGC(disp, gc);
fehbg = estrjoin(" ", "feh", fehbg_args, bgfill, "--bg-center", filbuf, NULL);
} else if (filled == 1) {
pmap_d1 = XCreatePixmap(disp, root, scr->width, scr->height, depth);
#ifdef HAVE_LIBXINERAMA
if (opt.xinerama_index >= 0) {
if (opt.image_bg == IMAGE_BG_WHITE)
gcval.foreground = WhitePixel(disp, DefaultScreen(disp));
else
gcval.foreground = BlackPixel(disp, DefaultScreen(disp));
gc = XCreateGC(disp, root, GCForeground, &gcval);
XFillRectangle(disp, pmap_d1, gc, 0, 0, scr->width, scr->height);
XFreeGC(disp, gc);
}
if (opt.xinerama && xinerama_screens) {
for (i = 0; i < num_xinerama_screens; i++) {
if (opt.xinerama_index < 0 || opt.xinerama_index == i) {
feh_wm_set_bg_filled(pmap_d1, im, use_filelist,
xinerama_screens[i].x_org, xinerama_screens[i].y_org,
xinerama_screens[i].width, xinerama_screens[i].height);
}
}
}
else
#endif /* HAVE_LIBXINERAMA */
feh_wm_set_bg_filled(pmap_d1, im, use_filelist
, 0, 0, scr->width, scr->height);
fehbg = estrjoin(" ", "feh", fehbg_args, "--bg-fill", filbuf, NULL);
} else if (filled == 2) {
pmap_d1 = XCreatePixmap(disp, root, scr->width, scr->height, depth);
if (opt.image_bg == IMAGE_BG_WHITE)
gcval.foreground = WhitePixel(disp, DefaultScreen(disp));
else
gcval.foreground = BlackPixel(disp, DefaultScreen(disp));
gc = XCreateGC(disp, root, GCForeground, &gcval);
XFillRectangle(disp, pmap_d1, gc, 0, 0, scr->width, scr->height);
#ifdef HAVE_LIBXINERAMA
if (opt.xinerama && xinerama_screens) {
for (i = 0; i < num_xinerama_screens; i++) {
if (opt.xinerama_index < 0 || opt.xinerama_index == i) {
feh_wm_set_bg_maxed(pmap_d1, im, use_filelist,
xinerama_screens[i].x_org, xinerama_screens[i].y_org,
xinerama_screens[i].width, xinerama_screens[i].height);
}
}
}
else
#endif /* HAVE_LIBXINERAMA */
feh_wm_set_bg_maxed(pmap_d1, im, use_filelist,
0, 0, scr->width, scr->height);
XFreeGC(disp, gc);
fehbg = estrjoin(" ", "feh", fehbg_args, bgfill, "--bg-max", filbuf, NULL);
} else {
if (use_filelist)
feh_wm_load_next(&im);
w = gib_imlib_image_get_width(im);
h = gib_imlib_image_get_height(im);
pmap_d1 = XCreatePixmap(disp, root, w, h, depth);
gib_imlib_render_image_on_drawable(pmap_d1, im, 0, 0, 1, 0, 0);
fehbg = estrjoin(" ", "feh --bg-tile", filbuf, NULL);
}
if (fehbg && !opt.no_fehbg) {
home = getenv("HOME");
if (home) {
FILE *fp;
char *path;
struct stat s;
path = estrjoin("/", home, ".fehbg", NULL);
if ((fp = fopen(path, "w")) == NULL) {
weprintf("Can't write to %s", path);
} else {
fprintf(fp, "#!/bin/sh\n%s\n", fehbg);
fclose(fp);
stat(path, &s);
if (chmod(path, s.st_mode | S_IXUSR | S_IXGRP) != 0) {
weprintf("Can't set %s as executable", path);
}
}
free(path);
}
}
free(fehbg);
/* create new display, copy pixmap to new display */
disp2 = XOpenDisplay(NULL);
if (!disp2)
eprintf("Can't reopen X display.");
root2 = RootWindow(disp2, DefaultScreen(disp2));
depth2 = DefaultDepth(disp2, DefaultScreen(disp2));
XSync(disp, False);
pmap_d2 = XCreatePixmap(disp2, root2, scr->width, scr->height, depth2);
gcvalues.fill_style = FillTiled;
gcvalues.tile = pmap_d1;
gc = XCreateGC(disp2, pmap_d2, GCFillStyle | GCTile, &gcvalues);
XFillRectangle(disp2, pmap_d2, gc, 0, 0, scr->width, scr->height);
XFreeGC(disp2, gc);
XSync(disp2, False);
XSync(disp, False);
XFreePixmap(disp, pmap_d1);
prop_root = XInternAtom(disp2, "_XROOTPMAP_ID", True);
prop_esetroot = XInternAtom(disp2, "ESETROOT_PMAP_ID", True);
if (prop_root != None && prop_esetroot != None) {
XGetWindowProperty(disp2, root2, prop_root, 0L, 1L,
False, AnyPropertyType, &type, &format, &length, &after, &data_root);
if (type == XA_PIXMAP) {
XGetWindowProperty(disp2, root2,
prop_esetroot, 0L, 1L,
False, AnyPropertyType,
&type, &format, &length, &after, &data_esetroot);
if (data_root && data_esetroot) {
if (type == XA_PIXMAP && *((Pixmap *) data_root) == *((Pixmap *) data_esetroot)) {
XKillClient(disp2, *((Pixmap *)
data_root));
}
}
}
}
if (data_root)
XFree(data_root);
if (data_esetroot)
XFree(data_esetroot);
/* This will locate the property, creating it if it doesn't exist */
prop_root = XInternAtom(disp2, "_XROOTPMAP_ID", False);
prop_esetroot = XInternAtom(disp2, "ESETROOT_PMAP_ID", False);
if (prop_root == None || prop_esetroot == None)
eprintf("creation of pixmap property failed.");
XChangeProperty(disp2, root2, prop_root, XA_PIXMAP, 32, PropModeReplace, (unsigned char *) &pmap_d2, 1);
XChangeProperty(disp2, root2, prop_esetroot, XA_PIXMAP, 32,
PropModeReplace, (unsigned char *) &pmap_d2, 1);
XSetWindowBackgroundPixmap(disp2, root2, pmap_d2);
XClearWindow(disp2, root2);
XFlush(disp2);
XSetCloseDownMode(disp2, RetainPermanent);
XCloseDisplay(disp2);
}
return;
}
signed char feh_wm_get_wm_is_e(void)
{
static signed char e = -1;
/* check if E is actually running */
if (e == -1) {
/* XXX: This only covers E17 prior to 6/22/05 */
if ((XInternAtom(disp, "ENLIGHTENMENT_COMMS", True) != None)
&& (XInternAtom(disp, "ENLIGHTENMENT_VERSION", True) != None)) {
D(("Enlightenment detected.\n"));
e = 1;
} else {
D(("Enlightenment not detected.\n"));
e = 0;
}
}
return(e);
}
int feh_wm_get_num_desks(void)
{
char *buf, *ptr;
int desks;
if (!feh_wm_get_wm_is_e())
return(-1);
buf = enl_send_and_wait("num_desks ?");
if (buf == IPC_FAKE) /* Fake E17 IPC */
return(-1);
D(("Got from E IPC: %s\n", buf));
ptr = buf;
while (ptr && !isdigit(*ptr))
ptr++;
desks = atoi(ptr);
return(desks);
}
Window enl_ipc_get_win(void)
{
unsigned char *str = NULL;
Atom prop, prop2, ever;
unsigned long num, after;
int format;
Window dummy_win;
int dummy_int;
unsigned int dummy_uint;
D(("Searching for IPC window.\n"));
/*
* Shortcircuit this entire func
* if we already know it's an e17 fake
*/
if (e17_fake_ipc)
return(ipc_win);
prop = XInternAtom(disp, "ENLIGHTENMENT_COMMS", True);
if (prop == None) {
D(("Enlightenment is not running.\n"));
return(None);
} else {
/* XXX: This will only work with E17 prior to 6/22/2005 */
ever = XInternAtom(disp, "ENLIGHTENMENT_VERSION", True);
if (ever == None) {
/* This is an E without ENLIGHTENMENT_VERSION */
D(("E16 IPC Protocol not supported"));
return(None);
}
}
XGetWindowProperty(disp, root, prop, 0, 14, False, AnyPropertyType, &prop2, &format, &num, &after, &str);
if (str) {
sscanf((char *) str, "%*s %x", (unsigned int *) &ipc_win);
XFree(str);
}
if (ipc_win != None) {
if (!XGetGeometry
(disp, ipc_win, &dummy_win, &dummy_int, &dummy_int,
&dummy_uint, &dummy_uint, &dummy_uint, &dummy_uint)) {
D((" -> IPC Window property is valid, but the window doesn't exist.\n"));
ipc_win = None;
}
str = NULL;
if (ipc_win != None) {
XGetWindowProperty(disp, ipc_win, prop, 0, 14,
False, AnyPropertyType, &prop2, &format, &num, &after, &str);
if (str) {
XFree(str);
} else {
D((" -> IPC Window lacks the proper atom. I can't talk to fake IPC windows....\n"));
ipc_win = None;
}
}
}
if (ipc_win != None) {
XGetWindowProperty(disp, ipc_win, ever, 0, 14, False,
AnyPropertyType, &prop2, &format, &num, &after, &str);
if (str) {
/*
* This is E17's way of telling us it's only pretending
* as a workaround for a bug related to the way java handles
* Window Managers.
* (Only valid after date of this comment)
* -- richlowe 2005-06-22
*/
XFree(str);
D((" -> Found a fake E17 IPC window, ignoring"));
ipc_win = None;
e17_fake_ipc = 1;
return(ipc_win);
}
D((" -> IPC Window found and verified as 0x%08x. Registering feh as an IPC client.\n", (int) ipc_win));
XSelectInput(disp, ipc_win, StructureNotifyMask | SubstructureNotifyMask);
enl_ipc_send("set clientname " PACKAGE);
enl_ipc_send("set version " VERSION);
enl_ipc_send("set email tom@linuxbrit.co.uk");
enl_ipc_send("set web http://www.linuxbrit.co.uk");
enl_ipc_send("set info Feh - be pr0n or be dead");
}
if (my_ipc_win == None) {
my_ipc_win = XCreateSimpleWindow(disp, root, -2, -2, 1, 1, 0, 0, 0);
}
return(ipc_win);
}
void enl_ipc_send(char *str)
{
static char *last_msg = NULL;
char buff[21];
register unsigned short i;
register unsigned char j;
unsigned short len;
XEvent ev;
if (str == NULL) {
if (last_msg == NULL)
eprintf("eeek");
str = last_msg;
D(("Resending last message \"%s\" to Enlightenment.\n", str));
} else {
if (last_msg != NULL) {
free(last_msg);
}
last_msg = estrdup(str);
D(("Sending \"%s\" to Enlightenment.\n", str));
}
if (ipc_win == None) {
if ((ipc_win = enl_ipc_get_win()) == None) {
D(("Hrm. Enlightenment doesn't seem to be running. No IPC window, no IPC.\n"));
return;
}
}
len = strlen(str);
ipc_atom = XInternAtom(disp, "ENL_MSG", False);
if (ipc_atom == None) {
D(("IPC error: Unable to find/create ENL_MSG atom.\n"));
return;
}
for (; XCheckTypedWindowEvent(disp, my_ipc_win, ClientMessage, &ev);); /* Discard any out-of-sync messages */
ev.xclient.type = ClientMessage;
ev.xclient.serial = 0;
ev.xclient.send_event = True;
ev.xclient.window = ipc_win;
ev.xclient.message_type = ipc_atom;
ev.xclient.format = 8;
for (i = 0; i < len + 1; i += 12) {
sprintf(buff, "%8x", (int) my_ipc_win);
for (j = 0; j < 12; j++) {
buff[8 + j] = str[i + j];
if (!str[i + j]) {
break;
}
}
buff[20] = 0;
for (j = 0; j < 20; j++) {
ev.xclient.data.b[j] = buff[j];
}
XSendEvent(disp, ipc_win, False, 0, (XEvent *) & ev);
}
return;
}
static sighandler_t *enl_ipc_timeout(int sig)
{
timeout = 1;
return((sighandler_t *) sig);
}
char *enl_wait_for_reply(void)
{
XEvent ev;
static char msg_buffer[20];
register unsigned char i;
alarm(2);
for (; !XCheckTypedWindowEvent(disp, my_ipc_win, ClientMessage, &ev)
&& !timeout;);
alarm(0);
if (ev.xany.type != ClientMessage) {
return(IPC_TIMEOUT);
}
for (i = 0; i < 20; i++) {
msg_buffer[i] = ev.xclient.data.b[i];
}
return(msg_buffer + 8);
}
char *enl_ipc_get(const char *msg_data)
{
static char *message = NULL;
static size_t len = 0;
char buff[13], *ret_msg = NULL;
register unsigned char i;
unsigned char blen;
if (msg_data == IPC_TIMEOUT) {
return(IPC_TIMEOUT);
}
for (i = 0; i < 12; i++) {
buff[i] = msg_data[i];
}
buff[12] = 0;
blen = strlen(buff);
if (message != NULL) {
len += blen;
message = (char *) erealloc(message, len + 1);
strcat(message, buff);
} else {
len = blen;
message = (char *) emalloc(len + 1);
strcpy(message, buff);
}
if (blen < 12) {
ret_msg = message;
message = NULL;
D(("Received complete reply: \"%s\"\n", ret_msg));
}
return(ret_msg);
}
char *enl_send_and_wait(char *msg)
{
char *reply = IPC_TIMEOUT;
sighandler_t old_alrm;
/*
* Shortcut this func and return IPC_FAKE
* If the IPC Window is the E17 fake
*/
if (e17_fake_ipc)
return IPC_FAKE;
if (ipc_win == None) {
/* The IPC window is missing. Wait for it to return or feh to be killed. */
/* Only called once in the E17 case */
for (; enl_ipc_get_win() == None;) {
if (e17_fake_ipc)
return IPC_FAKE;
else
sleep(1);
}
}
old_alrm = (sighandler_t) signal(SIGALRM, (sighandler_t) enl_ipc_timeout);
for (; reply == IPC_TIMEOUT;) {
timeout = 0;
enl_ipc_send(msg);
for (; !(reply = enl_ipc_get(enl_wait_for_reply())););
if (reply == IPC_TIMEOUT) {
/* We timed out. The IPC window must be AWOL. Reset and resend message. */
D(("IPC timed out. IPC window has gone. Clearing ipc_win.\n"));
XSelectInput(disp, ipc_win, None);
ipc_win = None;
}
}
signal(SIGALRM, old_alrm);
return(reply);
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_3301_0 |
crossvul-cpp_data_good_5474_4 | /* $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, §_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;
uint16 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, j, bytes_per_sample, bytes_per_pixel, shift_width, result = 1;
int32 bytes_read = 0;
uint16 bps, nstrips, planar, 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, §ions[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-787/c/good_5474_4 |
crossvul-cpp_data_good_205_2 | /*
* ring buffer based function tracer
*
* Copyright (C) 2007-2012 Steven Rostedt <srostedt@redhat.com>
* Copyright (C) 2008 Ingo Molnar <mingo@redhat.com>
*
* Originally taken from the RT patch by:
* Arnaldo Carvalho de Melo <acme@redhat.com>
*
* Based on code from the latency_tracer, that is:
* Copyright (C) 2004-2006 Ingo Molnar
* Copyright (C) 2004 Nadia Yvette Chambers
*/
#include <linux/ring_buffer.h>
#include <generated/utsrelease.h>
#include <linux/stacktrace.h>
#include <linux/writeback.h>
#include <linux/kallsyms.h>
#include <linux/seq_file.h>
#include <linux/notifier.h>
#include <linux/irqflags.h>
#include <linux/debugfs.h>
#include <linux/tracefs.h>
#include <linux/pagemap.h>
#include <linux/hardirq.h>
#include <linux/linkage.h>
#include <linux/uaccess.h>
#include <linux/vmalloc.h>
#include <linux/ftrace.h>
#include <linux/module.h>
#include <linux/percpu.h>
#include <linux/splice.h>
#include <linux/kdebug.h>
#include <linux/string.h>
#include <linux/mount.h>
#include <linux/rwsem.h>
#include <linux/slab.h>
#include <linux/ctype.h>
#include <linux/init.h>
#include <linux/poll.h>
#include <linux/nmi.h>
#include <linux/fs.h>
#include <linux/trace.h>
#include <linux/sched/clock.h>
#include <linux/sched/rt.h>
#include "trace.h"
#include "trace_output.h"
/*
* On boot up, the ring buffer is set to the minimum size, so that
* we do not waste memory on systems that are not using tracing.
*/
bool ring_buffer_expanded;
/*
* We need to change this state when a selftest is running.
* A selftest will lurk into the ring-buffer to count the
* entries inserted during the selftest although some concurrent
* insertions into the ring-buffer such as trace_printk could occurred
* at the same time, giving false positive or negative results.
*/
static bool __read_mostly tracing_selftest_running;
/*
* If a tracer is running, we do not want to run SELFTEST.
*/
bool __read_mostly tracing_selftest_disabled;
/* Pipe tracepoints to printk */
struct trace_iterator *tracepoint_print_iter;
int tracepoint_printk;
static DEFINE_STATIC_KEY_FALSE(tracepoint_printk_key);
/* For tracers that don't implement custom flags */
static struct tracer_opt dummy_tracer_opt[] = {
{ }
};
static int
dummy_set_flag(struct trace_array *tr, u32 old_flags, u32 bit, int set)
{
return 0;
}
/*
* To prevent the comm cache from being overwritten when no
* tracing is active, only save the comm when a trace event
* occurred.
*/
static DEFINE_PER_CPU(bool, trace_taskinfo_save);
/*
* Kill all tracing for good (never come back).
* It is initialized to 1 but will turn to zero if the initialization
* of the tracer is successful. But that is the only place that sets
* this back to zero.
*/
static int tracing_disabled = 1;
cpumask_var_t __read_mostly tracing_buffer_mask;
/*
* ftrace_dump_on_oops - variable to dump ftrace buffer on oops
*
* If there is an oops (or kernel panic) and the ftrace_dump_on_oops
* is set, then ftrace_dump is called. This will output the contents
* of the ftrace buffers to the console. This is very useful for
* capturing traces that lead to crashes and outputing it to a
* serial console.
*
* It is default off, but you can enable it with either specifying
* "ftrace_dump_on_oops" in the kernel command line, or setting
* /proc/sys/kernel/ftrace_dump_on_oops
* Set 1 if you want to dump buffers of all CPUs
* Set 2 if you want to dump the buffer of the CPU that triggered oops
*/
enum ftrace_dump_mode ftrace_dump_on_oops;
/* When set, tracing will stop when a WARN*() is hit */
int __disable_trace_on_warning;
#ifdef CONFIG_TRACE_EVAL_MAP_FILE
/* Map of enums to their values, for "eval_map" file */
struct trace_eval_map_head {
struct module *mod;
unsigned long length;
};
union trace_eval_map_item;
struct trace_eval_map_tail {
/*
* "end" is first and points to NULL as it must be different
* than "mod" or "eval_string"
*/
union trace_eval_map_item *next;
const char *end; /* points to NULL */
};
static DEFINE_MUTEX(trace_eval_mutex);
/*
* The trace_eval_maps are saved in an array with two extra elements,
* one at the beginning, and one at the end. The beginning item contains
* the count of the saved maps (head.length), and the module they
* belong to if not built in (head.mod). The ending item contains a
* pointer to the next array of saved eval_map items.
*/
union trace_eval_map_item {
struct trace_eval_map map;
struct trace_eval_map_head head;
struct trace_eval_map_tail tail;
};
static union trace_eval_map_item *trace_eval_maps;
#endif /* CONFIG_TRACE_EVAL_MAP_FILE */
static int tracing_set_tracer(struct trace_array *tr, const char *buf);
#define MAX_TRACER_SIZE 100
static char bootup_tracer_buf[MAX_TRACER_SIZE] __initdata;
static char *default_bootup_tracer;
static bool allocate_snapshot;
static int __init set_cmdline_ftrace(char *str)
{
strlcpy(bootup_tracer_buf, str, MAX_TRACER_SIZE);
default_bootup_tracer = bootup_tracer_buf;
/* We are using ftrace early, expand it */
ring_buffer_expanded = true;
return 1;
}
__setup("ftrace=", set_cmdline_ftrace);
static int __init set_ftrace_dump_on_oops(char *str)
{
if (*str++ != '=' || !*str) {
ftrace_dump_on_oops = DUMP_ALL;
return 1;
}
if (!strcmp("orig_cpu", str)) {
ftrace_dump_on_oops = DUMP_ORIG;
return 1;
}
return 0;
}
__setup("ftrace_dump_on_oops", set_ftrace_dump_on_oops);
static int __init stop_trace_on_warning(char *str)
{
if ((strcmp(str, "=0") != 0 && strcmp(str, "=off") != 0))
__disable_trace_on_warning = 1;
return 1;
}
__setup("traceoff_on_warning", stop_trace_on_warning);
static int __init boot_alloc_snapshot(char *str)
{
allocate_snapshot = true;
/* We also need the main ring buffer expanded */
ring_buffer_expanded = true;
return 1;
}
__setup("alloc_snapshot", boot_alloc_snapshot);
static char trace_boot_options_buf[MAX_TRACER_SIZE] __initdata;
static int __init set_trace_boot_options(char *str)
{
strlcpy(trace_boot_options_buf, str, MAX_TRACER_SIZE);
return 0;
}
__setup("trace_options=", set_trace_boot_options);
static char trace_boot_clock_buf[MAX_TRACER_SIZE] __initdata;
static char *trace_boot_clock __initdata;
static int __init set_trace_boot_clock(char *str)
{
strlcpy(trace_boot_clock_buf, str, MAX_TRACER_SIZE);
trace_boot_clock = trace_boot_clock_buf;
return 0;
}
__setup("trace_clock=", set_trace_boot_clock);
static int __init set_tracepoint_printk(char *str)
{
if ((strcmp(str, "=0") != 0 && strcmp(str, "=off") != 0))
tracepoint_printk = 1;
return 1;
}
__setup("tp_printk", set_tracepoint_printk);
unsigned long long ns2usecs(u64 nsec)
{
nsec += 500;
do_div(nsec, 1000);
return nsec;
}
/* trace_flags holds trace_options default values */
#define TRACE_DEFAULT_FLAGS \
(FUNCTION_DEFAULT_FLAGS | \
TRACE_ITER_PRINT_PARENT | TRACE_ITER_PRINTK | \
TRACE_ITER_ANNOTATE | TRACE_ITER_CONTEXT_INFO | \
TRACE_ITER_RECORD_CMD | TRACE_ITER_OVERWRITE | \
TRACE_ITER_IRQ_INFO | TRACE_ITER_MARKERS)
/* trace_options that are only supported by global_trace */
#define TOP_LEVEL_TRACE_FLAGS (TRACE_ITER_PRINTK | \
TRACE_ITER_PRINTK_MSGONLY | TRACE_ITER_RECORD_CMD)
/* trace_flags that are default zero for instances */
#define ZEROED_TRACE_FLAGS \
(TRACE_ITER_EVENT_FORK | TRACE_ITER_FUNC_FORK)
/*
* The global_trace is the descriptor that holds the top-level tracing
* buffers for the live tracing.
*/
static struct trace_array global_trace = {
.trace_flags = TRACE_DEFAULT_FLAGS,
};
LIST_HEAD(ftrace_trace_arrays);
int trace_array_get(struct trace_array *this_tr)
{
struct trace_array *tr;
int ret = -ENODEV;
mutex_lock(&trace_types_lock);
list_for_each_entry(tr, &ftrace_trace_arrays, list) {
if (tr == this_tr) {
tr->ref++;
ret = 0;
break;
}
}
mutex_unlock(&trace_types_lock);
return ret;
}
static void __trace_array_put(struct trace_array *this_tr)
{
WARN_ON(!this_tr->ref);
this_tr->ref--;
}
void trace_array_put(struct trace_array *this_tr)
{
mutex_lock(&trace_types_lock);
__trace_array_put(this_tr);
mutex_unlock(&trace_types_lock);
}
int call_filter_check_discard(struct trace_event_call *call, void *rec,
struct ring_buffer *buffer,
struct ring_buffer_event *event)
{
if (unlikely(call->flags & TRACE_EVENT_FL_FILTERED) &&
!filter_match_preds(call->filter, rec)) {
__trace_event_discard_commit(buffer, event);
return 1;
}
return 0;
}
void trace_free_pid_list(struct trace_pid_list *pid_list)
{
vfree(pid_list->pids);
kfree(pid_list);
}
/**
* trace_find_filtered_pid - check if a pid exists in a filtered_pid list
* @filtered_pids: The list of pids to check
* @search_pid: The PID to find in @filtered_pids
*
* Returns true if @search_pid is fonud in @filtered_pids, and false otherwis.
*/
bool
trace_find_filtered_pid(struct trace_pid_list *filtered_pids, pid_t search_pid)
{
/*
* If pid_max changed after filtered_pids was created, we
* by default ignore all pids greater than the previous pid_max.
*/
if (search_pid >= filtered_pids->pid_max)
return false;
return test_bit(search_pid, filtered_pids->pids);
}
/**
* trace_ignore_this_task - should a task be ignored for tracing
* @filtered_pids: The list of pids to check
* @task: The task that should be ignored if not filtered
*
* Checks if @task should be traced or not from @filtered_pids.
* Returns true if @task should *NOT* be traced.
* Returns false if @task should be traced.
*/
bool
trace_ignore_this_task(struct trace_pid_list *filtered_pids, struct task_struct *task)
{
/*
* Return false, because if filtered_pids does not exist,
* all pids are good to trace.
*/
if (!filtered_pids)
return false;
return !trace_find_filtered_pid(filtered_pids, task->pid);
}
/**
* trace_pid_filter_add_remove_task - Add or remove a task from a pid_list
* @pid_list: The list to modify
* @self: The current task for fork or NULL for exit
* @task: The task to add or remove
*
* If adding a task, if @self is defined, the task is only added if @self
* is also included in @pid_list. This happens on fork and tasks should
* only be added when the parent is listed. If @self is NULL, then the
* @task pid will be removed from the list, which would happen on exit
* of a task.
*/
void trace_filter_add_remove_task(struct trace_pid_list *pid_list,
struct task_struct *self,
struct task_struct *task)
{
if (!pid_list)
return;
/* For forks, we only add if the forking task is listed */
if (self) {
if (!trace_find_filtered_pid(pid_list, self->pid))
return;
}
/* Sorry, but we don't support pid_max changing after setting */
if (task->pid >= pid_list->pid_max)
return;
/* "self" is set for forks, and NULL for exits */
if (self)
set_bit(task->pid, pid_list->pids);
else
clear_bit(task->pid, pid_list->pids);
}
/**
* trace_pid_next - Used for seq_file to get to the next pid of a pid_list
* @pid_list: The pid list to show
* @v: The last pid that was shown (+1 the actual pid to let zero be displayed)
* @pos: The position of the file
*
* This is used by the seq_file "next" operation to iterate the pids
* listed in a trace_pid_list structure.
*
* Returns the pid+1 as we want to display pid of zero, but NULL would
* stop the iteration.
*/
void *trace_pid_next(struct trace_pid_list *pid_list, void *v, loff_t *pos)
{
unsigned long pid = (unsigned long)v;
(*pos)++;
/* pid already is +1 of the actual prevous bit */
pid = find_next_bit(pid_list->pids, pid_list->pid_max, pid);
/* Return pid + 1 to allow zero to be represented */
if (pid < pid_list->pid_max)
return (void *)(pid + 1);
return NULL;
}
/**
* trace_pid_start - Used for seq_file to start reading pid lists
* @pid_list: The pid list to show
* @pos: The position of the file
*
* This is used by seq_file "start" operation to start the iteration
* of listing pids.
*
* Returns the pid+1 as we want to display pid of zero, but NULL would
* stop the iteration.
*/
void *trace_pid_start(struct trace_pid_list *pid_list, loff_t *pos)
{
unsigned long pid;
loff_t l = 0;
pid = find_first_bit(pid_list->pids, pid_list->pid_max);
if (pid >= pid_list->pid_max)
return NULL;
/* Return pid + 1 so that zero can be the exit value */
for (pid++; pid && l < *pos;
pid = (unsigned long)trace_pid_next(pid_list, (void *)pid, &l))
;
return (void *)pid;
}
/**
* trace_pid_show - show the current pid in seq_file processing
* @m: The seq_file structure to write into
* @v: A void pointer of the pid (+1) value to display
*
* Can be directly used by seq_file operations to display the current
* pid value.
*/
int trace_pid_show(struct seq_file *m, void *v)
{
unsigned long pid = (unsigned long)v - 1;
seq_printf(m, "%lu\n", pid);
return 0;
}
/* 128 should be much more than enough */
#define PID_BUF_SIZE 127
int trace_pid_write(struct trace_pid_list *filtered_pids,
struct trace_pid_list **new_pid_list,
const char __user *ubuf, size_t cnt)
{
struct trace_pid_list *pid_list;
struct trace_parser parser;
unsigned long val;
int nr_pids = 0;
ssize_t read = 0;
ssize_t ret = 0;
loff_t pos;
pid_t pid;
if (trace_parser_get_init(&parser, PID_BUF_SIZE + 1))
return -ENOMEM;
/*
* Always recreate a new array. The write is an all or nothing
* operation. Always create a new array when adding new pids by
* the user. If the operation fails, then the current list is
* not modified.
*/
pid_list = kmalloc(sizeof(*pid_list), GFP_KERNEL);
if (!pid_list)
return -ENOMEM;
pid_list->pid_max = READ_ONCE(pid_max);
/* Only truncating will shrink pid_max */
if (filtered_pids && filtered_pids->pid_max > pid_list->pid_max)
pid_list->pid_max = filtered_pids->pid_max;
pid_list->pids = vzalloc((pid_list->pid_max + 7) >> 3);
if (!pid_list->pids) {
kfree(pid_list);
return -ENOMEM;
}
if (filtered_pids) {
/* copy the current bits to the new max */
for_each_set_bit(pid, filtered_pids->pids,
filtered_pids->pid_max) {
set_bit(pid, pid_list->pids);
nr_pids++;
}
}
while (cnt > 0) {
pos = 0;
ret = trace_get_user(&parser, ubuf, cnt, &pos);
if (ret < 0 || !trace_parser_loaded(&parser))
break;
read += ret;
ubuf += ret;
cnt -= ret;
ret = -EINVAL;
if (kstrtoul(parser.buffer, 0, &val))
break;
if (val >= pid_list->pid_max)
break;
pid = (pid_t)val;
set_bit(pid, pid_list->pids);
nr_pids++;
trace_parser_clear(&parser);
ret = 0;
}
trace_parser_put(&parser);
if (ret < 0) {
trace_free_pid_list(pid_list);
return ret;
}
if (!nr_pids) {
/* Cleared the list of pids */
trace_free_pid_list(pid_list);
read = ret;
pid_list = NULL;
}
*new_pid_list = pid_list;
return read;
}
static u64 buffer_ftrace_now(struct trace_buffer *buf, int cpu)
{
u64 ts;
/* Early boot up does not have a buffer yet */
if (!buf->buffer)
return trace_clock_local();
ts = ring_buffer_time_stamp(buf->buffer, cpu);
ring_buffer_normalize_time_stamp(buf->buffer, cpu, &ts);
return ts;
}
u64 ftrace_now(int cpu)
{
return buffer_ftrace_now(&global_trace.trace_buffer, cpu);
}
/**
* tracing_is_enabled - Show if global_trace has been disabled
*
* Shows if the global trace has been enabled or not. It uses the
* mirror flag "buffer_disabled" to be used in fast paths such as for
* the irqsoff tracer. But it may be inaccurate due to races. If you
* need to know the accurate state, use tracing_is_on() which is a little
* slower, but accurate.
*/
int tracing_is_enabled(void)
{
/*
* For quick access (irqsoff uses this in fast path), just
* return the mirror variable of the state of the ring buffer.
* It's a little racy, but we don't really care.
*/
smp_rmb();
return !global_trace.buffer_disabled;
}
/*
* trace_buf_size is the size in bytes that is allocated
* for a buffer. Note, the number of bytes is always rounded
* to page size.
*
* This number is purposely set to a low number of 16384.
* If the dump on oops happens, it will be much appreciated
* to not have to wait for all that output. Anyway this can be
* boot time and run time configurable.
*/
#define TRACE_BUF_SIZE_DEFAULT 1441792UL /* 16384 * 88 (sizeof(entry)) */
static unsigned long trace_buf_size = TRACE_BUF_SIZE_DEFAULT;
/* trace_types holds a link list of available tracers. */
static struct tracer *trace_types __read_mostly;
/*
* trace_types_lock is used to protect the trace_types list.
*/
DEFINE_MUTEX(trace_types_lock);
/*
* serialize the access of the ring buffer
*
* ring buffer serializes readers, but it is low level protection.
* The validity of the events (which returns by ring_buffer_peek() ..etc)
* are not protected by ring buffer.
*
* The content of events may become garbage if we allow other process consumes
* these events concurrently:
* A) the page of the consumed events may become a normal page
* (not reader page) in ring buffer, and this page will be rewrited
* by events producer.
* B) The page of the consumed events may become a page for splice_read,
* and this page will be returned to system.
*
* These primitives allow multi process access to different cpu ring buffer
* concurrently.
*
* These primitives don't distinguish read-only and read-consume access.
* Multi read-only access are also serialized.
*/
#ifdef CONFIG_SMP
static DECLARE_RWSEM(all_cpu_access_lock);
static DEFINE_PER_CPU(struct mutex, cpu_access_lock);
static inline void trace_access_lock(int cpu)
{
if (cpu == RING_BUFFER_ALL_CPUS) {
/* gain it for accessing the whole ring buffer. */
down_write(&all_cpu_access_lock);
} else {
/* gain it for accessing a cpu ring buffer. */
/* Firstly block other trace_access_lock(RING_BUFFER_ALL_CPUS). */
down_read(&all_cpu_access_lock);
/* Secondly block other access to this @cpu ring buffer. */
mutex_lock(&per_cpu(cpu_access_lock, cpu));
}
}
static inline void trace_access_unlock(int cpu)
{
if (cpu == RING_BUFFER_ALL_CPUS) {
up_write(&all_cpu_access_lock);
} else {
mutex_unlock(&per_cpu(cpu_access_lock, cpu));
up_read(&all_cpu_access_lock);
}
}
static inline void trace_access_lock_init(void)
{
int cpu;
for_each_possible_cpu(cpu)
mutex_init(&per_cpu(cpu_access_lock, cpu));
}
#else
static DEFINE_MUTEX(access_lock);
static inline void trace_access_lock(int cpu)
{
(void)cpu;
mutex_lock(&access_lock);
}
static inline void trace_access_unlock(int cpu)
{
(void)cpu;
mutex_unlock(&access_lock);
}
static inline void trace_access_lock_init(void)
{
}
#endif
#ifdef CONFIG_STACKTRACE
static void __ftrace_trace_stack(struct ring_buffer *buffer,
unsigned long flags,
int skip, int pc, struct pt_regs *regs);
static inline void ftrace_trace_stack(struct trace_array *tr,
struct ring_buffer *buffer,
unsigned long flags,
int skip, int pc, struct pt_regs *regs);
#else
static inline void __ftrace_trace_stack(struct ring_buffer *buffer,
unsigned long flags,
int skip, int pc, struct pt_regs *regs)
{
}
static inline void ftrace_trace_stack(struct trace_array *tr,
struct ring_buffer *buffer,
unsigned long flags,
int skip, int pc, struct pt_regs *regs)
{
}
#endif
static __always_inline void
trace_event_setup(struct ring_buffer_event *event,
int type, unsigned long flags, int pc)
{
struct trace_entry *ent = ring_buffer_event_data(event);
tracing_generic_entry_update(ent, flags, pc);
ent->type = type;
}
static __always_inline struct ring_buffer_event *
__trace_buffer_lock_reserve(struct ring_buffer *buffer,
int type,
unsigned long len,
unsigned long flags, int pc)
{
struct ring_buffer_event *event;
event = ring_buffer_lock_reserve(buffer, len);
if (event != NULL)
trace_event_setup(event, type, flags, pc);
return event;
}
void tracer_tracing_on(struct trace_array *tr)
{
if (tr->trace_buffer.buffer)
ring_buffer_record_on(tr->trace_buffer.buffer);
/*
* This flag is looked at when buffers haven't been allocated
* yet, or by some tracers (like irqsoff), that just want to
* know if the ring buffer has been disabled, but it can handle
* races of where it gets disabled but we still do a record.
* As the check is in the fast path of the tracers, it is more
* important to be fast than accurate.
*/
tr->buffer_disabled = 0;
/* Make the flag seen by readers */
smp_wmb();
}
/**
* tracing_on - enable tracing buffers
*
* This function enables tracing buffers that may have been
* disabled with tracing_off.
*/
void tracing_on(void)
{
tracer_tracing_on(&global_trace);
}
EXPORT_SYMBOL_GPL(tracing_on);
static __always_inline void
__buffer_unlock_commit(struct ring_buffer *buffer, struct ring_buffer_event *event)
{
__this_cpu_write(trace_taskinfo_save, true);
/* If this is the temp buffer, we need to commit fully */
if (this_cpu_read(trace_buffered_event) == event) {
/* Length is in event->array[0] */
ring_buffer_write(buffer, event->array[0], &event->array[1]);
/* Release the temp buffer */
this_cpu_dec(trace_buffered_event_cnt);
} else
ring_buffer_unlock_commit(buffer, event);
}
/**
* __trace_puts - write a constant string into the trace buffer.
* @ip: The address of the caller
* @str: The constant string to write
* @size: The size of the string.
*/
int __trace_puts(unsigned long ip, const char *str, int size)
{
struct ring_buffer_event *event;
struct ring_buffer *buffer;
struct print_entry *entry;
unsigned long irq_flags;
int alloc;
int pc;
if (!(global_trace.trace_flags & TRACE_ITER_PRINTK))
return 0;
pc = preempt_count();
if (unlikely(tracing_selftest_running || tracing_disabled))
return 0;
alloc = sizeof(*entry) + size + 2; /* possible \n added */
local_save_flags(irq_flags);
buffer = global_trace.trace_buffer.buffer;
event = __trace_buffer_lock_reserve(buffer, TRACE_PRINT, alloc,
irq_flags, pc);
if (!event)
return 0;
entry = ring_buffer_event_data(event);
entry->ip = ip;
memcpy(&entry->buf, str, size);
/* Add a newline if necessary */
if (entry->buf[size - 1] != '\n') {
entry->buf[size] = '\n';
entry->buf[size + 1] = '\0';
} else
entry->buf[size] = '\0';
__buffer_unlock_commit(buffer, event);
ftrace_trace_stack(&global_trace, buffer, irq_flags, 4, pc, NULL);
return size;
}
EXPORT_SYMBOL_GPL(__trace_puts);
/**
* __trace_bputs - write the pointer to a constant string into trace buffer
* @ip: The address of the caller
* @str: The constant string to write to the buffer to
*/
int __trace_bputs(unsigned long ip, const char *str)
{
struct ring_buffer_event *event;
struct ring_buffer *buffer;
struct bputs_entry *entry;
unsigned long irq_flags;
int size = sizeof(struct bputs_entry);
int pc;
if (!(global_trace.trace_flags & TRACE_ITER_PRINTK))
return 0;
pc = preempt_count();
if (unlikely(tracing_selftest_running || tracing_disabled))
return 0;
local_save_flags(irq_flags);
buffer = global_trace.trace_buffer.buffer;
event = __trace_buffer_lock_reserve(buffer, TRACE_BPUTS, size,
irq_flags, pc);
if (!event)
return 0;
entry = ring_buffer_event_data(event);
entry->ip = ip;
entry->str = str;
__buffer_unlock_commit(buffer, event);
ftrace_trace_stack(&global_trace, buffer, irq_flags, 4, pc, NULL);
return 1;
}
EXPORT_SYMBOL_GPL(__trace_bputs);
#ifdef CONFIG_TRACER_SNAPSHOT
void tracing_snapshot_instance(struct trace_array *tr)
{
struct tracer *tracer = tr->current_trace;
unsigned long flags;
if (in_nmi()) {
internal_trace_puts("*** SNAPSHOT CALLED FROM NMI CONTEXT ***\n");
internal_trace_puts("*** snapshot is being ignored ***\n");
return;
}
if (!tr->allocated_snapshot) {
internal_trace_puts("*** SNAPSHOT NOT ALLOCATED ***\n");
internal_trace_puts("*** stopping trace here! ***\n");
tracing_off();
return;
}
/* Note, snapshot can not be used when the tracer uses it */
if (tracer->use_max_tr) {
internal_trace_puts("*** LATENCY TRACER ACTIVE ***\n");
internal_trace_puts("*** Can not use snapshot (sorry) ***\n");
return;
}
local_irq_save(flags);
update_max_tr(tr, current, smp_processor_id());
local_irq_restore(flags);
}
/**
* tracing_snapshot - take a snapshot of the current buffer.
*
* This causes a swap between the snapshot buffer and the current live
* tracing buffer. You can use this to take snapshots of the live
* trace when some condition is triggered, but continue to trace.
*
* Note, make sure to allocate the snapshot with either
* a tracing_snapshot_alloc(), or by doing it manually
* with: echo 1 > /sys/kernel/debug/tracing/snapshot
*
* If the snapshot buffer is not allocated, it will stop tracing.
* Basically making a permanent snapshot.
*/
void tracing_snapshot(void)
{
struct trace_array *tr = &global_trace;
tracing_snapshot_instance(tr);
}
EXPORT_SYMBOL_GPL(tracing_snapshot);
static int resize_buffer_duplicate_size(struct trace_buffer *trace_buf,
struct trace_buffer *size_buf, int cpu_id);
static void set_buffer_entries(struct trace_buffer *buf, unsigned long val);
int tracing_alloc_snapshot_instance(struct trace_array *tr)
{
int ret;
if (!tr->allocated_snapshot) {
/* allocate spare buffer */
ret = resize_buffer_duplicate_size(&tr->max_buffer,
&tr->trace_buffer, RING_BUFFER_ALL_CPUS);
if (ret < 0)
return ret;
tr->allocated_snapshot = true;
}
return 0;
}
static void free_snapshot(struct trace_array *tr)
{
/*
* We don't free the ring buffer. instead, resize it because
* The max_tr ring buffer has some state (e.g. ring->clock) and
* we want preserve it.
*/
ring_buffer_resize(tr->max_buffer.buffer, 1, RING_BUFFER_ALL_CPUS);
set_buffer_entries(&tr->max_buffer, 1);
tracing_reset_online_cpus(&tr->max_buffer);
tr->allocated_snapshot = false;
}
/**
* tracing_alloc_snapshot - allocate snapshot buffer.
*
* This only allocates the snapshot buffer if it isn't already
* allocated - it doesn't also take a snapshot.
*
* This is meant to be used in cases where the snapshot buffer needs
* to be set up for events that can't sleep but need to be able to
* trigger a snapshot.
*/
int tracing_alloc_snapshot(void)
{
struct trace_array *tr = &global_trace;
int ret;
ret = tracing_alloc_snapshot_instance(tr);
WARN_ON(ret < 0);
return ret;
}
EXPORT_SYMBOL_GPL(tracing_alloc_snapshot);
/**
* tracing_snapshot_alloc - allocate and take a snapshot of the current buffer.
*
* This is similar to tracing_snapshot(), but it will allocate the
* snapshot buffer if it isn't already allocated. Use this only
* where it is safe to sleep, as the allocation may sleep.
*
* This causes a swap between the snapshot buffer and the current live
* tracing buffer. You can use this to take snapshots of the live
* trace when some condition is triggered, but continue to trace.
*/
void tracing_snapshot_alloc(void)
{
int ret;
ret = tracing_alloc_snapshot();
if (ret < 0)
return;
tracing_snapshot();
}
EXPORT_SYMBOL_GPL(tracing_snapshot_alloc);
#else
void tracing_snapshot(void)
{
WARN_ONCE(1, "Snapshot feature not enabled, but internal snapshot used");
}
EXPORT_SYMBOL_GPL(tracing_snapshot);
int tracing_alloc_snapshot(void)
{
WARN_ONCE(1, "Snapshot feature not enabled, but snapshot allocation used");
return -ENODEV;
}
EXPORT_SYMBOL_GPL(tracing_alloc_snapshot);
void tracing_snapshot_alloc(void)
{
/* Give warning */
tracing_snapshot();
}
EXPORT_SYMBOL_GPL(tracing_snapshot_alloc);
#endif /* CONFIG_TRACER_SNAPSHOT */
void tracer_tracing_off(struct trace_array *tr)
{
if (tr->trace_buffer.buffer)
ring_buffer_record_off(tr->trace_buffer.buffer);
/*
* This flag is looked at when buffers haven't been allocated
* yet, or by some tracers (like irqsoff), that just want to
* know if the ring buffer has been disabled, but it can handle
* races of where it gets disabled but we still do a record.
* As the check is in the fast path of the tracers, it is more
* important to be fast than accurate.
*/
tr->buffer_disabled = 1;
/* Make the flag seen by readers */
smp_wmb();
}
/**
* tracing_off - turn off tracing buffers
*
* This function stops the tracing buffers from recording data.
* It does not disable any overhead the tracers themselves may
* be causing. This function simply causes all recording to
* the ring buffers to fail.
*/
void tracing_off(void)
{
tracer_tracing_off(&global_trace);
}
EXPORT_SYMBOL_GPL(tracing_off);
void disable_trace_on_warning(void)
{
if (__disable_trace_on_warning)
tracing_off();
}
/**
* tracer_tracing_is_on - show real state of ring buffer enabled
* @tr : the trace array to know if ring buffer is enabled
*
* Shows real state of the ring buffer if it is enabled or not.
*/
int tracer_tracing_is_on(struct trace_array *tr)
{
if (tr->trace_buffer.buffer)
return ring_buffer_record_is_on(tr->trace_buffer.buffer);
return !tr->buffer_disabled;
}
/**
* tracing_is_on - show state of ring buffers enabled
*/
int tracing_is_on(void)
{
return tracer_tracing_is_on(&global_trace);
}
EXPORT_SYMBOL_GPL(tracing_is_on);
static int __init set_buf_size(char *str)
{
unsigned long buf_size;
if (!str)
return 0;
buf_size = memparse(str, &str);
/* nr_entries can not be zero */
if (buf_size == 0)
return 0;
trace_buf_size = buf_size;
return 1;
}
__setup("trace_buf_size=", set_buf_size);
static int __init set_tracing_thresh(char *str)
{
unsigned long threshold;
int ret;
if (!str)
return 0;
ret = kstrtoul(str, 0, &threshold);
if (ret < 0)
return 0;
tracing_thresh = threshold * 1000;
return 1;
}
__setup("tracing_thresh=", set_tracing_thresh);
unsigned long nsecs_to_usecs(unsigned long nsecs)
{
return nsecs / 1000;
}
/*
* TRACE_FLAGS is defined as a tuple matching bit masks with strings.
* It uses C(a, b) where 'a' is the eval (enum) name and 'b' is the string that
* matches it. By defining "C(a, b) b", TRACE_FLAGS becomes a list
* of strings in the order that the evals (enum) were defined.
*/
#undef C
#define C(a, b) b
/* These must match the bit postions in trace_iterator_flags */
static const char *trace_options[] = {
TRACE_FLAGS
NULL
};
static struct {
u64 (*func)(void);
const char *name;
int in_ns; /* is this clock in nanoseconds? */
} trace_clocks[] = {
{ trace_clock_local, "local", 1 },
{ trace_clock_global, "global", 1 },
{ trace_clock_counter, "counter", 0 },
{ trace_clock_jiffies, "uptime", 0 },
{ trace_clock, "perf", 1 },
{ ktime_get_mono_fast_ns, "mono", 1 },
{ ktime_get_raw_fast_ns, "mono_raw", 1 },
{ ktime_get_boot_fast_ns, "boot", 1 },
ARCH_TRACE_CLOCKS
};
bool trace_clock_in_ns(struct trace_array *tr)
{
if (trace_clocks[tr->clock_id].in_ns)
return true;
return false;
}
/*
* trace_parser_get_init - gets the buffer for trace parser
*/
int trace_parser_get_init(struct trace_parser *parser, int size)
{
memset(parser, 0, sizeof(*parser));
parser->buffer = kmalloc(size, GFP_KERNEL);
if (!parser->buffer)
return 1;
parser->size = size;
return 0;
}
/*
* trace_parser_put - frees the buffer for trace parser
*/
void trace_parser_put(struct trace_parser *parser)
{
kfree(parser->buffer);
parser->buffer = NULL;
}
/*
* trace_get_user - reads the user input string separated by space
* (matched by isspace(ch))
*
* For each string found the 'struct trace_parser' is updated,
* and the function returns.
*
* Returns number of bytes read.
*
* See kernel/trace/trace.h for 'struct trace_parser' details.
*/
int trace_get_user(struct trace_parser *parser, const char __user *ubuf,
size_t cnt, loff_t *ppos)
{
char ch;
size_t read = 0;
ssize_t ret;
if (!*ppos)
trace_parser_clear(parser);
ret = get_user(ch, ubuf++);
if (ret)
goto out;
read++;
cnt--;
/*
* The parser is not finished with the last write,
* continue reading the user input without skipping spaces.
*/
if (!parser->cont) {
/* skip white space */
while (cnt && isspace(ch)) {
ret = get_user(ch, ubuf++);
if (ret)
goto out;
read++;
cnt--;
}
parser->idx = 0;
/* only spaces were written */
if (isspace(ch) || !ch) {
*ppos += read;
ret = read;
goto out;
}
}
/* read the non-space input */
while (cnt && !isspace(ch) && ch) {
if (parser->idx < parser->size - 1)
parser->buffer[parser->idx++] = ch;
else {
ret = -EINVAL;
goto out;
}
ret = get_user(ch, ubuf++);
if (ret)
goto out;
read++;
cnt--;
}
/* We either got finished input or we have to wait for another call. */
if (isspace(ch) || !ch) {
parser->buffer[parser->idx] = 0;
parser->cont = false;
} else if (parser->idx < parser->size - 1) {
parser->cont = true;
parser->buffer[parser->idx++] = ch;
/* Make sure the parsed string always terminates with '\0'. */
parser->buffer[parser->idx] = 0;
} else {
ret = -EINVAL;
goto out;
}
*ppos += read;
ret = read;
out:
return ret;
}
/* TODO add a seq_buf_to_buffer() */
static ssize_t trace_seq_to_buffer(struct trace_seq *s, void *buf, size_t cnt)
{
int len;
if (trace_seq_used(s) <= s->seq.readpos)
return -EBUSY;
len = trace_seq_used(s) - s->seq.readpos;
if (cnt > len)
cnt = len;
memcpy(buf, s->buffer + s->seq.readpos, cnt);
s->seq.readpos += cnt;
return cnt;
}
unsigned long __read_mostly tracing_thresh;
#ifdef CONFIG_TRACER_MAX_TRACE
/*
* Copy the new maximum trace into the separate maximum-trace
* structure. (this way the maximum trace is permanently saved,
* for later retrieval via /sys/kernel/tracing/tracing_max_latency)
*/
static void
__update_max_tr(struct trace_array *tr, struct task_struct *tsk, int cpu)
{
struct trace_buffer *trace_buf = &tr->trace_buffer;
struct trace_buffer *max_buf = &tr->max_buffer;
struct trace_array_cpu *data = per_cpu_ptr(trace_buf->data, cpu);
struct trace_array_cpu *max_data = per_cpu_ptr(max_buf->data, cpu);
max_buf->cpu = cpu;
max_buf->time_start = data->preempt_timestamp;
max_data->saved_latency = tr->max_latency;
max_data->critical_start = data->critical_start;
max_data->critical_end = data->critical_end;
memcpy(max_data->comm, tsk->comm, TASK_COMM_LEN);
max_data->pid = tsk->pid;
/*
* If tsk == current, then use current_uid(), as that does not use
* RCU. The irq tracer can be called out of RCU scope.
*/
if (tsk == current)
max_data->uid = current_uid();
else
max_data->uid = task_uid(tsk);
max_data->nice = tsk->static_prio - 20 - MAX_RT_PRIO;
max_data->policy = tsk->policy;
max_data->rt_priority = tsk->rt_priority;
/* record this tasks comm */
tracing_record_cmdline(tsk);
}
/**
* update_max_tr - snapshot all trace buffers from global_trace to max_tr
* @tr: tracer
* @tsk: the task with the latency
* @cpu: The cpu that initiated the trace.
*
* Flip the buffers between the @tr and the max_tr and record information
* about which task was the cause of this latency.
*/
void
update_max_tr(struct trace_array *tr, struct task_struct *tsk, int cpu)
{
if (tr->stop_count)
return;
WARN_ON_ONCE(!irqs_disabled());
if (!tr->allocated_snapshot) {
/* Only the nop tracer should hit this when disabling */
WARN_ON_ONCE(tr->current_trace != &nop_trace);
return;
}
arch_spin_lock(&tr->max_lock);
swap(tr->trace_buffer.buffer, tr->max_buffer.buffer);
__update_max_tr(tr, tsk, cpu);
arch_spin_unlock(&tr->max_lock);
}
/**
* update_max_tr_single - only copy one trace over, and reset the rest
* @tr - tracer
* @tsk - task with the latency
* @cpu - the cpu of the buffer to copy.
*
* Flip the trace of a single CPU buffer between the @tr and the max_tr.
*/
void
update_max_tr_single(struct trace_array *tr, struct task_struct *tsk, int cpu)
{
int ret;
if (tr->stop_count)
return;
WARN_ON_ONCE(!irqs_disabled());
if (!tr->allocated_snapshot) {
/* Only the nop tracer should hit this when disabling */
WARN_ON_ONCE(tr->current_trace != &nop_trace);
return;
}
arch_spin_lock(&tr->max_lock);
ret = ring_buffer_swap_cpu(tr->max_buffer.buffer, tr->trace_buffer.buffer, cpu);
if (ret == -EBUSY) {
/*
* We failed to swap the buffer due to a commit taking
* place on this CPU. We fail to record, but we reset
* the max trace buffer (no one writes directly to it)
* and flag that it failed.
*/
trace_array_printk_buf(tr->max_buffer.buffer, _THIS_IP_,
"Failed to swap buffers due to commit in progress\n");
}
WARN_ON_ONCE(ret && ret != -EAGAIN && ret != -EBUSY);
__update_max_tr(tr, tsk, cpu);
arch_spin_unlock(&tr->max_lock);
}
#endif /* CONFIG_TRACER_MAX_TRACE */
static int wait_on_pipe(struct trace_iterator *iter, bool full)
{
/* Iterators are static, they should be filled or empty */
if (trace_buffer_iter(iter, iter->cpu_file))
return 0;
return ring_buffer_wait(iter->trace_buffer->buffer, iter->cpu_file,
full);
}
#ifdef CONFIG_FTRACE_STARTUP_TEST
static bool selftests_can_run;
struct trace_selftests {
struct list_head list;
struct tracer *type;
};
static LIST_HEAD(postponed_selftests);
static int save_selftest(struct tracer *type)
{
struct trace_selftests *selftest;
selftest = kmalloc(sizeof(*selftest), GFP_KERNEL);
if (!selftest)
return -ENOMEM;
selftest->type = type;
list_add(&selftest->list, &postponed_selftests);
return 0;
}
static int run_tracer_selftest(struct tracer *type)
{
struct trace_array *tr = &global_trace;
struct tracer *saved_tracer = tr->current_trace;
int ret;
if (!type->selftest || tracing_selftest_disabled)
return 0;
/*
* If a tracer registers early in boot up (before scheduling is
* initialized and such), then do not run its selftests yet.
* Instead, run it a little later in the boot process.
*/
if (!selftests_can_run)
return save_selftest(type);
/*
* Run a selftest on this tracer.
* Here we reset the trace buffer, and set the current
* tracer to be this tracer. The tracer can then run some
* internal tracing to verify that everything is in order.
* If we fail, we do not register this tracer.
*/
tracing_reset_online_cpus(&tr->trace_buffer);
tr->current_trace = type;
#ifdef CONFIG_TRACER_MAX_TRACE
if (type->use_max_tr) {
/* If we expanded the buffers, make sure the max is expanded too */
if (ring_buffer_expanded)
ring_buffer_resize(tr->max_buffer.buffer, trace_buf_size,
RING_BUFFER_ALL_CPUS);
tr->allocated_snapshot = true;
}
#endif
/* the test is responsible for initializing and enabling */
pr_info("Testing tracer %s: ", type->name);
ret = type->selftest(type, tr);
/* the test is responsible for resetting too */
tr->current_trace = saved_tracer;
if (ret) {
printk(KERN_CONT "FAILED!\n");
/* Add the warning after printing 'FAILED' */
WARN_ON(1);
return -1;
}
/* Only reset on passing, to avoid touching corrupted buffers */
tracing_reset_online_cpus(&tr->trace_buffer);
#ifdef CONFIG_TRACER_MAX_TRACE
if (type->use_max_tr) {
tr->allocated_snapshot = false;
/* Shrink the max buffer again */
if (ring_buffer_expanded)
ring_buffer_resize(tr->max_buffer.buffer, 1,
RING_BUFFER_ALL_CPUS);
}
#endif
printk(KERN_CONT "PASSED\n");
return 0;
}
static __init int init_trace_selftests(void)
{
struct trace_selftests *p, *n;
struct tracer *t, **last;
int ret;
selftests_can_run = true;
mutex_lock(&trace_types_lock);
if (list_empty(&postponed_selftests))
goto out;
pr_info("Running postponed tracer tests:\n");
list_for_each_entry_safe(p, n, &postponed_selftests, list) {
ret = run_tracer_selftest(p->type);
/* If the test fails, then warn and remove from available_tracers */
if (ret < 0) {
WARN(1, "tracer: %s failed selftest, disabling\n",
p->type->name);
last = &trace_types;
for (t = trace_types; t; t = t->next) {
if (t == p->type) {
*last = t->next;
break;
}
last = &t->next;
}
}
list_del(&p->list);
kfree(p);
}
out:
mutex_unlock(&trace_types_lock);
return 0;
}
core_initcall(init_trace_selftests);
#else
static inline int run_tracer_selftest(struct tracer *type)
{
return 0;
}
#endif /* CONFIG_FTRACE_STARTUP_TEST */
static void add_tracer_options(struct trace_array *tr, struct tracer *t);
static void __init apply_trace_boot_options(void);
/**
* register_tracer - register a tracer with the ftrace system.
* @type - the plugin for the tracer
*
* Register a new plugin tracer.
*/
int __init register_tracer(struct tracer *type)
{
struct tracer *t;
int ret = 0;
if (!type->name) {
pr_info("Tracer must have a name\n");
return -1;
}
if (strlen(type->name) >= MAX_TRACER_SIZE) {
pr_info("Tracer has a name longer than %d\n", MAX_TRACER_SIZE);
return -1;
}
mutex_lock(&trace_types_lock);
tracing_selftest_running = true;
for (t = trace_types; t; t = t->next) {
if (strcmp(type->name, t->name) == 0) {
/* already found */
pr_info("Tracer %s already registered\n",
type->name);
ret = -1;
goto out;
}
}
if (!type->set_flag)
type->set_flag = &dummy_set_flag;
if (!type->flags) {
/*allocate a dummy tracer_flags*/
type->flags = kmalloc(sizeof(*type->flags), GFP_KERNEL);
if (!type->flags) {
ret = -ENOMEM;
goto out;
}
type->flags->val = 0;
type->flags->opts = dummy_tracer_opt;
} else
if (!type->flags->opts)
type->flags->opts = dummy_tracer_opt;
/* store the tracer for __set_tracer_option */
type->flags->trace = type;
ret = run_tracer_selftest(type);
if (ret < 0)
goto out;
type->next = trace_types;
trace_types = type;
add_tracer_options(&global_trace, type);
out:
tracing_selftest_running = false;
mutex_unlock(&trace_types_lock);
if (ret || !default_bootup_tracer)
goto out_unlock;
if (strncmp(default_bootup_tracer, type->name, MAX_TRACER_SIZE))
goto out_unlock;
printk(KERN_INFO "Starting tracer '%s'\n", type->name);
/* Do we want this tracer to start on bootup? */
tracing_set_tracer(&global_trace, type->name);
default_bootup_tracer = NULL;
apply_trace_boot_options();
/* disable other selftests, since this will break it. */
tracing_selftest_disabled = true;
#ifdef CONFIG_FTRACE_STARTUP_TEST
printk(KERN_INFO "Disabling FTRACE selftests due to running tracer '%s'\n",
type->name);
#endif
out_unlock:
return ret;
}
void tracing_reset(struct trace_buffer *buf, int cpu)
{
struct ring_buffer *buffer = buf->buffer;
if (!buffer)
return;
ring_buffer_record_disable(buffer);
/* Make sure all commits have finished */
synchronize_sched();
ring_buffer_reset_cpu(buffer, cpu);
ring_buffer_record_enable(buffer);
}
void tracing_reset_online_cpus(struct trace_buffer *buf)
{
struct ring_buffer *buffer = buf->buffer;
int cpu;
if (!buffer)
return;
ring_buffer_record_disable(buffer);
/* Make sure all commits have finished */
synchronize_sched();
buf->time_start = buffer_ftrace_now(buf, buf->cpu);
for_each_online_cpu(cpu)
ring_buffer_reset_cpu(buffer, cpu);
ring_buffer_record_enable(buffer);
}
/* Must have trace_types_lock held */
void tracing_reset_all_online_cpus(void)
{
struct trace_array *tr;
list_for_each_entry(tr, &ftrace_trace_arrays, list) {
if (!tr->clear_trace)
continue;
tr->clear_trace = false;
tracing_reset_online_cpus(&tr->trace_buffer);
#ifdef CONFIG_TRACER_MAX_TRACE
tracing_reset_online_cpus(&tr->max_buffer);
#endif
}
}
static int *tgid_map;
#define SAVED_CMDLINES_DEFAULT 128
#define NO_CMDLINE_MAP UINT_MAX
static arch_spinlock_t trace_cmdline_lock = __ARCH_SPIN_LOCK_UNLOCKED;
struct saved_cmdlines_buffer {
unsigned map_pid_to_cmdline[PID_MAX_DEFAULT+1];
unsigned *map_cmdline_to_pid;
unsigned cmdline_num;
int cmdline_idx;
char *saved_cmdlines;
};
static struct saved_cmdlines_buffer *savedcmd;
/* temporary disable recording */
static atomic_t trace_record_taskinfo_disabled __read_mostly;
static inline char *get_saved_cmdlines(int idx)
{
return &savedcmd->saved_cmdlines[idx * TASK_COMM_LEN];
}
static inline void set_cmdline(int idx, const char *cmdline)
{
memcpy(get_saved_cmdlines(idx), cmdline, TASK_COMM_LEN);
}
static int allocate_cmdlines_buffer(unsigned int val,
struct saved_cmdlines_buffer *s)
{
s->map_cmdline_to_pid = kmalloc_array(val,
sizeof(*s->map_cmdline_to_pid),
GFP_KERNEL);
if (!s->map_cmdline_to_pid)
return -ENOMEM;
s->saved_cmdlines = kmalloc_array(TASK_COMM_LEN, val, GFP_KERNEL);
if (!s->saved_cmdlines) {
kfree(s->map_cmdline_to_pid);
return -ENOMEM;
}
s->cmdline_idx = 0;
s->cmdline_num = val;
memset(&s->map_pid_to_cmdline, NO_CMDLINE_MAP,
sizeof(s->map_pid_to_cmdline));
memset(s->map_cmdline_to_pid, NO_CMDLINE_MAP,
val * sizeof(*s->map_cmdline_to_pid));
return 0;
}
static int trace_create_savedcmd(void)
{
int ret;
savedcmd = kmalloc(sizeof(*savedcmd), GFP_KERNEL);
if (!savedcmd)
return -ENOMEM;
ret = allocate_cmdlines_buffer(SAVED_CMDLINES_DEFAULT, savedcmd);
if (ret < 0) {
kfree(savedcmd);
savedcmd = NULL;
return -ENOMEM;
}
return 0;
}
int is_tracing_stopped(void)
{
return global_trace.stop_count;
}
/**
* tracing_start - quick start of the tracer
*
* If tracing is enabled but was stopped by tracing_stop,
* this will start the tracer back up.
*/
void tracing_start(void)
{
struct ring_buffer *buffer;
unsigned long flags;
if (tracing_disabled)
return;
raw_spin_lock_irqsave(&global_trace.start_lock, flags);
if (--global_trace.stop_count) {
if (global_trace.stop_count < 0) {
/* Someone screwed up their debugging */
WARN_ON_ONCE(1);
global_trace.stop_count = 0;
}
goto out;
}
/* Prevent the buffers from switching */
arch_spin_lock(&global_trace.max_lock);
buffer = global_trace.trace_buffer.buffer;
if (buffer)
ring_buffer_record_enable(buffer);
#ifdef CONFIG_TRACER_MAX_TRACE
buffer = global_trace.max_buffer.buffer;
if (buffer)
ring_buffer_record_enable(buffer);
#endif
arch_spin_unlock(&global_trace.max_lock);
out:
raw_spin_unlock_irqrestore(&global_trace.start_lock, flags);
}
static void tracing_start_tr(struct trace_array *tr)
{
struct ring_buffer *buffer;
unsigned long flags;
if (tracing_disabled)
return;
/* If global, we need to also start the max tracer */
if (tr->flags & TRACE_ARRAY_FL_GLOBAL)
return tracing_start();
raw_spin_lock_irqsave(&tr->start_lock, flags);
if (--tr->stop_count) {
if (tr->stop_count < 0) {
/* Someone screwed up their debugging */
WARN_ON_ONCE(1);
tr->stop_count = 0;
}
goto out;
}
buffer = tr->trace_buffer.buffer;
if (buffer)
ring_buffer_record_enable(buffer);
out:
raw_spin_unlock_irqrestore(&tr->start_lock, flags);
}
/**
* tracing_stop - quick stop of the tracer
*
* Light weight way to stop tracing. Use in conjunction with
* tracing_start.
*/
void tracing_stop(void)
{
struct ring_buffer *buffer;
unsigned long flags;
raw_spin_lock_irqsave(&global_trace.start_lock, flags);
if (global_trace.stop_count++)
goto out;
/* Prevent the buffers from switching */
arch_spin_lock(&global_trace.max_lock);
buffer = global_trace.trace_buffer.buffer;
if (buffer)
ring_buffer_record_disable(buffer);
#ifdef CONFIG_TRACER_MAX_TRACE
buffer = global_trace.max_buffer.buffer;
if (buffer)
ring_buffer_record_disable(buffer);
#endif
arch_spin_unlock(&global_trace.max_lock);
out:
raw_spin_unlock_irqrestore(&global_trace.start_lock, flags);
}
static void tracing_stop_tr(struct trace_array *tr)
{
struct ring_buffer *buffer;
unsigned long flags;
/* If global, we need to also stop the max tracer */
if (tr->flags & TRACE_ARRAY_FL_GLOBAL)
return tracing_stop();
raw_spin_lock_irqsave(&tr->start_lock, flags);
if (tr->stop_count++)
goto out;
buffer = tr->trace_buffer.buffer;
if (buffer)
ring_buffer_record_disable(buffer);
out:
raw_spin_unlock_irqrestore(&tr->start_lock, flags);
}
static int trace_save_cmdline(struct task_struct *tsk)
{
unsigned pid, idx;
/* treat recording of idle task as a success */
if (!tsk->pid)
return 1;
if (unlikely(tsk->pid > PID_MAX_DEFAULT))
return 0;
/*
* It's not the end of the world if we don't get
* the lock, but we also don't want to spin
* nor do we want to disable interrupts,
* so if we miss here, then better luck next time.
*/
if (!arch_spin_trylock(&trace_cmdline_lock))
return 0;
idx = savedcmd->map_pid_to_cmdline[tsk->pid];
if (idx == NO_CMDLINE_MAP) {
idx = (savedcmd->cmdline_idx + 1) % savedcmd->cmdline_num;
/*
* Check whether the cmdline buffer at idx has a pid
* mapped. We are going to overwrite that entry so we
* need to clear the map_pid_to_cmdline. Otherwise we
* would read the new comm for the old pid.
*/
pid = savedcmd->map_cmdline_to_pid[idx];
if (pid != NO_CMDLINE_MAP)
savedcmd->map_pid_to_cmdline[pid] = NO_CMDLINE_MAP;
savedcmd->map_cmdline_to_pid[idx] = tsk->pid;
savedcmd->map_pid_to_cmdline[tsk->pid] = idx;
savedcmd->cmdline_idx = idx;
}
set_cmdline(idx, tsk->comm);
arch_spin_unlock(&trace_cmdline_lock);
return 1;
}
static void __trace_find_cmdline(int pid, char comm[])
{
unsigned map;
if (!pid) {
strcpy(comm, "<idle>");
return;
}
if (WARN_ON_ONCE(pid < 0)) {
strcpy(comm, "<XXX>");
return;
}
if (pid > PID_MAX_DEFAULT) {
strcpy(comm, "<...>");
return;
}
map = savedcmd->map_pid_to_cmdline[pid];
if (map != NO_CMDLINE_MAP)
strlcpy(comm, get_saved_cmdlines(map), TASK_COMM_LEN);
else
strcpy(comm, "<...>");
}
void trace_find_cmdline(int pid, char comm[])
{
preempt_disable();
arch_spin_lock(&trace_cmdline_lock);
__trace_find_cmdline(pid, comm);
arch_spin_unlock(&trace_cmdline_lock);
preempt_enable();
}
int trace_find_tgid(int pid)
{
if (unlikely(!tgid_map || !pid || pid > PID_MAX_DEFAULT))
return 0;
return tgid_map[pid];
}
static int trace_save_tgid(struct task_struct *tsk)
{
/* treat recording of idle task as a success */
if (!tsk->pid)
return 1;
if (unlikely(!tgid_map || tsk->pid > PID_MAX_DEFAULT))
return 0;
tgid_map[tsk->pid] = tsk->tgid;
return 1;
}
static bool tracing_record_taskinfo_skip(int flags)
{
if (unlikely(!(flags & (TRACE_RECORD_CMDLINE | TRACE_RECORD_TGID))))
return true;
if (atomic_read(&trace_record_taskinfo_disabled) || !tracing_is_on())
return true;
if (!__this_cpu_read(trace_taskinfo_save))
return true;
return false;
}
/**
* tracing_record_taskinfo - record the task info of a task
*
* @task - task to record
* @flags - TRACE_RECORD_CMDLINE for recording comm
* - TRACE_RECORD_TGID for recording tgid
*/
void tracing_record_taskinfo(struct task_struct *task, int flags)
{
bool done;
if (tracing_record_taskinfo_skip(flags))
return;
/*
* Record as much task information as possible. If some fail, continue
* to try to record the others.
*/
done = !(flags & TRACE_RECORD_CMDLINE) || trace_save_cmdline(task);
done &= !(flags & TRACE_RECORD_TGID) || trace_save_tgid(task);
/* If recording any information failed, retry again soon. */
if (!done)
return;
__this_cpu_write(trace_taskinfo_save, false);
}
/**
* tracing_record_taskinfo_sched_switch - record task info for sched_switch
*
* @prev - previous task during sched_switch
* @next - next task during sched_switch
* @flags - TRACE_RECORD_CMDLINE for recording comm
* TRACE_RECORD_TGID for recording tgid
*/
void tracing_record_taskinfo_sched_switch(struct task_struct *prev,
struct task_struct *next, int flags)
{
bool done;
if (tracing_record_taskinfo_skip(flags))
return;
/*
* Record as much task information as possible. If some fail, continue
* to try to record the others.
*/
done = !(flags & TRACE_RECORD_CMDLINE) || trace_save_cmdline(prev);
done &= !(flags & TRACE_RECORD_CMDLINE) || trace_save_cmdline(next);
done &= !(flags & TRACE_RECORD_TGID) || trace_save_tgid(prev);
done &= !(flags & TRACE_RECORD_TGID) || trace_save_tgid(next);
/* If recording any information failed, retry again soon. */
if (!done)
return;
__this_cpu_write(trace_taskinfo_save, false);
}
/* Helpers to record a specific task information */
void tracing_record_cmdline(struct task_struct *task)
{
tracing_record_taskinfo(task, TRACE_RECORD_CMDLINE);
}
void tracing_record_tgid(struct task_struct *task)
{
tracing_record_taskinfo(task, TRACE_RECORD_TGID);
}
/*
* Several functions return TRACE_TYPE_PARTIAL_LINE if the trace_seq
* overflowed, and TRACE_TYPE_HANDLED otherwise. This helper function
* simplifies those functions and keeps them in sync.
*/
enum print_line_t trace_handle_return(struct trace_seq *s)
{
return trace_seq_has_overflowed(s) ?
TRACE_TYPE_PARTIAL_LINE : TRACE_TYPE_HANDLED;
}
EXPORT_SYMBOL_GPL(trace_handle_return);
void
tracing_generic_entry_update(struct trace_entry *entry, unsigned long flags,
int pc)
{
struct task_struct *tsk = current;
entry->preempt_count = pc & 0xff;
entry->pid = (tsk) ? tsk->pid : 0;
entry->flags =
#ifdef CONFIG_TRACE_IRQFLAGS_SUPPORT
(irqs_disabled_flags(flags) ? TRACE_FLAG_IRQS_OFF : 0) |
#else
TRACE_FLAG_IRQS_NOSUPPORT |
#endif
((pc & NMI_MASK ) ? TRACE_FLAG_NMI : 0) |
((pc & HARDIRQ_MASK) ? TRACE_FLAG_HARDIRQ : 0) |
((pc & SOFTIRQ_OFFSET) ? TRACE_FLAG_SOFTIRQ : 0) |
(tif_need_resched() ? TRACE_FLAG_NEED_RESCHED : 0) |
(test_preempt_need_resched() ? TRACE_FLAG_PREEMPT_RESCHED : 0);
}
EXPORT_SYMBOL_GPL(tracing_generic_entry_update);
struct ring_buffer_event *
trace_buffer_lock_reserve(struct ring_buffer *buffer,
int type,
unsigned long len,
unsigned long flags, int pc)
{
return __trace_buffer_lock_reserve(buffer, type, len, flags, pc);
}
DEFINE_PER_CPU(struct ring_buffer_event *, trace_buffered_event);
DEFINE_PER_CPU(int, trace_buffered_event_cnt);
static int trace_buffered_event_ref;
/**
* trace_buffered_event_enable - enable buffering events
*
* When events are being filtered, it is quicker to use a temporary
* buffer to write the event data into if there's a likely chance
* that it will not be committed. The discard of the ring buffer
* is not as fast as committing, and is much slower than copying
* a commit.
*
* When an event is to be filtered, allocate per cpu buffers to
* write the event data into, and if the event is filtered and discarded
* it is simply dropped, otherwise, the entire data is to be committed
* in one shot.
*/
void trace_buffered_event_enable(void)
{
struct ring_buffer_event *event;
struct page *page;
int cpu;
WARN_ON_ONCE(!mutex_is_locked(&event_mutex));
if (trace_buffered_event_ref++)
return;
for_each_tracing_cpu(cpu) {
page = alloc_pages_node(cpu_to_node(cpu),
GFP_KERNEL | __GFP_NORETRY, 0);
if (!page)
goto failed;
event = page_address(page);
memset(event, 0, sizeof(*event));
per_cpu(trace_buffered_event, cpu) = event;
preempt_disable();
if (cpu == smp_processor_id() &&
this_cpu_read(trace_buffered_event) !=
per_cpu(trace_buffered_event, cpu))
WARN_ON_ONCE(1);
preempt_enable();
}
return;
failed:
trace_buffered_event_disable();
}
static void enable_trace_buffered_event(void *data)
{
/* Probably not needed, but do it anyway */
smp_rmb();
this_cpu_dec(trace_buffered_event_cnt);
}
static void disable_trace_buffered_event(void *data)
{
this_cpu_inc(trace_buffered_event_cnt);
}
/**
* trace_buffered_event_disable - disable buffering events
*
* When a filter is removed, it is faster to not use the buffered
* events, and to commit directly into the ring buffer. Free up
* the temp buffers when there are no more users. This requires
* special synchronization with current events.
*/
void trace_buffered_event_disable(void)
{
int cpu;
WARN_ON_ONCE(!mutex_is_locked(&event_mutex));
if (WARN_ON_ONCE(!trace_buffered_event_ref))
return;
if (--trace_buffered_event_ref)
return;
preempt_disable();
/* For each CPU, set the buffer as used. */
smp_call_function_many(tracing_buffer_mask,
disable_trace_buffered_event, NULL, 1);
preempt_enable();
/* Wait for all current users to finish */
synchronize_sched();
for_each_tracing_cpu(cpu) {
free_page((unsigned long)per_cpu(trace_buffered_event, cpu));
per_cpu(trace_buffered_event, cpu) = NULL;
}
/*
* Make sure trace_buffered_event is NULL before clearing
* trace_buffered_event_cnt.
*/
smp_wmb();
preempt_disable();
/* Do the work on each cpu */
smp_call_function_many(tracing_buffer_mask,
enable_trace_buffered_event, NULL, 1);
preempt_enable();
}
static struct ring_buffer *temp_buffer;
struct ring_buffer_event *
trace_event_buffer_lock_reserve(struct ring_buffer **current_rb,
struct trace_event_file *trace_file,
int type, unsigned long len,
unsigned long flags, int pc)
{
struct ring_buffer_event *entry;
int val;
*current_rb = trace_file->tr->trace_buffer.buffer;
if (!ring_buffer_time_stamp_abs(*current_rb) && (trace_file->flags &
(EVENT_FILE_FL_SOFT_DISABLED | EVENT_FILE_FL_FILTERED)) &&
(entry = this_cpu_read(trace_buffered_event))) {
/* Try to use the per cpu buffer first */
val = this_cpu_inc_return(trace_buffered_event_cnt);
if (val == 1) {
trace_event_setup(entry, type, flags, pc);
entry->array[0] = len;
return entry;
}
this_cpu_dec(trace_buffered_event_cnt);
}
entry = __trace_buffer_lock_reserve(*current_rb,
type, len, flags, pc);
/*
* If tracing is off, but we have triggers enabled
* we still need to look at the event data. Use the temp_buffer
* to store the trace event for the tigger to use. It's recusive
* safe and will not be recorded anywhere.
*/
if (!entry && trace_file->flags & EVENT_FILE_FL_TRIGGER_COND) {
*current_rb = temp_buffer;
entry = __trace_buffer_lock_reserve(*current_rb,
type, len, flags, pc);
}
return entry;
}
EXPORT_SYMBOL_GPL(trace_event_buffer_lock_reserve);
static DEFINE_SPINLOCK(tracepoint_iter_lock);
static DEFINE_MUTEX(tracepoint_printk_mutex);
static void output_printk(struct trace_event_buffer *fbuffer)
{
struct trace_event_call *event_call;
struct trace_event *event;
unsigned long flags;
struct trace_iterator *iter = tracepoint_print_iter;
/* We should never get here if iter is NULL */
if (WARN_ON_ONCE(!iter))
return;
event_call = fbuffer->trace_file->event_call;
if (!event_call || !event_call->event.funcs ||
!event_call->event.funcs->trace)
return;
event = &fbuffer->trace_file->event_call->event;
spin_lock_irqsave(&tracepoint_iter_lock, flags);
trace_seq_init(&iter->seq);
iter->ent = fbuffer->entry;
event_call->event.funcs->trace(iter, 0, event);
trace_seq_putc(&iter->seq, 0);
printk("%s", iter->seq.buffer);
spin_unlock_irqrestore(&tracepoint_iter_lock, flags);
}
int tracepoint_printk_sysctl(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp,
loff_t *ppos)
{
int save_tracepoint_printk;
int ret;
mutex_lock(&tracepoint_printk_mutex);
save_tracepoint_printk = tracepoint_printk;
ret = proc_dointvec(table, write, buffer, lenp, ppos);
/*
* This will force exiting early, as tracepoint_printk
* is always zero when tracepoint_printk_iter is not allocated
*/
if (!tracepoint_print_iter)
tracepoint_printk = 0;
if (save_tracepoint_printk == tracepoint_printk)
goto out;
if (tracepoint_printk)
static_key_enable(&tracepoint_printk_key.key);
else
static_key_disable(&tracepoint_printk_key.key);
out:
mutex_unlock(&tracepoint_printk_mutex);
return ret;
}
void trace_event_buffer_commit(struct trace_event_buffer *fbuffer)
{
if (static_key_false(&tracepoint_printk_key.key))
output_printk(fbuffer);
event_trigger_unlock_commit(fbuffer->trace_file, fbuffer->buffer,
fbuffer->event, fbuffer->entry,
fbuffer->flags, fbuffer->pc);
}
EXPORT_SYMBOL_GPL(trace_event_buffer_commit);
/*
* Skip 3:
*
* trace_buffer_unlock_commit_regs()
* trace_event_buffer_commit()
* trace_event_raw_event_xxx()
*/
# define STACK_SKIP 3
void trace_buffer_unlock_commit_regs(struct trace_array *tr,
struct ring_buffer *buffer,
struct ring_buffer_event *event,
unsigned long flags, int pc,
struct pt_regs *regs)
{
__buffer_unlock_commit(buffer, event);
/*
* If regs is not set, then skip the necessary functions.
* Note, we can still get here via blktrace, wakeup tracer
* and mmiotrace, but that's ok if they lose a function or
* two. They are not that meaningful.
*/
ftrace_trace_stack(tr, buffer, flags, regs ? 0 : STACK_SKIP, pc, regs);
ftrace_trace_userstack(buffer, flags, pc);
}
/*
* Similar to trace_buffer_unlock_commit_regs() but do not dump stack.
*/
void
trace_buffer_unlock_commit_nostack(struct ring_buffer *buffer,
struct ring_buffer_event *event)
{
__buffer_unlock_commit(buffer, event);
}
static void
trace_process_export(struct trace_export *export,
struct ring_buffer_event *event)
{
struct trace_entry *entry;
unsigned int size = 0;
entry = ring_buffer_event_data(event);
size = ring_buffer_event_length(event);
export->write(export, entry, size);
}
static DEFINE_MUTEX(ftrace_export_lock);
static struct trace_export __rcu *ftrace_exports_list __read_mostly;
static DEFINE_STATIC_KEY_FALSE(ftrace_exports_enabled);
static inline void ftrace_exports_enable(void)
{
static_branch_enable(&ftrace_exports_enabled);
}
static inline void ftrace_exports_disable(void)
{
static_branch_disable(&ftrace_exports_enabled);
}
void ftrace_exports(struct ring_buffer_event *event)
{
struct trace_export *export;
preempt_disable_notrace();
export = rcu_dereference_raw_notrace(ftrace_exports_list);
while (export) {
trace_process_export(export, event);
export = rcu_dereference_raw_notrace(export->next);
}
preempt_enable_notrace();
}
static inline void
add_trace_export(struct trace_export **list, struct trace_export *export)
{
rcu_assign_pointer(export->next, *list);
/*
* We are entering export into the list but another
* CPU might be walking that list. We need to make sure
* the export->next pointer is valid before another CPU sees
* the export pointer included into the list.
*/
rcu_assign_pointer(*list, export);
}
static inline int
rm_trace_export(struct trace_export **list, struct trace_export *export)
{
struct trace_export **p;
for (p = list; *p != NULL; p = &(*p)->next)
if (*p == export)
break;
if (*p != export)
return -1;
rcu_assign_pointer(*p, (*p)->next);
return 0;
}
static inline void
add_ftrace_export(struct trace_export **list, struct trace_export *export)
{
if (*list == NULL)
ftrace_exports_enable();
add_trace_export(list, export);
}
static inline int
rm_ftrace_export(struct trace_export **list, struct trace_export *export)
{
int ret;
ret = rm_trace_export(list, export);
if (*list == NULL)
ftrace_exports_disable();
return ret;
}
int register_ftrace_export(struct trace_export *export)
{
if (WARN_ON_ONCE(!export->write))
return -1;
mutex_lock(&ftrace_export_lock);
add_ftrace_export(&ftrace_exports_list, export);
mutex_unlock(&ftrace_export_lock);
return 0;
}
EXPORT_SYMBOL_GPL(register_ftrace_export);
int unregister_ftrace_export(struct trace_export *export)
{
int ret;
mutex_lock(&ftrace_export_lock);
ret = rm_ftrace_export(&ftrace_exports_list, export);
mutex_unlock(&ftrace_export_lock);
return ret;
}
EXPORT_SYMBOL_GPL(unregister_ftrace_export);
void
trace_function(struct trace_array *tr,
unsigned long ip, unsigned long parent_ip, unsigned long flags,
int pc)
{
struct trace_event_call *call = &event_function;
struct ring_buffer *buffer = tr->trace_buffer.buffer;
struct ring_buffer_event *event;
struct ftrace_entry *entry;
event = __trace_buffer_lock_reserve(buffer, TRACE_FN, sizeof(*entry),
flags, pc);
if (!event)
return;
entry = ring_buffer_event_data(event);
entry->ip = ip;
entry->parent_ip = parent_ip;
if (!call_filter_check_discard(call, entry, buffer, event)) {
if (static_branch_unlikely(&ftrace_exports_enabled))
ftrace_exports(event);
__buffer_unlock_commit(buffer, event);
}
}
#ifdef CONFIG_STACKTRACE
#define FTRACE_STACK_MAX_ENTRIES (PAGE_SIZE / sizeof(unsigned long))
struct ftrace_stack {
unsigned long calls[FTRACE_STACK_MAX_ENTRIES];
};
static DEFINE_PER_CPU(struct ftrace_stack, ftrace_stack);
static DEFINE_PER_CPU(int, ftrace_stack_reserve);
static void __ftrace_trace_stack(struct ring_buffer *buffer,
unsigned long flags,
int skip, int pc, struct pt_regs *regs)
{
struct trace_event_call *call = &event_kernel_stack;
struct ring_buffer_event *event;
struct stack_entry *entry;
struct stack_trace trace;
int use_stack;
int size = FTRACE_STACK_ENTRIES;
trace.nr_entries = 0;
trace.skip = skip;
/*
* Add one, for this function and the call to save_stack_trace()
* If regs is set, then these functions will not be in the way.
*/
#ifndef CONFIG_UNWINDER_ORC
if (!regs)
trace.skip++;
#endif
/*
* Since events can happen in NMIs there's no safe way to
* use the per cpu ftrace_stacks. We reserve it and if an interrupt
* or NMI comes in, it will just have to use the default
* FTRACE_STACK_SIZE.
*/
preempt_disable_notrace();
use_stack = __this_cpu_inc_return(ftrace_stack_reserve);
/*
* We don't need any atomic variables, just a barrier.
* If an interrupt comes in, we don't care, because it would
* have exited and put the counter back to what we want.
* We just need a barrier to keep gcc from moving things
* around.
*/
barrier();
if (use_stack == 1) {
trace.entries = this_cpu_ptr(ftrace_stack.calls);
trace.max_entries = FTRACE_STACK_MAX_ENTRIES;
if (regs)
save_stack_trace_regs(regs, &trace);
else
save_stack_trace(&trace);
if (trace.nr_entries > size)
size = trace.nr_entries;
} else
/* From now on, use_stack is a boolean */
use_stack = 0;
size *= sizeof(unsigned long);
event = __trace_buffer_lock_reserve(buffer, TRACE_STACK,
sizeof(*entry) + size, flags, pc);
if (!event)
goto out;
entry = ring_buffer_event_data(event);
memset(&entry->caller, 0, size);
if (use_stack)
memcpy(&entry->caller, trace.entries,
trace.nr_entries * sizeof(unsigned long));
else {
trace.max_entries = FTRACE_STACK_ENTRIES;
trace.entries = entry->caller;
if (regs)
save_stack_trace_regs(regs, &trace);
else
save_stack_trace(&trace);
}
entry->size = trace.nr_entries;
if (!call_filter_check_discard(call, entry, buffer, event))
__buffer_unlock_commit(buffer, event);
out:
/* Again, don't let gcc optimize things here */
barrier();
__this_cpu_dec(ftrace_stack_reserve);
preempt_enable_notrace();
}
static inline void ftrace_trace_stack(struct trace_array *tr,
struct ring_buffer *buffer,
unsigned long flags,
int skip, int pc, struct pt_regs *regs)
{
if (!(tr->trace_flags & TRACE_ITER_STACKTRACE))
return;
__ftrace_trace_stack(buffer, flags, skip, pc, regs);
}
void __trace_stack(struct trace_array *tr, unsigned long flags, int skip,
int pc)
{
struct ring_buffer *buffer = tr->trace_buffer.buffer;
if (rcu_is_watching()) {
__ftrace_trace_stack(buffer, flags, skip, pc, NULL);
return;
}
/*
* When an NMI triggers, RCU is enabled via rcu_nmi_enter(),
* but if the above rcu_is_watching() failed, then the NMI
* triggered someplace critical, and rcu_irq_enter() should
* not be called from NMI.
*/
if (unlikely(in_nmi()))
return;
rcu_irq_enter_irqson();
__ftrace_trace_stack(buffer, flags, skip, pc, NULL);
rcu_irq_exit_irqson();
}
/**
* trace_dump_stack - record a stack back trace in the trace buffer
* @skip: Number of functions to skip (helper handlers)
*/
void trace_dump_stack(int skip)
{
unsigned long flags;
if (tracing_disabled || tracing_selftest_running)
return;
local_save_flags(flags);
#ifndef CONFIG_UNWINDER_ORC
/* Skip 1 to skip this function. */
skip++;
#endif
__ftrace_trace_stack(global_trace.trace_buffer.buffer,
flags, skip, preempt_count(), NULL);
}
static DEFINE_PER_CPU(int, user_stack_count);
void
ftrace_trace_userstack(struct ring_buffer *buffer, unsigned long flags, int pc)
{
struct trace_event_call *call = &event_user_stack;
struct ring_buffer_event *event;
struct userstack_entry *entry;
struct stack_trace trace;
if (!(global_trace.trace_flags & TRACE_ITER_USERSTACKTRACE))
return;
/*
* NMIs can not handle page faults, even with fix ups.
* The save user stack can (and often does) fault.
*/
if (unlikely(in_nmi()))
return;
/*
* prevent recursion, since the user stack tracing may
* trigger other kernel events.
*/
preempt_disable();
if (__this_cpu_read(user_stack_count))
goto out;
__this_cpu_inc(user_stack_count);
event = __trace_buffer_lock_reserve(buffer, TRACE_USER_STACK,
sizeof(*entry), flags, pc);
if (!event)
goto out_drop_count;
entry = ring_buffer_event_data(event);
entry->tgid = current->tgid;
memset(&entry->caller, 0, sizeof(entry->caller));
trace.nr_entries = 0;
trace.max_entries = FTRACE_STACK_ENTRIES;
trace.skip = 0;
trace.entries = entry->caller;
save_stack_trace_user(&trace);
if (!call_filter_check_discard(call, entry, buffer, event))
__buffer_unlock_commit(buffer, event);
out_drop_count:
__this_cpu_dec(user_stack_count);
out:
preempt_enable();
}
#ifdef UNUSED
static void __trace_userstack(struct trace_array *tr, unsigned long flags)
{
ftrace_trace_userstack(tr, flags, preempt_count());
}
#endif /* UNUSED */
#endif /* CONFIG_STACKTRACE */
/* created for use with alloc_percpu */
struct trace_buffer_struct {
int nesting;
char buffer[4][TRACE_BUF_SIZE];
};
static struct trace_buffer_struct *trace_percpu_buffer;
/*
* Thise allows for lockless recording. If we're nested too deeply, then
* this returns NULL.
*/
static char *get_trace_buf(void)
{
struct trace_buffer_struct *buffer = this_cpu_ptr(trace_percpu_buffer);
if (!buffer || buffer->nesting >= 4)
return NULL;
buffer->nesting++;
/* Interrupts must see nesting incremented before we use the buffer */
barrier();
return &buffer->buffer[buffer->nesting][0];
}
static void put_trace_buf(void)
{
/* Don't let the decrement of nesting leak before this */
barrier();
this_cpu_dec(trace_percpu_buffer->nesting);
}
static int alloc_percpu_trace_buffer(void)
{
struct trace_buffer_struct *buffers;
buffers = alloc_percpu(struct trace_buffer_struct);
if (WARN(!buffers, "Could not allocate percpu trace_printk buffer"))
return -ENOMEM;
trace_percpu_buffer = buffers;
return 0;
}
static int buffers_allocated;
void trace_printk_init_buffers(void)
{
if (buffers_allocated)
return;
if (alloc_percpu_trace_buffer())
return;
/* trace_printk() is for debug use only. Don't use it in production. */
pr_warn("\n");
pr_warn("**********************************************************\n");
pr_warn("** NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE **\n");
pr_warn("** **\n");
pr_warn("** trace_printk() being used. Allocating extra memory. **\n");
pr_warn("** **\n");
pr_warn("** This means that this is a DEBUG kernel and it is **\n");
pr_warn("** unsafe for production use. **\n");
pr_warn("** **\n");
pr_warn("** If you see this message and you are not debugging **\n");
pr_warn("** the kernel, report this immediately to your vendor! **\n");
pr_warn("** **\n");
pr_warn("** NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE **\n");
pr_warn("**********************************************************\n");
/* Expand the buffers to set size */
tracing_update_buffers();
buffers_allocated = 1;
/*
* trace_printk_init_buffers() can be called by modules.
* If that happens, then we need to start cmdline recording
* directly here. If the global_trace.buffer is already
* allocated here, then this was called by module code.
*/
if (global_trace.trace_buffer.buffer)
tracing_start_cmdline_record();
}
void trace_printk_start_comm(void)
{
/* Start tracing comms if trace printk is set */
if (!buffers_allocated)
return;
tracing_start_cmdline_record();
}
static void trace_printk_start_stop_comm(int enabled)
{
if (!buffers_allocated)
return;
if (enabled)
tracing_start_cmdline_record();
else
tracing_stop_cmdline_record();
}
/**
* trace_vbprintk - write binary msg to tracing buffer
*
*/
int trace_vbprintk(unsigned long ip, const char *fmt, va_list args)
{
struct trace_event_call *call = &event_bprint;
struct ring_buffer_event *event;
struct ring_buffer *buffer;
struct trace_array *tr = &global_trace;
struct bprint_entry *entry;
unsigned long flags;
char *tbuffer;
int len = 0, size, pc;
if (unlikely(tracing_selftest_running || tracing_disabled))
return 0;
/* Don't pollute graph traces with trace_vprintk internals */
pause_graph_tracing();
pc = preempt_count();
preempt_disable_notrace();
tbuffer = get_trace_buf();
if (!tbuffer) {
len = 0;
goto out_nobuffer;
}
len = vbin_printf((u32 *)tbuffer, TRACE_BUF_SIZE/sizeof(int), fmt, args);
if (len > TRACE_BUF_SIZE/sizeof(int) || len < 0)
goto out;
local_save_flags(flags);
size = sizeof(*entry) + sizeof(u32) * len;
buffer = tr->trace_buffer.buffer;
event = __trace_buffer_lock_reserve(buffer, TRACE_BPRINT, size,
flags, pc);
if (!event)
goto out;
entry = ring_buffer_event_data(event);
entry->ip = ip;
entry->fmt = fmt;
memcpy(entry->buf, tbuffer, sizeof(u32) * len);
if (!call_filter_check_discard(call, entry, buffer, event)) {
__buffer_unlock_commit(buffer, event);
ftrace_trace_stack(tr, buffer, flags, 6, pc, NULL);
}
out:
put_trace_buf();
out_nobuffer:
preempt_enable_notrace();
unpause_graph_tracing();
return len;
}
EXPORT_SYMBOL_GPL(trace_vbprintk);
static int
__trace_array_vprintk(struct ring_buffer *buffer,
unsigned long ip, const char *fmt, va_list args)
{
struct trace_event_call *call = &event_print;
struct ring_buffer_event *event;
int len = 0, size, pc;
struct print_entry *entry;
unsigned long flags;
char *tbuffer;
if (tracing_disabled || tracing_selftest_running)
return 0;
/* Don't pollute graph traces with trace_vprintk internals */
pause_graph_tracing();
pc = preempt_count();
preempt_disable_notrace();
tbuffer = get_trace_buf();
if (!tbuffer) {
len = 0;
goto out_nobuffer;
}
len = vscnprintf(tbuffer, TRACE_BUF_SIZE, fmt, args);
local_save_flags(flags);
size = sizeof(*entry) + len + 1;
event = __trace_buffer_lock_reserve(buffer, TRACE_PRINT, size,
flags, pc);
if (!event)
goto out;
entry = ring_buffer_event_data(event);
entry->ip = ip;
memcpy(&entry->buf, tbuffer, len + 1);
if (!call_filter_check_discard(call, entry, buffer, event)) {
__buffer_unlock_commit(buffer, event);
ftrace_trace_stack(&global_trace, buffer, flags, 6, pc, NULL);
}
out:
put_trace_buf();
out_nobuffer:
preempt_enable_notrace();
unpause_graph_tracing();
return len;
}
int trace_array_vprintk(struct trace_array *tr,
unsigned long ip, const char *fmt, va_list args)
{
return __trace_array_vprintk(tr->trace_buffer.buffer, ip, fmt, args);
}
int trace_array_printk(struct trace_array *tr,
unsigned long ip, const char *fmt, ...)
{
int ret;
va_list ap;
if (!(global_trace.trace_flags & TRACE_ITER_PRINTK))
return 0;
va_start(ap, fmt);
ret = trace_array_vprintk(tr, ip, fmt, ap);
va_end(ap);
return ret;
}
int trace_array_printk_buf(struct ring_buffer *buffer,
unsigned long ip, const char *fmt, ...)
{
int ret;
va_list ap;
if (!(global_trace.trace_flags & TRACE_ITER_PRINTK))
return 0;
va_start(ap, fmt);
ret = __trace_array_vprintk(buffer, ip, fmt, ap);
va_end(ap);
return ret;
}
int trace_vprintk(unsigned long ip, const char *fmt, va_list args)
{
return trace_array_vprintk(&global_trace, ip, fmt, args);
}
EXPORT_SYMBOL_GPL(trace_vprintk);
static void trace_iterator_increment(struct trace_iterator *iter)
{
struct ring_buffer_iter *buf_iter = trace_buffer_iter(iter, iter->cpu);
iter->idx++;
if (buf_iter)
ring_buffer_read(buf_iter, NULL);
}
static struct trace_entry *
peek_next_entry(struct trace_iterator *iter, int cpu, u64 *ts,
unsigned long *lost_events)
{
struct ring_buffer_event *event;
struct ring_buffer_iter *buf_iter = trace_buffer_iter(iter, cpu);
if (buf_iter)
event = ring_buffer_iter_peek(buf_iter, ts);
else
event = ring_buffer_peek(iter->trace_buffer->buffer, cpu, ts,
lost_events);
if (event) {
iter->ent_size = ring_buffer_event_length(event);
return ring_buffer_event_data(event);
}
iter->ent_size = 0;
return NULL;
}
static struct trace_entry *
__find_next_entry(struct trace_iterator *iter, int *ent_cpu,
unsigned long *missing_events, u64 *ent_ts)
{
struct ring_buffer *buffer = iter->trace_buffer->buffer;
struct trace_entry *ent, *next = NULL;
unsigned long lost_events = 0, next_lost = 0;
int cpu_file = iter->cpu_file;
u64 next_ts = 0, ts;
int next_cpu = -1;
int next_size = 0;
int cpu;
/*
* If we are in a per_cpu trace file, don't bother by iterating over
* all cpu and peek directly.
*/
if (cpu_file > RING_BUFFER_ALL_CPUS) {
if (ring_buffer_empty_cpu(buffer, cpu_file))
return NULL;
ent = peek_next_entry(iter, cpu_file, ent_ts, missing_events);
if (ent_cpu)
*ent_cpu = cpu_file;
return ent;
}
for_each_tracing_cpu(cpu) {
if (ring_buffer_empty_cpu(buffer, cpu))
continue;
ent = peek_next_entry(iter, cpu, &ts, &lost_events);
/*
* Pick the entry with the smallest timestamp:
*/
if (ent && (!next || ts < next_ts)) {
next = ent;
next_cpu = cpu;
next_ts = ts;
next_lost = lost_events;
next_size = iter->ent_size;
}
}
iter->ent_size = next_size;
if (ent_cpu)
*ent_cpu = next_cpu;
if (ent_ts)
*ent_ts = next_ts;
if (missing_events)
*missing_events = next_lost;
return next;
}
/* Find the next real entry, without updating the iterator itself */
struct trace_entry *trace_find_next_entry(struct trace_iterator *iter,
int *ent_cpu, u64 *ent_ts)
{
return __find_next_entry(iter, ent_cpu, NULL, ent_ts);
}
/* Find the next real entry, and increment the iterator to the next entry */
void *trace_find_next_entry_inc(struct trace_iterator *iter)
{
iter->ent = __find_next_entry(iter, &iter->cpu,
&iter->lost_events, &iter->ts);
if (iter->ent)
trace_iterator_increment(iter);
return iter->ent ? iter : NULL;
}
static void trace_consume(struct trace_iterator *iter)
{
ring_buffer_consume(iter->trace_buffer->buffer, iter->cpu, &iter->ts,
&iter->lost_events);
}
static void *s_next(struct seq_file *m, void *v, loff_t *pos)
{
struct trace_iterator *iter = m->private;
int i = (int)*pos;
void *ent;
WARN_ON_ONCE(iter->leftover);
(*pos)++;
/* can't go backwards */
if (iter->idx > i)
return NULL;
if (iter->idx < 0)
ent = trace_find_next_entry_inc(iter);
else
ent = iter;
while (ent && iter->idx < i)
ent = trace_find_next_entry_inc(iter);
iter->pos = *pos;
return ent;
}
void tracing_iter_reset(struct trace_iterator *iter, int cpu)
{
struct ring_buffer_event *event;
struct ring_buffer_iter *buf_iter;
unsigned long entries = 0;
u64 ts;
per_cpu_ptr(iter->trace_buffer->data, cpu)->skipped_entries = 0;
buf_iter = trace_buffer_iter(iter, cpu);
if (!buf_iter)
return;
ring_buffer_iter_reset(buf_iter);
/*
* We could have the case with the max latency tracers
* that a reset never took place on a cpu. This is evident
* by the timestamp being before the start of the buffer.
*/
while ((event = ring_buffer_iter_peek(buf_iter, &ts))) {
if (ts >= iter->trace_buffer->time_start)
break;
entries++;
ring_buffer_read(buf_iter, NULL);
}
per_cpu_ptr(iter->trace_buffer->data, cpu)->skipped_entries = entries;
}
/*
* The current tracer is copied to avoid a global locking
* all around.
*/
static void *s_start(struct seq_file *m, loff_t *pos)
{
struct trace_iterator *iter = m->private;
struct trace_array *tr = iter->tr;
int cpu_file = iter->cpu_file;
void *p = NULL;
loff_t l = 0;
int cpu;
/*
* copy the tracer to avoid using a global lock all around.
* iter->trace is a copy of current_trace, the pointer to the
* name may be used instead of a strcmp(), as iter->trace->name
* will point to the same string as current_trace->name.
*/
mutex_lock(&trace_types_lock);
if (unlikely(tr->current_trace && iter->trace->name != tr->current_trace->name))
*iter->trace = *tr->current_trace;
mutex_unlock(&trace_types_lock);
#ifdef CONFIG_TRACER_MAX_TRACE
if (iter->snapshot && iter->trace->use_max_tr)
return ERR_PTR(-EBUSY);
#endif
if (!iter->snapshot)
atomic_inc(&trace_record_taskinfo_disabled);
if (*pos != iter->pos) {
iter->ent = NULL;
iter->cpu = 0;
iter->idx = -1;
if (cpu_file == RING_BUFFER_ALL_CPUS) {
for_each_tracing_cpu(cpu)
tracing_iter_reset(iter, cpu);
} else
tracing_iter_reset(iter, cpu_file);
iter->leftover = 0;
for (p = iter; p && l < *pos; p = s_next(m, p, &l))
;
} else {
/*
* If we overflowed the seq_file before, then we want
* to just reuse the trace_seq buffer again.
*/
if (iter->leftover)
p = iter;
else {
l = *pos - 1;
p = s_next(m, p, &l);
}
}
trace_event_read_lock();
trace_access_lock(cpu_file);
return p;
}
static void s_stop(struct seq_file *m, void *p)
{
struct trace_iterator *iter = m->private;
#ifdef CONFIG_TRACER_MAX_TRACE
if (iter->snapshot && iter->trace->use_max_tr)
return;
#endif
if (!iter->snapshot)
atomic_dec(&trace_record_taskinfo_disabled);
trace_access_unlock(iter->cpu_file);
trace_event_read_unlock();
}
static void
get_total_entries(struct trace_buffer *buf,
unsigned long *total, unsigned long *entries)
{
unsigned long count;
int cpu;
*total = 0;
*entries = 0;
for_each_tracing_cpu(cpu) {
count = ring_buffer_entries_cpu(buf->buffer, cpu);
/*
* If this buffer has skipped entries, then we hold all
* entries for the trace and we need to ignore the
* ones before the time stamp.
*/
if (per_cpu_ptr(buf->data, cpu)->skipped_entries) {
count -= per_cpu_ptr(buf->data, cpu)->skipped_entries;
/* total is the same as the entries */
*total += count;
} else
*total += count +
ring_buffer_overrun_cpu(buf->buffer, cpu);
*entries += count;
}
}
static void print_lat_help_header(struct seq_file *m)
{
seq_puts(m, "# _------=> CPU# \n"
"# / _-----=> irqs-off \n"
"# | / _----=> need-resched \n"
"# || / _---=> hardirq/softirq \n"
"# ||| / _--=> preempt-depth \n"
"# |||| / delay \n"
"# cmd pid ||||| time | caller \n"
"# \\ / ||||| \\ | / \n");
}
static void print_event_info(struct trace_buffer *buf, struct seq_file *m)
{
unsigned long total;
unsigned long entries;
get_total_entries(buf, &total, &entries);
seq_printf(m, "# entries-in-buffer/entries-written: %lu/%lu #P:%d\n",
entries, total, num_online_cpus());
seq_puts(m, "#\n");
}
static void print_func_help_header(struct trace_buffer *buf, struct seq_file *m,
unsigned int flags)
{
bool tgid = flags & TRACE_ITER_RECORD_TGID;
print_event_info(buf, m);
seq_printf(m, "# TASK-PID CPU# %s TIMESTAMP FUNCTION\n", tgid ? "TGID " : "");
seq_printf(m, "# | | | %s | |\n", tgid ? " | " : "");
}
static void print_func_help_header_irq(struct trace_buffer *buf, struct seq_file *m,
unsigned int flags)
{
bool tgid = flags & TRACE_ITER_RECORD_TGID;
const char tgid_space[] = " ";
const char space[] = " ";
seq_printf(m, "# %s _-----=> irqs-off\n",
tgid ? tgid_space : space);
seq_printf(m, "# %s / _----=> need-resched\n",
tgid ? tgid_space : space);
seq_printf(m, "# %s| / _---=> hardirq/softirq\n",
tgid ? tgid_space : space);
seq_printf(m, "# %s|| / _--=> preempt-depth\n",
tgid ? tgid_space : space);
seq_printf(m, "# %s||| / delay\n",
tgid ? tgid_space : space);
seq_printf(m, "# TASK-PID CPU#%s|||| TIMESTAMP FUNCTION\n",
tgid ? " TGID " : space);
seq_printf(m, "# | | | %s|||| | |\n",
tgid ? " | " : space);
}
void
print_trace_header(struct seq_file *m, struct trace_iterator *iter)
{
unsigned long sym_flags = (global_trace.trace_flags & TRACE_ITER_SYM_MASK);
struct trace_buffer *buf = iter->trace_buffer;
struct trace_array_cpu *data = per_cpu_ptr(buf->data, buf->cpu);
struct tracer *type = iter->trace;
unsigned long entries;
unsigned long total;
const char *name = "preemption";
name = type->name;
get_total_entries(buf, &total, &entries);
seq_printf(m, "# %s latency trace v1.1.5 on %s\n",
name, UTS_RELEASE);
seq_puts(m, "# -----------------------------------"
"---------------------------------\n");
seq_printf(m, "# latency: %lu us, #%lu/%lu, CPU#%d |"
" (M:%s VP:%d, KP:%d, SP:%d HP:%d",
nsecs_to_usecs(data->saved_latency),
entries,
total,
buf->cpu,
#if defined(CONFIG_PREEMPT_NONE)
"server",
#elif defined(CONFIG_PREEMPT_VOLUNTARY)
"desktop",
#elif defined(CONFIG_PREEMPT)
"preempt",
#else
"unknown",
#endif
/* These are reserved for later use */
0, 0, 0, 0);
#ifdef CONFIG_SMP
seq_printf(m, " #P:%d)\n", num_online_cpus());
#else
seq_puts(m, ")\n");
#endif
seq_puts(m, "# -----------------\n");
seq_printf(m, "# | task: %.16s-%d "
"(uid:%d nice:%ld policy:%ld rt_prio:%ld)\n",
data->comm, data->pid,
from_kuid_munged(seq_user_ns(m), data->uid), data->nice,
data->policy, data->rt_priority);
seq_puts(m, "# -----------------\n");
if (data->critical_start) {
seq_puts(m, "# => started at: ");
seq_print_ip_sym(&iter->seq, data->critical_start, sym_flags);
trace_print_seq(m, &iter->seq);
seq_puts(m, "\n# => ended at: ");
seq_print_ip_sym(&iter->seq, data->critical_end, sym_flags);
trace_print_seq(m, &iter->seq);
seq_puts(m, "\n#\n");
}
seq_puts(m, "#\n");
}
static void test_cpu_buff_start(struct trace_iterator *iter)
{
struct trace_seq *s = &iter->seq;
struct trace_array *tr = iter->tr;
if (!(tr->trace_flags & TRACE_ITER_ANNOTATE))
return;
if (!(iter->iter_flags & TRACE_FILE_ANNOTATE))
return;
if (cpumask_available(iter->started) &&
cpumask_test_cpu(iter->cpu, iter->started))
return;
if (per_cpu_ptr(iter->trace_buffer->data, iter->cpu)->skipped_entries)
return;
if (cpumask_available(iter->started))
cpumask_set_cpu(iter->cpu, iter->started);
/* Don't print started cpu buffer for the first entry of the trace */
if (iter->idx > 1)
trace_seq_printf(s, "##### CPU %u buffer started ####\n",
iter->cpu);
}
static enum print_line_t print_trace_fmt(struct trace_iterator *iter)
{
struct trace_array *tr = iter->tr;
struct trace_seq *s = &iter->seq;
unsigned long sym_flags = (tr->trace_flags & TRACE_ITER_SYM_MASK);
struct trace_entry *entry;
struct trace_event *event;
entry = iter->ent;
test_cpu_buff_start(iter);
event = ftrace_find_event(entry->type);
if (tr->trace_flags & TRACE_ITER_CONTEXT_INFO) {
if (iter->iter_flags & TRACE_FILE_LAT_FMT)
trace_print_lat_context(iter);
else
trace_print_context(iter);
}
if (trace_seq_has_overflowed(s))
return TRACE_TYPE_PARTIAL_LINE;
if (event)
return event->funcs->trace(iter, sym_flags, event);
trace_seq_printf(s, "Unknown type %d\n", entry->type);
return trace_handle_return(s);
}
static enum print_line_t print_raw_fmt(struct trace_iterator *iter)
{
struct trace_array *tr = iter->tr;
struct trace_seq *s = &iter->seq;
struct trace_entry *entry;
struct trace_event *event;
entry = iter->ent;
if (tr->trace_flags & TRACE_ITER_CONTEXT_INFO)
trace_seq_printf(s, "%d %d %llu ",
entry->pid, iter->cpu, iter->ts);
if (trace_seq_has_overflowed(s))
return TRACE_TYPE_PARTIAL_LINE;
event = ftrace_find_event(entry->type);
if (event)
return event->funcs->raw(iter, 0, event);
trace_seq_printf(s, "%d ?\n", entry->type);
return trace_handle_return(s);
}
static enum print_line_t print_hex_fmt(struct trace_iterator *iter)
{
struct trace_array *tr = iter->tr;
struct trace_seq *s = &iter->seq;
unsigned char newline = '\n';
struct trace_entry *entry;
struct trace_event *event;
entry = iter->ent;
if (tr->trace_flags & TRACE_ITER_CONTEXT_INFO) {
SEQ_PUT_HEX_FIELD(s, entry->pid);
SEQ_PUT_HEX_FIELD(s, iter->cpu);
SEQ_PUT_HEX_FIELD(s, iter->ts);
if (trace_seq_has_overflowed(s))
return TRACE_TYPE_PARTIAL_LINE;
}
event = ftrace_find_event(entry->type);
if (event) {
enum print_line_t ret = event->funcs->hex(iter, 0, event);
if (ret != TRACE_TYPE_HANDLED)
return ret;
}
SEQ_PUT_FIELD(s, newline);
return trace_handle_return(s);
}
static enum print_line_t print_bin_fmt(struct trace_iterator *iter)
{
struct trace_array *tr = iter->tr;
struct trace_seq *s = &iter->seq;
struct trace_entry *entry;
struct trace_event *event;
entry = iter->ent;
if (tr->trace_flags & TRACE_ITER_CONTEXT_INFO) {
SEQ_PUT_FIELD(s, entry->pid);
SEQ_PUT_FIELD(s, iter->cpu);
SEQ_PUT_FIELD(s, iter->ts);
if (trace_seq_has_overflowed(s))
return TRACE_TYPE_PARTIAL_LINE;
}
event = ftrace_find_event(entry->type);
return event ? event->funcs->binary(iter, 0, event) :
TRACE_TYPE_HANDLED;
}
int trace_empty(struct trace_iterator *iter)
{
struct ring_buffer_iter *buf_iter;
int cpu;
/* If we are looking at one CPU buffer, only check that one */
if (iter->cpu_file != RING_BUFFER_ALL_CPUS) {
cpu = iter->cpu_file;
buf_iter = trace_buffer_iter(iter, cpu);
if (buf_iter) {
if (!ring_buffer_iter_empty(buf_iter))
return 0;
} else {
if (!ring_buffer_empty_cpu(iter->trace_buffer->buffer, cpu))
return 0;
}
return 1;
}
for_each_tracing_cpu(cpu) {
buf_iter = trace_buffer_iter(iter, cpu);
if (buf_iter) {
if (!ring_buffer_iter_empty(buf_iter))
return 0;
} else {
if (!ring_buffer_empty_cpu(iter->trace_buffer->buffer, cpu))
return 0;
}
}
return 1;
}
/* Called with trace_event_read_lock() held. */
enum print_line_t print_trace_line(struct trace_iterator *iter)
{
struct trace_array *tr = iter->tr;
unsigned long trace_flags = tr->trace_flags;
enum print_line_t ret;
if (iter->lost_events) {
trace_seq_printf(&iter->seq, "CPU:%d [LOST %lu EVENTS]\n",
iter->cpu, iter->lost_events);
if (trace_seq_has_overflowed(&iter->seq))
return TRACE_TYPE_PARTIAL_LINE;
}
if (iter->trace && iter->trace->print_line) {
ret = iter->trace->print_line(iter);
if (ret != TRACE_TYPE_UNHANDLED)
return ret;
}
if (iter->ent->type == TRACE_BPUTS &&
trace_flags & TRACE_ITER_PRINTK &&
trace_flags & TRACE_ITER_PRINTK_MSGONLY)
return trace_print_bputs_msg_only(iter);
if (iter->ent->type == TRACE_BPRINT &&
trace_flags & TRACE_ITER_PRINTK &&
trace_flags & TRACE_ITER_PRINTK_MSGONLY)
return trace_print_bprintk_msg_only(iter);
if (iter->ent->type == TRACE_PRINT &&
trace_flags & TRACE_ITER_PRINTK &&
trace_flags & TRACE_ITER_PRINTK_MSGONLY)
return trace_print_printk_msg_only(iter);
if (trace_flags & TRACE_ITER_BIN)
return print_bin_fmt(iter);
if (trace_flags & TRACE_ITER_HEX)
return print_hex_fmt(iter);
if (trace_flags & TRACE_ITER_RAW)
return print_raw_fmt(iter);
return print_trace_fmt(iter);
}
void trace_latency_header(struct seq_file *m)
{
struct trace_iterator *iter = m->private;
struct trace_array *tr = iter->tr;
/* print nothing if the buffers are empty */
if (trace_empty(iter))
return;
if (iter->iter_flags & TRACE_FILE_LAT_FMT)
print_trace_header(m, iter);
if (!(tr->trace_flags & TRACE_ITER_VERBOSE))
print_lat_help_header(m);
}
void trace_default_header(struct seq_file *m)
{
struct trace_iterator *iter = m->private;
struct trace_array *tr = iter->tr;
unsigned long trace_flags = tr->trace_flags;
if (!(trace_flags & TRACE_ITER_CONTEXT_INFO))
return;
if (iter->iter_flags & TRACE_FILE_LAT_FMT) {
/* print nothing if the buffers are empty */
if (trace_empty(iter))
return;
print_trace_header(m, iter);
if (!(trace_flags & TRACE_ITER_VERBOSE))
print_lat_help_header(m);
} else {
if (!(trace_flags & TRACE_ITER_VERBOSE)) {
if (trace_flags & TRACE_ITER_IRQ_INFO)
print_func_help_header_irq(iter->trace_buffer,
m, trace_flags);
else
print_func_help_header(iter->trace_buffer, m,
trace_flags);
}
}
}
static void test_ftrace_alive(struct seq_file *m)
{
if (!ftrace_is_dead())
return;
seq_puts(m, "# WARNING: FUNCTION TRACING IS CORRUPTED\n"
"# MAY BE MISSING FUNCTION EVENTS\n");
}
#ifdef CONFIG_TRACER_MAX_TRACE
static void show_snapshot_main_help(struct seq_file *m)
{
seq_puts(m, "# echo 0 > snapshot : Clears and frees snapshot buffer\n"
"# echo 1 > snapshot : Allocates snapshot buffer, if not already allocated.\n"
"# Takes a snapshot of the main buffer.\n"
"# echo 2 > snapshot : Clears snapshot buffer (but does not allocate or free)\n"
"# (Doesn't have to be '2' works with any number that\n"
"# is not a '0' or '1')\n");
}
static void show_snapshot_percpu_help(struct seq_file *m)
{
seq_puts(m, "# echo 0 > snapshot : Invalid for per_cpu snapshot file.\n");
#ifdef CONFIG_RING_BUFFER_ALLOW_SWAP
seq_puts(m, "# echo 1 > snapshot : Allocates snapshot buffer, if not already allocated.\n"
"# Takes a snapshot of the main buffer for this cpu.\n");
#else
seq_puts(m, "# echo 1 > snapshot : Not supported with this kernel.\n"
"# Must use main snapshot file to allocate.\n");
#endif
seq_puts(m, "# echo 2 > snapshot : Clears this cpu's snapshot buffer (but does not allocate)\n"
"# (Doesn't have to be '2' works with any number that\n"
"# is not a '0' or '1')\n");
}
static void print_snapshot_help(struct seq_file *m, struct trace_iterator *iter)
{
if (iter->tr->allocated_snapshot)
seq_puts(m, "#\n# * Snapshot is allocated *\n#\n");
else
seq_puts(m, "#\n# * Snapshot is freed *\n#\n");
seq_puts(m, "# Snapshot commands:\n");
if (iter->cpu_file == RING_BUFFER_ALL_CPUS)
show_snapshot_main_help(m);
else
show_snapshot_percpu_help(m);
}
#else
/* Should never be called */
static inline void print_snapshot_help(struct seq_file *m, struct trace_iterator *iter) { }
#endif
static int s_show(struct seq_file *m, void *v)
{
struct trace_iterator *iter = v;
int ret;
if (iter->ent == NULL) {
if (iter->tr) {
seq_printf(m, "# tracer: %s\n", iter->trace->name);
seq_puts(m, "#\n");
test_ftrace_alive(m);
}
if (iter->snapshot && trace_empty(iter))
print_snapshot_help(m, iter);
else if (iter->trace && iter->trace->print_header)
iter->trace->print_header(m);
else
trace_default_header(m);
} else if (iter->leftover) {
/*
* If we filled the seq_file buffer earlier, we
* want to just show it now.
*/
ret = trace_print_seq(m, &iter->seq);
/* ret should this time be zero, but you never know */
iter->leftover = ret;
} else {
print_trace_line(iter);
ret = trace_print_seq(m, &iter->seq);
/*
* If we overflow the seq_file buffer, then it will
* ask us for this data again at start up.
* Use that instead.
* ret is 0 if seq_file write succeeded.
* -1 otherwise.
*/
iter->leftover = ret;
}
return 0;
}
/*
* Should be used after trace_array_get(), trace_types_lock
* ensures that i_cdev was already initialized.
*/
static inline int tracing_get_cpu(struct inode *inode)
{
if (inode->i_cdev) /* See trace_create_cpu_file() */
return (long)inode->i_cdev - 1;
return RING_BUFFER_ALL_CPUS;
}
static const struct seq_operations tracer_seq_ops = {
.start = s_start,
.next = s_next,
.stop = s_stop,
.show = s_show,
};
static struct trace_iterator *
__tracing_open(struct inode *inode, struct file *file, bool snapshot)
{
struct trace_array *tr = inode->i_private;
struct trace_iterator *iter;
int cpu;
if (tracing_disabled)
return ERR_PTR(-ENODEV);
iter = __seq_open_private(file, &tracer_seq_ops, sizeof(*iter));
if (!iter)
return ERR_PTR(-ENOMEM);
iter->buffer_iter = kcalloc(nr_cpu_ids, sizeof(*iter->buffer_iter),
GFP_KERNEL);
if (!iter->buffer_iter)
goto release;
/*
* We make a copy of the current tracer to avoid concurrent
* changes on it while we are reading.
*/
mutex_lock(&trace_types_lock);
iter->trace = kzalloc(sizeof(*iter->trace), GFP_KERNEL);
if (!iter->trace)
goto fail;
*iter->trace = *tr->current_trace;
if (!zalloc_cpumask_var(&iter->started, GFP_KERNEL))
goto fail;
iter->tr = tr;
#ifdef CONFIG_TRACER_MAX_TRACE
/* Currently only the top directory has a snapshot */
if (tr->current_trace->print_max || snapshot)
iter->trace_buffer = &tr->max_buffer;
else
#endif
iter->trace_buffer = &tr->trace_buffer;
iter->snapshot = snapshot;
iter->pos = -1;
iter->cpu_file = tracing_get_cpu(inode);
mutex_init(&iter->mutex);
/* Notify the tracer early; before we stop tracing. */
if (iter->trace && iter->trace->open)
iter->trace->open(iter);
/* Annotate start of buffers if we had overruns */
if (ring_buffer_overruns(iter->trace_buffer->buffer))
iter->iter_flags |= TRACE_FILE_ANNOTATE;
/* Output in nanoseconds only if we are using a clock in nanoseconds. */
if (trace_clocks[tr->clock_id].in_ns)
iter->iter_flags |= TRACE_FILE_TIME_IN_NS;
/* stop the trace while dumping if we are not opening "snapshot" */
if (!iter->snapshot)
tracing_stop_tr(tr);
if (iter->cpu_file == RING_BUFFER_ALL_CPUS) {
for_each_tracing_cpu(cpu) {
iter->buffer_iter[cpu] =
ring_buffer_read_prepare(iter->trace_buffer->buffer, cpu);
}
ring_buffer_read_prepare_sync();
for_each_tracing_cpu(cpu) {
ring_buffer_read_start(iter->buffer_iter[cpu]);
tracing_iter_reset(iter, cpu);
}
} else {
cpu = iter->cpu_file;
iter->buffer_iter[cpu] =
ring_buffer_read_prepare(iter->trace_buffer->buffer, cpu);
ring_buffer_read_prepare_sync();
ring_buffer_read_start(iter->buffer_iter[cpu]);
tracing_iter_reset(iter, cpu);
}
mutex_unlock(&trace_types_lock);
return iter;
fail:
mutex_unlock(&trace_types_lock);
kfree(iter->trace);
kfree(iter->buffer_iter);
release:
seq_release_private(inode, file);
return ERR_PTR(-ENOMEM);
}
int tracing_open_generic(struct inode *inode, struct file *filp)
{
if (tracing_disabled)
return -ENODEV;
filp->private_data = inode->i_private;
return 0;
}
bool tracing_is_disabled(void)
{
return (tracing_disabled) ? true: false;
}
/*
* Open and update trace_array ref count.
* Must have the current trace_array passed to it.
*/
static int tracing_open_generic_tr(struct inode *inode, struct file *filp)
{
struct trace_array *tr = inode->i_private;
if (tracing_disabled)
return -ENODEV;
if (trace_array_get(tr) < 0)
return -ENODEV;
filp->private_data = inode->i_private;
return 0;
}
static int tracing_release(struct inode *inode, struct file *file)
{
struct trace_array *tr = inode->i_private;
struct seq_file *m = file->private_data;
struct trace_iterator *iter;
int cpu;
if (!(file->f_mode & FMODE_READ)) {
trace_array_put(tr);
return 0;
}
/* Writes do not use seq_file */
iter = m->private;
mutex_lock(&trace_types_lock);
for_each_tracing_cpu(cpu) {
if (iter->buffer_iter[cpu])
ring_buffer_read_finish(iter->buffer_iter[cpu]);
}
if (iter->trace && iter->trace->close)
iter->trace->close(iter);
if (!iter->snapshot)
/* reenable tracing if it was previously enabled */
tracing_start_tr(tr);
__trace_array_put(tr);
mutex_unlock(&trace_types_lock);
mutex_destroy(&iter->mutex);
free_cpumask_var(iter->started);
kfree(iter->trace);
kfree(iter->buffer_iter);
seq_release_private(inode, file);
return 0;
}
static int tracing_release_generic_tr(struct inode *inode, struct file *file)
{
struct trace_array *tr = inode->i_private;
trace_array_put(tr);
return 0;
}
static int tracing_single_release_tr(struct inode *inode, struct file *file)
{
struct trace_array *tr = inode->i_private;
trace_array_put(tr);
return single_release(inode, file);
}
static int tracing_open(struct inode *inode, struct file *file)
{
struct trace_array *tr = inode->i_private;
struct trace_iterator *iter;
int ret = 0;
if (trace_array_get(tr) < 0)
return -ENODEV;
/* If this file was open for write, then erase contents */
if ((file->f_mode & FMODE_WRITE) && (file->f_flags & O_TRUNC)) {
int cpu = tracing_get_cpu(inode);
struct trace_buffer *trace_buf = &tr->trace_buffer;
#ifdef CONFIG_TRACER_MAX_TRACE
if (tr->current_trace->print_max)
trace_buf = &tr->max_buffer;
#endif
if (cpu == RING_BUFFER_ALL_CPUS)
tracing_reset_online_cpus(trace_buf);
else
tracing_reset(trace_buf, cpu);
}
if (file->f_mode & FMODE_READ) {
iter = __tracing_open(inode, file, false);
if (IS_ERR(iter))
ret = PTR_ERR(iter);
else if (tr->trace_flags & TRACE_ITER_LATENCY_FMT)
iter->iter_flags |= TRACE_FILE_LAT_FMT;
}
if (ret < 0)
trace_array_put(tr);
return ret;
}
/*
* Some tracers are not suitable for instance buffers.
* A tracer is always available for the global array (toplevel)
* or if it explicitly states that it is.
*/
static bool
trace_ok_for_array(struct tracer *t, struct trace_array *tr)
{
return (tr->flags & TRACE_ARRAY_FL_GLOBAL) || t->allow_instances;
}
/* Find the next tracer that this trace array may use */
static struct tracer *
get_tracer_for_array(struct trace_array *tr, struct tracer *t)
{
while (t && !trace_ok_for_array(t, tr))
t = t->next;
return t;
}
static void *
t_next(struct seq_file *m, void *v, loff_t *pos)
{
struct trace_array *tr = m->private;
struct tracer *t = v;
(*pos)++;
if (t)
t = get_tracer_for_array(tr, t->next);
return t;
}
static void *t_start(struct seq_file *m, loff_t *pos)
{
struct trace_array *tr = m->private;
struct tracer *t;
loff_t l = 0;
mutex_lock(&trace_types_lock);
t = get_tracer_for_array(tr, trace_types);
for (; t && l < *pos; t = t_next(m, t, &l))
;
return t;
}
static void t_stop(struct seq_file *m, void *p)
{
mutex_unlock(&trace_types_lock);
}
static int t_show(struct seq_file *m, void *v)
{
struct tracer *t = v;
if (!t)
return 0;
seq_puts(m, t->name);
if (t->next)
seq_putc(m, ' ');
else
seq_putc(m, '\n');
return 0;
}
static const struct seq_operations show_traces_seq_ops = {
.start = t_start,
.next = t_next,
.stop = t_stop,
.show = t_show,
};
static int show_traces_open(struct inode *inode, struct file *file)
{
struct trace_array *tr = inode->i_private;
struct seq_file *m;
int ret;
if (tracing_disabled)
return -ENODEV;
ret = seq_open(file, &show_traces_seq_ops);
if (ret)
return ret;
m = file->private_data;
m->private = tr;
return 0;
}
static ssize_t
tracing_write_stub(struct file *filp, const char __user *ubuf,
size_t count, loff_t *ppos)
{
return count;
}
loff_t tracing_lseek(struct file *file, loff_t offset, int whence)
{
int ret;
if (file->f_mode & FMODE_READ)
ret = seq_lseek(file, offset, whence);
else
file->f_pos = ret = 0;
return ret;
}
static const struct file_operations tracing_fops = {
.open = tracing_open,
.read = seq_read,
.write = tracing_write_stub,
.llseek = tracing_lseek,
.release = tracing_release,
};
static const struct file_operations show_traces_fops = {
.open = show_traces_open,
.read = seq_read,
.release = seq_release,
.llseek = seq_lseek,
};
static ssize_t
tracing_cpumask_read(struct file *filp, char __user *ubuf,
size_t count, loff_t *ppos)
{
struct trace_array *tr = file_inode(filp)->i_private;
char *mask_str;
int len;
len = snprintf(NULL, 0, "%*pb\n",
cpumask_pr_args(tr->tracing_cpumask)) + 1;
mask_str = kmalloc(len, GFP_KERNEL);
if (!mask_str)
return -ENOMEM;
len = snprintf(mask_str, len, "%*pb\n",
cpumask_pr_args(tr->tracing_cpumask));
if (len >= count) {
count = -EINVAL;
goto out_err;
}
count = simple_read_from_buffer(ubuf, count, ppos, mask_str, len);
out_err:
kfree(mask_str);
return count;
}
static ssize_t
tracing_cpumask_write(struct file *filp, const char __user *ubuf,
size_t count, loff_t *ppos)
{
struct trace_array *tr = file_inode(filp)->i_private;
cpumask_var_t tracing_cpumask_new;
int err, cpu;
if (!alloc_cpumask_var(&tracing_cpumask_new, GFP_KERNEL))
return -ENOMEM;
err = cpumask_parse_user(ubuf, count, tracing_cpumask_new);
if (err)
goto err_unlock;
local_irq_disable();
arch_spin_lock(&tr->max_lock);
for_each_tracing_cpu(cpu) {
/*
* Increase/decrease the disabled counter if we are
* about to flip a bit in the cpumask:
*/
if (cpumask_test_cpu(cpu, tr->tracing_cpumask) &&
!cpumask_test_cpu(cpu, tracing_cpumask_new)) {
atomic_inc(&per_cpu_ptr(tr->trace_buffer.data, cpu)->disabled);
ring_buffer_record_disable_cpu(tr->trace_buffer.buffer, cpu);
}
if (!cpumask_test_cpu(cpu, tr->tracing_cpumask) &&
cpumask_test_cpu(cpu, tracing_cpumask_new)) {
atomic_dec(&per_cpu_ptr(tr->trace_buffer.data, cpu)->disabled);
ring_buffer_record_enable_cpu(tr->trace_buffer.buffer, cpu);
}
}
arch_spin_unlock(&tr->max_lock);
local_irq_enable();
cpumask_copy(tr->tracing_cpumask, tracing_cpumask_new);
free_cpumask_var(tracing_cpumask_new);
return count;
err_unlock:
free_cpumask_var(tracing_cpumask_new);
return err;
}
static const struct file_operations tracing_cpumask_fops = {
.open = tracing_open_generic_tr,
.read = tracing_cpumask_read,
.write = tracing_cpumask_write,
.release = tracing_release_generic_tr,
.llseek = generic_file_llseek,
};
static int tracing_trace_options_show(struct seq_file *m, void *v)
{
struct tracer_opt *trace_opts;
struct trace_array *tr = m->private;
u32 tracer_flags;
int i;
mutex_lock(&trace_types_lock);
tracer_flags = tr->current_trace->flags->val;
trace_opts = tr->current_trace->flags->opts;
for (i = 0; trace_options[i]; i++) {
if (tr->trace_flags & (1 << i))
seq_printf(m, "%s\n", trace_options[i]);
else
seq_printf(m, "no%s\n", trace_options[i]);
}
for (i = 0; trace_opts[i].name; i++) {
if (tracer_flags & trace_opts[i].bit)
seq_printf(m, "%s\n", trace_opts[i].name);
else
seq_printf(m, "no%s\n", trace_opts[i].name);
}
mutex_unlock(&trace_types_lock);
return 0;
}
static int __set_tracer_option(struct trace_array *tr,
struct tracer_flags *tracer_flags,
struct tracer_opt *opts, int neg)
{
struct tracer *trace = tracer_flags->trace;
int ret;
ret = trace->set_flag(tr, tracer_flags->val, opts->bit, !neg);
if (ret)
return ret;
if (neg)
tracer_flags->val &= ~opts->bit;
else
tracer_flags->val |= opts->bit;
return 0;
}
/* Try to assign a tracer specific option */
static int set_tracer_option(struct trace_array *tr, char *cmp, int neg)
{
struct tracer *trace = tr->current_trace;
struct tracer_flags *tracer_flags = trace->flags;
struct tracer_opt *opts = NULL;
int i;
for (i = 0; tracer_flags->opts[i].name; i++) {
opts = &tracer_flags->opts[i];
if (strcmp(cmp, opts->name) == 0)
return __set_tracer_option(tr, trace->flags, opts, neg);
}
return -EINVAL;
}
/* Some tracers require overwrite to stay enabled */
int trace_keep_overwrite(struct tracer *tracer, u32 mask, int set)
{
if (tracer->enabled && (mask & TRACE_ITER_OVERWRITE) && !set)
return -1;
return 0;
}
int set_tracer_flag(struct trace_array *tr, unsigned int mask, int enabled)
{
/* do nothing if flag is already set */
if (!!(tr->trace_flags & mask) == !!enabled)
return 0;
/* Give the tracer a chance to approve the change */
if (tr->current_trace->flag_changed)
if (tr->current_trace->flag_changed(tr, mask, !!enabled))
return -EINVAL;
if (enabled)
tr->trace_flags |= mask;
else
tr->trace_flags &= ~mask;
if (mask == TRACE_ITER_RECORD_CMD)
trace_event_enable_cmd_record(enabled);
if (mask == TRACE_ITER_RECORD_TGID) {
if (!tgid_map)
tgid_map = kcalloc(PID_MAX_DEFAULT + 1,
sizeof(*tgid_map),
GFP_KERNEL);
if (!tgid_map) {
tr->trace_flags &= ~TRACE_ITER_RECORD_TGID;
return -ENOMEM;
}
trace_event_enable_tgid_record(enabled);
}
if (mask == TRACE_ITER_EVENT_FORK)
trace_event_follow_fork(tr, enabled);
if (mask == TRACE_ITER_FUNC_FORK)
ftrace_pid_follow_fork(tr, enabled);
if (mask == TRACE_ITER_OVERWRITE) {
ring_buffer_change_overwrite(tr->trace_buffer.buffer, enabled);
#ifdef CONFIG_TRACER_MAX_TRACE
ring_buffer_change_overwrite(tr->max_buffer.buffer, enabled);
#endif
}
if (mask == TRACE_ITER_PRINTK) {
trace_printk_start_stop_comm(enabled);
trace_printk_control(enabled);
}
return 0;
}
static int trace_set_options(struct trace_array *tr, char *option)
{
char *cmp;
int neg = 0;
int ret;
size_t orig_len = strlen(option);
cmp = strstrip(option);
if (strncmp(cmp, "no", 2) == 0) {
neg = 1;
cmp += 2;
}
mutex_lock(&trace_types_lock);
ret = match_string(trace_options, -1, cmp);
/* If no option could be set, test the specific tracer options */
if (ret < 0)
ret = set_tracer_option(tr, cmp, neg);
else
ret = set_tracer_flag(tr, 1 << ret, !neg);
mutex_unlock(&trace_types_lock);
/*
* If the first trailing whitespace is replaced with '\0' by strstrip,
* turn it back into a space.
*/
if (orig_len > strlen(option))
option[strlen(option)] = ' ';
return ret;
}
static void __init apply_trace_boot_options(void)
{
char *buf = trace_boot_options_buf;
char *option;
while (true) {
option = strsep(&buf, ",");
if (!option)
break;
if (*option)
trace_set_options(&global_trace, option);
/* Put back the comma to allow this to be called again */
if (buf)
*(buf - 1) = ',';
}
}
static ssize_t
tracing_trace_options_write(struct file *filp, const char __user *ubuf,
size_t cnt, loff_t *ppos)
{
struct seq_file *m = filp->private_data;
struct trace_array *tr = m->private;
char buf[64];
int ret;
if (cnt >= sizeof(buf))
return -EINVAL;
if (copy_from_user(buf, ubuf, cnt))
return -EFAULT;
buf[cnt] = 0;
ret = trace_set_options(tr, buf);
if (ret < 0)
return ret;
*ppos += cnt;
return cnt;
}
static int tracing_trace_options_open(struct inode *inode, struct file *file)
{
struct trace_array *tr = inode->i_private;
int ret;
if (tracing_disabled)
return -ENODEV;
if (trace_array_get(tr) < 0)
return -ENODEV;
ret = single_open(file, tracing_trace_options_show, inode->i_private);
if (ret < 0)
trace_array_put(tr);
return ret;
}
static const struct file_operations tracing_iter_fops = {
.open = tracing_trace_options_open,
.read = seq_read,
.llseek = seq_lseek,
.release = tracing_single_release_tr,
.write = tracing_trace_options_write,
};
static const char readme_msg[] =
"tracing mini-HOWTO:\n\n"
"# echo 0 > tracing_on : quick way to disable tracing\n"
"# echo 1 > tracing_on : quick way to re-enable tracing\n\n"
" Important files:\n"
" trace\t\t\t- The static contents of the buffer\n"
"\t\t\t To clear the buffer write into this file: echo > trace\n"
" trace_pipe\t\t- A consuming read to see the contents of the buffer\n"
" current_tracer\t- function and latency tracers\n"
" available_tracers\t- list of configured tracers for current_tracer\n"
" buffer_size_kb\t- view and modify size of per cpu buffer\n"
" buffer_total_size_kb - view total size of all cpu buffers\n\n"
" trace_clock\t\t-change the clock used to order events\n"
" local: Per cpu clock but may not be synced across CPUs\n"
" global: Synced across CPUs but slows tracing down.\n"
" counter: Not a clock, but just an increment\n"
" uptime: Jiffy counter from time of boot\n"
" perf: Same clock that perf events use\n"
#ifdef CONFIG_X86_64
" x86-tsc: TSC cycle counter\n"
#endif
"\n timestamp_mode\t-view the mode used to timestamp events\n"
" delta: Delta difference against a buffer-wide timestamp\n"
" absolute: Absolute (standalone) timestamp\n"
"\n trace_marker\t\t- Writes into this file writes into the kernel buffer\n"
"\n trace_marker_raw\t\t- Writes into this file writes binary data into the kernel buffer\n"
" tracing_cpumask\t- Limit which CPUs to trace\n"
" instances\t\t- Make sub-buffers with: mkdir instances/foo\n"
"\t\t\t Remove sub-buffer with rmdir\n"
" trace_options\t\t- Set format or modify how tracing happens\n"
"\t\t\t Disable an option by adding a suffix 'no' to the\n"
"\t\t\t option name\n"
" saved_cmdlines_size\t- echo command number in here to store comm-pid list\n"
#ifdef CONFIG_DYNAMIC_FTRACE
"\n available_filter_functions - list of functions that can be filtered on\n"
" set_ftrace_filter\t- echo function name in here to only trace these\n"
"\t\t\t functions\n"
"\t accepts: func_full_name or glob-matching-pattern\n"
"\t modules: Can select a group via module\n"
"\t Format: :mod:<module-name>\n"
"\t example: echo :mod:ext3 > set_ftrace_filter\n"
"\t triggers: a command to perform when function is hit\n"
"\t Format: <function>:<trigger>[:count]\n"
"\t trigger: traceon, traceoff\n"
"\t\t enable_event:<system>:<event>\n"
"\t\t disable_event:<system>:<event>\n"
#ifdef CONFIG_STACKTRACE
"\t\t stacktrace\n"
#endif
#ifdef CONFIG_TRACER_SNAPSHOT
"\t\t snapshot\n"
#endif
"\t\t dump\n"
"\t\t cpudump\n"
"\t example: echo do_fault:traceoff > set_ftrace_filter\n"
"\t echo do_trap:traceoff:3 > set_ftrace_filter\n"
"\t The first one will disable tracing every time do_fault is hit\n"
"\t The second will disable tracing at most 3 times when do_trap is hit\n"
"\t The first time do trap is hit and it disables tracing, the\n"
"\t counter will decrement to 2. If tracing is already disabled,\n"
"\t the counter will not decrement. It only decrements when the\n"
"\t trigger did work\n"
"\t To remove trigger without count:\n"
"\t echo '!<function>:<trigger> > set_ftrace_filter\n"
"\t To remove trigger with a count:\n"
"\t echo '!<function>:<trigger>:0 > set_ftrace_filter\n"
" set_ftrace_notrace\t- echo function name in here to never trace.\n"
"\t accepts: func_full_name, *func_end, func_begin*, *func_middle*\n"
"\t modules: Can select a group via module command :mod:\n"
"\t Does not accept triggers\n"
#endif /* CONFIG_DYNAMIC_FTRACE */
#ifdef CONFIG_FUNCTION_TRACER
" set_ftrace_pid\t- Write pid(s) to only function trace those pids\n"
"\t\t (function)\n"
#endif
#ifdef CONFIG_FUNCTION_GRAPH_TRACER
" set_graph_function\t- Trace the nested calls of a function (function_graph)\n"
" set_graph_notrace\t- Do not trace the nested calls of a function (function_graph)\n"
" max_graph_depth\t- Trace a limited depth of nested calls (0 is unlimited)\n"
#endif
#ifdef CONFIG_TRACER_SNAPSHOT
"\n snapshot\t\t- Like 'trace' but shows the content of the static\n"
"\t\t\t snapshot buffer. Read the contents for more\n"
"\t\t\t information\n"
#endif
#ifdef CONFIG_STACK_TRACER
" stack_trace\t\t- Shows the max stack trace when active\n"
" stack_max_size\t- Shows current max stack size that was traced\n"
"\t\t\t Write into this file to reset the max size (trigger a\n"
"\t\t\t new trace)\n"
#ifdef CONFIG_DYNAMIC_FTRACE
" stack_trace_filter\t- Like set_ftrace_filter but limits what stack_trace\n"
"\t\t\t traces\n"
#endif
#endif /* CONFIG_STACK_TRACER */
#ifdef CONFIG_KPROBE_EVENTS
" kprobe_events\t\t- Add/remove/show the kernel dynamic events\n"
"\t\t\t Write into this file to define/undefine new trace events.\n"
#endif
#ifdef CONFIG_UPROBE_EVENTS
" uprobe_events\t\t- Add/remove/show the userspace dynamic events\n"
"\t\t\t Write into this file to define/undefine new trace events.\n"
#endif
#if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS)
"\t accepts: event-definitions (one definition per line)\n"
"\t Format: p[:[<group>/]<event>] <place> [<args>]\n"
"\t r[maxactive][:[<group>/]<event>] <place> [<args>]\n"
"\t -:[<group>/]<event>\n"
#ifdef CONFIG_KPROBE_EVENTS
"\t place: [<module>:]<symbol>[+<offset>]|<memaddr>\n"
"place (kretprobe): [<module>:]<symbol>[+<offset>]|<memaddr>\n"
#endif
#ifdef CONFIG_UPROBE_EVENTS
"\t place: <path>:<offset>\n"
#endif
"\t args: <name>=fetcharg[:type]\n"
"\t fetcharg: %<register>, @<address>, @<symbol>[+|-<offset>],\n"
"\t $stack<index>, $stack, $retval, $comm\n"
"\t type: s8/16/32/64, u8/16/32/64, x8/16/32/64, string,\n"
"\t b<bit-width>@<bit-offset>/<container-size>\n"
#endif
" events/\t\t- Directory containing all trace event subsystems:\n"
" enable\t\t- Write 0/1 to enable/disable tracing of all events\n"
" events/<system>/\t- Directory containing all trace events for <system>:\n"
" enable\t\t- Write 0/1 to enable/disable tracing of all <system>\n"
"\t\t\t events\n"
" filter\t\t- If set, only events passing filter are traced\n"
" events/<system>/<event>/\t- Directory containing control files for\n"
"\t\t\t <event>:\n"
" enable\t\t- Write 0/1 to enable/disable tracing of <event>\n"
" filter\t\t- If set, only events passing filter are traced\n"
" trigger\t\t- If set, a command to perform when event is hit\n"
"\t Format: <trigger>[:count][if <filter>]\n"
"\t trigger: traceon, traceoff\n"
"\t enable_event:<system>:<event>\n"
"\t disable_event:<system>:<event>\n"
#ifdef CONFIG_HIST_TRIGGERS
"\t enable_hist:<system>:<event>\n"
"\t disable_hist:<system>:<event>\n"
#endif
#ifdef CONFIG_STACKTRACE
"\t\t stacktrace\n"
#endif
#ifdef CONFIG_TRACER_SNAPSHOT
"\t\t snapshot\n"
#endif
#ifdef CONFIG_HIST_TRIGGERS
"\t\t hist (see below)\n"
#endif
"\t example: echo traceoff > events/block/block_unplug/trigger\n"
"\t echo traceoff:3 > events/block/block_unplug/trigger\n"
"\t echo 'enable_event:kmem:kmalloc:3 if nr_rq > 1' > \\\n"
"\t events/block/block_unplug/trigger\n"
"\t The first disables tracing every time block_unplug is hit.\n"
"\t The second disables tracing the first 3 times block_unplug is hit.\n"
"\t The third enables the kmalloc event the first 3 times block_unplug\n"
"\t is hit and has value of greater than 1 for the 'nr_rq' event field.\n"
"\t Like function triggers, the counter is only decremented if it\n"
"\t enabled or disabled tracing.\n"
"\t To remove a trigger without a count:\n"
"\t echo '!<trigger> > <system>/<event>/trigger\n"
"\t To remove a trigger with a count:\n"
"\t echo '!<trigger>:0 > <system>/<event>/trigger\n"
"\t Filters can be ignored when removing a trigger.\n"
#ifdef CONFIG_HIST_TRIGGERS
" hist trigger\t- If set, event hits are aggregated into a hash table\n"
"\t Format: hist:keys=<field1[,field2,...]>\n"
"\t [:values=<field1[,field2,...]>]\n"
"\t [:sort=<field1[,field2,...]>]\n"
"\t [:size=#entries]\n"
"\t [:pause][:continue][:clear]\n"
"\t [:name=histname1]\n"
"\t [if <filter>]\n\n"
"\t When a matching event is hit, an entry is added to a hash\n"
"\t table using the key(s) and value(s) named, and the value of a\n"
"\t sum called 'hitcount' is incremented. Keys and values\n"
"\t correspond to fields in the event's format description. Keys\n"
"\t can be any field, or the special string 'stacktrace'.\n"
"\t Compound keys consisting of up to two fields can be specified\n"
"\t by the 'keys' keyword. Values must correspond to numeric\n"
"\t fields. Sort keys consisting of up to two fields can be\n"
"\t specified using the 'sort' keyword. The sort direction can\n"
"\t be modified by appending '.descending' or '.ascending' to a\n"
"\t sort field. The 'size' parameter can be used to specify more\n"
"\t or fewer than the default 2048 entries for the hashtable size.\n"
"\t If a hist trigger is given a name using the 'name' parameter,\n"
"\t its histogram data will be shared with other triggers of the\n"
"\t same name, and trigger hits will update this common data.\n\n"
"\t Reading the 'hist' file for the event will dump the hash\n"
"\t table in its entirety to stdout. If there are multiple hist\n"
"\t triggers attached to an event, there will be a table for each\n"
"\t trigger in the output. The table displayed for a named\n"
"\t trigger will be the same as any other instance having the\n"
"\t same name. The default format used to display a given field\n"
"\t can be modified by appending any of the following modifiers\n"
"\t to the field name, as applicable:\n\n"
"\t .hex display a number as a hex value\n"
"\t .sym display an address as a symbol\n"
"\t .sym-offset display an address as a symbol and offset\n"
"\t .execname display a common_pid as a program name\n"
"\t .syscall display a syscall id as a syscall name\n"
"\t .log2 display log2 value rather than raw number\n"
"\t .usecs display a common_timestamp in microseconds\n\n"
"\t The 'pause' parameter can be used to pause an existing hist\n"
"\t trigger or to start a hist trigger but not log any events\n"
"\t until told to do so. 'continue' can be used to start or\n"
"\t restart a paused hist trigger.\n\n"
"\t The 'clear' parameter will clear the contents of a running\n"
"\t hist trigger and leave its current paused/active state\n"
"\t unchanged.\n\n"
"\t The enable_hist and disable_hist triggers can be used to\n"
"\t have one event conditionally start and stop another event's\n"
"\t already-attached hist trigger. The syntax is analagous to\n"
"\t the enable_event and disable_event triggers.\n"
#endif
;
static ssize_t
tracing_readme_read(struct file *filp, char __user *ubuf,
size_t cnt, loff_t *ppos)
{
return simple_read_from_buffer(ubuf, cnt, ppos,
readme_msg, strlen(readme_msg));
}
static const struct file_operations tracing_readme_fops = {
.open = tracing_open_generic,
.read = tracing_readme_read,
.llseek = generic_file_llseek,
};
static void *saved_tgids_next(struct seq_file *m, void *v, loff_t *pos)
{
int *ptr = v;
if (*pos || m->count)
ptr++;
(*pos)++;
for (; ptr <= &tgid_map[PID_MAX_DEFAULT]; ptr++) {
if (trace_find_tgid(*ptr))
return ptr;
}
return NULL;
}
static void *saved_tgids_start(struct seq_file *m, loff_t *pos)
{
void *v;
loff_t l = 0;
if (!tgid_map)
return NULL;
v = &tgid_map[0];
while (l <= *pos) {
v = saved_tgids_next(m, v, &l);
if (!v)
return NULL;
}
return v;
}
static void saved_tgids_stop(struct seq_file *m, void *v)
{
}
static int saved_tgids_show(struct seq_file *m, void *v)
{
int pid = (int *)v - tgid_map;
seq_printf(m, "%d %d\n", pid, trace_find_tgid(pid));
return 0;
}
static const struct seq_operations tracing_saved_tgids_seq_ops = {
.start = saved_tgids_start,
.stop = saved_tgids_stop,
.next = saved_tgids_next,
.show = saved_tgids_show,
};
static int tracing_saved_tgids_open(struct inode *inode, struct file *filp)
{
if (tracing_disabled)
return -ENODEV;
return seq_open(filp, &tracing_saved_tgids_seq_ops);
}
static const struct file_operations tracing_saved_tgids_fops = {
.open = tracing_saved_tgids_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
static void *saved_cmdlines_next(struct seq_file *m, void *v, loff_t *pos)
{
unsigned int *ptr = v;
if (*pos || m->count)
ptr++;
(*pos)++;
for (; ptr < &savedcmd->map_cmdline_to_pid[savedcmd->cmdline_num];
ptr++) {
if (*ptr == -1 || *ptr == NO_CMDLINE_MAP)
continue;
return ptr;
}
return NULL;
}
static void *saved_cmdlines_start(struct seq_file *m, loff_t *pos)
{
void *v;
loff_t l = 0;
preempt_disable();
arch_spin_lock(&trace_cmdline_lock);
v = &savedcmd->map_cmdline_to_pid[0];
while (l <= *pos) {
v = saved_cmdlines_next(m, v, &l);
if (!v)
return NULL;
}
return v;
}
static void saved_cmdlines_stop(struct seq_file *m, void *v)
{
arch_spin_unlock(&trace_cmdline_lock);
preempt_enable();
}
static int saved_cmdlines_show(struct seq_file *m, void *v)
{
char buf[TASK_COMM_LEN];
unsigned int *pid = v;
__trace_find_cmdline(*pid, buf);
seq_printf(m, "%d %s\n", *pid, buf);
return 0;
}
static const struct seq_operations tracing_saved_cmdlines_seq_ops = {
.start = saved_cmdlines_start,
.next = saved_cmdlines_next,
.stop = saved_cmdlines_stop,
.show = saved_cmdlines_show,
};
static int tracing_saved_cmdlines_open(struct inode *inode, struct file *filp)
{
if (tracing_disabled)
return -ENODEV;
return seq_open(filp, &tracing_saved_cmdlines_seq_ops);
}
static const struct file_operations tracing_saved_cmdlines_fops = {
.open = tracing_saved_cmdlines_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
static ssize_t
tracing_saved_cmdlines_size_read(struct file *filp, char __user *ubuf,
size_t cnt, loff_t *ppos)
{
char buf[64];
int r;
arch_spin_lock(&trace_cmdline_lock);
r = scnprintf(buf, sizeof(buf), "%u\n", savedcmd->cmdline_num);
arch_spin_unlock(&trace_cmdline_lock);
return simple_read_from_buffer(ubuf, cnt, ppos, buf, r);
}
static void free_saved_cmdlines_buffer(struct saved_cmdlines_buffer *s)
{
kfree(s->saved_cmdlines);
kfree(s->map_cmdline_to_pid);
kfree(s);
}
static int tracing_resize_saved_cmdlines(unsigned int val)
{
struct saved_cmdlines_buffer *s, *savedcmd_temp;
s = kmalloc(sizeof(*s), GFP_KERNEL);
if (!s)
return -ENOMEM;
if (allocate_cmdlines_buffer(val, s) < 0) {
kfree(s);
return -ENOMEM;
}
arch_spin_lock(&trace_cmdline_lock);
savedcmd_temp = savedcmd;
savedcmd = s;
arch_spin_unlock(&trace_cmdline_lock);
free_saved_cmdlines_buffer(savedcmd_temp);
return 0;
}
static ssize_t
tracing_saved_cmdlines_size_write(struct file *filp, const char __user *ubuf,
size_t cnt, loff_t *ppos)
{
unsigned long val;
int ret;
ret = kstrtoul_from_user(ubuf, cnt, 10, &val);
if (ret)
return ret;
/* must have at least 1 entry or less than PID_MAX_DEFAULT */
if (!val || val > PID_MAX_DEFAULT)
return -EINVAL;
ret = tracing_resize_saved_cmdlines((unsigned int)val);
if (ret < 0)
return ret;
*ppos += cnt;
return cnt;
}
static const struct file_operations tracing_saved_cmdlines_size_fops = {
.open = tracing_open_generic,
.read = tracing_saved_cmdlines_size_read,
.write = tracing_saved_cmdlines_size_write,
};
#ifdef CONFIG_TRACE_EVAL_MAP_FILE
static union trace_eval_map_item *
update_eval_map(union trace_eval_map_item *ptr)
{
if (!ptr->map.eval_string) {
if (ptr->tail.next) {
ptr = ptr->tail.next;
/* Set ptr to the next real item (skip head) */
ptr++;
} else
return NULL;
}
return ptr;
}
static void *eval_map_next(struct seq_file *m, void *v, loff_t *pos)
{
union trace_eval_map_item *ptr = v;
/*
* Paranoid! If ptr points to end, we don't want to increment past it.
* This really should never happen.
*/
ptr = update_eval_map(ptr);
if (WARN_ON_ONCE(!ptr))
return NULL;
ptr++;
(*pos)++;
ptr = update_eval_map(ptr);
return ptr;
}
static void *eval_map_start(struct seq_file *m, loff_t *pos)
{
union trace_eval_map_item *v;
loff_t l = 0;
mutex_lock(&trace_eval_mutex);
v = trace_eval_maps;
if (v)
v++;
while (v && l < *pos) {
v = eval_map_next(m, v, &l);
}
return v;
}
static void eval_map_stop(struct seq_file *m, void *v)
{
mutex_unlock(&trace_eval_mutex);
}
static int eval_map_show(struct seq_file *m, void *v)
{
union trace_eval_map_item *ptr = v;
seq_printf(m, "%s %ld (%s)\n",
ptr->map.eval_string, ptr->map.eval_value,
ptr->map.system);
return 0;
}
static const struct seq_operations tracing_eval_map_seq_ops = {
.start = eval_map_start,
.next = eval_map_next,
.stop = eval_map_stop,
.show = eval_map_show,
};
static int tracing_eval_map_open(struct inode *inode, struct file *filp)
{
if (tracing_disabled)
return -ENODEV;
return seq_open(filp, &tracing_eval_map_seq_ops);
}
static const struct file_operations tracing_eval_map_fops = {
.open = tracing_eval_map_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
static inline union trace_eval_map_item *
trace_eval_jmp_to_tail(union trace_eval_map_item *ptr)
{
/* Return tail of array given the head */
return ptr + ptr->head.length + 1;
}
static void
trace_insert_eval_map_file(struct module *mod, struct trace_eval_map **start,
int len)
{
struct trace_eval_map **stop;
struct trace_eval_map **map;
union trace_eval_map_item *map_array;
union trace_eval_map_item *ptr;
stop = start + len;
/*
* The trace_eval_maps contains the map plus a head and tail item,
* where the head holds the module and length of array, and the
* tail holds a pointer to the next list.
*/
map_array = kmalloc_array(len + 2, sizeof(*map_array), GFP_KERNEL);
if (!map_array) {
pr_warn("Unable to allocate trace eval mapping\n");
return;
}
mutex_lock(&trace_eval_mutex);
if (!trace_eval_maps)
trace_eval_maps = map_array;
else {
ptr = trace_eval_maps;
for (;;) {
ptr = trace_eval_jmp_to_tail(ptr);
if (!ptr->tail.next)
break;
ptr = ptr->tail.next;
}
ptr->tail.next = map_array;
}
map_array->head.mod = mod;
map_array->head.length = len;
map_array++;
for (map = start; (unsigned long)map < (unsigned long)stop; map++) {
map_array->map = **map;
map_array++;
}
memset(map_array, 0, sizeof(*map_array));
mutex_unlock(&trace_eval_mutex);
}
static void trace_create_eval_file(struct dentry *d_tracer)
{
trace_create_file("eval_map", 0444, d_tracer,
NULL, &tracing_eval_map_fops);
}
#else /* CONFIG_TRACE_EVAL_MAP_FILE */
static inline void trace_create_eval_file(struct dentry *d_tracer) { }
static inline void trace_insert_eval_map_file(struct module *mod,
struct trace_eval_map **start, int len) { }
#endif /* !CONFIG_TRACE_EVAL_MAP_FILE */
static void trace_insert_eval_map(struct module *mod,
struct trace_eval_map **start, int len)
{
struct trace_eval_map **map;
if (len <= 0)
return;
map = start;
trace_event_eval_update(map, len);
trace_insert_eval_map_file(mod, start, len);
}
static ssize_t
tracing_set_trace_read(struct file *filp, char __user *ubuf,
size_t cnt, loff_t *ppos)
{
struct trace_array *tr = filp->private_data;
char buf[MAX_TRACER_SIZE+2];
int r;
mutex_lock(&trace_types_lock);
r = sprintf(buf, "%s\n", tr->current_trace->name);
mutex_unlock(&trace_types_lock);
return simple_read_from_buffer(ubuf, cnt, ppos, buf, r);
}
int tracer_init(struct tracer *t, struct trace_array *tr)
{
tracing_reset_online_cpus(&tr->trace_buffer);
return t->init(tr);
}
static void set_buffer_entries(struct trace_buffer *buf, unsigned long val)
{
int cpu;
for_each_tracing_cpu(cpu)
per_cpu_ptr(buf->data, cpu)->entries = val;
}
#ifdef CONFIG_TRACER_MAX_TRACE
/* resize @tr's buffer to the size of @size_tr's entries */
static int resize_buffer_duplicate_size(struct trace_buffer *trace_buf,
struct trace_buffer *size_buf, int cpu_id)
{
int cpu, ret = 0;
if (cpu_id == RING_BUFFER_ALL_CPUS) {
for_each_tracing_cpu(cpu) {
ret = ring_buffer_resize(trace_buf->buffer,
per_cpu_ptr(size_buf->data, cpu)->entries, cpu);
if (ret < 0)
break;
per_cpu_ptr(trace_buf->data, cpu)->entries =
per_cpu_ptr(size_buf->data, cpu)->entries;
}
} else {
ret = ring_buffer_resize(trace_buf->buffer,
per_cpu_ptr(size_buf->data, cpu_id)->entries, cpu_id);
if (ret == 0)
per_cpu_ptr(trace_buf->data, cpu_id)->entries =
per_cpu_ptr(size_buf->data, cpu_id)->entries;
}
return ret;
}
#endif /* CONFIG_TRACER_MAX_TRACE */
static int __tracing_resize_ring_buffer(struct trace_array *tr,
unsigned long size, int cpu)
{
int ret;
/*
* If kernel or user changes the size of the ring buffer
* we use the size that was given, and we can forget about
* expanding it later.
*/
ring_buffer_expanded = true;
/* May be called before buffers are initialized */
if (!tr->trace_buffer.buffer)
return 0;
ret = ring_buffer_resize(tr->trace_buffer.buffer, size, cpu);
if (ret < 0)
return ret;
#ifdef CONFIG_TRACER_MAX_TRACE
if (!(tr->flags & TRACE_ARRAY_FL_GLOBAL) ||
!tr->current_trace->use_max_tr)
goto out;
ret = ring_buffer_resize(tr->max_buffer.buffer, size, cpu);
if (ret < 0) {
int r = resize_buffer_duplicate_size(&tr->trace_buffer,
&tr->trace_buffer, cpu);
if (r < 0) {
/*
* AARGH! We are left with different
* size max buffer!!!!
* The max buffer is our "snapshot" buffer.
* When a tracer needs a snapshot (one of the
* latency tracers), it swaps the max buffer
* with the saved snap shot. We succeeded to
* update the size of the main buffer, but failed to
* update the size of the max buffer. But when we tried
* to reset the main buffer to the original size, we
* failed there too. This is very unlikely to
* happen, but if it does, warn and kill all
* tracing.
*/
WARN_ON(1);
tracing_disabled = 1;
}
return ret;
}
if (cpu == RING_BUFFER_ALL_CPUS)
set_buffer_entries(&tr->max_buffer, size);
else
per_cpu_ptr(tr->max_buffer.data, cpu)->entries = size;
out:
#endif /* CONFIG_TRACER_MAX_TRACE */
if (cpu == RING_BUFFER_ALL_CPUS)
set_buffer_entries(&tr->trace_buffer, size);
else
per_cpu_ptr(tr->trace_buffer.data, cpu)->entries = size;
return ret;
}
static ssize_t tracing_resize_ring_buffer(struct trace_array *tr,
unsigned long size, int cpu_id)
{
int ret = size;
mutex_lock(&trace_types_lock);
if (cpu_id != RING_BUFFER_ALL_CPUS) {
/* make sure, this cpu is enabled in the mask */
if (!cpumask_test_cpu(cpu_id, tracing_buffer_mask)) {
ret = -EINVAL;
goto out;
}
}
ret = __tracing_resize_ring_buffer(tr, size, cpu_id);
if (ret < 0)
ret = -ENOMEM;
out:
mutex_unlock(&trace_types_lock);
return ret;
}
/**
* tracing_update_buffers - used by tracing facility to expand ring buffers
*
* To save on memory when the tracing is never used on a system with it
* configured in. The ring buffers are set to a minimum size. But once
* a user starts to use the tracing facility, then they need to grow
* to their default size.
*
* This function is to be called when a tracer is about to be used.
*/
int tracing_update_buffers(void)
{
int ret = 0;
mutex_lock(&trace_types_lock);
if (!ring_buffer_expanded)
ret = __tracing_resize_ring_buffer(&global_trace, trace_buf_size,
RING_BUFFER_ALL_CPUS);
mutex_unlock(&trace_types_lock);
return ret;
}
struct trace_option_dentry;
static void
create_trace_option_files(struct trace_array *tr, struct tracer *tracer);
/*
* Used to clear out the tracer before deletion of an instance.
* Must have trace_types_lock held.
*/
static void tracing_set_nop(struct trace_array *tr)
{
if (tr->current_trace == &nop_trace)
return;
tr->current_trace->enabled--;
if (tr->current_trace->reset)
tr->current_trace->reset(tr);
tr->current_trace = &nop_trace;
}
static void add_tracer_options(struct trace_array *tr, struct tracer *t)
{
/* Only enable if the directory has been created already. */
if (!tr->dir)
return;
create_trace_option_files(tr, t);
}
static int tracing_set_tracer(struct trace_array *tr, const char *buf)
{
struct tracer *t;
#ifdef CONFIG_TRACER_MAX_TRACE
bool had_max_tr;
#endif
int ret = 0;
mutex_lock(&trace_types_lock);
if (!ring_buffer_expanded) {
ret = __tracing_resize_ring_buffer(tr, trace_buf_size,
RING_BUFFER_ALL_CPUS);
if (ret < 0)
goto out;
ret = 0;
}
for (t = trace_types; t; t = t->next) {
if (strcmp(t->name, buf) == 0)
break;
}
if (!t) {
ret = -EINVAL;
goto out;
}
if (t == tr->current_trace)
goto out;
/* Some tracers won't work on kernel command line */
if (system_state < SYSTEM_RUNNING && t->noboot) {
pr_warn("Tracer '%s' is not allowed on command line, ignored\n",
t->name);
goto out;
}
/* Some tracers are only allowed for the top level buffer */
if (!trace_ok_for_array(t, tr)) {
ret = -EINVAL;
goto out;
}
/* If trace pipe files are being read, we can't change the tracer */
if (tr->current_trace->ref) {
ret = -EBUSY;
goto out;
}
trace_branch_disable();
tr->current_trace->enabled--;
if (tr->current_trace->reset)
tr->current_trace->reset(tr);
/* Current trace needs to be nop_trace before synchronize_sched */
tr->current_trace = &nop_trace;
#ifdef CONFIG_TRACER_MAX_TRACE
had_max_tr = tr->allocated_snapshot;
if (had_max_tr && !t->use_max_tr) {
/*
* We need to make sure that the update_max_tr sees that
* current_trace changed to nop_trace to keep it from
* swapping the buffers after we resize it.
* The update_max_tr is called from interrupts disabled
* so a synchronized_sched() is sufficient.
*/
synchronize_sched();
free_snapshot(tr);
}
#endif
#ifdef CONFIG_TRACER_MAX_TRACE
if (t->use_max_tr && !had_max_tr) {
ret = tracing_alloc_snapshot_instance(tr);
if (ret < 0)
goto out;
}
#endif
if (t->init) {
ret = tracer_init(t, tr);
if (ret)
goto out;
}
tr->current_trace = t;
tr->current_trace->enabled++;
trace_branch_enable(tr);
out:
mutex_unlock(&trace_types_lock);
return ret;
}
static ssize_t
tracing_set_trace_write(struct file *filp, const char __user *ubuf,
size_t cnt, loff_t *ppos)
{
struct trace_array *tr = filp->private_data;
char buf[MAX_TRACER_SIZE+1];
int i;
size_t ret;
int err;
ret = cnt;
if (cnt > MAX_TRACER_SIZE)
cnt = MAX_TRACER_SIZE;
if (copy_from_user(buf, ubuf, cnt))
return -EFAULT;
buf[cnt] = 0;
/* strip ending whitespace. */
for (i = cnt - 1; i > 0 && isspace(buf[i]); i--)
buf[i] = 0;
err = tracing_set_tracer(tr, buf);
if (err)
return err;
*ppos += ret;
return ret;
}
static ssize_t
tracing_nsecs_read(unsigned long *ptr, char __user *ubuf,
size_t cnt, loff_t *ppos)
{
char buf[64];
int r;
r = snprintf(buf, sizeof(buf), "%ld\n",
*ptr == (unsigned long)-1 ? -1 : nsecs_to_usecs(*ptr));
if (r > sizeof(buf))
r = sizeof(buf);
return simple_read_from_buffer(ubuf, cnt, ppos, buf, r);
}
static ssize_t
tracing_nsecs_write(unsigned long *ptr, const char __user *ubuf,
size_t cnt, loff_t *ppos)
{
unsigned long val;
int ret;
ret = kstrtoul_from_user(ubuf, cnt, 10, &val);
if (ret)
return ret;
*ptr = val * 1000;
return cnt;
}
static ssize_t
tracing_thresh_read(struct file *filp, char __user *ubuf,
size_t cnt, loff_t *ppos)
{
return tracing_nsecs_read(&tracing_thresh, ubuf, cnt, ppos);
}
static ssize_t
tracing_thresh_write(struct file *filp, const char __user *ubuf,
size_t cnt, loff_t *ppos)
{
struct trace_array *tr = filp->private_data;
int ret;
mutex_lock(&trace_types_lock);
ret = tracing_nsecs_write(&tracing_thresh, ubuf, cnt, ppos);
if (ret < 0)
goto out;
if (tr->current_trace->update_thresh) {
ret = tr->current_trace->update_thresh(tr);
if (ret < 0)
goto out;
}
ret = cnt;
out:
mutex_unlock(&trace_types_lock);
return ret;
}
#if defined(CONFIG_TRACER_MAX_TRACE) || defined(CONFIG_HWLAT_TRACER)
static ssize_t
tracing_max_lat_read(struct file *filp, char __user *ubuf,
size_t cnt, loff_t *ppos)
{
return tracing_nsecs_read(filp->private_data, ubuf, cnt, ppos);
}
static ssize_t
tracing_max_lat_write(struct file *filp, const char __user *ubuf,
size_t cnt, loff_t *ppos)
{
return tracing_nsecs_write(filp->private_data, ubuf, cnt, ppos);
}
#endif
static int tracing_open_pipe(struct inode *inode, struct file *filp)
{
struct trace_array *tr = inode->i_private;
struct trace_iterator *iter;
int ret = 0;
if (tracing_disabled)
return -ENODEV;
if (trace_array_get(tr) < 0)
return -ENODEV;
mutex_lock(&trace_types_lock);
/* create a buffer to store the information to pass to userspace */
iter = kzalloc(sizeof(*iter), GFP_KERNEL);
if (!iter) {
ret = -ENOMEM;
__trace_array_put(tr);
goto out;
}
trace_seq_init(&iter->seq);
iter->trace = tr->current_trace;
if (!alloc_cpumask_var(&iter->started, GFP_KERNEL)) {
ret = -ENOMEM;
goto fail;
}
/* trace pipe does not show start of buffer */
cpumask_setall(iter->started);
if (tr->trace_flags & TRACE_ITER_LATENCY_FMT)
iter->iter_flags |= TRACE_FILE_LAT_FMT;
/* Output in nanoseconds only if we are using a clock in nanoseconds. */
if (trace_clocks[tr->clock_id].in_ns)
iter->iter_flags |= TRACE_FILE_TIME_IN_NS;
iter->tr = tr;
iter->trace_buffer = &tr->trace_buffer;
iter->cpu_file = tracing_get_cpu(inode);
mutex_init(&iter->mutex);
filp->private_data = iter;
if (iter->trace->pipe_open)
iter->trace->pipe_open(iter);
nonseekable_open(inode, filp);
tr->current_trace->ref++;
out:
mutex_unlock(&trace_types_lock);
return ret;
fail:
kfree(iter->trace);
kfree(iter);
__trace_array_put(tr);
mutex_unlock(&trace_types_lock);
return ret;
}
static int tracing_release_pipe(struct inode *inode, struct file *file)
{
struct trace_iterator *iter = file->private_data;
struct trace_array *tr = inode->i_private;
mutex_lock(&trace_types_lock);
tr->current_trace->ref--;
if (iter->trace->pipe_close)
iter->trace->pipe_close(iter);
mutex_unlock(&trace_types_lock);
free_cpumask_var(iter->started);
mutex_destroy(&iter->mutex);
kfree(iter);
trace_array_put(tr);
return 0;
}
static __poll_t
trace_poll(struct trace_iterator *iter, struct file *filp, poll_table *poll_table)
{
struct trace_array *tr = iter->tr;
/* Iterators are static, they should be filled or empty */
if (trace_buffer_iter(iter, iter->cpu_file))
return EPOLLIN | EPOLLRDNORM;
if (tr->trace_flags & TRACE_ITER_BLOCK)
/*
* Always select as readable when in blocking mode
*/
return EPOLLIN | EPOLLRDNORM;
else
return ring_buffer_poll_wait(iter->trace_buffer->buffer, iter->cpu_file,
filp, poll_table);
}
static __poll_t
tracing_poll_pipe(struct file *filp, poll_table *poll_table)
{
struct trace_iterator *iter = filp->private_data;
return trace_poll(iter, filp, poll_table);
}
/* Must be called with iter->mutex held. */
static int tracing_wait_pipe(struct file *filp)
{
struct trace_iterator *iter = filp->private_data;
int ret;
while (trace_empty(iter)) {
if ((filp->f_flags & O_NONBLOCK)) {
return -EAGAIN;
}
/*
* We block until we read something and tracing is disabled.
* We still block if tracing is disabled, but we have never
* read anything. This allows a user to cat this file, and
* then enable tracing. But after we have read something,
* we give an EOF when tracing is again disabled.
*
* iter->pos will be 0 if we haven't read anything.
*/
if (!tracer_tracing_is_on(iter->tr) && iter->pos)
break;
mutex_unlock(&iter->mutex);
ret = wait_on_pipe(iter, false);
mutex_lock(&iter->mutex);
if (ret)
return ret;
}
return 1;
}
/*
* Consumer reader.
*/
static ssize_t
tracing_read_pipe(struct file *filp, char __user *ubuf,
size_t cnt, loff_t *ppos)
{
struct trace_iterator *iter = filp->private_data;
ssize_t sret;
/*
* Avoid more than one consumer on a single file descriptor
* This is just a matter of traces coherency, the ring buffer itself
* is protected.
*/
mutex_lock(&iter->mutex);
/* return any leftover data */
sret = trace_seq_to_user(&iter->seq, ubuf, cnt);
if (sret != -EBUSY)
goto out;
trace_seq_init(&iter->seq);
if (iter->trace->read) {
sret = iter->trace->read(iter, filp, ubuf, cnt, ppos);
if (sret)
goto out;
}
waitagain:
sret = tracing_wait_pipe(filp);
if (sret <= 0)
goto out;
/* stop when tracing is finished */
if (trace_empty(iter)) {
sret = 0;
goto out;
}
if (cnt >= PAGE_SIZE)
cnt = PAGE_SIZE - 1;
/* reset all but tr, trace, and overruns */
memset(&iter->seq, 0,
sizeof(struct trace_iterator) -
offsetof(struct trace_iterator, seq));
cpumask_clear(iter->started);
iter->pos = -1;
trace_event_read_lock();
trace_access_lock(iter->cpu_file);
while (trace_find_next_entry_inc(iter) != NULL) {
enum print_line_t ret;
int save_len = iter->seq.seq.len;
ret = print_trace_line(iter);
if (ret == TRACE_TYPE_PARTIAL_LINE) {
/* don't print partial lines */
iter->seq.seq.len = save_len;
break;
}
if (ret != TRACE_TYPE_NO_CONSUME)
trace_consume(iter);
if (trace_seq_used(&iter->seq) >= cnt)
break;
/*
* Setting the full flag means we reached the trace_seq buffer
* size and we should leave by partial output condition above.
* One of the trace_seq_* functions is not used properly.
*/
WARN_ONCE(iter->seq.full, "full flag set for trace type %d",
iter->ent->type);
}
trace_access_unlock(iter->cpu_file);
trace_event_read_unlock();
/* Now copy what we have to the user */
sret = trace_seq_to_user(&iter->seq, ubuf, cnt);
if (iter->seq.seq.readpos >= trace_seq_used(&iter->seq))
trace_seq_init(&iter->seq);
/*
* If there was nothing to send to user, in spite of consuming trace
* entries, go back to wait for more entries.
*/
if (sret == -EBUSY)
goto waitagain;
out:
mutex_unlock(&iter->mutex);
return sret;
}
static void tracing_spd_release_pipe(struct splice_pipe_desc *spd,
unsigned int idx)
{
__free_page(spd->pages[idx]);
}
static const struct pipe_buf_operations tracing_pipe_buf_ops = {
.can_merge = 0,
.confirm = generic_pipe_buf_confirm,
.release = generic_pipe_buf_release,
.steal = generic_pipe_buf_steal,
.get = generic_pipe_buf_get,
};
static size_t
tracing_fill_pipe_page(size_t rem, struct trace_iterator *iter)
{
size_t count;
int save_len;
int ret;
/* Seq buffer is page-sized, exactly what we need. */
for (;;) {
save_len = iter->seq.seq.len;
ret = print_trace_line(iter);
if (trace_seq_has_overflowed(&iter->seq)) {
iter->seq.seq.len = save_len;
break;
}
/*
* This should not be hit, because it should only
* be set if the iter->seq overflowed. But check it
* anyway to be safe.
*/
if (ret == TRACE_TYPE_PARTIAL_LINE) {
iter->seq.seq.len = save_len;
break;
}
count = trace_seq_used(&iter->seq) - save_len;
if (rem < count) {
rem = 0;
iter->seq.seq.len = save_len;
break;
}
if (ret != TRACE_TYPE_NO_CONSUME)
trace_consume(iter);
rem -= count;
if (!trace_find_next_entry_inc(iter)) {
rem = 0;
iter->ent = NULL;
break;
}
}
return rem;
}
static ssize_t tracing_splice_read_pipe(struct file *filp,
loff_t *ppos,
struct pipe_inode_info *pipe,
size_t len,
unsigned int flags)
{
struct page *pages_def[PIPE_DEF_BUFFERS];
struct partial_page partial_def[PIPE_DEF_BUFFERS];
struct trace_iterator *iter = filp->private_data;
struct splice_pipe_desc spd = {
.pages = pages_def,
.partial = partial_def,
.nr_pages = 0, /* This gets updated below. */
.nr_pages_max = PIPE_DEF_BUFFERS,
.ops = &tracing_pipe_buf_ops,
.spd_release = tracing_spd_release_pipe,
};
ssize_t ret;
size_t rem;
unsigned int i;
if (splice_grow_spd(pipe, &spd))
return -ENOMEM;
mutex_lock(&iter->mutex);
if (iter->trace->splice_read) {
ret = iter->trace->splice_read(iter, filp,
ppos, pipe, len, flags);
if (ret)
goto out_err;
}
ret = tracing_wait_pipe(filp);
if (ret <= 0)
goto out_err;
if (!iter->ent && !trace_find_next_entry_inc(iter)) {
ret = -EFAULT;
goto out_err;
}
trace_event_read_lock();
trace_access_lock(iter->cpu_file);
/* Fill as many pages as possible. */
for (i = 0, rem = len; i < spd.nr_pages_max && rem; i++) {
spd.pages[i] = alloc_page(GFP_KERNEL);
if (!spd.pages[i])
break;
rem = tracing_fill_pipe_page(rem, iter);
/* Copy the data into the page, so we can start over. */
ret = trace_seq_to_buffer(&iter->seq,
page_address(spd.pages[i]),
trace_seq_used(&iter->seq));
if (ret < 0) {
__free_page(spd.pages[i]);
break;
}
spd.partial[i].offset = 0;
spd.partial[i].len = trace_seq_used(&iter->seq);
trace_seq_init(&iter->seq);
}
trace_access_unlock(iter->cpu_file);
trace_event_read_unlock();
mutex_unlock(&iter->mutex);
spd.nr_pages = i;
if (i)
ret = splice_to_pipe(pipe, &spd);
else
ret = 0;
out:
splice_shrink_spd(&spd);
return ret;
out_err:
mutex_unlock(&iter->mutex);
goto out;
}
static ssize_t
tracing_entries_read(struct file *filp, char __user *ubuf,
size_t cnt, loff_t *ppos)
{
struct inode *inode = file_inode(filp);
struct trace_array *tr = inode->i_private;
int cpu = tracing_get_cpu(inode);
char buf[64];
int r = 0;
ssize_t ret;
mutex_lock(&trace_types_lock);
if (cpu == RING_BUFFER_ALL_CPUS) {
int cpu, buf_size_same;
unsigned long size;
size = 0;
buf_size_same = 1;
/* check if all cpu sizes are same */
for_each_tracing_cpu(cpu) {
/* fill in the size from first enabled cpu */
if (size == 0)
size = per_cpu_ptr(tr->trace_buffer.data, cpu)->entries;
if (size != per_cpu_ptr(tr->trace_buffer.data, cpu)->entries) {
buf_size_same = 0;
break;
}
}
if (buf_size_same) {
if (!ring_buffer_expanded)
r = sprintf(buf, "%lu (expanded: %lu)\n",
size >> 10,
trace_buf_size >> 10);
else
r = sprintf(buf, "%lu\n", size >> 10);
} else
r = sprintf(buf, "X\n");
} else
r = sprintf(buf, "%lu\n", per_cpu_ptr(tr->trace_buffer.data, cpu)->entries >> 10);
mutex_unlock(&trace_types_lock);
ret = simple_read_from_buffer(ubuf, cnt, ppos, buf, r);
return ret;
}
static ssize_t
tracing_entries_write(struct file *filp, const char __user *ubuf,
size_t cnt, loff_t *ppos)
{
struct inode *inode = file_inode(filp);
struct trace_array *tr = inode->i_private;
unsigned long val;
int ret;
ret = kstrtoul_from_user(ubuf, cnt, 10, &val);
if (ret)
return ret;
/* must have at least 1 entry */
if (!val)
return -EINVAL;
/* value is in KB */
val <<= 10;
ret = tracing_resize_ring_buffer(tr, val, tracing_get_cpu(inode));
if (ret < 0)
return ret;
*ppos += cnt;
return cnt;
}
static ssize_t
tracing_total_entries_read(struct file *filp, char __user *ubuf,
size_t cnt, loff_t *ppos)
{
struct trace_array *tr = filp->private_data;
char buf[64];
int r, cpu;
unsigned long size = 0, expanded_size = 0;
mutex_lock(&trace_types_lock);
for_each_tracing_cpu(cpu) {
size += per_cpu_ptr(tr->trace_buffer.data, cpu)->entries >> 10;
if (!ring_buffer_expanded)
expanded_size += trace_buf_size >> 10;
}
if (ring_buffer_expanded)
r = sprintf(buf, "%lu\n", size);
else
r = sprintf(buf, "%lu (expanded: %lu)\n", size, expanded_size);
mutex_unlock(&trace_types_lock);
return simple_read_from_buffer(ubuf, cnt, ppos, buf, r);
}
static ssize_t
tracing_free_buffer_write(struct file *filp, const char __user *ubuf,
size_t cnt, loff_t *ppos)
{
/*
* There is no need to read what the user has written, this function
* is just to make sure that there is no error when "echo" is used
*/
*ppos += cnt;
return cnt;
}
static int
tracing_free_buffer_release(struct inode *inode, struct file *filp)
{
struct trace_array *tr = inode->i_private;
/* disable tracing ? */
if (tr->trace_flags & TRACE_ITER_STOP_ON_FREE)
tracer_tracing_off(tr);
/* resize the ring buffer to 0 */
tracing_resize_ring_buffer(tr, 0, RING_BUFFER_ALL_CPUS);
trace_array_put(tr);
return 0;
}
static ssize_t
tracing_mark_write(struct file *filp, const char __user *ubuf,
size_t cnt, loff_t *fpos)
{
struct trace_array *tr = filp->private_data;
struct ring_buffer_event *event;
enum event_trigger_type tt = ETT_NONE;
struct ring_buffer *buffer;
struct print_entry *entry;
unsigned long irq_flags;
const char faulted[] = "<faulted>";
ssize_t written;
int size;
int len;
/* Used in tracing_mark_raw_write() as well */
#define FAULTED_SIZE (sizeof(faulted) - 1) /* '\0' is already accounted for */
if (tracing_disabled)
return -EINVAL;
if (!(tr->trace_flags & TRACE_ITER_MARKERS))
return -EINVAL;
if (cnt > TRACE_BUF_SIZE)
cnt = TRACE_BUF_SIZE;
BUILD_BUG_ON(TRACE_BUF_SIZE >= PAGE_SIZE);
local_save_flags(irq_flags);
size = sizeof(*entry) + cnt + 2; /* add '\0' and possible '\n' */
/* If less than "<faulted>", then make sure we can still add that */
if (cnt < FAULTED_SIZE)
size += FAULTED_SIZE - cnt;
buffer = tr->trace_buffer.buffer;
event = __trace_buffer_lock_reserve(buffer, TRACE_PRINT, size,
irq_flags, preempt_count());
if (unlikely(!event))
/* Ring buffer disabled, return as if not open for write */
return -EBADF;
entry = ring_buffer_event_data(event);
entry->ip = _THIS_IP_;
len = __copy_from_user_inatomic(&entry->buf, ubuf, cnt);
if (len) {
memcpy(&entry->buf, faulted, FAULTED_SIZE);
cnt = FAULTED_SIZE;
written = -EFAULT;
} else
written = cnt;
len = cnt;
if (tr->trace_marker_file && !list_empty(&tr->trace_marker_file->triggers)) {
/* do not add \n before testing triggers, but add \0 */
entry->buf[cnt] = '\0';
tt = event_triggers_call(tr->trace_marker_file, entry, event);
}
if (entry->buf[cnt - 1] != '\n') {
entry->buf[cnt] = '\n';
entry->buf[cnt + 1] = '\0';
} else
entry->buf[cnt] = '\0';
__buffer_unlock_commit(buffer, event);
if (tt)
event_triggers_post_call(tr->trace_marker_file, tt);
if (written > 0)
*fpos += written;
return written;
}
/* Limit it for now to 3K (including tag) */
#define RAW_DATA_MAX_SIZE (1024*3)
static ssize_t
tracing_mark_raw_write(struct file *filp, const char __user *ubuf,
size_t cnt, loff_t *fpos)
{
struct trace_array *tr = filp->private_data;
struct ring_buffer_event *event;
struct ring_buffer *buffer;
struct raw_data_entry *entry;
const char faulted[] = "<faulted>";
unsigned long irq_flags;
ssize_t written;
int size;
int len;
#define FAULT_SIZE_ID (FAULTED_SIZE + sizeof(int))
if (tracing_disabled)
return -EINVAL;
if (!(tr->trace_flags & TRACE_ITER_MARKERS))
return -EINVAL;
/* The marker must at least have a tag id */
if (cnt < sizeof(unsigned int) || cnt > RAW_DATA_MAX_SIZE)
return -EINVAL;
if (cnt > TRACE_BUF_SIZE)
cnt = TRACE_BUF_SIZE;
BUILD_BUG_ON(TRACE_BUF_SIZE >= PAGE_SIZE);
local_save_flags(irq_flags);
size = sizeof(*entry) + cnt;
if (cnt < FAULT_SIZE_ID)
size += FAULT_SIZE_ID - cnt;
buffer = tr->trace_buffer.buffer;
event = __trace_buffer_lock_reserve(buffer, TRACE_RAW_DATA, size,
irq_flags, preempt_count());
if (!event)
/* Ring buffer disabled, return as if not open for write */
return -EBADF;
entry = ring_buffer_event_data(event);
len = __copy_from_user_inatomic(&entry->id, ubuf, cnt);
if (len) {
entry->id = -1;
memcpy(&entry->buf, faulted, FAULTED_SIZE);
written = -EFAULT;
} else
written = cnt;
__buffer_unlock_commit(buffer, event);
if (written > 0)
*fpos += written;
return written;
}
static int tracing_clock_show(struct seq_file *m, void *v)
{
struct trace_array *tr = m->private;
int i;
for (i = 0; i < ARRAY_SIZE(trace_clocks); i++)
seq_printf(m,
"%s%s%s%s", i ? " " : "",
i == tr->clock_id ? "[" : "", trace_clocks[i].name,
i == tr->clock_id ? "]" : "");
seq_putc(m, '\n');
return 0;
}
int tracing_set_clock(struct trace_array *tr, const char *clockstr)
{
int i;
for (i = 0; i < ARRAY_SIZE(trace_clocks); i++) {
if (strcmp(trace_clocks[i].name, clockstr) == 0)
break;
}
if (i == ARRAY_SIZE(trace_clocks))
return -EINVAL;
mutex_lock(&trace_types_lock);
tr->clock_id = i;
ring_buffer_set_clock(tr->trace_buffer.buffer, trace_clocks[i].func);
/*
* New clock may not be consistent with the previous clock.
* Reset the buffer so that it doesn't have incomparable timestamps.
*/
tracing_reset_online_cpus(&tr->trace_buffer);
#ifdef CONFIG_TRACER_MAX_TRACE
if (tr->max_buffer.buffer)
ring_buffer_set_clock(tr->max_buffer.buffer, trace_clocks[i].func);
tracing_reset_online_cpus(&tr->max_buffer);
#endif
mutex_unlock(&trace_types_lock);
return 0;
}
static ssize_t tracing_clock_write(struct file *filp, const char __user *ubuf,
size_t cnt, loff_t *fpos)
{
struct seq_file *m = filp->private_data;
struct trace_array *tr = m->private;
char buf[64];
const char *clockstr;
int ret;
if (cnt >= sizeof(buf))
return -EINVAL;
if (copy_from_user(buf, ubuf, cnt))
return -EFAULT;
buf[cnt] = 0;
clockstr = strstrip(buf);
ret = tracing_set_clock(tr, clockstr);
if (ret)
return ret;
*fpos += cnt;
return cnt;
}
static int tracing_clock_open(struct inode *inode, struct file *file)
{
struct trace_array *tr = inode->i_private;
int ret;
if (tracing_disabled)
return -ENODEV;
if (trace_array_get(tr))
return -ENODEV;
ret = single_open(file, tracing_clock_show, inode->i_private);
if (ret < 0)
trace_array_put(tr);
return ret;
}
static int tracing_time_stamp_mode_show(struct seq_file *m, void *v)
{
struct trace_array *tr = m->private;
mutex_lock(&trace_types_lock);
if (ring_buffer_time_stamp_abs(tr->trace_buffer.buffer))
seq_puts(m, "delta [absolute]\n");
else
seq_puts(m, "[delta] absolute\n");
mutex_unlock(&trace_types_lock);
return 0;
}
static int tracing_time_stamp_mode_open(struct inode *inode, struct file *file)
{
struct trace_array *tr = inode->i_private;
int ret;
if (tracing_disabled)
return -ENODEV;
if (trace_array_get(tr))
return -ENODEV;
ret = single_open(file, tracing_time_stamp_mode_show, inode->i_private);
if (ret < 0)
trace_array_put(tr);
return ret;
}
int tracing_set_time_stamp_abs(struct trace_array *tr, bool abs)
{
int ret = 0;
mutex_lock(&trace_types_lock);
if (abs && tr->time_stamp_abs_ref++)
goto out;
if (!abs) {
if (WARN_ON_ONCE(!tr->time_stamp_abs_ref)) {
ret = -EINVAL;
goto out;
}
if (--tr->time_stamp_abs_ref)
goto out;
}
ring_buffer_set_time_stamp_abs(tr->trace_buffer.buffer, abs);
#ifdef CONFIG_TRACER_MAX_TRACE
if (tr->max_buffer.buffer)
ring_buffer_set_time_stamp_abs(tr->max_buffer.buffer, abs);
#endif
out:
mutex_unlock(&trace_types_lock);
return ret;
}
struct ftrace_buffer_info {
struct trace_iterator iter;
void *spare;
unsigned int spare_cpu;
unsigned int read;
};
#ifdef CONFIG_TRACER_SNAPSHOT
static int tracing_snapshot_open(struct inode *inode, struct file *file)
{
struct trace_array *tr = inode->i_private;
struct trace_iterator *iter;
struct seq_file *m;
int ret = 0;
if (trace_array_get(tr) < 0)
return -ENODEV;
if (file->f_mode & FMODE_READ) {
iter = __tracing_open(inode, file, true);
if (IS_ERR(iter))
ret = PTR_ERR(iter);
} else {
/* Writes still need the seq_file to hold the private data */
ret = -ENOMEM;
m = kzalloc(sizeof(*m), GFP_KERNEL);
if (!m)
goto out;
iter = kzalloc(sizeof(*iter), GFP_KERNEL);
if (!iter) {
kfree(m);
goto out;
}
ret = 0;
iter->tr = tr;
iter->trace_buffer = &tr->max_buffer;
iter->cpu_file = tracing_get_cpu(inode);
m->private = iter;
file->private_data = m;
}
out:
if (ret < 0)
trace_array_put(tr);
return ret;
}
static ssize_t
tracing_snapshot_write(struct file *filp, const char __user *ubuf, size_t cnt,
loff_t *ppos)
{
struct seq_file *m = filp->private_data;
struct trace_iterator *iter = m->private;
struct trace_array *tr = iter->tr;
unsigned long val;
int ret;
ret = tracing_update_buffers();
if (ret < 0)
return ret;
ret = kstrtoul_from_user(ubuf, cnt, 10, &val);
if (ret)
return ret;
mutex_lock(&trace_types_lock);
if (tr->current_trace->use_max_tr) {
ret = -EBUSY;
goto out;
}
switch (val) {
case 0:
if (iter->cpu_file != RING_BUFFER_ALL_CPUS) {
ret = -EINVAL;
break;
}
if (tr->allocated_snapshot)
free_snapshot(tr);
break;
case 1:
/* Only allow per-cpu swap if the ring buffer supports it */
#ifndef CONFIG_RING_BUFFER_ALLOW_SWAP
if (iter->cpu_file != RING_BUFFER_ALL_CPUS) {
ret = -EINVAL;
break;
}
#endif
if (!tr->allocated_snapshot) {
ret = tracing_alloc_snapshot_instance(tr);
if (ret < 0)
break;
}
local_irq_disable();
/* Now, we're going to swap */
if (iter->cpu_file == RING_BUFFER_ALL_CPUS)
update_max_tr(tr, current, smp_processor_id());
else
update_max_tr_single(tr, current, iter->cpu_file);
local_irq_enable();
break;
default:
if (tr->allocated_snapshot) {
if (iter->cpu_file == RING_BUFFER_ALL_CPUS)
tracing_reset_online_cpus(&tr->max_buffer);
else
tracing_reset(&tr->max_buffer, iter->cpu_file);
}
break;
}
if (ret >= 0) {
*ppos += cnt;
ret = cnt;
}
out:
mutex_unlock(&trace_types_lock);
return ret;
}
static int tracing_snapshot_release(struct inode *inode, struct file *file)
{
struct seq_file *m = file->private_data;
int ret;
ret = tracing_release(inode, file);
if (file->f_mode & FMODE_READ)
return ret;
/* If write only, the seq_file is just a stub */
if (m)
kfree(m->private);
kfree(m);
return 0;
}
static int tracing_buffers_open(struct inode *inode, struct file *filp);
static ssize_t tracing_buffers_read(struct file *filp, char __user *ubuf,
size_t count, loff_t *ppos);
static int tracing_buffers_release(struct inode *inode, struct file *file);
static ssize_t tracing_buffers_splice_read(struct file *file, loff_t *ppos,
struct pipe_inode_info *pipe, size_t len, unsigned int flags);
static int snapshot_raw_open(struct inode *inode, struct file *filp)
{
struct ftrace_buffer_info *info;
int ret;
ret = tracing_buffers_open(inode, filp);
if (ret < 0)
return ret;
info = filp->private_data;
if (info->iter.trace->use_max_tr) {
tracing_buffers_release(inode, filp);
return -EBUSY;
}
info->iter.snapshot = true;
info->iter.trace_buffer = &info->iter.tr->max_buffer;
return ret;
}
#endif /* CONFIG_TRACER_SNAPSHOT */
static const struct file_operations tracing_thresh_fops = {
.open = tracing_open_generic,
.read = tracing_thresh_read,
.write = tracing_thresh_write,
.llseek = generic_file_llseek,
};
#if defined(CONFIG_TRACER_MAX_TRACE) || defined(CONFIG_HWLAT_TRACER)
static const struct file_operations tracing_max_lat_fops = {
.open = tracing_open_generic,
.read = tracing_max_lat_read,
.write = tracing_max_lat_write,
.llseek = generic_file_llseek,
};
#endif
static const struct file_operations set_tracer_fops = {
.open = tracing_open_generic,
.read = tracing_set_trace_read,
.write = tracing_set_trace_write,
.llseek = generic_file_llseek,
};
static const struct file_operations tracing_pipe_fops = {
.open = tracing_open_pipe,
.poll = tracing_poll_pipe,
.read = tracing_read_pipe,
.splice_read = tracing_splice_read_pipe,
.release = tracing_release_pipe,
.llseek = no_llseek,
};
static const struct file_operations tracing_entries_fops = {
.open = tracing_open_generic_tr,
.read = tracing_entries_read,
.write = tracing_entries_write,
.llseek = generic_file_llseek,
.release = tracing_release_generic_tr,
};
static const struct file_operations tracing_total_entries_fops = {
.open = tracing_open_generic_tr,
.read = tracing_total_entries_read,
.llseek = generic_file_llseek,
.release = tracing_release_generic_tr,
};
static const struct file_operations tracing_free_buffer_fops = {
.open = tracing_open_generic_tr,
.write = tracing_free_buffer_write,
.release = tracing_free_buffer_release,
};
static const struct file_operations tracing_mark_fops = {
.open = tracing_open_generic_tr,
.write = tracing_mark_write,
.llseek = generic_file_llseek,
.release = tracing_release_generic_tr,
};
static const struct file_operations tracing_mark_raw_fops = {
.open = tracing_open_generic_tr,
.write = tracing_mark_raw_write,
.llseek = generic_file_llseek,
.release = tracing_release_generic_tr,
};
static const struct file_operations trace_clock_fops = {
.open = tracing_clock_open,
.read = seq_read,
.llseek = seq_lseek,
.release = tracing_single_release_tr,
.write = tracing_clock_write,
};
static const struct file_operations trace_time_stamp_mode_fops = {
.open = tracing_time_stamp_mode_open,
.read = seq_read,
.llseek = seq_lseek,
.release = tracing_single_release_tr,
};
#ifdef CONFIG_TRACER_SNAPSHOT
static const struct file_operations snapshot_fops = {
.open = tracing_snapshot_open,
.read = seq_read,
.write = tracing_snapshot_write,
.llseek = tracing_lseek,
.release = tracing_snapshot_release,
};
static const struct file_operations snapshot_raw_fops = {
.open = snapshot_raw_open,
.read = tracing_buffers_read,
.release = tracing_buffers_release,
.splice_read = tracing_buffers_splice_read,
.llseek = no_llseek,
};
#endif /* CONFIG_TRACER_SNAPSHOT */
static int tracing_buffers_open(struct inode *inode, struct file *filp)
{
struct trace_array *tr = inode->i_private;
struct ftrace_buffer_info *info;
int ret;
if (tracing_disabled)
return -ENODEV;
if (trace_array_get(tr) < 0)
return -ENODEV;
info = kzalloc(sizeof(*info), GFP_KERNEL);
if (!info) {
trace_array_put(tr);
return -ENOMEM;
}
mutex_lock(&trace_types_lock);
info->iter.tr = tr;
info->iter.cpu_file = tracing_get_cpu(inode);
info->iter.trace = tr->current_trace;
info->iter.trace_buffer = &tr->trace_buffer;
info->spare = NULL;
/* Force reading ring buffer for first read */
info->read = (unsigned int)-1;
filp->private_data = info;
tr->current_trace->ref++;
mutex_unlock(&trace_types_lock);
ret = nonseekable_open(inode, filp);
if (ret < 0)
trace_array_put(tr);
return ret;
}
static __poll_t
tracing_buffers_poll(struct file *filp, poll_table *poll_table)
{
struct ftrace_buffer_info *info = filp->private_data;
struct trace_iterator *iter = &info->iter;
return trace_poll(iter, filp, poll_table);
}
static ssize_t
tracing_buffers_read(struct file *filp, char __user *ubuf,
size_t count, loff_t *ppos)
{
struct ftrace_buffer_info *info = filp->private_data;
struct trace_iterator *iter = &info->iter;
ssize_t ret = 0;
ssize_t size;
if (!count)
return 0;
#ifdef CONFIG_TRACER_MAX_TRACE
if (iter->snapshot && iter->tr->current_trace->use_max_tr)
return -EBUSY;
#endif
if (!info->spare) {
info->spare = ring_buffer_alloc_read_page(iter->trace_buffer->buffer,
iter->cpu_file);
if (IS_ERR(info->spare)) {
ret = PTR_ERR(info->spare);
info->spare = NULL;
} else {
info->spare_cpu = iter->cpu_file;
}
}
if (!info->spare)
return ret;
/* Do we have previous read data to read? */
if (info->read < PAGE_SIZE)
goto read;
again:
trace_access_lock(iter->cpu_file);
ret = ring_buffer_read_page(iter->trace_buffer->buffer,
&info->spare,
count,
iter->cpu_file, 0);
trace_access_unlock(iter->cpu_file);
if (ret < 0) {
if (trace_empty(iter)) {
if ((filp->f_flags & O_NONBLOCK))
return -EAGAIN;
ret = wait_on_pipe(iter, false);
if (ret)
return ret;
goto again;
}
return 0;
}
info->read = 0;
read:
size = PAGE_SIZE - info->read;
if (size > count)
size = count;
ret = copy_to_user(ubuf, info->spare + info->read, size);
if (ret == size)
return -EFAULT;
size -= ret;
*ppos += size;
info->read += size;
return size;
}
static int tracing_buffers_release(struct inode *inode, struct file *file)
{
struct ftrace_buffer_info *info = file->private_data;
struct trace_iterator *iter = &info->iter;
mutex_lock(&trace_types_lock);
iter->tr->current_trace->ref--;
__trace_array_put(iter->tr);
if (info->spare)
ring_buffer_free_read_page(iter->trace_buffer->buffer,
info->spare_cpu, info->spare);
kfree(info);
mutex_unlock(&trace_types_lock);
return 0;
}
struct buffer_ref {
struct ring_buffer *buffer;
void *page;
int cpu;
int ref;
};
static void buffer_pipe_buf_release(struct pipe_inode_info *pipe,
struct pipe_buffer *buf)
{
struct buffer_ref *ref = (struct buffer_ref *)buf->private;
if (--ref->ref)
return;
ring_buffer_free_read_page(ref->buffer, ref->cpu, ref->page);
kfree(ref);
buf->private = 0;
}
static void buffer_pipe_buf_get(struct pipe_inode_info *pipe,
struct pipe_buffer *buf)
{
struct buffer_ref *ref = (struct buffer_ref *)buf->private;
ref->ref++;
}
/* Pipe buffer operations for a buffer. */
static const struct pipe_buf_operations buffer_pipe_buf_ops = {
.can_merge = 0,
.confirm = generic_pipe_buf_confirm,
.release = buffer_pipe_buf_release,
.steal = generic_pipe_buf_steal,
.get = buffer_pipe_buf_get,
};
/*
* Callback from splice_to_pipe(), if we need to release some pages
* at the end of the spd in case we error'ed out in filling the pipe.
*/
static void buffer_spd_release(struct splice_pipe_desc *spd, unsigned int i)
{
struct buffer_ref *ref =
(struct buffer_ref *)spd->partial[i].private;
if (--ref->ref)
return;
ring_buffer_free_read_page(ref->buffer, ref->cpu, ref->page);
kfree(ref);
spd->partial[i].private = 0;
}
static ssize_t
tracing_buffers_splice_read(struct file *file, loff_t *ppos,
struct pipe_inode_info *pipe, size_t len,
unsigned int flags)
{
struct ftrace_buffer_info *info = file->private_data;
struct trace_iterator *iter = &info->iter;
struct partial_page partial_def[PIPE_DEF_BUFFERS];
struct page *pages_def[PIPE_DEF_BUFFERS];
struct splice_pipe_desc spd = {
.pages = pages_def,
.partial = partial_def,
.nr_pages_max = PIPE_DEF_BUFFERS,
.ops = &buffer_pipe_buf_ops,
.spd_release = buffer_spd_release,
};
struct buffer_ref *ref;
int entries, i;
ssize_t ret = 0;
#ifdef CONFIG_TRACER_MAX_TRACE
if (iter->snapshot && iter->tr->current_trace->use_max_tr)
return -EBUSY;
#endif
if (*ppos & (PAGE_SIZE - 1))
return -EINVAL;
if (len & (PAGE_SIZE - 1)) {
if (len < PAGE_SIZE)
return -EINVAL;
len &= PAGE_MASK;
}
if (splice_grow_spd(pipe, &spd))
return -ENOMEM;
again:
trace_access_lock(iter->cpu_file);
entries = ring_buffer_entries_cpu(iter->trace_buffer->buffer, iter->cpu_file);
for (i = 0; i < spd.nr_pages_max && len && entries; i++, len -= PAGE_SIZE) {
struct page *page;
int r;
ref = kzalloc(sizeof(*ref), GFP_KERNEL);
if (!ref) {
ret = -ENOMEM;
break;
}
ref->ref = 1;
ref->buffer = iter->trace_buffer->buffer;
ref->page = ring_buffer_alloc_read_page(ref->buffer, iter->cpu_file);
if (IS_ERR(ref->page)) {
ret = PTR_ERR(ref->page);
ref->page = NULL;
kfree(ref);
break;
}
ref->cpu = iter->cpu_file;
r = ring_buffer_read_page(ref->buffer, &ref->page,
len, iter->cpu_file, 1);
if (r < 0) {
ring_buffer_free_read_page(ref->buffer, ref->cpu,
ref->page);
kfree(ref);
break;
}
page = virt_to_page(ref->page);
spd.pages[i] = page;
spd.partial[i].len = PAGE_SIZE;
spd.partial[i].offset = 0;
spd.partial[i].private = (unsigned long)ref;
spd.nr_pages++;
*ppos += PAGE_SIZE;
entries = ring_buffer_entries_cpu(iter->trace_buffer->buffer, iter->cpu_file);
}
trace_access_unlock(iter->cpu_file);
spd.nr_pages = i;
/* did we read anything? */
if (!spd.nr_pages) {
if (ret)
goto out;
ret = -EAGAIN;
if ((file->f_flags & O_NONBLOCK) || (flags & SPLICE_F_NONBLOCK))
goto out;
ret = wait_on_pipe(iter, true);
if (ret)
goto out;
goto again;
}
ret = splice_to_pipe(pipe, &spd);
out:
splice_shrink_spd(&spd);
return ret;
}
static const struct file_operations tracing_buffers_fops = {
.open = tracing_buffers_open,
.read = tracing_buffers_read,
.poll = tracing_buffers_poll,
.release = tracing_buffers_release,
.splice_read = tracing_buffers_splice_read,
.llseek = no_llseek,
};
static ssize_t
tracing_stats_read(struct file *filp, char __user *ubuf,
size_t count, loff_t *ppos)
{
struct inode *inode = file_inode(filp);
struct trace_array *tr = inode->i_private;
struct trace_buffer *trace_buf = &tr->trace_buffer;
int cpu = tracing_get_cpu(inode);
struct trace_seq *s;
unsigned long cnt;
unsigned long long t;
unsigned long usec_rem;
s = kmalloc(sizeof(*s), GFP_KERNEL);
if (!s)
return -ENOMEM;
trace_seq_init(s);
cnt = ring_buffer_entries_cpu(trace_buf->buffer, cpu);
trace_seq_printf(s, "entries: %ld\n", cnt);
cnt = ring_buffer_overrun_cpu(trace_buf->buffer, cpu);
trace_seq_printf(s, "overrun: %ld\n", cnt);
cnt = ring_buffer_commit_overrun_cpu(trace_buf->buffer, cpu);
trace_seq_printf(s, "commit overrun: %ld\n", cnt);
cnt = ring_buffer_bytes_cpu(trace_buf->buffer, cpu);
trace_seq_printf(s, "bytes: %ld\n", cnt);
if (trace_clocks[tr->clock_id].in_ns) {
/* local or global for trace_clock */
t = ns2usecs(ring_buffer_oldest_event_ts(trace_buf->buffer, cpu));
usec_rem = do_div(t, USEC_PER_SEC);
trace_seq_printf(s, "oldest event ts: %5llu.%06lu\n",
t, usec_rem);
t = ns2usecs(ring_buffer_time_stamp(trace_buf->buffer, cpu));
usec_rem = do_div(t, USEC_PER_SEC);
trace_seq_printf(s, "now ts: %5llu.%06lu\n", t, usec_rem);
} else {
/* counter or tsc mode for trace_clock */
trace_seq_printf(s, "oldest event ts: %llu\n",
ring_buffer_oldest_event_ts(trace_buf->buffer, cpu));
trace_seq_printf(s, "now ts: %llu\n",
ring_buffer_time_stamp(trace_buf->buffer, cpu));
}
cnt = ring_buffer_dropped_events_cpu(trace_buf->buffer, cpu);
trace_seq_printf(s, "dropped events: %ld\n", cnt);
cnt = ring_buffer_read_events_cpu(trace_buf->buffer, cpu);
trace_seq_printf(s, "read events: %ld\n", cnt);
count = simple_read_from_buffer(ubuf, count, ppos,
s->buffer, trace_seq_used(s));
kfree(s);
return count;
}
static const struct file_operations tracing_stats_fops = {
.open = tracing_open_generic_tr,
.read = tracing_stats_read,
.llseek = generic_file_llseek,
.release = tracing_release_generic_tr,
};
#ifdef CONFIG_DYNAMIC_FTRACE
static ssize_t
tracing_read_dyn_info(struct file *filp, char __user *ubuf,
size_t cnt, loff_t *ppos)
{
unsigned long *p = filp->private_data;
char buf[64]; /* Not too big for a shallow stack */
int r;
r = scnprintf(buf, 63, "%ld", *p);
buf[r++] = '\n';
return simple_read_from_buffer(ubuf, cnt, ppos, buf, r);
}
static const struct file_operations tracing_dyn_info_fops = {
.open = tracing_open_generic,
.read = tracing_read_dyn_info,
.llseek = generic_file_llseek,
};
#endif /* CONFIG_DYNAMIC_FTRACE */
#if defined(CONFIG_TRACER_SNAPSHOT) && defined(CONFIG_DYNAMIC_FTRACE)
static void
ftrace_snapshot(unsigned long ip, unsigned long parent_ip,
struct trace_array *tr, struct ftrace_probe_ops *ops,
void *data)
{
tracing_snapshot_instance(tr);
}
static void
ftrace_count_snapshot(unsigned long ip, unsigned long parent_ip,
struct trace_array *tr, struct ftrace_probe_ops *ops,
void *data)
{
struct ftrace_func_mapper *mapper = data;
long *count = NULL;
if (mapper)
count = (long *)ftrace_func_mapper_find_ip(mapper, ip);
if (count) {
if (*count <= 0)
return;
(*count)--;
}
tracing_snapshot_instance(tr);
}
static int
ftrace_snapshot_print(struct seq_file *m, unsigned long ip,
struct ftrace_probe_ops *ops, void *data)
{
struct ftrace_func_mapper *mapper = data;
long *count = NULL;
seq_printf(m, "%ps:", (void *)ip);
seq_puts(m, "snapshot");
if (mapper)
count = (long *)ftrace_func_mapper_find_ip(mapper, ip);
if (count)
seq_printf(m, ":count=%ld\n", *count);
else
seq_puts(m, ":unlimited\n");
return 0;
}
static int
ftrace_snapshot_init(struct ftrace_probe_ops *ops, struct trace_array *tr,
unsigned long ip, void *init_data, void **data)
{
struct ftrace_func_mapper *mapper = *data;
if (!mapper) {
mapper = allocate_ftrace_func_mapper();
if (!mapper)
return -ENOMEM;
*data = mapper;
}
return ftrace_func_mapper_add_ip(mapper, ip, init_data);
}
static void
ftrace_snapshot_free(struct ftrace_probe_ops *ops, struct trace_array *tr,
unsigned long ip, void *data)
{
struct ftrace_func_mapper *mapper = data;
if (!ip) {
if (!mapper)
return;
free_ftrace_func_mapper(mapper, NULL);
return;
}
ftrace_func_mapper_remove_ip(mapper, ip);
}
static struct ftrace_probe_ops snapshot_probe_ops = {
.func = ftrace_snapshot,
.print = ftrace_snapshot_print,
};
static struct ftrace_probe_ops snapshot_count_probe_ops = {
.func = ftrace_count_snapshot,
.print = ftrace_snapshot_print,
.init = ftrace_snapshot_init,
.free = ftrace_snapshot_free,
};
static int
ftrace_trace_snapshot_callback(struct trace_array *tr, struct ftrace_hash *hash,
char *glob, char *cmd, char *param, int enable)
{
struct ftrace_probe_ops *ops;
void *count = (void *)-1;
char *number;
int ret;
if (!tr)
return -ENODEV;
/* hash funcs only work with set_ftrace_filter */
if (!enable)
return -EINVAL;
ops = param ? &snapshot_count_probe_ops : &snapshot_probe_ops;
if (glob[0] == '!')
return unregister_ftrace_function_probe_func(glob+1, tr, ops);
if (!param)
goto out_reg;
number = strsep(¶m, ":");
if (!strlen(number))
goto out_reg;
/*
* We use the callback data field (which is a pointer)
* as our counter.
*/
ret = kstrtoul(number, 0, (unsigned long *)&count);
if (ret)
return ret;
out_reg:
ret = tracing_alloc_snapshot_instance(tr);
if (ret < 0)
goto out;
ret = register_ftrace_function_probe(glob, tr, ops, count);
out:
return ret < 0 ? ret : 0;
}
static struct ftrace_func_command ftrace_snapshot_cmd = {
.name = "snapshot",
.func = ftrace_trace_snapshot_callback,
};
static __init int register_snapshot_cmd(void)
{
return register_ftrace_command(&ftrace_snapshot_cmd);
}
#else
static inline __init int register_snapshot_cmd(void) { return 0; }
#endif /* defined(CONFIG_TRACER_SNAPSHOT) && defined(CONFIG_DYNAMIC_FTRACE) */
static struct dentry *tracing_get_dentry(struct trace_array *tr)
{
if (WARN_ON(!tr->dir))
return ERR_PTR(-ENODEV);
/* Top directory uses NULL as the parent */
if (tr->flags & TRACE_ARRAY_FL_GLOBAL)
return NULL;
/* All sub buffers have a descriptor */
return tr->dir;
}
static struct dentry *tracing_dentry_percpu(struct trace_array *tr, int cpu)
{
struct dentry *d_tracer;
if (tr->percpu_dir)
return tr->percpu_dir;
d_tracer = tracing_get_dentry(tr);
if (IS_ERR(d_tracer))
return NULL;
tr->percpu_dir = tracefs_create_dir("per_cpu", d_tracer);
WARN_ONCE(!tr->percpu_dir,
"Could not create tracefs directory 'per_cpu/%d'\n", cpu);
return tr->percpu_dir;
}
static struct dentry *
trace_create_cpu_file(const char *name, umode_t mode, struct dentry *parent,
void *data, long cpu, const struct file_operations *fops)
{
struct dentry *ret = trace_create_file(name, mode, parent, data, fops);
if (ret) /* See tracing_get_cpu() */
d_inode(ret)->i_cdev = (void *)(cpu + 1);
return ret;
}
static void
tracing_init_tracefs_percpu(struct trace_array *tr, long cpu)
{
struct dentry *d_percpu = tracing_dentry_percpu(tr, cpu);
struct dentry *d_cpu;
char cpu_dir[30]; /* 30 characters should be more than enough */
if (!d_percpu)
return;
snprintf(cpu_dir, 30, "cpu%ld", cpu);
d_cpu = tracefs_create_dir(cpu_dir, d_percpu);
if (!d_cpu) {
pr_warn("Could not create tracefs '%s' entry\n", cpu_dir);
return;
}
/* per cpu trace_pipe */
trace_create_cpu_file("trace_pipe", 0444, d_cpu,
tr, cpu, &tracing_pipe_fops);
/* per cpu trace */
trace_create_cpu_file("trace", 0644, d_cpu,
tr, cpu, &tracing_fops);
trace_create_cpu_file("trace_pipe_raw", 0444, d_cpu,
tr, cpu, &tracing_buffers_fops);
trace_create_cpu_file("stats", 0444, d_cpu,
tr, cpu, &tracing_stats_fops);
trace_create_cpu_file("buffer_size_kb", 0444, d_cpu,
tr, cpu, &tracing_entries_fops);
#ifdef CONFIG_TRACER_SNAPSHOT
trace_create_cpu_file("snapshot", 0644, d_cpu,
tr, cpu, &snapshot_fops);
trace_create_cpu_file("snapshot_raw", 0444, d_cpu,
tr, cpu, &snapshot_raw_fops);
#endif
}
#ifdef CONFIG_FTRACE_SELFTEST
/* Let selftest have access to static functions in this file */
#include "trace_selftest.c"
#endif
static ssize_t
trace_options_read(struct file *filp, char __user *ubuf, size_t cnt,
loff_t *ppos)
{
struct trace_option_dentry *topt = filp->private_data;
char *buf;
if (topt->flags->val & topt->opt->bit)
buf = "1\n";
else
buf = "0\n";
return simple_read_from_buffer(ubuf, cnt, ppos, buf, 2);
}
static ssize_t
trace_options_write(struct file *filp, const char __user *ubuf, size_t cnt,
loff_t *ppos)
{
struct trace_option_dentry *topt = filp->private_data;
unsigned long val;
int ret;
ret = kstrtoul_from_user(ubuf, cnt, 10, &val);
if (ret)
return ret;
if (val != 0 && val != 1)
return -EINVAL;
if (!!(topt->flags->val & topt->opt->bit) != val) {
mutex_lock(&trace_types_lock);
ret = __set_tracer_option(topt->tr, topt->flags,
topt->opt, !val);
mutex_unlock(&trace_types_lock);
if (ret)
return ret;
}
*ppos += cnt;
return cnt;
}
static const struct file_operations trace_options_fops = {
.open = tracing_open_generic,
.read = trace_options_read,
.write = trace_options_write,
.llseek = generic_file_llseek,
};
/*
* In order to pass in both the trace_array descriptor as well as the index
* to the flag that the trace option file represents, the trace_array
* has a character array of trace_flags_index[], which holds the index
* of the bit for the flag it represents. index[0] == 0, index[1] == 1, etc.
* The address of this character array is passed to the flag option file
* read/write callbacks.
*
* In order to extract both the index and the trace_array descriptor,
* get_tr_index() uses the following algorithm.
*
* idx = *ptr;
*
* As the pointer itself contains the address of the index (remember
* index[1] == 1).
*
* Then to get the trace_array descriptor, by subtracting that index
* from the ptr, we get to the start of the index itself.
*
* ptr - idx == &index[0]
*
* Then a simple container_of() from that pointer gets us to the
* trace_array descriptor.
*/
static void get_tr_index(void *data, struct trace_array **ptr,
unsigned int *pindex)
{
*pindex = *(unsigned char *)data;
*ptr = container_of(data - *pindex, struct trace_array,
trace_flags_index);
}
static ssize_t
trace_options_core_read(struct file *filp, char __user *ubuf, size_t cnt,
loff_t *ppos)
{
void *tr_index = filp->private_data;
struct trace_array *tr;
unsigned int index;
char *buf;
get_tr_index(tr_index, &tr, &index);
if (tr->trace_flags & (1 << index))
buf = "1\n";
else
buf = "0\n";
return simple_read_from_buffer(ubuf, cnt, ppos, buf, 2);
}
static ssize_t
trace_options_core_write(struct file *filp, const char __user *ubuf, size_t cnt,
loff_t *ppos)
{
void *tr_index = filp->private_data;
struct trace_array *tr;
unsigned int index;
unsigned long val;
int ret;
get_tr_index(tr_index, &tr, &index);
ret = kstrtoul_from_user(ubuf, cnt, 10, &val);
if (ret)
return ret;
if (val != 0 && val != 1)
return -EINVAL;
mutex_lock(&trace_types_lock);
ret = set_tracer_flag(tr, 1 << index, val);
mutex_unlock(&trace_types_lock);
if (ret < 0)
return ret;
*ppos += cnt;
return cnt;
}
static const struct file_operations trace_options_core_fops = {
.open = tracing_open_generic,
.read = trace_options_core_read,
.write = trace_options_core_write,
.llseek = generic_file_llseek,
};
struct dentry *trace_create_file(const char *name,
umode_t mode,
struct dentry *parent,
void *data,
const struct file_operations *fops)
{
struct dentry *ret;
ret = tracefs_create_file(name, mode, parent, data, fops);
if (!ret)
pr_warn("Could not create tracefs '%s' entry\n", name);
return ret;
}
static struct dentry *trace_options_init_dentry(struct trace_array *tr)
{
struct dentry *d_tracer;
if (tr->options)
return tr->options;
d_tracer = tracing_get_dentry(tr);
if (IS_ERR(d_tracer))
return NULL;
tr->options = tracefs_create_dir("options", d_tracer);
if (!tr->options) {
pr_warn("Could not create tracefs directory 'options'\n");
return NULL;
}
return tr->options;
}
static void
create_trace_option_file(struct trace_array *tr,
struct trace_option_dentry *topt,
struct tracer_flags *flags,
struct tracer_opt *opt)
{
struct dentry *t_options;
t_options = trace_options_init_dentry(tr);
if (!t_options)
return;
topt->flags = flags;
topt->opt = opt;
topt->tr = tr;
topt->entry = trace_create_file(opt->name, 0644, t_options, topt,
&trace_options_fops);
}
static void
create_trace_option_files(struct trace_array *tr, struct tracer *tracer)
{
struct trace_option_dentry *topts;
struct trace_options *tr_topts;
struct tracer_flags *flags;
struct tracer_opt *opts;
int cnt;
int i;
if (!tracer)
return;
flags = tracer->flags;
if (!flags || !flags->opts)
return;
/*
* If this is an instance, only create flags for tracers
* the instance may have.
*/
if (!trace_ok_for_array(tracer, tr))
return;
for (i = 0; i < tr->nr_topts; i++) {
/* Make sure there's no duplicate flags. */
if (WARN_ON_ONCE(tr->topts[i].tracer->flags == tracer->flags))
return;
}
opts = flags->opts;
for (cnt = 0; opts[cnt].name; cnt++)
;
topts = kcalloc(cnt + 1, sizeof(*topts), GFP_KERNEL);
if (!topts)
return;
tr_topts = krealloc(tr->topts, sizeof(*tr->topts) * (tr->nr_topts + 1),
GFP_KERNEL);
if (!tr_topts) {
kfree(topts);
return;
}
tr->topts = tr_topts;
tr->topts[tr->nr_topts].tracer = tracer;
tr->topts[tr->nr_topts].topts = topts;
tr->nr_topts++;
for (cnt = 0; opts[cnt].name; cnt++) {
create_trace_option_file(tr, &topts[cnt], flags,
&opts[cnt]);
WARN_ONCE(topts[cnt].entry == NULL,
"Failed to create trace option: %s",
opts[cnt].name);
}
}
static struct dentry *
create_trace_option_core_file(struct trace_array *tr,
const char *option, long index)
{
struct dentry *t_options;
t_options = trace_options_init_dentry(tr);
if (!t_options)
return NULL;
return trace_create_file(option, 0644, t_options,
(void *)&tr->trace_flags_index[index],
&trace_options_core_fops);
}
static void create_trace_options_dir(struct trace_array *tr)
{
struct dentry *t_options;
bool top_level = tr == &global_trace;
int i;
t_options = trace_options_init_dentry(tr);
if (!t_options)
return;
for (i = 0; trace_options[i]; i++) {
if (top_level ||
!((1 << i) & TOP_LEVEL_TRACE_FLAGS))
create_trace_option_core_file(tr, trace_options[i], i);
}
}
static ssize_t
rb_simple_read(struct file *filp, char __user *ubuf,
size_t cnt, loff_t *ppos)
{
struct trace_array *tr = filp->private_data;
char buf[64];
int r;
r = tracer_tracing_is_on(tr);
r = sprintf(buf, "%d\n", r);
return simple_read_from_buffer(ubuf, cnt, ppos, buf, r);
}
static ssize_t
rb_simple_write(struct file *filp, const char __user *ubuf,
size_t cnt, loff_t *ppos)
{
struct trace_array *tr = filp->private_data;
struct ring_buffer *buffer = tr->trace_buffer.buffer;
unsigned long val;
int ret;
ret = kstrtoul_from_user(ubuf, cnt, 10, &val);
if (ret)
return ret;
if (buffer) {
mutex_lock(&trace_types_lock);
if (val) {
tracer_tracing_on(tr);
if (tr->current_trace->start)
tr->current_trace->start(tr);
} else {
tracer_tracing_off(tr);
if (tr->current_trace->stop)
tr->current_trace->stop(tr);
}
mutex_unlock(&trace_types_lock);
}
(*ppos)++;
return cnt;
}
static const struct file_operations rb_simple_fops = {
.open = tracing_open_generic_tr,
.read = rb_simple_read,
.write = rb_simple_write,
.release = tracing_release_generic_tr,
.llseek = default_llseek,
};
struct dentry *trace_instance_dir;
static void
init_tracer_tracefs(struct trace_array *tr, struct dentry *d_tracer);
static int
allocate_trace_buffer(struct trace_array *tr, struct trace_buffer *buf, int size)
{
enum ring_buffer_flags rb_flags;
rb_flags = tr->trace_flags & TRACE_ITER_OVERWRITE ? RB_FL_OVERWRITE : 0;
buf->tr = tr;
buf->buffer = ring_buffer_alloc(size, rb_flags);
if (!buf->buffer)
return -ENOMEM;
buf->data = alloc_percpu(struct trace_array_cpu);
if (!buf->data) {
ring_buffer_free(buf->buffer);
buf->buffer = NULL;
return -ENOMEM;
}
/* Allocate the first page for all buffers */
set_buffer_entries(&tr->trace_buffer,
ring_buffer_size(tr->trace_buffer.buffer, 0));
return 0;
}
static int allocate_trace_buffers(struct trace_array *tr, int size)
{
int ret;
ret = allocate_trace_buffer(tr, &tr->trace_buffer, size);
if (ret)
return ret;
#ifdef CONFIG_TRACER_MAX_TRACE
ret = allocate_trace_buffer(tr, &tr->max_buffer,
allocate_snapshot ? size : 1);
if (WARN_ON(ret)) {
ring_buffer_free(tr->trace_buffer.buffer);
tr->trace_buffer.buffer = NULL;
free_percpu(tr->trace_buffer.data);
tr->trace_buffer.data = NULL;
return -ENOMEM;
}
tr->allocated_snapshot = allocate_snapshot;
/*
* Only the top level trace array gets its snapshot allocated
* from the kernel command line.
*/
allocate_snapshot = false;
#endif
return 0;
}
static void free_trace_buffer(struct trace_buffer *buf)
{
if (buf->buffer) {
ring_buffer_free(buf->buffer);
buf->buffer = NULL;
free_percpu(buf->data);
buf->data = NULL;
}
}
static void free_trace_buffers(struct trace_array *tr)
{
if (!tr)
return;
free_trace_buffer(&tr->trace_buffer);
#ifdef CONFIG_TRACER_MAX_TRACE
free_trace_buffer(&tr->max_buffer);
#endif
}
static void init_trace_flags_index(struct trace_array *tr)
{
int i;
/* Used by the trace options files */
for (i = 0; i < TRACE_FLAGS_MAX_SIZE; i++)
tr->trace_flags_index[i] = i;
}
static void __update_tracer_options(struct trace_array *tr)
{
struct tracer *t;
for (t = trace_types; t; t = t->next)
add_tracer_options(tr, t);
}
static void update_tracer_options(struct trace_array *tr)
{
mutex_lock(&trace_types_lock);
__update_tracer_options(tr);
mutex_unlock(&trace_types_lock);
}
static int instance_mkdir(const char *name)
{
struct trace_array *tr;
int ret;
mutex_lock(&event_mutex);
mutex_lock(&trace_types_lock);
ret = -EEXIST;
list_for_each_entry(tr, &ftrace_trace_arrays, list) {
if (tr->name && strcmp(tr->name, name) == 0)
goto out_unlock;
}
ret = -ENOMEM;
tr = kzalloc(sizeof(*tr), GFP_KERNEL);
if (!tr)
goto out_unlock;
tr->name = kstrdup(name, GFP_KERNEL);
if (!tr->name)
goto out_free_tr;
if (!alloc_cpumask_var(&tr->tracing_cpumask, GFP_KERNEL))
goto out_free_tr;
tr->trace_flags = global_trace.trace_flags & ~ZEROED_TRACE_FLAGS;
cpumask_copy(tr->tracing_cpumask, cpu_all_mask);
raw_spin_lock_init(&tr->start_lock);
tr->max_lock = (arch_spinlock_t)__ARCH_SPIN_LOCK_UNLOCKED;
tr->current_trace = &nop_trace;
INIT_LIST_HEAD(&tr->systems);
INIT_LIST_HEAD(&tr->events);
INIT_LIST_HEAD(&tr->hist_vars);
if (allocate_trace_buffers(tr, trace_buf_size) < 0)
goto out_free_tr;
tr->dir = tracefs_create_dir(name, trace_instance_dir);
if (!tr->dir)
goto out_free_tr;
ret = event_trace_add_tracer(tr->dir, tr);
if (ret) {
tracefs_remove_recursive(tr->dir);
goto out_free_tr;
}
ftrace_init_trace_array(tr);
init_tracer_tracefs(tr, tr->dir);
init_trace_flags_index(tr);
__update_tracer_options(tr);
list_add(&tr->list, &ftrace_trace_arrays);
mutex_unlock(&trace_types_lock);
mutex_unlock(&event_mutex);
return 0;
out_free_tr:
free_trace_buffers(tr);
free_cpumask_var(tr->tracing_cpumask);
kfree(tr->name);
kfree(tr);
out_unlock:
mutex_unlock(&trace_types_lock);
mutex_unlock(&event_mutex);
return ret;
}
static int instance_rmdir(const char *name)
{
struct trace_array *tr;
int found = 0;
int ret;
int i;
mutex_lock(&event_mutex);
mutex_lock(&trace_types_lock);
ret = -ENODEV;
list_for_each_entry(tr, &ftrace_trace_arrays, list) {
if (tr->name && strcmp(tr->name, name) == 0) {
found = 1;
break;
}
}
if (!found)
goto out_unlock;
ret = -EBUSY;
if (tr->ref || (tr->current_trace && tr->current_trace->ref))
goto out_unlock;
list_del(&tr->list);
/* Disable all the flags that were enabled coming in */
for (i = 0; i < TRACE_FLAGS_MAX_SIZE; i++) {
if ((1 << i) & ZEROED_TRACE_FLAGS)
set_tracer_flag(tr, 1 << i, 0);
}
tracing_set_nop(tr);
clear_ftrace_function_probes(tr);
event_trace_del_tracer(tr);
ftrace_clear_pids(tr);
ftrace_destroy_function_files(tr);
tracefs_remove_recursive(tr->dir);
free_trace_buffers(tr);
for (i = 0; i < tr->nr_topts; i++) {
kfree(tr->topts[i].topts);
}
kfree(tr->topts);
free_cpumask_var(tr->tracing_cpumask);
kfree(tr->name);
kfree(tr);
ret = 0;
out_unlock:
mutex_unlock(&trace_types_lock);
mutex_unlock(&event_mutex);
return ret;
}
static __init void create_trace_instances(struct dentry *d_tracer)
{
trace_instance_dir = tracefs_create_instance_dir("instances", d_tracer,
instance_mkdir,
instance_rmdir);
if (WARN_ON(!trace_instance_dir))
return;
}
static void
init_tracer_tracefs(struct trace_array *tr, struct dentry *d_tracer)
{
struct trace_event_file *file;
int cpu;
trace_create_file("available_tracers", 0444, d_tracer,
tr, &show_traces_fops);
trace_create_file("current_tracer", 0644, d_tracer,
tr, &set_tracer_fops);
trace_create_file("tracing_cpumask", 0644, d_tracer,
tr, &tracing_cpumask_fops);
trace_create_file("trace_options", 0644, d_tracer,
tr, &tracing_iter_fops);
trace_create_file("trace", 0644, d_tracer,
tr, &tracing_fops);
trace_create_file("trace_pipe", 0444, d_tracer,
tr, &tracing_pipe_fops);
trace_create_file("buffer_size_kb", 0644, d_tracer,
tr, &tracing_entries_fops);
trace_create_file("buffer_total_size_kb", 0444, d_tracer,
tr, &tracing_total_entries_fops);
trace_create_file("free_buffer", 0200, d_tracer,
tr, &tracing_free_buffer_fops);
trace_create_file("trace_marker", 0220, d_tracer,
tr, &tracing_mark_fops);
file = __find_event_file(tr, "ftrace", "print");
if (file && file->dir)
trace_create_file("trigger", 0644, file->dir, file,
&event_trigger_fops);
tr->trace_marker_file = file;
trace_create_file("trace_marker_raw", 0220, d_tracer,
tr, &tracing_mark_raw_fops);
trace_create_file("trace_clock", 0644, d_tracer, tr,
&trace_clock_fops);
trace_create_file("tracing_on", 0644, d_tracer,
tr, &rb_simple_fops);
trace_create_file("timestamp_mode", 0444, d_tracer, tr,
&trace_time_stamp_mode_fops);
create_trace_options_dir(tr);
#if defined(CONFIG_TRACER_MAX_TRACE) || defined(CONFIG_HWLAT_TRACER)
trace_create_file("tracing_max_latency", 0644, d_tracer,
&tr->max_latency, &tracing_max_lat_fops);
#endif
if (ftrace_create_function_files(tr, d_tracer))
WARN(1, "Could not allocate function filter files");
#ifdef CONFIG_TRACER_SNAPSHOT
trace_create_file("snapshot", 0644, d_tracer,
tr, &snapshot_fops);
#endif
for_each_tracing_cpu(cpu)
tracing_init_tracefs_percpu(tr, cpu);
ftrace_init_tracefs(tr, d_tracer);
}
static struct vfsmount *trace_automount(struct dentry *mntpt, void *ingore)
{
struct vfsmount *mnt;
struct file_system_type *type;
/*
* To maintain backward compatibility for tools that mount
* debugfs to get to the tracing facility, tracefs is automatically
* mounted to the debugfs/tracing directory.
*/
type = get_fs_type("tracefs");
if (!type)
return NULL;
mnt = vfs_submount(mntpt, type, "tracefs", NULL);
put_filesystem(type);
if (IS_ERR(mnt))
return NULL;
mntget(mnt);
return mnt;
}
/**
* tracing_init_dentry - initialize top level trace array
*
* This is called when creating files or directories in the tracing
* directory. It is called via fs_initcall() by any of the boot up code
* and expects to return the dentry of the top level tracing directory.
*/
struct dentry *tracing_init_dentry(void)
{
struct trace_array *tr = &global_trace;
/* The top level trace array uses NULL as parent */
if (tr->dir)
return NULL;
if (WARN_ON(!tracefs_initialized()) ||
(IS_ENABLED(CONFIG_DEBUG_FS) &&
WARN_ON(!debugfs_initialized())))
return ERR_PTR(-ENODEV);
/*
* As there may still be users that expect the tracing
* files to exist in debugfs/tracing, we must automount
* the tracefs file system there, so older tools still
* work with the newer kerenl.
*/
tr->dir = debugfs_create_automount("tracing", NULL,
trace_automount, NULL);
if (!tr->dir) {
pr_warn_once("Could not create debugfs directory 'tracing'\n");
return ERR_PTR(-ENOMEM);
}
return NULL;
}
extern struct trace_eval_map *__start_ftrace_eval_maps[];
extern struct trace_eval_map *__stop_ftrace_eval_maps[];
static void __init trace_eval_init(void)
{
int len;
len = __stop_ftrace_eval_maps - __start_ftrace_eval_maps;
trace_insert_eval_map(NULL, __start_ftrace_eval_maps, len);
}
#ifdef CONFIG_MODULES
static void trace_module_add_evals(struct module *mod)
{
if (!mod->num_trace_evals)
return;
/*
* Modules with bad taint do not have events created, do
* not bother with enums either.
*/
if (trace_module_has_bad_taint(mod))
return;
trace_insert_eval_map(mod, mod->trace_evals, mod->num_trace_evals);
}
#ifdef CONFIG_TRACE_EVAL_MAP_FILE
static void trace_module_remove_evals(struct module *mod)
{
union trace_eval_map_item *map;
union trace_eval_map_item **last = &trace_eval_maps;
if (!mod->num_trace_evals)
return;
mutex_lock(&trace_eval_mutex);
map = trace_eval_maps;
while (map) {
if (map->head.mod == mod)
break;
map = trace_eval_jmp_to_tail(map);
last = &map->tail.next;
map = map->tail.next;
}
if (!map)
goto out;
*last = trace_eval_jmp_to_tail(map)->tail.next;
kfree(map);
out:
mutex_unlock(&trace_eval_mutex);
}
#else
static inline void trace_module_remove_evals(struct module *mod) { }
#endif /* CONFIG_TRACE_EVAL_MAP_FILE */
static int trace_module_notify(struct notifier_block *self,
unsigned long val, void *data)
{
struct module *mod = data;
switch (val) {
case MODULE_STATE_COMING:
trace_module_add_evals(mod);
break;
case MODULE_STATE_GOING:
trace_module_remove_evals(mod);
break;
}
return 0;
}
static struct notifier_block trace_module_nb = {
.notifier_call = trace_module_notify,
.priority = 0,
};
#endif /* CONFIG_MODULES */
static __init int tracer_init_tracefs(void)
{
struct dentry *d_tracer;
trace_access_lock_init();
d_tracer = tracing_init_dentry();
if (IS_ERR(d_tracer))
return 0;
event_trace_init();
init_tracer_tracefs(&global_trace, d_tracer);
ftrace_init_tracefs_toplevel(&global_trace, d_tracer);
trace_create_file("tracing_thresh", 0644, d_tracer,
&global_trace, &tracing_thresh_fops);
trace_create_file("README", 0444, d_tracer,
NULL, &tracing_readme_fops);
trace_create_file("saved_cmdlines", 0444, d_tracer,
NULL, &tracing_saved_cmdlines_fops);
trace_create_file("saved_cmdlines_size", 0644, d_tracer,
NULL, &tracing_saved_cmdlines_size_fops);
trace_create_file("saved_tgids", 0444, d_tracer,
NULL, &tracing_saved_tgids_fops);
trace_eval_init();
trace_create_eval_file(d_tracer);
#ifdef CONFIG_MODULES
register_module_notifier(&trace_module_nb);
#endif
#ifdef CONFIG_DYNAMIC_FTRACE
trace_create_file("dyn_ftrace_total_info", 0444, d_tracer,
&ftrace_update_tot_cnt, &tracing_dyn_info_fops);
#endif
create_trace_instances(d_tracer);
update_tracer_options(&global_trace);
return 0;
}
static int trace_panic_handler(struct notifier_block *this,
unsigned long event, void *unused)
{
if (ftrace_dump_on_oops)
ftrace_dump(ftrace_dump_on_oops);
return NOTIFY_OK;
}
static struct notifier_block trace_panic_notifier = {
.notifier_call = trace_panic_handler,
.next = NULL,
.priority = 150 /* priority: INT_MAX >= x >= 0 */
};
static int trace_die_handler(struct notifier_block *self,
unsigned long val,
void *data)
{
switch (val) {
case DIE_OOPS:
if (ftrace_dump_on_oops)
ftrace_dump(ftrace_dump_on_oops);
break;
default:
break;
}
return NOTIFY_OK;
}
static struct notifier_block trace_die_notifier = {
.notifier_call = trace_die_handler,
.priority = 200
};
/*
* printk is set to max of 1024, we really don't need it that big.
* Nothing should be printing 1000 characters anyway.
*/
#define TRACE_MAX_PRINT 1000
/*
* Define here KERN_TRACE so that we have one place to modify
* it if we decide to change what log level the ftrace dump
* should be at.
*/
#define KERN_TRACE KERN_EMERG
void
trace_printk_seq(struct trace_seq *s)
{
/* Probably should print a warning here. */
if (s->seq.len >= TRACE_MAX_PRINT)
s->seq.len = TRACE_MAX_PRINT;
/*
* More paranoid code. Although the buffer size is set to
* PAGE_SIZE, and TRACE_MAX_PRINT is 1000, this is just
* an extra layer of protection.
*/
if (WARN_ON_ONCE(s->seq.len >= s->seq.size))
s->seq.len = s->seq.size - 1;
/* should be zero ended, but we are paranoid. */
s->buffer[s->seq.len] = 0;
printk(KERN_TRACE "%s", s->buffer);
trace_seq_init(s);
}
void trace_init_global_iter(struct trace_iterator *iter)
{
iter->tr = &global_trace;
iter->trace = iter->tr->current_trace;
iter->cpu_file = RING_BUFFER_ALL_CPUS;
iter->trace_buffer = &global_trace.trace_buffer;
if (iter->trace && iter->trace->open)
iter->trace->open(iter);
/* Annotate start of buffers if we had overruns */
if (ring_buffer_overruns(iter->trace_buffer->buffer))
iter->iter_flags |= TRACE_FILE_ANNOTATE;
/* Output in nanoseconds only if we are using a clock in nanoseconds. */
if (trace_clocks[iter->tr->clock_id].in_ns)
iter->iter_flags |= TRACE_FILE_TIME_IN_NS;
}
void ftrace_dump(enum ftrace_dump_mode oops_dump_mode)
{
/* use static because iter can be a bit big for the stack */
static struct trace_iterator iter;
static atomic_t dump_running;
struct trace_array *tr = &global_trace;
unsigned int old_userobj;
unsigned long flags;
int cnt = 0, cpu;
/* Only allow one dump user at a time. */
if (atomic_inc_return(&dump_running) != 1) {
atomic_dec(&dump_running);
return;
}
/*
* Always turn off tracing when we dump.
* We don't need to show trace output of what happens
* between multiple crashes.
*
* If the user does a sysrq-z, then they can re-enable
* tracing with echo 1 > tracing_on.
*/
tracing_off();
local_irq_save(flags);
/* Simulate the iterator */
trace_init_global_iter(&iter);
for_each_tracing_cpu(cpu) {
atomic_inc(&per_cpu_ptr(iter.trace_buffer->data, cpu)->disabled);
}
old_userobj = tr->trace_flags & TRACE_ITER_SYM_USEROBJ;
/* don't look at user memory in panic mode */
tr->trace_flags &= ~TRACE_ITER_SYM_USEROBJ;
switch (oops_dump_mode) {
case DUMP_ALL:
iter.cpu_file = RING_BUFFER_ALL_CPUS;
break;
case DUMP_ORIG:
iter.cpu_file = raw_smp_processor_id();
break;
case DUMP_NONE:
goto out_enable;
default:
printk(KERN_TRACE "Bad dumping mode, switching to all CPUs dump\n");
iter.cpu_file = RING_BUFFER_ALL_CPUS;
}
printk(KERN_TRACE "Dumping ftrace buffer:\n");
/* Did function tracer already get disabled? */
if (ftrace_is_dead()) {
printk("# WARNING: FUNCTION TRACING IS CORRUPTED\n");
printk("# MAY BE MISSING FUNCTION EVENTS\n");
}
/*
* We need to stop all tracing on all CPUS to read the
* the next buffer. This is a bit expensive, but is
* not done often. We fill all what we can read,
* and then release the locks again.
*/
while (!trace_empty(&iter)) {
if (!cnt)
printk(KERN_TRACE "---------------------------------\n");
cnt++;
/* reset all but tr, trace, and overruns */
memset(&iter.seq, 0,
sizeof(struct trace_iterator) -
offsetof(struct trace_iterator, seq));
iter.iter_flags |= TRACE_FILE_LAT_FMT;
iter.pos = -1;
if (trace_find_next_entry_inc(&iter) != NULL) {
int ret;
ret = print_trace_line(&iter);
if (ret != TRACE_TYPE_NO_CONSUME)
trace_consume(&iter);
}
touch_nmi_watchdog();
trace_printk_seq(&iter.seq);
}
if (!cnt)
printk(KERN_TRACE " (ftrace buffer empty)\n");
else
printk(KERN_TRACE "---------------------------------\n");
out_enable:
tr->trace_flags |= old_userobj;
for_each_tracing_cpu(cpu) {
atomic_dec(&per_cpu_ptr(iter.trace_buffer->data, cpu)->disabled);
}
atomic_dec(&dump_running);
local_irq_restore(flags);
}
EXPORT_SYMBOL_GPL(ftrace_dump);
int trace_run_command(const char *buf, int (*createfn)(int, char **))
{
char **argv;
int argc, ret;
argc = 0;
ret = 0;
argv = argv_split(GFP_KERNEL, buf, &argc);
if (!argv)
return -ENOMEM;
if (argc)
ret = createfn(argc, argv);
argv_free(argv);
return ret;
}
#define WRITE_BUFSIZE 4096
ssize_t trace_parse_run_command(struct file *file, const char __user *buffer,
size_t count, loff_t *ppos,
int (*createfn)(int, char **))
{
char *kbuf, *buf, *tmp;
int ret = 0;
size_t done = 0;
size_t size;
kbuf = kmalloc(WRITE_BUFSIZE, GFP_KERNEL);
if (!kbuf)
return -ENOMEM;
while (done < count) {
size = count - done;
if (size >= WRITE_BUFSIZE)
size = WRITE_BUFSIZE - 1;
if (copy_from_user(kbuf, buffer + done, size)) {
ret = -EFAULT;
goto out;
}
kbuf[size] = '\0';
buf = kbuf;
do {
tmp = strchr(buf, '\n');
if (tmp) {
*tmp = '\0';
size = tmp - buf + 1;
} else {
size = strlen(buf);
if (done + size < count) {
if (buf != kbuf)
break;
/* This can accept WRITE_BUFSIZE - 2 ('\n' + '\0') */
pr_warn("Line length is too long: Should be less than %d\n",
WRITE_BUFSIZE - 2);
ret = -EINVAL;
goto out;
}
}
done += size;
/* Remove comments */
tmp = strchr(buf, '#');
if (tmp)
*tmp = '\0';
ret = trace_run_command(buf, createfn);
if (ret)
goto out;
buf += size;
} while (done < count);
}
ret = done;
out:
kfree(kbuf);
return ret;
}
__init static int tracer_alloc_buffers(void)
{
int ring_buf_size;
int ret = -ENOMEM;
/*
* Make sure we don't accidently add more trace options
* than we have bits for.
*/
BUILD_BUG_ON(TRACE_ITER_LAST_BIT > TRACE_FLAGS_MAX_SIZE);
if (!alloc_cpumask_var(&tracing_buffer_mask, GFP_KERNEL))
goto out;
if (!alloc_cpumask_var(&global_trace.tracing_cpumask, GFP_KERNEL))
goto out_free_buffer_mask;
/* Only allocate trace_printk buffers if a trace_printk exists */
if (__stop___trace_bprintk_fmt != __start___trace_bprintk_fmt)
/* Must be called before global_trace.buffer is allocated */
trace_printk_init_buffers();
/* To save memory, keep the ring buffer size to its minimum */
if (ring_buffer_expanded)
ring_buf_size = trace_buf_size;
else
ring_buf_size = 1;
cpumask_copy(tracing_buffer_mask, cpu_possible_mask);
cpumask_copy(global_trace.tracing_cpumask, cpu_all_mask);
raw_spin_lock_init(&global_trace.start_lock);
/*
* The prepare callbacks allocates some memory for the ring buffer. We
* don't free the buffer if the if the CPU goes down. If we were to free
* the buffer, then the user would lose any trace that was in the
* buffer. The memory will be removed once the "instance" is removed.
*/
ret = cpuhp_setup_state_multi(CPUHP_TRACE_RB_PREPARE,
"trace/RB:preapre", trace_rb_cpu_prepare,
NULL);
if (ret < 0)
goto out_free_cpumask;
/* Used for event triggers */
ret = -ENOMEM;
temp_buffer = ring_buffer_alloc(PAGE_SIZE, RB_FL_OVERWRITE);
if (!temp_buffer)
goto out_rm_hp_state;
if (trace_create_savedcmd() < 0)
goto out_free_temp_buffer;
/* TODO: make the number of buffers hot pluggable with CPUS */
if (allocate_trace_buffers(&global_trace, ring_buf_size) < 0) {
printk(KERN_ERR "tracer: failed to allocate ring buffer!\n");
WARN_ON(1);
goto out_free_savedcmd;
}
if (global_trace.buffer_disabled)
tracing_off();
if (trace_boot_clock) {
ret = tracing_set_clock(&global_trace, trace_boot_clock);
if (ret < 0)
pr_warn("Trace clock %s not defined, going back to default\n",
trace_boot_clock);
}
/*
* register_tracer() might reference current_trace, so it
* needs to be set before we register anything. This is
* just a bootstrap of current_trace anyway.
*/
global_trace.current_trace = &nop_trace;
global_trace.max_lock = (arch_spinlock_t)__ARCH_SPIN_LOCK_UNLOCKED;
ftrace_init_global_array_ops(&global_trace);
init_trace_flags_index(&global_trace);
register_tracer(&nop_trace);
/* Function tracing may start here (via kernel command line) */
init_function_trace();
/* All seems OK, enable tracing */
tracing_disabled = 0;
atomic_notifier_chain_register(&panic_notifier_list,
&trace_panic_notifier);
register_die_notifier(&trace_die_notifier);
global_trace.flags = TRACE_ARRAY_FL_GLOBAL;
INIT_LIST_HEAD(&global_trace.systems);
INIT_LIST_HEAD(&global_trace.events);
INIT_LIST_HEAD(&global_trace.hist_vars);
list_add(&global_trace.list, &ftrace_trace_arrays);
apply_trace_boot_options();
register_snapshot_cmd();
return 0;
out_free_savedcmd:
free_saved_cmdlines_buffer(savedcmd);
out_free_temp_buffer:
ring_buffer_free(temp_buffer);
out_rm_hp_state:
cpuhp_remove_multi_state(CPUHP_TRACE_RB_PREPARE);
out_free_cpumask:
free_cpumask_var(global_trace.tracing_cpumask);
out_free_buffer_mask:
free_cpumask_var(tracing_buffer_mask);
out:
return ret;
}
void __init early_trace_init(void)
{
if (tracepoint_printk) {
tracepoint_print_iter =
kmalloc(sizeof(*tracepoint_print_iter), GFP_KERNEL);
if (WARN_ON(!tracepoint_print_iter))
tracepoint_printk = 0;
else
static_key_enable(&tracepoint_printk_key.key);
}
tracer_alloc_buffers();
}
void __init trace_init(void)
{
trace_event_init();
}
__init static int clear_boot_tracer(void)
{
/*
* The default tracer at boot buffer is an init section.
* This function is called in lateinit. If we did not
* find the boot tracer, then clear it out, to prevent
* later registration from accessing the buffer that is
* about to be freed.
*/
if (!default_bootup_tracer)
return 0;
printk(KERN_INFO "ftrace bootup tracer '%s' not registered.\n",
default_bootup_tracer);
default_bootup_tracer = NULL;
return 0;
}
fs_initcall(tracer_init_tracefs);
late_initcall_sync(clear_boot_tracer);
#ifdef CONFIG_HAVE_UNSTABLE_SCHED_CLOCK
__init static int tracing_set_default_clock(void)
{
/* sched_clock_stable() is determined in late_initcall */
if (!trace_boot_clock && !sched_clock_stable()) {
printk(KERN_WARNING
"Unstable clock detected, switching default tracing clock to \"global\"\n"
"If you want to keep using the local clock, then add:\n"
" \"trace_clock=local\"\n"
"on the kernel command line\n");
tracing_set_clock(&global_trace, "global");
}
return 0;
}
late_initcall_sync(tracing_set_default_clock);
#endif
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_205_2 |
crossvul-cpp_data_good_3373_1 | /* This file was converted by gperf_unfold_key_conv.py
from gperf output file. */
/* ANSI-C code produced by gperf version 3.0.4 */
/* Command-line: gperf -n -C -T -c -t -j1 -L ANSI-C -F,-1,0 -N unicode_unfold_key unicode_unfold_key.gperf */
/* Computed positions: -k'1-3' */
/* This gperf source file was generated by make_unicode_fold_data.py */
#include <string.h>
#include "regenc.h"
#define TOTAL_KEYWORDS 1321
#define MIN_WORD_LENGTH 3
#define MAX_WORD_LENGTH 3
#define MIN_HASH_VALUE 11
#define MAX_HASH_VALUE 1544
/* maximum key range = 1534, duplicates = 0 */
#ifdef __GNUC__
__inline
#else
#ifdef __cplusplus
inline
#endif
#endif
/*ARGSUSED*/
static unsigned int
hash(OnigCodePoint codes[])
{
static const unsigned short asso_values[] =
{
8, 6, 2, 124, 5, 1, 36, 1545, 1545, 1545,
1545, 1545, 1545, 11, 1545, 1545, 1545, 16, 1545, 1545,
562, 1545, 1545, 1545, 1545, 77, 1545, 1545, 1545, 1545,
1545, 0, 3, 1545, 61, 628, 1379, 206, 1378, 607,
1372, 597, 1399, 569, 1371, 4, 1365, 559, 1359, 548,
1353, 836, 1393, 830, 1345, 587, 1344, 581, 1336, 539,
1335, 530, 982, 521, 970, 818, 1389, 723, 1329, 351,
1320, 333, 1312, 293, 1311, 320, 1304, 176, 589, 311,
1165, 302, 1384, 1243, 579, 780, 173, 1230, 147, 1213,
75, 1219, 1296, 1009, 1293, 1282, 1267, 1217, 1030, 331,
1291, 1210, 1286, 998, 500, 993, 1359, 806, 1281, 510,
1048, 501, 662, 797, 754, 792, 372, 775, 290, 768,
228, 755, 292, 1159, 489, 1135, 267, 1229, 233, 1053,
222, 728, 159, 708, 484, 695, 155, 995, 247, 686,
859, 674, 747, 618, 561, 381, 313, 987, 167, 975,
165, 1279, 388, 1207, 157, 765, 900, 1007, 794, 476,
21, 1198, 1271, 490, 1265, 478, 1245, 18, 8, 253,
1188, 652, 7, 245, 1185, 415, 1256, 226, 1177, 54,
1169, 214, 1155, 195, 607, 42, 963, 30, 1147, 185,
1139, 465, 1129, 451, 1121, 86, 948, 136, 940, 76,
909, 66, 664, 126, 644, 116, 632, 106, 930, 166,
925, 149, 915, 96, 903, 390, 364, 283, 746, 273,
1098, 372, 1095, 265, 528, 361, 311, 897, 1195, 396,
1103, 425, 1094, 1088, 893, 887, 573, 407, 237, 1083,
934, 1145, 432, 1076, 679, 714, 956, 1112, 509, 880,
62, 873, 157, 864, 276, 1069, 112, 855, 156, 1063,
1545, 848, 152, 1057, 1545, 1047, 145, 1041, 144, 1035,
49, 1025, 142, 1256, 1545, 1239, 355, 342, 21, 1019,
14, 1233, 459, 843, 822, 740, 38, 553, 96, 448,
8
};
return asso_values[(unsigned char)onig_codes_byte_at(codes, 2)+35] + asso_values[(unsigned char)onig_codes_byte_at(codes, 1)+1] + asso_values[(unsigned char)onig_codes_byte_at(codes, 0)];
}
#ifdef __GNUC__
__inline
#if defined __GNUC_STDC_INLINE__ || defined __GNUC_GNU_INLINE__
__attribute__ ((__gnu_inline__))
#endif
#endif
const struct ByUnfoldKey *
unicode_unfold_key(OnigCodePoint code)
{
static const struct ByUnfoldKey wordlist[] =
{
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0},
{0x1040a, 3267, 1},
{0x1e0a, 1727, 1},
{0x040a, 1016, 1},
{0x010a, 186, 1},
{0x1f0a, 2088, 1},
{0x2c0a, 2451, 1},
{0x0189, 619, 1},
{0x1f89, 134, 2},
{0x1f85, 154, 2},
{0x0389, 733, 1},
{0x03ff, 724, 1},
{0xab89, 1523, 1},
{0xab85, 1511, 1},
{0x10c89, 3384, 1},
{0x10c85, 3372, 1},
{0x1e84, 1911, 1},
{0x03f5, 752, 1},
{0x0184, 360, 1},
{0x1f84, 149, 2},
{0x2c84, 2592, 1},
{0x017d, 351, 1},
{0x1ff3, 96, 2},
{0xab84, 1508, 1},
{0xa784, 3105, 1},
{0x10c84, 3369, 1},
{0xab7d, 1487, 1},
{0xa77d, 1706, 1},
{0x1e98, 38, 2},
{0x0498, 1106, 1},
{0x0198, 375, 1},
{0x1f98, 169, 2},
{0x2c98, 2622, 1},
{0x0398, 762, 1},
{0xa684, 2940, 1},
{0xab98, 1568, 1},
{0xa798, 3123, 1},
{0x10c98, 3429, 1},
{0x050a, 1277, 1},
{0x1ffb, 2265, 1},
{0x1e96, 16, 2},
{0x0496, 1103, 1},
{0x0196, 652, 1},
{0x1f96, 199, 2},
{0x2c96, 2619, 1},
{0x0396, 756, 1},
{0xa698, 2970, 1},
{0xab96, 1562, 1},
{0xa796, 3120, 1},
{0x10c96, 3423, 1},
{0x1feb, 2259, 1},
{0x2ceb, 2736, 1},
{0x1e90, 1929, 1},
{0x0490, 1094, 1},
{0x0190, 628, 1},
{0x1f90, 169, 2},
{0x2c90, 2610, 1},
{0x0390, 25, 3},
{0xa696, 2967, 1},
{0xab90, 1544, 1},
{0xa790, 3114, 1},
{0x10c90, 3405, 1},
{0x01d7, 444, 1},
{0x1fd7, 31, 3},
{0x1ea6, 1947, 1},
{0x04a6, 1127, 1},
{0x01a6, 676, 1},
{0x1fa6, 239, 2},
{0x2ca6, 2643, 1},
{0x03a6, 810, 1},
{0xa690, 2958, 1},
{0xaba6, 1610, 1},
{0xa7a6, 3144, 1},
{0x10ca6, 3471, 1},
{0x1ea4, 1944, 1},
{0x04a4, 1124, 1},
{0x01a4, 390, 1},
{0x1fa4, 229, 2},
{0x2ca4, 2640, 1},
{0x03a4, 804, 1},
{0x10a6, 2763, 1},
{0xaba4, 1604, 1},
{0xa7a4, 3141, 1},
{0x10ca4, 3465, 1},
{0x1ea0, 1938, 1},
{0x04a0, 1118, 1},
{0x01a0, 384, 1},
{0x1fa0, 209, 2},
{0x2ca0, 2634, 1},
{0x03a0, 792, 1},
{0x10a4, 2757, 1},
{0xaba0, 1592, 1},
{0xa7a0, 3135, 1},
{0x10ca0, 3453, 1},
{0x1eb2, 1965, 1},
{0x04b2, 1145, 1},
{0x01b2, 694, 1},
{0x1fb2, 249, 2},
{0x2cb2, 2661, 1},
{0x03fd, 718, 1},
{0x10a0, 2745, 1},
{0xabb2, 1646, 1},
{0xa7b2, 703, 1},
{0x10cb2, 3507, 1},
{0x1eac, 1956, 1},
{0x04ac, 1136, 1},
{0x01ac, 396, 1},
{0x1fac, 229, 2},
{0x2cac, 2652, 1},
{0x0537, 1352, 1},
{0x10b2, 2799, 1},
{0xabac, 1628, 1},
{0xa7ac, 637, 1},
{0x10cac, 3489, 1},
{0x1eaa, 1953, 1},
{0x04aa, 1133, 1},
{0x00dd, 162, 1},
{0x1faa, 219, 2},
{0x2caa, 2649, 1},
{0x03aa, 824, 1},
{0x10ac, 2781, 1},
{0xabaa, 1622, 1},
{0xa7aa, 646, 1},
{0x10caa, 3483, 1},
{0x1ea8, 1950, 1},
{0x04a8, 1130, 1},
{0x020a, 517, 1},
{0x1fa8, 209, 2},
{0x2ca8, 2646, 1},
{0x03a8, 817, 1},
{0x10aa, 2775, 1},
{0xaba8, 1616, 1},
{0xa7a8, 3147, 1},
{0x10ca8, 3477, 1},
{0x1ea2, 1941, 1},
{0x04a2, 1121, 1},
{0x01a2, 387, 1},
{0x1fa2, 219, 2},
{0x2ca2, 2637, 1},
{0x118a6, 3528, 1},
{0x10a8, 2769, 1},
{0xaba2, 1598, 1},
{0xa7a2, 3138, 1},
{0x10ca2, 3459, 1},
{0x2ced, 2739, 1},
{0x1fe9, 2283, 1},
{0x1fe7, 47, 3},
{0x1eb0, 1962, 1},
{0x04b0, 1142, 1},
{0x118a4, 3522, 1},
{0x10a2, 2751, 1},
{0x2cb0, 2658, 1},
{0x03b0, 41, 3},
{0x1fe3, 41, 3},
{0xabb0, 1640, 1},
{0xa7b0, 706, 1},
{0x10cb0, 3501, 1},
{0x01d9, 447, 1},
{0x1fd9, 2277, 1},
{0x118a0, 3510, 1},
{0x00df, 24, 2},
{0x00d9, 150, 1},
{0xab77, 1469, 1},
{0x10b0, 2793, 1},
{0x1eae, 1959, 1},
{0x04ae, 1139, 1},
{0x01ae, 685, 1},
{0x1fae, 239, 2},
{0x2cae, 2655, 1},
{0x118b2, 3564, 1},
{0xab73, 1457, 1},
{0xabae, 1634, 1},
{0xab71, 1451, 1},
{0x10cae, 3495, 1},
{0x1e2a, 1775, 1},
{0x042a, 968, 1},
{0x012a, 234, 1},
{0x1f2a, 2130, 1},
{0x2c2a, 2547, 1},
{0x118ac, 3546, 1},
{0x10ae, 2787, 1},
{0x0535, 1346, 1},
{0xa72a, 2988, 1},
{0x1e9a, 0, 2},
{0x049a, 1109, 1},
{0xff37, 3225, 1},
{0x1f9a, 179, 2},
{0x2c9a, 2625, 1},
{0x039a, 772, 1},
{0x118aa, 3540, 1},
{0xab9a, 1574, 1},
{0xa79a, 3126, 1},
{0x10c9a, 3435, 1},
{0x1e94, 1935, 1},
{0x0494, 1100, 1},
{0x0194, 640, 1},
{0x1f94, 189, 2},
{0x2c94, 2616, 1},
{0x0394, 749, 1},
{0x118a8, 3534, 1},
{0xab94, 1556, 1},
{0xa69a, 2973, 1},
{0x10c94, 3417, 1},
{0x10402, 3243, 1},
{0x1e02, 1715, 1},
{0x0402, 992, 1},
{0x0102, 174, 1},
{0x0533, 1340, 1},
{0x2c02, 2427, 1},
{0x118a2, 3516, 1},
{0x052a, 1325, 1},
{0xa694, 2964, 1},
{0x1e92, 1932, 1},
{0x0492, 1097, 1},
{0x2165, 2307, 1},
{0x1f92, 179, 2},
{0x2c92, 2613, 1},
{0x0392, 742, 1},
{0x2161, 2295, 1},
{0xab92, 1550, 1},
{0xa792, 3117, 1},
{0x10c92, 3411, 1},
{0x118b0, 3558, 1},
{0x1f5f, 2199, 1},
{0x1e8e, 1926, 1},
{0x048e, 1091, 1},
{0x018e, 453, 1},
{0x1f8e, 159, 2},
{0x2c8e, 2607, 1},
{0x038e, 833, 1},
{0xa692, 2961, 1},
{0xab8e, 1538, 1},
{0x0055, 59, 1},
{0x10c8e, 3399, 1},
{0x1f5d, 2196, 1},
{0x212a, 27, 1},
{0x04cb, 1181, 1},
{0x01cb, 425, 1},
{0x1fcb, 2241, 1},
{0x118ae, 3552, 1},
{0x0502, 1265, 1},
{0x00cb, 111, 1},
{0xa68e, 2955, 1},
{0x1e8a, 1920, 1},
{0x048a, 1085, 1},
{0x018a, 622, 1},
{0x1f8a, 139, 2},
{0x2c8a, 2601, 1},
{0x038a, 736, 1},
{0x2c67, 2571, 1},
{0xab8a, 1526, 1},
{0x1e86, 1914, 1},
{0x10c8a, 3387, 1},
{0x0186, 616, 1},
{0x1f86, 159, 2},
{0x2c86, 2595, 1},
{0x0386, 727, 1},
{0xff35, 3219, 1},
{0xab86, 1514, 1},
{0xa786, 3108, 1},
{0x10c86, 3375, 1},
{0xa68a, 2949, 1},
{0x0555, 1442, 1},
{0x1ebc, 1980, 1},
{0x04bc, 1160, 1},
{0x01bc, 411, 1},
{0x1fbc, 62, 2},
{0x2cbc, 2676, 1},
{0x1f5b, 2193, 1},
{0xa686, 2943, 1},
{0xabbc, 1676, 1},
{0x1eb8, 1974, 1},
{0x04b8, 1154, 1},
{0x01b8, 408, 1},
{0x1fb8, 2268, 1},
{0x2cb8, 2670, 1},
{0x01db, 450, 1},
{0x1fdb, 2247, 1},
{0xabb8, 1664, 1},
{0x10bc, 2829, 1},
{0x00db, 156, 1},
{0x1eb6, 1971, 1},
{0x04b6, 1151, 1},
{0xff33, 3213, 1},
{0x1fb6, 58, 2},
{0x2cb6, 2667, 1},
{0xff2a, 3186, 1},
{0x10b8, 2817, 1},
{0xabb6, 1658, 1},
{0xa7b6, 3153, 1},
{0x10426, 3351, 1},
{0x1e26, 1769, 1},
{0x0426, 956, 1},
{0x0126, 228, 1},
{0x0053, 52, 1},
{0x2c26, 2535, 1},
{0x0057, 65, 1},
{0x10b6, 2811, 1},
{0x022a, 562, 1},
{0xa726, 2982, 1},
{0x1e2e, 1781, 1},
{0x042e, 980, 1},
{0x012e, 240, 1},
{0x1f2e, 2142, 1},
{0x2c2e, 2559, 1},
{0xffffffff, -1, 0},
{0x2167, 2313, 1},
{0xffffffff, -1, 0},
{0xa72e, 2994, 1},
{0x1e2c, 1778, 1},
{0x042c, 974, 1},
{0x012c, 237, 1},
{0x1f2c, 2136, 1},
{0x2c2c, 2553, 1},
{0x1f6f, 2223, 1},
{0x2c6f, 604, 1},
{0xabbf, 1685, 1},
{0xa72c, 2991, 1},
{0x1e28, 1772, 1},
{0x0428, 962, 1},
{0x0128, 231, 1},
{0x1f28, 2124, 1},
{0x2c28, 2541, 1},
{0xffffffff, -1, 0},
{0x0553, 1436, 1},
{0x10bf, 2838, 1},
{0xa728, 2985, 1},
{0x0526, 1319, 1},
{0x0202, 505, 1},
{0x1e40, 1808, 1},
{0x10424, 3345, 1},
{0x1e24, 1766, 1},
{0x0424, 950, 1},
{0x0124, 225, 1},
{0xffffffff, -1, 0},
{0x2c24, 2529, 1},
{0x052e, 1331, 1},
{0xa740, 3018, 1},
{0x118bc, 3594, 1},
{0xa724, 2979, 1},
{0x1ef2, 2061, 1},
{0x04f2, 1241, 1},
{0x01f2, 483, 1},
{0x1ff2, 257, 2},
{0x2cf2, 2742, 1},
{0x052c, 1328, 1},
{0x118b8, 3582, 1},
{0xa640, 2865, 1},
{0x10422, 3339, 1},
{0x1e22, 1763, 1},
{0x0422, 944, 1},
{0x0122, 222, 1},
{0x2126, 820, 1},
{0x2c22, 2523, 1},
{0x0528, 1322, 1},
{0x01f1, 483, 1},
{0x118b6, 3576, 1},
{0xa722, 2976, 1},
{0x03f1, 796, 1},
{0x1ebe, 1983, 1},
{0x04be, 1163, 1},
{0xfb02, 12, 2},
{0x1fbe, 767, 1},
{0x2cbe, 2679, 1},
{0x01b5, 405, 1},
{0x0540, 1379, 1},
{0xabbe, 1682, 1},
{0x0524, 1316, 1},
{0x00b5, 779, 1},
{0xabb5, 1655, 1},
{0x1eba, 1977, 1},
{0x04ba, 1157, 1},
{0x216f, 2337, 1},
{0x1fba, 2226, 1},
{0x2cba, 2673, 1},
{0x10be, 2835, 1},
{0x0051, 46, 1},
{0xabba, 1670, 1},
{0x10b5, 2808, 1},
{0x1e6e, 1878, 1},
{0x046e, 1055, 1},
{0x016e, 330, 1},
{0x1f6e, 2220, 1},
{0x2c6e, 664, 1},
{0x118bf, 3603, 1},
{0x0522, 1313, 1},
{0x10ba, 2823, 1},
{0xa76e, 3087, 1},
{0x1eb4, 1968, 1},
{0x04b4, 1148, 1},
{0x2c75, 2583, 1},
{0x1fb4, 50, 2},
{0x2cb4, 2664, 1},
{0xab75, 1463, 1},
{0x1ec2, 1989, 1},
{0xabb4, 1652, 1},
{0xa7b4, 3150, 1},
{0x1fc2, 253, 2},
{0x2cc2, 2685, 1},
{0x03c2, 800, 1},
{0x00c2, 83, 1},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xff26, 3174, 1},
{0x10b4, 2805, 1},
{0x1eca, 2001, 1},
{0x0551, 1430, 1},
{0x01ca, 425, 1},
{0x1fca, 2238, 1},
{0x2cca, 2697, 1},
{0x10c2, 2847, 1},
{0x00ca, 108, 1},
{0xff2e, 3198, 1},
{0x1e8c, 1923, 1},
{0x048c, 1088, 1},
{0x0226, 556, 1},
{0x1f8c, 149, 2},
{0x2c8c, 2604, 1},
{0x038c, 830, 1},
{0xffffffff, -1, 0},
{0xab8c, 1532, 1},
{0xff2c, 3192, 1},
{0x10c8c, 3393, 1},
{0x1ec4, 1992, 1},
{0x022e, 568, 1},
{0x01c4, 417, 1},
{0x1fc4, 54, 2},
{0x2cc4, 2688, 1},
{0xffffffff, -1, 0},
{0x00c4, 89, 1},
{0xff28, 3180, 1},
{0xa68c, 2952, 1},
{0x01cf, 432, 1},
{0x022c, 565, 1},
{0x118be, 3600, 1},
{0x03cf, 839, 1},
{0x00cf, 123, 1},
{0x118b5, 3573, 1},
{0xffffffff, -1, 0},
{0x10c4, 2853, 1},
{0x216e, 2334, 1},
{0x24cb, 2406, 1},
{0x0228, 559, 1},
{0xff24, 3168, 1},
{0xffffffff, -1, 0},
{0x118ba, 3588, 1},
{0x1efe, 2079, 1},
{0x04fe, 1259, 1},
{0x01fe, 499, 1},
{0x1e9e, 24, 2},
{0x049e, 1115, 1},
{0x03fe, 721, 1},
{0x1f9e, 199, 2},
{0x2c9e, 2631, 1},
{0x039e, 786, 1},
{0x0224, 553, 1},
{0xab9e, 1586, 1},
{0xa79e, 3132, 1},
{0x10c9e, 3447, 1},
{0x01f7, 414, 1},
{0x1ff7, 67, 3},
{0xff22, 3162, 1},
{0x03f7, 884, 1},
{0x118b4, 3570, 1},
{0x049c, 1112, 1},
{0x019c, 661, 1},
{0x1f9c, 189, 2},
{0x2c9c, 2628, 1},
{0x039c, 779, 1},
{0x24bc, 2361, 1},
{0xab9c, 1580, 1},
{0xa79c, 3129, 1},
{0x10c9c, 3441, 1},
{0x0222, 550, 1},
{0x1e7c, 1899, 1},
{0x047c, 1076, 1},
{0x1e82, 1908, 1},
{0x24b8, 2349, 1},
{0x0182, 357, 1},
{0x1f82, 139, 2},
{0x2c82, 2589, 1},
{0xab7c, 1484, 1},
{0xffffffff, -1, 0},
{0xab82, 1502, 1},
{0xa782, 3102, 1},
{0x10c82, 3363, 1},
{0x2c63, 1709, 1},
{0x24b6, 2343, 1},
{0x1e80, 1905, 1},
{0x0480, 1082, 1},
{0x1f59, 2190, 1},
{0x1f80, 129, 2},
{0x2c80, 2586, 1},
{0x0059, 71, 1},
{0xa682, 2937, 1},
{0xab80, 1496, 1},
{0xa780, 3099, 1},
{0x10c80, 3357, 1},
{0xffffffff, -1, 0},
{0x1e4c, 1826, 1},
{0x0145, 270, 1},
{0x014c, 279, 1},
{0x1f4c, 2184, 1},
{0x0345, 767, 1},
{0x0045, 12, 1},
{0x004c, 31, 1},
{0xa680, 2934, 1},
{0xa74c, 3036, 1},
{0x1e4a, 1823, 1},
{0x01d5, 441, 1},
{0x014a, 276, 1},
{0x1f4a, 2178, 1},
{0x03d5, 810, 1},
{0x00d5, 141, 1},
{0x004a, 24, 1},
{0x24bf, 2370, 1},
{0xa74a, 3033, 1},
{0xa64c, 2883, 1},
{0x1041c, 3321, 1},
{0x1e1c, 1754, 1},
{0x041c, 926, 1},
{0x011c, 213, 1},
{0x1f1c, 2118, 1},
{0x2c1c, 2505, 1},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xa64a, 2880, 1},
{0x1041a, 3315, 1},
{0x1e1a, 1751, 1},
{0x041a, 920, 1},
{0x011a, 210, 1},
{0x1f1a, 2112, 1},
{0x2c1a, 2499, 1},
{0xabbd, 1679, 1},
{0x0545, 1394, 1},
{0x054c, 1415, 1},
{0x10418, 3309, 1},
{0x1e18, 1748, 1},
{0x0418, 914, 1},
{0x0118, 207, 1},
{0x1f18, 2106, 1},
{0x2c18, 2493, 1},
{0x10bd, 2832, 1},
{0x2163, 2301, 1},
{0x054a, 1409, 1},
{0x1040e, 3279, 1},
{0x1e0e, 1733, 1},
{0x040e, 1028, 1},
{0x010e, 192, 1},
{0x1f0e, 2100, 1},
{0x2c0e, 2463, 1},
{0x1efc, 2076, 1},
{0x04fc, 1256, 1},
{0x01fc, 496, 1},
{0x1ffc, 96, 2},
{0x051c, 1304, 1},
{0x1040c, 3273, 1},
{0x1e0c, 1730, 1},
{0x040c, 1022, 1},
{0x010c, 189, 1},
{0x1f0c, 2094, 1},
{0x2c0c, 2457, 1},
{0x1f6d, 2217, 1},
{0x2c6d, 607, 1},
{0x051a, 1301, 1},
{0x24be, 2367, 1},
{0x10408, 3261, 1},
{0x1e08, 1724, 1},
{0x0408, 1010, 1},
{0x0108, 183, 1},
{0x1f08, 2082, 1},
{0x2c08, 2445, 1},
{0x04c9, 1178, 1},
{0x0518, 1298, 1},
{0x1fc9, 2235, 1},
{0xffffffff, -1, 0},
{0x24ba, 2355, 1},
{0x00c9, 105, 1},
{0x10416, 3303, 1},
{0x1e16, 1745, 1},
{0x0416, 908, 1},
{0x0116, 204, 1},
{0x050e, 1283, 1},
{0x2c16, 2487, 1},
{0x10414, 3297, 1},
{0x1e14, 1742, 1},
{0x0414, 902, 1},
{0x0114, 201, 1},
{0x042b, 971, 1},
{0x2c14, 2481, 1},
{0x1f2b, 2133, 1},
{0x2c2b, 2550, 1},
{0xffffffff, -1, 0},
{0x050c, 1280, 1},
{0x10406, 3255, 1},
{0x1e06, 1721, 1},
{0x0406, 1004, 1},
{0x0106, 180, 1},
{0x13fb, 1697, 1},
{0x2c06, 2439, 1},
{0x24c2, 2379, 1},
{0x118bd, 3597, 1},
{0xffffffff, -1, 0},
{0x0508, 1274, 1},
{0x10404, 3249, 1},
{0x1e04, 1718, 1},
{0x0404, 998, 1},
{0x0104, 177, 1},
{0x1f95, 194, 2},
{0x2c04, 2433, 1},
{0x0395, 752, 1},
{0x24ca, 2403, 1},
{0xab95, 1559, 1},
{0x0531, 1334, 1},
{0x10c95, 3420, 1},
{0x0516, 1295, 1},
{0x1e6c, 1875, 1},
{0x046c, 1052, 1},
{0x016c, 327, 1},
{0x1f6c, 2214, 1},
{0x216d, 2331, 1},
{0x0514, 1292, 1},
{0x0245, 697, 1},
{0x024c, 598, 1},
{0xa76c, 3084, 1},
{0x10400, 3237, 1},
{0x1e00, 1712, 1},
{0x0400, 986, 1},
{0x0100, 171, 1},
{0x24c4, 2385, 1},
{0x2c00, 2421, 1},
{0x0506, 1271, 1},
{0x024a, 595, 1},
{0x1fab, 224, 2},
{0xa66c, 2931, 1},
{0x03ab, 827, 1},
{0x24cf, 2418, 1},
{0xabab, 1625, 1},
{0xa7ab, 631, 1},
{0x10cab, 3486, 1},
{0xffffffff, -1, 0},
{0x0504, 1268, 1},
{0xffffffff, -1, 0},
{0x021c, 544, 1},
{0x01a9, 679, 1},
{0x1fa9, 214, 2},
{0x10ab, 2778, 1},
{0x03a9, 820, 1},
{0x212b, 92, 1},
{0xaba9, 1619, 1},
{0x1e88, 1917, 1},
{0x10ca9, 3480, 1},
{0x021a, 541, 1},
{0x1f88, 129, 2},
{0x2c88, 2598, 1},
{0x0388, 730, 1},
{0x13fd, 1703, 1},
{0xab88, 1520, 1},
{0x10a9, 2772, 1},
{0x10c88, 3381, 1},
{0xffffffff, -1, 0},
{0x0218, 538, 1},
{0x0500, 1262, 1},
{0x1f4d, 2187, 1},
{0x01a7, 393, 1},
{0x1fa7, 244, 2},
{0x004d, 34, 1},
{0x03a7, 814, 1},
{0xa688, 2946, 1},
{0xaba7, 1613, 1},
{0x020e, 523, 1},
{0x10ca7, 3474, 1},
{0x1e6a, 1872, 1},
{0x046a, 1049, 1},
{0x016a, 324, 1},
{0x1f6a, 2208, 1},
{0xffffffff, -1, 0},
{0x216c, 2328, 1},
{0x10a7, 2766, 1},
{0x01d1, 435, 1},
{0xa76a, 3081, 1},
{0x020c, 520, 1},
{0x03d1, 762, 1},
{0x00d1, 129, 1},
{0x1e68, 1869, 1},
{0x0468, 1046, 1},
{0x0168, 321, 1},
{0x1f68, 2202, 1},
{0xffffffff, -1, 0},
{0xff31, 3207, 1},
{0xa66a, 2928, 1},
{0x0208, 514, 1},
{0xa768, 3078, 1},
{0x1e64, 1863, 1},
{0x0464, 1040, 1},
{0x0164, 315, 1},
{0x054d, 1418, 1},
{0x2c64, 673, 1},
{0xffffffff, -1, 0},
{0xff2b, 3189, 1},
{0xffffffff, -1, 0},
{0xa764, 3072, 1},
{0xa668, 2925, 1},
{0x0216, 535, 1},
{0xffffffff, -1, 0},
{0x118ab, 3543, 1},
{0x1e62, 1860, 1},
{0x0462, 1037, 1},
{0x0162, 312, 1},
{0x0214, 532, 1},
{0x2c62, 655, 1},
{0xa664, 2919, 1},
{0x1ed2, 2013, 1},
{0x04d2, 1193, 1},
{0xa762, 3069, 1},
{0x1fd2, 20, 3},
{0x2cd2, 2709, 1},
{0x118a9, 3537, 1},
{0x00d2, 132, 1},
{0x0206, 511, 1},
{0x10420, 3333, 1},
{0x1e20, 1760, 1},
{0x0420, 938, 1},
{0x0120, 219, 1},
{0xa662, 2916, 1},
{0x2c20, 2517, 1},
{0x1e60, 1856, 1},
{0x0460, 1034, 1},
{0x0160, 309, 1},
{0x0204, 508, 1},
{0x2c60, 2562, 1},
{0xffffffff, -1, 0},
{0x24bd, 2364, 1},
{0x216a, 2322, 1},
{0xa760, 3066, 1},
{0xffffffff, -1, 0},
{0xfb16, 125, 2},
{0x118a7, 3531, 1},
{0x1efa, 2073, 1},
{0x04fa, 1253, 1},
{0x01fa, 493, 1},
{0x1ffa, 2262, 1},
{0xfb14, 109, 2},
{0x03fa, 887, 1},
{0xa660, 2913, 1},
{0x2168, 2316, 1},
{0x01b7, 700, 1},
{0x1fb7, 10, 3},
{0x1f6b, 2211, 1},
{0x2c6b, 2577, 1},
{0x0200, 502, 1},
{0xabb7, 1661, 1},
{0xfb06, 29, 2},
{0x1e56, 1841, 1},
{0x2164, 2304, 1},
{0x0156, 294, 1},
{0x1f56, 62, 3},
{0x0520, 1310, 1},
{0x004f, 40, 1},
{0x0056, 62, 1},
{0x10b7, 2814, 1},
{0xa756, 3051, 1},
{0xfb04, 5, 3},
{0x1e78, 1893, 1},
{0x0478, 1070, 1},
{0x0178, 168, 1},
{0x1e54, 1838, 1},
{0x2162, 2298, 1},
{0x0154, 291, 1},
{0x1f54, 57, 3},
{0xab78, 1472, 1},
{0xa656, 2898, 1},
{0x0054, 56, 1},
{0x1e52, 1835, 1},
{0xa754, 3048, 1},
{0x0152, 288, 1},
{0x1f52, 52, 3},
{0x24c9, 2400, 1},
{0x1e32, 1787, 1},
{0x0052, 49, 1},
{0x0132, 243, 1},
{0xa752, 3045, 1},
{0xffffffff, -1, 0},
{0xfb00, 4, 2},
{0xa654, 2895, 1},
{0xffffffff, -1, 0},
{0xa732, 2997, 1},
{0x2160, 2292, 1},
{0x054f, 1424, 1},
{0x0556, 1445, 1},
{0x1e50, 1832, 1},
{0xa652, 2892, 1},
{0x0150, 285, 1},
{0x1f50, 84, 2},
{0x017b, 348, 1},
{0x1e4e, 1829, 1},
{0x0050, 43, 1},
{0x014e, 282, 1},
{0xa750, 3042, 1},
{0xab7b, 1481, 1},
{0xa77b, 3093, 1},
{0x004e, 37, 1},
{0x0554, 1439, 1},
{0xa74e, 3039, 1},
{0x1e48, 1820, 1},
{0xffffffff, -1, 0},
{0x216b, 2325, 1},
{0x1f48, 2172, 1},
{0xa650, 2889, 1},
{0x0552, 1433, 1},
{0x0048, 21, 1},
{0xffffffff, -1, 0},
{0xa748, 3030, 1},
{0xa64e, 2886, 1},
{0x0532, 1337, 1},
{0x1041e, 3327, 1},
{0x1e1e, 1757, 1},
{0x041e, 932, 1},
{0x011e, 216, 1},
{0x118b7, 3579, 1},
{0x2c1e, 2511, 1},
{0xffffffff, -1, 0},
{0xa648, 2877, 1},
{0x1ff9, 2253, 1},
{0xffffffff, -1, 0},
{0x03f9, 878, 1},
{0x0550, 1427, 1},
{0x10412, 3291, 1},
{0x1e12, 1739, 1},
{0x0412, 896, 1},
{0x0112, 198, 1},
{0x054e, 1421, 1},
{0x2c12, 2475, 1},
{0x10410, 3285, 1},
{0x1e10, 1736, 1},
{0x0410, 890, 1},
{0x0110, 195, 1},
{0xffffffff, -1, 0},
{0x2c10, 2469, 1},
{0x2132, 2289, 1},
{0x0548, 1403, 1},
{0x1ef8, 2070, 1},
{0x04f8, 1250, 1},
{0x01f8, 490, 1},
{0x1ff8, 2250, 1},
{0x0220, 381, 1},
{0x1ee2, 2037, 1},
{0x04e2, 1217, 1},
{0x01e2, 462, 1},
{0x1fe2, 36, 3},
{0x2ce2, 2733, 1},
{0x03e2, 857, 1},
{0x051e, 1307, 1},
{0x1ede, 2031, 1},
{0x04de, 1211, 1},
{0x01de, 456, 1},
{0xffffffff, -1, 0},
{0x2cde, 2727, 1},
{0x03de, 851, 1},
{0x00de, 165, 1},
{0x1f69, 2205, 1},
{0x2c69, 2574, 1},
{0x1eda, 2025, 1},
{0x04da, 1205, 1},
{0x0512, 1289, 1},
{0x1fda, 2244, 1},
{0x2cda, 2721, 1},
{0x03da, 845, 1},
{0x00da, 153, 1},
{0xffffffff, -1, 0},
{0x0510, 1286, 1},
{0x1ed8, 2022, 1},
{0x04d8, 1202, 1},
{0xffffffff, -1, 0},
{0x1fd8, 2274, 1},
{0x2cd8, 2718, 1},
{0x03d8, 842, 1},
{0x00d8, 147, 1},
{0x1ed6, 2019, 1},
{0x04d6, 1199, 1},
{0xffffffff, -1, 0},
{0x1fd6, 76, 2},
{0x2cd6, 2715, 1},
{0x03d6, 792, 1},
{0x00d6, 144, 1},
{0x1ec8, 1998, 1},
{0xffffffff, -1, 0},
{0x01c8, 421, 1},
{0x1fc8, 2232, 1},
{0x2cc8, 2694, 1},
{0xff32, 3210, 1},
{0x00c8, 102, 1},
{0x04c7, 1175, 1},
{0x01c7, 421, 1},
{0x1fc7, 15, 3},
{0x1ec0, 1986, 1},
{0x04c0, 1187, 1},
{0x00c7, 99, 1},
{0xffffffff, -1, 0},
{0x2cc0, 2682, 1},
{0x0179, 345, 1},
{0x00c0, 77, 1},
{0x0232, 574, 1},
{0x01b3, 402, 1},
{0x1fb3, 62, 2},
{0xab79, 1475, 1},
{0xa779, 3090, 1},
{0x10c7, 2859, 1},
{0xabb3, 1649, 1},
{0xa7b3, 3156, 1},
{0x1fa5, 234, 2},
{0x10c0, 2841, 1},
{0x03a5, 807, 1},
{0xffffffff, -1, 0},
{0xaba5, 1607, 1},
{0x01b1, 691, 1},
{0x10ca5, 3468, 1},
{0x10b3, 2802, 1},
{0x2169, 2319, 1},
{0x024e, 601, 1},
{0xabb1, 1643, 1},
{0xa7b1, 682, 1},
{0x10cb1, 3504, 1},
{0x10a5, 2760, 1},
{0xffffffff, -1, 0},
{0x01af, 399, 1},
{0x1faf, 244, 2},
{0xffffffff, -1, 0},
{0x0248, 592, 1},
{0x10b1, 2796, 1},
{0xabaf, 1637, 1},
{0x1fad, 234, 2},
{0x10caf, 3498, 1},
{0x04cd, 1184, 1},
{0x01cd, 429, 1},
{0xabad, 1631, 1},
{0xa7ad, 658, 1},
{0x10cad, 3492, 1},
{0x00cd, 117, 1},
{0x10af, 2790, 1},
{0x021e, 547, 1},
{0x1fa3, 224, 2},
{0xffffffff, -1, 0},
{0x03a3, 800, 1},
{0x10ad, 2784, 1},
{0xaba3, 1601, 1},
{0xffffffff, -1, 0},
{0x10ca3, 3462, 1},
{0x10cd, 2862, 1},
{0x1fa1, 214, 2},
{0x24b7, 2346, 1},
{0x03a1, 796, 1},
{0x0212, 529, 1},
{0xaba1, 1595, 1},
{0x10a3, 2754, 1},
{0x10ca1, 3456, 1},
{0x01d3, 438, 1},
{0x1fd3, 25, 3},
{0x0210, 526, 1},
{0xffffffff, -1, 0},
{0x00d3, 135, 1},
{0x1e97, 34, 2},
{0x10a1, 2748, 1},
{0x0197, 649, 1},
{0x1f97, 204, 2},
{0xffffffff, -1, 0},
{0x0397, 759, 1},
{0x1041d, 3324, 1},
{0xab97, 1565, 1},
{0x041d, 929, 1},
{0x10c97, 3426, 1},
{0x1f1d, 2121, 1},
{0x2c1d, 2508, 1},
{0x1e72, 1884, 1},
{0x0472, 1061, 1},
{0x0172, 336, 1},
{0x118b3, 3567, 1},
{0x2c72, 2580, 1},
{0x0372, 712, 1},
{0x1041b, 3318, 1},
{0xab72, 1454, 1},
{0x041b, 923, 1},
{0x118a5, 3525, 1},
{0x1f1b, 2115, 1},
{0x2c1b, 2502, 1},
{0x1e70, 1881, 1},
{0x0470, 1058, 1},
{0x0170, 333, 1},
{0x118b1, 3561, 1},
{0x2c70, 610, 1},
{0x0370, 709, 1},
{0x1e46, 1817, 1},
{0xab70, 1448, 1},
{0x1e66, 1866, 1},
{0x0466, 1043, 1},
{0x0166, 318, 1},
{0x1e44, 1814, 1},
{0x0046, 15, 1},
{0x118af, 3555, 1},
{0xa746, 3027, 1},
{0xffffffff, -1, 0},
{0xa766, 3075, 1},
{0x0044, 9, 1},
{0x118ad, 3549, 1},
{0xa744, 3024, 1},
{0x1e7a, 1896, 1},
{0x047a, 1073, 1},
{0x1e3a, 1799, 1},
{0xffffffff, -1, 0},
{0xa646, 2874, 1},
{0x1f3a, 2154, 1},
{0xa666, 2922, 1},
{0xab7a, 1478, 1},
{0x118a3, 3519, 1},
{0xa644, 2871, 1},
{0xa73a, 3009, 1},
{0xffffffff, -1, 0},
{0x1ef4, 2064, 1},
{0x04f4, 1244, 1},
{0x01f4, 487, 1},
{0x1ff4, 101, 2},
{0x118a1, 3513, 1},
{0x03f4, 762, 1},
{0x1eec, 2052, 1},
{0x04ec, 1232, 1},
{0x01ec, 477, 1},
{0x1fec, 2286, 1},
{0x0546, 1397, 1},
{0x03ec, 872, 1},
{0xffffffff, -1, 0},
{0x013f, 261, 1},
{0x1f3f, 2169, 1},
{0x0544, 1391, 1},
{0x1eea, 2049, 1},
{0x04ea, 1229, 1},
{0x01ea, 474, 1},
{0x1fea, 2256, 1},
{0xffffffff, -1, 0},
{0x03ea, 869, 1},
{0x1ee8, 2046, 1},
{0x04e8, 1226, 1},
{0x01e8, 471, 1},
{0x1fe8, 2280, 1},
{0x053a, 1361, 1},
{0x03e8, 866, 1},
{0x1ee6, 2043, 1},
{0x04e6, 1223, 1},
{0x01e6, 468, 1},
{0x1fe6, 88, 2},
{0x1f4b, 2181, 1},
{0x03e6, 863, 1},
{0x1e5e, 1853, 1},
{0x004b, 27, 1},
{0x015e, 306, 1},
{0x2166, 2310, 1},
{0x1ee4, 2040, 1},
{0x04e4, 1220, 1},
{0x01e4, 465, 1},
{0x1fe4, 80, 2},
{0xa75e, 3063, 1},
{0x03e4, 860, 1},
{0x1ee0, 2034, 1},
{0x04e0, 1214, 1},
{0x01e0, 459, 1},
{0x053f, 1376, 1},
{0x2ce0, 2730, 1},
{0x03e0, 854, 1},
{0x1edc, 2028, 1},
{0x04dc, 1208, 1},
{0xa65e, 2910, 1},
{0xffffffff, -1, 0},
{0x2cdc, 2724, 1},
{0x03dc, 848, 1},
{0x00dc, 159, 1},
{0x1ed0, 2010, 1},
{0x04d0, 1190, 1},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0x2cd0, 2706, 1},
{0x03d0, 742, 1},
{0x00d0, 126, 1},
{0x1ecc, 2004, 1},
{0x054b, 1412, 1},
{0xffffffff, -1, 0},
{0x1fcc, 71, 2},
{0x2ccc, 2700, 1},
{0x1ec6, 1995, 1},
{0x00cc, 114, 1},
{0xffffffff, -1, 0},
{0x1fc6, 67, 2},
{0x2cc6, 2691, 1},
{0x24c8, 2397, 1},
{0x00c6, 96, 1},
{0x04c5, 1172, 1},
{0x01c5, 417, 1},
{0xffffffff, -1, 0},
{0x1fbb, 2229, 1},
{0x24c7, 2394, 1},
{0x00c5, 92, 1},
{0x1fb9, 2271, 1},
{0xabbb, 1673, 1},
{0x24c0, 2373, 1},
{0x04c3, 1169, 1},
{0xabb9, 1667, 1},
{0x1fc3, 71, 2},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0x00c3, 86, 1},
{0x10c5, 2856, 1},
{0x10bb, 2826, 1},
{0x1ed4, 2016, 1},
{0x04d4, 1196, 1},
{0x10b9, 2820, 1},
{0x13fc, 1700, 1},
{0x2cd4, 2712, 1},
{0x0246, 589, 1},
{0x00d4, 138, 1},
{0x10c3, 2850, 1},
{0xffffffff, -1, 0},
{0xff3a, 3234, 1},
{0x0244, 688, 1},
{0x019f, 670, 1},
{0x1f9f, 204, 2},
{0xffffffff, -1, 0},
{0x039f, 789, 1},
{0xffffffff, -1, 0},
{0xab9f, 1589, 1},
{0xffffffff, -1, 0},
{0x10c9f, 3450, 1},
{0x019d, 667, 1},
{0x1f9d, 194, 2},
{0x023a, 2565, 1},
{0x039d, 783, 1},
{0x1e5a, 1847, 1},
{0xab9d, 1583, 1},
{0x015a, 300, 1},
{0x10c9d, 3444, 1},
{0x1e9b, 1856, 1},
{0x24cd, 2412, 1},
{0x005a, 74, 1},
{0x1f9b, 184, 2},
{0xa75a, 3057, 1},
{0x039b, 776, 1},
{0x1ece, 2007, 1},
{0xab9b, 1577, 1},
{0x1e99, 42, 2},
{0x10c9b, 3438, 1},
{0x2cce, 2703, 1},
{0x1f99, 174, 2},
{0x00ce, 120, 1},
{0x0399, 767, 1},
{0xa65a, 2904, 1},
{0xab99, 1571, 1},
{0xffffffff, -1, 0},
{0x10c99, 3432, 1},
{0x0193, 634, 1},
{0x1f93, 184, 2},
{0x1e58, 1844, 1},
{0x0393, 746, 1},
{0x0158, 297, 1},
{0xab93, 1553, 1},
{0xffffffff, -1, 0},
{0x10c93, 3414, 1},
{0x0058, 68, 1},
{0x042d, 977, 1},
{0xa758, 3054, 1},
{0x1f2d, 2139, 1},
{0x2c2d, 2556, 1},
{0x118bb, 3591, 1},
{0x0191, 369, 1},
{0x1f91, 174, 2},
{0x118b9, 3585, 1},
{0x0391, 739, 1},
{0xffffffff, -1, 0},
{0xab91, 1547, 1},
{0xa658, 2901, 1},
{0x10c91, 3408, 1},
{0x018f, 625, 1},
{0x1f8f, 164, 2},
{0xffffffff, -1, 0},
{0x038f, 836, 1},
{0xffffffff, -1, 0},
{0xab8f, 1541, 1},
{0xffffffff, -1, 0},
{0x10c8f, 3402, 1},
{0x018b, 366, 1},
{0x1f8b, 144, 2},
{0xffffffff, -1, 0},
{0x0187, 363, 1},
{0x1f87, 164, 2},
{0xab8b, 1529, 1},
{0xa78b, 3111, 1},
{0x10c8b, 3390, 1},
{0xab87, 1517, 1},
{0x04c1, 1166, 1},
{0x10c87, 3378, 1},
{0x1e7e, 1902, 1},
{0x047e, 1079, 1},
{0xffffffff, -1, 0},
{0x00c1, 80, 1},
{0x2c7e, 580, 1},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xab7e, 1490, 1},
{0xa77e, 3096, 1},
{0x1e76, 1890, 1},
{0x0476, 1067, 1},
{0x0176, 342, 1},
{0x1e42, 1811, 1},
{0x10c1, 2844, 1},
{0x0376, 715, 1},
{0x1e36, 1793, 1},
{0xab76, 1466, 1},
{0x0136, 249, 1},
{0x0042, 3, 1},
{0x1e3e, 1805, 1},
{0xa742, 3021, 1},
{0x1e38, 1796, 1},
{0x1f3e, 2166, 1},
{0xa736, 3003, 1},
{0x1f38, 2148, 1},
{0xffffffff, -1, 0},
{0x0587, 105, 2},
{0xa73e, 3015, 1},
{0xffffffff, -1, 0},
{0xa738, 3006, 1},
{0xa642, 2868, 1},
{0x1e5c, 1850, 1},
{0x1e34, 1790, 1},
{0x015c, 303, 1},
{0x0134, 246, 1},
{0x1ef6, 2067, 1},
{0x04f6, 1247, 1},
{0x01f6, 372, 1},
{0x1ff6, 92, 2},
{0xa75c, 3060, 1},
{0xa734, 3000, 1},
{0x1ef0, 2058, 1},
{0x04f0, 1238, 1},
{0x01f0, 20, 2},
{0xffffffff, -1, 0},
{0x1e30, 1784, 1},
{0x03f0, 772, 1},
{0x0130, 261, 2},
{0x0542, 1385, 1},
{0xa65c, 2907, 1},
{0x1f83, 144, 2},
{0x0536, 1349, 1},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xab83, 1505, 1},
{0x053e, 1373, 1},
{0x10c83, 3366, 1},
{0x0538, 1355, 1},
{0x1eee, 2055, 1},
{0x04ee, 1235, 1},
{0x01ee, 480, 1},
{0x1f8d, 154, 2},
{0xffffffff, -1, 0},
{0x03ee, 875, 1},
{0xffffffff, -1, 0},
{0xab8d, 1535, 1},
{0xa78d, 643, 1},
{0x10c8d, 3396, 1},
{0x0534, 1343, 1},
{0x0181, 613, 1},
{0x1f81, 134, 2},
{0x013d, 258, 1},
{0x1f3d, 2163, 1},
{0xffffffff, -1, 0},
{0xab81, 1499, 1},
{0x017f, 52, 1},
{0x10c81, 3360, 1},
{0x2c7f, 583, 1},
{0x037f, 881, 1},
{0xff2d, 3195, 1},
{0xab7f, 1493, 1},
{0x1e74, 1887, 1},
{0x0474, 1064, 1},
{0x0174, 339, 1},
{0x1e3c, 1802, 1},
{0x0149, 46, 2},
{0x1f49, 2175, 1},
{0x1f3c, 2160, 1},
{0xab74, 1460, 1},
{0x0049, 3606, 1},
{0x0143, 267, 1},
{0x24cc, 2409, 1},
{0xa73c, 3012, 1},
{0xffffffff, -1, 0},
{0x0043, 6, 1},
{0x0141, 264, 1},
{0x24c6, 2391, 1},
{0x013b, 255, 1},
{0x1f3b, 2157, 1},
{0x0041, 0, 1},
{0x0139, 252, 1},
{0x1f39, 2151, 1},
{0x24c5, 2388, 1},
{0x24bb, 2358, 1},
{0x13fa, 1694, 1},
{0x053d, 1370, 1},
{0x24b9, 2352, 1},
{0x0429, 965, 1},
{0x2183, 2340, 1},
{0x1f29, 2127, 1},
{0x2c29, 2544, 1},
{0x24c3, 2382, 1},
{0x10427, 3354, 1},
{0x10425, 3348, 1},
{0x0427, 959, 1},
{0x0425, 953, 1},
{0xffffffff, -1, 0},
{0x2c27, 2538, 1},
{0x2c25, 2532, 1},
{0x0549, 1406, 1},
{0x053c, 1367, 1},
{0x10423, 3342, 1},
{0xffffffff, -1, 0},
{0x0423, 947, 1},
{0x0543, 1388, 1},
{0xffffffff, -1, 0},
{0x2c23, 2526, 1},
{0xff36, 3222, 1},
{0xffffffff, -1, 0},
{0x0541, 1382, 1},
{0x10421, 3336, 1},
{0x053b, 1364, 1},
{0x0421, 941, 1},
{0xff38, 3228, 1},
{0x0539, 1358, 1},
{0x2c21, 2520, 1},
{0x10419, 3312, 1},
{0x10417, 3306, 1},
{0x0419, 917, 1},
{0x0417, 911, 1},
{0x1f19, 2109, 1},
{0x2c19, 2496, 1},
{0x2c17, 2490, 1},
{0x023e, 2568, 1},
{0xff34, 3216, 1},
{0x10415, 3300, 1},
{0x10413, 3294, 1},
{0x0415, 905, 1},
{0x0413, 899, 1},
{0xffffffff, -1, 0},
{0x2c15, 2484, 1},
{0x2c13, 2478, 1},
{0xffffffff, -1, 0},
{0x24ce, 2415, 1},
{0x1040f, 3282, 1},
{0xffffffff, -1, 0},
{0x040f, 1031, 1},
{0xff30, 3204, 1},
{0x1f0f, 2103, 1},
{0x2c0f, 2466, 1},
{0x1040d, 3276, 1},
{0xffffffff, -1, 0},
{0x040d, 1025, 1},
{0x0147, 273, 1},
{0x1f0d, 2097, 1},
{0x2c0d, 2460, 1},
{0x1040b, 3270, 1},
{0x0047, 18, 1},
{0x040b, 1019, 1},
{0x0230, 571, 1},
{0x1f0b, 2091, 1},
{0x2c0b, 2454, 1},
{0x10409, 3264, 1},
{0x10405, 3252, 1},
{0x0409, 1013, 1},
{0x0405, 1001, 1},
{0x1f09, 2085, 1},
{0x2c09, 2448, 1},
{0x2c05, 2436, 1},
{0x10403, 3246, 1},
{0x10401, 3240, 1},
{0x0403, 995, 1},
{0x0401, 989, 1},
{0xffffffff, -1, 0},
{0x2c03, 2430, 1},
{0x2c01, 2424, 1},
{0x13f9, 1691, 1},
{0x042f, 983, 1},
{0xffffffff, -1, 0},
{0x1f2f, 2145, 1},
{0x1041f, 3330, 1},
{0xffffffff, -1, 0},
{0x041f, 935, 1},
{0x023d, 378, 1},
{0x10411, 3288, 1},
{0x2c1f, 2514, 1},
{0x0411, 893, 1},
{0x0547, 1400, 1},
{0xffffffff, -1, 0},
{0x2c11, 2472, 1},
{0x10407, 3258, 1},
{0xffffffff, -1, 0},
{0x0407, 1007, 1},
{0x24c1, 2376, 1},
{0xffffffff, -1, 0},
{0x2c07, 2442, 1},
{0xffffffff, -1, 0},
{0x13f8, 1688, 1},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xff39, 3231, 1},
{0xffffffff, -1, 0},
{0x0243, 354, 1},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0x0241, 586, 1},
{0xff29, 3183, 1},
{0x023b, 577, 1},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xff27, 3177, 1},
{0xff25, 3171, 1},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xff23, 3165, 1},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xff21, 3159, 1},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0},
{0xfb17, 117, 2},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xff2f, 3201, 1},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xfb15, 113, 2},
{0xfb13, 121, 2},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xffffffff, -1, 0},
{0xfb05, 29, 2},
{0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0},
{0xfb03, 0, 3},
{0xfb01, 8, 2}
};
if (0 == 0)
{
int key = hash(&code);
if (key <= MAX_HASH_VALUE && key >= 0)
{
OnigCodePoint gcode = wordlist[key].code;
if (code == gcode && wordlist[key].index >= 0)
return &wordlist[key];
}
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_3373_1 |
crossvul-cpp_data_bad_674_4 | /**
* FreeRDP: A Remote Desktop Protocol Implementation
* NSCodec Library - SSE2 Optimizations
*
* Copyright 2012 Vic Lee
*
* 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <xmmintrin.h>
#include <emmintrin.h>
#include <freerdp/codec/color.h>
#include <winpr/crt.h>
#include <winpr/sysinfo.h>
#include "nsc_types.h"
#include "nsc_sse2.h"
static void nsc_encode_argb_to_aycocg_sse2(NSC_CONTEXT* context,
const BYTE* data, UINT32 scanline)
{
UINT16 x;
UINT16 y;
UINT16 rw;
BYTE ccl;
const BYTE* src;
BYTE* yplane = NULL;
BYTE* coplane = NULL;
BYTE* cgplane = NULL;
BYTE* aplane = NULL;
__m128i r_val;
__m128i g_val;
__m128i b_val;
__m128i a_val;
__m128i y_val;
__m128i co_val;
__m128i cg_val;
UINT32 tempWidth;
tempWidth = ROUND_UP_TO(context->width, 8);
rw = (context->ChromaSubsamplingLevel > 0 ? tempWidth : context->width);
ccl = context->ColorLossLevel;
for (y = 0; y < context->height; y++)
{
src = data + (context->height - 1 - y) * scanline;
yplane = context->priv->PlaneBuffers[0] + y * rw;
coplane = context->priv->PlaneBuffers[1] + y * rw;
cgplane = context->priv->PlaneBuffers[2] + y * rw;
aplane = context->priv->PlaneBuffers[3] + y * context->width;
for (x = 0; x < context->width; x += 8)
{
switch (context->format)
{
case PIXEL_FORMAT_BGRX32:
b_val = _mm_set_epi16(*(src + 28), *(src + 24), *(src + 20), *(src + 16),
*(src + 12), *(src + 8), *(src + 4), *src);
g_val = _mm_set_epi16(*(src + 29), *(src + 25), *(src + 21), *(src + 17),
*(src + 13), *(src + 9), *(src + 5), *(src + 1));
r_val = _mm_set_epi16(*(src + 30), *(src + 26), *(src + 22), *(src + 18),
*(src + 14), *(src + 10), *(src + 6), *(src + 2));
a_val = _mm_set1_epi16(0xFF);
src += 32;
break;
case PIXEL_FORMAT_BGRA32:
b_val = _mm_set_epi16(*(src + 28), *(src + 24), *(src + 20), *(src + 16),
*(src + 12), *(src + 8), *(src + 4), *src);
g_val = _mm_set_epi16(*(src + 29), *(src + 25), *(src + 21), *(src + 17),
*(src + 13), *(src + 9), *(src + 5), *(src + 1));
r_val = _mm_set_epi16(*(src + 30), *(src + 26), *(src + 22), *(src + 18),
*(src + 14), *(src + 10), *(src + 6), *(src + 2));
a_val = _mm_set_epi16(*(src + 31), *(src + 27), *(src + 23), *(src + 19),
*(src + 15), *(src + 11), *(src + 7), *(src + 3));
src += 32;
break;
case PIXEL_FORMAT_RGBX32:
r_val = _mm_set_epi16(*(src + 28), *(src + 24), *(src + 20), *(src + 16),
*(src + 12), *(src + 8), *(src + 4), *src);
g_val = _mm_set_epi16(*(src + 29), *(src + 25), *(src + 21), *(src + 17),
*(src + 13), *(src + 9), *(src + 5), *(src + 1));
b_val = _mm_set_epi16(*(src + 30), *(src + 26), *(src + 22), *(src + 18),
*(src + 14), *(src + 10), *(src + 6), *(src + 2));
a_val = _mm_set1_epi16(0xFF);
src += 32;
break;
case PIXEL_FORMAT_RGBA32:
r_val = _mm_set_epi16(*(src + 28), *(src + 24), *(src + 20), *(src + 16),
*(src + 12), *(src + 8), *(src + 4), *src);
g_val = _mm_set_epi16(*(src + 29), *(src + 25), *(src + 21), *(src + 17),
*(src + 13), *(src + 9), *(src + 5), *(src + 1));
b_val = _mm_set_epi16(*(src + 30), *(src + 26), *(src + 22), *(src + 18),
*(src + 14), *(src + 10), *(src + 6), *(src + 2));
a_val = _mm_set_epi16(*(src + 31), *(src + 27), *(src + 23), *(src + 19),
*(src + 15), *(src + 11), *(src + 7), *(src + 3));
src += 32;
break;
case PIXEL_FORMAT_BGR24:
b_val = _mm_set_epi16(*(src + 21), *(src + 18), *(src + 15), *(src + 12),
*(src + 9), *(src + 6), *(src + 3), *src);
g_val = _mm_set_epi16(*(src + 22), *(src + 19), *(src + 16), *(src + 13),
*(src + 10), *(src + 7), *(src + 4), *(src + 1));
r_val = _mm_set_epi16(*(src + 23), *(src + 20), *(src + 17), *(src + 14),
*(src + 11), *(src + 8), *(src + 5), *(src + 2));
a_val = _mm_set1_epi16(0xFF);
src += 24;
break;
case PIXEL_FORMAT_RGB24:
r_val = _mm_set_epi16(*(src + 21), *(src + 18), *(src + 15), *(src + 12),
*(src + 9), *(src + 6), *(src + 3), *src);
g_val = _mm_set_epi16(*(src + 22), *(src + 19), *(src + 16), *(src + 13),
*(src + 10), *(src + 7), *(src + 4), *(src + 1));
b_val = _mm_set_epi16(*(src + 23), *(src + 20), *(src + 17), *(src + 14),
*(src + 11), *(src + 8), *(src + 5), *(src + 2));
a_val = _mm_set1_epi16(0xFF);
src += 24;
break;
case PIXEL_FORMAT_BGR16:
b_val = _mm_set_epi16(
(((*(src + 15)) & 0xF8) | ((*(src + 15)) >> 5)),
(((*(src + 13)) & 0xF8) | ((*(src + 13)) >> 5)),
(((*(src + 11)) & 0xF8) | ((*(src + 11)) >> 5)),
(((*(src + 9)) & 0xF8) | ((*(src + 9)) >> 5)),
(((*(src + 7)) & 0xF8) | ((*(src + 7)) >> 5)),
(((*(src + 5)) & 0xF8) | ((*(src + 5)) >> 5)),
(((*(src + 3)) & 0xF8) | ((*(src + 3)) >> 5)),
(((*(src + 1)) & 0xF8) | ((*(src + 1)) >> 5)));
g_val = _mm_set_epi16(
((((*(src + 15)) & 0x07) << 5) | (((*(src + 14)) & 0xE0) >> 3)),
((((*(src + 13)) & 0x07) << 5) | (((*(src + 12)) & 0xE0) >> 3)),
((((*(src + 11)) & 0x07) << 5) | (((*(src + 10)) & 0xE0) >> 3)),
((((*(src + 9)) & 0x07) << 5) | (((*(src + 8)) & 0xE0) >> 3)),
((((*(src + 7)) & 0x07) << 5) | (((*(src + 6)) & 0xE0) >> 3)),
((((*(src + 5)) & 0x07) << 5) | (((*(src + 4)) & 0xE0) >> 3)),
((((*(src + 3)) & 0x07) << 5) | (((*(src + 2)) & 0xE0) >> 3)),
((((*(src + 1)) & 0x07) << 5) | (((*src) & 0xE0) >> 3)));
r_val = _mm_set_epi16(
((((*(src + 14)) & 0x1F) << 3) | (((*(src + 14)) >> 2) & 0x07)),
((((*(src + 12)) & 0x1F) << 3) | (((*(src + 12)) >> 2) & 0x07)),
((((*(src + 10)) & 0x1F) << 3) | (((*(src + 10)) >> 2) & 0x07)),
((((*(src + 8)) & 0x1F) << 3) | (((*(src + 8)) >> 2) & 0x07)),
((((*(src + 6)) & 0x1F) << 3) | (((*(src + 6)) >> 2) & 0x07)),
((((*(src + 4)) & 0x1F) << 3) | (((*(src + 4)) >> 2) & 0x07)),
((((*(src + 2)) & 0x1F) << 3) | (((*(src + 2)) >> 2) & 0x07)),
((((*src) & 0x1F) << 3) | (((*src) >> 2) & 0x07)));
a_val = _mm_set1_epi16(0xFF);
src += 16;
break;
case PIXEL_FORMAT_RGB16:
r_val = _mm_set_epi16(
(((*(src + 15)) & 0xF8) | ((*(src + 15)) >> 5)),
(((*(src + 13)) & 0xF8) | ((*(src + 13)) >> 5)),
(((*(src + 11)) & 0xF8) | ((*(src + 11)) >> 5)),
(((*(src + 9)) & 0xF8) | ((*(src + 9)) >> 5)),
(((*(src + 7)) & 0xF8) | ((*(src + 7)) >> 5)),
(((*(src + 5)) & 0xF8) | ((*(src + 5)) >> 5)),
(((*(src + 3)) & 0xF8) | ((*(src + 3)) >> 5)),
(((*(src + 1)) & 0xF8) | ((*(src + 1)) >> 5)));
g_val = _mm_set_epi16(
((((*(src + 15)) & 0x07) << 5) | (((*(src + 14)) & 0xE0) >> 3)),
((((*(src + 13)) & 0x07) << 5) | (((*(src + 12)) & 0xE0) >> 3)),
((((*(src + 11)) & 0x07) << 5) | (((*(src + 10)) & 0xE0) >> 3)),
((((*(src + 9)) & 0x07) << 5) | (((*(src + 8)) & 0xE0) >> 3)),
((((*(src + 7)) & 0x07) << 5) | (((*(src + 6)) & 0xE0) >> 3)),
((((*(src + 5)) & 0x07) << 5) | (((*(src + 4)) & 0xE0) >> 3)),
((((*(src + 3)) & 0x07) << 5) | (((*(src + 2)) & 0xE0) >> 3)),
((((*(src + 1)) & 0x07) << 5) | (((*src) & 0xE0) >> 3)));
b_val = _mm_set_epi16(
((((*(src + 14)) & 0x1F) << 3) | (((*(src + 14)) >> 2) & 0x07)),
((((*(src + 12)) & 0x1F) << 3) | (((*(src + 12)) >> 2) & 0x07)),
((((*(src + 10)) & 0x1F) << 3) | (((*(src + 10)) >> 2) & 0x07)),
((((*(src + 8)) & 0x1F) << 3) | (((*(src + 8)) >> 2) & 0x07)),
((((*(src + 6)) & 0x1F) << 3) | (((*(src + 6)) >> 2) & 0x07)),
((((*(src + 4)) & 0x1F) << 3) | (((*(src + 4)) >> 2) & 0x07)),
((((*(src + 2)) & 0x1F) << 3) | (((*(src + 2)) >> 2) & 0x07)),
((((*src) & 0x1F) << 3) | (((*src) >> 2) & 0x07)));
a_val = _mm_set1_epi16(0xFF);
src += 16;
break;
case PIXEL_FORMAT_A4:
{
int shift;
BYTE idx[8];
for (shift = 7; shift >= 0; shift--)
{
idx[shift] = ((*src) >> shift) & 1;
idx[shift] |= (((*(src + 1)) >> shift) & 1) << 1;
idx[shift] |= (((*(src + 2)) >> shift) & 1) << 2;
idx[shift] |= (((*(src + 3)) >> shift) & 1) << 3;
idx[shift] *= 3;
}
r_val = _mm_set_epi16(
context->palette[idx[0]],
context->palette[idx[1]],
context->palette[idx[2]],
context->palette[idx[3]],
context->palette[idx[4]],
context->palette[idx[5]],
context->palette[idx[6]],
context->palette[idx[7]]);
g_val = _mm_set_epi16(
context->palette[idx[0] + 1],
context->palette[idx[1] + 1],
context->palette[idx[2] + 1],
context->palette[idx[3] + 1],
context->palette[idx[4] + 1],
context->palette[idx[5] + 1],
context->palette[idx[6] + 1],
context->palette[idx[7] + 1]);
b_val = _mm_set_epi16(
context->palette[idx[0] + 2],
context->palette[idx[1] + 2],
context->palette[idx[2] + 2],
context->palette[idx[3] + 2],
context->palette[idx[4] + 2],
context->palette[idx[5] + 2],
context->palette[idx[6] + 2],
context->palette[idx[7] + 2]);
src += 4;
}
a_val = _mm_set1_epi16(0xFF);
break;
case PIXEL_FORMAT_RGB8:
{
r_val = _mm_set_epi16(
context->palette[(*(src + 7)) * 3],
context->palette[(*(src + 6)) * 3],
context->palette[(*(src + 5)) * 3],
context->palette[(*(src + 4)) * 3],
context->palette[(*(src + 3)) * 3],
context->palette[(*(src + 2)) * 3],
context->palette[(*(src + 1)) * 3],
context->palette[(*src) * 3]);
g_val = _mm_set_epi16(
context->palette[(*(src + 7)) * 3 + 1],
context->palette[(*(src + 6)) * 3 + 1],
context->palette[(*(src + 5)) * 3 + 1],
context->palette[(*(src + 4)) * 3 + 1],
context->palette[(*(src + 3)) * 3 + 1],
context->palette[(*(src + 2)) * 3 + 1],
context->palette[(*(src + 1)) * 3 + 1],
context->palette[(*src) * 3 + 1]);
b_val = _mm_set_epi16(
context->palette[(*(src + 7)) * 3 + 2],
context->palette[(*(src + 6)) * 3 + 2],
context->palette[(*(src + 5)) * 3 + 2],
context->palette[(*(src + 4)) * 3 + 2],
context->palette[(*(src + 3)) * 3 + 2],
context->palette[(*(src + 2)) * 3 + 2],
context->palette[(*(src + 1)) * 3 + 2],
context->palette[(*src) * 3 + 2]);
src += 8;
}
a_val = _mm_set1_epi16(0xFF);
break;
default:
r_val = g_val = b_val = a_val = _mm_set1_epi16(0);
break;
}
y_val = _mm_srai_epi16(r_val, 2);
y_val = _mm_add_epi16(y_val, _mm_srai_epi16(g_val, 1));
y_val = _mm_add_epi16(y_val, _mm_srai_epi16(b_val, 2));
co_val = _mm_sub_epi16(r_val, b_val);
co_val = _mm_srai_epi16(co_val, ccl);
cg_val = _mm_sub_epi16(g_val, _mm_srai_epi16(r_val, 1));
cg_val = _mm_sub_epi16(cg_val, _mm_srai_epi16(b_val, 1));
cg_val = _mm_srai_epi16(cg_val, ccl);
y_val = _mm_packus_epi16(y_val, y_val);
_mm_storeu_si128((__m128i*) yplane, y_val);
co_val = _mm_packs_epi16(co_val, co_val);
_mm_storeu_si128((__m128i*) coplane, co_val);
cg_val = _mm_packs_epi16(cg_val, cg_val);
_mm_storeu_si128((__m128i*) cgplane, cg_val);
a_val = _mm_packus_epi16(a_val, a_val);
_mm_storeu_si128((__m128i*) aplane, a_val);
yplane += 8;
coplane += 8;
cgplane += 8;
aplane += 8;
}
if (context->ChromaSubsamplingLevel > 0 && (context->width % 2) == 1)
{
context->priv->PlaneBuffers[0][y * rw + context->width] =
context->priv->PlaneBuffers[0][y * rw + context->width - 1];
context->priv->PlaneBuffers[1][y * rw + context->width] =
context->priv->PlaneBuffers[1][y * rw + context->width - 1];
context->priv->PlaneBuffers[2][y * rw + context->width] =
context->priv->PlaneBuffers[2][y * rw + context->width - 1];
}
}
if (context->ChromaSubsamplingLevel > 0 && (y % 2) == 1)
{
yplane = context->priv->PlaneBuffers[0] + y * rw;
coplane = context->priv->PlaneBuffers[1] + y * rw;
cgplane = context->priv->PlaneBuffers[2] + y * rw;
CopyMemory(yplane, yplane - rw, rw);
CopyMemory(coplane, coplane - rw, rw);
CopyMemory(cgplane, cgplane - rw, rw);
}
}
static void nsc_encode_subsampling_sse2(NSC_CONTEXT* context)
{
UINT16 x;
UINT16 y;
BYTE* co_dst;
BYTE* cg_dst;
INT8* co_src0;
INT8* co_src1;
INT8* cg_src0;
INT8* cg_src1;
UINT32 tempWidth;
UINT32 tempHeight;
__m128i t;
__m128i val;
__m128i mask = _mm_set1_epi16(0xFF);
tempWidth = ROUND_UP_TO(context->width, 8);
tempHeight = ROUND_UP_TO(context->height, 2);
for (y = 0; y < tempHeight >> 1; y++)
{
co_dst = context->priv->PlaneBuffers[1] + y * (tempWidth >> 1);
cg_dst = context->priv->PlaneBuffers[2] + y * (tempWidth >> 1);
co_src0 = (INT8*) context->priv->PlaneBuffers[1] + (y << 1) * tempWidth;
co_src1 = co_src0 + tempWidth;
cg_src0 = (INT8*) context->priv->PlaneBuffers[2] + (y << 1) * tempWidth;
cg_src1 = cg_src0 + tempWidth;
for (x = 0; x < tempWidth >> 1; x += 8)
{
t = _mm_loadu_si128((__m128i*) co_src0);
t = _mm_avg_epu8(t, _mm_loadu_si128((__m128i*) co_src1));
val = _mm_and_si128(_mm_srli_si128(t, 1), mask);
val = _mm_avg_epu16(val, _mm_and_si128(t, mask));
val = _mm_packus_epi16(val, val);
_mm_storeu_si128((__m128i*) co_dst, val);
co_dst += 8;
co_src0 += 16;
co_src1 += 16;
t = _mm_loadu_si128((__m128i*) cg_src0);
t = _mm_avg_epu8(t, _mm_loadu_si128((__m128i*) cg_src1));
val = _mm_and_si128(_mm_srli_si128(t, 1), mask);
val = _mm_avg_epu16(val, _mm_and_si128(t, mask));
val = _mm_packus_epi16(val, val);
_mm_storeu_si128((__m128i*) cg_dst, val);
cg_dst += 8;
cg_src0 += 16;
cg_src1 += 16;
}
}
}
static void nsc_encode_sse2(NSC_CONTEXT* context, const BYTE* data,
UINT32 scanline)
{
nsc_encode_argb_to_aycocg_sse2(context, data, scanline);
if (context->ChromaSubsamplingLevel > 0)
{
nsc_encode_subsampling_sse2(context);
}
}
void nsc_init_sse2(NSC_CONTEXT* context)
{
if (!IsProcessorFeaturePresent(PF_XMMI64_INSTRUCTIONS_AVAILABLE))
return;
PROFILER_RENAME(context->priv->prof_nsc_encode, "nsc_encode_sse2");
context->encode = nsc_encode_sse2;
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_674_4 |
crossvul-cpp_data_good_2775_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) 2008, Jerome Fimes, Communications & Systemes <jerome.fimes@c-s.fr>
* Copyright (c) 2006-2007, Parvatha Elangovan
* Copyright (c) 2010-2011, Kaori Hagihara
* Copyright (c) 2011-2012, Centre National d'Etudes Spatiales (CNES), France
* 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"
/** @defgroup J2K J2K - JPEG-2000 codestream reader/writer */
/*@{*/
/** @name Local static functions */
/*@{*/
#define OPJ_UNUSED(x) (void)x
/**
* Sets up the procedures to do on reading header. Developpers wanting to extend the library can add their own reading procedures.
*/
static OPJ_BOOL opj_j2k_setup_header_reading(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager);
/**
* The read header procedure.
*/
static OPJ_BOOL opj_j2k_read_header_procedure(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* The default encoding validation procedure without any extension.
*
* @param p_j2k the jpeg2000 codec to validate.
* @param p_stream the input stream to validate.
* @param p_manager the user event manager.
*
* @return true if the parameters are correct.
*/
static OPJ_BOOL opj_j2k_encoding_validation(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* The default decoding validation procedure without any extension.
*
* @param p_j2k the jpeg2000 codec to validate.
* @param p_stream the input stream to validate.
* @param p_manager the user event manager.
*
* @return true if the parameters are correct.
*/
static OPJ_BOOL opj_j2k_decoding_validation(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Sets up the validation ,i.e. adds the procedures to lauch to make sure the codec parameters
* are valid. Developpers wanting to extend the library can add their own validation procedures.
*/
static OPJ_BOOL opj_j2k_setup_encoding_validation(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager);
/**
* Sets up the validation ,i.e. adds the procedures to lauch to make sure the codec parameters
* are valid. Developpers wanting to extend the library can add their own validation procedures.
*/
static OPJ_BOOL opj_j2k_setup_decoding_validation(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager);
/**
* Sets up the validation ,i.e. adds the procedures to lauch to make sure the codec parameters
* are valid. Developpers wanting to extend the library can add their own validation procedures.
*/
static OPJ_BOOL opj_j2k_setup_end_compress(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager);
/**
* The mct encoding validation procedure.
*
* @param p_j2k the jpeg2000 codec to validate.
* @param p_stream the input stream to validate.
* @param p_manager the user event manager.
*
* @return true if the parameters are correct.
*/
static OPJ_BOOL opj_j2k_mct_validation(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Builds the tcd decoder to use to decode tile.
*/
static OPJ_BOOL opj_j2k_build_decoder(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Builds the tcd encoder to use to encode tile.
*/
static OPJ_BOOL opj_j2k_build_encoder(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Creates a tile-coder decoder.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_create_tcd(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Excutes the given procedures on the given codec.
*
* @param p_procedure_list the list of procedures to execute
* @param p_j2k the jpeg2000 codec to execute the procedures on.
* @param p_stream the stream to execute the procedures on.
* @param p_manager the user manager.
*
* @return true if all the procedures were successfully executed.
*/
static OPJ_BOOL opj_j2k_exec(opj_j2k_t * p_j2k,
opj_procedure_list_t * p_procedure_list,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Updates the rates of the tcp.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_update_rates(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Copies the decoding tile parameters onto all the tile parameters.
* Creates also the tile decoder.
*/
static OPJ_BOOL opj_j2k_copy_default_tcp_and_create_tcd(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Destroys the memory associated with the decoding of headers.
*/
static OPJ_BOOL opj_j2k_destroy_header_memory(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads the lookup table containing all the marker, status and action, and returns the handler associated
* with the marker value.
* @param p_id Marker value to look up
*
* @return the handler associated with the id.
*/
static const struct opj_dec_memory_marker_handler * opj_j2k_get_marker_handler(
OPJ_UINT32 p_id);
/**
* Destroys a tile coding parameter structure.
*
* @param p_tcp the tile coding parameter to destroy.
*/
static void opj_j2k_tcp_destroy(opj_tcp_t *p_tcp);
/**
* Destroys the data inside a tile coding parameter structure.
*
* @param p_tcp the tile coding parameter which contain data to destroy.
*/
static void opj_j2k_tcp_data_destroy(opj_tcp_t *p_tcp);
/**
* Destroys a coding parameter structure.
*
* @param p_cp the coding parameter to destroy.
*/
static void opj_j2k_cp_destroy(opj_cp_t *p_cp);
/**
* Compare 2 a SPCod/ SPCoc elements, i.e. the coding style of a given component of a tile.
*
* @param p_j2k J2K codec.
* @param p_tile_no Tile number
* @param p_first_comp_no The 1st component number to compare.
* @param p_second_comp_no The 1st component number to compare.
*
* @return OPJ_TRUE if SPCdod are equals.
*/
static OPJ_BOOL opj_j2k_compare_SPCod_SPCoc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no);
/**
* Writes a SPCod or SPCoc element, i.e. the coding style of a given component of a tile.
*
* @param p_j2k J2K codec.
* @param p_tile_no FIXME DOC
* @param p_comp_no the component number to output.
* @param p_data FIXME DOC
* @param p_header_size FIXME DOC
* @param p_manager the user event manager.
*
* @return FIXME DOC
*/
static OPJ_BOOL opj_j2k_write_SPCod_SPCoc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_header_size,
opj_event_mgr_t * p_manager);
/**
* Gets the size taken by writing a SPCod or SPCoc for the given tile and component.
*
* @param p_j2k the J2K codec.
* @param p_tile_no the tile index.
* @param p_comp_no the component being outputted.
*
* @return the number of bytes taken by the SPCod element.
*/
static OPJ_UINT32 opj_j2k_get_SPCod_SPCoc_size(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no);
/**
* Reads a SPCod or SPCoc element, i.e. the coding style of a given component of a tile.
* @param p_j2k the jpeg2000 codec.
* @param compno FIXME DOC
* @param p_header_data the data contained in the COM box.
* @param p_header_size the size of the data contained in the COM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_SPCod_SPCoc(opj_j2k_t *p_j2k,
OPJ_UINT32 compno,
OPJ_BYTE * p_header_data,
OPJ_UINT32 * p_header_size,
opj_event_mgr_t * p_manager);
/**
* Gets the size taken by writing SQcd or SQcc element, i.e. the quantization values of a band in the QCD or QCC.
*
* @param p_tile_no the tile index.
* @param p_comp_no the component being outputted.
* @param p_j2k the J2K codec.
*
* @return the number of bytes taken by the SPCod element.
*/
static OPJ_UINT32 opj_j2k_get_SQcd_SQcc_size(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no);
/**
* Compares 2 SQcd or SQcc element, i.e. the quantization values of a band in the QCD or QCC.
*
* @param p_j2k J2K codec.
* @param p_tile_no the tile to output.
* @param p_first_comp_no the first component number to compare.
* @param p_second_comp_no the second component number to compare.
*
* @return OPJ_TRUE if equals.
*/
static OPJ_BOOL opj_j2k_compare_SQcd_SQcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no);
/**
* Writes a SQcd or SQcc element, i.e. the quantization values of a band in the QCD or QCC.
*
* @param p_tile_no the tile to output.
* @param p_comp_no the component number to output.
* @param p_data the data buffer.
* @param p_header_size pointer to the size of the data buffer, it is changed by the function.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*
*/
static OPJ_BOOL opj_j2k_write_SQcd_SQcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_header_size,
opj_event_mgr_t * p_manager);
/**
* Updates the Tile Length Marker.
*/
static void opj_j2k_update_tlm(opj_j2k_t * p_j2k, OPJ_UINT32 p_tile_part_size);
/**
* Reads a SQcd or SQcc element, i.e. the quantization values of a band in the QCD or QCC.
*
* @param p_j2k J2K codec.
* @param compno the component number to output.
* @param p_header_data the data buffer.
* @param p_header_size pointer to the size of the data buffer, it is changed by the function.
* @param p_manager the user event manager.
*
*/
static OPJ_BOOL opj_j2k_read_SQcd_SQcc(opj_j2k_t *p_j2k,
OPJ_UINT32 compno,
OPJ_BYTE * p_header_data,
OPJ_UINT32 * p_header_size,
opj_event_mgr_t * p_manager);
/**
* Copies the tile component parameters of all the component from the first tile component.
*
* @param p_j2k the J2k codec.
*/
static void opj_j2k_copy_tile_component_parameters(opj_j2k_t *p_j2k);
/**
* Copies the tile quantization parameters of all the component from the first tile component.
*
* @param p_j2k the J2k codec.
*/
static void opj_j2k_copy_tile_quantization_parameters(opj_j2k_t *p_j2k);
/**
* Reads the tiles.
*/
static OPJ_BOOL opj_j2k_decode_tiles(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
static OPJ_BOOL opj_j2k_pre_write_tile(opj_j2k_t * p_j2k,
OPJ_UINT32 p_tile_index,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
static OPJ_BOOL opj_j2k_update_image_data(opj_tcd_t * p_tcd, OPJ_BYTE * p_data,
opj_image_t* p_output_image);
static void opj_get_tile_dimensions(opj_image_t * l_image,
opj_tcd_tilecomp_t * l_tilec,
opj_image_comp_t * l_img_comp,
OPJ_UINT32* l_size_comp,
OPJ_UINT32* l_width,
OPJ_UINT32* l_height,
OPJ_UINT32* l_offset_x,
OPJ_UINT32* l_offset_y,
OPJ_UINT32* l_image_width,
OPJ_UINT32* l_stride,
OPJ_UINT32* l_tile_offset);
static void opj_j2k_get_tile_data(opj_tcd_t * p_tcd, OPJ_BYTE * p_data);
static OPJ_BOOL opj_j2k_post_write_tile(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Sets up the procedures to do on writing header.
* Developers wanting to extend the library can add their own writing procedures.
*/
static OPJ_BOOL opj_j2k_setup_header_writing(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager);
static OPJ_BOOL opj_j2k_write_first_tile_part(opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_total_data_size,
opj_stream_private_t *p_stream,
struct opj_event_mgr * p_manager);
static OPJ_BOOL opj_j2k_write_all_tile_parts(opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_total_data_size,
opj_stream_private_t *p_stream,
struct opj_event_mgr * p_manager);
/**
* Gets the offset of the header.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_get_end_header(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
static OPJ_BOOL opj_j2k_allocate_tile_element_cstr_index(opj_j2k_t *p_j2k);
/*
* -----------------------------------------------------------------------
* -----------------------------------------------------------------------
* -----------------------------------------------------------------------
*/
/**
* Writes the SOC marker (Start Of Codestream)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_soc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a SOC marker (Start of Codestream)
* @param p_j2k the jpeg2000 file codec.
* @param p_stream XXX needs data
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_soc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes the SIZ marker (image and tile size)
*
* @param p_j2k J2K codec.
* @param p_stream the stream to write data to.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_siz(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a SIZ marker (image and tile size)
* @param p_j2k the jpeg2000 file codec.
* @param p_header_data the data contained in the SIZ box.
* @param p_header_size the size of the data contained in the SIZ marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_siz(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the COM marker (comment)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_com(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a COM marker (comments)
* @param p_j2k the jpeg2000 file codec.
* @param p_header_data the data contained in the COM box.
* @param p_header_size the size of the data contained in the COM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_com(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the COD marker (Coding style default)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_cod(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a COD marker (Coding Styke defaults)
* @param p_header_data the data contained in the COD box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the COD marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_cod(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Compares 2 COC markers (Coding style component)
*
* @param p_j2k J2K codec.
* @param p_first_comp_no the index of the first component to compare.
* @param p_second_comp_no the index of the second component to compare.
*
* @return OPJ_TRUE if equals
*/
static OPJ_BOOL opj_j2k_compare_coc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no);
/**
* Writes the COC marker (Coding style component)
*
* @param p_j2k J2K codec.
* @param p_comp_no the index of the component to output.
* @param p_stream the stream to write data to.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_coc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes the COC marker (Coding style component)
*
* @param p_j2k J2K codec.
* @param p_comp_no the index of the component to output.
* @param p_data FIXME DOC
* @param p_data_written FIXME DOC
* @param p_manager the user event manager.
*/
static void opj_j2k_write_coc_in_memory(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
opj_event_mgr_t * p_manager);
/**
* Gets the maximum size taken by a coc.
*
* @param p_j2k the jpeg2000 codec to use.
*/
static OPJ_UINT32 opj_j2k_get_max_coc_size(opj_j2k_t *p_j2k);
/**
* Reads a COC marker (Coding Style Component)
* @param p_header_data the data contained in the COC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the COC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_coc(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the QCD marker (quantization default)
*
* @param p_j2k J2K codec.
* @param p_stream the stream to write data to.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_qcd(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a QCD marker (Quantization defaults)
* @param p_header_data the data contained in the QCD box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the QCD marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_qcd(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Compare QCC markers (quantization component)
*
* @param p_j2k J2K codec.
* @param p_first_comp_no the index of the first component to compare.
* @param p_second_comp_no the index of the second component to compare.
*
* @return OPJ_TRUE if equals.
*/
static OPJ_BOOL opj_j2k_compare_qcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no);
/**
* Writes the QCC marker (quantization component)
*
* @param p_comp_no the index of the component to output.
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_qcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes the QCC marker (quantization component)
*
* @param p_j2k J2K codec.
* @param p_comp_no the index of the component to output.
* @param p_data FIXME DOC
* @param p_data_written the stream to write data to.
* @param p_manager the user event manager.
*/
static void opj_j2k_write_qcc_in_memory(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
opj_event_mgr_t * p_manager);
/**
* Gets the maximum size taken by a qcc.
*/
static OPJ_UINT32 opj_j2k_get_max_qcc_size(opj_j2k_t *p_j2k);
/**
* Reads a QCC marker (Quantization component)
* @param p_header_data the data contained in the QCC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the QCC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_qcc(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the POC marker (Progression Order Change)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_poc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes the POC marker (Progression Order Change)
*
* @param p_j2k J2K codec.
* @param p_data FIXME DOC
* @param p_data_written the stream to write data to.
* @param p_manager the user event manager.
*/
static void opj_j2k_write_poc_in_memory(opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
opj_event_mgr_t * p_manager);
/**
* Gets the maximum size taken by the writing of a POC.
*/
static OPJ_UINT32 opj_j2k_get_max_poc_size(opj_j2k_t *p_j2k);
/**
* Reads a POC marker (Progression Order Change)
*
* @param p_header_data the data contained in the POC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the POC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_poc(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Gets the maximum size taken by the toc headers of all the tile parts of any given tile.
*/
static OPJ_UINT32 opj_j2k_get_max_toc_size(opj_j2k_t *p_j2k);
/**
* Gets the maximum size taken by the headers of the SOT.
*
* @param p_j2k the jpeg2000 codec to use.
*/
static OPJ_UINT32 opj_j2k_get_specific_header_sizes(opj_j2k_t *p_j2k);
/**
* Reads a CRG marker (Component registration)
*
* @param p_header_data the data contained in the TLM box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the TLM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_crg(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Reads a TLM marker (Tile Length Marker)
*
* @param p_header_data the data contained in the TLM box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the TLM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_tlm(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the updated tlm.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_updated_tlm(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a PLM marker (Packet length, main header marker)
*
* @param p_header_data the data contained in the TLM box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the TLM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_plm(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Reads a PLT marker (Packet length, tile-part header)
*
* @param p_header_data the data contained in the PLT box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the PLT marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_plt(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Reads a PPM marker (Packed headers, main header)
*
* @param p_header_data the data contained in the POC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the POC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_ppm(
opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Merges all PPM markers read (Packed headers, main header)
*
* @param p_cp main coding parameters.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_merge_ppm(opj_cp_t *p_cp, opj_event_mgr_t * p_manager);
/**
* Reads a PPT marker (Packed packet headers, tile-part header)
*
* @param p_header_data the data contained in the PPT box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the PPT marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_ppt(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Merges all PPT markers read (Packed headers, tile-part header)
*
* @param p_tcp the tile.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_merge_ppt(opj_tcp_t *p_tcp,
opj_event_mgr_t * p_manager);
/**
* Writes the TLM marker (Tile Length Marker)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_tlm(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes the SOT marker (Start of tile-part)
*
* @param p_j2k J2K codec.
* @param p_data FIXME DOC
* @param p_data_written FIXME DOC
* @param p_stream the stream to write data to.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_sot(opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
const opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads values from a SOT marker (Start of tile-part)
*
* the j2k decoder state is not affected. No side effects, no checks except for p_header_size.
*
* @param p_header_data the data contained in the SOT marker.
* @param p_header_size the size of the data contained in the SOT marker.
* @param p_tile_no Isot.
* @param p_tot_len Psot.
* @param p_current_part TPsot.
* @param p_num_parts TNsot.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_get_sot_values(OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
OPJ_UINT32* p_tile_no,
OPJ_UINT32* p_tot_len,
OPJ_UINT32* p_current_part,
OPJ_UINT32* p_num_parts,
opj_event_mgr_t * p_manager);
/**
* Reads a SOT marker (Start of tile-part)
*
* @param p_header_data the data contained in the SOT marker.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the PPT marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_sot(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the SOD marker (Start of data)
*
* @param p_j2k J2K codec.
* @param p_tile_coder FIXME DOC
* @param p_data FIXME DOC
* @param p_data_written FIXME DOC
* @param p_total_data_size FIXME DOC
* @param p_stream the stream to write data to.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_sod(opj_j2k_t *p_j2k,
opj_tcd_t * p_tile_coder,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_total_data_size,
const opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a SOD marker (Start Of Data)
*
* @param p_j2k the jpeg2000 codec.
* @param p_stream FIXME DOC
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_sod(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
static void opj_j2k_update_tlm(opj_j2k_t * p_j2k, OPJ_UINT32 p_tile_part_size)
{
opj_write_bytes(p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current,
p_j2k->m_current_tile_number, 1); /* PSOT */
++p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current;
opj_write_bytes(p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current,
p_tile_part_size, 4); /* PSOT */
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current += 4;
}
/**
* Writes the RGN marker (Region Of Interest)
*
* @param p_tile_no the tile to output
* @param p_comp_no the component to output
* @param nb_comps the number of components
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_rgn(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no,
OPJ_UINT32 nb_comps,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a RGN marker (Region Of Interest)
*
* @param p_header_data the data contained in the POC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the POC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_rgn(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the EOC marker (End of Codestream)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_eoc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
#if 0
/**
* Reads a EOC marker (End Of Codestream)
*
* @param p_j2k the jpeg2000 codec.
* @param p_stream FIXME DOC
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_eoc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
#endif
/**
* Writes the CBD-MCT-MCC-MCO markers (Multi components transform)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_mct_data_group(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Inits the Info
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_init_info(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
Add main header marker information
@param cstr_index Codestream information structure
@param type marker type
@param pos byte offset of marker segment
@param len length of marker segment
*/
static OPJ_BOOL opj_j2k_add_mhmarker(opj_codestream_index_t *cstr_index,
OPJ_UINT32 type, OPJ_OFF_T pos, OPJ_UINT32 len) ;
/**
Add tile header marker information
@param tileno tile index number
@param cstr_index Codestream information structure
@param type marker type
@param pos byte offset of marker segment
@param len length of marker segment
*/
static OPJ_BOOL opj_j2k_add_tlmarker(OPJ_UINT32 tileno,
opj_codestream_index_t *cstr_index, OPJ_UINT32 type, OPJ_OFF_T pos,
OPJ_UINT32 len);
/**
* Reads an unknown marker
*
* @param p_j2k the jpeg2000 codec.
* @param p_stream the stream object to read from.
* @param output_marker FIXME DOC
* @param p_manager the user event manager.
*
* @return true if the marker could be deduced.
*/
static OPJ_BOOL opj_j2k_read_unk(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
OPJ_UINT32 *output_marker,
opj_event_mgr_t * p_manager);
/**
* Writes the MCT marker (Multiple Component Transform)
*
* @param p_j2k J2K codec.
* @param p_mct_record FIXME DOC
* @param p_stream the stream to write data to.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_mct_record(opj_j2k_t *p_j2k,
opj_mct_data_t * p_mct_record,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a MCT marker (Multiple Component Transform)
*
* @param p_header_data the data contained in the MCT box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the MCT marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_mct(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the MCC marker (Multiple Component Collection)
*
* @param p_j2k J2K codec.
* @param p_mcc_record FIXME DOC
* @param p_stream the stream to write data to.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_mcc_record(opj_j2k_t *p_j2k,
opj_simple_mcc_decorrelation_data_t * p_mcc_record,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a MCC marker (Multiple Component Collection)
*
* @param p_header_data the data contained in the MCC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the MCC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_mcc(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the MCO marker (Multiple component transformation ordering)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_mco(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a MCO marker (Multiple Component Transform Ordering)
*
* @param p_header_data the data contained in the MCO box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the MCO marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_mco(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
static OPJ_BOOL opj_j2k_add_mct(opj_tcp_t * p_tcp, opj_image_t * p_image,
OPJ_UINT32 p_index);
static void opj_j2k_read_int16_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_read_int32_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_read_float32_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_read_float64_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_read_int16_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_read_int32_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_read_float32_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_read_float64_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_write_float_to_int16(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_write_float_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_write_float_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_write_float_to_float64(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
/**
* Ends the encoding, i.e. frees memory.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_end_encoding(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes the CBD marker (Component bit depth definition)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_cbd(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a CBD marker (Component bit depth definition)
* @param p_header_data the data contained in the CBD box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the CBD marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_cbd(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes COC marker for each component.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_all_coc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes QCC marker for each component.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_all_qcc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes regions of interests.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_regions(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes EPC ????
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_epc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Checks the progression order changes values. Tells of the poc given as input are valid.
* A nice message is outputted at errors.
*
* @param p_pocs the progression order changes.
* @param p_nb_pocs the number of progression order changes.
* @param p_nb_resolutions the number of resolutions.
* @param numcomps the number of components
* @param numlayers the number of layers.
* @param p_manager the user event manager.
*
* @return true if the pocs are valid.
*/
static OPJ_BOOL opj_j2k_check_poc_val(const opj_poc_t *p_pocs,
OPJ_UINT32 p_nb_pocs,
OPJ_UINT32 p_nb_resolutions,
OPJ_UINT32 numcomps,
OPJ_UINT32 numlayers,
opj_event_mgr_t * p_manager);
/**
* Gets the number of tile parts used for the given change of progression (if any) and the given tile.
*
* @param cp the coding parameters.
* @param pino the offset of the given poc (i.e. its position in the coding parameter).
* @param tileno the given tile.
*
* @return the number of tile parts.
*/
static OPJ_UINT32 opj_j2k_get_num_tp(opj_cp_t *cp, OPJ_UINT32 pino,
OPJ_UINT32 tileno);
/**
* Calculates the total number of tile parts needed by the encoder to
* encode such an image. If not enough memory is available, then the function return false.
*
* @param p_nb_tiles pointer that will hold the number of tile parts.
* @param cp the coding parameters for the image.
* @param image the image to encode.
* @param p_j2k the p_j2k encoder.
* @param p_manager the user event manager.
*
* @return true if the function was successful, false else.
*/
static OPJ_BOOL opj_j2k_calculate_tp(opj_j2k_t *p_j2k,
opj_cp_t *cp,
OPJ_UINT32 * p_nb_tiles,
opj_image_t *image,
opj_event_mgr_t * p_manager);
static void opj_j2k_dump_MH_info(opj_j2k_t* p_j2k, FILE* out_stream);
static void opj_j2k_dump_MH_index(opj_j2k_t* p_j2k, FILE* out_stream);
static opj_codestream_index_t* opj_j2k_create_cstr_index(void);
static OPJ_FLOAT32 opj_j2k_get_tp_stride(opj_tcp_t * p_tcp);
static OPJ_FLOAT32 opj_j2k_get_default_stride(opj_tcp_t * p_tcp);
static int opj_j2k_initialise_4K_poc(opj_poc_t *POC, int numres);
static void opj_j2k_set_cinema_parameters(opj_cparameters_t *parameters,
opj_image_t *image, opj_event_mgr_t *p_manager);
static OPJ_BOOL opj_j2k_is_cinema_compliant(opj_image_t *image, OPJ_UINT16 rsiz,
opj_event_mgr_t *p_manager);
/**
* Checks for invalid number of tile-parts in SOT marker (TPsot==TNsot). See issue 254.
*
* @param p_stream the stream to read data from.
* @param tile_no tile number we're looking for.
* @param p_correction_needed output value. if true, non conformant codestream needs TNsot correction.
* @param p_manager the user event manager.
*
* @return true if the function was successful, false else.
*/
static OPJ_BOOL opj_j2k_need_nb_tile_parts_correction(opj_stream_private_t
*p_stream, OPJ_UINT32 tile_no, OPJ_BOOL* p_correction_needed,
opj_event_mgr_t * p_manager);
/*@}*/
/*@}*/
/* ----------------------------------------------------------------------- */
typedef struct j2k_prog_order {
OPJ_PROG_ORDER enum_prog;
char str_prog[5];
} j2k_prog_order_t;
static const j2k_prog_order_t j2k_prog_order_list[] = {
{OPJ_CPRL, "CPRL"},
{OPJ_LRCP, "LRCP"},
{OPJ_PCRL, "PCRL"},
{OPJ_RLCP, "RLCP"},
{OPJ_RPCL, "RPCL"},
{(OPJ_PROG_ORDER) - 1, ""}
};
/**
* FIXME DOC
*/
static const OPJ_UINT32 MCT_ELEMENT_SIZE [] = {
2,
4,
4,
8
};
typedef void (* opj_j2k_mct_function)(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static const opj_j2k_mct_function j2k_mct_read_functions_to_float [] = {
opj_j2k_read_int16_to_float,
opj_j2k_read_int32_to_float,
opj_j2k_read_float32_to_float,
opj_j2k_read_float64_to_float
};
static const opj_j2k_mct_function j2k_mct_read_functions_to_int32 [] = {
opj_j2k_read_int16_to_int32,
opj_j2k_read_int32_to_int32,
opj_j2k_read_float32_to_int32,
opj_j2k_read_float64_to_int32
};
static const opj_j2k_mct_function j2k_mct_write_functions_from_float [] = {
opj_j2k_write_float_to_int16,
opj_j2k_write_float_to_int32,
opj_j2k_write_float_to_float,
opj_j2k_write_float_to_float64
};
typedef struct opj_dec_memory_marker_handler {
/** marker value */
OPJ_UINT32 id;
/** value of the state when the marker can appear */
OPJ_UINT32 states;
/** action linked to the marker */
OPJ_BOOL(*handler)(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
}
opj_dec_memory_marker_handler_t;
static const opj_dec_memory_marker_handler_t j2k_memory_marker_handler_tab [] =
{
{J2K_MS_SOT, J2K_STATE_MH | J2K_STATE_TPHSOT, opj_j2k_read_sot},
{J2K_MS_COD, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_cod},
{J2K_MS_COC, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_coc},
{J2K_MS_RGN, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_rgn},
{J2K_MS_QCD, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_qcd},
{J2K_MS_QCC, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_qcc},
{J2K_MS_POC, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_poc},
{J2K_MS_SIZ, J2K_STATE_MHSIZ, opj_j2k_read_siz},
{J2K_MS_TLM, J2K_STATE_MH, opj_j2k_read_tlm},
{J2K_MS_PLM, J2K_STATE_MH, opj_j2k_read_plm},
{J2K_MS_PLT, J2K_STATE_TPH, opj_j2k_read_plt},
{J2K_MS_PPM, J2K_STATE_MH, opj_j2k_read_ppm},
{J2K_MS_PPT, J2K_STATE_TPH, opj_j2k_read_ppt},
{J2K_MS_SOP, 0, 0},
{J2K_MS_CRG, J2K_STATE_MH, opj_j2k_read_crg},
{J2K_MS_COM, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_com},
{J2K_MS_MCT, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_mct},
{J2K_MS_CBD, J2K_STATE_MH, opj_j2k_read_cbd},
{J2K_MS_MCC, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_mcc},
{J2K_MS_MCO, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_mco},
#ifdef USE_JPWL
#ifdef TODO_MS /* remove these functions which are not commpatible with the v2 API */
{J2K_MS_EPC, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_epc},
{J2K_MS_EPB, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_epb},
{J2K_MS_ESD, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_esd},
{J2K_MS_RED, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_red},
#endif
#endif /* USE_JPWL */
#ifdef USE_JPSEC
{J2K_MS_SEC, J2K_DEC_STATE_MH, j2k_read_sec},
{J2K_MS_INSEC, 0, j2k_read_insec}
#endif /* USE_JPSEC */
{J2K_MS_UNK, J2K_STATE_MH | J2K_STATE_TPH, 0}/*opj_j2k_read_unk is directly used*/
};
static void opj_j2k_read_int16_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_FLOAT32 * l_dest_data = (OPJ_FLOAT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_UINT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
opj_read_bytes(l_src_data, &l_temp, 2);
l_src_data += sizeof(OPJ_INT16);
*(l_dest_data++) = (OPJ_FLOAT32) l_temp;
}
}
static void opj_j2k_read_int32_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_FLOAT32 * l_dest_data = (OPJ_FLOAT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_UINT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
opj_read_bytes(l_src_data, &l_temp, 4);
l_src_data += sizeof(OPJ_INT32);
*(l_dest_data++) = (OPJ_FLOAT32) l_temp;
}
}
static void opj_j2k_read_float32_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_FLOAT32 * l_dest_data = (OPJ_FLOAT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_FLOAT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
opj_read_float(l_src_data, &l_temp);
l_src_data += sizeof(OPJ_FLOAT32);
*(l_dest_data++) = l_temp;
}
}
static void opj_j2k_read_float64_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_FLOAT32 * l_dest_data = (OPJ_FLOAT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_FLOAT64 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
opj_read_double(l_src_data, &l_temp);
l_src_data += sizeof(OPJ_FLOAT64);
*(l_dest_data++) = (OPJ_FLOAT32) l_temp;
}
}
static void opj_j2k_read_int16_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_INT32 * l_dest_data = (OPJ_INT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_UINT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
opj_read_bytes(l_src_data, &l_temp, 2);
l_src_data += sizeof(OPJ_INT16);
*(l_dest_data++) = (OPJ_INT32) l_temp;
}
}
static void opj_j2k_read_int32_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_INT32 * l_dest_data = (OPJ_INT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_UINT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
opj_read_bytes(l_src_data, &l_temp, 4);
l_src_data += sizeof(OPJ_INT32);
*(l_dest_data++) = (OPJ_INT32) l_temp;
}
}
static void opj_j2k_read_float32_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_INT32 * l_dest_data = (OPJ_INT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_FLOAT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
opj_read_float(l_src_data, &l_temp);
l_src_data += sizeof(OPJ_FLOAT32);
*(l_dest_data++) = (OPJ_INT32) l_temp;
}
}
static void opj_j2k_read_float64_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_INT32 * l_dest_data = (OPJ_INT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_FLOAT64 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
opj_read_double(l_src_data, &l_temp);
l_src_data += sizeof(OPJ_FLOAT64);
*(l_dest_data++) = (OPJ_INT32) l_temp;
}
}
static void opj_j2k_write_float_to_int16(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_dest_data = (OPJ_BYTE *) p_dest_data;
OPJ_FLOAT32 * l_src_data = (OPJ_FLOAT32 *) p_src_data;
OPJ_UINT32 i;
OPJ_UINT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
l_temp = (OPJ_UINT32) * (l_src_data++);
opj_write_bytes(l_dest_data, l_temp, sizeof(OPJ_INT16));
l_dest_data += sizeof(OPJ_INT16);
}
}
static void opj_j2k_write_float_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_dest_data = (OPJ_BYTE *) p_dest_data;
OPJ_FLOAT32 * l_src_data = (OPJ_FLOAT32 *) p_src_data;
OPJ_UINT32 i;
OPJ_UINT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
l_temp = (OPJ_UINT32) * (l_src_data++);
opj_write_bytes(l_dest_data, l_temp, sizeof(OPJ_INT32));
l_dest_data += sizeof(OPJ_INT32);
}
}
static void opj_j2k_write_float_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_dest_data = (OPJ_BYTE *) p_dest_data;
OPJ_FLOAT32 * l_src_data = (OPJ_FLOAT32 *) p_src_data;
OPJ_UINT32 i;
OPJ_FLOAT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
l_temp = (OPJ_FLOAT32) * (l_src_data++);
opj_write_float(l_dest_data, l_temp);
l_dest_data += sizeof(OPJ_FLOAT32);
}
}
static void opj_j2k_write_float_to_float64(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_dest_data = (OPJ_BYTE *) p_dest_data;
OPJ_FLOAT32 * l_src_data = (OPJ_FLOAT32 *) p_src_data;
OPJ_UINT32 i;
OPJ_FLOAT64 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
l_temp = (OPJ_FLOAT64) * (l_src_data++);
opj_write_double(l_dest_data, l_temp);
l_dest_data += sizeof(OPJ_FLOAT64);
}
}
const char *opj_j2k_convert_progression_order(OPJ_PROG_ORDER prg_order)
{
const j2k_prog_order_t *po;
for (po = j2k_prog_order_list; po->enum_prog != -1; po++) {
if (po->enum_prog == prg_order) {
return po->str_prog;
}
}
return po->str_prog;
}
static OPJ_BOOL opj_j2k_check_poc_val(const opj_poc_t *p_pocs,
OPJ_UINT32 p_nb_pocs,
OPJ_UINT32 p_nb_resolutions,
OPJ_UINT32 p_num_comps,
OPJ_UINT32 p_num_layers,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32* packet_array;
OPJ_UINT32 index, resno, compno, layno;
OPJ_UINT32 i;
OPJ_UINT32 step_c = 1;
OPJ_UINT32 step_r = p_num_comps * step_c;
OPJ_UINT32 step_l = p_nb_resolutions * step_r;
OPJ_BOOL loss = OPJ_FALSE;
OPJ_UINT32 layno0 = 0;
packet_array = (OPJ_UINT32*) opj_calloc(step_l * p_num_layers,
sizeof(OPJ_UINT32));
if (packet_array == 00) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory for checking the poc values.\n");
return OPJ_FALSE;
}
if (p_nb_pocs == 0) {
opj_free(packet_array);
return OPJ_TRUE;
}
index = step_r * p_pocs->resno0;
/* take each resolution for each poc */
for (resno = p_pocs->resno0 ; resno < p_pocs->resno1 ; ++resno) {
OPJ_UINT32 res_index = index + p_pocs->compno0 * step_c;
/* take each comp of each resolution for each poc */
for (compno = p_pocs->compno0 ; compno < p_pocs->compno1 ; ++compno) {
OPJ_UINT32 comp_index = res_index + layno0 * step_l;
/* and finally take each layer of each res of ... */
for (layno = layno0; layno < p_pocs->layno1 ; ++layno) {
/*index = step_r * resno + step_c * compno + step_l * layno;*/
packet_array[comp_index] = 1;
comp_index += step_l;
}
res_index += step_c;
}
index += step_r;
}
++p_pocs;
/* iterate through all the pocs */
for (i = 1; i < p_nb_pocs ; ++i) {
OPJ_UINT32 l_last_layno1 = (p_pocs - 1)->layno1 ;
layno0 = (p_pocs->layno1 > l_last_layno1) ? l_last_layno1 : 0;
index = step_r * p_pocs->resno0;
/* take each resolution for each poc */
for (resno = p_pocs->resno0 ; resno < p_pocs->resno1 ; ++resno) {
OPJ_UINT32 res_index = index + p_pocs->compno0 * step_c;
/* take each comp of each resolution for each poc */
for (compno = p_pocs->compno0 ; compno < p_pocs->compno1 ; ++compno) {
OPJ_UINT32 comp_index = res_index + layno0 * step_l;
/* and finally take each layer of each res of ... */
for (layno = layno0; layno < p_pocs->layno1 ; ++layno) {
/*index = step_r * resno + step_c * compno + step_l * layno;*/
packet_array[comp_index] = 1;
comp_index += step_l;
}
res_index += step_c;
}
index += step_r;
}
++p_pocs;
}
index = 0;
for (layno = 0; layno < p_num_layers ; ++layno) {
for (resno = 0; resno < p_nb_resolutions; ++resno) {
for (compno = 0; compno < p_num_comps; ++compno) {
loss |= (packet_array[index] != 1);
/*index = step_r * resno + step_c * compno + step_l * layno;*/
index += step_c;
}
}
}
if (loss) {
opj_event_msg(p_manager, EVT_ERROR, "Missing packets possible loss of data\n");
}
opj_free(packet_array);
return !loss;
}
/* ----------------------------------------------------------------------- */
static OPJ_UINT32 opj_j2k_get_num_tp(opj_cp_t *cp, OPJ_UINT32 pino,
OPJ_UINT32 tileno)
{
const OPJ_CHAR *prog = 00;
OPJ_INT32 i;
OPJ_UINT32 tpnum = 1;
opj_tcp_t *tcp = 00;
opj_poc_t * l_current_poc = 00;
/* preconditions */
assert(tileno < (cp->tw * cp->th));
assert(pino < (cp->tcps[tileno].numpocs + 1));
/* get the given tile coding parameter */
tcp = &cp->tcps[tileno];
assert(tcp != 00);
l_current_poc = &(tcp->pocs[pino]);
assert(l_current_poc != 0);
/* get the progression order as a character string */
prog = opj_j2k_convert_progression_order(tcp->prg);
assert(strlen(prog) > 0);
if (cp->m_specific_param.m_enc.m_tp_on == 1) {
for (i = 0; i < 4; ++i) {
switch (prog[i]) {
/* component wise */
case 'C':
tpnum *= l_current_poc->compE;
break;
/* resolution wise */
case 'R':
tpnum *= l_current_poc->resE;
break;
/* precinct wise */
case 'P':
tpnum *= l_current_poc->prcE;
break;
/* layer wise */
case 'L':
tpnum *= l_current_poc->layE;
break;
}
/* whould we split here ? */
if (cp->m_specific_param.m_enc.m_tp_flag == prog[i]) {
cp->m_specific_param.m_enc.m_tp_pos = i;
break;
}
}
} else {
tpnum = 1;
}
return tpnum;
}
static OPJ_BOOL opj_j2k_calculate_tp(opj_j2k_t *p_j2k,
opj_cp_t *cp,
OPJ_UINT32 * p_nb_tiles,
opj_image_t *image,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 pino, tileno;
OPJ_UINT32 l_nb_tiles;
opj_tcp_t *tcp;
/* preconditions */
assert(p_nb_tiles != 00);
assert(cp != 00);
assert(image != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_j2k);
OPJ_UNUSED(p_manager);
l_nb_tiles = cp->tw * cp->th;
* p_nb_tiles = 0;
tcp = cp->tcps;
/* INDEX >> */
/* TODO mergeV2: check this part which use cstr_info */
/*if (p_j2k->cstr_info) {
opj_tile_info_t * l_info_tile_ptr = p_j2k->cstr_info->tile;
for (tileno = 0; tileno < l_nb_tiles; ++tileno) {
OPJ_UINT32 cur_totnum_tp = 0;
opj_pi_update_encoding_parameters(image,cp,tileno);
for (pino = 0; pino <= tcp->numpocs; ++pino)
{
OPJ_UINT32 tp_num = opj_j2k_get_num_tp(cp,pino,tileno);
*p_nb_tiles = *p_nb_tiles + tp_num;
cur_totnum_tp += tp_num;
}
tcp->m_nb_tile_parts = cur_totnum_tp;
l_info_tile_ptr->tp = (opj_tp_info_t *) opj_malloc(cur_totnum_tp * sizeof(opj_tp_info_t));
if (l_info_tile_ptr->tp == 00) {
return OPJ_FALSE;
}
memset(l_info_tile_ptr->tp,0,cur_totnum_tp * sizeof(opj_tp_info_t));
l_info_tile_ptr->num_tps = cur_totnum_tp;
++l_info_tile_ptr;
++tcp;
}
}
else */{
for (tileno = 0; tileno < l_nb_tiles; ++tileno) {
OPJ_UINT32 cur_totnum_tp = 0;
opj_pi_update_encoding_parameters(image, cp, tileno);
for (pino = 0; pino <= tcp->numpocs; ++pino) {
OPJ_UINT32 tp_num = opj_j2k_get_num_tp(cp, pino, tileno);
*p_nb_tiles = *p_nb_tiles + tp_num;
cur_totnum_tp += tp_num;
}
tcp->m_nb_tile_parts = cur_totnum_tp;
++tcp;
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_soc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
/* 2 bytes will be written */
OPJ_BYTE * l_start_stream = 00;
/* preconditions */
assert(p_stream != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_start_stream = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
/* write SOC identifier */
opj_write_bytes(l_start_stream, J2K_MS_SOC, 2);
if (opj_stream_write_data(p_stream, l_start_stream, 2, p_manager) != 2) {
return OPJ_FALSE;
}
/* UniPG>> */
#ifdef USE_JPWL
/* update markers struct */
/*
OPJ_BOOL res = j2k_add_marker(p_j2k->cstr_info, J2K_MS_SOC, p_stream_tell(p_stream) - 2, 2);
*/
assert(0 && "TODO");
#endif /* USE_JPWL */
/* <<UniPG */
return OPJ_TRUE;
}
/**
* Reads a SOC marker (Start of Codestream)
* @param p_j2k the jpeg2000 file codec.
* @param p_stream FIXME DOC
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_soc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_BYTE l_data [2];
OPJ_UINT32 l_marker;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
if (opj_stream_read_data(p_stream, l_data, 2, p_manager) != 2) {
return OPJ_FALSE;
}
opj_read_bytes(l_data, &l_marker, 2);
if (l_marker != J2K_MS_SOC) {
return OPJ_FALSE;
}
/* Next marker should be a SIZ marker in the main header */
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_MHSIZ;
/* FIXME move it in a index structure included in p_j2k*/
p_j2k->cstr_index->main_head_start = opj_stream_tell(p_stream) - 2;
opj_event_msg(p_manager, EVT_INFO, "Start to read j2k main header (%d).\n",
p_j2k->cstr_index->main_head_start);
/* Add the marker to the codestream index*/
if (OPJ_FALSE == opj_j2k_add_mhmarker(p_j2k->cstr_index, J2K_MS_SOC,
p_j2k->cstr_index->main_head_start, 2)) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add mh marker\n");
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_siz(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 i;
OPJ_UINT32 l_size_len;
OPJ_BYTE * l_current_ptr;
opj_image_t * l_image = 00;
opj_cp_t *cp = 00;
opj_image_comp_t * l_img_comp = 00;
/* preconditions */
assert(p_stream != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_image = p_j2k->m_private_image;
cp = &(p_j2k->m_cp);
l_size_len = 40 + 3 * l_image->numcomps;
l_img_comp = l_image->comps;
if (l_size_len > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_size_len);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory for the SIZ marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_size_len;
}
l_current_ptr = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
/* write SOC identifier */
opj_write_bytes(l_current_ptr, J2K_MS_SIZ, 2); /* SIZ */
l_current_ptr += 2;
opj_write_bytes(l_current_ptr, l_size_len - 2, 2); /* L_SIZ */
l_current_ptr += 2;
opj_write_bytes(l_current_ptr, cp->rsiz, 2); /* Rsiz (capabilities) */
l_current_ptr += 2;
opj_write_bytes(l_current_ptr, l_image->x1, 4); /* Xsiz */
l_current_ptr += 4;
opj_write_bytes(l_current_ptr, l_image->y1, 4); /* Ysiz */
l_current_ptr += 4;
opj_write_bytes(l_current_ptr, l_image->x0, 4); /* X0siz */
l_current_ptr += 4;
opj_write_bytes(l_current_ptr, l_image->y0, 4); /* Y0siz */
l_current_ptr += 4;
opj_write_bytes(l_current_ptr, cp->tdx, 4); /* XTsiz */
l_current_ptr += 4;
opj_write_bytes(l_current_ptr, cp->tdy, 4); /* YTsiz */
l_current_ptr += 4;
opj_write_bytes(l_current_ptr, cp->tx0, 4); /* XT0siz */
l_current_ptr += 4;
opj_write_bytes(l_current_ptr, cp->ty0, 4); /* YT0siz */
l_current_ptr += 4;
opj_write_bytes(l_current_ptr, l_image->numcomps, 2); /* Csiz */
l_current_ptr += 2;
for (i = 0; i < l_image->numcomps; ++i) {
/* TODO here with MCT ? */
opj_write_bytes(l_current_ptr, l_img_comp->prec - 1 + (l_img_comp->sgnd << 7),
1); /* Ssiz_i */
++l_current_ptr;
opj_write_bytes(l_current_ptr, l_img_comp->dx, 1); /* XRsiz_i */
++l_current_ptr;
opj_write_bytes(l_current_ptr, l_img_comp->dy, 1); /* YRsiz_i */
++l_current_ptr;
++l_img_comp;
}
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_size_len,
p_manager) != l_size_len) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a SIZ marker (image and tile size)
* @param p_j2k the jpeg2000 file codec.
* @param p_header_data the data contained in the SIZ box.
* @param p_header_size the size of the data contained in the SIZ marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_siz(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 i;
OPJ_UINT32 l_nb_comp;
OPJ_UINT32 l_nb_comp_remain;
OPJ_UINT32 l_remaining_size;
OPJ_UINT32 l_nb_tiles;
OPJ_UINT32 l_tmp, l_tx1, l_ty1;
OPJ_UINT32 l_prec0, l_sgnd0;
opj_image_t *l_image = 00;
opj_cp_t *l_cp = 00;
opj_image_comp_t * l_img_comp = 00;
opj_tcp_t * l_current_tile_param = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_header_data != 00);
l_image = p_j2k->m_private_image;
l_cp = &(p_j2k->m_cp);
/* minimum size == 39 - 3 (= minimum component parameter) */
if (p_header_size < 36) {
opj_event_msg(p_manager, EVT_ERROR, "Error with SIZ marker size\n");
return OPJ_FALSE;
}
l_remaining_size = p_header_size - 36;
l_nb_comp = l_remaining_size / 3;
l_nb_comp_remain = l_remaining_size % 3;
if (l_nb_comp_remain != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error with SIZ marker size\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_tmp,
2); /* Rsiz (capabilities) */
p_header_data += 2;
l_cp->rsiz = (OPJ_UINT16) l_tmp;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_image->x1, 4); /* Xsiz */
p_header_data += 4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_image->y1, 4); /* Ysiz */
p_header_data += 4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_image->x0, 4); /* X0siz */
p_header_data += 4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_image->y0, 4); /* Y0siz */
p_header_data += 4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_cp->tdx,
4); /* XTsiz */
p_header_data += 4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_cp->tdy,
4); /* YTsiz */
p_header_data += 4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_cp->tx0,
4); /* XT0siz */
p_header_data += 4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_cp->ty0,
4); /* YT0siz */
p_header_data += 4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_tmp,
2); /* Csiz */
p_header_data += 2;
if (l_tmp < 16385) {
l_image->numcomps = (OPJ_UINT16) l_tmp;
} else {
opj_event_msg(p_manager, EVT_ERROR,
"Error with SIZ marker: number of component is illegal -> %d\n", l_tmp);
return OPJ_FALSE;
}
if (l_image->numcomps != l_nb_comp) {
opj_event_msg(p_manager, EVT_ERROR,
"Error with SIZ marker: number of component is not compatible with the remaining number of parameters ( %d vs %d)\n",
l_image->numcomps, l_nb_comp);
return OPJ_FALSE;
}
/* testcase 4035.pdf.SIGSEGV.d8b.3375 */
/* testcase issue427-null-image-size.jp2 */
if ((l_image->x0 >= l_image->x1) || (l_image->y0 >= l_image->y1)) {
opj_event_msg(p_manager, EVT_ERROR,
"Error with SIZ marker: negative or zero image size (%" PRId64 " x %" PRId64
")\n", (OPJ_INT64)l_image->x1 - l_image->x0,
(OPJ_INT64)l_image->y1 - l_image->y0);
return OPJ_FALSE;
}
/* testcase 2539.pdf.SIGFPE.706.1712 (also 3622.pdf.SIGFPE.706.2916 and 4008.pdf.SIGFPE.706.3345 and maybe more) */
if ((l_cp->tdx == 0U) || (l_cp->tdy == 0U)) {
opj_event_msg(p_manager, EVT_ERROR,
"Error with SIZ marker: invalid tile size (tdx: %d, tdy: %d)\n", l_cp->tdx,
l_cp->tdy);
return OPJ_FALSE;
}
/* testcase 1610.pdf.SIGSEGV.59c.681 */
if ((0xFFFFFFFFU / l_image->x1) < l_image->y1) {
opj_event_msg(p_manager, EVT_ERROR,
"Prevent buffer overflow (x1: %d, y1: %d)\n", l_image->x1, l_image->y1);
return OPJ_FALSE;
}
/* testcase issue427-illegal-tile-offset.jp2 */
l_tx1 = opj_uint_adds(l_cp->tx0, l_cp->tdx); /* manage overflow */
l_ty1 = opj_uint_adds(l_cp->ty0, l_cp->tdy); /* manage overflow */
if ((l_cp->tx0 > l_image->x0) || (l_cp->ty0 > l_image->y0) ||
(l_tx1 <= l_image->x0) || (l_ty1 <= l_image->y0)) {
opj_event_msg(p_manager, EVT_ERROR,
"Error with SIZ marker: illegal tile offset\n");
return OPJ_FALSE;
}
if (!p_j2k->dump_state) {
OPJ_UINT32 siz_w, siz_h;
siz_w = l_image->x1 - l_image->x0;
siz_h = l_image->y1 - l_image->y0;
if (p_j2k->ihdr_w > 0 && p_j2k->ihdr_h > 0
&& (p_j2k->ihdr_w != siz_w || p_j2k->ihdr_h != siz_h)) {
opj_event_msg(p_manager, EVT_ERROR,
"Error with SIZ marker: IHDR w(%u) h(%u) vs. SIZ w(%u) h(%u)\n", p_j2k->ihdr_w,
p_j2k->ihdr_h, siz_w, siz_h);
return OPJ_FALSE;
}
}
#ifdef USE_JPWL
if (l_cp->correct) {
/* if JPWL is on, we check whether TX errors have damaged
too much the SIZ parameters */
if (!(l_image->x1 * l_image->y1)) {
opj_event_msg(p_manager, EVT_ERROR,
"JPWL: bad image size (%d x %d)\n",
l_image->x1, l_image->y1);
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
}
/* FIXME check previously in the function so why keep this piece of code ? Need by the norm ?
if (l_image->numcomps != ((len - 38) / 3)) {
opj_event_msg(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
"JPWL: Csiz is %d => space in SIZ only for %d comps.!!!\n",
l_image->numcomps, ((len - 38) / 3));
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
*/ /* we try to correct */
/* opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust this\n");
if (l_image->numcomps < ((len - 38) / 3)) {
len = 38 + 3 * l_image->numcomps;
opj_event_msg(p_manager, EVT_WARNING, "- setting Lsiz to %d => HYPOTHESIS!!!\n",
len);
} else {
l_image->numcomps = ((len - 38) / 3);
opj_event_msg(p_manager, EVT_WARNING, "- setting Csiz to %d => HYPOTHESIS!!!\n",
l_image->numcomps);
}
}
*/
/* update components number in the jpwl_exp_comps filed */
l_cp->exp_comps = l_image->numcomps;
}
#endif /* USE_JPWL */
/* Allocate the resulting image components */
l_image->comps = (opj_image_comp_t*) opj_calloc(l_image->numcomps,
sizeof(opj_image_comp_t));
if (l_image->comps == 00) {
l_image->numcomps = 0;
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to take in charge SIZ marker\n");
return OPJ_FALSE;
}
l_img_comp = l_image->comps;
l_prec0 = 0;
l_sgnd0 = 0;
/* Read the component information */
for (i = 0; i < l_image->numcomps; ++i) {
OPJ_UINT32 tmp;
opj_read_bytes(p_header_data, &tmp, 1); /* Ssiz_i */
++p_header_data;
l_img_comp->prec = (tmp & 0x7f) + 1;
l_img_comp->sgnd = tmp >> 7;
if (p_j2k->dump_state == 0) {
if (i == 0) {
l_prec0 = l_img_comp->prec;
l_sgnd0 = l_img_comp->sgnd;
} else if (!l_cp->allow_different_bit_depth_sign
&& (l_img_comp->prec != l_prec0 || l_img_comp->sgnd != l_sgnd0)) {
opj_event_msg(p_manager, EVT_WARNING,
"Despite JP2 BPC!=255, precision and/or sgnd values for comp[%d] is different than comp[0]:\n"
" [0] prec(%d) sgnd(%d) [%d] prec(%d) sgnd(%d)\n", i, l_prec0, l_sgnd0,
i, l_img_comp->prec, l_img_comp->sgnd);
}
/* TODO: we should perhaps also check against JP2 BPCC values */
}
opj_read_bytes(p_header_data, &tmp, 1); /* XRsiz_i */
++p_header_data;
l_img_comp->dx = (OPJ_UINT32)tmp; /* should be between 1 and 255 */
opj_read_bytes(p_header_data, &tmp, 1); /* YRsiz_i */
++p_header_data;
l_img_comp->dy = (OPJ_UINT32)tmp; /* should be between 1 and 255 */
if (l_img_comp->dx < 1 || l_img_comp->dx > 255 ||
l_img_comp->dy < 1 || l_img_comp->dy > 255) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid values for comp = %d : dx=%u dy=%u (should be between 1 and 255 according to the JPEG2000 norm)\n",
i, l_img_comp->dx, l_img_comp->dy);
return OPJ_FALSE;
}
/* Avoids later undefined shift in computation of */
/* p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps[i].m_dc_level_shift = 1
<< (l_image->comps[i].prec - 1); */
if (l_img_comp->prec > 31) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid values for comp = %d : prec=%u (should be between 1 and 38 according to the JPEG2000 norm. OpenJpeg only supports up to 31)\n",
i, l_img_comp->prec);
return OPJ_FALSE;
}
#ifdef USE_JPWL
if (l_cp->correct) {
/* if JPWL is on, we check whether TX errors have damaged
too much the SIZ parameters, again */
if (!(l_image->comps[i].dx * l_image->comps[i].dy)) {
opj_event_msg(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
"JPWL: bad XRsiz_%d/YRsiz_%d (%d x %d)\n",
i, i, l_image->comps[i].dx, l_image->comps[i].dy);
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
/* we try to correct */
opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust them\n");
if (!l_image->comps[i].dx) {
l_image->comps[i].dx = 1;
opj_event_msg(p_manager, EVT_WARNING,
"- setting XRsiz_%d to %d => HYPOTHESIS!!!\n",
i, l_image->comps[i].dx);
}
if (!l_image->comps[i].dy) {
l_image->comps[i].dy = 1;
opj_event_msg(p_manager, EVT_WARNING,
"- setting YRsiz_%d to %d => HYPOTHESIS!!!\n",
i, l_image->comps[i].dy);
}
}
}
#endif /* USE_JPWL */
l_img_comp->resno_decoded =
0; /* number of resolution decoded */
l_img_comp->factor =
l_cp->m_specific_param.m_dec.m_reduce; /* reducing factor per component */
++l_img_comp;
}
if (l_cp->tdx == 0 || l_cp->tdy == 0) {
return OPJ_FALSE;
}
/* Compute the number of tiles */
l_cp->tw = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)(l_image->x1 - l_cp->tx0),
(OPJ_INT32)l_cp->tdx);
l_cp->th = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)(l_image->y1 - l_cp->ty0),
(OPJ_INT32)l_cp->tdy);
/* Check that the number of tiles is valid */
if (l_cp->tw == 0 || l_cp->th == 0 || l_cp->tw > 65535 / l_cp->th) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid number of tiles : %u x %u (maximum fixed by jpeg2000 norm is 65535 tiles)\n",
l_cp->tw, l_cp->th);
return OPJ_FALSE;
}
l_nb_tiles = l_cp->tw * l_cp->th;
/* Define the tiles which will be decoded */
if (p_j2k->m_specific_param.m_decoder.m_discard_tiles) {
p_j2k->m_specific_param.m_decoder.m_start_tile_x =
(p_j2k->m_specific_param.m_decoder.m_start_tile_x - l_cp->tx0) / l_cp->tdx;
p_j2k->m_specific_param.m_decoder.m_start_tile_y =
(p_j2k->m_specific_param.m_decoder.m_start_tile_y - l_cp->ty0) / l_cp->tdy;
p_j2k->m_specific_param.m_decoder.m_end_tile_x = (OPJ_UINT32)opj_int_ceildiv((
OPJ_INT32)(p_j2k->m_specific_param.m_decoder.m_end_tile_x - l_cp->tx0),
(OPJ_INT32)l_cp->tdx);
p_j2k->m_specific_param.m_decoder.m_end_tile_y = (OPJ_UINT32)opj_int_ceildiv((
OPJ_INT32)(p_j2k->m_specific_param.m_decoder.m_end_tile_y - l_cp->ty0),
(OPJ_INT32)l_cp->tdy);
} else {
p_j2k->m_specific_param.m_decoder.m_start_tile_x = 0;
p_j2k->m_specific_param.m_decoder.m_start_tile_y = 0;
p_j2k->m_specific_param.m_decoder.m_end_tile_x = l_cp->tw;
p_j2k->m_specific_param.m_decoder.m_end_tile_y = l_cp->th;
}
#ifdef USE_JPWL
if (l_cp->correct) {
/* if JPWL is on, we check whether TX errors have damaged
too much the SIZ parameters */
if ((l_cp->tw < 1) || (l_cp->th < 1) || (l_cp->tw > l_cp->max_tiles) ||
(l_cp->th > l_cp->max_tiles)) {
opj_event_msg(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
"JPWL: bad number of tiles (%d x %d)\n",
l_cp->tw, l_cp->th);
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
/* we try to correct */
opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust them\n");
if (l_cp->tw < 1) {
l_cp->tw = 1;
opj_event_msg(p_manager, EVT_WARNING,
"- setting %d tiles in x => HYPOTHESIS!!!\n",
l_cp->tw);
}
if (l_cp->tw > l_cp->max_tiles) {
l_cp->tw = 1;
opj_event_msg(p_manager, EVT_WARNING,
"- too large x, increase expectance of %d\n"
"- setting %d tiles in x => HYPOTHESIS!!!\n",
l_cp->max_tiles, l_cp->tw);
}
if (l_cp->th < 1) {
l_cp->th = 1;
opj_event_msg(p_manager, EVT_WARNING,
"- setting %d tiles in y => HYPOTHESIS!!!\n",
l_cp->th);
}
if (l_cp->th > l_cp->max_tiles) {
l_cp->th = 1;
opj_event_msg(p_manager, EVT_WARNING,
"- too large y, increase expectance of %d to continue\n",
"- setting %d tiles in y => HYPOTHESIS!!!\n",
l_cp->max_tiles, l_cp->th);
}
}
}
#endif /* USE_JPWL */
/* memory allocations */
l_cp->tcps = (opj_tcp_t*) opj_calloc(l_nb_tiles, sizeof(opj_tcp_t));
if (l_cp->tcps == 00) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to take in charge SIZ marker\n");
return OPJ_FALSE;
}
#ifdef USE_JPWL
if (l_cp->correct) {
if (!l_cp->tcps) {
opj_event_msg(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
"JPWL: could not alloc tcps field of cp\n");
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
}
}
#endif /* USE_JPWL */
p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps =
(opj_tccp_t*) opj_calloc(l_image->numcomps, sizeof(opj_tccp_t));
if (p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps == 00) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to take in charge SIZ marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mct_records =
(opj_mct_data_t*)opj_calloc(OPJ_J2K_MCT_DEFAULT_NB_RECORDS,
sizeof(opj_mct_data_t));
if (! p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mct_records) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to take in charge SIZ marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_decoder.m_default_tcp->m_nb_max_mct_records =
OPJ_J2K_MCT_DEFAULT_NB_RECORDS;
p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mcc_records =
(opj_simple_mcc_decorrelation_data_t*)
opj_calloc(OPJ_J2K_MCC_DEFAULT_NB_RECORDS,
sizeof(opj_simple_mcc_decorrelation_data_t));
if (! p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mcc_records) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to take in charge SIZ marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_decoder.m_default_tcp->m_nb_max_mcc_records =
OPJ_J2K_MCC_DEFAULT_NB_RECORDS;
/* set up default dc level shift */
for (i = 0; i < l_image->numcomps; ++i) {
if (! l_image->comps[i].sgnd) {
p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps[i].m_dc_level_shift = 1
<< (l_image->comps[i].prec - 1);
}
}
l_current_tile_param = l_cp->tcps;
for (i = 0; i < l_nb_tiles; ++i) {
l_current_tile_param->tccps = (opj_tccp_t*) opj_calloc(l_image->numcomps,
sizeof(opj_tccp_t));
if (l_current_tile_param->tccps == 00) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to take in charge SIZ marker\n");
return OPJ_FALSE;
}
++l_current_tile_param;
}
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_MH;
opj_image_comp_header_update(l_image, l_cp);
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_com(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_comment_size;
OPJ_UINT32 l_total_com_size;
const OPJ_CHAR *l_comment;
OPJ_BYTE * l_current_ptr = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
l_comment = p_j2k->m_cp.comment;
l_comment_size = (OPJ_UINT32)strlen(l_comment);
l_total_com_size = l_comment_size + 6;
if (l_total_com_size >
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_total_com_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to write the COM marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_total_com_size;
}
l_current_ptr = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_ptr, J2K_MS_COM, 2); /* COM */
l_current_ptr += 2;
opj_write_bytes(l_current_ptr, l_total_com_size - 2, 2); /* L_COM */
l_current_ptr += 2;
opj_write_bytes(l_current_ptr, 1,
2); /* General use (IS 8859-15:1999 (Latin) values) */
l_current_ptr += 2;
memcpy(l_current_ptr, l_comment, l_comment_size);
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_total_com_size,
p_manager) != l_total_com_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a COM marker (comments)
* @param p_j2k the jpeg2000 file codec.
* @param p_header_data the data contained in the COM box.
* @param p_header_size the size of the data contained in the COM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_com(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_header_data != 00);
OPJ_UNUSED(p_j2k);
OPJ_UNUSED(p_header_data);
OPJ_UNUSED(p_header_size);
OPJ_UNUSED(p_manager);
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_cod(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
OPJ_UINT32 l_code_size, l_remaining_size;
OPJ_BYTE * l_current_data = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_j2k->m_current_tile_number];
l_code_size = 9 + opj_j2k_get_SPCod_SPCoc_size(p_j2k,
p_j2k->m_current_tile_number, 0);
l_remaining_size = l_code_size;
if (l_code_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_code_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write COD marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_code_size;
}
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_data, J2K_MS_COD, 2); /* COD */
l_current_data += 2;
opj_write_bytes(l_current_data, l_code_size - 2, 2); /* L_COD */
l_current_data += 2;
opj_write_bytes(l_current_data, l_tcp->csty, 1); /* Scod */
++l_current_data;
opj_write_bytes(l_current_data, (OPJ_UINT32)l_tcp->prg, 1); /* SGcod (A) */
++l_current_data;
opj_write_bytes(l_current_data, l_tcp->numlayers, 2); /* SGcod (B) */
l_current_data += 2;
opj_write_bytes(l_current_data, l_tcp->mct, 1); /* SGcod (C) */
++l_current_data;
l_remaining_size -= 9;
if (! opj_j2k_write_SPCod_SPCoc(p_j2k, p_j2k->m_current_tile_number, 0,
l_current_data, &l_remaining_size, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing COD marker\n");
return OPJ_FALSE;
}
if (l_remaining_size != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing COD marker\n");
return OPJ_FALSE;
}
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_code_size,
p_manager) != l_code_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a COD marker (Coding Styke defaults)
* @param p_header_data the data contained in the COD box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the COD marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_cod(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
/* loop */
OPJ_UINT32 i;
OPJ_UINT32 l_tmp;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_image_t *l_image = 00;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_image = p_j2k->m_private_image;
l_cp = &(p_j2k->m_cp);
/* If we are in the first tile-part header of the current tile */
l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
/* Only one COD per tile */
if (l_tcp->cod) {
opj_event_msg(p_manager, EVT_ERROR,
"COD marker already read. No more than one COD marker per tile.\n");
return OPJ_FALSE;
}
l_tcp->cod = 1;
/* Make sure room is sufficient */
if (p_header_size < 5) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading COD marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_tcp->csty, 1); /* Scod */
++p_header_data;
/* Make sure we know how to decode this */
if ((l_tcp->csty & ~(OPJ_UINT32)(J2K_CP_CSTY_PRT | J2K_CP_CSTY_SOP |
J2K_CP_CSTY_EPH)) != 0U) {
opj_event_msg(p_manager, EVT_ERROR, "Unknown Scod value in COD marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_tmp, 1); /* SGcod (A) */
++p_header_data;
l_tcp->prg = (OPJ_PROG_ORDER) l_tmp;
/* Make sure progression order is valid */
if (l_tcp->prg > OPJ_CPRL) {
opj_event_msg(p_manager, EVT_ERROR,
"Unknown progression order in COD marker\n");
l_tcp->prg = OPJ_PROG_UNKNOWN;
}
opj_read_bytes(p_header_data, &l_tcp->numlayers, 2); /* SGcod (B) */
p_header_data += 2;
if ((l_tcp->numlayers < 1U) || (l_tcp->numlayers > 65535U)) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid number of layers in COD marker : %d not in range [1-65535]\n",
l_tcp->numlayers);
return OPJ_FALSE;
}
/* If user didn't set a number layer to decode take the max specify in the codestream. */
if (l_cp->m_specific_param.m_dec.m_layer) {
l_tcp->num_layers_to_decode = l_cp->m_specific_param.m_dec.m_layer;
} else {
l_tcp->num_layers_to_decode = l_tcp->numlayers;
}
opj_read_bytes(p_header_data, &l_tcp->mct, 1); /* SGcod (C) */
++p_header_data;
p_header_size -= 5;
for (i = 0; i < l_image->numcomps; ++i) {
l_tcp->tccps[i].csty = l_tcp->csty & J2K_CCP_CSTY_PRT;
}
if (! opj_j2k_read_SPCod_SPCoc(p_j2k, 0, p_header_data, &p_header_size,
p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading COD marker\n");
return OPJ_FALSE;
}
if (p_header_size != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading COD marker\n");
return OPJ_FALSE;
}
/* Apply the coding style to other components of the current tile or the m_default_tcp*/
opj_j2k_copy_tile_component_parameters(p_j2k);
/* Index */
#ifdef WIP_REMOVE_MSD
if (p_j2k->cstr_info) {
/*opj_codestream_info_t *l_cstr_info = p_j2k->cstr_info;*/
p_j2k->cstr_info->prog = l_tcp->prg;
p_j2k->cstr_info->numlayers = l_tcp->numlayers;
p_j2k->cstr_info->numdecompos = (OPJ_INT32*) opj_malloc(
l_image->numcomps * sizeof(OPJ_UINT32));
if (!p_j2k->cstr_info->numdecompos) {
return OPJ_FALSE;
}
for (i = 0; i < l_image->numcomps; ++i) {
p_j2k->cstr_info->numdecompos[i] = l_tcp->tccps[i].numresolutions - 1;
}
}
#endif
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_coc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 l_coc_size, l_remaining_size;
OPJ_UINT32 l_comp_room;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_comp_room = (p_j2k->m_private_image->numcomps <= 256) ? 1 : 2;
l_coc_size = 5 + l_comp_room + opj_j2k_get_SPCod_SPCoc_size(p_j2k,
p_j2k->m_current_tile_number, p_comp_no);
if (l_coc_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data;
/*p_j2k->m_specific_param.m_encoder.m_header_tile_data
= (OPJ_BYTE*)opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data,
l_coc_size);*/
new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_coc_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write COC marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_coc_size;
}
opj_j2k_write_coc_in_memory(p_j2k, p_comp_no,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, &l_remaining_size,
p_manager);
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_coc_size,
p_manager) != l_coc_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_compare_coc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no)
{
opj_cp_t *l_cp = NULL;
opj_tcp_t *l_tcp = NULL;
/* preconditions */
assert(p_j2k != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_j2k->m_current_tile_number];
if (l_tcp->tccps[p_first_comp_no].csty != l_tcp->tccps[p_second_comp_no].csty) {
return OPJ_FALSE;
}
return opj_j2k_compare_SPCod_SPCoc(p_j2k, p_j2k->m_current_tile_number,
p_first_comp_no, p_second_comp_no);
}
static void opj_j2k_write_coc_in_memory(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
opj_event_mgr_t * p_manager
)
{
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
OPJ_UINT32 l_coc_size, l_remaining_size;
OPJ_BYTE * l_current_data = 00;
opj_image_t *l_image = 00;
OPJ_UINT32 l_comp_room;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_j2k->m_current_tile_number];
l_image = p_j2k->m_private_image;
l_comp_room = (l_image->numcomps <= 256) ? 1 : 2;
l_coc_size = 5 + l_comp_room + opj_j2k_get_SPCod_SPCoc_size(p_j2k,
p_j2k->m_current_tile_number, p_comp_no);
l_remaining_size = l_coc_size;
l_current_data = p_data;
opj_write_bytes(l_current_data, J2K_MS_COC,
2); /* COC */
l_current_data += 2;
opj_write_bytes(l_current_data, l_coc_size - 2,
2); /* L_COC */
l_current_data += 2;
opj_write_bytes(l_current_data, p_comp_no, l_comp_room); /* Ccoc */
l_current_data += l_comp_room;
opj_write_bytes(l_current_data, l_tcp->tccps[p_comp_no].csty,
1); /* Scoc */
++l_current_data;
l_remaining_size -= (5 + l_comp_room);
opj_j2k_write_SPCod_SPCoc(p_j2k, p_j2k->m_current_tile_number, 0,
l_current_data, &l_remaining_size, p_manager);
* p_data_written = l_coc_size;
}
static OPJ_UINT32 opj_j2k_get_max_coc_size(opj_j2k_t *p_j2k)
{
OPJ_UINT32 i, j;
OPJ_UINT32 l_nb_comp;
OPJ_UINT32 l_nb_tiles;
OPJ_UINT32 l_max = 0;
/* preconditions */
l_nb_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th ;
l_nb_comp = p_j2k->m_private_image->numcomps;
for (i = 0; i < l_nb_tiles; ++i) {
for (j = 0; j < l_nb_comp; ++j) {
l_max = opj_uint_max(l_max, opj_j2k_get_SPCod_SPCoc_size(p_j2k, i, j));
}
}
return 6 + l_max;
}
/**
* Reads a COC marker (Coding Style Component)
* @param p_header_data the data contained in the COC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the COC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_coc(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
opj_cp_t *l_cp = NULL;
opj_tcp_t *l_tcp = NULL;
opj_image_t *l_image = NULL;
OPJ_UINT32 l_comp_room;
OPJ_UINT32 l_comp_no;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH)
?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
l_image = p_j2k->m_private_image;
l_comp_room = l_image->numcomps <= 256 ? 1 : 2;
/* make sure room is sufficient*/
if (p_header_size < l_comp_room + 1) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading COC marker\n");
return OPJ_FALSE;
}
p_header_size -= l_comp_room + 1;
opj_read_bytes(p_header_data, &l_comp_no,
l_comp_room); /* Ccoc */
p_header_data += l_comp_room;
if (l_comp_no >= l_image->numcomps) {
opj_event_msg(p_manager, EVT_ERROR,
"Error reading COC marker (bad number of components)\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_tcp->tccps[l_comp_no].csty,
1); /* Scoc */
++p_header_data ;
if (! opj_j2k_read_SPCod_SPCoc(p_j2k, l_comp_no, p_header_data, &p_header_size,
p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading COC marker\n");
return OPJ_FALSE;
}
if (p_header_size != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading COC marker\n");
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_qcd(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_qcd_size, l_remaining_size;
OPJ_BYTE * l_current_data = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_qcd_size = 4 + opj_j2k_get_SQcd_SQcc_size(p_j2k, p_j2k->m_current_tile_number,
0);
l_remaining_size = l_qcd_size;
if (l_qcd_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_qcd_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write QCD marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_qcd_size;
}
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_data, J2K_MS_QCD, 2); /* QCD */
l_current_data += 2;
opj_write_bytes(l_current_data, l_qcd_size - 2, 2); /* L_QCD */
l_current_data += 2;
l_remaining_size -= 4;
if (! opj_j2k_write_SQcd_SQcc(p_j2k, p_j2k->m_current_tile_number, 0,
l_current_data, &l_remaining_size, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing QCD marker\n");
return OPJ_FALSE;
}
if (l_remaining_size != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing QCD marker\n");
return OPJ_FALSE;
}
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_qcd_size,
p_manager) != l_qcd_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a QCD marker (Quantization defaults)
* @param p_header_data the data contained in the QCD box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the QCD marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_qcd(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_j2k_read_SQcd_SQcc(p_j2k, 0, p_header_data, &p_header_size,
p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading QCD marker\n");
return OPJ_FALSE;
}
if (p_header_size != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading QCD marker\n");
return OPJ_FALSE;
}
/* Apply the quantization parameters to other components of the current tile or the m_default_tcp */
opj_j2k_copy_tile_quantization_parameters(p_j2k);
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_qcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_qcc_size, l_remaining_size;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_qcc_size = 5 + opj_j2k_get_SQcd_SQcc_size(p_j2k, p_j2k->m_current_tile_number,
p_comp_no);
l_qcc_size += p_j2k->m_private_image->numcomps <= 256 ? 0 : 1;
l_remaining_size = l_qcc_size;
if (l_qcc_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_qcc_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write QCC marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_qcc_size;
}
opj_j2k_write_qcc_in_memory(p_j2k, p_comp_no,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, &l_remaining_size,
p_manager);
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_qcc_size,
p_manager) != l_qcc_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_compare_qcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no)
{
return opj_j2k_compare_SQcd_SQcc(p_j2k, p_j2k->m_current_tile_number,
p_first_comp_no, p_second_comp_no);
}
static void opj_j2k_write_qcc_in_memory(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_qcc_size, l_remaining_size;
OPJ_BYTE * l_current_data = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
l_qcc_size = 6 + opj_j2k_get_SQcd_SQcc_size(p_j2k, p_j2k->m_current_tile_number,
p_comp_no);
l_remaining_size = l_qcc_size;
l_current_data = p_data;
opj_write_bytes(l_current_data, J2K_MS_QCC, 2); /* QCC */
l_current_data += 2;
if (p_j2k->m_private_image->numcomps <= 256) {
--l_qcc_size;
opj_write_bytes(l_current_data, l_qcc_size - 2, 2); /* L_QCC */
l_current_data += 2;
opj_write_bytes(l_current_data, p_comp_no, 1); /* Cqcc */
++l_current_data;
/* in the case only one byte is sufficient the last byte allocated is useless -> still do -6 for available */
l_remaining_size -= 6;
} else {
opj_write_bytes(l_current_data, l_qcc_size - 2, 2); /* L_QCC */
l_current_data += 2;
opj_write_bytes(l_current_data, p_comp_no, 2); /* Cqcc */
l_current_data += 2;
l_remaining_size -= 6;
}
opj_j2k_write_SQcd_SQcc(p_j2k, p_j2k->m_current_tile_number, p_comp_no,
l_current_data, &l_remaining_size, p_manager);
*p_data_written = l_qcc_size;
}
static OPJ_UINT32 opj_j2k_get_max_qcc_size(opj_j2k_t *p_j2k)
{
return opj_j2k_get_max_coc_size(p_j2k);
}
/**
* Reads a QCC marker (Quantization component)
* @param p_header_data the data contained in the QCC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the QCC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_qcc(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_num_comp, l_comp_no;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_num_comp = p_j2k->m_private_image->numcomps;
if (l_num_comp <= 256) {
if (p_header_size < 1) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading QCC marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_comp_no, 1);
++p_header_data;
--p_header_size;
} else {
if (p_header_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading QCC marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_comp_no, 2);
p_header_data += 2;
p_header_size -= 2;
}
#ifdef USE_JPWL
if (p_j2k->m_cp.correct) {
static OPJ_UINT32 backup_compno = 0;
/* compno is negative or larger than the number of components!!! */
if (/*(l_comp_no < 0) ||*/ (l_comp_no >= l_num_comp)) {
opj_event_msg(p_manager, EVT_ERROR,
"JPWL: bad component number in QCC (%d out of a maximum of %d)\n",
l_comp_no, l_num_comp);
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
/* we try to correct */
l_comp_no = backup_compno % l_num_comp;
opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust this\n"
"- setting component number to %d\n",
l_comp_no);
}
/* keep your private count of tiles */
backup_compno++;
};
#endif /* USE_JPWL */
if (l_comp_no >= p_j2k->m_private_image->numcomps) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid component number: %d, regarding the number of components %d\n",
l_comp_no, p_j2k->m_private_image->numcomps);
return OPJ_FALSE;
}
if (! opj_j2k_read_SQcd_SQcc(p_j2k, l_comp_no, p_header_data, &p_header_size,
p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading QCC marker\n");
return OPJ_FALSE;
}
if (p_header_size != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading QCC marker\n");
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_poc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_nb_comp;
OPJ_UINT32 l_nb_poc;
OPJ_UINT32 l_poc_size;
OPJ_UINT32 l_written_size = 0;
opj_tcp_t *l_tcp = 00;
OPJ_UINT32 l_poc_room;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_tcp = &p_j2k->m_cp.tcps[p_j2k->m_current_tile_number];
l_nb_comp = p_j2k->m_private_image->numcomps;
l_nb_poc = 1 + l_tcp->numpocs;
if (l_nb_comp <= 256) {
l_poc_room = 1;
} else {
l_poc_room = 2;
}
l_poc_size = 4 + (5 + 2 * l_poc_room) * l_nb_poc;
if (l_poc_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_poc_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write POC marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_poc_size;
}
opj_j2k_write_poc_in_memory(p_j2k,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, &l_written_size,
p_manager);
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_poc_size,
p_manager) != l_poc_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static void opj_j2k_write_poc_in_memory(opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 i;
OPJ_BYTE * l_current_data = 00;
OPJ_UINT32 l_nb_comp;
OPJ_UINT32 l_nb_poc;
OPJ_UINT32 l_poc_size;
opj_image_t *l_image = 00;
opj_tcp_t *l_tcp = 00;
opj_tccp_t *l_tccp = 00;
opj_poc_t *l_current_poc = 00;
OPJ_UINT32 l_poc_room;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_manager);
l_tcp = &p_j2k->m_cp.tcps[p_j2k->m_current_tile_number];
l_tccp = &l_tcp->tccps[0];
l_image = p_j2k->m_private_image;
l_nb_comp = l_image->numcomps;
l_nb_poc = 1 + l_tcp->numpocs;
if (l_nb_comp <= 256) {
l_poc_room = 1;
} else {
l_poc_room = 2;
}
l_poc_size = 4 + (5 + 2 * l_poc_room) * l_nb_poc;
l_current_data = p_data;
opj_write_bytes(l_current_data, J2K_MS_POC,
2); /* POC */
l_current_data += 2;
opj_write_bytes(l_current_data, l_poc_size - 2,
2); /* Lpoc */
l_current_data += 2;
l_current_poc = l_tcp->pocs;
for (i = 0; i < l_nb_poc; ++i) {
opj_write_bytes(l_current_data, l_current_poc->resno0,
1); /* RSpoc_i */
++l_current_data;
opj_write_bytes(l_current_data, l_current_poc->compno0,
l_poc_room); /* CSpoc_i */
l_current_data += l_poc_room;
opj_write_bytes(l_current_data, l_current_poc->layno1,
2); /* LYEpoc_i */
l_current_data += 2;
opj_write_bytes(l_current_data, l_current_poc->resno1,
1); /* REpoc_i */
++l_current_data;
opj_write_bytes(l_current_data, l_current_poc->compno1,
l_poc_room); /* CEpoc_i */
l_current_data += l_poc_room;
opj_write_bytes(l_current_data, (OPJ_UINT32)l_current_poc->prg,
1); /* Ppoc_i */
++l_current_data;
/* change the value of the max layer according to the actual number of layers in the file, components and resolutions*/
l_current_poc->layno1 = (OPJ_UINT32)opj_int_min((OPJ_INT32)
l_current_poc->layno1, (OPJ_INT32)l_tcp->numlayers);
l_current_poc->resno1 = (OPJ_UINT32)opj_int_min((OPJ_INT32)
l_current_poc->resno1, (OPJ_INT32)l_tccp->numresolutions);
l_current_poc->compno1 = (OPJ_UINT32)opj_int_min((OPJ_INT32)
l_current_poc->compno1, (OPJ_INT32)l_nb_comp);
++l_current_poc;
}
*p_data_written = l_poc_size;
}
static OPJ_UINT32 opj_j2k_get_max_poc_size(opj_j2k_t *p_j2k)
{
opj_tcp_t * l_tcp = 00;
OPJ_UINT32 l_nb_tiles = 0;
OPJ_UINT32 l_max_poc = 0;
OPJ_UINT32 i;
l_tcp = p_j2k->m_cp.tcps;
l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
for (i = 0; i < l_nb_tiles; ++i) {
l_max_poc = opj_uint_max(l_max_poc, l_tcp->numpocs);
++l_tcp;
}
++l_max_poc;
return 4 + 9 * l_max_poc;
}
static OPJ_UINT32 opj_j2k_get_max_toc_size(opj_j2k_t *p_j2k)
{
OPJ_UINT32 i;
OPJ_UINT32 l_nb_tiles;
OPJ_UINT32 l_max = 0;
opj_tcp_t * l_tcp = 00;
l_tcp = p_j2k->m_cp.tcps;
l_nb_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th ;
for (i = 0; i < l_nb_tiles; ++i) {
l_max = opj_uint_max(l_max, l_tcp->m_nb_tile_parts);
++l_tcp;
}
return 12 * l_max;
}
static OPJ_UINT32 opj_j2k_get_specific_header_sizes(opj_j2k_t *p_j2k)
{
OPJ_UINT32 l_nb_bytes = 0;
OPJ_UINT32 l_nb_comps;
OPJ_UINT32 l_coc_bytes, l_qcc_bytes;
l_nb_comps = p_j2k->m_private_image->numcomps - 1;
l_nb_bytes += opj_j2k_get_max_toc_size(p_j2k);
if (!(OPJ_IS_CINEMA(p_j2k->m_cp.rsiz))) {
l_coc_bytes = opj_j2k_get_max_coc_size(p_j2k);
l_nb_bytes += l_nb_comps * l_coc_bytes;
l_qcc_bytes = opj_j2k_get_max_qcc_size(p_j2k);
l_nb_bytes += l_nb_comps * l_qcc_bytes;
}
l_nb_bytes += opj_j2k_get_max_poc_size(p_j2k);
/*** DEVELOPER CORNER, Add room for your headers ***/
return l_nb_bytes;
}
/**
* Reads a POC marker (Progression Order Change)
*
* @param p_header_data the data contained in the POC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the POC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_poc(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 i, l_nb_comp, l_tmp;
opj_image_t * l_image = 00;
OPJ_UINT32 l_old_poc_nb, l_current_poc_nb, l_current_poc_remaining;
OPJ_UINT32 l_chunk_size, l_comp_room;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_poc_t *l_current_poc = 00;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_image = p_j2k->m_private_image;
l_nb_comp = l_image->numcomps;
if (l_nb_comp <= 256) {
l_comp_room = 1;
} else {
l_comp_room = 2;
}
l_chunk_size = 5 + 2 * l_comp_room;
l_current_poc_nb = p_header_size / l_chunk_size;
l_current_poc_remaining = p_header_size % l_chunk_size;
if ((l_current_poc_nb <= 0) || (l_current_poc_remaining != 0)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading POC marker\n");
return OPJ_FALSE;
}
l_cp = &(p_j2k->m_cp);
l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
l_old_poc_nb = l_tcp->POC ? l_tcp->numpocs + 1 : 0;
l_current_poc_nb += l_old_poc_nb;
if (l_current_poc_nb >= 32) {
opj_event_msg(p_manager, EVT_ERROR, "Too many POCs %d\n", l_current_poc_nb);
return OPJ_FALSE;
}
assert(l_current_poc_nb < 32);
/* now poc is in use.*/
l_tcp->POC = 1;
l_current_poc = &l_tcp->pocs[l_old_poc_nb];
for (i = l_old_poc_nb; i < l_current_poc_nb; ++i) {
opj_read_bytes(p_header_data, &(l_current_poc->resno0),
1); /* RSpoc_i */
++p_header_data;
opj_read_bytes(p_header_data, &(l_current_poc->compno0),
l_comp_room); /* CSpoc_i */
p_header_data += l_comp_room;
opj_read_bytes(p_header_data, &(l_current_poc->layno1),
2); /* LYEpoc_i */
/* make sure layer end is in acceptable bounds */
l_current_poc->layno1 = opj_uint_min(l_current_poc->layno1, l_tcp->numlayers);
p_header_data += 2;
opj_read_bytes(p_header_data, &(l_current_poc->resno1),
1); /* REpoc_i */
++p_header_data;
opj_read_bytes(p_header_data, &(l_current_poc->compno1),
l_comp_room); /* CEpoc_i */
p_header_data += l_comp_room;
opj_read_bytes(p_header_data, &l_tmp,
1); /* Ppoc_i */
++p_header_data;
l_current_poc->prg = (OPJ_PROG_ORDER) l_tmp;
/* make sure comp is in acceptable bounds */
l_current_poc->compno1 = opj_uint_min(l_current_poc->compno1, l_nb_comp);
++l_current_poc;
}
l_tcp->numpocs = l_current_poc_nb - 1;
return OPJ_TRUE;
}
/**
* Reads a CRG marker (Component registration)
*
* @param p_header_data the data contained in the TLM box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the TLM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_crg(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_nb_comp;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_header_data);
l_nb_comp = p_j2k->m_private_image->numcomps;
if (p_header_size != l_nb_comp * 4) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading CRG marker\n");
return OPJ_FALSE;
}
/* Do not care of this at the moment since only local variables are set here */
/*
for
(i = 0; i < l_nb_comp; ++i)
{
opj_read_bytes(p_header_data,&l_Xcrg_i,2); // Xcrg_i
p_header_data+=2;
opj_read_bytes(p_header_data,&l_Ycrg_i,2); // Xcrg_i
p_header_data+=2;
}
*/
return OPJ_TRUE;
}
/**
* Reads a TLM marker (Tile Length Marker)
*
* @param p_header_data the data contained in the TLM box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the TLM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_tlm(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_Ztlm, l_Stlm, l_ST, l_SP, l_tot_num_tp_remaining, l_quotient,
l_Ptlm_size;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_j2k);
if (p_header_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading TLM marker\n");
return OPJ_FALSE;
}
p_header_size -= 2;
opj_read_bytes(p_header_data, &l_Ztlm,
1); /* Ztlm */
++p_header_data;
opj_read_bytes(p_header_data, &l_Stlm,
1); /* Stlm */
++p_header_data;
l_ST = ((l_Stlm >> 4) & 0x3);
l_SP = (l_Stlm >> 6) & 0x1;
l_Ptlm_size = (l_SP + 1) * 2;
l_quotient = l_Ptlm_size + l_ST;
l_tot_num_tp_remaining = p_header_size % l_quotient;
if (l_tot_num_tp_remaining != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading TLM marker\n");
return OPJ_FALSE;
}
/* FIXME Do not care of this at the moment since only local variables are set here */
/*
for
(i = 0; i < l_tot_num_tp; ++i)
{
opj_read_bytes(p_header_data,&l_Ttlm_i,l_ST); // Ttlm_i
p_header_data += l_ST;
opj_read_bytes(p_header_data,&l_Ptlm_i,l_Ptlm_size); // Ptlm_i
p_header_data += l_Ptlm_size;
}*/
return OPJ_TRUE;
}
/**
* Reads a PLM marker (Packet length, main header marker)
*
* @param p_header_data the data contained in the TLM box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the TLM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_plm(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_j2k);
OPJ_UNUSED(p_header_data);
if (p_header_size < 1) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading PLM marker\n");
return OPJ_FALSE;
}
/* Do not care of this at the moment since only local variables are set here */
/*
opj_read_bytes(p_header_data,&l_Zplm,1); // Zplm
++p_header_data;
--p_header_size;
while
(p_header_size > 0)
{
opj_read_bytes(p_header_data,&l_Nplm,1); // Nplm
++p_header_data;
p_header_size -= (1+l_Nplm);
if
(p_header_size < 0)
{
opj_event_msg(p_manager, EVT_ERROR, "Error reading PLM marker\n");
return false;
}
for
(i = 0; i < l_Nplm; ++i)
{
opj_read_bytes(p_header_data,&l_tmp,1); // Iplm_ij
++p_header_data;
// take only the last seven bytes
l_packet_len |= (l_tmp & 0x7f);
if
(l_tmp & 0x80)
{
l_packet_len <<= 7;
}
else
{
// store packet length and proceed to next packet
l_packet_len = 0;
}
}
if
(l_packet_len != 0)
{
opj_event_msg(p_manager, EVT_ERROR, "Error reading PLM marker\n");
return false;
}
}
*/
return OPJ_TRUE;
}
/**
* Reads a PLT marker (Packet length, tile-part header)
*
* @param p_header_data the data contained in the PLT box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the PLT marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_plt(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_Zplt, l_tmp, l_packet_len = 0, i;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_j2k);
if (p_header_size < 1) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading PLT marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_Zplt, 1); /* Zplt */
++p_header_data;
--p_header_size;
for (i = 0; i < p_header_size; ++i) {
opj_read_bytes(p_header_data, &l_tmp, 1); /* Iplt_ij */
++p_header_data;
/* take only the last seven bytes */
l_packet_len |= (l_tmp & 0x7f);
if (l_tmp & 0x80) {
l_packet_len <<= 7;
} else {
/* store packet length and proceed to next packet */
l_packet_len = 0;
}
}
if (l_packet_len != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading PLT marker\n");
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a PPM marker (Packed packet headers, main header)
*
* @param p_header_data the data contained in the POC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the POC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_ppm(
opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager)
{
opj_cp_t *l_cp = 00;
OPJ_UINT32 l_Z_ppm;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
/* We need to have the Z_ppm element + 1 byte of Nppm/Ippm at minimum */
if (p_header_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading PPM marker\n");
return OPJ_FALSE;
}
l_cp = &(p_j2k->m_cp);
l_cp->ppm = 1;
opj_read_bytes(p_header_data, &l_Z_ppm, 1); /* Z_ppm */
++p_header_data;
--p_header_size;
/* check allocation needed */
if (l_cp->ppm_markers == NULL) { /* first PPM marker */
OPJ_UINT32 l_newCount = l_Z_ppm + 1U; /* can't overflow, l_Z_ppm is UINT8 */
assert(l_cp->ppm_markers_count == 0U);
l_cp->ppm_markers = (opj_ppx *) opj_calloc(l_newCount, sizeof(opj_ppx));
if (l_cp->ppm_markers == NULL) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPM marker\n");
return OPJ_FALSE;
}
l_cp->ppm_markers_count = l_newCount;
} else if (l_cp->ppm_markers_count <= l_Z_ppm) {
OPJ_UINT32 l_newCount = l_Z_ppm + 1U; /* can't overflow, l_Z_ppm is UINT8 */
opj_ppx *new_ppm_markers;
new_ppm_markers = (opj_ppx *) opj_realloc(l_cp->ppm_markers,
l_newCount * sizeof(opj_ppx));
if (new_ppm_markers == NULL) {
/* clean up to be done on l_cp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPM marker\n");
return OPJ_FALSE;
}
l_cp->ppm_markers = new_ppm_markers;
memset(l_cp->ppm_markers + l_cp->ppm_markers_count, 0,
(l_newCount - l_cp->ppm_markers_count) * sizeof(opj_ppx));
l_cp->ppm_markers_count = l_newCount;
}
if (l_cp->ppm_markers[l_Z_ppm].m_data != NULL) {
/* clean up to be done on l_cp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Zppm %u already read\n", l_Z_ppm);
return OPJ_FALSE;
}
l_cp->ppm_markers[l_Z_ppm].m_data = (OPJ_BYTE *) opj_malloc(p_header_size);
if (l_cp->ppm_markers[l_Z_ppm].m_data == NULL) {
/* clean up to be done on l_cp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPM marker\n");
return OPJ_FALSE;
}
l_cp->ppm_markers[l_Z_ppm].m_data_size = p_header_size;
memcpy(l_cp->ppm_markers[l_Z_ppm].m_data, p_header_data, p_header_size);
return OPJ_TRUE;
}
/**
* Merges all PPM markers read (Packed headers, main header)
*
* @param p_cp main coding parameters.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_merge_ppm(opj_cp_t *p_cp, opj_event_mgr_t * p_manager)
{
OPJ_UINT32 i, l_ppm_data_size, l_N_ppm_remaining;
/* preconditions */
assert(p_cp != 00);
assert(p_manager != 00);
assert(p_cp->ppm_buffer == NULL);
if (p_cp->ppm == 0U) {
return OPJ_TRUE;
}
l_ppm_data_size = 0U;
l_N_ppm_remaining = 0U;
for (i = 0U; i < p_cp->ppm_markers_count; ++i) {
if (p_cp->ppm_markers[i].m_data !=
NULL) { /* standard doesn't seem to require contiguous Zppm */
OPJ_UINT32 l_N_ppm;
OPJ_UINT32 l_data_size = p_cp->ppm_markers[i].m_data_size;
const OPJ_BYTE* l_data = p_cp->ppm_markers[i].m_data;
if (l_N_ppm_remaining >= l_data_size) {
l_N_ppm_remaining -= l_data_size;
l_data_size = 0U;
} else {
l_data += l_N_ppm_remaining;
l_data_size -= l_N_ppm_remaining;
l_N_ppm_remaining = 0U;
}
if (l_data_size > 0U) {
do {
/* read Nppm */
if (l_data_size < 4U) {
/* clean up to be done on l_cp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Not enough bytes to read Nppm\n");
return OPJ_FALSE;
}
opj_read_bytes(l_data, &l_N_ppm, 4);
l_data += 4;
l_data_size -= 4;
l_ppm_data_size +=
l_N_ppm; /* can't overflow, max 256 markers of max 65536 bytes, that is when PPM markers are not corrupted which is checked elsewhere */
if (l_data_size >= l_N_ppm) {
l_data_size -= l_N_ppm;
l_data += l_N_ppm;
} else {
l_N_ppm_remaining = l_N_ppm - l_data_size;
l_data_size = 0U;
}
} while (l_data_size > 0U);
}
}
}
if (l_N_ppm_remaining != 0U) {
/* clean up to be done on l_cp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Corrupted PPM markers\n");
return OPJ_FALSE;
}
p_cp->ppm_buffer = (OPJ_BYTE *) opj_malloc(l_ppm_data_size);
if (p_cp->ppm_buffer == 00) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPM marker\n");
return OPJ_FALSE;
}
p_cp->ppm_len = l_ppm_data_size;
l_ppm_data_size = 0U;
l_N_ppm_remaining = 0U;
for (i = 0U; i < p_cp->ppm_markers_count; ++i) {
if (p_cp->ppm_markers[i].m_data !=
NULL) { /* standard doesn't seem to require contiguous Zppm */
OPJ_UINT32 l_N_ppm;
OPJ_UINT32 l_data_size = p_cp->ppm_markers[i].m_data_size;
const OPJ_BYTE* l_data = p_cp->ppm_markers[i].m_data;
if (l_N_ppm_remaining >= l_data_size) {
memcpy(p_cp->ppm_buffer + l_ppm_data_size, l_data, l_data_size);
l_ppm_data_size += l_data_size;
l_N_ppm_remaining -= l_data_size;
l_data_size = 0U;
} else {
memcpy(p_cp->ppm_buffer + l_ppm_data_size, l_data, l_N_ppm_remaining);
l_ppm_data_size += l_N_ppm_remaining;
l_data += l_N_ppm_remaining;
l_data_size -= l_N_ppm_remaining;
l_N_ppm_remaining = 0U;
}
if (l_data_size > 0U) {
do {
/* read Nppm */
if (l_data_size < 4U) {
/* clean up to be done on l_cp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Not enough bytes to read Nppm\n");
return OPJ_FALSE;
}
opj_read_bytes(l_data, &l_N_ppm, 4);
l_data += 4;
l_data_size -= 4;
if (l_data_size >= l_N_ppm) {
memcpy(p_cp->ppm_buffer + l_ppm_data_size, l_data, l_N_ppm);
l_ppm_data_size += l_N_ppm;
l_data_size -= l_N_ppm;
l_data += l_N_ppm;
} else {
memcpy(p_cp->ppm_buffer + l_ppm_data_size, l_data, l_data_size);
l_ppm_data_size += l_data_size;
l_N_ppm_remaining = l_N_ppm - l_data_size;
l_data_size = 0U;
}
} while (l_data_size > 0U);
}
opj_free(p_cp->ppm_markers[i].m_data);
p_cp->ppm_markers[i].m_data = NULL;
p_cp->ppm_markers[i].m_data_size = 0U;
}
}
p_cp->ppm_data = p_cp->ppm_buffer;
p_cp->ppm_data_size = p_cp->ppm_len;
p_cp->ppm_markers_count = 0U;
opj_free(p_cp->ppm_markers);
p_cp->ppm_markers = NULL;
return OPJ_TRUE;
}
/**
* Reads a PPT marker (Packed packet headers, tile-part header)
*
* @param p_header_data the data contained in the PPT box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the PPT marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_ppt(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
OPJ_UINT32 l_Z_ppt;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
/* We need to have the Z_ppt element + 1 byte of Ippt at minimum */
if (p_header_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading PPT marker\n");
return OPJ_FALSE;
}
l_cp = &(p_j2k->m_cp);
if (l_cp->ppm) {
opj_event_msg(p_manager, EVT_ERROR,
"Error reading PPT marker: packet header have been previously found in the main header (PPM marker).\n");
return OPJ_FALSE;
}
l_tcp = &(l_cp->tcps[p_j2k->m_current_tile_number]);
l_tcp->ppt = 1;
opj_read_bytes(p_header_data, &l_Z_ppt, 1); /* Z_ppt */
++p_header_data;
--p_header_size;
/* check allocation needed */
if (l_tcp->ppt_markers == NULL) { /* first PPT marker */
OPJ_UINT32 l_newCount = l_Z_ppt + 1U; /* can't overflow, l_Z_ppt is UINT8 */
assert(l_tcp->ppt_markers_count == 0U);
l_tcp->ppt_markers = (opj_ppx *) opj_calloc(l_newCount, sizeof(opj_ppx));
if (l_tcp->ppt_markers == NULL) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPT marker\n");
return OPJ_FALSE;
}
l_tcp->ppt_markers_count = l_newCount;
} else if (l_tcp->ppt_markers_count <= l_Z_ppt) {
OPJ_UINT32 l_newCount = l_Z_ppt + 1U; /* can't overflow, l_Z_ppt is UINT8 */
opj_ppx *new_ppt_markers;
new_ppt_markers = (opj_ppx *) opj_realloc(l_tcp->ppt_markers,
l_newCount * sizeof(opj_ppx));
if (new_ppt_markers == NULL) {
/* clean up to be done on l_tcp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPT marker\n");
return OPJ_FALSE;
}
l_tcp->ppt_markers = new_ppt_markers;
memset(l_tcp->ppt_markers + l_tcp->ppt_markers_count, 0,
(l_newCount - l_tcp->ppt_markers_count) * sizeof(opj_ppx));
l_tcp->ppt_markers_count = l_newCount;
}
if (l_tcp->ppt_markers[l_Z_ppt].m_data != NULL) {
/* clean up to be done on l_tcp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Zppt %u already read\n", l_Z_ppt);
return OPJ_FALSE;
}
l_tcp->ppt_markers[l_Z_ppt].m_data = (OPJ_BYTE *) opj_malloc(p_header_size);
if (l_tcp->ppt_markers[l_Z_ppt].m_data == NULL) {
/* clean up to be done on l_tcp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPT marker\n");
return OPJ_FALSE;
}
l_tcp->ppt_markers[l_Z_ppt].m_data_size = p_header_size;
memcpy(l_tcp->ppt_markers[l_Z_ppt].m_data, p_header_data, p_header_size);
return OPJ_TRUE;
}
/**
* Merges all PPT markers read (Packed packet headers, tile-part header)
*
* @param p_tcp the tile.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_merge_ppt(opj_tcp_t *p_tcp, opj_event_mgr_t * p_manager)
{
OPJ_UINT32 i, l_ppt_data_size;
/* preconditions */
assert(p_tcp != 00);
assert(p_manager != 00);
assert(p_tcp->ppt_buffer == NULL);
if (p_tcp->ppt == 0U) {
return OPJ_TRUE;
}
l_ppt_data_size = 0U;
for (i = 0U; i < p_tcp->ppt_markers_count; ++i) {
l_ppt_data_size +=
p_tcp->ppt_markers[i].m_data_size; /* can't overflow, max 256 markers of max 65536 bytes */
}
p_tcp->ppt_buffer = (OPJ_BYTE *) opj_malloc(l_ppt_data_size);
if (p_tcp->ppt_buffer == 00) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPT marker\n");
return OPJ_FALSE;
}
p_tcp->ppt_len = l_ppt_data_size;
l_ppt_data_size = 0U;
for (i = 0U; i < p_tcp->ppt_markers_count; ++i) {
if (p_tcp->ppt_markers[i].m_data !=
NULL) { /* standard doesn't seem to require contiguous Zppt */
memcpy(p_tcp->ppt_buffer + l_ppt_data_size, p_tcp->ppt_markers[i].m_data,
p_tcp->ppt_markers[i].m_data_size);
l_ppt_data_size +=
p_tcp->ppt_markers[i].m_data_size; /* can't overflow, max 256 markers of max 65536 bytes */
opj_free(p_tcp->ppt_markers[i].m_data);
p_tcp->ppt_markers[i].m_data = NULL;
p_tcp->ppt_markers[i].m_data_size = 0U;
}
}
p_tcp->ppt_markers_count = 0U;
opj_free(p_tcp->ppt_markers);
p_tcp->ppt_markers = NULL;
p_tcp->ppt_data = p_tcp->ppt_buffer;
p_tcp->ppt_data_size = p_tcp->ppt_len;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_tlm(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_BYTE * l_current_data = 00;
OPJ_UINT32 l_tlm_size;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_tlm_size = 6 + (5 * p_j2k->m_specific_param.m_encoder.m_total_tile_parts);
if (l_tlm_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_tlm_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write TLM marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_tlm_size;
}
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
/* change the way data is written to avoid seeking if possible */
/* TODO */
p_j2k->m_specific_param.m_encoder.m_tlm_start = opj_stream_tell(p_stream);
opj_write_bytes(l_current_data, J2K_MS_TLM,
2); /* TLM */
l_current_data += 2;
opj_write_bytes(l_current_data, l_tlm_size - 2,
2); /* Lpoc */
l_current_data += 2;
opj_write_bytes(l_current_data, 0,
1); /* Ztlm=0*/
++l_current_data;
opj_write_bytes(l_current_data, 0x50,
1); /* Stlm ST=1(8bits-255 tiles max),SP=1(Ptlm=32bits) */
++l_current_data;
/* do nothing on the 5 * l_j2k->m_specific_param.m_encoder.m_total_tile_parts remaining data */
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_tlm_size,
p_manager) != l_tlm_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_sot(opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
const opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
OPJ_UNUSED(p_stream);
OPJ_UNUSED(p_manager);
opj_write_bytes(p_data, J2K_MS_SOT,
2); /* SOT */
p_data += 2;
opj_write_bytes(p_data, 10,
2); /* Lsot */
p_data += 2;
opj_write_bytes(p_data, p_j2k->m_current_tile_number,
2); /* Isot */
p_data += 2;
/* Psot */
p_data += 4;
opj_write_bytes(p_data,
p_j2k->m_specific_param.m_encoder.m_current_tile_part_number,
1); /* TPsot */
++p_data;
opj_write_bytes(p_data,
p_j2k->m_cp.tcps[p_j2k->m_current_tile_number].m_nb_tile_parts,
1); /* TNsot */
++p_data;
/* UniPG>> */
#ifdef USE_JPWL
/* update markers struct */
/*
OPJ_BOOL res = j2k_add_marker(p_j2k->cstr_info, J2K_MS_SOT, p_j2k->sot_start, len + 2);
*/
assert(0 && "TODO");
#endif /* USE_JPWL */
* p_data_written = 12;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_get_sot_values(OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
OPJ_UINT32* p_tile_no,
OPJ_UINT32* p_tot_len,
OPJ_UINT32* p_current_part,
OPJ_UINT32* p_num_parts,
opj_event_mgr_t * p_manager)
{
/* preconditions */
assert(p_header_data != 00);
assert(p_manager != 00);
/* Size of this marker is fixed = 12 (we have already read marker and its size)*/
if (p_header_size != 8) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading SOT marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, p_tile_no, 2); /* Isot */
p_header_data += 2;
opj_read_bytes(p_header_data, p_tot_len, 4); /* Psot */
p_header_data += 4;
opj_read_bytes(p_header_data, p_current_part, 1); /* TPsot */
++p_header_data;
opj_read_bytes(p_header_data, p_num_parts, 1); /* TNsot */
++p_header_data;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_read_sot(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager)
{
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
OPJ_UINT32 l_tot_len, l_num_parts = 0;
OPJ_UINT32 l_current_part;
OPJ_UINT32 l_tile_x, l_tile_y;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_j2k_get_sot_values(p_header_data, p_header_size,
&(p_j2k->m_current_tile_number), &l_tot_len, &l_current_part, &l_num_parts,
p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading SOT marker\n");
return OPJ_FALSE;
}
l_cp = &(p_j2k->m_cp);
/* testcase 2.pdf.SIGFPE.706.1112 */
if (p_j2k->m_current_tile_number >= l_cp->tw * l_cp->th) {
opj_event_msg(p_manager, EVT_ERROR, "Invalid tile number %d\n",
p_j2k->m_current_tile_number);
return OPJ_FALSE;
}
l_tcp = &l_cp->tcps[p_j2k->m_current_tile_number];
l_tile_x = p_j2k->m_current_tile_number % l_cp->tw;
l_tile_y = p_j2k->m_current_tile_number / l_cp->tw;
/* Fixes issue with id_000020,sig_06,src_001958,op_flip4,pos_149 */
/* of https://github.com/uclouvain/openjpeg/issues/939 */
/* We must avoid reading twice the same tile part number for a given tile */
/* so as to avoid various issues, like opj_j2k_merge_ppt being called */
/* several times. */
/* ISO 15444-1 A.4.2 Start of tile-part (SOT) mandates that tile parts */
/* should appear in increasing order. */
if (l_tcp->m_current_tile_part_number + 1 != (OPJ_INT32)l_current_part) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid tile part index for tile number %d. "
"Got %d, expected %d\n",
p_j2k->m_current_tile_number,
l_current_part,
l_tcp->m_current_tile_part_number + 1);
return OPJ_FALSE;
}
++ l_tcp->m_current_tile_part_number;
#ifdef USE_JPWL
if (l_cp->correct) {
OPJ_UINT32 tileno = p_j2k->m_current_tile_number;
static OPJ_UINT32 backup_tileno = 0;
/* tileno is negative or larger than the number of tiles!!! */
if (tileno > (l_cp->tw * l_cp->th)) {
opj_event_msg(p_manager, EVT_ERROR,
"JPWL: bad tile number (%d out of a maximum of %d)\n",
tileno, (l_cp->tw * l_cp->th));
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
/* we try to correct */
tileno = backup_tileno;
opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust this\n"
"- setting tile number to %d\n",
tileno);
}
/* keep your private count of tiles */
backup_tileno++;
};
#endif /* USE_JPWL */
/* look for the tile in the list of already processed tile (in parts). */
/* Optimization possible here with a more complex data structure and with the removing of tiles */
/* since the time taken by this function can only grow at the time */
/* PSot should be equal to zero or >=14 or <= 2^32-1 */
if ((l_tot_len != 0) && (l_tot_len < 14)) {
if (l_tot_len ==
12) { /* MSD: Special case for the PHR data which are read by kakadu*/
opj_event_msg(p_manager, EVT_WARNING, "Empty SOT marker detected: Psot=%d.\n",
l_tot_len);
} else {
opj_event_msg(p_manager, EVT_ERROR,
"Psot value is not correct regards to the JPEG2000 norm: %d.\n", l_tot_len);
return OPJ_FALSE;
}
}
#ifdef USE_JPWL
if (l_cp->correct) {
/* totlen is negative or larger than the bytes left!!! */
if (/*(l_tot_len < 0) ||*/ (l_tot_len >
p_header_size)) { /* FIXME it seems correct; for info in V1 -> (p_stream_numbytesleft(p_stream) + 8))) { */
opj_event_msg(p_manager, EVT_ERROR,
"JPWL: bad tile byte size (%d bytes against %d bytes left)\n",
l_tot_len,
p_header_size); /* FIXME it seems correct; for info in V1 -> p_stream_numbytesleft(p_stream) + 8); */
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
/* we try to correct */
l_tot_len = 0;
opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust this\n"
"- setting Psot to %d => assuming it is the last tile\n",
l_tot_len);
}
};
#endif /* USE_JPWL */
/* Ref A.4.2: Psot could be equal zero if it is the last tile-part of the codestream.*/
if (!l_tot_len) {
opj_event_msg(p_manager, EVT_INFO,
"Psot value of the current tile-part is equal to zero, "
"we assuming it is the last tile-part of the codestream.\n");
p_j2k->m_specific_param.m_decoder.m_last_tile_part = 1;
}
if (l_tcp->m_nb_tile_parts != 0 && l_current_part >= l_tcp->m_nb_tile_parts) {
/* Fixes https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=2851 */
opj_event_msg(p_manager, EVT_ERROR,
"In SOT marker, TPSot (%d) is not valid regards to the previous "
"number of tile-part (%d), giving up\n", l_current_part,
l_tcp->m_nb_tile_parts);
p_j2k->m_specific_param.m_decoder.m_last_tile_part = 1;
return OPJ_FALSE;
}
if (l_num_parts !=
0) { /* Number of tile-part header is provided by this tile-part header */
l_num_parts += p_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction;
/* Useful to manage the case of textGBR.jp2 file because two values of TNSot are allowed: the correct numbers of
* tile-parts for that tile and zero (A.4.2 of 15444-1 : 2002). */
if (l_tcp->m_nb_tile_parts) {
if (l_current_part >= l_tcp->m_nb_tile_parts) {
opj_event_msg(p_manager, EVT_ERROR,
"In SOT marker, TPSot (%d) is not valid regards to the current "
"number of tile-part (%d), giving up\n", l_current_part,
l_tcp->m_nb_tile_parts);
p_j2k->m_specific_param.m_decoder.m_last_tile_part = 1;
return OPJ_FALSE;
}
}
if (l_current_part >= l_num_parts) {
/* testcase 451.pdf.SIGSEGV.ce9.3723 */
opj_event_msg(p_manager, EVT_ERROR,
"In SOT marker, TPSot (%d) is not valid regards to the current "
"number of tile-part (header) (%d), giving up\n", l_current_part, l_num_parts);
p_j2k->m_specific_param.m_decoder.m_last_tile_part = 1;
return OPJ_FALSE;
}
l_tcp->m_nb_tile_parts = l_num_parts;
}
/* If know the number of tile part header we will check if we didn't read the last*/
if (l_tcp->m_nb_tile_parts) {
if (l_tcp->m_nb_tile_parts == (l_current_part + 1)) {
p_j2k->m_specific_param.m_decoder.m_can_decode =
1; /* Process the last tile-part header*/
}
}
if (!p_j2k->m_specific_param.m_decoder.m_last_tile_part) {
/* Keep the size of data to skip after this marker */
p_j2k->m_specific_param.m_decoder.m_sot_length = l_tot_len -
12; /* SOT_marker_size = 12 */
} else {
/* FIXME: need to be computed from the number of bytes remaining in the codestream */
p_j2k->m_specific_param.m_decoder.m_sot_length = 0;
}
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPH;
/* Check if the current tile is outside the area we want decode or not corresponding to the tile index*/
if (p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec == -1) {
p_j2k->m_specific_param.m_decoder.m_skip_data =
(l_tile_x < p_j2k->m_specific_param.m_decoder.m_start_tile_x)
|| (l_tile_x >= p_j2k->m_specific_param.m_decoder.m_end_tile_x)
|| (l_tile_y < p_j2k->m_specific_param.m_decoder.m_start_tile_y)
|| (l_tile_y >= p_j2k->m_specific_param.m_decoder.m_end_tile_y);
} else {
assert(p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec >= 0);
p_j2k->m_specific_param.m_decoder.m_skip_data =
(p_j2k->m_current_tile_number != (OPJ_UINT32)
p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec);
}
/* Index */
if (p_j2k->cstr_index) {
assert(p_j2k->cstr_index->tile_index != 00);
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tileno =
p_j2k->m_current_tile_number;
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_tpsno =
l_current_part;
if (l_num_parts != 0) {
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].nb_tps =
l_num_parts;
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps =
l_num_parts;
if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index) {
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index =
(opj_tp_index_t*)opj_calloc(l_num_parts, sizeof(opj_tp_index_t));
if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to read SOT marker. Tile index allocation failed\n");
return OPJ_FALSE;
}
} else {
opj_tp_index_t *new_tp_index = (opj_tp_index_t *) opj_realloc(
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index,
l_num_parts * sizeof(opj_tp_index_t));
if (! new_tp_index) {
opj_free(p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index);
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index = NULL;
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to read SOT marker. Tile index allocation failed\n");
return OPJ_FALSE;
}
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index =
new_tp_index;
}
} else {
/*if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index)*/ {
if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index) {
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps = 10;
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index =
(opj_tp_index_t*)opj_calloc(
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps,
sizeof(opj_tp_index_t));
if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index) {
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps = 0;
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to read SOT marker. Tile index allocation failed\n");
return OPJ_FALSE;
}
}
if (l_current_part >=
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps) {
opj_tp_index_t *new_tp_index;
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps =
l_current_part + 1;
new_tp_index = (opj_tp_index_t *) opj_realloc(
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index,
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps *
sizeof(opj_tp_index_t));
if (! new_tp_index) {
opj_free(p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index);
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index = NULL;
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps = 0;
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to read SOT marker. Tile index allocation failed\n");
return OPJ_FALSE;
}
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index =
new_tp_index;
}
}
}
}
/* FIXME move this onto a separate method to call before reading any SOT, remove part about main_end header, use a index struct inside p_j2k */
/* if (p_j2k->cstr_info) {
if (l_tcp->first) {
if (tileno == 0) {
p_j2k->cstr_info->main_head_end = p_stream_tell(p_stream) - 13;
}
p_j2k->cstr_info->tile[tileno].tileno = tileno;
p_j2k->cstr_info->tile[tileno].start_pos = p_stream_tell(p_stream) - 12;
p_j2k->cstr_info->tile[tileno].end_pos = p_j2k->cstr_info->tile[tileno].start_pos + totlen - 1;
p_j2k->cstr_info->tile[tileno].num_tps = numparts;
if (numparts) {
p_j2k->cstr_info->tile[tileno].tp = (opj_tp_info_t *) opj_malloc(numparts * sizeof(opj_tp_info_t));
}
else {
p_j2k->cstr_info->tile[tileno].tp = (opj_tp_info_t *) opj_malloc(10 * sizeof(opj_tp_info_t)); // Fixme (10)
}
}
else {
p_j2k->cstr_info->tile[tileno].end_pos += totlen;
}
p_j2k->cstr_info->tile[tileno].tp[partno].tp_start_pos = p_stream_tell(p_stream) - 12;
p_j2k->cstr_info->tile[tileno].tp[partno].tp_end_pos =
p_j2k->cstr_info->tile[tileno].tp[partno].tp_start_pos + totlen - 1;
}*/
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_sod(opj_j2k_t *p_j2k,
opj_tcd_t * p_tile_coder,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_total_data_size,
const opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
opj_codestream_info_t *l_cstr_info = 00;
OPJ_UINT32 l_remaining_data;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
OPJ_UNUSED(p_stream);
opj_write_bytes(p_data, J2K_MS_SOD,
2); /* SOD */
p_data += 2;
/* make room for the EOF marker */
l_remaining_data = p_total_data_size - 4;
/* update tile coder */
p_tile_coder->tp_num =
p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number ;
p_tile_coder->cur_tp_num =
p_j2k->m_specific_param.m_encoder.m_current_tile_part_number;
/* INDEX >> */
/* TODO mergeV2: check this part which use cstr_info */
/*l_cstr_info = p_j2k->cstr_info;
if (l_cstr_info) {
if (!p_j2k->m_specific_param.m_encoder.m_current_tile_part_number ) {
//TODO cstr_info->tile[p_j2k->m_current_tile_number].end_header = p_stream_tell(p_stream) + p_j2k->pos_correction - 1;
l_cstr_info->tile[p_j2k->m_current_tile_number].tileno = p_j2k->m_current_tile_number;
}
else {*/
/*
TODO
if
(cstr_info->tile[p_j2k->m_current_tile_number].packet[cstr_info->packno - 1].end_pos < p_stream_tell(p_stream))
{
cstr_info->tile[p_j2k->m_current_tile_number].packet[cstr_info->packno].start_pos = p_stream_tell(p_stream);
}*/
/*}*/
/* UniPG>> */
#ifdef USE_JPWL
/* update markers struct */
/*OPJ_BOOL res = j2k_add_marker(p_j2k->cstr_info, J2K_MS_SOD, p_j2k->sod_start, 2);
*/
assert(0 && "TODO");
#endif /* USE_JPWL */
/* <<UniPG */
/*}*/
/* << INDEX */
if (p_j2k->m_specific_param.m_encoder.m_current_tile_part_number == 0) {
p_tile_coder->tcd_image->tiles->packno = 0;
if (l_cstr_info) {
l_cstr_info->packno = 0;
}
}
*p_data_written = 0;
if (! opj_tcd_encode_tile(p_tile_coder, p_j2k->m_current_tile_number, p_data,
p_data_written, l_remaining_data, l_cstr_info,
p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Cannot encode tile\n");
return OPJ_FALSE;
}
*p_data_written += 2;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_read_sod(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_SIZE_T l_current_read_size;
opj_codestream_index_t * l_cstr_index = 00;
OPJ_BYTE ** l_current_data = 00;
opj_tcp_t * l_tcp = 00;
OPJ_UINT32 * l_tile_len = 00;
OPJ_BOOL l_sot_length_pb_detected = OPJ_FALSE;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_tcp = &(p_j2k->m_cp.tcps[p_j2k->m_current_tile_number]);
if (p_j2k->m_specific_param.m_decoder.m_last_tile_part) {
/* opj_stream_get_number_byte_left returns OPJ_OFF_T
// but we are in the last tile part,
// so its result will fit on OPJ_UINT32 unless we find
// a file with a single tile part of more than 4 GB...*/
p_j2k->m_specific_param.m_decoder.m_sot_length = (OPJ_UINT32)(
opj_stream_get_number_byte_left(p_stream) - 2);
} else {
/* Check to avoid pass the limit of OPJ_UINT32 */
if (p_j2k->m_specific_param.m_decoder.m_sot_length >= 2) {
p_j2k->m_specific_param.m_decoder.m_sot_length -= 2;
} else {
/* MSD: case commented to support empty SOT marker (PHR data) */
}
}
l_current_data = &(l_tcp->m_data);
l_tile_len = &l_tcp->m_data_size;
/* Patch to support new PHR data */
if (p_j2k->m_specific_param.m_decoder.m_sot_length) {
/* If we are here, we'll try to read the data after allocation */
/* Check enough bytes left in stream before allocation */
if ((OPJ_OFF_T)p_j2k->m_specific_param.m_decoder.m_sot_length >
opj_stream_get_number_byte_left(p_stream)) {
opj_event_msg(p_manager, EVT_ERROR,
"Tile part length size inconsistent with stream length\n");
return OPJ_FALSE;
}
if (p_j2k->m_specific_param.m_decoder.m_sot_length >
UINT_MAX - OPJ_COMMON_CBLK_DATA_EXTRA) {
opj_event_msg(p_manager, EVT_ERROR,
"p_j2k->m_specific_param.m_decoder.m_sot_length > "
"UINT_MAX - OPJ_COMMON_CBLK_DATA_EXTRA");
return OPJ_FALSE;
}
/* Add a margin of OPJ_COMMON_CBLK_DATA_EXTRA to the allocation we */
/* do so that opj_mqc_init_dec_common() can safely add a synthetic */
/* 0xFFFF marker. */
if (! *l_current_data) {
/* LH: oddly enough, in this path, l_tile_len!=0.
* TODO: If this was consistent, we could simplify the code to only use realloc(), as realloc(0,...) default to malloc(0,...).
*/
*l_current_data = (OPJ_BYTE*) opj_malloc(
p_j2k->m_specific_param.m_decoder.m_sot_length + OPJ_COMMON_CBLK_DATA_EXTRA);
} else {
OPJ_BYTE *l_new_current_data;
if (*l_tile_len > UINT_MAX - OPJ_COMMON_CBLK_DATA_EXTRA -
p_j2k->m_specific_param.m_decoder.m_sot_length) {
opj_event_msg(p_manager, EVT_ERROR,
"*l_tile_len > UINT_MAX - OPJ_COMMON_CBLK_DATA_EXTRA - "
"p_j2k->m_specific_param.m_decoder.m_sot_length");
return OPJ_FALSE;
}
l_new_current_data = (OPJ_BYTE *) opj_realloc(*l_current_data,
*l_tile_len + p_j2k->m_specific_param.m_decoder.m_sot_length +
OPJ_COMMON_CBLK_DATA_EXTRA);
if (! l_new_current_data) {
opj_free(*l_current_data);
/*nothing more is done as l_current_data will be set to null, and just
afterward we enter in the error path
and the actual tile_len is updated (committed) at the end of the
function. */
}
*l_current_data = l_new_current_data;
}
if (*l_current_data == 00) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to decode tile\n");
return OPJ_FALSE;
}
} else {
l_sot_length_pb_detected = OPJ_TRUE;
}
/* Index */
l_cstr_index = p_j2k->cstr_index;
if (l_cstr_index) {
OPJ_OFF_T l_current_pos = opj_stream_tell(p_stream) - 2;
OPJ_UINT32 l_current_tile_part =
l_cstr_index->tile_index[p_j2k->m_current_tile_number].current_tpsno;
l_cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index[l_current_tile_part].end_header
=
l_current_pos;
l_cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index[l_current_tile_part].end_pos
=
l_current_pos + p_j2k->m_specific_param.m_decoder.m_sot_length + 2;
if (OPJ_FALSE == opj_j2k_add_tlmarker(p_j2k->m_current_tile_number,
l_cstr_index,
J2K_MS_SOD,
l_current_pos,
p_j2k->m_specific_param.m_decoder.m_sot_length + 2)) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add tl marker\n");
return OPJ_FALSE;
}
/*l_cstr_index->packno = 0;*/
}
/* Patch to support new PHR data */
if (!l_sot_length_pb_detected) {
l_current_read_size = opj_stream_read_data(
p_stream,
*l_current_data + *l_tile_len,
p_j2k->m_specific_param.m_decoder.m_sot_length,
p_manager);
} else {
l_current_read_size = 0;
}
if (l_current_read_size != p_j2k->m_specific_param.m_decoder.m_sot_length) {
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_NEOC;
} else {
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPHSOT;
}
*l_tile_len += (OPJ_UINT32)l_current_read_size;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_rgn(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no,
OPJ_UINT32 nb_comps,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_BYTE * l_current_data = 00;
OPJ_UINT32 l_rgn_size;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_tccp_t *l_tccp = 00;
OPJ_UINT32 l_comp_room;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_tile_no];
l_tccp = &l_tcp->tccps[p_comp_no];
if (nb_comps <= 256) {
l_comp_room = 1;
} else {
l_comp_room = 2;
}
l_rgn_size = 6 + l_comp_room;
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_data, J2K_MS_RGN,
2); /* RGN */
l_current_data += 2;
opj_write_bytes(l_current_data, l_rgn_size - 2,
2); /* Lrgn */
l_current_data += 2;
opj_write_bytes(l_current_data, p_comp_no,
l_comp_room); /* Crgn */
l_current_data += l_comp_room;
opj_write_bytes(l_current_data, 0,
1); /* Srgn */
++l_current_data;
opj_write_bytes(l_current_data, (OPJ_UINT32)l_tccp->roishift,
1); /* SPrgn */
++l_current_data;
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_rgn_size,
p_manager) != l_rgn_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_eoc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
opj_write_bytes(p_j2k->m_specific_param.m_encoder.m_header_tile_data,
J2K_MS_EOC, 2); /* EOC */
/* UniPG>> */
#ifdef USE_JPWL
/* update markers struct */
/*
OPJ_BOOL res = j2k_add_marker(p_j2k->cstr_info, J2K_MS_EOC, p_stream_tell(p_stream) - 2, 2);
*/
#endif /* USE_JPWL */
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, 2, p_manager) != 2) {
return OPJ_FALSE;
}
if (! opj_stream_flush(p_stream, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a RGN marker (Region Of Interest)
*
* @param p_header_data the data contained in the POC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the POC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_rgn(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_nb_comp;
opj_image_t * l_image = 00;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
OPJ_UINT32 l_comp_room, l_comp_no, l_roi_sty;
/* preconditions*/
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_image = p_j2k->m_private_image;
l_nb_comp = l_image->numcomps;
if (l_nb_comp <= 256) {
l_comp_room = 1;
} else {
l_comp_room = 2;
}
if (p_header_size != 2 + l_comp_room) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading RGN marker\n");
return OPJ_FALSE;
}
l_cp = &(p_j2k->m_cp);
l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
opj_read_bytes(p_header_data, &l_comp_no, l_comp_room); /* Crgn */
p_header_data += l_comp_room;
opj_read_bytes(p_header_data, &l_roi_sty,
1); /* Srgn */
++p_header_data;
#ifdef USE_JPWL
if (l_cp->correct) {
/* totlen is negative or larger than the bytes left!!! */
if (l_comp_room >= l_nb_comp) {
opj_event_msg(p_manager, EVT_ERROR,
"JPWL: bad component number in RGN (%d when there are only %d)\n",
l_comp_room, l_nb_comp);
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
}
};
#endif /* USE_JPWL */
/* testcase 3635.pdf.asan.77.2930 */
if (l_comp_no >= l_nb_comp) {
opj_event_msg(p_manager, EVT_ERROR,
"bad component number in RGN (%d when there are only %d)\n",
l_comp_no, l_nb_comp);
return OPJ_FALSE;
}
opj_read_bytes(p_header_data,
(OPJ_UINT32 *)(&(l_tcp->tccps[l_comp_no].roishift)), 1); /* SPrgn */
++p_header_data;
return OPJ_TRUE;
}
static OPJ_FLOAT32 opj_j2k_get_tp_stride(opj_tcp_t * p_tcp)
{
return (OPJ_FLOAT32)((p_tcp->m_nb_tile_parts - 1) * 14);
}
static OPJ_FLOAT32 opj_j2k_get_default_stride(opj_tcp_t * p_tcp)
{
(void)p_tcp;
return 0;
}
static OPJ_BOOL opj_j2k_update_rates(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
opj_cp_t * l_cp = 00;
opj_image_t * l_image = 00;
opj_tcp_t * l_tcp = 00;
opj_image_comp_t * l_img_comp = 00;
OPJ_UINT32 i, j, k;
OPJ_INT32 l_x0, l_y0, l_x1, l_y1;
OPJ_FLOAT32 * l_rates = 0;
OPJ_FLOAT32 l_sot_remove;
OPJ_UINT32 l_bits_empty, l_size_pixel;
OPJ_UINT32 l_tile_size = 0;
OPJ_UINT32 l_last_res;
OPJ_FLOAT32(* l_tp_stride_func)(opj_tcp_t *) = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
OPJ_UNUSED(p_manager);
l_cp = &(p_j2k->m_cp);
l_image = p_j2k->m_private_image;
l_tcp = l_cp->tcps;
l_bits_empty = 8 * l_image->comps->dx * l_image->comps->dy;
l_size_pixel = l_image->numcomps * l_image->comps->prec;
l_sot_remove = (OPJ_FLOAT32) opj_stream_tell(p_stream) / (OPJ_FLOAT32)(
l_cp->th * l_cp->tw);
if (l_cp->m_specific_param.m_enc.m_tp_on) {
l_tp_stride_func = opj_j2k_get_tp_stride;
} else {
l_tp_stride_func = opj_j2k_get_default_stride;
}
for (i = 0; i < l_cp->th; ++i) {
for (j = 0; j < l_cp->tw; ++j) {
OPJ_FLOAT32 l_offset = (OPJ_FLOAT32)(*l_tp_stride_func)(l_tcp) /
(OPJ_FLOAT32)l_tcp->numlayers;
/* 4 borders of the tile rescale on the image if necessary */
l_x0 = opj_int_max((OPJ_INT32)(l_cp->tx0 + j * l_cp->tdx),
(OPJ_INT32)l_image->x0);
l_y0 = opj_int_max((OPJ_INT32)(l_cp->ty0 + i * l_cp->tdy),
(OPJ_INT32)l_image->y0);
l_x1 = opj_int_min((OPJ_INT32)(l_cp->tx0 + (j + 1) * l_cp->tdx),
(OPJ_INT32)l_image->x1);
l_y1 = opj_int_min((OPJ_INT32)(l_cp->ty0 + (i + 1) * l_cp->tdy),
(OPJ_INT32)l_image->y1);
l_rates = l_tcp->rates;
/* Modification of the RATE >> */
if (*l_rates > 0.0f) {
*l_rates = (((OPJ_FLOAT32)(l_size_pixel * (OPJ_UINT32)(l_x1 - l_x0) *
(OPJ_UINT32)(l_y1 - l_y0)))
/
((*l_rates) * (OPJ_FLOAT32)l_bits_empty)
)
-
l_offset;
}
++l_rates;
for (k = 1; k < l_tcp->numlayers; ++k) {
if (*l_rates > 0.0f) {
*l_rates = (((OPJ_FLOAT32)(l_size_pixel * (OPJ_UINT32)(l_x1 - l_x0) *
(OPJ_UINT32)(l_y1 - l_y0)))
/
((*l_rates) * (OPJ_FLOAT32)l_bits_empty)
)
-
l_offset;
}
++l_rates;
}
++l_tcp;
}
}
l_tcp = l_cp->tcps;
for (i = 0; i < l_cp->th; ++i) {
for (j = 0; j < l_cp->tw; ++j) {
l_rates = l_tcp->rates;
if (*l_rates > 0.0f) {
*l_rates -= l_sot_remove;
if (*l_rates < 30.0f) {
*l_rates = 30.0f;
}
}
++l_rates;
l_last_res = l_tcp->numlayers - 1;
for (k = 1; k < l_last_res; ++k) {
if (*l_rates > 0.0f) {
*l_rates -= l_sot_remove;
if (*l_rates < * (l_rates - 1) + 10.0f) {
*l_rates = (*(l_rates - 1)) + 20.0f;
}
}
++l_rates;
}
if (*l_rates > 0.0f) {
*l_rates -= (l_sot_remove + 2.f);
if (*l_rates < * (l_rates - 1) + 10.0f) {
*l_rates = (*(l_rates - 1)) + 20.0f;
}
}
++l_tcp;
}
}
l_img_comp = l_image->comps;
l_tile_size = 0;
for (i = 0; i < l_image->numcomps; ++i) {
l_tile_size += (opj_uint_ceildiv(l_cp->tdx, l_img_comp->dx)
*
opj_uint_ceildiv(l_cp->tdy, l_img_comp->dy)
*
l_img_comp->prec
);
++l_img_comp;
}
l_tile_size = (OPJ_UINT32)(l_tile_size * 0.1625); /* 1.3/8 = 0.1625 */
l_tile_size += opj_j2k_get_specific_header_sizes(p_j2k);
p_j2k->m_specific_param.m_encoder.m_encoded_tile_size = l_tile_size;
p_j2k->m_specific_param.m_encoder.m_encoded_tile_data =
(OPJ_BYTE *) opj_malloc(p_j2k->m_specific_param.m_encoder.m_encoded_tile_size);
if (p_j2k->m_specific_param.m_encoder.m_encoded_tile_data == 00) {
return OPJ_FALSE;
}
if (OPJ_IS_CINEMA(l_cp->rsiz)) {
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer =
(OPJ_BYTE *) opj_malloc(5 *
p_j2k->m_specific_param.m_encoder.m_total_tile_parts);
if (! p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer) {
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current =
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer;
}
return OPJ_TRUE;
}
#if 0
static OPJ_BOOL opj_j2k_read_eoc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 i;
opj_tcd_t * l_tcd = 00;
OPJ_UINT32 l_nb_tiles;
opj_tcp_t * l_tcp = 00;
OPJ_BOOL l_success;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
l_tcp = p_j2k->m_cp.tcps;
l_tcd = opj_tcd_create(OPJ_TRUE);
if (l_tcd == 00) {
opj_event_msg(p_manager, EVT_ERROR, "Cannot decode tile, memory error\n");
return OPJ_FALSE;
}
for (i = 0; i < l_nb_tiles; ++i) {
if (l_tcp->m_data) {
if (! opj_tcd_init_decode_tile(l_tcd, i)) {
opj_tcd_destroy(l_tcd);
opj_event_msg(p_manager, EVT_ERROR, "Cannot decode tile, memory error\n");
return OPJ_FALSE;
}
l_success = opj_tcd_decode_tile(l_tcd, l_tcp->m_data, l_tcp->m_data_size, i,
p_j2k->cstr_index);
/* cleanup */
if (! l_success) {
p_j2k->m_specific_param.m_decoder.m_state |= J2K_STATE_ERR;
break;
}
}
opj_j2k_tcp_destroy(l_tcp);
++l_tcp;
}
opj_tcd_destroy(l_tcd);
return OPJ_TRUE;
}
#endif
static OPJ_BOOL opj_j2k_get_end_header(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
OPJ_UNUSED(p_manager);
p_j2k->cstr_index->main_head_end = opj_stream_tell(p_stream);
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_mct_data_group(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 i;
opj_simple_mcc_decorrelation_data_t * l_mcc_record;
opj_mct_data_t * l_mct_record;
opj_tcp_t * l_tcp;
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
if (! opj_j2k_write_cbd(p_j2k, p_stream, p_manager)) {
return OPJ_FALSE;
}
l_tcp = &(p_j2k->m_cp.tcps[p_j2k->m_current_tile_number]);
l_mct_record = l_tcp->m_mct_records;
for (i = 0; i < l_tcp->m_nb_mct_records; ++i) {
if (! opj_j2k_write_mct_record(p_j2k, l_mct_record, p_stream, p_manager)) {
return OPJ_FALSE;
}
++l_mct_record;
}
l_mcc_record = l_tcp->m_mcc_records;
for (i = 0; i < l_tcp->m_nb_mcc_records; ++i) {
if (! opj_j2k_write_mcc_record(p_j2k, l_mcc_record, p_stream, p_manager)) {
return OPJ_FALSE;
}
++l_mcc_record;
}
if (! opj_j2k_write_mco(p_j2k, p_stream, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_all_coc(
opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 compno;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
for (compno = 1; compno < p_j2k->m_private_image->numcomps; ++compno) {
/* cod is first component of first tile */
if (! opj_j2k_compare_coc(p_j2k, 0, compno)) {
if (! opj_j2k_write_coc(p_j2k, compno, p_stream, p_manager)) {
return OPJ_FALSE;
}
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_all_qcc(
opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 compno;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
for (compno = 1; compno < p_j2k->m_private_image->numcomps; ++compno) {
/* qcd is first component of first tile */
if (! opj_j2k_compare_qcc(p_j2k, 0, compno)) {
if (! opj_j2k_write_qcc(p_j2k, compno, p_stream, p_manager)) {
return OPJ_FALSE;
}
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_regions(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 compno;
const opj_tccp_t *l_tccp = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_tccp = p_j2k->m_cp.tcps->tccps;
for (compno = 0; compno < p_j2k->m_private_image->numcomps; ++compno) {
if (l_tccp->roishift) {
if (! opj_j2k_write_rgn(p_j2k, 0, compno, p_j2k->m_private_image->numcomps,
p_stream, p_manager)) {
return OPJ_FALSE;
}
}
++l_tccp;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_epc(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
opj_codestream_index_t * l_cstr_index = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
OPJ_UNUSED(p_manager);
l_cstr_index = p_j2k->cstr_index;
if (l_cstr_index) {
l_cstr_index->codestream_size = (OPJ_UINT64)opj_stream_tell(p_stream);
/* UniPG>> */
/* The following adjustment is done to adjust the codestream size */
/* if SOD is not at 0 in the buffer. Useful in case of JP2, where */
/* the first bunch of bytes is not in the codestream */
l_cstr_index->codestream_size -= (OPJ_UINT64)l_cstr_index->main_head_start;
/* <<UniPG */
}
#ifdef USE_JPWL
/* preparation of JPWL marker segments */
#if 0
if (cp->epc_on) {
/* encode according to JPWL */
jpwl_encode(p_j2k, p_stream, image);
}
#endif
assert(0 && "TODO");
#endif /* USE_JPWL */
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_read_unk(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
OPJ_UINT32 *output_marker,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_unknown_marker;
const opj_dec_memory_marker_handler_t * l_marker_handler;
OPJ_UINT32 l_size_unk = 2;
/* preconditions*/
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
opj_event_msg(p_manager, EVT_WARNING, "Unknown marker\n");
for (;;) {
/* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer*/
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* read 2 bytes as the new marker ID*/
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,
&l_unknown_marker, 2);
if (!(l_unknown_marker < 0xff00)) {
/* Get the marker handler from the marker ID*/
l_marker_handler = opj_j2k_get_marker_handler(l_unknown_marker);
if (!(p_j2k->m_specific_param.m_decoder.m_state & l_marker_handler->states)) {
opj_event_msg(p_manager, EVT_ERROR,
"Marker is not compliant with its position\n");
return OPJ_FALSE;
} else {
if (l_marker_handler->id != J2K_MS_UNK) {
/* Add the marker to the codestream index*/
if (l_marker_handler->id != J2K_MS_SOT) {
OPJ_BOOL res = opj_j2k_add_mhmarker(p_j2k->cstr_index, J2K_MS_UNK,
(OPJ_UINT32) opj_stream_tell(p_stream) - l_size_unk,
l_size_unk);
if (res == OPJ_FALSE) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add mh marker\n");
return OPJ_FALSE;
}
}
break; /* next marker is known and well located */
} else {
l_size_unk += 2;
}
}
}
}
*output_marker = l_marker_handler->id ;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_mct_record(opj_j2k_t *p_j2k,
opj_mct_data_t * p_mct_record,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 l_mct_size;
OPJ_BYTE * l_current_data = 00;
OPJ_UINT32 l_tmp;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_mct_size = 10 + p_mct_record->m_data_size;
if (l_mct_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mct_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write MCT marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_mct_size;
}
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_data, J2K_MS_MCT,
2); /* MCT */
l_current_data += 2;
opj_write_bytes(l_current_data, l_mct_size - 2,
2); /* Lmct */
l_current_data += 2;
opj_write_bytes(l_current_data, 0,
2); /* Zmct */
l_current_data += 2;
/* only one marker atm */
l_tmp = (p_mct_record->m_index & 0xff) | (p_mct_record->m_array_type << 8) |
(p_mct_record->m_element_type << 10);
opj_write_bytes(l_current_data, l_tmp, 2);
l_current_data += 2;
opj_write_bytes(l_current_data, 0,
2); /* Ymct */
l_current_data += 2;
memcpy(l_current_data, p_mct_record->m_data, p_mct_record->m_data_size);
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mct_size,
p_manager) != l_mct_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a MCT marker (Multiple Component Transform)
*
* @param p_header_data the data contained in the MCT box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the MCT marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_mct(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 i;
opj_tcp_t *l_tcp = 00;
OPJ_UINT32 l_tmp;
OPJ_UINT32 l_indix;
opj_mct_data_t * l_mct_data;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
l_tcp = p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH ?
&p_j2k->m_cp.tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
if (p_header_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCT marker\n");
return OPJ_FALSE;
}
/* first marker */
opj_read_bytes(p_header_data, &l_tmp, 2); /* Zmct */
p_header_data += 2;
if (l_tmp != 0) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge mct data within multiple MCT records\n");
return OPJ_TRUE;
}
if (p_header_size <= 6) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCT marker\n");
return OPJ_FALSE;
}
/* Imct -> no need for other values, take the first, type is double with decorrelation x0000 1101 0000 0000*/
opj_read_bytes(p_header_data, &l_tmp, 2); /* Imct */
p_header_data += 2;
l_indix = l_tmp & 0xff;
l_mct_data = l_tcp->m_mct_records;
for (i = 0; i < l_tcp->m_nb_mct_records; ++i) {
if (l_mct_data->m_index == l_indix) {
break;
}
++l_mct_data;
}
/* NOT FOUND */
if (i == l_tcp->m_nb_mct_records) {
if (l_tcp->m_nb_mct_records == l_tcp->m_nb_max_mct_records) {
opj_mct_data_t *new_mct_records;
l_tcp->m_nb_max_mct_records += OPJ_J2K_MCT_DEFAULT_NB_RECORDS;
new_mct_records = (opj_mct_data_t *) opj_realloc(l_tcp->m_mct_records,
l_tcp->m_nb_max_mct_records * sizeof(opj_mct_data_t));
if (! new_mct_records) {
opj_free(l_tcp->m_mct_records);
l_tcp->m_mct_records = NULL;
l_tcp->m_nb_max_mct_records = 0;
l_tcp->m_nb_mct_records = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read MCT marker\n");
return OPJ_FALSE;
}
/* Update m_mcc_records[].m_offset_array and m_decorrelation_array
* to point to the new addresses */
if (new_mct_records != l_tcp->m_mct_records) {
for (i = 0; i < l_tcp->m_nb_mcc_records; ++i) {
opj_simple_mcc_decorrelation_data_t* l_mcc_record =
&(l_tcp->m_mcc_records[i]);
if (l_mcc_record->m_decorrelation_array) {
l_mcc_record->m_decorrelation_array =
new_mct_records +
(l_mcc_record->m_decorrelation_array -
l_tcp->m_mct_records);
}
if (l_mcc_record->m_offset_array) {
l_mcc_record->m_offset_array =
new_mct_records +
(l_mcc_record->m_offset_array -
l_tcp->m_mct_records);
}
}
}
l_tcp->m_mct_records = new_mct_records;
l_mct_data = l_tcp->m_mct_records + l_tcp->m_nb_mct_records;
memset(l_mct_data, 0, (l_tcp->m_nb_max_mct_records - l_tcp->m_nb_mct_records) *
sizeof(opj_mct_data_t));
}
l_mct_data = l_tcp->m_mct_records + l_tcp->m_nb_mct_records;
++l_tcp->m_nb_mct_records;
}
if (l_mct_data->m_data) {
opj_free(l_mct_data->m_data);
l_mct_data->m_data = 00;
l_mct_data->m_data_size = 0;
}
l_mct_data->m_index = l_indix;
l_mct_data->m_array_type = (J2K_MCT_ARRAY_TYPE)((l_tmp >> 8) & 3);
l_mct_data->m_element_type = (J2K_MCT_ELEMENT_TYPE)((l_tmp >> 10) & 3);
opj_read_bytes(p_header_data, &l_tmp, 2); /* Ymct */
p_header_data += 2;
if (l_tmp != 0) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge multiple MCT markers\n");
return OPJ_TRUE;
}
p_header_size -= 6;
l_mct_data->m_data = (OPJ_BYTE*)opj_malloc(p_header_size);
if (! l_mct_data->m_data) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCT marker\n");
return OPJ_FALSE;
}
memcpy(l_mct_data->m_data, p_header_data, p_header_size);
l_mct_data->m_data_size = p_header_size;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_mcc_record(opj_j2k_t *p_j2k,
struct opj_simple_mcc_decorrelation_data * p_mcc_record,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 i;
OPJ_UINT32 l_mcc_size;
OPJ_BYTE * l_current_data = 00;
OPJ_UINT32 l_nb_bytes_for_comp;
OPJ_UINT32 l_mask;
OPJ_UINT32 l_tmcc;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
if (p_mcc_record->m_nb_comps > 255) {
l_nb_bytes_for_comp = 2;
l_mask = 0x8000;
} else {
l_nb_bytes_for_comp = 1;
l_mask = 0;
}
l_mcc_size = p_mcc_record->m_nb_comps * 2 * l_nb_bytes_for_comp + 19;
if (l_mcc_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mcc_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write MCC marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_mcc_size;
}
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_data, J2K_MS_MCC,
2); /* MCC */
l_current_data += 2;
opj_write_bytes(l_current_data, l_mcc_size - 2,
2); /* Lmcc */
l_current_data += 2;
/* first marker */
opj_write_bytes(l_current_data, 0,
2); /* Zmcc */
l_current_data += 2;
opj_write_bytes(l_current_data, p_mcc_record->m_index,
1); /* Imcc -> no need for other values, take the first */
++l_current_data;
/* only one marker atm */
opj_write_bytes(l_current_data, 0,
2); /* Ymcc */
l_current_data += 2;
opj_write_bytes(l_current_data, 1,
2); /* Qmcc -> number of collections -> 1 */
l_current_data += 2;
opj_write_bytes(l_current_data, 0x1,
1); /* Xmcci type of component transformation -> array based decorrelation */
++l_current_data;
opj_write_bytes(l_current_data, p_mcc_record->m_nb_comps | l_mask,
2); /* Nmcci number of input components involved and size for each component offset = 8 bits */
l_current_data += 2;
for (i = 0; i < p_mcc_record->m_nb_comps; ++i) {
opj_write_bytes(l_current_data, i,
l_nb_bytes_for_comp); /* Cmccij Component offset*/
l_current_data += l_nb_bytes_for_comp;
}
opj_write_bytes(l_current_data, p_mcc_record->m_nb_comps | l_mask,
2); /* Mmcci number of output components involved and size for each component offset = 8 bits */
l_current_data += 2;
for (i = 0; i < p_mcc_record->m_nb_comps; ++i) {
opj_write_bytes(l_current_data, i,
l_nb_bytes_for_comp); /* Wmccij Component offset*/
l_current_data += l_nb_bytes_for_comp;
}
l_tmcc = ((!p_mcc_record->m_is_irreversible) & 1U) << 16;
if (p_mcc_record->m_decorrelation_array) {
l_tmcc |= p_mcc_record->m_decorrelation_array->m_index;
}
if (p_mcc_record->m_offset_array) {
l_tmcc |= ((p_mcc_record->m_offset_array->m_index) << 8);
}
opj_write_bytes(l_current_data, l_tmcc,
3); /* Tmcci : use MCT defined as number 1 and irreversible array based. */
l_current_data += 3;
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mcc_size,
p_manager) != l_mcc_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_read_mcc(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 i, j;
OPJ_UINT32 l_tmp;
OPJ_UINT32 l_indix;
opj_tcp_t * l_tcp;
opj_simple_mcc_decorrelation_data_t * l_mcc_record;
opj_mct_data_t * l_mct_data;
OPJ_UINT32 l_nb_collections;
OPJ_UINT32 l_nb_comps;
OPJ_UINT32 l_nb_bytes_by_comp;
OPJ_BOOL l_new_mcc = OPJ_FALSE;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_tcp = p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH ?
&p_j2k->m_cp.tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
if (p_header_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
/* first marker */
opj_read_bytes(p_header_data, &l_tmp, 2); /* Zmcc */
p_header_data += 2;
if (l_tmp != 0) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge multiple data spanning\n");
return OPJ_TRUE;
}
if (p_header_size < 7) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_indix,
1); /* Imcc -> no need for other values, take the first */
++p_header_data;
l_mcc_record = l_tcp->m_mcc_records;
for (i = 0; i < l_tcp->m_nb_mcc_records; ++i) {
if (l_mcc_record->m_index == l_indix) {
break;
}
++l_mcc_record;
}
/** NOT FOUND */
if (i == l_tcp->m_nb_mcc_records) {
if (l_tcp->m_nb_mcc_records == l_tcp->m_nb_max_mcc_records) {
opj_simple_mcc_decorrelation_data_t *new_mcc_records;
l_tcp->m_nb_max_mcc_records += OPJ_J2K_MCC_DEFAULT_NB_RECORDS;
new_mcc_records = (opj_simple_mcc_decorrelation_data_t *) opj_realloc(
l_tcp->m_mcc_records, l_tcp->m_nb_max_mcc_records * sizeof(
opj_simple_mcc_decorrelation_data_t));
if (! new_mcc_records) {
opj_free(l_tcp->m_mcc_records);
l_tcp->m_mcc_records = NULL;
l_tcp->m_nb_max_mcc_records = 0;
l_tcp->m_nb_mcc_records = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read MCC marker\n");
return OPJ_FALSE;
}
l_tcp->m_mcc_records = new_mcc_records;
l_mcc_record = l_tcp->m_mcc_records + l_tcp->m_nb_mcc_records;
memset(l_mcc_record, 0, (l_tcp->m_nb_max_mcc_records - l_tcp->m_nb_mcc_records)
* sizeof(opj_simple_mcc_decorrelation_data_t));
}
l_mcc_record = l_tcp->m_mcc_records + l_tcp->m_nb_mcc_records;
l_new_mcc = OPJ_TRUE;
}
l_mcc_record->m_index = l_indix;
/* only one marker atm */
opj_read_bytes(p_header_data, &l_tmp, 2); /* Ymcc */
p_header_data += 2;
if (l_tmp != 0) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge multiple data spanning\n");
return OPJ_TRUE;
}
opj_read_bytes(p_header_data, &l_nb_collections,
2); /* Qmcc -> number of collections -> 1 */
p_header_data += 2;
if (l_nb_collections > 1) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge multiple collections\n");
return OPJ_TRUE;
}
p_header_size -= 7;
for (i = 0; i < l_nb_collections; ++i) {
if (p_header_size < 3) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_tmp,
1); /* Xmcci type of component transformation -> array based decorrelation */
++p_header_data;
if (l_tmp != 1) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge collections other than array decorrelation\n");
return OPJ_TRUE;
}
opj_read_bytes(p_header_data, &l_nb_comps, 2);
p_header_data += 2;
p_header_size -= 3;
l_nb_bytes_by_comp = 1 + (l_nb_comps >> 15);
l_mcc_record->m_nb_comps = l_nb_comps & 0x7fff;
if (p_header_size < (l_nb_bytes_by_comp * l_mcc_record->m_nb_comps + 2)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
p_header_size -= (l_nb_bytes_by_comp * l_mcc_record->m_nb_comps + 2);
for (j = 0; j < l_mcc_record->m_nb_comps; ++j) {
opj_read_bytes(p_header_data, &l_tmp,
l_nb_bytes_by_comp); /* Cmccij Component offset*/
p_header_data += l_nb_bytes_by_comp;
if (l_tmp != j) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge collections with indix shuffle\n");
return OPJ_TRUE;
}
}
opj_read_bytes(p_header_data, &l_nb_comps, 2);
p_header_data += 2;
l_nb_bytes_by_comp = 1 + (l_nb_comps >> 15);
l_nb_comps &= 0x7fff;
if (l_nb_comps != l_mcc_record->m_nb_comps) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge collections without same number of indixes\n");
return OPJ_TRUE;
}
if (p_header_size < (l_nb_bytes_by_comp * l_mcc_record->m_nb_comps + 3)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
p_header_size -= (l_nb_bytes_by_comp * l_mcc_record->m_nb_comps + 3);
for (j = 0; j < l_mcc_record->m_nb_comps; ++j) {
opj_read_bytes(p_header_data, &l_tmp,
l_nb_bytes_by_comp); /* Wmccij Component offset*/
p_header_data += l_nb_bytes_by_comp;
if (l_tmp != j) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge collections with indix shuffle\n");
return OPJ_TRUE;
}
}
opj_read_bytes(p_header_data, &l_tmp, 3); /* Wmccij Component offset*/
p_header_data += 3;
l_mcc_record->m_is_irreversible = !((l_tmp >> 16) & 1);
l_mcc_record->m_decorrelation_array = 00;
l_mcc_record->m_offset_array = 00;
l_indix = l_tmp & 0xff;
if (l_indix != 0) {
l_mct_data = l_tcp->m_mct_records;
for (j = 0; j < l_tcp->m_nb_mct_records; ++j) {
if (l_mct_data->m_index == l_indix) {
l_mcc_record->m_decorrelation_array = l_mct_data;
break;
}
++l_mct_data;
}
if (l_mcc_record->m_decorrelation_array == 00) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
}
l_indix = (l_tmp >> 8) & 0xff;
if (l_indix != 0) {
l_mct_data = l_tcp->m_mct_records;
for (j = 0; j < l_tcp->m_nb_mct_records; ++j) {
if (l_mct_data->m_index == l_indix) {
l_mcc_record->m_offset_array = l_mct_data;
break;
}
++l_mct_data;
}
if (l_mcc_record->m_offset_array == 00) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
}
}
if (p_header_size != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
if (l_new_mcc) {
++l_tcp->m_nb_mcc_records;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_mco(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager
)
{
OPJ_BYTE * l_current_data = 00;
OPJ_UINT32 l_mco_size;
opj_tcp_t * l_tcp = 00;
opj_simple_mcc_decorrelation_data_t * l_mcc_record;
OPJ_UINT32 i;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_tcp = &(p_j2k->m_cp.tcps[p_j2k->m_current_tile_number]);
l_mco_size = 5 + l_tcp->m_nb_mcc_records;
if (l_mco_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mco_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write MCO marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_mco_size;
}
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_data, J2K_MS_MCO, 2); /* MCO */
l_current_data += 2;
opj_write_bytes(l_current_data, l_mco_size - 2, 2); /* Lmco */
l_current_data += 2;
opj_write_bytes(l_current_data, l_tcp->m_nb_mcc_records,
1); /* Nmco : only one transform stage*/
++l_current_data;
l_mcc_record = l_tcp->m_mcc_records;
for (i = 0; i < l_tcp->m_nb_mcc_records; ++i) {
opj_write_bytes(l_current_data, l_mcc_record->m_index,
1); /* Imco -> use the mcc indicated by 1*/
++l_current_data;
++l_mcc_record;
}
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mco_size,
p_manager) != l_mco_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a MCO marker (Multiple Component Transform Ordering)
*
* @param p_header_data the data contained in the MCO box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the MCO marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_mco(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_tmp, i;
OPJ_UINT32 l_nb_stages;
opj_tcp_t * l_tcp;
opj_tccp_t * l_tccp;
opj_image_t * l_image;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_image = p_j2k->m_private_image;
l_tcp = p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH ?
&p_j2k->m_cp.tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
if (p_header_size < 1) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCO marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_nb_stages,
1); /* Nmco : only one transform stage*/
++p_header_data;
if (l_nb_stages > 1) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge multiple transformation stages.\n");
return OPJ_TRUE;
}
if (p_header_size != l_nb_stages + 1) {
opj_event_msg(p_manager, EVT_WARNING, "Error reading MCO marker\n");
return OPJ_FALSE;
}
l_tccp = l_tcp->tccps;
for (i = 0; i < l_image->numcomps; ++i) {
l_tccp->m_dc_level_shift = 0;
++l_tccp;
}
if (l_tcp->m_mct_decoding_matrix) {
opj_free(l_tcp->m_mct_decoding_matrix);
l_tcp->m_mct_decoding_matrix = 00;
}
for (i = 0; i < l_nb_stages; ++i) {
opj_read_bytes(p_header_data, &l_tmp, 1);
++p_header_data;
if (! opj_j2k_add_mct(l_tcp, p_j2k->m_private_image, l_tmp)) {
return OPJ_FALSE;
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_add_mct(opj_tcp_t * p_tcp, opj_image_t * p_image,
OPJ_UINT32 p_index)
{
OPJ_UINT32 i;
opj_simple_mcc_decorrelation_data_t * l_mcc_record;
opj_mct_data_t * l_deco_array, * l_offset_array;
OPJ_UINT32 l_data_size, l_mct_size, l_offset_size;
OPJ_UINT32 l_nb_elem;
OPJ_UINT32 * l_offset_data, * l_current_offset_data;
opj_tccp_t * l_tccp;
/* preconditions */
assert(p_tcp != 00);
l_mcc_record = p_tcp->m_mcc_records;
for (i = 0; i < p_tcp->m_nb_mcc_records; ++i) {
if (l_mcc_record->m_index == p_index) {
break;
}
}
if (i == p_tcp->m_nb_mcc_records) {
/** element discarded **/
return OPJ_TRUE;
}
if (l_mcc_record->m_nb_comps != p_image->numcomps) {
/** do not support number of comps != image */
return OPJ_TRUE;
}
l_deco_array = l_mcc_record->m_decorrelation_array;
if (l_deco_array) {
l_data_size = MCT_ELEMENT_SIZE[l_deco_array->m_element_type] * p_image->numcomps
* p_image->numcomps;
if (l_deco_array->m_data_size != l_data_size) {
return OPJ_FALSE;
}
l_nb_elem = p_image->numcomps * p_image->numcomps;
l_mct_size = l_nb_elem * (OPJ_UINT32)sizeof(OPJ_FLOAT32);
p_tcp->m_mct_decoding_matrix = (OPJ_FLOAT32*)opj_malloc(l_mct_size);
if (! p_tcp->m_mct_decoding_matrix) {
return OPJ_FALSE;
}
j2k_mct_read_functions_to_float[l_deco_array->m_element_type](
l_deco_array->m_data, p_tcp->m_mct_decoding_matrix, l_nb_elem);
}
l_offset_array = l_mcc_record->m_offset_array;
if (l_offset_array) {
l_data_size = MCT_ELEMENT_SIZE[l_offset_array->m_element_type] *
p_image->numcomps;
if (l_offset_array->m_data_size != l_data_size) {
return OPJ_FALSE;
}
l_nb_elem = p_image->numcomps;
l_offset_size = l_nb_elem * (OPJ_UINT32)sizeof(OPJ_UINT32);
l_offset_data = (OPJ_UINT32*)opj_malloc(l_offset_size);
if (! l_offset_data) {
return OPJ_FALSE;
}
j2k_mct_read_functions_to_int32[l_offset_array->m_element_type](
l_offset_array->m_data, l_offset_data, l_nb_elem);
l_tccp = p_tcp->tccps;
l_current_offset_data = l_offset_data;
for (i = 0; i < p_image->numcomps; ++i) {
l_tccp->m_dc_level_shift = (OPJ_INT32) * (l_current_offset_data++);
++l_tccp;
}
opj_free(l_offset_data);
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_cbd(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 i;
OPJ_UINT32 l_cbd_size;
OPJ_BYTE * l_current_data = 00;
opj_image_t *l_image = 00;
opj_image_comp_t * l_comp = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_image = p_j2k->m_private_image;
l_cbd_size = 6 + p_j2k->m_private_image->numcomps;
if (l_cbd_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_cbd_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write CBD marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_cbd_size;
}
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_data, J2K_MS_CBD, 2); /* CBD */
l_current_data += 2;
opj_write_bytes(l_current_data, l_cbd_size - 2, 2); /* L_CBD */
l_current_data += 2;
opj_write_bytes(l_current_data, l_image->numcomps, 2); /* Ncbd */
l_current_data += 2;
l_comp = l_image->comps;
for (i = 0; i < l_image->numcomps; ++i) {
opj_write_bytes(l_current_data, (l_comp->sgnd << 7) | (l_comp->prec - 1),
1); /* Component bit depth */
++l_current_data;
++l_comp;
}
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_cbd_size,
p_manager) != l_cbd_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a CBD marker (Component bit depth definition)
* @param p_header_data the data contained in the CBD box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the CBD marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_cbd(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_nb_comp, l_num_comp;
OPJ_UINT32 l_comp_def;
OPJ_UINT32 i;
opj_image_comp_t * l_comp = 00;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_num_comp = p_j2k->m_private_image->numcomps;
if (p_header_size != (p_j2k->m_private_image->numcomps + 2)) {
opj_event_msg(p_manager, EVT_ERROR, "Crror reading CBD marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_nb_comp,
2); /* Ncbd */
p_header_data += 2;
if (l_nb_comp != l_num_comp) {
opj_event_msg(p_manager, EVT_ERROR, "Crror reading CBD marker\n");
return OPJ_FALSE;
}
l_comp = p_j2k->m_private_image->comps;
for (i = 0; i < l_num_comp; ++i) {
opj_read_bytes(p_header_data, &l_comp_def,
1); /* Component bit depth */
++p_header_data;
l_comp->sgnd = (l_comp_def >> 7) & 1;
l_comp->prec = (l_comp_def & 0x7f) + 1;
if (l_comp->prec > 31) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid values for comp = %d : prec=%u (should be between 1 and 38 according to the JPEG2000 norm. OpenJpeg only supports up to 31)\n",
i, l_comp->prec);
return OPJ_FALSE;
}
++l_comp;
}
return OPJ_TRUE;
}
/* ----------------------------------------------------------------------- */
/* J2K / JPT decoder interface */
/* ----------------------------------------------------------------------- */
void opj_j2k_setup_decoder(opj_j2k_t *j2k, opj_dparameters_t *parameters)
{
if (j2k && parameters) {
j2k->m_cp.m_specific_param.m_dec.m_layer = parameters->cp_layer;
j2k->m_cp.m_specific_param.m_dec.m_reduce = parameters->cp_reduce;
j2k->dump_state = (parameters->flags & OPJ_DPARAMETERS_DUMP_FLAG);
#ifdef USE_JPWL
j2k->m_cp.correct = parameters->jpwl_correct;
j2k->m_cp.exp_comps = parameters->jpwl_exp_comps;
j2k->m_cp.max_tiles = parameters->jpwl_max_tiles;
#endif /* USE_JPWL */
}
}
OPJ_BOOL opj_j2k_set_threads(opj_j2k_t *j2k, OPJ_UINT32 num_threads)
{
if (opj_has_thread_support()) {
opj_thread_pool_destroy(j2k->m_tp);
j2k->m_tp = NULL;
if (num_threads <= (OPJ_UINT32)INT_MAX) {
j2k->m_tp = opj_thread_pool_create((int)num_threads);
}
if (j2k->m_tp == NULL) {
j2k->m_tp = opj_thread_pool_create(0);
return OPJ_FALSE;
}
return OPJ_TRUE;
}
return OPJ_FALSE;
}
static int opj_j2k_get_default_thread_count()
{
const char* num_threads = getenv("OPJ_NUM_THREADS");
if (num_threads == NULL || !opj_has_thread_support()) {
return 0;
}
if (strcmp(num_threads, "ALL_CPUS") == 0) {
return opj_get_num_cpus();
}
return atoi(num_threads);
}
/* ----------------------------------------------------------------------- */
/* J2K encoder interface */
/* ----------------------------------------------------------------------- */
opj_j2k_t* opj_j2k_create_compress(void)
{
opj_j2k_t *l_j2k = (opj_j2k_t*) opj_calloc(1, sizeof(opj_j2k_t));
if (!l_j2k) {
return NULL;
}
l_j2k->m_is_decoder = 0;
l_j2k->m_cp.m_is_decoder = 0;
l_j2k->m_specific_param.m_encoder.m_header_tile_data = (OPJ_BYTE *) opj_malloc(
OPJ_J2K_DEFAULT_HEADER_SIZE);
if (! l_j2k->m_specific_param.m_encoder.m_header_tile_data) {
opj_j2k_destroy(l_j2k);
return NULL;
}
l_j2k->m_specific_param.m_encoder.m_header_tile_data_size =
OPJ_J2K_DEFAULT_HEADER_SIZE;
/* validation list creation*/
l_j2k->m_validation_list = opj_procedure_list_create();
if (! l_j2k->m_validation_list) {
opj_j2k_destroy(l_j2k);
return NULL;
}
/* execution list creation*/
l_j2k->m_procedure_list = opj_procedure_list_create();
if (! l_j2k->m_procedure_list) {
opj_j2k_destroy(l_j2k);
return NULL;
}
l_j2k->m_tp = opj_thread_pool_create(opj_j2k_get_default_thread_count());
if (!l_j2k->m_tp) {
l_j2k->m_tp = opj_thread_pool_create(0);
}
if (!l_j2k->m_tp) {
opj_j2k_destroy(l_j2k);
return NULL;
}
return l_j2k;
}
static int opj_j2k_initialise_4K_poc(opj_poc_t *POC, int numres)
{
POC[0].tile = 1;
POC[0].resno0 = 0;
POC[0].compno0 = 0;
POC[0].layno1 = 1;
POC[0].resno1 = (OPJ_UINT32)(numres - 1);
POC[0].compno1 = 3;
POC[0].prg1 = OPJ_CPRL;
POC[1].tile = 1;
POC[1].resno0 = (OPJ_UINT32)(numres - 1);
POC[1].compno0 = 0;
POC[1].layno1 = 1;
POC[1].resno1 = (OPJ_UINT32)numres;
POC[1].compno1 = 3;
POC[1].prg1 = OPJ_CPRL;
return 2;
}
static void opj_j2k_set_cinema_parameters(opj_cparameters_t *parameters,
opj_image_t *image, opj_event_mgr_t *p_manager)
{
/* Configure cinema parameters */
int i;
/* No tiling */
parameters->tile_size_on = OPJ_FALSE;
parameters->cp_tdx = 1;
parameters->cp_tdy = 1;
/* One tile part for each component */
parameters->tp_flag = 'C';
parameters->tp_on = 1;
/* Tile and Image shall be at (0,0) */
parameters->cp_tx0 = 0;
parameters->cp_ty0 = 0;
parameters->image_offset_x0 = 0;
parameters->image_offset_y0 = 0;
/* Codeblock size= 32*32 */
parameters->cblockw_init = 32;
parameters->cblockh_init = 32;
/* Codeblock style: no mode switch enabled */
parameters->mode = 0;
/* No ROI */
parameters->roi_compno = -1;
/* No subsampling */
parameters->subsampling_dx = 1;
parameters->subsampling_dy = 1;
/* 9-7 transform */
parameters->irreversible = 1;
/* Number of layers */
if (parameters->tcp_numlayers > 1) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
"1 single quality layer"
"-> Number of layers forced to 1 (rather than %d)\n"
"-> Rate of the last layer (%3.1f) will be used",
parameters->tcp_numlayers,
parameters->tcp_rates[parameters->tcp_numlayers - 1]);
parameters->tcp_rates[0] = parameters->tcp_rates[parameters->tcp_numlayers - 1];
parameters->tcp_numlayers = 1;
}
/* Resolution levels */
switch (parameters->rsiz) {
case OPJ_PROFILE_CINEMA_2K:
if (parameters->numresolution > 6) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 (2k dc profile) requires:\n"
"Number of decomposition levels <= 5\n"
"-> Number of decomposition levels forced to 5 (rather than %d)\n",
parameters->numresolution + 1);
parameters->numresolution = 6;
}
break;
case OPJ_PROFILE_CINEMA_4K:
if (parameters->numresolution < 2) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-4 (4k dc profile) requires:\n"
"Number of decomposition levels >= 1 && <= 6\n"
"-> Number of decomposition levels forced to 1 (rather than %d)\n",
parameters->numresolution + 1);
parameters->numresolution = 1;
} else if (parameters->numresolution > 7) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-4 (4k dc profile) requires:\n"
"Number of decomposition levels >= 1 && <= 6\n"
"-> Number of decomposition levels forced to 6 (rather than %d)\n",
parameters->numresolution + 1);
parameters->numresolution = 7;
}
break;
default :
break;
}
/* Precincts */
parameters->csty |= 0x01;
if (parameters->numresolution == 1) {
parameters->res_spec = 1;
parameters->prcw_init[0] = 128;
parameters->prch_init[0] = 128;
} else {
parameters->res_spec = parameters->numresolution - 1;
for (i = 0; i < parameters->res_spec; i++) {
parameters->prcw_init[i] = 256;
parameters->prch_init[i] = 256;
}
}
/* The progression order shall be CPRL */
parameters->prog_order = OPJ_CPRL;
/* Progression order changes for 4K, disallowed for 2K */
if (parameters->rsiz == OPJ_PROFILE_CINEMA_4K) {
parameters->numpocs = (OPJ_UINT32)opj_j2k_initialise_4K_poc(parameters->POC,
parameters->numresolution);
} else {
parameters->numpocs = 0;
}
/* Limited bit-rate */
parameters->cp_disto_alloc = 1;
if (parameters->max_cs_size <= 0) {
/* No rate has been introduced, 24 fps is assumed */
parameters->max_cs_size = OPJ_CINEMA_24_CS;
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
"Maximum 1302083 compressed bytes @ 24fps\n"
"As no rate has been given, this limit will be used.\n");
} else if (parameters->max_cs_size > OPJ_CINEMA_24_CS) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
"Maximum 1302083 compressed bytes @ 24fps\n"
"-> Specified rate exceeds this limit. Rate will be forced to 1302083 bytes.\n");
parameters->max_cs_size = OPJ_CINEMA_24_CS;
}
if (parameters->max_comp_size <= 0) {
/* No rate has been introduced, 24 fps is assumed */
parameters->max_comp_size = OPJ_CINEMA_24_COMP;
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
"Maximum 1041666 compressed bytes @ 24fps\n"
"As no rate has been given, this limit will be used.\n");
} else if (parameters->max_comp_size > OPJ_CINEMA_24_COMP) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
"Maximum 1041666 compressed bytes @ 24fps\n"
"-> Specified rate exceeds this limit. Rate will be forced to 1041666 bytes.\n");
parameters->max_comp_size = OPJ_CINEMA_24_COMP;
}
parameters->tcp_rates[0] = (OPJ_FLOAT32)(image->numcomps * image->comps[0].w *
image->comps[0].h * image->comps[0].prec) /
(OPJ_FLOAT32)(((OPJ_UINT32)parameters->max_cs_size) * 8 * image->comps[0].dx *
image->comps[0].dy);
}
static OPJ_BOOL opj_j2k_is_cinema_compliant(opj_image_t *image, OPJ_UINT16 rsiz,
opj_event_mgr_t *p_manager)
{
OPJ_UINT32 i;
/* Number of components */
if (image->numcomps != 3) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 (2k dc profile) requires:\n"
"3 components"
"-> Number of components of input image (%d) is not compliant\n"
"-> Non-profile-3 codestream will be generated\n",
image->numcomps);
return OPJ_FALSE;
}
/* Bitdepth */
for (i = 0; i < image->numcomps; i++) {
if ((image->comps[i].bpp != 12) | (image->comps[i].sgnd)) {
char signed_str[] = "signed";
char unsigned_str[] = "unsigned";
char *tmp_str = image->comps[i].sgnd ? signed_str : unsigned_str;
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 (2k dc profile) requires:\n"
"Precision of each component shall be 12 bits unsigned"
"-> At least component %d of input image (%d bits, %s) is not compliant\n"
"-> Non-profile-3 codestream will be generated\n",
i, image->comps[i].bpp, tmp_str);
return OPJ_FALSE;
}
}
/* Image size */
switch (rsiz) {
case OPJ_PROFILE_CINEMA_2K:
if (((image->comps[0].w > 2048) | (image->comps[0].h > 1080))) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 (2k dc profile) requires:\n"
"width <= 2048 and height <= 1080\n"
"-> Input image size %d x %d is not compliant\n"
"-> Non-profile-3 codestream will be generated\n",
image->comps[0].w, image->comps[0].h);
return OPJ_FALSE;
}
break;
case OPJ_PROFILE_CINEMA_4K:
if (((image->comps[0].w > 4096) | (image->comps[0].h > 2160))) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-4 (4k dc profile) requires:\n"
"width <= 4096 and height <= 2160\n"
"-> Image size %d x %d is not compliant\n"
"-> Non-profile-4 codestream will be generated\n",
image->comps[0].w, image->comps[0].h);
return OPJ_FALSE;
}
break;
default :
break;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_setup_encoder(opj_j2k_t *p_j2k,
opj_cparameters_t *parameters,
opj_image_t *image,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 i, j, tileno, numpocs_tile;
opj_cp_t *cp = 00;
if (!p_j2k || !parameters || ! image) {
return OPJ_FALSE;
}
if ((parameters->numresolution <= 0) ||
(parameters->numresolution > OPJ_J2K_MAXRLVLS)) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid number of resolutions : %d not in range [1,%d]\n",
parameters->numresolution, OPJ_J2K_MAXRLVLS);
return OPJ_FALSE;
}
/* keep a link to cp so that we can destroy it later in j2k_destroy_compress */
cp = &(p_j2k->m_cp);
/* set default values for cp */
cp->tw = 1;
cp->th = 1;
/* FIXME ADE: to be removed once deprecated cp_cinema and cp_rsiz have been removed */
if (parameters->rsiz ==
OPJ_PROFILE_NONE) { /* consider deprecated fields only if RSIZ has not been set */
OPJ_BOOL deprecated_used = OPJ_FALSE;
switch (parameters->cp_cinema) {
case OPJ_CINEMA2K_24:
parameters->rsiz = OPJ_PROFILE_CINEMA_2K;
parameters->max_cs_size = OPJ_CINEMA_24_CS;
parameters->max_comp_size = OPJ_CINEMA_24_COMP;
deprecated_used = OPJ_TRUE;
break;
case OPJ_CINEMA2K_48:
parameters->rsiz = OPJ_PROFILE_CINEMA_2K;
parameters->max_cs_size = OPJ_CINEMA_48_CS;
parameters->max_comp_size = OPJ_CINEMA_48_COMP;
deprecated_used = OPJ_TRUE;
break;
case OPJ_CINEMA4K_24:
parameters->rsiz = OPJ_PROFILE_CINEMA_4K;
parameters->max_cs_size = OPJ_CINEMA_24_CS;
parameters->max_comp_size = OPJ_CINEMA_24_COMP;
deprecated_used = OPJ_TRUE;
break;
case OPJ_OFF:
default:
break;
}
switch (parameters->cp_rsiz) {
case OPJ_CINEMA2K:
parameters->rsiz = OPJ_PROFILE_CINEMA_2K;
deprecated_used = OPJ_TRUE;
break;
case OPJ_CINEMA4K:
parameters->rsiz = OPJ_PROFILE_CINEMA_4K;
deprecated_used = OPJ_TRUE;
break;
case OPJ_MCT:
parameters->rsiz = OPJ_PROFILE_PART2 | OPJ_EXTENSION_MCT;
deprecated_used = OPJ_TRUE;
case OPJ_STD_RSIZ:
default:
break;
}
if (deprecated_used) {
opj_event_msg(p_manager, EVT_WARNING,
"Deprecated fields cp_cinema or cp_rsiz are used\n"
"Please consider using only the rsiz field\n"
"See openjpeg.h documentation for more details\n");
}
}
/* If no explicit layers are provided, use lossless settings */
if (parameters->tcp_numlayers == 0) {
parameters->tcp_numlayers = 1;
parameters->cp_disto_alloc = 1;
parameters->tcp_rates[0] = 0;
}
/* see if max_codestream_size does limit input rate */
if (parameters->max_cs_size <= 0) {
if (parameters->tcp_rates[parameters->tcp_numlayers - 1] > 0) {
OPJ_FLOAT32 temp_size;
temp_size = (OPJ_FLOAT32)(image->numcomps * image->comps[0].w *
image->comps[0].h * image->comps[0].prec) /
(parameters->tcp_rates[parameters->tcp_numlayers - 1] * 8 *
(OPJ_FLOAT32)image->comps[0].dx * (OPJ_FLOAT32)image->comps[0].dy);
parameters->max_cs_size = (int) floor(temp_size);
} else {
parameters->max_cs_size = 0;
}
} else {
OPJ_FLOAT32 temp_rate;
OPJ_BOOL cap = OPJ_FALSE;
temp_rate = (OPJ_FLOAT32)(image->numcomps * image->comps[0].w *
image->comps[0].h * image->comps[0].prec) /
(OPJ_FLOAT32)(((OPJ_UINT32)parameters->max_cs_size) * 8 * image->comps[0].dx *
image->comps[0].dy);
for (i = 0; i < (OPJ_UINT32) parameters->tcp_numlayers; i++) {
if (parameters->tcp_rates[i] < temp_rate) {
parameters->tcp_rates[i] = temp_rate;
cap = OPJ_TRUE;
}
}
if (cap) {
opj_event_msg(p_manager, EVT_WARNING,
"The desired maximum codestream size has limited\n"
"at least one of the desired quality layers\n");
}
}
/* Manage profiles and applications and set RSIZ */
/* set cinema parameters if required */
if (OPJ_IS_CINEMA(parameters->rsiz)) {
if ((parameters->rsiz == OPJ_PROFILE_CINEMA_S2K)
|| (parameters->rsiz == OPJ_PROFILE_CINEMA_S4K)) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Scalable Digital Cinema profiles not yet supported\n");
parameters->rsiz = OPJ_PROFILE_NONE;
} else {
opj_j2k_set_cinema_parameters(parameters, image, p_manager);
if (!opj_j2k_is_cinema_compliant(image, parameters->rsiz, p_manager)) {
parameters->rsiz = OPJ_PROFILE_NONE;
}
}
} else if (OPJ_IS_STORAGE(parameters->rsiz)) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Long Term Storage profile not yet supported\n");
parameters->rsiz = OPJ_PROFILE_NONE;
} else if (OPJ_IS_BROADCAST(parameters->rsiz)) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Broadcast profiles not yet supported\n");
parameters->rsiz = OPJ_PROFILE_NONE;
} else if (OPJ_IS_IMF(parameters->rsiz)) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 IMF profiles not yet supported\n");
parameters->rsiz = OPJ_PROFILE_NONE;
} else if (OPJ_IS_PART2(parameters->rsiz)) {
if (parameters->rsiz == ((OPJ_PROFILE_PART2) | (OPJ_EXTENSION_NONE))) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Part-2 profile defined\n"
"but no Part-2 extension enabled.\n"
"Profile set to NONE.\n");
parameters->rsiz = OPJ_PROFILE_NONE;
} else if (parameters->rsiz != ((OPJ_PROFILE_PART2) | (OPJ_EXTENSION_MCT))) {
opj_event_msg(p_manager, EVT_WARNING,
"Unsupported Part-2 extension enabled\n"
"Profile set to NONE.\n");
parameters->rsiz = OPJ_PROFILE_NONE;
}
}
/*
copy user encoding parameters
*/
cp->m_specific_param.m_enc.m_max_comp_size = (OPJ_UINT32)
parameters->max_comp_size;
cp->rsiz = parameters->rsiz;
cp->m_specific_param.m_enc.m_disto_alloc = (OPJ_UINT32)
parameters->cp_disto_alloc & 1u;
cp->m_specific_param.m_enc.m_fixed_alloc = (OPJ_UINT32)
parameters->cp_fixed_alloc & 1u;
cp->m_specific_param.m_enc.m_fixed_quality = (OPJ_UINT32)
parameters->cp_fixed_quality & 1u;
/* mod fixed_quality */
if (parameters->cp_fixed_alloc && parameters->cp_matrice) {
size_t array_size = (size_t)parameters->tcp_numlayers *
(size_t)parameters->numresolution * 3 * sizeof(OPJ_INT32);
cp->m_specific_param.m_enc.m_matrice = (OPJ_INT32 *) opj_malloc(array_size);
if (!cp->m_specific_param.m_enc.m_matrice) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate copy of user encoding parameters matrix \n");
return OPJ_FALSE;
}
memcpy(cp->m_specific_param.m_enc.m_matrice, parameters->cp_matrice,
array_size);
}
/* tiles */
cp->tdx = (OPJ_UINT32)parameters->cp_tdx;
cp->tdy = (OPJ_UINT32)parameters->cp_tdy;
/* tile offset */
cp->tx0 = (OPJ_UINT32)parameters->cp_tx0;
cp->ty0 = (OPJ_UINT32)parameters->cp_ty0;
/* comment string */
if (parameters->cp_comment) {
cp->comment = (char*)opj_malloc(strlen(parameters->cp_comment) + 1U);
if (!cp->comment) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate copy of comment string\n");
return OPJ_FALSE;
}
strcpy(cp->comment, parameters->cp_comment);
} else {
/* Create default comment for codestream */
const char comment[] = "Created by OpenJPEG version ";
const size_t clen = strlen(comment);
const char *version = opj_version();
/* UniPG>> */
#ifdef USE_JPWL
cp->comment = (char*)opj_malloc(clen + strlen(version) + 11);
if (!cp->comment) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate comment string\n");
return OPJ_FALSE;
}
sprintf(cp->comment, "%s%s with JPWL", comment, version);
#else
cp->comment = (char*)opj_malloc(clen + strlen(version) + 1);
if (!cp->comment) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate comment string\n");
return OPJ_FALSE;
}
sprintf(cp->comment, "%s%s", comment, version);
#endif
/* <<UniPG */
}
/*
calculate other encoding parameters
*/
if (parameters->tile_size_on) {
cp->tw = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)(image->x1 - cp->tx0),
(OPJ_INT32)cp->tdx);
cp->th = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)(image->y1 - cp->ty0),
(OPJ_INT32)cp->tdy);
} else {
cp->tdx = image->x1 - cp->tx0;
cp->tdy = image->y1 - cp->ty0;
}
if (parameters->tp_on) {
cp->m_specific_param.m_enc.m_tp_flag = (OPJ_BYTE)parameters->tp_flag;
cp->m_specific_param.m_enc.m_tp_on = 1;
}
#ifdef USE_JPWL
/*
calculate JPWL encoding parameters
*/
if (parameters->jpwl_epc_on) {
OPJ_INT32 i;
/* set JPWL on */
cp->epc_on = OPJ_TRUE;
cp->info_on = OPJ_FALSE; /* no informative technique */
/* set EPB on */
if ((parameters->jpwl_hprot_MH > 0) || (parameters->jpwl_hprot_TPH[0] > 0)) {
cp->epb_on = OPJ_TRUE;
cp->hprot_MH = parameters->jpwl_hprot_MH;
for (i = 0; i < JPWL_MAX_NO_TILESPECS; i++) {
cp->hprot_TPH_tileno[i] = parameters->jpwl_hprot_TPH_tileno[i];
cp->hprot_TPH[i] = parameters->jpwl_hprot_TPH[i];
}
/* if tile specs are not specified, copy MH specs */
if (cp->hprot_TPH[0] == -1) {
cp->hprot_TPH_tileno[0] = 0;
cp->hprot_TPH[0] = parameters->jpwl_hprot_MH;
}
for (i = 0; i < JPWL_MAX_NO_PACKSPECS; i++) {
cp->pprot_tileno[i] = parameters->jpwl_pprot_tileno[i];
cp->pprot_packno[i] = parameters->jpwl_pprot_packno[i];
cp->pprot[i] = parameters->jpwl_pprot[i];
}
}
/* set ESD writing */
if ((parameters->jpwl_sens_size == 1) || (parameters->jpwl_sens_size == 2)) {
cp->esd_on = OPJ_TRUE;
cp->sens_size = parameters->jpwl_sens_size;
cp->sens_addr = parameters->jpwl_sens_addr;
cp->sens_range = parameters->jpwl_sens_range;
cp->sens_MH = parameters->jpwl_sens_MH;
for (i = 0; i < JPWL_MAX_NO_TILESPECS; i++) {
cp->sens_TPH_tileno[i] = parameters->jpwl_sens_TPH_tileno[i];
cp->sens_TPH[i] = parameters->jpwl_sens_TPH[i];
}
}
/* always set RED writing to false: we are at the encoder */
cp->red_on = OPJ_FALSE;
} else {
cp->epc_on = OPJ_FALSE;
}
#endif /* USE_JPWL */
/* initialize the mutiple tiles */
/* ---------------------------- */
cp->tcps = (opj_tcp_t*) opj_calloc(cp->tw * cp->th, sizeof(opj_tcp_t));
if (!cp->tcps) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate tile coding parameters\n");
return OPJ_FALSE;
}
if (parameters->numpocs) {
/* initialisation of POC */
opj_j2k_check_poc_val(parameters->POC, parameters->numpocs,
(OPJ_UINT32)parameters->numresolution, image->numcomps,
(OPJ_UINT32)parameters->tcp_numlayers, p_manager);
/* TODO MSD use the return value*/
}
for (tileno = 0; tileno < cp->tw * cp->th; tileno++) {
opj_tcp_t *tcp = &cp->tcps[tileno];
tcp->numlayers = (OPJ_UINT32)parameters->tcp_numlayers;
for (j = 0; j < tcp->numlayers; j++) {
if (OPJ_IS_CINEMA(cp->rsiz)) {
if (cp->m_specific_param.m_enc.m_fixed_quality) {
tcp->distoratio[j] = parameters->tcp_distoratio[j];
}
tcp->rates[j] = parameters->tcp_rates[j];
} else {
if (cp->m_specific_param.m_enc.m_fixed_quality) { /* add fixed_quality */
tcp->distoratio[j] = parameters->tcp_distoratio[j];
} else {
tcp->rates[j] = parameters->tcp_rates[j];
}
}
}
tcp->csty = (OPJ_UINT32)parameters->csty;
tcp->prg = parameters->prog_order;
tcp->mct = (OPJ_UINT32)parameters->tcp_mct;
numpocs_tile = 0;
tcp->POC = 0;
if (parameters->numpocs) {
/* initialisation of POC */
tcp->POC = 1;
for (i = 0; i < parameters->numpocs; i++) {
if (tileno + 1 == parameters->POC[i].tile) {
opj_poc_t *tcp_poc = &tcp->pocs[numpocs_tile];
tcp_poc->resno0 = parameters->POC[numpocs_tile].resno0;
tcp_poc->compno0 = parameters->POC[numpocs_tile].compno0;
tcp_poc->layno1 = parameters->POC[numpocs_tile].layno1;
tcp_poc->resno1 = parameters->POC[numpocs_tile].resno1;
tcp_poc->compno1 = parameters->POC[numpocs_tile].compno1;
tcp_poc->prg1 = parameters->POC[numpocs_tile].prg1;
tcp_poc->tile = parameters->POC[numpocs_tile].tile;
numpocs_tile++;
}
}
tcp->numpocs = numpocs_tile - 1 ;
} else {
tcp->numpocs = 0;
}
tcp->tccps = (opj_tccp_t*) opj_calloc(image->numcomps, sizeof(opj_tccp_t));
if (!tcp->tccps) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate tile component coding parameters\n");
return OPJ_FALSE;
}
if (parameters->mct_data) {
OPJ_UINT32 lMctSize = image->numcomps * image->numcomps * (OPJ_UINT32)sizeof(
OPJ_FLOAT32);
OPJ_FLOAT32 * lTmpBuf = (OPJ_FLOAT32*)opj_malloc(lMctSize);
OPJ_INT32 * l_dc_shift = (OPJ_INT32 *)((OPJ_BYTE *) parameters->mct_data +
lMctSize);
if (!lTmpBuf) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate temp buffer\n");
return OPJ_FALSE;
}
tcp->mct = 2;
tcp->m_mct_coding_matrix = (OPJ_FLOAT32*)opj_malloc(lMctSize);
if (! tcp->m_mct_coding_matrix) {
opj_free(lTmpBuf);
lTmpBuf = NULL;
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate encoder MCT coding matrix \n");
return OPJ_FALSE;
}
memcpy(tcp->m_mct_coding_matrix, parameters->mct_data, lMctSize);
memcpy(lTmpBuf, parameters->mct_data, lMctSize);
tcp->m_mct_decoding_matrix = (OPJ_FLOAT32*)opj_malloc(lMctSize);
if (! tcp->m_mct_decoding_matrix) {
opj_free(lTmpBuf);
lTmpBuf = NULL;
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate encoder MCT decoding matrix \n");
return OPJ_FALSE;
}
if (opj_matrix_inversion_f(lTmpBuf, (tcp->m_mct_decoding_matrix),
image->numcomps) == OPJ_FALSE) {
opj_free(lTmpBuf);
lTmpBuf = NULL;
opj_event_msg(p_manager, EVT_ERROR,
"Failed to inverse encoder MCT decoding matrix \n");
return OPJ_FALSE;
}
tcp->mct_norms = (OPJ_FLOAT64*)
opj_malloc(image->numcomps * sizeof(OPJ_FLOAT64));
if (! tcp->mct_norms) {
opj_free(lTmpBuf);
lTmpBuf = NULL;
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate encoder MCT norms \n");
return OPJ_FALSE;
}
opj_calculate_norms(tcp->mct_norms, image->numcomps,
tcp->m_mct_decoding_matrix);
opj_free(lTmpBuf);
for (i = 0; i < image->numcomps; i++) {
opj_tccp_t *tccp = &tcp->tccps[i];
tccp->m_dc_level_shift = l_dc_shift[i];
}
if (opj_j2k_setup_mct_encoding(tcp, image) == OPJ_FALSE) {
/* free will be handled by opj_j2k_destroy */
opj_event_msg(p_manager, EVT_ERROR, "Failed to setup j2k mct encoding\n");
return OPJ_FALSE;
}
} else {
if (tcp->mct == 1 && image->numcomps >= 3) { /* RGB->YCC MCT is enabled */
if ((image->comps[0].dx != image->comps[1].dx) ||
(image->comps[0].dx != image->comps[2].dx) ||
(image->comps[0].dy != image->comps[1].dy) ||
(image->comps[0].dy != image->comps[2].dy)) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot perform MCT on components with different sizes. Disabling MCT.\n");
tcp->mct = 0;
}
}
for (i = 0; i < image->numcomps; i++) {
opj_tccp_t *tccp = &tcp->tccps[i];
opj_image_comp_t * l_comp = &(image->comps[i]);
if (! l_comp->sgnd) {
tccp->m_dc_level_shift = 1 << (l_comp->prec - 1);
}
}
}
for (i = 0; i < image->numcomps; i++) {
opj_tccp_t *tccp = &tcp->tccps[i];
tccp->csty = parameters->csty &
0x01; /* 0 => one precinct || 1 => custom precinct */
tccp->numresolutions = (OPJ_UINT32)parameters->numresolution;
tccp->cblkw = (OPJ_UINT32)opj_int_floorlog2(parameters->cblockw_init);
tccp->cblkh = (OPJ_UINT32)opj_int_floorlog2(parameters->cblockh_init);
tccp->cblksty = (OPJ_UINT32)parameters->mode;
tccp->qmfbid = parameters->irreversible ? 0 : 1;
tccp->qntsty = parameters->irreversible ? J2K_CCP_QNTSTY_SEQNT :
J2K_CCP_QNTSTY_NOQNT;
tccp->numgbits = 2;
if ((OPJ_INT32)i == parameters->roi_compno) {
tccp->roishift = parameters->roi_shift;
} else {
tccp->roishift = 0;
}
if (parameters->csty & J2K_CCP_CSTY_PRT) {
OPJ_INT32 p = 0, it_res;
assert(tccp->numresolutions > 0);
for (it_res = (OPJ_INT32)tccp->numresolutions - 1; it_res >= 0; it_res--) {
if (p < parameters->res_spec) {
if (parameters->prcw_init[p] < 1) {
tccp->prcw[it_res] = 1;
} else {
tccp->prcw[it_res] = (OPJ_UINT32)opj_int_floorlog2(parameters->prcw_init[p]);
}
if (parameters->prch_init[p] < 1) {
tccp->prch[it_res] = 1;
} else {
tccp->prch[it_res] = (OPJ_UINT32)opj_int_floorlog2(parameters->prch_init[p]);
}
} else {
OPJ_INT32 res_spec = parameters->res_spec;
OPJ_INT32 size_prcw = 0;
OPJ_INT32 size_prch = 0;
assert(res_spec > 0); /* issue 189 */
size_prcw = parameters->prcw_init[res_spec - 1] >> (p - (res_spec - 1));
size_prch = parameters->prch_init[res_spec - 1] >> (p - (res_spec - 1));
if (size_prcw < 1) {
tccp->prcw[it_res] = 1;
} else {
tccp->prcw[it_res] = (OPJ_UINT32)opj_int_floorlog2(size_prcw);
}
if (size_prch < 1) {
tccp->prch[it_res] = 1;
} else {
tccp->prch[it_res] = (OPJ_UINT32)opj_int_floorlog2(size_prch);
}
}
p++;
/*printf("\nsize precinct for level %d : %d,%d\n", it_res,tccp->prcw[it_res], tccp->prch[it_res]); */
} /*end for*/
} else {
for (j = 0; j < tccp->numresolutions; j++) {
tccp->prcw[j] = 15;
tccp->prch[j] = 15;
}
}
opj_dwt_calc_explicit_stepsizes(tccp, image->comps[i].prec);
}
}
if (parameters->mct_data) {
opj_free(parameters->mct_data);
parameters->mct_data = 00;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_add_mhmarker(opj_codestream_index_t *cstr_index,
OPJ_UINT32 type, OPJ_OFF_T pos, OPJ_UINT32 len)
{
assert(cstr_index != 00);
/* expand the list? */
if ((cstr_index->marknum + 1) > cstr_index->maxmarknum) {
opj_marker_info_t *new_marker;
cstr_index->maxmarknum = (OPJ_UINT32)(100 + (OPJ_FLOAT32)
cstr_index->maxmarknum);
new_marker = (opj_marker_info_t *) opj_realloc(cstr_index->marker,
cstr_index->maxmarknum * sizeof(opj_marker_info_t));
if (! new_marker) {
opj_free(cstr_index->marker);
cstr_index->marker = NULL;
cstr_index->maxmarknum = 0;
cstr_index->marknum = 0;
/* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add mh marker\n"); */
return OPJ_FALSE;
}
cstr_index->marker = new_marker;
}
/* add the marker */
cstr_index->marker[cstr_index->marknum].type = (OPJ_UINT16)type;
cstr_index->marker[cstr_index->marknum].pos = (OPJ_INT32)pos;
cstr_index->marker[cstr_index->marknum].len = (OPJ_INT32)len;
cstr_index->marknum++;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_add_tlmarker(OPJ_UINT32 tileno,
opj_codestream_index_t *cstr_index, OPJ_UINT32 type, OPJ_OFF_T pos,
OPJ_UINT32 len)
{
assert(cstr_index != 00);
assert(cstr_index->tile_index != 00);
/* expand the list? */
if ((cstr_index->tile_index[tileno].marknum + 1) >
cstr_index->tile_index[tileno].maxmarknum) {
opj_marker_info_t *new_marker;
cstr_index->tile_index[tileno].maxmarknum = (OPJ_UINT32)(100 +
(OPJ_FLOAT32) cstr_index->tile_index[tileno].maxmarknum);
new_marker = (opj_marker_info_t *) opj_realloc(
cstr_index->tile_index[tileno].marker,
cstr_index->tile_index[tileno].maxmarknum * sizeof(opj_marker_info_t));
if (! new_marker) {
opj_free(cstr_index->tile_index[tileno].marker);
cstr_index->tile_index[tileno].marker = NULL;
cstr_index->tile_index[tileno].maxmarknum = 0;
cstr_index->tile_index[tileno].marknum = 0;
/* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add tl marker\n"); */
return OPJ_FALSE;
}
cstr_index->tile_index[tileno].marker = new_marker;
}
/* add the marker */
cstr_index->tile_index[tileno].marker[cstr_index->tile_index[tileno].marknum].type
= (OPJ_UINT16)type;
cstr_index->tile_index[tileno].marker[cstr_index->tile_index[tileno].marknum].pos
= (OPJ_INT32)pos;
cstr_index->tile_index[tileno].marker[cstr_index->tile_index[tileno].marknum].len
= (OPJ_INT32)len;
cstr_index->tile_index[tileno].marknum++;
if (type == J2K_MS_SOT) {
OPJ_UINT32 l_current_tile_part = cstr_index->tile_index[tileno].current_tpsno;
if (cstr_index->tile_index[tileno].tp_index) {
cstr_index->tile_index[tileno].tp_index[l_current_tile_part].start_pos = pos;
}
}
return OPJ_TRUE;
}
/*
* -----------------------------------------------------------------------
* -----------------------------------------------------------------------
* -----------------------------------------------------------------------
*/
OPJ_BOOL opj_j2k_end_decompress(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
(void)p_j2k;
(void)p_stream;
(void)p_manager;
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_read_header(opj_stream_private_t *p_stream,
opj_j2k_t* p_j2k,
opj_image_t** p_image,
opj_event_mgr_t* p_manager)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
/* create an empty image header */
p_j2k->m_private_image = opj_image_create0();
if (! p_j2k->m_private_image) {
return OPJ_FALSE;
}
/* customization of the validation */
if (! opj_j2k_setup_decoding_validation(p_j2k, p_manager)) {
opj_image_destroy(p_j2k->m_private_image);
p_j2k->m_private_image = NULL;
return OPJ_FALSE;
}
/* validation of the parameters codec */
if (! opj_j2k_exec(p_j2k, p_j2k->m_validation_list, p_stream, p_manager)) {
opj_image_destroy(p_j2k->m_private_image);
p_j2k->m_private_image = NULL;
return OPJ_FALSE;
}
/* customization of the encoding */
if (! opj_j2k_setup_header_reading(p_j2k, p_manager)) {
opj_image_destroy(p_j2k->m_private_image);
p_j2k->m_private_image = NULL;
return OPJ_FALSE;
}
/* read header */
if (! opj_j2k_exec(p_j2k, p_j2k->m_procedure_list, p_stream, p_manager)) {
opj_image_destroy(p_j2k->m_private_image);
p_j2k->m_private_image = NULL;
return OPJ_FALSE;
}
*p_image = opj_image_create0();
if (!(*p_image)) {
return OPJ_FALSE;
}
/* Copy codestream image information to the output image */
opj_copy_image_header(p_j2k->m_private_image, *p_image);
/*Allocate and initialize some elements of codestrem index*/
if (!opj_j2k_allocate_tile_element_cstr_index(p_j2k)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_setup_header_reading(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager)
{
/* preconditions*/
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_read_header_procedure, p_manager)) {
return OPJ_FALSE;
}
/* DEVELOPER CORNER, add your custom procedures */
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_copy_default_tcp_and_create_tcd, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_setup_decoding_validation(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager)
{
/* preconditions*/
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list,
(opj_procedure)opj_j2k_build_decoder, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list,
(opj_procedure)opj_j2k_decoding_validation, p_manager)) {
return OPJ_FALSE;
}
/* DEVELOPER CORNER, add your custom validation procedure */
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_mct_validation(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_BOOL l_is_valid = OPJ_TRUE;
OPJ_UINT32 i, j;
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_stream);
OPJ_UNUSED(p_manager);
if ((p_j2k->m_cp.rsiz & 0x8200) == 0x8200) {
OPJ_UINT32 l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
opj_tcp_t * l_tcp = p_j2k->m_cp.tcps;
for (i = 0; i < l_nb_tiles; ++i) {
if (l_tcp->mct == 2) {
opj_tccp_t * l_tccp = l_tcp->tccps;
l_is_valid &= (l_tcp->m_mct_coding_matrix != 00);
for (j = 0; j < p_j2k->m_private_image->numcomps; ++j) {
l_is_valid &= !(l_tccp->qmfbid & 1);
++l_tccp;
}
}
++l_tcp;
}
}
return l_is_valid;
}
OPJ_BOOL opj_j2k_setup_mct_encoding(opj_tcp_t * p_tcp, opj_image_t * p_image)
{
OPJ_UINT32 i;
OPJ_UINT32 l_indix = 1;
opj_mct_data_t * l_mct_deco_data = 00, * l_mct_offset_data = 00;
opj_simple_mcc_decorrelation_data_t * l_mcc_data;
OPJ_UINT32 l_mct_size, l_nb_elem;
OPJ_FLOAT32 * l_data, * l_current_data;
opj_tccp_t * l_tccp;
/* preconditions */
assert(p_tcp != 00);
if (p_tcp->mct != 2) {
return OPJ_TRUE;
}
if (p_tcp->m_mct_decoding_matrix) {
if (p_tcp->m_nb_mct_records == p_tcp->m_nb_max_mct_records) {
opj_mct_data_t *new_mct_records;
p_tcp->m_nb_max_mct_records += OPJ_J2K_MCT_DEFAULT_NB_RECORDS;
new_mct_records = (opj_mct_data_t *) opj_realloc(p_tcp->m_mct_records,
p_tcp->m_nb_max_mct_records * sizeof(opj_mct_data_t));
if (! new_mct_records) {
opj_free(p_tcp->m_mct_records);
p_tcp->m_mct_records = NULL;
p_tcp->m_nb_max_mct_records = 0;
p_tcp->m_nb_mct_records = 0;
/* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to setup mct encoding\n"); */
return OPJ_FALSE;
}
p_tcp->m_mct_records = new_mct_records;
l_mct_deco_data = p_tcp->m_mct_records + p_tcp->m_nb_mct_records;
memset(l_mct_deco_data, 0,
(p_tcp->m_nb_max_mct_records - p_tcp->m_nb_mct_records) * sizeof(
opj_mct_data_t));
}
l_mct_deco_data = p_tcp->m_mct_records + p_tcp->m_nb_mct_records;
if (l_mct_deco_data->m_data) {
opj_free(l_mct_deco_data->m_data);
l_mct_deco_data->m_data = 00;
}
l_mct_deco_data->m_index = l_indix++;
l_mct_deco_data->m_array_type = MCT_TYPE_DECORRELATION;
l_mct_deco_data->m_element_type = MCT_TYPE_FLOAT;
l_nb_elem = p_image->numcomps * p_image->numcomps;
l_mct_size = l_nb_elem * MCT_ELEMENT_SIZE[l_mct_deco_data->m_element_type];
l_mct_deco_data->m_data = (OPJ_BYTE*)opj_malloc(l_mct_size);
if (! l_mct_deco_data->m_data) {
return OPJ_FALSE;
}
j2k_mct_write_functions_from_float[l_mct_deco_data->m_element_type](
p_tcp->m_mct_decoding_matrix, l_mct_deco_data->m_data, l_nb_elem);
l_mct_deco_data->m_data_size = l_mct_size;
++p_tcp->m_nb_mct_records;
}
if (p_tcp->m_nb_mct_records == p_tcp->m_nb_max_mct_records) {
opj_mct_data_t *new_mct_records;
p_tcp->m_nb_max_mct_records += OPJ_J2K_MCT_DEFAULT_NB_RECORDS;
new_mct_records = (opj_mct_data_t *) opj_realloc(p_tcp->m_mct_records,
p_tcp->m_nb_max_mct_records * sizeof(opj_mct_data_t));
if (! new_mct_records) {
opj_free(p_tcp->m_mct_records);
p_tcp->m_mct_records = NULL;
p_tcp->m_nb_max_mct_records = 0;
p_tcp->m_nb_mct_records = 0;
/* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to setup mct encoding\n"); */
return OPJ_FALSE;
}
p_tcp->m_mct_records = new_mct_records;
l_mct_offset_data = p_tcp->m_mct_records + p_tcp->m_nb_mct_records;
memset(l_mct_offset_data, 0,
(p_tcp->m_nb_max_mct_records - p_tcp->m_nb_mct_records) * sizeof(
opj_mct_data_t));
if (l_mct_deco_data) {
l_mct_deco_data = l_mct_offset_data - 1;
}
}
l_mct_offset_data = p_tcp->m_mct_records + p_tcp->m_nb_mct_records;
if (l_mct_offset_data->m_data) {
opj_free(l_mct_offset_data->m_data);
l_mct_offset_data->m_data = 00;
}
l_mct_offset_data->m_index = l_indix++;
l_mct_offset_data->m_array_type = MCT_TYPE_OFFSET;
l_mct_offset_data->m_element_type = MCT_TYPE_FLOAT;
l_nb_elem = p_image->numcomps;
l_mct_size = l_nb_elem * MCT_ELEMENT_SIZE[l_mct_offset_data->m_element_type];
l_mct_offset_data->m_data = (OPJ_BYTE*)opj_malloc(l_mct_size);
if (! l_mct_offset_data->m_data) {
return OPJ_FALSE;
}
l_data = (OPJ_FLOAT32*)opj_malloc(l_nb_elem * sizeof(OPJ_FLOAT32));
if (! l_data) {
opj_free(l_mct_offset_data->m_data);
l_mct_offset_data->m_data = 00;
return OPJ_FALSE;
}
l_tccp = p_tcp->tccps;
l_current_data = l_data;
for (i = 0; i < l_nb_elem; ++i) {
*(l_current_data++) = (OPJ_FLOAT32)(l_tccp->m_dc_level_shift);
++l_tccp;
}
j2k_mct_write_functions_from_float[l_mct_offset_data->m_element_type](l_data,
l_mct_offset_data->m_data, l_nb_elem);
opj_free(l_data);
l_mct_offset_data->m_data_size = l_mct_size;
++p_tcp->m_nb_mct_records;
if (p_tcp->m_nb_mcc_records == p_tcp->m_nb_max_mcc_records) {
opj_simple_mcc_decorrelation_data_t *new_mcc_records;
p_tcp->m_nb_max_mcc_records += OPJ_J2K_MCT_DEFAULT_NB_RECORDS;
new_mcc_records = (opj_simple_mcc_decorrelation_data_t *) opj_realloc(
p_tcp->m_mcc_records, p_tcp->m_nb_max_mcc_records * sizeof(
opj_simple_mcc_decorrelation_data_t));
if (! new_mcc_records) {
opj_free(p_tcp->m_mcc_records);
p_tcp->m_mcc_records = NULL;
p_tcp->m_nb_max_mcc_records = 0;
p_tcp->m_nb_mcc_records = 0;
/* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to setup mct encoding\n"); */
return OPJ_FALSE;
}
p_tcp->m_mcc_records = new_mcc_records;
l_mcc_data = p_tcp->m_mcc_records + p_tcp->m_nb_mcc_records;
memset(l_mcc_data, 0, (p_tcp->m_nb_max_mcc_records - p_tcp->m_nb_mcc_records) *
sizeof(opj_simple_mcc_decorrelation_data_t));
}
l_mcc_data = p_tcp->m_mcc_records + p_tcp->m_nb_mcc_records;
l_mcc_data->m_decorrelation_array = l_mct_deco_data;
l_mcc_data->m_is_irreversible = 1;
l_mcc_data->m_nb_comps = p_image->numcomps;
l_mcc_data->m_index = l_indix++;
l_mcc_data->m_offset_array = l_mct_offset_data;
++p_tcp->m_nb_mcc_records;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_build_decoder(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
/* add here initialization of cp
copy paste of setup_decoder */
(void)p_j2k;
(void)p_stream;
(void)p_manager;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_build_encoder(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
/* add here initialization of cp
copy paste of setup_encoder */
(void)p_j2k;
(void)p_stream;
(void)p_manager;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_encoding_validation(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_BOOL l_is_valid = OPJ_TRUE;
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_stream);
/* STATE checking */
/* make sure the state is at 0 */
l_is_valid &= (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_NONE);
/* POINTER validation */
/* make sure a p_j2k codec is present */
l_is_valid &= (p_j2k->m_procedure_list != 00);
/* make sure a validation list is present */
l_is_valid &= (p_j2k->m_validation_list != 00);
/* ISO 15444-1:2004 states between 1 & 33 (0 -> 32) */
/* 33 (32) would always fail the check below (if a cast to 64bits was done) */
/* FIXME Shall we change OPJ_J2K_MAXRLVLS to 32 ? */
if ((p_j2k->m_cp.tcps->tccps->numresolutions <= 0) ||
(p_j2k->m_cp.tcps->tccps->numresolutions > 32)) {
opj_event_msg(p_manager, EVT_ERROR,
"Number of resolutions is too high in comparison to the size of tiles\n");
return OPJ_FALSE;
}
if ((p_j2k->m_cp.tdx) < (OPJ_UINT32)(1 <<
(p_j2k->m_cp.tcps->tccps->numresolutions - 1U))) {
opj_event_msg(p_manager, EVT_ERROR,
"Number of resolutions is too high in comparison to the size of tiles\n");
return OPJ_FALSE;
}
if ((p_j2k->m_cp.tdy) < (OPJ_UINT32)(1 <<
(p_j2k->m_cp.tcps->tccps->numresolutions - 1U))) {
opj_event_msg(p_manager, EVT_ERROR,
"Number of resolutions is too high in comparison to the size of tiles\n");
return OPJ_FALSE;
}
/* PARAMETER VALIDATION */
return l_is_valid;
}
static OPJ_BOOL opj_j2k_decoding_validation(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_BOOL l_is_valid = OPJ_TRUE;
/* preconditions*/
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_stream);
OPJ_UNUSED(p_manager);
/* STATE checking */
/* make sure the state is at 0 */
#ifdef TODO_MSD
l_is_valid &= (p_j2k->m_specific_param.m_decoder.m_state == J2K_DEC_STATE_NONE);
#endif
l_is_valid &= (p_j2k->m_specific_param.m_decoder.m_state == 0x0000);
/* POINTER validation */
/* make sure a p_j2k codec is present */
/* make sure a procedure list is present */
l_is_valid &= (p_j2k->m_procedure_list != 00);
/* make sure a validation list is present */
l_is_valid &= (p_j2k->m_validation_list != 00);
/* PARAMETER VALIDATION */
return l_is_valid;
}
static OPJ_BOOL opj_j2k_read_header_procedure(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 l_current_marker;
OPJ_UINT32 l_marker_size;
const opj_dec_memory_marker_handler_t * l_marker_handler = 00;
OPJ_BOOL l_has_siz = 0;
OPJ_BOOL l_has_cod = 0;
OPJ_BOOL l_has_qcd = 0;
/* preconditions */
assert(p_stream != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
/* We enter in the main header */
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_MHSOC;
/* Try to read the SOC marker, the codestream must begin with SOC marker */
if (! opj_j2k_read_soc(p_j2k, p_stream, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Expected a SOC marker \n");
return OPJ_FALSE;
}
/* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* Read 2 bytes as the new marker ID */
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,
&l_current_marker, 2);
/* Try to read until the SOT is detected */
while (l_current_marker != J2K_MS_SOT) {
/* Check if the current marker ID is valid */
if (l_current_marker < 0xff00) {
opj_event_msg(p_manager, EVT_ERROR,
"A marker ID was expected (0xff--) instead of %.8x\n", l_current_marker);
return OPJ_FALSE;
}
/* Get the marker handler from the marker ID */
l_marker_handler = opj_j2k_get_marker_handler(l_current_marker);
/* Manage case where marker is unknown */
if (l_marker_handler->id == J2K_MS_UNK) {
if (! opj_j2k_read_unk(p_j2k, p_stream, &l_current_marker, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR,
"Unknow marker have been detected and generated error.\n");
return OPJ_FALSE;
}
if (l_current_marker == J2K_MS_SOT) {
break; /* SOT marker is detected main header is completely read */
} else { /* Get the marker handler from the marker ID */
l_marker_handler = opj_j2k_get_marker_handler(l_current_marker);
}
}
if (l_marker_handler->id == J2K_MS_SIZ) {
/* Mark required SIZ marker as found */
l_has_siz = 1;
}
if (l_marker_handler->id == J2K_MS_COD) {
/* Mark required COD marker as found */
l_has_cod = 1;
}
if (l_marker_handler->id == J2K_MS_QCD) {
/* Mark required QCD marker as found */
l_has_qcd = 1;
}
/* Check if the marker is known and if it is the right place to find it */
if (!(p_j2k->m_specific_param.m_decoder.m_state & l_marker_handler->states)) {
opj_event_msg(p_manager, EVT_ERROR,
"Marker is not compliant with its position\n");
return OPJ_FALSE;
}
/* Try to read 2 bytes (the marker size) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* read 2 bytes as the marker size */
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data, &l_marker_size,
2);
if (l_marker_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Invalid marker size\n");
return OPJ_FALSE;
}
l_marker_size -= 2; /* Subtract the size of the marker ID already read */
/* Check if the marker size is compatible with the header data size */
if (l_marker_size > p_j2k->m_specific_param.m_decoder.m_header_data_size) {
OPJ_BYTE *new_header_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size);
if (! new_header_data) {
opj_free(p_j2k->m_specific_param.m_decoder.m_header_data);
p_j2k->m_specific_param.m_decoder.m_header_data = NULL;
p_j2k->m_specific_param.m_decoder.m_header_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read header\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_decoder.m_header_data = new_header_data;
p_j2k->m_specific_param.m_decoder.m_header_data_size = l_marker_size;
}
/* Try to read the rest of the marker segment from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size,
p_manager) != l_marker_size) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* Read the marker segment with the correct marker handler */
if (!(*(l_marker_handler->handler))(p_j2k,
p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR,
"Marker handler function failed to read the marker segment\n");
return OPJ_FALSE;
}
/* Add the marker to the codestream index*/
if (OPJ_FALSE == opj_j2k_add_mhmarker(
p_j2k->cstr_index,
l_marker_handler->id,
(OPJ_UINT32) opj_stream_tell(p_stream) - l_marker_size - 4,
l_marker_size + 4)) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add mh marker\n");
return OPJ_FALSE;
}
/* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* read 2 bytes as the new marker ID */
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,
&l_current_marker, 2);
}
if (l_has_siz == 0) {
opj_event_msg(p_manager, EVT_ERROR,
"required SIZ marker not found in main header\n");
return OPJ_FALSE;
}
if (l_has_cod == 0) {
opj_event_msg(p_manager, EVT_ERROR,
"required COD marker not found in main header\n");
return OPJ_FALSE;
}
if (l_has_qcd == 0) {
opj_event_msg(p_manager, EVT_ERROR,
"required QCD marker not found in main header\n");
return OPJ_FALSE;
}
if (! opj_j2k_merge_ppm(&(p_j2k->m_cp), p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Failed to merge PPM data\n");
return OPJ_FALSE;
}
opj_event_msg(p_manager, EVT_INFO, "Main header has been correctly decoded.\n");
/* Position of the last element if the main header */
p_j2k->cstr_index->main_head_end = (OPJ_UINT32) opj_stream_tell(p_stream) - 2;
/* Next step: read a tile-part header */
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPHSOT;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_exec(opj_j2k_t * p_j2k,
opj_procedure_list_t * p_procedure_list,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_BOOL(** l_procedure)(opj_j2k_t *, opj_stream_private_t *,
opj_event_mgr_t *) = 00;
OPJ_BOOL l_result = OPJ_TRUE;
OPJ_UINT32 l_nb_proc, i;
/* preconditions*/
assert(p_procedure_list != 00);
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
l_nb_proc = opj_procedure_list_get_nb_procedures(p_procedure_list);
l_procedure = (OPJ_BOOL(**)(opj_j2k_t *, opj_stream_private_t *,
opj_event_mgr_t *)) opj_procedure_list_get_first_procedure(p_procedure_list);
for (i = 0; i < l_nb_proc; ++i) {
l_result = l_result && ((*l_procedure)(p_j2k, p_stream, p_manager));
++l_procedure;
}
/* and clear the procedure list at the end.*/
opj_procedure_list_clear(p_procedure_list);
return l_result;
}
/* FIXME DOC*/
static OPJ_BOOL opj_j2k_copy_default_tcp_and_create_tcd(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
opj_tcp_t * l_tcp = 00;
opj_tcp_t * l_default_tcp = 00;
OPJ_UINT32 l_nb_tiles;
OPJ_UINT32 i, j;
opj_tccp_t *l_current_tccp = 00;
OPJ_UINT32 l_tccp_size;
OPJ_UINT32 l_mct_size;
opj_image_t * l_image;
OPJ_UINT32 l_mcc_records_size, l_mct_records_size;
opj_mct_data_t * l_src_mct_rec, *l_dest_mct_rec;
opj_simple_mcc_decorrelation_data_t * l_src_mcc_rec, *l_dest_mcc_rec;
OPJ_UINT32 l_offset;
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_stream);
l_image = p_j2k->m_private_image;
l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
l_tcp = p_j2k->m_cp.tcps;
l_tccp_size = l_image->numcomps * (OPJ_UINT32)sizeof(opj_tccp_t);
l_default_tcp = p_j2k->m_specific_param.m_decoder.m_default_tcp;
l_mct_size = l_image->numcomps * l_image->numcomps * (OPJ_UINT32)sizeof(
OPJ_FLOAT32);
/* For each tile */
for (i = 0; i < l_nb_tiles; ++i) {
/* keep the tile-compo coding parameters pointer of the current tile coding parameters*/
l_current_tccp = l_tcp->tccps;
/*Copy default coding parameters into the current tile coding parameters*/
memcpy(l_tcp, l_default_tcp, sizeof(opj_tcp_t));
/* Initialize some values of the current tile coding parameters*/
l_tcp->cod = 0;
l_tcp->ppt = 0;
l_tcp->ppt_data = 00;
l_tcp->m_current_tile_part_number = -1;
/* Remove memory not owned by this tile in case of early error return. */
l_tcp->m_mct_decoding_matrix = 00;
l_tcp->m_nb_max_mct_records = 0;
l_tcp->m_mct_records = 00;
l_tcp->m_nb_max_mcc_records = 0;
l_tcp->m_mcc_records = 00;
/* Reconnect the tile-compo coding parameters pointer to the current tile coding parameters*/
l_tcp->tccps = l_current_tccp;
/* Get the mct_decoding_matrix of the dflt_tile_cp and copy them into the current tile cp*/
if (l_default_tcp->m_mct_decoding_matrix) {
l_tcp->m_mct_decoding_matrix = (OPJ_FLOAT32*)opj_malloc(l_mct_size);
if (! l_tcp->m_mct_decoding_matrix) {
return OPJ_FALSE;
}
memcpy(l_tcp->m_mct_decoding_matrix, l_default_tcp->m_mct_decoding_matrix,
l_mct_size);
}
/* Get the mct_record of the dflt_tile_cp and copy them into the current tile cp*/
l_mct_records_size = l_default_tcp->m_nb_max_mct_records * (OPJ_UINT32)sizeof(
opj_mct_data_t);
l_tcp->m_mct_records = (opj_mct_data_t*)opj_malloc(l_mct_records_size);
if (! l_tcp->m_mct_records) {
return OPJ_FALSE;
}
memcpy(l_tcp->m_mct_records, l_default_tcp->m_mct_records, l_mct_records_size);
/* Copy the mct record data from dflt_tile_cp to the current tile*/
l_src_mct_rec = l_default_tcp->m_mct_records;
l_dest_mct_rec = l_tcp->m_mct_records;
for (j = 0; j < l_default_tcp->m_nb_mct_records; ++j) {
if (l_src_mct_rec->m_data) {
l_dest_mct_rec->m_data = (OPJ_BYTE*) opj_malloc(l_src_mct_rec->m_data_size);
if (! l_dest_mct_rec->m_data) {
return OPJ_FALSE;
}
memcpy(l_dest_mct_rec->m_data, l_src_mct_rec->m_data,
l_src_mct_rec->m_data_size);
}
++l_src_mct_rec;
++l_dest_mct_rec;
/* Update with each pass to free exactly what has been allocated on early return. */
l_tcp->m_nb_max_mct_records += 1;
}
/* Get the mcc_record of the dflt_tile_cp and copy them into the current tile cp*/
l_mcc_records_size = l_default_tcp->m_nb_max_mcc_records * (OPJ_UINT32)sizeof(
opj_simple_mcc_decorrelation_data_t);
l_tcp->m_mcc_records = (opj_simple_mcc_decorrelation_data_t*) opj_malloc(
l_mcc_records_size);
if (! l_tcp->m_mcc_records) {
return OPJ_FALSE;
}
memcpy(l_tcp->m_mcc_records, l_default_tcp->m_mcc_records, l_mcc_records_size);
l_tcp->m_nb_max_mcc_records = l_default_tcp->m_nb_max_mcc_records;
/* Copy the mcc record data from dflt_tile_cp to the current tile*/
l_src_mcc_rec = l_default_tcp->m_mcc_records;
l_dest_mcc_rec = l_tcp->m_mcc_records;
for (j = 0; j < l_default_tcp->m_nb_max_mcc_records; ++j) {
if (l_src_mcc_rec->m_decorrelation_array) {
l_offset = (OPJ_UINT32)(l_src_mcc_rec->m_decorrelation_array -
l_default_tcp->m_mct_records);
l_dest_mcc_rec->m_decorrelation_array = l_tcp->m_mct_records + l_offset;
}
if (l_src_mcc_rec->m_offset_array) {
l_offset = (OPJ_UINT32)(l_src_mcc_rec->m_offset_array -
l_default_tcp->m_mct_records);
l_dest_mcc_rec->m_offset_array = l_tcp->m_mct_records + l_offset;
}
++l_src_mcc_rec;
++l_dest_mcc_rec;
}
/* Copy all the dflt_tile_compo_cp to the current tile cp */
memcpy(l_current_tccp, l_default_tcp->tccps, l_tccp_size);
/* Move to next tile cp*/
++l_tcp;
}
/* Create the current tile decoder*/
p_j2k->m_tcd = (opj_tcd_t*)opj_tcd_create(OPJ_TRUE); /* FIXME why a cast ? */
if (! p_j2k->m_tcd) {
return OPJ_FALSE;
}
if (!opj_tcd_init(p_j2k->m_tcd, l_image, &(p_j2k->m_cp), p_j2k->m_tp)) {
opj_tcd_destroy(p_j2k->m_tcd);
p_j2k->m_tcd = 00;
opj_event_msg(p_manager, EVT_ERROR, "Cannot decode tile, memory error\n");
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static const opj_dec_memory_marker_handler_t * opj_j2k_get_marker_handler(
OPJ_UINT32 p_id)
{
const opj_dec_memory_marker_handler_t *e;
for (e = j2k_memory_marker_handler_tab; e->id != 0; ++e) {
if (e->id == p_id) {
break; /* we find a handler corresponding to the marker ID*/
}
}
return e;
}
void opj_j2k_destroy(opj_j2k_t *p_j2k)
{
if (p_j2k == 00) {
return;
}
if (p_j2k->m_is_decoder) {
if (p_j2k->m_specific_param.m_decoder.m_default_tcp != 00) {
opj_j2k_tcp_destroy(p_j2k->m_specific_param.m_decoder.m_default_tcp);
opj_free(p_j2k->m_specific_param.m_decoder.m_default_tcp);
p_j2k->m_specific_param.m_decoder.m_default_tcp = 00;
}
if (p_j2k->m_specific_param.m_decoder.m_header_data != 00) {
opj_free(p_j2k->m_specific_param.m_decoder.m_header_data);
p_j2k->m_specific_param.m_decoder.m_header_data = 00;
p_j2k->m_specific_param.m_decoder.m_header_data_size = 0;
}
} else {
if (p_j2k->m_specific_param.m_encoder.m_encoded_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_encoded_tile_data);
p_j2k->m_specific_param.m_encoder.m_encoded_tile_data = 00;
}
if (p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer) {
opj_free(p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer);
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer = 00;
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current = 00;
}
if (p_j2k->m_specific_param.m_encoder.m_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = 00;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
}
}
opj_tcd_destroy(p_j2k->m_tcd);
opj_j2k_cp_destroy(&(p_j2k->m_cp));
memset(&(p_j2k->m_cp), 0, sizeof(opj_cp_t));
opj_procedure_list_destroy(p_j2k->m_procedure_list);
p_j2k->m_procedure_list = 00;
opj_procedure_list_destroy(p_j2k->m_validation_list);
p_j2k->m_procedure_list = 00;
j2k_destroy_cstr_index(p_j2k->cstr_index);
p_j2k->cstr_index = NULL;
opj_image_destroy(p_j2k->m_private_image);
p_j2k->m_private_image = NULL;
opj_image_destroy(p_j2k->m_output_image);
p_j2k->m_output_image = NULL;
opj_thread_pool_destroy(p_j2k->m_tp);
p_j2k->m_tp = NULL;
opj_free(p_j2k);
}
void j2k_destroy_cstr_index(opj_codestream_index_t *p_cstr_ind)
{
if (p_cstr_ind) {
if (p_cstr_ind->marker) {
opj_free(p_cstr_ind->marker);
p_cstr_ind->marker = NULL;
}
if (p_cstr_ind->tile_index) {
OPJ_UINT32 it_tile = 0;
for (it_tile = 0; it_tile < p_cstr_ind->nb_of_tiles; it_tile++) {
if (p_cstr_ind->tile_index[it_tile].packet_index) {
opj_free(p_cstr_ind->tile_index[it_tile].packet_index);
p_cstr_ind->tile_index[it_tile].packet_index = NULL;
}
if (p_cstr_ind->tile_index[it_tile].tp_index) {
opj_free(p_cstr_ind->tile_index[it_tile].tp_index);
p_cstr_ind->tile_index[it_tile].tp_index = NULL;
}
if (p_cstr_ind->tile_index[it_tile].marker) {
opj_free(p_cstr_ind->tile_index[it_tile].marker);
p_cstr_ind->tile_index[it_tile].marker = NULL;
}
}
opj_free(p_cstr_ind->tile_index);
p_cstr_ind->tile_index = NULL;
}
opj_free(p_cstr_ind);
}
}
static void opj_j2k_tcp_destroy(opj_tcp_t *p_tcp)
{
if (p_tcp == 00) {
return;
}
if (p_tcp->ppt_markers != 00) {
OPJ_UINT32 i;
for (i = 0U; i < p_tcp->ppt_markers_count; ++i) {
if (p_tcp->ppt_markers[i].m_data != NULL) {
opj_free(p_tcp->ppt_markers[i].m_data);
}
}
p_tcp->ppt_markers_count = 0U;
opj_free(p_tcp->ppt_markers);
p_tcp->ppt_markers = NULL;
}
if (p_tcp->ppt_buffer != 00) {
opj_free(p_tcp->ppt_buffer);
p_tcp->ppt_buffer = 00;
}
if (p_tcp->tccps != 00) {
opj_free(p_tcp->tccps);
p_tcp->tccps = 00;
}
if (p_tcp->m_mct_coding_matrix != 00) {
opj_free(p_tcp->m_mct_coding_matrix);
p_tcp->m_mct_coding_matrix = 00;
}
if (p_tcp->m_mct_decoding_matrix != 00) {
opj_free(p_tcp->m_mct_decoding_matrix);
p_tcp->m_mct_decoding_matrix = 00;
}
if (p_tcp->m_mcc_records) {
opj_free(p_tcp->m_mcc_records);
p_tcp->m_mcc_records = 00;
p_tcp->m_nb_max_mcc_records = 0;
p_tcp->m_nb_mcc_records = 0;
}
if (p_tcp->m_mct_records) {
opj_mct_data_t * l_mct_data = p_tcp->m_mct_records;
OPJ_UINT32 i;
for (i = 0; i < p_tcp->m_nb_mct_records; ++i) {
if (l_mct_data->m_data) {
opj_free(l_mct_data->m_data);
l_mct_data->m_data = 00;
}
++l_mct_data;
}
opj_free(p_tcp->m_mct_records);
p_tcp->m_mct_records = 00;
}
if (p_tcp->mct_norms != 00) {
opj_free(p_tcp->mct_norms);
p_tcp->mct_norms = 00;
}
opj_j2k_tcp_data_destroy(p_tcp);
}
static void opj_j2k_tcp_data_destroy(opj_tcp_t *p_tcp)
{
if (p_tcp->m_data) {
opj_free(p_tcp->m_data);
p_tcp->m_data = NULL;
p_tcp->m_data_size = 0;
}
}
static void opj_j2k_cp_destroy(opj_cp_t *p_cp)
{
OPJ_UINT32 l_nb_tiles;
opj_tcp_t * l_current_tile = 00;
if (p_cp == 00) {
return;
}
if (p_cp->tcps != 00) {
OPJ_UINT32 i;
l_current_tile = p_cp->tcps;
l_nb_tiles = p_cp->th * p_cp->tw;
for (i = 0U; i < l_nb_tiles; ++i) {
opj_j2k_tcp_destroy(l_current_tile);
++l_current_tile;
}
opj_free(p_cp->tcps);
p_cp->tcps = 00;
}
if (p_cp->ppm_markers != 00) {
OPJ_UINT32 i;
for (i = 0U; i < p_cp->ppm_markers_count; ++i) {
if (p_cp->ppm_markers[i].m_data != NULL) {
opj_free(p_cp->ppm_markers[i].m_data);
}
}
p_cp->ppm_markers_count = 0U;
opj_free(p_cp->ppm_markers);
p_cp->ppm_markers = NULL;
}
opj_free(p_cp->ppm_buffer);
p_cp->ppm_buffer = 00;
p_cp->ppm_data =
NULL; /* ppm_data belongs to the allocated buffer pointed by ppm_buffer */
opj_free(p_cp->comment);
p_cp->comment = 00;
if (! p_cp->m_is_decoder) {
opj_free(p_cp->m_specific_param.m_enc.m_matrice);
p_cp->m_specific_param.m_enc.m_matrice = 00;
}
}
static OPJ_BOOL opj_j2k_need_nb_tile_parts_correction(opj_stream_private_t
*p_stream, OPJ_UINT32 tile_no, OPJ_BOOL* p_correction_needed,
opj_event_mgr_t * p_manager)
{
OPJ_BYTE l_header_data[10];
OPJ_OFF_T l_stream_pos_backup;
OPJ_UINT32 l_current_marker;
OPJ_UINT32 l_marker_size;
OPJ_UINT32 l_tile_no, l_tot_len, l_current_part, l_num_parts;
/* initialize to no correction needed */
*p_correction_needed = OPJ_FALSE;
if (!opj_stream_has_seek(p_stream)) {
/* We can't do much in this case, seek is needed */
return OPJ_TRUE;
}
l_stream_pos_backup = opj_stream_tell(p_stream);
if (l_stream_pos_backup == -1) {
/* let's do nothing */
return OPJ_TRUE;
}
for (;;) {
/* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream, l_header_data, 2, p_manager) != 2) {
/* assume all is OK */
if (! opj_stream_seek(p_stream, l_stream_pos_backup, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/* Read 2 bytes from buffer as the new marker ID */
opj_read_bytes(l_header_data, &l_current_marker, 2);
if (l_current_marker != J2K_MS_SOT) {
/* assume all is OK */
if (! opj_stream_seek(p_stream, l_stream_pos_backup, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/* Try to read 2 bytes (the marker size) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream, l_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* Read 2 bytes from the buffer as the marker size */
opj_read_bytes(l_header_data, &l_marker_size, 2);
/* Check marker size for SOT Marker */
if (l_marker_size != 10) {
opj_event_msg(p_manager, EVT_ERROR, "Inconsistent marker size\n");
return OPJ_FALSE;
}
l_marker_size -= 2;
if (opj_stream_read_data(p_stream, l_header_data, l_marker_size,
p_manager) != l_marker_size) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
if (! opj_j2k_get_sot_values(l_header_data, l_marker_size, &l_tile_no,
&l_tot_len, &l_current_part, &l_num_parts, p_manager)) {
return OPJ_FALSE;
}
if (l_tile_no == tile_no) {
/* we found what we were looking for */
break;
}
if ((l_tot_len == 0U) || (l_tot_len < 14U)) {
/* last SOT until EOC or invalid Psot value */
/* assume all is OK */
if (! opj_stream_seek(p_stream, l_stream_pos_backup, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
l_tot_len -= 12U;
/* look for next SOT marker */
if (opj_stream_skip(p_stream, (OPJ_OFF_T)(l_tot_len),
p_manager) != (OPJ_OFF_T)(l_tot_len)) {
/* assume all is OK */
if (! opj_stream_seek(p_stream, l_stream_pos_backup, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
}
/* check for correction */
if (l_current_part == l_num_parts) {
*p_correction_needed = OPJ_TRUE;
}
if (! opj_stream_seek(p_stream, l_stream_pos_backup, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_read_tile_header(opj_j2k_t * p_j2k,
OPJ_UINT32 * p_tile_index,
OPJ_UINT32 * p_data_size,
OPJ_INT32 * p_tile_x0, OPJ_INT32 * p_tile_y0,
OPJ_INT32 * p_tile_x1, OPJ_INT32 * p_tile_y1,
OPJ_UINT32 * p_nb_comps,
OPJ_BOOL * p_go_on,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 l_current_marker = J2K_MS_SOT;
OPJ_UINT32 l_marker_size;
const opj_dec_memory_marker_handler_t * l_marker_handler = 00;
opj_tcp_t * l_tcp = NULL;
/* preconditions */
assert(p_stream != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
/* Reach the End Of Codestream ?*/
if (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_EOC) {
l_current_marker = J2K_MS_EOC;
}
/* We need to encounter a SOT marker (a new tile-part header) */
else if (p_j2k->m_specific_param.m_decoder.m_state != J2K_STATE_TPHSOT) {
return OPJ_FALSE;
}
/* Read into the codestream until reach the EOC or ! can_decode ??? FIXME */
while ((!p_j2k->m_specific_param.m_decoder.m_can_decode) &&
(l_current_marker != J2K_MS_EOC)) {
/* Try to read until the Start Of Data is detected */
while (l_current_marker != J2K_MS_SOD) {
if (opj_stream_get_number_byte_left(p_stream) == 0) {
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_NEOC;
break;
}
/* Try to read 2 bytes (the marker size) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* Read 2 bytes from the buffer as the marker size */
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data, &l_marker_size,
2);
/* Check marker size (does not include marker ID but includes marker size) */
if (l_marker_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Inconsistent marker size\n");
return OPJ_FALSE;
}
/* cf. https://code.google.com/p/openjpeg/issues/detail?id=226 */
if (l_current_marker == 0x8080 &&
opj_stream_get_number_byte_left(p_stream) == 0) {
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_NEOC;
break;
}
/* Why this condition? FIXME */
if (p_j2k->m_specific_param.m_decoder.m_state & J2K_STATE_TPH) {
p_j2k->m_specific_param.m_decoder.m_sot_length -= (l_marker_size + 2);
}
l_marker_size -= 2; /* Subtract the size of the marker ID already read */
/* Get the marker handler from the marker ID */
l_marker_handler = opj_j2k_get_marker_handler(l_current_marker);
/* Check if the marker is known and if it is the right place to find it */
if (!(p_j2k->m_specific_param.m_decoder.m_state & l_marker_handler->states)) {
opj_event_msg(p_manager, EVT_ERROR,
"Marker is not compliant with its position\n");
return OPJ_FALSE;
}
/* FIXME manage case of unknown marker as in the main header ? */
/* Check if the marker size is compatible with the header data size */
if (l_marker_size > p_j2k->m_specific_param.m_decoder.m_header_data_size) {
OPJ_BYTE *new_header_data = NULL;
/* If we are here, this means we consider this marker as known & we will read it */
/* Check enough bytes left in stream before allocation */
if ((OPJ_OFF_T)l_marker_size > opj_stream_get_number_byte_left(p_stream)) {
opj_event_msg(p_manager, EVT_ERROR,
"Marker size inconsistent with stream length\n");
return OPJ_FALSE;
}
new_header_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size);
if (! new_header_data) {
opj_free(p_j2k->m_specific_param.m_decoder.m_header_data);
p_j2k->m_specific_param.m_decoder.m_header_data = NULL;
p_j2k->m_specific_param.m_decoder.m_header_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read header\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_decoder.m_header_data = new_header_data;
p_j2k->m_specific_param.m_decoder.m_header_data_size = l_marker_size;
}
/* Try to read the rest of the marker segment from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size,
p_manager) != l_marker_size) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
if (!l_marker_handler->handler) {
/* See issue #175 */
opj_event_msg(p_manager, EVT_ERROR, "Not sure how that happened.\n");
return OPJ_FALSE;
}
/* Read the marker segment with the correct marker handler */
if (!(*(l_marker_handler->handler))(p_j2k,
p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR,
"Fail to read the current marker segment (%#x)\n", l_current_marker);
return OPJ_FALSE;
}
/* Add the marker to the codestream index*/
if (OPJ_FALSE == opj_j2k_add_tlmarker(p_j2k->m_current_tile_number,
p_j2k->cstr_index,
l_marker_handler->id,
(OPJ_UINT32) opj_stream_tell(p_stream) - l_marker_size - 4,
l_marker_size + 4)) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add tl marker\n");
return OPJ_FALSE;
}
/* Keep the position of the last SOT marker read */
if (l_marker_handler->id == J2K_MS_SOT) {
OPJ_UINT32 sot_pos = (OPJ_UINT32) opj_stream_tell(p_stream) - l_marker_size - 4
;
if (sot_pos > p_j2k->m_specific_param.m_decoder.m_last_sot_read_pos) {
p_j2k->m_specific_param.m_decoder.m_last_sot_read_pos = sot_pos;
}
}
if (p_j2k->m_specific_param.m_decoder.m_skip_data) {
/* Skip the rest of the tile part header*/
if (opj_stream_skip(p_stream, p_j2k->m_specific_param.m_decoder.m_sot_length,
p_manager) != p_j2k->m_specific_param.m_decoder.m_sot_length) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
l_current_marker = J2K_MS_SOD; /* Normally we reached a SOD */
} else {
/* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer*/
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* Read 2 bytes from the buffer as the new marker ID */
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,
&l_current_marker, 2);
}
}
if (opj_stream_get_number_byte_left(p_stream) == 0
&& p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_NEOC) {
break;
}
/* If we didn't skip data before, we need to read the SOD marker*/
if (! p_j2k->m_specific_param.m_decoder.m_skip_data) {
/* Try to read the SOD marker and skip data ? FIXME */
if (! opj_j2k_read_sod(p_j2k, p_stream, p_manager)) {
return OPJ_FALSE;
}
if (p_j2k->m_specific_param.m_decoder.m_can_decode &&
!p_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction_checked) {
/* Issue 254 */
OPJ_BOOL l_correction_needed;
p_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction_checked = 1;
if (!opj_j2k_need_nb_tile_parts_correction(p_stream,
p_j2k->m_current_tile_number, &l_correction_needed, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR,
"opj_j2k_apply_nb_tile_parts_correction error\n");
return OPJ_FALSE;
}
if (l_correction_needed) {
OPJ_UINT32 l_nb_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th;
OPJ_UINT32 l_tile_no;
p_j2k->m_specific_param.m_decoder.m_can_decode = 0;
p_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction = 1;
/* correct tiles */
for (l_tile_no = 0U; l_tile_no < l_nb_tiles; ++l_tile_no) {
if (p_j2k->m_cp.tcps[l_tile_no].m_nb_tile_parts != 0U) {
p_j2k->m_cp.tcps[l_tile_no].m_nb_tile_parts += 1;
}
}
opj_event_msg(p_manager, EVT_WARNING,
"Non conformant codestream TPsot==TNsot.\n");
}
}
if (! p_j2k->m_specific_param.m_decoder.m_can_decode) {
/* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* Read 2 bytes from buffer as the new marker ID */
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,
&l_current_marker, 2);
}
} else {
/* Indicate we will try to read a new tile-part header*/
p_j2k->m_specific_param.m_decoder.m_skip_data = 0;
p_j2k->m_specific_param.m_decoder.m_can_decode = 0;
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPHSOT;
/* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* Read 2 bytes from buffer as the new marker ID */
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,
&l_current_marker, 2);
}
}
/* Current marker is the EOC marker ?*/
if (l_current_marker == J2K_MS_EOC) {
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_EOC;
}
/* FIXME DOC ???*/
if (! p_j2k->m_specific_param.m_decoder.m_can_decode) {
OPJ_UINT32 l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
l_tcp = p_j2k->m_cp.tcps + p_j2k->m_current_tile_number;
while ((p_j2k->m_current_tile_number < l_nb_tiles) && (l_tcp->m_data == 00)) {
++p_j2k->m_current_tile_number;
++l_tcp;
}
if (p_j2k->m_current_tile_number == l_nb_tiles) {
*p_go_on = OPJ_FALSE;
return OPJ_TRUE;
}
}
if (! opj_j2k_merge_ppt(p_j2k->m_cp.tcps + p_j2k->m_current_tile_number,
p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Failed to merge PPT data\n");
return OPJ_FALSE;
}
/*FIXME ???*/
if (! opj_tcd_init_decode_tile(p_j2k->m_tcd, p_j2k->m_current_tile_number,
p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Cannot decode tile, memory error\n");
return OPJ_FALSE;
}
opj_event_msg(p_manager, EVT_INFO, "Header of tile %d / %d has been read.\n",
p_j2k->m_current_tile_number + 1, (p_j2k->m_cp.th * p_j2k->m_cp.tw));
*p_tile_index = p_j2k->m_current_tile_number;
*p_go_on = OPJ_TRUE;
*p_data_size = opj_tcd_get_decoded_tile_size(p_j2k->m_tcd);
if (*p_data_size == UINT_MAX) {
return OPJ_FALSE;
}
*p_tile_x0 = p_j2k->m_tcd->tcd_image->tiles->x0;
*p_tile_y0 = p_j2k->m_tcd->tcd_image->tiles->y0;
*p_tile_x1 = p_j2k->m_tcd->tcd_image->tiles->x1;
*p_tile_y1 = p_j2k->m_tcd->tcd_image->tiles->y1;
*p_nb_comps = p_j2k->m_tcd->tcd_image->tiles->numcomps;
p_j2k->m_specific_param.m_decoder.m_state |= J2K_STATE_DATA;
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_decode_tile(opj_j2k_t * p_j2k,
OPJ_UINT32 p_tile_index,
OPJ_BYTE * p_data,
OPJ_UINT32 p_data_size,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 l_current_marker;
OPJ_BYTE l_data [2];
opj_tcp_t * l_tcp;
/* preconditions */
assert(p_stream != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
if (!(p_j2k->m_specific_param.m_decoder.m_state & J2K_STATE_DATA)
|| (p_tile_index != p_j2k->m_current_tile_number)) {
return OPJ_FALSE;
}
l_tcp = &(p_j2k->m_cp.tcps[p_tile_index]);
if (! l_tcp->m_data) {
opj_j2k_tcp_destroy(l_tcp);
return OPJ_FALSE;
}
if (! opj_tcd_decode_tile(p_j2k->m_tcd,
l_tcp->m_data,
l_tcp->m_data_size,
p_tile_index,
p_j2k->cstr_index, p_manager)) {
opj_j2k_tcp_destroy(l_tcp);
p_j2k->m_specific_param.m_decoder.m_state |= J2K_STATE_ERR;
opj_event_msg(p_manager, EVT_ERROR, "Failed to decode.\n");
return OPJ_FALSE;
}
/* p_data can be set to NULL when the call will take care of using */
/* itself the TCD data. This is typically the case for whole single */
/* tile decoding optimization. */
if (p_data != NULL) {
if (! opj_tcd_update_tile_data(p_j2k->m_tcd, p_data, p_data_size)) {
return OPJ_FALSE;
}
/* To avoid to destroy the tcp which can be useful when we try to decode a tile decoded before (cf j2k_random_tile_access)
* we destroy just the data which will be re-read in read_tile_header*/
/*opj_j2k_tcp_destroy(l_tcp);
p_j2k->m_tcd->tcp = 0;*/
opj_j2k_tcp_data_destroy(l_tcp);
}
p_j2k->m_specific_param.m_decoder.m_can_decode = 0;
p_j2k->m_specific_param.m_decoder.m_state &= (~(OPJ_UINT32)J2K_STATE_DATA);
if (opj_stream_get_number_byte_left(p_stream) == 0
&& p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_NEOC) {
return OPJ_TRUE;
}
if (p_j2k->m_specific_param.m_decoder.m_state != J2K_STATE_EOC) {
if (opj_stream_read_data(p_stream, l_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
opj_read_bytes(l_data, &l_current_marker, 2);
if (l_current_marker == J2K_MS_EOC) {
p_j2k->m_current_tile_number = 0;
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_EOC;
} else if (l_current_marker != J2K_MS_SOT) {
if (opj_stream_get_number_byte_left(p_stream) == 0) {
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_NEOC;
opj_event_msg(p_manager, EVT_WARNING, "Stream does not end with EOC\n");
return OPJ_TRUE;
}
opj_event_msg(p_manager, EVT_ERROR, "Stream too short, expected SOT\n");
return OPJ_FALSE;
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_update_image_data(opj_tcd_t * p_tcd, OPJ_BYTE * p_data,
opj_image_t* p_output_image)
{
OPJ_UINT32 i, j, k = 0;
OPJ_UINT32 l_width_src, l_height_src;
OPJ_UINT32 l_width_dest, l_height_dest;
OPJ_INT32 l_offset_x0_src, l_offset_y0_src, l_offset_x1_src, l_offset_y1_src;
OPJ_SIZE_T l_start_offset_src, l_line_offset_src, l_end_offset_src ;
OPJ_UINT32 l_start_x_dest, l_start_y_dest;
OPJ_UINT32 l_x0_dest, l_y0_dest, l_x1_dest, l_y1_dest;
OPJ_SIZE_T l_start_offset_dest, l_line_offset_dest;
opj_image_comp_t * l_img_comp_src = 00;
opj_image_comp_t * l_img_comp_dest = 00;
opj_tcd_tilecomp_t * l_tilec = 00;
opj_image_t * l_image_src = 00;
OPJ_UINT32 l_size_comp, l_remaining;
OPJ_INT32 * l_dest_ptr;
opj_tcd_resolution_t* l_res = 00;
l_tilec = p_tcd->tcd_image->tiles->comps;
l_image_src = p_tcd->image;
l_img_comp_src = l_image_src->comps;
l_img_comp_dest = p_output_image->comps;
for (i = 0; i < l_image_src->numcomps; i++) {
/* Allocate output component buffer if necessary */
if (!l_img_comp_dest->data) {
OPJ_SIZE_T l_width = l_img_comp_dest->w;
OPJ_SIZE_T l_height = l_img_comp_dest->h;
if ((l_height == 0U) || (l_width > (SIZE_MAX / l_height)) ||
l_width * l_height > SIZE_MAX / sizeof(OPJ_INT32)) {
/* would overflow */
return OPJ_FALSE;
}
l_img_comp_dest->data = (OPJ_INT32*) opj_image_data_alloc(l_width * l_height *
sizeof(OPJ_INT32));
if (! l_img_comp_dest->data) {
return OPJ_FALSE;
}
/* Do we really need this memset ? */
memset(l_img_comp_dest->data, 0, l_width * l_height * sizeof(OPJ_INT32));
}
/* Copy info from decoded comp image to output image */
l_img_comp_dest->resno_decoded = l_img_comp_src->resno_decoded;
/*-----*/
/* Compute the precision of the output buffer */
l_size_comp = l_img_comp_src->prec >> 3; /*(/ 8)*/
l_remaining = l_img_comp_src->prec & 7; /* (%8) */
l_res = l_tilec->resolutions + l_img_comp_src->resno_decoded;
if (l_remaining) {
++l_size_comp;
}
if (l_size_comp == 3) {
l_size_comp = 4;
}
/*-----*/
/* Current tile component size*/
/*if (i == 0) {
fprintf(stdout, "SRC: l_res_x0=%d, l_res_x1=%d, l_res_y0=%d, l_res_y1=%d\n",
l_res->x0, l_res->x1, l_res->y0, l_res->y1);
}*/
l_width_src = (OPJ_UINT32)(l_res->x1 - l_res->x0);
l_height_src = (OPJ_UINT32)(l_res->y1 - l_res->y0);
/* Border of the current output component*/
l_x0_dest = opj_uint_ceildivpow2(l_img_comp_dest->x0, l_img_comp_dest->factor);
l_y0_dest = opj_uint_ceildivpow2(l_img_comp_dest->y0, l_img_comp_dest->factor);
l_x1_dest = l_x0_dest +
l_img_comp_dest->w; /* can't overflow given that image->x1 is uint32 */
l_y1_dest = l_y0_dest + l_img_comp_dest->h;
/*if (i == 0) {
fprintf(stdout, "DEST: l_x0_dest=%d, l_x1_dest=%d, l_y0_dest=%d, l_y1_dest=%d (%d)\n",
l_x0_dest, l_x1_dest, l_y0_dest, l_y1_dest, l_img_comp_dest->factor );
}*/
/*-----*/
/* Compute the area (l_offset_x0_src, l_offset_y0_src, l_offset_x1_src, l_offset_y1_src)
* of the input buffer (decoded tile component) which will be move
* in the output buffer. Compute the area of the output buffer (l_start_x_dest,
* l_start_y_dest, l_width_dest, l_height_dest) which will be modified
* by this input area.
* */
assert(l_res->x0 >= 0);
assert(l_res->x1 >= 0);
if (l_x0_dest < (OPJ_UINT32)l_res->x0) {
l_start_x_dest = (OPJ_UINT32)l_res->x0 - l_x0_dest;
l_offset_x0_src = 0;
if (l_x1_dest >= (OPJ_UINT32)l_res->x1) {
l_width_dest = l_width_src;
l_offset_x1_src = 0;
} else {
l_width_dest = l_x1_dest - (OPJ_UINT32)l_res->x0 ;
l_offset_x1_src = (OPJ_INT32)(l_width_src - l_width_dest);
}
} else {
l_start_x_dest = 0U;
l_offset_x0_src = (OPJ_INT32)l_x0_dest - l_res->x0;
if (l_x1_dest >= (OPJ_UINT32)l_res->x1) {
l_width_dest = l_width_src - (OPJ_UINT32)l_offset_x0_src;
l_offset_x1_src = 0;
} else {
l_width_dest = l_img_comp_dest->w ;
l_offset_x1_src = l_res->x1 - (OPJ_INT32)l_x1_dest;
}
}
if (l_y0_dest < (OPJ_UINT32)l_res->y0) {
l_start_y_dest = (OPJ_UINT32)l_res->y0 - l_y0_dest;
l_offset_y0_src = 0;
if (l_y1_dest >= (OPJ_UINT32)l_res->y1) {
l_height_dest = l_height_src;
l_offset_y1_src = 0;
} else {
l_height_dest = l_y1_dest - (OPJ_UINT32)l_res->y0 ;
l_offset_y1_src = (OPJ_INT32)(l_height_src - l_height_dest);
}
} else {
l_start_y_dest = 0U;
l_offset_y0_src = (OPJ_INT32)l_y0_dest - l_res->y0;
if (l_y1_dest >= (OPJ_UINT32)l_res->y1) {
l_height_dest = l_height_src - (OPJ_UINT32)l_offset_y0_src;
l_offset_y1_src = 0;
} else {
l_height_dest = l_img_comp_dest->h ;
l_offset_y1_src = l_res->y1 - (OPJ_INT32)l_y1_dest;
}
}
if ((l_offset_x0_src < 0) || (l_offset_y0_src < 0) || (l_offset_x1_src < 0) ||
(l_offset_y1_src < 0)) {
return OPJ_FALSE;
}
/* testcase 2977.pdf.asan.67.2198 */
if ((OPJ_INT32)l_width_dest < 0 || (OPJ_INT32)l_height_dest < 0) {
return OPJ_FALSE;
}
/*-----*/
/* Compute the input buffer offset */
l_start_offset_src = (OPJ_SIZE_T)l_offset_x0_src + (OPJ_SIZE_T)l_offset_y0_src
* (OPJ_SIZE_T)l_width_src;
l_line_offset_src = (OPJ_SIZE_T)l_offset_x1_src + (OPJ_SIZE_T)l_offset_x0_src;
l_end_offset_src = (OPJ_SIZE_T)l_offset_y1_src * (OPJ_SIZE_T)l_width_src -
(OPJ_SIZE_T)l_offset_x0_src;
/* Compute the output buffer offset */
l_start_offset_dest = (OPJ_SIZE_T)l_start_x_dest + (OPJ_SIZE_T)l_start_y_dest
* (OPJ_SIZE_T)l_img_comp_dest->w;
l_line_offset_dest = (OPJ_SIZE_T)l_img_comp_dest->w - (OPJ_SIZE_T)l_width_dest;
/* Move the output buffer to the first place where we will write*/
l_dest_ptr = l_img_comp_dest->data + l_start_offset_dest;
/*if (i == 0) {
fprintf(stdout, "COMPO[%d]:\n",i);
fprintf(stdout, "SRC: l_start_x_src=%d, l_start_y_src=%d, l_width_src=%d, l_height_src=%d\n"
"\t tile offset:%d, %d, %d, %d\n"
"\t buffer offset: %d; %d, %d\n",
l_res->x0, l_res->y0, l_width_src, l_height_src,
l_offset_x0_src, l_offset_y0_src, l_offset_x1_src, l_offset_y1_src,
l_start_offset_src, l_line_offset_src, l_end_offset_src);
fprintf(stdout, "DEST: l_start_x_dest=%d, l_start_y_dest=%d, l_width_dest=%d, l_height_dest=%d\n"
"\t start offset: %d, line offset= %d\n",
l_start_x_dest, l_start_y_dest, l_width_dest, l_height_dest, l_start_offset_dest, l_line_offset_dest);
}*/
switch (l_size_comp) {
case 1: {
OPJ_CHAR * l_src_ptr = (OPJ_CHAR*) p_data;
l_src_ptr += l_start_offset_src; /* Move to the first place where we will read*/
if (l_img_comp_src->sgnd) {
for (j = 0 ; j < l_height_dest ; ++j) {
for (k = 0 ; k < l_width_dest ; ++k) {
*(l_dest_ptr++) = (OPJ_INT32)(*
(l_src_ptr++)); /* Copy only the data needed for the output image */
}
l_dest_ptr +=
l_line_offset_dest; /* Move to the next place where we will write */
l_src_ptr += l_line_offset_src ; /* Move to the next place where we will read */
}
} else {
for (j = 0 ; j < l_height_dest ; ++j) {
for (k = 0 ; k < l_width_dest ; ++k) {
*(l_dest_ptr++) = (OPJ_INT32)((*(l_src_ptr++)) & 0xff);
}
l_dest_ptr += l_line_offset_dest;
l_src_ptr += l_line_offset_src;
}
}
l_src_ptr +=
l_end_offset_src; /* Move to the end of this component-part of the input buffer */
p_data = (OPJ_BYTE*)
l_src_ptr; /* Keep the current position for the next component-part */
}
break;
case 2: {
OPJ_INT16 * l_src_ptr = (OPJ_INT16 *) p_data;
l_src_ptr += l_start_offset_src;
if (l_img_comp_src->sgnd) {
for (j = 0; j < l_height_dest; ++j) {
for (k = 0; k < l_width_dest; ++k) {
OPJ_INT16 val;
memcpy(&val, l_src_ptr, sizeof(val));
l_src_ptr ++;
*(l_dest_ptr++) = val;
}
l_dest_ptr += l_line_offset_dest;
l_src_ptr += l_line_offset_src ;
}
} else {
for (j = 0; j < l_height_dest; ++j) {
for (k = 0; k < l_width_dest; ++k) {
OPJ_INT16 val;
memcpy(&val, l_src_ptr, sizeof(val));
l_src_ptr ++;
*(l_dest_ptr++) = val & 0xffff;
}
l_dest_ptr += l_line_offset_dest;
l_src_ptr += l_line_offset_src ;
}
}
l_src_ptr += l_end_offset_src;
p_data = (OPJ_BYTE*) l_src_ptr;
}
break;
case 4: {
OPJ_INT32 * l_src_ptr = (OPJ_INT32 *) p_data;
l_src_ptr += l_start_offset_src;
for (j = 0; j < l_height_dest; ++j) {
memcpy(l_dest_ptr, l_src_ptr, l_width_dest * sizeof(OPJ_INT32));
l_dest_ptr += l_width_dest + l_line_offset_dest;
l_src_ptr += l_width_dest + l_line_offset_src ;
}
l_src_ptr += l_end_offset_src;
p_data = (OPJ_BYTE*) l_src_ptr;
}
break;
}
++l_img_comp_dest;
++l_img_comp_src;
++l_tilec;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_set_decode_area(opj_j2k_t *p_j2k,
opj_image_t* p_image,
OPJ_INT32 p_start_x, OPJ_INT32 p_start_y,
OPJ_INT32 p_end_x, OPJ_INT32 p_end_y,
opj_event_mgr_t * p_manager)
{
opj_cp_t * l_cp = &(p_j2k->m_cp);
opj_image_t * l_image = p_j2k->m_private_image;
OPJ_UINT32 it_comp;
OPJ_INT32 l_comp_x1, l_comp_y1;
opj_image_comp_t* l_img_comp = NULL;
/* Check if we are read the main header */
if (p_j2k->m_specific_param.m_decoder.m_state != J2K_STATE_TPHSOT) {
opj_event_msg(p_manager, EVT_ERROR,
"Need to decode the main header before begin to decode the remaining codestream");
return OPJ_FALSE;
}
if (!p_start_x && !p_start_y && !p_end_x && !p_end_y) {
opj_event_msg(p_manager, EVT_INFO,
"No decoded area parameters, set the decoded area to the whole image\n");
p_j2k->m_specific_param.m_decoder.m_start_tile_x = 0;
p_j2k->m_specific_param.m_decoder.m_start_tile_y = 0;
p_j2k->m_specific_param.m_decoder.m_end_tile_x = l_cp->tw;
p_j2k->m_specific_param.m_decoder.m_end_tile_y = l_cp->th;
return OPJ_TRUE;
}
/* ----- */
/* Check if the positions provided by the user are correct */
/* Left */
if (p_start_x < 0) {
opj_event_msg(p_manager, EVT_ERROR,
"Left position of the decoded area (region_x0=%d) should be >= 0.\n",
p_start_x);
return OPJ_FALSE;
} else if ((OPJ_UINT32)p_start_x > l_image->x1) {
opj_event_msg(p_manager, EVT_ERROR,
"Left position of the decoded area (region_x0=%d) is outside the image area (Xsiz=%d).\n",
p_start_x, l_image->x1);
return OPJ_FALSE;
} else if ((OPJ_UINT32)p_start_x < l_image->x0) {
opj_event_msg(p_manager, EVT_WARNING,
"Left position of the decoded area (region_x0=%d) is outside the image area (XOsiz=%d).\n",
p_start_x, l_image->x0);
p_j2k->m_specific_param.m_decoder.m_start_tile_x = 0;
p_image->x0 = l_image->x0;
} else {
p_j2k->m_specific_param.m_decoder.m_start_tile_x = ((OPJ_UINT32)p_start_x -
l_cp->tx0) / l_cp->tdx;
p_image->x0 = (OPJ_UINT32)p_start_x;
}
/* Up */
if (p_start_x < 0) {
opj_event_msg(p_manager, EVT_ERROR,
"Up position of the decoded area (region_y0=%d) should be >= 0.\n",
p_start_y);
return OPJ_FALSE;
} else if ((OPJ_UINT32)p_start_y > l_image->y1) {
opj_event_msg(p_manager, EVT_ERROR,
"Up position of the decoded area (region_y0=%d) is outside the image area (Ysiz=%d).\n",
p_start_y, l_image->y1);
return OPJ_FALSE;
} else if ((OPJ_UINT32)p_start_y < l_image->y0) {
opj_event_msg(p_manager, EVT_WARNING,
"Up position of the decoded area (region_y0=%d) is outside the image area (YOsiz=%d).\n",
p_start_y, l_image->y0);
p_j2k->m_specific_param.m_decoder.m_start_tile_y = 0;
p_image->y0 = l_image->y0;
} else {
p_j2k->m_specific_param.m_decoder.m_start_tile_y = ((OPJ_UINT32)p_start_y -
l_cp->ty0) / l_cp->tdy;
p_image->y0 = (OPJ_UINT32)p_start_y;
}
/* Right */
if (p_end_x <= 0) {
opj_event_msg(p_manager, EVT_ERROR,
"Right position of the decoded area (region_x1=%d) should be > 0.\n",
p_end_x);
return OPJ_FALSE;
} else if ((OPJ_UINT32)p_end_x < l_image->x0) {
opj_event_msg(p_manager, EVT_ERROR,
"Right position of the decoded area (region_x1=%d) is outside the image area (XOsiz=%d).\n",
p_end_x, l_image->x0);
return OPJ_FALSE;
} else if ((OPJ_UINT32)p_end_x > l_image->x1) {
opj_event_msg(p_manager, EVT_WARNING,
"Right position of the decoded area (region_x1=%d) is outside the image area (Xsiz=%d).\n",
p_end_x, l_image->x1);
p_j2k->m_specific_param.m_decoder.m_end_tile_x = l_cp->tw;
p_image->x1 = l_image->x1;
} else {
p_j2k->m_specific_param.m_decoder.m_end_tile_x = (OPJ_UINT32)opj_int_ceildiv(
p_end_x - (OPJ_INT32)l_cp->tx0, (OPJ_INT32)l_cp->tdx);
p_image->x1 = (OPJ_UINT32)p_end_x;
}
/* Bottom */
if (p_end_y <= 0) {
opj_event_msg(p_manager, EVT_ERROR,
"Bottom position of the decoded area (region_y1=%d) should be > 0.\n",
p_end_y);
return OPJ_FALSE;
} else if ((OPJ_UINT32)p_end_y < l_image->y0) {
opj_event_msg(p_manager, EVT_ERROR,
"Bottom position of the decoded area (region_y1=%d) is outside the image area (YOsiz=%d).\n",
p_end_y, l_image->y0);
return OPJ_FALSE;
}
if ((OPJ_UINT32)p_end_y > l_image->y1) {
opj_event_msg(p_manager, EVT_WARNING,
"Bottom position of the decoded area (region_y1=%d) is outside the image area (Ysiz=%d).\n",
p_end_y, l_image->y1);
p_j2k->m_specific_param.m_decoder.m_end_tile_y = l_cp->th;
p_image->y1 = l_image->y1;
} else {
p_j2k->m_specific_param.m_decoder.m_end_tile_y = (OPJ_UINT32)opj_int_ceildiv(
p_end_y - (OPJ_INT32)l_cp->ty0, (OPJ_INT32)l_cp->tdy);
p_image->y1 = (OPJ_UINT32)p_end_y;
}
/* ----- */
p_j2k->m_specific_param.m_decoder.m_discard_tiles = 1;
l_img_comp = p_image->comps;
for (it_comp = 0; it_comp < p_image->numcomps; ++it_comp) {
OPJ_INT32 l_h, l_w;
l_img_comp->x0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->x0,
(OPJ_INT32)l_img_comp->dx);
l_img_comp->y0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->y0,
(OPJ_INT32)l_img_comp->dy);
l_comp_x1 = opj_int_ceildiv((OPJ_INT32)p_image->x1, (OPJ_INT32)l_img_comp->dx);
l_comp_y1 = opj_int_ceildiv((OPJ_INT32)p_image->y1, (OPJ_INT32)l_img_comp->dy);
l_w = opj_int_ceildivpow2(l_comp_x1, (OPJ_INT32)l_img_comp->factor)
- opj_int_ceildivpow2((OPJ_INT32)l_img_comp->x0, (OPJ_INT32)l_img_comp->factor);
if (l_w < 0) {
opj_event_msg(p_manager, EVT_ERROR,
"Size x of the decoded component image is incorrect (comp[%d].w=%d).\n",
it_comp, l_w);
return OPJ_FALSE;
}
l_img_comp->w = (OPJ_UINT32)l_w;
l_h = opj_int_ceildivpow2(l_comp_y1, (OPJ_INT32)l_img_comp->factor)
- opj_int_ceildivpow2((OPJ_INT32)l_img_comp->y0, (OPJ_INT32)l_img_comp->factor);
if (l_h < 0) {
opj_event_msg(p_manager, EVT_ERROR,
"Size y of the decoded component image is incorrect (comp[%d].h=%d).\n",
it_comp, l_h);
return OPJ_FALSE;
}
l_img_comp->h = (OPJ_UINT32)l_h;
l_img_comp++;
}
opj_event_msg(p_manager, EVT_INFO, "Setting decoding area to %d,%d,%d,%d\n",
p_image->x0, p_image->y0, p_image->x1, p_image->y1);
return OPJ_TRUE;
}
opj_j2k_t* opj_j2k_create_decompress(void)
{
opj_j2k_t *l_j2k = (opj_j2k_t*) opj_calloc(1, sizeof(opj_j2k_t));
if (!l_j2k) {
return 00;
}
l_j2k->m_is_decoder = 1;
l_j2k->m_cp.m_is_decoder = 1;
/* in the absence of JP2 boxes, consider different bit depth / sign */
/* per component is allowed */
l_j2k->m_cp.allow_different_bit_depth_sign = 1;
#ifdef OPJ_DISABLE_TPSOT_FIX
l_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction_checked = 1;
#endif
l_j2k->m_specific_param.m_decoder.m_default_tcp = (opj_tcp_t*) opj_calloc(1,
sizeof(opj_tcp_t));
if (!l_j2k->m_specific_param.m_decoder.m_default_tcp) {
opj_j2k_destroy(l_j2k);
return 00;
}
l_j2k->m_specific_param.m_decoder.m_header_data = (OPJ_BYTE *) opj_calloc(1,
OPJ_J2K_DEFAULT_HEADER_SIZE);
if (! l_j2k->m_specific_param.m_decoder.m_header_data) {
opj_j2k_destroy(l_j2k);
return 00;
}
l_j2k->m_specific_param.m_decoder.m_header_data_size =
OPJ_J2K_DEFAULT_HEADER_SIZE;
l_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec = -1 ;
l_j2k->m_specific_param.m_decoder.m_last_sot_read_pos = 0 ;
/* codestream index creation */
l_j2k->cstr_index = opj_j2k_create_cstr_index();
if (!l_j2k->cstr_index) {
opj_j2k_destroy(l_j2k);
return 00;
}
/* validation list creation */
l_j2k->m_validation_list = opj_procedure_list_create();
if (! l_j2k->m_validation_list) {
opj_j2k_destroy(l_j2k);
return 00;
}
/* execution list creation */
l_j2k->m_procedure_list = opj_procedure_list_create();
if (! l_j2k->m_procedure_list) {
opj_j2k_destroy(l_j2k);
return 00;
}
l_j2k->m_tp = opj_thread_pool_create(opj_j2k_get_default_thread_count());
if (!l_j2k->m_tp) {
l_j2k->m_tp = opj_thread_pool_create(0);
}
if (!l_j2k->m_tp) {
opj_j2k_destroy(l_j2k);
return NULL;
}
return l_j2k;
}
static opj_codestream_index_t* opj_j2k_create_cstr_index(void)
{
opj_codestream_index_t* cstr_index = (opj_codestream_index_t*)
opj_calloc(1, sizeof(opj_codestream_index_t));
if (!cstr_index) {
return NULL;
}
cstr_index->maxmarknum = 100;
cstr_index->marknum = 0;
cstr_index->marker = (opj_marker_info_t*)
opj_calloc(cstr_index->maxmarknum, sizeof(opj_marker_info_t));
if (!cstr_index-> marker) {
opj_free(cstr_index);
return NULL;
}
cstr_index->tile_index = NULL;
return cstr_index;
}
static OPJ_UINT32 opj_j2k_get_SPCod_SPCoc_size(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no)
{
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_tccp_t *l_tccp = 00;
/* preconditions */
assert(p_j2k != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_tile_no];
l_tccp = &l_tcp->tccps[p_comp_no];
/* preconditions again */
assert(p_tile_no < (l_cp->tw * l_cp->th));
assert(p_comp_no < p_j2k->m_private_image->numcomps);
if (l_tccp->csty & J2K_CCP_CSTY_PRT) {
return 5 + l_tccp->numresolutions;
} else {
return 5;
}
}
static OPJ_BOOL opj_j2k_compare_SPCod_SPCoc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no)
{
OPJ_UINT32 i;
opj_cp_t *l_cp = NULL;
opj_tcp_t *l_tcp = NULL;
opj_tccp_t *l_tccp0 = NULL;
opj_tccp_t *l_tccp1 = NULL;
/* preconditions */
assert(p_j2k != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_tile_no];
l_tccp0 = &l_tcp->tccps[p_first_comp_no];
l_tccp1 = &l_tcp->tccps[p_second_comp_no];
if (l_tccp0->numresolutions != l_tccp1->numresolutions) {
return OPJ_FALSE;
}
if (l_tccp0->cblkw != l_tccp1->cblkw) {
return OPJ_FALSE;
}
if (l_tccp0->cblkh != l_tccp1->cblkh) {
return OPJ_FALSE;
}
if (l_tccp0->cblksty != l_tccp1->cblksty) {
return OPJ_FALSE;
}
if (l_tccp0->qmfbid != l_tccp1->qmfbid) {
return OPJ_FALSE;
}
if ((l_tccp0->csty & J2K_CCP_CSTY_PRT) != (l_tccp1->csty & J2K_CCP_CSTY_PRT)) {
return OPJ_FALSE;
}
for (i = 0U; i < l_tccp0->numresolutions; ++i) {
if (l_tccp0->prcw[i] != l_tccp1->prcw[i]) {
return OPJ_FALSE;
}
if (l_tccp0->prch[i] != l_tccp1->prch[i]) {
return OPJ_FALSE;
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_SPCod_SPCoc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_header_size,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 i;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_tccp_t *l_tccp = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_header_size != 00);
assert(p_manager != 00);
assert(p_data != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_tile_no];
l_tccp = &l_tcp->tccps[p_comp_no];
/* preconditions again */
assert(p_tile_no < (l_cp->tw * l_cp->th));
assert(p_comp_no < (p_j2k->m_private_image->numcomps));
if (*p_header_size < 5) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing SPCod SPCoc element\n");
return OPJ_FALSE;
}
opj_write_bytes(p_data, l_tccp->numresolutions - 1, 1); /* SPcoc (D) */
++p_data;
opj_write_bytes(p_data, l_tccp->cblkw - 2, 1); /* SPcoc (E) */
++p_data;
opj_write_bytes(p_data, l_tccp->cblkh - 2, 1); /* SPcoc (F) */
++p_data;
opj_write_bytes(p_data, l_tccp->cblksty,
1); /* SPcoc (G) */
++p_data;
opj_write_bytes(p_data, l_tccp->qmfbid,
1); /* SPcoc (H) */
++p_data;
*p_header_size = *p_header_size - 5;
if (l_tccp->csty & J2K_CCP_CSTY_PRT) {
if (*p_header_size < l_tccp->numresolutions) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing SPCod SPCoc element\n");
return OPJ_FALSE;
}
for (i = 0; i < l_tccp->numresolutions; ++i) {
opj_write_bytes(p_data, l_tccp->prcw[i] + (l_tccp->prch[i] << 4),
1); /* SPcoc (I_i) */
++p_data;
}
*p_header_size = *p_header_size - l_tccp->numresolutions;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_read_SPCod_SPCoc(opj_j2k_t *p_j2k,
OPJ_UINT32 compno,
OPJ_BYTE * p_header_data,
OPJ_UINT32 * p_header_size,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 i, l_tmp;
opj_cp_t *l_cp = NULL;
opj_tcp_t *l_tcp = NULL;
opj_tccp_t *l_tccp = NULL;
OPJ_BYTE * l_current_ptr = NULL;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_header_data != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
/* precondition again */
assert(compno < p_j2k->m_private_image->numcomps);
l_tccp = &l_tcp->tccps[compno];
l_current_ptr = p_header_data;
/* make sure room is sufficient */
if (*p_header_size < 5) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading SPCod SPCoc element\n");
return OPJ_FALSE;
}
opj_read_bytes(l_current_ptr, &l_tccp->numresolutions,
1); /* SPcox (D) */
++l_tccp->numresolutions; /* tccp->numresolutions = read() + 1 */
if (l_tccp->numresolutions > OPJ_J2K_MAXRLVLS) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid value for numresolutions : %d, max value is set in openjpeg.h at %d\n",
l_tccp->numresolutions, OPJ_J2K_MAXRLVLS);
return OPJ_FALSE;
}
++l_current_ptr;
/* If user wants to remove more resolutions than the codestream contains, return error */
if (l_cp->m_specific_param.m_dec.m_reduce >= l_tccp->numresolutions) {
opj_event_msg(p_manager, EVT_ERROR,
"Error decoding component %d.\nThe number of resolutions to remove is higher than the number "
"of resolutions of this component\nModify the cp_reduce parameter.\n\n",
compno);
p_j2k->m_specific_param.m_decoder.m_state |=
0x8000;/* FIXME J2K_DEC_STATE_ERR;*/
return OPJ_FALSE;
}
opj_read_bytes(l_current_ptr, &l_tccp->cblkw, 1); /* SPcoc (E) */
++l_current_ptr;
l_tccp->cblkw += 2;
opj_read_bytes(l_current_ptr, &l_tccp->cblkh, 1); /* SPcoc (F) */
++l_current_ptr;
l_tccp->cblkh += 2;
if ((l_tccp->cblkw > 10) || (l_tccp->cblkh > 10) ||
((l_tccp->cblkw + l_tccp->cblkh) > 12)) {
opj_event_msg(p_manager, EVT_ERROR,
"Error reading SPCod SPCoc element, Invalid cblkw/cblkh combination\n");
return OPJ_FALSE;
}
opj_read_bytes(l_current_ptr, &l_tccp->cblksty, 1); /* SPcoc (G) */
++l_current_ptr;
if (l_tccp->cblksty & 0xC0U) { /* 2 msb are reserved, assume we can't read */
opj_event_msg(p_manager, EVT_ERROR,
"Error reading SPCod SPCoc element, Invalid code-block style found\n");
return OPJ_FALSE;
}
opj_read_bytes(l_current_ptr, &l_tccp->qmfbid, 1); /* SPcoc (H) */
++l_current_ptr;
*p_header_size = *p_header_size - 5;
/* use custom precinct size ? */
if (l_tccp->csty & J2K_CCP_CSTY_PRT) {
if (*p_header_size < l_tccp->numresolutions) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading SPCod SPCoc element\n");
return OPJ_FALSE;
}
for (i = 0; i < l_tccp->numresolutions; ++i) {
opj_read_bytes(l_current_ptr, &l_tmp, 1); /* SPcoc (I_i) */
++l_current_ptr;
/* Precinct exponent 0 is only allowed for lowest resolution level (Table A.21) */
if ((i != 0) && (((l_tmp & 0xf) == 0) || ((l_tmp >> 4) == 0))) {
opj_event_msg(p_manager, EVT_ERROR, "Invalid precinct size\n");
return OPJ_FALSE;
}
l_tccp->prcw[i] = l_tmp & 0xf;
l_tccp->prch[i] = l_tmp >> 4;
}
*p_header_size = *p_header_size - l_tccp->numresolutions;
} else {
/* set default size for the precinct width and height */
for (i = 0; i < l_tccp->numresolutions; ++i) {
l_tccp->prcw[i] = 15;
l_tccp->prch[i] = 15;
}
}
#ifdef WIP_REMOVE_MSD
/* INDEX >> */
if (p_j2k->cstr_info && compno == 0) {
OPJ_UINT32 l_data_size = l_tccp->numresolutions * sizeof(OPJ_UINT32);
p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].cblkh =
l_tccp->cblkh;
p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].cblkw =
l_tccp->cblkw;
p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].numresolutions
= l_tccp->numresolutions;
p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].cblksty =
l_tccp->cblksty;
p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].qmfbid =
l_tccp->qmfbid;
memcpy(p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].pdx, l_tccp->prcw,
l_data_size);
memcpy(p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].pdy, l_tccp->prch,
l_data_size);
}
/* << INDEX */
#endif
return OPJ_TRUE;
}
static void opj_j2k_copy_tile_component_parameters(opj_j2k_t *p_j2k)
{
/* loop */
OPJ_UINT32 i;
opj_cp_t *l_cp = NULL;
opj_tcp_t *l_tcp = NULL;
opj_tccp_t *l_ref_tccp = NULL, *l_copied_tccp = NULL;
OPJ_UINT32 l_prc_size;
/* preconditions */
assert(p_j2k != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH)
?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
l_ref_tccp = &l_tcp->tccps[0];
l_copied_tccp = l_ref_tccp + 1;
l_prc_size = l_ref_tccp->numresolutions * (OPJ_UINT32)sizeof(OPJ_UINT32);
for (i = 1; i < p_j2k->m_private_image->numcomps; ++i) {
l_copied_tccp->numresolutions = l_ref_tccp->numresolutions;
l_copied_tccp->cblkw = l_ref_tccp->cblkw;
l_copied_tccp->cblkh = l_ref_tccp->cblkh;
l_copied_tccp->cblksty = l_ref_tccp->cblksty;
l_copied_tccp->qmfbid = l_ref_tccp->qmfbid;
memcpy(l_copied_tccp->prcw, l_ref_tccp->prcw, l_prc_size);
memcpy(l_copied_tccp->prch, l_ref_tccp->prch, l_prc_size);
++l_copied_tccp;
}
}
static OPJ_UINT32 opj_j2k_get_SQcd_SQcc_size(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no)
{
OPJ_UINT32 l_num_bands;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_tccp_t *l_tccp = 00;
/* preconditions */
assert(p_j2k != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_tile_no];
l_tccp = &l_tcp->tccps[p_comp_no];
/* preconditions again */
assert(p_tile_no < l_cp->tw * l_cp->th);
assert(p_comp_no < p_j2k->m_private_image->numcomps);
l_num_bands = (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 1 :
(l_tccp->numresolutions * 3 - 2);
if (l_tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) {
return 1 + l_num_bands;
} else {
return 1 + 2 * l_num_bands;
}
}
static OPJ_BOOL opj_j2k_compare_SQcd_SQcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no)
{
opj_cp_t *l_cp = NULL;
opj_tcp_t *l_tcp = NULL;
opj_tccp_t *l_tccp0 = NULL;
opj_tccp_t *l_tccp1 = NULL;
OPJ_UINT32 l_band_no, l_num_bands;
/* preconditions */
assert(p_j2k != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_tile_no];
l_tccp0 = &l_tcp->tccps[p_first_comp_no];
l_tccp1 = &l_tcp->tccps[p_second_comp_no];
if (l_tccp0->qntsty != l_tccp1->qntsty) {
return OPJ_FALSE;
}
if (l_tccp0->numgbits != l_tccp1->numgbits) {
return OPJ_FALSE;
}
if (l_tccp0->qntsty == J2K_CCP_QNTSTY_SIQNT) {
l_num_bands = 1U;
} else {
l_num_bands = l_tccp0->numresolutions * 3U - 2U;
if (l_num_bands != (l_tccp1->numresolutions * 3U - 2U)) {
return OPJ_FALSE;
}
}
for (l_band_no = 0; l_band_no < l_num_bands; ++l_band_no) {
if (l_tccp0->stepsizes[l_band_no].expn != l_tccp1->stepsizes[l_band_no].expn) {
return OPJ_FALSE;
}
}
if (l_tccp0->qntsty != J2K_CCP_QNTSTY_NOQNT) {
for (l_band_no = 0; l_band_no < l_num_bands; ++l_band_no) {
if (l_tccp0->stepsizes[l_band_no].mant != l_tccp1->stepsizes[l_band_no].mant) {
return OPJ_FALSE;
}
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_SQcd_SQcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_header_size,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 l_header_size;
OPJ_UINT32 l_band_no, l_num_bands;
OPJ_UINT32 l_expn, l_mant;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_tccp_t *l_tccp = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_header_size != 00);
assert(p_manager != 00);
assert(p_data != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_tile_no];
l_tccp = &l_tcp->tccps[p_comp_no];
/* preconditions again */
assert(p_tile_no < l_cp->tw * l_cp->th);
assert(p_comp_no < p_j2k->m_private_image->numcomps);
l_num_bands = (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 1 :
(l_tccp->numresolutions * 3 - 2);
if (l_tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) {
l_header_size = 1 + l_num_bands;
if (*p_header_size < l_header_size) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing SQcd SQcc element\n");
return OPJ_FALSE;
}
opj_write_bytes(p_data, l_tccp->qntsty + (l_tccp->numgbits << 5),
1); /* Sqcx */
++p_data;
for (l_band_no = 0; l_band_no < l_num_bands; ++l_band_no) {
l_expn = (OPJ_UINT32)l_tccp->stepsizes[l_band_no].expn;
opj_write_bytes(p_data, l_expn << 3, 1); /* SPqcx_i */
++p_data;
}
} else {
l_header_size = 1 + 2 * l_num_bands;
if (*p_header_size < l_header_size) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing SQcd SQcc element\n");
return OPJ_FALSE;
}
opj_write_bytes(p_data, l_tccp->qntsty + (l_tccp->numgbits << 5),
1); /* Sqcx */
++p_data;
for (l_band_no = 0; l_band_no < l_num_bands; ++l_band_no) {
l_expn = (OPJ_UINT32)l_tccp->stepsizes[l_band_no].expn;
l_mant = (OPJ_UINT32)l_tccp->stepsizes[l_band_no].mant;
opj_write_bytes(p_data, (l_expn << 11) + l_mant, 2); /* SPqcx_i */
p_data += 2;
}
}
*p_header_size = *p_header_size - l_header_size;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_read_SQcd_SQcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
OPJ_BYTE* p_header_data,
OPJ_UINT32 * p_header_size,
opj_event_mgr_t * p_manager
)
{
/* loop*/
OPJ_UINT32 l_band_no;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_tccp_t *l_tccp = 00;
OPJ_BYTE * l_current_ptr = 00;
OPJ_UINT32 l_tmp, l_num_band;
/* preconditions*/
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_header_data != 00);
l_cp = &(p_j2k->m_cp);
/* come from tile part header or main header ?*/
l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH)
?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
/* precondition again*/
assert(p_comp_no < p_j2k->m_private_image->numcomps);
l_tccp = &l_tcp->tccps[p_comp_no];
l_current_ptr = p_header_data;
if (*p_header_size < 1) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading SQcd or SQcc element\n");
return OPJ_FALSE;
}
*p_header_size -= 1;
opj_read_bytes(l_current_ptr, &l_tmp, 1); /* Sqcx */
++l_current_ptr;
l_tccp->qntsty = l_tmp & 0x1f;
l_tccp->numgbits = l_tmp >> 5;
if (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) {
l_num_band = 1;
} else {
l_num_band = (l_tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) ?
(*p_header_size) :
(*p_header_size) / 2;
if (l_num_band > OPJ_J2K_MAXBANDS) {
opj_event_msg(p_manager, EVT_WARNING,
"While reading CCP_QNTSTY element inside QCD or QCC marker segment, "
"number of subbands (%d) is greater to OPJ_J2K_MAXBANDS (%d). So we limit the number of elements stored to "
"OPJ_J2K_MAXBANDS (%d) and skip the rest. \n", l_num_band, OPJ_J2K_MAXBANDS,
OPJ_J2K_MAXBANDS);
/*return OPJ_FALSE;*/
}
}
#ifdef USE_JPWL
if (l_cp->correct) {
/* if JPWL is on, we check whether there are too many subbands */
if (/*(l_num_band < 0) ||*/ (l_num_band >= OPJ_J2K_MAXBANDS)) {
opj_event_msg(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
"JPWL: bad number of subbands in Sqcx (%d)\n",
l_num_band);
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
/* we try to correct */
l_num_band = 1;
opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust them\n"
"- setting number of bands to %d => HYPOTHESIS!!!\n",
l_num_band);
};
};
#endif /* USE_JPWL */
if (l_tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) {
for (l_band_no = 0; l_band_no < l_num_band; l_band_no++) {
opj_read_bytes(l_current_ptr, &l_tmp, 1); /* SPqcx_i */
++l_current_ptr;
if (l_band_no < OPJ_J2K_MAXBANDS) {
l_tccp->stepsizes[l_band_no].expn = (OPJ_INT32)(l_tmp >> 3);
l_tccp->stepsizes[l_band_no].mant = 0;
}
}
*p_header_size = *p_header_size - l_num_band;
} else {
for (l_band_no = 0; l_band_no < l_num_band; l_band_no++) {
opj_read_bytes(l_current_ptr, &l_tmp, 2); /* SPqcx_i */
l_current_ptr += 2;
if (l_band_no < OPJ_J2K_MAXBANDS) {
l_tccp->stepsizes[l_band_no].expn = (OPJ_INT32)(l_tmp >> 11);
l_tccp->stepsizes[l_band_no].mant = l_tmp & 0x7ff;
}
}
*p_header_size = *p_header_size - 2 * l_num_band;
}
/* Add Antonin : if scalar_derived -> compute other stepsizes */
if (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) {
for (l_band_no = 1; l_band_no < OPJ_J2K_MAXBANDS; l_band_no++) {
l_tccp->stepsizes[l_band_no].expn =
((OPJ_INT32)(l_tccp->stepsizes[0].expn) - (OPJ_INT32)((l_band_no - 1) / 3) > 0)
?
(OPJ_INT32)(l_tccp->stepsizes[0].expn) - (OPJ_INT32)((l_band_no - 1) / 3) : 0;
l_tccp->stepsizes[l_band_no].mant = l_tccp->stepsizes[0].mant;
}
}
return OPJ_TRUE;
}
static void opj_j2k_copy_tile_quantization_parameters(opj_j2k_t *p_j2k)
{
OPJ_UINT32 i;
opj_cp_t *l_cp = NULL;
opj_tcp_t *l_tcp = NULL;
opj_tccp_t *l_ref_tccp = NULL;
opj_tccp_t *l_copied_tccp = NULL;
OPJ_UINT32 l_size;
/* preconditions */
assert(p_j2k != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH ?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
l_ref_tccp = &l_tcp->tccps[0];
l_copied_tccp = l_ref_tccp + 1;
l_size = OPJ_J2K_MAXBANDS * sizeof(opj_stepsize_t);
for (i = 1; i < p_j2k->m_private_image->numcomps; ++i) {
l_copied_tccp->qntsty = l_ref_tccp->qntsty;
l_copied_tccp->numgbits = l_ref_tccp->numgbits;
memcpy(l_copied_tccp->stepsizes, l_ref_tccp->stepsizes, l_size);
++l_copied_tccp;
}
}
static void opj_j2k_dump_tile_info(opj_tcp_t * l_default_tile,
OPJ_INT32 numcomps, FILE* out_stream)
{
if (l_default_tile) {
OPJ_INT32 compno;
fprintf(out_stream, "\t default tile {\n");
fprintf(out_stream, "\t\t csty=%#x\n", l_default_tile->csty);
fprintf(out_stream, "\t\t prg=%#x\n", l_default_tile->prg);
fprintf(out_stream, "\t\t numlayers=%d\n", l_default_tile->numlayers);
fprintf(out_stream, "\t\t mct=%x\n", l_default_tile->mct);
for (compno = 0; compno < numcomps; compno++) {
opj_tccp_t *l_tccp = &(l_default_tile->tccps[compno]);
OPJ_UINT32 resno;
OPJ_INT32 bandno, numbands;
/* coding style*/
fprintf(out_stream, "\t\t comp %d {\n", compno);
fprintf(out_stream, "\t\t\t csty=%#x\n", l_tccp->csty);
fprintf(out_stream, "\t\t\t numresolutions=%d\n", l_tccp->numresolutions);
fprintf(out_stream, "\t\t\t cblkw=2^%d\n", l_tccp->cblkw);
fprintf(out_stream, "\t\t\t cblkh=2^%d\n", l_tccp->cblkh);
fprintf(out_stream, "\t\t\t cblksty=%#x\n", l_tccp->cblksty);
fprintf(out_stream, "\t\t\t qmfbid=%d\n", l_tccp->qmfbid);
fprintf(out_stream, "\t\t\t preccintsize (w,h)=");
for (resno = 0; resno < l_tccp->numresolutions; resno++) {
fprintf(out_stream, "(%d,%d) ", l_tccp->prcw[resno], l_tccp->prch[resno]);
}
fprintf(out_stream, "\n");
/* quantization style*/
fprintf(out_stream, "\t\t\t qntsty=%d\n", l_tccp->qntsty);
fprintf(out_stream, "\t\t\t numgbits=%d\n", l_tccp->numgbits);
fprintf(out_stream, "\t\t\t stepsizes (m,e)=");
numbands = (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 1 :
(OPJ_INT32)l_tccp->numresolutions * 3 - 2;
for (bandno = 0; bandno < numbands; bandno++) {
fprintf(out_stream, "(%d,%d) ", l_tccp->stepsizes[bandno].mant,
l_tccp->stepsizes[bandno].expn);
}
fprintf(out_stream, "\n");
/* RGN value*/
fprintf(out_stream, "\t\t\t roishift=%d\n", l_tccp->roishift);
fprintf(out_stream, "\t\t }\n");
} /*end of component of default tile*/
fprintf(out_stream, "\t }\n"); /*end of default tile*/
}
}
void j2k_dump(opj_j2k_t* p_j2k, OPJ_INT32 flag, FILE* out_stream)
{
/* Check if the flag is compatible with j2k file*/
if ((flag & OPJ_JP2_INFO) || (flag & OPJ_JP2_IND)) {
fprintf(out_stream, "Wrong flag\n");
return;
}
/* Dump the image_header */
if (flag & OPJ_IMG_INFO) {
if (p_j2k->m_private_image) {
j2k_dump_image_header(p_j2k->m_private_image, 0, out_stream);
}
}
/* Dump the codestream info from main header */
if (flag & OPJ_J2K_MH_INFO) {
if (p_j2k->m_private_image) {
opj_j2k_dump_MH_info(p_j2k, out_stream);
}
}
/* Dump all tile/codestream info */
if (flag & OPJ_J2K_TCH_INFO) {
OPJ_UINT32 l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
OPJ_UINT32 i;
opj_tcp_t * l_tcp = p_j2k->m_cp.tcps;
if (p_j2k->m_private_image) {
for (i = 0; i < l_nb_tiles; ++i) {
opj_j2k_dump_tile_info(l_tcp, (OPJ_INT32)p_j2k->m_private_image->numcomps,
out_stream);
++l_tcp;
}
}
}
/* Dump the codestream info of the current tile */
if (flag & OPJ_J2K_TH_INFO) {
}
/* Dump the codestream index from main header */
if (flag & OPJ_J2K_MH_IND) {
opj_j2k_dump_MH_index(p_j2k, out_stream);
}
/* Dump the codestream index of the current tile */
if (flag & OPJ_J2K_TH_IND) {
}
}
static void opj_j2k_dump_MH_index(opj_j2k_t* p_j2k, FILE* out_stream)
{
opj_codestream_index_t* cstr_index = p_j2k->cstr_index;
OPJ_UINT32 it_marker, it_tile, it_tile_part;
fprintf(out_stream, "Codestream index from main header: {\n");
fprintf(out_stream, "\t Main header start position=%" PRIi64 "\n"
"\t Main header end position=%" PRIi64 "\n",
cstr_index->main_head_start, cstr_index->main_head_end);
fprintf(out_stream, "\t Marker list: {\n");
if (cstr_index->marker) {
for (it_marker = 0; it_marker < cstr_index->marknum ; it_marker++) {
fprintf(out_stream, "\t\t type=%#x, pos=%" PRIi64 ", len=%d\n",
cstr_index->marker[it_marker].type,
cstr_index->marker[it_marker].pos,
cstr_index->marker[it_marker].len);
}
}
fprintf(out_stream, "\t }\n");
if (cstr_index->tile_index) {
/* Simple test to avoid to write empty information*/
OPJ_UINT32 l_acc_nb_of_tile_part = 0;
for (it_tile = 0; it_tile < cstr_index->nb_of_tiles ; it_tile++) {
l_acc_nb_of_tile_part += cstr_index->tile_index[it_tile].nb_tps;
}
if (l_acc_nb_of_tile_part) {
fprintf(out_stream, "\t Tile index: {\n");
for (it_tile = 0; it_tile < cstr_index->nb_of_tiles ; it_tile++) {
OPJ_UINT32 nb_of_tile_part = cstr_index->tile_index[it_tile].nb_tps;
fprintf(out_stream, "\t\t nb of tile-part in tile [%d]=%d\n", it_tile,
nb_of_tile_part);
if (cstr_index->tile_index[it_tile].tp_index) {
for (it_tile_part = 0; it_tile_part < nb_of_tile_part; it_tile_part++) {
fprintf(out_stream, "\t\t\t tile-part[%d]: star_pos=%" PRIi64 ", end_header=%"
PRIi64 ", end_pos=%" PRIi64 ".\n",
it_tile_part,
cstr_index->tile_index[it_tile].tp_index[it_tile_part].start_pos,
cstr_index->tile_index[it_tile].tp_index[it_tile_part].end_header,
cstr_index->tile_index[it_tile].tp_index[it_tile_part].end_pos);
}
}
if (cstr_index->tile_index[it_tile].marker) {
for (it_marker = 0; it_marker < cstr_index->tile_index[it_tile].marknum ;
it_marker++) {
fprintf(out_stream, "\t\t type=%#x, pos=%" PRIi64 ", len=%d\n",
cstr_index->tile_index[it_tile].marker[it_marker].type,
cstr_index->tile_index[it_tile].marker[it_marker].pos,
cstr_index->tile_index[it_tile].marker[it_marker].len);
}
}
}
fprintf(out_stream, "\t }\n");
}
}
fprintf(out_stream, "}\n");
}
static void opj_j2k_dump_MH_info(opj_j2k_t* p_j2k, FILE* out_stream)
{
fprintf(out_stream, "Codestream info from main header: {\n");
fprintf(out_stream, "\t tx0=%d, ty0=%d\n", p_j2k->m_cp.tx0, p_j2k->m_cp.ty0);
fprintf(out_stream, "\t tdx=%d, tdy=%d\n", p_j2k->m_cp.tdx, p_j2k->m_cp.tdy);
fprintf(out_stream, "\t tw=%d, th=%d\n", p_j2k->m_cp.tw, p_j2k->m_cp.th);
opj_j2k_dump_tile_info(p_j2k->m_specific_param.m_decoder.m_default_tcp,
(OPJ_INT32)p_j2k->m_private_image->numcomps, out_stream);
fprintf(out_stream, "}\n");
}
void j2k_dump_image_header(opj_image_t* img_header, OPJ_BOOL dev_dump_flag,
FILE* out_stream)
{
char tab[2];
if (dev_dump_flag) {
fprintf(stdout, "[DEV] Dump an image_header struct {\n");
tab[0] = '\0';
} else {
fprintf(out_stream, "Image info {\n");
tab[0] = '\t';
tab[1] = '\0';
}
fprintf(out_stream, "%s x0=%d, y0=%d\n", tab, img_header->x0, img_header->y0);
fprintf(out_stream, "%s x1=%d, y1=%d\n", tab, img_header->x1,
img_header->y1);
fprintf(out_stream, "%s numcomps=%d\n", tab, img_header->numcomps);
if (img_header->comps) {
OPJ_UINT32 compno;
for (compno = 0; compno < img_header->numcomps; compno++) {
fprintf(out_stream, "%s\t component %d {\n", tab, compno);
j2k_dump_image_comp_header(&(img_header->comps[compno]), dev_dump_flag,
out_stream);
fprintf(out_stream, "%s}\n", tab);
}
}
fprintf(out_stream, "}\n");
}
void j2k_dump_image_comp_header(opj_image_comp_t* comp_header,
OPJ_BOOL dev_dump_flag, FILE* out_stream)
{
char tab[3];
if (dev_dump_flag) {
fprintf(stdout, "[DEV] Dump an image_comp_header struct {\n");
tab[0] = '\0';
} else {
tab[0] = '\t';
tab[1] = '\t';
tab[2] = '\0';
}
fprintf(out_stream, "%s dx=%d, dy=%d\n", tab, comp_header->dx, comp_header->dy);
fprintf(out_stream, "%s prec=%d\n", tab, comp_header->prec);
fprintf(out_stream, "%s sgnd=%d\n", tab, comp_header->sgnd);
if (dev_dump_flag) {
fprintf(out_stream, "}\n");
}
}
opj_codestream_info_v2_t* j2k_get_cstr_info(opj_j2k_t* p_j2k)
{
OPJ_UINT32 compno;
OPJ_UINT32 numcomps = p_j2k->m_private_image->numcomps;
opj_tcp_t *l_default_tile;
opj_codestream_info_v2_t* cstr_info = (opj_codestream_info_v2_t*) opj_calloc(1,
sizeof(opj_codestream_info_v2_t));
if (!cstr_info) {
return NULL;
}
cstr_info->nbcomps = p_j2k->m_private_image->numcomps;
cstr_info->tx0 = p_j2k->m_cp.tx0;
cstr_info->ty0 = p_j2k->m_cp.ty0;
cstr_info->tdx = p_j2k->m_cp.tdx;
cstr_info->tdy = p_j2k->m_cp.tdy;
cstr_info->tw = p_j2k->m_cp.tw;
cstr_info->th = p_j2k->m_cp.th;
cstr_info->tile_info = NULL; /* Not fill from the main header*/
l_default_tile = p_j2k->m_specific_param.m_decoder.m_default_tcp;
cstr_info->m_default_tile_info.csty = l_default_tile->csty;
cstr_info->m_default_tile_info.prg = l_default_tile->prg;
cstr_info->m_default_tile_info.numlayers = l_default_tile->numlayers;
cstr_info->m_default_tile_info.mct = l_default_tile->mct;
cstr_info->m_default_tile_info.tccp_info = (opj_tccp_info_t*) opj_calloc(
cstr_info->nbcomps, sizeof(opj_tccp_info_t));
if (!cstr_info->m_default_tile_info.tccp_info) {
opj_destroy_cstr_info(&cstr_info);
return NULL;
}
for (compno = 0; compno < numcomps; compno++) {
opj_tccp_t *l_tccp = &(l_default_tile->tccps[compno]);
opj_tccp_info_t *l_tccp_info = &
(cstr_info->m_default_tile_info.tccp_info[compno]);
OPJ_INT32 bandno, numbands;
/* coding style*/
l_tccp_info->csty = l_tccp->csty;
l_tccp_info->numresolutions = l_tccp->numresolutions;
l_tccp_info->cblkw = l_tccp->cblkw;
l_tccp_info->cblkh = l_tccp->cblkh;
l_tccp_info->cblksty = l_tccp->cblksty;
l_tccp_info->qmfbid = l_tccp->qmfbid;
if (l_tccp->numresolutions < OPJ_J2K_MAXRLVLS) {
memcpy(l_tccp_info->prch, l_tccp->prch, l_tccp->numresolutions);
memcpy(l_tccp_info->prcw, l_tccp->prcw, l_tccp->numresolutions);
}
/* quantization style*/
l_tccp_info->qntsty = l_tccp->qntsty;
l_tccp_info->numgbits = l_tccp->numgbits;
numbands = (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 1 :
(OPJ_INT32)l_tccp->numresolutions * 3 - 2;
if (numbands < OPJ_J2K_MAXBANDS) {
for (bandno = 0; bandno < numbands; bandno++) {
l_tccp_info->stepsizes_mant[bandno] = (OPJ_UINT32)
l_tccp->stepsizes[bandno].mant;
l_tccp_info->stepsizes_expn[bandno] = (OPJ_UINT32)
l_tccp->stepsizes[bandno].expn;
}
}
/* RGN value*/
l_tccp_info->roishift = l_tccp->roishift;
}
return cstr_info;
}
opj_codestream_index_t* j2k_get_cstr_index(opj_j2k_t* p_j2k)
{
opj_codestream_index_t* l_cstr_index = (opj_codestream_index_t*)
opj_calloc(1, sizeof(opj_codestream_index_t));
if (!l_cstr_index) {
return NULL;
}
l_cstr_index->main_head_start = p_j2k->cstr_index->main_head_start;
l_cstr_index->main_head_end = p_j2k->cstr_index->main_head_end;
l_cstr_index->codestream_size = p_j2k->cstr_index->codestream_size;
l_cstr_index->marknum = p_j2k->cstr_index->marknum;
l_cstr_index->marker = (opj_marker_info_t*)opj_malloc(l_cstr_index->marknum *
sizeof(opj_marker_info_t));
if (!l_cstr_index->marker) {
opj_free(l_cstr_index);
return NULL;
}
if (p_j2k->cstr_index->marker) {
memcpy(l_cstr_index->marker, p_j2k->cstr_index->marker,
l_cstr_index->marknum * sizeof(opj_marker_info_t));
} else {
opj_free(l_cstr_index->marker);
l_cstr_index->marker = NULL;
}
l_cstr_index->nb_of_tiles = p_j2k->cstr_index->nb_of_tiles;
l_cstr_index->tile_index = (opj_tile_index_t*)opj_calloc(
l_cstr_index->nb_of_tiles, sizeof(opj_tile_index_t));
if (!l_cstr_index->tile_index) {
opj_free(l_cstr_index->marker);
opj_free(l_cstr_index);
return NULL;
}
if (!p_j2k->cstr_index->tile_index) {
opj_free(l_cstr_index->tile_index);
l_cstr_index->tile_index = NULL;
} else {
OPJ_UINT32 it_tile = 0;
for (it_tile = 0; it_tile < l_cstr_index->nb_of_tiles; it_tile++) {
/* Tile Marker*/
l_cstr_index->tile_index[it_tile].marknum =
p_j2k->cstr_index->tile_index[it_tile].marknum;
l_cstr_index->tile_index[it_tile].marker =
(opj_marker_info_t*)opj_malloc(l_cstr_index->tile_index[it_tile].marknum *
sizeof(opj_marker_info_t));
if (!l_cstr_index->tile_index[it_tile].marker) {
OPJ_UINT32 it_tile_free;
for (it_tile_free = 0; it_tile_free < it_tile; it_tile_free++) {
opj_free(l_cstr_index->tile_index[it_tile_free].marker);
}
opj_free(l_cstr_index->tile_index);
opj_free(l_cstr_index->marker);
opj_free(l_cstr_index);
return NULL;
}
if (p_j2k->cstr_index->tile_index[it_tile].marker)
memcpy(l_cstr_index->tile_index[it_tile].marker,
p_j2k->cstr_index->tile_index[it_tile].marker,
l_cstr_index->tile_index[it_tile].marknum * sizeof(opj_marker_info_t));
else {
opj_free(l_cstr_index->tile_index[it_tile].marker);
l_cstr_index->tile_index[it_tile].marker = NULL;
}
/* Tile part index*/
l_cstr_index->tile_index[it_tile].nb_tps =
p_j2k->cstr_index->tile_index[it_tile].nb_tps;
l_cstr_index->tile_index[it_tile].tp_index =
(opj_tp_index_t*)opj_malloc(l_cstr_index->tile_index[it_tile].nb_tps * sizeof(
opj_tp_index_t));
if (!l_cstr_index->tile_index[it_tile].tp_index) {
OPJ_UINT32 it_tile_free;
for (it_tile_free = 0; it_tile_free < it_tile; it_tile_free++) {
opj_free(l_cstr_index->tile_index[it_tile_free].marker);
opj_free(l_cstr_index->tile_index[it_tile_free].tp_index);
}
opj_free(l_cstr_index->tile_index);
opj_free(l_cstr_index->marker);
opj_free(l_cstr_index);
return NULL;
}
if (p_j2k->cstr_index->tile_index[it_tile].tp_index) {
memcpy(l_cstr_index->tile_index[it_tile].tp_index,
p_j2k->cstr_index->tile_index[it_tile].tp_index,
l_cstr_index->tile_index[it_tile].nb_tps * sizeof(opj_tp_index_t));
} else {
opj_free(l_cstr_index->tile_index[it_tile].tp_index);
l_cstr_index->tile_index[it_tile].tp_index = NULL;
}
/* Packet index (NOT USED)*/
l_cstr_index->tile_index[it_tile].nb_packet = 0;
l_cstr_index->tile_index[it_tile].packet_index = NULL;
}
}
return l_cstr_index;
}
static OPJ_BOOL opj_j2k_allocate_tile_element_cstr_index(opj_j2k_t *p_j2k)
{
OPJ_UINT32 it_tile = 0;
p_j2k->cstr_index->nb_of_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th;
p_j2k->cstr_index->tile_index = (opj_tile_index_t*)opj_calloc(
p_j2k->cstr_index->nb_of_tiles, sizeof(opj_tile_index_t));
if (!p_j2k->cstr_index->tile_index) {
return OPJ_FALSE;
}
for (it_tile = 0; it_tile < p_j2k->cstr_index->nb_of_tiles; it_tile++) {
p_j2k->cstr_index->tile_index[it_tile].maxmarknum = 100;
p_j2k->cstr_index->tile_index[it_tile].marknum = 0;
p_j2k->cstr_index->tile_index[it_tile].marker = (opj_marker_info_t*)
opj_calloc(p_j2k->cstr_index->tile_index[it_tile].maxmarknum,
sizeof(opj_marker_info_t));
if (!p_j2k->cstr_index->tile_index[it_tile].marker) {
return OPJ_FALSE;
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_decode_tiles(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_BOOL l_go_on = OPJ_TRUE;
OPJ_UINT32 l_current_tile_no;
OPJ_UINT32 l_data_size, l_max_data_size;
OPJ_INT32 l_tile_x0, l_tile_y0, l_tile_x1, l_tile_y1;
OPJ_UINT32 l_nb_comps;
OPJ_BYTE * l_current_data;
OPJ_UINT32 nr_tiles = 0;
/* Particular case for whole single tile decoding */
/* We can avoid allocating intermediate tile buffers */
if (p_j2k->m_cp.tw == 1 && p_j2k->m_cp.th == 1 &&
p_j2k->m_cp.tx0 == 0 && p_j2k->m_cp.ty0 == 0 &&
p_j2k->m_output_image->x0 == 0 &&
p_j2k->m_output_image->y0 == 0 &&
p_j2k->m_output_image->x1 == p_j2k->m_cp.tdx &&
p_j2k->m_output_image->y1 == p_j2k->m_cp.tdy &&
p_j2k->m_output_image->comps[0].factor == 0) {
OPJ_UINT32 i;
if (! opj_j2k_read_tile_header(p_j2k,
&l_current_tile_no,
&l_data_size,
&l_tile_x0, &l_tile_y0,
&l_tile_x1, &l_tile_y1,
&l_nb_comps,
&l_go_on,
p_stream,
p_manager)) {
return OPJ_FALSE;
}
if (! opj_j2k_decode_tile(p_j2k, l_current_tile_no, NULL, 0,
p_stream, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Failed to decode tile 1/1\n");
return OPJ_FALSE;
}
/* Transfer TCD data to output image data */
for (i = 0; i < p_j2k->m_output_image->numcomps; i++) {
opj_image_data_free(p_j2k->m_output_image->comps[i].data);
p_j2k->m_output_image->comps[i].data =
p_j2k->m_tcd->tcd_image->tiles->comps[i].data;
p_j2k->m_output_image->comps[i].resno_decoded =
p_j2k->m_tcd->image->comps[i].resno_decoded;
p_j2k->m_tcd->tcd_image->tiles->comps[i].data = NULL;
}
return OPJ_TRUE;
}
l_current_data = (OPJ_BYTE*)opj_malloc(1000);
if (! l_current_data) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to decode tiles\n");
return OPJ_FALSE;
}
l_max_data_size = 1000;
for (;;) {
if (! opj_j2k_read_tile_header(p_j2k,
&l_current_tile_no,
&l_data_size,
&l_tile_x0, &l_tile_y0,
&l_tile_x1, &l_tile_y1,
&l_nb_comps,
&l_go_on,
p_stream,
p_manager)) {
opj_free(l_current_data);
return OPJ_FALSE;
}
if (! l_go_on) {
break;
}
if (l_data_size > l_max_data_size) {
OPJ_BYTE *l_new_current_data = (OPJ_BYTE *) opj_realloc(l_current_data,
l_data_size);
if (! l_new_current_data) {
opj_free(l_current_data);
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to decode tile %d/%d\n",
l_current_tile_no + 1, p_j2k->m_cp.th * p_j2k->m_cp.tw);
return OPJ_FALSE;
}
l_current_data = l_new_current_data;
l_max_data_size = l_data_size;
}
if (! opj_j2k_decode_tile(p_j2k, l_current_tile_no, l_current_data, l_data_size,
p_stream, p_manager)) {
opj_free(l_current_data);
opj_event_msg(p_manager, EVT_ERROR, "Failed to decode tile %d/%d\n",
l_current_tile_no + 1, p_j2k->m_cp.th * p_j2k->m_cp.tw);
return OPJ_FALSE;
}
opj_event_msg(p_manager, EVT_INFO, "Tile %d/%d has been decoded.\n",
l_current_tile_no + 1, p_j2k->m_cp.th * p_j2k->m_cp.tw);
if (! opj_j2k_update_image_data(p_j2k->m_tcd, l_current_data,
p_j2k->m_output_image)) {
opj_free(l_current_data);
return OPJ_FALSE;
}
opj_event_msg(p_manager, EVT_INFO,
"Image data has been updated with tile %d.\n\n", l_current_tile_no + 1);
if (opj_stream_get_number_byte_left(p_stream) == 0
&& p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_NEOC) {
break;
}
if (++nr_tiles == p_j2k->m_cp.th * p_j2k->m_cp.tw) {
break;
}
}
opj_free(l_current_data);
return OPJ_TRUE;
}
/**
* Sets up the procedures to do on decoding data. Developpers wanting to extend the library can add their own reading procedures.
*/
static OPJ_BOOL opj_j2k_setup_decoding(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager)
{
/* preconditions*/
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_decode_tiles, p_manager)) {
return OPJ_FALSE;
}
/* DEVELOPER CORNER, add your custom procedures */
return OPJ_TRUE;
}
/*
* Read and decode one tile.
*/
static OPJ_BOOL opj_j2k_decode_one_tile(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_BOOL l_go_on = OPJ_TRUE;
OPJ_UINT32 l_current_tile_no;
OPJ_UINT32 l_tile_no_to_dec;
OPJ_UINT32 l_data_size, l_max_data_size;
OPJ_INT32 l_tile_x0, l_tile_y0, l_tile_x1, l_tile_y1;
OPJ_UINT32 l_nb_comps;
OPJ_BYTE * l_current_data;
OPJ_UINT32 l_nb_tiles;
OPJ_UINT32 i;
l_current_data = (OPJ_BYTE*)opj_malloc(1000);
if (! l_current_data) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to decode one tile\n");
return OPJ_FALSE;
}
l_max_data_size = 1000;
/*Allocate and initialize some elements of codestrem index if not already done*/
if (!p_j2k->cstr_index->tile_index) {
if (!opj_j2k_allocate_tile_element_cstr_index(p_j2k)) {
opj_free(l_current_data);
return OPJ_FALSE;
}
}
/* Move into the codestream to the first SOT used to decode the desired tile */
l_tile_no_to_dec = (OPJ_UINT32)
p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec;
if (p_j2k->cstr_index->tile_index)
if (p_j2k->cstr_index->tile_index->tp_index) {
if (! p_j2k->cstr_index->tile_index[l_tile_no_to_dec].nb_tps) {
/* the index for this tile has not been built,
* so move to the last SOT read */
if (!(opj_stream_read_seek(p_stream,
p_j2k->m_specific_param.m_decoder.m_last_sot_read_pos + 2, p_manager))) {
opj_event_msg(p_manager, EVT_ERROR, "Problem with seek function\n");
opj_free(l_current_data);
return OPJ_FALSE;
}
} else {
if (!(opj_stream_read_seek(p_stream,
p_j2k->cstr_index->tile_index[l_tile_no_to_dec].tp_index[0].start_pos + 2,
p_manager))) {
opj_event_msg(p_manager, EVT_ERROR, "Problem with seek function\n");
opj_free(l_current_data);
return OPJ_FALSE;
}
}
/* Special case if we have previously read the EOC marker (if the previous tile getted is the last ) */
if (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_EOC) {
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPHSOT;
}
}
/* Reset current tile part number for all tiles, and not only the one */
/* of interest. */
/* Not completely sure this is always correct but required for */
/* ./build/bin/j2k_random_tile_access ./build/tests/tte1.j2k */
l_nb_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th;
for (i = 0; i < l_nb_tiles; ++i) {
p_j2k->m_cp.tcps[i].m_current_tile_part_number = -1;
}
for (;;) {
if (! opj_j2k_read_tile_header(p_j2k,
&l_current_tile_no,
&l_data_size,
&l_tile_x0, &l_tile_y0,
&l_tile_x1, &l_tile_y1,
&l_nb_comps,
&l_go_on,
p_stream,
p_manager)) {
opj_free(l_current_data);
return OPJ_FALSE;
}
if (! l_go_on) {
break;
}
if (l_data_size > l_max_data_size) {
OPJ_BYTE *l_new_current_data = (OPJ_BYTE *) opj_realloc(l_current_data,
l_data_size);
if (! l_new_current_data) {
opj_free(l_current_data);
l_current_data = NULL;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to decode tile %d/%d\n",
l_current_tile_no + 1, p_j2k->m_cp.th * p_j2k->m_cp.tw);
return OPJ_FALSE;
}
l_current_data = l_new_current_data;
l_max_data_size = l_data_size;
}
if (! opj_j2k_decode_tile(p_j2k, l_current_tile_no, l_current_data, l_data_size,
p_stream, p_manager)) {
opj_free(l_current_data);
return OPJ_FALSE;
}
opj_event_msg(p_manager, EVT_INFO, "Tile %d/%d has been decoded.\n",
l_current_tile_no + 1, p_j2k->m_cp.th * p_j2k->m_cp.tw);
if (! opj_j2k_update_image_data(p_j2k->m_tcd, l_current_data,
p_j2k->m_output_image)) {
opj_free(l_current_data);
return OPJ_FALSE;
}
opj_event_msg(p_manager, EVT_INFO,
"Image data has been updated with tile %d.\n\n", l_current_tile_no + 1);
if (l_current_tile_no == l_tile_no_to_dec) {
/* move into the codestream to the first SOT (FIXME or not move?)*/
if (!(opj_stream_read_seek(p_stream, p_j2k->cstr_index->main_head_end + 2,
p_manager))) {
opj_event_msg(p_manager, EVT_ERROR, "Problem with seek function\n");
opj_free(l_current_data);
return OPJ_FALSE;
}
break;
} else {
opj_event_msg(p_manager, EVT_WARNING,
"Tile read, decoded and updated is not the desired one (%d vs %d).\n",
l_current_tile_no + 1, l_tile_no_to_dec + 1);
}
}
opj_free(l_current_data);
return OPJ_TRUE;
}
/**
* Sets up the procedures to do on decoding one tile. Developpers wanting to extend the library can add their own reading procedures.
*/
static OPJ_BOOL opj_j2k_setup_decoding_tile(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager)
{
/* preconditions*/
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_decode_one_tile, p_manager)) {
return OPJ_FALSE;
}
/* DEVELOPER CORNER, add your custom procedures */
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_decode(opj_j2k_t * p_j2k,
opj_stream_private_t * p_stream,
opj_image_t * p_image,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 compno;
if (!p_image) {
return OPJ_FALSE;
}
p_j2k->m_output_image = opj_image_create0();
if (!(p_j2k->m_output_image)) {
return OPJ_FALSE;
}
opj_copy_image_header(p_image, p_j2k->m_output_image);
/* customization of the decoding */
if (!opj_j2k_setup_decoding(p_j2k, p_manager)) {
return OPJ_FALSE;
}
/* Decode the codestream */
if (! opj_j2k_exec(p_j2k, p_j2k->m_procedure_list, p_stream, p_manager)) {
opj_image_destroy(p_j2k->m_private_image);
p_j2k->m_private_image = NULL;
return OPJ_FALSE;
}
/* Move data and copy one information from codec to output image*/
for (compno = 0; compno < p_image->numcomps; compno++) {
p_image->comps[compno].resno_decoded =
p_j2k->m_output_image->comps[compno].resno_decoded;
p_image->comps[compno].data = p_j2k->m_output_image->comps[compno].data;
#if 0
char fn[256];
sprintf(fn, "/tmp/%d.raw", compno);
FILE *debug = fopen(fn, "wb");
fwrite(p_image->comps[compno].data, sizeof(OPJ_INT32),
p_image->comps[compno].w * p_image->comps[compno].h, debug);
fclose(debug);
#endif
p_j2k->m_output_image->comps[compno].data = NULL;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_get_tile(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_image_t* p_image,
opj_event_mgr_t * p_manager,
OPJ_UINT32 tile_index)
{
OPJ_UINT32 compno;
OPJ_UINT32 l_tile_x, l_tile_y;
opj_image_comp_t* l_img_comp;
if (!p_image) {
opj_event_msg(p_manager, EVT_ERROR, "We need an image previously created.\n");
return OPJ_FALSE;
}
if (/*(tile_index < 0) &&*/ (tile_index >= p_j2k->m_cp.tw * p_j2k->m_cp.th)) {
opj_event_msg(p_manager, EVT_ERROR,
"Tile index provided by the user is incorrect %d (max = %d) \n", tile_index,
(p_j2k->m_cp.tw * p_j2k->m_cp.th) - 1);
return OPJ_FALSE;
}
/* Compute the dimension of the desired tile*/
l_tile_x = tile_index % p_j2k->m_cp.tw;
l_tile_y = tile_index / p_j2k->m_cp.tw;
p_image->x0 = l_tile_x * p_j2k->m_cp.tdx + p_j2k->m_cp.tx0;
if (p_image->x0 < p_j2k->m_private_image->x0) {
p_image->x0 = p_j2k->m_private_image->x0;
}
p_image->x1 = (l_tile_x + 1) * p_j2k->m_cp.tdx + p_j2k->m_cp.tx0;
if (p_image->x1 > p_j2k->m_private_image->x1) {
p_image->x1 = p_j2k->m_private_image->x1;
}
p_image->y0 = l_tile_y * p_j2k->m_cp.tdy + p_j2k->m_cp.ty0;
if (p_image->y0 < p_j2k->m_private_image->y0) {
p_image->y0 = p_j2k->m_private_image->y0;
}
p_image->y1 = (l_tile_y + 1) * p_j2k->m_cp.tdy + p_j2k->m_cp.ty0;
if (p_image->y1 > p_j2k->m_private_image->y1) {
p_image->y1 = p_j2k->m_private_image->y1;
}
l_img_comp = p_image->comps;
for (compno = 0; compno < p_image->numcomps; ++compno) {
OPJ_INT32 l_comp_x1, l_comp_y1;
l_img_comp->factor = p_j2k->m_private_image->comps[compno].factor;
l_img_comp->x0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->x0,
(OPJ_INT32)l_img_comp->dx);
l_img_comp->y0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->y0,
(OPJ_INT32)l_img_comp->dy);
l_comp_x1 = opj_int_ceildiv((OPJ_INT32)p_image->x1, (OPJ_INT32)l_img_comp->dx);
l_comp_y1 = opj_int_ceildiv((OPJ_INT32)p_image->y1, (OPJ_INT32)l_img_comp->dy);
l_img_comp->w = (OPJ_UINT32)(opj_int_ceildivpow2(l_comp_x1,
(OPJ_INT32)l_img_comp->factor) - opj_int_ceildivpow2((OPJ_INT32)l_img_comp->x0,
(OPJ_INT32)l_img_comp->factor));
l_img_comp->h = (OPJ_UINT32)(opj_int_ceildivpow2(l_comp_y1,
(OPJ_INT32)l_img_comp->factor) - opj_int_ceildivpow2((OPJ_INT32)l_img_comp->y0,
(OPJ_INT32)l_img_comp->factor));
l_img_comp++;
}
/* Destroy the previous output image*/
if (p_j2k->m_output_image) {
opj_image_destroy(p_j2k->m_output_image);
}
/* Create the ouput image from the information previously computed*/
p_j2k->m_output_image = opj_image_create0();
if (!(p_j2k->m_output_image)) {
return OPJ_FALSE;
}
opj_copy_image_header(p_image, p_j2k->m_output_image);
p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec = (OPJ_INT32)tile_index;
/* customization of the decoding */
if (!opj_j2k_setup_decoding_tile(p_j2k, p_manager)) {
return OPJ_FALSE;
}
/* Decode the codestream */
if (! opj_j2k_exec(p_j2k, p_j2k->m_procedure_list, p_stream, p_manager)) {
opj_image_destroy(p_j2k->m_private_image);
p_j2k->m_private_image = NULL;
return OPJ_FALSE;
}
/* Move data and copy one information from codec to output image*/
for (compno = 0; compno < p_image->numcomps; compno++) {
p_image->comps[compno].resno_decoded =
p_j2k->m_output_image->comps[compno].resno_decoded;
if (p_image->comps[compno].data) {
opj_image_data_free(p_image->comps[compno].data);
}
p_image->comps[compno].data = p_j2k->m_output_image->comps[compno].data;
p_j2k->m_output_image->comps[compno].data = NULL;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_set_decoded_resolution_factor(opj_j2k_t *p_j2k,
OPJ_UINT32 res_factor,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 it_comp;
p_j2k->m_cp.m_specific_param.m_dec.m_reduce = res_factor;
if (p_j2k->m_private_image) {
if (p_j2k->m_private_image->comps) {
if (p_j2k->m_specific_param.m_decoder.m_default_tcp) {
if (p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps) {
for (it_comp = 0 ; it_comp < p_j2k->m_private_image->numcomps; it_comp++) {
OPJ_UINT32 max_res =
p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps[it_comp].numresolutions;
if (res_factor >= max_res) {
opj_event_msg(p_manager, EVT_ERROR,
"Resolution factor is greater than the maximum resolution in the component.\n");
return OPJ_FALSE;
}
p_j2k->m_private_image->comps[it_comp].factor = res_factor;
}
return OPJ_TRUE;
}
}
}
}
return OPJ_FALSE;
}
OPJ_BOOL opj_j2k_encode(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 i, j;
OPJ_UINT32 l_nb_tiles;
OPJ_UINT32 l_max_tile_size = 0, l_current_tile_size;
OPJ_BYTE * l_current_data = 00;
OPJ_BOOL l_reuse_data = OPJ_FALSE;
opj_tcd_t* p_tcd = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
p_tcd = p_j2k->m_tcd;
l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
if (l_nb_tiles == 1) {
l_reuse_data = OPJ_TRUE;
#ifdef __SSE__
for (j = 0; j < p_j2k->m_tcd->image->numcomps; ++j) {
opj_image_comp_t * l_img_comp = p_tcd->image->comps + j;
if (((size_t)l_img_comp->data & 0xFU) !=
0U) { /* tile data shall be aligned on 16 bytes */
l_reuse_data = OPJ_FALSE;
}
}
#endif
}
for (i = 0; i < l_nb_tiles; ++i) {
if (! opj_j2k_pre_write_tile(p_j2k, i, p_stream, p_manager)) {
if (l_current_data) {
opj_free(l_current_data);
}
return OPJ_FALSE;
}
/* if we only have one tile, then simply set tile component data equal to image component data */
/* otherwise, allocate the data */
for (j = 0; j < p_j2k->m_tcd->image->numcomps; ++j) {
opj_tcd_tilecomp_t* l_tilec = p_tcd->tcd_image->tiles->comps + j;
if (l_reuse_data) {
opj_image_comp_t * l_img_comp = p_tcd->image->comps + j;
l_tilec->data = l_img_comp->data;
l_tilec->ownsData = OPJ_FALSE;
} else {
if (! opj_alloc_tile_component_data(l_tilec)) {
opj_event_msg(p_manager, EVT_ERROR, "Error allocating tile component data.");
if (l_current_data) {
opj_free(l_current_data);
}
return OPJ_FALSE;
}
}
}
l_current_tile_size = opj_tcd_get_encoded_tile_size(p_j2k->m_tcd);
if (!l_reuse_data) {
if (l_current_tile_size > l_max_tile_size) {
OPJ_BYTE *l_new_current_data = (OPJ_BYTE *) opj_realloc(l_current_data,
l_current_tile_size);
if (! l_new_current_data) {
if (l_current_data) {
opj_free(l_current_data);
}
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to encode all tiles\n");
return OPJ_FALSE;
}
l_current_data = l_new_current_data;
l_max_tile_size = l_current_tile_size;
}
/* copy image data (32 bit) to l_current_data as contiguous, all-component, zero offset buffer */
/* 32 bit components @ 8 bit precision get converted to 8 bit */
/* 32 bit components @ 16 bit precision get converted to 16 bit */
opj_j2k_get_tile_data(p_j2k->m_tcd, l_current_data);
/* now copy this data into the tile component */
if (! opj_tcd_copy_tile_data(p_j2k->m_tcd, l_current_data,
l_current_tile_size)) {
opj_event_msg(p_manager, EVT_ERROR,
"Size mismatch between tile data and sent data.");
opj_free(l_current_data);
return OPJ_FALSE;
}
}
if (! opj_j2k_post_write_tile(p_j2k, p_stream, p_manager)) {
if (l_current_data) {
opj_free(l_current_data);
}
return OPJ_FALSE;
}
}
if (l_current_data) {
opj_free(l_current_data);
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_end_compress(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
/* customization of the encoding */
if (! opj_j2k_setup_end_compress(p_j2k, p_manager)) {
return OPJ_FALSE;
}
if (! opj_j2k_exec(p_j2k, p_j2k->m_procedure_list, p_stream, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_start_compress(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_image_t * p_image,
opj_event_mgr_t * p_manager)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
p_j2k->m_private_image = opj_image_create0();
if (! p_j2k->m_private_image) {
opj_event_msg(p_manager, EVT_ERROR, "Failed to allocate image header.");
return OPJ_FALSE;
}
opj_copy_image_header(p_image, p_j2k->m_private_image);
/* TODO_MSD: Find a better way */
if (p_image->comps) {
OPJ_UINT32 it_comp;
for (it_comp = 0 ; it_comp < p_image->numcomps; it_comp++) {
if (p_image->comps[it_comp].data) {
p_j2k->m_private_image->comps[it_comp].data = p_image->comps[it_comp].data;
p_image->comps[it_comp].data = NULL;
}
}
}
/* customization of the validation */
if (! opj_j2k_setup_encoding_validation(p_j2k, p_manager)) {
return OPJ_FALSE;
}
/* validation of the parameters codec */
if (! opj_j2k_exec(p_j2k, p_j2k->m_validation_list, p_stream, p_manager)) {
return OPJ_FALSE;
}
/* customization of the encoding */
if (! opj_j2k_setup_header_writing(p_j2k, p_manager)) {
return OPJ_FALSE;
}
/* write header */
if (! opj_j2k_exec(p_j2k, p_j2k->m_procedure_list, p_stream, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_pre_write_tile(opj_j2k_t * p_j2k,
OPJ_UINT32 p_tile_index,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
(void)p_stream;
if (p_tile_index != p_j2k->m_current_tile_number) {
opj_event_msg(p_manager, EVT_ERROR, "The given tile index does not match.");
return OPJ_FALSE;
}
opj_event_msg(p_manager, EVT_INFO, "tile number %d / %d\n",
p_j2k->m_current_tile_number + 1, p_j2k->m_cp.tw * p_j2k->m_cp.th);
p_j2k->m_specific_param.m_encoder.m_current_tile_part_number = 0;
p_j2k->m_tcd->cur_totnum_tp = p_j2k->m_cp.tcps[p_tile_index].m_nb_tile_parts;
p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = 0;
/* initialisation before tile encoding */
if (! opj_tcd_init_encode_tile(p_j2k->m_tcd, p_j2k->m_current_tile_number,
p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static void opj_get_tile_dimensions(opj_image_t * l_image,
opj_tcd_tilecomp_t * l_tilec,
opj_image_comp_t * l_img_comp,
OPJ_UINT32* l_size_comp,
OPJ_UINT32* l_width,
OPJ_UINT32* l_height,
OPJ_UINT32* l_offset_x,
OPJ_UINT32* l_offset_y,
OPJ_UINT32* l_image_width,
OPJ_UINT32* l_stride,
OPJ_UINT32* l_tile_offset)
{
OPJ_UINT32 l_remaining;
*l_size_comp = l_img_comp->prec >> 3; /* (/8) */
l_remaining = l_img_comp->prec & 7; /* (%8) */
if (l_remaining) {
*l_size_comp += 1;
}
if (*l_size_comp == 3) {
*l_size_comp = 4;
}
*l_width = (OPJ_UINT32)(l_tilec->x1 - l_tilec->x0);
*l_height = (OPJ_UINT32)(l_tilec->y1 - l_tilec->y0);
*l_offset_x = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)l_image->x0,
(OPJ_INT32)l_img_comp->dx);
*l_offset_y = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)l_image->y0,
(OPJ_INT32)l_img_comp->dy);
*l_image_width = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)l_image->x1 -
(OPJ_INT32)l_image->x0, (OPJ_INT32)l_img_comp->dx);
*l_stride = *l_image_width - *l_width;
*l_tile_offset = ((OPJ_UINT32)l_tilec->x0 - *l_offset_x) + ((
OPJ_UINT32)l_tilec->y0 - *l_offset_y) * *l_image_width;
}
static void opj_j2k_get_tile_data(opj_tcd_t * p_tcd, OPJ_BYTE * p_data)
{
OPJ_UINT32 i, j, k = 0;
for (i = 0; i < p_tcd->image->numcomps; ++i) {
opj_image_t * l_image = p_tcd->image;
OPJ_INT32 * l_src_ptr;
opj_tcd_tilecomp_t * l_tilec = p_tcd->tcd_image->tiles->comps + i;
opj_image_comp_t * l_img_comp = l_image->comps + i;
OPJ_UINT32 l_size_comp, l_width, l_height, l_offset_x, l_offset_y,
l_image_width, l_stride, l_tile_offset;
opj_get_tile_dimensions(l_image,
l_tilec,
l_img_comp,
&l_size_comp,
&l_width,
&l_height,
&l_offset_x,
&l_offset_y,
&l_image_width,
&l_stride,
&l_tile_offset);
l_src_ptr = l_img_comp->data + l_tile_offset;
switch (l_size_comp) {
case 1: {
OPJ_CHAR * l_dest_ptr = (OPJ_CHAR*) p_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_dest_ptr;
++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_dest_ptr;
++l_src_ptr;
}
l_src_ptr += l_stride;
}
}
p_data = (OPJ_BYTE*) l_dest_ptr;
}
break;
case 2: {
OPJ_INT16 * l_dest_ptr = (OPJ_INT16 *) p_data;
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_data = (OPJ_BYTE*) l_dest_ptr;
}
break;
case 4: {
OPJ_INT32 * l_dest_ptr = (OPJ_INT32 *) p_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_data = (OPJ_BYTE*) l_dest_ptr;
}
break;
}
}
}
static OPJ_BOOL opj_j2k_post_write_tile(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 l_nb_bytes_written;
OPJ_BYTE * l_current_data = 00;
OPJ_UINT32 l_tile_size = 0;
OPJ_UINT32 l_available_data;
/* preconditions */
assert(p_j2k->m_specific_param.m_encoder.m_encoded_tile_data);
l_tile_size = p_j2k->m_specific_param.m_encoder.m_encoded_tile_size;
l_available_data = l_tile_size;
l_current_data = p_j2k->m_specific_param.m_encoder.m_encoded_tile_data;
l_nb_bytes_written = 0;
if (! opj_j2k_write_first_tile_part(p_j2k, l_current_data, &l_nb_bytes_written,
l_available_data, p_stream, p_manager)) {
return OPJ_FALSE;
}
l_current_data += l_nb_bytes_written;
l_available_data -= l_nb_bytes_written;
l_nb_bytes_written = 0;
if (! opj_j2k_write_all_tile_parts(p_j2k, l_current_data, &l_nb_bytes_written,
l_available_data, p_stream, p_manager)) {
return OPJ_FALSE;
}
l_available_data -= l_nb_bytes_written;
l_nb_bytes_written = l_tile_size - l_available_data;
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_encoded_tile_data,
l_nb_bytes_written, p_manager) != l_nb_bytes_written) {
return OPJ_FALSE;
}
++p_j2k->m_current_tile_number;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_setup_end_compress(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
/* DEVELOPER CORNER, insert your custom procedures */
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_eoc, p_manager)) {
return OPJ_FALSE;
}
if (OPJ_IS_CINEMA(p_j2k->m_cp.rsiz)) {
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_updated_tlm, p_manager)) {
return OPJ_FALSE;
}
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_epc, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_end_encoding, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_destroy_header_memory, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_setup_encoding_validation(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list,
(opj_procedure)opj_j2k_build_encoder, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list,
(opj_procedure)opj_j2k_encoding_validation, p_manager)) {
return OPJ_FALSE;
}
/* DEVELOPER CORNER, add your custom validation procedure */
if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list,
(opj_procedure)opj_j2k_mct_validation, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_setup_header_writing(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_init_info, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_soc, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_siz, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_cod, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_qcd, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_all_coc, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_all_qcc, p_manager)) {
return OPJ_FALSE;
}
if (OPJ_IS_CINEMA(p_j2k->m_cp.rsiz)) {
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_tlm, p_manager)) {
return OPJ_FALSE;
}
if (p_j2k->m_cp.rsiz == OPJ_PROFILE_CINEMA_4K) {
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_poc, p_manager)) {
return OPJ_FALSE;
}
}
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_regions, p_manager)) {
return OPJ_FALSE;
}
if (p_j2k->m_cp.comment != 00) {
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_com, p_manager)) {
return OPJ_FALSE;
}
}
/* DEVELOPER CORNER, insert your custom procedures */
if (p_j2k->m_cp.rsiz & OPJ_EXTENSION_MCT) {
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_mct_data_group, p_manager)) {
return OPJ_FALSE;
}
}
/* End of Developer Corner */
if (p_j2k->cstr_index) {
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_get_end_header, p_manager)) {
return OPJ_FALSE;
}
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_create_tcd, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_update_rates, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_first_tile_part(opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_total_data_size,
opj_stream_private_t *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 l_nb_bytes_written = 0;
OPJ_UINT32 l_current_nb_bytes_written;
OPJ_BYTE * l_begin_data = 00;
opj_tcd_t * l_tcd = 00;
opj_cp_t * l_cp = 00;
l_tcd = p_j2k->m_tcd;
l_cp = &(p_j2k->m_cp);
l_tcd->cur_pino = 0;
/*Get number of tile parts*/
p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = 0;
/* INDEX >> */
/* << INDEX */
l_current_nb_bytes_written = 0;
l_begin_data = p_data;
if (! opj_j2k_write_sot(p_j2k, p_data, &l_current_nb_bytes_written, p_stream,
p_manager)) {
return OPJ_FALSE;
}
l_nb_bytes_written += l_current_nb_bytes_written;
p_data += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
if (!OPJ_IS_CINEMA(l_cp->rsiz)) {
#if 0
for (compno = 1; compno < p_j2k->m_private_image->numcomps; compno++) {
l_current_nb_bytes_written = 0;
opj_j2k_write_coc_in_memory(p_j2k, compno, p_data, &l_current_nb_bytes_written,
p_manager);
l_nb_bytes_written += l_current_nb_bytes_written;
p_data += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
l_current_nb_bytes_written = 0;
opj_j2k_write_qcc_in_memory(p_j2k, compno, p_data, &l_current_nb_bytes_written,
p_manager);
l_nb_bytes_written += l_current_nb_bytes_written;
p_data += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
}
#endif
if (l_cp->tcps[p_j2k->m_current_tile_number].numpocs) {
l_current_nb_bytes_written = 0;
opj_j2k_write_poc_in_memory(p_j2k, p_data, &l_current_nb_bytes_written,
p_manager);
l_nb_bytes_written += l_current_nb_bytes_written;
p_data += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
}
}
l_current_nb_bytes_written = 0;
if (! opj_j2k_write_sod(p_j2k, l_tcd, p_data, &l_current_nb_bytes_written,
p_total_data_size, p_stream, p_manager)) {
return OPJ_FALSE;
}
l_nb_bytes_written += l_current_nb_bytes_written;
* p_data_written = l_nb_bytes_written;
/* Writing Psot in SOT marker */
opj_write_bytes(l_begin_data + 6, l_nb_bytes_written,
4); /* PSOT */
if (OPJ_IS_CINEMA(l_cp->rsiz)) {
opj_j2k_update_tlm(p_j2k, l_nb_bytes_written);
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_all_tile_parts(opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_total_data_size,
opj_stream_private_t *p_stream,
struct opj_event_mgr * p_manager
)
{
OPJ_UINT32 tilepartno = 0;
OPJ_UINT32 l_nb_bytes_written = 0;
OPJ_UINT32 l_current_nb_bytes_written;
OPJ_UINT32 l_part_tile_size;
OPJ_UINT32 tot_num_tp;
OPJ_UINT32 pino;
OPJ_BYTE * l_begin_data;
opj_tcp_t *l_tcp = 00;
opj_tcd_t * l_tcd = 00;
opj_cp_t * l_cp = 00;
l_tcd = p_j2k->m_tcd;
l_cp = &(p_j2k->m_cp);
l_tcp = l_cp->tcps + p_j2k->m_current_tile_number;
/*Get number of tile parts*/
tot_num_tp = opj_j2k_get_num_tp(l_cp, 0, p_j2k->m_current_tile_number);
/* start writing remaining tile parts */
++p_j2k->m_specific_param.m_encoder.m_current_tile_part_number;
for (tilepartno = 1; tilepartno < tot_num_tp ; ++tilepartno) {
p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = tilepartno;
l_current_nb_bytes_written = 0;
l_part_tile_size = 0;
l_begin_data = p_data;
if (! opj_j2k_write_sot(p_j2k, p_data, &l_current_nb_bytes_written, p_stream,
p_manager)) {
return OPJ_FALSE;
}
l_nb_bytes_written += l_current_nb_bytes_written;
p_data += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
l_part_tile_size += l_current_nb_bytes_written;
l_current_nb_bytes_written = 0;
if (! opj_j2k_write_sod(p_j2k, l_tcd, p_data, &l_current_nb_bytes_written,
p_total_data_size, p_stream, p_manager)) {
return OPJ_FALSE;
}
p_data += l_current_nb_bytes_written;
l_nb_bytes_written += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
l_part_tile_size += l_current_nb_bytes_written;
/* Writing Psot in SOT marker */
opj_write_bytes(l_begin_data + 6, l_part_tile_size,
4); /* PSOT */
if (OPJ_IS_CINEMA(l_cp->rsiz)) {
opj_j2k_update_tlm(p_j2k, l_part_tile_size);
}
++p_j2k->m_specific_param.m_encoder.m_current_tile_part_number;
}
for (pino = 1; pino <= l_tcp->numpocs; ++pino) {
l_tcd->cur_pino = pino;
/*Get number of tile parts*/
tot_num_tp = opj_j2k_get_num_tp(l_cp, pino, p_j2k->m_current_tile_number);
for (tilepartno = 0; tilepartno < tot_num_tp ; ++tilepartno) {
p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = tilepartno;
l_current_nb_bytes_written = 0;
l_part_tile_size = 0;
l_begin_data = p_data;
if (! opj_j2k_write_sot(p_j2k, p_data, &l_current_nb_bytes_written, p_stream,
p_manager)) {
return OPJ_FALSE;
}
l_nb_bytes_written += l_current_nb_bytes_written;
p_data += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
l_part_tile_size += l_current_nb_bytes_written;
l_current_nb_bytes_written = 0;
if (! opj_j2k_write_sod(p_j2k, l_tcd, p_data, &l_current_nb_bytes_written,
p_total_data_size, p_stream, p_manager)) {
return OPJ_FALSE;
}
l_nb_bytes_written += l_current_nb_bytes_written;
p_data += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
l_part_tile_size += l_current_nb_bytes_written;
/* Writing Psot in SOT marker */
opj_write_bytes(l_begin_data + 6, l_part_tile_size,
4); /* PSOT */
if (OPJ_IS_CINEMA(l_cp->rsiz)) {
opj_j2k_update_tlm(p_j2k, l_part_tile_size);
}
++p_j2k->m_specific_param.m_encoder.m_current_tile_part_number;
}
}
*p_data_written = l_nb_bytes_written;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_updated_tlm(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 l_tlm_size;
OPJ_OFF_T l_tlm_position, l_current_position;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_tlm_size = 5 * p_j2k->m_specific_param.m_encoder.m_total_tile_parts;
l_tlm_position = 6 + p_j2k->m_specific_param.m_encoder.m_tlm_start;
l_current_position = opj_stream_tell(p_stream);
if (! opj_stream_seek(p_stream, l_tlm_position, p_manager)) {
return OPJ_FALSE;
}
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer, l_tlm_size,
p_manager) != l_tlm_size) {
return OPJ_FALSE;
}
if (! opj_stream_seek(p_stream, l_current_position, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_end_encoding(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
OPJ_UNUSED(p_stream);
OPJ_UNUSED(p_manager);
opj_tcd_destroy(p_j2k->m_tcd);
p_j2k->m_tcd = 00;
if (p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer) {
opj_free(p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer);
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer = 0;
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current = 0;
}
if (p_j2k->m_specific_param.m_encoder.m_encoded_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_encoded_tile_data);
p_j2k->m_specific_param.m_encoder.m_encoded_tile_data = 0;
}
p_j2k->m_specific_param.m_encoder.m_encoded_tile_size = 0;
return OPJ_TRUE;
}
/**
* Destroys the memory associated with the decoding of headers.
*/
static OPJ_BOOL opj_j2k_destroy_header_memory(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_stream);
OPJ_UNUSED(p_manager);
if (p_j2k->m_specific_param.m_encoder.m_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = 0;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_init_info(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
opj_codestream_info_t * l_cstr_info = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
(void)l_cstr_info;
OPJ_UNUSED(p_stream);
/* TODO mergeV2: check this part which use cstr_info */
/*l_cstr_info = p_j2k->cstr_info;
if (l_cstr_info) {
OPJ_UINT32 compno;
l_cstr_info->tile = (opj_tile_info_t *) opj_malloc(p_j2k->m_cp.tw * p_j2k->m_cp.th * sizeof(opj_tile_info_t));
l_cstr_info->image_w = p_j2k->m_image->x1 - p_j2k->m_image->x0;
l_cstr_info->image_h = p_j2k->m_image->y1 - p_j2k->m_image->y0;
l_cstr_info->prog = (&p_j2k->m_cp.tcps[0])->prg;
l_cstr_info->tw = p_j2k->m_cp.tw;
l_cstr_info->th = p_j2k->m_cp.th;
l_cstr_info->tile_x = p_j2k->m_cp.tdx;*/ /* new version parser */
/*l_cstr_info->tile_y = p_j2k->m_cp.tdy;*/ /* new version parser */
/*l_cstr_info->tile_Ox = p_j2k->m_cp.tx0;*/ /* new version parser */
/*l_cstr_info->tile_Oy = p_j2k->m_cp.ty0;*/ /* new version parser */
/*l_cstr_info->numcomps = p_j2k->m_image->numcomps;
l_cstr_info->numlayers = (&p_j2k->m_cp.tcps[0])->numlayers;
l_cstr_info->numdecompos = (OPJ_INT32*) opj_malloc(p_j2k->m_image->numcomps * sizeof(OPJ_INT32));
for (compno=0; compno < p_j2k->m_image->numcomps; compno++) {
l_cstr_info->numdecompos[compno] = (&p_j2k->m_cp.tcps[0])->tccps->numresolutions - 1;
}
l_cstr_info->D_max = 0.0; */ /* ADD Marcela */
/*l_cstr_info->main_head_start = opj_stream_tell(p_stream);*/ /* position of SOC */
/*l_cstr_info->maxmarknum = 100;
l_cstr_info->marker = (opj_marker_info_t *) opj_malloc(l_cstr_info->maxmarknum * sizeof(opj_marker_info_t));
l_cstr_info->marknum = 0;
}*/
return opj_j2k_calculate_tp(p_j2k, &(p_j2k->m_cp),
&p_j2k->m_specific_param.m_encoder.m_total_tile_parts, p_j2k->m_private_image,
p_manager);
}
/**
* Creates a tile-coder decoder.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_create_tcd(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
OPJ_UNUSED(p_stream);
p_j2k->m_tcd = opj_tcd_create(OPJ_FALSE);
if (! p_j2k->m_tcd) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to create Tile Coder\n");
return OPJ_FALSE;
}
if (!opj_tcd_init(p_j2k->m_tcd, p_j2k->m_private_image, &p_j2k->m_cp,
p_j2k->m_tp)) {
opj_tcd_destroy(p_j2k->m_tcd);
p_j2k->m_tcd = 00;
return OPJ_FALSE;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_write_tile(opj_j2k_t * p_j2k,
OPJ_UINT32 p_tile_index,
OPJ_BYTE * p_data,
OPJ_UINT32 p_data_size,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
if (! opj_j2k_pre_write_tile(p_j2k, p_tile_index, p_stream, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR,
"Error while opj_j2k_pre_write_tile with tile index = %d\n", p_tile_index);
return OPJ_FALSE;
} else {
OPJ_UINT32 j;
/* Allocate data */
for (j = 0; j < p_j2k->m_tcd->image->numcomps; ++j) {
opj_tcd_tilecomp_t* l_tilec = p_j2k->m_tcd->tcd_image->tiles->comps + j;
if (! opj_alloc_tile_component_data(l_tilec)) {
opj_event_msg(p_manager, EVT_ERROR, "Error allocating tile component data.");
return OPJ_FALSE;
}
}
/* now copy data into the tile component */
if (! opj_tcd_copy_tile_data(p_j2k->m_tcd, p_data, p_data_size)) {
opj_event_msg(p_manager, EVT_ERROR,
"Size mismatch between tile data and sent data.");
return OPJ_FALSE;
}
if (! opj_j2k_post_write_tile(p_j2k, p_stream, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR,
"Error while opj_j2k_post_write_tile with tile index = %d\n", p_tile_index);
return OPJ_FALSE;
}
}
return OPJ_TRUE;
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_2775_0 |
crossvul-cpp_data_bad_5499_0 | /*
* IPv6 fragment reassembly for connection tracking
*
* Copyright (C)2004 USAGI/WIDE Project
*
* Author:
* Yasuyuki Kozakai @USAGI <yasuyuki.kozakai@toshiba.co.jp>
*
* Based on: net/ipv6/reassembly.c
*
* 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.
*/
#define pr_fmt(fmt) "IPv6-nf: " fmt
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/string.h>
#include <linux/socket.h>
#include <linux/sockios.h>
#include <linux/jiffies.h>
#include <linux/net.h>
#include <linux/list.h>
#include <linux/netdevice.h>
#include <linux/in6.h>
#include <linux/ipv6.h>
#include <linux/icmpv6.h>
#include <linux/random.h>
#include <linux/slab.h>
#include <net/sock.h>
#include <net/snmp.h>
#include <net/inet_frag.h>
#include <net/ipv6.h>
#include <net/protocol.h>
#include <net/transp_v6.h>
#include <net/rawv6.h>
#include <net/ndisc.h>
#include <net/addrconf.h>
#include <net/inet_ecn.h>
#include <net/netfilter/ipv6/nf_conntrack_ipv6.h>
#include <linux/sysctl.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv6.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <net/netfilter/ipv6/nf_defrag_ipv6.h>
static const char nf_frags_cache_name[] = "nf-frags";
struct nf_ct_frag6_skb_cb
{
struct inet6_skb_parm h;
int offset;
};
#define NFCT_FRAG6_CB(skb) ((struct nf_ct_frag6_skb_cb *)((skb)->cb))
static struct inet_frags nf_frags;
#ifdef CONFIG_SYSCTL
static int zero;
static struct ctl_table nf_ct_frag6_sysctl_table[] = {
{
.procname = "nf_conntrack_frag6_timeout",
.data = &init_net.nf_frag.frags.timeout,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "nf_conntrack_frag6_low_thresh",
.data = &init_net.nf_frag.frags.low_thresh,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = &zero,
.extra2 = &init_net.nf_frag.frags.high_thresh
},
{
.procname = "nf_conntrack_frag6_high_thresh",
.data = &init_net.nf_frag.frags.high_thresh,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = &init_net.nf_frag.frags.low_thresh
},
{ }
};
static int nf_ct_frag6_sysctl_register(struct net *net)
{
struct ctl_table *table;
struct ctl_table_header *hdr;
table = nf_ct_frag6_sysctl_table;
if (!net_eq(net, &init_net)) {
table = kmemdup(table, sizeof(nf_ct_frag6_sysctl_table),
GFP_KERNEL);
if (table == NULL)
goto err_alloc;
table[0].data = &net->nf_frag.frags.timeout;
table[1].data = &net->nf_frag.frags.low_thresh;
table[1].extra2 = &net->nf_frag.frags.high_thresh;
table[2].data = &net->nf_frag.frags.high_thresh;
table[2].extra1 = &net->nf_frag.frags.low_thresh;
table[2].extra2 = &init_net.nf_frag.frags.high_thresh;
}
hdr = register_net_sysctl(net, "net/netfilter", table);
if (hdr == NULL)
goto err_reg;
net->nf_frag.sysctl.frags_hdr = hdr;
return 0;
err_reg:
if (!net_eq(net, &init_net))
kfree(table);
err_alloc:
return -ENOMEM;
}
static void __net_exit nf_ct_frags6_sysctl_unregister(struct net *net)
{
struct ctl_table *table;
table = net->nf_frag.sysctl.frags_hdr->ctl_table_arg;
unregister_net_sysctl_table(net->nf_frag.sysctl.frags_hdr);
if (!net_eq(net, &init_net))
kfree(table);
}
#else
static int nf_ct_frag6_sysctl_register(struct net *net)
{
return 0;
}
static void __net_exit nf_ct_frags6_sysctl_unregister(struct net *net)
{
}
#endif
static inline u8 ip6_frag_ecn(const struct ipv6hdr *ipv6h)
{
return 1 << (ipv6_get_dsfield(ipv6h) & INET_ECN_MASK);
}
static unsigned int nf_hash_frag(__be32 id, const struct in6_addr *saddr,
const struct in6_addr *daddr)
{
net_get_random_once(&nf_frags.rnd, sizeof(nf_frags.rnd));
return jhash_3words(ipv6_addr_hash(saddr), ipv6_addr_hash(daddr),
(__force u32)id, nf_frags.rnd);
}
static unsigned int nf_hashfn(const struct inet_frag_queue *q)
{
const struct frag_queue *nq;
nq = container_of(q, struct frag_queue, q);
return nf_hash_frag(nq->id, &nq->saddr, &nq->daddr);
}
static void nf_ct_frag6_expire(unsigned long data)
{
struct frag_queue *fq;
struct net *net;
fq = container_of((struct inet_frag_queue *)data, struct frag_queue, q);
net = container_of(fq->q.net, struct net, nf_frag.frags);
ip6_expire_frag_queue(net, fq, &nf_frags);
}
/* Creation primitives. */
static inline struct frag_queue *fq_find(struct net *net, __be32 id,
u32 user, struct in6_addr *src,
struct in6_addr *dst, int iif, u8 ecn)
{
struct inet_frag_queue *q;
struct ip6_create_arg arg;
unsigned int hash;
arg.id = id;
arg.user = user;
arg.src = src;
arg.dst = dst;
arg.iif = iif;
arg.ecn = ecn;
local_bh_disable();
hash = nf_hash_frag(id, src, dst);
q = inet_frag_find(&net->nf_frag.frags, &nf_frags, &arg, hash);
local_bh_enable();
if (IS_ERR_OR_NULL(q)) {
inet_frag_maybe_warn_overflow(q, pr_fmt());
return NULL;
}
return container_of(q, struct frag_queue, q);
}
static int nf_ct_frag6_queue(struct frag_queue *fq, struct sk_buff *skb,
const struct frag_hdr *fhdr, int nhoff)
{
struct sk_buff *prev, *next;
unsigned int payload_len;
int offset, end;
u8 ecn;
if (fq->q.flags & INET_FRAG_COMPLETE) {
pr_debug("Already completed\n");
goto err;
}
payload_len = ntohs(ipv6_hdr(skb)->payload_len);
offset = ntohs(fhdr->frag_off) & ~0x7;
end = offset + (payload_len -
((u8 *)(fhdr + 1) - (u8 *)(ipv6_hdr(skb) + 1)));
if ((unsigned int)end > IPV6_MAXPLEN) {
pr_debug("offset is too large.\n");
return -1;
}
ecn = ip6_frag_ecn(ipv6_hdr(skb));
if (skb->ip_summed == CHECKSUM_COMPLETE) {
const unsigned char *nh = skb_network_header(skb);
skb->csum = csum_sub(skb->csum,
csum_partial(nh, (u8 *)(fhdr + 1) - nh,
0));
}
/* Is this the final fragment? */
if (!(fhdr->frag_off & htons(IP6_MF))) {
/* If we already have some bits beyond end
* or have different end, the segment is corrupted.
*/
if (end < fq->q.len ||
((fq->q.flags & INET_FRAG_LAST_IN) && end != fq->q.len)) {
pr_debug("already received last fragment\n");
goto err;
}
fq->q.flags |= INET_FRAG_LAST_IN;
fq->q.len = end;
} else {
/* Check if the fragment is rounded to 8 bytes.
* Required by the RFC.
*/
if (end & 0x7) {
/* RFC2460 says always send parameter problem in
* this case. -DaveM
*/
pr_debug("end of fragment not rounded to 8 bytes.\n");
return -1;
}
if (end > fq->q.len) {
/* Some bits beyond end -> corruption. */
if (fq->q.flags & INET_FRAG_LAST_IN) {
pr_debug("last packet already reached.\n");
goto err;
}
fq->q.len = end;
}
}
if (end == offset)
goto err;
/* Point into the IP datagram 'data' part. */
if (!pskb_pull(skb, (u8 *) (fhdr + 1) - skb->data)) {
pr_debug("queue: message is too short.\n");
goto err;
}
if (pskb_trim_rcsum(skb, end - offset)) {
pr_debug("Can't trim\n");
goto err;
}
/* Find out which fragments are in front and at the back of us
* in the chain of fragments so far. We must know where to put
* this fragment, right?
*/
prev = fq->q.fragments_tail;
if (!prev || NFCT_FRAG6_CB(prev)->offset < offset) {
next = NULL;
goto found;
}
prev = NULL;
for (next = fq->q.fragments; next != NULL; next = next->next) {
if (NFCT_FRAG6_CB(next)->offset >= offset)
break; /* bingo! */
prev = next;
}
found:
/* RFC5722, Section 4:
* When reassembling an IPv6 datagram, if
* one or more its constituent fragments is determined to be an
* overlapping fragment, the entire datagram (and any constituent
* fragments, including those not yet received) MUST be silently
* discarded.
*/
/* Check for overlap with preceding fragment. */
if (prev &&
(NFCT_FRAG6_CB(prev)->offset + prev->len) > offset)
goto discard_fq;
/* Look for overlap with succeeding segment. */
if (next && NFCT_FRAG6_CB(next)->offset < end)
goto discard_fq;
NFCT_FRAG6_CB(skb)->offset = offset;
/* Insert this fragment in the chain of fragments. */
skb->next = next;
if (!next)
fq->q.fragments_tail = skb;
if (prev)
prev->next = skb;
else
fq->q.fragments = skb;
if (skb->dev) {
fq->iif = skb->dev->ifindex;
skb->dev = NULL;
}
fq->q.stamp = skb->tstamp;
fq->q.meat += skb->len;
fq->ecn |= ecn;
if (payload_len > fq->q.max_size)
fq->q.max_size = payload_len;
add_frag_mem_limit(fq->q.net, skb->truesize);
/* The first fragment.
* nhoffset is obtained from the first fragment, of course.
*/
if (offset == 0) {
fq->nhoffset = nhoff;
fq->q.flags |= INET_FRAG_FIRST_IN;
}
return 0;
discard_fq:
inet_frag_kill(&fq->q, &nf_frags);
err:
return -1;
}
/*
* Check if this packet is complete.
*
* It is called with locked fq, and caller must check that
* queue is eligible for reassembly i.e. it is not COMPLETE,
* the last and the first frames arrived and all the bits are here.
*
* returns true if *prev skb has been transformed into the reassembled
* skb, false otherwise.
*/
static bool
nf_ct_frag6_reasm(struct frag_queue *fq, struct sk_buff *prev, struct net_device *dev)
{
struct sk_buff *fp, *head = fq->q.fragments;
int payload_len;
u8 ecn;
inet_frag_kill(&fq->q, &nf_frags);
WARN_ON(head == NULL);
WARN_ON(NFCT_FRAG6_CB(head)->offset != 0);
ecn = ip_frag_ecn_table[fq->ecn];
if (unlikely(ecn == 0xff))
return false;
/* Unfragmented part is taken from the first segment. */
payload_len = ((head->data - skb_network_header(head)) -
sizeof(struct ipv6hdr) + fq->q.len -
sizeof(struct frag_hdr));
if (payload_len > IPV6_MAXPLEN) {
net_dbg_ratelimited("nf_ct_frag6_reasm: payload len = %d\n",
payload_len);
return false;
}
/* Head of list must not be cloned. */
if (skb_unclone(head, GFP_ATOMIC))
return false;
/* If the first fragment is fragmented itself, we split
* it to two chunks: the first with data and paged part
* and the second, holding only fragments. */
if (skb_has_frag_list(head)) {
struct sk_buff *clone;
int i, plen = 0;
clone = alloc_skb(0, GFP_ATOMIC);
if (clone == NULL)
return false;
clone->next = head->next;
head->next = clone;
skb_shinfo(clone)->frag_list = skb_shinfo(head)->frag_list;
skb_frag_list_init(head);
for (i = 0; i < skb_shinfo(head)->nr_frags; i++)
plen += skb_frag_size(&skb_shinfo(head)->frags[i]);
clone->len = clone->data_len = head->data_len - plen;
head->data_len -= clone->len;
head->len -= clone->len;
clone->csum = 0;
clone->ip_summed = head->ip_summed;
add_frag_mem_limit(fq->q.net, clone->truesize);
}
/* morph head into last received skb: prev.
*
* This allows callers of ipv6 conntrack defrag to continue
* to use the last skb(frag) passed into the reasm engine.
* The last skb frag 'silently' turns into the full reassembled skb.
*
* Since prev is also part of q->fragments we have to clone it first.
*/
if (head != prev) {
struct sk_buff *iter;
fp = skb_clone(prev, GFP_ATOMIC);
if (!fp)
return false;
fp->next = prev->next;
iter = head;
while (iter) {
if (iter->next == prev) {
iter->next = fp;
break;
}
iter = iter->next;
}
skb_morph(prev, head);
prev->next = head->next;
consume_skb(head);
head = prev;
}
/* We have to remove fragment header from datagram and to relocate
* header in order to calculate ICV correctly. */
skb_network_header(head)[fq->nhoffset] = skb_transport_header(head)[0];
memmove(head->head + sizeof(struct frag_hdr), head->head,
(head->data - head->head) - sizeof(struct frag_hdr));
head->mac_header += sizeof(struct frag_hdr);
head->network_header += sizeof(struct frag_hdr);
skb_shinfo(head)->frag_list = head->next;
skb_reset_transport_header(head);
skb_push(head, head->data - skb_network_header(head));
for (fp = head->next; fp; fp = fp->next) {
head->data_len += fp->len;
head->len += fp->len;
if (head->ip_summed != fp->ip_summed)
head->ip_summed = CHECKSUM_NONE;
else if (head->ip_summed == CHECKSUM_COMPLETE)
head->csum = csum_add(head->csum, fp->csum);
head->truesize += fp->truesize;
}
sub_frag_mem_limit(fq->q.net, head->truesize);
head->ignore_df = 1;
head->next = NULL;
head->dev = dev;
head->tstamp = fq->q.stamp;
ipv6_hdr(head)->payload_len = htons(payload_len);
ipv6_change_dsfield(ipv6_hdr(head), 0xff, ecn);
IP6CB(head)->frag_max_size = sizeof(struct ipv6hdr) + fq->q.max_size;
/* Yes, and fold redundant checksum back. 8) */
if (head->ip_summed == CHECKSUM_COMPLETE)
head->csum = csum_partial(skb_network_header(head),
skb_network_header_len(head),
head->csum);
fq->q.fragments = NULL;
fq->q.fragments_tail = NULL;
return true;
}
/*
* find the header just before Fragment Header.
*
* if success return 0 and set ...
* (*prevhdrp): the value of "Next Header Field" in the header
* just before Fragment Header.
* (*prevhoff): the offset of "Next Header Field" in the header
* just before Fragment Header.
* (*fhoff) : the offset of Fragment Header.
*
* Based on ipv6_skip_hdr() in net/ipv6/exthdr.c
*
*/
static int
find_prev_fhdr(struct sk_buff *skb, u8 *prevhdrp, int *prevhoff, int *fhoff)
{
u8 nexthdr = ipv6_hdr(skb)->nexthdr;
const int netoff = skb_network_offset(skb);
u8 prev_nhoff = netoff + offsetof(struct ipv6hdr, nexthdr);
int start = netoff + sizeof(struct ipv6hdr);
int len = skb->len - start;
u8 prevhdr = NEXTHDR_IPV6;
while (nexthdr != NEXTHDR_FRAGMENT) {
struct ipv6_opt_hdr hdr;
int hdrlen;
if (!ipv6_ext_hdr(nexthdr)) {
return -1;
}
if (nexthdr == NEXTHDR_NONE) {
pr_debug("next header is none\n");
return -1;
}
if (len < (int)sizeof(struct ipv6_opt_hdr)) {
pr_debug("too short\n");
return -1;
}
if (skb_copy_bits(skb, start, &hdr, sizeof(hdr)))
BUG();
if (nexthdr == NEXTHDR_AUTH)
hdrlen = (hdr.hdrlen+2)<<2;
else
hdrlen = ipv6_optlen(&hdr);
prevhdr = nexthdr;
prev_nhoff = start;
nexthdr = hdr.nexthdr;
len -= hdrlen;
start += hdrlen;
}
if (len < 0)
return -1;
*prevhdrp = prevhdr;
*prevhoff = prev_nhoff;
*fhoff = start;
return 0;
}
int nf_ct_frag6_gather(struct net *net, struct sk_buff *skb, u32 user)
{
struct net_device *dev = skb->dev;
int fhoff, nhoff, ret;
struct frag_hdr *fhdr;
struct frag_queue *fq;
struct ipv6hdr *hdr;
u8 prevhdr;
/* Jumbo payload inhibits frag. header */
if (ipv6_hdr(skb)->payload_len == 0) {
pr_debug("payload len = 0\n");
return -EINVAL;
}
if (find_prev_fhdr(skb, &prevhdr, &nhoff, &fhoff) < 0)
return -EINVAL;
if (!pskb_may_pull(skb, fhoff + sizeof(*fhdr)))
return -ENOMEM;
skb_set_transport_header(skb, fhoff);
hdr = ipv6_hdr(skb);
fhdr = (struct frag_hdr *)skb_transport_header(skb);
fq = fq_find(net, fhdr->identification, user, &hdr->saddr, &hdr->daddr,
skb->dev ? skb->dev->ifindex : 0, ip6_frag_ecn(hdr));
if (fq == NULL) {
pr_debug("Can't find and can't create new queue\n");
return -ENOMEM;
}
spin_lock_bh(&fq->q.lock);
if (nf_ct_frag6_queue(fq, skb, fhdr, nhoff) < 0) {
ret = -EINVAL;
goto out_unlock;
}
/* after queue has assumed skb ownership, only 0 or -EINPROGRESS
* must be returned.
*/
ret = -EINPROGRESS;
if (fq->q.flags == (INET_FRAG_FIRST_IN | INET_FRAG_LAST_IN) &&
fq->q.meat == fq->q.len &&
nf_ct_frag6_reasm(fq, skb, dev))
ret = 0;
out_unlock:
spin_unlock_bh(&fq->q.lock);
inet_frag_put(&fq->q, &nf_frags);
return ret;
}
EXPORT_SYMBOL_GPL(nf_ct_frag6_gather);
static int nf_ct_net_init(struct net *net)
{
int res;
net->nf_frag.frags.high_thresh = IPV6_FRAG_HIGH_THRESH;
net->nf_frag.frags.low_thresh = IPV6_FRAG_LOW_THRESH;
net->nf_frag.frags.timeout = IPV6_FRAG_TIMEOUT;
res = inet_frags_init_net(&net->nf_frag.frags);
if (res)
return res;
res = nf_ct_frag6_sysctl_register(net);
if (res)
inet_frags_uninit_net(&net->nf_frag.frags);
return res;
}
static void nf_ct_net_exit(struct net *net)
{
nf_ct_frags6_sysctl_unregister(net);
inet_frags_exit_net(&net->nf_frag.frags, &nf_frags);
}
static struct pernet_operations nf_ct_net_ops = {
.init = nf_ct_net_init,
.exit = nf_ct_net_exit,
};
int nf_ct_frag6_init(void)
{
int ret = 0;
nf_frags.hashfn = nf_hashfn;
nf_frags.constructor = ip6_frag_init;
nf_frags.destructor = NULL;
nf_frags.qsize = sizeof(struct frag_queue);
nf_frags.match = ip6_frag_match;
nf_frags.frag_expire = nf_ct_frag6_expire;
nf_frags.frags_cache_name = nf_frags_cache_name;
ret = inet_frags_init(&nf_frags);
if (ret)
goto out;
ret = register_pernet_subsys(&nf_ct_net_ops);
if (ret)
inet_frags_fini(&nf_frags);
out:
return ret;
}
void nf_ct_frag6_cleanup(void)
{
unregister_pernet_subsys(&nf_ct_net_ops);
inet_frags_fini(&nf_frags);
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_5499_0 |
crossvul-cpp_data_bad_3992_0 | /*
* This file is part of FFmpeg.
*
* FFmpeg 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.
*
* FFmpeg 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 FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "cbs.h"
#include "cbs_internal.h"
#include "cbs_jpeg.h"
#define HEADER(name) do { \
ff_cbs_trace_header(ctx, name); \
} while (0)
#define CHECK(call) do { \
err = (call); \
if (err < 0) \
return err; \
} while (0)
#define SUBSCRIPTS(subs, ...) (subs > 0 ? ((int[subs + 1]){ subs, __VA_ARGS__ }) : NULL)
#define u(width, name, range_min, range_max) \
xu(width, name, range_min, range_max, 0)
#define us(width, name, sub, range_min, range_max) \
xu(width, name, range_min, range_max, 1, sub)
#define READ
#define READWRITE read
#define RWContext GetBitContext
#define FUNC(name) cbs_jpeg_read_ ## name
#define xu(width, name, range_min, range_max, subs, ...) do { \
uint32_t value = range_min; \
CHECK(ff_cbs_read_unsigned(ctx, rw, width, #name, \
SUBSCRIPTS(subs, __VA_ARGS__), \
&value, range_min, range_max)); \
current->name = value; \
} while (0)
#include "cbs_jpeg_syntax_template.c"
#undef READ
#undef READWRITE
#undef RWContext
#undef FUNC
#undef xu
#define WRITE
#define READWRITE write
#define RWContext PutBitContext
#define FUNC(name) cbs_jpeg_write_ ## name
#define xu(width, name, range_min, range_max, subs, ...) do { \
uint32_t value = current->name; \
CHECK(ff_cbs_write_unsigned(ctx, rw, width, #name, \
SUBSCRIPTS(subs, __VA_ARGS__), \
value, range_min, range_max)); \
} while (0)
#include "cbs_jpeg_syntax_template.c"
#undef READ
#undef READWRITE
#undef RWContext
#undef FUNC
#undef xu
static void cbs_jpeg_free_application_data(void *unit, uint8_t *content)
{
JPEGRawApplicationData *ad = (JPEGRawApplicationData*)content;
av_buffer_unref(&ad->Ap_ref);
av_freep(&content);
}
static void cbs_jpeg_free_comment(void *unit, uint8_t *content)
{
JPEGRawComment *comment = (JPEGRawComment*)content;
av_buffer_unref(&comment->Cm_ref);
av_freep(&content);
}
static void cbs_jpeg_free_scan(void *unit, uint8_t *content)
{
JPEGRawScan *scan = (JPEGRawScan*)content;
av_buffer_unref(&scan->data_ref);
av_freep(&content);
}
static int cbs_jpeg_split_fragment(CodedBitstreamContext *ctx,
CodedBitstreamFragment *frag,
int header)
{
AVBufferRef *data_ref;
uint8_t *data;
size_t data_size;
int unit, start, end, marker, next_start, next_marker;
int err, i, j, length;
if (frag->data_size < 4) {
// Definitely too short to be meaningful.
return AVERROR_INVALIDDATA;
}
for (i = 0; i + 1 < frag->data_size && frag->data[i] != 0xff; i++);
if (i > 0) {
av_log(ctx->log_ctx, AV_LOG_WARNING, "Discarding %d bytes at "
"beginning of image.\n", i);
}
for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++);
if (i + 1 >= frag->data_size && frag->data[i]) {
av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: "
"no SOI marker found.\n");
return AVERROR_INVALIDDATA;
}
marker = frag->data[i];
if (marker != JPEG_MARKER_SOI) {
av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: first "
"marker is %02x, should be SOI.\n", marker);
return AVERROR_INVALIDDATA;
}
for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++);
if (i + 1 >= frag->data_size) {
av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: "
"no image content found.\n");
return AVERROR_INVALIDDATA;
}
marker = frag->data[i];
start = i + 1;
for (unit = 0;; unit++) {
if (marker == JPEG_MARKER_EOI) {
break;
} else if (marker == JPEG_MARKER_SOS) {
for (i = start; i + 1 < frag->data_size; i++) {
if (frag->data[i] != 0xff)
continue;
end = i;
for (++i; i + 1 < frag->data_size &&
frag->data[i] == 0xff; i++);
if (i + 1 >= frag->data_size) {
next_marker = -1;
} else {
if (frag->data[i] == 0x00)
continue;
next_marker = frag->data[i];
next_start = i + 1;
}
break;
}
} else {
i = start;
if (i + 2 > frag->data_size) {
av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: "
"truncated at %02x marker.\n", marker);
return AVERROR_INVALIDDATA;
}
length = AV_RB16(frag->data + i);
if (i + length > frag->data_size) {
av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: "
"truncated at %02x marker segment.\n", marker);
return AVERROR_INVALIDDATA;
}
end = start + length;
i = end;
if (frag->data[i] != 0xff) {
next_marker = -1;
} else {
for (++i; i + 1 < frag->data_size &&
frag->data[i] == 0xff; i++);
if (i + 1 >= frag->data_size) {
next_marker = -1;
} else {
next_marker = frag->data[i];
next_start = i + 1;
}
}
}
if (marker == JPEG_MARKER_SOS) {
length = AV_RB16(frag->data + start);
data_ref = NULL;
data = av_malloc(end - start +
AV_INPUT_BUFFER_PADDING_SIZE);
if (!data)
return AVERROR(ENOMEM);
memcpy(data, frag->data + start, length);
for (i = start + length, j = length; i < end; i++, j++) {
if (frag->data[i] == 0xff) {
while (frag->data[i] == 0xff)
++i;
data[j] = 0xff;
} else {
data[j] = frag->data[i];
}
}
data_size = j;
memset(data + data_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
} else {
data = frag->data + start;
data_size = end - start;
data_ref = frag->data_ref;
}
err = ff_cbs_insert_unit_data(ctx, frag, unit, marker,
data, data_size, data_ref);
if (err < 0) {
if (!data_ref)
av_freep(&data);
return err;
}
if (next_marker == -1)
break;
marker = next_marker;
start = next_start;
}
return 0;
}
static int cbs_jpeg_read_unit(CodedBitstreamContext *ctx,
CodedBitstreamUnit *unit)
{
GetBitContext gbc;
int err;
err = init_get_bits(&gbc, unit->data, 8 * unit->data_size);
if (err < 0)
return err;
if (unit->type >= JPEG_MARKER_SOF0 &&
unit->type <= JPEG_MARKER_SOF3) {
err = ff_cbs_alloc_unit_content(ctx, unit,
sizeof(JPEGRawFrameHeader),
NULL);
if (err < 0)
return err;
err = cbs_jpeg_read_frame_header(ctx, &gbc, unit->content);
if (err < 0)
return err;
} else if (unit->type >= JPEG_MARKER_APPN &&
unit->type <= JPEG_MARKER_APPN + 15) {
err = ff_cbs_alloc_unit_content(ctx, unit,
sizeof(JPEGRawApplicationData),
&cbs_jpeg_free_application_data);
if (err < 0)
return err;
err = cbs_jpeg_read_application_data(ctx, &gbc, unit->content);
if (err < 0)
return err;
} else if (unit->type == JPEG_MARKER_SOS) {
JPEGRawScan *scan;
int pos;
err = ff_cbs_alloc_unit_content(ctx, unit,
sizeof(JPEGRawScan),
&cbs_jpeg_free_scan);
if (err < 0)
return err;
scan = unit->content;
err = cbs_jpeg_read_scan_header(ctx, &gbc, &scan->header);
if (err < 0)
return err;
pos = get_bits_count(&gbc);
av_assert0(pos % 8 == 0);
if (pos > 0) {
scan->data_size = unit->data_size - pos / 8;
scan->data_ref = av_buffer_ref(unit->data_ref);
if (!scan->data_ref)
return AVERROR(ENOMEM);
scan->data = unit->data + pos / 8;
}
} else {
switch (unit->type) {
#define SEGMENT(marker, type, func, free) \
case JPEG_MARKER_ ## marker: \
{ \
err = ff_cbs_alloc_unit_content(ctx, unit, \
sizeof(type), free); \
if (err < 0) \
return err; \
err = cbs_jpeg_read_ ## func(ctx, &gbc, unit->content); \
if (err < 0) \
return err; \
} \
break
SEGMENT(DQT, JPEGRawQuantisationTableSpecification, dqt, NULL);
SEGMENT(DHT, JPEGRawHuffmanTableSpecification, dht, NULL);
SEGMENT(COM, JPEGRawComment, comment, &cbs_jpeg_free_comment);
#undef SEGMENT
default:
return AVERROR(ENOSYS);
}
}
return 0;
}
static int cbs_jpeg_write_scan(CodedBitstreamContext *ctx,
CodedBitstreamUnit *unit,
PutBitContext *pbc)
{
JPEGRawScan *scan = unit->content;
int i, err;
err = cbs_jpeg_write_scan_header(ctx, pbc, &scan->header);
if (err < 0)
return err;
if (scan->data) {
if (scan->data_size * 8 > put_bits_left(pbc))
return AVERROR(ENOSPC);
for (i = 0; i < scan->data_size; i++)
put_bits(pbc, 8, scan->data[i]);
}
return 0;
}
static int cbs_jpeg_write_segment(CodedBitstreamContext *ctx,
CodedBitstreamUnit *unit,
PutBitContext *pbc)
{
int err;
if (unit->type >= JPEG_MARKER_SOF0 &&
unit->type <= JPEG_MARKER_SOF3) {
err = cbs_jpeg_write_frame_header(ctx, pbc, unit->content);
} else if (unit->type >= JPEG_MARKER_APPN &&
unit->type <= JPEG_MARKER_APPN + 15) {
err = cbs_jpeg_write_application_data(ctx, pbc, unit->content);
} else {
switch (unit->type) {
#define SEGMENT(marker, func) \
case JPEG_MARKER_ ## marker: \
err = cbs_jpeg_write_ ## func(ctx, pbc, unit->content); \
break;
SEGMENT(DQT, dqt);
SEGMENT(DHT, dht);
SEGMENT(COM, comment);
default:
return AVERROR_PATCHWELCOME;
}
}
return err;
}
static int cbs_jpeg_write_unit(CodedBitstreamContext *ctx,
CodedBitstreamUnit *unit)
{
CodedBitstreamJPEGContext *priv = ctx->priv_data;
PutBitContext pbc;
int err;
if (!priv->write_buffer) {
// Initial write buffer size is 1MB.
priv->write_buffer_size = 1024 * 1024;
reallocate_and_try_again:
err = av_reallocp(&priv->write_buffer, priv->write_buffer_size);
if (err < 0) {
av_log(ctx->log_ctx, AV_LOG_ERROR, "Unable to allocate a "
"sufficiently large write buffer (last attempt "
"%"SIZE_SPECIFIER" bytes).\n", priv->write_buffer_size);
return err;
}
}
init_put_bits(&pbc, priv->write_buffer, priv->write_buffer_size);
if (unit->type == JPEG_MARKER_SOS)
err = cbs_jpeg_write_scan(ctx, unit, &pbc);
else
err = cbs_jpeg_write_segment(ctx, unit, &pbc);
if (err == AVERROR(ENOSPC)) {
// Overflow.
priv->write_buffer_size *= 2;
goto reallocate_and_try_again;
}
if (err < 0) {
// Write failed for some other reason.
return err;
}
if (put_bits_count(&pbc) % 8)
unit->data_bit_padding = 8 - put_bits_count(&pbc) % 8;
else
unit->data_bit_padding = 0;
unit->data_size = (put_bits_count(&pbc) + 7) / 8;
flush_put_bits(&pbc);
err = ff_cbs_alloc_unit_data(ctx, unit, unit->data_size);
if (err < 0)
return err;
memcpy(unit->data, priv->write_buffer, unit->data_size);
return 0;
}
static int cbs_jpeg_assemble_fragment(CodedBitstreamContext *ctx,
CodedBitstreamFragment *frag)
{
const CodedBitstreamUnit *unit;
uint8_t *data;
size_t size, dp, sp;
int i;
size = 4; // SOI + EOI.
for (i = 0; i < frag->nb_units; i++) {
unit = &frag->units[i];
size += 2 + unit->data_size;
if (unit->type == JPEG_MARKER_SOS) {
for (sp = 0; sp < unit->data_size; sp++) {
if (unit->data[sp] == 0xff)
++size;
}
}
}
frag->data_ref = av_buffer_alloc(size + AV_INPUT_BUFFER_PADDING_SIZE);
if (!frag->data_ref)
return AVERROR(ENOMEM);
data = frag->data_ref->data;
dp = 0;
data[dp++] = 0xff;
data[dp++] = JPEG_MARKER_SOI;
for (i = 0; i < frag->nb_units; i++) {
unit = &frag->units[i];
data[dp++] = 0xff;
data[dp++] = unit->type;
if (unit->type != JPEG_MARKER_SOS) {
memcpy(data + dp, unit->data, unit->data_size);
dp += unit->data_size;
} else {
sp = AV_RB16(unit->data);
av_assert0(sp <= unit->data_size);
memcpy(data + dp, unit->data, sp);
dp += sp;
for (; sp < unit->data_size; sp++) {
if (unit->data[sp] == 0xff) {
data[dp++] = 0xff;
data[dp++] = 0x00;
} else {
data[dp++] = unit->data[sp];
}
}
}
}
data[dp++] = 0xff;
data[dp++] = JPEG_MARKER_EOI;
av_assert0(dp == size);
memset(data + size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
frag->data = data;
frag->data_size = size;
return 0;
}
static void cbs_jpeg_close(CodedBitstreamContext *ctx)
{
CodedBitstreamJPEGContext *priv = ctx->priv_data;
av_freep(&priv->write_buffer);
}
const CodedBitstreamType ff_cbs_type_jpeg = {
.codec_id = AV_CODEC_ID_MJPEG,
.priv_data_size = sizeof(CodedBitstreamJPEGContext),
.split_fragment = &cbs_jpeg_split_fragment,
.read_unit = &cbs_jpeg_read_unit,
.write_unit = &cbs_jpeg_write_unit,
.assemble_fragment = &cbs_jpeg_assemble_fragment,
.close = &cbs_jpeg_close,
};
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_3992_0 |
crossvul-cpp_data_good_5102_1 | /* $Id$ */
/*
* Copyright (c) 1996-1997 Sam Leffler
* Copyright (c) 1996 Pixar
*
* 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
* Pixar, 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 Pixar, 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 PIXAR, 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 "tiffiop.h"
#ifdef PIXARLOG_SUPPORT
/*
* TIFF Library.
* PixarLog Compression Support
*
* Contributed by Dan McCoy.
*
* PixarLog film support uses the TIFF library to store companded
* 11 bit values into a tiff file, which are compressed using the
* zip compressor.
*
* The codec can take as input and produce as output 32-bit IEEE float values
* as well as 16-bit or 8-bit unsigned integer values.
*
* On writing any of the above are converted into the internal
* 11-bit log format. In the case of 8 and 16 bit values, the
* input is assumed to be unsigned linear color values that represent
* the range 0-1. In the case of IEEE values, the 0-1 range is assumed to
* be the normal linear color range, in addition over 1 values are
* accepted up to a value of about 25.0 to encode "hot" highlights and such.
* The encoding is lossless for 8-bit values, slightly lossy for the
* other bit depths. The actual color precision should be better
* than the human eye can perceive with extra room to allow for
* error introduced by further image computation. As with any quantized
* color format, it is possible to perform image calculations which
* expose the quantization error. This format should certainly be less
* susceptible to such errors than standard 8-bit encodings, but more
* susceptible than straight 16-bit or 32-bit encodings.
*
* On reading the internal format is converted to the desired output format.
* The program can request which format it desires by setting the internal
* pseudo tag TIFFTAG_PIXARLOGDATAFMT to one of these possible values:
* PIXARLOGDATAFMT_FLOAT = provide IEEE float values.
* PIXARLOGDATAFMT_16BIT = provide unsigned 16-bit integer values
* PIXARLOGDATAFMT_8BIT = provide unsigned 8-bit integer values
*
* alternately PIXARLOGDATAFMT_8BITABGR provides unsigned 8-bit integer
* values with the difference that if there are exactly three or four channels
* (rgb or rgba) it swaps the channel order (bgr or abgr).
*
* PIXARLOGDATAFMT_11BITLOG provides the internal encoding directly
* packed in 16-bit values. However no tools are supplied for interpreting
* these values.
*
* "hot" (over 1.0) areas written in floating point get clamped to
* 1.0 in the integer data types.
*
* When the file is closed after writing, the bit depth and sample format
* are set always to appear as if 8-bit data has been written into it.
* That way a naive program unaware of the particulars of the encoding
* gets the format it is most likely able to handle.
*
* The codec does it's own horizontal differencing step on the coded
* values so the libraries predictor stuff should be turned off.
* The codec also handle byte swapping the encoded values as necessary
* since the library does not have the information necessary
* to know the bit depth of the raw unencoded buffer.
*
* NOTE: This decoder does not appear to update tif_rawcp, and tif_rawcc.
* This can cause problems with the implementation of CHUNKY_STRIP_READ_SUPPORT
* as noted in http://trac.osgeo.org/gdal/ticket/3894. FrankW - Jan'11
*/
#include "tif_predict.h"
#include "zlib.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* Tables for converting to/from 11 bit coded values */
#define TSIZE 2048 /* decode table size (11-bit tokens) */
#define TSIZEP1 2049 /* Plus one for slop */
#define ONE 1250 /* token value of 1.0 exactly */
#define RATIO 1.004 /* nominal ratio for log part */
#define CODE_MASK 0x7ff /* 11 bits. */
static float Fltsize;
static float LogK1, LogK2;
#define REPEAT(n, op) { int i; i=n; do { i--; op; } while (i>0); }
static void
horizontalAccumulateF(uint16 *wp, int n, int stride, float *op,
float *ToLinearF)
{
register unsigned int cr, cg, cb, ca, mask;
register float t0, t1, t2, t3;
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
t0 = ToLinearF[cr = (wp[0] & mask)];
t1 = ToLinearF[cg = (wp[1] & mask)];
t2 = ToLinearF[cb = (wp[2] & mask)];
op[0] = t0;
op[1] = t1;
op[2] = t2;
n -= 3;
while (n > 0) {
wp += 3;
op += 3;
n -= 3;
t0 = ToLinearF[(cr += wp[0]) & mask];
t1 = ToLinearF[(cg += wp[1]) & mask];
t2 = ToLinearF[(cb += wp[2]) & mask];
op[0] = t0;
op[1] = t1;
op[2] = t2;
}
} else if (stride == 4) {
t0 = ToLinearF[cr = (wp[0] & mask)];
t1 = ToLinearF[cg = (wp[1] & mask)];
t2 = ToLinearF[cb = (wp[2] & mask)];
t3 = ToLinearF[ca = (wp[3] & mask)];
op[0] = t0;
op[1] = t1;
op[2] = t2;
op[3] = t3;
n -= 4;
while (n > 0) {
wp += 4;
op += 4;
n -= 4;
t0 = ToLinearF[(cr += wp[0]) & mask];
t1 = ToLinearF[(cg += wp[1]) & mask];
t2 = ToLinearF[(cb += wp[2]) & mask];
t3 = ToLinearF[(ca += wp[3]) & mask];
op[0] = t0;
op[1] = t1;
op[2] = t2;
op[3] = t3;
}
} else {
REPEAT(stride, *op = ToLinearF[*wp&mask]; wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; *op = ToLinearF[*wp&mask]; wp++; op++)
n -= stride;
}
}
}
}
static void
horizontalAccumulate12(uint16 *wp, int n, int stride, int16 *op,
float *ToLinearF)
{
register unsigned int cr, cg, cb, ca, mask;
register float t0, t1, t2, t3;
#define SCALE12 2048.0F
#define CLAMP12(t) (((t) < 3071) ? (uint16) (t) : 3071)
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
t0 = ToLinearF[cr = (wp[0] & mask)] * SCALE12;
t1 = ToLinearF[cg = (wp[1] & mask)] * SCALE12;
t2 = ToLinearF[cb = (wp[2] & mask)] * SCALE12;
op[0] = CLAMP12(t0);
op[1] = CLAMP12(t1);
op[2] = CLAMP12(t2);
n -= 3;
while (n > 0) {
wp += 3;
op += 3;
n -= 3;
t0 = ToLinearF[(cr += wp[0]) & mask] * SCALE12;
t1 = ToLinearF[(cg += wp[1]) & mask] * SCALE12;
t2 = ToLinearF[(cb += wp[2]) & mask] * SCALE12;
op[0] = CLAMP12(t0);
op[1] = CLAMP12(t1);
op[2] = CLAMP12(t2);
}
} else if (stride == 4) {
t0 = ToLinearF[cr = (wp[0] & mask)] * SCALE12;
t1 = ToLinearF[cg = (wp[1] & mask)] * SCALE12;
t2 = ToLinearF[cb = (wp[2] & mask)] * SCALE12;
t3 = ToLinearF[ca = (wp[3] & mask)] * SCALE12;
op[0] = CLAMP12(t0);
op[1] = CLAMP12(t1);
op[2] = CLAMP12(t2);
op[3] = CLAMP12(t3);
n -= 4;
while (n > 0) {
wp += 4;
op += 4;
n -= 4;
t0 = ToLinearF[(cr += wp[0]) & mask] * SCALE12;
t1 = ToLinearF[(cg += wp[1]) & mask] * SCALE12;
t2 = ToLinearF[(cb += wp[2]) & mask] * SCALE12;
t3 = ToLinearF[(ca += wp[3]) & mask] * SCALE12;
op[0] = CLAMP12(t0);
op[1] = CLAMP12(t1);
op[2] = CLAMP12(t2);
op[3] = CLAMP12(t3);
}
} else {
REPEAT(stride, t0 = ToLinearF[*wp&mask] * SCALE12;
*op = CLAMP12(t0); wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; t0 = ToLinearF[wp[stride]&mask]*SCALE12;
*op = CLAMP12(t0); wp++; op++)
n -= stride;
}
}
}
}
static void
horizontalAccumulate16(uint16 *wp, int n, int stride, uint16 *op,
uint16 *ToLinear16)
{
register unsigned int cr, cg, cb, ca, mask;
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
op[0] = ToLinear16[cr = (wp[0] & mask)];
op[1] = ToLinear16[cg = (wp[1] & mask)];
op[2] = ToLinear16[cb = (wp[2] & mask)];
n -= 3;
while (n > 0) {
wp += 3;
op += 3;
n -= 3;
op[0] = ToLinear16[(cr += wp[0]) & mask];
op[1] = ToLinear16[(cg += wp[1]) & mask];
op[2] = ToLinear16[(cb += wp[2]) & mask];
}
} else if (stride == 4) {
op[0] = ToLinear16[cr = (wp[0] & mask)];
op[1] = ToLinear16[cg = (wp[1] & mask)];
op[2] = ToLinear16[cb = (wp[2] & mask)];
op[3] = ToLinear16[ca = (wp[3] & mask)];
n -= 4;
while (n > 0) {
wp += 4;
op += 4;
n -= 4;
op[0] = ToLinear16[(cr += wp[0]) & mask];
op[1] = ToLinear16[(cg += wp[1]) & mask];
op[2] = ToLinear16[(cb += wp[2]) & mask];
op[3] = ToLinear16[(ca += wp[3]) & mask];
}
} else {
REPEAT(stride, *op = ToLinear16[*wp&mask]; wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; *op = ToLinear16[*wp&mask]; wp++; op++)
n -= stride;
}
}
}
}
/*
* Returns the log encoded 11-bit values with the horizontal
* differencing undone.
*/
static void
horizontalAccumulate11(uint16 *wp, int n, int stride, uint16 *op)
{
register unsigned int cr, cg, cb, ca, mask;
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
op[0] = wp[0]; op[1] = wp[1]; op[2] = wp[2];
cr = wp[0]; cg = wp[1]; cb = wp[2];
n -= 3;
while (n > 0) {
wp += 3;
op += 3;
n -= 3;
op[0] = (uint16)((cr += wp[0]) & mask);
op[1] = (uint16)((cg += wp[1]) & mask);
op[2] = (uint16)((cb += wp[2]) & mask);
}
} else if (stride == 4) {
op[0] = wp[0]; op[1] = wp[1];
op[2] = wp[2]; op[3] = wp[3];
cr = wp[0]; cg = wp[1]; cb = wp[2]; ca = wp[3];
n -= 4;
while (n > 0) {
wp += 4;
op += 4;
n -= 4;
op[0] = (uint16)((cr += wp[0]) & mask);
op[1] = (uint16)((cg += wp[1]) & mask);
op[2] = (uint16)((cb += wp[2]) & mask);
op[3] = (uint16)((ca += wp[3]) & mask);
}
} else {
REPEAT(stride, *op = *wp&mask; wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; *op = *wp&mask; wp++; op++)
n -= stride;
}
}
}
}
static void
horizontalAccumulate8(uint16 *wp, int n, int stride, unsigned char *op,
unsigned char *ToLinear8)
{
register unsigned int cr, cg, cb, ca, mask;
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
op[0] = ToLinear8[cr = (wp[0] & mask)];
op[1] = ToLinear8[cg = (wp[1] & mask)];
op[2] = ToLinear8[cb = (wp[2] & mask)];
n -= 3;
while (n > 0) {
n -= 3;
wp += 3;
op += 3;
op[0] = ToLinear8[(cr += wp[0]) & mask];
op[1] = ToLinear8[(cg += wp[1]) & mask];
op[2] = ToLinear8[(cb += wp[2]) & mask];
}
} else if (stride == 4) {
op[0] = ToLinear8[cr = (wp[0] & mask)];
op[1] = ToLinear8[cg = (wp[1] & mask)];
op[2] = ToLinear8[cb = (wp[2] & mask)];
op[3] = ToLinear8[ca = (wp[3] & mask)];
n -= 4;
while (n > 0) {
n -= 4;
wp += 4;
op += 4;
op[0] = ToLinear8[(cr += wp[0]) & mask];
op[1] = ToLinear8[(cg += wp[1]) & mask];
op[2] = ToLinear8[(cb += wp[2]) & mask];
op[3] = ToLinear8[(ca += wp[3]) & mask];
}
} else {
REPEAT(stride, *op = ToLinear8[*wp&mask]; wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; *op = ToLinear8[*wp&mask]; wp++; op++)
n -= stride;
}
}
}
}
static void
horizontalAccumulate8abgr(uint16 *wp, int n, int stride, unsigned char *op,
unsigned char *ToLinear8)
{
register unsigned int cr, cg, cb, ca, mask;
register unsigned char t0, t1, t2, t3;
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
op[0] = 0;
t1 = ToLinear8[cb = (wp[2] & mask)];
t2 = ToLinear8[cg = (wp[1] & mask)];
t3 = ToLinear8[cr = (wp[0] & mask)];
op[1] = t1;
op[2] = t2;
op[3] = t3;
n -= 3;
while (n > 0) {
n -= 3;
wp += 3;
op += 4;
op[0] = 0;
t1 = ToLinear8[(cb += wp[2]) & mask];
t2 = ToLinear8[(cg += wp[1]) & mask];
t3 = ToLinear8[(cr += wp[0]) & mask];
op[1] = t1;
op[2] = t2;
op[3] = t3;
}
} else if (stride == 4) {
t0 = ToLinear8[ca = (wp[3] & mask)];
t1 = ToLinear8[cb = (wp[2] & mask)];
t2 = ToLinear8[cg = (wp[1] & mask)];
t3 = ToLinear8[cr = (wp[0] & mask)];
op[0] = t0;
op[1] = t1;
op[2] = t2;
op[3] = t3;
n -= 4;
while (n > 0) {
n -= 4;
wp += 4;
op += 4;
t0 = ToLinear8[(ca += wp[3]) & mask];
t1 = ToLinear8[(cb += wp[2]) & mask];
t2 = ToLinear8[(cg += wp[1]) & mask];
t3 = ToLinear8[(cr += wp[0]) & mask];
op[0] = t0;
op[1] = t1;
op[2] = t2;
op[3] = t3;
}
} else {
REPEAT(stride, *op = ToLinear8[*wp&mask]; wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; *op = ToLinear8[*wp&mask]; wp++; op++)
n -= stride;
}
}
}
}
/*
* State block for each open TIFF
* file using PixarLog compression/decompression.
*/
typedef struct {
TIFFPredictorState predict;
z_stream stream;
tmsize_t tbuf_size; /* only set/used on reading for now */
uint16 *tbuf;
uint16 stride;
int state;
int user_datafmt;
int quality;
#define PLSTATE_INIT 1
TIFFVSetMethod vgetparent; /* super-class method */
TIFFVSetMethod vsetparent; /* super-class method */
float *ToLinearF;
uint16 *ToLinear16;
unsigned char *ToLinear8;
uint16 *FromLT2;
uint16 *From14; /* Really for 16-bit data, but we shift down 2 */
uint16 *From8;
} PixarLogState;
static int
PixarLogMakeTables(PixarLogState *sp)
{
/*
* We make several tables here to convert between various external
* representations (float, 16-bit, and 8-bit) and the internal
* 11-bit companded representation. The 11-bit representation has two
* distinct regions. A linear bottom end up through .018316 in steps
* of about .000073, and a region of constant ratio up to about 25.
* These floating point numbers are stored in the main table ToLinearF.
* All other tables are derived from this one. The tables (and the
* ratios) are continuous at the internal seam.
*/
int nlin, lt2size;
int i, j;
double b, c, linstep, v;
float *ToLinearF;
uint16 *ToLinear16;
unsigned char *ToLinear8;
uint16 *FromLT2;
uint16 *From14; /* Really for 16-bit data, but we shift down 2 */
uint16 *From8;
c = log(RATIO);
nlin = (int)(1./c); /* nlin must be an integer */
c = 1./nlin;
b = exp(-c*ONE); /* multiplicative scale factor [b*exp(c*ONE) = 1] */
linstep = b*c*exp(1.);
LogK1 = (float)(1./c); /* if (v >= 2) token = k1*log(v*k2) */
LogK2 = (float)(1./b);
lt2size = (int)(2./linstep) + 1;
FromLT2 = (uint16 *)_TIFFmalloc(lt2size*sizeof(uint16));
From14 = (uint16 *)_TIFFmalloc(16384*sizeof(uint16));
From8 = (uint16 *)_TIFFmalloc(256*sizeof(uint16));
ToLinearF = (float *)_TIFFmalloc(TSIZEP1 * sizeof(float));
ToLinear16 = (uint16 *)_TIFFmalloc(TSIZEP1 * sizeof(uint16));
ToLinear8 = (unsigned char *)_TIFFmalloc(TSIZEP1 * sizeof(unsigned char));
if (FromLT2 == NULL || From14 == NULL || From8 == NULL ||
ToLinearF == NULL || ToLinear16 == NULL || ToLinear8 == NULL) {
if (FromLT2) _TIFFfree(FromLT2);
if (From14) _TIFFfree(From14);
if (From8) _TIFFfree(From8);
if (ToLinearF) _TIFFfree(ToLinearF);
if (ToLinear16) _TIFFfree(ToLinear16);
if (ToLinear8) _TIFFfree(ToLinear8);
sp->FromLT2 = NULL;
sp->From14 = NULL;
sp->From8 = NULL;
sp->ToLinearF = NULL;
sp->ToLinear16 = NULL;
sp->ToLinear8 = NULL;
return 0;
}
j = 0;
for (i = 0; i < nlin; i++) {
v = i * linstep;
ToLinearF[j++] = (float)v;
}
for (i = nlin; i < TSIZE; i++)
ToLinearF[j++] = (float)(b*exp(c*i));
ToLinearF[2048] = ToLinearF[2047];
for (i = 0; i < TSIZEP1; i++) {
v = ToLinearF[i]*65535.0 + 0.5;
ToLinear16[i] = (v > 65535.0) ? 65535 : (uint16)v;
v = ToLinearF[i]*255.0 + 0.5;
ToLinear8[i] = (v > 255.0) ? 255 : (unsigned char)v;
}
j = 0;
for (i = 0; i < lt2size; i++) {
if ((i*linstep)*(i*linstep) > ToLinearF[j]*ToLinearF[j+1])
j++;
FromLT2[i] = (uint16)j;
}
/*
* Since we lose info anyway on 16-bit data, we set up a 14-bit
* table and shift 16-bit values down two bits on input.
* saves a little table space.
*/
j = 0;
for (i = 0; i < 16384; i++) {
while ((i/16383.)*(i/16383.) > ToLinearF[j]*ToLinearF[j+1])
j++;
From14[i] = (uint16)j;
}
j = 0;
for (i = 0; i < 256; i++) {
while ((i/255.)*(i/255.) > ToLinearF[j]*ToLinearF[j+1])
j++;
From8[i] = (uint16)j;
}
Fltsize = (float)(lt2size/2);
sp->ToLinearF = ToLinearF;
sp->ToLinear16 = ToLinear16;
sp->ToLinear8 = ToLinear8;
sp->FromLT2 = FromLT2;
sp->From14 = From14;
sp->From8 = From8;
return 1;
}
#define DecoderState(tif) ((PixarLogState*) (tif)->tif_data)
#define EncoderState(tif) ((PixarLogState*) (tif)->tif_data)
static int PixarLogEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s);
static int PixarLogDecode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s);
#define PIXARLOGDATAFMT_UNKNOWN -1
static int
PixarLogGuessDataFmt(TIFFDirectory *td)
{
int guess = PIXARLOGDATAFMT_UNKNOWN;
int format = td->td_sampleformat;
/* If the user didn't tell us his datafmt,
* take our best guess from the bitspersample.
*/
switch (td->td_bitspersample) {
case 32:
if (format == SAMPLEFORMAT_IEEEFP)
guess = PIXARLOGDATAFMT_FLOAT;
break;
case 16:
if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT)
guess = PIXARLOGDATAFMT_16BIT;
break;
case 12:
if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_INT)
guess = PIXARLOGDATAFMT_12BITPICIO;
break;
case 11:
if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT)
guess = PIXARLOGDATAFMT_11BITLOG;
break;
case 8:
if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT)
guess = PIXARLOGDATAFMT_8BIT;
break;
}
return guess;
}
static tmsize_t
multiply_ms(tmsize_t m1, tmsize_t m2)
{
tmsize_t bytes = m1 * m2;
if (m1 && bytes / m1 != m2)
bytes = 0;
return bytes;
}
static tmsize_t
add_ms(tmsize_t m1, tmsize_t m2)
{
tmsize_t bytes = m1 + m2;
/* if either input is zero, assume overflow already occurred */
if (m1 == 0 || m2 == 0)
bytes = 0;
else if (bytes <= m1 || bytes <= m2)
bytes = 0;
return bytes;
}
static int
PixarLogFixupTags(TIFF* tif)
{
(void) tif;
return (1);
}
static int
PixarLogSetupDecode(TIFF* tif)
{
static const char module[] = "PixarLogSetupDecode";
TIFFDirectory *td = &tif->tif_dir;
PixarLogState* sp = DecoderState(tif);
tmsize_t tbuf_size;
assert(sp != NULL);
/* Make sure no byte swapping happens on the data
* after decompression. */
tif->tif_postdecode = _TIFFNoPostDecode;
/* for some reason, we can't do this in TIFFInitPixarLog */
sp->stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ?
td->td_samplesperpixel : 1);
tbuf_size = multiply_ms(multiply_ms(multiply_ms(sp->stride, td->td_imagewidth),
td->td_rowsperstrip), sizeof(uint16));
/* add one more stride in case input ends mid-stride */
tbuf_size = add_ms(tbuf_size, sizeof(uint16) * sp->stride);
if (tbuf_size == 0)
return (0); /* TODO: this is an error return without error report through TIFFErrorExt */
sp->tbuf = (uint16 *) _TIFFmalloc(tbuf_size);
if (sp->tbuf == NULL)
return (0);
sp->tbuf_size = tbuf_size;
if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN)
sp->user_datafmt = PixarLogGuessDataFmt(td);
if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) {
TIFFErrorExt(tif->tif_clientdata, module,
"PixarLog compression can't handle bits depth/data format combination (depth: %d)",
td->td_bitspersample);
return (0);
}
if (inflateInit(&sp->stream) != Z_OK) {
TIFFErrorExt(tif->tif_clientdata, module, "%s", sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
} else {
sp->state |= PLSTATE_INIT;
return (1);
}
}
/*
* Setup state for decoding a strip.
*/
static int
PixarLogPreDecode(TIFF* tif, uint16 s)
{
static const char module[] = "PixarLogPreDecode";
PixarLogState* sp = DecoderState(tif);
(void) s;
assert(sp != NULL);
sp->stream.next_in = tif->tif_rawdata;
assert(sizeof(sp->stream.avail_in)==4); /* if this assert gets raised,
we need to simplify this code to reflect a ZLib that is likely updated
to deal with 8byte memory sizes, though this code will respond
appropriately even before we simplify it */
sp->stream.avail_in = (uInt) tif->tif_rawcc;
if ((tmsize_t)sp->stream.avail_in != tif->tif_rawcc)
{
TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size");
return (0);
}
return (inflateReset(&sp->stream) == Z_OK);
}
static int
PixarLogDecode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s)
{
static const char module[] = "PixarLogDecode";
TIFFDirectory *td = &tif->tif_dir;
PixarLogState* sp = DecoderState(tif);
tmsize_t i;
tmsize_t nsamples;
int llen;
uint16 *up;
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_FLOAT:
nsamples = occ / sizeof(float); /* XXX float == 32 bits */
break;
case PIXARLOGDATAFMT_16BIT:
case PIXARLOGDATAFMT_12BITPICIO:
case PIXARLOGDATAFMT_11BITLOG:
nsamples = occ / sizeof(uint16); /* XXX uint16 == 16 bits */
break;
case PIXARLOGDATAFMT_8BIT:
case PIXARLOGDATAFMT_8BITABGR:
nsamples = occ;
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"%d bit input not supported in PixarLog",
td->td_bitspersample);
return 0;
}
llen = sp->stride * td->td_imagewidth;
(void) s;
assert(sp != NULL);
sp->stream.next_out = (unsigned char *) sp->tbuf;
assert(sizeof(sp->stream.avail_out)==4); /* if this assert gets raised,
we need to simplify this code to reflect a ZLib that is likely updated
to deal with 8byte memory sizes, though this code will respond
appropriately even before we simplify it */
sp->stream.avail_out = (uInt) (nsamples * sizeof(uint16));
if (sp->stream.avail_out != nsamples * sizeof(uint16))
{
TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size");
return (0);
}
/* Check that we will not fill more than what was allocated */
if (sp->stream.avail_out > sp->tbuf_size)
{
TIFFErrorExt(tif->tif_clientdata, module, "sp->stream.avail_out > sp->tbuf_size");
return (0);
}
do {
int state = inflate(&sp->stream, Z_PARTIAL_FLUSH);
if (state == Z_STREAM_END) {
break; /* XXX */
}
if (state == Z_DATA_ERROR) {
TIFFErrorExt(tif->tif_clientdata, module,
"Decoding error at scanline %lu, %s",
(unsigned long) tif->tif_row, sp->stream.msg ? sp->stream.msg : "(null)");
if (inflateSync(&sp->stream) != Z_OK)
return (0);
continue;
}
if (state != Z_OK) {
TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s",
sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
}
} while (sp->stream.avail_out > 0);
/* hopefully, we got all the bytes we needed */
if (sp->stream.avail_out != 0) {
TIFFErrorExt(tif->tif_clientdata, module,
"Not enough data at scanline %lu (short " TIFF_UINT64_FORMAT " bytes)",
(unsigned long) tif->tif_row, (TIFF_UINT64_T) sp->stream.avail_out);
return (0);
}
up = sp->tbuf;
/* Swap bytes in the data if from a different endian machine. */
if (tif->tif_flags & TIFF_SWAB)
TIFFSwabArrayOfShort(up, nsamples);
/*
* if llen is not an exact multiple of nsamples, the decode operation
* may overflow the output buffer, so truncate it enough to prevent
* that but still salvage as much data as possible.
*/
if (nsamples % llen) {
TIFFWarningExt(tif->tif_clientdata, module,
"stride %lu is not a multiple of sample count, "
"%lu, data truncated.", (unsigned long) llen, (unsigned long) nsamples);
nsamples -= nsamples % llen;
}
for (i = 0; i < nsamples; i += llen, up += llen) {
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_FLOAT:
horizontalAccumulateF(up, llen, sp->stride,
(float *)op, sp->ToLinearF);
op += llen * sizeof(float);
break;
case PIXARLOGDATAFMT_16BIT:
horizontalAccumulate16(up, llen, sp->stride,
(uint16 *)op, sp->ToLinear16);
op += llen * sizeof(uint16);
break;
case PIXARLOGDATAFMT_12BITPICIO:
horizontalAccumulate12(up, llen, sp->stride,
(int16 *)op, sp->ToLinearF);
op += llen * sizeof(int16);
break;
case PIXARLOGDATAFMT_11BITLOG:
horizontalAccumulate11(up, llen, sp->stride,
(uint16 *)op);
op += llen * sizeof(uint16);
break;
case PIXARLOGDATAFMT_8BIT:
horizontalAccumulate8(up, llen, sp->stride,
(unsigned char *)op, sp->ToLinear8);
op += llen * sizeof(unsigned char);
break;
case PIXARLOGDATAFMT_8BITABGR:
horizontalAccumulate8abgr(up, llen, sp->stride,
(unsigned char *)op, sp->ToLinear8);
op += llen * sizeof(unsigned char);
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"Unsupported bits/sample: %d",
td->td_bitspersample);
return (0);
}
}
return (1);
}
static int
PixarLogSetupEncode(TIFF* tif)
{
static const char module[] = "PixarLogSetupEncode";
TIFFDirectory *td = &tif->tif_dir;
PixarLogState* sp = EncoderState(tif);
tmsize_t tbuf_size;
assert(sp != NULL);
/* for some reason, we can't do this in TIFFInitPixarLog */
sp->stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ?
td->td_samplesperpixel : 1);
tbuf_size = multiply_ms(multiply_ms(multiply_ms(sp->stride, td->td_imagewidth),
td->td_rowsperstrip), sizeof(uint16));
if (tbuf_size == 0)
return (0); /* TODO: this is an error return without error report through TIFFErrorExt */
sp->tbuf = (uint16 *) _TIFFmalloc(tbuf_size);
if (sp->tbuf == NULL)
return (0);
if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN)
sp->user_datafmt = PixarLogGuessDataFmt(td);
if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) {
TIFFErrorExt(tif->tif_clientdata, module, "PixarLog compression can't handle %d bit linear encodings", td->td_bitspersample);
return (0);
}
if (deflateInit(&sp->stream, sp->quality) != Z_OK) {
TIFFErrorExt(tif->tif_clientdata, module, "%s", sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
} else {
sp->state |= PLSTATE_INIT;
return (1);
}
}
/*
* Reset encoding state at the start of a strip.
*/
static int
PixarLogPreEncode(TIFF* tif, uint16 s)
{
static const char module[] = "PixarLogPreEncode";
PixarLogState *sp = EncoderState(tif);
(void) s;
assert(sp != NULL);
sp->stream.next_out = tif->tif_rawdata;
assert(sizeof(sp->stream.avail_out)==4); /* if this assert gets raised,
we need to simplify this code to reflect a ZLib that is likely updated
to deal with 8byte memory sizes, though this code will respond
appropriately even before we simplify it */
sp->stream.avail_out = (uInt)tif->tif_rawdatasize;
if ((tmsize_t)sp->stream.avail_out != tif->tif_rawdatasize)
{
TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size");
return (0);
}
return (deflateReset(&sp->stream) == Z_OK);
}
static void
horizontalDifferenceF(float *ip, int n, int stride, uint16 *wp, uint16 *FromLT2)
{
int32 r1, g1, b1, a1, r2, g2, b2, a2, mask;
float fltsize = Fltsize;
#define CLAMP(v) ( (v<(float)0.) ? 0 \
: (v<(float)2.) ? FromLT2[(int)(v*fltsize)] \
: (v>(float)24.2) ? 2047 \
: LogK1*log(v*LogK2) + 0.5 )
mask = CODE_MASK;
if (n >= stride) {
if (stride == 3) {
r2 = wp[0] = (uint16) CLAMP(ip[0]);
g2 = wp[1] = (uint16) CLAMP(ip[1]);
b2 = wp[2] = (uint16) CLAMP(ip[2]);
n -= 3;
while (n > 0) {
n -= 3;
wp += 3;
ip += 3;
r1 = (int32) CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = (int32) CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = (int32) CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
}
} else if (stride == 4) {
r2 = wp[0] = (uint16) CLAMP(ip[0]);
g2 = wp[1] = (uint16) CLAMP(ip[1]);
b2 = wp[2] = (uint16) CLAMP(ip[2]);
a2 = wp[3] = (uint16) CLAMP(ip[3]);
n -= 4;
while (n > 0) {
n -= 4;
wp += 4;
ip += 4;
r1 = (int32) CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = (int32) CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = (int32) CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
a1 = (int32) CLAMP(ip[3]); wp[3] = (uint16)((a1-a2) & mask); a2 = a1;
}
} else {
ip += n - 1; /* point to last one */
wp += n - 1; /* point to last one */
n -= stride;
while (n > 0) {
REPEAT(stride, wp[0] = (uint16) CLAMP(ip[0]);
wp[stride] -= wp[0];
wp[stride] &= mask;
wp--; ip--)
n -= stride;
}
REPEAT(stride, wp[0] = (uint16) CLAMP(ip[0]); wp--; ip--)
}
}
}
static void
horizontalDifference16(unsigned short *ip, int n, int stride,
unsigned short *wp, uint16 *From14)
{
register int r1, g1, b1, a1, r2, g2, b2, a2, mask;
/* assumption is unsigned pixel values */
#undef CLAMP
#define CLAMP(v) From14[(v) >> 2]
mask = CODE_MASK;
if (n >= stride) {
if (stride == 3) {
r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);
b2 = wp[2] = CLAMP(ip[2]);
n -= 3;
while (n > 0) {
n -= 3;
wp += 3;
ip += 3;
r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
}
} else if (stride == 4) {
r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);
b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]);
n -= 4;
while (n > 0) {
n -= 4;
wp += 4;
ip += 4;
r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
a1 = CLAMP(ip[3]); wp[3] = (uint16)((a1-a2) & mask); a2 = a1;
}
} else {
ip += n - 1; /* point to last one */
wp += n - 1; /* point to last one */
n -= stride;
while (n > 0) {
REPEAT(stride, wp[0] = CLAMP(ip[0]);
wp[stride] -= wp[0];
wp[stride] &= mask;
wp--; ip--)
n -= stride;
}
REPEAT(stride, wp[0] = CLAMP(ip[0]); wp--; ip--)
}
}
}
static void
horizontalDifference8(unsigned char *ip, int n, int stride,
unsigned short *wp, uint16 *From8)
{
register int r1, g1, b1, a1, r2, g2, b2, a2, mask;
#undef CLAMP
#define CLAMP(v) (From8[(v)])
mask = CODE_MASK;
if (n >= stride) {
if (stride == 3) {
r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);
b2 = wp[2] = CLAMP(ip[2]);
n -= 3;
while (n > 0) {
n -= 3;
r1 = CLAMP(ip[3]); wp[3] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = CLAMP(ip[4]); wp[4] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = CLAMP(ip[5]); wp[5] = (uint16)((b1-b2) & mask); b2 = b1;
wp += 3;
ip += 3;
}
} else if (stride == 4) {
r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);
b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]);
n -= 4;
while (n > 0) {
n -= 4;
r1 = CLAMP(ip[4]); wp[4] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = CLAMP(ip[5]); wp[5] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = CLAMP(ip[6]); wp[6] = (uint16)((b1-b2) & mask); b2 = b1;
a1 = CLAMP(ip[7]); wp[7] = (uint16)((a1-a2) & mask); a2 = a1;
wp += 4;
ip += 4;
}
} else {
wp += n + stride - 1; /* point to last one */
ip += n + stride - 1; /* point to last one */
n -= stride;
while (n > 0) {
REPEAT(stride, wp[0] = CLAMP(ip[0]);
wp[stride] -= wp[0];
wp[stride] &= mask;
wp--; ip--)
n -= stride;
}
REPEAT(stride, wp[0] = CLAMP(ip[0]); wp--; ip--)
}
}
}
/*
* Encode a chunk of pixels.
*/
static int
PixarLogEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
{
static const char module[] = "PixarLogEncode";
TIFFDirectory *td = &tif->tif_dir;
PixarLogState *sp = EncoderState(tif);
tmsize_t i;
tmsize_t n;
int llen;
unsigned short * up;
(void) s;
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_FLOAT:
n = cc / sizeof(float); /* XXX float == 32 bits */
break;
case PIXARLOGDATAFMT_16BIT:
case PIXARLOGDATAFMT_12BITPICIO:
case PIXARLOGDATAFMT_11BITLOG:
n = cc / sizeof(uint16); /* XXX uint16 == 16 bits */
break;
case PIXARLOGDATAFMT_8BIT:
case PIXARLOGDATAFMT_8BITABGR:
n = cc;
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"%d bit input not supported in PixarLog",
td->td_bitspersample);
return 0;
}
llen = sp->stride * td->td_imagewidth;
for (i = 0, up = sp->tbuf; i < n; i += llen, up += llen) {
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_FLOAT:
horizontalDifferenceF((float *)bp, llen,
sp->stride, up, sp->FromLT2);
bp += llen * sizeof(float);
break;
case PIXARLOGDATAFMT_16BIT:
horizontalDifference16((uint16 *)bp, llen,
sp->stride, up, sp->From14);
bp += llen * sizeof(uint16);
break;
case PIXARLOGDATAFMT_8BIT:
horizontalDifference8((unsigned char *)bp, llen,
sp->stride, up, sp->From8);
bp += llen * sizeof(unsigned char);
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"%d bit input not supported in PixarLog",
td->td_bitspersample);
return 0;
}
}
sp->stream.next_in = (unsigned char *) sp->tbuf;
assert(sizeof(sp->stream.avail_in)==4); /* if this assert gets raised,
we need to simplify this code to reflect a ZLib that is likely updated
to deal with 8byte memory sizes, though this code will respond
appropriately even before we simplify it */
sp->stream.avail_in = (uInt) (n * sizeof(uint16));
if ((sp->stream.avail_in / sizeof(uint16)) != (uInt) n)
{
TIFFErrorExt(tif->tif_clientdata, module,
"ZLib cannot deal with buffers this size");
return (0);
}
do {
if (deflate(&sp->stream, Z_NO_FLUSH) != Z_OK) {
TIFFErrorExt(tif->tif_clientdata, module, "Encoder error: %s",
sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
}
if (sp->stream.avail_out == 0) {
tif->tif_rawcc = tif->tif_rawdatasize;
TIFFFlushData1(tif);
sp->stream.next_out = tif->tif_rawdata;
sp->stream.avail_out = (uInt) tif->tif_rawdatasize; /* this is a safe typecast, as check is made already in PixarLogPreEncode */
}
} while (sp->stream.avail_in > 0);
return (1);
}
/*
* Finish off an encoded strip by flushing the last
* string and tacking on an End Of Information code.
*/
static int
PixarLogPostEncode(TIFF* tif)
{
static const char module[] = "PixarLogPostEncode";
PixarLogState *sp = EncoderState(tif);
int state;
sp->stream.avail_in = 0;
do {
state = deflate(&sp->stream, Z_FINISH);
switch (state) {
case Z_STREAM_END:
case Z_OK:
if ((tmsize_t)sp->stream.avail_out != tif->tif_rawdatasize) {
tif->tif_rawcc =
tif->tif_rawdatasize - sp->stream.avail_out;
TIFFFlushData1(tif);
sp->stream.next_out = tif->tif_rawdata;
sp->stream.avail_out = (uInt) tif->tif_rawdatasize; /* this is a safe typecast, as check is made already in PixarLogPreEncode */
}
break;
default:
TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s",
sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
}
} while (state != Z_STREAM_END);
return (1);
}
static void
PixarLogClose(TIFF* tif)
{
TIFFDirectory *td = &tif->tif_dir;
/* In a really sneaky (and really incorrect, and untruthful, and
* troublesome, and error-prone) maneuver that completely goes against
* the spirit of TIFF, and breaks TIFF, on close, we covertly
* modify both bitspersample and sampleformat in the directory to
* indicate 8-bit linear. This way, the decode "just works" even for
* readers that don't know about PixarLog, or how to set
* the PIXARLOGDATFMT pseudo-tag.
*/
td->td_bitspersample = 8;
td->td_sampleformat = SAMPLEFORMAT_UINT;
}
static void
PixarLogCleanup(TIFF* tif)
{
PixarLogState* sp = (PixarLogState*) tif->tif_data;
assert(sp != 0);
(void)TIFFPredictorCleanup(tif);
tif->tif_tagmethods.vgetfield = sp->vgetparent;
tif->tif_tagmethods.vsetfield = sp->vsetparent;
if (sp->FromLT2) _TIFFfree(sp->FromLT2);
if (sp->From14) _TIFFfree(sp->From14);
if (sp->From8) _TIFFfree(sp->From8);
if (sp->ToLinearF) _TIFFfree(sp->ToLinearF);
if (sp->ToLinear16) _TIFFfree(sp->ToLinear16);
if (sp->ToLinear8) _TIFFfree(sp->ToLinear8);
if (sp->state&PLSTATE_INIT) {
if (tif->tif_mode == O_RDONLY)
inflateEnd(&sp->stream);
else
deflateEnd(&sp->stream);
}
if (sp->tbuf)
_TIFFfree(sp->tbuf);
_TIFFfree(sp);
tif->tif_data = NULL;
_TIFFSetDefaultCompressionState(tif);
}
static int
PixarLogVSetField(TIFF* tif, uint32 tag, va_list ap)
{
static const char module[] = "PixarLogVSetField";
PixarLogState *sp = (PixarLogState *)tif->tif_data;
int result;
switch (tag) {
case TIFFTAG_PIXARLOGQUALITY:
sp->quality = (int) va_arg(ap, int);
if (tif->tif_mode != O_RDONLY && (sp->state&PLSTATE_INIT)) {
if (deflateParams(&sp->stream,
sp->quality, Z_DEFAULT_STRATEGY) != Z_OK) {
TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s",
sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
}
}
return (1);
case TIFFTAG_PIXARLOGDATAFMT:
sp->user_datafmt = (int) va_arg(ap, int);
/* Tweak the TIFF header so that the rest of libtiff knows what
* size of data will be passed between app and library, and
* assume that the app knows what it is doing and is not
* confused by these header manipulations...
*/
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_8BIT:
case PIXARLOGDATAFMT_8BITABGR:
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 8);
TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
break;
case PIXARLOGDATAFMT_11BITLOG:
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16);
TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
break;
case PIXARLOGDATAFMT_12BITPICIO:
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16);
TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_INT);
break;
case PIXARLOGDATAFMT_16BIT:
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16);
TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
break;
case PIXARLOGDATAFMT_FLOAT:
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 32);
TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP);
break;
}
/*
* Must recalculate sizes should bits/sample change.
*/
tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tmsize_t)(-1);
tif->tif_scanlinesize = TIFFScanlineSize(tif);
result = 1; /* NB: pseudo tag */
break;
default:
result = (*sp->vsetparent)(tif, tag, ap);
}
return (result);
}
static int
PixarLogVGetField(TIFF* tif, uint32 tag, va_list ap)
{
PixarLogState *sp = (PixarLogState *)tif->tif_data;
switch (tag) {
case TIFFTAG_PIXARLOGQUALITY:
*va_arg(ap, int*) = sp->quality;
break;
case TIFFTAG_PIXARLOGDATAFMT:
*va_arg(ap, int*) = sp->user_datafmt;
break;
default:
return (*sp->vgetparent)(tif, tag, ap);
}
return (1);
}
static const TIFFField pixarlogFields[] = {
{TIFFTAG_PIXARLOGDATAFMT, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL},
{TIFFTAG_PIXARLOGQUALITY, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL}
};
int
TIFFInitPixarLog(TIFF* tif, int scheme)
{
static const char module[] = "TIFFInitPixarLog";
PixarLogState* sp;
assert(scheme == COMPRESSION_PIXARLOG);
/*
* Merge codec-specific tag information.
*/
if (!_TIFFMergeFields(tif, pixarlogFields,
TIFFArrayCount(pixarlogFields))) {
TIFFErrorExt(tif->tif_clientdata, module,
"Merging PixarLog codec-specific tags failed");
return 0;
}
/*
* Allocate state block so tag methods have storage to record values.
*/
tif->tif_data = (uint8*) _TIFFmalloc(sizeof (PixarLogState));
if (tif->tif_data == NULL)
goto bad;
sp = (PixarLogState*) tif->tif_data;
_TIFFmemset(sp, 0, sizeof (*sp));
sp->stream.data_type = Z_BINARY;
sp->user_datafmt = PIXARLOGDATAFMT_UNKNOWN;
/*
* Install codec methods.
*/
tif->tif_fixuptags = PixarLogFixupTags;
tif->tif_setupdecode = PixarLogSetupDecode;
tif->tif_predecode = PixarLogPreDecode;
tif->tif_decoderow = PixarLogDecode;
tif->tif_decodestrip = PixarLogDecode;
tif->tif_decodetile = PixarLogDecode;
tif->tif_setupencode = PixarLogSetupEncode;
tif->tif_preencode = PixarLogPreEncode;
tif->tif_postencode = PixarLogPostEncode;
tif->tif_encoderow = PixarLogEncode;
tif->tif_encodestrip = PixarLogEncode;
tif->tif_encodetile = PixarLogEncode;
tif->tif_close = PixarLogClose;
tif->tif_cleanup = PixarLogCleanup;
/* Override SetField so we can handle our private pseudo-tag */
sp->vgetparent = tif->tif_tagmethods.vgetfield;
tif->tif_tagmethods.vgetfield = PixarLogVGetField; /* hook for codec tags */
sp->vsetparent = tif->tif_tagmethods.vsetfield;
tif->tif_tagmethods.vsetfield = PixarLogVSetField; /* hook for codec tags */
/* Default values for codec-specific fields */
sp->quality = Z_DEFAULT_COMPRESSION; /* default comp. level */
sp->state = 0;
/* we don't wish to use the predictor,
* the default is none, which predictor value 1
*/
(void) TIFFPredictorInit(tif);
/*
* build the companding tables
*/
PixarLogMakeTables(sp);
return (1);
bad:
TIFFErrorExt(tif->tif_clientdata, module,
"No space for PixarLog state block");
return (0);
}
#endif /* PIXARLOG_SUPPORT */
/* 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-787/c/good_5102_1 |
crossvul-cpp_data_bad_3106_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP SSSSS DDDD %
% P P SS D D %
% PPPP SSS D D %
% P SS D D %
% P SSSSS DDDD %
% %
% %
% Read/Write Adobe Photoshop Image Format %
% %
% Software Design %
% Cristy %
% Leonard Rosenthol %
% July 1992 %
% Dirk Lemstra %
% December 2013 %
% %
% %
% Copyright 1999-2017 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/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/channel.h"
#include "MagickCore/colormap.h"
#include "MagickCore/colormap-private.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/constitute.h"
#include "MagickCore/enhance.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/module.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/profile.h"
#include "MagickCore/property.h"
#include "MagickCore/registry.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
#ifdef MAGICKCORE_ZLIB_DELEGATE
#include <zlib.h>
#endif
#include "psd-private.h"
/*
Define declaractions.
*/
#define MaxPSDChannels 56
#define PSDQuantum(x) (((ssize_t) (x)+1) & -2)
/*
Enumerated declaractions.
*/
typedef enum
{
Raw = 0,
RLE = 1,
ZipWithoutPrediction = 2,
ZipWithPrediction = 3
} PSDCompressionType;
typedef enum
{
BitmapMode = 0,
GrayscaleMode = 1,
IndexedMode = 2,
RGBMode = 3,
CMYKMode = 4,
MultichannelMode = 7,
DuotoneMode = 8,
LabMode = 9
} PSDImageType;
/*
Typedef declaractions.
*/
typedef struct _ChannelInfo
{
short int
type;
size_t
size;
} ChannelInfo;
typedef struct _MaskInfo
{
Image
*image;
RectangleInfo
page;
unsigned char
background,
flags;
} MaskInfo;
typedef struct _LayerInfo
{
ChannelInfo
channel_info[MaxPSDChannels];
char
blendkey[4];
Image
*image;
MaskInfo
mask;
Quantum
opacity;
RectangleInfo
page;
size_t
offset_x,
offset_y;
unsigned char
clipping,
flags,
name[256],
visible;
unsigned short
channels;
StringInfo
*info;
} LayerInfo;
/*
Forward declarations.
*/
static MagickBooleanType
WritePSDImage(const ImageInfo *,Image *,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s P S D %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsPSD()() returns MagickTrue if the image format type, identified by the
% magick string, is PSD.
%
% The format of the IsPSD method is:
%
% MagickBooleanType IsPSD(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsPSD(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (LocaleNCompare((const char *) magick,"8BPS",4) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadPSDImage() reads an Adobe Photoshop 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 ReadPSDImage method is:
%
% Image *ReadPSDImage(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 const char *CompositeOperatorToPSDBlendMode(CompositeOperator op)
{
const char
*blend_mode;
switch (op)
{
case ColorBurnCompositeOp: blend_mode = "idiv"; break;
case ColorDodgeCompositeOp: blend_mode = "div "; break;
case ColorizeCompositeOp: blend_mode = "colr"; break;
case DarkenCompositeOp: blend_mode = "dark"; break;
case DifferenceCompositeOp: blend_mode = "diff"; break;
case DissolveCompositeOp: blend_mode = "diss"; break;
case ExclusionCompositeOp: blend_mode = "smud"; break;
case HardLightCompositeOp: blend_mode = "hLit"; break;
case HardMixCompositeOp: blend_mode = "hMix"; break;
case HueCompositeOp: blend_mode = "hue "; break;
case LightenCompositeOp: blend_mode = "lite"; break;
case LinearBurnCompositeOp: blend_mode = "lbrn"; break;
case LinearDodgeCompositeOp:blend_mode = "lddg"; break;
case LinearLightCompositeOp:blend_mode = "lLit"; break;
case LuminizeCompositeOp: blend_mode = "lum "; break;
case MultiplyCompositeOp: blend_mode = "mul "; break;
case OverCompositeOp: blend_mode = "norm"; break;
case OverlayCompositeOp: blend_mode = "over"; break;
case PinLightCompositeOp: blend_mode = "pLit"; break;
case SaturateCompositeOp: blend_mode = "sat "; break;
case ScreenCompositeOp: blend_mode = "scrn"; break;
case SoftLightCompositeOp: blend_mode = "sLit"; break;
case VividLightCompositeOp: blend_mode = "vLit"; break;
default: blend_mode = "norm";
}
return(blend_mode);
}
/*
For some reason Photoshop seems to blend semi-transparent pixels with white.
This method reverts the blending. This can be disabled by setting the
option 'psd:alpha-unblend' to off.
*/
static MagickBooleanType CorrectPSDAlphaBlend(const ImageInfo *image_info,
Image *image,ExceptionInfo* exception)
{
const char
*option;
MagickBooleanType
status;
ssize_t
y;
if (image->alpha_trait != BlendPixelTrait || image->colorspace != sRGBColorspace)
return(MagickTrue);
option=GetImageOption(image_info,"psd:alpha-unblend");
if (IsStringFalse(option) != MagickFalse)
return(MagickTrue);
status=MagickTrue;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
gamma;
register ssize_t
i;
gamma=QuantumScale*GetPixelAlpha(image, q);
if (gamma != 0.0 && gamma != 1.0)
{
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
if (channel != AlphaPixelChannel)
q[i]=ClampToQuantum((q[i]-((1.0-gamma)*QuantumRange))/gamma);
}
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
status=MagickFalse;
}
return(status);
}
static inline CompressionType ConvertPSDCompression(
PSDCompressionType compression)
{
switch (compression)
{
case RLE:
return RLECompression;
case ZipWithPrediction:
case ZipWithoutPrediction:
return ZipCompression;
default:
return NoCompression;
}
}
static MagickBooleanType ApplyPSDLayerOpacity(Image *image,Quantum opacity,
MagickBooleanType revert,ExceptionInfo *exception)
{
MagickBooleanType
status;
ssize_t
y;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" applying layer opacity %.20g", (double) opacity);
if (opacity == OpaqueAlpha)
return(MagickTrue);
image->alpha_trait=BlendPixelTrait;
status=MagickTrue;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (revert == MagickFalse)
SetPixelAlpha(image,(Quantum) (QuantumScale*(GetPixelAlpha(image,q))*
opacity),q);
else if (opacity > 0)
SetPixelAlpha(image,(Quantum) (QuantumRange*(GetPixelAlpha(image,q)/
(MagickRealType) opacity)),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
status=MagickFalse;
}
return(status);
}
static MagickBooleanType ApplyPSDOpacityMask(Image *image,const Image *mask,
Quantum background,MagickBooleanType revert,ExceptionInfo *exception)
{
Image
*complete_mask;
MagickBooleanType
status;
PixelInfo
color;
ssize_t
y;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" applying opacity mask");
complete_mask=CloneImage(image,image->columns,image->rows,MagickTrue,
exception);
complete_mask->alpha_trait=BlendPixelTrait;
GetPixelInfo(complete_mask,&color);
color.red=background;
SetImageColor(complete_mask,&color,exception);
status=CompositeImage(complete_mask,mask,OverCompositeOp,MagickTrue,
mask->page.x-image->page.x,mask->page.y-image->page.y,exception);
if (status == MagickFalse)
{
complete_mask=DestroyImage(complete_mask);
return(status);
}
image->alpha_trait=BlendPixelTrait;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register Quantum
*p;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
p=GetAuthenticPixels(complete_mask,0,y,complete_mask->columns,1,exception);
if ((q == (Quantum *) NULL) || (p == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
MagickRealType
alpha,
intensity;
alpha=GetPixelAlpha(image,q);
intensity=GetPixelIntensity(complete_mask,p);
if (revert == MagickFalse)
SetPixelAlpha(image,ClampToQuantum(intensity*(QuantumScale*alpha)),q);
else if (intensity > 0)
SetPixelAlpha(image,ClampToQuantum((alpha/intensity)*QuantumRange),q);
q+=GetPixelChannels(image);
p+=GetPixelChannels(complete_mask);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
status=MagickFalse;
}
complete_mask=DestroyImage(complete_mask);
return(status);
}
static void PreservePSDOpacityMask(Image *image,LayerInfo* layer_info,
ExceptionInfo *exception)
{
char
*key;
RandomInfo
*random_info;
StringInfo
*key_info;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" preserving opacity mask");
random_info=AcquireRandomInfo();
key_info=GetRandomKey(random_info,2+1);
key=(char *) GetStringInfoDatum(key_info);
key[8]=layer_info->mask.background;
key[9]='\0';
layer_info->mask.image->page.x+=layer_info->page.x;
layer_info->mask.image->page.y+=layer_info->page.y;
(void) SetImageRegistry(ImageRegistryType,(const char *) key,
layer_info->mask.image,exception);
(void) SetImageArtifact(layer_info->image,"psd:opacity-mask",
(const char *) key);
key_info=DestroyStringInfo(key_info);
random_info=DestroyRandomInfo(random_info);
}
static ssize_t DecodePSDPixels(const size_t number_compact_pixels,
const unsigned char *compact_pixels,const ssize_t depth,
const size_t number_pixels,unsigned char *pixels)
{
#define CheckNumberCompactPixels \
if (packets == 0) \
return(i); \
packets--
#define CheckNumberPixels(count) \
if (((ssize_t) i + count) > (ssize_t) number_pixels) \
return(i); \
i+=count
int
pixel;
register ssize_t
i,
j;
size_t
length;
ssize_t
packets;
packets=(ssize_t) number_compact_pixels;
for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); )
{
packets--;
length=(size_t) (*compact_pixels++);
if (length == 128)
continue;
if (length > 128)
{
length=256-length+1;
CheckNumberCompactPixels;
pixel=(*compact_pixels++);
for (j=0; j < (ssize_t) length; j++)
{
switch (depth)
{
case 1:
{
CheckNumberPixels(8);
*pixels++=(pixel >> 7) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 6) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 5) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 4) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 3) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 2) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 1) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 0) & 0x01 ? 0U : 255U;
break;
}
case 2:
{
CheckNumberPixels(4);
*pixels++=(unsigned char) ((pixel >> 6) & 0x03);
*pixels++=(unsigned char) ((pixel >> 4) & 0x03);
*pixels++=(unsigned char) ((pixel >> 2) & 0x03);
*pixels++=(unsigned char) ((pixel & 0x03) & 0x03);
break;
}
case 4:
{
CheckNumberPixels(2);
*pixels++=(unsigned char) ((pixel >> 4) & 0xff);
*pixels++=(unsigned char) ((pixel & 0x0f) & 0xff);
break;
}
default:
{
CheckNumberPixels(1);
*pixels++=(unsigned char) pixel;
break;
}
}
}
continue;
}
length++;
for (j=0; j < (ssize_t) length; j++)
{
CheckNumberCompactPixels;
switch (depth)
{
case 1:
{
CheckNumberPixels(8);
*pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U;
break;
}
case 2:
{
CheckNumberPixels(4);
*pixels++=(*compact_pixels >> 6) & 0x03;
*pixels++=(*compact_pixels >> 4) & 0x03;
*pixels++=(*compact_pixels >> 2) & 0x03;
*pixels++=(*compact_pixels & 0x03) & 0x03;
break;
}
case 4:
{
CheckNumberPixels(2);
*pixels++=(*compact_pixels >> 4) & 0xff;
*pixels++=(*compact_pixels & 0x0f) & 0xff;
break;
}
default:
{
CheckNumberPixels(1);
*pixels++=(*compact_pixels);
break;
}
}
compact_pixels++;
}
}
return(i);
}
static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info,
const ssize_t number_layers)
{
ssize_t
i;
for (i=0; i<number_layers; i++)
{
if (layer_info[i].image != (Image *) NULL)
layer_info[i].image=DestroyImage(layer_info[i].image);
if (layer_info[i].mask.image != (Image *) NULL)
layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image);
if (layer_info[i].info != (StringInfo *) NULL)
layer_info[i].info=DestroyStringInfo(layer_info[i].info);
}
return (LayerInfo *) RelinquishMagickMemory(layer_info);
}
static inline size_t GetPSDPacketSize(Image *image)
{
if (image->storage_class == PseudoClass)
{
if (image->colors > 256)
return(2);
else if (image->depth > 8)
return(2);
}
else
if (image->depth > 8)
return(2);
return(1);
}
static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image)
{
if (psd_info->version == 1)
return((MagickSizeType) ReadBlobLong(image));
return((MagickSizeType) ReadBlobLongLong(image));
}
static inline size_t GetPSDRowSize(Image *image)
{
if (image->depth == 1)
return(((image->columns+7)/8)*GetPSDPacketSize(image));
else
return(image->columns*GetPSDPacketSize(image));
}
static const char *ModeToString(PSDImageType type)
{
switch (type)
{
case BitmapMode: return "Bitmap";
case GrayscaleMode: return "Grayscale";
case IndexedMode: return "Indexed";
case RGBMode: return "RGB";
case CMYKMode: return "CMYK";
case MultichannelMode: return "Multichannel";
case DuotoneMode: return "Duotone";
case LabMode: return "L*A*B";
default: return "unknown";
}
}
static MagickBooleanType NegateCMYK(Image *image,ExceptionInfo *exception)
{
ChannelType
channel_mask;
MagickBooleanType
status;
channel_mask=SetImageChannelMask(image,(ChannelType)(AllChannels &~
AlphaChannel));
status=NegateImage(image,MagickFalse,exception);
(void) SetImageChannelMask(image,channel_mask);
return(status);
}
static void ParseImageResourceBlocks(Image *image,
const unsigned char *blocks,size_t length,
MagickBooleanType *has_merged_image,ExceptionInfo *exception)
{
const unsigned char
*p;
StringInfo
*profile;
unsigned int
count,
long_sans;
unsigned short
id,
short_sans;
if (length < 16)
return;
profile=BlobToStringInfo((const unsigned char *) NULL,length);
SetStringInfoDatum(profile,blocks);
(void) SetImageProfile(image,"8bim",profile,exception);
profile=DestroyStringInfo(profile);
for (p=blocks; (p >= blocks) && (p < (blocks+length-16)); )
{
if (LocaleNCompare((const char *) p,"8BIM",4) != 0)
break;
p=PushLongPixel(MSBEndian,p,&long_sans);
p=PushShortPixel(MSBEndian,p,&id);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushLongPixel(MSBEndian,p,&count);
if ((p+count) > (blocks+length-16))
return;
switch (id)
{
case 0x03ed:
{
char
value[MagickPathExtent];
unsigned short
resolution;
/*
Resolution info.
*/
p=PushShortPixel(MSBEndian,p,&resolution);
image->resolution.x=(double) resolution;
(void) FormatLocaleString(value,MagickPathExtent,"%g",image->resolution.x);
(void) SetImageProperty(image,"tiff:XResolution",value,exception);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&resolution);
image->resolution.y=(double) resolution;
(void) FormatLocaleString(value,MagickPathExtent,"%g",image->resolution.y);
(void) SetImageProperty(image,"tiff:YResolution",value,exception);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
image->units=PixelsPerInchResolution;
break;
}
case 0x0421:
{
if (*(p+4) == 0)
*has_merged_image=MagickFalse;
p+=count;
break;
}
default:
{
p+=count;
break;
}
}
if ((count & 0x01) != 0)
p++;
}
return;
}
static CompositeOperator PSDBlendModeToCompositeOperator(const char *mode)
{
if (mode == (const char *) NULL)
return(OverCompositeOp);
if (LocaleNCompare(mode,"norm",4) == 0)
return(OverCompositeOp);
if (LocaleNCompare(mode,"mul ",4) == 0)
return(MultiplyCompositeOp);
if (LocaleNCompare(mode,"diss",4) == 0)
return(DissolveCompositeOp);
if (LocaleNCompare(mode,"diff",4) == 0)
return(DifferenceCompositeOp);
if (LocaleNCompare(mode,"dark",4) == 0)
return(DarkenCompositeOp);
if (LocaleNCompare(mode,"lite",4) == 0)
return(LightenCompositeOp);
if (LocaleNCompare(mode,"hue ",4) == 0)
return(HueCompositeOp);
if (LocaleNCompare(mode,"sat ",4) == 0)
return(SaturateCompositeOp);
if (LocaleNCompare(mode,"colr",4) == 0)
return(ColorizeCompositeOp);
if (LocaleNCompare(mode,"lum ",4) == 0)
return(LuminizeCompositeOp);
if (LocaleNCompare(mode,"scrn",4) == 0)
return(ScreenCompositeOp);
if (LocaleNCompare(mode,"over",4) == 0)
return(OverlayCompositeOp);
if (LocaleNCompare(mode,"hLit",4) == 0)
return(HardLightCompositeOp);
if (LocaleNCompare(mode,"sLit",4) == 0)
return(SoftLightCompositeOp);
if (LocaleNCompare(mode,"smud",4) == 0)
return(ExclusionCompositeOp);
if (LocaleNCompare(mode,"div ",4) == 0)
return(ColorDodgeCompositeOp);
if (LocaleNCompare(mode,"idiv",4) == 0)
return(ColorBurnCompositeOp);
if (LocaleNCompare(mode,"lbrn",4) == 0)
return(LinearBurnCompositeOp);
if (LocaleNCompare(mode,"lddg",4) == 0)
return(LinearDodgeCompositeOp);
if (LocaleNCompare(mode,"lLit",4) == 0)
return(LinearLightCompositeOp);
if (LocaleNCompare(mode,"vLit",4) == 0)
return(VividLightCompositeOp);
if (LocaleNCompare(mode,"pLit",4) == 0)
return(PinLightCompositeOp);
if (LocaleNCompare(mode,"hMix",4) == 0)
return(HardMixCompositeOp);
return(OverCompositeOp);
}
static inline void ReversePSDString(Image *image,char *p,size_t length)
{
char
*q;
if (image->endian == MSBEndian)
return;
q=p+length;
for(--q; p < q; ++p, --q)
{
*p = *p ^ *q,
*q = *p ^ *q,
*p = *p ^ *q;
}
}
static inline void SetPSDPixel(Image *image,const size_t channels,
const ssize_t type,const size_t packet_size,const Quantum pixel,Quantum *q,
ExceptionInfo *exception)
{
if (image->storage_class == PseudoClass)
{
if (packet_size == 1)
SetPixelIndex(image,ScaleQuantumToChar(pixel),q);
else
SetPixelIndex(image,ScaleQuantumToShort(pixel),q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
ConstrainColormapIndex(image,GetPixelIndex(image,q),exception),q);
return;
}
switch (type)
{
case -1:
{
SetPixelAlpha(image, pixel,q);
break;
}
case -2:
case 0:
{
SetPixelRed(image,pixel,q);
if (channels == 1 || type == -2)
SetPixelGray(image,pixel,q);
break;
}
case 1:
{
if (image->storage_class == PseudoClass)
SetPixelAlpha(image,pixel,q);
else
SetPixelGreen(image,pixel,q);
break;
}
case 2:
{
if (image->storage_class == PseudoClass)
SetPixelAlpha(image,pixel,q);
else
SetPixelBlue(image,pixel,q);
break;
}
case 3:
{
if (image->colorspace == CMYKColorspace)
SetPixelBlack(image,pixel,q);
else
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,pixel,q);
break;
}
case 4:
{
if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) &&
(channels > 3))
break;
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,pixel,q);
break;
}
}
}
static MagickBooleanType ReadPSDChannelPixels(Image *image,
const size_t channels,const size_t row,const ssize_t type,
const unsigned char *pixels,ExceptionInfo *exception)
{
Quantum
pixel;
register const unsigned char
*p;
register Quantum
*q;
register ssize_t
x;
size_t
packet_size;
unsigned short
nibble;
p=pixels;
q=GetAuthenticPixels(image,0,row,image->columns,1,exception);
if (q == (Quantum *) NULL)
return MagickFalse;
packet_size=GetPSDPacketSize(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (packet_size == 1)
pixel=ScaleCharToQuantum(*p++);
else
{
p=PushShortPixel(MSBEndian,p,&nibble);
pixel=ScaleShortToQuantum(nibble);
}
if (image->depth > 1)
{
SetPSDPixel(image,channels,type,packet_size,pixel,q,exception);
q+=GetPixelChannels(image);
}
else
{
ssize_t
bit,
number_bits;
number_bits=image->columns-x;
if (number_bits > 8)
number_bits=8;
for (bit = 0; bit < number_bits; bit++)
{
SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel)
& (0x01 << (7-bit))) != 0 ? 0 : QuantumRange,q,exception);
q+=GetPixelChannels(image);
x++;
}
if (x != (ssize_t) image->columns)
x--;
continue;
}
}
return(SyncAuthenticPixels(image,exception));
}
static MagickBooleanType ReadPSDChannelRaw(Image *image,const size_t channels,
const ssize_t type,ExceptionInfo *exception)
{
MagickBooleanType
status;
size_t
count,
row_size;
ssize_t
y;
unsigned char
*pixels;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is RAW");
row_size=GetPSDRowSize(image);
pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=MagickTrue;
for (y=0; y < (ssize_t) image->rows; y++)
{
status=MagickFalse;
count=ReadBlob(image,row_size,pixels);
if (count != row_size)
break;
status=ReadPSDChannelPixels(image,channels,y,type,pixels,exception);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(status);
}
static inline MagickOffsetType *ReadPSDRLESizes(Image *image,
const PSDInfo *psd_info,const size_t size)
{
MagickOffsetType
*sizes;
ssize_t
y;
sizes=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*sizes));
if(sizes != (MagickOffsetType *) NULL)
{
for (y=0; y < (ssize_t) size; y++)
{
if (psd_info->version == 1)
sizes[y]=(MagickOffsetType) ReadBlobShort(image);
else
sizes[y]=(MagickOffsetType) ReadBlobLong(image);
}
}
return sizes;
}
static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info,
const ssize_t type,MagickOffsetType *sizes,ExceptionInfo *exception)
{
MagickBooleanType
status;
size_t
length,
row_size;
ssize_t
count,
y;
unsigned char
*compact_pixels,
*pixels;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is RLE compressed");
row_size=GetPSDRowSize(image);
pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
length=0;
for (y=0; y < (ssize_t) image->rows; y++)
if ((MagickOffsetType) length < sizes[y])
length=(size_t) sizes[y];
if (length > row_size + 256) // arbitrary number
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
ThrowBinaryException(ResourceLimitError,"InvalidLength",
image->filename);
}
compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels));
if (compact_pixels == (unsigned char *) NULL)
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
(void) ResetMagickMemory(compact_pixels,0,length*sizeof(*compact_pixels));
status=MagickTrue;
for (y=0; y < (ssize_t) image->rows; y++)
{
status=MagickFalse;
count=ReadBlob(image,(size_t) sizes[y],compact_pixels);
if (count != (ssize_t) sizes[y])
break;
count=DecodePSDPixels((size_t) sizes[y],compact_pixels,
(ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels);
if (count != (ssize_t) row_size)
break;
status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels,
exception);
if (status == MagickFalse)
break;
}
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(status);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels,
const ssize_t type,const PSDCompressionType compression,
const size_t compact_size,ExceptionInfo *exception)
{
MagickBooleanType
status;
register unsigned char
*p;
size_t
count,
length,
packet_size,
row_size;
ssize_t
y;
unsigned char
*compact_pixels,
*pixels;
z_stream
stream;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is ZIP compressed");
compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size,
sizeof(*compact_pixels));
if (compact_pixels == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
packet_size=GetPSDPacketSize(image);
row_size=image->columns*packet_size;
count=image->rows*row_size;
pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
{
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
ResetMagickMemory(&stream,0,sizeof(stream));
stream.data_type=Z_BINARY;
(void) ReadBlob(image,compact_size,compact_pixels);
stream.next_in=(Bytef *)compact_pixels;
stream.avail_in=(uInt) compact_size;
stream.next_out=(Bytef *)pixels;
stream.avail_out=(uInt) count;
if (inflateInit(&stream) == Z_OK)
{
int
ret;
while (stream.avail_out > 0)
{
ret=inflate(&stream,Z_SYNC_FLUSH);
if ((ret != Z_OK) && (ret != Z_STREAM_END))
{
compact_pixels=(unsigned char *) RelinquishMagickMemory(
compact_pixels);
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(MagickFalse);
}
}
}
if (compression == ZipWithPrediction)
{
p=pixels;
while (count > 0)
{
length=image->columns;
while (--length)
{
if (packet_size == 2)
{
p[2]+=p[0]+((p[1]+p[3]) >> 8);
p[3]+=p[1];
}
else
*(p+1)+=*p;
p+=packet_size;
}
p+=packet_size;
count-=row_size;
}
}
status=MagickTrue;
p=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
status=ReadPSDChannelPixels(image,channels,y,type,p,exception);
if (status == MagickFalse)
break;
p+=row_size;
}
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(status);
}
#endif
static MagickBooleanType ReadPSDChannel(Image *image,
const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info,
const size_t channel,const PSDCompressionType compression,
ExceptionInfo *exception)
{
Image
*channel_image,
*mask;
MagickOffsetType
offset;
MagickBooleanType
status;
channel_image=image;
mask=(Image *) NULL;
if (layer_info->channel_info[channel].type < -1)
{
const char
*option;
/*
Ignore mask that is not a user supplied layer mask, if the mask is
disabled or if the flags have unsupported values.
*/
option=GetImageOption(image_info,"psd:preserve-opacity-mask");
if ((layer_info->channel_info[channel].type != -2) ||
(layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) &&
(IsStringTrue(option) == MagickFalse)))
{
SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR);
return(MagickTrue);
}
mask=CloneImage(image,layer_info->mask.page.width,
layer_info->mask.page.height,MagickFalse,exception);
SetImageType(mask,GrayscaleType,exception);
channel_image=mask;
}
offset=TellBlob(image);
status=MagickTrue;
switch(compression)
{
case Raw:
status=ReadPSDChannelRaw(channel_image,psd_info->channels,
layer_info->channel_info[channel].type,exception);
break;
case RLE:
{
MagickOffsetType
*sizes;
sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows);
if (sizes == (MagickOffsetType *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=ReadPSDChannelRLE(channel_image,psd_info,
layer_info->channel_info[channel].type,sizes,exception);
sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes);
}
break;
case ZipWithPrediction:
case ZipWithoutPrediction:
#ifdef MAGICKCORE_ZLIB_DELEGATE
status=ReadPSDChannelZip(channel_image,layer_info->channels,
layer_info->channel_info[channel].type,compression,
layer_info->channel_info[channel].size-2,exception);
#else
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn",
"'%s' (ZLIB)",image->filename);
#endif
break;
default:
(void) ThrowMagickException(exception,GetMagickModule(),TypeWarning,
"CompressionNotSupported","'%.20g'",(double) compression);
break;
}
SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET);
if (status == MagickFalse)
{
if (mask != (Image *) NULL)
DestroyImage(mask);
ThrowBinaryException(CoderError,"UnableToDecompressImage",
image->filename);
}
layer_info->mask.image=mask;
return(status);
}
static MagickBooleanType ReadPSDLayer(Image *image,const ImageInfo *image_info,
const PSDInfo *psd_info,LayerInfo* layer_info,ExceptionInfo *exception)
{
char
message[MagickPathExtent];
MagickBooleanType
status;
PSDCompressionType
compression;
ssize_t
j;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" setting up new layer image");
if (psd_info->mode != IndexedMode)
(void) SetImageBackgroundColor(layer_info->image,exception);
layer_info->image->compose=PSDBlendModeToCompositeOperator(
layer_info->blendkey);
if (layer_info->visible == MagickFalse)
layer_info->image->compose=NoCompositeOp;
if (psd_info->mode == CMYKMode)
SetImageColorspace(layer_info->image,CMYKColorspace,exception);
else if ((psd_info->mode == BitmapMode) || (psd_info->mode == DuotoneMode) ||
(psd_info->mode == GrayscaleMode))
SetImageColorspace(layer_info->image,GRAYColorspace,exception);
/*
Set up some hidden attributes for folks that need them.
*/
(void) FormatLocaleString(message,MagickPathExtent,"%.20g",
(double) layer_info->page.x);
(void) SetImageArtifact(layer_info->image,"psd:layer.x",message);
(void) FormatLocaleString(message,MagickPathExtent,"%.20g",
(double) layer_info->page.y);
(void) SetImageArtifact(layer_info->image,"psd:layer.y",message);
(void) FormatLocaleString(message,MagickPathExtent,"%.20g",(double)
layer_info->opacity);
(void) SetImageArtifact(layer_info->image,"psd:layer.opacity",message);
(void) SetImageProperty(layer_info->image,"label",(char *) layer_info->name,
exception);
status=MagickTrue;
for (j=0; j < (ssize_t) layer_info->channels; j++)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading data for channel %.20g",(double) j);
compression=(PSDCompressionType) ReadBlobShort(layer_info->image);
layer_info->image->compression=ConvertPSDCompression(compression);
if (layer_info->channel_info[j].type == -1)
layer_info->image->alpha_trait=BlendPixelTrait;
status=ReadPSDChannel(layer_info->image,image_info,psd_info,layer_info,j,
compression,exception);
if (status == MagickFalse)
break;
}
if (status != MagickFalse)
status=ApplyPSDLayerOpacity(layer_info->image,layer_info->opacity,
MagickFalse,exception);
if ((status != MagickFalse) &&
(layer_info->image->colorspace == CMYKColorspace))
status=NegateCMYK(layer_info->image,exception);
if ((status != MagickFalse) && (layer_info->mask.image != (Image *) NULL))
{
const char
*option;
layer_info->mask.image->page.x=layer_info->mask.page.x;
layer_info->mask.image->page.y=layer_info->mask.page.y;
/* Do not composite the mask when it is disabled */
if ((layer_info->mask.flags & 0x02) == 0x02)
layer_info->mask.image->compose=NoCompositeOp;
else
status=ApplyPSDOpacityMask(layer_info->image,layer_info->mask.image,
layer_info->mask.background == 0 ? 0 : QuantumRange,MagickFalse,
exception);
option=GetImageOption(image_info,"psd:preserve-opacity-mask");
if (IsStringTrue(option) != MagickFalse)
PreservePSDOpacityMask(image,layer_info,exception);
layer_info->mask.image=DestroyImage(layer_info->mask.image);
}
return(status);
}
ModuleExport MagickBooleanType ReadPSDLayers(Image *image,
const ImageInfo *image_info,const PSDInfo *psd_info,
const MagickBooleanType skip_layers,ExceptionInfo *exception)
{
char
type[4];
LayerInfo
*layer_info;
MagickSizeType
size;
MagickBooleanType
status;
register ssize_t
i;
ssize_t
count,
j,
number_layers;
size=GetPSDSize(psd_info,image);
if (size == 0)
{
/*
Skip layers & masks.
*/
(void) ReadBlobLong(image);
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
status=MagickFalse;
if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0))
return(MagickTrue);
else
{
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
if ((count != 0) && (LocaleNCompare(type,"Lr16",4) == 0))
size=GetPSDSize(psd_info,image);
else
return(MagickTrue);
}
}
status=MagickTrue;
if (size != 0)
{
layer_info=(LayerInfo *) NULL;
number_layers=(short) ReadBlobShort(image);
if (number_layers < 0)
{
/*
The first alpha channel in the merged result contains the
transparency data for the merged result.
*/
number_layers=MagickAbsoluteValue(number_layers);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" negative layer count corrected for");
image->alpha_trait=BlendPixelTrait;
}
/*
We only need to know if the image has an alpha channel
*/
if (skip_layers != MagickFalse)
return(MagickTrue);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image contains %.20g layers",(double) number_layers);
if (number_layers == 0)
ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers",
image->filename);
layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers,
sizeof(*layer_info));
if (layer_info == (LayerInfo *) NULL)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" allocation of LayerInfo failed");
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
(void) ResetMagickMemory(layer_info,0,(size_t) number_layers*
sizeof(*layer_info));
for (i=0; i < number_layers; i++)
{
ssize_t
x,
y;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading layer #%.20g",(double) i+1);
layer_info[i].page.y=ReadBlobSignedLong(image);
layer_info[i].page.x=ReadBlobSignedLong(image);
y=ReadBlobSignedLong(image);
x=ReadBlobSignedLong(image);
layer_info[i].page.width=(size_t) (x-layer_info[i].page.x);
layer_info[i].page.height=(size_t) (y-layer_info[i].page.y);
layer_info[i].channels=ReadBlobShort(image);
if (layer_info[i].channels > MaxPSDChannels)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded",
image->filename);
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g",
(double) layer_info[i].page.x,(double) layer_info[i].page.y,
(double) layer_info[i].page.height,(double)
layer_info[i].page.width,(double) layer_info[i].channels);
for (j=0; j < (ssize_t) layer_info[i].channels; j++)
{
layer_info[i].channel_info[j].type=(short) ReadBlobShort(image);
layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info,
image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" channel[%.20g]: type=%.20g, size=%.20g",(double) j,
(double) layer_info[i].channel_info[j].type,
(double) layer_info[i].channel_info[j].size);
}
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer type was %.4s instead of 8BIM", type);
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"ImproperImageHeader",
image->filename);
}
count=ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey);
ReversePSDString(image,layer_info[i].blendkey,4);
layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
layer_info[i].clipping=(unsigned char) ReadBlobByte(image);
layer_info[i].flags=(unsigned char) ReadBlobByte(image);
layer_info[i].visible=!(layer_info[i].flags & 0x02);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s",
layer_info[i].blendkey,(double) layer_info[i].opacity,
layer_info[i].clipping ? "true" : "false",layer_info[i].flags,
layer_info[i].visible ? "true" : "false");
(void) ReadBlobByte(image); /* filler */
size=ReadBlobLong(image);
if (size != 0)
{
MagickSizeType
combined_length,
length;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer contains additional info");
length=ReadBlobLong(image);
combined_length=length+4;
if (length != 0)
{
/*
Layer mask info.
*/
layer_info[i].mask.page.y=ReadBlobSignedLong(image);
layer_info[i].mask.page.x=ReadBlobSignedLong(image);
layer_info[i].mask.page.height=(size_t) (ReadBlobLong(image)-
layer_info[i].mask.page.y);
layer_info[i].mask.page.width=(size_t) (ReadBlobLong(image)-
layer_info[i].mask.page.x);
layer_info[i].mask.background=(unsigned char) ReadBlobByte(
image);
layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image);
if (!(layer_info[i].mask.flags & 0x01))
{
layer_info[i].mask.page.y=layer_info[i].mask.page.y-
layer_info[i].page.y;
layer_info[i].mask.page.x=layer_info[i].mask.page.x-
layer_info[i].page.x;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g",
(double) layer_info[i].mask.page.x,(double)
layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width,
(double) layer_info[i].mask.page.height,(double)
((MagickOffsetType) length)-18);
/*
Skip over the rest of the layer mask information.
*/
if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile",
image->filename);
}
}
length=ReadBlobLong(image);
combined_length+=length+4;
if (length != 0)
{
/*
Layer blending ranges info.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer blending ranges: length=%.20g",(double)
((MagickOffsetType) length));
/*
We read it, but don't use it...
*/
for (j=0; j < (ssize_t) length; j+=8)
{
size_t blend_source=ReadBlobLong(image);
size_t blend_dest=ReadBlobLong(image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" source(%x), dest(%x)",(unsigned int)
blend_source,(unsigned int) blend_dest);
}
}
/*
Layer name.
*/
length=(MagickSizeType) (unsigned char) ReadBlobByte(image);
combined_length+=length+1;
if (length > 0)
(void) ReadBlob(image,(size_t) length++,layer_info[i].name);
layer_info[i].name[length]='\0';
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer name: %s",layer_info[i].name);
if ((length % 4) != 0)
{
length=4-(length % 4);
combined_length+=length;
/* Skip over the padding of the layer name */
if (DiscardBlobBytes(image,length) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
}
length=(MagickSizeType) size-combined_length;
if (length > 0)
{
unsigned char
*info;
layer_info[i].info=AcquireStringInfo((const size_t) length);
info=GetStringInfoDatum(layer_info[i].info);
(void) ReadBlob(image,(const size_t) length,info);
}
}
}
for (i=0; i < number_layers; i++)
{
if ((layer_info[i].page.width == 0) ||
(layer_info[i].page.height == 0))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is empty");
if (layer_info[i].info != (StringInfo *) NULL)
layer_info[i].info=DestroyStringInfo(layer_info[i].info);
continue;
}
/*
Allocate layered image.
*/
layer_info[i].image=CloneImage(image,layer_info[i].page.width,
layer_info[i].page.height,MagickFalse,exception);
if (layer_info[i].image == (Image *) NULL)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" allocation of image for layer %.20g failed",(double) i);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
if (layer_info[i].info != (StringInfo *) NULL)
{
(void) SetImageProfile(layer_info[i].image,"psd:additional-info",
layer_info[i].info,exception);
layer_info[i].info=DestroyStringInfo(layer_info[i].info);
}
}
if (image_info->ping == MagickFalse)
{
for (i=0; i < number_layers; i++)
{
if (layer_info[i].image == (Image *) NULL)
{
for (j=0; j < layer_info[i].channels; j++)
{
if (DiscardBlobBytes(image,(MagickSizeType)
layer_info[i].channel_info[j].size) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
}
continue;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading data for layer %.20g",(double) i);
status=ReadPSDLayer(image,image_info,psd_info,&layer_info[i],
exception);
if (status == MagickFalse)
break;
status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType)
number_layers);
if (status == MagickFalse)
break;
}
}
if (status != MagickFalse)
{
for (i=0; i < number_layers; i++)
{
if (layer_info[i].image == (Image *) NULL)
{
for (j=i; j < number_layers - 1; j++)
layer_info[j] = layer_info[j+1];
number_layers--;
i--;
}
}
if (number_layers > 0)
{
for (i=0; i < number_layers; i++)
{
if (i > 0)
layer_info[i].image->previous=layer_info[i-1].image;
if (i < (number_layers-1))
layer_info[i].image->next=layer_info[i+1].image;
layer_info[i].image->page=layer_info[i].page;
}
image->next=layer_info[0].image;
layer_info[0].image->previous=image;
}
layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info);
}
else
layer_info=DestroyLayerInfo(layer_info,number_layers);
}
return(status);
}
static MagickBooleanType ReadPSDMergedImage(const ImageInfo *image_info,
Image *image,const PSDInfo *psd_info,ExceptionInfo *exception)
{
MagickOffsetType
*sizes;
MagickBooleanType
status;
PSDCompressionType
compression;
register ssize_t
i;
compression=(PSDCompressionType) ReadBlobMSBShort(image);
image->compression=ConvertPSDCompression(compression);
if (compression != Raw && compression != RLE)
{
(void) ThrowMagickException(exception,GetMagickModule(),
TypeWarning,"CompressionNotSupported","'%.20g'",(double) compression);
return(MagickFalse);
}
sizes=(MagickOffsetType *) NULL;
if (compression == RLE)
{
sizes=ReadPSDRLESizes(image,psd_info,image->rows*psd_info->channels);
if (sizes == (MagickOffsetType *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
status=MagickTrue;
for (i=0; i < (ssize_t) psd_info->channels; i++)
{
if (compression == RLE)
status=ReadPSDChannelRLE(image,psd_info,i,sizes+(i*image->rows),
exception);
else
status=ReadPSDChannelRaw(image,psd_info->channels,i,exception);
if (status != MagickFalse)
status=SetImageProgress(image,LoadImagesTag,i,psd_info->channels);
if (status == MagickFalse)
break;
}
if ((status != MagickFalse) && (image->colorspace == CMYKColorspace))
status=NegateCMYK(image,exception);
if (status != MagickFalse)
status=CorrectPSDAlphaBlend(image_info,image,exception);
sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes);
return(status);
}
static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
has_merged_image,
skip_layers;
MagickOffsetType
offset;
MagickSizeType
length;
MagickBooleanType
status;
PSDInfo
psd_info;
register ssize_t
i;
ssize_t
count;
unsigned char
*data;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read image header.
*/
image->endian=MSBEndian;
count=ReadBlob(image,4,(unsigned char *) psd_info.signature);
psd_info.version=ReadBlobMSBShort(image);
if ((count == 0) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) ||
((psd_info.version != 1) && (psd_info.version != 2)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
(void) ReadBlob(image,6,psd_info.reserved);
psd_info.channels=ReadBlobMSBShort(image);
if (psd_info.channels > MaxPSDChannels)
ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded");
psd_info.rows=ReadBlobMSBLong(image);
psd_info.columns=ReadBlobMSBLong(image);
if ((psd_info.version == 1) && ((psd_info.rows > 30000) ||
(psd_info.columns > 30000)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
psd_info.depth=ReadBlobMSBShort(image);
if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
psd_info.mode=ReadBlobMSBShort(image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s",
(double) psd_info.columns,(double) psd_info.rows,(double)
psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType)
psd_info.mode));
/*
Initialize image.
*/
image->depth=psd_info.depth;
image->columns=psd_info.columns;
image->rows=psd_info.rows;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
if (SetImageBackgroundColor(image,exception) == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
if (psd_info.mode == LabMode)
SetImageColorspace(image,LabColorspace,exception);
if (psd_info.mode == CMYKMode)
{
SetImageColorspace(image,CMYKColorspace,exception);
if (psd_info.channels > 4)
SetImageAlphaChannel(image,ActivateAlphaChannel,exception);
}
else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) ||
(psd_info.mode == DuotoneMode))
{
status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536,
exception);
if (status == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image colormap allocated");
SetImageColorspace(image,GRAYColorspace,exception);
if (psd_info.channels > 1)
SetImageAlphaChannel(image,ActivateAlphaChannel,exception);
}
else
if (psd_info.channels > 3)
SetImageAlphaChannel(image,ActivateAlphaChannel,exception);
/*
Read PSD raster colormap only present for indexed and duotone images.
*/
length=ReadBlobMSBLong(image);
if (length != 0)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading colormap");
if (psd_info.mode == DuotoneMode)
{
/*
Duotone image data; the format of this data is undocumented.
*/
data=(unsigned char *) AcquireQuantumMemory((size_t) length,
sizeof(*data));
if (data == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ReadBlob(image,(size_t) length,data);
data=(unsigned char *) RelinquishMagickMemory(data);
}
else
{
size_t
number_colors;
/*
Read PSD raster colormap.
*/
number_colors=length/3;
if (number_colors > 65536)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (AcquireImageColormap(image,number_colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].red=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].green=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].blue=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->alpha_trait=UndefinedPixelTrait;
}
}
if ((image->depth == 1) && (image->storage_class != PseudoClass))
ThrowReaderException(CorruptImageError, "ImproperImageHeader");
has_merged_image=MagickTrue;
length=ReadBlobMSBLong(image);
if (length != 0)
{
unsigned char
*blocks;
/*
Image resources block.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading image resource blocks - %.20g bytes",(double)
((MagickOffsetType) length));
blocks=(unsigned char *) AcquireQuantumMemory((size_t) length,
sizeof(*blocks));
if (blocks == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,(size_t) length,blocks);
if ((count != (ssize_t) length) || (length < 4) ||
(LocaleNCompare((char *) blocks,"8BIM",4) != 0))
{
blocks=(unsigned char *) RelinquishMagickMemory(blocks);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image,
exception);
blocks=(unsigned char *) RelinquishMagickMemory(blocks);
}
/*
Layer and mask block.
*/
length=GetPSDSize(&psd_info,image);
if (length == 8)
{
length=ReadBlobMSBLong(image);
length=ReadBlobMSBLong(image);
}
offset=TellBlob(image);
skip_layers=MagickFalse;
if ((image_info->number_scenes == 1) && (image_info->scene == 0) &&
(has_merged_image != MagickFalse))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" read composite only");
skip_layers=MagickTrue;
}
if (length == 0)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image has no layers");
}
else
{
if (ReadPSDLayers(image,image_info,&psd_info,skip_layers,exception) !=
MagickTrue)
{
(void) CloseBlob(image);
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Skip the rest of the layer and mask information.
*/
SeekBlob(image,offset+length,SEEK_SET);
}
/*
If we are only "pinging" the image, then we're done - so return.
*/
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
Read the precombined layer, present for PSD < 4 compatibility.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading the precombined layer");
if ((has_merged_image != MagickFalse) || (GetImageListLength(image) == 1))
has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image,
&psd_info,exception);
if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) &&
(length != 0))
{
SeekBlob(image,offset,SEEK_SET);
status=ReadPSDLayers(image,image_info,&psd_info,MagickFalse,exception);
if (status != MagickTrue)
{
(void) CloseBlob(image);
image=DestroyImageList(image);
return((Image *) NULL);
}
}
if (has_merged_image == MagickFalse)
{
Image
*merged;
if (GetImageListLength(image) == 1)
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
SetImageAlphaChannel(image,TransparentAlphaChannel,exception);
image->background_color.alpha=TransparentAlpha;
image->background_color.alpha_trait=BlendPixelTrait;
merged=MergeImageLayers(image,FlattenLayer,exception);
ReplaceImageInList(&image,merged);
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterPSDImage() adds properties for the PSD image format to
% the list of supported formats. The properties 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 RegisterPSDImage method is:
%
% size_t RegisterPSDImage(void)
%
*/
ModuleExport size_t RegisterPSDImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("PSD","PSB","Adobe Large Document Format");
entry->decoder=(DecodeImageHandler *) ReadPSDImage;
entry->encoder=(EncodeImageHandler *) WritePSDImage;
entry->magick=(IsImageFormatHandler *) IsPSD;
entry->flags|=CoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("PSD","PSD","Adobe Photoshop bitmap");
entry->decoder=(DecodeImageHandler *) ReadPSDImage;
entry->encoder=(EncodeImageHandler *) WritePSDImage;
entry->magick=(IsImageFormatHandler *) IsPSD;
entry->flags|=CoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterPSDImage() removes format registrations made by the
% PSD module from the list of supported formats.
%
% The format of the UnregisterPSDImage method is:
%
% UnregisterPSDImage(void)
%
*/
ModuleExport void UnregisterPSDImage(void)
{
(void) UnregisterMagickInfo("PSB");
(void) UnregisterMagickInfo("PSD");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WritePSDImage() writes an image in the Adobe Photoshop encoded image format.
%
% The format of the WritePSDImage method is:
%
% MagickBooleanType WritePSDImage(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 inline ssize_t SetPSDOffset(const PSDInfo *psd_info,Image *image,
const size_t offset)
{
if (psd_info->version == 1)
return(WriteBlobMSBShort(image,(unsigned short) offset));
return(WriteBlobMSBLong(image,(unsigned short) offset));
}
static inline ssize_t WritePSDOffset(const PSDInfo *psd_info,Image *image,
const MagickSizeType size,const MagickSizeType offset)
{
MagickSizeType
current_offset;
ssize_t
result;
current_offset=TellBlob(image);
SeekBlob(image,offset,SEEK_SET);
if (psd_info->version == 1)
result=WriteBlobMSBShort(image,(unsigned short) size);
else
result=(WriteBlobMSBLong(image,(unsigned short) size));
SeekBlob(image,current_offset,SEEK_SET);
return(result);
}
static inline ssize_t SetPSDSize(const PSDInfo *psd_info,Image *image,
const MagickSizeType size)
{
if (psd_info->version == 1)
return(WriteBlobMSBLong(image,(unsigned int) size));
return(WriteBlobMSBLongLong(image,size));
}
static inline ssize_t WritePSDSize(const PSDInfo *psd_info,Image *image,
const MagickSizeType size,const MagickSizeType offset)
{
MagickSizeType
current_offset;
ssize_t
result;
current_offset=TellBlob(image);
SeekBlob(image,offset,SEEK_SET);
if (psd_info->version == 1)
result=WriteBlobMSBLong(image,(unsigned int) size);
else
result=WriteBlobMSBLongLong(image,size);
SeekBlob(image,current_offset,SEEK_SET);
return(result);
}
static size_t PSDPackbitsEncodeImage(Image *image,const size_t length,
const unsigned char *pixels,unsigned char *compact_pixels,
ExceptionInfo *exception)
{
int
count;
register ssize_t
i,
j;
register unsigned char
*q;
unsigned char
*packbits;
/*
Compress pixels with Packbits encoding.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(pixels != (unsigned char *) NULL);
assert(compact_pixels != (unsigned char *) NULL);
packbits=(unsigned char *) AcquireQuantumMemory(128UL,sizeof(*packbits));
if (packbits == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
q=compact_pixels;
for (i=(ssize_t) length; i != 0; )
{
switch (i)
{
case 1:
{
i--;
*q++=(unsigned char) 0;
*q++=(*pixels);
break;
}
case 2:
{
i-=2;
*q++=(unsigned char) 1;
*q++=(*pixels);
*q++=pixels[1];
break;
}
case 3:
{
i-=3;
if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2)))
{
*q++=(unsigned char) ((256-3)+1);
*q++=(*pixels);
break;
}
*q++=(unsigned char) 2;
*q++=(*pixels);
*q++=pixels[1];
*q++=pixels[2];
break;
}
default:
{
if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2)))
{
/*
Packed run.
*/
count=3;
while (((ssize_t) count < i) && (*pixels == *(pixels+count)))
{
count++;
if (count >= 127)
break;
}
i-=count;
*q++=(unsigned char) ((256-count)+1);
*q++=(*pixels);
pixels+=count;
break;
}
/*
Literal run.
*/
count=0;
while ((*(pixels+count) != *(pixels+count+1)) ||
(*(pixels+count+1) != *(pixels+count+2)))
{
packbits[count+1]=pixels[count];
count++;
if (((ssize_t) count >= (i-3)) || (count >= 127))
break;
}
i-=count;
*packbits=(unsigned char) (count-1);
for (j=0; j <= (ssize_t) count; j++)
*q++=packbits[j];
pixels+=count;
break;
}
}
}
*q++=(unsigned char) 128; /* EOD marker */
packbits=(unsigned char *) RelinquishMagickMemory(packbits);
return((size_t) (q-compact_pixels));
}
static size_t WriteCompressionStart(const PSDInfo *psd_info,Image *image,
const Image *next_image,const ssize_t channels)
{
size_t
length;
ssize_t
i,
y;
if (next_image->compression == RLECompression)
{
length=WriteBlobMSBShort(image,RLE);
for (i=0; i < channels; i++)
for (y=0; y < (ssize_t) next_image->rows; y++)
length+=SetPSDOffset(psd_info,image,0);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
else if (next_image->compression == ZipCompression)
length=WriteBlobMSBShort(image,ZipWithoutPrediction);
#endif
else
length=WriteBlobMSBShort(image,Raw);
return(length);
}
static size_t WritePSDChannel(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
const QuantumType quantum_type, unsigned char *compact_pixels,
MagickOffsetType size_offset,const MagickBooleanType separate,
ExceptionInfo *exception)
{
int
y;
MagickBooleanType
monochrome;
QuantumInfo
*quantum_info;
register const Quantum
*p;
register ssize_t
i;
size_t
count,
length;
unsigned char
*pixels;
#ifdef MAGICKCORE_ZLIB_DELEGATE
#define CHUNK 16384
int
flush,
level;
unsigned char
*compressed_pixels;
z_stream
stream;
compressed_pixels=(unsigned char *) NULL;
flush=Z_NO_FLUSH;
#endif
count=0;
if (separate != MagickFalse)
{
size_offset=TellBlob(image)+2;
count+=WriteCompressionStart(psd_info,image,next_image,1);
}
if (next_image->depth > 8)
next_image->depth=16;
monochrome=IsImageMonochrome(image) && (image->depth == 1) ?
MagickTrue : MagickFalse;
quantum_info=AcquireQuantumInfo(image_info,next_image);
if (quantum_info == (QuantumInfo *) NULL)
return(0);
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
#ifdef MAGICKCORE_ZLIB_DELEGATE
if (next_image->compression == ZipCompression)
{
compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK,
sizeof(*compressed_pixels));
if (compressed_pixels == (unsigned char *) NULL)
{
quantum_info=DestroyQuantumInfo(quantum_info);
return(0);
}
ResetMagickMemory(&stream,0,sizeof(stream));
stream.data_type=Z_BINARY;
level=Z_DEFAULT_COMPRESSION;
if ((image_info->quality > 0 && image_info->quality < 10))
level=(int) image_info->quality;
if (deflateInit(&stream,level) != Z_OK)
{
quantum_info=DestroyQuantumInfo(quantum_info);
return(0);
}
}
#endif
for (y=0; y < (ssize_t) next_image->rows; y++)
{
p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (monochrome != MagickFalse)
for (i=0; i < (ssize_t) length; i++)
pixels[i]=(~pixels[i]);
if (next_image->compression == RLECompression)
{
length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels,
exception);
count+=WriteBlob(image,length,compact_pixels);
size_offset+=WritePSDOffset(psd_info,image,length,size_offset);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
else if (next_image->compression == ZipCompression)
{
stream.avail_in=(uInt) length;
stream.next_in=(Bytef *) pixels;
if (y == (ssize_t) next_image->rows-1)
flush=Z_FINISH;
do {
stream.avail_out=(uInt) CHUNK;
stream.next_out=(Bytef *) compressed_pixels;
if (deflate(&stream,flush) == Z_STREAM_ERROR)
break;
length=(size_t) CHUNK-stream.avail_out;
if (length > 0)
count+=WriteBlob(image,length,compressed_pixels);
} while (stream.avail_out == 0);
}
#endif
else
count+=WriteBlob(image,length,pixels);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
if (next_image->compression == ZipCompression)
{
(void) deflateEnd(&stream);
compressed_pixels=(unsigned char *) RelinquishMagickMemory(
compressed_pixels);
}
#endif
quantum_info=DestroyQuantumInfo(quantum_info);
return(count);
}
static unsigned char *AcquireCompactPixels(const Image *image,
ExceptionInfo *exception)
{
size_t
packet_size;
unsigned char
*compact_pixels;
packet_size=image->depth > 8UL ? 2UL : 1UL;
compact_pixels=(unsigned char *) AcquireQuantumMemory((9*
image->columns)+1,packet_size*sizeof(*compact_pixels));
if (compact_pixels == (unsigned char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
image->filename);
}
return(compact_pixels);
}
static size_t WritePSDChannels(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
MagickOffsetType size_offset,const MagickBooleanType separate,
ExceptionInfo *exception)
{
Image
*mask;
MagickOffsetType
rows_offset;
size_t
channels,
count,
length,
offset_length;
unsigned char
*compact_pixels;
count=0;
offset_length=0;
rows_offset=0;
compact_pixels=(unsigned char *) NULL;
if (next_image->compression == RLECompression)
{
compact_pixels=AcquireCompactPixels(image,exception);
if (compact_pixels == (unsigned char *) NULL)
return(0);
}
channels=1;
if (separate == MagickFalse)
{
if (next_image->storage_class != PseudoClass)
{
if (IsImageGray(next_image) == MagickFalse)
channels=next_image->colorspace == CMYKColorspace ? 4 : 3;
if (next_image->alpha_trait != UndefinedPixelTrait)
channels++;
}
rows_offset=TellBlob(image)+2;
count+=WriteCompressionStart(psd_info,image,next_image,channels);
offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4));
}
size_offset+=2;
if (next_image->storage_class == PseudoClass)
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
IndexQuantum,compact_pixels,rows_offset,separate,exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
else
{
if (IsImageGray(next_image) != MagickFalse)
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
GrayQuantum,compact_pixels,rows_offset,separate,exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
else
{
if (next_image->colorspace == CMYKColorspace)
(void) NegateCMYK(next_image,exception);
length=WritePSDChannel(psd_info,image_info,image,next_image,
RedQuantum,compact_pixels,rows_offset,separate,exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
length=WritePSDChannel(psd_info,image_info,image,next_image,
GreenQuantum,compact_pixels,rows_offset,separate,exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
length=WritePSDChannel(psd_info,image_info,image,next_image,
BlueQuantum,compact_pixels,rows_offset,separate,exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
if (next_image->colorspace == CMYKColorspace)
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
BlackQuantum,compact_pixels,rows_offset,separate,exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
}
if (next_image->alpha_trait != UndefinedPixelTrait)
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
AlphaQuantum,compact_pixels,rows_offset,separate,exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
}
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
if (next_image->colorspace == CMYKColorspace)
(void) NegateCMYK(next_image,exception);
if (separate != MagickFalse)
{
const char
*property;
property=GetImageArtifact(next_image,"psd:opacity-mask");
if (property != (const char *) NULL)
{
mask=(Image *) GetImageRegistry(ImageRegistryType,property,
exception);
if (mask != (Image *) NULL)
{
if (mask->compression == RLECompression)
{
compact_pixels=AcquireCompactPixels(mask,exception);
if (compact_pixels == (unsigned char *) NULL)
return(0);
}
length=WritePSDChannel(psd_info,image_info,image,mask,
RedQuantum,compact_pixels,rows_offset,MagickTrue,exception);
(void) WritePSDSize(psd_info,image,length,size_offset);
count+=length;
compact_pixels=(unsigned char *) RelinquishMagickMemory(
compact_pixels);
}
}
}
return(count);
}
static size_t WritePascalString(Image *image,const char *value,size_t padding)
{
size_t
count,
length;
register ssize_t
i;
/*
Max length is 255.
*/
count=0;
length=(strlen(value) > 255UL ) ? 255UL : strlen(value);
if (length == 0)
count+=WriteBlobByte(image,0);
else
{
count+=WriteBlobByte(image,(unsigned char) length);
count+=WriteBlob(image,length,(const unsigned char *) value);
}
length++;
if ((length % padding) == 0)
return(count);
for (i=0; i < (ssize_t) (padding-(length % padding)); i++)
count+=WriteBlobByte(image,0);
return(count);
}
static void WriteResolutionResourceBlock(Image *image)
{
double
x_resolution,
y_resolution;
unsigned short
units;
if (image->units == PixelsPerCentimeterResolution)
{
x_resolution=2.54*65536.0*image->resolution.x+0.5;
y_resolution=2.54*65536.0*image->resolution.y+0.5;
units=2;
}
else
{
x_resolution=65536.0*image->resolution.x+0.5;
y_resolution=65536.0*image->resolution.y+0.5;
units=1;
}
(void) WriteBlob(image,4,(const unsigned char *) "8BIM");
(void) WriteBlobMSBShort(image,0x03ED);
(void) WriteBlobMSBShort(image,0);
(void) WriteBlobMSBLong(image,16); /* resource size */
(void) WriteBlobMSBLong(image,(unsigned int) (x_resolution+0.5));
(void) WriteBlobMSBShort(image,units); /* horizontal resolution unit */
(void) WriteBlobMSBShort(image,units); /* width unit */
(void) WriteBlobMSBLong(image,(unsigned int) (y_resolution+0.5));
(void) WriteBlobMSBShort(image,units); /* vertical resolution unit */
(void) WriteBlobMSBShort(image,units); /* height unit */
}
static inline size_t WriteChannelSize(const PSDInfo *psd_info,Image *image,
const signed short channel)
{
size_t
count;
count=WriteBlobMSBSignedShort(image,channel);
count+=SetPSDSize(psd_info,image,0);
return(count);
}
static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile)
{
register const unsigned char
*p;
size_t
length;
unsigned char
*datum;
unsigned int
count,
long_sans;
unsigned short
id,
short_sans;
length=GetStringInfoLength(bim_profile);
if (length < 16)
return;
datum=GetStringInfoDatum(bim_profile);
for (p=datum; (p >= datum) && (p < (datum+length-16)); )
{
register unsigned char
*q;
q=(unsigned char *) p;
if (LocaleNCompare((const char *) p,"8BIM",4) != 0)
break;
p=PushLongPixel(MSBEndian,p,&long_sans);
p=PushShortPixel(MSBEndian,p,&id);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushLongPixel(MSBEndian,p,&count);
if (id == 0x0000040f)
{
ssize_t
quantum;
quantum=PSDQuantum(count)+12;
if ((quantum >= 12) && (quantum < (ssize_t) length))
{
if ((q+quantum < (datum+length-16)))
(void) CopyMagickMemory(q,q+quantum,length-quantum-(q-datum));
SetStringInfoLength(bim_profile,length-quantum);
}
break;
}
p+=count;
if ((count & 0x01) != 0)
p++;
}
}
static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile)
{
register const unsigned char
*p;
size_t
length;
unsigned char
*datum;
unsigned int
count,
long_sans;
unsigned short
id,
short_sans;
length=GetStringInfoLength(bim_profile);
if (length < 16)
return;
datum=GetStringInfoDatum(bim_profile);
for (p=datum; (p >= datum) && (p < (datum+length-16)); )
{
register unsigned char
*q;
ssize_t
cnt;
q=(unsigned char *) p;
if (LocaleNCompare((const char *) p,"8BIM",4) != 0)
return;
p=PushLongPixel(MSBEndian,p,&long_sans);
p=PushShortPixel(MSBEndian,p,&id);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushLongPixel(MSBEndian,p,&count);
cnt=PSDQuantum(count);
if (cnt < 0)
return;
if ((id == 0x000003ed) && (cnt < (ssize_t) (length-12)))
{
(void) CopyMagickMemory(q,q+cnt+12,length-(cnt+12)-(q-datum));
SetStringInfoLength(bim_profile,length-(cnt+12));
break;
}
p+=count;
if ((count & 0x01) != 0)
p++;
}
}
static const StringInfo *GetAdditionalInformation(const ImageInfo *image_info,
Image *image,ExceptionInfo *exception)
{
#define PSDKeySize 5
#define PSDAllowedLength 36
char
key[PSDKeySize];
/* Whitelist of keys from: https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/ */
const char
allowed[PSDAllowedLength][PSDKeySize] = {
"blnc", "blwh", "brit", "brst", "clbl", "clrL", "curv", "expA", "FMsk",
"GdFl", "grdm", "hue ", "hue2", "infx", "knko", "lclr", "levl", "lnsr",
"lfx2", "luni", "lrFX", "lspf", "lyid", "lyvr", "mixr", "nvrt", "phfl",
"post", "PtFl", "selc", "shpa", "sn2P", "SoCo", "thrs", "tsly", "vibA"
},
*option;
const StringInfo
*info;
MagickBooleanType
found;
register size_t
i;
size_t
remaining_length,
length;
StringInfo
*profile;
unsigned char
*p;
unsigned int
size;
info=GetImageProfile(image,"psd:additional-info");
if (info == (const StringInfo *) NULL)
return((const StringInfo *) NULL);
option=GetImageOption(image_info,"psd:additional-info");
if (LocaleCompare(option,"all") == 0)
return(info);
if (LocaleCompare(option,"selective") != 0)
{
profile=RemoveImageProfile(image,"psd:additional-info");
return(DestroyStringInfo(profile));
}
length=GetStringInfoLength(info);
p=GetStringInfoDatum(info);
remaining_length=length;
length=0;
while (remaining_length >= 12)
{
/* skip over signature */
p+=4;
key[0]=(*p++);
key[1]=(*p++);
key[2]=(*p++);
key[3]=(*p++);
key[4]='\0';
size=(unsigned int) (*p++) << 24;
size|=(unsigned int) (*p++) << 16;
size|=(unsigned int) (*p++) << 8;
size|=(unsigned int) (*p++);
size=size & 0xffffffff;
remaining_length-=12;
if ((size_t) size > remaining_length)
return((const StringInfo *) NULL);
found=MagickFalse;
for (i=0; i < PSDAllowedLength; i++)
{
if (LocaleNCompare(key,allowed[i],PSDKeySize) != 0)
continue;
found=MagickTrue;
break;
}
remaining_length-=(size_t) size;
if (found == MagickFalse)
{
if (remaining_length > 0)
p=(unsigned char *) CopyMagickMemory(p-12,p+size,remaining_length);
continue;
}
length+=(size_t) size+12;
p+=size;
}
profile=RemoveImageProfile(image,"psd:additional-info");
if (length == 0)
return(DestroyStringInfo(profile));
SetStringInfoLength(profile,(const size_t) length);
SetImageProfile(image,"psd:additional-info",info,exception);
return(profile);
}
static MagickBooleanType WritePSDImage(const ImageInfo *image_info,
Image *image,ExceptionInfo *exception)
{
char
layer_name[MagickPathExtent];
const char
*property;
const StringInfo
*icc_profile,
*info;
Image
*base_image,
*next_image;
MagickBooleanType
status;
MagickOffsetType
*layer_size_offsets,
size_offset;
PSDInfo
psd_info;
register ssize_t
i;
size_t
layer_count,
layer_index,
length,
name_length,
num_channels,
packet_size,
rounded_size,
size;
StringInfo
*bim_profile;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
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);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
packet_size=(size_t) (image->depth > 8 ? 6 : 3);
if (image->alpha_trait != UndefinedPixelTrait)
packet_size+=image->depth > 8 ? 2 : 1;
psd_info.version=1;
if ((LocaleCompare(image_info->magick,"PSB") == 0) ||
(image->columns > 30000) || (image->rows > 30000))
psd_info.version=2;
(void) WriteBlob(image,4,(const unsigned char *) "8BPS");
(void) WriteBlobMSBShort(image,psd_info.version); /* version */
for (i=1; i <= 6; i++)
(void) WriteBlobByte(image, 0); /* 6 bytes of reserved */
if (SetImageGray(image,exception) != MagickFalse)
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL);
else
if ((image_info->type != TrueColorType) && (image_info->type !=
TrueColorAlphaType) && (image->storage_class == PseudoClass))
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL);
else
{
if (image->storage_class == PseudoClass)
(void) SetImageStorageClass(image,DirectClass,exception);
if (image->colorspace != CMYKColorspace)
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL);
else
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL);
}
(void) WriteBlobMSBShort(image,(unsigned short) num_channels);
(void) WriteBlobMSBLong(image,(unsigned int) image->rows);
(void) WriteBlobMSBLong(image,(unsigned int) image->columns);
if (IsImageGray(image) != MagickFalse)
{
MagickBooleanType
monochrome;
/*
Write depth & mode.
*/
monochrome=IsImageMonochrome(image) && (image->depth == 1) ?
MagickTrue : MagickFalse;
(void) WriteBlobMSBShort(image,(unsigned short)
(monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8));
(void) WriteBlobMSBShort(image,(unsigned short)
(monochrome != MagickFalse ? BitmapMode : GrayscaleMode));
}
else
{
(void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class ==
PseudoClass ? 8 : image->depth > 8 ? 16 : 8));
if (((image_info->colorspace != UndefinedColorspace) ||
(image->colorspace != CMYKColorspace)) &&
(image_info->colorspace != CMYKColorspace))
{
(void) TransformImageColorspace(image,sRGBColorspace,exception);
(void) WriteBlobMSBShort(image,(unsigned short)
(image->storage_class == PseudoClass ? IndexedMode : RGBMode));
}
else
{
if (image->colorspace != CMYKColorspace)
(void) TransformImageColorspace(image,CMYKColorspace,exception);
(void) WriteBlobMSBShort(image,CMYKMode);
}
}
if ((IsImageGray(image) != MagickFalse) ||
(image->storage_class == DirectClass) || (image->colors > 256))
(void) WriteBlobMSBLong(image,0);
else
{
/*
Write PSD raster colormap.
*/
(void) WriteBlobMSBLong(image,768);
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].red));
for ( ; i < 256; i++)
(void) WriteBlobByte(image,0);
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(
image->colormap[i].green));
for ( ; i < 256; i++)
(void) WriteBlobByte(image,0);
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].blue));
for ( ; i < 256; i++)
(void) WriteBlobByte(image,0);
}
/*
Image resource block.
*/
length=28; /* 0x03EB */
bim_profile=(StringInfo *) GetImageProfile(image,"8bim");
icc_profile=GetImageProfile(image,"icc");
if (bim_profile != (StringInfo *) NULL)
{
bim_profile=CloneStringInfo(bim_profile);
if (icc_profile != (StringInfo *) NULL)
RemoveICCProfileFromResourceBlock(bim_profile);
RemoveResolutionFromResourceBlock(bim_profile);
length+=PSDQuantum(GetStringInfoLength(bim_profile));
}
if (icc_profile != (const StringInfo *) NULL)
length+=PSDQuantum(GetStringInfoLength(icc_profile))+12;
(void) WriteBlobMSBLong(image,(unsigned int) length);
WriteResolutionResourceBlock(image);
if (bim_profile != (StringInfo *) NULL)
{
(void) WriteBlob(image,GetStringInfoLength(bim_profile),
GetStringInfoDatum(bim_profile));
bim_profile=DestroyStringInfo(bim_profile);
}
if (icc_profile != (StringInfo *) NULL)
{
(void) WriteBlob(image,4,(const unsigned char *) "8BIM");
(void) WriteBlobMSBShort(image,0x0000040F);
(void) WriteBlobMSBShort(image,0);
(void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength(
icc_profile));
(void) WriteBlob(image,GetStringInfoLength(icc_profile),
GetStringInfoDatum(icc_profile));
if ((MagickOffsetType) GetStringInfoLength(icc_profile) !=
PSDQuantum(GetStringInfoLength(icc_profile)))
(void) WriteBlobByte(image,0);
}
base_image=GetNextImageInList(image);
if (base_image == (Image *) NULL)
base_image=image;
size=0;
size_offset=TellBlob(image);
SetPSDSize(&psd_info,image,0);
SetPSDSize(&psd_info,image,0);
layer_count=0;
for (next_image=base_image; next_image != NULL; )
{
layer_count++;
next_image=GetNextImageInList(next_image);
}
if (image->alpha_trait != UndefinedPixelTrait)
size+=WriteBlobMSBShort(image,-(unsigned short) layer_count);
else
size+=WriteBlobMSBShort(image,(unsigned short) layer_count);
layer_size_offsets=(MagickOffsetType *) AcquireQuantumMemory(
(size_t) layer_count,sizeof(MagickOffsetType));
if (layer_size_offsets == (MagickOffsetType *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
layer_index=0;
for (next_image=base_image; next_image != NULL; )
{
Image
*mask;
unsigned char
default_color;
unsigned short
channels,
total_channels;
mask=(Image *) NULL;
property=GetImageArtifact(next_image,"psd:opacity-mask");
default_color=0;
if (property != (const char *) NULL)
{
mask=(Image *) GetImageRegistry(ImageRegistryType,property,exception);
default_color=strlen(property) == 9 ? 255 : 0;
}
size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.y);
size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.x);
size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.y+
next_image->rows));
size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.x+
next_image->columns));
channels=1U;
if ((next_image->storage_class != PseudoClass) &&
(IsImageGray(next_image) == MagickFalse))
channels=next_image->colorspace == CMYKColorspace ? 4U : 3U;
total_channels=channels;
if (next_image->alpha_trait != UndefinedPixelTrait)
total_channels++;
if (mask != (Image *) NULL)
total_channels++;
size+=WriteBlobMSBShort(image,total_channels);
layer_size_offsets[layer_index++]=TellBlob(image);
for (i=0; i < (ssize_t) channels; i++)
size+=WriteChannelSize(&psd_info,image,(signed short) i);
if (next_image->alpha_trait != UndefinedPixelTrait)
size+=WriteChannelSize(&psd_info,image,-1);
if (mask != (Image *) NULL)
size+=WriteChannelSize(&psd_info,image,-2);
size+=WriteBlob(image,4,(const unsigned char *) "8BIM");
size+=WriteBlob(image,4,(const unsigned char *)
CompositeOperatorToPSDBlendMode(next_image->compose));
property=GetImageArtifact(next_image,"psd:layer.opacity");
if (property != (const char *) NULL)
{
Quantum
opacity;
opacity=(Quantum) StringToInteger(property);
size+=WriteBlobByte(image,ScaleQuantumToChar(opacity));
(void) ApplyPSDLayerOpacity(next_image,opacity,MagickTrue,exception);
}
else
size+=WriteBlobByte(image,255);
size+=WriteBlobByte(image,0);
size+=WriteBlobByte(image,next_image->compose==NoCompositeOp ?
1 << 0x02 : 1); /* layer properties - visible, etc. */
size+=WriteBlobByte(image,0);
info=GetAdditionalInformation(image_info,next_image,exception);
property=(const char *) GetImageProperty(next_image,"label",exception);
if (property == (const char *) NULL)
{
(void) FormatLocaleString(layer_name,MagickPathExtent,"L%.20g",
(double) layer_index);
property=layer_name;
}
name_length=strlen(property)+1;
if ((name_length % 4) != 0)
name_length+=(4-(name_length % 4));
if (info != (const StringInfo *) NULL)
name_length+=GetStringInfoLength(info);
name_length+=8;
if (mask != (Image *) NULL)
name_length+=20;
size+=WriteBlobMSBLong(image,(unsigned int) name_length);
if (mask == (Image *) NULL)
size+=WriteBlobMSBLong(image,0);
else
{
if (mask->compose != NoCompositeOp)
(void) ApplyPSDOpacityMask(next_image,mask,ScaleCharToQuantum(
default_color),MagickTrue,exception);
mask->page.y+=image->page.y;
mask->page.x+=image->page.x;
size+=WriteBlobMSBLong(image,20);
size+=WriteBlobMSBSignedLong(image,mask->page.y);
size+=WriteBlobMSBSignedLong(image,mask->page.x);
size+=WriteBlobMSBLong(image,(const unsigned int) mask->rows+
mask->page.y);
size+=WriteBlobMSBLong(image,(const unsigned int) mask->columns+
mask->page.x);
size+=WriteBlobByte(image,default_color);
size+=WriteBlobByte(image,mask->compose == NoCompositeOp ? 2 : 0);
size+=WriteBlobMSBShort(image,0);
}
size+=WriteBlobMSBLong(image,0);
size+=WritePascalString(image,property,4);
if (info != (const StringInfo *) NULL)
size+=WriteBlob(image,GetStringInfoLength(info),
GetStringInfoDatum(info));
next_image=GetNextImageInList(next_image);
}
/*
Now the image data!
*/
next_image=base_image;
layer_index=0;
while (next_image != NULL)
{
length=WritePSDChannels(&psd_info,image_info,image,next_image,
layer_size_offsets[layer_index++],MagickTrue,exception);
if (length == 0)
{
status=MagickFalse;
break;
}
size+=length;
next_image=GetNextImageInList(next_image);
}
(void) WriteBlobMSBLong(image,0); /* user mask data */
/*
Write the total size
*/
size_offset+=WritePSDSize(&psd_info,image,size+
(psd_info.version == 1 ? 8 : 16),size_offset);
if ((size/2) != ((size+1)/2))
rounded_size=size+1;
else
rounded_size=size;
(void) WritePSDSize(&psd_info,image,rounded_size,size_offset);
layer_size_offsets=(MagickOffsetType *) RelinquishMagickMemory(
layer_size_offsets);
/*
Remove the opacity mask from the registry
*/
next_image=base_image;
while (next_image != (Image *) NULL)
{
property=GetImageArtifact(next_image,"psd:opacity-mask");
if (property != (const char *) NULL)
DeleteImageRegistry(property);
next_image=GetNextImageInList(next_image);
}
/*
Write composite image.
*/
if (status != MagickFalse)
{
CompressionType
compression;
compression=image->compression;
if (image->compression == ZipCompression)
image->compression=RLECompression;
if (WritePSDChannels(&psd_info,image_info,image,image,0,MagickFalse,
exception) == 0)
status=MagickFalse;
image->compression=compression;
}
(void) CloseBlob(image);
return(status);
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_3106_0 |
crossvul-cpp_data_good_674_1 | /**
* FreeRDP: A Remote Desktop Protocol Implementation
* NSCodec Codec
*
* Copyright 2011 Samsung, Author Jiten Pathy
* Copyright 2012 Vic Lee
* 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winpr/crt.h>
#include <freerdp/codec/nsc.h>
#include <freerdp/codec/color.h>
#include "nsc_types.h"
#include "nsc_encode.h"
#include "nsc_sse2.h"
#ifndef NSC_INIT_SIMD
#define NSC_INIT_SIMD(_nsc_context) do { } while (0)
#endif
static BOOL nsc_decode(NSC_CONTEXT* context)
{
UINT16 x;
UINT16 y;
UINT16 rw;
BYTE shift;
BYTE* bmpdata;
size_t pos = 0;
if (!context)
return FALSE;
rw = ROUND_UP_TO(context->width, 8);
shift = context->ColorLossLevel - 1; /* colorloss recovery + YCoCg shift */
bmpdata = context->BitmapData;
if (!bmpdata)
return FALSE;
for (y = 0; y < context->height; y++)
{
const BYTE* yplane;
const BYTE* coplane;
const BYTE* cgplane;
const BYTE* aplane = context->priv->PlaneBuffers[3] + y * context->width; /* A */
if (context->ChromaSubsamplingLevel)
{
yplane = context->priv->PlaneBuffers[0] + y * rw; /* Y */
coplane = context->priv->PlaneBuffers[1] + (y >> 1) * (rw >>
1); /* Co, supersampled */
cgplane = context->priv->PlaneBuffers[2] + (y >> 1) * (rw >>
1); /* Cg, supersampled */
}
else
{
yplane = context->priv->PlaneBuffers[0] + y * context->width; /* Y */
coplane = context->priv->PlaneBuffers[1] + y * context->width; /* Co */
cgplane = context->priv->PlaneBuffers[2] + y * context->width; /* Cg */
}
for (x = 0; x < context->width; x++)
{
INT16 y_val = (INT16) * yplane;
INT16 co_val = (INT16)(INT8)(*coplane << shift);
INT16 cg_val = (INT16)(INT8)(*cgplane << shift);
INT16 r_val = y_val + co_val - cg_val;
INT16 g_val = y_val + cg_val;
INT16 b_val = y_val - co_val - cg_val;
if (pos + 4 > context->BitmapDataLength)
return FALSE;
pos += 4;
*bmpdata++ = MINMAX(b_val, 0, 0xFF);
*bmpdata++ = MINMAX(g_val, 0, 0xFF);
*bmpdata++ = MINMAX(r_val, 0, 0xFF);
*bmpdata++ = *aplane;
yplane++;
coplane += (context->ChromaSubsamplingLevel ? x % 2 : 1);
cgplane += (context->ChromaSubsamplingLevel ? x % 2 : 1);
aplane++;
}
}
return TRUE;
}
static BOOL nsc_rle_decode(BYTE* in, BYTE* out, UINT32 outSize, UINT32 originalSize)
{
UINT32 len;
UINT32 left;
BYTE value;
left = originalSize;
while (left > 4)
{
value = *in++;
if (left == 5)
{
if (outSize < 1)
return FALSE;
outSize--;
*out++ = value;
left--;
}
else if (value == *in)
{
in++;
if (*in < 0xFF)
{
len = (UINT32) * in++;
len += 2;
}
else
{
in++;
len = *((UINT32*) in);
in += 4;
}
if (outSize < len)
return FALSE;
outSize -= len;
FillMemory(out, len, value);
out += len;
left -= len;
}
else
{
if (outSize < 1)
return FALSE;
outSize--;
*out++ = value;
left--;
}
}
if ((outSize < 4) || (left < 4))
return FALSE;
memcpy(out, in, 4);
return TRUE;
}
static BOOL nsc_rle_decompress_data(NSC_CONTEXT* context)
{
UINT16 i;
BYTE* rle;
UINT32 planeSize;
UINT32 originalSize;
if (!context)
return FALSE;
rle = context->Planes;
for (i = 0; i < 4; i++)
{
originalSize = context->OrgByteCount[i];
planeSize = context->PlaneByteCount[i];
if (planeSize == 0)
{
if (context->priv->PlaneBuffersLength < originalSize)
return FALSE;
FillMemory(context->priv->PlaneBuffers[i], originalSize, 0xFF);
}
else if (planeSize < originalSize)
{
if (!nsc_rle_decode(rle, context->priv->PlaneBuffers[i], context->priv->PlaneBuffersLength,
originalSize))
return FALSE;
}
else
{
if (context->priv->PlaneBuffersLength < originalSize)
return FALSE;
CopyMemory(context->priv->PlaneBuffers[i], rle, originalSize);
}
rle += planeSize;
}
return TRUE;
}
static BOOL nsc_stream_initialize(NSC_CONTEXT* context, wStream* s)
{
int i;
if (Stream_GetRemainingLength(s) < 20)
return FALSE;
for (i = 0; i < 4; i++)
Stream_Read_UINT32(s, context->PlaneByteCount[i]);
Stream_Read_UINT8(s, context->ColorLossLevel); /* ColorLossLevel (1 byte) */
Stream_Read_UINT8(s,
context->ChromaSubsamplingLevel); /* ChromaSubsamplingLevel (1 byte) */
Stream_Seek(s, 2); /* Reserved (2 bytes) */
context->Planes = Stream_Pointer(s);
return TRUE;
}
static BOOL nsc_context_initialize(NSC_CONTEXT* context, wStream* s)
{
int i;
UINT32 length;
UINT32 tempWidth;
UINT32 tempHeight;
if (!nsc_stream_initialize(context, s))
return FALSE;
length = context->width * context->height * 4;
if (!context->BitmapData)
{
context->BitmapData = calloc(1, length + 16);
if (!context->BitmapData)
return FALSE;
context->BitmapDataLength = length;
}
else if (length > context->BitmapDataLength)
{
void* tmp;
tmp = realloc(context->BitmapData, length + 16);
if (!tmp)
return FALSE;
context->BitmapData = tmp;
context->BitmapDataLength = length;
}
tempWidth = ROUND_UP_TO(context->width, 8);
tempHeight = ROUND_UP_TO(context->height, 2);
/* The maximum length a decoded plane can reach in all cases */
length = tempWidth * tempHeight;
if (length > context->priv->PlaneBuffersLength)
{
for (i = 0; i < 4; i++)
{
void* tmp = (BYTE*) realloc(context->priv->PlaneBuffers[i], length);
if (!tmp)
return FALSE;
context->priv->PlaneBuffers[i] = tmp;
}
context->priv->PlaneBuffersLength = length;
}
for (i = 0; i < 4; i++)
{
context->OrgByteCount[i] = context->width * context->height;
}
if (context->ChromaSubsamplingLevel)
{
context->OrgByteCount[0] = tempWidth * context->height;
context->OrgByteCount[1] = (tempWidth >> 1) * (tempHeight >> 1);
context->OrgByteCount[2] = context->OrgByteCount[1];
}
return TRUE;
}
static void nsc_profiler_print(NSC_CONTEXT_PRIV* priv)
{
PROFILER_PRINT_HEADER
PROFILER_PRINT(priv->prof_nsc_rle_decompress_data)
PROFILER_PRINT(priv->prof_nsc_decode)
PROFILER_PRINT(priv->prof_nsc_rle_compress_data)
PROFILER_PRINT(priv->prof_nsc_encode)
PROFILER_PRINT_FOOTER
}
BOOL nsc_context_reset(NSC_CONTEXT* context, UINT32 width, UINT32 height)
{
if (!context)
return FALSE;
context->width = width;
context->height = height;
return TRUE;
}
NSC_CONTEXT* nsc_context_new(void)
{
NSC_CONTEXT* context;
context = (NSC_CONTEXT*) calloc(1, sizeof(NSC_CONTEXT));
if (!context)
return NULL;
context->priv = (NSC_CONTEXT_PRIV*) calloc(1, sizeof(NSC_CONTEXT_PRIV));
if (!context->priv)
goto error;
context->priv->log = WLog_Get("com.freerdp.codec.nsc");
WLog_OpenAppender(context->priv->log);
context->BitmapData = NULL;
context->decode = nsc_decode;
context->encode = nsc_encode;
context->priv->PlanePool = BufferPool_New(TRUE, 0, 16);
if (!context->priv->PlanePool)
goto error;
PROFILER_CREATE(context->priv->prof_nsc_rle_decompress_data,
"nsc_rle_decompress_data")
PROFILER_CREATE(context->priv->prof_nsc_decode, "nsc_decode")
PROFILER_CREATE(context->priv->prof_nsc_rle_compress_data,
"nsc_rle_compress_data")
PROFILER_CREATE(context->priv->prof_nsc_encode, "nsc_encode")
/* Default encoding parameters */
context->ColorLossLevel = 3;
context->ChromaSubsamplingLevel = 1;
/* init optimized methods */
NSC_INIT_SIMD(context);
return context;
error:
nsc_context_free(context);
return NULL;
}
void nsc_context_free(NSC_CONTEXT* context)
{
size_t i;
if (!context)
return;
if (context->priv)
{
for (i = 0; i < 4; i++)
free(context->priv->PlaneBuffers[i]);
BufferPool_Free(context->priv->PlanePool);
nsc_profiler_print(context->priv);
PROFILER_FREE(context->priv->prof_nsc_rle_decompress_data)
PROFILER_FREE(context->priv->prof_nsc_decode)
PROFILER_FREE(context->priv->prof_nsc_rle_compress_data)
PROFILER_FREE(context->priv->prof_nsc_encode)
free(context->priv);
}
free(context->BitmapData);
free(context);
}
BOOL nsc_context_set_pixel_format(NSC_CONTEXT* context, UINT32 pixel_format)
{
if (!context)
return FALSE;
context->format = pixel_format;
return TRUE;
}
BOOL nsc_process_message(NSC_CONTEXT* context, UINT16 bpp,
UINT32 width, UINT32 height,
const BYTE* data, UINT32 length,
BYTE* pDstData, UINT32 DstFormat,
UINT32 nDstStride,
UINT32 nXDst, UINT32 nYDst, UINT32 nWidth,
UINT32 nHeight, UINT32 flip)
{
wStream* s;
BOOL ret;
s = Stream_New((BYTE*)data, length);
if (!s)
return FALSE;
if (nDstStride == 0)
nDstStride = nWidth * GetBytesPerPixel(DstFormat);
switch (bpp)
{
case 32:
context->format = PIXEL_FORMAT_BGRA32;
break;
case 24:
context->format = PIXEL_FORMAT_BGR24;
break;
case 16:
context->format = PIXEL_FORMAT_BGR16;
break;
case 8:
context->format = PIXEL_FORMAT_RGB8;
break;
case 4:
context->format = PIXEL_FORMAT_A4;
break;
default:
Stream_Free(s, TRUE);
return FALSE;
}
context->width = width;
context->height = height;
ret = nsc_context_initialize(context, s);
Stream_Free(s, FALSE);
if (!ret)
return FALSE;
/* RLE decode */
{
BOOL rc;
PROFILER_ENTER(context->priv->prof_nsc_rle_decompress_data)
rc = nsc_rle_decompress_data(context);
PROFILER_EXIT(context->priv->prof_nsc_rle_decompress_data)
if (!rc)
return FALSE;
}
/* Colorloss recover, Chroma supersample and AYCoCg to ARGB Conversion in one step */
{
BOOL rc;
PROFILER_ENTER(context->priv->prof_nsc_decode)
rc = context->decode(context);
PROFILER_EXIT(context->priv->prof_nsc_decode)
if (!rc)
return FALSE;
}
if (!freerdp_image_copy(pDstData, DstFormat, nDstStride, nXDst, nYDst,
width, height, context->BitmapData,
PIXEL_FORMAT_BGRA32, 0, 0, 0, NULL, flip))
return FALSE;
return TRUE;
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_674_1 |
crossvul-cpp_data_good_1197_0 | /* lookup.c - implementation of IDNA2008 lookup functions
Copyright (C) 2011-2017 Simon Josefsson
Libidn2 is free software: you can redistribute it and/or modify it
under the terms of either:
* the GNU Lesser General Public License as published by the Free
Software Foundation; either version 3 of the License, or (at
your option) any later version.
or
* 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.
or both in parallel, as here.
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 copies of the GNU General Public License and
the GNU Lesser General Public License along with this program. If
not, see <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include "idn2.h"
#include <errno.h> /* errno */
#include <stdlib.h> /* malloc, free */
#include "punycode.h"
#include <unitypes.h>
#include <uniconv.h> /* u8_strconv_from_locale */
#include <uninorm.h> /* u32_normalize */
#include <unistr.h> /* u8_to_u32 */
#include "idna.h" /* _idn2_label_test */
#include "tr46map.h" /* definition for tr46map.c */
static int set_default_flags(int *flags)
{
if (((*flags) & IDN2_TRANSITIONAL) && ((*flags) & IDN2_NONTRANSITIONAL))
return IDN2_INVALID_FLAGS;
if (((*flags) & (IDN2_TRANSITIONAL|IDN2_NONTRANSITIONAL)) && ((*flags) & IDN2_NO_TR46))
return IDN2_INVALID_FLAGS;
if (!((*flags) & (IDN2_NO_TR46|IDN2_TRANSITIONAL)))
*flags |= IDN2_NONTRANSITIONAL;
return IDN2_OK;
}
static int
label (const uint8_t * src, size_t srclen, uint8_t * dst, size_t * dstlen,
int flags)
{
size_t plen;
uint32_t *p;
int rc;
size_t tmpl;
if (_idn2_ascii_p (src, srclen))
{
if (flags & IDN2_ALABEL_ROUNDTRIP)
/* FIXME implement this MAY:
If the input to this procedure appears to be an A-label
(i.e., it starts in "xn--", interpreted
case-insensitively), the lookup application MAY attempt to
convert it to a U-label, first ensuring that the A-label is
entirely in lowercase (converting it to lowercase if
necessary), and apply the tests of Section 5.4 and the
conversion of Section 5.5 to that form. */
return IDN2_INVALID_FLAGS;
if (srclen > IDN2_LABEL_MAX_LENGTH)
return IDN2_TOO_BIG_LABEL;
if (srclen > *dstlen)
return IDN2_TOO_BIG_DOMAIN;
memcpy (dst, src, srclen);
*dstlen = srclen;
return IDN2_OK;
}
rc = _idn2_u8_to_u32_nfc (src, srclen, &p, &plen, flags & IDN2_NFC_INPUT);
if (rc != IDN2_OK)
return rc;
if (!(flags & IDN2_TRANSITIONAL))
{
rc = _idn2_label_test(
TEST_NFC |
TEST_2HYPHEN |
TEST_LEADING_COMBINING |
TEST_DISALLOWED |
TEST_CONTEXTJ_RULE |
TEST_CONTEXTO_WITH_RULE |
TEST_UNASSIGNED | TEST_BIDI |
((flags & IDN2_NONTRANSITIONAL) ? TEST_NONTRANSITIONAL : 0) |
((flags & IDN2_USE_STD3_ASCII_RULES) ? 0 : TEST_ALLOW_STD3_DISALLOWED),
p, plen);
if (rc != IDN2_OK)
{
free(p);
return rc;
}
}
dst[0] = 'x';
dst[1] = 'n';
dst[2] = '-';
dst[3] = '-';
tmpl = *dstlen - 4;
rc = _idn2_punycode_encode (plen, p, &tmpl, (char *) dst + 4);
free (p);
if (rc != IDN2_OK)
return rc;
*dstlen = 4 + tmpl;
return IDN2_OK;
}
#define TR46_TRANSITIONAL_CHECK \
(TEST_NFC | TEST_2HYPHEN | TEST_HYPHEN_STARTEND | TEST_LEADING_COMBINING | TEST_TRANSITIONAL)
#define TR46_NONTRANSITIONAL_CHECK \
(TEST_NFC | TEST_2HYPHEN | TEST_HYPHEN_STARTEND | TEST_LEADING_COMBINING | TEST_NONTRANSITIONAL)
static int
_tr46 (const uint8_t * domain_u8, uint8_t ** out, int flags)
{
size_t len, it;
uint32_t *domain_u32;
int err = IDN2_OK, rc;
int transitional = 0;
int test_flags;
if (flags & IDN2_TRANSITIONAL)
transitional = 1;
/* convert UTF-8 to UTF-32 */
if (!(domain_u32 =
u8_to_u32 (domain_u8, u8_strlen (domain_u8) + 1, NULL, &len)))
{
if (errno == ENOMEM)
return IDN2_MALLOC;
return IDN2_ENCODING_ERROR;
}
size_t len2 = 0;
for (it = 0; it < len - 1; it++)
{
IDNAMap map;
get_idna_map (domain_u32[it], &map);
if (map_is (&map, TR46_FLG_DISALLOWED))
{
if (domain_u32[it])
{
free (domain_u32);
return IDN2_DISALLOWED;
}
len2++;
}
else if (map_is (&map, TR46_FLG_MAPPED))
{
len2 += map.nmappings;
}
else if (map_is (&map, TR46_FLG_VALID))
{
len2++;
}
else if (map_is (&map, TR46_FLG_IGNORED))
{
continue;
}
else if (map_is (&map, TR46_FLG_DEVIATION))
{
if (transitional)
{
len2 += map.nmappings;
}
else
len2++;
}
else if (!(flags & IDN2_USE_STD3_ASCII_RULES))
{
if (map_is (&map, TR46_FLG_DISALLOWED_STD3_VALID))
{
/* valid because UseSTD3ASCIIRules=false, see #TR46 5 */
len2++;
}
else if (map_is (&map, TR46_FLG_DISALLOWED_STD3_MAPPED))
{
/* mapped because UseSTD3ASCIIRules=false, see #TR46 5 */
len2 += map.nmappings;
}
}
}
uint32_t *tmp = (uint32_t *) malloc ((len2 + 1) * sizeof (uint32_t));
if (!tmp)
{
free (domain_u32);
return IDN2_MALLOC;
}
len2 = 0;
for (it = 0; it < len - 1; it++)
{
uint32_t c = domain_u32[it];
IDNAMap map;
get_idna_map (c, &map);
if (map_is (&map, TR46_FLG_DISALLOWED))
{
tmp[len2++] = c;
}
else if (map_is (&map, TR46_FLG_MAPPED))
{
len2 += get_map_data (tmp + len2, &map);
}
else if (map_is (&map, TR46_FLG_VALID))
{
tmp[len2++] = c;
}
else if (map_is (&map, TR46_FLG_IGNORED))
{
continue;
}
else if (map_is (&map, TR46_FLG_DEVIATION))
{
if (transitional)
{
len2 += get_map_data (tmp + len2, &map);
}
else
tmp[len2++] = c;
}
else if (!(flags & IDN2_USE_STD3_ASCII_RULES))
{
if (map_is (&map, TR46_FLG_DISALLOWED_STD3_VALID))
{
tmp[len2++] = c;
}
else if (map_is (&map, TR46_FLG_DISALLOWED_STD3_MAPPED))
{
len2 += get_map_data (tmp + len2, &map);
}
}
}
free (domain_u32);
/* Normalize to NFC */
tmp[len2] = 0;
domain_u32 = u32_normalize (UNINORM_NFC, tmp, len2 + 1, NULL, &len);
free (tmp);
tmp = NULL;
if (!domain_u32)
{
if (errno == ENOMEM)
return IDN2_MALLOC;
return IDN2_ENCODING_ERROR;
}
/* split into labels and check */
uint32_t *e, *s;
for (e = s = domain_u32; *e; s = e)
{
while (*e && *e != '.')
e++;
if (e - s >= 4 && s[0] == 'x' && s[1] == 'n' && s[2] == '-'
&& s[3] == '-')
{
/* decode punycode and check result non-transitional */
size_t ace_len;
uint32_t name_u32[IDN2_LABEL_MAX_LENGTH];
size_t name_len = IDN2_LABEL_MAX_LENGTH;
uint8_t *ace;
ace = u32_to_u8 (s + 4, e - s - 4, NULL, &ace_len);
if (!ace)
{
free (domain_u32);
if (errno == ENOMEM)
return IDN2_MALLOC;
return IDN2_ENCODING_ERROR;
}
rc =
_idn2_punycode_decode (ace_len, (char *) ace, &name_len, name_u32);
free (ace);
if (rc)
{
free (domain_u32);
return rc;
}
test_flags = TR46_NONTRANSITIONAL_CHECK;
if (!(flags & IDN2_USE_STD3_ASCII_RULES))
test_flags |= TEST_ALLOW_STD3_DISALLOWED;
if ((rc =
_idn2_label_test (test_flags, name_u32,
name_len)))
err = rc;
}
else
{
test_flags = transitional ? TR46_TRANSITIONAL_CHECK : TR46_NONTRANSITIONAL_CHECK;
if (!(flags & IDN2_USE_STD3_ASCII_RULES))
test_flags |= TEST_ALLOW_STD3_DISALLOWED;
if ((rc =
_idn2_label_test (test_flags, s, e - s)))
err = rc;
}
if (*e)
e++;
}
if (err == IDN2_OK && out)
{
uint8_t *_out = u32_to_u8 (domain_u32, len, NULL, &len);
free (domain_u32);
if (!_out)
{
if (errno == ENOMEM)
return IDN2_MALLOC;
return IDN2_ENCODING_ERROR;
}
*out = _out;
}
else
free (domain_u32);
return err;
}
/**
* idn2_lookup_u8:
* @src: input zero-terminated UTF-8 string in Unicode NFC normalized form.
* @lookupname: newly allocated output variable with name to lookup in DNS.
* @flags: optional #idn2_flags to modify behaviour.
*
* Perform IDNA2008 lookup string conversion on domain name @src, as
* described in section 5 of RFC 5891. Note that the input string
* must be encoded in UTF-8 and be in Unicode NFC form.
*
* Pass %IDN2_NFC_INPUT in @flags to convert input to NFC form before
* further processing. %IDN2_TRANSITIONAL and %IDN2_NONTRANSITIONAL
* do already imply %IDN2_NFC_INPUT.
* Pass %IDN2_ALABEL_ROUNDTRIP in @flags to
* convert any input A-labels to U-labels and perform additional
* testing (not implemented yet).
* Pass %IDN2_TRANSITIONAL to enable Unicode TR46
* transitional processing, and %IDN2_NONTRANSITIONAL to enable
* Unicode TR46 non-transitional processing. Multiple flags may be
* specified by binary or:ing them together.
*
* After version 2.0.3: %IDN2_USE_STD3_ASCII_RULES disabled by default.
* Previously we were eliminating non-STD3 characters from domain strings
* such as _443._tcp.example.com, or IPs 1.2.3.4/24 provided to libidn2
* functions. That was an unexpected regression for applications switching
* from libidn and thus it is no longer applied by default.
* Use %IDN2_USE_STD3_ASCII_RULES to enable that behavior again.
*
* After version 0.11: @lookupname may be NULL to test lookup of @src
* without allocating memory.
*
* Returns: On successful conversion %IDN2_OK is returned, if the
* output domain or any label would have been too long
* %IDN2_TOO_BIG_DOMAIN or %IDN2_TOO_BIG_LABEL is returned, or
* another error code is returned.
*
* Since: 0.1
**/
int
idn2_lookup_u8 (const uint8_t * src, uint8_t ** lookupname, int flags)
{
size_t lookupnamelen = 0;
uint8_t _lookupname[IDN2_DOMAIN_MAX_LENGTH + 1];
uint8_t _mapped[IDN2_DOMAIN_MAX_LENGTH + 1];
int rc;
if (src == NULL)
{
if (lookupname)
*lookupname = NULL;
return IDN2_OK;
}
rc = set_default_flags(&flags);
if (rc != IDN2_OK)
return rc;
if (!(flags & IDN2_NO_TR46))
{
uint8_t *out;
size_t outlen;
rc = _tr46 (src, &out, flags);
if (rc != IDN2_OK)
return rc;
outlen = u8_strlen (out);
if (outlen >= sizeof (_mapped))
{
free (out);
return IDN2_TOO_BIG_DOMAIN;
}
memcpy (_mapped, out, outlen + 1);
src = _mapped;
free (out);
}
do
{
const uint8_t *end = (uint8_t *) strchrnul ((const char *) src, '.');
/* XXX Do we care about non-U+002E dots such as U+3002, U+FF0E
and U+FF61 here? Perhaps when IDN2_NFC_INPUT? */
size_t labellen = end - src;
uint8_t tmp[IDN2_LABEL_MAX_LENGTH];
size_t tmplen = IDN2_LABEL_MAX_LENGTH;
rc = label (src, labellen, tmp, &tmplen, flags);
if (rc != IDN2_OK)
return rc;
if (lookupnamelen + tmplen
> IDN2_DOMAIN_MAX_LENGTH - (tmplen == 0 && *end == '\0' ? 1 : 2))
return IDN2_TOO_BIG_DOMAIN;
memcpy (_lookupname + lookupnamelen, tmp, tmplen);
lookupnamelen += tmplen;
if (*end == '.')
{
if (lookupnamelen + 1 > IDN2_DOMAIN_MAX_LENGTH)
return IDN2_TOO_BIG_DOMAIN;
_lookupname[lookupnamelen] = '.';
lookupnamelen++;
}
_lookupname[lookupnamelen] = '\0';
src = end;
}
while (*src++);
if (lookupname)
{
uint8_t *tmp = (uint8_t *) malloc (lookupnamelen + 1);
if (tmp == NULL)
return IDN2_MALLOC;
memcpy (tmp, _lookupname, lookupnamelen + 1);
*lookupname = tmp;
}
return IDN2_OK;
}
/**
* idn2_lookup_ul:
* @src: input zero-terminated locale encoded string.
* @lookupname: newly allocated output variable with name to lookup in DNS.
* @flags: optional #idn2_flags to modify behaviour.
*
* Perform IDNA2008 lookup string conversion on domain name @src, as
* described in section 5 of RFC 5891. Note that the input is assumed
* to be encoded in the locale's default coding system, and will be
* transcoded to UTF-8 and NFC normalized by this function.
*
* Pass %IDN2_ALABEL_ROUNDTRIP in @flags to convert any input A-labels
* to U-labels and perform additional testing. Pass
* %IDN2_TRANSITIONAL to enable Unicode TR46 transitional processing,
* and %IDN2_NONTRANSITIONAL to enable Unicode TR46 non-transitional
* processing. Multiple flags may be specified by binary or:ing them
* together, for example %IDN2_ALABEL_ROUNDTRIP |
* %IDN2_NONTRANSITIONAL. The %IDN2_NFC_INPUT in @flags is always
* enabled in this function.
*
* After version 0.11: @lookupname may be NULL to test lookup of @src
* without allocating memory.
*
* Returns: On successful conversion %IDN2_OK is returned, if
* conversion from locale to UTF-8 fails then %IDN2_ICONV_FAIL is
* returned, if the output domain or any label would have been too
* long %IDN2_TOO_BIG_DOMAIN or %IDN2_TOO_BIG_LABEL is returned, or
* another error code is returned.
*
* Since: 0.1
**/
int
idn2_lookup_ul (const char * src, char ** lookupname, int flags)
{
uint8_t *utf8src = NULL;
int rc;
if (src)
{
const char *encoding = locale_charset ();
utf8src = u8_strconv_from_encoding (src, encoding, iconveh_error);
if (!utf8src)
{
if (errno == ENOMEM)
return IDN2_MALLOC;
return IDN2_ICONV_FAIL;
}
}
rc = idn2_lookup_u8 (utf8src, (uint8_t **) lookupname,
flags | IDN2_NFC_INPUT);
free (utf8src);
return rc;
}
/**
* idn2_to_ascii_4i:
* @input: zero terminated input Unicode (UCS-4) string.
* @inlen: number of elements in @input.
* @output: pointer to newly allocated zero-terminated output string.
* @flags: optional #idn2_flags to modify behaviour.
*
* The ToASCII operation takes a sequence of Unicode code points that make
* up one domain label and transforms it into a sequence of code points in
* the ASCII range (0..7F). If ToASCII succeeds, the original sequence and
* the resulting sequence are equivalent labels.
*
* It is important to note that the ToASCII operation can fail.
* ToASCII fails if any step of it fails. If any step of the
* ToASCII operation fails on any label in a domain name, that domain
* name MUST NOT be used as an internationalized domain name.
* The method for dealing with this failure is application-specific.
*
* The inputs to ToASCII are a sequence of code points.
*
* ToASCII never alters a sequence of code points that are all in the ASCII
* range to begin with (although it could fail). Applying the ToASCII operation multiple
* effect as applying it just once.
*
* The default behavior of this function (when flags are zero) is to apply
* the IDNA2008 rules without the TR46 amendments. As the TR46
* non-transitional processing is nowadays ubiquitous, when unsure, it is
* recommended to call this function with the %IDN2_NONTRANSITIONAL
* and the %IDN2_NFC_INPUT flags for compatibility with other software.
*
* Return value: Returns %IDN2_OK on success, or error code.
*
* Since: 2.0.0
**/
int
idn2_to_ascii_4i (const uint32_t * input, size_t inlen, char * output, int flags)
{
uint32_t *input_u32;
uint8_t *input_u8, *output_u8;
size_t length;
int rc;
if (!input)
{
if (output)
*output = 0;
return IDN2_OK;
}
input_u32 = (uint32_t *) malloc ((inlen + 1) * sizeof(uint32_t));
if (!input_u32)
return IDN2_MALLOC;
u32_cpy (input_u32, input, inlen);
input_u32[inlen] = 0;
input_u8 = u32_to_u8 (input_u32, inlen + 1, NULL, &length);
free (input_u32);
if (!input_u8)
{
if (errno == ENOMEM)
return IDN2_MALLOC;
return IDN2_ENCODING_ERROR;
}
rc = idn2_lookup_u8 (input_u8, &output_u8, flags);
free (input_u8);
if (rc == IDN2_OK)
{
/* wow, this is ugly, but libidn manpage states:
* char * out output zero terminated string that must have room for at
* least 63 characters plus the terminating zero.
*/
size_t len = strlen ((char *) output_u8);
if (len > 63)
{
free (output_u8);
return IDN2_TOO_BIG_DOMAIN;
}
if (output)
strcpy (output, (char *) output_u8);
free (output_u8);
}
return rc;
}
/**
* idn2_to_ascii_4z:
* @input: zero terminated input Unicode (UCS-4) string.
* @output: pointer to newly allocated zero-terminated output string.
* @flags: optional #idn2_flags to modify behaviour.
*
* Convert UCS-4 domain name to ASCII string using the IDNA2008
* rules. The domain name may contain several labels, separated by dots.
* The output buffer must be deallocated by the caller.
*
* The default behavior of this function (when flags are zero) is to apply
* the IDNA2008 rules without the TR46 amendments. As the TR46
* non-transitional processing is nowadays ubiquitous, when unsure, it is
* recommended to call this function with the %IDN2_NONTRANSITIONAL
* and the %IDN2_NFC_INPUT flags for compatibility with other software.
*
* Return value: Returns %IDN2_OK on success, or error code.
*
* Since: 2.0.0
**/
int
idn2_to_ascii_4z (const uint32_t * input, char ** output, int flags)
{
uint8_t *input_u8;
size_t length;
int rc;
if (!input)
{
if (output)
*output = NULL;
return IDN2_OK;
}
input_u8 = u32_to_u8 (input, u32_strlen(input) + 1, NULL, &length);
if (!input_u8)
{
if (errno == ENOMEM)
return IDN2_MALLOC;
return IDN2_ENCODING_ERROR;
}
rc = idn2_lookup_u8 (input_u8, (uint8_t **) output, flags);
free (input_u8);
return rc;
}
/**
* idn2_to_ascii_8z:
* @input: zero terminated input UTF-8 string.
* @output: pointer to newly allocated output string.
* @flags: optional #idn2_flags to modify behaviour.
*
* Convert UTF-8 domain name to ASCII string using the IDNA2008
* rules. The domain name may contain several labels, separated by dots.
* The output buffer must be deallocated by the caller.
*
* The default behavior of this function (when flags are zero) is to apply
* the IDNA2008 rules without the TR46 amendments. As the TR46
* non-transitional processing is nowadays ubiquitous, when unsure, it is
* recommended to call this function with the %IDN2_NONTRANSITIONAL
* and the %IDN2_NFC_INPUT flags for compatibility with other software.
*
* Return value: Returns %IDN2_OK on success, or error code.
*
* Since: 2.0.0
**/
int
idn2_to_ascii_8z (const char * input, char ** output, int flags)
{
return idn2_lookup_u8 ((const uint8_t *) input, (uint8_t **) output, flags);
}
/**
* idn2_to_ascii_lz:
* @input: zero terminated input UTF-8 string.
* @output: pointer to newly allocated output string.
* @flags: optional #idn2_flags to modify behaviour.
*
* Convert a domain name in locale's encoding to ASCII string using the IDNA2008
* rules. The domain name may contain several labels, separated by dots.
* The output buffer must be deallocated by the caller.
*
* The default behavior of this function (when flags are zero) is to apply
* the IDNA2008 rules without the TR46 amendments. As the TR46
* non-transitional processing is nowadays ubiquitous, when unsure, it is
* recommended to call this function with the %IDN2_NONTRANSITIONAL
* and the %IDN2_NFC_INPUT flags for compatibility with other software.
*
* Returns: %IDN2_OK on success, or error code.
* Same as described in idn2_lookup_ul() documentation.
*
* Since: 2.0.0
**/
int
idn2_to_ascii_lz (const char * input, char ** output, int flags)
{
return idn2_lookup_ul (input, output, flags);
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_1197_0 |
crossvul-cpp_data_bad_95_1 | ////////////////////////////////////////////////////////////////////////////
// **** WAVPACK **** //
// Hybrid Lossless Wavefile Compressor //
// Copyright (c) 1998 - 2016 David Bryant. //
// All Rights Reserved. //
// Distributed under the BSD Software License (see license.txt) //
////////////////////////////////////////////////////////////////////////////
// wave64.c
// This module is a helper to the WavPack command-line programs to support Sony's
// Wave64 WAV file varient. Note that unlike the WAV/RF64 version, this does not
// fall back to conventional WAV in the < 4GB case.
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <math.h>
#include <stdio.h>
#include <ctype.h>
#include "wavpack.h"
#include "utils.h"
#include "md5.h"
typedef struct {
char ckID [16];
int64_t ckSize;
char formType [16];
} Wave64FileHeader;
typedef struct {
char ckID [16];
int64_t ckSize;
} Wave64ChunkHeader;
#define Wave64ChunkHeaderFormat "88D"
static const unsigned char riff_guid [16] = { 'r','i','f','f', 0x2e,0x91,0xcf,0x11,0xa5,0xd6,0x28,0xdb,0x04,0xc1,0x00,0x00 };
static const unsigned char wave_guid [16] = { 'w','a','v','e', 0xf3,0xac,0xd3,0x11,0x8c,0xd1,0x00,0xc0,0x4f,0x8e,0xdb,0x8a };
static const unsigned char fmt_guid [16] = { 'f','m','t',' ', 0xf3,0xac,0xd3,0x11,0x8c,0xd1,0x00,0xc0,0x4f,0x8e,0xdb,0x8a };
static const unsigned char data_guid [16] = { 'd','a','t','a', 0xf3,0xac,0xd3,0x11,0x8c,0xd1,0x00,0xc0,0x4f,0x8e,0xdb,0x8a };
#define WAVPACK_NO_ERROR 0
#define WAVPACK_SOFT_ERROR 1
#define WAVPACK_HARD_ERROR 2
extern int debug_logging_mode;
int ParseWave64HeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config)
{
int64_t total_samples = 0, infilesize;
Wave64ChunkHeader chunk_header;
Wave64FileHeader filehdr;
WaveHeader WaveHeader;
uint32_t bcount;
infilesize = DoGetFileSize (infile);
memcpy (&filehdr, fourcc, 4);
if (!DoReadFile (infile, ((char *) &filehdr) + 4, sizeof (Wave64FileHeader) - 4, &bcount) ||
bcount != sizeof (Wave64FileHeader) - 4 || memcmp (filehdr.ckID, riff_guid, sizeof (riff_guid)) ||
memcmp (filehdr.formType, wave_guid, sizeof (wave_guid))) {
error_line ("%s is not a valid .W64 file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &filehdr, sizeof (filehdr))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
#if 1 // this might be a little too picky...
WavpackLittleEndianToNative (&filehdr, Wave64ChunkHeaderFormat);
if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) &&
filehdr.ckSize && filehdr.ckSize + 1 && filehdr.ckSize != infilesize) {
error_line ("%s is not a valid .W64 file!", infilename);
return WAVPACK_SOFT_ERROR;
}
#endif
// loop through all elements of the wave64 header
// (until the data chuck) and copy them to the output file
while (1) {
if (!DoReadFile (infile, &chunk_header, sizeof (Wave64ChunkHeader), &bcount) ||
bcount != sizeof (Wave64ChunkHeader)) {
error_line ("%s is not a valid .W64 file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &chunk_header, sizeof (Wave64ChunkHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackLittleEndianToNative (&chunk_header, Wave64ChunkHeaderFormat);
chunk_header.ckSize -= sizeof (chunk_header);
// if it's the format chunk, we want to get some info out of there and
// make sure it's a .wav file we can handle
if (!memcmp (chunk_header.ckID, fmt_guid, sizeof (fmt_guid))) {
int supported = TRUE, format;
chunk_header.ckSize = (chunk_header.ckSize + 7) & ~7L;
if (chunk_header.ckSize < 16 || chunk_header.ckSize > sizeof (WaveHeader) ||
!DoReadFile (infile, &WaveHeader, (uint32_t) chunk_header.ckSize, &bcount) ||
bcount != chunk_header.ckSize) {
error_line ("%s is not a valid .W64 file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &WaveHeader, (uint32_t) chunk_header.ckSize)) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackLittleEndianToNative (&WaveHeader, WaveHeaderFormat);
if (debug_logging_mode) {
error_line ("format tag size = %d", chunk_header.ckSize);
error_line ("FormatTag = %x, NumChannels = %d, BitsPerSample = %d",
WaveHeader.FormatTag, WaveHeader.NumChannels, WaveHeader.BitsPerSample);
error_line ("BlockAlign = %d, SampleRate = %d, BytesPerSecond = %d",
WaveHeader.BlockAlign, WaveHeader.SampleRate, WaveHeader.BytesPerSecond);
if (chunk_header.ckSize > 16)
error_line ("cbSize = %d, ValidBitsPerSample = %d", WaveHeader.cbSize,
WaveHeader.ValidBitsPerSample);
if (chunk_header.ckSize > 20)
error_line ("ChannelMask = %x, SubFormat = %d",
WaveHeader.ChannelMask, WaveHeader.SubFormat);
}
if (chunk_header.ckSize > 16 && WaveHeader.cbSize == 2)
config->qmode |= QMODE_ADOBE_MODE;
format = (WaveHeader.FormatTag == 0xfffe && chunk_header.ckSize == 40) ?
WaveHeader.SubFormat : WaveHeader.FormatTag;
config->bits_per_sample = (chunk_header.ckSize == 40 && WaveHeader.ValidBitsPerSample) ?
WaveHeader.ValidBitsPerSample : WaveHeader.BitsPerSample;
if (format != 1 && format != 3)
supported = FALSE;
if (format == 3 && config->bits_per_sample != 32)
supported = FALSE;
if (!WaveHeader.NumChannels || WaveHeader.NumChannels > 256 ||
WaveHeader.BlockAlign / WaveHeader.NumChannels < (config->bits_per_sample + 7) / 8 ||
WaveHeader.BlockAlign / WaveHeader.NumChannels > 4 ||
WaveHeader.BlockAlign % WaveHeader.NumChannels)
supported = FALSE;
if (config->bits_per_sample < 1 || config->bits_per_sample > 32)
supported = FALSE;
if (!supported) {
error_line ("%s is an unsupported .W64 format!", infilename);
return WAVPACK_SOFT_ERROR;
}
if (chunk_header.ckSize < 40) {
if (!config->channel_mask && !(config->qmode & QMODE_CHANS_UNASSIGNED)) {
if (WaveHeader.NumChannels <= 2)
config->channel_mask = 0x5 - WaveHeader.NumChannels;
else if (WaveHeader.NumChannels <= 18)
config->channel_mask = (1 << WaveHeader.NumChannels) - 1;
else
config->channel_mask = 0x3ffff;
}
}
else if (WaveHeader.ChannelMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) {
error_line ("this W64 file already has channel order information!");
return WAVPACK_SOFT_ERROR;
}
else if (WaveHeader.ChannelMask)
config->channel_mask = WaveHeader.ChannelMask;
if (format == 3)
config->float_norm_exp = 127;
else if ((config->qmode & QMODE_ADOBE_MODE) &&
WaveHeader.BlockAlign / WaveHeader.NumChannels == 4) {
if (WaveHeader.BitsPerSample == 24)
config->float_norm_exp = 127 + 23;
else if (WaveHeader.BitsPerSample == 32)
config->float_norm_exp = 127 + 15;
}
if (debug_logging_mode) {
if (config->float_norm_exp == 127)
error_line ("data format: normalized 32-bit floating point");
else
error_line ("data format: %d-bit integers stored in %d byte(s)",
config->bits_per_sample, WaveHeader.BlockAlign / WaveHeader.NumChannels);
}
}
else if (!memcmp (chunk_header.ckID, data_guid, sizeof (data_guid))) { // on the data chunk, get size and exit loop
if (!WaveHeader.NumChannels) { // make sure we saw "fmt" chunk
error_line ("%s is not a valid .W64 file!", infilename);
return WAVPACK_SOFT_ERROR;
}
if ((config->qmode & QMODE_IGNORE_LENGTH) || chunk_header.ckSize <= 0) {
config->qmode |= QMODE_IGNORE_LENGTH;
if (infilesize && DoGetFilePosition (infile) != -1)
total_samples = (infilesize - DoGetFilePosition (infile)) / WaveHeader.BlockAlign;
else
total_samples = -1;
}
else {
if (infilesize && infilesize - chunk_header.ckSize > 16777216) {
error_line ("this .W64 file has over 16 MB of extra RIFF data, probably is corrupt!");
return WAVPACK_SOFT_ERROR;
}
total_samples = chunk_header.ckSize / WaveHeader.BlockAlign;
if (!total_samples) {
error_line ("this .W64 file has no audio samples, probably is corrupt!");
return WAVPACK_SOFT_ERROR;
}
if (total_samples > MAX_WAVPACK_SAMPLES) {
error_line ("%s has too many samples for WavPack!", infilename);
return WAVPACK_SOFT_ERROR;
}
}
config->bytes_per_sample = WaveHeader.BlockAlign / WaveHeader.NumChannels;
config->num_channels = WaveHeader.NumChannels;
config->sample_rate = WaveHeader.SampleRate;
break;
}
else { // just copy unknown chunks to output file
int bytes_to_copy = (chunk_header.ckSize + 7) & ~7L;
char *buff;
if (bytes_to_copy < 0 || bytes_to_copy > 4194304) {
error_line ("%s is not a valid .W64 file!", infilename);
return WAVPACK_SOFT_ERROR;
}
buff = malloc (bytes_to_copy);
if (debug_logging_mode)
error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes",
chunk_header.ckID [0], chunk_header.ckID [1], chunk_header.ckID [2],
chunk_header.ckID [3], chunk_header.ckSize);
if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) ||
bcount != bytes_to_copy ||
(!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, buff, bytes_to_copy))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
free (buff);
return WAVPACK_SOFT_ERROR;
}
free (buff);
}
}
if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) {
error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
return WAVPACK_NO_ERROR;
}
int WriteWave64Header (FILE *outfile, WavpackContext *wpc, int64_t total_samples, int qmode)
{
Wave64ChunkHeader datahdr, fmthdr;
Wave64FileHeader filehdr;
WaveHeader wavhdr;
uint32_t bcount;
int64_t total_data_bytes, total_file_bytes;
int num_channels = WavpackGetNumChannels (wpc);
int32_t channel_mask = WavpackGetChannelMask (wpc);
int32_t sample_rate = WavpackGetSampleRate (wpc);
int bytes_per_sample = WavpackGetBytesPerSample (wpc);
int bits_per_sample = WavpackGetBitsPerSample (wpc);
int format = WavpackGetFloatNormExp (wpc) ? 3 : 1;
int wavhdrsize = 16;
if (format == 3 && WavpackGetFloatNormExp (wpc) != 127) {
error_line ("can't create valid Wave64 header for non-normalized floating data!");
return FALSE;
}
if (total_samples == -1)
total_samples = 0x7ffff000 / (bytes_per_sample * num_channels);
total_data_bytes = total_samples * bytes_per_sample * num_channels;
CLEAR (wavhdr);
wavhdr.FormatTag = format;
wavhdr.NumChannels = num_channels;
wavhdr.SampleRate = sample_rate;
wavhdr.BytesPerSecond = sample_rate * num_channels * bytes_per_sample;
wavhdr.BlockAlign = bytes_per_sample * num_channels;
wavhdr.BitsPerSample = bits_per_sample;
if (num_channels > 2 || channel_mask != 0x5 - num_channels) {
wavhdrsize = sizeof (wavhdr);
wavhdr.cbSize = 22;
wavhdr.ValidBitsPerSample = bits_per_sample;
wavhdr.SubFormat = format;
wavhdr.ChannelMask = channel_mask;
wavhdr.FormatTag = 0xfffe;
wavhdr.BitsPerSample = bytes_per_sample * 8;
wavhdr.GUID [4] = 0x10;
wavhdr.GUID [6] = 0x80;
wavhdr.GUID [9] = 0xaa;
wavhdr.GUID [11] = 0x38;
wavhdr.GUID [12] = 0x9b;
wavhdr.GUID [13] = 0x71;
}
total_file_bytes = sizeof (filehdr) + sizeof (fmthdr) + wavhdrsize + sizeof (datahdr) + ((total_data_bytes + 7) & ~(int64_t)7);
memcpy (filehdr.ckID, riff_guid, sizeof (riff_guid));
memcpy (filehdr.formType, wave_guid, sizeof (wave_guid));
filehdr.ckSize = total_file_bytes;
memcpy (fmthdr.ckID, fmt_guid, sizeof (fmt_guid));
fmthdr.ckSize = sizeof (fmthdr) + wavhdrsize;
memcpy (datahdr.ckID, data_guid, sizeof (data_guid));
datahdr.ckSize = total_data_bytes + sizeof (datahdr);
// write the RIFF chunks up to just before the data starts
WavpackNativeToLittleEndian (&filehdr, Wave64ChunkHeaderFormat);
WavpackNativeToLittleEndian (&fmthdr, Wave64ChunkHeaderFormat);
WavpackNativeToLittleEndian (&wavhdr, WaveHeaderFormat);
WavpackNativeToLittleEndian (&datahdr, Wave64ChunkHeaderFormat);
if (!DoWriteFile (outfile, &filehdr, sizeof (filehdr), &bcount) || bcount != sizeof (filehdr) ||
!DoWriteFile (outfile, &fmthdr, sizeof (fmthdr), &bcount) || bcount != sizeof (fmthdr) ||
!DoWriteFile (outfile, &wavhdr, wavhdrsize, &bcount) || bcount != wavhdrsize ||
!DoWriteFile (outfile, &datahdr, sizeof (datahdr), &bcount) || bcount != sizeof (datahdr)) {
error_line ("can't write .W64 data, disk probably full!");
return FALSE;
}
return TRUE;
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_95_1 |
crossvul-cpp_data_good_4263_1 | /******************************************************************************
* pdf.c
*
* pdfresurrect - PDF history extraction tool
*
* Copyright (C) 2008-2010, 2012-2013, 2017-20, Matt Davis (enferex).
*
* Special thanks to all of the contributors: See AUTHORS.
*
* Special thanks to 757labs (757 crew), they are a great group
* of people to hack on projects and brainstorm with.
*
* pdf.c is part of pdfresurrect.
* pdfresurrect 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 3 of the License, or
* (at your option) any later version.
*
* pdfresurrect 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 pdfresurrect. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "pdf.h"
#include "main.h"
/*
* Macros
*/
/* SAFE_F
*
* Safe file read: use for fgetc() calls, this is really ugly looking.
* _fp: FILE * handle
* _expr: The expression with fgetc() in it:
*
* example: If we get a character from the file and it is ascii character 'a'
* This assumes the coder wants to store the 'a' in variable ch
* Kinda pointless if you already know that you have 'a', but for
* illustrative purposes.
*
* if (SAFE_F(my_fp, ((c=fgetc(my_fp)) == 'a')))
* do_way_cool_stuff();
*/
#define SAFE_F(_fp, _expr) \
((!ferror(_fp) && !feof(_fp) && (_expr)))
/* FAIL
*
* Emit the diagnostic '_msg' and exit.
* _msg: Message to emit prior to exiting.
*/
#define FAIL(_msg) \
do { \
ERR(_msg); \
exit(EXIT_FAILURE); \
} while (0)
/* SAFE_E
*
* Safe expression handling. This macro is a wrapper
* that compares the result of an expression (_expr) to the expected
* value (_cmp).
*
* _expr: Expression to test.
* _cmp: Expected value, error if this returns false.
* _msg: What to say when an error occurs.
*/
#define SAFE_E(_expr, _cmp, _msg) \
do { \
if ((_expr) != (_cmp)) { \
FAIL(_msg); \
} \
} while (0)
/*
* Forwards
*/
static int is_valid_xref(FILE *fp, pdf_t *pdf, xref_t *xref);
static void load_xref_entries(FILE *fp, xref_t *xref);
static void load_xref_from_plaintext(FILE *fp, xref_t *xref);
static void load_xref_from_stream(FILE *fp, xref_t *xref);
static void get_xref_linear_skipped(FILE *fp, xref_t *xref);
static void resolve_linearized_pdf(pdf_t *pdf);
static pdf_creator_t *new_creator(int *n_elements);
static void load_creator(FILE *fp, pdf_t *pdf);
static void load_creator_from_buf(
FILE *fp,
xref_t *xref,
const char *buf,
size_t buf_size);
static void load_creator_from_xml(xref_t *xref, const char *buf);
static void load_creator_from_old_format(
FILE *fp,
xref_t *xref,
const char *buf,
size_t buf_size);
static char *get_object_from_here(FILE *fp, size_t *size, int *is_stream);
static char *get_object(
FILE *fp,
int obj_id,
const xref_t *xref,
size_t *size,
int *is_stream);
static const char *get_type(FILE *fp, int obj_id, const xref_t *xref);
/* static int get_page(int obj_id, const xref_t *xref); */
static char *get_header(FILE *fp);
static char *decode_text_string(const char *str, size_t str_len);
static int get_next_eof(FILE *fp);
/*
* Defined
*/
pdf_t *pdf_new(const char *name)
{
const char *n;
pdf_t *pdf;
pdf = safe_calloc(sizeof(pdf_t));
if (name)
{
/* Just get the file name (not path) */
if ((n = strrchr(name, '/')))
++n;
else
n = name;
pdf->name = safe_calloc(strlen(n) + 1);
strcpy(pdf->name, n);
}
else /* !name */
{
pdf->name = safe_calloc(strlen("Unknown") + 1);
strcpy(pdf->name, "Unknown");
}
return pdf;
}
void pdf_delete(pdf_t *pdf)
{
int i;
for (i=0; i<pdf->n_xrefs; i++)
{
free(pdf->xrefs[i].creator);
free(pdf->xrefs[i].entries);
}
free(pdf->name);
free(pdf->xrefs);
free(pdf);
}
int pdf_is_pdf(FILE *fp)
{
char *header;
if (!(header = get_header(fp)))
return 0;
/* First 1024 bytes of doc must be header (1.7 spec pg 1102) */
const char *c = strstr(header, "%PDF-");
const int is_pdf = c && ((c - header+strlen("%PDF-M.m")) < 1024);
free(header);
return is_pdf;
}
void pdf_get_version(FILE *fp, pdf_t *pdf)
{
char *header = get_header(fp);
/* Locate version string start and make sure we dont go past header
* The format is %PDF-M.m, where 'M' is the major number and 'm' minor.
*/
const char *c;
if ((c = strstr(header, "%PDF-")) &&
((c + 6)[0] == '.') && // Separator
isdigit((c + 5)[0]) && // Major number
isdigit((c + 7)[0])) // Minor number
{
pdf->pdf_major_version = atoi(c + strlen("%PDF-"));
pdf->pdf_minor_version = atoi(c + strlen("%PDF-M."));
}
free(header);
}
int pdf_load_xrefs(FILE *fp, pdf_t *pdf)
{
int i, ver, is_linear;
long pos, pos_count;
char x, *c, buf[256];
c = NULL;
/* Count number of xrefs */
pdf->n_xrefs = 0;
fseek(fp, 0, SEEK_SET);
while (get_next_eof(fp) >= 0)
++pdf->n_xrefs;
if (!pdf->n_xrefs)
return 0;
/* Load in the start/end positions */
fseek(fp, 0, SEEK_SET);
pdf->xrefs = safe_calloc(sizeof(xref_t) * pdf->n_xrefs);
ver = 1;
for (i=0; i<pdf->n_xrefs; i++)
{
/* Seek to %%EOF */
if ((pos = get_next_eof(fp)) < 0)
break;
/* Set and increment the version */
pdf->xrefs[i].version = ver++;
/* Rewind until we find end of "startxref" */
pos_count = 0;
while (SAFE_F(fp, ((x = fgetc(fp)) != 'f')))
fseek(fp, pos - (++pos_count), SEEK_SET);
/* Suck in end of "startxref" to start of %%EOF */
if (pos_count >= sizeof(buf)) {
FAIL("Failed to locate the startxref token. "
"This might be a corrupt PDF.\n");
}
memset(buf, 0, sizeof(buf));
SAFE_E(fread(buf, 1, pos_count, fp), pos_count,
"Failed to read startxref.\n");
c = buf;
while (*c == ' ' || *c == '\n' || *c == '\r')
++c;
/* xref start position */
pdf->xrefs[i].start = atol(c);
/* If xref is 0 handle linear xref table */
if (pdf->xrefs[i].start == 0)
get_xref_linear_skipped(fp, &pdf->xrefs[i]);
/* Non-linear, normal operation, so just find the end of the xref */
else
{
/* xref end position */
pos = ftell(fp);
fseek(fp, pdf->xrefs[i].start, SEEK_SET);
pdf->xrefs[i].end = get_next_eof(fp);
/* Look for next EOF and xref data */
fseek(fp, pos, SEEK_SET);
}
/* Check validity */
if (!is_valid_xref(fp, pdf, &pdf->xrefs[i]))
{
is_linear = pdf->xrefs[i].is_linear;
memset(&pdf->xrefs[i], 0, sizeof(xref_t));
pdf->xrefs[i].is_linear = is_linear;
rewind(fp);
get_next_eof(fp);
continue;
}
/* Load the entries from the xref */
load_xref_entries(fp, &pdf->xrefs[i]);
}
/* Now we have all xref tables, if this is linearized, we need
* to make adjustments so that things spit out properly
*/
if (pdf->xrefs[0].is_linear)
resolve_linearized_pdf(pdf);
/* Ok now we have all xref data. Go through those versions of the
* PDF and try to obtain creator information
*/
load_creator(fp, pdf);
return pdf->n_xrefs;
}
/* Load page information */
char pdf_get_object_status(
const pdf_t *pdf,
int xref_idx,
int entry_idx)
{
int i, curr_ver;
const xref_t *prev_xref;
const xref_entry_t *prev, *curr;
curr = &pdf->xrefs[xref_idx].entries[entry_idx];
curr_ver = pdf->xrefs[xref_idx].version;
if (curr_ver == 1)
return 'A';
/* Deleted (freed) */
if (curr->f_or_n == 'f')
return 'D';
/* Get previous version */
prev_xref = NULL;
for (i=xref_idx; i>-1; --i)
if (pdf->xrefs[i].version < curr_ver)
{
prev_xref = &pdf->xrefs[i];
break;
}
if (!prev_xref)
return '?';
/* Locate the object in the previous one that matches current one */
prev = NULL;
for (i=0; i<prev_xref->n_entries; ++i)
if (prev_xref->entries[i].obj_id == curr->obj_id)
{
prev = &prev_xref->entries[i];
break;
}
/* Added in place of a previously freed id */
if (!prev || ((prev->f_or_n == 'f') && (curr->f_or_n == 'n')))
return 'A';
/* Modified */
else if (prev->offset != curr->offset)
return 'M';
return '?';
}
void pdf_zero_object(
FILE *fp,
const pdf_t *pdf,
int xref_idx,
int entry_idx)
{
int i;
char *obj;
size_t obj_sz;
xref_entry_t *entry;
entry = &pdf->xrefs[xref_idx].entries[entry_idx];
fseek(fp, entry->offset, SEEK_SET);
/* Get object and size */
obj = get_object(fp, entry->obj_id, &pdf->xrefs[xref_idx], NULL, NULL);
i = obj_sz = 0;
while (strncmp((++i)+obj, "endobj", 6))
++obj_sz;
if (obj_sz)
obj_sz += strlen("endobj") + 1;
/* Zero object */
for (i=0; i<obj_sz; i++)
fputc('0', fp);
printf("Zeroed object %d\n", entry->obj_id);
free(obj);
}
/* Output information per version */
void pdf_summarize(
FILE *fp,
const pdf_t *pdf,
const char *name,
pdf_flag_t flags)
{
int i, j, page, n_versions, n_entries;
FILE *dst, *out;
char *dst_name, *c;
dst = NULL;
dst_name = NULL;
if (name)
{
dst_name = safe_calloc(strlen(name) * 2 + 16);
sprintf(dst_name, "%s/%s", name, name);
if ((c = strrchr(dst_name, '.')) && (strncmp(c, ".pdf", 4) == 0))
*c = '\0';
strcat(dst_name, ".summary");
if (!(dst = fopen(dst_name, "w")))
{
ERR("Could not open file '%s' for writing\n", dst_name);
return;
}
}
/* Send output to file or stdout */
out = (dst) ? dst : stdout;
/* Count versions */
n_versions = pdf->n_xrefs;
if (n_versions && pdf->xrefs[0].is_linear)
--n_versions;
/* Ignore bad xref entry */
for (i=1; i<pdf->n_xrefs; ++i)
if (pdf->xrefs[i].end == 0)
--n_versions;
/* If we have no valid versions but linear, count that */
if (!pdf->n_xrefs || (!n_versions && pdf->xrefs[0].is_linear))
n_versions = 1;
/* Compare each object (if we dont have xref streams) */
n_entries = 0;
for (i=0; !(const int)pdf->has_xref_streams && i<pdf->n_xrefs; i++)
{
if (flags & PDF_FLAG_QUIET)
continue;
for (j=0; j<pdf->xrefs[i].n_entries; j++)
{
++n_entries;
fprintf(out,
"%s: --%c-- Version %d -- Object %d (%s)",
pdf->name,
pdf_get_object_status(pdf, i, j),
pdf->xrefs[i].version,
pdf->xrefs[i].entries[j].obj_id,
get_type(fp, pdf->xrefs[i].entries[j].obj_id,
&pdf->xrefs[i]));
/* TODO
page = get_page(pdf->xrefs[i].entries[j].obj_id, &pdf->xrefs[i]);
*/
if (0 /*page*/)
fprintf(out, " Page(%d)\n", page);
else
fprintf(out, "\n");
}
}
/* Trailing summary */
if (!(flags & PDF_FLAG_QUIET))
{
/* Let the user know that we cannot we print a per-object summary.
* If we have a 1.5 PDF using streams for xref, we have not objects
* to display, so let the user know whats up.
*/
if (pdf->has_xref_streams || !n_entries)
fprintf(out,
"%s: This PDF contains potential cross reference streams.\n"
"%s: An object summary is not available.\n",
pdf->name,
pdf->name);
fprintf(out,
"---------- %s ----------\n"
"Versions: %d\n",
pdf->name,
n_versions);
/* Count entries for summary */
if (!pdf->has_xref_streams)
for (i=0; i<pdf->n_xrefs; i++)
{
if (pdf->xrefs[i].is_linear)
continue;
n_entries = pdf->xrefs[i].n_entries;
/* If we are a linearized PDF, all versions are made from those
* objects too. So count em'
*/
if (pdf->xrefs[0].is_linear)
n_entries += pdf->xrefs[0].n_entries;
if (pdf->xrefs[i].version && n_entries)
fprintf(out,
"Version %d -- %d objects\n",
pdf->xrefs[i].version,
n_entries);
}
}
else /* Quiet output */
fprintf(out, "%s: %d\n", pdf->name, n_versions);
if (dst)
{
fclose(dst);
free(dst_name);
}
}
/* Returns '1' if we successfully display data (means its probably not xml) */
int pdf_display_creator(const pdf_t *pdf, int xref_idx)
{
int i;
if (!pdf->xrefs[xref_idx].creator)
return 0;
for (i=0; i<pdf->xrefs[xref_idx].n_creator_entries; ++i)
printf("%s: %s\n",
pdf->xrefs[xref_idx].creator[i].key,
pdf->xrefs[xref_idx].creator[i].value);
return (i > 0);
}
/* Checks if the xref is valid and sets 'is_stream' flag if the xref is a
* stream (PDF 1.5 or higher)
*/
static int is_valid_xref(FILE *fp, pdf_t *pdf, xref_t *xref)
{
int is_valid;
long start;
char *c, buf[16];
memset(buf, 0, sizeof(buf));
is_valid = 0;
start = ftell(fp);
fseek(fp, xref->start, SEEK_SET);
if (fgets(buf, 16, fp) == NULL) {
ERR("Failed to load xref string.");
exit(EXIT_FAILURE);
}
if (strncmp(buf, "xref", strlen("xref")) == 0)
is_valid = 1;
else
{
/* PDFv1.5+ allows for xref data to be stored in streams vs plaintext */
fseek(fp, xref->start, SEEK_SET);
c = get_object_from_here(fp, NULL, &xref->is_stream);
if (c && xref->is_stream)
{
pdf->has_xref_streams = 1;
is_valid = 1;
}
free(c);
}
fseek(fp, start, SEEK_SET);
return is_valid;
}
static void load_xref_entries(FILE *fp, xref_t *xref)
{
if (xref->is_stream)
load_xref_from_stream(fp, xref);
else
load_xref_from_plaintext(fp, xref);
}
static void load_xref_from_plaintext(FILE *fp, xref_t *xref)
{
int i, obj_id, added_entries;
char c, buf[32] = {0};
long start, pos;
size_t buf_idx;
start = ftell(fp);
/* Get number of entries */
pos = xref->end;
fseek(fp, pos, SEEK_SET);
while (ftell(fp) != 0)
if (SAFE_F(fp, (fgetc(fp) == '/' && fgetc(fp) == 'S')))
break;
else
SAFE_E(fseek(fp, --pos, SEEK_SET), 0, "Failed seek to xref /Size.\n");
SAFE_E(fread(buf, 1, 21, fp), 21, "Failed to load entry Size string.\n");
xref->n_entries = atoi(buf + strlen("ize "));
xref->entries = safe_calloc(xref->n_entries * sizeof(struct _xref_entry));
/* Load entry data */
obj_id = 0;
fseek(fp, xref->start + strlen("xref"), SEEK_SET);
added_entries = 0;
for (i=0; i<xref->n_entries; i++)
{
/* Advance past newlines. */
c = fgetc(fp);
while (c == '\n' || c == '\r')
c = fgetc(fp);
/* Collect data up until the following newline. */
buf_idx = 0;
while (c != '\n' && c != '\r' && !feof(fp) &&
!ferror(fp) && buf_idx < sizeof(buf))
{
buf[buf_idx++] = c;
c = fgetc(fp);
}
if (buf_idx >= sizeof(buf)) {
FAIL("Failed to locate newline character. "
"This might be a corrupt PDF.\n");
}
buf[buf_idx] = '\0';
/* Went to far and hit start of trailer */
if (strchr(buf, 't'))
break;
/* Entry or object id */
if (strlen(buf) > 17)
{
const char *token = NULL;
xref->entries[i].obj_id = obj_id++;
token = strtok(buf, " ");
if (!token) {
FAIL("Failed to parse xref entry. "
"This might be a corrupt PDF.\n");
}
xref->entries[i].offset = atol(token);
token = strtok(NULL, " ");
if (!token) {
FAIL("Failed to parse xref entry. "
"This might be a corrupt PDF.\n");
}
xref->entries[i].gen_num = atoi(token);
xref->entries[i].f_or_n = buf[17];
++added_entries;
}
else
{
obj_id = atoi(buf);
--i;
}
}
xref->n_entries = added_entries;
fseek(fp, start, SEEK_SET);
}
/* Load an xref table from a stream (PDF v1.5 +) */
static void load_xref_from_stream(FILE *fp, xref_t *xref)
{
long start;
int is_stream;
char *stream;
size_t size;
start = ftell(fp);
fseek(fp, xref->start, SEEK_SET);
stream = NULL;
stream = get_object_from_here(fp, &size, &is_stream);
fseek(fp, start, SEEK_SET);
/* TODO: decode and analyize stream */
free(stream);
return;
}
static void get_xref_linear_skipped(FILE *fp, xref_t *xref)
{
int err;
char ch, buf[256];
if (xref->start != 0)
return;
/* Special case (Linearized PDF with initial startxref at 0) */
xref->is_linear = 1;
/* Seek to %%EOF */
if ((xref->end = get_next_eof(fp)) < 0)
return;
/* Locate the trailer */
err = 0;
while (!(err = ferror(fp)) && fread(buf, 1, 8, fp))
{
if (strncmp(buf, "trailer", strlen("trailer")) == 0)
break;
else if ((ftell(fp) - 9) < 0)
return;
fseek(fp, -9, SEEK_CUR);
}
if (err)
return;
/* If we found 'trailer' look backwards for 'xref' */
ch = 0;
while (SAFE_F(fp, ((ch = fgetc(fp)) != 'x')))
fseek(fp, -2, SEEK_CUR);
if (ch == 'x')
{
xref->start = ftell(fp) - 1;
fseek(fp, -1, SEEK_CUR);
}
/* Now continue to next eof ... */
fseek(fp, xref->start, SEEK_SET);
}
/* This must only be called after all xref and entries have been acquired */
static void resolve_linearized_pdf(pdf_t *pdf)
{
int i;
xref_t buf;
if (pdf->n_xrefs < 2)
return;
if (!pdf->xrefs[0].is_linear)
return;
/* Swap Linear with Version 1 */
buf = pdf->xrefs[0];
pdf->xrefs[0] = pdf->xrefs[1];
pdf->xrefs[1] = buf;
/* Resolve is_linear flag and version */
pdf->xrefs[0].is_linear = 1;
pdf->xrefs[0].version = 1;
pdf->xrefs[1].is_linear = 0;
pdf->xrefs[1].version = 1;
/* Adjust the other version values now */
for (i=2; i<pdf->n_xrefs; ++i)
--pdf->xrefs[i].version;
}
static pdf_creator_t *new_creator(int *n_elements)
{
pdf_creator_t *daddy;
static const pdf_creator_t creator_template[] =
{
{"Title", ""},
{"Author", ""},
{"Subject", ""},
{"Keywords", ""},
{"Creator", ""},
{"Producer", ""},
{"CreationDate", ""},
{"ModDate", ""},
{"Trapped", ""},
};
daddy = safe_calloc(sizeof(creator_template));
memcpy(daddy, creator_template, sizeof(creator_template));
if (n_elements)
*n_elements = sizeof(creator_template) / sizeof(creator_template[0]);
return daddy;
}
#define END_OF_TRAILER(_c, _st, _fp) \
{ \
if (_c == '>') \
{ \
fseek(_fp, _st, SEEK_SET); \
continue; \
} \
}
static void load_creator(FILE *fp, pdf_t *pdf)
{
int i, buf_idx;
char c, *buf, obj_id_buf[32] = {0};
long start;
size_t sz;
start = ftell(fp);
/* For each PDF version */
for (i=0; i<pdf->n_xrefs; ++i)
{
if (!pdf->xrefs[i].version)
continue;
/* Find trailer */
fseek(fp, pdf->xrefs[i].start, SEEK_SET);
while (SAFE_F(fp, (fgetc(fp) != 't')))
; /* Iterate to "trailer" */
/* Look for "<< ....... /Info ......" */
c = '\0';
while (SAFE_F(fp, ((c = fgetc(fp)) != '>')))
if (SAFE_F(fp, ((c == '/') &&
(fgetc(fp) == 'I') && ((fgetc(fp) == 'n')))))
break;
/* Could not find /Info in trailer */
END_OF_TRAILER(c, start, fp);
while (SAFE_F(fp, (!isspace(c = fgetc(fp)) && (c != '>'))))
; /* Iterate to first white space /Info<space><data> */
/* No space between /Info and its data */
END_OF_TRAILER(c, start, fp);
while (SAFE_F(fp, (isspace(c = fgetc(fp)) && (c != '>'))))
; /* Iterate right on top of first non-whitespace /Info data */
/* No data for /Info */
END_OF_TRAILER(c, start, fp);
/* Get obj id as number */
buf_idx = 0;
obj_id_buf[buf_idx++] = c;
while ((buf_idx < (sizeof(obj_id_buf) - 1)) &&
SAFE_F(fp, (!isspace(c = fgetc(fp)) && (c != '>'))))
obj_id_buf[buf_idx++] = c;
END_OF_TRAILER(c, start, fp);
/* Get the object for the creator data. If linear, try both xrefs */
buf = get_object(fp, atoll(obj_id_buf), &pdf->xrefs[i], &sz, NULL);
if (!buf && pdf->xrefs[i].is_linear && (i+1 < pdf->n_xrefs))
buf = get_object(fp, atoll(obj_id_buf), &pdf->xrefs[i+1], &sz, NULL);
load_creator_from_buf(fp, &pdf->xrefs[i], buf, sz);
free(buf);
}
fseek(fp, start, SEEK_SET);
}
static void load_creator_from_buf(
FILE *fp,
xref_t *xref,
const char *buf,
size_t buf_size)
{
int is_xml;
char *c;
if (!buf)
return;
/* Check to see if this is xml or old-school */
if ((c = strstr(buf, "/Type")))
while (*c && !isspace(*c))
++c;
/* Probably "Metadata" */
is_xml = 0;
if (c && (*c == 'M'))
is_xml = 1;
/* Is the buffer XML(PDF 1.4+) or old format? */
if (is_xml)
load_creator_from_xml(xref, buf);
else
load_creator_from_old_format(fp, xref, buf, buf_size);
}
static void load_creator_from_xml(xref_t *xref, const char *buf)
{
/* TODO */
}
static void load_creator_from_old_format(
FILE *fp,
xref_t *xref,
const char *buf,
size_t buf_size)
{
int i, n_eles, length, is_escaped, obj_id;
char *c, *ascii, *start, *s, *saved_buf_search, *obj;
size_t obj_size;
pdf_creator_t *info;
info = new_creator(&n_eles);
/* Mark the end of buf, so that we do not crawl past it */
if (buf_size < 1) return;
const char *buf_end = buf + buf_size - 1;
/* Treat 'end' as either the end of 'buf' or the end of 'obj'. Obj is if
* the creator element (e.g., ModDate, Producer, etc) is an object and not
* part of 'buf'.
*/
const char *end = buf_end;
for (i=0; i<n_eles; ++i)
{
if (!(c = strstr(buf, info[i].key)))
continue;
/* Find the value (skipping whitespace) */
c += strlen(info[i].key);
while (isspace(*c))
++c;
if (c >= buf_end) {
FAIL("Failed to locate space, likely a corrupt PDF.");
}
/* If looking at the start of a pdf token, we have gone too far */
if (*c == '/')
continue;
/* If the value is a number and not a '(' then the data is located in
* an object we need to fetch, and not inline
*/
obj = saved_buf_search = NULL;
obj_size = 0;
end = buf_end; /* Init to be the buffer, this might not be an obj. */
if (isdigit(*c))
{
obj_id = atoi(c);
saved_buf_search = c;
s = saved_buf_search;
obj = get_object(fp, obj_id, xref, &obj_size, NULL);
end = obj + obj_size;
c = obj;
/* Iterate to '(' */
while (c && (*c != '(') && (c < end))
++c;
if (c >= end) {
FAIL("Failed to locate a '(' character. "
"This might be a corrupt PDF.\n");
}
/* Advance the search to the next token */
while (s && (*s == '/') && (s < buf_end))
++s;
if (s >= buf_end) {
FAIL("Failed to locate a '/' character. "
"This might be a corrupt PDF.\n");
}
saved_buf_search = s;
}
/* Find the end of the value */
start = c;
length = is_escaped = 0;
while (c && ((*c != '\r') && (*c != '\n') && (*c != '<')))
{
/* Bail out if we see an un-escaped ')' closing character */
if (!is_escaped && (*c == ')'))
break;
else if (*c == '\\')
is_escaped = 1;
else
is_escaped = 0;
++c;
++length;
if (c > end) {
FAIL("Failed to locate the end of a value. "
"This might be a corrupt PDF.\n");
}
}
if (length == 0)
continue;
/* Add 1 to length so it gets the closing ')' when we copy */
if (length)
length += 1;
length = (length > KV_MAX_VALUE_LENGTH) ? KV_MAX_VALUE_LENGTH : length;
strncpy(info[i].value, start, length);
info[i].value[KV_MAX_VALUE_LENGTH - 1] = '\0';
/* Restore where we were searching from */
if (saved_buf_search)
{
/* Release memory from get_object() called earlier */
free(obj);
c = saved_buf_search;
}
} /* For all creation information tags */
/* Go through the values and convert if encoded */
for (i = 0; i < n_eles; ++i) {
const size_t val_str_len = strnlen(info[i].value, KV_MAX_VALUE_LENGTH);
if ((ascii = decode_text_string(info[i].value, val_str_len))) {
strncpy(info[i].value, ascii, val_str_len);
free(ascii);
}
}
xref->creator = info;
xref->n_creator_entries = n_eles;
}
/* Returns object data at the start of the file pointer
* This interfaces to 'get_object'
*/
static char *get_object_from_here(FILE *fp, size_t *size, int *is_stream)
{
long start;
char buf[256];
int obj_id;
xref_t xref;
xref_entry_t entry;
start = ftell(fp);
/* Object ID */
memset(buf, 0, 256);
SAFE_E(fread(buf, 1, 255, fp), 255, "Failed to load object ID.\n");
if (!(obj_id = atoi(buf)))
{
fseek(fp, start, SEEK_SET);
return NULL;
}
/* Create xref entry to pass to the get_object routine */
memset(&entry, 0, sizeof(xref_entry_t));
entry.obj_id = obj_id;
entry.offset = start;
/* Xref and single entry for the object we want data from */
memset(&xref, 0, sizeof(xref_t));
xref.n_entries = 1;
xref.entries = &entry;
fseek(fp, start, SEEK_SET);
return get_object(fp, obj_id, &xref, size, is_stream);
}
static char *get_object(
FILE *fp,
int obj_id,
const xref_t *xref,
size_t *size,
int *is_stream)
{
static const int blk_sz = 256;
int i, total_sz, read_sz, n_blks, search, stream;
size_t obj_sz;
char *c, *data;
long start;
const xref_entry_t *entry;
if (size)
*size = 0;
if (is_stream)
*is_stream = 0;
start = ftell(fp);
/* Find object */
entry = NULL;
for (i=0; i<xref->n_entries; i++)
if (xref->entries[i].obj_id == obj_id)
{
entry = &xref->entries[i];
break;
}
if (!entry)
return NULL;
/* Jump to object start */
fseek(fp, entry->offset, SEEK_SET);
/* Initial allocation */
obj_sz = 0; /* Bytes in object */
total_sz = 0; /* Bytes read in */
n_blks = 1;
data = safe_calloc(blk_sz * n_blks);
/* Suck in data */
stream = 0;
while ((read_sz = fread(data+total_sz, 1, blk_sz-1, fp)) && !ferror(fp))
{
total_sz += read_sz;
*(data + total_sz) = '\0';
if (total_sz + blk_sz >= (blk_sz * n_blks))
data = realloc(data, blk_sz * (++n_blks));
if (!data) {
ERR("Failed to reallocate buffer.\n");
exit(EXIT_FAILURE);
}
search = total_sz - read_sz;
if (search < 0)
search = 0;
if ((c = strstr(data + search, "endobj")))
{
*(c + strlen("endobj") + 1) = '\0';
obj_sz = (char *)strstr(data + search, "endobj") - (char *)data;
obj_sz += strlen("endobj") + 1;
break;
}
else if (strstr(data, "stream"))
stream = 1;
}
clearerr(fp);
fseek(fp, start, SEEK_SET);
if (size) {
*size = obj_sz;
if (!obj_sz && data) {
free(data);
data = NULL;
}
}
if (is_stream)
*is_stream = stream;
return data;
}
static const char *get_type(FILE *fp, int obj_id, const xref_t *xref)
{
int is_stream;
char *c, *obj, *endobj;
static char buf[32];
long start;
start = ftell(fp);
if (!(obj = get_object(fp, obj_id, xref, NULL, &is_stream)) ||
is_stream ||
!(endobj = strstr(obj, "endobj")))
{
free(obj);
fseek(fp, start, SEEK_SET);
if (is_stream)
return "Stream";
else
return "Unknown";
}
/* Get the Type value (avoiding font names like Type1) */
c = obj;
while ((c = strstr(c, "/Type")) && (c < endobj))
if (isdigit(*(c + strlen("/Type"))))
{
++c;
continue;
}
else
break;
if (!c || (c && (c > endobj)))
{
free(obj);
fseek(fp, start, SEEK_SET);
return "Unknown";
}
/* Skip to first blank/whitespace */
c += strlen("/Type");
while (isspace(*c) || *c == '/')
++c;
/* 'c' should be pointing to the type name. Find the end of the name. */
size_t n_chars = 0;
const char *name_itr = c;
while ((name_itr < endobj) &&
!(isspace(*name_itr) || *name_itr == '/' || *name_itr == '>')) {
++name_itr;
++n_chars;
}
if (n_chars >= sizeof(buf))
{
free(obj);
fseek(fp, start, SEEK_SET);
return "Unknown";
}
/* Return the value by storing it in static mem. */
memcpy(buf, c, n_chars);
buf[n_chars] = '\0';
free(obj);
fseek(fp, start, SEEK_SET);
return buf;
}
static char *get_header(FILE *fp)
{
/* First 1024 bytes of doc must be header (1.7 spec pg 1102) */
char *header = safe_calloc(1024);
long start = ftell(fp);
fseek(fp, 0, SEEK_SET);
SAFE_E(fread(header, 1, 1023, fp), 1023, "Failed to load PDF header.\n");
fseek(fp, start, SEEK_SET);
return header;
}
static char *decode_text_string(const char *str, size_t str_len)
{
int idx, is_hex, is_utf16be, ascii_idx;
char *ascii, hex_buf[5] = {0};
is_hex = is_utf16be = idx = ascii_idx = 0;
/* Regular encoding */
if (str[0] == '(')
{
ascii = safe_calloc(str_len + 1);
strncpy(ascii, str, str_len + 1);
return ascii;
}
else if (str[0] == '<')
{
is_hex = 1;
++idx;
}
/* Text strings can be either PDFDocEncoding or UTF-16BE */
if (is_hex && (str_len > 5) &&
(str[idx] == 'F') && (str[idx+1] == 'E') &&
(str[idx+2] == 'F') && (str[idx+3] == 'F'))
{
is_utf16be = 1;
idx += 4;
}
else
return NULL;
/* Now decode as hex */
ascii = safe_calloc(str_len);
for ( ; idx<str_len; ++idx)
{
hex_buf[0] = str[idx++];
hex_buf[1] = str[idx++];
hex_buf[2] = str[idx++];
hex_buf[3] = str[idx];
ascii[ascii_idx++] = strtol(hex_buf, NULL, 16);
}
return ascii;
}
/* Return the offset to the beginning of the %%EOF string.
* A negative value is returned when done scanning.
*/
static int get_next_eof(FILE *fp)
{
int match, c;
const char buf[] = "%%EOF";
match = 0;
while ((c = fgetc(fp)) != EOF)
{
if (c == buf[match])
++match;
else
match = 0;
if (match == 5) /* strlen("%%EOF") */
return ftell(fp) - 5;
}
return -1;
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_4263_1 |
crossvul-cpp_data_bad_2758_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) 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"
#include "opj_common.h"
/** @defgroup T2 T2 - Implementation of a tier-2 coding */
/*@{*/
/** @name Local static functions */
/*@{*/
static void opj_t2_putcommacode(opj_bio_t *bio, OPJ_INT32 n);
static OPJ_UINT32 opj_t2_getcommacode(opj_bio_t *bio);
/**
Variable length code for signalling delta Zil (truncation point)
@param bio Bit Input/Output component
@param n delta Zil
*/
static void opj_t2_putnumpasses(opj_bio_t *bio, OPJ_UINT32 n);
static OPJ_UINT32 opj_t2_getnumpasses(opj_bio_t *bio);
/**
Encode a packet of a tile to a destination buffer
@param tileno Number of the tile encoded
@param tile Tile for which to write the packets
@param tcp Tile coding parameters
@param pi Packet identity
@param dest Destination buffer
@param p_data_written FIXME DOC
@param len Length of the destination buffer
@param cstr_info Codestream information structure
@param p_t2_mode If == THRESH_CALC In Threshold calculation ,If == FINAL_PASS Final pass
@param p_manager the user event manager
@return
*/
static OPJ_BOOL opj_t2_encode_packet(OPJ_UINT32 tileno,
opj_tcd_tile_t *tile,
opj_tcp_t *tcp,
opj_pi_iterator_t *pi,
OPJ_BYTE *dest,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 len,
opj_codestream_info_t *cstr_info,
J2K_T2_MODE p_t2_mode,
opj_event_mgr_t *p_manager);
/**
Decode a packet of a tile from a source buffer
@param t2 T2 handle
@param tile Tile for which to write the packets
@param tcp Tile coding parameters
@param pi Packet identity
@param src Source buffer
@param data_read FIXME DOC
@param max_length FIXME DOC
@param pack_info Packet information
@param p_manager the user event manager
@return FIXME DOC
*/
static OPJ_BOOL opj_t2_decode_packet(opj_t2_t* t2,
opj_tcd_tile_t *tile,
opj_tcp_t *tcp,
opj_pi_iterator_t *pi,
OPJ_BYTE *src,
OPJ_UINT32 * data_read,
OPJ_UINT32 max_length,
opj_packet_info_t *pack_info,
opj_event_mgr_t *p_manager);
static OPJ_BOOL opj_t2_skip_packet(opj_t2_t* p_t2,
opj_tcd_tile_t *p_tile,
opj_tcp_t *p_tcp,
opj_pi_iterator_t *p_pi,
OPJ_BYTE *p_src,
OPJ_UINT32 * p_data_read,
OPJ_UINT32 p_max_length,
opj_packet_info_t *p_pack_info,
opj_event_mgr_t *p_manager);
static OPJ_BOOL opj_t2_read_packet_header(opj_t2_t* p_t2,
opj_tcd_tile_t *p_tile,
opj_tcp_t *p_tcp,
opj_pi_iterator_t *p_pi,
OPJ_BOOL * p_is_data_present,
OPJ_BYTE *p_src_data,
OPJ_UINT32 * p_data_read,
OPJ_UINT32 p_max_length,
opj_packet_info_t *p_pack_info,
opj_event_mgr_t *p_manager);
static OPJ_BOOL opj_t2_read_packet_data(opj_t2_t* p_t2,
opj_tcd_tile_t *p_tile,
opj_pi_iterator_t *p_pi,
OPJ_BYTE *p_src_data,
OPJ_UINT32 * p_data_read,
OPJ_UINT32 p_max_length,
opj_packet_info_t *pack_info,
opj_event_mgr_t *p_manager);
static OPJ_BOOL opj_t2_skip_packet_data(opj_t2_t* p_t2,
opj_tcd_tile_t *p_tile,
opj_pi_iterator_t *p_pi,
OPJ_UINT32 * p_data_read,
OPJ_UINT32 p_max_length,
opj_packet_info_t *pack_info,
opj_event_mgr_t *p_manager);
/**
@param cblk
@param index
@param cblksty
@param first
*/
static OPJ_BOOL opj_t2_init_seg(opj_tcd_cblk_dec_t* cblk,
OPJ_UINT32 index,
OPJ_UINT32 cblksty,
OPJ_UINT32 first);
/*@}*/
/*@}*/
/* ----------------------------------------------------------------------- */
/* #define RESTART 0x04 */
static void opj_t2_putcommacode(opj_bio_t *bio, OPJ_INT32 n)
{
while (--n >= 0) {
opj_bio_write(bio, 1, 1);
}
opj_bio_write(bio, 0, 1);
}
static OPJ_UINT32 opj_t2_getcommacode(opj_bio_t *bio)
{
OPJ_UINT32 n = 0;
while (opj_bio_read(bio, 1)) {
++n;
}
return n;
}
static void opj_t2_putnumpasses(opj_bio_t *bio, OPJ_UINT32 n)
{
if (n == 1) {
opj_bio_write(bio, 0, 1);
} else if (n == 2) {
opj_bio_write(bio, 2, 2);
} else if (n <= 5) {
opj_bio_write(bio, 0xc | (n - 3), 4);
} else if (n <= 36) {
opj_bio_write(bio, 0x1e0 | (n - 6), 9);
} else if (n <= 164) {
opj_bio_write(bio, 0xff80 | (n - 37), 16);
}
}
static OPJ_UINT32 opj_t2_getnumpasses(opj_bio_t *bio)
{
OPJ_UINT32 n;
if (!opj_bio_read(bio, 1)) {
return 1;
}
if (!opj_bio_read(bio, 1)) {
return 2;
}
if ((n = opj_bio_read(bio, 2)) != 3) {
return (3 + n);
}
if ((n = opj_bio_read(bio, 5)) != 31) {
return (6 + n);
}
return (37 + opj_bio_read(bio, 7));
}
/* ----------------------------------------------------------------------- */
OPJ_BOOL opj_t2_encode_packets(opj_t2_t* p_t2,
OPJ_UINT32 p_tile_no,
opj_tcd_tile_t *p_tile,
OPJ_UINT32 p_maxlayers,
OPJ_BYTE *p_dest,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_max_len,
opj_codestream_info_t *cstr_info,
OPJ_UINT32 p_tp_num,
OPJ_INT32 p_tp_pos,
OPJ_UINT32 p_pino,
J2K_T2_MODE p_t2_mode,
opj_event_mgr_t *p_manager)
{
OPJ_BYTE *l_current_data = p_dest;
OPJ_UINT32 l_nb_bytes = 0;
OPJ_UINT32 compno;
OPJ_UINT32 poc;
opj_pi_iterator_t *l_pi = 00;
opj_pi_iterator_t *l_current_pi = 00;
opj_image_t *l_image = p_t2->image;
opj_cp_t *l_cp = p_t2->cp;
opj_tcp_t *l_tcp = &l_cp->tcps[p_tile_no];
OPJ_UINT32 pocno = (l_cp->rsiz == OPJ_PROFILE_CINEMA_4K) ? 2 : 1;
OPJ_UINT32 l_max_comp = l_cp->m_specific_param.m_enc.m_max_comp_size > 0 ?
l_image->numcomps : 1;
OPJ_UINT32 l_nb_pocs = l_tcp->numpocs + 1;
l_pi = opj_pi_initialise_encode(l_image, l_cp, p_tile_no, p_t2_mode);
if (!l_pi) {
return OPJ_FALSE;
}
* p_data_written = 0;
if (p_t2_mode == THRESH_CALC) { /* Calculating threshold */
l_current_pi = l_pi;
for (compno = 0; compno < l_max_comp; ++compno) {
OPJ_UINT32 l_comp_len = 0;
l_current_pi = l_pi;
for (poc = 0; poc < pocno ; ++poc) {
OPJ_UINT32 l_tp_num = compno;
/* TODO MSD : check why this function cannot fail (cf. v1) */
opj_pi_create_encode(l_pi, l_cp, p_tile_no, poc, l_tp_num, p_tp_pos, p_t2_mode);
if (l_current_pi->poc.prg == OPJ_PROG_UNKNOWN) {
/* TODO ADE : add an error */
opj_pi_destroy(l_pi, l_nb_pocs);
return OPJ_FALSE;
}
while (opj_pi_next(l_current_pi)) {
if (l_current_pi->layno < p_maxlayers) {
l_nb_bytes = 0;
if (! opj_t2_encode_packet(p_tile_no, p_tile, l_tcp, l_current_pi,
l_current_data, &l_nb_bytes,
p_max_len, cstr_info,
p_t2_mode,
p_manager)) {
opj_pi_destroy(l_pi, l_nb_pocs);
return OPJ_FALSE;
}
l_comp_len += l_nb_bytes;
l_current_data += l_nb_bytes;
p_max_len -= l_nb_bytes;
* p_data_written += l_nb_bytes;
}
}
if (l_cp->m_specific_param.m_enc.m_max_comp_size) {
if (l_comp_len > l_cp->m_specific_param.m_enc.m_max_comp_size) {
opj_pi_destroy(l_pi, l_nb_pocs);
return OPJ_FALSE;
}
}
++l_current_pi;
}
}
} else { /* t2_mode == FINAL_PASS */
opj_pi_create_encode(l_pi, l_cp, p_tile_no, p_pino, p_tp_num, p_tp_pos,
p_t2_mode);
l_current_pi = &l_pi[p_pino];
if (l_current_pi->poc.prg == OPJ_PROG_UNKNOWN) {
/* TODO ADE : add an error */
opj_pi_destroy(l_pi, l_nb_pocs);
return OPJ_FALSE;
}
while (opj_pi_next(l_current_pi)) {
if (l_current_pi->layno < p_maxlayers) {
l_nb_bytes = 0;
if (! opj_t2_encode_packet(p_tile_no, p_tile, l_tcp, l_current_pi,
l_current_data, &l_nb_bytes, p_max_len,
cstr_info, p_t2_mode, p_manager)) {
opj_pi_destroy(l_pi, l_nb_pocs);
return OPJ_FALSE;
}
l_current_data += l_nb_bytes;
p_max_len -= l_nb_bytes;
* p_data_written += l_nb_bytes;
/* INDEX >> */
if (cstr_info) {
if (cstr_info->index_write) {
opj_tile_info_t *info_TL = &cstr_info->tile[p_tile_no];
opj_packet_info_t *info_PK = &info_TL->packet[cstr_info->packno];
if (!cstr_info->packno) {
info_PK->start_pos = info_TL->end_header + 1;
} else {
info_PK->start_pos = ((l_cp->m_specific_param.m_enc.m_tp_on | l_tcp->POC) &&
info_PK->start_pos) ? info_PK->start_pos : info_TL->packet[cstr_info->packno -
1].end_pos + 1;
}
info_PK->end_pos = info_PK->start_pos + l_nb_bytes - 1;
info_PK->end_ph_pos += info_PK->start_pos -
1; /* End of packet header which now only represents the distance
to start of packet is incremented by value of start of packet*/
}
cstr_info->packno++;
}
/* << INDEX */
++p_tile->packno;
}
}
}
opj_pi_destroy(l_pi, l_nb_pocs);
return OPJ_TRUE;
}
/* see issue 80 */
#if 0
#define JAS_FPRINTF fprintf
#else
/* issue 290 */
static void opj_null_jas_fprintf(FILE* file, const char * format, ...)
{
(void)file;
(void)format;
}
#define JAS_FPRINTF opj_null_jas_fprintf
#endif
OPJ_BOOL opj_t2_decode_packets(opj_t2_t *p_t2,
OPJ_UINT32 p_tile_no,
opj_tcd_tile_t *p_tile,
OPJ_BYTE *p_src,
OPJ_UINT32 * p_data_read,
OPJ_UINT32 p_max_len,
opj_codestream_index_t *p_cstr_index,
opj_event_mgr_t *p_manager)
{
OPJ_BYTE *l_current_data = p_src;
opj_pi_iterator_t *l_pi = 00;
OPJ_UINT32 pino;
opj_image_t *l_image = p_t2->image;
opj_cp_t *l_cp = p_t2->cp;
opj_tcp_t *l_tcp = &(p_t2->cp->tcps[p_tile_no]);
OPJ_UINT32 l_nb_bytes_read;
OPJ_UINT32 l_nb_pocs = l_tcp->numpocs + 1;
opj_pi_iterator_t *l_current_pi = 00;
#ifdef TODO_MSD
OPJ_UINT32 curtp = 0;
OPJ_UINT32 tp_start_packno;
#endif
opj_packet_info_t *l_pack_info = 00;
opj_image_comp_t* l_img_comp = 00;
OPJ_ARG_NOT_USED(p_cstr_index);
#ifdef TODO_MSD
if (p_cstr_index) {
l_pack_info = p_cstr_index->tile_index[p_tile_no].packet;
}
#endif
/* create a packet iterator */
l_pi = opj_pi_create_decode(l_image, l_cp, p_tile_no);
if (!l_pi) {
return OPJ_FALSE;
}
l_current_pi = l_pi;
for (pino = 0; pino <= l_tcp->numpocs; ++pino) {
/* if the resolution needed is too low, one dim of the tilec could be equal to zero
* and no packets are used to decode this resolution and
* l_current_pi->resno is always >= p_tile->comps[l_current_pi->compno].minimum_num_resolutions
* and no l_img_comp->resno_decoded are computed
*/
OPJ_BOOL* first_pass_failed = NULL;
if (l_current_pi->poc.prg == OPJ_PROG_UNKNOWN) {
/* TODO ADE : add an error */
opj_pi_destroy(l_pi, l_nb_pocs);
return OPJ_FALSE;
}
first_pass_failed = (OPJ_BOOL*)opj_malloc(l_image->numcomps * sizeof(OPJ_BOOL));
if (!first_pass_failed) {
opj_pi_destroy(l_pi, l_nb_pocs);
return OPJ_FALSE;
}
memset(first_pass_failed, OPJ_TRUE, l_image->numcomps * sizeof(OPJ_BOOL));
while (opj_pi_next(l_current_pi)) {
JAS_FPRINTF(stderr,
"packet offset=00000166 prg=%d cmptno=%02d rlvlno=%02d prcno=%03d lyrno=%02d\n\n",
l_current_pi->poc.prg1, l_current_pi->compno, l_current_pi->resno,
l_current_pi->precno, l_current_pi->layno);
if (l_tcp->num_layers_to_decode > l_current_pi->layno
&& l_current_pi->resno <
p_tile->comps[l_current_pi->compno].minimum_num_resolutions) {
l_nb_bytes_read = 0;
first_pass_failed[l_current_pi->compno] = OPJ_FALSE;
if (! opj_t2_decode_packet(p_t2, p_tile, l_tcp, l_current_pi, l_current_data,
&l_nb_bytes_read, p_max_len, l_pack_info, p_manager)) {
opj_pi_destroy(l_pi, l_nb_pocs);
opj_free(first_pass_failed);
return OPJ_FALSE;
}
l_img_comp = &(l_image->comps[l_current_pi->compno]);
l_img_comp->resno_decoded = opj_uint_max(l_current_pi->resno,
l_img_comp->resno_decoded);
} else {
l_nb_bytes_read = 0;
if (! opj_t2_skip_packet(p_t2, p_tile, l_tcp, l_current_pi, l_current_data,
&l_nb_bytes_read, p_max_len, l_pack_info, p_manager)) {
opj_pi_destroy(l_pi, l_nb_pocs);
opj_free(first_pass_failed);
return OPJ_FALSE;
}
}
if (first_pass_failed[l_current_pi->compno]) {
l_img_comp = &(l_image->comps[l_current_pi->compno]);
if (l_img_comp->resno_decoded == 0) {
l_img_comp->resno_decoded =
p_tile->comps[l_current_pi->compno].minimum_num_resolutions - 1;
}
}
l_current_data += l_nb_bytes_read;
p_max_len -= l_nb_bytes_read;
/* INDEX >> */
#ifdef TODO_MSD
if (p_cstr_info) {
opj_tile_info_v2_t *info_TL = &p_cstr_info->tile[p_tile_no];
opj_packet_info_t *info_PK = &info_TL->packet[p_cstr_info->packno];
tp_start_packno = 0;
if (!p_cstr_info->packno) {
info_PK->start_pos = info_TL->end_header + 1;
} else if (info_TL->packet[p_cstr_info->packno - 1].end_pos >=
(OPJ_INT32)
p_cstr_info->tile[p_tile_no].tp[curtp].tp_end_pos) { /* New tile part */
info_TL->tp[curtp].tp_numpacks = p_cstr_info->packno -
tp_start_packno; /* Number of packets in previous tile-part */
tp_start_packno = p_cstr_info->packno;
curtp++;
info_PK->start_pos = p_cstr_info->tile[p_tile_no].tp[curtp].tp_end_header + 1;
} else {
info_PK->start_pos = (l_cp->m_specific_param.m_enc.m_tp_on &&
info_PK->start_pos) ? info_PK->start_pos : info_TL->packet[p_cstr_info->packno -
1].end_pos + 1;
}
info_PK->end_pos = info_PK->start_pos + l_nb_bytes_read - 1;
info_PK->end_ph_pos += info_PK->start_pos -
1; /* End of packet header which now only represents the distance */
++p_cstr_info->packno;
}
#endif
/* << INDEX */
}
++l_current_pi;
opj_free(first_pass_failed);
}
/* INDEX >> */
#ifdef TODO_MSD
if
(p_cstr_info) {
p_cstr_info->tile[p_tile_no].tp[curtp].tp_numpacks = p_cstr_info->packno -
tp_start_packno; /* Number of packets in last tile-part */
}
#endif
/* << INDEX */
/* don't forget to release pi */
opj_pi_destroy(l_pi, l_nb_pocs);
*p_data_read = (OPJ_UINT32)(l_current_data - p_src);
return OPJ_TRUE;
}
/* ----------------------------------------------------------------------- */
/**
* Creates a Tier 2 handle
*
* @param p_image Source or destination image
* @param p_cp Image coding parameters.
* @return a new T2 handle if successful, NULL otherwise.
*/
opj_t2_t* opj_t2_create(opj_image_t *p_image, opj_cp_t *p_cp)
{
/* create the t2 structure */
opj_t2_t *l_t2 = (opj_t2_t*)opj_calloc(1, sizeof(opj_t2_t));
if (!l_t2) {
return NULL;
}
l_t2->image = p_image;
l_t2->cp = p_cp;
return l_t2;
}
void opj_t2_destroy(opj_t2_t *t2)
{
if (t2) {
opj_free(t2);
}
}
static OPJ_BOOL opj_t2_decode_packet(opj_t2_t* p_t2,
opj_tcd_tile_t *p_tile,
opj_tcp_t *p_tcp,
opj_pi_iterator_t *p_pi,
OPJ_BYTE *p_src,
OPJ_UINT32 * p_data_read,
OPJ_UINT32 p_max_length,
opj_packet_info_t *p_pack_info,
opj_event_mgr_t *p_manager)
{
OPJ_BOOL l_read_data;
OPJ_UINT32 l_nb_bytes_read = 0;
OPJ_UINT32 l_nb_total_bytes_read = 0;
*p_data_read = 0;
if (! opj_t2_read_packet_header(p_t2, p_tile, p_tcp, p_pi, &l_read_data, p_src,
&l_nb_bytes_read, p_max_length, p_pack_info, p_manager)) {
return OPJ_FALSE;
}
p_src += l_nb_bytes_read;
l_nb_total_bytes_read += l_nb_bytes_read;
p_max_length -= l_nb_bytes_read;
/* we should read data for the packet */
if (l_read_data) {
l_nb_bytes_read = 0;
if (! opj_t2_read_packet_data(p_t2, p_tile, p_pi, p_src, &l_nb_bytes_read,
p_max_length, p_pack_info, p_manager)) {
return OPJ_FALSE;
}
l_nb_total_bytes_read += l_nb_bytes_read;
}
*p_data_read = l_nb_total_bytes_read;
return OPJ_TRUE;
}
static OPJ_BOOL opj_t2_encode_packet(OPJ_UINT32 tileno,
opj_tcd_tile_t * tile,
opj_tcp_t * tcp,
opj_pi_iterator_t *pi,
OPJ_BYTE *dest,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 length,
opj_codestream_info_t *cstr_info,
J2K_T2_MODE p_t2_mode,
opj_event_mgr_t *p_manager)
{
OPJ_UINT32 bandno, cblkno;
OPJ_BYTE* c = dest;
OPJ_UINT32 l_nb_bytes;
OPJ_UINT32 compno = pi->compno; /* component value */
OPJ_UINT32 resno = pi->resno; /* resolution level value */
OPJ_UINT32 precno = pi->precno; /* precinct value */
OPJ_UINT32 layno = pi->layno; /* quality layer value */
OPJ_UINT32 l_nb_blocks;
opj_tcd_band_t *band = 00;
opj_tcd_cblk_enc_t* cblk = 00;
opj_tcd_pass_t *pass = 00;
opj_tcd_tilecomp_t *tilec = &tile->comps[compno];
opj_tcd_resolution_t *res = &tilec->resolutions[resno];
opj_bio_t *bio = 00; /* BIO component */
OPJ_BOOL packet_empty = OPJ_TRUE;
/* <SOP 0xff91> */
if (tcp->csty & J2K_CP_CSTY_SOP) {
c[0] = 255;
c[1] = 145;
c[2] = 0;
c[3] = 4;
#if 0
c[4] = (tile->packno % 65536) / 256;
c[5] = (tile->packno % 65536) % 256;
#else
c[4] = (tile->packno >> 8) & 0xff; /* packno is uint32_t */
c[5] = tile->packno & 0xff;
#endif
c += 6;
length -= 6;
}
/* </SOP> */
if (!layno) {
band = res->bands;
for (bandno = 0; bandno < res->numbands; ++bandno, ++band) {
opj_tcd_precinct_t *prc;
/* Skip empty bands */
if (opj_tcd_is_band_empty(band)) {
continue;
}
prc = &band->precincts[precno];
opj_tgt_reset(prc->incltree);
opj_tgt_reset(prc->imsbtree);
l_nb_blocks = prc->cw * prc->ch;
for (cblkno = 0; cblkno < l_nb_blocks; ++cblkno) {
cblk = &prc->cblks.enc[cblkno];
cblk->numpasses = 0;
opj_tgt_setvalue(prc->imsbtree, cblkno, band->numbps - (OPJ_INT32)cblk->numbps);
}
}
}
bio = opj_bio_create();
if (!bio) {
/* FIXME event manager error callback */
return OPJ_FALSE;
}
opj_bio_init_enc(bio, c, length);
/* Check if the packet is empty */
/* Note: we could also skip that step and always write a packet header */
band = res->bands;
for (bandno = 0; bandno < res->numbands; ++bandno, ++band) {
opj_tcd_precinct_t *prc;
/* Skip empty bands */
if (opj_tcd_is_band_empty(band)) {
continue;
}
prc = &band->precincts[precno];
l_nb_blocks = prc->cw * prc->ch;
cblk = prc->cblks.enc;
for (cblkno = 0; cblkno < l_nb_blocks; cblkno++, ++cblk) {
opj_tcd_layer_t *layer = &cblk->layers[layno];
/* if cblk not included, go to the next cblk */
if (!layer->numpasses) {
continue;
}
packet_empty = OPJ_FALSE;
break;
}
if (!packet_empty) {
break;
}
}
opj_bio_write(bio, packet_empty ? 0 : 1, 1); /* Empty header bit */
/* Writing Packet header */
band = res->bands;
for (bandno = 0; !packet_empty &&
bandno < res->numbands; ++bandno, ++band) {
opj_tcd_precinct_t *prc;
/* Skip empty bands */
if (opj_tcd_is_band_empty(band)) {
continue;
}
prc = &band->precincts[precno];
l_nb_blocks = prc->cw * prc->ch;
cblk = prc->cblks.enc;
for (cblkno = 0; cblkno < l_nb_blocks; ++cblkno) {
opj_tcd_layer_t *layer = &cblk->layers[layno];
if (!cblk->numpasses && layer->numpasses) {
opj_tgt_setvalue(prc->incltree, cblkno, (OPJ_INT32)layno);
}
++cblk;
}
cblk = prc->cblks.enc;
for (cblkno = 0; cblkno < l_nb_blocks; cblkno++) {
opj_tcd_layer_t *layer = &cblk->layers[layno];
OPJ_UINT32 increment = 0;
OPJ_UINT32 nump = 0;
OPJ_UINT32 len = 0, passno;
OPJ_UINT32 l_nb_passes;
/* cblk inclusion bits */
if (!cblk->numpasses) {
opj_tgt_encode(bio, prc->incltree, cblkno, (OPJ_INT32)(layno + 1));
} else {
opj_bio_write(bio, layer->numpasses != 0, 1);
}
/* if cblk not included, go to the next cblk */
if (!layer->numpasses) {
++cblk;
continue;
}
/* if first instance of cblk --> zero bit-planes information */
if (!cblk->numpasses) {
cblk->numlenbits = 3;
opj_tgt_encode(bio, prc->imsbtree, cblkno, 999);
}
/* number of coding passes included */
opj_t2_putnumpasses(bio, layer->numpasses);
l_nb_passes = cblk->numpasses + layer->numpasses;
pass = cblk->passes + cblk->numpasses;
/* computation of the increase of the length indicator and insertion in the header */
for (passno = cblk->numpasses; passno < l_nb_passes; ++passno) {
++nump;
len += pass->len;
if (pass->term || passno == (cblk->numpasses + layer->numpasses) - 1) {
increment = (OPJ_UINT32)opj_int_max((OPJ_INT32)increment,
opj_int_floorlog2((OPJ_INT32)len) + 1
- ((OPJ_INT32)cblk->numlenbits + opj_int_floorlog2((OPJ_INT32)nump)));
len = 0;
nump = 0;
}
++pass;
}
opj_t2_putcommacode(bio, (OPJ_INT32)increment);
/* computation of the new Length indicator */
cblk->numlenbits += increment;
pass = cblk->passes + cblk->numpasses;
/* insertion of the codeword segment length */
for (passno = cblk->numpasses; passno < l_nb_passes; ++passno) {
nump++;
len += pass->len;
if (pass->term || passno == (cblk->numpasses + layer->numpasses) - 1) {
opj_bio_write(bio, (OPJ_UINT32)len,
cblk->numlenbits + (OPJ_UINT32)opj_int_floorlog2((OPJ_INT32)nump));
len = 0;
nump = 0;
}
++pass;
}
++cblk;
}
}
if (!opj_bio_flush(bio)) {
opj_bio_destroy(bio);
return OPJ_FALSE; /* modified to eliminate longjmp !! */
}
l_nb_bytes = (OPJ_UINT32)opj_bio_numbytes(bio);
c += l_nb_bytes;
length -= l_nb_bytes;
opj_bio_destroy(bio);
/* <EPH 0xff92> */
if (tcp->csty & J2K_CP_CSTY_EPH) {
c[0] = 255;
c[1] = 146;
c += 2;
length -= 2;
}
/* </EPH> */
/* << INDEX */
/* End of packet header position. Currently only represents the distance to start of packet
Will be updated later by incrementing with packet start value*/
if (cstr_info && cstr_info->index_write) {
opj_packet_info_t *info_PK = &cstr_info->tile[tileno].packet[cstr_info->packno];
info_PK->end_ph_pos = (OPJ_INT32)(c - dest);
}
/* INDEX >> */
/* Writing the packet body */
band = res->bands;
for (bandno = 0; !packet_empty && bandno < res->numbands; bandno++, ++band) {
opj_tcd_precinct_t *prc;
/* Skip empty bands */
if (opj_tcd_is_band_empty(band)) {
continue;
}
prc = &band->precincts[precno];
l_nb_blocks = prc->cw * prc->ch;
cblk = prc->cblks.enc;
for (cblkno = 0; cblkno < l_nb_blocks; ++cblkno) {
opj_tcd_layer_t *layer = &cblk->layers[layno];
if (!layer->numpasses) {
++cblk;
continue;
}
if (layer->len > length) {
if (p_t2_mode == FINAL_PASS) {
opj_event_msg(p_manager, EVT_ERROR,
"opj_t2_encode_packet(): only %u bytes remaining in "
"output buffer. %u needed.\n",
length, layer->len);
}
return OPJ_FALSE;
}
memcpy(c, layer->data, layer->len);
cblk->numpasses += layer->numpasses;
c += layer->len;
length -= layer->len;
/* << INDEX */
if (cstr_info && cstr_info->index_write) {
opj_packet_info_t *info_PK = &cstr_info->tile[tileno].packet[cstr_info->packno];
info_PK->disto += layer->disto;
if (cstr_info->D_max < info_PK->disto) {
cstr_info->D_max = info_PK->disto;
}
}
++cblk;
/* INDEX >> */
}
}
assert(c >= dest);
* p_data_written += (OPJ_UINT32)(c - dest);
return OPJ_TRUE;
}
static OPJ_BOOL opj_t2_skip_packet(opj_t2_t* p_t2,
opj_tcd_tile_t *p_tile,
opj_tcp_t *p_tcp,
opj_pi_iterator_t *p_pi,
OPJ_BYTE *p_src,
OPJ_UINT32 * p_data_read,
OPJ_UINT32 p_max_length,
opj_packet_info_t *p_pack_info,
opj_event_mgr_t *p_manager)
{
OPJ_BOOL l_read_data;
OPJ_UINT32 l_nb_bytes_read = 0;
OPJ_UINT32 l_nb_total_bytes_read = 0;
*p_data_read = 0;
if (! opj_t2_read_packet_header(p_t2, p_tile, p_tcp, p_pi, &l_read_data, p_src,
&l_nb_bytes_read, p_max_length, p_pack_info, p_manager)) {
return OPJ_FALSE;
}
p_src += l_nb_bytes_read;
l_nb_total_bytes_read += l_nb_bytes_read;
p_max_length -= l_nb_bytes_read;
/* we should read data for the packet */
if (l_read_data) {
l_nb_bytes_read = 0;
if (! opj_t2_skip_packet_data(p_t2, p_tile, p_pi, &l_nb_bytes_read,
p_max_length, p_pack_info, p_manager)) {
return OPJ_FALSE;
}
l_nb_total_bytes_read += l_nb_bytes_read;
}
*p_data_read = l_nb_total_bytes_read;
return OPJ_TRUE;
}
static OPJ_BOOL opj_t2_read_packet_header(opj_t2_t* p_t2,
opj_tcd_tile_t *p_tile,
opj_tcp_t *p_tcp,
opj_pi_iterator_t *p_pi,
OPJ_BOOL * p_is_data_present,
OPJ_BYTE *p_src_data,
OPJ_UINT32 * p_data_read,
OPJ_UINT32 p_max_length,
opj_packet_info_t *p_pack_info,
opj_event_mgr_t *p_manager)
{
/* loop */
OPJ_UINT32 bandno, cblkno;
OPJ_UINT32 l_nb_code_blocks;
OPJ_UINT32 l_remaining_length;
OPJ_UINT32 l_header_length;
OPJ_UINT32 * l_modified_length_ptr = 00;
OPJ_BYTE *l_current_data = p_src_data;
opj_cp_t *l_cp = p_t2->cp;
opj_bio_t *l_bio = 00; /* BIO component */
opj_tcd_band_t *l_band = 00;
opj_tcd_cblk_dec_t* l_cblk = 00;
opj_tcd_resolution_t* l_res =
&p_tile->comps[p_pi->compno].resolutions[p_pi->resno];
OPJ_BYTE *l_header_data = 00;
OPJ_BYTE **l_header_data_start = 00;
OPJ_UINT32 l_present;
if (p_pi->layno == 0) {
l_band = l_res->bands;
/* reset tagtrees */
for (bandno = 0; bandno < l_res->numbands; ++bandno) {
if (!opj_tcd_is_band_empty(l_band)) {
opj_tcd_precinct_t *l_prc = &l_band->precincts[p_pi->precno];
if (!(p_pi->precno < (l_band->precincts_data_size / sizeof(
opj_tcd_precinct_t)))) {
opj_event_msg(p_manager, EVT_ERROR, "Invalid precinct\n");
return OPJ_FALSE;
}
opj_tgt_reset(l_prc->incltree);
opj_tgt_reset(l_prc->imsbtree);
l_cblk = l_prc->cblks.dec;
l_nb_code_blocks = l_prc->cw * l_prc->ch;
for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) {
l_cblk->numsegs = 0;
l_cblk->real_num_segs = 0;
++l_cblk;
}
}
++l_band;
}
}
/* SOP markers */
if (p_tcp->csty & J2K_CP_CSTY_SOP) {
if (p_max_length < 6) {
opj_event_msg(p_manager, EVT_WARNING,
"Not enough space for expected SOP marker\n");
} else if ((*l_current_data) != 0xff || (*(l_current_data + 1) != 0x91)) {
opj_event_msg(p_manager, EVT_WARNING, "Expected SOP marker\n");
} else {
l_current_data += 6;
}
/** TODO : check the Nsop value */
}
/*
When the marker PPT/PPM is used the packet header are store in PPT/PPM marker
This part deal with this caracteristic
step 1: Read packet header in the saved structure
step 2: Return to codestream for decoding
*/
l_bio = opj_bio_create();
if (! l_bio) {
return OPJ_FALSE;
}
if (l_cp->ppm == 1) { /* PPM */
l_header_data_start = &l_cp->ppm_data;
l_header_data = *l_header_data_start;
l_modified_length_ptr = &(l_cp->ppm_len);
} else if (p_tcp->ppt == 1) { /* PPT */
l_header_data_start = &(p_tcp->ppt_data);
l_header_data = *l_header_data_start;
l_modified_length_ptr = &(p_tcp->ppt_len);
} else { /* Normal Case */
l_header_data_start = &(l_current_data);
l_header_data = *l_header_data_start;
l_remaining_length = (OPJ_UINT32)(p_src_data + p_max_length - l_header_data);
l_modified_length_ptr = &(l_remaining_length);
}
opj_bio_init_dec(l_bio, l_header_data, *l_modified_length_ptr);
l_present = opj_bio_read(l_bio, 1);
JAS_FPRINTF(stderr, "present=%d \n", l_present);
if (!l_present) {
/* TODO MSD: no test to control the output of this function*/
opj_bio_inalign(l_bio);
l_header_data += opj_bio_numbytes(l_bio);
opj_bio_destroy(l_bio);
/* EPH markers */
if (p_tcp->csty & J2K_CP_CSTY_EPH) {
if ((*l_modified_length_ptr - (OPJ_UINT32)(l_header_data -
*l_header_data_start)) < 2U) {
opj_event_msg(p_manager, EVT_WARNING,
"Not enough space for expected EPH marker\n");
} else if ((*l_header_data) != 0xff || (*(l_header_data + 1) != 0x92)) {
opj_event_msg(p_manager, EVT_WARNING, "Expected EPH marker\n");
} else {
l_header_data += 2;
}
}
l_header_length = (OPJ_UINT32)(l_header_data - *l_header_data_start);
*l_modified_length_ptr -= l_header_length;
*l_header_data_start += l_header_length;
/* << INDEX */
/* End of packet header position. Currently only represents the distance to start of packet
Will be updated later by incrementing with packet start value */
if (p_pack_info) {
p_pack_info->end_ph_pos = (OPJ_INT32)(l_current_data - p_src_data);
}
/* INDEX >> */
* p_is_data_present = OPJ_FALSE;
*p_data_read = (OPJ_UINT32)(l_current_data - p_src_data);
return OPJ_TRUE;
}
l_band = l_res->bands;
for (bandno = 0; bandno < l_res->numbands; ++bandno, ++l_band) {
opj_tcd_precinct_t *l_prc = &(l_band->precincts[p_pi->precno]);
if (opj_tcd_is_band_empty(l_band)) {
continue;
}
l_nb_code_blocks = l_prc->cw * l_prc->ch;
l_cblk = l_prc->cblks.dec;
for (cblkno = 0; cblkno < l_nb_code_blocks; cblkno++) {
OPJ_UINT32 l_included, l_increment, l_segno;
OPJ_INT32 n;
/* if cblk not yet included before --> inclusion tagtree */
if (!l_cblk->numsegs) {
l_included = opj_tgt_decode(l_bio, l_prc->incltree, cblkno,
(OPJ_INT32)(p_pi->layno + 1));
/* else one bit */
} else {
l_included = opj_bio_read(l_bio, 1);
}
/* if cblk not included */
if (!l_included) {
l_cblk->numnewpasses = 0;
++l_cblk;
JAS_FPRINTF(stderr, "included=%d \n", l_included);
continue;
}
/* if cblk not yet included --> zero-bitplane tagtree */
if (!l_cblk->numsegs) {
OPJ_UINT32 i = 0;
while (!opj_tgt_decode(l_bio, l_prc->imsbtree, cblkno, (OPJ_INT32)i)) {
++i;
}
l_cblk->numbps = (OPJ_UINT32)l_band->numbps + 1 - i;
l_cblk->numlenbits = 3;
}
/* number of coding passes */
l_cblk->numnewpasses = opj_t2_getnumpasses(l_bio);
l_increment = opj_t2_getcommacode(l_bio);
/* length indicator increment */
l_cblk->numlenbits += l_increment;
l_segno = 0;
if (!l_cblk->numsegs) {
if (! opj_t2_init_seg(l_cblk, l_segno, p_tcp->tccps[p_pi->compno].cblksty, 1)) {
opj_bio_destroy(l_bio);
return OPJ_FALSE;
}
} else {
l_segno = l_cblk->numsegs - 1;
if (l_cblk->segs[l_segno].numpasses == l_cblk->segs[l_segno].maxpasses) {
++l_segno;
if (! opj_t2_init_seg(l_cblk, l_segno, p_tcp->tccps[p_pi->compno].cblksty, 0)) {
opj_bio_destroy(l_bio);
return OPJ_FALSE;
}
}
}
n = (OPJ_INT32)l_cblk->numnewpasses;
do {
OPJ_UINT32 bit_number;
l_cblk->segs[l_segno].numnewpasses = (OPJ_UINT32)opj_int_min((OPJ_INT32)(
l_cblk->segs[l_segno].maxpasses - l_cblk->segs[l_segno].numpasses), n);
bit_number = l_cblk->numlenbits + opj_uint_floorlog2(
l_cblk->segs[l_segno].numnewpasses);
if (bit_number > 32) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid bit number %d in opj_t2_read_packet_header()\n",
bit_number);
opj_bio_destroy(l_bio);
return OPJ_FALSE;
}
l_cblk->segs[l_segno].newlen = opj_bio_read(l_bio, bit_number);
JAS_FPRINTF(stderr, "included=%d numnewpasses=%d increment=%d len=%d \n",
l_included, l_cblk->segs[l_segno].numnewpasses, l_increment,
l_cblk->segs[l_segno].newlen);
n -= (OPJ_INT32)l_cblk->segs[l_segno].numnewpasses;
if (n > 0) {
++l_segno;
if (! opj_t2_init_seg(l_cblk, l_segno, p_tcp->tccps[p_pi->compno].cblksty, 0)) {
opj_bio_destroy(l_bio);
return OPJ_FALSE;
}
}
} while (n > 0);
++l_cblk;
}
}
if (!opj_bio_inalign(l_bio)) {
opj_bio_destroy(l_bio);
return OPJ_FALSE;
}
l_header_data += opj_bio_numbytes(l_bio);
opj_bio_destroy(l_bio);
/* EPH markers */
if (p_tcp->csty & J2K_CP_CSTY_EPH) {
if ((*l_modified_length_ptr - (OPJ_UINT32)(l_header_data -
*l_header_data_start)) < 2U) {
opj_event_msg(p_manager, EVT_WARNING,
"Not enough space for expected EPH marker\n");
} else if ((*l_header_data) != 0xff || (*(l_header_data + 1) != 0x92)) {
opj_event_msg(p_manager, EVT_WARNING, "Expected EPH marker\n");
} else {
l_header_data += 2;
}
}
l_header_length = (OPJ_UINT32)(l_header_data - *l_header_data_start);
JAS_FPRINTF(stderr, "hdrlen=%d \n", l_header_length);
JAS_FPRINTF(stderr, "packet body\n");
*l_modified_length_ptr -= l_header_length;
*l_header_data_start += l_header_length;
/* << INDEX */
/* End of packet header position. Currently only represents the distance to start of packet
Will be updated later by incrementing with packet start value */
if (p_pack_info) {
p_pack_info->end_ph_pos = (OPJ_INT32)(l_current_data - p_src_data);
}
/* INDEX >> */
*p_is_data_present = OPJ_TRUE;
*p_data_read = (OPJ_UINT32)(l_current_data - p_src_data);
return OPJ_TRUE;
}
static OPJ_BOOL opj_t2_read_packet_data(opj_t2_t* p_t2,
opj_tcd_tile_t *p_tile,
opj_pi_iterator_t *p_pi,
OPJ_BYTE *p_src_data,
OPJ_UINT32 * p_data_read,
OPJ_UINT32 p_max_length,
opj_packet_info_t *pack_info,
opj_event_mgr_t* p_manager)
{
OPJ_UINT32 bandno, cblkno;
OPJ_UINT32 l_nb_code_blocks;
OPJ_BYTE *l_current_data = p_src_data;
opj_tcd_band_t *l_band = 00;
opj_tcd_cblk_dec_t* l_cblk = 00;
opj_tcd_resolution_t* l_res =
&p_tile->comps[p_pi->compno].resolutions[p_pi->resno];
OPJ_ARG_NOT_USED(p_t2);
OPJ_ARG_NOT_USED(pack_info);
l_band = l_res->bands;
for (bandno = 0; bandno < l_res->numbands; ++bandno) {
opj_tcd_precinct_t *l_prc = &l_band->precincts[p_pi->precno];
if ((l_band->x1 - l_band->x0 == 0) || (l_band->y1 - l_band->y0 == 0)) {
++l_band;
continue;
}
l_nb_code_blocks = l_prc->cw * l_prc->ch;
l_cblk = l_prc->cblks.dec;
for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) {
opj_tcd_seg_t *l_seg = 00;
if (!l_cblk->numnewpasses) {
/* nothing to do */
++l_cblk;
continue;
}
if (!l_cblk->numsegs) {
l_seg = l_cblk->segs;
++l_cblk->numsegs;
} else {
l_seg = &l_cblk->segs[l_cblk->numsegs - 1];
if (l_seg->numpasses == l_seg->maxpasses) {
++l_seg;
++l_cblk->numsegs;
}
}
do {
/* Check possible overflow (on l_current_data only, assumes input args already checked) then size */
if ((((OPJ_SIZE_T)l_current_data + (OPJ_SIZE_T)l_seg->newlen) <
(OPJ_SIZE_T)l_current_data) ||
(l_current_data + l_seg->newlen > p_src_data + p_max_length)) {
opj_event_msg(p_manager, EVT_ERROR,
"read: segment too long (%d) with max (%d) for codeblock %d (p=%d, b=%d, r=%d, c=%d)\n",
l_seg->newlen, p_max_length, cblkno, p_pi->precno, bandno, p_pi->resno,
p_pi->compno);
return OPJ_FALSE;
}
#ifdef USE_JPWL
/* we need here a j2k handle to verify if making a check to
the validity of cblocks parameters is selected from user (-W) */
/* let's check that we are not exceeding */
if ((l_cblk->len + l_seg->newlen) > 8192) {
opj_event_msg(p_manager, EVT_WARNING,
"JPWL: segment too long (%d) for codeblock %d (p=%d, b=%d, r=%d, c=%d)\n",
l_seg->newlen, cblkno, p_pi->precno, bandno, p_pi->resno, p_pi->compno);
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
l_seg->newlen = 8192 - l_cblk->len;
opj_event_msg(p_manager, EVT_WARNING, " - truncating segment to %d\n",
l_seg->newlen);
break;
};
#endif /* USE_JPWL */
if (l_cblk->numchunks == l_cblk->numchunksalloc) {
OPJ_UINT32 l_numchunksalloc = l_cblk->numchunksalloc * 2 + 1;
opj_tcd_seg_data_chunk_t* l_chunks =
(opj_tcd_seg_data_chunk_t*)opj_realloc(l_cblk->chunks,
l_numchunksalloc * sizeof(opj_tcd_seg_data_chunk_t));
if (l_chunks == NULL) {
opj_event_msg(p_manager, EVT_ERROR,
"cannot allocate opj_tcd_seg_data_chunk_t* array");
return OPJ_FALSE;
}
l_cblk->chunks = l_chunks;
l_cblk->numchunksalloc = l_numchunksalloc;
}
l_cblk->chunks[l_cblk->numchunks].data = l_current_data;
l_cblk->chunks[l_cblk->numchunks].len = l_seg->newlen;
l_cblk->numchunks ++;
l_current_data += l_seg->newlen;
l_seg->len += l_seg->newlen;
l_seg->numpasses += l_seg->numnewpasses;
l_cblk->numnewpasses -= l_seg->numnewpasses;
l_seg->real_num_passes = l_seg->numpasses;
if (l_cblk->numnewpasses > 0) {
++l_seg;
++l_cblk->numsegs;
}
} while (l_cblk->numnewpasses > 0);
l_cblk->real_num_segs = l_cblk->numsegs;
++l_cblk;
} /* next code_block */
++l_band;
}
*(p_data_read) = (OPJ_UINT32)(l_current_data - p_src_data);
return OPJ_TRUE;
}
static OPJ_BOOL opj_t2_skip_packet_data(opj_t2_t* p_t2,
opj_tcd_tile_t *p_tile,
opj_pi_iterator_t *p_pi,
OPJ_UINT32 * p_data_read,
OPJ_UINT32 p_max_length,
opj_packet_info_t *pack_info,
opj_event_mgr_t *p_manager)
{
OPJ_UINT32 bandno, cblkno;
OPJ_UINT32 l_nb_code_blocks;
opj_tcd_band_t *l_band = 00;
opj_tcd_cblk_dec_t* l_cblk = 00;
opj_tcd_resolution_t* l_res =
&p_tile->comps[p_pi->compno].resolutions[p_pi->resno];
OPJ_ARG_NOT_USED(p_t2);
OPJ_ARG_NOT_USED(pack_info);
*p_data_read = 0;
l_band = l_res->bands;
for (bandno = 0; bandno < l_res->numbands; ++bandno) {
opj_tcd_precinct_t *l_prc = &l_band->precincts[p_pi->precno];
if ((l_band->x1 - l_band->x0 == 0) || (l_band->y1 - l_band->y0 == 0)) {
++l_band;
continue;
}
l_nb_code_blocks = l_prc->cw * l_prc->ch;
l_cblk = l_prc->cblks.dec;
for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) {
opj_tcd_seg_t *l_seg = 00;
if (!l_cblk->numnewpasses) {
/* nothing to do */
++l_cblk;
continue;
}
if (!l_cblk->numsegs) {
l_seg = l_cblk->segs;
++l_cblk->numsegs;
} else {
l_seg = &l_cblk->segs[l_cblk->numsegs - 1];
if (l_seg->numpasses == l_seg->maxpasses) {
++l_seg;
++l_cblk->numsegs;
}
}
do {
/* Check possible overflow then size */
if (((*p_data_read + l_seg->newlen) < (*p_data_read)) ||
((*p_data_read + l_seg->newlen) > p_max_length)) {
opj_event_msg(p_manager, EVT_ERROR,
"skip: segment too long (%d) with max (%d) for codeblock %d (p=%d, b=%d, r=%d, c=%d)\n",
l_seg->newlen, p_max_length, cblkno, p_pi->precno, bandno, p_pi->resno,
p_pi->compno);
return OPJ_FALSE;
}
#ifdef USE_JPWL
/* we need here a j2k handle to verify if making a check to
the validity of cblocks parameters is selected from user (-W) */
/* let's check that we are not exceeding */
if ((l_cblk->len + l_seg->newlen) > 8192) {
opj_event_msg(p_manager, EVT_WARNING,
"JPWL: segment too long (%d) for codeblock %d (p=%d, b=%d, r=%d, c=%d)\n",
l_seg->newlen, cblkno, p_pi->precno, bandno, p_pi->resno, p_pi->compno);
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return -999;
}
l_seg->newlen = 8192 - l_cblk->len;
opj_event_msg(p_manager, EVT_WARNING, " - truncating segment to %d\n",
l_seg->newlen);
break;
};
#endif /* USE_JPWL */
JAS_FPRINTF(stderr, "p_data_read (%d) newlen (%d) \n", *p_data_read,
l_seg->newlen);
*(p_data_read) += l_seg->newlen;
l_seg->numpasses += l_seg->numnewpasses;
l_cblk->numnewpasses -= l_seg->numnewpasses;
if (l_cblk->numnewpasses > 0) {
++l_seg;
++l_cblk->numsegs;
}
} while (l_cblk->numnewpasses > 0);
++l_cblk;
}
++l_band;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_t2_init_seg(opj_tcd_cblk_dec_t* cblk,
OPJ_UINT32 index,
OPJ_UINT32 cblksty,
OPJ_UINT32 first)
{
opj_tcd_seg_t* seg = 00;
OPJ_UINT32 l_nb_segs = index + 1;
if (l_nb_segs > cblk->m_current_max_segs) {
opj_tcd_seg_t* new_segs;
OPJ_UINT32 l_m_current_max_segs = cblk->m_current_max_segs +
OPJ_J2K_DEFAULT_NB_SEGS;
new_segs = (opj_tcd_seg_t*) opj_realloc(cblk->segs,
l_m_current_max_segs * sizeof(opj_tcd_seg_t));
if (! new_segs) {
/* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to initialize segment %d\n", l_nb_segs); */
return OPJ_FALSE;
}
cblk->segs = new_segs;
memset(new_segs + cblk->m_current_max_segs,
0, OPJ_J2K_DEFAULT_NB_SEGS * sizeof(opj_tcd_seg_t));
cblk->m_current_max_segs = l_m_current_max_segs;
}
seg = &cblk->segs[index];
opj_tcd_reinit_segment(seg);
if (cblksty & J2K_CCP_CBLKSTY_TERMALL) {
seg->maxpasses = 1;
} else if (cblksty & J2K_CCP_CBLKSTY_LAZY) {
if (first) {
seg->maxpasses = 10;
} else {
seg->maxpasses = (((seg - 1)->maxpasses == 1) ||
((seg - 1)->maxpasses == 10)) ? 2 : 1;
}
} else {
/* See paragraph "B.10.6 Number of coding passes" of the standard.
* Probably that 109 must be interpreted a (Mb-1)*3 + 1 with Mb=37,
* Mb being the maximum number of bit-planes available for the
* representation of coefficients in the sub-band */
seg->maxpasses = 109;
}
return OPJ_TRUE;
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_2758_1 |
crossvul-cpp_data_bad_5482_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; 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, int 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);
int iskew = imagew - 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; 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 + tilew > imagew) {
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, 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);
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; 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, 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);
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-787/c/bad_5482_1 |
crossvul-cpp_data_bad_3411_1 | // Notes and useful links:
// This conversation (https://www.sourceware.org/ml/gdb/2009-02/msg00100.html) suggests GDB clients usually ignore error codes
// Useful, but not to be blindly trusted - http://www.embecosm.com/appnotes/ean4/embecosm-howto-rsp-server-ean4-issue-2.html
// https://github.com/llvm-mirror/lldb/blob/master/docs/lldb-gdb-remote.txt
// http://www.cygwin.com/ml/gdb/2008-05/msg00166.html
#include "gdbserver/core.h"
#include "gdbr_common.h"
#include "libgdbr.h"
#include "packet.h"
#include "utils.h"
#include "r_util/r_str.h"
static int _server_handle_qSupported(libgdbr_t *g) {
int ret;
char *buf;
if (!(buf = malloc (128))) {
return -1;
}
snprintf (buf, 127, "PacketSize=%x", (ut32) (g->read_max - 1));
if ((ret = handle_qSupported (g)) < 0) {
return -1;
}
ret = send_msg (g, buf);
free (buf);
return ret;
}
static int _server_handle_qTStatus(libgdbr_t *g) {
int ret;
// TODO Handle proper reporting of trace status
const char *message = "";
if ((ret = send_ack (g)) < 0) {
return -1;
}
return send_msg (g, message);
}
static int _server_handle_s(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) {
char message[64];
if (send_ack (g) < 0) {
return -1;
}
if (g->data_len > 1) {
// We don't handle s[addr] packet
return send_msg (g, "E01");
}
if (cmd_cb (core_ptr, "ds", NULL, 0) < 0) {
send_msg (g, "E01");
return -1;
}
// TODO This packet should specify why we stopped. Right now only for trap
snprintf (message, sizeof (message) - 1, "T05thread:%x;", cmd_cb (core_ptr, "dptr", NULL, 0));
return send_msg (g, message);
}
static int _server_handle_c(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) {
char message[64];
if (send_ack (g) < 0) {
return -1;
}
if (g->data_len > 1) {
// We don't handle s[addr] packet
return send_msg (g, "E01");
}
if (cmd_cb (core_ptr, "dc", NULL, 0) < 0) {
send_msg (g, "E01");
return -1;
}
// TODO This packet should specify why we stopped. Right now only for trap
snprintf (message, sizeof (message) - 1, "T05thread:%x;", cmd_cb (core_ptr, "dptr", NULL, 0));
return send_msg (g, message);
}
static int _server_handle_ques(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) {
// TODO This packet should specify why we stopped. Right now only for trap
char message[64];
if (send_ack (g) < 0) {
return -1;
}
snprintf (message, sizeof (message) - 1, "T05thread:%x;", cmd_cb (core_ptr, "dptr", NULL, 0));
return send_msg (g, message);
}
static int _server_handle_qC(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) {
char *buf;
int ret;
size_t buf_len = 80;
if ((ret = send_ack (g)) < 0) {
return -1;
}
if (!(buf = malloc (buf_len))) {
return -1;
}
if ((ret = cmd_cb (core_ptr, "dp", buf, buf_len)) < 0) {
free (buf);
return -1;
}
ret = send_msg (g, buf);
free (buf);
return ret;
}
static int _server_handle_k(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) {
send_ack (g);
return -1;
}
static int _server_handle_vKill(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) {
if (send_ack (g) < 0) {
return -1;
}
// TODO handle killing of pid
send_msg (g, "OK");
return -1;
}
static int _server_handle_z(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) {
if (send_ack (g) < 0) {
return -1;
}
char set; // Z = set, z = remove
int type;
ut64 addr;
char cmd[64];
sscanf (g->data, "%c%d,%"PFMT64x, &set, &type, &addr);
if (type != 0) {
// TODO handle hw breakpoints and watchpoints
return send_msg (g, "E01");
}
switch (set) {
case 'Z':
// Set
snprintf (cmd, sizeof (cmd) - 1, "db 0x%"PFMT64x, addr);
break;
case 'z':
// Remove
snprintf (cmd, sizeof (cmd) - 1, "db- 0x%"PFMT64x, addr);
break;
default:
return send_msg (g, "E01");
}
if (cmd_cb (core_ptr, cmd, NULL, 0) < 0) {
send_msg (g, "E01");
return -1;
}
return send_msg (g, "OK");
}
static int _server_handle_vCont(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) {
char *action = NULL;
if (send_ack (g) < 0) {
return -1;
}
g->data[g->data_len] = '\0';
if (g->data[5] == '?') {
// Query about everything we support
return send_msg (g, "vCont;c;s");
}
if (!(action = strtok (g->data, ";"))) {
return send_msg (g, "E01");
}
while (action = strtok (NULL, ";")) {
eprintf ("action: %s\n", action);
switch (action[0]) {
case 's':
// TODO handle thread selections
if (cmd_cb (core_ptr, "ds", NULL, 0) < 0) {
send_msg (g, "E01");
return -1;
}
return send_msg (g, "OK");
case 'c':
// TODO handle thread selections
if (cmd_cb (core_ptr, "dc", NULL, 0) < 0) {
send_msg (g, "E01");
return -1;
}
return send_msg (g, "OK");
default:
// TODO support others
return send_msg (g, "E01");
}
}
}
static int _server_handle_qAttached(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) {
if (send_ack (g) < 0) {
return -1;
}
// TODO check if process was attached or created
// Right now, says that process was created
return send_msg (g, "0");
}
// TODO, proper handling of Hg and Hc (right now handled identically)
// Set thread for all operations other than "step" and "continue"
static int _server_handle_Hg(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) {
// We don't yet support multiprocess. Client is not supposed to send Hgp. If we receive it anyway,
// send error
char cmd[32];
int tid;
if (send_ack (g) < 0) {
return -1;
}
if (g->data_len <= 2 || isalpha (g->data[2])) {
return send_msg (g, "E01");
}
// Hg-1 = "all threads", Hg0 = "pick any thread"
if (g->data[2] == '0' || !strncmp (g->data + 2, "-1", 2)) {
return send_msg (g, "OK");
}
sscanf (g->data + 2, "%x", &tid);
snprintf (cmd, sizeof (cmd) - 1, "dpt=%d", tid);
// Set thread for future operations
if (cmd_cb (core_ptr, cmd, NULL, 0) < 0) {
send_msg (g, "E01");
return -1;
}
return send_msg (g, "OK");
}
// Set thread for "step" and "continue"
static int _server_handle_Hc(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) {
// Usually this is only sent with Hc-1. Still. Set the threads for next operations
char cmd[32];
int tid;
if (send_ack (g) < 0) {
return -1;
}
if (g->data_len <= 2 || isalpha (g->data[2])) {
return send_msg (g, "E01");
}
// Hc-1 = "all threads", Hc0 = "pick any thread"
if (g->data[2] == '0' || !strncmp (g->data + 2, "-1", 2)) {
return send_msg (g, "OK");
}
sscanf (g->data + 2, "%x", &tid);
snprintf (cmd, sizeof (cmd) - 1, "dpt=%d", tid);
// Set thread for future operations
if (cmd_cb (core_ptr, cmd, NULL, 0) < 0) {
send_msg (g, "E01");
return -1;
}
return send_msg (g, "OK");
}
static int _server_handle_qfThreadInfo(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) {
char *buf;
int ret;
size_t buf_len = 80;
if ((ret = send_ack (g)) < 0) {
return -1;
}
if (!(buf = malloc (buf_len))) {
return -1;
}
if ((ret = cmd_cb (core_ptr, "dpt", buf, buf_len)) < 0) {
free (buf);
return -1;
}
ret = send_msg (g, buf);
free (buf);
return ret;
}
static int _server_handle_qsThreadInfo(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) {
// TODO handle overflow from qfThreadInfo. Otherwise this won't work with programs with many threads
if (send_ack (g) < 0 || send_msg (g, "l") < 0) {
return -1;
}
return 0;
}
static int _server_handle_g(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) {
char *buf;
// To be very safe
int buf_len = 4096;
int ret;
if (send_ack (g) < 0) {
return -1;
}
if (!(buf = malloc (buf_len))) {
send_msg (g, "E01");
return -1;
}
memset (buf, 0, buf_len);
if ((buf_len = cmd_cb (core_ptr, "dr", buf, buf_len)) < 0) {
free (buf);
send_msg (g, "E01");
return -1;
}
ret = send_msg (g, buf);
free (buf);
return ret;
}
static int _server_handle_m(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) {
int ret;
ut64 addr;
int length;
char *buf1, *buf2, cmd[64];
int buf1_len, buf2_len;
if (send_ack (g) < 0) {
return -1;
}
g->data[g->data_len] = 0;
sscanf (g->data, "m%"PFMT64x",%d", &addr, &length);
if (g->data_len < 4 || !strchr (g->data, ',')) {
return send_msg (g, "E01");
}
buf1_len = length;
buf2_len = length * 2 + 1;
if (!(buf1 = malloc (buf1_len))) {
return -1;
}
if (!(buf2 = malloc (buf2_len))) {
free (buf1);
return -1;
}
memset (buf2, 0, buf2_len);
snprintf (cmd, sizeof (cmd) - 1, "m %"PFMT64x" %d", addr, length);
if ((buf1_len = cmd_cb (core_ptr, cmd, buf1, buf1_len)) < 0) {
free (buf1);
free (buf2);
send_msg (g, "E01");
return -1;
}
pack_hex (buf1, buf1_len, buf2);
ret = send_msg (g, buf2);
free (buf1);
free (buf2);
return ret;
}
static int _server_handle_vMustReplyEmpty(libgdbr_t *g) {
if (send_ack (g) < 0) {
return -1;
}
return send_msg (g, "");
}
static int _server_handle_qTfV(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) {
// TODO
if (send_ack (g) < 0) {
return -1;
}
return send_msg (g, "");
}
int gdbr_server_serve(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) {
int ret;
if (!g) {
return -1;
}
while (1) {
read_packet (g);
if (g->data_len == 0) {
continue;
}
if (r_str_startswith (g->data, "k")) {
return _server_handle_k (g, cmd_cb, core_ptr);
}
if (r_str_startswith (g->data, "vKill")) {
return _server_handle_vKill (g, cmd_cb, core_ptr);
}
if (r_str_startswith (g->data, "qSupported")) {
if ((ret = _server_handle_qSupported (g)) < 0) {
return ret;
}
continue;
}
if (r_str_startswith (g->data, "qTStatus")) {
if ((ret = _server_handle_qTStatus (g)) < 0) {
return ret;
}
continue;
}
if (r_str_startswith (g->data, "qC") && g->data_len == 2) {
if ((ret = _server_handle_qC (g, cmd_cb, core_ptr)) < 0) {
return ret;
}
continue;
}
if (r_str_startswith (g->data, "qAttached")) {
if ((ret = _server_handle_qAttached (g, cmd_cb, core_ptr)) < 0) {
return ret;
}
continue;
}
if (r_str_startswith (g->data, "vMustReplyEmpty")) {
if ((ret = _server_handle_vMustReplyEmpty (g)) < 0) {
return ret;
}
continue;
}
if (r_str_startswith (g->data, "qTfV")) {
if ((ret = _server_handle_qTfV (g, cmd_cb, core_ptr)) < 0) {
return ret;
}
continue;
}
if (r_str_startswith (g->data, "qfThreadInfo")) {
if ((ret = _server_handle_qfThreadInfo (g, cmd_cb, core_ptr)) < 0) {
return ret;
}
continue;
}
if (r_str_startswith (g->data, "qsThreadInfo")) {
if ((ret = _server_handle_qsThreadInfo (g, cmd_cb, core_ptr)) < 0) {
return ret;
}
continue;
}
if (r_str_startswith (g->data, "Hg")) {
if ((ret = _server_handle_Hg (g, cmd_cb, core_ptr)) < 0) {
return ret;
}
continue;
}
if (r_str_startswith (g->data, "Hc")) {
if ((ret = _server_handle_Hc (g, cmd_cb, core_ptr)) < 0) {
return ret;
}
continue;
}
if (r_str_startswith (g->data, "?")) {
if ((ret = _server_handle_ques (g, cmd_cb, core_ptr)) < 0) {
return ret;
}
continue;
}
if (r_str_startswith (g->data, "g") && g->data_len == 1) {
if ((ret = _server_handle_g (g, cmd_cb, core_ptr)) < 0) {
return ret;
}
continue;
}
if (r_str_startswith (g->data, "vCont")) {
if ((ret = _server_handle_vCont (g, cmd_cb, core_ptr)) < 0) {
return ret;
}
continue;
}
if (g->data[0] == 'z' || g->data[0] == 'Z') {
if ((ret = _server_handle_z (g, cmd_cb, core_ptr)) < 0) {
return ret;
}
continue;
}
if (g->data[0] == 's') {
if ((ret = _server_handle_s (g, cmd_cb, core_ptr)) < 0) {
return ret;
}
continue;
}
if (g->data[0] == 'c') {
if ((ret = _server_handle_c (g, cmd_cb, core_ptr)) < 0) {
return ret;
}
continue;
}
if (r_str_startswith (g->data, "m")) {
if ((ret = _server_handle_m (g, cmd_cb, core_ptr)) < 0) {
return ret;
}
continue;
}
// Unrecognized packet
if (send_ack (g) < 0 || send_msg (g, "") < 0) {
g->data[g->data_len] = '\0';
eprintf ("Unknown packet: %s\n", g->data);
return -1;
}
};
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_3411_1 |
crossvul-cpp_data_good_3374_0 | /**********************************************************************
regparse.c - Oniguruma (regular expression library)
**********************************************************************/
/*-
* Copyright (c) 2002-2016 K.Kosako <sndgk393 AT ybb DOT ne DOT jp>
* 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 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 AUTHOR 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 "regparse.h"
#include "st.h"
#ifdef DEBUG_NODE_FREE
#include <stdio.h>
#endif
#define WARN_BUFSIZE 256
#define CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS
OnigSyntaxType OnigSyntaxRuby = {
(( SYN_GNU_REGEX_OP | ONIG_SYN_OP_QMARK_NON_GREEDY |
ONIG_SYN_OP_ESC_OCTAL3 | ONIG_SYN_OP_ESC_X_HEX2 |
ONIG_SYN_OP_ESC_X_BRACE_HEX8 | ONIG_SYN_OP_ESC_CONTROL_CHARS |
ONIG_SYN_OP_ESC_C_CONTROL )
& ~ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END )
, ( ONIG_SYN_OP2_QMARK_GROUP_EFFECT |
ONIG_SYN_OP2_OPTION_RUBY |
ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP | ONIG_SYN_OP2_ESC_K_NAMED_BACKREF |
ONIG_SYN_OP2_ESC_G_SUBEXP_CALL |
ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY |
ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT |
ONIG_SYN_OP2_PLUS_POSSESSIVE_REPEAT |
ONIG_SYN_OP2_CCLASS_SET_OP | ONIG_SYN_OP2_ESC_CAPITAL_C_BAR_CONTROL |
ONIG_SYN_OP2_ESC_CAPITAL_M_BAR_META | ONIG_SYN_OP2_ESC_V_VTAB |
ONIG_SYN_OP2_ESC_H_XDIGIT )
, ( SYN_GNU_REGEX_BV |
ONIG_SYN_ALLOW_INTERVAL_LOW_ABBREV |
ONIG_SYN_DIFFERENT_LEN_ALT_LOOK_BEHIND |
ONIG_SYN_CAPTURE_ONLY_NAMED_GROUP |
ONIG_SYN_ALLOW_MULTIPLEX_DEFINITION_NAME |
ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY |
ONIG_SYN_WARN_CC_OP_NOT_ESCAPED |
ONIG_SYN_WARN_REDUNDANT_NESTED_REPEAT )
, ONIG_OPTION_NONE
,
{
(OnigCodePoint )'\\' /* esc */
, (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* anychar '.' */
, (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* anytime '*' */
, (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* zero or one time '?' */
, (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* one or more time '+' */
, (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* anychar anytime */
}
};
OnigSyntaxType* OnigDefaultSyntax = ONIG_SYNTAX_RUBY;
extern void onig_null_warn(const char* s ARG_UNUSED) { }
#ifdef DEFAULT_WARN_FUNCTION
static OnigWarnFunc onig_warn = (OnigWarnFunc )DEFAULT_WARN_FUNCTION;
#else
static OnigWarnFunc onig_warn = onig_null_warn;
#endif
#ifdef DEFAULT_VERB_WARN_FUNCTION
static OnigWarnFunc onig_verb_warn = (OnigWarnFunc )DEFAULT_VERB_WARN_FUNCTION;
#else
static OnigWarnFunc onig_verb_warn = onig_null_warn;
#endif
extern void onig_set_warn_func(OnigWarnFunc f)
{
onig_warn = f;
}
extern void onig_set_verb_warn_func(OnigWarnFunc f)
{
onig_verb_warn = f;
}
extern void
onig_warning(const char* s)
{
if (onig_warn == onig_null_warn) return ;
(*onig_warn)(s);
}
#define DEFAULT_MAX_CAPTURE_NUM 32767
static int MaxCaptureNum = DEFAULT_MAX_CAPTURE_NUM;
extern int
onig_set_capture_num_limit(int num)
{
if (num < 0) return -1;
MaxCaptureNum = num;
return 0;
}
static unsigned int ParseDepthLimit = DEFAULT_PARSE_DEPTH_LIMIT;
extern unsigned int
onig_get_parse_depth_limit(void)
{
return ParseDepthLimit;
}
extern int
onig_set_parse_depth_limit(unsigned int depth)
{
if (depth == 0)
ParseDepthLimit = DEFAULT_PARSE_DEPTH_LIMIT;
else
ParseDepthLimit = depth;
return 0;
}
static void
bbuf_free(BBuf* bbuf)
{
if (IS_NOT_NULL(bbuf)) {
if (IS_NOT_NULL(bbuf->p)) xfree(bbuf->p);
xfree(bbuf);
}
}
static int
bbuf_clone(BBuf** rto, BBuf* from)
{
int r;
BBuf *to;
*rto = to = (BBuf* )xmalloc(sizeof(BBuf));
CHECK_NULL_RETURN_MEMERR(to);
r = BBUF_INIT(to, from->alloc);
if (r != 0) return r;
to->used = from->used;
xmemcpy(to->p, from->p, from->used);
return 0;
}
#define BACKREF_REL_TO_ABS(rel_no, env) \
((env)->num_mem + 1 + (rel_no))
#define ONOFF(v,f,negative) (negative) ? ((v) &= ~(f)) : ((v) |= (f))
#define MBCODE_START_POS(enc) \
(OnigCodePoint )(ONIGENC_MBC_MINLEN(enc) > 1 ? 0 : 0x80)
#define SET_ALL_MULTI_BYTE_RANGE(enc, pbuf) \
add_code_range_to_buf(pbuf, MBCODE_START_POS(enc), ~((OnigCodePoint )0))
#define ADD_ALL_MULTI_BYTE_RANGE(enc, mbuf) do {\
if (! ONIGENC_IS_SINGLEBYTE(enc)) {\
r = SET_ALL_MULTI_BYTE_RANGE(enc, &(mbuf));\
if (r) return r;\
}\
} while (0)
#define BITSET_IS_EMPTY(bs,empty) do {\
int i;\
empty = 1;\
for (i = 0; i < (int )BITSET_SIZE; i++) {\
if ((bs)[i] != 0) {\
empty = 0; break;\
}\
}\
} while (0)
static void
bitset_set_range(BitSetRef bs, int from, int to)
{
int i;
for (i = from; i <= to && i < SINGLE_BYTE_SIZE; i++) {
BITSET_SET_BIT(bs, i);
}
}
#if 0
static void
bitset_set_all(BitSetRef bs)
{
int i;
for (i = 0; i < BITSET_SIZE; i++) { bs[i] = ~((Bits )0); }
}
#endif
static void
bitset_invert(BitSetRef bs)
{
int i;
for (i = 0; i < (int )BITSET_SIZE; i++) { bs[i] = ~(bs[i]); }
}
static void
bitset_invert_to(BitSetRef from, BitSetRef to)
{
int i;
for (i = 0; i < (int )BITSET_SIZE; i++) { to[i] = ~(from[i]); }
}
static void
bitset_and(BitSetRef dest, BitSetRef bs)
{
int i;
for (i = 0; i < (int )BITSET_SIZE; i++) { dest[i] &= bs[i]; }
}
static void
bitset_or(BitSetRef dest, BitSetRef bs)
{
int i;
for (i = 0; i < (int )BITSET_SIZE; i++) { dest[i] |= bs[i]; }
}
static void
bitset_copy(BitSetRef dest, BitSetRef bs)
{
int i;
for (i = 0; i < (int )BITSET_SIZE; i++) { dest[i] = bs[i]; }
}
extern int
onig_strncmp(const UChar* s1, const UChar* s2, int n)
{
int x;
while (n-- > 0) {
x = *s2++ - *s1++;
if (x) return x;
}
return 0;
}
extern void
onig_strcpy(UChar* dest, const UChar* src, const UChar* end)
{
int len = end - src;
if (len > 0) {
xmemcpy(dest, src, len);
dest[len] = (UChar )0;
}
}
#ifdef USE_NAMED_GROUP
static UChar*
strdup_with_null(OnigEncoding enc, UChar* s, UChar* end)
{
int slen, term_len, i;
UChar *r;
slen = end - s;
term_len = ONIGENC_MBC_MINLEN(enc);
r = (UChar* )xmalloc(slen + term_len);
CHECK_NULL_RETURN(r);
xmemcpy(r, s, slen);
for (i = 0; i < term_len; i++)
r[slen + i] = (UChar )0;
return r;
}
#endif
/* scan pattern methods */
#define PEND_VALUE 0
#define PFETCH_READY UChar* pfetch_prev
#define PEND (p < end ? 0 : 1)
#define PUNFETCH p = pfetch_prev
#define PINC do { \
pfetch_prev = p; \
p += ONIGENC_MBC_ENC_LEN(enc, p); \
} while (0)
#define PFETCH(c) do { \
c = ONIGENC_MBC_TO_CODE(enc, p, end); \
pfetch_prev = p; \
p += ONIGENC_MBC_ENC_LEN(enc, p); \
} while (0)
#define PINC_S do { \
p += ONIGENC_MBC_ENC_LEN(enc, p); \
} while (0)
#define PFETCH_S(c) do { \
c = ONIGENC_MBC_TO_CODE(enc, p, end); \
p += ONIGENC_MBC_ENC_LEN(enc, p); \
} while (0)
#define PPEEK (p < end ? ONIGENC_MBC_TO_CODE(enc, p, end) : PEND_VALUE)
#define PPEEK_IS(c) (PPEEK == (OnigCodePoint )c)
static UChar*
strcat_capa(UChar* dest, UChar* dest_end, const UChar* src, const UChar* src_end,
int capa)
{
UChar* r;
if (dest)
r = (UChar* )xrealloc(dest, capa + 1);
else
r = (UChar* )xmalloc(capa + 1);
CHECK_NULL_RETURN(r);
onig_strcpy(r + (dest_end - dest), src, src_end);
return r;
}
/* dest on static area */
static UChar*
strcat_capa_from_static(UChar* dest, UChar* dest_end,
const UChar* src, const UChar* src_end, int capa)
{
UChar* r;
r = (UChar* )xmalloc(capa + 1);
CHECK_NULL_RETURN(r);
onig_strcpy(r, dest, dest_end);
onig_strcpy(r + (dest_end - dest), src, src_end);
return r;
}
#ifdef USE_ST_LIBRARY
typedef struct {
UChar* s;
UChar* end;
} st_str_end_key;
static int
str_end_cmp(st_str_end_key* x, st_str_end_key* y)
{
UChar *p, *q;
int c;
if ((x->end - x->s) != (y->end - y->s))
return 1;
p = x->s;
q = y->s;
while (p < x->end) {
c = (int )*p - (int )*q;
if (c != 0) return c;
p++; q++;
}
return 0;
}
static int
str_end_hash(st_str_end_key* x)
{
UChar *p;
int val = 0;
p = x->s;
while (p < x->end) {
val = val * 997 + (int )*p++;
}
return val + (val >> 5);
}
extern hash_table_type*
onig_st_init_strend_table_with_size(int size)
{
static struct st_hash_type hashType = {
str_end_cmp,
str_end_hash,
};
return (hash_table_type* )
onig_st_init_table_with_size(&hashType, size);
}
extern int
onig_st_lookup_strend(hash_table_type* table, const UChar* str_key,
const UChar* end_key, hash_data_type *value)
{
st_str_end_key key;
key.s = (UChar* )str_key;
key.end = (UChar* )end_key;
return onig_st_lookup(table, (st_data_t )(&key), value);
}
extern int
onig_st_insert_strend(hash_table_type* table, const UChar* str_key,
const UChar* end_key, hash_data_type value)
{
st_str_end_key* key;
int result;
key = (st_str_end_key* )xmalloc(sizeof(st_str_end_key));
key->s = (UChar* )str_key;
key->end = (UChar* )end_key;
result = onig_st_insert(table, (st_data_t )key, value);
if (result) {
xfree(key);
}
return result;
}
#endif /* USE_ST_LIBRARY */
#ifdef USE_NAMED_GROUP
#define INIT_NAME_BACKREFS_ALLOC_NUM 8
typedef struct {
UChar* name;
int name_len; /* byte length */
int back_num; /* number of backrefs */
int back_alloc;
int back_ref1;
int* back_refs;
} NameEntry;
#ifdef USE_ST_LIBRARY
typedef st_table NameTable;
typedef st_data_t HashDataType; /* 1.6 st.h doesn't define st_data_t type */
#define NAMEBUF_SIZE 24
#define NAMEBUF_SIZE_1 25
#ifdef ONIG_DEBUG
static int
i_print_name_entry(UChar* key, NameEntry* e, void* arg)
{
int i;
FILE* fp = (FILE* )arg;
fprintf(fp, "%s: ", e->name);
if (e->back_num == 0)
fputs("-", fp);
else if (e->back_num == 1)
fprintf(fp, "%d", e->back_ref1);
else {
for (i = 0; i < e->back_num; i++) {
if (i > 0) fprintf(fp, ", ");
fprintf(fp, "%d", e->back_refs[i]);
}
}
fputs("\n", fp);
return ST_CONTINUE;
}
extern int
onig_print_names(FILE* fp, regex_t* reg)
{
NameTable* t = (NameTable* )reg->name_table;
if (IS_NOT_NULL(t)) {
fprintf(fp, "name table\n");
onig_st_foreach(t, i_print_name_entry, (HashDataType )fp);
fputs("\n", fp);
}
return 0;
}
#endif /* ONIG_DEBUG */
static int
i_free_name_entry(UChar* key, NameEntry* e, void* arg ARG_UNUSED)
{
xfree(e->name);
if (IS_NOT_NULL(e->back_refs)) xfree(e->back_refs);
xfree(key);
xfree(e);
return ST_DELETE;
}
static int
names_clear(regex_t* reg)
{
NameTable* t = (NameTable* )reg->name_table;
if (IS_NOT_NULL(t)) {
onig_st_foreach(t, i_free_name_entry, 0);
}
return 0;
}
extern int
onig_names_free(regex_t* reg)
{
int r;
NameTable* t;
r = names_clear(reg);
if (r) return r;
t = (NameTable* )reg->name_table;
if (IS_NOT_NULL(t)) onig_st_free_table(t);
reg->name_table = (void* )NULL;
return 0;
}
static NameEntry*
name_find(regex_t* reg, const UChar* name, const UChar* name_end)
{
NameEntry* e;
NameTable* t = (NameTable* )reg->name_table;
e = (NameEntry* )NULL;
if (IS_NOT_NULL(t)) {
onig_st_lookup_strend(t, name, name_end, (HashDataType* )((void* )(&e)));
}
return e;
}
typedef struct {
int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*);
regex_t* reg;
void* arg;
int ret;
OnigEncoding enc;
} INamesArg;
static int
i_names(UChar* key ARG_UNUSED, NameEntry* e, INamesArg* arg)
{
int r = (*(arg->func))(e->name,
e->name + e->name_len,
e->back_num,
(e->back_num > 1 ? e->back_refs : &(e->back_ref1)),
arg->reg, arg->arg);
if (r != 0) {
arg->ret = r;
return ST_STOP;
}
return ST_CONTINUE;
}
extern int
onig_foreach_name(regex_t* reg,
int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*), void* arg)
{
INamesArg narg;
NameTable* t = (NameTable* )reg->name_table;
narg.ret = 0;
if (IS_NOT_NULL(t)) {
narg.func = func;
narg.reg = reg;
narg.arg = arg;
narg.enc = reg->enc; /* should be pattern encoding. */
onig_st_foreach(t, i_names, (HashDataType )&narg);
}
return narg.ret;
}
static int
i_renumber_name(UChar* key ARG_UNUSED, NameEntry* e, GroupNumRemap* map)
{
int i;
if (e->back_num > 1) {
for (i = 0; i < e->back_num; i++) {
e->back_refs[i] = map[e->back_refs[i]].new_val;
}
}
else if (e->back_num == 1) {
e->back_ref1 = map[e->back_ref1].new_val;
}
return ST_CONTINUE;
}
extern int
onig_renumber_name_table(regex_t* reg, GroupNumRemap* map)
{
NameTable* t = (NameTable* )reg->name_table;
if (IS_NOT_NULL(t)) {
onig_st_foreach(t, i_renumber_name, (HashDataType )map);
}
return 0;
}
extern int
onig_number_of_names(regex_t* reg)
{
NameTable* t = (NameTable* )reg->name_table;
if (IS_NOT_NULL(t))
return t->num_entries;
else
return 0;
}
#else /* USE_ST_LIBRARY */
#define INIT_NAMES_ALLOC_NUM 8
typedef struct {
NameEntry* e;
int num;
int alloc;
} NameTable;
#ifdef ONIG_DEBUG
extern int
onig_print_names(FILE* fp, regex_t* reg)
{
int i, j;
NameEntry* e;
NameTable* t = (NameTable* )reg->name_table;
if (IS_NOT_NULL(t) && t->num > 0) {
fprintf(fp, "name table\n");
for (i = 0; i < t->num; i++) {
e = &(t->e[i]);
fprintf(fp, "%s: ", e->name);
if (e->back_num == 0) {
fputs("-", fp);
}
else if (e->back_num == 1) {
fprintf(fp, "%d", e->back_ref1);
}
else {
for (j = 0; j < e->back_num; j++) {
if (j > 0) fprintf(fp, ", ");
fprintf(fp, "%d", e->back_refs[j]);
}
}
fputs("\n", fp);
}
fputs("\n", fp);
}
return 0;
}
#endif
static int
names_clear(regex_t* reg)
{
int i;
NameEntry* e;
NameTable* t = (NameTable* )reg->name_table;
if (IS_NOT_NULL(t)) {
for (i = 0; i < t->num; i++) {
e = &(t->e[i]);
if (IS_NOT_NULL(e->name)) {
xfree(e->name);
e->name = NULL;
e->name_len = 0;
e->back_num = 0;
e->back_alloc = 0;
if (IS_NOT_NULL(e->back_refs)) xfree(e->back_refs);
e->back_refs = (int* )NULL;
}
}
if (IS_NOT_NULL(t->e)) {
xfree(t->e);
t->e = NULL;
}
t->num = 0;
}
return 0;
}
extern int
onig_names_free(regex_t* reg)
{
int r;
NameTable* t;
r = names_clear(reg);
if (r) return r;
t = (NameTable* )reg->name_table;
if (IS_NOT_NULL(t)) xfree(t);
reg->name_table = NULL;
return 0;
}
static NameEntry*
name_find(regex_t* reg, UChar* name, UChar* name_end)
{
int i, len;
NameEntry* e;
NameTable* t = (NameTable* )reg->name_table;
if (IS_NOT_NULL(t)) {
len = name_end - name;
for (i = 0; i < t->num; i++) {
e = &(t->e[i]);
if (len == e->name_len && onig_strncmp(name, e->name, len) == 0)
return e;
}
}
return (NameEntry* )NULL;
}
extern int
onig_foreach_name(regex_t* reg,
int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*), void* arg)
{
int i, r;
NameEntry* e;
NameTable* t = (NameTable* )reg->name_table;
if (IS_NOT_NULL(t)) {
for (i = 0; i < t->num; i++) {
e = &(t->e[i]);
r = (*func)(e->name, e->name + e->name_len, e->back_num,
(e->back_num > 1 ? e->back_refs : &(e->back_ref1)),
reg, arg);
if (r != 0) return r;
}
}
return 0;
}
extern int
onig_number_of_names(regex_t* reg)
{
NameTable* t = (NameTable* )reg->name_table;
if (IS_NOT_NULL(t))
return t->num;
else
return 0;
}
#endif /* else USE_ST_LIBRARY */
static int
name_add(regex_t* reg, UChar* name, UChar* name_end, int backref, ScanEnv* env)
{
int alloc;
NameEntry* e;
NameTable* t = (NameTable* )reg->name_table;
if (name_end - name <= 0)
return ONIGERR_EMPTY_GROUP_NAME;
e = name_find(reg, name, name_end);
if (IS_NULL(e)) {
#ifdef USE_ST_LIBRARY
if (IS_NULL(t)) {
t = onig_st_init_strend_table_with_size(5);
reg->name_table = (void* )t;
}
e = (NameEntry* )xmalloc(sizeof(NameEntry));
CHECK_NULL_RETURN_MEMERR(e);
e->name = strdup_with_null(reg->enc, name, name_end);
if (IS_NULL(e->name)) {
xfree(e); return ONIGERR_MEMORY;
}
onig_st_insert_strend(t, e->name, (e->name + (name_end - name)),
(HashDataType )e);
e->name_len = name_end - name;
e->back_num = 0;
e->back_alloc = 0;
e->back_refs = (int* )NULL;
#else
if (IS_NULL(t)) {
alloc = INIT_NAMES_ALLOC_NUM;
t = (NameTable* )xmalloc(sizeof(NameTable));
CHECK_NULL_RETURN_MEMERR(t);
t->e = NULL;
t->alloc = 0;
t->num = 0;
t->e = (NameEntry* )xmalloc(sizeof(NameEntry) * alloc);
if (IS_NULL(t->e)) {
xfree(t);
return ONIGERR_MEMORY;
}
t->alloc = alloc;
reg->name_table = t;
goto clear;
}
else if (t->num == t->alloc) {
int i;
alloc = t->alloc * 2;
t->e = (NameEntry* )xrealloc(t->e, sizeof(NameEntry) * alloc);
CHECK_NULL_RETURN_MEMERR(t->e);
t->alloc = alloc;
clear:
for (i = t->num; i < t->alloc; i++) {
t->e[i].name = NULL;
t->e[i].name_len = 0;
t->e[i].back_num = 0;
t->e[i].back_alloc = 0;
t->e[i].back_refs = (int* )NULL;
}
}
e = &(t->e[t->num]);
t->num++;
e->name = strdup_with_null(reg->enc, name, name_end);
if (IS_NULL(e->name)) return ONIGERR_MEMORY;
e->name_len = name_end - name;
#endif
}
if (e->back_num >= 1 &&
! IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_MULTIPLEX_DEFINITION_NAME)) {
onig_scan_env_set_error_string(env, ONIGERR_MULTIPLEX_DEFINED_NAME,
name, name_end);
return ONIGERR_MULTIPLEX_DEFINED_NAME;
}
e->back_num++;
if (e->back_num == 1) {
e->back_ref1 = backref;
}
else {
if (e->back_num == 2) {
alloc = INIT_NAME_BACKREFS_ALLOC_NUM;
e->back_refs = (int* )xmalloc(sizeof(int) * alloc);
CHECK_NULL_RETURN_MEMERR(e->back_refs);
e->back_alloc = alloc;
e->back_refs[0] = e->back_ref1;
e->back_refs[1] = backref;
}
else {
if (e->back_num > e->back_alloc) {
alloc = e->back_alloc * 2;
e->back_refs = (int* )xrealloc(e->back_refs, sizeof(int) * alloc);
CHECK_NULL_RETURN_MEMERR(e->back_refs);
e->back_alloc = alloc;
}
e->back_refs[e->back_num - 1] = backref;
}
}
return 0;
}
extern int
onig_name_to_group_numbers(regex_t* reg, const UChar* name,
const UChar* name_end, int** nums)
{
NameEntry* e = name_find(reg, name, name_end);
if (IS_NULL(e)) return ONIGERR_UNDEFINED_NAME_REFERENCE;
switch (e->back_num) {
case 0:
break;
case 1:
*nums = &(e->back_ref1);
break;
default:
*nums = e->back_refs;
break;
}
return e->back_num;
}
extern int
onig_name_to_backref_number(regex_t* reg, const UChar* name,
const UChar* name_end, OnigRegion *region)
{
int i, n, *nums;
n = onig_name_to_group_numbers(reg, name, name_end, &nums);
if (n < 0)
return n;
else if (n == 0)
return ONIGERR_PARSER_BUG;
else if (n == 1)
return nums[0];
else {
if (IS_NOT_NULL(region)) {
for (i = n - 1; i >= 0; i--) {
if (region->beg[nums[i]] != ONIG_REGION_NOTPOS)
return nums[i];
}
}
return nums[n - 1];
}
}
#else /* USE_NAMED_GROUP */
extern int
onig_name_to_group_numbers(regex_t* reg, const UChar* name,
const UChar* name_end, int** nums)
{
return ONIG_NO_SUPPORT_CONFIG;
}
extern int
onig_name_to_backref_number(regex_t* reg, const UChar* name,
const UChar* name_end, OnigRegion* region)
{
return ONIG_NO_SUPPORT_CONFIG;
}
extern int
onig_foreach_name(regex_t* reg,
int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*), void* arg)
{
return ONIG_NO_SUPPORT_CONFIG;
}
extern int
onig_number_of_names(regex_t* reg)
{
return 0;
}
#endif /* else USE_NAMED_GROUP */
extern int
onig_noname_group_capture_is_active(regex_t* reg)
{
if (ONIG_IS_OPTION_ON(reg->options, ONIG_OPTION_DONT_CAPTURE_GROUP))
return 0;
#ifdef USE_NAMED_GROUP
if (onig_number_of_names(reg) > 0 &&
IS_SYNTAX_BV(reg->syntax, ONIG_SYN_CAPTURE_ONLY_NAMED_GROUP) &&
!ONIG_IS_OPTION_ON(reg->options, ONIG_OPTION_CAPTURE_GROUP)) {
return 0;
}
#endif
return 1;
}
#define INIT_SCANENV_MEMNODES_ALLOC_SIZE 16
static void
scan_env_clear(ScanEnv* env)
{
int i;
BIT_STATUS_CLEAR(env->capture_history);
BIT_STATUS_CLEAR(env->bt_mem_start);
BIT_STATUS_CLEAR(env->bt_mem_end);
BIT_STATUS_CLEAR(env->backrefed_mem);
env->error = (UChar* )NULL;
env->error_end = (UChar* )NULL;
env->num_call = 0;
env->num_mem = 0;
#ifdef USE_NAMED_GROUP
env->num_named = 0;
#endif
env->mem_alloc = 0;
env->mem_nodes_dynamic = (Node** )NULL;
for (i = 0; i < SCANENV_MEMNODES_SIZE; i++)
env->mem_nodes_static[i] = NULL_NODE;
#ifdef USE_COMBINATION_EXPLOSION_CHECK
env->num_comb_exp_check = 0;
env->comb_exp_max_regnum = 0;
env->curr_max_regnum = 0;
env->has_recursion = 0;
#endif
env->parse_depth = 0;
}
static int
scan_env_add_mem_entry(ScanEnv* env)
{
int i, need, alloc;
Node** p;
need = env->num_mem + 1;
if (need > MaxCaptureNum && MaxCaptureNum != 0)
return ONIGERR_TOO_MANY_CAPTURES;
if (need >= SCANENV_MEMNODES_SIZE) {
if (env->mem_alloc <= need) {
if (IS_NULL(env->mem_nodes_dynamic)) {
alloc = INIT_SCANENV_MEMNODES_ALLOC_SIZE;
p = (Node** )xmalloc(sizeof(Node*) * alloc);
xmemcpy(p, env->mem_nodes_static,
sizeof(Node*) * SCANENV_MEMNODES_SIZE);
}
else {
alloc = env->mem_alloc * 2;
p = (Node** )xrealloc(env->mem_nodes_dynamic, sizeof(Node*) * alloc);
}
CHECK_NULL_RETURN_MEMERR(p);
for (i = env->num_mem + 1; i < alloc; i++)
p[i] = NULL_NODE;
env->mem_nodes_dynamic = p;
env->mem_alloc = alloc;
}
}
env->num_mem++;
return env->num_mem;
}
static int
scan_env_set_mem_node(ScanEnv* env, int num, Node* node)
{
if (env->num_mem >= num)
SCANENV_MEM_NODES(env)[num] = node;
else
return ONIGERR_PARSER_BUG;
return 0;
}
extern void
onig_node_free(Node* node)
{
start:
if (IS_NULL(node)) return ;
#ifdef DEBUG_NODE_FREE
fprintf(stderr, "onig_node_free: %p\n", node);
#endif
switch (NTYPE(node)) {
case NT_STR:
if (NSTR(node)->capa != 0 &&
IS_NOT_NULL(NSTR(node)->s) && NSTR(node)->s != NSTR(node)->buf) {
xfree(NSTR(node)->s);
}
break;
case NT_LIST:
case NT_ALT:
onig_node_free(NCAR(node));
{
Node* next_node = NCDR(node);
xfree(node);
node = next_node;
goto start;
}
break;
case NT_CCLASS:
{
CClassNode* cc = NCCLASS(node);
if (IS_NCCLASS_SHARE(cc)) return ;
if (cc->mbuf)
bbuf_free(cc->mbuf);
}
break;
case NT_QTFR:
if (NQTFR(node)->target)
onig_node_free(NQTFR(node)->target);
break;
case NT_ENCLOSE:
if (NENCLOSE(node)->target)
onig_node_free(NENCLOSE(node)->target);
break;
case NT_BREF:
if (IS_NOT_NULL(NBREF(node)->back_dynamic))
xfree(NBREF(node)->back_dynamic);
break;
case NT_ANCHOR:
if (NANCHOR(node)->target)
onig_node_free(NANCHOR(node)->target);
break;
}
xfree(node);
}
static Node*
node_new(void)
{
Node* node;
node = (Node* )xmalloc(sizeof(Node));
/* xmemset(node, 0, sizeof(Node)); */
#ifdef DEBUG_NODE_FREE
fprintf(stderr, "node_new: %p\n", node);
#endif
return node;
}
static void
initialize_cclass(CClassNode* cc)
{
BITSET_CLEAR(cc->bs);
/* cc->base.flags = 0; */
cc->flags = 0;
cc->mbuf = NULL;
}
static Node*
node_new_cclass(void)
{
Node* node = node_new();
CHECK_NULL_RETURN(node);
SET_NTYPE(node, NT_CCLASS);
initialize_cclass(NCCLASS(node));
return node;
}
static Node*
node_new_ctype(int type, int not)
{
Node* node = node_new();
CHECK_NULL_RETURN(node);
SET_NTYPE(node, NT_CTYPE);
NCTYPE(node)->ctype = type;
NCTYPE(node)->not = not;
return node;
}
static Node*
node_new_anychar(void)
{
Node* node = node_new();
CHECK_NULL_RETURN(node);
SET_NTYPE(node, NT_CANY);
return node;
}
static Node*
node_new_list(Node* left, Node* right)
{
Node* node = node_new();
CHECK_NULL_RETURN(node);
SET_NTYPE(node, NT_LIST);
NCAR(node) = left;
NCDR(node) = right;
return node;
}
extern Node*
onig_node_new_list(Node* left, Node* right)
{
return node_new_list(left, right);
}
extern Node*
onig_node_list_add(Node* list, Node* x)
{
Node *n;
n = onig_node_new_list(x, NULL);
if (IS_NULL(n)) return NULL_NODE;
if (IS_NOT_NULL(list)) {
while (IS_NOT_NULL(NCDR(list)))
list = NCDR(list);
NCDR(list) = n;
}
return n;
}
extern Node*
onig_node_new_alt(Node* left, Node* right)
{
Node* node = node_new();
CHECK_NULL_RETURN(node);
SET_NTYPE(node, NT_ALT);
NCAR(node) = left;
NCDR(node) = right;
return node;
}
extern Node*
onig_node_new_anchor(int type)
{
Node* node = node_new();
CHECK_NULL_RETURN(node);
SET_NTYPE(node, NT_ANCHOR);
NANCHOR(node)->type = type;
NANCHOR(node)->target = NULL;
NANCHOR(node)->char_len = -1;
return node;
}
static Node*
node_new_backref(int back_num, int* backrefs, int by_name,
#ifdef USE_BACKREF_WITH_LEVEL
int exist_level, int nest_level,
#endif
ScanEnv* env)
{
int i;
Node* node = node_new();
CHECK_NULL_RETURN(node);
SET_NTYPE(node, NT_BREF);
NBREF(node)->state = 0;
NBREF(node)->back_num = back_num;
NBREF(node)->back_dynamic = (int* )NULL;
if (by_name != 0)
NBREF(node)->state |= NST_NAME_REF;
#ifdef USE_BACKREF_WITH_LEVEL
if (exist_level != 0) {
NBREF(node)->state |= NST_NEST_LEVEL;
NBREF(node)->nest_level = nest_level;
}
#endif
for (i = 0; i < back_num; i++) {
if (backrefs[i] <= env->num_mem &&
IS_NULL(SCANENV_MEM_NODES(env)[backrefs[i]])) {
NBREF(node)->state |= NST_RECURSION; /* /...(\1).../ */
break;
}
}
if (back_num <= NODE_BACKREFS_SIZE) {
for (i = 0; i < back_num; i++)
NBREF(node)->back_static[i] = backrefs[i];
}
else {
int* p = (int* )xmalloc(sizeof(int) * back_num);
if (IS_NULL(p)) {
onig_node_free(node);
return NULL;
}
NBREF(node)->back_dynamic = p;
for (i = 0; i < back_num; i++)
p[i] = backrefs[i];
}
return node;
}
#ifdef USE_SUBEXP_CALL
static Node*
node_new_call(UChar* name, UChar* name_end, int gnum)
{
Node* node = node_new();
CHECK_NULL_RETURN(node);
SET_NTYPE(node, NT_CALL);
NCALL(node)->state = 0;
NCALL(node)->target = NULL_NODE;
NCALL(node)->name = name;
NCALL(node)->name_end = name_end;
NCALL(node)->group_num = gnum; /* call by number if gnum != 0 */
return node;
}
#endif
static Node*
node_new_quantifier(int lower, int upper, int by_number)
{
Node* node = node_new();
CHECK_NULL_RETURN(node);
SET_NTYPE(node, NT_QTFR);
NQTFR(node)->state = 0;
NQTFR(node)->target = NULL;
NQTFR(node)->lower = lower;
NQTFR(node)->upper = upper;
NQTFR(node)->greedy = 1;
NQTFR(node)->target_empty_info = NQ_TARGET_ISNOT_EMPTY;
NQTFR(node)->head_exact = NULL_NODE;
NQTFR(node)->next_head_exact = NULL_NODE;
NQTFR(node)->is_refered = 0;
if (by_number != 0)
NQTFR(node)->state |= NST_BY_NUMBER;
#ifdef USE_COMBINATION_EXPLOSION_CHECK
NQTFR(node)->comb_exp_check_num = 0;
#endif
return node;
}
static Node*
node_new_enclose(int type)
{
Node* node = node_new();
CHECK_NULL_RETURN(node);
SET_NTYPE(node, NT_ENCLOSE);
NENCLOSE(node)->type = type;
NENCLOSE(node)->state = 0;
NENCLOSE(node)->regnum = 0;
NENCLOSE(node)->option = 0;
NENCLOSE(node)->target = NULL;
NENCLOSE(node)->call_addr = -1;
NENCLOSE(node)->opt_count = 0;
return node;
}
extern Node*
onig_node_new_enclose(int type)
{
return node_new_enclose(type);
}
static Node*
node_new_enclose_memory(OnigOptionType option, int is_named)
{
Node* node = node_new_enclose(ENCLOSE_MEMORY);
CHECK_NULL_RETURN(node);
if (is_named != 0)
SET_ENCLOSE_STATUS(node, NST_NAMED_GROUP);
#ifdef USE_SUBEXP_CALL
NENCLOSE(node)->option = option;
#endif
return node;
}
static Node*
node_new_option(OnigOptionType option)
{
Node* node = node_new_enclose(ENCLOSE_OPTION);
CHECK_NULL_RETURN(node);
NENCLOSE(node)->option = option;
return node;
}
extern int
onig_node_str_cat(Node* node, const UChar* s, const UChar* end)
{
int addlen = end - s;
if (addlen > 0) {
int len = NSTR(node)->end - NSTR(node)->s;
if (NSTR(node)->capa > 0 || (len + addlen > NODE_STR_BUF_SIZE - 1)) {
UChar* p;
int capa = len + addlen + NODE_STR_MARGIN;
if (capa <= NSTR(node)->capa) {
onig_strcpy(NSTR(node)->s + len, s, end);
}
else {
if (NSTR(node)->s == NSTR(node)->buf)
p = strcat_capa_from_static(NSTR(node)->s, NSTR(node)->end,
s, end, capa);
else
p = strcat_capa(NSTR(node)->s, NSTR(node)->end, s, end, capa);
CHECK_NULL_RETURN_MEMERR(p);
NSTR(node)->s = p;
NSTR(node)->capa = capa;
}
}
else {
onig_strcpy(NSTR(node)->s + len, s, end);
}
NSTR(node)->end = NSTR(node)->s + len + addlen;
}
return 0;
}
extern int
onig_node_str_set(Node* node, const UChar* s, const UChar* end)
{
onig_node_str_clear(node);
return onig_node_str_cat(node, s, end);
}
static int
node_str_cat_char(Node* node, UChar c)
{
UChar s[1];
s[0] = c;
return onig_node_str_cat(node, s, s + 1);
}
extern void
onig_node_conv_to_str_node(Node* node, int flag)
{
SET_NTYPE(node, NT_STR);
NSTR(node)->flag = flag;
NSTR(node)->capa = 0;
NSTR(node)->s = NSTR(node)->buf;
NSTR(node)->end = NSTR(node)->buf;
}
extern void
onig_node_str_clear(Node* node)
{
if (NSTR(node)->capa != 0 &&
IS_NOT_NULL(NSTR(node)->s) && NSTR(node)->s != NSTR(node)->buf) {
xfree(NSTR(node)->s);
}
NSTR(node)->capa = 0;
NSTR(node)->flag = 0;
NSTR(node)->s = NSTR(node)->buf;
NSTR(node)->end = NSTR(node)->buf;
}
static Node*
node_new_str(const UChar* s, const UChar* end)
{
Node* node = node_new();
CHECK_NULL_RETURN(node);
SET_NTYPE(node, NT_STR);
NSTR(node)->capa = 0;
NSTR(node)->flag = 0;
NSTR(node)->s = NSTR(node)->buf;
NSTR(node)->end = NSTR(node)->buf;
if (onig_node_str_cat(node, s, end)) {
onig_node_free(node);
return NULL;
}
return node;
}
extern Node*
onig_node_new_str(const UChar* s, const UChar* end)
{
return node_new_str(s, end);
}
static Node*
node_new_str_raw(UChar* s, UChar* end)
{
Node* node = node_new_str(s, end);
NSTRING_SET_RAW(node);
return node;
}
static Node*
node_new_empty(void)
{
return node_new_str(NULL, NULL);
}
static Node*
node_new_str_raw_char(UChar c)
{
UChar p[1];
p[0] = c;
return node_new_str_raw(p, p + 1);
}
static Node*
str_node_split_last_char(StrNode* sn, OnigEncoding enc)
{
const UChar *p;
Node* n = NULL_NODE;
if (sn->end > sn->s) {
p = onigenc_get_prev_char_head(enc, sn->s, sn->end);
if (p && p > sn->s) { /* can be split. */
n = node_new_str(p, sn->end);
if ((sn->flag & NSTR_RAW) != 0)
NSTRING_SET_RAW(n);
sn->end = (UChar* )p;
}
}
return n;
}
static int
str_node_can_be_split(StrNode* sn, OnigEncoding enc)
{
if (sn->end > sn->s) {
return ((enclen(enc, sn->s) < sn->end - sn->s) ? 1 : 0);
}
return 0;
}
#ifdef USE_PAD_TO_SHORT_BYTE_CHAR
static int
node_str_head_pad(StrNode* sn, int num, UChar val)
{
UChar buf[NODE_STR_BUF_SIZE];
int i, len;
len = sn->end - sn->s;
onig_strcpy(buf, sn->s, sn->end);
onig_strcpy(&(sn->s[num]), buf, buf + len);
sn->end += num;
for (i = 0; i < num; i++) {
sn->s[i] = val;
}
}
#endif
extern int
onig_scan_unsigned_number(UChar** src, const UChar* end, OnigEncoding enc)
{
unsigned int num, val;
OnigCodePoint c;
UChar* p = *src;
PFETCH_READY;
num = 0;
while (!PEND) {
PFETCH(c);
if (ONIGENC_IS_CODE_DIGIT(enc, c)) {
val = (unsigned int )DIGITVAL(c);
if ((INT_MAX_LIMIT - val) / 10UL < num)
return -1; /* overflow */
num = num * 10 + val;
}
else {
PUNFETCH;
break;
}
}
*src = p;
return num;
}
static int
scan_unsigned_hexadecimal_number(UChar** src, UChar* end, int maxlen,
OnigEncoding enc)
{
OnigCodePoint c;
unsigned int num, val;
UChar* p = *src;
PFETCH_READY;
num = 0;
while (! PEND && maxlen-- != 0) {
PFETCH(c);
if (ONIGENC_IS_CODE_XDIGIT(enc, c)) {
val = (unsigned int )XDIGITVAL(enc,c);
if ((INT_MAX_LIMIT - val) / 16UL < num)
return -1; /* overflow */
num = (num << 4) + XDIGITVAL(enc,c);
}
else {
PUNFETCH;
break;
}
}
*src = p;
return num;
}
static int
scan_unsigned_octal_number(UChar** src, UChar* end, int maxlen,
OnigEncoding enc)
{
OnigCodePoint c;
unsigned int num, val;
UChar* p = *src;
PFETCH_READY;
num = 0;
while (!PEND && maxlen-- != 0) {
PFETCH(c);
if (ONIGENC_IS_CODE_DIGIT(enc, c) && c < '8') {
val = ODIGITVAL(c);
if ((INT_MAX_LIMIT - val) / 8UL < num)
return -1; /* overflow */
num = (num << 3) + val;
}
else {
PUNFETCH;
break;
}
}
*src = p;
return num;
}
#define BBUF_WRITE_CODE_POINT(bbuf,pos,code) \
BBUF_WRITE(bbuf, pos, &(code), SIZE_CODE_POINT)
/* data format:
[n][from-1][to-1][from-2][to-2] ... [from-n][to-n]
(all data size is OnigCodePoint)
*/
static int
new_code_range(BBuf** pbuf)
{
#define INIT_MULTI_BYTE_RANGE_SIZE (SIZE_CODE_POINT * 5)
int r;
OnigCodePoint n;
BBuf* bbuf;
bbuf = *pbuf = (BBuf* )xmalloc(sizeof(BBuf));
CHECK_NULL_RETURN_MEMERR(*pbuf);
r = BBUF_INIT(*pbuf, INIT_MULTI_BYTE_RANGE_SIZE);
if (r) return r;
n = 0;
BBUF_WRITE_CODE_POINT(bbuf, 0, n);
return 0;
}
static int
add_code_range_to_buf(BBuf** pbuf, OnigCodePoint from, OnigCodePoint to)
{
int r, inc_n, pos;
int low, high, bound, x;
OnigCodePoint n, *data;
BBuf* bbuf;
if (from > to) {
n = from; from = to; to = n;
}
if (IS_NULL(*pbuf)) {
r = new_code_range(pbuf);
if (r) return r;
bbuf = *pbuf;
n = 0;
}
else {
bbuf = *pbuf;
GET_CODE_POINT(n, bbuf->p);
}
data = (OnigCodePoint* )(bbuf->p);
data++;
for (low = 0, bound = n; low < bound; ) {
x = (low + bound) >> 1;
if (from > data[x*2 + 1])
low = x + 1;
else
bound = x;
}
high = (to == ~((OnigCodePoint )0)) ? n : low;
for (bound = n; high < bound; ) {
x = (high + bound) >> 1;
if (to + 1 >= data[x*2])
high = x + 1;
else
bound = x;
}
inc_n = low + 1 - high;
if (n + inc_n > ONIG_MAX_MULTI_BYTE_RANGES_NUM)
return ONIGERR_TOO_MANY_MULTI_BYTE_RANGES;
if (inc_n != 1) {
if (from > data[low*2])
from = data[low*2];
if (to < data[(high - 1)*2 + 1])
to = data[(high - 1)*2 + 1];
}
if (inc_n != 0 && (OnigCodePoint )high < n) {
int from_pos = SIZE_CODE_POINT * (1 + high * 2);
int to_pos = SIZE_CODE_POINT * (1 + (low + 1) * 2);
int size = (n - high) * 2 * SIZE_CODE_POINT;
if (inc_n > 0) {
BBUF_MOVE_RIGHT(bbuf, from_pos, to_pos, size);
}
else {
BBUF_MOVE_LEFT_REDUCE(bbuf, from_pos, to_pos);
}
}
pos = SIZE_CODE_POINT * (1 + low * 2);
BBUF_ENSURE_SIZE(bbuf, pos + SIZE_CODE_POINT * 2);
BBUF_WRITE_CODE_POINT(bbuf, pos, from);
BBUF_WRITE_CODE_POINT(bbuf, pos + SIZE_CODE_POINT, to);
n += inc_n;
BBUF_WRITE_CODE_POINT(bbuf, 0, n);
return 0;
}
static int
add_code_range(BBuf** pbuf, ScanEnv* env, OnigCodePoint from, OnigCodePoint to)
{
if (from > to) {
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC))
return 0;
else
return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS;
}
return add_code_range_to_buf(pbuf, from, to);
}
static int
not_code_range_buf(OnigEncoding enc, BBuf* bbuf, BBuf** pbuf)
{
int r, i, n;
OnigCodePoint pre, from, *data, to = 0;
*pbuf = (BBuf* )NULL;
if (IS_NULL(bbuf)) {
set_all:
return SET_ALL_MULTI_BYTE_RANGE(enc, pbuf);
}
data = (OnigCodePoint* )(bbuf->p);
GET_CODE_POINT(n, data);
data++;
if (n <= 0) goto set_all;
r = 0;
pre = MBCODE_START_POS(enc);
for (i = 0; i < n; i++) {
from = data[i*2];
to = data[i*2+1];
if (pre <= from - 1) {
r = add_code_range_to_buf(pbuf, pre, from - 1);
if (r != 0) return r;
}
if (to == ~((OnigCodePoint )0)) break;
pre = to + 1;
}
if (to < ~((OnigCodePoint )0)) {
r = add_code_range_to_buf(pbuf, to + 1, ~((OnigCodePoint )0));
}
return r;
}
#define SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2) do {\
BBuf *tbuf; \
int tnot; \
tnot = not1; not1 = not2; not2 = tnot; \
tbuf = bbuf1; bbuf1 = bbuf2; bbuf2 = tbuf; \
} while (0)
static int
or_code_range_buf(OnigEncoding enc, BBuf* bbuf1, int not1,
BBuf* bbuf2, int not2, BBuf** pbuf)
{
int r;
OnigCodePoint i, n1, *data1;
OnigCodePoint from, to;
*pbuf = (BBuf* )NULL;
if (IS_NULL(bbuf1) && IS_NULL(bbuf2)) {
if (not1 != 0 || not2 != 0)
return SET_ALL_MULTI_BYTE_RANGE(enc, pbuf);
return 0;
}
r = 0;
if (IS_NULL(bbuf2))
SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2);
if (IS_NULL(bbuf1)) {
if (not1 != 0) {
return SET_ALL_MULTI_BYTE_RANGE(enc, pbuf);
}
else {
if (not2 == 0) {
return bbuf_clone(pbuf, bbuf2);
}
else {
return not_code_range_buf(enc, bbuf2, pbuf);
}
}
}
if (not1 != 0)
SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2);
data1 = (OnigCodePoint* )(bbuf1->p);
GET_CODE_POINT(n1, data1);
data1++;
if (not2 == 0 && not1 == 0) { /* 1 OR 2 */
r = bbuf_clone(pbuf, bbuf2);
}
else if (not1 == 0) { /* 1 OR (not 2) */
r = not_code_range_buf(enc, bbuf2, pbuf);
}
if (r != 0) return r;
for (i = 0; i < n1; i++) {
from = data1[i*2];
to = data1[i*2+1];
r = add_code_range_to_buf(pbuf, from, to);
if (r != 0) return r;
}
return 0;
}
static int
and_code_range1(BBuf** pbuf, OnigCodePoint from1, OnigCodePoint to1,
OnigCodePoint* data, int n)
{
int i, r;
OnigCodePoint from2, to2;
for (i = 0; i < n; i++) {
from2 = data[i*2];
to2 = data[i*2+1];
if (from2 < from1) {
if (to2 < from1) continue;
else {
from1 = to2 + 1;
}
}
else if (from2 <= to1) {
if (to2 < to1) {
if (from1 <= from2 - 1) {
r = add_code_range_to_buf(pbuf, from1, from2-1);
if (r != 0) return r;
}
from1 = to2 + 1;
}
else {
to1 = from2 - 1;
}
}
else {
from1 = from2;
}
if (from1 > to1) break;
}
if (from1 <= to1) {
r = add_code_range_to_buf(pbuf, from1, to1);
if (r != 0) return r;
}
return 0;
}
static int
and_code_range_buf(BBuf* bbuf1, int not1, BBuf* bbuf2, int not2, BBuf** pbuf)
{
int r;
OnigCodePoint i, j, n1, n2, *data1, *data2;
OnigCodePoint from, to, from1, to1, from2, to2;
*pbuf = (BBuf* )NULL;
if (IS_NULL(bbuf1)) {
if (not1 != 0 && IS_NOT_NULL(bbuf2)) /* not1 != 0 -> not2 == 0 */
return bbuf_clone(pbuf, bbuf2);
return 0;
}
else if (IS_NULL(bbuf2)) {
if (not2 != 0)
return bbuf_clone(pbuf, bbuf1);
return 0;
}
if (not1 != 0)
SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2);
data1 = (OnigCodePoint* )(bbuf1->p);
data2 = (OnigCodePoint* )(bbuf2->p);
GET_CODE_POINT(n1, data1);
GET_CODE_POINT(n2, data2);
data1++;
data2++;
if (not2 == 0 && not1 == 0) { /* 1 AND 2 */
for (i = 0; i < n1; i++) {
from1 = data1[i*2];
to1 = data1[i*2+1];
for (j = 0; j < n2; j++) {
from2 = data2[j*2];
to2 = data2[j*2+1];
if (from2 > to1) break;
if (to2 < from1) continue;
from = MAX(from1, from2);
to = MIN(to1, to2);
r = add_code_range_to_buf(pbuf, from, to);
if (r != 0) return r;
}
}
}
else if (not1 == 0) { /* 1 AND (not 2) */
for (i = 0; i < n1; i++) {
from1 = data1[i*2];
to1 = data1[i*2+1];
r = and_code_range1(pbuf, from1, to1, data2, n2);
if (r != 0) return r;
}
}
return 0;
}
static int
and_cclass(CClassNode* dest, CClassNode* cc, OnigEncoding enc)
{
int r, not1, not2;
BBuf *buf1, *buf2, *pbuf;
BitSetRef bsr1, bsr2;
BitSet bs1, bs2;
not1 = IS_NCCLASS_NOT(dest);
bsr1 = dest->bs;
buf1 = dest->mbuf;
not2 = IS_NCCLASS_NOT(cc);
bsr2 = cc->bs;
buf2 = cc->mbuf;
if (not1 != 0) {
bitset_invert_to(bsr1, bs1);
bsr1 = bs1;
}
if (not2 != 0) {
bitset_invert_to(bsr2, bs2);
bsr2 = bs2;
}
bitset_and(bsr1, bsr2);
if (bsr1 != dest->bs) {
bitset_copy(dest->bs, bsr1);
bsr1 = dest->bs;
}
if (not1 != 0) {
bitset_invert(dest->bs);
}
if (! ONIGENC_IS_SINGLEBYTE(enc)) {
if (not1 != 0 && not2 != 0) {
r = or_code_range_buf(enc, buf1, 0, buf2, 0, &pbuf);
}
else {
r = and_code_range_buf(buf1, not1, buf2, not2, &pbuf);
if (r == 0 && not1 != 0) {
BBuf *tbuf;
r = not_code_range_buf(enc, pbuf, &tbuf);
if (r != 0) {
bbuf_free(pbuf);
return r;
}
bbuf_free(pbuf);
pbuf = tbuf;
}
}
if (r != 0) return r;
dest->mbuf = pbuf;
bbuf_free(buf1);
return r;
}
return 0;
}
static int
or_cclass(CClassNode* dest, CClassNode* cc, OnigEncoding enc)
{
int r, not1, not2;
BBuf *buf1, *buf2, *pbuf;
BitSetRef bsr1, bsr2;
BitSet bs1, bs2;
not1 = IS_NCCLASS_NOT(dest);
bsr1 = dest->bs;
buf1 = dest->mbuf;
not2 = IS_NCCLASS_NOT(cc);
bsr2 = cc->bs;
buf2 = cc->mbuf;
if (not1 != 0) {
bitset_invert_to(bsr1, bs1);
bsr1 = bs1;
}
if (not2 != 0) {
bitset_invert_to(bsr2, bs2);
bsr2 = bs2;
}
bitset_or(bsr1, bsr2);
if (bsr1 != dest->bs) {
bitset_copy(dest->bs, bsr1);
bsr1 = dest->bs;
}
if (not1 != 0) {
bitset_invert(dest->bs);
}
if (! ONIGENC_IS_SINGLEBYTE(enc)) {
if (not1 != 0 && not2 != 0) {
r = and_code_range_buf(buf1, 0, buf2, 0, &pbuf);
}
else {
r = or_code_range_buf(enc, buf1, not1, buf2, not2, &pbuf);
if (r == 0 && not1 != 0) {
BBuf *tbuf;
r = not_code_range_buf(enc, pbuf, &tbuf);
if (r != 0) {
bbuf_free(pbuf);
return r;
}
bbuf_free(pbuf);
pbuf = tbuf;
}
}
if (r != 0) return r;
dest->mbuf = pbuf;
bbuf_free(buf1);
return r;
}
else
return 0;
}
static OnigCodePoint
conv_backslash_value(OnigCodePoint c, ScanEnv* env)
{
if (IS_SYNTAX_OP(env->syntax, ONIG_SYN_OP_ESC_CONTROL_CHARS)) {
switch (c) {
case 'n': return '\n';
case 't': return '\t';
case 'r': return '\r';
case 'f': return '\f';
case 'a': return '\007';
case 'b': return '\010';
case 'e': return '\033';
case 'v':
if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ESC_V_VTAB))
return '\v';
break;
default:
break;
}
}
return c;
}
static int
is_invalid_quantifier_target(Node* node)
{
switch (NTYPE(node)) {
case NT_ANCHOR:
return 1;
break;
case NT_ENCLOSE:
/* allow enclosed elements */
/* return is_invalid_quantifier_target(NENCLOSE(node)->target); */
break;
case NT_LIST:
do {
if (! is_invalid_quantifier_target(NCAR(node))) return 0;
} while (IS_NOT_NULL(node = NCDR(node)));
return 0;
break;
case NT_ALT:
do {
if (is_invalid_quantifier_target(NCAR(node))) return 1;
} while (IS_NOT_NULL(node = NCDR(node)));
break;
default:
break;
}
return 0;
}
/* ?:0, *:1, +:2, ??:3, *?:4, +?:5 */
static int
popular_quantifier_num(QtfrNode* q)
{
if (q->greedy) {
if (q->lower == 0) {
if (q->upper == 1) return 0;
else if (IS_REPEAT_INFINITE(q->upper)) return 1;
}
else if (q->lower == 1) {
if (IS_REPEAT_INFINITE(q->upper)) return 2;
}
}
else {
if (q->lower == 0) {
if (q->upper == 1) return 3;
else if (IS_REPEAT_INFINITE(q->upper)) return 4;
}
else if (q->lower == 1) {
if (IS_REPEAT_INFINITE(q->upper)) return 5;
}
}
return -1;
}
enum ReduceType {
RQ_ASIS = 0, /* as is */
RQ_DEL = 1, /* delete parent */
RQ_A, /* to '*' */
RQ_AQ, /* to '*?' */
RQ_QQ, /* to '??' */
RQ_P_QQ, /* to '+)??' */
RQ_PQ_Q /* to '+?)?' */
};
static enum ReduceType ReduceTypeTable[6][6] = {
{RQ_DEL, RQ_A, RQ_A, RQ_QQ, RQ_AQ, RQ_ASIS}, /* '?' */
{RQ_DEL, RQ_DEL, RQ_DEL, RQ_P_QQ, RQ_P_QQ, RQ_DEL}, /* '*' */
{RQ_A, RQ_A, RQ_DEL, RQ_ASIS, RQ_P_QQ, RQ_DEL}, /* '+' */
{RQ_DEL, RQ_AQ, RQ_AQ, RQ_DEL, RQ_AQ, RQ_AQ}, /* '??' */
{RQ_DEL, RQ_DEL, RQ_DEL, RQ_DEL, RQ_DEL, RQ_DEL}, /* '*?' */
{RQ_ASIS, RQ_PQ_Q, RQ_DEL, RQ_AQ, RQ_AQ, RQ_DEL} /* '+?' */
};
extern void
onig_reduce_nested_quantifier(Node* pnode, Node* cnode)
{
int pnum, cnum;
QtfrNode *p, *c;
p = NQTFR(pnode);
c = NQTFR(cnode);
pnum = popular_quantifier_num(p);
cnum = popular_quantifier_num(c);
if (pnum < 0 || cnum < 0) return ;
switch(ReduceTypeTable[cnum][pnum]) {
case RQ_DEL:
*pnode = *cnode;
break;
case RQ_A:
p->target = c->target;
p->lower = 0; p->upper = REPEAT_INFINITE; p->greedy = 1;
break;
case RQ_AQ:
p->target = c->target;
p->lower = 0; p->upper = REPEAT_INFINITE; p->greedy = 0;
break;
case RQ_QQ:
p->target = c->target;
p->lower = 0; p->upper = 1; p->greedy = 0;
break;
case RQ_P_QQ:
p->target = cnode;
p->lower = 0; p->upper = 1; p->greedy = 0;
c->lower = 1; c->upper = REPEAT_INFINITE; c->greedy = 1;
return ;
break;
case RQ_PQ_Q:
p->target = cnode;
p->lower = 0; p->upper = 1; p->greedy = 1;
c->lower = 1; c->upper = REPEAT_INFINITE; c->greedy = 0;
return ;
break;
case RQ_ASIS:
p->target = cnode;
return ;
break;
}
c->target = NULL_NODE;
onig_node_free(cnode);
}
enum TokenSyms {
TK_EOT = 0, /* end of token */
TK_RAW_BYTE = 1,
TK_CHAR,
TK_STRING,
TK_CODE_POINT,
TK_ANYCHAR,
TK_CHAR_TYPE,
TK_BACKREF,
TK_CALL,
TK_ANCHOR,
TK_OP_REPEAT,
TK_INTERVAL,
TK_ANYCHAR_ANYTIME, /* SQL '%' == .* */
TK_ALT,
TK_SUBEXP_OPEN,
TK_SUBEXP_CLOSE,
TK_CC_OPEN,
TK_QUOTE_OPEN,
TK_CHAR_PROPERTY, /* \p{...}, \P{...} */
/* in cc */
TK_CC_CLOSE,
TK_CC_RANGE,
TK_POSIX_BRACKET_OPEN,
TK_CC_AND, /* && */
TK_CC_CC_OPEN /* [ */
};
typedef struct {
enum TokenSyms type;
int escaped;
int base; /* is number: 8, 16 (used in [....]) */
UChar* backp;
union {
UChar* s;
int c;
OnigCodePoint code;
int anchor;
int subtype;
struct {
int lower;
int upper;
int greedy;
int possessive;
} repeat;
struct {
int num;
int ref1;
int* refs;
int by_name;
#ifdef USE_BACKREF_WITH_LEVEL
int exist_level;
int level; /* \k<name+n> */
#endif
} backref;
struct {
UChar* name;
UChar* name_end;
int gnum;
} call;
struct {
int ctype;
int not;
} prop;
} u;
} OnigToken;
static int
fetch_range_quantifier(UChar** src, UChar* end, OnigToken* tok, ScanEnv* env)
{
int low, up, syn_allow, non_low = 0;
int r = 0;
OnigCodePoint c;
OnigEncoding enc = env->enc;
UChar* p = *src;
PFETCH_READY;
syn_allow = IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_INVALID_INTERVAL);
if (PEND) {
if (syn_allow)
return 1; /* "....{" : OK! */
else
return ONIGERR_END_PATTERN_AT_LEFT_BRACE; /* "....{" syntax error */
}
if (! syn_allow) {
c = PPEEK;
if (c == ')' || c == '(' || c == '|') {
return ONIGERR_END_PATTERN_AT_LEFT_BRACE;
}
}
low = onig_scan_unsigned_number(&p, end, env->enc);
if (low < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE;
if (low > ONIG_MAX_REPEAT_NUM)
return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE;
if (p == *src) { /* can't read low */
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_INTERVAL_LOW_ABBREV)) {
/* allow {,n} as {0,n} */
low = 0;
non_low = 1;
}
else
goto invalid;
}
if (PEND) goto invalid;
PFETCH(c);
if (c == ',') {
UChar* prev = p;
up = onig_scan_unsigned_number(&p, end, env->enc);
if (up < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE;
if (up > ONIG_MAX_REPEAT_NUM)
return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE;
if (p == prev) {
if (non_low != 0)
goto invalid;
up = REPEAT_INFINITE; /* {n,} : {n,infinite} */
}
}
else {
if (non_low != 0)
goto invalid;
PUNFETCH;
up = low; /* {n} : exact n times */
r = 2; /* fixed */
}
if (PEND) goto invalid;
PFETCH(c);
if (IS_SYNTAX_OP(env->syntax, ONIG_SYN_OP_ESC_BRACE_INTERVAL)) {
if (c != MC_ESC(env->syntax)) goto invalid;
PFETCH(c);
}
if (c != '}') goto invalid;
if (!IS_REPEAT_INFINITE(up) && low > up) {
return ONIGERR_UPPER_SMALLER_THAN_LOWER_IN_REPEAT_RANGE;
}
tok->type = TK_INTERVAL;
tok->u.repeat.lower = low;
tok->u.repeat.upper = up;
*src = p;
return r; /* 0: normal {n,m}, 2: fixed {n} */
invalid:
if (syn_allow) {
/* *src = p; */ /* !!! Don't do this line !!! */
return 1; /* OK */
}
else
return ONIGERR_INVALID_REPEAT_RANGE_PATTERN;
}
/* \M-, \C-, \c, or \... */
static int
fetch_escaped_value(UChar** src, UChar* end, ScanEnv* env, OnigCodePoint* val)
{
int v;
OnigCodePoint c;
OnigEncoding enc = env->enc;
UChar* p = *src;
if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE;
PFETCH_S(c);
switch (c) {
case 'M':
if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ESC_CAPITAL_M_BAR_META)) {
if (PEND) return ONIGERR_END_PATTERN_AT_META;
PFETCH_S(c);
if (c != '-') return ONIGERR_META_CODE_SYNTAX;
if (PEND) return ONIGERR_END_PATTERN_AT_META;
PFETCH_S(c);
if (c == MC_ESC(env->syntax)) {
v = fetch_escaped_value(&p, end, env, &c);
if (v < 0) return v;
}
c = ((c & 0xff) | 0x80);
}
else
goto backslash;
break;
case 'C':
if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ESC_CAPITAL_C_BAR_CONTROL)) {
if (PEND) return ONIGERR_END_PATTERN_AT_CONTROL;
PFETCH_S(c);
if (c != '-') return ONIGERR_CONTROL_CODE_SYNTAX;
goto control;
}
else
goto backslash;
case 'c':
if (IS_SYNTAX_OP(env->syntax, ONIG_SYN_OP_ESC_C_CONTROL)) {
control:
if (PEND) return ONIGERR_END_PATTERN_AT_CONTROL;
PFETCH_S(c);
if (c == '?') {
c = 0177;
}
else {
if (c == MC_ESC(env->syntax)) {
v = fetch_escaped_value(&p, end, env, &c);
if (v < 0) return v;
}
c &= 0x9f;
}
break;
}
/* fall through */
default:
{
backslash:
c = conv_backslash_value(c, env);
}
break;
}
*src = p;
*val = c;
return 0;
}
static int fetch_token(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env);
static OnigCodePoint
get_name_end_code_point(OnigCodePoint start)
{
switch (start) {
case '<': return (OnigCodePoint )'>'; break;
case '\'': return (OnigCodePoint )'\''; break;
default:
break;
}
return (OnigCodePoint )0;
}
#ifdef USE_NAMED_GROUP
#ifdef USE_BACKREF_WITH_LEVEL
/*
\k<name+n>, \k<name-n>
\k<num+n>, \k<num-n>
\k<-num+n>, \k<-num-n>
*/
static int
fetch_name_with_level(OnigCodePoint start_code, UChar** src, UChar* end,
UChar** rname_end, ScanEnv* env,
int* rback_num, int* rlevel)
{
int r, sign, is_num, exist_level;
OnigCodePoint end_code;
OnigCodePoint c = 0;
OnigEncoding enc = env->enc;
UChar *name_end;
UChar *pnum_head;
UChar *p = *src;
PFETCH_READY;
*rback_num = 0;
is_num = exist_level = 0;
sign = 1;
pnum_head = *src;
end_code = get_name_end_code_point(start_code);
name_end = end;
r = 0;
if (PEND) {
return ONIGERR_EMPTY_GROUP_NAME;
}
else {
PFETCH(c);
if (c == end_code)
return ONIGERR_EMPTY_GROUP_NAME;
if (ONIGENC_IS_CODE_DIGIT(enc, c)) {
is_num = 1;
}
else if (c == '-') {
is_num = 2;
sign = -1;
pnum_head = p;
}
else if (!ONIGENC_IS_CODE_WORD(enc, c)) {
r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME;
}
}
while (!PEND) {
name_end = p;
PFETCH(c);
if (c == end_code || c == ')' || c == '+' || c == '-') {
if (is_num == 2) r = ONIGERR_INVALID_GROUP_NAME;
break;
}
if (is_num != 0) {
if (ONIGENC_IS_CODE_DIGIT(enc, c)) {
is_num = 1;
}
else {
r = ONIGERR_INVALID_GROUP_NAME;
is_num = 0;
}
}
else if (!ONIGENC_IS_CODE_WORD(enc, c)) {
r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME;
}
}
if (r == 0 && c != end_code) {
if (c == '+' || c == '-') {
int level;
int flag = (c == '-' ? -1 : 1);
if (PEND) {
r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME;
goto end;
}
PFETCH(c);
if (! ONIGENC_IS_CODE_DIGIT(enc, c)) goto err;
PUNFETCH;
level = onig_scan_unsigned_number(&p, end, enc);
if (level < 0) return ONIGERR_TOO_BIG_NUMBER;
*rlevel = (level * flag);
exist_level = 1;
if (!PEND) {
PFETCH(c);
if (c == end_code)
goto end;
}
}
err:
r = ONIGERR_INVALID_GROUP_NAME;
name_end = end;
}
end:
if (r == 0) {
if (is_num != 0) {
*rback_num = onig_scan_unsigned_number(&pnum_head, name_end, enc);
if (*rback_num < 0) return ONIGERR_TOO_BIG_NUMBER;
else if (*rback_num == 0) goto err;
*rback_num *= sign;
}
*rname_end = name_end;
*src = p;
return (exist_level ? 1 : 0);
}
else {
onig_scan_env_set_error_string(env, r, *src, name_end);
return r;
}
}
#endif /* USE_BACKREF_WITH_LEVEL */
/*
ref: 0 -> define name (don't allow number name)
1 -> reference name (allow number name)
*/
static int
fetch_name(OnigCodePoint start_code, UChar** src, UChar* end,
UChar** rname_end, ScanEnv* env, int* rback_num, int ref)
{
int r, is_num, sign;
OnigCodePoint end_code;
OnigCodePoint c = 0;
OnigEncoding enc = env->enc;
UChar *name_end;
UChar *pnum_head;
UChar *p = *src;
*rback_num = 0;
end_code = get_name_end_code_point(start_code);
name_end = end;
pnum_head = *src;
r = 0;
is_num = 0;
sign = 1;
if (PEND) {
return ONIGERR_EMPTY_GROUP_NAME;
}
else {
PFETCH_S(c);
if (c == end_code)
return ONIGERR_EMPTY_GROUP_NAME;
if (ONIGENC_IS_CODE_DIGIT(enc, c)) {
if (ref == 1)
is_num = 1;
else {
r = ONIGERR_INVALID_GROUP_NAME;
is_num = 0;
}
}
else if (c == '-') {
if (ref == 1) {
is_num = 2;
sign = -1;
pnum_head = p;
}
else {
r = ONIGERR_INVALID_GROUP_NAME;
is_num = 0;
}
}
else if (!ONIGENC_IS_CODE_WORD(enc, c)) {
r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME;
}
}
if (r == 0) {
while (!PEND) {
name_end = p;
PFETCH_S(c);
if (c == end_code || c == ')') {
if (is_num == 2) r = ONIGERR_INVALID_GROUP_NAME;
break;
}
if (is_num != 0) {
if (ONIGENC_IS_CODE_DIGIT(enc, c)) {
is_num = 1;
}
else {
if (!ONIGENC_IS_CODE_WORD(enc, c))
r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME;
else
r = ONIGERR_INVALID_GROUP_NAME;
is_num = 0;
}
}
else {
if (!ONIGENC_IS_CODE_WORD(enc, c)) {
r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME;
}
}
}
if (c != end_code) {
r = ONIGERR_INVALID_GROUP_NAME;
name_end = end;
}
if (is_num != 0) {
*rback_num = onig_scan_unsigned_number(&pnum_head, name_end, enc);
if (*rback_num < 0) return ONIGERR_TOO_BIG_NUMBER;
else if (*rback_num == 0) {
r = ONIGERR_INVALID_GROUP_NAME;
goto err;
}
*rback_num *= sign;
}
*rname_end = name_end;
*src = p;
return 0;
}
else {
while (!PEND) {
name_end = p;
PFETCH_S(c);
if (c == end_code || c == ')')
break;
}
if (PEND)
name_end = end;
err:
onig_scan_env_set_error_string(env, r, *src, name_end);
return r;
}
}
#else
static int
fetch_name(OnigCodePoint start_code, UChar** src, UChar* end,
UChar** rname_end, ScanEnv* env, int* rback_num, int ref)
{
int r, is_num, sign;
OnigCodePoint end_code;
OnigCodePoint c = 0;
UChar *name_end;
OnigEncoding enc = env->enc;
UChar *pnum_head;
UChar *p = *src;
PFETCH_READY;
*rback_num = 0;
end_code = get_name_end_code_point(start_code);
*rname_end = name_end = end;
r = 0;
pnum_head = *src;
is_num = 0;
sign = 1;
if (PEND) {
return ONIGERR_EMPTY_GROUP_NAME;
}
else {
PFETCH(c);
if (c == end_code)
return ONIGERR_EMPTY_GROUP_NAME;
if (ONIGENC_IS_CODE_DIGIT(enc, c)) {
is_num = 1;
}
else if (c == '-') {
is_num = 2;
sign = -1;
pnum_head = p;
}
else {
r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME;
}
}
while (!PEND) {
name_end = p;
PFETCH(c);
if (c == end_code || c == ')') break;
if (! ONIGENC_IS_CODE_DIGIT(enc, c))
r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME;
}
if (r == 0 && c != end_code) {
r = ONIGERR_INVALID_GROUP_NAME;
name_end = end;
}
if (r == 0) {
*rback_num = onig_scan_unsigned_number(&pnum_head, name_end, enc);
if (*rback_num < 0) return ONIGERR_TOO_BIG_NUMBER;
else if (*rback_num == 0) {
r = ONIGERR_INVALID_GROUP_NAME;
goto err;
}
*rback_num *= sign;
*rname_end = name_end;
*src = p;
return 0;
}
else {
err:
onig_scan_env_set_error_string(env, r, *src, name_end);
return r;
}
}
#endif /* USE_NAMED_GROUP */
static void
CC_ESC_WARN(ScanEnv* env, UChar *c)
{
if (onig_warn == onig_null_warn) return ;
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_WARN_CC_OP_NOT_ESCAPED) &&
IS_SYNTAX_BV(env->syntax, ONIG_SYN_BACKSLASH_ESCAPE_IN_CC)) {
UChar buf[WARN_BUFSIZE];
onig_snprintf_with_pattern(buf, WARN_BUFSIZE, env->enc,
env->pattern, env->pattern_end,
(UChar* )"character class has '%s' without escape", c);
(*onig_warn)((char* )buf);
}
}
static void
CLOSE_BRACKET_WITHOUT_ESC_WARN(ScanEnv* env, UChar* c)
{
if (onig_warn == onig_null_warn) return ;
if (IS_SYNTAX_BV((env)->syntax, ONIG_SYN_WARN_CC_OP_NOT_ESCAPED)) {
UChar buf[WARN_BUFSIZE];
onig_snprintf_with_pattern(buf, WARN_BUFSIZE, (env)->enc,
(env)->pattern, (env)->pattern_end,
(UChar* )"regular expression has '%s' without escape", c);
(*onig_warn)((char* )buf);
}
}
static UChar*
find_str_position(OnigCodePoint s[], int n, UChar* from, UChar* to,
UChar **next, OnigEncoding enc)
{
int i;
OnigCodePoint x;
UChar *q;
UChar *p = from;
while (p < to) {
x = ONIGENC_MBC_TO_CODE(enc, p, to);
q = p + enclen(enc, p);
if (x == s[0]) {
for (i = 1; i < n && q < to; i++) {
x = ONIGENC_MBC_TO_CODE(enc, q, to);
if (x != s[i]) break;
q += enclen(enc, q);
}
if (i >= n) {
if (IS_NOT_NULL(next))
*next = q;
return p;
}
}
p = q;
}
return NULL_UCHARP;
}
static int
str_exist_check_with_esc(OnigCodePoint s[], int n, UChar* from, UChar* to,
OnigCodePoint bad, OnigEncoding enc, OnigSyntaxType* syn)
{
int i, in_esc;
OnigCodePoint x;
UChar *q;
UChar *p = from;
in_esc = 0;
while (p < to) {
if (in_esc) {
in_esc = 0;
p += enclen(enc, p);
}
else {
x = ONIGENC_MBC_TO_CODE(enc, p, to);
q = p + enclen(enc, p);
if (x == s[0]) {
for (i = 1; i < n && q < to; i++) {
x = ONIGENC_MBC_TO_CODE(enc, q, to);
if (x != s[i]) break;
q += enclen(enc, q);
}
if (i >= n) return 1;
p += enclen(enc, p);
}
else {
x = ONIGENC_MBC_TO_CODE(enc, p, to);
if (x == bad) return 0;
else if (x == MC_ESC(syn)) in_esc = 1;
p = q;
}
}
}
return 0;
}
static int
fetch_token_in_cc(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env)
{
int num;
OnigCodePoint c, c2;
OnigSyntaxType* syn = env->syntax;
OnigEncoding enc = env->enc;
UChar* prev;
UChar* p = *src;
PFETCH_READY;
if (PEND) {
tok->type = TK_EOT;
return tok->type;
}
PFETCH(c);
tok->type = TK_CHAR;
tok->base = 0;
tok->u.c = c;
tok->escaped = 0;
if (c == ']') {
tok->type = TK_CC_CLOSE;
}
else if (c == '-') {
tok->type = TK_CC_RANGE;
}
else if (c == MC_ESC(syn)) {
if (! IS_SYNTAX_BV(syn, ONIG_SYN_BACKSLASH_ESCAPE_IN_CC))
goto end;
if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE;
PFETCH(c);
tok->escaped = 1;
tok->u.c = c;
switch (c) {
case 'w':
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_WORD;
tok->u.prop.not = 0;
break;
case 'W':
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_WORD;
tok->u.prop.not = 1;
break;
case 'd':
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT;
tok->u.prop.not = 0;
break;
case 'D':
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT;
tok->u.prop.not = 1;
break;
case 's':
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_SPACE;
tok->u.prop.not = 0;
break;
case 'S':
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_SPACE;
tok->u.prop.not = 1;
break;
case 'h':
if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT;
tok->u.prop.not = 0;
break;
case 'H':
if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT;
tok->u.prop.not = 1;
break;
case 'p':
case 'P':
if (PEND) break;
c2 = PPEEK;
if (c2 == '{' &&
IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY)) {
PINC;
tok->type = TK_CHAR_PROPERTY;
tok->u.prop.not = (c == 'P' ? 1 : 0);
if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT)) {
PFETCH(c2);
if (c2 == '^') {
tok->u.prop.not = (tok->u.prop.not == 0 ? 1 : 0);
}
else
PUNFETCH;
}
}
break;
case 'x':
if (PEND) break;
prev = p;
if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) {
PINC;
num = scan_unsigned_hexadecimal_number(&p, end, 8, enc);
if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE;
if (!PEND) {
c2 = PPEEK;
if (ONIGENC_IS_CODE_XDIGIT(enc, c2))
return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE;
}
if (p > prev + enclen(enc, prev) && !PEND && (PPEEK_IS('}'))) {
PINC;
tok->type = TK_CODE_POINT;
tok->base = 16;
tok->u.code = (OnigCodePoint )num;
}
else {
/* can't read nothing or invalid format */
p = prev;
}
}
else if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_HEX2)) {
num = scan_unsigned_hexadecimal_number(&p, end, 2, enc);
if (num < 0) return ONIGERR_TOO_BIG_NUMBER;
if (p == prev) { /* can't read nothing. */
num = 0; /* but, it's not error */
}
tok->type = TK_RAW_BYTE;
tok->base = 16;
tok->u.c = num;
}
break;
case 'u':
if (PEND) break;
prev = p;
if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) {
num = scan_unsigned_hexadecimal_number(&p, end, 4, enc);
if (num < 0) return ONIGERR_TOO_BIG_NUMBER;
if (p == prev) { /* can't read nothing. */
num = 0; /* but, it's not error */
}
tok->type = TK_CODE_POINT;
tok->base = 16;
tok->u.code = (OnigCodePoint )num;
}
break;
case '0':
case '1': case '2': case '3': case '4': case '5': case '6': case '7':
if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_OCTAL3)) {
PUNFETCH;
prev = p;
num = scan_unsigned_octal_number(&p, end, 3, enc);
if (num < 0) return ONIGERR_TOO_BIG_NUMBER;
if (p == prev) { /* can't read nothing. */
num = 0; /* but, it's not error */
}
tok->type = TK_RAW_BYTE;
tok->base = 8;
tok->u.c = num;
}
break;
default:
PUNFETCH;
num = fetch_escaped_value(&p, end, env, &c2);
if (num < 0) return num;
if (tok->u.c != c2) {
tok->u.code = c2;
tok->type = TK_CODE_POINT;
}
break;
}
}
else if (c == '[') {
if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_POSIX_BRACKET) && (PPEEK_IS(':'))) {
OnigCodePoint send[] = { (OnigCodePoint )':', (OnigCodePoint )']' };
tok->backp = p; /* point at '[' is read */
PINC;
if (str_exist_check_with_esc(send, 2, p, end,
(OnigCodePoint )']', enc, syn)) {
tok->type = TK_POSIX_BRACKET_OPEN;
}
else {
PUNFETCH;
goto cc_in_cc;
}
}
else {
cc_in_cc:
if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_CCLASS_SET_OP)) {
tok->type = TK_CC_CC_OPEN;
}
else {
CC_ESC_WARN(env, (UChar* )"[");
}
}
}
else if (c == '&') {
if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_CCLASS_SET_OP) &&
!PEND && (PPEEK_IS('&'))) {
PINC;
tok->type = TK_CC_AND;
}
}
end:
*src = p;
return tok->type;
}
static int
fetch_token(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env)
{
int r, num;
OnigCodePoint c;
OnigEncoding enc = env->enc;
OnigSyntaxType* syn = env->syntax;
UChar* prev;
UChar* p = *src;
PFETCH_READY;
start:
if (PEND) {
tok->type = TK_EOT;
return tok->type;
}
tok->type = TK_STRING;
tok->base = 0;
tok->backp = p;
PFETCH(c);
if (IS_MC_ESC_CODE(c, syn)) {
if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE;
tok->backp = p;
PFETCH(c);
tok->u.c = c;
tok->escaped = 1;
switch (c) {
case '*':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_ASTERISK_ZERO_INF)) break;
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 0;
tok->u.repeat.upper = REPEAT_INFINITE;
goto greedy_check;
break;
case '+':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_PLUS_ONE_INF)) break;
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 1;
tok->u.repeat.upper = REPEAT_INFINITE;
goto greedy_check;
break;
case '?':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_QMARK_ZERO_ONE)) break;
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 0;
tok->u.repeat.upper = 1;
greedy_check:
if (!PEND && PPEEK_IS('?') &&
IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_NON_GREEDY)) {
PFETCH(c);
tok->u.repeat.greedy = 0;
tok->u.repeat.possessive = 0;
}
else {
possessive_check:
if (!PEND && PPEEK_IS('+') &&
((IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_REPEAT) &&
tok->type != TK_INTERVAL) ||
(IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_INTERVAL) &&
tok->type == TK_INTERVAL))) {
PFETCH(c);
tok->u.repeat.greedy = 1;
tok->u.repeat.possessive = 1;
}
else {
tok->u.repeat.greedy = 1;
tok->u.repeat.possessive = 0;
}
}
break;
case '{':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_BRACE_INTERVAL)) break;
r = fetch_range_quantifier(&p, end, tok, env);
if (r < 0) return r; /* error */
if (r == 0) goto greedy_check;
else if (r == 2) { /* {n} */
if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY))
goto possessive_check;
goto greedy_check;
}
/* r == 1 : normal char */
break;
case '|':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_VBAR_ALT)) break;
tok->type = TK_ALT;
break;
case '(':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break;
tok->type = TK_SUBEXP_OPEN;
break;
case ')':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break;
tok->type = TK_SUBEXP_CLOSE;
break;
case 'w':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_WORD;
tok->u.prop.not = 0;
break;
case 'W':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_WORD;
tok->u.prop.not = 1;
break;
case 'b':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break;
tok->type = TK_ANCHOR;
tok->u.anchor = ANCHOR_WORD_BOUND;
break;
case 'B':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break;
tok->type = TK_ANCHOR;
tok->u.anchor = ANCHOR_NOT_WORD_BOUND;
break;
#ifdef USE_WORD_BEGIN_END
case '<':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break;
tok->type = TK_ANCHOR;
tok->u.anchor = ANCHOR_WORD_BEGIN;
break;
case '>':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break;
tok->type = TK_ANCHOR;
tok->u.anchor = ANCHOR_WORD_END;
break;
#endif
case 's':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_SPACE;
tok->u.prop.not = 0;
break;
case 'S':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_SPACE;
tok->u.prop.not = 1;
break;
case 'd':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT;
tok->u.prop.not = 0;
break;
case 'D':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT;
tok->u.prop.not = 1;
break;
case 'h':
if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT;
tok->u.prop.not = 0;
break;
case 'H':
if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT;
tok->u.prop.not = 1;
break;
case 'A':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break;
begin_buf:
tok->type = TK_ANCHOR;
tok->u.subtype = ANCHOR_BEGIN_BUF;
break;
case 'Z':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break;
tok->type = TK_ANCHOR;
tok->u.subtype = ANCHOR_SEMI_END_BUF;
break;
case 'z':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break;
end_buf:
tok->type = TK_ANCHOR;
tok->u.subtype = ANCHOR_END_BUF;
break;
case 'G':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_CAPITAL_G_BEGIN_ANCHOR)) break;
tok->type = TK_ANCHOR;
tok->u.subtype = ANCHOR_BEGIN_POSITION;
break;
case '`':
if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break;
goto begin_buf;
break;
case '\'':
if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break;
goto end_buf;
break;
case 'x':
if (PEND) break;
prev = p;
if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) {
PINC;
num = scan_unsigned_hexadecimal_number(&p, end, 8, enc);
if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE;
if (!PEND) {
if (ONIGENC_IS_CODE_XDIGIT(enc, PPEEK))
return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE;
}
if ((p > prev + enclen(enc, prev)) && !PEND && PPEEK_IS('}')) {
PINC;
tok->type = TK_CODE_POINT;
tok->u.code = (OnigCodePoint )num;
}
else {
/* can't read nothing or invalid format */
p = prev;
}
}
else if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_HEX2)) {
num = scan_unsigned_hexadecimal_number(&p, end, 2, enc);
if (num < 0) return ONIGERR_TOO_BIG_NUMBER;
if (p == prev) { /* can't read nothing. */
num = 0; /* but, it's not error */
}
tok->type = TK_RAW_BYTE;
tok->base = 16;
tok->u.c = num;
}
break;
case 'u':
if (PEND) break;
prev = p;
if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) {
num = scan_unsigned_hexadecimal_number(&p, end, 4, enc);
if (num < 0) return ONIGERR_TOO_BIG_NUMBER;
if (p == prev) { /* can't read nothing. */
num = 0; /* but, it's not error */
}
tok->type = TK_CODE_POINT;
tok->base = 16;
tok->u.code = (OnigCodePoint )num;
}
break;
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
PUNFETCH;
prev = p;
num = onig_scan_unsigned_number(&p, end, enc);
if (num < 0 || num > ONIG_MAX_BACKREF_NUM) {
goto skip_backref;
}
if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_DECIMAL_BACKREF) &&
(num <= env->num_mem || num <= 9)) { /* This spec. from GNU regex */
if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) {
if (num > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[num]))
return ONIGERR_INVALID_BACKREF;
}
tok->type = TK_BACKREF;
tok->u.backref.num = 1;
tok->u.backref.ref1 = num;
tok->u.backref.by_name = 0;
#ifdef USE_BACKREF_WITH_LEVEL
tok->u.backref.exist_level = 0;
#endif
break;
}
skip_backref:
if (c == '8' || c == '9') {
/* normal char */
p = prev; PINC;
break;
}
p = prev;
/* fall through */
case '0':
if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_OCTAL3)) {
prev = p;
num = scan_unsigned_octal_number(&p, end, (c == '0' ? 2:3), enc);
if (num < 0) return ONIGERR_TOO_BIG_NUMBER;
if (p == prev) { /* can't read nothing. */
num = 0; /* but, it's not error */
}
tok->type = TK_RAW_BYTE;
tok->base = 8;
tok->u.c = num;
}
else if (c != '0') {
PINC;
}
break;
#ifdef USE_NAMED_GROUP
case 'k':
if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_K_NAMED_BACKREF)) {
PFETCH(c);
if (c == '<' || c == '\'') {
UChar* name_end;
int* backs;
int back_num;
prev = p;
#ifdef USE_BACKREF_WITH_LEVEL
name_end = NULL_UCHARP; /* no need. escape gcc warning. */
r = fetch_name_with_level((OnigCodePoint )c, &p, end, &name_end,
env, &back_num, &tok->u.backref.level);
if (r == 1) tok->u.backref.exist_level = 1;
else tok->u.backref.exist_level = 0;
#else
r = fetch_name(&p, end, &name_end, env, &back_num, 1);
#endif
if (r < 0) return r;
if (back_num != 0) {
if (back_num < 0) {
back_num = BACKREF_REL_TO_ABS(back_num, env);
if (back_num <= 0)
return ONIGERR_INVALID_BACKREF;
}
if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) {
if (back_num > env->num_mem ||
IS_NULL(SCANENV_MEM_NODES(env)[back_num]))
return ONIGERR_INVALID_BACKREF;
}
tok->type = TK_BACKREF;
tok->u.backref.by_name = 0;
tok->u.backref.num = 1;
tok->u.backref.ref1 = back_num;
}
else {
num = onig_name_to_group_numbers(env->reg, prev, name_end, &backs);
if (num <= 0) {
onig_scan_env_set_error_string(env,
ONIGERR_UNDEFINED_NAME_REFERENCE, prev, name_end);
return ONIGERR_UNDEFINED_NAME_REFERENCE;
}
if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) {
int i;
for (i = 0; i < num; i++) {
if (backs[i] > env->num_mem ||
IS_NULL(SCANENV_MEM_NODES(env)[backs[i]]))
return ONIGERR_INVALID_BACKREF;
}
}
tok->type = TK_BACKREF;
tok->u.backref.by_name = 1;
if (num == 1) {
tok->u.backref.num = 1;
tok->u.backref.ref1 = backs[0];
}
else {
tok->u.backref.num = num;
tok->u.backref.refs = backs;
}
}
}
else
PUNFETCH;
}
break;
#endif
#ifdef USE_SUBEXP_CALL
case 'g':
if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_G_SUBEXP_CALL)) {
PFETCH(c);
if (c == '<' || c == '\'') {
int gnum;
UChar* name_end;
prev = p;
r = fetch_name((OnigCodePoint )c, &p, end, &name_end, env, &gnum, 1);
if (r < 0) return r;
tok->type = TK_CALL;
tok->u.call.name = prev;
tok->u.call.name_end = name_end;
tok->u.call.gnum = gnum;
}
else
PUNFETCH;
}
break;
#endif
case 'Q':
if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_Q_QUOTE)) {
tok->type = TK_QUOTE_OPEN;
}
break;
case 'p':
case 'P':
if (!PEND && PPEEK_IS('{') &&
IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY)) {
PINC;
tok->type = TK_CHAR_PROPERTY;
tok->u.prop.not = (c == 'P' ? 1 : 0);
if (!PEND &&
IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT)) {
PFETCH(c);
if (c == '^') {
tok->u.prop.not = (tok->u.prop.not == 0 ? 1 : 0);
}
else
PUNFETCH;
}
}
break;
default:
{
OnigCodePoint c2;
PUNFETCH;
num = fetch_escaped_value(&p, end, env, &c2);
if (num < 0) return num;
/* set_raw: */
if (tok->u.c != c2) {
tok->type = TK_CODE_POINT;
tok->u.code = c2;
}
else { /* string */
p = tok->backp + enclen(enc, tok->backp);
}
}
break;
}
}
else {
tok->u.c = c;
tok->escaped = 0;
#ifdef USE_VARIABLE_META_CHARS
if ((c != ONIG_INEFFECTIVE_META_CHAR) &&
IS_SYNTAX_OP(syn, ONIG_SYN_OP_VARIABLE_META_CHARACTERS)) {
if (c == MC_ANYCHAR(syn))
goto any_char;
else if (c == MC_ANYTIME(syn))
goto anytime;
else if (c == MC_ZERO_OR_ONE_TIME(syn))
goto zero_or_one_time;
else if (c == MC_ONE_OR_MORE_TIME(syn))
goto one_or_more_time;
else if (c == MC_ANYCHAR_ANYTIME(syn)) {
tok->type = TK_ANYCHAR_ANYTIME;
goto out;
}
}
#endif
switch (c) {
case '.':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_DOT_ANYCHAR)) break;
#ifdef USE_VARIABLE_META_CHARS
any_char:
#endif
tok->type = TK_ANYCHAR;
break;
case '*':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ASTERISK_ZERO_INF)) break;
#ifdef USE_VARIABLE_META_CHARS
anytime:
#endif
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 0;
tok->u.repeat.upper = REPEAT_INFINITE;
goto greedy_check;
break;
case '+':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_PLUS_ONE_INF)) break;
#ifdef USE_VARIABLE_META_CHARS
one_or_more_time:
#endif
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 1;
tok->u.repeat.upper = REPEAT_INFINITE;
goto greedy_check;
break;
case '?':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_ZERO_ONE)) break;
#ifdef USE_VARIABLE_META_CHARS
zero_or_one_time:
#endif
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 0;
tok->u.repeat.upper = 1;
goto greedy_check;
break;
case '{':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACE_INTERVAL)) break;
r = fetch_range_quantifier(&p, end, tok, env);
if (r < 0) return r; /* error */
if (r == 0) goto greedy_check;
else if (r == 2) { /* {n} */
if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY))
goto possessive_check;
goto greedy_check;
}
/* r == 1 : normal char */
break;
case '|':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_VBAR_ALT)) break;
tok->type = TK_ALT;
break;
case '(':
if (!PEND && PPEEK_IS('?') &&
IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_QMARK_GROUP_EFFECT)) {
PINC;
if (!PEND && PPEEK_IS('#')) {
PFETCH(c);
while (1) {
if (PEND) return ONIGERR_END_PATTERN_IN_GROUP;
PFETCH(c);
if (c == MC_ESC(syn)) {
if (!PEND) PFETCH(c);
}
else {
if (c == ')') break;
}
}
goto start;
}
PUNFETCH;
}
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break;
tok->type = TK_SUBEXP_OPEN;
break;
case ')':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break;
tok->type = TK_SUBEXP_CLOSE;
break;
case '^':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break;
tok->type = TK_ANCHOR;
tok->u.subtype = (IS_SINGLELINE(env->option)
? ANCHOR_BEGIN_BUF : ANCHOR_BEGIN_LINE);
break;
case '$':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break;
tok->type = TK_ANCHOR;
tok->u.subtype = (IS_SINGLELINE(env->option)
? ANCHOR_SEMI_END_BUF : ANCHOR_END_LINE);
break;
case '[':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACKET_CC)) break;
tok->type = TK_CC_OPEN;
break;
case ']':
if (*src > env->pattern) /* /].../ is allowed. */
CLOSE_BRACKET_WITHOUT_ESC_WARN(env, (UChar* )"]");
break;
case '#':
if (IS_EXTEND(env->option)) {
while (!PEND) {
PFETCH(c);
if (ONIGENC_IS_CODE_NEWLINE(enc, c))
break;
}
goto start;
break;
}
break;
case ' ': case '\t': case '\n': case '\r': case '\f':
if (IS_EXTEND(env->option))
goto start;
break;
default:
/* string */
break;
}
}
#ifdef USE_VARIABLE_META_CHARS
out:
#endif
*src = p;
return tok->type;
}
static int
add_ctype_to_cc_by_range(CClassNode* cc, int ctype ARG_UNUSED, int not,
OnigEncoding enc ARG_UNUSED,
OnigCodePoint sb_out, const OnigCodePoint mbr[])
{
int i, r;
OnigCodePoint j;
int n = ONIGENC_CODE_RANGE_NUM(mbr);
if (not == 0) {
for (i = 0; i < n; i++) {
for (j = ONIGENC_CODE_RANGE_FROM(mbr, i);
j <= ONIGENC_CODE_RANGE_TO(mbr, i); j++) {
if (j >= sb_out) {
if (j > ONIGENC_CODE_RANGE_FROM(mbr, i)) {
r = add_code_range_to_buf(&(cc->mbuf), j,
ONIGENC_CODE_RANGE_TO(mbr, i));
if (r != 0) return r;
i++;
}
goto sb_end;
}
BITSET_SET_BIT(cc->bs, j);
}
}
sb_end:
for ( ; i < n; i++) {
r = add_code_range_to_buf(&(cc->mbuf),
ONIGENC_CODE_RANGE_FROM(mbr, i),
ONIGENC_CODE_RANGE_TO(mbr, i));
if (r != 0) return r;
}
}
else {
OnigCodePoint prev = 0;
for (i = 0; i < n; i++) {
for (j = prev;
j < ONIGENC_CODE_RANGE_FROM(mbr, i); j++) {
if (j >= sb_out) {
goto sb_end2;
}
BITSET_SET_BIT(cc->bs, j);
}
prev = ONIGENC_CODE_RANGE_TO(mbr, i) + 1;
}
for (j = prev; j < sb_out; j++) {
BITSET_SET_BIT(cc->bs, j);
}
sb_end2:
prev = sb_out;
for (i = 0; i < n; i++) {
if (prev < ONIGENC_CODE_RANGE_FROM(mbr, i)) {
r = add_code_range_to_buf(&(cc->mbuf), prev,
ONIGENC_CODE_RANGE_FROM(mbr, i) - 1);
if (r != 0) return r;
}
prev = ONIGENC_CODE_RANGE_TO(mbr, i) + 1;
}
if (prev < 0x7fffffff) {
r = add_code_range_to_buf(&(cc->mbuf), prev, 0x7fffffff);
if (r != 0) return r;
}
}
return 0;
}
static int
add_ctype_to_cc(CClassNode* cc, int ctype, int not, ScanEnv* env)
{
int c, r;
const OnigCodePoint *ranges;
OnigCodePoint sb_out;
OnigEncoding enc = env->enc;
r = ONIGENC_GET_CTYPE_CODE_RANGE(enc, ctype, &sb_out, &ranges);
if (r == 0) {
return add_ctype_to_cc_by_range(cc, ctype, not, env->enc, sb_out, ranges);
}
else if (r != ONIG_NO_SUPPORT_CONFIG) {
return r;
}
r = 0;
switch (ctype) {
case ONIGENC_CTYPE_ALPHA:
case ONIGENC_CTYPE_BLANK:
case ONIGENC_CTYPE_CNTRL:
case ONIGENC_CTYPE_DIGIT:
case ONIGENC_CTYPE_LOWER:
case ONIGENC_CTYPE_PUNCT:
case ONIGENC_CTYPE_SPACE:
case ONIGENC_CTYPE_UPPER:
case ONIGENC_CTYPE_XDIGIT:
case ONIGENC_CTYPE_ASCII:
case ONIGENC_CTYPE_ALNUM:
if (not != 0) {
for (c = 0; c < SINGLE_BYTE_SIZE; c++) {
if (! ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype))
BITSET_SET_BIT(cc->bs, c);
}
ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf);
}
else {
for (c = 0; c < SINGLE_BYTE_SIZE; c++) {
if (ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype))
BITSET_SET_BIT(cc->bs, c);
}
}
break;
case ONIGENC_CTYPE_GRAPH:
case ONIGENC_CTYPE_PRINT:
if (not != 0) {
for (c = 0; c < SINGLE_BYTE_SIZE; c++) {
if (! ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype))
BITSET_SET_BIT(cc->bs, c);
}
}
else {
for (c = 0; c < SINGLE_BYTE_SIZE; c++) {
if (ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype))
BITSET_SET_BIT(cc->bs, c);
}
ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf);
}
break;
case ONIGENC_CTYPE_WORD:
if (not == 0) {
for (c = 0; c < SINGLE_BYTE_SIZE; c++) {
if (IS_CODE_SB_WORD(enc, c)) BITSET_SET_BIT(cc->bs, c);
}
ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf);
}
else {
for (c = 0; c < SINGLE_BYTE_SIZE; c++) {
if ((ONIGENC_CODE_TO_MBCLEN(enc, c) > 0) /* check invalid code point */
&& ! ONIGENC_IS_CODE_WORD(enc, c))
BITSET_SET_BIT(cc->bs, c);
}
}
break;
default:
return ONIGERR_PARSER_BUG;
break;
}
return r;
}
static int
parse_posix_bracket(CClassNode* cc, UChar** src, UChar* end, ScanEnv* env)
{
#define POSIX_BRACKET_CHECK_LIMIT_LENGTH 20
#define POSIX_BRACKET_NAME_MIN_LEN 4
static PosixBracketEntryType PBS[] = {
{ (UChar* )"alnum", ONIGENC_CTYPE_ALNUM, 5 },
{ (UChar* )"alpha", ONIGENC_CTYPE_ALPHA, 5 },
{ (UChar* )"blank", ONIGENC_CTYPE_BLANK, 5 },
{ (UChar* )"cntrl", ONIGENC_CTYPE_CNTRL, 5 },
{ (UChar* )"digit", ONIGENC_CTYPE_DIGIT, 5 },
{ (UChar* )"graph", ONIGENC_CTYPE_GRAPH, 5 },
{ (UChar* )"lower", ONIGENC_CTYPE_LOWER, 5 },
{ (UChar* )"print", ONIGENC_CTYPE_PRINT, 5 },
{ (UChar* )"punct", ONIGENC_CTYPE_PUNCT, 5 },
{ (UChar* )"space", ONIGENC_CTYPE_SPACE, 5 },
{ (UChar* )"upper", ONIGENC_CTYPE_UPPER, 5 },
{ (UChar* )"xdigit", ONIGENC_CTYPE_XDIGIT, 6 },
{ (UChar* )"ascii", ONIGENC_CTYPE_ASCII, 5 },
{ (UChar* )"word", ONIGENC_CTYPE_WORD, 4 },
{ (UChar* )NULL, -1, 0 }
};
PosixBracketEntryType *pb;
int not, i, r;
OnigCodePoint c;
OnigEncoding enc = env->enc;
UChar *p = *src;
if (PPEEK_IS('^')) {
PINC_S;
not = 1;
}
else
not = 0;
if (onigenc_strlen(enc, p, end) < POSIX_BRACKET_NAME_MIN_LEN + 3)
goto not_posix_bracket;
for (pb = PBS; IS_NOT_NULL(pb->name); pb++) {
if (onigenc_with_ascii_strncmp(enc, p, end, pb->name, pb->len) == 0) {
p = (UChar* )onigenc_step(enc, p, end, pb->len);
if (onigenc_with_ascii_strncmp(enc, p, end, (UChar* )":]", 2) != 0)
return ONIGERR_INVALID_POSIX_BRACKET_TYPE;
r = add_ctype_to_cc(cc, pb->ctype, not, env);
if (r != 0) return r;
PINC_S; PINC_S;
*src = p;
return 0;
}
}
not_posix_bracket:
c = 0;
i = 0;
while (!PEND && ((c = PPEEK) != ':') && c != ']') {
PINC_S;
if (++i > POSIX_BRACKET_CHECK_LIMIT_LENGTH) break;
}
if (c == ':' && ! PEND) {
PINC_S;
if (! PEND) {
PFETCH_S(c);
if (c == ']')
return ONIGERR_INVALID_POSIX_BRACKET_TYPE;
}
}
return 1; /* 1: is not POSIX bracket, but no error. */
}
static int
fetch_char_property_to_ctype(UChar** src, UChar* end, ScanEnv* env)
{
int r;
OnigCodePoint c;
OnigEncoding enc = env->enc;
UChar *prev, *start, *p = *src;
r = 0;
start = prev = p;
while (!PEND) {
prev = p;
PFETCH_S(c);
if (c == '}') {
r = ONIGENC_PROPERTY_NAME_TO_CTYPE(enc, start, prev);
if (r < 0) break;
*src = p;
return r;
}
else if (c == '(' || c == ')' || c == '{' || c == '|') {
r = ONIGERR_INVALID_CHAR_PROPERTY_NAME;
break;
}
}
onig_scan_env_set_error_string(env, r, *src, prev);
return r;
}
static int
parse_char_property(Node** np, OnigToken* tok, UChar** src, UChar* end,
ScanEnv* env)
{
int r, ctype;
CClassNode* cc;
ctype = fetch_char_property_to_ctype(src, end, env);
if (ctype < 0) return ctype;
*np = node_new_cclass();
CHECK_NULL_RETURN_MEMERR(*np);
cc = NCCLASS(*np);
r = add_ctype_to_cc(cc, ctype, 0, env);
if (r != 0) return r;
if (tok->u.prop.not != 0) NCCLASS_SET_NOT(cc);
return 0;
}
enum CCSTATE {
CCS_VALUE,
CCS_RANGE,
CCS_COMPLETE,
CCS_START
};
enum CCVALTYPE {
CCV_SB,
CCV_CODE_POINT,
CCV_CLASS
};
static int
next_state_class(CClassNode* cc, OnigCodePoint* vs, enum CCVALTYPE* type,
enum CCSTATE* state, ScanEnv* env)
{
int r;
if (*state == CCS_RANGE)
return ONIGERR_CHAR_CLASS_VALUE_AT_END_OF_RANGE;
if (*state == CCS_VALUE && *type != CCV_CLASS) {
if (*type == CCV_SB)
BITSET_SET_BIT(cc->bs, (int )(*vs));
else if (*type == CCV_CODE_POINT) {
r = add_code_range(&(cc->mbuf), env, *vs, *vs);
if (r < 0) return r;
}
}
*state = CCS_VALUE;
*type = CCV_CLASS;
return 0;
}
static int
next_state_val(CClassNode* cc, OnigCodePoint *vs, OnigCodePoint v,
int* vs_israw, int v_israw,
enum CCVALTYPE intype, enum CCVALTYPE* type,
enum CCSTATE* state, ScanEnv* env)
{
int r;
switch (*state) {
case CCS_VALUE:
if (*type == CCV_SB) {
if (*vs > 0xff)
return ONIGERR_INVALID_CODE_POINT_VALUE;
BITSET_SET_BIT(cc->bs, (int )(*vs));
}
else if (*type == CCV_CODE_POINT) {
r = add_code_range(&(cc->mbuf), env, *vs, *vs);
if (r < 0) return r;
}
break;
case CCS_RANGE:
if (intype == *type) {
if (intype == CCV_SB) {
if (*vs > 0xff || v > 0xff)
return ONIGERR_INVALID_CODE_POINT_VALUE;
if (*vs > v) {
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC))
goto ccs_range_end;
else
return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS;
}
bitset_set_range(cc->bs, (int )*vs, (int )v);
}
else {
r = add_code_range(&(cc->mbuf), env, *vs, v);
if (r < 0) return r;
}
}
else {
#if 0
if (intype == CCV_CODE_POINT && *type == CCV_SB) {
#endif
if (*vs > v) {
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC))
goto ccs_range_end;
else
return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS;
}
bitset_set_range(cc->bs, (int )*vs, (int )(v < 0xff ? v : 0xff));
r = add_code_range(&(cc->mbuf), env, (OnigCodePoint )*vs, v);
if (r < 0) return r;
#if 0
}
else
return ONIGERR_MISMATCH_CODE_LENGTH_IN_CLASS_RANGE;
#endif
}
ccs_range_end:
*state = CCS_COMPLETE;
break;
case CCS_COMPLETE:
case CCS_START:
*state = CCS_VALUE;
break;
default:
break;
}
*vs_israw = v_israw;
*vs = v;
*type = intype;
return 0;
}
static int
code_exist_check(OnigCodePoint c, UChar* from, UChar* end, int ignore_escaped,
ScanEnv* env)
{
int in_esc;
OnigCodePoint code;
OnigEncoding enc = env->enc;
UChar* p = from;
in_esc = 0;
while (! PEND) {
if (ignore_escaped && in_esc) {
in_esc = 0;
}
else {
PFETCH_S(code);
if (code == c) return 1;
if (code == MC_ESC(env->syntax)) in_esc = 1;
}
}
return 0;
}
static int
parse_char_class(Node** np, OnigToken* tok, UChar** src, UChar* end,
ScanEnv* env)
{
int r, neg, len, fetched, and_start;
OnigCodePoint v, vs;
UChar *p;
Node* node;
CClassNode *cc, *prev_cc;
CClassNode work_cc;
enum CCSTATE state;
enum CCVALTYPE val_type, in_type;
int val_israw, in_israw;
*np = NULL_NODE;
env->parse_depth++;
if (env->parse_depth > ParseDepthLimit)
return ONIGERR_PARSE_DEPTH_LIMIT_OVER;
prev_cc = (CClassNode* )NULL;
r = fetch_token_in_cc(tok, src, end, env);
if (r == TK_CHAR && tok->u.c == '^' && tok->escaped == 0) {
neg = 1;
r = fetch_token_in_cc(tok, src, end, env);
}
else {
neg = 0;
}
if (r < 0) return r;
if (r == TK_CC_CLOSE) {
if (! code_exist_check((OnigCodePoint )']',
*src, env->pattern_end, 1, env))
return ONIGERR_EMPTY_CHAR_CLASS;
CC_ESC_WARN(env, (UChar* )"]");
r = tok->type = TK_CHAR; /* allow []...] */
}
*np = node = node_new_cclass();
CHECK_NULL_RETURN_MEMERR(node);
cc = NCCLASS(node);
and_start = 0;
state = CCS_START;
p = *src;
while (r != TK_CC_CLOSE) {
fetched = 0;
switch (r) {
case TK_CHAR:
any_char_in:
len = ONIGENC_CODE_TO_MBCLEN(env->enc, tok->u.c);
if (len > 1) {
in_type = CCV_CODE_POINT;
}
else if (len < 0) {
r = len;
goto err;
}
else {
/* sb_char: */
in_type = CCV_SB;
}
v = (OnigCodePoint )tok->u.c;
in_israw = 0;
goto val_entry2;
break;
case TK_RAW_BYTE:
/* tok->base != 0 : octal or hexadec. */
if (! ONIGENC_IS_SINGLEBYTE(env->enc) && tok->base != 0) {
UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN];
UChar* bufe = buf + ONIGENC_CODE_TO_MBC_MAXLEN;
UChar* psave = p;
int i, base = tok->base;
buf[0] = tok->u.c;
for (i = 1; i < ONIGENC_MBC_MAXLEN(env->enc); i++) {
r = fetch_token_in_cc(tok, &p, end, env);
if (r < 0) goto err;
if (r != TK_RAW_BYTE || tok->base != base) {
fetched = 1;
break;
}
buf[i] = tok->u.c;
}
if (i < ONIGENC_MBC_MINLEN(env->enc)) {
r = ONIGERR_TOO_SHORT_MULTI_BYTE_STRING;
goto err;
}
len = enclen(env->enc, buf);
if (i < len) {
r = ONIGERR_TOO_SHORT_MULTI_BYTE_STRING;
goto err;
}
else if (i > len) { /* fetch back */
p = psave;
for (i = 1; i < len; i++) {
r = fetch_token_in_cc(tok, &p, end, env);
}
fetched = 0;
}
if (i == 1) {
v = (OnigCodePoint )buf[0];
goto raw_single;
}
else {
v = ONIGENC_MBC_TO_CODE(env->enc, buf, bufe);
in_type = CCV_CODE_POINT;
}
}
else {
v = (OnigCodePoint )tok->u.c;
raw_single:
in_type = CCV_SB;
}
in_israw = 1;
goto val_entry2;
break;
case TK_CODE_POINT:
v = tok->u.code;
in_israw = 1;
val_entry:
len = ONIGENC_CODE_TO_MBCLEN(env->enc, v);
if (len < 0) {
r = len;
goto err;
}
in_type = (len == 1 ? CCV_SB : CCV_CODE_POINT);
val_entry2:
r = next_state_val(cc, &vs, v, &val_israw, in_israw, in_type, &val_type,
&state, env);
if (r != 0) goto err;
break;
case TK_POSIX_BRACKET_OPEN:
r = parse_posix_bracket(cc, &p, end, env);
if (r < 0) goto err;
if (r == 1) { /* is not POSIX bracket */
CC_ESC_WARN(env, (UChar* )"[");
p = tok->backp;
v = (OnigCodePoint )tok->u.c;
in_israw = 0;
goto val_entry;
}
goto next_class;
break;
case TK_CHAR_TYPE:
r = add_ctype_to_cc(cc, tok->u.prop.ctype, tok->u.prop.not, env);
if (r != 0) return r;
next_class:
r = next_state_class(cc, &vs, &val_type, &state, env);
if (r != 0) goto err;
break;
case TK_CHAR_PROPERTY:
{
int ctype;
ctype = fetch_char_property_to_ctype(&p, end, env);
if (ctype < 0) return ctype;
r = add_ctype_to_cc(cc, ctype, tok->u.prop.not, env);
if (r != 0) return r;
goto next_class;
}
break;
case TK_CC_RANGE:
if (state == CCS_VALUE) {
r = fetch_token_in_cc(tok, &p, end, env);
if (r < 0) goto err;
fetched = 1;
if (r == TK_CC_CLOSE) { /* allow [x-] */
range_end_val:
v = (OnigCodePoint )'-';
in_israw = 0;
goto val_entry;
}
else if (r == TK_CC_AND) {
CC_ESC_WARN(env, (UChar* )"-");
goto range_end_val;
}
state = CCS_RANGE;
}
else if (state == CCS_START) {
/* [-xa] is allowed */
v = (OnigCodePoint )tok->u.c;
in_israw = 0;
r = fetch_token_in_cc(tok, &p, end, env);
if (r < 0) goto err;
fetched = 1;
/* [--x] or [a&&-x] is warned. */
if (r == TK_CC_RANGE || and_start != 0)
CC_ESC_WARN(env, (UChar* )"-");
goto val_entry;
}
else if (state == CCS_RANGE) {
CC_ESC_WARN(env, (UChar* )"-");
goto any_char_in; /* [!--x] is allowed */
}
else { /* CCS_COMPLETE */
r = fetch_token_in_cc(tok, &p, end, env);
if (r < 0) goto err;
fetched = 1;
if (r == TK_CC_CLOSE) goto range_end_val; /* allow [a-b-] */
else if (r == TK_CC_AND) {
CC_ESC_WARN(env, (UChar* )"-");
goto range_end_val;
}
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_DOUBLE_RANGE_OP_IN_CC)) {
CC_ESC_WARN(env, (UChar* )"-");
goto range_end_val; /* [0-9-a] is allowed as [0-9\-a] */
}
r = ONIGERR_UNMATCHED_RANGE_SPECIFIER_IN_CHAR_CLASS;
goto err;
}
break;
case TK_CC_CC_OPEN: /* [ */
{
Node *anode;
CClassNode* acc;
r = parse_char_class(&anode, tok, &p, end, env);
if (r != 0) {
onig_node_free(anode);
goto cc_open_err;
}
acc = NCCLASS(anode);
r = or_cclass(cc, acc, env->enc);
onig_node_free(anode);
cc_open_err:
if (r != 0) goto err;
}
break;
case TK_CC_AND: /* && */
{
if (state == CCS_VALUE) {
r = next_state_val(cc, &vs, 0, &val_israw, 0, val_type,
&val_type, &state, env);
if (r != 0) goto err;
}
/* initialize local variables */
and_start = 1;
state = CCS_START;
if (IS_NOT_NULL(prev_cc)) {
r = and_cclass(prev_cc, cc, env->enc);
if (r != 0) goto err;
bbuf_free(cc->mbuf);
}
else {
prev_cc = cc;
cc = &work_cc;
}
initialize_cclass(cc);
}
break;
case TK_EOT:
r = ONIGERR_PREMATURE_END_OF_CHAR_CLASS;
goto err;
break;
default:
r = ONIGERR_PARSER_BUG;
goto err;
break;
}
if (fetched)
r = tok->type;
else {
r = fetch_token_in_cc(tok, &p, end, env);
if (r < 0) goto err;
}
}
if (state == CCS_VALUE) {
r = next_state_val(cc, &vs, 0, &val_israw, 0, val_type,
&val_type, &state, env);
if (r != 0) goto err;
}
if (IS_NOT_NULL(prev_cc)) {
r = and_cclass(prev_cc, cc, env->enc);
if (r != 0) goto err;
bbuf_free(cc->mbuf);
cc = prev_cc;
}
if (neg != 0)
NCCLASS_SET_NOT(cc);
else
NCCLASS_CLEAR_NOT(cc);
if (IS_NCCLASS_NOT(cc) &&
IS_SYNTAX_BV(env->syntax, ONIG_SYN_NOT_NEWLINE_IN_NEGATIVE_CC)) {
int is_empty;
is_empty = (IS_NULL(cc->mbuf) ? 1 : 0);
if (is_empty != 0)
BITSET_IS_EMPTY(cc->bs, is_empty);
if (is_empty == 0) {
#define NEWLINE_CODE 0x0a
if (ONIGENC_IS_CODE_NEWLINE(env->enc, NEWLINE_CODE)) {
if (ONIGENC_CODE_TO_MBCLEN(env->enc, NEWLINE_CODE) == 1)
BITSET_SET_BIT(cc->bs, NEWLINE_CODE);
else
add_code_range(&(cc->mbuf), env, NEWLINE_CODE, NEWLINE_CODE);
}
}
}
*src = p;
env->parse_depth--;
return 0;
err:
if (cc != NCCLASS(*np))
bbuf_free(cc->mbuf);
return r;
}
static int parse_subexp(Node** top, OnigToken* tok, int term,
UChar** src, UChar* end, ScanEnv* env);
static int
parse_enclose(Node** np, OnigToken* tok, int term, UChar** src, UChar* end,
ScanEnv* env)
{
int r, num;
Node *target;
OnigOptionType option;
OnigCodePoint c;
OnigEncoding enc = env->enc;
#ifdef USE_NAMED_GROUP
int list_capture;
#endif
UChar* p = *src;
PFETCH_READY;
*np = NULL;
if (PEND) return ONIGERR_END_PATTERN_WITH_UNMATCHED_PARENTHESIS;
option = env->option;
if (PPEEK_IS('?') &&
IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_GROUP_EFFECT)) {
PINC;
if (PEND) return ONIGERR_END_PATTERN_IN_GROUP;
PFETCH(c);
switch (c) {
case ':': /* (?:...) grouping only */
group:
r = fetch_token(tok, &p, end, env);
if (r < 0) return r;
r = parse_subexp(np, tok, term, &p, end, env);
if (r < 0) return r;
*src = p;
return 1; /* group */
break;
case '=':
*np = onig_node_new_anchor(ANCHOR_PREC_READ);
break;
case '!': /* preceding read */
*np = onig_node_new_anchor(ANCHOR_PREC_READ_NOT);
break;
case '>': /* (?>...) stop backtrack */
*np = node_new_enclose(ENCLOSE_STOP_BACKTRACK);
break;
#ifdef USE_NAMED_GROUP
case '\'':
if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) {
goto named_group1;
}
else
return ONIGERR_UNDEFINED_GROUP_OPTION;
break;
#endif
case '<': /* look behind (?<=...), (?<!...) */
if (PEND) return ONIGERR_END_PATTERN_WITH_UNMATCHED_PARENTHESIS;
PFETCH(c);
if (c == '=')
*np = onig_node_new_anchor(ANCHOR_LOOK_BEHIND);
else if (c == '!')
*np = onig_node_new_anchor(ANCHOR_LOOK_BEHIND_NOT);
#ifdef USE_NAMED_GROUP
else {
if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) {
UChar *name;
UChar *name_end;
PUNFETCH;
c = '<';
named_group1:
list_capture = 0;
named_group2:
name = p;
r = fetch_name((OnigCodePoint )c, &p, end, &name_end, env, &num, 0);
if (r < 0) return r;
num = scan_env_add_mem_entry(env);
if (num < 0) return num;
if (list_capture != 0 && num >= (int )BIT_STATUS_BITS_NUM)
return ONIGERR_GROUP_NUMBER_OVER_FOR_CAPTURE_HISTORY;
r = name_add(env->reg, name, name_end, num, env);
if (r != 0) return r;
*np = node_new_enclose_memory(env->option, 1);
CHECK_NULL_RETURN_MEMERR(*np);
NENCLOSE(*np)->regnum = num;
if (list_capture != 0)
BIT_STATUS_ON_AT_SIMPLE(env->capture_history, num);
env->num_named++;
}
else {
return ONIGERR_UNDEFINED_GROUP_OPTION;
}
}
#else
else {
return ONIGERR_UNDEFINED_GROUP_OPTION;
}
#endif
break;
case '@':
if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ATMARK_CAPTURE_HISTORY)) {
#ifdef USE_NAMED_GROUP
if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) {
PFETCH(c);
if (c == '<' || c == '\'') {
list_capture = 1;
goto named_group2; /* (?@<name>...) */
}
PUNFETCH;
}
#endif
*np = node_new_enclose_memory(env->option, 0);
CHECK_NULL_RETURN_MEMERR(*np);
num = scan_env_add_mem_entry(env);
if (num < 0) {
return num;
}
else if (num >= (int )BIT_STATUS_BITS_NUM) {
return ONIGERR_GROUP_NUMBER_OVER_FOR_CAPTURE_HISTORY;
}
NENCLOSE(*np)->regnum = num;
BIT_STATUS_ON_AT_SIMPLE(env->capture_history, num);
}
else {
return ONIGERR_UNDEFINED_GROUP_OPTION;
}
break;
#ifdef USE_POSIXLINE_OPTION
case 'p':
#endif
case '-': case 'i': case 'm': case 's': case 'x':
{
int neg = 0;
while (1) {
switch (c) {
case ':':
case ')':
break;
case '-': neg = 1; break;
case 'x': ONOFF(option, ONIG_OPTION_EXTEND, neg); break;
case 'i': ONOFF(option, ONIG_OPTION_IGNORECASE, neg); break;
case 's':
if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_PERL)) {
ONOFF(option, ONIG_OPTION_MULTILINE, neg);
}
else
return ONIGERR_UNDEFINED_GROUP_OPTION;
break;
case 'm':
if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_PERL)) {
ONOFF(option, ONIG_OPTION_SINGLELINE, (neg == 0 ? 1 : 0));
}
else if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_RUBY)) {
ONOFF(option, ONIG_OPTION_MULTILINE, neg);
}
else
return ONIGERR_UNDEFINED_GROUP_OPTION;
break;
#ifdef USE_POSIXLINE_OPTION
case 'p':
ONOFF(option, ONIG_OPTION_MULTILINE|ONIG_OPTION_SINGLELINE, neg);
break;
#endif
default:
return ONIGERR_UNDEFINED_GROUP_OPTION;
}
if (c == ')') {
*np = node_new_option(option);
CHECK_NULL_RETURN_MEMERR(*np);
*src = p;
return 2; /* option only */
}
else if (c == ':') {
OnigOptionType prev = env->option;
env->option = option;
r = fetch_token(tok, &p, end, env);
if (r < 0) return r;
r = parse_subexp(&target, tok, term, &p, end, env);
env->option = prev;
if (r < 0) {
onig_node_free(target);
return r;
}
*np = node_new_option(option);
CHECK_NULL_RETURN_MEMERR(*np);
NENCLOSE(*np)->target = target;
*src = p;
return 0;
}
if (PEND) return ONIGERR_END_PATTERN_IN_GROUP;
PFETCH(c);
}
}
break;
default:
return ONIGERR_UNDEFINED_GROUP_OPTION;
}
}
else {
if (ONIG_IS_OPTION_ON(env->option, ONIG_OPTION_DONT_CAPTURE_GROUP))
goto group;
*np = node_new_enclose_memory(env->option, 0);
CHECK_NULL_RETURN_MEMERR(*np);
num = scan_env_add_mem_entry(env);
if (num < 0) return num;
NENCLOSE(*np)->regnum = num;
}
CHECK_NULL_RETURN_MEMERR(*np);
r = fetch_token(tok, &p, end, env);
if (r < 0) return r;
r = parse_subexp(&target, tok, term, &p, end, env);
if (r < 0) {
onig_node_free(target);
return r;
}
if (NTYPE(*np) == NT_ANCHOR)
NANCHOR(*np)->target = target;
else {
NENCLOSE(*np)->target = target;
if (NENCLOSE(*np)->type == ENCLOSE_MEMORY) {
/* Don't move this to previous of parse_subexp() */
r = scan_env_set_mem_node(env, NENCLOSE(*np)->regnum, *np);
if (r != 0) return r;
}
}
*src = p;
return 0;
}
static const char* PopularQStr[] = {
"?", "*", "+", "??", "*?", "+?"
};
static const char* ReduceQStr[] = {
"", "", "*", "*?", "??", "+ and ??", "+? and ?"
};
static int
set_quantifier(Node* qnode, Node* target, int group, ScanEnv* env)
{
QtfrNode* qn;
qn = NQTFR(qnode);
if (qn->lower == 1 && qn->upper == 1) {
return 1;
}
switch (NTYPE(target)) {
case NT_STR:
if (! group) {
StrNode* sn = NSTR(target);
if (str_node_can_be_split(sn, env->enc)) {
Node* n = str_node_split_last_char(sn, env->enc);
if (IS_NOT_NULL(n)) {
qn->target = n;
return 2;
}
}
}
break;
case NT_QTFR:
{ /* check redundant double repeat. */
/* verbose warn (?:.?)? etc... but not warn (.?)? etc... */
QtfrNode* qnt = NQTFR(target);
int nestq_num = popular_quantifier_num(qn);
int targetq_num = popular_quantifier_num(qnt);
#ifdef USE_WARNING_REDUNDANT_NESTED_REPEAT_OPERATOR
if (!IS_QUANTIFIER_BY_NUMBER(qn) && !IS_QUANTIFIER_BY_NUMBER(qnt) &&
IS_SYNTAX_BV(env->syntax, ONIG_SYN_WARN_REDUNDANT_NESTED_REPEAT)) {
UChar buf[WARN_BUFSIZE];
switch(ReduceTypeTable[targetq_num][nestq_num]) {
case RQ_ASIS:
break;
case RQ_DEL:
if (onig_verb_warn != onig_null_warn) {
onig_snprintf_with_pattern(buf, WARN_BUFSIZE, env->enc,
env->pattern, env->pattern_end,
(UChar* )"redundant nested repeat operator");
(*onig_verb_warn)((char* )buf);
}
goto warn_exit;
break;
default:
if (onig_verb_warn != onig_null_warn) {
onig_snprintf_with_pattern(buf, WARN_BUFSIZE, env->enc,
env->pattern, env->pattern_end,
(UChar* )"nested repeat operator %s and %s was replaced with '%s'",
PopularQStr[targetq_num], PopularQStr[nestq_num],
ReduceQStr[ReduceTypeTable[targetq_num][nestq_num]]);
(*onig_verb_warn)((char* )buf);
}
goto warn_exit;
break;
}
}
warn_exit:
#endif
if (targetq_num >= 0) {
if (nestq_num >= 0) {
onig_reduce_nested_quantifier(qnode, target);
goto q_exit;
}
else if (targetq_num == 1 || targetq_num == 2) { /* * or + */
/* (?:a*){n,m}, (?:a+){n,m} => (?:a*){n,n}, (?:a+){n,n} */
if (! IS_REPEAT_INFINITE(qn->upper) && qn->upper > 1 && qn->greedy) {
qn->upper = (qn->lower == 0 ? 1 : qn->lower);
}
}
}
}
break;
default:
break;
}
qn->target = target;
q_exit:
return 0;
}
#ifndef CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS
static int
clear_not_flag_cclass(CClassNode* cc, OnigEncoding enc)
{
BBuf *tbuf;
int r;
if (IS_NCCLASS_NOT(cc)) {
bitset_invert(cc->bs);
if (! ONIGENC_IS_SINGLEBYTE(enc)) {
r = not_code_range_buf(enc, cc->mbuf, &tbuf);
if (r != 0) return r;
bbuf_free(cc->mbuf);
cc->mbuf = tbuf;
}
NCCLASS_CLEAR_NOT(cc);
}
return 0;
}
#endif /* CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS */
typedef struct {
ScanEnv* env;
CClassNode* cc;
Node* alt_root;
Node** ptail;
} IApplyCaseFoldArg;
static int
i_apply_case_fold(OnigCodePoint from, OnigCodePoint to[],
int to_len, void* arg)
{
IApplyCaseFoldArg* iarg;
ScanEnv* env;
CClassNode* cc;
BitSetRef bs;
iarg = (IApplyCaseFoldArg* )arg;
env = iarg->env;
cc = iarg->cc;
bs = cc->bs;
if (to_len == 1) {
int is_in = onig_is_code_in_cc(env->enc, from, cc);
#ifdef CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS
if ((is_in != 0 && !IS_NCCLASS_NOT(cc)) ||
(is_in == 0 && IS_NCCLASS_NOT(cc))) {
if (ONIGENC_MBC_MINLEN(env->enc) > 1 || *to >= SINGLE_BYTE_SIZE) {
add_code_range(&(cc->mbuf), env, *to, *to);
}
else {
BITSET_SET_BIT(bs, *to);
}
}
#else
if (is_in != 0) {
if (ONIGENC_MBC_MINLEN(env->enc) > 1 || *to >= SINGLE_BYTE_SIZE) {
if (IS_NCCLASS_NOT(cc)) clear_not_flag_cclass(cc, env->enc);
add_code_range(&(cc->mbuf), env, *to, *to);
}
else {
if (IS_NCCLASS_NOT(cc)) {
BITSET_CLEAR_BIT(bs, *to);
}
else
BITSET_SET_BIT(bs, *to);
}
}
#endif /* CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS */
}
else {
int r, i, len;
UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN];
Node *snode = NULL_NODE;
if (onig_is_code_in_cc(env->enc, from, cc)
#ifdef CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS
&& !IS_NCCLASS_NOT(cc)
#endif
) {
for (i = 0; i < to_len; i++) {
len = ONIGENC_CODE_TO_MBC(env->enc, to[i], buf);
if (i == 0) {
snode = onig_node_new_str(buf, buf + len);
CHECK_NULL_RETURN_MEMERR(snode);
/* char-class expanded multi-char only
compare with string folded at match time. */
NSTRING_SET_AMBIG(snode);
}
else {
r = onig_node_str_cat(snode, buf, buf + len);
if (r < 0) {
onig_node_free(snode);
return r;
}
}
}
*(iarg->ptail) = onig_node_new_alt(snode, NULL_NODE);
CHECK_NULL_RETURN_MEMERR(*(iarg->ptail));
iarg->ptail = &(NCDR((*(iarg->ptail))));
}
}
return 0;
}
static int
parse_exp(Node** np, OnigToken* tok, int term,
UChar** src, UChar* end, ScanEnv* env)
{
int r, len, group = 0;
Node* qn;
Node** targetp;
*np = NULL;
if (tok->type == (enum TokenSyms )term)
goto end_of_token;
switch (tok->type) {
case TK_ALT:
case TK_EOT:
end_of_token:
*np = node_new_empty();
return tok->type;
break;
case TK_SUBEXP_OPEN:
r = parse_enclose(np, tok, TK_SUBEXP_CLOSE, src, end, env);
if (r < 0) return r;
if (r == 1) group = 1;
else if (r == 2) { /* option only */
Node* target;
OnigOptionType prev = env->option;
env->option = NENCLOSE(*np)->option;
r = fetch_token(tok, src, end, env);
if (r < 0) return r;
r = parse_subexp(&target, tok, term, src, end, env);
env->option = prev;
if (r < 0) {
onig_node_free(target);
return r;
}
NENCLOSE(*np)->target = target;
return tok->type;
}
break;
case TK_SUBEXP_CLOSE:
if (! IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_UNMATCHED_CLOSE_SUBEXP))
return ONIGERR_UNMATCHED_CLOSE_PARENTHESIS;
if (tok->escaped) goto tk_raw_byte;
else goto tk_byte;
break;
case TK_STRING:
tk_byte:
{
*np = node_new_str(tok->backp, *src);
CHECK_NULL_RETURN_MEMERR(*np);
while (1) {
r = fetch_token(tok, src, end, env);
if (r < 0) return r;
if (r != TK_STRING) break;
r = onig_node_str_cat(*np, tok->backp, *src);
if (r < 0) return r;
}
string_end:
targetp = np;
goto repeat;
}
break;
case TK_RAW_BYTE:
tk_raw_byte:
{
*np = node_new_str_raw_char((UChar )tok->u.c);
CHECK_NULL_RETURN_MEMERR(*np);
len = 1;
while (1) {
if (len >= ONIGENC_MBC_MINLEN(env->enc)) {
if (len == enclen(env->enc, NSTR(*np)->s)) {//should not enclen_end()
r = fetch_token(tok, src, end, env);
NSTRING_CLEAR_RAW(*np);
goto string_end;
}
}
r = fetch_token(tok, src, end, env);
if (r < 0) return r;
if (r != TK_RAW_BYTE) {
/* Don't use this, it is wrong for little endian encodings. */
#ifdef USE_PAD_TO_SHORT_BYTE_CHAR
int rem;
if (len < ONIGENC_MBC_MINLEN(env->enc)) {
rem = ONIGENC_MBC_MINLEN(env->enc) - len;
(void )node_str_head_pad(NSTR(*np), rem, (UChar )0);
if (len + rem == enclen(env->enc, NSTR(*np)->s)) {
NSTRING_CLEAR_RAW(*np);
goto string_end;
}
}
#endif
return ONIGERR_TOO_SHORT_MULTI_BYTE_STRING;
}
r = node_str_cat_char(*np, (UChar )tok->u.c);
if (r < 0) return r;
len++;
}
}
break;
case TK_CODE_POINT:
{
UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN];
int num = ONIGENC_CODE_TO_MBC(env->enc, tok->u.code, buf);
if (num < 0) return num;
#ifdef NUMBERED_CHAR_IS_NOT_CASE_AMBIG
*np = node_new_str_raw(buf, buf + num);
#else
*np = node_new_str(buf, buf + num);
#endif
CHECK_NULL_RETURN_MEMERR(*np);
}
break;
case TK_QUOTE_OPEN:
{
OnigCodePoint end_op[2];
UChar *qstart, *qend, *nextp;
end_op[0] = (OnigCodePoint )MC_ESC(env->syntax);
end_op[1] = (OnigCodePoint )'E';
qstart = *src;
qend = find_str_position(end_op, 2, qstart, end, &nextp, env->enc);
if (IS_NULL(qend)) {
nextp = qend = end;
}
*np = node_new_str(qstart, qend);
CHECK_NULL_RETURN_MEMERR(*np);
*src = nextp;
}
break;
case TK_CHAR_TYPE:
{
switch (tok->u.prop.ctype) {
case ONIGENC_CTYPE_WORD:
*np = node_new_ctype(tok->u.prop.ctype, tok->u.prop.not);
CHECK_NULL_RETURN_MEMERR(*np);
break;
case ONIGENC_CTYPE_SPACE:
case ONIGENC_CTYPE_DIGIT:
case ONIGENC_CTYPE_XDIGIT:
{
CClassNode* cc;
*np = node_new_cclass();
CHECK_NULL_RETURN_MEMERR(*np);
cc = NCCLASS(*np);
add_ctype_to_cc(cc, tok->u.prop.ctype, 0, env);
if (tok->u.prop.not != 0) NCCLASS_SET_NOT(cc);
}
break;
default:
return ONIGERR_PARSER_BUG;
break;
}
}
break;
case TK_CHAR_PROPERTY:
r = parse_char_property(np, tok, src, end, env);
if (r != 0) return r;
break;
case TK_CC_OPEN:
{
CClassNode* cc;
r = parse_char_class(np, tok, src, end, env);
if (r != 0) return r;
cc = NCCLASS(*np);
if (IS_IGNORECASE(env->option)) {
IApplyCaseFoldArg iarg;
iarg.env = env;
iarg.cc = cc;
iarg.alt_root = NULL_NODE;
iarg.ptail = &(iarg.alt_root);
r = ONIGENC_APPLY_ALL_CASE_FOLD(env->enc, env->case_fold_flag,
i_apply_case_fold, &iarg);
if (r != 0) {
onig_node_free(iarg.alt_root);
return r;
}
if (IS_NOT_NULL(iarg.alt_root)) {
Node* work = onig_node_new_alt(*np, iarg.alt_root);
if (IS_NULL(work)) {
onig_node_free(iarg.alt_root);
return ONIGERR_MEMORY;
}
*np = work;
}
}
}
break;
case TK_ANYCHAR:
*np = node_new_anychar();
CHECK_NULL_RETURN_MEMERR(*np);
break;
case TK_ANYCHAR_ANYTIME:
*np = node_new_anychar();
CHECK_NULL_RETURN_MEMERR(*np);
qn = node_new_quantifier(0, REPEAT_INFINITE, 0);
CHECK_NULL_RETURN_MEMERR(qn);
NQTFR(qn)->target = *np;
*np = qn;
break;
case TK_BACKREF:
len = tok->u.backref.num;
*np = node_new_backref(len,
(len > 1 ? tok->u.backref.refs : &(tok->u.backref.ref1)),
tok->u.backref.by_name,
#ifdef USE_BACKREF_WITH_LEVEL
tok->u.backref.exist_level,
tok->u.backref.level,
#endif
env);
CHECK_NULL_RETURN_MEMERR(*np);
break;
#ifdef USE_SUBEXP_CALL
case TK_CALL:
{
int gnum = tok->u.call.gnum;
if (gnum < 0) {
gnum = BACKREF_REL_TO_ABS(gnum, env);
if (gnum <= 0)
return ONIGERR_INVALID_BACKREF;
}
*np = node_new_call(tok->u.call.name, tok->u.call.name_end, gnum);
CHECK_NULL_RETURN_MEMERR(*np);
env->num_call++;
}
break;
#endif
case TK_ANCHOR:
*np = onig_node_new_anchor(tok->u.anchor);
break;
case TK_OP_REPEAT:
case TK_INTERVAL:
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_CONTEXT_INDEP_REPEAT_OPS)) {
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_CONTEXT_INVALID_REPEAT_OPS))
return ONIGERR_TARGET_OF_REPEAT_OPERATOR_NOT_SPECIFIED;
else
*np = node_new_empty();
}
else {
goto tk_byte;
}
break;
default:
return ONIGERR_PARSER_BUG;
break;
}
{
targetp = np;
re_entry:
r = fetch_token(tok, src, end, env);
if (r < 0) return r;
repeat:
if (r == TK_OP_REPEAT || r == TK_INTERVAL) {
if (is_invalid_quantifier_target(*targetp))
return ONIGERR_TARGET_OF_REPEAT_OPERATOR_INVALID;
qn = node_new_quantifier(tok->u.repeat.lower, tok->u.repeat.upper,
(r == TK_INTERVAL ? 1 : 0));
CHECK_NULL_RETURN_MEMERR(qn);
NQTFR(qn)->greedy = tok->u.repeat.greedy;
r = set_quantifier(qn, *targetp, group, env);
if (r < 0) {
onig_node_free(qn);
return r;
}
if (tok->u.repeat.possessive != 0) {
Node* en;
en = node_new_enclose(ENCLOSE_STOP_BACKTRACK);
if (IS_NULL(en)) {
onig_node_free(qn);
return ONIGERR_MEMORY;
}
NENCLOSE(en)->target = qn;
qn = en;
}
if (r == 0) {
*targetp = qn;
}
else if (r == 1) {
onig_node_free(qn);
}
else if (r == 2) { /* split case: /abc+/ */
Node *tmp;
*targetp = node_new_list(*targetp, NULL);
if (IS_NULL(*targetp)) {
onig_node_free(qn);
return ONIGERR_MEMORY;
}
tmp = NCDR(*targetp) = node_new_list(qn, NULL);
if (IS_NULL(tmp)) {
onig_node_free(qn);
return ONIGERR_MEMORY;
}
targetp = &(NCAR(tmp));
}
goto re_entry;
}
}
return r;
}
static int
parse_branch(Node** top, OnigToken* tok, int term,
UChar** src, UChar* end, ScanEnv* env)
{
int r;
Node *node, **headp;
*top = NULL;
r = parse_exp(&node, tok, term, src, end, env);
if (r < 0) {
onig_node_free(node);
return r;
}
if (r == TK_EOT || r == term || r == TK_ALT) {
*top = node;
}
else {
*top = node_new_list(node, NULL);
headp = &(NCDR(*top));
while (r != TK_EOT && r != term && r != TK_ALT) {
r = parse_exp(&node, tok, term, src, end, env);
if (r < 0) {
onig_node_free(node);
return r;
}
if (NTYPE(node) == NT_LIST) {
*headp = node;
while (IS_NOT_NULL(NCDR(node))) node = NCDR(node);
headp = &(NCDR(node));
}
else {
*headp = node_new_list(node, NULL);
headp = &(NCDR(*headp));
}
}
}
return r;
}
/* term_tok: TK_EOT or TK_SUBEXP_CLOSE */
static int
parse_subexp(Node** top, OnigToken* tok, int term,
UChar** src, UChar* end, ScanEnv* env)
{
int r;
Node *node, **headp;
*top = NULL;
env->parse_depth++;
if (env->parse_depth > ParseDepthLimit)
return ONIGERR_PARSE_DEPTH_LIMIT_OVER;
r = parse_branch(&node, tok, term, src, end, env);
if (r < 0) {
onig_node_free(node);
return r;
}
if (r == term) {
*top = node;
}
else if (r == TK_ALT) {
*top = onig_node_new_alt(node, NULL);
headp = &(NCDR(*top));
while (r == TK_ALT) {
r = fetch_token(tok, src, end, env);
if (r < 0) return r;
r = parse_branch(&node, tok, term, src, end, env);
if (r < 0) {
onig_node_free(node);
return r;
}
*headp = onig_node_new_alt(node, NULL);
headp = &(NCDR(*headp));
}
if (tok->type != (enum TokenSyms )term)
goto err;
}
else {
onig_node_free(node);
err:
if (term == TK_SUBEXP_CLOSE)
return ONIGERR_END_PATTERN_WITH_UNMATCHED_PARENTHESIS;
else
return ONIGERR_PARSER_BUG;
}
env->parse_depth--;
return r;
}
static int
parse_regexp(Node** top, UChar** src, UChar* end, ScanEnv* env)
{
int r;
OnigToken tok;
r = fetch_token(&tok, src, end, env);
if (r < 0) return r;
r = parse_subexp(top, &tok, TK_EOT, src, end, env);
if (r < 0) return r;
return 0;
}
extern int
onig_parse_make_tree(Node** root, const UChar* pattern, const UChar* end,
regex_t* reg, ScanEnv* env)
{
int r;
UChar* p;
#ifdef USE_NAMED_GROUP
names_clear(reg);
#endif
scan_env_clear(env);
env->option = reg->options;
env->case_fold_flag = reg->case_fold_flag;
env->enc = reg->enc;
env->syntax = reg->syntax;
env->pattern = (UChar* )pattern;
env->pattern_end = (UChar* )end;
env->reg = reg;
*root = NULL;
if (! ONIGENC_IS_VALID_MBC_STRING(env->enc, pattern, end))
return ONIGERR_INVALID_WIDE_CHAR_VALUE;
p = (UChar* )pattern;
r = parse_regexp(root, &p, (UChar* )end, env);
reg->num_mem = env->num_mem;
return r;
}
extern void
onig_scan_env_set_error_string(ScanEnv* env, int ecode ARG_UNUSED,
UChar* arg, UChar* arg_end)
{
env->error = arg;
env->error_end = arg_end;
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_3374_0 |
crossvul-cpp_data_bad_3172_1 | /*
* tnef.c -- extract files from microsoft TNEF format
*
* Copyright (C)1999-2006 Mark Simpson <damned@theworld.com>
* Copyright (C)1997 Thomas Boll <tb@boll.ch> [ORIGINAL AUTHOR]
*
* 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.
*
* Commentary:
* scans tnef file and extracts all attachments
* attachments are written to their original file-names if possible
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif /* HAVE_CONFIG_H */
#include "common.h"
#include "tnef.h"
#include "alloc.h"
#include "attr.h"
#include "debug.h"
#include "file.h"
#include "mapi_attr.h"
#include "options.h"
#include "path.h"
#include "rtf.h"
#include "util.h"
typedef struct
{
VarLenData **text_body;
VarLenData **html_bodies;
VarLenData **rtf_bodies;
} MessageBody;
typedef enum
{
TEXT = 't',
HTML = 'h',
RTF = 'r'
} MessageBodyTypes;
/* Reads and decodes a object from the stream */
static Attr*
read_object (FILE *in)
{
Attr *attr = NULL;
/* peek to see if there is more to read from this stream */
int tmp_char = fgetc(in);
if (tmp_char == -1) return NULL;
ungetc(tmp_char, in);
attr = attr_read (in);
return attr;
}
static void
free_bodies(VarLenData **bodies, int len)
{
while (len--)
{
XFREE(bodies[len]->data);
XFREE(bodies[len]);
}
}
static File**
get_body_files (const char* filename,
const char pref,
const MessageBody* body)
{
File **files = NULL;
VarLenData **data;
char *ext = "";
char *type = "unknown";
int i;
switch (pref)
{
case 'r':
data = body->rtf_bodies;
ext = ".rtf";
type = "text/rtf";
break;
case 'h':
data = body->html_bodies;
ext = ".html";
type = "text/html";
break;
case 't':
data = body->text_body;
ext = ".txt";
type = "text/plain";
break;
default:
data = NULL;
break;
}
if (data)
{
int count = 0;
char *tmp
= CHECKED_XCALLOC(char,
strlen(filename) + strlen(ext) + 1);
strcpy (tmp, filename);
strcat (tmp, ext);
char *mime = CHECKED_XCALLOC(char, strlen(type) + 1);
strcpy (mime, type);
/* first get a count */
while (data[count++]);
files = (File**)XCALLOC(File*, count + 1);
for (i = 0; data[i]; i++)
{
files[i] = (File*)XCALLOC(File, 1);
files[i]->name = tmp;
files[i]->mime_type = mime;
files[i]->len = data[i]->len;
files[i]->data
= CHECKED_XMALLOC(unsigned char, data[i]->len);
memmove (files[i]->data, data[i]->data, data[i]->len);
}
}
return files;
}
static VarLenData**
get_text_data (Attr *attr)
{
VarLenData **body = XCALLOC(VarLenData*, 2);
body[0] = XCALLOC(VarLenData, 1);
body[0]->len = attr->len;
body[0]->data = CHECKED_XCALLOC(unsigned char, attr->len);
memmove (body[0]->data, attr->buf, attr->len);
return body;
}
static VarLenData**
get_html_data (MAPI_Attr *a)
{
VarLenData **body = XCALLOC(VarLenData*, a->num_values + 1);
int j;
for (j = 0; j < a->num_values; j++)
{
body[j] = XMALLOC(VarLenData, 1);
body[j]->len = a->values[j].len;
body[j]->data = CHECKED_XCALLOC(unsigned char, a->values[j].len);
memmove (body[j]->data, a->values[j].data.buf, body[j]->len);
}
return body;
}
int
data_left (FILE* input_file)
{
int retval = 1;
if (feof(input_file)) retval = 0;
else if (input_file != stdin)
{
/* check if there is enough data left */
struct stat statbuf;
size_t pos, data_left;
fstat (fileno(input_file), &statbuf);
pos = ftell(input_file);
data_left = (statbuf.st_size - pos);
if (data_left > 0 && data_left < MINIMUM_ATTR_LENGTH)
{
if ( CRUFT_SKIP )
{
/* look for specific flavor of cruft -- trailing "\r\n" */
if ( data_left == 2 )
{
int c = fgetc( input_file );
if ( c < 0 ) /* this should never happen */
{
fprintf( stderr, "ERROR: confused beyond all redemption.\n" );
exit (1);
}
ungetc( c, input_file );
if ( c == 0x0d ) /* test for "\r" part of "\r\n" */
{
/* "trust" that next char is 0x0a and ignore this cruft */
if ( VERBOSE_ON )
fprintf( stderr, "WARNING: garbage at end of file (ignored)\n" );
if ( DEBUG_ON )
debug_print( "!!garbage at end of file (ignored)\n" );
}
else
{
fprintf( stderr, "ERROR: garbage at end of file.\n" );
}
}
else
{
fprintf (stderr, "ERROR: garbage at end of file.\n");
}
}
else
{
fprintf (stderr, "ERROR: garbage at end of file.\n");
}
retval = 0;
}
}
return retval;
}
/* The entry point into this module. This parses an entire TNEF file. */
int
parse_file (FILE* input_file, char* directory,
char *body_filename, char *body_pref,
int flags)
{
uint32 d;
uint16 key;
Attr *attr = NULL;
File *file = NULL;
int rtf_size = 0, html_size = 0;
MessageBody body;
memset (&body, '\0', sizeof (MessageBody));
/* store the program options in our file global variables */
g_flags = flags;
/* check that this is in fact a TNEF file */
d = geti32(input_file);
if (d != TNEF_SIGNATURE)
{
fprintf (stdout, "Seems not to be a TNEF file\n");
return 1;
}
/* Get the key */
key = geti16(input_file);
debug_print ("TNEF Key: %hx\n", key);
/* The rest of the file is a series of 'messages' and 'attachments' */
while ( data_left( input_file ) )
{
attr = read_object( input_file );
if ( attr == NULL ) break;
/* This signals the beginning of a file */
if (attr->name == attATTACHRENDDATA)
{
if (file)
{
file_write (file, directory);
file_free (file);
}
else
{
file = CHECKED_XCALLOC (File, 1);
}
}
/* Add the data to our lists. */
switch (attr->lvl_type)
{
case LVL_MESSAGE:
if (attr->name == attBODY)
{
body.text_body = get_text_data (attr);
}
else if (attr->name == attMAPIPROPS)
{
MAPI_Attr **mapi_attrs
= mapi_attr_read (attr->len, attr->buf);
if (mapi_attrs)
{
int i;
for (i = 0; mapi_attrs[i]; i++)
{
MAPI_Attr *a = mapi_attrs[i];
if (a->name == MAPI_BODY_HTML)
{
body.html_bodies = get_html_data (a);
html_size = a->num_values;
}
else if (a->name == MAPI_RTF_COMPRESSED)
{
body.rtf_bodies = get_rtf_data (a);
rtf_size = a->num_values;
}
}
/* cannot save attributes to file, since they
* are not attachment attributes */
/* file_add_mapi_attrs (file, mapi_attrs); */
mapi_attr_free_list (mapi_attrs);
XFREE (mapi_attrs);
}
}
break;
case LVL_ATTACHMENT:
file_add_attr (file, attr);
break;
default:
fprintf (stderr, "Invalid lvl type on attribute: %d\n",
attr->lvl_type);
return 1;
break;
}
attr_free (attr);
XFREE (attr);
}
if (file)
{
file_write (file, directory);
file_free (file);
XFREE (file);
}
/* Write the message body */
if (flags & SAVEBODY)
{
int i = 0;
int all_flag = 0;
if (strcmp (body_pref, "all") == 0)
{
all_flag = 1;
body_pref = "rht";
}
for (; i < 3; i++)
{
File **files
= get_body_files (body_filename, body_pref[i], &body);
if (files)
{
int j = 0;
for (; files[j]; j++)
{
file_write(files[j], directory);
file_free (files[j]);
XFREE(files[j]);
}
XFREE(files);
if (!all_flag) break;
}
}
}
if (body.text_body)
{
free_bodies(body.text_body, 1);
XFREE(body.text_body);
}
if (rtf_size > 0)
{
free_bodies(body.rtf_bodies, rtf_size);
XFREE(body.rtf_bodies);
}
if (html_size > 0)
{
free_bodies(body.html_bodies, html_size);
XFREE(body.html_bodies);
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_3172_1 |
crossvul-cpp_data_good_277_2 | /* This file is part of libmspack.
* (C) 2003-2011 Stuart Caie.
*
* KWAJ is a format very similar to SZDD. KWAJ method 3 (LZH) was
* written by Jeff Johnson.
*
* libmspack is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License (LGPL) version 2.1
*
* For further details, see the file COPYING.LIB distributed with libmspack
*/
/* KWAJ decompression implementation */
#include <system.h>
#include <kwaj.h>
#include <mszip.h>
/* prototypes */
static struct mskwajd_header *kwajd_open(
struct mskwaj_decompressor *base, const char *filename);
static void kwajd_close(
struct mskwaj_decompressor *base, struct mskwajd_header *hdr);
static int kwajd_read_headers(
struct mspack_system *sys, struct mspack_file *fh,
struct mskwajd_header *hdr);
static int kwajd_extract(
struct mskwaj_decompressor *base, struct mskwajd_header *hdr,
const char *filename);
static int kwajd_decompress(
struct mskwaj_decompressor *base, const char *input, const char *output);
static int kwajd_error(
struct mskwaj_decompressor *base);
static struct kwajd_stream *lzh_init(
struct mspack_system *sys, struct mspack_file *in, struct mspack_file *out);
static int lzh_decompress(
struct kwajd_stream *kwaj);
static void lzh_free(
struct kwajd_stream *kwaj);
static int lzh_read_lens(
struct kwajd_stream *kwaj,
unsigned int type, unsigned int numsyms,
unsigned char *lens);
static int lzh_read_input(
struct kwajd_stream *kwaj);
/***************************************
* MSPACK_CREATE_KWAJ_DECOMPRESSOR
***************************************
* constructor
*/
struct mskwaj_decompressor *
mspack_create_kwaj_decompressor(struct mspack_system *sys)
{
struct mskwaj_decompressor_p *self = NULL;
if (!sys) sys = mspack_default_system;
if (!mspack_valid_system(sys)) return NULL;
if ((self = (struct mskwaj_decompressor_p *) sys->alloc(sys, sizeof(struct mskwaj_decompressor_p)))) {
self->base.open = &kwajd_open;
self->base.close = &kwajd_close;
self->base.extract = &kwajd_extract;
self->base.decompress = &kwajd_decompress;
self->base.last_error = &kwajd_error;
self->system = sys;
self->error = MSPACK_ERR_OK;
}
return (struct mskwaj_decompressor *) self;
}
/***************************************
* MSPACK_DESTROY_KWAJ_DECOMPRESSOR
***************************************
* destructor
*/
void mspack_destroy_kwaj_decompressor(struct mskwaj_decompressor *base)
{
struct mskwaj_decompressor_p *self = (struct mskwaj_decompressor_p *) base;
if (self) {
struct mspack_system *sys = self->system;
sys->free(self);
}
}
/***************************************
* KWAJD_OPEN
***************************************
* opens a KWAJ file without decompressing, reads header
*/
static struct mskwajd_header *kwajd_open(struct mskwaj_decompressor *base,
const char *filename)
{
struct mskwaj_decompressor_p *self = (struct mskwaj_decompressor_p *) base;
struct mskwajd_header *hdr;
struct mspack_system *sys;
struct mspack_file *fh;
if (!self) return NULL;
sys = self->system;
fh = sys->open(sys, filename, MSPACK_SYS_OPEN_READ);
hdr = (struct mskwajd_header *) sys->alloc(sys, sizeof(struct mskwajd_header_p));
if (fh && hdr) {
((struct mskwajd_header_p *) hdr)->fh = fh;
self->error = kwajd_read_headers(sys, fh, hdr);
}
else {
if (!fh) self->error = MSPACK_ERR_OPEN;
if (!hdr) self->error = MSPACK_ERR_NOMEMORY;
}
if (self->error) {
if (fh) sys->close(fh);
if (hdr) sys->free(hdr);
hdr = NULL;
}
return hdr;
}
/***************************************
* KWAJD_CLOSE
***************************************
* closes a KWAJ file
*/
static void kwajd_close(struct mskwaj_decompressor *base,
struct mskwajd_header *hdr)
{
struct mskwaj_decompressor_p *self = (struct mskwaj_decompressor_p *) base;
struct mskwajd_header_p *hdr_p = (struct mskwajd_header_p *) hdr;
if (!self || !self->system) return;
/* close the file handle associated */
self->system->close(hdr_p->fh);
/* free the memory associated */
self->system->free(hdr);
self->error = MSPACK_ERR_OK;
}
/***************************************
* KWAJD_READ_HEADERS
***************************************
* reads the headers of a KWAJ format file
*/
static int kwajd_read_headers(struct mspack_system *sys,
struct mspack_file *fh,
struct mskwajd_header *hdr)
{
unsigned char buf[16];
int i;
/* read in the header */
if (sys->read(fh, &buf[0], kwajh_SIZEOF) != kwajh_SIZEOF) {
return MSPACK_ERR_READ;
}
/* check for "KWAJ" signature */
if (((unsigned int) EndGetI32(&buf[kwajh_Signature1]) != 0x4A41574B) ||
((unsigned int) EndGetI32(&buf[kwajh_Signature2]) != 0xD127F088))
{
return MSPACK_ERR_SIGNATURE;
}
/* basic header fields */
hdr->comp_type = EndGetI16(&buf[kwajh_CompMethod]);
hdr->data_offset = EndGetI16(&buf[kwajh_DataOffset]);
hdr->headers = EndGetI16(&buf[kwajh_Flags]);
hdr->length = 0;
hdr->filename = NULL;
hdr->extra = NULL;
hdr->extra_length = 0;
/* optional headers */
/* 4 bytes: length of unpacked file */
if (hdr->headers & MSKWAJ_HDR_HASLENGTH) {
if (sys->read(fh, &buf[0], 4) != 4) return MSPACK_ERR_READ;
hdr->length = EndGetI32(&buf[0]);
}
/* 2 bytes: unknown purpose */
if (hdr->headers & MSKWAJ_HDR_HASUNKNOWN1) {
if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ;
}
/* 2 bytes: length of section, then [length] bytes: unknown purpose */
if (hdr->headers & MSKWAJ_HDR_HASUNKNOWN2) {
if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ;
i = EndGetI16(&buf[0]);
if (sys->seek(fh, (off_t)i, MSPACK_SYS_SEEK_CUR)) return MSPACK_ERR_SEEK;
}
/* filename and extension */
if (hdr->headers & (MSKWAJ_HDR_HASFILENAME | MSKWAJ_HDR_HASFILEEXT)) {
int len;
/* allocate memory for maximum length filename */
char *fn = (char *) sys->alloc(sys, (size_t) 13);
if (!(hdr->filename = fn)) return MSPACK_ERR_NOMEMORY;
/* copy filename if present */
if (hdr->headers & MSKWAJ_HDR_HASFILENAME) {
/* read and copy up to 9 bytes of a null terminated string */
if ((len = sys->read(fh, &buf[0], 9)) < 2) return MSPACK_ERR_READ;
for (i = 0; i < len; i++) if (!(*fn++ = buf[i])) break;
/* if string was 9 bytes with no null terminator, reject it */
if (i == 9 && buf[8] != '\0') return MSPACK_ERR_DATAFORMAT;
/* seek to byte after string ended in file */
if (sys->seek(fh, (off_t)(i + 1 - len), MSPACK_SYS_SEEK_CUR))
return MSPACK_ERR_SEEK;
fn--; /* remove the null terminator */
}
/* copy extension if present */
if (hdr->headers & MSKWAJ_HDR_HASFILEEXT) {
*fn++ = '.';
/* read and copy up to 4 bytes of a null terminated string */
if ((len = sys->read(fh, &buf[0], 4)) < 2) return MSPACK_ERR_READ;
for (i = 0; i < len; i++) if (!(*fn++ = buf[i])) break;
/* if string was 4 bytes with no null terminator, reject it */
if (i == 4 && buf[3] != '\0') return MSPACK_ERR_DATAFORMAT;
/* seek to byte after string ended in file */
if (sys->seek(fh, (off_t)(i + 1 - len), MSPACK_SYS_SEEK_CUR))
return MSPACK_ERR_SEEK;
fn--; /* remove the null terminator */
}
*fn = '\0';
}
/* 2 bytes: extra text length then [length] bytes of extra text data */
if (hdr->headers & MSKWAJ_HDR_HASEXTRATEXT) {
if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ;
i = EndGetI16(&buf[0]);
hdr->extra = (char *) sys->alloc(sys, (size_t)i+1);
if (! hdr->extra) return MSPACK_ERR_NOMEMORY;
if (sys->read(fh, hdr->extra, i) != i) return MSPACK_ERR_READ;
hdr->extra[i] = '\0';
hdr->extra_length = i;
}
return MSPACK_ERR_OK;
}
/***************************************
* KWAJD_EXTRACT
***************************************
* decompresses a KWAJ file
*/
static int kwajd_extract(struct mskwaj_decompressor *base,
struct mskwajd_header *hdr, const char *filename)
{
struct mskwaj_decompressor_p *self = (struct mskwaj_decompressor_p *) base;
struct mspack_system *sys;
struct mspack_file *fh, *outfh;
if (!self) return MSPACK_ERR_ARGS;
if (!hdr) return self->error = MSPACK_ERR_ARGS;
sys = self->system;
fh = ((struct mskwajd_header_p *) hdr)->fh;
/* seek to the compressed data */
if (sys->seek(fh, hdr->data_offset, MSPACK_SYS_SEEK_START)) {
return self->error = MSPACK_ERR_SEEK;
}
/* open file for output */
if (!(outfh = sys->open(sys, filename, MSPACK_SYS_OPEN_WRITE))) {
return self->error = MSPACK_ERR_OPEN;
}
self->error = MSPACK_ERR_OK;
/* decompress based on format */
if (hdr->comp_type == MSKWAJ_COMP_NONE ||
hdr->comp_type == MSKWAJ_COMP_XOR)
{
/* NONE is a straight copy. XOR is a copy xored with 0xFF */
unsigned char *buf = (unsigned char *) sys->alloc(sys, (size_t) KWAJ_INPUT_SIZE);
if (buf) {
int read, i;
while ((read = sys->read(fh, buf, KWAJ_INPUT_SIZE)) > 0) {
if (hdr->comp_type == MSKWAJ_COMP_XOR) {
for (i = 0; i < read; i++) buf[i] ^= 0xFF;
}
if (sys->write(outfh, buf, read) != read) {
self->error = MSPACK_ERR_WRITE;
break;
}
}
if (read < 0) self->error = MSPACK_ERR_READ;
sys->free(buf);
}
else {
self->error = MSPACK_ERR_NOMEMORY;
}
}
else if (hdr->comp_type == MSKWAJ_COMP_SZDD) {
self->error = lzss_decompress(sys, fh, outfh, KWAJ_INPUT_SIZE,
LZSS_MODE_EXPAND);
}
else if (hdr->comp_type == MSKWAJ_COMP_LZH) {
struct kwajd_stream *lzh = lzh_init(sys, fh, outfh);
self->error = (lzh) ? lzh_decompress(lzh) : MSPACK_ERR_NOMEMORY;
lzh_free(lzh);
}
else if (hdr->comp_type == MSKWAJ_COMP_MSZIP) {
struct mszipd_stream *zip = mszipd_init(sys,fh,outfh,KWAJ_INPUT_SIZE,0);
self->error = (zip) ? mszipd_decompress_kwaj(zip) : MSPACK_ERR_NOMEMORY;
mszipd_free(zip);
}
else {
self->error = MSPACK_ERR_DATAFORMAT;
}
/* close output file */
sys->close(outfh);
return self->error;
}
/***************************************
* KWAJD_DECOMPRESS
***************************************
* unpacks directly from input to output
*/
static int kwajd_decompress(struct mskwaj_decompressor *base,
const char *input, const char *output)
{
struct mskwaj_decompressor_p *self = (struct mskwaj_decompressor_p *) base;
struct mskwajd_header *hdr;
int error;
if (!self) return MSPACK_ERR_ARGS;
if (!(hdr = kwajd_open(base, input))) return self->error;
error = kwajd_extract(base, hdr, output);
kwajd_close(base, hdr);
return self->error = error;
}
/***************************************
* KWAJD_ERROR
***************************************
* returns the last error that occurred
*/
static int kwajd_error(struct mskwaj_decompressor *base)
{
struct mskwaj_decompressor_p *self = (struct mskwaj_decompressor_p *) base;
return (self) ? self->error : MSPACK_ERR_ARGS;
}
/***************************************
* LZH_INIT, LZH_DECOMPRESS, LZH_FREE
***************************************
* unpacks KWAJ method 3 files
*/
/* import bit-reading macros and code */
#define BITS_TYPE struct kwajd_stream
#define BITS_VAR lzh
#define BITS_ORDER_MSB
#define BITS_NO_READ_INPUT
#define READ_BYTES do { \
if (i_ptr >= i_end) { \
if ((err = lzh_read_input(lzh))) return err; \
i_ptr = lzh->i_ptr; \
i_end = lzh->i_end; \
} \
INJECT_BITS(*i_ptr++, 8); \
} while (0)
#include <readbits.h>
/* import huffman-reading macros and code */
#define TABLEBITS(tbl) KWAJ_TABLEBITS
#define MAXSYMBOLS(tbl) KWAJ_##tbl##_SYMS
#define HUFF_TABLE(tbl,idx) lzh->tbl##_table[idx]
#define HUFF_LEN(tbl,idx) lzh->tbl##_len[idx]
#define HUFF_ERROR return MSPACK_ERR_DATAFORMAT
#include <readhuff.h>
/* In the KWAJ LZH format, there is no special 'eof' marker, it just
* ends. Depending on how many bits are left in the final byte when
* the stream ends, that might be enough to start another literal or
* match. The only easy way to detect that we've come to an end is to
* guard all bit-reading. We allow fake bits to be read once we reach
* the end of the stream, but we check if we then consumed any of
* those fake bits, after doing the READ_BITS / READ_HUFFSYM. This
* isn't how the default readbits.h read_input() works (it simply lets
* 2 fake bytes in then stops), so we implement our own.
*/
#define READ_BITS_SAFE(val, n) do { \
READ_BITS(val, n); \
if (lzh->input_end && bits_left < lzh->input_end) \
return MSPACK_ERR_OK; \
} while (0)
#define READ_HUFFSYM_SAFE(tbl, val) do { \
READ_HUFFSYM(tbl, val); \
if (lzh->input_end && bits_left < lzh->input_end) \
return MSPACK_ERR_OK; \
} while (0)
#define BUILD_TREE(tbl, type) \
STORE_BITS; \
err = lzh_read_lens(lzh, type, MAXSYMBOLS(tbl), &HUFF_LEN(tbl,0)); \
if (err) return err; \
RESTORE_BITS; \
if (make_decode_table(MAXSYMBOLS(tbl), TABLEBITS(tbl), \
&HUFF_LEN(tbl,0), &HUFF_TABLE(tbl,0))) \
return MSPACK_ERR_DATAFORMAT;
#define WRITE_BYTE do { \
if (lzh->sys->write(lzh->output, &lzh->window[pos], 1) != 1) \
return MSPACK_ERR_WRITE; \
} while (0)
static struct kwajd_stream *lzh_init(struct mspack_system *sys,
struct mspack_file *in, struct mspack_file *out)
{
struct kwajd_stream *lzh;
if (!sys || !in || !out) return NULL;
if (!(lzh = (struct kwajd_stream *) sys->alloc(sys, sizeof(struct kwajd_stream)))) return NULL;
lzh->sys = sys;
lzh->input = in;
lzh->output = out;
return lzh;
}
static int lzh_decompress(struct kwajd_stream *lzh)
{
register unsigned int bit_buffer;
register int bits_left, i;
register unsigned short sym;
unsigned char *i_ptr, *i_end, lit_run = 0;
int j, pos = 0, len, offset, err;
unsigned int types[6];
/* reset global state */
INIT_BITS;
RESTORE_BITS;
memset(&lzh->window[0], LZSS_WINDOW_FILL, (size_t) LZSS_WINDOW_SIZE);
/* read 6 encoding types (for byte alignment) but only 5 are needed */
for (i = 0; i < 6; i++) READ_BITS_SAFE(types[i], 4);
/* read huffman table symbol lengths and build huffman trees */
BUILD_TREE(MATCHLEN1, types[0]);
BUILD_TREE(MATCHLEN2, types[1]);
BUILD_TREE(LITLEN, types[2]);
BUILD_TREE(OFFSET, types[3]);
BUILD_TREE(LITERAL, types[4]);
while (!lzh->input_end) {
if (lit_run) READ_HUFFSYM_SAFE(MATCHLEN2, len);
else READ_HUFFSYM_SAFE(MATCHLEN1, len);
if (len > 0) {
len += 2;
lit_run = 0; /* not the end of a literal run */
READ_HUFFSYM_SAFE(OFFSET, j); offset = j << 6;
READ_BITS_SAFE(j, 6); offset |= j;
/* copy match as output and into the ring buffer */
while (len-- > 0) {
lzh->window[pos] = lzh->window[(pos+4096-offset) & 4095];
WRITE_BYTE;
pos++; pos &= 4095;
}
}
else {
READ_HUFFSYM_SAFE(LITLEN, len); len++;
lit_run = (len == 32) ? 0 : 1; /* end of a literal run? */
while (len-- > 0) {
READ_HUFFSYM_SAFE(LITERAL, j);
/* copy as output and into the ring buffer */
lzh->window[pos] = j;
WRITE_BYTE;
pos++; pos &= 4095;
}
}
}
return MSPACK_ERR_OK;
}
static void lzh_free(struct kwajd_stream *lzh)
{
struct mspack_system *sys;
if (!lzh || !lzh->sys) return;
sys = lzh->sys;
sys->free(lzh);
}
static int lzh_read_lens(struct kwajd_stream *lzh,
unsigned int type, unsigned int numsyms,
unsigned char *lens)
{
register unsigned int bit_buffer;
register int bits_left;
unsigned char *i_ptr, *i_end;
unsigned int i, c, sel;
int err;
RESTORE_BITS;
switch (type) {
case 0:
i = numsyms; c = (i==16)?4: (i==32)?5: (i==64)?6: (i==256)?8 :0;
for (i = 0; i < numsyms; i++) lens[i] = c;
break;
case 1:
READ_BITS_SAFE(c, 4); lens[0] = c;
for (i = 1; i < numsyms; i++) {
READ_BITS_SAFE(sel, 1); if (sel == 0) lens[i] = c;
else { READ_BITS_SAFE(sel, 1); if (sel == 0) lens[i] = ++c;
else { READ_BITS_SAFE(c, 4); lens[i] = c; }}
}
break;
case 2:
READ_BITS_SAFE(c, 4); lens[0] = c;
for (i = 1; i < numsyms; i++) {
READ_BITS_SAFE(sel, 2);
if (sel == 3) READ_BITS_SAFE(c, 4); else c += (char) sel-1;
lens[i] = c;
}
break;
case 3:
for (i = 0; i < numsyms; i++) {
READ_BITS_SAFE(c, 4); lens[i] = c;
}
break;
}
STORE_BITS;
return MSPACK_ERR_OK;
}
static int lzh_read_input(struct kwajd_stream *lzh) {
int read;
if (lzh->input_end) {
lzh->input_end += 8;
lzh->inbuf[0] = 0;
read = 1;
}
else {
read = lzh->sys->read(lzh->input, &lzh->inbuf[0], KWAJ_INPUT_SIZE);
if (read < 0) return MSPACK_ERR_READ;
if (read == 0) {
lzh->input_end = 8;
lzh->inbuf[0] = 0;
read = 1;
}
}
/* update i_ptr and i_end */
lzh->i_ptr = &lzh->inbuf[0];
lzh->i_end = &lzh->inbuf[read];
return MSPACK_ERR_OK;
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_277_2 |
crossvul-cpp_data_bad_3296_0 | /*
* PNG image format
* Copyright (c) 2003 Fabrice Bellard
*
* This file is part of FFmpeg.
*
* FFmpeg 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.
*
* FFmpeg 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 FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
//#define DEBUG
#include "libavutil/avassert.h"
#include "libavutil/bprint.h"
#include "libavutil/imgutils.h"
#include "libavutil/stereo3d.h"
#include "avcodec.h"
#include "bytestream.h"
#include "internal.h"
#include "apng.h"
#include "png.h"
#include "pngdsp.h"
#include "thread.h"
#include <zlib.h>
typedef struct PNGDecContext {
PNGDSPContext dsp;
AVCodecContext *avctx;
GetByteContext gb;
ThreadFrame previous_picture;
ThreadFrame last_picture;
ThreadFrame picture;
int state;
int width, height;
int cur_w, cur_h;
int last_w, last_h;
int x_offset, y_offset;
int last_x_offset, last_y_offset;
uint8_t dispose_op, blend_op;
uint8_t last_dispose_op;
int bit_depth;
int color_type;
int compression_type;
int interlace_type;
int filter_type;
int channels;
int bits_per_pixel;
int bpp;
int has_trns;
uint8_t transparent_color_be[6];
uint8_t *image_buf;
int image_linesize;
uint32_t palette[256];
uint8_t *crow_buf;
uint8_t *last_row;
unsigned int last_row_size;
uint8_t *tmp_row;
unsigned int tmp_row_size;
uint8_t *buffer;
int buffer_size;
int pass;
int crow_size; /* compressed row size (include filter type) */
int row_size; /* decompressed row size */
int pass_row_size; /* decompress row size of the current pass */
int y;
z_stream zstream;
} PNGDecContext;
/* Mask to determine which pixels are valid in a pass */
static const uint8_t png_pass_mask[NB_PASSES] = {
0x01, 0x01, 0x11, 0x11, 0x55, 0x55, 0xff,
};
/* Mask to determine which y pixels can be written in a pass */
static const uint8_t png_pass_dsp_ymask[NB_PASSES] = {
0xff, 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
};
/* Mask to determine which pixels to overwrite while displaying */
static const uint8_t png_pass_dsp_mask[NB_PASSES] = {
0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff
};
/* NOTE: we try to construct a good looking image at each pass. width
* is the original image width. We also do pixel format conversion at
* this stage */
static void png_put_interlaced_row(uint8_t *dst, int width,
int bits_per_pixel, int pass,
int color_type, const uint8_t *src)
{
int x, mask, dsp_mask, j, src_x, b, bpp;
uint8_t *d;
const uint8_t *s;
mask = png_pass_mask[pass];
dsp_mask = png_pass_dsp_mask[pass];
switch (bits_per_pixel) {
case 1:
src_x = 0;
for (x = 0; x < width; x++) {
j = (x & 7);
if ((dsp_mask << j) & 0x80) {
b = (src[src_x >> 3] >> (7 - (src_x & 7))) & 1;
dst[x >> 3] &= 0xFF7F>>j;
dst[x >> 3] |= b << (7 - j);
}
if ((mask << j) & 0x80)
src_x++;
}
break;
case 2:
src_x = 0;
for (x = 0; x < width; x++) {
int j2 = 2 * (x & 3);
j = (x & 7);
if ((dsp_mask << j) & 0x80) {
b = (src[src_x >> 2] >> (6 - 2*(src_x & 3))) & 3;
dst[x >> 2] &= 0xFF3F>>j2;
dst[x >> 2] |= b << (6 - j2);
}
if ((mask << j) & 0x80)
src_x++;
}
break;
case 4:
src_x = 0;
for (x = 0; x < width; x++) {
int j2 = 4*(x&1);
j = (x & 7);
if ((dsp_mask << j) & 0x80) {
b = (src[src_x >> 1] >> (4 - 4*(src_x & 1))) & 15;
dst[x >> 1] &= 0xFF0F>>j2;
dst[x >> 1] |= b << (4 - j2);
}
if ((mask << j) & 0x80)
src_x++;
}
break;
default:
bpp = bits_per_pixel >> 3;
d = dst;
s = src;
for (x = 0; x < width; x++) {
j = x & 7;
if ((dsp_mask << j) & 0x80) {
memcpy(d, s, bpp);
}
d += bpp;
if ((mask << j) & 0x80)
s += bpp;
}
break;
}
}
void ff_add_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top,
int w, int bpp)
{
int i;
for (i = 0; i < w; i++) {
int a, b, c, p, pa, pb, pc;
a = dst[i - bpp];
b = top[i];
c = top[i - bpp];
p = b - c;
pc = a - c;
pa = abs(p);
pb = abs(pc);
pc = abs(p + pc);
if (pa <= pb && pa <= pc)
p = a;
else if (pb <= pc)
p = b;
else
p = c;
dst[i] = p + src[i];
}
}
#define UNROLL1(bpp, op) \
{ \
r = dst[0]; \
if (bpp >= 2) \
g = dst[1]; \
if (bpp >= 3) \
b = dst[2]; \
if (bpp >= 4) \
a = dst[3]; \
for (; i <= size - bpp; i += bpp) { \
dst[i + 0] = r = op(r, src[i + 0], last[i + 0]); \
if (bpp == 1) \
continue; \
dst[i + 1] = g = op(g, src[i + 1], last[i + 1]); \
if (bpp == 2) \
continue; \
dst[i + 2] = b = op(b, src[i + 2], last[i + 2]); \
if (bpp == 3) \
continue; \
dst[i + 3] = a = op(a, src[i + 3], last[i + 3]); \
} \
}
#define UNROLL_FILTER(op) \
if (bpp == 1) { \
UNROLL1(1, op) \
} else if (bpp == 2) { \
UNROLL1(2, op) \
} else if (bpp == 3) { \
UNROLL1(3, op) \
} else if (bpp == 4) { \
UNROLL1(4, op) \
} \
for (; i < size; i++) { \
dst[i] = op(dst[i - bpp], src[i], last[i]); \
}
/* NOTE: 'dst' can be equal to 'last' */
static void png_filter_row(PNGDSPContext *dsp, uint8_t *dst, int filter_type,
uint8_t *src, uint8_t *last, int size, int bpp)
{
int i, p, r, g, b, a;
switch (filter_type) {
case PNG_FILTER_VALUE_NONE:
memcpy(dst, src, size);
break;
case PNG_FILTER_VALUE_SUB:
for (i = 0; i < bpp; i++)
dst[i] = src[i];
if (bpp == 4) {
p = *(int *)dst;
for (; i < size; i += bpp) {
unsigned s = *(int *)(src + i);
p = ((s & 0x7f7f7f7f) + (p & 0x7f7f7f7f)) ^ ((s ^ p) & 0x80808080);
*(int *)(dst + i) = p;
}
} else {
#define OP_SUB(x, s, l) ((x) + (s))
UNROLL_FILTER(OP_SUB);
}
break;
case PNG_FILTER_VALUE_UP:
dsp->add_bytes_l2(dst, src, last, size);
break;
case PNG_FILTER_VALUE_AVG:
for (i = 0; i < bpp; i++) {
p = (last[i] >> 1);
dst[i] = p + src[i];
}
#define OP_AVG(x, s, l) (((((x) + (l)) >> 1) + (s)) & 0xff)
UNROLL_FILTER(OP_AVG);
break;
case PNG_FILTER_VALUE_PAETH:
for (i = 0; i < bpp; i++) {
p = last[i];
dst[i] = p + src[i];
}
if (bpp > 2 && size > 4) {
/* would write off the end of the array if we let it process
* the last pixel with bpp=3 */
int w = (bpp & 3) ? size - 3 : size;
if (w > i) {
dsp->add_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
i = w;
}
}
ff_add_png_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
break;
}
}
/* This used to be called "deloco" in FFmpeg
* and is actually an inverse reversible colorspace transformation */
#define YUV2RGB(NAME, TYPE) \
static void deloco_ ## NAME(TYPE *dst, int size, int alpha) \
{ \
int i; \
for (i = 0; i < size; i += 3 + alpha) { \
int g = dst [i + 1]; \
dst[i + 0] += g; \
dst[i + 2] += g; \
} \
}
YUV2RGB(rgb8, uint8_t)
YUV2RGB(rgb16, uint16_t)
/* process exactly one decompressed row */
static void png_handle_row(PNGDecContext *s)
{
uint8_t *ptr, *last_row;
int got_line;
if (!s->interlace_type) {
ptr = s->image_buf + s->image_linesize * (s->y + s->y_offset) + s->x_offset * s->bpp;
if (s->y == 0)
last_row = s->last_row;
else
last_row = ptr - s->image_linesize;
png_filter_row(&s->dsp, ptr, s->crow_buf[0], s->crow_buf + 1,
last_row, s->row_size, s->bpp);
/* loco lags by 1 row so that it doesn't interfere with top prediction */
if (s->filter_type == PNG_FILTER_TYPE_LOCO && s->y > 0) {
if (s->bit_depth == 16) {
deloco_rgb16((uint16_t *)(ptr - s->image_linesize), s->row_size / 2,
s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
} else {
deloco_rgb8(ptr - s->image_linesize, s->row_size,
s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
}
}
s->y++;
if (s->y == s->cur_h) {
s->state |= PNG_ALLIMAGE;
if (s->filter_type == PNG_FILTER_TYPE_LOCO) {
if (s->bit_depth == 16) {
deloco_rgb16((uint16_t *)ptr, s->row_size / 2,
s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
} else {
deloco_rgb8(ptr, s->row_size,
s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
}
}
}
} else {
got_line = 0;
for (;;) {
ptr = s->image_buf + s->image_linesize * (s->y + s->y_offset) + s->x_offset * s->bpp;
if ((ff_png_pass_ymask[s->pass] << (s->y & 7)) & 0x80) {
/* if we already read one row, it is time to stop to
* wait for the next one */
if (got_line)
break;
png_filter_row(&s->dsp, s->tmp_row, s->crow_buf[0], s->crow_buf + 1,
s->last_row, s->pass_row_size, s->bpp);
FFSWAP(uint8_t *, s->last_row, s->tmp_row);
FFSWAP(unsigned int, s->last_row_size, s->tmp_row_size);
got_line = 1;
}
if ((png_pass_dsp_ymask[s->pass] << (s->y & 7)) & 0x80) {
png_put_interlaced_row(ptr, s->cur_w, s->bits_per_pixel, s->pass,
s->color_type, s->last_row);
}
s->y++;
if (s->y == s->cur_h) {
memset(s->last_row, 0, s->row_size);
for (;;) {
if (s->pass == NB_PASSES - 1) {
s->state |= PNG_ALLIMAGE;
goto the_end;
} else {
s->pass++;
s->y = 0;
s->pass_row_size = ff_png_pass_row_size(s->pass,
s->bits_per_pixel,
s->cur_w);
s->crow_size = s->pass_row_size + 1;
if (s->pass_row_size != 0)
break;
/* skip pass if empty row */
}
}
}
}
the_end:;
}
}
static int png_decode_idat(PNGDecContext *s, int length)
{
int ret;
s->zstream.avail_in = FFMIN(length, bytestream2_get_bytes_left(&s->gb));
s->zstream.next_in = (unsigned char *)s->gb.buffer;
bytestream2_skip(&s->gb, length);
/* decode one line if possible */
while (s->zstream.avail_in > 0) {
ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
if (ret != Z_OK && ret != Z_STREAM_END) {
av_log(s->avctx, AV_LOG_ERROR, "inflate returned error %d\n", ret);
return AVERROR_EXTERNAL;
}
if (s->zstream.avail_out == 0) {
if (!(s->state & PNG_ALLIMAGE)) {
png_handle_row(s);
}
s->zstream.avail_out = s->crow_size;
s->zstream.next_out = s->crow_buf;
}
if (ret == Z_STREAM_END && s->zstream.avail_in > 0) {
av_log(NULL, AV_LOG_WARNING,
"%d undecompressed bytes left in buffer\n", s->zstream.avail_in);
return 0;
}
}
return 0;
}
static int decode_zbuf(AVBPrint *bp, const uint8_t *data,
const uint8_t *data_end)
{
z_stream zstream;
unsigned char *buf;
unsigned buf_size;
int ret;
zstream.zalloc = ff_png_zalloc;
zstream.zfree = ff_png_zfree;
zstream.opaque = NULL;
if (inflateInit(&zstream) != Z_OK)
return AVERROR_EXTERNAL;
zstream.next_in = (unsigned char *)data;
zstream.avail_in = data_end - data;
av_bprint_init(bp, 0, -1);
while (zstream.avail_in > 0) {
av_bprint_get_buffer(bp, 2, &buf, &buf_size);
if (buf_size < 2) {
ret = AVERROR(ENOMEM);
goto fail;
}
zstream.next_out = buf;
zstream.avail_out = buf_size - 1;
ret = inflate(&zstream, Z_PARTIAL_FLUSH);
if (ret != Z_OK && ret != Z_STREAM_END) {
ret = AVERROR_EXTERNAL;
goto fail;
}
bp->len += zstream.next_out - buf;
if (ret == Z_STREAM_END)
break;
}
inflateEnd(&zstream);
bp->str[bp->len] = 0;
return 0;
fail:
inflateEnd(&zstream);
av_bprint_finalize(bp, NULL);
return ret;
}
static uint8_t *iso88591_to_utf8(const uint8_t *in, size_t size_in)
{
size_t extra = 0, i;
uint8_t *out, *q;
for (i = 0; i < size_in; i++)
extra += in[i] >= 0x80;
if (size_in == SIZE_MAX || extra > SIZE_MAX - size_in - 1)
return NULL;
q = out = av_malloc(size_in + extra + 1);
if (!out)
return NULL;
for (i = 0; i < size_in; i++) {
if (in[i] >= 0x80) {
*(q++) = 0xC0 | (in[i] >> 6);
*(q++) = 0x80 | (in[i] & 0x3F);
} else {
*(q++) = in[i];
}
}
*(q++) = 0;
return out;
}
static int decode_text_chunk(PNGDecContext *s, uint32_t length, int compressed,
AVDictionary **dict)
{
int ret, method;
const uint8_t *data = s->gb.buffer;
const uint8_t *data_end = data + length;
const uint8_t *keyword = data;
const uint8_t *keyword_end = memchr(keyword, 0, data_end - keyword);
uint8_t *kw_utf8 = NULL, *text, *txt_utf8 = NULL;
unsigned text_len;
AVBPrint bp;
if (!keyword_end)
return AVERROR_INVALIDDATA;
data = keyword_end + 1;
if (compressed) {
if (data == data_end)
return AVERROR_INVALIDDATA;
method = *(data++);
if (method)
return AVERROR_INVALIDDATA;
if ((ret = decode_zbuf(&bp, data, data_end)) < 0)
return ret;
text_len = bp.len;
av_bprint_finalize(&bp, (char **)&text);
if (!text)
return AVERROR(ENOMEM);
} else {
text = (uint8_t *)data;
text_len = data_end - text;
}
kw_utf8 = iso88591_to_utf8(keyword, keyword_end - keyword);
txt_utf8 = iso88591_to_utf8(text, text_len);
if (text != data)
av_free(text);
if (!(kw_utf8 && txt_utf8)) {
av_free(kw_utf8);
av_free(txt_utf8);
return AVERROR(ENOMEM);
}
av_dict_set(dict, kw_utf8, txt_utf8,
AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
return 0;
}
static int decode_ihdr_chunk(AVCodecContext *avctx, PNGDecContext *s,
uint32_t length)
{
if (length != 13)
return AVERROR_INVALIDDATA;
if (s->state & PNG_IDAT) {
av_log(avctx, AV_LOG_ERROR, "IHDR after IDAT\n");
return AVERROR_INVALIDDATA;
}
if (s->state & PNG_IHDR) {
av_log(avctx, AV_LOG_ERROR, "Multiple IHDR\n");
return AVERROR_INVALIDDATA;
}
s->width = s->cur_w = bytestream2_get_be32(&s->gb);
s->height = s->cur_h = bytestream2_get_be32(&s->gb);
if (av_image_check_size(s->width, s->height, 0, avctx)) {
s->cur_w = s->cur_h = s->width = s->height = 0;
av_log(avctx, AV_LOG_ERROR, "Invalid image size\n");
return AVERROR_INVALIDDATA;
}
s->bit_depth = bytestream2_get_byte(&s->gb);
s->color_type = bytestream2_get_byte(&s->gb);
s->compression_type = bytestream2_get_byte(&s->gb);
s->filter_type = bytestream2_get_byte(&s->gb);
s->interlace_type = bytestream2_get_byte(&s->gb);
bytestream2_skip(&s->gb, 4); /* crc */
s->state |= PNG_IHDR;
if (avctx->debug & FF_DEBUG_PICT_INFO)
av_log(avctx, AV_LOG_DEBUG, "width=%d height=%d depth=%d color_type=%d "
"compression_type=%d filter_type=%d interlace_type=%d\n",
s->width, s->height, s->bit_depth, s->color_type,
s->compression_type, s->filter_type, s->interlace_type);
return 0;
}
static int decode_phys_chunk(AVCodecContext *avctx, PNGDecContext *s)
{
if (s->state & PNG_IDAT) {
av_log(avctx, AV_LOG_ERROR, "pHYs after IDAT\n");
return AVERROR_INVALIDDATA;
}
avctx->sample_aspect_ratio.num = bytestream2_get_be32(&s->gb);
avctx->sample_aspect_ratio.den = bytestream2_get_be32(&s->gb);
if (avctx->sample_aspect_ratio.num < 0 || avctx->sample_aspect_ratio.den < 0)
avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
bytestream2_skip(&s->gb, 1); /* unit specifier */
bytestream2_skip(&s->gb, 4); /* crc */
return 0;
}
static int decode_idat_chunk(AVCodecContext *avctx, PNGDecContext *s,
uint32_t length, AVFrame *p)
{
int ret;
size_t byte_depth = s->bit_depth > 8 ? 2 : 1;
if (!(s->state & PNG_IHDR)) {
av_log(avctx, AV_LOG_ERROR, "IDAT without IHDR\n");
return AVERROR_INVALIDDATA;
}
if (!(s->state & PNG_IDAT)) {
/* init image info */
avctx->width = s->width;
avctx->height = s->height;
s->channels = ff_png_get_nb_channels(s->color_type);
s->bits_per_pixel = s->bit_depth * s->channels;
s->bpp = (s->bits_per_pixel + 7) >> 3;
s->row_size = (s->cur_w * s->bits_per_pixel + 7) >> 3;
if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
s->color_type == PNG_COLOR_TYPE_RGB) {
avctx->pix_fmt = AV_PIX_FMT_RGB24;
} else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
avctx->pix_fmt = AV_PIX_FMT_RGBA;
} else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
s->color_type == PNG_COLOR_TYPE_GRAY) {
avctx->pix_fmt = AV_PIX_FMT_GRAY8;
} else if (s->bit_depth == 16 &&
s->color_type == PNG_COLOR_TYPE_GRAY) {
avctx->pix_fmt = AV_PIX_FMT_GRAY16BE;
} else if (s->bit_depth == 16 &&
s->color_type == PNG_COLOR_TYPE_RGB) {
avctx->pix_fmt = AV_PIX_FMT_RGB48BE;
} else if (s->bit_depth == 16 &&
s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
} else if ((s->bits_per_pixel == 1 || s->bits_per_pixel == 2 || s->bits_per_pixel == 4 || s->bits_per_pixel == 8) &&
s->color_type == PNG_COLOR_TYPE_PALETTE) {
avctx->pix_fmt = AV_PIX_FMT_PAL8;
} else if (s->bit_depth == 1 && s->bits_per_pixel == 1 && avctx->codec_id != AV_CODEC_ID_APNG) {
avctx->pix_fmt = AV_PIX_FMT_MONOBLACK;
} else if (s->bit_depth == 8 &&
s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
avctx->pix_fmt = AV_PIX_FMT_YA8;
} else if (s->bit_depth == 16 &&
s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
avctx->pix_fmt = AV_PIX_FMT_YA16BE;
} else {
av_log(avctx, AV_LOG_ERROR, "unsupported bit depth %d "
"and color type %d\n",
s->bit_depth, s->color_type);
return AVERROR_INVALIDDATA;
}
if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) {
switch (avctx->pix_fmt) {
case AV_PIX_FMT_RGB24:
avctx->pix_fmt = AV_PIX_FMT_RGBA;
break;
case AV_PIX_FMT_RGB48BE:
avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
break;
case AV_PIX_FMT_GRAY8:
avctx->pix_fmt = AV_PIX_FMT_YA8;
break;
case AV_PIX_FMT_GRAY16BE:
avctx->pix_fmt = AV_PIX_FMT_YA16BE;
break;
default:
avpriv_request_sample(avctx, "bit depth %d "
"and color type %d with TRNS",
s->bit_depth, s->color_type);
return AVERROR_INVALIDDATA;
}
s->bpp += byte_depth;
}
if ((ret = ff_thread_get_buffer(avctx, &s->picture, AV_GET_BUFFER_FLAG_REF)) < 0)
return ret;
if (avctx->codec_id == AV_CODEC_ID_APNG && s->last_dispose_op != APNG_DISPOSE_OP_PREVIOUS) {
ff_thread_release_buffer(avctx, &s->previous_picture);
if ((ret = ff_thread_get_buffer(avctx, &s->previous_picture, AV_GET_BUFFER_FLAG_REF)) < 0)
return ret;
}
ff_thread_finish_setup(avctx);
p->pict_type = AV_PICTURE_TYPE_I;
p->key_frame = 1;
p->interlaced_frame = !!s->interlace_type;
/* compute the compressed row size */
if (!s->interlace_type) {
s->crow_size = s->row_size + 1;
} else {
s->pass = 0;
s->pass_row_size = ff_png_pass_row_size(s->pass,
s->bits_per_pixel,
s->cur_w);
s->crow_size = s->pass_row_size + 1;
}
ff_dlog(avctx, "row_size=%d crow_size =%d\n",
s->row_size, s->crow_size);
s->image_buf = p->data[0];
s->image_linesize = p->linesize[0];
/* copy the palette if needed */
if (avctx->pix_fmt == AV_PIX_FMT_PAL8)
memcpy(p->data[1], s->palette, 256 * sizeof(uint32_t));
/* empty row is used if differencing to the first row */
av_fast_padded_mallocz(&s->last_row, &s->last_row_size, s->row_size);
if (!s->last_row)
return AVERROR_INVALIDDATA;
if (s->interlace_type ||
s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
av_fast_padded_malloc(&s->tmp_row, &s->tmp_row_size, s->row_size);
if (!s->tmp_row)
return AVERROR_INVALIDDATA;
}
/* compressed row */
av_fast_padded_malloc(&s->buffer, &s->buffer_size, s->row_size + 16);
if (!s->buffer)
return AVERROR(ENOMEM);
/* we want crow_buf+1 to be 16-byte aligned */
s->crow_buf = s->buffer + 15;
s->zstream.avail_out = s->crow_size;
s->zstream.next_out = s->crow_buf;
}
s->state |= PNG_IDAT;
/* set image to non-transparent bpp while decompressing */
if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE)
s->bpp -= byte_depth;
ret = png_decode_idat(s, length);
if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE)
s->bpp += byte_depth;
if (ret < 0)
return ret;
bytestream2_skip(&s->gb, 4); /* crc */
return 0;
}
static int decode_plte_chunk(AVCodecContext *avctx, PNGDecContext *s,
uint32_t length)
{
int n, i, r, g, b;
if ((length % 3) != 0 || length > 256 * 3)
return AVERROR_INVALIDDATA;
/* read the palette */
n = length / 3;
for (i = 0; i < n; i++) {
r = bytestream2_get_byte(&s->gb);
g = bytestream2_get_byte(&s->gb);
b = bytestream2_get_byte(&s->gb);
s->palette[i] = (0xFFU << 24) | (r << 16) | (g << 8) | b;
}
for (; i < 256; i++)
s->palette[i] = (0xFFU << 24);
s->state |= PNG_PLTE;
bytestream2_skip(&s->gb, 4); /* crc */
return 0;
}
static int decode_trns_chunk(AVCodecContext *avctx, PNGDecContext *s,
uint32_t length)
{
int v, i;
if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
if (length > 256 || !(s->state & PNG_PLTE))
return AVERROR_INVALIDDATA;
for (i = 0; i < length; i++) {
v = bytestream2_get_byte(&s->gb);
s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
}
} else if (s->color_type == PNG_COLOR_TYPE_GRAY || s->color_type == PNG_COLOR_TYPE_RGB) {
if ((s->color_type == PNG_COLOR_TYPE_GRAY && length != 2) ||
(s->color_type == PNG_COLOR_TYPE_RGB && length != 6))
return AVERROR_INVALIDDATA;
for (i = 0; i < length / 2; i++) {
/* only use the least significant bits */
v = av_mod_uintp2(bytestream2_get_be16(&s->gb), s->bit_depth);
if (s->bit_depth > 8)
AV_WB16(&s->transparent_color_be[2 * i], v);
else
s->transparent_color_be[i] = v;
}
} else {
return AVERROR_INVALIDDATA;
}
bytestream2_skip(&s->gb, 4); /* crc */
s->has_trns = 1;
return 0;
}
static void handle_small_bpp(PNGDecContext *s, AVFrame *p)
{
if (s->bits_per_pixel == 1 && s->color_type == PNG_COLOR_TYPE_PALETTE) {
int i, j, k;
uint8_t *pd = p->data[0];
for (j = 0; j < s->height; j++) {
i = s->width / 8;
for (k = 7; k >= 1; k--)
if ((s->width&7) >= k)
pd[8*i + k - 1] = (pd[i]>>8-k) & 1;
for (i--; i >= 0; i--) {
pd[8*i + 7]= pd[i] & 1;
pd[8*i + 6]= (pd[i]>>1) & 1;
pd[8*i + 5]= (pd[i]>>2) & 1;
pd[8*i + 4]= (pd[i]>>3) & 1;
pd[8*i + 3]= (pd[i]>>4) & 1;
pd[8*i + 2]= (pd[i]>>5) & 1;
pd[8*i + 1]= (pd[i]>>6) & 1;
pd[8*i + 0]= pd[i]>>7;
}
pd += s->image_linesize;
}
} else if (s->bits_per_pixel == 2) {
int i, j;
uint8_t *pd = p->data[0];
for (j = 0; j < s->height; j++) {
i = s->width / 4;
if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
if ((s->width&3) >= 3) pd[4*i + 2]= (pd[i] >> 2) & 3;
if ((s->width&3) >= 2) pd[4*i + 1]= (pd[i] >> 4) & 3;
if ((s->width&3) >= 1) pd[4*i + 0]= pd[i] >> 6;
for (i--; i >= 0; i--) {
pd[4*i + 3]= pd[i] & 3;
pd[4*i + 2]= (pd[i]>>2) & 3;
pd[4*i + 1]= (pd[i]>>4) & 3;
pd[4*i + 0]= pd[i]>>6;
}
} else {
if ((s->width&3) >= 3) pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
if ((s->width&3) >= 2) pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
if ((s->width&3) >= 1) pd[4*i + 0]= ( pd[i]>>6 )*0x55;
for (i--; i >= 0; i--) {
pd[4*i + 3]= ( pd[i] & 3)*0x55;
pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
pd[4*i + 0]= ( pd[i]>>6 )*0x55;
}
}
pd += s->image_linesize;
}
} else if (s->bits_per_pixel == 4) {
int i, j;
uint8_t *pd = p->data[0];
for (j = 0; j < s->height; j++) {
i = s->width/2;
if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
if (s->width&1) pd[2*i+0]= pd[i]>>4;
for (i--; i >= 0; i--) {
pd[2*i + 1] = pd[i] & 15;
pd[2*i + 0] = pd[i] >> 4;
}
} else {
if (s->width & 1) pd[2*i + 0]= (pd[i] >> 4) * 0x11;
for (i--; i >= 0; i--) {
pd[2*i + 1] = (pd[i] & 15) * 0x11;
pd[2*i + 0] = (pd[i] >> 4) * 0x11;
}
}
pd += s->image_linesize;
}
}
}
static int decode_fctl_chunk(AVCodecContext *avctx, PNGDecContext *s,
uint32_t length)
{
uint32_t sequence_number;
int cur_w, cur_h, x_offset, y_offset, dispose_op, blend_op;
if (length != 26)
return AVERROR_INVALIDDATA;
if (!(s->state & PNG_IHDR)) {
av_log(avctx, AV_LOG_ERROR, "fctl before IHDR\n");
return AVERROR_INVALIDDATA;
}
s->last_w = s->cur_w;
s->last_h = s->cur_h;
s->last_x_offset = s->x_offset;
s->last_y_offset = s->y_offset;
s->last_dispose_op = s->dispose_op;
sequence_number = bytestream2_get_be32(&s->gb);
cur_w = bytestream2_get_be32(&s->gb);
cur_h = bytestream2_get_be32(&s->gb);
x_offset = bytestream2_get_be32(&s->gb);
y_offset = bytestream2_get_be32(&s->gb);
bytestream2_skip(&s->gb, 4); /* delay_num (2), delay_den (2) */
dispose_op = bytestream2_get_byte(&s->gb);
blend_op = bytestream2_get_byte(&s->gb);
bytestream2_skip(&s->gb, 4); /* crc */
if (sequence_number == 0 &&
(cur_w != s->width ||
cur_h != s->height ||
x_offset != 0 ||
y_offset != 0) ||
cur_w <= 0 || cur_h <= 0 ||
x_offset < 0 || y_offset < 0 ||
cur_w > s->width - x_offset|| cur_h > s->height - y_offset)
return AVERROR_INVALIDDATA;
if (blend_op != APNG_BLEND_OP_OVER && blend_op != APNG_BLEND_OP_SOURCE) {
av_log(avctx, AV_LOG_ERROR, "Invalid blend_op %d\n", blend_op);
return AVERROR_INVALIDDATA;
}
if ((sequence_number == 0 || !s->previous_picture.f->data[0]) &&
dispose_op == APNG_DISPOSE_OP_PREVIOUS) {
// No previous frame to revert to for the first frame
// Spec says to just treat it as a APNG_DISPOSE_OP_BACKGROUND
dispose_op = APNG_DISPOSE_OP_BACKGROUND;
}
if (blend_op == APNG_BLEND_OP_OVER && !s->has_trns && (
avctx->pix_fmt == AV_PIX_FMT_RGB24 ||
avctx->pix_fmt == AV_PIX_FMT_RGB48BE ||
avctx->pix_fmt == AV_PIX_FMT_PAL8 ||
avctx->pix_fmt == AV_PIX_FMT_GRAY8 ||
avctx->pix_fmt == AV_PIX_FMT_GRAY16BE ||
avctx->pix_fmt == AV_PIX_FMT_MONOBLACK
)) {
// APNG_BLEND_OP_OVER is the same as APNG_BLEND_OP_SOURCE when there is no alpha channel
blend_op = APNG_BLEND_OP_SOURCE;
}
s->cur_w = cur_w;
s->cur_h = cur_h;
s->x_offset = x_offset;
s->y_offset = y_offset;
s->dispose_op = dispose_op;
s->blend_op = blend_op;
return 0;
}
static void handle_p_frame_png(PNGDecContext *s, AVFrame *p)
{
int i, j;
uint8_t *pd = p->data[0];
uint8_t *pd_last = s->last_picture.f->data[0];
int ls = FFMIN(av_image_get_linesize(p->format, s->width, 0), s->width * s->bpp);
ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
for (j = 0; j < s->height; j++) {
for (i = 0; i < ls; i++)
pd[i] += pd_last[i];
pd += s->image_linesize;
pd_last += s->image_linesize;
}
}
// divide by 255 and round to nearest
// apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
#define FAST_DIV255(x) ((((x) + 128) * 257) >> 16)
static int handle_p_frame_apng(AVCodecContext *avctx, PNGDecContext *s,
AVFrame *p)
{
size_t x, y;
uint8_t *buffer;
if (s->blend_op == APNG_BLEND_OP_OVER &&
avctx->pix_fmt != AV_PIX_FMT_RGBA &&
avctx->pix_fmt != AV_PIX_FMT_GRAY8A &&
avctx->pix_fmt != AV_PIX_FMT_PAL8) {
avpriv_request_sample(avctx, "Blending with pixel format %s",
av_get_pix_fmt_name(avctx->pix_fmt));
return AVERROR_PATCHWELCOME;
}
buffer = av_malloc_array(s->image_linesize, s->height);
if (!buffer)
return AVERROR(ENOMEM);
// Do the disposal operation specified by the last frame on the frame
if (s->last_dispose_op != APNG_DISPOSE_OP_PREVIOUS) {
ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
memcpy(buffer, s->last_picture.f->data[0], s->image_linesize * s->height);
if (s->last_dispose_op == APNG_DISPOSE_OP_BACKGROUND)
for (y = s->last_y_offset; y < s->last_y_offset + s->last_h; ++y)
memset(buffer + s->image_linesize * y + s->bpp * s->last_x_offset, 0, s->bpp * s->last_w);
memcpy(s->previous_picture.f->data[0], buffer, s->image_linesize * s->height);
ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
} else {
ff_thread_await_progress(&s->previous_picture, INT_MAX, 0);
memcpy(buffer, s->previous_picture.f->data[0], s->image_linesize * s->height);
}
// Perform blending
if (s->blend_op == APNG_BLEND_OP_SOURCE) {
for (y = s->y_offset; y < s->y_offset + s->cur_h; ++y) {
size_t row_start = s->image_linesize * y + s->bpp * s->x_offset;
memcpy(buffer + row_start, p->data[0] + row_start, s->bpp * s->cur_w);
}
} else { // APNG_BLEND_OP_OVER
for (y = s->y_offset; y < s->y_offset + s->cur_h; ++y) {
uint8_t *foreground = p->data[0] + s->image_linesize * y + s->bpp * s->x_offset;
uint8_t *background = buffer + s->image_linesize * y + s->bpp * s->x_offset;
for (x = s->x_offset; x < s->x_offset + s->cur_w; ++x, foreground += s->bpp, background += s->bpp) {
size_t b;
uint8_t foreground_alpha, background_alpha, output_alpha;
uint8_t output[10];
// Since we might be blending alpha onto alpha, we use the following equations:
// output_alpha = foreground_alpha + (1 - foreground_alpha) * background_alpha
// output = (foreground_alpha * foreground + (1 - foreground_alpha) * background_alpha * background) / output_alpha
switch (avctx->pix_fmt) {
case AV_PIX_FMT_RGBA:
foreground_alpha = foreground[3];
background_alpha = background[3];
break;
case AV_PIX_FMT_GRAY8A:
foreground_alpha = foreground[1];
background_alpha = background[1];
break;
case AV_PIX_FMT_PAL8:
foreground_alpha = s->palette[foreground[0]] >> 24;
background_alpha = s->palette[background[0]] >> 24;
break;
}
if (foreground_alpha == 0)
continue;
if (foreground_alpha == 255) {
memcpy(background, foreground, s->bpp);
continue;
}
if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
// TODO: Alpha blending with PAL8 will likely need the entire image converted over to RGBA first
avpriv_request_sample(avctx, "Alpha blending palette samples");
background[0] = foreground[0];
continue;
}
output_alpha = foreground_alpha + FAST_DIV255((255 - foreground_alpha) * background_alpha);
av_assert0(s->bpp <= 10);
for (b = 0; b < s->bpp - 1; ++b) {
if (output_alpha == 0) {
output[b] = 0;
} else if (background_alpha == 255) {
output[b] = FAST_DIV255(foreground_alpha * foreground[b] + (255 - foreground_alpha) * background[b]);
} else {
output[b] = (255 * foreground_alpha * foreground[b] + (255 - foreground_alpha) * background_alpha * background[b]) / (255 * output_alpha);
}
}
output[b] = output_alpha;
memcpy(background, output, s->bpp);
}
}
}
// Copy blended buffer into the frame and free
memcpy(p->data[0], buffer, s->image_linesize * s->height);
av_free(buffer);
return 0;
}
static int decode_frame_common(AVCodecContext *avctx, PNGDecContext *s,
AVFrame *p, AVPacket *avpkt)
{
AVDictionary *metadata = NULL;
uint32_t tag, length;
int decode_next_dat = 0;
int ret;
for (;;) {
length = bytestream2_get_bytes_left(&s->gb);
if (length <= 0) {
if (avctx->codec_id == AV_CODEC_ID_PNG &&
avctx->skip_frame == AVDISCARD_ALL) {
av_frame_set_metadata(p, metadata);
return 0;
}
if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && length == 0) {
if (!(s->state & PNG_IDAT))
return 0;
else
goto exit_loop;
}
av_log(avctx, AV_LOG_ERROR, "%d bytes left\n", length);
if ( s->state & PNG_ALLIMAGE
&& avctx->strict_std_compliance <= FF_COMPLIANCE_NORMAL)
goto exit_loop;
ret = AVERROR_INVALIDDATA;
goto fail;
}
length = bytestream2_get_be32(&s->gb);
if (length > 0x7fffffff || length > bytestream2_get_bytes_left(&s->gb)) {
av_log(avctx, AV_LOG_ERROR, "chunk too big\n");
ret = AVERROR_INVALIDDATA;
goto fail;
}
tag = bytestream2_get_le32(&s->gb);
if (avctx->debug & FF_DEBUG_STARTCODE)
av_log(avctx, AV_LOG_DEBUG, "png: tag=%c%c%c%c length=%u\n",
(tag & 0xff),
((tag >> 8) & 0xff),
((tag >> 16) & 0xff),
((tag >> 24) & 0xff), length);
if (avctx->codec_id == AV_CODEC_ID_PNG &&
avctx->skip_frame == AVDISCARD_ALL) {
switch(tag) {
case MKTAG('I', 'H', 'D', 'R'):
case MKTAG('p', 'H', 'Y', 's'):
case MKTAG('t', 'E', 'X', 't'):
case MKTAG('I', 'D', 'A', 'T'):
case MKTAG('t', 'R', 'N', 'S'):
break;
default:
goto skip_tag;
}
}
switch (tag) {
case MKTAG('I', 'H', 'D', 'R'):
if ((ret = decode_ihdr_chunk(avctx, s, length)) < 0)
goto fail;
break;
case MKTAG('p', 'H', 'Y', 's'):
if ((ret = decode_phys_chunk(avctx, s)) < 0)
goto fail;
break;
case MKTAG('f', 'c', 'T', 'L'):
if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
goto skip_tag;
if ((ret = decode_fctl_chunk(avctx, s, length)) < 0)
goto fail;
decode_next_dat = 1;
break;
case MKTAG('f', 'd', 'A', 'T'):
if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
goto skip_tag;
if (!decode_next_dat) {
ret = AVERROR_INVALIDDATA;
goto fail;
}
bytestream2_get_be32(&s->gb);
length -= 4;
/* fallthrough */
case MKTAG('I', 'D', 'A', 'T'):
if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && !decode_next_dat)
goto skip_tag;
if ((ret = decode_idat_chunk(avctx, s, length, p)) < 0)
goto fail;
break;
case MKTAG('P', 'L', 'T', 'E'):
if (decode_plte_chunk(avctx, s, length) < 0)
goto skip_tag;
break;
case MKTAG('t', 'R', 'N', 'S'):
if (decode_trns_chunk(avctx, s, length) < 0)
goto skip_tag;
break;
case MKTAG('t', 'E', 'X', 't'):
if (decode_text_chunk(s, length, 0, &metadata) < 0)
av_log(avctx, AV_LOG_WARNING, "Broken tEXt chunk\n");
bytestream2_skip(&s->gb, length + 4);
break;
case MKTAG('z', 'T', 'X', 't'):
if (decode_text_chunk(s, length, 1, &metadata) < 0)
av_log(avctx, AV_LOG_WARNING, "Broken zTXt chunk\n");
bytestream2_skip(&s->gb, length + 4);
break;
case MKTAG('s', 'T', 'E', 'R'): {
int mode = bytestream2_get_byte(&s->gb);
AVStereo3D *stereo3d = av_stereo3d_create_side_data(p);
if (!stereo3d)
goto fail;
if (mode == 0 || mode == 1) {
stereo3d->type = AV_STEREO3D_SIDEBYSIDE;
stereo3d->flags = mode ? 0 : AV_STEREO3D_FLAG_INVERT;
} else {
av_log(avctx, AV_LOG_WARNING,
"Unknown value in sTER chunk (%d)\n", mode);
}
bytestream2_skip(&s->gb, 4); /* crc */
break;
}
case MKTAG('I', 'E', 'N', 'D'):
if (!(s->state & PNG_ALLIMAGE))
av_log(avctx, AV_LOG_ERROR, "IEND without all image\n");
if (!(s->state & (PNG_ALLIMAGE|PNG_IDAT))) {
ret = AVERROR_INVALIDDATA;
goto fail;
}
bytestream2_skip(&s->gb, 4); /* crc */
goto exit_loop;
default:
/* skip tag */
skip_tag:
bytestream2_skip(&s->gb, length + 4);
break;
}
}
exit_loop:
if (avctx->codec_id == AV_CODEC_ID_PNG &&
avctx->skip_frame == AVDISCARD_ALL) {
av_frame_set_metadata(p, metadata);
return 0;
}
if (s->bits_per_pixel <= 4)
handle_small_bpp(s, p);
/* apply transparency if needed */
if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) {
size_t byte_depth = s->bit_depth > 8 ? 2 : 1;
size_t raw_bpp = s->bpp - byte_depth;
unsigned x, y;
for (y = 0; y < s->height; ++y) {
uint8_t *row = &s->image_buf[s->image_linesize * y];
/* since we're updating in-place, we have to go from right to left */
for (x = s->width; x > 0; --x) {
uint8_t *pixel = &row[s->bpp * (x - 1)];
memmove(pixel, &row[raw_bpp * (x - 1)], raw_bpp);
if (!memcmp(pixel, s->transparent_color_be, raw_bpp)) {
memset(&pixel[raw_bpp], 0, byte_depth);
} else {
memset(&pixel[raw_bpp], 0xff, byte_depth);
}
}
}
}
/* handle P-frames only if a predecessor frame is available */
if (s->last_picture.f->data[0]) {
if ( !(avpkt->flags & AV_PKT_FLAG_KEY) && avctx->codec_tag != AV_RL32("MPNG")
&& s->last_picture.f->width == p->width
&& s->last_picture.f->height== p->height
&& s->last_picture.f->format== p->format
) {
if (CONFIG_PNG_DECODER && avctx->codec_id != AV_CODEC_ID_APNG)
handle_p_frame_png(s, p);
else if (CONFIG_APNG_DECODER &&
avctx->codec_id == AV_CODEC_ID_APNG &&
(ret = handle_p_frame_apng(avctx, s, p)) < 0)
goto fail;
}
}
ff_thread_report_progress(&s->picture, INT_MAX, 0);
ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
av_frame_set_metadata(p, metadata);
metadata = NULL;
return 0;
fail:
av_dict_free(&metadata);
ff_thread_report_progress(&s->picture, INT_MAX, 0);
ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
return ret;
}
#if CONFIG_PNG_DECODER
static int decode_frame_png(AVCodecContext *avctx,
void *data, int *got_frame,
AVPacket *avpkt)
{
PNGDecContext *const s = avctx->priv_data;
const uint8_t *buf = avpkt->data;
int buf_size = avpkt->size;
AVFrame *p;
int64_t sig;
int ret;
ff_thread_release_buffer(avctx, &s->last_picture);
FFSWAP(ThreadFrame, s->picture, s->last_picture);
p = s->picture.f;
bytestream2_init(&s->gb, buf, buf_size);
/* check signature */
sig = bytestream2_get_be64(&s->gb);
if (sig != PNGSIG &&
sig != MNGSIG) {
av_log(avctx, AV_LOG_ERROR, "Invalid PNG signature 0x%08"PRIX64".\n", sig);
return AVERROR_INVALIDDATA;
}
s->y = s->state = s->has_trns = 0;
/* init the zlib */
s->zstream.zalloc = ff_png_zalloc;
s->zstream.zfree = ff_png_zfree;
s->zstream.opaque = NULL;
ret = inflateInit(&s->zstream);
if (ret != Z_OK) {
av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
return AVERROR_EXTERNAL;
}
if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
goto the_end;
if (avctx->skip_frame == AVDISCARD_ALL) {
*got_frame = 0;
ret = bytestream2_tell(&s->gb);
goto the_end;
}
if ((ret = av_frame_ref(data, s->picture.f)) < 0)
return ret;
*got_frame = 1;
ret = bytestream2_tell(&s->gb);
the_end:
inflateEnd(&s->zstream);
s->crow_buf = NULL;
return ret;
}
#endif
#if CONFIG_APNG_DECODER
static int decode_frame_apng(AVCodecContext *avctx,
void *data, int *got_frame,
AVPacket *avpkt)
{
PNGDecContext *const s = avctx->priv_data;
int ret;
AVFrame *p;
ff_thread_release_buffer(avctx, &s->last_picture);
FFSWAP(ThreadFrame, s->picture, s->last_picture);
p = s->picture.f;
if (!(s->state & PNG_IHDR)) {
if (!avctx->extradata_size)
return AVERROR_INVALIDDATA;
/* only init fields, there is no zlib use in extradata */
s->zstream.zalloc = ff_png_zalloc;
s->zstream.zfree = ff_png_zfree;
bytestream2_init(&s->gb, avctx->extradata, avctx->extradata_size);
if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
goto end;
}
/* reset state for a new frame */
if ((ret = inflateInit(&s->zstream)) != Z_OK) {
av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
ret = AVERROR_EXTERNAL;
goto end;
}
s->y = 0;
s->state &= ~(PNG_IDAT | PNG_ALLIMAGE);
bytestream2_init(&s->gb, avpkt->data, avpkt->size);
if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
goto end;
if (!(s->state & PNG_ALLIMAGE))
av_log(avctx, AV_LOG_WARNING, "Frame did not contain a complete image\n");
if (!(s->state & (PNG_ALLIMAGE|PNG_IDAT))) {
ret = AVERROR_INVALIDDATA;
goto end;
}
if ((ret = av_frame_ref(data, s->picture.f)) < 0)
goto end;
*got_frame = 1;
ret = bytestream2_tell(&s->gb);
end:
inflateEnd(&s->zstream);
return ret;
}
#endif
#if HAVE_THREADS
static int update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
{
PNGDecContext *psrc = src->priv_data;
PNGDecContext *pdst = dst->priv_data;
int ret;
if (dst == src)
return 0;
ff_thread_release_buffer(dst, &pdst->picture);
if (psrc->picture.f->data[0] &&
(ret = ff_thread_ref_frame(&pdst->picture, &psrc->picture)) < 0)
return ret;
if (CONFIG_APNG_DECODER && dst->codec_id == AV_CODEC_ID_APNG) {
pdst->width = psrc->width;
pdst->height = psrc->height;
pdst->bit_depth = psrc->bit_depth;
pdst->color_type = psrc->color_type;
pdst->compression_type = psrc->compression_type;
pdst->interlace_type = psrc->interlace_type;
pdst->filter_type = psrc->filter_type;
pdst->cur_w = psrc->cur_w;
pdst->cur_h = psrc->cur_h;
pdst->x_offset = psrc->x_offset;
pdst->y_offset = psrc->y_offset;
pdst->has_trns = psrc->has_trns;
memcpy(pdst->transparent_color_be, psrc->transparent_color_be, sizeof(pdst->transparent_color_be));
pdst->dispose_op = psrc->dispose_op;
memcpy(pdst->palette, psrc->palette, sizeof(pdst->palette));
pdst->state |= psrc->state & (PNG_IHDR | PNG_PLTE);
ff_thread_release_buffer(dst, &pdst->last_picture);
if (psrc->last_picture.f->data[0] &&
(ret = ff_thread_ref_frame(&pdst->last_picture, &psrc->last_picture)) < 0)
return ret;
ff_thread_release_buffer(dst, &pdst->previous_picture);
if (psrc->previous_picture.f->data[0] &&
(ret = ff_thread_ref_frame(&pdst->previous_picture, &psrc->previous_picture)) < 0)
return ret;
}
return 0;
}
#endif
static av_cold int png_dec_init(AVCodecContext *avctx)
{
PNGDecContext *s = avctx->priv_data;
avctx->color_range = AVCOL_RANGE_JPEG;
s->avctx = avctx;
s->previous_picture.f = av_frame_alloc();
s->last_picture.f = av_frame_alloc();
s->picture.f = av_frame_alloc();
if (!s->previous_picture.f || !s->last_picture.f || !s->picture.f) {
av_frame_free(&s->previous_picture.f);
av_frame_free(&s->last_picture.f);
av_frame_free(&s->picture.f);
return AVERROR(ENOMEM);
}
if (!avctx->internal->is_copy) {
avctx->internal->allocate_progress = 1;
ff_pngdsp_init(&s->dsp);
}
return 0;
}
static av_cold int png_dec_end(AVCodecContext *avctx)
{
PNGDecContext *s = avctx->priv_data;
ff_thread_release_buffer(avctx, &s->previous_picture);
av_frame_free(&s->previous_picture.f);
ff_thread_release_buffer(avctx, &s->last_picture);
av_frame_free(&s->last_picture.f);
ff_thread_release_buffer(avctx, &s->picture);
av_frame_free(&s->picture.f);
av_freep(&s->buffer);
s->buffer_size = 0;
av_freep(&s->last_row);
s->last_row_size = 0;
av_freep(&s->tmp_row);
s->tmp_row_size = 0;
return 0;
}
#if CONFIG_APNG_DECODER
AVCodec ff_apng_decoder = {
.name = "apng",
.long_name = NULL_IF_CONFIG_SMALL("APNG (Animated Portable Network Graphics) image"),
.type = AVMEDIA_TYPE_VIDEO,
.id = AV_CODEC_ID_APNG,
.priv_data_size = sizeof(PNGDecContext),
.init = png_dec_init,
.close = png_dec_end,
.decode = decode_frame_apng,
.init_thread_copy = ONLY_IF_THREADS_ENABLED(png_dec_init),
.update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
.capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
};
#endif
#if CONFIG_PNG_DECODER
AVCodec ff_png_decoder = {
.name = "png",
.long_name = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
.type = AVMEDIA_TYPE_VIDEO,
.id = AV_CODEC_ID_PNG,
.priv_data_size = sizeof(PNGDecContext),
.init = png_dec_init,
.close = png_dec_end,
.decode = decode_frame_png,
.init_thread_copy = ONLY_IF_THREADS_ENABLED(png_dec_init),
.update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
.capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
.caps_internal = FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM,
};
#endif
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_3296_0 |
crossvul-cpp_data_bad_106_0 | /*
* ebtables
*
* Author:
* Bart De Schuymer <bdschuym@pandora.be>
*
* ebtables.c,v 2.0, July, 2002
*
* This code is strongly inspired by the iptables code which is
* Copyright (C) 1999 Paul `Rusty' Russell & Michael J. Neuling
*
* 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.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kmod.h>
#include <linux/module.h>
#include <linux/vmalloc.h>
#include <linux/netfilter/x_tables.h>
#include <linux/netfilter_bridge/ebtables.h>
#include <linux/spinlock.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
#include <linux/smp.h>
#include <linux/cpumask.h>
#include <linux/audit.h>
#include <net/sock.h>
/* needed for logical [in,out]-dev filtering */
#include "../br_private.h"
#define BUGPRINT(format, args...) printk("kernel msg: ebtables bug: please "\
"report to author: "format, ## args)
/* #define BUGPRINT(format, args...) */
/* Each cpu has its own set of counters, so there is no need for write_lock in
* the softirq
* For reading or updating the counters, the user context needs to
* get a write_lock
*/
/* The size of each set of counters is altered to get cache alignment */
#define SMP_ALIGN(x) (((x) + SMP_CACHE_BYTES-1) & ~(SMP_CACHE_BYTES-1))
#define COUNTER_OFFSET(n) (SMP_ALIGN(n * sizeof(struct ebt_counter)))
#define COUNTER_BASE(c, n, cpu) ((struct ebt_counter *)(((char *)c) + \
COUNTER_OFFSET(n) * cpu))
static DEFINE_MUTEX(ebt_mutex);
#ifdef CONFIG_COMPAT
static void ebt_standard_compat_from_user(void *dst, const void *src)
{
int v = *(compat_int_t *)src;
if (v >= 0)
v += xt_compat_calc_jump(NFPROTO_BRIDGE, v);
memcpy(dst, &v, sizeof(v));
}
static int ebt_standard_compat_to_user(void __user *dst, const void *src)
{
compat_int_t cv = *(int *)src;
if (cv >= 0)
cv -= xt_compat_calc_jump(NFPROTO_BRIDGE, cv);
return copy_to_user(dst, &cv, sizeof(cv)) ? -EFAULT : 0;
}
#endif
static struct xt_target ebt_standard_target = {
.name = "standard",
.revision = 0,
.family = NFPROTO_BRIDGE,
.targetsize = sizeof(int),
#ifdef CONFIG_COMPAT
.compatsize = sizeof(compat_int_t),
.compat_from_user = ebt_standard_compat_from_user,
.compat_to_user = ebt_standard_compat_to_user,
#endif
};
static inline int
ebt_do_watcher(const struct ebt_entry_watcher *w, struct sk_buff *skb,
struct xt_action_param *par)
{
par->target = w->u.watcher;
par->targinfo = w->data;
w->u.watcher->target(skb, par);
/* watchers don't give a verdict */
return 0;
}
static inline int
ebt_do_match(struct ebt_entry_match *m, const struct sk_buff *skb,
struct xt_action_param *par)
{
par->match = m->u.match;
par->matchinfo = m->data;
return m->u.match->match(skb, par) ? EBT_MATCH : EBT_NOMATCH;
}
static inline int
ebt_dev_check(const char *entry, const struct net_device *device)
{
int i = 0;
const char *devname;
if (*entry == '\0')
return 0;
if (!device)
return 1;
devname = device->name;
/* 1 is the wildcard token */
while (entry[i] != '\0' && entry[i] != 1 && entry[i] == devname[i])
i++;
return devname[i] != entry[i] && entry[i] != 1;
}
/* process standard matches */
static inline int
ebt_basic_match(const struct ebt_entry *e, const struct sk_buff *skb,
const struct net_device *in, const struct net_device *out)
{
const struct ethhdr *h = eth_hdr(skb);
const struct net_bridge_port *p;
__be16 ethproto;
if (skb_vlan_tag_present(skb))
ethproto = htons(ETH_P_8021Q);
else
ethproto = h->h_proto;
if (e->bitmask & EBT_802_3) {
if (NF_INVF(e, EBT_IPROTO, eth_proto_is_802_3(ethproto)))
return 1;
} else if (!(e->bitmask & EBT_NOPROTO) &&
NF_INVF(e, EBT_IPROTO, e->ethproto != ethproto))
return 1;
if (NF_INVF(e, EBT_IIN, ebt_dev_check(e->in, in)))
return 1;
if (NF_INVF(e, EBT_IOUT, ebt_dev_check(e->out, out)))
return 1;
/* rcu_read_lock()ed by nf_hook_thresh */
if (in && (p = br_port_get_rcu(in)) != NULL &&
NF_INVF(e, EBT_ILOGICALIN,
ebt_dev_check(e->logical_in, p->br->dev)))
return 1;
if (out && (p = br_port_get_rcu(out)) != NULL &&
NF_INVF(e, EBT_ILOGICALOUT,
ebt_dev_check(e->logical_out, p->br->dev)))
return 1;
if (e->bitmask & EBT_SOURCEMAC) {
if (NF_INVF(e, EBT_ISOURCE,
!ether_addr_equal_masked(h->h_source, e->sourcemac,
e->sourcemsk)))
return 1;
}
if (e->bitmask & EBT_DESTMAC) {
if (NF_INVF(e, EBT_IDEST,
!ether_addr_equal_masked(h->h_dest, e->destmac,
e->destmsk)))
return 1;
}
return 0;
}
static inline
struct ebt_entry *ebt_next_entry(const struct ebt_entry *entry)
{
return (void *)entry + entry->next_offset;
}
/* Do some firewalling */
unsigned int ebt_do_table(struct sk_buff *skb,
const struct nf_hook_state *state,
struct ebt_table *table)
{
unsigned int hook = state->hook;
int i, nentries;
struct ebt_entry *point;
struct ebt_counter *counter_base, *cb_base;
const struct ebt_entry_target *t;
int verdict, sp = 0;
struct ebt_chainstack *cs;
struct ebt_entries *chaininfo;
const char *base;
const struct ebt_table_info *private;
struct xt_action_param acpar;
acpar.state = state;
acpar.hotdrop = false;
read_lock_bh(&table->lock);
private = table->private;
cb_base = COUNTER_BASE(private->counters, private->nentries,
smp_processor_id());
if (private->chainstack)
cs = private->chainstack[smp_processor_id()];
else
cs = NULL;
chaininfo = private->hook_entry[hook];
nentries = private->hook_entry[hook]->nentries;
point = (struct ebt_entry *)(private->hook_entry[hook]->data);
counter_base = cb_base + private->hook_entry[hook]->counter_offset;
/* base for chain jumps */
base = private->entries;
i = 0;
while (i < nentries) {
if (ebt_basic_match(point, skb, state->in, state->out))
goto letscontinue;
if (EBT_MATCH_ITERATE(point, ebt_do_match, skb, &acpar) != 0)
goto letscontinue;
if (acpar.hotdrop) {
read_unlock_bh(&table->lock);
return NF_DROP;
}
/* increase counter */
(*(counter_base + i)).pcnt++;
(*(counter_base + i)).bcnt += skb->len;
/* these should only watch: not modify, nor tell us
* what to do with the packet
*/
EBT_WATCHER_ITERATE(point, ebt_do_watcher, skb, &acpar);
t = (struct ebt_entry_target *)
(((char *)point) + point->target_offset);
/* standard target */
if (!t->u.target->target)
verdict = ((struct ebt_standard_target *)t)->verdict;
else {
acpar.target = t->u.target;
acpar.targinfo = t->data;
verdict = t->u.target->target(skb, &acpar);
}
if (verdict == EBT_ACCEPT) {
read_unlock_bh(&table->lock);
return NF_ACCEPT;
}
if (verdict == EBT_DROP) {
read_unlock_bh(&table->lock);
return NF_DROP;
}
if (verdict == EBT_RETURN) {
letsreturn:
if (WARN(sp == 0, "RETURN on base chain")) {
/* act like this is EBT_CONTINUE */
goto letscontinue;
}
sp--;
/* put all the local variables right */
i = cs[sp].n;
chaininfo = cs[sp].chaininfo;
nentries = chaininfo->nentries;
point = cs[sp].e;
counter_base = cb_base +
chaininfo->counter_offset;
continue;
}
if (verdict == EBT_CONTINUE)
goto letscontinue;
if (WARN(verdict < 0, "bogus standard verdict\n")) {
read_unlock_bh(&table->lock);
return NF_DROP;
}
/* jump to a udc */
cs[sp].n = i + 1;
cs[sp].chaininfo = chaininfo;
cs[sp].e = ebt_next_entry(point);
i = 0;
chaininfo = (struct ebt_entries *) (base + verdict);
if (WARN(chaininfo->distinguisher, "jump to non-chain\n")) {
read_unlock_bh(&table->lock);
return NF_DROP;
}
nentries = chaininfo->nentries;
point = (struct ebt_entry *)chaininfo->data;
counter_base = cb_base + chaininfo->counter_offset;
sp++;
continue;
letscontinue:
point = ebt_next_entry(point);
i++;
}
/* I actually like this :) */
if (chaininfo->policy == EBT_RETURN)
goto letsreturn;
if (chaininfo->policy == EBT_ACCEPT) {
read_unlock_bh(&table->lock);
return NF_ACCEPT;
}
read_unlock_bh(&table->lock);
return NF_DROP;
}
/* If it succeeds, returns element and locks mutex */
static inline void *
find_inlist_lock_noload(struct list_head *head, const char *name, int *error,
struct mutex *mutex)
{
struct {
struct list_head list;
char name[EBT_FUNCTION_MAXNAMELEN];
} *e;
mutex_lock(mutex);
list_for_each_entry(e, head, list) {
if (strcmp(e->name, name) == 0)
return e;
}
*error = -ENOENT;
mutex_unlock(mutex);
return NULL;
}
static void *
find_inlist_lock(struct list_head *head, const char *name, const char *prefix,
int *error, struct mutex *mutex)
{
return try_then_request_module(
find_inlist_lock_noload(head, name, error, mutex),
"%s%s", prefix, name);
}
static inline struct ebt_table *
find_table_lock(struct net *net, const char *name, int *error,
struct mutex *mutex)
{
return find_inlist_lock(&net->xt.tables[NFPROTO_BRIDGE], name,
"ebtable_", error, mutex);
}
static inline int
ebt_check_match(struct ebt_entry_match *m, struct xt_mtchk_param *par,
unsigned int *cnt)
{
const struct ebt_entry *e = par->entryinfo;
struct xt_match *match;
size_t left = ((char *)e + e->watchers_offset) - (char *)m;
int ret;
if (left < sizeof(struct ebt_entry_match) ||
left - sizeof(struct ebt_entry_match) < m->match_size)
return -EINVAL;
match = xt_find_match(NFPROTO_BRIDGE, m->u.name, 0);
if (IS_ERR(match) || match->family != NFPROTO_BRIDGE) {
if (!IS_ERR(match))
module_put(match->me);
request_module("ebt_%s", m->u.name);
match = xt_find_match(NFPROTO_BRIDGE, m->u.name, 0);
}
if (IS_ERR(match))
return PTR_ERR(match);
m->u.match = match;
par->match = match;
par->matchinfo = m->data;
ret = xt_check_match(par, m->match_size,
e->ethproto, e->invflags & EBT_IPROTO);
if (ret < 0) {
module_put(match->me);
return ret;
}
(*cnt)++;
return 0;
}
static inline int
ebt_check_watcher(struct ebt_entry_watcher *w, struct xt_tgchk_param *par,
unsigned int *cnt)
{
const struct ebt_entry *e = par->entryinfo;
struct xt_target *watcher;
size_t left = ((char *)e + e->target_offset) - (char *)w;
int ret;
if (left < sizeof(struct ebt_entry_watcher) ||
left - sizeof(struct ebt_entry_watcher) < w->watcher_size)
return -EINVAL;
watcher = xt_request_find_target(NFPROTO_BRIDGE, w->u.name, 0);
if (IS_ERR(watcher))
return PTR_ERR(watcher);
w->u.watcher = watcher;
par->target = watcher;
par->targinfo = w->data;
ret = xt_check_target(par, w->watcher_size,
e->ethproto, e->invflags & EBT_IPROTO);
if (ret < 0) {
module_put(watcher->me);
return ret;
}
(*cnt)++;
return 0;
}
static int ebt_verify_pointers(const struct ebt_replace *repl,
struct ebt_table_info *newinfo)
{
unsigned int limit = repl->entries_size;
unsigned int valid_hooks = repl->valid_hooks;
unsigned int offset = 0;
int i;
for (i = 0; i < NF_BR_NUMHOOKS; i++)
newinfo->hook_entry[i] = NULL;
newinfo->entries_size = repl->entries_size;
newinfo->nentries = repl->nentries;
while (offset < limit) {
size_t left = limit - offset;
struct ebt_entry *e = (void *)newinfo->entries + offset;
if (left < sizeof(unsigned int))
break;
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
if ((valid_hooks & (1 << i)) == 0)
continue;
if ((char __user *)repl->hook_entry[i] ==
repl->entries + offset)
break;
}
if (i != NF_BR_NUMHOOKS || !(e->bitmask & EBT_ENTRY_OR_ENTRIES)) {
if (e->bitmask != 0) {
/* we make userspace set this right,
* so there is no misunderstanding
*/
BUGPRINT("EBT_ENTRY_OR_ENTRIES shouldn't be set "
"in distinguisher\n");
return -EINVAL;
}
if (i != NF_BR_NUMHOOKS)
newinfo->hook_entry[i] = (struct ebt_entries *)e;
if (left < sizeof(struct ebt_entries))
break;
offset += sizeof(struct ebt_entries);
} else {
if (left < sizeof(struct ebt_entry))
break;
if (left < e->next_offset)
break;
if (e->next_offset < sizeof(struct ebt_entry))
return -EINVAL;
offset += e->next_offset;
}
}
if (offset != limit) {
BUGPRINT("entries_size too small\n");
return -EINVAL;
}
/* check if all valid hooks have a chain */
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
if (!newinfo->hook_entry[i] &&
(valid_hooks & (1 << i))) {
BUGPRINT("Valid hook without chain\n");
return -EINVAL;
}
}
return 0;
}
/* this one is very careful, as it is the first function
* to parse the userspace data
*/
static inline int
ebt_check_entry_size_and_hooks(const struct ebt_entry *e,
const struct ebt_table_info *newinfo,
unsigned int *n, unsigned int *cnt,
unsigned int *totalcnt, unsigned int *udc_cnt)
{
int i;
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
if ((void *)e == (void *)newinfo->hook_entry[i])
break;
}
/* beginning of a new chain
* if i == NF_BR_NUMHOOKS it must be a user defined chain
*/
if (i != NF_BR_NUMHOOKS || !e->bitmask) {
/* this checks if the previous chain has as many entries
* as it said it has
*/
if (*n != *cnt) {
BUGPRINT("nentries does not equal the nr of entries "
"in the chain\n");
return -EINVAL;
}
if (((struct ebt_entries *)e)->policy != EBT_DROP &&
((struct ebt_entries *)e)->policy != EBT_ACCEPT) {
/* only RETURN from udc */
if (i != NF_BR_NUMHOOKS ||
((struct ebt_entries *)e)->policy != EBT_RETURN) {
BUGPRINT("bad policy\n");
return -EINVAL;
}
}
if (i == NF_BR_NUMHOOKS) /* it's a user defined chain */
(*udc_cnt)++;
if (((struct ebt_entries *)e)->counter_offset != *totalcnt) {
BUGPRINT("counter_offset != totalcnt");
return -EINVAL;
}
*n = ((struct ebt_entries *)e)->nentries;
*cnt = 0;
return 0;
}
/* a plain old entry, heh */
if (sizeof(struct ebt_entry) > e->watchers_offset ||
e->watchers_offset > e->target_offset ||
e->target_offset >= e->next_offset) {
BUGPRINT("entry offsets not in right order\n");
return -EINVAL;
}
/* this is not checked anywhere else */
if (e->next_offset - e->target_offset < sizeof(struct ebt_entry_target)) {
BUGPRINT("target size too small\n");
return -EINVAL;
}
(*cnt)++;
(*totalcnt)++;
return 0;
}
struct ebt_cl_stack {
struct ebt_chainstack cs;
int from;
unsigned int hookmask;
};
/* We need these positions to check that the jumps to a different part of the
* entries is a jump to the beginning of a new chain.
*/
static inline int
ebt_get_udc_positions(struct ebt_entry *e, struct ebt_table_info *newinfo,
unsigned int *n, struct ebt_cl_stack *udc)
{
int i;
/* we're only interested in chain starts */
if (e->bitmask)
return 0;
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
if (newinfo->hook_entry[i] == (struct ebt_entries *)e)
break;
}
/* only care about udc */
if (i != NF_BR_NUMHOOKS)
return 0;
udc[*n].cs.chaininfo = (struct ebt_entries *)e;
/* these initialisations are depended on later in check_chainloops() */
udc[*n].cs.n = 0;
udc[*n].hookmask = 0;
(*n)++;
return 0;
}
static inline int
ebt_cleanup_match(struct ebt_entry_match *m, struct net *net, unsigned int *i)
{
struct xt_mtdtor_param par;
if (i && (*i)-- == 0)
return 1;
par.net = net;
par.match = m->u.match;
par.matchinfo = m->data;
par.family = NFPROTO_BRIDGE;
if (par.match->destroy != NULL)
par.match->destroy(&par);
module_put(par.match->me);
return 0;
}
static inline int
ebt_cleanup_watcher(struct ebt_entry_watcher *w, struct net *net, unsigned int *i)
{
struct xt_tgdtor_param par;
if (i && (*i)-- == 0)
return 1;
par.net = net;
par.target = w->u.watcher;
par.targinfo = w->data;
par.family = NFPROTO_BRIDGE;
if (par.target->destroy != NULL)
par.target->destroy(&par);
module_put(par.target->me);
return 0;
}
static inline int
ebt_cleanup_entry(struct ebt_entry *e, struct net *net, unsigned int *cnt)
{
struct xt_tgdtor_param par;
struct ebt_entry_target *t;
if (e->bitmask == 0)
return 0;
/* we're done */
if (cnt && (*cnt)-- == 0)
return 1;
EBT_WATCHER_ITERATE(e, ebt_cleanup_watcher, net, NULL);
EBT_MATCH_ITERATE(e, ebt_cleanup_match, net, NULL);
t = (struct ebt_entry_target *)(((char *)e) + e->target_offset);
par.net = net;
par.target = t->u.target;
par.targinfo = t->data;
par.family = NFPROTO_BRIDGE;
if (par.target->destroy != NULL)
par.target->destroy(&par);
module_put(par.target->me);
return 0;
}
static inline int
ebt_check_entry(struct ebt_entry *e, struct net *net,
const struct ebt_table_info *newinfo,
const char *name, unsigned int *cnt,
struct ebt_cl_stack *cl_s, unsigned int udc_cnt)
{
struct ebt_entry_target *t;
struct xt_target *target;
unsigned int i, j, hook = 0, hookmask = 0;
size_t gap;
int ret;
struct xt_mtchk_param mtpar;
struct xt_tgchk_param tgpar;
/* don't mess with the struct ebt_entries */
if (e->bitmask == 0)
return 0;
if (e->bitmask & ~EBT_F_MASK) {
BUGPRINT("Unknown flag for bitmask\n");
return -EINVAL;
}
if (e->invflags & ~EBT_INV_MASK) {
BUGPRINT("Unknown flag for inv bitmask\n");
return -EINVAL;
}
if ((e->bitmask & EBT_NOPROTO) && (e->bitmask & EBT_802_3)) {
BUGPRINT("NOPROTO & 802_3 not allowed\n");
return -EINVAL;
}
/* what hook do we belong to? */
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
if (!newinfo->hook_entry[i])
continue;
if ((char *)newinfo->hook_entry[i] < (char *)e)
hook = i;
else
break;
}
/* (1 << NF_BR_NUMHOOKS) tells the check functions the rule is on
* a base chain
*/
if (i < NF_BR_NUMHOOKS)
hookmask = (1 << hook) | (1 << NF_BR_NUMHOOKS);
else {
for (i = 0; i < udc_cnt; i++)
if ((char *)(cl_s[i].cs.chaininfo) > (char *)e)
break;
if (i == 0)
hookmask = (1 << hook) | (1 << NF_BR_NUMHOOKS);
else
hookmask = cl_s[i - 1].hookmask;
}
i = 0;
mtpar.net = tgpar.net = net;
mtpar.table = tgpar.table = name;
mtpar.entryinfo = tgpar.entryinfo = e;
mtpar.hook_mask = tgpar.hook_mask = hookmask;
mtpar.family = tgpar.family = NFPROTO_BRIDGE;
ret = EBT_MATCH_ITERATE(e, ebt_check_match, &mtpar, &i);
if (ret != 0)
goto cleanup_matches;
j = 0;
ret = EBT_WATCHER_ITERATE(e, ebt_check_watcher, &tgpar, &j);
if (ret != 0)
goto cleanup_watchers;
t = (struct ebt_entry_target *)(((char *)e) + e->target_offset);
gap = e->next_offset - e->target_offset;
target = xt_request_find_target(NFPROTO_BRIDGE, t->u.name, 0);
if (IS_ERR(target)) {
ret = PTR_ERR(target);
goto cleanup_watchers;
}
t->u.target = target;
if (t->u.target == &ebt_standard_target) {
if (gap < sizeof(struct ebt_standard_target)) {
BUGPRINT("Standard target size too big\n");
ret = -EFAULT;
goto cleanup_watchers;
}
if (((struct ebt_standard_target *)t)->verdict <
-NUM_STANDARD_TARGETS) {
BUGPRINT("Invalid standard target\n");
ret = -EFAULT;
goto cleanup_watchers;
}
} else if (t->target_size > gap - sizeof(struct ebt_entry_target)) {
module_put(t->u.target->me);
ret = -EFAULT;
goto cleanup_watchers;
}
tgpar.target = target;
tgpar.targinfo = t->data;
ret = xt_check_target(&tgpar, t->target_size,
e->ethproto, e->invflags & EBT_IPROTO);
if (ret < 0) {
module_put(target->me);
goto cleanup_watchers;
}
(*cnt)++;
return 0;
cleanup_watchers:
EBT_WATCHER_ITERATE(e, ebt_cleanup_watcher, net, &j);
cleanup_matches:
EBT_MATCH_ITERATE(e, ebt_cleanup_match, net, &i);
return ret;
}
/* checks for loops and sets the hook mask for udc
* the hook mask for udc tells us from which base chains the udc can be
* accessed. This mask is a parameter to the check() functions of the extensions
*/
static int check_chainloops(const struct ebt_entries *chain, struct ebt_cl_stack *cl_s,
unsigned int udc_cnt, unsigned int hooknr, char *base)
{
int i, chain_nr = -1, pos = 0, nentries = chain->nentries, verdict;
const struct ebt_entry *e = (struct ebt_entry *)chain->data;
const struct ebt_entry_target *t;
while (pos < nentries || chain_nr != -1) {
/* end of udc, go back one 'recursion' step */
if (pos == nentries) {
/* put back values of the time when this chain was called */
e = cl_s[chain_nr].cs.e;
if (cl_s[chain_nr].from != -1)
nentries =
cl_s[cl_s[chain_nr].from].cs.chaininfo->nentries;
else
nentries = chain->nentries;
pos = cl_s[chain_nr].cs.n;
/* make sure we won't see a loop that isn't one */
cl_s[chain_nr].cs.n = 0;
chain_nr = cl_s[chain_nr].from;
if (pos == nentries)
continue;
}
t = (struct ebt_entry_target *)
(((char *)e) + e->target_offset);
if (strcmp(t->u.name, EBT_STANDARD_TARGET))
goto letscontinue;
if (e->target_offset + sizeof(struct ebt_standard_target) >
e->next_offset) {
BUGPRINT("Standard target size too big\n");
return -1;
}
verdict = ((struct ebt_standard_target *)t)->verdict;
if (verdict >= 0) { /* jump to another chain */
struct ebt_entries *hlp2 =
(struct ebt_entries *)(base + verdict);
for (i = 0; i < udc_cnt; i++)
if (hlp2 == cl_s[i].cs.chaininfo)
break;
/* bad destination or loop */
if (i == udc_cnt) {
BUGPRINT("bad destination\n");
return -1;
}
if (cl_s[i].cs.n) {
BUGPRINT("loop\n");
return -1;
}
if (cl_s[i].hookmask & (1 << hooknr))
goto letscontinue;
/* this can't be 0, so the loop test is correct */
cl_s[i].cs.n = pos + 1;
pos = 0;
cl_s[i].cs.e = ebt_next_entry(e);
e = (struct ebt_entry *)(hlp2->data);
nentries = hlp2->nentries;
cl_s[i].from = chain_nr;
chain_nr = i;
/* this udc is accessible from the base chain for hooknr */
cl_s[i].hookmask |= (1 << hooknr);
continue;
}
letscontinue:
e = ebt_next_entry(e);
pos++;
}
return 0;
}
/* do the parsing of the table/chains/entries/matches/watchers/targets, heh */
static int translate_table(struct net *net, const char *name,
struct ebt_table_info *newinfo)
{
unsigned int i, j, k, udc_cnt;
int ret;
struct ebt_cl_stack *cl_s = NULL; /* used in the checking for chain loops */
i = 0;
while (i < NF_BR_NUMHOOKS && !newinfo->hook_entry[i])
i++;
if (i == NF_BR_NUMHOOKS) {
BUGPRINT("No valid hooks specified\n");
return -EINVAL;
}
if (newinfo->hook_entry[i] != (struct ebt_entries *)newinfo->entries) {
BUGPRINT("Chains don't start at beginning\n");
return -EINVAL;
}
/* make sure chains are ordered after each other in same order
* as their corresponding hooks
*/
for (j = i + 1; j < NF_BR_NUMHOOKS; j++) {
if (!newinfo->hook_entry[j])
continue;
if (newinfo->hook_entry[j] <= newinfo->hook_entry[i]) {
BUGPRINT("Hook order must be followed\n");
return -EINVAL;
}
i = j;
}
/* do some early checkings and initialize some things */
i = 0; /* holds the expected nr. of entries for the chain */
j = 0; /* holds the up to now counted entries for the chain */
k = 0; /* holds the total nr. of entries, should equal
* newinfo->nentries afterwards
*/
udc_cnt = 0; /* will hold the nr. of user defined chains (udc) */
ret = EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size,
ebt_check_entry_size_and_hooks, newinfo,
&i, &j, &k, &udc_cnt);
if (ret != 0)
return ret;
if (i != j) {
BUGPRINT("nentries does not equal the nr of entries in the "
"(last) chain\n");
return -EINVAL;
}
if (k != newinfo->nentries) {
BUGPRINT("Total nentries is wrong\n");
return -EINVAL;
}
/* get the location of the udc, put them in an array
* while we're at it, allocate the chainstack
*/
if (udc_cnt) {
/* this will get free'd in do_replace()/ebt_register_table()
* if an error occurs
*/
newinfo->chainstack =
vmalloc(nr_cpu_ids * sizeof(*(newinfo->chainstack)));
if (!newinfo->chainstack)
return -ENOMEM;
for_each_possible_cpu(i) {
newinfo->chainstack[i] =
vmalloc(udc_cnt * sizeof(*(newinfo->chainstack[0])));
if (!newinfo->chainstack[i]) {
while (i)
vfree(newinfo->chainstack[--i]);
vfree(newinfo->chainstack);
newinfo->chainstack = NULL;
return -ENOMEM;
}
}
cl_s = vmalloc(udc_cnt * sizeof(*cl_s));
if (!cl_s)
return -ENOMEM;
i = 0; /* the i'th udc */
EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size,
ebt_get_udc_positions, newinfo, &i, cl_s);
/* sanity check */
if (i != udc_cnt) {
BUGPRINT("i != udc_cnt\n");
vfree(cl_s);
return -EFAULT;
}
}
/* Check for loops */
for (i = 0; i < NF_BR_NUMHOOKS; i++)
if (newinfo->hook_entry[i])
if (check_chainloops(newinfo->hook_entry[i],
cl_s, udc_cnt, i, newinfo->entries)) {
vfree(cl_s);
return -EINVAL;
}
/* we now know the following (along with E=mc²):
* - the nr of entries in each chain is right
* - the size of the allocated space is right
* - all valid hooks have a corresponding chain
* - there are no loops
* - wrong data can still be on the level of a single entry
* - could be there are jumps to places that are not the
* beginning of a chain. This can only occur in chains that
* are not accessible from any base chains, so we don't care.
*/
/* used to know what we need to clean up if something goes wrong */
i = 0;
ret = EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size,
ebt_check_entry, net, newinfo, name, &i, cl_s, udc_cnt);
if (ret != 0) {
EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size,
ebt_cleanup_entry, net, &i);
}
vfree(cl_s);
return ret;
}
/* called under write_lock */
static void get_counters(const struct ebt_counter *oldcounters,
struct ebt_counter *counters, unsigned int nentries)
{
int i, cpu;
struct ebt_counter *counter_base;
/* counters of cpu 0 */
memcpy(counters, oldcounters,
sizeof(struct ebt_counter) * nentries);
/* add other counters to those of cpu 0 */
for_each_possible_cpu(cpu) {
if (cpu == 0)
continue;
counter_base = COUNTER_BASE(oldcounters, nentries, cpu);
for (i = 0; i < nentries; i++) {
counters[i].pcnt += counter_base[i].pcnt;
counters[i].bcnt += counter_base[i].bcnt;
}
}
}
static int do_replace_finish(struct net *net, struct ebt_replace *repl,
struct ebt_table_info *newinfo)
{
int ret, i;
struct ebt_counter *counterstmp = NULL;
/* used to be able to unlock earlier */
struct ebt_table_info *table;
struct ebt_table *t;
/* the user wants counters back
* the check on the size is done later, when we have the lock
*/
if (repl->num_counters) {
unsigned long size = repl->num_counters * sizeof(*counterstmp);
counterstmp = vmalloc(size);
if (!counterstmp)
return -ENOMEM;
}
newinfo->chainstack = NULL;
ret = ebt_verify_pointers(repl, newinfo);
if (ret != 0)
goto free_counterstmp;
ret = translate_table(net, repl->name, newinfo);
if (ret != 0)
goto free_counterstmp;
t = find_table_lock(net, repl->name, &ret, &ebt_mutex);
if (!t) {
ret = -ENOENT;
goto free_iterate;
}
/* the table doesn't like it */
if (t->check && (ret = t->check(newinfo, repl->valid_hooks)))
goto free_unlock;
if (repl->num_counters && repl->num_counters != t->private->nentries) {
BUGPRINT("Wrong nr. of counters requested\n");
ret = -EINVAL;
goto free_unlock;
}
/* we have the mutex lock, so no danger in reading this pointer */
table = t->private;
/* make sure the table can only be rmmod'ed if it contains no rules */
if (!table->nentries && newinfo->nentries && !try_module_get(t->me)) {
ret = -ENOENT;
goto free_unlock;
} else if (table->nentries && !newinfo->nentries)
module_put(t->me);
/* we need an atomic snapshot of the counters */
write_lock_bh(&t->lock);
if (repl->num_counters)
get_counters(t->private->counters, counterstmp,
t->private->nentries);
t->private = newinfo;
write_unlock_bh(&t->lock);
mutex_unlock(&ebt_mutex);
/* so, a user can change the chains while having messed up her counter
* allocation. Only reason why this is done is because this way the lock
* is held only once, while this doesn't bring the kernel into a
* dangerous state.
*/
if (repl->num_counters &&
copy_to_user(repl->counters, counterstmp,
repl->num_counters * sizeof(struct ebt_counter))) {
/* Silent error, can't fail, new table is already in place */
net_warn_ratelimited("ebtables: counters copy to user failed while replacing table\n");
}
/* decrease module count and free resources */
EBT_ENTRY_ITERATE(table->entries, table->entries_size,
ebt_cleanup_entry, net, NULL);
vfree(table->entries);
if (table->chainstack) {
for_each_possible_cpu(i)
vfree(table->chainstack[i]);
vfree(table->chainstack);
}
vfree(table);
vfree(counterstmp);
#ifdef CONFIG_AUDIT
if (audit_enabled) {
audit_log(current->audit_context, GFP_KERNEL,
AUDIT_NETFILTER_CFG,
"table=%s family=%u entries=%u",
repl->name, AF_BRIDGE, repl->nentries);
}
#endif
return ret;
free_unlock:
mutex_unlock(&ebt_mutex);
free_iterate:
EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size,
ebt_cleanup_entry, net, NULL);
free_counterstmp:
vfree(counterstmp);
/* can be initialized in translate_table() */
if (newinfo->chainstack) {
for_each_possible_cpu(i)
vfree(newinfo->chainstack[i]);
vfree(newinfo->chainstack);
}
return ret;
}
/* replace the table */
static int do_replace(struct net *net, const void __user *user,
unsigned int len)
{
int ret, countersize;
struct ebt_table_info *newinfo;
struct ebt_replace tmp;
if (copy_from_user(&tmp, user, sizeof(tmp)) != 0)
return -EFAULT;
if (len != sizeof(tmp) + tmp.entries_size) {
BUGPRINT("Wrong len argument\n");
return -EINVAL;
}
if (tmp.entries_size == 0) {
BUGPRINT("Entries_size never zero\n");
return -EINVAL;
}
/* overflow check */
if (tmp.nentries >= ((INT_MAX - sizeof(struct ebt_table_info)) /
NR_CPUS - SMP_CACHE_BYTES) / sizeof(struct ebt_counter))
return -ENOMEM;
if (tmp.num_counters >= INT_MAX / sizeof(struct ebt_counter))
return -ENOMEM;
tmp.name[sizeof(tmp.name) - 1] = 0;
countersize = COUNTER_OFFSET(tmp.nentries) * nr_cpu_ids;
newinfo = vmalloc(sizeof(*newinfo) + countersize);
if (!newinfo)
return -ENOMEM;
if (countersize)
memset(newinfo->counters, 0, countersize);
newinfo->entries = vmalloc(tmp.entries_size);
if (!newinfo->entries) {
ret = -ENOMEM;
goto free_newinfo;
}
if (copy_from_user(
newinfo->entries, tmp.entries, tmp.entries_size) != 0) {
BUGPRINT("Couldn't copy entries from userspace\n");
ret = -EFAULT;
goto free_entries;
}
ret = do_replace_finish(net, &tmp, newinfo);
if (ret == 0)
return ret;
free_entries:
vfree(newinfo->entries);
free_newinfo:
vfree(newinfo);
return ret;
}
static void __ebt_unregister_table(struct net *net, struct ebt_table *table)
{
int i;
mutex_lock(&ebt_mutex);
list_del(&table->list);
mutex_unlock(&ebt_mutex);
EBT_ENTRY_ITERATE(table->private->entries, table->private->entries_size,
ebt_cleanup_entry, net, NULL);
if (table->private->nentries)
module_put(table->me);
vfree(table->private->entries);
if (table->private->chainstack) {
for_each_possible_cpu(i)
vfree(table->private->chainstack[i]);
vfree(table->private->chainstack);
}
vfree(table->private);
kfree(table);
}
int ebt_register_table(struct net *net, const struct ebt_table *input_table,
const struct nf_hook_ops *ops, struct ebt_table **res)
{
struct ebt_table_info *newinfo;
struct ebt_table *t, *table;
struct ebt_replace_kernel *repl;
int ret, i, countersize;
void *p;
if (input_table == NULL || (repl = input_table->table) == NULL ||
repl->entries == NULL || repl->entries_size == 0 ||
repl->counters != NULL || input_table->private != NULL) {
BUGPRINT("Bad table data for ebt_register_table!!!\n");
return -EINVAL;
}
/* Don't add one table to multiple lists. */
table = kmemdup(input_table, sizeof(struct ebt_table), GFP_KERNEL);
if (!table) {
ret = -ENOMEM;
goto out;
}
countersize = COUNTER_OFFSET(repl->nentries) * nr_cpu_ids;
newinfo = vmalloc(sizeof(*newinfo) + countersize);
ret = -ENOMEM;
if (!newinfo)
goto free_table;
p = vmalloc(repl->entries_size);
if (!p)
goto free_newinfo;
memcpy(p, repl->entries, repl->entries_size);
newinfo->entries = p;
newinfo->entries_size = repl->entries_size;
newinfo->nentries = repl->nentries;
if (countersize)
memset(newinfo->counters, 0, countersize);
/* fill in newinfo and parse the entries */
newinfo->chainstack = NULL;
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
if ((repl->valid_hooks & (1 << i)) == 0)
newinfo->hook_entry[i] = NULL;
else
newinfo->hook_entry[i] = p +
((char *)repl->hook_entry[i] - repl->entries);
}
ret = translate_table(net, repl->name, newinfo);
if (ret != 0) {
BUGPRINT("Translate_table failed\n");
goto free_chainstack;
}
if (table->check && table->check(newinfo, table->valid_hooks)) {
BUGPRINT("The table doesn't like its own initial data, lol\n");
ret = -EINVAL;
goto free_chainstack;
}
table->private = newinfo;
rwlock_init(&table->lock);
mutex_lock(&ebt_mutex);
list_for_each_entry(t, &net->xt.tables[NFPROTO_BRIDGE], list) {
if (strcmp(t->name, table->name) == 0) {
ret = -EEXIST;
BUGPRINT("Table name already exists\n");
goto free_unlock;
}
}
/* Hold a reference count if the chains aren't empty */
if (newinfo->nentries && !try_module_get(table->me)) {
ret = -ENOENT;
goto free_unlock;
}
list_add(&table->list, &net->xt.tables[NFPROTO_BRIDGE]);
mutex_unlock(&ebt_mutex);
WRITE_ONCE(*res, table);
if (!ops)
return 0;
ret = nf_register_net_hooks(net, ops, hweight32(table->valid_hooks));
if (ret) {
__ebt_unregister_table(net, table);
*res = NULL;
}
return ret;
free_unlock:
mutex_unlock(&ebt_mutex);
free_chainstack:
if (newinfo->chainstack) {
for_each_possible_cpu(i)
vfree(newinfo->chainstack[i]);
vfree(newinfo->chainstack);
}
vfree(newinfo->entries);
free_newinfo:
vfree(newinfo);
free_table:
kfree(table);
out:
return ret;
}
void ebt_unregister_table(struct net *net, struct ebt_table *table,
const struct nf_hook_ops *ops)
{
if (ops)
nf_unregister_net_hooks(net, ops, hweight32(table->valid_hooks));
__ebt_unregister_table(net, table);
}
/* userspace just supplied us with counters */
static int do_update_counters(struct net *net, const char *name,
struct ebt_counter __user *counters,
unsigned int num_counters,
const void __user *user, unsigned int len)
{
int i, ret;
struct ebt_counter *tmp;
struct ebt_table *t;
if (num_counters == 0)
return -EINVAL;
tmp = vmalloc(num_counters * sizeof(*tmp));
if (!tmp)
return -ENOMEM;
t = find_table_lock(net, name, &ret, &ebt_mutex);
if (!t)
goto free_tmp;
if (num_counters != t->private->nentries) {
BUGPRINT("Wrong nr of counters\n");
ret = -EINVAL;
goto unlock_mutex;
}
if (copy_from_user(tmp, counters, num_counters * sizeof(*counters))) {
ret = -EFAULT;
goto unlock_mutex;
}
/* we want an atomic add of the counters */
write_lock_bh(&t->lock);
/* we add to the counters of the first cpu */
for (i = 0; i < num_counters; i++) {
t->private->counters[i].pcnt += tmp[i].pcnt;
t->private->counters[i].bcnt += tmp[i].bcnt;
}
write_unlock_bh(&t->lock);
ret = 0;
unlock_mutex:
mutex_unlock(&ebt_mutex);
free_tmp:
vfree(tmp);
return ret;
}
static int update_counters(struct net *net, const void __user *user,
unsigned int len)
{
struct ebt_replace hlp;
if (copy_from_user(&hlp, user, sizeof(hlp)))
return -EFAULT;
if (len != sizeof(hlp) + hlp.num_counters * sizeof(struct ebt_counter))
return -EINVAL;
return do_update_counters(net, hlp.name, hlp.counters,
hlp.num_counters, user, len);
}
static inline int ebt_obj_to_user(char __user *um, const char *_name,
const char *data, int entrysize,
int usersize, int datasize)
{
char name[EBT_FUNCTION_MAXNAMELEN] = {0};
/* ebtables expects 32 bytes long names but xt_match names are 29 bytes
* long. Copy 29 bytes and fill remaining bytes with zeroes.
*/
strlcpy(name, _name, sizeof(name));
if (copy_to_user(um, name, EBT_FUNCTION_MAXNAMELEN) ||
put_user(datasize, (int __user *)(um + EBT_FUNCTION_MAXNAMELEN)) ||
xt_data_to_user(um + entrysize, data, usersize, datasize,
XT_ALIGN(datasize)))
return -EFAULT;
return 0;
}
static inline int ebt_match_to_user(const struct ebt_entry_match *m,
const char *base, char __user *ubase)
{
return ebt_obj_to_user(ubase + ((char *)m - base),
m->u.match->name, m->data, sizeof(*m),
m->u.match->usersize, m->match_size);
}
static inline int ebt_watcher_to_user(const struct ebt_entry_watcher *w,
const char *base, char __user *ubase)
{
return ebt_obj_to_user(ubase + ((char *)w - base),
w->u.watcher->name, w->data, sizeof(*w),
w->u.watcher->usersize, w->watcher_size);
}
static inline int ebt_entry_to_user(struct ebt_entry *e, const char *base,
char __user *ubase)
{
int ret;
char __user *hlp;
const struct ebt_entry_target *t;
if (e->bitmask == 0) {
/* special case !EBT_ENTRY_OR_ENTRIES */
if (copy_to_user(ubase + ((char *)e - base), e,
sizeof(struct ebt_entries)))
return -EFAULT;
return 0;
}
if (copy_to_user(ubase + ((char *)e - base), e, sizeof(*e)))
return -EFAULT;
hlp = ubase + (((char *)e + e->target_offset) - base);
t = (struct ebt_entry_target *)(((char *)e) + e->target_offset);
ret = EBT_MATCH_ITERATE(e, ebt_match_to_user, base, ubase);
if (ret != 0)
return ret;
ret = EBT_WATCHER_ITERATE(e, ebt_watcher_to_user, base, ubase);
if (ret != 0)
return ret;
ret = ebt_obj_to_user(hlp, t->u.target->name, t->data, sizeof(*t),
t->u.target->usersize, t->target_size);
if (ret != 0)
return ret;
return 0;
}
static int copy_counters_to_user(struct ebt_table *t,
const struct ebt_counter *oldcounters,
void __user *user, unsigned int num_counters,
unsigned int nentries)
{
struct ebt_counter *counterstmp;
int ret = 0;
/* userspace might not need the counters */
if (num_counters == 0)
return 0;
if (num_counters != nentries) {
BUGPRINT("Num_counters wrong\n");
return -EINVAL;
}
counterstmp = vmalloc(nentries * sizeof(*counterstmp));
if (!counterstmp)
return -ENOMEM;
write_lock_bh(&t->lock);
get_counters(oldcounters, counterstmp, nentries);
write_unlock_bh(&t->lock);
if (copy_to_user(user, counterstmp,
nentries * sizeof(struct ebt_counter)))
ret = -EFAULT;
vfree(counterstmp);
return ret;
}
/* called with ebt_mutex locked */
static int copy_everything_to_user(struct ebt_table *t, void __user *user,
const int *len, int cmd)
{
struct ebt_replace tmp;
const struct ebt_counter *oldcounters;
unsigned int entries_size, nentries;
int ret;
char *entries;
if (cmd == EBT_SO_GET_ENTRIES) {
entries_size = t->private->entries_size;
nentries = t->private->nentries;
entries = t->private->entries;
oldcounters = t->private->counters;
} else {
entries_size = t->table->entries_size;
nentries = t->table->nentries;
entries = t->table->entries;
oldcounters = t->table->counters;
}
if (copy_from_user(&tmp, user, sizeof(tmp)))
return -EFAULT;
if (*len != sizeof(struct ebt_replace) + entries_size +
(tmp.num_counters ? nentries * sizeof(struct ebt_counter) : 0))
return -EINVAL;
if (tmp.nentries != nentries) {
BUGPRINT("Nentries wrong\n");
return -EINVAL;
}
if (tmp.entries_size != entries_size) {
BUGPRINT("Wrong size\n");
return -EINVAL;
}
ret = copy_counters_to_user(t, oldcounters, tmp.counters,
tmp.num_counters, nentries);
if (ret)
return ret;
/* set the match/watcher/target names right */
return EBT_ENTRY_ITERATE(entries, entries_size,
ebt_entry_to_user, entries, tmp.entries);
}
static int do_ebt_set_ctl(struct sock *sk,
int cmd, void __user *user, unsigned int len)
{
int ret;
struct net *net = sock_net(sk);
if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
return -EPERM;
switch (cmd) {
case EBT_SO_SET_ENTRIES:
ret = do_replace(net, user, len);
break;
case EBT_SO_SET_COUNTERS:
ret = update_counters(net, user, len);
break;
default:
ret = -EINVAL;
}
return ret;
}
static int do_ebt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)
{
int ret;
struct ebt_replace tmp;
struct ebt_table *t;
struct net *net = sock_net(sk);
if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
return -EPERM;
if (copy_from_user(&tmp, user, sizeof(tmp)))
return -EFAULT;
tmp.name[sizeof(tmp.name) - 1] = '\0';
t = find_table_lock(net, tmp.name, &ret, &ebt_mutex);
if (!t)
return ret;
switch (cmd) {
case EBT_SO_GET_INFO:
case EBT_SO_GET_INIT_INFO:
if (*len != sizeof(struct ebt_replace)) {
ret = -EINVAL;
mutex_unlock(&ebt_mutex);
break;
}
if (cmd == EBT_SO_GET_INFO) {
tmp.nentries = t->private->nentries;
tmp.entries_size = t->private->entries_size;
tmp.valid_hooks = t->valid_hooks;
} else {
tmp.nentries = t->table->nentries;
tmp.entries_size = t->table->entries_size;
tmp.valid_hooks = t->table->valid_hooks;
}
mutex_unlock(&ebt_mutex);
if (copy_to_user(user, &tmp, *len) != 0) {
BUGPRINT("c2u Didn't work\n");
ret = -EFAULT;
break;
}
ret = 0;
break;
case EBT_SO_GET_ENTRIES:
case EBT_SO_GET_INIT_ENTRIES:
ret = copy_everything_to_user(t, user, len, cmd);
mutex_unlock(&ebt_mutex);
break;
default:
mutex_unlock(&ebt_mutex);
ret = -EINVAL;
}
return ret;
}
#ifdef CONFIG_COMPAT
/* 32 bit-userspace compatibility definitions. */
struct compat_ebt_replace {
char name[EBT_TABLE_MAXNAMELEN];
compat_uint_t valid_hooks;
compat_uint_t nentries;
compat_uint_t entries_size;
/* start of the chains */
compat_uptr_t hook_entry[NF_BR_NUMHOOKS];
/* nr of counters userspace expects back */
compat_uint_t num_counters;
/* where the kernel will put the old counters. */
compat_uptr_t counters;
compat_uptr_t entries;
};
/* struct ebt_entry_match, _target and _watcher have same layout */
struct compat_ebt_entry_mwt {
union {
char name[EBT_FUNCTION_MAXNAMELEN];
compat_uptr_t ptr;
} u;
compat_uint_t match_size;
compat_uint_t data[0];
};
/* account for possible padding between match_size and ->data */
static int ebt_compat_entry_padsize(void)
{
BUILD_BUG_ON(XT_ALIGN(sizeof(struct ebt_entry_match)) <
COMPAT_XT_ALIGN(sizeof(struct compat_ebt_entry_mwt)));
return (int) XT_ALIGN(sizeof(struct ebt_entry_match)) -
COMPAT_XT_ALIGN(sizeof(struct compat_ebt_entry_mwt));
}
static int ebt_compat_match_offset(const struct xt_match *match,
unsigned int userlen)
{
/* ebt_among needs special handling. The kernel .matchsize is
* set to -1 at registration time; at runtime an EBT_ALIGN()ed
* value is expected.
* Example: userspace sends 4500, ebt_among.c wants 4504.
*/
if (unlikely(match->matchsize == -1))
return XT_ALIGN(userlen) - COMPAT_XT_ALIGN(userlen);
return xt_compat_match_offset(match);
}
static int compat_match_to_user(struct ebt_entry_match *m, void __user **dstptr,
unsigned int *size)
{
const struct xt_match *match = m->u.match;
struct compat_ebt_entry_mwt __user *cm = *dstptr;
int off = ebt_compat_match_offset(match, m->match_size);
compat_uint_t msize = m->match_size - off;
if (WARN_ON(off >= m->match_size))
return -EINVAL;
if (copy_to_user(cm->u.name, match->name,
strlen(match->name) + 1) || put_user(msize, &cm->match_size))
return -EFAULT;
if (match->compat_to_user) {
if (match->compat_to_user(cm->data, m->data))
return -EFAULT;
} else {
if (xt_data_to_user(cm->data, m->data, match->usersize, msize,
COMPAT_XT_ALIGN(msize)))
return -EFAULT;
}
*size -= ebt_compat_entry_padsize() + off;
*dstptr = cm->data;
*dstptr += msize;
return 0;
}
static int compat_target_to_user(struct ebt_entry_target *t,
void __user **dstptr,
unsigned int *size)
{
const struct xt_target *target = t->u.target;
struct compat_ebt_entry_mwt __user *cm = *dstptr;
int off = xt_compat_target_offset(target);
compat_uint_t tsize = t->target_size - off;
if (WARN_ON(off >= t->target_size))
return -EINVAL;
if (copy_to_user(cm->u.name, target->name,
strlen(target->name) + 1) || put_user(tsize, &cm->match_size))
return -EFAULT;
if (target->compat_to_user) {
if (target->compat_to_user(cm->data, t->data))
return -EFAULT;
} else {
if (xt_data_to_user(cm->data, t->data, target->usersize, tsize,
COMPAT_XT_ALIGN(tsize)))
return -EFAULT;
}
*size -= ebt_compat_entry_padsize() + off;
*dstptr = cm->data;
*dstptr += tsize;
return 0;
}
static int compat_watcher_to_user(struct ebt_entry_watcher *w,
void __user **dstptr,
unsigned int *size)
{
return compat_target_to_user((struct ebt_entry_target *)w,
dstptr, size);
}
static int compat_copy_entry_to_user(struct ebt_entry *e, void __user **dstptr,
unsigned int *size)
{
struct ebt_entry_target *t;
struct ebt_entry __user *ce;
u32 watchers_offset, target_offset, next_offset;
compat_uint_t origsize;
int ret;
if (e->bitmask == 0) {
if (*size < sizeof(struct ebt_entries))
return -EINVAL;
if (copy_to_user(*dstptr, e, sizeof(struct ebt_entries)))
return -EFAULT;
*dstptr += sizeof(struct ebt_entries);
*size -= sizeof(struct ebt_entries);
return 0;
}
if (*size < sizeof(*ce))
return -EINVAL;
ce = *dstptr;
if (copy_to_user(ce, e, sizeof(*ce)))
return -EFAULT;
origsize = *size;
*dstptr += sizeof(*ce);
ret = EBT_MATCH_ITERATE(e, compat_match_to_user, dstptr, size);
if (ret)
return ret;
watchers_offset = e->watchers_offset - (origsize - *size);
ret = EBT_WATCHER_ITERATE(e, compat_watcher_to_user, dstptr, size);
if (ret)
return ret;
target_offset = e->target_offset - (origsize - *size);
t = (struct ebt_entry_target *) ((char *) e + e->target_offset);
ret = compat_target_to_user(t, dstptr, size);
if (ret)
return ret;
next_offset = e->next_offset - (origsize - *size);
if (put_user(watchers_offset, &ce->watchers_offset) ||
put_user(target_offset, &ce->target_offset) ||
put_user(next_offset, &ce->next_offset))
return -EFAULT;
*size -= sizeof(*ce);
return 0;
}
static int compat_calc_match(struct ebt_entry_match *m, int *off)
{
*off += ebt_compat_match_offset(m->u.match, m->match_size);
*off += ebt_compat_entry_padsize();
return 0;
}
static int compat_calc_watcher(struct ebt_entry_watcher *w, int *off)
{
*off += xt_compat_target_offset(w->u.watcher);
*off += ebt_compat_entry_padsize();
return 0;
}
static int compat_calc_entry(const struct ebt_entry *e,
const struct ebt_table_info *info,
const void *base,
struct compat_ebt_replace *newinfo)
{
const struct ebt_entry_target *t;
unsigned int entry_offset;
int off, ret, i;
if (e->bitmask == 0)
return 0;
off = 0;
entry_offset = (void *)e - base;
EBT_MATCH_ITERATE(e, compat_calc_match, &off);
EBT_WATCHER_ITERATE(e, compat_calc_watcher, &off);
t = (const struct ebt_entry_target *) ((char *) e + e->target_offset);
off += xt_compat_target_offset(t->u.target);
off += ebt_compat_entry_padsize();
newinfo->entries_size -= off;
ret = xt_compat_add_offset(NFPROTO_BRIDGE, entry_offset, off);
if (ret)
return ret;
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
const void *hookptr = info->hook_entry[i];
if (info->hook_entry[i] &&
(e < (struct ebt_entry *)(base - hookptr))) {
newinfo->hook_entry[i] -= off;
pr_debug("0x%08X -> 0x%08X\n",
newinfo->hook_entry[i] + off,
newinfo->hook_entry[i]);
}
}
return 0;
}
static int compat_table_info(const struct ebt_table_info *info,
struct compat_ebt_replace *newinfo)
{
unsigned int size = info->entries_size;
const void *entries = info->entries;
newinfo->entries_size = size;
xt_compat_init_offsets(NFPROTO_BRIDGE, info->nentries);
return EBT_ENTRY_ITERATE(entries, size, compat_calc_entry, info,
entries, newinfo);
}
static int compat_copy_everything_to_user(struct ebt_table *t,
void __user *user, int *len, int cmd)
{
struct compat_ebt_replace repl, tmp;
struct ebt_counter *oldcounters;
struct ebt_table_info tinfo;
int ret;
void __user *pos;
memset(&tinfo, 0, sizeof(tinfo));
if (cmd == EBT_SO_GET_ENTRIES) {
tinfo.entries_size = t->private->entries_size;
tinfo.nentries = t->private->nentries;
tinfo.entries = t->private->entries;
oldcounters = t->private->counters;
} else {
tinfo.entries_size = t->table->entries_size;
tinfo.nentries = t->table->nentries;
tinfo.entries = t->table->entries;
oldcounters = t->table->counters;
}
if (copy_from_user(&tmp, user, sizeof(tmp)))
return -EFAULT;
if (tmp.nentries != tinfo.nentries ||
(tmp.num_counters && tmp.num_counters != tinfo.nentries))
return -EINVAL;
memcpy(&repl, &tmp, sizeof(repl));
if (cmd == EBT_SO_GET_ENTRIES)
ret = compat_table_info(t->private, &repl);
else
ret = compat_table_info(&tinfo, &repl);
if (ret)
return ret;
if (*len != sizeof(tmp) + repl.entries_size +
(tmp.num_counters? tinfo.nentries * sizeof(struct ebt_counter): 0)) {
pr_err("wrong size: *len %d, entries_size %u, replsz %d\n",
*len, tinfo.entries_size, repl.entries_size);
return -EINVAL;
}
/* userspace might not need the counters */
ret = copy_counters_to_user(t, oldcounters, compat_ptr(tmp.counters),
tmp.num_counters, tinfo.nentries);
if (ret)
return ret;
pos = compat_ptr(tmp.entries);
return EBT_ENTRY_ITERATE(tinfo.entries, tinfo.entries_size,
compat_copy_entry_to_user, &pos, &tmp.entries_size);
}
struct ebt_entries_buf_state {
char *buf_kern_start; /* kernel buffer to copy (translated) data to */
u32 buf_kern_len; /* total size of kernel buffer */
u32 buf_kern_offset; /* amount of data copied so far */
u32 buf_user_offset; /* read position in userspace buffer */
};
static int ebt_buf_count(struct ebt_entries_buf_state *state, unsigned int sz)
{
state->buf_kern_offset += sz;
return state->buf_kern_offset >= sz ? 0 : -EINVAL;
}
static int ebt_buf_add(struct ebt_entries_buf_state *state,
void *data, unsigned int sz)
{
if (state->buf_kern_start == NULL)
goto count_only;
if (WARN_ON(state->buf_kern_offset + sz > state->buf_kern_len))
return -EINVAL;
memcpy(state->buf_kern_start + state->buf_kern_offset, data, sz);
count_only:
state->buf_user_offset += sz;
return ebt_buf_count(state, sz);
}
static int ebt_buf_add_pad(struct ebt_entries_buf_state *state, unsigned int sz)
{
char *b = state->buf_kern_start;
if (WARN_ON(b && state->buf_kern_offset > state->buf_kern_len))
return -EINVAL;
if (b != NULL && sz > 0)
memset(b + state->buf_kern_offset, 0, sz);
/* do not adjust ->buf_user_offset here, we added kernel-side padding */
return ebt_buf_count(state, sz);
}
enum compat_mwt {
EBT_COMPAT_MATCH,
EBT_COMPAT_WATCHER,
EBT_COMPAT_TARGET,
};
static int compat_mtw_from_user(struct compat_ebt_entry_mwt *mwt,
enum compat_mwt compat_mwt,
struct ebt_entries_buf_state *state,
const unsigned char *base)
{
char name[EBT_FUNCTION_MAXNAMELEN];
struct xt_match *match;
struct xt_target *wt;
void *dst = NULL;
int off, pad = 0;
unsigned int size_kern, match_size = mwt->match_size;
strlcpy(name, mwt->u.name, sizeof(name));
if (state->buf_kern_start)
dst = state->buf_kern_start + state->buf_kern_offset;
switch (compat_mwt) {
case EBT_COMPAT_MATCH:
match = xt_request_find_match(NFPROTO_BRIDGE, name, 0);
if (IS_ERR(match))
return PTR_ERR(match);
off = ebt_compat_match_offset(match, match_size);
if (dst) {
if (match->compat_from_user)
match->compat_from_user(dst, mwt->data);
else
memcpy(dst, mwt->data, match_size);
}
size_kern = match->matchsize;
if (unlikely(size_kern == -1))
size_kern = match_size;
module_put(match->me);
break;
case EBT_COMPAT_WATCHER: /* fallthrough */
case EBT_COMPAT_TARGET:
wt = xt_request_find_target(NFPROTO_BRIDGE, name, 0);
if (IS_ERR(wt))
return PTR_ERR(wt);
off = xt_compat_target_offset(wt);
if (dst) {
if (wt->compat_from_user)
wt->compat_from_user(dst, mwt->data);
else
memcpy(dst, mwt->data, match_size);
}
size_kern = wt->targetsize;
module_put(wt->me);
break;
default:
return -EINVAL;
}
state->buf_kern_offset += match_size + off;
state->buf_user_offset += match_size;
pad = XT_ALIGN(size_kern) - size_kern;
if (pad > 0 && dst) {
if (WARN_ON(state->buf_kern_len <= pad))
return -EINVAL;
if (WARN_ON(state->buf_kern_offset - (match_size + off) + size_kern > state->buf_kern_len - pad))
return -EINVAL;
memset(dst + size_kern, 0, pad);
}
return off + match_size;
}
/* return size of all matches, watchers or target, including necessary
* alignment and padding.
*/
static int ebt_size_mwt(struct compat_ebt_entry_mwt *match32,
unsigned int size_left, enum compat_mwt type,
struct ebt_entries_buf_state *state, const void *base)
{
int growth = 0;
char *buf;
if (size_left == 0)
return 0;
buf = (char *) match32;
while (size_left >= sizeof(*match32)) {
struct ebt_entry_match *match_kern;
int ret;
match_kern = (struct ebt_entry_match *) state->buf_kern_start;
if (match_kern) {
char *tmp;
tmp = state->buf_kern_start + state->buf_kern_offset;
match_kern = (struct ebt_entry_match *) tmp;
}
ret = ebt_buf_add(state, buf, sizeof(*match32));
if (ret < 0)
return ret;
size_left -= sizeof(*match32);
/* add padding before match->data (if any) */
ret = ebt_buf_add_pad(state, ebt_compat_entry_padsize());
if (ret < 0)
return ret;
if (match32->match_size > size_left)
return -EINVAL;
size_left -= match32->match_size;
ret = compat_mtw_from_user(match32, type, state, base);
if (ret < 0)
return ret;
if (WARN_ON(ret < match32->match_size))
return -EINVAL;
growth += ret - match32->match_size;
growth += ebt_compat_entry_padsize();
buf += sizeof(*match32);
buf += match32->match_size;
if (match_kern)
match_kern->match_size = ret;
WARN_ON(type == EBT_COMPAT_TARGET && size_left);
match32 = (struct compat_ebt_entry_mwt *) buf;
}
return growth;
}
/* called for all ebt_entry structures. */
static int size_entry_mwt(struct ebt_entry *entry, const unsigned char *base,
unsigned int *total,
struct ebt_entries_buf_state *state)
{
unsigned int i, j, startoff, new_offset = 0;
/* stores match/watchers/targets & offset of next struct ebt_entry: */
unsigned int offsets[4];
unsigned int *offsets_update = NULL;
int ret;
char *buf_start;
if (*total < sizeof(struct ebt_entries))
return -EINVAL;
if (!entry->bitmask) {
*total -= sizeof(struct ebt_entries);
return ebt_buf_add(state, entry, sizeof(struct ebt_entries));
}
if (*total < sizeof(*entry) || entry->next_offset < sizeof(*entry))
return -EINVAL;
startoff = state->buf_user_offset;
/* pull in most part of ebt_entry, it does not need to be changed. */
ret = ebt_buf_add(state, entry,
offsetof(struct ebt_entry, watchers_offset));
if (ret < 0)
return ret;
offsets[0] = sizeof(struct ebt_entry); /* matches come first */
memcpy(&offsets[1], &entry->watchers_offset,
sizeof(offsets) - sizeof(offsets[0]));
if (state->buf_kern_start) {
buf_start = state->buf_kern_start + state->buf_kern_offset;
offsets_update = (unsigned int *) buf_start;
}
ret = ebt_buf_add(state, &offsets[1],
sizeof(offsets) - sizeof(offsets[0]));
if (ret < 0)
return ret;
buf_start = (char *) entry;
/* 0: matches offset, always follows ebt_entry.
* 1: watchers offset, from ebt_entry structure
* 2: target offset, from ebt_entry structure
* 3: next ebt_entry offset, from ebt_entry structure
*
* offsets are relative to beginning of struct ebt_entry (i.e., 0).
*/
for (i = 0, j = 1 ; j < 4 ; j++, i++) {
struct compat_ebt_entry_mwt *match32;
unsigned int size;
char *buf = buf_start + offsets[i];
if (offsets[i] > offsets[j])
return -EINVAL;
match32 = (struct compat_ebt_entry_mwt *) buf;
size = offsets[j] - offsets[i];
ret = ebt_size_mwt(match32, size, i, state, base);
if (ret < 0)
return ret;
new_offset += ret;
if (offsets_update && new_offset) {
pr_debug("change offset %d to %d\n",
offsets_update[i], offsets[j] + new_offset);
offsets_update[i] = offsets[j] + new_offset;
}
}
if (state->buf_kern_start == NULL) {
unsigned int offset = buf_start - (char *) base;
ret = xt_compat_add_offset(NFPROTO_BRIDGE, offset, new_offset);
if (ret < 0)
return ret;
}
startoff = state->buf_user_offset - startoff;
if (WARN_ON(*total < startoff))
return -EINVAL;
*total -= startoff;
return 0;
}
/* repl->entries_size is the size of the ebt_entry blob in userspace.
* It might need more memory when copied to a 64 bit kernel in case
* userspace is 32-bit. So, first task: find out how much memory is needed.
*
* Called before validation is performed.
*/
static int compat_copy_entries(unsigned char *data, unsigned int size_user,
struct ebt_entries_buf_state *state)
{
unsigned int size_remaining = size_user;
int ret;
ret = EBT_ENTRY_ITERATE(data, size_user, size_entry_mwt, data,
&size_remaining, state);
if (ret < 0)
return ret;
WARN_ON(size_remaining);
return state->buf_kern_offset;
}
static int compat_copy_ebt_replace_from_user(struct ebt_replace *repl,
void __user *user, unsigned int len)
{
struct compat_ebt_replace tmp;
int i;
if (len < sizeof(tmp))
return -EINVAL;
if (copy_from_user(&tmp, user, sizeof(tmp)))
return -EFAULT;
if (len != sizeof(tmp) + tmp.entries_size)
return -EINVAL;
if (tmp.entries_size == 0)
return -EINVAL;
if (tmp.nentries >= ((INT_MAX - sizeof(struct ebt_table_info)) /
NR_CPUS - SMP_CACHE_BYTES) / sizeof(struct ebt_counter))
return -ENOMEM;
if (tmp.num_counters >= INT_MAX / sizeof(struct ebt_counter))
return -ENOMEM;
memcpy(repl, &tmp, offsetof(struct ebt_replace, hook_entry));
/* starting with hook_entry, 32 vs. 64 bit structures are different */
for (i = 0; i < NF_BR_NUMHOOKS; i++)
repl->hook_entry[i] = compat_ptr(tmp.hook_entry[i]);
repl->num_counters = tmp.num_counters;
repl->counters = compat_ptr(tmp.counters);
repl->entries = compat_ptr(tmp.entries);
return 0;
}
static int compat_do_replace(struct net *net, void __user *user,
unsigned int len)
{
int ret, i, countersize, size64;
struct ebt_table_info *newinfo;
struct ebt_replace tmp;
struct ebt_entries_buf_state state;
void *entries_tmp;
ret = compat_copy_ebt_replace_from_user(&tmp, user, len);
if (ret) {
/* try real handler in case userland supplied needed padding */
if (ret == -EINVAL && do_replace(net, user, len) == 0)
ret = 0;
return ret;
}
countersize = COUNTER_OFFSET(tmp.nentries) * nr_cpu_ids;
newinfo = vmalloc(sizeof(*newinfo) + countersize);
if (!newinfo)
return -ENOMEM;
if (countersize)
memset(newinfo->counters, 0, countersize);
memset(&state, 0, sizeof(state));
newinfo->entries = vmalloc(tmp.entries_size);
if (!newinfo->entries) {
ret = -ENOMEM;
goto free_newinfo;
}
if (copy_from_user(
newinfo->entries, tmp.entries, tmp.entries_size) != 0) {
ret = -EFAULT;
goto free_entries;
}
entries_tmp = newinfo->entries;
xt_compat_lock(NFPROTO_BRIDGE);
xt_compat_init_offsets(NFPROTO_BRIDGE, tmp.nentries);
ret = compat_copy_entries(entries_tmp, tmp.entries_size, &state);
if (ret < 0)
goto out_unlock;
pr_debug("tmp.entries_size %d, kern off %d, user off %d delta %d\n",
tmp.entries_size, state.buf_kern_offset, state.buf_user_offset,
xt_compat_calc_jump(NFPROTO_BRIDGE, tmp.entries_size));
size64 = ret;
newinfo->entries = vmalloc(size64);
if (!newinfo->entries) {
vfree(entries_tmp);
ret = -ENOMEM;
goto out_unlock;
}
memset(&state, 0, sizeof(state));
state.buf_kern_start = newinfo->entries;
state.buf_kern_len = size64;
ret = compat_copy_entries(entries_tmp, tmp.entries_size, &state);
if (WARN_ON(ret < 0))
goto out_unlock;
vfree(entries_tmp);
tmp.entries_size = size64;
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
char __user *usrptr;
if (tmp.hook_entry[i]) {
unsigned int delta;
usrptr = (char __user *) tmp.hook_entry[i];
delta = usrptr - tmp.entries;
usrptr += xt_compat_calc_jump(NFPROTO_BRIDGE, delta);
tmp.hook_entry[i] = (struct ebt_entries __user *)usrptr;
}
}
xt_compat_flush_offsets(NFPROTO_BRIDGE);
xt_compat_unlock(NFPROTO_BRIDGE);
ret = do_replace_finish(net, &tmp, newinfo);
if (ret == 0)
return ret;
free_entries:
vfree(newinfo->entries);
free_newinfo:
vfree(newinfo);
return ret;
out_unlock:
xt_compat_flush_offsets(NFPROTO_BRIDGE);
xt_compat_unlock(NFPROTO_BRIDGE);
goto free_entries;
}
static int compat_update_counters(struct net *net, void __user *user,
unsigned int len)
{
struct compat_ebt_replace hlp;
if (copy_from_user(&hlp, user, sizeof(hlp)))
return -EFAULT;
/* try real handler in case userland supplied needed padding */
if (len != sizeof(hlp) + hlp.num_counters * sizeof(struct ebt_counter))
return update_counters(net, user, len);
return do_update_counters(net, hlp.name, compat_ptr(hlp.counters),
hlp.num_counters, user, len);
}
static int compat_do_ebt_set_ctl(struct sock *sk,
int cmd, void __user *user, unsigned int len)
{
int ret;
struct net *net = sock_net(sk);
if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
return -EPERM;
switch (cmd) {
case EBT_SO_SET_ENTRIES:
ret = compat_do_replace(net, user, len);
break;
case EBT_SO_SET_COUNTERS:
ret = compat_update_counters(net, user, len);
break;
default:
ret = -EINVAL;
}
return ret;
}
static int compat_do_ebt_get_ctl(struct sock *sk, int cmd,
void __user *user, int *len)
{
int ret;
struct compat_ebt_replace tmp;
struct ebt_table *t;
struct net *net = sock_net(sk);
if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
return -EPERM;
/* try real handler in case userland supplied needed padding */
if ((cmd == EBT_SO_GET_INFO ||
cmd == EBT_SO_GET_INIT_INFO) && *len != sizeof(tmp))
return do_ebt_get_ctl(sk, cmd, user, len);
if (copy_from_user(&tmp, user, sizeof(tmp)))
return -EFAULT;
tmp.name[sizeof(tmp.name) - 1] = '\0';
t = find_table_lock(net, tmp.name, &ret, &ebt_mutex);
if (!t)
return ret;
xt_compat_lock(NFPROTO_BRIDGE);
switch (cmd) {
case EBT_SO_GET_INFO:
tmp.nentries = t->private->nentries;
ret = compat_table_info(t->private, &tmp);
if (ret)
goto out;
tmp.valid_hooks = t->valid_hooks;
if (copy_to_user(user, &tmp, *len) != 0) {
ret = -EFAULT;
break;
}
ret = 0;
break;
case EBT_SO_GET_INIT_INFO:
tmp.nentries = t->table->nentries;
tmp.entries_size = t->table->entries_size;
tmp.valid_hooks = t->table->valid_hooks;
if (copy_to_user(user, &tmp, *len) != 0) {
ret = -EFAULT;
break;
}
ret = 0;
break;
case EBT_SO_GET_ENTRIES:
case EBT_SO_GET_INIT_ENTRIES:
/* try real handler first in case of userland-side padding.
* in case we are dealing with an 'ordinary' 32 bit binary
* without 64bit compatibility padding, this will fail right
* after copy_from_user when the *len argument is validated.
*
* the compat_ variant needs to do one pass over the kernel
* data set to adjust for size differences before it the check.
*/
if (copy_everything_to_user(t, user, len, cmd) == 0)
ret = 0;
else
ret = compat_copy_everything_to_user(t, user, len, cmd);
break;
default:
ret = -EINVAL;
}
out:
xt_compat_flush_offsets(NFPROTO_BRIDGE);
xt_compat_unlock(NFPROTO_BRIDGE);
mutex_unlock(&ebt_mutex);
return ret;
}
#endif
static struct nf_sockopt_ops ebt_sockopts = {
.pf = PF_INET,
.set_optmin = EBT_BASE_CTL,
.set_optmax = EBT_SO_SET_MAX + 1,
.set = do_ebt_set_ctl,
#ifdef CONFIG_COMPAT
.compat_set = compat_do_ebt_set_ctl,
#endif
.get_optmin = EBT_BASE_CTL,
.get_optmax = EBT_SO_GET_MAX + 1,
.get = do_ebt_get_ctl,
#ifdef CONFIG_COMPAT
.compat_get = compat_do_ebt_get_ctl,
#endif
.owner = THIS_MODULE,
};
static int __init ebtables_init(void)
{
int ret;
ret = xt_register_target(&ebt_standard_target);
if (ret < 0)
return ret;
ret = nf_register_sockopt(&ebt_sockopts);
if (ret < 0) {
xt_unregister_target(&ebt_standard_target);
return ret;
}
return 0;
}
static void __exit ebtables_fini(void)
{
nf_unregister_sockopt(&ebt_sockopts);
xt_unregister_target(&ebt_standard_target);
}
EXPORT_SYMBOL(ebt_register_table);
EXPORT_SYMBOL(ebt_unregister_table);
EXPORT_SYMBOL(ebt_do_table);
module_init(ebtables_init);
module_exit(ebtables_fini);
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_106_0 |
crossvul-cpp_data_bad_5474_2 | /* $Id$ */
/*
* Copyright (c) 1988-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.
*
* Scanline-oriented Write Support
*/
#include "tiffiop.h"
#include <stdio.h>
#define STRIPINCR 20 /* expansion factor on strip array */
#define WRITECHECKSTRIPS(tif, module) \
(((tif)->tif_flags&TIFF_BEENWRITING) || TIFFWriteCheck((tif),0,module))
#define WRITECHECKTILES(tif, module) \
(((tif)->tif_flags&TIFF_BEENWRITING) || TIFFWriteCheck((tif),1,module))
#define BUFFERCHECK(tif) \
((((tif)->tif_flags & TIFF_BUFFERSETUP) && tif->tif_rawdata) || \
TIFFWriteBufferSetup((tif), NULL, (tmsize_t) -1))
static int TIFFGrowStrips(TIFF* tif, uint32 delta, const char* module);
static int TIFFAppendToStrip(TIFF* tif, uint32 strip, uint8* data, tmsize_t cc);
int
TIFFWriteScanline(TIFF* tif, void* buf, uint32 row, uint16 sample)
{
static const char module[] = "TIFFWriteScanline";
register TIFFDirectory *td;
int status, imagegrew = 0;
uint32 strip;
if (!WRITECHECKSTRIPS(tif, module))
return (-1);
/*
* Handle delayed allocation of data buffer. This
* permits it to be sized more intelligently (using
* directory information).
*/
if (!BUFFERCHECK(tif))
return (-1);
tif->tif_flags |= TIFF_BUF4WRITE; /* not strictly sure this is right*/
td = &tif->tif_dir;
/*
* Extend image length if needed
* (but only for PlanarConfig=1).
*/
if (row >= td->td_imagelength) { /* extend image */
if (td->td_planarconfig == PLANARCONFIG_SEPARATE) {
TIFFErrorExt(tif->tif_clientdata, module,
"Can not change \"ImageLength\" when using separate planes");
return (-1);
}
td->td_imagelength = row+1;
imagegrew = 1;
}
/*
* Calculate strip and check for crossings.
*/
if (td->td_planarconfig == PLANARCONFIG_SEPARATE) {
if (sample >= td->td_samplesperpixel) {
TIFFErrorExt(tif->tif_clientdata, module,
"%lu: Sample out of range, max %lu",
(unsigned long) sample, (unsigned long) td->td_samplesperpixel);
return (-1);
}
strip = sample*td->td_stripsperimage + row/td->td_rowsperstrip;
} else
strip = row / td->td_rowsperstrip;
/*
* Check strip array to make sure there's space. We don't support
* dynamically growing files that have data organized in separate
* bitplanes because it's too painful. In that case we require that
* the imagelength be set properly before the first write (so that the
* strips array will be fully allocated above).
*/
if (strip >= td->td_nstrips && !TIFFGrowStrips(tif, 1, module))
return (-1);
if (strip != tif->tif_curstrip) {
/*
* Changing strips -- flush any data present.
*/
if (!TIFFFlushData(tif))
return (-1);
tif->tif_curstrip = strip;
/*
* Watch out for a growing image. The value of strips/image
* will initially be 1 (since it can't be deduced until the
* imagelength is known).
*/
if (strip >= td->td_stripsperimage && imagegrew)
td->td_stripsperimage =
TIFFhowmany_32(td->td_imagelength,td->td_rowsperstrip);
if (td->td_stripsperimage == 0) {
TIFFErrorExt(tif->tif_clientdata, module, "Zero strips per image");
return (-1);
}
tif->tif_row =
(strip % td->td_stripsperimage) * td->td_rowsperstrip;
if ((tif->tif_flags & TIFF_CODERSETUP) == 0) {
if (!(*tif->tif_setupencode)(tif))
return (-1);
tif->tif_flags |= TIFF_CODERSETUP;
}
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
if( td->td_stripbytecount[strip] > 0 )
{
/* if we are writing over existing tiles, zero length */
td->td_stripbytecount[strip] = 0;
/* this forces TIFFAppendToStrip() to do a seek */
tif->tif_curoff = 0;
}
if (!(*tif->tif_preencode)(tif, sample))
return (-1);
tif->tif_flags |= TIFF_POSTENCODE;
}
/*
* Ensure the write is either sequential or at the
* beginning of a strip (or that we can randomly
* access the data -- i.e. no encoding).
*/
if (row != tif->tif_row) {
if (row < tif->tif_row) {
/*
* Moving backwards within the same strip:
* backup to the start and then decode
* forward (below).
*/
tif->tif_row = (strip % td->td_stripsperimage) *
td->td_rowsperstrip;
tif->tif_rawcp = tif->tif_rawdata;
}
/*
* Seek forward to the desired row.
*/
if (!(*tif->tif_seek)(tif, row - tif->tif_row))
return (-1);
tif->tif_row = row;
}
/* swab if needed - note that source buffer will be altered */
tif->tif_postdecode( tif, (uint8*) buf, tif->tif_scanlinesize );
status = (*tif->tif_encoderow)(tif, (uint8*) buf,
tif->tif_scanlinesize, sample);
/* we are now poised at the beginning of the next row */
tif->tif_row = row + 1;
return (status);
}
/*
* Encode the supplied data and write it to the
* specified strip.
*
* NB: Image length must be setup before writing.
*/
tmsize_t
TIFFWriteEncodedStrip(TIFF* tif, uint32 strip, void* data, tmsize_t cc)
{
static const char module[] = "TIFFWriteEncodedStrip";
TIFFDirectory *td = &tif->tif_dir;
uint16 sample;
if (!WRITECHECKSTRIPS(tif, module))
return ((tmsize_t) -1);
/*
* Check strip array to make sure there's space.
* We don't support dynamically growing files that
* have data organized in separate bitplanes because
* it's too painful. In that case we require that
* the imagelength be set properly before the first
* write (so that the strips array will be fully
* allocated above).
*/
if (strip >= td->td_nstrips) {
if (td->td_planarconfig == PLANARCONFIG_SEPARATE) {
TIFFErrorExt(tif->tif_clientdata, module,
"Can not grow image by strips when using separate planes");
return ((tmsize_t) -1);
}
if (!TIFFGrowStrips(tif, 1, module))
return ((tmsize_t) -1);
td->td_stripsperimage =
TIFFhowmany_32(td->td_imagelength, td->td_rowsperstrip);
}
/*
* Handle delayed allocation of data buffer. This
* permits it to be sized according to the directory
* info.
*/
if (!BUFFERCHECK(tif))
return ((tmsize_t) -1);
tif->tif_flags |= TIFF_BUF4WRITE;
tif->tif_curstrip = strip;
if (td->td_stripsperimage == 0) {
TIFFErrorExt(tif->tif_clientdata, module, "Zero strips per image");
return ((tmsize_t) -1);
}
tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip;
if ((tif->tif_flags & TIFF_CODERSETUP) == 0) {
if (!(*tif->tif_setupencode)(tif))
return ((tmsize_t) -1);
tif->tif_flags |= TIFF_CODERSETUP;
}
if( td->td_stripbytecount[strip] > 0 )
{
/* Make sure that at the first attempt of rewriting the tile, we will have */
/* more bytes available in the output buffer than the previous byte count, */
/* so that TIFFAppendToStrip() will detect the overflow when it is called the first */
/* time if the new compressed tile is bigger than the older one. (GDAL #4771) */
if( tif->tif_rawdatasize <= (tmsize_t)td->td_stripbytecount[strip] )
{
if( !(TIFFWriteBufferSetup(tif, NULL,
(tmsize_t)TIFFroundup_64((uint64)(td->td_stripbytecount[strip] + 1), 1024))) )
return ((tmsize_t)(-1));
}
/* Force TIFFAppendToStrip() to consider placing data at end
of file. */
tif->tif_curoff = 0;
}
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
tif->tif_flags &= ~TIFF_POSTENCODE;
/* shortcut to avoid an extra memcpy() */
if( td->td_compression == COMPRESSION_NONE )
{
/* swab if needed - note that source buffer will be altered */
tif->tif_postdecode( tif, (uint8*) data, cc );
if (!isFillOrder(tif, td->td_fillorder) &&
(tif->tif_flags & TIFF_NOBITREV) == 0)
TIFFReverseBits((uint8*) data, cc);
if (cc > 0 &&
!TIFFAppendToStrip(tif, strip, (uint8*) data, cc))
return ((tmsize_t) -1);
return (cc);
}
sample = (uint16)(strip / td->td_stripsperimage);
if (!(*tif->tif_preencode)(tif, sample))
return ((tmsize_t) -1);
/* swab if needed - note that source buffer will be altered */
tif->tif_postdecode( tif, (uint8*) data, cc );
if (!(*tif->tif_encodestrip)(tif, (uint8*) data, cc, sample))
return ((tmsize_t) -1);
if (!(*tif->tif_postencode)(tif))
return ((tmsize_t) -1);
if (!isFillOrder(tif, td->td_fillorder) &&
(tif->tif_flags & TIFF_NOBITREV) == 0)
TIFFReverseBits(tif->tif_rawdata, tif->tif_rawcc);
if (tif->tif_rawcc > 0 &&
!TIFFAppendToStrip(tif, strip, tif->tif_rawdata, tif->tif_rawcc))
return ((tmsize_t) -1);
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
return (cc);
}
/*
* Write the supplied data to the specified strip.
*
* NB: Image length must be setup before writing.
*/
tmsize_t
TIFFWriteRawStrip(TIFF* tif, uint32 strip, void* data, tmsize_t cc)
{
static const char module[] = "TIFFWriteRawStrip";
TIFFDirectory *td = &tif->tif_dir;
if (!WRITECHECKSTRIPS(tif, module))
return ((tmsize_t) -1);
/*
* Check strip array to make sure there's space.
* We don't support dynamically growing files that
* have data organized in separate bitplanes because
* it's too painful. In that case we require that
* the imagelength be set properly before the first
* write (so that the strips array will be fully
* allocated above).
*/
if (strip >= td->td_nstrips) {
if (td->td_planarconfig == PLANARCONFIG_SEPARATE) {
TIFFErrorExt(tif->tif_clientdata, module,
"Can not grow image by strips when using separate planes");
return ((tmsize_t) -1);
}
/*
* Watch out for a growing image. The value of
* strips/image will initially be 1 (since it
* can't be deduced until the imagelength is known).
*/
if (strip >= td->td_stripsperimage)
td->td_stripsperimage =
TIFFhowmany_32(td->td_imagelength,td->td_rowsperstrip);
if (!TIFFGrowStrips(tif, 1, module))
return ((tmsize_t) -1);
}
tif->tif_curstrip = strip;
if (td->td_stripsperimage == 0) {
TIFFErrorExt(tif->tif_clientdata, module,"Zero strips per image");
return ((tmsize_t) -1);
}
tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip;
return (TIFFAppendToStrip(tif, strip, (uint8*) data, cc) ?
cc : (tmsize_t) -1);
}
/*
* Write and compress a tile of data. The
* tile is selected by the (x,y,z,s) coordinates.
*/
tmsize_t
TIFFWriteTile(TIFF* tif, void* buf, uint32 x, uint32 y, uint32 z, uint16 s)
{
if (!TIFFCheckTile(tif, x, y, z, s))
return ((tmsize_t)(-1));
/*
* NB: A tile size of -1 is used instead of tif_tilesize knowing
* that TIFFWriteEncodedTile will clamp this to the tile size.
* This is done because the tile size may not be defined until
* after the output buffer is setup in TIFFWriteBufferSetup.
*/
return (TIFFWriteEncodedTile(tif,
TIFFComputeTile(tif, x, y, z, s), buf, (tmsize_t)(-1)));
}
/*
* Encode the supplied data and write it to the
* specified tile. There must be space for the
* data. The function clamps individual writes
* to a tile to the tile size, but does not (and
* can not) check that multiple writes to the same
* tile do not write more than tile size data.
*
* NB: Image length must be setup before writing; this
* interface does not support automatically growing
* the image on each write (as TIFFWriteScanline does).
*/
tmsize_t
TIFFWriteEncodedTile(TIFF* tif, uint32 tile, void* data, tmsize_t cc)
{
static const char module[] = "TIFFWriteEncodedTile";
TIFFDirectory *td;
uint16 sample;
uint32 howmany32;
if (!WRITECHECKTILES(tif, module))
return ((tmsize_t)(-1));
td = &tif->tif_dir;
if (tile >= td->td_nstrips) {
TIFFErrorExt(tif->tif_clientdata, module, "Tile %lu out of range, max %lu",
(unsigned long) tile, (unsigned long) td->td_nstrips);
return ((tmsize_t)(-1));
}
/*
* Handle delayed allocation of data buffer. This
* permits it to be sized more intelligently (using
* directory information).
*/
if (!BUFFERCHECK(tif))
return ((tmsize_t)(-1));
tif->tif_flags |= TIFF_BUF4WRITE;
tif->tif_curtile = tile;
if( td->td_stripbytecount[tile] > 0 )
{
/* Make sure that at the first attempt of rewriting the tile, we will have */
/* more bytes available in the output buffer than the previous byte count, */
/* so that TIFFAppendToStrip() will detect the overflow when it is called the first */
/* time if the new compressed tile is bigger than the older one. (GDAL #4771) */
if( tif->tif_rawdatasize <= (tmsize_t) td->td_stripbytecount[tile] )
{
if( !(TIFFWriteBufferSetup(tif, NULL,
(tmsize_t)TIFFroundup_64((uint64)(td->td_stripbytecount[tile] + 1), 1024))) )
return ((tmsize_t)(-1));
}
/* Force TIFFAppendToStrip() to consider placing data at end
of file. */
tif->tif_curoff = 0;
}
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
/*
* Compute tiles per row & per column to compute
* current row and column
*/
howmany32=TIFFhowmany_32(td->td_imagelength, td->td_tilelength);
if (howmany32 == 0) {
TIFFErrorExt(tif->tif_clientdata,module,"Zero tiles");
return ((tmsize_t)(-1));
}
tif->tif_row = (tile % howmany32) * td->td_tilelength;
howmany32=TIFFhowmany_32(td->td_imagewidth, td->td_tilewidth);
if (howmany32 == 0) {
TIFFErrorExt(tif->tif_clientdata,module,"Zero tiles");
return ((tmsize_t)(-1));
}
tif->tif_col = (tile % howmany32) * td->td_tilewidth;
if ((tif->tif_flags & TIFF_CODERSETUP) == 0) {
if (!(*tif->tif_setupencode)(tif))
return ((tmsize_t)(-1));
tif->tif_flags |= TIFF_CODERSETUP;
}
tif->tif_flags &= ~TIFF_POSTENCODE;
/*
* Clamp write amount to the tile size. This is mostly
* done so that callers can pass in some large number
* (e.g. -1) and have the tile size used instead.
*/
if ( cc < 1 || cc > tif->tif_tilesize)
cc = tif->tif_tilesize;
/* shortcut to avoid an extra memcpy() */
if( td->td_compression == COMPRESSION_NONE )
{
/* swab if needed - note that source buffer will be altered */
tif->tif_postdecode( tif, (uint8*) data, cc );
if (!isFillOrder(tif, td->td_fillorder) &&
(tif->tif_flags & TIFF_NOBITREV) == 0)
TIFFReverseBits((uint8*) data, cc);
if (cc > 0 &&
!TIFFAppendToStrip(tif, tile, (uint8*) data, cc))
return ((tmsize_t) -1);
return (cc);
}
sample = (uint16)(tile/td->td_stripsperimage);
if (!(*tif->tif_preencode)(tif, sample))
return ((tmsize_t)(-1));
/* swab if needed - note that source buffer will be altered */
tif->tif_postdecode( tif, (uint8*) data, cc );
if (!(*tif->tif_encodetile)(tif, (uint8*) data, cc, sample))
return ((tmsize_t) -1);
if (!(*tif->tif_postencode)(tif))
return ((tmsize_t)(-1));
if (!isFillOrder(tif, td->td_fillorder) &&
(tif->tif_flags & TIFF_NOBITREV) == 0)
TIFFReverseBits((uint8*)tif->tif_rawdata, tif->tif_rawcc);
if (tif->tif_rawcc > 0 && !TIFFAppendToStrip(tif, tile,
tif->tif_rawdata, tif->tif_rawcc))
return ((tmsize_t)(-1));
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
return (cc);
}
/*
* Write the supplied data to the specified strip.
* There must be space for the data; we don't check
* if strips overlap!
*
* NB: Image length must be setup before writing; this
* interface does not support automatically growing
* the image on each write (as TIFFWriteScanline does).
*/
tmsize_t
TIFFWriteRawTile(TIFF* tif, uint32 tile, void* data, tmsize_t cc)
{
static const char module[] = "TIFFWriteRawTile";
if (!WRITECHECKTILES(tif, module))
return ((tmsize_t)(-1));
if (tile >= tif->tif_dir.td_nstrips) {
TIFFErrorExt(tif->tif_clientdata, module, "Tile %lu out of range, max %lu",
(unsigned long) tile,
(unsigned long) tif->tif_dir.td_nstrips);
return ((tmsize_t)(-1));
}
return (TIFFAppendToStrip(tif, tile, (uint8*) data, cc) ?
cc : (tmsize_t)(-1));
}
#define isUnspecified(tif, f) \
(TIFFFieldSet(tif,f) && (tif)->tif_dir.td_imagelength == 0)
int
TIFFSetupStrips(TIFF* tif)
{
TIFFDirectory* td = &tif->tif_dir;
if (isTiled(tif))
td->td_stripsperimage =
isUnspecified(tif, FIELD_TILEDIMENSIONS) ?
td->td_samplesperpixel : TIFFNumberOfTiles(tif);
else
td->td_stripsperimage =
isUnspecified(tif, FIELD_ROWSPERSTRIP) ?
td->td_samplesperpixel : TIFFNumberOfStrips(tif);
td->td_nstrips = td->td_stripsperimage;
if (td->td_planarconfig == PLANARCONFIG_SEPARATE)
td->td_stripsperimage /= td->td_samplesperpixel;
td->td_stripoffset = (uint64 *)
_TIFFmalloc(td->td_nstrips * sizeof (uint64));
td->td_stripbytecount = (uint64 *)
_TIFFmalloc(td->td_nstrips * sizeof (uint64));
if (td->td_stripoffset == NULL || td->td_stripbytecount == NULL)
return (0);
/*
* Place data at the end-of-file
* (by setting offsets to zero).
*/
_TIFFmemset(td->td_stripoffset, 0, td->td_nstrips*sizeof (uint64));
_TIFFmemset(td->td_stripbytecount, 0, td->td_nstrips*sizeof (uint64));
TIFFSetFieldBit(tif, FIELD_STRIPOFFSETS);
TIFFSetFieldBit(tif, FIELD_STRIPBYTECOUNTS);
return (1);
}
#undef isUnspecified
/*
* Verify file is writable and that the directory
* information is setup properly. In doing the latter
* we also "freeze" the state of the directory so
* that important information is not changed.
*/
int
TIFFWriteCheck(TIFF* tif, int tiles, const char* module)
{
if (tif->tif_mode == O_RDONLY) {
TIFFErrorExt(tif->tif_clientdata, module, "File not open for writing");
return (0);
}
if (tiles ^ isTiled(tif)) {
TIFFErrorExt(tif->tif_clientdata, module, tiles ?
"Can not write tiles to a stripped image" :
"Can not write scanlines to a tiled image");
return (0);
}
_TIFFFillStriles( tif );
/*
* On the first write verify all the required information
* has been setup and initialize any data structures that
* had to wait until directory information was set.
* Note that a lot of our work is assumed to remain valid
* because we disallow any of the important parameters
* from changing after we start writing (i.e. once
* TIFF_BEENWRITING is set, TIFFSetField will only allow
* the image's length to be changed).
*/
if (!TIFFFieldSet(tif, FIELD_IMAGEDIMENSIONS)) {
TIFFErrorExt(tif->tif_clientdata, module,
"Must set \"ImageWidth\" before writing data");
return (0);
}
if (tif->tif_dir.td_samplesperpixel == 1) {
/*
* Planarconfiguration is irrelevant in case of single band
* images and need not be included. We will set it anyway,
* because this field is used in other parts of library even
* in the single band case.
*/
if (!TIFFFieldSet(tif, FIELD_PLANARCONFIG))
tif->tif_dir.td_planarconfig = PLANARCONFIG_CONTIG;
} else {
if (!TIFFFieldSet(tif, FIELD_PLANARCONFIG)) {
TIFFErrorExt(tif->tif_clientdata, module,
"Must set \"PlanarConfiguration\" before writing data");
return (0);
}
}
if (tif->tif_dir.td_stripoffset == NULL && !TIFFSetupStrips(tif)) {
tif->tif_dir.td_nstrips = 0;
TIFFErrorExt(tif->tif_clientdata, module, "No space for %s arrays",
isTiled(tif) ? "tile" : "strip");
return (0);
}
if (isTiled(tif))
{
tif->tif_tilesize = TIFFTileSize(tif);
if (tif->tif_tilesize == 0)
return (0);
}
else
tif->tif_tilesize = (tmsize_t)(-1);
tif->tif_scanlinesize = TIFFScanlineSize(tif);
if (tif->tif_scanlinesize == 0)
return (0);
tif->tif_flags |= TIFF_BEENWRITING;
return (1);
}
/*
* Setup the raw data buffer used for encoding.
*/
int
TIFFWriteBufferSetup(TIFF* tif, void* bp, tmsize_t size)
{
static const char module[] = "TIFFWriteBufferSetup";
if (tif->tif_rawdata) {
if (tif->tif_flags & TIFF_MYBUFFER) {
_TIFFfree(tif->tif_rawdata);
tif->tif_flags &= ~TIFF_MYBUFFER;
}
tif->tif_rawdata = NULL;
}
if (size == (tmsize_t)(-1)) {
size = (isTiled(tif) ?
tif->tif_tilesize : TIFFStripSize(tif));
/*
* Make raw data buffer at least 8K
*/
if (size < 8*1024)
size = 8*1024;
bp = NULL; /* NB: force malloc */
}
if (bp == NULL) {
bp = _TIFFmalloc(size);
if (bp == NULL) {
TIFFErrorExt(tif->tif_clientdata, module, "No space for output buffer");
return (0);
}
tif->tif_flags |= TIFF_MYBUFFER;
} else
tif->tif_flags &= ~TIFF_MYBUFFER;
tif->tif_rawdata = (uint8*) bp;
tif->tif_rawdatasize = size;
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
tif->tif_flags |= TIFF_BUFFERSETUP;
return (1);
}
/*
* Grow the strip data structures by delta strips.
*/
static int
TIFFGrowStrips(TIFF* tif, uint32 delta, const char* module)
{
TIFFDirectory *td = &tif->tif_dir;
uint64* new_stripoffset;
uint64* new_stripbytecount;
assert(td->td_planarconfig == PLANARCONFIG_CONTIG);
new_stripoffset = (uint64*)_TIFFrealloc(td->td_stripoffset,
(td->td_nstrips + delta) * sizeof (uint64));
new_stripbytecount = (uint64*)_TIFFrealloc(td->td_stripbytecount,
(td->td_nstrips + delta) * sizeof (uint64));
if (new_stripoffset == NULL || new_stripbytecount == NULL) {
if (new_stripoffset)
_TIFFfree(new_stripoffset);
if (new_stripbytecount)
_TIFFfree(new_stripbytecount);
td->td_nstrips = 0;
TIFFErrorExt(tif->tif_clientdata, module, "No space to expand strip arrays");
return (0);
}
td->td_stripoffset = new_stripoffset;
td->td_stripbytecount = new_stripbytecount;
_TIFFmemset(td->td_stripoffset + td->td_nstrips,
0, delta*sizeof (uint64));
_TIFFmemset(td->td_stripbytecount + td->td_nstrips,
0, delta*sizeof (uint64));
td->td_nstrips += delta;
tif->tif_flags |= TIFF_DIRTYDIRECT;
return (1);
}
/*
* Append the data to the specified strip.
*/
static int
TIFFAppendToStrip(TIFF* tif, uint32 strip, uint8* data, tmsize_t cc)
{
static const char module[] = "TIFFAppendToStrip";
TIFFDirectory *td = &tif->tif_dir;
uint64 m;
int64 old_byte_count = -1;
if (td->td_stripoffset[strip] == 0 || tif->tif_curoff == 0) {
assert(td->td_nstrips > 0);
if( td->td_stripbytecount[strip] != 0
&& td->td_stripoffset[strip] != 0
&& td->td_stripbytecount[strip] >= (uint64) cc )
{
/*
* There is already tile data on disk, and the new tile
* data we have will fit in the same space. The only
* aspect of this that is risky is that there could be
* more data to append to this strip before we are done
* depending on how we are getting called.
*/
if (!SeekOK(tif, td->td_stripoffset[strip])) {
TIFFErrorExt(tif->tif_clientdata, module,
"Seek error at scanline %lu",
(unsigned long)tif->tif_row);
return (0);
}
}
else
{
/*
* Seek to end of file, and set that as our location to
* write this strip.
*/
td->td_stripoffset[strip] = TIFFSeekFile(tif, 0, SEEK_END);
tif->tif_flags |= TIFF_DIRTYSTRIP;
}
tif->tif_curoff = td->td_stripoffset[strip];
/*
* We are starting a fresh strip/tile, so set the size to zero.
*/
old_byte_count = td->td_stripbytecount[strip];
td->td_stripbytecount[strip] = 0;
}
m = tif->tif_curoff+cc;
if (!(tif->tif_flags&TIFF_BIGTIFF))
m = (uint32)m;
if ((m<tif->tif_curoff)||(m<(uint64)cc))
{
TIFFErrorExt(tif->tif_clientdata, module, "Maximum TIFF file size exceeded");
return (0);
}
if (!WriteOK(tif, data, cc)) {
TIFFErrorExt(tif->tif_clientdata, module, "Write error at scanline %lu",
(unsigned long) tif->tif_row);
return (0);
}
tif->tif_curoff = m;
td->td_stripbytecount[strip] += cc;
if( (int64) td->td_stripbytecount[strip] != old_byte_count )
tif->tif_flags |= TIFF_DIRTYSTRIP;
return (1);
}
/*
* Internal version of TIFFFlushData that can be
* called by ``encodestrip routines'' w/o concern
* for infinite recursion.
*/
int
TIFFFlushData1(TIFF* tif)
{
if (tif->tif_rawcc > 0 && tif->tif_flags & TIFF_BUF4WRITE ) {
if (!isFillOrder(tif, tif->tif_dir.td_fillorder) &&
(tif->tif_flags & TIFF_NOBITREV) == 0)
TIFFReverseBits((uint8*)tif->tif_rawdata,
tif->tif_rawcc);
if (!TIFFAppendToStrip(tif,
isTiled(tif) ? tif->tif_curtile : tif->tif_curstrip,
tif->tif_rawdata, tif->tif_rawcc))
return (0);
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
}
return (1);
}
/*
* Set the current write offset. This should only be
* used to set the offset to a known previous location
* (very carefully), or to 0 so that the next write gets
* appended to the end of the file.
*/
void
TIFFSetWriteOffset(TIFF* tif, toff_t off)
{
tif->tif_curoff = off;
}
/* 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-787/c/bad_5474_2 |
crossvul-cpp_data_good_5304_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% W W PPPP GGGG %
% W W P P G %
% W W W PPPP G GGG %
% WW WW P G G %
% W W P GGG %
% %
% %
% Read WordPerfect Image Format %
% %
% Software Design %
% Jaroslav Fojtik %
% June 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 "magick/studio.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/colormap-private.h"
#include "magick/constitute.h"
#include "magick/distort.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/cache.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magic.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/pixel-accessor.h"
#include "magick/quantum-private.h"
#include "magick/resource_.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"
#include "magick/transform.h"
#include "magick/utility.h"
#include "magick/utility-private.h"
typedef struct
{
unsigned char Red;
unsigned char Blue;
unsigned char Green;
} RGB_Record;
/* Default palette for WPG level 1 */
static const RGB_Record WPG1_Palette[256]={
{ 0, 0, 0}, { 0, 0,168},
{ 0,168, 0}, { 0,168,168},
{168, 0, 0}, {168, 0,168},
{168, 84, 0}, {168,168,168},
{ 84, 84, 84}, { 84, 84,252},
{ 84,252, 84}, { 84,252,252},
{252, 84, 84}, {252, 84,252},
{252,252, 84}, {252,252,252}, /*16*/
{ 0, 0, 0}, { 20, 20, 20},
{ 32, 32, 32}, { 44, 44, 44},
{ 56, 56, 56}, { 68, 68, 68},
{ 80, 80, 80}, { 96, 96, 96},
{112,112,112}, {128,128,128},
{144,144,144}, {160,160,160},
{180,180,180}, {200,200,200},
{224,224,224}, {252,252,252}, /*32*/
{ 0, 0,252}, { 64, 0,252},
{124, 0,252}, {188, 0,252},
{252, 0,252}, {252, 0,188},
{252, 0,124}, {252, 0, 64},
{252, 0, 0}, {252, 64, 0},
{252,124, 0}, {252,188, 0},
{252,252, 0}, {188,252, 0},
{124,252, 0}, { 64,252, 0}, /*48*/
{ 0,252, 0}, { 0,252, 64},
{ 0,252,124}, { 0,252,188},
{ 0,252,252}, { 0,188,252},
{ 0,124,252}, { 0, 64,252},
{124,124,252}, {156,124,252},
{188,124,252}, {220,124,252},
{252,124,252}, {252,124,220},
{252,124,188}, {252,124,156}, /*64*/
{252,124,124}, {252,156,124},
{252,188,124}, {252,220,124},
{252,252,124}, {220,252,124},
{188,252,124}, {156,252,124},
{124,252,124}, {124,252,156},
{124,252,188}, {124,252,220},
{124,252,252}, {124,220,252},
{124,188,252}, {124,156,252}, /*80*/
{180,180,252}, {196,180,252},
{216,180,252}, {232,180,252},
{252,180,252}, {252,180,232},
{252,180,216}, {252,180,196},
{252,180,180}, {252,196,180},
{252,216,180}, {252,232,180},
{252,252,180}, {232,252,180},
{216,252,180}, {196,252,180}, /*96*/
{180,220,180}, {180,252,196},
{180,252,216}, {180,252,232},
{180,252,252}, {180,232,252},
{180,216,252}, {180,196,252},
{0,0,112}, {28,0,112},
{56,0,112}, {84,0,112},
{112,0,112}, {112,0,84},
{112,0,56}, {112,0,28}, /*112*/
{112,0,0}, {112,28,0},
{112,56,0}, {112,84,0},
{112,112,0}, {84,112,0},
{56,112,0}, {28,112,0},
{0,112,0}, {0,112,28},
{0,112,56}, {0,112,84},
{0,112,112}, {0,84,112},
{0,56,112}, {0,28,112}, /*128*/
{56,56,112}, {68,56,112},
{84,56,112}, {96,56,112},
{112,56,112}, {112,56,96},
{112,56,84}, {112,56,68},
{112,56,56}, {112,68,56},
{112,84,56}, {112,96,56},
{112,112,56}, {96,112,56},
{84,112,56}, {68,112,56}, /*144*/
{56,112,56}, {56,112,69},
{56,112,84}, {56,112,96},
{56,112,112}, {56,96,112},
{56,84,112}, {56,68,112},
{80,80,112}, {88,80,112},
{96,80,112}, {104,80,112},
{112,80,112}, {112,80,104},
{112,80,96}, {112,80,88}, /*160*/
{112,80,80}, {112,88,80},
{112,96,80}, {112,104,80},
{112,112,80}, {104,112,80},
{96,112,80}, {88,112,80},
{80,112,80}, {80,112,88},
{80,112,96}, {80,112,104},
{80,112,112}, {80,114,112},
{80,96,112}, {80,88,112}, /*176*/
{0,0,64}, {16,0,64},
{32,0,64}, {48,0,64},
{64,0,64}, {64,0,48},
{64,0,32}, {64,0,16},
{64,0,0}, {64,16,0},
{64,32,0}, {64,48,0},
{64,64,0}, {48,64,0},
{32,64,0}, {16,64,0}, /*192*/
{0,64,0}, {0,64,16},
{0,64,32}, {0,64,48},
{0,64,64}, {0,48,64},
{0,32,64}, {0,16,64},
{32,32,64}, {40,32,64},
{48,32,64}, {56,32,64},
{64,32,64}, {64,32,56},
{64,32,48}, {64,32,40}, /*208*/
{64,32,32}, {64,40,32},
{64,48,32}, {64,56,32},
{64,64,32}, {56,64,32},
{48,64,32}, {40,64,32},
{32,64,32}, {32,64,40},
{32,64,48}, {32,64,56},
{32,64,64}, {32,56,64},
{32,48,64}, {32,40,64}, /*224*/
{44,44,64}, {48,44,64},
{52,44,64}, {60,44,64},
{64,44,64}, {64,44,60},
{64,44,52}, {64,44,48},
{64,44,44}, {64,48,44},
{64,52,44}, {64,60,44},
{64,64,44}, {60,64,44},
{52,64,44}, {48,64,44}, /*240*/
{44,64,44}, {44,64,48},
{44,64,52}, {44,64,60},
{44,64,64}, {44,60,64},
{44,55,64}, {44,48,64},
{0,0,0}, {0,0,0},
{0,0,0}, {0,0,0},
{0,0,0}, {0,0,0},
{0,0,0}, {0,0,0} /*256*/
};
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s W P G %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsWPG() returns True if the image format type, identified by the magick
% string, is WPG.
%
% The format of the IsWPG method is:
%
% unsigned int IsWPG(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o status: Method IsWPG returns True if the image format type is WPG.
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static unsigned int IsWPG(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (memcmp(magick,"\377WPC",4) == 0)
return(MagickTrue);
return(MagickFalse);
}
static void Rd_WP_DWORD(Image *image,size_t *d)
{
unsigned char
b;
b=ReadBlobByte(image);
*d=b;
if (b < 0xFFU)
return;
b=ReadBlobByte(image);
*d=(size_t) b;
b=ReadBlobByte(image);
*d+=(size_t) b*256l;
if (*d < 0x8000)
return;
*d=(*d & 0x7FFF) << 16;
b=ReadBlobByte(image);
*d+=(size_t) b;
b=ReadBlobByte(image);
*d+=(size_t) b*256l;
return;
}
static void InsertRow(unsigned char *p,ssize_t y,Image *image, int bpp)
{
ExceptionInfo
*exception;
int
bit;
ssize_t
x;
register PixelPacket
*q;
IndexPacket
index;
register IndexPacket
*indexes;
exception=(&image->exception);
switch (bpp)
{
case 1: /* Convert bitmap scanline. */
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < ((ssize_t) image->columns-7); x+=8)
{
for (bit=0; bit < 8; bit++)
{
index=((*p) & (0x80 >> bit) ? 0x01 : 0x00);
SetPixelIndex(indexes+x+bit,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
}
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=0; bit < (ssize_t) (image->columns % 8); bit++)
{
index=((*p) & (0x80 >> bit) ? 0x01 : 0x00);
SetPixelIndex(indexes+x+bit,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
}
p++;
}
if (!SyncAuthenticPixels(image,exception))
break;
break;
}
case 2: /* Convert PseudoColor scanline. */
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < ((ssize_t) image->columns-1); x+=4)
{
index=ConstrainColormapIndex(image,(*p >> 6) & 0x3);
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
index=ConstrainColormapIndex(image,(*p >> 4) & 0x3);
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
index=ConstrainColormapIndex(image,(*p >> 2) & 0x3);
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
index=ConstrainColormapIndex(image,(*p) & 0x3);
SetPixelIndex(indexes+x+1,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
p++;
q++;
}
if ((image->columns % 4) != 0)
{
index=ConstrainColormapIndex(image,(*p >> 6) & 0x3);
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
if ((image->columns % 4) >= 1)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0x3);
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
if ((image->columns % 4) >= 2)
{
index=ConstrainColormapIndex(image,(*p >> 2) & 0x3);
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
}
}
p++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
break;
}
case 4: /* Convert PseudoColor scanline. */
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < ((ssize_t) image->columns-1); x+=2)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f);
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
index=ConstrainColormapIndex(image,(*p) & 0x0f);
SetPixelIndex(indexes+x+1,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
p++;
q++;
}
if ((image->columns % 2) != 0)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f);
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
p++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
break;
}
case 8: /* Convert PseudoColor scanline. */
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL) break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ConstrainColormapIndex(image,*p);
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
p++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
break;
case 24: /* Convert DirectColor scanline. */
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(*p++));
SetPixelGreen(q,ScaleCharToQuantum(*p++));
SetPixelBlue(q,ScaleCharToQuantum(*p++));
q++;
}
if (!SyncAuthenticPixels(image,exception))
break;
break;
}
}
/* Helper for WPG1 raster reader. */
#define InsertByte(b) \
{ \
BImgBuff[x]=b; \
x++; \
if((ssize_t) x>=ldblk) \
{ \
InsertRow(BImgBuff,(ssize_t) y,image,bpp); \
x=0; \
y++; \
} \
}
/* WPG1 raster reader. */
static int UnpackWPGRaster(Image *image,int bpp)
{
int
x,
y,
i;
unsigned char
bbuf,
*BImgBuff,
RunCount;
ssize_t
ldblk;
x=0;
y=0;
ldblk=(ssize_t) ((bpp*image->columns+7)/8);
BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk,
8*sizeof(*BImgBuff));
if(BImgBuff==NULL) return(-2);
while(y<(ssize_t) image->rows)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
bbuf=(unsigned char) c;
RunCount=bbuf & 0x7F;
if(bbuf & 0x80)
{
if(RunCount) /* repeat next byte runcount * */
{
bbuf=ReadBlobByte(image);
for(i=0;i<(int) RunCount;i++) InsertByte(bbuf);
}
else { /* read next byte as RunCount; repeat 0xFF runcount* */
c=ReadBlobByte(image);
if (c < 0)
break;
RunCount=(unsigned char) c;
for(i=0;i<(int) RunCount;i++) InsertByte(0xFF);
}
}
else {
if(RunCount) /* next runcount byte are readed directly */
{
for(i=0;i < (int) RunCount;i++)
{
bbuf=ReadBlobByte(image);
InsertByte(bbuf);
}
}
else { /* repeat previous line runcount* */
c=ReadBlobByte(image);
if (c < 0)
break;
RunCount=(unsigned char) c;
if(x) { /* attempt to duplicate row from x position: */
/* I do not know what to do here */
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
return(-3);
}
for(i=0;i < (int) RunCount;i++)
{
x=0;
y++; /* Here I need to duplicate previous row RUNCOUNT* */
if(y<2) continue;
if(y>(ssize_t) image->rows)
{
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
return(-4);
}
InsertRow(BImgBuff,y-1,image,bpp);
}
}
}
}
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
return(y < (ssize_t) image->rows ? -5 : 0);
}
/* Helper for WPG2 reader. */
#define InsertByte6(b) \
{ \
DisableMSCWarning(4310) \
if(XorMe)\
BImgBuff[x] = (unsigned char)~b;\
else\
BImgBuff[x] = b;\
RestoreMSCWarning \
x++; \
if((ssize_t) x >= ldblk) \
{ \
InsertRow(BImgBuff,(ssize_t) y,image,bpp); \
x=0; \
y++; \
} \
}
/* WPG2 raster reader. */
static int UnpackWPG2Raster(Image *image,int bpp)
{
int XorMe = 0;
int
RunCount;
size_t
x,
y;
ssize_t
i,
ldblk;
unsigned int
SampleSize=1;
unsigned char
bbuf,
*BImgBuff,
SampleBuffer[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
x=0;
y=0;
ldblk=(ssize_t) ((bpp*image->columns+7)/8);
BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk,
sizeof(*BImgBuff));
if(BImgBuff==NULL)
return(-2);
while( y< image->rows)
{
bbuf=ReadBlobByte(image);
switch(bbuf)
{
case 0x7D:
SampleSize=ReadBlobByte(image); /* DSZ */
if(SampleSize>8)
return(-2);
if(SampleSize<1)
return(-2);
break;
case 0x7E:
(void) FormatLocaleFile(stderr,
"\nUnsupported WPG token XOR, please report!");
XorMe=!XorMe;
break;
case 0x7F:
RunCount=ReadBlobByte(image); /* BLK */
if (RunCount < 0)
break;
for(i=0; i < SampleSize*(RunCount+1); i++)
{
InsertByte6(0);
}
break;
case 0xFD:
RunCount=ReadBlobByte(image); /* EXT */
if (RunCount < 0)
break;
for(i=0; i<= RunCount;i++)
for(bbuf=0; bbuf < SampleSize; bbuf++)
InsertByte6(SampleBuffer[bbuf]);
break;
case 0xFE:
RunCount=ReadBlobByte(image); /* RST */
if (RunCount < 0)
break;
if(x!=0)
{
(void) FormatLocaleFile(stderr,
"\nUnsupported WPG2 unaligned token RST x=%.20g, please report!\n"
,(double) x);
return(-3);
}
{
/* duplicate the previous row RunCount x */
for(i=0;i<=RunCount;i++)
{
InsertRow(BImgBuff,(ssize_t) (image->rows >= y ? y : image->rows-1),
image,bpp);
y++;
}
}
break;
case 0xFF:
RunCount=ReadBlobByte(image); /* WHT */
if (RunCount < 0)
break;
for (i=0; i < SampleSize*(RunCount+1); i++)
{
InsertByte6(0xFF);
}
break;
default:
RunCount=bbuf & 0x7F;
if(bbuf & 0x80) /* REP */
{
for(i=0; i < SampleSize; i++)
SampleBuffer[i]=ReadBlobByte(image);
for(i=0;i<=RunCount;i++)
for(bbuf=0;bbuf<SampleSize;bbuf++)
InsertByte6(SampleBuffer[bbuf]);
}
else { /* NRP */
for(i=0; i< SampleSize*(RunCount+1);i++)
{
bbuf=ReadBlobByte(image);
InsertByte6(bbuf);
}
}
}
}
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
return(0);
}
typedef float tCTM[3][3];
static unsigned LoadWPG2Flags(Image *image,char Precision,float *Angle,tCTM *CTM)
{
const unsigned char TPR=1,TRN=2,SKW=4,SCL=8,ROT=0x10,OID=0x20,LCK=0x80;
ssize_t x;
unsigned DenX;
unsigned Flags;
(void) memset(*CTM,0,sizeof(*CTM)); /*CTM.erase();CTM.resize(3,3);*/
(*CTM)[0][0]=1;
(*CTM)[1][1]=1;
(*CTM)[2][2]=1;
Flags=ReadBlobLSBShort(image);
if(Flags & LCK) (void) ReadBlobLSBLong(image); /*Edit lock*/
if(Flags & OID)
{
if(Precision==0)
{(void) ReadBlobLSBShort(image);} /*ObjectID*/
else
{(void) ReadBlobLSBLong(image);} /*ObjectID (Double precision)*/
}
if(Flags & ROT)
{
x=ReadBlobLSBLong(image); /*Rot Angle*/
if(Angle) *Angle=x/65536.0;
}
if(Flags & (ROT|SCL))
{
x=ReadBlobLSBLong(image); /*Sx*cos()*/
(*CTM)[0][0] = (float)x/0x10000;
x=ReadBlobLSBLong(image); /*Sy*cos()*/
(*CTM)[1][1] = (float)x/0x10000;
}
if(Flags & (ROT|SKW))
{
x=ReadBlobLSBLong(image); /*Kx*sin()*/
(*CTM)[1][0] = (float)x/0x10000;
x=ReadBlobLSBLong(image); /*Ky*sin()*/
(*CTM)[0][1] = (float)x/0x10000;
}
if(Flags & TRN)
{
x=ReadBlobLSBLong(image); DenX=ReadBlobLSBShort(image); /*Tx*/
if(x>=0) (*CTM)[0][2] = (float)x+(float)DenX/0x10000;
else (*CTM)[0][2] = (float)x-(float)DenX/0x10000;
x=ReadBlobLSBLong(image); DenX=ReadBlobLSBShort(image); /*Ty*/
(*CTM)[1][2]=(float)x + ((x>=0)?1:-1)*(float)DenX/0x10000;
if(x>=0) (*CTM)[1][2] = (float)x+(float)DenX/0x10000;
else (*CTM)[1][2] = (float)x-(float)DenX/0x10000;
}
if(Flags & TPR)
{
x=ReadBlobLSBShort(image); DenX=ReadBlobLSBShort(image); /*Px*/
(*CTM)[2][0] = x + (float)DenX/0x10000;;
x=ReadBlobLSBShort(image); DenX=ReadBlobLSBShort(image); /*Py*/
(*CTM)[2][1] = x + (float)DenX/0x10000;
}
return(Flags);
}
static Image *ExtractPostscript(Image *image,const ImageInfo *image_info,
MagickOffsetType PS_Offset,ssize_t PS_Size,ExceptionInfo *exception)
{
char
postscript_file[MaxTextExtent];
const MagicInfo
*magic_info;
FILE
*ps_file;
ImageInfo
*clone_info;
Image
*image2;
unsigned char
magick[2*MaxTextExtent];
if ((clone_info=CloneImageInfo(image_info)) == NULL)
return(image);
clone_info->blob=(void *) NULL;
clone_info->length=0;
/* Obtain temporary file */
(void) AcquireUniqueFilename(postscript_file);
ps_file=fopen_utf8(postscript_file,"wb");
if (ps_file == (FILE *) NULL)
goto FINISH;
/* Copy postscript to temporary file */
(void) SeekBlob(image,PS_Offset,SEEK_SET);
(void) ReadBlob(image, 2*MaxTextExtent, magick);
(void) SeekBlob(image,PS_Offset,SEEK_SET);
while(PS_Size-- > 0)
{
(void) fputc(ReadBlobByte(image),ps_file);
}
(void) fclose(ps_file);
/* Detect file format - Check magic.mgk configuration file. */
magic_info=GetMagicInfo(magick,2*MaxTextExtent,exception);
if(magic_info == (const MagicInfo *) NULL) goto FINISH_UNL;
/* printf("Detected:%s \n",magic_info->name); */
if(exception->severity != UndefinedException) goto FINISH_UNL;
if(magic_info->name == (char *) NULL) goto FINISH_UNL;
(void) CopyMagickMemory(clone_info->magick,magic_info->name,MaxTextExtent);
/* Read nested image */
/*FormatString(clone_info->filename,"%s:%s",magic_info->name,postscript_file);*/
FormatLocaleString(clone_info->filename,MaxTextExtent,"%s",postscript_file);
image2=ReadImage(clone_info,exception);
if (!image2)
goto FINISH_UNL;
/*
Replace current image with new image while copying base image
attributes.
*/
(void) CopyMagickMemory(image2->filename,image->filename,MaxTextExtent);
(void) CopyMagickMemory(image2->magick_filename,image->magick_filename,MaxTextExtent);
(void) CopyMagickMemory(image2->magick,image->magick,MaxTextExtent);
image2->depth=image->depth;
DestroyBlob(image2);
image2->blob=ReferenceBlob(image->blob);
if ((image->rows == 0) || (image->columns == 0))
DeleteImageFromList(&image);
AppendImageToList(&image,image2);
FINISH_UNL:
(void) RelinquishUniqueFileResource(postscript_file);
FINISH:
DestroyImageInfo(clone_info);
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d W P G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method ReadWPGImage reads an WPG X 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 ReadWPGImage method is:
%
% Image *ReadWPGImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: Method ReadWPGImage returns a pointer to the image after
% reading. A null image is returned if there is a memory shortage or if
% the image cannot be read.
%
% o image_info: Specifies a pointer to a ImageInfo structure.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadWPGImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
typedef struct
{
size_t FileId;
MagickOffsetType DataOffset;
unsigned int ProductType;
unsigned int FileType;
unsigned char MajorVersion;
unsigned char MinorVersion;
unsigned int EncryptKey;
unsigned int Reserved;
} WPGHeader;
typedef struct
{
unsigned char RecType;
size_t RecordLength;
} WPGRecord;
typedef struct
{
unsigned char Class;
unsigned char RecType;
size_t Extension;
size_t RecordLength;
} WPG2Record;
typedef struct
{
unsigned HorizontalUnits;
unsigned VerticalUnits;
unsigned char PosSizePrecision;
} WPG2Start;
typedef struct
{
unsigned int Width;
unsigned int Height;
unsigned int Depth;
unsigned int HorzRes;
unsigned int VertRes;
} WPGBitmapType1;
typedef struct
{
unsigned int Width;
unsigned int Height;
unsigned char Depth;
unsigned char Compression;
} WPG2BitmapType1;
typedef struct
{
unsigned int RotAngle;
unsigned int LowLeftX;
unsigned int LowLeftY;
unsigned int UpRightX;
unsigned int UpRightY;
unsigned int Width;
unsigned int Height;
unsigned int Depth;
unsigned int HorzRes;
unsigned int VertRes;
} WPGBitmapType2;
typedef struct
{
unsigned int StartIndex;
unsigned int NumOfEntries;
} WPGColorMapRec;
/*
typedef struct {
size_t PS_unknown1;
unsigned int PS_unknown2;
unsigned int PS_unknown3;
} WPGPSl1Record;
*/
Image
*image;
unsigned int
status;
WPGHeader
Header;
WPGRecord
Rec;
WPG2Record
Rec2;
WPG2Start StartWPG;
WPGBitmapType1
BitmapHeader1;
WPG2BitmapType1
Bitmap2Header1;
WPGBitmapType2
BitmapHeader2;
WPGColorMapRec
WPG_Palette;
int
i,
bpp,
WPG2Flags;
ssize_t
ldblk;
size_t
one;
unsigned char
*BImgBuff;
tCTM CTM; /*current transform matrix*/
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
one=1;
image=AcquireImage(image_info);
image->depth=8;
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read WPG image.
*/
Header.FileId=ReadBlobLSBLong(image);
Header.DataOffset=(MagickOffsetType) ReadBlobLSBLong(image);
Header.ProductType=ReadBlobLSBShort(image);
Header.FileType=ReadBlobLSBShort(image);
Header.MajorVersion=ReadBlobByte(image);
Header.MinorVersion=ReadBlobByte(image);
Header.EncryptKey=ReadBlobLSBShort(image);
Header.Reserved=ReadBlobLSBShort(image);
if (Header.FileId!=0x435057FF || (Header.ProductType>>8)!=0x16)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (Header.EncryptKey!=0)
ThrowReaderException(CoderError,"EncryptedWPGImageFileNotSupported");
image->columns = 1;
image->rows = 1;
image->colors = 0;
bpp=0;
BitmapHeader2.RotAngle=0;
switch(Header.FileType)
{
case 1: /* WPG level 1 */
while(!EOFBlob(image)) /* object parser loop */
{
(void) SeekBlob(image,Header.DataOffset,SEEK_SET);
if(EOFBlob(image))
break;
Rec.RecType=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rd_WP_DWORD(image,&Rec.RecordLength);
if(EOFBlob(image))
break;
Header.DataOffset=TellBlob(image)+Rec.RecordLength;
switch(Rec.RecType)
{
case 0x0B: /* bitmap type 1 */
BitmapHeader1.Width=ReadBlobLSBShort(image);
BitmapHeader1.Height=ReadBlobLSBShort(image);
if ((BitmapHeader1.Width == 0) || (BitmapHeader1.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
BitmapHeader1.Depth=ReadBlobLSBShort(image);
BitmapHeader1.HorzRes=ReadBlobLSBShort(image);
BitmapHeader1.VertRes=ReadBlobLSBShort(image);
if(BitmapHeader1.HorzRes && BitmapHeader1.VertRes)
{
image->units=PixelsPerCentimeterResolution;
image->x_resolution=BitmapHeader1.HorzRes/470.0;
image->y_resolution=BitmapHeader1.VertRes/470.0;
}
image->columns=BitmapHeader1.Width;
image->rows=BitmapHeader1.Height;
bpp=BitmapHeader1.Depth;
goto UnpackRaster;
case 0x0E: /*Color palette */
WPG_Palette.StartIndex=ReadBlobLSBShort(image);
WPG_Palette.NumOfEntries=ReadBlobLSBShort(image);
image->colors=WPG_Palette.NumOfEntries;
if (!AcquireImageColormap(image,image->colors))
goto NoMemory;
for (i=WPG_Palette.StartIndex;
i < (int)WPG_Palette.NumOfEntries; i++)
{
image->colormap[i].red=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->colormap[i].green=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->colormap[i].blue=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
}
break;
case 0x11: /* Start PS l1 */
if(Rec.RecordLength > 8)
image=ExtractPostscript(image,image_info,
TellBlob(image)+8, /* skip PS header in the wpg */
(ssize_t) Rec.RecordLength-8,exception);
break;
case 0x14: /* bitmap type 2 */
BitmapHeader2.RotAngle=ReadBlobLSBShort(image);
BitmapHeader2.LowLeftX=ReadBlobLSBShort(image);
BitmapHeader2.LowLeftY=ReadBlobLSBShort(image);
BitmapHeader2.UpRightX=ReadBlobLSBShort(image);
BitmapHeader2.UpRightY=ReadBlobLSBShort(image);
BitmapHeader2.Width=ReadBlobLSBShort(image);
BitmapHeader2.Height=ReadBlobLSBShort(image);
if ((BitmapHeader2.Width == 0) || (BitmapHeader2.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
BitmapHeader2.Depth=ReadBlobLSBShort(image);
BitmapHeader2.HorzRes=ReadBlobLSBShort(image);
BitmapHeader2.VertRes=ReadBlobLSBShort(image);
image->units=PixelsPerCentimeterResolution;
image->page.width=(unsigned int)
((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightX)/470.0);
image->page.height=(unsigned int)
((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightY)/470.0);
image->page.x=(int) (BitmapHeader2.LowLeftX/470.0);
image->page.y=(int) (BitmapHeader2.LowLeftX/470.0);
if(BitmapHeader2.HorzRes && BitmapHeader2.VertRes)
{
image->x_resolution=BitmapHeader2.HorzRes/470.0;
image->y_resolution=BitmapHeader2.VertRes/470.0;
}
image->columns=BitmapHeader2.Width;
image->rows=BitmapHeader2.Height;
bpp=BitmapHeader2.Depth;
UnpackRaster:
if ((image->colors == 0) && (bpp != 24))
{
image->colors=one << bpp;
if (!AcquireImageColormap(image,image->colors))
{
NoMemory:
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
/* printf("Load default colormap \n"); */
for (i=0; (i < (int) image->colors) && (i < 256); i++)
{
image->colormap[i].red=ScaleCharToQuantum(WPG1_Palette[i].Red);
image->colormap[i].green=ScaleCharToQuantum(WPG1_Palette[i].Green);
image->colormap[i].blue=ScaleCharToQuantum(WPG1_Palette[i].Blue);
}
}
else
{
if (bpp < 24)
if ( (image->colors < (one << bpp)) && (bpp != 24) )
image->colormap=(PixelPacket *) ResizeQuantumMemory(
image->colormap,(size_t) (one << bpp),
sizeof(*image->colormap));
}
if (bpp == 1)
{
if(image->colormap[0].red==0 &&
image->colormap[0].green==0 &&
image->colormap[0].blue==0 &&
image->colormap[1].red==0 &&
image->colormap[1].green==0 &&
image->colormap[1].blue==0)
{ /* fix crippled monochrome palette */
image->colormap[1].red =
image->colormap[1].green =
image->colormap[1].blue = QuantumRange;
}
}
if(UnpackWPGRaster(image,bpp) < 0)
/* The raster cannot be unpacked */
{
DecompressionFailed:
ThrowReaderException(CoderError,"UnableToDecompressImage");
}
if(Rec.RecType==0x14 && BitmapHeader2.RotAngle!=0 && !image_info->ping)
{
/* flop command */
if(BitmapHeader2.RotAngle & 0x8000)
{
Image
*flop_image;
flop_image = FlopImage(image, exception);
if (flop_image != (Image *) NULL) {
DuplicateBlob(flop_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flop_image);
}
}
/* flip command */
if(BitmapHeader2.RotAngle & 0x2000)
{
Image
*flip_image;
flip_image = FlipImage(image, exception);
if (flip_image != (Image *) NULL) {
DuplicateBlob(flip_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flip_image);
}
}
/* rotate command */
if(BitmapHeader2.RotAngle & 0x0FFF)
{
Image
*rotate_image;
rotate_image=RotateImage(image,(BitmapHeader2.RotAngle &
0x0FFF), exception);
if (rotate_image != (Image *) NULL) {
DuplicateBlob(rotate_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,rotate_image);
}
}
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image);
image->depth=8;
if (image->next == (Image *) NULL)
goto Finish;
image=SyncNextImageInList(image);
image->columns=image->rows=0;
image->colors=0;
break;
case 0x1B: /* Postscript l2 */
if(Rec.RecordLength>0x3C)
image=ExtractPostscript(image,image_info,
TellBlob(image)+0x3C, /* skip PS l2 header in the wpg */
(ssize_t) Rec.RecordLength-0x3C,exception);
break;
}
}
break;
case 2: /* WPG level 2 */
(void) memset(CTM,0,sizeof(CTM));
StartWPG.PosSizePrecision = 0;
while(!EOFBlob(image)) /* object parser loop */
{
(void) SeekBlob(image,Header.DataOffset,SEEK_SET);
if(EOFBlob(image))
break;
Rec2.Class=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rec2.RecType=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rd_WP_DWORD(image,&Rec2.Extension);
Rd_WP_DWORD(image,&Rec2.RecordLength);
if(EOFBlob(image))
break;
Header.DataOffset=TellBlob(image)+Rec2.RecordLength;
switch(Rec2.RecType)
{
case 1:
StartWPG.HorizontalUnits=ReadBlobLSBShort(image);
StartWPG.VerticalUnits=ReadBlobLSBShort(image);
StartWPG.PosSizePrecision=ReadBlobByte(image);
break;
case 0x0C: /* Color palette */
WPG_Palette.StartIndex=ReadBlobLSBShort(image);
WPG_Palette.NumOfEntries=ReadBlobLSBShort(image);
image->colors=WPG_Palette.NumOfEntries;
if (AcquireImageColormap(image,image->colors) == MagickFalse)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
for (i=WPG_Palette.StartIndex;
i < (int)WPG_Palette.NumOfEntries; i++)
{
image->colormap[i].red=ScaleCharToQuantum((char)
ReadBlobByte(image));
image->colormap[i].green=ScaleCharToQuantum((char)
ReadBlobByte(image));
image->colormap[i].blue=ScaleCharToQuantum((char)
ReadBlobByte(image));
(void) ReadBlobByte(image); /*Opacity??*/
}
break;
case 0x0E:
Bitmap2Header1.Width=ReadBlobLSBShort(image);
Bitmap2Header1.Height=ReadBlobLSBShort(image);
if ((Bitmap2Header1.Width == 0) || (Bitmap2Header1.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
Bitmap2Header1.Depth=ReadBlobByte(image);
Bitmap2Header1.Compression=ReadBlobByte(image);
if(Bitmap2Header1.Compression > 1)
continue; /*Unknown compression method */
switch(Bitmap2Header1.Depth)
{
case 1:
bpp=1;
break;
case 2:
bpp=2;
break;
case 3:
bpp=4;
break;
case 4:
bpp=8;
break;
case 8:
bpp=24;
break;
default:
continue; /*Ignore raster with unknown depth*/
}
image->columns=Bitmap2Header1.Width;
image->rows=Bitmap2Header1.Height;
if ((image->colors == 0) && (bpp != 24))
{
size_t
one;
one=1;
image->colors=one << bpp;
if (!AcquireImageColormap(image,image->colors))
goto NoMemory;
}
else
{
if(bpp < 24)
if( image->colors<(one << bpp) && bpp!=24 )
image->colormap=(PixelPacket *) ResizeQuantumMemory(
image->colormap,(size_t) (one << bpp),
sizeof(*image->colormap));
}
switch(Bitmap2Header1.Compression)
{
case 0: /*Uncompressed raster*/
{
ldblk=(ssize_t) ((bpp*image->columns+7)/8);
BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t)
ldblk,sizeof(*BImgBuff));
if (BImgBuff == (unsigned char *) NULL)
goto NoMemory;
for(i=0; i< (ssize_t) image->rows; i++)
{
(void) ReadBlob(image,ldblk,BImgBuff);
InsertRow(BImgBuff,i,image,bpp);
}
if(BImgBuff)
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);;
break;
}
case 1: /*RLE for WPG2 */
{
if( UnpackWPG2Raster(image,bpp) < 0)
goto DecompressionFailed;
break;
}
}
if(CTM[0][0]<0 && !image_info->ping)
{ /*?? RotAngle=360-RotAngle;*/
Image
*flop_image;
flop_image = FlopImage(image, exception);
if (flop_image != (Image *) NULL) {
DuplicateBlob(flop_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flop_image);
}
/* Try to change CTM according to Flip - I am not sure, must be checked.
Tx(0,0)=-1; Tx(1,0)=0; Tx(2,0)=0;
Tx(0,1)= 0; Tx(1,1)=1; Tx(2,1)=0;
Tx(0,2)=(WPG._2Rect.X_ur+WPG._2Rect.X_ll);
Tx(1,2)=0; Tx(2,2)=1; */
}
if(CTM[1][1]<0 && !image_info->ping)
{ /*?? RotAngle=360-RotAngle;*/
Image
*flip_image;
flip_image = FlipImage(image, exception);
if (flip_image != (Image *) NULL) {
DuplicateBlob(flip_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flip_image);
}
/* Try to change CTM according to Flip - I am not sure, must be checked.
float_matrix Tx(3,3);
Tx(0,0)= 1; Tx(1,0)= 0; Tx(2,0)=0;
Tx(0,1)= 0; Tx(1,1)=-1; Tx(2,1)=0;
Tx(0,2)= 0; Tx(1,2)=(WPG._2Rect.Y_ur+WPG._2Rect.Y_ll);
Tx(2,2)=1; */
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image);
image->depth=8;
if (image->next == (Image *) NULL)
goto Finish;
image=SyncNextImageInList(image);
image->columns=image->rows=1;
image->colors=0;
break;
case 0x12: /* Postscript WPG2*/
i=ReadBlobLSBShort(image);
if(Rec2.RecordLength > (unsigned int) i)
image=ExtractPostscript(image,image_info,
TellBlob(image)+i, /*skip PS header in the wpg2*/
(ssize_t) (Rec2.RecordLength-i-2),exception);
break;
case 0x1B: /*bitmap rectangle*/
WPG2Flags = LoadWPG2Flags(image,StartWPG.PosSizePrecision,NULL,&CTM);
(void) WPG2Flags;
break;
}
}
break;
default:
{
ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported");
}
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
Finish:
(void) CloseBlob(image);
{
Image
*p;
ssize_t
scene=0;
/*
Rewind list, removing any empty images while rewinding.
*/
p=image;
image=NULL;
while (p != (Image *) NULL)
{
Image *tmp=p;
if ((p->rows == 0) || (p->columns == 0)) {
p=p->previous;
DeleteImageFromList(&tmp);
} else {
image=p;
p=p->previous;
}
}
/*
Fix scene numbers.
*/
for (p=image; p != (Image *) NULL; p=p->next)
p->scene=(size_t) scene++;
}
if (image == (Image *) NULL)
ThrowReaderException(CorruptImageError,
"ImageFileDoesNotContainAnyImageData");
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r W P G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method RegisterWPGImage adds attributes for the WPG 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 RegisterWPGImage method is:
%
% size_t RegisterWPGImage(void)
%
*/
ModuleExport size_t RegisterWPGImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("WPG");
entry->decoder=(DecodeImageHandler *) ReadWPGImage;
entry->magick=(IsImageFormatHandler *) IsWPG;
entry->description=AcquireString("Word Perfect Graphics");
entry->module=ConstantString("WPG");
entry->seekable_stream=MagickTrue;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r W P G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method UnregisterWPGImage removes format registrations made by the
% WPG module from the list of supported formats.
%
% The format of the UnregisterWPGImage method is:
%
% UnregisterWPGImage(void)
%
*/
ModuleExport void UnregisterWPGImage(void)
{
(void) UnregisterMagickInfo("WPG");
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_5304_0 |
crossvul-cpp_data_bad_526_1 | /*
* GPAC - Multimedia Framework C SDK
*
* Authors: Jean Le Feuvre
* Copyright (c) Telecom ParisTech 2000-2012
* All rights reserved
*
* This file is part of GPAC / Media Tools sub-project
*
* GPAC 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, or (at your option)
* any later version.
*
* GPAC 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; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
#include <gpac/constants.h>
#include <gpac/utf.h>
#include <gpac/xml.h>
#include <gpac/token.h>
#include <gpac/color.h>
#include <gpac/internal/media_dev.h>
#include <gpac/internal/isomedia_dev.h>
#ifndef GPAC_DISABLE_ISOM_WRITE
void gf_media_update_bitrate(GF_ISOFile *file, u32 track);
enum
{
GF_TEXT_IMPORT_NONE = 0,
GF_TEXT_IMPORT_SRT,
GF_TEXT_IMPORT_SUB,
GF_TEXT_IMPORT_TTXT,
GF_TEXT_IMPORT_TEXML,
GF_TEXT_IMPORT_WEBVTT,
GF_TEXT_IMPORT_TTML,
GF_TEXT_IMPORT_SWF_SVG,
};
#define REM_TRAIL_MARKS(__str, __sep) while (1) { \
u32 _len = (u32) strlen(__str); \
if (!_len) break; \
_len--; \
if (strchr(__sep, __str[_len])) __str[_len] = 0; \
else break; \
} \
s32 gf_text_get_utf_type(FILE *in_src)
{
u32 read;
unsigned char BOM[5];
read = (u32) fread(BOM, sizeof(char), 5, in_src);
if ((s32) read < 1)
return -1;
if ((BOM[0]==0xFF) && (BOM[1]==0xFE)) {
/*UTF32 not supported*/
if (!BOM[2] && !BOM[3]) return -1;
gf_fseek(in_src, 2, SEEK_SET);
return 3;
}
if ((BOM[0]==0xFE) && (BOM[1]==0xFF)) {
/*UTF32 not supported*/
if (!BOM[2] && !BOM[3]) return -1;
gf_fseek(in_src, 2, SEEK_SET);
return 2;
} else if ((BOM[0]==0xEF) && (BOM[1]==0xBB) && (BOM[2]==0xBF)) {
gf_fseek(in_src, 3, SEEK_SET);
return 1;
}
if (BOM[0]<0x80) {
gf_fseek(in_src, 0, SEEK_SET);
return 0;
}
return -1;
}
static GF_Err gf_text_guess_format(char *filename, u32 *fmt)
{
char szLine[2048];
u32 val;
s32 uni_type;
FILE *test = gf_fopen(filename, "rb");
if (!test) return GF_URL_ERROR;
uni_type = gf_text_get_utf_type(test);
if (uni_type>1) {
const u16 *sptr;
char szUTF[1024];
u32 read = (u32) fread(szUTF, 1, 1023, test);
if ((s32) read < 0) {
gf_fclose(test);
return GF_IO_ERR;
}
szUTF[read]=0;
sptr = (u16*)szUTF;
/*read = (u32) */gf_utf8_wcstombs(szLine, read, &sptr);
} else {
val = (u32) fread(szLine, 1, 1024, test);
if ((s32) val<0) return GF_IO_ERR;
szLine[val]=0;
}
REM_TRAIL_MARKS(szLine, "\r\n\t ")
*fmt = GF_TEXT_IMPORT_NONE;
if ((szLine[0]=='{') && strstr(szLine, "}{")) *fmt = GF_TEXT_IMPORT_SUB;
else if (szLine[0] == '<') {
char *ext = strrchr(filename, '.');
if (!strnicmp(ext, ".ttxt", 5)) *fmt = GF_TEXT_IMPORT_TTXT;
else if (!strnicmp(ext, ".ttml", 5)) *fmt = GF_TEXT_IMPORT_TTML;
ext = strstr(szLine, "?>");
if (ext) ext += 2;
if (ext && !ext[0]) {
if (!fgets(szLine, 2048, test))
szLine[0] = '\0';
}
if (strstr(szLine, "x-quicktime-tx3g") || strstr(szLine, "text3GTrack")) *fmt = GF_TEXT_IMPORT_TEXML;
else if (strstr(szLine, "TextStream")) *fmt = GF_TEXT_IMPORT_TTXT;
else if (strstr(szLine, "tt")) *fmt = GF_TEXT_IMPORT_TTML;
}
else if (strstr(szLine, "WEBVTT") )
*fmt = GF_TEXT_IMPORT_WEBVTT;
else if (strstr(szLine, " --> ") )
*fmt = GF_TEXT_IMPORT_SRT; /* might want to change the default to WebVTT */
gf_fclose(test);
return GF_OK;
}
#define TTXT_DEFAULT_WIDTH 400
#define TTXT_DEFAULT_HEIGHT 60
#define TTXT_DEFAULT_FONT_SIZE 18
#ifndef GPAC_DISABLE_MEDIA_IMPORT
void gf_text_get_video_size(GF_MediaImporter *import, u32 *width, u32 *height)
{
u32 w, h, f_w, f_h, i;
GF_ISOFile *dest = import->dest;
if (import->text_track_width && import->text_track_height) {
(*width) = import->text_track_width;
(*height) = import->text_track_height;
return;
}
f_w = f_h = 0;
for (i=0; i<gf_isom_get_track_count(dest); i++) {
switch (gf_isom_get_media_type(dest, i+1)) {
case GF_ISOM_MEDIA_SCENE:
case GF_ISOM_MEDIA_VISUAL:
case GF_ISOM_MEDIA_AUXV:
case GF_ISOM_MEDIA_PICT:
gf_isom_get_visual_info(dest, i+1, 1, &w, &h);
if (w > f_w) f_w = w;
if (h > f_h) f_h = h;
gf_isom_get_track_layout_info(dest, i+1, &w, &h, NULL, NULL, NULL);
if (w > f_w) f_w = w;
if (h > f_h) f_h = h;
break;
}
}
(*width) = f_w ? f_w : TTXT_DEFAULT_WIDTH;
(*height) = f_h ? f_h : TTXT_DEFAULT_HEIGHT;
}
void gf_text_import_set_language(GF_MediaImporter *import, u32 track)
{
if (import->esd && import->esd->langDesc) {
char lang[4];
lang[0] = (import->esd->langDesc->langCode>>16) & 0xFF;
lang[1] = (import->esd->langDesc->langCode>>8) & 0xFF;
lang[2] = (import->esd->langDesc->langCode) & 0xFF;
lang[3] = 0;
gf_isom_set_media_language(import->dest, track, lang);
}
}
#endif
char *gf_text_get_utf8_line(char *szLine, u32 lineSize, FILE *txt_in, s32 unicode_type)
{
u32 i, j, len;
char *sOK;
char szLineConv[1024];
unsigned short *sptr;
memset(szLine, 0, sizeof(char)*lineSize);
sOK = fgets(szLine, lineSize, txt_in);
if (!sOK) return NULL;
if (unicode_type<=1) {
j=0;
len = (u32) strlen(szLine);
for (i=0; i<len; i++) {
if (!unicode_type && (szLine[i] & 0x80)) {
/*non UTF8 (likely some win-CP)*/
if ((szLine[i+1] & 0xc0) != 0x80) {
szLineConv[j] = 0xc0 | ( (szLine[i] >> 6) & 0x3 );
j++;
szLine[i] &= 0xbf;
}
/*UTF8 2 bytes char*/
else if ( (szLine[i] & 0xe0) == 0xc0) {
szLineConv[j] = szLine[i];
i++;
j++;
}
/*UTF8 3 bytes char*/
else if ( (szLine[i] & 0xf0) == 0xe0) {
szLineConv[j] = szLine[i];
i++;
j++;
szLineConv[j] = szLine[i];
i++;
j++;
}
/*UTF8 4 bytes char*/
else if ( (szLine[i] & 0xf8) == 0xf0) {
szLineConv[j] = szLine[i];
i++;
j++;
szLineConv[j] = szLine[i];
i++;
j++;
szLineConv[j] = szLine[i];
i++;
j++;
} else {
i+=1;
continue;
}
}
szLineConv[j] = szLine[i];
j++;
}
szLineConv[j] = 0;
strcpy(szLine, szLineConv);
return sOK;
}
#ifdef GPAC_BIG_ENDIAN
if (unicode_type==3) {
#else
if (unicode_type==2) {
#endif
i=0;
while (1) {
char c;
if (!szLine[i] && !szLine[i+1]) break;
c = szLine[i+1];
szLine[i+1] = szLine[i];
szLine[i] = c;
i+=2;
}
}
sptr = (u16 *)szLine;
i = (u32) gf_utf8_wcstombs(szLineConv, 1024, (const unsigned short **) &sptr);
if (i >= (u32)ARRAY_LENGTH(szLineConv))
return NULL;
szLineConv[i] = 0;
strcpy(szLine, szLineConv);
/*this is ugly indeed: since input is UTF16-LE, there are many chances the fgets never reads the \0 after a \n*/
if (unicode_type==3) fgetc(txt_in);
return sOK;
}
#ifndef GPAC_DISABLE_MEDIA_IMPORT
static GF_Err gf_text_import_srt(GF_MediaImporter *import)
{
FILE *srt_in;
u32 track, timescale, i, count;
GF_TextConfig*cfg;
GF_Err e;
GF_StyleRecord rec;
GF_TextSample * samp;
GF_ISOSample *s;
u32 sh, sm, ss, sms, eh, em, es, ems, txt_line, char_len, char_line, nb_samp, j, duration, rem_styles;
Bool set_start_char, set_end_char, first_samp, rem_color;
u64 start, end, prev_end, file_size;
u32 state, curLine, line, len, ID, OCR_ES_ID, default_color;
s32 unicode_type;
char szLine[2048], szText[2048], *ptr;
unsigned short uniLine[5000], uniText[5000], *sptr;
srt_in = gf_fopen(import->in_name, "rt");
gf_fseek(srt_in, 0, SEEK_END);
file_size = gf_ftell(srt_in);
gf_fseek(srt_in, 0, SEEK_SET);
unicode_type = gf_text_get_utf_type(srt_in);
if (unicode_type<0) {
gf_fclose(srt_in);
return gf_import_message(import, GF_NOT_SUPPORTED, "Unsupported SRT UTF encoding");
}
cfg = NULL;
if (import->esd) {
if (!import->esd->slConfig) {
import->esd->slConfig = (GF_SLConfig *) gf_odf_desc_new(GF_ODF_SLC_TAG);
import->esd->slConfig->predefined = 2;
import->esd->slConfig->timestampResolution = 1000;
}
timescale = import->esd->slConfig->timestampResolution;
if (!timescale) timescale = 1000;
/*explicit text config*/
if (import->esd->decoderConfig && import->esd->decoderConfig->decoderSpecificInfo->tag == GF_ODF_TEXT_CFG_TAG) {
cfg = (GF_TextConfig *) import->esd->decoderConfig->decoderSpecificInfo;
import->esd->decoderConfig->decoderSpecificInfo = NULL;
}
ID = import->esd->ESID;
OCR_ES_ID = import->esd->OCRESID;
} else {
timescale = 1000;
OCR_ES_ID = ID = 0;
}
if (cfg && cfg->timescale) timescale = cfg->timescale;
track = gf_isom_new_track(import->dest, ID, GF_ISOM_MEDIA_TEXT, timescale);
if (!track) {
gf_fclose(srt_in);
return gf_import_message(import, gf_isom_last_error(import->dest), "Error creating text track");
}
gf_isom_set_track_enabled(import->dest, track, 1);
import->final_trackID = gf_isom_get_track_id(import->dest, track);
if (import->esd && !import->esd->ESID) import->esd->ESID = import->final_trackID;
if (OCR_ES_ID) gf_isom_set_track_reference(import->dest, track, GF_ISOM_REF_OCR, OCR_ES_ID);
/*setup track*/
if (cfg) {
char *firstFont = NULL;
/*set track info*/
gf_isom_set_track_layout_info(import->dest, track, cfg->text_width<<16, cfg->text_height<<16, 0, 0, cfg->layer);
/*and set sample descriptions*/
count = gf_list_count(cfg->sample_descriptions);
for (i=0; i<count; i++) {
GF_TextSampleDescriptor *sd= (GF_TextSampleDescriptor *)gf_list_get(cfg->sample_descriptions, i);
if (!sd->font_count) {
sd->fonts = (GF_FontRecord*)gf_malloc(sizeof(GF_FontRecord));
sd->font_count = 1;
sd->fonts[0].fontID = 1;
sd->fonts[0].fontName = gf_strdup("Serif");
}
if (!sd->default_style.fontID) sd->default_style.fontID = sd->fonts[0].fontID;
if (!sd->default_style.font_size) sd->default_style.font_size = 16;
if (!sd->default_style.text_color) sd->default_style.text_color = 0xFF000000;
/*store attribs*/
if (!i) rec = sd->default_style;
gf_isom_new_text_description(import->dest, track, sd, NULL, NULL, &state);
if (!firstFont) firstFont = sd->fonts[0].fontName;
}
gf_import_message(import, GF_OK, "Timed Text (SRT) import - text track %d x %d, font %s (size %d)", cfg->text_width, cfg->text_height, firstFont, rec.font_size);
gf_odf_desc_del((GF_Descriptor *)cfg);
} else {
u32 w, h;
GF_TextSampleDescriptor *sd;
gf_text_get_video_size(import, &w, &h);
/*have to work with default - use max size (if only one video, this means the text region is the
entire display, and with bottom alignment things should be fine...*/
gf_isom_set_track_layout_info(import->dest, track, w<<16, h<<16, 0, 0, 0);
sd = (GF_TextSampleDescriptor*)gf_odf_desc_new(GF_ODF_TX3G_TAG);
sd->fonts = (GF_FontRecord*)gf_malloc(sizeof(GF_FontRecord));
sd->font_count = 1;
sd->fonts[0].fontID = 1;
sd->fonts[0].fontName = gf_strdup(import->fontName ? import->fontName : "Serif");
sd->back_color = 0x00000000; /*transparent*/
sd->default_style.fontID = 1;
sd->default_style.font_size = import->fontSize ? import->fontSize : TTXT_DEFAULT_FONT_SIZE;
sd->default_style.text_color = 0xFFFFFFFF; /*white*/
sd->default_style.style_flags = 0;
sd->horiz_justif = 1; /*center of scene*/
sd->vert_justif = (s8) -1; /*bottom of scene*/
if (import->flags & GF_IMPORT_SKIP_TXT_BOX) {
sd->default_pos.top = sd->default_pos.left = sd->default_pos.right = sd->default_pos.bottom = 0;
} else {
if ((sd->default_pos.bottom==sd->default_pos.top) || (sd->default_pos.right==sd->default_pos.left)) {
sd->default_pos.left = import->text_x;
sd->default_pos.top = import->text_y;
sd->default_pos.right = (import->text_width ? import->text_width : w) + sd->default_pos.left;
sd->default_pos.bottom = (import->text_height ? import->text_height : h) + sd->default_pos.top;
}
}
/*store attribs*/
rec = sd->default_style;
gf_isom_new_text_description(import->dest, track, sd, NULL, NULL, &state);
gf_import_message(import, GF_OK, "Timed Text (SRT) import - text track %d x %d, font %s (size %d)", w, h, sd->fonts[0].fontName, rec.font_size);
gf_odf_desc_del((GF_Descriptor *)sd);
}
gf_text_import_set_language(import, track);
duration = (u32) (((Double) import->duration)*timescale/1000.0);
default_color = rec.text_color;
e = GF_OK;
state = 0;
end = prev_end = 0;
curLine = 0;
txt_line = 0;
set_start_char = set_end_char = GF_FALSE;
char_len = 0;
start = 0;
nb_samp = 0;
samp = gf_isom_new_text_sample();
first_samp = GF_TRUE;
while (1) {
char *sOK = gf_text_get_utf8_line(szLine, 2048, srt_in, unicode_type);
if (sOK) REM_TRAIL_MARKS(szLine, "\r\n\t ")
if (!sOK || !strlen(szLine)) {
rec.style_flags = 0;
rec.startCharOffset = rec.endCharOffset = 0;
if (txt_line) {
if (prev_end && (start != prev_end)) {
GF_TextSample * empty_samp = gf_isom_new_text_sample();
s = gf_isom_text_to_sample(empty_samp);
gf_isom_delete_text_sample(empty_samp);
if (state<=2) {
s->DTS = (u64) ((timescale*prev_end)/1000);
s->IsRAP = RAP;
gf_isom_add_sample(import->dest, track, 1, s);
nb_samp++;
}
gf_isom_sample_del(&s);
}
s = gf_isom_text_to_sample(samp);
if (state<=2) {
s->DTS = (u64) ((timescale*start)/1000);
s->IsRAP = RAP;
gf_isom_add_sample(import->dest, track, 1, s);
gf_isom_sample_del(&s);
nb_samp++;
prev_end = end;
}
txt_line = 0;
char_len = 0;
set_start_char = set_end_char = GF_FALSE;
rec.startCharOffset = rec.endCharOffset = 0;
gf_isom_text_reset(samp);
//gf_import_progress(import, nb_samp, nb_samp+1);
gf_set_progress("Importing SRT", gf_ftell(srt_in), file_size);
if (duration && (end >= duration)) break;
}
state = 0;
if (!sOK) break;
continue;
}
switch (state) {
case 0:
if (sscanf(szLine, "%u", &line) != 1) {
e = gf_import_message(import, GF_CORRUPTED_DATA, "Bad SRT formatting - expecting number got \"%s\"", szLine);
goto exit;
}
if (line != curLine + 1) gf_import_message(import, GF_OK, "WARNING: corrupted SRT frame %d after frame %d", line, curLine);
curLine = line;
state = 1;
break;
case 1:
if (sscanf(szLine, "%u:%u:%u,%u --> %u:%u:%u,%u", &sh, &sm, &ss, &sms, &eh, &em, &es, &ems) != 8) {
sh = eh = 0;
if (sscanf(szLine, "%u:%u,%u --> %u:%u,%u", &sm, &ss, &sms, &em, &es, &ems) != 6) {
e = gf_import_message(import, GF_CORRUPTED_DATA, "Error scanning SRT frame %d timing", curLine);
goto exit;
}
}
start = (3600*sh + 60*sm + ss)*1000 + sms;
if (start<end) {
gf_import_message(import, GF_OK, "WARNING: overlapping SRT frame %d - starts "LLD" ms is before end of previous one "LLD" ms - adjusting time stamps", curLine, start, end);
start = end;
}
end = (3600*eh + 60*em + es)*1000 + ems;
/*make stream start at 0 by inserting a fake AU*/
if (first_samp && (start>0)) {
s = gf_isom_text_to_sample(samp);
s->DTS = 0;
gf_isom_add_sample(import->dest, track, 1, s);
gf_isom_sample_del(&s);
nb_samp++;
}
rec.style_flags = 0;
state = 2;
if (end<=prev_end) {
gf_import_message(import, GF_OK, "WARNING: overlapping SRT frame %d end "LLD" is at or before previous end "LLD" - removing", curLine, end, prev_end);
start = end;
state = 3;
}
break;
default:
/*reset only when text is present*/
first_samp = GF_FALSE;
/*go to line*/
if (txt_line) {
gf_isom_text_add_text(samp, "\n", 1);
char_len += 1;
}
ptr = (char *) szLine;
{
size_t _len = gf_utf8_mbstowcs(uniLine, 5000, (const char **) &ptr);
if (_len == (size_t) -1) {
e = gf_import_message(import, GF_CORRUPTED_DATA, "Invalid UTF data (line %d)", curLine);
goto exit;
}
len = (u32) _len;
}
i=j=0;
rem_styles = 0;
rem_color = 0;
while (i<len) {
u32 font_style = 0;
u32 style_nb_chars = 0;
u32 style_def_type = 0;
if ( (uniLine[i]=='<') && (uniLine[i+2]=='>')) {
style_nb_chars = 3;
style_def_type = 1;
}
else if ( (uniLine[i]=='<') && (uniLine[i+1]=='/') && (uniLine[i+3]=='>')) {
style_def_type = 2;
style_nb_chars = 4;
}
else if (uniLine[i]=='<') {
const unsigned short* src = uniLine + i;
size_t alen = gf_utf8_wcstombs(szLine, 2048, (const unsigned short**) & src);
szLine[alen] = 0;
strlwr(szLine);
if (!strncmp(szLine, "<font ", 6) ) {
char *a_sep = strstr(szLine, "color");
if (a_sep) a_sep = strchr(a_sep, '"');
if (a_sep) {
char *e_sep = strchr(a_sep+1, '"');
if (e_sep) {
e_sep[0] = 0;
font_style = gf_color_parse(a_sep+1);
e_sep[0] = '"';
e_sep = strchr(e_sep+1, '>');
if (e_sep) {
style_nb_chars = (u32) (1 + e_sep - szLine);
style_def_type = 1;
}
}
}
}
else if (!strncmp(szLine, "</font>", 7) ) {
style_nb_chars = 7;
style_def_type = 2;
font_style = 0xFFFFFFFF;
}
//skip unknown
else {
char *a_sep = strstr(szLine, ">");
if (a_sep) {
style_nb_chars = (u32) (a_sep - szLine);
i += style_nb_chars;
continue;
}
}
}
/*start of new style*/
if (style_def_type==1) {
/*store prev style*/
if (set_end_char) {
assert(set_start_char);
gf_isom_text_add_style(samp, &rec);
set_end_char = set_start_char = GF_FALSE;
rec.style_flags &= ~rem_styles;
rem_styles = 0;
if (rem_color) {
rec.text_color = default_color;
rem_color = 0;
}
}
if (set_start_char && (rec.startCharOffset != j)) {
rec.endCharOffset = char_len + j;
if (rec.style_flags) gf_isom_text_add_style(samp, &rec);
}
switch (uniLine[i+1]) {
case 'b':
case 'B':
rec.style_flags |= GF_TXT_STYLE_BOLD;
set_start_char = GF_TRUE;
rec.startCharOffset = char_len + j;
break;
case 'i':
case 'I':
rec.style_flags |= GF_TXT_STYLE_ITALIC;
set_start_char = GF_TRUE;
rec.startCharOffset = char_len + j;
break;
case 'u':
case 'U':
rec.style_flags |= GF_TXT_STYLE_UNDERLINED;
set_start_char = GF_TRUE;
rec.startCharOffset = char_len + j;
break;
case 'f':
case 'F':
if (font_style) {
rec.text_color = font_style;
set_start_char = GF_TRUE;
rec.startCharOffset = char_len + j;
}
break;
}
i += style_nb_chars;
continue;
}
/*end of prev style*/
if (style_def_type==2) {
switch (uniLine[i+2]) {
case 'b':
case 'B':
rem_styles |= GF_TXT_STYLE_BOLD;
set_end_char = GF_TRUE;
rec.endCharOffset = char_len + j;
break;
case 'i':
case 'I':
rem_styles |= GF_TXT_STYLE_ITALIC;
set_end_char = GF_TRUE;
rec.endCharOffset = char_len + j;
break;
case 'u':
case 'U':
rem_styles |= GF_TXT_STYLE_UNDERLINED;
set_end_char = GF_TRUE;
rec.endCharOffset = char_len + j;
break;
case 'f':
case 'F':
if (font_style) {
rem_color = 1;
set_end_char = GF_TRUE;
rec.endCharOffset = char_len + j;
}
}
i+=style_nb_chars;
continue;
}
/*store style*/
if (set_end_char) {
gf_isom_text_add_style(samp, &rec);
set_end_char = GF_FALSE;
set_start_char = GF_TRUE;
rec.startCharOffset = char_len + j;
rec.style_flags &= ~rem_styles;
rem_styles = 0;
rec.text_color = default_color;
rem_color = 0;
}
uniText[j] = uniLine[i];
j++;
i++;
}
/*store last style*/
if (set_end_char) {
gf_isom_text_add_style(samp, &rec);
set_end_char = GF_FALSE;
set_start_char = GF_TRUE;
rec.startCharOffset = char_len + j;
rec.style_flags &= ~rem_styles;
}
char_line = j;
uniText[j] = 0;
sptr = (u16 *) uniText;
len = (u32) gf_utf8_wcstombs(szText, 5000, (const u16 **) &sptr);
gf_isom_text_add_text(samp, szText, len);
char_len += char_line;
txt_line ++;
break;
}
if (duration && (start >= duration)) {
end = 0;
break;
}
}
/*final flush*/
if (end && !(import->flags & GF_IMPORT_NO_TEXT_FLUSH ) ) {
gf_isom_text_reset(samp);
s = gf_isom_text_to_sample(samp);
s->DTS = (u64) ((timescale*end)/1000);
s->IsRAP = RAP;
gf_isom_add_sample(import->dest, track, 1, s);
gf_isom_sample_del(&s);
nb_samp++;
gf_isom_set_last_sample_duration(import->dest, track, 0);
} else {
if (duration && (start >= duration)) {
gf_isom_set_last_sample_duration(import->dest, track, (timescale*duration)/1000);
} else {
gf_isom_set_last_sample_duration(import->dest, track, 0);
}
}
gf_isom_delete_text_sample(samp);
gf_set_progress("Importing SRT", nb_samp, nb_samp);
exit:
if (e) gf_isom_remove_track(import->dest, track);
gf_fclose(srt_in);
return e;
}
/* Structure used to pass importer and track data to the parsers without exposing the GF_MediaImporter structure
used by WebVTT and Flash->SVG */
typedef struct {
GF_MediaImporter *import;
u32 timescale;
u32 track;
u32 descriptionIndex;
} GF_ISOFlusher;
#ifndef GPAC_DISABLE_VTT
static GF_Err gf_webvtt_import_report(void *user, GF_Err e, char *message, const char *line)
{
GF_ISOFlusher *flusher = (GF_ISOFlusher *)user;
return gf_import_message(flusher->import, e, message, line);
}
static void gf_webvtt_import_header(void *user, const char *config)
{
GF_ISOFlusher *flusher = (GF_ISOFlusher *)user;
gf_isom_update_webvtt_description(flusher->import->dest, flusher->track, flusher->descriptionIndex, config);
}
static void gf_webvtt_flush_sample_to_iso(void *user, GF_WebVTTSample *samp)
{
GF_ISOSample *s;
GF_ISOFlusher *flusher = (GF_ISOFlusher *)user;
//gf_webvtt_dump_sample(stdout, samp);
s = gf_isom_webvtt_to_sample(samp);
if (s) {
s->DTS = (u64) (flusher->timescale*gf_webvtt_sample_get_start(samp)/1000);
s->IsRAP = RAP;
gf_isom_add_sample(flusher->import->dest, flusher->track, flusher->descriptionIndex, s);
gf_isom_sample_del(&s);
}
gf_webvtt_sample_del(samp);
}
static GF_Err gf_text_import_webvtt(GF_MediaImporter *import)
{
GF_Err e;
u32 track;
u32 timescale;
u32 duration;
u32 descIndex=1;
u32 ID;
u32 OCR_ES_ID;
GF_GenericSubtitleConfig *cfg;
GF_WebVTTParser *vttparser;
GF_ISOFlusher flusher;
cfg = NULL;
if (import->esd) {
if (!import->esd->slConfig) {
import->esd->slConfig = (GF_SLConfig *) gf_odf_desc_new(GF_ODF_SLC_TAG);
import->esd->slConfig->predefined = 2;
import->esd->slConfig->timestampResolution = 1000;
}
timescale = import->esd->slConfig->timestampResolution;
if (!timescale) timescale = 1000;
/*explicit text config*/
if (import->esd->decoderConfig && import->esd->decoderConfig->decoderSpecificInfo->tag == GF_ODF_GEN_SUB_CFG_TAG) {
cfg = (GF_GenericSubtitleConfig *) import->esd->decoderConfig->decoderSpecificInfo;
import->esd->decoderConfig->decoderSpecificInfo = NULL;
}
ID = import->esd->ESID;
OCR_ES_ID = import->esd->OCRESID;
} else {
timescale = 1000;
OCR_ES_ID = ID = 0;
}
if (cfg && cfg->timescale) timescale = cfg->timescale;
track = gf_isom_new_track(import->dest, ID, GF_ISOM_MEDIA_TEXT, timescale);
if (!track) {
return gf_import_message(import, gf_isom_last_error(import->dest), "Error creating WebVTT track");
}
gf_isom_set_track_enabled(import->dest, track, 1);
import->final_trackID = gf_isom_get_track_id(import->dest, track);
if (import->esd && !import->esd->ESID) import->esd->ESID = import->final_trackID;
if (OCR_ES_ID) gf_isom_set_track_reference(import->dest, track, GF_ISOM_REF_OCR, OCR_ES_ID);
/*setup track*/
if (cfg) {
u32 i;
u32 count;
/*set track info*/
gf_isom_set_track_layout_info(import->dest, track, cfg->text_width<<16, cfg->text_height<<16, 0, 0, cfg->layer);
/*and set sample descriptions*/
count = gf_list_count(cfg->sample_descriptions);
for (i=0; i<count; i++) {
gf_isom_new_webvtt_description(import->dest, track, NULL, NULL, NULL, &descIndex);
}
gf_import_message(import, GF_OK, "WebVTT import - text track %d x %d", cfg->text_width, cfg->text_height);
gf_odf_desc_del((GF_Descriptor *)cfg);
} else {
u32 w;
u32 h;
gf_text_get_video_size(import, &w, &h);
gf_isom_set_track_layout_info(import->dest, track, w<<16, h<<16, 0, 0, 0);
gf_isom_new_webvtt_description(import->dest, track, NULL, NULL, NULL, &descIndex);
gf_import_message(import, GF_OK, "WebVTT import");
}
gf_text_import_set_language(import, track);
duration = (u32) (((Double) import->duration)*timescale/1000.0);
vttparser = gf_webvtt_parser_new();
flusher.import = import;
flusher.timescale = timescale;
flusher.track = track;
flusher.descriptionIndex = descIndex;
e = gf_webvtt_parser_init(vttparser, import->in_name, &flusher, gf_webvtt_import_report, gf_webvtt_flush_sample_to_iso, gf_webvtt_import_header);
if (e != GF_OK) {
gf_webvtt_parser_del(vttparser);
return gf_import_message(import, GF_NOT_SUPPORTED, "Unsupported WebVTT UTF encoding");
}
e = gf_webvtt_parser_parse(vttparser, duration);
if (e != GF_OK) {
gf_isom_remove_track(import->dest, track);
}
/*do not add any empty sample at the end since it modifies track duration and is not needed - it is the player job
to figure out when to stop displaying the last text sample
However update the last sample duration*/
gf_isom_set_last_sample_duration(import->dest, track, (u32) gf_webvtt_parser_last_duration(vttparser));
gf_webvtt_parser_del(vttparser);
return e;
}
#endif /*GPAC_DISABLE_VTT*/
static char *ttxt_parse_string(GF_MediaImporter *import, char *str, Bool strip_lines)
{
u32 i=0;
u32 k=0;
u32 len = (u32) strlen(str);
u32 state = 0;
if (!strip_lines) {
for (i=0; i<len; i++) {
if ((str[i] == '\r') && (str[i+1] == '\n')) {
i++;
}
str[k] = str[i];
k++;
}
str[k]=0;
return str;
}
if (str[0]!='\'') return str;
for (i=0; i<len; i++) {
if (str[i] == '\'') {
if (!state) {
if (k) {
str[k]='\n';
k++;
}
state = !state;
} else if (state) {
if ( (i+1==len) ||
((str[i+1]==' ') || (str[i+1]=='\n') || (str[i+1]=='\r') || (str[i+1]=='\t') || (str[i+1]=='\''))
) {
state = !state;
} else {
str[k] = str[i];
k++;
}
}
} else if (state) {
str[k] = str[i];
k++;
}
}
str[k]=0;
return str;
}
static void ttml_import_progress(void *cbk, u64 cur_samp, u64 count)
{
gf_set_progress("TTML Loading", cur_samp, count);
}
static void gf_text_import_ebu_ttd_remove_samples(GF_XMLNode *root, GF_XMLNode **sample_list_node)
{
u32 idx = 0, body_num = 0;
GF_XMLNode *node = NULL;
*sample_list_node = NULL;
while ( (node = (GF_XMLNode*)gf_list_enum(root->content, &idx))) {
if (!strcmp(node->name, "body")) {
GF_XMLNode *body_node;
u32 body_idx = 0;
while ( (body_node = (GF_XMLNode*)gf_list_enum(node->content, &body_idx))) {
if (!strcmp(body_node->name, "div")) {
*sample_list_node = body_node;
body_num = gf_list_count(body_node->content);
while (body_num--) {
GF_XMLNode *content_node = (GF_XMLNode*)gf_list_get(body_node->content, 0);
assert(gf_list_find(body_node->content, content_node) == 0);
gf_list_rem(body_node->content, 0);
gf_xml_dom_node_del(content_node);
}
return;
}
}
}
}
}
#define TTML_NAMESPACE "http://www.w3.org/ns/ttml"
static GF_Err gf_text_import_ebu_ttd(GF_MediaImporter *import, GF_DOMParser *parser, GF_XMLNode *root)
{
GF_Err e, e_opt;
u32 i, track, ID, desc_idx, nb_samples, nb_children;
u64 last_sample_duration, last_sample_end;
GF_XMLAttribute *att;
GF_XMLNode *node, *root_working_copy, *sample_list_node;
GF_DOMParser *parser_working_copy;
char *samp_text;
Bool has_body;
samp_text = NULL;
root_working_copy = NULL;
parser_working_copy = NULL;
/*setup track in 3GP format directly (no ES desc)*/
ID = (import->esd) ? import->esd->ESID : 0;
track = gf_isom_new_track(import->dest, ID, GF_ISOM_MEDIA_MPEG_SUBT, 1000);
if (!track) {
e = gf_isom_last_error(import->dest);
goto exit;
}
gf_isom_set_track_enabled(import->dest, track, 1);
/*some MPEG-4 setup*/
if (import->esd) {
if (!import->esd->ESID) import->esd->ESID = gf_isom_get_track_id(import->dest, track);
if (!import->esd->decoderConfig) import->esd->decoderConfig = (GF_DecoderConfig *) gf_odf_desc_new(GF_ODF_DCD_TAG);
if (!import->esd->slConfig) import->esd->slConfig = (GF_SLConfig *) gf_odf_desc_new(GF_ODF_SLC_TAG);
import->esd->slConfig->timestampResolution = 1000;
import->esd->decoderConfig->streamType = GF_STREAM_TEXT;
import->esd->decoderConfig->objectTypeIndication = GPAC_OTI_TEXT_MPEG4;
if (import->esd->OCRESID) gf_isom_set_track_reference(import->dest, track, GF_ISOM_REF_OCR, import->esd->OCRESID);
}
gf_import_message(import, GF_OK, "TTML EBU-TTD Import");
/*** root (including language) ***/
i=0;
while ( (att = (GF_XMLAttribute *)gf_list_enum(root->attributes, &i))) {
GF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, ("Found root attribute name %s, value %s\n", att->name, att->value));
if (!strcmp(att->name, "xmlns")) {
if (strcmp(att->value, TTML_NAMESPACE)) {
e = gf_import_message(import, GF_BAD_PARAM, "Found invalid EBU-TTD root attribute name %s, value %s (shall be \"%s\")\n", att->name, att->value, TTML_NAMESPACE);
goto exit;
}
} else if (!strcmp(att->name, "xml:lang")) {
if (import->esd && !import->esd->langDesc) {
char *lang;
lang = gf_strdup(att->value);
import->esd->langDesc = (GF_Language *) gf_odf_desc_new(GF_ODF_LANG_TAG);
gf_isom_set_media_language(import->dest, track, lang);
} else {
gf_isom_set_media_language(import->dest, track, att->value);
}
}
}
/*** style ***/
#if 0
{
Bool has_styling, has_style;
GF_TextSampleDescriptor *sd;
has_styling = GF_FALSE;
has_style = GF_FALSE;
sd = (GF_TextSampleDescriptor*)gf_odf_desc_new(GF_ODF_TX3G_TAG);
i=0;
while ( (node = (GF_XMLNode*)gf_list_enum(root->content, &i))) {
if (node->type) {
continue;
} else if (gf_xml_get_element_check_namespace(node, "head", root->ns) == GF_OK) {
GF_XMLNode *head_node;
u32 head_idx = 0;
while ( (head_node = (GF_XMLNode*)gf_list_enum(node->content, &head_idx))) {
if (gf_xml_get_element_check_namespace(head_node, "styling", root->ns) == GF_OK) {
GF_XMLNode *styling_node;
u32 styling_idx;
if (has_styling) {
e = gf_import_message(import, GF_BAD_PARAM, "[TTML EBU-TTD] duplicated \"styling\" element. Abort.\n");
goto exit;
}
has_styling = GF_TRUE;
styling_idx = 0;
while ( (styling_node = (GF_XMLNode*)gf_list_enum(head_node->content, &styling_idx))) {
if (gf_xml_get_element_check_namespace(styling_node, "style", root->ns) == GF_OK) {
GF_XMLAttribute *p_att;
u32 style_idx = 0;
while ( (p_att = (GF_XMLAttribute*)gf_list_enum(styling_node->attributes, &style_idx))) {
if (!strcmp(p_att->name, "tts:direction")) {
} else if (!strcmp(p_att->name, "tts:fontFamily")) {
sd->fonts = (GF_FontRecord*)gf_malloc(sizeof(GF_FontRecord));
sd->font_count = 1;
sd->fonts[0].fontID = 1;
sd->fonts[0].fontName = gf_strdup(p_att->value);
} else if (!strcmp(p_att->name, "tts:backgroundColor")) {
GF_LOG(GF_LOG_INFO, GF_LOG_PARSER, ("EBU-TTD style attribute \"%s\" ignored.\n", p_att->name));
//sd->back_color = ;
} else {
if ( !strcmp(p_att->name, "tts:fontSize")
|| !strcmp(p_att->name, "tts:lineHeight")
|| !strcmp(p_att->name, "tts:textAlign")
|| !strcmp(p_att->name, "tts:color")
|| !strcmp(p_att->name, "tts:fontStyle")
|| !strcmp(p_att->name, "tts:fontWeight")
|| !strcmp(p_att->name, "tts:textDecoration")
|| !strcmp(p_att->name, "tts:unicodeBidi")
|| !strcmp(p_att->name, "tts:wrapOption")
|| !strcmp(p_att->name, "tts:multiRowAlign")
|| !strcmp(p_att->name, "tts:linePadding")) {
GF_LOG(GF_LOG_INFO, GF_LOG_PARSER, ("EBU-TTD style attribute \"%s\" ignored.\n", p_att->name));
} else {
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("EBU-TTD unknown style attribute: \"%s\". Ignoring.\n", p_att->name));
}
}
}
break; //TODO: we only take care of the first style
}
}
}
}
}
}
if (!has_styling) {
e = gf_import_message(import, GF_BAD_PARAM, "[TTML EBU-TTD] missing \"styling\" element. Abort.\n");
goto exit;
}
if (!has_style) {
e = gf_import_message(import, GF_BAD_PARAM, "[TTML EBU-TTD] missing \"style\" element. Abort.\n");
goto exit;
}
e = gf_isom_new_text_description(import->dest, track, sd, NULL, NULL, &desc_idx);
gf_odf_desc_del((GF_Descriptor*)sd);
}
#else
e = gf_isom_new_xml_subtitle_description(import->dest, track, TTML_NAMESPACE, NULL, NULL, &desc_idx);
#endif
if (e != GF_OK) {
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTML EBU-TTD] incorrect sample description. Abort.\n"));
e = gf_isom_last_error(import->dest);
goto exit;
}
/*** body ***/
parser_working_copy = gf_xml_dom_new();
e = gf_xml_dom_parse(parser_working_copy, import->in_name, NULL, NULL);
assert (e == GF_OK);
root_working_copy = gf_xml_dom_get_root(parser_working_copy);
assert(root_working_copy);
last_sample_duration = 0;
last_sample_end = 0;
nb_samples = 0;
nb_children = gf_list_count(root->content);
has_body = GF_FALSE;
i=0;
while ( (node = (GF_XMLNode*)gf_list_enum(root->content, &i))) {
if (node->type) {
nb_children--;
continue;
}
e_opt = gf_xml_get_element_check_namespace(node, "body", root->ns);
if (e_opt == GF_BAD_PARAM) {
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTML EBU-TTD] ignored \"%s\" node, check your namespaces\n", node->name));
} else if (e_opt == GF_OK) {
GF_XMLNode *body_node;
u32 body_idx = 0;
if (has_body) {
e = gf_import_message(import, GF_BAD_PARAM, "[TTML EBU-TTD] duplicated \"body\" element. Abort.\n");
goto exit;
}
has_body = GF_TRUE;
/*remove all the entries from the working copy, we'll add samples one to one to create full XML samples*/
gf_text_import_ebu_ttd_remove_samples(root_working_copy, &sample_list_node);
while ( (body_node = (GF_XMLNode*)gf_list_enum(node->content, &body_idx))) {
e_opt = gf_xml_get_element_check_namespace(body_node, "div", root->ns);
if (e_opt == GF_BAD_PARAM) {
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTML EBU-TTD] ignored \"%s\" node, check your namespaces\n", node->name));
} else if (e_opt == GF_OK) {
GF_XMLNode *div_node;
u32 div_idx = 0, nb_p_found = 0;
while ( (div_node = (GF_XMLNode*)gf_list_enum(body_node->content, &div_idx))) {
e_opt = gf_xml_get_element_check_namespace(div_node, "p", root->ns);
if (e_opt != GF_OK) {
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTML] ignored \"%s\" node, check your namespaces\n", node->name));
} else if (e_opt == GF_OK) {
GF_XMLNode *p_node;
GF_XMLAttribute *p_att;
u32 p_idx = 0, h, m, s, f, ms;
s64 ts_begin = -1, ts_end = -1;
//sample is either in the <p> ...
while ( (p_att = (GF_XMLAttribute*)gf_list_enum(div_node->attributes, &p_idx))) {
if (!p_att) continue;
if (!strcmp(p_att->name, "begin")) {
if (ts_begin != -1) {
e = gf_import_message(import, GF_BAD_PARAM, "[TTML] duplicated \"begin\" attribute. Abort.\n");
goto exit;
}
if (sscanf(p_att->value, "%u:%u:%u.%u", &h, &m, &s, &ms) == 4) {
ts_begin = (h*3600 + m*60+s)*1000+ms;
} else if (sscanf(p_att->value, "%u:%u:%u:%u", &h, &m, &s, &f) == 4) {
ts_begin = (h*3600 + m*60+s)*1000+f*40;
} else if (sscanf(p_att->value, "%u:%u:%u", &h, &m, &s) == 3) {
ts_begin = (h*3600 + m*60+s)*1000;
}
} else if (!strcmp(p_att->name, "end")) {
if (ts_end != -1) {
e = gf_import_message(import, GF_BAD_PARAM, "[TTML] duplicated \"end\" attribute. Abort.\n");
goto exit;
}
if (sscanf(p_att->value, "%u:%u:%u.%u", &h, &m, &s, &ms) == 4) {
ts_end = (h*3600 + m*60+s)*1000+ms;
} else if (sscanf(p_att->value, "%u:%u:%u:%u", &h, &m, &s, &f) == 4) {
ts_end = (h*3600 + m*60+s)*1000+f*40;
} else if (sscanf(p_att->value, "%u:%u:%u", &h, &m, &s) == 3) {
ts_end = (h*3600 + m*60+s)*1000;
}
}
if ((ts_begin != -1) && (ts_end != -1) && !samp_text && sample_list_node) {
e = gf_xml_dom_append_child(sample_list_node, div_node);
assert(e == GF_OK);
assert(!samp_text);
samp_text = gf_xml_dom_serialize((GF_XMLNode*)root_working_copy, GF_FALSE);
e = gf_xml_dom_rem_child(sample_list_node, div_node);
assert(e == GF_OK);
}
}
//or under a <span>
p_idx = 0;
while ( (p_node = (GF_XMLNode*)gf_list_enum(div_node->content, &p_idx))) {
e_opt = gf_xml_get_element_check_namespace(p_node, "span", root->ns);
if (e_opt == GF_BAD_PARAM) {
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTML] ignored \"%s\" node, check your namespaces\n", node->name));
} else if (e_opt == GF_OK) {
u32 span_idx = 0;
GF_XMLAttribute *span_att;
while ( (span_att = (GF_XMLAttribute*)gf_list_enum(p_node->attributes, &span_idx))) {
if (!span_att) continue;
if (!strcmp(span_att->name, "begin")) {
if (ts_begin != -1) {
e = gf_import_message(import, GF_BAD_PARAM, "[TTML] duplicated \"begin\" attribute under <span>. Abort.\n");
goto exit;
}
if (sscanf(span_att->value, "%u:%u:%u.%u", &h, &m, &s, &ms) == 4) {
ts_begin = (h*3600 + m*60+s)*1000+ms;
} else if (sscanf(p_att->value, "%u:%u:%u:%u", &h, &m, &s, &f) == 4) {
ts_begin = (h*3600 + m*60+s)*1000+f*40;
} else if (sscanf(span_att->value, "%u:%u:%u", &h, &m, &s) == 3) {
ts_begin = (h*3600 + m*60+s)*1000;
}
} else if (!strcmp(span_att->name, "end")) {
if (ts_end != -1) {
e = gf_import_message(import, GF_BAD_PARAM, "[TTML] duplicated \"end\" attribute under <span>. Abort.\n");
goto exit;
}
if (sscanf(span_att->value, "%u:%u:%u.%u", &h, &m, &s, &ms) == 4) {
ts_end = (h*3600 + m*60+s)*1000+ms;
} else if (sscanf(p_att->value, "%u:%u:%u:%u", &h, &m, &s, &f) == 4) {
ts_end = (h*3600 + m*60+s)*1000+f*40;
} else if (sscanf(span_att->value, "%u:%u:%u", &h, &m, &s) == 3) {
ts_end = (h*3600 + m*60+s)*1000;
}
}
if ((ts_begin != -1) && (ts_end != -1) && !samp_text && sample_list_node) {
if (samp_text) {
e = gf_import_message(import, GF_BAD_PARAM, "[TTML] duplicated sample text under <span>. Abort.\n");
goto exit;
}
/*append the sample*/
e = gf_xml_dom_append_child(sample_list_node, div_node);
assert(e == GF_OK);
assert(!samp_text);
samp_text = gf_xml_dom_serialize((GF_XMLNode*)root_working_copy, GF_FALSE);
e = gf_xml_dom_rem_child(sample_list_node, div_node);
assert(e == GF_OK);
}
}
}
}
if ((ts_begin != -1) && (ts_end != -1) && samp_text) {
GF_ISOSample *s;
GF_GenericSubtitleSample *samp;
u32 len;
char *str;
if (ts_end < ts_begin) {
e = gf_import_message(import, GF_BAD_PARAM, "[TTML] invalid timings: \"begin\"="LLD" , \"end\"="LLD". Abort.\n", ts_begin, ts_end);
goto exit;
}
if (ts_begin < (s64)last_sample_end) {
e = gf_import_message(import, GF_BAD_PARAM, "[TTML] timing overlapping not supported: \"begin\" is "LLD" , last \"end\" was "LLD". Abort.\n", ts_begin, last_sample_end);
goto exit;
}
str = ttxt_parse_string(import, samp_text, GF_TRUE);
len = (u32) strlen(str);
samp = gf_isom_new_xml_subtitle_sample();
/*each sample consists of a full valid XML file*/
e = gf_isom_xml_subtitle_sample_add_text(samp, str, len);
if (e) {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[TTML] ISOM - sample add text: %s", gf_error_to_string(e)));
goto exit;
}
gf_free(samp_text);
samp_text = NULL;
s = gf_isom_xml_subtitle_to_sample(samp);
gf_isom_delete_xml_subtitle_sample(samp);
if (!nb_samples) {
s->DTS = 0; /*in MP4 we must start at T=0*/
last_sample_duration = ts_end;
} else {
s->DTS = ts_begin;
last_sample_duration = ts_end - ts_begin;
}
last_sample_end = ts_end;
GF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, ("ts_begin="LLD", ts_end="LLD", last_sample_duration="LLU" (real duration: "LLU"), last_sample_end="LLU"\n", ts_begin, ts_end, ts_end - last_sample_end, last_sample_duration, last_sample_end));
e = gf_isom_add_sample(import->dest, track, desc_idx, s);
if (e) {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[TTML] ISOM - Add Sample: %s", gf_error_to_string(e)));
goto exit;
}
gf_isom_sample_del(&s);
nb_samples++;
nb_p_found++;
gf_set_progress("Importing TTML", nb_samples, nb_children);
if (import->duration && (ts_end > import->duration))
break;
} else {
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTML] incomplete sample (begin="LLD", end="LLD", text=\"%s\"). Skip.\n", ts_begin, ts_end, samp_text ? samp_text : "NULL"));
}
}
}
if (!nb_p_found) {
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTML EBU-TTD] \"%s\" div node has no <p> elements. Aborting.\n", node->name));
goto exit;
}
}
}
}
}
if (!has_body) {
e = gf_import_message(import, GF_BAD_PARAM, "[TTML EBU-TTD] missing \"body\" element. Abort.\n");
goto exit;
}
GF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, ("last_sample_duration="LLU", last_sample_end="LLU"\n", last_sample_duration, last_sample_end));
gf_isom_set_last_sample_duration(import->dest, track, (u32) last_sample_duration);
gf_media_update_bitrate(import->dest, track);
gf_set_progress("Importing TTML EBU-TTD", nb_samples, nb_samples);
exit:
gf_free(samp_text);
gf_xml_dom_del(parser_working_copy);
if (!gf_isom_get_sample_count(import->dest, track)) {
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTML EBU-TTD] No sample imported. Might be an error. Check your content.\n"));
}
return e;
}
static GF_Err gf_text_import_ttml(GF_MediaImporter *import)
{
GF_Err e;
GF_DOMParser *parser;
GF_XMLNode *root;
if (import->flags == GF_IMPORT_PROBE_ONLY)
return GF_OK;
parser = gf_xml_dom_new();
e = gf_xml_dom_parse(parser, import->in_name, ttml_import_progress, import);
if (e) {
gf_import_message(import, e, "Error parsing TTML file: Line %d - %s. Abort.", gf_xml_dom_get_line(parser), gf_xml_dom_get_error(parser));
gf_xml_dom_del(parser);
return e;
}
root = gf_xml_dom_get_root(parser);
if (!root) {
gf_import_message(import, e, "Error parsing TTML file: no \"root\" found. Abort.");
gf_xml_dom_del(parser);
return e;
}
/*look for TTML*/
if (gf_xml_get_element_check_namespace(root, "tt", NULL) == GF_OK) {
e = gf_text_import_ebu_ttd(import, parser, root);
if (e == GF_OK) {
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("Note: TTML import - EBU-TTD detected\n"));
} else {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("Parsing TTML file with error: %s\n", gf_error_to_string(e)));
GF_LOG(GF_LOG_INFO, GF_LOG_PARSER, ("Unsupported TTML file - only EBU-TTD is supported (root shall be \"tt\", got \"%s\")\n", root->name));
GF_LOG(GF_LOG_INFO, GF_LOG_PARSER, ("Importing as generic TTML\n"));
e = GF_OK;
}
} else {
if (root->ns) {
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("TTML file not recognized: root element is \"%s:%s\" (check your namespaces)\n", root->ns, root->name));
} else {
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("TTML file not recognized: root element is \"%s\"\n", root->name));
}
e = GF_BAD_PARAM;
}
gf_xml_dom_del(parser);
return e;
}
/* SimpleText Text tracks -related functions */
GF_Box *boxstring_new_with_data(u32 type, const char *string);
#ifndef GPAC_DISABLE_SWF_IMPORT
/* SWF Importer */
#include <gpac/internal/swf_dev.h>
static GF_Err swf_svg_add_iso_sample(void *user, const char *data, u32 length, u64 timestamp, Bool isRap)
{
GF_Err e = GF_OK;
GF_ISOFlusher *flusher = (GF_ISOFlusher *)user;
GF_ISOSample *s;
GF_BitStream *bs;
bs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);
if (!bs) return GF_BAD_PARAM;
gf_bs_write_data(bs, data, length);
s = gf_isom_sample_new();
if (s) {
gf_bs_get_content(bs, &s->data, &s->dataLength);
s->DTS = (u64) (flusher->timescale*timestamp/1000);
s->IsRAP = isRap ? RAP : RAP_NO;
gf_isom_add_sample(flusher->import->dest, flusher->track, flusher->descriptionIndex, s);
gf_isom_sample_del(&s);
} else {
e = GF_BAD_PARAM;
}
gf_bs_del(bs);
return e;
}
static GF_Err swf_svg_add_iso_header(void *user, const char *data, u32 length, Bool isHeader)
{
GF_ISOFlusher *flusher = (GF_ISOFlusher *)user;
if (!flusher) return GF_BAD_PARAM;
if (isHeader) {
return gf_isom_update_stxt_description(flusher->import->dest, flusher->track, NULL, data, flusher->descriptionIndex);
} else {
return gf_isom_append_sample_data(flusher->import->dest, flusher->track, (char *)data, length);
}
}
GF_EXPORT
GF_Err gf_text_import_swf(GF_MediaImporter *import)
{
GF_Err e = GF_OK;
u32 track;
u32 timescale;
//u32 duration;
u32 descIndex;
u32 ID;
u32 OCR_ES_ID;
GF_GenericSubtitleConfig *cfg;
SWFReader *read;
GF_ISOFlusher flusher;
char *mime;
if (import->flags & GF_IMPORT_PROBE_ONLY) {
import->nb_tracks = 1;
return GF_OK;
}
cfg = NULL;
if (import->esd) {
if (!import->esd->slConfig) {
import->esd->slConfig = (GF_SLConfig *) gf_odf_desc_new(GF_ODF_SLC_TAG);
import->esd->slConfig->predefined = 2;
import->esd->slConfig->timestampResolution = 1000;
}
timescale = import->esd->slConfig->timestampResolution;
if (!timescale) timescale = 1000;
/*explicit text config*/
if (import->esd->decoderConfig && import->esd->decoderConfig->decoderSpecificInfo->tag == GF_ODF_GEN_SUB_CFG_TAG) {
cfg = (GF_GenericSubtitleConfig *) import->esd->decoderConfig->decoderSpecificInfo;
import->esd->decoderConfig->decoderSpecificInfo = NULL;
}
ID = import->esd->ESID;
OCR_ES_ID = import->esd->OCRESID;
} else {
timescale = 1000;
OCR_ES_ID = ID = 0;
}
if (cfg && cfg->timescale) timescale = cfg->timescale;
track = gf_isom_new_track(import->dest, ID, GF_ISOM_MEDIA_TEXT, timescale);
if (!track) {
return gf_import_message(import, gf_isom_last_error(import->dest), "Error creating text track");
}
gf_isom_set_track_enabled(import->dest, track, 1);
if (import->esd && !import->esd->ESID) import->esd->ESID = gf_isom_get_track_id(import->dest, track);
if (OCR_ES_ID) gf_isom_set_track_reference(import->dest, track, GF_ISOM_REF_OCR, OCR_ES_ID);
if (!stricmp(import->streamFormat, "SVG")) {
mime = "image/svg+xml";
} else {
mime = "application/octet-stream";
}
read = gf_swf_reader_new(NULL, import->in_name);
gf_swf_read_header(read);
/*setup track*/
if (cfg) {
u32 i;
u32 count;
/*set track info*/
gf_isom_set_track_layout_info(import->dest, track, cfg->text_width<<16, cfg->text_height<<16, 0, 0, cfg->layer);
/*and set sample descriptions*/
count = gf_list_count(cfg->sample_descriptions);
for (i=0; i<count; i++) {
gf_isom_new_stxt_description(import->dest, track, GF_ISOM_SUBTYPE_STXT, mime, NULL, NULL, &descIndex);
}
gf_import_message(import, GF_OK, "SWF import - text track %d x %d", cfg->text_width, cfg->text_height);
gf_odf_desc_del((GF_Descriptor *)cfg);
} else {
u32 w = (u32)read->width;
u32 h = (u32)read->height;
if (!w || !h)
gf_text_get_video_size(import, &w, &h);
gf_isom_set_track_layout_info(import->dest, track, w<<16, h<<16, 0, 0, 0);
gf_isom_new_stxt_description(import->dest, track, GF_ISOM_SUBTYPE_STXT, mime, NULL, NULL, &descIndex);
gf_import_message(import, GF_OK, "SWF import (as text - type: %s)", import->streamFormat);
}
gf_text_import_set_language(import, track);
//duration = (u32) (((Double) import->duration)*timescale/1000.0);
flusher.import = import;
flusher.track = track;
flusher.timescale = timescale;
flusher.descriptionIndex = descIndex;
gf_swf_reader_set_user_mode(read, &flusher, swf_svg_add_iso_sample, swf_svg_add_iso_header);
if (!import->streamFormat || (import->streamFormat && !stricmp(import->streamFormat, "SVG"))) {
#ifndef GPAC_DISABLE_SVG
e = swf_to_svg_init(read, import->swf_flags, import->swf_flatten_angle);
#endif
} else { /*if (import->streamFormat && !strcmp(import->streamFormat, "BIFS"))*/
#ifndef GPAC_DISABLE_VRML
e = swf_to_bifs_init(read);
#endif
}
if (e) {
goto exit;
}
/*parse all tags*/
while (e == GF_OK) {
e = swf_parse_tag(read);
}
if (e==GF_EOS) e = GF_OK;
exit:
gf_swf_reader_del(read);
gf_media_update_bitrate(import->dest, track);
return e;
}
/* end of SWF Importer */
#else
GF_EXPORT
GF_Err gf_text_import_swf(GF_MediaImporter *import)
{
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("Warning: GPAC was compiled without SWF import support, can't import track.\n"));
return GF_NOT_SUPPORTED;
}
#endif /*GPAC_DISABLE_SWF_IMPORT*/
static GF_Err gf_text_import_sub(GF_MediaImporter *import)
{
FILE *sub_in;
u32 track, ID, timescale, i, j, desc_idx, start, end, prev_end, nb_samp, duration, len, line;
u64 file_size;
GF_TextConfig*cfg;
GF_Err e;
Double FPS;
GF_TextSample * samp;
Bool first_samp;
s32 unicode_type;
char szLine[2048], szTime[20], szText[2048];
GF_ISOSample *s;
sub_in = gf_fopen(import->in_name, "rt");
unicode_type = gf_text_get_utf_type(sub_in);
if (unicode_type<0) {
gf_fclose(sub_in);
return gf_import_message(import, GF_NOT_SUPPORTED, "Unsupported SUB UTF encoding");
}
FPS = GF_IMPORT_DEFAULT_FPS;
if (import->video_fps) FPS = import->video_fps;
cfg = NULL;
if (import->esd) {
if (!import->esd->slConfig) {
import->esd->slConfig = (GF_SLConfig *) gf_odf_desc_new(GF_ODF_SLC_TAG);
import->esd->slConfig->predefined = 2;
import->esd->slConfig->timestampResolution = 1000;
}
timescale = import->esd->slConfig->timestampResolution;
if (!timescale) timescale = 1000;
/*explicit text config*/
if (import->esd->decoderConfig && import->esd->decoderConfig->decoderSpecificInfo->tag == GF_ODF_TEXT_CFG_TAG) {
cfg = (GF_TextConfig *) import->esd->decoderConfig->decoderSpecificInfo;
import->esd->decoderConfig->decoderSpecificInfo = NULL;
}
ID = import->esd->ESID;
} else {
timescale = 1000;
ID = 0;
}
if (cfg && cfg->timescale) timescale = cfg->timescale;
track = gf_isom_new_track(import->dest, ID, GF_ISOM_MEDIA_TEXT, timescale);
if (!track) {
gf_fclose(sub_in);
return gf_import_message(import, gf_isom_last_error(import->dest), "Error creating text track");
}
gf_isom_set_track_enabled(import->dest, track, 1);
if (import->esd && !import->esd->ESID) import->esd->ESID = gf_isom_get_track_id(import->dest, track);
gf_text_import_set_language(import, track);
file_size = 0;
/*setup track*/
if (cfg) {
u32 count;
char *firstFont = NULL;
/*set track info*/
gf_isom_set_track_layout_info(import->dest, track, cfg->text_width<<16, cfg->text_height<<16, 0, 0, cfg->layer);
/*and set sample descriptions*/
count = gf_list_count(cfg->sample_descriptions);
for (i=0; i<count; i++) {
GF_TextSampleDescriptor *sd= (GF_TextSampleDescriptor *)gf_list_get(cfg->sample_descriptions, i);
if (!sd->font_count) {
sd->fonts = (GF_FontRecord*)gf_malloc(sizeof(GF_FontRecord));
sd->font_count = 1;
sd->fonts[0].fontID = 1;
sd->fonts[0].fontName = gf_strdup("Serif");
}
if (!sd->default_style.fontID) sd->default_style.fontID = sd->fonts[0].fontID;
if (!sd->default_style.font_size) sd->default_style.font_size = 16;
if (!sd->default_style.text_color) sd->default_style.text_color = 0xFF000000;
file_size = sd->default_style.font_size;
gf_isom_new_text_description(import->dest, track, sd, NULL, NULL, &desc_idx);
if (!firstFont) firstFont = sd->fonts[0].fontName;
}
gf_import_message(import, GF_OK, "Timed Text (SUB @ %02.2f) import - text track %d x %d, font %s (size %d)", FPS, cfg->text_width, cfg->text_height, firstFont, file_size);
gf_odf_desc_del((GF_Descriptor *)cfg);
} else {
u32 w, h;
GF_TextSampleDescriptor *sd;
gf_text_get_video_size(import, &w, &h);
/*have to work with default - use max size (if only one video, this means the text region is the
entire display, and with bottom alignment things should be fine...*/
gf_isom_set_track_layout_info(import->dest, track, w<<16, h<<16, 0, 0, 0);
sd = (GF_TextSampleDescriptor*)gf_odf_desc_new(GF_ODF_TX3G_TAG);
sd->fonts = (GF_FontRecord*)gf_malloc(sizeof(GF_FontRecord));
sd->font_count = 1;
sd->fonts[0].fontID = 1;
sd->fonts[0].fontName = gf_strdup("Serif");
sd->back_color = 0x00000000; /*transparent*/
sd->default_style.fontID = 1;
sd->default_style.font_size = TTXT_DEFAULT_FONT_SIZE;
sd->default_style.text_color = 0xFFFFFFFF; /*white*/
sd->default_style.style_flags = 0;
sd->horiz_justif = 1; /*center of scene*/
sd->vert_justif = (s8) -1; /*bottom of scene*/
if (import->flags & GF_IMPORT_SKIP_TXT_BOX) {
sd->default_pos.top = sd->default_pos.left = sd->default_pos.right = sd->default_pos.bottom = 0;
} else {
if ((sd->default_pos.bottom==sd->default_pos.top) || (sd->default_pos.right==sd->default_pos.left)) {
sd->default_pos.left = import->text_x;
sd->default_pos.top = import->text_y;
sd->default_pos.right = (import->text_width ? import->text_width : w) + sd->default_pos.left;
sd->default_pos.bottom = (import->text_height ? import->text_height : h) + sd->default_pos.top;
}
}
gf_isom_new_text_description(import->dest, track, sd, NULL, NULL, &desc_idx);
gf_import_message(import, GF_OK, "Timed Text (SUB @ %02.2f) import - text track %d x %d, font %s (size %d)", FPS, w, h, sd->fonts[0].fontName, TTXT_DEFAULT_FONT_SIZE);
gf_odf_desc_del((GF_Descriptor *)sd);
}
duration = (u32) (((Double) import->duration)*timescale/1000.0);
e = GF_OK;
nb_samp = 0;
samp = gf_isom_new_text_sample();
FPS = ((Double) timescale ) / FPS;
end = prev_end = 0;
line = 0;
first_samp = GF_TRUE;
while (1) {
char *sOK = gf_text_get_utf8_line(szLine, 2048, sub_in, unicode_type);
if (!sOK) break;
REM_TRAIL_MARKS(szLine, "\r\n\t ")
line++;
len = (u32) strlen(szLine);
if (!len) continue;
i=0;
if (szLine[i] != '{') {
e = gf_import_message(import, GF_NON_COMPLIANT_BITSTREAM, "Bad SUB file (line %d): expecting \"{\" got \"%c\"", line, szLine[i]);
goto exit;
}
while (szLine[i+1] && szLine[i+1]!='}') {
szTime[i] = szLine[i+1];
i++;
}
szTime[i] = 0;
start = atoi(szTime);
if (start<end) {
gf_import_message(import, GF_OK, "WARNING: corrupted SUB frame (line %d) - starts (at %d ms) before end of previous one (%d ms) - adjusting time stamps", line, start, end);
start = end;
}
j=i+2;
i=0;
if (szLine[i+j] != '{') {
e = gf_import_message(import, GF_NON_COMPLIANT_BITSTREAM, "Bad SUB file - expecting \"{\" got \"%c\"", szLine[i]);
goto exit;
}
while (szLine[i+1+j] && szLine[i+1+j]!='}') {
szTime[i] = szLine[i+1+j];
i++;
}
szTime[i] = 0;
end = atoi(szTime);
j+=i+2;
if (start>end) {
gf_import_message(import, GF_OK, "WARNING: corrupted SUB frame (line %d) - ends (at %d ms) before start of current frame (%d ms) - skipping", line, end, start);
continue;
}
gf_isom_text_reset(samp);
if (start && first_samp) {
s = gf_isom_text_to_sample(samp);
s->DTS = 0;
s->IsRAP = RAP;
gf_isom_add_sample(import->dest, track, 1, s);
gf_isom_sample_del(&s);
first_samp = GF_FALSE;
nb_samp++;
}
for (i=j; i<len; i++) {
if (szLine[i]=='|') {
szText[i-j] = '\n';
} else {
szText[i-j] = szLine[i];
}
}
szText[i-j] = 0;
gf_isom_text_add_text(samp, szText, (u32) strlen(szText) );
if (prev_end) {
GF_TextSample * empty_samp = gf_isom_new_text_sample();
s = gf_isom_text_to_sample(empty_samp);
s->DTS = (u64) (FPS*(s64)prev_end);
gf_isom_add_sample(import->dest, track, 1, s);
gf_isom_sample_del(&s);
nb_samp++;
gf_isom_delete_text_sample(empty_samp);
}
s = gf_isom_text_to_sample(samp);
s->DTS = (u64) (FPS*(s64)start);
gf_isom_add_sample(import->dest, track, 1, s);
gf_isom_sample_del(&s);
nb_samp++;
gf_isom_text_reset(samp);
prev_end = end;
gf_set_progress("Importing SUB", gf_ftell(sub_in), file_size);
if (duration && (end >= duration)) break;
}
/*final flush*/
if (end && !(import->flags & GF_IMPORT_NO_TEXT_FLUSH ) ) {
gf_isom_text_reset(samp);
s = gf_isom_text_to_sample(samp);
s->DTS = (u64)(FPS*(s64)end);
gf_isom_add_sample(import->dest, track, 1, s);
gf_isom_sample_del(&s);
nb_samp++;
}
gf_isom_delete_text_sample(samp);
gf_isom_set_last_sample_duration(import->dest, track, 0);
gf_set_progress("Importing SUB", nb_samp, nb_samp);
exit:
if (e) gf_isom_remove_track(import->dest, track);
gf_fclose(sub_in);
return e;
}
#define CHECK_STR(__str) \
if (!__str) { \
e = gf_import_message(import, GF_BAD_PARAM, "Invalid XML formatting (line %d)", parser.line); \
goto exit; \
} \
u32 ttxt_get_color(GF_MediaImporter *import, char *val)
{
u32 r, g, b, a, res;
r = g = b = a = 0;
if (sscanf(val, "%x %x %x %x", &r, &g, &b, &a) != 4) {
gf_import_message(import, GF_OK, "Warning: color badly formatted");
}
res = (a&0xFF);
res<<=8;
res |= (r&0xFF);
res<<=8;
res |= (g&0xFF);
res<<=8;
res |= (b&0xFF);
return res;
}
void ttxt_parse_text_box(GF_MediaImporter *import, GF_XMLNode *n, GF_BoxRecord *box)
{
u32 i=0;
GF_XMLAttribute *att;
memset(box, 0, sizeof(GF_BoxRecord));
while ( (att=(GF_XMLAttribute *)gf_list_enum(n->attributes, &i))) {
if (!stricmp(att->name, "top")) box->top = atoi(att->value);
else if (!stricmp(att->name, "bottom")) box->bottom = atoi(att->value);
else if (!stricmp(att->name, "left")) box->left = atoi(att->value);
else if (!stricmp(att->name, "right")) box->right = atoi(att->value);
}
}
void ttxt_parse_text_style(GF_MediaImporter *import, GF_XMLNode *n, GF_StyleRecord *style)
{
u32 i=0;
GF_XMLAttribute *att;
memset(style, 0, sizeof(GF_StyleRecord));
style->fontID = 1;
style->font_size = TTXT_DEFAULT_FONT_SIZE;
style->text_color = 0xFFFFFFFF;
while ( (att=(GF_XMLAttribute *)gf_list_enum(n->attributes, &i))) {
if (!stricmp(att->name, "fromChar")) style->startCharOffset = atoi(att->value);
else if (!stricmp(att->name, "toChar")) style->endCharOffset = atoi(att->value);
else if (!stricmp(att->name, "fontID")) style->fontID = atoi(att->value);
else if (!stricmp(att->name, "fontSize")) style->font_size = atoi(att->value);
else if (!stricmp(att->name, "color")) style->text_color = ttxt_get_color(import, att->value);
else if (!stricmp(att->name, "styles")) {
if (strstr(att->value, "Bold")) style->style_flags |= GF_TXT_STYLE_BOLD;
if (strstr(att->value, "Italic")) style->style_flags |= GF_TXT_STYLE_ITALIC;
if (strstr(att->value, "Underlined")) style->style_flags |= GF_TXT_STYLE_UNDERLINED;
}
}
}
static void ttxt_import_progress(void *cbk, u64 cur_samp, u64 count)
{
gf_set_progress("TTXT Loading", cur_samp, count);
}
static GF_Err gf_text_import_ttxt(GF_MediaImporter *import)
{
GF_Err e;
Bool last_sample_empty;
u32 i, j, k, track, ID, nb_samples, nb_descs, nb_children;
u64 last_sample_duration;
GF_XMLAttribute *att;
GF_DOMParser *parser;
GF_XMLNode *root, *node, *ext;
if (import->flags==GF_IMPORT_PROBE_ONLY) return GF_OK;
parser = gf_xml_dom_new();
e = gf_xml_dom_parse(parser, import->in_name, ttxt_import_progress, import);
if (e) {
gf_import_message(import, e, "Error parsing TTXT file: Line %d - %s", gf_xml_dom_get_line(parser), gf_xml_dom_get_error(parser));
gf_xml_dom_del(parser);
return e;
}
root = gf_xml_dom_get_root(parser);
e = GF_OK;
if (strcmp(root->name, "TextStream")) {
e = gf_import_message(import, GF_BAD_PARAM, "Invalid Timed Text file - expecting \"TextStream\" got %s", "TextStream", root->name);
goto exit;
}
/*setup track in 3GP format directly (no ES desc)*/
ID = (import->esd) ? import->esd->ESID : 0;
track = gf_isom_new_track(import->dest, ID, GF_ISOM_MEDIA_TEXT, 1000);
if (!track) {
e = gf_isom_last_error(import->dest);
goto exit;
}
gf_isom_set_track_enabled(import->dest, track, 1);
/*some MPEG-4 setup*/
if (import->esd) {
if (!import->esd->ESID) import->esd->ESID = gf_isom_get_track_id(import->dest, track);
if (!import->esd->decoderConfig) import->esd->decoderConfig = (GF_DecoderConfig *) gf_odf_desc_new(GF_ODF_DCD_TAG);
if (!import->esd->slConfig) import->esd->slConfig = (GF_SLConfig *) gf_odf_desc_new(GF_ODF_SLC_TAG);
import->esd->slConfig->timestampResolution = 1000;
import->esd->decoderConfig->streamType = GF_STREAM_TEXT;
import->esd->decoderConfig->objectTypeIndication = GPAC_OTI_TEXT_MPEG4;
if (import->esd->OCRESID) gf_isom_set_track_reference(import->dest, track, GF_ISOM_REF_OCR, import->esd->OCRESID);
}
gf_text_import_set_language(import, track);
gf_import_message(import, GF_OK, "Timed Text (GPAC TTXT) Import");
last_sample_empty = GF_FALSE;
last_sample_duration = 0;
nb_descs = 0;
nb_samples = 0;
nb_children = gf_list_count(root->content);
i=0;
while ( (node = (GF_XMLNode*)gf_list_enum(root->content, &i))) {
if (node->type) {
nb_children--;
continue;
}
if (!strcmp(node->name, "TextStreamHeader")) {
GF_XMLNode *sdesc;
s32 w, h, tx, ty, layer;
u32 tref_id;
w = TTXT_DEFAULT_WIDTH;
h = TTXT_DEFAULT_HEIGHT;
tx = ty = layer = 0;
nb_children--;
tref_id = 0;
j=0;
while ( (att=(GF_XMLAttribute *)gf_list_enum(node->attributes, &j))) {
if (!strcmp(att->name, "width")) w = atoi(att->value);
else if (!strcmp(att->name, "height")) h = atoi(att->value);
else if (!strcmp(att->name, "layer")) layer = atoi(att->value);
else if (!strcmp(att->name, "translation_x")) tx = atoi(att->value);
else if (!strcmp(att->name, "translation_y")) ty = atoi(att->value);
else if (!strcmp(att->name, "trefID")) tref_id = atoi(att->value);
}
if (tref_id)
gf_isom_set_track_reference(import->dest, track, GF_ISOM_BOX_TYPE_CHAP, tref_id);
gf_isom_set_track_layout_info(import->dest, track, w<<16, h<<16, tx<<16, ty<<16, (s16) layer);
j=0;
while ( (sdesc=(GF_XMLNode*)gf_list_enum(node->content, &j))) {
if (sdesc->type) continue;
if (!strcmp(sdesc->name, "TextSampleDescription")) {
GF_TextSampleDescriptor td;
u32 idx;
memset(&td, 0, sizeof(GF_TextSampleDescriptor));
td.tag = GF_ODF_TEXT_CFG_TAG;
td.vert_justif = (s8) -1;
td.default_style.fontID = 1;
td.default_style.font_size = TTXT_DEFAULT_FONT_SIZE;
k=0;
while ( (att=(GF_XMLAttribute *)gf_list_enum(sdesc->attributes, &k))) {
if (!strcmp(att->name, "horizontalJustification")) {
if (!stricmp(att->value, "center")) td.horiz_justif = 1;
else if (!stricmp(att->value, "right")) td.horiz_justif = (s8) -1;
else if (!stricmp(att->value, "left")) td.horiz_justif = 0;
}
else if (!strcmp(att->name, "verticalJustification")) {
if (!stricmp(att->value, "center")) td.vert_justif = 1;
else if (!stricmp(att->value, "bottom")) td.vert_justif = (s8) -1;
else if (!stricmp(att->value, "top")) td.vert_justif = 0;
}
else if (!strcmp(att->name, "backColor")) td.back_color = ttxt_get_color(import, att->value);
else if (!strcmp(att->name, "verticalText") && !stricmp(att->value, "yes") ) td.displayFlags |= GF_TXT_VERTICAL;
else if (!strcmp(att->name, "fillTextRegion") && !stricmp(att->value, "yes") ) td.displayFlags |= GF_TXT_FILL_REGION;
else if (!strcmp(att->name, "continuousKaraoke") && !stricmp(att->value, "yes") ) td.displayFlags |= GF_TXT_KARAOKE;
else if (!strcmp(att->name, "scroll")) {
if (!stricmp(att->value, "inout")) td.displayFlags |= GF_TXT_SCROLL_IN | GF_TXT_SCROLL_OUT;
else if (!stricmp(att->value, "in")) td.displayFlags |= GF_TXT_SCROLL_IN;
else if (!stricmp(att->value, "out")) td.displayFlags |= GF_TXT_SCROLL_OUT;
}
else if (!strcmp(att->name, "scrollMode")) {
u32 scroll_mode = GF_TXT_SCROLL_CREDITS;
if (!stricmp(att->value, "Credits")) scroll_mode = GF_TXT_SCROLL_CREDITS;
else if (!stricmp(att->value, "Marquee")) scroll_mode = GF_TXT_SCROLL_MARQUEE;
else if (!stricmp(att->value, "Right")) scroll_mode = GF_TXT_SCROLL_RIGHT;
else if (!stricmp(att->value, "Down")) scroll_mode = GF_TXT_SCROLL_DOWN;
td.displayFlags |= ((scroll_mode<<7) & GF_TXT_SCROLL_DIRECTION);
}
}
k=0;
while ( (ext=(GF_XMLNode*)gf_list_enum(sdesc->content, &k))) {
if (ext->type) continue;
if (!strcmp(ext->name, "TextBox")) ttxt_parse_text_box(import, ext, &td.default_pos);
else if (!strcmp(ext->name, "Style")) ttxt_parse_text_style(import, ext, &td.default_style);
else if (!strcmp(ext->name, "FontTable")) {
GF_XMLNode *ftable;
u32 z=0;
while ( (ftable=(GF_XMLNode*)gf_list_enum(ext->content, &z))) {
u32 m;
if (ftable->type || strcmp(ftable->name, "FontTableEntry")) continue;
td.font_count += 1;
td.fonts = (GF_FontRecord*)gf_realloc(td.fonts, sizeof(GF_FontRecord)*td.font_count);
m=0;
while ( (att=(GF_XMLAttribute *)gf_list_enum(ftable->attributes, &m))) {
if (!stricmp(att->name, "fontID")) td.fonts[td.font_count-1].fontID = atoi(att->value);
else if (!stricmp(att->name, "fontName")) td.fonts[td.font_count-1].fontName = gf_strdup(att->value);
}
}
}
}
if (import->flags & GF_IMPORT_SKIP_TXT_BOX) {
td.default_pos.top = td.default_pos.left = td.default_pos.right = td.default_pos.bottom = 0;
} else {
if ((td.default_pos.bottom==td.default_pos.top) || (td.default_pos.right==td.default_pos.left)) {
td.default_pos.top = td.default_pos.left = 0;
td.default_pos.right = w;
td.default_pos.bottom = h;
}
}
if (!td.fonts) {
td.font_count = 1;
td.fonts = (GF_FontRecord*)gf_malloc(sizeof(GF_FontRecord));
td.fonts[0].fontID = 1;
td.fonts[0].fontName = gf_strdup("Serif");
}
gf_isom_new_text_description(import->dest, track, &td, NULL, NULL, &idx);
for (k=0; k<td.font_count; k++) gf_free(td.fonts[k].fontName);
gf_free(td.fonts);
nb_descs ++;
}
}
}
/*sample text*/
else if (!strcmp(node->name, "TextSample")) {
GF_ISOSample *s;
GF_TextSample * samp;
u32 ts, descIndex;
Bool has_text = GF_FALSE;
if (!nb_descs) {
e = gf_import_message(import, GF_BAD_PARAM, "Invalid Timed Text file - text stream header not found or empty");
goto exit;
}
samp = gf_isom_new_text_sample();
ts = 0;
descIndex = 1;
last_sample_empty = GF_TRUE;
j=0;
while ( (att=(GF_XMLAttribute*)gf_list_enum(node->attributes, &j))) {
if (!strcmp(att->name, "sampleTime")) {
u32 h, m, s, ms;
if (sscanf(att->value, "%u:%u:%u.%u", &h, &m, &s, &ms) == 4) {
ts = (h*3600 + m*60 + s)*1000 + ms;
} else {
ts = (u32) (atof(att->value) * 1000);
}
}
else if (!strcmp(att->name, "sampleDescriptionIndex")) descIndex = atoi(att->value);
else if (!strcmp(att->name, "text")) {
u32 len;
char *str = ttxt_parse_string(import, att->value, GF_TRUE);
len = (u32) strlen(str);
gf_isom_text_add_text(samp, str, len);
last_sample_empty = len ? GF_FALSE : GF_TRUE;
has_text = GF_TRUE;
}
else if (!strcmp(att->name, "scrollDelay")) gf_isom_text_set_scroll_delay(samp, (u32) (1000*atoi(att->value)));
else if (!strcmp(att->name, "highlightColor")) gf_isom_text_set_highlight_color_argb(samp, ttxt_get_color(import, att->value));
else if (!strcmp(att->name, "wrap") && !strcmp(att->value, "Automatic")) gf_isom_text_set_wrap(samp, 0x01);
}
/*get all modifiers*/
j=0;
while ( (ext=(GF_XMLNode*)gf_list_enum(node->content, &j))) {
if (!has_text && (ext->type==GF_XML_TEXT_TYPE)) {
u32 len;
char *str = ttxt_parse_string(import, ext->name, GF_FALSE);
len = (u32) strlen(str);
gf_isom_text_add_text(samp, str, len);
last_sample_empty = len ? GF_FALSE : GF_TRUE;
has_text = GF_TRUE;
}
if (ext->type) continue;
if (!stricmp(ext->name, "Style")) {
GF_StyleRecord r;
ttxt_parse_text_style(import, ext, &r);
gf_isom_text_add_style(samp, &r);
}
else if (!stricmp(ext->name, "TextBox")) {
GF_BoxRecord r;
ttxt_parse_text_box(import, ext, &r);
gf_isom_text_set_box(samp, r.top, r.left, r.bottom, r.right);
}
else if (!stricmp(ext->name, "Highlight")) {
u16 start, end;
start = end = 0;
k=0;
while ( (att=(GF_XMLAttribute *)gf_list_enum(ext->attributes, &k))) {
if (!strcmp(att->name, "fromChar")) start = atoi(att->value);
else if (!strcmp(att->name, "toChar")) end = atoi(att->value);
}
gf_isom_text_add_highlight(samp, start, end);
}
else if (!stricmp(ext->name, "Blinking")) {
u16 start, end;
start = end = 0;
k=0;
while ( (att=(GF_XMLAttribute *)gf_list_enum(ext->attributes, &k))) {
if (!strcmp(att->name, "fromChar")) start = atoi(att->value);
else if (!strcmp(att->name, "toChar")) end = atoi(att->value);
}
gf_isom_text_add_blink(samp, start, end);
}
else if (!stricmp(ext->name, "HyperLink")) {
u16 start, end;
char *url, *url_tt;
start = end = 0;
url = url_tt = NULL;
k=0;
while ( (att=(GF_XMLAttribute *)gf_list_enum(ext->attributes, &k))) {
if (!strcmp(att->name, "fromChar")) start = atoi(att->value);
else if (!strcmp(att->name, "toChar")) end = atoi(att->value);
else if (!strcmp(att->name, "URL")) url = gf_strdup(att->value);
else if (!strcmp(att->name, "URLToolTip")) url_tt = gf_strdup(att->value);
}
gf_isom_text_add_hyperlink(samp, url, url_tt, start, end);
if (url) gf_free(url);
if (url_tt) gf_free(url_tt);
}
else if (!stricmp(ext->name, "Karaoke")) {
u32 startTime;
GF_XMLNode *krok;
startTime = 0;
k=0;
while ( (att=(GF_XMLAttribute *)gf_list_enum(ext->attributes, &k))) {
if (!strcmp(att->name, "startTime")) startTime = (u32) (1000*atof(att->value));
}
gf_isom_text_add_karaoke(samp, startTime);
k=0;
while ( (krok=(GF_XMLNode*)gf_list_enum(ext->content, &k))) {
u16 start, end;
u32 endTime, m;
if (krok->type) continue;
if (strcmp(krok->name, "KaraokeRange")) continue;
start = end = 0;
endTime = 0;
m=0;
while ( (att=(GF_XMLAttribute *)gf_list_enum(krok->attributes, &m))) {
if (!strcmp(att->name, "fromChar")) start = atoi(att->value);
else if (!strcmp(att->name, "toChar")) end = atoi(att->value);
else if (!strcmp(att->name, "endTime")) endTime = (u32) (1000*atof(att->value));
}
gf_isom_text_set_karaoke_segment(samp, endTime, start, end);
}
}
}
/*in MP4 we must start at T=0, so add an empty sample*/
if (ts && !nb_samples) {
GF_TextSample * firstsamp = gf_isom_new_text_sample();
s = gf_isom_text_to_sample(firstsamp);
s->DTS = 0;
gf_isom_add_sample(import->dest, track, 1, s);
nb_samples++;
gf_isom_delete_text_sample(firstsamp);
gf_isom_sample_del(&s);
}
s = gf_isom_text_to_sample(samp);
gf_isom_delete_text_sample(samp);
s->DTS = ts;
if (last_sample_empty) {
last_sample_duration = s->DTS - last_sample_duration;
} else {
last_sample_duration = s->DTS;
}
e = gf_isom_add_sample(import->dest, track, descIndex, s);
if (e) goto exit;
gf_isom_sample_del(&s);
nb_samples++;
gf_set_progress("Importing TTXT", nb_samples, nb_children);
if (import->duration && (ts>import->duration)) break;
}
}
if (last_sample_empty) {
gf_isom_remove_sample(import->dest, track, nb_samples);
gf_isom_set_last_sample_duration(import->dest, track, (u32) last_sample_duration);
}
gf_set_progress("Importing TTXT", nb_samples, nb_samples);
exit:
gf_xml_dom_del(parser);
return e;
}
u32 tx3g_get_color(GF_MediaImporter *import, char *value)
{
u32 r, g, b, a;
u32 res, v;
r = g = b = a = 0;
if (sscanf(value, "%u%%, %u%%, %u%%, %u%%", &r, &g, &b, &a) != 4) {
gf_import_message(import, GF_OK, "Warning: color badly formatted");
}
v = (u32) (a*255/100);
res = (v&0xFF);
res<<=8;
v = (u32) (r*255/100);
res |= (v&0xFF);
res<<=8;
v = (u32) (g*255/100);
res |= (v&0xFF);
res<<=8;
v = (u32) (b*255/100);
res |= (v&0xFF);
return res;
}
void tx3g_parse_text_box(GF_MediaImporter *import, GF_XMLNode *n, GF_BoxRecord *box)
{
u32 i=0;
GF_XMLAttribute *att;
memset(box, 0, sizeof(GF_BoxRecord));
while ((att=(GF_XMLAttribute *)gf_list_enum(n->attributes, &i))) {
if (!stricmp(att->name, "x")) box->left = atoi(att->value);
else if (!stricmp(att->name, "y")) box->top = atoi(att->value);
else if (!stricmp(att->name, "height")) box->bottom = atoi(att->value);
else if (!stricmp(att->name, "width")) box->right = atoi(att->value);
}
}
typedef struct
{
u32 id;
u32 pos;
} Marker;
#define GET_MARKER_POS(_val, __isend) \
{ \
u32 i, __m = atoi(att->value); \
_val = 0; \
for (i=0; i<nb_marks; i++) { if (__m==marks[i].id) { _val = marks[i].pos; /*if (__isend) _val--; */break; } } \
}
static void texml_import_progress(void *cbk, u64 cur_samp, u64 count)
{
gf_set_progress("TeXML Loading", cur_samp, count);
}
static GF_Err gf_text_import_texml(GF_MediaImporter *import)
{
GF_Err e;
u32 track, ID, nb_samples, nb_children, nb_descs, timescale, w, h, i, j, k;
u64 DTS;
s32 tx, ty, layer;
GF_StyleRecord styles[50];
Marker marks[50];
GF_XMLAttribute *att;
GF_DOMParser *parser;
GF_XMLNode *root, *node;
if (import->flags==GF_IMPORT_PROBE_ONLY) return GF_OK;
parser = gf_xml_dom_new();
e = gf_xml_dom_parse(parser, import->in_name, texml_import_progress, import);
if (e) {
gf_import_message(import, e, "Error parsing TeXML file: Line %d - %s", gf_xml_dom_get_line(parser), gf_xml_dom_get_error(parser));
gf_xml_dom_del(parser);
return e;
}
root = gf_xml_dom_get_root(parser);
if (strcmp(root->name, "text3GTrack")) {
e = gf_import_message(import, GF_BAD_PARAM, "Invalid QT TeXML file - expecting root \"text3GTrack\" got \"%s\"", root->name);
goto exit;
}
w = TTXT_DEFAULT_WIDTH;
h = TTXT_DEFAULT_HEIGHT;
tx = ty = 0;
layer = 0;
timescale = 1000;
i=0;
while ( (att=(GF_XMLAttribute *)gf_list_enum(root->attributes, &i))) {
if (!strcmp(att->name, "trackWidth")) w = atoi(att->value);
else if (!strcmp(att->name, "trackHeight")) h = atoi(att->value);
else if (!strcmp(att->name, "layer")) layer = atoi(att->value);
else if (!strcmp(att->name, "timescale")) timescale = atoi(att->value);
else if (!strcmp(att->name, "transform")) {
Float fx, fy;
sscanf(att->value, "translate(%f,%f)", &fx, &fy);
tx = (u32) fx;
ty = (u32) fy;
}
}
/*setup track in 3GP format directly (no ES desc)*/
ID = (import->esd) ? import->esd->ESID : 0;
track = gf_isom_new_track(import->dest, ID, GF_ISOM_MEDIA_TEXT, timescale);
if (!track) {
e = gf_isom_last_error(import->dest);
goto exit;
}
gf_isom_set_track_enabled(import->dest, track, 1);
/*some MPEG-4 setup*/
if (import->esd) {
if (!import->esd->ESID) import->esd->ESID = gf_isom_get_track_id(import->dest, track);
if (!import->esd->decoderConfig) import->esd->decoderConfig = (GF_DecoderConfig *) gf_odf_desc_new(GF_ODF_DCD_TAG);
if (!import->esd->slConfig) import->esd->slConfig = (GF_SLConfig *) gf_odf_desc_new(GF_ODF_SLC_TAG);
import->esd->slConfig->timestampResolution = timescale;
import->esd->decoderConfig->streamType = GF_STREAM_TEXT;
import->esd->decoderConfig->objectTypeIndication = GPAC_OTI_TEXT_MPEG4;
if (import->esd->OCRESID) gf_isom_set_track_reference(import->dest, track, GF_ISOM_REF_OCR, import->esd->OCRESID);
}
DTS = 0;
gf_isom_set_track_layout_info(import->dest, track, w<<16, h<<16, tx<<16, ty<<16, (s16) layer);
gf_text_import_set_language(import, track);
e = GF_OK;
gf_import_message(import, GF_OK, "Timed Text (QT TeXML) Import - Track Size %d x %d", w, h);
nb_children = gf_list_count(root->content);
nb_descs = 0;
nb_samples = 0;
i=0;
while ( (node=(GF_XMLNode*)gf_list_enum(root->content, &i))) {
GF_XMLNode *desc;
GF_TextSampleDescriptor td;
GF_TextSample * samp = NULL;
GF_ISOSample *s;
u32 duration, descIndex, nb_styles, nb_marks;
Bool isRAP, same_style, same_box;
if (node->type) continue;
if (strcmp(node->name, "sample")) continue;
isRAP = GF_FALSE;
duration = 1000;
j=0;
while ((att=(GF_XMLAttribute *)gf_list_enum(node->attributes, &j))) {
if (!strcmp(att->name, "duration")) duration = atoi(att->value);
else if (!strcmp(att->name, "keyframe")) isRAP = (!stricmp(att->value, "true") ? GF_TRUE : GF_FALSE);
}
nb_styles = 0;
nb_marks = 0;
same_style = same_box = GF_FALSE;
descIndex = 1;
j=0;
while ((desc=(GF_XMLNode*)gf_list_enum(node->content, &j))) {
if (desc->type) continue;
if (!strcmp(desc->name, "description")) {
GF_XMLNode *sub;
memset(&td, 0, sizeof(GF_TextSampleDescriptor));
td.tag = GF_ODF_TEXT_CFG_TAG;
td.vert_justif = (s8) -1;
td.default_style.fontID = 1;
td.default_style.font_size = TTXT_DEFAULT_FONT_SIZE;
k=0;
while ((att=(GF_XMLAttribute *)gf_list_enum(desc->attributes, &k))) {
if (!strcmp(att->name, "horizontalJustification")) {
if (!stricmp(att->value, "center")) td.horiz_justif = 1;
else if (!stricmp(att->value, "right")) td.horiz_justif = (s8) -1;
else if (!stricmp(att->value, "left")) td.horiz_justif = 0;
}
else if (!strcmp(att->name, "verticalJustification")) {
if (!stricmp(att->value, "center")) td.vert_justif = 1;
else if (!stricmp(att->value, "bottom")) td.vert_justif = (s8) -1;
else if (!stricmp(att->value, "top")) td.vert_justif = 0;
}
else if (!strcmp(att->name, "backgroundColor")) td.back_color = tx3g_get_color(import, att->value);
else if (!strcmp(att->name, "displayFlags")) {
Bool rev_scroll = GF_FALSE;
if (strstr(att->value, "scroll")) {
u32 scroll_mode = 0;
if (strstr(att->value, "scrollIn")) td.displayFlags |= GF_TXT_SCROLL_IN;
if (strstr(att->value, "scrollOut")) td.displayFlags |= GF_TXT_SCROLL_OUT;
if (strstr(att->value, "reverse")) rev_scroll = GF_TRUE;
if (strstr(att->value, "horizontal")) scroll_mode = rev_scroll ? GF_TXT_SCROLL_RIGHT : GF_TXT_SCROLL_MARQUEE;
else scroll_mode = (rev_scroll ? GF_TXT_SCROLL_DOWN : GF_TXT_SCROLL_CREDITS);
td.displayFlags |= (scroll_mode<<7) & GF_TXT_SCROLL_DIRECTION;
}
/*TODO FIXME: check in QT doc !!*/
if (strstr(att->value, "writeTextVertically")) td.displayFlags |= GF_TXT_VERTICAL;
if (!strcmp(att->name, "continuousKaraoke")) td.displayFlags |= GF_TXT_KARAOKE;
}
}
k=0;
while ((sub=(GF_XMLNode*)gf_list_enum(desc->content, &k))) {
if (sub->type) continue;
if (!strcmp(sub->name, "defaultTextBox")) tx3g_parse_text_box(import, sub, &td.default_pos);
else if (!strcmp(sub->name, "fontTable")) {
GF_XMLNode *ftable;
u32 m=0;
while ((ftable=(GF_XMLNode*)gf_list_enum(sub->content, &m))) {
if (ftable->type) continue;
if (!strcmp(ftable->name, "font")) {
u32 n=0;
td.font_count += 1;
td.fonts = (GF_FontRecord*)gf_realloc(td.fonts, sizeof(GF_FontRecord)*td.font_count);
while ((att=(GF_XMLAttribute *)gf_list_enum(ftable->attributes, &n))) {
if (!stricmp(att->name, "id")) td.fonts[td.font_count-1].fontID = atoi(att->value);
else if (!stricmp(att->name, "name")) td.fonts[td.font_count-1].fontName = gf_strdup(att->value);
}
}
}
}
else if (!strcmp(sub->name, "sharedStyles")) {
GF_XMLNode *style, *ftable;
u32 m=0;
while ((style=(GF_XMLNode*)gf_list_enum(sub->content, &m))) {
if (style->type) continue;
if (!strcmp(style->name, "style")) break;
}
if (style) {
char *cur;
s32 start=0;
char css_style[1024], css_val[1024];
memset(&styles[nb_styles], 0, sizeof(GF_StyleRecord));
m=0;
while ( (att=(GF_XMLAttribute *)gf_list_enum(style->attributes, &m))) {
if (!strcmp(att->name, "id")) styles[nb_styles].startCharOffset = atoi(att->value);
}
m=0;
while ( (ftable=(GF_XMLNode*)gf_list_enum(style->content, &m))) {
if (ftable->type) break;
}
cur = ftable->name;
while (cur) {
start = gf_token_get_strip(cur, 0, "{:", " ", css_style, 1024);
if (start <0) break;
start = gf_token_get_strip(cur, start, ":}", " ", css_val, 1024);
if (start <0) break;
cur = strchr(cur+start, '{');
if (!strcmp(css_style, "font-table")) {
u32 z;
styles[nb_styles].fontID = atoi(css_val);
for (z=0; z<td.font_count; z++) {
if (td.fonts[z].fontID == styles[nb_styles].fontID)
break;
}
}
else if (!strcmp(css_style, "font-size")) styles[nb_styles].font_size = atoi(css_val);
else if (!strcmp(css_style, "font-style") && !strcmp(css_val, "italic")) styles[nb_styles].style_flags |= GF_TXT_STYLE_ITALIC;
else if (!strcmp(css_style, "font-weight") && !strcmp(css_val, "bold")) styles[nb_styles].style_flags |= GF_TXT_STYLE_BOLD;
else if (!strcmp(css_style, "text-decoration") && !strcmp(css_val, "underline")) styles[nb_styles].style_flags |= GF_TXT_STYLE_UNDERLINED;
else if (!strcmp(css_style, "color")) styles[nb_styles].text_color = tx3g_get_color(import, css_val);
}
if (!nb_styles) td.default_style = styles[0];
nb_styles++;
}
}
}
if ((td.default_pos.bottom==td.default_pos.top) || (td.default_pos.right==td.default_pos.left)) {
td.default_pos.top = td.default_pos.left = 0;
td.default_pos.right = w;
td.default_pos.bottom = h;
}
if (!td.fonts) {
td.font_count = 1;
td.fonts = (GF_FontRecord*)gf_malloc(sizeof(GF_FontRecord));
td.fonts[0].fontID = 1;
td.fonts[0].fontName = gf_strdup("Serif");
}
gf_isom_text_has_similar_description(import->dest, track, &td, &descIndex, &same_box, &same_style);
if (!descIndex) {
gf_isom_new_text_description(import->dest, track, &td, NULL, NULL, &descIndex);
same_style = same_box = GF_TRUE;
}
for (k=0; k<td.font_count; k++) gf_free(td.fonts[k].fontName);
gf_free(td.fonts);
nb_descs ++;
}
else if (!strcmp(desc->name, "sampleData")) {
GF_XMLNode *sub;
u16 start, end;
u32 styleID;
u32 nb_chars, txt_len, m;
nb_chars = 0;
samp = gf_isom_new_text_sample();
k=0;
while ((att=(GF_XMLAttribute *)gf_list_enum(desc->attributes, &k))) {
if (!strcmp(att->name, "targetEncoding") && !strcmp(att->value, "utf16")) ;//is_utf16 = 1;
else if (!strcmp(att->name, "scrollDelay")) gf_isom_text_set_scroll_delay(samp, atoi(att->value) );
else if (!strcmp(att->name, "highlightColor")) gf_isom_text_set_highlight_color_argb(samp, tx3g_get_color(import, att->value));
}
start = end = 0;
k=0;
while ((sub=(GF_XMLNode*)gf_list_enum(desc->content, &k))) {
if (sub->type) continue;
if (!strcmp(sub->name, "text")) {
GF_XMLNode *text;
styleID = 0;
m=0;
while ((att=(GF_XMLAttribute *)gf_list_enum(sub->attributes, &m))) {
if (!strcmp(att->name, "styleID")) styleID = atoi(att->value);
}
txt_len = 0;
m=0;
while ((text=(GF_XMLNode*)gf_list_enum(sub->content, &m))) {
if (!text->type) {
if (!strcmp(text->name, "marker")) {
u32 z;
memset(&marks[nb_marks], 0, sizeof(Marker));
marks[nb_marks].pos = nb_chars+txt_len;
z = 0;
while ( (att=(GF_XMLAttribute *)gf_list_enum(text->attributes, &z))) {
if (!strcmp(att->name, "id")) marks[nb_marks].id = atoi(att->value);
}
nb_marks++;
}
} else if (text->type==GF_XML_TEXT_TYPE) {
txt_len += (u32) strlen(text->name);
gf_isom_text_add_text(samp, text->name, (u32) strlen(text->name));
}
}
if (styleID && (!same_style || (td.default_style.startCharOffset != styleID))) {
GF_StyleRecord st = td.default_style;
for (m=0; m<nb_styles; m++) {
if (styles[m].startCharOffset==styleID) {
st = styles[m];
break;
}
}
st.startCharOffset = nb_chars;
st.endCharOffset = nb_chars + txt_len;
gf_isom_text_add_style(samp, &st);
}
nb_chars += txt_len;
}
else if (!stricmp(sub->name, "highlight")) {
m=0;
while ((att=(GF_XMLAttribute *)gf_list_enum(sub->attributes, &m))) {
if (!strcmp(att->name, "startMarker")) GET_MARKER_POS(start, 0)
else if (!strcmp(att->name, "endMarker")) GET_MARKER_POS(end, 1)
}
gf_isom_text_add_highlight(samp, start, end);
}
else if (!stricmp(sub->name, "blink")) {
m=0;
while ((att=(GF_XMLAttribute *)gf_list_enum(sub->attributes, &m))) {
if (!strcmp(att->name, "startMarker")) GET_MARKER_POS(start, 0)
else if (!strcmp(att->name, "endMarker")) GET_MARKER_POS(end, 1)
}
gf_isom_text_add_blink(samp, start, end);
}
else if (!stricmp(sub->name, "link")) {
char *url, *url_tt;
url = url_tt = NULL;
m=0;
while ((att=(GF_XMLAttribute *)gf_list_enum(sub->attributes, &m))) {
if (!strcmp(att->name, "startMarker")) GET_MARKER_POS(start, 0)
else if (!strcmp(att->name, "endMarker")) GET_MARKER_POS(end, 1)
else if (!strcmp(att->name, "URL") || !strcmp(att->name, "href")) url = gf_strdup(att->value);
else if (!strcmp(att->name, "URLToolTip") || !strcmp(att->name, "altString")) url_tt = gf_strdup(att->value);
}
gf_isom_text_add_hyperlink(samp, url, url_tt, start, end);
if (url) gf_free(url);
if (url_tt) gf_free(url_tt);
}
else if (!stricmp(sub->name, "karaoke")) {
u32 time = 0;
GF_XMLNode *krok;
m=0;
while ((att=(GF_XMLAttribute *)gf_list_enum(sub->attributes, &m))) {
if (!strcmp(att->name, "startTime")) time = atoi(att->value);
}
gf_isom_text_add_karaoke(samp, time);
m=0;
while ((krok=(GF_XMLNode*)gf_list_enum(sub->content, &m))) {
u32 u=0;
if (krok->type) continue;
if (strcmp(krok->name, "run")) continue;
start = end = 0;
while ((att=(GF_XMLAttribute *)gf_list_enum(krok->attributes, &u))) {
if (!strcmp(att->name, "startMarker")) GET_MARKER_POS(start, 0)
else if (!strcmp(att->name, "endMarker")) GET_MARKER_POS(end, 1)
else if (!strcmp(att->name, "duration")) time += atoi(att->value);
}
gf_isom_text_set_karaoke_segment(samp, time, start, end);
}
}
}
}
}
/*OK, let's add the sample*/
if (samp) {
if (!same_box) gf_isom_text_set_box(samp, td.default_pos.top, td.default_pos.left, td.default_pos.bottom, td.default_pos.right);
// if (!same_style) gf_isom_text_add_style(samp, &td.default_style);
s = gf_isom_text_to_sample(samp);
gf_isom_delete_text_sample(samp);
s->IsRAP = isRAP ? RAP : RAP_NO;
s->DTS = DTS;
gf_isom_add_sample(import->dest, track, descIndex, s);
gf_isom_sample_del(&s);
nb_samples++;
DTS += duration;
gf_set_progress("Importing TeXML", nb_samples, nb_children);
if (import->duration && (DTS*1000> timescale*import->duration)) break;
}
}
gf_isom_set_last_sample_duration(import->dest, track, 0);
gf_set_progress("Importing TeXML", nb_samples, nb_samples);
exit:
gf_xml_dom_del(parser);
return e;
}
GF_Err gf_import_timed_text(GF_MediaImporter *import)
{
GF_Err e;
u32 fmt;
e = gf_text_guess_format(import->in_name, &fmt);
if (e) return e;
if (import->streamFormat) {
if (!strcmp(import->streamFormat, "VTT")) fmt = GF_TEXT_IMPORT_WEBVTT;
else if (!strcmp(import->streamFormat, "TTML")) fmt = GF_TEXT_IMPORT_TTML;
if ((strstr(import->in_name, ".swf") || strstr(import->in_name, ".SWF")) && !stricmp(import->streamFormat, "SVG")) fmt = GF_TEXT_IMPORT_SWF_SVG;
}
if (!fmt) {
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTXT Import] Input %s does not look like a supported text format - ignoring\n", import->in_name));
return GF_NOT_SUPPORTED;
}
if (import->flags & GF_IMPORT_PROBE_ONLY) {
if (fmt==GF_TEXT_IMPORT_SUB) import->flags |= GF_IMPORT_OVERRIDE_FPS;
return GF_OK;
}
switch (fmt) {
case GF_TEXT_IMPORT_SRT:
return gf_text_import_srt(import);
case GF_TEXT_IMPORT_SUB:
return gf_text_import_sub(import);
case GF_TEXT_IMPORT_TTXT:
return gf_text_import_ttxt(import);
case GF_TEXT_IMPORT_TEXML:
return gf_text_import_texml(import);
#ifndef GPAC_DISABLE_VTT
case GF_TEXT_IMPORT_WEBVTT:
return gf_text_import_webvtt(import);
#endif
case GF_TEXT_IMPORT_SWF_SVG:
return gf_text_import_swf(import);
case GF_TEXT_IMPORT_TTML:
return gf_text_import_ttml(import);
default:
return GF_BAD_PARAM;
}
}
#endif /*GPAC_DISABLE_MEDIA_IMPORT*/
#endif /*GPAC_DISABLE_ISOM_WRITE*/
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_526_1 |
crossvul-cpp_data_bad_4490_0 | /* rsa.c
*
* Copyright (C) 2006-2020 wolfSSL Inc.
*
* This file is part of wolfSSL.
*
* wolfSSL 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.
*
* wolfSSL 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-1335, USA
*/
/*
DESCRIPTION
This library provides the interface to the RSA.
RSA keys can be used to encrypt, decrypt, sign and verify data.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <wolfssl/wolfcrypt/settings.h>
#include <wolfssl/wolfcrypt/error-crypt.h>
#ifndef NO_RSA
#if defined(HAVE_FIPS) && \
defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)
/* set NO_WRAPPERS before headers, use direct internal f()s not wrappers */
#define FIPS_NO_WRAPPERS
#ifdef USE_WINDOWS_API
#pragma code_seg(".fipsA$e")
#pragma const_seg(".fipsB$e")
#endif
#endif
#include <wolfssl/wolfcrypt/rsa.h>
#ifdef WOLFSSL_AFALG_XILINX_RSA
#include <wolfssl/wolfcrypt/port/af_alg/wc_afalg.h>
#endif
#ifdef WOLFSSL_HAVE_SP_RSA
#include <wolfssl/wolfcrypt/sp.h>
#endif
/*
Possible RSA enable options:
* NO_RSA: Overall control of RSA default: on (not defined)
* WC_RSA_BLINDING: Uses Blinding w/ Private Ops default: off
Note: slower by ~20%
* WOLFSSL_KEY_GEN: Allows Private Key Generation default: off
* RSA_LOW_MEM: NON CRT Private Operations, less memory default: off
* WC_NO_RSA_OAEP: Disables RSA OAEP padding default: on (not defined)
* WC_RSA_NONBLOCK: Enables support for RSA non-blocking default: off
* WC_RSA_NONBLOCK_TIME:Enables support for time based blocking default: off
* time calculation.
*/
/*
RSA Key Size Configuration:
* FP_MAX_BITS: With USE_FAST_MATH only default: 4096
If USE_FAST_MATH then use this to override default.
Value is key size * 2. Example: RSA 3072 = 6144
*/
/* If building for old FIPS. */
#if defined(HAVE_FIPS) && \
(!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2))
int wc_InitRsaKey(RsaKey* key, void* ptr)
{
if (key == NULL) {
return BAD_FUNC_ARG;
}
return InitRsaKey_fips(key, ptr);
}
int wc_InitRsaKey_ex(RsaKey* key, void* ptr, int devId)
{
(void)devId;
if (key == NULL) {
return BAD_FUNC_ARG;
}
return InitRsaKey_fips(key, ptr);
}
int wc_FreeRsaKey(RsaKey* key)
{
return FreeRsaKey_fips(key);
}
#ifndef WOLFSSL_RSA_VERIFY_ONLY
int wc_RsaPublicEncrypt(const byte* in, word32 inLen, byte* out,
word32 outLen, RsaKey* key, WC_RNG* rng)
{
if (in == NULL || out == NULL || key == NULL || rng == NULL) {
return BAD_FUNC_ARG;
}
return RsaPublicEncrypt_fips(in, inLen, out, outLen, key, rng);
}
#endif
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
int wc_RsaPrivateDecryptInline(byte* in, word32 inLen, byte** out,
RsaKey* key)
{
if (in == NULL || out == NULL || key == NULL) {
return BAD_FUNC_ARG;
}
return RsaPrivateDecryptInline_fips(in, inLen, out, key);
}
int wc_RsaPrivateDecrypt(const byte* in, word32 inLen, byte* out,
word32 outLen, RsaKey* key)
{
if (in == NULL || out == NULL || key == NULL) {
return BAD_FUNC_ARG;
}
return RsaPrivateDecrypt_fips(in, inLen, out, outLen, key);
}
int wc_RsaSSL_Sign(const byte* in, word32 inLen, byte* out,
word32 outLen, RsaKey* key, WC_RNG* rng)
{
if (in == NULL || out == NULL || key == NULL || inLen == 0) {
return BAD_FUNC_ARG;
}
return RsaSSL_Sign_fips(in, inLen, out, outLen, key, rng);
}
#endif
int wc_RsaSSL_VerifyInline(byte* in, word32 inLen, byte** out, RsaKey* key)
{
if (in == NULL || out == NULL || key == NULL) {
return BAD_FUNC_ARG;
}
return RsaSSL_VerifyInline_fips(in, inLen, out, key);
}
int wc_RsaSSL_Verify(const byte* in, word32 inLen, byte* out,
word32 outLen, RsaKey* key)
{
if (in == NULL || out == NULL || key == NULL || inLen == 0) {
return BAD_FUNC_ARG;
}
return RsaSSL_Verify_fips(in, inLen, out, outLen, key);
}
int wc_RsaEncryptSize(RsaKey* key)
{
if (key == NULL) {
return BAD_FUNC_ARG;
}
return RsaEncryptSize_fips(key);
}
#ifndef WOLFSSL_RSA_VERIFY_ONLY
int wc_RsaFlattenPublicKey(RsaKey* key, byte* a, word32* aSz, byte* b,
word32* bSz)
{
/* not specified as fips so not needing _fips */
return RsaFlattenPublicKey(key, a, aSz, b, bSz);
}
#endif
#ifdef WOLFSSL_KEY_GEN
int wc_MakeRsaKey(RsaKey* key, int size, long e, WC_RNG* rng)
{
return MakeRsaKey(key, size, e, rng);
}
#endif
/* these are functions in asn and are routed to wolfssl/wolfcrypt/asn.c
* wc_RsaPrivateKeyDecode
* wc_RsaPublicKeyDecode
*/
#else /* else build without fips, or for new fips */
#include <wolfssl/wolfcrypt/random.h>
#include <wolfssl/wolfcrypt/logging.h>
#ifdef WOLF_CRYPTO_CB
#include <wolfssl/wolfcrypt/cryptocb.h>
#endif
#ifdef NO_INLINE
#include <wolfssl/wolfcrypt/misc.h>
#else
#define WOLFSSL_MISC_INCLUDED
#include <wolfcrypt/src/misc.c>
#endif
enum {
RSA_STATE_NONE = 0,
RSA_STATE_ENCRYPT_PAD,
RSA_STATE_ENCRYPT_EXPTMOD,
RSA_STATE_ENCRYPT_RES,
RSA_STATE_DECRYPT_EXPTMOD,
RSA_STATE_DECRYPT_UNPAD,
RSA_STATE_DECRYPT_RES,
};
static void wc_RsaCleanup(RsaKey* key)
{
#ifndef WOLFSSL_RSA_VERIFY_INLINE
if (key && key->data) {
/* make sure any allocated memory is free'd */
if (key->dataIsAlloc) {
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
if (key->type == RSA_PRIVATE_DECRYPT ||
key->type == RSA_PRIVATE_ENCRYPT) {
ForceZero(key->data, key->dataLen);
}
#endif
XFREE(key->data, key->heap, DYNAMIC_TYPE_WOLF_BIGINT);
key->dataIsAlloc = 0;
}
key->data = NULL;
key->dataLen = 0;
}
#else
(void)key;
#endif
}
int wc_InitRsaKey_ex(RsaKey* key, void* heap, int devId)
{
int ret = 0;
if (key == NULL) {
return BAD_FUNC_ARG;
}
XMEMSET(key, 0, sizeof(RsaKey));
key->type = RSA_TYPE_UNKNOWN;
key->state = RSA_STATE_NONE;
key->heap = heap;
#ifndef WOLFSSL_RSA_VERIFY_INLINE
key->dataIsAlloc = 0;
key->data = NULL;
#endif
key->dataLen = 0;
#ifdef WC_RSA_BLINDING
key->rng = NULL;
#endif
#ifdef WOLF_CRYPTO_CB
key->devId = devId;
#else
(void)devId;
#endif
#ifdef WOLFSSL_ASYNC_CRYPT
#ifdef WOLFSSL_CERT_GEN
XMEMSET(&key->certSignCtx, 0, sizeof(CertSignCtx));
#endif
#ifdef WC_ASYNC_ENABLE_RSA
/* handle as async */
ret = wolfAsync_DevCtxInit(&key->asyncDev, WOLFSSL_ASYNC_MARKER_RSA,
key->heap, devId);
if (ret != 0)
return ret;
#endif /* WC_ASYNC_ENABLE_RSA */
#endif /* WOLFSSL_ASYNC_CRYPT */
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
ret = mp_init_multi(&key->n, &key->e, NULL, NULL, NULL, NULL);
if (ret != MP_OKAY)
return ret;
#if !defined(WOLFSSL_KEY_GEN) && !defined(OPENSSL_EXTRA) && defined(RSA_LOW_MEM)
ret = mp_init_multi(&key->d, &key->p, &key->q, NULL, NULL, NULL);
#else
ret = mp_init_multi(&key->d, &key->p, &key->q, &key->dP, &key->dQ, &key->u);
#endif
if (ret != MP_OKAY) {
mp_clear(&key->n);
mp_clear(&key->e);
return ret;
}
#else
ret = mp_init(&key->n);
if (ret != MP_OKAY)
return ret;
ret = mp_init(&key->e);
if (ret != MP_OKAY) {
mp_clear(&key->n);
return ret;
}
#endif
#ifdef WOLFSSL_XILINX_CRYPT
key->pubExp = 0;
key->mod = NULL;
#endif
#ifdef WOLFSSL_AFALG_XILINX_RSA
key->alFd = WC_SOCK_NOTSET;
key->rdFd = WC_SOCK_NOTSET;
#endif
return ret;
}
int wc_InitRsaKey(RsaKey* key, void* heap)
{
return wc_InitRsaKey_ex(key, heap, INVALID_DEVID);
}
#ifdef HAVE_PKCS11
int wc_InitRsaKey_Id(RsaKey* key, unsigned char* id, int len, void* heap,
int devId)
{
int ret = 0;
if (key == NULL)
ret = BAD_FUNC_ARG;
if (ret == 0 && (len < 0 || len > RSA_MAX_ID_LEN))
ret = BUFFER_E;
if (ret == 0)
ret = wc_InitRsaKey_ex(key, heap, devId);
if (ret == 0 && id != NULL && len != 0) {
XMEMCPY(key->id, id, len);
key->idLen = len;
}
return ret;
}
#endif
#ifdef WOLFSSL_XILINX_CRYPT
#define MAX_E_SIZE 4
/* Used to setup hardware state
*
* key the RSA key to setup
*
* returns 0 on success
*/
int wc_InitRsaHw(RsaKey* key)
{
unsigned char* m; /* RSA modulous */
word32 e = 0; /* RSA public exponent */
int mSz;
int eSz;
if (key == NULL) {
return BAD_FUNC_ARG;
}
mSz = mp_unsigned_bin_size(&(key->n));
m = (unsigned char*)XMALLOC(mSz, key->heap, DYNAMIC_TYPE_KEY);
if (m == NULL) {
return MEMORY_E;
}
if (mp_to_unsigned_bin(&(key->n), m) != MP_OKAY) {
WOLFSSL_MSG("Unable to get RSA key modulus");
XFREE(m, key->heap, DYNAMIC_TYPE_KEY);
return MP_READ_E;
}
eSz = mp_unsigned_bin_size(&(key->e));
if (eSz > MAX_E_SIZE) {
WOLFSSL_MSG("Exponent of size 4 bytes expected");
XFREE(m, key->heap, DYNAMIC_TYPE_KEY);
return BAD_FUNC_ARG;
}
if (mp_to_unsigned_bin(&(key->e), (byte*)&e + (MAX_E_SIZE - eSz))
!= MP_OKAY) {
XFREE(m, key->heap, DYNAMIC_TYPE_KEY);
WOLFSSL_MSG("Unable to get RSA key exponent");
return MP_READ_E;
}
/* check for existing mod buffer to avoid memory leak */
if (key->mod != NULL) {
XFREE(key->mod, key->heap, DYNAMIC_TYPE_KEY);
}
key->pubExp = e;
key->mod = m;
if (XSecure_RsaInitialize(&(key->xRsa), key->mod, NULL,
(byte*)&(key->pubExp)) != XST_SUCCESS) {
WOLFSSL_MSG("Unable to initialize RSA on hardware");
XFREE(m, key->heap, DYNAMIC_TYPE_KEY);
return BAD_STATE_E;
}
#ifdef WOLFSSL_XILINX_PATCH
/* currently a patch of xsecure_rsa.c for 2048 bit keys */
if (wc_RsaEncryptSize(key) == 256) {
if (XSecure_RsaSetSize(&(key->xRsa), 2048) != XST_SUCCESS) {
WOLFSSL_MSG("Unable to set RSA key size on hardware");
XFREE(m, key->heap, DYNAMIC_TYPE_KEY);
return BAD_STATE_E;
}
}
#endif
return 0;
} /* WOLFSSL_XILINX_CRYPT*/
#elif defined(WOLFSSL_CRYPTOCELL)
int wc_InitRsaHw(RsaKey* key)
{
CRYSError_t ret = 0;
byte e[3];
word32 eSz = sizeof(e);
byte n[256];
word32 nSz = sizeof(n);
byte d[256];
word32 dSz = sizeof(d);
byte p[128];
word32 pSz = sizeof(p);
byte q[128];
word32 qSz = sizeof(q);
if (key == NULL) {
return BAD_FUNC_ARG;
}
ret = wc_RsaExportKey(key, e, &eSz, n, &nSz, d, &dSz, p, &pSz, q, &qSz);
if (ret != 0)
return MP_READ_E;
ret = CRYS_RSA_Build_PubKey(&key->ctx.pubKey, e, eSz, n, nSz);
if (ret != SA_SILIB_RET_OK){
WOLFSSL_MSG("CRYS_RSA_Build_PubKey failed");
return ret;
}
ret = CRYS_RSA_Build_PrivKey(&key->ctx.privKey, d, dSz, e, eSz, n, nSz);
if (ret != SA_SILIB_RET_OK){
WOLFSSL_MSG("CRYS_RSA_Build_PrivKey failed");
return ret;
}
key->type = RSA_PRIVATE;
return 0;
}
static int cc310_RSA_GenerateKeyPair(RsaKey* key, int size, long e)
{
CRYSError_t ret = 0;
CRYS_RSAKGData_t KeyGenData;
CRYS_RSAKGFipsContext_t FipsCtx;
byte ex[3];
uint16_t eSz = sizeof(ex);
byte n[256];
uint16_t nSz = sizeof(n);
ret = CRYS_RSA_KG_GenerateKeyPair(&wc_rndState,
wc_rndGenVectFunc,
(byte*)&e,
3*sizeof(uint8_t),
size,
&key->ctx.privKey,
&key->ctx.pubKey,
&KeyGenData,
&FipsCtx);
if (ret != SA_SILIB_RET_OK){
WOLFSSL_MSG("CRYS_RSA_KG_GenerateKeyPair failed");
return ret;
}
ret = CRYS_RSA_Get_PubKey(&key->ctx.pubKey, ex, &eSz, n, &nSz);
if (ret != SA_SILIB_RET_OK){
WOLFSSL_MSG("CRYS_RSA_Get_PubKey failed");
return ret;
}
ret = wc_RsaPublicKeyDecodeRaw(n, nSz, ex, eSz, key);
key->type = RSA_PRIVATE;
return ret;
}
#endif /* WOLFSSL_CRYPTOCELL */
int wc_FreeRsaKey(RsaKey* key)
{
int ret = 0;
if (key == NULL) {
return BAD_FUNC_ARG;
}
wc_RsaCleanup(key);
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA)
wolfAsync_DevCtxFree(&key->asyncDev, WOLFSSL_ASYNC_MARKER_RSA);
#endif
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
if (key->type == RSA_PRIVATE) {
#if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)
mp_forcezero(&key->u);
mp_forcezero(&key->dQ);
mp_forcezero(&key->dP);
#endif
mp_forcezero(&key->q);
mp_forcezero(&key->p);
mp_forcezero(&key->d);
}
/* private part */
#if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)
mp_clear(&key->u);
mp_clear(&key->dQ);
mp_clear(&key->dP);
#endif
mp_clear(&key->q);
mp_clear(&key->p);
mp_clear(&key->d);
#endif /* WOLFSSL_RSA_PUBLIC_ONLY */
/* public part */
mp_clear(&key->e);
mp_clear(&key->n);
#ifdef WOLFSSL_XILINX_CRYPT
XFREE(key->mod, key->heap, DYNAMIC_TYPE_KEY);
key->mod = NULL;
#endif
#ifdef WOLFSSL_AFALG_XILINX_RSA
/* make sure that sockets are closed on cleanup */
if (key->alFd > 0) {
close(key->alFd);
key->alFd = WC_SOCK_NOTSET;
}
if (key->rdFd > 0) {
close(key->rdFd);
key->rdFd = WC_SOCK_NOTSET;
}
#endif
return ret;
}
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
#if defined(WOLFSSL_KEY_GEN) && !defined(WOLFSSL_NO_RSA_KEY_CHECK)
/* Check the pair-wise consistency of the RSA key.
* From NIST SP 800-56B, section 6.4.1.1.
* Verify that k = (k^e)^d, for some k: 1 < k < n-1. */
int wc_CheckRsaKey(RsaKey* key)
{
#if defined(WOLFSSL_CRYPTOCELL)
return 0;
#endif
#ifdef WOLFSSL_SMALL_STACK
mp_int *k = NULL, *tmp = NULL;
#else
mp_int k[1], tmp[1];
#endif
int ret = 0;
#ifdef WOLFSSL_SMALL_STACK
k = (mp_int*)XMALLOC(sizeof(mp_int) * 2, NULL, DYNAMIC_TYPE_RSA);
if (k == NULL)
return MEMORY_E;
tmp = k + 1;
#endif
if (mp_init_multi(k, tmp, NULL, NULL, NULL, NULL) != MP_OKAY)
ret = MP_INIT_E;
if (ret == 0) {
if (key == NULL)
ret = BAD_FUNC_ARG;
}
if (ret == 0) {
if (mp_set_int(k, 0x2342) != MP_OKAY)
ret = MP_READ_E;
}
#ifdef WOLFSSL_HAVE_SP_RSA
if (ret == 0) {
switch (mp_count_bits(&key->n)) {
#ifndef WOLFSSL_SP_NO_2048
case 2048:
ret = sp_ModExp_2048(k, &key->e, &key->n, tmp);
if (ret != 0)
ret = MP_EXPTMOD_E;
if (ret == 0) {
ret = sp_ModExp_2048(tmp, &key->d, &key->n, tmp);
if (ret != 0)
ret = MP_EXPTMOD_E;
}
break;
#endif /* WOLFSSL_SP_NO_2048 */
#ifndef WOLFSSL_SP_NO_3072
case 3072:
ret = sp_ModExp_3072(k, &key->e, &key->n, tmp);
if (ret != 0)
ret = MP_EXPTMOD_E;
if (ret == 0) {
ret = sp_ModExp_3072(tmp, &key->d, &key->n, tmp);
if (ret != 0)
ret = MP_EXPTMOD_E;
}
break;
#endif /* WOLFSSL_SP_NO_3072 */
#ifdef WOLFSSL_SP_4096
case 4096:
ret = sp_ModExp_4096(k, &key->e, &key->n, tmp);
if (ret != 0)
ret = MP_EXPTMOD_E;
if (ret == 0) {
ret = sp_ModExp_4096(tmp, &key->d, &key->n, tmp);
if (ret != 0)
ret = MP_EXPTMOD_E;
}
break;
#endif /* WOLFSSL_SP_4096 */
default:
/* If using only single prcsision math then issue key size error,
otherwise fall-back to multi-precision math calculation */
#ifdef WOLFSSL_SP_MATH
ret = WC_KEY_SIZE_E;
#endif
break;
}
}
#endif /* WOLFSSL_HAVE_SP_RSA */
#ifndef WOLFSSL_SP_MATH
if (ret == 0) {
if (mp_exptmod(k, &key->e, &key->n, tmp) != MP_OKAY)
ret = MP_EXPTMOD_E;
}
if (ret == 0) {
if (mp_exptmod(tmp, &key->d, &key->n, tmp) != MP_OKAY)
ret = MP_EXPTMOD_E;
}
#endif /* !WOLFSSL_SP_MATH */
if (ret == 0) {
if (mp_cmp(k, tmp) != MP_EQ)
ret = RSA_KEY_PAIR_E;
}
/* Check d is less than n. */
if (ret == 0 ) {
if (mp_cmp(&key->d, &key->n) != MP_LT) {
ret = MP_EXPTMOD_E;
}
}
/* Check p*q = n. */
if (ret == 0 ) {
if (mp_mul(&key->p, &key->q, tmp) != MP_OKAY) {
ret = MP_EXPTMOD_E;
}
}
if (ret == 0 ) {
if (mp_cmp(&key->n, tmp) != MP_EQ) {
ret = MP_EXPTMOD_E;
}
}
/* Check dP, dQ and u if they exist */
if (ret == 0 && !mp_iszero(&key->dP)) {
if (mp_sub_d(&key->p, 1, tmp) != MP_OKAY) {
ret = MP_EXPTMOD_E;
}
/* Check dP <= p-1. */
if (ret == 0) {
if (mp_cmp(&key->dP, tmp) != MP_LT) {
ret = MP_EXPTMOD_E;
}
}
/* Check e*dP mod p-1 = 1. (dP = 1/e mod p-1) */
if (ret == 0) {
if (mp_mulmod(&key->dP, &key->e, tmp, tmp) != MP_OKAY) {
ret = MP_EXPTMOD_E;
}
}
if (ret == 0 ) {
if (!mp_isone(tmp)) {
ret = MP_EXPTMOD_E;
}
}
if (ret == 0) {
if (mp_sub_d(&key->q, 1, tmp) != MP_OKAY) {
ret = MP_EXPTMOD_E;
}
}
/* Check dQ <= q-1. */
if (ret == 0) {
if (mp_cmp(&key->dQ, tmp) != MP_LT) {
ret = MP_EXPTMOD_E;
}
}
/* Check e*dP mod p-1 = 1. (dQ = 1/e mod q-1) */
if (ret == 0) {
if (mp_mulmod(&key->dQ, &key->e, tmp, tmp) != MP_OKAY) {
ret = MP_EXPTMOD_E;
}
}
if (ret == 0 ) {
if (!mp_isone(tmp)) {
ret = MP_EXPTMOD_E;
}
}
/* Check u <= p. */
if (ret == 0) {
if (mp_cmp(&key->u, &key->p) != MP_LT) {
ret = MP_EXPTMOD_E;
}
}
/* Check u*q mod p = 1. (u = 1/q mod p) */
if (ret == 0) {
if (mp_mulmod(&key->u, &key->q, &key->p, tmp) != MP_OKAY) {
ret = MP_EXPTMOD_E;
}
}
if (ret == 0 ) {
if (!mp_isone(tmp)) {
ret = MP_EXPTMOD_E;
}
}
}
mp_forcezero(tmp);
mp_clear(tmp);
mp_clear(k);
#ifdef WOLFSSL_SMALL_STACK
XFREE(k, NULL, DYNAMIC_TYPE_RSA);
#endif
return ret;
}
#endif /* WOLFSSL_KEY_GEN && !WOLFSSL_NO_RSA_KEY_CHECK */
#endif /* WOLFSSL_RSA_PUBLIC_ONLY */
#if !defined(WC_NO_RSA_OAEP) || defined(WC_RSA_PSS)
/* Uses MGF1 standard as a mask generation function
hType: hash type used
seed: seed to use for generating mask
seedSz: size of seed buffer
out: mask output after generation
outSz: size of output buffer
*/
#if !defined(NO_SHA) || !defined(NO_SHA256) || defined(WOLFSSL_SHA384) || defined(WOLFSSL_SHA512)
static int RsaMGF1(enum wc_HashType hType, byte* seed, word32 seedSz,
byte* out, word32 outSz, void* heap)
{
byte* tmp;
/* needs to be large enough for seed size plus counter(4) */
byte tmpA[WC_MAX_DIGEST_SIZE + 4];
byte tmpF; /* 1 if dynamic memory needs freed */
word32 tmpSz;
int hLen;
int ret;
word32 counter;
word32 idx;
hLen = wc_HashGetDigestSize(hType);
counter = 0;
idx = 0;
(void)heap;
/* check error return of wc_HashGetDigestSize */
if (hLen < 0) {
return hLen;
}
/* if tmp is not large enough than use some dynamic memory */
if ((seedSz + 4) > sizeof(tmpA) || (word32)hLen > sizeof(tmpA)) {
/* find largest amount of memory needed which will be the max of
* hLen and (seedSz + 4) since tmp is used to store the hash digest */
tmpSz = ((seedSz + 4) > (word32)hLen)? seedSz + 4: (word32)hLen;
tmp = (byte*)XMALLOC(tmpSz, heap, DYNAMIC_TYPE_RSA_BUFFER);
if (tmp == NULL) {
return MEMORY_E;
}
tmpF = 1; /* make sure to free memory when done */
}
else {
/* use array on the stack */
tmpSz = sizeof(tmpA);
tmp = tmpA;
tmpF = 0; /* no need to free memory at end */
}
do {
int i = 0;
XMEMCPY(tmp, seed, seedSz);
/* counter to byte array appended to tmp */
tmp[seedSz] = (byte)((counter >> 24) & 0xFF);
tmp[seedSz + 1] = (byte)((counter >> 16) & 0xFF);
tmp[seedSz + 2] = (byte)((counter >> 8) & 0xFF);
tmp[seedSz + 3] = (byte)((counter) & 0xFF);
/* hash and append to existing output */
if ((ret = wc_Hash(hType, tmp, (seedSz + 4), tmp, tmpSz)) != 0) {
/* check for if dynamic memory was needed, then free */
if (tmpF) {
XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
}
return ret;
}
for (i = 0; i < hLen && idx < outSz; i++) {
out[idx++] = tmp[i];
}
counter++;
} while (idx < outSz);
/* check for if dynamic memory was needed, then free */
if (tmpF) {
XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
}
return 0;
}
#endif /* SHA2 Hashes */
/* helper function to direct which mask generation function is used
switched on type input
*/
static int RsaMGF(int type, byte* seed, word32 seedSz, byte* out,
word32 outSz, void* heap)
{
int ret;
switch(type) {
#ifndef NO_SHA
case WC_MGF1SHA1:
ret = RsaMGF1(WC_HASH_TYPE_SHA, seed, seedSz, out, outSz, heap);
break;
#endif
#ifndef NO_SHA256
#ifdef WOLFSSL_SHA224
case WC_MGF1SHA224:
ret = RsaMGF1(WC_HASH_TYPE_SHA224, seed, seedSz, out, outSz, heap);
break;
#endif
case WC_MGF1SHA256:
ret = RsaMGF1(WC_HASH_TYPE_SHA256, seed, seedSz, out, outSz, heap);
break;
#endif
#ifdef WOLFSSL_SHA384
case WC_MGF1SHA384:
ret = RsaMGF1(WC_HASH_TYPE_SHA384, seed, seedSz, out, outSz, heap);
break;
#endif
#ifdef WOLFSSL_SHA512
case WC_MGF1SHA512:
ret = RsaMGF1(WC_HASH_TYPE_SHA512, seed, seedSz, out, outSz, heap);
break;
#endif
default:
WOLFSSL_MSG("Unknown MGF type: check build options");
ret = BAD_FUNC_ARG;
}
/* in case of default avoid unused warning */
(void)seed;
(void)seedSz;
(void)out;
(void)outSz;
(void)heap;
return ret;
}
#endif /* !WC_NO_RSA_OAEP || WC_RSA_PSS */
/* Padding */
#ifndef WOLFSSL_RSA_VERIFY_ONLY
#ifndef WC_NO_RNG
#ifndef WC_NO_RSA_OAEP
static int RsaPad_OAEP(const byte* input, word32 inputLen, byte* pkcsBlock,
word32 pkcsBlockLen, byte padValue, WC_RNG* rng,
enum wc_HashType hType, int mgf, byte* optLabel, word32 labelLen,
void* heap)
{
int ret;
int hLen;
int psLen;
int i;
word32 idx;
byte* dbMask;
#ifdef WOLFSSL_SMALL_STACK
byte* lHash = NULL;
byte* seed = NULL;
#else
/* must be large enough to contain largest hash */
byte lHash[WC_MAX_DIGEST_SIZE];
byte seed[ WC_MAX_DIGEST_SIZE];
#endif
/* no label is allowed, but catch if no label provided and length > 0 */
if (optLabel == NULL && labelLen > 0) {
return BUFFER_E;
}
/* limit of label is the same as limit of hash function which is massive */
hLen = wc_HashGetDigestSize(hType);
if (hLen < 0) {
return hLen;
}
#ifdef WOLFSSL_SMALL_STACK
lHash = (byte*)XMALLOC(hLen, heap, DYNAMIC_TYPE_RSA_BUFFER);
if (lHash == NULL) {
return MEMORY_E;
}
seed = (byte*)XMALLOC(hLen, heap, DYNAMIC_TYPE_RSA_BUFFER);
if (seed == NULL) {
XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
return MEMORY_E;
}
#else
/* hLen should never be larger than lHash since size is max digest size,
but check before blindly calling wc_Hash */
if ((word32)hLen > sizeof(lHash)) {
WOLFSSL_MSG("OAEP lHash to small for digest!!");
return MEMORY_E;
}
#endif
if ((ret = wc_Hash(hType, optLabel, labelLen, lHash, hLen)) != 0) {
WOLFSSL_MSG("OAEP hash type possibly not supported or lHash to small");
#ifdef WOLFSSL_SMALL_STACK
XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
#endif
return ret;
}
/* handles check of location for idx as well as psLen, cast to int to check
for pkcsBlockLen(k) - 2 * hLen - 2 being negative
This check is similar to decryption where k > 2 * hLen + 2 as msg
size approaches 0. In decryption if k is less than or equal -- then there
is no possible room for msg.
k = RSA key size
hLen = hash digest size -- will always be >= 0 at this point
*/
if ((word32)(2 * hLen + 2) > pkcsBlockLen) {
WOLFSSL_MSG("OAEP pad error hash to big for RSA key size");
#ifdef WOLFSSL_SMALL_STACK
XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
#endif
return BAD_FUNC_ARG;
}
if (inputLen > (pkcsBlockLen - 2 * hLen - 2)) {
WOLFSSL_MSG("OAEP pad error message too long");
#ifdef WOLFSSL_SMALL_STACK
XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
#endif
return BAD_FUNC_ARG;
}
/* concatenate lHash || PS || 0x01 || msg */
idx = pkcsBlockLen - 1 - inputLen;
psLen = pkcsBlockLen - inputLen - 2 * hLen - 2;
if (pkcsBlockLen < inputLen) { /*make sure not writing over end of buffer */
#ifdef WOLFSSL_SMALL_STACK
XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
#endif
return BUFFER_E;
}
XMEMCPY(pkcsBlock + (pkcsBlockLen - inputLen), input, inputLen);
pkcsBlock[idx--] = 0x01; /* PS and M separator */
while (psLen > 0 && idx > 0) {
pkcsBlock[idx--] = 0x00;
psLen--;
}
idx = idx - hLen + 1;
XMEMCPY(pkcsBlock + idx, lHash, hLen);
/* generate random seed */
if ((ret = wc_RNG_GenerateBlock(rng, seed, hLen)) != 0) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
#endif
return ret;
}
/* create maskedDB from dbMask */
dbMask = (byte*)XMALLOC(pkcsBlockLen - hLen - 1, heap, DYNAMIC_TYPE_RSA);
if (dbMask == NULL) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
#endif
return MEMORY_E;
}
XMEMSET(dbMask, 0, pkcsBlockLen - hLen - 1); /* help static analyzer */
ret = RsaMGF(mgf, seed, hLen, dbMask, pkcsBlockLen - hLen - 1, heap);
if (ret != 0) {
XFREE(dbMask, heap, DYNAMIC_TYPE_RSA);
#ifdef WOLFSSL_SMALL_STACK
XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
#endif
return ret;
}
i = 0;
idx = hLen + 1;
while (idx < pkcsBlockLen && (word32)i < (pkcsBlockLen - hLen -1)) {
pkcsBlock[idx] = dbMask[i++] ^ pkcsBlock[idx];
idx++;
}
XFREE(dbMask, heap, DYNAMIC_TYPE_RSA);
/* create maskedSeed from seedMask */
idx = 0;
pkcsBlock[idx++] = 0x00;
/* create seedMask inline */
if ((ret = RsaMGF(mgf, pkcsBlock + hLen + 1, pkcsBlockLen - hLen - 1,
pkcsBlock + 1, hLen, heap)) != 0) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
#endif
return ret;
}
/* xor created seedMask with seed to make maskedSeed */
i = 0;
while (idx < (word32)(hLen + 1) && i < hLen) {
pkcsBlock[idx] = pkcsBlock[idx] ^ seed[i++];
idx++;
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
#endif
(void)padValue;
return 0;
}
#endif /* !WC_NO_RSA_OAEP */
#ifdef WC_RSA_PSS
/* 0x00 .. 0x00 0x01 | Salt | Gen Hash | 0xbc
* XOR MGF over all bytes down to end of Salt
* Gen Hash = HASH(8 * 0x00 | Message Hash | Salt)
*
* input Digest of the message.
* inputLen Length of digest.
* pkcsBlock Buffer to write to.
* pkcsBlockLen Length of buffer to write to.
* rng Random number generator (for salt).
* htype Hash function to use.
* mgf Mask generation function.
* saltLen Length of salt to put in padding.
* bits Length of key in bits.
* heap Used for dynamic memory allocation.
* returns 0 on success, PSS_SALTLEN_E when the salt length is invalid
* and other negative values on error.
*/
static int RsaPad_PSS(const byte* input, word32 inputLen, byte* pkcsBlock,
word32 pkcsBlockLen, WC_RNG* rng, enum wc_HashType hType, int mgf,
int saltLen, int bits, void* heap)
{
int ret = 0;
int hLen, i, o, maskLen, hiBits;
byte* m;
byte* s;
#if defined(WOLFSSL_PSS_LONG_SALT) || defined(WOLFSSL_PSS_SALT_LEN_DISCOVER)
#if defined(WOLFSSL_NO_MALLOC) && !defined(WOLFSSL_STATIC_MEMORY)
byte salt[RSA_MAX_SIZE/8 + RSA_PSS_PAD_SZ];
#else
byte* salt = NULL;
#endif
#else
byte salt[WC_MAX_DIGEST_SIZE];
#endif
#if defined(WOLFSSL_PSS_LONG_SALT) || defined(WOLFSSL_PSS_SALT_LEN_DISCOVER)
if (pkcsBlockLen > RSA_MAX_SIZE/8) {
return MEMORY_E;
}
#endif
hLen = wc_HashGetDigestSize(hType);
if (hLen < 0)
return hLen;
if ((int)inputLen != hLen) {
return BAD_FUNC_ARG;
}
hiBits = (bits - 1) & 0x7;
if (hiBits == 0) {
/* Per RFC8017, set the leftmost 8emLen - emBits bits of the
leftmost octet in DB to zero.
*/
*(pkcsBlock++) = 0;
pkcsBlockLen--;
}
if (saltLen == RSA_PSS_SALT_LEN_DEFAULT) {
saltLen = hLen;
#ifdef WOLFSSL_SHA512
/* See FIPS 186-4 section 5.5 item (e). */
if (bits == 1024 && hLen == WC_SHA512_DIGEST_SIZE) {
saltLen = RSA_PSS_SALT_MAX_SZ;
}
#endif
}
#ifndef WOLFSSL_PSS_LONG_SALT
else if (saltLen > hLen) {
return PSS_SALTLEN_E;
}
#endif
#ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
else if (saltLen < RSA_PSS_SALT_LEN_DEFAULT) {
return PSS_SALTLEN_E;
}
#else
else if (saltLen == RSA_PSS_SALT_LEN_DISCOVER) {
saltLen = (int)pkcsBlockLen - hLen - 2;
if (saltLen < 0) {
return PSS_SALTLEN_E;
}
}
else if (saltLen < RSA_PSS_SALT_LEN_DISCOVER) {
return PSS_SALTLEN_E;
}
#endif
if ((int)pkcsBlockLen - hLen < saltLen + 2) {
return PSS_SALTLEN_E;
}
maskLen = pkcsBlockLen - 1 - hLen;
#if defined(WOLFSSL_PSS_LONG_SALT) || defined(WOLFSSL_PSS_SALT_LEN_DISCOVER)
#if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
salt = (byte*)XMALLOC(RSA_PSS_PAD_SZ + inputLen + saltLen, heap,
DYNAMIC_TYPE_RSA_BUFFER);
if (salt == NULL) {
return MEMORY_E;
}
#endif
s = m = salt;
XMEMSET(m, 0, RSA_PSS_PAD_SZ);
m += RSA_PSS_PAD_SZ;
XMEMCPY(m, input, inputLen);
m += inputLen;
o = (int)(m - s);
if (saltLen > 0) {
ret = wc_RNG_GenerateBlock(rng, m, saltLen);
if (ret == 0) {
m += saltLen;
}
}
#else
s = m = pkcsBlock;
XMEMSET(m, 0, RSA_PSS_PAD_SZ);
m += RSA_PSS_PAD_SZ;
XMEMCPY(m, input, inputLen);
m += inputLen;
o = 0;
if (saltLen > 0) {
ret = wc_RNG_GenerateBlock(rng, salt, saltLen);
if (ret == 0) {
XMEMCPY(m, salt, saltLen);
m += saltLen;
}
}
#endif
if (ret == 0) {
/* Put Hash at end of pkcsBlock - 1 */
ret = wc_Hash(hType, s, (word32)(m - s), pkcsBlock + maskLen, hLen);
}
if (ret == 0) {
/* Set the last eight bits or trailer field to the octet 0xbc */
pkcsBlock[pkcsBlockLen - 1] = RSA_PSS_PAD_TERM;
ret = RsaMGF(mgf, pkcsBlock + maskLen, hLen, pkcsBlock, maskLen, heap);
}
if (ret == 0) {
/* Clear the first high bit when "8emLen - emBits" is non-zero.
where emBits = n modBits - 1 */
if (hiBits)
pkcsBlock[0] &= (1 << hiBits) - 1;
m = pkcsBlock + maskLen - saltLen - 1;
*(m++) ^= 0x01;
for (i = 0; i < saltLen; i++) {
m[i] ^= salt[o + i];
}
}
#if defined(WOLFSSL_PSS_LONG_SALT) || defined(WOLFSSL_PSS_SALT_LEN_DISCOVER)
#if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
if (salt != NULL) {
XFREE(salt, heap, DYNAMIC_TYPE_RSA_BUFFER);
}
#endif
#endif
return ret;
}
#endif /* WC_RSA_PSS */
#endif /* !WC_NO_RNG */
static int RsaPad(const byte* input, word32 inputLen, byte* pkcsBlock,
word32 pkcsBlockLen, byte padValue, WC_RNG* rng)
{
if (input == NULL || inputLen == 0 || pkcsBlock == NULL ||
pkcsBlockLen == 0) {
return BAD_FUNC_ARG;
}
if (pkcsBlockLen - RSA_MIN_PAD_SZ < inputLen) {
WOLFSSL_MSG("RsaPad error, invalid length");
return RSA_PAD_E;
}
pkcsBlock[0] = 0x0; /* set first byte to zero and advance */
pkcsBlock++; pkcsBlockLen--;
pkcsBlock[0] = padValue; /* insert padValue */
if (padValue == RSA_BLOCK_TYPE_1) {
/* pad with 0xff bytes */
XMEMSET(&pkcsBlock[1], 0xFF, pkcsBlockLen - inputLen - 2);
}
else {
#if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WC_NO_RNG)
/* pad with non-zero random bytes */
word32 padLen, i;
int ret;
padLen = pkcsBlockLen - inputLen - 1;
ret = wc_RNG_GenerateBlock(rng, &pkcsBlock[1], padLen);
if (ret != 0) {
return ret;
}
/* remove zeros */
for (i = 1; i < padLen; i++) {
if (pkcsBlock[i] == 0) pkcsBlock[i] = 0x01;
}
#else
(void)rng;
return RSA_WRONG_TYPE_E;
#endif
}
pkcsBlock[pkcsBlockLen-inputLen-1] = 0; /* separator */
XMEMCPY(pkcsBlock+pkcsBlockLen-inputLen, input, inputLen);
return 0;
}
/* helper function to direct which padding is used */
int wc_RsaPad_ex(const byte* input, word32 inputLen, byte* pkcsBlock,
word32 pkcsBlockLen, byte padValue, WC_RNG* rng, int padType,
enum wc_HashType hType, int mgf, byte* optLabel, word32 labelLen,
int saltLen, int bits, void* heap)
{
int ret;
switch (padType)
{
case WC_RSA_PKCSV15_PAD:
/*WOLFSSL_MSG("wolfSSL Using RSA PKCSV15 padding");*/
ret = RsaPad(input, inputLen, pkcsBlock, pkcsBlockLen,
padValue, rng);
break;
#ifndef WC_NO_RNG
#ifndef WC_NO_RSA_OAEP
case WC_RSA_OAEP_PAD:
WOLFSSL_MSG("wolfSSL Using RSA OAEP padding");
ret = RsaPad_OAEP(input, inputLen, pkcsBlock, pkcsBlockLen,
padValue, rng, hType, mgf, optLabel, labelLen, heap);
break;
#endif
#ifdef WC_RSA_PSS
case WC_RSA_PSS_PAD:
WOLFSSL_MSG("wolfSSL Using RSA PSS padding");
ret = RsaPad_PSS(input, inputLen, pkcsBlock, pkcsBlockLen, rng,
hType, mgf, saltLen, bits, heap);
break;
#endif
#endif /* !WC_NO_RNG */
#ifdef WC_RSA_NO_PADDING
case WC_RSA_NO_PAD:
WOLFSSL_MSG("wolfSSL Using NO padding");
/* In the case of no padding being used check that input is exactly
* the RSA key length */
if (bits <= 0 || inputLen != ((word32)bits/WOLFSSL_BIT_SIZE)) {
WOLFSSL_MSG("Bad input size");
ret = RSA_PAD_E;
}
else {
XMEMCPY(pkcsBlock, input, inputLen);
ret = 0;
}
break;
#endif
default:
WOLFSSL_MSG("Unknown RSA Pad Type");
ret = RSA_PAD_E;
}
/* silence warning if not used with padding scheme */
(void)input;
(void)inputLen;
(void)pkcsBlock;
(void)pkcsBlockLen;
(void)padValue;
(void)rng;
(void)padType;
(void)hType;
(void)mgf;
(void)optLabel;
(void)labelLen;
(void)saltLen;
(void)bits;
(void)heap;
return ret;
}
#endif /* WOLFSSL_RSA_VERIFY_ONLY */
/* UnPadding */
#ifndef WC_NO_RSA_OAEP
/* UnPad plaintext, set start to *output, return length of plaintext,
* < 0 on error */
static int RsaUnPad_OAEP(byte *pkcsBlock, unsigned int pkcsBlockLen,
byte **output, enum wc_HashType hType, int mgf,
byte* optLabel, word32 labelLen, void* heap)
{
int hLen;
int ret;
byte h[WC_MAX_DIGEST_SIZE]; /* max digest size */
byte* tmp;
word32 idx;
/* no label is allowed, but catch if no label provided and length > 0 */
if (optLabel == NULL && labelLen > 0) {
return BUFFER_E;
}
hLen = wc_HashGetDigestSize(hType);
if ((hLen < 0) || (pkcsBlockLen < (2 * (word32)hLen + 2))) {
return BAD_FUNC_ARG;
}
tmp = (byte*)XMALLOC(pkcsBlockLen, heap, DYNAMIC_TYPE_RSA_BUFFER);
if (tmp == NULL) {
return MEMORY_E;
}
XMEMSET(tmp, 0, pkcsBlockLen);
/* find seedMask value */
if ((ret = RsaMGF(mgf, (byte*)(pkcsBlock + (hLen + 1)),
pkcsBlockLen - hLen - 1, tmp, hLen, heap)) != 0) {
XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
return ret;
}
/* xor seedMask value with maskedSeed to get seed value */
for (idx = 0; idx < (word32)hLen; idx++) {
tmp[idx] = tmp[idx] ^ pkcsBlock[1 + idx];
}
/* get dbMask value */
if ((ret = RsaMGF(mgf, tmp, hLen, tmp + hLen,
pkcsBlockLen - hLen - 1, heap)) != 0) {
XFREE(tmp, NULL, DYNAMIC_TYPE_RSA_BUFFER);
return ret;
}
/* get DB value by doing maskedDB xor dbMask */
for (idx = 0; idx < (pkcsBlockLen - hLen - 1); idx++) {
pkcsBlock[hLen + 1 + idx] = pkcsBlock[hLen + 1 + idx] ^ tmp[idx + hLen];
}
/* done with use of tmp buffer */
XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
/* advance idx to index of PS and msg separator, account for PS size of 0*/
idx = hLen + 1 + hLen;
while (idx < pkcsBlockLen && pkcsBlock[idx] == 0) {idx++;}
/* create hash of label for comparison with hash sent */
if ((ret = wc_Hash(hType, optLabel, labelLen, h, hLen)) != 0) {
return ret;
}
/* say no to chosen ciphertext attack.
Comparison of lHash, Y, and separator value needs to all happen in
constant time.
Attackers should not be able to get error condition from the timing of
these checks.
*/
ret = 0;
ret |= ConstantCompare(pkcsBlock + hLen + 1, h, hLen);
ret += pkcsBlock[idx++] ^ 0x01; /* separator value is 0x01 */
ret += pkcsBlock[0] ^ 0x00; /* Y, the first value, should be 0 */
/* Return 0 data length on error. */
idx = ctMaskSelInt(ctMaskEq(ret, 0), idx, pkcsBlockLen);
/* adjust pointer to correct location in array and return size of M */
*output = (byte*)(pkcsBlock + idx);
return pkcsBlockLen - idx;
}
#endif /* WC_NO_RSA_OAEP */
#ifdef WC_RSA_PSS
/* 0x00 .. 0x00 0x01 | Salt | Gen Hash | 0xbc
* MGF over all bytes down to end of Salt
*
* pkcsBlock Buffer holding decrypted data.
* pkcsBlockLen Length of buffer.
* htype Hash function to use.
* mgf Mask generation function.
* saltLen Length of salt to put in padding.
* bits Length of key in bits.
* heap Used for dynamic memory allocation.
* returns the sum of salt length and SHA-256 digest size on success.
* Otherwise, PSS_SALTLEN_E for an incorrect salt length,
* WC_KEY_SIZE_E for an incorrect encoded message (EM) size
and other negative values on error.
*/
static int RsaUnPad_PSS(byte *pkcsBlock, unsigned int pkcsBlockLen,
byte **output, enum wc_HashType hType, int mgf,
int saltLen, int bits, void* heap)
{
int ret;
byte* tmp;
int hLen, i, maskLen;
#ifdef WOLFSSL_SHA512
int orig_bits = bits;
#endif
#if defined(WOLFSSL_NO_MALLOC) && !defined(WOLFSSL_STATIC_MEMORY)
byte tmp_buf[RSA_MAX_SIZE/8];
tmp = tmp_buf;
if (pkcsBlockLen > RSA_MAX_SIZE/8) {
return MEMORY_E;
}
#endif
hLen = wc_HashGetDigestSize(hType);
if (hLen < 0)
return hLen;
bits = (bits - 1) & 0x7;
if ((pkcsBlock[0] & (0xff << bits)) != 0) {
return BAD_PADDING_E;
}
if (bits == 0) {
pkcsBlock++;
pkcsBlockLen--;
}
maskLen = (int)pkcsBlockLen - 1 - hLen;
if (maskLen < 0) {
WOLFSSL_MSG("RsaUnPad_PSS: Hash too large");
return WC_KEY_SIZE_E;
}
if (saltLen == RSA_PSS_SALT_LEN_DEFAULT) {
saltLen = hLen;
#ifdef WOLFSSL_SHA512
/* See FIPS 186-4 section 5.5 item (e). */
if (orig_bits == 1024 && hLen == WC_SHA512_DIGEST_SIZE)
saltLen = RSA_PSS_SALT_MAX_SZ;
#endif
}
#ifndef WOLFSSL_PSS_LONG_SALT
else if (saltLen > hLen)
return PSS_SALTLEN_E;
#endif
#ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
else if (saltLen < RSA_PSS_SALT_LEN_DEFAULT)
return PSS_SALTLEN_E;
if (maskLen < saltLen + 1) {
return PSS_SALTLEN_E;
}
#else
else if (saltLen < RSA_PSS_SALT_LEN_DISCOVER)
return PSS_SALTLEN_E;
if (saltLen != RSA_PSS_SALT_LEN_DISCOVER && maskLen < saltLen + 1) {
return WC_KEY_SIZE_E;
}
#endif
if (pkcsBlock[pkcsBlockLen - 1] != RSA_PSS_PAD_TERM) {
WOLFSSL_MSG("RsaUnPad_PSS: Padding Term Error");
return BAD_PADDING_E;
}
#if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
tmp = (byte*)XMALLOC(maskLen, heap, DYNAMIC_TYPE_RSA_BUFFER);
if (tmp == NULL) {
return MEMORY_E;
}
#endif
if ((ret = RsaMGF(mgf, pkcsBlock + maskLen, hLen, tmp, maskLen,
heap)) != 0) {
XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
return ret;
}
tmp[0] &= (1 << bits) - 1;
pkcsBlock[0] &= (1 << bits) - 1;
#ifdef WOLFSSL_PSS_SALT_LEN_DISCOVER
if (saltLen == RSA_PSS_SALT_LEN_DISCOVER) {
for (i = 0; i < maskLen - 1; i++) {
if (tmp[i] != pkcsBlock[i]) {
break;
}
}
if (tmp[i] != (pkcsBlock[i] ^ 0x01)) {
XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
WOLFSSL_MSG("RsaUnPad_PSS: Padding Error Match");
return PSS_SALTLEN_RECOVER_E;
}
saltLen = maskLen - (i + 1);
}
else
#endif
{
for (i = 0; i < maskLen - 1 - saltLen; i++) {
if (tmp[i] != pkcsBlock[i]) {
XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
WOLFSSL_MSG("RsaUnPad_PSS: Padding Error Match");
return PSS_SALTLEN_E;
}
}
if (tmp[i] != (pkcsBlock[i] ^ 0x01)) {
XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
WOLFSSL_MSG("RsaUnPad_PSS: Padding Error End");
return PSS_SALTLEN_E;
}
}
for (i++; i < maskLen; i++)
pkcsBlock[i] ^= tmp[i];
#if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
#endif
*output = pkcsBlock + maskLen - saltLen;
return saltLen + hLen;
}
#endif
/* UnPad plaintext, set start to *output, return length of plaintext,
* < 0 on error */
static int RsaUnPad(const byte *pkcsBlock, unsigned int pkcsBlockLen,
byte **output, byte padValue)
{
int ret = BAD_FUNC_ARG;
word16 i;
#ifndef WOLFSSL_RSA_VERIFY_ONLY
byte invalid = 0;
#endif
if (output == NULL || pkcsBlockLen < 2 || pkcsBlockLen > 0xFFFF) {
return BAD_FUNC_ARG;
}
if (padValue == RSA_BLOCK_TYPE_1) {
/* First byte must be 0x00 and Second byte, block type, 0x01 */
if (pkcsBlock[0] != 0 || pkcsBlock[1] != RSA_BLOCK_TYPE_1) {
WOLFSSL_MSG("RsaUnPad error, invalid formatting");
return RSA_PAD_E;
}
/* check the padding until we find the separator */
for (i = 2; i < pkcsBlockLen && pkcsBlock[i++] == 0xFF; ) { }
/* Minimum of 11 bytes of pre-message data and must have separator. */
if (i < RSA_MIN_PAD_SZ || pkcsBlock[i-1] != 0) {
WOLFSSL_MSG("RsaUnPad error, bad formatting");
return RSA_PAD_E;
}
*output = (byte *)(pkcsBlock + i);
ret = pkcsBlockLen - i;
}
#ifndef WOLFSSL_RSA_VERIFY_ONLY
else {
word16 j;
word16 pastSep = 0;
/* Decrypted with private key - unpad must be constant time. */
for (i = 0, j = 2; j < pkcsBlockLen; j++) {
/* Update i if not passed the separator and at separator. */
i |= (~pastSep) & ctMask16Eq(pkcsBlock[j], 0x00) & (j + 1);
pastSep |= ctMask16Eq(pkcsBlock[j], 0x00);
}
/* Minimum of 11 bytes of pre-message data - including leading 0x00. */
invalid |= ctMaskLT(i, RSA_MIN_PAD_SZ);
/* Must have seen separator. */
invalid |= ~pastSep;
/* First byte must be 0x00. */
invalid |= ctMaskNotEq(pkcsBlock[0], 0x00);
/* Check against expected block type: padValue */
invalid |= ctMaskNotEq(pkcsBlock[1], padValue);
*output = (byte *)(pkcsBlock + i);
ret = ((int)~invalid) & (pkcsBlockLen - i);
}
#endif
return ret;
}
/* helper function to direct unpadding
*
* bits is the key modulus size in bits
*/
int wc_RsaUnPad_ex(byte* pkcsBlock, word32 pkcsBlockLen, byte** out,
byte padValue, int padType, enum wc_HashType hType,
int mgf, byte* optLabel, word32 labelLen, int saltLen,
int bits, void* heap)
{
int ret;
switch (padType) {
case WC_RSA_PKCSV15_PAD:
/*WOLFSSL_MSG("wolfSSL Using RSA PKCSV15 un-padding");*/
ret = RsaUnPad(pkcsBlock, pkcsBlockLen, out, padValue);
break;
#ifndef WC_NO_RSA_OAEP
case WC_RSA_OAEP_PAD:
WOLFSSL_MSG("wolfSSL Using RSA OAEP un-padding");
ret = RsaUnPad_OAEP((byte*)pkcsBlock, pkcsBlockLen, out,
hType, mgf, optLabel, labelLen, heap);
break;
#endif
#ifdef WC_RSA_PSS
case WC_RSA_PSS_PAD:
WOLFSSL_MSG("wolfSSL Using RSA PSS un-padding");
ret = RsaUnPad_PSS((byte*)pkcsBlock, pkcsBlockLen, out, hType, mgf,
saltLen, bits, heap);
break;
#endif
#ifdef WC_RSA_NO_PADDING
case WC_RSA_NO_PAD:
WOLFSSL_MSG("wolfSSL Using NO un-padding");
/* In the case of no padding being used check that input is exactly
* the RSA key length */
if (bits <= 0 || pkcsBlockLen !=
((word32)(bits+WOLFSSL_BIT_SIZE-1)/WOLFSSL_BIT_SIZE)) {
WOLFSSL_MSG("Bad input size");
ret = RSA_PAD_E;
}
else {
if (out != NULL) {
*out = pkcsBlock;
}
ret = pkcsBlockLen;
}
break;
#endif /* WC_RSA_NO_PADDING */
default:
WOLFSSL_MSG("Unknown RSA UnPad Type");
ret = RSA_PAD_E;
}
/* silence warning if not used with padding scheme */
(void)hType;
(void)mgf;
(void)optLabel;
(void)labelLen;
(void)saltLen;
(void)bits;
(void)heap;
return ret;
}
#ifdef WC_RSA_NONBLOCK
static int wc_RsaFunctionNonBlock(const byte* in, word32 inLen, byte* out,
word32* outLen, int type, RsaKey* key)
{
int ret = 0;
word32 keyLen, len;
if (key == NULL || key->nb == NULL) {
return BAD_FUNC_ARG;
}
if (key->nb->exptmod.state == TFM_EXPTMOD_NB_INIT) {
if (mp_init(&key->nb->tmp) != MP_OKAY) {
ret = MP_INIT_E;
}
if (ret == 0) {
if (mp_read_unsigned_bin(&key->nb->tmp, (byte*)in, inLen) != MP_OKAY) {
ret = MP_READ_E;
}
}
}
if (ret == 0) {
switch(type) {
case RSA_PRIVATE_DECRYPT:
case RSA_PRIVATE_ENCRYPT:
ret = fp_exptmod_nb(&key->nb->exptmod, &key->nb->tmp, &key->d,
&key->n, &key->nb->tmp);
if (ret == FP_WOULDBLOCK)
return ret;
if (ret != MP_OKAY)
ret = MP_EXPTMOD_E;
break;
case RSA_PUBLIC_ENCRYPT:
case RSA_PUBLIC_DECRYPT:
ret = fp_exptmod_nb(&key->nb->exptmod, &key->nb->tmp, &key->e,
&key->n, &key->nb->tmp);
if (ret == FP_WOULDBLOCK)
return ret;
if (ret != MP_OKAY)
ret = MP_EXPTMOD_E;
break;
default:
ret = RSA_WRONG_TYPE_E;
break;
}
}
if (ret == 0) {
keyLen = wc_RsaEncryptSize(key);
if (keyLen > *outLen)
ret = RSA_BUFFER_E;
}
if (ret == 0) {
len = mp_unsigned_bin_size(&key->nb->tmp);
/* pad front w/ zeros to match key length */
while (len < keyLen) {
*out++ = 0x00;
len++;
}
*outLen = keyLen;
/* convert */
if (mp_to_unsigned_bin(&key->nb->tmp, out) != MP_OKAY) {
ret = MP_TO_E;
}
}
mp_clear(&key->nb->tmp);
return ret;
}
#endif /* WC_RSA_NONBLOCK */
#ifdef WOLFSSL_XILINX_CRYPT
/*
* Xilinx hardened crypto acceleration.
*
* Returns 0 on success and negative values on error.
*/
static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out,
word32* outLen, int type, RsaKey* key, WC_RNG* rng)
{
int ret = 0;
word32 keyLen;
(void)rng;
keyLen = wc_RsaEncryptSize(key);
if (keyLen > *outLen) {
WOLFSSL_MSG("Output buffer is not big enough");
return BAD_FUNC_ARG;
}
if (inLen != keyLen) {
WOLFSSL_MSG("Expected that inLen equals RSA key length");
return BAD_FUNC_ARG;
}
switch(type) {
case RSA_PRIVATE_DECRYPT:
case RSA_PRIVATE_ENCRYPT:
#ifdef WOLFSSL_XILINX_CRYPTO_OLD
/* Currently public exponent is loaded by default.
* In SDK 2017.1 RSA exponent values are expected to be of 4 bytes
* leading to private key operations with Xsecure_RsaDecrypt not being
* supported */
ret = RSA_WRONG_TYPE_E;
#else
{
byte *d;
int dSz;
XSecure_Rsa rsa;
dSz = mp_unsigned_bin_size(&key->d);
d = (byte*)XMALLOC(dSz, key->heap, DYNAMIC_TYPE_PRIVATE_KEY);
if (d == NULL) {
ret = MEMORY_E;
}
else {
ret = mp_to_unsigned_bin(&key->d, d);
XSecure_RsaInitialize(&rsa, key->mod, NULL, d);
}
if (ret == 0) {
if (XSecure_RsaPrivateDecrypt(&rsa, (u8*)in, inLen, out) !=
XST_SUCCESS) {
ret = BAD_STATE_E;
}
}
if (d != NULL) {
XFREE(d, key->heap, DYNAMIC_TYPE_PRIVATE_KEY);
}
}
#endif
break;
case RSA_PUBLIC_ENCRYPT:
case RSA_PUBLIC_DECRYPT:
#ifdef WOLFSSL_XILINX_CRYPTO_OLD
if (XSecure_RsaDecrypt(&(key->xRsa), in, out) != XST_SUCCESS) {
ret = BAD_STATE_E;
}
#else
/* starting at Xilinx release 2019 the function XSecure_RsaDecrypt was removed */
if (XSecure_RsaPublicEncrypt(&(key->xRsa), (u8*)in, inLen, out) != XST_SUCCESS) {
WOLFSSL_MSG("Error happened when calling hardware RSA public operation");
ret = BAD_STATE_E;
}
#endif
break;
default:
ret = RSA_WRONG_TYPE_E;
}
*outLen = keyLen;
return ret;
}
#elif defined(WOLFSSL_AFALG_XILINX_RSA)
#ifndef ERROR_OUT
#define ERROR_OUT(x) ret = (x); goto done
#endif
static const char WC_TYPE_ASYMKEY[] = "skcipher";
static const char WC_NAME_RSA[] = "xilinx-zynqmp-rsa";
#ifndef MAX_XILINX_RSA_KEY
/* max key size of 4096 bits / 512 bytes */
#define MAX_XILINX_RSA_KEY 512
#endif
static const byte XILINX_RSA_FLAG[] = {0x1};
/* AF_ALG implementation of RSA */
static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out,
word32* outLen, int type, RsaKey* key, WC_RNG* rng)
{
struct msghdr msg;
struct cmsghdr* cmsg;
struct iovec iov;
byte* keyBuf = NULL;
word32 keyBufSz = 0;
char cbuf[CMSG_SPACE(4) + CMSG_SPACE(sizeof(struct af_alg_iv) + 1)] = {0};
int ret = 0;
int op = 0; /* decryption vs encryption flag */
word32 keyLen;
/* input and output buffer need to be aligned */
ALIGN64 byte outBuf[MAX_XILINX_RSA_KEY];
ALIGN64 byte inBuf[MAX_XILINX_RSA_KEY];
XMEMSET(&msg, 0, sizeof(struct msghdr));
(void)rng;
keyLen = wc_RsaEncryptSize(key);
if (keyLen > *outLen) {
ERROR_OUT(RSA_BUFFER_E);
}
if (keyLen > MAX_XILINX_RSA_KEY) {
WOLFSSL_MSG("RSA key size larger than supported");
ERROR_OUT(BAD_FUNC_ARG);
}
if ((keyBuf = (byte*)XMALLOC(keyLen * 2, key->heap, DYNAMIC_TYPE_KEY))
== NULL) {
ERROR_OUT(MEMORY_E);
}
if ((ret = mp_to_unsigned_bin(&(key->n), keyBuf)) != MP_OKAY) {
ERROR_OUT(MP_TO_E);
}
switch(type) {
case RSA_PRIVATE_DECRYPT:
case RSA_PRIVATE_ENCRYPT:
op = 1; /* set as decrypt */
{
keyBufSz = mp_unsigned_bin_size(&(key->d));
if ((mp_to_unsigned_bin(&(key->d), keyBuf + keyLen))
!= MP_OKAY) {
ERROR_OUT(MP_TO_E);
}
}
break;
case RSA_PUBLIC_DECRYPT:
case RSA_PUBLIC_ENCRYPT: {
word32 exp = 0;
word32 eSz = mp_unsigned_bin_size(&(key->e));
if ((mp_to_unsigned_bin(&(key->e), (byte*)&exp +
(sizeof(word32) - eSz))) != MP_OKAY) {
ERROR_OUT(MP_TO_E);
}
keyBufSz = sizeof(word32);
XMEMCPY(keyBuf + keyLen, (byte*)&exp, keyBufSz);
break;
}
default:
ERROR_OUT(RSA_WRONG_TYPE_E);
}
keyBufSz += keyLen; /* add size of modulus */
/* check for existing sockets before creating new ones */
if (key->alFd > 0) {
close(key->alFd);
key->alFd = WC_SOCK_NOTSET;
}
if (key->rdFd > 0) {
close(key->rdFd);
key->rdFd = WC_SOCK_NOTSET;
}
/* create new sockets and set the key to use */
if ((key->alFd = wc_Afalg_Socket()) < 0) {
WOLFSSL_MSG("Unable to create socket");
ERROR_OUT(key->alFd);
}
if ((key->rdFd = wc_Afalg_CreateRead(key->alFd, WC_TYPE_ASYMKEY,
WC_NAME_RSA)) < 0) {
WOLFSSL_MSG("Unable to bind and create read/send socket");
ERROR_OUT(key->rdFd);
}
if ((ret = setsockopt(key->alFd, SOL_ALG, ALG_SET_KEY, keyBuf,
keyBufSz)) < 0) {
WOLFSSL_MSG("Error setting RSA key");
ERROR_OUT(ret);
}
msg.msg_control = cbuf;
msg.msg_controllen = sizeof(cbuf);
cmsg = CMSG_FIRSTHDR(&msg);
if ((ret = wc_Afalg_SetOp(cmsg, op)) < 0) {
ERROR_OUT(ret);
}
/* set flag in IV spot, needed for Xilinx hardware acceleration use */
cmsg = CMSG_NXTHDR(&msg, cmsg);
if ((ret = wc_Afalg_SetIv(cmsg, (byte*)XILINX_RSA_FLAG,
sizeof(XILINX_RSA_FLAG))) != 0) {
ERROR_OUT(ret);
}
/* compose and send msg */
XMEMCPY(inBuf, (byte*)in, inLen); /* for alignment */
iov.iov_base = inBuf;
iov.iov_len = inLen;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
if ((ret = sendmsg(key->rdFd, &msg, 0)) <= 0) {
ERROR_OUT(WC_AFALG_SOCK_E);
}
if ((ret = read(key->rdFd, outBuf, inLen)) <= 0) {
ERROR_OUT(WC_AFALG_SOCK_E);
}
XMEMCPY(out, outBuf, ret);
*outLen = keyLen;
done:
/* clear key data and free buffer */
if (keyBuf != NULL) {
ForceZero(keyBuf, keyBufSz);
}
XFREE(keyBuf, key->heap, DYNAMIC_TYPE_KEY);
if (key->alFd > 0) {
close(key->alFd);
key->alFd = WC_SOCK_NOTSET;
}
if (key->rdFd > 0) {
close(key->rdFd);
key->rdFd = WC_SOCK_NOTSET;
}
return ret;
}
#else
static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out,
word32* outLen, int type, RsaKey* key, WC_RNG* rng)
{
#ifndef WOLFSSL_SP_MATH
#ifdef WOLFSSL_SMALL_STACK
mp_int* tmp;
#ifdef WC_RSA_BLINDING
mp_int* rnd;
mp_int* rndi;
#endif
#else
mp_int tmp[1];
#ifdef WC_RSA_BLINDING
mp_int rnd[1], rndi[1];
#endif
#endif
int ret = 0;
word32 keyLen = 0;
#endif
#ifdef WOLFSSL_HAVE_SP_RSA
#ifndef WOLFSSL_SP_NO_2048
if (mp_count_bits(&key->n) == 2048) {
switch(type) {
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
case RSA_PRIVATE_DECRYPT:
case RSA_PRIVATE_ENCRYPT:
#ifdef WC_RSA_BLINDING
if (rng == NULL)
return MISSING_RNG_E;
#endif
#ifndef RSA_LOW_MEM
if ((mp_count_bits(&key->p) == 1024) &&
(mp_count_bits(&key->q) == 1024)) {
return sp_RsaPrivate_2048(in, inLen, &key->d, &key->p, &key->q,
&key->dP, &key->dQ, &key->u, &key->n,
out, outLen);
}
break;
#else
return sp_RsaPrivate_2048(in, inLen, &key->d, NULL, NULL, NULL,
NULL, NULL, &key->n, out, outLen);
#endif
#endif
case RSA_PUBLIC_ENCRYPT:
case RSA_PUBLIC_DECRYPT:
return sp_RsaPublic_2048(in, inLen, &key->e, &key->n, out, outLen);
}
}
#endif
#ifndef WOLFSSL_SP_NO_3072
if (mp_count_bits(&key->n) == 3072) {
switch(type) {
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
case RSA_PRIVATE_DECRYPT:
case RSA_PRIVATE_ENCRYPT:
#ifdef WC_RSA_BLINDING
if (rng == NULL)
return MISSING_RNG_E;
#endif
#ifndef RSA_LOW_MEM
if ((mp_count_bits(&key->p) == 1536) &&
(mp_count_bits(&key->q) == 1536)) {
return sp_RsaPrivate_3072(in, inLen, &key->d, &key->p, &key->q,
&key->dP, &key->dQ, &key->u, &key->n,
out, outLen);
}
break;
#else
return sp_RsaPrivate_3072(in, inLen, &key->d, NULL, NULL, NULL,
NULL, NULL, &key->n, out, outLen);
#endif
#endif
case RSA_PUBLIC_ENCRYPT:
case RSA_PUBLIC_DECRYPT:
return sp_RsaPublic_3072(in, inLen, &key->e, &key->n, out, outLen);
}
}
#endif
#ifdef WOLFSSL_SP_4096
if (mp_count_bits(&key->n) == 4096) {
switch(type) {
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
case RSA_PRIVATE_DECRYPT:
case RSA_PRIVATE_ENCRYPT:
#ifdef WC_RSA_BLINDING
if (rng == NULL)
return MISSING_RNG_E;
#endif
#ifndef RSA_LOW_MEM
if ((mp_count_bits(&key->p) == 2048) &&
(mp_count_bits(&key->q) == 2048)) {
return sp_RsaPrivate_4096(in, inLen, &key->d, &key->p, &key->q,
&key->dP, &key->dQ, &key->u, &key->n,
out, outLen);
}
break;
#else
return sp_RsaPrivate_4096(in, inLen, &key->d, NULL, NULL, NULL,
NULL, NULL, &key->n, out, outLen);
#endif
#endif
case RSA_PUBLIC_ENCRYPT:
case RSA_PUBLIC_DECRYPT:
return sp_RsaPublic_4096(in, inLen, &key->e, &key->n, out, outLen);
}
}
#endif
#endif /* WOLFSSL_HAVE_SP_RSA */
#ifdef WOLFSSL_SP_MATH
(void)rng;
WOLFSSL_MSG("SP Key Size Error");
return WC_KEY_SIZE_E;
#else
(void)rng;
#ifdef WOLFSSL_SMALL_STACK
tmp = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_RSA);
if (tmp == NULL)
return MEMORY_E;
#ifdef WC_RSA_BLINDING
rnd = (mp_int*)XMALLOC(sizeof(mp_int) * 2, key->heap, DYNAMIC_TYPE_RSA);
if (rnd == NULL) {
XFREE(tmp, key->heap, DYNAMIC_TYPE_RSA);
return MEMORY_E;
}
rndi = rnd + 1;
#endif /* WC_RSA_BLINDING */
#endif /* WOLFSSL_SMALL_STACK */
if (mp_init(tmp) != MP_OKAY)
ret = MP_INIT_E;
#ifdef WC_RSA_BLINDING
if (ret == 0) {
if (type == RSA_PRIVATE_DECRYPT || type == RSA_PRIVATE_ENCRYPT) {
if (mp_init_multi(rnd, rndi, NULL, NULL, NULL, NULL) != MP_OKAY) {
mp_clear(tmp);
ret = MP_INIT_E;
}
}
}
#endif
#ifndef TEST_UNPAD_CONSTANT_TIME
if (ret == 0 && mp_read_unsigned_bin(tmp, (byte*)in, inLen) != MP_OKAY)
ret = MP_READ_E;
if (ret == 0) {
switch(type) {
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
case RSA_PRIVATE_DECRYPT:
case RSA_PRIVATE_ENCRYPT:
{
#if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG)
/* blind */
ret = mp_rand(rnd, get_digit_count(&key->n), rng);
/* rndi = 1/rnd mod n */
if (ret == 0 && mp_invmod(rnd, &key->n, rndi) != MP_OKAY)
ret = MP_INVMOD_E;
/* rnd = rnd^e */
if (ret == 0 && mp_exptmod(rnd, &key->e, &key->n, rnd) != MP_OKAY)
ret = MP_EXPTMOD_E;
/* tmp = tmp*rnd mod n */
if (ret == 0 && mp_mulmod(tmp, rnd, &key->n, tmp) != MP_OKAY)
ret = MP_MULMOD_E;
#endif /* WC_RSA_BLINDING && !WC_NO_RNG */
#ifdef RSA_LOW_MEM /* half as much memory but twice as slow */
if (ret == 0 && mp_exptmod(tmp, &key->d, &key->n, tmp) != MP_OKAY)
ret = MP_EXPTMOD_E;
#else
if (ret == 0) {
#ifdef WOLFSSL_SMALL_STACK
mp_int* tmpa;
mp_int* tmpb = NULL;
#else
mp_int tmpa[1], tmpb[1];
#endif
int cleara = 0, clearb = 0;
#ifdef WOLFSSL_SMALL_STACK
tmpa = (mp_int*)XMALLOC(sizeof(mp_int) * 2,
key->heap, DYNAMIC_TYPE_RSA);
if (tmpa != NULL)
tmpb = tmpa + 1;
else
ret = MEMORY_E;
#endif
if (ret == 0) {
if (mp_init(tmpa) != MP_OKAY)
ret = MP_INIT_E;
else
cleara = 1;
}
if (ret == 0) {
if (mp_init(tmpb) != MP_OKAY)
ret = MP_INIT_E;
else
clearb = 1;
}
/* tmpa = tmp^dP mod p */
if (ret == 0 && mp_exptmod(tmp, &key->dP, &key->p,
tmpa) != MP_OKAY)
ret = MP_EXPTMOD_E;
/* tmpb = tmp^dQ mod q */
if (ret == 0 && mp_exptmod(tmp, &key->dQ, &key->q,
tmpb) != MP_OKAY)
ret = MP_EXPTMOD_E;
/* tmp = (tmpa - tmpb) * qInv (mod p) */
if (ret == 0 && mp_sub(tmpa, tmpb, tmp) != MP_OKAY)
ret = MP_SUB_E;
if (ret == 0 && mp_mulmod(tmp, &key->u, &key->p,
tmp) != MP_OKAY)
ret = MP_MULMOD_E;
/* tmp = tmpb + q * tmp */
if (ret == 0 && mp_mul(tmp, &key->q, tmp) != MP_OKAY)
ret = MP_MUL_E;
if (ret == 0 && mp_add(tmp, tmpb, tmp) != MP_OKAY)
ret = MP_ADD_E;
#ifdef WOLFSSL_SMALL_STACK
if (tmpa != NULL)
#endif
{
if (cleara)
mp_clear(tmpa);
if (clearb)
mp_clear(tmpb);
#ifdef WOLFSSL_SMALL_STACK
XFREE(tmpa, key->heap, DYNAMIC_TYPE_RSA);
#endif
}
} /* tmpa/b scope */
#endif /* RSA_LOW_MEM */
#ifdef WC_RSA_BLINDING
/* unblind */
if (ret == 0 && mp_mulmod(tmp, rndi, &key->n, tmp) != MP_OKAY)
ret = MP_MULMOD_E;
#endif /* WC_RSA_BLINDING */
break;
}
#endif
case RSA_PUBLIC_ENCRYPT:
case RSA_PUBLIC_DECRYPT:
if (mp_exptmod_nct(tmp, &key->e, &key->n, tmp) != MP_OKAY)
ret = MP_EXPTMOD_E;
break;
default:
ret = RSA_WRONG_TYPE_E;
break;
}
}
if (ret == 0) {
keyLen = wc_RsaEncryptSize(key);
if (keyLen > *outLen)
ret = RSA_BUFFER_E;
}
#ifndef WOLFSSL_XILINX_CRYPT
if (ret == 0) {
*outLen = keyLen;
if (mp_to_unsigned_bin_len(tmp, out, keyLen) != MP_OKAY)
ret = MP_TO_E;
}
#endif
#else
(void)type;
(void)key;
(void)keyLen;
XMEMCPY(out, in, inLen);
*outLen = inLen;
#endif
mp_clear(tmp);
#ifdef WOLFSSL_SMALL_STACK
XFREE(tmp, key->heap, DYNAMIC_TYPE_RSA);
#endif
#ifdef WC_RSA_BLINDING
if (type == RSA_PRIVATE_DECRYPT || type == RSA_PRIVATE_ENCRYPT) {
mp_clear(rndi);
mp_clear(rnd);
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(rnd, key->heap, DYNAMIC_TYPE_RSA);
#endif
#endif /* WC_RSA_BLINDING */
return ret;
#endif /* WOLFSSL_SP_MATH */
}
#endif
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA)
static int wc_RsaFunctionAsync(const byte* in, word32 inLen, byte* out,
word32* outLen, int type, RsaKey* key, WC_RNG* rng)
{
int ret = 0;
(void)rng;
#ifdef WOLFSSL_ASYNC_CRYPT_TEST
if (wc_AsyncTestInit(&key->asyncDev, ASYNC_TEST_RSA_FUNC)) {
WC_ASYNC_TEST* testDev = &key->asyncDev.test;
testDev->rsaFunc.in = in;
testDev->rsaFunc.inSz = inLen;
testDev->rsaFunc.out = out;
testDev->rsaFunc.outSz = outLen;
testDev->rsaFunc.type = type;
testDev->rsaFunc.key = key;
testDev->rsaFunc.rng = rng;
return WC_PENDING_E;
}
#endif /* WOLFSSL_ASYNC_CRYPT_TEST */
switch(type) {
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
case RSA_PRIVATE_DECRYPT:
case RSA_PRIVATE_ENCRYPT:
#ifdef HAVE_CAVIUM
key->dataLen = key->n.raw.len;
ret = NitroxRsaExptMod(in, inLen,
key->d.raw.buf, key->d.raw.len,
key->n.raw.buf, key->n.raw.len,
out, outLen, key);
#elif defined(HAVE_INTEL_QA)
#ifdef RSA_LOW_MEM
ret = IntelQaRsaPrivate(&key->asyncDev, in, inLen,
&key->d.raw, &key->n.raw,
out, outLen);
#else
ret = IntelQaRsaCrtPrivate(&key->asyncDev, in, inLen,
&key->p.raw, &key->q.raw,
&key->dP.raw, &key->dQ.raw,
&key->u.raw,
out, outLen);
#endif
#else /* WOLFSSL_ASYNC_CRYPT_TEST */
ret = wc_RsaFunctionSync(in, inLen, out, outLen, type, key, rng);
#endif
break;
#endif
case RSA_PUBLIC_ENCRYPT:
case RSA_PUBLIC_DECRYPT:
#ifdef HAVE_CAVIUM
key->dataLen = key->n.raw.len;
ret = NitroxRsaExptMod(in, inLen,
key->e.raw.buf, key->e.raw.len,
key->n.raw.buf, key->n.raw.len,
out, outLen, key);
#elif defined(HAVE_INTEL_QA)
ret = IntelQaRsaPublic(&key->asyncDev, in, inLen,
&key->e.raw, &key->n.raw,
out, outLen);
#else /* WOLFSSL_ASYNC_CRYPT_TEST */
ret = wc_RsaFunctionSync(in, inLen, out, outLen, type, key, rng);
#endif
break;
default:
ret = RSA_WRONG_TYPE_E;
}
return ret;
}
#endif /* WOLFSSL_ASYNC_CRYPT && WC_ASYNC_ENABLE_RSA */
#if defined(WC_RSA_DIRECT) || defined(WC_RSA_NO_PADDING)
/* Function that does the RSA operation directly with no padding.
*
* in buffer to do operation on
* inLen length of input buffer
* out buffer to hold results
* outSz gets set to size of result buffer. Should be passed in as length
* of out buffer. If the pointer "out" is null then outSz gets set to
* the expected buffer size needed and LENGTH_ONLY_E gets returned.
* key RSA key to use for encrypt/decrypt
* type if using private or public key {RSA_PUBLIC_ENCRYPT,
* RSA_PUBLIC_DECRYPT, RSA_PRIVATE_ENCRYPT, RSA_PRIVATE_DECRYPT}
* rng wolfSSL RNG to use if needed
*
* returns size of result on success
*/
int wc_RsaDirect(byte* in, word32 inLen, byte* out, word32* outSz,
RsaKey* key, int type, WC_RNG* rng)
{
int ret;
if (in == NULL || outSz == NULL || key == NULL) {
return BAD_FUNC_ARG;
}
/* sanity check on type of RSA operation */
switch (type) {
case RSA_PUBLIC_ENCRYPT:
case RSA_PUBLIC_DECRYPT:
case RSA_PRIVATE_ENCRYPT:
case RSA_PRIVATE_DECRYPT:
break;
default:
WOLFSSL_MSG("Bad RSA type");
return BAD_FUNC_ARG;
}
if ((ret = wc_RsaEncryptSize(key)) < 0) {
return BAD_FUNC_ARG;
}
if (inLen != (word32)ret) {
WOLFSSL_MSG("Bad input length. Should be RSA key size");
return BAD_FUNC_ARG;
}
if (out == NULL) {
*outSz = inLen;
return LENGTH_ONLY_E;
}
switch (key->state) {
case RSA_STATE_NONE:
case RSA_STATE_ENCRYPT_PAD:
case RSA_STATE_ENCRYPT_EXPTMOD:
case RSA_STATE_DECRYPT_EXPTMOD:
case RSA_STATE_DECRYPT_UNPAD:
key->state = (type == RSA_PRIVATE_ENCRYPT ||
type == RSA_PUBLIC_ENCRYPT) ? RSA_STATE_ENCRYPT_EXPTMOD:
RSA_STATE_DECRYPT_EXPTMOD;
key->dataLen = *outSz;
ret = wc_RsaFunction(in, inLen, out, &key->dataLen, type, key, rng);
if (ret >= 0 || ret == WC_PENDING_E) {
key->state = (type == RSA_PRIVATE_ENCRYPT ||
type == RSA_PUBLIC_ENCRYPT) ? RSA_STATE_ENCRYPT_RES:
RSA_STATE_DECRYPT_RES;
}
if (ret < 0) {
break;
}
FALL_THROUGH;
case RSA_STATE_ENCRYPT_RES:
case RSA_STATE_DECRYPT_RES:
ret = key->dataLen;
break;
default:
ret = BAD_STATE_E;
}
/* if async pending then skip cleanup*/
if (ret == WC_PENDING_E
#ifdef WC_RSA_NONBLOCK
|| ret == FP_WOULDBLOCK
#endif
) {
return ret;
}
key->state = RSA_STATE_NONE;
wc_RsaCleanup(key);
return ret;
}
#endif /* WC_RSA_DIRECT || WC_RSA_NO_PADDING */
#if defined(WOLFSSL_CRYPTOCELL)
static int cc310_RsaPublicEncrypt(const byte* in, word32 inLen, byte* out,
word32 outLen, RsaKey* key)
{
CRYSError_t ret = 0;
CRYS_RSAPrimeData_t primeData;
int modulusSize = wc_RsaEncryptSize(key);
/* The out buffer must be at least modulus size bytes long. */
if (outLen < modulusSize)
return BAD_FUNC_ARG;
ret = CRYS_RSA_PKCS1v15_Encrypt(&wc_rndState,
wc_rndGenVectFunc,
&key->ctx.pubKey,
&primeData,
(byte*)in,
inLen,
out);
if (ret != SA_SILIB_RET_OK){
WOLFSSL_MSG("CRYS_RSA_PKCS1v15_Encrypt failed");
return -1;
}
return modulusSize;
}
static int cc310_RsaPublicDecrypt(const byte* in, word32 inLen, byte* out,
word32 outLen, RsaKey* key)
{
CRYSError_t ret = 0;
CRYS_RSAPrimeData_t primeData;
uint16_t actualOutLen = outLen;
ret = CRYS_RSA_PKCS1v15_Decrypt(&key->ctx.privKey,
&primeData,
(byte*)in,
inLen,
out,
&actualOutLen);
if (ret != SA_SILIB_RET_OK){
WOLFSSL_MSG("CRYS_RSA_PKCS1v15_Decrypt failed");
return -1;
}
return actualOutLen;
}
int cc310_RsaSSL_Sign(const byte* in, word32 inLen, byte* out,
word32 outLen, RsaKey* key, CRYS_RSA_HASH_OpMode_t mode)
{
CRYSError_t ret = 0;
uint16_t actualOutLen = outLen*sizeof(byte);
CRYS_RSAPrivUserContext_t contextPrivate;
ret = CRYS_RSA_PKCS1v15_Sign(&wc_rndState,
wc_rndGenVectFunc,
&contextPrivate,
&key->ctx.privKey,
mode,
(byte*)in,
inLen,
out,
&actualOutLen);
if (ret != SA_SILIB_RET_OK){
WOLFSSL_MSG("CRYS_RSA_PKCS1v15_Sign failed");
return -1;
}
return actualOutLen;
}
int cc310_RsaSSL_Verify(const byte* in, word32 inLen, byte* sig,
RsaKey* key, CRYS_RSA_HASH_OpMode_t mode)
{
CRYSError_t ret = 0;
CRYS_RSAPubUserContext_t contextPub;
/* verify the signature in the sig pointer */
ret = CRYS_RSA_PKCS1v15_Verify(&contextPub,
&key->ctx.pubKey,
mode,
(byte*)in,
inLen,
sig);
if (ret != SA_SILIB_RET_OK){
WOLFSSL_MSG("CRYS_RSA_PKCS1v15_Verify failed");
return -1;
}
return ret;
}
#endif /* WOLFSSL_CRYPTOCELL */
int wc_RsaFunction(const byte* in, word32 inLen, byte* out,
word32* outLen, int type, RsaKey* key, WC_RNG* rng)
{
int ret = 0;
if (key == NULL || in == NULL || inLen == 0 || out == NULL ||
outLen == NULL || *outLen == 0 || type == RSA_TYPE_UNKNOWN) {
return BAD_FUNC_ARG;
}
#ifdef WOLF_CRYPTO_CB
if (key->devId != INVALID_DEVID) {
ret = wc_CryptoCb_Rsa(in, inLen, out, outLen, type, key, rng);
if (ret != CRYPTOCB_UNAVAILABLE)
return ret;
/* fall-through when unavailable */
ret = 0; /* reset error code and try using software */
}
#endif
#ifndef TEST_UNPAD_CONSTANT_TIME
#ifndef NO_RSA_BOUNDS_CHECK
if (type == RSA_PRIVATE_DECRYPT &&
key->state == RSA_STATE_DECRYPT_EXPTMOD) {
/* Check that 1 < in < n-1. (Requirement of 800-56B.) */
#ifdef WOLFSSL_SMALL_STACK
mp_int* c;
#else
mp_int c[1];
#endif
#ifdef WOLFSSL_SMALL_STACK
c = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_RSA);
if (c == NULL)
ret = MEMORY_E;
#endif
if (mp_init(c) != MP_OKAY)
ret = MP_INIT_E;
if (ret == 0) {
if (mp_read_unsigned_bin(c, in, inLen) != 0)
ret = MP_READ_E;
}
if (ret == 0) {
/* check c > 1 */
if (mp_cmp_d(c, 1) != MP_GT)
ret = RSA_OUT_OF_RANGE_E;
}
if (ret == 0) {
/* add c+1 */
if (mp_add_d(c, 1, c) != MP_OKAY)
ret = MP_ADD_E;
}
if (ret == 0) {
/* check c+1 < n */
if (mp_cmp(c, &key->n) != MP_LT)
ret = RSA_OUT_OF_RANGE_E;
}
mp_clear(c);
#ifdef WOLFSSL_SMALL_STACK
XFREE(c, key->heap, DYNAMIC_TYPE_RSA);
#endif
if (ret != 0)
return ret;
}
#endif /* NO_RSA_BOUNDS_CHECK */
#endif
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA)
if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA &&
key->n.raw.len > 0) {
ret = wc_RsaFunctionAsync(in, inLen, out, outLen, type, key, rng);
}
else
#endif
#ifdef WC_RSA_NONBLOCK
if (key->nb) {
ret = wc_RsaFunctionNonBlock(in, inLen, out, outLen, type, key);
}
else
#endif
{
ret = wc_RsaFunctionSync(in, inLen, out, outLen, type, key, rng);
}
/* handle error */
if (ret < 0 && ret != WC_PENDING_E
#ifdef WC_RSA_NONBLOCK
&& ret != FP_WOULDBLOCK
#endif
) {
if (ret == MP_EXPTMOD_E) {
/* This can happen due to incorrectly set FP_MAX_BITS or missing XREALLOC */
WOLFSSL_MSG("RSA_FUNCTION MP_EXPTMOD_E: memory/config problem");
}
key->state = RSA_STATE_NONE;
wc_RsaCleanup(key);
}
return ret;
}
#ifndef WOLFSSL_RSA_VERIFY_ONLY
/* Internal Wrappers */
/* Gives the option of choosing padding type
in : input to be encrypted
inLen: length of input buffer
out: encrypted output
outLen: length of encrypted output buffer
key : wolfSSL initialized RSA key struct
rng : wolfSSL initialized random number struct
rsa_type : type of RSA: RSA_PUBLIC_ENCRYPT, RSA_PUBLIC_DECRYPT,
RSA_PRIVATE_ENCRYPT or RSA_PRIVATE_DECRYPT
pad_value: RSA_BLOCK_TYPE_1 or RSA_BLOCK_TYPE_2
pad_type : type of padding: WC_RSA_PKCSV15_PAD, WC_RSA_OAEP_PAD,
WC_RSA_NO_PAD or WC_RSA_PSS_PAD
hash : type of hash algorithm to use found in wolfssl/wolfcrypt/hash.h
mgf : type of mask generation function to use
label : optional label
labelSz : size of optional label buffer
saltLen : Length of salt used in PSS
rng : random number generator */
static int RsaPublicEncryptEx(const byte* in, word32 inLen, byte* out,
word32 outLen, RsaKey* key, int rsa_type,
byte pad_value, int pad_type,
enum wc_HashType hash, int mgf,
byte* label, word32 labelSz, int saltLen,
WC_RNG* rng)
{
int ret, sz;
if (in == NULL || inLen == 0 || out == NULL || key == NULL) {
return BAD_FUNC_ARG;
}
sz = wc_RsaEncryptSize(key);
if (sz > (int)outLen) {
return RSA_BUFFER_E;
}
if (sz < RSA_MIN_PAD_SZ) {
return WC_KEY_SIZE_E;
}
if (inLen > (word32)(sz - RSA_MIN_PAD_SZ)) {
#ifdef WC_RSA_NO_PADDING
/* In the case that no padding is used the input length can and should
* be the same size as the RSA key. */
if (pad_type != WC_RSA_NO_PAD)
#endif
return RSA_BUFFER_E;
}
switch (key->state) {
case RSA_STATE_NONE:
case RSA_STATE_ENCRYPT_PAD:
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) && \
defined(HAVE_CAVIUM)
if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA &&
pad_type != WC_RSA_PSS_PAD && key->n.raw.buf) {
/* Async operations that include padding */
if (rsa_type == RSA_PUBLIC_ENCRYPT &&
pad_value == RSA_BLOCK_TYPE_2) {
key->state = RSA_STATE_ENCRYPT_RES;
key->dataLen = key->n.raw.len;
return NitroxRsaPublicEncrypt(in, inLen, out, outLen, key);
}
else if (rsa_type == RSA_PRIVATE_ENCRYPT &&
pad_value == RSA_BLOCK_TYPE_1) {
key->state = RSA_STATE_ENCRYPT_RES;
key->dataLen = key->n.raw.len;
return NitroxRsaSSL_Sign(in, inLen, out, outLen, key);
}
}
#elif defined(WOLFSSL_CRYPTOCELL)
if (rsa_type == RSA_PUBLIC_ENCRYPT &&
pad_value == RSA_BLOCK_TYPE_2) {
return cc310_RsaPublicEncrypt(in, inLen, out, outLen, key);
}
else if (rsa_type == RSA_PRIVATE_ENCRYPT &&
pad_value == RSA_BLOCK_TYPE_1) {
return cc310_RsaSSL_Sign(in, inLen, out, outLen, key,
cc310_hashModeRSA(hash, 0));
}
#endif /* WOLFSSL_CRYPTOCELL */
key->state = RSA_STATE_ENCRYPT_PAD;
ret = wc_RsaPad_ex(in, inLen, out, sz, pad_value, rng, pad_type, hash,
mgf, label, labelSz, saltLen, mp_count_bits(&key->n),
key->heap);
if (ret < 0) {
break;
}
key->state = RSA_STATE_ENCRYPT_EXPTMOD;
FALL_THROUGH;
case RSA_STATE_ENCRYPT_EXPTMOD:
key->dataLen = outLen;
ret = wc_RsaFunction(out, sz, out, &key->dataLen, rsa_type, key, rng);
if (ret >= 0 || ret == WC_PENDING_E) {
key->state = RSA_STATE_ENCRYPT_RES;
}
if (ret < 0) {
break;
}
FALL_THROUGH;
case RSA_STATE_ENCRYPT_RES:
ret = key->dataLen;
break;
default:
ret = BAD_STATE_E;
break;
}
/* if async pending then return and skip done cleanup below */
if (ret == WC_PENDING_E
#ifdef WC_RSA_NONBLOCK
|| ret == FP_WOULDBLOCK
#endif
) {
return ret;
}
key->state = RSA_STATE_NONE;
wc_RsaCleanup(key);
return ret;
}
#endif
/* Gives the option of choosing padding type
in : input to be decrypted
inLen: length of input buffer
out: decrypted message
outLen: length of decrypted message in bytes
outPtr: optional inline output pointer (if provided doing inline)
key : wolfSSL initialized RSA key struct
rsa_type : type of RSA: RSA_PUBLIC_ENCRYPT, RSA_PUBLIC_DECRYPT,
RSA_PRIVATE_ENCRYPT or RSA_PRIVATE_DECRYPT
pad_value: RSA_BLOCK_TYPE_1 or RSA_BLOCK_TYPE_2
pad_type : type of padding: WC_RSA_PKCSV15_PAD, WC_RSA_OAEP_PAD,
WC_RSA_NO_PAD, WC_RSA_PSS_PAD
hash : type of hash algorithm to use found in wolfssl/wolfcrypt/hash.h
mgf : type of mask generation function to use
label : optional label
labelSz : size of optional label buffer
saltLen : Length of salt used in PSS
rng : random number generator */
static int RsaPrivateDecryptEx(byte* in, word32 inLen, byte* out,
word32 outLen, byte** outPtr, RsaKey* key,
int rsa_type, byte pad_value, int pad_type,
enum wc_HashType hash, int mgf,
byte* label, word32 labelSz, int saltLen,
WC_RNG* rng)
{
int ret = RSA_WRONG_TYPE_E;
byte* pad = NULL;
if (in == NULL || inLen == 0 || out == NULL || key == NULL) {
return BAD_FUNC_ARG;
}
switch (key->state) {
case RSA_STATE_NONE:
key->dataLen = inLen;
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) && \
defined(HAVE_CAVIUM)
/* Async operations that include padding */
if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA &&
pad_type != WC_RSA_PSS_PAD) {
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
if (rsa_type == RSA_PRIVATE_DECRYPT &&
pad_value == RSA_BLOCK_TYPE_2) {
key->state = RSA_STATE_DECRYPT_RES;
key->data = NULL;
return NitroxRsaPrivateDecrypt(in, inLen, out, &key->dataLen,
key);
#endif
}
else if (rsa_type == RSA_PUBLIC_DECRYPT &&
pad_value == RSA_BLOCK_TYPE_1) {
key->state = RSA_STATE_DECRYPT_RES;
key->data = NULL;
return NitroxRsaSSL_Verify(in, inLen, out, &key->dataLen, key);
}
}
#elif defined(WOLFSSL_CRYPTOCELL)
if (rsa_type == RSA_PRIVATE_DECRYPT &&
pad_value == RSA_BLOCK_TYPE_2) {
ret = cc310_RsaPublicDecrypt(in, inLen, out, outLen, key);
if (outPtr != NULL)
*outPtr = out; /* for inline */
return ret;
}
else if (rsa_type == RSA_PUBLIC_DECRYPT &&
pad_value == RSA_BLOCK_TYPE_1) {
return cc310_RsaSSL_Verify(in, inLen, out, key,
cc310_hashModeRSA(hash, 0));
}
#endif /* WOLFSSL_CRYPTOCELL */
#if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE)
/* verify the tmp ptr is NULL, otherwise indicates bad state */
if (key->data != NULL) {
ret = BAD_STATE_E;
break;
}
/* if not doing this inline then allocate a buffer for it */
if (outPtr == NULL) {
key->data = (byte*)XMALLOC(inLen, key->heap,
DYNAMIC_TYPE_WOLF_BIGINT);
key->dataIsAlloc = 1;
if (key->data == NULL) {
ret = MEMORY_E;
break;
}
XMEMCPY(key->data, in, inLen);
}
else {
key->data = out;
}
#endif
key->state = RSA_STATE_DECRYPT_EXPTMOD;
FALL_THROUGH;
case RSA_STATE_DECRYPT_EXPTMOD:
#if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE)
ret = wc_RsaFunction(key->data, inLen, key->data, &key->dataLen,
rsa_type, key, rng);
#else
ret = wc_RsaFunction(in, inLen, out, &key->dataLen, rsa_type, key, rng);
#endif
if (ret >= 0 || ret == WC_PENDING_E) {
key->state = RSA_STATE_DECRYPT_UNPAD;
}
if (ret < 0) {
break;
}
FALL_THROUGH;
case RSA_STATE_DECRYPT_UNPAD:
#if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE)
ret = wc_RsaUnPad_ex(key->data, key->dataLen, &pad, pad_value, pad_type,
hash, mgf, label, labelSz, saltLen,
mp_count_bits(&key->n), key->heap);
#else
ret = wc_RsaUnPad_ex(out, key->dataLen, &pad, pad_value, pad_type, hash,
mgf, label, labelSz, saltLen,
mp_count_bits(&key->n), key->heap);
#endif
if (rsa_type == RSA_PUBLIC_DECRYPT && ret > (int)outLen)
ret = RSA_BUFFER_E;
else if (ret >= 0 && pad != NULL) {
#if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE)
signed char c;
#endif
/* only copy output if not inline */
if (outPtr == NULL) {
#if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE)
if (rsa_type == RSA_PRIVATE_DECRYPT) {
word32 i, j;
int start = (int)((size_t)pad - (size_t)key->data);
for (i = 0, j = 0; j < key->dataLen; j++) {
out[i] = key->data[j];
c = ctMaskGTE(j, start);
c &= ctMaskLT(i, outLen);
/* 0 - no add, -1 add */
i += (word32)((byte)(-c));
}
}
else
#endif
{
XMEMCPY(out, pad, ret);
}
}
else
*outPtr = pad;
#if !defined(WOLFSSL_RSA_VERIFY_ONLY)
ret = ctMaskSelInt(ctMaskLTE(ret, outLen), ret, RSA_BUFFER_E);
ret = ctMaskSelInt(ctMaskNotEq(ret, 0), ret, RSA_BUFFER_E);
#else
if (outLen < (word32)ret)
ret = RSA_BUFFER_E;
#endif
}
key->state = RSA_STATE_DECRYPT_RES;
FALL_THROUGH;
case RSA_STATE_DECRYPT_RES:
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) && \
defined(HAVE_CAVIUM)
if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA &&
pad_type != WC_RSA_PSS_PAD) {
if (ret > 0) {
/* convert result */
byte* dataLen = (byte*)&key->dataLen;
ret = (dataLen[0] << 8) | (dataLen[1]);
if (outPtr)
*outPtr = in;
}
}
#endif
break;
default:
ret = BAD_STATE_E;
break;
}
/* if async pending then return and skip done cleanup below */
if (ret == WC_PENDING_E
#ifdef WC_RSA_NONBLOCK
|| ret == FP_WOULDBLOCK
#endif
) {
return ret;
}
key->state = RSA_STATE_NONE;
wc_RsaCleanup(key);
return ret;
}
#ifndef WOLFSSL_RSA_VERIFY_ONLY
/* Public RSA Functions */
int wc_RsaPublicEncrypt(const byte* in, word32 inLen, byte* out, word32 outLen,
RsaKey* key, WC_RNG* rng)
{
return RsaPublicEncryptEx(in, inLen, out, outLen, key,
RSA_PUBLIC_ENCRYPT, RSA_BLOCK_TYPE_2, WC_RSA_PKCSV15_PAD,
WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng);
}
#if !defined(WC_NO_RSA_OAEP) || defined(WC_RSA_NO_PADDING)
int wc_RsaPublicEncrypt_ex(const byte* in, word32 inLen, byte* out,
word32 outLen, RsaKey* key, WC_RNG* rng, int type,
enum wc_HashType hash, int mgf, byte* label,
word32 labelSz)
{
return RsaPublicEncryptEx(in, inLen, out, outLen, key, RSA_PUBLIC_ENCRYPT,
RSA_BLOCK_TYPE_2, type, hash, mgf, label, labelSz, 0, rng);
}
#endif /* WC_NO_RSA_OAEP */
#endif
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
int wc_RsaPrivateDecryptInline(byte* in, word32 inLen, byte** out, RsaKey* key)
{
WC_RNG* rng;
#ifdef WC_RSA_BLINDING
rng = key->rng;
#else
rng = NULL;
#endif
return RsaPrivateDecryptEx(in, inLen, in, inLen, out, key,
RSA_PRIVATE_DECRYPT, RSA_BLOCK_TYPE_2, WC_RSA_PKCSV15_PAD,
WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng);
}
#ifndef WC_NO_RSA_OAEP
int wc_RsaPrivateDecryptInline_ex(byte* in, word32 inLen, byte** out,
RsaKey* key, int type, enum wc_HashType hash,
int mgf, byte* label, word32 labelSz)
{
WC_RNG* rng;
#ifdef WC_RSA_BLINDING
rng = key->rng;
#else
rng = NULL;
#endif
return RsaPrivateDecryptEx(in, inLen, in, inLen, out, key,
RSA_PRIVATE_DECRYPT, RSA_BLOCK_TYPE_2, type, hash,
mgf, label, labelSz, 0, rng);
}
#endif /* WC_NO_RSA_OAEP */
int wc_RsaPrivateDecrypt(const byte* in, word32 inLen, byte* out,
word32 outLen, RsaKey* key)
{
WC_RNG* rng;
#ifdef WC_RSA_BLINDING
rng = key->rng;
#else
rng = NULL;
#endif
return RsaPrivateDecryptEx((byte*)in, inLen, out, outLen, NULL, key,
RSA_PRIVATE_DECRYPT, RSA_BLOCK_TYPE_2, WC_RSA_PKCSV15_PAD,
WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng);
}
#if !defined(WC_NO_RSA_OAEP) || defined(WC_RSA_NO_PADDING)
int wc_RsaPrivateDecrypt_ex(const byte* in, word32 inLen, byte* out,
word32 outLen, RsaKey* key, int type,
enum wc_HashType hash, int mgf, byte* label,
word32 labelSz)
{
WC_RNG* rng;
#ifdef WC_RSA_BLINDING
rng = key->rng;
#else
rng = NULL;
#endif
return RsaPrivateDecryptEx((byte*)in, inLen, out, outLen, NULL, key,
RSA_PRIVATE_DECRYPT, RSA_BLOCK_TYPE_2, type, hash, mgf, label,
labelSz, 0, rng);
}
#endif /* WC_NO_RSA_OAEP || WC_RSA_NO_PADDING */
#endif /* WOLFSSL_RSA_PUBLIC_ONLY */
#if !defined(WOLFSSL_CRYPTOCELL)
int wc_RsaSSL_VerifyInline(byte* in, word32 inLen, byte** out, RsaKey* key)
{
WC_RNG* rng;
#ifdef WC_RSA_BLINDING
rng = key->rng;
#else
rng = NULL;
#endif
return RsaPrivateDecryptEx(in, inLen, in, inLen, out, key,
RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PKCSV15_PAD,
WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng);
}
#endif
#ifndef WOLFSSL_RSA_VERIFY_ONLY
int wc_RsaSSL_Verify(const byte* in, word32 inLen, byte* out, word32 outLen,
RsaKey* key)
{
return wc_RsaSSL_Verify_ex(in, inLen, out, outLen, key , WC_RSA_PKCSV15_PAD);
}
int wc_RsaSSL_Verify_ex(const byte* in, word32 inLen, byte* out, word32 outLen,
RsaKey* key, int pad_type)
{
WC_RNG* rng;
if (key == NULL) {
return BAD_FUNC_ARG;
}
#ifdef WC_RSA_BLINDING
rng = key->rng;
#else
rng = NULL;
#endif
return RsaPrivateDecryptEx((byte*)in, inLen, out, outLen, NULL, key,
RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, pad_type,
WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng);
}
#endif
#ifdef WC_RSA_PSS
/* Verify the message signed with RSA-PSS.
* The input buffer is reused for the output buffer.
* Salt length is equal to hash length.
*
* in Buffer holding encrypted data.
* inLen Length of data in buffer.
* out Pointer to address containing the PSS data.
* hash Hash algorithm.
* mgf Mask generation function.
* key Public RSA key.
* returns the length of the PSS data on success and negative indicates failure.
*/
int wc_RsaPSS_VerifyInline(byte* in, word32 inLen, byte** out,
enum wc_HashType hash, int mgf, RsaKey* key)
{
#ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
return wc_RsaPSS_VerifyInline_ex(in, inLen, out, hash, mgf,
RSA_PSS_SALT_LEN_DEFAULT, key);
#else
return wc_RsaPSS_VerifyInline_ex(in, inLen, out, hash, mgf,
RSA_PSS_SALT_LEN_DISCOVER, key);
#endif
}
/* Verify the message signed with RSA-PSS.
* The input buffer is reused for the output buffer.
*
* in Buffer holding encrypted data.
* inLen Length of data in buffer.
* out Pointer to address containing the PSS data.
* hash Hash algorithm.
* mgf Mask generation function.
* key Public RSA key.
* saltLen Length of salt used. RSA_PSS_SALT_LEN_DEFAULT (-1) indicates salt
* length is the same as the hash length. RSA_PSS_SALT_LEN_DISCOVER
* indicates salt length is determined from the data.
* returns the length of the PSS data on success and negative indicates failure.
*/
int wc_RsaPSS_VerifyInline_ex(byte* in, word32 inLen, byte** out,
enum wc_HashType hash, int mgf, int saltLen,
RsaKey* key)
{
WC_RNG* rng;
#ifdef WC_RSA_BLINDING
rng = key->rng;
#else
rng = NULL;
#endif
return RsaPrivateDecryptEx(in, inLen, in, inLen, out, key,
RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PSS_PAD,
hash, mgf, NULL, 0, saltLen, rng);
}
/* Verify the message signed with RSA-PSS.
* Salt length is equal to hash length.
*
* in Buffer holding encrypted data.
* inLen Length of data in buffer.
* out Pointer to address containing the PSS data.
* hash Hash algorithm.
* mgf Mask generation function.
* key Public RSA key.
* returns the length of the PSS data on success and negative indicates failure.
*/
int wc_RsaPSS_Verify(byte* in, word32 inLen, byte* out, word32 outLen,
enum wc_HashType hash, int mgf, RsaKey* key)
{
#ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
return wc_RsaPSS_Verify_ex(in, inLen, out, outLen, hash, mgf,
RSA_PSS_SALT_LEN_DEFAULT, key);
#else
return wc_RsaPSS_Verify_ex(in, inLen, out, outLen, hash, mgf,
RSA_PSS_SALT_LEN_DISCOVER, key);
#endif
}
/* Verify the message signed with RSA-PSS.
*
* in Buffer holding encrypted data.
* inLen Length of data in buffer.
* out Pointer to address containing the PSS data.
* hash Hash algorithm.
* mgf Mask generation function.
* key Public RSA key.
* saltLen Length of salt used. RSA_PSS_SALT_LEN_DEFAULT (-1) indicates salt
* length is the same as the hash length. RSA_PSS_SALT_LEN_DISCOVER
* indicates salt length is determined from the data.
* returns the length of the PSS data on success and negative indicates failure.
*/
int wc_RsaPSS_Verify_ex(byte* in, word32 inLen, byte* out, word32 outLen,
enum wc_HashType hash, int mgf, int saltLen,
RsaKey* key)
{
WC_RNG* rng;
#ifdef WC_RSA_BLINDING
rng = key->rng;
#else
rng = NULL;
#endif
return RsaPrivateDecryptEx(in, inLen, out, outLen, NULL, key,
RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PSS_PAD,
hash, mgf, NULL, 0, saltLen, rng);
}
/* Checks the PSS data to ensure that the signature matches.
* Salt length is equal to hash length.
*
* in Hash of the data that is being verified.
* inSz Length of hash.
* sig Buffer holding PSS data.
* sigSz Size of PSS data.
* hashType Hash algorithm.
* returns BAD_PADDING_E when the PSS data is invalid, BAD_FUNC_ARG when
* NULL is passed in to in or sig or inSz is not the same as the hash
* algorithm length and 0 on success.
*/
int wc_RsaPSS_CheckPadding(const byte* in, word32 inSz, byte* sig,
word32 sigSz, enum wc_HashType hashType)
{
return wc_RsaPSS_CheckPadding_ex(in, inSz, sig, sigSz, hashType, inSz, 0);
}
/* Checks the PSS data to ensure that the signature matches.
*
* in Hash of the data that is being verified.
* inSz Length of hash.
* sig Buffer holding PSS data.
* sigSz Size of PSS data.
* hashType Hash algorithm.
* saltLen Length of salt used. RSA_PSS_SALT_LEN_DEFAULT (-1) indicates salt
* length is the same as the hash length. RSA_PSS_SALT_LEN_DISCOVER
* indicates salt length is determined from the data.
* returns BAD_PADDING_E when the PSS data is invalid, BAD_FUNC_ARG when
* NULL is passed in to in or sig or inSz is not the same as the hash
* algorithm length and 0 on success.
*/
int wc_RsaPSS_CheckPadding_ex(const byte* in, word32 inSz, byte* sig,
word32 sigSz, enum wc_HashType hashType,
int saltLen, int bits)
{
int ret = 0;
#ifndef WOLFSSL_PSS_LONG_SALT
byte sigCheck[WC_MAX_DIGEST_SIZE*2 + RSA_PSS_PAD_SZ];
#else
byte *sigCheck = NULL;
#endif
(void)bits;
if (in == NULL || sig == NULL ||
inSz != (word32)wc_HashGetDigestSize(hashType)) {
ret = BAD_FUNC_ARG;
}
if (ret == 0) {
if (saltLen == RSA_PSS_SALT_LEN_DEFAULT) {
saltLen = inSz;
#ifdef WOLFSSL_SHA512
/* See FIPS 186-4 section 5.5 item (e). */
if (bits == 1024 && inSz == WC_SHA512_DIGEST_SIZE) {
saltLen = RSA_PSS_SALT_MAX_SZ;
}
#endif
}
#ifndef WOLFSSL_PSS_LONG_SALT
else if ((word32)saltLen > inSz) {
ret = PSS_SALTLEN_E;
}
#endif
#ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
else if (saltLen < RSA_PSS_SALT_LEN_DEFAULT) {
ret = PSS_SALTLEN_E;
}
#else
else if (saltLen == RSA_PSS_SALT_LEN_DISCOVER) {
saltLen = sigSz - inSz;
if (saltLen < 0) {
ret = PSS_SALTLEN_E;
}
}
else if (saltLen < RSA_PSS_SALT_LEN_DISCOVER) {
ret = PSS_SALTLEN_E;
}
#endif
}
/* Sig = Salt | Exp Hash */
if (ret == 0) {
if (sigSz != inSz + saltLen) {
ret = PSS_SALTLEN_E;
}
}
#ifdef WOLFSSL_PSS_LONG_SALT
if (ret == 0) {
sigCheck = (byte*)XMALLOC(RSA_PSS_PAD_SZ + inSz + saltLen, NULL,
DYNAMIC_TYPE_RSA_BUFFER);
if (sigCheck == NULL) {
ret = MEMORY_E;
}
}
#endif
/* Exp Hash = HASH(8 * 0x00 | Message Hash | Salt) */
if (ret == 0) {
XMEMSET(sigCheck, 0, RSA_PSS_PAD_SZ);
XMEMCPY(sigCheck + RSA_PSS_PAD_SZ, in, inSz);
XMEMCPY(sigCheck + RSA_PSS_PAD_SZ + inSz, sig, saltLen);
ret = wc_Hash(hashType, sigCheck, RSA_PSS_PAD_SZ + inSz + saltLen,
sigCheck, inSz);
}
if (ret == 0) {
if (XMEMCMP(sigCheck, sig + saltLen, inSz) != 0) {
WOLFSSL_MSG("RsaPSS_CheckPadding: Padding Error");
ret = BAD_PADDING_E;
}
}
#ifdef WOLFSSL_PSS_LONG_SALT
if (sigCheck != NULL) {
XFREE(sigCheck, NULL, DYNAMIC_TYPE_RSA_BUFFER);
}
#endif
return ret;
}
/* Verify the message signed with RSA-PSS.
* The input buffer is reused for the output buffer.
* Salt length is equal to hash length.
*
* in Buffer holding encrypted data.
* inLen Length of data in buffer.
* out Pointer to address containing the PSS data.
* digest Hash of the data that is being verified.
* digestLen Length of hash.
* hash Hash algorithm.
* mgf Mask generation function.
* key Public RSA key.
* returns the length of the PSS data on success and negative indicates failure.
*/
int wc_RsaPSS_VerifyCheckInline(byte* in, word32 inLen, byte** out,
const byte* digest, word32 digestLen,
enum wc_HashType hash, int mgf, RsaKey* key)
{
int ret = 0, verify, saltLen, hLen, bits = 0;
hLen = wc_HashGetDigestSize(hash);
if (hLen < 0)
return BAD_FUNC_ARG;
if ((word32)hLen != digestLen)
return BAD_FUNC_ARG;
saltLen = hLen;
#ifdef WOLFSSL_SHA512
/* See FIPS 186-4 section 5.5 item (e). */
bits = mp_count_bits(&key->n);
if (bits == 1024 && hLen == WC_SHA512_DIGEST_SIZE)
saltLen = RSA_PSS_SALT_MAX_SZ;
#endif
verify = wc_RsaPSS_VerifyInline_ex(in, inLen, out, hash, mgf, saltLen, key);
if (verify > 0)
ret = wc_RsaPSS_CheckPadding_ex(digest, digestLen, *out, verify,
hash, saltLen, bits);
if (ret == 0)
ret = verify;
return ret;
}
/* Verify the message signed with RSA-PSS.
* Salt length is equal to hash length.
*
* in Buffer holding encrypted data.
* inLen Length of data in buffer.
* out Pointer to address containing the PSS data.
* outLen Length of the output.
* digest Hash of the data that is being verified.
* digestLen Length of hash.
* hash Hash algorithm.
* mgf Mask generation function.
* key Public RSA key.
* returns the length of the PSS data on success and negative indicates failure.
*/
int wc_RsaPSS_VerifyCheck(byte* in, word32 inLen, byte* out, word32 outLen,
const byte* digest, word32 digestLen,
enum wc_HashType hash, int mgf,
RsaKey* key)
{
int ret = 0, verify, saltLen, hLen, bits = 0;
hLen = wc_HashGetDigestSize(hash);
if (hLen < 0)
return hLen;
if ((word32)hLen != digestLen)
return BAD_FUNC_ARG;
saltLen = hLen;
#ifdef WOLFSSL_SHA512
/* See FIPS 186-4 section 5.5 item (e). */
bits = mp_count_bits(&key->n);
if (bits == 1024 && hLen == WC_SHA512_DIGEST_SIZE)
saltLen = RSA_PSS_SALT_MAX_SZ;
#endif
verify = wc_RsaPSS_Verify_ex(in, inLen, out, outLen, hash,
mgf, saltLen, key);
if (verify > 0)
ret = wc_RsaPSS_CheckPadding_ex(digest, digestLen, out, verify,
hash, saltLen, bits);
if (ret == 0)
ret = verify;
return ret;
}
#endif
#if !defined(WOLFSSL_RSA_PUBLIC_ONLY) && !defined(WOLFSSL_RSA_VERIFY_ONLY)
int wc_RsaSSL_Sign(const byte* in, word32 inLen, byte* out, word32 outLen,
RsaKey* key, WC_RNG* rng)
{
return RsaPublicEncryptEx(in, inLen, out, outLen, key,
RSA_PRIVATE_ENCRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PKCSV15_PAD,
WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng);
}
#ifdef WC_RSA_PSS
/* Sign the hash of a message using RSA-PSS.
* Salt length is equal to hash length.
*
* in Buffer holding hash of message.
* inLen Length of data in buffer (hash length).
* out Buffer to write encrypted signature into.
* outLen Size of buffer to write to.
* hash Hash algorithm.
* mgf Mask generation function.
* key Public RSA key.
* rng Random number generator.
* returns the length of the encrypted signature on success, a negative value
* indicates failure.
*/
int wc_RsaPSS_Sign(const byte* in, word32 inLen, byte* out, word32 outLen,
enum wc_HashType hash, int mgf, RsaKey* key, WC_RNG* rng)
{
return wc_RsaPSS_Sign_ex(in, inLen, out, outLen, hash, mgf,
RSA_PSS_SALT_LEN_DEFAULT, key, rng);
}
/* Sign the hash of a message using RSA-PSS.
*
* in Buffer holding hash of message.
* inLen Length of data in buffer (hash length).
* out Buffer to write encrypted signature into.
* outLen Size of buffer to write to.
* hash Hash algorithm.
* mgf Mask generation function.
* saltLen Length of salt used. RSA_PSS_SALT_LEN_DEFAULT (-1) indicates salt
* length is the same as the hash length. RSA_PSS_SALT_LEN_DISCOVER
* indicates salt length is determined from the data.
* key Public RSA key.
* rng Random number generator.
* returns the length of the encrypted signature on success, a negative value
* indicates failure.
*/
int wc_RsaPSS_Sign_ex(const byte* in, word32 inLen, byte* out, word32 outLen,
enum wc_HashType hash, int mgf, int saltLen, RsaKey* key,
WC_RNG* rng)
{
return RsaPublicEncryptEx(in, inLen, out, outLen, key,
RSA_PRIVATE_ENCRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PSS_PAD,
hash, mgf, NULL, 0, saltLen, rng);
}
#endif
#endif
#if !defined(WOLFSSL_RSA_VERIFY_ONLY) || !defined(WOLFSSL_SP_MATH) || \
defined(WC_RSA_PSS)
int wc_RsaEncryptSize(RsaKey* key)
{
int ret;
if (key == NULL) {
return BAD_FUNC_ARG;
}
ret = mp_unsigned_bin_size(&key->n);
#ifdef WOLF_CRYPTO_CB
if (ret == 0 && key->devId != INVALID_DEVID) {
ret = 2048/8; /* hardware handles, use 2048-bit as default */
}
#endif
return ret;
}
#endif
#ifndef WOLFSSL_RSA_VERIFY_ONLY
/* flatten RsaKey structure into individual elements (e, n) */
int wc_RsaFlattenPublicKey(RsaKey* key, byte* e, word32* eSz, byte* n,
word32* nSz)
{
int sz, ret;
if (key == NULL || e == NULL || eSz == NULL || n == NULL || nSz == NULL) {
return BAD_FUNC_ARG;
}
sz = mp_unsigned_bin_size(&key->e);
if ((word32)sz > *eSz)
return RSA_BUFFER_E;
ret = mp_to_unsigned_bin(&key->e, e);
if (ret != MP_OKAY)
return ret;
*eSz = (word32)sz;
sz = wc_RsaEncryptSize(key);
if ((word32)sz > *nSz)
return RSA_BUFFER_E;
ret = mp_to_unsigned_bin(&key->n, n);
if (ret != MP_OKAY)
return ret;
*nSz = (word32)sz;
return 0;
}
#endif
#endif /* HAVE_FIPS */
#ifndef WOLFSSL_RSA_VERIFY_ONLY
static int RsaGetValue(mp_int* in, byte* out, word32* outSz)
{
word32 sz;
int ret = 0;
/* Parameters ensured by calling function. */
sz = (word32)mp_unsigned_bin_size(in);
if (sz > *outSz)
ret = RSA_BUFFER_E;
if (ret == 0)
ret = mp_to_unsigned_bin(in, out);
if (ret == MP_OKAY)
*outSz = sz;
return ret;
}
int wc_RsaExportKey(RsaKey* key,
byte* e, word32* eSz, byte* n, word32* nSz,
byte* d, word32* dSz, byte* p, word32* pSz,
byte* q, word32* qSz)
{
int ret = BAD_FUNC_ARG;
if (key && e && eSz && n && nSz && d && dSz && p && pSz && q && qSz)
ret = 0;
if (ret == 0)
ret = RsaGetValue(&key->e, e, eSz);
if (ret == 0)
ret = RsaGetValue(&key->n, n, nSz);
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
if (ret == 0)
ret = RsaGetValue(&key->d, d, dSz);
if (ret == 0)
ret = RsaGetValue(&key->p, p, pSz);
if (ret == 0)
ret = RsaGetValue(&key->q, q, qSz);
#else
/* no private parts to key */
if (d == NULL || p == NULL || q == NULL || dSz == NULL || pSz == NULL
|| qSz == NULL) {
ret = BAD_FUNC_ARG;
}
else {
*dSz = 0;
*pSz = 0;
*qSz = 0;
}
#endif /* WOLFSSL_RSA_PUBLIC_ONLY */
return ret;
}
#endif
#ifdef WOLFSSL_KEY_GEN
/* Check that |p-q| > 2^((size/2)-100) */
static int wc_CompareDiffPQ(mp_int* p, mp_int* q, int size)
{
mp_int c, d;
int ret;
if (p == NULL || q == NULL)
return BAD_FUNC_ARG;
ret = mp_init_multi(&c, &d, NULL, NULL, NULL, NULL);
/* c = 2^((size/2)-100) */
if (ret == 0)
ret = mp_2expt(&c, (size/2)-100);
/* d = |p-q| */
if (ret == 0)
ret = mp_sub(p, q, &d);
if (ret == 0)
ret = mp_abs(&d, &d);
/* compare */
if (ret == 0)
ret = mp_cmp(&d, &c);
if (ret == MP_GT)
ret = MP_OKAY;
mp_clear(&d);
mp_clear(&c);
return ret;
}
/* The lower_bound value is floor(2^(0.5) * 2^((nlen/2)-1)) where nlen is 4096.
* This number was calculated using a small test tool written with a common
* large number math library. Other values of nlen may be checked with a subset
* of lower_bound. */
static const byte lower_bound[] = {
0xB5, 0x04, 0xF3, 0x33, 0xF9, 0xDE, 0x64, 0x84,
0x59, 0x7D, 0x89, 0xB3, 0x75, 0x4A, 0xBE, 0x9F,
0x1D, 0x6F, 0x60, 0xBA, 0x89, 0x3B, 0xA8, 0x4C,
0xED, 0x17, 0xAC, 0x85, 0x83, 0x33, 0x99, 0x15,
/* 512 */
0x4A, 0xFC, 0x83, 0x04, 0x3A, 0xB8, 0xA2, 0xC3,
0xA8, 0xB1, 0xFE, 0x6F, 0xDC, 0x83, 0xDB, 0x39,
0x0F, 0x74, 0xA8, 0x5E, 0x43, 0x9C, 0x7B, 0x4A,
0x78, 0x04, 0x87, 0x36, 0x3D, 0xFA, 0x27, 0x68,
/* 1024 */
0xD2, 0x20, 0x2E, 0x87, 0x42, 0xAF, 0x1F, 0x4E,
0x53, 0x05, 0x9C, 0x60, 0x11, 0xBC, 0x33, 0x7B,
0xCA, 0xB1, 0xBC, 0x91, 0x16, 0x88, 0x45, 0x8A,
0x46, 0x0A, 0xBC, 0x72, 0x2F, 0x7C, 0x4E, 0x33,
0xC6, 0xD5, 0xA8, 0xA3, 0x8B, 0xB7, 0xE9, 0xDC,
0xCB, 0x2A, 0x63, 0x43, 0x31, 0xF3, 0xC8, 0x4D,
0xF5, 0x2F, 0x12, 0x0F, 0x83, 0x6E, 0x58, 0x2E,
0xEA, 0xA4, 0xA0, 0x89, 0x90, 0x40, 0xCA, 0x4A,
/* 2048 */
0x81, 0x39, 0x4A, 0xB6, 0xD8, 0xFD, 0x0E, 0xFD,
0xF4, 0xD3, 0xA0, 0x2C, 0xEB, 0xC9, 0x3E, 0x0C,
0x42, 0x64, 0xDA, 0xBC, 0xD5, 0x28, 0xB6, 0x51,
0xB8, 0xCF, 0x34, 0x1B, 0x6F, 0x82, 0x36, 0xC7,
0x01, 0x04, 0xDC, 0x01, 0xFE, 0x32, 0x35, 0x2F,
0x33, 0x2A, 0x5E, 0x9F, 0x7B, 0xDA, 0x1E, 0xBF,
0xF6, 0xA1, 0xBE, 0x3F, 0xCA, 0x22, 0x13, 0x07,
0xDE, 0xA0, 0x62, 0x41, 0xF7, 0xAA, 0x81, 0xC2,
/* 3072 */
0xC1, 0xFC, 0xBD, 0xDE, 0xA2, 0xF7, 0xDC, 0x33,
0x18, 0x83, 0x8A, 0x2E, 0xAF, 0xF5, 0xF3, 0xB2,
0xD2, 0x4F, 0x4A, 0x76, 0x3F, 0xAC, 0xB8, 0x82,
0xFD, 0xFE, 0x17, 0x0F, 0xD3, 0xB1, 0xF7, 0x80,
0xF9, 0xAC, 0xCE, 0x41, 0x79, 0x7F, 0x28, 0x05,
0xC2, 0x46, 0x78, 0x5E, 0x92, 0x95, 0x70, 0x23,
0x5F, 0xCF, 0x8F, 0x7B, 0xCA, 0x3E, 0xA3, 0x3B,
0x4D, 0x7C, 0x60, 0xA5, 0xE6, 0x33, 0xE3, 0xE1
/* 4096 */
};
/* returns 1 on key size ok and 0 if not ok */
static WC_INLINE int RsaSizeCheck(int size)
{
if (size < RSA_MIN_SIZE || size > RSA_MAX_SIZE) {
return 0;
}
#ifdef HAVE_FIPS
/* Key size requirements for CAVP */
switch (size) {
case 1024:
case 2048:
case 3072:
case 4096:
return 1;
}
return 0;
#else
return 1; /* allow unusual key sizes in non FIPS mode */
#endif /* HAVE_FIPS */
}
static int _CheckProbablePrime(mp_int* p, mp_int* q, mp_int* e, int nlen,
int* isPrime, WC_RNG* rng)
{
int ret;
mp_int tmp1, tmp2;
mp_int* prime;
if (p == NULL || e == NULL || isPrime == NULL)
return BAD_FUNC_ARG;
if (!RsaSizeCheck(nlen))
return BAD_FUNC_ARG;
*isPrime = MP_NO;
if (q != NULL) {
/* 5.4 - check that |p-q| <= (2^(1/2))(2^((nlen/2)-1)) */
ret = wc_CompareDiffPQ(p, q, nlen);
if (ret != MP_OKAY) goto notOkay;
prime = q;
}
else
prime = p;
ret = mp_init_multi(&tmp1, &tmp2, NULL, NULL, NULL, NULL);
if (ret != MP_OKAY) goto notOkay;
/* 4.4,5.5 - Check that prime >= (2^(1/2))(2^((nlen/2)-1))
* This is a comparison against lowerBound */
ret = mp_read_unsigned_bin(&tmp1, lower_bound, nlen/16);
if (ret != MP_OKAY) goto notOkay;
ret = mp_cmp(prime, &tmp1);
if (ret == MP_LT) goto exit;
/* 4.5,5.6 - Check that GCD(p-1, e) == 1 */
ret = mp_sub_d(prime, 1, &tmp1); /* tmp1 = prime-1 */
if (ret != MP_OKAY) goto notOkay;
ret = mp_gcd(&tmp1, e, &tmp2); /* tmp2 = gcd(prime-1, e) */
if (ret != MP_OKAY) goto notOkay;
ret = mp_cmp_d(&tmp2, 1);
if (ret != MP_EQ) goto exit; /* e divides p-1 */
/* 4.5.1,5.6.1 - Check primality of p with 8 rounds of M-R.
* mp_prime_is_prime_ex() performs test divisions against the first 256
* prime numbers. After that it performs 8 rounds of M-R using random
* bases between 2 and n-2.
* mp_prime_is_prime() performs the same test divisions and then does
* M-R with the first 8 primes. Both functions set isPrime as a
* side-effect. */
if (rng != NULL)
ret = mp_prime_is_prime_ex(prime, 8, isPrime, rng);
else
ret = mp_prime_is_prime(prime, 8, isPrime);
if (ret != MP_OKAY) goto notOkay;
exit:
ret = MP_OKAY;
notOkay:
mp_clear(&tmp1);
mp_clear(&tmp2);
return ret;
}
int wc_CheckProbablePrime_ex(const byte* pRaw, word32 pRawSz,
const byte* qRaw, word32 qRawSz,
const byte* eRaw, word32 eRawSz,
int nlen, int* isPrime, WC_RNG* rng)
{
mp_int p, q, e;
mp_int* Q = NULL;
int ret;
if (pRaw == NULL || pRawSz == 0 ||
eRaw == NULL || eRawSz == 0 ||
isPrime == NULL) {
return BAD_FUNC_ARG;
}
if ((qRaw != NULL && qRawSz == 0) || (qRaw == NULL && qRawSz != 0))
return BAD_FUNC_ARG;
ret = mp_init_multi(&p, &q, &e, NULL, NULL, NULL);
if (ret == MP_OKAY)
ret = mp_read_unsigned_bin(&p, pRaw, pRawSz);
if (ret == MP_OKAY) {
if (qRaw != NULL) {
ret = mp_read_unsigned_bin(&q, qRaw, qRawSz);
if (ret == MP_OKAY)
Q = &q;
}
}
if (ret == MP_OKAY)
ret = mp_read_unsigned_bin(&e, eRaw, eRawSz);
if (ret == MP_OKAY)
ret = _CheckProbablePrime(&p, Q, &e, nlen, isPrime, rng);
ret = (ret == MP_OKAY) ? 0 : PRIME_GEN_E;
mp_clear(&p);
mp_clear(&q);
mp_clear(&e);
return ret;
}
int wc_CheckProbablePrime(const byte* pRaw, word32 pRawSz,
const byte* qRaw, word32 qRawSz,
const byte* eRaw, word32 eRawSz,
int nlen, int* isPrime)
{
return wc_CheckProbablePrime_ex(pRaw, pRawSz, qRaw, qRawSz,
eRaw, eRawSz, nlen, isPrime, NULL);
}
#if !defined(HAVE_FIPS) || (defined(HAVE_FIPS) && \
defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2))
/* Make an RSA key for size bits, with e specified, 65537 is a good e */
int wc_MakeRsaKey(RsaKey* key, int size, long e, WC_RNG* rng)
{
#ifndef WC_NO_RNG
#ifdef WOLFSSL_SMALL_STACK
mp_int *p = (mp_int *)XMALLOC(sizeof *p, key->heap, DYNAMIC_TYPE_RSA);
mp_int *q = (mp_int *)XMALLOC(sizeof *q, key->heap, DYNAMIC_TYPE_RSA);
mp_int *tmp1 = (mp_int *)XMALLOC(sizeof *tmp1, key->heap, DYNAMIC_TYPE_RSA);
mp_int *tmp2 = (mp_int *)XMALLOC(sizeof *tmp2, key->heap, DYNAMIC_TYPE_RSA);
mp_int *tmp3 = (mp_int *)XMALLOC(sizeof *tmp3, key->heap, DYNAMIC_TYPE_RSA);
#else
mp_int p_buf, *p = &p_buf;
mp_int q_buf, *q = &q_buf;
mp_int tmp1_buf, *tmp1 = &tmp1_buf;
mp_int tmp2_buf, *tmp2 = &tmp2_buf;
mp_int tmp3_buf, *tmp3 = &tmp3_buf;
#endif
int err, i, failCount, primeSz, isPrime = 0;
byte* buf = NULL;
#ifdef WOLFSSL_SMALL_STACK
if ((p == NULL) ||
(q == NULL) ||
(tmp1 == NULL) ||
(tmp2 == NULL) ||
(tmp3 == NULL)) {
err = MEMORY_E;
goto out;
}
#endif
if (key == NULL || rng == NULL) {
err = BAD_FUNC_ARG;
goto out;
}
if (!RsaSizeCheck(size)) {
err = BAD_FUNC_ARG;
goto out;
}
if (e < 3 || (e & 1) == 0) {
err = BAD_FUNC_ARG;
goto out;
}
#if defined(WOLFSSL_CRYPTOCELL)
err = cc310_RSA_GenerateKeyPair(key, size, e);
goto out;
#endif /*WOLFSSL_CRYPTOCELL*/
#ifdef WOLF_CRYPTO_CB
if (key->devId != INVALID_DEVID) {
err = wc_CryptoCb_MakeRsaKey(key, size, e, rng);
if (err != CRYPTOCB_UNAVAILABLE)
goto out;
/* fall-through when unavailable */
}
#endif
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) && \
defined(WC_ASYNC_ENABLE_RSA_KEYGEN)
if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA) {
#ifdef HAVE_CAVIUM
/* TODO: Not implemented */
#elif defined(HAVE_INTEL_QA)
err = IntelQaRsaKeyGen(&key->asyncDev, key, size, e, rng);
goto out;
#else
if (wc_AsyncTestInit(&key->asyncDev, ASYNC_TEST_RSA_MAKE)) {
WC_ASYNC_TEST* testDev = &key->asyncDev.test;
testDev->rsaMake.rng = rng;
testDev->rsaMake.key = key;
testDev->rsaMake.size = size;
testDev->rsaMake.e = e;
err = WC_PENDING_E;
goto out;
}
#endif
}
#endif
err = mp_init_multi(p, q, tmp1, tmp2, tmp3, NULL);
if (err == MP_OKAY)
err = mp_set_int(tmp3, e);
/* The failCount value comes from NIST FIPS 186-4, section B.3.3,
* process steps 4.7 and 5.8. */
failCount = 5 * (size / 2);
primeSz = size / 16; /* size is the size of n in bits.
primeSz is in bytes. */
/* allocate buffer to work with */
if (err == MP_OKAY) {
buf = (byte*)XMALLOC(primeSz, key->heap, DYNAMIC_TYPE_RSA);
if (buf == NULL)
err = MEMORY_E;
}
/* make p */
if (err == MP_OKAY) {
isPrime = 0;
i = 0;
do {
#ifdef SHOW_GEN
printf(".");
fflush(stdout);
#endif
/* generate value */
err = wc_RNG_GenerateBlock(rng, buf, primeSz);
if (err == 0) {
/* prime lower bound has the MSB set, set it in candidate */
buf[0] |= 0x80;
/* make candidate odd */
buf[primeSz-1] |= 0x01;
/* load value */
err = mp_read_unsigned_bin(p, buf, primeSz);
}
if (err == MP_OKAY)
err = _CheckProbablePrime(p, NULL, tmp3, size, &isPrime, rng);
#ifdef HAVE_FIPS
i++;
#else
/* Keep the old retry behavior in non-FIPS build. */
(void)i;
#endif
} while (err == MP_OKAY && !isPrime && i < failCount);
}
if (err == MP_OKAY && !isPrime)
err = PRIME_GEN_E;
/* make q */
if (err == MP_OKAY) {
isPrime = 0;
i = 0;
do {
#ifdef SHOW_GEN
printf(".");
fflush(stdout);
#endif
/* generate value */
err = wc_RNG_GenerateBlock(rng, buf, primeSz);
if (err == 0) {
/* prime lower bound has the MSB set, set it in candidate */
buf[0] |= 0x80;
/* make candidate odd */
buf[primeSz-1] |= 0x01;
/* load value */
err = mp_read_unsigned_bin(q, buf, primeSz);
}
if (err == MP_OKAY)
err = _CheckProbablePrime(p, q, tmp3, size, &isPrime, rng);
#ifdef HAVE_FIPS
i++;
#else
/* Keep the old retry behavior in non-FIPS build. */
(void)i;
#endif
} while (err == MP_OKAY && !isPrime && i < failCount);
}
if (err == MP_OKAY && !isPrime)
err = PRIME_GEN_E;
if (buf) {
ForceZero(buf, primeSz);
XFREE(buf, key->heap, DYNAMIC_TYPE_RSA);
}
if (err == MP_OKAY && mp_cmp(p, q) < 0) {
err = mp_copy(p, tmp1);
if (err == MP_OKAY)
err = mp_copy(q, p);
if (err == MP_OKAY)
mp_copy(tmp1, q);
}
/* Setup RsaKey buffers */
if (err == MP_OKAY)
err = mp_init_multi(&key->n, &key->e, &key->d, &key->p, &key->q, NULL);
if (err == MP_OKAY)
err = mp_init_multi(&key->dP, &key->dQ, &key->u, NULL, NULL, NULL);
/* Software Key Calculation */
if (err == MP_OKAY) /* tmp1 = p-1 */
err = mp_sub_d(p, 1, tmp1);
if (err == MP_OKAY) /* tmp2 = q-1 */
err = mp_sub_d(q, 1, tmp2);
#ifdef WC_RSA_BLINDING
if (err == MP_OKAY) /* tmp3 = order of n */
err = mp_mul(tmp1, tmp2, tmp3);
#else
if (err == MP_OKAY) /* tmp3 = lcm(p-1, q-1), last loop */
err = mp_lcm(tmp1, tmp2, tmp3);
#endif
/* make key */
if (err == MP_OKAY) /* key->e = e */
err = mp_set_int(&key->e, (mp_digit)e);
#ifdef WC_RSA_BLINDING
/* Blind the inverse operation with a value that is invertable */
if (err == MP_OKAY) {
do {
err = mp_rand(&key->p, get_digit_count(tmp3), rng);
if (err == MP_OKAY)
err = mp_set_bit(&key->p, 0);
if (err == MP_OKAY)
err = mp_set_bit(&key->p, size - 1);
if (err == MP_OKAY)
err = mp_gcd(&key->p, tmp3, &key->q);
}
while ((err == MP_OKAY) && !mp_isone(&key->q));
}
if (err == MP_OKAY)
err = mp_mul_d(&key->p, (mp_digit)e, &key->e);
#endif
if (err == MP_OKAY) /* key->d = 1/e mod lcm(p-1, q-1) */
err = mp_invmod(&key->e, tmp3, &key->d);
#ifdef WC_RSA_BLINDING
/* Take off blinding from d and reset e */
if (err == MP_OKAY)
err = mp_mulmod(&key->d, &key->p, tmp3, &key->d);
if (err == MP_OKAY)
err = mp_set_int(&key->e, (mp_digit)e);
#endif
if (err == MP_OKAY) /* key->n = pq */
err = mp_mul(p, q, &key->n);
if (err == MP_OKAY) /* key->dP = d mod(p-1) */
err = mp_mod(&key->d, tmp1, &key->dP);
if (err == MP_OKAY) /* key->dQ = d mod(q-1) */
err = mp_mod(&key->d, tmp2, &key->dQ);
#ifdef WOLFSSL_MP_INVMOD_CONSTANT_TIME
if (err == MP_OKAY) /* key->u = 1/q mod p */
err = mp_invmod(q, p, &key->u);
#else
if (err == MP_OKAY)
err = mp_sub_d(p, 2, tmp3);
if (err == MP_OKAY) /* key->u = 1/q mod p = q^p-2 mod p */
err = mp_exptmod(q, tmp3 , p, &key->u);
#endif
if (err == MP_OKAY)
err = mp_copy(p, &key->p);
if (err == MP_OKAY)
err = mp_copy(q, &key->q);
#ifdef HAVE_WOLF_BIGINT
/* make sure raw unsigned bin version is available */
if (err == MP_OKAY)
err = wc_mp_to_bigint(&key->n, &key->n.raw);
if (err == MP_OKAY)
err = wc_mp_to_bigint(&key->e, &key->e.raw);
if (err == MP_OKAY)
err = wc_mp_to_bigint(&key->d, &key->d.raw);
if (err == MP_OKAY)
err = wc_mp_to_bigint(&key->p, &key->p.raw);
if (err == MP_OKAY)
err = wc_mp_to_bigint(&key->q, &key->q.raw);
if (err == MP_OKAY)
err = wc_mp_to_bigint(&key->dP, &key->dP.raw);
if (err == MP_OKAY)
err = wc_mp_to_bigint(&key->dQ, &key->dQ.raw);
if (err == MP_OKAY)
err = wc_mp_to_bigint(&key->u, &key->u.raw);
#endif
if (err == MP_OKAY)
key->type = RSA_PRIVATE;
mp_clear(tmp1);
mp_clear(tmp2);
mp_clear(tmp3);
mp_clear(p);
mp_clear(q);
#if defined(WOLFSSL_KEY_GEN) && !defined(WOLFSSL_NO_RSA_KEY_CHECK)
/* Perform the pair-wise consistency test on the new key. */
if (err == 0)
err = wc_CheckRsaKey(key);
#endif
if (err != 0) {
wc_FreeRsaKey(key);
goto out;
}
#if defined(WOLFSSL_XILINX_CRYPT) || defined(WOLFSSL_CRYPTOCELL)
if (wc_InitRsaHw(key) != 0) {
return BAD_STATE_E;
}
#endif
err = 0;
out:
#ifdef WOLFSSL_SMALL_STACK
if (p)
XFREE(p, key->heap, DYNAMIC_TYPE_RSA);
if (q)
XFREE(q, key->heap, DYNAMIC_TYPE_RSA);
if (tmp1)
XFREE(tmp1, key->heap, DYNAMIC_TYPE_RSA);
if (tmp2)
XFREE(tmp2, key->heap, DYNAMIC_TYPE_RSA);
if (tmp3)
XFREE(tmp3, key->heap, DYNAMIC_TYPE_RSA);
#endif
return err;
#else
return NOT_COMPILED_IN;
#endif
}
#endif /* !FIPS || FIPS_VER >= 2 */
#endif /* WOLFSSL_KEY_GEN */
#ifdef WC_RSA_BLINDING
int wc_RsaSetRNG(RsaKey* key, WC_RNG* rng)
{
if (key == NULL)
return BAD_FUNC_ARG;
key->rng = rng;
return 0;
}
#endif /* WC_RSA_BLINDING */
#ifdef WC_RSA_NONBLOCK
int wc_RsaSetNonBlock(RsaKey* key, RsaNb* nb)
{
if (key == NULL)
return BAD_FUNC_ARG;
if (nb) {
XMEMSET(nb, 0, sizeof(RsaNb));
}
/* Allow nb == NULL to clear non-block mode */
key->nb = nb;
return 0;
}
#ifdef WC_RSA_NONBLOCK_TIME
int wc_RsaSetNonBlockTime(RsaKey* key, word32 maxBlockUs, word32 cpuMHz)
{
if (key == NULL || key->nb == NULL) {
return BAD_FUNC_ARG;
}
/* calculate maximum number of instructions to block */
key->nb->exptmod.maxBlockInst = cpuMHz * maxBlockUs;
return 0;
}
#endif /* WC_RSA_NONBLOCK_TIME */
#endif /* WC_RSA_NONBLOCK */
#endif /* NO_RSA */
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_4490_0 |
crossvul-cpp_data_bad_205_3 | /*
* trace_events_filter - generic event filtering
*
* 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.
*
* Copyright (C) 2009 Tom Zanussi <tzanussi@gmail.com>
*/
#include <linux/module.h>
#include <linux/ctype.h>
#include <linux/mutex.h>
#include <linux/perf_event.h>
#include <linux/slab.h>
#include "trace.h"
#include "trace_output.h"
#define DEFAULT_SYS_FILTER_MESSAGE \
"### global filter ###\n" \
"# Use this to set filters for multiple events.\n" \
"# Only events with the given fields will be affected.\n" \
"# If no events are modified, an error message will be displayed here"
/* Due to token parsing '<=' must be before '<' and '>=' must be before '>' */
#define OPS \
C( OP_GLOB, "~" ), \
C( OP_NE, "!=" ), \
C( OP_EQ, "==" ), \
C( OP_LE, "<=" ), \
C( OP_LT, "<" ), \
C( OP_GE, ">=" ), \
C( OP_GT, ">" ), \
C( OP_BAND, "&" ), \
C( OP_MAX, NULL )
#undef C
#define C(a, b) a
enum filter_op_ids { OPS };
#undef C
#define C(a, b) b
static const char * ops[] = { OPS };
/*
* pred functions are OP_LE, OP_LT, OP_GE, OP_GT, and OP_BAND
* pred_funcs_##type below must match the order of them above.
*/
#define PRED_FUNC_START OP_LE
#define PRED_FUNC_MAX (OP_BAND - PRED_FUNC_START)
#define ERRORS \
C(NONE, "No error"), \
C(INVALID_OP, "Invalid operator"), \
C(TOO_MANY_OPEN, "Too many '('"), \
C(TOO_MANY_CLOSE, "Too few '('"), \
C(MISSING_QUOTE, "Missing matching quote"), \
C(OPERAND_TOO_LONG, "Operand too long"), \
C(EXPECT_STRING, "Expecting string field"), \
C(EXPECT_DIGIT, "Expecting numeric field"), \
C(ILLEGAL_FIELD_OP, "Illegal operation for field type"), \
C(FIELD_NOT_FOUND, "Field not found"), \
C(ILLEGAL_INTVAL, "Illegal integer value"), \
C(BAD_SUBSYS_FILTER, "Couldn't find or set field in one of a subsystem's events"), \
C(TOO_MANY_PREDS, "Too many terms in predicate expression"), \
C(INVALID_FILTER, "Meaningless filter expression"), \
C(IP_FIELD_ONLY, "Only 'ip' field is supported for function trace"), \
C(INVALID_VALUE, "Invalid value (did you forget quotes)?"),
#undef C
#define C(a, b) FILT_ERR_##a
enum { ERRORS };
#undef C
#define C(a, b) b
static char *err_text[] = { ERRORS };
/* Called after a '!' character but "!=" and "!~" are not "not"s */
static bool is_not(const char *str)
{
switch (str[1]) {
case '=':
case '~':
return false;
}
return true;
}
/**
* prog_entry - a singe entry in the filter program
* @target: Index to jump to on a branch (actually one minus the index)
* @when_to_branch: The value of the result of the predicate to do a branch
* @pred: The predicate to execute.
*/
struct prog_entry {
int target;
int when_to_branch;
struct filter_pred *pred;
};
/**
* update_preds- assign a program entry a label target
* @prog: The program array
* @N: The index of the current entry in @prog
* @when_to_branch: What to assign a program entry for its branch condition
*
* The program entry at @N has a target that points to the index of a program
* entry that can have its target and when_to_branch fields updated.
* Update the current program entry denoted by index @N target field to be
* that of the updated entry. This will denote the entry to update if
* we are processing an "||" after an "&&"
*/
static void update_preds(struct prog_entry *prog, int N, int invert)
{
int t, s;
t = prog[N].target;
s = prog[t].target;
prog[t].when_to_branch = invert;
prog[t].target = N;
prog[N].target = s;
}
struct filter_parse_error {
int lasterr;
int lasterr_pos;
};
static void parse_error(struct filter_parse_error *pe, int err, int pos)
{
pe->lasterr = err;
pe->lasterr_pos = pos;
}
typedef int (*parse_pred_fn)(const char *str, void *data, int pos,
struct filter_parse_error *pe,
struct filter_pred **pred);
enum {
INVERT = 1,
PROCESS_AND = 2,
PROCESS_OR = 4,
};
/*
* Without going into a formal proof, this explains the method that is used in
* parsing the logical expressions.
*
* For example, if we have: "a && !(!b || (c && g)) || d || e && !f"
* The first pass will convert it into the following program:
*
* n1: r=a; l1: if (!r) goto l4;
* n2: r=b; l2: if (!r) goto l4;
* n3: r=c; r=!r; l3: if (r) goto l4;
* n4: r=g; r=!r; l4: if (r) goto l5;
* n5: r=d; l5: if (r) goto T
* n6: r=e; l6: if (!r) goto l7;
* n7: r=f; r=!r; l7: if (!r) goto F
* T: return TRUE
* F: return FALSE
*
* To do this, we use a data structure to represent each of the above
* predicate and conditions that has:
*
* predicate, when_to_branch, invert, target
*
* The "predicate" will hold the function to determine the result "r".
* The "when_to_branch" denotes what "r" should be if a branch is to be taken
* "&&" would contain "!r" or (0) and "||" would contain "r" or (1).
* The "invert" holds whether the value should be reversed before testing.
* The "target" contains the label "l#" to jump to.
*
* A stack is created to hold values when parentheses are used.
*
* To simplify the logic, the labels will start at 0 and not 1.
*
* The possible invert values are 1 and 0. The number of "!"s that are in scope
* before the predicate determines the invert value, if the number is odd then
* the invert value is 1 and 0 otherwise. This means the invert value only
* needs to be toggled when a new "!" is introduced compared to what is stored
* on the stack, where parentheses were used.
*
* The top of the stack and "invert" are initialized to zero.
*
* ** FIRST PASS **
*
* #1 A loop through all the tokens is done:
*
* #2 If the token is an "(", the stack is push, and the current stack value
* gets the current invert value, and the loop continues to the next token.
* The top of the stack saves the "invert" value to keep track of what
* the current inversion is. As "!(a && !b || c)" would require all
* predicates being affected separately by the "!" before the parentheses.
* And that would end up being equivalent to "(!a || b) && !c"
*
* #3 If the token is an "!", the current "invert" value gets inverted, and
* the loop continues. Note, if the next token is a predicate, then
* this "invert" value is only valid for the current program entry,
* and does not affect other predicates later on.
*
* The only other acceptable token is the predicate string.
*
* #4 A new entry into the program is added saving: the predicate and the
* current value of "invert". The target is currently assigned to the
* previous program index (this will not be its final value).
*
* #5 We now enter another loop and look at the next token. The only valid
* tokens are ")", "&&", "||" or end of the input string "\0".
*
* #6 The invert variable is reset to the current value saved on the top of
* the stack.
*
* #7 The top of the stack holds not only the current invert value, but also
* if a "&&" or "||" needs to be processed. Note, the "&&" takes higher
* precedence than "||". That is "a && b || c && d" is equivalent to
* "(a && b) || (c && d)". Thus the first thing to do is to see if "&&" needs
* to be processed. This is the case if an "&&" was the last token. If it was
* then we call update_preds(). This takes the program, the current index in
* the program, and the current value of "invert". More will be described
* below about this function.
*
* #8 If the next token is "&&" then we set a flag in the top of the stack
* that denotes that "&&" needs to be processed, break out of this loop
* and continue with the outer loop.
*
* #9 Otherwise, if a "||" needs to be processed then update_preds() is called.
* This is called with the program, the current index in the program, but
* this time with an inverted value of "invert" (that is !invert). This is
* because the value taken will become the "when_to_branch" value of the
* program.
* Note, this is called when the next token is not an "&&". As stated before,
* "&&" takes higher precedence, and "||" should not be processed yet if the
* next logical operation is "&&".
*
* #10 If the next token is "||" then we set a flag in the top of the stack
* that denotes that "||" needs to be processed, break out of this loop
* and continue with the outer loop.
*
* #11 If this is the end of the input string "\0" then we break out of both
* loops.
*
* #12 Otherwise, the next token is ")", where we pop the stack and continue
* this inner loop.
*
* Now to discuss the update_pred() function, as that is key to the setting up
* of the program. Remember the "target" of the program is initialized to the
* previous index and not the "l" label. The target holds the index into the
* program that gets affected by the operand. Thus if we have something like
* "a || b && c", when we process "a" the target will be "-1" (undefined).
* When we process "b", its target is "0", which is the index of "a", as that's
* the predicate that is affected by "||". But because the next token after "b"
* is "&&" we don't call update_preds(). Instead continue to "c". As the
* next token after "c" is not "&&" but the end of input, we first process the
* "&&" by calling update_preds() for the "&&" then we process the "||" by
* callin updates_preds() with the values for processing "||".
*
* What does that mean? What update_preds() does is to first save the "target"
* of the program entry indexed by the current program entry's "target"
* (remember the "target" is initialized to previous program entry), and then
* sets that "target" to the current index which represents the label "l#".
* That entry's "when_to_branch" is set to the value passed in (the "invert"
* or "!invert"). Then it sets the current program entry's target to the saved
* "target" value (the old value of the program that had its "target" updated
* to the label).
*
* Looking back at "a || b && c", we have the following steps:
* "a" - prog[0] = { "a", X, -1 } // pred, when_to_branch, target
* "||" - flag that we need to process "||"; continue outer loop
* "b" - prog[1] = { "b", X, 0 }
* "&&" - flag that we need to process "&&"; continue outer loop
* (Notice we did not process "||")
* "c" - prog[2] = { "c", X, 1 }
* update_preds(prog, 2, 0); // invert = 0 as we are processing "&&"
* t = prog[2].target; // t = 1
* s = prog[t].target; // s = 0
* prog[t].target = 2; // Set target to "l2"
* prog[t].when_to_branch = 0;
* prog[2].target = s;
* update_preds(prog, 2, 1); // invert = 1 as we are now processing "||"
* t = prog[2].target; // t = 0
* s = prog[t].target; // s = -1
* prog[t].target = 2; // Set target to "l2"
* prog[t].when_to_branch = 1;
* prog[2].target = s;
*
* #13 Which brings us to the final step of the first pass, which is to set
* the last program entry's when_to_branch and target, which will be
* when_to_branch = 0; target = N; ( the label after the program entry after
* the last program entry processed above).
*
* If we denote "TRUE" to be the entry after the last program entry processed,
* and "FALSE" the program entry after that, we are now done with the first
* pass.
*
* Making the above "a || b && c" have a progam of:
* prog[0] = { "a", 1, 2 }
* prog[1] = { "b", 0, 2 }
* prog[2] = { "c", 0, 3 }
*
* Which translates into:
* n0: r = a; l0: if (r) goto l2;
* n1: r = b; l1: if (!r) goto l2;
* n2: r = c; l2: if (!r) goto l3; // Which is the same as "goto F;"
* T: return TRUE; l3:
* F: return FALSE
*
* Although, after the first pass, the program is correct, it is
* inefficient. The simple sample of "a || b && c" could be easily been
* converted into:
* n0: r = a; if (r) goto T
* n1: r = b; if (!r) goto F
* n2: r = c; if (!r) goto F
* T: return TRUE;
* F: return FALSE;
*
* The First Pass is over the input string. The next too passes are over
* the program itself.
*
* ** SECOND PASS **
*
* Which brings us to the second pass. If a jump to a label has the
* same condition as that label, it can instead jump to its target.
* The original example of "a && !(!b || (c && g)) || d || e && !f"
* where the first pass gives us:
*
* n1: r=a; l1: if (!r) goto l4;
* n2: r=b; l2: if (!r) goto l4;
* n3: r=c; r=!r; l3: if (r) goto l4;
* n4: r=g; r=!r; l4: if (r) goto l5;
* n5: r=d; l5: if (r) goto T
* n6: r=e; l6: if (!r) goto l7;
* n7: r=f; r=!r; l7: if (!r) goto F:
* T: return TRUE;
* F: return FALSE
*
* We can see that "l3: if (r) goto l4;" and at l4, we have "if (r) goto l5;".
* And "l5: if (r) goto T", we could optimize this by converting l3 and l4
* to go directly to T. To accomplish this, we start from the last
* entry in the program and work our way back. If the target of the entry
* has the same "when_to_branch" then we could use that entry's target.
* Doing this, the above would end up as:
*
* n1: r=a; l1: if (!r) goto l4;
* n2: r=b; l2: if (!r) goto l4;
* n3: r=c; r=!r; l3: if (r) goto T;
* n4: r=g; r=!r; l4: if (r) goto T;
* n5: r=d; l5: if (r) goto T;
* n6: r=e; l6: if (!r) goto F;
* n7: r=f; r=!r; l7: if (!r) goto F;
* T: return TRUE
* F: return FALSE
*
* In that same pass, if the "when_to_branch" doesn't match, we can simply
* go to the program entry after the label. That is, "l2: if (!r) goto l4;"
* where "l4: if (r) goto T;", then we can convert l2 to be:
* "l2: if (!r) goto n5;".
*
* This will have the second pass give us:
* n1: r=a; l1: if (!r) goto n5;
* n2: r=b; l2: if (!r) goto n5;
* n3: r=c; r=!r; l3: if (r) goto T;
* n4: r=g; r=!r; l4: if (r) goto T;
* n5: r=d; l5: if (r) goto T
* n6: r=e; l6: if (!r) goto F;
* n7: r=f; r=!r; l7: if (!r) goto F
* T: return TRUE
* F: return FALSE
*
* Notice, all the "l#" labels are no longer used, and they can now
* be discarded.
*
* ** THIRD PASS **
*
* For the third pass we deal with the inverts. As they simply just
* make the "when_to_branch" get inverted, a simple loop over the
* program to that does: "when_to_branch ^= invert;" will do the
* job, leaving us with:
* n1: r=a; if (!r) goto n5;
* n2: r=b; if (!r) goto n5;
* n3: r=c: if (!r) goto T;
* n4: r=g; if (!r) goto T;
* n5: r=d; if (r) goto T
* n6: r=e; if (!r) goto F;
* n7: r=f; if (r) goto F
* T: return TRUE
* F: return FALSE
*
* As "r = a; if (!r) goto n5;" is obviously the same as
* "if (!a) goto n5;" without doing anything we can interperate the
* program as:
* n1: if (!a) goto n5;
* n2: if (!b) goto n5;
* n3: if (!c) goto T;
* n4: if (!g) goto T;
* n5: if (d) goto T
* n6: if (!e) goto F;
* n7: if (f) goto F
* T: return TRUE
* F: return FALSE
*
* Since the inverts are discarded at the end, there's no reason to store
* them in the program array (and waste memory). A separate array to hold
* the inverts is used and freed at the end.
*/
static struct prog_entry *
predicate_parse(const char *str, int nr_parens, int nr_preds,
parse_pred_fn parse_pred, void *data,
struct filter_parse_error *pe)
{
struct prog_entry *prog_stack;
struct prog_entry *prog;
const char *ptr = str;
char *inverts = NULL;
int *op_stack;
int *top;
int invert = 0;
int ret = -ENOMEM;
int len;
int N = 0;
int i;
nr_preds += 2; /* For TRUE and FALSE */
op_stack = kmalloc_array(nr_parens, sizeof(*op_stack), GFP_KERNEL);
if (!op_stack)
return ERR_PTR(-ENOMEM);
prog_stack = kmalloc_array(nr_preds, sizeof(*prog_stack), GFP_KERNEL);
if (!prog_stack) {
parse_error(pe, -ENOMEM, 0);
goto out_free;
}
inverts = kmalloc_array(nr_preds, sizeof(*inverts), GFP_KERNEL);
if (!inverts) {
parse_error(pe, -ENOMEM, 0);
goto out_free;
}
top = op_stack;
prog = prog_stack;
*top = 0;
/* First pass */
while (*ptr) { /* #1 */
const char *next = ptr++;
if (isspace(*next))
continue;
switch (*next) {
case '(': /* #2 */
if (top - op_stack > nr_parens)
return ERR_PTR(-EINVAL);
*(++top) = invert;
continue;
case '!': /* #3 */
if (!is_not(next))
break;
invert = !invert;
continue;
}
if (N >= nr_preds) {
parse_error(pe, FILT_ERR_TOO_MANY_PREDS, next - str);
goto out_free;
}
inverts[N] = invert; /* #4 */
prog[N].target = N-1;
len = parse_pred(next, data, ptr - str, pe, &prog[N].pred);
if (len < 0) {
ret = len;
goto out_free;
}
ptr = next + len;
N++;
ret = -1;
while (1) { /* #5 */
next = ptr++;
if (isspace(*next))
continue;
switch (*next) {
case ')':
case '\0':
break;
case '&':
case '|':
if (next[1] == next[0]) {
ptr++;
break;
}
default:
parse_error(pe, FILT_ERR_TOO_MANY_PREDS,
next - str);
goto out_free;
}
invert = *top & INVERT;
if (*top & PROCESS_AND) { /* #7 */
update_preds(prog, N - 1, invert);
*top &= ~PROCESS_AND;
}
if (*next == '&') { /* #8 */
*top |= PROCESS_AND;
break;
}
if (*top & PROCESS_OR) { /* #9 */
update_preds(prog, N - 1, !invert);
*top &= ~PROCESS_OR;
}
if (*next == '|') { /* #10 */
*top |= PROCESS_OR;
break;
}
if (!*next) /* #11 */
goto out;
if (top == op_stack) {
ret = -1;
/* Too few '(' */
parse_error(pe, FILT_ERR_TOO_MANY_CLOSE, ptr - str);
goto out_free;
}
top--; /* #12 */
}
}
out:
if (top != op_stack) {
/* Too many '(' */
parse_error(pe, FILT_ERR_TOO_MANY_OPEN, ptr - str);
goto out_free;
}
prog[N].pred = NULL; /* #13 */
prog[N].target = 1; /* TRUE */
prog[N+1].pred = NULL;
prog[N+1].target = 0; /* FALSE */
prog[N-1].target = N;
prog[N-1].when_to_branch = false;
/* Second Pass */
for (i = N-1 ; i--; ) {
int target = prog[i].target;
if (prog[i].when_to_branch == prog[target].when_to_branch)
prog[i].target = prog[target].target;
}
/* Third Pass */
for (i = 0; i < N; i++) {
invert = inverts[i] ^ prog[i].when_to_branch;
prog[i].when_to_branch = invert;
/* Make sure the program always moves forward */
if (WARN_ON(prog[i].target <= i)) {
ret = -EINVAL;
goto out_free;
}
}
return prog;
out_free:
kfree(op_stack);
kfree(prog_stack);
kfree(inverts);
return ERR_PTR(ret);
}
#define DEFINE_COMPARISON_PRED(type) \
static int filter_pred_LT_##type(struct filter_pred *pred, void *event) \
{ \
type *addr = (type *)(event + pred->offset); \
type val = (type)pred->val; \
return *addr < val; \
} \
static int filter_pred_LE_##type(struct filter_pred *pred, void *event) \
{ \
type *addr = (type *)(event + pred->offset); \
type val = (type)pred->val; \
return *addr <= val; \
} \
static int filter_pred_GT_##type(struct filter_pred *pred, void *event) \
{ \
type *addr = (type *)(event + pred->offset); \
type val = (type)pred->val; \
return *addr > val; \
} \
static int filter_pred_GE_##type(struct filter_pred *pred, void *event) \
{ \
type *addr = (type *)(event + pred->offset); \
type val = (type)pred->val; \
return *addr >= val; \
} \
static int filter_pred_BAND_##type(struct filter_pred *pred, void *event) \
{ \
type *addr = (type *)(event + pred->offset); \
type val = (type)pred->val; \
return !!(*addr & val); \
} \
static const filter_pred_fn_t pred_funcs_##type[] = { \
filter_pred_LE_##type, \
filter_pred_LT_##type, \
filter_pred_GE_##type, \
filter_pred_GT_##type, \
filter_pred_BAND_##type, \
};
#define DEFINE_EQUALITY_PRED(size) \
static int filter_pred_##size(struct filter_pred *pred, void *event) \
{ \
u##size *addr = (u##size *)(event + pred->offset); \
u##size val = (u##size)pred->val; \
int match; \
\
match = (val == *addr) ^ pred->not; \
\
return match; \
}
DEFINE_COMPARISON_PRED(s64);
DEFINE_COMPARISON_PRED(u64);
DEFINE_COMPARISON_PRED(s32);
DEFINE_COMPARISON_PRED(u32);
DEFINE_COMPARISON_PRED(s16);
DEFINE_COMPARISON_PRED(u16);
DEFINE_COMPARISON_PRED(s8);
DEFINE_COMPARISON_PRED(u8);
DEFINE_EQUALITY_PRED(64);
DEFINE_EQUALITY_PRED(32);
DEFINE_EQUALITY_PRED(16);
DEFINE_EQUALITY_PRED(8);
/* Filter predicate for fixed sized arrays of characters */
static int filter_pred_string(struct filter_pred *pred, void *event)
{
char *addr = (char *)(event + pred->offset);
int cmp, match;
cmp = pred->regex.match(addr, &pred->regex, pred->regex.field_len);
match = cmp ^ pred->not;
return match;
}
/* Filter predicate for char * pointers */
static int filter_pred_pchar(struct filter_pred *pred, void *event)
{
char **addr = (char **)(event + pred->offset);
int cmp, match;
int len = strlen(*addr) + 1; /* including tailing '\0' */
cmp = pred->regex.match(*addr, &pred->regex, len);
match = cmp ^ pred->not;
return match;
}
/*
* Filter predicate for dynamic sized arrays of characters.
* These are implemented through a list of strings at the end
* of the entry.
* Also each of these strings have a field in the entry which
* contains its offset from the beginning of the entry.
* We have then first to get this field, dereference it
* and add it to the address of the entry, and at last we have
* the address of the string.
*/
static int filter_pred_strloc(struct filter_pred *pred, void *event)
{
u32 str_item = *(u32 *)(event + pred->offset);
int str_loc = str_item & 0xffff;
int str_len = str_item >> 16;
char *addr = (char *)(event + str_loc);
int cmp, match;
cmp = pred->regex.match(addr, &pred->regex, str_len);
match = cmp ^ pred->not;
return match;
}
/* Filter predicate for CPUs. */
static int filter_pred_cpu(struct filter_pred *pred, void *event)
{
int cpu, cmp;
cpu = raw_smp_processor_id();
cmp = pred->val;
switch (pred->op) {
case OP_EQ:
return cpu == cmp;
case OP_NE:
return cpu != cmp;
case OP_LT:
return cpu < cmp;
case OP_LE:
return cpu <= cmp;
case OP_GT:
return cpu > cmp;
case OP_GE:
return cpu >= cmp;
default:
return 0;
}
}
/* Filter predicate for COMM. */
static int filter_pred_comm(struct filter_pred *pred, void *event)
{
int cmp;
cmp = pred->regex.match(current->comm, &pred->regex,
TASK_COMM_LEN);
return cmp ^ pred->not;
}
static int filter_pred_none(struct filter_pred *pred, void *event)
{
return 0;
}
/*
* regex_match_foo - Basic regex callbacks
*
* @str: the string to be searched
* @r: the regex structure containing the pattern string
* @len: the length of the string to be searched (including '\0')
*
* Note:
* - @str might not be NULL-terminated if it's of type DYN_STRING
* or STATIC_STRING, unless @len is zero.
*/
static int regex_match_full(char *str, struct regex *r, int len)
{
/* len of zero means str is dynamic and ends with '\0' */
if (!len)
return strcmp(str, r->pattern) == 0;
return strncmp(str, r->pattern, len) == 0;
}
static int regex_match_front(char *str, struct regex *r, int len)
{
if (len && len < r->len)
return 0;
return strncmp(str, r->pattern, r->len) == 0;
}
static int regex_match_middle(char *str, struct regex *r, int len)
{
if (!len)
return strstr(str, r->pattern) != NULL;
return strnstr(str, r->pattern, len) != NULL;
}
static int regex_match_end(char *str, struct regex *r, int len)
{
int strlen = len - 1;
if (strlen >= r->len &&
memcmp(str + strlen - r->len, r->pattern, r->len) == 0)
return 1;
return 0;
}
static int regex_match_glob(char *str, struct regex *r, int len __maybe_unused)
{
if (glob_match(r->pattern, str))
return 1;
return 0;
}
/**
* filter_parse_regex - parse a basic regex
* @buff: the raw regex
* @len: length of the regex
* @search: will point to the beginning of the string to compare
* @not: tell whether the match will have to be inverted
*
* This passes in a buffer containing a regex and this function will
* set search to point to the search part of the buffer and
* return the type of search it is (see enum above).
* This does modify buff.
*
* Returns enum type.
* search returns the pointer to use for comparison.
* not returns 1 if buff started with a '!'
* 0 otherwise.
*/
enum regex_type filter_parse_regex(char *buff, int len, char **search, int *not)
{
int type = MATCH_FULL;
int i;
if (buff[0] == '!') {
*not = 1;
buff++;
len--;
} else
*not = 0;
*search = buff;
for (i = 0; i < len; i++) {
if (buff[i] == '*') {
if (!i) {
type = MATCH_END_ONLY;
} else if (i == len - 1) {
if (type == MATCH_END_ONLY)
type = MATCH_MIDDLE_ONLY;
else
type = MATCH_FRONT_ONLY;
buff[i] = 0;
break;
} else { /* pattern continues, use full glob */
return MATCH_GLOB;
}
} else if (strchr("[?\\", buff[i])) {
return MATCH_GLOB;
}
}
if (buff[0] == '*')
*search = buff + 1;
return type;
}
static void filter_build_regex(struct filter_pred *pred)
{
struct regex *r = &pred->regex;
char *search;
enum regex_type type = MATCH_FULL;
if (pred->op == OP_GLOB) {
type = filter_parse_regex(r->pattern, r->len, &search, &pred->not);
r->len = strlen(search);
memmove(r->pattern, search, r->len+1);
}
switch (type) {
case MATCH_FULL:
r->match = regex_match_full;
break;
case MATCH_FRONT_ONLY:
r->match = regex_match_front;
break;
case MATCH_MIDDLE_ONLY:
r->match = regex_match_middle;
break;
case MATCH_END_ONLY:
r->match = regex_match_end;
break;
case MATCH_GLOB:
r->match = regex_match_glob;
break;
}
}
/* return 1 if event matches, 0 otherwise (discard) */
int filter_match_preds(struct event_filter *filter, void *rec)
{
struct prog_entry *prog;
int i;
/* no filter is considered a match */
if (!filter)
return 1;
prog = rcu_dereference_sched(filter->prog);
if (!prog)
return 1;
for (i = 0; prog[i].pred; i++) {
struct filter_pred *pred = prog[i].pred;
int match = pred->fn(pred, rec);
if (match == prog[i].when_to_branch)
i = prog[i].target;
}
return prog[i].target;
}
EXPORT_SYMBOL_GPL(filter_match_preds);
static void remove_filter_string(struct event_filter *filter)
{
if (!filter)
return;
kfree(filter->filter_string);
filter->filter_string = NULL;
}
static void append_filter_err(struct filter_parse_error *pe,
struct event_filter *filter)
{
struct trace_seq *s;
int pos = pe->lasterr_pos;
char *buf;
int len;
if (WARN_ON(!filter->filter_string))
return;
s = kmalloc(sizeof(*s), GFP_KERNEL);
if (!s)
return;
trace_seq_init(s);
len = strlen(filter->filter_string);
if (pos > len)
pos = len;
/* indexing is off by one */
if (pos)
pos++;
trace_seq_puts(s, filter->filter_string);
if (pe->lasterr > 0) {
trace_seq_printf(s, "\n%*s", pos, "^");
trace_seq_printf(s, "\nparse_error: %s\n", err_text[pe->lasterr]);
} else {
trace_seq_printf(s, "\nError: (%d)\n", pe->lasterr);
}
trace_seq_putc(s, 0);
buf = kmemdup_nul(s->buffer, s->seq.len, GFP_KERNEL);
if (buf) {
kfree(filter->filter_string);
filter->filter_string = buf;
}
kfree(s);
}
static inline struct event_filter *event_filter(struct trace_event_file *file)
{
return file->filter;
}
/* caller must hold event_mutex */
void print_event_filter(struct trace_event_file *file, struct trace_seq *s)
{
struct event_filter *filter = event_filter(file);
if (filter && filter->filter_string)
trace_seq_printf(s, "%s\n", filter->filter_string);
else
trace_seq_puts(s, "none\n");
}
void print_subsystem_event_filter(struct event_subsystem *system,
struct trace_seq *s)
{
struct event_filter *filter;
mutex_lock(&event_mutex);
filter = system->filter;
if (filter && filter->filter_string)
trace_seq_printf(s, "%s\n", filter->filter_string);
else
trace_seq_puts(s, DEFAULT_SYS_FILTER_MESSAGE "\n");
mutex_unlock(&event_mutex);
}
static void free_prog(struct event_filter *filter)
{
struct prog_entry *prog;
int i;
prog = rcu_access_pointer(filter->prog);
if (!prog)
return;
for (i = 0; prog[i].pred; i++)
kfree(prog[i].pred);
kfree(prog);
}
static void filter_disable(struct trace_event_file *file)
{
unsigned long old_flags = file->flags;
file->flags &= ~EVENT_FILE_FL_FILTERED;
if (old_flags != file->flags)
trace_buffered_event_disable();
}
static void __free_filter(struct event_filter *filter)
{
if (!filter)
return;
free_prog(filter);
kfree(filter->filter_string);
kfree(filter);
}
void free_event_filter(struct event_filter *filter)
{
__free_filter(filter);
}
static inline void __remove_filter(struct trace_event_file *file)
{
filter_disable(file);
remove_filter_string(file->filter);
}
static void filter_free_subsystem_preds(struct trace_subsystem_dir *dir,
struct trace_array *tr)
{
struct trace_event_file *file;
list_for_each_entry(file, &tr->events, list) {
if (file->system != dir)
continue;
__remove_filter(file);
}
}
static inline void __free_subsystem_filter(struct trace_event_file *file)
{
__free_filter(file->filter);
file->filter = NULL;
}
static void filter_free_subsystem_filters(struct trace_subsystem_dir *dir,
struct trace_array *tr)
{
struct trace_event_file *file;
list_for_each_entry(file, &tr->events, list) {
if (file->system != dir)
continue;
__free_subsystem_filter(file);
}
}
int filter_assign_type(const char *type)
{
if (strstr(type, "__data_loc") && strstr(type, "char"))
return FILTER_DYN_STRING;
if (strchr(type, '[') && strstr(type, "char"))
return FILTER_STATIC_STRING;
return FILTER_OTHER;
}
static filter_pred_fn_t select_comparison_fn(enum filter_op_ids op,
int field_size, int field_is_signed)
{
filter_pred_fn_t fn = NULL;
int pred_func_index = -1;
switch (op) {
case OP_EQ:
case OP_NE:
break;
default:
if (WARN_ON_ONCE(op < PRED_FUNC_START))
return NULL;
pred_func_index = op - PRED_FUNC_START;
if (WARN_ON_ONCE(pred_func_index > PRED_FUNC_MAX))
return NULL;
}
switch (field_size) {
case 8:
if (pred_func_index < 0)
fn = filter_pred_64;
else if (field_is_signed)
fn = pred_funcs_s64[pred_func_index];
else
fn = pred_funcs_u64[pred_func_index];
break;
case 4:
if (pred_func_index < 0)
fn = filter_pred_32;
else if (field_is_signed)
fn = pred_funcs_s32[pred_func_index];
else
fn = pred_funcs_u32[pred_func_index];
break;
case 2:
if (pred_func_index < 0)
fn = filter_pred_16;
else if (field_is_signed)
fn = pred_funcs_s16[pred_func_index];
else
fn = pred_funcs_u16[pred_func_index];
break;
case 1:
if (pred_func_index < 0)
fn = filter_pred_8;
else if (field_is_signed)
fn = pred_funcs_s8[pred_func_index];
else
fn = pred_funcs_u8[pred_func_index];
break;
}
return fn;
}
/* Called when a predicate is encountered by predicate_parse() */
static int parse_pred(const char *str, void *data,
int pos, struct filter_parse_error *pe,
struct filter_pred **pred_ptr)
{
struct trace_event_call *call = data;
struct ftrace_event_field *field;
struct filter_pred *pred = NULL;
char num_buf[24]; /* Big enough to hold an address */
char *field_name;
char q;
u64 val;
int len;
int ret;
int op;
int s;
int i = 0;
/* First find the field to associate to */
while (isspace(str[i]))
i++;
s = i;
while (isalnum(str[i]) || str[i] == '_')
i++;
len = i - s;
if (!len)
return -1;
field_name = kmemdup_nul(str + s, len, GFP_KERNEL);
if (!field_name)
return -ENOMEM;
/* Make sure that the field exists */
field = trace_find_event_field(call, field_name);
kfree(field_name);
if (!field) {
parse_error(pe, FILT_ERR_FIELD_NOT_FOUND, pos + i);
return -EINVAL;
}
while (isspace(str[i]))
i++;
/* Make sure this op is supported */
for (op = 0; ops[op]; op++) {
/* This is why '<=' must come before '<' in ops[] */
if (strncmp(str + i, ops[op], strlen(ops[op])) == 0)
break;
}
if (!ops[op]) {
parse_error(pe, FILT_ERR_INVALID_OP, pos + i);
goto err_free;
}
i += strlen(ops[op]);
while (isspace(str[i]))
i++;
s = i;
pred = kzalloc(sizeof(*pred), GFP_KERNEL);
if (!pred)
return -ENOMEM;
pred->field = field;
pred->offset = field->offset;
pred->op = op;
if (ftrace_event_is_function(call)) {
/*
* Perf does things different with function events.
* It only allows an "ip" field, and expects a string.
* But the string does not need to be surrounded by quotes.
* If it is a string, the assigned function as a nop,
* (perf doesn't use it) and grab everything.
*/
if (strcmp(field->name, "ip") != 0) {
parse_error(pe, FILT_ERR_IP_FIELD_ONLY, pos + i);
goto err_free;
}
pred->fn = filter_pred_none;
/*
* Quotes are not required, but if they exist then we need
* to read them till we hit a matching one.
*/
if (str[i] == '\'' || str[i] == '"')
q = str[i];
else
q = 0;
for (i++; str[i]; i++) {
if (q && str[i] == q)
break;
if (!q && (str[i] == ')' || str[i] == '&' ||
str[i] == '|'))
break;
}
/* Skip quotes */
if (q)
s++;
len = i - s;
if (len >= MAX_FILTER_STR_VAL) {
parse_error(pe, FILT_ERR_OPERAND_TOO_LONG, pos + i);
goto err_free;
}
pred->regex.len = len;
strncpy(pred->regex.pattern, str + s, len);
pred->regex.pattern[len] = 0;
/* This is either a string, or an integer */
} else if (str[i] == '\'' || str[i] == '"') {
char q = str[i];
/* Make sure the op is OK for strings */
switch (op) {
case OP_NE:
pred->not = 1;
/* Fall through */
case OP_GLOB:
case OP_EQ:
break;
default:
parse_error(pe, FILT_ERR_ILLEGAL_FIELD_OP, pos + i);
goto err_free;
}
/* Make sure the field is OK for strings */
if (!is_string_field(field)) {
parse_error(pe, FILT_ERR_EXPECT_DIGIT, pos + i);
goto err_free;
}
for (i++; str[i]; i++) {
if (str[i] == q)
break;
}
if (!str[i]) {
parse_error(pe, FILT_ERR_MISSING_QUOTE, pos + i);
goto err_free;
}
/* Skip quotes */
s++;
len = i - s;
if (len >= MAX_FILTER_STR_VAL) {
parse_error(pe, FILT_ERR_OPERAND_TOO_LONG, pos + i);
goto err_free;
}
pred->regex.len = len;
strncpy(pred->regex.pattern, str + s, len);
pred->regex.pattern[len] = 0;
filter_build_regex(pred);
if (field->filter_type == FILTER_COMM) {
pred->fn = filter_pred_comm;
} else if (field->filter_type == FILTER_STATIC_STRING) {
pred->fn = filter_pred_string;
pred->regex.field_len = field->size;
} else if (field->filter_type == FILTER_DYN_STRING)
pred->fn = filter_pred_strloc;
else
pred->fn = filter_pred_pchar;
/* go past the last quote */
i++;
} else if (isdigit(str[i])) {
/* Make sure the field is not a string */
if (is_string_field(field)) {
parse_error(pe, FILT_ERR_EXPECT_STRING, pos + i);
goto err_free;
}
if (op == OP_GLOB) {
parse_error(pe, FILT_ERR_ILLEGAL_FIELD_OP, pos + i);
goto err_free;
}
/* We allow 0xDEADBEEF */
while (isalnum(str[i]))
i++;
len = i - s;
/* 0xfeedfacedeadbeef is 18 chars max */
if (len >= sizeof(num_buf)) {
parse_error(pe, FILT_ERR_OPERAND_TOO_LONG, pos + i);
goto err_free;
}
strncpy(num_buf, str + s, len);
num_buf[len] = 0;
/* Make sure it is a value */
if (field->is_signed)
ret = kstrtoll(num_buf, 0, &val);
else
ret = kstrtoull(num_buf, 0, &val);
if (ret) {
parse_error(pe, FILT_ERR_ILLEGAL_INTVAL, pos + s);
goto err_free;
}
pred->val = val;
if (field->filter_type == FILTER_CPU)
pred->fn = filter_pred_cpu;
else {
pred->fn = select_comparison_fn(pred->op, field->size,
field->is_signed);
if (pred->op == OP_NE)
pred->not = 1;
}
} else {
parse_error(pe, FILT_ERR_INVALID_VALUE, pos + i);
goto err_free;
}
*pred_ptr = pred;
return i;
err_free:
kfree(pred);
return -EINVAL;
}
enum {
TOO_MANY_CLOSE = -1,
TOO_MANY_OPEN = -2,
MISSING_QUOTE = -3,
};
/*
* Read the filter string once to calculate the number of predicates
* as well as how deep the parentheses go.
*
* Returns:
* 0 - everything is fine (err is undefined)
* -1 - too many ')'
* -2 - too many '('
* -3 - No matching quote
*/
static int calc_stack(const char *str, int *parens, int *preds, int *err)
{
bool is_pred = false;
int nr_preds = 0;
int open = 1; /* Count the expression as "(E)" */
int last_quote = 0;
int max_open = 1;
int quote = 0;
int i;
*err = 0;
for (i = 0; str[i]; i++) {
if (isspace(str[i]))
continue;
if (quote) {
if (str[i] == quote)
quote = 0;
continue;
}
switch (str[i]) {
case '\'':
case '"':
quote = str[i];
last_quote = i;
break;
case '|':
case '&':
if (str[i+1] != str[i])
break;
is_pred = false;
continue;
case '(':
is_pred = false;
open++;
if (open > max_open)
max_open = open;
continue;
case ')':
is_pred = false;
if (open == 1) {
*err = i;
return TOO_MANY_CLOSE;
}
open--;
continue;
}
if (!is_pred) {
nr_preds++;
is_pred = true;
}
}
if (quote) {
*err = last_quote;
return MISSING_QUOTE;
}
if (open != 1) {
int level = open;
/* find the bad open */
for (i--; i; i--) {
if (quote) {
if (str[i] == quote)
quote = 0;
continue;
}
switch (str[i]) {
case '(':
if (level == open) {
*err = i;
return TOO_MANY_OPEN;
}
level--;
break;
case ')':
level++;
break;
case '\'':
case '"':
quote = str[i];
break;
}
}
/* First character is the '(' with missing ')' */
*err = 0;
return TOO_MANY_OPEN;
}
/* Set the size of the required stacks */
*parens = max_open;
*preds = nr_preds;
return 0;
}
static int process_preds(struct trace_event_call *call,
const char *filter_string,
struct event_filter *filter,
struct filter_parse_error *pe)
{
struct prog_entry *prog;
int nr_parens;
int nr_preds;
int index;
int ret;
ret = calc_stack(filter_string, &nr_parens, &nr_preds, &index);
if (ret < 0) {
switch (ret) {
case MISSING_QUOTE:
parse_error(pe, FILT_ERR_MISSING_QUOTE, index);
break;
case TOO_MANY_OPEN:
parse_error(pe, FILT_ERR_TOO_MANY_OPEN, index);
break;
default:
parse_error(pe, FILT_ERR_TOO_MANY_CLOSE, index);
}
return ret;
}
if (!nr_preds)
return -EINVAL;
prog = predicate_parse(filter_string, nr_parens, nr_preds,
parse_pred, call, pe);
if (IS_ERR(prog))
return PTR_ERR(prog);
rcu_assign_pointer(filter->prog, prog);
return 0;
}
static inline void event_set_filtered_flag(struct trace_event_file *file)
{
unsigned long old_flags = file->flags;
file->flags |= EVENT_FILE_FL_FILTERED;
if (old_flags != file->flags)
trace_buffered_event_enable();
}
static inline void event_set_filter(struct trace_event_file *file,
struct event_filter *filter)
{
rcu_assign_pointer(file->filter, filter);
}
static inline void event_clear_filter(struct trace_event_file *file)
{
RCU_INIT_POINTER(file->filter, NULL);
}
static inline void
event_set_no_set_filter_flag(struct trace_event_file *file)
{
file->flags |= EVENT_FILE_FL_NO_SET_FILTER;
}
static inline void
event_clear_no_set_filter_flag(struct trace_event_file *file)
{
file->flags &= ~EVENT_FILE_FL_NO_SET_FILTER;
}
static inline bool
event_no_set_filter_flag(struct trace_event_file *file)
{
if (file->flags & EVENT_FILE_FL_NO_SET_FILTER)
return true;
return false;
}
struct filter_list {
struct list_head list;
struct event_filter *filter;
};
static int process_system_preds(struct trace_subsystem_dir *dir,
struct trace_array *tr,
struct filter_parse_error *pe,
char *filter_string)
{
struct trace_event_file *file;
struct filter_list *filter_item;
struct event_filter *filter = NULL;
struct filter_list *tmp;
LIST_HEAD(filter_list);
bool fail = true;
int err;
list_for_each_entry(file, &tr->events, list) {
if (file->system != dir)
continue;
filter = kzalloc(sizeof(*filter), GFP_KERNEL);
if (!filter)
goto fail_mem;
filter->filter_string = kstrdup(filter_string, GFP_KERNEL);
if (!filter->filter_string)
goto fail_mem;
err = process_preds(file->event_call, filter_string, filter, pe);
if (err) {
filter_disable(file);
parse_error(pe, FILT_ERR_BAD_SUBSYS_FILTER, 0);
append_filter_err(pe, filter);
} else
event_set_filtered_flag(file);
filter_item = kzalloc(sizeof(*filter_item), GFP_KERNEL);
if (!filter_item)
goto fail_mem;
list_add_tail(&filter_item->list, &filter_list);
/*
* Regardless of if this returned an error, we still
* replace the filter for the call.
*/
filter_item->filter = event_filter(file);
event_set_filter(file, filter);
filter = NULL;
fail = false;
}
if (fail)
goto fail;
/*
* The calls can still be using the old filters.
* Do a synchronize_sched() to ensure all calls are
* done with them before we free them.
*/
synchronize_sched();
list_for_each_entry_safe(filter_item, tmp, &filter_list, list) {
__free_filter(filter_item->filter);
list_del(&filter_item->list);
kfree(filter_item);
}
return 0;
fail:
/* No call succeeded */
list_for_each_entry_safe(filter_item, tmp, &filter_list, list) {
list_del(&filter_item->list);
kfree(filter_item);
}
parse_error(pe, FILT_ERR_BAD_SUBSYS_FILTER, 0);
return -EINVAL;
fail_mem:
kfree(filter);
/* If any call succeeded, we still need to sync */
if (!fail)
synchronize_sched();
list_for_each_entry_safe(filter_item, tmp, &filter_list, list) {
__free_filter(filter_item->filter);
list_del(&filter_item->list);
kfree(filter_item);
}
return -ENOMEM;
}
static int create_filter_start(char *filter_string, bool set_str,
struct filter_parse_error **pse,
struct event_filter **filterp)
{
struct event_filter *filter;
struct filter_parse_error *pe = NULL;
int err = 0;
if (WARN_ON_ONCE(*pse || *filterp))
return -EINVAL;
filter = kzalloc(sizeof(*filter), GFP_KERNEL);
if (filter && set_str) {
filter->filter_string = kstrdup(filter_string, GFP_KERNEL);
if (!filter->filter_string)
err = -ENOMEM;
}
pe = kzalloc(sizeof(*pe), GFP_KERNEL);
if (!filter || !pe || err) {
kfree(pe);
__free_filter(filter);
return -ENOMEM;
}
/* we're committed to creating a new filter */
*filterp = filter;
*pse = pe;
return 0;
}
static void create_filter_finish(struct filter_parse_error *pe)
{
kfree(pe);
}
/**
* create_filter - create a filter for a trace_event_call
* @call: trace_event_call to create a filter for
* @filter_str: filter string
* @set_str: remember @filter_str and enable detailed error in filter
* @filterp: out param for created filter (always updated on return)
*
* Creates a filter for @call with @filter_str. If @set_str is %true,
* @filter_str is copied and recorded in the new filter.
*
* On success, returns 0 and *@filterp points to the new filter. On
* failure, returns -errno and *@filterp may point to %NULL or to a new
* filter. In the latter case, the returned filter contains error
* information if @set_str is %true and the caller is responsible for
* freeing it.
*/
static int create_filter(struct trace_event_call *call,
char *filter_string, bool set_str,
struct event_filter **filterp)
{
struct filter_parse_error *pe = NULL;
int err;
err = create_filter_start(filter_string, set_str, &pe, filterp);
if (err)
return err;
err = process_preds(call, filter_string, *filterp, pe);
if (err && set_str)
append_filter_err(pe, *filterp);
return err;
}
int create_event_filter(struct trace_event_call *call,
char *filter_str, bool set_str,
struct event_filter **filterp)
{
return create_filter(call, filter_str, set_str, filterp);
}
/**
* create_system_filter - create a filter for an event_subsystem
* @system: event_subsystem to create a filter for
* @filter_str: filter string
* @filterp: out param for created filter (always updated on return)
*
* Identical to create_filter() except that it creates a subsystem filter
* and always remembers @filter_str.
*/
static int create_system_filter(struct trace_subsystem_dir *dir,
struct trace_array *tr,
char *filter_str, struct event_filter **filterp)
{
struct filter_parse_error *pe = NULL;
int err;
err = create_filter_start(filter_str, true, &pe, filterp);
if (!err) {
err = process_system_preds(dir, tr, pe, filter_str);
if (!err) {
/* System filters just show a default message */
kfree((*filterp)->filter_string);
(*filterp)->filter_string = NULL;
} else {
append_filter_err(pe, *filterp);
}
}
create_filter_finish(pe);
return err;
}
/* caller must hold event_mutex */
int apply_event_filter(struct trace_event_file *file, char *filter_string)
{
struct trace_event_call *call = file->event_call;
struct event_filter *filter = NULL;
int err;
if (!strcmp(strstrip(filter_string), "0")) {
filter_disable(file);
filter = event_filter(file);
if (!filter)
return 0;
event_clear_filter(file);
/* Make sure the filter is not being used */
synchronize_sched();
__free_filter(filter);
return 0;
}
err = create_filter(call, filter_string, true, &filter);
/*
* Always swap the call filter with the new filter
* even if there was an error. If there was an error
* in the filter, we disable the filter and show the error
* string
*/
if (filter) {
struct event_filter *tmp;
tmp = event_filter(file);
if (!err)
event_set_filtered_flag(file);
else
filter_disable(file);
event_set_filter(file, filter);
if (tmp) {
/* Make sure the call is done with the filter */
synchronize_sched();
__free_filter(tmp);
}
}
return err;
}
int apply_subsystem_event_filter(struct trace_subsystem_dir *dir,
char *filter_string)
{
struct event_subsystem *system = dir->subsystem;
struct trace_array *tr = dir->tr;
struct event_filter *filter = NULL;
int err = 0;
mutex_lock(&event_mutex);
/* Make sure the system still has events */
if (!dir->nr_events) {
err = -ENODEV;
goto out_unlock;
}
if (!strcmp(strstrip(filter_string), "0")) {
filter_free_subsystem_preds(dir, tr);
remove_filter_string(system->filter);
filter = system->filter;
system->filter = NULL;
/* Ensure all filters are no longer used */
synchronize_sched();
filter_free_subsystem_filters(dir, tr);
__free_filter(filter);
goto out_unlock;
}
err = create_system_filter(dir, tr, filter_string, &filter);
if (filter) {
/*
* No event actually uses the system filter
* we can free it without synchronize_sched().
*/
__free_filter(system->filter);
system->filter = filter;
}
out_unlock:
mutex_unlock(&event_mutex);
return err;
}
#ifdef CONFIG_PERF_EVENTS
void ftrace_profile_free_filter(struct perf_event *event)
{
struct event_filter *filter = event->filter;
event->filter = NULL;
__free_filter(filter);
}
struct function_filter_data {
struct ftrace_ops *ops;
int first_filter;
int first_notrace;
};
#ifdef CONFIG_FUNCTION_TRACER
static char **
ftrace_function_filter_re(char *buf, int len, int *count)
{
char *str, **re;
str = kstrndup(buf, len, GFP_KERNEL);
if (!str)
return NULL;
/*
* The argv_split function takes white space
* as a separator, so convert ',' into spaces.
*/
strreplace(str, ',', ' ');
re = argv_split(GFP_KERNEL, str, count);
kfree(str);
return re;
}
static int ftrace_function_set_regexp(struct ftrace_ops *ops, int filter,
int reset, char *re, int len)
{
int ret;
if (filter)
ret = ftrace_set_filter(ops, re, len, reset);
else
ret = ftrace_set_notrace(ops, re, len, reset);
return ret;
}
static int __ftrace_function_set_filter(int filter, char *buf, int len,
struct function_filter_data *data)
{
int i, re_cnt, ret = -EINVAL;
int *reset;
char **re;
reset = filter ? &data->first_filter : &data->first_notrace;
/*
* The 'ip' field could have multiple filters set, separated
* either by space or comma. We first cut the filter and apply
* all pieces separatelly.
*/
re = ftrace_function_filter_re(buf, len, &re_cnt);
if (!re)
return -EINVAL;
for (i = 0; i < re_cnt; i++) {
ret = ftrace_function_set_regexp(data->ops, filter, *reset,
re[i], strlen(re[i]));
if (ret)
break;
if (*reset)
*reset = 0;
}
argv_free(re);
return ret;
}
static int ftrace_function_check_pred(struct filter_pred *pred)
{
struct ftrace_event_field *field = pred->field;
/*
* Check the predicate for function trace, verify:
* - only '==' and '!=' is used
* - the 'ip' field is used
*/
if ((pred->op != OP_EQ) && (pred->op != OP_NE))
return -EINVAL;
if (strcmp(field->name, "ip"))
return -EINVAL;
return 0;
}
static int ftrace_function_set_filter_pred(struct filter_pred *pred,
struct function_filter_data *data)
{
int ret;
/* Checking the node is valid for function trace. */
ret = ftrace_function_check_pred(pred);
if (ret)
return ret;
return __ftrace_function_set_filter(pred->op == OP_EQ,
pred->regex.pattern,
pred->regex.len,
data);
}
static bool is_or(struct prog_entry *prog, int i)
{
int target;
/*
* Only "||" is allowed for function events, thus,
* all true branches should jump to true, and any
* false branch should jump to false.
*/
target = prog[i].target + 1;
/* True and false have NULL preds (all prog entries should jump to one */
if (prog[target].pred)
return false;
/* prog[target].target is 1 for TRUE, 0 for FALSE */
return prog[i].when_to_branch == prog[target].target;
}
static int ftrace_function_set_filter(struct perf_event *event,
struct event_filter *filter)
{
struct prog_entry *prog = rcu_dereference_protected(filter->prog,
lockdep_is_held(&event_mutex));
struct function_filter_data data = {
.first_filter = 1,
.first_notrace = 1,
.ops = &event->ftrace_ops,
};
int i;
for (i = 0; prog[i].pred; i++) {
struct filter_pred *pred = prog[i].pred;
if (!is_or(prog, i))
return -EINVAL;
if (ftrace_function_set_filter_pred(pred, &data) < 0)
return -EINVAL;
}
return 0;
}
#else
static int ftrace_function_set_filter(struct perf_event *event,
struct event_filter *filter)
{
return -ENODEV;
}
#endif /* CONFIG_FUNCTION_TRACER */
int ftrace_profile_set_filter(struct perf_event *event, int event_id,
char *filter_str)
{
int err;
struct event_filter *filter = NULL;
struct trace_event_call *call;
mutex_lock(&event_mutex);
call = event->tp_event;
err = -EINVAL;
if (!call)
goto out_unlock;
err = -EEXIST;
if (event->filter)
goto out_unlock;
err = create_filter(call, filter_str, false, &filter);
if (err)
goto free_filter;
if (ftrace_event_is_function(call))
err = ftrace_function_set_filter(event, filter);
else
event->filter = filter;
free_filter:
if (err || ftrace_event_is_function(call))
__free_filter(filter);
out_unlock:
mutex_unlock(&event_mutex);
return err;
}
#endif /* CONFIG_PERF_EVENTS */
#ifdef CONFIG_FTRACE_STARTUP_TEST
#include <linux/types.h>
#include <linux/tracepoint.h>
#define CREATE_TRACE_POINTS
#include "trace_events_filter_test.h"
#define DATA_REC(m, va, vb, vc, vd, ve, vf, vg, vh, nvisit) \
{ \
.filter = FILTER, \
.rec = { .a = va, .b = vb, .c = vc, .d = vd, \
.e = ve, .f = vf, .g = vg, .h = vh }, \
.match = m, \
.not_visited = nvisit, \
}
#define YES 1
#define NO 0
static struct test_filter_data_t {
char *filter;
struct trace_event_raw_ftrace_test_filter rec;
int match;
char *not_visited;
} test_filter_data[] = {
#define FILTER "a == 1 && b == 1 && c == 1 && d == 1 && " \
"e == 1 && f == 1 && g == 1 && h == 1"
DATA_REC(YES, 1, 1, 1, 1, 1, 1, 1, 1, ""),
DATA_REC(NO, 0, 1, 1, 1, 1, 1, 1, 1, "bcdefgh"),
DATA_REC(NO, 1, 1, 1, 1, 1, 1, 1, 0, ""),
#undef FILTER
#define FILTER "a == 1 || b == 1 || c == 1 || d == 1 || " \
"e == 1 || f == 1 || g == 1 || h == 1"
DATA_REC(NO, 0, 0, 0, 0, 0, 0, 0, 0, ""),
DATA_REC(YES, 0, 0, 0, 0, 0, 0, 0, 1, ""),
DATA_REC(YES, 1, 0, 0, 0, 0, 0, 0, 0, "bcdefgh"),
#undef FILTER
#define FILTER "(a == 1 || b == 1) && (c == 1 || d == 1) && " \
"(e == 1 || f == 1) && (g == 1 || h == 1)"
DATA_REC(NO, 0, 0, 1, 1, 1, 1, 1, 1, "dfh"),
DATA_REC(YES, 0, 1, 0, 1, 0, 1, 0, 1, ""),
DATA_REC(YES, 1, 0, 1, 0, 0, 1, 0, 1, "bd"),
DATA_REC(NO, 1, 0, 1, 0, 0, 1, 0, 0, "bd"),
#undef FILTER
#define FILTER "(a == 1 && b == 1) || (c == 1 && d == 1) || " \
"(e == 1 && f == 1) || (g == 1 && h == 1)"
DATA_REC(YES, 1, 0, 1, 1, 1, 1, 1, 1, "efgh"),
DATA_REC(YES, 0, 0, 0, 0, 0, 0, 1, 1, ""),
DATA_REC(NO, 0, 0, 0, 0, 0, 0, 0, 1, ""),
#undef FILTER
#define FILTER "(a == 1 && b == 1) && (c == 1 && d == 1) && " \
"(e == 1 && f == 1) || (g == 1 && h == 1)"
DATA_REC(YES, 1, 1, 1, 1, 1, 1, 0, 0, "gh"),
DATA_REC(NO, 0, 0, 0, 0, 0, 0, 0, 1, ""),
DATA_REC(YES, 1, 1, 1, 1, 1, 0, 1, 1, ""),
#undef FILTER
#define FILTER "((a == 1 || b == 1) || (c == 1 || d == 1) || " \
"(e == 1 || f == 1)) && (g == 1 || h == 1)"
DATA_REC(YES, 1, 1, 1, 1, 1, 1, 0, 1, "bcdef"),
DATA_REC(NO, 0, 0, 0, 0, 0, 0, 0, 0, ""),
DATA_REC(YES, 1, 1, 1, 1, 1, 0, 1, 1, "h"),
#undef FILTER
#define FILTER "((((((((a == 1) && (b == 1)) || (c == 1)) && (d == 1)) || " \
"(e == 1)) && (f == 1)) || (g == 1)) && (h == 1))"
DATA_REC(YES, 1, 1, 1, 1, 1, 1, 1, 1, "ceg"),
DATA_REC(NO, 0, 1, 0, 1, 0, 1, 0, 1, ""),
DATA_REC(NO, 1, 0, 1, 0, 1, 0, 1, 0, ""),
#undef FILTER
#define FILTER "((((((((a == 1) || (b == 1)) && (c == 1)) || (d == 1)) && " \
"(e == 1)) || (f == 1)) && (g == 1)) || (h == 1))"
DATA_REC(YES, 1, 1, 1, 1, 1, 1, 1, 1, "bdfh"),
DATA_REC(YES, 0, 1, 0, 1, 0, 1, 0, 1, ""),
DATA_REC(YES, 1, 0, 1, 0, 1, 0, 1, 0, "bdfh"),
};
#undef DATA_REC
#undef FILTER
#undef YES
#undef NO
#define DATA_CNT ARRAY_SIZE(test_filter_data)
static int test_pred_visited;
static int test_pred_visited_fn(struct filter_pred *pred, void *event)
{
struct ftrace_event_field *field = pred->field;
test_pred_visited = 1;
printk(KERN_INFO "\npred visited %s\n", field->name);
return 1;
}
static void update_pred_fn(struct event_filter *filter, char *fields)
{
struct prog_entry *prog = rcu_dereference_protected(filter->prog,
lockdep_is_held(&event_mutex));
int i;
for (i = 0; prog[i].pred; i++) {
struct filter_pred *pred = prog[i].pred;
struct ftrace_event_field *field = pred->field;
WARN_ON_ONCE(!pred->fn);
if (!field) {
WARN_ONCE(1, "all leafs should have field defined %d", i);
continue;
}
if (!strchr(fields, *field->name))
continue;
pred->fn = test_pred_visited_fn;
}
}
static __init int ftrace_test_event_filter(void)
{
int i;
printk(KERN_INFO "Testing ftrace filter: ");
for (i = 0; i < DATA_CNT; i++) {
struct event_filter *filter = NULL;
struct test_filter_data_t *d = &test_filter_data[i];
int err;
err = create_filter(&event_ftrace_test_filter, d->filter,
false, &filter);
if (err) {
printk(KERN_INFO
"Failed to get filter for '%s', err %d\n",
d->filter, err);
__free_filter(filter);
break;
}
/* Needed to dereference filter->prog */
mutex_lock(&event_mutex);
/*
* The preemption disabling is not really needed for self
* tests, but the rcu dereference will complain without it.
*/
preempt_disable();
if (*d->not_visited)
update_pred_fn(filter, d->not_visited);
test_pred_visited = 0;
err = filter_match_preds(filter, &d->rec);
preempt_enable();
mutex_unlock(&event_mutex);
__free_filter(filter);
if (test_pred_visited) {
printk(KERN_INFO
"Failed, unwanted pred visited for filter %s\n",
d->filter);
break;
}
if (err != d->match) {
printk(KERN_INFO
"Failed to match filter '%s', expected %d\n",
d->filter, d->match);
break;
}
}
if (i == DATA_CNT)
printk(KERN_CONT "OK\n");
return 0;
}
late_initcall(ftrace_test_event_filter);
#endif /* CONFIG_FTRACE_STARTUP_TEST */
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_205_3 |
crossvul-cpp_data_good_5257_0 | /*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| 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. |
+----------------------------------------------------------------------+
| Authors: Rasmus Lerdorf <rasmus@php.net> |
| Stig Bakken <ssb@php.net> |
| Jim Winstead <jimw@php.net> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
/* gd 1.2 is copyright 1994, 1995, Quest Protein Database Center,
Cold Spring Harbor Labs. */
/* Note that there is no code from the gd package in this file */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "php_ini.h"
#include "ext/standard/head.h"
#include <math.h>
#include "SAPI.h"
#include "php_gd.h"
#include "ext/standard/info.h"
#include "php_open_temporary_file.h"
#if HAVE_SYS_WAIT_H
# include <sys/wait.h>
#endif
#if HAVE_UNISTD_H
# include <unistd.h>
#endif
#ifdef PHP_WIN32
# include <io.h>
# include <fcntl.h>
# include <windows.h>
# include <Winuser.h>
# include <Wingdi.h>
#endif
#ifdef HAVE_GD_XPM
# include <X11/xpm.h>
#endif
# include "gd_compat.h"
static int le_gd, le_gd_font;
#if HAVE_LIBT1
#include <t1lib.h>
static int le_ps_font, le_ps_enc;
static void php_free_ps_font(zend_rsrc_list_entry *rsrc TSRMLS_DC);
static void php_free_ps_enc(zend_rsrc_list_entry *rsrc TSRMLS_DC);
#endif
#include <gd.h>
#ifndef HAVE_GD_BUNDLED
# include <gd_errors.h>
#endif
#include <gdfontt.h> /* 1 Tiny font */
#include <gdfonts.h> /* 2 Small font */
#include <gdfontmb.h> /* 3 Medium bold font */
#include <gdfontl.h> /* 4 Large font */
#include <gdfontg.h> /* 5 Giant font */
#ifdef ENABLE_GD_TTF
# ifdef HAVE_LIBFREETYPE
# include <ft2build.h>
# include FT_FREETYPE_H
# endif
#endif
#if defined(HAVE_GD_XPM) && defined(HAVE_GD_BUNDLED)
# include "X11/xpm.h"
#endif
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#ifdef ENABLE_GD_TTF
static void php_imagettftext_common(INTERNAL_FUNCTION_PARAMETERS, int, int);
#endif
#include "gd_ctx.c"
/* as it is not really public, duplicate declaration here to avoid
pointless warnings */
int overflow2(int a, int b);
/* Section Filters Declarations */
/* IMPORTANT NOTE FOR NEW FILTER
* Do not forget to update:
* IMAGE_FILTER_MAX: define the last filter index
* IMAGE_FILTER_MAX_ARGS: define the biggest amount of arguments
* image_filter array in PHP_FUNCTION(imagefilter)
* */
#define IMAGE_FILTER_NEGATE 0
#define IMAGE_FILTER_GRAYSCALE 1
#define IMAGE_FILTER_BRIGHTNESS 2
#define IMAGE_FILTER_CONTRAST 3
#define IMAGE_FILTER_COLORIZE 4
#define IMAGE_FILTER_EDGEDETECT 5
#define IMAGE_FILTER_EMBOSS 6
#define IMAGE_FILTER_GAUSSIAN_BLUR 7
#define IMAGE_FILTER_SELECTIVE_BLUR 8
#define IMAGE_FILTER_MEAN_REMOVAL 9
#define IMAGE_FILTER_SMOOTH 10
#define IMAGE_FILTER_PIXELATE 11
#define IMAGE_FILTER_MAX 11
#define IMAGE_FILTER_MAX_ARGS 6
static void php_image_filter_negate(INTERNAL_FUNCTION_PARAMETERS);
static void php_image_filter_grayscale(INTERNAL_FUNCTION_PARAMETERS);
static void php_image_filter_brightness(INTERNAL_FUNCTION_PARAMETERS);
static void php_image_filter_contrast(INTERNAL_FUNCTION_PARAMETERS);
static void php_image_filter_colorize(INTERNAL_FUNCTION_PARAMETERS);
static void php_image_filter_edgedetect(INTERNAL_FUNCTION_PARAMETERS);
static void php_image_filter_emboss(INTERNAL_FUNCTION_PARAMETERS);
static void php_image_filter_gaussian_blur(INTERNAL_FUNCTION_PARAMETERS);
static void php_image_filter_selective_blur(INTERNAL_FUNCTION_PARAMETERS);
static void php_image_filter_mean_removal(INTERNAL_FUNCTION_PARAMETERS);
static void php_image_filter_smooth(INTERNAL_FUNCTION_PARAMETERS);
static void php_image_filter_pixelate(INTERNAL_FUNCTION_PARAMETERS);
/* End Section filters declarations */
static gdImagePtr _php_image_create_from_string (zval **Data, char *tn, gdImagePtr (*ioctx_func_p)() TSRMLS_DC);
static void _php_image_create_from(INTERNAL_FUNCTION_PARAMETERS, int image_type, char *tn, gdImagePtr (*func_p)(), gdImagePtr (*ioctx_func_p)());
static void _php_image_output(INTERNAL_FUNCTION_PARAMETERS, int image_type, char *tn, void (*func_p)());
static int _php_image_type(char data[8]);
static void _php_image_convert(INTERNAL_FUNCTION_PARAMETERS, int image_type);
static void _php_image_bw_convert(gdImagePtr im_org, gdIOCtx *out, int threshold);
/* {{{ arginfo */
ZEND_BEGIN_ARG_INFO(arginfo_gd_info, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imageloadfont, 0)
ZEND_ARG_INFO(0, filename)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagesetstyle, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, styles) /* ARRAY_INFO(0, styles, 0) */
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagecreatetruecolor, 0)
ZEND_ARG_INFO(0, x_size)
ZEND_ARG_INFO(0, y_size)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imageistruecolor, 0)
ZEND_ARG_INFO(0, im)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagetruecolortopalette, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, ditherFlag)
ZEND_ARG_INFO(0, colorsWanted)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagepalettetotruecolor, 0)
ZEND_ARG_INFO(0, im)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagecolormatch, 0)
ZEND_ARG_INFO(0, im1)
ZEND_ARG_INFO(0, im2)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagesetthickness, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, thickness)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagefilledellipse, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, cx)
ZEND_ARG_INFO(0, cy)
ZEND_ARG_INFO(0, w)
ZEND_ARG_INFO(0, h)
ZEND_ARG_INFO(0, color)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagefilledarc, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, cx)
ZEND_ARG_INFO(0, cy)
ZEND_ARG_INFO(0, w)
ZEND_ARG_INFO(0, h)
ZEND_ARG_INFO(0, s)
ZEND_ARG_INFO(0, e)
ZEND_ARG_INFO(0, col)
ZEND_ARG_INFO(0, style)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagealphablending, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, blend)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagesavealpha, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, save)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagelayereffect, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, effect)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagecolorallocatealpha, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, red)
ZEND_ARG_INFO(0, green)
ZEND_ARG_INFO(0, blue)
ZEND_ARG_INFO(0, alpha)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagecolorresolvealpha, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, red)
ZEND_ARG_INFO(0, green)
ZEND_ARG_INFO(0, blue)
ZEND_ARG_INFO(0, alpha)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagecolorclosestalpha, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, red)
ZEND_ARG_INFO(0, green)
ZEND_ARG_INFO(0, blue)
ZEND_ARG_INFO(0, alpha)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagecolorexactalpha, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, red)
ZEND_ARG_INFO(0, green)
ZEND_ARG_INFO(0, blue)
ZEND_ARG_INFO(0, alpha)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagecopyresampled, 0)
ZEND_ARG_INFO(0, dst_im)
ZEND_ARG_INFO(0, src_im)
ZEND_ARG_INFO(0, dst_x)
ZEND_ARG_INFO(0, dst_y)
ZEND_ARG_INFO(0, src_x)
ZEND_ARG_INFO(0, src_y)
ZEND_ARG_INFO(0, dst_w)
ZEND_ARG_INFO(0, dst_h)
ZEND_ARG_INFO(0, src_w)
ZEND_ARG_INFO(0, src_h)
ZEND_END_ARG_INFO()
#ifdef PHP_WIN32
ZEND_BEGIN_ARG_INFO_EX(arginfo_imagegrabwindow, 0, 0, 1)
ZEND_ARG_INFO(0, handle)
ZEND_ARG_INFO(0, client_area)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagegrabscreen, 0)
ZEND_END_ARG_INFO()
#endif
ZEND_BEGIN_ARG_INFO_EX(arginfo_imagerotate, 0, 0, 3)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, angle)
ZEND_ARG_INFO(0, bgdcolor)
ZEND_ARG_INFO(0, ignoretransparent)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagesettile, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, tile)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagesetbrush, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, brush)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagecreate, 0)
ZEND_ARG_INFO(0, x_size)
ZEND_ARG_INFO(0, y_size)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagetypes, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromstring, 0)
ZEND_ARG_INFO(0, image)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromgif, 0)
ZEND_ARG_INFO(0, filename)
ZEND_END_ARG_INFO()
#ifdef HAVE_GD_JPG
ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromjpeg, 0)
ZEND_ARG_INFO(0, filename)
ZEND_END_ARG_INFO()
#endif
#ifdef HAVE_GD_PNG
ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefrompng, 0)
ZEND_ARG_INFO(0, filename)
ZEND_END_ARG_INFO()
#endif
#ifdef HAVE_GD_WEBP
ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromwebp, 0)
ZEND_ARG_INFO(0, filename)
ZEND_END_ARG_INFO()
#endif
ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromxbm, 0)
ZEND_ARG_INFO(0, filename)
ZEND_END_ARG_INFO()
#if defined(HAVE_GD_XPM)
ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromxpm, 0)
ZEND_ARG_INFO(0, filename)
ZEND_END_ARG_INFO()
#endif
ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromwbmp, 0)
ZEND_ARG_INFO(0, filename)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromgd, 0)
ZEND_ARG_INFO(0, filename)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromgd2, 0)
ZEND_ARG_INFO(0, filename)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromgd2part, 0)
ZEND_ARG_INFO(0, filename)
ZEND_ARG_INFO(0, srcX)
ZEND_ARG_INFO(0, srcY)
ZEND_ARG_INFO(0, width)
ZEND_ARG_INFO(0, height)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_imagexbm, 0, 0, 2)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, filename)
ZEND_ARG_INFO(0, foreground)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_imagegif, 0, 0, 1)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, filename)
ZEND_END_ARG_INFO()
#ifdef HAVE_GD_PNG
ZEND_BEGIN_ARG_INFO_EX(arginfo_imagepng, 0, 0, 1)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, filename)
ZEND_END_ARG_INFO()
#endif
#ifdef HAVE_GD_WEBP
ZEND_BEGIN_ARG_INFO_EX(arginfo_imagewebp, 0, 0, 1)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, filename)
ZEND_END_ARG_INFO()
#endif
#ifdef HAVE_GD_JPG
ZEND_BEGIN_ARG_INFO_EX(arginfo_imagejpeg, 0, 0, 1)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, filename)
ZEND_ARG_INFO(0, quality)
ZEND_END_ARG_INFO()
#endif
ZEND_BEGIN_ARG_INFO_EX(arginfo_imagewbmp, 0, 0, 1)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, filename)
ZEND_ARG_INFO(0, foreground)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_imagegd, 0, 0, 1)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, filename)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_imagegd2, 0, 0, 1)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, filename)
ZEND_ARG_INFO(0, chunk_size)
ZEND_ARG_INFO(0, type)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagedestroy, 0)
ZEND_ARG_INFO(0, im)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagecolorallocate, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, red)
ZEND_ARG_INFO(0, green)
ZEND_ARG_INFO(0, blue)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagepalettecopy, 0)
ZEND_ARG_INFO(0, dst)
ZEND_ARG_INFO(0, src)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagecolorat, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, x)
ZEND_ARG_INFO(0, y)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagecolorclosest, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, red)
ZEND_ARG_INFO(0, green)
ZEND_ARG_INFO(0, blue)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagecolorclosesthwb, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, red)
ZEND_ARG_INFO(0, green)
ZEND_ARG_INFO(0, blue)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagecolordeallocate, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, index)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagecolorresolve, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, red)
ZEND_ARG_INFO(0, green)
ZEND_ARG_INFO(0, blue)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagecolorexact, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, red)
ZEND_ARG_INFO(0, green)
ZEND_ARG_INFO(0, blue)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_imagecolorset, 0, 0, 5)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, color)
ZEND_ARG_INFO(0, red)
ZEND_ARG_INFO(0, green)
ZEND_ARG_INFO(0, blue)
ZEND_ARG_INFO(0, alpha)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagecolorsforindex, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, index)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagegammacorrect, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, inputgamma)
ZEND_ARG_INFO(0, outputgamma)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagesetpixel, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, x)
ZEND_ARG_INFO(0, y)
ZEND_ARG_INFO(0, col)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imageline, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, x1)
ZEND_ARG_INFO(0, y1)
ZEND_ARG_INFO(0, x2)
ZEND_ARG_INFO(0, y2)
ZEND_ARG_INFO(0, col)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagedashedline, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, x1)
ZEND_ARG_INFO(0, y1)
ZEND_ARG_INFO(0, x2)
ZEND_ARG_INFO(0, y2)
ZEND_ARG_INFO(0, col)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagerectangle, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, x1)
ZEND_ARG_INFO(0, y1)
ZEND_ARG_INFO(0, x2)
ZEND_ARG_INFO(0, y2)
ZEND_ARG_INFO(0, col)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagefilledrectangle, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, x1)
ZEND_ARG_INFO(0, y1)
ZEND_ARG_INFO(0, x2)
ZEND_ARG_INFO(0, y2)
ZEND_ARG_INFO(0, col)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagearc, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, cx)
ZEND_ARG_INFO(0, cy)
ZEND_ARG_INFO(0, w)
ZEND_ARG_INFO(0, h)
ZEND_ARG_INFO(0, s)
ZEND_ARG_INFO(0, e)
ZEND_ARG_INFO(0, col)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imageellipse, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, cx)
ZEND_ARG_INFO(0, cy)
ZEND_ARG_INFO(0, w)
ZEND_ARG_INFO(0, h)
ZEND_ARG_INFO(0, color)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagefilltoborder, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, x)
ZEND_ARG_INFO(0, y)
ZEND_ARG_INFO(0, border)
ZEND_ARG_INFO(0, col)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagefill, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, x)
ZEND_ARG_INFO(0, y)
ZEND_ARG_INFO(0, col)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagecolorstotal, 0)
ZEND_ARG_INFO(0, im)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_imagecolortransparent, 0, 0, 1)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, col)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_imageinterlace, 0, 0, 1)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, interlace)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagepolygon, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, points) /* ARRAY_INFO(0, points, 0) */
ZEND_ARG_INFO(0, num_pos)
ZEND_ARG_INFO(0, col)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagefilledpolygon, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, points) /* ARRAY_INFO(0, points, 0) */
ZEND_ARG_INFO(0, num_pos)
ZEND_ARG_INFO(0, col)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagefontwidth, 0)
ZEND_ARG_INFO(0, font)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagefontheight, 0)
ZEND_ARG_INFO(0, font)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagechar, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, font)
ZEND_ARG_INFO(0, x)
ZEND_ARG_INFO(0, y)
ZEND_ARG_INFO(0, c)
ZEND_ARG_INFO(0, col)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagecharup, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, font)
ZEND_ARG_INFO(0, x)
ZEND_ARG_INFO(0, y)
ZEND_ARG_INFO(0, c)
ZEND_ARG_INFO(0, col)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagestring, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, font)
ZEND_ARG_INFO(0, x)
ZEND_ARG_INFO(0, y)
ZEND_ARG_INFO(0, str)
ZEND_ARG_INFO(0, col)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagestringup, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, font)
ZEND_ARG_INFO(0, x)
ZEND_ARG_INFO(0, y)
ZEND_ARG_INFO(0, str)
ZEND_ARG_INFO(0, col)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagecopy, 0)
ZEND_ARG_INFO(0, dst_im)
ZEND_ARG_INFO(0, src_im)
ZEND_ARG_INFO(0, dst_x)
ZEND_ARG_INFO(0, dst_y)
ZEND_ARG_INFO(0, src_x)
ZEND_ARG_INFO(0, src_y)
ZEND_ARG_INFO(0, src_w)
ZEND_ARG_INFO(0, src_h)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagecopymerge, 0)
ZEND_ARG_INFO(0, src_im)
ZEND_ARG_INFO(0, dst_im)
ZEND_ARG_INFO(0, dst_x)
ZEND_ARG_INFO(0, dst_y)
ZEND_ARG_INFO(0, src_x)
ZEND_ARG_INFO(0, src_y)
ZEND_ARG_INFO(0, src_w)
ZEND_ARG_INFO(0, src_h)
ZEND_ARG_INFO(0, pct)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagecopymergegray, 0)
ZEND_ARG_INFO(0, src_im)
ZEND_ARG_INFO(0, dst_im)
ZEND_ARG_INFO(0, dst_x)
ZEND_ARG_INFO(0, dst_y)
ZEND_ARG_INFO(0, src_x)
ZEND_ARG_INFO(0, src_y)
ZEND_ARG_INFO(0, src_w)
ZEND_ARG_INFO(0, src_h)
ZEND_ARG_INFO(0, pct)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagecopyresized, 0)
ZEND_ARG_INFO(0, dst_im)
ZEND_ARG_INFO(0, src_im)
ZEND_ARG_INFO(0, dst_x)
ZEND_ARG_INFO(0, dst_y)
ZEND_ARG_INFO(0, src_x)
ZEND_ARG_INFO(0, src_y)
ZEND_ARG_INFO(0, dst_w)
ZEND_ARG_INFO(0, dst_h)
ZEND_ARG_INFO(0, src_w)
ZEND_ARG_INFO(0, src_h)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagesx, 0)
ZEND_ARG_INFO(0, im)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagesy, 0)
ZEND_ARG_INFO(0, im)
ZEND_END_ARG_INFO()
#ifdef ENABLE_GD_TTF
#if HAVE_LIBFREETYPE
ZEND_BEGIN_ARG_INFO_EX(arginfo_imageftbbox, 0, 0, 4)
ZEND_ARG_INFO(0, size)
ZEND_ARG_INFO(0, angle)
ZEND_ARG_INFO(0, font_file)
ZEND_ARG_INFO(0, text)
ZEND_ARG_INFO(0, extrainfo) /* ARRAY_INFO(0, extrainfo, 0) */
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_imagefttext, 0, 0, 8)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, size)
ZEND_ARG_INFO(0, angle)
ZEND_ARG_INFO(0, x)
ZEND_ARG_INFO(0, y)
ZEND_ARG_INFO(0, col)
ZEND_ARG_INFO(0, font_file)
ZEND_ARG_INFO(0, text)
ZEND_ARG_INFO(0, extrainfo) /* ARRAY_INFO(0, extrainfo, 0) */
ZEND_END_ARG_INFO()
#endif
ZEND_BEGIN_ARG_INFO(arginfo_imagettfbbox, 0)
ZEND_ARG_INFO(0, size)
ZEND_ARG_INFO(0, angle)
ZEND_ARG_INFO(0, font_file)
ZEND_ARG_INFO(0, text)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagettftext, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, size)
ZEND_ARG_INFO(0, angle)
ZEND_ARG_INFO(0, x)
ZEND_ARG_INFO(0, y)
ZEND_ARG_INFO(0, col)
ZEND_ARG_INFO(0, font_file)
ZEND_ARG_INFO(0, text)
ZEND_END_ARG_INFO()
#endif
#ifdef HAVE_LIBT1
ZEND_BEGIN_ARG_INFO(arginfo_imagepsloadfont, 0)
ZEND_ARG_INFO(0, pathname)
ZEND_END_ARG_INFO()
/*
ZEND_BEGIN_ARG_INFO(arginfo_imagepscopyfont, 0)
ZEND_ARG_INFO(0, font_index)
ZEND_END_ARG_INFO()
*/
ZEND_BEGIN_ARG_INFO(arginfo_imagepsfreefont, 0)
ZEND_ARG_INFO(0, font_index)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagepsencodefont, 0)
ZEND_ARG_INFO(0, font_index)
ZEND_ARG_INFO(0, filename)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagepsextendfont, 0)
ZEND_ARG_INFO(0, font_index)
ZEND_ARG_INFO(0, extend)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagepsslantfont, 0)
ZEND_ARG_INFO(0, font_index)
ZEND_ARG_INFO(0, slant)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_imagepstext, 0, 0, 8)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, text)
ZEND_ARG_INFO(0, font)
ZEND_ARG_INFO(0, size)
ZEND_ARG_INFO(0, foreground)
ZEND_ARG_INFO(0, background)
ZEND_ARG_INFO(0, xcoord)
ZEND_ARG_INFO(0, ycoord)
ZEND_ARG_INFO(0, space)
ZEND_ARG_INFO(0, tightness)
ZEND_ARG_INFO(0, angle)
ZEND_ARG_INFO(0, antialias)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_imagepsbbox, 0, 0, 3)
ZEND_ARG_INFO(0, text)
ZEND_ARG_INFO(0, font)
ZEND_ARG_INFO(0, size)
ZEND_ARG_INFO(0, space)
ZEND_ARG_INFO(0, tightness)
ZEND_ARG_INFO(0, angle)
ZEND_END_ARG_INFO()
#endif
ZEND_BEGIN_ARG_INFO_EX(arginfo_image2wbmp, 0, 0, 1)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, filename)
ZEND_ARG_INFO(0, threshold)
ZEND_END_ARG_INFO()
#if defined(HAVE_GD_JPG)
ZEND_BEGIN_ARG_INFO(arginfo_jpeg2wbmp, 0)
ZEND_ARG_INFO(0, f_org)
ZEND_ARG_INFO(0, f_dest)
ZEND_ARG_INFO(0, d_height)
ZEND_ARG_INFO(0, d_width)
ZEND_ARG_INFO(0, d_threshold)
ZEND_END_ARG_INFO()
#endif
#if defined(HAVE_GD_PNG)
ZEND_BEGIN_ARG_INFO(arginfo_png2wbmp, 0)
ZEND_ARG_INFO(0, f_org)
ZEND_ARG_INFO(0, f_dest)
ZEND_ARG_INFO(0, d_height)
ZEND_ARG_INFO(0, d_width)
ZEND_ARG_INFO(0, d_threshold)
ZEND_END_ARG_INFO()
#endif
ZEND_BEGIN_ARG_INFO_EX(arginfo_imagefilter, 0, 0, 2)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, filtertype)
ZEND_ARG_INFO(0, arg1)
ZEND_ARG_INFO(0, arg2)
ZEND_ARG_INFO(0, arg3)
ZEND_ARG_INFO(0, arg4)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imageconvolution, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, matrix3x3) /* ARRAY_INFO(0, matrix3x3, 0) */
ZEND_ARG_INFO(0, div)
ZEND_ARG_INFO(0, offset)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imageflip, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, mode)
ZEND_END_ARG_INFO()
#ifdef HAVE_GD_BUNDLED
ZEND_BEGIN_ARG_INFO(arginfo_imageantialias, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, on)
ZEND_END_ARG_INFO()
#endif
ZEND_BEGIN_ARG_INFO(arginfo_imagecrop, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, rect)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_imagecropauto, 0, 0, 1)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, mode)
ZEND_ARG_INFO(0, threshold)
ZEND_ARG_INFO(0, color)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_imagescale, 0, 0, 2)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, new_width)
ZEND_ARG_INFO(0, new_height)
ZEND_ARG_INFO(0, mode)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_imageaffine, 0, 0, 2)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, affine)
ZEND_ARG_INFO(0, clip)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_imageaffinematrixget, 0, 0, 1)
ZEND_ARG_INFO(0, type)
ZEND_ARG_INFO(0, options)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imageaffinematrixconcat, 0)
ZEND_ARG_INFO(0, m1)
ZEND_ARG_INFO(0, m2)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_imagesetinterpolation, 0)
ZEND_ARG_INFO(0, im)
ZEND_ARG_INFO(0, method)
ZEND_END_ARG_INFO()
/* }}} */
/* {{{ gd_functions[]
*/
const zend_function_entry gd_functions[] = {
PHP_FE(gd_info, arginfo_gd_info)
PHP_FE(imagearc, arginfo_imagearc)
PHP_FE(imageellipse, arginfo_imageellipse)
PHP_FE(imagechar, arginfo_imagechar)
PHP_FE(imagecharup, arginfo_imagecharup)
PHP_FE(imagecolorat, arginfo_imagecolorat)
PHP_FE(imagecolorallocate, arginfo_imagecolorallocate)
PHP_FE(imagepalettecopy, arginfo_imagepalettecopy)
PHP_FE(imagecreatefromstring, arginfo_imagecreatefromstring)
PHP_FE(imagecolorclosest, arginfo_imagecolorclosest)
PHP_FE(imagecolorclosesthwb, arginfo_imagecolorclosesthwb)
PHP_FE(imagecolordeallocate, arginfo_imagecolordeallocate)
PHP_FE(imagecolorresolve, arginfo_imagecolorresolve)
PHP_FE(imagecolorexact, arginfo_imagecolorexact)
PHP_FE(imagecolorset, arginfo_imagecolorset)
PHP_FE(imagecolortransparent, arginfo_imagecolortransparent)
PHP_FE(imagecolorstotal, arginfo_imagecolorstotal)
PHP_FE(imagecolorsforindex, arginfo_imagecolorsforindex)
PHP_FE(imagecopy, arginfo_imagecopy)
PHP_FE(imagecopymerge, arginfo_imagecopymerge)
PHP_FE(imagecopymergegray, arginfo_imagecopymergegray)
PHP_FE(imagecopyresized, arginfo_imagecopyresized)
PHP_FE(imagecreate, arginfo_imagecreate)
PHP_FE(imagecreatetruecolor, arginfo_imagecreatetruecolor)
PHP_FE(imageistruecolor, arginfo_imageistruecolor)
PHP_FE(imagetruecolortopalette, arginfo_imagetruecolortopalette)
PHP_FE(imagepalettetotruecolor, arginfo_imagepalettetotruecolor)
PHP_FE(imagesetthickness, arginfo_imagesetthickness)
PHP_FE(imagefilledarc, arginfo_imagefilledarc)
PHP_FE(imagefilledellipse, arginfo_imagefilledellipse)
PHP_FE(imagealphablending, arginfo_imagealphablending)
PHP_FE(imagesavealpha, arginfo_imagesavealpha)
PHP_FE(imagecolorallocatealpha, arginfo_imagecolorallocatealpha)
PHP_FE(imagecolorresolvealpha, arginfo_imagecolorresolvealpha)
PHP_FE(imagecolorclosestalpha, arginfo_imagecolorclosestalpha)
PHP_FE(imagecolorexactalpha, arginfo_imagecolorexactalpha)
PHP_FE(imagecopyresampled, arginfo_imagecopyresampled)
#ifdef PHP_WIN32
PHP_FE(imagegrabwindow, arginfo_imagegrabwindow)
PHP_FE(imagegrabscreen, arginfo_imagegrabscreen)
#endif
PHP_FE(imagerotate, arginfo_imagerotate)
PHP_FE(imageflip, arginfo_imageflip)
#ifdef HAVE_GD_BUNDLED
PHP_FE(imageantialias, arginfo_imageantialias)
#endif
PHP_FE(imagecrop, arginfo_imagecrop)
PHP_FE(imagecropauto, arginfo_imagecropauto)
PHP_FE(imagescale, arginfo_imagescale)
PHP_FE(imageaffine, arginfo_imageaffine)
PHP_FE(imageaffinematrixconcat, arginfo_imageaffinematrixconcat)
PHP_FE(imageaffinematrixget, arginfo_imageaffinematrixget)
PHP_FE(imagesetinterpolation, arginfo_imagesetinterpolation)
PHP_FE(imagesettile, arginfo_imagesettile)
PHP_FE(imagesetbrush, arginfo_imagesetbrush)
PHP_FE(imagesetstyle, arginfo_imagesetstyle)
#ifdef HAVE_GD_PNG
PHP_FE(imagecreatefrompng, arginfo_imagecreatefrompng)
#endif
#ifdef HAVE_GD_WEBP
PHP_FE(imagecreatefromwebp, arginfo_imagecreatefromwebp)
#endif
PHP_FE(imagecreatefromgif, arginfo_imagecreatefromgif)
#ifdef HAVE_GD_JPG
PHP_FE(imagecreatefromjpeg, arginfo_imagecreatefromjpeg)
#endif
PHP_FE(imagecreatefromwbmp, arginfo_imagecreatefromwbmp)
PHP_FE(imagecreatefromxbm, arginfo_imagecreatefromxbm)
#if defined(HAVE_GD_XPM)
PHP_FE(imagecreatefromxpm, arginfo_imagecreatefromxpm)
#endif
PHP_FE(imagecreatefromgd, arginfo_imagecreatefromgd)
PHP_FE(imagecreatefromgd2, arginfo_imagecreatefromgd2)
PHP_FE(imagecreatefromgd2part, arginfo_imagecreatefromgd2part)
#ifdef HAVE_GD_PNG
PHP_FE(imagepng, arginfo_imagepng)
#endif
#ifdef HAVE_GD_WEBP
PHP_FE(imagewebp, arginfo_imagewebp)
#endif
PHP_FE(imagegif, arginfo_imagegif)
#ifdef HAVE_GD_JPG
PHP_FE(imagejpeg, arginfo_imagejpeg)
#endif
PHP_FE(imagewbmp, arginfo_imagewbmp)
PHP_FE(imagegd, arginfo_imagegd)
PHP_FE(imagegd2, arginfo_imagegd2)
PHP_FE(imagedestroy, arginfo_imagedestroy)
PHP_FE(imagegammacorrect, arginfo_imagegammacorrect)
PHP_FE(imagefill, arginfo_imagefill)
PHP_FE(imagefilledpolygon, arginfo_imagefilledpolygon)
PHP_FE(imagefilledrectangle, arginfo_imagefilledrectangle)
PHP_FE(imagefilltoborder, arginfo_imagefilltoborder)
PHP_FE(imagefontwidth, arginfo_imagefontwidth)
PHP_FE(imagefontheight, arginfo_imagefontheight)
PHP_FE(imageinterlace, arginfo_imageinterlace)
PHP_FE(imageline, arginfo_imageline)
PHP_FE(imageloadfont, arginfo_imageloadfont)
PHP_FE(imagepolygon, arginfo_imagepolygon)
PHP_FE(imagerectangle, arginfo_imagerectangle)
PHP_FE(imagesetpixel, arginfo_imagesetpixel)
PHP_FE(imagestring, arginfo_imagestring)
PHP_FE(imagestringup, arginfo_imagestringup)
PHP_FE(imagesx, arginfo_imagesx)
PHP_FE(imagesy, arginfo_imagesy)
PHP_FE(imagedashedline, arginfo_imagedashedline)
#ifdef ENABLE_GD_TTF
PHP_FE(imagettfbbox, arginfo_imagettfbbox)
PHP_FE(imagettftext, arginfo_imagettftext)
#if HAVE_GD_FREETYPE && HAVE_LIBFREETYPE
PHP_FE(imageftbbox, arginfo_imageftbbox)
PHP_FE(imagefttext, arginfo_imagefttext)
#endif
#endif
#ifdef HAVE_LIBT1
PHP_FE(imagepsloadfont, arginfo_imagepsloadfont)
/*
PHP_FE(imagepscopyfont, arginfo_imagepscopyfont)
*/
PHP_FE(imagepsfreefont, arginfo_imagepsfreefont)
PHP_FE(imagepsencodefont, arginfo_imagepsencodefont)
PHP_FE(imagepsextendfont, arginfo_imagepsextendfont)
PHP_FE(imagepsslantfont, arginfo_imagepsslantfont)
PHP_FE(imagepstext, arginfo_imagepstext)
PHP_FE(imagepsbbox, arginfo_imagepsbbox)
#endif
PHP_FE(imagetypes, arginfo_imagetypes)
#if defined(HAVE_GD_JPG)
PHP_FE(jpeg2wbmp, arginfo_jpeg2wbmp)
#endif
#if defined(HAVE_GD_PNG)
PHP_FE(png2wbmp, arginfo_png2wbmp)
#endif
PHP_FE(image2wbmp, arginfo_image2wbmp)
PHP_FE(imagelayereffect, arginfo_imagelayereffect)
PHP_FE(imagexbm, arginfo_imagexbm)
PHP_FE(imagecolormatch, arginfo_imagecolormatch)
/* gd filters */
PHP_FE(imagefilter, arginfo_imagefilter)
PHP_FE(imageconvolution, arginfo_imageconvolution)
PHP_FE_END
};
/* }}} */
zend_module_entry gd_module_entry = {
STANDARD_MODULE_HEADER,
"gd",
gd_functions,
PHP_MINIT(gd),
#if HAVE_LIBT1
PHP_MSHUTDOWN(gd),
#else
NULL,
#endif
NULL,
#if HAVE_GD_FREETYPE && HAVE_LIBFREETYPE
PHP_RSHUTDOWN(gd),
#else
NULL,
#endif
PHP_MINFO(gd),
NO_VERSION_YET,
STANDARD_MODULE_PROPERTIES
};
#ifdef COMPILE_DL_GD
ZEND_GET_MODULE(gd)
#endif
/* {{{ PHP_INI_BEGIN */
PHP_INI_BEGIN()
PHP_INI_ENTRY("gd.jpeg_ignore_warning", "0", PHP_INI_ALL, NULL)
PHP_INI_END()
/* }}} */
/* {{{ php_free_gd_image
*/
static void php_free_gd_image(zend_rsrc_list_entry *rsrc TSRMLS_DC)
{
gdImageDestroy((gdImagePtr) rsrc->ptr);
}
/* }}} */
/* {{{ php_free_gd_font
*/
static void php_free_gd_font(zend_rsrc_list_entry *rsrc TSRMLS_DC)
{
gdFontPtr fp = (gdFontPtr) rsrc->ptr;
if (fp->data) {
efree(fp->data);
}
efree(fp);
}
/* }}} */
#ifndef HAVE_GD_BUNDLED
/* {{{ php_gd_error_method
*/
void php_gd_error_method(int type, const char *format, va_list args)
{
TSRMLS_FETCH();
switch (type) {
case GD_DEBUG:
case GD_INFO:
case GD_NOTICE:
type = E_NOTICE;
break;
case GD_WARNING:
type = E_WARNING;
break;
default:
type = E_ERROR;
}
php_verror(NULL, "", type, format, args TSRMLS_CC);
}
/* }}} */
#endif
/* {{{ PHP_MSHUTDOWN_FUNCTION
*/
#if HAVE_LIBT1
PHP_MSHUTDOWN_FUNCTION(gd)
{
T1_CloseLib();
#if HAVE_GD_BUNDLED && HAVE_LIBFREETYPE
gdFontCacheMutexShutdown();
#endif
UNREGISTER_INI_ENTRIES();
return SUCCESS;
}
#endif
/* }}} */
/* {{{ PHP_MINIT_FUNCTION
*/
PHP_MINIT_FUNCTION(gd)
{
le_gd = zend_register_list_destructors_ex(php_free_gd_image, NULL, "gd", module_number);
le_gd_font = zend_register_list_destructors_ex(php_free_gd_font, NULL, "gd font", module_number);
#if HAVE_GD_BUNDLED && HAVE_LIBFREETYPE
gdFontCacheMutexSetup();
#endif
#if HAVE_LIBT1
T1_SetBitmapPad(8);
T1_InitLib(NO_LOGFILE | IGNORE_CONFIGFILE | IGNORE_FONTDATABASE);
T1_SetLogLevel(T1LOG_DEBUG);
le_ps_font = zend_register_list_destructors_ex(php_free_ps_font, NULL, "gd PS font", module_number);
le_ps_enc = zend_register_list_destructors_ex(php_free_ps_enc, NULL, "gd PS encoding", module_number);
#endif
#ifndef HAVE_GD_BUNDLED
gdSetErrorMethod(php_gd_error_method);
#endif
REGISTER_INI_ENTRIES();
REGISTER_LONG_CONSTANT("IMG_GIF", 1, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_JPG", 2, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_JPEG", 2, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_PNG", 4, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_WBMP", 8, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_XPM", 16, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_WEBP", 32, CONST_CS | CONST_PERSISTENT);
/* special colours for gd */
REGISTER_LONG_CONSTANT("IMG_COLOR_TILED", gdTiled, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_COLOR_STYLED", gdStyled, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_COLOR_BRUSHED", gdBrushed, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_COLOR_STYLEDBRUSHED", gdStyledBrushed, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_COLOR_TRANSPARENT", gdTransparent, CONST_CS | CONST_PERSISTENT);
/* for imagefilledarc */
REGISTER_LONG_CONSTANT("IMG_ARC_ROUNDED", gdArc, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_ARC_PIE", gdPie, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_ARC_CHORD", gdChord, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_ARC_NOFILL", gdNoFill, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_ARC_EDGED", gdEdged, CONST_CS | CONST_PERSISTENT);
/* GD2 image format types */
REGISTER_LONG_CONSTANT("IMG_GD2_RAW", GD2_FMT_RAW, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_GD2_COMPRESSED", GD2_FMT_COMPRESSED, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FLIP_HORIZONTAL", GD_FLIP_HORINZONTAL, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FLIP_VERTICAL", GD_FLIP_VERTICAL, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FLIP_BOTH", GD_FLIP_BOTH, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_EFFECT_REPLACE", gdEffectReplace, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_EFFECT_ALPHABLEND", gdEffectAlphaBlend, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_EFFECT_NORMAL", gdEffectNormal, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_EFFECT_OVERLAY", gdEffectOverlay, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_CROP_DEFAULT", GD_CROP_DEFAULT, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_CROP_TRANSPARENT", GD_CROP_TRANSPARENT, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_CROP_BLACK", GD_CROP_BLACK, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_CROP_WHITE", GD_CROP_WHITE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_CROP_SIDES", GD_CROP_SIDES, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_CROP_THRESHOLD", GD_CROP_THRESHOLD, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_BELL", GD_BELL, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_BESSEL", GD_BESSEL, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_BILINEAR_FIXED", GD_BILINEAR_FIXED, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_BICUBIC", GD_BICUBIC, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_BICUBIC_FIXED", GD_BICUBIC_FIXED, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_BLACKMAN", GD_BLACKMAN, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_BOX", GD_BOX, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_BSPLINE", GD_BSPLINE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_CATMULLROM", GD_CATMULLROM, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_GAUSSIAN", GD_GAUSSIAN, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_GENERALIZED_CUBIC", GD_GENERALIZED_CUBIC, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_HERMITE", GD_HERMITE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_HAMMING", GD_HAMMING, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_HANNING", GD_HANNING, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_MITCHELL", GD_MITCHELL, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_POWER", GD_POWER, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_QUADRATIC", GD_QUADRATIC, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_SINC", GD_SINC, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_NEAREST_NEIGHBOUR", GD_NEAREST_NEIGHBOUR, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_WEIGHTED4", GD_WEIGHTED4, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_TRIANGLE", GD_TRIANGLE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_AFFINE_TRANSLATE", GD_AFFINE_TRANSLATE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_AFFINE_SCALE", GD_AFFINE_SCALE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_AFFINE_ROTATE", GD_AFFINE_ROTATE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_AFFINE_SHEAR_HORIZONTAL", GD_AFFINE_SHEAR_HORIZONTAL, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_AFFINE_SHEAR_VERTICAL", GD_AFFINE_SHEAR_VERTICAL, CONST_CS | CONST_PERSISTENT);
#if defined(HAVE_GD_BUNDLED)
REGISTER_LONG_CONSTANT("GD_BUNDLED", 1, CONST_CS | CONST_PERSISTENT);
#else
REGISTER_LONG_CONSTANT("GD_BUNDLED", 0, CONST_CS | CONST_PERSISTENT);
#endif
/* Section Filters */
REGISTER_LONG_CONSTANT("IMG_FILTER_NEGATE", IMAGE_FILTER_NEGATE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FILTER_GRAYSCALE", IMAGE_FILTER_GRAYSCALE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FILTER_BRIGHTNESS", IMAGE_FILTER_BRIGHTNESS, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FILTER_CONTRAST", IMAGE_FILTER_CONTRAST, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FILTER_COLORIZE", IMAGE_FILTER_COLORIZE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FILTER_EDGEDETECT", IMAGE_FILTER_EDGEDETECT, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FILTER_GAUSSIAN_BLUR", IMAGE_FILTER_GAUSSIAN_BLUR, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FILTER_SELECTIVE_BLUR", IMAGE_FILTER_SELECTIVE_BLUR, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FILTER_EMBOSS", IMAGE_FILTER_EMBOSS, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FILTER_MEAN_REMOVAL", IMAGE_FILTER_MEAN_REMOVAL, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FILTER_SMOOTH", IMAGE_FILTER_SMOOTH, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FILTER_PIXELATE", IMAGE_FILTER_PIXELATE, CONST_CS | CONST_PERSISTENT);
/* End Section Filters */
#ifdef GD_VERSION_STRING
REGISTER_STRING_CONSTANT("GD_VERSION", GD_VERSION_STRING, CONST_CS | CONST_PERSISTENT);
#endif
#if defined(GD_MAJOR_VERSION) && defined(GD_MINOR_VERSION) && defined(GD_RELEASE_VERSION) && defined(GD_EXTRA_VERSION)
REGISTER_LONG_CONSTANT("GD_MAJOR_VERSION", GD_MAJOR_VERSION, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("GD_MINOR_VERSION", GD_MINOR_VERSION, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("GD_RELEASE_VERSION", GD_RELEASE_VERSION, CONST_CS | CONST_PERSISTENT);
REGISTER_STRING_CONSTANT("GD_EXTRA_VERSION", GD_EXTRA_VERSION, CONST_CS | CONST_PERSISTENT);
#endif
#ifdef HAVE_GD_PNG
/*
* cannot include #include "png.h"
* /usr/include/pngconf.h:310:2: error: #error png.h already includes setjmp.h with some additional fixup.
* as error, use the values for now...
*/
REGISTER_LONG_CONSTANT("PNG_NO_FILTER", 0x00, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PNG_FILTER_NONE", 0x08, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PNG_FILTER_SUB", 0x10, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PNG_FILTER_UP", 0x20, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PNG_FILTER_AVG", 0x40, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PNG_FILTER_PAETH", 0x80, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PNG_ALL_FILTERS", 0x08 | 0x10 | 0x20 | 0x40 | 0x80, CONST_CS | CONST_PERSISTENT);
#endif
return SUCCESS;
}
/* }}} */
/* {{{ PHP_RSHUTDOWN_FUNCTION
*/
#if HAVE_GD_FREETYPE && HAVE_LIBFREETYPE
PHP_RSHUTDOWN_FUNCTION(gd)
{
gdFontCacheShutdown();
return SUCCESS;
}
#endif
/* }}} */
#if defined(HAVE_GD_BUNDLED)
#define PHP_GD_VERSION_STRING "bundled (2.1.0 compatible)"
#else
# define PHP_GD_VERSION_STRING GD_VERSION_STRING
#endif
/* {{{ PHP_MINFO_FUNCTION
*/
PHP_MINFO_FUNCTION(gd)
{
php_info_print_table_start();
php_info_print_table_row(2, "GD Support", "enabled");
/* need to use a PHPAPI function here because it is external module in windows */
#if defined(HAVE_GD_BUNDLED)
php_info_print_table_row(2, "GD Version", PHP_GD_VERSION_STRING);
#else
php_info_print_table_row(2, "GD headers Version", PHP_GD_VERSION_STRING);
#if defined(HAVE_GD_LIBVERSION)
php_info_print_table_row(2, "GD library Version", gdVersionString());
#endif
#endif
#ifdef ENABLE_GD_TTF
php_info_print_table_row(2, "FreeType Support", "enabled");
#if HAVE_LIBFREETYPE
php_info_print_table_row(2, "FreeType Linkage", "with freetype");
{
char tmp[256];
#ifdef FREETYPE_PATCH
snprintf(tmp, sizeof(tmp), "%d.%d.%d", FREETYPE_MAJOR, FREETYPE_MINOR, FREETYPE_PATCH);
#elif defined(FREETYPE_MAJOR)
snprintf(tmp, sizeof(tmp), "%d.%d", FREETYPE_MAJOR, FREETYPE_MINOR);
#else
snprintf(tmp, sizeof(tmp), "1.x");
#endif
php_info_print_table_row(2, "FreeType Version", tmp);
}
#else
php_info_print_table_row(2, "FreeType Linkage", "with unknown library");
#endif
#endif
#ifdef HAVE_LIBT1
php_info_print_table_row(2, "T1Lib Support", "enabled");
#endif
php_info_print_table_row(2, "GIF Read Support", "enabled");
php_info_print_table_row(2, "GIF Create Support", "enabled");
#ifdef HAVE_GD_JPG
{
php_info_print_table_row(2, "JPEG Support", "enabled");
php_info_print_table_row(2, "libJPEG Version", gdJpegGetVersionString());
}
#endif
#ifdef HAVE_GD_PNG
php_info_print_table_row(2, "PNG Support", "enabled");
php_info_print_table_row(2, "libPNG Version", gdPngGetVersionString());
#endif
php_info_print_table_row(2, "WBMP Support", "enabled");
#if defined(HAVE_GD_XPM)
php_info_print_table_row(2, "XPM Support", "enabled");
{
char tmp[12];
snprintf(tmp, sizeof(tmp), "%d", XpmLibraryVersion());
php_info_print_table_row(2, "libXpm Version", tmp);
}
#endif
php_info_print_table_row(2, "XBM Support", "enabled");
#if defined(USE_GD_JISX0208)
php_info_print_table_row(2, "JIS-mapped Japanese Font Support", "enabled");
#endif
#ifdef HAVE_GD_WEBP
php_info_print_table_row(2, "WebP Support", "enabled");
#endif
php_info_print_table_end();
DISPLAY_INI_ENTRIES();
}
/* }}} */
/* {{{ proto array gd_info()
*/
PHP_FUNCTION(gd_info)
{
if (zend_parse_parameters_none() == FAILURE) {
RETURN_FALSE;
}
array_init(return_value);
add_assoc_string(return_value, "GD Version", PHP_GD_VERSION_STRING, 1);
#ifdef ENABLE_GD_TTF
add_assoc_bool(return_value, "FreeType Support", 1);
#if HAVE_LIBFREETYPE
add_assoc_string(return_value, "FreeType Linkage", "with freetype", 1);
#else
add_assoc_string(return_value, "FreeType Linkage", "with unknown library", 1);
#endif
#else
add_assoc_bool(return_value, "FreeType Support", 0);
#endif
#ifdef HAVE_LIBT1
add_assoc_bool(return_value, "T1Lib Support", 1);
#else
add_assoc_bool(return_value, "T1Lib Support", 0);
#endif
add_assoc_bool(return_value, "GIF Read Support", 1);
add_assoc_bool(return_value, "GIF Create Support", 1);
#ifdef HAVE_GD_JPG
add_assoc_bool(return_value, "JPEG Support", 1);
#else
add_assoc_bool(return_value, "JPEG Support", 0);
#endif
#ifdef HAVE_GD_PNG
add_assoc_bool(return_value, "PNG Support", 1);
#else
add_assoc_bool(return_value, "PNG Support", 0);
#endif
add_assoc_bool(return_value, "WBMP Support", 1);
#if defined(HAVE_GD_XPM)
add_assoc_bool(return_value, "XPM Support", 1);
#else
add_assoc_bool(return_value, "XPM Support", 0);
#endif
add_assoc_bool(return_value, "XBM Support", 1);
#ifdef HAVE_GD_WEBP
add_assoc_bool(return_value, "WebP Support", 1);
#else
add_assoc_bool(return_value, "WebP Support", 0);
#endif
#if defined(USE_GD_JISX0208)
add_assoc_bool(return_value, "JIS-mapped Japanese Font Support", 1);
#else
add_assoc_bool(return_value, "JIS-mapped Japanese Font Support", 0);
#endif
}
/* }}} */
/* Need this for cpdf. See also comment in file.c php3i_get_le_fp() */
PHP_GD_API int phpi_get_le_gd(void)
{
return le_gd;
}
/* }}} */
#define FLIPWORD(a) (((a & 0xff000000) >> 24) | ((a & 0x00ff0000) >> 8) | ((a & 0x0000ff00) << 8) | ((a & 0x000000ff) << 24))
/* {{{ proto int imageloadfont(string filename)
Load a new font */
PHP_FUNCTION(imageloadfont)
{
char *file;
int file_name, hdr_size = sizeof(gdFont) - sizeof(char *);
int ind, body_size, n = 0, b, i, body_size_check;
gdFontPtr font;
php_stream *stream;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p", &file, &file_name) == FAILURE) {
return;
}
stream = php_stream_open_wrapper(file, "rb", IGNORE_PATH | IGNORE_URL_WIN | REPORT_ERRORS, NULL);
if (stream == NULL) {
RETURN_FALSE;
}
/* Only supports a architecture-dependent binary dump format
* at the moment.
* The file format is like this on machines with 32-byte integers:
*
* byte 0-3: (int) number of characters in the font
* byte 4-7: (int) value of first character in the font (often 32, space)
* byte 8-11: (int) pixel width of each character
* byte 12-15: (int) pixel height of each character
* bytes 16-: (char) array with character data, one byte per pixel
* in each character, for a total of
* (nchars*width*height) bytes.
*/
font = (gdFontPtr) emalloc(sizeof(gdFont));
b = 0;
while (b < hdr_size && (n = php_stream_read(stream, (char*)&font[b], hdr_size - b))) {
b += n;
}
if (!n) {
efree(font);
if (php_stream_eof(stream)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "End of file while reading header");
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error while reading header");
}
php_stream_close(stream);
RETURN_FALSE;
}
i = php_stream_tell(stream);
php_stream_seek(stream, 0, SEEK_END);
body_size_check = php_stream_tell(stream) - hdr_size;
php_stream_seek(stream, i, SEEK_SET);
body_size = font->w * font->h * font->nchars;
if (body_size != body_size_check) {
font->w = FLIPWORD(font->w);
font->h = FLIPWORD(font->h);
font->nchars = FLIPWORD(font->nchars);
body_size = font->w * font->h * font->nchars;
}
if (overflow2(font->nchars, font->h) || overflow2(font->nchars * font->h, font->w )) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error reading font, invalid font header");
efree(font);
php_stream_close(stream);
RETURN_FALSE;
}
if (body_size != body_size_check) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error reading font");
efree(font);
php_stream_close(stream);
RETURN_FALSE;
}
font->data = emalloc(body_size);
b = 0;
while (b < body_size && (n = php_stream_read(stream, &font->data[b], body_size - b))) {
b += n;
}
if (!n) {
efree(font->data);
efree(font);
if (php_stream_eof(stream)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "End of file while reading body");
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error while reading body");
}
php_stream_close(stream);
RETURN_FALSE;
}
php_stream_close(stream);
/* Adding 5 to the font index so we will never have font indices
* that overlap with the old fonts (with indices 1-5). The first
* list index given out is always 1.
*/
ind = 5 + zend_list_insert(font, le_gd_font TSRMLS_CC);
RETURN_LONG(ind);
}
/* }}} */
/* {{{ proto bool imagesetstyle(resource im, array styles)
Set the line drawing styles for use with imageline and IMG_COLOR_STYLED. */
PHP_FUNCTION(imagesetstyle)
{
zval *IM, *styles;
gdImagePtr im;
int * stylearr;
int index;
HashPosition pos;
int num_styles;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra", &IM, &styles) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
num_styles = zend_hash_num_elements(HASH_OF(styles));
if (num_styles == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "styles array must not be empty");
RETURN_FALSE;
}
/* copy the style values in the stylearr */
stylearr = safe_emalloc(sizeof(int), num_styles, 0);
zend_hash_internal_pointer_reset_ex(HASH_OF(styles), &pos);
for (index = 0;; zend_hash_move_forward_ex(HASH_OF(styles), &pos)) {
zval ** item;
if (zend_hash_get_current_data_ex(HASH_OF(styles), (void **) &item, &pos) == FAILURE) {
break;
}
if (Z_TYPE_PP(item) != IS_LONG) {
zval lval;
lval = **item;
zval_copy_ctor(&lval);
convert_to_long(&lval);
stylearr[index++] = Z_LVAL(lval);
} else {
stylearr[index++] = Z_LVAL_PP(item);
}
}
gdImageSetStyle(im, stylearr, index);
efree(stylearr);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto resource imagecreatetruecolor(int x_size, int y_size)
Create a new true color image */
PHP_FUNCTION(imagecreatetruecolor)
{
long x_size, y_size;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll", &x_size, &y_size) == FAILURE) {
return;
}
if (x_size <= 0 || y_size <= 0 || x_size >= INT_MAX || y_size >= INT_MAX) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid image dimensions");
RETURN_FALSE;
}
im = gdImageCreateTrueColor(x_size, y_size);
if (!im) {
RETURN_FALSE;
}
ZEND_REGISTER_RESOURCE(return_value, im, le_gd);
}
/* }}} */
/* {{{ proto bool imageistruecolor(resource im)
return true if the image uses truecolor */
PHP_FUNCTION(imageistruecolor)
{
zval *IM;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &IM) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
RETURN_BOOL(im->trueColor);
}
/* }}} */
/* {{{ proto void imagetruecolortopalette(resource im, bool ditherFlag, int colorsWanted)
Convert a true colour image to a palette based image with a number of colours, optionally using dithering. */
PHP_FUNCTION(imagetruecolortopalette)
{
zval *IM;
zend_bool dither;
long ncolors;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rbl", &IM, &dither, &ncolors) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
if (ncolors <= 0 || ncolors > INT_MAX) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Number of colors has to be greater than zero and no more than %d", INT_MAX);
RETURN_FALSE;
}
gdImageTrueColorToPalette(im, dither, (int)ncolors);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto void imagetruecolortopalette(resource im, bool ditherFlag, int colorsWanted)
Convert a true colour image to a palette based image with a number of colours, optionally using dithering. */
PHP_FUNCTION(imagepalettetotruecolor)
{
zval *IM;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &IM) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
if (gdImagePaletteToTrueColor(im) == 0) {
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool imagecolormatch(resource im1, resource im2)
Makes the colors of the palette version of an image more closely match the true color version */
PHP_FUNCTION(imagecolormatch)
{
zval *IM1, *IM2;
gdImagePtr im1, im2;
int result;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rr", &IM1, &IM2) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im1, gdImagePtr, &IM1, -1, "Image", le_gd);
ZEND_FETCH_RESOURCE(im2, gdImagePtr, &IM2, -1, "Image", le_gd);
result = gdImageColorMatch(im1, im2);
switch (result) {
case -1:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Image1 must be TrueColor" );
RETURN_FALSE;
break;
case -2:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Image2 must be Palette" );
RETURN_FALSE;
break;
case -3:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Image1 and Image2 must be the same size" );
RETURN_FALSE;
break;
case -4:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Image2 must have at least one color" );
RETURN_FALSE;
break;
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool imagesetthickness(resource im, int thickness)
Set line thickness for drawing lines, ellipses, rectangles, polygons etc. */
PHP_FUNCTION(imagesetthickness)
{
zval *IM;
long thick;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &IM, &thick) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
gdImageSetThickness(im, thick);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool imagefilledellipse(resource im, int cx, int cy, int w, int h, int color)
Draw an ellipse */
PHP_FUNCTION(imagefilledellipse)
{
zval *IM;
long cx, cy, w, h, color;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlllll", &IM, &cx, &cy, &w, &h, &color) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
gdImageFilledEllipse(im, cx, cy, w, h, color);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool imagefilledarc(resource im, int cx, int cy, int w, int h, int s, int e, int col, int style)
Draw a filled partial ellipse */
PHP_FUNCTION(imagefilledarc)
{
zval *IM;
long cx, cy, w, h, ST, E, col, style;
gdImagePtr im;
int e, st;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rllllllll", &IM, &cx, &cy, &w, &h, &ST, &E, &col, &style) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
e = E;
if (e < 0) {
e %= 360;
}
st = ST;
if (st < 0) {
st %= 360;
}
gdImageFilledArc(im, cx, cy, w, h, st, e, col, style);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool imagealphablending(resource im, bool on)
Turn alpha blending mode on or off for the given image */
PHP_FUNCTION(imagealphablending)
{
zval *IM;
zend_bool blend;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rb", &IM, &blend) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
gdImageAlphaBlending(im, blend);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool imagesavealpha(resource im, bool on)
Include alpha channel to a saved image */
PHP_FUNCTION(imagesavealpha)
{
zval *IM;
zend_bool save;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rb", &IM, &save) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
gdImageSaveAlpha(im, save);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool imagelayereffect(resource im, int effect)
Set the alpha blending flag to use the bundled libgd layering effects */
PHP_FUNCTION(imagelayereffect)
{
zval *IM;
long effect;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &IM, &effect) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
gdImageAlphaBlending(im, effect);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto int imagecolorallocatealpha(resource im, int red, int green, int blue, int alpha)
Allocate a color with an alpha level. Works for true color and palette based images */
PHP_FUNCTION(imagecolorallocatealpha)
{
zval *IM;
long red, green, blue, alpha;
gdImagePtr im;
int ct = (-1);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rllll", &IM, &red, &green, &blue, &alpha) == FAILURE) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
ct = gdImageColorAllocateAlpha(im, red, green, blue, alpha);
if (ct < 0) {
RETURN_FALSE;
}
RETURN_LONG((long)ct);
}
/* }}} */
/* {{{ proto int imagecolorresolvealpha(resource im, int red, int green, int blue, int alpha)
Resolve/Allocate a colour with an alpha level. Works for true colour and palette based images */
PHP_FUNCTION(imagecolorresolvealpha)
{
zval *IM;
long red, green, blue, alpha;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rllll", &IM, &red, &green, &blue, &alpha) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
RETURN_LONG(gdImageColorResolveAlpha(im, red, green, blue, alpha));
}
/* }}} */
/* {{{ proto int imagecolorclosestalpha(resource im, int red, int green, int blue, int alpha)
Find the closest matching colour with alpha transparency */
PHP_FUNCTION(imagecolorclosestalpha)
{
zval *IM;
long red, green, blue, alpha;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rllll", &IM, &red, &green, &blue, &alpha) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
RETURN_LONG(gdImageColorClosestAlpha(im, red, green, blue, alpha));
}
/* }}} */
/* {{{ proto int imagecolorexactalpha(resource im, int red, int green, int blue, int alpha)
Find exact match for colour with transparency */
PHP_FUNCTION(imagecolorexactalpha)
{
zval *IM;
long red, green, blue, alpha;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rllll", &IM, &red, &green, &blue, &alpha) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
RETURN_LONG(gdImageColorExactAlpha(im, red, green, blue, alpha));
}
/* }}} */
/* {{{ proto bool imagecopyresampled(resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h)
Copy and resize part of an image using resampling to help ensure clarity */
PHP_FUNCTION(imagecopyresampled)
{
zval *SIM, *DIM;
long SX, SY, SW, SH, DX, DY, DW, DH;
gdImagePtr im_dst, im_src;
int srcH, srcW, dstH, dstW, srcY, srcX, dstY, dstX;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rrllllllll", &DIM, &SIM, &DX, &DY, &SX, &SY, &DW, &DH, &SW, &SH) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im_dst, gdImagePtr, &DIM, -1, "Image", le_gd);
ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd);
srcX = SX;
srcY = SY;
srcH = SH;
srcW = SW;
dstX = DX;
dstY = DY;
dstH = DH;
dstW = DW;
gdImageCopyResampled(im_dst, im_src, dstX, dstY, srcX, srcY, dstW, dstH, srcW, srcH);
RETURN_TRUE;
}
/* }}} */
#ifdef PHP_WIN32
/* {{{ proto resource imagegrabwindow(int window_handle [, int client_area])
Grab a window or its client area using a windows handle (HWND property in COM instance) */
PHP_FUNCTION(imagegrabwindow)
{
HWND window;
long client_area = 0;
RECT rc = {0};
RECT rc_win = {0};
int Width, Height;
HDC hdc;
HDC memDC;
HBITMAP memBM;
HBITMAP hOld;
HINSTANCE handle;
long lwindow_handle;
typedef BOOL (WINAPI *tPrintWindow)(HWND, HDC,UINT);
tPrintWindow pPrintWindow = 0;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|l", &lwindow_handle, &client_area) == FAILURE) {
RETURN_FALSE;
}
window = (HWND) lwindow_handle;
if (!IsWindow(window)) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid window handle");
RETURN_FALSE;
}
hdc = GetDC(0);
if (client_area) {
GetClientRect(window, &rc);
Width = rc.right;
Height = rc.bottom;
} else {
GetWindowRect(window, &rc);
Width = rc.right - rc.left;
Height = rc.bottom - rc.top;
}
Width = (Width/4)*4;
memDC = CreateCompatibleDC(hdc);
memBM = CreateCompatibleBitmap(hdc, Width, Height);
hOld = (HBITMAP) SelectObject (memDC, memBM);
handle = LoadLibrary("User32.dll");
if ( handle == 0 ) {
goto clean;
}
pPrintWindow = (tPrintWindow) GetProcAddress(handle, "PrintWindow");
if ( pPrintWindow ) {
pPrintWindow(window, memDC, (UINT) client_area);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Windows API too old");
goto clean;
}
FreeLibrary(handle);
im = gdImageCreateTrueColor(Width, Height);
if (im) {
int x,y;
for (y=0; y <= Height; y++) {
for (x=0; x <= Width; x++) {
int c = GetPixel(memDC, x,y);
gdImageSetPixel(im, x, y, gdTrueColor(GetRValue(c), GetGValue(c), GetBValue(c)));
}
}
}
clean:
SelectObject(memDC,hOld);
DeleteObject(memBM);
DeleteDC(memDC);
ReleaseDC( 0, hdc );
if (!im) {
RETURN_FALSE;
} else {
ZEND_REGISTER_RESOURCE(return_value, im, le_gd);
}
}
/* }}} */
/* {{{ proto resource imagegrabscreen()
Grab a screenshot */
PHP_FUNCTION(imagegrabscreen)
{
HWND window = GetDesktopWindow();
RECT rc = {0};
int Width, Height;
HDC hdc;
HDC memDC;
HBITMAP memBM;
HBITMAP hOld;
typedef BOOL (WINAPI *tPrintWindow)(HWND, HDC,UINT);
tPrintWindow pPrintWindow = 0;
gdImagePtr im;
hdc = GetDC(0);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (!hdc) {
RETURN_FALSE;
}
GetWindowRect(window, &rc);
Width = rc.right - rc.left;
Height = rc.bottom - rc.top;
Width = (Width/4)*4;
memDC = CreateCompatibleDC(hdc);
memBM = CreateCompatibleBitmap(hdc, Width, Height);
hOld = (HBITMAP) SelectObject (memDC, memBM);
BitBlt( memDC, 0, 0, Width, Height , hdc, rc.left, rc.top , SRCCOPY );
im = gdImageCreateTrueColor(Width, Height);
if (im) {
int x,y;
for (y=0; y <= Height; y++) {
for (x=0; x <= Width; x++) {
int c = GetPixel(memDC, x,y);
gdImageSetPixel(im, x, y, gdTrueColor(GetRValue(c), GetGValue(c), GetBValue(c)));
}
}
}
SelectObject(memDC,hOld);
DeleteObject(memBM);
DeleteDC(memDC);
ReleaseDC( 0, hdc );
if (!im) {
RETURN_FALSE;
} else {
ZEND_REGISTER_RESOURCE(return_value, im, le_gd);
}
}
/* }}} */
#endif /* PHP_WIN32 */
/* {{{ proto resource imagerotate(resource src_im, float angle, int bgdcolor [, int ignoretransparent])
Rotate an image using a custom angle */
PHP_FUNCTION(imagerotate)
{
zval *SIM;
gdImagePtr im_dst, im_src;
double degrees;
long color;
long ignoretransparent = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rdl|l", &SIM, °rees, &color, &ignoretransparent) == FAILURE) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd);
im_dst = gdImageRotateInterpolated(im_src, (const float)degrees, color);
if (im_dst != NULL) {
ZEND_REGISTER_RESOURCE(return_value, im_dst, le_gd);
} else {
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto bool imagesettile(resource image, resource tile)
Set the tile image to $tile when filling $image with the "IMG_COLOR_TILED" color */
PHP_FUNCTION(imagesettile)
{
zval *IM, *TILE;
gdImagePtr im, tile;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rr", &IM, &TILE) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
ZEND_FETCH_RESOURCE(tile, gdImagePtr, &TILE, -1, "Image", le_gd);
gdImageSetTile(im, tile);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool imagesetbrush(resource image, resource brush)
Set the brush image to $brush when filling $image with the "IMG_COLOR_BRUSHED" color */
PHP_FUNCTION(imagesetbrush)
{
zval *IM, *TILE;
gdImagePtr im, tile;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rr", &IM, &TILE) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
ZEND_FETCH_RESOURCE(tile, gdImagePtr, &TILE, -1, "Image", le_gd);
gdImageSetBrush(im, tile);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto resource imagecreate(int x_size, int y_size)
Create a new image */
PHP_FUNCTION(imagecreate)
{
long x_size, y_size;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll", &x_size, &y_size) == FAILURE) {
return;
}
if (x_size <= 0 || y_size <= 0 || x_size >= INT_MAX || y_size >= INT_MAX) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid image dimensions");
RETURN_FALSE;
}
im = gdImageCreate(x_size, y_size);
if (!im) {
RETURN_FALSE;
}
ZEND_REGISTER_RESOURCE(return_value, im, le_gd);
}
/* }}} */
/* {{{ proto int imagetypes(void)
Return the types of images supported in a bitfield - 1=GIF, 2=JPEG, 4=PNG, 8=WBMP, 16=XPM */
PHP_FUNCTION(imagetypes)
{
int ret=0;
ret = 1;
#ifdef HAVE_GD_JPG
ret |= 2;
#endif
#ifdef HAVE_GD_PNG
ret |= 4;
#endif
ret |= 8;
#if defined(HAVE_GD_XPM)
ret |= 16;
#endif
#ifdef HAVE_GD_WEBP
ret |= 32;
#endif
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG(ret);
}
/* }}} */
/* {{{ _php_ctx_getmbi
*/
static int _php_ctx_getmbi(gdIOCtx *ctx)
{
int i, mbi = 0;
do {
i = (ctx->getC)(ctx);
if (i < 0) {
return -1;
}
mbi = (mbi << 7) | (i & 0x7f);
} while (i & 0x80);
return mbi;
}
/* }}} */
/* {{{ _php_image_type
*/
static const char php_sig_gd2[3] = {'g', 'd', '2'};
static int _php_image_type (char data[8])
{
/* Based on ext/standard/image.c */
if (data == NULL) {
return -1;
}
if (!memcmp(data, php_sig_gd2, 3)) {
return PHP_GDIMG_TYPE_GD2;
} else if (!memcmp(data, php_sig_jpg, 3)) {
return PHP_GDIMG_TYPE_JPG;
} else if (!memcmp(data, php_sig_png, 3)) {
if (!memcmp(data, php_sig_png, 8)) {
return PHP_GDIMG_TYPE_PNG;
}
} else if (!memcmp(data, php_sig_gif, 3)) {
return PHP_GDIMG_TYPE_GIF;
}
else {
gdIOCtx *io_ctx;
io_ctx = gdNewDynamicCtxEx(8, data, 0);
if (io_ctx) {
if (_php_ctx_getmbi(io_ctx) == 0 && _php_ctx_getmbi(io_ctx) >= 0) {
io_ctx->gd_free(io_ctx);
return PHP_GDIMG_TYPE_WBM;
} else {
io_ctx->gd_free(io_ctx);
}
}
}
return -1;
}
/* }}} */
/* {{{ _php_image_create_from_string
*/
gdImagePtr _php_image_create_from_string(zval **data, char *tn, gdImagePtr (*ioctx_func_p)() TSRMLS_DC)
{
gdImagePtr im;
gdIOCtx *io_ctx;
io_ctx = gdNewDynamicCtxEx(Z_STRLEN_PP(data), Z_STRVAL_PP(data), 0);
if (!io_ctx) {
return NULL;
}
im = (*ioctx_func_p)(io_ctx);
if (!im) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Passed data is not in '%s' format", tn);
io_ctx->gd_free(io_ctx);
return NULL;
}
io_ctx->gd_free(io_ctx);
return im;
}
/* }}} */
/* {{{ proto resource imagecreatefromstring(string image)
Create a new image from the image stream in the string */
PHP_FUNCTION(imagecreatefromstring)
{
zval **data;
gdImagePtr im;
int imtype;
char sig[8];
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Z", &data) == FAILURE) {
return;
}
convert_to_string_ex(data);
if (Z_STRLEN_PP(data) < 8) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty string or invalid image");
RETURN_FALSE;
}
memcpy(sig, Z_STRVAL_PP(data), 8);
imtype = _php_image_type(sig);
switch (imtype) {
case PHP_GDIMG_TYPE_JPG:
#ifdef HAVE_GD_JPG
im = _php_image_create_from_string(data, "JPEG", gdImageCreateFromJpegCtx TSRMLS_CC);
#else
php_error_docref(NULL TSRMLS_CC, E_WARNING, "No JPEG support in this PHP build");
RETURN_FALSE;
#endif
break;
case PHP_GDIMG_TYPE_PNG:
#ifdef HAVE_GD_PNG
im = _php_image_create_from_string(data, "PNG", gdImageCreateFromPngCtx TSRMLS_CC);
#else
php_error_docref(NULL TSRMLS_CC, E_WARNING, "No PNG support in this PHP build");
RETURN_FALSE;
#endif
break;
case PHP_GDIMG_TYPE_GIF:
im = _php_image_create_from_string(data, "GIF", gdImageCreateFromGifCtx TSRMLS_CC);
break;
case PHP_GDIMG_TYPE_WBM:
im = _php_image_create_from_string(data, "WBMP", gdImageCreateFromWBMPCtx TSRMLS_CC);
break;
case PHP_GDIMG_TYPE_GD2:
im = _php_image_create_from_string(data, "GD2", gdImageCreateFromGd2Ctx TSRMLS_CC);
break;
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Data is not in a recognized format");
RETURN_FALSE;
}
if (!im) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't create GD Image Stream out of Data");
RETURN_FALSE;
}
ZEND_REGISTER_RESOURCE(return_value, im, le_gd);
}
/* }}} */
/* {{{ _php_image_create_from
*/
static void _php_image_create_from(INTERNAL_FUNCTION_PARAMETERS, int image_type, char *tn, gdImagePtr (*func_p)(), gdImagePtr (*ioctx_func_p)())
{
char *file;
int file_len;
long srcx, srcy, width, height;
gdImagePtr im = NULL;
php_stream *stream;
FILE * fp = NULL;
long ignore_warning;
if (image_type == PHP_GDIMG_TYPE_GD2PART) {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "pllll", &file, &file_len, &srcx, &srcy, &width, &height) == FAILURE) {
return;
}
if (width < 1 || height < 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Zero width or height not allowed");
RETURN_FALSE;
}
} else {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p", &file, &file_len) == FAILURE) {
return;
}
}
stream = php_stream_open_wrapper(file, "rb", REPORT_ERRORS|IGNORE_PATH|IGNORE_URL_WIN, NULL);
if (stream == NULL) {
RETURN_FALSE;
}
/* try and avoid allocating a FILE* if the stream is not naturally a FILE* */
if (php_stream_is(stream, PHP_STREAM_IS_STDIO)) {
if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO, (void**)&fp, REPORT_ERRORS)) {
goto out_err;
}
} else if (ioctx_func_p) {
/* we can create an io context */
gdIOCtx* io_ctx;
size_t buff_size;
char *buff;
/* needs to be malloc (persistent) - GD will free() it later */
buff_size = php_stream_copy_to_mem(stream, &buff, PHP_STREAM_COPY_ALL, 1);
if (!buff_size) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,"Cannot read image data");
goto out_err;
}
io_ctx = gdNewDynamicCtxEx(buff_size, buff, 0);
if (!io_ctx) {
pefree(buff, 1);
php_error_docref(NULL TSRMLS_CC, E_WARNING,"Cannot allocate GD IO context");
goto out_err;
}
if (image_type == PHP_GDIMG_TYPE_GD2PART) {
im = (*ioctx_func_p)(io_ctx, srcx, srcy, width, height);
} else {
im = (*ioctx_func_p)(io_ctx);
}
io_ctx->gd_free(io_ctx);
pefree(buff, 1);
}
else if (php_stream_can_cast(stream, PHP_STREAM_AS_STDIO)) {
/* try and force the stream to be FILE* */
if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO | PHP_STREAM_CAST_TRY_HARD, (void **) &fp, REPORT_ERRORS)) {
goto out_err;
}
}
if (!im && fp) {
switch (image_type) {
case PHP_GDIMG_TYPE_GD2PART:
im = (*func_p)(fp, srcx, srcy, width, height);
break;
#if defined(HAVE_GD_XPM)
case PHP_GDIMG_TYPE_XPM:
im = gdImageCreateFromXpm(file);
break;
#endif
#ifdef HAVE_GD_JPG
case PHP_GDIMG_TYPE_JPG:
ignore_warning = INI_INT("gd.jpeg_ignore_warning");
im = gdImageCreateFromJpegEx(fp, ignore_warning);
break;
#endif
default:
im = (*func_p)(fp);
break;
}
fflush(fp);
}
/* register_im: */
if (im) {
ZEND_REGISTER_RESOURCE(return_value, im, le_gd);
php_stream_close(stream);
return;
}
php_error_docref(NULL TSRMLS_CC, E_WARNING, "'%s' is not a valid %s file", file, tn);
out_err:
php_stream_close(stream);
RETURN_FALSE;
}
/* }}} */
/* {{{ proto resource imagecreatefromgif(string filename)
Create a new image from GIF file or URL */
PHP_FUNCTION(imagecreatefromgif)
{
_php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_GIF, "GIF", gdImageCreateFromGif, gdImageCreateFromGifCtx);
}
/* }}} */
#ifdef HAVE_GD_JPG
/* {{{ proto resource imagecreatefromjpeg(string filename)
Create a new image from JPEG file or URL */
PHP_FUNCTION(imagecreatefromjpeg)
{
_php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_JPG, "JPEG", gdImageCreateFromJpeg, gdImageCreateFromJpegCtx);
}
/* }}} */
#endif /* HAVE_GD_JPG */
#ifdef HAVE_GD_PNG
/* {{{ proto resource imagecreatefrompng(string filename)
Create a new image from PNG file or URL */
PHP_FUNCTION(imagecreatefrompng)
{
_php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_PNG, "PNG", gdImageCreateFromPng, gdImageCreateFromPngCtx);
}
/* }}} */
#endif /* HAVE_GD_PNG */
#ifdef HAVE_GD_WEBP
/* {{{ proto resource imagecreatefromwebp(string filename)
Create a new image from WEBP file or URL */
PHP_FUNCTION(imagecreatefromwebp)
{
_php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_WEBP, "WEBP", gdImageCreateFromWebp, gdImageCreateFromWebpCtx);
}
/* }}} */
#endif /* HAVE_GD_VPX */
/* {{{ proto resource imagecreatefromxbm(string filename)
Create a new image from XBM file or URL */
PHP_FUNCTION(imagecreatefromxbm)
{
_php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_XBM, "XBM", gdImageCreateFromXbm, NULL);
}
/* }}} */
#if defined(HAVE_GD_XPM)
/* {{{ proto resource imagecreatefromxpm(string filename)
Create a new image from XPM file or URL */
PHP_FUNCTION(imagecreatefromxpm)
{
_php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_XPM, "XPM", gdImageCreateFromXpm, NULL);
}
/* }}} */
#endif
/* {{{ proto resource imagecreatefromwbmp(string filename)
Create a new image from WBMP file or URL */
PHP_FUNCTION(imagecreatefromwbmp)
{
_php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_WBM, "WBMP", gdImageCreateFromWBMP, gdImageCreateFromWBMPCtx);
}
/* }}} */
/* {{{ proto resource imagecreatefromgd(string filename)
Create a new image from GD file or URL */
PHP_FUNCTION(imagecreatefromgd)
{
_php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_GD, "GD", gdImageCreateFromGd, gdImageCreateFromGdCtx);
}
/* }}} */
/* {{{ proto resource imagecreatefromgd2(string filename)
Create a new image from GD2 file or URL */
PHP_FUNCTION(imagecreatefromgd2)
{
_php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_GD2, "GD2", gdImageCreateFromGd2, gdImageCreateFromGd2Ctx);
}
/* }}} */
/* {{{ proto resource imagecreatefromgd2part(string filename, int srcX, int srcY, int width, int height)
Create a new image from a given part of GD2 file or URL */
PHP_FUNCTION(imagecreatefromgd2part)
{
_php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_GD2PART, "GD2", gdImageCreateFromGd2Part, gdImageCreateFromGd2PartCtx);
}
/* }}} */
/* {{{ _php_image_output
*/
static void _php_image_output(INTERNAL_FUNCTION_PARAMETERS, int image_type, char *tn, void (*func_p)())
{
zval *imgind;
char *file = NULL;
long quality = 0, type = 0;
gdImagePtr im;
char *fn = NULL;
FILE *fp;
int file_len = 0, argc = ZEND_NUM_ARGS();
int q = -1, i, t = 1;
/* The quality parameter for Wbmp stands for the threshold when called from image2wbmp() */
/* When called from imagewbmp() the quality parameter stands for the foreground color. Default: black. */
/* The quality parameter for gd2 stands for chunk size */
if (zend_parse_parameters(argc TSRMLS_CC, "r|pll", &imgind, &file, &file_len, &quality, &type) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &imgind, -1, "Image", le_gd);
if (argc > 1) {
fn = file;
if (argc == 3) {
q = quality;
}
if (argc == 4) {
t = type;
}
}
if (argc >= 2 && file_len) {
PHP_GD_CHECK_OPEN_BASEDIR(fn, "Invalid filename");
fp = VCWD_FOPEN(fn, "wb");
if (!fp) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' for writing", fn);
RETURN_FALSE;
}
switch (image_type) {
case PHP_GDIMG_CONVERT_WBM:
if (q == -1) {
q = 0;
} else if (q < 0 || q > 255) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid threshold value '%d'. It must be between 0 and 255", q);
q = 0;
}
gdImageWBMP(im, q, fp);
break;
case PHP_GDIMG_TYPE_JPG:
(*func_p)(im, fp, q);
break;
case PHP_GDIMG_TYPE_WBM:
for (i = 0; i < gdImageColorsTotal(im); i++) {
if (gdImageRed(im, i) == 0) break;
}
(*func_p)(im, i, fp);
break;
case PHP_GDIMG_TYPE_GD:
if (im->trueColor){
gdImageTrueColorToPalette(im,1,256);
}
(*func_p)(im, fp);
break;
case PHP_GDIMG_TYPE_GD2:
if (q == -1) {
q = 128;
}
(*func_p)(im, fp, q, t);
break;
default:
if (q == -1) {
q = 128;
}
(*func_p)(im, fp, q, t);
break;
}
fflush(fp);
fclose(fp);
} else {
int b;
FILE *tmp;
char buf[4096];
char *path;
tmp = php_open_temporary_file(NULL, NULL, &path TSRMLS_CC);
if (tmp == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open temporary file");
RETURN_FALSE;
}
switch (image_type) {
case PHP_GDIMG_CONVERT_WBM:
if (q == -1) {
q = 0;
} else if (q < 0 || q > 255) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid threshold value '%d'. It must be between 0 and 255", q);
q = 0;
}
gdImageWBMP(im, q, tmp);
break;
case PHP_GDIMG_TYPE_JPG:
(*func_p)(im, tmp, q);
break;
case PHP_GDIMG_TYPE_WBM:
for (i = 0; i < gdImageColorsTotal(im); i++) {
if (gdImageRed(im, i) == 0) {
break;
}
}
(*func_p)(im, q, tmp);
break;
case PHP_GDIMG_TYPE_GD:
if (im->trueColor) {
gdImageTrueColorToPalette(im,1,256);
}
(*func_p)(im, tmp);
break;
case PHP_GDIMG_TYPE_GD2:
if (q == -1) {
q = 128;
}
(*func_p)(im, tmp, q, t);
break;
default:
(*func_p)(im, tmp);
break;
}
fseek(tmp, 0, SEEK_SET);
#if APACHE && defined(CHARSET_EBCDIC)
/* XXX this is unlikely to work any more thies@thieso.net */
/* This is a binary file already: avoid EBCDIC->ASCII conversion */
ap_bsetflag(php3_rqst->connection->client, B_EBCDIC2ASCII, 0);
#endif
while ((b = fread(buf, 1, sizeof(buf), tmp)) > 0) {
php_write(buf, b TSRMLS_CC);
}
fclose(tmp);
VCWD_UNLINK((const char *)path); /* make sure that the temporary file is removed */
efree(path);
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto int imagexbm(int im, string filename [, int foreground])
Output XBM image to browser or file */
PHP_FUNCTION(imagexbm)
{
_php_image_output_ctx(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_XBM, "XBM", gdImageXbmCtx);
}
/* }}} */
/* {{{ proto bool imagegif(resource im [, string filename])
Output GIF image to browser or file */
PHP_FUNCTION(imagegif)
{
_php_image_output_ctx(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_GIF, "GIF", gdImageGifCtx);
}
/* }}} */
#ifdef HAVE_GD_PNG
/* {{{ proto bool imagepng(resource im [, string filename])
Output PNG image to browser or file */
PHP_FUNCTION(imagepng)
{
_php_image_output_ctx(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_PNG, "PNG", gdImagePngCtxEx);
}
/* }}} */
#endif /* HAVE_GD_PNG */
#ifdef HAVE_GD_WEBP
/* {{{ proto bool imagewebp(resource im [, string filename[, quality]] )
Output WEBP image to browser or file */
PHP_FUNCTION(imagewebp)
{
_php_image_output_ctx(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_WEBP, "WEBP", gdImageWebpCtx);
}
/* }}} */
#endif /* HAVE_GD_WEBP */
#ifdef HAVE_GD_JPG
/* {{{ proto bool imagejpeg(resource im [, string filename [, int quality]])
Output JPEG image to browser or file */
PHP_FUNCTION(imagejpeg)
{
_php_image_output_ctx(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_JPG, "JPEG", gdImageJpegCtx);
}
/* }}} */
#endif /* HAVE_GD_JPG */
/* {{{ proto bool imagewbmp(resource im [, string filename, [, int foreground]])
Output WBMP image to browser or file */
PHP_FUNCTION(imagewbmp)
{
_php_image_output_ctx(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_WBM, "WBMP", gdImageWBMPCtx);
}
/* }}} */
/* {{{ proto bool imagegd(resource im [, string filename])
Output GD image to browser or file */
PHP_FUNCTION(imagegd)
{
_php_image_output(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_GD, "GD", gdImageGd);
}
/* }}} */
/* {{{ proto bool imagegd2(resource im [, string filename, [, int chunk_size, [, int type]]])
Output GD2 image to browser or file */
PHP_FUNCTION(imagegd2)
{
_php_image_output(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_GD2, "GD2", gdImageGd2);
}
/* }}} */
/* {{{ proto bool imagedestroy(resource im)
Destroy an image */
PHP_FUNCTION(imagedestroy)
{
zval *IM;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &IM) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
zend_list_delete(Z_LVAL_P(IM));
RETURN_TRUE;
}
/* }}} */
/* {{{ proto int imagecolorallocate(resource im, int red, int green, int blue)
Allocate a color for an image */
PHP_FUNCTION(imagecolorallocate)
{
zval *IM;
long red, green, blue;
gdImagePtr im;
int ct = (-1);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlll", &IM, &red, &green, &blue) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
ct = gdImageColorAllocate(im, red, green, blue);
if (ct < 0) {
RETURN_FALSE;
}
RETURN_LONG(ct);
}
/* }}} */
/* {{{ proto void imagepalettecopy(resource dst, resource src)
Copy the palette from the src image onto the dst image */
PHP_FUNCTION(imagepalettecopy)
{
zval *dstim, *srcim;
gdImagePtr dst, src;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rr", &dstim, &srcim) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(dst, gdImagePtr, &dstim, -1, "Image", le_gd);
ZEND_FETCH_RESOURCE(src, gdImagePtr, &srcim, -1, "Image", le_gd);
gdImagePaletteCopy(dst, src);
}
/* }}} */
/* {{{ proto int imagecolorat(resource im, int x, int y)
Get the index of the color of a pixel */
PHP_FUNCTION(imagecolorat)
{
zval *IM;
long x, y;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rll", &IM, &x, &y) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
if (gdImageTrueColor(im)) {
if (im->tpixels && gdImageBoundsSafe(im, x, y)) {
RETURN_LONG(gdImageTrueColorPixel(im, x, y));
} else {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "%ld,%ld is out of bounds", x, y);
RETURN_FALSE;
}
} else {
if (im->pixels && gdImageBoundsSafe(im, x, y)) {
RETURN_LONG(im->pixels[y][x]);
} else {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "%ld,%ld is out of bounds", x, y);
RETURN_FALSE;
}
}
}
/* }}} */
/* {{{ proto int imagecolorclosest(resource im, int red, int green, int blue)
Get the index of the closest color to the specified color */
PHP_FUNCTION(imagecolorclosest)
{
zval *IM;
long red, green, blue;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlll", &IM, &red, &green, &blue) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
RETURN_LONG(gdImageColorClosest(im, red, green, blue));
}
/* }}} */
/* {{{ proto int imagecolorclosesthwb(resource im, int red, int green, int blue)
Get the index of the color which has the hue, white and blackness nearest to the given color */
PHP_FUNCTION(imagecolorclosesthwb)
{
zval *IM;
long red, green, blue;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlll", &IM, &red, &green, &blue) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
RETURN_LONG(gdImageColorClosestHWB(im, red, green, blue));
}
/* }}} */
/* {{{ proto bool imagecolordeallocate(resource im, int index)
De-allocate a color for an image */
PHP_FUNCTION(imagecolordeallocate)
{
zval *IM;
long index;
int col;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &IM, &index) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
/* We can return right away for a truecolor image as deallocating colours is meaningless here */
if (gdImageTrueColor(im)) {
RETURN_TRUE;
}
col = index;
if (col >= 0 && col < gdImageColorsTotal(im)) {
gdImageColorDeallocate(im, col);
RETURN_TRUE;
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Color index %d out of range", col);
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto int imagecolorresolve(resource im, int red, int green, int blue)
Get the index of the specified color or its closest possible alternative */
PHP_FUNCTION(imagecolorresolve)
{
zval *IM;
long red, green, blue;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlll", &IM, &red, &green, &blue) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
RETURN_LONG(gdImageColorResolve(im, red, green, blue));
}
/* }}} */
/* {{{ proto int imagecolorexact(resource im, int red, int green, int blue)
Get the index of the specified color */
PHP_FUNCTION(imagecolorexact)
{
zval *IM;
long red, green, blue;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlll", &IM, &red, &green, &blue) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
RETURN_LONG(gdImageColorExact(im, red, green, blue));
}
/* }}} */
/* {{{ proto void imagecolorset(resource im, int col, int red, int green, int blue)
Set the color for the specified palette index */
PHP_FUNCTION(imagecolorset)
{
zval *IM;
long color, red, green, blue, alpha = 0;
int col;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rllll|l", &IM, &color, &red, &green, &blue, &alpha) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
col = color;
if (col >= 0 && col < gdImageColorsTotal(im)) {
im->red[col] = red;
im->green[col] = green;
im->blue[col] = blue;
im->alpha[col] = alpha;
} else {
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto array imagecolorsforindex(resource im, int col)
Get the colors for an index */
PHP_FUNCTION(imagecolorsforindex)
{
zval *IM;
long index;
int col;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &IM, &index) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
col = index;
if ((col >= 0 && gdImageTrueColor(im)) || (!gdImageTrueColor(im) && col >= 0 && col < gdImageColorsTotal(im))) {
array_init(return_value);
add_assoc_long(return_value,"red", gdImageRed(im,col));
add_assoc_long(return_value,"green", gdImageGreen(im,col));
add_assoc_long(return_value,"blue", gdImageBlue(im,col));
add_assoc_long(return_value,"alpha", gdImageAlpha(im,col));
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Color index %d out of range", col);
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto bool imagegammacorrect(resource im, float inputgamma, float outputgamma)
Apply a gamma correction to a GD image */
PHP_FUNCTION(imagegammacorrect)
{
zval *IM;
gdImagePtr im;
int i;
double input, output;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rdd", &IM, &input, &output) == FAILURE) {
return;
}
if ( input <= 0.0 || output <= 0.0 ) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Gamma values should be positive");
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
if (gdImageTrueColor(im)) {
int x, y, c;
for (y = 0; y < gdImageSY(im); y++) {
for (x = 0; x < gdImageSX(im); x++) {
c = gdImageGetPixel(im, x, y);
gdImageSetPixel(im, x, y,
gdTrueColorAlpha(
(int) ((pow((pow((gdTrueColorGetRed(c) / 255.0), input)), 1.0 / output) * 255) + .5),
(int) ((pow((pow((gdTrueColorGetGreen(c) / 255.0), input)), 1.0 / output) * 255) + .5),
(int) ((pow((pow((gdTrueColorGetBlue(c) / 255.0), input)), 1.0 / output) * 255) + .5),
gdTrueColorGetAlpha(c)
)
);
}
}
RETURN_TRUE;
}
for (i = 0; i < gdImageColorsTotal(im); i++) {
im->red[i] = (int)((pow((pow((im->red[i] / 255.0), input)), 1.0 / output) * 255) + .5);
im->green[i] = (int)((pow((pow((im->green[i] / 255.0), input)), 1.0 / output) * 255) + .5);
im->blue[i] = (int)((pow((pow((im->blue[i] / 255.0), input)), 1.0 / output) * 255) + .5);
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool imagesetpixel(resource im, int x, int y, int col)
Set a single pixel */
PHP_FUNCTION(imagesetpixel)
{
zval *IM;
long x, y, col;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlll", &IM, &x, &y, &col) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
gdImageSetPixel(im, x, y, col);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool imageline(resource im, int x1, int y1, int x2, int y2, int col)
Draw a line */
PHP_FUNCTION(imageline)
{
zval *IM;
long x1, y1, x2, y2, col;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlllll", &IM, &x1, &y1, &x2, &y2, &col) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
#ifdef HAVE_GD_BUNDLED
if (im->antialias) {
gdImageAALine(im, x1, y1, x2, y2, col);
} else
#endif
{
gdImageLine(im, x1, y1, x2, y2, col);
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool imagedashedline(resource im, int x1, int y1, int x2, int y2, int col)
Draw a dashed line */
PHP_FUNCTION(imagedashedline)
{
zval *IM;
long x1, y1, x2, y2, col;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlllll", &IM, &x1, &y1, &x2, &y2, &col) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
gdImageDashedLine(im, x1, y1, x2, y2, col);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool imagerectangle(resource im, int x1, int y1, int x2, int y2, int col)
Draw a rectangle */
PHP_FUNCTION(imagerectangle)
{
zval *IM;
long x1, y1, x2, y2, col;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlllll", &IM, &x1, &y1, &x2, &y2, &col) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
gdImageRectangle(im, x1, y1, x2, y2, col);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool imagefilledrectangle(resource im, int x1, int y1, int x2, int y2, int col)
Draw a filled rectangle */
PHP_FUNCTION(imagefilledrectangle)
{
zval *IM;
long x1, y1, x2, y2, col;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlllll", &IM, &x1, &y1, &x2, &y2, &col) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
gdImageFilledRectangle(im, x1, y1, x2, y2, col);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool imagearc(resource im, int cx, int cy, int w, int h, int s, int e, int col)
Draw a partial ellipse */
PHP_FUNCTION(imagearc)
{
zval *IM;
long cx, cy, w, h, ST, E, col;
gdImagePtr im;
int e, st;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlllllll", &IM, &cx, &cy, &w, &h, &ST, &E, &col) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
e = E;
if (e < 0) {
e %= 360;
}
st = ST;
if (st < 0) {
st %= 360;
}
gdImageArc(im, cx, cy, w, h, st, e, col);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool imageellipse(resource im, int cx, int cy, int w, int h, int color)
Draw an ellipse */
PHP_FUNCTION(imageellipse)
{
zval *IM;
long cx, cy, w, h, color;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlllll", &IM, &cx, &cy, &w, &h, &color) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
gdImageEllipse(im, cx, cy, w, h, color);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool imagefilltoborder(resource im, int x, int y, int border, int col)
Flood fill to specific color */
PHP_FUNCTION(imagefilltoborder)
{
zval *IM;
long x, y, border, col;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rllll", &IM, &x, &y, &border, &col) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
gdImageFillToBorder(im, x, y, border, col);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool imagefill(resource im, int x, int y, int col)
Flood fill */
PHP_FUNCTION(imagefill)
{
zval *IM;
long x, y, col;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlll", &IM, &x, &y, &col) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
gdImageFill(im, x, y, col);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto int imagecolorstotal(resource im)
Find out the number of colors in an image's palette */
PHP_FUNCTION(imagecolorstotal)
{
zval *IM;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &IM) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
RETURN_LONG(gdImageColorsTotal(im));
}
/* }}} */
/* {{{ proto int imagecolortransparent(resource im [, int col])
Define a color as transparent */
PHP_FUNCTION(imagecolortransparent)
{
zval *IM;
long COL = 0;
gdImagePtr im;
int argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc TSRMLS_CC, "r|l", &IM, &COL) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
if (argc > 1) {
gdImageColorTransparent(im, COL);
}
RETURN_LONG(gdImageGetTransparent(im));
}
/* }}} */
/* {{{ proto int imageinterlace(resource im [, int interlace])
Enable or disable interlace */
PHP_FUNCTION(imageinterlace)
{
zval *IM;
int argc = ZEND_NUM_ARGS();
long INT = 0;
gdImagePtr im;
if (zend_parse_parameters(argc TSRMLS_CC, "r|l", &IM, &INT) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
if (argc > 1) {
gdImageInterlace(im, INT);
}
RETURN_LONG(gdImageGetInterlaced(im));
}
/* }}} */
/* {{{ php_imagepolygon
arg = 0 normal polygon
arg = 1 filled polygon */
/* im, points, num_points, col */
static void php_imagepolygon(INTERNAL_FUNCTION_PARAMETERS, int filled)
{
zval *IM, *POINTS;
long NPOINTS, COL;
zval **var = NULL;
gdImagePtr im;
gdPointPtr points;
int npoints, col, nelem, i;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rall", &IM, &POINTS, &NPOINTS, &COL) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
npoints = NPOINTS;
col = COL;
nelem = zend_hash_num_elements(Z_ARRVAL_P(POINTS));
if (nelem < 6) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have at least 3 points in your array");
RETURN_FALSE;
}
if (npoints <= 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must give a positive number of points");
RETURN_FALSE;
}
if (nelem < npoints * 2) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Trying to use %d points in array with only %d points", npoints, nelem/2);
RETURN_FALSE;
}
points = (gdPointPtr) safe_emalloc(npoints, sizeof(gdPoint), 0);
for (i = 0; i < npoints; i++) {
if (zend_hash_index_find(Z_ARRVAL_P(POINTS), (i * 2), (void **) &var) == SUCCESS) {
if (Z_TYPE_PP(var) != IS_LONG) {
zval lval;
lval = **var;
zval_copy_ctor(&lval);
convert_to_long(&lval);
points[i].x = Z_LVAL(lval);
} else {
points[i].x = Z_LVAL_PP(var);
}
}
if (zend_hash_index_find(Z_ARRVAL_P(POINTS), (i * 2) + 1, (void **) &var) == SUCCESS) {
if (Z_TYPE_PP(var) != IS_LONG) {
zval lval;
lval = **var;
zval_copy_ctor(&lval);
convert_to_long(&lval);
points[i].y = Z_LVAL(lval);
} else {
points[i].y = Z_LVAL_PP(var);
}
}
}
if (filled) {
gdImageFilledPolygon(im, points, npoints, col);
} else {
gdImagePolygon(im, points, npoints, col);
}
efree(points);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool imagepolygon(resource im, array point, int num_points, int col)
Draw a polygon */
PHP_FUNCTION(imagepolygon)
{
php_imagepolygon(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
}
/* }}} */
/* {{{ proto bool imagefilledpolygon(resource im, array point, int num_points, int col)
Draw a filled polygon */
PHP_FUNCTION(imagefilledpolygon)
{
php_imagepolygon(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
}
/* }}} */
/* {{{ php_find_gd_font
*/
static gdFontPtr php_find_gd_font(int size TSRMLS_DC)
{
gdFontPtr font;
int ind_type;
switch (size) {
case 1:
font = gdFontTiny;
break;
case 2:
font = gdFontSmall;
break;
case 3:
font = gdFontMediumBold;
break;
case 4:
font = gdFontLarge;
break;
case 5:
font = gdFontGiant;
break;
default:
font = zend_list_find(size - 5, &ind_type);
if (!font || ind_type != le_gd_font) {
if (size < 1) {
font = gdFontTiny;
} else {
font = gdFontGiant;
}
}
break;
}
return font;
}
/* }}} */
/* {{{ php_imagefontsize
* arg = 0 ImageFontWidth
* arg = 1 ImageFontHeight
*/
static void php_imagefontsize(INTERNAL_FUNCTION_PARAMETERS, int arg)
{
long SIZE;
gdFontPtr font;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &SIZE) == FAILURE) {
return;
}
font = php_find_gd_font(SIZE TSRMLS_CC);
RETURN_LONG(arg ? font->h : font->w);
}
/* }}} */
/* {{{ proto int imagefontwidth(int font)
Get font width */
PHP_FUNCTION(imagefontwidth)
{
php_imagefontsize(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
}
/* }}} */
/* {{{ proto int imagefontheight(int font)
Get font height */
PHP_FUNCTION(imagefontheight)
{
php_imagefontsize(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
}
/* }}} */
/* {{{ php_gdimagecharup
* workaround for a bug in gd 1.2 */
static void php_gdimagecharup(gdImagePtr im, gdFontPtr f, int x, int y, int c, int color)
{
int cx, cy, px, py, fline;
cx = 0;
cy = 0;
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++;
}
}
/* }}} */
/* {{{ php_imagechar
* arg = 0 ImageChar
* arg = 1 ImageCharUp
* arg = 2 ImageString
* arg = 3 ImageStringUp
*/
static void php_imagechar(INTERNAL_FUNCTION_PARAMETERS, int mode)
{
zval *IM;
long SIZE, X, Y, COL;
char *C;
int C_len;
gdImagePtr im;
int ch = 0, col, x, y, size, i, l = 0;
unsigned char *str = NULL;
gdFontPtr font;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlllsl", &IM, &SIZE, &X, &Y, &C, &C_len, &COL) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
col = COL;
if (mode < 2) {
ch = (int)((unsigned char)*C);
} else {
str = (unsigned char *) estrndup(C, C_len);
l = strlen((char *)str);
}
y = Y;
x = X;
size = SIZE;
font = php_find_gd_font(size TSRMLS_CC);
switch (mode) {
case 0:
gdImageChar(im, font, x, y, ch, col);
break;
case 1:
php_gdimagecharup(im, font, x, y, ch, col);
break;
case 2:
for (i = 0; (i < l); i++) {
gdImageChar(im, font, x, y, (int) ((unsigned char) str[i]), col);
x += font->w;
}
break;
case 3: {
for (i = 0; (i < l); i++) {
/* php_gdimagecharup(im, font, x, y, (int) str[i], col); */
gdImageCharUp(im, font, x, y, (int) str[i], col);
y -= font->w;
}
break;
}
}
if (str) {
efree(str);
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool imagechar(resource im, int font, int x, int y, string c, int col)
Draw a character */
PHP_FUNCTION(imagechar)
{
php_imagechar(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
}
/* }}} */
/* {{{ proto bool imagecharup(resource im, int font, int x, int y, string c, int col)
Draw a character rotated 90 degrees counter-clockwise */
PHP_FUNCTION(imagecharup)
{
php_imagechar(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
}
/* }}} */
/* {{{ proto bool imagestring(resource im, int font, int x, int y, string str, int col)
Draw a string horizontally */
PHP_FUNCTION(imagestring)
{
php_imagechar(INTERNAL_FUNCTION_PARAM_PASSTHRU, 2);
}
/* }}} */
/* {{{ proto bool imagestringup(resource im, int font, int x, int y, string str, int col)
Draw a string vertically - rotated 90 degrees counter-clockwise */
PHP_FUNCTION(imagestringup)
{
php_imagechar(INTERNAL_FUNCTION_PARAM_PASSTHRU, 3);
}
/* }}} */
/* {{{ proto bool imagecopy(resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h)
Copy part of an image */
PHP_FUNCTION(imagecopy)
{
zval *SIM, *DIM;
long SX, SY, SW, SH, DX, DY;
gdImagePtr im_dst, im_src;
int srcH, srcW, srcY, srcX, dstY, dstX;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rrllllll", &DIM, &SIM, &DX, &DY, &SX, &SY, &SW, &SH) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd);
ZEND_FETCH_RESOURCE(im_dst, gdImagePtr, &DIM, -1, "Image", le_gd);
srcX = SX;
srcY = SY;
srcH = SH;
srcW = SW;
dstX = DX;
dstY = DY;
gdImageCopy(im_dst, im_src, dstX, dstY, srcX, srcY, srcW, srcH);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool imagecopymerge(resource src_im, resource dst_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h, int pct)
Merge one part of an image with another */
PHP_FUNCTION(imagecopymerge)
{
zval *SIM, *DIM;
long SX, SY, SW, SH, DX, DY, PCT;
gdImagePtr im_dst, im_src;
int srcH, srcW, srcY, srcX, dstY, dstX, pct;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rrlllllll", &DIM, &SIM, &DX, &DY, &SX, &SY, &SW, &SH, &PCT) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd);
ZEND_FETCH_RESOURCE(im_dst, gdImagePtr, &DIM, -1, "Image", le_gd);
srcX = SX;
srcY = SY;
srcH = SH;
srcW = SW;
dstX = DX;
dstY = DY;
pct = PCT;
gdImageCopyMerge(im_dst, im_src, dstX, dstY, srcX, srcY, srcW, srcH, pct);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool imagecopymergegray(resource src_im, resource dst_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h, int pct)
Merge one part of an image with another */
PHP_FUNCTION(imagecopymergegray)
{
zval *SIM, *DIM;
long SX, SY, SW, SH, DX, DY, PCT;
gdImagePtr im_dst, im_src;
int srcH, srcW, srcY, srcX, dstY, dstX, pct;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rrlllllll", &DIM, &SIM, &DX, &DY, &SX, &SY, &SW, &SH, &PCT) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd);
ZEND_FETCH_RESOURCE(im_dst, gdImagePtr, &DIM, -1, "Image", le_gd);
srcX = SX;
srcY = SY;
srcH = SH;
srcW = SW;
dstX = DX;
dstY = DY;
pct = PCT;
gdImageCopyMergeGray(im_dst, im_src, dstX, dstY, srcX, srcY, srcW, srcH, pct);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool imagecopyresized(resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h)
Copy and resize part of an image */
PHP_FUNCTION(imagecopyresized)
{
zval *SIM, *DIM;
long SX, SY, SW, SH, DX, DY, DW, DH;
gdImagePtr im_dst, im_src;
int srcH, srcW, dstH, dstW, srcY, srcX, dstY, dstX;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rrllllllll", &DIM, &SIM, &DX, &DY, &SX, &SY, &DW, &DH, &SW, &SH) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im_dst, gdImagePtr, &DIM, -1, "Image", le_gd);
ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd);
srcX = SX;
srcY = SY;
srcH = SH;
srcW = SW;
dstX = DX;
dstY = DY;
dstH = DH;
dstW = DW;
if (dstW <= 0 || dstH <= 0 || srcW <= 0 || srcH <= 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid image dimensions");
RETURN_FALSE;
}
gdImageCopyResized(im_dst, im_src, dstX, dstY, srcX, srcY, dstW, dstH, srcW, srcH);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto int imagesx(resource im)
Get image width */
PHP_FUNCTION(imagesx)
{
zval *IM;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &IM) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
RETURN_LONG(gdImageSX(im));
}
/* }}} */
/* {{{ proto int imagesy(resource im)
Get image height */
PHP_FUNCTION(imagesy)
{
zval *IM;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &IM) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
RETURN_LONG(gdImageSY(im));
}
/* }}} */
#ifdef ENABLE_GD_TTF
#define TTFTEXT_DRAW 0
#define TTFTEXT_BBOX 1
#endif
#ifdef ENABLE_GD_TTF
#if HAVE_GD_FREETYPE && HAVE_LIBFREETYPE
/* {{{ proto array imageftbbox(float size, float angle, string font_file, string text [, array extrainfo])
Give the bounding box of a text using fonts via freetype2 */
PHP_FUNCTION(imageftbbox)
{
php_imagettftext_common(INTERNAL_FUNCTION_PARAM_PASSTHRU, TTFTEXT_BBOX, 1);
}
/* }}} */
/* {{{ proto array imagefttext(resource im, float size, float angle, int x, int y, int col, string font_file, string text [, array extrainfo])
Write text to the image using fonts via freetype2 */
PHP_FUNCTION(imagefttext)
{
php_imagettftext_common(INTERNAL_FUNCTION_PARAM_PASSTHRU, TTFTEXT_DRAW, 1);
}
/* }}} */
#endif /* HAVE_GD_FREETYPE && HAVE_LIBFREETYPE */
/* {{{ proto array imagettfbbox(float size, float angle, string font_file, string text)
Give the bounding box of a text using TrueType fonts */
PHP_FUNCTION(imagettfbbox)
{
php_imagettftext_common(INTERNAL_FUNCTION_PARAM_PASSTHRU, TTFTEXT_BBOX, 0);
}
/* }}} */
/* {{{ proto array imagettftext(resource im, float size, float angle, int x, int y, int col, string font_file, string text)
Write text to the image using a TrueType font */
PHP_FUNCTION(imagettftext)
{
php_imagettftext_common(INTERNAL_FUNCTION_PARAM_PASSTHRU, TTFTEXT_DRAW, 0);
}
/* }}} */
/* {{{ php_imagettftext_common
*/
static void php_imagettftext_common(INTERNAL_FUNCTION_PARAMETERS, int mode, int extended)
{
zval *IM, *EXT = NULL;
gdImagePtr im=NULL;
long col = -1, x = -1, y = -1;
int str_len, fontname_len, i, brect[8];
double ptsize, angle;
char *str = NULL, *fontname = NULL;
char *error = NULL;
int argc = ZEND_NUM_ARGS();
gdFTStringExtra strex = {0};
if (mode == TTFTEXT_BBOX) {
if (argc < 4 || argc > ((extended) ? 5 : 4)) {
ZEND_WRONG_PARAM_COUNT();
} else if (zend_parse_parameters(argc TSRMLS_CC, "ddss|a", &ptsize, &angle, &fontname, &fontname_len, &str, &str_len, &EXT) == FAILURE) {
RETURN_FALSE;
}
} else {
if (argc < 8 || argc > ((extended) ? 9 : 8)) {
ZEND_WRONG_PARAM_COUNT();
} else if (zend_parse_parameters(argc TSRMLS_CC, "rddlllss|a", &IM, &ptsize, &angle, &x, &y, &col, &fontname, &fontname_len, &str, &str_len, &EXT) == FAILURE) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
}
/* convert angle to radians */
angle = angle * (M_PI/180);
if (extended && EXT) { /* parse extended info */
HashPosition pos;
/* walk the assoc array */
zend_hash_internal_pointer_reset_ex(HASH_OF(EXT), &pos);
do {
zval ** item;
char * key;
ulong num_key;
if (zend_hash_get_current_key_ex(HASH_OF(EXT), &key, NULL, &num_key, 0, &pos) != HASH_KEY_IS_STRING) {
continue;
}
if (zend_hash_get_current_data_ex(HASH_OF(EXT), (void **) &item, &pos) == FAILURE) {
continue;
}
if (strcmp("linespacing", key) == 0) {
convert_to_double_ex(item);
strex.flags |= gdFTEX_LINESPACE;
strex.linespacing = Z_DVAL_PP(item);
}
} while (zend_hash_move_forward_ex(HASH_OF(EXT), &pos) == SUCCESS);
}
#ifdef VIRTUAL_DIR
{
char tmp_font_path[MAXPATHLEN];
if (!VCWD_REALPATH(fontname, tmp_font_path)) {
fontname = NULL;
}
}
#endif /* VIRTUAL_DIR */
PHP_GD_CHECK_OPEN_BASEDIR(fontname, "Invalid font filename");
#ifdef HAVE_GD_FREETYPE
if (extended) {
error = gdImageStringFTEx(im, brect, col, fontname, ptsize, angle, x, y, str, &strex);
}
else
error = gdImageStringFT(im, brect, col, fontname, ptsize, angle, x, y, str);
#endif /* HAVE_GD_FREETYPE */
if (error) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", error);
RETURN_FALSE;
}
array_init(return_value);
/* return array with the text's bounding box */
for (i = 0; i < 8; i++) {
add_next_index_long(return_value, brect[i]);
}
}
/* }}} */
#endif /* ENABLE_GD_TTF */
#if HAVE_LIBT1
/* {{{ php_free_ps_font
*/
static void php_free_ps_font(zend_rsrc_list_entry *rsrc TSRMLS_DC)
{
int *font = (int *) rsrc->ptr;
T1_DeleteFont(*font);
efree(font);
}
/* }}} */
/* {{{ php_free_ps_enc
*/
static void php_free_ps_enc(zend_rsrc_list_entry *rsrc TSRMLS_DC)
{
char **enc = (char **) rsrc->ptr;
T1_DeleteEncoding(enc);
}
/* }}} */
/* {{{ proto resource imagepsloadfont(string pathname)
Load a new font from specified file */
PHP_FUNCTION(imagepsloadfont)
{
char *file;
int file_len, f_ind, *font;
#ifdef PHP_WIN32
struct stat st;
#endif
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p", &file, &file_len) == FAILURE) {
return;
}
#ifdef PHP_WIN32
if (VCWD_STAT(file, &st) < 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Font file not found (%s)", file);
RETURN_FALSE;
}
#endif
f_ind = T1_AddFont(file);
if (f_ind < 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "T1Lib Error (%i): %s", f_ind, T1_StrError(f_ind));
RETURN_FALSE;
}
if (T1_LoadFont(f_ind)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't load the font");
RETURN_FALSE;
}
font = (int *) emalloc(sizeof(int));
*font = f_ind;
ZEND_REGISTER_RESOURCE(return_value, font, le_ps_font);
}
/* }}} */
/* {{{ proto int imagepscopyfont(int font_index)
Make a copy of a font for purposes like extending or reenconding */
/* The function in t1lib which this function uses seem to be buggy...
PHP_FUNCTION(imagepscopyfont)
{
int l_ind, type;
gd_ps_font *nf_ind, *of_ind;
long fnt;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &fnt) == FAILURE) {
return;
}
of_ind = zend_list_find(fnt, &type);
if (type != le_ps_font) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "%ld is not a Type 1 font index", fnt);
RETURN_FALSE;
}
nf_ind = emalloc(sizeof(gd_ps_font));
nf_ind->font_id = T1_CopyFont(of_ind->font_id);
if (nf_ind->font_id < 0) {
l_ind = nf_ind->font_id;
efree(nf_ind);
switch (l_ind) {
case -1:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "FontID %d is not loaded in memory", l_ind);
RETURN_FALSE;
break;
case -2:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Tried to copy a logical font");
RETURN_FALSE;
break;
case -3:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Memory allocation fault in t1lib");
RETURN_FALSE;
break;
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "An unknown error occurred in t1lib");
RETURN_FALSE;
break;
}
}
nf_ind->extend = 1;
l_ind = zend_list_insert(nf_ind, le_ps_font TSRMLS_CC);
RETURN_LONG(l_ind);
}
*/
/* }}} */
/* {{{ proto bool imagepsfreefont(resource font_index)
Free memory used by a font */
PHP_FUNCTION(imagepsfreefont)
{
zval *fnt;
int *f_ind;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &fnt) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, "Type 1 font", le_ps_font);
zend_list_delete(Z_LVAL_P(fnt));
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool imagepsencodefont(resource font_index, string filename)
To change a fonts character encoding vector */
PHP_FUNCTION(imagepsencodefont)
{
zval *fnt;
char *enc, **enc_vector;
int enc_len, *f_ind;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rp", &fnt, &enc, &enc_len) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, "Type 1 font", le_ps_font);
if ((enc_vector = T1_LoadEncoding(enc)) == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't load encoding vector from %s", enc);
RETURN_FALSE;
}
T1_DeleteAllSizes(*f_ind);
if (T1_ReencodeFont(*f_ind, enc_vector)) {
T1_DeleteEncoding(enc_vector);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't re-encode font");
RETURN_FALSE;
}
zend_list_insert(enc_vector, le_ps_enc TSRMLS_CC);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool imagepsextendfont(resource font_index, float extend)
Extend or or condense (if extend < 1) a font */
PHP_FUNCTION(imagepsextendfont)
{
zval *fnt;
double ext;
int *f_ind;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rd", &fnt, &ext) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, "Type 1 font", le_ps_font);
T1_DeleteAllSizes(*f_ind);
if (ext <= 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Second parameter %F out of range (must be > 0)", ext);
RETURN_FALSE;
}
if (T1_ExtendFont(*f_ind, ext) != 0) {
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool imagepsslantfont(resource font_index, float slant)
Slant a font */
PHP_FUNCTION(imagepsslantfont)
{
zval *fnt;
double slt;
int *f_ind;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rd", &fnt, &slt) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, "Type 1 font", le_ps_font);
if (T1_SlantFont(*f_ind, slt) != 0) {
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto array imagepstext(resource image, string text, resource font, int size, int foreground, int background, int xcoord, int ycoord [, int space [, int tightness [, float angle [, int antialias])
Rasterize a string over an image */
PHP_FUNCTION(imagepstext)
{
zval *img, *fnt;
int i, j;
long _fg, _bg, x, y, size, space = 0, aa_steps = 4, width = 0;
int *f_ind;
int h_lines, v_lines, c_ind;
int rd, gr, bl, fg_rd, fg_gr, fg_bl, bg_rd, bg_gr, bg_bl;
int fg_al, bg_al, al;
int aa[16];
int amount_kern, add_width;
double angle = 0.0, extend;
unsigned long aa_greys[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
gdImagePtr bg_img;
GLYPH *str_img;
T1_OUTLINE *char_path, *str_path;
T1_TMATRIX *transform = NULL;
char *str;
int str_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rsrlllll|lldl", &img, &str, &str_len, &fnt, &size, &_fg, &_bg, &x, &y, &space, &width, &angle, &aa_steps) == FAILURE) {
return;
}
if (aa_steps != 4 && aa_steps != 16) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Antialias steps must be 4 or 16");
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE(bg_img, gdImagePtr, &img, -1, "Image", le_gd);
ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, "Type 1 font", le_ps_font);
/* Ensure that the provided colors are valid */
if (_fg < 0 || (!gdImageTrueColor(bg_img) && _fg > gdImageColorsTotal(bg_img))) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Foreground color index %ld out of range", _fg);
RETURN_FALSE;
}
if (_bg < 0 || (!gdImageTrueColor(bg_img) && _fg > gdImageColorsTotal(bg_img))) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Background color index %ld out of range", _bg);
RETURN_FALSE;
}
fg_rd = gdImageRed (bg_img, _fg);
fg_gr = gdImageGreen(bg_img, _fg);
fg_bl = gdImageBlue (bg_img, _fg);
fg_al = gdImageAlpha(bg_img, _fg);
bg_rd = gdImageRed (bg_img, _bg);
bg_gr = gdImageGreen(bg_img, _bg);
bg_bl = gdImageBlue (bg_img, _bg);
bg_al = gdImageAlpha(bg_img, _bg);
for (i = 0; i < aa_steps; i++) {
rd = bg_rd + (double) (fg_rd - bg_rd) / aa_steps * (i + 1);
gr = bg_gr + (double) (fg_gr - bg_gr) / aa_steps * (i + 1);
bl = bg_bl + (double) (fg_bl - bg_bl) / aa_steps * (i + 1);
al = bg_al + (double) (fg_al - bg_al) / aa_steps * (i + 1);
aa[i] = gdImageColorResolveAlpha(bg_img, rd, gr, bl, al);
}
T1_AASetBitsPerPixel(8);
switch (aa_steps) {
case 4:
T1_AASetGrayValues(0, 1, 2, 3, 4);
T1_AASetLevel(T1_AA_LOW);
break;
case 16:
T1_AAHSetGrayValues(aa_greys);
T1_AASetLevel(T1_AA_HIGH);
break;
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid value %ld as number of steps for antialiasing", aa_steps);
RETURN_FALSE;
}
if (angle) {
transform = T1_RotateMatrix(NULL, angle);
}
if (width) {
extend = T1_GetExtend(*f_ind);
str_path = T1_GetCharOutline(*f_ind, str[0], size, transform);
if (!str_path) {
if (T1_errno) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "T1Lib Error: %s", T1_StrError(T1_errno));
}
RETURN_FALSE;
}
for (i = 1; i < str_len; i++) {
amount_kern = (int) T1_GetKerning(*f_ind, str[i - 1], str[i]);
amount_kern += str[i - 1] == ' ' ? space : 0;
add_width = (int) (amount_kern + width) / extend;
char_path = T1_GetMoveOutline(*f_ind, add_width, 0, 0, size, transform);
str_path = T1_ConcatOutlines(str_path, char_path);
char_path = T1_GetCharOutline(*f_ind, str[i], size, transform);
str_path = T1_ConcatOutlines(str_path, char_path);
}
str_img = T1_AAFillOutline(str_path, 0);
} else {
str_img = T1_AASetString(*f_ind, str, str_len, space, T1_KERNING, size, transform);
}
if (T1_errno) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "T1Lib Error: %s", T1_StrError(T1_errno));
RETURN_FALSE;
}
h_lines = str_img->metrics.ascent - str_img->metrics.descent;
v_lines = str_img->metrics.rightSideBearing - str_img->metrics.leftSideBearing;
for (i = 0; i < v_lines; i++) {
for (j = 0; j < h_lines; j++) {
switch (str_img->bits[j * v_lines + i]) {
case 0:
break;
default:
c_ind = aa[str_img->bits[j * v_lines + i] - 1];
gdImageSetPixel(bg_img, x + str_img->metrics.leftSideBearing + i, y - str_img->metrics.ascent + j, c_ind);
break;
}
}
}
array_init(return_value);
add_next_index_long(return_value, str_img->metrics.leftSideBearing);
add_next_index_long(return_value, str_img->metrics.descent);
add_next_index_long(return_value, str_img->metrics.rightSideBearing);
add_next_index_long(return_value, str_img->metrics.ascent);
}
/* }}} */
/* {{{ proto array imagepsbbox(string text, resource font, int size [, int space, int tightness, float angle])
Return the bounding box needed by a string if rasterized */
PHP_FUNCTION(imagepsbbox)
{
zval *fnt;
long sz = 0, sp = 0, wd = 0;
char *str;
int i, space = 0, add_width = 0, char_width, amount_kern;
int cur_x, cur_y, dx, dy;
int x1, y1, x2, y2, x3, y3, x4, y4;
int *f_ind;
int str_len, per_char = 0;
int argc = ZEND_NUM_ARGS();
double angle = 0, sin_a = 0, cos_a = 0;
BBox char_bbox, str_bbox = {0, 0, 0, 0};
if (argc != 3 && argc != 6) {
ZEND_WRONG_PARAM_COUNT();
}
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "srl|lld", &str, &str_len, &fnt, &sz, &sp, &wd, &angle) == FAILURE) {
return;
}
if (argc == 6) {
space = sp;
add_width = wd;
angle = angle * M_PI / 180;
sin_a = sin(angle);
cos_a = cos(angle);
per_char = add_width || angle ? 1 : 0;
}
ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, "Type 1 font", le_ps_font);
#define max(a, b) (a > b ? a : b)
#define min(a, b) (a < b ? a : b)
#define new_x(a, b) (int) ((a) * cos_a - (b) * sin_a)
#define new_y(a, b) (int) ((a) * sin_a + (b) * cos_a)
if (per_char) {
space += T1_GetCharWidth(*f_ind, ' ');
cur_x = cur_y = 0;
for (i = 0; i < str_len; i++) {
if (str[i] == ' ') {
char_bbox.llx = char_bbox.lly = char_bbox.ury = 0;
char_bbox.urx = char_width = space;
} else {
char_bbox = T1_GetCharBBox(*f_ind, str[i]);
char_width = T1_GetCharWidth(*f_ind, str[i]);
}
amount_kern = i ? T1_GetKerning(*f_ind, str[i - 1], str[i]) : 0;
/* Transfer character bounding box to right place */
x1 = new_x(char_bbox.llx, char_bbox.lly) + cur_x;
y1 = new_y(char_bbox.llx, char_bbox.lly) + cur_y;
x2 = new_x(char_bbox.llx, char_bbox.ury) + cur_x;
y2 = new_y(char_bbox.llx, char_bbox.ury) + cur_y;
x3 = new_x(char_bbox.urx, char_bbox.ury) + cur_x;
y3 = new_y(char_bbox.urx, char_bbox.ury) + cur_y;
x4 = new_x(char_bbox.urx, char_bbox.lly) + cur_x;
y4 = new_y(char_bbox.urx, char_bbox.lly) + cur_y;
/* Find min & max values and compare them with current bounding box */
str_bbox.llx = min(str_bbox.llx, min(x1, min(x2, min(x3, x4))));
str_bbox.lly = min(str_bbox.lly, min(y1, min(y2, min(y3, y4))));
str_bbox.urx = max(str_bbox.urx, max(x1, max(x2, max(x3, x4))));
str_bbox.ury = max(str_bbox.ury, max(y1, max(y2, max(y3, y4))));
/* Move to the next base point */
dx = new_x(char_width + add_width + amount_kern, 0);
dy = new_y(char_width + add_width + amount_kern, 0);
cur_x += dx;
cur_y += dy;
/*
printf("%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n", x1, y1, x2, y2, x3, y3, x4, y4, char_bbox.llx, char_bbox.lly, char_bbox.urx, char_bbox.ury, char_width, amount_kern, cur_x, cur_y, dx, dy);
*/
}
} else {
str_bbox = T1_GetStringBBox(*f_ind, str, str_len, space, T1_KERNING);
}
if (T1_errno) {
RETURN_FALSE;
}
array_init(return_value);
/*
printf("%d %d %d %d\n", str_bbox.llx, str_bbox.lly, str_bbox.urx, str_bbox.ury);
*/
add_next_index_long(return_value, (int) ceil(((double) str_bbox.llx)*sz/1000));
add_next_index_long(return_value, (int) ceil(((double) str_bbox.lly)*sz/1000));
add_next_index_long(return_value, (int) ceil(((double) str_bbox.urx)*sz/1000));
add_next_index_long(return_value, (int) ceil(((double) str_bbox.ury)*sz/1000));
}
/* }}} */
#endif
/* {{{ proto bool image2wbmp(resource im [, string filename [, int threshold]])
Output WBMP image to browser or file */
PHP_FUNCTION(image2wbmp)
{
_php_image_output(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_CONVERT_WBM, "WBMP", _php_image_bw_convert);
}
/* }}} */
#if defined(HAVE_GD_JPG)
/* {{{ proto bool jpeg2wbmp (string f_org, string f_dest, int d_height, int d_width, int threshold)
Convert JPEG image to WBMP image */
PHP_FUNCTION(jpeg2wbmp)
{
_php_image_convert(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_JPG);
}
/* }}} */
#endif
#if defined(HAVE_GD_PNG)
/* {{{ proto bool png2wbmp (string f_org, string f_dest, int d_height, int d_width, int threshold)
Convert PNG image to WBMP image */
PHP_FUNCTION(png2wbmp)
{
_php_image_convert(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_PNG);
}
/* }}} */
#endif
/* {{{ _php_image_bw_convert
* It converts a gd Image to bw using a threshold value */
static void _php_image_bw_convert(gdImagePtr im_org, gdIOCtx *out, int threshold)
{
gdImagePtr im_dest;
int white, black;
int color, color_org, median;
int dest_height = gdImageSY(im_org);
int dest_width = gdImageSX(im_org);
int x, y;
TSRMLS_FETCH();
im_dest = gdImageCreate(dest_width, dest_height);
if (im_dest == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate temporary buffer");
return;
}
white = gdImageColorAllocate(im_dest, 255, 255, 255);
if (white == -1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate the colors for the destination buffer");
return;
}
black = gdImageColorAllocate(im_dest, 0, 0, 0);
if (black == -1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate the colors for the destination buffer");
return;
}
if (im_org->trueColor) {
gdImageTrueColorToPalette(im_org, 1, 256);
}
for (y = 0; y < dest_height; y++) {
for (x = 0; x < dest_width; x++) {
color_org = gdImageGetPixel(im_org, x, y);
median = (im_org->red[color_org] + im_org->green[color_org] + im_org->blue[color_org]) / 3;
if (median < threshold) {
color = black;
} else {
color = white;
}
gdImageSetPixel (im_dest, x, y, color);
}
}
gdImageWBMPCtx (im_dest, black, out);
}
/* }}} */
/* {{{ _php_image_convert
* _php_image_convert converts jpeg/png images to wbmp and resizes them as needed */
static void _php_image_convert(INTERNAL_FUNCTION_PARAMETERS, int image_type )
{
char *f_org, *f_dest;
int f_org_len, f_dest_len;
long height, width, threshold;
gdImagePtr im_org, im_dest, im_tmp;
char *fn_org = NULL;
char *fn_dest = NULL;
FILE *org, *dest;
int dest_height = -1;
int dest_width = -1;
int org_height, org_width;
int white, black;
int color, color_org, median;
int int_threshold;
int x, y;
float x_ratio, y_ratio;
long ignore_warning;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "pplll", &f_org, &f_org_len, &f_dest, &f_dest_len, &height, &width, &threshold) == FAILURE) {
return;
}
fn_org = f_org;
fn_dest = f_dest;
dest_height = height;
dest_width = width;
int_threshold = threshold;
/* Check threshold value */
if (int_threshold < 0 || int_threshold > 8) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid threshold value '%d'", int_threshold);
RETURN_FALSE;
}
/* Check origin file */
PHP_GD_CHECK_OPEN_BASEDIR(fn_org, "Invalid origin filename");
/* Check destination file */
PHP_GD_CHECK_OPEN_BASEDIR(fn_dest, "Invalid destination filename");
/* Open origin file */
org = VCWD_FOPEN(fn_org, "rb");
if (!org) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' for reading", fn_org);
RETURN_FALSE;
}
/* Open destination file */
dest = VCWD_FOPEN(fn_dest, "wb");
if (!dest) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' for writing", fn_dest);
RETURN_FALSE;
}
switch (image_type) {
case PHP_GDIMG_TYPE_GIF:
im_org = gdImageCreateFromGif(org);
if (im_org == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' Not a valid GIF file", fn_dest);
RETURN_FALSE;
}
break;
#ifdef HAVE_GD_JPG
case PHP_GDIMG_TYPE_JPG:
ignore_warning = INI_INT("gd.jpeg_ignore_warning");
im_org = gdImageCreateFromJpegEx(org, ignore_warning);
if (im_org == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' Not a valid JPEG file", fn_dest);
RETURN_FALSE;
}
break;
#endif /* HAVE_GD_JPG */
#ifdef HAVE_GD_PNG
case PHP_GDIMG_TYPE_PNG:
im_org = gdImageCreateFromPng(org);
if (im_org == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' Not a valid PNG file", fn_dest);
RETURN_FALSE;
}
break;
#endif /* HAVE_GD_PNG */
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Format not supported");
RETURN_FALSE;
break;
}
org_width = gdImageSX (im_org);
org_height = gdImageSY (im_org);
x_ratio = (float) org_width / (float) dest_width;
y_ratio = (float) org_height / (float) dest_height;
if (x_ratio > 1 && y_ratio > 1) {
if (y_ratio > x_ratio) {
x_ratio = y_ratio;
} else {
y_ratio = x_ratio;
}
dest_width = (int) (org_width / x_ratio);
dest_height = (int) (org_height / y_ratio);
} else {
x_ratio = (float) dest_width / (float) org_width;
y_ratio = (float) dest_height / (float) org_height;
if (y_ratio < x_ratio) {
x_ratio = y_ratio;
} else {
y_ratio = x_ratio;
}
dest_width = (int) (org_width * x_ratio);
dest_height = (int) (org_height * y_ratio);
}
im_tmp = gdImageCreate (dest_width, dest_height);
if (im_tmp == NULL ) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate temporary buffer");
RETURN_FALSE;
}
gdImageCopyResized (im_tmp, im_org, 0, 0, 0, 0, dest_width, dest_height, org_width, org_height);
gdImageDestroy(im_org);
fclose(org);
im_dest = gdImageCreate(dest_width, dest_height);
if (im_dest == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate destination buffer");
RETURN_FALSE;
}
white = gdImageColorAllocate(im_dest, 255, 255, 255);
if (white == -1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate the colors for the destination buffer");
RETURN_FALSE;
}
black = gdImageColorAllocate(im_dest, 0, 0, 0);
if (black == -1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate the colors for the destination buffer");
RETURN_FALSE;
}
int_threshold = int_threshold * 32;
for (y = 0; y < dest_height; y++) {
for (x = 0; x < dest_width; x++) {
color_org = gdImageGetPixel (im_tmp, x, y);
median = (im_tmp->red[color_org] + im_tmp->green[color_org] + im_tmp->blue[color_org]) / 3;
if (median < int_threshold) {
color = black;
} else {
color = white;
}
gdImageSetPixel (im_dest, x, y, color);
}
}
gdImageDestroy (im_tmp );
gdImageWBMP(im_dest, black , dest);
fflush(dest);
fclose(dest);
gdImageDestroy(im_dest);
RETURN_TRUE;
}
/* }}} */
/* Section Filters */
#define PHP_GD_SINGLE_RES \
zval *SIM; \
gdImagePtr im_src; \
if (zend_parse_parameters(1 TSRMLS_CC, "r", &SIM) == FAILURE) { \
RETURN_FALSE; \
} \
ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); \
if (im_src == NULL) { \
RETURN_FALSE; \
}
static void php_image_filter_negate(INTERNAL_FUNCTION_PARAMETERS)
{
PHP_GD_SINGLE_RES
if (gdImageNegate(im_src) == 1) {
RETURN_TRUE;
}
RETURN_FALSE;
}
static void php_image_filter_grayscale(INTERNAL_FUNCTION_PARAMETERS)
{
PHP_GD_SINGLE_RES
if (gdImageGrayScale(im_src) == 1) {
RETURN_TRUE;
}
RETURN_FALSE;
}
static void php_image_filter_brightness(INTERNAL_FUNCTION_PARAMETERS)
{
zval *SIM;
gdImagePtr im_src;
long brightness, tmp;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zll", &SIM, &tmp, &brightness) == FAILURE) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd);
if (im_src == NULL) {
RETURN_FALSE;
}
if (gdImageBrightness(im_src, (int)brightness) == 1) {
RETURN_TRUE;
}
RETURN_FALSE;
}
static void php_image_filter_contrast(INTERNAL_FUNCTION_PARAMETERS)
{
zval *SIM;
gdImagePtr im_src;
long contrast, tmp;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rll", &SIM, &tmp, &contrast) == FAILURE) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd);
if (im_src == NULL) {
RETURN_FALSE;
}
if (gdImageContrast(im_src, (int)contrast) == 1) {
RETURN_TRUE;
}
RETURN_FALSE;
}
static void php_image_filter_colorize(INTERNAL_FUNCTION_PARAMETERS)
{
zval *SIM;
gdImagePtr im_src;
long r,g,b,tmp;
long a = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rllll|l", &SIM, &tmp, &r, &g, &b, &a) == FAILURE) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd);
if (im_src == NULL) {
RETURN_FALSE;
}
if (gdImageColor(im_src, (int) r, (int) g, (int) b, (int) a) == 1) {
RETURN_TRUE;
}
RETURN_FALSE;
}
static void php_image_filter_edgedetect(INTERNAL_FUNCTION_PARAMETERS)
{
PHP_GD_SINGLE_RES
if (gdImageEdgeDetectQuick(im_src) == 1) {
RETURN_TRUE;
}
RETURN_FALSE;
}
static void php_image_filter_emboss(INTERNAL_FUNCTION_PARAMETERS)
{
PHP_GD_SINGLE_RES
if (gdImageEmboss(im_src) == 1) {
RETURN_TRUE;
}
RETURN_FALSE;
}
static void php_image_filter_gaussian_blur(INTERNAL_FUNCTION_PARAMETERS)
{
PHP_GD_SINGLE_RES
if (gdImageGaussianBlur(im_src) == 1) {
RETURN_TRUE;
}
RETURN_FALSE;
}
static void php_image_filter_selective_blur(INTERNAL_FUNCTION_PARAMETERS)
{
PHP_GD_SINGLE_RES
if (gdImageSelectiveBlur(im_src) == 1) {
RETURN_TRUE;
}
RETURN_FALSE;
}
static void php_image_filter_mean_removal(INTERNAL_FUNCTION_PARAMETERS)
{
PHP_GD_SINGLE_RES
if (gdImageMeanRemoval(im_src) == 1) {
RETURN_TRUE;
}
RETURN_FALSE;
}
static void php_image_filter_smooth(INTERNAL_FUNCTION_PARAMETERS)
{
zval *SIM;
long tmp;
gdImagePtr im_src;
double weight;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rld", &SIM, &tmp, &weight) == FAILURE) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd);
if (im_src == NULL) {
RETURN_FALSE;
}
if (gdImageSmooth(im_src, (float)weight)==1) {
RETURN_TRUE;
}
RETURN_FALSE;
}
static void php_image_filter_pixelate(INTERNAL_FUNCTION_PARAMETERS)
{
zval *IM;
gdImagePtr im;
long tmp, blocksize;
zend_bool mode = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rll|b", &IM, &tmp, &blocksize, &mode) == FAILURE) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
if (im == NULL) {
RETURN_FALSE;
}
if (gdImagePixelate(im, (int) blocksize, (const unsigned int) mode)) {
RETURN_TRUE;
}
RETURN_FALSE;
}
/* {{{ proto bool imagefilter(resource src_im, int filtertype, [args] )
Applies Filter an image using a custom angle */
PHP_FUNCTION(imagefilter)
{
zval *tmp;
typedef void (*image_filter)(INTERNAL_FUNCTION_PARAMETERS);
long filtertype;
image_filter filters[] =
{
php_image_filter_negate ,
php_image_filter_grayscale,
php_image_filter_brightness,
php_image_filter_contrast,
php_image_filter_colorize,
php_image_filter_edgedetect,
php_image_filter_emboss,
php_image_filter_gaussian_blur,
php_image_filter_selective_blur,
php_image_filter_mean_removal,
php_image_filter_smooth,
php_image_filter_pixelate
};
if (ZEND_NUM_ARGS() < 2 || ZEND_NUM_ARGS() > IMAGE_FILTER_MAX_ARGS) {
WRONG_PARAM_COUNT;
} else if (zend_parse_parameters(2 TSRMLS_CC, "rl", &tmp, &filtertype) == FAILURE) {
return;
}
if (filtertype >= 0 && filtertype <= IMAGE_FILTER_MAX) {
filters[filtertype](INTERNAL_FUNCTION_PARAM_PASSTHRU);
}
}
/* }}} */
/* {{{ proto resource imageconvolution(resource src_im, array matrix3x3, double div, double offset)
Apply a 3x3 convolution matrix, using coefficient div and offset */
PHP_FUNCTION(imageconvolution)
{
zval *SIM, *hash_matrix;
zval **var = NULL, **var2 = NULL;
gdImagePtr im_src = NULL;
double div, offset;
int nelem, i, j, res;
float matrix[3][3] = {{0,0,0}, {0,0,0}, {0,0,0}};
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "radd", &SIM, &hash_matrix, &div, &offset) == FAILURE) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd);
nelem = zend_hash_num_elements(Z_ARRVAL_P(hash_matrix));
if (nelem != 3) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have 3x3 array");
RETURN_FALSE;
}
for (i=0; i<3; i++) {
if (zend_hash_index_find(Z_ARRVAL_P(hash_matrix), (i), (void **) &var) == SUCCESS && Z_TYPE_PP(var) == IS_ARRAY) {
if (Z_TYPE_PP(var) != IS_ARRAY || zend_hash_num_elements(Z_ARRVAL_PP(var)) != 3 ) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have 3x3 array");
RETURN_FALSE;
}
for (j=0; j<3; j++) {
if (zend_hash_index_find(Z_ARRVAL_PP(var), (j), (void **) &var2) == SUCCESS) {
if (Z_TYPE_PP(var2) != IS_DOUBLE) {
zval dval;
dval = **var2;
zval_copy_ctor(&dval);
convert_to_double(&dval);
matrix[i][j] = (float)Z_DVAL(dval);
} else {
matrix[i][j] = (float)Z_DVAL_PP(var2);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have a 3x3 matrix");
RETURN_FALSE;
}
}
}
}
res = gdImageConvolution(im_src, matrix, (float)div, (float)offset);
if (res) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
/* }}} */
/* End section: Filters */
/* {{{ proto void imageflip(resource im, int mode)
Flip an image (in place) horizontally, vertically or both directions. */
PHP_FUNCTION(imageflip)
{
zval *IM;
long mode;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &IM, &mode) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
switch (mode) {
case GD_FLIP_VERTICAL:
gdImageFlipVertical(im);
break;
case GD_FLIP_HORINZONTAL:
gdImageFlipHorizontal(im);
break;
case GD_FLIP_BOTH:
gdImageFlipBoth(im);
break;
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown flip mode");
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
#ifdef HAVE_GD_BUNDLED
/* {{{ proto bool imageantialias(resource im, bool on)
Should antialiased functions used or not*/
PHP_FUNCTION(imageantialias)
{
zval *IM;
zend_bool alias;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rb", &IM, &alias) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
gdImageAntialias(im, alias);
RETURN_TRUE;
}
/* }}} */
#endif
/* {{{ proto void imagecrop(resource im, array rect)
Crop an image using the given coordinates and size, x, y, width and height. */
PHP_FUNCTION(imagecrop)
{
zval *IM;
gdImagePtr im;
gdImagePtr im_crop;
gdRect rect;
zval *z_rect;
zval **tmp;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra", &IM, &z_rect) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
if (zend_hash_find(HASH_OF(z_rect), "x", sizeof("x"), (void **)&tmp) != FAILURE) {
if (Z_TYPE_PP(tmp) != IS_LONG) {
zval lval;
lval = **tmp;
zval_copy_ctor(&lval);
convert_to_long(&lval);
rect.x = Z_LVAL(lval);
} else {
rect.x = Z_LVAL_PP(tmp);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing x position");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(z_rect), "y", sizeof("x"), (void **)&tmp) != FAILURE) {
if (Z_TYPE_PP(tmp) != IS_LONG) {
zval lval;
lval = **tmp;
zval_copy_ctor(&lval);
convert_to_long(&lval);
rect.y = Z_LVAL(lval);
} else {
rect.y = Z_LVAL_PP(tmp);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing y position");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(z_rect), "width", sizeof("width"), (void **)&tmp) != FAILURE) {
if (Z_TYPE_PP(tmp) != IS_LONG) {
zval lval;
lval = **tmp;
zval_copy_ctor(&lval);
convert_to_long(&lval);
rect.width = Z_LVAL(lval);
} else {
rect.width = Z_LVAL_PP(tmp);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing width");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(z_rect), "height", sizeof("height"), (void **)&tmp) != FAILURE) {
if (Z_TYPE_PP(tmp) != IS_LONG) {
zval lval;
lval = **tmp;
zval_copy_ctor(&lval);
convert_to_long(&lval);
rect.height = Z_LVAL(lval);
} else {
rect.height = Z_LVAL_PP(tmp);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing height");
RETURN_FALSE;
}
im_crop = gdImageCrop(im, &rect);
if (im_crop == NULL) {
RETURN_FALSE;
} else {
ZEND_REGISTER_RESOURCE(return_value, im_crop, le_gd);
}
}
/* }}} */
/* {{{ proto void imagecropauto(resource im [, int mode [, threshold [, color]]])
Crop an image automatically using one of the available modes. */
PHP_FUNCTION(imagecropauto)
{
zval *IM;
long mode = -1;
long color = -1;
double threshold = 0.5f;
gdImagePtr im;
gdImagePtr im_crop;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|ldl", &IM, &mode, &threshold, &color) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
switch (mode) {
case -1:
mode = GD_CROP_DEFAULT;
case GD_CROP_DEFAULT:
case GD_CROP_TRANSPARENT:
case GD_CROP_BLACK:
case GD_CROP_WHITE:
case GD_CROP_SIDES:
im_crop = gdImageCropAuto(im, mode);
break;
case GD_CROP_THRESHOLD:
if (color < 0 || (!gdImageTrueColor(im) && color >= gdImageColorsTotal(im))) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Color argument missing with threshold mode");
RETURN_FALSE;
}
im_crop = gdImageCropThreshold(im, color, (float) threshold);
break;
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown crop mode");
RETURN_FALSE;
}
if (im_crop == NULL) {
RETURN_FALSE;
} else {
ZEND_REGISTER_RESOURCE(return_value, im_crop, le_gd);
}
}
/* }}} */
/* {{{ proto resource imagescale(resource im, new_width[, new_height[, method]])
Scale an image using the given new width and height. */
PHP_FUNCTION(imagescale)
{
zval *IM;
gdImagePtr im;
gdImagePtr im_scaled = NULL;
int new_width, new_height;
long tmp_w, tmp_h=-1, tmp_m = GD_BILINEAR_FIXED;
gdInterpolationMethod method;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl|ll", &IM, &tmp_w, &tmp_h, &tmp_m) == FAILURE) {
return;
}
method = tmp_m;
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
if (tmp_h < 0) {
/* preserve ratio */
long src_x, src_y;
src_x = gdImageSX(im);
src_y = gdImageSY(im);
if (src_x) {
tmp_h = tmp_w * src_y / src_x;
}
}
if (tmp_h <= 0 || tmp_w <= 0) {
RETURN_FALSE;
}
new_width = tmp_w;
new_height = tmp_h;
if (gdImageSetInterpolationMethod(im, method)) {
im_scaled = gdImageScale(im, new_width, new_height);
}
if (im_scaled == NULL) {
RETURN_FALSE;
} else {
ZEND_REGISTER_RESOURCE(return_value, im_scaled, le_gd);
}
}
/* }}} */
/* {{{ proto resource imageaffine(resource src, array affine[, array clip])
Return an image containing the affine tramsformed src image, using an optional clipping area */
PHP_FUNCTION(imageaffine)
{
zval *IM;
gdImagePtr src;
gdImagePtr dst;
gdRect rect;
gdRectPtr pRect = NULL;
zval *z_rect = NULL;
zval *z_affine;
zval **tmp;
double affine[6];
int i, nelems;
zval **zval_affine_elem = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra|a", &IM, &z_affine, &z_rect) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(src, gdImagePtr, &IM, -1, "Image", le_gd);
if ((nelems = zend_hash_num_elements(Z_ARRVAL_P(z_affine))) != 6) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Affine array must have six elements");
RETURN_FALSE;
}
for (i = 0; i < nelems; i++) {
if (zend_hash_index_find(Z_ARRVAL_P(z_affine), i, (void **) &zval_affine_elem) == SUCCESS) {
switch (Z_TYPE_PP(zval_affine_elem)) {
case IS_LONG:
affine[i] = Z_LVAL_PP(zval_affine_elem);
break;
case IS_DOUBLE:
affine[i] = Z_DVAL_PP(zval_affine_elem);
break;
case IS_STRING:
{
zval dval;
dval = **zval_affine_elem;
zval_copy_ctor(&dval);
convert_to_double(&dval);
affine[i] = Z_DVAL(dval);
}
break;
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %i", i);
RETURN_FALSE;
}
}
}
if (z_rect != NULL) {
if (zend_hash_find(HASH_OF(z_rect), "x", sizeof("x"), (void **)&tmp) != FAILURE) {
if (Z_TYPE_PP(tmp) != IS_LONG) {
zval lval;
lval = **tmp;
zval_copy_ctor(&lval);
convert_to_long(&lval);
rect.x = Z_LVAL(lval);
} else {
rect.x = Z_LVAL_PP(tmp);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing x position");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(z_rect), "y", sizeof("x"), (void **)&tmp) != FAILURE) {
if (Z_TYPE_PP(tmp) != IS_LONG) {
zval lval;
lval = **tmp;
zval_copy_ctor(&lval);
convert_to_long(&lval);
rect.y = Z_LVAL(lval);
} else {
rect.y = Z_LVAL_PP(tmp);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing y position");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(z_rect), "width", sizeof("width"), (void **)&tmp) != FAILURE) {
if (Z_TYPE_PP(tmp) != IS_LONG) {
zval lval;
lval = **tmp;
zval_copy_ctor(&lval);
convert_to_long(&lval);
rect.width = Z_LVAL(lval);
} else {
rect.width = Z_LVAL_PP(tmp);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing width");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(z_rect), "height", sizeof("height"), (void **)&tmp) != FAILURE) {
if (Z_TYPE_PP(tmp) != IS_LONG) {
zval lval;
lval = **tmp;
zval_copy_ctor(&lval);
convert_to_long(&lval);
rect.height = Z_LVAL(lval);
} else {
rect.height = Z_LVAL_PP(tmp);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing height");
RETURN_FALSE;
}
pRect = ▭
} else {
rect.x = -1;
rect.y = -1;
rect.width = gdImageSX(src);
rect.height = gdImageSY(src);
pRect = NULL;
}
if (gdTransformAffineGetImage(&dst, src, pRect, affine) != GD_TRUE) {
RETURN_FALSE;
}
if (dst == NULL) {
RETURN_FALSE;
} else {
ZEND_REGISTER_RESOURCE(return_value, dst, le_gd);
}
}
/* }}} */
/* {{{ proto array imageaffinematrixget(type[, options])
Return an image containing the affine tramsformed src image, using an optional clipping area */
PHP_FUNCTION(imageaffinematrixget)
{
double affine[6];
long type;
zval *options = NULL;
zval **tmp;
int res = GD_FALSE, i;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|z", &type, &options) == FAILURE) {
return;
}
switch((gdAffineStandardMatrix)type) {
case GD_AFFINE_TRANSLATE:
case GD_AFFINE_SCALE: {
double x, y;
if (!options || Z_TYPE_P(options) != IS_ARRAY) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array expected as options");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(options), "x", sizeof("x"), (void **)&tmp) != FAILURE) {
if (Z_TYPE_PP(tmp) != IS_DOUBLE) {
zval dval;
dval = **tmp;
zval_copy_ctor(&dval);
convert_to_double(&dval);
x = Z_DVAL(dval);
} else {
x = Z_DVAL_PP(tmp);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing x position");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(options), "y", sizeof("y"), (void **)&tmp) != FAILURE) {
if (Z_TYPE_PP(tmp) != IS_DOUBLE) {
zval dval;
dval = **tmp;
zval_copy_ctor(&dval);
convert_to_double(&dval);
y = Z_DVAL(dval);
} else {
y = Z_DVAL_PP(tmp);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing y position");
RETURN_FALSE;
}
if (type == GD_AFFINE_TRANSLATE) {
res = gdAffineTranslate(affine, x, y);
} else {
res = gdAffineScale(affine, x, y);
}
break;
}
case GD_AFFINE_ROTATE:
case GD_AFFINE_SHEAR_HORIZONTAL:
case GD_AFFINE_SHEAR_VERTICAL: {
double angle;
if (!options) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Number is expected as option");
RETURN_FALSE;
}
if(Z_TYPE_P(options) != IS_DOUBLE) {
zval dval;
dval = *options;
zval_copy_ctor(&dval);
convert_to_double(&dval);
angle = Z_DVAL(dval);
} else {
angle = Z_DVAL_P(options);
}
if (type == GD_AFFINE_SHEAR_HORIZONTAL) {
res = gdAffineShearHorizontal(affine, angle);
} else if (type == GD_AFFINE_SHEAR_VERTICAL) {
res = gdAffineShearVertical(affine, angle);
} else {
res = gdAffineRotate(affine, angle);
}
break;
}
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %li", type);
RETURN_FALSE;
}
if (res == GD_FALSE) {
RETURN_FALSE;
} else {
array_init(return_value);
for (i = 0; i < 6; i++) {
add_index_double(return_value, i, affine[i]);
}
}
}
/* {{{ proto array imageaffineconcat(array m1, array m2)
Concat two matrices (as in doing many ops in one go) */
PHP_FUNCTION(imageaffinematrixconcat)
{
double m1[6];
double m2[6];
double mr[6];
zval **tmp;
zval *z_m1;
zval *z_m2;
int i, nelems;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "aa", &z_m1, &z_m2) == FAILURE) {
return;
}
if (((nelems = zend_hash_num_elements(Z_ARRVAL_P(z_m1))) != 6) || (nelems = zend_hash_num_elements(Z_ARRVAL_P(z_m2))) != 6) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Affine arrays must have six elements");
RETURN_FALSE;
}
for (i = 0; i < 6; i++) {
if (zend_hash_index_find(Z_ARRVAL_P(z_m1), i, (void **) &tmp) == SUCCESS) {
switch (Z_TYPE_PP(tmp)) {
case IS_LONG:
m1[i] = Z_LVAL_PP(tmp);
break;
case IS_DOUBLE:
m1[i] = Z_DVAL_PP(tmp);
break;
case IS_STRING:
{
zval dval;
dval = **tmp;
zval_copy_ctor(&dval);
convert_to_double(&dval);
m1[i] = Z_DVAL(dval);
}
break;
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %i", i);
RETURN_FALSE;
}
}
if (zend_hash_index_find(Z_ARRVAL_P(z_m2), i, (void **) &tmp) == SUCCESS) {
switch (Z_TYPE_PP(tmp)) {
case IS_LONG:
m2[i] = Z_LVAL_PP(tmp);
break;
case IS_DOUBLE:
m2[i] = Z_DVAL_PP(tmp);
break;
case IS_STRING:
{
zval dval;
dval = **tmp;
zval_copy_ctor(&dval);
convert_to_double(&dval);
m2[i] = Z_DVAL(dval);
}
break;
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %i", i);
RETURN_FALSE;
}
}
}
if (gdAffineConcat (mr, m1, m2) != GD_TRUE) {
RETURN_FALSE;
}
array_init(return_value);
for (i = 0; i < 6; i++) {
add_index_double(return_value, i, mr[i]);
}
}
/* {{{ proto resource imagesetinterpolation(resource im, [, method]])
Set the default interpolation method, passing -1 or 0 sets it to the libgd default (bilinear). */
PHP_FUNCTION(imagesetinterpolation)
{
zval *IM;
gdImagePtr im;
long method = GD_BILINEAR_FIXED;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|l", &IM, &method) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
if (method == -1) {
method = GD_BILINEAR_FIXED;
}
RETURN_BOOL(gdImageSetInterpolationMethod(im, (gdInterpolationMethod) method));
}
/* }}} */
/*
* 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-787/c/good_5257_0 |
crossvul-cpp_data_bad_1881_0 | /*
* $Id: pam_radius_auth.c,v 1.39 2007/03/26 05:35:31 fcusack Exp $
* pam_radius_auth
* Authenticate a user via a RADIUS session
*
* 0.9.0 - Didn't compile quite right.
* 0.9.1 - Hands off passwords properly. Solaris still isn't completely happy
* 0.9.2 - Solaris now does challenge-response. Added configuration file
* handling, and skip_passwd field
* 1.0.0 - Added handling of port name/number, and continue on select
* 1.1.0 - more options, password change requests work now, too.
* 1.1.1 - Added client_id=foo (NAS-Identifier), defaulting to PAM_SERVICE
* 1.1.2 - multi-server capability.
* 1.2.0 - ugly merger of pam_radius.c to get full RADIUS capability
* 1.3.0 - added my own accounting code. Simple, clean, and neat.
* 1.3.1 - Supports accounting port (oops!), and do accounting authentication
* 1.3.2 - added support again for 'skip_passwd' control flag.
* 1.3.10 - ALWAYS add Password attribute, to make packets RFC compliant.
* 1.3.11 - Bug fixes by Jon Nelson <jnelson@securepipe.com>
* 1.3.12 - miscellanous bug fixes. Don't add password to accounting
* requests; log more errors; add NAS-Port and NAS-Port-Type
* attributes to ALL packets. Some patches based on input from
* Grzegorz Paszka <Grzegorz.Paszka@pik-net.pl>
* 1.3.13 - Always update the configuration file, even if we're given
* no options. Patch from Jon Nelson <jnelson@securepipe.com>
* 1.3.14 - Don't use PATH_MAX, so it builds on GNU Hurd.
* 1.3.15 - Implement retry option, miscellanous bug fixes.
* 1.3.16 - Miscellaneous fixes (see CVS for history)
* 1.3.17 - Security fixes
* 1.4.0 - bind to any open port, add add force_prompt, max_challenge, prompt options
*
*
* 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
*
* The original pam_radius.c code is copyright (c) Cristian Gafton, 1996,
* <gafton@redhat.com>
*
* Some challenge-response code is copyright (c) CRYPTOCard Inc, 1998.
* All rights reserved.
*/
#define PAM_SM_AUTH
#define PAM_SM_PASSWORD
#define PAM_SM_SESSION
#include <limits.h>
#include <errno.h>
#include <sys/time.h>
#include "pam_radius_auth.h"
#define DPRINT if (opt_debug & PAM_DEBUG_ARG) _pam_log
/* internal data */
static CONST char *pam_module_name = "pam_radius_auth";
static char conf_file[BUFFER_SIZE]; /* configuration file */
static int opt_debug = FALSE; /* print debug info */
/* we need to save these from open_session to close_session, since
* when close_session will be called we won't be root anymore and
* won't be able to access again the radius server configuration file
* -- cristiang */
static radius_server_t *live_server = NULL;
static time_t session_time;
/* logging */
static void _pam_log(int err, CONST char *format, ...)
{
va_list args;
char buffer[BUFFER_SIZE];
va_start(args, format);
vsprintf(buffer, format, args);
/* don't do openlog or closelog, but put our name in to be friendly */
syslog(err, "%s: %s", pam_module_name, buffer);
va_end(args);
}
/* argument parsing */
static int _pam_parse(int argc, CONST char **argv, radius_conf_t *conf)
{
int ctrl=0;
memset(conf, 0, sizeof(radius_conf_t)); /* ensure it's initialized */
strcpy(conf_file, CONF_FILE);
/* set the default prompt */
snprintf(conf->prompt, MAXPROMPT, "%s: ", DEFAULT_PROMPT);
/*
* If either is not there, then we can't parse anything.
*/
if ((argc == 0) || (argv == NULL)) {
return ctrl;
}
/* step through arguments */
for (ctrl=0; argc-- > 0; ++argv) {
/* generic options */
if (!strncmp(*argv,"conf=",5)) {
/* protect against buffer overflow */
if (strlen(*argv+5) >= sizeof(conf_file)) {
_pam_log(LOG_ERR, "conf= argument too long");
conf_file[0] = 0;
return 0;
}
strcpy(conf_file,*argv+5);
} else if (!strcmp(*argv, "use_first_pass")) {
ctrl |= PAM_USE_FIRST_PASS;
} else if (!strcmp(*argv, "try_first_pass")) {
ctrl |= PAM_TRY_FIRST_PASS;
} else if (!strcmp(*argv, "skip_passwd")) {
ctrl |= PAM_SKIP_PASSWD;
} else if (!strncmp(*argv, "retry=", 6)) {
conf->retries = atoi(*argv+6);
} else if (!strcmp(*argv, "localifdown")) {
conf->localifdown = 1;
} else if (!strncmp(*argv, "client_id=", 10)) {
if (conf->client_id) {
_pam_log(LOG_WARNING, "ignoring duplicate '%s'", *argv);
} else {
conf->client_id = (char *) *argv+10; /* point to the client-id */
}
} else if (!strcmp(*argv, "accounting_bug")) {
conf->accounting_bug = TRUE;
} else if (!strcmp(*argv, "ruser")) {
ctrl |= PAM_RUSER_ARG;
} else if (!strcmp(*argv, "debug")) {
ctrl |= PAM_DEBUG_ARG;
conf->debug = 1;
opt_debug = TRUE;
} else if (!strncmp(*argv, "prompt=", 7)) {
if (!strncmp(conf->prompt, (char*)*argv+7, MAXPROMPT)) {
_pam_log(LOG_WARNING, "ignoring duplicate '%s'", *argv);
} else {
/* truncate excessive prompts to (MAXPROMPT - 3) length */
if (strlen((char*)*argv+7) >= (MAXPROMPT - 3)) {
*((char*)*argv+7 + (MAXPROMPT - 3)) = 0;
}
/* set the new prompt */
memset(conf->prompt, 0, sizeof(conf->prompt));
snprintf(conf->prompt, MAXPROMPT, "%s: ", (char*)*argv+7);
}
} else if (!strcmp(*argv, "force_prompt")) {
conf->force_prompt= TRUE;
} else if (!strncmp(*argv, "max_challenge=", 14)) {
conf->max_challenge = atoi(*argv+14);
} else {
_pam_log(LOG_WARNING, "unrecognized option '%s'", *argv);
}
}
return ctrl;
}
/* Callback function used to free the saved return value for pam_setcred. */
void _int_free(pam_handle_t * pamh, void *x, int error_status)
{
free(x);
}
/*************************************************************************
* SMALL HELPER FUNCTIONS
*************************************************************************/
/*
* Return an IP address in host long notation from
* one supplied in standard dot notation.
*/
static uint32_t ipstr2long(char *ip_str) {
char buf[6];
char *ptr;
int i;
int count;
uint32_t ipaddr;
int cur_byte;
ipaddr = (uint32_t)0;
for(i = 0;i < 4;i++) {
ptr = buf;
count = 0;
*ptr = '\0';
while(*ip_str != '.' && *ip_str != '\0' && count < 4) {
if (!isdigit(*ip_str)) {
return (uint32_t)0;
}
*ptr++ = *ip_str++;
count++;
}
if (count >= 4 || count == 0) {
return (uint32_t)0;
}
*ptr = '\0';
cur_byte = atoi(buf);
if (cur_byte < 0 || cur_byte > 255) {
return (uint32_t)0;
}
ip_str++;
ipaddr = ipaddr << 8 | (uint32_t)cur_byte;
}
return ipaddr;
}
/*
* Check for valid IP address in standard dot notation.
*/
static int good_ipaddr(char *addr) {
int dot_count;
int digit_count;
dot_count = 0;
digit_count = 0;
while(*addr != '\0' && *addr != ' ') {
if (*addr == '.') {
dot_count++;
digit_count = 0;
} else if (!isdigit(*addr)) {
dot_count = 5;
} else {
digit_count++;
if (digit_count > 3) {
dot_count = 5;
}
}
addr++;
}
if (dot_count != 3) {
return -1;
} else {
return 0;
}
}
/*
* Return an IP address in host long notation from a host
* name or address in dot notation.
*/
static uint32_t get_ipaddr(char *host) {
struct hostent *hp;
if (good_ipaddr(host) == 0) {
return ipstr2long(host);
} else if ((hp = gethostbyname(host)) == (struct hostent *)NULL) {
return (uint32_t)0;
}
return ntohl(*(uint32_t *)hp->h_addr);
}
/*
* take server->hostname, and convert it to server->ip and server->port
*/
static int host2server(radius_server_t *server)
{
char *p;
if ((p = strchr(server->hostname, ':')) != NULL) {
*(p++) = '\0'; /* split the port off from the host name */
}
if ((server->ip.s_addr = get_ipaddr(server->hostname)) == ((uint32_t)0)) {
DPRINT(LOG_DEBUG, "DEBUG: get_ipaddr(%s) returned 0.\n", server->hostname);
return PAM_AUTHINFO_UNAVAIL;
}
/*
* If the server port hasn't already been defined, go get it.
*/
if (!server->port) {
if (p && isdigit(*p)) { /* the port looks like it's a number */
unsigned int i = atoi(p) & 0xffff;
if (!server->accounting) {
server->port = htons((uint16_t) i);
} else {
server->port = htons((uint16_t) (i + 1));
}
} else { /* the port looks like it's a name */
struct servent *svp;
if (p) { /* maybe it's not "radius" */
svp = getservbyname (p, "udp");
/* quotes allow distinction from above, lest p be radius or radacct */
DPRINT(LOG_DEBUG, "DEBUG: getservbyname('%s', udp) returned %p.\n", p, svp);
*(--p) = ':'; /* be sure to put the delimiter back */
} else {
if (!server->accounting) {
svp = getservbyname ("radius", "udp");
DPRINT(LOG_DEBUG, "DEBUG: getservbyname(radius, udp) returned %p.\n", svp);
} else {
svp = getservbyname ("radacct", "udp");
DPRINT(LOG_DEBUG, "DEBUG: getservbyname(radacct, udp) returned %p.\n", svp);
}
}
if (svp == (struct servent *) 0) {
/* debugging above... */
return PAM_AUTHINFO_UNAVAIL;
}
server->port = svp->s_port;
}
}
return PAM_SUCCESS;
}
/*
* Do XOR of two buffers.
*/
static unsigned char * xor(unsigned char *p, unsigned char *q, int length)
{
int i;
unsigned char *retval = p;
for (i = 0; i < length; i++) {
*(p++) ^= *(q++);
}
return retval;
}
/**************************************************************************
* MID-LEVEL RADIUS CODE
**************************************************************************/
/*
* get a pseudo-random vector.
*/
static void get_random_vector(unsigned char *vector)
{
#ifdef linux
int fd = open("/dev/urandom",O_RDONLY); /* Linux: get *real* random numbers */
int total = 0;
if (fd >= 0) {
while (total < AUTH_VECTOR_LEN) {
int bytes = read(fd, vector + total, AUTH_VECTOR_LEN - total);
if (bytes <= 0)
break; /* oops! Error */
total += bytes;
}
close(fd);
}
if (total != AUTH_VECTOR_LEN)
#endif
{ /* do this *always* on other platforms */
MD5_CTX my_md5;
struct timeval tv;
struct timezone tz;
static unsigned int session = 0; /* make the number harder to guess */
/* Use the time of day with the best resolution the system can
give us -- often close to microsecond accuracy. */
gettimeofday(&tv,&tz);
if (session == 0) {
session = getppid(); /* (possibly) hard to guess information */
}
tv.tv_sec ^= getpid() * session++;
/* Hash things to get maybe cryptographically strong pseudo-random numbers */
MD5Init(&my_md5);
MD5Update(&my_md5, (unsigned char *) &tv, sizeof(tv));
MD5Update(&my_md5, (unsigned char *) &tz, sizeof(tz));
MD5Final(vector, &my_md5); /* set the final vector */
}
}
/*
* RFC 2139 says to do generate the accounting request vector this way.
* However, the Livingston 1.16 server doesn't check it. The Cistron
* server (http://home.cistron.nl/~miquels/radius/) does, and this code
* seems to work with it. It also works with Funk's Steel-Belted RADIUS.
*/
static void get_accounting_vector(AUTH_HDR *request, radius_server_t *server)
{
MD5_CTX my_md5;
int secretlen = strlen(server->secret);
int len = ntohs(request->length);
memset(request->vector, 0, AUTH_VECTOR_LEN);
MD5Init(&my_md5);
memcpy(((char *)request) + len, server->secret, secretlen);
MD5Update(&my_md5, (unsigned char *)request, len + secretlen);
MD5Final(request->vector, &my_md5); /* set the final vector */
}
/*
* Verify the response from the server
*/
static int verify_packet(char *secret, AUTH_HDR *response, AUTH_HDR *request)
{
MD5_CTX my_md5;
unsigned char calculated[AUTH_VECTOR_LEN];
unsigned char reply[AUTH_VECTOR_LEN];
/*
* We could dispense with the memcpy, and do MD5's of the packet
* + vector piece by piece. This is easier understand, and maybe faster.
*/
memcpy(reply, response->vector, AUTH_VECTOR_LEN); /* save the reply */
memcpy(response->vector, request->vector, AUTH_VECTOR_LEN); /* sent vector */
/* MD5(response packet header + vector + response packet data + secret) */
MD5Init(&my_md5);
MD5Update(&my_md5, (unsigned char *) response, ntohs(response->length));
/*
* This next bit is necessary because of a bug in the original Livingston
* RADIUS server. The authentication vector is *supposed* to be MD5'd
* with the old password (as the secret) for password changes.
* However, the old password isn't used. The "authentication" vector
* for the server reply packet is simply the MD5 of the reply packet.
* Odd, the code is 99% there, but the old password is never copied
* to the secret!
*/
if (*secret) {
MD5Update(&my_md5, (unsigned char *) secret, strlen(secret));
}
MD5Final(calculated, &my_md5); /* set the final vector */
/* Did he use the same random vector + shared secret? */
if (memcmp(calculated, reply, AUTH_VECTOR_LEN) != 0) {
return FALSE;
}
return TRUE;
}
/*
* Find an attribute in a RADIUS packet. Note that the packet length
* is *always* kept in network byte order.
*/
static attribute_t *find_attribute(AUTH_HDR *response, unsigned char type)
{
attribute_t *attr = (attribute_t *) &response->data;
int len = ntohs(response->length) - AUTH_HDR_LEN;
while (attr->attribute != type) {
if ((len -= attr->length) <= 0) {
return NULL; /* not found */
}
attr = (attribute_t *) ((char *) attr + attr->length);
}
return attr;
}
/*
* Add an attribute to a RADIUS packet.
*/
static void add_attribute(AUTH_HDR *request, unsigned char type, CONST unsigned char *data, int length)
{
attribute_t *p;
p = (attribute_t *) ((unsigned char *)request + ntohs(request->length));
p->attribute = type;
p->length = length + 2; /* the total size of the attribute */
request->length = htons(ntohs(request->length) + p->length);
memcpy(p->data, data, length);
}
/*
* Add an integer attribute to a RADIUS packet.
*/
static void add_int_attribute(AUTH_HDR *request, unsigned char type, int data)
{
int value = htonl(data);
add_attribute(request, type, (unsigned char *) &value, sizeof(int));
}
/*
* Add a RADIUS password attribute to the packet. Some magic is done here.
*
* If it's an PW_OLD_PASSWORD attribute, it's encrypted using the encrypted
* PW_PASSWORD attribute as the initialization vector.
*
* If the password attribute already exists, it's over-written. This allows
* us to simply call add_password to update the password for different
* servers.
*/
static void add_password(AUTH_HDR *request, unsigned char type, CONST char *password, char *secret)
{
MD5_CTX md5_secret, my_md5;
unsigned char misc[AUTH_VECTOR_LEN];
int i;
int length = strlen(password);
unsigned char hashed[256 + AUTH_PASS_LEN]; /* can't be longer than this */
unsigned char *vector;
attribute_t *attr;
if (length > MAXPASS) { /* shorten the password for now */
length = MAXPASS;
}
if (length == 0) {
length = AUTH_PASS_LEN; /* 0 maps to 16 */
} if ((length & (AUTH_PASS_LEN - 1)) != 0) {
length += (AUTH_PASS_LEN - 1); /* round it up */
length &= ~(AUTH_PASS_LEN - 1); /* chop it off */
} /* 16*N maps to itself */
memset(hashed, 0, length);
memcpy(hashed, password, strlen(password));
attr = find_attribute(request, PW_PASSWORD);
if (type == PW_PASSWORD) {
vector = request->vector;
} else {
vector = attr->data; /* attr CANNOT be NULL here. */
}
/* ************************************************************ */
/* encrypt the password */
/* password : e[0] = p[0] ^ MD5(secret + vector) */
MD5Init(&md5_secret);
MD5Update(&md5_secret, (unsigned char *) secret, strlen(secret));
my_md5 = md5_secret; /* so we won't re-do the hash later */
MD5Update(&my_md5, vector, AUTH_VECTOR_LEN);
MD5Final(misc, &my_md5); /* set the final vector */
xor(hashed, misc, AUTH_PASS_LEN);
/* For each step through, e[i] = p[i] ^ MD5(secret + e[i-1]) */
for (i = 1; i < (length >> 4); i++) {
my_md5 = md5_secret; /* grab old value of the hash */
MD5Update(&my_md5, &hashed[(i-1) * AUTH_PASS_LEN], AUTH_PASS_LEN);
MD5Final(misc, &my_md5); /* set the final vector */
xor(&hashed[i * AUTH_PASS_LEN], misc, AUTH_PASS_LEN);
}
if (type == PW_OLD_PASSWORD) {
attr = find_attribute(request, PW_OLD_PASSWORD);
}
if (!attr) {
add_attribute(request, type, hashed, length);
} else {
memcpy(attr->data, hashed, length); /* overwrite the packet */
}
}
static void cleanup(radius_server_t *server)
{
radius_server_t *next;
while (server) {
next = server->next;
_pam_drop(server->hostname);
_pam_forget(server->secret);
_pam_drop(server);
server = next;
}
}
/*
* allocate and open a local port for communication with the RADIUS
* server
*/
static int initialize(radius_conf_t *conf, int accounting)
{
struct sockaddr salocal;
char hostname[BUFFER_SIZE];
char secret[BUFFER_SIZE];
char buffer[BUFFER_SIZE];
char *p;
FILE *fserver;
radius_server_t *server = NULL;
struct sockaddr_in * s_in;
int timeout;
int line = 0;
/* the first time around, read the configuration file */
if ((fserver = fopen (conf_file, "r")) == (FILE*)NULL) {
_pam_log(LOG_ERR, "Could not open configuration file %s: %s\n",
conf_file, strerror(errno));
return PAM_ABORT;
}
while (!feof(fserver) && (fgets (buffer, sizeof(buffer), fserver) != (char*) NULL) && (!ferror(fserver))) {
line++;
p = buffer;
/*
* Skip blank lines and whitespace
*/
while (*p && ((*p == ' ') || (*p == '\t') || (*p == '\r') || (*p == '\n'))) {
p++;
}
/*
* Nothing, or just a comment. Ignore the line.
*/
if ((!*p) || (*p == '#')) {
continue;
}
timeout = 3;
if (sscanf(p, "%s %s %d", hostname, secret, &timeout) < 2) {
_pam_log(LOG_ERR, "ERROR reading %s, line %d: Could not read hostname or secret\n",
conf_file, line);
continue; /* invalid line */
} else { /* read it in and save the data */
radius_server_t *tmp;
tmp = malloc(sizeof(radius_server_t));
if (server) {
server->next = tmp;
server = server->next;
} else {
conf->server = tmp;
server= tmp; /* first time */
}
/* sometime later do memory checks here */
server->hostname = strdup(hostname);
server->secret = strdup(secret);
server->accounting = accounting;
server->port = 0;
if ((timeout < 1) || (timeout > 60)) {
server->timeout = 3;
} else {
server->timeout = timeout;
}
server->next = NULL;
}
}
fclose(fserver);
if (!server) { /* no server found, die a horrible death */
_pam_log(LOG_ERR, "No RADIUS server found in configuration file %s\n",
conf_file);
return PAM_AUTHINFO_UNAVAIL;
}
/* open a socket. Dies if it fails */
conf->sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (conf->sockfd < 0) {
_pam_log(LOG_ERR, "Failed to open RADIUS socket: %s\n", strerror(errno));
return PAM_AUTHINFO_UNAVAIL;
}
/* set up the local end of the socket communications */
s_in = (struct sockaddr_in *) &salocal;
memset ((char *) s_in, '\0', sizeof(struct sockaddr));
s_in->sin_family = AF_INET;
s_in->sin_addr.s_addr = INADDR_ANY;
s_in->sin_port = 0;
if (bind(conf->sockfd, &salocal, sizeof (struct sockaddr_in)) < 0) {
_pam_log(LOG_ERR, "Failed binding to port: %s", strerror(errno));
close(conf->sockfd);
return PAM_AUTHINFO_UNAVAIL;
}
return PAM_SUCCESS;
}
/*
* Helper function for building a radius packet.
* It initializes *some* of the header, and adds common attributes.
*/
static void build_radius_packet(AUTH_HDR *request, CONST char *user, CONST char *password, radius_conf_t *conf)
{
char hostname[256];
uint32_t ipaddr;
hostname[0] = '\0';
gethostname(hostname, sizeof(hostname) - 1);
request->length = htons(AUTH_HDR_LEN);
if (password) { /* make a random authentication req vector */
get_random_vector(request->vector);
}
add_attribute(request, PW_USER_NAME, (unsigned char *) user, strlen(user));
/*
* Add a password, if given.
*/
if (password) {
add_password(request, PW_PASSWORD, password, conf->server->secret);
/*
* Add a NULL password to non-accounting requests.
*/
} else if (request->code != PW_ACCOUNTING_REQUEST) {
add_password(request, PW_PASSWORD, "", conf->server->secret);
}
/* the packet is from localhost if on localhost, to make configs easier */
if ((conf->server->ip.s_addr == ntohl(0x7f000001)) || (!hostname[0])) {
ipaddr = 0x7f000001;
} else {
struct hostent *hp;
if ((hp = gethostbyname(hostname)) == (struct hostent *) NULL) {
ipaddr = 0x00000000; /* no client IP address */
} else {
ipaddr = ntohl(*(uint32_t *) hp->h_addr); /* use the first one available */
}
}
/* If we can't find an IP address, then don't add one */
if (ipaddr) {
add_int_attribute(request, PW_NAS_IP_ADDRESS, ipaddr);
}
/* There's always a NAS identifier */
if (conf->client_id && *conf->client_id) {
add_attribute(request, PW_NAS_IDENTIFIER, (unsigned char *) conf->client_id, strlen(conf->client_id));
}
/*
* Add in the port (pid) and port type (virtual).
*
* We might want to give the TTY name here, too.
*/
add_int_attribute(request, PW_NAS_PORT_ID, getpid());
add_int_attribute(request, PW_NAS_PORT_TYPE, PW_NAS_PORT_TYPE_VIRTUAL);
}
/*
* Talk RADIUS to a server.
* Send a packet and get the response
*/
static int talk_radius(radius_conf_t *conf, AUTH_HDR *request, AUTH_HDR *response,
char *password, char *old_password, int tries)
{
socklen_t salen;
int total_length;
fd_set set;
struct timeval tv;
time_t now, end;
int rcode;
struct sockaddr saremote;
struct sockaddr_in *s_in = (struct sockaddr_in *) &saremote;
radius_server_t *server = conf->server;
int ok;
int server_tries;
int retval;
/* ************************************************************ */
/* Now that we're done building the request, we can send it */
/*
Hmm... on password change requests, all of the found server information
could be saved with a pam_set_data(), which means even the radius_conf_t
information will have to be malloc'd at some point
On the other hand, we could just try all of the servers again in
sequence, on the off chance that one may have ended up fixing itself.
*/
/* loop over all available servers */
while (server != NULL) {
/* clear the response */
memset(response, 0, sizeof(AUTH_HDR));
/* only look up IP information as necessary */
if ((retval = host2server(server)) != PAM_SUCCESS) {
_pam_log(LOG_ERR,
"Failed looking up IP address for RADIUS server %s (errcode=%d)",
server->hostname, retval);
ok = FALSE;
goto next; /* skip to the next server */
}
/* set up per-server IP && port configuration */
memset ((char *) s_in, '\0', sizeof(struct sockaddr));
s_in->sin_family = AF_INET;
s_in->sin_addr.s_addr = htonl(server->ip.s_addr);
s_in->sin_port = server->port;
total_length = ntohs(request->length);
if (!password) { /* make an RFC 2139 p6 request authenticator */
get_accounting_vector(request, server);
}
server_tries = tries;
send:
/* send the packet */
if (sendto(conf->sockfd, (char *) request, total_length, 0,
&saremote, sizeof(struct sockaddr_in)) < 0) {
_pam_log(LOG_ERR, "Error sending RADIUS packet to server %s: %s",
server->hostname, strerror(errno));
ok = FALSE;
goto next; /* skip to the next server */
}
/* ************************************************************ */
/* Wait for the response, and verify it. */
salen = sizeof(struct sockaddr);
tv.tv_sec = server->timeout; /* wait for the specified time */
tv.tv_usec = 0;
FD_ZERO(&set); /* clear out the set */
FD_SET(conf->sockfd, &set); /* wait only for the RADIUS UDP socket */
time(&now);
end = now + tv.tv_sec;
/* loop, waiting for the select to return data */
ok = TRUE;
while (ok) {
rcode = select(conf->sockfd + 1, &set, NULL, NULL, &tv);
/* select timed out */
if (rcode == 0) {
_pam_log(LOG_ERR, "RADIUS server %s failed to respond", server->hostname);
if (--server_tries) {
goto send;
}
ok = FALSE;
break; /* exit from the select loop */
} else if (rcode < 0) {
/* select had an error */
if (errno == EINTR) { /* we were interrupted */
time(&now);
if (now > end) {
_pam_log(LOG_ERR, "RADIUS server %s failed to respond",
server->hostname);
if (--server_tries) goto send;
ok = FALSE;
break; /* exit from the select loop */
}
tv.tv_sec = end - now;
if (tv.tv_sec == 0) { /* keep waiting */
tv.tv_sec = 1;
}
} else { /* not an interrupt, it was a real error */
_pam_log(LOG_ERR, "Error waiting for response from RADIUS server %s: %s",
server->hostname, strerror(errno));
ok = FALSE;
break;
}
/* the select returned OK */
} else if (FD_ISSET(conf->sockfd, &set)) {
/* try to receive some data */
if ((total_length = recvfrom(conf->sockfd, (void *) response, BUFFER_SIZE,
0, &saremote, &salen)) < 0) {
_pam_log(LOG_ERR, "error reading RADIUS packet from server %s: %s",
server->hostname, strerror(errno));
ok = FALSE;
break;
/* there's data, see if it's valid */
} else {
char *p = server->secret;
if ((ntohs(response->length) != total_length) ||
(ntohs(response->length) > BUFFER_SIZE)) {
_pam_log(LOG_ERR, "RADIUS packet from server %s is corrupted",
server->hostname);
ok = FALSE;
break;
}
/* Check if we have the data OK. We should also check request->id */
if (password) {
if (old_password) {
#ifdef LIVINGSTON_PASSWORD_VERIFY_BUG_FIXED
p = old_password; /* what it should be */
#else
p = ""; /* what it really is */
#endif
}
/*
* RFC 2139 p.6 says not do do this, but the Livingston 1.16
* server disagrees. If the user says he wants the bug, give in.
*/
} else { /* authentication request */
if (conf->accounting_bug) {
p = "";
}
}
if (!verify_packet(p, response, request)) {
_pam_log(LOG_ERR, "packet from RADIUS server %s failed verification: "
"The shared secret is probably incorrect.", server->hostname);
ok = FALSE;
break;
}
/*
* Check that the response ID matches the request ID.
*/
if (response->id != request->id) {
_pam_log(LOG_WARNING, "Response packet ID %d does not match the "
"request packet ID %d: verification of packet fails",
response->id, request->id);
ok = FALSE;
break;
}
}
/*
* Whew! The select is done. It hasn't timed out, or errored out.
* It's our descriptor. We've got some data. It's the right size.
* The packet is valid.
* NOW, we can skip out of the select loop, and process the packet
*/
break;
}
/* otherwise, we've got data on another descriptor, keep select'ing */
}
/* go to the next server if this one didn't respond */
next:
if (!ok) {
radius_server_t *old; /* forget about this server */
old = server;
server = server->next;
conf->server = server;
_pam_forget(old->secret);
free(old->hostname);
free(old);
if (server) { /* if there's more servers to check */
/* get a new authentication vector, and update the passwords */
get_random_vector(request->vector);
request->id = request->vector[0];
/* update passwords, as appropriate */
if (password) {
get_random_vector(request->vector);
if (old_password) { /* password change request */
add_password(request, PW_PASSWORD, password, old_password);
add_password(request, PW_OLD_PASSWORD, old_password, old_password);
} else { /* authentication request */
add_password(request, PW_PASSWORD, password, server->secret);
}
}
}
continue;
} else {
/* we've found one that does respond, forget about the other servers */
cleanup(server->next);
server->next = NULL;
live_server = server; /* we've got a live one! */
break;
}
}
if (!server) {
_pam_log(LOG_ERR, "All RADIUS servers failed to respond.");
if (conf->localifdown)
retval = PAM_IGNORE;
else
retval = PAM_AUTHINFO_UNAVAIL;
} else {
retval = PAM_SUCCESS;
}
return retval;
}
/**************************************************************************
* MIDLEVEL PAM CODE
**************************************************************************/
/* this is our front-end for module-application conversations */
#undef PAM_FAIL_CHECK
#define PAM_FAIL_CHECK if (retval != PAM_SUCCESS) { return retval; }
static int rad_converse(pam_handle_t *pamh, int msg_style, char *message, char **password)
{
CONST struct pam_conv *conv;
struct pam_message resp_msg;
CONST struct pam_message *msg[1];
struct pam_response *resp = NULL;
int retval;
resp_msg.msg_style = msg_style;
resp_msg.msg = message;
msg[0] = &resp_msg;
/* grab the password */
retval = pam_get_item(pamh, PAM_CONV, (CONST void **) &conv);
PAM_FAIL_CHECK;
retval = conv->conv(1, msg, &resp,conv->appdata_ptr);
PAM_FAIL_CHECK;
if (password) { /* assume msg.type needs a response */
/* I'm not sure if this next bit is necessary on Linux */
#ifdef sun
/* NULL response, fail authentication */
if ((resp == NULL) || (resp->resp == NULL)) {
return PAM_SYSTEM_ERR;
}
#endif
*password = resp->resp;
free(resp);
}
return PAM_SUCCESS;
}
/**************************************************************************
* GENERAL CODE
**************************************************************************/
#undef PAM_FAIL_CHECK
#define PAM_FAIL_CHECK if (retval != PAM_SUCCESS) { \
int *pret = malloc(sizeof(int)); \
*pret = retval; \
pam_set_data(pamh, "rad_setcred_return", (void *) pret, _int_free); \
return retval; }
PAM_EXTERN int pam_sm_authenticate(pam_handle_t *pamh,int flags,int argc,CONST char **argv)
{
CONST char *user;
CONST char *userinfo;
char *password = NULL;
CONST char *rhost;
char *resp2challenge = NULL;
int ctrl;
int retval = PAM_AUTH_ERR;
int num_challenge = 0;
char recv_buffer[4096];
char send_buffer[4096];
AUTH_HDR *request = (AUTH_HDR *) send_buffer;
AUTH_HDR *response = (AUTH_HDR *) recv_buffer;
radius_conf_t config;
ctrl = _pam_parse(argc, argv, &config);
/* grab the user name */
retval = pam_get_user(pamh, &user, NULL);
PAM_FAIL_CHECK;
/* check that they've entered something, and not too long, either */
if ((user == NULL) || (strlen(user) > MAXPWNAM)) {
int *pret = malloc(sizeof(int));
*pret = PAM_USER_UNKNOWN;
pam_set_data(pamh, "rad_setcred_return", (void *) pret, _int_free);
DPRINT(LOG_DEBUG, "User name was NULL, or too long");
return PAM_USER_UNKNOWN;
}
DPRINT(LOG_DEBUG, "Got user name %s", user);
if (ctrl & PAM_RUSER_ARG) {
retval = pam_get_item(pamh, PAM_RUSER, (CONST void **) &userinfo);
PAM_FAIL_CHECK;
DPRINT(LOG_DEBUG, "Got PAM_RUSER name %s", userinfo);
if (!strcmp("root", user)) {
user = userinfo;
DPRINT(LOG_DEBUG, "Username now %s from ruser", user);
} else {
DPRINT(LOG_DEBUG, "Skipping ruser for non-root auth");
}
}
/*
* Get the IP address of the authentication server
* Then, open a socket, and bind it to a port
*/
retval = initialize(&config, FALSE);
PAM_FAIL_CHECK;
/*
* If there's no client id specified, use the service type, to help
* keep track of which service is doing the authentication.
*/
if (!config.client_id) {
retval = pam_get_item(pamh, PAM_SERVICE, (CONST void **) &config.client_id);
PAM_FAIL_CHECK;
}
/* now we've got a socket open, so we've got to clean it up on error */
#undef PAM_FAIL_CHECK
#define PAM_FAIL_CHECK if (retval != PAM_SUCCESS) {goto error; }
/* build and initialize the RADIUS packet */
request->code = PW_AUTHENTICATION_REQUEST;
get_random_vector(request->vector);
request->id = request->vector[0]; /* this should be evenly distributed */
/* grab the password (if any) from the previous authentication layer */
if (!config.force_prompt) {
DPRINT(LOG_DEBUG, "ignore last_pass, force_prompt set");
retval = pam_get_item(pamh, PAM_AUTHTOK, (CONST void **) &password);
PAM_FAIL_CHECK;
}
if (password) {
password = strdup(password);
DPRINT(LOG_DEBUG, "Got password %s", password);
}
/* no previous password: maybe get one from the user */
if (!password) {
if (ctrl & PAM_USE_FIRST_PASS) {
retval = PAM_AUTH_ERR; /* use one pass only, stopping if it fails */
goto error;
}
/* check to see if we send a NULL password the first time around */
if (!(ctrl & PAM_SKIP_PASSWD)) {
retval = rad_converse(pamh, PAM_PROMPT_ECHO_OFF, config.prompt, &password);
PAM_FAIL_CHECK;
}
} /* end of password == NULL */
build_radius_packet(request, user, password, &config);
/* not all servers understand this service type, but some do */
add_int_attribute(request, PW_USER_SERVICE_TYPE, PW_AUTHENTICATE_ONLY);
/*
* Tell the server which host the user is coming from.
*
* Note that this is NOT the IP address of the machine running PAM!
* It's the IP address of the client.
*/
retval = pam_get_item(pamh, PAM_RHOST, (CONST void **) &rhost);
PAM_FAIL_CHECK;
if (rhost) {
add_attribute(request, PW_CALLING_STATION_ID, (unsigned char *) rhost,
strlen(rhost));
}
DPRINT(LOG_DEBUG, "Sending RADIUS request code %d", request->code);
retval = talk_radius(&config, request, response, password, NULL, config.retries + 1);
PAM_FAIL_CHECK;
DPRINT(LOG_DEBUG, "Got RADIUS response code %d", response->code);
/*
* If we get an authentication failure, and we sent a NULL password,
* ask the user for one and continue.
*
* If we get an access challenge, then do a response, for as many
* challenges as we receive.
*/
while (response->code == PW_ACCESS_CHALLENGE) {
attribute_t *a_state, *a_reply;
char challenge[BUFFER_SIZE];
/* Now we do a bit more work: challenge the user, and get a response */
if (((a_state = find_attribute(response, PW_STATE)) == NULL) ||
((a_reply = find_attribute(response, PW_REPLY_MESSAGE)) == NULL)) {
/* Actually, State isn't required. */
_pam_log(LOG_ERR, "RADIUS Access-Challenge received with State or Reply-Message missing");
retval = PAM_AUTHINFO_UNAVAIL;
goto error;
}
/*
* Security fixes.
*/
if ((a_state->length <= 2) || (a_reply->length <= 2)) {
_pam_log(LOG_ERR, "RADIUS Access-Challenge received with invalid State or Reply-Message");
retval = PAM_AUTHINFO_UNAVAIL;
goto error;
}
memcpy(challenge, a_reply->data, a_reply->length - 2);
challenge[a_reply->length - 2] = 0;
/* It's full challenge-response, we should have echo on */
retval = rad_converse(pamh, PAM_PROMPT_ECHO_ON, challenge, &resp2challenge);
PAM_FAIL_CHECK;
/* now that we've got a response, build a new radius packet */
build_radius_packet(request, user, resp2challenge, &config);
/* request->code is already PW_AUTHENTICATION_REQUEST */
request->id++; /* one up from the request */
if (rhost) {
add_attribute(request, PW_CALLING_STATION_ID, (unsigned char *) rhost,
strlen(rhost));
}
/* copy the state over from the servers response */
add_attribute(request, PW_STATE, a_state->data, a_state->length - 2);
retval = talk_radius(&config, request, response, resp2challenge, NULL, 1);
PAM_FAIL_CHECK;
DPRINT(LOG_DEBUG, "Got response to challenge code %d", response->code);
/*
* max_challenge limits the # of challenges a server can issue
* It's a workaround for buggy servers
*/
if (config.max_challenge > 0 && response->code == PW_ACCESS_CHALLENGE) {
num_challenge++;
if (num_challenge >= config.max_challenge) {
DPRINT(LOG_DEBUG, "maximum number of challenges (%d) reached, failing", num_challenge);
break;
}
}
}
/* Whew! Done the pasword checks, look for an authentication acknowledge */
if (response->code == PW_AUTHENTICATION_ACK) {
retval = PAM_SUCCESS;
} else {
retval = PAM_AUTH_ERR; /* authentication failure */
error:
/* If there was a password pass it to the next layer */
if (password && *password) {
pam_set_item(pamh, PAM_AUTHTOK, password);
}
}
DPRINT(LOG_DEBUG, "authentication %s", retval==PAM_SUCCESS ? "succeeded":"failed");
close(config.sockfd);
cleanup(config.server);
_pam_forget(password);
_pam_forget(resp2challenge);
{
int *pret = malloc(sizeof(int));
*pret = retval;
pam_set_data(pamh, "rad_setcred_return", (void *) pret, _int_free);
}
return retval;
}
/*
* Return a value matching the return value of pam_sm_authenticate, for
* greatest compatibility.
* (Always returning PAM_SUCCESS breaks other authentication modules;
* always returning PAM_IGNORE breaks PAM when we're the only module.)
*/
PAM_EXTERN int pam_sm_setcred(pam_handle_t *pamh,int flags,int argc,CONST char **argv)
{
int retval, *pret;
retval = PAM_SUCCESS;
pret = &retval;
pam_get_data(pamh, "rad_setcred_return", (CONST void **) &pret);
return *pret;
}
#undef PAM_FAIL_CHECK
#define PAM_FAIL_CHECK if (retval != PAM_SUCCESS) { return PAM_SESSION_ERR; }
static int pam_private_session(pam_handle_t *pamh, int flags, int argc, CONST char **argv, int status)
{
CONST char *user;
int ctrl;
int retval = PAM_AUTH_ERR;
char recv_buffer[4096];
char send_buffer[4096];
AUTH_HDR *request = (AUTH_HDR *) send_buffer;
AUTH_HDR *response = (AUTH_HDR *) recv_buffer;
radius_conf_t config;
ctrl = _pam_parse(argc, argv, &config);
/* grab the user name */
retval = pam_get_user(pamh, &user, NULL);
PAM_FAIL_CHECK;
/* check that they've entered something, and not too long, either */
if ((user == NULL) || (strlen(user) > MAXPWNAM)) {
return PAM_USER_UNKNOWN;
}
/*
* Get the IP address of the authentication server
* Then, open a socket, and bind it to a port
*/
retval = initialize(&config, TRUE);
PAM_FAIL_CHECK;
/*
* If there's no client id specified, use the service type, to help
* keep track of which service is doing the authentication.
*/
if (!config.client_id) {
retval = pam_get_item(pamh, PAM_SERVICE, (CONST void **) &config.client_id);
PAM_FAIL_CHECK;
}
/* now we've got a socket open, so we've got to clean it up on error */
#undef PAM_FAIL_CHECK
#define PAM_FAIL_CHECK if (retval != PAM_SUCCESS) {goto error; }
/* build and initialize the RADIUS packet */
request->code = PW_ACCOUNTING_REQUEST;
get_random_vector(request->vector);
request->id = request->vector[0]; /* this should be evenly distributed */
build_radius_packet(request, user, NULL, &config);
add_int_attribute(request, PW_ACCT_STATUS_TYPE, status);
sprintf(recv_buffer, "%08d", (int) getpid());
add_attribute(request, PW_ACCT_SESSION_ID, (unsigned char *) recv_buffer, strlen(recv_buffer));
add_int_attribute(request, PW_ACCT_AUTHENTIC, PW_AUTH_RADIUS);
if (status == PW_STATUS_START) {
session_time = time(NULL);
} else {
add_int_attribute(request, PW_ACCT_SESSION_TIME, time(NULL) - session_time);
}
retval = talk_radius(&config, request, response, NULL, NULL, 1);
PAM_FAIL_CHECK;
/* oops! They don't have the right password. Complain and die. */
if (response->code != PW_ACCOUNTING_RESPONSE) {
retval = PAM_PERM_DENIED;
goto error;
}
retval = PAM_SUCCESS;
error:
close(config.sockfd);
cleanup(config.server);
return retval;
}
PAM_EXTERN int pam_sm_open_session(pam_handle_t *pamh, int flags, int argc, CONST char **argv)
{
return pam_private_session(pamh, flags, argc, argv, PW_STATUS_START);
}
PAM_EXTERN int pam_sm_close_session(pam_handle_t *pamh, int flags, int argc, CONST char **argv)
{
return pam_private_session(pamh, flags, argc, argv, PW_STATUS_STOP);
}
#undef PAM_FAIL_CHECK
#define PAM_FAIL_CHECK if (retval != PAM_SUCCESS) {return retval; }
#define MAX_PASSWD_TRIES 3
PAM_EXTERN int pam_sm_chauthtok(pam_handle_t *pamh, int flags, int argc, CONST char **argv)
{
CONST char *user;
char *password = NULL;
char *new_password = NULL;
char *check_password = NULL;
int ctrl;
int retval = PAM_AUTHTOK_ERR;
int attempts;
char recv_buffer[4096];
char send_buffer[4096];
AUTH_HDR *request = (AUTH_HDR *) send_buffer;
AUTH_HDR *response = (AUTH_HDR *) recv_buffer;
radius_conf_t config;
ctrl = _pam_parse(argc, argv, &config);
/* grab the user name */
retval = pam_get_user(pamh, &user, NULL);
PAM_FAIL_CHECK;
/* check that they've entered something, and not too long, either */
if ((user == NULL) || (strlen(user) > MAXPWNAM)) {
return PAM_USER_UNKNOWN;
}
/*
* Get the IP address of the authentication server
* Then, open a socket, and bind it to a port
*/
retval = initialize(&config, FALSE);
PAM_FAIL_CHECK;
/*
* If there's no client id specified, use the service type, to help
* keep track of which service is doing the authentication.
*/
if (!config.client_id) {
retval = pam_get_item(pamh, PAM_SERVICE, (CONST void **) &config.client_id);
PAM_FAIL_CHECK;
}
/* now we've got a socket open, so we've got to clean it up on error */
#undef PAM_FAIL_CHECK
#define PAM_FAIL_CHECK if (retval != PAM_SUCCESS) {goto error; }
/* grab the old password (if any) from the previous password layer */
retval = pam_get_item(pamh, PAM_OLDAUTHTOK, (CONST void **) &password);
PAM_FAIL_CHECK;
if (password) password = strdup(password);
/* grab the new password (if any) from the previous password layer */
retval = pam_get_item(pamh, PAM_AUTHTOK, (CONST void **) &new_password);
PAM_FAIL_CHECK;
if (new_password) new_password = strdup(new_password);
/* preliminary password change checks. */
if (flags & PAM_PRELIM_CHECK) {
if (!password) { /* no previous password: ask for one */
retval = rad_converse(pamh, PAM_PROMPT_ECHO_OFF, config.prompt, &password);
PAM_FAIL_CHECK;
}
/*
* We now check the password to see if it's the right one.
* If it isn't, we let the user try again.
* Note that RADIUS doesn't have any concept of 'root'. The only way
* that root can change someone's password is to log into the RADIUS
* server, and and change it there.
*/
/* build and initialize the access request RADIUS packet */
request->code = PW_AUTHENTICATION_REQUEST;
get_random_vector(request->vector);
request->id = request->vector[0]; /* this should be evenly distributed */
build_radius_packet(request, user, password, &config);
add_int_attribute(request, PW_USER_SERVICE_TYPE, PW_AUTHENTICATE_ONLY);
retval = talk_radius(&config, request, response, password, NULL, 1);
PAM_FAIL_CHECK;
/* oops! They don't have the right password. Complain and die. */
if (response->code != PW_AUTHENTICATION_ACK) {
_pam_forget(password);
retval = PAM_PERM_DENIED;
goto error;
}
/*
* We're now sure it's the right user.
* Ask for their new password, if appropriate
*/
if (!new_password) { /* not found yet: ask for it */
int new_attempts;
attempts = 0;
/* loop, trying to get matching new passwords */
while (attempts++ < 3) {
/* loop, trying to get a new password */
new_attempts = 0;
while (new_attempts++ < 3) {
retval = rad_converse(pamh, PAM_PROMPT_ECHO_OFF,
"New password: ", &new_password);
PAM_FAIL_CHECK;
/* the old password may be short. Check it, first. */
if (strcmp(password, new_password) == 0) { /* are they the same? */
rad_converse(pamh, PAM_ERROR_MSG,
"You must choose a new password.", NULL);
_pam_forget(new_password);
continue;
} else if (strlen(new_password) < 6) {
rad_converse(pamh, PAM_ERROR_MSG, "it's WAY too short", NULL);
_pam_forget(new_password);
continue;
}
/* insert crypt password checking here */
break; /* the new password is OK */
}
if (new_attempts >= 3) { /* too many new password attempts: die */
retval = PAM_AUTHTOK_ERR;
goto error;
}
/* make sure of the password by asking for verification */
retval = rad_converse(pamh, PAM_PROMPT_ECHO_OFF,
"New password (again): ", &check_password);
PAM_FAIL_CHECK;
retval = strcmp(new_password, check_password);
_pam_forget(check_password);
/* if they don't match, don't pass them to the next module */
if (retval != 0) {
_pam_forget(new_password);
rad_converse(pamh, PAM_ERROR_MSG,
"You must enter the same password twice.", NULL);
retval = PAM_AUTHTOK_ERR;
goto error; /* ??? maybe this should be a 'continue' ??? */
}
break; /* everything's fine */
} /* loop, trying to get matching new passwords */
if (attempts >= 3) { /* too many new password attempts: die */
retval = PAM_AUTHTOK_ERR;
goto error;
}
} /* now we have a new password which passes all of our tests */
/*
* Solaris 2.6 calls pam_sm_chauthtok only ONCE, with PAM_PRELIM_CHECK
* set.
*/
#ifndef sun
/* If told to update the authentication token, do so. */
} else if (flags & PAM_UPDATE_AUTHTOK) {
#endif
if (!password || !new_password) { /* ensure we've got passwords */
retval = PAM_AUTHTOK_ERR;
goto error;
}
/* build and initialize the password change request RADIUS packet */
request->code = PW_PASSWORD_REQUEST;
get_random_vector(request->vector);
request->id = request->vector[0]; /* this should be evenly distributed */
/* the secret here can not be know to the user, so it's the new password */
_pam_forget(config.server->secret);
config.server->secret = strdup(password); /* it's free'd later */
build_radius_packet(request, user, new_password, &config);
add_password(request, PW_OLD_PASSWORD, password, password);
retval = talk_radius(&config, request, response, new_password, password, 1);
PAM_FAIL_CHECK;
/* Whew! Done password changing, check for password acknowledge */
if (response->code != PW_PASSWORD_ACK) {
retval = PAM_AUTHTOK_ERR;
goto error;
}
}
/*
* Send the passwords to the next stage if preliminary checks fail,
* or if the password change request fails.
*/
if ((flags & PAM_PRELIM_CHECK) || (retval != PAM_SUCCESS)) {
error:
/* If there was a password pass it to the next layer */
if (password && *password) {
pam_set_item(pamh, PAM_OLDAUTHTOK, password);
}
if (new_password && *new_password) {
pam_set_item(pamh, PAM_AUTHTOK, new_password);
}
}
if (ctrl & PAM_DEBUG_ARG) {
_pam_log(LOG_DEBUG, "password change %s", retval==PAM_SUCCESS ? "succeeded" : "failed");
}
close(config.sockfd);
cleanup(config.server);
_pam_forget(password);
_pam_forget(new_password);
return retval;
}
/*
* Do nothing for account management. This is apparently needed by
* some programs.
*/
PAM_EXTERN int pam_sm_acct_mgmt(pam_handle_t *pamh,int flags,int argc,CONST char **argv)
{
int retval;
retval = PAM_SUCCESS;
return retval;
}
#ifdef PAM_STATIC
/* static module data */
struct pam_module _pam_radius_modstruct = {
"pam_radius_auth",
pam_sm_authenticate,
pam_sm_setcred,
pam_sm_acct_mgmt,
pam_sm_open_session,
pam_sm_close_session,
pam_sm_chauthtok,
};
#endif
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_1881_0 |
crossvul-cpp_data_bad_205_1 | /*
* linux/kernel/softirq.c
*
* Copyright (C) 1992 Linus Torvalds
*
* Distribute under GPLv2.
*
* Rewritten. Old one was good in 2.2, but in 2.3 it was immoral. --ANK (990903)
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/export.h>
#include <linux/kernel_stat.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/notifier.h>
#include <linux/percpu.h>
#include <linux/cpu.h>
#include <linux/freezer.h>
#include <linux/kthread.h>
#include <linux/rcupdate.h>
#include <linux/ftrace.h>
#include <linux/smp.h>
#include <linux/smpboot.h>
#include <linux/tick.h>
#include <linux/irq.h>
#define CREATE_TRACE_POINTS
#include <trace/events/irq.h>
/*
- No shared variables, all the data are CPU local.
- If a softirq needs serialization, let it serialize itself
by its own spinlocks.
- Even if softirq is serialized, only local cpu is marked for
execution. Hence, we get something sort of weak cpu binding.
Though it is still not clear, will it result in better locality
or will not.
Examples:
- NET RX softirq. It is multithreaded and does not require
any global serialization.
- NET TX softirq. It kicks software netdevice queues, hence
it is logically serialized per device, but this serialization
is invisible to common code.
- Tasklets: serialized wrt itself.
*/
#ifndef __ARCH_IRQ_STAT
DEFINE_PER_CPU_ALIGNED(irq_cpustat_t, irq_stat);
EXPORT_PER_CPU_SYMBOL(irq_stat);
#endif
static struct softirq_action softirq_vec[NR_SOFTIRQS] __cacheline_aligned_in_smp;
DEFINE_PER_CPU(struct task_struct *, ksoftirqd);
const char * const softirq_to_name[NR_SOFTIRQS] = {
"HI", "TIMER", "NET_TX", "NET_RX", "BLOCK", "IRQ_POLL",
"TASKLET", "SCHED", "HRTIMER", "RCU"
};
/*
* we cannot loop indefinitely here to avoid userspace starvation,
* but we also don't want to introduce a worst case 1/HZ latency
* to the pending events, so lets the scheduler to balance
* the softirq load for us.
*/
static void wakeup_softirqd(void)
{
/* Interrupts are disabled: no need to stop preemption */
struct task_struct *tsk = __this_cpu_read(ksoftirqd);
if (tsk && tsk->state != TASK_RUNNING)
wake_up_process(tsk);
}
/*
* If ksoftirqd is scheduled, we do not want to process pending softirqs
* right now. Let ksoftirqd handle this at its own rate, to get fairness.
*/
static bool ksoftirqd_running(void)
{
struct task_struct *tsk = __this_cpu_read(ksoftirqd);
return tsk && (tsk->state == TASK_RUNNING);
}
/*
* preempt_count and SOFTIRQ_OFFSET usage:
* - preempt_count is changed by SOFTIRQ_OFFSET on entering or leaving
* softirq processing.
* - preempt_count is changed by SOFTIRQ_DISABLE_OFFSET (= 2 * SOFTIRQ_OFFSET)
* on local_bh_disable or local_bh_enable.
* This lets us distinguish between whether we are currently processing
* softirq and whether we just have bh disabled.
*/
/*
* This one is for softirq.c-internal use,
* where hardirqs are disabled legitimately:
*/
#ifdef CONFIG_TRACE_IRQFLAGS
void __local_bh_disable_ip(unsigned long ip, unsigned int cnt)
{
unsigned long flags;
WARN_ON_ONCE(in_irq());
raw_local_irq_save(flags);
/*
* The preempt tracer hooks into preempt_count_add and will break
* lockdep because it calls back into lockdep after SOFTIRQ_OFFSET
* is set and before current->softirq_enabled is cleared.
* We must manually increment preempt_count here and manually
* call the trace_preempt_off later.
*/
__preempt_count_add(cnt);
/*
* Were softirqs turned off above:
*/
if (softirq_count() == (cnt & SOFTIRQ_MASK))
trace_softirqs_off(ip);
raw_local_irq_restore(flags);
if (preempt_count() == cnt) {
#ifdef CONFIG_DEBUG_PREEMPT
current->preempt_disable_ip = get_lock_parent_ip();
#endif
trace_preempt_off(CALLER_ADDR0, get_lock_parent_ip());
}
}
EXPORT_SYMBOL(__local_bh_disable_ip);
#endif /* CONFIG_TRACE_IRQFLAGS */
static void __local_bh_enable(unsigned int cnt)
{
lockdep_assert_irqs_disabled();
if (softirq_count() == (cnt & SOFTIRQ_MASK))
trace_softirqs_on(_RET_IP_);
preempt_count_sub(cnt);
}
/*
* Special-case - softirqs can safely be enabled by __do_softirq(),
* without processing still-pending softirqs:
*/
void _local_bh_enable(void)
{
WARN_ON_ONCE(in_irq());
__local_bh_enable(SOFTIRQ_DISABLE_OFFSET);
}
EXPORT_SYMBOL(_local_bh_enable);
void __local_bh_enable_ip(unsigned long ip, unsigned int cnt)
{
WARN_ON_ONCE(in_irq());
lockdep_assert_irqs_enabled();
#ifdef CONFIG_TRACE_IRQFLAGS
local_irq_disable();
#endif
/*
* Are softirqs going to be turned on now:
*/
if (softirq_count() == SOFTIRQ_DISABLE_OFFSET)
trace_softirqs_on(ip);
/*
* Keep preemption disabled until we are done with
* softirq processing:
*/
preempt_count_sub(cnt - 1);
if (unlikely(!in_interrupt() && local_softirq_pending())) {
/*
* Run softirq if any pending. And do it in its own stack
* as we may be calling this deep in a task call stack already.
*/
do_softirq();
}
preempt_count_dec();
#ifdef CONFIG_TRACE_IRQFLAGS
local_irq_enable();
#endif
preempt_check_resched();
}
EXPORT_SYMBOL(__local_bh_enable_ip);
/*
* We restart softirq processing for at most MAX_SOFTIRQ_RESTART times,
* but break the loop if need_resched() is set or after 2 ms.
* The MAX_SOFTIRQ_TIME provides a nice upper bound in most cases, but in
* certain cases, such as stop_machine(), jiffies may cease to
* increment and so we need the MAX_SOFTIRQ_RESTART limit as
* well to make sure we eventually return from this method.
*
* These limits have been established via experimentation.
* The two things to balance is latency against fairness -
* we want to handle softirqs as soon as possible, but they
* should not be able to lock up the box.
*/
#define MAX_SOFTIRQ_TIME msecs_to_jiffies(2)
#define MAX_SOFTIRQ_RESTART 10
#ifdef CONFIG_TRACE_IRQFLAGS
/*
* When we run softirqs from irq_exit() and thus on the hardirq stack we need
* to keep the lockdep irq context tracking as tight as possible in order to
* not miss-qualify lock contexts and miss possible deadlocks.
*/
static inline bool lockdep_softirq_start(void)
{
bool in_hardirq = false;
if (trace_hardirq_context(current)) {
in_hardirq = true;
trace_hardirq_exit();
}
lockdep_softirq_enter();
return in_hardirq;
}
static inline void lockdep_softirq_end(bool in_hardirq)
{
lockdep_softirq_exit();
if (in_hardirq)
trace_hardirq_enter();
}
#else
static inline bool lockdep_softirq_start(void) { return false; }
static inline void lockdep_softirq_end(bool in_hardirq) { }
#endif
asmlinkage __visible void __softirq_entry __do_softirq(void)
{
unsigned long end = jiffies + MAX_SOFTIRQ_TIME;
unsigned long old_flags = current->flags;
int max_restart = MAX_SOFTIRQ_RESTART;
struct softirq_action *h;
bool in_hardirq;
__u32 pending;
int softirq_bit;
/*
* Mask out PF_MEMALLOC s current task context is borrowed for the
* softirq. A softirq handled such as network RX might set PF_MEMALLOC
* again if the socket is related to swap
*/
current->flags &= ~PF_MEMALLOC;
pending = local_softirq_pending();
account_irq_enter_time(current);
__local_bh_disable_ip(_RET_IP_, SOFTIRQ_OFFSET);
in_hardirq = lockdep_softirq_start();
restart:
/* Reset the pending bitmask before enabling irqs */
set_softirq_pending(0);
local_irq_enable();
h = softirq_vec;
while ((softirq_bit = ffs(pending))) {
unsigned int vec_nr;
int prev_count;
h += softirq_bit - 1;
vec_nr = h - softirq_vec;
prev_count = preempt_count();
kstat_incr_softirqs_this_cpu(vec_nr);
trace_softirq_entry(vec_nr);
h->action(h);
trace_softirq_exit(vec_nr);
if (unlikely(prev_count != preempt_count())) {
pr_err("huh, entered softirq %u %s %p with preempt_count %08x, exited with %08x?\n",
vec_nr, softirq_to_name[vec_nr], h->action,
prev_count, preempt_count());
preempt_count_set(prev_count);
}
h++;
pending >>= softirq_bit;
}
rcu_bh_qs();
local_irq_disable();
pending = local_softirq_pending();
if (pending) {
if (time_before(jiffies, end) && !need_resched() &&
--max_restart)
goto restart;
wakeup_softirqd();
}
lockdep_softirq_end(in_hardirq);
account_irq_exit_time(current);
__local_bh_enable(SOFTIRQ_OFFSET);
WARN_ON_ONCE(in_interrupt());
current_restore_flags(old_flags, PF_MEMALLOC);
}
asmlinkage __visible void do_softirq(void)
{
__u32 pending;
unsigned long flags;
if (in_interrupt())
return;
local_irq_save(flags);
pending = local_softirq_pending();
if (pending && !ksoftirqd_running())
do_softirq_own_stack();
local_irq_restore(flags);
}
/*
* Enter an interrupt context.
*/
void irq_enter(void)
{
rcu_irq_enter();
if (is_idle_task(current) && !in_interrupt()) {
/*
* Prevent raise_softirq from needlessly waking up ksoftirqd
* here, as softirq will be serviced on return from interrupt.
*/
local_bh_disable();
tick_irq_enter();
_local_bh_enable();
}
__irq_enter();
}
static inline void invoke_softirq(void)
{
if (ksoftirqd_running())
return;
if (!force_irqthreads) {
#ifdef CONFIG_HAVE_IRQ_EXIT_ON_IRQ_STACK
/*
* We can safely execute softirq on the current stack if
* it is the irq stack, because it should be near empty
* at this stage.
*/
__do_softirq();
#else
/*
* Otherwise, irq_exit() is called on the task stack that can
* be potentially deep already. So call softirq in its own stack
* to prevent from any overrun.
*/
do_softirq_own_stack();
#endif
} else {
wakeup_softirqd();
}
}
static inline void tick_irq_exit(void)
{
#ifdef CONFIG_NO_HZ_COMMON
int cpu = smp_processor_id();
/* Make sure that timer wheel updates are propagated */
if ((idle_cpu(cpu) && !need_resched()) || tick_nohz_full_cpu(cpu)) {
if (!in_interrupt())
tick_nohz_irq_exit();
}
#endif
}
/*
* Exit an interrupt context. Process softirqs if needed and possible:
*/
void irq_exit(void)
{
#ifndef __ARCH_IRQ_EXIT_IRQS_DISABLED
local_irq_disable();
#else
lockdep_assert_irqs_disabled();
#endif
account_irq_exit_time(current);
preempt_count_sub(HARDIRQ_OFFSET);
if (!in_interrupt() && local_softirq_pending())
invoke_softirq();
tick_irq_exit();
rcu_irq_exit();
trace_hardirq_exit(); /* must be last! */
}
/*
* This function must run with irqs disabled!
*/
inline void raise_softirq_irqoff(unsigned int nr)
{
__raise_softirq_irqoff(nr);
/*
* If we're in an interrupt or softirq, we're done
* (this also catches softirq-disabled code). We will
* actually run the softirq once we return from
* the irq or softirq.
*
* Otherwise we wake up ksoftirqd to make sure we
* schedule the softirq soon.
*/
if (!in_interrupt())
wakeup_softirqd();
}
void raise_softirq(unsigned int nr)
{
unsigned long flags;
local_irq_save(flags);
raise_softirq_irqoff(nr);
local_irq_restore(flags);
}
void __raise_softirq_irqoff(unsigned int nr)
{
trace_softirq_raise(nr);
or_softirq_pending(1UL << nr);
}
void open_softirq(int nr, void (*action)(struct softirq_action *))
{
softirq_vec[nr].action = action;
}
/*
* Tasklets
*/
struct tasklet_head {
struct tasklet_struct *head;
struct tasklet_struct **tail;
};
static DEFINE_PER_CPU(struct tasklet_head, tasklet_vec);
static DEFINE_PER_CPU(struct tasklet_head, tasklet_hi_vec);
static void __tasklet_schedule_common(struct tasklet_struct *t,
struct tasklet_head __percpu *headp,
unsigned int softirq_nr)
{
struct tasklet_head *head;
unsigned long flags;
local_irq_save(flags);
head = this_cpu_ptr(headp);
t->next = NULL;
*head->tail = t;
head->tail = &(t->next);
raise_softirq_irqoff(softirq_nr);
local_irq_restore(flags);
}
void __tasklet_schedule(struct tasklet_struct *t)
{
__tasklet_schedule_common(t, &tasklet_vec,
TASKLET_SOFTIRQ);
}
EXPORT_SYMBOL(__tasklet_schedule);
void __tasklet_hi_schedule(struct tasklet_struct *t)
{
__tasklet_schedule_common(t, &tasklet_hi_vec,
HI_SOFTIRQ);
}
EXPORT_SYMBOL(__tasklet_hi_schedule);
static void tasklet_action_common(struct softirq_action *a,
struct tasklet_head *tl_head,
unsigned int softirq_nr)
{
struct tasklet_struct *list;
local_irq_disable();
list = tl_head->head;
tl_head->head = NULL;
tl_head->tail = &tl_head->head;
local_irq_enable();
while (list) {
struct tasklet_struct *t = list;
list = list->next;
if (tasklet_trylock(t)) {
if (!atomic_read(&t->count)) {
if (!test_and_clear_bit(TASKLET_STATE_SCHED,
&t->state))
BUG();
t->func(t->data);
tasklet_unlock(t);
continue;
}
tasklet_unlock(t);
}
local_irq_disable();
t->next = NULL;
*tl_head->tail = t;
tl_head->tail = &t->next;
__raise_softirq_irqoff(softirq_nr);
local_irq_enable();
}
}
static __latent_entropy void tasklet_action(struct softirq_action *a)
{
tasklet_action_common(a, this_cpu_ptr(&tasklet_vec), TASKLET_SOFTIRQ);
}
static __latent_entropy void tasklet_hi_action(struct softirq_action *a)
{
tasklet_action_common(a, this_cpu_ptr(&tasklet_hi_vec), HI_SOFTIRQ);
}
void tasklet_init(struct tasklet_struct *t,
void (*func)(unsigned long), unsigned long data)
{
t->next = NULL;
t->state = 0;
atomic_set(&t->count, 0);
t->func = func;
t->data = data;
}
EXPORT_SYMBOL(tasklet_init);
void tasklet_kill(struct tasklet_struct *t)
{
if (in_interrupt())
pr_notice("Attempt to kill tasklet from interrupt\n");
while (test_and_set_bit(TASKLET_STATE_SCHED, &t->state)) {
do {
yield();
} while (test_bit(TASKLET_STATE_SCHED, &t->state));
}
tasklet_unlock_wait(t);
clear_bit(TASKLET_STATE_SCHED, &t->state);
}
EXPORT_SYMBOL(tasklet_kill);
/*
* tasklet_hrtimer
*/
/*
* The trampoline is called when the hrtimer expires. It schedules a tasklet
* to run __tasklet_hrtimer_trampoline() which in turn will call the intended
* hrtimer callback, but from softirq context.
*/
static enum hrtimer_restart __hrtimer_tasklet_trampoline(struct hrtimer *timer)
{
struct tasklet_hrtimer *ttimer =
container_of(timer, struct tasklet_hrtimer, timer);
tasklet_hi_schedule(&ttimer->tasklet);
return HRTIMER_NORESTART;
}
/*
* Helper function which calls the hrtimer callback from
* tasklet/softirq context
*/
static void __tasklet_hrtimer_trampoline(unsigned long data)
{
struct tasklet_hrtimer *ttimer = (void *)data;
enum hrtimer_restart restart;
restart = ttimer->function(&ttimer->timer);
if (restart != HRTIMER_NORESTART)
hrtimer_restart(&ttimer->timer);
}
/**
* tasklet_hrtimer_init - Init a tasklet/hrtimer combo for softirq callbacks
* @ttimer: tasklet_hrtimer which is initialized
* @function: hrtimer callback function which gets called from softirq context
* @which_clock: clock id (CLOCK_MONOTONIC/CLOCK_REALTIME)
* @mode: hrtimer mode (HRTIMER_MODE_ABS/HRTIMER_MODE_REL)
*/
void tasklet_hrtimer_init(struct tasklet_hrtimer *ttimer,
enum hrtimer_restart (*function)(struct hrtimer *),
clockid_t which_clock, enum hrtimer_mode mode)
{
hrtimer_init(&ttimer->timer, which_clock, mode);
ttimer->timer.function = __hrtimer_tasklet_trampoline;
tasklet_init(&ttimer->tasklet, __tasklet_hrtimer_trampoline,
(unsigned long)ttimer);
ttimer->function = function;
}
EXPORT_SYMBOL_GPL(tasklet_hrtimer_init);
void __init softirq_init(void)
{
int cpu;
for_each_possible_cpu(cpu) {
per_cpu(tasklet_vec, cpu).tail =
&per_cpu(tasklet_vec, cpu).head;
per_cpu(tasklet_hi_vec, cpu).tail =
&per_cpu(tasklet_hi_vec, cpu).head;
}
open_softirq(TASKLET_SOFTIRQ, tasklet_action);
open_softirq(HI_SOFTIRQ, tasklet_hi_action);
}
static int ksoftirqd_should_run(unsigned int cpu)
{
return local_softirq_pending();
}
static void run_ksoftirqd(unsigned int cpu)
{
local_irq_disable();
if (local_softirq_pending()) {
/*
* We can safely run softirq on inline stack, as we are not deep
* in the task stack here.
*/
__do_softirq();
local_irq_enable();
cond_resched();
return;
}
local_irq_enable();
}
#ifdef CONFIG_HOTPLUG_CPU
/*
* tasklet_kill_immediate is called to remove a tasklet which can already be
* scheduled for execution on @cpu.
*
* Unlike tasklet_kill, this function removes the tasklet
* _immediately_, even if the tasklet is in TASKLET_STATE_SCHED state.
*
* When this function is called, @cpu must be in the CPU_DEAD state.
*/
void tasklet_kill_immediate(struct tasklet_struct *t, unsigned int cpu)
{
struct tasklet_struct **i;
BUG_ON(cpu_online(cpu));
BUG_ON(test_bit(TASKLET_STATE_RUN, &t->state));
if (!test_bit(TASKLET_STATE_SCHED, &t->state))
return;
/* CPU is dead, so no lock needed. */
for (i = &per_cpu(tasklet_vec, cpu).head; *i; i = &(*i)->next) {
if (*i == t) {
*i = t->next;
/* If this was the tail element, move the tail ptr */
if (*i == NULL)
per_cpu(tasklet_vec, cpu).tail = i;
return;
}
}
BUG();
}
static int takeover_tasklets(unsigned int cpu)
{
/* CPU is dead, so no lock needed. */
local_irq_disable();
/* Find end, append list for that CPU. */
if (&per_cpu(tasklet_vec, cpu).head != per_cpu(tasklet_vec, cpu).tail) {
*__this_cpu_read(tasklet_vec.tail) = per_cpu(tasklet_vec, cpu).head;
this_cpu_write(tasklet_vec.tail, per_cpu(tasklet_vec, cpu).tail);
per_cpu(tasklet_vec, cpu).head = NULL;
per_cpu(tasklet_vec, cpu).tail = &per_cpu(tasklet_vec, cpu).head;
}
raise_softirq_irqoff(TASKLET_SOFTIRQ);
if (&per_cpu(tasklet_hi_vec, cpu).head != per_cpu(tasklet_hi_vec, cpu).tail) {
*__this_cpu_read(tasklet_hi_vec.tail) = per_cpu(tasklet_hi_vec, cpu).head;
__this_cpu_write(tasklet_hi_vec.tail, per_cpu(tasklet_hi_vec, cpu).tail);
per_cpu(tasklet_hi_vec, cpu).head = NULL;
per_cpu(tasklet_hi_vec, cpu).tail = &per_cpu(tasklet_hi_vec, cpu).head;
}
raise_softirq_irqoff(HI_SOFTIRQ);
local_irq_enable();
return 0;
}
#else
#define takeover_tasklets NULL
#endif /* CONFIG_HOTPLUG_CPU */
static struct smp_hotplug_thread softirq_threads = {
.store = &ksoftirqd,
.thread_should_run = ksoftirqd_should_run,
.thread_fn = run_ksoftirqd,
.thread_comm = "ksoftirqd/%u",
};
static __init int spawn_ksoftirqd(void)
{
cpuhp_setup_state_nocalls(CPUHP_SOFTIRQ_DEAD, "softirq:dead", NULL,
takeover_tasklets);
BUG_ON(smpboot_register_percpu_thread(&softirq_threads));
return 0;
}
early_initcall(spawn_ksoftirqd);
/*
* [ These __weak aliases are kept in a separate compilation unit, so that
* GCC does not inline them incorrectly. ]
*/
int __init __weak early_irq_init(void)
{
return 0;
}
int __init __weak arch_probe_nr_irqs(void)
{
return NR_IRQS_LEGACY;
}
int __init __weak arch_early_irq_init(void)
{
return 0;
}
unsigned int __weak arch_dynirq_lower_bound(unsigned int from)
{
return from;
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_205_1 |
crossvul-cpp_data_bad_3873_0 | /* regcomp.c
*/
/*
* 'A fair jaw-cracker dwarf-language must be.' --Samwise Gamgee
*
* [p.285 of _The Lord of the Rings_, II/iii: "The Ring Goes South"]
*/
/* This file contains functions for compiling a regular expression. See
* also regexec.c which funnily enough, contains functions for executing
* a regular expression.
*
* This file is also copied at build time to ext/re/re_comp.c, where
* it's built with -DPERL_EXT_RE_BUILD -DPERL_EXT_RE_DEBUG -DPERL_EXT.
* This causes the main functions to be compiled under new names and with
* debugging support added, which makes "use re 'debug'" work.
*/
/* NOTE: this is derived from Henry Spencer's regexp code, and should not
* confused with the original package (see point 3 below). Thanks, Henry!
*/
/* Additional note: this code is very heavily munged from Henry's version
* in places. In some spots I've traded clarity for efficiency, so don't
* blame Henry for some of the lack of readability.
*/
/* The names of the functions have been changed from regcomp and
* regexec to pregcomp and pregexec in order to avoid conflicts
* with the POSIX routines of the same names.
*/
#ifdef PERL_EXT_RE_BUILD
#include "re_top.h"
#endif
/*
* pregcomp and pregexec -- regsub and regerror are not used in perl
*
* Copyright (c) 1986 by University of Toronto.
* Written by Henry Spencer. Not derived from licensed software.
*
* Permission is granted to anyone to use this software for any
* purpose on any computer system, and to redistribute it freely,
* subject to the following restrictions:
*
* 1. The author is not responsible for the consequences of use of
* this software, no matter how awful, even if they arise
* from defects in it.
*
* 2. The origin of this software must not be misrepresented, either
* by explicit claim or by omission.
*
* 3. Altered versions must be plainly marked as such, and must not
* be misrepresented as being the original software.
*
*
**** Alterations to Henry's code are...
****
**** Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
**** 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
**** by Larry Wall and others
****
**** You may distribute under the terms of either the GNU General Public
**** License or the Artistic License, as specified in the README file.
*
* Beware that some of this code is subtly aware of the way operator
* precedence is structured in regular expressions. Serious changes in
* regular-expression syntax might require a total rethink.
*/
#include "EXTERN.h"
#define PERL_IN_REGCOMP_C
#include "perl.h"
#define REG_COMP_C
#ifdef PERL_IN_XSUB_RE
# include "re_comp.h"
EXTERN_C const struct regexp_engine my_reg_engine;
#else
# include "regcomp.h"
#endif
#include "dquote_inline.h"
#include "invlist_inline.h"
#include "unicode_constants.h"
#define HAS_NONLATIN1_FOLD_CLOSURE(i) \
_HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
#define HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(i) \
_HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
#define IS_NON_FINAL_FOLD(c) _IS_NON_FINAL_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
#define IS_IN_SOME_FOLD_L1(c) _IS_IN_SOME_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
#ifndef STATIC
#define STATIC static
#endif
/* this is a chain of data about sub patterns we are processing that
need to be handled separately/specially in study_chunk. Its so
we can simulate recursion without losing state. */
struct scan_frame;
typedef struct scan_frame {
regnode *last_regnode; /* last node to process in this frame */
regnode *next_regnode; /* next node to process when last is reached */
U32 prev_recursed_depth;
I32 stopparen; /* what stopparen do we use */
struct scan_frame *this_prev_frame; /* this previous frame */
struct scan_frame *prev_frame; /* previous frame */
struct scan_frame *next_frame; /* next frame */
} scan_frame;
/* Certain characters are output as a sequence with the first being a
* backslash. */
#define isBACKSLASHED_PUNCT(c) strchr("-[]\\^", c)
struct RExC_state_t {
U32 flags; /* RXf_* are we folding, multilining? */
U32 pm_flags; /* PMf_* stuff from the calling PMOP */
char *precomp; /* uncompiled string. */
char *precomp_end; /* pointer to end of uncompiled string. */
REGEXP *rx_sv; /* The SV that is the regexp. */
regexp *rx; /* perl core regexp structure */
regexp_internal *rxi; /* internal data for regexp object
pprivate field */
char *start; /* Start of input for compile */
char *end; /* End of input for compile */
char *parse; /* Input-scan pointer. */
char *copy_start; /* start of copy of input within
constructed parse string */
char *save_copy_start; /* Provides one level of saving
and restoring 'copy_start' */
char *copy_start_in_input; /* Position in input string
corresponding to copy_start */
SSize_t whilem_seen; /* number of WHILEM in this expr */
regnode *emit_start; /* Start of emitted-code area */
regnode_offset emit; /* Code-emit pointer */
I32 naughty; /* How bad is this pattern? */
I32 sawback; /* Did we see \1, ...? */
U32 seen;
SSize_t size; /* Number of regnode equivalents in
pattern */
/* position beyond 'precomp' of the warning message furthest away from
* 'precomp'. During the parse, no warnings are raised for any problems
* earlier in the parse than this position. This works if warnings are
* raised the first time a given spot is parsed, and if only one
* independent warning is raised for any given spot */
Size_t latest_warn_offset;
I32 npar; /* Capture buffer count so far in the
parse, (OPEN) plus one. ("par" 0 is
the whole pattern)*/
I32 total_par; /* During initial parse, is either 0,
or -1; the latter indicating a
reparse is needed. After that pass,
it is what 'npar' became after the
pass. Hence, it being > 0 indicates
we are in a reparse situation */
I32 nestroot; /* root parens we are in - used by
accept */
I32 seen_zerolen;
regnode_offset *open_parens; /* offsets to open parens */
regnode_offset *close_parens; /* offsets to close parens */
I32 parens_buf_size; /* #slots malloced open/close_parens */
regnode *end_op; /* END node in program */
I32 utf8; /* whether the pattern is utf8 or not */
I32 orig_utf8; /* whether the pattern was originally in utf8 */
/* XXX use this for future optimisation of case
* where pattern must be upgraded to utf8. */
I32 uni_semantics; /* If a d charset modifier should use unicode
rules, even if the pattern is not in
utf8 */
HV *paren_names; /* Paren names */
regnode **recurse; /* Recurse regops */
I32 recurse_count; /* Number of recurse regops we have generated */
U8 *study_chunk_recursed; /* bitmap of which subs we have moved
through */
U32 study_chunk_recursed_bytes; /* bytes in bitmap */
I32 in_lookbehind;
I32 contains_locale;
I32 override_recoding;
#ifdef EBCDIC
I32 recode_x_to_native;
#endif
I32 in_multi_char_class;
struct reg_code_blocks *code_blocks;/* positions of literal (?{})
within pattern */
int code_index; /* next code_blocks[] slot */
SSize_t maxlen; /* mininum possible number of chars in string to match */
scan_frame *frame_head;
scan_frame *frame_last;
U32 frame_count;
AV *warn_text;
HV *unlexed_names;
#ifdef ADD_TO_REGEXEC
char *starttry; /* -Dr: where regtry was called. */
#define RExC_starttry (pRExC_state->starttry)
#endif
SV *runtime_code_qr; /* qr with the runtime code blocks */
#ifdef DEBUGGING
const char *lastparse;
I32 lastnum;
AV *paren_name_list; /* idx -> name */
U32 study_chunk_recursed_count;
SV *mysv1;
SV *mysv2;
#define RExC_lastparse (pRExC_state->lastparse)
#define RExC_lastnum (pRExC_state->lastnum)
#define RExC_paren_name_list (pRExC_state->paren_name_list)
#define RExC_study_chunk_recursed_count (pRExC_state->study_chunk_recursed_count)
#define RExC_mysv (pRExC_state->mysv1)
#define RExC_mysv1 (pRExC_state->mysv1)
#define RExC_mysv2 (pRExC_state->mysv2)
#endif
bool seen_d_op;
bool strict;
bool study_started;
bool in_script_run;
bool use_BRANCHJ;
};
#define RExC_flags (pRExC_state->flags)
#define RExC_pm_flags (pRExC_state->pm_flags)
#define RExC_precomp (pRExC_state->precomp)
#define RExC_copy_start_in_input (pRExC_state->copy_start_in_input)
#define RExC_copy_start_in_constructed (pRExC_state->copy_start)
#define RExC_save_copy_start_in_constructed (pRExC_state->save_copy_start)
#define RExC_precomp_end (pRExC_state->precomp_end)
#define RExC_rx_sv (pRExC_state->rx_sv)
#define RExC_rx (pRExC_state->rx)
#define RExC_rxi (pRExC_state->rxi)
#define RExC_start (pRExC_state->start)
#define RExC_end (pRExC_state->end)
#define RExC_parse (pRExC_state->parse)
#define RExC_latest_warn_offset (pRExC_state->latest_warn_offset )
#define RExC_whilem_seen (pRExC_state->whilem_seen)
#define RExC_seen_d_op (pRExC_state->seen_d_op) /* Seen something that differs
under /d from /u ? */
#ifdef RE_TRACK_PATTERN_OFFSETS
# define RExC_offsets (RExC_rxi->u.offsets) /* I am not like the
others */
#endif
#define RExC_emit (pRExC_state->emit)
#define RExC_emit_start (pRExC_state->emit_start)
#define RExC_sawback (pRExC_state->sawback)
#define RExC_seen (pRExC_state->seen)
#define RExC_size (pRExC_state->size)
#define RExC_maxlen (pRExC_state->maxlen)
#define RExC_npar (pRExC_state->npar)
#define RExC_total_parens (pRExC_state->total_par)
#define RExC_parens_buf_size (pRExC_state->parens_buf_size)
#define RExC_nestroot (pRExC_state->nestroot)
#define RExC_seen_zerolen (pRExC_state->seen_zerolen)
#define RExC_utf8 (pRExC_state->utf8)
#define RExC_uni_semantics (pRExC_state->uni_semantics)
#define RExC_orig_utf8 (pRExC_state->orig_utf8)
#define RExC_open_parens (pRExC_state->open_parens)
#define RExC_close_parens (pRExC_state->close_parens)
#define RExC_end_op (pRExC_state->end_op)
#define RExC_paren_names (pRExC_state->paren_names)
#define RExC_recurse (pRExC_state->recurse)
#define RExC_recurse_count (pRExC_state->recurse_count)
#define RExC_study_chunk_recursed (pRExC_state->study_chunk_recursed)
#define RExC_study_chunk_recursed_bytes \
(pRExC_state->study_chunk_recursed_bytes)
#define RExC_in_lookbehind (pRExC_state->in_lookbehind)
#define RExC_contains_locale (pRExC_state->contains_locale)
#ifdef EBCDIC
# define RExC_recode_x_to_native (pRExC_state->recode_x_to_native)
#endif
#define RExC_in_multi_char_class (pRExC_state->in_multi_char_class)
#define RExC_frame_head (pRExC_state->frame_head)
#define RExC_frame_last (pRExC_state->frame_last)
#define RExC_frame_count (pRExC_state->frame_count)
#define RExC_strict (pRExC_state->strict)
#define RExC_study_started (pRExC_state->study_started)
#define RExC_warn_text (pRExC_state->warn_text)
#define RExC_in_script_run (pRExC_state->in_script_run)
#define RExC_use_BRANCHJ (pRExC_state->use_BRANCHJ)
#define RExC_unlexed_names (pRExC_state->unlexed_names)
/* Heuristic check on the complexity of the pattern: if TOO_NAUGHTY, we set
* a flag to disable back-off on the fixed/floating substrings - if it's
* a high complexity pattern we assume the benefit of avoiding a full match
* is worth the cost of checking for the substrings even if they rarely help.
*/
#define RExC_naughty (pRExC_state->naughty)
#define TOO_NAUGHTY (10)
#define MARK_NAUGHTY(add) \
if (RExC_naughty < TOO_NAUGHTY) \
RExC_naughty += (add)
#define MARK_NAUGHTY_EXP(exp, add) \
if (RExC_naughty < TOO_NAUGHTY) \
RExC_naughty += RExC_naughty / (exp) + (add)
#define ISMULT1(c) ((c) == '*' || (c) == '+' || (c) == '?')
#define ISMULT2(s) ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
((*s) == '{' && regcurly(s)))
/*
* Flags to be passed up and down.
*/
#define WORST 0 /* Worst case. */
#define HASWIDTH 0x01 /* Known to not match null strings, could match
non-null ones. */
/* Simple enough to be STAR/PLUS operand; in an EXACTish node must be a single
* character. (There needs to be a case: in the switch statement in regexec.c
* for any node marked SIMPLE.) Note that this is not the same thing as
* REGNODE_SIMPLE */
#define SIMPLE 0x02
#define SPSTART 0x04 /* Starts with * or + */
#define POSTPONED 0x08 /* (?1),(?&name), (??{...}) or similar */
#define TRYAGAIN 0x10 /* Weeded out a declaration. */
#define RESTART_PARSE 0x20 /* Need to redo the parse */
#define NEED_UTF8 0x40 /* In conjunction with RESTART_PARSE, need to
calcuate sizes as UTF-8 */
#define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
/* whether trie related optimizations are enabled */
#if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
#define TRIE_STUDY_OPT
#define FULL_TRIE_STUDY
#define TRIE_STCLASS
#endif
#define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3]
#define PBITVAL(paren) (1 << ((paren) & 7))
#define PAREN_TEST(u8str,paren) ( PBYTE(u8str,paren) & PBITVAL(paren))
#define PAREN_SET(u8str,paren) PBYTE(u8str,paren) |= PBITVAL(paren)
#define PAREN_UNSET(u8str,paren) PBYTE(u8str,paren) &= (~PBITVAL(paren))
#define REQUIRE_UTF8(flagp) STMT_START { \
if (!UTF) { \
*flagp = RESTART_PARSE|NEED_UTF8; \
return 0; \
} \
} STMT_END
/* Change from /d into /u rules, and restart the parse. RExC_uni_semantics is
* a flag that indicates we need to override /d with /u as a result of
* something in the pattern. It should only be used in regards to calling
* set_regex_charset() or get_regex_charse() */
#define REQUIRE_UNI_RULES(flagp, restart_retval) \
STMT_START { \
if (DEPENDS_SEMANTICS) { \
set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET); \
RExC_uni_semantics = 1; \
if (RExC_seen_d_op && LIKELY(! IN_PARENS_PASS)) { \
/* No need to restart the parse if we haven't seen \
* anything that differs between /u and /d, and no need \
* to restart immediately if we're going to reparse \
* anyway to count parens */ \
*flagp |= RESTART_PARSE; \
return restart_retval; \
} \
} \
} STMT_END
#define REQUIRE_BRANCHJ(flagp, restart_retval) \
STMT_START { \
RExC_use_BRANCHJ = 1; \
*flagp |= RESTART_PARSE; \
return restart_retval; \
} STMT_END
/* Until we have completed the parse, we leave RExC_total_parens at 0 or
* less. After that, it must always be positive, because the whole re is
* considered to be surrounded by virtual parens. Setting it to negative
* indicates there is some construct that needs to know the actual number of
* parens to be properly handled. And that means an extra pass will be
* required after we've counted them all */
#define ALL_PARENS_COUNTED (RExC_total_parens > 0)
#define REQUIRE_PARENS_PASS \
STMT_START { /* No-op if have completed a pass */ \
if (! ALL_PARENS_COUNTED) RExC_total_parens = -1; \
} STMT_END
#define IN_PARENS_PASS (RExC_total_parens < 0)
/* This is used to return failure (zero) early from the calling function if
* various flags in 'flags' are set. Two flags always cause a return:
* 'RESTART_PARSE' and 'NEED_UTF8'. 'extra' can be used to specify any
* additional flags that should cause a return; 0 if none. If the return will
* be done, '*flagp' is first set to be all of the flags that caused the
* return. */
#define RETURN_FAIL_ON_RESTART_OR_FLAGS(flags,flagp,extra) \
STMT_START { \
if ((flags) & (RESTART_PARSE|NEED_UTF8|(extra))) { \
*(flagp) = (flags) & (RESTART_PARSE|NEED_UTF8|(extra)); \
return 0; \
} \
} STMT_END
#define MUST_RESTART(flags) ((flags) & (RESTART_PARSE))
#define RETURN_FAIL_ON_RESTART(flags,flagp) \
RETURN_FAIL_ON_RESTART_OR_FLAGS( flags, flagp, 0)
#define RETURN_FAIL_ON_RESTART_FLAGP(flagp) \
if (MUST_RESTART(*(flagp))) return 0
/* This converts the named class defined in regcomp.h to its equivalent class
* number defined in handy.h. */
#define namedclass_to_classnum(class) ((int) ((class) / 2))
#define classnum_to_namedclass(classnum) ((classnum) * 2)
#define _invlist_union_complement_2nd(a, b, output) \
_invlist_union_maybe_complement_2nd(a, b, TRUE, output)
#define _invlist_intersection_complement_2nd(a, b, output) \
_invlist_intersection_maybe_complement_2nd(a, b, TRUE, output)
/* About scan_data_t.
During optimisation we recurse through the regexp program performing
various inplace (keyhole style) optimisations. In addition study_chunk
and scan_commit populate this data structure with information about
what strings MUST appear in the pattern. We look for the longest
string that must appear at a fixed location, and we look for the
longest string that may appear at a floating location. So for instance
in the pattern:
/FOO[xX]A.*B[xX]BAR/
Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
strings (because they follow a .* construct). study_chunk will identify
both FOO and BAR as being the longest fixed and floating strings respectively.
The strings can be composites, for instance
/(f)(o)(o)/
will result in a composite fixed substring 'foo'.
For each string some basic information is maintained:
- min_offset
This is the position the string must appear at, or not before.
It also implicitly (when combined with minlenp) tells us how many
characters must match before the string we are searching for.
Likewise when combined with minlenp and the length of the string it
tells us how many characters must appear after the string we have
found.
- max_offset
Only used for floating strings. This is the rightmost point that
the string can appear at. If set to SSize_t_MAX it indicates that the
string can occur infinitely far to the right.
For fixed strings, it is equal to min_offset.
- minlenp
A pointer to the minimum number of characters of the pattern that the
string was found inside. This is important as in the case of positive
lookahead or positive lookbehind we can have multiple patterns
involved. Consider
/(?=FOO).*F/
The minimum length of the pattern overall is 3, the minimum length
of the lookahead part is 3, but the minimum length of the part that
will actually match is 1. So 'FOO's minimum length is 3, but the
minimum length for the F is 1. This is important as the minimum length
is used to determine offsets in front of and behind the string being
looked for. Since strings can be composites this is the length of the
pattern at the time it was committed with a scan_commit. Note that
the length is calculated by study_chunk, so that the minimum lengths
are not known until the full pattern has been compiled, thus the
pointer to the value.
- lookbehind
In the case of lookbehind the string being searched for can be
offset past the start point of the final matching string.
If this value was just blithely removed from the min_offset it would
invalidate some of the calculations for how many chars must match
before or after (as they are derived from min_offset and minlen and
the length of the string being searched for).
When the final pattern is compiled and the data is moved from the
scan_data_t structure into the regexp structure the information
about lookbehind is factored in, with the information that would
have been lost precalculated in the end_shift field for the
associated string.
The fields pos_min and pos_delta are used to store the minimum offset
and the delta to the maximum offset at the current point in the pattern.
*/
struct scan_data_substrs {
SV *str; /* longest substring found in pattern */
SSize_t min_offset; /* earliest point in string it can appear */
SSize_t max_offset; /* latest point in string it can appear */
SSize_t *minlenp; /* pointer to the minlen relevant to the string */
SSize_t lookbehind; /* is the pos of the string modified by LB */
I32 flags; /* per substring SF_* and SCF_* flags */
};
typedef struct scan_data_t {
/*I32 len_min; unused */
/*I32 len_delta; unused */
SSize_t pos_min;
SSize_t pos_delta;
SV *last_found;
SSize_t last_end; /* min value, <0 unless valid. */
SSize_t last_start_min;
SSize_t last_start_max;
U8 cur_is_floating; /* whether the last_* values should be set as
* the next fixed (0) or floating (1)
* substring */
/* [0] is longest fixed substring so far, [1] is longest float so far */
struct scan_data_substrs substrs[2];
I32 flags; /* common SF_* and SCF_* flags */
I32 whilem_c;
SSize_t *last_closep;
regnode_ssc *start_class;
} scan_data_t;
/*
* Forward declarations for pregcomp()'s friends.
*/
static const scan_data_t zero_scan_data = {
0, 0, NULL, 0, 0, 0, 0,
{
{ NULL, 0, 0, 0, 0, 0 },
{ NULL, 0, 0, 0, 0, 0 },
},
0, 0, NULL, NULL
};
/* study flags */
#define SF_BEFORE_SEOL 0x0001
#define SF_BEFORE_MEOL 0x0002
#define SF_BEFORE_EOL (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
#define SF_IS_INF 0x0040
#define SF_HAS_PAR 0x0080
#define SF_IN_PAR 0x0100
#define SF_HAS_EVAL 0x0200
/* SCF_DO_SUBSTR is the flag that tells the regexp analyzer to track the
* longest substring in the pattern. When it is not set the optimiser keeps
* track of position, but does not keep track of the actual strings seen,
*
* So for instance /foo/ will be parsed with SCF_DO_SUBSTR being true, but
* /foo/i will not.
*
* Similarly, /foo.*(blah|erm|huh).*fnorble/ will have "foo" and "fnorble"
* parsed with SCF_DO_SUBSTR on, but while processing the (...) it will be
* turned off because of the alternation (BRANCH). */
#define SCF_DO_SUBSTR 0x0400
#define SCF_DO_STCLASS_AND 0x0800
#define SCF_DO_STCLASS_OR 0x1000
#define SCF_DO_STCLASS (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
#define SCF_WHILEM_VISITED_POS 0x2000
#define SCF_TRIE_RESTUDY 0x4000 /* Do restudy? */
#define SCF_SEEN_ACCEPT 0x8000
#define SCF_TRIE_DOING_RESTUDY 0x10000
#define SCF_IN_DEFINE 0x20000
#define UTF cBOOL(RExC_utf8)
/* The enums for all these are ordered so things work out correctly */
#define LOC (get_regex_charset(RExC_flags) == REGEX_LOCALE_CHARSET)
#define DEPENDS_SEMANTICS (get_regex_charset(RExC_flags) \
== REGEX_DEPENDS_CHARSET)
#define UNI_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_UNICODE_CHARSET)
#define AT_LEAST_UNI_SEMANTICS (get_regex_charset(RExC_flags) \
>= REGEX_UNICODE_CHARSET)
#define ASCII_RESTRICTED (get_regex_charset(RExC_flags) \
== REGEX_ASCII_RESTRICTED_CHARSET)
#define AT_LEAST_ASCII_RESTRICTED (get_regex_charset(RExC_flags) \
>= REGEX_ASCII_RESTRICTED_CHARSET)
#define ASCII_FOLD_RESTRICTED (get_regex_charset(RExC_flags) \
== REGEX_ASCII_MORE_RESTRICTED_CHARSET)
#define FOLD cBOOL(RExC_flags & RXf_PMf_FOLD)
/* For programs that want to be strictly Unicode compatible by dying if any
* attempt is made to match a non-Unicode code point against a Unicode
* property. */
#define ALWAYS_WARN_SUPER ckDEAD(packWARN(WARN_NON_UNICODE))
#define OOB_NAMEDCLASS -1
/* There is no code point that is out-of-bounds, so this is problematic. But
* its only current use is to initialize a variable that is always set before
* looked at. */
#define OOB_UNICODE 0xDEADBEEF
#define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
/* length of regex to show in messages that don't mark a position within */
#define RegexLengthToShowInErrorMessages 127
/*
* If MARKER[12] are adjusted, be sure to adjust the constants at the top
* of t/op/regmesg.t, the tests in t/op/re_tests, and those in
* op/pragma/warn/regcomp.
*/
#define MARKER1 "<-- HERE" /* marker as it appears in the description */
#define MARKER2 " <-- HERE " /* marker as it appears within the regex */
#define REPORT_LOCATION " in regex; marked by " MARKER1 \
" in m/%" UTF8f MARKER2 "%" UTF8f "/"
/* The code in this file in places uses one level of recursion with parsing
* rebased to an alternate string constructed by us in memory. This can take
* the form of something that is completely different from the input, or
* something that uses the input as part of the alternate. In the first case,
* there should be no possibility of an error, as we are in complete control of
* the alternate string. But in the second case we don't completely control
* the input portion, so there may be errors in that. Here's an example:
* /[abc\x{DF}def]/ui
* is handled specially because \x{df} folds to a sequence of more than one
* character: 'ss'. What is done is to create and parse an alternate string,
* which looks like this:
* /(?:\x{DF}|[abc\x{DF}def])/ui
* where it uses the input unchanged in the middle of something it constructs,
* which is a branch for the DF outside the character class, and clustering
* parens around the whole thing. (It knows enough to skip the DF inside the
* class while in this substitute parse.) 'abc' and 'def' may have errors that
* need to be reported. The general situation looks like this:
*
* |<------- identical ------>|
* sI tI xI eI
* Input: ---------------------------------------------------------------
* Constructed: ---------------------------------------------------
* sC tC xC eC EC
* |<------- identical ------>|
*
* sI..eI is the portion of the input pattern we are concerned with here.
* sC..EC is the constructed substitute parse string.
* sC..tC is constructed by us
* tC..eC is an exact duplicate of the portion of the input pattern tI..eI.
* In the diagram, these are vertically aligned.
* eC..EC is also constructed by us.
* xC is the position in the substitute parse string where we found a
* problem.
* xI is the position in the original pattern corresponding to xC.
*
* We want to display a message showing the real input string. Thus we need to
* translate from xC to xI. We know that xC >= tC, since the portion of the
* string sC..tC has been constructed by us, and so shouldn't have errors. We
* get:
* xI = tI + (xC - tC)
*
* When the substitute parse is constructed, the code needs to set:
* RExC_start (sC)
* RExC_end (eC)
* RExC_copy_start_in_input (tI)
* RExC_copy_start_in_constructed (tC)
* and restore them when done.
*
* During normal processing of the input pattern, both
* 'RExC_copy_start_in_input' and 'RExC_copy_start_in_constructed' are set to
* sI, so that xC equals xI.
*/
#define sI RExC_precomp
#define eI RExC_precomp_end
#define sC RExC_start
#define eC RExC_end
#define tI RExC_copy_start_in_input
#define tC RExC_copy_start_in_constructed
#define xI(xC) (tI + (xC - tC))
#define xI_offset(xC) (xI(xC) - sI)
#define REPORT_LOCATION_ARGS(xC) \
UTF8fARG(UTF, \
(xI(xC) > eI) /* Don't run off end */ \
? eI - sI /* Length before the <--HERE */ \
: ((xI_offset(xC) >= 0) \
? xI_offset(xC) \
: (Perl_croak(aTHX_ "panic: %s: %d: negative offset: %" \
IVdf " trying to output message for " \
" pattern %.*s", \
__FILE__, __LINE__, (IV) xI_offset(xC), \
((int) (eC - sC)), sC), 0)), \
sI), /* The input pattern printed up to the <--HERE */ \
UTF8fARG(UTF, \
(xI(xC) > eI) ? 0 : eI - xI(xC), /* Length after <--HERE */ \
(xI(xC) > eI) ? eI : xI(xC)) /* pattern after <--HERE */
/* Used to point after bad bytes for an error message, but avoid skipping
* past a nul byte. */
#define SKIP_IF_CHAR(s, e) (!*(s) ? 0 : UTF ? UTF8_SAFE_SKIP(s, e) : 1)
/* Set up to clean up after our imminent demise */
#define PREPARE_TO_DIE \
STMT_START { \
if (RExC_rx_sv) \
SAVEFREESV(RExC_rx_sv); \
if (RExC_open_parens) \
SAVEFREEPV(RExC_open_parens); \
if (RExC_close_parens) \
SAVEFREEPV(RExC_close_parens); \
} STMT_END
/*
* Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
* arg. Show regex, up to a maximum length. If it's too long, chop and add
* "...".
*/
#define _FAIL(code) STMT_START { \
const char *ellipses = ""; \
IV len = RExC_precomp_end - RExC_precomp; \
\
PREPARE_TO_DIE; \
if (len > RegexLengthToShowInErrorMessages) { \
/* chop 10 shorter than the max, to ensure meaning of "..." */ \
len = RegexLengthToShowInErrorMessages - 10; \
ellipses = "..."; \
} \
code; \
} STMT_END
#define FAIL(msg) _FAIL( \
Perl_croak(aTHX_ "%s in regex m/%" UTF8f "%s/", \
msg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
#define FAIL2(msg,arg) _FAIL( \
Perl_croak(aTHX_ msg " in regex m/%" UTF8f "%s/", \
arg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
/*
* Simple_vFAIL -- like FAIL, but marks the current location in the scan
*/
#define Simple_vFAIL(m) STMT_START { \
Perl_croak(aTHX_ "%s" REPORT_LOCATION, \
m, REPORT_LOCATION_ARGS(RExC_parse)); \
} STMT_END
/*
* Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
*/
#define vFAIL(m) STMT_START { \
PREPARE_TO_DIE; \
Simple_vFAIL(m); \
} STMT_END
/*
* Like Simple_vFAIL(), but accepts two arguments.
*/
#define Simple_vFAIL2(m,a1) STMT_START { \
S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, \
REPORT_LOCATION_ARGS(RExC_parse)); \
} STMT_END
/*
* Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
*/
#define vFAIL2(m,a1) STMT_START { \
PREPARE_TO_DIE; \
Simple_vFAIL2(m, a1); \
} STMT_END
/*
* Like Simple_vFAIL(), but accepts three arguments.
*/
#define Simple_vFAIL3(m, a1, a2) STMT_START { \
S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, \
REPORT_LOCATION_ARGS(RExC_parse)); \
} STMT_END
/*
* Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
*/
#define vFAIL3(m,a1,a2) STMT_START { \
PREPARE_TO_DIE; \
Simple_vFAIL3(m, a1, a2); \
} STMT_END
/*
* Like Simple_vFAIL(), but accepts four arguments.
*/
#define Simple_vFAIL4(m, a1, a2, a3) STMT_START { \
S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, a3, \
REPORT_LOCATION_ARGS(RExC_parse)); \
} STMT_END
#define vFAIL4(m,a1,a2,a3) STMT_START { \
PREPARE_TO_DIE; \
Simple_vFAIL4(m, a1, a2, a3); \
} STMT_END
/* A specialized version of vFAIL2 that works with UTF8f */
#define vFAIL2utf8f(m, a1) STMT_START { \
PREPARE_TO_DIE; \
S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, \
REPORT_LOCATION_ARGS(RExC_parse)); \
} STMT_END
#define vFAIL3utf8f(m, a1, a2) STMT_START { \
PREPARE_TO_DIE; \
S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, \
REPORT_LOCATION_ARGS(RExC_parse)); \
} STMT_END
/* Setting this to NULL is a signal to not output warnings */
#define TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE \
STMT_START { \
RExC_save_copy_start_in_constructed = RExC_copy_start_in_constructed;\
RExC_copy_start_in_constructed = NULL; \
} STMT_END
#define RESTORE_WARNINGS \
RExC_copy_start_in_constructed = RExC_save_copy_start_in_constructed
/* Since a warning can be generated multiple times as the input is reparsed, we
* output it the first time we come to that point in the parse, but suppress it
* otherwise. 'RExC_copy_start_in_constructed' being NULL is a flag to not
* generate any warnings */
#define TO_OUTPUT_WARNINGS(loc) \
( RExC_copy_start_in_constructed \
&& ((xI(loc)) - RExC_precomp) > (Ptrdiff_t) RExC_latest_warn_offset)
/* After we've emitted a warning, we save the position in the input so we don't
* output it again */
#define UPDATE_WARNINGS_LOC(loc) \
STMT_START { \
if (TO_OUTPUT_WARNINGS(loc)) { \
RExC_latest_warn_offset = MAX(sI, MIN(eI, xI(loc))) \
- RExC_precomp; \
} \
} STMT_END
/* 'warns' is the output of the packWARNx macro used in 'code' */
#define _WARN_HELPER(loc, warns, code) \
STMT_START { \
if (! RExC_copy_start_in_constructed) { \
Perl_croak( aTHX_ "panic! %s: %d: Tried to warn when none" \
" expected at '%s'", \
__FILE__, __LINE__, loc); \
} \
if (TO_OUTPUT_WARNINGS(loc)) { \
if (ckDEAD(warns)) \
PREPARE_TO_DIE; \
code; \
UPDATE_WARNINGS_LOC(loc); \
} \
} STMT_END
/* m is not necessarily a "literal string", in this macro */
#define reg_warn_non_literal_string(loc, m) \
_WARN_HELPER(loc, packWARN(WARN_REGEXP), \
Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
"%s" REPORT_LOCATION, \
m, REPORT_LOCATION_ARGS(loc)))
#define ckWARNreg(loc,m) \
_WARN_HELPER(loc, packWARN(WARN_REGEXP), \
Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
m REPORT_LOCATION, \
REPORT_LOCATION_ARGS(loc)))
#define vWARN(loc, m) \
_WARN_HELPER(loc, packWARN(WARN_REGEXP), \
Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
m REPORT_LOCATION, \
REPORT_LOCATION_ARGS(loc))) \
#define vWARN_dep(loc, m) \
_WARN_HELPER(loc, packWARN(WARN_DEPRECATED), \
Perl_warner(aTHX_ packWARN(WARN_DEPRECATED), \
m REPORT_LOCATION, \
REPORT_LOCATION_ARGS(loc)))
#define ckWARNdep(loc,m) \
_WARN_HELPER(loc, packWARN(WARN_DEPRECATED), \
Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED), \
m REPORT_LOCATION, \
REPORT_LOCATION_ARGS(loc)))
#define ckWARNregdep(loc,m) \
_WARN_HELPER(loc, packWARN2(WARN_DEPRECATED, WARN_REGEXP), \
Perl_ck_warner_d(aTHX_ packWARN2(WARN_DEPRECATED, \
WARN_REGEXP), \
m REPORT_LOCATION, \
REPORT_LOCATION_ARGS(loc)))
#define ckWARN2reg_d(loc,m, a1) \
_WARN_HELPER(loc, packWARN(WARN_REGEXP), \
Perl_ck_warner_d(aTHX_ packWARN(WARN_REGEXP), \
m REPORT_LOCATION, \
a1, REPORT_LOCATION_ARGS(loc)))
#define ckWARN2reg(loc, m, a1) \
_WARN_HELPER(loc, packWARN(WARN_REGEXP), \
Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
m REPORT_LOCATION, \
a1, REPORT_LOCATION_ARGS(loc)))
#define vWARN3(loc, m, a1, a2) \
_WARN_HELPER(loc, packWARN(WARN_REGEXP), \
Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
m REPORT_LOCATION, \
a1, a2, REPORT_LOCATION_ARGS(loc)))
#define ckWARN3reg(loc, m, a1, a2) \
_WARN_HELPER(loc, packWARN(WARN_REGEXP), \
Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
m REPORT_LOCATION, \
a1, a2, \
REPORT_LOCATION_ARGS(loc)))
#define vWARN4(loc, m, a1, a2, a3) \
_WARN_HELPER(loc, packWARN(WARN_REGEXP), \
Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
m REPORT_LOCATION, \
a1, a2, a3, \
REPORT_LOCATION_ARGS(loc)))
#define ckWARN4reg(loc, m, a1, a2, a3) \
_WARN_HELPER(loc, packWARN(WARN_REGEXP), \
Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
m REPORT_LOCATION, \
a1, a2, a3, \
REPORT_LOCATION_ARGS(loc)))
#define vWARN5(loc, m, a1, a2, a3, a4) \
_WARN_HELPER(loc, packWARN(WARN_REGEXP), \
Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
m REPORT_LOCATION, \
a1, a2, a3, a4, \
REPORT_LOCATION_ARGS(loc)))
#define ckWARNexperimental(loc, class, m) \
_WARN_HELPER(loc, packWARN(class), \
Perl_ck_warner_d(aTHX_ packWARN(class), \
m REPORT_LOCATION, \
REPORT_LOCATION_ARGS(loc)))
/* Convert between a pointer to a node and its offset from the beginning of the
* program */
#define REGNODE_p(offset) (RExC_emit_start + (offset))
#define REGNODE_OFFSET(node) ((node) - RExC_emit_start)
/* Macros for recording node offsets. 20001227 mjd@plover.com
* Nodes are numbered 1, 2, 3, 4. Node #n's position is recorded in
* element 2*n-1 of the array. Element #2n holds the byte length node #n.
* Element 0 holds the number n.
* Position is 1 indexed.
*/
#ifndef RE_TRACK_PATTERN_OFFSETS
#define Set_Node_Offset_To_R(offset,byte)
#define Set_Node_Offset(node,byte)
#define Set_Cur_Node_Offset
#define Set_Node_Length_To_R(node,len)
#define Set_Node_Length(node,len)
#define Set_Node_Cur_Length(node,start)
#define Node_Offset(n)
#define Node_Length(n)
#define Set_Node_Offset_Length(node,offset,len)
#define ProgLen(ri) ri->u.proglen
#define SetProgLen(ri,x) ri->u.proglen = x
#define Track_Code(code)
#else
#define ProgLen(ri) ri->u.offsets[0]
#define SetProgLen(ri,x) ri->u.offsets[0] = x
#define Set_Node_Offset_To_R(offset,byte) STMT_START { \
MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n", \
__LINE__, (int)(offset), (int)(byte))); \
if((offset) < 0) { \
Perl_croak(aTHX_ "value of node is %d in Offset macro", \
(int)(offset)); \
} else { \
RExC_offsets[2*(offset)-1] = (byte); \
} \
} STMT_END
#define Set_Node_Offset(node,byte) \
Set_Node_Offset_To_R(REGNODE_OFFSET(node), (byte)-RExC_start)
#define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
#define Set_Node_Length_To_R(node,len) STMT_START { \
MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n", \
__LINE__, (int)(node), (int)(len))); \
if((node) < 0) { \
Perl_croak(aTHX_ "value of node is %d in Length macro", \
(int)(node)); \
} else { \
RExC_offsets[2*(node)] = (len); \
} \
} STMT_END
#define Set_Node_Length(node,len) \
Set_Node_Length_To_R(REGNODE_OFFSET(node), len)
#define Set_Node_Cur_Length(node, start) \
Set_Node_Length(node, RExC_parse - start)
/* Get offsets and lengths */
#define Node_Offset(n) (RExC_offsets[2*(REGNODE_OFFSET(n))-1])
#define Node_Length(n) (RExC_offsets[2*(REGNODE_OFFSET(n))])
#define Set_Node_Offset_Length(node,offset,len) STMT_START { \
Set_Node_Offset_To_R(REGNODE_OFFSET(node), (offset)); \
Set_Node_Length_To_R(REGNODE_OFFSET(node), (len)); \
} STMT_END
#define Track_Code(code) STMT_START { code } STMT_END
#endif
#if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
#define EXPERIMENTAL_INPLACESCAN
#endif /*PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS*/
#ifdef DEBUGGING
int
Perl_re_printf(pTHX_ const char *fmt, ...)
{
va_list ap;
int result;
PerlIO *f= Perl_debug_log;
PERL_ARGS_ASSERT_RE_PRINTF;
va_start(ap, fmt);
result = PerlIO_vprintf(f, fmt, ap);
va_end(ap);
return result;
}
int
Perl_re_indentf(pTHX_ const char *fmt, U32 depth, ...)
{
va_list ap;
int result;
PerlIO *f= Perl_debug_log;
PERL_ARGS_ASSERT_RE_INDENTF;
va_start(ap, depth);
PerlIO_printf(f, "%*s", ( (int)depth % 20 ) * 2, "");
result = PerlIO_vprintf(f, fmt, ap);
va_end(ap);
return result;
}
#endif /* DEBUGGING */
#define DEBUG_RExC_seen() \
DEBUG_OPTIMISE_MORE_r({ \
Perl_re_printf( aTHX_ "RExC_seen: "); \
\
if (RExC_seen & REG_ZERO_LEN_SEEN) \
Perl_re_printf( aTHX_ "REG_ZERO_LEN_SEEN "); \
\
if (RExC_seen & REG_LOOKBEHIND_SEEN) \
Perl_re_printf( aTHX_ "REG_LOOKBEHIND_SEEN "); \
\
if (RExC_seen & REG_GPOS_SEEN) \
Perl_re_printf( aTHX_ "REG_GPOS_SEEN "); \
\
if (RExC_seen & REG_RECURSE_SEEN) \
Perl_re_printf( aTHX_ "REG_RECURSE_SEEN "); \
\
if (RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN) \
Perl_re_printf( aTHX_ "REG_TOP_LEVEL_BRANCHES_SEEN "); \
\
if (RExC_seen & REG_VERBARG_SEEN) \
Perl_re_printf( aTHX_ "REG_VERBARG_SEEN "); \
\
if (RExC_seen & REG_CUTGROUP_SEEN) \
Perl_re_printf( aTHX_ "REG_CUTGROUP_SEEN "); \
\
if (RExC_seen & REG_RUN_ON_COMMENT_SEEN) \
Perl_re_printf( aTHX_ "REG_RUN_ON_COMMENT_SEEN "); \
\
if (RExC_seen & REG_UNFOLDED_MULTI_SEEN) \
Perl_re_printf( aTHX_ "REG_UNFOLDED_MULTI_SEEN "); \
\
if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) \
Perl_re_printf( aTHX_ "REG_UNBOUNDED_QUANTIFIER_SEEN "); \
\
Perl_re_printf( aTHX_ "\n"); \
});
#define DEBUG_SHOW_STUDY_FLAG(flags,flag) \
if ((flags) & flag) Perl_re_printf( aTHX_ "%s ", #flag)
#ifdef DEBUGGING
static void
S_debug_show_study_flags(pTHX_ U32 flags, const char *open_str,
const char *close_str)
{
if (!flags)
return;
Perl_re_printf( aTHX_ "%s", open_str);
DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_SEOL);
DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_MEOL);
DEBUG_SHOW_STUDY_FLAG(flags, SF_IS_INF);
DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_PAR);
DEBUG_SHOW_STUDY_FLAG(flags, SF_IN_PAR);
DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_EVAL);
DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_SUBSTR);
DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_AND);
DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_OR);
DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS);
DEBUG_SHOW_STUDY_FLAG(flags, SCF_WHILEM_VISITED_POS);
DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_RESTUDY);
DEBUG_SHOW_STUDY_FLAG(flags, SCF_SEEN_ACCEPT);
DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_DOING_RESTUDY);
DEBUG_SHOW_STUDY_FLAG(flags, SCF_IN_DEFINE);
Perl_re_printf( aTHX_ "%s", close_str);
}
static void
S_debug_studydata(pTHX_ const char *where, scan_data_t *data,
U32 depth, int is_inf)
{
GET_RE_DEBUG_FLAGS_DECL;
DEBUG_OPTIMISE_MORE_r({
if (!data)
return;
Perl_re_indentf(aTHX_ "%s: Pos:%" IVdf "/%" IVdf " Flags: 0x%" UVXf,
depth,
where,
(IV)data->pos_min,
(IV)data->pos_delta,
(UV)data->flags
);
S_debug_show_study_flags(aTHX_ data->flags," [","]");
Perl_re_printf( aTHX_
" Whilem_c: %" IVdf " Lcp: %" IVdf " %s",
(IV)data->whilem_c,
(IV)(data->last_closep ? *((data)->last_closep) : -1),
is_inf ? "INF " : ""
);
if (data->last_found) {
int i;
Perl_re_printf(aTHX_
"Last:'%s' %" IVdf ":%" IVdf "/%" IVdf,
SvPVX_const(data->last_found),
(IV)data->last_end,
(IV)data->last_start_min,
(IV)data->last_start_max
);
for (i = 0; i < 2; i++) {
Perl_re_printf(aTHX_
" %s%s: '%s' @ %" IVdf "/%" IVdf,
data->cur_is_floating == i ? "*" : "",
i ? "Float" : "Fixed",
SvPVX_const(data->substrs[i].str),
(IV)data->substrs[i].min_offset,
(IV)data->substrs[i].max_offset
);
S_debug_show_study_flags(aTHX_ data->substrs[i].flags," [","]");
}
}
Perl_re_printf( aTHX_ "\n");
});
}
static void
S_debug_peep(pTHX_ const char *str, const RExC_state_t *pRExC_state,
regnode *scan, U32 depth, U32 flags)
{
GET_RE_DEBUG_FLAGS_DECL;
DEBUG_OPTIMISE_r({
regnode *Next;
if (!scan)
return;
Next = regnext(scan);
regprop(RExC_rx, RExC_mysv, scan, NULL, pRExC_state);
Perl_re_indentf( aTHX_ "%s>%3d: %s (%d)",
depth,
str,
REG_NODE_NUM(scan), SvPV_nolen_const(RExC_mysv),
Next ? (REG_NODE_NUM(Next)) : 0 );
S_debug_show_study_flags(aTHX_ flags," [ ","]");
Perl_re_printf( aTHX_ "\n");
});
}
# define DEBUG_STUDYDATA(where, data, depth, is_inf) \
S_debug_studydata(aTHX_ where, data, depth, is_inf)
# define DEBUG_PEEP(str, scan, depth, flags) \
S_debug_peep(aTHX_ str, pRExC_state, scan, depth, flags)
#else
# define DEBUG_STUDYDATA(where, data, depth, is_inf) NOOP
# define DEBUG_PEEP(str, scan, depth, flags) NOOP
#endif
/* =========================================================
* BEGIN edit_distance stuff.
*
* This calculates how many single character changes of any type are needed to
* transform a string into another one. It is taken from version 3.1 of
*
* https://metacpan.org/pod/Text::Levenshtein::Damerau::XS
*/
/* Our unsorted dictionary linked list. */
/* Note we use UVs, not chars. */
struct dictionary{
UV key;
UV value;
struct dictionary* next;
};
typedef struct dictionary item;
PERL_STATIC_INLINE item*
push(UV key, item* curr)
{
item* head;
Newx(head, 1, item);
head->key = key;
head->value = 0;
head->next = curr;
return head;
}
PERL_STATIC_INLINE item*
find(item* head, UV key)
{
item* iterator = head;
while (iterator){
if (iterator->key == key){
return iterator;
}
iterator = iterator->next;
}
return NULL;
}
PERL_STATIC_INLINE item*
uniquePush(item* head, UV key)
{
item* iterator = head;
while (iterator){
if (iterator->key == key) {
return head;
}
iterator = iterator->next;
}
return push(key, head);
}
PERL_STATIC_INLINE void
dict_free(item* head)
{
item* iterator = head;
while (iterator) {
item* temp = iterator;
iterator = iterator->next;
Safefree(temp);
}
head = NULL;
}
/* End of Dictionary Stuff */
/* All calculations/work are done here */
STATIC int
S_edit_distance(const UV* src,
const UV* tgt,
const STRLEN x, /* length of src[] */
const STRLEN y, /* length of tgt[] */
const SSize_t maxDistance
)
{
item *head = NULL;
UV swapCount, swapScore, targetCharCount, i, j;
UV *scores;
UV score_ceil = x + y;
PERL_ARGS_ASSERT_EDIT_DISTANCE;
/* intialize matrix start values */
Newx(scores, ( (x + 2) * (y + 2)), UV);
scores[0] = score_ceil;
scores[1 * (y + 2) + 0] = score_ceil;
scores[0 * (y + 2) + 1] = score_ceil;
scores[1 * (y + 2) + 1] = 0;
head = uniquePush(uniquePush(head, src[0]), tgt[0]);
/* work loops */
/* i = src index */
/* j = tgt index */
for (i=1;i<=x;i++) {
if (i < x)
head = uniquePush(head, src[i]);
scores[(i+1) * (y + 2) + 1] = i;
scores[(i+1) * (y + 2) + 0] = score_ceil;
swapCount = 0;
for (j=1;j<=y;j++) {
if (i == 1) {
if(j < y)
head = uniquePush(head, tgt[j]);
scores[1 * (y + 2) + (j + 1)] = j;
scores[0 * (y + 2) + (j + 1)] = score_ceil;
}
targetCharCount = find(head, tgt[j-1])->value;
swapScore = scores[targetCharCount * (y + 2) + swapCount] + i - targetCharCount - 1 + j - swapCount;
if (src[i-1] != tgt[j-1]){
scores[(i+1) * (y + 2) + (j + 1)] = MIN(swapScore,(MIN(scores[i * (y + 2) + j], MIN(scores[(i+1) * (y + 2) + j], scores[i * (y + 2) + (j + 1)])) + 1));
}
else {
swapCount = j;
scores[(i+1) * (y + 2) + (j + 1)] = MIN(scores[i * (y + 2) + j], swapScore);
}
}
find(head, src[i-1])->value = i;
}
{
IV score = scores[(x+1) * (y + 2) + (y + 1)];
dict_free(head);
Safefree(scores);
return (maxDistance != 0 && maxDistance < score)?(-1):score;
}
}
/* END of edit_distance() stuff
* ========================================================= */
/* is c a control character for which we have a mnemonic? */
#define isMNEMONIC_CNTRL(c) _IS_MNEMONIC_CNTRL_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
STATIC const char *
S_cntrl_to_mnemonic(const U8 c)
{
/* Returns the mnemonic string that represents character 'c', if one
* exists; NULL otherwise. The only ones that exist for the purposes of
* this routine are a few control characters */
switch (c) {
case '\a': return "\\a";
case '\b': return "\\b";
case ESC_NATIVE: return "\\e";
case '\f': return "\\f";
case '\n': return "\\n";
case '\r': return "\\r";
case '\t': return "\\t";
}
return NULL;
}
/* Mark that we cannot extend a found fixed substring at this point.
Update the longest found anchored substring or the longest found
floating substrings if needed. */
STATIC void
S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data,
SSize_t *minlenp, int is_inf)
{
const STRLEN l = CHR_SVLEN(data->last_found);
SV * const longest_sv = data->substrs[data->cur_is_floating].str;
const STRLEN old_l = CHR_SVLEN(longest_sv);
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_SCAN_COMMIT;
if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
const U8 i = data->cur_is_floating;
SvSetMagicSV(longest_sv, data->last_found);
data->substrs[i].min_offset = l ? data->last_start_min : data->pos_min;
if (!i) /* fixed */
data->substrs[0].max_offset = data->substrs[0].min_offset;
else { /* float */
data->substrs[1].max_offset = (l
? data->last_start_max
: (data->pos_delta > SSize_t_MAX - data->pos_min
? SSize_t_MAX
: data->pos_min + data->pos_delta));
if (is_inf
|| (STRLEN)data->substrs[1].max_offset > (STRLEN)SSize_t_MAX)
data->substrs[1].max_offset = SSize_t_MAX;
}
if (data->flags & SF_BEFORE_EOL)
data->substrs[i].flags |= (data->flags & SF_BEFORE_EOL);
else
data->substrs[i].flags &= ~SF_BEFORE_EOL;
data->substrs[i].minlenp = minlenp;
data->substrs[i].lookbehind = 0;
}
SvCUR_set(data->last_found, 0);
{
SV * const sv = data->last_found;
if (SvUTF8(sv) && SvMAGICAL(sv)) {
MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
if (mg)
mg->mg_len = 0;
}
}
data->last_end = -1;
data->flags &= ~SF_BEFORE_EOL;
DEBUG_STUDYDATA("commit", data, 0, is_inf);
}
/* An SSC is just a regnode_charclass_posix with an extra field: the inversion
* list that describes which code points it matches */
STATIC void
S_ssc_anything(pTHX_ regnode_ssc *ssc)
{
/* Set the SSC 'ssc' to match an empty string or any code point */
PERL_ARGS_ASSERT_SSC_ANYTHING;
assert(is_ANYOF_SYNTHETIC(ssc));
/* mortalize so won't leak */
ssc->invlist = sv_2mortal(_add_range_to_invlist(NULL, 0, UV_MAX));
ANYOF_FLAGS(ssc) |= SSC_MATCHES_EMPTY_STRING; /* Plus matches empty */
}
STATIC int
S_ssc_is_anything(const regnode_ssc *ssc)
{
/* Returns TRUE if the SSC 'ssc' can match the empty string and any code
* point; FALSE otherwise. Thus, this is used to see if using 'ssc' buys
* us anything: if the function returns TRUE, 'ssc' hasn't been restricted
* in any way, so there's no point in using it */
UV start, end;
bool ret;
PERL_ARGS_ASSERT_SSC_IS_ANYTHING;
assert(is_ANYOF_SYNTHETIC(ssc));
if (! (ANYOF_FLAGS(ssc) & SSC_MATCHES_EMPTY_STRING)) {
return FALSE;
}
/* See if the list consists solely of the range 0 - Infinity */
invlist_iterinit(ssc->invlist);
ret = invlist_iternext(ssc->invlist, &start, &end)
&& start == 0
&& end == UV_MAX;
invlist_iterfinish(ssc->invlist);
if (ret) {
return TRUE;
}
/* If e.g., both \w and \W are set, matches everything */
if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
int i;
for (i = 0; i < ANYOF_POSIXL_MAX; i += 2) {
if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i+1)) {
return TRUE;
}
}
}
return FALSE;
}
STATIC void
S_ssc_init(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc)
{
/* Initializes the SSC 'ssc'. This includes setting it to match an empty
* string, any code point, or any posix class under locale */
PERL_ARGS_ASSERT_SSC_INIT;
Zero(ssc, 1, regnode_ssc);
set_ANYOF_SYNTHETIC(ssc);
ARG_SET(ssc, ANYOF_ONLY_HAS_BITMAP);
ssc_anything(ssc);
/* If any portion of the regex is to operate under locale rules that aren't
* fully known at compile time, initialization includes it. The reason
* this isn't done for all regexes is that the optimizer was written under
* the assumption that locale was all-or-nothing. Given the complexity and
* lack of documentation in the optimizer, and that there are inadequate
* test cases for locale, many parts of it may not work properly, it is
* safest to avoid locale unless necessary. */
if (RExC_contains_locale) {
ANYOF_POSIXL_SETALL(ssc);
}
else {
ANYOF_POSIXL_ZERO(ssc);
}
}
STATIC int
S_ssc_is_cp_posixl_init(const RExC_state_t *pRExC_state,
const regnode_ssc *ssc)
{
/* Returns TRUE if the SSC 'ssc' is in its initial state with regard only
* to the list of code points matched, and locale posix classes; hence does
* not check its flags) */
UV start, end;
bool ret;
PERL_ARGS_ASSERT_SSC_IS_CP_POSIXL_INIT;
assert(is_ANYOF_SYNTHETIC(ssc));
invlist_iterinit(ssc->invlist);
ret = invlist_iternext(ssc->invlist, &start, &end)
&& start == 0
&& end == UV_MAX;
invlist_iterfinish(ssc->invlist);
if (! ret) {
return FALSE;
}
if (RExC_contains_locale && ! ANYOF_POSIXL_SSC_TEST_ALL_SET(ssc)) {
return FALSE;
}
return TRUE;
}
#define INVLIST_INDEX 0
#define ONLY_LOCALE_MATCHES_INDEX 1
#define DEFERRED_USER_DEFINED_INDEX 2
STATIC SV*
S_get_ANYOF_cp_list_for_ssc(pTHX_ const RExC_state_t *pRExC_state,
const regnode_charclass* const node)
{
/* Returns a mortal inversion list defining which code points are matched
* by 'node', which is of type ANYOF. Handles complementing the result if
* appropriate. If some code points aren't knowable at this time, the
* returned list must, and will, contain every code point that is a
* possibility. */
dVAR;
SV* invlist = NULL;
SV* only_utf8_locale_invlist = NULL;
unsigned int i;
const U32 n = ARG(node);
bool new_node_has_latin1 = FALSE;
const U8 flags = OP(node) == ANYOFH ? 0 : ANYOF_FLAGS(node);
PERL_ARGS_ASSERT_GET_ANYOF_CP_LIST_FOR_SSC;
/* Look at the data structure created by S_set_ANYOF_arg() */
if (n != ANYOF_ONLY_HAS_BITMAP) {
SV * const rv = MUTABLE_SV(RExC_rxi->data->data[n]);
AV * const av = MUTABLE_AV(SvRV(rv));
SV **const ary = AvARRAY(av);
assert(RExC_rxi->data->what[n] == 's');
if (av_tindex_skip_len_mg(av) >= DEFERRED_USER_DEFINED_INDEX) {
/* Here there are things that won't be known until runtime -- we
* have to assume it could be anything */
invlist = sv_2mortal(_new_invlist(1));
return _add_range_to_invlist(invlist, 0, UV_MAX);
}
else if (ary[INVLIST_INDEX]) {
/* Use the node's inversion list */
invlist = sv_2mortal(invlist_clone(ary[INVLIST_INDEX], NULL));
}
/* Get the code points valid only under UTF-8 locales */
if ( (flags & ANYOFL_FOLD)
&& av_tindex_skip_len_mg(av) >= ONLY_LOCALE_MATCHES_INDEX)
{
only_utf8_locale_invlist = ary[ONLY_LOCALE_MATCHES_INDEX];
}
}
if (! invlist) {
invlist = sv_2mortal(_new_invlist(0));
}
/* An ANYOF node contains a bitmap for the first NUM_ANYOF_CODE_POINTS
* code points, and an inversion list for the others, but if there are code
* points that should match only conditionally on the target string being
* UTF-8, those are placed in the inversion list, and not the bitmap.
* Since there are circumstances under which they could match, they are
* included in the SSC. But if the ANYOF node is to be inverted, we have
* to exclude them here, so that when we invert below, the end result
* actually does include them. (Think about "\xe0" =~ /[^\xc0]/di;). We
* have to do this here before we add the unconditionally matched code
* points */
if (flags & ANYOF_INVERT) {
_invlist_intersection_complement_2nd(invlist,
PL_UpperLatin1,
&invlist);
}
/* Add in the points from the bit map */
if (OP(node) != ANYOFH) {
for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) {
if (ANYOF_BITMAP_TEST(node, i)) {
unsigned int start = i++;
for (; i < NUM_ANYOF_CODE_POINTS
&& ANYOF_BITMAP_TEST(node, i); ++i)
{
/* empty */
}
invlist = _add_range_to_invlist(invlist, start, i-1);
new_node_has_latin1 = TRUE;
}
}
}
/* If this can match all upper Latin1 code points, have to add them
* as well. But don't add them if inverting, as when that gets done below,
* it would exclude all these characters, including the ones it shouldn't
* that were added just above */
if (! (flags & ANYOF_INVERT) && OP(node) == ANYOFD
&& (flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))
{
_invlist_union(invlist, PL_UpperLatin1, &invlist);
}
/* Similarly for these */
if (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
_invlist_union_complement_2nd(invlist, PL_InBitmap, &invlist);
}
if (flags & ANYOF_INVERT) {
_invlist_invert(invlist);
}
else if (flags & ANYOFL_FOLD) {
if (new_node_has_latin1) {
/* Under /li, any 0-255 could fold to any other 0-255, depending on
* the locale. We can skip this if there are no 0-255 at all. */
_invlist_union(invlist, PL_Latin1, &invlist);
invlist = add_cp_to_invlist(invlist, LATIN_SMALL_LETTER_DOTLESS_I);
invlist = add_cp_to_invlist(invlist, LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE);
}
else {
if (_invlist_contains_cp(invlist, LATIN_SMALL_LETTER_DOTLESS_I)) {
invlist = add_cp_to_invlist(invlist, 'I');
}
if (_invlist_contains_cp(invlist,
LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE))
{
invlist = add_cp_to_invlist(invlist, 'i');
}
}
}
/* Similarly add the UTF-8 locale possible matches. These have to be
* deferred until after the non-UTF-8 locale ones are taken care of just
* above, or it leads to wrong results under ANYOF_INVERT */
if (only_utf8_locale_invlist) {
_invlist_union_maybe_complement_2nd(invlist,
only_utf8_locale_invlist,
flags & ANYOF_INVERT,
&invlist);
}
return invlist;
}
/* These two functions currently do the exact same thing */
#define ssc_init_zero ssc_init
#define ssc_add_cp(ssc, cp) ssc_add_range((ssc), (cp), (cp))
#define ssc_match_all_cp(ssc) ssc_add_range(ssc, 0, UV_MAX)
/* 'AND' a given class with another one. Can create false positives. 'ssc'
* should not be inverted. 'and_with->flags & ANYOF_MATCHES_POSIXL' should be
* 0 if 'and_with' is a regnode_charclass instead of a regnode_ssc. */
STATIC void
S_ssc_and(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
const regnode_charclass *and_with)
{
/* Accumulate into SSC 'ssc' its 'AND' with 'and_with', which is either
* another SSC or a regular ANYOF class. Can create false positives. */
SV* anded_cp_list;
U8 and_with_flags = (OP(and_with) == ANYOFH) ? 0 : ANYOF_FLAGS(and_with);
U8 anded_flags;
PERL_ARGS_ASSERT_SSC_AND;
assert(is_ANYOF_SYNTHETIC(ssc));
/* 'and_with' is used as-is if it too is an SSC; otherwise have to extract
* the code point inversion list and just the relevant flags */
if (is_ANYOF_SYNTHETIC(and_with)) {
anded_cp_list = ((regnode_ssc *)and_with)->invlist;
anded_flags = and_with_flags;
/* XXX This is a kludge around what appears to be deficiencies in the
* optimizer. If we make S_ssc_anything() add in the WARN_SUPER flag,
* there are paths through the optimizer where it doesn't get weeded
* out when it should. And if we don't make some extra provision for
* it like the code just below, it doesn't get added when it should.
* This solution is to add it only when AND'ing, which is here, and
* only when what is being AND'ed is the pristine, original node
* matching anything. Thus it is like adding it to ssc_anything() but
* only when the result is to be AND'ed. Probably the same solution
* could be adopted for the same problem we have with /l matching,
* which is solved differently in S_ssc_init(), and that would lead to
* fewer false positives than that solution has. But if this solution
* creates bugs, the consequences are only that a warning isn't raised
* that should be; while the consequences for having /l bugs is
* incorrect matches */
if (ssc_is_anything((regnode_ssc *)and_with)) {
anded_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
}
}
else {
anded_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, and_with);
if (OP(and_with) == ANYOFD) {
anded_flags = and_with_flags & ANYOF_COMMON_FLAGS;
}
else {
anded_flags = and_with_flags
&( ANYOF_COMMON_FLAGS
|ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
|ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
if (ANYOFL_UTF8_LOCALE_REQD(and_with_flags)) {
anded_flags &=
ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
}
}
}
ANYOF_FLAGS(ssc) &= anded_flags;
/* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
* C2 is the list of code points in 'and-with'; P2, its posix classes.
* 'and_with' may be inverted. When not inverted, we have the situation of
* computing:
* (C1 | P1) & (C2 | P2)
* = (C1 & (C2 | P2)) | (P1 & (C2 | P2))
* = ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
* <= ((C1 & C2) | P2)) | ( P1 | (P1 & P2))
* <= ((C1 & C2) | P1 | P2)
* Alternatively, the last few steps could be:
* = ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
* <= ((C1 & C2) | C1 ) | ( C2 | (P1 & P2))
* <= (C1 | C2 | (P1 & P2))
* We favor the second approach if either P1 or P2 is non-empty. This is
* because these components are a barrier to doing optimizations, as what
* they match cannot be known until the moment of matching as they are
* dependent on the current locale, 'AND"ing them likely will reduce or
* eliminate them.
* But we can do better if we know that C1,P1 are in their initial state (a
* frequent occurrence), each matching everything:
* (<everything>) & (C2 | P2) = C2 | P2
* Similarly, if C2,P2 are in their initial state (again a frequent
* occurrence), the result is a no-op
* (C1 | P1) & (<everything>) = C1 | P1
*
* Inverted, we have
* (C1 | P1) & ~(C2 | P2) = (C1 | P1) & (~C2 & ~P2)
* = (C1 & (~C2 & ~P2)) | (P1 & (~C2 & ~P2))
* <= (C1 & ~C2) | (P1 & ~P2)
* */
if ((and_with_flags & ANYOF_INVERT)
&& ! is_ANYOF_SYNTHETIC(and_with))
{
unsigned int i;
ssc_intersection(ssc,
anded_cp_list,
FALSE /* Has already been inverted */
);
/* If either P1 or P2 is empty, the intersection will be also; can skip
* the loop */
if (! (and_with_flags & ANYOF_MATCHES_POSIXL)) {
ANYOF_POSIXL_ZERO(ssc);
}
else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
/* Note that the Posix class component P from 'and_with' actually
* looks like:
* P = Pa | Pb | ... | Pn
* where each component is one posix class, such as in [\w\s].
* Thus
* ~P = ~(Pa | Pb | ... | Pn)
* = ~Pa & ~Pb & ... & ~Pn
* <= ~Pa | ~Pb | ... | ~Pn
* The last is something we can easily calculate, but unfortunately
* is likely to have many false positives. We could do better
* in some (but certainly not all) instances if two classes in
* P have known relationships. For example
* :lower: <= :alpha: <= :alnum: <= \w <= :graph: <= :print:
* So
* :lower: & :print: = :lower:
* And similarly for classes that must be disjoint. For example,
* since \s and \w can have no elements in common based on rules in
* the POSIX standard,
* \w & ^\S = nothing
* Unfortunately, some vendor locales do not meet the Posix
* standard, in particular almost everything by Microsoft.
* The loop below just changes e.g., \w into \W and vice versa */
regnode_charclass_posixl temp;
int add = 1; /* To calculate the index of the complement */
Zero(&temp, 1, regnode_charclass_posixl);
ANYOF_POSIXL_ZERO(&temp);
for (i = 0; i < ANYOF_MAX; i++) {
assert(i % 2 != 0
|| ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)
|| ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i + 1));
if (ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)) {
ANYOF_POSIXL_SET(&temp, i + add);
}
add = 0 - add; /* 1 goes to -1; -1 goes to 1 */
}
ANYOF_POSIXL_AND(&temp, ssc);
} /* else ssc already has no posixes */
} /* else: Not inverted. This routine is a no-op if 'and_with' is an SSC
in its initial state */
else if (! is_ANYOF_SYNTHETIC(and_with)
|| ! ssc_is_cp_posixl_init(pRExC_state, (regnode_ssc *)and_with))
{
/* But if 'ssc' is in its initial state, the result is just 'and_with';
* copy it over 'ssc' */
if (ssc_is_cp_posixl_init(pRExC_state, ssc)) {
if (is_ANYOF_SYNTHETIC(and_with)) {
StructCopy(and_with, ssc, regnode_ssc);
}
else {
ssc->invlist = anded_cp_list;
ANYOF_POSIXL_ZERO(ssc);
if (and_with_flags & ANYOF_MATCHES_POSIXL) {
ANYOF_POSIXL_OR((regnode_charclass_posixl*) and_with, ssc);
}
}
}
else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)
|| (and_with_flags & ANYOF_MATCHES_POSIXL))
{
/* One or the other of P1, P2 is non-empty. */
if (and_with_flags & ANYOF_MATCHES_POSIXL) {
ANYOF_POSIXL_AND((regnode_charclass_posixl*) and_with, ssc);
}
ssc_union(ssc, anded_cp_list, FALSE);
}
else { /* P1 = P2 = empty */
ssc_intersection(ssc, anded_cp_list, FALSE);
}
}
}
STATIC void
S_ssc_or(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
const regnode_charclass *or_with)
{
/* Accumulate into SSC 'ssc' its 'OR' with 'or_with', which is either
* another SSC or a regular ANYOF class. Can create false positives if
* 'or_with' is to be inverted. */
SV* ored_cp_list;
U8 ored_flags;
U8 or_with_flags = (OP(or_with) == ANYOFH) ? 0 : ANYOF_FLAGS(or_with);
PERL_ARGS_ASSERT_SSC_OR;
assert(is_ANYOF_SYNTHETIC(ssc));
/* 'or_with' is used as-is if it too is an SSC; otherwise have to extract
* the code point inversion list and just the relevant flags */
if (is_ANYOF_SYNTHETIC(or_with)) {
ored_cp_list = ((regnode_ssc*) or_with)->invlist;
ored_flags = or_with_flags;
}
else {
ored_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, or_with);
ored_flags = or_with_flags & ANYOF_COMMON_FLAGS;
if (OP(or_with) != ANYOFD) {
ored_flags
|= or_with_flags
& ( ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
|ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
if (ANYOFL_UTF8_LOCALE_REQD(or_with_flags)) {
ored_flags |=
ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
}
}
}
ANYOF_FLAGS(ssc) |= ored_flags;
/* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
* C2 is the list of code points in 'or-with'; P2, its posix classes.
* 'or_with' may be inverted. When not inverted, we have the simple
* situation of computing:
* (C1 | P1) | (C2 | P2) = (C1 | C2) | (P1 | P2)
* If P1|P2 yields a situation with both a class and its complement are
* set, like having both \w and \W, this matches all code points, and we
* can delete these from the P component of the ssc going forward. XXX We
* might be able to delete all the P components, but I (khw) am not certain
* about this, and it is better to be safe.
*
* Inverted, we have
* (C1 | P1) | ~(C2 | P2) = (C1 | P1) | (~C2 & ~P2)
* <= (C1 | P1) | ~C2
* <= (C1 | ~C2) | P1
* (which results in actually simpler code than the non-inverted case)
* */
if ((or_with_flags & ANYOF_INVERT)
&& ! is_ANYOF_SYNTHETIC(or_with))
{
/* We ignore P2, leaving P1 going forward */
} /* else Not inverted */
else if (or_with_flags & ANYOF_MATCHES_POSIXL) {
ANYOF_POSIXL_OR((regnode_charclass_posixl*)or_with, ssc);
if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
unsigned int i;
for (i = 0; i < ANYOF_MAX; i += 2) {
if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i + 1))
{
ssc_match_all_cp(ssc);
ANYOF_POSIXL_CLEAR(ssc, i);
ANYOF_POSIXL_CLEAR(ssc, i+1);
}
}
}
}
ssc_union(ssc,
ored_cp_list,
FALSE /* Already has been inverted */
);
}
PERL_STATIC_INLINE void
S_ssc_union(pTHX_ regnode_ssc *ssc, SV* const invlist, const bool invert2nd)
{
PERL_ARGS_ASSERT_SSC_UNION;
assert(is_ANYOF_SYNTHETIC(ssc));
_invlist_union_maybe_complement_2nd(ssc->invlist,
invlist,
invert2nd,
&ssc->invlist);
}
PERL_STATIC_INLINE void
S_ssc_intersection(pTHX_ regnode_ssc *ssc,
SV* const invlist,
const bool invert2nd)
{
PERL_ARGS_ASSERT_SSC_INTERSECTION;
assert(is_ANYOF_SYNTHETIC(ssc));
_invlist_intersection_maybe_complement_2nd(ssc->invlist,
invlist,
invert2nd,
&ssc->invlist);
}
PERL_STATIC_INLINE void
S_ssc_add_range(pTHX_ regnode_ssc *ssc, const UV start, const UV end)
{
PERL_ARGS_ASSERT_SSC_ADD_RANGE;
assert(is_ANYOF_SYNTHETIC(ssc));
ssc->invlist = _add_range_to_invlist(ssc->invlist, start, end);
}
PERL_STATIC_INLINE void
S_ssc_cp_and(pTHX_ regnode_ssc *ssc, const UV cp)
{
/* AND just the single code point 'cp' into the SSC 'ssc' */
SV* cp_list = _new_invlist(2);
PERL_ARGS_ASSERT_SSC_CP_AND;
assert(is_ANYOF_SYNTHETIC(ssc));
cp_list = add_cp_to_invlist(cp_list, cp);
ssc_intersection(ssc, cp_list,
FALSE /* Not inverted */
);
SvREFCNT_dec_NN(cp_list);
}
PERL_STATIC_INLINE void
S_ssc_clear_locale(regnode_ssc *ssc)
{
/* Set the SSC 'ssc' to not match any locale things */
PERL_ARGS_ASSERT_SSC_CLEAR_LOCALE;
assert(is_ANYOF_SYNTHETIC(ssc));
ANYOF_POSIXL_ZERO(ssc);
ANYOF_FLAGS(ssc) &= ~ANYOF_LOCALE_FLAGS;
}
#define NON_OTHER_COUNT NON_OTHER_COUNT_FOR_USE_ONLY_BY_REGCOMP_DOT_C
STATIC bool
S_is_ssc_worth_it(const RExC_state_t * pRExC_state, const regnode_ssc * ssc)
{
/* The synthetic start class is used to hopefully quickly winnow down
* places where a pattern could start a match in the target string. If it
* doesn't really narrow things down that much, there isn't much point to
* having the overhead of using it. This function uses some very crude
* heuristics to decide if to use the ssc or not.
*
* It returns TRUE if 'ssc' rules out more than half what it considers to
* be the "likely" possible matches, but of course it doesn't know what the
* actual things being matched are going to be; these are only guesses
*
* For /l matches, it assumes that the only likely matches are going to be
* in the 0-255 range, uniformly distributed, so half of that is 127
* For /a and /d matches, it assumes that the likely matches will be just
* the ASCII range, so half of that is 63
* For /u and there isn't anything matching above the Latin1 range, it
* assumes that that is the only range likely to be matched, and uses
* half that as the cut-off: 127. If anything matches above Latin1,
* it assumes that all of Unicode could match (uniformly), except for
* non-Unicode code points and things in the General Category "Other"
* (unassigned, private use, surrogates, controls and formats). This
* is a much large number. */
U32 count = 0; /* Running total of number of code points matched by
'ssc' */
UV start, end; /* Start and end points of current range in inversion
XXX outdated. UTF-8 locales are common, what about invert? list */
const U32 max_code_points = (LOC)
? 256
: (( ! UNI_SEMANTICS
|| invlist_highest(ssc->invlist) < 256)
? 128
: NON_OTHER_COUNT);
const U32 max_match = max_code_points / 2;
PERL_ARGS_ASSERT_IS_SSC_WORTH_IT;
invlist_iterinit(ssc->invlist);
while (invlist_iternext(ssc->invlist, &start, &end)) {
if (start >= max_code_points) {
break;
}
end = MIN(end, max_code_points - 1);
count += end - start + 1;
if (count >= max_match) {
invlist_iterfinish(ssc->invlist);
return FALSE;
}
}
return TRUE;
}
STATIC void
S_ssc_finalize(pTHX_ RExC_state_t *pRExC_state, regnode_ssc *ssc)
{
/* The inversion list in the SSC is marked mortal; now we need a more
* permanent copy, which is stored the same way that is done in a regular
* ANYOF node, with the first NUM_ANYOF_CODE_POINTS code points in a bit
* map */
SV* invlist = invlist_clone(ssc->invlist, NULL);
PERL_ARGS_ASSERT_SSC_FINALIZE;
assert(is_ANYOF_SYNTHETIC(ssc));
/* The code in this file assumes that all but these flags aren't relevant
* to the SSC, except SSC_MATCHES_EMPTY_STRING, which should be cleared
* by the time we reach here */
assert(! (ANYOF_FLAGS(ssc)
& ~( ANYOF_COMMON_FLAGS
|ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
|ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)));
populate_ANYOF_from_invlist( (regnode *) ssc, &invlist);
set_ANYOF_arg(pRExC_state, (regnode *) ssc, invlist, NULL, NULL);
/* Make sure is clone-safe */
ssc->invlist = NULL;
if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
ANYOF_FLAGS(ssc) |= ANYOF_MATCHES_POSIXL;
OP(ssc) = ANYOFPOSIXL;
}
else if (RExC_contains_locale) {
OP(ssc) = ANYOFL;
}
assert(! (ANYOF_FLAGS(ssc) & ANYOF_LOCALE_FLAGS) || RExC_contains_locale);
}
#define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
#define TRIE_LIST_CUR(state) ( TRIE_LIST_ITEM( state, 0 ).forid )
#define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
#define TRIE_LIST_USED(idx) ( trie->states[state].trans.list \
? (TRIE_LIST_CUR( idx ) - 1) \
: 0 )
#ifdef DEBUGGING
/*
dump_trie(trie,widecharmap,revcharmap)
dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc)
dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc)
These routines dump out a trie in a somewhat readable format.
The _interim_ variants are used for debugging the interim
tables that are used to generate the final compressed
representation which is what dump_trie expects.
Part of the reason for their existence is to provide a form
of documentation as to how the different representations function.
*/
/*
Dumps the final compressed table form of the trie to Perl_debug_log.
Used for debugging make_trie().
*/
STATIC void
S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap,
AV *revcharmap, U32 depth)
{
U32 state;
SV *sv=sv_newmortal();
int colwidth= widecharmap ? 6 : 4;
U16 word;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_DUMP_TRIE;
Perl_re_indentf( aTHX_ "Char : %-6s%-6s%-4s ",
depth+1, "Match","Base","Ofs" );
for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
SV ** const tmp = av_fetch( revcharmap, state, 0);
if ( tmp ) {
Perl_re_printf( aTHX_ "%*s",
colwidth,
pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
PL_colors[0], PL_colors[1],
(SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
PERL_PV_ESCAPE_FIRSTCHAR
)
);
}
}
Perl_re_printf( aTHX_ "\n");
Perl_re_indentf( aTHX_ "State|-----------------------", depth+1);
for( state = 0 ; state < trie->uniquecharcount ; state++ )
Perl_re_printf( aTHX_ "%.*s", colwidth, "--------");
Perl_re_printf( aTHX_ "\n");
for( state = 1 ; state < trie->statecount ; state++ ) {
const U32 base = trie->states[ state ].trans.base;
Perl_re_indentf( aTHX_ "#%4" UVXf "|", depth+1, (UV)state);
if ( trie->states[ state ].wordnum ) {
Perl_re_printf( aTHX_ " W%4X", trie->states[ state ].wordnum );
} else {
Perl_re_printf( aTHX_ "%6s", "" );
}
Perl_re_printf( aTHX_ " @%4" UVXf " ", (UV)base );
if ( base ) {
U32 ofs = 0;
while( ( base + ofs < trie->uniquecharcount ) ||
( base + ofs - trie->uniquecharcount < trie->lasttrans
&& trie->trans[ base + ofs - trie->uniquecharcount ].check
!= state))
ofs++;
Perl_re_printf( aTHX_ "+%2" UVXf "[ ", (UV)ofs);
for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
if ( ( base + ofs >= trie->uniquecharcount )
&& ( base + ofs - trie->uniquecharcount
< trie->lasttrans )
&& trie->trans[ base + ofs
- trie->uniquecharcount ].check == state )
{
Perl_re_printf( aTHX_ "%*" UVXf, colwidth,
(UV)trie->trans[ base + ofs - trie->uniquecharcount ].next
);
} else {
Perl_re_printf( aTHX_ "%*s", colwidth," ." );
}
}
Perl_re_printf( aTHX_ "]");
}
Perl_re_printf( aTHX_ "\n" );
}
Perl_re_indentf( aTHX_ "word_info N:(prev,len)=",
depth);
for (word=1; word <= trie->wordcount; word++) {
Perl_re_printf( aTHX_ " %d:(%d,%d)",
(int)word, (int)(trie->wordinfo[word].prev),
(int)(trie->wordinfo[word].len));
}
Perl_re_printf( aTHX_ "\n" );
}
/*
Dumps a fully constructed but uncompressed trie in list form.
List tries normally only are used for construction when the number of
possible chars (trie->uniquecharcount) is very high.
Used for debugging make_trie().
*/
STATIC void
S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
HV *widecharmap, AV *revcharmap, U32 next_alloc,
U32 depth)
{
U32 state;
SV *sv=sv_newmortal();
int colwidth= widecharmap ? 6 : 4;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_LIST;
/* print out the table precompression. */
Perl_re_indentf( aTHX_ "State :Word | Transition Data\n",
depth+1 );
Perl_re_indentf( aTHX_ "%s",
depth+1, "------:-----+-----------------\n" );
for( state=1 ; state < next_alloc ; state ++ ) {
U16 charid;
Perl_re_indentf( aTHX_ " %4" UVXf " :",
depth+1, (UV)state );
if ( ! trie->states[ state ].wordnum ) {
Perl_re_printf( aTHX_ "%5s| ","");
} else {
Perl_re_printf( aTHX_ "W%4x| ",
trie->states[ state ].wordnum
);
}
for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
SV ** const tmp = av_fetch( revcharmap,
TRIE_LIST_ITEM(state, charid).forid, 0);
if ( tmp ) {
Perl_re_printf( aTHX_ "%*s:%3X=%4" UVXf " | ",
colwidth,
pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp),
colwidth,
PL_colors[0], PL_colors[1],
(SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)
| PERL_PV_ESCAPE_FIRSTCHAR
) ,
TRIE_LIST_ITEM(state, charid).forid,
(UV)TRIE_LIST_ITEM(state, charid).newstate
);
if (!(charid % 10))
Perl_re_printf( aTHX_ "\n%*s| ",
(int)((depth * 2) + 14), "");
}
}
Perl_re_printf( aTHX_ "\n");
}
}
/*
Dumps a fully constructed but uncompressed trie in table form.
This is the normal DFA style state transition table, with a few
twists to facilitate compression later.
Used for debugging make_trie().
*/
STATIC void
S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie,
HV *widecharmap, AV *revcharmap, U32 next_alloc,
U32 depth)
{
U32 state;
U16 charid;
SV *sv=sv_newmortal();
int colwidth= widecharmap ? 6 : 4;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_TABLE;
/*
print out the table precompression so that we can do a visual check
that they are identical.
*/
Perl_re_indentf( aTHX_ "Char : ", depth+1 );
for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
SV ** const tmp = av_fetch( revcharmap, charid, 0);
if ( tmp ) {
Perl_re_printf( aTHX_ "%*s",
colwidth,
pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
PL_colors[0], PL_colors[1],
(SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
PERL_PV_ESCAPE_FIRSTCHAR
)
);
}
}
Perl_re_printf( aTHX_ "\n");
Perl_re_indentf( aTHX_ "State+-", depth+1 );
for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
Perl_re_printf( aTHX_ "%.*s", colwidth,"--------");
}
Perl_re_printf( aTHX_ "\n" );
for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
Perl_re_indentf( aTHX_ "%4" UVXf " : ",
depth+1,
(UV)TRIE_NODENUM( state ) );
for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
if (v)
Perl_re_printf( aTHX_ "%*" UVXf, colwidth, v );
else
Perl_re_printf( aTHX_ "%*s", colwidth, "." );
}
if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
Perl_re_printf( aTHX_ " (%4" UVXf ")\n",
(UV)trie->trans[ state ].check );
} else {
Perl_re_printf( aTHX_ " (%4" UVXf ") W%4X\n",
(UV)trie->trans[ state ].check,
trie->states[ TRIE_NODENUM( state ) ].wordnum );
}
}
}
#endif
/* make_trie(startbranch,first,last,tail,word_count,flags,depth)
startbranch: the first branch in the whole branch sequence
first : start branch of sequence of branch-exact nodes.
May be the same as startbranch
last : Thing following the last branch.
May be the same as tail.
tail : item following the branch sequence
count : words in the sequence
flags : currently the OP() type we will be building one of /EXACT(|F|FA|FU|FU_SS|L|FLU8)/
depth : indent depth
Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
A trie is an N'ary tree where the branches are determined by digital
decomposition of the key. IE, at the root node you look up the 1st character and
follow that branch repeat until you find the end of the branches. Nodes can be
marked as "accepting" meaning they represent a complete word. Eg:
/he|she|his|hers/
would convert into the following structure. Numbers represent states, letters
following numbers represent valid transitions on the letter from that state, if
the number is in square brackets it represents an accepting state, otherwise it
will be in parenthesis.
+-h->+-e->[3]-+-r->(8)-+-s->[9]
| |
| (2)
| |
(1) +-i->(6)-+-s->[7]
|
+-s->(3)-+-h->(4)-+-e->[5]
Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
This shows that when matching against the string 'hers' we will begin at state 1
read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
is also accepting. Thus we know that we can match both 'he' and 'hers' with a
single traverse. We store a mapping from accepting to state to which word was
matched, and then when we have multiple possibilities we try to complete the
rest of the regex in the order in which they occurred in the alternation.
The only prior NFA like behaviour that would be changed by the TRIE support is
the silent ignoring of duplicate alternations which are of the form:
/ (DUPE|DUPE) X? (?{ ... }) Y /x
Thus EVAL blocks following a trie may be called a different number of times with
and without the optimisation. With the optimisations dupes will be silently
ignored. This inconsistent behaviour of EVAL type nodes is well established as
the following demonstrates:
'words'=~/(word|word|word)(?{ print $1 })[xyz]/
which prints out 'word' three times, but
'words'=~/(word|word|word)(?{ print $1 })S/
which doesnt print it out at all. This is due to other optimisations kicking in.
Example of what happens on a structural level:
The regexp /(ac|ad|ab)+/ will produce the following debug output:
1: CURLYM[1] {1,32767}(18)
5: BRANCH(8)
6: EXACT <ac>(16)
8: BRANCH(11)
9: EXACT <ad>(16)
11: BRANCH(14)
12: EXACT <ab>(16)
16: SUCCEED(0)
17: NOTHING(18)
18: END(0)
This would be optimizable with startbranch=5, first=5, last=16, tail=16
and should turn into:
1: CURLYM[1] {1,32767}(18)
5: TRIE(16)
[Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
<ac>
<ad>
<ab>
16: SUCCEED(0)
17: NOTHING(18)
18: END(0)
Cases where tail != last would be like /(?foo|bar)baz/:
1: BRANCH(4)
2: EXACT <foo>(8)
4: BRANCH(7)
5: EXACT <bar>(8)
7: TAIL(8)
8: EXACT <baz>(10)
10: END(0)
which would be optimizable with startbranch=1, first=1, last=7, tail=8
and would end up looking like:
1: TRIE(8)
[Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
<foo>
<bar>
7: TAIL(8)
8: EXACT <baz>(10)
10: END(0)
d = uvchr_to_utf8_flags(d, uv, 0);
is the recommended Unicode-aware way of saying
*(d++) = uv;
*/
#define TRIE_STORE_REVCHAR(val) \
STMT_START { \
if (UTF) { \
SV *zlopp = newSV(UTF8_MAXBYTES); \
unsigned char *flrbbbbb = (unsigned char *) SvPVX(zlopp); \
unsigned const char *const kapow = uvchr_to_utf8(flrbbbbb, val); \
SvCUR_set(zlopp, kapow - flrbbbbb); \
SvPOK_on(zlopp); \
SvUTF8_on(zlopp); \
av_push(revcharmap, zlopp); \
} else { \
char ooooff = (char)val; \
av_push(revcharmap, newSVpvn(&ooooff, 1)); \
} \
} STMT_END
/* This gets the next character from the input, folding it if not already
* folded. */
#define TRIE_READ_CHAR STMT_START { \
wordlen++; \
if ( UTF ) { \
/* if it is UTF then it is either already folded, or does not need \
* folding */ \
uvc = valid_utf8_to_uvchr( (const U8*) uc, &len); \
} \
else if (folder == PL_fold_latin1) { \
/* This folder implies Unicode rules, which in the range expressible \
* by not UTF is the lower case, with the two exceptions, one of \
* which should have been taken care of before calling this */ \
assert(*uc != LATIN_SMALL_LETTER_SHARP_S); \
uvc = toLOWER_L1(*uc); \
if (UNLIKELY(uvc == MICRO_SIGN)) uvc = GREEK_SMALL_LETTER_MU; \
len = 1; \
} else { \
/* raw data, will be folded later if needed */ \
uvc = (U32)*uc; \
len = 1; \
} \
} STMT_END
#define TRIE_LIST_PUSH(state,fid,ns) STMT_START { \
if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) { \
U32 ging = TRIE_LIST_LEN( state ) * 2; \
Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
TRIE_LIST_LEN( state ) = ging; \
} \
TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid; \
TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns; \
TRIE_LIST_CUR( state )++; \
} STMT_END
#define TRIE_LIST_NEW(state) STMT_START { \
Newx( trie->states[ state ].trans.list, \
4, reg_trie_trans_le ); \
TRIE_LIST_CUR( state ) = 1; \
TRIE_LIST_LEN( state ) = 4; \
} STMT_END
#define TRIE_HANDLE_WORD(state) STMT_START { \
U16 dupe= trie->states[ state ].wordnum; \
regnode * const noper_next = regnext( noper ); \
\
DEBUG_r({ \
/* store the word for dumping */ \
SV* tmp; \
if (OP(noper) != NOTHING) \
tmp = newSVpvn_utf8(STRING(noper), STR_LEN(noper), UTF); \
else \
tmp = newSVpvn_utf8( "", 0, UTF ); \
av_push( trie_words, tmp ); \
}); \
\
curword++; \
trie->wordinfo[curword].prev = 0; \
trie->wordinfo[curword].len = wordlen; \
trie->wordinfo[curword].accept = state; \
\
if ( noper_next < tail ) { \
if (!trie->jump) \
trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, \
sizeof(U16) ); \
trie->jump[curword] = (U16)(noper_next - convert); \
if (!jumper) \
jumper = noper_next; \
if (!nextbranch) \
nextbranch= regnext(cur); \
} \
\
if ( dupe ) { \
/* It's a dupe. Pre-insert into the wordinfo[].prev */\
/* chain, so that when the bits of chain are later */\
/* linked together, the dups appear in the chain */\
trie->wordinfo[curword].prev = trie->wordinfo[dupe].prev; \
trie->wordinfo[dupe].prev = curword; \
} else { \
/* we haven't inserted this word yet. */ \
trie->states[ state ].wordnum = curword; \
} \
} STMT_END
#define TRIE_TRANS_STATE(state,base,ucharcount,charid,special) \
( ( base + charid >= ucharcount \
&& base + charid < ubound \
&& state == trie->trans[ base - ucharcount + charid ].check \
&& trie->trans[ base - ucharcount + charid ].next ) \
? trie->trans[ base - ucharcount + charid ].next \
: ( state==1 ? special : 0 ) \
)
#define TRIE_BITMAP_SET_FOLDED(trie, uvc, folder) \
STMT_START { \
TRIE_BITMAP_SET(trie, uvc); \
/* store the folded codepoint */ \
if ( folder ) \
TRIE_BITMAP_SET(trie, folder[(U8) uvc ]); \
\
if ( !UTF ) { \
/* store first byte of utf8 representation of */ \
/* variant codepoints */ \
if (! UVCHR_IS_INVARIANT(uvc)) { \
TRIE_BITMAP_SET(trie, UTF8_TWO_BYTE_HI(uvc)); \
} \
} \
} STMT_END
#define MADE_TRIE 1
#define MADE_JUMP_TRIE 2
#define MADE_EXACT_TRIE 4
STATIC I32
S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch,
regnode *first, regnode *last, regnode *tail,
U32 word_count, U32 flags, U32 depth)
{
/* first pass, loop through and scan words */
reg_trie_data *trie;
HV *widecharmap = NULL;
AV *revcharmap = newAV();
regnode *cur;
STRLEN len = 0;
UV uvc = 0;
U16 curword = 0;
U32 next_alloc = 0;
regnode *jumper = NULL;
regnode *nextbranch = NULL;
regnode *convert = NULL;
U32 *prev_states; /* temp array mapping each state to previous one */
/* we just use folder as a flag in utf8 */
const U8 * folder = NULL;
/* in the below add_data call we are storing either 'tu' or 'tuaa'
* which stands for one trie structure, one hash, optionally followed
* by two arrays */
#ifdef DEBUGGING
const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tuaa"));
AV *trie_words = NULL;
/* along with revcharmap, this only used during construction but both are
* useful during debugging so we store them in the struct when debugging.
*/
#else
const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tu"));
STRLEN trie_charcount=0;
#endif
SV *re_trie_maxbuff;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_MAKE_TRIE;
#ifndef DEBUGGING
PERL_UNUSED_ARG(depth);
#endif
switch (flags) {
case EXACT: case EXACT_ONLY8: case EXACTL: break;
case EXACTFAA:
case EXACTFUP:
case EXACTFU:
case EXACTFLU8: folder = PL_fold_latin1; break;
case EXACTF: folder = PL_fold; break;
default: Perl_croak( aTHX_ "panic! In trie construction, unknown node type %u %s", (unsigned) flags, PL_reg_name[flags] );
}
trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
trie->refcount = 1;
trie->startstate = 1;
trie->wordcount = word_count;
RExC_rxi->data->data[ data_slot ] = (void*)trie;
trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
if (flags == EXACT || flags == EXACT_ONLY8 || flags == EXACTL)
trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
trie->wordinfo = (reg_trie_wordinfo *) PerlMemShared_calloc(
trie->wordcount+1, sizeof(reg_trie_wordinfo));
DEBUG_r({
trie_words = newAV();
});
re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, GV_ADD);
assert(re_trie_maxbuff);
if (!SvIOK(re_trie_maxbuff)) {
sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
}
DEBUG_TRIE_COMPILE_r({
Perl_re_indentf( aTHX_
"make_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
depth+1,
REG_NODE_NUM(startbranch), REG_NODE_NUM(first),
REG_NODE_NUM(last), REG_NODE_NUM(tail), (int)depth);
});
/* Find the node we are going to overwrite */
if ( first == startbranch && OP( last ) != BRANCH ) {
/* whole branch chain */
convert = first;
} else {
/* branch sub-chain */
convert = NEXTOPER( first );
}
/* -- First loop and Setup --
We first traverse the branches and scan each word to determine if it
contains widechars, and how many unique chars there are, this is
important as we have to build a table with at least as many columns as we
have unique chars.
We use an array of integers to represent the character codes 0..255
(trie->charmap) and we use a an HV* to store Unicode characters. We use
the native representation of the character value as the key and IV's for
the coded index.
*TODO* If we keep track of how many times each character is used we can
remap the columns so that the table compression later on is more
efficient in terms of memory by ensuring the most common value is in the
middle and the least common are on the outside. IMO this would be better
than a most to least common mapping as theres a decent chance the most
common letter will share a node with the least common, meaning the node
will not be compressible. With a middle is most common approach the worst
case is when we have the least common nodes twice.
*/
for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
regnode *noper = NEXTOPER( cur );
const U8 *uc;
const U8 *e;
int foldlen = 0;
U32 wordlen = 0; /* required init */
STRLEN minchars = 0;
STRLEN maxchars = 0;
bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the
bitmap?*/
if (OP(noper) == NOTHING) {
/* skip past a NOTHING at the start of an alternation
* eg, /(?:)a|(?:b)/ should be the same as /a|b/
*
* If the next node is not something we are supposed to process
* we will just ignore it due to the condition guarding the
* next block.
*/
regnode *noper_next= regnext(noper);
if (noper_next < tail)
noper= noper_next;
}
if ( noper < tail
&& ( OP(noper) == flags
|| (flags == EXACT && OP(noper) == EXACT_ONLY8)
|| (flags == EXACTFU && ( OP(noper) == EXACTFU_ONLY8
|| OP(noper) == EXACTFUP))))
{
uc= (U8*)STRING(noper);
e= uc + STR_LEN(noper);
} else {
trie->minlen= 0;
continue;
}
if ( set_bit ) { /* bitmap only alloced when !(UTF&&Folding) */
TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte
regardless of encoding */
if (OP( noper ) == EXACTFUP) {
/* false positives are ok, so just set this */
TRIE_BITMAP_SET(trie, LATIN_SMALL_LETTER_SHARP_S);
}
}
for ( ; uc < e ; uc += len ) { /* Look at each char in the current
branch */
TRIE_CHARCOUNT(trie)++;
TRIE_READ_CHAR;
/* TRIE_READ_CHAR returns the current character, or its fold if /i
* is in effect. Under /i, this character can match itself, or
* anything that folds to it. If not under /i, it can match just
* itself. Most folds are 1-1, for example k, K, and KELVIN SIGN
* all fold to k, and all are single characters. But some folds
* expand to more than one character, so for example LATIN SMALL
* LIGATURE FFI folds to the three character sequence 'ffi'. If
* the string beginning at 'uc' is 'ffi', it could be matched by
* three characters, or just by the one ligature character. (It
* could also be matched by two characters: LATIN SMALL LIGATURE FF
* followed by 'i', or by 'f' followed by LATIN SMALL LIGATURE FI).
* (Of course 'I' and/or 'F' instead of 'i' and 'f' can also
* match.) The trie needs to know the minimum and maximum number
* of characters that could match so that it can use size alone to
* quickly reject many match attempts. The max is simple: it is
* the number of folded characters in this branch (since a fold is
* never shorter than what folds to it. */
maxchars++;
/* And the min is equal to the max if not under /i (indicated by
* 'folder' being NULL), or there are no multi-character folds. If
* there is a multi-character fold, the min is incremented just
* once, for the character that folds to the sequence. Each
* character in the sequence needs to be added to the list below of
* characters in the trie, but we count only the first towards the
* min number of characters needed. This is done through the
* variable 'foldlen', which is returned by the macros that look
* for these sequences as the number of bytes the sequence
* occupies. Each time through the loop, we decrement 'foldlen' by
* how many bytes the current char occupies. Only when it reaches
* 0 do we increment 'minchars' or look for another multi-character
* sequence. */
if (folder == NULL) {
minchars++;
}
else if (foldlen > 0) {
foldlen -= (UTF) ? UTF8SKIP(uc) : 1;
}
else {
minchars++;
/* See if *uc is the beginning of a multi-character fold. If
* so, we decrement the length remaining to look at, to account
* for the current character this iteration. (We can use 'uc'
* instead of the fold returned by TRIE_READ_CHAR because for
* non-UTF, the latin1_safe macro is smart enough to account
* for all the unfolded characters, and because for UTF, the
* string will already have been folded earlier in the
* compilation process */
if (UTF) {
if ((foldlen = is_MULTI_CHAR_FOLD_utf8_safe(uc, e))) {
foldlen -= UTF8SKIP(uc);
}
}
else if ((foldlen = is_MULTI_CHAR_FOLD_latin1_safe(uc, e))) {
foldlen--;
}
}
/* The current character (and any potential folds) should be added
* to the possible matching characters for this position in this
* branch */
if ( uvc < 256 ) {
if ( folder ) {
U8 folded= folder[ (U8) uvc ];
if ( !trie->charmap[ folded ] ) {
trie->charmap[ folded ]=( ++trie->uniquecharcount );
TRIE_STORE_REVCHAR( folded );
}
}
if ( !trie->charmap[ uvc ] ) {
trie->charmap[ uvc ]=( ++trie->uniquecharcount );
TRIE_STORE_REVCHAR( uvc );
}
if ( set_bit ) {
/* store the codepoint in the bitmap, and its folded
* equivalent. */
TRIE_BITMAP_SET_FOLDED(trie, uvc, folder);
set_bit = 0; /* We've done our bit :-) */
}
} else {
/* XXX We could come up with the list of code points that fold
* to this using PL_utf8_foldclosures, except not for
* multi-char folds, as there may be multiple combinations
* there that could work, which needs to wait until runtime to
* resolve (The comment about LIGATURE FFI above is such an
* example */
SV** svpp;
if ( !widecharmap )
widecharmap = newHV();
svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
if ( !svpp )
Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%" UVXf, uvc );
if ( !SvTRUE( *svpp ) ) {
sv_setiv( *svpp, ++trie->uniquecharcount );
TRIE_STORE_REVCHAR(uvc);
}
}
} /* end loop through characters in this branch of the trie */
/* We take the min and max for this branch and combine to find the min
* and max for all branches processed so far */
if( cur == first ) {
trie->minlen = minchars;
trie->maxlen = maxchars;
} else if (minchars < trie->minlen) {
trie->minlen = minchars;
} else if (maxchars > trie->maxlen) {
trie->maxlen = maxchars;
}
} /* end first pass */
DEBUG_TRIE_COMPILE_r(
Perl_re_indentf( aTHX_
"TRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
depth+1,
( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
(int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
(int)trie->minlen, (int)trie->maxlen )
);
/*
We now know what we are dealing with in terms of unique chars and
string sizes so we can calculate how much memory a naive
representation using a flat table will take. If it's over a reasonable
limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
conservative but potentially much slower representation using an array
of lists.
At the end we convert both representations into the same compressed
form that will be used in regexec.c for matching with. The latter
is a form that cannot be used to construct with but has memory
properties similar to the list form and access properties similar
to the table form making it both suitable for fast searches and
small enough that its feasable to store for the duration of a program.
See the comment in the code where the compressed table is produced
inplace from the flat tabe representation for an explanation of how
the compression works.
*/
Newx(prev_states, TRIE_CHARCOUNT(trie) + 2, U32);
prev_states[1] = 0;
if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1)
> SvIV(re_trie_maxbuff) )
{
/*
Second Pass -- Array Of Lists Representation
Each state will be represented by a list of charid:state records
(reg_trie_trans_le) the first such element holds the CUR and LEN
points of the allocated array. (See defines above).
We build the initial structure using the lists, and then convert
it into the compressed table form which allows faster lookups
(but cant be modified once converted).
*/
STRLEN transcount = 1;
DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_ "Compiling trie using list compiler\n",
depth+1));
trie->states = (reg_trie_state *)
PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
sizeof(reg_trie_state) );
TRIE_LIST_NEW(1);
next_alloc = 2;
for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
regnode *noper = NEXTOPER( cur );
U32 state = 1; /* required init */
U16 charid = 0; /* sanity init */
U32 wordlen = 0; /* required init */
if (OP(noper) == NOTHING) {
regnode *noper_next= regnext(noper);
if (noper_next < tail)
noper= noper_next;
/* we will undo this assignment if noper does not
* point at a trieable type in the else clause of
* the following statement. */
}
if ( noper < tail
&& ( OP(noper) == flags
|| (flags == EXACT && OP(noper) == EXACT_ONLY8)
|| (flags == EXACTFU && ( OP(noper) == EXACTFU_ONLY8
|| OP(noper) == EXACTFUP))))
{
const U8 *uc= (U8*)STRING(noper);
const U8 *e= uc + STR_LEN(noper);
for ( ; uc < e ; uc += len ) {
TRIE_READ_CHAR;
if ( uvc < 256 ) {
charid = trie->charmap[ uvc ];
} else {
SV** const svpp = hv_fetch( widecharmap,
(char*)&uvc,
sizeof( UV ),
0);
if ( !svpp ) {
charid = 0;
} else {
charid=(U16)SvIV( *svpp );
}
}
/* charid is now 0 if we dont know the char read, or
* nonzero if we do */
if ( charid ) {
U16 check;
U32 newstate = 0;
charid--;
if ( !trie->states[ state ].trans.list ) {
TRIE_LIST_NEW( state );
}
for ( check = 1;
check <= TRIE_LIST_USED( state );
check++ )
{
if ( TRIE_LIST_ITEM( state, check ).forid
== charid )
{
newstate = TRIE_LIST_ITEM( state, check ).newstate;
break;
}
}
if ( ! newstate ) {
newstate = next_alloc++;
prev_states[newstate] = state;
TRIE_LIST_PUSH( state, charid, newstate );
transcount++;
}
state = newstate;
} else {
Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc );
}
}
} else {
/* If we end up here it is because we skipped past a NOTHING, but did not end up
* on a trieable type. So we need to reset noper back to point at the first regop
* in the branch before we call TRIE_HANDLE_WORD()
*/
noper= NEXTOPER(cur);
}
TRIE_HANDLE_WORD(state);
} /* end second pass */
/* next alloc is the NEXT state to be allocated */
trie->statecount = next_alloc;
trie->states = (reg_trie_state *)
PerlMemShared_realloc( trie->states,
next_alloc
* sizeof(reg_trie_state) );
/* and now dump it out before we compress it */
DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
revcharmap, next_alloc,
depth+1)
);
trie->trans = (reg_trie_trans *)
PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
{
U32 state;
U32 tp = 0;
U32 zp = 0;
for( state=1 ; state < next_alloc ; state ++ ) {
U32 base=0;
/*
DEBUG_TRIE_COMPILE_MORE_r(
Perl_re_printf( aTHX_ "tp: %d zp: %d ",tp,zp)
);
*/
if (trie->states[state].trans.list) {
U16 minid=TRIE_LIST_ITEM( state, 1).forid;
U16 maxid=minid;
U16 idx;
for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
if ( forid < minid ) {
minid=forid;
} else if ( forid > maxid ) {
maxid=forid;
}
}
if ( transcount < tp + maxid - minid + 1) {
transcount *= 2;
trie->trans = (reg_trie_trans *)
PerlMemShared_realloc( trie->trans,
transcount
* sizeof(reg_trie_trans) );
Zero( trie->trans + (transcount / 2),
transcount / 2,
reg_trie_trans );
}
base = trie->uniquecharcount + tp - minid;
if ( maxid == minid ) {
U32 set = 0;
for ( ; zp < tp ; zp++ ) {
if ( ! trie->trans[ zp ].next ) {
base = trie->uniquecharcount + zp - minid;
trie->trans[ zp ].next = TRIE_LIST_ITEM( state,
1).newstate;
trie->trans[ zp ].check = state;
set = 1;
break;
}
}
if ( !set ) {
trie->trans[ tp ].next = TRIE_LIST_ITEM( state,
1).newstate;
trie->trans[ tp ].check = state;
tp++;
zp = tp;
}
} else {
for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
const U32 tid = base
- trie->uniquecharcount
+ TRIE_LIST_ITEM( state, idx ).forid;
trie->trans[ tid ].next = TRIE_LIST_ITEM( state,
idx ).newstate;
trie->trans[ tid ].check = state;
}
tp += ( maxid - minid + 1 );
}
Safefree(trie->states[ state ].trans.list);
}
/*
DEBUG_TRIE_COMPILE_MORE_r(
Perl_re_printf( aTHX_ " base: %d\n",base);
);
*/
trie->states[ state ].trans.base=base;
}
trie->lasttrans = tp + 1;
}
} else {
/*
Second Pass -- Flat Table Representation.
we dont use the 0 slot of either trans[] or states[] so we add 1 to
each. We know that we will need Charcount+1 trans at most to store
the data (one row per char at worst case) So we preallocate both
structures assuming worst case.
We then construct the trie using only the .next slots of the entry
structs.
We use the .check field of the first entry of the node temporarily
to make compression both faster and easier by keeping track of how
many non zero fields are in the node.
Since trans are numbered from 1 any 0 pointer in the table is a FAIL
transition.
There are two terms at use here: state as a TRIE_NODEIDX() which is
a number representing the first entry of the node, and state as a
TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1)
and TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3)
if there are 2 entrys per node. eg:
A B A B
1. 2 4 1. 3 7
2. 0 3 3. 0 5
3. 0 0 5. 0 0
4. 0 0 7. 0 0
The table is internally in the right hand, idx form. However as we
also have to deal with the states array which is indexed by nodenum
we have to use TRIE_NODENUM() to convert.
*/
DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_ "Compiling trie using table compiler\n",
depth+1));
trie->trans = (reg_trie_trans *)
PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
* trie->uniquecharcount + 1,
sizeof(reg_trie_trans) );
trie->states = (reg_trie_state *)
PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
sizeof(reg_trie_state) );
next_alloc = trie->uniquecharcount + 1;
for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
regnode *noper = NEXTOPER( cur );
U32 state = 1; /* required init */
U16 charid = 0; /* sanity init */
U32 accept_state = 0; /* sanity init */
U32 wordlen = 0; /* required init */
if (OP(noper) == NOTHING) {
regnode *noper_next= regnext(noper);
if (noper_next < tail)
noper= noper_next;
/* we will undo this assignment if noper does not
* point at a trieable type in the else clause of
* the following statement. */
}
if ( noper < tail
&& ( OP(noper) == flags
|| (flags == EXACT && OP(noper) == EXACT_ONLY8)
|| (flags == EXACTFU && ( OP(noper) == EXACTFU_ONLY8
|| OP(noper) == EXACTFUP))))
{
const U8 *uc= (U8*)STRING(noper);
const U8 *e= uc + STR_LEN(noper);
for ( ; uc < e ; uc += len ) {
TRIE_READ_CHAR;
if ( uvc < 256 ) {
charid = trie->charmap[ uvc ];
} else {
SV* const * const svpp = hv_fetch( widecharmap,
(char*)&uvc,
sizeof( UV ),
0);
charid = svpp ? (U16)SvIV(*svpp) : 0;
}
if ( charid ) {
charid--;
if ( !trie->trans[ state + charid ].next ) {
trie->trans[ state + charid ].next = next_alloc;
trie->trans[ state ].check++;
prev_states[TRIE_NODENUM(next_alloc)]
= TRIE_NODENUM(state);
next_alloc += trie->uniquecharcount;
}
state = trie->trans[ state + charid ].next;
} else {
Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc );
}
/* charid is now 0 if we dont know the char read, or
* nonzero if we do */
}
} else {
/* If we end up here it is because we skipped past a NOTHING, but did not end up
* on a trieable type. So we need to reset noper back to point at the first regop
* in the branch before we call TRIE_HANDLE_WORD().
*/
noper= NEXTOPER(cur);
}
accept_state = TRIE_NODENUM( state );
TRIE_HANDLE_WORD(accept_state);
} /* end second pass */
/* and now dump it out before we compress it */
DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
revcharmap,
next_alloc, depth+1));
{
/*
* Inplace compress the table.*
For sparse data sets the table constructed by the trie algorithm will
be mostly 0/FAIL transitions or to put it another way mostly empty.
(Note that leaf nodes will not contain any transitions.)
This algorithm compresses the tables by eliminating most such
transitions, at the cost of a modest bit of extra work during lookup:
- Each states[] entry contains a .base field which indicates the
index in the state[] array wheres its transition data is stored.
- If .base is 0 there are no valid transitions from that node.
- If .base is nonzero then charid is added to it to find an entry in
the trans array.
-If trans[states[state].base+charid].check!=state then the
transition is taken to be a 0/Fail transition. Thus if there are fail
transitions at the front of the node then the .base offset will point
somewhere inside the previous nodes data (or maybe even into a node
even earlier), but the .check field determines if the transition is
valid.
XXX - wrong maybe?
The following process inplace converts the table to the compressed
table: We first do not compress the root node 1,and mark all its
.check pointers as 1 and set its .base pointer as 1 as well. This
allows us to do a DFA construction from the compressed table later,
and ensures that any .base pointers we calculate later are greater
than 0.
- We set 'pos' to indicate the first entry of the second node.
- We then iterate over the columns of the node, finding the first and
last used entry at l and m. We then copy l..m into pos..(pos+m-l),
and set the .check pointers accordingly, and advance pos
appropriately and repreat for the next node. Note that when we copy
the next pointers we have to convert them from the original
NODEIDX form to NODENUM form as the former is not valid post
compression.
- If a node has no transitions used we mark its base as 0 and do not
advance the pos pointer.
- If a node only has one transition we use a second pointer into the
structure to fill in allocated fail transitions from other states.
This pointer is independent of the main pointer and scans forward
looking for null transitions that are allocated to a state. When it
finds one it writes the single transition into the "hole". If the
pointer doesnt find one the single transition is appended as normal.
- Once compressed we can Renew/realloc the structures to release the
excess space.
See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
specifically Fig 3.47 and the associated pseudocode.
demq
*/
const U32 laststate = TRIE_NODENUM( next_alloc );
U32 state, charid;
U32 pos = 0, zp=0;
trie->statecount = laststate;
for ( state = 1 ; state < laststate ; state++ ) {
U8 flag = 0;
const U32 stateidx = TRIE_NODEIDX( state );
const U32 o_used = trie->trans[ stateidx ].check;
U32 used = trie->trans[ stateidx ].check;
trie->trans[ stateidx ].check = 0;
for ( charid = 0;
used && charid < trie->uniquecharcount;
charid++ )
{
if ( flag || trie->trans[ stateidx + charid ].next ) {
if ( trie->trans[ stateidx + charid ].next ) {
if (o_used == 1) {
for ( ; zp < pos ; zp++ ) {
if ( ! trie->trans[ zp ].next ) {
break;
}
}
trie->states[ state ].trans.base
= zp
+ trie->uniquecharcount
- charid ;
trie->trans[ zp ].next
= SAFE_TRIE_NODENUM( trie->trans[ stateidx
+ charid ].next );
trie->trans[ zp ].check = state;
if ( ++zp > pos ) pos = zp;
break;
}
used--;
}
if ( !flag ) {
flag = 1;
trie->states[ state ].trans.base
= pos + trie->uniquecharcount - charid ;
}
trie->trans[ pos ].next
= SAFE_TRIE_NODENUM(
trie->trans[ stateidx + charid ].next );
trie->trans[ pos ].check = state;
pos++;
}
}
}
trie->lasttrans = pos + 1;
trie->states = (reg_trie_state *)
PerlMemShared_realloc( trie->states, laststate
* sizeof(reg_trie_state) );
DEBUG_TRIE_COMPILE_MORE_r(
Perl_re_indentf( aTHX_ "Alloc: %d Orig: %" IVdf " elements, Final:%" IVdf ". Savings of %%%5.2f\n",
depth+1,
(int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount
+ 1 ),
(IV)next_alloc,
(IV)pos,
( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
);
} /* end table compress */
}
DEBUG_TRIE_COMPILE_MORE_r(
Perl_re_indentf( aTHX_ "Statecount:%" UVxf " Lasttrans:%" UVxf "\n",
depth+1,
(UV)trie->statecount,
(UV)trie->lasttrans)
);
/* resize the trans array to remove unused space */
trie->trans = (reg_trie_trans *)
PerlMemShared_realloc( trie->trans, trie->lasttrans
* sizeof(reg_trie_trans) );
{ /* Modify the program and insert the new TRIE node */
U8 nodetype =(U8)(flags & 0xFF);
char *str=NULL;
#ifdef DEBUGGING
regnode *optimize = NULL;
#ifdef RE_TRACK_PATTERN_OFFSETS
U32 mjd_offset = 0;
U32 mjd_nodelen = 0;
#endif /* RE_TRACK_PATTERN_OFFSETS */
#endif /* DEBUGGING */
/*
This means we convert either the first branch or the first Exact,
depending on whether the thing following (in 'last') is a branch
or not and whther first is the startbranch (ie is it a sub part of
the alternation or is it the whole thing.)
Assuming its a sub part we convert the EXACT otherwise we convert
the whole branch sequence, including the first.
*/
/* Find the node we are going to overwrite */
if ( first != startbranch || OP( last ) == BRANCH ) {
/* branch sub-chain */
NEXT_OFF( first ) = (U16)(last - first);
#ifdef RE_TRACK_PATTERN_OFFSETS
DEBUG_r({
mjd_offset= Node_Offset((convert));
mjd_nodelen= Node_Length((convert));
});
#endif
/* whole branch chain */
}
#ifdef RE_TRACK_PATTERN_OFFSETS
else {
DEBUG_r({
const regnode *nop = NEXTOPER( convert );
mjd_offset= Node_Offset((nop));
mjd_nodelen= Node_Length((nop));
});
}
DEBUG_OPTIMISE_r(
Perl_re_indentf( aTHX_ "MJD offset:%" UVuf " MJD length:%" UVuf "\n",
depth+1,
(UV)mjd_offset, (UV)mjd_nodelen)
);
#endif
/* But first we check to see if there is a common prefix we can
split out as an EXACT and put in front of the TRIE node. */
trie->startstate= 1;
if ( trie->bitmap && !widecharmap && !trie->jump ) {
/* we want to find the first state that has more than
* one transition, if that state is not the first state
* then we have a common prefix which we can remove.
*/
U32 state;
for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
U32 ofs = 0;
I32 first_ofs = -1; /* keeps track of the ofs of the first
transition, -1 means none */
U32 count = 0;
const U32 base = trie->states[ state ].trans.base;
/* does this state terminate an alternation? */
if ( trie->states[state].wordnum )
count = 1;
for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
if ( ( base + ofs >= trie->uniquecharcount ) &&
( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
{
if ( ++count > 1 ) {
/* we have more than one transition */
SV **tmp;
U8 *ch;
/* if this is the first state there is no common prefix
* to extract, so we can exit */
if ( state == 1 ) break;
tmp = av_fetch( revcharmap, ofs, 0);
ch = (U8*)SvPV_nolen_const( *tmp );
/* if we are on count 2 then we need to initialize the
* bitmap, and store the previous char if there was one
* in it*/
if ( count == 2 ) {
/* clear the bitmap */
Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
DEBUG_OPTIMISE_r(
Perl_re_indentf( aTHX_ "New Start State=%" UVuf " Class: [",
depth+1,
(UV)state));
if (first_ofs >= 0) {
SV ** const tmp = av_fetch( revcharmap, first_ofs, 0);
const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
TRIE_BITMAP_SET_FOLDED(trie,*ch, folder);
DEBUG_OPTIMISE_r(
Perl_re_printf( aTHX_ "%s", (char*)ch)
);
}
}
/* store the current firstchar in the bitmap */
TRIE_BITMAP_SET_FOLDED(trie,*ch, folder);
DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "%s", ch));
}
first_ofs = ofs;
}
}
if ( count == 1 ) {
/* This state has only one transition, its transition is part
* of a common prefix - we need to concatenate the char it
* represents to what we have so far. */
SV **tmp = av_fetch( revcharmap, first_ofs, 0);
STRLEN len;
char *ch = SvPV( *tmp, len );
DEBUG_OPTIMISE_r({
SV *sv=sv_newmortal();
Perl_re_indentf( aTHX_ "Prefix State: %" UVuf " Ofs:%" UVuf " Char='%s'\n",
depth+1,
(UV)state, (UV)first_ofs,
pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6,
PL_colors[0], PL_colors[1],
(SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
PERL_PV_ESCAPE_FIRSTCHAR
)
);
});
if ( state==1 ) {
OP( convert ) = nodetype;
str=STRING(convert);
STR_LEN(convert)=0;
}
STR_LEN(convert) += len;
while (len--)
*str++ = *ch++;
} else {
#ifdef DEBUGGING
if (state>1)
DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "]\n"));
#endif
break;
}
}
trie->prefixlen = (state-1);
if (str) {
regnode *n = convert+NODE_SZ_STR(convert);
NEXT_OFF(convert) = NODE_SZ_STR(convert);
trie->startstate = state;
trie->minlen -= (state - 1);
trie->maxlen -= (state - 1);
#ifdef DEBUGGING
/* At least the UNICOS C compiler choked on this
* being argument to DEBUG_r(), so let's just have
* it right here. */
if (
#ifdef PERL_EXT_RE_BUILD
1
#else
DEBUG_r_TEST
#endif
) {
regnode *fix = convert;
U32 word = trie->wordcount;
#ifdef RE_TRACK_PATTERN_OFFSETS
mjd_nodelen++;
#endif
Set_Node_Offset_Length(convert, mjd_offset, state - 1);
while( ++fix < n ) {
Set_Node_Offset_Length(fix, 0, 0);
}
while (word--) {
SV ** const tmp = av_fetch( trie_words, word, 0 );
if (tmp) {
if ( STR_LEN(convert) <= SvCUR(*tmp) )
sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
else
sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
}
}
}
#endif
if (trie->maxlen) {
convert = n;
} else {
NEXT_OFF(convert) = (U16)(tail - convert);
DEBUG_r(optimize= n);
}
}
}
if (!jumper)
jumper = last;
if ( trie->maxlen ) {
NEXT_OFF( convert ) = (U16)(tail - convert);
ARG_SET( convert, data_slot );
/* Store the offset to the first unabsorbed branch in
jump[0], which is otherwise unused by the jump logic.
We use this when dumping a trie and during optimisation. */
if (trie->jump)
trie->jump[0] = (U16)(nextbranch - convert);
/* If the start state is not accepting (meaning there is no empty string/NOTHING)
* and there is a bitmap
* and the first "jump target" node we found leaves enough room
* then convert the TRIE node into a TRIEC node, with the bitmap
* embedded inline in the opcode - this is hypothetically faster.
*/
if ( !trie->states[trie->startstate].wordnum
&& trie->bitmap
&& ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
{
OP( convert ) = TRIEC;
Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
PerlMemShared_free(trie->bitmap);
trie->bitmap= NULL;
} else
OP( convert ) = TRIE;
/* store the type in the flags */
convert->flags = nodetype;
DEBUG_r({
optimize = convert
+ NODE_STEP_REGNODE
+ regarglen[ OP( convert ) ];
});
/* XXX We really should free up the resource in trie now,
as we won't use them - (which resources?) dmq */
}
/* needed for dumping*/
DEBUG_r(if (optimize) {
regnode *opt = convert;
while ( ++opt < optimize) {
Set_Node_Offset_Length(opt, 0, 0);
}
/*
Try to clean up some of the debris left after the
optimisation.
*/
while( optimize < jumper ) {
Track_Code( mjd_nodelen += Node_Length((optimize)); );
OP( optimize ) = OPTIMIZED;
Set_Node_Offset_Length(optimize, 0, 0);
optimize++;
}
Set_Node_Offset_Length(convert, mjd_offset, mjd_nodelen);
});
} /* end node insert */
/* Finish populating the prev field of the wordinfo array. Walk back
* from each accept state until we find another accept state, and if
* so, point the first word's .prev field at the second word. If the
* second already has a .prev field set, stop now. This will be the
* case either if we've already processed that word's accept state,
* or that state had multiple words, and the overspill words were
* already linked up earlier.
*/
{
U16 word;
U32 state;
U16 prev;
for (word=1; word <= trie->wordcount; word++) {
prev = 0;
if (trie->wordinfo[word].prev)
continue;
state = trie->wordinfo[word].accept;
while (state) {
state = prev_states[state];
if (!state)
break;
prev = trie->states[state].wordnum;
if (prev)
break;
}
trie->wordinfo[word].prev = prev;
}
Safefree(prev_states);
}
/* and now dump out the compressed format */
DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
#ifdef DEBUGGING
RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
#else
SvREFCNT_dec_NN(revcharmap);
#endif
return trie->jump
? MADE_JUMP_TRIE
: trie->startstate>1
? MADE_EXACT_TRIE
: MADE_TRIE;
}
STATIC regnode *
S_construct_ahocorasick_from_trie(pTHX_ RExC_state_t *pRExC_state, regnode *source, U32 depth)
{
/* The Trie is constructed and compressed now so we can build a fail array if
* it's needed
This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and
3.32 in the
"Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi,
Ullman 1985/88
ISBN 0-201-10088-6
We find the fail state for each state in the trie, this state is the longest
proper suffix of the current state's 'word' that is also a proper prefix of
another word in our trie. State 1 represents the word '' and is thus the
default fail state. This allows the DFA not to have to restart after its
tried and failed a word at a given point, it simply continues as though it
had been matching the other word in the first place.
Consider
'abcdgu'=~/abcdefg|cdgu/
When we get to 'd' we are still matching the first word, we would encounter
'g' which would fail, which would bring us to the state representing 'd' in
the second word where we would try 'g' and succeed, proceeding to match
'cdgu'.
*/
/* add a fail transition */
const U32 trie_offset = ARG(source);
reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
U32 *q;
const U32 ucharcount = trie->uniquecharcount;
const U32 numstates = trie->statecount;
const U32 ubound = trie->lasttrans + ucharcount;
U32 q_read = 0;
U32 q_write = 0;
U32 charid;
U32 base = trie->states[ 1 ].trans.base;
U32 *fail;
reg_ac_data *aho;
const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("T"));
regnode *stclass;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_CONSTRUCT_AHOCORASICK_FROM_TRIE;
PERL_UNUSED_CONTEXT;
#ifndef DEBUGGING
PERL_UNUSED_ARG(depth);
#endif
if ( OP(source) == TRIE ) {
struct regnode_1 *op = (struct regnode_1 *)
PerlMemShared_calloc(1, sizeof(struct regnode_1));
StructCopy(source, op, struct regnode_1);
stclass = (regnode *)op;
} else {
struct regnode_charclass *op = (struct regnode_charclass *)
PerlMemShared_calloc(1, sizeof(struct regnode_charclass));
StructCopy(source, op, struct regnode_charclass);
stclass = (regnode *)op;
}
OP(stclass)+=2; /* convert the TRIE type to its AHO-CORASICK equivalent */
ARG_SET( stclass, data_slot );
aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
RExC_rxi->data->data[ data_slot ] = (void*)aho;
aho->trie=trie_offset;
aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
Copy( trie->states, aho->states, numstates, reg_trie_state );
Newx( q, numstates, U32);
aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
aho->refcount = 1;
fail = aho->fail;
/* initialize fail[0..1] to be 1 so that we always have
a valid final fail state */
fail[ 0 ] = fail[ 1 ] = 1;
for ( charid = 0; charid < ucharcount ; charid++ ) {
const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
if ( newstate ) {
q[ q_write ] = newstate;
/* set to point at the root */
fail[ q[ q_write++ ] ]=1;
}
}
while ( q_read < q_write) {
const U32 cur = q[ q_read++ % numstates ];
base = trie->states[ cur ].trans.base;
for ( charid = 0 ; charid < ucharcount ; charid++ ) {
const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
if (ch_state) {
U32 fail_state = cur;
U32 fail_base;
do {
fail_state = fail[ fail_state ];
fail_base = aho->states[ fail_state ].trans.base;
} while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
fail[ ch_state ] = fail_state;
if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
{
aho->states[ ch_state ].wordnum = aho->states[ fail_state ].wordnum;
}
q[ q_write++ % numstates] = ch_state;
}
}
}
/* restore fail[0..1] to 0 so that we "fall out" of the AC loop
when we fail in state 1, this allows us to use the
charclass scan to find a valid start char. This is based on the principle
that theres a good chance the string being searched contains lots of stuff
that cant be a start char.
*/
fail[ 0 ] = fail[ 1 ] = 0;
DEBUG_TRIE_COMPILE_r({
Perl_re_indentf( aTHX_ "Stclass Failtable (%" UVuf " states): 0",
depth, (UV)numstates
);
for( q_read=1; q_read<numstates; q_read++ ) {
Perl_re_printf( aTHX_ ", %" UVuf, (UV)fail[q_read]);
}
Perl_re_printf( aTHX_ "\n");
});
Safefree(q);
/*RExC_seen |= REG_TRIEDFA_SEEN;*/
return stclass;
}
/* The below joins as many adjacent EXACTish nodes as possible into a single
* one. The regop may be changed if the node(s) contain certain sequences that
* require special handling. The joining is only done if:
* 1) there is room in the current conglomerated node to entirely contain the
* next one.
* 2) they are compatible node types
*
* The adjacent nodes actually may be separated by NOTHING-kind nodes, and
* these get optimized out
*
* XXX khw thinks this should be enhanced to fill EXACT (at least) nodes as full
* as possible, even if that means splitting an existing node so that its first
* part is moved to the preceeding node. This would maximise the efficiency of
* memEQ during matching.
*
* If a node is to match under /i (folded), the number of characters it matches
* can be different than its character length if it contains a multi-character
* fold. *min_subtract is set to the total delta number of characters of the
* input nodes.
*
* And *unfolded_multi_char is set to indicate whether or not the node contains
* an unfolded multi-char fold. This happens when it won't be known until
* runtime whether the fold is valid or not; namely
* 1) for EXACTF nodes that contain LATIN SMALL LETTER SHARP S, as only if the
* target string being matched against turns out to be UTF-8 is that fold
* valid; or
* 2) for EXACTFL nodes whose folding rules depend on the locale in force at
* runtime.
* (Multi-char folds whose components are all above the Latin1 range are not
* run-time locale dependent, and have already been folded by the time this
* function is called.)
*
* This is as good a place as any to discuss the design of handling these
* multi-character fold sequences. It's been wrong in Perl for a very long
* time. There are three code points in Unicode whose multi-character folds
* were long ago discovered to mess things up. The previous designs for
* dealing with these involved assigning a special node for them. This
* approach doesn't always work, as evidenced by this example:
* "\xDFs" =~ /s\xDF/ui # Used to fail before these patches
* Both sides fold to "sss", but if the pattern is parsed to create a node that
* would match just the \xDF, it won't be able to handle the case where a
* successful match would have to cross the node's boundary. The new approach
* that hopefully generally solves the problem generates an EXACTFUP node
* that is "sss" in this case.
*
* It turns out that there are problems with all multi-character folds, and not
* just these three. Now the code is general, for all such cases. The
* approach taken is:
* 1) This routine examines each EXACTFish node that could contain multi-
* character folded sequences. Since a single character can fold into
* such a sequence, the minimum match length for this node is less than
* the number of characters in the node. This routine returns in
* *min_subtract how many characters to subtract from the the actual
* length of the string to get a real minimum match length; it is 0 if
* there are no multi-char foldeds. This delta is used by the caller to
* adjust the min length of the match, and the delta between min and max,
* so that the optimizer doesn't reject these possibilities based on size
* constraints.
*
* 2) For the sequence involving the LATIN SMALL LETTER SHARP S (U+00DF)
* under /u, we fold it to 'ss' in regatom(), and in this routine, after
* joining, we scan for occurrences of the sequence 'ss' in non-UTF-8
* EXACTFU nodes. The node type of such nodes is then changed to
* EXACTFUP, indicating it is problematic, and needs careful handling.
* (The procedures in step 1) above are sufficient to handle this case in
* UTF-8 encoded nodes.) The reason this is problematic is that this is
* the only case where there is a possible fold length change in non-UTF-8
* patterns. By reserving a special node type for problematic cases, the
* far more common regular EXACTFU nodes can be processed faster.
* regexec.c takes advantage of this.
*
* EXACTFUP has been created as a grab-bag for (hopefully uncommon)
* problematic cases. These all only occur when the pattern is not
* UTF-8. In addition to the 'ss' sequence where there is a possible fold
* length change, it handles the situation where the string cannot be
* entirely folded. The strings in an EXACTFish node are folded as much
* as possible during compilation in regcomp.c. This saves effort in
* regex matching. By using an EXACTFUP node when it is not possible to
* fully fold at compile time, regexec.c can know that everything in an
* EXACTFU node is folded, so folding can be skipped at runtime. The only
* case where folding in EXACTFU nodes can't be done at compile time is
* the presumably uncommon MICRO SIGN, when the pattern isn't UTF-8. This
* is because its fold requires UTF-8 to represent. Thus EXACTFUP nodes
* handle two very different cases. Alternatively, there could have been
* a node type where there are length changes, one for unfolded, and one
* for both. If yet another special case needed to be created, the number
* of required node types would have to go to 7. khw figures that even
* though there are plenty of node types to spare, that the maintenance
* cost wasn't worth the small speedup of doing it that way, especially
* since he thinks the MICRO SIGN is rarely encountered in practice.
*
* There are other cases where folding isn't done at compile time, but
* none of them are under /u, and hence not for EXACTFU nodes. The folds
* in EXACTFL nodes aren't known until runtime, and vary as the locale
* changes. Some folds in EXACTF depend on if the runtime target string
* is UTF-8 or not. (regatom() will create an EXACTFU node even under /di
* when no fold in it depends on the UTF-8ness of the target string.)
*
* 3) A problem remains for unfolded multi-char folds. (These occur when the
* validity of the fold won't be known until runtime, and so must remain
* unfolded for now. This happens for the sharp s in EXACTF and EXACTFAA
* nodes when the pattern isn't in UTF-8. (Note, BTW, that there cannot
* be an EXACTF node with a UTF-8 pattern.) They also occur for various
* folds in EXACTFL nodes, regardless of the UTF-ness of the pattern.)
* The reason this is a problem is that the optimizer part of regexec.c
* (probably unwittingly, in Perl_regexec_flags()) makes an assumption
* that a character in the pattern corresponds to at most a single
* character in the target string. (And I do mean character, and not byte
* here, unlike other parts of the documentation that have never been
* updated to account for multibyte Unicode.) Sharp s in EXACTF and
* EXACTFL nodes can match the two character string 'ss'; in EXACTFAA
* nodes it can match "\x{17F}\x{17F}". These, along with other ones in
* EXACTFL nodes, violate the assumption, and they are the only instances
* where it is violated. I'm reluctant to try to change the assumption,
* as the code involved is impenetrable to me (khw), so instead the code
* here punts. This routine examines EXACTFL nodes, and (when the pattern
* isn't UTF-8) EXACTF and EXACTFAA for such unfolded folds, and returns a
* boolean indicating whether or not the node contains such a fold. When
* it is true, the caller sets a flag that later causes the optimizer in
* this file to not set values for the floating and fixed string lengths,
* and thus avoids the optimizer code in regexec.c that makes the invalid
* assumption. Thus, there is no optimization based on string lengths for
* EXACTFL nodes that contain these few folds, nor for non-UTF8-pattern
* EXACTF and EXACTFAA nodes that contain the sharp s. (The reason the
* assumption is wrong only in these cases is that all other non-UTF-8
* folds are 1-1; and, for UTF-8 patterns, we pre-fold all other folds to
* their expanded versions. (Again, we can't prefold sharp s to 'ss' in
* EXACTF nodes because we don't know at compile time if it actually
* matches 'ss' or not. For EXACTF nodes it will match iff the target
* string is in UTF-8. This is in contrast to EXACTFU nodes, where it
* always matches; and EXACTFAA where it never does. In an EXACTFAA node
* in a UTF-8 pattern, sharp s is folded to "\x{17F}\x{17F}, avoiding the
* problem; but in a non-UTF8 pattern, folding it to that above-Latin1
* string would require the pattern to be forced into UTF-8, the overhead
* of which we want to avoid. Similarly the unfolded multi-char folds in
* EXACTFL nodes will match iff the locale at the time of match is a UTF-8
* locale.)
*
* Similarly, the code that generates tries doesn't currently handle
* not-already-folded multi-char folds, and it looks like a pain to change
* that. Therefore, trie generation of EXACTFAA nodes with the sharp s
* doesn't work. Instead, such an EXACTFAA is turned into a new regnode,
* EXACTFAA_NO_TRIE, which the trie code knows not to handle. Most people
* using /iaa matching will be doing so almost entirely with ASCII
* strings, so this should rarely be encountered in practice */
#define JOIN_EXACT(scan,min_subtract,unfolded_multi_char, flags) \
if (PL_regkind[OP(scan)] == EXACT) \
join_exact(pRExC_state,(scan),(min_subtract),unfolded_multi_char, (flags), NULL, depth+1)
STATIC U32
S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan,
UV *min_subtract, bool *unfolded_multi_char,
U32 flags, regnode *val, U32 depth)
{
/* Merge several consecutive EXACTish nodes into one. */
regnode *n = regnext(scan);
U32 stringok = 1;
regnode *next = scan + NODE_SZ_STR(scan);
U32 merged = 0;
U32 stopnow = 0;
#ifdef DEBUGGING
regnode *stop = scan;
GET_RE_DEBUG_FLAGS_DECL;
#else
PERL_UNUSED_ARG(depth);
#endif
PERL_ARGS_ASSERT_JOIN_EXACT;
#ifndef EXPERIMENTAL_INPLACESCAN
PERL_UNUSED_ARG(flags);
PERL_UNUSED_ARG(val);
#endif
DEBUG_PEEP("join", scan, depth, 0);
assert(PL_regkind[OP(scan)] == EXACT);
/* Look through the subsequent nodes in the chain. Skip NOTHING, merge
* EXACT ones that are mergeable to the current one. */
while ( n
&& ( PL_regkind[OP(n)] == NOTHING
|| (stringok && PL_regkind[OP(n)] == EXACT))
&& NEXT_OFF(n)
&& NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX)
{
if (OP(n) == TAIL || n > next)
stringok = 0;
if (PL_regkind[OP(n)] == NOTHING) {
DEBUG_PEEP("skip:", n, depth, 0);
NEXT_OFF(scan) += NEXT_OFF(n);
next = n + NODE_STEP_REGNODE;
#ifdef DEBUGGING
if (stringok)
stop = n;
#endif
n = regnext(n);
}
else if (stringok) {
const unsigned int oldl = STR_LEN(scan);
regnode * const nnext = regnext(n);
/* XXX I (khw) kind of doubt that this works on platforms (should
* Perl ever run on one) where U8_MAX is above 255 because of lots
* of other assumptions */
/* Don't join if the sum can't fit into a single node */
if (oldl + STR_LEN(n) > U8_MAX)
break;
/* Joining something that requires UTF-8 with something that
* doesn't, means the result requires UTF-8. */
if (OP(scan) == EXACT && (OP(n) == EXACT_ONLY8)) {
OP(scan) = EXACT_ONLY8;
}
else if (OP(scan) == EXACT_ONLY8 && (OP(n) == EXACT)) {
; /* join is compatible, no need to change OP */
}
else if ((OP(scan) == EXACTFU) && (OP(n) == EXACTFU_ONLY8)) {
OP(scan) = EXACTFU_ONLY8;
}
else if ((OP(scan) == EXACTFU_ONLY8) && (OP(n) == EXACTFU)) {
; /* join is compatible, no need to change OP */
}
else if (OP(scan) == EXACTFU && OP(n) == EXACTFU) {
; /* join is compatible, no need to change OP */
}
else if (OP(scan) == EXACTFU && OP(n) == EXACTFU_S_EDGE) {
/* Under /di, temporary EXACTFU_S_EDGE nodes are generated,
* which can join with EXACTFU ones. We check for this case
* here. These need to be resolved to either EXACTFU or
* EXACTF at joining time. They have nothing in them that
* would forbid them from being the more desirable EXACTFU
* nodes except that they begin and/or end with a single [Ss].
* The reason this is problematic is because they could be
* joined in this loop with an adjacent node that ends and/or
* begins with [Ss] which would then form the sequence 'ss',
* which matches differently under /di than /ui, in which case
* EXACTFU can't be used. If the 'ss' sequence doesn't get
* formed, the nodes get absorbed into any adjacent EXACTFU
* node. And if the only adjacent node is EXACTF, they get
* absorbed into that, under the theory that a longer node is
* better than two shorter ones, even if one is EXACTFU. Note
* that EXACTFU_ONLY8 is generated only for UTF-8 patterns,
* and the EXACTFU_S_EDGE ones only for non-UTF-8. */
if (STRING(n)[STR_LEN(n)-1] == 's') {
/* Here the joined node would end with 's'. If the node
* following the combination is an EXACTF one, it's better to
* join this trailing edge 's' node with that one, leaving the
* current one in 'scan' be the more desirable EXACTFU */
if (OP(nnext) == EXACTF) {
break;
}
OP(scan) = EXACTFU_S_EDGE;
} /* Otherwise, the beginning 's' of the 2nd node just
becomes an interior 's' in 'scan' */
}
else if (OP(scan) == EXACTF && OP(n) == EXACTF) {
; /* join is compatible, no need to change OP */
}
else if (OP(scan) == EXACTF && OP(n) == EXACTFU_S_EDGE) {
/* EXACTF nodes are compatible for joining with EXACTFU_S_EDGE
* nodes. But the latter nodes can be also joined with EXACTFU
* ones, and that is a better outcome, so if the node following
* 'n' is EXACTFU, quit now so that those two can be joined
* later */
if (OP(nnext) == EXACTFU) {
break;
}
/* The join is compatible, and the combined node will be
* EXACTF. (These don't care if they begin or end with 's' */
}
else if (OP(scan) == EXACTFU_S_EDGE && OP(n) == EXACTFU_S_EDGE) {
if ( STRING(scan)[STR_LEN(scan)-1] == 's'
&& STRING(n)[0] == 's')
{
/* When combined, we have the sequence 'ss', which means we
* have to remain /di */
OP(scan) = EXACTF;
}
}
else if (OP(scan) == EXACTFU_S_EDGE && OP(n) == EXACTFU) {
if (STRING(n)[0] == 's') {
; /* Here the join is compatible and the combined node
starts with 's', no need to change OP */
}
else { /* Now the trailing 's' is in the interior */
OP(scan) = EXACTFU;
}
}
else if (OP(scan) == EXACTFU_S_EDGE && OP(n) == EXACTF) {
/* The join is compatible, and the combined node will be
* EXACTF. (These don't care if they begin or end with 's' */
OP(scan) = EXACTF;
}
else if (OP(scan) != OP(n)) {
/* The only other compatible joinings are the same node type */
break;
}
DEBUG_PEEP("merg", n, depth, 0);
merged++;
NEXT_OFF(scan) += NEXT_OFF(n);
STR_LEN(scan) += STR_LEN(n);
next = n + NODE_SZ_STR(n);
/* Now we can overwrite *n : */
Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
#ifdef DEBUGGING
stop = next - 1;
#endif
n = nnext;
if (stopnow) break;
}
#ifdef EXPERIMENTAL_INPLACESCAN
if (flags && !NEXT_OFF(n)) {
DEBUG_PEEP("atch", val, depth, 0);
if (reg_off_by_arg[OP(n)]) {
ARG_SET(n, val - n);
}
else {
NEXT_OFF(n) = val - n;
}
stopnow = 1;
}
#endif
}
/* This temporary node can now be turned into EXACTFU, and must, as
* regexec.c doesn't handle it */
if (OP(scan) == EXACTFU_S_EDGE) {
OP(scan) = EXACTFU;
}
*min_subtract = 0;
*unfolded_multi_char = FALSE;
/* Here, all the adjacent mergeable EXACTish nodes have been merged. We
* can now analyze for sequences of problematic code points. (Prior to
* this final joining, sequences could have been split over boundaries, and
* hence missed). The sequences only happen in folding, hence for any
* non-EXACT EXACTish node */
if (OP(scan) != EXACT && OP(scan) != EXACT_ONLY8 && OP(scan) != EXACTL) {
U8* s0 = (U8*) STRING(scan);
U8* s = s0;
U8* s_end = s0 + STR_LEN(scan);
int total_count_delta = 0; /* Total delta number of characters that
multi-char folds expand to */
/* One pass is made over the node's string looking for all the
* possibilities. To avoid some tests in the loop, there are two main
* cases, for UTF-8 patterns (which can't have EXACTF nodes) and
* non-UTF-8 */
if (UTF) {
U8* folded = NULL;
if (OP(scan) == EXACTFL) {
U8 *d;
/* An EXACTFL node would already have been changed to another
* node type unless there is at least one character in it that
* is problematic; likely a character whose fold definition
* won't be known until runtime, and so has yet to be folded.
* For all but the UTF-8 locale, folds are 1-1 in length, but
* to handle the UTF-8 case, we need to create a temporary
* folded copy using UTF-8 locale rules in order to analyze it.
* This is because our macros that look to see if a sequence is
* a multi-char fold assume everything is folded (otherwise the
* tests in those macros would be too complicated and slow).
* Note that here, the non-problematic folds will have already
* been done, so we can just copy such characters. We actually
* don't completely fold the EXACTFL string. We skip the
* unfolded multi-char folds, as that would just create work
* below to figure out the size they already are */
Newx(folded, UTF8_MAX_FOLD_CHAR_EXPAND * STR_LEN(scan) + 1, U8);
d = folded;
while (s < s_end) {
STRLEN s_len = UTF8SKIP(s);
if (! is_PROBLEMATIC_LOCALE_FOLD_utf8(s)) {
Copy(s, d, s_len, U8);
d += s_len;
}
else if (is_FOLDS_TO_MULTI_utf8(s)) {
*unfolded_multi_char = TRUE;
Copy(s, d, s_len, U8);
d += s_len;
}
else if (isASCII(*s)) {
*(d++) = toFOLD(*s);
}
else {
STRLEN len;
_toFOLD_utf8_flags(s, s_end, d, &len, FOLD_FLAGS_FULL);
d += len;
}
s += s_len;
}
/* Point the remainder of the routine to look at our temporary
* folded copy */
s = folded;
s_end = d;
} /* End of creating folded copy of EXACTFL string */
/* Examine the string for a multi-character fold sequence. UTF-8
* patterns have all characters pre-folded by the time this code is
* executed */
while (s < s_end - 1) /* Can stop 1 before the end, as minimum
length sequence we are looking for is 2 */
{
int count = 0; /* How many characters in a multi-char fold */
int len = is_MULTI_CHAR_FOLD_utf8_safe(s, s_end);
if (! len) { /* Not a multi-char fold: get next char */
s += UTF8SKIP(s);
continue;
}
{ /* Here is a generic multi-char fold. */
U8* multi_end = s + len;
/* Count how many characters are in it. In the case of
* /aa, no folds which contain ASCII code points are
* allowed, so check for those, and skip if found. */
if (OP(scan) != EXACTFAA && OP(scan) != EXACTFAA_NO_TRIE) {
count = utf8_length(s, multi_end);
s = multi_end;
}
else {
while (s < multi_end) {
if (isASCII(*s)) {
s++;
goto next_iteration;
}
else {
s += UTF8SKIP(s);
}
count++;
}
}
}
/* The delta is how long the sequence is minus 1 (1 is how long
* the character that folds to the sequence is) */
total_count_delta += count - 1;
next_iteration: ;
}
/* We created a temporary folded copy of the string in EXACTFL
* nodes. Therefore we need to be sure it doesn't go below zero,
* as the real string could be shorter */
if (OP(scan) == EXACTFL) {
int total_chars = utf8_length((U8*) STRING(scan),
(U8*) STRING(scan) + STR_LEN(scan));
if (total_count_delta > total_chars) {
total_count_delta = total_chars;
}
}
*min_subtract += total_count_delta;
Safefree(folded);
}
else if (OP(scan) == EXACTFAA) {
/* Non-UTF-8 pattern, EXACTFAA node. There can't be a multi-char
* fold to the ASCII range (and there are no existing ones in the
* upper latin1 range). But, as outlined in the comments preceding
* this function, we need to flag any occurrences of the sharp s.
* This character forbids trie formation (because of added
* complexity) */
#if UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */ \
|| (UNICODE_MAJOR_VERSION == 3 && ( UNICODE_DOT_VERSION > 0) \
|| UNICODE_DOT_DOT_VERSION > 0)
while (s < s_end) {
if (*s == LATIN_SMALL_LETTER_SHARP_S) {
OP(scan) = EXACTFAA_NO_TRIE;
*unfolded_multi_char = TRUE;
break;
}
s++;
}
}
else {
/* Non-UTF-8 pattern, not EXACTFAA node. Look for the multi-char
* folds that are all Latin1. As explained in the comments
* preceding this function, we look also for the sharp s in EXACTF
* and EXACTFL nodes; it can be in the final position. Otherwise
* we can stop looking 1 byte earlier because have to find at least
* two characters for a multi-fold */
const U8* upper = (OP(scan) == EXACTF || OP(scan) == EXACTFL)
? s_end
: s_end -1;
while (s < upper) {
int len = is_MULTI_CHAR_FOLD_latin1_safe(s, s_end);
if (! len) { /* Not a multi-char fold. */
if (*s == LATIN_SMALL_LETTER_SHARP_S
&& (OP(scan) == EXACTF || OP(scan) == EXACTFL))
{
*unfolded_multi_char = TRUE;
}
s++;
continue;
}
if (len == 2
&& isALPHA_FOLD_EQ(*s, 's')
&& isALPHA_FOLD_EQ(*(s+1), 's'))
{
/* EXACTF nodes need to know that the minimum length
* changed so that a sharp s in the string can match this
* ss in the pattern, but they remain EXACTF nodes, as they
* won't match this unless the target string is is UTF-8,
* which we don't know until runtime. EXACTFL nodes can't
* transform into EXACTFU nodes */
if (OP(scan) != EXACTF && OP(scan) != EXACTFL) {
OP(scan) = EXACTFUP;
}
}
*min_subtract += len - 1;
s += len;
}
#endif
}
if ( STR_LEN(scan) == 1
&& isALPHA_A(* STRING(scan))
&& ( OP(scan) == EXACTFAA
|| ( OP(scan) == EXACTFU
&& ! HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(* STRING(scan)))))
{
U8 mask = ~ ('A' ^ 'a'); /* These differ in just one bit */
/* Replace a length 1 ASCII fold pair node with an ANYOFM node,
* with the mask set to the complement of the bit that differs
* between upper and lower case, and the lowest code point of the
* pair (which the '&' forces) */
OP(scan) = ANYOFM;
ARG_SET(scan, *STRING(scan) & mask);
FLAGS(scan) = mask;
}
}
#ifdef DEBUGGING
/* Allow dumping but overwriting the collection of skipped
* ops and/or strings with fake optimized ops */
n = scan + NODE_SZ_STR(scan);
while (n <= stop) {
OP(n) = OPTIMIZED;
FLAGS(n) = 0;
NEXT_OFF(n) = 0;
n++;
}
#endif
DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl", scan, depth, 0);});
return stopnow;
}
/* REx optimizer. Converts nodes into quicker variants "in place".
Finds fixed substrings. */
/* Stops at toplevel WHILEM as well as at "last". At end *scanp is set
to the position after last scanned or to NULL. */
#define INIT_AND_WITHP \
assert(!and_withp); \
Newx(and_withp, 1, regnode_ssc); \
SAVEFREEPV(and_withp)
static void
S_unwind_scan_frames(pTHX_ const void *p)
{
scan_frame *f= (scan_frame *)p;
do {
scan_frame *n= f->next_frame;
Safefree(f);
f= n;
} while (f);
}
/* the return from this sub is the minimum length that could possibly match */
STATIC SSize_t
S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
SSize_t *minlenp, SSize_t *deltap,
regnode *last,
scan_data_t *data,
I32 stopparen,
U32 recursed_depth,
regnode_ssc *and_withp,
U32 flags, U32 depth)
/* scanp: Start here (read-write). */
/* deltap: Write maxlen-minlen here. */
/* last: Stop before this one. */
/* data: string data about the pattern */
/* stopparen: treat close N as END */
/* recursed: which subroutines have we recursed into */
/* and_withp: Valid if flags & SCF_DO_STCLASS_OR */
{
dVAR;
/* There must be at least this number of characters to match */
SSize_t min = 0;
I32 pars = 0, code;
regnode *scan = *scanp, *next;
SSize_t delta = 0;
int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
int is_inf_internal = 0; /* The studied chunk is infinite */
I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
scan_data_t data_fake;
SV *re_trie_maxbuff = NULL;
regnode *first_non_open = scan;
SSize_t stopmin = SSize_t_MAX;
scan_frame *frame = NULL;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_STUDY_CHUNK;
RExC_study_started= 1;
Zero(&data_fake, 1, scan_data_t);
if ( depth == 0 ) {
while (first_non_open && OP(first_non_open) == OPEN)
first_non_open=regnext(first_non_open);
}
fake_study_recurse:
DEBUG_r(
RExC_study_chunk_recursed_count++;
);
DEBUG_OPTIMISE_MORE_r(
{
Perl_re_indentf( aTHX_ "study_chunk stopparen=%ld recursed_count=%lu depth=%lu recursed_depth=%lu scan=%p last=%p",
depth, (long)stopparen,
(unsigned long)RExC_study_chunk_recursed_count,
(unsigned long)depth, (unsigned long)recursed_depth,
scan,
last);
if (recursed_depth) {
U32 i;
U32 j;
for ( j = 0 ; j < recursed_depth ; j++ ) {
for ( i = 0 ; i < (U32)RExC_total_parens ; i++ ) {
if (
PAREN_TEST(RExC_study_chunk_recursed +
( j * RExC_study_chunk_recursed_bytes), i )
&& (
!j ||
!PAREN_TEST(RExC_study_chunk_recursed +
(( j - 1 ) * RExC_study_chunk_recursed_bytes), i)
)
) {
Perl_re_printf( aTHX_ " %d",(int)i);
break;
}
}
if ( j + 1 < recursed_depth ) {
Perl_re_printf( aTHX_ ",");
}
}
}
Perl_re_printf( aTHX_ "\n");
}
);
while ( scan && OP(scan) != END && scan < last ){
UV min_subtract = 0; /* How mmany chars to subtract from the minimum
node length to get a real minimum (because
the folded version may be shorter) */
bool unfolded_multi_char = FALSE;
/* Peephole optimizer: */
DEBUG_STUDYDATA("Peep", data, depth, is_inf);
DEBUG_PEEP("Peep", scan, depth, flags);
/* The reason we do this here is that we need to deal with things like
* /(?:f)(?:o)(?:o)/ which cant be dealt with by the normal EXACT
* parsing code, as each (?:..) is handled by a different invocation of
* reg() -- Yves
*/
JOIN_EXACT(scan,&min_subtract, &unfolded_multi_char, 0);
/* Follow the next-chain of the current node and optimize
away all the NOTHINGs from it. */
if (OP(scan) != CURLYX) {
const int max = (reg_off_by_arg[OP(scan)]
? I32_MAX
/* I32 may be smaller than U16 on CRAYs! */
: (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
int noff;
regnode *n = scan;
/* Skip NOTHING and LONGJMP. */
while ((n = regnext(n))
&& ((PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
|| ((OP(n) == LONGJMP) && (noff = ARG(n))))
&& off + noff < max)
off += noff;
if (reg_off_by_arg[OP(scan)])
ARG(scan) = off;
else
NEXT_OFF(scan) = off;
}
/* The principal pseudo-switch. Cannot be a switch, since we
look into several different things. */
if ( OP(scan) == DEFINEP ) {
SSize_t minlen = 0;
SSize_t deltanext = 0;
SSize_t fake_last_close = 0;
I32 f = SCF_IN_DEFINE;
StructCopy(&zero_scan_data, &data_fake, scan_data_t);
scan = regnext(scan);
assert( OP(scan) == IFTHEN );
DEBUG_PEEP("expect IFTHEN", scan, depth, flags);
data_fake.last_closep= &fake_last_close;
minlen = *minlenp;
next = regnext(scan);
scan = NEXTOPER(NEXTOPER(scan));
DEBUG_PEEP("scan", scan, depth, flags);
DEBUG_PEEP("next", next, depth, flags);
/* we suppose the run is continuous, last=next...
* NOTE we dont use the return here! */
/* DEFINEP study_chunk() recursion */
(void)study_chunk(pRExC_state, &scan, &minlen,
&deltanext, next, &data_fake, stopparen,
recursed_depth, NULL, f, depth+1);
scan = next;
} else
if (
OP(scan) == BRANCH ||
OP(scan) == BRANCHJ ||
OP(scan) == IFTHEN
) {
next = regnext(scan);
code = OP(scan);
/* The op(next)==code check below is to see if we
* have "BRANCH-BRANCH", "BRANCHJ-BRANCHJ", "IFTHEN-IFTHEN"
* IFTHEN is special as it might not appear in pairs.
* Not sure whether BRANCH-BRANCHJ is possible, regardless
* we dont handle it cleanly. */
if (OP(next) == code || code == IFTHEN) {
/* NOTE - There is similar code to this block below for
* handling TRIE nodes on a re-study. If you change stuff here
* check there too. */
SSize_t max1 = 0, min1 = SSize_t_MAX, num = 0;
regnode_ssc accum;
regnode * const startbranch=scan;
if (flags & SCF_DO_SUBSTR) {
/* Cannot merge strings after this. */
scan_commit(pRExC_state, data, minlenp, is_inf);
}
if (flags & SCF_DO_STCLASS)
ssc_init_zero(pRExC_state, &accum);
while (OP(scan) == code) {
SSize_t deltanext, minnext, fake;
I32 f = 0;
regnode_ssc this_class;
DEBUG_PEEP("Branch", scan, depth, flags);
num++;
StructCopy(&zero_scan_data, &data_fake, scan_data_t);
if (data) {
data_fake.whilem_c = data->whilem_c;
data_fake.last_closep = data->last_closep;
}
else
data_fake.last_closep = &fake;
data_fake.pos_delta = delta;
next = regnext(scan);
scan = NEXTOPER(scan); /* everything */
if (code != BRANCH) /* everything but BRANCH */
scan = NEXTOPER(scan);
if (flags & SCF_DO_STCLASS) {
ssc_init(pRExC_state, &this_class);
data_fake.start_class = &this_class;
f = SCF_DO_STCLASS_AND;
}
if (flags & SCF_WHILEM_VISITED_POS)
f |= SCF_WHILEM_VISITED_POS;
/* we suppose the run is continuous, last=next...*/
/* recurse study_chunk() for each BRANCH in an alternation */
minnext = study_chunk(pRExC_state, &scan, minlenp,
&deltanext, next, &data_fake, stopparen,
recursed_depth, NULL, f, depth+1);
if (min1 > minnext)
min1 = minnext;
if (deltanext == SSize_t_MAX) {
is_inf = is_inf_internal = 1;
max1 = SSize_t_MAX;
} else if (max1 < minnext + deltanext)
max1 = minnext + deltanext;
scan = next;
if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
pars++;
if (data_fake.flags & SCF_SEEN_ACCEPT) {
if ( stopmin > minnext)
stopmin = min + min1;
flags &= ~SCF_DO_SUBSTR;
if (data)
data->flags |= SCF_SEEN_ACCEPT;
}
if (data) {
if (data_fake.flags & SF_HAS_EVAL)
data->flags |= SF_HAS_EVAL;
data->whilem_c = data_fake.whilem_c;
}
if (flags & SCF_DO_STCLASS)
ssc_or(pRExC_state, &accum, (regnode_charclass*)&this_class);
}
if (code == IFTHEN && num < 2) /* Empty ELSE branch */
min1 = 0;
if (flags & SCF_DO_SUBSTR) {
data->pos_min += min1;
if (data->pos_delta >= SSize_t_MAX - (max1 - min1))
data->pos_delta = SSize_t_MAX;
else
data->pos_delta += max1 - min1;
if (max1 != min1 || is_inf)
data->cur_is_floating = 1;
}
min += min1;
if (delta == SSize_t_MAX
|| SSize_t_MAX - delta - (max1 - min1) < 0)
delta = SSize_t_MAX;
else
delta += max1 - min1;
if (flags & SCF_DO_STCLASS_OR) {
ssc_or(pRExC_state, data->start_class, (regnode_charclass*) &accum);
if (min1) {
ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
flags &= ~SCF_DO_STCLASS;
}
}
else if (flags & SCF_DO_STCLASS_AND) {
if (min1) {
ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum);
flags &= ~SCF_DO_STCLASS;
}
else {
/* Switch to OR mode: cache the old value of
* data->start_class */
INIT_AND_WITHP;
StructCopy(data->start_class, and_withp, regnode_ssc);
flags &= ~SCF_DO_STCLASS_AND;
StructCopy(&accum, data->start_class, regnode_ssc);
flags |= SCF_DO_STCLASS_OR;
}
}
if (PERL_ENABLE_TRIE_OPTIMISATION &&
OP( startbranch ) == BRANCH )
{
/* demq.
Assuming this was/is a branch we are dealing with: 'scan'
now points at the item that follows the branch sequence,
whatever it is. We now start at the beginning of the
sequence and look for subsequences of
BRANCH->EXACT=>x1
BRANCH->EXACT=>x2
tail
which would be constructed from a pattern like
/A|LIST|OF|WORDS/
If we can find such a subsequence we need to turn the first
element into a trie and then add the subsequent branch exact
strings to the trie.
We have two cases
1. patterns where the whole set of branches can be
converted.
2. patterns where only a subset can be converted.
In case 1 we can replace the whole set with a single regop
for the trie. In case 2 we need to keep the start and end
branches so
'BRANCH EXACT; BRANCH EXACT; BRANCH X'
becomes BRANCH TRIE; BRANCH X;
There is an additional case, that being where there is a
common prefix, which gets split out into an EXACT like node
preceding the TRIE node.
If x(1..n)==tail then we can do a simple trie, if not we make
a "jump" trie, such that when we match the appropriate word
we "jump" to the appropriate tail node. Essentially we turn
a nested if into a case structure of sorts.
*/
int made=0;
if (!re_trie_maxbuff) {
re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
if (!SvIOK(re_trie_maxbuff))
sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
}
if ( SvIV(re_trie_maxbuff)>=0 ) {
regnode *cur;
regnode *first = (regnode *)NULL;
regnode *last = (regnode *)NULL;
regnode *tail = scan;
U8 trietype = 0;
U32 count=0;
/* var tail is used because there may be a TAIL
regop in the way. Ie, the exacts will point to the
thing following the TAIL, but the last branch will
point at the TAIL. So we advance tail. If we
have nested (?:) we may have to move through several
tails.
*/
while ( OP( tail ) == TAIL ) {
/* this is the TAIL generated by (?:) */
tail = regnext( tail );
}
DEBUG_TRIE_COMPILE_r({
regprop(RExC_rx, RExC_mysv, tail, NULL, pRExC_state);
Perl_re_indentf( aTHX_ "%s %" UVuf ":%s\n",
depth+1,
"Looking for TRIE'able sequences. Tail node is ",
(UV) REGNODE_OFFSET(tail),
SvPV_nolen_const( RExC_mysv )
);
});
/*
Step through the branches
cur represents each branch,
noper is the first thing to be matched as part
of that branch
noper_next is the regnext() of that node.
We normally handle a case like this
/FOO[xyz]|BAR[pqr]/ via a "jump trie" but we also
support building with NOJUMPTRIE, which restricts
the trie logic to structures like /FOO|BAR/.
If noper is a trieable nodetype then the branch is
a possible optimization target. If we are building
under NOJUMPTRIE then we require that noper_next is
the same as scan (our current position in the regex
program).
Once we have two or more consecutive such branches
we can create a trie of the EXACT's contents and
stitch it in place into the program.
If the sequence represents all of the branches in
the alternation we replace the entire thing with a
single TRIE node.
Otherwise when it is a subsequence we need to
stitch it in place and replace only the relevant
branches. This means the first branch has to remain
as it is used by the alternation logic, and its
next pointer, and needs to be repointed at the item
on the branch chain following the last branch we
have optimized away.
This could be either a BRANCH, in which case the
subsequence is internal, or it could be the item
following the branch sequence in which case the
subsequence is at the end (which does not
necessarily mean the first node is the start of the
alternation).
TRIE_TYPE(X) is a define which maps the optype to a
trietype.
optype | trietype
----------------+-----------
NOTHING | NOTHING
EXACT | EXACT
EXACT_ONLY8 | EXACT
EXACTFU | EXACTFU
EXACTFU_ONLY8 | EXACTFU
EXACTFUP | EXACTFU
EXACTFAA | EXACTFAA
EXACTL | EXACTL
EXACTFLU8 | EXACTFLU8
*/
#define TRIE_TYPE(X) ( ( NOTHING == (X) ) \
? NOTHING \
: ( EXACT == (X) || EXACT_ONLY8 == (X) ) \
? EXACT \
: ( EXACTFU == (X) \
|| EXACTFU_ONLY8 == (X) \
|| EXACTFUP == (X) ) \
? EXACTFU \
: ( EXACTFAA == (X) ) \
? EXACTFAA \
: ( EXACTL == (X) ) \
? EXACTL \
: ( EXACTFLU8 == (X) ) \
? EXACTFLU8 \
: 0 )
/* dont use tail as the end marker for this traverse */
for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {
regnode * const noper = NEXTOPER( cur );
U8 noper_type = OP( noper );
U8 noper_trietype = TRIE_TYPE( noper_type );
#if defined(DEBUGGING) || defined(NOJUMPTRIE)
regnode * const noper_next = regnext( noper );
U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0;
U8 noper_next_trietype = (noper_next && noper_next < tail) ? TRIE_TYPE( noper_next_type ) :0;
#endif
DEBUG_TRIE_COMPILE_r({
regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
Perl_re_indentf( aTHX_ "- %d:%s (%d)",
depth+1,
REG_NODE_NUM(cur), SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur) );
regprop(RExC_rx, RExC_mysv, noper, NULL, pRExC_state);
Perl_re_printf( aTHX_ " -> %d:%s",
REG_NODE_NUM(noper), SvPV_nolen_const(RExC_mysv));
if ( noper_next ) {
regprop(RExC_rx, RExC_mysv, noper_next, NULL, pRExC_state);
Perl_re_printf( aTHX_ "\t=> %d:%s\t",
REG_NODE_NUM(noper_next), SvPV_nolen_const(RExC_mysv));
}
Perl_re_printf( aTHX_ "(First==%d,Last==%d,Cur==%d,tt==%s,ntt==%s,nntt==%s)\n",
REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur),
PL_reg_name[trietype], PL_reg_name[noper_trietype], PL_reg_name[noper_next_trietype]
);
});
/* Is noper a trieable nodetype that can be merged
* with the current trie (if there is one)? */
if ( noper_trietype
&&
(
( noper_trietype == NOTHING )
|| ( trietype == NOTHING )
|| ( trietype == noper_trietype )
)
#ifdef NOJUMPTRIE
&& noper_next >= tail
#endif
&& count < U16_MAX)
{
/* Handle mergable triable node Either we are
* the first node in a new trieable sequence,
* in which case we do some bookkeeping,
* otherwise we update the end pointer. */
if ( !first ) {
first = cur;
if ( noper_trietype == NOTHING ) {
#if !defined(DEBUGGING) && !defined(NOJUMPTRIE)
regnode * const noper_next = regnext( noper );
U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0;
U8 noper_next_trietype = noper_next_type ? TRIE_TYPE( noper_next_type ) :0;
#endif
if ( noper_next_trietype ) {
trietype = noper_next_trietype;
} else if (noper_next_type) {
/* a NOTHING regop is 1 regop wide.
* We need at least two for a trie
* so we can't merge this in */
first = NULL;
}
} else {
trietype = noper_trietype;
}
} else {
if ( trietype == NOTHING )
trietype = noper_trietype;
last = cur;
}
if (first)
count++;
} /* end handle mergable triable node */
else {
/* handle unmergable node -
* noper may either be a triable node which can
* not be tried together with the current trie,
* or a non triable node */
if ( last ) {
/* If last is set and trietype is not
* NOTHING then we have found at least two
* triable branch sequences in a row of a
* similar trietype so we can turn them
* into a trie. If/when we allow NOTHING to
* start a trie sequence this condition
* will be required, and it isn't expensive
* so we leave it in for now. */
if ( trietype && trietype != NOTHING )
make_trie( pRExC_state,
startbranch, first, cur, tail,
count, trietype, depth+1 );
last = NULL; /* note: we clear/update
first, trietype etc below,
so we dont do it here */
}
if ( noper_trietype
#ifdef NOJUMPTRIE
&& noper_next >= tail
#endif
){
/* noper is triable, so we can start a new
* trie sequence */
count = 1;
first = cur;
trietype = noper_trietype;
} else if (first) {
/* if we already saw a first but the
* current node is not triable then we have
* to reset the first information. */
count = 0;
first = NULL;
trietype = 0;
}
} /* end handle unmergable node */
} /* loop over branches */
DEBUG_TRIE_COMPILE_r({
regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
Perl_re_indentf( aTHX_ "- %s (%d) <SCAN FINISHED> ",
depth+1, SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur));
Perl_re_printf( aTHX_ "(First==%d, Last==%d, Cur==%d, tt==%s)\n",
REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur),
PL_reg_name[trietype]
);
});
if ( last && trietype ) {
if ( trietype != NOTHING ) {
/* the last branch of the sequence was part of
* a trie, so we have to construct it here
* outside of the loop */
made= make_trie( pRExC_state, startbranch,
first, scan, tail, count,
trietype, depth+1 );
#ifdef TRIE_STUDY_OPT
if ( ((made == MADE_EXACT_TRIE &&
startbranch == first)
|| ( first_non_open == first )) &&
depth==0 ) {
flags |= SCF_TRIE_RESTUDY;
if ( startbranch == first
&& scan >= tail )
{
RExC_seen &=~REG_TOP_LEVEL_BRANCHES_SEEN;
}
}
#endif
} else {
/* at this point we know whatever we have is a
* NOTHING sequence/branch AND if 'startbranch'
* is 'first' then we can turn the whole thing
* into a NOTHING
*/
if ( startbranch == first ) {
regnode *opt;
/* the entire thing is a NOTHING sequence,
* something like this: (?:|) So we can
* turn it into a plain NOTHING op. */
DEBUG_TRIE_COMPILE_r({
regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
Perl_re_indentf( aTHX_ "- %s (%d) <NOTHING BRANCH SEQUENCE>\n",
depth+1,
SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur));
});
OP(startbranch)= NOTHING;
NEXT_OFF(startbranch)= tail - startbranch;
for ( opt= startbranch + 1; opt < tail ; opt++ )
OP(opt)= OPTIMIZED;
}
}
} /* end if ( last) */
} /* TRIE_MAXBUF is non zero */
} /* do trie */
}
else if ( code == BRANCHJ ) { /* single branch is optimized. */
scan = NEXTOPER(NEXTOPER(scan));
} else /* single branch is optimized. */
scan = NEXTOPER(scan);
continue;
} else if (OP(scan) == SUSPEND || OP(scan) == GOSUB) {
I32 paren = 0;
regnode *start = NULL;
regnode *end = NULL;
U32 my_recursed_depth= recursed_depth;
if (OP(scan) != SUSPEND) { /* GOSUB */
/* Do setup, note this code has side effects beyond
* the rest of this block. Specifically setting
* RExC_recurse[] must happen at least once during
* study_chunk(). */
paren = ARG(scan);
RExC_recurse[ARG2L(scan)] = scan;
start = REGNODE_p(RExC_open_parens[paren]);
end = REGNODE_p(RExC_close_parens[paren]);
/* NOTE we MUST always execute the above code, even
* if we do nothing with a GOSUB */
if (
( flags & SCF_IN_DEFINE )
||
(
(is_inf_internal || is_inf || (data && data->flags & SF_IS_INF))
&&
( (flags & (SCF_DO_STCLASS | SCF_DO_SUBSTR)) == 0 )
)
) {
/* no need to do anything here if we are in a define. */
/* or we are after some kind of infinite construct
* so we can skip recursing into this item.
* Since it is infinite we will not change the maxlen
* or delta, and if we miss something that might raise
* the minlen it will merely pessimise a little.
*
* Iow /(?(DEFINE)(?<foo>foo|food))a+(?&foo)/
* might result in a minlen of 1 and not of 4,
* but this doesn't make us mismatch, just try a bit
* harder than we should.
* */
scan= regnext(scan);
continue;
}
if (
!recursed_depth
||
!PAREN_TEST(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes), paren)
) {
/* it is quite possible that there are more efficient ways
* to do this. We maintain a bitmap per level of recursion
* of which patterns we have entered so we can detect if a
* pattern creates a possible infinite loop. When we
* recurse down a level we copy the previous levels bitmap
* down. When we are at recursion level 0 we zero the top
* level bitmap. It would be nice to implement a different
* more efficient way of doing this. In particular the top
* level bitmap may be unnecessary.
*/
if (!recursed_depth) {
Zero(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes, U8);
} else {
Copy(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes),
RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes),
RExC_study_chunk_recursed_bytes, U8);
}
/* we havent recursed into this paren yet, so recurse into it */
DEBUG_STUDYDATA("gosub-set", data, depth, is_inf);
PAREN_SET(RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes), paren);
my_recursed_depth= recursed_depth + 1;
} else {
DEBUG_STUDYDATA("gosub-inf", data, depth, is_inf);
/* some form of infinite recursion, assume infinite length
* */
if (flags & SCF_DO_SUBSTR) {
scan_commit(pRExC_state, data, minlenp, is_inf);
data->cur_is_floating = 1;
}
is_inf = is_inf_internal = 1;
if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
ssc_anything(data->start_class);
flags &= ~SCF_DO_STCLASS;
start= NULL; /* reset start so we dont recurse later on. */
}
} else {
paren = stopparen;
start = scan + 2;
end = regnext(scan);
}
if (start) {
scan_frame *newframe;
assert(end);
if (!RExC_frame_last) {
Newxz(newframe, 1, scan_frame);
SAVEDESTRUCTOR_X(S_unwind_scan_frames, newframe);
RExC_frame_head= newframe;
RExC_frame_count++;
} else if (!RExC_frame_last->next_frame) {
Newxz(newframe, 1, scan_frame);
RExC_frame_last->next_frame= newframe;
newframe->prev_frame= RExC_frame_last;
RExC_frame_count++;
} else {
newframe= RExC_frame_last->next_frame;
}
RExC_frame_last= newframe;
newframe->next_regnode = regnext(scan);
newframe->last_regnode = last;
newframe->stopparen = stopparen;
newframe->prev_recursed_depth = recursed_depth;
newframe->this_prev_frame= frame;
DEBUG_STUDYDATA("frame-new", data, depth, is_inf);
DEBUG_PEEP("fnew", scan, depth, flags);
frame = newframe;
scan = start;
stopparen = paren;
last = end;
depth = depth + 1;
recursed_depth= my_recursed_depth;
continue;
}
}
else if ( OP(scan) == EXACT
|| OP(scan) == EXACT_ONLY8
|| OP(scan) == EXACTL)
{
SSize_t l = STR_LEN(scan);
UV uc;
assert(l);
if (UTF) {
const U8 * const s = (U8*)STRING(scan);
uc = utf8_to_uvchr_buf(s, s + l, NULL);
l = utf8_length(s, s + l);
} else {
uc = *((U8*)STRING(scan));
}
min += l;
if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
/* The code below prefers earlier match for fixed
offset, later match for variable offset. */
if (data->last_end == -1) { /* Update the start info. */
data->last_start_min = data->pos_min;
data->last_start_max = is_inf
? SSize_t_MAX : data->pos_min + data->pos_delta;
}
sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));
if (UTF)
SvUTF8_on(data->last_found);
{
SV * const sv = data->last_found;
MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
mg_find(sv, PERL_MAGIC_utf8) : NULL;
if (mg && mg->mg_len >= 0)
mg->mg_len += utf8_length((U8*)STRING(scan),
(U8*)STRING(scan)+STR_LEN(scan));
}
data->last_end = data->pos_min + l;
data->pos_min += l; /* As in the first entry. */
data->flags &= ~SF_BEFORE_EOL;
}
/* ANDing the code point leaves at most it, and not in locale, and
* can't match null string */
if (flags & SCF_DO_STCLASS_AND) {
ssc_cp_and(data->start_class, uc);
ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
ssc_clear_locale(data->start_class);
}
else if (flags & SCF_DO_STCLASS_OR) {
ssc_add_cp(data->start_class, uc);
ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
/* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
}
flags &= ~SCF_DO_STCLASS;
}
else if (PL_regkind[OP(scan)] == EXACT) {
/* But OP != EXACT!, so is EXACTFish */
SSize_t l = STR_LEN(scan);
const U8 * s = (U8*)STRING(scan);
/* Search for fixed substrings supports EXACT only. */
if (flags & SCF_DO_SUBSTR) {
assert(data);
scan_commit(pRExC_state, data, minlenp, is_inf);
}
if (UTF) {
l = utf8_length(s, s + l);
}
if (unfolded_multi_char) {
RExC_seen |= REG_UNFOLDED_MULTI_SEEN;
}
min += l - min_subtract;
assert (min >= 0);
delta += min_subtract;
if (flags & SCF_DO_SUBSTR) {
data->pos_min += l - min_subtract;
if (data->pos_min < 0) {
data->pos_min = 0;
}
data->pos_delta += min_subtract;
if (min_subtract) {
data->cur_is_floating = 1; /* float */
}
}
if (flags & SCF_DO_STCLASS) {
SV* EXACTF_invlist = _make_exactf_invlist(pRExC_state, scan);
assert(EXACTF_invlist);
if (flags & SCF_DO_STCLASS_AND) {
if (OP(scan) != EXACTFL)
ssc_clear_locale(data->start_class);
ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
ANYOF_POSIXL_ZERO(data->start_class);
ssc_intersection(data->start_class, EXACTF_invlist, FALSE);
}
else { /* SCF_DO_STCLASS_OR */
ssc_union(data->start_class, EXACTF_invlist, FALSE);
ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
/* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
}
flags &= ~SCF_DO_STCLASS;
SvREFCNT_dec(EXACTF_invlist);
}
}
else if (REGNODE_VARIES(OP(scan))) {
SSize_t mincount, maxcount, minnext, deltanext, pos_before = 0;
I32 fl = 0, f = flags;
regnode * const oscan = scan;
regnode_ssc this_class;
regnode_ssc *oclass = NULL;
I32 next_is_eval = 0;
switch (PL_regkind[OP(scan)]) {
case WHILEM: /* End of (?:...)* . */
scan = NEXTOPER(scan);
goto finish;
case PLUS:
if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
next = NEXTOPER(scan);
if ( OP(next) == EXACT
|| OP(next) == EXACT_ONLY8
|| OP(next) == EXACTL
|| (flags & SCF_DO_STCLASS))
{
mincount = 1;
maxcount = REG_INFTY;
next = regnext(scan);
scan = NEXTOPER(scan);
goto do_curly;
}
}
if (flags & SCF_DO_SUBSTR)
data->pos_min++;
min++;
/* FALLTHROUGH */
case STAR:
next = NEXTOPER(scan);
/* This temporary node can now be turned into EXACTFU, and
* must, as regexec.c doesn't handle it */
if (OP(next) == EXACTFU_S_EDGE) {
OP(next) = EXACTFU;
}
if ( STR_LEN(next) == 1
&& isALPHA_A(* STRING(next))
&& ( OP(next) == EXACTFAA
|| ( OP(next) == EXACTFU
&& ! HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(* STRING(next)))))
{
/* These differ in just one bit */
U8 mask = ~ ('A' ^ 'a');
assert(isALPHA_A(* STRING(next)));
/* Then replace it by an ANYOFM node, with
* the mask set to the complement of the
* bit that differs between upper and lower
* case, and the lowest code point of the
* pair (which the '&' forces) */
OP(next) = ANYOFM;
ARG_SET(next, *STRING(next) & mask);
FLAGS(next) = mask;
}
if (flags & SCF_DO_STCLASS) {
mincount = 0;
maxcount = REG_INFTY;
next = regnext(scan);
scan = NEXTOPER(scan);
goto do_curly;
}
if (flags & SCF_DO_SUBSTR) {
scan_commit(pRExC_state, data, minlenp, is_inf);
/* Cannot extend fixed substrings */
data->cur_is_floating = 1; /* float */
}
is_inf = is_inf_internal = 1;
scan = regnext(scan);
goto optimize_curly_tail;
case CURLY:
if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM)
&& (scan->flags == stopparen))
{
mincount = 1;
maxcount = 1;
} else {
mincount = ARG1(scan);
maxcount = ARG2(scan);
}
next = regnext(scan);
if (OP(scan) == CURLYX) {
I32 lp = (data ? *(data->last_closep) : 0);
scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);
}
scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
next_is_eval = (OP(scan) == EVAL);
do_curly:
if (flags & SCF_DO_SUBSTR) {
if (mincount == 0)
scan_commit(pRExC_state, data, minlenp, is_inf);
/* Cannot extend fixed substrings */
pos_before = data->pos_min;
}
if (data) {
fl = data->flags;
data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
if (is_inf)
data->flags |= SF_IS_INF;
}
if (flags & SCF_DO_STCLASS) {
ssc_init(pRExC_state, &this_class);
oclass = data->start_class;
data->start_class = &this_class;
f |= SCF_DO_STCLASS_AND;
f &= ~SCF_DO_STCLASS_OR;
}
/* Exclude from super-linear cache processing any {n,m}
regops for which the combination of input pos and regex
pos is not enough information to determine if a match
will be possible.
For example, in the regex /foo(bar\s*){4,8}baz/ with the
regex pos at the \s*, the prospects for a match depend not
only on the input position but also on how many (bar\s*)
repeats into the {4,8} we are. */
if ((mincount > 1) || (maxcount > 1 && maxcount != REG_INFTY))
f &= ~SCF_WHILEM_VISITED_POS;
/* This will finish on WHILEM, setting scan, or on NULL: */
/* recurse study_chunk() on loop bodies */
minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
last, data, stopparen, recursed_depth, NULL,
(mincount == 0
? (f & ~SCF_DO_SUBSTR)
: f)
,depth+1);
if (flags & SCF_DO_STCLASS)
data->start_class = oclass;
if (mincount == 0 || minnext == 0) {
if (flags & SCF_DO_STCLASS_OR) {
ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
}
else if (flags & SCF_DO_STCLASS_AND) {
/* Switch to OR mode: cache the old value of
* data->start_class */
INIT_AND_WITHP;
StructCopy(data->start_class, and_withp, regnode_ssc);
flags &= ~SCF_DO_STCLASS_AND;
StructCopy(&this_class, data->start_class, regnode_ssc);
flags |= SCF_DO_STCLASS_OR;
ANYOF_FLAGS(data->start_class)
|= SSC_MATCHES_EMPTY_STRING;
}
} else { /* Non-zero len */
if (flags & SCF_DO_STCLASS_OR) {
ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
}
else if (flags & SCF_DO_STCLASS_AND)
ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
flags &= ~SCF_DO_STCLASS;
}
if (!scan) /* It was not CURLYX, but CURLY. */
scan = next;
if (((flags & (SCF_TRIE_DOING_RESTUDY|SCF_DO_SUBSTR))==SCF_DO_SUBSTR)
/* ? quantifier ok, except for (?{ ... }) */
&& (next_is_eval || !(mincount == 0 && maxcount == 1))
&& (minnext == 0) && (deltanext == 0)
&& data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
&& maxcount <= REG_INFTY/3) /* Complement check for big
count */
{
_WARN_HELPER(RExC_precomp_end, packWARN(WARN_REGEXP),
Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),
"Quantifier unexpected on zero-length expression "
"in regex m/%" UTF8f "/",
UTF8fARG(UTF, RExC_precomp_end - RExC_precomp,
RExC_precomp)));
}
min += minnext * mincount;
is_inf_internal |= deltanext == SSize_t_MAX
|| (maxcount == REG_INFTY && minnext + deltanext > 0);
is_inf |= is_inf_internal;
if (is_inf) {
delta = SSize_t_MAX;
} else {
delta += (minnext + deltanext) * maxcount
- minnext * mincount;
}
/* Try powerful optimization CURLYX => CURLYN. */
if ( OP(oscan) == CURLYX && data
&& data->flags & SF_IN_PAR
&& !(data->flags & SF_HAS_EVAL)
&& !deltanext && minnext == 1 ) {
/* Try to optimize to CURLYN. */
regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
regnode * const nxt1 = nxt;
#ifdef DEBUGGING
regnode *nxt2;
#endif
/* Skip open. */
nxt = regnext(nxt);
if (!REGNODE_SIMPLE(OP(nxt))
&& !(PL_regkind[OP(nxt)] == EXACT
&& STR_LEN(nxt) == 1))
goto nogo;
#ifdef DEBUGGING
nxt2 = nxt;
#endif
nxt = regnext(nxt);
if (OP(nxt) != CLOSE)
goto nogo;
if (RExC_open_parens) {
/*open->CURLYM*/
RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan);
/*close->while*/
RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt) + 2;
}
/* Now we know that nxt2 is the only contents: */
oscan->flags = (U8)ARG(nxt);
OP(oscan) = CURLYN;
OP(nxt1) = NOTHING; /* was OPEN. */
#ifdef DEBUGGING
OP(nxt1 + 1) = OPTIMIZED; /* was count. */
NEXT_OFF(nxt1+ 1) = 0; /* just for consistency. */
NEXT_OFF(nxt2) = 0; /* just for consistency with CURLY. */
OP(nxt) = OPTIMIZED; /* was CLOSE. */
OP(nxt + 1) = OPTIMIZED; /* was count. */
NEXT_OFF(nxt+ 1) = 0; /* just for consistency. */
#endif
}
nogo:
/* Try optimization CURLYX => CURLYM. */
if ( OP(oscan) == CURLYX && data
&& !(data->flags & SF_HAS_PAR)
&& !(data->flags & SF_HAS_EVAL)
&& !deltanext /* atom is fixed width */
&& minnext != 0 /* CURLYM can't handle zero width */
/* Nor characters whose fold at run-time may be
* multi-character */
&& ! (RExC_seen & REG_UNFOLDED_MULTI_SEEN)
) {
/* XXXX How to optimize if data == 0? */
/* Optimize to a simpler form. */
regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
regnode *nxt2;
OP(oscan) = CURLYM;
while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
&& (OP(nxt2) != WHILEM))
nxt = nxt2;
OP(nxt2) = SUCCEED; /* Whas WHILEM */
/* Need to optimize away parenths. */
if ((data->flags & SF_IN_PAR) && OP(nxt) == CLOSE) {
/* Set the parenth number. */
regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
oscan->flags = (U8)ARG(nxt);
if (RExC_open_parens) {
/*open->CURLYM*/
RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan);
/*close->NOTHING*/
RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt2)
+ 1;
}
OP(nxt1) = OPTIMIZED; /* was OPEN. */
OP(nxt) = OPTIMIZED; /* was CLOSE. */
#ifdef DEBUGGING
OP(nxt1 + 1) = OPTIMIZED; /* was count. */
OP(nxt + 1) = OPTIMIZED; /* was count. */
NEXT_OFF(nxt1 + 1) = 0; /* just for consistency. */
NEXT_OFF(nxt + 1) = 0; /* just for consistency. */
#endif
#if 0
while ( nxt1 && (OP(nxt1) != WHILEM)) {
regnode *nnxt = regnext(nxt1);
if (nnxt == nxt) {
if (reg_off_by_arg[OP(nxt1)])
ARG_SET(nxt1, nxt2 - nxt1);
else if (nxt2 - nxt1 < U16_MAX)
NEXT_OFF(nxt1) = nxt2 - nxt1;
else
OP(nxt) = NOTHING; /* Cannot beautify */
}
nxt1 = nnxt;
}
#endif
/* Optimize again: */
/* recurse study_chunk() on optimised CURLYX => CURLYM */
study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,
NULL, stopparen, recursed_depth, NULL, 0,
depth+1);
}
else
oscan->flags = 0;
}
else if ((OP(oscan) == CURLYX)
&& (flags & SCF_WHILEM_VISITED_POS)
/* See the comment on a similar expression above.
However, this time it's not a subexpression
we care about, but the expression itself. */
&& (maxcount == REG_INFTY)
&& data) {
/* This stays as CURLYX, we can put the count/of pair. */
/* Find WHILEM (as in regexec.c) */
regnode *nxt = oscan + NEXT_OFF(oscan);
if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
nxt += ARG(nxt);
nxt = PREVOPER(nxt);
if (nxt->flags & 0xf) {
/* we've already set whilem count on this node */
} else if (++data->whilem_c < 16) {
assert(data->whilem_c <= RExC_whilem_seen);
nxt->flags = (U8)(data->whilem_c
| (RExC_whilem_seen << 4)); /* On WHILEM */
}
}
if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
pars++;
if (flags & SCF_DO_SUBSTR) {
SV *last_str = NULL;
STRLEN last_chrs = 0;
int counted = mincount != 0;
if (data->last_end > 0 && mincount != 0) { /* Ends with a
string. */
SSize_t b = pos_before >= data->last_start_min
? pos_before : data->last_start_min;
STRLEN l;
const char * const s = SvPV_const(data->last_found, l);
SSize_t old = b - data->last_start_min;
assert(old >= 0);
if (UTF)
old = utf8_hop_forward((U8*)s, old,
(U8 *) SvEND(data->last_found))
- (U8*)s;
l -= old;
/* Get the added string: */
last_str = newSVpvn_utf8(s + old, l, UTF);
last_chrs = UTF ? utf8_length((U8*)(s + old),
(U8*)(s + old + l)) : l;
if (deltanext == 0 && pos_before == b) {
/* What was added is a constant string */
if (mincount > 1) {
SvGROW(last_str, (mincount * l) + 1);
repeatcpy(SvPVX(last_str) + l,
SvPVX_const(last_str), l,
mincount - 1);
SvCUR_set(last_str, SvCUR(last_str) * mincount);
/* Add additional parts. */
SvCUR_set(data->last_found,
SvCUR(data->last_found) - l);
sv_catsv(data->last_found, last_str);
{
SV * sv = data->last_found;
MAGIC *mg =
SvUTF8(sv) && SvMAGICAL(sv) ?
mg_find(sv, PERL_MAGIC_utf8) : NULL;
if (mg && mg->mg_len >= 0)
mg->mg_len += last_chrs * (mincount-1);
}
last_chrs *= mincount;
data->last_end += l * (mincount - 1);
}
} else {
/* start offset must point into the last copy */
data->last_start_min += minnext * (mincount - 1);
data->last_start_max =
is_inf
? SSize_t_MAX
: data->last_start_max +
(maxcount - 1) * (minnext + data->pos_delta);
}
}
/* It is counted once already... */
data->pos_min += minnext * (mincount - counted);
#if 0
Perl_re_printf( aTHX_ "counted=%" UVuf " deltanext=%" UVuf
" SSize_t_MAX=%" UVuf " minnext=%" UVuf
" maxcount=%" UVuf " mincount=%" UVuf "\n",
(UV)counted, (UV)deltanext, (UV)SSize_t_MAX, (UV)minnext, (UV)maxcount,
(UV)mincount);
if (deltanext != SSize_t_MAX)
Perl_re_printf( aTHX_ "LHS=%" UVuf " RHS=%" UVuf "\n",
(UV)(-counted * deltanext + (minnext + deltanext) * maxcount
- minnext * mincount), (UV)(SSize_t_MAX - data->pos_delta));
#endif
if (deltanext == SSize_t_MAX
|| -counted * deltanext + (minnext + deltanext) * maxcount - minnext * mincount >= SSize_t_MAX - data->pos_delta)
data->pos_delta = SSize_t_MAX;
else
data->pos_delta += - counted * deltanext +
(minnext + deltanext) * maxcount - minnext * mincount;
if (mincount != maxcount) {
/* Cannot extend fixed substrings found inside
the group. */
scan_commit(pRExC_state, data, minlenp, is_inf);
if (mincount && last_str) {
SV * const sv = data->last_found;
MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
mg_find(sv, PERL_MAGIC_utf8) : NULL;
if (mg)
mg->mg_len = -1;
sv_setsv(sv, last_str);
data->last_end = data->pos_min;
data->last_start_min = data->pos_min - last_chrs;
data->last_start_max = is_inf
? SSize_t_MAX
: data->pos_min + data->pos_delta - last_chrs;
}
data->cur_is_floating = 1; /* float */
}
SvREFCNT_dec(last_str);
}
if (data && (fl & SF_HAS_EVAL))
data->flags |= SF_HAS_EVAL;
optimize_curly_tail:
if (OP(oscan) != CURLYX) {
while (PL_regkind[OP(next = regnext(oscan))] == NOTHING
&& NEXT_OFF(next))
NEXT_OFF(oscan) += NEXT_OFF(next);
}
continue;
default:
#ifdef DEBUGGING
Perl_croak(aTHX_ "panic: unexpected varying REx opcode %d",
OP(scan));
#endif
case REF:
case CLUMP:
if (flags & SCF_DO_SUBSTR) {
/* Cannot expect anything... */
scan_commit(pRExC_state, data, minlenp, is_inf);
data->cur_is_floating = 1; /* float */
}
is_inf = is_inf_internal = 1;
if (flags & SCF_DO_STCLASS_OR) {
if (OP(scan) == CLUMP) {
/* Actually is any start char, but very few code points
* aren't start characters */
ssc_match_all_cp(data->start_class);
}
else {
ssc_anything(data->start_class);
}
}
flags &= ~SCF_DO_STCLASS;
break;
}
}
else if (OP(scan) == LNBREAK) {
if (flags & SCF_DO_STCLASS) {
if (flags & SCF_DO_STCLASS_AND) {
ssc_intersection(data->start_class,
PL_XPosix_ptrs[_CC_VERTSPACE], FALSE);
ssc_clear_locale(data->start_class);
ANYOF_FLAGS(data->start_class)
&= ~SSC_MATCHES_EMPTY_STRING;
}
else if (flags & SCF_DO_STCLASS_OR) {
ssc_union(data->start_class,
PL_XPosix_ptrs[_CC_VERTSPACE],
FALSE);
ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
/* See commit msg for
* 749e076fceedeb708a624933726e7989f2302f6a */
ANYOF_FLAGS(data->start_class)
&= ~SSC_MATCHES_EMPTY_STRING;
}
flags &= ~SCF_DO_STCLASS;
}
min++;
if (delta != SSize_t_MAX)
delta++; /* Because of the 2 char string cr-lf */
if (flags & SCF_DO_SUBSTR) {
/* Cannot expect anything... */
scan_commit(pRExC_state, data, minlenp, is_inf);
data->pos_min += 1;
if (data->pos_delta != SSize_t_MAX) {
data->pos_delta += 1;
}
data->cur_is_floating = 1; /* float */
}
}
else if (REGNODE_SIMPLE(OP(scan))) {
if (flags & SCF_DO_SUBSTR) {
scan_commit(pRExC_state, data, minlenp, is_inf);
data->pos_min++;
}
min++;
if (flags & SCF_DO_STCLASS) {
bool invert = 0;
SV* my_invlist = NULL;
U8 namedclass;
/* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
/* Some of the logic below assumes that switching
locale on will only add false positives. */
switch (OP(scan)) {
default:
#ifdef DEBUGGING
Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d",
OP(scan));
#endif
case SANY:
if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
ssc_match_all_cp(data->start_class);
break;
case REG_ANY:
{
SV* REG_ANY_invlist = _new_invlist(2);
REG_ANY_invlist = add_cp_to_invlist(REG_ANY_invlist,
'\n');
if (flags & SCF_DO_STCLASS_OR) {
ssc_union(data->start_class,
REG_ANY_invlist,
TRUE /* TRUE => invert, hence all but \n
*/
);
}
else if (flags & SCF_DO_STCLASS_AND) {
ssc_intersection(data->start_class,
REG_ANY_invlist,
TRUE /* TRUE => invert */
);
ssc_clear_locale(data->start_class);
}
SvREFCNT_dec_NN(REG_ANY_invlist);
}
break;
case ANYOFD:
case ANYOFL:
case ANYOFPOSIXL:
case ANYOFH:
case ANYOF:
if (flags & SCF_DO_STCLASS_AND)
ssc_and(pRExC_state, data->start_class,
(regnode_charclass *) scan);
else
ssc_or(pRExC_state, data->start_class,
(regnode_charclass *) scan);
break;
case NANYOFM:
case ANYOFM:
{
SV* cp_list = get_ANYOFM_contents(scan);
if (flags & SCF_DO_STCLASS_OR) {
ssc_union(data->start_class, cp_list, invert);
}
else if (flags & SCF_DO_STCLASS_AND) {
ssc_intersection(data->start_class, cp_list, invert);
}
SvREFCNT_dec_NN(cp_list);
break;
}
case NPOSIXL:
invert = 1;
/* FALLTHROUGH */
case POSIXL:
namedclass = classnum_to_namedclass(FLAGS(scan)) + invert;
if (flags & SCF_DO_STCLASS_AND) {
bool was_there = cBOOL(
ANYOF_POSIXL_TEST(data->start_class,
namedclass));
ANYOF_POSIXL_ZERO(data->start_class);
if (was_there) { /* Do an AND */
ANYOF_POSIXL_SET(data->start_class, namedclass);
}
/* No individual code points can now match */
data->start_class->invlist
= sv_2mortal(_new_invlist(0));
}
else {
int complement = namedclass + ((invert) ? -1 : 1);
assert(flags & SCF_DO_STCLASS_OR);
/* If the complement of this class was already there,
* the result is that they match all code points,
* (\d + \D == everything). Remove the classes from
* future consideration. Locale is not relevant in
* this case */
if (ANYOF_POSIXL_TEST(data->start_class, complement)) {
ssc_match_all_cp(data->start_class);
ANYOF_POSIXL_CLEAR(data->start_class, namedclass);
ANYOF_POSIXL_CLEAR(data->start_class, complement);
}
else { /* The usual case; just add this class to the
existing set */
ANYOF_POSIXL_SET(data->start_class, namedclass);
}
}
break;
case NPOSIXA: /* For these, we always know the exact set of
what's matched */
invert = 1;
/* FALLTHROUGH */
case POSIXA:
my_invlist = invlist_clone(PL_Posix_ptrs[FLAGS(scan)], NULL);
goto join_posix_and_ascii;
case NPOSIXD:
case NPOSIXU:
invert = 1;
/* FALLTHROUGH */
case POSIXD:
case POSIXU:
my_invlist = invlist_clone(PL_XPosix_ptrs[FLAGS(scan)], NULL);
/* NPOSIXD matches all upper Latin1 code points unless the
* target string being matched is UTF-8, which is
* unknowable until match time. Since we are going to
* invert, we want to get rid of all of them so that the
* inversion will match all */
if (OP(scan) == NPOSIXD) {
_invlist_subtract(my_invlist, PL_UpperLatin1,
&my_invlist);
}
join_posix_and_ascii:
if (flags & SCF_DO_STCLASS_AND) {
ssc_intersection(data->start_class, my_invlist, invert);
ssc_clear_locale(data->start_class);
}
else {
assert(flags & SCF_DO_STCLASS_OR);
ssc_union(data->start_class, my_invlist, invert);
}
SvREFCNT_dec(my_invlist);
}
if (flags & SCF_DO_STCLASS_OR)
ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
flags &= ~SCF_DO_STCLASS;
}
}
else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
data->flags |= (OP(scan) == MEOL
? SF_BEFORE_MEOL
: SF_BEFORE_SEOL);
scan_commit(pRExC_state, data, minlenp, is_inf);
}
else if ( PL_regkind[OP(scan)] == BRANCHJ
/* Lookbehind, or need to calculate parens/evals/stclass: */
&& (scan->flags || data || (flags & SCF_DO_STCLASS))
&& (OP(scan) == IFMATCH || OP(scan) == UNLESSM))
{
if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY
|| OP(scan) == UNLESSM )
{
/* Negative Lookahead/lookbehind
In this case we can't do fixed string optimisation.
*/
SSize_t deltanext, minnext, fake = 0;
regnode *nscan;
regnode_ssc intrnl;
int f = 0;
StructCopy(&zero_scan_data, &data_fake, scan_data_t);
if (data) {
data_fake.whilem_c = data->whilem_c;
data_fake.last_closep = data->last_closep;
}
else
data_fake.last_closep = &fake;
data_fake.pos_delta = delta;
if ( flags & SCF_DO_STCLASS && !scan->flags
&& OP(scan) == IFMATCH ) { /* Lookahead */
ssc_init(pRExC_state, &intrnl);
data_fake.start_class = &intrnl;
f |= SCF_DO_STCLASS_AND;
}
if (flags & SCF_WHILEM_VISITED_POS)
f |= SCF_WHILEM_VISITED_POS;
next = regnext(scan);
nscan = NEXTOPER(NEXTOPER(scan));
/* recurse study_chunk() for lookahead body */
minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext,
last, &data_fake, stopparen,
recursed_depth, NULL, f, depth+1);
if (scan->flags) {
if ( deltanext < 0
|| deltanext > (I32) U8_MAX
|| minnext > (I32)U8_MAX
|| minnext + deltanext > (I32)U8_MAX)
{
FAIL2("Lookbehind longer than %" UVuf " not implemented",
(UV)U8_MAX);
}
/* The 'next_off' field has been repurposed to count the
* additional starting positions to try beyond the initial
* one. (This leaves it at 0 for non-variable length
* matches to avoid breakage for those not using this
* extension) */
if (deltanext) {
scan->next_off = deltanext;
ckWARNexperimental(RExC_parse,
WARN_EXPERIMENTAL__VLB,
"Variable length lookbehind is experimental");
}
scan->flags = (U8)minnext + deltanext;
}
if (data) {
if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
pars++;
if (data_fake.flags & SF_HAS_EVAL)
data->flags |= SF_HAS_EVAL;
data->whilem_c = data_fake.whilem_c;
}
if (f & SCF_DO_STCLASS_AND) {
if (flags & SCF_DO_STCLASS_OR) {
/* OR before, AND after: ideally we would recurse with
* data_fake to get the AND applied by study of the
* remainder of the pattern, and then derecurse;
* *** HACK *** for now just treat as "no information".
* See [perl #56690].
*/
ssc_init(pRExC_state, data->start_class);
} else {
/* AND before and after: combine and continue. These
* assertions are zero-length, so can match an EMPTY
* string */
ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl);
ANYOF_FLAGS(data->start_class)
|= SSC_MATCHES_EMPTY_STRING;
}
}
}
#if PERL_ENABLE_POSITIVE_ASSERTION_STUDY
else {
/* Positive Lookahead/lookbehind
In this case we can do fixed string optimisation,
but we must be careful about it. Note in the case of
lookbehind the positions will be offset by the minimum
length of the pattern, something we won't know about
until after the recurse.
*/
SSize_t deltanext, fake = 0;
regnode *nscan;
regnode_ssc intrnl;
int f = 0;
/* We use SAVEFREEPV so that when the full compile
is finished perl will clean up the allocated
minlens when it's all done. This way we don't
have to worry about freeing them when we know
they wont be used, which would be a pain.
*/
SSize_t *minnextp;
Newx( minnextp, 1, SSize_t );
SAVEFREEPV(minnextp);
if (data) {
StructCopy(data, &data_fake, scan_data_t);
if ((flags & SCF_DO_SUBSTR) && data->last_found) {
f |= SCF_DO_SUBSTR;
if (scan->flags)
scan_commit(pRExC_state, &data_fake, minlenp, is_inf);
data_fake.last_found=newSVsv(data->last_found);
}
}
else
data_fake.last_closep = &fake;
data_fake.flags = 0;
data_fake.substrs[0].flags = 0;
data_fake.substrs[1].flags = 0;
data_fake.pos_delta = delta;
if (is_inf)
data_fake.flags |= SF_IS_INF;
if ( flags & SCF_DO_STCLASS && !scan->flags
&& OP(scan) == IFMATCH ) { /* Lookahead */
ssc_init(pRExC_state, &intrnl);
data_fake.start_class = &intrnl;
f |= SCF_DO_STCLASS_AND;
}
if (flags & SCF_WHILEM_VISITED_POS)
f |= SCF_WHILEM_VISITED_POS;
next = regnext(scan);
nscan = NEXTOPER(NEXTOPER(scan));
/* positive lookahead study_chunk() recursion */
*minnextp = study_chunk(pRExC_state, &nscan, minnextp,
&deltanext, last, &data_fake,
stopparen, recursed_depth, NULL,
f, depth+1);
if (scan->flags) {
assert(0); /* This code has never been tested since this
is normally not compiled */
if ( deltanext < 0
|| deltanext > (I32) U8_MAX
|| *minnextp > (I32)U8_MAX
|| *minnextp + deltanext > (I32)U8_MAX)
{
FAIL2("Lookbehind longer than %" UVuf " not implemented",
(UV)U8_MAX);
}
if (deltanext) {
scan->next_off = deltanext;
}
scan->flags = (U8)*minnextp + deltanext;
}
*minnextp += min;
if (f & SCF_DO_STCLASS_AND) {
ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl);
ANYOF_FLAGS(data->start_class) |= SSC_MATCHES_EMPTY_STRING;
}
if (data) {
if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
pars++;
if (data_fake.flags & SF_HAS_EVAL)
data->flags |= SF_HAS_EVAL;
data->whilem_c = data_fake.whilem_c;
if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) {
int i;
if (RExC_rx->minlen<*minnextp)
RExC_rx->minlen=*minnextp;
scan_commit(pRExC_state, &data_fake, minnextp, is_inf);
SvREFCNT_dec_NN(data_fake.last_found);
for (i = 0; i < 2; i++) {
if (data_fake.substrs[i].minlenp != minlenp) {
data->substrs[i].min_offset =
data_fake.substrs[i].min_offset;
data->substrs[i].max_offset =
data_fake.substrs[i].max_offset;
data->substrs[i].minlenp =
data_fake.substrs[i].minlenp;
data->substrs[i].lookbehind += scan->flags;
}
}
}
}
}
#endif
}
else if (OP(scan) == OPEN) {
if (stopparen != (I32)ARG(scan))
pars++;
}
else if (OP(scan) == CLOSE) {
if (stopparen == (I32)ARG(scan)) {
break;
}
if ((I32)ARG(scan) == is_par) {
next = regnext(scan);
if ( next && (OP(next) != WHILEM) && next < last)
is_par = 0; /* Disable optimization */
}
if (data)
*(data->last_closep) = ARG(scan);
}
else if (OP(scan) == EVAL) {
if (data)
data->flags |= SF_HAS_EVAL;
}
else if ( PL_regkind[OP(scan)] == ENDLIKE ) {
if (flags & SCF_DO_SUBSTR) {
scan_commit(pRExC_state, data, minlenp, is_inf);
flags &= ~SCF_DO_SUBSTR;
}
if (data && OP(scan)==ACCEPT) {
data->flags |= SCF_SEEN_ACCEPT;
if (stopmin > min)
stopmin = min;
}
}
else if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */
{
if (flags & SCF_DO_SUBSTR) {
scan_commit(pRExC_state, data, minlenp, is_inf);
data->cur_is_floating = 1; /* float */
}
is_inf = is_inf_internal = 1;
if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
ssc_anything(data->start_class);
flags &= ~SCF_DO_STCLASS;
}
else if (OP(scan) == GPOS) {
if (!(RExC_rx->intflags & PREGf_GPOS_FLOAT) &&
!(delta || is_inf || (data && data->pos_delta)))
{
if (!(RExC_rx->intflags & PREGf_ANCH) && (flags & SCF_DO_SUBSTR))
RExC_rx->intflags |= PREGf_ANCH_GPOS;
if (RExC_rx->gofs < (STRLEN)min)
RExC_rx->gofs = min;
} else {
RExC_rx->intflags |= PREGf_GPOS_FLOAT;
RExC_rx->gofs = 0;
}
}
#ifdef TRIE_STUDY_OPT
#ifdef FULL_TRIE_STUDY
else if (PL_regkind[OP(scan)] == TRIE) {
/* NOTE - There is similar code to this block above for handling
BRANCH nodes on the initial study. If you change stuff here
check there too. */
regnode *trie_node= scan;
regnode *tail= regnext(scan);
reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
SSize_t max1 = 0, min1 = SSize_t_MAX;
regnode_ssc accum;
if (flags & SCF_DO_SUBSTR) { /* XXXX Add !SUSPEND? */
/* Cannot merge strings after this. */
scan_commit(pRExC_state, data, minlenp, is_inf);
}
if (flags & SCF_DO_STCLASS)
ssc_init_zero(pRExC_state, &accum);
if (!trie->jump) {
min1= trie->minlen;
max1= trie->maxlen;
} else {
const regnode *nextbranch= NULL;
U32 word;
for ( word=1 ; word <= trie->wordcount ; word++)
{
SSize_t deltanext=0, minnext=0, f = 0, fake;
regnode_ssc this_class;
StructCopy(&zero_scan_data, &data_fake, scan_data_t);
if (data) {
data_fake.whilem_c = data->whilem_c;
data_fake.last_closep = data->last_closep;
}
else
data_fake.last_closep = &fake;
data_fake.pos_delta = delta;
if (flags & SCF_DO_STCLASS) {
ssc_init(pRExC_state, &this_class);
data_fake.start_class = &this_class;
f = SCF_DO_STCLASS_AND;
}
if (flags & SCF_WHILEM_VISITED_POS)
f |= SCF_WHILEM_VISITED_POS;
if (trie->jump[word]) {
if (!nextbranch)
nextbranch = trie_node + trie->jump[0];
scan= trie_node + trie->jump[word];
/* We go from the jump point to the branch that follows
it. Note this means we need the vestigal unused
branches even though they arent otherwise used. */
/* optimise study_chunk() for TRIE */
minnext = study_chunk(pRExC_state, &scan, minlenp,
&deltanext, (regnode *)nextbranch, &data_fake,
stopparen, recursed_depth, NULL, f, depth+1);
}
if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
nextbranch= regnext((regnode*)nextbranch);
if (min1 > (SSize_t)(minnext + trie->minlen))
min1 = minnext + trie->minlen;
if (deltanext == SSize_t_MAX) {
is_inf = is_inf_internal = 1;
max1 = SSize_t_MAX;
} else if (max1 < (SSize_t)(minnext + deltanext + trie->maxlen))
max1 = minnext + deltanext + trie->maxlen;
if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
pars++;
if (data_fake.flags & SCF_SEEN_ACCEPT) {
if ( stopmin > min + min1)
stopmin = min + min1;
flags &= ~SCF_DO_SUBSTR;
if (data)
data->flags |= SCF_SEEN_ACCEPT;
}
if (data) {
if (data_fake.flags & SF_HAS_EVAL)
data->flags |= SF_HAS_EVAL;
data->whilem_c = data_fake.whilem_c;
}
if (flags & SCF_DO_STCLASS)
ssc_or(pRExC_state, &accum, (regnode_charclass *) &this_class);
}
}
if (flags & SCF_DO_SUBSTR) {
data->pos_min += min1;
data->pos_delta += max1 - min1;
if (max1 != min1 || is_inf)
data->cur_is_floating = 1; /* float */
}
min += min1;
if (delta != SSize_t_MAX) {
if (SSize_t_MAX - (max1 - min1) >= delta)
delta += max1 - min1;
else
delta = SSize_t_MAX;
}
if (flags & SCF_DO_STCLASS_OR) {
ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &accum);
if (min1) {
ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
flags &= ~SCF_DO_STCLASS;
}
}
else if (flags & SCF_DO_STCLASS_AND) {
if (min1) {
ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum);
flags &= ~SCF_DO_STCLASS;
}
else {
/* Switch to OR mode: cache the old value of
* data->start_class */
INIT_AND_WITHP;
StructCopy(data->start_class, and_withp, regnode_ssc);
flags &= ~SCF_DO_STCLASS_AND;
StructCopy(&accum, data->start_class, regnode_ssc);
flags |= SCF_DO_STCLASS_OR;
}
}
scan= tail;
continue;
}
#else
else if (PL_regkind[OP(scan)] == TRIE) {
reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
U8*bang=NULL;
min += trie->minlen;
delta += (trie->maxlen - trie->minlen);
flags &= ~SCF_DO_STCLASS; /* xxx */
if (flags & SCF_DO_SUBSTR) {
/* Cannot expect anything... */
scan_commit(pRExC_state, data, minlenp, is_inf);
data->pos_min += trie->minlen;
data->pos_delta += (trie->maxlen - trie->minlen);
if (trie->maxlen != trie->minlen)
data->cur_is_floating = 1; /* float */
}
if (trie->jump) /* no more substrings -- for now /grr*/
flags &= ~SCF_DO_SUBSTR;
}
#endif /* old or new */
#endif /* TRIE_STUDY_OPT */
/* Else: zero-length, ignore. */
scan = regnext(scan);
}
finish:
if (frame) {
/* we need to unwind recursion. */
depth = depth - 1;
DEBUG_STUDYDATA("frame-end", data, depth, is_inf);
DEBUG_PEEP("fend", scan, depth, flags);
/* restore previous context */
last = frame->last_regnode;
scan = frame->next_regnode;
stopparen = frame->stopparen;
recursed_depth = frame->prev_recursed_depth;
RExC_frame_last = frame->prev_frame;
frame = frame->this_prev_frame;
goto fake_study_recurse;
}
assert(!frame);
DEBUG_STUDYDATA("pre-fin", data, depth, is_inf);
*scanp = scan;
*deltap = is_inf_internal ? SSize_t_MAX : delta;
if (flags & SCF_DO_SUBSTR && is_inf)
data->pos_delta = SSize_t_MAX - data->pos_min;
if (is_par > (I32)U8_MAX)
is_par = 0;
if (is_par && pars==1 && data) {
data->flags |= SF_IN_PAR;
data->flags &= ~SF_HAS_PAR;
}
else if (pars && data) {
data->flags |= SF_HAS_PAR;
data->flags &= ~SF_IN_PAR;
}
if (flags & SCF_DO_STCLASS_OR)
ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
if (flags & SCF_TRIE_RESTUDY)
data->flags |= SCF_TRIE_RESTUDY;
DEBUG_STUDYDATA("post-fin", data, depth, is_inf);
{
SSize_t final_minlen= min < stopmin ? min : stopmin;
if (!(RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN)) {
if (final_minlen > SSize_t_MAX - delta)
RExC_maxlen = SSize_t_MAX;
else if (RExC_maxlen < final_minlen + delta)
RExC_maxlen = final_minlen + delta;
}
return final_minlen;
}
NOT_REACHED; /* NOTREACHED */
}
STATIC U32
S_add_data(RExC_state_t* const pRExC_state, const char* const s, const U32 n)
{
U32 count = RExC_rxi->data ? RExC_rxi->data->count : 0;
PERL_ARGS_ASSERT_ADD_DATA;
Renewc(RExC_rxi->data,
sizeof(*RExC_rxi->data) + sizeof(void*) * (count + n - 1),
char, struct reg_data);
if(count)
Renew(RExC_rxi->data->what, count + n, U8);
else
Newx(RExC_rxi->data->what, n, U8);
RExC_rxi->data->count = count + n;
Copy(s, RExC_rxi->data->what + count, n, U8);
return count;
}
/*XXX: todo make this not included in a non debugging perl, but appears to be
* used anyway there, in 'use re' */
#ifndef PERL_IN_XSUB_RE
void
Perl_reginitcolors(pTHX)
{
const char * const s = PerlEnv_getenv("PERL_RE_COLORS");
if (s) {
char *t = savepv(s);
int i = 0;
PL_colors[0] = t;
while (++i < 6) {
t = strchr(t, '\t');
if (t) {
*t = '\0';
PL_colors[i] = ++t;
}
else
PL_colors[i] = t = (char *)"";
}
} else {
int i = 0;
while (i < 6)
PL_colors[i++] = (char *)"";
}
PL_colorset = 1;
}
#endif
#ifdef TRIE_STUDY_OPT
#define CHECK_RESTUDY_GOTO_butfirst(dOsomething) \
STMT_START { \
if ( \
(data.flags & SCF_TRIE_RESTUDY) \
&& ! restudied++ \
) { \
dOsomething; \
goto reStudy; \
} \
} STMT_END
#else
#define CHECK_RESTUDY_GOTO_butfirst
#endif
/*
* pregcomp - compile a regular expression into internal code
*
* Decides which engine's compiler to call based on the hint currently in
* scope
*/
#ifndef PERL_IN_XSUB_RE
/* return the currently in-scope regex engine (or the default if none) */
regexp_engine const *
Perl_current_re_engine(pTHX)
{
if (IN_PERL_COMPILETIME) {
HV * const table = GvHV(PL_hintgv);
SV **ptr;
if (!table || !(PL_hints & HINT_LOCALIZE_HH))
return &PL_core_reg_engine;
ptr = hv_fetchs(table, "regcomp", FALSE);
if ( !(ptr && SvIOK(*ptr) && SvIV(*ptr)))
return &PL_core_reg_engine;
return INT2PTR(regexp_engine*, SvIV(*ptr));
}
else {
SV *ptr;
if (!PL_curcop->cop_hints_hash)
return &PL_core_reg_engine;
ptr = cop_hints_fetch_pvs(PL_curcop, "regcomp", 0);
if ( !(ptr && SvIOK(ptr) && SvIV(ptr)))
return &PL_core_reg_engine;
return INT2PTR(regexp_engine*, SvIV(ptr));
}
}
REGEXP *
Perl_pregcomp(pTHX_ SV * const pattern, const U32 flags)
{
regexp_engine const *eng = current_re_engine();
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_PREGCOMP;
/* Dispatch a request to compile a regexp to correct regexp engine. */
DEBUG_COMPILE_r({
Perl_re_printf( aTHX_ "Using engine %" UVxf "\n",
PTR2UV(eng));
});
return CALLREGCOMP_ENG(eng, pattern, flags);
}
#endif
/* public(ish) entry point for the perl core's own regex compiling code.
* It's actually a wrapper for Perl_re_op_compile that only takes an SV
* pattern rather than a list of OPs, and uses the internal engine rather
* than the current one */
REGEXP *
Perl_re_compile(pTHX_ SV * const pattern, U32 rx_flags)
{
SV *pat = pattern; /* defeat constness! */
PERL_ARGS_ASSERT_RE_COMPILE;
return Perl_re_op_compile(aTHX_ &pat, 1, NULL,
#ifdef PERL_IN_XSUB_RE
&my_reg_engine,
#else
&PL_core_reg_engine,
#endif
NULL, NULL, rx_flags, 0);
}
static void
S_free_codeblocks(pTHX_ struct reg_code_blocks *cbs)
{
int n;
if (--cbs->refcnt > 0)
return;
for (n = 0; n < cbs->count; n++) {
REGEXP *rx = cbs->cb[n].src_regex;
if (rx) {
cbs->cb[n].src_regex = NULL;
SvREFCNT_dec_NN(rx);
}
}
Safefree(cbs->cb);
Safefree(cbs);
}
static struct reg_code_blocks *
S_alloc_code_blocks(pTHX_ int ncode)
{
struct reg_code_blocks *cbs;
Newx(cbs, 1, struct reg_code_blocks);
cbs->count = ncode;
cbs->refcnt = 1;
SAVEDESTRUCTOR_X(S_free_codeblocks, cbs);
if (ncode)
Newx(cbs->cb, ncode, struct reg_code_block);
else
cbs->cb = NULL;
return cbs;
}
/* upgrade pattern pat_p of length plen_p to UTF8, and if there are code
* blocks, recalculate the indices. Update pat_p and plen_p in-place to
* point to the realloced string and length.
*
* This is essentially a copy of Perl_bytes_to_utf8() with the code index
* stuff added */
static void
S_pat_upgrade_to_utf8(pTHX_ RExC_state_t * const pRExC_state,
char **pat_p, STRLEN *plen_p, int num_code_blocks)
{
U8 *const src = (U8*)*pat_p;
U8 *dst, *d;
int n=0;
STRLEN s = 0;
bool do_end = 0;
GET_RE_DEBUG_FLAGS_DECL;
DEBUG_PARSE_r(Perl_re_printf( aTHX_
"UTF8 mismatch! Converting to utf8 for resizing and compile\n"));
/* 1 for each byte + 1 for each byte that expands to two, + trailing NUL */
Newx(dst, *plen_p + variant_under_utf8_count(src, src + *plen_p) + 1, U8);
d = dst;
while (s < *plen_p) {
append_utf8_from_native_byte(src[s], &d);
if (n < num_code_blocks) {
assert(pRExC_state->code_blocks);
if (!do_end && pRExC_state->code_blocks->cb[n].start == s) {
pRExC_state->code_blocks->cb[n].start = d - dst - 1;
assert(*(d - 1) == '(');
do_end = 1;
}
else if (do_end && pRExC_state->code_blocks->cb[n].end == s) {
pRExC_state->code_blocks->cb[n].end = d - dst - 1;
assert(*(d - 1) == ')');
do_end = 0;
n++;
}
}
s++;
}
*d = '\0';
*plen_p = d - dst;
*pat_p = (char*) dst;
SAVEFREEPV(*pat_p);
RExC_orig_utf8 = RExC_utf8 = 1;
}
/* S_concat_pat(): concatenate a list of args to the pattern string pat,
* while recording any code block indices, and handling overloading,
* nested qr// objects etc. If pat is null, it will allocate a new
* string, or just return the first arg, if there's only one.
*
* Returns the malloced/updated pat.
* patternp and pat_count is the array of SVs to be concatted;
* oplist is the optional list of ops that generated the SVs;
* recompile_p is a pointer to a boolean that will be set if
* the regex will need to be recompiled.
* delim, if non-null is an SV that will be inserted between each element
*/
static SV*
S_concat_pat(pTHX_ RExC_state_t * const pRExC_state,
SV *pat, SV ** const patternp, int pat_count,
OP *oplist, bool *recompile_p, SV *delim)
{
SV **svp;
int n = 0;
bool use_delim = FALSE;
bool alloced = FALSE;
/* if we know we have at least two args, create an empty string,
* then concatenate args to that. For no args, return an empty string */
if (!pat && pat_count != 1) {
pat = newSVpvs("");
SAVEFREESV(pat);
alloced = TRUE;
}
for (svp = patternp; svp < patternp + pat_count; svp++) {
SV *sv;
SV *rx = NULL;
STRLEN orig_patlen = 0;
bool code = 0;
SV *msv = use_delim ? delim : *svp;
if (!msv) msv = &PL_sv_undef;
/* if we've got a delimiter, we go round the loop twice for each
* svp slot (except the last), using the delimiter the second
* time round */
if (use_delim) {
svp--;
use_delim = FALSE;
}
else if (delim)
use_delim = TRUE;
if (SvTYPE(msv) == SVt_PVAV) {
/* we've encountered an interpolated array within
* the pattern, e.g. /...@a..../. Expand the list of elements,
* then recursively append elements.
* The code in this block is based on S_pushav() */
AV *const av = (AV*)msv;
const SSize_t maxarg = AvFILL(av) + 1;
SV **array;
if (oplist) {
assert(oplist->op_type == OP_PADAV
|| oplist->op_type == OP_RV2AV);
oplist = OpSIBLING(oplist);
}
if (SvRMAGICAL(av)) {
SSize_t i;
Newx(array, maxarg, SV*);
SAVEFREEPV(array);
for (i=0; i < maxarg; i++) {
SV ** const svp = av_fetch(av, i, FALSE);
array[i] = svp ? *svp : &PL_sv_undef;
}
}
else
array = AvARRAY(av);
pat = S_concat_pat(aTHX_ pRExC_state, pat,
array, maxarg, NULL, recompile_p,
/* $" */
GvSV((gv_fetchpvs("\"", GV_ADDMULTI, SVt_PV))));
continue;
}
/* we make the assumption here that each op in the list of
* op_siblings maps to one SV pushed onto the stack,
* except for code blocks, with have both an OP_NULL and
* and OP_CONST.
* This allows us to match up the list of SVs against the
* list of OPs to find the next code block.
*
* Note that PUSHMARK PADSV PADSV ..
* is optimised to
* PADRANGE PADSV PADSV ..
* so the alignment still works. */
if (oplist) {
if (oplist->op_type == OP_NULL
&& (oplist->op_flags & OPf_SPECIAL))
{
assert(n < pRExC_state->code_blocks->count);
pRExC_state->code_blocks->cb[n].start = pat ? SvCUR(pat) : 0;
pRExC_state->code_blocks->cb[n].block = oplist;
pRExC_state->code_blocks->cb[n].src_regex = NULL;
n++;
code = 1;
oplist = OpSIBLING(oplist); /* skip CONST */
assert(oplist);
}
oplist = OpSIBLING(oplist);;
}
/* apply magic and QR overloading to arg */
SvGETMAGIC(msv);
if (SvROK(msv) && SvAMAGIC(msv)) {
SV *sv = AMG_CALLunary(msv, regexp_amg);
if (sv) {
if (SvROK(sv))
sv = SvRV(sv);
if (SvTYPE(sv) != SVt_REGEXP)
Perl_croak(aTHX_ "Overloaded qr did not return a REGEXP");
msv = sv;
}
}
/* try concatenation overload ... */
if (pat && (SvAMAGIC(pat) || SvAMAGIC(msv)) &&
(sv = amagic_call(pat, msv, concat_amg, AMGf_assign)))
{
sv_setsv(pat, sv);
/* overloading involved: all bets are off over literal
* code. Pretend we haven't seen it */
if (n)
pRExC_state->code_blocks->count -= n;
n = 0;
}
else {
/* ... or failing that, try "" overload */
while (SvAMAGIC(msv)
&& (sv = AMG_CALLunary(msv, string_amg))
&& sv != msv
&& !( SvROK(msv)
&& SvROK(sv)
&& SvRV(msv) == SvRV(sv))
) {
msv = sv;
SvGETMAGIC(msv);
}
if (SvROK(msv) && SvTYPE(SvRV(msv)) == SVt_REGEXP)
msv = SvRV(msv);
if (pat) {
/* this is a partially unrolled
* sv_catsv_nomg(pat, msv);
* that allows us to adjust code block indices if
* needed */
STRLEN dlen;
char *dst = SvPV_force_nomg(pat, dlen);
orig_patlen = dlen;
if (SvUTF8(msv) && !SvUTF8(pat)) {
S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &dst, &dlen, n);
sv_setpvn(pat, dst, dlen);
SvUTF8_on(pat);
}
sv_catsv_nomg(pat, msv);
rx = msv;
}
else {
/* We have only one SV to process, but we need to verify
* it is properly null terminated or we will fail asserts
* later. In theory we probably shouldn't get such SV's,
* but if we do we should handle it gracefully. */
if ( SvTYPE(msv) != SVt_PV || (SvLEN(msv) > SvCUR(msv) && *(SvEND(msv)) == 0) || SvIsCOW_shared_hash(msv) ) {
/* not a string, or a string with a trailing null */
pat = msv;
} else {
/* a string with no trailing null, we need to copy it
* so it has a trailing null */
pat = sv_2mortal(newSVsv(msv));
}
}
if (code)
pRExC_state->code_blocks->cb[n-1].end = SvCUR(pat)-1;
}
/* extract any code blocks within any embedded qr//'s */
if (rx && SvTYPE(rx) == SVt_REGEXP
&& RX_ENGINE((REGEXP*)rx)->op_comp)
{
RXi_GET_DECL(ReANY((REGEXP *)rx), ri);
if (ri->code_blocks && ri->code_blocks->count) {
int i;
/* the presence of an embedded qr// with code means
* we should always recompile: the text of the
* qr// may not have changed, but it may be a
* different closure than last time */
*recompile_p = 1;
if (pRExC_state->code_blocks) {
int new_count = pRExC_state->code_blocks->count
+ ri->code_blocks->count;
Renew(pRExC_state->code_blocks->cb,
new_count, struct reg_code_block);
pRExC_state->code_blocks->count = new_count;
}
else
pRExC_state->code_blocks = S_alloc_code_blocks(aTHX_
ri->code_blocks->count);
for (i=0; i < ri->code_blocks->count; i++) {
struct reg_code_block *src, *dst;
STRLEN offset = orig_patlen
+ ReANY((REGEXP *)rx)->pre_prefix;
assert(n < pRExC_state->code_blocks->count);
src = &ri->code_blocks->cb[i];
dst = &pRExC_state->code_blocks->cb[n];
dst->start = src->start + offset;
dst->end = src->end + offset;
dst->block = src->block;
dst->src_regex = (REGEXP*) SvREFCNT_inc( (SV*)
src->src_regex
? src->src_regex
: (REGEXP*)rx);
n++;
}
}
}
}
/* avoid calling magic multiple times on a single element e.g. =~ $qr */
if (alloced)
SvSETMAGIC(pat);
return pat;
}
/* see if there are any run-time code blocks in the pattern.
* False positives are allowed */
static bool
S_has_runtime_code(pTHX_ RExC_state_t * const pRExC_state,
char *pat, STRLEN plen)
{
int n = 0;
STRLEN s;
PERL_UNUSED_CONTEXT;
for (s = 0; s < plen; s++) {
if ( pRExC_state->code_blocks
&& n < pRExC_state->code_blocks->count
&& s == pRExC_state->code_blocks->cb[n].start)
{
s = pRExC_state->code_blocks->cb[n].end;
n++;
continue;
}
/* TODO ideally should handle [..], (#..), /#.../x to reduce false
* positives here */
if (pat[s] == '(' && s+2 <= plen && pat[s+1] == '?' &&
(pat[s+2] == '{'
|| (s + 2 <= plen && pat[s+2] == '?' && pat[s+3] == '{'))
)
return 1;
}
return 0;
}
/* Handle run-time code blocks. We will already have compiled any direct
* or indirect literal code blocks. Now, take the pattern 'pat' and make a
* copy of it, but with any literal code blocks blanked out and
* appropriate chars escaped; then feed it into
*
* eval "qr'modified_pattern'"
*
* For example,
*
* a\bc(?{"this was literal"})def'ghi\\jkl(?{"this is runtime"})mno
*
* becomes
*
* qr'a\\bc_______________________def\'ghi\\\\jkl(?{"this is runtime"})mno'
*
* After eval_sv()-ing that, grab any new code blocks from the returned qr
* and merge them with any code blocks of the original regexp.
*
* If the pat is non-UTF8, while the evalled qr is UTF8, don't merge;
* instead, just save the qr and return FALSE; this tells our caller that
* the original pattern needs upgrading to utf8.
*/
static bool
S_compile_runtime_code(pTHX_ RExC_state_t * const pRExC_state,
char *pat, STRLEN plen)
{
SV *qr;
GET_RE_DEBUG_FLAGS_DECL;
if (pRExC_state->runtime_code_qr) {
/* this is the second time we've been called; this should
* only happen if the main pattern got upgraded to utf8
* during compilation; re-use the qr we compiled first time
* round (which should be utf8 too)
*/
qr = pRExC_state->runtime_code_qr;
pRExC_state->runtime_code_qr = NULL;
assert(RExC_utf8 && SvUTF8(qr));
}
else {
int n = 0;
STRLEN s;
char *p, *newpat;
int newlen = plen + 7; /* allow for "qr''xx\0" extra chars */
SV *sv, *qr_ref;
dSP;
/* determine how many extra chars we need for ' and \ escaping */
for (s = 0; s < plen; s++) {
if (pat[s] == '\'' || pat[s] == '\\')
newlen++;
}
Newx(newpat, newlen, char);
p = newpat;
*p++ = 'q'; *p++ = 'r'; *p++ = '\'';
for (s = 0; s < plen; s++) {
if ( pRExC_state->code_blocks
&& n < pRExC_state->code_blocks->count
&& s == pRExC_state->code_blocks->cb[n].start)
{
/* blank out literal code block so that they aren't
* recompiled: eg change from/to:
* /(?{xyz})/
* /(?=====)/
* and
* /(??{xyz})/
* /(?======)/
* and
* /(?(?{xyz}))/
* /(?(?=====))/
*/
assert(pat[s] == '(');
assert(pat[s+1] == '?');
*p++ = '(';
*p++ = '?';
s += 2;
while (s < pRExC_state->code_blocks->cb[n].end) {
*p++ = '=';
s++;
}
*p++ = ')';
n++;
continue;
}
if (pat[s] == '\'' || pat[s] == '\\')
*p++ = '\\';
*p++ = pat[s];
}
*p++ = '\'';
if (pRExC_state->pm_flags & RXf_PMf_EXTENDED) {
*p++ = 'x';
if (pRExC_state->pm_flags & RXf_PMf_EXTENDED_MORE) {
*p++ = 'x';
}
}
*p++ = '\0';
DEBUG_COMPILE_r({
Perl_re_printf( aTHX_
"%sre-parsing pattern for runtime code:%s %s\n",
PL_colors[4], PL_colors[5], newpat);
});
sv = newSVpvn_flags(newpat, p-newpat-1, RExC_utf8 ? SVf_UTF8 : 0);
Safefree(newpat);
ENTER;
SAVETMPS;
save_re_context();
PUSHSTACKi(PERLSI_REQUIRE);
/* G_RE_REPARSING causes the toker to collapse \\ into \ when
* parsing qr''; normally only q'' does this. It also alters
* hints handling */
eval_sv(sv, G_SCALAR|G_RE_REPARSING);
SvREFCNT_dec_NN(sv);
SPAGAIN;
qr_ref = POPs;
PUTBACK;
{
SV * const errsv = ERRSV;
if (SvTRUE_NN(errsv))
/* use croak_sv ? */
Perl_croak_nocontext("%" SVf, SVfARG(errsv));
}
assert(SvROK(qr_ref));
qr = SvRV(qr_ref);
assert(SvTYPE(qr) == SVt_REGEXP && RX_ENGINE((REGEXP*)qr)->op_comp);
/* the leaving below frees the tmp qr_ref.
* Give qr a life of its own */
SvREFCNT_inc(qr);
POPSTACK;
FREETMPS;
LEAVE;
}
if (!RExC_utf8 && SvUTF8(qr)) {
/* first time through; the pattern got upgraded; save the
* qr for the next time through */
assert(!pRExC_state->runtime_code_qr);
pRExC_state->runtime_code_qr = qr;
return 0;
}
/* extract any code blocks within the returned qr// */
/* merge the main (r1) and run-time (r2) code blocks into one */
{
RXi_GET_DECL(ReANY((REGEXP *)qr), r2);
struct reg_code_block *new_block, *dst;
RExC_state_t * const r1 = pRExC_state; /* convenient alias */
int i1 = 0, i2 = 0;
int r1c, r2c;
if (!r2->code_blocks || !r2->code_blocks->count) /* we guessed wrong */
{
SvREFCNT_dec_NN(qr);
return 1;
}
if (!r1->code_blocks)
r1->code_blocks = S_alloc_code_blocks(aTHX_ 0);
r1c = r1->code_blocks->count;
r2c = r2->code_blocks->count;
Newx(new_block, r1c + r2c, struct reg_code_block);
dst = new_block;
while (i1 < r1c || i2 < r2c) {
struct reg_code_block *src;
bool is_qr = 0;
if (i1 == r1c) {
src = &r2->code_blocks->cb[i2++];
is_qr = 1;
}
else if (i2 == r2c)
src = &r1->code_blocks->cb[i1++];
else if ( r1->code_blocks->cb[i1].start
< r2->code_blocks->cb[i2].start)
{
src = &r1->code_blocks->cb[i1++];
assert(src->end < r2->code_blocks->cb[i2].start);
}
else {
assert( r1->code_blocks->cb[i1].start
> r2->code_blocks->cb[i2].start);
src = &r2->code_blocks->cb[i2++];
is_qr = 1;
assert(src->end < r1->code_blocks->cb[i1].start);
}
assert(pat[src->start] == '(');
assert(pat[src->end] == ')');
dst->start = src->start;
dst->end = src->end;
dst->block = src->block;
dst->src_regex = is_qr ? (REGEXP*) SvREFCNT_inc( (SV*) qr)
: src->src_regex;
dst++;
}
r1->code_blocks->count += r2c;
Safefree(r1->code_blocks->cb);
r1->code_blocks->cb = new_block;
}
SvREFCNT_dec_NN(qr);
return 1;
}
STATIC bool
S_setup_longest(pTHX_ RExC_state_t *pRExC_state,
struct reg_substr_datum *rsd,
struct scan_data_substrs *sub,
STRLEN longest_length)
{
/* This is the common code for setting up the floating and fixed length
* string data extracted from Perl_re_op_compile() below. Returns a boolean
* as to whether succeeded or not */
I32 t;
SSize_t ml;
bool eol = cBOOL(sub->flags & SF_BEFORE_EOL);
bool meol = cBOOL(sub->flags & SF_BEFORE_MEOL);
if (! (longest_length
|| (eol /* Can't have SEOL and MULTI */
&& (! meol || (RExC_flags & RXf_PMf_MULTILINE)))
)
/* See comments for join_exact for why REG_UNFOLDED_MULTI_SEEN */
|| (RExC_seen & REG_UNFOLDED_MULTI_SEEN))
{
return FALSE;
}
/* copy the information about the longest from the reg_scan_data
over to the program. */
if (SvUTF8(sub->str)) {
rsd->substr = NULL;
rsd->utf8_substr = sub->str;
} else {
rsd->substr = sub->str;
rsd->utf8_substr = NULL;
}
/* end_shift is how many chars that must be matched that
follow this item. We calculate it ahead of time as once the
lookbehind offset is added in we lose the ability to correctly
calculate it.*/
ml = sub->minlenp ? *(sub->minlenp) : (SSize_t)longest_length;
rsd->end_shift = ml - sub->min_offset
- longest_length
/* XXX SvTAIL is always false here - did you mean FBMcf_TAIL
* intead? - DAPM
+ (SvTAIL(sub->str) != 0)
*/
+ sub->lookbehind;
t = (eol/* Can't have SEOL and MULTI */
&& (! meol || (RExC_flags & RXf_PMf_MULTILINE)));
fbm_compile(sub->str, t ? FBMcf_TAIL : 0);
return TRUE;
}
STATIC void
S_set_regex_pv(pTHX_ RExC_state_t *pRExC_state, REGEXP *Rx)
{
/* Calculates and sets in the compiled pattern 'Rx' the string to compile,
* properly wrapped with the right modifiers */
bool has_p = ((RExC_rx->extflags & RXf_PMf_KEEPCOPY) == RXf_PMf_KEEPCOPY);
bool has_charset = RExC_utf8 || (get_regex_charset(RExC_rx->extflags)
!= REGEX_DEPENDS_CHARSET);
/* The caret is output if there are any defaults: if not all the STD
* flags are set, or if no character set specifier is needed */
bool has_default =
(((RExC_rx->extflags & RXf_PMf_STD_PMMOD) != RXf_PMf_STD_PMMOD)
|| ! has_charset);
bool has_runon = ((RExC_seen & REG_RUN_ON_COMMENT_SEEN)
== REG_RUN_ON_COMMENT_SEEN);
U8 reganch = (U8)((RExC_rx->extflags & RXf_PMf_STD_PMMOD)
>> RXf_PMf_STD_PMMOD_SHIFT);
const char *fptr = STD_PAT_MODS; /*"msixxn"*/
char *p;
STRLEN pat_len = RExC_precomp_end - RExC_precomp;
/* We output all the necessary flags; we never output a minus, as all
* those are defaults, so are
* covered by the caret */
const STRLEN wraplen = pat_len + has_p + has_runon
+ has_default /* If needs a caret */
+ PL_bitcount[reganch] /* 1 char for each set standard flag */
/* If needs a character set specifier */
+ ((has_charset) ? MAX_CHARSET_NAME_LENGTH : 0)
+ (sizeof("(?:)") - 1);
PERL_ARGS_ASSERT_SET_REGEX_PV;
/* make sure PL_bitcount bounds not exceeded */
assert(sizeof(STD_PAT_MODS) <= 8);
p = sv_grow(MUTABLE_SV(Rx), wraplen + 1); /* +1 for the ending NUL */
SvPOK_on(Rx);
if (RExC_utf8)
SvFLAGS(Rx) |= SVf_UTF8;
*p++='('; *p++='?';
/* If a default, cover it using the caret */
if (has_default) {
*p++= DEFAULT_PAT_MOD;
}
if (has_charset) {
STRLEN len;
const char* name;
name = get_regex_charset_name(RExC_rx->extflags, &len);
if strEQ(name, DEPENDS_PAT_MODS) { /* /d under UTF-8 => /u */
assert(RExC_utf8);
name = UNICODE_PAT_MODS;
len = sizeof(UNICODE_PAT_MODS) - 1;
}
Copy(name, p, len, char);
p += len;
}
if (has_p)
*p++ = KEEPCOPY_PAT_MOD; /*'p'*/
{
char ch;
while((ch = *fptr++)) {
if(reganch & 1)
*p++ = ch;
reganch >>= 1;
}
}
*p++ = ':';
Copy(RExC_precomp, p, pat_len, char);
assert ((RX_WRAPPED(Rx) - p) < 16);
RExC_rx->pre_prefix = p - RX_WRAPPED(Rx);
p += pat_len;
/* Adding a trailing \n causes this to compile properly:
my $R = qr / A B C # D E/x; /($R)/
Otherwise the parens are considered part of the comment */
if (has_runon)
*p++ = '\n';
*p++ = ')';
*p = 0;
SvCUR_set(Rx, p - RX_WRAPPED(Rx));
}
/*
* Perl_re_op_compile - the perl internal RE engine's function to compile a
* regular expression into internal code.
* The pattern may be passed either as:
* a list of SVs (patternp plus pat_count)
* a list of OPs (expr)
* If both are passed, the SV list is used, but the OP list indicates
* which SVs are actually pre-compiled code blocks
*
* The SVs in the list have magic and qr overloading applied to them (and
* the list may be modified in-place with replacement SVs in the latter
* case).
*
* If the pattern hasn't changed from old_re, then old_re will be
* returned.
*
* eng is the current engine. If that engine has an op_comp method, then
* handle directly (i.e. we assume that op_comp was us); otherwise, just
* do the initial concatenation of arguments and pass on to the external
* engine.
*
* If is_bare_re is not null, set it to a boolean indicating whether the
* arg list reduced (after overloading) to a single bare regex which has
* been returned (i.e. /$qr/).
*
* orig_rx_flags contains RXf_* flags. See perlreapi.pod for more details.
*
* pm_flags contains the PMf_* flags, typically based on those from the
* pm_flags field of the related PMOP. Currently we're only interested in
* PMf_HAS_CV, PMf_IS_QR, PMf_USE_RE_EVAL.
*
* For many years this code had an initial sizing pass that calculated
* (sometimes incorrectly, leading to security holes) the size needed for the
* compiled pattern. That was changed by commit
* 7c932d07cab18751bfc7515b4320436273a459e2 in 5.29, which reallocs the size, a
* node at a time, as parsing goes along. Patches welcome to fix any obsolete
* references to this sizing pass.
*
* Now, an initial crude guess as to the size needed is made, based on the
* length of the pattern. Patches welcome to improve that guess. That amount
* of space is malloc'd and then immediately freed, and then clawed back node
* by node. This design is to minimze, to the extent possible, memory churn
* when doing the the reallocs.
*
* A separate parentheses counting pass may be needed in some cases.
* (Previously the sizing pass did this.) Patches welcome to reduce the number
* of these cases.
*
* The existence of a sizing pass necessitated design decisions that are no
* longer needed. There are potential areas of simplification.
*
* Beware that the optimization-preparation code in here knows about some
* of the structure of the compiled regexp. [I'll say.]
*/
REGEXP *
Perl_re_op_compile(pTHX_ SV ** const patternp, int pat_count,
OP *expr, const regexp_engine* eng, REGEXP *old_re,
bool *is_bare_re, const U32 orig_rx_flags, const U32 pm_flags)
{
dVAR;
REGEXP *Rx; /* Capital 'R' means points to a REGEXP */
STRLEN plen;
char *exp;
regnode *scan;
I32 flags;
SSize_t minlen = 0;
U32 rx_flags;
SV *pat;
SV** new_patternp = patternp;
/* these are all flags - maybe they should be turned
* into a single int with different bit masks */
I32 sawlookahead = 0;
I32 sawplus = 0;
I32 sawopen = 0;
I32 sawminmod = 0;
regex_charset initial_charset = get_regex_charset(orig_rx_flags);
bool recompile = 0;
bool runtime_code = 0;
scan_data_t data;
RExC_state_t RExC_state;
RExC_state_t * const pRExC_state = &RExC_state;
#ifdef TRIE_STUDY_OPT
int restudied = 0;
RExC_state_t copyRExC_state;
#endif
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_RE_OP_COMPILE;
DEBUG_r(if (!PL_colorset) reginitcolors());
/* Initialize these here instead of as-needed, as is quick and avoids
* having to test them each time otherwise */
if (! PL_InBitmap) {
#ifdef DEBUGGING
char * dump_len_string;
#endif
/* This is calculated here, because the Perl program that generates the
* static global ones doesn't currently have access to
* NUM_ANYOF_CODE_POINTS */
PL_InBitmap = _new_invlist(2);
PL_InBitmap = _add_range_to_invlist(PL_InBitmap, 0,
NUM_ANYOF_CODE_POINTS - 1);
#ifdef DEBUGGING
dump_len_string = PerlEnv_getenv("PERL_DUMP_RE_MAX_LEN");
if ( ! dump_len_string
|| ! grok_atoUV(dump_len_string, (UV *)&PL_dump_re_max_len, NULL))
{
PL_dump_re_max_len = 60; /* A reasonable default */
}
#endif
}
pRExC_state->warn_text = NULL;
pRExC_state->unlexed_names = NULL;
pRExC_state->code_blocks = NULL;
if (is_bare_re)
*is_bare_re = FALSE;
if (expr && (expr->op_type == OP_LIST ||
(expr->op_type == OP_NULL && expr->op_targ == OP_LIST))) {
/* allocate code_blocks if needed */
OP *o;
int ncode = 0;
for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o))
if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL))
ncode++; /* count of DO blocks */
if (ncode)
pRExC_state->code_blocks = S_alloc_code_blocks(aTHX_ ncode);
}
if (!pat_count) {
/* compile-time pattern with just OP_CONSTs and DO blocks */
int n;
OP *o;
/* find how many CONSTs there are */
assert(expr);
n = 0;
if (expr->op_type == OP_CONST)
n = 1;
else
for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
if (o->op_type == OP_CONST)
n++;
}
/* fake up an SV array */
assert(!new_patternp);
Newx(new_patternp, n, SV*);
SAVEFREEPV(new_patternp);
pat_count = n;
n = 0;
if (expr->op_type == OP_CONST)
new_patternp[n] = cSVOPx_sv(expr);
else
for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
if (o->op_type == OP_CONST)
new_patternp[n++] = cSVOPo_sv;
}
}
DEBUG_PARSE_r(Perl_re_printf( aTHX_
"Assembling pattern from %d elements%s\n", pat_count,
orig_rx_flags & RXf_SPLIT ? " for split" : ""));
/* set expr to the first arg op */
if (pRExC_state->code_blocks && pRExC_state->code_blocks->count
&& expr->op_type != OP_CONST)
{
expr = cLISTOPx(expr)->op_first;
assert( expr->op_type == OP_PUSHMARK
|| (expr->op_type == OP_NULL && expr->op_targ == OP_PUSHMARK)
|| expr->op_type == OP_PADRANGE);
expr = OpSIBLING(expr);
}
pat = S_concat_pat(aTHX_ pRExC_state, NULL, new_patternp, pat_count,
expr, &recompile, NULL);
/* handle bare (possibly after overloading) regex: foo =~ $re */
{
SV *re = pat;
if (SvROK(re))
re = SvRV(re);
if (SvTYPE(re) == SVt_REGEXP) {
if (is_bare_re)
*is_bare_re = TRUE;
SvREFCNT_inc(re);
DEBUG_PARSE_r(Perl_re_printf( aTHX_
"Precompiled pattern%s\n",
orig_rx_flags & RXf_SPLIT ? " for split" : ""));
return (REGEXP*)re;
}
}
exp = SvPV_nomg(pat, plen);
if (!eng->op_comp) {
if ((SvUTF8(pat) && IN_BYTES)
|| SvGMAGICAL(pat) || SvAMAGIC(pat))
{
/* make a temporary copy; either to convert to bytes,
* or to avoid repeating get-magic / overloaded stringify */
pat = newSVpvn_flags(exp, plen, SVs_TEMP |
(IN_BYTES ? 0 : SvUTF8(pat)));
}
return CALLREGCOMP_ENG(eng, pat, orig_rx_flags);
}
/* ignore the utf8ness if the pattern is 0 length */
RExC_utf8 = RExC_orig_utf8 = (plen == 0 || IN_BYTES) ? 0 : SvUTF8(pat);
RExC_uni_semantics = 0;
RExC_contains_locale = 0;
RExC_strict = cBOOL(pm_flags & RXf_PMf_STRICT);
RExC_in_script_run = 0;
RExC_study_started = 0;
pRExC_state->runtime_code_qr = NULL;
RExC_frame_head= NULL;
RExC_frame_last= NULL;
RExC_frame_count= 0;
RExC_latest_warn_offset = 0;
RExC_use_BRANCHJ = 0;
RExC_total_parens = 0;
RExC_open_parens = NULL;
RExC_close_parens = NULL;
RExC_paren_names = NULL;
RExC_size = 0;
RExC_seen_d_op = FALSE;
#ifdef DEBUGGING
RExC_paren_name_list = NULL;
#endif
DEBUG_r({
RExC_mysv1= sv_newmortal();
RExC_mysv2= sv_newmortal();
});
DEBUG_COMPILE_r({
SV *dsv= sv_newmortal();
RE_PV_QUOTED_DECL(s, RExC_utf8, dsv, exp, plen, PL_dump_re_max_len);
Perl_re_printf( aTHX_ "%sCompiling REx%s %s\n",
PL_colors[4], PL_colors[5], s);
});
/* we jump here if we have to recompile, e.g., from upgrading the pattern
* to utf8 */
if ((pm_flags & PMf_USE_RE_EVAL)
/* this second condition covers the non-regex literal case,
* i.e. $foo =~ '(?{})'. */
|| (IN_PERL_COMPILETIME && (PL_hints & HINT_RE_EVAL))
)
runtime_code = S_has_runtime_code(aTHX_ pRExC_state, exp, plen);
redo_parse:
/* return old regex if pattern hasn't changed */
/* XXX: note in the below we have to check the flags as well as the
* pattern.
*
* Things get a touch tricky as we have to compare the utf8 flag
* independently from the compile flags. */
if ( old_re
&& !recompile
&& !!RX_UTF8(old_re) == !!RExC_utf8
&& ( RX_COMPFLAGS(old_re) == ( orig_rx_flags & RXf_PMf_FLAGCOPYMASK ) )
&& RX_PRECOMP(old_re)
&& RX_PRELEN(old_re) == plen
&& memEQ(RX_PRECOMP(old_re), exp, plen)
&& !runtime_code /* with runtime code, always recompile */ )
{
return old_re;
}
/* Allocate the pattern's SV */
RExC_rx_sv = Rx = (REGEXP*) newSV_type(SVt_REGEXP);
RExC_rx = ReANY(Rx);
if ( RExC_rx == NULL )
FAIL("Regexp out of space");
rx_flags = orig_rx_flags;
if ( (UTF || RExC_uni_semantics)
&& initial_charset == REGEX_DEPENDS_CHARSET)
{
/* Set to use unicode semantics if the pattern is in utf8 and has the
* 'depends' charset specified, as it means unicode when utf8 */
set_regex_charset(&rx_flags, REGEX_UNICODE_CHARSET);
RExC_uni_semantics = 1;
}
RExC_pm_flags = pm_flags;
if (runtime_code) {
assert(TAINTING_get || !TAINT_get);
if (TAINT_get)
Perl_croak(aTHX_ "Eval-group in insecure regular expression");
if (!S_compile_runtime_code(aTHX_ pRExC_state, exp, plen)) {
/* whoops, we have a non-utf8 pattern, whilst run-time code
* got compiled as utf8. Try again with a utf8 pattern */
S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen,
pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0);
goto redo_parse;
}
}
assert(!pRExC_state->runtime_code_qr);
RExC_sawback = 0;
RExC_seen = 0;
RExC_maxlen = 0;
RExC_in_lookbehind = 0;
RExC_seen_zerolen = *exp == '^' ? -1 : 0;
#ifdef EBCDIC
RExC_recode_x_to_native = 0;
#endif
RExC_in_multi_char_class = 0;
RExC_start = RExC_copy_start_in_constructed = RExC_copy_start_in_input = RExC_precomp = exp;
RExC_precomp_end = RExC_end = exp + plen;
RExC_nestroot = 0;
RExC_whilem_seen = 0;
RExC_end_op = NULL;
RExC_recurse = NULL;
RExC_study_chunk_recursed = NULL;
RExC_study_chunk_recursed_bytes= 0;
RExC_recurse_count = 0;
pRExC_state->code_index = 0;
/* Initialize the string in the compiled pattern. This is so that there is
* something to output if necessary */
set_regex_pv(pRExC_state, Rx);
DEBUG_PARSE_r({
Perl_re_printf( aTHX_
"Starting parse and generation\n");
RExC_lastnum=0;
RExC_lastparse=NULL;
});
/* Allocate space and zero-initialize. Note, the two step process
of zeroing when in debug mode, thus anything assigned has to
happen after that */
if (! RExC_size) {
/* On the first pass of the parse, we guess how big this will be. Then
* we grow in one operation to that amount and then give it back. As
* we go along, we re-allocate what we need.
*
* XXX Currently the guess is essentially that the pattern will be an
* EXACT node with one byte input, one byte output. This is crude, and
* better heuristics are welcome.
*
* On any subsequent passes, we guess what we actually computed in the
* latest earlier pass. Such a pass probably didn't complete so is
* missing stuff. We could improve those guesses by knowing where the
* parse stopped, and use the length so far plus apply the above
* assumption to what's left. */
RExC_size = STR_SZ(RExC_end - RExC_start);
}
Newxc(RExC_rxi, sizeof(regexp_internal) + RExC_size, char, regexp_internal);
if ( RExC_rxi == NULL )
FAIL("Regexp out of space");
Zero(RExC_rxi, sizeof(regexp_internal) + RExC_size, char);
RXi_SET( RExC_rx, RExC_rxi );
/* We start from 0 (over from 0 in the case this is a reparse. The first
* node parsed will give back any excess memory we have allocated so far).
* */
RExC_size = 0;
/* non-zero initialization begins here */
RExC_rx->engine= eng;
RExC_rx->extflags = rx_flags;
RXp_COMPFLAGS(RExC_rx) = orig_rx_flags & RXf_PMf_FLAGCOPYMASK;
if (pm_flags & PMf_IS_QR) {
RExC_rxi->code_blocks = pRExC_state->code_blocks;
if (RExC_rxi->code_blocks) {
RExC_rxi->code_blocks->refcnt++;
}
}
RExC_rx->intflags = 0;
RExC_flags = rx_flags; /* don't let top level (?i) bleed */
RExC_parse = exp;
/* This NUL is guaranteed because the pattern comes from an SV*, and the sv
* code makes sure the final byte is an uncounted NUL. But should this
* ever not be the case, lots of things could read beyond the end of the
* buffer: loops like
* while(isFOO(*RExC_parse)) RExC_parse++;
* strchr(RExC_parse, "foo");
* etc. So it is worth noting. */
assert(*RExC_end == '\0');
RExC_naughty = 0;
RExC_npar = 1;
RExC_parens_buf_size = 0;
RExC_emit_start = RExC_rxi->program;
pRExC_state->code_index = 0;
*((char*) RExC_emit_start) = (char) REG_MAGIC;
RExC_emit = 1;
/* Do the parse */
if (reg(pRExC_state, 0, &flags, 1)) {
/* Success!, But we may need to redo the parse knowing how many parens
* there actually are */
if (IN_PARENS_PASS) {
flags |= RESTART_PARSE;
}
/* We have that number in RExC_npar */
RExC_total_parens = RExC_npar;
}
else if (! MUST_RESTART(flags)) {
ReREFCNT_dec(Rx);
Perl_croak(aTHX_ "panic: reg returned failure to re_op_compile, flags=%#" UVxf, (UV) flags);
}
/* Here, we either have success, or we have to redo the parse for some reason */
if (MUST_RESTART(flags)) {
/* It's possible to write a regexp in ascii that represents Unicode
codepoints outside of the byte range, such as via \x{100}. If we
detect such a sequence we have to convert the entire pattern to utf8
and then recompile, as our sizing calculation will have been based
on 1 byte == 1 character, but we will need to use utf8 to encode
at least some part of the pattern, and therefore must convert the whole
thing.
-- dmq */
if (flags & NEED_UTF8) {
/* We have stored the offset of the final warning output so far.
* That must be adjusted. Any variant characters between the start
* of the pattern and this warning count for 2 bytes in the final,
* so just add them again */
if (UNLIKELY(RExC_latest_warn_offset > 0)) {
RExC_latest_warn_offset +=
variant_under_utf8_count((U8 *) exp, (U8 *) exp
+ RExC_latest_warn_offset);
}
S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen,
pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0);
DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Need to redo parse after upgrade\n"));
}
else {
DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Need to redo parse\n"));
}
if (ALL_PARENS_COUNTED) {
/* Make enough room for all the known parens, and zero it */
Renew(RExC_open_parens, RExC_total_parens, regnode_offset);
Zero(RExC_open_parens, RExC_total_parens, regnode_offset);
RExC_open_parens[0] = 1; /* +1 for REG_MAGIC */
Renew(RExC_close_parens, RExC_total_parens, regnode_offset);
Zero(RExC_close_parens, RExC_total_parens, regnode_offset);
}
else { /* Parse did not complete. Reinitialize the parentheses
structures */
RExC_total_parens = 0;
if (RExC_open_parens) {
Safefree(RExC_open_parens);
RExC_open_parens = NULL;
}
if (RExC_close_parens) {
Safefree(RExC_close_parens);
RExC_close_parens = NULL;
}
}
/* Clean up what we did in this parse */
SvREFCNT_dec_NN(RExC_rx_sv);
goto redo_parse;
}
/* Here, we have successfully parsed and generated the pattern's program
* for the regex engine. We are ready to finish things up and look for
* optimizations. */
/* Update the string to compile, with correct modifiers, etc */
set_regex_pv(pRExC_state, Rx);
RExC_rx->nparens = RExC_total_parens - 1;
/* Uses the upper 4 bits of the FLAGS field, so keep within that size */
if (RExC_whilem_seen > 15)
RExC_whilem_seen = 15;
DEBUG_PARSE_r({
Perl_re_printf( aTHX_
"Required size %" IVdf " nodes\n", (IV)RExC_size);
RExC_lastnum=0;
RExC_lastparse=NULL;
});
#ifdef RE_TRACK_PATTERN_OFFSETS
DEBUG_OFFSETS_r(Perl_re_printf( aTHX_
"%s %" UVuf " bytes for offset annotations.\n",
RExC_offsets ? "Got" : "Couldn't get",
(UV)((RExC_offsets[0] * 2 + 1))));
DEBUG_OFFSETS_r(if (RExC_offsets) {
const STRLEN len = RExC_offsets[0];
STRLEN i;
GET_RE_DEBUG_FLAGS_DECL;
Perl_re_printf( aTHX_
"Offsets: [%" UVuf "]\n\t", (UV)RExC_offsets[0]);
for (i = 1; i <= len; i++) {
if (RExC_offsets[i*2-1] || RExC_offsets[i*2])
Perl_re_printf( aTHX_ "%" UVuf ":%" UVuf "[%" UVuf "] ",
(UV)i, (UV)RExC_offsets[i*2-1], (UV)RExC_offsets[i*2]);
}
Perl_re_printf( aTHX_ "\n");
});
#else
SetProgLen(RExC_rxi,RExC_size);
#endif
DEBUG_OPTIMISE_r(
Perl_re_printf( aTHX_ "Starting post parse optimization\n");
);
/* XXXX To minimize changes to RE engine we always allocate
3-units-long substrs field. */
Newx(RExC_rx->substrs, 1, struct reg_substr_data);
if (RExC_recurse_count) {
Newx(RExC_recurse, RExC_recurse_count, regnode *);
SAVEFREEPV(RExC_recurse);
}
if (RExC_seen & REG_RECURSE_SEEN) {
/* Note, RExC_total_parens is 1 + the number of parens in a pattern.
* So its 1 if there are no parens. */
RExC_study_chunk_recursed_bytes= (RExC_total_parens >> 3) +
((RExC_total_parens & 0x07) != 0);
Newx(RExC_study_chunk_recursed,
RExC_study_chunk_recursed_bytes * RExC_total_parens, U8);
SAVEFREEPV(RExC_study_chunk_recursed);
}
reStudy:
RExC_rx->minlen = minlen = sawlookahead = sawplus = sawopen = sawminmod = 0;
DEBUG_r(
RExC_study_chunk_recursed_count= 0;
);
Zero(RExC_rx->substrs, 1, struct reg_substr_data);
if (RExC_study_chunk_recursed) {
Zero(RExC_study_chunk_recursed,
RExC_study_chunk_recursed_bytes * RExC_total_parens, U8);
}
#ifdef TRIE_STUDY_OPT
if (!restudied) {
StructCopy(&zero_scan_data, &data, scan_data_t);
copyRExC_state = RExC_state;
} else {
U32 seen=RExC_seen;
DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "Restudying\n"));
RExC_state = copyRExC_state;
if (seen & REG_TOP_LEVEL_BRANCHES_SEEN)
RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN;
else
RExC_seen &= ~REG_TOP_LEVEL_BRANCHES_SEEN;
StructCopy(&zero_scan_data, &data, scan_data_t);
}
#else
StructCopy(&zero_scan_data, &data, scan_data_t);
#endif
/* Dig out information for optimizations. */
RExC_rx->extflags = RExC_flags; /* was pm_op */
/*dmq: removed as part of de-PMOP: pm->op_pmflags = RExC_flags; */
if (UTF)
SvUTF8_on(Rx); /* Unicode in it? */
RExC_rxi->regstclass = NULL;
if (RExC_naughty >= TOO_NAUGHTY) /* Probably an expensive pattern. */
RExC_rx->intflags |= PREGf_NAUGHTY;
scan = RExC_rxi->program + 1; /* First BRANCH. */
/* testing for BRANCH here tells us whether there is "must appear"
data in the pattern. If there is then we can use it for optimisations */
if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN)) { /* Only one top-level choice.
*/
SSize_t fake;
STRLEN longest_length[2];
regnode_ssc ch_class; /* pointed to by data */
int stclass_flag;
SSize_t last_close = 0; /* pointed to by data */
regnode *first= scan;
regnode *first_next= regnext(first);
int i;
/*
* Skip introductions and multiplicators >= 1
* so that we can extract the 'meat' of the pattern that must
* match in the large if() sequence following.
* NOTE that EXACT is NOT covered here, as it is normally
* picked up by the optimiser separately.
*
* This is unfortunate as the optimiser isnt handling lookahead
* properly currently.
*
*/
while ((OP(first) == OPEN && (sawopen = 1)) ||
/* An OR of *one* alternative - should not happen now. */
(OP(first) == BRANCH && OP(first_next) != BRANCH) ||
/* for now we can't handle lookbehind IFMATCH*/
(OP(first) == IFMATCH && !first->flags && (sawlookahead = 1)) ||
(OP(first) == PLUS) ||
(OP(first) == MINMOD) ||
/* An {n,m} with n>0 */
(PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) ||
(OP(first) == NOTHING && PL_regkind[OP(first_next)] != END ))
{
/*
* the only op that could be a regnode is PLUS, all the rest
* will be regnode_1 or regnode_2.
*
* (yves doesn't think this is true)
*/
if (OP(first) == PLUS)
sawplus = 1;
else {
if (OP(first) == MINMOD)
sawminmod = 1;
first += regarglen[OP(first)];
}
first = NEXTOPER(first);
first_next= regnext(first);
}
/* Starting-point info. */
again:
DEBUG_PEEP("first:", first, 0, 0);
/* Ignore EXACT as we deal with it later. */
if (PL_regkind[OP(first)] == EXACT) {
if ( OP(first) == EXACT
|| OP(first) == EXACT_ONLY8
|| OP(first) == EXACTL)
{
NOOP; /* Empty, get anchored substr later. */
}
else
RExC_rxi->regstclass = first;
}
#ifdef TRIE_STCLASS
else if (PL_regkind[OP(first)] == TRIE &&
((reg_trie_data *)RExC_rxi->data->data[ ARG(first) ])->minlen>0)
{
/* this can happen only on restudy */
RExC_rxi->regstclass = construct_ahocorasick_from_trie(pRExC_state, (regnode *)first, 0);
}
#endif
else if (REGNODE_SIMPLE(OP(first)))
RExC_rxi->regstclass = first;
else if (PL_regkind[OP(first)] == BOUND ||
PL_regkind[OP(first)] == NBOUND)
RExC_rxi->regstclass = first;
else if (PL_regkind[OP(first)] == BOL) {
RExC_rx->intflags |= (OP(first) == MBOL
? PREGf_ANCH_MBOL
: PREGf_ANCH_SBOL);
first = NEXTOPER(first);
goto again;
}
else if (OP(first) == GPOS) {
RExC_rx->intflags |= PREGf_ANCH_GPOS;
first = NEXTOPER(first);
goto again;
}
else if ((!sawopen || !RExC_sawback) &&
!sawlookahead &&
(OP(first) == STAR &&
PL_regkind[OP(NEXTOPER(first))] == REG_ANY) &&
!(RExC_rx->intflags & PREGf_ANCH) && !pRExC_state->code_blocks)
{
/* turn .* into ^.* with an implied $*=1 */
const int type =
(OP(NEXTOPER(first)) == REG_ANY)
? PREGf_ANCH_MBOL
: PREGf_ANCH_SBOL;
RExC_rx->intflags |= (type | PREGf_IMPLICIT);
first = NEXTOPER(first);
goto again;
}
if (sawplus && !sawminmod && !sawlookahead
&& (!sawopen || !RExC_sawback)
&& !pRExC_state->code_blocks) /* May examine pos and $& */
/* x+ must match at the 1st pos of run of x's */
RExC_rx->intflags |= PREGf_SKIP;
/* Scan is after the zeroth branch, first is atomic matcher. */
#ifdef TRIE_STUDY_OPT
DEBUG_PARSE_r(
if (!restudied)
Perl_re_printf( aTHX_ "first at %" IVdf "\n",
(IV)(first - scan + 1))
);
#else
DEBUG_PARSE_r(
Perl_re_printf( aTHX_ "first at %" IVdf "\n",
(IV)(first - scan + 1))
);
#endif
/*
* If there's something expensive in the r.e., find the
* longest literal string that must appear and make it the
* regmust. Resolve ties in favor of later strings, since
* the regstart check works with the beginning of the r.e.
* and avoiding duplication strengthens checking. Not a
* strong reason, but sufficient in the absence of others.
* [Now we resolve ties in favor of the earlier string if
* it happens that c_offset_min has been invalidated, since the
* earlier string may buy us something the later one won't.]
*/
data.substrs[0].str = newSVpvs("");
data.substrs[1].str = newSVpvs("");
data.last_found = newSVpvs("");
data.cur_is_floating = 0; /* initially any found substring is fixed */
ENTER_with_name("study_chunk");
SAVEFREESV(data.substrs[0].str);
SAVEFREESV(data.substrs[1].str);
SAVEFREESV(data.last_found);
first = scan;
if (!RExC_rxi->regstclass) {
ssc_init(pRExC_state, &ch_class);
data.start_class = &ch_class;
stclass_flag = SCF_DO_STCLASS_AND;
} else /* XXXX Check for BOUND? */
stclass_flag = 0;
data.last_closep = &last_close;
DEBUG_RExC_seen();
/*
* MAIN ENTRY FOR study_chunk() FOR m/PATTERN/
* (NO top level branches)
*/
minlen = study_chunk(pRExC_state, &first, &minlen, &fake,
scan + RExC_size, /* Up to end */
&data, -1, 0, NULL,
SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag
| (restudied ? SCF_TRIE_DOING_RESTUDY : 0),
0);
CHECK_RESTUDY_GOTO_butfirst(LEAVE_with_name("study_chunk"));
if ( RExC_total_parens == 1 && !data.cur_is_floating
&& data.last_start_min == 0 && data.last_end > 0
&& !RExC_seen_zerolen
&& !(RExC_seen & REG_VERBARG_SEEN)
&& !(RExC_seen & REG_GPOS_SEEN)
){
RExC_rx->extflags |= RXf_CHECK_ALL;
}
scan_commit(pRExC_state, &data,&minlen, 0);
/* XXX this is done in reverse order because that's the way the
* code was before it was parameterised. Don't know whether it
* actually needs doing in reverse order. DAPM */
for (i = 1; i >= 0; i--) {
longest_length[i] = CHR_SVLEN(data.substrs[i].str);
if ( !( i
&& SvCUR(data.substrs[0].str) /* ok to leave SvCUR */
&& data.substrs[0].min_offset
== data.substrs[1].min_offset
&& SvCUR(data.substrs[0].str)
== SvCUR(data.substrs[1].str)
)
&& S_setup_longest (aTHX_ pRExC_state,
&(RExC_rx->substrs->data[i]),
&(data.substrs[i]),
longest_length[i]))
{
RExC_rx->substrs->data[i].min_offset =
data.substrs[i].min_offset - data.substrs[i].lookbehind;
RExC_rx->substrs->data[i].max_offset = data.substrs[i].max_offset;
/* Don't offset infinity */
if (data.substrs[i].max_offset < SSize_t_MAX)
RExC_rx->substrs->data[i].max_offset -= data.substrs[i].lookbehind;
SvREFCNT_inc_simple_void_NN(data.substrs[i].str);
}
else {
RExC_rx->substrs->data[i].substr = NULL;
RExC_rx->substrs->data[i].utf8_substr = NULL;
longest_length[i] = 0;
}
}
LEAVE_with_name("study_chunk");
if (RExC_rxi->regstclass
&& (OP(RExC_rxi->regstclass) == REG_ANY || OP(RExC_rxi->regstclass) == SANY))
RExC_rxi->regstclass = NULL;
if ((!(RExC_rx->substrs->data[0].substr || RExC_rx->substrs->data[0].utf8_substr)
|| RExC_rx->substrs->data[0].min_offset)
&& stclass_flag
&& ! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING)
&& is_ssc_worth_it(pRExC_state, data.start_class))
{
const U32 n = add_data(pRExC_state, STR_WITH_LEN("f"));
ssc_finalize(pRExC_state, data.start_class);
Newx(RExC_rxi->data->data[n], 1, regnode_ssc);
StructCopy(data.start_class,
(regnode_ssc*)RExC_rxi->data->data[n],
regnode_ssc);
RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n];
RExC_rx->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
DEBUG_COMPILE_r({ SV *sv = sv_newmortal();
regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state);
Perl_re_printf( aTHX_
"synthetic stclass \"%s\".\n",
SvPVX_const(sv));});
data.start_class = NULL;
}
/* A temporary algorithm prefers floated substr to fixed one of
* same length to dig more info. */
i = (longest_length[0] <= longest_length[1]);
RExC_rx->substrs->check_ix = i;
RExC_rx->check_end_shift = RExC_rx->substrs->data[i].end_shift;
RExC_rx->check_substr = RExC_rx->substrs->data[i].substr;
RExC_rx->check_utf8 = RExC_rx->substrs->data[i].utf8_substr;
RExC_rx->check_offset_min = RExC_rx->substrs->data[i].min_offset;
RExC_rx->check_offset_max = RExC_rx->substrs->data[i].max_offset;
if (!i && (RExC_rx->intflags & (PREGf_ANCH_SBOL|PREGf_ANCH_GPOS)))
RExC_rx->intflags |= PREGf_NOSCAN;
if ((RExC_rx->check_substr || RExC_rx->check_utf8) ) {
RExC_rx->extflags |= RXf_USE_INTUIT;
if (SvTAIL(RExC_rx->check_substr ? RExC_rx->check_substr : RExC_rx->check_utf8))
RExC_rx->extflags |= RXf_INTUIT_TAIL;
}
/* XXX Unneeded? dmq (shouldn't as this is handled elsewhere)
if ( (STRLEN)minlen < longest_length[1] )
minlen= longest_length[1];
if ( (STRLEN)minlen < longest_length[0] )
minlen= longest_length[0];
*/
}
else {
/* Several toplevels. Best we can is to set minlen. */
SSize_t fake;
regnode_ssc ch_class;
SSize_t last_close = 0;
DEBUG_PARSE_r(Perl_re_printf( aTHX_ "\nMulti Top Level\n"));
scan = RExC_rxi->program + 1;
ssc_init(pRExC_state, &ch_class);
data.start_class = &ch_class;
data.last_closep = &last_close;
DEBUG_RExC_seen();
/*
* MAIN ENTRY FOR study_chunk() FOR m/P1|P2|.../
* (patterns WITH top level branches)
*/
minlen = study_chunk(pRExC_state,
&scan, &minlen, &fake, scan + RExC_size, &data, -1, 0, NULL,
SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS|(restudied
? SCF_TRIE_DOING_RESTUDY
: 0),
0);
CHECK_RESTUDY_GOTO_butfirst(NOOP);
RExC_rx->check_substr = NULL;
RExC_rx->check_utf8 = NULL;
RExC_rx->substrs->data[0].substr = NULL;
RExC_rx->substrs->data[0].utf8_substr = NULL;
RExC_rx->substrs->data[1].substr = NULL;
RExC_rx->substrs->data[1].utf8_substr = NULL;
if (! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING)
&& is_ssc_worth_it(pRExC_state, data.start_class))
{
const U32 n = add_data(pRExC_state, STR_WITH_LEN("f"));
ssc_finalize(pRExC_state, data.start_class);
Newx(RExC_rxi->data->data[n], 1, regnode_ssc);
StructCopy(data.start_class,
(regnode_ssc*)RExC_rxi->data->data[n],
regnode_ssc);
RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n];
RExC_rx->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
DEBUG_COMPILE_r({ SV* sv = sv_newmortal();
regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state);
Perl_re_printf( aTHX_
"synthetic stclass \"%s\".\n",
SvPVX_const(sv));});
data.start_class = NULL;
}
}
if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) {
RExC_rx->extflags |= RXf_UNBOUNDED_QUANTIFIER_SEEN;
RExC_rx->maxlen = REG_INFTY;
}
else {
RExC_rx->maxlen = RExC_maxlen;
}
/* Guard against an embedded (?=) or (?<=) with a longer minlen than
the "real" pattern. */
DEBUG_OPTIMISE_r({
Perl_re_printf( aTHX_ "minlen: %" IVdf " RExC_rx->minlen:%" IVdf " maxlen:%" IVdf "\n",
(IV)minlen, (IV)RExC_rx->minlen, (IV)RExC_maxlen);
});
RExC_rx->minlenret = minlen;
if (RExC_rx->minlen < minlen)
RExC_rx->minlen = minlen;
if (RExC_seen & REG_RECURSE_SEEN ) {
RExC_rx->intflags |= PREGf_RECURSE_SEEN;
Newx(RExC_rx->recurse_locinput, RExC_rx->nparens + 1, char *);
}
if (RExC_seen & REG_GPOS_SEEN)
RExC_rx->intflags |= PREGf_GPOS_SEEN;
if (RExC_seen & REG_LOOKBEHIND_SEEN)
RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* inplace might break the
lookbehind */
if (pRExC_state->code_blocks)
RExC_rx->extflags |= RXf_EVAL_SEEN;
if (RExC_seen & REG_VERBARG_SEEN)
{
RExC_rx->intflags |= PREGf_VERBARG_SEEN;
RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* don't understand this! Yves */
}
if (RExC_seen & REG_CUTGROUP_SEEN)
RExC_rx->intflags |= PREGf_CUTGROUP_SEEN;
if (pm_flags & PMf_USE_RE_EVAL)
RExC_rx->intflags |= PREGf_USE_RE_EVAL;
if (RExC_paren_names)
RXp_PAREN_NAMES(RExC_rx) = MUTABLE_HV(SvREFCNT_inc(RExC_paren_names));
else
RXp_PAREN_NAMES(RExC_rx) = NULL;
/* If we have seen an anchor in our pattern then we set the extflag RXf_IS_ANCHORED
* so it can be used in pp.c */
if (RExC_rx->intflags & PREGf_ANCH)
RExC_rx->extflags |= RXf_IS_ANCHORED;
{
/* this is used to identify "special" patterns that might result
* in Perl NOT calling the regex engine and instead doing the match "itself",
* particularly special cases in split//. By having the regex compiler
* do this pattern matching at a regop level (instead of by inspecting the pattern)
* we avoid weird issues with equivalent patterns resulting in different behavior,
* AND we allow non Perl engines to get the same optimizations by the setting the
* flags appropriately - Yves */
regnode *first = RExC_rxi->program + 1;
U8 fop = OP(first);
regnode *next = regnext(first);
U8 nop = OP(next);
if (PL_regkind[fop] == NOTHING && nop == END)
RExC_rx->extflags |= RXf_NULL;
else if ((fop == MBOL || (fop == SBOL && !first->flags)) && nop == END)
/* when fop is SBOL first->flags will be true only when it was
* produced by parsing /\A/, and not when parsing /^/. This is
* very important for the split code as there we want to
* treat /^/ as /^/m, but we do not want to treat /\A/ as /^/m.
* See rt #122761 for more details. -- Yves */
RExC_rx->extflags |= RXf_START_ONLY;
else if (fop == PLUS
&& PL_regkind[nop] == POSIXD && FLAGS(next) == _CC_SPACE
&& nop == END)
RExC_rx->extflags |= RXf_WHITE;
else if ( RExC_rx->extflags & RXf_SPLIT
&& (fop == EXACT || fop == EXACT_ONLY8 || fop == EXACTL)
&& STR_LEN(first) == 1
&& *(STRING(first)) == ' '
&& nop == END )
RExC_rx->extflags |= (RXf_SKIPWHITE|RXf_WHITE);
}
if (RExC_contains_locale) {
RXp_EXTFLAGS(RExC_rx) |= RXf_TAINTED;
}
#ifdef DEBUGGING
if (RExC_paren_names) {
RExC_rxi->name_list_idx = add_data( pRExC_state, STR_WITH_LEN("a"));
RExC_rxi->data->data[RExC_rxi->name_list_idx]
= (void*)SvREFCNT_inc(RExC_paren_name_list);
} else
#endif
RExC_rxi->name_list_idx = 0;
while ( RExC_recurse_count > 0 ) {
const regnode *scan = RExC_recurse[ --RExC_recurse_count ];
/*
* This data structure is set up in study_chunk() and is used
* to calculate the distance between a GOSUB regopcode and
* the OPEN/CURLYM (CURLYM's are special and can act like OPEN's)
* it refers to.
*
* If for some reason someone writes code that optimises
* away a GOSUB opcode then the assert should be changed to
* an if(scan) to guard the ARG2L_SET() - Yves
*
*/
assert(scan && OP(scan) == GOSUB);
ARG2L_SET( scan, RExC_open_parens[ARG(scan)] - REGNODE_OFFSET(scan));
}
Newxz(RExC_rx->offs, RExC_total_parens, regexp_paren_pair);
/* assume we don't need to swap parens around before we match */
DEBUG_TEST_r({
Perl_re_printf( aTHX_ "study_chunk_recursed_count: %lu\n",
(unsigned long)RExC_study_chunk_recursed_count);
});
DEBUG_DUMP_r({
DEBUG_RExC_seen();
Perl_re_printf( aTHX_ "Final program:\n");
regdump(RExC_rx);
});
if (RExC_open_parens) {
Safefree(RExC_open_parens);
RExC_open_parens = NULL;
}
if (RExC_close_parens) {
Safefree(RExC_close_parens);
RExC_close_parens = NULL;
}
#ifdef USE_ITHREADS
/* under ithreads the ?pat? PMf_USED flag on the pmop is simulated
* by setting the regexp SV to readonly-only instead. If the
* pattern's been recompiled, the USEDness should remain. */
if (old_re && SvREADONLY(old_re))
SvREADONLY_on(Rx);
#endif
return Rx;
}
SV*
Perl_reg_named_buff(pTHX_ REGEXP * const rx, SV * const key, SV * const value,
const U32 flags)
{
PERL_ARGS_ASSERT_REG_NAMED_BUFF;
PERL_UNUSED_ARG(value);
if (flags & RXapif_FETCH) {
return reg_named_buff_fetch(rx, key, flags);
} else if (flags & (RXapif_STORE | RXapif_DELETE | RXapif_CLEAR)) {
Perl_croak_no_modify();
return NULL;
} else if (flags & RXapif_EXISTS) {
return reg_named_buff_exists(rx, key, flags)
? &PL_sv_yes
: &PL_sv_no;
} else if (flags & RXapif_REGNAMES) {
return reg_named_buff_all(rx, flags);
} else if (flags & (RXapif_SCALAR | RXapif_REGNAMES_COUNT)) {
return reg_named_buff_scalar(rx, flags);
} else {
Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff", (int)flags);
return NULL;
}
}
SV*
Perl_reg_named_buff_iter(pTHX_ REGEXP * const rx, const SV * const lastkey,
const U32 flags)
{
PERL_ARGS_ASSERT_REG_NAMED_BUFF_ITER;
PERL_UNUSED_ARG(lastkey);
if (flags & RXapif_FIRSTKEY)
return reg_named_buff_firstkey(rx, flags);
else if (flags & RXapif_NEXTKEY)
return reg_named_buff_nextkey(rx, flags);
else {
Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_iter",
(int)flags);
return NULL;
}
}
SV*
Perl_reg_named_buff_fetch(pTHX_ REGEXP * const r, SV * const namesv,
const U32 flags)
{
SV *ret;
struct regexp *const rx = ReANY(r);
PERL_ARGS_ASSERT_REG_NAMED_BUFF_FETCH;
if (rx && RXp_PAREN_NAMES(rx)) {
HE *he_str = hv_fetch_ent( RXp_PAREN_NAMES(rx), namesv, 0, 0 );
if (he_str) {
IV i;
SV* sv_dat=HeVAL(he_str);
I32 *nums=(I32*)SvPVX(sv_dat);
AV * const retarray = (flags & RXapif_ALL) ? newAV() : NULL;
for ( i=0; i<SvIVX(sv_dat); i++ ) {
if ((I32)(rx->nparens) >= nums[i]
&& rx->offs[nums[i]].start != -1
&& rx->offs[nums[i]].end != -1)
{
ret = newSVpvs("");
CALLREG_NUMBUF_FETCH(r, nums[i], ret);
if (!retarray)
return ret;
} else {
if (retarray)
ret = newSVsv(&PL_sv_undef);
}
if (retarray)
av_push(retarray, ret);
}
if (retarray)
return newRV_noinc(MUTABLE_SV(retarray));
}
}
return NULL;
}
bool
Perl_reg_named_buff_exists(pTHX_ REGEXP * const r, SV * const key,
const U32 flags)
{
struct regexp *const rx = ReANY(r);
PERL_ARGS_ASSERT_REG_NAMED_BUFF_EXISTS;
if (rx && RXp_PAREN_NAMES(rx)) {
if (flags & RXapif_ALL) {
return hv_exists_ent(RXp_PAREN_NAMES(rx), key, 0);
} else {
SV *sv = CALLREG_NAMED_BUFF_FETCH(r, key, flags);
if (sv) {
SvREFCNT_dec_NN(sv);
return TRUE;
} else {
return FALSE;
}
}
} else {
return FALSE;
}
}
SV*
Perl_reg_named_buff_firstkey(pTHX_ REGEXP * const r, const U32 flags)
{
struct regexp *const rx = ReANY(r);
PERL_ARGS_ASSERT_REG_NAMED_BUFF_FIRSTKEY;
if ( rx && RXp_PAREN_NAMES(rx) ) {
(void)hv_iterinit(RXp_PAREN_NAMES(rx));
return CALLREG_NAMED_BUFF_NEXTKEY(r, NULL, flags & ~RXapif_FIRSTKEY);
} else {
return FALSE;
}
}
SV*
Perl_reg_named_buff_nextkey(pTHX_ REGEXP * const r, const U32 flags)
{
struct regexp *const rx = ReANY(r);
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REG_NAMED_BUFF_NEXTKEY;
if (rx && RXp_PAREN_NAMES(rx)) {
HV *hv = RXp_PAREN_NAMES(rx);
HE *temphe;
while ( (temphe = hv_iternext_flags(hv, 0)) ) {
IV i;
IV parno = 0;
SV* sv_dat = HeVAL(temphe);
I32 *nums = (I32*)SvPVX(sv_dat);
for ( i = 0; i < SvIVX(sv_dat); i++ ) {
if ((I32)(rx->lastparen) >= nums[i] &&
rx->offs[nums[i]].start != -1 &&
rx->offs[nums[i]].end != -1)
{
parno = nums[i];
break;
}
}
if (parno || flags & RXapif_ALL) {
return newSVhek(HeKEY_hek(temphe));
}
}
}
return NULL;
}
SV*
Perl_reg_named_buff_scalar(pTHX_ REGEXP * const r, const U32 flags)
{
SV *ret;
AV *av;
SSize_t length;
struct regexp *const rx = ReANY(r);
PERL_ARGS_ASSERT_REG_NAMED_BUFF_SCALAR;
if (rx && RXp_PAREN_NAMES(rx)) {
if (flags & (RXapif_ALL | RXapif_REGNAMES_COUNT)) {
return newSViv(HvTOTALKEYS(RXp_PAREN_NAMES(rx)));
} else if (flags & RXapif_ONE) {
ret = CALLREG_NAMED_BUFF_ALL(r, (flags | RXapif_REGNAMES));
av = MUTABLE_AV(SvRV(ret));
length = av_tindex(av);
SvREFCNT_dec_NN(ret);
return newSViv(length + 1);
} else {
Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_scalar",
(int)flags);
return NULL;
}
}
return &PL_sv_undef;
}
SV*
Perl_reg_named_buff_all(pTHX_ REGEXP * const r, const U32 flags)
{
struct regexp *const rx = ReANY(r);
AV *av = newAV();
PERL_ARGS_ASSERT_REG_NAMED_BUFF_ALL;
if (rx && RXp_PAREN_NAMES(rx)) {
HV *hv= RXp_PAREN_NAMES(rx);
HE *temphe;
(void)hv_iterinit(hv);
while ( (temphe = hv_iternext_flags(hv, 0)) ) {
IV i;
IV parno = 0;
SV* sv_dat = HeVAL(temphe);
I32 *nums = (I32*)SvPVX(sv_dat);
for ( i = 0; i < SvIVX(sv_dat); i++ ) {
if ((I32)(rx->lastparen) >= nums[i] &&
rx->offs[nums[i]].start != -1 &&
rx->offs[nums[i]].end != -1)
{
parno = nums[i];
break;
}
}
if (parno || flags & RXapif_ALL) {
av_push(av, newSVhek(HeKEY_hek(temphe)));
}
}
}
return newRV_noinc(MUTABLE_SV(av));
}
void
Perl_reg_numbered_buff_fetch(pTHX_ REGEXP * const r, const I32 paren,
SV * const sv)
{
struct regexp *const rx = ReANY(r);
char *s = NULL;
SSize_t i = 0;
SSize_t s1, t1;
I32 n = paren;
PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_FETCH;
if ( n == RX_BUFF_IDX_CARET_PREMATCH
|| n == RX_BUFF_IDX_CARET_FULLMATCH
|| n == RX_BUFF_IDX_CARET_POSTMATCH
)
{
bool keepcopy = cBOOL(rx->extflags & RXf_PMf_KEEPCOPY);
if (!keepcopy) {
/* on something like
* $r = qr/.../;
* /$qr/p;
* the KEEPCOPY is set on the PMOP rather than the regex */
if (PL_curpm && r == PM_GETRE(PL_curpm))
keepcopy = cBOOL(PL_curpm->op_pmflags & PMf_KEEPCOPY);
}
if (!keepcopy)
goto ret_undef;
}
if (!rx->subbeg)
goto ret_undef;
if (n == RX_BUFF_IDX_CARET_FULLMATCH)
/* no need to distinguish between them any more */
n = RX_BUFF_IDX_FULLMATCH;
if ((n == RX_BUFF_IDX_PREMATCH || n == RX_BUFF_IDX_CARET_PREMATCH)
&& rx->offs[0].start != -1)
{
/* $`, ${^PREMATCH} */
i = rx->offs[0].start;
s = rx->subbeg;
}
else
if ((n == RX_BUFF_IDX_POSTMATCH || n == RX_BUFF_IDX_CARET_POSTMATCH)
&& rx->offs[0].end != -1)
{
/* $', ${^POSTMATCH} */
s = rx->subbeg - rx->suboffset + rx->offs[0].end;
i = rx->sublen + rx->suboffset - rx->offs[0].end;
}
else
if ( 0 <= n && n <= (I32)rx->nparens &&
(s1 = rx->offs[n].start) != -1 &&
(t1 = rx->offs[n].end) != -1)
{
/* $&, ${^MATCH}, $1 ... */
i = t1 - s1;
s = rx->subbeg + s1 - rx->suboffset;
} else {
goto ret_undef;
}
assert(s >= rx->subbeg);
assert((STRLEN)rx->sublen >= (STRLEN)((s - rx->subbeg) + i) );
if (i >= 0) {
#ifdef NO_TAINT_SUPPORT
sv_setpvn(sv, s, i);
#else
const int oldtainted = TAINT_get;
TAINT_NOT;
sv_setpvn(sv, s, i);
TAINT_set(oldtainted);
#endif
if (RXp_MATCH_UTF8(rx))
SvUTF8_on(sv);
else
SvUTF8_off(sv);
if (TAINTING_get) {
if (RXp_MATCH_TAINTED(rx)) {
if (SvTYPE(sv) >= SVt_PVMG) {
MAGIC* const mg = SvMAGIC(sv);
MAGIC* mgt;
TAINT;
SvMAGIC_set(sv, mg->mg_moremagic);
SvTAINT(sv);
if ((mgt = SvMAGIC(sv))) {
mg->mg_moremagic = mgt;
SvMAGIC_set(sv, mg);
}
} else {
TAINT;
SvTAINT(sv);
}
} else
SvTAINTED_off(sv);
}
} else {
ret_undef:
sv_set_undef(sv);
return;
}
}
void
Perl_reg_numbered_buff_store(pTHX_ REGEXP * const rx, const I32 paren,
SV const * const value)
{
PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_STORE;
PERL_UNUSED_ARG(rx);
PERL_UNUSED_ARG(paren);
PERL_UNUSED_ARG(value);
if (!PL_localizing)
Perl_croak_no_modify();
}
I32
Perl_reg_numbered_buff_length(pTHX_ REGEXP * const r, const SV * const sv,
const I32 paren)
{
struct regexp *const rx = ReANY(r);
I32 i;
I32 s1, t1;
PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_LENGTH;
if ( paren == RX_BUFF_IDX_CARET_PREMATCH
|| paren == RX_BUFF_IDX_CARET_FULLMATCH
|| paren == RX_BUFF_IDX_CARET_POSTMATCH
)
{
bool keepcopy = cBOOL(rx->extflags & RXf_PMf_KEEPCOPY);
if (!keepcopy) {
/* on something like
* $r = qr/.../;
* /$qr/p;
* the KEEPCOPY is set on the PMOP rather than the regex */
if (PL_curpm && r == PM_GETRE(PL_curpm))
keepcopy = cBOOL(PL_curpm->op_pmflags & PMf_KEEPCOPY);
}
if (!keepcopy)
goto warn_undef;
}
/* Some of this code was originally in C<Perl_magic_len> in F<mg.c> */
switch (paren) {
case RX_BUFF_IDX_CARET_PREMATCH: /* ${^PREMATCH} */
case RX_BUFF_IDX_PREMATCH: /* $` */
if (rx->offs[0].start != -1) {
i = rx->offs[0].start;
if (i > 0) {
s1 = 0;
t1 = i;
goto getlen;
}
}
return 0;
case RX_BUFF_IDX_CARET_POSTMATCH: /* ${^POSTMATCH} */
case RX_BUFF_IDX_POSTMATCH: /* $' */
if (rx->offs[0].end != -1) {
i = rx->sublen - rx->offs[0].end;
if (i > 0) {
s1 = rx->offs[0].end;
t1 = rx->sublen;
goto getlen;
}
}
return 0;
default: /* $& / ${^MATCH}, $1, $2, ... */
if (paren <= (I32)rx->nparens &&
(s1 = rx->offs[paren].start) != -1 &&
(t1 = rx->offs[paren].end) != -1)
{
i = t1 - s1;
goto getlen;
} else {
warn_undef:
if (ckWARN(WARN_UNINITIALIZED))
report_uninit((const SV *)sv);
return 0;
}
}
getlen:
if (i > 0 && RXp_MATCH_UTF8(rx)) {
const char * const s = rx->subbeg - rx->suboffset + s1;
const U8 *ep;
STRLEN el;
i = t1 - s1;
if (is_utf8_string_loclen((U8*)s, i, &ep, &el))
i = el;
}
return i;
}
SV*
Perl_reg_qr_package(pTHX_ REGEXP * const rx)
{
PERL_ARGS_ASSERT_REG_QR_PACKAGE;
PERL_UNUSED_ARG(rx);
if (0)
return NULL;
else
return newSVpvs("Regexp");
}
/* Scans the name of a named buffer from the pattern.
* If flags is REG_RSN_RETURN_NULL returns null.
* If flags is REG_RSN_RETURN_NAME returns an SV* containing the name
* If flags is REG_RSN_RETURN_DATA returns the data SV* corresponding
* to the parsed name as looked up in the RExC_paren_names hash.
* If there is an error throws a vFAIL().. type exception.
*/
#define REG_RSN_RETURN_NULL 0
#define REG_RSN_RETURN_NAME 1
#define REG_RSN_RETURN_DATA 2
STATIC SV*
S_reg_scan_name(pTHX_ RExC_state_t *pRExC_state, U32 flags)
{
char *name_start = RExC_parse;
SV* sv_name;
PERL_ARGS_ASSERT_REG_SCAN_NAME;
assert (RExC_parse <= RExC_end);
if (RExC_parse == RExC_end) NOOP;
else if (isIDFIRST_lazy_if_safe(RExC_parse, RExC_end, UTF)) {
/* Note that the code here assumes well-formed UTF-8. Skip IDFIRST by
* using do...while */
if (UTF)
do {
RExC_parse += UTF8SKIP(RExC_parse);
} while ( RExC_parse < RExC_end
&& isWORDCHAR_utf8_safe((U8*)RExC_parse, (U8*) RExC_end));
else
do {
RExC_parse++;
} while (RExC_parse < RExC_end && isWORDCHAR(*RExC_parse));
} else {
RExC_parse++; /* so the <- from the vFAIL is after the offending
character */
vFAIL("Group name must start with a non-digit word character");
}
sv_name = newSVpvn_flags(name_start, (int)(RExC_parse - name_start),
SVs_TEMP | (UTF ? SVf_UTF8 : 0));
if ( flags == REG_RSN_RETURN_NAME)
return sv_name;
else if (flags==REG_RSN_RETURN_DATA) {
HE *he_str = NULL;
SV *sv_dat = NULL;
if ( ! sv_name ) /* should not happen*/
Perl_croak(aTHX_ "panic: no svname in reg_scan_name");
if (RExC_paren_names)
he_str = hv_fetch_ent( RExC_paren_names, sv_name, 0, 0 );
if ( he_str )
sv_dat = HeVAL(he_str);
if ( ! sv_dat ) { /* Didn't find group */
/* It might be a forward reference; we can't fail until we
* know, by completing the parse to get all the groups, and
* then reparsing */
if (ALL_PARENS_COUNTED) {
vFAIL("Reference to nonexistent named group");
}
else {
REQUIRE_PARENS_PASS;
}
}
return sv_dat;
}
Perl_croak(aTHX_ "panic: bad flag %lx in reg_scan_name",
(unsigned long) flags);
}
#define DEBUG_PARSE_MSG(funcname) DEBUG_PARSE_r({ \
if (RExC_lastparse!=RExC_parse) { \
Perl_re_printf( aTHX_ "%s", \
Perl_pv_pretty(aTHX_ RExC_mysv1, RExC_parse, \
RExC_end - RExC_parse, 16, \
"", "", \
PERL_PV_ESCAPE_UNI_DETECT | \
PERL_PV_PRETTY_ELLIPSES | \
PERL_PV_PRETTY_LTGT | \
PERL_PV_ESCAPE_RE | \
PERL_PV_PRETTY_EXACTSIZE \
) \
); \
} else \
Perl_re_printf( aTHX_ "%16s",""); \
\
if (RExC_lastnum!=RExC_emit) \
Perl_re_printf( aTHX_ "|%4d", RExC_emit); \
else \
Perl_re_printf( aTHX_ "|%4s",""); \
Perl_re_printf( aTHX_ "|%*s%-4s", \
(int)((depth*2)), "", \
(funcname) \
); \
RExC_lastnum=RExC_emit; \
RExC_lastparse=RExC_parse; \
})
#define DEBUG_PARSE(funcname) DEBUG_PARSE_r({ \
DEBUG_PARSE_MSG((funcname)); \
Perl_re_printf( aTHX_ "%4s","\n"); \
})
#define DEBUG_PARSE_FMT(funcname,fmt,args) DEBUG_PARSE_r({\
DEBUG_PARSE_MSG((funcname)); \
Perl_re_printf( aTHX_ fmt "\n",args); \
})
/* This section of code defines the inversion list object and its methods. The
* interfaces are highly subject to change, so as much as possible is static to
* this file. An inversion list is here implemented as a malloc'd C UV array
* as an SVt_INVLIST scalar.
*
* An inversion list for Unicode is an array of code points, sorted by ordinal
* number. Each element gives the code point that begins a range that extends
* up-to but not including the code point given by the next element. The final
* element gives the first code point of a range that extends to the platform's
* infinity. The even-numbered elements (invlist[0], invlist[2], invlist[4],
* ...) give ranges whose code points are all in the inversion list. We say
* that those ranges are in the set. The odd-numbered elements give ranges
* whose code points are not in the inversion list, and hence not in the set.
* Thus, element [0] is the first code point in the list. Element [1]
* is the first code point beyond that not in the list; and element [2] is the
* first code point beyond that that is in the list. In other words, the first
* range is invlist[0]..(invlist[1]-1), and all code points in that range are
* in the inversion list. The second range is invlist[1]..(invlist[2]-1), and
* all code points in that range are not in the inversion list. The third
* range invlist[2]..(invlist[3]-1) gives code points that are in the inversion
* list, and so forth. Thus every element whose index is divisible by two
* gives the beginning of a range that is in the list, and every element whose
* index is not divisible by two gives the beginning of a range not in the
* list. If the final element's index is divisible by two, the inversion list
* extends to the platform's infinity; otherwise the highest code point in the
* inversion list is the contents of that element minus 1.
*
* A range that contains just a single code point N will look like
* invlist[i] == N
* invlist[i+1] == N+1
*
* If N is UV_MAX (the highest representable code point on the machine), N+1 is
* impossible to represent, so element [i+1] is omitted. The single element
* inversion list
* invlist[0] == UV_MAX
* contains just UV_MAX, but is interpreted as matching to infinity.
*
* Taking the complement (inverting) an inversion list is quite simple, if the
* first element is 0, remove it; otherwise add a 0 element at the beginning.
* This implementation reserves an element at the beginning of each inversion
* list to always contain 0; there is an additional flag in the header which
* indicates if the list begins at the 0, or is offset to begin at the next
* element. This means that the inversion list can be inverted without any
* copying; just flip the flag.
*
* More about inversion lists can be found in "Unicode Demystified"
* Chapter 13 by Richard Gillam, published by Addison-Wesley.
*
* The inversion list data structure is currently implemented as an SV pointing
* to an array of UVs that the SV thinks are bytes. This allows us to have an
* array of UV whose memory management is automatically handled by the existing
* facilities for SV's.
*
* Some of the methods should always be private to the implementation, and some
* should eventually be made public */
/* The header definitions are in F<invlist_inline.h> */
#ifndef PERL_IN_XSUB_RE
PERL_STATIC_INLINE UV*
S__invlist_array_init(SV* const invlist, const bool will_have_0)
{
/* Returns a pointer to the first element in the inversion list's array.
* This is called upon initialization of an inversion list. Where the
* array begins depends on whether the list has the code point U+0000 in it
* or not. The other parameter tells it whether the code that follows this
* call is about to put a 0 in the inversion list or not. The first
* element is either the element reserved for 0, if TRUE, or the element
* after it, if FALSE */
bool* offset = get_invlist_offset_addr(invlist);
UV* zero_addr = (UV *) SvPVX(invlist);
PERL_ARGS_ASSERT__INVLIST_ARRAY_INIT;
/* Must be empty */
assert(! _invlist_len(invlist));
*zero_addr = 0;
/* 1^1 = 0; 1^0 = 1 */
*offset = 1 ^ will_have_0;
return zero_addr + *offset;
}
PERL_STATIC_INLINE void
S_invlist_set_len(pTHX_ SV* const invlist, const UV len, const bool offset)
{
/* Sets the current number of elements stored in the inversion list.
* Updates SvCUR correspondingly */
PERL_UNUSED_CONTEXT;
PERL_ARGS_ASSERT_INVLIST_SET_LEN;
assert(is_invlist(invlist));
SvCUR_set(invlist,
(len == 0)
? 0
: TO_INTERNAL_SIZE(len + offset));
assert(SvLEN(invlist) == 0 || SvCUR(invlist) <= SvLEN(invlist));
}
STATIC void
S_invlist_replace_list_destroys_src(pTHX_ SV * dest, SV * src)
{
/* Replaces the inversion list in 'dest' with the one from 'src'. It
* steals the list from 'src', so 'src' is made to have a NULL list. This
* is similar to what SvSetMagicSV() would do, if it were implemented on
* inversion lists, though this routine avoids a copy */
const UV src_len = _invlist_len(src);
const bool src_offset = *get_invlist_offset_addr(src);
const STRLEN src_byte_len = SvLEN(src);
char * array = SvPVX(src);
const int oldtainted = TAINT_get;
PERL_ARGS_ASSERT_INVLIST_REPLACE_LIST_DESTROYS_SRC;
assert(is_invlist(src));
assert(is_invlist(dest));
assert(! invlist_is_iterating(src));
assert(SvCUR(src) == 0 || SvCUR(src) < SvLEN(src));
/* Make sure it ends in the right place with a NUL, as our inversion list
* manipulations aren't careful to keep this true, but sv_usepvn_flags()
* asserts it */
array[src_byte_len - 1] = '\0';
TAINT_NOT; /* Otherwise it breaks */
sv_usepvn_flags(dest,
(char *) array,
src_byte_len - 1,
/* This flag is documented to cause a copy to be avoided */
SV_HAS_TRAILING_NUL);
TAINT_set(oldtainted);
SvPV_set(src, 0);
SvLEN_set(src, 0);
SvCUR_set(src, 0);
/* Finish up copying over the other fields in an inversion list */
*get_invlist_offset_addr(dest) = src_offset;
invlist_set_len(dest, src_len, src_offset);
*get_invlist_previous_index_addr(dest) = 0;
invlist_iterfinish(dest);
}
PERL_STATIC_INLINE IV*
S_get_invlist_previous_index_addr(SV* invlist)
{
/* Return the address of the IV that is reserved to hold the cached index
* */
PERL_ARGS_ASSERT_GET_INVLIST_PREVIOUS_INDEX_ADDR;
assert(is_invlist(invlist));
return &(((XINVLIST*) SvANY(invlist))->prev_index);
}
PERL_STATIC_INLINE IV
S_invlist_previous_index(SV* const invlist)
{
/* Returns cached index of previous search */
PERL_ARGS_ASSERT_INVLIST_PREVIOUS_INDEX;
return *get_invlist_previous_index_addr(invlist);
}
PERL_STATIC_INLINE void
S_invlist_set_previous_index(SV* const invlist, const IV index)
{
/* Caches <index> for later retrieval */
PERL_ARGS_ASSERT_INVLIST_SET_PREVIOUS_INDEX;
assert(index == 0 || index < (int) _invlist_len(invlist));
*get_invlist_previous_index_addr(invlist) = index;
}
PERL_STATIC_INLINE void
S_invlist_trim(SV* invlist)
{
/* Free the not currently-being-used space in an inversion list */
/* But don't free up the space needed for the 0 UV that is always at the
* beginning of the list, nor the trailing NUL */
const UV min_size = TO_INTERNAL_SIZE(1) + 1;
PERL_ARGS_ASSERT_INVLIST_TRIM;
assert(is_invlist(invlist));
SvPV_renew(invlist, MAX(min_size, SvCUR(invlist) + 1));
}
PERL_STATIC_INLINE void
S_invlist_clear(pTHX_ SV* invlist) /* Empty the inversion list */
{
PERL_ARGS_ASSERT_INVLIST_CLEAR;
assert(is_invlist(invlist));
invlist_set_len(invlist, 0, 0);
invlist_trim(invlist);
}
#endif /* ifndef PERL_IN_XSUB_RE */
PERL_STATIC_INLINE bool
S_invlist_is_iterating(SV* const invlist)
{
PERL_ARGS_ASSERT_INVLIST_IS_ITERATING;
return *(get_invlist_iter_addr(invlist)) < (STRLEN) UV_MAX;
}
#ifndef PERL_IN_XSUB_RE
PERL_STATIC_INLINE UV
S_invlist_max(SV* const invlist)
{
/* Returns the maximum number of elements storable in the inversion list's
* array, without having to realloc() */
PERL_ARGS_ASSERT_INVLIST_MAX;
assert(is_invlist(invlist));
/* Assumes worst case, in which the 0 element is not counted in the
* inversion list, so subtracts 1 for that */
return SvLEN(invlist) == 0 /* This happens under _new_invlist_C_array */
? FROM_INTERNAL_SIZE(SvCUR(invlist)) - 1
: FROM_INTERNAL_SIZE(SvLEN(invlist)) - 1;
}
STATIC void
S_initialize_invlist_guts(pTHX_ SV* invlist, const Size_t initial_size)
{
PERL_ARGS_ASSERT_INITIALIZE_INVLIST_GUTS;
/* First 1 is in case the zero element isn't in the list; second 1 is for
* trailing NUL */
SvGROW(invlist, TO_INTERNAL_SIZE(initial_size + 1) + 1);
invlist_set_len(invlist, 0, 0);
/* Force iterinit() to be used to get iteration to work */
invlist_iterfinish(invlist);
*get_invlist_previous_index_addr(invlist) = 0;
}
SV*
Perl__new_invlist(pTHX_ IV initial_size)
{
/* Return a pointer to a newly constructed inversion list, with enough
* space to store 'initial_size' elements. If that number is negative, a
* system default is used instead */
SV* new_list;
if (initial_size < 0) {
initial_size = 10;
}
new_list = newSV_type(SVt_INVLIST);
initialize_invlist_guts(new_list, initial_size);
return new_list;
}
SV*
Perl__new_invlist_C_array(pTHX_ const UV* const list)
{
/* Return a pointer to a newly constructed inversion list, initialized to
* point to <list>, which has to be in the exact correct inversion list
* form, including internal fields. Thus this is a dangerous routine that
* should not be used in the wrong hands. The passed in 'list' contains
* several header fields at the beginning that are not part of the
* inversion list body proper */
const STRLEN length = (STRLEN) list[0];
const UV version_id = list[1];
const bool offset = cBOOL(list[2]);
#define HEADER_LENGTH 3
/* If any of the above changes in any way, you must change HEADER_LENGTH
* (if appropriate) and regenerate INVLIST_VERSION_ID by running
* perl -E 'say int(rand 2**31-1)'
*/
#define INVLIST_VERSION_ID 148565664 /* This is a combination of a version and
data structure type, so that one being
passed in can be validated to be an
inversion list of the correct vintage.
*/
SV* invlist = newSV_type(SVt_INVLIST);
PERL_ARGS_ASSERT__NEW_INVLIST_C_ARRAY;
if (version_id != INVLIST_VERSION_ID) {
Perl_croak(aTHX_ "panic: Incorrect version for previously generated inversion list");
}
/* The generated array passed in includes header elements that aren't part
* of the list proper, so start it just after them */
SvPV_set(invlist, (char *) (list + HEADER_LENGTH));
SvLEN_set(invlist, 0); /* Means we own the contents, and the system
shouldn't touch it */
*(get_invlist_offset_addr(invlist)) = offset;
/* The 'length' passed to us is the physical number of elements in the
* inversion list. But if there is an offset the logical number is one
* less than that */
invlist_set_len(invlist, length - offset, offset);
invlist_set_previous_index(invlist, 0);
/* Initialize the iteration pointer. */
invlist_iterfinish(invlist);
SvREADONLY_on(invlist);
return invlist;
}
STATIC void
S_invlist_extend(pTHX_ SV* const invlist, const UV new_max)
{
/* Grow the maximum size of an inversion list */
PERL_ARGS_ASSERT_INVLIST_EXTEND;
assert(is_invlist(invlist));
/* Add one to account for the zero element at the beginning which may not
* be counted by the calling parameters */
SvGROW((SV *)invlist, TO_INTERNAL_SIZE(new_max + 1));
}
STATIC void
S__append_range_to_invlist(pTHX_ SV* const invlist,
const UV start, const UV end)
{
/* Subject to change or removal. Append the range from 'start' to 'end' at
* the end of the inversion list. The range must be above any existing
* ones. */
UV* array;
UV max = invlist_max(invlist);
UV len = _invlist_len(invlist);
bool offset;
PERL_ARGS_ASSERT__APPEND_RANGE_TO_INVLIST;
if (len == 0) { /* Empty lists must be initialized */
offset = start != 0;
array = _invlist_array_init(invlist, ! offset);
}
else {
/* Here, the existing list is non-empty. The current max entry in the
* list is generally the first value not in the set, except when the
* set extends to the end of permissible values, in which case it is
* the first entry in that final set, and so this call is an attempt to
* append out-of-order */
UV final_element = len - 1;
array = invlist_array(invlist);
if ( array[final_element] > start
|| ELEMENT_RANGE_MATCHES_INVLIST(final_element))
{
Perl_croak(aTHX_ "panic: attempting to append to an inversion list, but wasn't at the end of the list, final=%" UVuf ", start=%" UVuf ", match=%c",
array[final_element], start,
ELEMENT_RANGE_MATCHES_INVLIST(final_element) ? 't' : 'f');
}
/* Here, it is a legal append. If the new range begins 1 above the end
* of the range below it, it is extending the range below it, so the
* new first value not in the set is one greater than the newly
* extended range. */
offset = *get_invlist_offset_addr(invlist);
if (array[final_element] == start) {
if (end != UV_MAX) {
array[final_element] = end + 1;
}
else {
/* But if the end is the maximum representable on the machine,
* assume that infinity was actually what was meant. Just let
* the range that this would extend to have no end */
invlist_set_len(invlist, len - 1, offset);
}
return;
}
}
/* Here the new range doesn't extend any existing set. Add it */
len += 2; /* Includes an element each for the start and end of range */
/* If wll overflow the existing space, extend, which may cause the array to
* be moved */
if (max < len) {
invlist_extend(invlist, len);
/* Have to set len here to avoid assert failure in invlist_array() */
invlist_set_len(invlist, len, offset);
array = invlist_array(invlist);
}
else {
invlist_set_len(invlist, len, offset);
}
/* The next item on the list starts the range, the one after that is
* one past the new range. */
array[len - 2] = start;
if (end != UV_MAX) {
array[len - 1] = end + 1;
}
else {
/* But if the end is the maximum representable on the machine, just let
* the range have no end */
invlist_set_len(invlist, len - 1, offset);
}
}
SSize_t
Perl__invlist_search(SV* const invlist, const UV cp)
{
/* Searches the inversion list for the entry that contains the input code
* point <cp>. If <cp> is not in the list, -1 is returned. Otherwise, the
* return value is the index into the list's array of the range that
* contains <cp>, that is, 'i' such that
* array[i] <= cp < array[i+1]
*/
IV low = 0;
IV mid;
IV high = _invlist_len(invlist);
const IV highest_element = high - 1;
const UV* array;
PERL_ARGS_ASSERT__INVLIST_SEARCH;
/* If list is empty, return failure. */
if (high == 0) {
return -1;
}
/* (We can't get the array unless we know the list is non-empty) */
array = invlist_array(invlist);
mid = invlist_previous_index(invlist);
assert(mid >=0);
if (mid > highest_element) {
mid = highest_element;
}
/* <mid> contains the cache of the result of the previous call to this
* function (0 the first time). See if this call is for the same result,
* or if it is for mid-1. This is under the theory that calls to this
* function will often be for related code points that are near each other.
* And benchmarks show that caching gives better results. We also test
* here if the code point is within the bounds of the list. These tests
* replace others that would have had to be made anyway to make sure that
* the array bounds were not exceeded, and these give us extra information
* at the same time */
if (cp >= array[mid]) {
if (cp >= array[highest_element]) {
return highest_element;
}
/* Here, array[mid] <= cp < array[highest_element]. This means that
* the final element is not the answer, so can exclude it; it also
* means that <mid> is not the final element, so can refer to 'mid + 1'
* safely */
if (cp < array[mid + 1]) {
return mid;
}
high--;
low = mid + 1;
}
else { /* cp < aray[mid] */
if (cp < array[0]) { /* Fail if outside the array */
return -1;
}
high = mid;
if (cp >= array[mid - 1]) {
goto found_entry;
}
}
/* Binary search. What we are looking for is <i> such that
* array[i] <= cp < array[i+1]
* The loop below converges on the i+1. Note that there may not be an
* (i+1)th element in the array, and things work nonetheless */
while (low < high) {
mid = (low + high) / 2;
assert(mid <= highest_element);
if (array[mid] <= cp) { /* cp >= array[mid] */
low = mid + 1;
/* We could do this extra test to exit the loop early.
if (cp < array[low]) {
return mid;
}
*/
}
else { /* cp < array[mid] */
high = mid;
}
}
found_entry:
high--;
invlist_set_previous_index(invlist, high);
return high;
}
void
Perl__invlist_union_maybe_complement_2nd(pTHX_ SV* const a, SV* const b,
const bool complement_b, SV** output)
{
/* Take the union of two inversion lists and point '*output' to it. On
* input, '*output' MUST POINT TO NULL OR TO AN SV* INVERSION LIST (possibly
* even 'a' or 'b'). If to an inversion list, the contents of the original
* list will be replaced by the union. The first list, 'a', may be
* NULL, in which case a copy of the second list is placed in '*output'.
* If 'complement_b' is TRUE, the union is taken of the complement
* (inversion) of 'b' instead of b itself.
*
* The basis for this comes from "Unicode Demystified" Chapter 13 by
* Richard Gillam, published by Addison-Wesley, and explained at some
* length there. The preface says to incorporate its examples into your
* code at your own risk.
*
* The algorithm is like a merge sort. */
const UV* array_a; /* a's array */
const UV* array_b;
UV len_a; /* length of a's array */
UV len_b;
SV* u; /* the resulting union */
UV* array_u;
UV len_u = 0;
UV i_a = 0; /* current index into a's array */
UV i_b = 0;
UV i_u = 0;
/* running count, as explained in the algorithm source book; items are
* stopped accumulating and are output when the count changes to/from 0.
* The count is incremented when we start a range that's in an input's set,
* and decremented when we start a range that's not in a set. So this
* variable can be 0, 1, or 2. When it is 0 neither input is in their set,
* and hence nothing goes into the union; 1, just one of the inputs is in
* its set (and its current range gets added to the union); and 2 when both
* inputs are in their sets. */
UV count = 0;
PERL_ARGS_ASSERT__INVLIST_UNION_MAYBE_COMPLEMENT_2ND;
assert(a != b);
assert(*output == NULL || is_invlist(*output));
len_b = _invlist_len(b);
if (len_b == 0) {
/* Here, 'b' is empty, hence it's complement is all possible code
* points. So if the union includes the complement of 'b', it includes
* everything, and we need not even look at 'a'. It's easiest to
* create a new inversion list that matches everything. */
if (complement_b) {
SV* everything = _add_range_to_invlist(NULL, 0, UV_MAX);
if (*output == NULL) { /* If the output didn't exist, just point it
at the new list */
*output = everything;
}
else { /* Otherwise, replace its contents with the new list */
invlist_replace_list_destroys_src(*output, everything);
SvREFCNT_dec_NN(everything);
}
return;
}
/* Here, we don't want the complement of 'b', and since 'b' is empty,
* the union will come entirely from 'a'. If 'a' is NULL or empty, the
* output will be empty */
if (a == NULL || _invlist_len(a) == 0) {
if (*output == NULL) {
*output = _new_invlist(0);
}
else {
invlist_clear(*output);
}
return;
}
/* Here, 'a' is not empty, but 'b' is, so 'a' entirely determines the
* union. We can just return a copy of 'a' if '*output' doesn't point
* to an existing list */
if (*output == NULL) {
*output = invlist_clone(a, NULL);
return;
}
/* If the output is to overwrite 'a', we have a no-op, as it's
* already in 'a' */
if (*output == a) {
return;
}
/* Here, '*output' is to be overwritten by 'a' */
u = invlist_clone(a, NULL);
invlist_replace_list_destroys_src(*output, u);
SvREFCNT_dec_NN(u);
return;
}
/* Here 'b' is not empty. See about 'a' */
if (a == NULL || ((len_a = _invlist_len(a)) == 0)) {
/* Here, 'a' is empty (and b is not). That means the union will come
* entirely from 'b'. If '*output' is NULL, we can directly return a
* clone of 'b'. Otherwise, we replace the contents of '*output' with
* the clone */
SV ** dest = (*output == NULL) ? output : &u;
*dest = invlist_clone(b, NULL);
if (complement_b) {
_invlist_invert(*dest);
}
if (dest == &u) {
invlist_replace_list_destroys_src(*output, u);
SvREFCNT_dec_NN(u);
}
return;
}
/* Here both lists exist and are non-empty */
array_a = invlist_array(a);
array_b = invlist_array(b);
/* If are to take the union of 'a' with the complement of b, set it
* up so are looking at b's complement. */
if (complement_b) {
/* To complement, we invert: if the first element is 0, remove it. To
* do this, we just pretend the array starts one later */
if (array_b[0] == 0) {
array_b++;
len_b--;
}
else {
/* But if the first element is not zero, we pretend the list starts
* at the 0 that is always stored immediately before the array. */
array_b--;
len_b++;
}
}
/* Size the union for the worst case: that the sets are completely
* disjoint */
u = _new_invlist(len_a + len_b);
/* Will contain U+0000 if either component does */
array_u = _invlist_array_init(u, ( len_a > 0 && array_a[0] == 0)
|| (len_b > 0 && array_b[0] == 0));
/* Go through each input list item by item, stopping when have exhausted
* one of them */
while (i_a < len_a && i_b < len_b) {
UV cp; /* The element to potentially add to the union's array */
bool cp_in_set; /* is it in the the input list's set or not */
/* We need to take one or the other of the two inputs for the union.
* Since we are merging two sorted lists, we take the smaller of the
* next items. In case of a tie, we take first the one that is in its
* set. If we first took the one not in its set, it would decrement
* the count, possibly to 0 which would cause it to be output as ending
* the range, and the next time through we would take the same number,
* and output it again as beginning the next range. By doing it the
* opposite way, there is no possibility that the count will be
* momentarily decremented to 0, and thus the two adjoining ranges will
* be seamlessly merged. (In a tie and both are in the set or both not
* in the set, it doesn't matter which we take first.) */
if ( array_a[i_a] < array_b[i_b]
|| ( array_a[i_a] == array_b[i_b]
&& ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
{
cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
cp = array_a[i_a++];
}
else {
cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
cp = array_b[i_b++];
}
/* Here, have chosen which of the two inputs to look at. Only output
* if the running count changes to/from 0, which marks the
* beginning/end of a range that's in the set */
if (cp_in_set) {
if (count == 0) {
array_u[i_u++] = cp;
}
count++;
}
else {
count--;
if (count == 0) {
array_u[i_u++] = cp;
}
}
}
/* The loop above increments the index into exactly one of the input lists
* each iteration, and ends when either index gets to its list end. That
* means the other index is lower than its end, and so something is
* remaining in that one. We decrement 'count', as explained below, if
* that list is in its set. (i_a and i_b each currently index the element
* beyond the one we care about.) */
if ( (i_a != len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
|| (i_b != len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
{
count--;
}
/* Above we decremented 'count' if the list that had unexamined elements in
* it was in its set. This has made it so that 'count' being non-zero
* means there isn't anything left to output; and 'count' equal to 0 means
* that what is left to output is precisely that which is left in the
* non-exhausted input list.
*
* To see why, note first that the exhausted input obviously has nothing
* left to add to the union. If it was in its set at its end, that means
* the set extends from here to the platform's infinity, and hence so does
* the union and the non-exhausted set is irrelevant. The exhausted set
* also contributed 1 to 'count'. If 'count' was 2, it got decremented to
* 1, but if it was 1, the non-exhausted set wasn't in its set, and so
* 'count' remains at 1. This is consistent with the decremented 'count'
* != 0 meaning there's nothing left to add to the union.
*
* But if the exhausted input wasn't in its set, it contributed 0 to
* 'count', and the rest of the union will be whatever the other input is.
* If 'count' was 0, neither list was in its set, and 'count' remains 0;
* otherwise it gets decremented to 0. This is consistent with 'count'
* == 0 meaning the remainder of the union is whatever is left in the
* non-exhausted list. */
if (count != 0) {
len_u = i_u;
}
else {
IV copy_count = len_a - i_a;
if (copy_count > 0) { /* The non-exhausted input is 'a' */
Copy(array_a + i_a, array_u + i_u, copy_count, UV);
}
else { /* The non-exhausted input is b */
copy_count = len_b - i_b;
Copy(array_b + i_b, array_u + i_u, copy_count, UV);
}
len_u = i_u + copy_count;
}
/* Set the result to the final length, which can change the pointer to
* array_u, so re-find it. (Note that it is unlikely that this will
* change, as we are shrinking the space, not enlarging it) */
if (len_u != _invlist_len(u)) {
invlist_set_len(u, len_u, *get_invlist_offset_addr(u));
invlist_trim(u);
array_u = invlist_array(u);
}
if (*output == NULL) { /* Simply return the new inversion list */
*output = u;
}
else {
/* Otherwise, overwrite the inversion list that was in '*output'. We
* could instead free '*output', and then set it to 'u', but experience
* has shown [perl #127392] that if the input is a mortal, we can get a
* huge build-up of these during regex compilation before they get
* freed. */
invlist_replace_list_destroys_src(*output, u);
SvREFCNT_dec_NN(u);
}
return;
}
void
Perl__invlist_intersection_maybe_complement_2nd(pTHX_ SV* const a, SV* const b,
const bool complement_b, SV** i)
{
/* Take the intersection of two inversion lists and point '*i' to it. On
* input, '*i' MUST POINT TO NULL OR TO AN SV* INVERSION LIST (possibly
* even 'a' or 'b'). If to an inversion list, the contents of the original
* list will be replaced by the intersection. The first list, 'a', may be
* NULL, in which case '*i' will be an empty list. If 'complement_b' is
* TRUE, the result will be the intersection of 'a' and the complement (or
* inversion) of 'b' instead of 'b' directly.
*
* The basis for this comes from "Unicode Demystified" Chapter 13 by
* Richard Gillam, published by Addison-Wesley, and explained at some
* length there. The preface says to incorporate its examples into your
* code at your own risk. In fact, it had bugs
*
* The algorithm is like a merge sort, and is essentially the same as the
* union above
*/
const UV* array_a; /* a's array */
const UV* array_b;
UV len_a; /* length of a's array */
UV len_b;
SV* r; /* the resulting intersection */
UV* array_r;
UV len_r = 0;
UV i_a = 0; /* current index into a's array */
UV i_b = 0;
UV i_r = 0;
/* running count of how many of the two inputs are postitioned at ranges
* that are in their sets. As explained in the algorithm source book,
* items are stopped accumulating and are output when the count changes
* to/from 2. The count is incremented when we start a range that's in an
* input's set, and decremented when we start a range that's not in a set.
* Only when it is 2 are we in the intersection. */
UV count = 0;
PERL_ARGS_ASSERT__INVLIST_INTERSECTION_MAYBE_COMPLEMENT_2ND;
assert(a != b);
assert(*i == NULL || is_invlist(*i));
/* Special case if either one is empty */
len_a = (a == NULL) ? 0 : _invlist_len(a);
if ((len_a == 0) || ((len_b = _invlist_len(b)) == 0)) {
if (len_a != 0 && complement_b) {
/* Here, 'a' is not empty, therefore from the enclosing 'if', 'b'
* must be empty. Here, also we are using 'b's complement, which
* hence must be every possible code point. Thus the intersection
* is simply 'a'. */
if (*i == a) { /* No-op */
return;
}
if (*i == NULL) {
*i = invlist_clone(a, NULL);
return;
}
r = invlist_clone(a, NULL);
invlist_replace_list_destroys_src(*i, r);
SvREFCNT_dec_NN(r);
return;
}
/* Here, 'a' or 'b' is empty and not using the complement of 'b'. The
* intersection must be empty */
if (*i == NULL) {
*i = _new_invlist(0);
return;
}
invlist_clear(*i);
return;
}
/* Here both lists exist and are non-empty */
array_a = invlist_array(a);
array_b = invlist_array(b);
/* If are to take the intersection of 'a' with the complement of b, set it
* up so are looking at b's complement. */
if (complement_b) {
/* To complement, we invert: if the first element is 0, remove it. To
* do this, we just pretend the array starts one later */
if (array_b[0] == 0) {
array_b++;
len_b--;
}
else {
/* But if the first element is not zero, we pretend the list starts
* at the 0 that is always stored immediately before the array. */
array_b--;
len_b++;
}
}
/* Size the intersection for the worst case: that the intersection ends up
* fragmenting everything to be completely disjoint */
r= _new_invlist(len_a + len_b);
/* Will contain U+0000 iff both components do */
array_r = _invlist_array_init(r, len_a > 0 && array_a[0] == 0
&& len_b > 0 && array_b[0] == 0);
/* Go through each list item by item, stopping when have exhausted one of
* them */
while (i_a < len_a && i_b < len_b) {
UV cp; /* The element to potentially add to the intersection's
array */
bool cp_in_set; /* Is it in the input list's set or not */
/* We need to take one or the other of the two inputs for the
* intersection. Since we are merging two sorted lists, we take the
* smaller of the next items. In case of a tie, we take first the one
* that is not in its set (a difference from the union algorithm). If
* we first took the one in its set, it would increment the count,
* possibly to 2 which would cause it to be output as starting a range
* in the intersection, and the next time through we would take that
* same number, and output it again as ending the set. By doing the
* opposite of this, there is no possibility that the count will be
* momentarily incremented to 2. (In a tie and both are in the set or
* both not in the set, it doesn't matter which we take first.) */
if ( array_a[i_a] < array_b[i_b]
|| ( array_a[i_a] == array_b[i_b]
&& ! ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
{
cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
cp = array_a[i_a++];
}
else {
cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
cp= array_b[i_b++];
}
/* Here, have chosen which of the two inputs to look at. Only output
* if the running count changes to/from 2, which marks the
* beginning/end of a range that's in the intersection */
if (cp_in_set) {
count++;
if (count == 2) {
array_r[i_r++] = cp;
}
}
else {
if (count == 2) {
array_r[i_r++] = cp;
}
count--;
}
}
/* The loop above increments the index into exactly one of the input lists
* each iteration, and ends when either index gets to its list end. That
* means the other index is lower than its end, and so something is
* remaining in that one. We increment 'count', as explained below, if the
* exhausted list was in its set. (i_a and i_b each currently index the
* element beyond the one we care about.) */
if ( (i_a == len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
|| (i_b == len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
{
count++;
}
/* Above we incremented 'count' if the exhausted list was in its set. This
* has made it so that 'count' being below 2 means there is nothing left to
* output; otheriwse what's left to add to the intersection is precisely
* that which is left in the non-exhausted input list.
*
* To see why, note first that the exhausted input obviously has nothing
* left to affect the intersection. If it was in its set at its end, that
* means the set extends from here to the platform's infinity, and hence
* anything in the non-exhausted's list will be in the intersection, and
* anything not in it won't be. Hence, the rest of the intersection is
* precisely what's in the non-exhausted list The exhausted set also
* contributed 1 to 'count', meaning 'count' was at least 1. Incrementing
* it means 'count' is now at least 2. This is consistent with the
* incremented 'count' being >= 2 means to add the non-exhausted list to
* the intersection.
*
* But if the exhausted input wasn't in its set, it contributed 0 to
* 'count', and the intersection can't include anything further; the
* non-exhausted set is irrelevant. 'count' was at most 1, and doesn't get
* incremented. This is consistent with 'count' being < 2 meaning nothing
* further to add to the intersection. */
if (count < 2) { /* Nothing left to put in the intersection. */
len_r = i_r;
}
else { /* copy the non-exhausted list, unchanged. */
IV copy_count = len_a - i_a;
if (copy_count > 0) { /* a is the one with stuff left */
Copy(array_a + i_a, array_r + i_r, copy_count, UV);
}
else { /* b is the one with stuff left */
copy_count = len_b - i_b;
Copy(array_b + i_b, array_r + i_r, copy_count, UV);
}
len_r = i_r + copy_count;
}
/* Set the result to the final length, which can change the pointer to
* array_r, so re-find it. (Note that it is unlikely that this will
* change, as we are shrinking the space, not enlarging it) */
if (len_r != _invlist_len(r)) {
invlist_set_len(r, len_r, *get_invlist_offset_addr(r));
invlist_trim(r);
array_r = invlist_array(r);
}
if (*i == NULL) { /* Simply return the calculated intersection */
*i = r;
}
else { /* Otherwise, replace the existing inversion list in '*i'. We could
instead free '*i', and then set it to 'r', but experience has
shown [perl #127392] that if the input is a mortal, we can get a
huge build-up of these during regex compilation before they get
freed. */
if (len_r) {
invlist_replace_list_destroys_src(*i, r);
}
else {
invlist_clear(*i);
}
SvREFCNT_dec_NN(r);
}
return;
}
SV*
Perl__add_range_to_invlist(pTHX_ SV* invlist, UV start, UV end)
{
/* Add the range from 'start' to 'end' inclusive to the inversion list's
* set. A pointer to the inversion list is returned. This may actually be
* a new list, in which case the passed in one has been destroyed. The
* passed-in inversion list can be NULL, in which case a new one is created
* with just the one range in it. The new list is not necessarily
* NUL-terminated. Space is not freed if the inversion list shrinks as a
* result of this function. The gain would not be large, and in many
* cases, this is called multiple times on a single inversion list, so
* anything freed may almost immediately be needed again.
*
* This used to mostly call the 'union' routine, but that is much more
* heavyweight than really needed for a single range addition */
UV* array; /* The array implementing the inversion list */
UV len; /* How many elements in 'array' */
SSize_t i_s; /* index into the invlist array where 'start'
should go */
SSize_t i_e = 0; /* And the index where 'end' should go */
UV cur_highest; /* The highest code point in the inversion list
upon entry to this function */
/* This range becomes the whole inversion list if none already existed */
if (invlist == NULL) {
invlist = _new_invlist(2);
_append_range_to_invlist(invlist, start, end);
return invlist;
}
/* Likewise, if the inversion list is currently empty */
len = _invlist_len(invlist);
if (len == 0) {
_append_range_to_invlist(invlist, start, end);
return invlist;
}
/* Starting here, we have to know the internals of the list */
array = invlist_array(invlist);
/* If the new range ends higher than the current highest ... */
cur_highest = invlist_highest(invlist);
if (end > cur_highest) {
/* If the whole range is higher, we can just append it */
if (start > cur_highest) {
_append_range_to_invlist(invlist, start, end);
return invlist;
}
/* Otherwise, add the portion that is higher ... */
_append_range_to_invlist(invlist, cur_highest + 1, end);
/* ... and continue on below to handle the rest. As a result of the
* above append, we know that the index of the end of the range is the
* final even numbered one of the array. Recall that the final element
* always starts a range that extends to infinity. If that range is in
* the set (meaning the set goes from here to infinity), it will be an
* even index, but if it isn't in the set, it's odd, and the final
* range in the set is one less, which is even. */
if (end == UV_MAX) {
i_e = len;
}
else {
i_e = len - 2;
}
}
/* We have dealt with appending, now see about prepending. If the new
* range starts lower than the current lowest ... */
if (start < array[0]) {
/* Adding something which has 0 in it is somewhat tricky, and uncommon.
* Let the union code handle it, rather than having to know the
* trickiness in two code places. */
if (UNLIKELY(start == 0)) {
SV* range_invlist;
range_invlist = _new_invlist(2);
_append_range_to_invlist(range_invlist, start, end);
_invlist_union(invlist, range_invlist, &invlist);
SvREFCNT_dec_NN(range_invlist);
return invlist;
}
/* If the whole new range comes before the first entry, and doesn't
* extend it, we have to insert it as an additional range */
if (end < array[0] - 1) {
i_s = i_e = -1;
goto splice_in_new_range;
}
/* Here the new range adjoins the existing first range, extending it
* downwards. */
array[0] = start;
/* And continue on below to handle the rest. We know that the index of
* the beginning of the range is the first one of the array */
i_s = 0;
}
else { /* Not prepending any part of the new range to the existing list.
* Find where in the list it should go. This finds i_s, such that:
* invlist[i_s] <= start < array[i_s+1]
*/
i_s = _invlist_search(invlist, start);
}
/* At this point, any extending before the beginning of the inversion list
* and/or after the end has been done. This has made it so that, in the
* code below, each endpoint of the new range is either in a range that is
* in the set, or is in a gap between two ranges that are. This means we
* don't have to worry about exceeding the array bounds.
*
* Find where in the list the new range ends (but we can skip this if we
* have already determined what it is, or if it will be the same as i_s,
* which we already have computed) */
if (i_e == 0) {
i_e = (start == end)
? i_s
: _invlist_search(invlist, end);
}
/* Here generally invlist[i_e] <= end < array[i_e+1]. But if invlist[i_e]
* is a range that goes to infinity there is no element at invlist[i_e+1],
* so only the first relation holds. */
if ( ! ELEMENT_RANGE_MATCHES_INVLIST(i_s)) {
/* Here, the ranges on either side of the beginning of the new range
* are in the set, and this range starts in the gap between them.
*
* The new range extends the range above it downwards if the new range
* ends at or above that range's start */
const bool extends_the_range_above = ( end == UV_MAX
|| end + 1 >= array[i_s+1]);
/* The new range extends the range below it upwards if it begins just
* after where that range ends */
if (start == array[i_s]) {
/* If the new range fills the entire gap between the other ranges,
* they will get merged together. Other ranges may also get
* merged, depending on how many of them the new range spans. In
* the general case, we do the merge later, just once, after we
* figure out how many to merge. But in the case where the new
* range exactly spans just this one gap (possibly extending into
* the one above), we do the merge here, and an early exit. This
* is done here to avoid having to special case later. */
if (i_e - i_s <= 1) {
/* If i_e - i_s == 1, it means that the new range terminates
* within the range above, and hence 'extends_the_range_above'
* must be true. (If the range above it extends to infinity,
* 'i_s+2' will be above the array's limit, but 'len-i_s-2'
* will be 0, so no harm done.) */
if (extends_the_range_above) {
Move(array + i_s + 2, array + i_s, len - i_s - 2, UV);
invlist_set_len(invlist,
len - 2,
*(get_invlist_offset_addr(invlist)));
return invlist;
}
/* Here, i_e must == i_s. We keep them in sync, as they apply
* to the same range, and below we are about to decrement i_s
* */
i_e--;
}
/* Here, the new range is adjacent to the one below. (It may also
* span beyond the range above, but that will get resolved later.)
* Extend the range below to include this one. */
array[i_s] = (end == UV_MAX) ? UV_MAX : end + 1;
i_s--;
start = array[i_s];
}
else if (extends_the_range_above) {
/* Here the new range only extends the range above it, but not the
* one below. It merges with the one above. Again, we keep i_e
* and i_s in sync if they point to the same range */
if (i_e == i_s) {
i_e++;
}
i_s++;
array[i_s] = start;
}
}
/* Here, we've dealt with the new range start extending any adjoining
* existing ranges.
*
* If the new range extends to infinity, it is now the final one,
* regardless of what was there before */
if (UNLIKELY(end == UV_MAX)) {
invlist_set_len(invlist, i_s + 1, *(get_invlist_offset_addr(invlist)));
return invlist;
}
/* If i_e started as == i_s, it has also been dealt with,
* and been updated to the new i_s, which will fail the following if */
if (! ELEMENT_RANGE_MATCHES_INVLIST(i_e)) {
/* Here, the ranges on either side of the end of the new range are in
* the set, and this range ends in the gap between them.
*
* If this range is adjacent to (hence extends) the range above it, it
* becomes part of that range; likewise if it extends the range below,
* it becomes part of that range */
if (end + 1 == array[i_e+1]) {
i_e++;
array[i_e] = start;
}
else if (start <= array[i_e]) {
array[i_e] = end + 1;
i_e--;
}
}
if (i_s == i_e) {
/* If the range fits entirely in an existing range (as possibly already
* extended above), it doesn't add anything new */
if (ELEMENT_RANGE_MATCHES_INVLIST(i_s)) {
return invlist;
}
/* Here, no part of the range is in the list. Must add it. It will
* occupy 2 more slots */
splice_in_new_range:
invlist_extend(invlist, len + 2);
array = invlist_array(invlist);
/* Move the rest of the array down two slots. Don't include any
* trailing NUL */
Move(array + i_e + 1, array + i_e + 3, len - i_e - 1, UV);
/* Do the actual splice */
array[i_e+1] = start;
array[i_e+2] = end + 1;
invlist_set_len(invlist, len + 2, *(get_invlist_offset_addr(invlist)));
return invlist;
}
/* Here the new range crossed the boundaries of a pre-existing range. The
* code above has adjusted things so that both ends are in ranges that are
* in the set. This means everything in between must also be in the set.
* Just squash things together */
Move(array + i_e + 1, array + i_s + 1, len - i_e - 1, UV);
invlist_set_len(invlist,
len - i_e + i_s,
*(get_invlist_offset_addr(invlist)));
return invlist;
}
SV*
Perl__setup_canned_invlist(pTHX_ const STRLEN size, const UV element0,
UV** other_elements_ptr)
{
/* Create and return an inversion list whose contents are to be populated
* by the caller. The caller gives the number of elements (in 'size') and
* the very first element ('element0'). This function will set
* '*other_elements_ptr' to an array of UVs, where the remaining elements
* are to be placed.
*
* Obviously there is some trust involved that the caller will properly
* fill in the other elements of the array.
*
* (The first element needs to be passed in, as the underlying code does
* things differently depending on whether it is zero or non-zero) */
SV* invlist = _new_invlist(size);
bool offset;
PERL_ARGS_ASSERT__SETUP_CANNED_INVLIST;
invlist = add_cp_to_invlist(invlist, element0);
offset = *get_invlist_offset_addr(invlist);
invlist_set_len(invlist, size, offset);
*other_elements_ptr = invlist_array(invlist) + 1;
return invlist;
}
#endif
PERL_STATIC_INLINE SV*
S_add_cp_to_invlist(pTHX_ SV* invlist, const UV cp) {
return _add_range_to_invlist(invlist, cp, cp);
}
#ifndef PERL_IN_XSUB_RE
void
Perl__invlist_invert(pTHX_ SV* const invlist)
{
/* Complement the input inversion list. This adds a 0 if the list didn't
* have a zero; removes it otherwise. As described above, the data
* structure is set up so that this is very efficient */
PERL_ARGS_ASSERT__INVLIST_INVERT;
assert(! invlist_is_iterating(invlist));
/* The inverse of matching nothing is matching everything */
if (_invlist_len(invlist) == 0) {
_append_range_to_invlist(invlist, 0, UV_MAX);
return;
}
*get_invlist_offset_addr(invlist) = ! *get_invlist_offset_addr(invlist);
}
SV*
Perl_invlist_clone(pTHX_ SV* const invlist, SV* new_invlist)
{
/* Return a new inversion list that is a copy of the input one, which is
* unchanged. The new list will not be mortal even if the old one was. */
const STRLEN nominal_length = _invlist_len(invlist);
const STRLEN physical_length = SvCUR(invlist);
const bool offset = *(get_invlist_offset_addr(invlist));
PERL_ARGS_ASSERT_INVLIST_CLONE;
if (new_invlist == NULL) {
new_invlist = _new_invlist(nominal_length);
}
else {
sv_upgrade(new_invlist, SVt_INVLIST);
initialize_invlist_guts(new_invlist, nominal_length);
}
*(get_invlist_offset_addr(new_invlist)) = offset;
invlist_set_len(new_invlist, nominal_length, offset);
Copy(SvPVX(invlist), SvPVX(new_invlist), physical_length, char);
return new_invlist;
}
#endif
PERL_STATIC_INLINE STRLEN*
S_get_invlist_iter_addr(SV* invlist)
{
/* Return the address of the UV that contains the current iteration
* position */
PERL_ARGS_ASSERT_GET_INVLIST_ITER_ADDR;
assert(is_invlist(invlist));
return &(((XINVLIST*) SvANY(invlist))->iterator);
}
PERL_STATIC_INLINE void
S_invlist_iterinit(SV* invlist) /* Initialize iterator for invlist */
{
PERL_ARGS_ASSERT_INVLIST_ITERINIT;
*get_invlist_iter_addr(invlist) = 0;
}
PERL_STATIC_INLINE void
S_invlist_iterfinish(SV* invlist)
{
/* Terminate iterator for invlist. This is to catch development errors.
* Any iteration that is interrupted before completed should call this
* function. Functions that add code points anywhere else but to the end
* of an inversion list assert that they are not in the middle of an
* iteration. If they were, the addition would make the iteration
* problematical: if the iteration hadn't reached the place where things
* were being added, it would be ok */
PERL_ARGS_ASSERT_INVLIST_ITERFINISH;
*get_invlist_iter_addr(invlist) = (STRLEN) UV_MAX;
}
STATIC bool
S_invlist_iternext(SV* invlist, UV* start, UV* end)
{
/* An C<invlist_iterinit> call on <invlist> must be used to set this up.
* This call sets in <*start> and <*end>, the next range in <invlist>.
* Returns <TRUE> if successful and the next call will return the next
* range; <FALSE> if was already at the end of the list. If the latter,
* <*start> and <*end> are unchanged, and the next call to this function
* will start over at the beginning of the list */
STRLEN* pos = get_invlist_iter_addr(invlist);
UV len = _invlist_len(invlist);
UV *array;
PERL_ARGS_ASSERT_INVLIST_ITERNEXT;
if (*pos >= len) {
*pos = (STRLEN) UV_MAX; /* Force iterinit() to be required next time */
return FALSE;
}
array = invlist_array(invlist);
*start = array[(*pos)++];
if (*pos >= len) {
*end = UV_MAX;
}
else {
*end = array[(*pos)++] - 1;
}
return TRUE;
}
PERL_STATIC_INLINE UV
S_invlist_highest(SV* const invlist)
{
/* Returns the highest code point that matches an inversion list. This API
* has an ambiguity, as it returns 0 under either the highest is actually
* 0, or if the list is empty. If this distinction matters to you, check
* for emptiness before calling this function */
UV len = _invlist_len(invlist);
UV *array;
PERL_ARGS_ASSERT_INVLIST_HIGHEST;
if (len == 0) {
return 0;
}
array = invlist_array(invlist);
/* The last element in the array in the inversion list always starts a
* range that goes to infinity. That range may be for code points that are
* matched in the inversion list, or it may be for ones that aren't
* matched. In the latter case, the highest code point in the set is one
* less than the beginning of this range; otherwise it is the final element
* of this range: infinity */
return (ELEMENT_RANGE_MATCHES_INVLIST(len - 1))
? UV_MAX
: array[len - 1] - 1;
}
STATIC SV *
S_invlist_contents(pTHX_ SV* const invlist, const bool traditional_style)
{
/* Get the contents of an inversion list into a string SV so that they can
* be printed out. If 'traditional_style' is TRUE, it uses the format
* traditionally done for debug tracing; otherwise it uses a format
* suitable for just copying to the output, with blanks between ranges and
* a dash between range components */
UV start, end;
SV* output;
const char intra_range_delimiter = (traditional_style ? '\t' : '-');
const char inter_range_delimiter = (traditional_style ? '\n' : ' ');
if (traditional_style) {
output = newSVpvs("\n");
}
else {
output = newSVpvs("");
}
PERL_ARGS_ASSERT_INVLIST_CONTENTS;
assert(! invlist_is_iterating(invlist));
invlist_iterinit(invlist);
while (invlist_iternext(invlist, &start, &end)) {
if (end == UV_MAX) {
Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%cINFTY%c",
start, intra_range_delimiter,
inter_range_delimiter);
}
else if (end != start) {
Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%c%04" UVXf "%c",
start,
intra_range_delimiter,
end, inter_range_delimiter);
}
else {
Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%c",
start, inter_range_delimiter);
}
}
if (SvCUR(output) && ! traditional_style) {/* Get rid of trailing blank */
SvCUR_set(output, SvCUR(output) - 1);
}
return output;
}
#ifndef PERL_IN_XSUB_RE
void
Perl__invlist_dump(pTHX_ PerlIO *file, I32 level,
const char * const indent, SV* const invlist)
{
/* Designed to be called only by do_sv_dump(). Dumps out the ranges of the
* inversion list 'invlist' to 'file' at 'level' Each line is prefixed by
* the string 'indent'. The output looks like this:
[0] 0x000A .. 0x000D
[2] 0x0085
[4] 0x2028 .. 0x2029
[6] 0x3104 .. INFTY
* This means that the first range of code points matched by the list are
* 0xA through 0xD; the second range contains only the single code point
* 0x85, etc. An inversion list is an array of UVs. Two array elements
* are used to define each range (except if the final range extends to
* infinity, only a single element is needed). The array index of the
* first element for the corresponding range is given in brackets. */
UV start, end;
STRLEN count = 0;
PERL_ARGS_ASSERT__INVLIST_DUMP;
if (invlist_is_iterating(invlist)) {
Perl_dump_indent(aTHX_ level, file,
"%sCan't dump inversion list because is in middle of iterating\n",
indent);
return;
}
invlist_iterinit(invlist);
while (invlist_iternext(invlist, &start, &end)) {
if (end == UV_MAX) {
Perl_dump_indent(aTHX_ level, file,
"%s[%" UVuf "] 0x%04" UVXf " .. INFTY\n",
indent, (UV)count, start);
}
else if (end != start) {
Perl_dump_indent(aTHX_ level, file,
"%s[%" UVuf "] 0x%04" UVXf " .. 0x%04" UVXf "\n",
indent, (UV)count, start, end);
}
else {
Perl_dump_indent(aTHX_ level, file, "%s[%" UVuf "] 0x%04" UVXf "\n",
indent, (UV)count, start);
}
count += 2;
}
}
#endif
#if defined(PERL_ARGS_ASSERT__INVLISTEQ) && !defined(PERL_IN_XSUB_RE)
bool
Perl__invlistEQ(pTHX_ SV* const a, SV* const b, const bool complement_b)
{
/* Return a boolean as to if the two passed in inversion lists are
* identical. The final argument, if TRUE, says to take the complement of
* the second inversion list before doing the comparison */
const UV len_a = _invlist_len(a);
UV len_b = _invlist_len(b);
const UV* array_a = NULL;
const UV* array_b = NULL;
PERL_ARGS_ASSERT__INVLISTEQ;
/* This code avoids accessing the arrays unless it knows the length is
* non-zero */
if (len_a == 0) {
if (len_b == 0) {
return ! complement_b;
}
}
else {
array_a = invlist_array(a);
}
if (len_b != 0) {
array_b = invlist_array(b);
}
/* If are to compare 'a' with the complement of b, set it
* up so are looking at b's complement. */
if (complement_b) {
/* The complement of nothing is everything, so <a> would have to have
* just one element, starting at zero (ending at infinity) */
if (len_b == 0) {
return (len_a == 1 && array_a[0] == 0);
}
if (array_b[0] == 0) {
/* Otherwise, to complement, we invert. Here, the first element is
* 0, just remove it. To do this, we just pretend the array starts
* one later */
array_b++;
len_b--;
}
else {
/* But if the first element is not zero, we pretend the list starts
* at the 0 that is always stored immediately before the array. */
array_b--;
len_b++;
}
}
return len_a == len_b
&& memEQ(array_a, array_b, len_a * sizeof(array_a[0]));
}
#endif
/*
* As best we can, determine the characters that can match the start of
* the given EXACTF-ish node. This is for use in creating ssc nodes, so there
* can be false positive matches
*
* Returns the invlist as a new SV*; it is the caller's responsibility to
* call SvREFCNT_dec() when done with it.
*/
STATIC SV*
S__make_exactf_invlist(pTHX_ RExC_state_t *pRExC_state, regnode *node)
{
dVAR;
const U8 * s = (U8*)STRING(node);
SSize_t bytelen = STR_LEN(node);
UV uc;
/* Start out big enough for 2 separate code points */
SV* invlist = _new_invlist(4);
PERL_ARGS_ASSERT__MAKE_EXACTF_INVLIST;
if (! UTF) {
uc = *s;
/* We punt and assume can match anything if the node begins
* with a multi-character fold. Things are complicated. For
* example, /ffi/i could match any of:
* "\N{LATIN SMALL LIGATURE FFI}"
* "\N{LATIN SMALL LIGATURE FF}I"
* "F\N{LATIN SMALL LIGATURE FI}"
* plus several other things; and making sure we have all the
* possibilities is hard. */
if (is_MULTI_CHAR_FOLD_latin1_safe(s, s + bytelen)) {
invlist = _add_range_to_invlist(invlist, 0, UV_MAX);
}
else {
/* Any Latin1 range character can potentially match any
* other depending on the locale, and in Turkic locales, U+130 and
* U+131 */
if (OP(node) == EXACTFL) {
_invlist_union(invlist, PL_Latin1, &invlist);
invlist = add_cp_to_invlist(invlist,
LATIN_SMALL_LETTER_DOTLESS_I);
invlist = add_cp_to_invlist(invlist,
LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE);
}
else {
/* But otherwise, it matches at least itself. We can
* quickly tell if it has a distinct fold, and if so,
* it matches that as well */
invlist = add_cp_to_invlist(invlist, uc);
if (IS_IN_SOME_FOLD_L1(uc))
invlist = add_cp_to_invlist(invlist, PL_fold_latin1[uc]);
}
/* Some characters match above-Latin1 ones under /i. This
* is true of EXACTFL ones when the locale is UTF-8 */
if (HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(uc)
&& (! isASCII(uc) || (OP(node) != EXACTFAA
&& OP(node) != EXACTFAA_NO_TRIE)))
{
add_above_Latin1_folds(pRExC_state, (U8) uc, &invlist);
}
}
}
else { /* Pattern is UTF-8 */
U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' };
const U8* e = s + bytelen;
IV fc;
fc = uc = utf8_to_uvchr_buf(s, s + bytelen, NULL);
/* The only code points that aren't folded in a UTF EXACTFish
* node are are the problematic ones in EXACTFL nodes */
if (OP(node) == EXACTFL && is_PROBLEMATIC_LOCALE_FOLDEDS_START_cp(uc)) {
/* We need to check for the possibility that this EXACTFL
* node begins with a multi-char fold. Therefore we fold
* the first few characters of it so that we can make that
* check */
U8 *d = folded;
int i;
fc = -1;
for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < e; i++) {
if (isASCII(*s)) {
*(d++) = (U8) toFOLD(*s);
if (fc < 0) { /* Save the first fold */
fc = *(d-1);
}
s++;
}
else {
STRLEN len;
UV fold = toFOLD_utf8_safe(s, e, d, &len);
if (fc < 0) { /* Save the first fold */
fc = fold;
}
d += len;
s += UTF8SKIP(s);
}
}
/* And set up so the code below that looks in this folded
* buffer instead of the node's string */
e = d;
s = folded;
}
/* When we reach here 's' points to the fold of the first
* character(s) of the node; and 'e' points to far enough along
* the folded string to be just past any possible multi-char
* fold.
*
* Unlike the non-UTF-8 case, the macro for determining if a
* string is a multi-char fold requires all the characters to
* already be folded. This is because of all the complications
* if not. Note that they are folded anyway, except in EXACTFL
* nodes. Like the non-UTF case above, we punt if the node
* begins with a multi-char fold */
if (is_MULTI_CHAR_FOLD_utf8_safe(s, e)) {
invlist = _add_range_to_invlist(invlist, 0, UV_MAX);
}
else { /* Single char fold */
unsigned int k;
unsigned int first_fold;
const unsigned int * remaining_folds;
Size_t folds_count;
/* It matches itself */
invlist = add_cp_to_invlist(invlist, fc);
/* ... plus all the things that fold to it, which are found in
* PL_utf8_foldclosures */
folds_count = _inverse_folds(fc, &first_fold,
&remaining_folds);
for (k = 0; k < folds_count; k++) {
UV c = (k == 0) ? first_fold : remaining_folds[k-1];
/* /aa doesn't allow folds between ASCII and non- */
if ( (OP(node) == EXACTFAA || OP(node) == EXACTFAA_NO_TRIE)
&& isASCII(c) != isASCII(fc))
{
continue;
}
invlist = add_cp_to_invlist(invlist, c);
}
if (OP(node) == EXACTFL) {
/* If either [iI] are present in an EXACTFL node the above code
* should have added its normal case pair, but under a Turkish
* locale they could match instead the case pairs from it. Add
* those as potential matches as well */
if (isALPHA_FOLD_EQ(fc, 'I')) {
invlist = add_cp_to_invlist(invlist,
LATIN_SMALL_LETTER_DOTLESS_I);
invlist = add_cp_to_invlist(invlist,
LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE);
}
else if (fc == LATIN_SMALL_LETTER_DOTLESS_I) {
invlist = add_cp_to_invlist(invlist, 'I');
}
else if (fc == LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE) {
invlist = add_cp_to_invlist(invlist, 'i');
}
}
}
}
return invlist;
}
#undef HEADER_LENGTH
#undef TO_INTERNAL_SIZE
#undef FROM_INTERNAL_SIZE
#undef INVLIST_VERSION_ID
/* End of inversion list object */
STATIC void
S_parse_lparen_question_flags(pTHX_ RExC_state_t *pRExC_state)
{
/* This parses the flags that are in either the '(?foo)' or '(?foo:bar)'
* constructs, and updates RExC_flags with them. On input, RExC_parse
* should point to the first flag; it is updated on output to point to the
* final ')' or ':'. There needs to be at least one flag, or this will
* abort */
/* for (?g), (?gc), and (?o) warnings; warning
about (?c) will warn about (?g) -- japhy */
#define WASTED_O 0x01
#define WASTED_G 0x02
#define WASTED_C 0x04
#define WASTED_GC (WASTED_G|WASTED_C)
I32 wastedflags = 0x00;
U32 posflags = 0, negflags = 0;
U32 *flagsp = &posflags;
char has_charset_modifier = '\0';
regex_charset cs;
bool has_use_defaults = FALSE;
const char* const seqstart = RExC_parse - 1; /* Point to the '?' */
int x_mod_count = 0;
PERL_ARGS_ASSERT_PARSE_LPAREN_QUESTION_FLAGS;
/* '^' as an initial flag sets certain defaults */
if (UCHARAT(RExC_parse) == '^') {
RExC_parse++;
has_use_defaults = TRUE;
STD_PMMOD_FLAGS_CLEAR(&RExC_flags);
cs = (RExC_uni_semantics)
? REGEX_UNICODE_CHARSET
: REGEX_DEPENDS_CHARSET;
set_regex_charset(&RExC_flags, cs);
}
else {
cs = get_regex_charset(RExC_flags);
if ( cs == REGEX_DEPENDS_CHARSET
&& RExC_uni_semantics)
{
cs = REGEX_UNICODE_CHARSET;
}
}
while (RExC_parse < RExC_end) {
/* && strchr("iogcmsx", *RExC_parse) */
/* (?g), (?gc) and (?o) are useless here
and must be globally applied -- japhy */
switch (*RExC_parse) {
/* Code for the imsxn flags */
CASE_STD_PMMOD_FLAGS_PARSE_SET(flagsp, x_mod_count);
case LOCALE_PAT_MOD:
if (has_charset_modifier) {
goto excess_modifier;
}
else if (flagsp == &negflags) {
goto neg_modifier;
}
cs = REGEX_LOCALE_CHARSET;
has_charset_modifier = LOCALE_PAT_MOD;
break;
case UNICODE_PAT_MOD:
if (has_charset_modifier) {
goto excess_modifier;
}
else if (flagsp == &negflags) {
goto neg_modifier;
}
cs = REGEX_UNICODE_CHARSET;
has_charset_modifier = UNICODE_PAT_MOD;
break;
case ASCII_RESTRICT_PAT_MOD:
if (flagsp == &negflags) {
goto neg_modifier;
}
if (has_charset_modifier) {
if (cs != REGEX_ASCII_RESTRICTED_CHARSET) {
goto excess_modifier;
}
/* Doubled modifier implies more restricted */
cs = REGEX_ASCII_MORE_RESTRICTED_CHARSET;
}
else {
cs = REGEX_ASCII_RESTRICTED_CHARSET;
}
has_charset_modifier = ASCII_RESTRICT_PAT_MOD;
break;
case DEPENDS_PAT_MOD:
if (has_use_defaults) {
goto fail_modifiers;
}
else if (flagsp == &negflags) {
goto neg_modifier;
}
else if (has_charset_modifier) {
goto excess_modifier;
}
/* The dual charset means unicode semantics if the
* pattern (or target, not known until runtime) are
* utf8, or something in the pattern indicates unicode
* semantics */
cs = (RExC_uni_semantics)
? REGEX_UNICODE_CHARSET
: REGEX_DEPENDS_CHARSET;
has_charset_modifier = DEPENDS_PAT_MOD;
break;
excess_modifier:
RExC_parse++;
if (has_charset_modifier == ASCII_RESTRICT_PAT_MOD) {
vFAIL2("Regexp modifier \"%c\" may appear a maximum of twice", ASCII_RESTRICT_PAT_MOD);
}
else if (has_charset_modifier == *(RExC_parse - 1)) {
vFAIL2("Regexp modifier \"%c\" may not appear twice",
*(RExC_parse - 1));
}
else {
vFAIL3("Regexp modifiers \"%c\" and \"%c\" are mutually exclusive", has_charset_modifier, *(RExC_parse - 1));
}
NOT_REACHED; /*NOTREACHED*/
neg_modifier:
RExC_parse++;
vFAIL2("Regexp modifier \"%c\" may not appear after the \"-\"",
*(RExC_parse - 1));
NOT_REACHED; /*NOTREACHED*/
case ONCE_PAT_MOD: /* 'o' */
case GLOBAL_PAT_MOD: /* 'g' */
if (ckWARN(WARN_REGEXP)) {
const I32 wflagbit = *RExC_parse == 'o'
? WASTED_O
: WASTED_G;
if (! (wastedflags & wflagbit) ) {
wastedflags |= wflagbit;
/* diag_listed_as: Useless (?-%s) - don't use /%s modifier in regex; marked by <-- HERE in m/%s/ */
vWARN5(
RExC_parse + 1,
"Useless (%s%c) - %suse /%c modifier",
flagsp == &negflags ? "?-" : "?",
*RExC_parse,
flagsp == &negflags ? "don't " : "",
*RExC_parse
);
}
}
break;
case CONTINUE_PAT_MOD: /* 'c' */
if (ckWARN(WARN_REGEXP)) {
if (! (wastedflags & WASTED_C) ) {
wastedflags |= WASTED_GC;
/* diag_listed_as: Useless (?-%s) - don't use /%s modifier in regex; marked by <-- HERE in m/%s/ */
vWARN3(
RExC_parse + 1,
"Useless (%sc) - %suse /gc modifier",
flagsp == &negflags ? "?-" : "?",
flagsp == &negflags ? "don't " : ""
);
}
}
break;
case KEEPCOPY_PAT_MOD: /* 'p' */
if (flagsp == &negflags) {
ckWARNreg(RExC_parse + 1,"Useless use of (?-p)");
} else {
*flagsp |= RXf_PMf_KEEPCOPY;
}
break;
case '-':
/* A flag is a default iff it is following a minus, so
* if there is a minus, it means will be trying to
* re-specify a default which is an error */
if (has_use_defaults || flagsp == &negflags) {
goto fail_modifiers;
}
flagsp = &negflags;
wastedflags = 0; /* reset so (?g-c) warns twice */
x_mod_count = 0;
break;
case ':':
case ')':
if ((posflags & (RXf_PMf_EXTENDED|RXf_PMf_EXTENDED_MORE)) == RXf_PMf_EXTENDED) {
negflags |= RXf_PMf_EXTENDED_MORE;
}
RExC_flags |= posflags;
if (negflags & RXf_PMf_EXTENDED) {
negflags |= RXf_PMf_EXTENDED_MORE;
}
RExC_flags &= ~negflags;
set_regex_charset(&RExC_flags, cs);
return;
default:
fail_modifiers:
RExC_parse += SKIP_IF_CHAR(RExC_parse, RExC_end);
/* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
vFAIL2utf8f("Sequence (%" UTF8f "...) not recognized",
UTF8fARG(UTF, RExC_parse-seqstart, seqstart));
NOT_REACHED; /*NOTREACHED*/
}
RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
}
vFAIL("Sequence (?... not terminated");
}
/*
- reg - regular expression, i.e. main body or parenthesized thing
*
* Caller must absorb opening parenthesis.
*
* Combining parenthesis handling with the base level of regular expression
* is a trifle forced, but the need to tie the tails of the branches to what
* follows makes it hard to avoid.
*/
#define REGTAIL(x,y,z) regtail((x),(y),(z),depth+1)
#ifdef DEBUGGING
#define REGTAIL_STUDY(x,y,z) regtail_study((x),(y),(z),depth+1)
#else
#define REGTAIL_STUDY(x,y,z) regtail((x),(y),(z),depth+1)
#endif
PERL_STATIC_INLINE regnode_offset
S_handle_named_backref(pTHX_ RExC_state_t *pRExC_state,
I32 *flagp,
char * parse_start,
char ch
)
{
regnode_offset ret;
char* name_start = RExC_parse;
U32 num = 0;
SV *sv_dat = reg_scan_name(pRExC_state, REG_RSN_RETURN_DATA);
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_HANDLE_NAMED_BACKREF;
if (RExC_parse == name_start || *RExC_parse != ch) {
/* diag_listed_as: Sequence \%s... not terminated in regex; marked by <-- HERE in m/%s/ */
vFAIL2("Sequence %.3s... not terminated", parse_start);
}
if (sv_dat) {
num = add_data( pRExC_state, STR_WITH_LEN("S"));
RExC_rxi->data->data[num]=(void*)sv_dat;
SvREFCNT_inc_simple_void_NN(sv_dat);
}
RExC_sawback = 1;
ret = reganode(pRExC_state,
((! FOLD)
? NREF
: (ASCII_FOLD_RESTRICTED)
? NREFFA
: (AT_LEAST_UNI_SEMANTICS)
? NREFFU
: (LOC)
? NREFFL
: NREFF),
num);
*flagp |= HASWIDTH;
Set_Node_Offset(REGNODE_p(ret), parse_start+1);
Set_Node_Cur_Length(REGNODE_p(ret), parse_start);
nextchar(pRExC_state);
return ret;
}
/* On success, returns the offset at which any next node should be placed into
* the regex engine program being compiled.
*
* Returns 0 otherwise, with *flagp set to indicate why:
* TRYAGAIN at the end of (?) that only sets flags.
* RESTART_PARSE if the parse needs to be restarted, or'd with
* NEED_UTF8 if the pattern needs to be upgraded to UTF-8.
* Otherwise would only return 0 if regbranch() returns 0, which cannot
* happen. */
STATIC regnode_offset
S_reg(pTHX_ RExC_state_t *pRExC_state, I32 paren, I32 *flagp, U32 depth)
/* paren: Parenthesized? 0=top; 1,2=inside '(': changed to letter.
* 2 is like 1, but indicates that nextchar() has been called to advance
* RExC_parse beyond the '('. Things like '(?' are indivisible tokens, and
* this flag alerts us to the need to check for that */
{
regnode_offset ret = 0; /* Will be the head of the group. */
regnode_offset br;
regnode_offset lastbr;
regnode_offset ender = 0;
I32 parno = 0;
I32 flags;
U32 oregflags = RExC_flags;
bool have_branch = 0;
bool is_open = 0;
I32 freeze_paren = 0;
I32 after_freeze = 0;
I32 num; /* numeric backreferences */
SV * max_open; /* Max number of unclosed parens */
char * parse_start = RExC_parse; /* MJD */
char * const oregcomp_parse = RExC_parse;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REG;
DEBUG_PARSE("reg ");
max_open = get_sv(RE_COMPILE_RECURSION_LIMIT, GV_ADD);
assert(max_open);
if (!SvIOK(max_open)) {
sv_setiv(max_open, RE_COMPILE_RECURSION_INIT);
}
if (depth > 4 * (UV) SvIV(max_open)) { /* We increase depth by 4 for each
open paren */
vFAIL("Too many nested open parens");
}
*flagp = 0; /* Tentatively. */
/* Having this true makes it feasible to have a lot fewer tests for the
* parse pointer being in scope. For example, we can write
* while(isFOO(*RExC_parse)) RExC_parse++;
* instead of
* while(RExC_parse < RExC_end && isFOO(*RExC_parse)) RExC_parse++;
*/
assert(*RExC_end == '\0');
/* Make an OPEN node, if parenthesized. */
if (paren) {
/* Under /x, space and comments can be gobbled up between the '(' and
* here (if paren ==2). The forms '(*VERB' and '(?...' disallow such
* intervening space, as the sequence is a token, and a token should be
* indivisible */
bool has_intervening_patws = (paren == 2)
&& *(RExC_parse - 1) != '(';
if (RExC_parse >= RExC_end) {
vFAIL("Unmatched (");
}
if (paren == 'r') { /* Atomic script run */
paren = '>';
goto parse_rest;
}
else if ( *RExC_parse == '*') { /* (*VERB:ARG), (*construct:...) */
char *start_verb = RExC_parse + 1;
STRLEN verb_len;
char *start_arg = NULL;
unsigned char op = 0;
int arg_required = 0;
int internal_argval = -1; /* if >-1 we are not allowed an argument*/
bool has_upper = FALSE;
if (has_intervening_patws) {
RExC_parse++; /* past the '*' */
/* For strict backwards compatibility, don't change the message
* now that we also have lowercase operands */
if (isUPPER(*RExC_parse)) {
vFAIL("In '(*VERB...)', the '(' and '*' must be adjacent");
}
else {
vFAIL("In '(*...)', the '(' and '*' must be adjacent");
}
}
while (RExC_parse < RExC_end && *RExC_parse != ')' ) {
if ( *RExC_parse == ':' ) {
start_arg = RExC_parse + 1;
break;
}
else if (! UTF) {
if (isUPPER(*RExC_parse)) {
has_upper = TRUE;
}
RExC_parse++;
}
else {
RExC_parse += UTF8SKIP(RExC_parse);
}
}
verb_len = RExC_parse - start_verb;
if ( start_arg ) {
if (RExC_parse >= RExC_end) {
goto unterminated_verb_pattern;
}
RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
while ( RExC_parse < RExC_end && *RExC_parse != ')' ) {
RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
}
if ( RExC_parse >= RExC_end || *RExC_parse != ')' ) {
unterminated_verb_pattern:
if (has_upper) {
vFAIL("Unterminated verb pattern argument");
}
else {
vFAIL("Unterminated '(*...' argument");
}
}
} else {
if ( RExC_parse >= RExC_end || *RExC_parse != ')' ) {
if (has_upper) {
vFAIL("Unterminated verb pattern");
}
else {
vFAIL("Unterminated '(*...' construct");
}
}
}
/* Here, we know that RExC_parse < RExC_end */
switch ( *start_verb ) {
case 'A': /* (*ACCEPT) */
if ( memEQs(start_verb, verb_len,"ACCEPT") ) {
op = ACCEPT;
internal_argval = RExC_nestroot;
}
break;
case 'C': /* (*COMMIT) */
if ( memEQs(start_verb, verb_len,"COMMIT") )
op = COMMIT;
break;
case 'F': /* (*FAIL) */
if ( verb_len==1 || memEQs(start_verb, verb_len,"FAIL") ) {
op = OPFAIL;
}
break;
case ':': /* (*:NAME) */
case 'M': /* (*MARK:NAME) */
if ( verb_len==0 || memEQs(start_verb, verb_len,"MARK") ) {
op = MARKPOINT;
arg_required = 1;
}
break;
case 'P': /* (*PRUNE) */
if ( memEQs(start_verb, verb_len,"PRUNE") )
op = PRUNE;
break;
case 'S': /* (*SKIP) */
if ( memEQs(start_verb, verb_len,"SKIP") )
op = SKIP;
break;
case 'T': /* (*THEN) */
/* [19:06] <TimToady> :: is then */
if ( memEQs(start_verb, verb_len,"THEN") ) {
op = CUTGROUP;
RExC_seen |= REG_CUTGROUP_SEEN;
}
break;
case 'a':
if ( memEQs(start_verb, verb_len, "asr")
|| memEQs(start_verb, verb_len, "atomic_script_run"))
{
paren = 'r'; /* Mnemonic: recursed run */
goto script_run;
}
else if (memEQs(start_verb, verb_len, "atomic")) {
paren = 't'; /* AtOMIC */
goto alpha_assertions;
}
break;
case 'p':
if ( memEQs(start_verb, verb_len, "plb")
|| memEQs(start_verb, verb_len, "positive_lookbehind"))
{
paren = 'b';
goto lookbehind_alpha_assertions;
}
else if ( memEQs(start_verb, verb_len, "pla")
|| memEQs(start_verb, verb_len, "positive_lookahead"))
{
paren = 'a';
goto alpha_assertions;
}
break;
case 'n':
if ( memEQs(start_verb, verb_len, "nlb")
|| memEQs(start_verb, verb_len, "negative_lookbehind"))
{
paren = 'B';
goto lookbehind_alpha_assertions;
}
else if ( memEQs(start_verb, verb_len, "nla")
|| memEQs(start_verb, verb_len, "negative_lookahead"))
{
paren = 'A';
goto alpha_assertions;
}
break;
case 's':
if ( memEQs(start_verb, verb_len, "sr")
|| memEQs(start_verb, verb_len, "script_run"))
{
regnode_offset atomic;
paren = 's';
script_run:
/* This indicates Unicode rules. */
REQUIRE_UNI_RULES(flagp, 0);
if (! start_arg) {
goto no_colon;
}
RExC_parse = start_arg;
if (RExC_in_script_run) {
/* Nested script runs are treated as no-ops, because
* if the nested one fails, the outer one must as
* well. It could fail sooner, and avoid (??{} with
* side effects, but that is explicitly documented as
* undefined behavior. */
ret = 0;
if (paren == 's') {
paren = ':';
goto parse_rest;
}
/* But, the atomic part of a nested atomic script run
* isn't a no-op, but can be treated just like a '(?>'
* */
paren = '>';
goto parse_rest;
}
/* By doing this here, we avoid extra warnings for nested
* script runs */
ckWARNexperimental(RExC_parse,
WARN_EXPERIMENTAL__SCRIPT_RUN,
"The script_run feature is experimental");
if (paren == 's') {
/* Here, we're starting a new regular script run */
ret = reg_node(pRExC_state, SROPEN);
RExC_in_script_run = 1;
is_open = 1;
goto parse_rest;
}
/* Here, we are starting an atomic script run. This is
* handled by recursing to deal with the atomic portion
* separately, enclosed in SROPEN ... SRCLOSE nodes */
ret = reg_node(pRExC_state, SROPEN);
RExC_in_script_run = 1;
atomic = reg(pRExC_state, 'r', &flags, depth);
if (flags & (RESTART_PARSE|NEED_UTF8)) {
*flagp = flags & (RESTART_PARSE|NEED_UTF8);
return 0;
}
if (! REGTAIL(pRExC_state, ret, atomic)) {
REQUIRE_BRANCHJ(flagp, 0);
}
if (! REGTAIL(pRExC_state, atomic, reg_node(pRExC_state,
SRCLOSE)))
{
REQUIRE_BRANCHJ(flagp, 0);
}
RExC_in_script_run = 0;
return ret;
}
break;
lookbehind_alpha_assertions:
RExC_seen |= REG_LOOKBEHIND_SEEN;
RExC_in_lookbehind++;
/*FALLTHROUGH*/
alpha_assertions:
ckWARNexperimental(RExC_parse,
WARN_EXPERIMENTAL__ALPHA_ASSERTIONS,
"The alpha_assertions feature is experimental");
RExC_seen_zerolen++;
if (! start_arg) {
goto no_colon;
}
/* An empty negative lookahead assertion simply is failure */
if (paren == 'A' && RExC_parse == start_arg) {
ret=reganode(pRExC_state, OPFAIL, 0);
nextchar(pRExC_state);
return ret;
}
RExC_parse = start_arg;
goto parse_rest;
no_colon:
vFAIL2utf8f(
"'(*%" UTF8f "' requires a terminating ':'",
UTF8fARG(UTF, verb_len, start_verb));
NOT_REACHED; /*NOTREACHED*/
} /* End of switch */
if ( ! op ) {
RExC_parse += UTF
? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
: 1;
if (has_upper || verb_len == 0) {
vFAIL2utf8f(
"Unknown verb pattern '%" UTF8f "'",
UTF8fARG(UTF, verb_len, start_verb));
}
else {
vFAIL2utf8f(
"Unknown '(*...)' construct '%" UTF8f "'",
UTF8fARG(UTF, verb_len, start_verb));
}
}
if ( RExC_parse == start_arg ) {
start_arg = NULL;
}
if ( arg_required && !start_arg ) {
vFAIL3("Verb pattern '%.*s' has a mandatory argument",
verb_len, start_verb);
}
if (internal_argval == -1) {
ret = reganode(pRExC_state, op, 0);
} else {
ret = reg2Lanode(pRExC_state, op, 0, internal_argval);
}
RExC_seen |= REG_VERBARG_SEEN;
if (start_arg) {
SV *sv = newSVpvn( start_arg,
RExC_parse - start_arg);
ARG(REGNODE_p(ret)) = add_data( pRExC_state,
STR_WITH_LEN("S"));
RExC_rxi->data->data[ARG(REGNODE_p(ret))]=(void*)sv;
FLAGS(REGNODE_p(ret)) = 1;
} else {
FLAGS(REGNODE_p(ret)) = 0;
}
if ( internal_argval != -1 )
ARG2L_SET(REGNODE_p(ret), internal_argval);
nextchar(pRExC_state);
return ret;
}
else if (*RExC_parse == '?') { /* (?...) */
bool is_logical = 0;
const char * const seqstart = RExC_parse;
const char * endptr;
if (has_intervening_patws) {
RExC_parse++;
vFAIL("In '(?...)', the '(' and '?' must be adjacent");
}
RExC_parse++; /* past the '?' */
paren = *RExC_parse; /* might be a trailing NUL, if not
well-formed */
RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
if (RExC_parse > RExC_end) {
paren = '\0';
}
ret = 0; /* For look-ahead/behind. */
switch (paren) {
case 'P': /* (?P...) variants for those used to PCRE/Python */
paren = *RExC_parse;
if ( paren == '<') { /* (?P<...>) named capture */
RExC_parse++;
if (RExC_parse >= RExC_end) {
vFAIL("Sequence (?P<... not terminated");
}
goto named_capture;
}
else if (paren == '>') { /* (?P>name) named recursion */
RExC_parse++;
if (RExC_parse >= RExC_end) {
vFAIL("Sequence (?P>... not terminated");
}
goto named_recursion;
}
else if (paren == '=') { /* (?P=...) named backref */
RExC_parse++;
return handle_named_backref(pRExC_state, flagp,
parse_start, ')');
}
RExC_parse += SKIP_IF_CHAR(RExC_parse, RExC_end);
/* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
vFAIL3("Sequence (%.*s...) not recognized",
RExC_parse-seqstart, seqstart);
NOT_REACHED; /*NOTREACHED*/
case '<': /* (?<...) */
if (*RExC_parse == '!')
paren = ',';
else if (*RExC_parse != '=')
named_capture:
{ /* (?<...>) */
char *name_start;
SV *svname;
paren= '>';
/* FALLTHROUGH */
case '\'': /* (?'...') */
name_start = RExC_parse;
svname = reg_scan_name(pRExC_state, REG_RSN_RETURN_NAME);
if ( RExC_parse == name_start
|| RExC_parse >= RExC_end
|| *RExC_parse != paren)
{
vFAIL2("Sequence (?%c... not terminated",
paren=='>' ? '<' : paren);
}
{
HE *he_str;
SV *sv_dat = NULL;
if (!svname) /* shouldn't happen */
Perl_croak(aTHX_
"panic: reg_scan_name returned NULL");
if (!RExC_paren_names) {
RExC_paren_names= newHV();
sv_2mortal(MUTABLE_SV(RExC_paren_names));
#ifdef DEBUGGING
RExC_paren_name_list= newAV();
sv_2mortal(MUTABLE_SV(RExC_paren_name_list));
#endif
}
he_str = hv_fetch_ent( RExC_paren_names, svname, 1, 0 );
if ( he_str )
sv_dat = HeVAL(he_str);
if ( ! sv_dat ) {
/* croak baby croak */
Perl_croak(aTHX_
"panic: paren_name hash element allocation failed");
} else if ( SvPOK(sv_dat) ) {
/* (?|...) can mean we have dupes so scan to check
its already been stored. Maybe a flag indicating
we are inside such a construct would be useful,
but the arrays are likely to be quite small, so
for now we punt -- dmq */
IV count = SvIV(sv_dat);
I32 *pv = (I32*)SvPVX(sv_dat);
IV i;
for ( i = 0 ; i < count ; i++ ) {
if ( pv[i] == RExC_npar ) {
count = 0;
break;
}
}
if ( count ) {
pv = (I32*)SvGROW(sv_dat,
SvCUR(sv_dat) + sizeof(I32)+1);
SvCUR_set(sv_dat, SvCUR(sv_dat) + sizeof(I32));
pv[count] = RExC_npar;
SvIV_set(sv_dat, SvIVX(sv_dat) + 1);
}
} else {
(void)SvUPGRADE(sv_dat, SVt_PVNV);
sv_setpvn(sv_dat, (char *)&(RExC_npar),
sizeof(I32));
SvIOK_on(sv_dat);
SvIV_set(sv_dat, 1);
}
#ifdef DEBUGGING
/* Yes this does cause a memory leak in debugging Perls
* */
if (!av_store(RExC_paren_name_list,
RExC_npar, SvREFCNT_inc_NN(svname)))
SvREFCNT_dec_NN(svname);
#endif
/*sv_dump(sv_dat);*/
}
nextchar(pRExC_state);
paren = 1;
goto capturing_parens;
}
RExC_seen |= REG_LOOKBEHIND_SEEN;
RExC_in_lookbehind++;
RExC_parse++;
if (RExC_parse >= RExC_end) {
vFAIL("Sequence (?... not terminated");
}
/* FALLTHROUGH */
case '=': /* (?=...) */
RExC_seen_zerolen++;
break;
case '!': /* (?!...) */
RExC_seen_zerolen++;
/* check if we're really just a "FAIL" assertion */
skip_to_be_ignored_text(pRExC_state, &RExC_parse,
FALSE /* Don't force to /x */ );
if (*RExC_parse == ')') {
ret=reganode(pRExC_state, OPFAIL, 0);
nextchar(pRExC_state);
return ret;
}
break;
case '|': /* (?|...) */
/* branch reset, behave like a (?:...) except that
buffers in alternations share the same numbers */
paren = ':';
after_freeze = freeze_paren = RExC_npar;
/* XXX This construct currently requires an extra pass.
* Investigation would be required to see if that could be
* changed */
REQUIRE_PARENS_PASS;
break;
case ':': /* (?:...) */
case '>': /* (?>...) */
break;
case '$': /* (?$...) */
case '@': /* (?@...) */
vFAIL2("Sequence (?%c...) not implemented", (int)paren);
break;
case '0' : /* (?0) */
case 'R' : /* (?R) */
if (RExC_parse == RExC_end || *RExC_parse != ')')
FAIL("Sequence (?R) not terminated");
num = 0;
RExC_seen |= REG_RECURSE_SEEN;
/* XXX These constructs currently require an extra pass.
* It probably could be changed */
REQUIRE_PARENS_PASS;
*flagp |= POSTPONED;
goto gen_recurse_regop;
/*notreached*/
/* named and numeric backreferences */
case '&': /* (?&NAME) */
parse_start = RExC_parse - 1;
named_recursion:
{
SV *sv_dat = reg_scan_name(pRExC_state,
REG_RSN_RETURN_DATA);
num = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
}
if (RExC_parse >= RExC_end || *RExC_parse != ')')
vFAIL("Sequence (?&... not terminated");
goto gen_recurse_regop;
/* NOTREACHED */
case '+':
if (! inRANGE(RExC_parse[0], '1', '9')) {
RExC_parse++;
vFAIL("Illegal pattern");
}
goto parse_recursion;
/* NOTREACHED*/
case '-': /* (?-1) */
if (! inRANGE(RExC_parse[0], '1', '9')) {
RExC_parse--; /* rewind to let it be handled later */
goto parse_flags;
}
/* FALLTHROUGH */
case '1': case '2': case '3': case '4': /* (?1) */
case '5': case '6': case '7': case '8': case '9':
RExC_parse = (char *) seqstart + 1; /* Point to the digit */
parse_recursion:
{
bool is_neg = FALSE;
UV unum;
parse_start = RExC_parse - 1; /* MJD */
if (*RExC_parse == '-') {
RExC_parse++;
is_neg = TRUE;
}
endptr = RExC_end;
if (grok_atoUV(RExC_parse, &unum, &endptr)
&& unum <= I32_MAX
) {
num = (I32)unum;
RExC_parse = (char*)endptr;
} else
num = I32_MAX;
if (is_neg) {
/* Some limit for num? */
num = -num;
}
}
if (*RExC_parse!=')')
vFAIL("Expecting close bracket");
gen_recurse_regop:
if ( paren == '-' ) {
/*
Diagram of capture buffer numbering.
Top line is the normal capture buffer numbers
Bottom line is the negative indexing as from
the X (the (?-2))
+ 1 2 3 4 5 X 6 7
/(a(x)y)(a(b(c(?-2)d)e)f)(g(h))/
- 5 4 3 2 1 X x x
*/
num = RExC_npar + num;
if (num < 1) {
/* It might be a forward reference; we can't fail until
* we know, by completing the parse to get all the
* groups, and then reparsing */
if (ALL_PARENS_COUNTED) {
RExC_parse++;
vFAIL("Reference to nonexistent group");
}
else {
REQUIRE_PARENS_PASS;
}
}
} else if ( paren == '+' ) {
num = RExC_npar + num - 1;
}
/* We keep track how many GOSUB items we have produced.
To start off the ARG2L() of the GOSUB holds its "id",
which is used later in conjunction with RExC_recurse
to calculate the offset we need to jump for the GOSUB,
which it will store in the final representation.
We have to defer the actual calculation until much later
as the regop may move.
*/
ret = reg2Lanode(pRExC_state, GOSUB, num, RExC_recurse_count);
if (num >= RExC_npar) {
/* It might be a forward reference; we can't fail until we
* know, by completing the parse to get all the groups, and
* then reparsing */
if (ALL_PARENS_COUNTED) {
if (num >= RExC_total_parens) {
RExC_parse++;
vFAIL("Reference to nonexistent group");
}
}
else {
REQUIRE_PARENS_PASS;
}
}
RExC_recurse_count++;
DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
"%*s%*s Recurse #%" UVuf " to %" IVdf "\n",
22, "| |", (int)(depth * 2 + 1), "",
(UV)ARG(REGNODE_p(ret)),
(IV)ARG2L(REGNODE_p(ret))));
RExC_seen |= REG_RECURSE_SEEN;
Set_Node_Length(REGNODE_p(ret),
1 + regarglen[OP(REGNODE_p(ret))]); /* MJD */
Set_Node_Offset(REGNODE_p(ret), parse_start); /* MJD */
*flagp |= POSTPONED;
assert(*RExC_parse == ')');
nextchar(pRExC_state);
return ret;
/* NOTREACHED */
case '?': /* (??...) */
is_logical = 1;
if (*RExC_parse != '{') {
RExC_parse += SKIP_IF_CHAR(RExC_parse, RExC_end);
/* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
vFAIL2utf8f(
"Sequence (%" UTF8f "...) not recognized",
UTF8fARG(UTF, RExC_parse-seqstart, seqstart));
NOT_REACHED; /*NOTREACHED*/
}
*flagp |= POSTPONED;
paren = '{';
RExC_parse++;
/* FALLTHROUGH */
case '{': /* (?{...}) */
{
U32 n = 0;
struct reg_code_block *cb;
OP * o;
RExC_seen_zerolen++;
if ( !pRExC_state->code_blocks
|| pRExC_state->code_index
>= pRExC_state->code_blocks->count
|| pRExC_state->code_blocks->cb[pRExC_state->code_index].start
!= (STRLEN)((RExC_parse -3 - (is_logical ? 1 : 0))
- RExC_start)
) {
if (RExC_pm_flags & PMf_USE_RE_EVAL)
FAIL("panic: Sequence (?{...}): no code block found\n");
FAIL("Eval-group not allowed at runtime, use re 'eval'");
}
/* this is a pre-compiled code block (?{...}) */
cb = &pRExC_state->code_blocks->cb[pRExC_state->code_index];
RExC_parse = RExC_start + cb->end;
o = cb->block;
if (cb->src_regex) {
n = add_data(pRExC_state, STR_WITH_LEN("rl"));
RExC_rxi->data->data[n] =
(void*)SvREFCNT_inc((SV*)cb->src_regex);
RExC_rxi->data->data[n+1] = (void*)o;
}
else {
n = add_data(pRExC_state,
(RExC_pm_flags & PMf_HAS_CV) ? "L" : "l", 1);
RExC_rxi->data->data[n] = (void*)o;
}
pRExC_state->code_index++;
nextchar(pRExC_state);
if (is_logical) {
regnode_offset eval;
ret = reg_node(pRExC_state, LOGICAL);
eval = reg2Lanode(pRExC_state, EVAL,
n,
/* for later propagation into (??{})
* return value */
RExC_flags & RXf_PMf_COMPILETIME
);
FLAGS(REGNODE_p(ret)) = 2;
if (! REGTAIL(pRExC_state, ret, eval)) {
REQUIRE_BRANCHJ(flagp, 0);
}
/* deal with the length of this later - MJD */
return ret;
}
ret = reg2Lanode(pRExC_state, EVAL, n, 0);
Set_Node_Length(REGNODE_p(ret), RExC_parse - parse_start + 1);
Set_Node_Offset(REGNODE_p(ret), parse_start);
return ret;
}
case '(': /* (?(?{...})...) and (?(?=...)...) */
{
int is_define= 0;
const int DEFINE_len = sizeof("DEFINE") - 1;
if ( RExC_parse < RExC_end - 1
&& ( ( RExC_parse[0] == '?' /* (?(?...)) */
&& ( RExC_parse[1] == '='
|| RExC_parse[1] == '!'
|| RExC_parse[1] == '<'
|| RExC_parse[1] == '{'))
|| ( RExC_parse[0] == '*' /* (?(*...)) */
&& ( memBEGINs(RExC_parse + 1,
(Size_t) (RExC_end - (RExC_parse + 1)),
"pla:")
|| memBEGINs(RExC_parse + 1,
(Size_t) (RExC_end - (RExC_parse + 1)),
"plb:")
|| memBEGINs(RExC_parse + 1,
(Size_t) (RExC_end - (RExC_parse + 1)),
"nla:")
|| memBEGINs(RExC_parse + 1,
(Size_t) (RExC_end - (RExC_parse + 1)),
"nlb:")
|| memBEGINs(RExC_parse + 1,
(Size_t) (RExC_end - (RExC_parse + 1)),
"positive_lookahead:")
|| memBEGINs(RExC_parse + 1,
(Size_t) (RExC_end - (RExC_parse + 1)),
"positive_lookbehind:")
|| memBEGINs(RExC_parse + 1,
(Size_t) (RExC_end - (RExC_parse + 1)),
"negative_lookahead:")
|| memBEGINs(RExC_parse + 1,
(Size_t) (RExC_end - (RExC_parse + 1)),
"negative_lookbehind:"))))
) { /* Lookahead or eval. */
I32 flag;
regnode_offset tail;
ret = reg_node(pRExC_state, LOGICAL);
FLAGS(REGNODE_p(ret)) = 1;
tail = reg(pRExC_state, 1, &flag, depth+1);
RETURN_FAIL_ON_RESTART(flag, flagp);
if (! REGTAIL(pRExC_state, ret, tail)) {
REQUIRE_BRANCHJ(flagp, 0);
}
goto insert_if;
}
else if ( RExC_parse[0] == '<' /* (?(<NAME>)...) */
|| RExC_parse[0] == '\'' ) /* (?('NAME')...) */
{
char ch = RExC_parse[0] == '<' ? '>' : '\'';
char *name_start= RExC_parse++;
U32 num = 0;
SV *sv_dat=reg_scan_name(pRExC_state, REG_RSN_RETURN_DATA);
if ( RExC_parse == name_start
|| RExC_parse >= RExC_end
|| *RExC_parse != ch)
{
vFAIL2("Sequence (?(%c... not terminated",
(ch == '>' ? '<' : ch));
}
RExC_parse++;
if (sv_dat) {
num = add_data( pRExC_state, STR_WITH_LEN("S"));
RExC_rxi->data->data[num]=(void*)sv_dat;
SvREFCNT_inc_simple_void_NN(sv_dat);
}
ret = reganode(pRExC_state, NGROUPP, num);
goto insert_if_check_paren;
}
else if (memBEGINs(RExC_parse,
(STRLEN) (RExC_end - RExC_parse),
"DEFINE"))
{
ret = reganode(pRExC_state, DEFINEP, 0);
RExC_parse += DEFINE_len;
is_define = 1;
goto insert_if_check_paren;
}
else if (RExC_parse[0] == 'R') {
RExC_parse++;
/* parno == 0 => /(?(R)YES|NO)/ "in any form of recursion OR eval"
* parno == 1 => /(?(R0)YES|NO)/ "in GOSUB (?0) / (?R)"
* parno == 2 => /(?(R1)YES|NO)/ "in GOSUB (?1) (parno-1)"
*/
parno = 0;
if (RExC_parse[0] == '0') {
parno = 1;
RExC_parse++;
}
else if (inRANGE(RExC_parse[0], '1', '9')) {
UV uv;
endptr = RExC_end;
if (grok_atoUV(RExC_parse, &uv, &endptr)
&& uv <= I32_MAX
) {
parno = (I32)uv + 1;
RExC_parse = (char*)endptr;
}
/* else "Switch condition not recognized" below */
} else if (RExC_parse[0] == '&') {
SV *sv_dat;
RExC_parse++;
sv_dat = reg_scan_name(pRExC_state,
REG_RSN_RETURN_DATA);
if (sv_dat)
parno = 1 + *((I32 *)SvPVX(sv_dat));
}
ret = reganode(pRExC_state, INSUBP, parno);
goto insert_if_check_paren;
}
else if (inRANGE(RExC_parse[0], '1', '9')) {
/* (?(1)...) */
char c;
UV uv;
endptr = RExC_end;
if (grok_atoUV(RExC_parse, &uv, &endptr)
&& uv <= I32_MAX
) {
parno = (I32)uv;
RExC_parse = (char*)endptr;
}
else {
vFAIL("panic: grok_atoUV returned FALSE");
}
ret = reganode(pRExC_state, GROUPP, parno);
insert_if_check_paren:
if (UCHARAT(RExC_parse) != ')') {
RExC_parse += UTF
? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
: 1;
vFAIL("Switch condition not recognized");
}
nextchar(pRExC_state);
insert_if:
if (! REGTAIL(pRExC_state, ret, reganode(pRExC_state,
IFTHEN, 0)))
{
REQUIRE_BRANCHJ(flagp, 0);
}
br = regbranch(pRExC_state, &flags, 1, depth+1);
if (br == 0) {
RETURN_FAIL_ON_RESTART(flags,flagp);
FAIL2("panic: regbranch returned failure, flags=%#" UVxf,
(UV) flags);
} else
if (! REGTAIL(pRExC_state, br, reganode(pRExC_state,
LONGJMP, 0)))
{
REQUIRE_BRANCHJ(flagp, 0);
}
c = UCHARAT(RExC_parse);
nextchar(pRExC_state);
if (flags&HASWIDTH)
*flagp |= HASWIDTH;
if (c == '|') {
if (is_define)
vFAIL("(?(DEFINE)....) does not allow branches");
/* Fake one for optimizer. */
lastbr = reganode(pRExC_state, IFTHEN, 0);
if (!regbranch(pRExC_state, &flags, 1, depth+1)) {
RETURN_FAIL_ON_RESTART(flags, flagp);
FAIL2("panic: regbranch returned failure, flags=%#" UVxf,
(UV) flags);
}
if (! REGTAIL(pRExC_state, ret, lastbr)) {
REQUIRE_BRANCHJ(flagp, 0);
}
if (flags&HASWIDTH)
*flagp |= HASWIDTH;
c = UCHARAT(RExC_parse);
nextchar(pRExC_state);
}
else
lastbr = 0;
if (c != ')') {
if (RExC_parse >= RExC_end)
vFAIL("Switch (?(condition)... not terminated");
else
vFAIL("Switch (?(condition)... contains too many branches");
}
ender = reg_node(pRExC_state, TAIL);
if (! REGTAIL(pRExC_state, br, ender)) {
REQUIRE_BRANCHJ(flagp, 0);
}
if (lastbr) {
if (! REGTAIL(pRExC_state, lastbr, ender)) {
REQUIRE_BRANCHJ(flagp, 0);
}
if (! REGTAIL(pRExC_state,
REGNODE_OFFSET(
NEXTOPER(
NEXTOPER(REGNODE_p(lastbr)))),
ender))
{
REQUIRE_BRANCHJ(flagp, 0);
}
}
else
if (! REGTAIL(pRExC_state, ret, ender)) {
REQUIRE_BRANCHJ(flagp, 0);
}
#if 0 /* Removing this doesn't cause failures in the test suite -- khw */
RExC_size++; /* XXX WHY do we need this?!!
For large programs it seems to be required
but I can't figure out why. -- dmq*/
#endif
return ret;
}
RExC_parse += UTF
? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
: 1;
vFAIL("Unknown switch condition (?(...))");
}
case '[': /* (?[ ... ]) */
return handle_regex_sets(pRExC_state, NULL, flagp, depth+1,
oregcomp_parse);
case 0: /* A NUL */
RExC_parse--; /* for vFAIL to print correctly */
vFAIL("Sequence (? incomplete");
break;
case ')':
if (RExC_strict) { /* [perl #132851] */
ckWARNreg(RExC_parse, "Empty (?) without any modifiers");
}
/* FALLTHROUGH */
default: /* e.g., (?i) */
RExC_parse = (char *) seqstart + 1;
parse_flags:
parse_lparen_question_flags(pRExC_state);
if (UCHARAT(RExC_parse) != ':') {
if (RExC_parse < RExC_end)
nextchar(pRExC_state);
*flagp = TRYAGAIN;
return 0;
}
paren = ':';
nextchar(pRExC_state);
ret = 0;
goto parse_rest;
} /* end switch */
}
else {
if (*RExC_parse == '{') {
ckWARNregdep(RExC_parse + 1,
"Unescaped left brace in regex is "
"deprecated here (and will be fatal "
"in Perl 5.32), passed through");
}
/* Not bothering to indent here, as the above 'else' is temporary
* */
if (!(RExC_flags & RXf_PMf_NOCAPTURE)) { /* (...) */
capturing_parens:
parno = RExC_npar;
RExC_npar++;
if (! ALL_PARENS_COUNTED) {
/* If we are in our first pass through (and maybe only pass),
* we need to allocate memory for the capturing parentheses
* data structures.
*/
if (!RExC_parens_buf_size) {
/* first guess at number of parens we might encounter */
RExC_parens_buf_size = 10;
/* setup RExC_open_parens, which holds the address of each
* OPEN tag, and to make things simpler for the 0 index the
* start of the program - this is used later for offsets */
Newxz(RExC_open_parens, RExC_parens_buf_size,
regnode_offset);
RExC_open_parens[0] = 1; /* +1 for REG_MAGIC */
/* setup RExC_close_parens, which holds the address of each
* CLOSE tag, and to make things simpler for the 0 index
* the end of the program - this is used later for offsets
* */
Newxz(RExC_close_parens, RExC_parens_buf_size,
regnode_offset);
/* we dont know where end op starts yet, so we dont need to
* set RExC_close_parens[0] like we do RExC_open_parens[0]
* above */
}
else if (RExC_npar > RExC_parens_buf_size) {
I32 old_size = RExC_parens_buf_size;
RExC_parens_buf_size *= 2;
Renew(RExC_open_parens, RExC_parens_buf_size,
regnode_offset);
Zero(RExC_open_parens + old_size,
RExC_parens_buf_size - old_size, regnode_offset);
Renew(RExC_close_parens, RExC_parens_buf_size,
regnode_offset);
Zero(RExC_close_parens + old_size,
RExC_parens_buf_size - old_size, regnode_offset);
}
}
ret = reganode(pRExC_state, OPEN, parno);
if (!RExC_nestroot)
RExC_nestroot = parno;
if (RExC_open_parens && !RExC_open_parens[parno])
{
DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
"%*s%*s Setting open paren #%" IVdf " to %d\n",
22, "| |", (int)(depth * 2 + 1), "",
(IV)parno, ret));
RExC_open_parens[parno]= ret;
}
Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
Set_Node_Offset(REGNODE_p(ret), RExC_parse); /* MJD */
is_open = 1;
} else {
/* with RXf_PMf_NOCAPTURE treat (...) as (?:...) */
paren = ':';
ret = 0;
}
}
}
else /* ! paren */
ret = 0;
parse_rest:
/* Pick up the branches, linking them together. */
parse_start = RExC_parse; /* MJD */
br = regbranch(pRExC_state, &flags, 1, depth+1);
/* branch_len = (paren != 0); */
if (br == 0) {
RETURN_FAIL_ON_RESTART(flags, flagp);
FAIL2("panic: regbranch returned failure, flags=%#" UVxf, (UV) flags);
}
if (*RExC_parse == '|') {
if (RExC_use_BRANCHJ) {
reginsert(pRExC_state, BRANCHJ, br, depth+1);
}
else { /* MJD */
reginsert(pRExC_state, BRANCH, br, depth+1);
Set_Node_Length(REGNODE_p(br), paren != 0);
Set_Node_Offset_To_R(br, parse_start-RExC_start);
}
have_branch = 1;
}
else if (paren == ':') {
*flagp |= flags&SIMPLE;
}
if (is_open) { /* Starts with OPEN. */
if (! REGTAIL(pRExC_state, ret, br)) { /* OPEN -> first. */
REQUIRE_BRANCHJ(flagp, 0);
}
}
else if (paren != '?') /* Not Conditional */
ret = br;
*flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
lastbr = br;
while (*RExC_parse == '|') {
if (RExC_use_BRANCHJ) {
bool shut_gcc_up;
ender = reganode(pRExC_state, LONGJMP, 0);
/* Append to the previous. */
shut_gcc_up = REGTAIL(pRExC_state,
REGNODE_OFFSET(NEXTOPER(NEXTOPER(REGNODE_p(lastbr)))),
ender);
PERL_UNUSED_VAR(shut_gcc_up);
}
nextchar(pRExC_state);
if (freeze_paren) {
if (RExC_npar > after_freeze)
after_freeze = RExC_npar;
RExC_npar = freeze_paren;
}
br = regbranch(pRExC_state, &flags, 0, depth+1);
if (br == 0) {
RETURN_FAIL_ON_RESTART(flags, flagp);
FAIL2("panic: regbranch returned failure, flags=%#" UVxf, (UV) flags);
}
if (! REGTAIL(pRExC_state, lastbr, br)) { /* BRANCH -> BRANCH. */
REQUIRE_BRANCHJ(flagp, 0);
}
lastbr = br;
*flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
}
if (have_branch || paren != ':') {
regnode * br;
/* Make a closing node, and hook it on the end. */
switch (paren) {
case ':':
ender = reg_node(pRExC_state, TAIL);
break;
case 1: case 2:
ender = reganode(pRExC_state, CLOSE, parno);
if ( RExC_close_parens ) {
DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
"%*s%*s Setting close paren #%" IVdf " to %d\n",
22, "| |", (int)(depth * 2 + 1), "",
(IV)parno, ender));
RExC_close_parens[parno]= ender;
if (RExC_nestroot == parno)
RExC_nestroot = 0;
}
Set_Node_Offset(REGNODE_p(ender), RExC_parse+1); /* MJD */
Set_Node_Length(REGNODE_p(ender), 1); /* MJD */
break;
case 's':
ender = reg_node(pRExC_state, SRCLOSE);
RExC_in_script_run = 0;
break;
case '<':
case 'a':
case 'A':
case 'b':
case 'B':
case ',':
case '=':
case '!':
*flagp &= ~HASWIDTH;
/* FALLTHROUGH */
case 't': /* aTomic */
case '>':
ender = reg_node(pRExC_state, SUCCEED);
break;
case 0:
ender = reg_node(pRExC_state, END);
assert(!RExC_end_op); /* there can only be one! */
RExC_end_op = REGNODE_p(ender);
if (RExC_close_parens) {
DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
"%*s%*s Setting close paren #0 (END) to %d\n",
22, "| |", (int)(depth * 2 + 1), "",
ender));
RExC_close_parens[0]= ender;
}
break;
}
DEBUG_PARSE_r({
DEBUG_PARSE_MSG("lsbr");
regprop(RExC_rx, RExC_mysv1, REGNODE_p(lastbr), NULL, pRExC_state);
regprop(RExC_rx, RExC_mysv2, REGNODE_p(ender), NULL, pRExC_state);
Perl_re_printf( aTHX_ "~ tying lastbr %s (%" IVdf ") to ender %s (%" IVdf ") offset %" IVdf "\n",
SvPV_nolen_const(RExC_mysv1),
(IV)lastbr,
SvPV_nolen_const(RExC_mysv2),
(IV)ender,
(IV)(ender - lastbr)
);
});
if (! REGTAIL(pRExC_state, lastbr, ender)) {
REQUIRE_BRANCHJ(flagp, 0);
}
if (have_branch) {
char is_nothing= 1;
if (depth==1)
RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN;
/* Hook the tails of the branches to the closing node. */
for (br = REGNODE_p(ret); br; br = regnext(br)) {
const U8 op = PL_regkind[OP(br)];
if (op == BRANCH) {
if (! REGTAIL_STUDY(pRExC_state,
REGNODE_OFFSET(NEXTOPER(br)),
ender))
{
REQUIRE_BRANCHJ(flagp, 0);
}
if ( OP(NEXTOPER(br)) != NOTHING
|| regnext(NEXTOPER(br)) != REGNODE_p(ender))
is_nothing= 0;
}
else if (op == BRANCHJ) {
bool shut_gcc_up = REGTAIL_STUDY(pRExC_state,
REGNODE_OFFSET(NEXTOPER(NEXTOPER(br))),
ender);
PERL_UNUSED_VAR(shut_gcc_up);
/* for now we always disable this optimisation * /
if ( OP(NEXTOPER(NEXTOPER(br))) != NOTHING
|| regnext(NEXTOPER(NEXTOPER(br))) != REGNODE_p(ender))
*/
is_nothing= 0;
}
}
if (is_nothing) {
regnode * ret_as_regnode = REGNODE_p(ret);
br= PL_regkind[OP(ret_as_regnode)] != BRANCH
? regnext(ret_as_regnode)
: ret_as_regnode;
DEBUG_PARSE_r({
DEBUG_PARSE_MSG("NADA");
regprop(RExC_rx, RExC_mysv1, ret_as_regnode,
NULL, pRExC_state);
regprop(RExC_rx, RExC_mysv2, REGNODE_p(ender),
NULL, pRExC_state);
Perl_re_printf( aTHX_ "~ converting ret %s (%" IVdf ") to ender %s (%" IVdf ") offset %" IVdf "\n",
SvPV_nolen_const(RExC_mysv1),
(IV)REG_NODE_NUM(ret_as_regnode),
SvPV_nolen_const(RExC_mysv2),
(IV)ender,
(IV)(ender - ret)
);
});
OP(br)= NOTHING;
if (OP(REGNODE_p(ender)) == TAIL) {
NEXT_OFF(br)= 0;
RExC_emit= REGNODE_OFFSET(br) + 1;
} else {
regnode *opt;
for ( opt= br + 1; opt < REGNODE_p(ender) ; opt++ )
OP(opt)= OPTIMIZED;
NEXT_OFF(br)= REGNODE_p(ender) - br;
}
}
}
}
{
const char *p;
/* Even/odd or x=don't care: 010101x10x */
static const char parens[] = "=!aA<,>Bbt";
/* flag below is set to 0 up through 'A'; 1 for larger */
if (paren && (p = strchr(parens, paren))) {
U8 node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
int flag = (p - parens) > 3;
if (paren == '>' || paren == 't') {
node = SUSPEND, flag = 0;
}
reginsert(pRExC_state, node, ret, depth+1);
Set_Node_Cur_Length(REGNODE_p(ret), parse_start);
Set_Node_Offset(REGNODE_p(ret), parse_start + 1);
FLAGS(REGNODE_p(ret)) = flag;
if (! REGTAIL_STUDY(pRExC_state, ret, reg_node(pRExC_state, TAIL)))
{
REQUIRE_BRANCHJ(flagp, 0);
}
}
}
/* Check for proper termination. */
if (paren) {
/* restore original flags, but keep (?p) and, if we've encountered
* something in the parse that changes /d rules into /u, keep the /u */
RExC_flags = oregflags | (RExC_flags & RXf_PMf_KEEPCOPY);
if (DEPENDS_SEMANTICS && RExC_uni_semantics) {
set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET);
}
if (RExC_parse >= RExC_end || UCHARAT(RExC_parse) != ')') {
RExC_parse = oregcomp_parse;
vFAIL("Unmatched (");
}
nextchar(pRExC_state);
}
else if (!paren && RExC_parse < RExC_end) {
if (*RExC_parse == ')') {
RExC_parse++;
vFAIL("Unmatched )");
}
else
FAIL("Junk on end of regexp"); /* "Can't happen". */
NOT_REACHED; /* NOTREACHED */
}
if (RExC_in_lookbehind) {
RExC_in_lookbehind--;
}
if (after_freeze > RExC_npar)
RExC_npar = after_freeze;
return(ret);
}
/*
- regbranch - one alternative of an | operator
*
* Implements the concatenation operator.
*
* On success, returns the offset at which any next node should be placed into
* the regex engine program being compiled.
*
* Returns 0 otherwise, setting flagp to RESTART_PARSE if the parse needs
* to be restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to
* UTF-8
*/
STATIC regnode_offset
S_regbranch(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, I32 first, U32 depth)
{
regnode_offset ret;
regnode_offset chain = 0;
regnode_offset latest;
I32 flags = 0, c = 0;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REGBRANCH;
DEBUG_PARSE("brnc");
if (first)
ret = 0;
else {
if (RExC_use_BRANCHJ)
ret = reganode(pRExC_state, BRANCHJ, 0);
else {
ret = reg_node(pRExC_state, BRANCH);
Set_Node_Length(REGNODE_p(ret), 1);
}
}
*flagp = WORST; /* Tentatively. */
skip_to_be_ignored_text(pRExC_state, &RExC_parse,
FALSE /* Don't force to /x */ );
while (RExC_parse < RExC_end && *RExC_parse != '|' && *RExC_parse != ')') {
flags &= ~TRYAGAIN;
latest = regpiece(pRExC_state, &flags, depth+1);
if (latest == 0) {
if (flags & TRYAGAIN)
continue;
RETURN_FAIL_ON_RESTART(flags, flagp);
FAIL2("panic: regpiece returned failure, flags=%#" UVxf, (UV) flags);
}
else if (ret == 0)
ret = latest;
*flagp |= flags&(HASWIDTH|POSTPONED);
if (chain == 0) /* First piece. */
*flagp |= flags&SPSTART;
else {
/* FIXME adding one for every branch after the first is probably
* excessive now we have TRIE support. (hv) */
MARK_NAUGHTY(1);
if (! REGTAIL(pRExC_state, chain, latest)) {
/* XXX We could just redo this branch, but figuring out what
* bookkeeping needs to be reset is a pain, and it's likely
* that other branches that goto END will also be too large */
REQUIRE_BRANCHJ(flagp, 0);
}
}
chain = latest;
c++;
}
if (chain == 0) { /* Loop ran zero times. */
chain = reg_node(pRExC_state, NOTHING);
if (ret == 0)
ret = chain;
}
if (c == 1) {
*flagp |= flags&SIMPLE;
}
return ret;
}
/*
- regpiece - something followed by possible quantifier * + ? {n,m}
*
* Note that the branching code sequences used for ? and the general cases
* of * and + are somewhat optimized: they use the same NOTHING node as
* both the endmarker for their branch list and the body of the last branch.
* It might seem that this node could be dispensed with entirely, but the
* endmarker role is not redundant.
*
* On success, returns the offset at which any next node should be placed into
* the regex engine program being compiled.
*
* Returns 0 otherwise, with *flagp set to indicate why:
* TRYAGAIN if regatom() returns 0 with TRYAGAIN.
* RESTART_PARSE if the parse needs to be restarted, or'd with
* NEED_UTF8 if the pattern needs to be upgraded to UTF-8.
*/
STATIC regnode_offset
S_regpiece(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
{
regnode_offset ret;
char op;
char *next;
I32 flags;
const char * const origparse = RExC_parse;
I32 min;
I32 max = REG_INFTY;
#ifdef RE_TRACK_PATTERN_OFFSETS
char *parse_start;
#endif
const char *maxpos = NULL;
UV uv;
/* Save the original in case we change the emitted regop to a FAIL. */
const regnode_offset orig_emit = RExC_emit;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REGPIECE;
DEBUG_PARSE("piec");
ret = regatom(pRExC_state, &flags, depth+1);
if (ret == 0) {
RETURN_FAIL_ON_RESTART_OR_FLAGS(flags, flagp, TRYAGAIN);
FAIL2("panic: regatom returned failure, flags=%#" UVxf, (UV) flags);
}
op = *RExC_parse;
if (op == '{' && regcurly(RExC_parse)) {
maxpos = NULL;
#ifdef RE_TRACK_PATTERN_OFFSETS
parse_start = RExC_parse; /* MJD */
#endif
next = RExC_parse + 1;
while (isDIGIT(*next) || *next == ',') {
if (*next == ',') {
if (maxpos)
break;
else
maxpos = next;
}
next++;
}
if (*next == '}') { /* got one */
const char* endptr;
if (!maxpos)
maxpos = next;
RExC_parse++;
if (isDIGIT(*RExC_parse)) {
endptr = RExC_end;
if (!grok_atoUV(RExC_parse, &uv, &endptr))
vFAIL("Invalid quantifier in {,}");
if (uv >= REG_INFTY)
vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
min = (I32)uv;
} else {
min = 0;
}
if (*maxpos == ',')
maxpos++;
else
maxpos = RExC_parse;
if (isDIGIT(*maxpos)) {
endptr = RExC_end;
if (!grok_atoUV(maxpos, &uv, &endptr))
vFAIL("Invalid quantifier in {,}");
if (uv >= REG_INFTY)
vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
max = (I32)uv;
} else {
max = REG_INFTY; /* meaning "infinity" */
}
RExC_parse = next;
nextchar(pRExC_state);
if (max < min) { /* If can't match, warn and optimize to fail
unconditionally */
reginsert(pRExC_state, OPFAIL, orig_emit, depth+1);
ckWARNreg(RExC_parse, "Quantifier {n,m} with n > m can't match");
NEXT_OFF(REGNODE_p(orig_emit)) =
regarglen[OPFAIL] + NODE_STEP_REGNODE;
return ret;
}
else if (min == max && *RExC_parse == '?')
{
ckWARN2reg(RExC_parse + 1,
"Useless use of greediness modifier '%c'",
*RExC_parse);
}
do_curly:
if ((flags&SIMPLE)) {
if (min == 0 && max == REG_INFTY) {
reginsert(pRExC_state, STAR, ret, depth+1);
MARK_NAUGHTY(4);
RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
goto nest_check;
}
if (min == 1 && max == REG_INFTY) {
reginsert(pRExC_state, PLUS, ret, depth+1);
MARK_NAUGHTY(3);
RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
goto nest_check;
}
MARK_NAUGHTY_EXP(2, 2);
reginsert(pRExC_state, CURLY, ret, depth+1);
Set_Node_Offset(REGNODE_p(ret), parse_start+1); /* MJD */
Set_Node_Cur_Length(REGNODE_p(ret), parse_start);
}
else {
const regnode_offset w = reg_node(pRExC_state, WHILEM);
FLAGS(REGNODE_p(w)) = 0;
if (! REGTAIL(pRExC_state, ret, w)) {
REQUIRE_BRANCHJ(flagp, 0);
}
if (RExC_use_BRANCHJ) {
reginsert(pRExC_state, LONGJMP, ret, depth+1);
reginsert(pRExC_state, NOTHING, ret, depth+1);
NEXT_OFF(REGNODE_p(ret)) = 3; /* Go over LONGJMP. */
}
reginsert(pRExC_state, CURLYX, ret, depth+1);
/* MJD hk */
Set_Node_Offset(REGNODE_p(ret), parse_start+1);
Set_Node_Length(REGNODE_p(ret),
op == '{' ? (RExC_parse - parse_start) : 1);
if (RExC_use_BRANCHJ)
NEXT_OFF(REGNODE_p(ret)) = 3; /* Go over NOTHING to
LONGJMP. */
if (! REGTAIL(pRExC_state, ret, reg_node(pRExC_state,
NOTHING)))
{
REQUIRE_BRANCHJ(flagp, 0);
}
RExC_whilem_seen++;
MARK_NAUGHTY_EXP(1, 4); /* compound interest */
}
FLAGS(REGNODE_p(ret)) = 0;
if (min > 0)
*flagp = WORST;
if (max > 0)
*flagp |= HASWIDTH;
ARG1_SET(REGNODE_p(ret), (U16)min);
ARG2_SET(REGNODE_p(ret), (U16)max);
if (max == REG_INFTY)
RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
goto nest_check;
}
}
if (!ISMULT1(op)) {
*flagp = flags;
return(ret);
}
#if 0 /* Now runtime fix should be reliable. */
/* if this is reinstated, don't forget to put this back into perldiag:
=item Regexp *+ operand could be empty at {#} in regex m/%s/
(F) The part of the regexp subject to either the * or + quantifier
could match an empty string. The {#} shows in the regular
expression about where the problem was discovered.
*/
if (!(flags&HASWIDTH) && op != '?')
vFAIL("Regexp *+ operand could be empty");
#endif
#ifdef RE_TRACK_PATTERN_OFFSETS
parse_start = RExC_parse;
#endif
nextchar(pRExC_state);
*flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
if (op == '*') {
min = 0;
goto do_curly;
}
else if (op == '+') {
min = 1;
goto do_curly;
}
else if (op == '?') {
min = 0; max = 1;
goto do_curly;
}
nest_check:
if (!(flags&(HASWIDTH|POSTPONED)) && max > REG_INFTY/3) {
ckWARN2reg(RExC_parse,
"%" UTF8f " matches null string many times",
UTF8fARG(UTF, (RExC_parse >= origparse
? RExC_parse - origparse
: 0),
origparse));
}
if (*RExC_parse == '?') {
nextchar(pRExC_state);
reginsert(pRExC_state, MINMOD, ret, depth+1);
if (! REGTAIL(pRExC_state, ret, ret + NODE_STEP_REGNODE)) {
REQUIRE_BRANCHJ(flagp, 0);
}
}
else if (*RExC_parse == '+') {
regnode_offset ender;
nextchar(pRExC_state);
ender = reg_node(pRExC_state, SUCCEED);
if (! REGTAIL(pRExC_state, ret, ender)) {
REQUIRE_BRANCHJ(flagp, 0);
}
reginsert(pRExC_state, SUSPEND, ret, depth+1);
ender = reg_node(pRExC_state, TAIL);
if (! REGTAIL(pRExC_state, ret, ender)) {
REQUIRE_BRANCHJ(flagp, 0);
}
}
if (ISMULT2(RExC_parse)) {
RExC_parse++;
vFAIL("Nested quantifiers");
}
return(ret);
}
STATIC bool
S_grok_bslash_N(pTHX_ RExC_state_t *pRExC_state,
regnode_offset * node_p,
UV * code_point_p,
int * cp_count,
I32 * flagp,
const bool strict,
const U32 depth
)
{
/* This routine teases apart the various meanings of \N and returns
* accordingly. The input parameters constrain which meaning(s) is/are valid
* in the current context.
*
* Exactly one of <node_p> and <code_point_p> must be non-NULL.
*
* If <code_point_p> is not NULL, the context is expecting the result to be a
* single code point. If this \N instance turns out to a single code point,
* the function returns TRUE and sets *code_point_p to that code point.
*
* If <node_p> is not NULL, the context is expecting the result to be one of
* the things representable by a regnode. If this \N instance turns out to be
* one such, the function generates the regnode, returns TRUE and sets *node_p
* to point to the offset of that regnode into the regex engine program being
* compiled.
*
* If this instance of \N isn't legal in any context, this function will
* generate a fatal error and not return.
*
* On input, RExC_parse should point to the first char following the \N at the
* time of the call. On successful return, RExC_parse will have been updated
* to point to just after the sequence identified by this routine. Also
* *flagp has been updated as needed.
*
* When there is some problem with the current context and this \N instance,
* the function returns FALSE, without advancing RExC_parse, nor setting
* *node_p, nor *code_point_p, nor *flagp.
*
* If <cp_count> is not NULL, the caller wants to know the length (in code
* points) that this \N sequence matches. This is set, and the input is
* parsed for errors, even if the function returns FALSE, as detailed below.
*
* There are 6 possibilities here, as detailed in the next 6 paragraphs.
*
* Probably the most common case is for the \N to specify a single code point.
* *cp_count will be set to 1, and *code_point_p will be set to that code
* point.
*
* Another possibility is for the input to be an empty \N{}. This is no
* longer accepted, and will generate a fatal error.
*
* Another possibility is for a custom charnames handler to be in effect which
* translates the input name to an empty string. *cp_count will be set to 0.
* *node_p will be set to a generated NOTHING node.
*
* Still another possibility is for the \N to mean [^\n]. *cp_count will be
* set to 0. *node_p will be set to a generated REG_ANY node.
*
* The fifth possibility is that \N resolves to a sequence of more than one
* code points. *cp_count will be set to the number of code points in the
* sequence. *node_p will be set to a generated node returned by this
* function calling S_reg().
*
* The final possibility is that it is premature to be calling this function;
* the parse needs to be restarted. This can happen when this changes from
* /d to /u rules, or when the pattern needs to be upgraded to UTF-8. The
* latter occurs only when the fifth possibility would otherwise be in
* effect, and is because one of those code points requires the pattern to be
* recompiled as UTF-8. The function returns FALSE, and sets the
* RESTART_PARSE and NEED_UTF8 flags in *flagp, as appropriate. When this
* happens, the caller needs to desist from continuing parsing, and return
* this information to its caller. This is not set for when there is only one
* code point, as this can be called as part of an ANYOF node, and they can
* store above-Latin1 code points without the pattern having to be in UTF-8.
*
* For non-single-quoted regexes, the tokenizer has resolved character and
* sequence names inside \N{...} into their Unicode values, normalizing the
* result into what we should see here: '\N{U+c1.c2...}', where c1... are the
* hex-represented code points in the sequence. This is done there because
* the names can vary based on what charnames pragma is in scope at the time,
* so we need a way to take a snapshot of what they resolve to at the time of
* the original parse. [perl #56444].
*
* That parsing is skipped for single-quoted regexes, so here we may get
* '\N{NAME}', which is parsed now. If the single-quoted regex is something
* like '\N{U+41}', that code point is Unicode, and has to be translated into
* the native character set for non-ASCII platforms. The other possibilities
* are already native, so no translation is done. */
char * endbrace; /* points to '}' following the name */
char* p = RExC_parse; /* Temporary */
SV * substitute_parse = NULL;
char *orig_end;
char *save_start;
I32 flags;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_GROK_BSLASH_N;
GET_RE_DEBUG_FLAGS;
assert(cBOOL(node_p) ^ cBOOL(code_point_p)); /* Exactly one should be set */
assert(! (node_p && cp_count)); /* At most 1 should be set */
if (cp_count) { /* Initialize return for the most common case */
*cp_count = 1;
}
/* The [^\n] meaning of \N ignores spaces and comments under the /x
* modifier. The other meanings do not, so use a temporary until we find
* out which we are being called with */
skip_to_be_ignored_text(pRExC_state, &p,
FALSE /* Don't force to /x */ );
/* Disambiguate between \N meaning a named character versus \N meaning
* [^\n]. The latter is assumed when the {...} following the \N is a legal
* quantifier, or if there is no '{' at all */
if (*p != '{' || regcurly(p)) {
RExC_parse = p;
if (cp_count) {
*cp_count = -1;
}
if (! node_p) {
return FALSE;
}
*node_p = reg_node(pRExC_state, REG_ANY);
*flagp |= HASWIDTH|SIMPLE;
MARK_NAUGHTY(1);
Set_Node_Length(REGNODE_p(*(node_p)), 1); /* MJD */
return TRUE;
}
/* The test above made sure that the next real character is a '{', but
* under the /x modifier, it could be separated by space (or a comment and
* \n) and this is not allowed (for consistency with \x{...} and the
* tokenizer handling of \N{NAME}). */
if (*RExC_parse != '{') {
vFAIL("Missing braces on \\N{}");
}
RExC_parse++; /* Skip past the '{' */
endbrace = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);
if (! endbrace) { /* no trailing brace */
vFAIL2("Missing right brace on \\%c{}", 'N');
}
/* Here, we have decided it should be a named character or sequence. These
* imply Unicode semantics */
REQUIRE_UNI_RULES(flagp, FALSE);
/* \N{_} is what toke.c returns to us to indicate a name that evaluates to
* nothing at all (not allowed under strict) */
if (endbrace - RExC_parse == 1 && *RExC_parse == '_') {
RExC_parse = endbrace;
if (strict) {
RExC_parse++; /* Position after the "}" */
vFAIL("Zero length \\N{}");
}
if (cp_count) {
*cp_count = 0;
}
nextchar(pRExC_state);
if (! node_p) {
return FALSE;
}
*node_p = reg_node(pRExC_state, NOTHING);
return TRUE;
}
if (endbrace - RExC_parse < 2 || ! strBEGINs(RExC_parse, "U+")) {
/* Here, the name isn't of the form U+.... This can happen if the
* pattern is single-quoted, so didn't get evaluated in toke.c. Now
* is the time to find out what the name means */
const STRLEN name_len = endbrace - RExC_parse;
SV * value_sv; /* What does this name evaluate to */
SV ** value_svp;
const U8 * value; /* string of name's value */
STRLEN value_len; /* and its length */
/* RExC_unlexed_names is a hash of names that weren't evaluated by
* toke.c, and their values. Make sure is initialized */
if (! RExC_unlexed_names) {
RExC_unlexed_names = newHV();
}
/* If we have already seen this name in this pattern, use that. This
* allows us to only call the charnames handler once per name per
* pattern. A broken or malicious handler could return something
* different each time, which could cause the results to vary depending
* on if something gets added or subtracted from the pattern that
* causes the number of passes to change, for example */
if ((value_svp = hv_fetch(RExC_unlexed_names, RExC_parse,
name_len, 0)))
{
value_sv = *value_svp;
}
else { /* Otherwise we have to go out and get the name */
const char * error_msg = NULL;
value_sv = get_and_check_backslash_N_name(RExC_parse, endbrace,
UTF,
&error_msg);
if (error_msg) {
RExC_parse = endbrace;
vFAIL(error_msg);
}
/* If no error message, should have gotten a valid return */
assert (value_sv);
/* Save the name's meaning for later use */
if (! hv_store(RExC_unlexed_names, RExC_parse, name_len,
value_sv, 0))
{
Perl_croak(aTHX_ "panic: hv_store() unexpectedly failed");
}
}
/* Here, we have the value the name evaluates to in 'value_sv' */
value = (U8 *) SvPV(value_sv, value_len);
/* See if the result is one code point vs 0 or multiple */
if (value_len > 0 && value_len <= (UV) ((SvUTF8(value_sv))
? UTF8SKIP(value)
: 1))
{
/* Here, exactly one code point. If that isn't what is wanted,
* fail */
if (! code_point_p) {
RExC_parse = p;
return FALSE;
}
/* Convert from string to numeric code point */
*code_point_p = (SvUTF8(value_sv))
? valid_utf8_to_uvchr(value, NULL)
: *value;
/* Have parsed this entire single code point \N{...}. *cp_count
* has already been set to 1, so don't do it again. */
RExC_parse = endbrace;
nextchar(pRExC_state);
return TRUE;
} /* End of is a single code point */
/* Count the code points, if caller desires. The API says to do this
* even if we will later return FALSE */
if (cp_count) {
*cp_count = 0;
*cp_count = (SvUTF8(value_sv))
? utf8_length(value, value + value_len)
: value_len;
}
/* Fail if caller doesn't want to handle a multi-code-point sequence.
* But don't back the pointer up if the caller wants to know how many
* code points there are (they need to handle it themselves in this
* case). */
if (! node_p) {
if (! cp_count) {
RExC_parse = p;
}
return FALSE;
}
/* Convert this to a sub-pattern of the form "(?: ... )", and then call
* reg recursively to parse it. That way, it retains its atomicness,
* while not having to worry about any special handling that some code
* points may have. */
substitute_parse = newSVpvs("?:");
sv_catsv(substitute_parse, value_sv);
sv_catpv(substitute_parse, ")");
#ifdef EBCDIC
/* The value should already be native, so no need to convert on EBCDIC
* platforms.*/
assert(! RExC_recode_x_to_native);
#endif
}
else { /* \N{U+...} */
Size_t count = 0; /* code point count kept internally */
/* We can get to here when the input is \N{U+...} or when toke.c has
* converted a name to the \N{U+...} form. This include changing a
* name that evaluates to multiple code points to \N{U+c1.c2.c3 ...} */
RExC_parse += 2; /* Skip past the 'U+' */
/* Code points are separated by dots. The '}' terminates the whole
* thing. */
do { /* Loop until the ending brace */
UV cp = 0;
char * start_digit; /* The first of the current code point */
if (! isXDIGIT(*RExC_parse)) {
RExC_parse++;
vFAIL("Invalid hexadecimal number in \\N{U+...}");
}
start_digit = RExC_parse;
count++;
/* Loop through the hex digits of the current code point */
do {
/* Adding this digit will shift the result 4 bits. If that
* result would be above the legal max, it's overflow */
if (cp > MAX_LEGAL_CP >> 4) {
/* Find the end of the code point */
do {
RExC_parse ++;
} while (isXDIGIT(*RExC_parse) || *RExC_parse == '_');
/* Be sure to synchronize this message with the similar one
* in utf8.c */
vFAIL4("Use of code point 0x%.*s is not allowed; the"
" permissible max is 0x%" UVxf,
(int) (RExC_parse - start_digit), start_digit,
MAX_LEGAL_CP);
}
/* Accumulate this (valid) digit into the running total */
cp = (cp << 4) + READ_XDIGIT(RExC_parse);
/* READ_XDIGIT advanced the input pointer. Ignore a single
* underscore separator */
if (*RExC_parse == '_' && isXDIGIT(RExC_parse[1])) {
RExC_parse++;
}
} while (isXDIGIT(*RExC_parse));
/* Here, have accumulated the next code point */
if (RExC_parse >= endbrace) { /* If done ... */
if (count != 1) {
goto do_concat;
}
/* Here, is a single code point; fail if doesn't want that */
if (! code_point_p) {
RExC_parse = p;
return FALSE;
}
/* A single code point is easy to handle; just return it */
*code_point_p = UNI_TO_NATIVE(cp);
RExC_parse = endbrace;
nextchar(pRExC_state);
return TRUE;
}
/* Here, the only legal thing would be a multiple character
* sequence (of the form "\N{U+c1.c2. ... }". So the next
* character must be a dot (and the one after that can't be the
* endbrace, or we'd have something like \N{U+100.} ) */
if (*RExC_parse != '.' || RExC_parse + 1 >= endbrace) {
RExC_parse += (RExC_orig_utf8) /* point to after 1st invalid */
? UTF8SKIP(RExC_parse)
: 1;
if (RExC_parse >= endbrace) { /* Guard against malformed utf8 */
RExC_parse = endbrace;
}
vFAIL("Invalid hexadecimal number in \\N{U+...}");
}
/* Here, looks like its really a multiple character sequence. Fail
* if that's not what the caller wants. But continue with counting
* and error checking if they still want a count */
if (! node_p && ! cp_count) {
return FALSE;
}
/* What is done here is to convert this to a sub-pattern of the
* form \x{char1}\x{char2}... and then call reg recursively to
* parse it (enclosing in "(?: ... )" ). That way, it retains its
* atomicness, while not having to worry about special handling
* that some code points may have. We don't create a subpattern,
* but go through the motions of code point counting and error
* checking, if the caller doesn't want a node returned. */
if (node_p && count == 1) {
substitute_parse = newSVpvs("?:");
}
do_concat:
if (node_p) {
/* Convert to notation the rest of the code understands */
sv_catpvs(substitute_parse, "\\x{");
sv_catpvn(substitute_parse, start_digit,
RExC_parse - start_digit);
sv_catpvs(substitute_parse, "}");
}
/* Move to after the dot (or ending brace the final time through.)
* */
RExC_parse++;
count++;
} while (RExC_parse < endbrace);
if (! node_p) { /* Doesn't want the node */
assert (cp_count);
*cp_count = count;
return FALSE;
}
sv_catpvs(substitute_parse, ")");
#ifdef EBCDIC
/* The values are Unicode, and therefore have to be converted to native
* on a non-Unicode (meaning non-ASCII) platform. */
RExC_recode_x_to_native = 1;
#endif
}
/* Here, we have the string the name evaluates to, ready to be parsed,
* stored in 'substitute_parse' as a series of valid "\x{...}\x{...}"
* constructs. This can be called from within a substitute parse already.
* The error reporting mechanism doesn't work for 2 levels of this, but the
* code above has validated this new construct, so there should be no
* errors generated by the below. And this isn' an exact copy, so the
* mechanism to seamlessly deal with this won't work, so turn off warnings
* during it */
save_start = RExC_start;
orig_end = RExC_end;
RExC_parse = RExC_start = SvPVX(substitute_parse);
RExC_end = RExC_parse + SvCUR(substitute_parse);
TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE;
*node_p = reg(pRExC_state, 1, &flags, depth+1);
/* Restore the saved values */
RESTORE_WARNINGS;
RExC_start = save_start;
RExC_parse = endbrace;
RExC_end = orig_end;
#ifdef EBCDIC
RExC_recode_x_to_native = 0;
#endif
SvREFCNT_dec_NN(substitute_parse);
if (! *node_p) {
RETURN_FAIL_ON_RESTART(flags, flagp);
FAIL2("panic: reg returned failure to grok_bslash_N, flags=%#" UVxf,
(UV) flags);
}
*flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
nextchar(pRExC_state);
return TRUE;
}
PERL_STATIC_INLINE U8
S_compute_EXACTish(RExC_state_t *pRExC_state)
{
U8 op;
PERL_ARGS_ASSERT_COMPUTE_EXACTISH;
if (! FOLD) {
return (LOC)
? EXACTL
: EXACT;
}
op = get_regex_charset(RExC_flags);
if (op >= REGEX_ASCII_RESTRICTED_CHARSET) {
op--; /* /a is same as /u, and map /aa's offset to what /a's would have
been, so there is no hole */
}
return op + EXACTF;
}
STATIC bool
S_new_regcurly(const char *s, const char *e)
{
/* This is a temporary function designed to match the most lenient form of
* a {m,n} quantifier we ever envision, with either number omitted, and
* spaces anywhere between/before/after them.
*
* If this function fails, then the string it matches is very unlikely to
* ever be considered a valid quantifier, so we can allow the '{' that
* begins it to be considered as a literal */
bool has_min = FALSE;
bool has_max = FALSE;
PERL_ARGS_ASSERT_NEW_REGCURLY;
if (s >= e || *s++ != '{')
return FALSE;
while (s < e && isSPACE(*s)) {
s++;
}
while (s < e && isDIGIT(*s)) {
has_min = TRUE;
s++;
}
while (s < e && isSPACE(*s)) {
s++;
}
if (*s == ',') {
s++;
while (s < e && isSPACE(*s)) {
s++;
}
while (s < e && isDIGIT(*s)) {
has_max = TRUE;
s++;
}
while (s < e && isSPACE(*s)) {
s++;
}
}
return s < e && *s == '}' && (has_min || has_max);
}
/* Parse backref decimal value, unless it's too big to sensibly be a backref,
* in which case return I32_MAX (rather than possibly 32-bit wrapping) */
static I32
S_backref_value(char *p, char *e)
{
const char* endptr = e;
UV val;
if (grok_atoUV(p, &val, &endptr) && val <= I32_MAX)
return (I32)val;
return I32_MAX;
}
/*
- regatom - the lowest level
Try to identify anything special at the start of the current parse position.
If there is, then handle it as required. This may involve generating a
single regop, such as for an assertion; or it may involve recursing, such as
to handle a () structure.
If the string doesn't start with something special then we gobble up
as much literal text as we can. If we encounter a quantifier, we have to
back off the final literal character, as that quantifier applies to just it
and not to the whole string of literals.
Once we have been able to handle whatever type of thing started the
sequence, we return the offset into the regex engine program being compiled
at which any next regnode should be placed.
Returns 0, setting *flagp to TRYAGAIN if reg() returns 0 with TRYAGAIN.
Returns 0, setting *flagp to RESTART_PARSE if the parse needs to be
restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to UTF-8
Otherwise does not return 0.
Note: we have to be careful with escapes, as they can be both literal
and special, and in the case of \10 and friends, context determines which.
A summary of the code structure is:
switch (first_byte) {
cases for each special:
handle this special;
break;
case '\\':
switch (2nd byte) {
cases for each unambiguous special:
handle this special;
break;
cases for each ambigous special/literal:
disambiguate;
if (special) handle here
else goto defchar;
default: // unambiguously literal:
goto defchar;
}
default: // is a literal char
// FALL THROUGH
defchar:
create EXACTish node for literal;
while (more input and node isn't full) {
switch (input_byte) {
cases for each special;
make sure parse pointer is set so that the next call to
regatom will see this special first
goto loopdone; // EXACTish node terminated by prev. char
default:
append char to EXACTISH node;
}
get next input byte;
}
loopdone:
}
return the generated node;
Specifically there are two separate switches for handling
escape sequences, with the one for handling literal escapes requiring
a dummy entry for all of the special escapes that are actually handled
by the other.
*/
STATIC regnode_offset
S_regatom(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
{
dVAR;
regnode_offset ret = 0;
I32 flags = 0;
char *parse_start;
U8 op;
int invert = 0;
U8 arg;
GET_RE_DEBUG_FLAGS_DECL;
*flagp = WORST; /* Tentatively. */
DEBUG_PARSE("atom");
PERL_ARGS_ASSERT_REGATOM;
tryagain:
parse_start = RExC_parse;
assert(RExC_parse < RExC_end);
switch ((U8)*RExC_parse) {
case '^':
RExC_seen_zerolen++;
nextchar(pRExC_state);
if (RExC_flags & RXf_PMf_MULTILINE)
ret = reg_node(pRExC_state, MBOL);
else
ret = reg_node(pRExC_state, SBOL);
Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
break;
case '$':
nextchar(pRExC_state);
if (*RExC_parse)
RExC_seen_zerolen++;
if (RExC_flags & RXf_PMf_MULTILINE)
ret = reg_node(pRExC_state, MEOL);
else
ret = reg_node(pRExC_state, SEOL);
Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
break;
case '.':
nextchar(pRExC_state);
if (RExC_flags & RXf_PMf_SINGLELINE)
ret = reg_node(pRExC_state, SANY);
else
ret = reg_node(pRExC_state, REG_ANY);
*flagp |= HASWIDTH|SIMPLE;
MARK_NAUGHTY(1);
Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
break;
case '[':
{
char * const oregcomp_parse = ++RExC_parse;
ret = regclass(pRExC_state, flagp, depth+1,
FALSE, /* means parse the whole char class */
TRUE, /* allow multi-char folds */
FALSE, /* don't silence non-portable warnings. */
(bool) RExC_strict,
TRUE, /* Allow an optimized regnode result */
NULL);
if (ret == 0) {
RETURN_FAIL_ON_RESTART_FLAGP(flagp);
FAIL2("panic: regclass returned failure to regatom, flags=%#" UVxf,
(UV) *flagp);
}
if (*RExC_parse != ']') {
RExC_parse = oregcomp_parse;
vFAIL("Unmatched [");
}
nextchar(pRExC_state);
Set_Node_Length(REGNODE_p(ret), RExC_parse - oregcomp_parse + 1); /* MJD */
break;
}
case '(':
nextchar(pRExC_state);
ret = reg(pRExC_state, 2, &flags, depth+1);
if (ret == 0) {
if (flags & TRYAGAIN) {
if (RExC_parse >= RExC_end) {
/* Make parent create an empty node if needed. */
*flagp |= TRYAGAIN;
return(0);
}
goto tryagain;
}
RETURN_FAIL_ON_RESTART(flags, flagp);
FAIL2("panic: reg returned failure to regatom, flags=%#" UVxf,
(UV) flags);
}
*flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
break;
case '|':
case ')':
if (flags & TRYAGAIN) {
*flagp |= TRYAGAIN;
return 0;
}
vFAIL("Internal urp");
/* Supposed to be caught earlier. */
break;
case '?':
case '+':
case '*':
RExC_parse++;
vFAIL("Quantifier follows nothing");
break;
case '\\':
/* Special Escapes
This switch handles escape sequences that resolve to some kind
of special regop and not to literal text. Escape sequences that
resolve to literal text are handled below in the switch marked
"Literal Escapes".
Every entry in this switch *must* have a corresponding entry
in the literal escape switch. However, the opposite is not
required, as the default for this switch is to jump to the
literal text handling code.
*/
RExC_parse++;
switch ((U8)*RExC_parse) {
/* Special Escapes */
case 'A':
RExC_seen_zerolen++;
ret = reg_node(pRExC_state, SBOL);
/* SBOL is shared with /^/ so we set the flags so we can tell
* /\A/ from /^/ in split. */
FLAGS(REGNODE_p(ret)) = 1;
*flagp |= SIMPLE;
goto finish_meta_pat;
case 'G':
ret = reg_node(pRExC_state, GPOS);
RExC_seen |= REG_GPOS_SEEN;
*flagp |= SIMPLE;
goto finish_meta_pat;
case 'K':
RExC_seen_zerolen++;
ret = reg_node(pRExC_state, KEEPS);
*flagp |= SIMPLE;
/* XXX:dmq : disabling in-place substitution seems to
* be necessary here to avoid cases of memory corruption, as
* with: C<$_="x" x 80; s/x\K/y/> -- rgs
*/
RExC_seen |= REG_LOOKBEHIND_SEEN;
goto finish_meta_pat;
case 'Z':
ret = reg_node(pRExC_state, SEOL);
*flagp |= SIMPLE;
RExC_seen_zerolen++; /* Do not optimize RE away */
goto finish_meta_pat;
case 'z':
ret = reg_node(pRExC_state, EOS);
*flagp |= SIMPLE;
RExC_seen_zerolen++; /* Do not optimize RE away */
goto finish_meta_pat;
case 'C':
vFAIL("\\C no longer supported");
case 'X':
ret = reg_node(pRExC_state, CLUMP);
*flagp |= HASWIDTH;
goto finish_meta_pat;
case 'W':
invert = 1;
/* FALLTHROUGH */
case 'w':
arg = ANYOF_WORDCHAR;
goto join_posix;
case 'B':
invert = 1;
/* FALLTHROUGH */
case 'b':
{
U8 flags = 0;
regex_charset charset = get_regex_charset(RExC_flags);
RExC_seen_zerolen++;
RExC_seen |= REG_LOOKBEHIND_SEEN;
op = BOUND + charset;
if (RExC_parse >= RExC_end || *(RExC_parse + 1) != '{') {
flags = TRADITIONAL_BOUND;
if (op > BOUNDA) { /* /aa is same as /a */
op = BOUNDA;
}
}
else {
STRLEN length;
char name = *RExC_parse;
char * endbrace = NULL;
RExC_parse += 2;
endbrace = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);
if (! endbrace) {
vFAIL2("Missing right brace on \\%c{}", name);
}
/* XXX Need to decide whether to take spaces or not. Should be
* consistent with \p{}, but that currently is SPACE, which
* means vertical too, which seems wrong
* while (isBLANK(*RExC_parse)) {
RExC_parse++;
}*/
if (endbrace == RExC_parse) {
RExC_parse++; /* After the '}' */
vFAIL2("Empty \\%c{}", name);
}
length = endbrace - RExC_parse;
/*while (isBLANK(*(RExC_parse + length - 1))) {
length--;
}*/
switch (*RExC_parse) {
case 'g':
if ( length != 1
&& (memNEs(RExC_parse + 1, length - 1, "cb")))
{
goto bad_bound_type;
}
flags = GCB_BOUND;
break;
case 'l':
if (length != 2 || *(RExC_parse + 1) != 'b') {
goto bad_bound_type;
}
flags = LB_BOUND;
break;
case 's':
if (length != 2 || *(RExC_parse + 1) != 'b') {
goto bad_bound_type;
}
flags = SB_BOUND;
break;
case 'w':
if (length != 2 || *(RExC_parse + 1) != 'b') {
goto bad_bound_type;
}
flags = WB_BOUND;
break;
default:
bad_bound_type:
RExC_parse = endbrace;
vFAIL2utf8f(
"'%" UTF8f "' is an unknown bound type",
UTF8fARG(UTF, length, endbrace - length));
NOT_REACHED; /*NOTREACHED*/
}
RExC_parse = endbrace;
REQUIRE_UNI_RULES(flagp, 0);
if (op == BOUND) {
op = BOUNDU;
}
else if (op >= BOUNDA) { /* /aa is same as /a */
op = BOUNDU;
length += 4;
/* Don't have to worry about UTF-8, in this message because
* to get here the contents of the \b must be ASCII */
ckWARN4reg(RExC_parse + 1, /* Include the '}' in msg */
"Using /u for '%.*s' instead of /%s",
(unsigned) length,
endbrace - length + 1,
(charset == REGEX_ASCII_RESTRICTED_CHARSET)
? ASCII_RESTRICT_PAT_MODS
: ASCII_MORE_RESTRICT_PAT_MODS);
}
}
if (op == BOUND) {
RExC_seen_d_op = TRUE;
}
else if (op == BOUNDL) {
RExC_contains_locale = 1;
}
if (invert) {
op += NBOUND - BOUND;
}
ret = reg_node(pRExC_state, op);
FLAGS(REGNODE_p(ret)) = flags;
*flagp |= SIMPLE;
goto finish_meta_pat;
}
case 'D':
invert = 1;
/* FALLTHROUGH */
case 'd':
arg = ANYOF_DIGIT;
if (! DEPENDS_SEMANTICS) {
goto join_posix;
}
/* \d doesn't have any matches in the upper Latin1 range, hence /d
* is equivalent to /u. Changing to /u saves some branches at
* runtime */
op = POSIXU;
goto join_posix_op_known;
case 'R':
ret = reg_node(pRExC_state, LNBREAK);
*flagp |= HASWIDTH|SIMPLE;
goto finish_meta_pat;
case 'H':
invert = 1;
/* FALLTHROUGH */
case 'h':
arg = ANYOF_BLANK;
op = POSIXU;
goto join_posix_op_known;
case 'V':
invert = 1;
/* FALLTHROUGH */
case 'v':
arg = ANYOF_VERTWS;
op = POSIXU;
goto join_posix_op_known;
case 'S':
invert = 1;
/* FALLTHROUGH */
case 's':
arg = ANYOF_SPACE;
join_posix:
op = POSIXD + get_regex_charset(RExC_flags);
if (op > POSIXA) { /* /aa is same as /a */
op = POSIXA;
}
else if (op == POSIXL) {
RExC_contains_locale = 1;
}
else if (op == POSIXD) {
RExC_seen_d_op = TRUE;
}
join_posix_op_known:
if (invert) {
op += NPOSIXD - POSIXD;
}
ret = reg_node(pRExC_state, op);
FLAGS(REGNODE_p(ret)) = namedclass_to_classnum(arg);
*flagp |= HASWIDTH|SIMPLE;
/* FALLTHROUGH */
finish_meta_pat:
if ( UCHARAT(RExC_parse + 1) == '{'
&& UNLIKELY(! new_regcurly(RExC_parse + 1, RExC_end)))
{
RExC_parse += 2;
vFAIL("Unescaped left brace in regex is illegal here");
}
nextchar(pRExC_state);
Set_Node_Length(REGNODE_p(ret), 2); /* MJD */
break;
case 'p':
case 'P':
RExC_parse--;
ret = regclass(pRExC_state, flagp, depth+1,
TRUE, /* means just parse this element */
FALSE, /* don't allow multi-char folds */
FALSE, /* don't silence non-portable warnings. It
would be a bug if these returned
non-portables */
(bool) RExC_strict,
TRUE, /* Allow an optimized regnode result */
NULL);
RETURN_FAIL_ON_RESTART_FLAGP(flagp);
/* regclass() can only return RESTART_PARSE and NEED_UTF8 if
* multi-char folds are allowed. */
if (!ret)
FAIL2("panic: regclass returned failure to regatom, flags=%#" UVxf,
(UV) *flagp);
RExC_parse--;
Set_Node_Offset(REGNODE_p(ret), parse_start);
Set_Node_Cur_Length(REGNODE_p(ret), parse_start - 2);
nextchar(pRExC_state);
break;
case 'N':
/* Handle \N, \N{} and \N{NAMED SEQUENCE} (the latter meaning the
* \N{...} evaluates to a sequence of more than one code points).
* The function call below returns a regnode, which is our result.
* The parameters cause it to fail if the \N{} evaluates to a
* single code point; we handle those like any other literal. The
* reason that the multicharacter case is handled here and not as
* part of the EXACtish code is because of quantifiers. In
* /\N{BLAH}+/, the '+' applies to the whole thing, and doing it
* this way makes that Just Happen. dmq.
* join_exact() will join this up with adjacent EXACTish nodes
* later on, if appropriate. */
++RExC_parse;
if (grok_bslash_N(pRExC_state,
&ret, /* Want a regnode returned */
NULL, /* Fail if evaluates to a single code
point */
NULL, /* Don't need a count of how many code
points */
flagp,
RExC_strict,
depth)
) {
break;
}
RETURN_FAIL_ON_RESTART_FLAGP(flagp);
/* Here, evaluates to a single code point. Go get that */
RExC_parse = parse_start;
goto defchar;
case 'k': /* Handle \k<NAME> and \k'NAME' */
parse_named_seq:
{
char ch;
if ( RExC_parse >= RExC_end - 1
|| (( ch = RExC_parse[1]) != '<'
&& ch != '\''
&& ch != '{'))
{
RExC_parse++;
/* diag_listed_as: Sequence \%s... not terminated in regex; marked by <-- HERE in m/%s/ */
vFAIL2("Sequence %.2s... not terminated", parse_start);
} else {
RExC_parse += 2;
ret = handle_named_backref(pRExC_state,
flagp,
parse_start,
(ch == '<')
? '>'
: (ch == '{')
? '}'
: '\'');
}
break;
}
case 'g':
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
{
I32 num;
bool hasbrace = 0;
if (*RExC_parse == 'g') {
bool isrel = 0;
RExC_parse++;
if (*RExC_parse == '{') {
RExC_parse++;
hasbrace = 1;
}
if (*RExC_parse == '-') {
RExC_parse++;
isrel = 1;
}
if (hasbrace && !isDIGIT(*RExC_parse)) {
if (isrel) RExC_parse--;
RExC_parse -= 2;
goto parse_named_seq;
}
if (RExC_parse >= RExC_end) {
goto unterminated_g;
}
num = S_backref_value(RExC_parse, RExC_end);
if (num == 0)
vFAIL("Reference to invalid group 0");
else if (num == I32_MAX) {
if (isDIGIT(*RExC_parse))
vFAIL("Reference to nonexistent group");
else
unterminated_g:
vFAIL("Unterminated \\g... pattern");
}
if (isrel) {
num = RExC_npar - num;
if (num < 1)
vFAIL("Reference to nonexistent or unclosed group");
}
}
else {
num = S_backref_value(RExC_parse, RExC_end);
/* bare \NNN might be backref or octal - if it is larger
* than or equal RExC_npar then it is assumed to be an
* octal escape. Note RExC_npar is +1 from the actual
* number of parens. */
/* Note we do NOT check if num == I32_MAX here, as that is
* handled by the RExC_npar check */
if (
/* any numeric escape < 10 is always a backref */
num > 9
/* any numeric escape < RExC_npar is a backref */
&& num >= RExC_npar
/* cannot be an octal escape if it starts with 8 */
&& *RExC_parse != '8'
/* cannot be an octal escape it it starts with 9 */
&& *RExC_parse != '9'
) {
/* Probably not meant to be a backref, instead likely
* to be an octal character escape, e.g. \35 or \777.
* The above logic should make it obvious why using
* octal escapes in patterns is problematic. - Yves */
RExC_parse = parse_start;
goto defchar;
}
}
/* At this point RExC_parse points at a numeric escape like
* \12 or \88 or something similar, which we should NOT treat
* as an octal escape. It may or may not be a valid backref
* escape. For instance \88888888 is unlikely to be a valid
* backref. */
while (isDIGIT(*RExC_parse))
RExC_parse++;
if (hasbrace) {
if (*RExC_parse != '}')
vFAIL("Unterminated \\g{...} pattern");
RExC_parse++;
}
if (num >= (I32)RExC_npar) {
/* It might be a forward reference; we can't fail until we
* know, by completing the parse to get all the groups, and
* then reparsing */
if (ALL_PARENS_COUNTED) {
if (num >= RExC_total_parens) {
vFAIL("Reference to nonexistent group");
}
}
else {
REQUIRE_PARENS_PASS;
}
}
RExC_sawback = 1;
ret = reganode(pRExC_state,
((! FOLD)
? REF
: (ASCII_FOLD_RESTRICTED)
? REFFA
: (AT_LEAST_UNI_SEMANTICS)
? REFFU
: (LOC)
? REFFL
: REFF),
num);
if (OP(REGNODE_p(ret)) == REFF) {
RExC_seen_d_op = TRUE;
}
*flagp |= HASWIDTH;
/* override incorrect value set in reganode MJD */
Set_Node_Offset(REGNODE_p(ret), parse_start);
Set_Node_Cur_Length(REGNODE_p(ret), parse_start-1);
skip_to_be_ignored_text(pRExC_state, &RExC_parse,
FALSE /* Don't force to /x */ );
}
break;
case '\0':
if (RExC_parse >= RExC_end)
FAIL("Trailing \\");
/* FALLTHROUGH */
default:
/* Do not generate "unrecognized" warnings here, we fall
back into the quick-grab loop below */
RExC_parse = parse_start;
goto defchar;
} /* end of switch on a \foo sequence */
break;
case '#':
/* '#' comments should have been spaced over before this function was
* called */
assert((RExC_flags & RXf_PMf_EXTENDED) == 0);
/*
if (RExC_flags & RXf_PMf_EXTENDED) {
RExC_parse = reg_skipcomment( pRExC_state, RExC_parse );
if (RExC_parse < RExC_end)
goto tryagain;
}
*/
/* FALLTHROUGH */
default:
defchar: {
/* Here, we have determined that the next thing is probably a
* literal character. RExC_parse points to the first byte of its
* definition. (It still may be an escape sequence that evaluates
* to a single character) */
STRLEN len = 0;
UV ender = 0;
char *p;
char *s;
/* This allows us to fill a node with just enough spare so that if the final
* character folds, its expansion is guaranteed to fit */
#define MAX_NODE_STRING_SIZE (255-UTF8_MAXBYTES_CASE)
char *s0;
U8 upper_parse = MAX_NODE_STRING_SIZE;
/* We start out as an EXACT node, even if under /i, until we find a
* character which is in a fold. The algorithm now segregates into
* separate nodes, characters that fold from those that don't under
* /i. (This hopefully will create nodes that are fixed strings
* even under /i, giving the optimizer something to grab on to.)
* So, if a node has something in it and the next character is in
* the opposite category, that node is closed up, and the function
* returns. Then regatom is called again, and a new node is
* created for the new category. */
U8 node_type = EXACT;
/* Assume the node will be fully used; the excess is given back at
* the end. We can't make any other length assumptions, as a byte
* input sequence could shrink down. */
Ptrdiff_t initial_size = STR_SZ(256);
bool next_is_quantifier;
char * oldp = NULL;
/* We can convert EXACTF nodes to EXACTFU if they contain only
* characters that match identically regardless of the target
* string's UTF8ness. The reason to do this is that EXACTF is not
* trie-able, EXACTFU is, and EXACTFU requires fewer operations at
* runtime.
*
* Similarly, we can convert EXACTFL nodes to EXACTFLU8 if they
* contain only above-Latin1 characters (hence must be in UTF8),
* which don't participate in folds with Latin1-range characters,
* as the latter's folds aren't known until runtime. */
bool maybe_exactfu = FOLD && (DEPENDS_SEMANTICS || LOC);
/* Single-character EXACTish nodes are almost always SIMPLE. This
* allows us to override this as encountered */
U8 maybe_SIMPLE = SIMPLE;
/* Does this node contain something that can't match unless the
* target string is (also) in UTF-8 */
bool requires_utf8_target = FALSE;
/* The sequence 'ss' is problematic in non-UTF-8 patterns. */
bool has_ss = FALSE;
/* So is the MICRO SIGN */
bool has_micro_sign = FALSE;
/* Allocate an EXACT node. The node_type may change below to
* another EXACTish node, but since the size of the node doesn't
* change, it works */
ret = regnode_guts(pRExC_state, node_type, initial_size, "exact");
FILL_NODE(ret, node_type);
RExC_emit++;
s = STRING(REGNODE_p(ret));
s0 = s;
reparse:
/* This breaks under rare circumstances. If folding, we do not
* want to split a node at a character that is a non-final in a
* multi-char fold, as an input string could just happen to want to
* match across the node boundary. The code at the end of the loop
* looks for this, and backs off until it finds not such a
* character, but it is possible (though extremely, extremely
* unlikely) for all characters in the node to be non-final fold
* ones, in which case we just leave the node fully filled, and
* hope that it doesn't match the string in just the wrong place */
assert( ! UTF /* Is at the beginning of a character */
|| UTF8_IS_INVARIANT(UCHARAT(RExC_parse))
|| UTF8_IS_START(UCHARAT(RExC_parse)));
/* Here, we have a literal character. Find the maximal string of
* them in the input that we can fit into a single EXACTish node.
* We quit at the first non-literal or when the node gets full, or
* under /i the categorization of folding/non-folding character
* changes */
for (p = RExC_parse; len < upper_parse && p < RExC_end; ) {
/* In most cases each iteration adds one byte to the output.
* The exceptions override this */
Size_t added_len = 1;
oldp = p;
/* White space has already been ignored */
assert( (RExC_flags & RXf_PMf_EXTENDED) == 0
|| ! is_PATWS_safe((p), RExC_end, UTF));
switch ((U8)*p) {
case '^':
case '$':
case '.':
case '[':
case '(':
case ')':
case '|':
goto loopdone;
case '\\':
/* Literal Escapes Switch
This switch is meant to handle escape sequences that
resolve to a literal character.
Every escape sequence that represents something
else, like an assertion or a char class, is handled
in the switch marked 'Special Escapes' above in this
routine, but also has an entry here as anything that
isn't explicitly mentioned here will be treated as
an unescaped equivalent literal.
*/
switch ((U8)*++p) {
/* These are all the special escapes. */
case 'A': /* Start assertion */
case 'b': case 'B': /* Word-boundary assertion*/
case 'C': /* Single char !DANGEROUS! */
case 'd': case 'D': /* digit class */
case 'g': case 'G': /* generic-backref, pos assertion */
case 'h': case 'H': /* HORIZWS */
case 'k': case 'K': /* named backref, keep marker */
case 'p': case 'P': /* Unicode property */
case 'R': /* LNBREAK */
case 's': case 'S': /* space class */
case 'v': case 'V': /* VERTWS */
case 'w': case 'W': /* word class */
case 'X': /* eXtended Unicode "combining
character sequence" */
case 'z': case 'Z': /* End of line/string assertion */
--p;
goto loopdone;
/* Anything after here is an escape that resolves to a
literal. (Except digits, which may or may not)
*/
case 'n':
ender = '\n';
p++;
break;
case 'N': /* Handle a single-code point named character. */
RExC_parse = p + 1;
if (! grok_bslash_N(pRExC_state,
NULL, /* Fail if evaluates to
anything other than a
single code point */
&ender, /* The returned single code
point */
NULL, /* Don't need a count of
how many code points */
flagp,
RExC_strict,
depth)
) {
if (*flagp & NEED_UTF8)
FAIL("panic: grok_bslash_N set NEED_UTF8");
RETURN_FAIL_ON_RESTART_FLAGP(flagp);
/* Here, it wasn't a single code point. Go close
* up this EXACTish node. The switch() prior to
* this switch handles the other cases */
RExC_parse = p = oldp;
goto loopdone;
}
p = RExC_parse;
RExC_parse = parse_start;
/* The \N{} means the pattern, if previously /d,
* becomes /u. That means it can't be an EXACTF node,
* but an EXACTFU */
if (node_type == EXACTF) {
node_type = EXACTFU;
/* If the node already contains something that
* differs between EXACTF and EXACTFU, reparse it
* as EXACTFU */
if (! maybe_exactfu) {
len = 0;
s = s0;
goto reparse;
}
}
break;
case 'r':
ender = '\r';
p++;
break;
case 't':
ender = '\t';
p++;
break;
case 'f':
ender = '\f';
p++;
break;
case 'e':
ender = ESC_NATIVE;
p++;
break;
case 'a':
ender = '\a';
p++;
break;
case 'o':
{
UV result;
const char* error_msg;
bool valid = grok_bslash_o(&p,
RExC_end,
&result,
&error_msg,
TO_OUTPUT_WARNINGS(p),
(bool) RExC_strict,
TRUE, /* Output warnings
for non-
portables */
UTF);
if (! valid) {
RExC_parse = p; /* going to die anyway; point
to exact spot of failure */
vFAIL(error_msg);
}
UPDATE_WARNINGS_LOC(p - 1);
ender = result;
break;
}
case 'x':
{
UV result = UV_MAX; /* initialize to erroneous
value */
const char* error_msg;
bool valid = grok_bslash_x(&p,
RExC_end,
&result,
&error_msg,
TO_OUTPUT_WARNINGS(p),
(bool) RExC_strict,
TRUE, /* Silence warnings
for non-
portables */
UTF);
if (! valid) {
RExC_parse = p; /* going to die anyway; point
to exact spot of failure */
vFAIL(error_msg);
}
UPDATE_WARNINGS_LOC(p - 1);
ender = result;
if (ender < 0x100) {
#ifdef EBCDIC
if (RExC_recode_x_to_native) {
ender = LATIN1_TO_NATIVE(ender);
}
#endif
}
break;
}
case 'c':
p++;
ender = grok_bslash_c(*p, TO_OUTPUT_WARNINGS(p));
UPDATE_WARNINGS_LOC(p);
p++;
break;
case '8': case '9': /* must be a backreference */
--p;
/* we have an escape like \8 which cannot be an octal escape
* so we exit the loop, and let the outer loop handle this
* escape which may or may not be a legitimate backref. */
goto loopdone;
case '1': case '2': case '3':case '4':
case '5': case '6': case '7':
/* When we parse backslash escapes there is ambiguity
* between backreferences and octal escapes. Any escape
* from \1 - \9 is a backreference, any multi-digit
* escape which does not start with 0 and which when
* evaluated as decimal could refer to an already
* parsed capture buffer is a back reference. Anything
* else is octal.
*
* Note this implies that \118 could be interpreted as
* 118 OR as "\11" . "8" depending on whether there
* were 118 capture buffers defined already in the
* pattern. */
/* NOTE, RExC_npar is 1 more than the actual number of
* parens we have seen so far, hence the "<" as opposed
* to "<=" */
if ( !isDIGIT(p[1]) || S_backref_value(p, RExC_end) < RExC_npar)
{ /* Not to be treated as an octal constant, go
find backref */
--p;
goto loopdone;
}
/* FALLTHROUGH */
case '0':
{
I32 flags = PERL_SCAN_SILENT_ILLDIGIT;
STRLEN numlen = 3;
ender = grok_oct(p, &numlen, &flags, NULL);
p += numlen;
if ( isDIGIT(*p) /* like \08, \178 */
&& ckWARN(WARN_REGEXP)
&& numlen < 3)
{
reg_warn_non_literal_string(
p + 1,
form_short_octal_warning(p, numlen));
}
}
break;
case '\0':
if (p >= RExC_end)
FAIL("Trailing \\");
/* FALLTHROUGH */
default:
if (isALPHANUMERIC(*p)) {
/* An alpha followed by '{' is going to fail next
* iteration, so don't output this warning in that
* case */
if (! isALPHA(*p) || *(p + 1) != '{') {
ckWARN2reg(p + 1, "Unrecognized escape \\%.1s"
" passed through", p);
}
}
goto normal_default;
} /* End of switch on '\' */
break;
case '{':
/* Trying to gain new uses for '{' without breaking too
* much existing code is hard. The solution currently
* adopted is:
* 1) If there is no ambiguity that a '{' should always
* be taken literally, at the start of a construct, we
* just do so.
* 2) If the literal '{' conflicts with our desired use
* of it as a metacharacter, we die. The deprecation
* cycles for this have come and gone.
* 3) If there is ambiguity, we raise a simple warning.
* This could happen, for example, if the user
* intended it to introduce a quantifier, but slightly
* misspelled the quantifier. Without this warning,
* the quantifier would silently be taken as a literal
* string of characters instead of a meta construct */
if (len || (p > RExC_start && isALPHA_A(*(p - 1)))) {
if ( RExC_strict
|| ( p > parse_start + 1
&& isALPHA_A(*(p - 1))
&& *(p - 2) == '\\')
|| new_regcurly(p, RExC_end))
{
RExC_parse = p + 1;
vFAIL("Unescaped left brace in regex is "
"illegal here");
}
ckWARNreg(p + 1, "Unescaped left brace in regex is"
" passed through");
}
goto normal_default;
case '}':
case ']':
if (p > RExC_parse && RExC_strict) {
ckWARN2reg(p + 1, "Unescaped literal '%c'", *p);
}
/*FALLTHROUGH*/
default: /* A literal character */
normal_default:
if (! UTF8_IS_INVARIANT(*p) && UTF) {
STRLEN numlen;
ender = utf8n_to_uvchr((U8*)p, RExC_end - p,
&numlen, UTF8_ALLOW_DEFAULT);
p += numlen;
}
else
ender = (U8) *p++;
break;
} /* End of switch on the literal */
/* Here, have looked at the literal character, and <ender>
* contains its ordinal; <p> points to the character after it.
* */
if (ender > 255) {
REQUIRE_UTF8(flagp);
}
/* We need to check if the next non-ignored thing is a
* quantifier. Move <p> to after anything that should be
* ignored, which, as a side effect, positions <p> for the next
* loop iteration */
skip_to_be_ignored_text(pRExC_state, &p,
FALSE /* Don't force to /x */ );
/* If the next thing is a quantifier, it applies to this
* character only, which means that this character has to be in
* its own node and can't just be appended to the string in an
* existing node, so if there are already other characters in
* the node, close the node with just them, and set up to do
* this character again next time through, when it will be the
* only thing in its new node */
next_is_quantifier = LIKELY(p < RExC_end)
&& UNLIKELY(ISMULT2(p));
if (next_is_quantifier && LIKELY(len)) {
p = oldp;
goto loopdone;
}
/* Ready to add 'ender' to the node */
if (! FOLD) { /* The simple case, just append the literal */
not_fold_common:
if (UVCHR_IS_INVARIANT(ender) || ! UTF) {
*(s++) = (char) ender;
}
else {
U8 * new_s = uvchr_to_utf8((U8*)s, ender);
added_len = (char *) new_s - s;
s = (char *) new_s;
if (ender > 255) {
requires_utf8_target = TRUE;
}
}
}
else if (LOC && is_PROBLEMATIC_LOCALE_FOLD_cp(ender)) {
/* Here are folding under /l, and the code point is
* problematic. If this is the first character in the
* node, change the node type to folding. Otherwise, if
* this is the first problematic character, close up the
* existing node, so can start a new node with this one */
if (! len) {
node_type = EXACTFL;
RExC_contains_locale = 1;
}
else if (node_type == EXACT) {
p = oldp;
goto loopdone;
}
/* This problematic code point means we can't simplify
* things */
maybe_exactfu = FALSE;
/* Here, we are adding a problematic fold character.
* "Problematic" in this context means that its fold isn't
* known until runtime. (The non-problematic code points
* are the above-Latin1 ones that fold to also all
* above-Latin1. Their folds don't vary no matter what the
* locale is.) But here we have characters whose fold
* depends on the locale. We just add in the unfolded
* character, and wait until runtime to fold it */
goto not_fold_common;
}
else /* regular fold; see if actually is in a fold */
if ( (ender < 256 && ! IS_IN_SOME_FOLD_L1(ender))
|| (ender > 255
&& ! _invlist_contains_cp(PL_in_some_fold, ender)))
{
/* Here, folding, but the character isn't in a fold.
*
* Start a new node if previous characters in the node were
* folded */
if (len && node_type != EXACT) {
p = oldp;
goto loopdone;
}
/* Here, continuing a node with non-folded characters. Add
* this one */
goto not_fold_common;
}
else { /* Here, does participate in some fold */
/* If this is the first character in the node, change its
* type to folding. Otherwise, if this is the first
* folding character in the node, close up the existing
* node, so can start a new node with this one. */
if (! len) {
node_type = compute_EXACTish(pRExC_state);
}
else if (node_type == EXACT) {
p = oldp;
goto loopdone;
}
if (UTF) { /* Use the folded value */
if (UVCHR_IS_INVARIANT(ender)) {
*(s)++ = (U8) toFOLD(ender);
}
else {
ender = _to_uni_fold_flags(
ender,
(U8 *) s,
&added_len,
FOLD_FLAGS_FULL | ((ASCII_FOLD_RESTRICTED)
? FOLD_FLAGS_NOMIX_ASCII
: 0));
s += added_len;
if ( ender > 255
&& LIKELY(ender != GREEK_SMALL_LETTER_MU))
{
/* U+B5 folds to the MU, so its possible for a
* non-UTF-8 target to match it */
requires_utf8_target = TRUE;
}
}
}
else {
/* Here is non-UTF8. First, see if the character's
* fold differs between /d and /u. */
if (PL_fold[ender] != PL_fold_latin1[ender]) {
maybe_exactfu = FALSE;
}
#if UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */ \
|| (UNICODE_MAJOR_VERSION == 3 && ( UNICODE_DOT_VERSION > 0) \
|| UNICODE_DOT_DOT_VERSION > 0)
/* On non-ancient Unicode versions, this includes the
* multi-char fold SHARP S to 'ss' */
if ( UNLIKELY(ender == LATIN_SMALL_LETTER_SHARP_S)
|| ( isALPHA_FOLD_EQ(ender, 's')
&& len > 0
&& isALPHA_FOLD_EQ(*(s-1), 's')))
{
/* Here, we have one of the following:
* a) a SHARP S. This folds to 'ss' only under
* /u rules. If we are in that situation,
* fold the SHARP S to 'ss'. See the comments
* for join_exact() as to why we fold this
* non-UTF at compile time, and no others.
* b) 'ss'. When under /u, there's nothing
* special needed to be done here. The
* previous iteration handled the first 's',
* and this iteration will handle the second.
* If, on the otherhand it's not /u, we have
* to exclude the possibility of moving to /u,
* so that we won't generate an unwanted
* match, unless, at runtime, the target
* string is in UTF-8.
* */
has_ss = TRUE;
maybe_exactfu = FALSE; /* Can't generate an
EXACTFU node (unless we
already are in one) */
if (UNLIKELY(ender == LATIN_SMALL_LETTER_SHARP_S)) {
maybe_SIMPLE = 0;
if (node_type == EXACTFU) {
*(s++) = 's';
/* Let the code below add in the extra 's' */
ender = 's';
added_len = 2;
}
}
}
#endif
else if (UNLIKELY(ender == MICRO_SIGN)) {
has_micro_sign = TRUE;
}
*(s++) = (DEPENDS_SEMANTICS)
? (char) toFOLD(ender)
/* Under /u, the fold of any character in
* the 0-255 range happens to be its
* lowercase equivalent, except for LATIN
* SMALL LETTER SHARP S, which was handled
* above, and the MICRO SIGN, whose fold
* requires UTF-8 to represent. */
: (char) toLOWER_L1(ender);
}
} /* End of adding current character to the node */
len += added_len;
if (next_is_quantifier) {
/* Here, the next input is a quantifier, and to get here,
* the current character is the only one in the node. */
goto loopdone;
}
} /* End of loop through literal characters */
/* Here we have either exhausted the input or ran out of room in
* the node. (If we encountered a character that can't be in the
* node, transfer is made directly to <loopdone>, and so we
* wouldn't have fallen off the end of the loop.) In the latter
* case, we artificially have to split the node into two, because
* we just don't have enough space to hold everything. This
* creates a problem if the final character participates in a
* multi-character fold in the non-final position, as a match that
* should have occurred won't, due to the way nodes are matched,
* and our artificial boundary. So back off until we find a non-
* problematic character -- one that isn't at the beginning or
* middle of such a fold. (Either it doesn't participate in any
* folds, or appears only in the final position of all the folds it
* does participate in.) A better solution with far fewer false
* positives, and that would fill the nodes more completely, would
* be to actually have available all the multi-character folds to
* test against, and to back-off only far enough to be sure that
* this node isn't ending with a partial one. <upper_parse> is set
* further below (if we need to reparse the node) to include just
* up through that final non-problematic character that this code
* identifies, so when it is set to less than the full node, we can
* skip the rest of this */
if (FOLD && p < RExC_end && upper_parse == MAX_NODE_STRING_SIZE) {
PERL_UINT_FAST8_T backup_count = 0;
const STRLEN full_len = len;
assert(len >= MAX_NODE_STRING_SIZE);
/* Here, <s> points to just beyond where we have output the
* final character of the node. Look backwards through the
* string until find a non- problematic character */
if (! UTF) {
/* This has no multi-char folds to non-UTF characters */
if (ASCII_FOLD_RESTRICTED) {
goto loopdone;
}
while (--s >= s0 && IS_NON_FINAL_FOLD(*s)) {
backup_count++;
}
len = s - s0 + 1;
}
else {
/* Point to the first byte of the final character */
s = (char *) utf8_hop_back((U8 *) s, -1, (U8 *) s0);
while (s >= s0) { /* Search backwards until find
a non-problematic char */
if (UTF8_IS_INVARIANT(*s)) {
/* There are no ascii characters that participate
* in multi-char folds under /aa. In EBCDIC, the
* non-ascii invariants are all control characters,
* so don't ever participate in any folds. */
if (ASCII_FOLD_RESTRICTED
|| ! IS_NON_FINAL_FOLD(*s))
{
break;
}
}
else if (UTF8_IS_DOWNGRADEABLE_START(*s)) {
if (! IS_NON_FINAL_FOLD(EIGHT_BIT_UTF8_TO_NATIVE(
*s, *(s+1))))
{
break;
}
}
else if (! _invlist_contains_cp(
PL_NonFinalFold,
valid_utf8_to_uvchr((U8 *) s, NULL)))
{
break;
}
/* Here, the current character is problematic in that
* it does occur in the non-final position of some
* fold, so try the character before it, but have to
* special case the very first byte in the string, so
* we don't read outside the string */
s = (s == s0) ? s -1 : (char *) utf8_hop((U8 *) s, -1);
backup_count++;
} /* End of loop backwards through the string */
/* If there were only problematic characters in the string,
* <s> will point to before s0, in which case the length
* should be 0, otherwise include the length of the
* non-problematic character just found */
len = (s < s0) ? 0 : s - s0 + UTF8SKIP(s);
}
/* Here, have found the final character, if any, that is
* non-problematic as far as ending the node without splitting
* it across a potential multi-char fold. <len> contains the
* number of bytes in the node up-to and including that
* character, or is 0 if there is no such character, meaning
* the whole node contains only problematic characters. In
* this case, give up and just take the node as-is. We can't
* do any better */
if (len == 0) {
len = full_len;
} else {
/* Here, the node does contain some characters that aren't
* problematic. If we didn't have to backup any, then the
* final character in the node is non-problematic, and we
* can take the node as-is */
if (backup_count == 0) {
goto loopdone;
}
else if (backup_count == 1) {
/* If the final character is problematic, but the
* penultimate is not, back-off that last character to
* later start a new node with it */
p = oldp;
goto loopdone;
}
/* Here, the final non-problematic character is earlier
* in the input than the penultimate character. What we do
* is reparse from the beginning, going up only as far as
* this final ok one, thus guaranteeing that the node ends
* in an acceptable character. The reason we reparse is
* that we know how far in the character is, but we don't
* know how to correlate its position with the input parse.
* An alternate implementation would be to build that
* correlation as we go along during the original parse,
* but that would entail extra work for every node, whereas
* this code gets executed only when the string is too
* large for the node, and the final two characters are
* problematic, an infrequent occurrence. Yet another
* possible strategy would be to save the tail of the
* string, and the next time regatom is called, initialize
* with that. The problem with this is that unless you
* back off one more character, you won't be guaranteed
* regatom will get called again, unless regbranch,
* regpiece ... are also changed. If you do back off that
* extra character, so that there is input guaranteed to
* force calling regatom, you can't handle the case where
* just the first character in the node is acceptable. I
* (khw) decided to try this method which doesn't have that
* pitfall; if performance issues are found, we can do a
* combination of the current approach plus that one */
upper_parse = len;
len = 0;
s = s0;
goto reparse;
}
} /* End of verifying node ends with an appropriate char */
loopdone: /* Jumped to when encounters something that shouldn't be
in the node */
/* Free up any over-allocated space; cast is to silence bogus
* warning in MS VC */
change_engine_size(pRExC_state,
- (Ptrdiff_t) (initial_size - STR_SZ(len)));
/* I (khw) don't know if you can get here with zero length, but the
* old code handled this situation by creating a zero-length EXACT
* node. Might as well be NOTHING instead */
if (len == 0) {
OP(REGNODE_p(ret)) = NOTHING;
}
else {
/* If the node type is EXACT here, check to see if it
* should be EXACTL, or EXACT_ONLY8. */
if (node_type == EXACT) {
if (LOC) {
node_type = EXACTL;
}
else if (requires_utf8_target) {
node_type = EXACT_ONLY8;
}
} else if (FOLD) {
if ( UNLIKELY(has_micro_sign || has_ss)
&& (node_type == EXACTFU || ( node_type == EXACTF
&& maybe_exactfu)))
{ /* These two conditions are problematic in non-UTF-8
EXACTFU nodes. */
assert(! UTF);
node_type = EXACTFUP;
}
else if (node_type == EXACTFL) {
/* 'maybe_exactfu' is deliberately set above to
* indicate this node type, where all code points in it
* are above 255 */
if (maybe_exactfu) {
node_type = EXACTFLU8;
}
else if (UNLIKELY(
_invlist_contains_cp(PL_HasMultiCharFold, ender)))
{
/* A character that folds to more than one will
* match multiple characters, so can't be SIMPLE.
* We don't have to worry about this with EXACTFLU8
* nodes just above, as they have already been
* folded (since the fold doesn't vary at run
* time). Here, if the final character in the node
* folds to multiple, it can't be simple. (This
* only has an effect if the node has only a single
* character, hence the final one, as elsewhere we
* turn off simple for nodes whose length > 1 */
maybe_SIMPLE = 0;
}
}
else if (node_type == EXACTF) { /* Means is /di */
/* If 'maybe_exactfu' is clear, then we need to stay
* /di. If it is set, it means there are no code
* points that match differently depending on UTF8ness
* of the target string, so it can become an EXACTFU
* node */
if (! maybe_exactfu) {
RExC_seen_d_op = TRUE;
}
else if ( isALPHA_FOLD_EQ(* STRING(REGNODE_p(ret)), 's')
|| isALPHA_FOLD_EQ(ender, 's'))
{
/* But, if the node begins or ends in an 's' we
* have to defer changing it into an EXACTFU, as
* the node could later get joined with another one
* that ends or begins with 's' creating an 'ss'
* sequence which would then wrongly match the
* sharp s without the target being UTF-8. We
* create a special node that we resolve later when
* we join nodes together */
node_type = EXACTFU_S_EDGE;
}
else {
node_type = EXACTFU;
}
}
if (requires_utf8_target && node_type == EXACTFU) {
node_type = EXACTFU_ONLY8;
}
}
OP(REGNODE_p(ret)) = node_type;
STR_LEN(REGNODE_p(ret)) = len;
RExC_emit += STR_SZ(len);
/* If the node isn't a single character, it can't be SIMPLE */
if (len > (Size_t) ((UTF) ? UVCHR_SKIP(ender) : 1)) {
maybe_SIMPLE = 0;
}
*flagp |= HASWIDTH | maybe_SIMPLE;
}
Set_Node_Length(REGNODE_p(ret), p - parse_start - 1);
RExC_parse = p;
{
/* len is STRLEN which is unsigned, need to copy to signed */
IV iv = len;
if (iv < 0)
vFAIL("Internal disaster");
}
} /* End of label 'defchar:' */
break;
} /* End of giant switch on input character */
/* Position parse to next real character */
skip_to_be_ignored_text(pRExC_state, &RExC_parse,
FALSE /* Don't force to /x */ );
if ( *RExC_parse == '{'
&& OP(REGNODE_p(ret)) != SBOL && ! regcurly(RExC_parse))
{
if (RExC_strict || new_regcurly(RExC_parse, RExC_end)) {
RExC_parse++;
vFAIL("Unescaped left brace in regex is illegal here");
}
ckWARNreg(RExC_parse + 1, "Unescaped left brace in regex is"
" passed through");
}
return(ret);
}
STATIC void
S_populate_ANYOF_from_invlist(pTHX_ regnode *node, SV** invlist_ptr)
{
/* Uses the inversion list '*invlist_ptr' to populate the ANYOF 'node'. It
* sets up the bitmap and any flags, removing those code points from the
* inversion list, setting it to NULL should it become completely empty */
dVAR;
PERL_ARGS_ASSERT_POPULATE_ANYOF_FROM_INVLIST;
assert(PL_regkind[OP(node)] == ANYOF);
/* There is no bitmap for this node type */
if (OP(node) == ANYOFH) {
return;
}
ANYOF_BITMAP_ZERO(node);
if (*invlist_ptr) {
/* This gets set if we actually need to modify things */
bool change_invlist = FALSE;
UV start, end;
/* Start looking through *invlist_ptr */
invlist_iterinit(*invlist_ptr);
while (invlist_iternext(*invlist_ptr, &start, &end)) {
UV high;
int i;
if (end == UV_MAX && start <= NUM_ANYOF_CODE_POINTS) {
ANYOF_FLAGS(node) |= ANYOF_MATCHES_ALL_ABOVE_BITMAP;
}
/* Quit if are above what we should change */
if (start >= NUM_ANYOF_CODE_POINTS) {
break;
}
change_invlist = TRUE;
/* Set all the bits in the range, up to the max that we are doing */
high = (end < NUM_ANYOF_CODE_POINTS - 1)
? end
: NUM_ANYOF_CODE_POINTS - 1;
for (i = start; i <= (int) high; i++) {
if (! ANYOF_BITMAP_TEST(node, i)) {
ANYOF_BITMAP_SET(node, i);
}
}
}
invlist_iterfinish(*invlist_ptr);
/* Done with loop; remove any code points that are in the bitmap from
* *invlist_ptr; similarly for code points above the bitmap if we have
* a flag to match all of them anyways */
if (change_invlist) {
_invlist_subtract(*invlist_ptr, PL_InBitmap, invlist_ptr);
}
if (ANYOF_FLAGS(node) & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
_invlist_intersection(*invlist_ptr, PL_InBitmap, invlist_ptr);
}
/* If have completely emptied it, remove it completely */
if (_invlist_len(*invlist_ptr) == 0) {
SvREFCNT_dec_NN(*invlist_ptr);
*invlist_ptr = NULL;
}
}
}
/* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
Character classes ([:foo:]) can also be negated ([:^foo:]).
Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
but trigger failures because they are currently unimplemented. */
#define POSIXCC_DONE(c) ((c) == ':')
#define POSIXCC_NOTYET(c) ((c) == '=' || (c) == '.')
#define POSIXCC(c) (POSIXCC_DONE(c) || POSIXCC_NOTYET(c))
#define MAYBE_POSIXCC(c) (POSIXCC(c) || (c) == '^' || (c) == ';')
#define WARNING_PREFIX "Assuming NOT a POSIX class since "
#define NO_BLANKS_POSIX_WARNING "no blanks are allowed in one"
#define SEMI_COLON_POSIX_WARNING "a semi-colon was found instead of a colon"
#define NOT_MEANT_TO_BE_A_POSIX_CLASS (OOB_NAMEDCLASS - 1)
/* 'posix_warnings' and 'warn_text' are names of variables in the following
* routine. q.v. */
#define ADD_POSIX_WARNING(p, text) STMT_START { \
if (posix_warnings) { \
if (! RExC_warn_text ) RExC_warn_text = \
(AV *) sv_2mortal((SV *) newAV()); \
av_push(RExC_warn_text, Perl_newSVpvf(aTHX_ \
WARNING_PREFIX \
text \
REPORT_LOCATION, \
REPORT_LOCATION_ARGS(p))); \
} \
} STMT_END
#define CLEAR_POSIX_WARNINGS() \
STMT_START { \
if (posix_warnings && RExC_warn_text) \
av_clear(RExC_warn_text); \
} STMT_END
#define CLEAR_POSIX_WARNINGS_AND_RETURN(ret) \
STMT_START { \
CLEAR_POSIX_WARNINGS(); \
return ret; \
} STMT_END
STATIC int
S_handle_possible_posix(pTHX_ RExC_state_t *pRExC_state,
const char * const s, /* Where the putative posix class begins.
Normally, this is one past the '['. This
parameter exists so it can be somewhere
besides RExC_parse. */
char ** updated_parse_ptr, /* Where to set the updated parse pointer, or
NULL */
AV ** posix_warnings, /* Where to place any generated warnings, or
NULL */
const bool check_only /* Don't die if error */
)
{
/* This parses what the caller thinks may be one of the three POSIX
* constructs:
* 1) a character class, like [:blank:]
* 2) a collating symbol, like [. .]
* 3) an equivalence class, like [= =]
* In the latter two cases, it croaks if it finds a syntactically legal
* one, as these are not handled by Perl.
*
* The main purpose is to look for a POSIX character class. It returns:
* a) the class number
* if it is a completely syntactically and semantically legal class.
* 'updated_parse_ptr', if not NULL, is set to point to just after the
* closing ']' of the class
* b) OOB_NAMEDCLASS
* if it appears that one of the three POSIX constructs was meant, but
* its specification was somehow defective. 'updated_parse_ptr', if
* not NULL, is set to point to the character just after the end
* character of the class. See below for handling of warnings.
* c) NOT_MEANT_TO_BE_A_POSIX_CLASS
* if it doesn't appear that a POSIX construct was intended.
* 'updated_parse_ptr' is not changed. No warnings nor errors are
* raised.
*
* In b) there may be errors or warnings generated. If 'check_only' is
* TRUE, then any errors are discarded. Warnings are returned to the
* caller via an AV* created into '*posix_warnings' if it is not NULL. If
* instead it is NULL, warnings are suppressed.
*
* The reason for this function, and its complexity is that a bracketed
* character class can contain just about anything. But it's easy to
* mistype the very specific posix class syntax but yielding a valid
* regular bracketed class, so it silently gets compiled into something
* quite unintended.
*
* The solution adopted here maintains backward compatibility except that
* it adds a warning if it looks like a posix class was intended but
* improperly specified. The warning is not raised unless what is input
* very closely resembles one of the 14 legal posix classes. To do this,
* it uses fuzzy parsing. It calculates how many single-character edits it
* would take to transform what was input into a legal posix class. Only
* if that number is quite small does it think that the intention was a
* posix class. Obviously these are heuristics, and there will be cases
* where it errs on one side or another, and they can be tweaked as
* experience informs.
*
* The syntax for a legal posix class is:
*
* qr/(?xa: \[ : \^? [[:lower:]]{4,6} : \] )/
*
* What this routine considers syntactically to be an intended posix class
* is this (the comments indicate some restrictions that the pattern
* doesn't show):
*
* qr/(?x: \[? # The left bracket, possibly
* # omitted
* \h* # possibly followed by blanks
* (?: \^ \h* )? # possibly a misplaced caret
* [:;]? # The opening class character,
* # possibly omitted. A typo
* # semi-colon can also be used.
* \h*
* \^? # possibly a correctly placed
* # caret, but not if there was also
* # a misplaced one
* \h*
* .{3,15} # The class name. If there are
* # deviations from the legal syntax,
* # its edit distance must be close
* # to a real class name in order
* # for it to be considered to be
* # an intended posix class.
* \h*
* [[:punct:]]? # The closing class character,
* # possibly omitted. If not a colon
* # nor semi colon, the class name
* # must be even closer to a valid
* # one
* \h*
* \]? # The right bracket, possibly
* # omitted.
* )/
*
* In the above, \h must be ASCII-only.
*
* These are heuristics, and can be tweaked as field experience dictates.
* There will be cases when someone didn't intend to specify a posix class
* that this warns as being so. The goal is to minimize these, while
* maximizing the catching of things intended to be a posix class that
* aren't parsed as such.
*/
const char* p = s;
const char * const e = RExC_end;
unsigned complement = 0; /* If to complement the class */
bool found_problem = FALSE; /* Assume OK until proven otherwise */
bool has_opening_bracket = FALSE;
bool has_opening_colon = FALSE;
int class_number = OOB_NAMEDCLASS; /* Out-of-bounds until find
valid class */
const char * possible_end = NULL; /* used for a 2nd parse pass */
const char* name_start; /* ptr to class name first char */
/* If the number of single-character typos the input name is away from a
* legal name is no more than this number, it is considered to have meant
* the legal name */
int max_distance = 2;
/* to store the name. The size determines the maximum length before we
* decide that no posix class was intended. Should be at least
* sizeof("alphanumeric") */
UV input_text[15];
STATIC_ASSERT_DECL(C_ARRAY_LENGTH(input_text) >= sizeof "alphanumeric");
PERL_ARGS_ASSERT_HANDLE_POSSIBLE_POSIX;
CLEAR_POSIX_WARNINGS();
if (p >= e) {
return NOT_MEANT_TO_BE_A_POSIX_CLASS;
}
if (*(p - 1) != '[') {
ADD_POSIX_WARNING(p, "it doesn't start with a '['");
found_problem = TRUE;
}
else {
has_opening_bracket = TRUE;
}
/* They could be confused and think you can put spaces between the
* components */
if (isBLANK(*p)) {
found_problem = TRUE;
do {
p++;
} while (p < e && isBLANK(*p));
ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
}
/* For [. .] and [= =]. These are quite different internally from [: :],
* so they are handled separately. */
if (POSIXCC_NOTYET(*p) && p < e - 3) /* 1 for the close, and 1 for the ']'
and 1 for at least one char in it
*/
{
const char open_char = *p;
const char * temp_ptr = p + 1;
/* These two constructs are not handled by perl, and if we find a
* syntactically valid one, we croak. khw, who wrote this code, finds
* this explanation of them very unclear:
* http://pubs.opengroup.org/onlinepubs/009696899/basedefs/xbd_chap09.html
* And searching the rest of the internet wasn't very helpful either.
* It looks like just about any byte can be in these constructs,
* depending on the locale. But unless the pattern is being compiled
* under /l, which is very rare, Perl runs under the C or POSIX locale.
* In that case, it looks like [= =] isn't allowed at all, and that
* [. .] could be any single code point, but for longer strings the
* constituent characters would have to be the ASCII alphabetics plus
* the minus-hyphen. Any sensible locale definition would limit itself
* to these. And any portable one definitely should. Trying to parse
* the general case is a nightmare (see [perl #127604]). So, this code
* looks only for interiors of these constructs that match:
* qr/.|[-\w]{2,}/
* Using \w relaxes the apparent rules a little, without adding much
* danger of mistaking something else for one of these constructs.
*
* [. .] in some implementations described on the internet is usable to
* escape a character that otherwise is special in bracketed character
* classes. For example [.].] means a literal right bracket instead of
* the ending of the class
*
* [= =] can legitimately contain a [. .] construct, but we don't
* handle this case, as that [. .] construct will later get parsed
* itself and croak then. And [= =] is checked for even when not under
* /l, as Perl has long done so.
*
* The code below relies on there being a trailing NUL, so it doesn't
* have to keep checking if the parse ptr < e.
*/
if (temp_ptr[1] == open_char) {
temp_ptr++;
}
else while ( temp_ptr < e
&& (isWORDCHAR(*temp_ptr) || *temp_ptr == '-'))
{
temp_ptr++;
}
if (*temp_ptr == open_char) {
temp_ptr++;
if (*temp_ptr == ']') {
temp_ptr++;
if (! found_problem && ! check_only) {
RExC_parse = (char *) temp_ptr;
vFAIL3("POSIX syntax [%c %c] is reserved for future "
"extensions", open_char, open_char);
}
/* Here, the syntax wasn't completely valid, or else the call
* is to check-only */
if (updated_parse_ptr) {
*updated_parse_ptr = (char *) temp_ptr;
}
CLEAR_POSIX_WARNINGS_AND_RETURN(OOB_NAMEDCLASS);
}
}
/* If we find something that started out to look like one of these
* constructs, but isn't, we continue below so that it can be checked
* for being a class name with a typo of '.' or '=' instead of a colon.
* */
}
/* Here, we think there is a possibility that a [: :] class was meant, and
* we have the first real character. It could be they think the '^' comes
* first */
if (*p == '^') {
found_problem = TRUE;
ADD_POSIX_WARNING(p + 1, "the '^' must come after the colon");
complement = 1;
p++;
if (isBLANK(*p)) {
found_problem = TRUE;
do {
p++;
} while (p < e && isBLANK(*p));
ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
}
}
/* But the first character should be a colon, which they could have easily
* mistyped on a qwerty keyboard as a semi-colon (and which may be hard to
* distinguish from a colon, so treat that as a colon). */
if (*p == ':') {
p++;
has_opening_colon = TRUE;
}
else if (*p == ';') {
found_problem = TRUE;
p++;
ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
has_opening_colon = TRUE;
}
else {
found_problem = TRUE;
ADD_POSIX_WARNING(p, "there must be a starting ':'");
/* Consider an initial punctuation (not one of the recognized ones) to
* be a left terminator */
if (*p != '^' && *p != ']' && isPUNCT(*p)) {
p++;
}
}
/* They may think that you can put spaces between the components */
if (isBLANK(*p)) {
found_problem = TRUE;
do {
p++;
} while (p < e && isBLANK(*p));
ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
}
if (*p == '^') {
/* We consider something like [^:^alnum:]] to not have been intended to
* be a posix class, but XXX maybe we should */
if (complement) {
CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
}
complement = 1;
p++;
}
/* Again, they may think that you can put spaces between the components */
if (isBLANK(*p)) {
found_problem = TRUE;
do {
p++;
} while (p < e && isBLANK(*p));
ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
}
if (*p == ']') {
/* XXX This ']' may be a typo, and something else was meant. But
* treating it as such creates enough complications, that that
* possibility isn't currently considered here. So we assume that the
* ']' is what is intended, and if we've already found an initial '[',
* this leaves this construct looking like [:] or [:^], which almost
* certainly weren't intended to be posix classes */
if (has_opening_bracket) {
CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
}
/* But this function can be called when we parse the colon for
* something like qr/[alpha:]]/, so we back up to look for the
* beginning */
p--;
if (*p == ';') {
found_problem = TRUE;
ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
}
else if (*p != ':') {
/* XXX We are currently very restrictive here, so this code doesn't
* consider the possibility that, say, /[alpha.]]/ was intended to
* be a posix class. */
CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
}
/* Here we have something like 'foo:]'. There was no initial colon,
* and we back up over 'foo. XXX Unlike the going forward case, we
* don't handle typos of non-word chars in the middle */
has_opening_colon = FALSE;
p--;
while (p > RExC_start && isWORDCHAR(*p)) {
p--;
}
p++;
/* Here, we have positioned ourselves to where we think the first
* character in the potential class is */
}
/* Now the interior really starts. There are certain key characters that
* can end the interior, or these could just be typos. To catch both
* cases, we may have to do two passes. In the first pass, we keep on
* going unless we come to a sequence that matches
* qr/ [[:punct:]] [[:blank:]]* \] /xa
* This means it takes a sequence to end the pass, so two typos in a row if
* that wasn't what was intended. If the class is perfectly formed, just
* this one pass is needed. We also stop if there are too many characters
* being accumulated, but this number is deliberately set higher than any
* real class. It is set high enough so that someone who thinks that
* 'alphanumeric' is a correct name would get warned that it wasn't.
* While doing the pass, we keep track of where the key characters were in
* it. If we don't find an end to the class, and one of the key characters
* was found, we redo the pass, but stop when we get to that character.
* Thus the key character was considered a typo in the first pass, but a
* terminator in the second. If two key characters are found, we stop at
* the second one in the first pass. Again this can miss two typos, but
* catches a single one
*
* In the first pass, 'possible_end' starts as NULL, and then gets set to
* point to the first key character. For the second pass, it starts as -1.
* */
name_start = p;
parse_name:
{
bool has_blank = FALSE;
bool has_upper = FALSE;
bool has_terminating_colon = FALSE;
bool has_terminating_bracket = FALSE;
bool has_semi_colon = FALSE;
unsigned int name_len = 0;
int punct_count = 0;
while (p < e) {
/* Squeeze out blanks when looking up the class name below */
if (isBLANK(*p) ) {
has_blank = TRUE;
found_problem = TRUE;
p++;
continue;
}
/* The name will end with a punctuation */
if (isPUNCT(*p)) {
const char * peek = p + 1;
/* Treat any non-']' punctuation followed by a ']' (possibly
* with intervening blanks) as trying to terminate the class.
* ']]' is very likely to mean a class was intended (but
* missing the colon), but the warning message that gets
* generated shows the error position better if we exit the
* loop at the bottom (eventually), so skip it here. */
if (*p != ']') {
if (peek < e && isBLANK(*peek)) {
has_blank = TRUE;
found_problem = TRUE;
do {
peek++;
} while (peek < e && isBLANK(*peek));
}
if (peek < e && *peek == ']') {
has_terminating_bracket = TRUE;
if (*p == ':') {
has_terminating_colon = TRUE;
}
else if (*p == ';') {
has_semi_colon = TRUE;
has_terminating_colon = TRUE;
}
else {
found_problem = TRUE;
}
p = peek + 1;
goto try_posix;
}
}
/* Here we have punctuation we thought didn't end the class.
* Keep track of the position of the key characters that are
* more likely to have been class-enders */
if (*p == ']' || *p == '[' || *p == ':' || *p == ';') {
/* Allow just one such possible class-ender not actually
* ending the class. */
if (possible_end) {
break;
}
possible_end = p;
}
/* If we have too many punctuation characters, no use in
* keeping going */
if (++punct_count > max_distance) {
break;
}
/* Treat the punctuation as a typo. */
input_text[name_len++] = *p;
p++;
}
else if (isUPPER(*p)) { /* Use lowercase for lookup */
input_text[name_len++] = toLOWER(*p);
has_upper = TRUE;
found_problem = TRUE;
p++;
} else if (! UTF || UTF8_IS_INVARIANT(*p)) {
input_text[name_len++] = *p;
p++;
}
else {
input_text[name_len++] = utf8_to_uvchr_buf((U8 *) p, e, NULL);
p+= UTF8SKIP(p);
}
/* The declaration of 'input_text' is how long we allow a potential
* class name to be, before saying they didn't mean a class name at
* all */
if (name_len >= C_ARRAY_LENGTH(input_text)) {
break;
}
}
/* We get to here when the possible class name hasn't been properly
* terminated before:
* 1) we ran off the end of the pattern; or
* 2) found two characters, each of which might have been intended to
* be the name's terminator
* 3) found so many punctuation characters in the purported name,
* that the edit distance to a valid one is exceeded
* 4) we decided it was more characters than anyone could have
* intended to be one. */
found_problem = TRUE;
/* In the final two cases, we know that looking up what we've
* accumulated won't lead to a match, even a fuzzy one. */
if ( name_len >= C_ARRAY_LENGTH(input_text)
|| punct_count > max_distance)
{
/* If there was an intermediate key character that could have been
* an intended end, redo the parse, but stop there */
if (possible_end && possible_end != (char *) -1) {
possible_end = (char *) -1; /* Special signal value to say
we've done a first pass */
p = name_start;
goto parse_name;
}
/* Otherwise, it can't have meant to have been a class */
CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
}
/* If we ran off the end, and the final character was a punctuation
* one, back up one, to look at that final one just below. Later, we
* will restore the parse pointer if appropriate */
if (name_len && p == e && isPUNCT(*(p-1))) {
p--;
name_len--;
}
if (p < e && isPUNCT(*p)) {
if (*p == ']') {
has_terminating_bracket = TRUE;
/* If this is a 2nd ']', and the first one is just below this
* one, consider that to be the real terminator. This gives a
* uniform and better positioning for the warning message */
if ( possible_end
&& possible_end != (char *) -1
&& *possible_end == ']'
&& name_len && input_text[name_len - 1] == ']')
{
name_len--;
p = possible_end;
/* And this is actually equivalent to having done the 2nd
* pass now, so set it to not try again */
possible_end = (char *) -1;
}
}
else {
if (*p == ':') {
has_terminating_colon = TRUE;
}
else if (*p == ';') {
has_semi_colon = TRUE;
has_terminating_colon = TRUE;
}
p++;
}
}
try_posix:
/* Here, we have a class name to look up. We can short circuit the
* stuff below for short names that can't possibly be meant to be a
* class name. (We can do this on the first pass, as any second pass
* will yield an even shorter name) */
if (name_len < 3) {
CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
}
/* Find which class it is. Initially switch on the length of the name.
* */
switch (name_len) {
case 4:
if (memEQs(name_start, 4, "word")) {
/* this is not POSIX, this is the Perl \w */
class_number = ANYOF_WORDCHAR;
}
break;
case 5:
/* Names all of length 5: alnum alpha ascii blank cntrl digit
* graph lower print punct space upper
* Offset 4 gives the best switch position. */
switch (name_start[4]) {
case 'a':
if (memBEGINs(name_start, 5, "alph")) /* alpha */
class_number = ANYOF_ALPHA;
break;
case 'e':
if (memBEGINs(name_start, 5, "spac")) /* space */
class_number = ANYOF_SPACE;
break;
case 'h':
if (memBEGINs(name_start, 5, "grap")) /* graph */
class_number = ANYOF_GRAPH;
break;
case 'i':
if (memBEGINs(name_start, 5, "asci")) /* ascii */
class_number = ANYOF_ASCII;
break;
case 'k':
if (memBEGINs(name_start, 5, "blan")) /* blank */
class_number = ANYOF_BLANK;
break;
case 'l':
if (memBEGINs(name_start, 5, "cntr")) /* cntrl */
class_number = ANYOF_CNTRL;
break;
case 'm':
if (memBEGINs(name_start, 5, "alnu")) /* alnum */
class_number = ANYOF_ALPHANUMERIC;
break;
case 'r':
if (memBEGINs(name_start, 5, "lowe")) /* lower */
class_number = (FOLD) ? ANYOF_CASED : ANYOF_LOWER;
else if (memBEGINs(name_start, 5, "uppe")) /* upper */
class_number = (FOLD) ? ANYOF_CASED : ANYOF_UPPER;
break;
case 't':
if (memBEGINs(name_start, 5, "digi")) /* digit */
class_number = ANYOF_DIGIT;
else if (memBEGINs(name_start, 5, "prin")) /* print */
class_number = ANYOF_PRINT;
else if (memBEGINs(name_start, 5, "punc")) /* punct */
class_number = ANYOF_PUNCT;
break;
}
break;
case 6:
if (memEQs(name_start, 6, "xdigit"))
class_number = ANYOF_XDIGIT;
break;
}
/* If the name exactly matches a posix class name the class number will
* here be set to it, and the input almost certainly was meant to be a
* posix class, so we can skip further checking. If instead the syntax
* is exactly correct, but the name isn't one of the legal ones, we
* will return that as an error below. But if neither of these apply,
* it could be that no posix class was intended at all, or that one
* was, but there was a typo. We tease these apart by doing fuzzy
* matching on the name */
if (class_number == OOB_NAMEDCLASS && found_problem) {
const UV posix_names[][6] = {
{ 'a', 'l', 'n', 'u', 'm' },
{ 'a', 'l', 'p', 'h', 'a' },
{ 'a', 's', 'c', 'i', 'i' },
{ 'b', 'l', 'a', 'n', 'k' },
{ 'c', 'n', 't', 'r', 'l' },
{ 'd', 'i', 'g', 'i', 't' },
{ 'g', 'r', 'a', 'p', 'h' },
{ 'l', 'o', 'w', 'e', 'r' },
{ 'p', 'r', 'i', 'n', 't' },
{ 'p', 'u', 'n', 'c', 't' },
{ 's', 'p', 'a', 'c', 'e' },
{ 'u', 'p', 'p', 'e', 'r' },
{ 'w', 'o', 'r', 'd' },
{ 'x', 'd', 'i', 'g', 'i', 't' }
};
/* The names of the above all have added NULs to make them the same
* size, so we need to also have the real lengths */
const UV posix_name_lengths[] = {
sizeof("alnum") - 1,
sizeof("alpha") - 1,
sizeof("ascii") - 1,
sizeof("blank") - 1,
sizeof("cntrl") - 1,
sizeof("digit") - 1,
sizeof("graph") - 1,
sizeof("lower") - 1,
sizeof("print") - 1,
sizeof("punct") - 1,
sizeof("space") - 1,
sizeof("upper") - 1,
sizeof("word") - 1,
sizeof("xdigit")- 1
};
unsigned int i;
int temp_max = max_distance; /* Use a temporary, so if we
reparse, we haven't changed the
outer one */
/* Use a smaller max edit distance if we are missing one of the
* delimiters */
if ( has_opening_bracket + has_opening_colon < 2
|| has_terminating_bracket + has_terminating_colon < 2)
{
temp_max--;
}
/* See if the input name is close to a legal one */
for (i = 0; i < C_ARRAY_LENGTH(posix_names); i++) {
/* Short circuit call if the lengths are too far apart to be
* able to match */
if (abs( (int) (name_len - posix_name_lengths[i]))
> temp_max)
{
continue;
}
if (edit_distance(input_text,
posix_names[i],
name_len,
posix_name_lengths[i],
temp_max
)
> -1)
{ /* If it is close, it probably was intended to be a class */
goto probably_meant_to_be;
}
}
/* Here the input name is not close enough to a valid class name
* for us to consider it to be intended to be a posix class. If
* we haven't already done so, and the parse found a character that
* could have been terminators for the name, but which we absorbed
* as typos during the first pass, repeat the parse, signalling it
* to stop at that character */
if (possible_end && possible_end != (char *) -1) {
possible_end = (char *) -1;
p = name_start;
goto parse_name;
}
/* Here neither pass found a close-enough class name */
CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
}
probably_meant_to_be:
/* Here we think that a posix specification was intended. Update any
* parse pointer */
if (updated_parse_ptr) {
*updated_parse_ptr = (char *) p;
}
/* If a posix class name was intended but incorrectly specified, we
* output or return the warnings */
if (found_problem) {
/* We set flags for these issues in the parse loop above instead of
* adding them to the list of warnings, because we can parse it
* twice, and we only want one warning instance */
if (has_upper) {
ADD_POSIX_WARNING(p, "the name must be all lowercase letters");
}
if (has_blank) {
ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
}
if (has_semi_colon) {
ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
}
else if (! has_terminating_colon) {
ADD_POSIX_WARNING(p, "there is no terminating ':'");
}
if (! has_terminating_bracket) {
ADD_POSIX_WARNING(p, "there is no terminating ']'");
}
if ( posix_warnings
&& RExC_warn_text
&& av_top_index(RExC_warn_text) > -1)
{
*posix_warnings = RExC_warn_text;
}
}
else if (class_number != OOB_NAMEDCLASS) {
/* If it is a known class, return the class. The class number
* #defines are structured so each complement is +1 to the normal
* one */
CLEAR_POSIX_WARNINGS_AND_RETURN(class_number + complement);
}
else if (! check_only) {
/* Here, it is an unrecognized class. This is an error (unless the
* call is to check only, which we've already handled above) */
const char * const complement_string = (complement)
? "^"
: "";
RExC_parse = (char *) p;
vFAIL3utf8f("POSIX class [:%s%" UTF8f ":] unknown",
complement_string,
UTF8fARG(UTF, RExC_parse - name_start - 2, name_start));
}
}
return OOB_NAMEDCLASS;
}
#undef ADD_POSIX_WARNING
STATIC unsigned int
S_regex_set_precedence(const U8 my_operator) {
/* Returns the precedence in the (?[...]) construct of the input operator,
* specified by its character representation. The precedence follows
* general Perl rules, but it extends this so that ')' and ']' have (low)
* precedence even though they aren't really operators */
switch (my_operator) {
case '!':
return 5;
case '&':
return 4;
case '^':
case '|':
case '+':
case '-':
return 3;
case ')':
return 2;
case ']':
return 1;
}
NOT_REACHED; /* NOTREACHED */
return 0; /* Silence compiler warning */
}
STATIC regnode_offset
S_handle_regex_sets(pTHX_ RExC_state_t *pRExC_state, SV** return_invlist,
I32 *flagp, U32 depth,
char * const oregcomp_parse)
{
/* Handle the (?[...]) construct to do set operations */
U8 curchar; /* Current character being parsed */
UV start, end; /* End points of code point ranges */
SV* final = NULL; /* The end result inversion list */
SV* result_string; /* 'final' stringified */
AV* stack; /* stack of operators and operands not yet
resolved */
AV* fence_stack = NULL; /* A stack containing the positions in
'stack' of where the undealt-with left
parens would be if they were actually
put there */
/* The 'volatile' is a workaround for an optimiser bug
* in Solaris Studio 12.3. See RT #127455 */
volatile IV fence = 0; /* Position of where most recent undealt-
with left paren in stack is; -1 if none.
*/
STRLEN len; /* Temporary */
regnode_offset node; /* Temporary, and final regnode returned by
this function */
const bool save_fold = FOLD; /* Temporary */
char *save_end, *save_parse; /* Temporaries */
const bool in_locale = LOC; /* we turn off /l during processing */
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_HANDLE_REGEX_SETS;
DEBUG_PARSE("xcls");
if (in_locale) {
set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET);
}
/* The use of this operator implies /u. This is required so that the
* compile time values are valid in all runtime cases */
REQUIRE_UNI_RULES(flagp, 0);
ckWARNexperimental(RExC_parse,
WARN_EXPERIMENTAL__REGEX_SETS,
"The regex_sets feature is experimental");
/* Everything in this construct is a metacharacter. Operands begin with
* either a '\' (for an escape sequence), or a '[' for a bracketed
* character class. Any other character should be an operator, or
* parenthesis for grouping. Both types of operands are handled by calling
* regclass() to parse them. It is called with a parameter to indicate to
* return the computed inversion list. The parsing here is implemented via
* a stack. Each entry on the stack is a single character representing one
* of the operators; or else a pointer to an operand inversion list. */
#define IS_OPERATOR(a) SvIOK(a)
#define IS_OPERAND(a) (! IS_OPERATOR(a))
/* The stack is kept in Łukasiewicz order. (That's pronounced similar
* to luke-a-shave-itch (or -itz), but people who didn't want to bother
* with pronouncing it called it Reverse Polish instead, but now that YOU
* know how to pronounce it you can use the correct term, thus giving due
* credit to the person who invented it, and impressing your geek friends.
* Wikipedia says that the pronounciation of "Ł" has been changing so that
* it is now more like an English initial W (as in wonk) than an L.)
*
* This means that, for example, 'a | b & c' is stored on the stack as
*
* c [4]
* b [3]
* & [2]
* a [1]
* | [0]
*
* where the numbers in brackets give the stack [array] element number.
* In this implementation, parentheses are not stored on the stack.
* Instead a '(' creates a "fence" so that the part of the stack below the
* fence is invisible except to the corresponding ')' (this allows us to
* replace testing for parens, by using instead subtraction of the fence
* position). As new operands are processed they are pushed onto the stack
* (except as noted in the next paragraph). New operators of higher
* precedence than the current final one are inserted on the stack before
* the lhs operand (so that when the rhs is pushed next, everything will be
* in the correct positions shown above. When an operator of equal or
* lower precedence is encountered in parsing, all the stacked operations
* of equal or higher precedence are evaluated, leaving the result as the
* top entry on the stack. This makes higher precedence operations
* evaluate before lower precedence ones, and causes operations of equal
* precedence to left associate.
*
* The only unary operator '!' is immediately pushed onto the stack when
* encountered. When an operand is encountered, if the top of the stack is
* a '!", the complement is immediately performed, and the '!' popped. The
* resulting value is treated as a new operand, and the logic in the
* previous paragraph is executed. Thus in the expression
* [a] + ! [b]
* the stack looks like
*
* !
* a
* +
*
* as 'b' gets parsed, the latter gets evaluated to '!b', and the stack
* becomes
*
* !b
* a
* +
*
* A ')' is treated as an operator with lower precedence than all the
* aforementioned ones, which causes all operations on the stack above the
* corresponding '(' to be evaluated down to a single resultant operand.
* Then the fence for the '(' is removed, and the operand goes through the
* algorithm above, without the fence.
*
* A separate stack is kept of the fence positions, so that the position of
* the latest so-far unbalanced '(' is at the top of it.
*
* The ']' ending the construct is treated as the lowest operator of all,
* so that everything gets evaluated down to a single operand, which is the
* result */
sv_2mortal((SV *)(stack = newAV()));
sv_2mortal((SV *)(fence_stack = newAV()));
while (RExC_parse < RExC_end) {
I32 top_index; /* Index of top-most element in 'stack' */
SV** top_ptr; /* Pointer to top 'stack' element */
SV* current = NULL; /* To contain the current inversion list
operand */
SV* only_to_avoid_leaks;
skip_to_be_ignored_text(pRExC_state, &RExC_parse,
TRUE /* Force /x */ );
if (RExC_parse >= RExC_end) { /* Fail */
break;
}
curchar = UCHARAT(RExC_parse);
redo_curchar:
#ifdef ENABLE_REGEX_SETS_DEBUGGING
/* Enable with -Accflags=-DENABLE_REGEX_SETS_DEBUGGING */
DEBUG_U(dump_regex_sets_structures(pRExC_state,
stack, fence, fence_stack));
#endif
top_index = av_tindex_skip_len_mg(stack);
switch (curchar) {
SV** stacked_ptr; /* Ptr to something already on 'stack' */
char stacked_operator; /* The topmost operator on the 'stack'. */
SV* lhs; /* Operand to the left of the operator */
SV* rhs; /* Operand to the right of the operator */
SV* fence_ptr; /* Pointer to top element of the fence
stack */
case '(':
if ( RExC_parse < RExC_end - 2
&& UCHARAT(RExC_parse + 1) == '?'
&& UCHARAT(RExC_parse + 2) == '^')
{
/* If is a '(?', could be an embedded '(?^flags:(?[...])'.
* This happens when we have some thing like
*
* my $thai_or_lao = qr/(?[ \p{Thai} + \p{Lao} ])/;
* ...
* qr/(?[ \p{Digit} & $thai_or_lao ])/;
*
* Here we would be handling the interpolated
* '$thai_or_lao'. We handle this by a recursive call to
* ourselves which returns the inversion list the
* interpolated expression evaluates to. We use the flags
* from the interpolated pattern. */
U32 save_flags = RExC_flags;
const char * save_parse;
RExC_parse += 2; /* Skip past the '(?' */
save_parse = RExC_parse;
/* Parse the flags for the '(?'. We already know the first
* flag to parse is a '^' */
parse_lparen_question_flags(pRExC_state);
if ( RExC_parse >= RExC_end - 4
|| UCHARAT(RExC_parse) != ':'
|| UCHARAT(++RExC_parse) != '('
|| UCHARAT(++RExC_parse) != '?'
|| UCHARAT(++RExC_parse) != '[')
{
/* In combination with the above, this moves the
* pointer to the point just after the first erroneous
* character. */
if (RExC_parse >= RExC_end - 4) {
RExC_parse = RExC_end;
}
else if (RExC_parse != save_parse) {
RExC_parse += (UTF)
? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
: 1;
}
vFAIL("Expecting '(?flags:(?[...'");
}
/* Recurse, with the meat of the embedded expression */
RExC_parse++;
if (! handle_regex_sets(pRExC_state, ¤t, flagp,
depth+1, oregcomp_parse))
{
RETURN_FAIL_ON_RESTART(*flagp, flagp);
}
/* Here, 'current' contains the embedded expression's
* inversion list, and RExC_parse points to the trailing
* ']'; the next character should be the ')' */
RExC_parse++;
if (UCHARAT(RExC_parse) != ')')
vFAIL("Expecting close paren for nested extended charclass");
/* Then the ')' matching the original '(' handled by this
* case: statement */
RExC_parse++;
if (UCHARAT(RExC_parse) != ')')
vFAIL("Expecting close paren for wrapper for nested extended charclass");
RExC_flags = save_flags;
goto handle_operand;
}
/* A regular '('. Look behind for illegal syntax */
if (top_index - fence >= 0) {
/* If the top entry on the stack is an operator, it had
* better be a '!', otherwise the entry below the top
* operand should be an operator */
if ( ! (top_ptr = av_fetch(stack, top_index, FALSE))
|| (IS_OPERATOR(*top_ptr) && SvUV(*top_ptr) != '!')
|| ( IS_OPERAND(*top_ptr)
&& ( top_index - fence < 1
|| ! (stacked_ptr = av_fetch(stack,
top_index - 1,
FALSE))
|| ! IS_OPERATOR(*stacked_ptr))))
{
RExC_parse++;
vFAIL("Unexpected '(' with no preceding operator");
}
}
/* Stack the position of this undealt-with left paren */
av_push(fence_stack, newSViv(fence));
fence = top_index + 1;
break;
case '\\':
/* regclass() can only return RESTART_PARSE and NEED_UTF8 if
* multi-char folds are allowed. */
if (!regclass(pRExC_state, flagp, depth+1,
TRUE, /* means parse just the next thing */
FALSE, /* don't allow multi-char folds */
FALSE, /* don't silence non-portable warnings. */
TRUE, /* strict */
FALSE, /* Require return to be an ANYOF */
¤t))
{
RETURN_FAIL_ON_RESTART(*flagp, flagp);
goto regclass_failed;
}
/* regclass() will return with parsing just the \ sequence,
* leaving the parse pointer at the next thing to parse */
RExC_parse--;
goto handle_operand;
case '[': /* Is a bracketed character class */
{
/* See if this is a [:posix:] class. */
bool is_posix_class = (OOB_NAMEDCLASS
< handle_possible_posix(pRExC_state,
RExC_parse + 1,
NULL,
NULL,
TRUE /* checking only */));
/* If it is a posix class, leave the parse pointer at the '['
* to fool regclass() into thinking it is part of a
* '[[:posix:]]'. */
if (! is_posix_class) {
RExC_parse++;
}
/* regclass() can only return RESTART_PARSE and NEED_UTF8 if
* multi-char folds are allowed. */
if (!regclass(pRExC_state, flagp, depth+1,
is_posix_class, /* parse the whole char
class only if not a
posix class */
FALSE, /* don't allow multi-char folds */
TRUE, /* silence non-portable warnings. */
TRUE, /* strict */
FALSE, /* Require return to be an ANYOF */
¤t))
{
RETURN_FAIL_ON_RESTART(*flagp, flagp);
goto regclass_failed;
}
if (! current) {
break;
}
/* function call leaves parse pointing to the ']', except if we
* faked it */
if (is_posix_class) {
RExC_parse--;
}
goto handle_operand;
}
case ']':
if (top_index >= 1) {
goto join_operators;
}
/* Only a single operand on the stack: are done */
goto done;
case ')':
if (av_tindex_skip_len_mg(fence_stack) < 0) {
if (UCHARAT(RExC_parse - 1) == ']') {
break;
}
RExC_parse++;
vFAIL("Unexpected ')'");
}
/* If nothing after the fence, is missing an operand */
if (top_index - fence < 0) {
RExC_parse++;
goto bad_syntax;
}
/* If at least two things on the stack, treat this as an
* operator */
if (top_index - fence >= 1) {
goto join_operators;
}
/* Here only a single thing on the fenced stack, and there is a
* fence. Get rid of it */
fence_ptr = av_pop(fence_stack);
assert(fence_ptr);
fence = SvIV(fence_ptr);
SvREFCNT_dec_NN(fence_ptr);
fence_ptr = NULL;
if (fence < 0) {
fence = 0;
}
/* Having gotten rid of the fence, we pop the operand at the
* stack top and process it as a newly encountered operand */
current = av_pop(stack);
if (IS_OPERAND(current)) {
goto handle_operand;
}
RExC_parse++;
goto bad_syntax;
case '&':
case '|':
case '+':
case '-':
case '^':
/* These binary operators should have a left operand already
* parsed */
if ( top_index - fence < 0
|| top_index - fence == 1
|| ( ! (top_ptr = av_fetch(stack, top_index, FALSE)))
|| ! IS_OPERAND(*top_ptr))
{
goto unexpected_binary;
}
/* If only the one operand is on the part of the stack visible
* to us, we just place this operator in the proper position */
if (top_index - fence < 2) {
/* Place the operator before the operand */
SV* lhs = av_pop(stack);
av_push(stack, newSVuv(curchar));
av_push(stack, lhs);
break;
}
/* But if there is something else on the stack, we need to
* process it before this new operator if and only if the
* stacked operation has equal or higher precedence than the
* new one */
join_operators:
/* The operator on the stack is supposed to be below both its
* operands */
if ( ! (stacked_ptr = av_fetch(stack, top_index - 2, FALSE))
|| IS_OPERAND(*stacked_ptr))
{
/* But if not, it's legal and indicates we are completely
* done if and only if we're currently processing a ']',
* which should be the final thing in the expression */
if (curchar == ']') {
goto done;
}
unexpected_binary:
RExC_parse++;
vFAIL2("Unexpected binary operator '%c' with no "
"preceding operand", curchar);
}
stacked_operator = (char) SvUV(*stacked_ptr);
if (regex_set_precedence(curchar)
> regex_set_precedence(stacked_operator))
{
/* Here, the new operator has higher precedence than the
* stacked one. This means we need to add the new one to
* the stack to await its rhs operand (and maybe more
* stuff). We put it before the lhs operand, leaving
* untouched the stacked operator and everything below it
* */
lhs = av_pop(stack);
assert(IS_OPERAND(lhs));
av_push(stack, newSVuv(curchar));
av_push(stack, lhs);
break;
}
/* Here, the new operator has equal or lower precedence than
* what's already there. This means the operation already
* there should be performed now, before the new one. */
rhs = av_pop(stack);
if (! IS_OPERAND(rhs)) {
/* This can happen when a ! is not followed by an operand,
* like in /(?[\t &!])/ */
goto bad_syntax;
}
lhs = av_pop(stack);
if (! IS_OPERAND(lhs)) {
/* This can happen when there is an empty (), like in
* /(?[[0]+()+])/ */
goto bad_syntax;
}
switch (stacked_operator) {
case '&':
_invlist_intersection(lhs, rhs, &rhs);
break;
case '|':
case '+':
_invlist_union(lhs, rhs, &rhs);
break;
case '-':
_invlist_subtract(lhs, rhs, &rhs);
break;
case '^': /* The union minus the intersection */
{
SV* i = NULL;
SV* u = NULL;
_invlist_union(lhs, rhs, &u);
_invlist_intersection(lhs, rhs, &i);
_invlist_subtract(u, i, &rhs);
SvREFCNT_dec_NN(i);
SvREFCNT_dec_NN(u);
break;
}
}
SvREFCNT_dec(lhs);
/* Here, the higher precedence operation has been done, and the
* result is in 'rhs'. We overwrite the stacked operator with
* the result. Then we redo this code to either push the new
* operator onto the stack or perform any higher precedence
* stacked operation */
only_to_avoid_leaks = av_pop(stack);
SvREFCNT_dec(only_to_avoid_leaks);
av_push(stack, rhs);
goto redo_curchar;
case '!': /* Highest priority, right associative */
/* If what's already at the top of the stack is another '!",
* they just cancel each other out */
if ( (top_ptr = av_fetch(stack, top_index, FALSE))
&& (IS_OPERATOR(*top_ptr) && SvUV(*top_ptr) == '!'))
{
only_to_avoid_leaks = av_pop(stack);
SvREFCNT_dec(only_to_avoid_leaks);
}
else { /* Otherwise, since it's right associative, just push
onto the stack */
av_push(stack, newSVuv(curchar));
}
break;
default:
RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
if (RExC_parse >= RExC_end) {
break;
}
vFAIL("Unexpected character");
handle_operand:
/* Here 'current' is the operand. If something is already on the
* stack, we have to check if it is a !. But first, the code above
* may have altered the stack in the time since we earlier set
* 'top_index'. */
top_index = av_tindex_skip_len_mg(stack);
if (top_index - fence >= 0) {
/* If the top entry on the stack is an operator, it had better
* be a '!', otherwise the entry below the top operand should
* be an operator */
top_ptr = av_fetch(stack, top_index, FALSE);
assert(top_ptr);
if (IS_OPERATOR(*top_ptr)) {
/* The only permissible operator at the top of the stack is
* '!', which is applied immediately to this operand. */
curchar = (char) SvUV(*top_ptr);
if (curchar != '!') {
SvREFCNT_dec(current);
vFAIL2("Unexpected binary operator '%c' with no "
"preceding operand", curchar);
}
_invlist_invert(current);
only_to_avoid_leaks = av_pop(stack);
SvREFCNT_dec(only_to_avoid_leaks);
/* And we redo with the inverted operand. This allows
* handling multiple ! in a row */
goto handle_operand;
}
/* Single operand is ok only for the non-binary ')'
* operator */
else if ((top_index - fence == 0 && curchar != ')')
|| (top_index - fence > 0
&& (! (stacked_ptr = av_fetch(stack,
top_index - 1,
FALSE))
|| IS_OPERAND(*stacked_ptr))))
{
SvREFCNT_dec(current);
vFAIL("Operand with no preceding operator");
}
}
/* Here there was nothing on the stack or the top element was
* another operand. Just add this new one */
av_push(stack, current);
} /* End of switch on next parse token */
RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
} /* End of loop parsing through the construct */
vFAIL("Syntax error in (?[...])");
done:
if (RExC_parse >= RExC_end || RExC_parse[1] != ')') {
if (RExC_parse < RExC_end) {
RExC_parse++;
}
vFAIL("Unexpected ']' with no following ')' in (?[...");
}
if (av_tindex_skip_len_mg(fence_stack) >= 0) {
vFAIL("Unmatched (");
}
if (av_tindex_skip_len_mg(stack) < 0 /* Was empty */
|| ((final = av_pop(stack)) == NULL)
|| ! IS_OPERAND(final)
|| ! is_invlist(final)
|| av_tindex_skip_len_mg(stack) >= 0) /* More left on stack */
{
bad_syntax:
SvREFCNT_dec(final);
vFAIL("Incomplete expression within '(?[ ])'");
}
/* Here, 'final' is the resultant inversion list from evaluating the
* expression. Return it if so requested */
if (return_invlist) {
*return_invlist = final;
return END;
}
/* Otherwise generate a resultant node, based on 'final'. regclass() is
* expecting a string of ranges and individual code points */
invlist_iterinit(final);
result_string = newSVpvs("");
while (invlist_iternext(final, &start, &end)) {
if (start == end) {
Perl_sv_catpvf(aTHX_ result_string, "\\x{%" UVXf "}", start);
}
else {
Perl_sv_catpvf(aTHX_ result_string, "\\x{%" UVXf "}-\\x{%" UVXf "}",
start, end);
}
}
/* About to generate an ANYOF (or similar) node from the inversion list we
* have calculated */
save_parse = RExC_parse;
RExC_parse = SvPV(result_string, len);
save_end = RExC_end;
RExC_end = RExC_parse + len;
TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE;
/* We turn off folding around the call, as the class we have constructed
* already has all folding taken into consideration, and we don't want
* regclass() to add to that */
RExC_flags &= ~RXf_PMf_FOLD;
/* regclass() can only return RESTART_PARSE and NEED_UTF8 if multi-char
* folds are allowed. */
node = regclass(pRExC_state, flagp, depth+1,
FALSE, /* means parse the whole char class */
FALSE, /* don't allow multi-char folds */
TRUE, /* silence non-portable warnings. The above may very
well have generated non-portable code points, but
they're valid on this machine */
FALSE, /* similarly, no need for strict */
FALSE, /* Require return to be an ANYOF */
NULL
);
RESTORE_WARNINGS;
RExC_parse = save_parse + 1;
RExC_end = save_end;
SvREFCNT_dec_NN(final);
SvREFCNT_dec_NN(result_string);
if (save_fold) {
RExC_flags |= RXf_PMf_FOLD;
}
if (!node) {
RETURN_FAIL_ON_RESTART(*flagp, flagp);
goto regclass_failed;
}
/* Fix up the node type if we are in locale. (We have pretended we are
* under /u for the purposes of regclass(), as this construct will only
* work under UTF-8 locales. But now we change the opcode to be ANYOFL (so
* as to cause any warnings about bad locales to be output in regexec.c),
* and add the flag that indicates to check if not in a UTF-8 locale. The
* reason we above forbid optimization into something other than an ANYOF
* node is simply to minimize the number of code changes in regexec.c.
* Otherwise we would have to create new EXACTish node types and deal with
* them. This decision could be revisited should this construct become
* popular.
*
* (One might think we could look at the resulting ANYOF node and suppress
* the flag if everything is above 255, as those would be UTF-8 only,
* but this isn't true, as the components that led to that result could
* have been locale-affected, and just happen to cancel each other out
* under UTF-8 locales.) */
if (in_locale) {
set_regex_charset(&RExC_flags, REGEX_LOCALE_CHARSET);
assert(OP(REGNODE_p(node)) == ANYOF);
OP(REGNODE_p(node)) = ANYOFL;
ANYOF_FLAGS(REGNODE_p(node))
|= ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
}
nextchar(pRExC_state);
Set_Node_Length(REGNODE_p(node), RExC_parse - oregcomp_parse + 1); /* MJD */
return node;
regclass_failed:
FAIL2("panic: regclass returned failure to handle_sets, " "flags=%#" UVxf,
(UV) *flagp);
}
#ifdef ENABLE_REGEX_SETS_DEBUGGING
STATIC void
S_dump_regex_sets_structures(pTHX_ RExC_state_t *pRExC_state,
AV * stack, const IV fence, AV * fence_stack)
{ /* Dumps the stacks in handle_regex_sets() */
const SSize_t stack_top = av_tindex_skip_len_mg(stack);
const SSize_t fence_stack_top = av_tindex_skip_len_mg(fence_stack);
SSize_t i;
PERL_ARGS_ASSERT_DUMP_REGEX_SETS_STRUCTURES;
PerlIO_printf(Perl_debug_log, "\nParse position is:%s\n", RExC_parse);
if (stack_top < 0) {
PerlIO_printf(Perl_debug_log, "Nothing on stack\n");
}
else {
PerlIO_printf(Perl_debug_log, "Stack: (fence=%d)\n", (int) fence);
for (i = stack_top; i >= 0; i--) {
SV ** element_ptr = av_fetch(stack, i, FALSE);
if (! element_ptr) {
}
if (IS_OPERATOR(*element_ptr)) {
PerlIO_printf(Perl_debug_log, "[%d]: %c\n",
(int) i, (int) SvIV(*element_ptr));
}
else {
PerlIO_printf(Perl_debug_log, "[%d] ", (int) i);
sv_dump(*element_ptr);
}
}
}
if (fence_stack_top < 0) {
PerlIO_printf(Perl_debug_log, "Nothing on fence_stack\n");
}
else {
PerlIO_printf(Perl_debug_log, "Fence_stack: \n");
for (i = fence_stack_top; i >= 0; i--) {
SV ** element_ptr = av_fetch(fence_stack, i, FALSE);
if (! element_ptr) {
}
PerlIO_printf(Perl_debug_log, "[%d]: %d\n",
(int) i, (int) SvIV(*element_ptr));
}
}
}
#endif
#undef IS_OPERATOR
#undef IS_OPERAND
STATIC void
S_add_above_Latin1_folds(pTHX_ RExC_state_t *pRExC_state, const U8 cp, SV** invlist)
{
/* This adds the Latin1/above-Latin1 folding rules.
*
* This should be called only for a Latin1-range code points, cp, which is
* known to be involved in a simple fold with other code points above
* Latin1. It would give false results if /aa has been specified.
* Multi-char folds are outside the scope of this, and must be handled
* specially. */
PERL_ARGS_ASSERT_ADD_ABOVE_LATIN1_FOLDS;
assert(HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(cp));
/* The rules that are valid for all Unicode versions are hard-coded in */
switch (cp) {
case 'k':
case 'K':
*invlist =
add_cp_to_invlist(*invlist, KELVIN_SIGN);
break;
case 's':
case 'S':
*invlist = add_cp_to_invlist(*invlist, LATIN_SMALL_LETTER_LONG_S);
break;
case MICRO_SIGN:
*invlist = add_cp_to_invlist(*invlist, GREEK_CAPITAL_LETTER_MU);
*invlist = add_cp_to_invlist(*invlist, GREEK_SMALL_LETTER_MU);
break;
case LATIN_CAPITAL_LETTER_A_WITH_RING_ABOVE:
case LATIN_SMALL_LETTER_A_WITH_RING_ABOVE:
*invlist = add_cp_to_invlist(*invlist, ANGSTROM_SIGN);
break;
case LATIN_SMALL_LETTER_Y_WITH_DIAERESIS:
*invlist = add_cp_to_invlist(*invlist,
LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS);
break;
default: /* Other code points are checked against the data for the
current Unicode version */
{
Size_t folds_count;
unsigned int first_fold;
const unsigned int * remaining_folds;
UV folded_cp;
if (isASCII(cp)) {
folded_cp = toFOLD(cp);
}
else {
U8 dummy_fold[UTF8_MAXBYTES_CASE+1];
Size_t dummy_len;
folded_cp = _to_fold_latin1(cp, dummy_fold, &dummy_len, 0);
}
if (folded_cp > 255) {
*invlist = add_cp_to_invlist(*invlist, folded_cp);
}
folds_count = _inverse_folds(folded_cp, &first_fold,
&remaining_folds);
if (folds_count == 0) {
/* Use deprecated warning to increase the chances of this being
* output */
ckWARN2reg_d(RExC_parse,
"Perl folding rules are not up-to-date for 0x%02X;"
" please use the perlbug utility to report;", cp);
}
else {
unsigned int i;
if (first_fold > 255) {
*invlist = add_cp_to_invlist(*invlist, first_fold);
}
for (i = 0; i < folds_count - 1; i++) {
if (remaining_folds[i] > 255) {
*invlist = add_cp_to_invlist(*invlist,
remaining_folds[i]);
}
}
}
break;
}
}
}
STATIC void
S_output_posix_warnings(pTHX_ RExC_state_t *pRExC_state, AV* posix_warnings)
{
/* Output the elements of the array given by '*posix_warnings' as REGEXP
* warnings. */
SV * msg;
const bool first_is_fatal = ckDEAD(packWARN(WARN_REGEXP));
PERL_ARGS_ASSERT_OUTPUT_POSIX_WARNINGS;
if (! TO_OUTPUT_WARNINGS(RExC_parse)) {
return;
}
while ((msg = av_shift(posix_warnings)) != &PL_sv_undef) {
if (first_is_fatal) { /* Avoid leaking this */
av_undef(posix_warnings); /* This isn't necessary if the
array is mortal, but is a
fail-safe */
(void) sv_2mortal(msg);
PREPARE_TO_DIE;
}
Perl_warner(aTHX_ packWARN(WARN_REGEXP), "%s", SvPVX(msg));
SvREFCNT_dec_NN(msg);
}
UPDATE_WARNINGS_LOC(RExC_parse);
}
STATIC AV *
S_add_multi_match(pTHX_ AV* multi_char_matches, SV* multi_string, const STRLEN cp_count)
{
/* This adds the string scalar <multi_string> to the array
* <multi_char_matches>. <multi_string> is known to have exactly
* <cp_count> code points in it. This is used when constructing a
* bracketed character class and we find something that needs to match more
* than a single character.
*
* <multi_char_matches> is actually an array of arrays. Each top-level
* element is an array that contains all the strings known so far that are
* the same length. And that length (in number of code points) is the same
* as the index of the top-level array. Hence, the [2] element is an
* array, each element thereof is a string containing TWO code points;
* while element [3] is for strings of THREE characters, and so on. Since
* this is for multi-char strings there can never be a [0] nor [1] element.
*
* When we rewrite the character class below, we will do so such that the
* longest strings are written first, so that it prefers the longest
* matching strings first. This is done even if it turns out that any
* quantifier is non-greedy, out of this programmer's (khw) laziness. Tom
* Christiansen has agreed that this is ok. This makes the test for the
* ligature 'ffi' come before the test for 'ff', for example */
AV* this_array;
AV** this_array_ptr;
PERL_ARGS_ASSERT_ADD_MULTI_MATCH;
if (! multi_char_matches) {
multi_char_matches = newAV();
}
if (av_exists(multi_char_matches, cp_count)) {
this_array_ptr = (AV**) av_fetch(multi_char_matches, cp_count, FALSE);
this_array = *this_array_ptr;
}
else {
this_array = newAV();
av_store(multi_char_matches, cp_count,
(SV*) this_array);
}
av_push(this_array, multi_string);
return multi_char_matches;
}
/* The names of properties whose definitions are not known at compile time are
* stored in this SV, after a constant heading. So if the length has been
* changed since initialization, then there is a run-time definition. */
#define HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION \
(SvCUR(listsv) != initial_listsv_len)
/* There is a restricted set of white space characters that are legal when
* ignoring white space in a bracketed character class. This generates the
* code to skip them.
*
* There is a line below that uses the same white space criteria but is outside
* this macro. Both here and there must use the same definition */
#define SKIP_BRACKETED_WHITE_SPACE(do_skip, p) \
STMT_START { \
if (do_skip) { \
while (isBLANK_A(UCHARAT(p))) \
{ \
p++; \
} \
} \
} STMT_END
STATIC regnode_offset
S_regclass(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth,
const bool stop_at_1, /* Just parse the next thing, don't
look for a full character class */
bool allow_mutiple_chars,
const bool silence_non_portable, /* Don't output warnings
about too large
characters */
const bool strict,
bool optimizable, /* ? Allow a non-ANYOF return
node */
SV** ret_invlist /* Return an inversion list, not a node */
)
{
/* parse a bracketed class specification. Most of these will produce an
* ANYOF node; but something like [a] will produce an EXACT node; [aA], an
* EXACTFish node; [[:ascii:]], a POSIXA node; etc. It is more complex
* under /i with multi-character folds: it will be rewritten following the
* paradigm of this example, where the <multi-fold>s are characters which
* fold to multiple character sequences:
* /[abc\x{multi-fold1}def\x{multi-fold2}ghi]/i
* gets effectively rewritten as:
* /(?:\x{multi-fold1}|\x{multi-fold2}|[abcdefghi]/i
* reg() gets called (recursively) on the rewritten version, and this
* function will return what it constructs. (Actually the <multi-fold>s
* aren't physically removed from the [abcdefghi], it's just that they are
* ignored in the recursion by means of a flag:
* <RExC_in_multi_char_class>.)
*
* ANYOF nodes contain a bit map for the first NUM_ANYOF_CODE_POINTS
* characters, with the corresponding bit set if that character is in the
* list. For characters above this, an inversion list is used. There
* are extra bits for \w, etc. in locale ANYOFs, as what these match is not
* determinable at compile time
*
* On success, returns the offset at which any next node should be placed
* into the regex engine program being compiled.
*
* Returns 0 otherwise, setting flagp to RESTART_PARSE if the parse needs
* to be restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to
* UTF-8
*/
dVAR;
UV prevvalue = OOB_UNICODE, save_prevvalue = OOB_UNICODE;
IV range = 0;
UV value = OOB_UNICODE, save_value = OOB_UNICODE;
regnode_offset ret = -1; /* Initialized to an illegal value */
STRLEN numlen;
int namedclass = OOB_NAMEDCLASS;
char *rangebegin = NULL;
SV *listsv = NULL; /* List of \p{user-defined} whose definitions
aren't available at the time this was called */
STRLEN initial_listsv_len = 0; /* Kind of a kludge to see if it is more
than just initialized. */
SV* properties = NULL; /* Code points that match \p{} \P{} */
SV* posixes = NULL; /* Code points that match classes like [:word:],
extended beyond the Latin1 range. These have to
be kept separate from other code points for much
of this function because their handling is
different under /i, and for most classes under
/d as well */
SV* nposixes = NULL; /* Similarly for [:^word:]. These are kept
separate for a while from the non-complemented
versions because of complications with /d
matching */
SV* simple_posixes = NULL; /* But under some conditions, the classes can be
treated more simply than the general case,
leading to less compilation and execution
work */
UV element_count = 0; /* Number of distinct elements in the class.
Optimizations may be possible if this is tiny */
AV * multi_char_matches = NULL; /* Code points that fold to more than one
character; used under /i */
UV n;
char * stop_ptr = RExC_end; /* where to stop parsing */
/* ignore unescaped whitespace? */
const bool skip_white = cBOOL( ret_invlist
|| (RExC_flags & RXf_PMf_EXTENDED_MORE));
/* inversion list of code points this node matches only when the target
* string is in UTF-8. These are all non-ASCII, < 256. (Because is under
* /d) */
SV* upper_latin1_only_utf8_matches = NULL;
/* Inversion list of code points this node matches regardless of things
* like locale, folding, utf8ness of the target string */
SV* cp_list = NULL;
/* Like cp_list, but code points on this list need to be checked for things
* that fold to/from them under /i */
SV* cp_foldable_list = NULL;
/* Like cp_list, but code points on this list are valid only when the
* runtime locale is UTF-8 */
SV* only_utf8_locale_list = NULL;
/* In a range, if one of the endpoints is non-character-set portable,
* meaning that it hard-codes a code point that may mean a different
* charactger in ASCII vs. EBCDIC, as opposed to, say, a literal 'A' or a
* mnemonic '\t' which each mean the same character no matter which
* character set the platform is on. */
unsigned int non_portable_endpoint = 0;
/* Is the range unicode? which means on a platform that isn't 1-1 native
* to Unicode (i.e. non-ASCII), each code point in it should be considered
* to be a Unicode value. */
bool unicode_range = FALSE;
bool invert = FALSE; /* Is this class to be complemented */
bool warn_super = ALWAYS_WARN_SUPER;
const char * orig_parse = RExC_parse;
/* This variable is used to mark where the end in the input is of something
* that looks like a POSIX construct but isn't. During the parse, when
* something looks like it could be such a construct is encountered, it is
* checked for being one, but not if we've already checked this area of the
* input. Only after this position is reached do we check again */
char *not_posix_region_end = RExC_parse - 1;
AV* posix_warnings = NULL;
const bool do_posix_warnings = ckWARN(WARN_REGEXP);
U8 op = END; /* The returned node-type, initialized to an impossible
one. */
U8 anyof_flags = 0; /* flag bits if the node is an ANYOF-type */
U32 posixl = 0; /* bit field of posix classes matched under /l */
/* Flags as to what things aren't knowable until runtime. (Note that these are
* mutually exclusive.) */
#define HAS_USER_DEFINED_PROPERTY 0x01 /* /u any user-defined properties that
haven't been defined as of yet */
#define HAS_D_RUNTIME_DEPENDENCY 0x02 /* /d if the target being matched is
UTF-8 or not */
#define HAS_L_RUNTIME_DEPENDENCY 0x04 /* /l what the posix classes match and
what gets folded */
U32 has_runtime_dependency = 0; /* OR of the above flags */
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REGCLASS;
#ifndef DEBUGGING
PERL_UNUSED_ARG(depth);
#endif
/* If wants an inversion list returned, we can't optimize to something
* else. */
if (ret_invlist) {
optimizable = FALSE;
}
DEBUG_PARSE("clas");
#if UNICODE_MAJOR_VERSION < 3 /* no multifolds in early Unicode */ \
|| (UNICODE_MAJOR_VERSION == 3 && UNICODE_DOT_VERSION == 0 \
&& UNICODE_DOT_DOT_VERSION == 0)
allow_mutiple_chars = FALSE;
#endif
/* We include the /i status at the beginning of this so that we can
* know it at runtime */
listsv = sv_2mortal(Perl_newSVpvf(aTHX_ "#%d\n", cBOOL(FOLD)));
initial_listsv_len = SvCUR(listsv);
SvTEMP_off(listsv); /* Grr, TEMPs and mortals are conflated. */
SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
assert(RExC_parse <= RExC_end);
if (UCHARAT(RExC_parse) == '^') { /* Complement the class */
RExC_parse++;
invert = TRUE;
allow_mutiple_chars = FALSE;
MARK_NAUGHTY(1);
SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
}
/* Check that they didn't say [:posix:] instead of [[:posix:]] */
if (! ret_invlist && MAYBE_POSIXCC(UCHARAT(RExC_parse))) {
int maybe_class = handle_possible_posix(pRExC_state,
RExC_parse,
¬_posix_region_end,
NULL,
TRUE /* checking only */);
if (maybe_class >= OOB_NAMEDCLASS && do_posix_warnings) {
ckWARN4reg(not_posix_region_end,
"POSIX syntax [%c %c] belongs inside character classes%s",
*RExC_parse, *RExC_parse,
(maybe_class == OOB_NAMEDCLASS)
? ((POSIXCC_NOTYET(*RExC_parse))
? " (but this one isn't implemented)"
: " (but this one isn't fully valid)")
: ""
);
}
}
/* If the caller wants us to just parse a single element, accomplish this
* by faking the loop ending condition */
if (stop_at_1 && RExC_end > RExC_parse) {
stop_ptr = RExC_parse + 1;
}
/* allow 1st char to be ']' (allowing it to be '-' is dealt with later) */
if (UCHARAT(RExC_parse) == ']')
goto charclassloop;
while (1) {
if ( posix_warnings
&& av_tindex_skip_len_mg(posix_warnings) >= 0
&& RExC_parse > not_posix_region_end)
{
/* Warnings about posix class issues are considered tentative until
* we are far enough along in the parse that we can no longer
* change our mind, at which point we output them. This is done
* each time through the loop so that a later class won't zap them
* before they have been dealt with. */
output_posix_warnings(pRExC_state, posix_warnings);
}
if (RExC_parse >= stop_ptr) {
break;
}
SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
if (UCHARAT(RExC_parse) == ']') {
break;
}
charclassloop:
namedclass = OOB_NAMEDCLASS; /* initialize as illegal */
save_value = value;
save_prevvalue = prevvalue;
if (!range) {
rangebegin = RExC_parse;
element_count++;
non_portable_endpoint = 0;
}
if (UTF && ! UTF8_IS_INVARIANT(* RExC_parse)) {
value = utf8n_to_uvchr((U8*)RExC_parse,
RExC_end - RExC_parse,
&numlen, UTF8_ALLOW_DEFAULT);
RExC_parse += numlen;
}
else
value = UCHARAT(RExC_parse++);
if (value == '[') {
char * posix_class_end;
namedclass = handle_possible_posix(pRExC_state,
RExC_parse,
&posix_class_end,
do_posix_warnings ? &posix_warnings : NULL,
FALSE /* die if error */);
if (namedclass > OOB_NAMEDCLASS) {
/* If there was an earlier attempt to parse this particular
* posix class, and it failed, it was a false alarm, as this
* successful one proves */
if ( posix_warnings
&& av_tindex_skip_len_mg(posix_warnings) >= 0
&& not_posix_region_end >= RExC_parse
&& not_posix_region_end <= posix_class_end)
{
av_undef(posix_warnings);
}
RExC_parse = posix_class_end;
}
else if (namedclass == OOB_NAMEDCLASS) {
not_posix_region_end = posix_class_end;
}
else {
namedclass = OOB_NAMEDCLASS;
}
}
else if ( RExC_parse - 1 > not_posix_region_end
&& MAYBE_POSIXCC(value))
{
(void) handle_possible_posix(
pRExC_state,
RExC_parse - 1, /* -1 because parse has already been
advanced */
¬_posix_region_end,
do_posix_warnings ? &posix_warnings : NULL,
TRUE /* checking only */);
}
else if ( strict && ! skip_white
&& ( _generic_isCC(value, _CC_VERTSPACE)
|| is_VERTWS_cp_high(value)))
{
vFAIL("Literal vertical space in [] is illegal except under /x");
}
else if (value == '\\') {
/* Is a backslash; get the code point of the char after it */
if (RExC_parse >= RExC_end) {
vFAIL("Unmatched [");
}
if (UTF && ! UTF8_IS_INVARIANT(UCHARAT(RExC_parse))) {
value = utf8n_to_uvchr((U8*)RExC_parse,
RExC_end - RExC_parse,
&numlen, UTF8_ALLOW_DEFAULT);
RExC_parse += numlen;
}
else
value = UCHARAT(RExC_parse++);
/* Some compilers cannot handle switching on 64-bit integer
* values, therefore value cannot be an UV. Yes, this will
* be a problem later if we want switch on Unicode.
* A similar issue a little bit later when switching on
* namedclass. --jhi */
/* If the \ is escaping white space when white space is being
* skipped, it means that that white space is wanted literally, and
* is already in 'value'. Otherwise, need to translate the escape
* into what it signifies. */
if (! skip_white || ! isBLANK_A(value)) switch ((I32)value) {
case 'w': namedclass = ANYOF_WORDCHAR; break;
case 'W': namedclass = ANYOF_NWORDCHAR; break;
case 's': namedclass = ANYOF_SPACE; break;
case 'S': namedclass = ANYOF_NSPACE; break;
case 'd': namedclass = ANYOF_DIGIT; break;
case 'D': namedclass = ANYOF_NDIGIT; break;
case 'v': namedclass = ANYOF_VERTWS; break;
case 'V': namedclass = ANYOF_NVERTWS; break;
case 'h': namedclass = ANYOF_HORIZWS; break;
case 'H': namedclass = ANYOF_NHORIZWS; break;
case 'N': /* Handle \N{NAME} in class */
{
const char * const backslash_N_beg = RExC_parse - 2;
int cp_count;
if (! grok_bslash_N(pRExC_state,
NULL, /* No regnode */
&value, /* Yes single value */
&cp_count, /* Multiple code pt count */
flagp,
strict,
depth)
) {
if (*flagp & NEED_UTF8)
FAIL("panic: grok_bslash_N set NEED_UTF8");
RETURN_FAIL_ON_RESTART_FLAGP(flagp);
if (cp_count < 0) {
vFAIL("\\N in a character class must be a named character: \\N{...}");
}
else if (cp_count == 0) {
ckWARNreg(RExC_parse,
"Ignoring zero length \\N{} in character class");
}
else { /* cp_count > 1 */
assert(cp_count > 1);
if (! RExC_in_multi_char_class) {
if ( ! allow_mutiple_chars
|| invert
|| range
|| *RExC_parse == '-')
{
if (strict) {
RExC_parse--;
vFAIL("\\N{} in inverted character class or as a range end-point is restricted to one character");
}
ckWARNreg(RExC_parse, "Using just the first character returned by \\N{} in character class");
break; /* <value> contains the first code
point. Drop out of the switch to
process it */
}
else {
SV * multi_char_N = newSVpvn(backslash_N_beg,
RExC_parse - backslash_N_beg);
multi_char_matches
= add_multi_match(multi_char_matches,
multi_char_N,
cp_count);
}
}
} /* End of cp_count != 1 */
/* This element should not be processed further in this
* class */
element_count--;
value = save_value;
prevvalue = save_prevvalue;
continue; /* Back to top of loop to get next char */
}
/* Here, is a single code point, and <value> contains it */
unicode_range = TRUE; /* \N{} are Unicode */
}
break;
case 'p':
case 'P':
{
char *e;
/* \p means they want Unicode semantics */
REQUIRE_UNI_RULES(flagp, 0);
if (RExC_parse >= RExC_end)
vFAIL2("Empty \\%c", (U8)value);
if (*RExC_parse == '{') {
const U8 c = (U8)value;
e = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);
if (!e) {
RExC_parse++;
vFAIL2("Missing right brace on \\%c{}", c);
}
RExC_parse++;
/* White space is allowed adjacent to the braces and after
* any '^', even when not under /x */
while (isSPACE(*RExC_parse)) {
RExC_parse++;
}
if (UCHARAT(RExC_parse) == '^') {
/* toggle. (The rhs xor gets the single bit that
* differs between P and p; the other xor inverts just
* that bit) */
value ^= 'P' ^ 'p';
RExC_parse++;
while (isSPACE(*RExC_parse)) {
RExC_parse++;
}
}
if (e == RExC_parse)
vFAIL2("Empty \\%c{}", c);
n = e - RExC_parse;
while (isSPACE(*(RExC_parse + n - 1)))
n--;
} /* The \p isn't immediately followed by a '{' */
else if (! isALPHA(*RExC_parse)) {
RExC_parse += (UTF)
? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
: 1;
vFAIL2("Character following \\%c must be '{' or a "
"single-character Unicode property name",
(U8) value);
}
else {
e = RExC_parse;
n = 1;
}
{
char* name = RExC_parse;
/* Any message returned about expanding the definition */
SV* msg = newSVpvs_flags("", SVs_TEMP);
/* If set TRUE, the property is user-defined as opposed to
* official Unicode */
bool user_defined = FALSE;
SV * prop_definition = parse_uniprop_string(
name, n, UTF, FOLD,
FALSE, /* This is compile-time */
/* We can't defer this defn when
* the full result is required in
* this call */
! cBOOL(ret_invlist),
&user_defined,
msg,
0 /* Base level */
);
if (SvCUR(msg)) { /* Assumes any error causes a msg */
assert(prop_definition == NULL);
RExC_parse = e + 1;
if (SvUTF8(msg)) { /* msg being UTF-8 makes the whole
thing so, or else the display is
mojibake */
RExC_utf8 = TRUE;
}
/* diag_listed_as: Can't find Unicode property definition "%s" in regex; marked by <-- HERE in m/%s/ */
vFAIL2utf8f("%" UTF8f, UTF8fARG(SvUTF8(msg),
SvCUR(msg), SvPVX(msg)));
}
if (! is_invlist(prop_definition)) {
/* Here, the definition isn't known, so we have gotten
* returned a string that will be evaluated if and when
* encountered at runtime. We add it to the list of
* such properties, along with whether it should be
* complemented or not */
if (value == 'P') {
sv_catpvs(listsv, "!");
}
else {
sv_catpvs(listsv, "+");
}
sv_catsv(listsv, prop_definition);
has_runtime_dependency |= HAS_USER_DEFINED_PROPERTY;
/* We don't know yet what this matches, so have to flag
* it */
anyof_flags |= ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP;
}
else {
assert (prop_definition && is_invlist(prop_definition));
/* Here we do have the complete property definition
*
* Temporary workaround for [perl #133136]. For this
* precise input that is in the .t that is failing,
* load utf8.pm, which is what the test wants, so that
* that .t passes */
if ( memEQs(RExC_start, e + 1 - RExC_start,
"foo\\p{Alnum}")
&& ! hv_common(GvHVn(PL_incgv),
NULL,
"utf8.pm", sizeof("utf8.pm") - 1,
0, HV_FETCH_ISEXISTS, NULL, 0))
{
require_pv("utf8.pm");
}
if (! user_defined &&
/* We warn on matching an above-Unicode code point
* if the match would return true, except don't
* warn for \p{All}, which has exactly one element
* = 0 */
(_invlist_contains_cp(prop_definition, 0x110000)
&& (! (_invlist_len(prop_definition) == 1
&& *invlist_array(prop_definition) == 0))))
{
warn_super = TRUE;
}
/* Invert if asking for the complement */
if (value == 'P') {
_invlist_union_complement_2nd(properties,
prop_definition,
&properties);
}
else {
_invlist_union(properties, prop_definition, &properties);
}
}
}
RExC_parse = e + 1;
namedclass = ANYOF_UNIPROP; /* no official name, but it's
named */
}
break;
case 'n': value = '\n'; break;
case 'r': value = '\r'; break;
case 't': value = '\t'; break;
case 'f': value = '\f'; break;
case 'b': value = '\b'; break;
case 'e': value = ESC_NATIVE; break;
case 'a': value = '\a'; break;
case 'o':
RExC_parse--; /* function expects to be pointed at the 'o' */
{
const char* error_msg;
bool valid = grok_bslash_o(&RExC_parse,
RExC_end,
&value,
&error_msg,
TO_OUTPUT_WARNINGS(RExC_parse),
strict,
silence_non_portable,
UTF);
if (! valid) {
vFAIL(error_msg);
}
UPDATE_WARNINGS_LOC(RExC_parse - 1);
}
non_portable_endpoint++;
break;
case 'x':
RExC_parse--; /* function expects to be pointed at the 'x' */
{
const char* error_msg;
bool valid = grok_bslash_x(&RExC_parse,
RExC_end,
&value,
&error_msg,
TO_OUTPUT_WARNINGS(RExC_parse),
strict,
silence_non_portable,
UTF);
if (! valid) {
vFAIL(error_msg);
}
UPDATE_WARNINGS_LOC(RExC_parse - 1);
}
non_portable_endpoint++;
break;
case 'c':
value = grok_bslash_c(*RExC_parse, TO_OUTPUT_WARNINGS(RExC_parse));
UPDATE_WARNINGS_LOC(RExC_parse);
RExC_parse++;
non_portable_endpoint++;
break;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7':
{
/* Take 1-3 octal digits */
I32 flags = PERL_SCAN_SILENT_ILLDIGIT;
numlen = (strict) ? 4 : 3;
value = grok_oct(--RExC_parse, &numlen, &flags, NULL);
RExC_parse += numlen;
if (numlen != 3) {
if (strict) {
RExC_parse += (UTF)
? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
: 1;
vFAIL("Need exactly 3 octal digits");
}
else if ( numlen < 3 /* like \08, \178 */
&& RExC_parse < RExC_end
&& isDIGIT(*RExC_parse)
&& ckWARN(WARN_REGEXP))
{
reg_warn_non_literal_string(
RExC_parse + 1,
form_short_octal_warning(RExC_parse, numlen));
}
}
non_portable_endpoint++;
break;
}
default:
/* Allow \_ to not give an error */
if (isWORDCHAR(value) && value != '_') {
if (strict) {
vFAIL2("Unrecognized escape \\%c in character class",
(int)value);
}
else {
ckWARN2reg(RExC_parse,
"Unrecognized escape \\%c in character class passed through",
(int)value);
}
}
break;
} /* End of switch on char following backslash */
} /* end of handling backslash escape sequences */
/* Here, we have the current token in 'value' */
if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */
U8 classnum;
/* a bad range like a-\d, a-[:digit:]. The '-' is taken as a
* literal, as is the character that began the false range, i.e.
* the 'a' in the examples */
if (range) {
const int w = (RExC_parse >= rangebegin)
? RExC_parse - rangebegin
: 0;
if (strict) {
vFAIL2utf8f(
"False [] range \"%" UTF8f "\"",
UTF8fARG(UTF, w, rangebegin));
}
else {
ckWARN2reg(RExC_parse,
"False [] range \"%" UTF8f "\"",
UTF8fARG(UTF, w, rangebegin));
cp_list = add_cp_to_invlist(cp_list, '-');
cp_foldable_list = add_cp_to_invlist(cp_foldable_list,
prevvalue);
}
range = 0; /* this was not a true range */
element_count += 2; /* So counts for three values */
}
classnum = namedclass_to_classnum(namedclass);
if (LOC && namedclass < ANYOF_POSIXL_MAX
#ifndef HAS_ISASCII
&& classnum != _CC_ASCII
#endif
) {
SV* scratch_list = NULL;
/* What the Posix classes (like \w, [:space:]) match isn't
* generally knowable under locale until actual match time. A
* special node is used for these which has extra space for a
* bitmap, with a bit reserved for each named class that is to
* be matched against. (This isn't needed for \p{} and
* pseudo-classes, as they are not affected by locale, and
* hence are dealt with separately.) However, if a named class
* and its complement are both present, then it matches
* everything, and there is no runtime dependency. Odd numbers
* are the complements of the next lower number, so xor works.
* (Note that something like [\w\D] should match everything,
* because \d should be a proper subset of \w. But rather than
* trust that the locale is well behaved, we leave this to
* runtime to sort out) */
if (POSIXL_TEST(posixl, namedclass ^ 1)) {
cp_list = _add_range_to_invlist(cp_list, 0, UV_MAX);
POSIXL_ZERO(posixl);
has_runtime_dependency &= ~HAS_L_RUNTIME_DEPENDENCY;
anyof_flags &= ~ANYOF_MATCHES_POSIXL;
continue; /* We could ignore the rest of the class, but
best to parse it for any errors */
}
else { /* Here, isn't the complement of any already parsed
class */
POSIXL_SET(posixl, namedclass);
has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY;
anyof_flags |= ANYOF_MATCHES_POSIXL;
/* The above-Latin1 characters are not subject to locale
* rules. Just add them to the unconditionally-matched
* list */
/* Get the list of the above-Latin1 code points this
* matches */
_invlist_intersection_maybe_complement_2nd(PL_AboveLatin1,
PL_XPosix_ptrs[classnum],
/* Odd numbers are complements,
* like NDIGIT, NASCII, ... */
namedclass % 2 != 0,
&scratch_list);
/* Checking if 'cp_list' is NULL first saves an extra
* clone. Its reference count will be decremented at the
* next union, etc, or if this is the only instance, at the
* end of the routine */
if (! cp_list) {
cp_list = scratch_list;
}
else {
_invlist_union(cp_list, scratch_list, &cp_list);
SvREFCNT_dec_NN(scratch_list);
}
continue; /* Go get next character */
}
}
else {
/* Here, is not /l, or is a POSIX class for which /l doesn't
* matter (or is a Unicode property, which is skipped here). */
if (namedclass >= ANYOF_POSIXL_MAX) { /* If a special class */
if (namedclass != ANYOF_UNIPROP) { /* UNIPROP = \p and \P */
/* Here, should be \h, \H, \v, or \V. None of /d, /i
* nor /l make a difference in what these match,
* therefore we just add what they match to cp_list. */
if (classnum != _CC_VERTSPACE) {
assert( namedclass == ANYOF_HORIZWS
|| namedclass == ANYOF_NHORIZWS);
/* It turns out that \h is just a synonym for
* XPosixBlank */
classnum = _CC_BLANK;
}
_invlist_union_maybe_complement_2nd(
cp_list,
PL_XPosix_ptrs[classnum],
namedclass % 2 != 0, /* Complement if odd
(NHORIZWS, NVERTWS)
*/
&cp_list);
}
}
else if ( AT_LEAST_UNI_SEMANTICS
|| classnum == _CC_ASCII
|| (DEPENDS_SEMANTICS && ( classnum == _CC_DIGIT
|| classnum == _CC_XDIGIT)))
{
/* We usually have to worry about /d affecting what POSIX
* classes match, with special code needed because we won't
* know until runtime what all matches. But there is no
* extra work needed under /u and /a; and [:ascii:] is
* unaffected by /d; and :digit: and :xdigit: don't have
* runtime differences under /d. So we can special case
* these, and avoid some extra work below, and at runtime.
* */
_invlist_union_maybe_complement_2nd(
simple_posixes,
((AT_LEAST_ASCII_RESTRICTED)
? PL_Posix_ptrs[classnum]
: PL_XPosix_ptrs[classnum]),
namedclass % 2 != 0,
&simple_posixes);
}
else { /* Garden variety class. If is NUPPER, NALPHA, ...
complement and use nposixes */
SV** posixes_ptr = namedclass % 2 == 0
? &posixes
: &nposixes;
_invlist_union_maybe_complement_2nd(
*posixes_ptr,
PL_XPosix_ptrs[classnum],
namedclass % 2 != 0,
posixes_ptr);
}
}
} /* end of namedclass \blah */
SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
/* If 'range' is set, 'value' is the ending of a range--check its
* validity. (If value isn't a single code point in the case of a
* range, we should have figured that out above in the code that
* catches false ranges). Later, we will handle each individual code
* point in the range. If 'range' isn't set, this could be the
* beginning of a range, so check for that by looking ahead to see if
* the next real character to be processed is the range indicator--the
* minus sign */
if (range) {
#ifdef EBCDIC
/* For unicode ranges, we have to test that the Unicode as opposed
* to the native values are not decreasing. (Above 255, there is
* no difference between native and Unicode) */
if (unicode_range && prevvalue < 255 && value < 255) {
if (NATIVE_TO_LATIN1(prevvalue) > NATIVE_TO_LATIN1(value)) {
goto backwards_range;
}
}
else
#endif
if (prevvalue > value) /* b-a */ {
int w;
#ifdef EBCDIC
backwards_range:
#endif
w = RExC_parse - rangebegin;
vFAIL2utf8f(
"Invalid [] range \"%" UTF8f "\"",
UTF8fARG(UTF, w, rangebegin));
NOT_REACHED; /* NOTREACHED */
}
}
else {
prevvalue = value; /* save the beginning of the potential range */
if (! stop_at_1 /* Can't be a range if parsing just one thing */
&& *RExC_parse == '-')
{
char* next_char_ptr = RExC_parse + 1;
/* Get the next real char after the '-' */
SKIP_BRACKETED_WHITE_SPACE(skip_white, next_char_ptr);
/* If the '-' is at the end of the class (just before the ']',
* it is a literal minus; otherwise it is a range */
if (next_char_ptr < RExC_end && *next_char_ptr != ']') {
RExC_parse = next_char_ptr;
/* a bad range like \w-, [:word:]- ? */
if (namedclass > OOB_NAMEDCLASS) {
if (strict || ckWARN(WARN_REGEXP)) {
const int w = RExC_parse >= rangebegin
? RExC_parse - rangebegin
: 0;
if (strict) {
vFAIL4("False [] range \"%*.*s\"",
w, w, rangebegin);
}
else {
vWARN4(RExC_parse,
"False [] range \"%*.*s\"",
w, w, rangebegin);
}
}
cp_list = add_cp_to_invlist(cp_list, '-');
element_count++;
} else
range = 1; /* yeah, it's a range! */
continue; /* but do it the next time */
}
}
}
if (namedclass > OOB_NAMEDCLASS) {
continue;
}
/* Here, we have a single value this time through the loop, and
* <prevvalue> is the beginning of the range, if any; or <value> if
* not. */
/* non-Latin1 code point implies unicode semantics. */
if (value > 255) {
REQUIRE_UNI_RULES(flagp, 0);
}
/* Ready to process either the single value, or the completed range.
* For single-valued non-inverted ranges, we consider the possibility
* of multi-char folds. (We made a conscious decision to not do this
* for the other cases because it can often lead to non-intuitive
* results. For example, you have the peculiar case that:
* "s s" =~ /^[^\xDF]+$/i => Y
* "ss" =~ /^[^\xDF]+$/i => N
*
* See [perl #89750] */
if (FOLD && allow_mutiple_chars && value == prevvalue) {
if ( value == LATIN_SMALL_LETTER_SHARP_S
|| (value > 255 && _invlist_contains_cp(PL_HasMultiCharFold,
value)))
{
/* Here <value> is indeed a multi-char fold. Get what it is */
U8 foldbuf[UTF8_MAXBYTES_CASE+1];
STRLEN foldlen;
UV folded = _to_uni_fold_flags(
value,
foldbuf,
&foldlen,
FOLD_FLAGS_FULL | (ASCII_FOLD_RESTRICTED
? FOLD_FLAGS_NOMIX_ASCII
: 0)
);
/* Here, <folded> should be the first character of the
* multi-char fold of <value>, with <foldbuf> containing the
* whole thing. But, if this fold is not allowed (because of
* the flags), <fold> will be the same as <value>, and should
* be processed like any other character, so skip the special
* handling */
if (folded != value) {
/* Skip if we are recursed, currently parsing the class
* again. Otherwise add this character to the list of
* multi-char folds. */
if (! RExC_in_multi_char_class) {
STRLEN cp_count = utf8_length(foldbuf,
foldbuf + foldlen);
SV* multi_fold = sv_2mortal(newSVpvs(""));
Perl_sv_catpvf(aTHX_ multi_fold, "\\x{%" UVXf "}", value);
multi_char_matches
= add_multi_match(multi_char_matches,
multi_fold,
cp_count);
}
/* This element should not be processed further in this
* class */
element_count--;
value = save_value;
prevvalue = save_prevvalue;
continue;
}
}
}
if (strict && ckWARN(WARN_REGEXP)) {
if (range) {
/* If the range starts above 255, everything is portable and
* likely to be so for any forseeable character set, so don't
* warn. */
if (unicode_range && non_portable_endpoint && prevvalue < 256) {
vWARN(RExC_parse, "Both or neither range ends should be Unicode");
}
else if (prevvalue != value) {
/* Under strict, ranges that stop and/or end in an ASCII
* printable should have each end point be a portable value
* for it (preferably like 'A', but we don't warn if it is
* a (portable) Unicode name or code point), and the range
* must be be all digits or all letters of the same case.
* Otherwise, the range is non-portable and unclear as to
* what it contains */
if ( (isPRINT_A(prevvalue) || isPRINT_A(value))
&& ( non_portable_endpoint
|| ! ( (isDIGIT_A(prevvalue) && isDIGIT_A(value))
|| (isLOWER_A(prevvalue) && isLOWER_A(value))
|| (isUPPER_A(prevvalue) && isUPPER_A(value))
))) {
vWARN(RExC_parse, "Ranges of ASCII printables should"
" be some subset of \"0-9\","
" \"A-Z\", or \"a-z\"");
}
else if (prevvalue >= FIRST_NON_ASCII_DECIMAL_DIGIT) {
SSize_t index_start;
SSize_t index_final;
/* But the nature of Unicode and languages mean we
* can't do the same checks for above-ASCII ranges,
* except in the case of digit ones. These should
* contain only digits from the same group of 10. The
* ASCII case is handled just above. Hence here, the
* range could be a range of digits. First some
* unlikely special cases. Grandfather in that a range
* ending in 19DA (NEW TAI LUE THAM DIGIT ONE) is bad
* if its starting value is one of the 10 digits prior
* to it. This is because it is an alternate way of
* writing 19D1, and some people may expect it to be in
* that group. But it is bad, because it won't give
* the expected results. In Unicode 5.2 it was
* considered to be in that group (of 11, hence), but
* this was fixed in the next version */
if (UNLIKELY(value == 0x19DA && prevvalue >= 0x19D0)) {
goto warn_bad_digit_range;
}
else if (UNLIKELY( prevvalue >= 0x1D7CE
&& value <= 0x1D7FF))
{
/* This is the only other case currently in Unicode
* where the algorithm below fails. The code
* points just above are the end points of a single
* range containing only decimal digits. It is 5
* different series of 0-9. All other ranges of
* digits currently in Unicode are just a single
* series. (And mktables will notify us if a later
* Unicode version breaks this.)
*
* If the range being checked is at most 9 long,
* and the digit values represented are in
* numerical order, they are from the same series.
* */
if ( value - prevvalue > 9
|| ((( value - 0x1D7CE) % 10)
<= (prevvalue - 0x1D7CE) % 10))
{
goto warn_bad_digit_range;
}
}
else {
/* For all other ranges of digits in Unicode, the
* algorithm is just to check if both end points
* are in the same series, which is the same range.
* */
index_start = _invlist_search(
PL_XPosix_ptrs[_CC_DIGIT],
prevvalue);
/* Warn if the range starts and ends with a digit,
* and they are not in the same group of 10. */
if ( index_start >= 0
&& ELEMENT_RANGE_MATCHES_INVLIST(index_start)
&& (index_final =
_invlist_search(PL_XPosix_ptrs[_CC_DIGIT],
value)) != index_start
&& index_final >= 0
&& ELEMENT_RANGE_MATCHES_INVLIST(index_final))
{
warn_bad_digit_range:
vWARN(RExC_parse, "Ranges of digits should be"
" from the same group of"
" 10");
}
}
}
}
}
if ((! range || prevvalue == value) && non_portable_endpoint) {
if (isPRINT_A(value)) {
char literal[3];
unsigned d = 0;
if (isBACKSLASHED_PUNCT(value)) {
literal[d++] = '\\';
}
literal[d++] = (char) value;
literal[d++] = '\0';
vWARN4(RExC_parse,
"\"%.*s\" is more clearly written simply as \"%s\"",
(int) (RExC_parse - rangebegin),
rangebegin,
literal
);
}
else if isMNEMONIC_CNTRL(value) {
vWARN4(RExC_parse,
"\"%.*s\" is more clearly written simply as \"%s\"",
(int) (RExC_parse - rangebegin),
rangebegin,
cntrl_to_mnemonic((U8) value)
);
}
}
}
/* Deal with this element of the class */
#ifndef EBCDIC
cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
prevvalue, value);
#else
/* On non-ASCII platforms, for ranges that span all of 0..255, and ones
* that don't require special handling, we can just add the range like
* we do for ASCII platforms */
if ((UNLIKELY(prevvalue == 0) && value >= 255)
|| ! (prevvalue < 256
&& (unicode_range
|| (! non_portable_endpoint
&& ((isLOWER_A(prevvalue) && isLOWER_A(value))
|| (isUPPER_A(prevvalue)
&& isUPPER_A(value)))))))
{
cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
prevvalue, value);
}
else {
/* Here, requires special handling. This can be because it is a
* range whose code points are considered to be Unicode, and so
* must be individually translated into native, or because its a
* subrange of 'A-Z' or 'a-z' which each aren't contiguous in
* EBCDIC, but we have defined them to include only the "expected"
* upper or lower case ASCII alphabetics. Subranges above 255 are
* the same in native and Unicode, so can be added as a range */
U8 start = NATIVE_TO_LATIN1(prevvalue);
unsigned j;
U8 end = (value < 256) ? NATIVE_TO_LATIN1(value) : 255;
for (j = start; j <= end; j++) {
cp_foldable_list = add_cp_to_invlist(cp_foldable_list, LATIN1_TO_NATIVE(j));
}
if (value > 255) {
cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
256, value);
}
}
#endif
range = 0; /* this range (if it was one) is done now */
} /* End of loop through all the text within the brackets */
if ( posix_warnings && av_tindex_skip_len_mg(posix_warnings) >= 0) {
output_posix_warnings(pRExC_state, posix_warnings);
}
/* If anything in the class expands to more than one character, we have to
* deal with them by building up a substitute parse string, and recursively
* calling reg() on it, instead of proceeding */
if (multi_char_matches) {
SV * substitute_parse = newSVpvn_flags("?:", 2, SVs_TEMP);
I32 cp_count;
STRLEN len;
char *save_end = RExC_end;
char *save_parse = RExC_parse;
char *save_start = RExC_start;
Size_t constructed_prefix_len = 0; /* This gives the length of the
constructed portion of the
substitute parse. */
bool first_time = TRUE; /* First multi-char occurrence doesn't get
a "|" */
I32 reg_flags;
assert(! invert);
/* Only one level of recursion allowed */
assert(RExC_copy_start_in_constructed == RExC_precomp);
#if 0 /* Have decided not to deal with multi-char folds in inverted classes,
because too confusing */
if (invert) {
sv_catpvs(substitute_parse, "(?:");
}
#endif
/* Look at the longest folds first */
for (cp_count = av_tindex_skip_len_mg(multi_char_matches);
cp_count > 0;
cp_count--)
{
if (av_exists(multi_char_matches, cp_count)) {
AV** this_array_ptr;
SV* this_sequence;
this_array_ptr = (AV**) av_fetch(multi_char_matches,
cp_count, FALSE);
while ((this_sequence = av_pop(*this_array_ptr)) !=
&PL_sv_undef)
{
if (! first_time) {
sv_catpvs(substitute_parse, "|");
}
first_time = FALSE;
sv_catpv(substitute_parse, SvPVX(this_sequence));
}
}
}
/* If the character class contains anything else besides these
* multi-character folds, have to include it in recursive parsing */
if (element_count) {
sv_catpvs(substitute_parse, "|[");
constructed_prefix_len = SvCUR(substitute_parse);
sv_catpvn(substitute_parse, orig_parse, RExC_parse - orig_parse);
/* Put in a closing ']' only if not going off the end, as otherwise
* we are adding something that really isn't there */
if (RExC_parse < RExC_end) {
sv_catpvs(substitute_parse, "]");
}
}
sv_catpvs(substitute_parse, ")");
#if 0
if (invert) {
/* This is a way to get the parse to skip forward a whole named
* sequence instead of matching the 2nd character when it fails the
* first */
sv_catpvs(substitute_parse, "(*THEN)(*SKIP)(*FAIL)|.)");
}
#endif
/* Set up the data structure so that any errors will be properly
* reported. See the comments at the definition of
* REPORT_LOCATION_ARGS for details */
RExC_copy_start_in_input = (char *) orig_parse;
RExC_start = RExC_parse = SvPV(substitute_parse, len);
RExC_copy_start_in_constructed = RExC_start + constructed_prefix_len;
RExC_end = RExC_parse + len;
RExC_in_multi_char_class = 1;
ret = reg(pRExC_state, 1, ®_flags, depth+1);
*flagp |= reg_flags & (HASWIDTH|SIMPLE|SPSTART|POSTPONED|RESTART_PARSE|NEED_UTF8);
/* And restore so can parse the rest of the pattern */
RExC_parse = save_parse;
RExC_start = RExC_copy_start_in_constructed = RExC_copy_start_in_input = save_start;
RExC_end = save_end;
RExC_in_multi_char_class = 0;
SvREFCNT_dec_NN(multi_char_matches);
return ret;
}
/* If folding, we calculate all characters that could fold to or from the
* ones already on the list */
if (cp_foldable_list) {
if (FOLD) {
UV start, end; /* End points of code point ranges */
SV* fold_intersection = NULL;
SV** use_list;
/* Our calculated list will be for Unicode rules. For locale
* matching, we have to keep a separate list that is consulted at
* runtime only when the locale indicates Unicode rules (and we
* don't include potential matches in the ASCII/Latin1 range, as
* any code point could fold to any other, based on the run-time
* locale). For non-locale, we just use the general list */
if (LOC) {
use_list = &only_utf8_locale_list;
}
else {
use_list = &cp_list;
}
/* Only the characters in this class that participate in folds need
* be checked. Get the intersection of this class and all the
* possible characters that are foldable. This can quickly narrow
* down a large class */
_invlist_intersection(PL_in_some_fold, cp_foldable_list,
&fold_intersection);
/* Now look at the foldable characters in this class individually */
invlist_iterinit(fold_intersection);
while (invlist_iternext(fold_intersection, &start, &end)) {
UV j;
UV folded;
/* Look at every character in the range */
for (j = start; j <= end; j++) {
U8 foldbuf[UTF8_MAXBYTES_CASE+1];
STRLEN foldlen;
unsigned int k;
Size_t folds_count;
unsigned int first_fold;
const unsigned int * remaining_folds;
if (j < 256) {
/* Under /l, we don't know what code points below 256
* fold to, except we do know the MICRO SIGN folds to
* an above-255 character if the locale is UTF-8, so we
* add it to the special list (in *use_list) Otherwise
* we know now what things can match, though some folds
* are valid under /d only if the target is UTF-8.
* Those go in a separate list */
if ( IS_IN_SOME_FOLD_L1(j)
&& ! (LOC && j != MICRO_SIGN))
{
/* ASCII is always matched; non-ASCII is matched
* only under Unicode rules (which could happen
* under /l if the locale is a UTF-8 one */
if (isASCII(j) || ! DEPENDS_SEMANTICS) {
*use_list = add_cp_to_invlist(*use_list,
PL_fold_latin1[j]);
}
else if (j != PL_fold_latin1[j]) {
upper_latin1_only_utf8_matches
= add_cp_to_invlist(
upper_latin1_only_utf8_matches,
PL_fold_latin1[j]);
}
}
if (HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(j)
&& (! isASCII(j) || ! ASCII_FOLD_RESTRICTED))
{
add_above_Latin1_folds(pRExC_state,
(U8) j,
use_list);
}
continue;
}
/* Here is an above Latin1 character. We don't have the
* rules hard-coded for it. First, get its fold. This is
* the simple fold, as the multi-character folds have been
* handled earlier and separated out */
folded = _to_uni_fold_flags(j, foldbuf, &foldlen,
(ASCII_FOLD_RESTRICTED)
? FOLD_FLAGS_NOMIX_ASCII
: 0);
/* Single character fold of above Latin1. Add everything
* in its fold closure to the list that this node should
* match. */
folds_count = _inverse_folds(folded, &first_fold,
&remaining_folds);
for (k = 0; k <= folds_count; k++) {
UV c = (k == 0) /* First time through use itself */
? folded
: (k == 1) /* 2nd time use, the first fold */
? first_fold
/* Then the remaining ones */
: remaining_folds[k-2];
/* /aa doesn't allow folds between ASCII and non- */
if (( ASCII_FOLD_RESTRICTED
&& (isASCII(c) != isASCII(j))))
{
continue;
}
/* Folds under /l which cross the 255/256 boundary are
* added to a separate list. (These are valid only
* when the locale is UTF-8.) */
if (c < 256 && LOC) {
*use_list = add_cp_to_invlist(*use_list, c);
continue;
}
if (isASCII(c) || c > 255 || AT_LEAST_UNI_SEMANTICS)
{
cp_list = add_cp_to_invlist(cp_list, c);
}
else {
/* Similarly folds involving non-ascii Latin1
* characters under /d are added to their list */
upper_latin1_only_utf8_matches
= add_cp_to_invlist(
upper_latin1_only_utf8_matches,
c);
}
}
}
}
SvREFCNT_dec_NN(fold_intersection);
}
/* Now that we have finished adding all the folds, there is no reason
* to keep the foldable list separate */
_invlist_union(cp_list, cp_foldable_list, &cp_list);
SvREFCNT_dec_NN(cp_foldable_list);
}
/* And combine the result (if any) with any inversion lists from posix
* classes. The lists are kept separate up to now because we don't want to
* fold the classes */
if (simple_posixes) { /* These are the classes known to be unaffected by
/a, /aa, and /d */
if (cp_list) {
_invlist_union(cp_list, simple_posixes, &cp_list);
SvREFCNT_dec_NN(simple_posixes);
}
else {
cp_list = simple_posixes;
}
}
if (posixes || nposixes) {
if (! DEPENDS_SEMANTICS) {
/* For everything but /d, we can just add the current 'posixes' and
* 'nposixes' to the main list */
if (posixes) {
if (cp_list) {
_invlist_union(cp_list, posixes, &cp_list);
SvREFCNT_dec_NN(posixes);
}
else {
cp_list = posixes;
}
}
if (nposixes) {
if (cp_list) {
_invlist_union(cp_list, nposixes, &cp_list);
SvREFCNT_dec_NN(nposixes);
}
else {
cp_list = nposixes;
}
}
}
else {
/* Under /d, things like \w match upper Latin1 characters only if
* the target string is in UTF-8. But things like \W match all the
* upper Latin1 characters if the target string is not in UTF-8.
*
* Handle the case with something like \W separately */
if (nposixes) {
SV* only_non_utf8_list = invlist_clone(PL_UpperLatin1, NULL);
/* A complemented posix class matches all upper Latin1
* characters if not in UTF-8. And it matches just certain
* ones when in UTF-8. That means those certain ones are
* matched regardless, so can just be added to the
* unconditional list */
if (cp_list) {
_invlist_union(cp_list, nposixes, &cp_list);
SvREFCNT_dec_NN(nposixes);
nposixes = NULL;
}
else {
cp_list = nposixes;
}
/* Likewise for 'posixes' */
_invlist_union(posixes, cp_list, &cp_list);
SvREFCNT_dec(posixes);
/* Likewise for anything else in the range that matched only
* under UTF-8 */
if (upper_latin1_only_utf8_matches) {
_invlist_union(cp_list,
upper_latin1_only_utf8_matches,
&cp_list);
SvREFCNT_dec_NN(upper_latin1_only_utf8_matches);
upper_latin1_only_utf8_matches = NULL;
}
/* If we don't match all the upper Latin1 characters regardless
* of UTF-8ness, we have to set a flag to match the rest when
* not in UTF-8 */
_invlist_subtract(only_non_utf8_list, cp_list,
&only_non_utf8_list);
if (_invlist_len(only_non_utf8_list) != 0) {
anyof_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
}
SvREFCNT_dec_NN(only_non_utf8_list);
}
else {
/* Here there were no complemented posix classes. That means
* the upper Latin1 characters in 'posixes' match only when the
* target string is in UTF-8. So we have to add them to the
* list of those types of code points, while adding the
* remainder to the unconditional list.
*
* First calculate what they are */
SV* nonascii_but_latin1_properties = NULL;
_invlist_intersection(posixes, PL_UpperLatin1,
&nonascii_but_latin1_properties);
/* And add them to the final list of such characters. */
_invlist_union(upper_latin1_only_utf8_matches,
nonascii_but_latin1_properties,
&upper_latin1_only_utf8_matches);
/* Remove them from what now becomes the unconditional list */
_invlist_subtract(posixes, nonascii_but_latin1_properties,
&posixes);
/* And add those unconditional ones to the final list */
if (cp_list) {
_invlist_union(cp_list, posixes, &cp_list);
SvREFCNT_dec_NN(posixes);
posixes = NULL;
}
else {
cp_list = posixes;
}
SvREFCNT_dec(nonascii_but_latin1_properties);
/* Get rid of any characters from the conditional list that we
* now know are matched unconditionally, which may make that
* list empty */
_invlist_subtract(upper_latin1_only_utf8_matches,
cp_list,
&upper_latin1_only_utf8_matches);
if (_invlist_len(upper_latin1_only_utf8_matches) == 0) {
SvREFCNT_dec_NN(upper_latin1_only_utf8_matches);
upper_latin1_only_utf8_matches = NULL;
}
}
}
}
/* And combine the result (if any) with any inversion list from properties.
* The lists are kept separate up to now so that we can distinguish the two
* in regards to matching above-Unicode. A run-time warning is generated
* if a Unicode property is matched against a non-Unicode code point. But,
* we allow user-defined properties to match anything, without any warning,
* and we also suppress the warning if there is a portion of the character
* class that isn't a Unicode property, and which matches above Unicode, \W
* or [\x{110000}] for example.
* (Note that in this case, unlike the Posix one above, there is no
* <upper_latin1_only_utf8_matches>, because having a Unicode property
* forces Unicode semantics */
if (properties) {
if (cp_list) {
/* If it matters to the final outcome, see if a non-property
* component of the class matches above Unicode. If so, the
* warning gets suppressed. This is true even if just a single
* such code point is specified, as, though not strictly correct if
* another such code point is matched against, the fact that they
* are using above-Unicode code points indicates they should know
* the issues involved */
if (warn_super) {
warn_super = ! (invert
^ (invlist_highest(cp_list) > PERL_UNICODE_MAX));
}
_invlist_union(properties, cp_list, &cp_list);
SvREFCNT_dec_NN(properties);
}
else {
cp_list = properties;
}
if (warn_super) {
anyof_flags
|= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
/* Because an ANYOF node is the only one that warns, this node
* can't be optimized into something else */
optimizable = FALSE;
}
}
/* Here, we have calculated what code points should be in the character
* class.
*
* Now we can see about various optimizations. Fold calculation (which we
* did above) needs to take place before inversion. Otherwise /[^k]/i
* would invert to include K, which under /i would match k, which it
* shouldn't. Therefore we can't invert folded locale now, as it won't be
* folded until runtime */
/* If we didn't do folding, it's because some information isn't available
* until runtime; set the run-time fold flag for these We know to set the
* flag if we have a non-NULL list for UTF-8 locales, or the class matches
* at least one 0-255 range code point */
if (LOC && FOLD) {
/* Some things on the list might be unconditionally included because of
* other components. Remove them, and clean up the list if it goes to
* 0 elements */
if (only_utf8_locale_list && cp_list) {
_invlist_subtract(only_utf8_locale_list, cp_list,
&only_utf8_locale_list);
if (_invlist_len(only_utf8_locale_list) == 0) {
SvREFCNT_dec_NN(only_utf8_locale_list);
only_utf8_locale_list = NULL;
}
}
if ( only_utf8_locale_list
|| (cp_list && ( _invlist_contains_cp(cp_list, LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE)
|| _invlist_contains_cp(cp_list, LATIN_SMALL_LETTER_DOTLESS_I))))
{
has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY;
anyof_flags
|= ANYOFL_FOLD
| ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
}
else if (cp_list) { /* Look to see if a 0-255 code point is in list */
UV start, end;
invlist_iterinit(cp_list);
if (invlist_iternext(cp_list, &start, &end) && start < 256) {
anyof_flags |= ANYOFL_FOLD;
has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY;
}
invlist_iterfinish(cp_list);
}
}
else if ( DEPENDS_SEMANTICS
&& ( upper_latin1_only_utf8_matches
|| (anyof_flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)))
{
RExC_seen_d_op = TRUE;
has_runtime_dependency |= HAS_D_RUNTIME_DEPENDENCY;
}
/* Optimize inverted patterns (e.g. [^a-z]) when everything is known at
* compile time. */
if ( cp_list
&& invert
&& ! has_runtime_dependency)
{
_invlist_invert(cp_list);
/* Clear the invert flag since have just done it here */
invert = FALSE;
}
if (ret_invlist) {
*ret_invlist = cp_list;
return RExC_emit;
}
/* All possible optimizations below still have these characteristics.
* (Multi-char folds aren't SIMPLE, but they don't get this far in this
* routine) */
*flagp |= HASWIDTH|SIMPLE;
if (anyof_flags & ANYOF_LOCALE_FLAGS) {
RExC_contains_locale = 1;
}
/* Some character classes are equivalent to other nodes. Such nodes take
* up less room, and some nodes require fewer operations to execute, than
* ANYOF nodes. EXACTish nodes may be joinable with adjacent nodes to
* improve efficiency. */
if (optimizable) {
PERL_UINT_FAST8_T i;
Size_t partial_cp_count = 0;
UV start[MAX_FOLD_FROMS+1] = { 0 }; /* +1 for the folded-to char */
UV end[MAX_FOLD_FROMS+1] = { 0 };
if (cp_list) { /* Count the code points in enough ranges that we would
see all the ones possible in any fold in this version
of Unicode */
invlist_iterinit(cp_list);
for (i = 0; i <= MAX_FOLD_FROMS; i++) {
if (! invlist_iternext(cp_list, &start[i], &end[i])) {
break;
}
partial_cp_count += end[i] - start[i] + 1;
}
invlist_iterfinish(cp_list);
}
/* If we know at compile time that this matches every possible code
* point, any run-time dependencies don't matter */
if (start[0] == 0 && end[0] == UV_MAX) {
if (invert) {
ret = reganode(pRExC_state, OPFAIL, 0);
}
else {
ret = reg_node(pRExC_state, SANY);
MARK_NAUGHTY(1);
}
goto not_anyof;
}
/* Similarly, for /l posix classes, if both a class and its
* complement match, any run-time dependencies don't matter */
if (posixl) {
for (namedclass = 0; namedclass < ANYOF_POSIXL_MAX;
namedclass += 2)
{
if ( POSIXL_TEST(posixl, namedclass) /* class */
&& POSIXL_TEST(posixl, namedclass + 1)) /* its complement */
{
if (invert) {
ret = reganode(pRExC_state, OPFAIL, 0);
}
else {
ret = reg_node(pRExC_state, SANY);
MARK_NAUGHTY(1);
}
goto not_anyof;
}
}
/* For well-behaved locales, some classes are subsets of others,
* so complementing the subset and including the non-complemented
* superset should match everything, like [\D[:alnum:]], and
* [[:^alpha:][:alnum:]], but some implementations of locales are
* buggy, and khw thinks its a bad idea to have optimization change
* behavior, even if it avoids an OS bug in a given case */
#define isSINGLE_BIT_SET(n) isPOWER_OF_2(n)
/* If is a single posix /l class, can optimize to just that op.
* Such a node will not match anything in the Latin1 range, as that
* is not determinable until runtime, but will match whatever the
* class does outside that range. (Note that some classes won't
* match anything outside the range, like [:ascii:]) */
if ( isSINGLE_BIT_SET(posixl)
&& (partial_cp_count == 0 || start[0] > 255))
{
U8 classnum;
SV * class_above_latin1 = NULL;
bool already_inverted;
bool are_equivalent;
/* Compute which bit is set, which is the same thing as, e.g.,
* ANYOF_CNTRL. From
* https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogDeBruijn
* */
static const int MultiplyDeBruijnBitPosition2[32] =
{
0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
};
namedclass = MultiplyDeBruijnBitPosition2[(posixl
* 0x077CB531U) >> 27];
classnum = namedclass_to_classnum(namedclass);
/* The named classes are such that the inverted number is one
* larger than the non-inverted one */
already_inverted = namedclass
- classnum_to_namedclass(classnum);
/* Create an inversion list of the official property, inverted
* if the constructed node list is inverted, and restricted to
* only the above latin1 code points, which are the only ones
* known at compile time */
_invlist_intersection_maybe_complement_2nd(
PL_AboveLatin1,
PL_XPosix_ptrs[classnum],
already_inverted,
&class_above_latin1);
are_equivalent = _invlistEQ(class_above_latin1, cp_list,
FALSE);
SvREFCNT_dec_NN(class_above_latin1);
if (are_equivalent) {
/* Resolve the run-time inversion flag with this possibly
* inverted class */
invert = invert ^ already_inverted;
ret = reg_node(pRExC_state,
POSIXL + invert * (NPOSIXL - POSIXL));
FLAGS(REGNODE_p(ret)) = classnum;
goto not_anyof;
}
}
}
/* khw can't think of any other possible transformation involving
* these. */
if (has_runtime_dependency & HAS_USER_DEFINED_PROPERTY) {
goto is_anyof;
}
if (! has_runtime_dependency) {
/* If the list is empty, nothing matches. This happens, for
* example, when a Unicode property that doesn't match anything is
* the only element in the character class (perluniprops.pod notes
* such properties). */
if (partial_cp_count == 0) {
if (invert) {
ret = reg_node(pRExC_state, SANY);
}
else {
ret = reganode(pRExC_state, OPFAIL, 0);
}
goto not_anyof;
}
/* If matches everything but \n */
if ( start[0] == 0 && end[0] == '\n' - 1
&& start[1] == '\n' + 1 && end[1] == UV_MAX)
{
assert (! invert);
ret = reg_node(pRExC_state, REG_ANY);
MARK_NAUGHTY(1);
goto not_anyof;
}
}
/* Next see if can optimize classes that contain just a few code points
* into an EXACTish node. The reason to do this is to let the
* optimizer join this node with adjacent EXACTish ones.
*
* An EXACTFish node can be generated even if not under /i, and vice
* versa. But care must be taken. An EXACTFish node has to be such
* that it only matches precisely the code points in the class, but we
* want to generate the least restrictive one that does that, to
* increase the odds of being able to join with an adjacent node. For
* example, if the class contains [kK], we have to make it an EXACTFAA
* node to prevent the KELVIN SIGN from matching. Whether we are under
* /i or not is irrelevant in this case. Less obvious is the pattern
* qr/[\x{02BC}]n/i. U+02BC is MODIFIER LETTER APOSTROPHE. That is
* supposed to match the single character U+0149 LATIN SMALL LETTER N
* PRECEDED BY APOSTROPHE. And so even though there is no simple fold
* that includes \X{02BC}, there is a multi-char fold that does, and so
* the node generated for it must be an EXACTFish one. On the other
* hand qr/:/i should generate a plain EXACT node since the colon
* participates in no fold whatsoever, and having it EXACT tells the
* optimizer the target string cannot match unless it has a colon in
* it.
*
* We don't typically generate an EXACTish node if doing so would
* require changing the pattern to UTF-8, as that affects /d and
* otherwise is slower. However, under /i, not changing to UTF-8 can
* miss some potential multi-character folds. We calculate the
* EXACTish node, and then decide if something would be missed if we
* don't upgrade */
if ( ! posixl
&& ! invert
/* Only try if there are no more code points in the class than
* in the max possible fold */
&& partial_cp_count > 0 && partial_cp_count <= MAX_FOLD_FROMS + 1
&& (start[0] < 256 || UTF || FOLD))
{
if (partial_cp_count == 1 && ! upper_latin1_only_utf8_matches)
{
/* We can always make a single code point class into an
* EXACTish node. */
if (LOC) {
/* Here is /l: Use EXACTL, except /li indicates EXACTFL,
* as that means there is a fold not known until runtime so
* shows as only a single code point here. */
op = (FOLD) ? EXACTFL : EXACTL;
}
else if (! FOLD) { /* Not /l and not /i */
op = (start[0] < 256) ? EXACT : EXACT_ONLY8;
}
else if (start[0] < 256) { /* /i, not /l, and the code point is
small */
/* Under /i, it gets a little tricky. A code point that
* doesn't participate in a fold should be an EXACT node.
* We know this one isn't the result of a simple fold, or
* there'd be more than one code point in the list, but it
* could be part of a multi- character fold. In that case
* we better not create an EXACT node, as we would wrongly
* be telling the optimizer that this code point must be in
* the target string, and that is wrong. This is because
* if the sequence around this code point forms a
* multi-char fold, what needs to be in the string could be
* the code point that folds to the sequence.
*
* This handles the case of below-255 code points, as we
* have an easy look up for those. The next clause handles
* the above-256 one */
op = IS_IN_SOME_FOLD_L1(start[0])
? EXACTFU
: EXACT;
}
else { /* /i, larger code point. Since we are under /i, and
have just this code point, we know that it can't
fold to something else, so PL_InMultiCharFold
applies to it */
op = _invlist_contains_cp(PL_InMultiCharFold,
start[0])
? EXACTFU_ONLY8
: EXACT_ONLY8;
}
value = start[0];
}
else if ( ! (has_runtime_dependency & ~HAS_D_RUNTIME_DEPENDENCY)
&& _invlist_contains_cp(PL_in_some_fold, start[0]))
{
/* Here, the only runtime dependency, if any, is from /d, and
* the class matches more than one code point, and the lowest
* code point participates in some fold. It might be that the
* other code points are /i equivalent to this one, and hence
* they would representable by an EXACTFish node. Above, we
* eliminated classes that contain too many code points to be
* EXACTFish, with the test for MAX_FOLD_FROMS
*
* First, special case the ASCII fold pairs, like 'B' and 'b'.
* We do this because we have EXACTFAA at our disposal for the
* ASCII range */
if (partial_cp_count == 2 && isASCII(start[0])) {
/* The only ASCII characters that participate in folds are
* alphabetics */
assert(isALPHA(start[0]));
if ( end[0] == start[0] /* First range is a single
character, so 2nd exists */
&& isALPHA_FOLD_EQ(start[0], start[1]))
{
/* Here, is part of an ASCII fold pair */
if ( ASCII_FOLD_RESTRICTED
|| HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(start[0]))
{
/* If the second clause just above was true, it
* means we can't be under /i, or else the list
* would have included more than this fold pair.
* Therefore we have to exclude the possibility of
* whatever else it is that folds to these, by
* using EXACTFAA */
op = EXACTFAA;
}
else if (HAS_NONLATIN1_FOLD_CLOSURE(start[0])) {
/* Here, there's no simple fold that start[0] is part
* of, but there is a multi-character one. If we
* are not under /i, we want to exclude that
* possibility; if under /i, we want to include it
* */
op = (FOLD) ? EXACTFU : EXACTFAA;
}
else {
/* Here, the only possible fold start[0] particpates in
* is with start[1]. /i or not isn't relevant */
op = EXACTFU;
}
value = toFOLD(start[0]);
}
}
else if ( ! upper_latin1_only_utf8_matches
|| ( _invlist_len(upper_latin1_only_utf8_matches)
== 2
&& PL_fold_latin1[
invlist_highest(upper_latin1_only_utf8_matches)]
== start[0]))
{
/* Here, the smallest character is non-ascii or there are
* more than 2 code points matched by this node. Also, we
* either don't have /d UTF-8 dependent matches, or if we
* do, they look like they could be a single character that
* is the fold of the lowest one in the always-match list.
* This test quickly excludes most of the false positives
* when there are /d UTF-8 depdendent matches. These are
* like LATIN CAPITAL LETTER A WITH GRAVE matching LATIN
* SMALL LETTER A WITH GRAVE iff the target string is
* UTF-8. (We don't have to worry above about exceeding
* the array bounds of PL_fold_latin1[] because any code
* point in 'upper_latin1_only_utf8_matches' is below 256.)
*
* EXACTFAA would apply only to pairs (hence exactly 2 code
* points) in the ASCII range, so we can't use it here to
* artificially restrict the fold domain, so we check if
* the class does or does not match some EXACTFish node.
* Further, if we aren't under /i, and and the folded-to
* character is part of a multi-character fold, we can't do
* this optimization, as the sequence around it could be
* that multi-character fold, and we don't here know the
* context, so we have to assume it is that multi-char
* fold, to prevent potential bugs.
*
* To do the general case, we first find the fold of the
* lowest code point (which may be higher than the lowest
* one), then find everything that folds to it. (The data
* structure we have only maps from the folded code points,
* so we have to do the earlier step.) */
Size_t foldlen;
U8 foldbuf[UTF8_MAXBYTES_CASE];
UV folded = _to_uni_fold_flags(start[0],
foldbuf, &foldlen, 0);
unsigned int first_fold;
const unsigned int * remaining_folds;
Size_t folds_to_this_cp_count = _inverse_folds(
folded,
&first_fold,
&remaining_folds);
Size_t folds_count = folds_to_this_cp_count + 1;
SV * fold_list = _new_invlist(folds_count);
unsigned int i;
/* If there are UTF-8 dependent matches, create a temporary
* list of what this node matches, including them. */
SV * all_cp_list = NULL;
SV ** use_this_list = &cp_list;
if (upper_latin1_only_utf8_matches) {
all_cp_list = _new_invlist(0);
use_this_list = &all_cp_list;
_invlist_union(cp_list,
upper_latin1_only_utf8_matches,
use_this_list);
}
/* Having gotten everything that participates in the fold
* containing the lowest code point, we turn that into an
* inversion list, making sure everything is included. */
fold_list = add_cp_to_invlist(fold_list, start[0]);
fold_list = add_cp_to_invlist(fold_list, folded);
if (folds_to_this_cp_count > 0) {
fold_list = add_cp_to_invlist(fold_list, first_fold);
for (i = 0; i + 1 < folds_to_this_cp_count; i++) {
fold_list = add_cp_to_invlist(fold_list,
remaining_folds[i]);
}
}
/* If the fold list is identical to what's in this ANYOF
* node, the node can be represented by an EXACTFish one
* instead */
if (_invlistEQ(*use_this_list, fold_list,
0 /* Don't complement */ )
) {
/* But, we have to be careful, as mentioned above.
* Just the right sequence of characters could match
* this if it is part of a multi-character fold. That
* IS what we want if we are under /i. But it ISN'T
* what we want if not under /i, as it could match when
* it shouldn't. So, when we aren't under /i and this
* character participates in a multi-char fold, we
* don't optimize into an EXACTFish node. So, for each
* case below we have to check if we are folding
* and if not, if it is not part of a multi-char fold.
* */
if (start[0] > 255) { /* Highish code point */
if (FOLD || ! _invlist_contains_cp(
PL_InMultiCharFold, folded))
{
op = (LOC)
? EXACTFLU8
: (ASCII_FOLD_RESTRICTED)
? EXACTFAA
: EXACTFU_ONLY8;
value = folded;
}
} /* Below, the lowest code point < 256 */
else if ( FOLD
&& folded == 's'
&& DEPENDS_SEMANTICS)
{ /* An EXACTF node containing a single character
's', can be an EXACTFU if it doesn't get
joined with an adjacent 's' */
op = EXACTFU_S_EDGE;
value = folded;
}
else if ( FOLD
|| ! HAS_NONLATIN1_FOLD_CLOSURE(start[0]))
{
if (upper_latin1_only_utf8_matches) {
op = EXACTF;
/* We can't use the fold, as that only matches
* under UTF-8 */
value = start[0];
}
else if ( UNLIKELY(start[0] == MICRO_SIGN)
&& ! UTF)
{ /* EXACTFUP is a special node for this
character */
op = (ASCII_FOLD_RESTRICTED)
? EXACTFAA
: EXACTFUP;
value = MICRO_SIGN;
}
else if ( ASCII_FOLD_RESTRICTED
&& ! isASCII(start[0]))
{ /* For ASCII under /iaa, we can use EXACTFU
below */
op = EXACTFAA;
value = folded;
}
else {
op = EXACTFU;
value = folded;
}
}
}
SvREFCNT_dec_NN(fold_list);
SvREFCNT_dec(all_cp_list);
}
}
if (op != END) {
/* Here, we have calculated what EXACTish node we would use.
* But we don't use it if it would require converting the
* pattern to UTF-8, unless not using it could cause us to miss
* some folds (hence be buggy) */
if (! UTF && value > 255) {
SV * in_multis = NULL;
assert(FOLD);
/* If there is no code point that is part of a multi-char
* fold, then there aren't any matches, so we don't do this
* optimization. Otherwise, it could match depending on
* the context around us, so we do upgrade */
_invlist_intersection(PL_InMultiCharFold, cp_list, &in_multis);
if (UNLIKELY(_invlist_len(in_multis) != 0)) {
REQUIRE_UTF8(flagp);
}
else {
op = END;
}
}
if (op != END) {
U8 len = (UTF) ? UVCHR_SKIP(value) : 1;
ret = regnode_guts(pRExC_state, op, len, "exact");
FILL_NODE(ret, op);
RExC_emit += 1 + STR_SZ(len);
STR_LEN(REGNODE_p(ret)) = len;
if (len == 1) {
*STRING(REGNODE_p(ret)) = (U8) value;
}
else {
uvchr_to_utf8((U8 *) STRING(REGNODE_p(ret)), value);
}
goto not_anyof;
}
}
}
if (! has_runtime_dependency) {
/* See if this can be turned into an ANYOFM node. Think about the
* bit patterns in two different bytes. In some positions, the
* bits in each will be 1; and in other positions both will be 0;
* and in some positions the bit will be 1 in one byte, and 0 in
* the other. Let 'n' be the number of positions where the bits
* differ. We create a mask which has exactly 'n' 0 bits, each in
* a position where the two bytes differ. Now take the set of all
* bytes that when ANDed with the mask yield the same result. That
* set has 2**n elements, and is representable by just two 8 bit
* numbers: the result and the mask. Importantly, matching the set
* can be vectorized by creating a word full of the result bytes,
* and a word full of the mask bytes, yielding a significant speed
* up. Here, see if this node matches such a set. As a concrete
* example consider [01], and the byte representing '0' which is
* 0x30 on ASCII machines. It has the bits 0011 0000. Take the
* mask 1111 1110. If we AND 0x31 and 0x30 with that mask we get
* 0x30. Any other bytes ANDed yield something else. So [01],
* which is a common usage, is optimizable into ANYOFM, and can
* benefit from the speed up. We can only do this on UTF-8
* invariant bytes, because they have the same bit patterns under
* UTF-8 as not. */
PERL_UINT_FAST8_T inverted = 0;
#ifdef EBCDIC
const PERL_UINT_FAST8_T max_permissible = 0xFF;
#else
const PERL_UINT_FAST8_T max_permissible = 0x7F;
#endif
/* If doesn't fit the criteria for ANYOFM, invert and try again.
* If that works we will instead later generate an NANYOFM, and
* invert back when through */
if (invlist_highest(cp_list) > max_permissible) {
_invlist_invert(cp_list);
inverted = 1;
}
if (invlist_highest(cp_list) <= max_permissible) {
UV this_start, this_end;
UV lowest_cp = UV_MAX; /* inited to suppress compiler warn */
U8 bits_differing = 0;
Size_t full_cp_count = 0;
bool first_time = TRUE;
/* Go through the bytes and find the bit positions that differ
* */
invlist_iterinit(cp_list);
while (invlist_iternext(cp_list, &this_start, &this_end)) {
unsigned int i = this_start;
if (first_time) {
if (! UVCHR_IS_INVARIANT(i)) {
goto done_anyofm;
}
first_time = FALSE;
lowest_cp = this_start;
/* We have set up the code point to compare with.
* Don't compare it with itself */
i++;
}
/* Find the bit positions that differ from the lowest code
* point in the node. Keep track of all such positions by
* OR'ing */
for (; i <= this_end; i++) {
if (! UVCHR_IS_INVARIANT(i)) {
goto done_anyofm;
}
bits_differing |= i ^ lowest_cp;
}
full_cp_count += this_end - this_start + 1;
}
invlist_iterfinish(cp_list);
/* At the end of the loop, we count how many bits differ from
* the bits in lowest code point, call the count 'd'. If the
* set we found contains 2**d elements, it is the closure of
* all code points that differ only in those bit positions. To
* convince yourself of that, first note that the number in the
* closure must be a power of 2, which we test for. The only
* way we could have that count and it be some differing set,
* is if we got some code points that don't differ from the
* lowest code point in any position, but do differ from each
* other in some other position. That means one code point has
* a 1 in that position, and another has a 0. But that would
* mean that one of them differs from the lowest code point in
* that position, which possibility we've already excluded. */
if ( (inverted || full_cp_count > 1)
&& full_cp_count == 1U << PL_bitcount[bits_differing])
{
U8 ANYOFM_mask;
op = ANYOFM + inverted;;
/* We need to make the bits that differ be 0's */
ANYOFM_mask = ~ bits_differing; /* This goes into FLAGS */
/* The argument is the lowest code point */
ret = reganode(pRExC_state, op, lowest_cp);
FLAGS(REGNODE_p(ret)) = ANYOFM_mask;
}
}
done_anyofm:
if (inverted) {
_invlist_invert(cp_list);
}
if (op != END) {
goto not_anyof;
}
}
if (! (anyof_flags & ANYOF_LOCALE_FLAGS)) {
PERL_UINT_FAST8_T type;
SV * intersection = NULL;
SV* d_invlist = NULL;
/* See if this matches any of the POSIX classes. The POSIXA and
* POSIXD ones are about the same speed as ANYOF ops, but take less
* room; the ones that have above-Latin1 code point matches are
* somewhat faster than ANYOF. */
for (type = POSIXA; type >= POSIXD; type--) {
int posix_class;
if (type == POSIXL) { /* But not /l posix classes */
continue;
}
for (posix_class = 0;
posix_class <= _HIGHEST_REGCOMP_DOT_H_SYNC;
posix_class++)
{
SV** our_code_points = &cp_list;
SV** official_code_points;
int try_inverted;
if (type == POSIXA) {
official_code_points = &PL_Posix_ptrs[posix_class];
}
else {
official_code_points = &PL_XPosix_ptrs[posix_class];
}
/* Skip non-existent classes of this type. e.g. \v only
* has an entry in PL_XPosix_ptrs */
if (! *official_code_points) {
continue;
}
/* Try both the regular class, and its inversion */
for (try_inverted = 0; try_inverted < 2; try_inverted++) {
bool this_inverted = invert ^ try_inverted;
if (type != POSIXD) {
/* This class that isn't /d can't match if we have
* /d dependencies */
if (has_runtime_dependency
& HAS_D_RUNTIME_DEPENDENCY)
{
continue;
}
}
else /* is /d */ if (! this_inverted) {
/* /d classes don't match anything non-ASCII below
* 256 unconditionally (which cp_list contains) */
_invlist_intersection(cp_list, PL_UpperLatin1,
&intersection);
if (_invlist_len(intersection) != 0) {
continue;
}
SvREFCNT_dec(d_invlist);
d_invlist = invlist_clone(cp_list, NULL);
/* But under UTF-8 it turns into using /u rules.
* Add the things it matches under these conditions
* so that we check below that these are identical
* to what the tested class should match */
if (upper_latin1_only_utf8_matches) {
_invlist_union(
d_invlist,
upper_latin1_only_utf8_matches,
&d_invlist);
}
our_code_points = &d_invlist;
}
else { /* POSIXD, inverted. If this doesn't have this
flag set, it isn't /d. */
if (! (anyof_flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))
{
continue;
}
our_code_points = &cp_list;
}
/* Here, have weeded out some things. We want to see
* if the list of characters this node contains
* ('*our_code_points') precisely matches those of the
* class we are currently checking against
* ('*official_code_points'). */
if (_invlistEQ(*our_code_points,
*official_code_points,
try_inverted))
{
/* Here, they precisely match. Optimize this ANYOF
* node into its equivalent POSIX one of the
* correct type, possibly inverted */
ret = reg_node(pRExC_state, (try_inverted)
? type + NPOSIXA
- POSIXA
: type);
FLAGS(REGNODE_p(ret)) = posix_class;
SvREFCNT_dec(d_invlist);
SvREFCNT_dec(intersection);
goto not_anyof;
}
}
}
}
SvREFCNT_dec(d_invlist);
SvREFCNT_dec(intersection);
}
/* If didn't find an optimization and there is no need for a
* bitmap, optimize to indicate that */
if ( start[0] >= NUM_ANYOF_CODE_POINTS
&& ! LOC
&& ! upper_latin1_only_utf8_matches
&& anyof_flags == 0)
{
UV highest_cp = invlist_highest(cp_list);
/* If the lowest and highest code point in the class have the same
* UTF-8 first byte, then all do, and we can store that byte for
* regexec.c to use so that it can more quickly scan the target
* string for potential matches for this class. We co-opt the the
* flags field for this. Zero means, they don't have the same
* first byte. We do accept here very large code points (for
* future use), but don't bother with this optimization for them,
* as it would cause other complications */
if (highest_cp > IV_MAX) {
anyof_flags = 0;
}
else {
U8 low_utf8[UTF8_MAXBYTES+1];
U8 high_utf8[UTF8_MAXBYTES+1];
(void) uvchr_to_utf8(low_utf8, start[0]);
(void) uvchr_to_utf8(high_utf8, invlist_highest(cp_list));
anyof_flags = (low_utf8[0] == high_utf8[0])
? low_utf8[0]
: 0;
}
op = ANYOFH;
}
} /* End of seeing if can optimize it into a different node */
is_anyof: /* It's going to be an ANYOF node. */
if (op != ANYOFH) {
op = (has_runtime_dependency & HAS_D_RUNTIME_DEPENDENCY)
? ANYOFD
: ((posixl)
? ANYOFPOSIXL
: ((LOC)
? ANYOFL
: ANYOF));
}
ret = regnode_guts(pRExC_state, op, regarglen[op], "anyof");
FILL_NODE(ret, op); /* We set the argument later */
RExC_emit += 1 + regarglen[op];
ANYOF_FLAGS(REGNODE_p(ret)) = anyof_flags;
/* Here, <cp_list> contains all the code points we can determine at
* compile time that match under all conditions. Go through it, and
* for things that belong in the bitmap, put them there, and delete from
* <cp_list>. While we are at it, see if everything above 255 is in the
* list, and if so, set a flag to speed up execution */
populate_ANYOF_from_invlist(REGNODE_p(ret), &cp_list);
if (posixl) {
ANYOF_POSIXL_SET_TO_BITMAP(REGNODE_p(ret), posixl);
}
if (invert) {
ANYOF_FLAGS(REGNODE_p(ret)) |= ANYOF_INVERT;
}
/* Here, the bitmap has been populated with all the Latin1 code points that
* always match. Can now add to the overall list those that match only
* when the target string is UTF-8 (<upper_latin1_only_utf8_matches>).
* */
if (upper_latin1_only_utf8_matches) {
if (cp_list) {
_invlist_union(cp_list,
upper_latin1_only_utf8_matches,
&cp_list);
SvREFCNT_dec_NN(upper_latin1_only_utf8_matches);
}
else {
cp_list = upper_latin1_only_utf8_matches;
}
ANYOF_FLAGS(REGNODE_p(ret)) |= ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP;
}
set_ANYOF_arg(pRExC_state, REGNODE_p(ret), cp_list,
(HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION)
? listsv : NULL,
only_utf8_locale_list);
return ret;
not_anyof:
/* Here, the node is getting optimized into something that's not an ANYOF
* one. Finish up. */
Set_Node_Offset_Length(REGNODE_p(ret), orig_parse - RExC_start,
RExC_parse - orig_parse);;
SvREFCNT_dec(cp_list);;
return ret;
}
#undef HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION
STATIC void
S_set_ANYOF_arg(pTHX_ RExC_state_t* const pRExC_state,
regnode* const node,
SV* const cp_list,
SV* const runtime_defns,
SV* const only_utf8_locale_list)
{
/* Sets the arg field of an ANYOF-type node 'node', using information about
* the node passed-in. If there is nothing outside the node's bitmap, the
* arg is set to ANYOF_ONLY_HAS_BITMAP. Otherwise, it sets the argument to
* the count returned by add_data(), having allocated and stored an array,
* av, as follows:
*
* av[0] stores the inversion list defining this class as far as known at
* this time, or PL_sv_undef if nothing definite is now known.
* av[1] stores the inversion list of code points that match only if the
* current locale is UTF-8, or if none, PL_sv_undef if there is an
* av[2], or no entry otherwise.
* av[2] stores the list of user-defined properties whose subroutine
* definitions aren't known at this time, or no entry if none. */
UV n;
PERL_ARGS_ASSERT_SET_ANYOF_ARG;
if (! cp_list && ! runtime_defns && ! only_utf8_locale_list) {
assert(! (ANYOF_FLAGS(node)
& ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP));
ARG_SET(node, ANYOF_ONLY_HAS_BITMAP);
}
else {
AV * const av = newAV();
SV *rv;
if (cp_list) {
av_store(av, INVLIST_INDEX, cp_list);
}
if (only_utf8_locale_list) {
av_store(av, ONLY_LOCALE_MATCHES_INDEX, only_utf8_locale_list);
}
if (runtime_defns) {
av_store(av, DEFERRED_USER_DEFINED_INDEX, SvREFCNT_inc(runtime_defns));
}
rv = newRV_noinc(MUTABLE_SV(av));
n = add_data(pRExC_state, STR_WITH_LEN("s"));
RExC_rxi->data->data[n] = (void*)rv;
ARG_SET(node, n);
}
}
#if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
SV *
Perl__get_regclass_nonbitmap_data(pTHX_ const regexp *prog,
const regnode* node,
bool doinit,
SV** listsvp,
SV** only_utf8_locale_ptr,
SV** output_invlist)
{
/* For internal core use only.
* Returns the inversion list for the input 'node' in the regex 'prog'.
* If <doinit> is 'true', will attempt to create the inversion list if not
* already done.
* If <listsvp> is non-null, will return the printable contents of the
* property definition. This can be used to get debugging information
* even before the inversion list exists, by calling this function with
* 'doinit' set to false, in which case the components that will be used
* to eventually create the inversion list are returned (in a printable
* form).
* If <only_utf8_locale_ptr> is not NULL, it is where this routine is to
* store an inversion list of code points that should match only if the
* execution-time locale is a UTF-8 one.
* If <output_invlist> is not NULL, it is where this routine is to store an
* inversion list of the code points that would be instead returned in
* <listsvp> if this were NULL. Thus, what gets output in <listsvp>
* when this parameter is used, is just the non-code point data that
* will go into creating the inversion list. This currently should be just
* user-defined properties whose definitions were not known at compile
* time. Using this parameter allows for easier manipulation of the
* inversion list's data by the caller. It is illegal to call this
* function with this parameter set, but not <listsvp>
*
* Tied intimately to how S_set_ANYOF_arg sets up the data structure. Note
* that, in spite of this function's name, the inversion list it returns
* may include the bitmap data as well */
SV *si = NULL; /* Input initialization string */
SV* invlist = NULL;
RXi_GET_DECL(prog, progi);
const struct reg_data * const data = prog ? progi->data : NULL;
PERL_ARGS_ASSERT__GET_REGCLASS_NONBITMAP_DATA;
assert(! output_invlist || listsvp);
if (data && data->count) {
const U32 n = ARG(node);
if (data->what[n] == 's') {
SV * const rv = MUTABLE_SV(data->data[n]);
AV * const av = MUTABLE_AV(SvRV(rv));
SV **const ary = AvARRAY(av);
invlist = ary[INVLIST_INDEX];
if (av_tindex_skip_len_mg(av) >= ONLY_LOCALE_MATCHES_INDEX) {
*only_utf8_locale_ptr = ary[ONLY_LOCALE_MATCHES_INDEX];
}
if (av_tindex_skip_len_mg(av) >= DEFERRED_USER_DEFINED_INDEX) {
si = ary[DEFERRED_USER_DEFINED_INDEX];
}
if (doinit && (si || invlist)) {
if (si) {
bool user_defined;
SV * msg = newSVpvs_flags("", SVs_TEMP);
SV * prop_definition = handle_user_defined_property(
"", 0, FALSE, /* There is no \p{}, \P{} */
SvPVX_const(si)[1] - '0', /* /i or not has been
stored here for just
this occasion */
TRUE, /* run time */
FALSE, /* This call must find the defn */
si, /* The property definition */
&user_defined,
msg,
0 /* base level call */
);
if (SvCUR(msg)) {
assert(prop_definition == NULL);
Perl_croak(aTHX_ "%" UTF8f,
UTF8fARG(SvUTF8(msg), SvCUR(msg), SvPVX(msg)));
}
if (invlist) {
_invlist_union(invlist, prop_definition, &invlist);
SvREFCNT_dec_NN(prop_definition);
}
else {
invlist = prop_definition;
}
STATIC_ASSERT_STMT(ONLY_LOCALE_MATCHES_INDEX == 1 + INVLIST_INDEX);
STATIC_ASSERT_STMT(DEFERRED_USER_DEFINED_INDEX == 1 + ONLY_LOCALE_MATCHES_INDEX);
av_store(av, INVLIST_INDEX, invlist);
av_fill(av, (ary[ONLY_LOCALE_MATCHES_INDEX])
? ONLY_LOCALE_MATCHES_INDEX:
INVLIST_INDEX);
si = NULL;
}
}
}
}
/* If requested, return a printable version of what this ANYOF node matches
* */
if (listsvp) {
SV* matches_string = NULL;
/* This function can be called at compile-time, before everything gets
* resolved, in which case we return the currently best available
* information, which is the string that will eventually be used to do
* that resolving, 'si' */
if (si) {
/* Here, we only have 'si' (and possibly some passed-in data in
* 'invlist', which is handled below) If the caller only wants
* 'si', use that. */
if (! output_invlist) {
matches_string = newSVsv(si);
}
else {
/* But if the caller wants an inversion list of the node, we
* need to parse 'si' and place as much as possible in the
* desired output inversion list, making 'matches_string' only
* contain the currently unresolvable things */
const char *si_string = SvPVX(si);
STRLEN remaining = SvCUR(si);
UV prev_cp = 0;
U8 count = 0;
/* Ignore everything before the first new-line */
while (*si_string != '\n' && remaining > 0) {
si_string++;
remaining--;
}
assert(remaining > 0);
si_string++;
remaining--;
while (remaining > 0) {
/* The data consists of just strings defining user-defined
* property names, but in prior incarnations, and perhaps
* somehow from pluggable regex engines, it could still
* hold hex code point definitions. Each component of a
* range would be separated by a tab, and each range by a
* new-line. If these are found, instead add them to the
* inversion list */
I32 grok_flags = PERL_SCAN_SILENT_ILLDIGIT
|PERL_SCAN_SILENT_NON_PORTABLE;
STRLEN len = remaining;
UV cp = grok_hex(si_string, &len, &grok_flags, NULL);
/* If the hex decode routine found something, it should go
* up to the next \n */
if ( *(si_string + len) == '\n') {
if (count) { /* 2nd code point on line */
*output_invlist = _add_range_to_invlist(*output_invlist, prev_cp, cp);
}
else {
*output_invlist = add_cp_to_invlist(*output_invlist, cp);
}
count = 0;
goto prepare_for_next_iteration;
}
/* If the hex decode was instead for the lower range limit,
* save it, and go parse the upper range limit */
if (*(si_string + len) == '\t') {
assert(count == 0);
prev_cp = cp;
count = 1;
prepare_for_next_iteration:
si_string += len + 1;
remaining -= len + 1;
continue;
}
/* Here, didn't find a legal hex number. Just add it from
* here to the next \n */
remaining -= len;
while (*(si_string + len) != '\n' && remaining > 0) {
remaining--;
len++;
}
if (*(si_string + len) == '\n') {
len++;
remaining--;
}
if (matches_string) {
sv_catpvn(matches_string, si_string, len - 1);
}
else {
matches_string = newSVpvn(si_string, len - 1);
}
si_string += len;
sv_catpvs(matches_string, " ");
} /* end of loop through the text */
assert(matches_string);
if (SvCUR(matches_string)) { /* Get rid of trailing blank */
SvCUR_set(matches_string, SvCUR(matches_string) - 1);
}
} /* end of has an 'si' */
}
/* Add the stuff that's already known */
if (invlist) {
/* Again, if the caller doesn't want the output inversion list, put
* everything in 'matches-string' */
if (! output_invlist) {
if ( ! matches_string) {
matches_string = newSVpvs("\n");
}
sv_catsv(matches_string, invlist_contents(invlist,
TRUE /* traditional style */
));
}
else if (! *output_invlist) {
*output_invlist = invlist_clone(invlist, NULL);
}
else {
_invlist_union(*output_invlist, invlist, output_invlist);
}
}
*listsvp = matches_string;
}
return invlist;
}
#endif /* !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION) */
/* reg_skipcomment()
Absorbs an /x style # comment from the input stream,
returning a pointer to the first character beyond the comment, or if the
comment terminates the pattern without anything following it, this returns
one past the final character of the pattern (in other words, RExC_end) and
sets the REG_RUN_ON_COMMENT_SEEN flag.
Note it's the callers responsibility to ensure that we are
actually in /x mode
*/
PERL_STATIC_INLINE char*
S_reg_skipcomment(RExC_state_t *pRExC_state, char* p)
{
PERL_ARGS_ASSERT_REG_SKIPCOMMENT;
assert(*p == '#');
while (p < RExC_end) {
if (*(++p) == '\n') {
return p+1;
}
}
/* we ran off the end of the pattern without ending the comment, so we have
* to add an \n when wrapping */
RExC_seen |= REG_RUN_ON_COMMENT_SEEN;
return p;
}
STATIC void
S_skip_to_be_ignored_text(pTHX_ RExC_state_t *pRExC_state,
char ** p,
const bool force_to_xmod
)
{
/* If the text at the current parse position '*p' is a '(?#...)' comment,
* or if we are under /x or 'force_to_xmod' is TRUE, and the text at '*p'
* is /x whitespace, advance '*p' so that on exit it points to the first
* byte past all such white space and comments */
const bool use_xmod = force_to_xmod || (RExC_flags & RXf_PMf_EXTENDED);
PERL_ARGS_ASSERT_SKIP_TO_BE_IGNORED_TEXT;
assert( ! UTF || UTF8_IS_INVARIANT(**p) || UTF8_IS_START(**p));
for (;;) {
if (RExC_end - (*p) >= 3
&& *(*p) == '('
&& *(*p + 1) == '?'
&& *(*p + 2) == '#')
{
while (*(*p) != ')') {
if ((*p) == RExC_end)
FAIL("Sequence (?#... not terminated");
(*p)++;
}
(*p)++;
continue;
}
if (use_xmod) {
const char * save_p = *p;
while ((*p) < RExC_end) {
STRLEN len;
if ((len = is_PATWS_safe((*p), RExC_end, UTF))) {
(*p) += len;
}
else if (*(*p) == '#') {
(*p) = reg_skipcomment(pRExC_state, (*p));
}
else {
break;
}
}
if (*p != save_p) {
continue;
}
}
break;
}
return;
}
/* nextchar()
Advances the parse position by one byte, unless that byte is the beginning
of a '(?#...)' style comment, or is /x whitespace and /x is in effect. In
those two cases, the parse position is advanced beyond all such comments and
white space.
This is the UTF, (?#...), and /x friendly way of saying RExC_parse++.
*/
STATIC void
S_nextchar(pTHX_ RExC_state_t *pRExC_state)
{
PERL_ARGS_ASSERT_NEXTCHAR;
if (RExC_parse < RExC_end) {
assert( ! UTF
|| UTF8_IS_INVARIANT(*RExC_parse)
|| UTF8_IS_START(*RExC_parse));
RExC_parse += (UTF)
? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
: 1;
skip_to_be_ignored_text(pRExC_state, &RExC_parse,
FALSE /* Don't force /x */ );
}
}
STATIC void
S_change_engine_size(pTHX_ RExC_state_t *pRExC_state, const Ptrdiff_t size)
{
/* 'size' is the delta to add or subtract from the current memory allocated
* to the regex engine being constructed */
PERL_ARGS_ASSERT_CHANGE_ENGINE_SIZE;
RExC_size += size;
Renewc(RExC_rxi,
sizeof(regexp_internal) + (RExC_size + 1) * sizeof(regnode),
/* +1 for REG_MAGIC */
char,
regexp_internal);
if ( RExC_rxi == NULL )
FAIL("Regexp out of space");
RXi_SET(RExC_rx, RExC_rxi);
RExC_emit_start = RExC_rxi->program;
if (size > 0) {
Zero(REGNODE_p(RExC_emit), size, regnode);
}
#ifdef RE_TRACK_PATTERN_OFFSETS
Renew(RExC_offsets, 2*RExC_size+1, U32);
if (size > 0) {
Zero(RExC_offsets + 2*(RExC_size - size) + 1, 2 * size, U32);
}
RExC_offsets[0] = RExC_size;
#endif
}
STATIC regnode_offset
S_regnode_guts(pTHX_ RExC_state_t *pRExC_state, const U8 op, const STRLEN extra_size, const char* const name)
{
/* Allocate a regnode for 'op', with 'extra_size' extra space. It aligns
* and increments RExC_size and RExC_emit
*
* It returns the regnode's offset into the regex engine program */
const regnode_offset ret = RExC_emit;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REGNODE_GUTS;
SIZE_ALIGN(RExC_size);
change_engine_size(pRExC_state, (Ptrdiff_t) 1 + extra_size);
NODE_ALIGN_FILL(REGNODE_p(ret));
#ifndef RE_TRACK_PATTERN_OFFSETS
PERL_UNUSED_ARG(name);
PERL_UNUSED_ARG(op);
#else
assert(extra_size >= regarglen[op] || PL_regkind[op] == ANYOF);
if (RExC_offsets) { /* MJD */
MJD_OFFSET_DEBUG(
("%s:%d: (op %s) %s %" UVuf " (len %" UVuf ") (max %" UVuf ").\n",
name, __LINE__,
PL_reg_name[op],
(UV)(RExC_emit) > RExC_offsets[0]
? "Overwriting end of array!\n" : "OK",
(UV)(RExC_emit),
(UV)(RExC_parse - RExC_start),
(UV)RExC_offsets[0]));
Set_Node_Offset(REGNODE_p(RExC_emit), RExC_parse + (op == END));
}
#endif
return(ret);
}
/*
- reg_node - emit a node
*/
STATIC regnode_offset /* Location. */
S_reg_node(pTHX_ RExC_state_t *pRExC_state, U8 op)
{
const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reg_node");
regnode_offset ptr = ret;
PERL_ARGS_ASSERT_REG_NODE;
assert(regarglen[op] == 0);
FILL_ADVANCE_NODE(ptr, op);
RExC_emit = ptr;
return(ret);
}
/*
- reganode - emit a node with an argument
*/
STATIC regnode_offset /* Location. */
S_reganode(pTHX_ RExC_state_t *pRExC_state, U8 op, U32 arg)
{
const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reganode");
regnode_offset ptr = ret;
PERL_ARGS_ASSERT_REGANODE;
/* ANYOF are special cased to allow non-length 1 args */
assert(regarglen[op] == 1);
FILL_ADVANCE_NODE_ARG(ptr, op, arg);
RExC_emit = ptr;
return(ret);
}
STATIC regnode_offset
S_reg2Lanode(pTHX_ RExC_state_t *pRExC_state, const U8 op, const U32 arg1, const I32 arg2)
{
/* emit a node with U32 and I32 arguments */
const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reg2Lanode");
regnode_offset ptr = ret;
PERL_ARGS_ASSERT_REG2LANODE;
assert(regarglen[op] == 2);
FILL_ADVANCE_NODE_2L_ARG(ptr, op, arg1, arg2);
RExC_emit = ptr;
return(ret);
}
/*
- reginsert - insert an operator in front of already-emitted operand
*
* That means that on exit 'operand' is the offset of the newly inserted
* operator, and the original operand has been relocated.
*
* IMPORTANT NOTE - it is the *callers* responsibility to correctly
* set up NEXT_OFF() of the inserted node if needed. Something like this:
*
* reginsert(pRExC, OPFAIL, orig_emit, depth+1);
* NEXT_OFF(orig_emit) = regarglen[OPFAIL] + NODE_STEP_REGNODE;
*
* ALSO NOTE - FLAGS(newly-inserted-operator) will be set to 0 as well.
*/
STATIC void
S_reginsert(pTHX_ RExC_state_t *pRExC_state, const U8 op,
const regnode_offset operand, const U32 depth)
{
regnode *src;
regnode *dst;
regnode *place;
const int offset = regarglen[(U8)op];
const int size = NODE_STEP_REGNODE + offset;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REGINSERT;
PERL_UNUSED_CONTEXT;
PERL_UNUSED_ARG(depth);
/* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
DEBUG_PARSE_FMT("inst"," - %s", PL_reg_name[op]);
assert(!RExC_study_started); /* I believe we should never use reginsert once we have started
studying. If this is wrong then we need to adjust RExC_recurse
below like we do with RExC_open_parens/RExC_close_parens. */
change_engine_size(pRExC_state, (Ptrdiff_t) size);
src = REGNODE_p(RExC_emit);
RExC_emit += size;
dst = REGNODE_p(RExC_emit);
/* If we are in a "count the parentheses" pass, the numbers are unreliable,
* and [perl #133871] shows this can lead to problems, so skip this
* realignment of parens until a later pass when they are reliable */
if (! IN_PARENS_PASS && RExC_open_parens) {
int paren;
/*DEBUG_PARSE_FMT("inst"," - %" IVdf, (IV)RExC_npar);*/
/* remember that RExC_npar is rex->nparens + 1,
* iow it is 1 more than the number of parens seen in
* the pattern so far. */
for ( paren=0 ; paren < RExC_npar ; paren++ ) {
/* note, RExC_open_parens[0] is the start of the
* regex, it can't move. RExC_close_parens[0] is the end
* of the regex, it *can* move. */
if ( paren && RExC_open_parens[paren] >= operand ) {
/*DEBUG_PARSE_FMT("open"," - %d", size);*/
RExC_open_parens[paren] += size;
} else {
/*DEBUG_PARSE_FMT("open"," - %s","ok");*/
}
if ( RExC_close_parens[paren] >= operand ) {
/*DEBUG_PARSE_FMT("close"," - %d", size);*/
RExC_close_parens[paren] += size;
} else {
/*DEBUG_PARSE_FMT("close"," - %s","ok");*/
}
}
}
if (RExC_end_op)
RExC_end_op += size;
while (src > REGNODE_p(operand)) {
StructCopy(--src, --dst, regnode);
#ifdef RE_TRACK_PATTERN_OFFSETS
if (RExC_offsets) { /* MJD 20010112 */
MJD_OFFSET_DEBUG(
("%s(%d): (op %s) %s copy %" UVuf " -> %" UVuf " (max %" UVuf ").\n",
"reginsert",
__LINE__,
PL_reg_name[op],
(UV)(REGNODE_OFFSET(dst)) > RExC_offsets[0]
? "Overwriting end of array!\n" : "OK",
(UV)REGNODE_OFFSET(src),
(UV)REGNODE_OFFSET(dst),
(UV)RExC_offsets[0]));
Set_Node_Offset_To_R(REGNODE_OFFSET(dst), Node_Offset(src));
Set_Node_Length_To_R(REGNODE_OFFSET(dst), Node_Length(src));
}
#endif
}
place = REGNODE_p(operand); /* Op node, where operand used to be. */
#ifdef RE_TRACK_PATTERN_OFFSETS
if (RExC_offsets) { /* MJD */
MJD_OFFSET_DEBUG(
("%s(%d): (op %s) %s %" UVuf " <- %" UVuf " (max %" UVuf ").\n",
"reginsert",
__LINE__,
PL_reg_name[op],
(UV)REGNODE_OFFSET(place) > RExC_offsets[0]
? "Overwriting end of array!\n" : "OK",
(UV)REGNODE_OFFSET(place),
(UV)(RExC_parse - RExC_start),
(UV)RExC_offsets[0]));
Set_Node_Offset(place, RExC_parse);
Set_Node_Length(place, 1);
}
#endif
src = NEXTOPER(place);
FLAGS(place) = 0;
FILL_NODE(operand, op);
/* Zero out any arguments in the new node */
Zero(src, offset, regnode);
}
/*
- regtail - set the next-pointer at the end of a node chain of p to val. If
that value won't fit in the space available, instead returns FALSE.
(Except asserts if we can't fit in the largest space the regex
engine is designed for.)
- SEE ALSO: regtail_study
*/
STATIC bool
S_regtail(pTHX_ RExC_state_t * pRExC_state,
const regnode_offset p,
const regnode_offset val,
const U32 depth)
{
regnode_offset scan;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REGTAIL;
#ifndef DEBUGGING
PERL_UNUSED_ARG(depth);
#endif
/* Find last node. */
scan = (regnode_offset) p;
for (;;) {
regnode * const temp = regnext(REGNODE_p(scan));
DEBUG_PARSE_r({
DEBUG_PARSE_MSG((scan==p ? "tail" : ""));
regprop(RExC_rx, RExC_mysv, REGNODE_p(scan), NULL, pRExC_state);
Perl_re_printf( aTHX_ "~ %s (%d) %s %s\n",
SvPV_nolen_const(RExC_mysv), scan,
(temp == NULL ? "->" : ""),
(temp == NULL ? PL_reg_name[OP(REGNODE_p(val))] : "")
);
});
if (temp == NULL)
break;
scan = REGNODE_OFFSET(temp);
}
if (reg_off_by_arg[OP(REGNODE_p(scan))]) {
assert((UV) (val - scan) <= U32_MAX);
ARG_SET(REGNODE_p(scan), val - scan);
}
else {
if (val - scan > U16_MAX) {
/* Populate this with something that won't loop and will likely
* lead to a crash if the caller ignores the failure return, and
* execution continues */
NEXT_OFF(REGNODE_p(scan)) = U16_MAX;
return FALSE;
}
NEXT_OFF(REGNODE_p(scan)) = val - scan;
}
return TRUE;
}
#ifdef DEBUGGING
/*
- regtail_study - set the next-pointer at the end of a node chain of p to val.
- Look for optimizable sequences at the same time.
- currently only looks for EXACT chains.
This is experimental code. The idea is to use this routine to perform
in place optimizations on branches and groups as they are constructed,
with the long term intention of removing optimization from study_chunk so
that it is purely analytical.
Currently only used when in DEBUG mode. The macro REGTAIL_STUDY() is used
to control which is which.
This used to return a value that was ignored. It was a problem that it is
#ifdef'd to be another function that didn't return a value. khw has changed it
so both currently return a pass/fail return.
*/
/* TODO: All four parms should be const */
STATIC bool
S_regtail_study(pTHX_ RExC_state_t *pRExC_state, regnode_offset p,
const regnode_offset val, U32 depth)
{
regnode_offset scan;
U8 exact = PSEUDO;
#ifdef EXPERIMENTAL_INPLACESCAN
I32 min = 0;
#endif
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REGTAIL_STUDY;
/* Find last node. */
scan = p;
for (;;) {
regnode * const temp = regnext(REGNODE_p(scan));
#ifdef EXPERIMENTAL_INPLACESCAN
if (PL_regkind[OP(REGNODE_p(scan))] == EXACT) {
bool unfolded_multi_char; /* Unexamined in this routine */
if (join_exact(pRExC_state, scan, &min,
&unfolded_multi_char, 1, REGNODE_p(val), depth+1))
return TRUE; /* Was return EXACT */
}
#endif
if ( exact ) {
switch (OP(REGNODE_p(scan))) {
case EXACT:
case EXACT_ONLY8:
case EXACTL:
case EXACTF:
case EXACTFU_S_EDGE:
case EXACTFAA_NO_TRIE:
case EXACTFAA:
case EXACTFU:
case EXACTFU_ONLY8:
case EXACTFLU8:
case EXACTFUP:
case EXACTFL:
if( exact == PSEUDO )
exact= OP(REGNODE_p(scan));
else if ( exact != OP(REGNODE_p(scan)) )
exact= 0;
case NOTHING:
break;
default:
exact= 0;
}
}
DEBUG_PARSE_r({
DEBUG_PARSE_MSG((scan==p ? "tsdy" : ""));
regprop(RExC_rx, RExC_mysv, REGNODE_p(scan), NULL, pRExC_state);
Perl_re_printf( aTHX_ "~ %s (%d) -> %s\n",
SvPV_nolen_const(RExC_mysv),
scan,
PL_reg_name[exact]);
});
if (temp == NULL)
break;
scan = REGNODE_OFFSET(temp);
}
DEBUG_PARSE_r({
DEBUG_PARSE_MSG("");
regprop(RExC_rx, RExC_mysv, REGNODE_p(val), NULL, pRExC_state);
Perl_re_printf( aTHX_
"~ attach to %s (%" IVdf ") offset to %" IVdf "\n",
SvPV_nolen_const(RExC_mysv),
(IV)val,
(IV)(val - scan)
);
});
if (reg_off_by_arg[OP(REGNODE_p(scan))]) {
assert((UV) (val - scan) <= U32_MAX);
ARG_SET(REGNODE_p(scan), val - scan);
}
else {
if (val - scan > U16_MAX) {
/* Populate this with something that won't loop and will likely
* lead to a crash if the caller ignores the failure return, and
* execution continues */
NEXT_OFF(REGNODE_p(scan)) = U16_MAX;
return FALSE;
}
NEXT_OFF(REGNODE_p(scan)) = val - scan;
}
return TRUE; /* Was 'return exact' */
}
#endif
STATIC SV*
S_get_ANYOFM_contents(pTHX_ const regnode * n) {
/* Returns an inversion list of all the code points matched by the
* ANYOFM/NANYOFM node 'n' */
SV * cp_list = _new_invlist(-1);
const U8 lowest = (U8) ARG(n);
unsigned int i;
U8 count = 0;
U8 needed = 1U << PL_bitcount[ (U8) ~ FLAGS(n)];
PERL_ARGS_ASSERT_GET_ANYOFM_CONTENTS;
/* Starting with the lowest code point, any code point that ANDed with the
* mask yields the lowest code point is in the set */
for (i = lowest; i <= 0xFF; i++) {
if ((i & FLAGS(n)) == ARG(n)) {
cp_list = add_cp_to_invlist(cp_list, i);
count++;
/* We know how many code points (a power of two) that are in the
* set. No use looking once we've got that number */
if (count >= needed) break;
}
}
if (OP(n) == NANYOFM) {
_invlist_invert(cp_list);
}
return cp_list;
}
/*
- regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
*/
#ifdef DEBUGGING
static void
S_regdump_intflags(pTHX_ const char *lead, const U32 flags)
{
int bit;
int set=0;
ASSUME(REG_INTFLAGS_NAME_SIZE <= sizeof(flags)*8);
for (bit=0; bit<REG_INTFLAGS_NAME_SIZE; bit++) {
if (flags & (1<<bit)) {
if (!set++ && lead)
Perl_re_printf( aTHX_ "%s", lead);
Perl_re_printf( aTHX_ "%s ", PL_reg_intflags_name[bit]);
}
}
if (lead) {
if (set)
Perl_re_printf( aTHX_ "\n");
else
Perl_re_printf( aTHX_ "%s[none-set]\n", lead);
}
}
static void
S_regdump_extflags(pTHX_ const char *lead, const U32 flags)
{
int bit;
int set=0;
regex_charset cs;
ASSUME(REG_EXTFLAGS_NAME_SIZE <= sizeof(flags)*8);
for (bit=0; bit<REG_EXTFLAGS_NAME_SIZE; bit++) {
if (flags & (1<<bit)) {
if ((1<<bit) & RXf_PMf_CHARSET) { /* Output separately, below */
continue;
}
if (!set++ && lead)
Perl_re_printf( aTHX_ "%s", lead);
Perl_re_printf( aTHX_ "%s ", PL_reg_extflags_name[bit]);
}
}
if ((cs = get_regex_charset(flags)) != REGEX_DEPENDS_CHARSET) {
if (!set++ && lead) {
Perl_re_printf( aTHX_ "%s", lead);
}
switch (cs) {
case REGEX_UNICODE_CHARSET:
Perl_re_printf( aTHX_ "UNICODE");
break;
case REGEX_LOCALE_CHARSET:
Perl_re_printf( aTHX_ "LOCALE");
break;
case REGEX_ASCII_RESTRICTED_CHARSET:
Perl_re_printf( aTHX_ "ASCII-RESTRICTED");
break;
case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
Perl_re_printf( aTHX_ "ASCII-MORE_RESTRICTED");
break;
default:
Perl_re_printf( aTHX_ "UNKNOWN CHARACTER SET");
break;
}
}
if (lead) {
if (set)
Perl_re_printf( aTHX_ "\n");
else
Perl_re_printf( aTHX_ "%s[none-set]\n", lead);
}
}
#endif
void
Perl_regdump(pTHX_ const regexp *r)
{
#ifdef DEBUGGING
int i;
SV * const sv = sv_newmortal();
SV *dsv= sv_newmortal();
RXi_GET_DECL(r, ri);
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REGDUMP;
(void)dumpuntil(r, ri->program, ri->program + 1, NULL, NULL, sv, 0, 0);
/* Header fields of interest. */
for (i = 0; i < 2; i++) {
if (r->substrs->data[i].substr) {
RE_PV_QUOTED_DECL(s, 0, dsv,
SvPVX_const(r->substrs->data[i].substr),
RE_SV_DUMPLEN(r->substrs->data[i].substr),
PL_dump_re_max_len);
Perl_re_printf( aTHX_
"%s %s%s at %" IVdf "..%" UVuf " ",
i ? "floating" : "anchored",
s,
RE_SV_TAIL(r->substrs->data[i].substr),
(IV)r->substrs->data[i].min_offset,
(UV)r->substrs->data[i].max_offset);
}
else if (r->substrs->data[i].utf8_substr) {
RE_PV_QUOTED_DECL(s, 1, dsv,
SvPVX_const(r->substrs->data[i].utf8_substr),
RE_SV_DUMPLEN(r->substrs->data[i].utf8_substr),
30);
Perl_re_printf( aTHX_
"%s utf8 %s%s at %" IVdf "..%" UVuf " ",
i ? "floating" : "anchored",
s,
RE_SV_TAIL(r->substrs->data[i].utf8_substr),
(IV)r->substrs->data[i].min_offset,
(UV)r->substrs->data[i].max_offset);
}
}
if (r->check_substr || r->check_utf8)
Perl_re_printf( aTHX_
(const char *)
( r->check_substr == r->substrs->data[1].substr
&& r->check_utf8 == r->substrs->data[1].utf8_substr
? "(checking floating" : "(checking anchored"));
if (r->intflags & PREGf_NOSCAN)
Perl_re_printf( aTHX_ " noscan");
if (r->extflags & RXf_CHECK_ALL)
Perl_re_printf( aTHX_ " isall");
if (r->check_substr || r->check_utf8)
Perl_re_printf( aTHX_ ") ");
if (ri->regstclass) {
regprop(r, sv, ri->regstclass, NULL, NULL);
Perl_re_printf( aTHX_ "stclass %s ", SvPVX_const(sv));
}
if (r->intflags & PREGf_ANCH) {
Perl_re_printf( aTHX_ "anchored");
if (r->intflags & PREGf_ANCH_MBOL)
Perl_re_printf( aTHX_ "(MBOL)");
if (r->intflags & PREGf_ANCH_SBOL)
Perl_re_printf( aTHX_ "(SBOL)");
if (r->intflags & PREGf_ANCH_GPOS)
Perl_re_printf( aTHX_ "(GPOS)");
Perl_re_printf( aTHX_ " ");
}
if (r->intflags & PREGf_GPOS_SEEN)
Perl_re_printf( aTHX_ "GPOS:%" UVuf " ", (UV)r->gofs);
if (r->intflags & PREGf_SKIP)
Perl_re_printf( aTHX_ "plus ");
if (r->intflags & PREGf_IMPLICIT)
Perl_re_printf( aTHX_ "implicit ");
Perl_re_printf( aTHX_ "minlen %" IVdf " ", (IV)r->minlen);
if (r->extflags & RXf_EVAL_SEEN)
Perl_re_printf( aTHX_ "with eval ");
Perl_re_printf( aTHX_ "\n");
DEBUG_FLAGS_r({
regdump_extflags("r->extflags: ", r->extflags);
regdump_intflags("r->intflags: ", r->intflags);
});
#else
PERL_ARGS_ASSERT_REGDUMP;
PERL_UNUSED_CONTEXT;
PERL_UNUSED_ARG(r);
#endif /* DEBUGGING */
}
/* Should be synchronized with ANYOF_ #defines in regcomp.h */
#ifdef DEBUGGING
# if _CC_WORDCHAR != 0 || _CC_DIGIT != 1 || _CC_ALPHA != 2 \
|| _CC_LOWER != 3 || _CC_UPPER != 4 || _CC_PUNCT != 5 \
|| _CC_PRINT != 6 || _CC_ALPHANUMERIC != 7 || _CC_GRAPH != 8 \
|| _CC_CASED != 9 || _CC_SPACE != 10 || _CC_BLANK != 11 \
|| _CC_XDIGIT != 12 || _CC_CNTRL != 13 || _CC_ASCII != 14 \
|| _CC_VERTSPACE != 15
# error Need to adjust order of anyofs[]
# endif
static const char * const anyofs[] = {
"\\w",
"\\W",
"\\d",
"\\D",
"[:alpha:]",
"[:^alpha:]",
"[:lower:]",
"[:^lower:]",
"[:upper:]",
"[:^upper:]",
"[:punct:]",
"[:^punct:]",
"[:print:]",
"[:^print:]",
"[:alnum:]",
"[:^alnum:]",
"[:graph:]",
"[:^graph:]",
"[:cased:]",
"[:^cased:]",
"\\s",
"\\S",
"[:blank:]",
"[:^blank:]",
"[:xdigit:]",
"[:^xdigit:]",
"[:cntrl:]",
"[:^cntrl:]",
"[:ascii:]",
"[:^ascii:]",
"\\v",
"\\V"
};
#endif
/*
- regprop - printable representation of opcode, with run time support
*/
void
Perl_regprop(pTHX_ const regexp *prog, SV *sv, const regnode *o, const regmatch_info *reginfo, const RExC_state_t *pRExC_state)
{
#ifdef DEBUGGING
dVAR;
int k;
RXi_GET_DECL(prog, progi);
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REGPROP;
SvPVCLEAR(sv);
if (OP(o) > REGNODE_MAX) /* regnode.type is unsigned */
/* It would be nice to FAIL() here, but this may be called from
regexec.c, and it would be hard to supply pRExC_state. */
Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d",
(int)OP(o), (int)REGNODE_MAX);
sv_catpv(sv, PL_reg_name[OP(o)]); /* Take off const! */
k = PL_regkind[OP(o)];
if (k == EXACT) {
sv_catpvs(sv, " ");
/* Using is_utf8_string() (via PERL_PV_UNI_DETECT)
* is a crude hack but it may be the best for now since
* we have no flag "this EXACTish node was UTF-8"
* --jhi */
pv_pretty(sv, STRING(o), STR_LEN(o), PL_dump_re_max_len,
PL_colors[0], PL_colors[1],
PERL_PV_ESCAPE_UNI_DETECT |
PERL_PV_ESCAPE_NONASCII |
PERL_PV_PRETTY_ELLIPSES |
PERL_PV_PRETTY_LTGT |
PERL_PV_PRETTY_NOCLEAR
);
} else if (k == TRIE) {
/* print the details of the trie in dumpuntil instead, as
* progi->data isn't available here */
const char op = OP(o);
const U32 n = ARG(o);
const reg_ac_data * const ac = IS_TRIE_AC(op) ?
(reg_ac_data *)progi->data->data[n] :
NULL;
const reg_trie_data * const trie
= (reg_trie_data*)progi->data->data[!IS_TRIE_AC(op) ? n : ac->trie];
Perl_sv_catpvf(aTHX_ sv, "-%s", PL_reg_name[o->flags]);
DEBUG_TRIE_COMPILE_r({
if (trie->jump)
sv_catpvs(sv, "(JUMP)");
Perl_sv_catpvf(aTHX_ sv,
"<S:%" UVuf "/%" IVdf " W:%" UVuf " L:%" UVuf "/%" UVuf " C:%" UVuf "/%" UVuf ">",
(UV)trie->startstate,
(IV)trie->statecount-1, /* -1 because of the unused 0 element */
(UV)trie->wordcount,
(UV)trie->minlen,
(UV)trie->maxlen,
(UV)TRIE_CHARCOUNT(trie),
(UV)trie->uniquecharcount
);
});
if ( IS_ANYOF_TRIE(op) || trie->bitmap ) {
sv_catpvs(sv, "[");
(void) put_charclass_bitmap_innards(sv,
((IS_ANYOF_TRIE(op))
? ANYOF_BITMAP(o)
: TRIE_BITMAP(trie)),
NULL,
NULL,
NULL,
FALSE
);
sv_catpvs(sv, "]");
}
} else if (k == CURLY) {
U32 lo = ARG1(o), hi = ARG2(o);
if (OP(o) == CURLYM || OP(o) == CURLYN || OP(o) == CURLYX)
Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
Perl_sv_catpvf(aTHX_ sv, "{%u,", (unsigned) lo);
if (hi == REG_INFTY)
sv_catpvs(sv, "INFTY");
else
Perl_sv_catpvf(aTHX_ sv, "%u", (unsigned) hi);
sv_catpvs(sv, "}");
}
else if (k == WHILEM && o->flags) /* Ordinal/of */
Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
else if (k == REF || k == OPEN || k == CLOSE
|| k == GROUPP || OP(o)==ACCEPT)
{
AV *name_list= NULL;
U32 parno= OP(o) == ACCEPT ? (U32)ARG2L(o) : ARG(o);
Perl_sv_catpvf(aTHX_ sv, "%" UVuf, (UV)parno); /* Parenth number */
if ( RXp_PAREN_NAMES(prog) ) {
name_list= MUTABLE_AV(progi->data->data[progi->name_list_idx]);
} else if ( pRExC_state ) {
name_list= RExC_paren_name_list;
}
if (name_list) {
if ( k != REF || (OP(o) < NREF)) {
SV **name= av_fetch(name_list, parno, 0 );
if (name)
Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
}
else {
SV *sv_dat= MUTABLE_SV(progi->data->data[ parno ]);
I32 *nums=(I32*)SvPVX(sv_dat);
SV **name= av_fetch(name_list, nums[0], 0 );
I32 n;
if (name) {
for ( n=0; n<SvIVX(sv_dat); n++ ) {
Perl_sv_catpvf(aTHX_ sv, "%s%" IVdf,
(n ? "," : ""), (IV)nums[n]);
}
Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
}
}
}
if ( k == REF && reginfo) {
U32 n = ARG(o); /* which paren pair */
I32 ln = prog->offs[n].start;
if (prog->lastparen < n || ln == -1 || prog->offs[n].end == -1)
Perl_sv_catpvf(aTHX_ sv, ": FAIL");
else if (ln == prog->offs[n].end)
Perl_sv_catpvf(aTHX_ sv, ": ACCEPT - EMPTY STRING");
else {
const char *s = reginfo->strbeg + ln;
Perl_sv_catpvf(aTHX_ sv, ": ");
Perl_pv_pretty( aTHX_ sv, s, prog->offs[n].end - prog->offs[n].start, 32, 0, 0,
PERL_PV_ESCAPE_UNI_DETECT|PERL_PV_PRETTY_NOCLEAR|PERL_PV_PRETTY_ELLIPSES|PERL_PV_PRETTY_QUOTE );
}
}
} else if (k == GOSUB) {
AV *name_list= NULL;
if ( RXp_PAREN_NAMES(prog) ) {
name_list= MUTABLE_AV(progi->data->data[progi->name_list_idx]);
} else if ( pRExC_state ) {
name_list= RExC_paren_name_list;
}
/* Paren and offset */
Perl_sv_catpvf(aTHX_ sv, "%d[%+d:%d]", (int)ARG(o),(int)ARG2L(o),
(int)((o + (int)ARG2L(o)) - progi->program) );
if (name_list) {
SV **name= av_fetch(name_list, ARG(o), 0 );
if (name)
Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
}
}
else if (k == LOGICAL)
/* 2: embedded, otherwise 1 */
Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags);
else if (k == ANYOF) {
const U8 flags = (OP(o) == ANYOFH) ? 0 : ANYOF_FLAGS(o);
bool do_sep = FALSE; /* Do we need to separate various components of
the output? */
/* Set if there is still an unresolved user-defined property */
SV *unresolved = NULL;
/* Things that are ignored except when the runtime locale is UTF-8 */
SV *only_utf8_locale_invlist = NULL;
/* Code points that don't fit in the bitmap */
SV *nonbitmap_invlist = NULL;
/* And things that aren't in the bitmap, but are small enough to be */
SV* bitmap_range_not_in_bitmap = NULL;
const bool inverted = flags & ANYOF_INVERT;
if (OP(o) == ANYOFL || OP(o) == ANYOFPOSIXL) {
if (ANYOFL_UTF8_LOCALE_REQD(flags)) {
sv_catpvs(sv, "{utf8-locale-reqd}");
}
if (flags & ANYOFL_FOLD) {
sv_catpvs(sv, "{i}");
}
}
/* If there is stuff outside the bitmap, get it */
if (ARG(o) != ANYOF_ONLY_HAS_BITMAP) {
(void) _get_regclass_nonbitmap_data(prog, o, FALSE,
&unresolved,
&only_utf8_locale_invlist,
&nonbitmap_invlist);
/* The non-bitmap data may contain stuff that could fit in the
* bitmap. This could come from a user-defined property being
* finally resolved when this call was done; or much more likely
* because there are matches that require UTF-8 to be valid, and so
* aren't in the bitmap. This is teased apart later */
_invlist_intersection(nonbitmap_invlist,
PL_InBitmap,
&bitmap_range_not_in_bitmap);
/* Leave just the things that don't fit into the bitmap */
_invlist_subtract(nonbitmap_invlist,
PL_InBitmap,
&nonbitmap_invlist);
}
/* Obey this flag to add all above-the-bitmap code points */
if (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
nonbitmap_invlist = _add_range_to_invlist(nonbitmap_invlist,
NUM_ANYOF_CODE_POINTS,
UV_MAX);
}
/* Ready to start outputting. First, the initial left bracket */
Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
if (OP(o) != ANYOFH) {
/* Then all the things that could fit in the bitmap */
do_sep = put_charclass_bitmap_innards(sv,
ANYOF_BITMAP(o),
bitmap_range_not_in_bitmap,
only_utf8_locale_invlist,
o,
/* Can't try inverting for a
* better display if there
* are things that haven't
* been resolved */
unresolved != NULL);
SvREFCNT_dec(bitmap_range_not_in_bitmap);
/* If there are user-defined properties which haven't been defined
* yet, output them. If the result is not to be inverted, it is
* clearest to output them in a separate [] from the bitmap range
* stuff. If the result is to be complemented, we have to show
* everything in one [], as the inversion applies to the whole
* thing. Use {braces} to separate them from anything in the
* bitmap and anything above the bitmap. */
if (unresolved) {
if (inverted) {
if (! do_sep) { /* If didn't output anything in the bitmap
*/
sv_catpvs(sv, "^");
}
sv_catpvs(sv, "{");
}
else if (do_sep) {
Perl_sv_catpvf(aTHX_ sv,"%s][%s", PL_colors[1],
PL_colors[0]);
}
sv_catsv(sv, unresolved);
if (inverted) {
sv_catpvs(sv, "}");
}
do_sep = ! inverted;
}
}
/* And, finally, add the above-the-bitmap stuff */
if (nonbitmap_invlist && _invlist_len(nonbitmap_invlist)) {
SV* contents;
/* See if truncation size is overridden */
const STRLEN dump_len = (PL_dump_re_max_len > 256)
? PL_dump_re_max_len
: 256;
/* This is output in a separate [] */
if (do_sep) {
Perl_sv_catpvf(aTHX_ sv,"%s][%s", PL_colors[1], PL_colors[0]);
}
/* And, for easy of understanding, it is shown in the
* uncomplemented form if possible. The one exception being if
* there are unresolved items, where the inversion has to be
* delayed until runtime */
if (inverted && ! unresolved) {
_invlist_invert(nonbitmap_invlist);
_invlist_subtract(nonbitmap_invlist, PL_InBitmap, &nonbitmap_invlist);
}
contents = invlist_contents(nonbitmap_invlist,
FALSE /* output suitable for catsv */
);
/* If the output is shorter than the permissible maximum, just do it. */
if (SvCUR(contents) <= dump_len) {
sv_catsv(sv, contents);
}
else {
const char * contents_string = SvPVX(contents);
STRLEN i = dump_len;
/* Otherwise, start at the permissible max and work back to the
* first break possibility */
while (i > 0 && contents_string[i] != ' ') {
i--;
}
if (i == 0) { /* Fail-safe. Use the max if we couldn't
find a legal break */
i = dump_len;
}
sv_catpvn(sv, contents_string, i);
sv_catpvs(sv, "...");
}
SvREFCNT_dec_NN(contents);
SvREFCNT_dec_NN(nonbitmap_invlist);
}
/* And finally the matching, closing ']' */
Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
if (OP(o) == ANYOFH && FLAGS(o) != 0) {
Perl_sv_catpvf(aTHX_ sv, " (First UTF-8 byte=\\x%02x)", FLAGS(o));
}
SvREFCNT_dec(unresolved);
}
else if (k == ANYOFM) {
SV * cp_list = get_ANYOFM_contents(o);
Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
if (OP(o) == NANYOFM) {
_invlist_invert(cp_list);
}
put_charclass_bitmap_innards(sv, NULL, cp_list, NULL, NULL, TRUE);
Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
SvREFCNT_dec(cp_list);
}
else if (k == POSIXD || k == NPOSIXD) {
U8 index = FLAGS(o) * 2;
if (index < C_ARRAY_LENGTH(anyofs)) {
if (*anyofs[index] != '[') {
sv_catpvs(sv, "[");
}
sv_catpv(sv, anyofs[index]);
if (*anyofs[index] != '[') {
sv_catpvs(sv, "]");
}
}
else {
Perl_sv_catpvf(aTHX_ sv, "[illegal type=%d])", index);
}
}
else if (k == BOUND || k == NBOUND) {
/* Must be synced with order of 'bound_type' in regcomp.h */
const char * const bounds[] = {
"", /* Traditional */
"{gcb}",
"{lb}",
"{sb}",
"{wb}"
};
assert(FLAGS(o) < C_ARRAY_LENGTH(bounds));
sv_catpv(sv, bounds[FLAGS(o)]);
}
else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH)) {
Perl_sv_catpvf(aTHX_ sv, "[%d", -(o->flags));
if (o->next_off) {
Perl_sv_catpvf(aTHX_ sv, "..-%d", o->flags - o->next_off);
}
Perl_sv_catpvf(aTHX_ sv, "]");
}
else if (OP(o) == SBOL)
Perl_sv_catpvf(aTHX_ sv, " /%s/", o->flags ? "\\A" : "^");
/* add on the verb argument if there is one */
if ( ( k == VERB || OP(o) == ACCEPT || OP(o) == OPFAIL ) && o->flags) {
if ( ARG(o) )
Perl_sv_catpvf(aTHX_ sv, ":%" SVf,
SVfARG((MUTABLE_SV(progi->data->data[ ARG( o ) ]))));
else
sv_catpvs(sv, ":NULL");
}
#else
PERL_UNUSED_CONTEXT;
PERL_UNUSED_ARG(sv);
PERL_UNUSED_ARG(o);
PERL_UNUSED_ARG(prog);
PERL_UNUSED_ARG(reginfo);
PERL_UNUSED_ARG(pRExC_state);
#endif /* DEBUGGING */
}
SV *
Perl_re_intuit_string(pTHX_ REGEXP * const r)
{ /* Assume that RE_INTUIT is set */
struct regexp *const prog = ReANY(r);
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_RE_INTUIT_STRING;
PERL_UNUSED_CONTEXT;
DEBUG_COMPILE_r(
{
const char * const s = SvPV_nolen_const(RX_UTF8(r)
? prog->check_utf8 : prog->check_substr);
if (!PL_colorset) reginitcolors();
Perl_re_printf( aTHX_
"%sUsing REx %ssubstr:%s \"%s%.60s%s%s\"\n",
PL_colors[4],
RX_UTF8(r) ? "utf8 " : "",
PL_colors[5], PL_colors[0],
s,
PL_colors[1],
(strlen(s) > PL_dump_re_max_len ? "..." : ""));
} );
/* use UTF8 check substring if regexp pattern itself is in UTF8 */
return RX_UTF8(r) ? prog->check_utf8 : prog->check_substr;
}
/*
pregfree()
handles refcounting and freeing the perl core regexp structure. When
it is necessary to actually free the structure the first thing it
does is call the 'free' method of the regexp_engine associated to
the regexp, allowing the handling of the void *pprivate; member
first. (This routine is not overridable by extensions, which is why
the extensions free is called first.)
See regdupe and regdupe_internal if you change anything here.
*/
#ifndef PERL_IN_XSUB_RE
void
Perl_pregfree(pTHX_ REGEXP *r)
{
SvREFCNT_dec(r);
}
void
Perl_pregfree2(pTHX_ REGEXP *rx)
{
struct regexp *const r = ReANY(rx);
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_PREGFREE2;
if (! r)
return;
if (r->mother_re) {
ReREFCNT_dec(r->mother_re);
} else {
CALLREGFREE_PVT(rx); /* free the private data */
SvREFCNT_dec(RXp_PAREN_NAMES(r));
}
if (r->substrs) {
int i;
for (i = 0; i < 2; i++) {
SvREFCNT_dec(r->substrs->data[i].substr);
SvREFCNT_dec(r->substrs->data[i].utf8_substr);
}
Safefree(r->substrs);
}
RX_MATCH_COPY_FREE(rx);
#ifdef PERL_ANY_COW
SvREFCNT_dec(r->saved_copy);
#endif
Safefree(r->offs);
SvREFCNT_dec(r->qr_anoncv);
if (r->recurse_locinput)
Safefree(r->recurse_locinput);
}
/* reg_temp_copy()
Copy ssv to dsv, both of which should of type SVt_REGEXP or SVt_PVLV,
except that dsv will be created if NULL.
This function is used in two main ways. First to implement
$r = qr/....; $s = $$r;
Secondly, it is used as a hacky workaround to the structural issue of
match results
being stored in the regexp structure which is in turn stored in
PL_curpm/PL_reg_curpm. The problem is that due to qr// the pattern
could be PL_curpm in multiple contexts, and could require multiple
result sets being associated with the pattern simultaneously, such
as when doing a recursive match with (??{$qr})
The solution is to make a lightweight copy of the regexp structure
when a qr// is returned from the code executed by (??{$qr}) this
lightweight copy doesn't actually own any of its data except for
the starp/end and the actual regexp structure itself.
*/
REGEXP *
Perl_reg_temp_copy(pTHX_ REGEXP *dsv, REGEXP *ssv)
{
struct regexp *drx;
struct regexp *const srx = ReANY(ssv);
const bool islv = dsv && SvTYPE(dsv) == SVt_PVLV;
PERL_ARGS_ASSERT_REG_TEMP_COPY;
if (!dsv)
dsv = (REGEXP*) newSV_type(SVt_REGEXP);
else {
assert(SvTYPE(dsv) == SVt_REGEXP || (SvTYPE(dsv) == SVt_PVLV));
/* our only valid caller, sv_setsv_flags(), should have done
* a SV_CHECK_THINKFIRST_COW_DROP() by now */
assert(!SvOOK(dsv));
assert(!SvIsCOW(dsv));
assert(!SvROK(dsv));
if (SvPVX_const(dsv)) {
if (SvLEN(dsv))
Safefree(SvPVX(dsv));
SvPVX(dsv) = NULL;
}
SvLEN_set(dsv, 0);
SvCUR_set(dsv, 0);
SvOK_off((SV *)dsv);
if (islv) {
/* For PVLVs, the head (sv_any) points to an XPVLV, while
* the LV's xpvlenu_rx will point to a regexp body, which
* we allocate here */
REGEXP *temp = (REGEXP *)newSV_type(SVt_REGEXP);
assert(!SvPVX(dsv));
((XPV*)SvANY(dsv))->xpv_len_u.xpvlenu_rx = temp->sv_any;
temp->sv_any = NULL;
SvFLAGS(temp) = (SvFLAGS(temp) & ~SVTYPEMASK) | SVt_NULL;
SvREFCNT_dec_NN(temp);
/* SvCUR still resides in the xpvlv struct, so the regexp copy-
ing below will not set it. */
SvCUR_set(dsv, SvCUR(ssv));
}
}
/* This ensures that SvTHINKFIRST(sv) is true, and hence that
sv_force_normal(sv) is called. */
SvFAKE_on(dsv);
drx = ReANY(dsv);
SvFLAGS(dsv) |= SvFLAGS(ssv) & (SVf_POK|SVp_POK|SVf_UTF8);
SvPV_set(dsv, RX_WRAPPED(ssv));
/* We share the same string buffer as the original regexp, on which we
hold a reference count, incremented when mother_re is set below.
The string pointer is copied here, being part of the regexp struct.
*/
memcpy(&(drx->xpv_cur), &(srx->xpv_cur),
sizeof(regexp) - STRUCT_OFFSET(regexp, xpv_cur));
if (!islv)
SvLEN_set(dsv, 0);
if (srx->offs) {
const I32 npar = srx->nparens+1;
Newx(drx->offs, npar, regexp_paren_pair);
Copy(srx->offs, drx->offs, npar, regexp_paren_pair);
}
if (srx->substrs) {
int i;
Newx(drx->substrs, 1, struct reg_substr_data);
StructCopy(srx->substrs, drx->substrs, struct reg_substr_data);
for (i = 0; i < 2; i++) {
SvREFCNT_inc_void(drx->substrs->data[i].substr);
SvREFCNT_inc_void(drx->substrs->data[i].utf8_substr);
}
/* check_substr and check_utf8, if non-NULL, point to either their
anchored or float namesakes, and don't hold a second reference. */
}
RX_MATCH_COPIED_off(dsv);
#ifdef PERL_ANY_COW
drx->saved_copy = NULL;
#endif
drx->mother_re = ReREFCNT_inc(srx->mother_re ? srx->mother_re : ssv);
SvREFCNT_inc_void(drx->qr_anoncv);
if (srx->recurse_locinput)
Newx(drx->recurse_locinput, srx->nparens + 1, char *);
return dsv;
}
#endif
/* regfree_internal()
Free the private data in a regexp. This is overloadable by
extensions. Perl takes care of the regexp structure in pregfree(),
this covers the *pprivate pointer which technically perl doesn't
know about, however of course we have to handle the
regexp_internal structure when no extension is in use.
Note this is called before freeing anything in the regexp
structure.
*/
void
Perl_regfree_internal(pTHX_ REGEXP * const rx)
{
struct regexp *const r = ReANY(rx);
RXi_GET_DECL(r, ri);
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REGFREE_INTERNAL;
if (! ri) {
return;
}
DEBUG_COMPILE_r({
if (!PL_colorset)
reginitcolors();
{
SV *dsv= sv_newmortal();
RE_PV_QUOTED_DECL(s, RX_UTF8(rx),
dsv, RX_PRECOMP(rx), RX_PRELEN(rx), PL_dump_re_max_len);
Perl_re_printf( aTHX_ "%sFreeing REx:%s %s\n",
PL_colors[4], PL_colors[5], s);
}
});
#ifdef RE_TRACK_PATTERN_OFFSETS
if (ri->u.offsets)
Safefree(ri->u.offsets); /* 20010421 MJD */
#endif
if (ri->code_blocks)
S_free_codeblocks(aTHX_ ri->code_blocks);
if (ri->data) {
int n = ri->data->count;
while (--n >= 0) {
/* If you add a ->what type here, update the comment in regcomp.h */
switch (ri->data->what[n]) {
case 'a':
case 'r':
case 's':
case 'S':
case 'u':
SvREFCNT_dec(MUTABLE_SV(ri->data->data[n]));
break;
case 'f':
Safefree(ri->data->data[n]);
break;
case 'l':
case 'L':
break;
case 'T':
{ /* Aho Corasick add-on structure for a trie node.
Used in stclass optimization only */
U32 refcount;
reg_ac_data *aho=(reg_ac_data*)ri->data->data[n];
#ifdef USE_ITHREADS
dVAR;
#endif
OP_REFCNT_LOCK;
refcount = --aho->refcount;
OP_REFCNT_UNLOCK;
if ( !refcount ) {
PerlMemShared_free(aho->states);
PerlMemShared_free(aho->fail);
/* do this last!!!! */
PerlMemShared_free(ri->data->data[n]);
/* we should only ever get called once, so
* assert as much, and also guard the free
* which /might/ happen twice. At the least
* it will make code anlyzers happy and it
* doesn't cost much. - Yves */
assert(ri->regstclass);
if (ri->regstclass) {
PerlMemShared_free(ri->regstclass);
ri->regstclass = 0;
}
}
}
break;
case 't':
{
/* trie structure. */
U32 refcount;
reg_trie_data *trie=(reg_trie_data*)ri->data->data[n];
#ifdef USE_ITHREADS
dVAR;
#endif
OP_REFCNT_LOCK;
refcount = --trie->refcount;
OP_REFCNT_UNLOCK;
if ( !refcount ) {
PerlMemShared_free(trie->charmap);
PerlMemShared_free(trie->states);
PerlMemShared_free(trie->trans);
if (trie->bitmap)
PerlMemShared_free(trie->bitmap);
if (trie->jump)
PerlMemShared_free(trie->jump);
PerlMemShared_free(trie->wordinfo);
/* do this last!!!! */
PerlMemShared_free(ri->data->data[n]);
}
}
break;
default:
Perl_croak(aTHX_ "panic: regfree data code '%c'",
ri->data->what[n]);
}
}
Safefree(ri->data->what);
Safefree(ri->data);
}
Safefree(ri);
}
#define av_dup_inc(s, t) MUTABLE_AV(sv_dup_inc((const SV *)s, t))
#define hv_dup_inc(s, t) MUTABLE_HV(sv_dup_inc((const SV *)s, t))
#define SAVEPVN(p, n) ((p) ? savepvn(p, n) : NULL)
/*
re_dup_guts - duplicate a regexp.
This routine is expected to clone a given regexp structure. It is only
compiled under USE_ITHREADS.
After all of the core data stored in struct regexp is duplicated
the regexp_engine.dupe method is used to copy any private data
stored in the *pprivate pointer. This allows extensions to handle
any duplication it needs to do.
See pregfree() and regfree_internal() if you change anything here.
*/
#if defined(USE_ITHREADS)
#ifndef PERL_IN_XSUB_RE
void
Perl_re_dup_guts(pTHX_ const REGEXP *sstr, REGEXP *dstr, CLONE_PARAMS *param)
{
dVAR;
I32 npar;
const struct regexp *r = ReANY(sstr);
struct regexp *ret = ReANY(dstr);
PERL_ARGS_ASSERT_RE_DUP_GUTS;
npar = r->nparens+1;
Newx(ret->offs, npar, regexp_paren_pair);
Copy(r->offs, ret->offs, npar, regexp_paren_pair);
if (ret->substrs) {
/* Do it this way to avoid reading from *r after the StructCopy().
That way, if any of the sv_dup_inc()s dislodge *r from the L1
cache, it doesn't matter. */
int i;
const bool anchored = r->check_substr
? r->check_substr == r->substrs->data[0].substr
: r->check_utf8 == r->substrs->data[0].utf8_substr;
Newx(ret->substrs, 1, struct reg_substr_data);
StructCopy(r->substrs, ret->substrs, struct reg_substr_data);
for (i = 0; i < 2; i++) {
ret->substrs->data[i].substr =
sv_dup_inc(ret->substrs->data[i].substr, param);
ret->substrs->data[i].utf8_substr =
sv_dup_inc(ret->substrs->data[i].utf8_substr, param);
}
/* check_substr and check_utf8, if non-NULL, point to either their
anchored or float namesakes, and don't hold a second reference. */
if (ret->check_substr) {
if (anchored) {
assert(r->check_utf8 == r->substrs->data[0].utf8_substr);
ret->check_substr = ret->substrs->data[0].substr;
ret->check_utf8 = ret->substrs->data[0].utf8_substr;
} else {
assert(r->check_substr == r->substrs->data[1].substr);
assert(r->check_utf8 == r->substrs->data[1].utf8_substr);
ret->check_substr = ret->substrs->data[1].substr;
ret->check_utf8 = ret->substrs->data[1].utf8_substr;
}
} else if (ret->check_utf8) {
if (anchored) {
ret->check_utf8 = ret->substrs->data[0].utf8_substr;
} else {
ret->check_utf8 = ret->substrs->data[1].utf8_substr;
}
}
}
RXp_PAREN_NAMES(ret) = hv_dup_inc(RXp_PAREN_NAMES(ret), param);
ret->qr_anoncv = MUTABLE_CV(sv_dup_inc((const SV *)ret->qr_anoncv, param));
if (r->recurse_locinput)
Newx(ret->recurse_locinput, r->nparens + 1, char *);
if (ret->pprivate)
RXi_SET(ret, CALLREGDUPE_PVT(dstr, param));
if (RX_MATCH_COPIED(dstr))
ret->subbeg = SAVEPVN(ret->subbeg, ret->sublen);
else
ret->subbeg = NULL;
#ifdef PERL_ANY_COW
ret->saved_copy = NULL;
#endif
/* Whether mother_re be set or no, we need to copy the string. We
cannot refrain from copying it when the storage points directly to
our mother regexp, because that's
1: a buffer in a different thread
2: something we no longer hold a reference on
so we need to copy it locally. */
RX_WRAPPED(dstr) = SAVEPVN(RX_WRAPPED_const(sstr), SvCUR(sstr)+1);
/* set malloced length to a non-zero value so it will be freed
* (otherwise in combination with SVf_FAKE it looks like an alien
* buffer). It doesn't have to be the actual malloced size, since it
* should never be grown */
SvLEN_set(dstr, SvCUR(sstr)+1);
ret->mother_re = NULL;
}
#endif /* PERL_IN_XSUB_RE */
/*
regdupe_internal()
This is the internal complement to regdupe() which is used to copy
the structure pointed to by the *pprivate pointer in the regexp.
This is the core version of the extension overridable cloning hook.
The regexp structure being duplicated will be copied by perl prior
to this and will be provided as the regexp *r argument, however
with the /old/ structures pprivate pointer value. Thus this routine
may override any copying normally done by perl.
It returns a pointer to the new regexp_internal structure.
*/
void *
Perl_regdupe_internal(pTHX_ REGEXP * const rx, CLONE_PARAMS *param)
{
dVAR;
struct regexp *const r = ReANY(rx);
regexp_internal *reti;
int len;
RXi_GET_DECL(r, ri);
PERL_ARGS_ASSERT_REGDUPE_INTERNAL;
len = ProgLen(ri);
Newxc(reti, sizeof(regexp_internal) + len*sizeof(regnode),
char, regexp_internal);
Copy(ri->program, reti->program, len+1, regnode);
if (ri->code_blocks) {
int n;
Newx(reti->code_blocks, 1, struct reg_code_blocks);
Newx(reti->code_blocks->cb, ri->code_blocks->count,
struct reg_code_block);
Copy(ri->code_blocks->cb, reti->code_blocks->cb,
ri->code_blocks->count, struct reg_code_block);
for (n = 0; n < ri->code_blocks->count; n++)
reti->code_blocks->cb[n].src_regex = (REGEXP*)
sv_dup_inc((SV*)(ri->code_blocks->cb[n].src_regex), param);
reti->code_blocks->count = ri->code_blocks->count;
reti->code_blocks->refcnt = 1;
}
else
reti->code_blocks = NULL;
reti->regstclass = NULL;
if (ri->data) {
struct reg_data *d;
const int count = ri->data->count;
int i;
Newxc(d, sizeof(struct reg_data) + count*sizeof(void *),
char, struct reg_data);
Newx(d->what, count, U8);
d->count = count;
for (i = 0; i < count; i++) {
d->what[i] = ri->data->what[i];
switch (d->what[i]) {
/* see also regcomp.h and regfree_internal() */
case 'a': /* actually an AV, but the dup function is identical.
values seem to be "plain sv's" generally. */
case 'r': /* a compiled regex (but still just another SV) */
case 's': /* an RV (currently only used for an RV to an AV by the ANYOF code)
this use case should go away, the code could have used
'a' instead - see S_set_ANYOF_arg() for array contents. */
case 'S': /* actually an SV, but the dup function is identical. */
case 'u': /* actually an HV, but the dup function is identical.
values are "plain sv's" */
d->data[i] = sv_dup_inc((const SV *)ri->data->data[i], param);
break;
case 'f':
/* Synthetic Start Class - "Fake" charclass we generate to optimize
* patterns which could start with several different things. Pre-TRIE
* this was more important than it is now, however this still helps
* in some places, for instance /x?a+/ might produce a SSC equivalent
* to [xa]. This is used by Perl_re_intuit_start() and S_find_byclass()
* in regexec.c
*/
/* This is cheating. */
Newx(d->data[i], 1, regnode_ssc);
StructCopy(ri->data->data[i], d->data[i], regnode_ssc);
reti->regstclass = (regnode*)d->data[i];
break;
case 'T':
/* AHO-CORASICK fail table */
/* Trie stclasses are readonly and can thus be shared
* without duplication. We free the stclass in pregfree
* when the corresponding reg_ac_data struct is freed.
*/
reti->regstclass= ri->regstclass;
/* FALLTHROUGH */
case 't':
/* TRIE transition table */
OP_REFCNT_LOCK;
((reg_trie_data*)ri->data->data[i])->refcount++;
OP_REFCNT_UNLOCK;
/* FALLTHROUGH */
case 'l': /* (?{...}) or (??{ ... }) code (cb->block) */
case 'L': /* same when RExC_pm_flags & PMf_HAS_CV and code
is not from another regexp */
d->data[i] = ri->data->data[i];
break;
default:
Perl_croak(aTHX_ "panic: re_dup_guts unknown data code '%c'",
ri->data->what[i]);
}
}
reti->data = d;
}
else
reti->data = NULL;
reti->name_list_idx = ri->name_list_idx;
#ifdef RE_TRACK_PATTERN_OFFSETS
if (ri->u.offsets) {
Newx(reti->u.offsets, 2*len+1, U32);
Copy(ri->u.offsets, reti->u.offsets, 2*len+1, U32);
}
#else
SetProgLen(reti, len);
#endif
return (void*)reti;
}
#endif /* USE_ITHREADS */
#ifndef PERL_IN_XSUB_RE
/*
- regnext - dig the "next" pointer out of a node
*/
regnode *
Perl_regnext(pTHX_ regnode *p)
{
I32 offset;
if (!p)
return(NULL);
if (OP(p) > REGNODE_MAX) { /* regnode.type is unsigned */
Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d",
(int)OP(p), (int)REGNODE_MAX);
}
offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
if (offset == 0)
return(NULL);
return(p+offset);
}
#endif
STATIC void
S_re_croak2(pTHX_ bool utf8, const char* pat1, const char* pat2,...)
{
va_list args;
STRLEN l1 = strlen(pat1);
STRLEN l2 = strlen(pat2);
char buf[512];
SV *msv;
const char *message;
PERL_ARGS_ASSERT_RE_CROAK2;
if (l1 > 510)
l1 = 510;
if (l1 + l2 > 510)
l2 = 510 - l1;
Copy(pat1, buf, l1 , char);
Copy(pat2, buf + l1, l2 , char);
buf[l1 + l2] = '\n';
buf[l1 + l2 + 1] = '\0';
va_start(args, pat2);
msv = vmess(buf, &args);
va_end(args);
message = SvPV_const(msv, l1);
if (l1 > 512)
l1 = 512;
Copy(message, buf, l1 , char);
/* l1-1 to avoid \n */
Perl_croak(aTHX_ "%" UTF8f, UTF8fARG(utf8, l1-1, buf));
}
/* XXX Here's a total kludge. But we need to re-enter for swash routines. */
#ifndef PERL_IN_XSUB_RE
void
Perl_save_re_context(pTHX)
{
I32 nparens = -1;
I32 i;
/* Save $1..$n (#18107: UTF-8 s/(\w+)/uc($1)/e); AMS 20021106. */
if (PL_curpm) {
const REGEXP * const rx = PM_GETRE(PL_curpm);
if (rx)
nparens = RX_NPARENS(rx);
}
/* RT #124109. This is a complete hack; in the SWASHNEW case we know
* that PL_curpm will be null, but that utf8.pm and the modules it
* loads will only use $1..$3.
* The t/porting/re_context.t test file checks this assumption.
*/
if (nparens == -1)
nparens = 3;
for (i = 1; i <= nparens; i++) {
char digits[TYPE_CHARS(long)];
const STRLEN len = my_snprintf(digits, sizeof(digits),
"%lu", (long)i);
GV *const *const gvp
= (GV**)hv_fetch(PL_defstash, digits, len, 0);
if (gvp) {
GV * const gv = *gvp;
if (SvTYPE(gv) == SVt_PVGV && GvSV(gv))
save_scalar(gv);
}
}
}
#endif
#ifdef DEBUGGING
STATIC void
S_put_code_point(pTHX_ SV *sv, UV c)
{
PERL_ARGS_ASSERT_PUT_CODE_POINT;
if (c > 255) {
Perl_sv_catpvf(aTHX_ sv, "\\x{%04" UVXf "}", c);
}
else if (isPRINT(c)) {
const char string = (char) c;
/* We use {phrase} as metanotation in the class, so also escape literal
* braces */
if (isBACKSLASHED_PUNCT(c) || c == '{' || c == '}')
sv_catpvs(sv, "\\");
sv_catpvn(sv, &string, 1);
}
else if (isMNEMONIC_CNTRL(c)) {
Perl_sv_catpvf(aTHX_ sv, "%s", cntrl_to_mnemonic((U8) c));
}
else {
Perl_sv_catpvf(aTHX_ sv, "\\x%02X", (U8) c);
}
}
#define MAX_PRINT_A MAX_PRINT_A_FOR_USE_ONLY_BY_REGCOMP_DOT_C
STATIC void
S_put_range(pTHX_ SV *sv, UV start, const UV end, const bool allow_literals)
{
/* Appends to 'sv' a displayable version of the range of code points from
* 'start' to 'end'. Mnemonics (like '\r') are used for the few controls
* that have them, when they occur at the beginning or end of the range.
* It uses hex to output the remaining code points, unless 'allow_literals'
* is true, in which case the printable ASCII ones are output as-is (though
* some of these will be escaped by put_code_point()).
*
* NOTE: This is designed only for printing ranges of code points that fit
* inside an ANYOF bitmap. Higher code points are simply suppressed
*/
const unsigned int min_range_count = 3;
assert(start <= end);
PERL_ARGS_ASSERT_PUT_RANGE;
while (start <= end) {
UV this_end;
const char * format;
if (end - start < min_range_count) {
/* Output chars individually when they occur in short ranges */
for (; start <= end; start++) {
put_code_point(sv, start);
}
break;
}
/* If permitted by the input options, and there is a possibility that
* this range contains a printable literal, look to see if there is
* one. */
if (allow_literals && start <= MAX_PRINT_A) {
/* If the character at the beginning of the range isn't an ASCII
* printable, effectively split the range into two parts:
* 1) the portion before the first such printable,
* 2) the rest
* and output them separately. */
if (! isPRINT_A(start)) {
UV temp_end = start + 1;
/* There is no point looking beyond the final possible
* printable, in MAX_PRINT_A */
UV max = MIN(end, MAX_PRINT_A);
while (temp_end <= max && ! isPRINT_A(temp_end)) {
temp_end++;
}
/* Here, temp_end points to one beyond the first printable if
* found, or to one beyond 'max' if not. If none found, make
* sure that we use the entire range */
if (temp_end > MAX_PRINT_A) {
temp_end = end + 1;
}
/* Output the first part of the split range: the part that
* doesn't have printables, with the parameter set to not look
* for literals (otherwise we would infinitely recurse) */
put_range(sv, start, temp_end - 1, FALSE);
/* The 2nd part of the range (if any) starts here. */
start = temp_end;
/* We do a continue, instead of dropping down, because even if
* the 2nd part is non-empty, it could be so short that we want
* to output it as individual characters, as tested for at the
* top of this loop. */
continue;
}
/* Here, 'start' is a printable ASCII. If it is an alphanumeric,
* output a sub-range of just the digits or letters, then process
* the remaining portion as usual. */
if (isALPHANUMERIC_A(start)) {
UV mask = (isDIGIT_A(start))
? _CC_DIGIT
: isUPPER_A(start)
? _CC_UPPER
: _CC_LOWER;
UV temp_end = start + 1;
/* Find the end of the sub-range that includes just the
* characters in the same class as the first character in it */
while (temp_end <= end && _generic_isCC_A(temp_end, mask)) {
temp_end++;
}
temp_end--;
/* For short ranges, don't duplicate the code above to output
* them; just call recursively */
if (temp_end - start < min_range_count) {
put_range(sv, start, temp_end, FALSE);
}
else { /* Output as a range */
put_code_point(sv, start);
sv_catpvs(sv, "-");
put_code_point(sv, temp_end);
}
start = temp_end + 1;
continue;
}
/* We output any other printables as individual characters */
if (isPUNCT_A(start) || isSPACE_A(start)) {
while (start <= end && (isPUNCT_A(start)
|| isSPACE_A(start)))
{
put_code_point(sv, start);
start++;
}
continue;
}
} /* End of looking for literals */
/* Here is not to output as a literal. Some control characters have
* mnemonic names. Split off any of those at the beginning and end of
* the range to print mnemonically. It isn't possible for many of
* these to be in a row, so this won't overwhelm with output */
if ( start <= end
&& (isMNEMONIC_CNTRL(start) || isMNEMONIC_CNTRL(end)))
{
while (isMNEMONIC_CNTRL(start) && start <= end) {
put_code_point(sv, start);
start++;
}
/* If this didn't take care of the whole range ... */
if (start <= end) {
/* Look backwards from the end to find the final non-mnemonic
* */
UV temp_end = end;
while (isMNEMONIC_CNTRL(temp_end)) {
temp_end--;
}
/* And separately output the interior range that doesn't start
* or end with mnemonics */
put_range(sv, start, temp_end, FALSE);
/* Then output the mnemonic trailing controls */
start = temp_end + 1;
while (start <= end) {
put_code_point(sv, start);
start++;
}
break;
}
}
/* As a final resort, output the range or subrange as hex. */
this_end = (end < NUM_ANYOF_CODE_POINTS)
? end
: NUM_ANYOF_CODE_POINTS - 1;
#if NUM_ANYOF_CODE_POINTS > 256
format = (this_end < 256)
? "\\x%02" UVXf "-\\x%02" UVXf
: "\\x{%04" UVXf "}-\\x{%04" UVXf "}";
#else
format = "\\x%02" UVXf "-\\x%02" UVXf;
#endif
GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral);
Perl_sv_catpvf(aTHX_ sv, format, start, this_end);
GCC_DIAG_RESTORE_STMT;
break;
}
}
STATIC void
S_put_charclass_bitmap_innards_invlist(pTHX_ SV *sv, SV* invlist)
{
/* Concatenate onto the PV in 'sv' a displayable form of the inversion list
* 'invlist' */
UV start, end;
bool allow_literals = TRUE;
PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS_INVLIST;
/* Generally, it is more readable if printable characters are output as
* literals, but if a range (nearly) spans all of them, it's best to output
* it as a single range. This code will use a single range if all but 2
* ASCII printables are in it */
invlist_iterinit(invlist);
while (invlist_iternext(invlist, &start, &end)) {
/* If the range starts beyond the final printable, it doesn't have any
* in it */
if (start > MAX_PRINT_A) {
break;
}
/* In both ASCII and EBCDIC, a SPACE is the lowest printable. To span
* all but two, the range must start and end no later than 2 from
* either end */
if (start < ' ' + 2 && end > MAX_PRINT_A - 2) {
if (end > MAX_PRINT_A) {
end = MAX_PRINT_A;
}
if (start < ' ') {
start = ' ';
}
if (end - start >= MAX_PRINT_A - ' ' - 2) {
allow_literals = FALSE;
}
break;
}
}
invlist_iterfinish(invlist);
/* Here we have figured things out. Output each range */
invlist_iterinit(invlist);
while (invlist_iternext(invlist, &start, &end)) {
if (start >= NUM_ANYOF_CODE_POINTS) {
break;
}
put_range(sv, start, end, allow_literals);
}
invlist_iterfinish(invlist);
return;
}
STATIC SV*
S_put_charclass_bitmap_innards_common(pTHX_
SV* invlist, /* The bitmap */
SV* posixes, /* Under /l, things like [:word:], \S */
SV* only_utf8, /* Under /d, matches iff the target is UTF-8 */
SV* not_utf8, /* /d, matches iff the target isn't UTF-8 */
SV* only_utf8_locale, /* Under /l, matches if the locale is UTF-8 */
const bool invert /* Is the result to be inverted? */
)
{
/* Create and return an SV containing a displayable version of the bitmap
* and associated information determined by the input parameters. If the
* output would have been only the inversion indicator '^', NULL is instead
* returned. */
dVAR;
SV * output;
PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS_COMMON;
if (invert) {
output = newSVpvs("^");
}
else {
output = newSVpvs("");
}
/* First, the code points in the bitmap that are unconditionally there */
put_charclass_bitmap_innards_invlist(output, invlist);
/* Traditionally, these have been placed after the main code points */
if (posixes) {
sv_catsv(output, posixes);
}
if (only_utf8 && _invlist_len(only_utf8)) {
Perl_sv_catpvf(aTHX_ output, "%s{utf8}%s", PL_colors[1], PL_colors[0]);
put_charclass_bitmap_innards_invlist(output, only_utf8);
}
if (not_utf8 && _invlist_len(not_utf8)) {
Perl_sv_catpvf(aTHX_ output, "%s{not utf8}%s", PL_colors[1], PL_colors[0]);
put_charclass_bitmap_innards_invlist(output, not_utf8);
}
if (only_utf8_locale && _invlist_len(only_utf8_locale)) {
Perl_sv_catpvf(aTHX_ output, "%s{utf8 locale}%s", PL_colors[1], PL_colors[0]);
put_charclass_bitmap_innards_invlist(output, only_utf8_locale);
/* This is the only list in this routine that can legally contain code
* points outside the bitmap range. The call just above to
* 'put_charclass_bitmap_innards_invlist' will simply suppress them, so
* output them here. There's about a half-dozen possible, and none in
* contiguous ranges longer than 2 */
if (invlist_highest(only_utf8_locale) >= NUM_ANYOF_CODE_POINTS) {
UV start, end;
SV* above_bitmap = NULL;
_invlist_subtract(only_utf8_locale, PL_InBitmap, &above_bitmap);
invlist_iterinit(above_bitmap);
while (invlist_iternext(above_bitmap, &start, &end)) {
UV i;
for (i = start; i <= end; i++) {
put_code_point(output, i);
}
}
invlist_iterfinish(above_bitmap);
SvREFCNT_dec_NN(above_bitmap);
}
}
if (invert && SvCUR(output) == 1) {
return NULL;
}
return output;
}
STATIC bool
S_put_charclass_bitmap_innards(pTHX_ SV *sv,
char *bitmap,
SV *nonbitmap_invlist,
SV *only_utf8_locale_invlist,
const regnode * const node,
const bool force_as_is_display)
{
/* Appends to 'sv' a displayable version of the innards of the bracketed
* character class defined by the other arguments:
* 'bitmap' points to the bitmap, or NULL if to ignore that.
* 'nonbitmap_invlist' is an inversion list of the code points that are in
* the bitmap range, but for some reason aren't in the bitmap; NULL if
* none. The reasons for this could be that they require some
* condition such as the target string being or not being in UTF-8
* (under /d), or because they came from a user-defined property that
* was not resolved at the time of the regex compilation (under /u)
* 'only_utf8_locale_invlist' is an inversion list of the code points that
* are valid only if the runtime locale is a UTF-8 one; NULL if none
* 'node' is the regex pattern ANYOF node. It is needed only when the
* above two parameters are not null, and is passed so that this
* routine can tease apart the various reasons for them.
* 'force_as_is_display' is TRUE if this routine should definitely NOT try
* to invert things to see if that leads to a cleaner display. If
* FALSE, this routine is free to use its judgment about doing this.
*
* It returns TRUE if there was actually something output. (It may be that
* the bitmap, etc is empty.)
*
* When called for outputting the bitmap of a non-ANYOF node, just pass the
* bitmap, with the succeeding parameters set to NULL, and the final one to
* FALSE.
*/
/* In general, it tries to display the 'cleanest' representation of the
* innards, choosing whether to display them inverted or not, regardless of
* whether the class itself is to be inverted. However, there are some
* cases where it can't try inverting, as what actually matches isn't known
* until runtime, and hence the inversion isn't either. */
dVAR;
bool inverting_allowed = ! force_as_is_display;
int i;
STRLEN orig_sv_cur = SvCUR(sv);
SV* invlist; /* Inversion list we accumulate of code points that
are unconditionally matched */
SV* only_utf8 = NULL; /* Under /d, list of matches iff the target is
UTF-8 */
SV* not_utf8 = NULL; /* /d, list of matches iff the target isn't UTF-8
*/
SV* posixes = NULL; /* Under /l, string of things like [:word:], \D */
SV* only_utf8_locale = NULL; /* Under /l, list of matches if the locale
is UTF-8 */
SV* as_is_display; /* The output string when we take the inputs
literally */
SV* inverted_display; /* The output string when we invert the inputs */
U8 flags = (node) ? ANYOF_FLAGS(node) : 0;
bool invert = cBOOL(flags & ANYOF_INVERT); /* Is the input to be inverted
to match? */
/* We are biased in favor of displaying things without them being inverted,
* as that is generally easier to understand */
const int bias = 5;
PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS;
/* Start off with whatever code points are passed in. (We clone, so we
* don't change the caller's list) */
if (nonbitmap_invlist) {
assert(invlist_highest(nonbitmap_invlist) < NUM_ANYOF_CODE_POINTS);
invlist = invlist_clone(nonbitmap_invlist, NULL);
}
else { /* Worst case size is every other code point is matched */
invlist = _new_invlist(NUM_ANYOF_CODE_POINTS / 2);
}
if (flags) {
if (OP(node) == ANYOFD) {
/* This flag indicates that the code points below 0x100 in the
* nonbitmap list are precisely the ones that match only when the
* target is UTF-8 (they should all be non-ASCII). */
if (flags & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)
{
_invlist_intersection(invlist, PL_UpperLatin1, &only_utf8);
_invlist_subtract(invlist, only_utf8, &invlist);
}
/* And this flag for matching all non-ASCII 0xFF and below */
if (flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
{
not_utf8 = invlist_clone(PL_UpperLatin1, NULL);
}
}
else if (OP(node) == ANYOFL || OP(node) == ANYOFPOSIXL) {
/* If either of these flags are set, what matches isn't
* determinable except during execution, so don't know enough here
* to invert */
if (flags & (ANYOFL_FOLD|ANYOF_MATCHES_POSIXL)) {
inverting_allowed = FALSE;
}
/* What the posix classes match also varies at runtime, so these
* will be output symbolically. */
if (ANYOF_POSIXL_TEST_ANY_SET(node)) {
int i;
posixes = newSVpvs("");
for (i = 0; i < ANYOF_POSIXL_MAX; i++) {
if (ANYOF_POSIXL_TEST(node, i)) {
sv_catpv(posixes, anyofs[i]);
}
}
}
}
}
/* Accumulate the bit map into the unconditional match list */
if (bitmap) {
for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) {
if (BITMAP_TEST(bitmap, i)) {
int start = i++;
for (;
i < NUM_ANYOF_CODE_POINTS && BITMAP_TEST(bitmap, i);
i++)
{ /* empty */ }
invlist = _add_range_to_invlist(invlist, start, i-1);
}
}
}
/* Make sure that the conditional match lists don't have anything in them
* that match unconditionally; otherwise the output is quite confusing.
* This could happen if the code that populates these misses some
* duplication. */
if (only_utf8) {
_invlist_subtract(only_utf8, invlist, &only_utf8);
}
if (not_utf8) {
_invlist_subtract(not_utf8, invlist, ¬_utf8);
}
if (only_utf8_locale_invlist) {
/* Since this list is passed in, we have to make a copy before
* modifying it */
only_utf8_locale = invlist_clone(only_utf8_locale_invlist, NULL);
_invlist_subtract(only_utf8_locale, invlist, &only_utf8_locale);
/* And, it can get really weird for us to try outputting an inverted
* form of this list when it has things above the bitmap, so don't even
* try */
if (invlist_highest(only_utf8_locale) >= NUM_ANYOF_CODE_POINTS) {
inverting_allowed = FALSE;
}
}
/* Calculate what the output would be if we take the input as-is */
as_is_display = put_charclass_bitmap_innards_common(invlist,
posixes,
only_utf8,
not_utf8,
only_utf8_locale,
invert);
/* If have to take the output as-is, just do that */
if (! inverting_allowed) {
if (as_is_display) {
sv_catsv(sv, as_is_display);
SvREFCNT_dec_NN(as_is_display);
}
}
else { /* But otherwise, create the output again on the inverted input, and
use whichever version is shorter */
int inverted_bias, as_is_bias;
/* We will apply our bias to whichever of the the results doesn't have
* the '^' */
if (invert) {
invert = FALSE;
as_is_bias = bias;
inverted_bias = 0;
}
else {
invert = TRUE;
as_is_bias = 0;
inverted_bias = bias;
}
/* Now invert each of the lists that contribute to the output,
* excluding from the result things outside the possible range */
/* For the unconditional inversion list, we have to add in all the
* conditional code points, so that when inverted, they will be gone
* from it */
_invlist_union(only_utf8, invlist, &invlist);
_invlist_union(not_utf8, invlist, &invlist);
_invlist_union(only_utf8_locale, invlist, &invlist);
_invlist_invert(invlist);
_invlist_intersection(invlist, PL_InBitmap, &invlist);
if (only_utf8) {
_invlist_invert(only_utf8);
_invlist_intersection(only_utf8, PL_UpperLatin1, &only_utf8);
}
else if (not_utf8) {
/* If a code point matches iff the target string is not in UTF-8,
* then complementing the result has it not match iff not in UTF-8,
* which is the same thing as matching iff it is UTF-8. */
only_utf8 = not_utf8;
not_utf8 = NULL;
}
if (only_utf8_locale) {
_invlist_invert(only_utf8_locale);
_invlist_intersection(only_utf8_locale,
PL_InBitmap,
&only_utf8_locale);
}
inverted_display = put_charclass_bitmap_innards_common(
invlist,
posixes,
only_utf8,
not_utf8,
only_utf8_locale, invert);
/* Use the shortest representation, taking into account our bias
* against showing it inverted */
if ( inverted_display
&& ( ! as_is_display
|| ( SvCUR(inverted_display) + inverted_bias
< SvCUR(as_is_display) + as_is_bias)))
{
sv_catsv(sv, inverted_display);
}
else if (as_is_display) {
sv_catsv(sv, as_is_display);
}
SvREFCNT_dec(as_is_display);
SvREFCNT_dec(inverted_display);
}
SvREFCNT_dec_NN(invlist);
SvREFCNT_dec(only_utf8);
SvREFCNT_dec(not_utf8);
SvREFCNT_dec(posixes);
SvREFCNT_dec(only_utf8_locale);
return SvCUR(sv) > orig_sv_cur;
}
#define CLEAR_OPTSTART \
if (optstart) STMT_START { \
DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ \
" (%" IVdf " nodes)\n", (IV)(node - optstart))); \
optstart=NULL; \
} STMT_END
#define DUMPUNTIL(b,e) \
CLEAR_OPTSTART; \
node=dumpuntil(r,start,(b),(e),last,sv,indent+1,depth+1);
STATIC const regnode *
S_dumpuntil(pTHX_ const regexp *r, const regnode *start, const regnode *node,
const regnode *last, const regnode *plast,
SV* sv, I32 indent, U32 depth)
{
U8 op = PSEUDO; /* Arbitrary non-END op. */
const regnode *next;
const regnode *optstart= NULL;
RXi_GET_DECL(r, ri);
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_DUMPUNTIL;
#ifdef DEBUG_DUMPUNTIL
Perl_re_printf( aTHX_ "--- %d : %d - %d - %d\n", indent, node-start,
last ? last-start : 0, plast ? plast-start : 0);
#endif
if (plast && plast < last)
last= plast;
while (PL_regkind[op] != END && (!last || node < last)) {
assert(node);
/* While that wasn't END last time... */
NODE_ALIGN(node);
op = OP(node);
if (op == CLOSE || op == SRCLOSE || op == WHILEM)
indent--;
next = regnext((regnode *)node);
/* Where, what. */
if (OP(node) == OPTIMIZED) {
if (!optstart && RE_DEBUG_FLAG(RE_DEBUG_COMPILE_OPTIMISE))
optstart = node;
else
goto after_print;
} else
CLEAR_OPTSTART;
regprop(r, sv, node, NULL, NULL);
Perl_re_printf( aTHX_ "%4" IVdf ":%*s%s", (IV)(node - start),
(int)(2*indent + 1), "", SvPVX_const(sv));
if (OP(node) != OPTIMIZED) {
if (next == NULL) /* Next ptr. */
Perl_re_printf( aTHX_ " (0)");
else if (PL_regkind[(U8)op] == BRANCH
&& PL_regkind[OP(next)] != BRANCH )
Perl_re_printf( aTHX_ " (FAIL)");
else
Perl_re_printf( aTHX_ " (%" IVdf ")", (IV)(next - start));
Perl_re_printf( aTHX_ "\n");
}
after_print:
if (PL_regkind[(U8)op] == BRANCHJ) {
assert(next);
{
const regnode *nnode = (OP(next) == LONGJMP
? regnext((regnode *)next)
: next);
if (last && nnode > last)
nnode = last;
DUMPUNTIL(NEXTOPER(NEXTOPER(node)), nnode);
}
}
else if (PL_regkind[(U8)op] == BRANCH) {
assert(next);
DUMPUNTIL(NEXTOPER(node), next);
}
else if ( PL_regkind[(U8)op] == TRIE ) {
const regnode *this_trie = node;
const char op = OP(node);
const U32 n = ARG(node);
const reg_ac_data * const ac = op>=AHOCORASICK ?
(reg_ac_data *)ri->data->data[n] :
NULL;
const reg_trie_data * const trie =
(reg_trie_data*)ri->data->data[op<AHOCORASICK ? n : ac->trie];
#ifdef DEBUGGING
AV *const trie_words
= MUTABLE_AV(ri->data->data[n + TRIE_WORDS_OFFSET]);
#endif
const regnode *nextbranch= NULL;
I32 word_idx;
SvPVCLEAR(sv);
for (word_idx= 0; word_idx < (I32)trie->wordcount; word_idx++) {
SV ** const elem_ptr = av_fetch(trie_words, word_idx, 0);
Perl_re_indentf( aTHX_ "%s ",
indent+3,
elem_ptr
? pv_pretty(sv, SvPV_nolen_const(*elem_ptr),
SvCUR(*elem_ptr), PL_dump_re_max_len,
PL_colors[0], PL_colors[1],
(SvUTF8(*elem_ptr)
? PERL_PV_ESCAPE_UNI
: 0)
| PERL_PV_PRETTY_ELLIPSES
| PERL_PV_PRETTY_LTGT
)
: "???"
);
if (trie->jump) {
U16 dist= trie->jump[word_idx+1];
Perl_re_printf( aTHX_ "(%" UVuf ")\n",
(UV)((dist ? this_trie + dist : next) - start));
if (dist) {
if (!nextbranch)
nextbranch= this_trie + trie->jump[0];
DUMPUNTIL(this_trie + dist, nextbranch);
}
if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
nextbranch= regnext((regnode *)nextbranch);
} else {
Perl_re_printf( aTHX_ "\n");
}
}
if (last && next > last)
node= last;
else
node= next;
}
else if ( op == CURLY ) { /* "next" might be very big: optimizer */
DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS,
NEXTOPER(node) + EXTRA_STEP_2ARGS + 1);
}
else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
assert(next);
DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS, next);
}
else if ( op == PLUS || op == STAR) {
DUMPUNTIL(NEXTOPER(node), NEXTOPER(node) + 1);
}
else if (PL_regkind[(U8)op] == EXACT) {
/* Literal string, where present. */
node += NODE_SZ_STR(node) - 1;
node = NEXTOPER(node);
}
else {
node = NEXTOPER(node);
node += regarglen[(U8)op];
}
if (op == CURLYX || op == OPEN || op == SROPEN)
indent++;
}
CLEAR_OPTSTART;
#ifdef DEBUG_DUMPUNTIL
Perl_re_printf( aTHX_ "--- %d\n", (int)indent);
#endif
return node;
}
#endif /* DEBUGGING */
#ifndef PERL_IN_XSUB_RE
#include "uni_keywords.h"
void
Perl_init_uniprops(pTHX)
{
dVAR;
PL_user_def_props = newHV();
#ifdef USE_ITHREADS
HvSHAREKEYS_off(PL_user_def_props);
PL_user_def_props_aTHX = aTHX;
#endif
/* Set up the inversion list global variables */
PL_XPosix_ptrs[_CC_ASCII] = _new_invlist_C_array(uni_prop_ptrs[UNI_ASCII]);
PL_XPosix_ptrs[_CC_ALPHANUMERIC] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXALNUM]);
PL_XPosix_ptrs[_CC_ALPHA] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXALPHA]);
PL_XPosix_ptrs[_CC_BLANK] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXBLANK]);
PL_XPosix_ptrs[_CC_CASED] = _new_invlist_C_array(uni_prop_ptrs[UNI_CASED]);
PL_XPosix_ptrs[_CC_CNTRL] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXCNTRL]);
PL_XPosix_ptrs[_CC_DIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXDIGIT]);
PL_XPosix_ptrs[_CC_GRAPH] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXGRAPH]);
PL_XPosix_ptrs[_CC_LOWER] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXLOWER]);
PL_XPosix_ptrs[_CC_PRINT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXPRINT]);
PL_XPosix_ptrs[_CC_PUNCT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXPUNCT]);
PL_XPosix_ptrs[_CC_SPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXSPACE]);
PL_XPosix_ptrs[_CC_UPPER] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXUPPER]);
PL_XPosix_ptrs[_CC_VERTSPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_VERTSPACE]);
PL_XPosix_ptrs[_CC_WORDCHAR] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXWORD]);
PL_XPosix_ptrs[_CC_XDIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXXDIGIT]);
PL_Posix_ptrs[_CC_ASCII] = _new_invlist_C_array(uni_prop_ptrs[UNI_ASCII]);
PL_Posix_ptrs[_CC_ALPHANUMERIC] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXALNUM]);
PL_Posix_ptrs[_CC_ALPHA] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXALPHA]);
PL_Posix_ptrs[_CC_BLANK] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXBLANK]);
PL_Posix_ptrs[_CC_CASED] = PL_Posix_ptrs[_CC_ALPHA];
PL_Posix_ptrs[_CC_CNTRL] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXCNTRL]);
PL_Posix_ptrs[_CC_DIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXDIGIT]);
PL_Posix_ptrs[_CC_GRAPH] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXGRAPH]);
PL_Posix_ptrs[_CC_LOWER] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXLOWER]);
PL_Posix_ptrs[_CC_PRINT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXPRINT]);
PL_Posix_ptrs[_CC_PUNCT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXPUNCT]);
PL_Posix_ptrs[_CC_SPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXSPACE]);
PL_Posix_ptrs[_CC_UPPER] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXUPPER]);
PL_Posix_ptrs[_CC_VERTSPACE] = NULL;
PL_Posix_ptrs[_CC_WORDCHAR] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXWORD]);
PL_Posix_ptrs[_CC_XDIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXXDIGIT]);
PL_GCB_invlist = _new_invlist_C_array(_Perl_GCB_invlist);
PL_SB_invlist = _new_invlist_C_array(_Perl_SB_invlist);
PL_WB_invlist = _new_invlist_C_array(_Perl_WB_invlist);
PL_LB_invlist = _new_invlist_C_array(_Perl_LB_invlist);
PL_SCX_invlist = _new_invlist_C_array(_Perl_SCX_invlist);
PL_AboveLatin1 = _new_invlist_C_array(AboveLatin1_invlist);
PL_Latin1 = _new_invlist_C_array(Latin1_invlist);
PL_UpperLatin1 = _new_invlist_C_array(UpperLatin1_invlist);
PL_Assigned_invlist = _new_invlist_C_array(uni_prop_ptrs[UNI_ASSIGNED]);
PL_utf8_perl_idstart = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_IDSTART]);
PL_utf8_perl_idcont = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_IDCONT]);
PL_utf8_charname_begin = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_CHARNAME_BEGIN]);
PL_utf8_charname_continue = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_CHARNAME_CONTINUE]);
PL_in_some_fold = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_ANY_FOLDS]);
PL_HasMultiCharFold = _new_invlist_C_array(uni_prop_ptrs[
UNI__PERL_FOLDS_TO_MULTI_CHAR]);
PL_InMultiCharFold = _new_invlist_C_array(uni_prop_ptrs[
UNI__PERL_IS_IN_MULTI_CHAR_FOLD]);
PL_NonFinalFold = _new_invlist_C_array(uni_prop_ptrs[
UNI__PERL_NON_FINAL_FOLDS]);
PL_utf8_toupper = _new_invlist_C_array(Uppercase_Mapping_invlist);
PL_utf8_tolower = _new_invlist_C_array(Lowercase_Mapping_invlist);
PL_utf8_totitle = _new_invlist_C_array(Titlecase_Mapping_invlist);
PL_utf8_tofold = _new_invlist_C_array(Case_Folding_invlist);
PL_utf8_tosimplefold = _new_invlist_C_array(Simple_Case_Folding_invlist);
PL_utf8_foldclosures = _new_invlist_C_array(_Perl_IVCF_invlist);
PL_utf8_mark = _new_invlist_C_array(uni_prop_ptrs[UNI_M]);
PL_CCC_non0_non230 = _new_invlist_C_array(_Perl_CCC_non0_non230_invlist);
PL_Private_Use = _new_invlist_C_array(uni_prop_ptrs[UNI_CO]);
#ifdef UNI_XIDC
/* The below are used only by deprecated functions. They could be removed */
PL_utf8_xidcont = _new_invlist_C_array(uni_prop_ptrs[UNI_XIDC]);
PL_utf8_idcont = _new_invlist_C_array(uni_prop_ptrs[UNI_IDC]);
PL_utf8_xidstart = _new_invlist_C_array(uni_prop_ptrs[UNI_XIDS]);
#endif
}
#if 0
This code was mainly added for backcompat to give a warning for non-portable
code points in user-defined properties. But experiments showed that the
warning in earlier perls were only omitted on overflow, which should be an
error, so there really isnt a backcompat issue, and actually adding the
warning when none was present before might cause breakage, for little gain. So
khw left this code in, but not enabled. Tests were never added.
embed.fnc entry:
Ei |const char *|get_extended_utf8_msg|const UV cp
PERL_STATIC_INLINE const char *
S_get_extended_utf8_msg(pTHX_ const UV cp)
{
U8 dummy[UTF8_MAXBYTES + 1];
HV *msgs;
SV **msg;
uvchr_to_utf8_flags_msgs(dummy, cp, UNICODE_WARN_PERL_EXTENDED,
&msgs);
msg = hv_fetchs(msgs, "text", 0);
assert(msg);
(void) sv_2mortal((SV *) msgs);
return SvPVX(*msg);
}
#endif
SV *
Perl_handle_user_defined_property(pTHX_
/* Parses the contents of a user-defined property definition; returning the
* expanded definition if possible. If so, the return is an inversion
* list.
*
* If there are subroutines that are part of the expansion and which aren't
* known at the time of the call to this function, this returns what
* parse_uniprop_string() returned for the first one encountered.
*
* If an error was found, NULL is returned, and 'msg' gets a suitable
* message appended to it. (Appending allows the back trace of how we got
* to the faulty definition to be displayed through nested calls of
* user-defined subs.)
*
* The caller IS responsible for freeing any returned SV.
*
* The syntax of the contents is pretty much described in perlunicode.pod,
* but we also allow comments on each line */
const char * name, /* Name of property */
const STRLEN name_len, /* The name's length in bytes */
const bool is_utf8, /* ? Is 'name' encoded in UTF-8 */
const bool to_fold, /* ? Is this under /i */
const bool runtime, /* ? Are we in compile- or run-time */
const bool deferrable, /* Is it ok for this property's full definition
to be deferred until later? */
SV* contents, /* The property's definition */
bool *user_defined_ptr, /* This will be set TRUE as we wouldn't be
getting called unless this is thought to be
a user-defined property */
SV * msg, /* Any error or warning msg(s) are appended to
this */
const STRLEN level) /* Recursion level of this call */
{
STRLEN len;
const char * string = SvPV_const(contents, len);
const char * const e = string + len;
const bool is_contents_utf8 = cBOOL(SvUTF8(contents));
const STRLEN msgs_length_on_entry = SvCUR(msg);
const char * s0 = string; /* Points to first byte in the current line
being parsed in 'string' */
const char overflow_msg[] = "Code point too large in \"";
SV* running_definition = NULL;
PERL_ARGS_ASSERT_HANDLE_USER_DEFINED_PROPERTY;
*user_defined_ptr = TRUE;
/* Look at each line */
while (s0 < e) {
const char * s; /* Current byte */
char op = '+'; /* Default operation is 'union' */
IV min = 0; /* range begin code point */
IV max = -1; /* and range end */
SV* this_definition;
/* Skip comment lines */
if (*s0 == '#') {
s0 = strchr(s0, '\n');
if (s0 == NULL) {
break;
}
s0++;
continue;
}
/* For backcompat, allow an empty first line */
if (*s0 == '\n') {
s0++;
continue;
}
/* First character in the line may optionally be the operation */
if ( *s0 == '+'
|| *s0 == '!'
|| *s0 == '-'
|| *s0 == '&')
{
op = *s0++;
}
/* If the line is one or two hex digits separated by blank space, its
* a range; otherwise it is either another user-defined property or an
* error */
s = s0;
if (! isXDIGIT(*s)) {
goto check_if_property;
}
do { /* Each new hex digit will add 4 bits. */
if (min > ( (IV) MAX_LEGAL_CP >> 4)) {
s = strchr(s, '\n');
if (s == NULL) {
s = e;
}
if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
sv_catpv(msg, overflow_msg);
Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
UTF8fARG(is_contents_utf8, s - s0, s0));
sv_catpvs(msg, "\"");
goto return_failure;
}
/* Accumulate this digit into the value */
min = (min << 4) + READ_XDIGIT(s);
} while (isXDIGIT(*s));
while (isBLANK(*s)) { s++; }
/* We allow comments at the end of the line */
if (*s == '#') {
s = strchr(s, '\n');
if (s == NULL) {
s = e;
}
s++;
}
else if (s < e && *s != '\n') {
if (! isXDIGIT(*s)) {
goto check_if_property;
}
/* Look for the high point of the range */
max = 0;
do {
if (max > ( (IV) MAX_LEGAL_CP >> 4)) {
s = strchr(s, '\n');
if (s == NULL) {
s = e;
}
if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
sv_catpv(msg, overflow_msg);
Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
UTF8fARG(is_contents_utf8, s - s0, s0));
sv_catpvs(msg, "\"");
goto return_failure;
}
max = (max << 4) + READ_XDIGIT(s);
} while (isXDIGIT(*s));
while (isBLANK(*s)) { s++; }
if (*s == '#') {
s = strchr(s, '\n');
if (s == NULL) {
s = e;
}
}
else if (s < e && *s != '\n') {
goto check_if_property;
}
}
if (max == -1) { /* The line only had one entry */
max = min;
}
else if (max < min) {
if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
sv_catpvs(msg, "Illegal range in \"");
Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
UTF8fARG(is_contents_utf8, s - s0, s0));
sv_catpvs(msg, "\"");
goto return_failure;
}
#if 0 /* See explanation at definition above of get_extended_utf8_msg() */
if ( UNICODE_IS_PERL_EXTENDED(min)
|| UNICODE_IS_PERL_EXTENDED(max))
{
if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
/* If both code points are non-portable, warn only on the lower
* one. */
sv_catpv(msg, get_extended_utf8_msg(
(UNICODE_IS_PERL_EXTENDED(min))
? min : max));
sv_catpvs(msg, " in \"");
Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
UTF8fARG(is_contents_utf8, s - s0, s0));
sv_catpvs(msg, "\"");
}
#endif
/* Here, this line contains a legal range */
this_definition = sv_2mortal(_new_invlist(2));
this_definition = _add_range_to_invlist(this_definition, min, max);
goto calculate;
check_if_property:
/* Here it isn't a legal range line. See if it is a legal property
* line. First find the end of the meat of the line */
s = strpbrk(s, "#\n");
if (s == NULL) {
s = e;
}
/* Ignore trailing blanks in keeping with the requirements of
* parse_uniprop_string() */
s--;
while (s > s0 && isBLANK_A(*s)) {
s--;
}
s++;
this_definition = parse_uniprop_string(s0, s - s0,
is_utf8, to_fold, runtime,
deferrable,
user_defined_ptr, msg,
(name_len == 0)
? level /* Don't increase level
if input is empty */
: level + 1
);
if (this_definition == NULL) {
goto return_failure; /* 'msg' should have had the reason
appended to it by the above call */
}
if (! is_invlist(this_definition)) { /* Unknown at this time */
return newSVsv(this_definition);
}
if (*s != '\n') {
s = strchr(s, '\n');
if (s == NULL) {
s = e;
}
}
calculate:
switch (op) {
case '+':
_invlist_union(running_definition, this_definition,
&running_definition);
break;
case '-':
_invlist_subtract(running_definition, this_definition,
&running_definition);
break;
case '&':
_invlist_intersection(running_definition, this_definition,
&running_definition);
break;
case '!':
_invlist_union_complement_2nd(running_definition,
this_definition, &running_definition);
break;
default:
Perl_croak(aTHX_ "panic: %s: %d: Unexpected operation %d",
__FILE__, __LINE__, op);
break;
}
/* Position past the '\n' */
s0 = s + 1;
} /* End of loop through the lines of 'contents' */
/* Here, we processed all the lines in 'contents' without error. If we
* didn't add any warnings, simply return success */
if (msgs_length_on_entry == SvCUR(msg)) {
/* If the expansion was empty, the answer isn't nothing: its an empty
* inversion list */
if (running_definition == NULL) {
running_definition = _new_invlist(1);
}
return running_definition;
}
/* Otherwise, add some explanatory text, but we will return success */
goto return_msg;
return_failure:
running_definition = NULL;
return_msg:
if (name_len > 0) {
sv_catpvs(msg, " in expansion of ");
Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_utf8, name_len, name));
}
return running_definition;
}
/* As explained below, certain operations need to take place in the first
* thread created. These macros switch contexts */
#ifdef USE_ITHREADS
# define DECLARATION_FOR_GLOBAL_CONTEXT \
PerlInterpreter * save_aTHX = aTHX;
# define SWITCH_TO_GLOBAL_CONTEXT \
PERL_SET_CONTEXT((aTHX = PL_user_def_props_aTHX))
# define RESTORE_CONTEXT PERL_SET_CONTEXT((aTHX = save_aTHX));
# define CUR_CONTEXT aTHX
# define ORIGINAL_CONTEXT save_aTHX
#else
# define DECLARATION_FOR_GLOBAL_CONTEXT
# define SWITCH_TO_GLOBAL_CONTEXT NOOP
# define RESTORE_CONTEXT NOOP
# define CUR_CONTEXT NULL
# define ORIGINAL_CONTEXT NULL
#endif
STATIC void
S_delete_recursion_entry(pTHX_ void *key)
{
/* Deletes the entry used to detect recursion when expanding user-defined
* properties. This is a function so it can be set up to be called even if
* the program unexpectedly quits */
dVAR;
SV ** current_entry;
const STRLEN key_len = strlen((const char *) key);
DECLARATION_FOR_GLOBAL_CONTEXT;
SWITCH_TO_GLOBAL_CONTEXT;
/* If the entry is one of these types, it is a permanent entry, and not the
* one used to detect recursions. This function should delete only the
* recursion entry */
current_entry = hv_fetch(PL_user_def_props, (const char *) key, key_len, 0);
if ( current_entry
&& ! is_invlist(*current_entry)
&& ! SvPOK(*current_entry))
{
(void) hv_delete(PL_user_def_props, (const char *) key, key_len,
G_DISCARD);
}
RESTORE_CONTEXT;
}
STATIC SV *
S_get_fq_name(pTHX_
const char * const name, /* The first non-blank in the \p{}, \P{} */
const Size_t name_len, /* Its length in bytes, not including any trailing space */
const bool is_utf8, /* ? Is 'name' encoded in UTF-8 */
const bool has_colon_colon
)
{
/* Returns a mortal SV containing the fully qualified version of the input
* name */
SV * fq_name;
fq_name = newSVpvs_flags("", SVs_TEMP);
/* Use the current package if it wasn't included in our input */
if (! has_colon_colon) {
const HV * pkg = (IN_PERL_COMPILETIME)
? PL_curstash
: CopSTASH(PL_curcop);
const char* pkgname = HvNAME(pkg);
Perl_sv_catpvf(aTHX_ fq_name, "%" UTF8f,
UTF8fARG(is_utf8, strlen(pkgname), pkgname));
sv_catpvs(fq_name, "::");
}
Perl_sv_catpvf(aTHX_ fq_name, "%" UTF8f,
UTF8fARG(is_utf8, name_len, name));
return fq_name;
}
SV *
Perl_parse_uniprop_string(pTHX_
/* Parse the interior of a \p{}, \P{}. Returns its definition if knowable
* now. If so, the return is an inversion list.
*
* If the property is user-defined, it is a subroutine, which in turn
* may call other subroutines. This function will call the whole nest of
* them to get the definition they return; if some aren't known at the time
* of the call to this function, the fully qualified name of the highest
* level sub is returned. It is an error to call this function at runtime
* without every sub defined.
*
* If an error was found, NULL is returned, and 'msg' gets a suitable
* message appended to it. (Appending allows the back trace of how we got
* to the faulty definition to be displayed through nested calls of
* user-defined subs.)
*
* The caller should NOT try to free any returned inversion list.
*
* Other parameters will be set on return as described below */
const char * const name, /* The first non-blank in the \p{}, \P{} */
const Size_t name_len, /* Its length in bytes, not including any
trailing space */
const bool is_utf8, /* ? Is 'name' encoded in UTF-8 */
const bool to_fold, /* ? Is this under /i */
const bool runtime, /* TRUE if this is being called at run time */
const bool deferrable, /* TRUE if it's ok for the definition to not be
known at this call */
bool *user_defined_ptr, /* Upon return from this function it will be
set to TRUE if any component is a
user-defined property */
SV * msg, /* Any error or warning msg(s) are appended to
this */
const STRLEN level) /* Recursion level of this call */
{
dVAR;
char* lookup_name; /* normalized name for lookup in our tables */
unsigned lookup_len; /* Its length */
bool stricter = FALSE; /* Some properties have stricter name
normalization rules, which we decide upon
based on parsing */
/* nv= or numeric_value=, or possibly one of the cjk numeric properties
* (though it requires extra effort to download them from Unicode and
* compile perl to know about them) */
bool is_nv_type = FALSE;
unsigned int i, j = 0;
int equals_pos = -1; /* Where the '=' is found, or negative if none */
int slash_pos = -1; /* Where the '/' is found, or negative if none */
int table_index = 0; /* The entry number for this property in the table
of all Unicode property names */
bool starts_with_In_or_Is = FALSE; /* ? Does the name start with 'In' or
'Is' */
Size_t lookup_offset = 0; /* Used to ignore the first few characters of
the normalized name in certain situations */
Size_t non_pkg_begin = 0; /* Offset of first byte in 'name' that isn't
part of a package name */
bool could_be_user_defined = TRUE; /* ? Could this be a user-defined
property rather than a Unicode
one. */
SV * prop_definition = NULL; /* The returned definition of 'name' or NULL
if an error. If it is an inversion list,
it is the definition. Otherwise it is a
string containing the fully qualified sub
name of 'name' */
SV * fq_name = NULL; /* For user-defined properties, the fully
qualified name */
bool invert_return = FALSE; /* ? Do we need to complement the result before
returning it */
PERL_ARGS_ASSERT_PARSE_UNIPROP_STRING;
/* The input will be normalized into 'lookup_name' */
Newx(lookup_name, name_len, char);
SAVEFREEPV(lookup_name);
/* Parse the input. */
for (i = 0; i < name_len; i++) {
char cur = name[i];
/* Most of the characters in the input will be of this ilk, being parts
* of a name */
if (isIDCONT_A(cur)) {
/* Case differences are ignored. Our lookup routine assumes
* everything is lowercase, so normalize to that */
if (isUPPER_A(cur)) {
lookup_name[j++] = toLOWER_A(cur);
continue;
}
if (cur == '_') { /* Don't include these in the normalized name */
continue;
}
lookup_name[j++] = cur;
/* The first character in a user-defined name must be of this type.
* */
if (i - non_pkg_begin == 0 && ! isIDFIRST_A(cur)) {
could_be_user_defined = FALSE;
}
continue;
}
/* Here, the character is not something typically in a name, But these
* two types of characters (and the '_' above) can be freely ignored in
* most situations. Later it may turn out we shouldn't have ignored
* them, and we have to reparse, but we don't have enough information
* yet to make that decision */
if (cur == '-' || isSPACE_A(cur)) {
could_be_user_defined = FALSE;
continue;
}
/* An equals sign or single colon mark the end of the first part of
* the property name */
if ( cur == '='
|| (cur == ':' && (i >= name_len - 1 || name[i+1] != ':')))
{
lookup_name[j++] = '='; /* Treat the colon as an '=' */
equals_pos = j; /* Note where it occurred in the input */
could_be_user_defined = FALSE;
break;
}
/* Otherwise, this character is part of the name. */
lookup_name[j++] = cur;
/* Here it isn't a single colon, so if it is a colon, it must be a
* double colon */
if (cur == ':') {
/* A double colon should be a package qualifier. We note its
* position and continue. Note that one could have
* pkg1::pkg2::...::foo
* so that the position at the end of the loop will be just after
* the final qualifier */
i++;
non_pkg_begin = i + 1;
lookup_name[j++] = ':';
}
else { /* Only word chars (and '::') can be in a user-defined name */
could_be_user_defined = FALSE;
}
} /* End of parsing through the lhs of the property name (or all of it if
no rhs) */
#define STRLENs(s) (sizeof("" s "") - 1)
/* If there is a single package name 'utf8::', it is ambiguous. It could
* be for a user-defined property, or it could be a Unicode property, as
* all of them are considered to be for that package. For the purposes of
* parsing the rest of the property, strip it off */
if (non_pkg_begin == STRLENs("utf8::") && memBEGINPs(name, name_len, "utf8::")) {
lookup_name += STRLENs("utf8::");
j -= STRLENs("utf8::");
equals_pos -= STRLENs("utf8::");
}
/* Here, we are either done with the whole property name, if it was simple;
* or are positioned just after the '=' if it is compound. */
if (equals_pos >= 0) {
assert(! stricter); /* We shouldn't have set this yet */
/* Space immediately after the '=' is ignored */
i++;
for (; i < name_len; i++) {
if (! isSPACE_A(name[i])) {
break;
}
}
/* Most punctuation after the equals indicates a subpattern, like
* \p{foo=/bar/} */
if ( isPUNCT_A(name[i])
&& name[i] != '-'
&& name[i] != '+'
&& name[i] != '_'
&& name[i] != '{')
{
/* Find the property. The table includes the equals sign, so we
* use 'j' as-is */
table_index = match_uniprop((U8 *) lookup_name, j);
if (table_index) {
const char * const * prop_values
= UNI_prop_value_ptrs[table_index];
SV * subpattern;
Size_t subpattern_len;
REGEXP * subpattern_re;
char open = name[i++];
char close;
const char * pos_in_brackets;
bool escaped = 0;
/* A backslash means the real delimitter is the next character.
* */
if (open == '\\') {
open = name[i++];
escaped = 1;
}
/* This data structure is constructed so that the matching
* closing bracket is 3 past its matching opening. The second
* set of closing is so that if the opening is something like
* ']', the closing will be that as well. Something similar is
* done in toke.c */
pos_in_brackets = strchr("([<)]>)]>", open);
close = (pos_in_brackets) ? pos_in_brackets[3] : open;
if ( i >= name_len
|| name[name_len-1] != close
|| (escaped && name[name_len-2] != '\\'))
{
sv_catpvs(msg, "Unicode property wildcard not terminated");
goto append_name_to_msg;
}
Perl_ck_warner_d(aTHX_
packWARN(WARN_EXPERIMENTAL__UNIPROP_WILDCARDS),
"The Unicode property wildcards feature is experimental");
/* Now create and compile the wildcard subpattern. Use /iaa
* because nothing outside of ASCII will match, and it the
* property values should all match /i. Note that when the
* pattern fails to compile, our added text to the user's
* pattern will be displayed to the user, which is not so
* desirable. */
subpattern_len = name_len - i - 1 - escaped;
subpattern = Perl_newSVpvf(aTHX_ "(?iaa:%.*s)",
(unsigned) subpattern_len,
name + i);
subpattern = sv_2mortal(subpattern);
subpattern_re = re_compile(subpattern, 0);
assert(subpattern_re); /* Should have died if didn't compile
successfully */
/* For each legal property value, see if the supplied pattern
* matches it. */
while (*prop_values) {
const char * const entry = *prop_values;
const Size_t len = strlen(entry);
SV* entry_sv = newSVpvn_flags(entry, len, SVs_TEMP);
if (pregexec(subpattern_re,
(char *) entry,
(char *) entry + len,
(char *) entry, 0,
entry_sv,
0))
{ /* Here, matched. Add to the returned list */
Size_t total_len = j + len;
SV * sub_invlist = NULL;
char * this_string;
/* We know this is a legal \p{property=value}. Call
* the function to return the list of code points that
* match it */
Newxz(this_string, total_len + 1, char);
Copy(lookup_name, this_string, j, char);
my_strlcat(this_string, entry, total_len + 1);
SAVEFREEPV(this_string);
sub_invlist = parse_uniprop_string(this_string,
total_len,
is_utf8,
to_fold,
runtime,
deferrable,
user_defined_ptr,
msg,
level + 1);
_invlist_union(prop_definition, sub_invlist,
&prop_definition);
}
prop_values++; /* Next iteration, look at next propvalue */
} /* End of looking through property values; (the data
structure is terminated by a NULL ptr) */
SvREFCNT_dec_NN(subpattern_re);
if (prop_definition) {
return prop_definition;
}
sv_catpvs(msg, "No Unicode property value wildcard matches:");
goto append_name_to_msg;
}
/* Here's how khw thinks we should proceed to handle the properties
* not yet done: Bidi Mirroring Glyph
Bidi Paired Bracket
Case Folding (both full and simple)
Decomposition Mapping
Equivalent Unified Ideograph
Name
Name Alias
Lowercase Mapping (both full and simple)
NFKC Case Fold
Titlecase Mapping (both full and simple)
Uppercase Mapping (both full and simple)
* Move the part that looks at the property values into a perl
* script, like utf8_heavy.pl is done. This makes things somewhat
* easier, but most importantly, it avoids always adding all these
* strings to the memory usage when the feature is little-used.
*
* The property values would all be concatenated into a single
* string per property with each value on a separate line, and the
* code point it's for on alternating lines. Then we match the
* user's input pattern m//mg, without having to worry about their
* uses of '^' and '$'. Only the values that aren't the default
* would be in the strings. Code points would be in UTF-8. The
* search pattern that we would construct would look like
* (?: \n (code-point_re) \n (?aam: user-re ) \n )
* And so $1 would contain the code point that matched the user-re.
* For properties where the default is the code point itself, such
* as any of the case changing mappings, the string would otherwise
* consist of all Unicode code points in UTF-8 strung together.
* This would be impractical. So instead, examine their compiled
* pattern, looking at the ssc. If none, reject the pattern as an
* error. Otherwise run the pattern against every code point in
* the ssc. The ssc is kind of like tr18's 3.9 Possible Match Sets
* And it might be good to create an API to return the ssc.
*
* For the name properties, a new function could be created in
* charnames which essentially does the same thing as above,
* sharing Name.pl with the other charname functions. Don't know
* about loose name matching, or algorithmically determined names.
* Decomposition.pl similarly.
*
* It might be that a new pattern modifier would have to be
* created, like /t for resTricTed, which changed the behavior of
* some constructs in their subpattern, like \A. */
} /* End of is a wildcard subppattern */
/* Certain properties whose values are numeric need special handling.
* They may optionally be prefixed by 'is'. Ignore that prefix for the
* purposes of checking if this is one of those properties */
if (memBEGINPs(lookup_name, j, "is")) {
lookup_offset = 2;
}
/* Then check if it is one of these specially-handled properties. The
* possibilities are hard-coded because easier this way, and the list
* is unlikely to change.
*
* All numeric value type properties are of this ilk, and are also
* special in a different way later on. So find those first. There
* are several numeric value type properties in the Unihan DB (which is
* unlikely to be compiled with perl, but we handle it here in case it
* does get compiled). They all end with 'numeric'. The interiors
* aren't checked for the precise property. This would stop working if
* a cjk property were to be created that ended with 'numeric' and
* wasn't a numeric type */
is_nv_type = memEQs(lookup_name + lookup_offset,
j - 1 - lookup_offset, "numericvalue")
|| memEQs(lookup_name + lookup_offset,
j - 1 - lookup_offset, "nv")
|| ( memENDPs(lookup_name + lookup_offset,
j - 1 - lookup_offset, "numeric")
&& ( memBEGINPs(lookup_name + lookup_offset,
j - 1 - lookup_offset, "cjk")
|| memBEGINPs(lookup_name + lookup_offset,
j - 1 - lookup_offset, "k")));
if ( is_nv_type
|| memEQs(lookup_name + lookup_offset,
j - 1 - lookup_offset, "canonicalcombiningclass")
|| memEQs(lookup_name + lookup_offset,
j - 1 - lookup_offset, "ccc")
|| memEQs(lookup_name + lookup_offset,
j - 1 - lookup_offset, "age")
|| memEQs(lookup_name + lookup_offset,
j - 1 - lookup_offset, "in")
|| memEQs(lookup_name + lookup_offset,
j - 1 - lookup_offset, "presentin"))
{
unsigned int k;
/* Since the stuff after the '=' is a number, we can't throw away
* '-' willy-nilly, as those could be a minus sign. Other stricter
* rules also apply. However, these properties all can have the
* rhs not be a number, in which case they contain at least one
* alphabetic. In those cases, the stricter rules don't apply.
* But the numeric type properties can have the alphas [Ee] to
* signify an exponent, and it is still a number with stricter
* rules. So look for an alpha that signifies not-strict */
stricter = TRUE;
for (k = i; k < name_len; k++) {
if ( isALPHA_A(name[k])
&& (! is_nv_type || ! isALPHA_FOLD_EQ(name[k], 'E')))
{
stricter = FALSE;
break;
}
}
}
if (stricter) {
/* A number may have a leading '+' or '-'. The latter is retained
* */
if (name[i] == '+') {
i++;
}
else if (name[i] == '-') {
lookup_name[j++] = '-';
i++;
}
/* Skip leading zeros including single underscores separating the
* zeros, or between the final leading zero and the first other
* digit */
for (; i < name_len - 1; i++) {
if ( name[i] != '0'
&& (name[i] != '_' || ! isDIGIT_A(name[i+1])))
{
break;
}
}
}
}
else { /* No '=' */
/* Only a few properties without an '=' should be parsed with stricter
* rules. The list is unlikely to change. */
if ( memBEGINPs(lookup_name, j, "perl")
&& memNEs(lookup_name + 4, j - 4, "space")
&& memNEs(lookup_name + 4, j - 4, "word"))
{
stricter = TRUE;
/* We set the inputs back to 0 and the code below will reparse,
* using strict */
i = j = 0;
}
}
/* Here, we have either finished the property, or are positioned to parse
* the remainder, and we know if stricter rules apply. Finish out, if not
* already done */
for (; i < name_len; i++) {
char cur = name[i];
/* In all instances, case differences are ignored, and we normalize to
* lowercase */
if (isUPPER_A(cur)) {
lookup_name[j++] = toLOWER(cur);
continue;
}
/* An underscore is skipped, but not under strict rules unless it
* separates two digits */
if (cur == '_') {
if ( stricter
&& ( i == 0 || (int) i == equals_pos || i == name_len- 1
|| ! isDIGIT_A(name[i-1]) || ! isDIGIT_A(name[i+1])))
{
lookup_name[j++] = '_';
}
continue;
}
/* Hyphens are skipped except under strict */
if (cur == '-' && ! stricter) {
continue;
}
/* XXX Bug in documentation. It says white space skipped adjacent to
* non-word char. Maybe we should, but shouldn't skip it next to a dot
* in a number */
if (isSPACE_A(cur) && ! stricter) {
continue;
}
lookup_name[j++] = cur;
/* Unless this is a non-trailing slash, we are done with it */
if (i >= name_len - 1 || cur != '/') {
continue;
}
slash_pos = j;
/* A slash in the 'numeric value' property indicates that what follows
* is a denominator. It can have a leading '+' and '0's that should be
* skipped. But we have never allowed a negative denominator, so treat
* a minus like every other character. (No need to rule out a second
* '/', as that won't match anything anyway */
if (is_nv_type) {
i++;
if (i < name_len && name[i] == '+') {
i++;
}
/* Skip leading zeros including underscores separating digits */
for (; i < name_len - 1; i++) {
if ( name[i] != '0'
&& (name[i] != '_' || ! isDIGIT_A(name[i+1])))
{
break;
}
}
/* Store the first real character in the denominator */
lookup_name[j++] = name[i];
}
}
/* Here are completely done parsing the input 'name', and 'lookup_name'
* contains a copy, normalized.
*
* This special case is grandfathered in: 'L_' and 'GC=L_' are accepted and
* different from without the underscores. */
if ( ( UNLIKELY(memEQs(lookup_name, j, "l"))
|| UNLIKELY(memEQs(lookup_name, j, "gc=l")))
&& UNLIKELY(name[name_len-1] == '_'))
{
lookup_name[j++] = '&';
}
/* If the original input began with 'In' or 'Is', it could be a subroutine
* call to a user-defined property instead of a Unicode property name. */
if ( non_pkg_begin + name_len > 2
&& name[non_pkg_begin+0] == 'I'
&& (name[non_pkg_begin+1] == 'n' || name[non_pkg_begin+1] == 's'))
{
starts_with_In_or_Is = TRUE;
}
else {
could_be_user_defined = FALSE;
}
if (could_be_user_defined) {
CV* user_sub;
/* If the user defined property returns the empty string, it could
* easily be because the pattern is being compiled before the data it
* actually needs to compile is available. This could be argued to be
* a bug in the perl code, but this is a change of behavior for Perl,
* so we handle it. This means that intentionally returning nothing
* will not be resolved until runtime */
bool empty_return = FALSE;
/* Here, the name could be for a user defined property, which are
* implemented as subs. */
user_sub = get_cvn_flags(name, name_len, 0);
if (user_sub) {
const char insecure[] = "Insecure user-defined property";
/* Here, there is a sub by the correct name. Normally we call it
* to get the property definition */
dSP;
SV * user_sub_sv = MUTABLE_SV(user_sub);
SV * error; /* Any error returned by calling 'user_sub' */
SV * key; /* The key into the hash of user defined sub names
*/
SV * placeholder;
SV ** saved_user_prop_ptr; /* Hash entry for this property */
/* How many times to retry when another thread is in the middle of
* expanding the same definition we want */
PERL_INT_FAST8_T retry_countdown = 10;
DECLARATION_FOR_GLOBAL_CONTEXT;
/* If we get here, we know this property is user-defined */
*user_defined_ptr = TRUE;
/* We refuse to call a potentially tainted subroutine; returning an
* error instead */
if (TAINT_get) {
if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
sv_catpvn(msg, insecure, sizeof(insecure) - 1);
goto append_name_to_msg;
}
/* In principal, we only call each subroutine property definition
* once during the life of the program. This guarantees that the
* property definition never changes. The results of the single
* sub call are stored in a hash, which is used instead for future
* references to this property. The property definition is thus
* immutable. But, to allow the user to have a /i-dependent
* definition, we call the sub once for non-/i, and once for /i,
* should the need arise, passing the /i status as a parameter.
*
* We start by constructing the hash key name, consisting of the
* fully qualified subroutine name, preceded by the /i status, so
* that there is a key for /i and a different key for non-/i */
key = newSVpvn(((to_fold) ? "1" : "0"), 1);
fq_name = S_get_fq_name(aTHX_ name, name_len, is_utf8,
non_pkg_begin != 0);
sv_catsv(key, fq_name);
sv_2mortal(key);
/* We only call the sub once throughout the life of the program
* (with the /i, non-/i exception noted above). That means the
* hash must be global and accessible to all threads. It is
* created at program start-up, before any threads are created, so
* is accessible to all children. But this creates some
* complications.
*
* 1) The keys can't be shared, or else problems arise; sharing is
* turned off at hash creation time
* 2) All SVs in it are there for the remainder of the life of the
* program, and must be created in the same interpreter context
* as the hash, or else they will be freed from the wrong pool
* at global destruction time. This is handled by switching to
* the hash's context to create each SV going into it, and then
* immediately switching back
* 3) All accesses to the hash must be controlled by a mutex, to
* prevent two threads from getting an unstable state should
* they simultaneously be accessing it. The code below is
* crafted so that the mutex is locked whenever there is an
* access and unlocked only when the next stable state is
* achieved.
*
* The hash stores either the definition of the property if it was
* valid, or, if invalid, the error message that was raised. We
* use the type of SV to distinguish.
*
* There's also the need to guard against the definition expansion
* from infinitely recursing. This is handled by storing the aTHX
* of the expanding thread during the expansion. Again the SV type
* is used to distinguish this from the other two cases. If we
* come to here and the hash entry for this property is our aTHX,
* it means we have recursed, and the code assumes that we would
* infinitely recurse, so instead stops and raises an error.
* (Any recursion has always been treated as infinite recursion in
* this feature.)
*
* If instead, the entry is for a different aTHX, it means that
* that thread has gotten here first, and hasn't finished expanding
* the definition yet. We just have to wait until it is done. We
* sleep and retry a few times, returning an error if the other
* thread doesn't complete. */
re_fetch:
USER_PROP_MUTEX_LOCK;
/* If we have an entry for this key, the subroutine has already
* been called once with this /i status. */
saved_user_prop_ptr = hv_fetch(PL_user_def_props,
SvPVX(key), SvCUR(key), 0);
if (saved_user_prop_ptr) {
/* If the saved result is an inversion list, it is the valid
* definition of this property */
if (is_invlist(*saved_user_prop_ptr)) {
prop_definition = *saved_user_prop_ptr;
/* The SV in the hash won't be removed until global
* destruction, so it is stable and we can unlock */
USER_PROP_MUTEX_UNLOCK;
/* The caller shouldn't try to free this SV */
return prop_definition;
}
/* Otherwise, if it is a string, it is the error message
* that was returned when we first tried to evaluate this
* property. Fail, and append the message */
if (SvPOK(*saved_user_prop_ptr)) {
if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
sv_catsv(msg, *saved_user_prop_ptr);
/* The SV in the hash won't be removed until global
* destruction, so it is stable and we can unlock */
USER_PROP_MUTEX_UNLOCK;
return NULL;
}
assert(SvIOK(*saved_user_prop_ptr));
/* Here, we have an unstable entry in the hash. Either another
* thread is in the middle of expanding the property's
* definition, or we are ourselves recursing. We use the aTHX
* in it to distinguish */
if (SvIV(*saved_user_prop_ptr) != PTR2IV(CUR_CONTEXT)) {
/* Here, it's another thread doing the expanding. We've
* looked as much as we are going to at the contents of the
* hash entry. It's safe to unlock. */
USER_PROP_MUTEX_UNLOCK;
/* Retry a few times */
if (retry_countdown-- > 0) {
PerlProc_sleep(1);
goto re_fetch;
}
if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
sv_catpvs(msg, "Timeout waiting for another thread to "
"define");
goto append_name_to_msg;
}
/* Here, we are recursing; don't dig any deeper */
USER_PROP_MUTEX_UNLOCK;
if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
sv_catpvs(msg,
"Infinite recursion in user-defined property");
goto append_name_to_msg;
}
/* Here, this thread has exclusive control, and there is no entry
* for this property in the hash. So we have the go ahead to
* expand the definition ourselves. */
PUSHSTACKi(PERLSI_MAGIC);
ENTER;
/* Create a temporary placeholder in the hash to detect recursion
* */
SWITCH_TO_GLOBAL_CONTEXT;
placeholder= newSVuv(PTR2IV(ORIGINAL_CONTEXT));
(void) hv_store_ent(PL_user_def_props, key, placeholder, 0);
RESTORE_CONTEXT;
/* Now that we have a placeholder, we can let other threads
* continue */
USER_PROP_MUTEX_UNLOCK;
/* Make sure the placeholder always gets destroyed */
SAVEDESTRUCTOR_X(S_delete_recursion_entry, SvPVX(key));
PUSHMARK(SP);
SAVETMPS;
/* Call the user's function, with the /i status as a parameter.
* Note that we have gone to a lot of trouble to keep this call
* from being within the locked mutex region. */
XPUSHs(boolSV(to_fold));
PUTBACK;
/* The following block was taken from swash_init(). Presumably
* they apply to here as well, though we no longer use a swash --
* khw */
SAVEHINTS();
save_re_context();
/* We might get here via a subroutine signature which uses a utf8
* parameter name, at which point PL_subname will have been set
* but not yet used. */
save_item(PL_subname);
(void) call_sv(user_sub_sv, G_EVAL|G_SCALAR);
SPAGAIN;
error = ERRSV;
if (TAINT_get || SvTRUE(error)) {
if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
if (SvTRUE(error)) {
sv_catpvs(msg, "Error \"");
sv_catsv(msg, error);
sv_catpvs(msg, "\"");
}
if (TAINT_get) {
if (SvTRUE(error)) sv_catpvs(msg, "; ");
sv_catpvn(msg, insecure, sizeof(insecure) - 1);
}
if (name_len > 0) {
sv_catpvs(msg, " in expansion of ");
Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_utf8,
name_len,
name));
}
(void) POPs;
prop_definition = NULL;
}
else { /* G_SCALAR guarantees a single return value */
SV * contents = POPs;
/* The contents is supposed to be the expansion of the property
* definition. If the definition is deferrable, and we got an
* empty string back, set a flag to later defer it (after clean
* up below). */
if ( deferrable
&& (! SvPOK(contents) || SvCUR(contents) == 0))
{
empty_return = TRUE;
}
else { /* Otherwise, call a function to check for valid syntax,
and handle it */
prop_definition = handle_user_defined_property(
name, name_len,
is_utf8, to_fold, runtime,
deferrable,
contents, user_defined_ptr,
msg,
level);
}
}
/* Here, we have the results of the expansion. Delete the
* placeholder, and if the definition is now known, replace it with
* that definition. We need exclusive access to the hash, and we
* can't let anyone else in, between when we delete the placeholder
* and add the permanent entry */
USER_PROP_MUTEX_LOCK;
S_delete_recursion_entry(aTHX_ SvPVX(key));
if ( ! empty_return
&& (! prop_definition || is_invlist(prop_definition)))
{
/* If we got success we use the inversion list defining the
* property; otherwise use the error message */
SWITCH_TO_GLOBAL_CONTEXT;
(void) hv_store_ent(PL_user_def_props,
key,
((prop_definition)
? newSVsv(prop_definition)
: newSVsv(msg)),
0);
RESTORE_CONTEXT;
}
/* All done, and the hash now has a permanent entry for this
* property. Give up exclusive control */
USER_PROP_MUTEX_UNLOCK;
FREETMPS;
LEAVE;
POPSTACK;
if (empty_return) {
goto definition_deferred;
}
if (prop_definition) {
/* If the definition is for something not known at this time,
* we toss it, and go return the main property name, as that's
* the one the user will be aware of */
if (! is_invlist(prop_definition)) {
SvREFCNT_dec_NN(prop_definition);
goto definition_deferred;
}
sv_2mortal(prop_definition);
}
/* And return */
return prop_definition;
} /* End of calling the subroutine for the user-defined property */
} /* End of it could be a user-defined property */
/* Here it wasn't a user-defined property that is known at this time. See
* if it is a Unicode property */
lookup_len = j; /* This is a more mnemonic name than 'j' */
/* Get the index into our pointer table of the inversion list corresponding
* to the property */
table_index = match_uniprop((U8 *) lookup_name, lookup_len);
/* If it didn't find the property ... */
if (table_index == 0) {
/* Try again stripping off any initial 'In' or 'Is' */
if (starts_with_In_or_Is) {
lookup_name += 2;
lookup_len -= 2;
equals_pos -= 2;
slash_pos -= 2;
table_index = match_uniprop((U8 *) lookup_name, lookup_len);
}
if (table_index == 0) {
char * canonical;
/* Here, we didn't find it. If not a numeric type property, and
* can't be a user-defined one, it isn't a legal property */
if (! is_nv_type) {
if (! could_be_user_defined) {
goto failed;
}
/* Here, the property name is legal as a user-defined one. At
* compile time, it might just be that the subroutine for that
* property hasn't been encountered yet, but at runtime, it's
* an error to try to use an undefined one */
if (! deferrable) {
if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
sv_catpvs(msg, "Unknown user-defined property name");
goto append_name_to_msg;
}
goto definition_deferred;
} /* End of isn't a numeric type property */
/* The numeric type properties need more work to decide. What we
* do is make sure we have the number in canonical form and look
* that up. */
if (slash_pos < 0) { /* No slash */
/* When it isn't a rational, take the input, convert it to a
* NV, then create a canonical string representation of that
* NV. */
NV value;
SSize_t value_len = lookup_len - equals_pos;
/* Get the value */
if ( value_len <= 0
|| my_atof3(lookup_name + equals_pos, &value,
value_len)
!= lookup_name + lookup_len)
{
goto failed;
}
/* If the value is an integer, the canonical value is integral
* */
if (Perl_ceil(value) == value) {
canonical = Perl_form(aTHX_ "%.*s%.0" NVff,
equals_pos, lookup_name, value);
}
else { /* Otherwise, it is %e with a known precision */
char * exp_ptr;
canonical = Perl_form(aTHX_ "%.*s%.*" NVef,
equals_pos, lookup_name,
PL_E_FORMAT_PRECISION, value);
/* The exponent generated is expecting two digits, whereas
* %e on some systems will generate three. Remove leading
* zeros in excess of 2 from the exponent. We start
* looking for them after the '=' */
exp_ptr = strchr(canonical + equals_pos, 'e');
if (exp_ptr) {
char * cur_ptr = exp_ptr + 2; /* past the 'e[+-]' */
SSize_t excess_exponent_len = strlen(cur_ptr) - 2;
assert(*(cur_ptr - 1) == '-' || *(cur_ptr - 1) == '+');
if (excess_exponent_len > 0) {
SSize_t leading_zeros = strspn(cur_ptr, "0");
SSize_t excess_leading_zeros
= MIN(leading_zeros, excess_exponent_len);
if (excess_leading_zeros > 0) {
Move(cur_ptr + excess_leading_zeros,
cur_ptr,
strlen(cur_ptr) - excess_leading_zeros
+ 1, /* Copy the NUL as well */
char);
}
}
}
}
}
else { /* Has a slash. Create a rational in canonical form */
UV numerator, denominator, gcd, trial;
const char * end_ptr;
const char * sign = "";
/* We can't just find the numerator, denominator, and do the
* division, then use the method above, because that is
* inexact. And the input could be a rational that is within
* epsilon (given our precision) of a valid rational, and would
* then incorrectly compare valid.
*
* We're only interested in the part after the '=' */
const char * this_lookup_name = lookup_name + equals_pos;
lookup_len -= equals_pos;
slash_pos -= equals_pos;
/* Handle any leading minus */
if (this_lookup_name[0] == '-') {
sign = "-";
this_lookup_name++;
lookup_len--;
slash_pos--;
}
/* Convert the numerator to numeric */
end_ptr = this_lookup_name + slash_pos;
if (! grok_atoUV(this_lookup_name, &numerator, &end_ptr)) {
goto failed;
}
/* It better have included all characters before the slash */
if (*end_ptr != '/') {
goto failed;
}
/* Set to look at just the denominator */
this_lookup_name += slash_pos;
lookup_len -= slash_pos;
end_ptr = this_lookup_name + lookup_len;
/* Convert the denominator to numeric */
if (! grok_atoUV(this_lookup_name, &denominator, &end_ptr)) {
goto failed;
}
/* It better be the rest of the characters, and don't divide by
* 0 */
if ( end_ptr != this_lookup_name + lookup_len
|| denominator == 0)
{
goto failed;
}
/* Get the greatest common denominator using
http://en.wikipedia.org/wiki/Euclidean_algorithm */
gcd = numerator;
trial = denominator;
while (trial != 0) {
UV temp = trial;
trial = gcd % trial;
gcd = temp;
}
/* If already in lowest possible terms, we have already tried
* looking this up */
if (gcd == 1) {
goto failed;
}
/* Reduce the rational, which should put it in canonical form
* */
numerator /= gcd;
denominator /= gcd;
canonical = Perl_form(aTHX_ "%.*s%s%" UVuf "/%" UVuf,
equals_pos, lookup_name, sign, numerator, denominator);
}
/* Here, we have the number in canonical form. Try that */
table_index = match_uniprop((U8 *) canonical, strlen(canonical));
if (table_index == 0) {
goto failed;
}
} /* End of still didn't find the property in our table */
} /* End of didn't find the property in our table */
/* Here, we have a non-zero return, which is an index into a table of ptrs.
* A negative return signifies that the real index is the absolute value,
* but the result needs to be inverted */
if (table_index < 0) {
invert_return = TRUE;
table_index = -table_index;
}
/* Out-of band indices indicate a deprecated property. The proper index is
* modulo it with the table size. And dividing by the table size yields
* an offset into a table constructed by regen/mk_invlists.pl to contain
* the corresponding warning message */
if (table_index > MAX_UNI_KEYWORD_INDEX) {
Size_t warning_offset = table_index / MAX_UNI_KEYWORD_INDEX;
table_index %= MAX_UNI_KEYWORD_INDEX;
Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED),
"Use of '%.*s' in \\p{} or \\P{} is deprecated because: %s",
(int) name_len, name, deprecated_property_msgs[warning_offset]);
}
/* In a few properties, a different property is used under /i. These are
* unlikely to change, so are hard-coded here. */
if (to_fold) {
if ( table_index == UNI_XPOSIXUPPER
|| table_index == UNI_XPOSIXLOWER
|| table_index == UNI_TITLE)
{
table_index = UNI_CASED;
}
else if ( table_index == UNI_UPPERCASELETTER
|| table_index == UNI_LOWERCASELETTER
# ifdef UNI_TITLECASELETTER /* Missing from early Unicodes */
|| table_index == UNI_TITLECASELETTER
# endif
) {
table_index = UNI_CASEDLETTER;
}
else if ( table_index == UNI_POSIXUPPER
|| table_index == UNI_POSIXLOWER)
{
table_index = UNI_POSIXALPHA;
}
}
/* Create and return the inversion list */
prop_definition =_new_invlist_C_array(uni_prop_ptrs[table_index]);
sv_2mortal(prop_definition);
/* See if there is a private use override to add to this definition */
{
COPHH * hinthash = (IN_PERL_COMPILETIME)
? CopHINTHASH_get(&PL_compiling)
: CopHINTHASH_get(PL_curcop);
SV * pu_overrides = cophh_fetch_pv(hinthash, "private_use", 0, 0);
if (UNLIKELY(pu_overrides && SvPOK(pu_overrides))) {
/* See if there is an element in the hints hash for this table */
SV * pu_lookup = Perl_newSVpvf(aTHX_ "%d=", table_index);
const char * pos = strstr(SvPVX(pu_overrides), SvPVX(pu_lookup));
if (pos) {
bool dummy;
SV * pu_definition;
SV * pu_invlist;
SV * expanded_prop_definition =
sv_2mortal(invlist_clone(prop_definition, NULL));
/* If so, it's definition is the string from here to the next
* \a character. And its format is the same as a user-defined
* property */
pos += SvCUR(pu_lookup);
pu_definition = newSVpvn(pos, strchr(pos, '\a') - pos);
pu_invlist = handle_user_defined_property(lookup_name,
lookup_len,
0, /* Not UTF-8 */
0, /* Not folded */
runtime,
deferrable,
pu_definition,
&dummy,
msg,
level);
if (TAINT_get) {
if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
sv_catpvs(msg, "Insecure private-use override");
goto append_name_to_msg;
}
/* For now, as a safety measure, make sure that it doesn't
* override non-private use code points */
_invlist_intersection(pu_invlist, PL_Private_Use, &pu_invlist);
/* Add it to the list to be returned */
_invlist_union(prop_definition, pu_invlist,
&expanded_prop_definition);
prop_definition = expanded_prop_definition;
Perl_ck_warner_d(aTHX_ packWARN(WARN_EXPERIMENTAL__PRIVATE_USE), "The private_use feature is experimental");
}
}
}
if (invert_return) {
_invlist_invert(prop_definition);
}
return prop_definition;
failed:
if (non_pkg_begin != 0) {
if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
sv_catpvs(msg, "Illegal user-defined property name");
}
else {
if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
sv_catpvs(msg, "Can't find Unicode property definition");
}
/* FALLTHROUGH */
append_name_to_msg:
{
const char * prefix = (runtime && level == 0) ? " \\p{" : " \"";
const char * suffix = (runtime && level == 0) ? "}" : "\"";
sv_catpv(msg, prefix);
Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_utf8, name_len, name));
sv_catpv(msg, suffix);
}
return NULL;
definition_deferred:
/* Here it could yet to be defined, so defer evaluation of this
* until its needed at runtime. We need the fully qualified property name
* to avoid ambiguity, and a trailing newline */
if (! fq_name) {
fq_name = S_get_fq_name(aTHX_ name, name_len, is_utf8,
non_pkg_begin != 0 /* If has "::" */
);
}
sv_catpvs(fq_name, "\n");
*user_defined_ptr = TRUE;
return fq_name;
}
#endif
/*
* ex: set ts=8 sts=4 sw=4 et:
*/
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_3873_0 |
crossvul-cpp_data_good_2760_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_apps_config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include "openjpeg.h"
#include "convert.h"
/*
* Get logarithm of an integer and round downwards.
*
* log2(a)
*/
static int int_floorlog2(int a)
{
int l;
for (l = 0; a > 1; l++) {
a >>= 1;
}
return l;
}
/* Component precision scaling */
void clip_component(opj_image_comp_t* component, OPJ_UINT32 precision)
{
OPJ_SIZE_T i;
OPJ_SIZE_T len;
OPJ_UINT32 umax = (OPJ_UINT32)((OPJ_INT32) - 1);
len = (OPJ_SIZE_T)component->w * (OPJ_SIZE_T)component->h;
if (precision < 32) {
umax = (1U << precision) - 1U;
}
if (component->sgnd) {
OPJ_INT32* l_data = component->data;
OPJ_INT32 max = (OPJ_INT32)(umax / 2U);
OPJ_INT32 min = -max - 1;
for (i = 0; i < len; ++i) {
if (l_data[i] > max) {
l_data[i] = max;
} else if (l_data[i] < min) {
l_data[i] = min;
}
}
} else {
OPJ_UINT32* l_data = (OPJ_UINT32*)component->data;
for (i = 0; i < len; ++i) {
if (l_data[i] > umax) {
l_data[i] = umax;
}
}
}
component->prec = precision;
}
/* Component precision scaling */
static void scale_component_up(opj_image_comp_t* component,
OPJ_UINT32 precision)
{
OPJ_SIZE_T i, len;
len = (OPJ_SIZE_T)component->w * (OPJ_SIZE_T)component->h;
if (component->sgnd) {
OPJ_INT64 newMax = (OPJ_INT64)(1U << (precision - 1));
OPJ_INT64 oldMax = (OPJ_INT64)(1U << (component->prec - 1));
OPJ_INT32* l_data = component->data;
for (i = 0; i < len; ++i) {
l_data[i] = (OPJ_INT32)(((OPJ_INT64)l_data[i] * newMax) / oldMax);
}
} else {
OPJ_UINT64 newMax = (OPJ_UINT64)((1U << precision) - 1U);
OPJ_UINT64 oldMax = (OPJ_UINT64)((1U << component->prec) - 1U);
OPJ_UINT32* l_data = (OPJ_UINT32*)component->data;
for (i = 0; i < len; ++i) {
l_data[i] = (OPJ_UINT32)(((OPJ_UINT64)l_data[i] * newMax) / oldMax);
}
}
component->prec = precision;
component->bpp = precision;
}
void scale_component(opj_image_comp_t* component, OPJ_UINT32 precision)
{
int shift;
OPJ_SIZE_T i, len;
if (component->prec == precision) {
return;
}
if (component->prec < precision) {
scale_component_up(component, precision);
return;
}
shift = (int)(component->prec - precision);
len = (OPJ_SIZE_T)component->w * (OPJ_SIZE_T)component->h;
if (component->sgnd) {
OPJ_INT32* l_data = component->data;
for (i = 0; i < len; ++i) {
l_data[i] >>= shift;
}
} else {
OPJ_UINT32* l_data = (OPJ_UINT32*)component->data;
for (i = 0; i < len; ++i) {
l_data[i] >>= shift;
}
}
component->bpp = precision;
component->prec = precision;
}
/* planar / interleaved conversions */
/* used by PNG/TIFF */
static void convert_32s_C1P1(const OPJ_INT32* pSrc, OPJ_INT32* const* pDst,
OPJ_SIZE_T length)
{
memcpy(pDst[0], pSrc, length * sizeof(OPJ_INT32));
}
static void convert_32s_C2P2(const OPJ_INT32* pSrc, OPJ_INT32* const* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
OPJ_INT32* pDst0 = pDst[0];
OPJ_INT32* pDst1 = pDst[1];
for (i = 0; i < length; i++) {
pDst0[i] = pSrc[2 * i + 0];
pDst1[i] = pSrc[2 * i + 1];
}
}
static void convert_32s_C3P3(const OPJ_INT32* pSrc, OPJ_INT32* const* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
OPJ_INT32* pDst0 = pDst[0];
OPJ_INT32* pDst1 = pDst[1];
OPJ_INT32* pDst2 = pDst[2];
for (i = 0; i < length; i++) {
pDst0[i] = pSrc[3 * i + 0];
pDst1[i] = pSrc[3 * i + 1];
pDst2[i] = pSrc[3 * i + 2];
}
}
static void convert_32s_C4P4(const OPJ_INT32* pSrc, OPJ_INT32* const* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
OPJ_INT32* pDst0 = pDst[0];
OPJ_INT32* pDst1 = pDst[1];
OPJ_INT32* pDst2 = pDst[2];
OPJ_INT32* pDst3 = pDst[3];
for (i = 0; i < length; i++) {
pDst0[i] = pSrc[4 * i + 0];
pDst1[i] = pSrc[4 * i + 1];
pDst2[i] = pSrc[4 * i + 2];
pDst3[i] = pSrc[4 * i + 3];
}
}
const convert_32s_CXPX convert_32s_CXPX_LUT[5] = {
NULL,
convert_32s_C1P1,
convert_32s_C2P2,
convert_32s_C3P3,
convert_32s_C4P4
};
static void convert_32s_P1C1(OPJ_INT32 const* const* pSrc, OPJ_INT32* pDst,
OPJ_SIZE_T length, OPJ_INT32 adjust)
{
OPJ_SIZE_T i;
const OPJ_INT32* pSrc0 = pSrc[0];
for (i = 0; i < length; i++) {
pDst[i] = pSrc0[i] + adjust;
}
}
static void convert_32s_P2C2(OPJ_INT32 const* const* pSrc, OPJ_INT32* pDst,
OPJ_SIZE_T length, OPJ_INT32 adjust)
{
OPJ_SIZE_T i;
const OPJ_INT32* pSrc0 = pSrc[0];
const OPJ_INT32* pSrc1 = pSrc[1];
for (i = 0; i < length; i++) {
pDst[2 * i + 0] = pSrc0[i] + adjust;
pDst[2 * i + 1] = pSrc1[i] + adjust;
}
}
static void convert_32s_P3C3(OPJ_INT32 const* const* pSrc, OPJ_INT32* pDst,
OPJ_SIZE_T length, OPJ_INT32 adjust)
{
OPJ_SIZE_T i;
const OPJ_INT32* pSrc0 = pSrc[0];
const OPJ_INT32* pSrc1 = pSrc[1];
const OPJ_INT32* pSrc2 = pSrc[2];
for (i = 0; i < length; i++) {
pDst[3 * i + 0] = pSrc0[i] + adjust;
pDst[3 * i + 1] = pSrc1[i] + adjust;
pDst[3 * i + 2] = pSrc2[i] + adjust;
}
}
static void convert_32s_P4C4(OPJ_INT32 const* const* pSrc, OPJ_INT32* pDst,
OPJ_SIZE_T length, OPJ_INT32 adjust)
{
OPJ_SIZE_T i;
const OPJ_INT32* pSrc0 = pSrc[0];
const OPJ_INT32* pSrc1 = pSrc[1];
const OPJ_INT32* pSrc2 = pSrc[2];
const OPJ_INT32* pSrc3 = pSrc[3];
for (i = 0; i < length; i++) {
pDst[4 * i + 0] = pSrc0[i] + adjust;
pDst[4 * i + 1] = pSrc1[i] + adjust;
pDst[4 * i + 2] = pSrc2[i] + adjust;
pDst[4 * i + 3] = pSrc3[i] + adjust;
}
}
const convert_32s_PXCX convert_32s_PXCX_LUT[5] = {
NULL,
convert_32s_P1C1,
convert_32s_P2C2,
convert_32s_P3C3,
convert_32s_P4C4
};
/* bit depth conversions */
/* used by PNG/TIFF up to 8bpp */
static void convert_1u32s_C1R(const OPJ_BYTE* pSrc, OPJ_INT32* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
for (i = 0; i < (length & ~(OPJ_SIZE_T)7U); i += 8U) {
OPJ_UINT32 val = *pSrc++;
pDst[i + 0] = (OPJ_INT32)(val >> 7);
pDst[i + 1] = (OPJ_INT32)((val >> 6) & 0x1U);
pDst[i + 2] = (OPJ_INT32)((val >> 5) & 0x1U);
pDst[i + 3] = (OPJ_INT32)((val >> 4) & 0x1U);
pDst[i + 4] = (OPJ_INT32)((val >> 3) & 0x1U);
pDst[i + 5] = (OPJ_INT32)((val >> 2) & 0x1U);
pDst[i + 6] = (OPJ_INT32)((val >> 1) & 0x1U);
pDst[i + 7] = (OPJ_INT32)(val & 0x1U);
}
if (length & 7U) {
OPJ_UINT32 val = *pSrc++;
length = length & 7U;
pDst[i + 0] = (OPJ_INT32)(val >> 7);
if (length > 1U) {
pDst[i + 1] = (OPJ_INT32)((val >> 6) & 0x1U);
if (length > 2U) {
pDst[i + 2] = (OPJ_INT32)((val >> 5) & 0x1U);
if (length > 3U) {
pDst[i + 3] = (OPJ_INT32)((val >> 4) & 0x1U);
if (length > 4U) {
pDst[i + 4] = (OPJ_INT32)((val >> 3) & 0x1U);
if (length > 5U) {
pDst[i + 5] = (OPJ_INT32)((val >> 2) & 0x1U);
if (length > 6U) {
pDst[i + 6] = (OPJ_INT32)((val >> 1) & 0x1U);
}
}
}
}
}
}
}
}
static void convert_2u32s_C1R(const OPJ_BYTE* pSrc, OPJ_INT32* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
for (i = 0; i < (length & ~(OPJ_SIZE_T)3U); i += 4U) {
OPJ_UINT32 val = *pSrc++;
pDst[i + 0] = (OPJ_INT32)(val >> 6);
pDst[i + 1] = (OPJ_INT32)((val >> 4) & 0x3U);
pDst[i + 2] = (OPJ_INT32)((val >> 2) & 0x3U);
pDst[i + 3] = (OPJ_INT32)(val & 0x3U);
}
if (length & 3U) {
OPJ_UINT32 val = *pSrc++;
length = length & 3U;
pDst[i + 0] = (OPJ_INT32)(val >> 6);
if (length > 1U) {
pDst[i + 1] = (OPJ_INT32)((val >> 4) & 0x3U);
if (length > 2U) {
pDst[i + 2] = (OPJ_INT32)((val >> 2) & 0x3U);
}
}
}
}
static void convert_4u32s_C1R(const OPJ_BYTE* pSrc, OPJ_INT32* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
for (i = 0; i < (length & ~(OPJ_SIZE_T)1U); i += 2U) {
OPJ_UINT32 val = *pSrc++;
pDst[i + 0] = (OPJ_INT32)(val >> 4);
pDst[i + 1] = (OPJ_INT32)(val & 0xFU);
}
if (length & 1U) {
OPJ_UINT8 val = *pSrc++;
pDst[i + 0] = (OPJ_INT32)(val >> 4);
}
}
static void convert_6u32s_C1R(const OPJ_BYTE* pSrc, OPJ_INT32* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
for (i = 0; i < (length & ~(OPJ_SIZE_T)3U); i += 4U) {
OPJ_UINT32 val0 = *pSrc++;
OPJ_UINT32 val1 = *pSrc++;
OPJ_UINT32 val2 = *pSrc++;
pDst[i + 0] = (OPJ_INT32)(val0 >> 2);
pDst[i + 1] = (OPJ_INT32)(((val0 & 0x3U) << 4) | (val1 >> 4));
pDst[i + 2] = (OPJ_INT32)(((val1 & 0xFU) << 2) | (val2 >> 6));
pDst[i + 3] = (OPJ_INT32)(val2 & 0x3FU);
}
if (length & 3U) {
OPJ_UINT32 val0 = *pSrc++;
length = length & 3U;
pDst[i + 0] = (OPJ_INT32)(val0 >> 2);
if (length > 1U) {
OPJ_UINT32 val1 = *pSrc++;
pDst[i + 1] = (OPJ_INT32)(((val0 & 0x3U) << 4) | (val1 >> 4));
if (length > 2U) {
OPJ_UINT32 val2 = *pSrc++;
pDst[i + 2] = (OPJ_INT32)(((val1 & 0xFU) << 2) | (val2 >> 6));
}
}
}
}
static void convert_8u32s_C1R(const OPJ_BYTE* pSrc, OPJ_INT32* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
for (i = 0; i < length; i++) {
pDst[i] = pSrc[i];
}
}
const convert_XXx32s_C1R convert_XXu32s_C1R_LUT[9] = {
NULL,
convert_1u32s_C1R,
convert_2u32s_C1R,
NULL,
convert_4u32s_C1R,
NULL,
convert_6u32s_C1R,
NULL,
convert_8u32s_C1R
};
static void convert_32s1u_C1R(const OPJ_INT32* pSrc, OPJ_BYTE* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
for (i = 0; i < (length & ~(OPJ_SIZE_T)7U); i += 8U) {
OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i + 0];
OPJ_UINT32 src1 = (OPJ_UINT32)pSrc[i + 1];
OPJ_UINT32 src2 = (OPJ_UINT32)pSrc[i + 2];
OPJ_UINT32 src3 = (OPJ_UINT32)pSrc[i + 3];
OPJ_UINT32 src4 = (OPJ_UINT32)pSrc[i + 4];
OPJ_UINT32 src5 = (OPJ_UINT32)pSrc[i + 5];
OPJ_UINT32 src6 = (OPJ_UINT32)pSrc[i + 6];
OPJ_UINT32 src7 = (OPJ_UINT32)pSrc[i + 7];
*pDst++ = (OPJ_BYTE)((src0 << 7) | (src1 << 6) | (src2 << 5) | (src3 << 4) |
(src4 << 3) | (src5 << 2) | (src6 << 1) | src7);
}
if (length & 7U) {
OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i + 0];
OPJ_UINT32 src1 = 0U;
OPJ_UINT32 src2 = 0U;
OPJ_UINT32 src3 = 0U;
OPJ_UINT32 src4 = 0U;
OPJ_UINT32 src5 = 0U;
OPJ_UINT32 src6 = 0U;
length = length & 7U;
if (length > 1U) {
src1 = (OPJ_UINT32)pSrc[i + 1];
if (length > 2U) {
src2 = (OPJ_UINT32)pSrc[i + 2];
if (length > 3U) {
src3 = (OPJ_UINT32)pSrc[i + 3];
if (length > 4U) {
src4 = (OPJ_UINT32)pSrc[i + 4];
if (length > 5U) {
src5 = (OPJ_UINT32)pSrc[i + 5];
if (length > 6U) {
src6 = (OPJ_UINT32)pSrc[i + 6];
}
}
}
}
}
}
*pDst++ = (OPJ_BYTE)((src0 << 7) | (src1 << 6) | (src2 << 5) | (src3 << 4) |
(src4 << 3) | (src5 << 2) | (src6 << 1));
}
}
static void convert_32s2u_C1R(const OPJ_INT32* pSrc, OPJ_BYTE* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
for (i = 0; i < (length & ~(OPJ_SIZE_T)3U); i += 4U) {
OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i + 0];
OPJ_UINT32 src1 = (OPJ_UINT32)pSrc[i + 1];
OPJ_UINT32 src2 = (OPJ_UINT32)pSrc[i + 2];
OPJ_UINT32 src3 = (OPJ_UINT32)pSrc[i + 3];
*pDst++ = (OPJ_BYTE)((src0 << 6) | (src1 << 4) | (src2 << 2) | src3);
}
if (length & 3U) {
OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i + 0];
OPJ_UINT32 src1 = 0U;
OPJ_UINT32 src2 = 0U;
length = length & 3U;
if (length > 1U) {
src1 = (OPJ_UINT32)pSrc[i + 1];
if (length > 2U) {
src2 = (OPJ_UINT32)pSrc[i + 2];
}
}
*pDst++ = (OPJ_BYTE)((src0 << 6) | (src1 << 4) | (src2 << 2));
}
}
static void convert_32s4u_C1R(const OPJ_INT32* pSrc, OPJ_BYTE* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
for (i = 0; i < (length & ~(OPJ_SIZE_T)1U); i += 2U) {
OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i + 0];
OPJ_UINT32 src1 = (OPJ_UINT32)pSrc[i + 1];
*pDst++ = (OPJ_BYTE)((src0 << 4) | src1);
}
if (length & 1U) {
OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i + 0];
*pDst++ = (OPJ_BYTE)((src0 << 4));
}
}
static void convert_32s6u_C1R(const OPJ_INT32* pSrc, OPJ_BYTE* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
for (i = 0; i < (length & ~(OPJ_SIZE_T)3U); i += 4U) {
OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i + 0];
OPJ_UINT32 src1 = (OPJ_UINT32)pSrc[i + 1];
OPJ_UINT32 src2 = (OPJ_UINT32)pSrc[i + 2];
OPJ_UINT32 src3 = (OPJ_UINT32)pSrc[i + 3];
*pDst++ = (OPJ_BYTE)((src0 << 2) | (src1 >> 4));
*pDst++ = (OPJ_BYTE)(((src1 & 0xFU) << 4) | (src2 >> 2));
*pDst++ = (OPJ_BYTE)(((src2 & 0x3U) << 6) | src3);
}
if (length & 3U) {
OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i + 0];
OPJ_UINT32 src1 = 0U;
OPJ_UINT32 src2 = 0U;
length = length & 3U;
if (length > 1U) {
src1 = (OPJ_UINT32)pSrc[i + 1];
if (length > 2U) {
src2 = (OPJ_UINT32)pSrc[i + 2];
}
}
*pDst++ = (OPJ_BYTE)((src0 << 2) | (src1 >> 4));
if (length > 1U) {
*pDst++ = (OPJ_BYTE)(((src1 & 0xFU) << 4) | (src2 >> 2));
if (length > 2U) {
*pDst++ = (OPJ_BYTE)(((src2 & 0x3U) << 6));
}
}
}
}
static void convert_32s8u_C1R(const OPJ_INT32* pSrc, OPJ_BYTE* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
for (i = 0; i < length; ++i) {
pDst[i] = (OPJ_BYTE)pSrc[i];
}
}
const convert_32sXXx_C1R convert_32sXXu_C1R_LUT[9] = {
NULL,
convert_32s1u_C1R,
convert_32s2u_C1R,
NULL,
convert_32s4u_C1R,
NULL,
convert_32s6u_C1R,
NULL,
convert_32s8u_C1R
};
/* -->> -->> -->> -->>
TGA IMAGE FORMAT
<<-- <<-- <<-- <<-- */
#ifdef INFORMATION_ONLY
/* TGA header definition. */
struct tga_header {
unsigned char id_length; /* Image id field length */
unsigned char colour_map_type; /* Colour map type */
unsigned char image_type; /* Image type */
/*
** Colour map specification
*/
unsigned short colour_map_index; /* First entry index */
unsigned short colour_map_length; /* Colour map length */
unsigned char colour_map_entry_size; /* Colour map entry size */
/*
** Image specification
*/
unsigned short x_origin; /* x origin of image */
unsigned short y_origin; /* u origin of image */
unsigned short image_width; /* Image width */
unsigned short image_height; /* Image height */
unsigned char pixel_depth; /* Pixel depth */
unsigned char image_desc; /* Image descriptor */
};
#endif /* INFORMATION_ONLY */
/* Returns a ushort from a little-endian serialized value */
static unsigned short get_tga_ushort(const unsigned char *data)
{
return (unsigned short)(data[0] | (data[1] << 8));
}
#define TGA_HEADER_SIZE 18
static int tga_readheader(FILE *fp, unsigned int *bits_per_pixel,
unsigned int *width, unsigned int *height, int *flip_image)
{
int palette_size;
unsigned char tga[TGA_HEADER_SIZE];
unsigned char id_len, /*cmap_type,*/ image_type;
unsigned char pixel_depth, image_desc;
unsigned short /*cmap_index,*/ cmap_len, cmap_entry_size;
unsigned short /*x_origin, y_origin,*/ image_w, image_h;
if (!bits_per_pixel || !width || !height || !flip_image) {
return 0;
}
if (fread(tga, TGA_HEADER_SIZE, 1, fp) != 1) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
return 0 ;
}
id_len = tga[0];
/*cmap_type = tga[1];*/
image_type = tga[2];
/*cmap_index = get_tga_ushort(&tga[3]);*/
cmap_len = get_tga_ushort(&tga[5]);
cmap_entry_size = tga[7];
#if 0
x_origin = get_tga_ushort(&tga[8]);
y_origin = get_tga_ushort(&tga[10]);
#endif
image_w = get_tga_ushort(&tga[12]);
image_h = get_tga_ushort(&tga[14]);
pixel_depth = tga[16];
image_desc = tga[17];
*bits_per_pixel = (unsigned int)pixel_depth;
*width = (unsigned int)image_w;
*height = (unsigned int)image_h;
/* Ignore tga identifier, if present ... */
if (id_len) {
unsigned char *id = (unsigned char *) malloc(id_len);
if (id == 0) {
fprintf(stderr, "tga_readheader: memory out\n");
return 0;
}
if (!fread(id, id_len, 1, fp)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
free(id);
return 0 ;
}
free(id);
}
/* Test for compressed formats ... not yet supported ...
// Note :- 9 - RLE encoded palettized.
// 10 - RLE encoded RGB. */
if (image_type > 8) {
fprintf(stderr, "Sorry, compressed tga files are not currently supported.\n");
return 0 ;
}
*flip_image = !(image_desc & 32);
/* Palettized formats are not yet supported, skip over the palette, if present ... */
palette_size = cmap_len * (cmap_entry_size / 8);
if (palette_size > 0) {
fprintf(stderr, "File contains a palette - not yet supported.");
fseek(fp, palette_size, SEEK_CUR);
}
return 1;
}
#ifdef OPJ_BIG_ENDIAN
static INLINE OPJ_UINT16 swap16(OPJ_UINT16 x)
{
return (OPJ_UINT16)(((x & 0x00ffU) << 8) | ((x & 0xff00U) >> 8));
}
#endif
static int tga_writeheader(FILE *fp, int bits_per_pixel, int width, int height,
OPJ_BOOL flip_image)
{
OPJ_UINT16 image_w, image_h, us0;
unsigned char uc0, image_type;
unsigned char pixel_depth, image_desc;
if (!bits_per_pixel || !width || !height) {
return 0;
}
pixel_depth = 0;
if (bits_per_pixel < 256) {
pixel_depth = (unsigned char)bits_per_pixel;
} else {
fprintf(stderr, "ERROR: Wrong bits per pixel inside tga_header");
return 0;
}
uc0 = 0;
if (fwrite(&uc0, 1, 1, fp) != 1) {
goto fails; /* id_length */
}
if (fwrite(&uc0, 1, 1, fp) != 1) {
goto fails; /* colour_map_type */
}
image_type = 2; /* Uncompressed. */
if (fwrite(&image_type, 1, 1, fp) != 1) {
goto fails;
}
us0 = 0;
if (fwrite(&us0, 2, 1, fp) != 1) {
goto fails; /* colour_map_index */
}
if (fwrite(&us0, 2, 1, fp) != 1) {
goto fails; /* colour_map_length */
}
if (fwrite(&uc0, 1, 1, fp) != 1) {
goto fails; /* colour_map_entry_size */
}
if (fwrite(&us0, 2, 1, fp) != 1) {
goto fails; /* x_origin */
}
if (fwrite(&us0, 2, 1, fp) != 1) {
goto fails; /* y_origin */
}
image_w = (unsigned short)width;
image_h = (unsigned short) height;
#ifndef OPJ_BIG_ENDIAN
if (fwrite(&image_w, 2, 1, fp) != 1) {
goto fails;
}
if (fwrite(&image_h, 2, 1, fp) != 1) {
goto fails;
}
#else
image_w = swap16(image_w);
image_h = swap16(image_h);
if (fwrite(&image_w, 2, 1, fp) != 1) {
goto fails;
}
if (fwrite(&image_h, 2, 1, fp) != 1) {
goto fails;
}
#endif
if (fwrite(&pixel_depth, 1, 1, fp) != 1) {
goto fails;
}
image_desc = 8; /* 8 bits per component. */
if (flip_image) {
image_desc |= 32;
}
if (fwrite(&image_desc, 1, 1, fp) != 1) {
goto fails;
}
return 1;
fails:
fputs("\nwrite_tgaheader: write ERROR\n", stderr);
return 0;
}
opj_image_t* tgatoimage(const char *filename, opj_cparameters_t *parameters)
{
FILE *f;
opj_image_t *image;
unsigned int image_width, image_height, pixel_bit_depth;
unsigned int x, y;
int flip_image = 0;
opj_image_cmptparm_t cmptparm[4]; /* maximum 4 components */
int numcomps;
OPJ_COLOR_SPACE color_space;
OPJ_BOOL mono ;
OPJ_BOOL save_alpha;
int subsampling_dx, subsampling_dy;
int i;
f = fopen(filename, "rb");
if (!f) {
fprintf(stderr, "Failed to open %s for reading !!\n", filename);
return 0;
}
if (!tga_readheader(f, &pixel_bit_depth, &image_width, &image_height,
&flip_image)) {
fclose(f);
return NULL;
}
/* We currently only support 24 & 32 bit tga's ... */
if (!((pixel_bit_depth == 24) || (pixel_bit_depth == 32))) {
fclose(f);
return NULL;
}
/* initialize image components */
memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));
mono = (pixel_bit_depth == 8) ||
(pixel_bit_depth == 16); /* Mono with & without alpha. */
save_alpha = (pixel_bit_depth == 16) ||
(pixel_bit_depth == 32); /* Mono with alpha, or RGB with alpha */
if (mono) {
color_space = OPJ_CLRSPC_GRAY;
numcomps = save_alpha ? 2 : 1;
} else {
numcomps = save_alpha ? 4 : 3;
color_space = OPJ_CLRSPC_SRGB;
}
/* If the declared file size is > 10 MB, check that the file is big */
/* enough to avoid excessive memory allocations */
if (image_height != 0 &&
image_width > 10000000U / image_height / (OPJ_UINT32)numcomps) {
char ch;
OPJ_UINT64 expected_file_size =
(OPJ_UINT64)image_width * image_height * (OPJ_UINT32)numcomps;
long curpos = ftell(f);
if (expected_file_size > (OPJ_UINT64)INT_MAX) {
expected_file_size = (OPJ_UINT64)INT_MAX;
}
fseek(f, (long)expected_file_size - 1, SEEK_SET);
if (fread(&ch, 1, 1, f) != 1) {
fclose(f);
return NULL;
}
fseek(f, curpos, SEEK_SET);
}
subsampling_dx = parameters->subsampling_dx;
subsampling_dy = parameters->subsampling_dy;
for (i = 0; i < numcomps; i++) {
cmptparm[i].prec = 8;
cmptparm[i].bpp = 8;
cmptparm[i].sgnd = 0;
cmptparm[i].dx = (OPJ_UINT32)subsampling_dx;
cmptparm[i].dy = (OPJ_UINT32)subsampling_dy;
cmptparm[i].w = image_width;
cmptparm[i].h = image_height;
}
/* create the image */
image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
if (!image) {
fclose(f);
return NULL;
}
/* set image offset and reference grid */
image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
image->x1 = !image->x0 ? (OPJ_UINT32)(image_width - 1) *
(OPJ_UINT32)subsampling_dx + 1 : image->x0 + (OPJ_UINT32)(image_width - 1) *
(OPJ_UINT32)subsampling_dx + 1;
image->y1 = !image->y0 ? (OPJ_UINT32)(image_height - 1) *
(OPJ_UINT32)subsampling_dy + 1 : image->y0 + (OPJ_UINT32)(image_height - 1) *
(OPJ_UINT32)subsampling_dy + 1;
/* set image data */
for (y = 0; y < image_height; y++) {
int index;
if (flip_image) {
index = (int)((image_height - y - 1) * image_width);
} else {
index = (int)(y * image_width);
}
if (numcomps == 3) {
for (x = 0; x < image_width; x++) {
unsigned char r, g, b;
if (!fread(&b, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&g, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&r, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
image->comps[0].data[index] = r;
image->comps[1].data[index] = g;
image->comps[2].data[index] = b;
index++;
}
} else if (numcomps == 4) {
for (x = 0; x < image_width; x++) {
unsigned char r, g, b, a;
if (!fread(&b, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&g, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&r, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&a, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
image->comps[0].data[index] = r;
image->comps[1].data[index] = g;
image->comps[2].data[index] = b;
image->comps[3].data[index] = a;
index++;
}
} else {
fprintf(stderr, "Currently unsupported bit depth : %s\n", filename);
}
}
fclose(f);
return image;
}
int imagetotga(opj_image_t * image, const char *outfile)
{
int width, height, bpp, x, y;
OPJ_BOOL write_alpha;
unsigned int i;
int adjustR, adjustG = 0, adjustB = 0, fails;
unsigned int alpha_channel;
float r, g, b, a;
unsigned char value;
float scale;
FILE *fdest;
size_t res;
fails = 1;
fdest = fopen(outfile, "wb");
if (!fdest) {
fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
return 1;
}
for (i = 0; i < image->numcomps - 1; i++) {
if ((image->comps[0].dx != image->comps[i + 1].dx)
|| (image->comps[0].dy != image->comps[i + 1].dy)
|| (image->comps[0].prec != image->comps[i + 1].prec)
|| (image->comps[0].sgnd != image->comps[i + 1].sgnd)) {
fclose(fdest);
fprintf(stderr,
"Unable to create a tga file with such J2K image charateristics.\n");
return 1;
}
}
width = (int)image->comps[0].w;
height = (int)image->comps[0].h;
/* Mono with alpha, or RGB with alpha. */
write_alpha = (image->numcomps == 2) || (image->numcomps == 4);
/* Write TGA header */
bpp = write_alpha ? 32 : 24;
if (!tga_writeheader(fdest, bpp, width, height, OPJ_TRUE)) {
goto fin;
}
alpha_channel = image->numcomps - 1;
scale = 255.0f / (float)((1 << image->comps[0].prec) - 1);
adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
if (image->numcomps >= 3) {
adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
}
for (y = 0; y < height; y++) {
unsigned int index = (unsigned int)(y * width);
for (x = 0; x < width; x++, index++) {
r = (float)(image->comps[0].data[index] + adjustR);
if (image->numcomps > 2) {
g = (float)(image->comps[1].data[index] + adjustG);
b = (float)(image->comps[2].data[index] + adjustB);
} else {
/* Greyscale ... */
g = r;
b = r;
}
/* TGA format writes BGR ... */
if (b > 255.) {
b = 255.;
} else if (b < 0.) {
b = 0.;
}
value = (unsigned char)(b * scale);
res = fwrite(&value, 1, 1, fdest);
if (res < 1) {
fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
goto fin;
}
if (g > 255.) {
g = 255.;
} else if (g < 0.) {
g = 0.;
}
value = (unsigned char)(g * scale);
res = fwrite(&value, 1, 1, fdest);
if (res < 1) {
fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
goto fin;
}
if (r > 255.) {
r = 255.;
} else if (r < 0.) {
r = 0.;
}
value = (unsigned char)(r * scale);
res = fwrite(&value, 1, 1, fdest);
if (res < 1) {
fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
goto fin;
}
if (write_alpha) {
a = (float)(image->comps[alpha_channel].data[index]);
if (a > 255.) {
a = 255.;
} else if (a < 0.) {
a = 0.;
}
value = (unsigned char)(a * scale);
res = fwrite(&value, 1, 1, fdest);
if (res < 1) {
fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
goto fin;
}
}
}
}
fails = 0;
fin:
fclose(fdest);
return fails;
}
/* -->> -->> -->> -->>
PGX IMAGE FORMAT
<<-- <<-- <<-- <<-- */
static unsigned char readuchar(FILE * f)
{
unsigned char c1;
if (!fread(&c1, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
return 0;
}
return c1;
}
static unsigned short readushort(FILE * f, int bigendian)
{
unsigned char c1, c2;
if (!fread(&c1, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
return 0;
}
if (!fread(&c2, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
return 0;
}
if (bigendian) {
return (unsigned short)((c1 << 8) + c2);
} else {
return (unsigned short)((c2 << 8) + c1);
}
}
static unsigned int readuint(FILE * f, int bigendian)
{
unsigned char c1, c2, c3, c4;
if (!fread(&c1, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
return 0;
}
if (!fread(&c2, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
return 0;
}
if (!fread(&c3, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
return 0;
}
if (!fread(&c4, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
return 0;
}
if (bigendian) {
return (unsigned int)(c1 << 24) + (unsigned int)(c2 << 16) + (unsigned int)(
c3 << 8) + c4;
} else {
return (unsigned int)(c4 << 24) + (unsigned int)(c3 << 16) + (unsigned int)(
c2 << 8) + c1;
}
}
opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters)
{
FILE *f = NULL;
int w, h, prec;
int i, numcomps, max;
OPJ_COLOR_SPACE color_space;
opj_image_cmptparm_t cmptparm; /* maximum of 1 component */
opj_image_t * image = NULL;
int adjustS, ushift, dshift, force8;
char endian1, endian2, sign;
char signtmp[32];
char temp[32];
int bigendian;
opj_image_comp_t *comp = NULL;
numcomps = 1;
color_space = OPJ_CLRSPC_GRAY;
memset(&cmptparm, 0, sizeof(opj_image_cmptparm_t));
max = 0;
f = fopen(filename, "rb");
if (!f) {
fprintf(stderr, "Failed to open %s for reading !\n", filename);
return NULL;
}
fseek(f, 0, SEEK_SET);
if (fscanf(f, "PG%31[ \t]%c%c%31[ \t+-]%d%31[ \t]%d%31[ \t]%d", temp, &endian1,
&endian2, signtmp, &prec, temp, &w, temp, &h) != 9) {
fclose(f);
fprintf(stderr,
"ERROR: Failed to read the right number of element from the fscanf() function!\n");
return NULL;
}
i = 0;
sign = '+';
while (signtmp[i] != '\0') {
if (signtmp[i] == '-') {
sign = '-';
}
i++;
}
fgetc(f);
if (endian1 == 'M' && endian2 == 'L') {
bigendian = 1;
} else if (endian2 == 'M' && endian1 == 'L') {
bigendian = 0;
} else {
fclose(f);
fprintf(stderr, "Bad pgx header, please check input file\n");
return NULL;
}
/* initialize image component */
cmptparm.x0 = (OPJ_UINT32)parameters->image_offset_x0;
cmptparm.y0 = (OPJ_UINT32)parameters->image_offset_y0;
cmptparm.w = !cmptparm.x0 ? (OPJ_UINT32)((w - 1) * parameters->subsampling_dx +
1) : cmptparm.x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)parameters->subsampling_dx
+ 1;
cmptparm.h = !cmptparm.y0 ? (OPJ_UINT32)((h - 1) * parameters->subsampling_dy +
1) : cmptparm.y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)parameters->subsampling_dy
+ 1;
if (sign == '-') {
cmptparm.sgnd = 1;
} else {
cmptparm.sgnd = 0;
}
if (prec < 8) {
force8 = 1;
ushift = 8 - prec;
dshift = prec - ushift;
if (cmptparm.sgnd) {
adjustS = (1 << (prec - 1));
} else {
adjustS = 0;
}
cmptparm.sgnd = 0;
prec = 8;
} else {
ushift = dshift = force8 = adjustS = 0;
}
cmptparm.prec = (OPJ_UINT32)prec;
cmptparm.bpp = (OPJ_UINT32)prec;
cmptparm.dx = (OPJ_UINT32)parameters->subsampling_dx;
cmptparm.dy = (OPJ_UINT32)parameters->subsampling_dy;
/* create the image */
image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm, color_space);
if (!image) {
fclose(f);
return NULL;
}
/* set image offset and reference grid */
image->x0 = cmptparm.x0;
image->y0 = cmptparm.x0;
image->x1 = cmptparm.w;
image->y1 = cmptparm.h;
/* set image data */
comp = &image->comps[0];
for (i = 0; i < w * h; i++) {
int v;
if (force8) {
v = readuchar(f) + adjustS;
v = (v << ushift) + (v >> dshift);
comp->data[i] = (unsigned char)v;
if (v > max) {
max = v;
}
continue;
}
if (comp->prec == 8) {
if (!comp->sgnd) {
v = readuchar(f);
} else {
v = (char) readuchar(f);
}
} else if (comp->prec <= 16) {
if (!comp->sgnd) {
v = readushort(f, bigendian);
} else {
v = (short) readushort(f, bigendian);
}
} else {
if (!comp->sgnd) {
v = (int)readuint(f, bigendian);
} else {
v = (int) readuint(f, bigendian);
}
}
if (v > max) {
max = v;
}
comp->data[i] = v;
}
fclose(f);
comp->bpp = (OPJ_UINT32)int_floorlog2(max) + 1;
return image;
}
#define CLAMP(x,a,b) x < a ? a : (x > b ? b : x)
static INLINE int clamp(const int value, const int prec, const int sgnd)
{
if (sgnd) {
if (prec <= 8) {
return CLAMP(value, -128, 127);
} else if (prec <= 16) {
return CLAMP(value, -32768, 32767);
} else {
return CLAMP(value, -2147483647 - 1, 2147483647);
}
} else {
if (prec <= 8) {
return CLAMP(value, 0, 255);
} else if (prec <= 16) {
return CLAMP(value, 0, 65535);
} else {
return value; /*CLAMP(value,0,4294967295);*/
}
}
}
int imagetopgx(opj_image_t * image, const char *outfile)
{
int w, h;
int i, j, fails = 1;
unsigned int compno;
FILE *fdest = NULL;
for (compno = 0; compno < image->numcomps; compno++) {
opj_image_comp_t *comp = &image->comps[compno];
char bname[256]; /* buffer for name */
char *name = bname; /* pointer */
int nbytes = 0;
size_t res;
const size_t olen = strlen(outfile);
const size_t dotpos = olen - 4;
const size_t total = dotpos + 1 + 1 + 4; /* '-' + '[1-3]' + '.pgx' */
if (outfile[dotpos] != '.') {
/* `pgx` was recognized but there is no dot at expected position */
fprintf(stderr, "ERROR -> Impossible happen.");
goto fin;
}
if (total > 256) {
name = (char*)malloc(total + 1);
if (name == NULL) {
fprintf(stderr, "imagetopgx: memory out\n");
goto fin;
}
}
strncpy(name, outfile, dotpos);
sprintf(name + dotpos, "_%u.pgx", compno);
fdest = fopen(name, "wb");
/* don't need name anymore */
if (!fdest) {
fprintf(stderr, "ERROR -> failed to open %s for writing\n", name);
if (total > 256) {
free(name);
}
goto fin;
}
w = (int)image->comps[compno].w;
h = (int)image->comps[compno].h;
fprintf(fdest, "PG ML %c %d %d %d\n", comp->sgnd ? '-' : '+', comp->prec,
w, h);
if (comp->prec <= 8) {
nbytes = 1;
} else if (comp->prec <= 16) {
nbytes = 2;
} else {
nbytes = 4;
}
for (i = 0; i < w * h; i++) {
/* FIXME: clamp func is being called within a loop */
const int val = clamp(image->comps[compno].data[i],
(int)comp->prec, (int)comp->sgnd);
for (j = nbytes - 1; j >= 0; j--) {
int v = (int)(val >> (j * 8));
unsigned char byte = (unsigned char)v;
res = fwrite(&byte, 1, 1, fdest);
if (res < 1) {
fprintf(stderr, "failed to write 1 byte for %s\n", name);
if (total > 256) {
free(name);
}
goto fin;
}
}
}
if (total > 256) {
free(name);
}
fclose(fdest);
fdest = NULL;
}
fails = 0;
fin:
if (fdest) {
fclose(fdest);
}
return fails;
}
/* -->> -->> -->> -->>
PNM IMAGE FORMAT
<<-- <<-- <<-- <<-- */
struct pnm_header {
int width, height, maxval, depth, format;
char rgb, rgba, gray, graya, bw;
char ok;
};
static char *skip_white(char *s)
{
if (s != NULL) {
while (*s) {
if (*s == '\n' || *s == '\r') {
return NULL;
}
if (isspace(*s)) {
++s;
continue;
}
return s;
}
}
return NULL;
}
static char *skip_int(char *start, int *out_n)
{
char *s;
char c;
*out_n = 0;
s = skip_white(start);
if (s == NULL) {
return NULL;
}
start = s;
while (*s) {
if (!isdigit(*s)) {
break;
}
++s;
}
c = *s;
*s = 0;
*out_n = atoi(start);
*s = c;
return s;
}
static char *skip_idf(char *start, char out_idf[256])
{
char *s;
char c;
s = skip_white(start);
if (s == NULL) {
return NULL;
}
start = s;
while (*s) {
if (isalpha(*s) || *s == '_') {
++s;
continue;
}
break;
}
c = *s;
*s = 0;
strncpy(out_idf, start, 255);
*s = c;
return s;
}
static void read_pnm_header(FILE *reader, struct pnm_header *ph)
{
int format, end, ttype;
char idf[256], type[256];
char line[256];
if (fgets(line, 250, reader) == NULL) {
fprintf(stderr, "\nWARNING: fgets return a NULL value");
return;
}
if (line[0] != 'P') {
fprintf(stderr, "read_pnm_header:PNM:magic P missing\n");
return;
}
format = atoi(line + 1);
if (format < 1 || format > 7) {
fprintf(stderr, "read_pnm_header:magic format %d invalid\n", format);
return;
}
ph->format = format;
ttype = end = 0;
while (fgets(line, 250, reader)) {
char *s;
int allow_null = 0;
if (*line == '#') {
continue;
}
s = line;
if (format == 7) {
s = skip_idf(s, idf);
if (s == NULL || *s == 0) {
return;
}
if (strcmp(idf, "ENDHDR") == 0) {
end = 1;
break;
}
if (strcmp(idf, "WIDTH") == 0) {
s = skip_int(s, &ph->width);
if (s == NULL || *s == 0) {
return;
}
continue;
}
if (strcmp(idf, "HEIGHT") == 0) {
s = skip_int(s, &ph->height);
if (s == NULL || *s == 0) {
return;
}
continue;
}
if (strcmp(idf, "DEPTH") == 0) {
s = skip_int(s, &ph->depth);
if (s == NULL || *s == 0) {
return;
}
continue;
}
if (strcmp(idf, "MAXVAL") == 0) {
s = skip_int(s, &ph->maxval);
if (s == NULL || *s == 0) {
return;
}
continue;
}
if (strcmp(idf, "TUPLTYPE") == 0) {
s = skip_idf(s, type);
if (s == NULL || *s == 0) {
return;
}
if (strcmp(type, "BLACKANDWHITE") == 0) {
ph->bw = 1;
ttype = 1;
continue;
}
if (strcmp(type, "GRAYSCALE") == 0) {
ph->gray = 1;
ttype = 1;
continue;
}
if (strcmp(type, "GRAYSCALE_ALPHA") == 0) {
ph->graya = 1;
ttype = 1;
continue;
}
if (strcmp(type, "RGB") == 0) {
ph->rgb = 1;
ttype = 1;
continue;
}
if (strcmp(type, "RGB_ALPHA") == 0) {
ph->rgba = 1;
ttype = 1;
continue;
}
fprintf(stderr, "read_pnm_header:unknown P7 TUPLTYPE %s\n", type);
return;
}
fprintf(stderr, "read_pnm_header:unknown P7 idf %s\n", idf);
return;
} /* if(format == 7) */
/* Here format is in range [1,6] */
if (ph->width == 0) {
s = skip_int(s, &ph->width);
if ((s == NULL) || (*s == 0) || (ph->width < 1)) {
return;
}
allow_null = 1;
}
if (ph->height == 0) {
s = skip_int(s, &ph->height);
if ((s == NULL) && allow_null) {
continue;
}
if ((s == NULL) || (*s == 0) || (ph->height < 1)) {
return;
}
if (format == 1 || format == 4) {
break;
}
allow_null = 1;
}
/* here, format is in P2, P3, P5, P6 */
s = skip_int(s, &ph->maxval);
if ((s == NULL) && allow_null) {
continue;
}
if ((s == NULL) || (*s == 0)) {
return;
}
break;
}/* while(fgets( ) */
if (format == 2 || format == 3 || format > 4) {
if (ph->maxval < 1 || ph->maxval > 65535) {
return;
}
}
if (ph->width < 1 || ph->height < 1) {
return;
}
if (format == 7) {
if (!end) {
fprintf(stderr, "read_pnm_header:P7 without ENDHDR\n");
return;
}
if (ph->depth < 1 || ph->depth > 4) {
return;
}
if (ttype) {
ph->ok = 1;
}
} else {
ph->ok = 1;
if (format == 1 || format == 4) {
ph->maxval = 255;
}
}
}
static int has_prec(int val)
{
if (val < 2) {
return 1;
}
if (val < 4) {
return 2;
}
if (val < 8) {
return 3;
}
if (val < 16) {
return 4;
}
if (val < 32) {
return 5;
}
if (val < 64) {
return 6;
}
if (val < 128) {
return 7;
}
if (val < 256) {
return 8;
}
if (val < 512) {
return 9;
}
if (val < 1024) {
return 10;
}
if (val < 2048) {
return 11;
}
if (val < 4096) {
return 12;
}
if (val < 8192) {
return 13;
}
if (val < 16384) {
return 14;
}
if (val < 32768) {
return 15;
}
return 16;
}
opj_image_t* pnmtoimage(const char *filename, opj_cparameters_t *parameters)
{
int subsampling_dx = parameters->subsampling_dx;
int subsampling_dy = parameters->subsampling_dy;
FILE *fp = NULL;
int i, compno, numcomps, w, h, prec, format;
OPJ_COLOR_SPACE color_space;
opj_image_cmptparm_t cmptparm[4]; /* RGBA: max. 4 components */
opj_image_t * image = NULL;
struct pnm_header header_info;
if ((fp = fopen(filename, "rb")) == NULL) {
fprintf(stderr, "pnmtoimage:Failed to open %s for reading!\n", filename);
return NULL;
}
memset(&header_info, 0, sizeof(struct pnm_header));
read_pnm_header(fp, &header_info);
if (!header_info.ok) {
fclose(fp);
return NULL;
}
/* This limitation could be removed by making sure to use size_t below */
if (header_info.height != 0 &&
header_info.width > INT_MAX / header_info.height) {
fprintf(stderr, "pnmtoimage:Image %dx%d too big!\n",
header_info.width, header_info.height);
fclose(fp);
return NULL;
}
format = header_info.format;
switch (format) {
case 1: /* ascii bitmap */
case 4: /* raw bitmap */
numcomps = 1;
break;
case 2: /* ascii greymap */
case 5: /* raw greymap */
numcomps = 1;
break;
case 3: /* ascii pixmap */
case 6: /* raw pixmap */
numcomps = 3;
break;
case 7: /* arbitrary map */
numcomps = header_info.depth;
break;
default:
fclose(fp);
return NULL;
}
if (numcomps < 3) {
color_space = OPJ_CLRSPC_GRAY; /* GRAY, GRAYA */
} else {
color_space = OPJ_CLRSPC_SRGB; /* RGB, RGBA */
}
prec = has_prec(header_info.maxval);
if (prec < 8) {
prec = 8;
}
w = header_info.width;
h = header_info.height;
subsampling_dx = parameters->subsampling_dx;
subsampling_dy = parameters->subsampling_dy;
memset(&cmptparm[0], 0, (size_t)numcomps * sizeof(opj_image_cmptparm_t));
for (i = 0; i < numcomps; i++) {
cmptparm[i].prec = (OPJ_UINT32)prec;
cmptparm[i].bpp = (OPJ_UINT32)prec;
cmptparm[i].sgnd = 0;
cmptparm[i].dx = (OPJ_UINT32)subsampling_dx;
cmptparm[i].dy = (OPJ_UINT32)subsampling_dy;
cmptparm[i].w = (OPJ_UINT32)w;
cmptparm[i].h = (OPJ_UINT32)h;
}
image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
if (!image) {
fclose(fp);
return NULL;
}
/* set image offset and reference grid */
image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
image->x1 = (OPJ_UINT32)(parameters->image_offset_x0 + (w - 1) * subsampling_dx
+ 1);
image->y1 = (OPJ_UINT32)(parameters->image_offset_y0 + (h - 1) * subsampling_dy
+ 1);
if ((format == 2) || (format == 3)) { /* ascii pixmap */
unsigned int index;
for (i = 0; i < w * h; i++) {
for (compno = 0; compno < numcomps; compno++) {
index = 0;
if (fscanf(fp, "%u", &index) != 1) {
fprintf(stderr,
"\nWARNING: fscanf return a number of element different from the expected.\n");
}
image->comps[compno].data[i] = (OPJ_INT32)(index * 255) / header_info.maxval;
}
}
} else if ((format == 5)
|| (format == 6)
|| ((format == 7)
&& (header_info.gray || header_info.graya
|| header_info.rgb || header_info.rgba))) { /* binary pixmap */
unsigned char c0, c1, one;
one = (prec < 9);
for (i = 0; i < w * h; i++) {
for (compno = 0; compno < numcomps; compno++) {
if (!fread(&c0, 1, 1, fp)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(fp);
return NULL;
}
if (one) {
image->comps[compno].data[i] = c0;
} else {
if (!fread(&c1, 1, 1, fp)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
}
/* netpbm: */
image->comps[compno].data[i] = ((c0 << 8) | c1);
}
}
}
} else if (format == 1) { /* ascii bitmap */
for (i = 0; i < w * h; i++) {
unsigned int index;
if (fscanf(fp, "%u", &index) != 1) {
fprintf(stderr,
"\nWARNING: fscanf return a number of element different from the expected.\n");
}
image->comps[0].data[i] = (index ? 0 : 255);
}
} else if (format == 4) {
int x, y, bit;
unsigned char uc;
i = 0;
for (y = 0; y < h; ++y) {
bit = -1;
uc = 0;
for (x = 0; x < w; ++x) {
if (bit == -1) {
bit = 7;
uc = (unsigned char)getc(fp);
}
image->comps[0].data[i] = (((uc >> bit) & 1) ? 0 : 255);
--bit;
++i;
}
}
} else if ((format == 7 && header_info.bw)) { /*MONO*/
unsigned char uc;
for (i = 0; i < w * h; ++i) {
if (!fread(&uc, 1, 1, fp)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
}
image->comps[0].data[i] = (uc & 1) ? 0 : 255;
}
}
fclose(fp);
return image;
}/* pnmtoimage() */
static int are_comps_similar(opj_image_t * image)
{
unsigned int i;
for (i = 1; i < image->numcomps; i++) {
if (image->comps[0].dx != image->comps[i].dx ||
image->comps[0].dy != image->comps[i].dy ||
(i <= 2 &&
(image->comps[0].prec != image->comps[i].prec ||
image->comps[0].sgnd != image->comps[i].sgnd))) {
return OPJ_FALSE;
}
}
return OPJ_TRUE;
}
int imagetopnm(opj_image_t * image, const char *outfile, int force_split)
{
int *red, *green, *blue, *alpha;
int wr, hr, max;
int i;
unsigned int compno, ncomp;
int adjustR, adjustG, adjustB, adjustA;
int fails, two, want_gray, has_alpha, triple;
int prec, v;
FILE *fdest = NULL;
const char *tmp = outfile;
char *destname;
alpha = NULL;
if ((prec = (int)image->comps[0].prec) > 16) {
fprintf(stderr, "%s:%d:imagetopnm\n\tprecision %d is larger than 16"
"\n\t: refused.\n", __FILE__, __LINE__, prec);
return 1;
}
two = has_alpha = 0;
fails = 1;
ncomp = image->numcomps;
while (*tmp) {
++tmp;
}
tmp -= 2;
want_gray = (*tmp == 'g' || *tmp == 'G');
ncomp = image->numcomps;
if (want_gray) {
ncomp = 1;
}
if ((force_split == 0) && ncomp >= 2 &&
are_comps_similar(image)) {
fdest = fopen(outfile, "wb");
if (!fdest) {
fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
return fails;
}
two = (prec > 8);
triple = (ncomp > 2);
wr = (int)image->comps[0].w;
hr = (int)image->comps[0].h;
max = (1 << prec) - 1;
has_alpha = (ncomp == 4 || ncomp == 2);
red = image->comps[0].data;
if (triple) {
green = image->comps[1].data;
blue = image->comps[2].data;
} else {
green = blue = NULL;
}
if (has_alpha) {
const char *tt = (triple ? "RGB_ALPHA" : "GRAYSCALE_ALPHA");
fprintf(fdest, "P7\n# OpenJPEG-%s\nWIDTH %d\nHEIGHT %d\nDEPTH %u\n"
"MAXVAL %d\nTUPLTYPE %s\nENDHDR\n", opj_version(),
wr, hr, ncomp, max, tt);
alpha = image->comps[ncomp - 1].data;
adjustA = (image->comps[ncomp - 1].sgnd ?
1 << (image->comps[ncomp - 1].prec - 1) : 0);
} else {
fprintf(fdest, "P6\n# OpenJPEG-%s\n%d %d\n%d\n",
opj_version(), wr, hr, max);
adjustA = 0;
}
adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
if (triple) {
adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
} else {
adjustG = adjustB = 0;
}
for (i = 0; i < wr * hr; ++i) {
if (two) {
v = *red + adjustR;
++red;
if (v > 65535) {
v = 65535;
} else if (v < 0) {
v = 0;
}
/* netpbm: */
fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);
if (triple) {
v = *green + adjustG;
++green;
if (v > 65535) {
v = 65535;
} else if (v < 0) {
v = 0;
}
/* netpbm: */
fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);
v = *blue + adjustB;
++blue;
if (v > 65535) {
v = 65535;
} else if (v < 0) {
v = 0;
}
/* netpbm: */
fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);
}/* if(triple) */
if (has_alpha) {
v = *alpha + adjustA;
++alpha;
if (v > 65535) {
v = 65535;
} else if (v < 0) {
v = 0;
}
/* netpbm: */
fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);
}
continue;
} /* if(two) */
/* prec <= 8: */
v = *red++;
if (v > 255) {
v = 255;
} else if (v < 0) {
v = 0;
}
fprintf(fdest, "%c", (unsigned char)v);
if (triple) {
v = *green++;
if (v > 255) {
v = 255;
} else if (v < 0) {
v = 0;
}
fprintf(fdest, "%c", (unsigned char)v);
v = *blue++;
if (v > 255) {
v = 255;
} else if (v < 0) {
v = 0;
}
fprintf(fdest, "%c", (unsigned char)v);
}
if (has_alpha) {
v = *alpha++;
if (v > 255) {
v = 255;
} else if (v < 0) {
v = 0;
}
fprintf(fdest, "%c", (unsigned char)v);
}
} /* for(i */
fclose(fdest);
return 0;
}
/* YUV or MONO: */
if (image->numcomps > ncomp) {
fprintf(stderr, "WARNING -> [PGM file] Only the first component\n");
fprintf(stderr, " is written to the file\n");
}
destname = (char*)malloc(strlen(outfile) + 8);
if (destname == NULL) {
fprintf(stderr, "imagetopnm: memory out\n");
return 1;
}
for (compno = 0; compno < ncomp; compno++) {
if (ncomp > 1) {
/*sprintf(destname, "%d.%s", compno, outfile);*/
const size_t olen = strlen(outfile);
const size_t dotpos = olen - 4;
strncpy(destname, outfile, dotpos);
sprintf(destname + dotpos, "_%u.pgm", compno);
} else {
sprintf(destname, "%s", outfile);
}
fdest = fopen(destname, "wb");
if (!fdest) {
fprintf(stderr, "ERROR -> failed to open %s for writing\n", destname);
free(destname);
return 1;
}
wr = (int)image->comps[compno].w;
hr = (int)image->comps[compno].h;
prec = (int)image->comps[compno].prec;
max = (1 << prec) - 1;
fprintf(fdest, "P5\n#OpenJPEG-%s\n%d %d\n%d\n",
opj_version(), wr, hr, max);
red = image->comps[compno].data;
adjustR =
(image->comps[compno].sgnd ? 1 << (image->comps[compno].prec - 1) : 0);
if (prec > 8) {
for (i = 0; i < wr * hr; i++) {
v = *red + adjustR;
++red;
if (v > 65535) {
v = 65535;
} else if (v < 0) {
v = 0;
}
/* netpbm: */
fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);
if (has_alpha) {
v = *alpha++;
if (v > 65535) {
v = 65535;
} else if (v < 0) {
v = 0;
}
/* netpbm: */
fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);
}
}/* for(i */
} else { /* prec <= 8 */
for (i = 0; i < wr * hr; ++i) {
v = *red + adjustR;
++red;
if (v > 255) {
v = 255;
} else if (v < 0) {
v = 0;
}
fprintf(fdest, "%c", (unsigned char)v);
}
}
fclose(fdest);
} /* for (compno */
free(destname);
return 0;
}/* imagetopnm() */
/* -->> -->> -->> -->>
RAW IMAGE FORMAT
<<-- <<-- <<-- <<-- */
static opj_image_t* rawtoimage_common(const char *filename,
opj_cparameters_t *parameters, raw_cparameters_t *raw_cp, OPJ_BOOL big_endian)
{
int subsampling_dx = parameters->subsampling_dx;
int subsampling_dy = parameters->subsampling_dy;
FILE *f = NULL;
int i, compno, numcomps, w, h;
OPJ_COLOR_SPACE color_space;
opj_image_cmptparm_t *cmptparm;
opj_image_t * image = NULL;
unsigned short ch;
if ((!(raw_cp->rawWidth & raw_cp->rawHeight & raw_cp->rawComp &
raw_cp->rawBitDepth)) == 0) {
fprintf(stderr, "\nError: invalid raw image parameters\n");
fprintf(stderr, "Please use the Format option -F:\n");
fprintf(stderr,
"-F <width>,<height>,<ncomp>,<bitdepth>,{s,u}@<dx1>x<dy1>:...:<dxn>x<dyn>\n");
fprintf(stderr,
"If subsampling is omitted, 1x1 is assumed for all components\n");
fprintf(stderr,
"Example: -i image.raw -o image.j2k -F 512,512,3,8,u@1x1:2x2:2x2\n");
fprintf(stderr, " for raw 512x512 image with 4:2:0 subsampling\n");
fprintf(stderr, "Aborting.\n");
return NULL;
}
f = fopen(filename, "rb");
if (!f) {
fprintf(stderr, "Failed to open %s for reading !!\n", filename);
fprintf(stderr, "Aborting\n");
return NULL;
}
numcomps = raw_cp->rawComp;
/* FIXME ADE at this point, tcp_mct has not been properly set in calling function */
if (numcomps == 1) {
color_space = OPJ_CLRSPC_GRAY;
} else if ((numcomps >= 3) && (parameters->tcp_mct == 0)) {
color_space = OPJ_CLRSPC_SYCC;
} else if ((numcomps >= 3) && (parameters->tcp_mct != 2)) {
color_space = OPJ_CLRSPC_SRGB;
} else {
color_space = OPJ_CLRSPC_UNKNOWN;
}
w = raw_cp->rawWidth;
h = raw_cp->rawHeight;
cmptparm = (opj_image_cmptparm_t*) calloc((OPJ_UINT32)numcomps,
sizeof(opj_image_cmptparm_t));
if (!cmptparm) {
fprintf(stderr, "Failed to allocate image components parameters !!\n");
fprintf(stderr, "Aborting\n");
fclose(f);
return NULL;
}
/* initialize image components */
for (i = 0; i < numcomps; i++) {
cmptparm[i].prec = (OPJ_UINT32)raw_cp->rawBitDepth;
cmptparm[i].bpp = (OPJ_UINT32)raw_cp->rawBitDepth;
cmptparm[i].sgnd = (OPJ_UINT32)raw_cp->rawSigned;
cmptparm[i].dx = (OPJ_UINT32)(subsampling_dx * raw_cp->rawComps[i].dx);
cmptparm[i].dy = (OPJ_UINT32)(subsampling_dy * raw_cp->rawComps[i].dy);
cmptparm[i].w = (OPJ_UINT32)w;
cmptparm[i].h = (OPJ_UINT32)h;
}
/* create the image */
image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
free(cmptparm);
if (!image) {
fclose(f);
return NULL;
}
/* set image offset and reference grid */
image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
image->x1 = (OPJ_UINT32)parameters->image_offset_x0 + (OPJ_UINT32)(w - 1) *
(OPJ_UINT32)subsampling_dx + 1;
image->y1 = (OPJ_UINT32)parameters->image_offset_y0 + (OPJ_UINT32)(h - 1) *
(OPJ_UINT32)subsampling_dy + 1;
if (raw_cp->rawBitDepth <= 8) {
unsigned char value = 0;
for (compno = 0; compno < numcomps; compno++) {
int nloop = (w * h) / (raw_cp->rawComps[compno].dx *
raw_cp->rawComps[compno].dy);
for (i = 0; i < nloop; i++) {
if (!fread(&value, 1, 1, f)) {
fprintf(stderr, "Error reading raw file. End of file probably reached.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
image->comps[compno].data[i] = raw_cp->rawSigned ? (char)value : value;
}
}
} else if (raw_cp->rawBitDepth <= 16) {
unsigned short value;
for (compno = 0; compno < numcomps; compno++) {
int nloop = (w * h) / (raw_cp->rawComps[compno].dx *
raw_cp->rawComps[compno].dy);
for (i = 0; i < nloop; i++) {
unsigned char temp1;
unsigned char temp2;
if (!fread(&temp1, 1, 1, f)) {
fprintf(stderr, "Error reading raw file. End of file probably reached.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&temp2, 1, 1, f)) {
fprintf(stderr, "Error reading raw file. End of file probably reached.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (big_endian) {
value = (unsigned short)((temp1 << 8) + temp2);
} else {
value = (unsigned short)((temp2 << 8) + temp1);
}
image->comps[compno].data[i] = raw_cp->rawSigned ? (short)value : value;
}
}
} else {
fprintf(stderr,
"OpenJPEG cannot encode raw components with bit depth higher than 16 bits.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (fread(&ch, 1, 1, f)) {
fprintf(stderr, "Warning. End of raw file not reached... processing anyway\n");
}
fclose(f);
return image;
}
opj_image_t* rawltoimage(const char *filename, opj_cparameters_t *parameters,
raw_cparameters_t *raw_cp)
{
return rawtoimage_common(filename, parameters, raw_cp, OPJ_FALSE);
}
opj_image_t* rawtoimage(const char *filename, opj_cparameters_t *parameters,
raw_cparameters_t *raw_cp)
{
return rawtoimage_common(filename, parameters, raw_cp, OPJ_TRUE);
}
static int imagetoraw_common(opj_image_t * image, const char *outfile,
OPJ_BOOL big_endian)
{
FILE *rawFile = NULL;
size_t res;
unsigned int compno, numcomps;
int w, h, fails;
int line, row, curr, mask;
int *ptr;
unsigned char uc;
(void)big_endian;
if ((image->numcomps * image->x1 * image->y1) == 0) {
fprintf(stderr, "\nError: invalid raw image parameters\n");
return 1;
}
numcomps = image->numcomps;
if (numcomps > 4) {
numcomps = 4;
}
for (compno = 1; compno < numcomps; ++compno) {
if (image->comps[0].dx != image->comps[compno].dx) {
break;
}
if (image->comps[0].dy != image->comps[compno].dy) {
break;
}
if (image->comps[0].prec != image->comps[compno].prec) {
break;
}
if (image->comps[0].sgnd != image->comps[compno].sgnd) {
break;
}
}
if (compno != numcomps) {
fprintf(stderr,
"imagetoraw_common: All components shall have the same subsampling, same bit depth, same sign.\n");
fprintf(stderr, "\tAborting\n");
return 1;
}
rawFile = fopen(outfile, "wb");
if (!rawFile) {
fprintf(stderr, "Failed to open %s for writing !!\n", outfile);
return 1;
}
fails = 1;
fprintf(stdout, "Raw image characteristics: %d components\n", image->numcomps);
for (compno = 0; compno < image->numcomps; compno++) {
fprintf(stdout, "Component %u characteristics: %dx%dx%d %s\n", compno,
image->comps[compno].w,
image->comps[compno].h, image->comps[compno].prec,
image->comps[compno].sgnd == 1 ? "signed" : "unsigned");
w = (int)image->comps[compno].w;
h = (int)image->comps[compno].h;
if (image->comps[compno].prec <= 8) {
if (image->comps[compno].sgnd == 1) {
mask = (1 << image->comps[compno].prec) - 1;
ptr = image->comps[compno].data;
for (line = 0; line < h; line++) {
for (row = 0; row < w; row++) {
curr = *ptr;
if (curr > 127) {
curr = 127;
} else if (curr < -128) {
curr = -128;
}
uc = (unsigned char)(curr & mask);
res = fwrite(&uc, 1, 1, rawFile);
if (res < 1) {
fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
goto fin;
}
ptr++;
}
}
} else if (image->comps[compno].sgnd == 0) {
mask = (1 << image->comps[compno].prec) - 1;
ptr = image->comps[compno].data;
for (line = 0; line < h; line++) {
for (row = 0; row < w; row++) {
curr = *ptr;
if (curr > 255) {
curr = 255;
} else if (curr < 0) {
curr = 0;
}
uc = (unsigned char)(curr & mask);
res = fwrite(&uc, 1, 1, rawFile);
if (res < 1) {
fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
goto fin;
}
ptr++;
}
}
}
} else if (image->comps[compno].prec <= 16) {
if (image->comps[compno].sgnd == 1) {
union {
signed short val;
signed char vals[2];
} uc16;
mask = (1 << image->comps[compno].prec) - 1;
ptr = image->comps[compno].data;
for (line = 0; line < h; line++) {
for (row = 0; row < w; row++) {
curr = *ptr;
if (curr > 32767) {
curr = 32767;
} else if (curr < -32768) {
curr = -32768;
}
uc16.val = (signed short)(curr & mask);
res = fwrite(uc16.vals, 1, 2, rawFile);
if (res < 2) {
fprintf(stderr, "failed to write 2 byte for %s\n", outfile);
goto fin;
}
ptr++;
}
}
} else if (image->comps[compno].sgnd == 0) {
union {
unsigned short val;
unsigned char vals[2];
} uc16;
mask = (1 << image->comps[compno].prec) - 1;
ptr = image->comps[compno].data;
for (line = 0; line < h; line++) {
for (row = 0; row < w; row++) {
curr = *ptr;
if (curr > 65535) {
curr = 65535;
} else if (curr < 0) {
curr = 0;
}
uc16.val = (unsigned short)(curr & mask);
res = fwrite(uc16.vals, 1, 2, rawFile);
if (res < 2) {
fprintf(stderr, "failed to write 2 byte for %s\n", outfile);
goto fin;
}
ptr++;
}
}
}
} else if (image->comps[compno].prec <= 32) {
fprintf(stderr, "More than 16 bits per component not handled yet\n");
goto fin;
} else {
fprintf(stderr, "Error: invalid precision: %d\n", image->comps[compno].prec);
goto fin;
}
}
fails = 0;
fin:
fclose(rawFile);
return fails;
}
int imagetoraw(opj_image_t * image, const char *outfile)
{
return imagetoraw_common(image, outfile, OPJ_TRUE);
}
int imagetorawl(opj_image_t * image, const char *outfile)
{
return imagetoraw_common(image, outfile, OPJ_FALSE);
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_2760_0 |
crossvul-cpp_data_bad_4491_0 | /* rsa.c
*
* Copyright (C) 2006-2020 wolfSSL Inc.
*
* This file is part of wolfSSL.
*
* wolfSSL 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.
*
* wolfSSL 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-1335, USA
*/
/*
DESCRIPTION
This library provides the interface to the RSA.
RSA keys can be used to encrypt, decrypt, sign and verify data.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <wolfssl/wolfcrypt/settings.h>
#include <wolfssl/wolfcrypt/error-crypt.h>
#ifndef NO_RSA
#if defined(HAVE_FIPS) && \
defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)
/* set NO_WRAPPERS before headers, use direct internal f()s not wrappers */
#define FIPS_NO_WRAPPERS
#ifdef USE_WINDOWS_API
#pragma code_seg(".fipsA$e")
#pragma const_seg(".fipsB$e")
#endif
#endif
#include <wolfssl/wolfcrypt/rsa.h>
#ifdef WOLFSSL_AFALG_XILINX_RSA
#include <wolfssl/wolfcrypt/port/af_alg/wc_afalg.h>
#endif
#ifdef WOLFSSL_HAVE_SP_RSA
#include <wolfssl/wolfcrypt/sp.h>
#endif
/*
Possible RSA enable options:
* NO_RSA: Overall control of RSA default: on (not defined)
* WC_RSA_BLINDING: Uses Blinding w/ Private Ops default: off
Note: slower by ~20%
* WOLFSSL_KEY_GEN: Allows Private Key Generation default: off
* RSA_LOW_MEM: NON CRT Private Operations, less memory default: off
* WC_NO_RSA_OAEP: Disables RSA OAEP padding default: on (not defined)
* WC_RSA_NONBLOCK: Enables support for RSA non-blocking default: off
* WC_RSA_NONBLOCK_TIME:Enables support for time based blocking default: off
* time calculation.
*/
/*
RSA Key Size Configuration:
* FP_MAX_BITS: With USE_FAST_MATH only default: 4096
If USE_FAST_MATH then use this to override default.
Value is key size * 2. Example: RSA 3072 = 6144
*/
/* If building for old FIPS. */
#if defined(HAVE_FIPS) && \
(!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2))
int wc_InitRsaKey(RsaKey* key, void* ptr)
{
if (key == NULL) {
return BAD_FUNC_ARG;
}
return InitRsaKey_fips(key, ptr);
}
int wc_InitRsaKey_ex(RsaKey* key, void* ptr, int devId)
{
(void)devId;
if (key == NULL) {
return BAD_FUNC_ARG;
}
return InitRsaKey_fips(key, ptr);
}
int wc_FreeRsaKey(RsaKey* key)
{
return FreeRsaKey_fips(key);
}
#ifndef WOLFSSL_RSA_VERIFY_ONLY
int wc_RsaPublicEncrypt(const byte* in, word32 inLen, byte* out,
word32 outLen, RsaKey* key, WC_RNG* rng)
{
if (in == NULL || out == NULL || key == NULL || rng == NULL) {
return BAD_FUNC_ARG;
}
return RsaPublicEncrypt_fips(in, inLen, out, outLen, key, rng);
}
#endif
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
int wc_RsaPrivateDecryptInline(byte* in, word32 inLen, byte** out,
RsaKey* key)
{
if (in == NULL || out == NULL || key == NULL) {
return BAD_FUNC_ARG;
}
return RsaPrivateDecryptInline_fips(in, inLen, out, key);
}
int wc_RsaPrivateDecrypt(const byte* in, word32 inLen, byte* out,
word32 outLen, RsaKey* key)
{
if (in == NULL || out == NULL || key == NULL) {
return BAD_FUNC_ARG;
}
return RsaPrivateDecrypt_fips(in, inLen, out, outLen, key);
}
int wc_RsaSSL_Sign(const byte* in, word32 inLen, byte* out,
word32 outLen, RsaKey* key, WC_RNG* rng)
{
if (in == NULL || out == NULL || key == NULL || inLen == 0) {
return BAD_FUNC_ARG;
}
return RsaSSL_Sign_fips(in, inLen, out, outLen, key, rng);
}
#endif
int wc_RsaSSL_VerifyInline(byte* in, word32 inLen, byte** out, RsaKey* key)
{
if (in == NULL || out == NULL || key == NULL) {
return BAD_FUNC_ARG;
}
return RsaSSL_VerifyInline_fips(in, inLen, out, key);
}
int wc_RsaSSL_Verify(const byte* in, word32 inLen, byte* out,
word32 outLen, RsaKey* key)
{
if (in == NULL || out == NULL || key == NULL || inLen == 0) {
return BAD_FUNC_ARG;
}
return RsaSSL_Verify_fips(in, inLen, out, outLen, key);
}
int wc_RsaEncryptSize(RsaKey* key)
{
if (key == NULL) {
return BAD_FUNC_ARG;
}
return RsaEncryptSize_fips(key);
}
#ifndef WOLFSSL_RSA_VERIFY_ONLY
int wc_RsaFlattenPublicKey(RsaKey* key, byte* a, word32* aSz, byte* b,
word32* bSz)
{
/* not specified as fips so not needing _fips */
return RsaFlattenPublicKey(key, a, aSz, b, bSz);
}
#endif
#ifdef WOLFSSL_KEY_GEN
int wc_MakeRsaKey(RsaKey* key, int size, long e, WC_RNG* rng)
{
return MakeRsaKey(key, size, e, rng);
}
#endif
/* these are functions in asn and are routed to wolfssl/wolfcrypt/asn.c
* wc_RsaPrivateKeyDecode
* wc_RsaPublicKeyDecode
*/
#else /* else build without fips, or for new fips */
#include <wolfssl/wolfcrypt/random.h>
#include <wolfssl/wolfcrypt/logging.h>
#ifdef WOLF_CRYPTO_CB
#include <wolfssl/wolfcrypt/cryptocb.h>
#endif
#ifdef NO_INLINE
#include <wolfssl/wolfcrypt/misc.h>
#else
#define WOLFSSL_MISC_INCLUDED
#include <wolfcrypt/src/misc.c>
#endif
enum {
RSA_STATE_NONE = 0,
RSA_STATE_ENCRYPT_PAD,
RSA_STATE_ENCRYPT_EXPTMOD,
RSA_STATE_ENCRYPT_RES,
RSA_STATE_DECRYPT_EXPTMOD,
RSA_STATE_DECRYPT_UNPAD,
RSA_STATE_DECRYPT_RES,
};
static void wc_RsaCleanup(RsaKey* key)
{
#ifndef WOLFSSL_RSA_VERIFY_INLINE
if (key && key->data) {
/* make sure any allocated memory is free'd */
if (key->dataIsAlloc) {
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
if (key->type == RSA_PRIVATE_DECRYPT ||
key->type == RSA_PRIVATE_ENCRYPT) {
ForceZero(key->data, key->dataLen);
}
#endif
XFREE(key->data, key->heap, DYNAMIC_TYPE_WOLF_BIGINT);
key->dataIsAlloc = 0;
}
key->data = NULL;
key->dataLen = 0;
}
#else
(void)key;
#endif
}
int wc_InitRsaKey_ex(RsaKey* key, void* heap, int devId)
{
int ret = 0;
if (key == NULL) {
return BAD_FUNC_ARG;
}
XMEMSET(key, 0, sizeof(RsaKey));
key->type = RSA_TYPE_UNKNOWN;
key->state = RSA_STATE_NONE;
key->heap = heap;
#ifndef WOLFSSL_RSA_VERIFY_INLINE
key->dataIsAlloc = 0;
key->data = NULL;
#endif
key->dataLen = 0;
#ifdef WC_RSA_BLINDING
key->rng = NULL;
#endif
#ifdef WOLF_CRYPTO_CB
key->devId = devId;
#else
(void)devId;
#endif
#ifdef WOLFSSL_ASYNC_CRYPT
#ifdef WOLFSSL_CERT_GEN
XMEMSET(&key->certSignCtx, 0, sizeof(CertSignCtx));
#endif
#ifdef WC_ASYNC_ENABLE_RSA
/* handle as async */
ret = wolfAsync_DevCtxInit(&key->asyncDev, WOLFSSL_ASYNC_MARKER_RSA,
key->heap, devId);
if (ret != 0)
return ret;
#endif /* WC_ASYNC_ENABLE_RSA */
#endif /* WOLFSSL_ASYNC_CRYPT */
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
ret = mp_init_multi(&key->n, &key->e, NULL, NULL, NULL, NULL);
if (ret != MP_OKAY)
return ret;
#if !defined(WOLFSSL_KEY_GEN) && !defined(OPENSSL_EXTRA) && defined(RSA_LOW_MEM)
ret = mp_init_multi(&key->d, &key->p, &key->q, NULL, NULL, NULL);
#else
ret = mp_init_multi(&key->d, &key->p, &key->q, &key->dP, &key->dQ, &key->u);
#endif
if (ret != MP_OKAY) {
mp_clear(&key->n);
mp_clear(&key->e);
return ret;
}
#else
ret = mp_init(&key->n);
if (ret != MP_OKAY)
return ret;
ret = mp_init(&key->e);
if (ret != MP_OKAY) {
mp_clear(&key->n);
return ret;
}
#endif
#ifdef WOLFSSL_XILINX_CRYPT
key->pubExp = 0;
key->mod = NULL;
#endif
#ifdef WOLFSSL_AFALG_XILINX_RSA
key->alFd = WC_SOCK_NOTSET;
key->rdFd = WC_SOCK_NOTSET;
#endif
return ret;
}
int wc_InitRsaKey(RsaKey* key, void* heap)
{
return wc_InitRsaKey_ex(key, heap, INVALID_DEVID);
}
#ifdef HAVE_PKCS11
int wc_InitRsaKey_Id(RsaKey* key, unsigned char* id, int len, void* heap,
int devId)
{
int ret = 0;
if (key == NULL)
ret = BAD_FUNC_ARG;
if (ret == 0 && (len < 0 || len > RSA_MAX_ID_LEN))
ret = BUFFER_E;
if (ret == 0)
ret = wc_InitRsaKey_ex(key, heap, devId);
if (ret == 0 && id != NULL && len != 0) {
XMEMCPY(key->id, id, len);
key->idLen = len;
}
return ret;
}
#endif
#ifdef WOLFSSL_XILINX_CRYPT
#define MAX_E_SIZE 4
/* Used to setup hardware state
*
* key the RSA key to setup
*
* returns 0 on success
*/
int wc_InitRsaHw(RsaKey* key)
{
unsigned char* m; /* RSA modulous */
word32 e = 0; /* RSA public exponent */
int mSz;
int eSz;
if (key == NULL) {
return BAD_FUNC_ARG;
}
mSz = mp_unsigned_bin_size(&(key->n));
m = (unsigned char*)XMALLOC(mSz, key->heap, DYNAMIC_TYPE_KEY);
if (m == NULL) {
return MEMORY_E;
}
if (mp_to_unsigned_bin(&(key->n), m) != MP_OKAY) {
WOLFSSL_MSG("Unable to get RSA key modulus");
XFREE(m, key->heap, DYNAMIC_TYPE_KEY);
return MP_READ_E;
}
eSz = mp_unsigned_bin_size(&(key->e));
if (eSz > MAX_E_SIZE) {
WOLFSSL_MSG("Exponent of size 4 bytes expected");
XFREE(m, key->heap, DYNAMIC_TYPE_KEY);
return BAD_FUNC_ARG;
}
if (mp_to_unsigned_bin(&(key->e), (byte*)&e + (MAX_E_SIZE - eSz))
!= MP_OKAY) {
XFREE(m, key->heap, DYNAMIC_TYPE_KEY);
WOLFSSL_MSG("Unable to get RSA key exponent");
return MP_READ_E;
}
/* check for existing mod buffer to avoid memory leak */
if (key->mod != NULL) {
XFREE(key->mod, key->heap, DYNAMIC_TYPE_KEY);
}
key->pubExp = e;
key->mod = m;
if (XSecure_RsaInitialize(&(key->xRsa), key->mod, NULL,
(byte*)&(key->pubExp)) != XST_SUCCESS) {
WOLFSSL_MSG("Unable to initialize RSA on hardware");
XFREE(m, key->heap, DYNAMIC_TYPE_KEY);
return BAD_STATE_E;
}
#ifdef WOLFSSL_XILINX_PATCH
/* currently a patch of xsecure_rsa.c for 2048 bit keys */
if (wc_RsaEncryptSize(key) == 256) {
if (XSecure_RsaSetSize(&(key->xRsa), 2048) != XST_SUCCESS) {
WOLFSSL_MSG("Unable to set RSA key size on hardware");
XFREE(m, key->heap, DYNAMIC_TYPE_KEY);
return BAD_STATE_E;
}
}
#endif
return 0;
} /* WOLFSSL_XILINX_CRYPT*/
#elif defined(WOLFSSL_CRYPTOCELL)
int wc_InitRsaHw(RsaKey* key)
{
CRYSError_t ret = 0;
byte e[3];
word32 eSz = sizeof(e);
byte n[256];
word32 nSz = sizeof(n);
byte d[256];
word32 dSz = sizeof(d);
byte p[128];
word32 pSz = sizeof(p);
byte q[128];
word32 qSz = sizeof(q);
if (key == NULL) {
return BAD_FUNC_ARG;
}
ret = wc_RsaExportKey(key, e, &eSz, n, &nSz, d, &dSz, p, &pSz, q, &qSz);
if (ret != 0)
return MP_READ_E;
ret = CRYS_RSA_Build_PubKey(&key->ctx.pubKey, e, eSz, n, nSz);
if (ret != SA_SILIB_RET_OK){
WOLFSSL_MSG("CRYS_RSA_Build_PubKey failed");
return ret;
}
ret = CRYS_RSA_Build_PrivKey(&key->ctx.privKey, d, dSz, e, eSz, n, nSz);
if (ret != SA_SILIB_RET_OK){
WOLFSSL_MSG("CRYS_RSA_Build_PrivKey failed");
return ret;
}
key->type = RSA_PRIVATE;
return 0;
}
static int cc310_RSA_GenerateKeyPair(RsaKey* key, int size, long e)
{
CRYSError_t ret = 0;
CRYS_RSAKGData_t KeyGenData;
CRYS_RSAKGFipsContext_t FipsCtx;
byte ex[3];
uint16_t eSz = sizeof(ex);
byte n[256];
uint16_t nSz = sizeof(n);
ret = CRYS_RSA_KG_GenerateKeyPair(&wc_rndState,
wc_rndGenVectFunc,
(byte*)&e,
3*sizeof(uint8_t),
size,
&key->ctx.privKey,
&key->ctx.pubKey,
&KeyGenData,
&FipsCtx);
if (ret != SA_SILIB_RET_OK){
WOLFSSL_MSG("CRYS_RSA_KG_GenerateKeyPair failed");
return ret;
}
ret = CRYS_RSA_Get_PubKey(&key->ctx.pubKey, ex, &eSz, n, &nSz);
if (ret != SA_SILIB_RET_OK){
WOLFSSL_MSG("CRYS_RSA_Get_PubKey failed");
return ret;
}
ret = wc_RsaPublicKeyDecodeRaw(n, nSz, ex, eSz, key);
key->type = RSA_PRIVATE;
return ret;
}
#endif /* WOLFSSL_CRYPTOCELL */
int wc_FreeRsaKey(RsaKey* key)
{
int ret = 0;
if (key == NULL) {
return BAD_FUNC_ARG;
}
wc_RsaCleanup(key);
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA)
wolfAsync_DevCtxFree(&key->asyncDev, WOLFSSL_ASYNC_MARKER_RSA);
#endif
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
if (key->type == RSA_PRIVATE) {
#if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)
mp_forcezero(&key->u);
mp_forcezero(&key->dQ);
mp_forcezero(&key->dP);
#endif
mp_forcezero(&key->q);
mp_forcezero(&key->p);
mp_forcezero(&key->d);
}
/* private part */
#if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)
mp_clear(&key->u);
mp_clear(&key->dQ);
mp_clear(&key->dP);
#endif
mp_clear(&key->q);
mp_clear(&key->p);
mp_clear(&key->d);
#endif /* WOLFSSL_RSA_PUBLIC_ONLY */
/* public part */
mp_clear(&key->e);
mp_clear(&key->n);
#ifdef WOLFSSL_XILINX_CRYPT
XFREE(key->mod, key->heap, DYNAMIC_TYPE_KEY);
key->mod = NULL;
#endif
#ifdef WOLFSSL_AFALG_XILINX_RSA
/* make sure that sockets are closed on cleanup */
if (key->alFd > 0) {
close(key->alFd);
key->alFd = WC_SOCK_NOTSET;
}
if (key->rdFd > 0) {
close(key->rdFd);
key->rdFd = WC_SOCK_NOTSET;
}
#endif
return ret;
}
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
#if defined(WOLFSSL_KEY_GEN) && !defined(WOLFSSL_NO_RSA_KEY_CHECK)
/* Check the pair-wise consistency of the RSA key.
* From NIST SP 800-56B, section 6.4.1.1.
* Verify that k = (k^e)^d, for some k: 1 < k < n-1. */
int wc_CheckRsaKey(RsaKey* key)
{
#if defined(WOLFSSL_CRYPTOCELL)
return 0;
#endif
#ifdef WOLFSSL_SMALL_STACK
mp_int *k = NULL, *tmp = NULL;
#else
mp_int k[1], tmp[1];
#endif
int ret = 0;
#ifdef WOLFSSL_SMALL_STACK
k = (mp_int*)XMALLOC(sizeof(mp_int) * 2, NULL, DYNAMIC_TYPE_RSA);
if (k == NULL)
return MEMORY_E;
tmp = k + 1;
#endif
if (mp_init_multi(k, tmp, NULL, NULL, NULL, NULL) != MP_OKAY)
ret = MP_INIT_E;
if (ret == 0) {
if (key == NULL)
ret = BAD_FUNC_ARG;
}
if (ret == 0) {
if (mp_set_int(k, 0x2342) != MP_OKAY)
ret = MP_READ_E;
}
#ifdef WOLFSSL_HAVE_SP_RSA
if (ret == 0) {
switch (mp_count_bits(&key->n)) {
#ifndef WOLFSSL_SP_NO_2048
case 2048:
ret = sp_ModExp_2048(k, &key->e, &key->n, tmp);
if (ret != 0)
ret = MP_EXPTMOD_E;
if (ret == 0) {
ret = sp_ModExp_2048(tmp, &key->d, &key->n, tmp);
if (ret != 0)
ret = MP_EXPTMOD_E;
}
break;
#endif /* WOLFSSL_SP_NO_2048 */
#ifndef WOLFSSL_SP_NO_3072
case 3072:
ret = sp_ModExp_3072(k, &key->e, &key->n, tmp);
if (ret != 0)
ret = MP_EXPTMOD_E;
if (ret == 0) {
ret = sp_ModExp_3072(tmp, &key->d, &key->n, tmp);
if (ret != 0)
ret = MP_EXPTMOD_E;
}
break;
#endif /* WOLFSSL_SP_NO_3072 */
#ifdef WOLFSSL_SP_4096
case 4096:
ret = sp_ModExp_4096(k, &key->e, &key->n, tmp);
if (ret != 0)
ret = MP_EXPTMOD_E;
if (ret == 0) {
ret = sp_ModExp_4096(tmp, &key->d, &key->n, tmp);
if (ret != 0)
ret = MP_EXPTMOD_E;
}
break;
#endif /* WOLFSSL_SP_4096 */
default:
/* If using only single prcsision math then issue key size error,
otherwise fall-back to multi-precision math calculation */
#ifdef WOLFSSL_SP_MATH
ret = WC_KEY_SIZE_E;
#endif
break;
}
}
#endif /* WOLFSSL_HAVE_SP_RSA */
#ifndef WOLFSSL_SP_MATH
if (ret == 0) {
if (mp_exptmod(k, &key->e, &key->n, tmp) != MP_OKAY)
ret = MP_EXPTMOD_E;
}
if (ret == 0) {
if (mp_exptmod(tmp, &key->d, &key->n, tmp) != MP_OKAY)
ret = MP_EXPTMOD_E;
}
#endif /* !WOLFSSL_SP_MATH */
if (ret == 0) {
if (mp_cmp(k, tmp) != MP_EQ)
ret = RSA_KEY_PAIR_E;
}
/* Check d is less than n. */
if (ret == 0 ) {
if (mp_cmp(&key->d, &key->n) != MP_LT) {
ret = MP_EXPTMOD_E;
}
}
/* Check p*q = n. */
if (ret == 0 ) {
if (mp_mul(&key->p, &key->q, tmp) != MP_OKAY) {
ret = MP_EXPTMOD_E;
}
}
if (ret == 0 ) {
if (mp_cmp(&key->n, tmp) != MP_EQ) {
ret = MP_EXPTMOD_E;
}
}
/* Check dP, dQ and u if they exist */
if (ret == 0 && !mp_iszero(&key->dP)) {
if (mp_sub_d(&key->p, 1, tmp) != MP_OKAY) {
ret = MP_EXPTMOD_E;
}
/* Check dP <= p-1. */
if (ret == 0) {
if (mp_cmp(&key->dP, tmp) != MP_LT) {
ret = MP_EXPTMOD_E;
}
}
/* Check e*dP mod p-1 = 1. (dP = 1/e mod p-1) */
if (ret == 0) {
if (mp_mulmod(&key->dP, &key->e, tmp, tmp) != MP_OKAY) {
ret = MP_EXPTMOD_E;
}
}
if (ret == 0 ) {
if (!mp_isone(tmp)) {
ret = MP_EXPTMOD_E;
}
}
if (ret == 0) {
if (mp_sub_d(&key->q, 1, tmp) != MP_OKAY) {
ret = MP_EXPTMOD_E;
}
}
/* Check dQ <= q-1. */
if (ret == 0) {
if (mp_cmp(&key->dQ, tmp) != MP_LT) {
ret = MP_EXPTMOD_E;
}
}
/* Check e*dP mod p-1 = 1. (dQ = 1/e mod q-1) */
if (ret == 0) {
if (mp_mulmod(&key->dQ, &key->e, tmp, tmp) != MP_OKAY) {
ret = MP_EXPTMOD_E;
}
}
if (ret == 0 ) {
if (!mp_isone(tmp)) {
ret = MP_EXPTMOD_E;
}
}
/* Check u <= p. */
if (ret == 0) {
if (mp_cmp(&key->u, &key->p) != MP_LT) {
ret = MP_EXPTMOD_E;
}
}
/* Check u*q mod p = 1. (u = 1/q mod p) */
if (ret == 0) {
if (mp_mulmod(&key->u, &key->q, &key->p, tmp) != MP_OKAY) {
ret = MP_EXPTMOD_E;
}
}
if (ret == 0 ) {
if (!mp_isone(tmp)) {
ret = MP_EXPTMOD_E;
}
}
}
mp_forcezero(tmp);
mp_clear(tmp);
mp_clear(k);
#ifdef WOLFSSL_SMALL_STACK
XFREE(k, NULL, DYNAMIC_TYPE_RSA);
#endif
return ret;
}
#endif /* WOLFSSL_KEY_GEN && !WOLFSSL_NO_RSA_KEY_CHECK */
#endif /* WOLFSSL_RSA_PUBLIC_ONLY */
#if !defined(WC_NO_RSA_OAEP) || defined(WC_RSA_PSS)
/* Uses MGF1 standard as a mask generation function
hType: hash type used
seed: seed to use for generating mask
seedSz: size of seed buffer
out: mask output after generation
outSz: size of output buffer
*/
#if !defined(NO_SHA) || !defined(NO_SHA256) || defined(WOLFSSL_SHA384) || defined(WOLFSSL_SHA512)
static int RsaMGF1(enum wc_HashType hType, byte* seed, word32 seedSz,
byte* out, word32 outSz, void* heap)
{
byte* tmp;
/* needs to be large enough for seed size plus counter(4) */
byte tmpA[WC_MAX_DIGEST_SIZE + 4];
byte tmpF; /* 1 if dynamic memory needs freed */
word32 tmpSz;
int hLen;
int ret;
word32 counter;
word32 idx;
hLen = wc_HashGetDigestSize(hType);
counter = 0;
idx = 0;
(void)heap;
/* check error return of wc_HashGetDigestSize */
if (hLen < 0) {
return hLen;
}
/* if tmp is not large enough than use some dynamic memory */
if ((seedSz + 4) > sizeof(tmpA) || (word32)hLen > sizeof(tmpA)) {
/* find largest amount of memory needed which will be the max of
* hLen and (seedSz + 4) since tmp is used to store the hash digest */
tmpSz = ((seedSz + 4) > (word32)hLen)? seedSz + 4: (word32)hLen;
tmp = (byte*)XMALLOC(tmpSz, heap, DYNAMIC_TYPE_RSA_BUFFER);
if (tmp == NULL) {
return MEMORY_E;
}
tmpF = 1; /* make sure to free memory when done */
}
else {
/* use array on the stack */
tmpSz = sizeof(tmpA);
tmp = tmpA;
tmpF = 0; /* no need to free memory at end */
}
do {
int i = 0;
XMEMCPY(tmp, seed, seedSz);
/* counter to byte array appended to tmp */
tmp[seedSz] = (byte)((counter >> 24) & 0xFF);
tmp[seedSz + 1] = (byte)((counter >> 16) & 0xFF);
tmp[seedSz + 2] = (byte)((counter >> 8) & 0xFF);
tmp[seedSz + 3] = (byte)((counter) & 0xFF);
/* hash and append to existing output */
if ((ret = wc_Hash(hType, tmp, (seedSz + 4), tmp, tmpSz)) != 0) {
/* check for if dynamic memory was needed, then free */
if (tmpF) {
XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
}
return ret;
}
for (i = 0; i < hLen && idx < outSz; i++) {
out[idx++] = tmp[i];
}
counter++;
} while (idx < outSz);
/* check for if dynamic memory was needed, then free */
if (tmpF) {
XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
}
return 0;
}
#endif /* SHA2 Hashes */
/* helper function to direct which mask generation function is used
switched on type input
*/
static int RsaMGF(int type, byte* seed, word32 seedSz, byte* out,
word32 outSz, void* heap)
{
int ret;
switch(type) {
#ifndef NO_SHA
case WC_MGF1SHA1:
ret = RsaMGF1(WC_HASH_TYPE_SHA, seed, seedSz, out, outSz, heap);
break;
#endif
#ifndef NO_SHA256
#ifdef WOLFSSL_SHA224
case WC_MGF1SHA224:
ret = RsaMGF1(WC_HASH_TYPE_SHA224, seed, seedSz, out, outSz, heap);
break;
#endif
case WC_MGF1SHA256:
ret = RsaMGF1(WC_HASH_TYPE_SHA256, seed, seedSz, out, outSz, heap);
break;
#endif
#ifdef WOLFSSL_SHA384
case WC_MGF1SHA384:
ret = RsaMGF1(WC_HASH_TYPE_SHA384, seed, seedSz, out, outSz, heap);
break;
#endif
#ifdef WOLFSSL_SHA512
case WC_MGF1SHA512:
ret = RsaMGF1(WC_HASH_TYPE_SHA512, seed, seedSz, out, outSz, heap);
break;
#endif
default:
WOLFSSL_MSG("Unknown MGF type: check build options");
ret = BAD_FUNC_ARG;
}
/* in case of default avoid unused warning */
(void)seed;
(void)seedSz;
(void)out;
(void)outSz;
(void)heap;
return ret;
}
#endif /* !WC_NO_RSA_OAEP || WC_RSA_PSS */
/* Padding */
#ifndef WOLFSSL_RSA_VERIFY_ONLY
#ifndef WC_NO_RNG
#ifndef WC_NO_RSA_OAEP
static int RsaPad_OAEP(const byte* input, word32 inputLen, byte* pkcsBlock,
word32 pkcsBlockLen, byte padValue, WC_RNG* rng,
enum wc_HashType hType, int mgf, byte* optLabel, word32 labelLen,
void* heap)
{
int ret;
int hLen;
int psLen;
int i;
word32 idx;
byte* dbMask;
#ifdef WOLFSSL_SMALL_STACK
byte* lHash = NULL;
byte* seed = NULL;
#else
/* must be large enough to contain largest hash */
byte lHash[WC_MAX_DIGEST_SIZE];
byte seed[ WC_MAX_DIGEST_SIZE];
#endif
/* no label is allowed, but catch if no label provided and length > 0 */
if (optLabel == NULL && labelLen > 0) {
return BUFFER_E;
}
/* limit of label is the same as limit of hash function which is massive */
hLen = wc_HashGetDigestSize(hType);
if (hLen < 0) {
return hLen;
}
#ifdef WOLFSSL_SMALL_STACK
lHash = (byte*)XMALLOC(hLen, heap, DYNAMIC_TYPE_RSA_BUFFER);
if (lHash == NULL) {
return MEMORY_E;
}
seed = (byte*)XMALLOC(hLen, heap, DYNAMIC_TYPE_RSA_BUFFER);
if (seed == NULL) {
XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
return MEMORY_E;
}
#else
/* hLen should never be larger than lHash since size is max digest size,
but check before blindly calling wc_Hash */
if ((word32)hLen > sizeof(lHash)) {
WOLFSSL_MSG("OAEP lHash to small for digest!!");
return MEMORY_E;
}
#endif
if ((ret = wc_Hash(hType, optLabel, labelLen, lHash, hLen)) != 0) {
WOLFSSL_MSG("OAEP hash type possibly not supported or lHash to small");
#ifdef WOLFSSL_SMALL_STACK
XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
#endif
return ret;
}
/* handles check of location for idx as well as psLen, cast to int to check
for pkcsBlockLen(k) - 2 * hLen - 2 being negative
This check is similar to decryption where k > 2 * hLen + 2 as msg
size approaches 0. In decryption if k is less than or equal -- then there
is no possible room for msg.
k = RSA key size
hLen = hash digest size -- will always be >= 0 at this point
*/
if ((word32)(2 * hLen + 2) > pkcsBlockLen) {
WOLFSSL_MSG("OAEP pad error hash to big for RSA key size");
#ifdef WOLFSSL_SMALL_STACK
XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
#endif
return BAD_FUNC_ARG;
}
if (inputLen > (pkcsBlockLen - 2 * hLen - 2)) {
WOLFSSL_MSG("OAEP pad error message too long");
#ifdef WOLFSSL_SMALL_STACK
XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
#endif
return BAD_FUNC_ARG;
}
/* concatenate lHash || PS || 0x01 || msg */
idx = pkcsBlockLen - 1 - inputLen;
psLen = pkcsBlockLen - inputLen - 2 * hLen - 2;
if (pkcsBlockLen < inputLen) { /*make sure not writing over end of buffer */
#ifdef WOLFSSL_SMALL_STACK
XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
#endif
return BUFFER_E;
}
XMEMCPY(pkcsBlock + (pkcsBlockLen - inputLen), input, inputLen);
pkcsBlock[idx--] = 0x01; /* PS and M separator */
while (psLen > 0 && idx > 0) {
pkcsBlock[idx--] = 0x00;
psLen--;
}
idx = idx - hLen + 1;
XMEMCPY(pkcsBlock + idx, lHash, hLen);
/* generate random seed */
if ((ret = wc_RNG_GenerateBlock(rng, seed, hLen)) != 0) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
#endif
return ret;
}
/* create maskedDB from dbMask */
dbMask = (byte*)XMALLOC(pkcsBlockLen - hLen - 1, heap, DYNAMIC_TYPE_RSA);
if (dbMask == NULL) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
#endif
return MEMORY_E;
}
XMEMSET(dbMask, 0, pkcsBlockLen - hLen - 1); /* help static analyzer */
ret = RsaMGF(mgf, seed, hLen, dbMask, pkcsBlockLen - hLen - 1, heap);
if (ret != 0) {
XFREE(dbMask, heap, DYNAMIC_TYPE_RSA);
#ifdef WOLFSSL_SMALL_STACK
XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
#endif
return ret;
}
i = 0;
idx = hLen + 1;
while (idx < pkcsBlockLen && (word32)i < (pkcsBlockLen - hLen -1)) {
pkcsBlock[idx] = dbMask[i++] ^ pkcsBlock[idx];
idx++;
}
XFREE(dbMask, heap, DYNAMIC_TYPE_RSA);
/* create maskedSeed from seedMask */
idx = 0;
pkcsBlock[idx++] = 0x00;
/* create seedMask inline */
if ((ret = RsaMGF(mgf, pkcsBlock + hLen + 1, pkcsBlockLen - hLen - 1,
pkcsBlock + 1, hLen, heap)) != 0) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
#endif
return ret;
}
/* xor created seedMask with seed to make maskedSeed */
i = 0;
while (idx < (word32)(hLen + 1) && i < hLen) {
pkcsBlock[idx] = pkcsBlock[idx] ^ seed[i++];
idx++;
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
#endif
(void)padValue;
return 0;
}
#endif /* !WC_NO_RSA_OAEP */
#ifdef WC_RSA_PSS
/* 0x00 .. 0x00 0x01 | Salt | Gen Hash | 0xbc
* XOR MGF over all bytes down to end of Salt
* Gen Hash = HASH(8 * 0x00 | Message Hash | Salt)
*
* input Digest of the message.
* inputLen Length of digest.
* pkcsBlock Buffer to write to.
* pkcsBlockLen Length of buffer to write to.
* rng Random number generator (for salt).
* htype Hash function to use.
* mgf Mask generation function.
* saltLen Length of salt to put in padding.
* bits Length of key in bits.
* heap Used for dynamic memory allocation.
* returns 0 on success, PSS_SALTLEN_E when the salt length is invalid
* and other negative values on error.
*/
static int RsaPad_PSS(const byte* input, word32 inputLen, byte* pkcsBlock,
word32 pkcsBlockLen, WC_RNG* rng, enum wc_HashType hType, int mgf,
int saltLen, int bits, void* heap)
{
int ret = 0;
int hLen, i, o, maskLen, hiBits;
byte* m;
byte* s;
#if defined(WOLFSSL_PSS_LONG_SALT) || defined(WOLFSSL_PSS_SALT_LEN_DISCOVER)
#if defined(WOLFSSL_NO_MALLOC) && !defined(WOLFSSL_STATIC_MEMORY)
byte salt[RSA_MAX_SIZE/8 + RSA_PSS_PAD_SZ];
#else
byte* salt = NULL;
#endif
#else
byte salt[WC_MAX_DIGEST_SIZE];
#endif
#if defined(WOLFSSL_PSS_LONG_SALT) || defined(WOLFSSL_PSS_SALT_LEN_DISCOVER)
if (pkcsBlockLen > RSA_MAX_SIZE/8) {
return MEMORY_E;
}
#endif
hLen = wc_HashGetDigestSize(hType);
if (hLen < 0)
return hLen;
if ((int)inputLen != hLen) {
return BAD_FUNC_ARG;
}
hiBits = (bits - 1) & 0x7;
if (hiBits == 0) {
/* Per RFC8017, set the leftmost 8emLen - emBits bits of the
leftmost octet in DB to zero.
*/
*(pkcsBlock++) = 0;
pkcsBlockLen--;
}
if (saltLen == RSA_PSS_SALT_LEN_DEFAULT) {
saltLen = hLen;
#ifdef WOLFSSL_SHA512
/* See FIPS 186-4 section 5.5 item (e). */
if (bits == 1024 && hLen == WC_SHA512_DIGEST_SIZE) {
saltLen = RSA_PSS_SALT_MAX_SZ;
}
#endif
}
#ifndef WOLFSSL_PSS_LONG_SALT
else if (saltLen > hLen) {
return PSS_SALTLEN_E;
}
#endif
#ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
else if (saltLen < RSA_PSS_SALT_LEN_DEFAULT) {
return PSS_SALTLEN_E;
}
#else
else if (saltLen == RSA_PSS_SALT_LEN_DISCOVER) {
saltLen = (int)pkcsBlockLen - hLen - 2;
if (saltLen < 0) {
return PSS_SALTLEN_E;
}
}
else if (saltLen < RSA_PSS_SALT_LEN_DISCOVER) {
return PSS_SALTLEN_E;
}
#endif
if ((int)pkcsBlockLen - hLen < saltLen + 2) {
return PSS_SALTLEN_E;
}
maskLen = pkcsBlockLen - 1 - hLen;
#if defined(WOLFSSL_PSS_LONG_SALT) || defined(WOLFSSL_PSS_SALT_LEN_DISCOVER)
#if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
salt = (byte*)XMALLOC(RSA_PSS_PAD_SZ + inputLen + saltLen, heap,
DYNAMIC_TYPE_RSA_BUFFER);
if (salt == NULL) {
return MEMORY_E;
}
#endif
s = m = salt;
XMEMSET(m, 0, RSA_PSS_PAD_SZ);
m += RSA_PSS_PAD_SZ;
XMEMCPY(m, input, inputLen);
m += inputLen;
o = (int)(m - s);
if (saltLen > 0) {
ret = wc_RNG_GenerateBlock(rng, m, saltLen);
if (ret == 0) {
m += saltLen;
}
}
#else
s = m = pkcsBlock;
XMEMSET(m, 0, RSA_PSS_PAD_SZ);
m += RSA_PSS_PAD_SZ;
XMEMCPY(m, input, inputLen);
m += inputLen;
o = 0;
if (saltLen > 0) {
ret = wc_RNG_GenerateBlock(rng, salt, saltLen);
if (ret == 0) {
XMEMCPY(m, salt, saltLen);
m += saltLen;
}
}
#endif
if (ret == 0) {
/* Put Hash at end of pkcsBlock - 1 */
ret = wc_Hash(hType, s, (word32)(m - s), pkcsBlock + maskLen, hLen);
}
if (ret == 0) {
/* Set the last eight bits or trailer field to the octet 0xbc */
pkcsBlock[pkcsBlockLen - 1] = RSA_PSS_PAD_TERM;
ret = RsaMGF(mgf, pkcsBlock + maskLen, hLen, pkcsBlock, maskLen, heap);
}
if (ret == 0) {
/* Clear the first high bit when "8emLen - emBits" is non-zero.
where emBits = n modBits - 1 */
if (hiBits)
pkcsBlock[0] &= (1 << hiBits) - 1;
m = pkcsBlock + maskLen - saltLen - 1;
*(m++) ^= 0x01;
for (i = 0; i < saltLen; i++) {
m[i] ^= salt[o + i];
}
}
#if defined(WOLFSSL_PSS_LONG_SALT) || defined(WOLFSSL_PSS_SALT_LEN_DISCOVER)
#if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
if (salt != NULL) {
XFREE(salt, heap, DYNAMIC_TYPE_RSA_BUFFER);
}
#endif
#endif
return ret;
}
#endif /* WC_RSA_PSS */
#endif /* !WC_NO_RNG */
static int RsaPad(const byte* input, word32 inputLen, byte* pkcsBlock,
word32 pkcsBlockLen, byte padValue, WC_RNG* rng)
{
if (input == NULL || inputLen == 0 || pkcsBlock == NULL ||
pkcsBlockLen == 0) {
return BAD_FUNC_ARG;
}
if (pkcsBlockLen - RSA_MIN_PAD_SZ < inputLen) {
WOLFSSL_MSG("RsaPad error, invalid length");
return RSA_PAD_E;
}
pkcsBlock[0] = 0x0; /* set first byte to zero and advance */
pkcsBlock++; pkcsBlockLen--;
pkcsBlock[0] = padValue; /* insert padValue */
if (padValue == RSA_BLOCK_TYPE_1) {
/* pad with 0xff bytes */
XMEMSET(&pkcsBlock[1], 0xFF, pkcsBlockLen - inputLen - 2);
}
else {
#if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WC_NO_RNG)
/* pad with non-zero random bytes */
word32 padLen, i;
int ret;
padLen = pkcsBlockLen - inputLen - 1;
ret = wc_RNG_GenerateBlock(rng, &pkcsBlock[1], padLen);
if (ret != 0) {
return ret;
}
/* remove zeros */
for (i = 1; i < padLen; i++) {
if (pkcsBlock[i] == 0) pkcsBlock[i] = 0x01;
}
#else
(void)rng;
return RSA_WRONG_TYPE_E;
#endif
}
pkcsBlock[pkcsBlockLen-inputLen-1] = 0; /* separator */
XMEMCPY(pkcsBlock+pkcsBlockLen-inputLen, input, inputLen);
return 0;
}
/* helper function to direct which padding is used */
int wc_RsaPad_ex(const byte* input, word32 inputLen, byte* pkcsBlock,
word32 pkcsBlockLen, byte padValue, WC_RNG* rng, int padType,
enum wc_HashType hType, int mgf, byte* optLabel, word32 labelLen,
int saltLen, int bits, void* heap)
{
int ret;
switch (padType)
{
case WC_RSA_PKCSV15_PAD:
/*WOLFSSL_MSG("wolfSSL Using RSA PKCSV15 padding");*/
ret = RsaPad(input, inputLen, pkcsBlock, pkcsBlockLen,
padValue, rng);
break;
#ifndef WC_NO_RNG
#ifndef WC_NO_RSA_OAEP
case WC_RSA_OAEP_PAD:
WOLFSSL_MSG("wolfSSL Using RSA OAEP padding");
ret = RsaPad_OAEP(input, inputLen, pkcsBlock, pkcsBlockLen,
padValue, rng, hType, mgf, optLabel, labelLen, heap);
break;
#endif
#ifdef WC_RSA_PSS
case WC_RSA_PSS_PAD:
WOLFSSL_MSG("wolfSSL Using RSA PSS padding");
ret = RsaPad_PSS(input, inputLen, pkcsBlock, pkcsBlockLen, rng,
hType, mgf, saltLen, bits, heap);
break;
#endif
#endif /* !WC_NO_RNG */
#ifdef WC_RSA_NO_PADDING
case WC_RSA_NO_PAD:
WOLFSSL_MSG("wolfSSL Using NO padding");
/* In the case of no padding being used check that input is exactly
* the RSA key length */
if (bits <= 0 || inputLen != ((word32)bits/WOLFSSL_BIT_SIZE)) {
WOLFSSL_MSG("Bad input size");
ret = RSA_PAD_E;
}
else {
XMEMCPY(pkcsBlock, input, inputLen);
ret = 0;
}
break;
#endif
default:
WOLFSSL_MSG("Unknown RSA Pad Type");
ret = RSA_PAD_E;
}
/* silence warning if not used with padding scheme */
(void)input;
(void)inputLen;
(void)pkcsBlock;
(void)pkcsBlockLen;
(void)padValue;
(void)rng;
(void)padType;
(void)hType;
(void)mgf;
(void)optLabel;
(void)labelLen;
(void)saltLen;
(void)bits;
(void)heap;
return ret;
}
#endif /* WOLFSSL_RSA_VERIFY_ONLY */
/* UnPadding */
#ifndef WC_NO_RSA_OAEP
/* UnPad plaintext, set start to *output, return length of plaintext,
* < 0 on error */
static int RsaUnPad_OAEP(byte *pkcsBlock, unsigned int pkcsBlockLen,
byte **output, enum wc_HashType hType, int mgf,
byte* optLabel, word32 labelLen, void* heap)
{
int hLen;
int ret;
byte h[WC_MAX_DIGEST_SIZE]; /* max digest size */
byte* tmp;
word32 idx;
/* no label is allowed, but catch if no label provided and length > 0 */
if (optLabel == NULL && labelLen > 0) {
return BUFFER_E;
}
hLen = wc_HashGetDigestSize(hType);
if ((hLen < 0) || (pkcsBlockLen < (2 * (word32)hLen + 2))) {
return BAD_FUNC_ARG;
}
tmp = (byte*)XMALLOC(pkcsBlockLen, heap, DYNAMIC_TYPE_RSA_BUFFER);
if (tmp == NULL) {
return MEMORY_E;
}
XMEMSET(tmp, 0, pkcsBlockLen);
/* find seedMask value */
if ((ret = RsaMGF(mgf, (byte*)(pkcsBlock + (hLen + 1)),
pkcsBlockLen - hLen - 1, tmp, hLen, heap)) != 0) {
XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
return ret;
}
/* xor seedMask value with maskedSeed to get seed value */
for (idx = 0; idx < (word32)hLen; idx++) {
tmp[idx] = tmp[idx] ^ pkcsBlock[1 + idx];
}
/* get dbMask value */
if ((ret = RsaMGF(mgf, tmp, hLen, tmp + hLen,
pkcsBlockLen - hLen - 1, heap)) != 0) {
XFREE(tmp, NULL, DYNAMIC_TYPE_RSA_BUFFER);
return ret;
}
/* get DB value by doing maskedDB xor dbMask */
for (idx = 0; idx < (pkcsBlockLen - hLen - 1); idx++) {
pkcsBlock[hLen + 1 + idx] = pkcsBlock[hLen + 1 + idx] ^ tmp[idx + hLen];
}
/* done with use of tmp buffer */
XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
/* advance idx to index of PS and msg separator, account for PS size of 0*/
idx = hLen + 1 + hLen;
while (idx < pkcsBlockLen && pkcsBlock[idx] == 0) {idx++;}
/* create hash of label for comparison with hash sent */
if ((ret = wc_Hash(hType, optLabel, labelLen, h, hLen)) != 0) {
return ret;
}
/* say no to chosen ciphertext attack.
Comparison of lHash, Y, and separator value needs to all happen in
constant time.
Attackers should not be able to get error condition from the timing of
these checks.
*/
ret = 0;
ret |= ConstantCompare(pkcsBlock + hLen + 1, h, hLen);
ret += pkcsBlock[idx++] ^ 0x01; /* separator value is 0x01 */
ret += pkcsBlock[0] ^ 0x00; /* Y, the first value, should be 0 */
/* Return 0 data length on error. */
idx = ctMaskSelInt(ctMaskEq(ret, 0), idx, pkcsBlockLen);
/* adjust pointer to correct location in array and return size of M */
*output = (byte*)(pkcsBlock + idx);
return pkcsBlockLen - idx;
}
#endif /* WC_NO_RSA_OAEP */
#ifdef WC_RSA_PSS
/* 0x00 .. 0x00 0x01 | Salt | Gen Hash | 0xbc
* MGF over all bytes down to end of Salt
*
* pkcsBlock Buffer holding decrypted data.
* pkcsBlockLen Length of buffer.
* htype Hash function to use.
* mgf Mask generation function.
* saltLen Length of salt to put in padding.
* bits Length of key in bits.
* heap Used for dynamic memory allocation.
* returns the sum of salt length and SHA-256 digest size on success.
* Otherwise, PSS_SALTLEN_E for an incorrect salt length,
* WC_KEY_SIZE_E for an incorrect encoded message (EM) size
and other negative values on error.
*/
static int RsaUnPad_PSS(byte *pkcsBlock, unsigned int pkcsBlockLen,
byte **output, enum wc_HashType hType, int mgf,
int saltLen, int bits, void* heap)
{
int ret;
byte* tmp;
int hLen, i, maskLen;
#ifdef WOLFSSL_SHA512
int orig_bits = bits;
#endif
#if defined(WOLFSSL_NO_MALLOC) && !defined(WOLFSSL_STATIC_MEMORY)
byte tmp_buf[RSA_MAX_SIZE/8];
tmp = tmp_buf;
if (pkcsBlockLen > RSA_MAX_SIZE/8) {
return MEMORY_E;
}
#endif
hLen = wc_HashGetDigestSize(hType);
if (hLen < 0)
return hLen;
bits = (bits - 1) & 0x7;
if ((pkcsBlock[0] & (0xff << bits)) != 0) {
return BAD_PADDING_E;
}
if (bits == 0) {
pkcsBlock++;
pkcsBlockLen--;
}
maskLen = (int)pkcsBlockLen - 1 - hLen;
if (maskLen < 0) {
WOLFSSL_MSG("RsaUnPad_PSS: Hash too large");
return WC_KEY_SIZE_E;
}
if (saltLen == RSA_PSS_SALT_LEN_DEFAULT) {
saltLen = hLen;
#ifdef WOLFSSL_SHA512
/* See FIPS 186-4 section 5.5 item (e). */
if (orig_bits == 1024 && hLen == WC_SHA512_DIGEST_SIZE)
saltLen = RSA_PSS_SALT_MAX_SZ;
#endif
}
#ifndef WOLFSSL_PSS_LONG_SALT
else if (saltLen > hLen)
return PSS_SALTLEN_E;
#endif
#ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
else if (saltLen < RSA_PSS_SALT_LEN_DEFAULT)
return PSS_SALTLEN_E;
if (maskLen < saltLen + 1) {
return PSS_SALTLEN_E;
}
#else
else if (saltLen < RSA_PSS_SALT_LEN_DISCOVER)
return PSS_SALTLEN_E;
if (saltLen != RSA_PSS_SALT_LEN_DISCOVER && maskLen < saltLen + 1) {
return WC_KEY_SIZE_E;
}
#endif
if (pkcsBlock[pkcsBlockLen - 1] != RSA_PSS_PAD_TERM) {
WOLFSSL_MSG("RsaUnPad_PSS: Padding Term Error");
return BAD_PADDING_E;
}
#if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
tmp = (byte*)XMALLOC(maskLen, heap, DYNAMIC_TYPE_RSA_BUFFER);
if (tmp == NULL) {
return MEMORY_E;
}
#endif
if ((ret = RsaMGF(mgf, pkcsBlock + maskLen, hLen, tmp, maskLen,
heap)) != 0) {
XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
return ret;
}
tmp[0] &= (1 << bits) - 1;
pkcsBlock[0] &= (1 << bits) - 1;
#ifdef WOLFSSL_PSS_SALT_LEN_DISCOVER
if (saltLen == RSA_PSS_SALT_LEN_DISCOVER) {
for (i = 0; i < maskLen - 1; i++) {
if (tmp[i] != pkcsBlock[i]) {
break;
}
}
if (tmp[i] != (pkcsBlock[i] ^ 0x01)) {
XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
WOLFSSL_MSG("RsaUnPad_PSS: Padding Error Match");
return PSS_SALTLEN_RECOVER_E;
}
saltLen = maskLen - (i + 1);
}
else
#endif
{
for (i = 0; i < maskLen - 1 - saltLen; i++) {
if (tmp[i] != pkcsBlock[i]) {
XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
WOLFSSL_MSG("RsaUnPad_PSS: Padding Error Match");
return PSS_SALTLEN_E;
}
}
if (tmp[i] != (pkcsBlock[i] ^ 0x01)) {
XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
WOLFSSL_MSG("RsaUnPad_PSS: Padding Error End");
return PSS_SALTLEN_E;
}
}
for (i++; i < maskLen; i++)
pkcsBlock[i] ^= tmp[i];
#if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
#endif
*output = pkcsBlock + maskLen - saltLen;
return saltLen + hLen;
}
#endif
/* UnPad plaintext, set start to *output, return length of plaintext,
* < 0 on error */
static int RsaUnPad(const byte *pkcsBlock, unsigned int pkcsBlockLen,
byte **output, byte padValue)
{
int ret = BAD_FUNC_ARG;
word16 i;
#ifndef WOLFSSL_RSA_VERIFY_ONLY
byte invalid = 0;
#endif
if (output == NULL || pkcsBlockLen < 2 || pkcsBlockLen > 0xFFFF) {
return BAD_FUNC_ARG;
}
if (padValue == RSA_BLOCK_TYPE_1) {
/* First byte must be 0x00 and Second byte, block type, 0x01 */
if (pkcsBlock[0] != 0 || pkcsBlock[1] != RSA_BLOCK_TYPE_1) {
WOLFSSL_MSG("RsaUnPad error, invalid formatting");
return RSA_PAD_E;
}
/* check the padding until we find the separator */
for (i = 2; i < pkcsBlockLen && pkcsBlock[i++] == 0xFF; ) { }
/* Minimum of 11 bytes of pre-message data and must have separator. */
if (i < RSA_MIN_PAD_SZ || pkcsBlock[i-1] != 0) {
WOLFSSL_MSG("RsaUnPad error, bad formatting");
return RSA_PAD_E;
}
*output = (byte *)(pkcsBlock + i);
ret = pkcsBlockLen - i;
}
#ifndef WOLFSSL_RSA_VERIFY_ONLY
else {
word16 j;
word16 pastSep = 0;
/* Decrypted with private key - unpad must be constant time. */
for (i = 0, j = 2; j < pkcsBlockLen; j++) {
/* Update i if not passed the separator and at separator. */
i |= (~pastSep) & ctMask16Eq(pkcsBlock[j], 0x00) & (j + 1);
pastSep |= ctMask16Eq(pkcsBlock[j], 0x00);
}
/* Minimum of 11 bytes of pre-message data - including leading 0x00. */
invalid |= ctMaskLT(i, RSA_MIN_PAD_SZ);
/* Must have seen separator. */
invalid |= ~pastSep;
/* First byte must be 0x00. */
invalid |= ctMaskNotEq(pkcsBlock[0], 0x00);
/* Check against expected block type: padValue */
invalid |= ctMaskNotEq(pkcsBlock[1], padValue);
*output = (byte *)(pkcsBlock + i);
ret = ((int)~invalid) & (pkcsBlockLen - i);
}
#endif
return ret;
}
/* helper function to direct unpadding
*
* bits is the key modulus size in bits
*/
int wc_RsaUnPad_ex(byte* pkcsBlock, word32 pkcsBlockLen, byte** out,
byte padValue, int padType, enum wc_HashType hType,
int mgf, byte* optLabel, word32 labelLen, int saltLen,
int bits, void* heap)
{
int ret;
switch (padType) {
case WC_RSA_PKCSV15_PAD:
/*WOLFSSL_MSG("wolfSSL Using RSA PKCSV15 un-padding");*/
ret = RsaUnPad(pkcsBlock, pkcsBlockLen, out, padValue);
break;
#ifndef WC_NO_RSA_OAEP
case WC_RSA_OAEP_PAD:
WOLFSSL_MSG("wolfSSL Using RSA OAEP un-padding");
ret = RsaUnPad_OAEP((byte*)pkcsBlock, pkcsBlockLen, out,
hType, mgf, optLabel, labelLen, heap);
break;
#endif
#ifdef WC_RSA_PSS
case WC_RSA_PSS_PAD:
WOLFSSL_MSG("wolfSSL Using RSA PSS un-padding");
ret = RsaUnPad_PSS((byte*)pkcsBlock, pkcsBlockLen, out, hType, mgf,
saltLen, bits, heap);
break;
#endif
#ifdef WC_RSA_NO_PADDING
case WC_RSA_NO_PAD:
WOLFSSL_MSG("wolfSSL Using NO un-padding");
/* In the case of no padding being used check that input is exactly
* the RSA key length */
if (bits <= 0 || pkcsBlockLen !=
((word32)(bits+WOLFSSL_BIT_SIZE-1)/WOLFSSL_BIT_SIZE)) {
WOLFSSL_MSG("Bad input size");
ret = RSA_PAD_E;
}
else {
if (out != NULL) {
*out = pkcsBlock;
}
ret = pkcsBlockLen;
}
break;
#endif /* WC_RSA_NO_PADDING */
default:
WOLFSSL_MSG("Unknown RSA UnPad Type");
ret = RSA_PAD_E;
}
/* silence warning if not used with padding scheme */
(void)hType;
(void)mgf;
(void)optLabel;
(void)labelLen;
(void)saltLen;
(void)bits;
(void)heap;
return ret;
}
#ifdef WC_RSA_NONBLOCK
static int wc_RsaFunctionNonBlock(const byte* in, word32 inLen, byte* out,
word32* outLen, int type, RsaKey* key)
{
int ret = 0;
word32 keyLen, len;
if (key == NULL || key->nb == NULL) {
return BAD_FUNC_ARG;
}
if (key->nb->exptmod.state == TFM_EXPTMOD_NB_INIT) {
if (mp_init(&key->nb->tmp) != MP_OKAY) {
ret = MP_INIT_E;
}
if (ret == 0) {
if (mp_read_unsigned_bin(&key->nb->tmp, (byte*)in, inLen) != MP_OKAY) {
ret = MP_READ_E;
}
}
}
if (ret == 0) {
switch(type) {
case RSA_PRIVATE_DECRYPT:
case RSA_PRIVATE_ENCRYPT:
ret = fp_exptmod_nb(&key->nb->exptmod, &key->nb->tmp, &key->d,
&key->n, &key->nb->tmp);
if (ret == FP_WOULDBLOCK)
return ret;
if (ret != MP_OKAY)
ret = MP_EXPTMOD_E;
break;
case RSA_PUBLIC_ENCRYPT:
case RSA_PUBLIC_DECRYPT:
ret = fp_exptmod_nb(&key->nb->exptmod, &key->nb->tmp, &key->e,
&key->n, &key->nb->tmp);
if (ret == FP_WOULDBLOCK)
return ret;
if (ret != MP_OKAY)
ret = MP_EXPTMOD_E;
break;
default:
ret = RSA_WRONG_TYPE_E;
break;
}
}
if (ret == 0) {
keyLen = wc_RsaEncryptSize(key);
if (keyLen > *outLen)
ret = RSA_BUFFER_E;
}
if (ret == 0) {
len = mp_unsigned_bin_size(&key->nb->tmp);
/* pad front w/ zeros to match key length */
while (len < keyLen) {
*out++ = 0x00;
len++;
}
*outLen = keyLen;
/* convert */
if (mp_to_unsigned_bin(&key->nb->tmp, out) != MP_OKAY) {
ret = MP_TO_E;
}
}
mp_clear(&key->nb->tmp);
return ret;
}
#endif /* WC_RSA_NONBLOCK */
#ifdef WOLFSSL_XILINX_CRYPT
/*
* Xilinx hardened crypto acceleration.
*
* Returns 0 on success and negative values on error.
*/
static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out,
word32* outLen, int type, RsaKey* key, WC_RNG* rng)
{
int ret = 0;
word32 keyLen;
(void)rng;
keyLen = wc_RsaEncryptSize(key);
if (keyLen > *outLen) {
WOLFSSL_MSG("Output buffer is not big enough");
return BAD_FUNC_ARG;
}
if (inLen != keyLen) {
WOLFSSL_MSG("Expected that inLen equals RSA key length");
return BAD_FUNC_ARG;
}
switch(type) {
case RSA_PRIVATE_DECRYPT:
case RSA_PRIVATE_ENCRYPT:
#ifdef WOLFSSL_XILINX_CRYPTO_OLD
/* Currently public exponent is loaded by default.
* In SDK 2017.1 RSA exponent values are expected to be of 4 bytes
* leading to private key operations with Xsecure_RsaDecrypt not being
* supported */
ret = RSA_WRONG_TYPE_E;
#else
{
byte *d;
int dSz;
XSecure_Rsa rsa;
dSz = mp_unsigned_bin_size(&key->d);
d = (byte*)XMALLOC(dSz, key->heap, DYNAMIC_TYPE_PRIVATE_KEY);
if (d == NULL) {
ret = MEMORY_E;
}
else {
ret = mp_to_unsigned_bin(&key->d, d);
XSecure_RsaInitialize(&rsa, key->mod, NULL, d);
}
if (ret == 0) {
if (XSecure_RsaPrivateDecrypt(&rsa, (u8*)in, inLen, out) !=
XST_SUCCESS) {
ret = BAD_STATE_E;
}
}
if (d != NULL) {
XFREE(d, key->heap, DYNAMIC_TYPE_PRIVATE_KEY);
}
}
#endif
break;
case RSA_PUBLIC_ENCRYPT:
case RSA_PUBLIC_DECRYPT:
#ifdef WOLFSSL_XILINX_CRYPTO_OLD
if (XSecure_RsaDecrypt(&(key->xRsa), in, out) != XST_SUCCESS) {
ret = BAD_STATE_E;
}
#else
/* starting at Xilinx release 2019 the function XSecure_RsaDecrypt was removed */
if (XSecure_RsaPublicEncrypt(&(key->xRsa), (u8*)in, inLen, out) != XST_SUCCESS) {
WOLFSSL_MSG("Error happened when calling hardware RSA public operation");
ret = BAD_STATE_E;
}
#endif
break;
default:
ret = RSA_WRONG_TYPE_E;
}
*outLen = keyLen;
return ret;
}
#elif defined(WOLFSSL_AFALG_XILINX_RSA)
#ifndef ERROR_OUT
#define ERROR_OUT(x) ret = (x); goto done
#endif
static const char WC_TYPE_ASYMKEY[] = "skcipher";
static const char WC_NAME_RSA[] = "xilinx-zynqmp-rsa";
#ifndef MAX_XILINX_RSA_KEY
/* max key size of 4096 bits / 512 bytes */
#define MAX_XILINX_RSA_KEY 512
#endif
static const byte XILINX_RSA_FLAG[] = {0x1};
/* AF_ALG implementation of RSA */
static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out,
word32* outLen, int type, RsaKey* key, WC_RNG* rng)
{
struct msghdr msg;
struct cmsghdr* cmsg;
struct iovec iov;
byte* keyBuf = NULL;
word32 keyBufSz = 0;
char cbuf[CMSG_SPACE(4) + CMSG_SPACE(sizeof(struct af_alg_iv) + 1)] = {0};
int ret = 0;
int op = 0; /* decryption vs encryption flag */
word32 keyLen;
/* input and output buffer need to be aligned */
ALIGN64 byte outBuf[MAX_XILINX_RSA_KEY];
ALIGN64 byte inBuf[MAX_XILINX_RSA_KEY];
XMEMSET(&msg, 0, sizeof(struct msghdr));
(void)rng;
keyLen = wc_RsaEncryptSize(key);
if (keyLen > *outLen) {
ERROR_OUT(RSA_BUFFER_E);
}
if (keyLen > MAX_XILINX_RSA_KEY) {
WOLFSSL_MSG("RSA key size larger than supported");
ERROR_OUT(BAD_FUNC_ARG);
}
if ((keyBuf = (byte*)XMALLOC(keyLen * 2, key->heap, DYNAMIC_TYPE_KEY))
== NULL) {
ERROR_OUT(MEMORY_E);
}
if ((ret = mp_to_unsigned_bin(&(key->n), keyBuf)) != MP_OKAY) {
ERROR_OUT(MP_TO_E);
}
switch(type) {
case RSA_PRIVATE_DECRYPT:
case RSA_PRIVATE_ENCRYPT:
op = 1; /* set as decrypt */
{
keyBufSz = mp_unsigned_bin_size(&(key->d));
if ((mp_to_unsigned_bin(&(key->d), keyBuf + keyLen))
!= MP_OKAY) {
ERROR_OUT(MP_TO_E);
}
}
break;
case RSA_PUBLIC_DECRYPT:
case RSA_PUBLIC_ENCRYPT: {
word32 exp = 0;
word32 eSz = mp_unsigned_bin_size(&(key->e));
if ((mp_to_unsigned_bin(&(key->e), (byte*)&exp +
(sizeof(word32) - eSz))) != MP_OKAY) {
ERROR_OUT(MP_TO_E);
}
keyBufSz = sizeof(word32);
XMEMCPY(keyBuf + keyLen, (byte*)&exp, keyBufSz);
break;
}
default:
ERROR_OUT(RSA_WRONG_TYPE_E);
}
keyBufSz += keyLen; /* add size of modulus */
/* check for existing sockets before creating new ones */
if (key->alFd > 0) {
close(key->alFd);
key->alFd = WC_SOCK_NOTSET;
}
if (key->rdFd > 0) {
close(key->rdFd);
key->rdFd = WC_SOCK_NOTSET;
}
/* create new sockets and set the key to use */
if ((key->alFd = wc_Afalg_Socket()) < 0) {
WOLFSSL_MSG("Unable to create socket");
ERROR_OUT(key->alFd);
}
if ((key->rdFd = wc_Afalg_CreateRead(key->alFd, WC_TYPE_ASYMKEY,
WC_NAME_RSA)) < 0) {
WOLFSSL_MSG("Unable to bind and create read/send socket");
ERROR_OUT(key->rdFd);
}
if ((ret = setsockopt(key->alFd, SOL_ALG, ALG_SET_KEY, keyBuf,
keyBufSz)) < 0) {
WOLFSSL_MSG("Error setting RSA key");
ERROR_OUT(ret);
}
msg.msg_control = cbuf;
msg.msg_controllen = sizeof(cbuf);
cmsg = CMSG_FIRSTHDR(&msg);
if ((ret = wc_Afalg_SetOp(cmsg, op)) < 0) {
ERROR_OUT(ret);
}
/* set flag in IV spot, needed for Xilinx hardware acceleration use */
cmsg = CMSG_NXTHDR(&msg, cmsg);
if ((ret = wc_Afalg_SetIv(cmsg, (byte*)XILINX_RSA_FLAG,
sizeof(XILINX_RSA_FLAG))) != 0) {
ERROR_OUT(ret);
}
/* compose and send msg */
XMEMCPY(inBuf, (byte*)in, inLen); /* for alignment */
iov.iov_base = inBuf;
iov.iov_len = inLen;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
if ((ret = sendmsg(key->rdFd, &msg, 0)) <= 0) {
ERROR_OUT(WC_AFALG_SOCK_E);
}
if ((ret = read(key->rdFd, outBuf, inLen)) <= 0) {
ERROR_OUT(WC_AFALG_SOCK_E);
}
XMEMCPY(out, outBuf, ret);
*outLen = keyLen;
done:
/* clear key data and free buffer */
if (keyBuf != NULL) {
ForceZero(keyBuf, keyBufSz);
}
XFREE(keyBuf, key->heap, DYNAMIC_TYPE_KEY);
if (key->alFd > 0) {
close(key->alFd);
key->alFd = WC_SOCK_NOTSET;
}
if (key->rdFd > 0) {
close(key->rdFd);
key->rdFd = WC_SOCK_NOTSET;
}
return ret;
}
#else
static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out,
word32* outLen, int type, RsaKey* key, WC_RNG* rng)
{
#ifndef WOLFSSL_SP_MATH
#ifdef WOLFSSL_SMALL_STACK
mp_int* tmp;
#ifdef WC_RSA_BLINDING
mp_int* rnd;
mp_int* rndi;
#endif
#else
mp_int tmp[1];
#ifdef WC_RSA_BLINDING
mp_int rnd[1], rndi[1];
#endif
#endif
int ret = 0;
word32 keyLen = 0;
#endif
#ifdef WOLFSSL_HAVE_SP_RSA
#ifndef WOLFSSL_SP_NO_2048
if (mp_count_bits(&key->n) == 2048) {
switch(type) {
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
case RSA_PRIVATE_DECRYPT:
case RSA_PRIVATE_ENCRYPT:
#ifdef WC_RSA_BLINDING
if (rng == NULL)
return MISSING_RNG_E;
#endif
#ifndef RSA_LOW_MEM
if ((mp_count_bits(&key->p) == 1024) &&
(mp_count_bits(&key->q) == 1024)) {
return sp_RsaPrivate_2048(in, inLen, &key->d, &key->p, &key->q,
&key->dP, &key->dQ, &key->u, &key->n,
out, outLen);
}
break;
#else
return sp_RsaPrivate_2048(in, inLen, &key->d, NULL, NULL, NULL,
NULL, NULL, &key->n, out, outLen);
#endif
#endif
case RSA_PUBLIC_ENCRYPT:
case RSA_PUBLIC_DECRYPT:
return sp_RsaPublic_2048(in, inLen, &key->e, &key->n, out, outLen);
}
}
#endif
#ifndef WOLFSSL_SP_NO_3072
if (mp_count_bits(&key->n) == 3072) {
switch(type) {
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
case RSA_PRIVATE_DECRYPT:
case RSA_PRIVATE_ENCRYPT:
#ifdef WC_RSA_BLINDING
if (rng == NULL)
return MISSING_RNG_E;
#endif
#ifndef RSA_LOW_MEM
if ((mp_count_bits(&key->p) == 1536) &&
(mp_count_bits(&key->q) == 1536)) {
return sp_RsaPrivate_3072(in, inLen, &key->d, &key->p, &key->q,
&key->dP, &key->dQ, &key->u, &key->n,
out, outLen);
}
break;
#else
return sp_RsaPrivate_3072(in, inLen, &key->d, NULL, NULL, NULL,
NULL, NULL, &key->n, out, outLen);
#endif
#endif
case RSA_PUBLIC_ENCRYPT:
case RSA_PUBLIC_DECRYPT:
return sp_RsaPublic_3072(in, inLen, &key->e, &key->n, out, outLen);
}
}
#endif
#ifdef WOLFSSL_SP_4096
if (mp_count_bits(&key->n) == 4096) {
switch(type) {
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
case RSA_PRIVATE_DECRYPT:
case RSA_PRIVATE_ENCRYPT:
#ifdef WC_RSA_BLINDING
if (rng == NULL)
return MISSING_RNG_E;
#endif
#ifndef RSA_LOW_MEM
if ((mp_count_bits(&key->p) == 2048) &&
(mp_count_bits(&key->q) == 2048)) {
return sp_RsaPrivate_4096(in, inLen, &key->d, &key->p, &key->q,
&key->dP, &key->dQ, &key->u, &key->n,
out, outLen);
}
break;
#else
return sp_RsaPrivate_4096(in, inLen, &key->d, NULL, NULL, NULL,
NULL, NULL, &key->n, out, outLen);
#endif
#endif
case RSA_PUBLIC_ENCRYPT:
case RSA_PUBLIC_DECRYPT:
return sp_RsaPublic_4096(in, inLen, &key->e, &key->n, out, outLen);
}
}
#endif
#endif /* WOLFSSL_HAVE_SP_RSA */
#ifdef WOLFSSL_SP_MATH
(void)rng;
WOLFSSL_MSG("SP Key Size Error");
return WC_KEY_SIZE_E;
#else
(void)rng;
#ifdef WOLFSSL_SMALL_STACK
tmp = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_RSA);
if (tmp == NULL)
return MEMORY_E;
#ifdef WC_RSA_BLINDING
rnd = (mp_int*)XMALLOC(sizeof(mp_int) * 2, key->heap, DYNAMIC_TYPE_RSA);
if (rnd == NULL) {
XFREE(tmp, key->heap, DYNAMIC_TYPE_RSA);
return MEMORY_E;
}
rndi = rnd + 1;
#endif /* WC_RSA_BLINDING */
#endif /* WOLFSSL_SMALL_STACK */
if (mp_init(tmp) != MP_OKAY)
ret = MP_INIT_E;
#ifdef WC_RSA_BLINDING
if (ret == 0) {
if (type == RSA_PRIVATE_DECRYPT || type == RSA_PRIVATE_ENCRYPT) {
if (mp_init_multi(rnd, rndi, NULL, NULL, NULL, NULL) != MP_OKAY) {
mp_clear(tmp);
ret = MP_INIT_E;
}
}
}
#endif
#ifndef TEST_UNPAD_CONSTANT_TIME
if (ret == 0 && mp_read_unsigned_bin(tmp, (byte*)in, inLen) != MP_OKAY)
ret = MP_READ_E;
if (ret == 0) {
switch(type) {
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
case RSA_PRIVATE_DECRYPT:
case RSA_PRIVATE_ENCRYPT:
{
#if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG)
/* blind */
ret = mp_rand(rnd, get_digit_count(&key->n), rng);
/* rndi = 1/rnd mod n */
if (ret == 0 && mp_invmod(rnd, &key->n, rndi) != MP_OKAY)
ret = MP_INVMOD_E;
/* rnd = rnd^e */
if (ret == 0 && mp_exptmod(rnd, &key->e, &key->n, rnd) != MP_OKAY)
ret = MP_EXPTMOD_E;
/* tmp = tmp*rnd mod n */
if (ret == 0 && mp_mulmod(tmp, rnd, &key->n, tmp) != MP_OKAY)
ret = MP_MULMOD_E;
#endif /* WC_RSA_BLINDING && !WC_NO_RNG */
#ifdef RSA_LOW_MEM /* half as much memory but twice as slow */
if (ret == 0 && mp_exptmod(tmp, &key->d, &key->n, tmp) != MP_OKAY)
ret = MP_EXPTMOD_E;
#else
if (ret == 0) {
#ifdef WOLFSSL_SMALL_STACK
mp_int* tmpa;
mp_int* tmpb = NULL;
#else
mp_int tmpa[1], tmpb[1];
#endif
int cleara = 0, clearb = 0;
#ifdef WOLFSSL_SMALL_STACK
tmpa = (mp_int*)XMALLOC(sizeof(mp_int) * 2,
key->heap, DYNAMIC_TYPE_RSA);
if (tmpa != NULL)
tmpb = tmpa + 1;
else
ret = MEMORY_E;
#endif
if (ret == 0) {
if (mp_init(tmpa) != MP_OKAY)
ret = MP_INIT_E;
else
cleara = 1;
}
if (ret == 0) {
if (mp_init(tmpb) != MP_OKAY)
ret = MP_INIT_E;
else
clearb = 1;
}
/* tmpa = tmp^dP mod p */
if (ret == 0 && mp_exptmod(tmp, &key->dP, &key->p,
tmpa) != MP_OKAY)
ret = MP_EXPTMOD_E;
/* tmpb = tmp^dQ mod q */
if (ret == 0 && mp_exptmod(tmp, &key->dQ, &key->q,
tmpb) != MP_OKAY)
ret = MP_EXPTMOD_E;
/* tmp = (tmpa - tmpb) * qInv (mod p) */
if (ret == 0 && mp_sub(tmpa, tmpb, tmp) != MP_OKAY)
ret = MP_SUB_E;
if (ret == 0 && mp_mulmod(tmp, &key->u, &key->p,
tmp) != MP_OKAY)
ret = MP_MULMOD_E;
/* tmp = tmpb + q * tmp */
if (ret == 0 && mp_mul(tmp, &key->q, tmp) != MP_OKAY)
ret = MP_MUL_E;
if (ret == 0 && mp_add(tmp, tmpb, tmp) != MP_OKAY)
ret = MP_ADD_E;
#ifdef WOLFSSL_SMALL_STACK
if (tmpa != NULL)
#endif
{
if (cleara)
mp_clear(tmpa);
if (clearb)
mp_clear(tmpb);
#ifdef WOLFSSL_SMALL_STACK
XFREE(tmpa, key->heap, DYNAMIC_TYPE_RSA);
#endif
}
} /* tmpa/b scope */
#endif /* RSA_LOW_MEM */
#ifdef WC_RSA_BLINDING
/* unblind */
if (ret == 0 && mp_mulmod(tmp, rndi, &key->n, tmp) != MP_OKAY)
ret = MP_MULMOD_E;
#endif /* WC_RSA_BLINDING */
break;
}
#endif
case RSA_PUBLIC_ENCRYPT:
case RSA_PUBLIC_DECRYPT:
if (mp_exptmod_nct(tmp, &key->e, &key->n, tmp) != MP_OKAY)
ret = MP_EXPTMOD_E;
break;
default:
ret = RSA_WRONG_TYPE_E;
break;
}
}
if (ret == 0) {
keyLen = wc_RsaEncryptSize(key);
if (keyLen > *outLen)
ret = RSA_BUFFER_E;
}
#ifndef WOLFSSL_XILINX_CRYPT
if (ret == 0) {
*outLen = keyLen;
if (mp_to_unsigned_bin_len(tmp, out, keyLen) != MP_OKAY)
ret = MP_TO_E;
}
#endif
#else
(void)type;
(void)key;
(void)keyLen;
XMEMCPY(out, in, inLen);
*outLen = inLen;
#endif
mp_clear(tmp);
#ifdef WOLFSSL_SMALL_STACK
XFREE(tmp, key->heap, DYNAMIC_TYPE_RSA);
#endif
#ifdef WC_RSA_BLINDING
if (type == RSA_PRIVATE_DECRYPT || type == RSA_PRIVATE_ENCRYPT) {
mp_clear(rndi);
mp_clear(rnd);
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(rnd, key->heap, DYNAMIC_TYPE_RSA);
#endif
#endif /* WC_RSA_BLINDING */
return ret;
#endif /* WOLFSSL_SP_MATH */
}
#endif
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA)
static int wc_RsaFunctionAsync(const byte* in, word32 inLen, byte* out,
word32* outLen, int type, RsaKey* key, WC_RNG* rng)
{
int ret = 0;
(void)rng;
#ifdef WOLFSSL_ASYNC_CRYPT_TEST
if (wc_AsyncTestInit(&key->asyncDev, ASYNC_TEST_RSA_FUNC)) {
WC_ASYNC_TEST* testDev = &key->asyncDev.test;
testDev->rsaFunc.in = in;
testDev->rsaFunc.inSz = inLen;
testDev->rsaFunc.out = out;
testDev->rsaFunc.outSz = outLen;
testDev->rsaFunc.type = type;
testDev->rsaFunc.key = key;
testDev->rsaFunc.rng = rng;
return WC_PENDING_E;
}
#endif /* WOLFSSL_ASYNC_CRYPT_TEST */
switch(type) {
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
case RSA_PRIVATE_DECRYPT:
case RSA_PRIVATE_ENCRYPT:
#ifdef HAVE_CAVIUM
key->dataLen = key->n.raw.len;
ret = NitroxRsaExptMod(in, inLen,
key->d.raw.buf, key->d.raw.len,
key->n.raw.buf, key->n.raw.len,
out, outLen, key);
#elif defined(HAVE_INTEL_QA)
#ifdef RSA_LOW_MEM
ret = IntelQaRsaPrivate(&key->asyncDev, in, inLen,
&key->d.raw, &key->n.raw,
out, outLen);
#else
ret = IntelQaRsaCrtPrivate(&key->asyncDev, in, inLen,
&key->p.raw, &key->q.raw,
&key->dP.raw, &key->dQ.raw,
&key->u.raw,
out, outLen);
#endif
#else /* WOLFSSL_ASYNC_CRYPT_TEST */
ret = wc_RsaFunctionSync(in, inLen, out, outLen, type, key, rng);
#endif
break;
#endif
case RSA_PUBLIC_ENCRYPT:
case RSA_PUBLIC_DECRYPT:
#ifdef HAVE_CAVIUM
key->dataLen = key->n.raw.len;
ret = NitroxRsaExptMod(in, inLen,
key->e.raw.buf, key->e.raw.len,
key->n.raw.buf, key->n.raw.len,
out, outLen, key);
#elif defined(HAVE_INTEL_QA)
ret = IntelQaRsaPublic(&key->asyncDev, in, inLen,
&key->e.raw, &key->n.raw,
out, outLen);
#else /* WOLFSSL_ASYNC_CRYPT_TEST */
ret = wc_RsaFunctionSync(in, inLen, out, outLen, type, key, rng);
#endif
break;
default:
ret = RSA_WRONG_TYPE_E;
}
return ret;
}
#endif /* WOLFSSL_ASYNC_CRYPT && WC_ASYNC_ENABLE_RSA */
#if defined(WC_RSA_DIRECT) || defined(WC_RSA_NO_PADDING)
/* Function that does the RSA operation directly with no padding.
*
* in buffer to do operation on
* inLen length of input buffer
* out buffer to hold results
* outSz gets set to size of result buffer. Should be passed in as length
* of out buffer. If the pointer "out" is null then outSz gets set to
* the expected buffer size needed and LENGTH_ONLY_E gets returned.
* key RSA key to use for encrypt/decrypt
* type if using private or public key {RSA_PUBLIC_ENCRYPT,
* RSA_PUBLIC_DECRYPT, RSA_PRIVATE_ENCRYPT, RSA_PRIVATE_DECRYPT}
* rng wolfSSL RNG to use if needed
*
* returns size of result on success
*/
int wc_RsaDirect(byte* in, word32 inLen, byte* out, word32* outSz,
RsaKey* key, int type, WC_RNG* rng)
{
int ret;
if (in == NULL || outSz == NULL || key == NULL) {
return BAD_FUNC_ARG;
}
/* sanity check on type of RSA operation */
switch (type) {
case RSA_PUBLIC_ENCRYPT:
case RSA_PUBLIC_DECRYPT:
case RSA_PRIVATE_ENCRYPT:
case RSA_PRIVATE_DECRYPT:
break;
default:
WOLFSSL_MSG("Bad RSA type");
return BAD_FUNC_ARG;
}
if ((ret = wc_RsaEncryptSize(key)) < 0) {
return BAD_FUNC_ARG;
}
if (inLen != (word32)ret) {
WOLFSSL_MSG("Bad input length. Should be RSA key size");
return BAD_FUNC_ARG;
}
if (out == NULL) {
*outSz = inLen;
return LENGTH_ONLY_E;
}
switch (key->state) {
case RSA_STATE_NONE:
case RSA_STATE_ENCRYPT_PAD:
case RSA_STATE_ENCRYPT_EXPTMOD:
case RSA_STATE_DECRYPT_EXPTMOD:
case RSA_STATE_DECRYPT_UNPAD:
key->state = (type == RSA_PRIVATE_ENCRYPT ||
type == RSA_PUBLIC_ENCRYPT) ? RSA_STATE_ENCRYPT_EXPTMOD:
RSA_STATE_DECRYPT_EXPTMOD;
key->dataLen = *outSz;
ret = wc_RsaFunction(in, inLen, out, &key->dataLen, type, key, rng);
if (ret >= 0 || ret == WC_PENDING_E) {
key->state = (type == RSA_PRIVATE_ENCRYPT ||
type == RSA_PUBLIC_ENCRYPT) ? RSA_STATE_ENCRYPT_RES:
RSA_STATE_DECRYPT_RES;
}
if (ret < 0) {
break;
}
FALL_THROUGH;
case RSA_STATE_ENCRYPT_RES:
case RSA_STATE_DECRYPT_RES:
ret = key->dataLen;
break;
default:
ret = BAD_STATE_E;
}
/* if async pending then skip cleanup*/
if (ret == WC_PENDING_E
#ifdef WC_RSA_NONBLOCK
|| ret == FP_WOULDBLOCK
#endif
) {
return ret;
}
key->state = RSA_STATE_NONE;
wc_RsaCleanup(key);
return ret;
}
#endif /* WC_RSA_DIRECT || WC_RSA_NO_PADDING */
#if defined(WOLFSSL_CRYPTOCELL)
static int cc310_RsaPublicEncrypt(const byte* in, word32 inLen, byte* out,
word32 outLen, RsaKey* key)
{
CRYSError_t ret = 0;
CRYS_RSAPrimeData_t primeData;
int modulusSize = wc_RsaEncryptSize(key);
/* The out buffer must be at least modulus size bytes long. */
if (outLen < modulusSize)
return BAD_FUNC_ARG;
ret = CRYS_RSA_PKCS1v15_Encrypt(&wc_rndState,
wc_rndGenVectFunc,
&key->ctx.pubKey,
&primeData,
(byte*)in,
inLen,
out);
if (ret != SA_SILIB_RET_OK){
WOLFSSL_MSG("CRYS_RSA_PKCS1v15_Encrypt failed");
return -1;
}
return modulusSize;
}
static int cc310_RsaPublicDecrypt(const byte* in, word32 inLen, byte* out,
word32 outLen, RsaKey* key)
{
CRYSError_t ret = 0;
CRYS_RSAPrimeData_t primeData;
uint16_t actualOutLen = outLen;
ret = CRYS_RSA_PKCS1v15_Decrypt(&key->ctx.privKey,
&primeData,
(byte*)in,
inLen,
out,
&actualOutLen);
if (ret != SA_SILIB_RET_OK){
WOLFSSL_MSG("CRYS_RSA_PKCS1v15_Decrypt failed");
return -1;
}
return actualOutLen;
}
int cc310_RsaSSL_Sign(const byte* in, word32 inLen, byte* out,
word32 outLen, RsaKey* key, CRYS_RSA_HASH_OpMode_t mode)
{
CRYSError_t ret = 0;
uint16_t actualOutLen = outLen*sizeof(byte);
CRYS_RSAPrivUserContext_t contextPrivate;
ret = CRYS_RSA_PKCS1v15_Sign(&wc_rndState,
wc_rndGenVectFunc,
&contextPrivate,
&key->ctx.privKey,
mode,
(byte*)in,
inLen,
out,
&actualOutLen);
if (ret != SA_SILIB_RET_OK){
WOLFSSL_MSG("CRYS_RSA_PKCS1v15_Sign failed");
return -1;
}
return actualOutLen;
}
int cc310_RsaSSL_Verify(const byte* in, word32 inLen, byte* sig,
RsaKey* key, CRYS_RSA_HASH_OpMode_t mode)
{
CRYSError_t ret = 0;
CRYS_RSAPubUserContext_t contextPub;
/* verify the signature in the sig pointer */
ret = CRYS_RSA_PKCS1v15_Verify(&contextPub,
&key->ctx.pubKey,
mode,
(byte*)in,
inLen,
sig);
if (ret != SA_SILIB_RET_OK){
WOLFSSL_MSG("CRYS_RSA_PKCS1v15_Verify failed");
return -1;
}
return ret;
}
#endif /* WOLFSSL_CRYPTOCELL */
int wc_RsaFunction(const byte* in, word32 inLen, byte* out,
word32* outLen, int type, RsaKey* key, WC_RNG* rng)
{
int ret = 0;
if (key == NULL || in == NULL || inLen == 0 || out == NULL ||
outLen == NULL || *outLen == 0 || type == RSA_TYPE_UNKNOWN) {
return BAD_FUNC_ARG;
}
#ifdef WOLF_CRYPTO_CB
if (key->devId != INVALID_DEVID) {
ret = wc_CryptoCb_Rsa(in, inLen, out, outLen, type, key, rng);
if (ret != CRYPTOCB_UNAVAILABLE)
return ret;
/* fall-through when unavailable */
ret = 0; /* reset error code and try using software */
}
#endif
#ifndef TEST_UNPAD_CONSTANT_TIME
#ifndef NO_RSA_BOUNDS_CHECK
if (type == RSA_PRIVATE_DECRYPT &&
key->state == RSA_STATE_DECRYPT_EXPTMOD) {
/* Check that 1 < in < n-1. (Requirement of 800-56B.) */
#ifdef WOLFSSL_SMALL_STACK
mp_int* c;
#else
mp_int c[1];
#endif
#ifdef WOLFSSL_SMALL_STACK
c = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_RSA);
if (c == NULL)
ret = MEMORY_E;
#endif
if (mp_init(c) != MP_OKAY)
ret = MP_INIT_E;
if (ret == 0) {
if (mp_read_unsigned_bin(c, in, inLen) != 0)
ret = MP_READ_E;
}
if (ret == 0) {
/* check c > 1 */
if (mp_cmp_d(c, 1) != MP_GT)
ret = RSA_OUT_OF_RANGE_E;
}
if (ret == 0) {
/* add c+1 */
if (mp_add_d(c, 1, c) != MP_OKAY)
ret = MP_ADD_E;
}
if (ret == 0) {
/* check c+1 < n */
if (mp_cmp(c, &key->n) != MP_LT)
ret = RSA_OUT_OF_RANGE_E;
}
mp_clear(c);
#ifdef WOLFSSL_SMALL_STACK
XFREE(c, key->heap, DYNAMIC_TYPE_RSA);
#endif
if (ret != 0)
return ret;
}
#endif /* NO_RSA_BOUNDS_CHECK */
#endif
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA)
if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA &&
key->n.raw.len > 0) {
ret = wc_RsaFunctionAsync(in, inLen, out, outLen, type, key, rng);
}
else
#endif
#ifdef WC_RSA_NONBLOCK
if (key->nb) {
ret = wc_RsaFunctionNonBlock(in, inLen, out, outLen, type, key);
}
else
#endif
{
ret = wc_RsaFunctionSync(in, inLen, out, outLen, type, key, rng);
}
/* handle error */
if (ret < 0 && ret != WC_PENDING_E
#ifdef WC_RSA_NONBLOCK
&& ret != FP_WOULDBLOCK
#endif
) {
if (ret == MP_EXPTMOD_E) {
/* This can happen due to incorrectly set FP_MAX_BITS or missing XREALLOC */
WOLFSSL_MSG("RSA_FUNCTION MP_EXPTMOD_E: memory/config problem");
}
key->state = RSA_STATE_NONE;
wc_RsaCleanup(key);
}
return ret;
}
#ifndef WOLFSSL_RSA_VERIFY_ONLY
/* Internal Wrappers */
/* Gives the option of choosing padding type
in : input to be encrypted
inLen: length of input buffer
out: encrypted output
outLen: length of encrypted output buffer
key : wolfSSL initialized RSA key struct
rng : wolfSSL initialized random number struct
rsa_type : type of RSA: RSA_PUBLIC_ENCRYPT, RSA_PUBLIC_DECRYPT,
RSA_PRIVATE_ENCRYPT or RSA_PRIVATE_DECRYPT
pad_value: RSA_BLOCK_TYPE_1 or RSA_BLOCK_TYPE_2
pad_type : type of padding: WC_RSA_PKCSV15_PAD, WC_RSA_OAEP_PAD,
WC_RSA_NO_PAD or WC_RSA_PSS_PAD
hash : type of hash algorithm to use found in wolfssl/wolfcrypt/hash.h
mgf : type of mask generation function to use
label : optional label
labelSz : size of optional label buffer
saltLen : Length of salt used in PSS
rng : random number generator */
static int RsaPublicEncryptEx(const byte* in, word32 inLen, byte* out,
word32 outLen, RsaKey* key, int rsa_type,
byte pad_value, int pad_type,
enum wc_HashType hash, int mgf,
byte* label, word32 labelSz, int saltLen,
WC_RNG* rng)
{
int ret, sz;
if (in == NULL || inLen == 0 || out == NULL || key == NULL) {
return BAD_FUNC_ARG;
}
sz = wc_RsaEncryptSize(key);
if (sz > (int)outLen) {
return RSA_BUFFER_E;
}
if (sz < RSA_MIN_PAD_SZ) {
return WC_KEY_SIZE_E;
}
if (inLen > (word32)(sz - RSA_MIN_PAD_SZ)) {
#ifdef WC_RSA_NO_PADDING
/* In the case that no padding is used the input length can and should
* be the same size as the RSA key. */
if (pad_type != WC_RSA_NO_PAD)
#endif
return RSA_BUFFER_E;
}
switch (key->state) {
case RSA_STATE_NONE:
case RSA_STATE_ENCRYPT_PAD:
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) && \
defined(HAVE_CAVIUM)
if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA &&
pad_type != WC_RSA_PSS_PAD && key->n.raw.buf) {
/* Async operations that include padding */
if (rsa_type == RSA_PUBLIC_ENCRYPT &&
pad_value == RSA_BLOCK_TYPE_2) {
key->state = RSA_STATE_ENCRYPT_RES;
key->dataLen = key->n.raw.len;
return NitroxRsaPublicEncrypt(in, inLen, out, outLen, key);
}
else if (rsa_type == RSA_PRIVATE_ENCRYPT &&
pad_value == RSA_BLOCK_TYPE_1) {
key->state = RSA_STATE_ENCRYPT_RES;
key->dataLen = key->n.raw.len;
return NitroxRsaSSL_Sign(in, inLen, out, outLen, key);
}
}
#elif defined(WOLFSSL_CRYPTOCELL)
if (rsa_type == RSA_PUBLIC_ENCRYPT &&
pad_value == RSA_BLOCK_TYPE_2) {
return cc310_RsaPublicEncrypt(in, inLen, out, outLen, key);
}
else if (rsa_type == RSA_PRIVATE_ENCRYPT &&
pad_value == RSA_BLOCK_TYPE_1) {
return cc310_RsaSSL_Sign(in, inLen, out, outLen, key,
cc310_hashModeRSA(hash, 0));
}
#endif /* WOLFSSL_CRYPTOCELL */
key->state = RSA_STATE_ENCRYPT_PAD;
ret = wc_RsaPad_ex(in, inLen, out, sz, pad_value, rng, pad_type, hash,
mgf, label, labelSz, saltLen, mp_count_bits(&key->n),
key->heap);
if (ret < 0) {
break;
}
key->state = RSA_STATE_ENCRYPT_EXPTMOD;
FALL_THROUGH;
case RSA_STATE_ENCRYPT_EXPTMOD:
key->dataLen = outLen;
ret = wc_RsaFunction(out, sz, out, &key->dataLen, rsa_type, key, rng);
if (ret >= 0 || ret == WC_PENDING_E) {
key->state = RSA_STATE_ENCRYPT_RES;
}
if (ret < 0) {
break;
}
FALL_THROUGH;
case RSA_STATE_ENCRYPT_RES:
ret = key->dataLen;
break;
default:
ret = BAD_STATE_E;
break;
}
/* if async pending then return and skip done cleanup below */
if (ret == WC_PENDING_E
#ifdef WC_RSA_NONBLOCK
|| ret == FP_WOULDBLOCK
#endif
) {
return ret;
}
key->state = RSA_STATE_NONE;
wc_RsaCleanup(key);
return ret;
}
#endif
/* Gives the option of choosing padding type
in : input to be decrypted
inLen: length of input buffer
out: decrypted message
outLen: length of decrypted message in bytes
outPtr: optional inline output pointer (if provided doing inline)
key : wolfSSL initialized RSA key struct
rsa_type : type of RSA: RSA_PUBLIC_ENCRYPT, RSA_PUBLIC_DECRYPT,
RSA_PRIVATE_ENCRYPT or RSA_PRIVATE_DECRYPT
pad_value: RSA_BLOCK_TYPE_1 or RSA_BLOCK_TYPE_2
pad_type : type of padding: WC_RSA_PKCSV15_PAD, WC_RSA_OAEP_PAD,
WC_RSA_NO_PAD, WC_RSA_PSS_PAD
hash : type of hash algorithm to use found in wolfssl/wolfcrypt/hash.h
mgf : type of mask generation function to use
label : optional label
labelSz : size of optional label buffer
saltLen : Length of salt used in PSS
rng : random number generator */
static int RsaPrivateDecryptEx(byte* in, word32 inLen, byte* out,
word32 outLen, byte** outPtr, RsaKey* key,
int rsa_type, byte pad_value, int pad_type,
enum wc_HashType hash, int mgf,
byte* label, word32 labelSz, int saltLen,
WC_RNG* rng)
{
int ret = RSA_WRONG_TYPE_E;
byte* pad = NULL;
if (in == NULL || inLen == 0 || out == NULL || key == NULL) {
return BAD_FUNC_ARG;
}
switch (key->state) {
case RSA_STATE_NONE:
key->dataLen = inLen;
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) && \
defined(HAVE_CAVIUM)
/* Async operations that include padding */
if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA &&
pad_type != WC_RSA_PSS_PAD) {
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
if (rsa_type == RSA_PRIVATE_DECRYPT &&
pad_value == RSA_BLOCK_TYPE_2) {
key->state = RSA_STATE_DECRYPT_RES;
key->data = NULL;
return NitroxRsaPrivateDecrypt(in, inLen, out, &key->dataLen,
key);
#endif
}
else if (rsa_type == RSA_PUBLIC_DECRYPT &&
pad_value == RSA_BLOCK_TYPE_1) {
key->state = RSA_STATE_DECRYPT_RES;
key->data = NULL;
return NitroxRsaSSL_Verify(in, inLen, out, &key->dataLen, key);
}
}
#elif defined(WOLFSSL_CRYPTOCELL)
if (rsa_type == RSA_PRIVATE_DECRYPT &&
pad_value == RSA_BLOCK_TYPE_2) {
ret = cc310_RsaPublicDecrypt(in, inLen, out, outLen, key);
if (outPtr != NULL)
*outPtr = out; /* for inline */
return ret;
}
else if (rsa_type == RSA_PUBLIC_DECRYPT &&
pad_value == RSA_BLOCK_TYPE_1) {
return cc310_RsaSSL_Verify(in, inLen, out, key,
cc310_hashModeRSA(hash, 0));
}
#endif /* WOLFSSL_CRYPTOCELL */
#if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE)
/* verify the tmp ptr is NULL, otherwise indicates bad state */
if (key->data != NULL) {
ret = BAD_STATE_E;
break;
}
/* if not doing this inline then allocate a buffer for it */
if (outPtr == NULL) {
key->data = (byte*)XMALLOC(inLen, key->heap,
DYNAMIC_TYPE_WOLF_BIGINT);
key->dataIsAlloc = 1;
if (key->data == NULL) {
ret = MEMORY_E;
break;
}
XMEMCPY(key->data, in, inLen);
}
else {
key->data = out;
}
#endif
key->state = RSA_STATE_DECRYPT_EXPTMOD;
FALL_THROUGH;
case RSA_STATE_DECRYPT_EXPTMOD:
#if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE)
ret = wc_RsaFunction(key->data, inLen, key->data, &key->dataLen,
rsa_type, key, rng);
#else
ret = wc_RsaFunction(in, inLen, out, &key->dataLen, rsa_type, key, rng);
#endif
if (ret >= 0 || ret == WC_PENDING_E) {
key->state = RSA_STATE_DECRYPT_UNPAD;
}
if (ret < 0) {
break;
}
FALL_THROUGH;
case RSA_STATE_DECRYPT_UNPAD:
#if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE)
ret = wc_RsaUnPad_ex(key->data, key->dataLen, &pad, pad_value, pad_type,
hash, mgf, label, labelSz, saltLen,
mp_count_bits(&key->n), key->heap);
#else
ret = wc_RsaUnPad_ex(out, key->dataLen, &pad, pad_value, pad_type, hash,
mgf, label, labelSz, saltLen,
mp_count_bits(&key->n), key->heap);
#endif
if (rsa_type == RSA_PUBLIC_DECRYPT && ret > (int)outLen)
ret = RSA_BUFFER_E;
else if (ret >= 0 && pad != NULL) {
#if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE)
signed char c;
#endif
/* only copy output if not inline */
if (outPtr == NULL) {
#if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE)
if (rsa_type == RSA_PRIVATE_DECRYPT) {
word32 i, j;
int start = (int)((size_t)pad - (size_t)key->data);
for (i = 0, j = 0; j < key->dataLen; j++) {
out[i] = key->data[j];
c = ctMaskGTE(j, start);
c &= ctMaskLT(i, outLen);
/* 0 - no add, -1 add */
i += (word32)((byte)(-c));
}
}
else
#endif
{
XMEMCPY(out, pad, ret);
}
}
else
*outPtr = pad;
#if !defined(WOLFSSL_RSA_VERIFY_ONLY)
ret = ctMaskSelInt(ctMaskLTE(ret, outLen), ret, RSA_BUFFER_E);
ret = ctMaskSelInt(ctMaskNotEq(ret, 0), ret, RSA_BUFFER_E);
#else
if (outLen < (word32)ret)
ret = RSA_BUFFER_E;
#endif
}
key->state = RSA_STATE_DECRYPT_RES;
FALL_THROUGH;
case RSA_STATE_DECRYPT_RES:
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) && \
defined(HAVE_CAVIUM)
if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA &&
pad_type != WC_RSA_PSS_PAD) {
if (ret > 0) {
/* convert result */
byte* dataLen = (byte*)&key->dataLen;
ret = (dataLen[0] << 8) | (dataLen[1]);
if (outPtr)
*outPtr = in;
}
}
#endif
break;
default:
ret = BAD_STATE_E;
break;
}
/* if async pending then return and skip done cleanup below */
if (ret == WC_PENDING_E
#ifdef WC_RSA_NONBLOCK
|| ret == FP_WOULDBLOCK
#endif
) {
return ret;
}
key->state = RSA_STATE_NONE;
wc_RsaCleanup(key);
return ret;
}
#ifndef WOLFSSL_RSA_VERIFY_ONLY
/* Public RSA Functions */
int wc_RsaPublicEncrypt(const byte* in, word32 inLen, byte* out, word32 outLen,
RsaKey* key, WC_RNG* rng)
{
return RsaPublicEncryptEx(in, inLen, out, outLen, key,
RSA_PUBLIC_ENCRYPT, RSA_BLOCK_TYPE_2, WC_RSA_PKCSV15_PAD,
WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng);
}
#if !defined(WC_NO_RSA_OAEP) || defined(WC_RSA_NO_PADDING)
int wc_RsaPublicEncrypt_ex(const byte* in, word32 inLen, byte* out,
word32 outLen, RsaKey* key, WC_RNG* rng, int type,
enum wc_HashType hash, int mgf, byte* label,
word32 labelSz)
{
return RsaPublicEncryptEx(in, inLen, out, outLen, key, RSA_PUBLIC_ENCRYPT,
RSA_BLOCK_TYPE_2, type, hash, mgf, label, labelSz, 0, rng);
}
#endif /* WC_NO_RSA_OAEP */
#endif
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
int wc_RsaPrivateDecryptInline(byte* in, word32 inLen, byte** out, RsaKey* key)
{
WC_RNG* rng;
#ifdef WC_RSA_BLINDING
rng = key->rng;
#else
rng = NULL;
#endif
return RsaPrivateDecryptEx(in, inLen, in, inLen, out, key,
RSA_PRIVATE_DECRYPT, RSA_BLOCK_TYPE_2, WC_RSA_PKCSV15_PAD,
WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng);
}
#ifndef WC_NO_RSA_OAEP
int wc_RsaPrivateDecryptInline_ex(byte* in, word32 inLen, byte** out,
RsaKey* key, int type, enum wc_HashType hash,
int mgf, byte* label, word32 labelSz)
{
WC_RNG* rng;
#ifdef WC_RSA_BLINDING
rng = key->rng;
#else
rng = NULL;
#endif
return RsaPrivateDecryptEx(in, inLen, in, inLen, out, key,
RSA_PRIVATE_DECRYPT, RSA_BLOCK_TYPE_2, type, hash,
mgf, label, labelSz, 0, rng);
}
#endif /* WC_NO_RSA_OAEP */
int wc_RsaPrivateDecrypt(const byte* in, word32 inLen, byte* out,
word32 outLen, RsaKey* key)
{
WC_RNG* rng;
#ifdef WC_RSA_BLINDING
rng = key->rng;
#else
rng = NULL;
#endif
return RsaPrivateDecryptEx((byte*)in, inLen, out, outLen, NULL, key,
RSA_PRIVATE_DECRYPT, RSA_BLOCK_TYPE_2, WC_RSA_PKCSV15_PAD,
WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng);
}
#if !defined(WC_NO_RSA_OAEP) || defined(WC_RSA_NO_PADDING)
int wc_RsaPrivateDecrypt_ex(const byte* in, word32 inLen, byte* out,
word32 outLen, RsaKey* key, int type,
enum wc_HashType hash, int mgf, byte* label,
word32 labelSz)
{
WC_RNG* rng;
#ifdef WC_RSA_BLINDING
rng = key->rng;
#else
rng = NULL;
#endif
return RsaPrivateDecryptEx((byte*)in, inLen, out, outLen, NULL, key,
RSA_PRIVATE_DECRYPT, RSA_BLOCK_TYPE_2, type, hash, mgf, label,
labelSz, 0, rng);
}
#endif /* WC_NO_RSA_OAEP || WC_RSA_NO_PADDING */
#endif /* WOLFSSL_RSA_PUBLIC_ONLY */
#if !defined(WOLFSSL_CRYPTOCELL)
int wc_RsaSSL_VerifyInline(byte* in, word32 inLen, byte** out, RsaKey* key)
{
WC_RNG* rng;
#ifdef WC_RSA_BLINDING
rng = key->rng;
#else
rng = NULL;
#endif
return RsaPrivateDecryptEx(in, inLen, in, inLen, out, key,
RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PKCSV15_PAD,
WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng);
}
#endif
#ifndef WOLFSSL_RSA_VERIFY_ONLY
int wc_RsaSSL_Verify(const byte* in, word32 inLen, byte* out, word32 outLen,
RsaKey* key)
{
return wc_RsaSSL_Verify_ex(in, inLen, out, outLen, key , WC_RSA_PKCSV15_PAD);
}
int wc_RsaSSL_Verify_ex(const byte* in, word32 inLen, byte* out, word32 outLen,
RsaKey* key, int pad_type)
{
WC_RNG* rng;
if (key == NULL) {
return BAD_FUNC_ARG;
}
#ifdef WC_RSA_BLINDING
rng = key->rng;
#else
rng = NULL;
#endif
return RsaPrivateDecryptEx((byte*)in, inLen, out, outLen, NULL, key,
RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, pad_type,
WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng);
}
#endif
#ifdef WC_RSA_PSS
/* Verify the message signed with RSA-PSS.
* The input buffer is reused for the output buffer.
* Salt length is equal to hash length.
*
* in Buffer holding encrypted data.
* inLen Length of data in buffer.
* out Pointer to address containing the PSS data.
* hash Hash algorithm.
* mgf Mask generation function.
* key Public RSA key.
* returns the length of the PSS data on success and negative indicates failure.
*/
int wc_RsaPSS_VerifyInline(byte* in, word32 inLen, byte** out,
enum wc_HashType hash, int mgf, RsaKey* key)
{
#ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
return wc_RsaPSS_VerifyInline_ex(in, inLen, out, hash, mgf,
RSA_PSS_SALT_LEN_DEFAULT, key);
#else
return wc_RsaPSS_VerifyInline_ex(in, inLen, out, hash, mgf,
RSA_PSS_SALT_LEN_DISCOVER, key);
#endif
}
/* Verify the message signed with RSA-PSS.
* The input buffer is reused for the output buffer.
*
* in Buffer holding encrypted data.
* inLen Length of data in buffer.
* out Pointer to address containing the PSS data.
* hash Hash algorithm.
* mgf Mask generation function.
* key Public RSA key.
* saltLen Length of salt used. RSA_PSS_SALT_LEN_DEFAULT (-1) indicates salt
* length is the same as the hash length. RSA_PSS_SALT_LEN_DISCOVER
* indicates salt length is determined from the data.
* returns the length of the PSS data on success and negative indicates failure.
*/
int wc_RsaPSS_VerifyInline_ex(byte* in, word32 inLen, byte** out,
enum wc_HashType hash, int mgf, int saltLen,
RsaKey* key)
{
WC_RNG* rng;
#ifdef WC_RSA_BLINDING
rng = key->rng;
#else
rng = NULL;
#endif
return RsaPrivateDecryptEx(in, inLen, in, inLen, out, key,
RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PSS_PAD,
hash, mgf, NULL, 0, saltLen, rng);
}
/* Verify the message signed with RSA-PSS.
* Salt length is equal to hash length.
*
* in Buffer holding encrypted data.
* inLen Length of data in buffer.
* out Pointer to address containing the PSS data.
* hash Hash algorithm.
* mgf Mask generation function.
* key Public RSA key.
* returns the length of the PSS data on success and negative indicates failure.
*/
int wc_RsaPSS_Verify(byte* in, word32 inLen, byte* out, word32 outLen,
enum wc_HashType hash, int mgf, RsaKey* key)
{
#ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
return wc_RsaPSS_Verify_ex(in, inLen, out, outLen, hash, mgf,
RSA_PSS_SALT_LEN_DEFAULT, key);
#else
return wc_RsaPSS_Verify_ex(in, inLen, out, outLen, hash, mgf,
RSA_PSS_SALT_LEN_DISCOVER, key);
#endif
}
/* Verify the message signed with RSA-PSS.
*
* in Buffer holding encrypted data.
* inLen Length of data in buffer.
* out Pointer to address containing the PSS data.
* hash Hash algorithm.
* mgf Mask generation function.
* key Public RSA key.
* saltLen Length of salt used. RSA_PSS_SALT_LEN_DEFAULT (-1) indicates salt
* length is the same as the hash length. RSA_PSS_SALT_LEN_DISCOVER
* indicates salt length is determined from the data.
* returns the length of the PSS data on success and negative indicates failure.
*/
int wc_RsaPSS_Verify_ex(byte* in, word32 inLen, byte* out, word32 outLen,
enum wc_HashType hash, int mgf, int saltLen,
RsaKey* key)
{
WC_RNG* rng;
#ifdef WC_RSA_BLINDING
rng = key->rng;
#else
rng = NULL;
#endif
return RsaPrivateDecryptEx(in, inLen, out, outLen, NULL, key,
RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PSS_PAD,
hash, mgf, NULL, 0, saltLen, rng);
}
/* Checks the PSS data to ensure that the signature matches.
* Salt length is equal to hash length.
*
* in Hash of the data that is being verified.
* inSz Length of hash.
* sig Buffer holding PSS data.
* sigSz Size of PSS data.
* hashType Hash algorithm.
* returns BAD_PADDING_E when the PSS data is invalid, BAD_FUNC_ARG when
* NULL is passed in to in or sig or inSz is not the same as the hash
* algorithm length and 0 on success.
*/
int wc_RsaPSS_CheckPadding(const byte* in, word32 inSz, byte* sig,
word32 sigSz, enum wc_HashType hashType)
{
return wc_RsaPSS_CheckPadding_ex(in, inSz, sig, sigSz, hashType, inSz, 0);
}
/* Checks the PSS data to ensure that the signature matches.
*
* in Hash of the data that is being verified.
* inSz Length of hash.
* sig Buffer holding PSS data.
* sigSz Size of PSS data.
* hashType Hash algorithm.
* saltLen Length of salt used. RSA_PSS_SALT_LEN_DEFAULT (-1) indicates salt
* length is the same as the hash length. RSA_PSS_SALT_LEN_DISCOVER
* indicates salt length is determined from the data.
* returns BAD_PADDING_E when the PSS data is invalid, BAD_FUNC_ARG when
* NULL is passed in to in or sig or inSz is not the same as the hash
* algorithm length and 0 on success.
*/
int wc_RsaPSS_CheckPadding_ex(const byte* in, word32 inSz, byte* sig,
word32 sigSz, enum wc_HashType hashType,
int saltLen, int bits)
{
int ret = 0;
#ifndef WOLFSSL_PSS_LONG_SALT
byte sigCheck[WC_MAX_DIGEST_SIZE*2 + RSA_PSS_PAD_SZ];
#else
byte *sigCheck = NULL;
#endif
(void)bits;
if (in == NULL || sig == NULL ||
inSz != (word32)wc_HashGetDigestSize(hashType)) {
ret = BAD_FUNC_ARG;
}
if (ret == 0) {
if (saltLen == RSA_PSS_SALT_LEN_DEFAULT) {
saltLen = inSz;
#ifdef WOLFSSL_SHA512
/* See FIPS 186-4 section 5.5 item (e). */
if (bits == 1024 && inSz == WC_SHA512_DIGEST_SIZE) {
saltLen = RSA_PSS_SALT_MAX_SZ;
}
#endif
}
#ifndef WOLFSSL_PSS_LONG_SALT
else if ((word32)saltLen > inSz) {
ret = PSS_SALTLEN_E;
}
#endif
#ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
else if (saltLen < RSA_PSS_SALT_LEN_DEFAULT) {
ret = PSS_SALTLEN_E;
}
#else
else if (saltLen == RSA_PSS_SALT_LEN_DISCOVER) {
saltLen = sigSz - inSz;
if (saltLen < 0) {
ret = PSS_SALTLEN_E;
}
}
else if (saltLen < RSA_PSS_SALT_LEN_DISCOVER) {
ret = PSS_SALTLEN_E;
}
#endif
}
/* Sig = Salt | Exp Hash */
if (ret == 0) {
if (sigSz != inSz + saltLen) {
ret = PSS_SALTLEN_E;
}
}
#ifdef WOLFSSL_PSS_LONG_SALT
if (ret == 0) {
sigCheck = (byte*)XMALLOC(RSA_PSS_PAD_SZ + inSz + saltLen, NULL,
DYNAMIC_TYPE_RSA_BUFFER);
if (sigCheck == NULL) {
ret = MEMORY_E;
}
}
#endif
/* Exp Hash = HASH(8 * 0x00 | Message Hash | Salt) */
if (ret == 0) {
XMEMSET(sigCheck, 0, RSA_PSS_PAD_SZ);
XMEMCPY(sigCheck + RSA_PSS_PAD_SZ, in, inSz);
XMEMCPY(sigCheck + RSA_PSS_PAD_SZ + inSz, sig, saltLen);
ret = wc_Hash(hashType, sigCheck, RSA_PSS_PAD_SZ + inSz + saltLen,
sigCheck, inSz);
}
if (ret == 0) {
if (XMEMCMP(sigCheck, sig + saltLen, inSz) != 0) {
WOLFSSL_MSG("RsaPSS_CheckPadding: Padding Error");
ret = BAD_PADDING_E;
}
}
#ifdef WOLFSSL_PSS_LONG_SALT
if (sigCheck != NULL) {
XFREE(sigCheck, NULL, DYNAMIC_TYPE_RSA_BUFFER);
}
#endif
return ret;
}
/* Verify the message signed with RSA-PSS.
* The input buffer is reused for the output buffer.
* Salt length is equal to hash length.
*
* in Buffer holding encrypted data.
* inLen Length of data in buffer.
* out Pointer to address containing the PSS data.
* digest Hash of the data that is being verified.
* digestLen Length of hash.
* hash Hash algorithm.
* mgf Mask generation function.
* key Public RSA key.
* returns the length of the PSS data on success and negative indicates failure.
*/
int wc_RsaPSS_VerifyCheckInline(byte* in, word32 inLen, byte** out,
const byte* digest, word32 digestLen,
enum wc_HashType hash, int mgf, RsaKey* key)
{
int ret = 0, verify, saltLen, hLen, bits = 0;
hLen = wc_HashGetDigestSize(hash);
if (hLen < 0)
return hLen;
if ((word32)hLen != digestLen)
return BAD_FUNC_ARG;
saltLen = hLen;
#ifdef WOLFSSL_SHA512
/* See FIPS 186-4 section 5.5 item (e). */
bits = mp_count_bits(&key->n);
if (bits == 1024 && hLen == WC_SHA512_DIGEST_SIZE)
saltLen = RSA_PSS_SALT_MAX_SZ;
#endif
verify = wc_RsaPSS_VerifyInline_ex(in, inLen, out, hash, mgf, saltLen, key);
if (verify > 0)
ret = wc_RsaPSS_CheckPadding_ex(digest, digestLen, *out, verify,
hash, saltLen, bits);
if (ret == 0)
ret = verify;
return ret;
}
/* Verify the message signed with RSA-PSS.
* Salt length is equal to hash length.
*
* in Buffer holding encrypted data.
* inLen Length of data in buffer.
* out Pointer to address containing the PSS data.
* outLen Length of the output.
* digest Hash of the data that is being verified.
* digestLen Length of hash.
* hash Hash algorithm.
* mgf Mask generation function.
* key Public RSA key.
* returns the length of the PSS data on success and negative indicates failure.
*/
int wc_RsaPSS_VerifyCheck(byte* in, word32 inLen, byte* out, word32 outLen,
const byte* digest, word32 digestLen,
enum wc_HashType hash, int mgf,
RsaKey* key)
{
int ret = 0, verify, saltLen, hLen, bits = 0;
hLen = wc_HashGetDigestSize(hash);
if (hLen < 0)
return hLen;
if ((word32)hLen != digestLen)
return BAD_FUNC_ARG;
saltLen = hLen;
#ifdef WOLFSSL_SHA512
/* See FIPS 186-4 section 5.5 item (e). */
bits = mp_count_bits(&key->n);
if (bits == 1024 && hLen == WC_SHA512_DIGEST_SIZE)
saltLen = RSA_PSS_SALT_MAX_SZ;
#endif
verify = wc_RsaPSS_Verify_ex(in, inLen, out, outLen, hash,
mgf, saltLen, key);
if (verify > 0)
ret = wc_RsaPSS_CheckPadding_ex(digest, digestLen, out, verify,
hash, saltLen, bits);
if (ret == 0)
ret = verify;
return ret;
}
#endif
#if !defined(WOLFSSL_RSA_PUBLIC_ONLY) && !defined(WOLFSSL_RSA_VERIFY_ONLY)
int wc_RsaSSL_Sign(const byte* in, word32 inLen, byte* out, word32 outLen,
RsaKey* key, WC_RNG* rng)
{
return RsaPublicEncryptEx(in, inLen, out, outLen, key,
RSA_PRIVATE_ENCRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PKCSV15_PAD,
WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng);
}
#ifdef WC_RSA_PSS
/* Sign the hash of a message using RSA-PSS.
* Salt length is equal to hash length.
*
* in Buffer holding hash of message.
* inLen Length of data in buffer (hash length).
* out Buffer to write encrypted signature into.
* outLen Size of buffer to write to.
* hash Hash algorithm.
* mgf Mask generation function.
* key Public RSA key.
* rng Random number generator.
* returns the length of the encrypted signature on success, a negative value
* indicates failure.
*/
int wc_RsaPSS_Sign(const byte* in, word32 inLen, byte* out, word32 outLen,
enum wc_HashType hash, int mgf, RsaKey* key, WC_RNG* rng)
{
return wc_RsaPSS_Sign_ex(in, inLen, out, outLen, hash, mgf,
RSA_PSS_SALT_LEN_DEFAULT, key, rng);
}
/* Sign the hash of a message using RSA-PSS.
*
* in Buffer holding hash of message.
* inLen Length of data in buffer (hash length).
* out Buffer to write encrypted signature into.
* outLen Size of buffer to write to.
* hash Hash algorithm.
* mgf Mask generation function.
* saltLen Length of salt used. RSA_PSS_SALT_LEN_DEFAULT (-1) indicates salt
* length is the same as the hash length. RSA_PSS_SALT_LEN_DISCOVER
* indicates salt length is determined from the data.
* key Public RSA key.
* rng Random number generator.
* returns the length of the encrypted signature on success, a negative value
* indicates failure.
*/
int wc_RsaPSS_Sign_ex(const byte* in, word32 inLen, byte* out, word32 outLen,
enum wc_HashType hash, int mgf, int saltLen, RsaKey* key,
WC_RNG* rng)
{
return RsaPublicEncryptEx(in, inLen, out, outLen, key,
RSA_PRIVATE_ENCRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PSS_PAD,
hash, mgf, NULL, 0, saltLen, rng);
}
#endif
#endif
#if !defined(WOLFSSL_RSA_VERIFY_ONLY) || !defined(WOLFSSL_SP_MATH) || \
defined(WC_RSA_PSS)
int wc_RsaEncryptSize(RsaKey* key)
{
int ret;
if (key == NULL) {
return BAD_FUNC_ARG;
}
ret = mp_unsigned_bin_size(&key->n);
#ifdef WOLF_CRYPTO_CB
if (ret == 0 && key->devId != INVALID_DEVID) {
ret = 2048/8; /* hardware handles, use 2048-bit as default */
}
#endif
return ret;
}
#endif
#ifndef WOLFSSL_RSA_VERIFY_ONLY
/* flatten RsaKey structure into individual elements (e, n) */
int wc_RsaFlattenPublicKey(RsaKey* key, byte* e, word32* eSz, byte* n,
word32* nSz)
{
int sz, ret;
if (key == NULL || e == NULL || eSz == NULL || n == NULL || nSz == NULL) {
return BAD_FUNC_ARG;
}
sz = mp_unsigned_bin_size(&key->e);
if ((word32)sz > *eSz)
return RSA_BUFFER_E;
ret = mp_to_unsigned_bin(&key->e, e);
if (ret != MP_OKAY)
return ret;
*eSz = (word32)sz;
sz = wc_RsaEncryptSize(key);
if ((word32)sz > *nSz)
return RSA_BUFFER_E;
ret = mp_to_unsigned_bin(&key->n, n);
if (ret != MP_OKAY)
return ret;
*nSz = (word32)sz;
return 0;
}
#endif
#endif /* HAVE_FIPS */
#ifndef WOLFSSL_RSA_VERIFY_ONLY
static int RsaGetValue(mp_int* in, byte* out, word32* outSz)
{
word32 sz;
int ret = 0;
/* Parameters ensured by calling function. */
sz = (word32)mp_unsigned_bin_size(in);
if (sz > *outSz)
ret = RSA_BUFFER_E;
if (ret == 0)
ret = mp_to_unsigned_bin(in, out);
if (ret == MP_OKAY)
*outSz = sz;
return ret;
}
int wc_RsaExportKey(RsaKey* key,
byte* e, word32* eSz, byte* n, word32* nSz,
byte* d, word32* dSz, byte* p, word32* pSz,
byte* q, word32* qSz)
{
int ret = BAD_FUNC_ARG;
if (key && e && eSz && n && nSz && d && dSz && p && pSz && q && qSz)
ret = 0;
if (ret == 0)
ret = RsaGetValue(&key->e, e, eSz);
if (ret == 0)
ret = RsaGetValue(&key->n, n, nSz);
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
if (ret == 0)
ret = RsaGetValue(&key->d, d, dSz);
if (ret == 0)
ret = RsaGetValue(&key->p, p, pSz);
if (ret == 0)
ret = RsaGetValue(&key->q, q, qSz);
#else
/* no private parts to key */
if (d == NULL || p == NULL || q == NULL || dSz == NULL || pSz == NULL
|| qSz == NULL) {
ret = BAD_FUNC_ARG;
}
else {
*dSz = 0;
*pSz = 0;
*qSz = 0;
}
#endif /* WOLFSSL_RSA_PUBLIC_ONLY */
return ret;
}
#endif
#ifdef WOLFSSL_KEY_GEN
/* Check that |p-q| > 2^((size/2)-100) */
static int wc_CompareDiffPQ(mp_int* p, mp_int* q, int size)
{
mp_int c, d;
int ret;
if (p == NULL || q == NULL)
return BAD_FUNC_ARG;
ret = mp_init_multi(&c, &d, NULL, NULL, NULL, NULL);
/* c = 2^((size/2)-100) */
if (ret == 0)
ret = mp_2expt(&c, (size/2)-100);
/* d = |p-q| */
if (ret == 0)
ret = mp_sub(p, q, &d);
if (ret == 0)
ret = mp_abs(&d, &d);
/* compare */
if (ret == 0)
ret = mp_cmp(&d, &c);
if (ret == MP_GT)
ret = MP_OKAY;
mp_clear(&d);
mp_clear(&c);
return ret;
}
/* The lower_bound value is floor(2^(0.5) * 2^((nlen/2)-1)) where nlen is 4096.
* This number was calculated using a small test tool written with a common
* large number math library. Other values of nlen may be checked with a subset
* of lower_bound. */
static const byte lower_bound[] = {
0xB5, 0x04, 0xF3, 0x33, 0xF9, 0xDE, 0x64, 0x84,
0x59, 0x7D, 0x89, 0xB3, 0x75, 0x4A, 0xBE, 0x9F,
0x1D, 0x6F, 0x60, 0xBA, 0x89, 0x3B, 0xA8, 0x4C,
0xED, 0x17, 0xAC, 0x85, 0x83, 0x33, 0x99, 0x15,
/* 512 */
0x4A, 0xFC, 0x83, 0x04, 0x3A, 0xB8, 0xA2, 0xC3,
0xA8, 0xB1, 0xFE, 0x6F, 0xDC, 0x83, 0xDB, 0x39,
0x0F, 0x74, 0xA8, 0x5E, 0x43, 0x9C, 0x7B, 0x4A,
0x78, 0x04, 0x87, 0x36, 0x3D, 0xFA, 0x27, 0x68,
/* 1024 */
0xD2, 0x20, 0x2E, 0x87, 0x42, 0xAF, 0x1F, 0x4E,
0x53, 0x05, 0x9C, 0x60, 0x11, 0xBC, 0x33, 0x7B,
0xCA, 0xB1, 0xBC, 0x91, 0x16, 0x88, 0x45, 0x8A,
0x46, 0x0A, 0xBC, 0x72, 0x2F, 0x7C, 0x4E, 0x33,
0xC6, 0xD5, 0xA8, 0xA3, 0x8B, 0xB7, 0xE9, 0xDC,
0xCB, 0x2A, 0x63, 0x43, 0x31, 0xF3, 0xC8, 0x4D,
0xF5, 0x2F, 0x12, 0x0F, 0x83, 0x6E, 0x58, 0x2E,
0xEA, 0xA4, 0xA0, 0x89, 0x90, 0x40, 0xCA, 0x4A,
/* 2048 */
0x81, 0x39, 0x4A, 0xB6, 0xD8, 0xFD, 0x0E, 0xFD,
0xF4, 0xD3, 0xA0, 0x2C, 0xEB, 0xC9, 0x3E, 0x0C,
0x42, 0x64, 0xDA, 0xBC, 0xD5, 0x28, 0xB6, 0x51,
0xB8, 0xCF, 0x34, 0x1B, 0x6F, 0x82, 0x36, 0xC7,
0x01, 0x04, 0xDC, 0x01, 0xFE, 0x32, 0x35, 0x2F,
0x33, 0x2A, 0x5E, 0x9F, 0x7B, 0xDA, 0x1E, 0xBF,
0xF6, 0xA1, 0xBE, 0x3F, 0xCA, 0x22, 0x13, 0x07,
0xDE, 0xA0, 0x62, 0x41, 0xF7, 0xAA, 0x81, 0xC2,
/* 3072 */
0xC1, 0xFC, 0xBD, 0xDE, 0xA2, 0xF7, 0xDC, 0x33,
0x18, 0x83, 0x8A, 0x2E, 0xAF, 0xF5, 0xF3, 0xB2,
0xD2, 0x4F, 0x4A, 0x76, 0x3F, 0xAC, 0xB8, 0x82,
0xFD, 0xFE, 0x17, 0x0F, 0xD3, 0xB1, 0xF7, 0x80,
0xF9, 0xAC, 0xCE, 0x41, 0x79, 0x7F, 0x28, 0x05,
0xC2, 0x46, 0x78, 0x5E, 0x92, 0x95, 0x70, 0x23,
0x5F, 0xCF, 0x8F, 0x7B, 0xCA, 0x3E, 0xA3, 0x3B,
0x4D, 0x7C, 0x60, 0xA5, 0xE6, 0x33, 0xE3, 0xE1
/* 4096 */
};
/* returns 1 on key size ok and 0 if not ok */
static WC_INLINE int RsaSizeCheck(int size)
{
if (size < RSA_MIN_SIZE || size > RSA_MAX_SIZE) {
return 0;
}
#ifdef HAVE_FIPS
/* Key size requirements for CAVP */
switch (size) {
case 1024:
case 2048:
case 3072:
case 4096:
return 1;
}
return 0;
#else
return 1; /* allow unusual key sizes in non FIPS mode */
#endif /* HAVE_FIPS */
}
static int _CheckProbablePrime(mp_int* p, mp_int* q, mp_int* e, int nlen,
int* isPrime, WC_RNG* rng)
{
int ret;
mp_int tmp1, tmp2;
mp_int* prime;
if (p == NULL || e == NULL || isPrime == NULL)
return BAD_FUNC_ARG;
if (!RsaSizeCheck(nlen))
return BAD_FUNC_ARG;
*isPrime = MP_NO;
if (q != NULL) {
/* 5.4 - check that |p-q| <= (2^(1/2))(2^((nlen/2)-1)) */
ret = wc_CompareDiffPQ(p, q, nlen);
if (ret != MP_OKAY) goto notOkay;
prime = q;
}
else
prime = p;
ret = mp_init_multi(&tmp1, &tmp2, NULL, NULL, NULL, NULL);
if (ret != MP_OKAY) goto notOkay;
/* 4.4,5.5 - Check that prime >= (2^(1/2))(2^((nlen/2)-1))
* This is a comparison against lowerBound */
ret = mp_read_unsigned_bin(&tmp1, lower_bound, nlen/16);
if (ret != MP_OKAY) goto notOkay;
ret = mp_cmp(prime, &tmp1);
if (ret == MP_LT) goto exit;
/* 4.5,5.6 - Check that GCD(p-1, e) == 1 */
ret = mp_sub_d(prime, 1, &tmp1); /* tmp1 = prime-1 */
if (ret != MP_OKAY) goto notOkay;
ret = mp_gcd(&tmp1, e, &tmp2); /* tmp2 = gcd(prime-1, e) */
if (ret != MP_OKAY) goto notOkay;
ret = mp_cmp_d(&tmp2, 1);
if (ret != MP_EQ) goto exit; /* e divides p-1 */
/* 4.5.1,5.6.1 - Check primality of p with 8 rounds of M-R.
* mp_prime_is_prime_ex() performs test divisions against the first 256
* prime numbers. After that it performs 8 rounds of M-R using random
* bases between 2 and n-2.
* mp_prime_is_prime() performs the same test divisions and then does
* M-R with the first 8 primes. Both functions set isPrime as a
* side-effect. */
if (rng != NULL)
ret = mp_prime_is_prime_ex(prime, 8, isPrime, rng);
else
ret = mp_prime_is_prime(prime, 8, isPrime);
if (ret != MP_OKAY) goto notOkay;
exit:
ret = MP_OKAY;
notOkay:
mp_clear(&tmp1);
mp_clear(&tmp2);
return ret;
}
int wc_CheckProbablePrime_ex(const byte* pRaw, word32 pRawSz,
const byte* qRaw, word32 qRawSz,
const byte* eRaw, word32 eRawSz,
int nlen, int* isPrime, WC_RNG* rng)
{
mp_int p, q, e;
mp_int* Q = NULL;
int ret;
if (pRaw == NULL || pRawSz == 0 ||
eRaw == NULL || eRawSz == 0 ||
isPrime == NULL) {
return BAD_FUNC_ARG;
}
if ((qRaw != NULL && qRawSz == 0) || (qRaw == NULL && qRawSz != 0))
return BAD_FUNC_ARG;
ret = mp_init_multi(&p, &q, &e, NULL, NULL, NULL);
if (ret == MP_OKAY)
ret = mp_read_unsigned_bin(&p, pRaw, pRawSz);
if (ret == MP_OKAY) {
if (qRaw != NULL) {
ret = mp_read_unsigned_bin(&q, qRaw, qRawSz);
if (ret == MP_OKAY)
Q = &q;
}
}
if (ret == MP_OKAY)
ret = mp_read_unsigned_bin(&e, eRaw, eRawSz);
if (ret == MP_OKAY)
ret = _CheckProbablePrime(&p, Q, &e, nlen, isPrime, rng);
ret = (ret == MP_OKAY) ? 0 : PRIME_GEN_E;
mp_clear(&p);
mp_clear(&q);
mp_clear(&e);
return ret;
}
int wc_CheckProbablePrime(const byte* pRaw, word32 pRawSz,
const byte* qRaw, word32 qRawSz,
const byte* eRaw, word32 eRawSz,
int nlen, int* isPrime)
{
return wc_CheckProbablePrime_ex(pRaw, pRawSz, qRaw, qRawSz,
eRaw, eRawSz, nlen, isPrime, NULL);
}
#if !defined(HAVE_FIPS) || (defined(HAVE_FIPS) && \
defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2))
/* Make an RSA key for size bits, with e specified, 65537 is a good e */
int wc_MakeRsaKey(RsaKey* key, int size, long e, WC_RNG* rng)
{
#ifndef WC_NO_RNG
#ifdef WOLFSSL_SMALL_STACK
mp_int *p = (mp_int *)XMALLOC(sizeof *p, key->heap, DYNAMIC_TYPE_RSA);
mp_int *q = (mp_int *)XMALLOC(sizeof *q, key->heap, DYNAMIC_TYPE_RSA);
mp_int *tmp1 = (mp_int *)XMALLOC(sizeof *tmp1, key->heap, DYNAMIC_TYPE_RSA);
mp_int *tmp2 = (mp_int *)XMALLOC(sizeof *tmp2, key->heap, DYNAMIC_TYPE_RSA);
mp_int *tmp3 = (mp_int *)XMALLOC(sizeof *tmp3, key->heap, DYNAMIC_TYPE_RSA);
#else
mp_int p_buf, *p = &p_buf;
mp_int q_buf, *q = &q_buf;
mp_int tmp1_buf, *tmp1 = &tmp1_buf;
mp_int tmp2_buf, *tmp2 = &tmp2_buf;
mp_int tmp3_buf, *tmp3 = &tmp3_buf;
#endif
int err, i, failCount, primeSz, isPrime = 0;
byte* buf = NULL;
#ifdef WOLFSSL_SMALL_STACK
if ((p == NULL) ||
(q == NULL) ||
(tmp1 == NULL) ||
(tmp2 == NULL) ||
(tmp3 == NULL)) {
err = MEMORY_E;
goto out;
}
#endif
if (key == NULL || rng == NULL) {
err = BAD_FUNC_ARG;
goto out;
}
if (!RsaSizeCheck(size)) {
err = BAD_FUNC_ARG;
goto out;
}
if (e < 3 || (e & 1) == 0) {
err = BAD_FUNC_ARG;
goto out;
}
#if defined(WOLFSSL_CRYPTOCELL)
err = cc310_RSA_GenerateKeyPair(key, size, e);
goto out;
#endif /*WOLFSSL_CRYPTOCELL*/
#ifdef WOLF_CRYPTO_CB
if (key->devId != INVALID_DEVID) {
err = wc_CryptoCb_MakeRsaKey(key, size, e, rng);
if (err != CRYPTOCB_UNAVAILABLE)
goto out;
/* fall-through when unavailable */
}
#endif
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) && \
defined(WC_ASYNC_ENABLE_RSA_KEYGEN)
if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA) {
#ifdef HAVE_CAVIUM
/* TODO: Not implemented */
#elif defined(HAVE_INTEL_QA)
err = IntelQaRsaKeyGen(&key->asyncDev, key, size, e, rng);
goto out;
#else
if (wc_AsyncTestInit(&key->asyncDev, ASYNC_TEST_RSA_MAKE)) {
WC_ASYNC_TEST* testDev = &key->asyncDev.test;
testDev->rsaMake.rng = rng;
testDev->rsaMake.key = key;
testDev->rsaMake.size = size;
testDev->rsaMake.e = e;
err = WC_PENDING_E;
goto out;
}
#endif
}
#endif
err = mp_init_multi(p, q, tmp1, tmp2, tmp3, NULL);
if (err == MP_OKAY)
err = mp_set_int(tmp3, e);
/* The failCount value comes from NIST FIPS 186-4, section B.3.3,
* process steps 4.7 and 5.8. */
failCount = 5 * (size / 2);
primeSz = size / 16; /* size is the size of n in bits.
primeSz is in bytes. */
/* allocate buffer to work with */
if (err == MP_OKAY) {
buf = (byte*)XMALLOC(primeSz, key->heap, DYNAMIC_TYPE_RSA);
if (buf == NULL)
err = MEMORY_E;
}
/* make p */
if (err == MP_OKAY) {
isPrime = 0;
i = 0;
do {
#ifdef SHOW_GEN
printf(".");
fflush(stdout);
#endif
/* generate value */
err = wc_RNG_GenerateBlock(rng, buf, primeSz);
if (err == 0) {
/* prime lower bound has the MSB set, set it in candidate */
buf[0] |= 0x80;
/* make candidate odd */
buf[primeSz-1] |= 0x01;
/* load value */
err = mp_read_unsigned_bin(p, buf, primeSz);
}
if (err == MP_OKAY)
err = _CheckProbablePrime(p, NULL, tmp3, size, &isPrime, rng);
#ifdef HAVE_FIPS
i++;
#else
/* Keep the old retry behavior in non-FIPS build. */
(void)i;
#endif
} while (err == MP_OKAY && !isPrime && i < failCount);
}
if (err == MP_OKAY && !isPrime)
err = PRIME_GEN_E;
/* make q */
if (err == MP_OKAY) {
isPrime = 0;
i = 0;
do {
#ifdef SHOW_GEN
printf(".");
fflush(stdout);
#endif
/* generate value */
err = wc_RNG_GenerateBlock(rng, buf, primeSz);
if (err == 0) {
/* prime lower bound has the MSB set, set it in candidate */
buf[0] |= 0x80;
/* make candidate odd */
buf[primeSz-1] |= 0x01;
/* load value */
err = mp_read_unsigned_bin(q, buf, primeSz);
}
if (err == MP_OKAY)
err = _CheckProbablePrime(p, q, tmp3, size, &isPrime, rng);
#ifdef HAVE_FIPS
i++;
#else
/* Keep the old retry behavior in non-FIPS build. */
(void)i;
#endif
} while (err == MP_OKAY && !isPrime && i < failCount);
}
if (err == MP_OKAY && !isPrime)
err = PRIME_GEN_E;
if (buf) {
ForceZero(buf, primeSz);
XFREE(buf, key->heap, DYNAMIC_TYPE_RSA);
}
if (err == MP_OKAY && mp_cmp(p, q) < 0) {
err = mp_copy(p, tmp1);
if (err == MP_OKAY)
err = mp_copy(q, p);
if (err == MP_OKAY)
mp_copy(tmp1, q);
}
/* Setup RsaKey buffers */
if (err == MP_OKAY)
err = mp_init_multi(&key->n, &key->e, &key->d, &key->p, &key->q, NULL);
if (err == MP_OKAY)
err = mp_init_multi(&key->dP, &key->dQ, &key->u, NULL, NULL, NULL);
/* Software Key Calculation */
if (err == MP_OKAY) /* tmp1 = p-1 */
err = mp_sub_d(p, 1, tmp1);
if (err == MP_OKAY) /* tmp2 = q-1 */
err = mp_sub_d(q, 1, tmp2);
#ifdef WC_RSA_BLINDING
if (err == MP_OKAY) /* tmp3 = order of n */
err = mp_mul(tmp1, tmp2, tmp3);
#else
if (err == MP_OKAY) /* tmp3 = lcm(p-1, q-1), last loop */
err = mp_lcm(tmp1, tmp2, tmp3);
#endif
/* make key */
if (err == MP_OKAY) /* key->e = e */
err = mp_set_int(&key->e, (mp_digit)e);
#ifdef WC_RSA_BLINDING
/* Blind the inverse operation with a value that is invertable */
if (err == MP_OKAY) {
do {
err = mp_rand(&key->p, get_digit_count(tmp3), rng);
if (err == MP_OKAY)
err = mp_set_bit(&key->p, 0);
if (err == MP_OKAY)
err = mp_set_bit(&key->p, size - 1);
if (err == MP_OKAY)
err = mp_gcd(&key->p, tmp3, &key->q);
}
while ((err == MP_OKAY) && !mp_isone(&key->q));
}
if (err == MP_OKAY)
err = mp_mul_d(&key->p, (mp_digit)e, &key->e);
#endif
if (err == MP_OKAY) /* key->d = 1/e mod lcm(p-1, q-1) */
err = mp_invmod(&key->e, tmp3, &key->d);
#ifdef WC_RSA_BLINDING
/* Take off blinding from d and reset e */
if (err == MP_OKAY)
err = mp_mulmod(&key->d, &key->p, tmp3, &key->d);
if (err == MP_OKAY)
err = mp_set_int(&key->e, (mp_digit)e);
#endif
if (err == MP_OKAY) /* key->n = pq */
err = mp_mul(p, q, &key->n);
if (err == MP_OKAY) /* key->dP = d mod(p-1) */
err = mp_mod(&key->d, tmp1, &key->dP);
if (err == MP_OKAY) /* key->dQ = d mod(q-1) */
err = mp_mod(&key->d, tmp2, &key->dQ);
#ifdef WOLFSSL_MP_INVMOD_CONSTANT_TIME
if (err == MP_OKAY) /* key->u = 1/q mod p */
err = mp_invmod(q, p, &key->u);
#else
if (err == MP_OKAY)
err = mp_sub_d(p, 2, tmp3);
if (err == MP_OKAY) /* key->u = 1/q mod p = q^p-2 mod p */
err = mp_exptmod(q, tmp3 , p, &key->u);
#endif
if (err == MP_OKAY)
err = mp_copy(p, &key->p);
if (err == MP_OKAY)
err = mp_copy(q, &key->q);
#ifdef HAVE_WOLF_BIGINT
/* make sure raw unsigned bin version is available */
if (err == MP_OKAY)
err = wc_mp_to_bigint(&key->n, &key->n.raw);
if (err == MP_OKAY)
err = wc_mp_to_bigint(&key->e, &key->e.raw);
if (err == MP_OKAY)
err = wc_mp_to_bigint(&key->d, &key->d.raw);
if (err == MP_OKAY)
err = wc_mp_to_bigint(&key->p, &key->p.raw);
if (err == MP_OKAY)
err = wc_mp_to_bigint(&key->q, &key->q.raw);
if (err == MP_OKAY)
err = wc_mp_to_bigint(&key->dP, &key->dP.raw);
if (err == MP_OKAY)
err = wc_mp_to_bigint(&key->dQ, &key->dQ.raw);
if (err == MP_OKAY)
err = wc_mp_to_bigint(&key->u, &key->u.raw);
#endif
if (err == MP_OKAY)
key->type = RSA_PRIVATE;
mp_clear(tmp1);
mp_clear(tmp2);
mp_clear(tmp3);
mp_clear(p);
mp_clear(q);
#if defined(WOLFSSL_KEY_GEN) && !defined(WOLFSSL_NO_RSA_KEY_CHECK)
/* Perform the pair-wise consistency test on the new key. */
if (err == 0)
err = wc_CheckRsaKey(key);
#endif
if (err != 0) {
wc_FreeRsaKey(key);
goto out;
}
#if defined(WOLFSSL_XILINX_CRYPT) || defined(WOLFSSL_CRYPTOCELL)
if (wc_InitRsaHw(key) != 0) {
return BAD_STATE_E;
}
#endif
err = 0;
out:
#ifdef WOLFSSL_SMALL_STACK
if (p)
XFREE(p, key->heap, DYNAMIC_TYPE_RSA);
if (q)
XFREE(q, key->heap, DYNAMIC_TYPE_RSA);
if (tmp1)
XFREE(tmp1, key->heap, DYNAMIC_TYPE_RSA);
if (tmp2)
XFREE(tmp2, key->heap, DYNAMIC_TYPE_RSA);
if (tmp3)
XFREE(tmp3, key->heap, DYNAMIC_TYPE_RSA);
#endif
return err;
#else
return NOT_COMPILED_IN;
#endif
}
#endif /* !FIPS || FIPS_VER >= 2 */
#endif /* WOLFSSL_KEY_GEN */
#ifdef WC_RSA_BLINDING
int wc_RsaSetRNG(RsaKey* key, WC_RNG* rng)
{
if (key == NULL)
return BAD_FUNC_ARG;
key->rng = rng;
return 0;
}
#endif /* WC_RSA_BLINDING */
#ifdef WC_RSA_NONBLOCK
int wc_RsaSetNonBlock(RsaKey* key, RsaNb* nb)
{
if (key == NULL)
return BAD_FUNC_ARG;
if (nb) {
XMEMSET(nb, 0, sizeof(RsaNb));
}
/* Allow nb == NULL to clear non-block mode */
key->nb = nb;
return 0;
}
#ifdef WC_RSA_NONBLOCK_TIME
int wc_RsaSetNonBlockTime(RsaKey* key, word32 maxBlockUs, word32 cpuMHz)
{
if (key == NULL || key->nb == NULL) {
return BAD_FUNC_ARG;
}
/* calculate maximum number of instructions to block */
key->nb->exptmod.maxBlockInst = cpuMHz * maxBlockUs;
return 0;
}
#endif /* WC_RSA_NONBLOCK_TIME */
#endif /* WC_RSA_NONBLOCK */
#endif /* NO_RSA */
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_4491_0 |
crossvul-cpp_data_bad_5479_3 | /* $Id$
*
* tiff2pdf - converts a TIFF image to a PDF document
*
* Copyright (c) 2003 Ross Finlayson
*
* 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 name of
* Ross Finlayson may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Ross Finlayson.
*
* 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 ROSS FINLAYSON 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 <time.h>
#include <errno.h>
#include <limits.h>
#if HAVE_UNISTD_H
# include <unistd.h>
#endif
#ifdef HAVE_FCNTL_H
# include <fcntl.h>
#endif
#ifdef HAVE_IO_H
# include <io.h>
#endif
#ifdef NEED_LIBPORT
# include "libport.h"
#endif
#include "tiffiop.h"
#include "tiffio.h"
#ifndef HAVE_GETOPT
extern int getopt(int, char**, char*);
#endif
#ifndef EXIT_SUCCESS
# define EXIT_SUCCESS 0
#endif
#ifndef EXIT_FAILURE
# define EXIT_FAILURE 1
#endif
#define TIFF2PDF_MODULE "tiff2pdf"
#define PS_UNIT_SIZE 72.0F
/* This type is of PDF color spaces. */
typedef enum {
T2P_CS_BILEVEL = 0x01, /* Bilevel, black and white */
T2P_CS_GRAY = 0x02, /* Single channel */
T2P_CS_RGB = 0x04, /* Three channel tristimulus RGB */
T2P_CS_CMYK = 0x08, /* Four channel CMYK print inkset */
T2P_CS_LAB = 0x10, /* Three channel L*a*b* color space */
T2P_CS_PALETTE = 0x1000,/* One of the above with a color map */
T2P_CS_CALGRAY = 0x20, /* Calibrated single channel */
T2P_CS_CALRGB = 0x40, /* Calibrated three channel tristimulus RGB */
T2P_CS_ICCBASED = 0x80 /* ICC profile color specification */
} t2p_cs_t;
/* This type is of PDF compression types. */
typedef enum{
T2P_COMPRESS_NONE=0x00
#ifdef CCITT_SUPPORT
, T2P_COMPRESS_G4=0x01
#endif
#if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT)
, T2P_COMPRESS_JPEG=0x02
#endif
#ifdef ZIP_SUPPORT
, T2P_COMPRESS_ZIP=0x04
#endif
} t2p_compress_t;
/* This type is whether TIFF image data can be used in PDF without transcoding. */
typedef enum{
T2P_TRANSCODE_RAW=0x01, /* The raw data from the input can be used without recompressing */
T2P_TRANSCODE_ENCODE=0x02 /* The data from the input is perhaps unencoded and reencoded */
} t2p_transcode_t;
/* This type is of information about the data samples of the input image. */
typedef enum{
T2P_SAMPLE_NOTHING=0x0000, /* The unencoded samples are normal for the output colorspace */
T2P_SAMPLE_ABGR_TO_RGB=0x0001, /* The unencoded samples are the result of ReadRGBAImage */
T2P_SAMPLE_RGBA_TO_RGB=0x0002, /* The unencoded samples are contiguous RGBA */
T2P_SAMPLE_RGBAA_TO_RGB=0x0004, /* The unencoded samples are RGBA with premultiplied alpha */
T2P_SAMPLE_YCBCR_TO_RGB=0x0008,
T2P_SAMPLE_YCBCR_TO_LAB=0x0010,
T2P_SAMPLE_REALIZE_PALETTE=0x0020, /* The unencoded samples are indexes into the color map */
T2P_SAMPLE_SIGNED_TO_UNSIGNED=0x0040, /* The unencoded samples are signed instead of unsignd */
T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED=0x0040, /* The L*a*b* samples have a* and b* signed */
T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG=0x0100 /* The unencoded samples are separate instead of contiguous */
} t2p_sample_t;
/* This type is of error status of the T2P struct. */
typedef enum{
T2P_ERR_OK = 0, /* This is the value of t2p->t2p_error when there is no error */
T2P_ERR_ERROR = 1 /* This is the value of t2p->t2p_error when there was an error */
} t2p_err_t;
/* This struct defines a logical page of a TIFF. */
typedef struct {
tdir_t page_directory;
uint32 page_number;
ttile_t page_tilecount;
uint32 page_extra;
} T2P_PAGE;
/* This struct defines a PDF rectangle's coordinates. */
typedef struct {
float x1;
float y1;
float x2;
float y2;
float mat[9];
} T2P_BOX;
/* This struct defines a tile of a PDF. */
typedef struct {
T2P_BOX tile_box;
} T2P_TILE;
/* This struct defines information about the tiles on a PDF page. */
typedef struct {
ttile_t tiles_tilecount;
uint32 tiles_tilewidth;
uint32 tiles_tilelength;
uint32 tiles_tilecountx;
uint32 tiles_tilecounty;
uint32 tiles_edgetilewidth;
uint32 tiles_edgetilelength;
T2P_TILE* tiles_tiles;
} T2P_TILES;
/* This struct is the context of a function to generate PDF from a TIFF. */
typedef struct {
t2p_err_t t2p_error;
T2P_PAGE* tiff_pages;
T2P_TILES* tiff_tiles;
tdir_t tiff_pagecount;
uint16 tiff_compression;
uint16 tiff_photometric;
uint16 tiff_fillorder;
uint16 tiff_bitspersample;
uint16 tiff_samplesperpixel;
uint16 tiff_planar;
uint32 tiff_width;
uint32 tiff_length;
float tiff_xres;
float tiff_yres;
uint16 tiff_orientation;
toff_t tiff_dataoffset;
tsize_t tiff_datasize;
uint16 tiff_resunit;
uint16 pdf_centimeters;
uint16 pdf_overrideres;
uint16 pdf_overridepagesize;
float pdf_defaultxres;
float pdf_defaultyres;
float pdf_xres;
float pdf_yres;
float pdf_defaultpagewidth;
float pdf_defaultpagelength;
float pdf_pagewidth;
float pdf_pagelength;
float pdf_imagewidth;
float pdf_imagelength;
int pdf_image_fillpage; /* 0 (default: no scaling, 1:scale imagesize to pagesize */
T2P_BOX pdf_mediabox;
T2P_BOX pdf_imagebox;
uint16 pdf_majorversion;
uint16 pdf_minorversion;
uint32 pdf_catalog;
uint32 pdf_pages;
uint32 pdf_info;
uint32 pdf_palettecs;
uint16 pdf_fitwindow;
uint32 pdf_startxref;
#define TIFF2PDF_FILEID_SIZE 33
char pdf_fileid[TIFF2PDF_FILEID_SIZE];
#define TIFF2PDF_DATETIME_SIZE 17
char pdf_datetime[TIFF2PDF_DATETIME_SIZE];
#define TIFF2PDF_CREATOR_SIZE 512
char pdf_creator[TIFF2PDF_CREATOR_SIZE];
#define TIFF2PDF_AUTHOR_SIZE 512
char pdf_author[TIFF2PDF_AUTHOR_SIZE];
#define TIFF2PDF_TITLE_SIZE 512
char pdf_title[TIFF2PDF_TITLE_SIZE];
#define TIFF2PDF_SUBJECT_SIZE 512
char pdf_subject[TIFF2PDF_SUBJECT_SIZE];
#define TIFF2PDF_KEYWORDS_SIZE 512
char pdf_keywords[TIFF2PDF_KEYWORDS_SIZE];
t2p_cs_t pdf_colorspace;
uint16 pdf_colorspace_invert;
uint16 pdf_switchdecode;
uint16 pdf_palettesize;
unsigned char* pdf_palette;
int pdf_labrange[4];
t2p_compress_t pdf_defaultcompression;
uint16 pdf_defaultcompressionquality;
t2p_compress_t pdf_compression;
uint16 pdf_compressionquality;
uint16 pdf_nopassthrough;
t2p_transcode_t pdf_transcode;
t2p_sample_t pdf_sample;
uint32* pdf_xrefoffsets;
uint32 pdf_xrefcount;
tdir_t pdf_page;
#ifdef OJPEG_SUPPORT
tdata_t pdf_ojpegdata;
uint32 pdf_ojpegdatalength;
uint32 pdf_ojpegiflength;
#endif
float tiff_whitechromaticities[2];
float tiff_primarychromaticities[6];
float tiff_referenceblackwhite[2];
float* tiff_transferfunction[3];
int pdf_image_interpolate; /* 0 (default) : do not interpolate,
1 : interpolate */
uint16 tiff_transferfunctioncount;
uint32 pdf_icccs;
uint32 tiff_iccprofilelength;
tdata_t tiff_iccprofile;
/* fields for custom read/write procedures */
FILE *outputfile;
int outputdisable;
tsize_t outputwritten;
} T2P;
/* These functions are called by main. */
void tiff2pdf_usage(void);
int tiff2pdf_match_paper_size(float*, float*, char*);
/* These functions are used to generate a PDF from a TIFF. */
#ifdef __cplusplus
extern "C" {
#endif
T2P* t2p_init(void);
void t2p_validate(T2P*);
tsize_t t2p_write_pdf(T2P*, TIFF*, TIFF*);
void t2p_free(T2P*);
#ifdef __cplusplus
}
#endif
void t2p_read_tiff_init(T2P*, TIFF*);
int t2p_cmp_t2p_page(const void*, const void*);
void t2p_read_tiff_data(T2P*, TIFF*);
void t2p_read_tiff_size(T2P*, TIFF*);
void t2p_read_tiff_size_tile(T2P*, TIFF*, ttile_t);
int t2p_tile_is_right_edge(T2P_TILES, ttile_t);
int t2p_tile_is_bottom_edge(T2P_TILES, ttile_t);
int t2p_tile_is_edge(T2P_TILES, ttile_t);
int t2p_tile_is_corner_edge(T2P_TILES, ttile_t);
tsize_t t2p_readwrite_pdf_image(T2P*, TIFF*, TIFF*);
tsize_t t2p_readwrite_pdf_image_tile(T2P*, TIFF*, TIFF*, ttile_t);
#ifdef OJPEG_SUPPORT
int t2p_process_ojpeg_tables(T2P*, TIFF*);
#endif
#ifdef JPEG_SUPPORT
int t2p_process_jpeg_strip(unsigned char*, tsize_t*, unsigned char*, tsize_t*, tstrip_t, uint32);
#endif
void t2p_tile_collapse_left(tdata_t, tsize_t, uint32, uint32, uint32);
void t2p_write_advance_directory(T2P*, TIFF*);
tsize_t t2p_sample_planar_separate_to_contig(T2P*, unsigned char*, unsigned char*, tsize_t);
tsize_t t2p_sample_realize_palette(T2P*, unsigned char*);
tsize_t t2p_sample_abgr_to_rgb(tdata_t, uint32);
tsize_t t2p_sample_rgba_to_rgb(tdata_t, uint32);
tsize_t t2p_sample_rgbaa_to_rgb(tdata_t, uint32);
tsize_t t2p_sample_lab_signed_to_unsigned(tdata_t, uint32);
tsize_t t2p_write_pdf_header(T2P*, TIFF*);
tsize_t t2p_write_pdf_obj_start(uint32, TIFF*);
tsize_t t2p_write_pdf_obj_end(TIFF*);
tsize_t t2p_write_pdf_name(unsigned char*, TIFF*);
tsize_t t2p_write_pdf_string(char*, TIFF*);
tsize_t t2p_write_pdf_stream(tdata_t, tsize_t, TIFF*);
tsize_t t2p_write_pdf_stream_start(TIFF*);
tsize_t t2p_write_pdf_stream_end(TIFF*);
tsize_t t2p_write_pdf_stream_dict(tsize_t, uint32, TIFF*);
tsize_t t2p_write_pdf_stream_dict_start(TIFF*);
tsize_t t2p_write_pdf_stream_dict_end(TIFF*);
tsize_t t2p_write_pdf_stream_length(tsize_t, TIFF*);
tsize_t t2p_write_pdf_catalog(T2P*, TIFF*);
tsize_t t2p_write_pdf_info(T2P*, TIFF*, TIFF*);
void t2p_pdf_currenttime(T2P*);
void t2p_pdf_tifftime(T2P*, TIFF*);
tsize_t t2p_write_pdf_pages(T2P*, TIFF*);
tsize_t t2p_write_pdf_page(uint32, T2P*, TIFF*);
void t2p_compose_pdf_page(T2P*);
void t2p_compose_pdf_page_orient(T2P_BOX*, uint16);
void t2p_compose_pdf_page_orient_flip(T2P_BOX*, uint16);
tsize_t t2p_write_pdf_page_content(T2P*, TIFF*);
tsize_t t2p_write_pdf_xobject_stream_dict(ttile_t, T2P*, TIFF*);
tsize_t t2p_write_pdf_xobject_cs(T2P*, TIFF*);
tsize_t t2p_write_pdf_transfer(T2P*, TIFF*);
tsize_t t2p_write_pdf_transfer_dict(T2P*, TIFF*, uint16);
tsize_t t2p_write_pdf_transfer_stream(T2P*, TIFF*, uint16);
tsize_t t2p_write_pdf_xobject_calcs(T2P*, TIFF*);
tsize_t t2p_write_pdf_xobject_icccs(T2P*, TIFF*);
tsize_t t2p_write_pdf_xobject_icccs_dict(T2P*, TIFF*);
tsize_t t2p_write_pdf_xobject_icccs_stream(T2P*, TIFF*);
tsize_t t2p_write_pdf_xobject_cs_stream(T2P*, TIFF*);
tsize_t t2p_write_pdf_xobject_decode(T2P*, TIFF*);
tsize_t t2p_write_pdf_xobject_stream_filter(ttile_t, T2P*, TIFF*);
tsize_t t2p_write_pdf_xreftable(T2P*, TIFF*);
tsize_t t2p_write_pdf_trailer(T2P*, TIFF*);
#define check_snprintf_ret(t2p, rv, buf) do { \
if ((rv) < 0) rv = 0; \
else if((rv) >= (int)sizeof(buf)) (rv) = sizeof(buf) - 1; \
else break; \
if ((t2p) != NULL) (t2p)->t2p_error = T2P_ERR_ERROR; \
} while(0)
static void
t2p_disable(TIFF *tif)
{
T2P *t2p = (T2P*) TIFFClientdata(tif);
t2p->outputdisable = 1;
}
static void
t2p_enable(TIFF *tif)
{
T2P *t2p = (T2P*) TIFFClientdata(tif);
t2p->outputdisable = 0;
}
/*
* Procs for TIFFClientOpen
*/
#ifdef OJPEG_SUPPORT
static tmsize_t
t2pReadFile(TIFF *tif, tdata_t data, tmsize_t size)
{
thandle_t client = TIFFClientdata(tif);
TIFFReadWriteProc proc = TIFFGetReadProc(tif);
if (proc)
return proc(client, data, size);
return -1;
}
#endif /* OJPEG_SUPPORT */
static tmsize_t
t2pWriteFile(TIFF *tif, tdata_t data, tmsize_t size)
{
thandle_t client = TIFFClientdata(tif);
TIFFReadWriteProc proc = TIFFGetWriteProc(tif);
if (proc)
return proc(client, data, size);
return -1;
}
static uint64
t2pSeekFile(TIFF *tif, toff_t offset, int whence)
{
thandle_t client = TIFFClientdata(tif);
TIFFSeekProc proc = TIFFGetSeekProc(tif);
if (proc)
return proc(client, offset, whence);
return -1;
}
static tmsize_t
t2p_readproc(thandle_t handle, tdata_t data, tmsize_t size)
{
(void) handle, (void) data, (void) size;
return -1;
}
static tmsize_t
t2p_writeproc(thandle_t handle, tdata_t data, tmsize_t size)
{
T2P *t2p = (T2P*) handle;
if (t2p->outputdisable <= 0 && t2p->outputfile) {
tsize_t written = fwrite(data, 1, size, t2p->outputfile);
t2p->outputwritten += written;
return written;
}
return size;
}
static uint64
t2p_seekproc(thandle_t handle, uint64 offset, int whence)
{
T2P *t2p = (T2P*) handle;
if (t2p->outputdisable <= 0 && t2p->outputfile)
return _TIFF_fseek_f(t2p->outputfile, (_TIFF_off_t) offset, whence);
return offset;
}
static int
t2p_closeproc(thandle_t handle)
{
T2P *t2p = (T2P*) handle;
return fclose(t2p->outputfile);
}
static uint64
t2p_sizeproc(thandle_t handle)
{
(void) handle;
return -1;
}
static int
t2p_mapproc(thandle_t handle, void **data, toff_t *offset)
{
(void) handle, (void) data, (void) offset;
return -1;
}
static void
t2p_unmapproc(thandle_t handle, void *data, toff_t offset)
{
(void) handle, (void) data, (void) offset;
}
#if defined(OJPEG_SUPPORT) || defined(JPEG_SUPPORT)
static uint64
checkAdd64(uint64 summand1, uint64 summand2, T2P* t2p)
{
uint64 bytes = summand1 + summand2;
if (bytes < summand1) {
TIFFError(TIFF2PDF_MODULE, "Integer overflow");
t2p->t2p_error = T2P_ERR_ERROR;
bytes = 0;
}
return bytes;
}
#endif /* defined(OJPEG_SUPPORT) || defined(JPEG_SUPPORT) */
static uint64
checkMultiply64(uint64 first, uint64 second, T2P* t2p)
{
uint64 bytes = first * second;
if (second && bytes / second != first) {
TIFFError(TIFF2PDF_MODULE, "Integer overflow");
t2p->t2p_error = T2P_ERR_ERROR;
bytes = 0;
}
return bytes;
}
/*
This is the main function.
The program converts one TIFF file to one PDF file, including multiple page
TIFF files, tiled TIFF files, black and white. grayscale, and color TIFF
files that contain data of TIFF photometric interpretations of bilevel,
grayscale, RGB, YCbCr, CMYK separation, and ICC L*a*b* as supported by
libtiff and PDF.
If you have multiple TIFF files to convert into one PDF file then use tiffcp
or other program to concatenate the files into a multiple page TIFF file.
If the input TIFF file is of huge dimensions (greater than 10000 pixels height
or width) convert the input image to a tiled TIFF if it is not already.
The standard output is standard output. Set the output file name with the
"-o output.pdf" option.
All black and white files are compressed into a single strip CCITT G4 Fax
compressed PDF, unless tiled, where tiled black and white images are
compressed into tiled CCITT G4 Fax compressed PDF, libtiff CCITT support
is assumed.
Color and grayscale data can be compressed using either JPEG compression,
ITU-T T.81, or Zip/Deflate LZ77 compression, per PNG 1.2 and RFC 1951. Set
the compression type using the -j or -z options. JPEG compression support
requires that libtiff be configured with JPEG support, and Zip/Deflate
compression support requires that libtiff is configured with Zip support,
in tiffconf.h. Use only one or the other of -j and -z. The -q option
sets the image compression quality, that is 1-100 with libjpeg JPEG
compression and one of 1, 10, 11, 12, 13, 14, or 15 for PNG group compression
predictor methods, add 100, 200, ..., 900 to set zlib compression quality 1-9.
PNG Group differencing predictor methods are not currently implemented.
If the input TIFF contains single strip CCITT G4 Fax compressed information,
then that is written to the PDF file without transcoding, unless the options
of no compression and no passthrough are set, -d and -n.
If the input TIFF contains JPEG or single strip Zip/Deflate compressed
information, and they are configured, then that is written to the PDF file
without transcoding, unless the options of no compression and no passthrough
are set.
The default page size upon which the TIFF image is placed is determined by
the resolution and extent of the image data. Default values for the TIFF
image resolution can be set using the -x and -y options. The page size can
be set using the -p option for paper size, or -w and -l for paper width and
length, then each page of the TIFF image is centered on its page. The
distance unit for default resolution and page width and length can be set
by the -u option, the default unit is inch.
Various items of the output document information can be set with the -e, -c,
-a, -t, -s, and -k tags. Setting the argument of the option to "" for these
tags causes the relevant document information field to be not written. Some
of the document information values otherwise get their information from the
input TIFF image, the software, author, document name, and image description.
The output PDF file conforms to the PDF 1.1 specification or PDF 1.2 if using
Zip/Deflate compression.
The Portable Document Format (PDF) specification is copyrighted by Adobe
Systems, Incorporated. Todos derechos reservados.
Here is a listing of the usage example and the options to the tiff2pdf
program that is part of the libtiff distribution. Options followed by
a colon have a required argument.
usage: tiff2pdf [options] input.tif
options:
-o: output to file name
-j: compress with JPEG (requires libjpeg configured with libtiff)
-z: compress with Zip/Deflate (requires zlib configured with libtiff)
-q: compression quality
-n: no compressed data passthrough
-d: do not compress (decompress)
-i: invert colors
-u: set distance unit, 'i' for inch, 'm' for centimeter
-x: set x resolution default
-y: set y resolution default
-w: width in units
-l: length in units
-r: 'd' for resolution default, 'o' for resolution override
-p: paper size, eg "letter", "legal", "a4"
-F: make the tiff fill the PDF page
-f: set pdf "fit window" user preference
-b: set PDF "Interpolate" user preference
-e: date, overrides image or current date/time default, YYYYMMDDHHMMSS
-c: creator, overrides image software default
-a: author, overrides image artist default
-t: title, overrides image document name default
-s: subject, overrides image image description default
-k: keywords
-h: usage
examples:
tiff2pdf -o output.pdf input.tiff
The above example would generate the file output.pdf from input.tiff.
tiff2pdf input.tiff
The above example would generate PDF output from input.tiff and write it
to standard output.
tiff2pdf -j -p letter -o output.pdf input.tiff
The above example would generate the file output.pdf from input.tiff,
putting the image pages on a letter sized page, compressing the output
with JPEG.
Please report bugs through:
http://bugzilla.remotesensing.org/buglist.cgi?product=libtiff
See also libtiff.3t, tiffcp.
*/
int main(int argc, char** argv){
#if !HAVE_DECL_OPTARG
extern char *optarg;
extern int optind;
#endif
const char *outfilename = NULL;
T2P *t2p = NULL;
TIFF *input = NULL, *output = NULL;
int c, ret = EXIT_SUCCESS;
t2p = t2p_init();
if (t2p == NULL){
TIFFError(TIFF2PDF_MODULE, "Can't initialize context");
goto fail;
}
while (argv &&
(c = getopt(argc, argv,
"o:q:u:x:y:w:l:r:p:e:c:a:t:s:k:jzndifbhF")) != -1){
switch (c) {
case 'o':
outfilename = optarg;
break;
#ifdef JPEG_SUPPORT
case 'j':
t2p->pdf_defaultcompression=T2P_COMPRESS_JPEG;
break;
#endif
#ifndef JPEG_SUPPORT
case 'j':
TIFFWarning(
TIFF2PDF_MODULE,
"JPEG support in libtiff required for JPEG compression, ignoring option");
break;
#endif
#ifdef ZIP_SUPPORT
case 'z':
t2p->pdf_defaultcompression=T2P_COMPRESS_ZIP;
break;
#endif
#ifndef ZIP_SUPPORT
case 'z':
TIFFWarning(
TIFF2PDF_MODULE,
"Zip support in libtiff required for Zip compression, ignoring option");
break;
#endif
case 'q':
t2p->pdf_defaultcompressionquality=atoi(optarg);
break;
case 'n':
t2p->pdf_nopassthrough=1;
break;
case 'd':
t2p->pdf_defaultcompression=T2P_COMPRESS_NONE;
break;
case 'u':
if(optarg[0]=='m'){
t2p->pdf_centimeters=1;
}
break;
case 'x':
t2p->pdf_defaultxres =
(float)atof(optarg) / (t2p->pdf_centimeters?2.54F:1.0F);
break;
case 'y':
t2p->pdf_defaultyres =
(float)atof(optarg) / (t2p->pdf_centimeters?2.54F:1.0F);
break;
case 'w':
t2p->pdf_overridepagesize=1;
t2p->pdf_defaultpagewidth =
((float)atof(optarg) * PS_UNIT_SIZE) / (t2p->pdf_centimeters?2.54F:1.0F);
break;
case 'l':
t2p->pdf_overridepagesize=1;
t2p->pdf_defaultpagelength =
((float)atof(optarg) * PS_UNIT_SIZE) / (t2p->pdf_centimeters?2.54F:1.0F);
break;
case 'r':
if(optarg[0]=='o'){
t2p->pdf_overrideres=1;
}
break;
case 'p':
if(tiff2pdf_match_paper_size(
&(t2p->pdf_defaultpagewidth),
&(t2p->pdf_defaultpagelength),
optarg)){
t2p->pdf_overridepagesize=1;
} else {
TIFFWarning(TIFF2PDF_MODULE,
"Unknown paper size %s, ignoring option",
optarg);
}
break;
case 'i':
t2p->pdf_colorspace_invert=1;
break;
case 'F':
t2p->pdf_image_fillpage = 1;
break;
case 'f':
t2p->pdf_fitwindow=1;
break;
case 'e':
if (strlen(optarg) == 0) {
t2p->pdf_datetime[0] = '\0';
} else {
t2p->pdf_datetime[0] = 'D';
t2p->pdf_datetime[1] = ':';
strncpy(t2p->pdf_datetime + 2, optarg,
sizeof(t2p->pdf_datetime) - 3);
t2p->pdf_datetime[sizeof(t2p->pdf_datetime) - 1] = '\0';
}
break;
case 'c':
strncpy(t2p->pdf_creator, optarg, sizeof(t2p->pdf_creator) - 1);
t2p->pdf_creator[sizeof(t2p->pdf_creator) - 1] = '\0';
break;
case 'a':
strncpy(t2p->pdf_author, optarg, sizeof(t2p->pdf_author) - 1);
t2p->pdf_author[sizeof(t2p->pdf_author) - 1] = '\0';
break;
case 't':
strncpy(t2p->pdf_title, optarg, sizeof(t2p->pdf_title) - 1);
t2p->pdf_title[sizeof(t2p->pdf_title) - 1] = '\0';
break;
case 's':
strncpy(t2p->pdf_subject, optarg, sizeof(t2p->pdf_subject) - 1);
t2p->pdf_subject[sizeof(t2p->pdf_subject) - 1] = '\0';
break;
case 'k':
strncpy(t2p->pdf_keywords, optarg, sizeof(t2p->pdf_keywords) - 1);
t2p->pdf_keywords[sizeof(t2p->pdf_keywords) - 1] = '\0';
break;
case 'b':
t2p->pdf_image_interpolate = 1;
break;
case 'h':
case '?':
tiff2pdf_usage();
goto success;
break;
}
}
/*
* Input
*/
if(argc > optind) {
input = TIFFOpen(argv[optind++], "r");
if (input==NULL) {
TIFFError(TIFF2PDF_MODULE,
"Can't open input file %s for reading",
argv[optind-1]);
goto fail;
}
} else {
TIFFError(TIFF2PDF_MODULE, "No input file specified");
tiff2pdf_usage();
goto fail;
}
if(argc > optind) {
TIFFError(TIFF2PDF_MODULE,
"No support for multiple input files");
tiff2pdf_usage();
goto fail;
}
/*
* Output
*/
t2p->outputdisable = 1;
if (outfilename) {
t2p->outputfile = fopen(outfilename, "wb");
if (t2p->outputfile == NULL) {
TIFFError(TIFF2PDF_MODULE,
"Can't open output file %s for writing",
outfilename);
goto fail;
}
} else {
outfilename = "-";
t2p->outputfile = stdout;
}
output = TIFFClientOpen(outfilename, "w", (thandle_t) t2p,
t2p_readproc, t2p_writeproc, t2p_seekproc,
t2p_closeproc, t2p_sizeproc,
t2p_mapproc, t2p_unmapproc);
t2p->outputdisable = 0;
if (output == NULL) {
TIFFError(TIFF2PDF_MODULE,
"Can't initialize output descriptor");
goto fail;
}
/*
* Validate
*/
t2p_validate(t2p);
t2pSeekFile(output, (toff_t) 0, SEEK_SET);
/*
* Write
*/
t2p_write_pdf(t2p, input, output);
if (t2p->t2p_error != 0) {
TIFFError(TIFF2PDF_MODULE,
"An error occurred creating output PDF file");
goto fail;
}
goto success;
fail:
ret = EXIT_FAILURE;
success:
if(input != NULL)
TIFFClose(input);
if (output != NULL)
TIFFClose(output);
if (t2p != NULL)
t2p_free(t2p);
return ret;
}
void tiff2pdf_usage(){
char* lines[]={
"usage: tiff2pdf [options] input.tiff",
"options:",
" -o: output to file name",
#ifdef JPEG_SUPPORT
" -j: compress with JPEG",
#endif
#ifdef ZIP_SUPPORT
" -z: compress with Zip/Deflate",
#endif
" -q: compression quality",
" -n: no compressed data passthrough",
" -d: do not compress (decompress)",
" -i: invert colors",
" -u: set distance unit, 'i' for inch, 'm' for centimeter",
" -x: set x resolution default in dots per unit",
" -y: set y resolution default in dots per unit",
" -w: width in units",
" -l: length in units",
" -r: 'd' for resolution default, 'o' for resolution override",
" -p: paper size, eg \"letter\", \"legal\", \"A4\"",
" -F: make the tiff fill the PDF page",
" -f: set PDF \"Fit Window\" user preference",
" -e: date, overrides image or current date/time default, YYYYMMDDHHMMSS",
" -c: sets document creator, overrides image software default",
" -a: sets document author, overrides image artist default",
" -t: sets document title, overrides image document name default",
" -s: sets document subject, overrides image image description default",
" -k: sets document keywords",
" -b: set PDF \"Interpolate\" user preference",
" -h: usage",
NULL
};
int i=0;
fprintf(stderr, "%s\n\n", TIFFGetVersion());
for (i=0;lines[i]!=NULL;i++){
fprintf(stderr, "%s\n", lines[i]);
}
return;
}
int tiff2pdf_match_paper_size(float* width, float* length, char* papersize){
size_t i, len;
const char* sizes[]={
"LETTER", "A4", "LEGAL",
"EXECUTIVE", "LETTER", "LEGAL", "LEDGER", "TABLOID",
"A", "B", "C", "D", "E", "F", "G", "H", "J", "K",
"A10", "A9", "A8", "A7", "A6", "A5", "A4", "A3", "A2", "A1", "A0",
"2A0", "4A0", "2A", "4A",
"B10", "B9", "B8", "B7", "B6", "B5", "B4", "B3", "B2", "B1", "B0",
"JISB10", "JISB9", "JISB8", "JISB7", "JISB6", "JISB5", "JISB4",
"JISB3", "JISB2", "JISB1", "JISB0",
"C10", "C9", "C8", "C7", "C6", "C5", "C4", "C3", "C2", "C1", "C0",
"RA2", "RA1", "RA0", "SRA4", "SRA3", "SRA2", "SRA1", "SRA0",
"A3EXTRA", "A4EXTRA",
"STATEMENT", "FOLIO", "QUARTO",
NULL
} ;
const int widths[]={
612, 595, 612,
522, 612,612,792,792,
612,792,1224,1584,2448,2016,792,2016,2448,2880,
74,105,147,210,298,420,595,842,1191,1684,2384,3370,4768,3370,4768,
88,125,176,249,354,499,709,1001,1417,2004,2835,
91,128,181,258,363,516,729,1032,1460,2064,2920,
79,113,162,230,323,459,649,918,1298,1298,2599,
1219,1729,2438,638,907,1276,1814,2551,
914,667,
396, 612, 609,
0
};
const int lengths[]={
792,842,1008,
756,792,1008,1224,1224,
792,1224,1584,2448,3168,2880,6480,10296,12672,10296,
105,147,210,298,420,595,842,1191,1684,2384,3370,4768,6741,4768,6741,
125,176,249,354,499,709,1001,1417,2004,2835,4008,
128,181,258,363,516,729,1032,1460,2064,2920,4127,
113,162,230,323,459,649,918,1298,1837,1837,3677,
1729,2438,3458,907,1276,1814,2551,3628,
1262,914,
612, 936, 780,
0
};
len=strlen(papersize);
for(i=0;i<len;i++){
papersize[i]=toupper((int) papersize[i]);
}
for(i=0;sizes[i]!=NULL; i++){
if (strcmp( (const char*)papersize, sizes[i])==0){
*width=(float)widths[i];
*length=(float)lengths[i];
return(1);
}
}
return(0);
}
/*
* This function allocates and initializes a T2P context struct pointer.
*/
T2P* t2p_init()
{
T2P* t2p = (T2P*) _TIFFmalloc(sizeof(T2P));
if(t2p==NULL){
TIFFError(
TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory for t2p_init",
(unsigned long) sizeof(T2P));
return( (T2P*) NULL );
}
_TIFFmemset(t2p, 0x00, sizeof(T2P));
t2p->pdf_majorversion=1;
t2p->pdf_minorversion=1;
t2p->pdf_defaultxres=300.0;
t2p->pdf_defaultyres=300.0;
t2p->pdf_defaultpagewidth=612.0;
t2p->pdf_defaultpagelength=792.0;
t2p->pdf_xrefcount=3; /* Catalog, Info, Pages */
return(t2p);
}
/*
* This function frees a T2P context struct pointer and any allocated data fields of it.
*/
void t2p_free(T2P* t2p)
{
int i = 0;
if (t2p != NULL) {
if(t2p->pdf_xrefoffsets != NULL){
_TIFFfree( (tdata_t) t2p->pdf_xrefoffsets);
}
if(t2p->tiff_pages != NULL){
_TIFFfree( (tdata_t) t2p->tiff_pages);
}
for(i=0;i<t2p->tiff_pagecount;i++){
if(t2p->tiff_tiles[i].tiles_tiles != NULL){
_TIFFfree( (tdata_t) t2p->tiff_tiles[i].tiles_tiles);
}
}
if(t2p->tiff_tiles != NULL){
_TIFFfree( (tdata_t) t2p->tiff_tiles);
}
if(t2p->pdf_palette != NULL){
_TIFFfree( (tdata_t) t2p->pdf_palette);
}
#ifdef OJPEG_SUPPORT
if(t2p->pdf_ojpegdata != NULL){
_TIFFfree( (tdata_t) t2p->pdf_ojpegdata);
}
#endif
_TIFFfree( (tdata_t) t2p );
}
return;
}
/*
This function validates the values of a T2P context struct pointer
before calling t2p_write_pdf with it.
*/
void t2p_validate(T2P* t2p){
#ifdef JPEG_SUPPORT
if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){
if(t2p->pdf_defaultcompressionquality>100 ||
t2p->pdf_defaultcompressionquality<1){
t2p->pdf_defaultcompressionquality=0;
}
}
#endif
#ifdef ZIP_SUPPORT
if(t2p->pdf_defaultcompression==T2P_COMPRESS_ZIP){
uint16 m=t2p->pdf_defaultcompressionquality%100;
if(t2p->pdf_defaultcompressionquality/100 > 9 ||
(m>1 && m<10) || m>15){
t2p->pdf_defaultcompressionquality=0;
}
if(t2p->pdf_defaultcompressionquality%100 !=0){
t2p->pdf_defaultcompressionquality/=100;
t2p->pdf_defaultcompressionquality*=100;
TIFFError(
TIFF2PDF_MODULE,
"PNG Group predictor differencing not implemented, assuming compression quality %u",
t2p->pdf_defaultcompressionquality);
}
t2p->pdf_defaultcompressionquality%=100;
if(t2p->pdf_minorversion<2){t2p->pdf_minorversion=2;}
}
#endif
(void)0;
return;
}
/*
This function scans the input TIFF file for pages. It attempts
to determine which IFD's of the TIFF file contain image document
pages. For each, it gathers some information that has to do
with the output of the PDF document as a whole.
*/
void t2p_read_tiff_init(T2P* t2p, TIFF* input){
tdir_t directorycount=0;
tdir_t i=0;
uint16 pagen=0;
uint16 paged=0;
uint16 xuint16=0;
directorycount=TIFFNumberOfDirectories(input);
t2p->tiff_pages = (T2P_PAGE*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,directorycount,sizeof(T2P_PAGE)));
if(t2p->tiff_pages==NULL){
TIFFError(
TIFF2PDF_MODULE,
"Can't allocate " TIFF_SIZE_FORMAT " bytes of memory for tiff_pages array, %s",
(TIFF_SIZE_T) directorycount * sizeof(T2P_PAGE),
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
_TIFFmemset( t2p->tiff_pages, 0x00, directorycount * sizeof(T2P_PAGE));
t2p->tiff_tiles = (T2P_TILES*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,directorycount,sizeof(T2P_TILES)));
if(t2p->tiff_tiles==NULL){
TIFFError(
TIFF2PDF_MODULE,
"Can't allocate " TIFF_SIZE_FORMAT " bytes of memory for tiff_tiles array, %s",
(TIFF_SIZE_T) directorycount * sizeof(T2P_TILES),
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
_TIFFmemset( t2p->tiff_tiles, 0x00, directorycount * sizeof(T2P_TILES));
for(i=0;i<directorycount;i++){
uint32 subfiletype = 0;
if(!TIFFSetDirectory(input, i)){
TIFFError(
TIFF2PDF_MODULE,
"Can't set directory %u of input file %s",
i,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
if(TIFFGetField(input, TIFFTAG_PAGENUMBER, &pagen, &paged)){
if((pagen>paged) && (paged != 0)){
t2p->tiff_pages[t2p->tiff_pagecount].page_number =
paged;
} else {
t2p->tiff_pages[t2p->tiff_pagecount].page_number =
pagen;
}
goto ispage2;
}
if(TIFFGetField(input, TIFFTAG_SUBFILETYPE, &subfiletype)){
if ( ((subfiletype & FILETYPE_PAGE) != 0)
|| (subfiletype == 0)){
goto ispage;
} else {
goto isnotpage;
}
}
if(TIFFGetField(input, TIFFTAG_OSUBFILETYPE, &subfiletype)){
if ((subfiletype == OFILETYPE_IMAGE)
|| (subfiletype == OFILETYPE_PAGE)
|| (subfiletype == 0) ){
goto ispage;
} else {
goto isnotpage;
}
}
ispage:
t2p->tiff_pages[t2p->tiff_pagecount].page_number=t2p->tiff_pagecount;
ispage2:
t2p->tiff_pages[t2p->tiff_pagecount].page_directory=i;
if(TIFFIsTiled(input)){
t2p->tiff_pages[t2p->tiff_pagecount].page_tilecount =
TIFFNumberOfTiles(input);
}
t2p->tiff_pagecount++;
isnotpage:
(void)0;
}
qsort((void*) t2p->tiff_pages, t2p->tiff_pagecount,
sizeof(T2P_PAGE), t2p_cmp_t2p_page);
for(i=0;i<t2p->tiff_pagecount;i++){
t2p->pdf_xrefcount += 5;
TIFFSetDirectory(input, t2p->tiff_pages[i].page_directory );
if((TIFFGetField(input, TIFFTAG_PHOTOMETRIC, &xuint16)
&& (xuint16==PHOTOMETRIC_PALETTE))
|| TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)) {
t2p->tiff_pages[i].page_extra++;
t2p->pdf_xrefcount++;
}
#ifdef ZIP_SUPPORT
if (TIFFGetField(input, TIFFTAG_COMPRESSION, &xuint16)) {
if( (xuint16== COMPRESSION_DEFLATE ||
xuint16== COMPRESSION_ADOBE_DEFLATE) &&
((t2p->tiff_pages[i].page_tilecount != 0)
|| TIFFNumberOfStrips(input)==1) &&
(t2p->pdf_nopassthrough==0) ){
if(t2p->pdf_minorversion<2){t2p->pdf_minorversion=2;}
}
}
#endif
if (TIFFGetField(input, TIFFTAG_TRANSFERFUNCTION,
&(t2p->tiff_transferfunction[0]),
&(t2p->tiff_transferfunction[1]),
&(t2p->tiff_transferfunction[2]))) {
if((t2p->tiff_transferfunction[1] != (float*) NULL) &&
(t2p->tiff_transferfunction[2] != (float*) NULL) &&
(t2p->tiff_transferfunction[1] !=
t2p->tiff_transferfunction[0])) {
t2p->tiff_transferfunctioncount = 3;
t2p->tiff_pages[i].page_extra += 4;
t2p->pdf_xrefcount += 4;
} else {
t2p->tiff_transferfunctioncount = 1;
t2p->tiff_pages[i].page_extra += 2;
t2p->pdf_xrefcount += 2;
}
if(t2p->pdf_minorversion < 2)
t2p->pdf_minorversion = 2;
} else {
t2p->tiff_transferfunctioncount=0;
}
if( TIFFGetField(
input,
TIFFTAG_ICCPROFILE,
&(t2p->tiff_iccprofilelength),
&(t2p->tiff_iccprofile)) != 0){
t2p->tiff_pages[i].page_extra++;
t2p->pdf_xrefcount++;
if(t2p->pdf_minorversion<3){t2p->pdf_minorversion=3;}
}
t2p->tiff_tiles[i].tiles_tilecount=
t2p->tiff_pages[i].page_tilecount;
if( (TIFFGetField(input, TIFFTAG_PLANARCONFIG, &xuint16) != 0)
&& (xuint16 == PLANARCONFIG_SEPARATE ) ){
if( !TIFFGetField(input, TIFFTAG_SAMPLESPERPIXEL, &xuint16) )
{
TIFFError(
TIFF2PDF_MODULE,
"Missing SamplesPerPixel, %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
if( (t2p->tiff_tiles[i].tiles_tilecount % xuint16) != 0 )
{
TIFFError(
TIFF2PDF_MODULE,
"Invalid tile count, %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
t2p->tiff_tiles[i].tiles_tilecount/= xuint16;
}
if( t2p->tiff_tiles[i].tiles_tilecount > 0){
t2p->pdf_xrefcount +=
(t2p->tiff_tiles[i].tiles_tilecount -1)*2;
TIFFGetField(input,
TIFFTAG_TILEWIDTH,
&( t2p->tiff_tiles[i].tiles_tilewidth) );
TIFFGetField(input,
TIFFTAG_TILELENGTH,
&( t2p->tiff_tiles[i].tiles_tilelength) );
t2p->tiff_tiles[i].tiles_tiles =
(T2P_TILE*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,t2p->tiff_tiles[i].tiles_tilecount,
sizeof(T2P_TILE)) );
if( t2p->tiff_tiles[i].tiles_tiles == NULL){
TIFFError(
TIFF2PDF_MODULE,
"Can't allocate " TIFF_SIZE_FORMAT " bytes of memory for t2p_read_tiff_init, %s",
(TIFF_SIZE_T) t2p->tiff_tiles[i].tiles_tilecount * sizeof(T2P_TILE),
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
}
}
return;
}
/*
* This function is used by qsort to sort a T2P_PAGE* array of page structures
* by page number. If the page numbers are the same, we fall back to comparing
* directory numbers to preserve the order of the input file.
*/
int t2p_cmp_t2p_page(const void* e1, const void* e2){
int d;
d = (int32)(((T2P_PAGE*)e1)->page_number) - (int32)(((T2P_PAGE*)e2)->page_number);
if(d == 0){
d = (int32)(((T2P_PAGE*)e1)->page_directory) - (int32)(((T2P_PAGE*)e2)->page_directory);
}
return d;
}
/*
This function sets the input directory to the directory of a given
page and determines information about the image. It checks
the image characteristics to determine if it is possible to convert
the image data into a page of PDF output, setting values of the T2P
struct for this page. It determines what color space is used in
the output PDF to represent the image.
It determines if the image can be converted as raw data without
requiring transcoding of the image data.
*/
void t2p_read_tiff_data(T2P* t2p, TIFF* input){
int i=0;
uint16* r;
uint16* g;
uint16* b;
uint16* a;
uint16 xuint16;
uint16* xuint16p;
float* xfloatp;
t2p->pdf_transcode = T2P_TRANSCODE_ENCODE;
t2p->pdf_sample = T2P_SAMPLE_NOTHING;
t2p->pdf_switchdecode = t2p->pdf_colorspace_invert;
TIFFSetDirectory(input, t2p->tiff_pages[t2p->pdf_page].page_directory);
TIFFGetField(input, TIFFTAG_IMAGEWIDTH, &(t2p->tiff_width));
if(t2p->tiff_width == 0){
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with zero width",
TIFFFileName(input) );
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
TIFFGetField(input, TIFFTAG_IMAGELENGTH, &(t2p->tiff_length));
if(t2p->tiff_length == 0){
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with zero length",
TIFFFileName(input) );
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
if(TIFFGetField(input, TIFFTAG_COMPRESSION, &(t2p->tiff_compression)) == 0){
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with no compression tag",
TIFFFileName(input) );
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
if( TIFFIsCODECConfigured(t2p->tiff_compression) == 0){
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with compression type %u: not configured",
TIFFFileName(input),
t2p->tiff_compression
);
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
TIFFGetFieldDefaulted(input, TIFFTAG_BITSPERSAMPLE, &(t2p->tiff_bitspersample));
switch(t2p->tiff_bitspersample){
case 1:
case 2:
case 4:
case 8:
break;
case 0:
TIFFWarning(
TIFF2PDF_MODULE,
"Image %s has 0 bits per sample, assuming 1",
TIFFFileName(input));
t2p->tiff_bitspersample=1;
break;
default:
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with %u bits per sample",
TIFFFileName(input),
t2p->tiff_bitspersample);
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
TIFFGetFieldDefaulted(input, TIFFTAG_SAMPLESPERPIXEL, &(t2p->tiff_samplesperpixel));
if(t2p->tiff_samplesperpixel>4){
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with %u samples per pixel",
TIFFFileName(input),
t2p->tiff_samplesperpixel);
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
if(t2p->tiff_samplesperpixel==0){
TIFFWarning(
TIFF2PDF_MODULE,
"Image %s has 0 samples per pixel, assuming 1",
TIFFFileName(input));
t2p->tiff_samplesperpixel=1;
}
if(TIFFGetField(input, TIFFTAG_SAMPLEFORMAT, &xuint16) != 0 ){
switch(xuint16){
case 0:
case 1:
case 4:
break;
default:
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with sample format %u",
TIFFFileName(input),
xuint16);
t2p->t2p_error = T2P_ERR_ERROR;
return;
break;
}
}
TIFFGetFieldDefaulted(input, TIFFTAG_FILLORDER, &(t2p->tiff_fillorder));
if(TIFFGetField(input, TIFFTAG_PHOTOMETRIC, &(t2p->tiff_photometric)) == 0){
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with no photometric interpretation tag",
TIFFFileName(input) );
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
switch(t2p->tiff_photometric){
case PHOTOMETRIC_MINISWHITE:
case PHOTOMETRIC_MINISBLACK:
if (t2p->tiff_bitspersample==1){
t2p->pdf_colorspace=T2P_CS_BILEVEL;
if(t2p->tiff_photometric==PHOTOMETRIC_MINISWHITE){
t2p->pdf_switchdecode ^= 1;
}
} else {
t2p->pdf_colorspace=T2P_CS_GRAY;
if(t2p->tiff_photometric==PHOTOMETRIC_MINISWHITE){
t2p->pdf_switchdecode ^= 1;
}
}
break;
case PHOTOMETRIC_RGB:
t2p->pdf_colorspace=T2P_CS_RGB;
if(t2p->tiff_samplesperpixel == 3){
break;
}
if(TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)){
if(xuint16==1)
goto photometric_palette;
}
if(t2p->tiff_samplesperpixel > 3) {
if(t2p->tiff_samplesperpixel == 4) {
t2p->pdf_colorspace = T2P_CS_RGB;
if(TIFFGetField(input,
TIFFTAG_EXTRASAMPLES,
&xuint16, &xuint16p)
&& xuint16 == 1) {
if(xuint16p[0] == EXTRASAMPLE_ASSOCALPHA){
if( t2p->tiff_bitspersample != 8 )
{
TIFFError(
TIFF2PDF_MODULE,
"No support for BitsPerSample=%d for RGBA",
t2p->tiff_bitspersample);
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
t2p->pdf_sample=T2P_SAMPLE_RGBAA_TO_RGB;
break;
}
if(xuint16p[0] == EXTRASAMPLE_UNASSALPHA){
if( t2p->tiff_bitspersample != 8 )
{
TIFFError(
TIFF2PDF_MODULE,
"No support for BitsPerSample=%d for RGBA",
t2p->tiff_bitspersample);
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
t2p->pdf_sample=T2P_SAMPLE_RGBA_TO_RGB;
break;
}
TIFFWarning(
TIFF2PDF_MODULE,
"RGB image %s has 4 samples per pixel, assuming RGBA",
TIFFFileName(input));
break;
}
t2p->pdf_colorspace=T2P_CS_CMYK;
t2p->pdf_switchdecode ^= 1;
TIFFWarning(
TIFF2PDF_MODULE,
"RGB image %s has 4 samples per pixel, assuming inverse CMYK",
TIFFFileName(input));
break;
} else {
TIFFError(
TIFF2PDF_MODULE,
"No support for RGB image %s with %u samples per pixel",
TIFFFileName(input),
t2p->tiff_samplesperpixel);
t2p->t2p_error = T2P_ERR_ERROR;
break;
}
} else {
TIFFError(
TIFF2PDF_MODULE,
"No support for RGB image %s with %u samples per pixel",
TIFFFileName(input),
t2p->tiff_samplesperpixel);
t2p->t2p_error = T2P_ERR_ERROR;
break;
}
case PHOTOMETRIC_PALETTE:
photometric_palette:
if(t2p->tiff_samplesperpixel!=1){
TIFFError(
TIFF2PDF_MODULE,
"No support for palettized image %s with not one sample per pixel",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
t2p->pdf_colorspace=T2P_CS_RGB | T2P_CS_PALETTE;
t2p->pdf_palettesize=0x0001<<t2p->tiff_bitspersample;
if(!TIFFGetField(input, TIFFTAG_COLORMAP, &r, &g, &b)){
TIFFError(
TIFF2PDF_MODULE,
"Palettized image %s has no color map",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
if(t2p->pdf_palette != NULL){
_TIFFfree(t2p->pdf_palette);
t2p->pdf_palette=NULL;
}
t2p->pdf_palette = (unsigned char*)
_TIFFmalloc(TIFFSafeMultiply(tmsize_t,t2p->pdf_palettesize,3));
if(t2p->pdf_palette==NULL){
TIFFError(
TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_read_tiff_image, %s",
t2p->pdf_palettesize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
for(i=0;i<t2p->pdf_palettesize;i++){
t2p->pdf_palette[(i*3)] = (unsigned char) (r[i]>>8);
t2p->pdf_palette[(i*3)+1]= (unsigned char) (g[i]>>8);
t2p->pdf_palette[(i*3)+2]= (unsigned char) (b[i]>>8);
}
t2p->pdf_palettesize *= 3;
break;
case PHOTOMETRIC_SEPARATED:
if(TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)){
if(xuint16==1){
goto photometric_palette_cmyk;
}
}
if( TIFFGetField(input, TIFFTAG_INKSET, &xuint16) ){
if(xuint16 != INKSET_CMYK){
TIFFError(
TIFF2PDF_MODULE,
"No support for %s because its inkset is not CMYK",
TIFFFileName(input) );
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
}
if(t2p->tiff_samplesperpixel==4){
t2p->pdf_colorspace=T2P_CS_CMYK;
} else {
TIFFError(
TIFF2PDF_MODULE,
"No support for %s because it has %u samples per pixel",
TIFFFileName(input),
t2p->tiff_samplesperpixel);
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
break;
photometric_palette_cmyk:
if(t2p->tiff_samplesperpixel!=1){
TIFFError(
TIFF2PDF_MODULE,
"No support for palettized CMYK image %s with not one sample per pixel",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
t2p->pdf_colorspace=T2P_CS_CMYK | T2P_CS_PALETTE;
t2p->pdf_palettesize=0x0001<<t2p->tiff_bitspersample;
if(!TIFFGetField(input, TIFFTAG_COLORMAP, &r, &g, &b, &a)){
TIFFError(
TIFF2PDF_MODULE,
"Palettized image %s has no color map",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
if(t2p->pdf_palette != NULL){
_TIFFfree(t2p->pdf_palette);
t2p->pdf_palette=NULL;
}
t2p->pdf_palette = (unsigned char*)
_TIFFmalloc(TIFFSafeMultiply(tmsize_t,t2p->pdf_palettesize,4));
if(t2p->pdf_palette==NULL){
TIFFError(
TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_read_tiff_image, %s",
t2p->pdf_palettesize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
for(i=0;i<t2p->pdf_palettesize;i++){
t2p->pdf_palette[(i*4)] = (unsigned char) (r[i]>>8);
t2p->pdf_palette[(i*4)+1]= (unsigned char) (g[i]>>8);
t2p->pdf_palette[(i*4)+2]= (unsigned char) (b[i]>>8);
t2p->pdf_palette[(i*4)+3]= (unsigned char) (a[i]>>8);
}
t2p->pdf_palettesize *= 4;
break;
case PHOTOMETRIC_YCBCR:
t2p->pdf_colorspace=T2P_CS_RGB;
if(t2p->tiff_samplesperpixel==1){
t2p->pdf_colorspace=T2P_CS_GRAY;
t2p->tiff_photometric=PHOTOMETRIC_MINISBLACK;
break;
}
t2p->pdf_sample=T2P_SAMPLE_YCBCR_TO_RGB;
#ifdef JPEG_SUPPORT
if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){
t2p->pdf_sample=T2P_SAMPLE_NOTHING;
}
#endif
break;
case PHOTOMETRIC_CIELAB:
if( t2p->tiff_samplesperpixel != 3){
TIFFError(
TIFF2PDF_MODULE,
"Unsupported samplesperpixel = %d for CIELAB",
t2p->tiff_samplesperpixel);
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
if( t2p->tiff_bitspersample != 8){
TIFFError(
TIFF2PDF_MODULE,
"Invalid bitspersample = %d for CIELAB",
t2p->tiff_bitspersample);
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
t2p->pdf_labrange[0]= -127;
t2p->pdf_labrange[1]= 127;
t2p->pdf_labrange[2]= -127;
t2p->pdf_labrange[3]= 127;
t2p->pdf_sample=T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED;
t2p->pdf_colorspace=T2P_CS_LAB;
break;
case PHOTOMETRIC_ICCLAB:
t2p->pdf_labrange[0]= 0;
t2p->pdf_labrange[1]= 255;
t2p->pdf_labrange[2]= 0;
t2p->pdf_labrange[3]= 255;
t2p->pdf_colorspace=T2P_CS_LAB;
break;
case PHOTOMETRIC_ITULAB:
if( t2p->tiff_samplesperpixel != 3){
TIFFError(
TIFF2PDF_MODULE,
"Unsupported samplesperpixel = %d for ITULAB",
t2p->tiff_samplesperpixel);
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
if( t2p->tiff_bitspersample != 8){
TIFFError(
TIFF2PDF_MODULE,
"Invalid bitspersample = %d for ITULAB",
t2p->tiff_bitspersample);
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
t2p->pdf_labrange[0]=-85;
t2p->pdf_labrange[1]=85;
t2p->pdf_labrange[2]=-75;
t2p->pdf_labrange[3]=124;
t2p->pdf_sample=T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED;
t2p->pdf_colorspace=T2P_CS_LAB;
break;
case PHOTOMETRIC_LOGL:
case PHOTOMETRIC_LOGLUV:
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with photometric interpretation LogL/LogLuv",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
default:
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with photometric interpretation %u",
TIFFFileName(input),
t2p->tiff_photometric);
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
if(TIFFGetField(input, TIFFTAG_PLANARCONFIG, &(t2p->tiff_planar))){
switch(t2p->tiff_planar){
case 0:
TIFFWarning(
TIFF2PDF_MODULE,
"Image %s has planar configuration 0, assuming 1",
TIFFFileName(input));
t2p->tiff_planar=PLANARCONFIG_CONTIG;
case PLANARCONFIG_CONTIG:
break;
case PLANARCONFIG_SEPARATE:
t2p->pdf_sample=T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG;
if(t2p->tiff_bitspersample!=8){
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with separated planar configuration and %u bits per sample",
TIFFFileName(input),
t2p->tiff_bitspersample);
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
break;
default:
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with planar configuration %u",
TIFFFileName(input),
t2p->tiff_planar);
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
}
TIFFGetFieldDefaulted(input, TIFFTAG_ORIENTATION,
&(t2p->tiff_orientation));
if(t2p->tiff_orientation>8){
TIFFWarning(TIFF2PDF_MODULE,
"Image %s has orientation %u, assuming 0",
TIFFFileName(input), t2p->tiff_orientation);
t2p->tiff_orientation=0;
}
if(TIFFGetField(input, TIFFTAG_XRESOLUTION, &(t2p->tiff_xres) ) == 0){
t2p->tiff_xres=0.0;
}
if(TIFFGetField(input, TIFFTAG_YRESOLUTION, &(t2p->tiff_yres) ) == 0){
t2p->tiff_yres=0.0;
}
TIFFGetFieldDefaulted(input, TIFFTAG_RESOLUTIONUNIT,
&(t2p->tiff_resunit));
if(t2p->tiff_resunit == RESUNIT_CENTIMETER) {
t2p->tiff_xres *= 2.54F;
t2p->tiff_yres *= 2.54F;
} else if (t2p->tiff_resunit != RESUNIT_INCH
&& t2p->pdf_centimeters != 0) {
t2p->tiff_xres *= 2.54F;
t2p->tiff_yres *= 2.54F;
}
t2p_compose_pdf_page(t2p);
if( t2p->t2p_error == T2P_ERR_ERROR )
return;
t2p->pdf_transcode = T2P_TRANSCODE_ENCODE;
if(t2p->pdf_nopassthrough==0){
#ifdef CCITT_SUPPORT
if(t2p->tiff_compression==COMPRESSION_CCITTFAX4
){
if(TIFFIsTiled(input) || (TIFFNumberOfStrips(input)==1) ){
t2p->pdf_transcode = T2P_TRANSCODE_RAW;
t2p->pdf_compression=T2P_COMPRESS_G4;
}
}
#endif
#ifdef ZIP_SUPPORT
if(t2p->tiff_compression== COMPRESSION_ADOBE_DEFLATE
|| t2p->tiff_compression==COMPRESSION_DEFLATE){
if(TIFFIsTiled(input) || (TIFFNumberOfStrips(input)==1) ){
t2p->pdf_transcode = T2P_TRANSCODE_RAW;
t2p->pdf_compression=T2P_COMPRESS_ZIP;
}
}
#endif
#ifdef OJPEG_SUPPORT
if(t2p->tiff_compression==COMPRESSION_OJPEG){
t2p->pdf_transcode = T2P_TRANSCODE_RAW;
t2p->pdf_compression=T2P_COMPRESS_JPEG;
t2p_process_ojpeg_tables(t2p, input);
}
#endif
#ifdef JPEG_SUPPORT
if(t2p->tiff_compression==COMPRESSION_JPEG){
t2p->pdf_transcode = T2P_TRANSCODE_RAW;
t2p->pdf_compression=T2P_COMPRESS_JPEG;
}
#endif
(void)0;
}
if(t2p->pdf_transcode!=T2P_TRANSCODE_RAW){
t2p->pdf_compression = t2p->pdf_defaultcompression;
}
#ifdef JPEG_SUPPORT
if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){
if(t2p->pdf_colorspace & T2P_CS_PALETTE){
t2p->pdf_sample|=T2P_SAMPLE_REALIZE_PALETTE;
t2p->pdf_colorspace ^= T2P_CS_PALETTE;
t2p->tiff_pages[t2p->pdf_page].page_extra--;
}
}
if(t2p->tiff_compression==COMPRESSION_JPEG){
if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with JPEG compression and separated planar configuration",
TIFFFileName(input));
t2p->t2p_error=T2P_ERR_ERROR;
return;
}
}
#endif
#ifdef OJPEG_SUPPORT
if(t2p->tiff_compression==COMPRESSION_OJPEG){
if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with OJPEG compression and separated planar configuration",
TIFFFileName(input));
t2p->t2p_error=T2P_ERR_ERROR;
return;
}
}
#endif
if(t2p->pdf_sample & T2P_SAMPLE_REALIZE_PALETTE){
if(t2p->pdf_colorspace & T2P_CS_CMYK){
t2p->tiff_samplesperpixel=4;
t2p->tiff_photometric=PHOTOMETRIC_SEPARATED;
} else {
t2p->tiff_samplesperpixel=3;
t2p->tiff_photometric=PHOTOMETRIC_RGB;
}
}
if (TIFFGetField(input, TIFFTAG_TRANSFERFUNCTION,
&(t2p->tiff_transferfunction[0]),
&(t2p->tiff_transferfunction[1]),
&(t2p->tiff_transferfunction[2]))) {
if((t2p->tiff_transferfunction[1] != (float*) NULL) &&
(t2p->tiff_transferfunction[2] != (float*) NULL) &&
(t2p->tiff_transferfunction[1] !=
t2p->tiff_transferfunction[0])) {
t2p->tiff_transferfunctioncount=3;
} else {
t2p->tiff_transferfunctioncount=1;
}
} else {
t2p->tiff_transferfunctioncount=0;
}
if(TIFFGetField(input, TIFFTAG_WHITEPOINT, &xfloatp)!=0){
t2p->tiff_whitechromaticities[0]=xfloatp[0];
t2p->tiff_whitechromaticities[1]=xfloatp[1];
if(t2p->pdf_colorspace & T2P_CS_GRAY){
t2p->pdf_colorspace |= T2P_CS_CALGRAY;
}
if(t2p->pdf_colorspace & T2P_CS_RGB){
t2p->pdf_colorspace |= T2P_CS_CALRGB;
}
}
if(TIFFGetField(input, TIFFTAG_PRIMARYCHROMATICITIES, &xfloatp)!=0){
t2p->tiff_primarychromaticities[0]=xfloatp[0];
t2p->tiff_primarychromaticities[1]=xfloatp[1];
t2p->tiff_primarychromaticities[2]=xfloatp[2];
t2p->tiff_primarychromaticities[3]=xfloatp[3];
t2p->tiff_primarychromaticities[4]=xfloatp[4];
t2p->tiff_primarychromaticities[5]=xfloatp[5];
if(t2p->pdf_colorspace & T2P_CS_RGB){
t2p->pdf_colorspace |= T2P_CS_CALRGB;
}
}
if(t2p->pdf_colorspace & T2P_CS_LAB){
if(TIFFGetField(input, TIFFTAG_WHITEPOINT, &xfloatp) != 0){
t2p->tiff_whitechromaticities[0]=xfloatp[0];
t2p->tiff_whitechromaticities[1]=xfloatp[1];
} else {
t2p->tiff_whitechromaticities[0]=0.3457F; /* 0.3127F; */
t2p->tiff_whitechromaticities[1]=0.3585F; /* 0.3290F; */
}
}
if(TIFFGetField(input,
TIFFTAG_ICCPROFILE,
&(t2p->tiff_iccprofilelength),
&(t2p->tiff_iccprofile))!=0){
t2p->pdf_colorspace |= T2P_CS_ICCBASED;
} else {
t2p->tiff_iccprofilelength=0;
t2p->tiff_iccprofile=NULL;
}
#ifdef CCITT_SUPPORT
if( t2p->tiff_bitspersample==1 &&
t2p->tiff_samplesperpixel==1){
t2p->pdf_compression = T2P_COMPRESS_G4;
}
#endif
return;
}
/*
This function returns the necessary size of a data buffer to contain the raw or
uncompressed image data from the input TIFF for a page.
*/
void t2p_read_tiff_size(T2P* t2p, TIFF* input){
uint64* sbc=NULL;
#if defined(JPEG_SUPPORT) || defined (OJPEG_SUPPORT)
unsigned char* jpt=NULL;
tstrip_t i=0;
tstrip_t stripcount=0;
#endif
uint64 k = 0;
if(t2p->pdf_transcode == T2P_TRANSCODE_RAW){
#ifdef CCITT_SUPPORT
if(t2p->pdf_compression == T2P_COMPRESS_G4 ){
TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc);
t2p->tiff_datasize=(tmsize_t)sbc[0];
return;
}
#endif
#ifdef ZIP_SUPPORT
if(t2p->pdf_compression == T2P_COMPRESS_ZIP){
TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc);
t2p->tiff_datasize=(tmsize_t)sbc[0];
return;
}
#endif
#ifdef OJPEG_SUPPORT
if(t2p->tiff_compression == COMPRESSION_OJPEG){
if(!TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc)){
TIFFError(TIFF2PDF_MODULE,
"Input file %s missing field: TIFFTAG_STRIPBYTECOUNTS",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
stripcount=TIFFNumberOfStrips(input);
for(i=0;i<stripcount;i++){
k = checkAdd64(k, sbc[i], t2p);
}
if(TIFFGetField(input, TIFFTAG_JPEGIFOFFSET, &(t2p->tiff_dataoffset))){
if(t2p->tiff_dataoffset != 0){
if(TIFFGetField(input, TIFFTAG_JPEGIFBYTECOUNT, &(t2p->tiff_datasize))!=0){
if((uint64)t2p->tiff_datasize < k) {
TIFFWarning(TIFF2PDF_MODULE,
"Input file %s has short JPEG interchange file byte count",
TIFFFileName(input));
t2p->pdf_ojpegiflength=t2p->tiff_datasize;
k = checkAdd64(k, t2p->tiff_datasize, t2p);
k = checkAdd64(k, 6, t2p);
k = checkAdd64(k, stripcount, t2p);
k = checkAdd64(k, stripcount, t2p);
t2p->tiff_datasize = (tsize_t) k;
if ((uint64) t2p->tiff_datasize != k) {
TIFFError(TIFF2PDF_MODULE, "Integer overflow");
t2p->t2p_error = T2P_ERR_ERROR;
}
return;
}
return;
}else {
TIFFError(TIFF2PDF_MODULE,
"Input file %s missing field: TIFFTAG_JPEGIFBYTECOUNT",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
}
}
k = checkAdd64(k, stripcount, t2p);
k = checkAdd64(k, stripcount, t2p);
k = checkAdd64(k, 2048, t2p);
t2p->tiff_datasize = (tsize_t) k;
if ((uint64) t2p->tiff_datasize != k) {
TIFFError(TIFF2PDF_MODULE, "Integer overflow");
t2p->t2p_error = T2P_ERR_ERROR;
}
return;
}
#endif
#ifdef JPEG_SUPPORT
if(t2p->tiff_compression == COMPRESSION_JPEG) {
uint32 count = 0;
if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0 ){
if(count > 4){
k += count;
k -= 2; /* don't use EOI of header */
}
} else {
k = 2; /* SOI for first strip */
}
stripcount=TIFFNumberOfStrips(input);
if(!TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc)){
TIFFError(TIFF2PDF_MODULE,
"Input file %s missing field: TIFFTAG_STRIPBYTECOUNTS",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
for(i=0;i<stripcount;i++){
k = checkAdd64(k, sbc[i], t2p);
k -=2; /* don't use EOI of strip */
k +=2; /* add space for restart marker */
}
k = checkAdd64(k, 2, t2p); /* use EOI of last strip */
k = checkAdd64(k, 6, t2p); /* for DRI marker of first strip */
t2p->tiff_datasize = (tsize_t) k;
if ((uint64) t2p->tiff_datasize != k) {
TIFFError(TIFF2PDF_MODULE, "Integer overflow");
t2p->t2p_error = T2P_ERR_ERROR;
}
return;
}
#endif
(void) 0;
}
k = checkMultiply64(TIFFScanlineSize(input), t2p->tiff_length, t2p);
if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){
k = checkMultiply64(k, t2p->tiff_samplesperpixel, t2p);
}
if (k == 0) {
/* Assume we had overflow inside TIFFScanlineSize */
t2p->t2p_error = T2P_ERR_ERROR;
}
t2p->tiff_datasize = (tsize_t) k;
if ((uint64) t2p->tiff_datasize != k) {
TIFFError(TIFF2PDF_MODULE, "Integer overflow");
t2p->t2p_error = T2P_ERR_ERROR;
}
return;
}
/*
This function returns the necessary size of a data buffer to contain the raw or
uncompressed image data from the input TIFF for a tile of a page.
*/
void t2p_read_tiff_size_tile(T2P* t2p, TIFF* input, ttile_t tile){
uint64* tbc = NULL;
uint16 edge=0;
#ifdef JPEG_SUPPORT
unsigned char* jpt;
#endif
uint64 k;
edge |= t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile);
edge |= t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile);
if(t2p->pdf_transcode==T2P_TRANSCODE_RAW){
if(edge
#if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT)
&& !(t2p->pdf_compression==T2P_COMPRESS_JPEG)
#endif
){
t2p->tiff_datasize=TIFFTileSize(input);
if (t2p->tiff_datasize == 0) {
/* Assume we had overflow inside TIFFTileSize */
t2p->t2p_error = T2P_ERR_ERROR;
}
return;
} else {
TIFFGetField(input, TIFFTAG_TILEBYTECOUNTS, &tbc);
k=tbc[tile];
#ifdef OJPEG_SUPPORT
if(t2p->tiff_compression==COMPRESSION_OJPEG){
k = checkAdd64(k, 2048, t2p);
}
#endif
#ifdef JPEG_SUPPORT
if(t2p->tiff_compression==COMPRESSION_JPEG) {
uint32 count = 0;
if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt)!=0){
if(count > 4){
k = checkAdd64(k, count, t2p);
k -= 2; /* don't use EOI of header or SOI of tile */
}
}
}
#endif
t2p->tiff_datasize = (tsize_t) k;
if ((uint64) t2p->tiff_datasize != k) {
TIFFError(TIFF2PDF_MODULE, "Integer overflow");
t2p->t2p_error = T2P_ERR_ERROR;
}
return;
}
}
k = TIFFTileSize(input);
if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){
k = checkMultiply64(k, t2p->tiff_samplesperpixel, t2p);
}
if (k == 0) {
/* Assume we had overflow inside TIFFTileSize */
t2p->t2p_error = T2P_ERR_ERROR;
}
t2p->tiff_datasize = (tsize_t) k;
if ((uint64) t2p->tiff_datasize != k) {
TIFFError(TIFF2PDF_MODULE, "Integer overflow");
t2p->t2p_error = T2P_ERR_ERROR;
}
return;
}
/*
* This functions returns a non-zero value when the tile is on the right edge
* and does not have full imaged tile width.
*/
int t2p_tile_is_right_edge(T2P_TILES tiles, ttile_t tile){
if( ((tile+1) % tiles.tiles_tilecountx == 0)
&& (tiles.tiles_edgetilewidth != 0) ){
return(1);
} else {
return(0);
}
}
/*
* This functions returns a non-zero value when the tile is on the bottom edge
* and does not have full imaged tile length.
*/
int t2p_tile_is_bottom_edge(T2P_TILES tiles, ttile_t tile){
if( ((tile+1) > (tiles.tiles_tilecount-tiles.tiles_tilecountx) )
&& (tiles.tiles_edgetilelength != 0) ){
return(1);
} else {
return(0);
}
}
/*
* This function returns a non-zero value when the tile is a right edge tile
* or a bottom edge tile.
*/
int t2p_tile_is_edge(T2P_TILES tiles, ttile_t tile){
return(t2p_tile_is_right_edge(tiles, tile) | t2p_tile_is_bottom_edge(tiles, tile) );
}
/*
This function returns a non-zero value when the tile is a right edge tile and a bottom
edge tile.
*/
int t2p_tile_is_corner_edge(T2P_TILES tiles, ttile_t tile){
return(t2p_tile_is_right_edge(tiles, tile) & t2p_tile_is_bottom_edge(tiles, tile) );
}
/*
This function reads the raster image data from the input TIFF for an image and writes
the data to the output PDF XObject image dictionary stream. It returns the amount written
or zero on error.
*/
tsize_t t2p_readwrite_pdf_image(T2P* t2p, TIFF* input, TIFF* output){
tsize_t written=0;
unsigned char* buffer=NULL;
unsigned char* samplebuffer=NULL;
tsize_t bufferoffset=0;
tsize_t samplebufferoffset=0;
tsize_t read=0;
tstrip_t i=0;
tstrip_t j=0;
tstrip_t stripcount=0;
tsize_t stripsize=0;
tsize_t sepstripcount=0;
tsize_t sepstripsize=0;
#ifdef OJPEG_SUPPORT
toff_t inputoffset=0;
uint16 h_samp=1;
uint16 v_samp=1;
uint16 ri=1;
uint32 rows=0;
#endif /* ifdef OJPEG_SUPPORT */
#ifdef JPEG_SUPPORT
unsigned char* jpt;
float* xfloatp;
uint64* sbc;
unsigned char* stripbuffer;
tsize_t striplength=0;
uint32 max_striplength=0;
#endif /* ifdef JPEG_SUPPORT */
/* Fail if prior error (in particular, can't trust tiff_datasize) */
if (t2p->t2p_error != T2P_ERR_OK)
return(0);
if(t2p->pdf_transcode == T2P_TRANSCODE_RAW){
#ifdef CCITT_SUPPORT
if(t2p->pdf_compression == T2P_COMPRESS_G4){
buffer = (unsigned char*)
_TIFFmalloc(t2p->tiff_datasize);
if (buffer == NULL) {
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory for "
"t2p_readwrite_pdf_image, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
TIFFReadRawStrip(input, 0, (tdata_t) buffer,
t2p->tiff_datasize);
if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){
/*
* make sure is lsb-to-msb
* bit-endianness fill order
*/
TIFFReverseBits(buffer,
t2p->tiff_datasize);
}
t2pWriteFile(output, (tdata_t) buffer,
t2p->tiff_datasize);
_TIFFfree(buffer);
return(t2p->tiff_datasize);
}
#endif /* ifdef CCITT_SUPPORT */
#ifdef ZIP_SUPPORT
if (t2p->pdf_compression == T2P_COMPRESS_ZIP) {
buffer = (unsigned char*)
_TIFFmalloc(t2p->tiff_datasize);
if(buffer == NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
memset(buffer, 0, t2p->tiff_datasize);
TIFFReadRawStrip(input, 0, (tdata_t) buffer,
t2p->tiff_datasize);
if (t2p->tiff_fillorder==FILLORDER_LSB2MSB) {
TIFFReverseBits(buffer,
t2p->tiff_datasize);
}
t2pWriteFile(output, (tdata_t) buffer,
t2p->tiff_datasize);
_TIFFfree(buffer);
return(t2p->tiff_datasize);
}
#endif /* ifdef ZIP_SUPPORT */
#ifdef OJPEG_SUPPORT
if(t2p->tiff_compression == COMPRESSION_OJPEG) {
if(t2p->tiff_dataoffset != 0) {
buffer = (unsigned char*)
_TIFFmalloc(t2p->tiff_datasize);
if(buffer == NULL) {
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
memset(buffer, 0, t2p->tiff_datasize);
if(t2p->pdf_ojpegiflength==0){
inputoffset=t2pSeekFile(input, 0,
SEEK_CUR);
t2pSeekFile(input,
t2p->tiff_dataoffset,
SEEK_SET);
t2pReadFile(input, (tdata_t) buffer,
t2p->tiff_datasize);
t2pSeekFile(input, inputoffset,
SEEK_SET);
t2pWriteFile(output, (tdata_t) buffer,
t2p->tiff_datasize);
_TIFFfree(buffer);
return(t2p->tiff_datasize);
} else {
inputoffset=t2pSeekFile(input, 0,
SEEK_CUR);
t2pSeekFile(input,
t2p->tiff_dataoffset,
SEEK_SET);
bufferoffset = t2pReadFile(input,
(tdata_t) buffer,
t2p->pdf_ojpegiflength);
t2p->pdf_ojpegiflength = 0;
t2pSeekFile(input, inputoffset,
SEEK_SET);
TIFFGetField(input,
TIFFTAG_YCBCRSUBSAMPLING,
&h_samp, &v_samp);
buffer[bufferoffset++]= 0xff;
buffer[bufferoffset++]= 0xdd;
buffer[bufferoffset++]= 0x00;
buffer[bufferoffset++]= 0x04;
h_samp*=8;
v_samp*=8;
ri=(t2p->tiff_width+h_samp-1) / h_samp;
TIFFGetField(input,
TIFFTAG_ROWSPERSTRIP,
&rows);
ri*=(rows+v_samp-1)/v_samp;
buffer[bufferoffset++]= (ri>>8) & 0xff;
buffer[bufferoffset++]= ri & 0xff;
stripcount=TIFFNumberOfStrips(input);
for(i=0;i<stripcount;i++){
if(i != 0 ){
buffer[bufferoffset++]=0xff;
buffer[bufferoffset++]=(0xd0 | ((i-1)%8));
}
bufferoffset+=TIFFReadRawStrip(input,
i,
(tdata_t) &(((unsigned char*)buffer)[bufferoffset]),
-1);
}
t2pWriteFile(output, (tdata_t) buffer, bufferoffset);
_TIFFfree(buffer);
return(bufferoffset);
}
} else {
if(! t2p->pdf_ojpegdata){
TIFFError(TIFF2PDF_MODULE,
"No support for OJPEG image %s with bad tables",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
buffer = (unsigned char*)
_TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
memset(buffer, 0, t2p->tiff_datasize);
_TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength);
bufferoffset=t2p->pdf_ojpegdatalength;
stripcount=TIFFNumberOfStrips(input);
for(i=0;i<stripcount;i++){
if(i != 0){
buffer[bufferoffset++]=0xff;
buffer[bufferoffset++]=(0xd0 | ((i-1)%8));
}
bufferoffset+=TIFFReadRawStrip(input,
i,
(tdata_t) &(((unsigned char*)buffer)[bufferoffset]),
-1);
}
if( ! ( (buffer[bufferoffset-1]==0xd9) && (buffer[bufferoffset-2]==0xff) ) ){
buffer[bufferoffset++]=0xff;
buffer[bufferoffset++]=0xd9;
}
t2pWriteFile(output, (tdata_t) buffer, bufferoffset);
_TIFFfree(buffer);
return(bufferoffset);
#if 0
/*
This hunk of code removed code is clearly
mis-placed and we are not sure where it
should be (if anywhere)
*/
TIFFError(TIFF2PDF_MODULE,
"No support for OJPEG image %s with no JPEG File Interchange offset",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
#endif
}
}
#endif /* ifdef OJPEG_SUPPORT */
#ifdef JPEG_SUPPORT
if(t2p->tiff_compression == COMPRESSION_JPEG) {
uint32 count = 0;
buffer = (unsigned char*)
_TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
memset(buffer, 0, t2p->tiff_datasize);
if (TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0) {
if(count > 4) {
_TIFFmemcpy(buffer, jpt, count);
bufferoffset += count - 2;
}
}
stripcount=TIFFNumberOfStrips(input);
TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc);
for(i=0;i<stripcount;i++){
if(sbc[i]>max_striplength) max_striplength=sbc[i];
}
stripbuffer = (unsigned char*)
_TIFFmalloc(max_striplength);
if(stripbuffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s",
max_striplength,
TIFFFileName(input));
_TIFFfree(buffer);
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
for(i=0;i<stripcount;i++){
striplength=TIFFReadRawStrip(input, i, (tdata_t) stripbuffer, -1);
if(!t2p_process_jpeg_strip(
stripbuffer,
&striplength,
buffer,
&bufferoffset,
i,
t2p->tiff_length)){
TIFFError(TIFF2PDF_MODULE,
"Can't process JPEG data in input file %s",
TIFFFileName(input));
_TIFFfree(samplebuffer);
_TIFFfree(buffer);
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
}
buffer[bufferoffset++]=0xff;
buffer[bufferoffset++]=0xd9;
t2pWriteFile(output, (tdata_t) buffer, bufferoffset);
_TIFFfree(stripbuffer);
_TIFFfree(buffer);
return(bufferoffset);
}
#endif /* ifdef JPEG_SUPPORT */
(void)0;
}
if(t2p->pdf_sample==T2P_SAMPLE_NOTHING){
buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
memset(buffer, 0, t2p->tiff_datasize);
stripsize=TIFFStripSize(input);
stripcount=TIFFNumberOfStrips(input);
for(i=0;i<stripcount;i++){
read =
TIFFReadEncodedStrip(input,
i,
(tdata_t) &buffer[bufferoffset],
TIFFmin(stripsize, t2p->tiff_datasize - bufferoffset));
if(read==-1){
TIFFError(TIFF2PDF_MODULE,
"Error on decoding strip %u of %s",
i,
TIFFFileName(input));
_TIFFfree(buffer);
t2p->t2p_error=T2P_ERR_ERROR;
return(0);
}
bufferoffset+=read;
}
} else {
if(t2p->pdf_sample & T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){
sepstripsize=TIFFStripSize(input);
sepstripcount=TIFFNumberOfStrips(input);
stripsize=sepstripsize*t2p->tiff_samplesperpixel;
stripcount=sepstripcount/t2p->tiff_samplesperpixel;
buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
memset(buffer, 0, t2p->tiff_datasize);
samplebuffer = (unsigned char*) _TIFFmalloc(stripsize);
if(samplebuffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
_TIFFfree(buffer);
return(0);
}
for(i=0;i<stripcount;i++){
samplebufferoffset=0;
for(j=0;j<t2p->tiff_samplesperpixel;j++){
read =
TIFFReadEncodedStrip(input,
i + j*stripcount,
(tdata_t) &(samplebuffer[samplebufferoffset]),
TIFFmin(sepstripsize, stripsize - samplebufferoffset));
if(read==-1){
TIFFError(TIFF2PDF_MODULE,
"Error on decoding strip %u of %s",
i + j*stripcount,
TIFFFileName(input));
_TIFFfree(buffer);
t2p->t2p_error=T2P_ERR_ERROR;
return(0);
}
samplebufferoffset+=read;
}
t2p_sample_planar_separate_to_contig(
t2p,
&(buffer[bufferoffset]),
samplebuffer,
samplebufferoffset);
bufferoffset+=samplebufferoffset;
}
_TIFFfree(samplebuffer);
goto dataready;
}
buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
memset(buffer, 0, t2p->tiff_datasize);
stripsize=TIFFStripSize(input);
stripcount=TIFFNumberOfStrips(input);
for(i=0;i<stripcount;i++){
read =
TIFFReadEncodedStrip(input,
i,
(tdata_t) &buffer[bufferoffset],
TIFFmin(stripsize, t2p->tiff_datasize - bufferoffset));
if(read==-1){
TIFFError(TIFF2PDF_MODULE,
"Error on decoding strip %u of %s",
i,
TIFFFileName(input));
_TIFFfree(samplebuffer);
_TIFFfree(buffer);
t2p->t2p_error=T2P_ERR_ERROR;
return(0);
}
bufferoffset+=read;
}
if(t2p->pdf_sample & T2P_SAMPLE_REALIZE_PALETTE){
// FIXME: overflow?
samplebuffer=(unsigned char*)_TIFFrealloc(
(tdata_t) buffer,
t2p->tiff_datasize * t2p->tiff_samplesperpixel);
if(samplebuffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
_TIFFfree(buffer);
return(0);
} else {
buffer=samplebuffer;
t2p->tiff_datasize *= t2p->tiff_samplesperpixel;
}
t2p_sample_realize_palette(t2p, buffer);
}
if(t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB){
t2p->tiff_datasize=t2p_sample_rgba_to_rgb(
(tdata_t)buffer,
t2p->tiff_width*t2p->tiff_length);
}
if(t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB){
t2p->tiff_datasize=t2p_sample_rgbaa_to_rgb(
(tdata_t)buffer,
t2p->tiff_width*t2p->tiff_length);
}
if(t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB){
samplebuffer=(unsigned char*)_TIFFrealloc(
(tdata_t)buffer,
t2p->tiff_width*t2p->tiff_length*4);
if(samplebuffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
_TIFFfree(buffer);
return(0);
} else {
buffer=samplebuffer;
}
if(!TIFFReadRGBAImageOriented(
input,
t2p->tiff_width,
t2p->tiff_length,
(uint32*)buffer,
ORIENTATION_TOPLEFT,
0)){
TIFFError(TIFF2PDF_MODULE,
"Can't use TIFFReadRGBAImageOriented to extract RGB image from %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
t2p->tiff_datasize=t2p_sample_abgr_to_rgb(
(tdata_t) buffer,
t2p->tiff_width*t2p->tiff_length);
}
if(t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED){
t2p->tiff_datasize=t2p_sample_lab_signed_to_unsigned(
(tdata_t)buffer,
t2p->tiff_width*t2p->tiff_length);
}
}
dataready:
t2p_disable(output);
TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric);
TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample);
TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel);
TIFFSetField(output, TIFFTAG_IMAGEWIDTH, t2p->tiff_width);
TIFFSetField(output, TIFFTAG_IMAGELENGTH, t2p->tiff_length);
TIFFSetField(output, TIFFTAG_ROWSPERSTRIP, t2p->tiff_length);
TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB);
switch(t2p->pdf_compression){
case T2P_COMPRESS_NONE:
TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
break;
#ifdef CCITT_SUPPORT
case T2P_COMPRESS_G4:
TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4);
break;
#endif /* ifdef CCITT_SUPPORT */
#ifdef JPEG_SUPPORT
case T2P_COMPRESS_JPEG:
if(t2p->tiff_photometric==PHOTOMETRIC_YCBCR) {
uint16 hor = 0, ver = 0;
if (TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &hor, &ver) !=0 ) {
if(hor != 0 && ver != 0){
TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, hor, ver);
}
}
if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){
TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp);
}
}
if(TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG)==0){
TIFFError(TIFF2PDF_MODULE,
"Unable to use JPEG compression for input %s and output %s",
TIFFFileName(input),
TIFFFileName(output));
_TIFFfree(buffer);
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0);
if(t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB)){
TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR){
TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
} else {
TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW);
}
}
if(t2p->pdf_colorspace & T2P_CS_GRAY){
(void)0;
}
if(t2p->pdf_colorspace & T2P_CS_CMYK){
(void)0;
}
if(t2p->pdf_defaultcompressionquality != 0){
TIFFSetField(output,
TIFFTAG_JPEGQUALITY,
t2p->pdf_defaultcompressionquality);
}
break;
#endif /* ifdef JPEG_SUPPORT */
#ifdef ZIP_SUPPORT
case T2P_COMPRESS_ZIP:
TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE);
if(t2p->pdf_defaultcompressionquality%100 != 0){
TIFFSetField(output,
TIFFTAG_PREDICTOR,
t2p->pdf_defaultcompressionquality % 100);
}
if(t2p->pdf_defaultcompressionquality/100 != 0){
TIFFSetField(output,
TIFFTAG_ZIPQUALITY,
(t2p->pdf_defaultcompressionquality / 100));
}
break;
#endif /* ifdef ZIP_SUPPORT */
default:
break;
}
t2p_enable(output);
t2p->outputwritten = 0;
#ifdef JPEG_SUPPORT
if(t2p->pdf_compression == T2P_COMPRESS_JPEG
&& t2p->tiff_photometric == PHOTOMETRIC_YCBCR){
bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t)0,
buffer,
stripsize * stripcount);
} else
#endif /* ifdef JPEG_SUPPORT */
{
bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t)0,
buffer,
t2p->tiff_datasize);
}
if (buffer != NULL) {
_TIFFfree(buffer);
buffer=NULL;
}
if (bufferoffset == (tsize_t)-1) {
TIFFError(TIFF2PDF_MODULE,
"Error writing encoded strip to output PDF %s",
TIFFFileName(output));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
written = t2p->outputwritten;
return(written);
}
/*
* This function reads the raster image data from the input TIFF for an image
* tile and writes the data to the output PDF XObject image dictionary stream
* for the tile. It returns the amount written or zero on error.
*/
tsize_t t2p_readwrite_pdf_image_tile(T2P* t2p, TIFF* input, TIFF* output, ttile_t tile){
uint16 edge=0;
tsize_t written=0;
unsigned char* buffer=NULL;
tsize_t bufferoffset=0;
unsigned char* samplebuffer=NULL;
tsize_t samplebufferoffset=0;
tsize_t read=0;
uint16 i=0;
ttile_t tilecount=0;
/* tsize_t tilesize=0; */
ttile_t septilecount=0;
tsize_t septilesize=0;
#ifdef JPEG_SUPPORT
unsigned char* jpt;
float* xfloatp;
uint32 xuint32=0;
#endif
/* Fail if prior error (in particular, can't trust tiff_datasize) */
if (t2p->t2p_error != T2P_ERR_OK)
return(0);
edge |= t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile);
edge |= t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile);
if( (t2p->pdf_transcode == T2P_TRANSCODE_RAW) && ((edge == 0)
#if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT)
|| (t2p->pdf_compression == T2P_COMPRESS_JPEG)
#endif
)
){
#ifdef CCITT_SUPPORT
if(t2p->pdf_compression == T2P_COMPRESS_G4){
buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
TIFFReadRawTile(input, tile, (tdata_t) buffer, t2p->tiff_datasize);
if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){
TIFFReverseBits(buffer, t2p->tiff_datasize);
}
t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize);
_TIFFfree(buffer);
return(t2p->tiff_datasize);
}
#endif
#ifdef ZIP_SUPPORT
if(t2p->pdf_compression == T2P_COMPRESS_ZIP){
buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
TIFFReadRawTile(input, tile, (tdata_t) buffer, t2p->tiff_datasize);
if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){
TIFFReverseBits(buffer, t2p->tiff_datasize);
}
t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize);
_TIFFfree(buffer);
return(t2p->tiff_datasize);
}
#endif
#ifdef OJPEG_SUPPORT
if(t2p->tiff_compression == COMPRESSION_OJPEG){
if(! t2p->pdf_ojpegdata){
TIFFError(TIFF2PDF_MODULE,
"No support for OJPEG image %s with "
"bad tables",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
buffer=(unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory "
"for t2p_readwrite_pdf_image, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
_TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength);
if(edge!=0){
if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile)){
buffer[7]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength >> 8) & 0xff;
buffer[8]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength ) & 0xff;
}
if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile)){
buffer[9]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth >> 8) & 0xff;
buffer[10]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth ) & 0xff;
}
}
bufferoffset=t2p->pdf_ojpegdatalength;
bufferoffset+=TIFFReadRawTile(input,
tile,
(tdata_t) &(((unsigned char*)buffer)[bufferoffset]),
-1);
((unsigned char*)buffer)[bufferoffset++]=0xff;
((unsigned char*)buffer)[bufferoffset++]=0xd9;
t2pWriteFile(output, (tdata_t) buffer, bufferoffset);
_TIFFfree(buffer);
return(bufferoffset);
}
#endif
#ifdef JPEG_SUPPORT
if(t2p->tiff_compression == COMPRESSION_JPEG){
unsigned char table_end[2];
uint32 count = 0;
buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate " TIFF_SIZE_FORMAT " bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
(TIFF_SIZE_T) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0) {
if (count > 0) {
_TIFFmemcpy(buffer, jpt, count);
bufferoffset += count - 2;
table_end[0] = buffer[bufferoffset-2];
table_end[1] = buffer[bufferoffset-1];
}
if (count > 0) {
xuint32 = bufferoffset;
bufferoffset += TIFFReadRawTile(
input,
tile,
(tdata_t) &(((unsigned char*)buffer)[bufferoffset-2]),
-1);
buffer[xuint32-2]=table_end[0];
buffer[xuint32-1]=table_end[1];
} else {
bufferoffset += TIFFReadRawTile(
input,
tile,
(tdata_t) &(((unsigned char*)buffer)[bufferoffset]),
-1);
}
}
t2pWriteFile(output, (tdata_t) buffer, bufferoffset);
_TIFFfree(buffer);
return(bufferoffset);
}
#endif
(void)0;
}
if(t2p->pdf_sample==T2P_SAMPLE_NOTHING){
buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory for "
"t2p_readwrite_pdf_image_tile, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
read = TIFFReadEncodedTile(
input,
tile,
(tdata_t) &buffer[bufferoffset],
t2p->tiff_datasize);
if(read==-1){
TIFFError(TIFF2PDF_MODULE,
"Error on decoding tile %u of %s",
tile,
TIFFFileName(input));
_TIFFfree(buffer);
t2p->t2p_error=T2P_ERR_ERROR;
return(0);
}
} else {
if(t2p->pdf_sample == T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){
septilesize=TIFFTileSize(input);
septilecount=TIFFNumberOfTiles(input);
/* tilesize=septilesize*t2p->tiff_samplesperpixel; */
tilecount=septilecount/t2p->tiff_samplesperpixel;
buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
samplebuffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(samplebuffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
samplebufferoffset=0;
for(i=0;i<t2p->tiff_samplesperpixel;i++){
read =
TIFFReadEncodedTile(input,
tile + i*tilecount,
(tdata_t) &(samplebuffer[samplebufferoffset]),
septilesize);
if(read==-1){
TIFFError(TIFF2PDF_MODULE,
"Error on decoding tile %u of %s",
tile + i*tilecount,
TIFFFileName(input));
_TIFFfree(samplebuffer);
_TIFFfree(buffer);
t2p->t2p_error=T2P_ERR_ERROR;
return(0);
}
samplebufferoffset+=read;
}
t2p_sample_planar_separate_to_contig(
t2p,
&(buffer[bufferoffset]),
samplebuffer,
samplebufferoffset);
bufferoffset+=samplebufferoffset;
_TIFFfree(samplebuffer);
}
if(buffer==NULL){
buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
read = TIFFReadEncodedTile(
input,
tile,
(tdata_t) &buffer[bufferoffset],
t2p->tiff_datasize);
if(read==-1){
TIFFError(TIFF2PDF_MODULE,
"Error on decoding tile %u of %s",
tile,
TIFFFileName(input));
_TIFFfree(buffer);
t2p->t2p_error=T2P_ERR_ERROR;
return(0);
}
}
if(t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB){
t2p->tiff_datasize=t2p_sample_rgba_to_rgb(
(tdata_t)buffer,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth
*t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
}
if(t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB){
t2p->tiff_datasize=t2p_sample_rgbaa_to_rgb(
(tdata_t)buffer,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth
*t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
}
if(t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB){
TIFFError(TIFF2PDF_MODULE,
"No support for YCbCr to RGB in tile for %s",
TIFFFileName(input));
_TIFFfree(buffer);
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED){
t2p->tiff_datasize=t2p_sample_lab_signed_to_unsigned(
(tdata_t)buffer,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth
*t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
}
}
if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) != 0){
t2p_tile_collapse_left(
buffer,
TIFFTileRowSize(input),
t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth,
t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
}
t2p_disable(output);
TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric);
TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample);
TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel);
if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0){
TIFFSetField(
output,
TIFFTAG_IMAGEWIDTH,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth);
} else {
TIFFSetField(
output,
TIFFTAG_IMAGEWIDTH,
t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth);
}
if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0){
TIFFSetField(
output,
TIFFTAG_IMAGELENGTH,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
TIFFSetField(
output,
TIFFTAG_ROWSPERSTRIP,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
} else {
TIFFSetField(
output,
TIFFTAG_IMAGELENGTH,
t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength);
TIFFSetField(
output,
TIFFTAG_ROWSPERSTRIP,
t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength);
}
TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB);
switch(t2p->pdf_compression){
case T2P_COMPRESS_NONE:
TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
break;
#ifdef CCITT_SUPPORT
case T2P_COMPRESS_G4:
TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4);
break;
#endif
#ifdef JPEG_SUPPORT
case T2P_COMPRESS_JPEG:
if (t2p->tiff_photometric==PHOTOMETRIC_YCBCR) {
uint16 hor = 0, ver = 0;
if (TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &hor, &ver)!=0) {
if (hor != 0 && ver != 0) {
TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, hor, ver);
}
}
if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){
TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp);
}
}
TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG);
TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0); /* JPEGTABLESMODE_NONE */
if(t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB)){
TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR){
TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
} else {
TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW);
}
}
if(t2p->pdf_colorspace & T2P_CS_GRAY){
(void)0;
}
if(t2p->pdf_colorspace & T2P_CS_CMYK){
(void)0;
}
if(t2p->pdf_defaultcompressionquality != 0){
TIFFSetField(output,
TIFFTAG_JPEGQUALITY,
t2p->pdf_defaultcompressionquality);
}
break;
#endif
#ifdef ZIP_SUPPORT
case T2P_COMPRESS_ZIP:
TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE);
if(t2p->pdf_defaultcompressionquality%100 != 0){
TIFFSetField(output,
TIFFTAG_PREDICTOR,
t2p->pdf_defaultcompressionquality % 100);
}
if(t2p->pdf_defaultcompressionquality/100 != 0){
TIFFSetField(output,
TIFFTAG_ZIPQUALITY,
(t2p->pdf_defaultcompressionquality / 100));
}
break;
#endif
default:
break;
}
t2p_enable(output);
t2p->outputwritten = 0;
bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t) 0, buffer,
TIFFStripSize(output));
if (buffer != NULL) {
_TIFFfree(buffer);
buffer = NULL;
}
if (bufferoffset == -1) {
TIFFError(TIFF2PDF_MODULE,
"Error writing encoded tile to output PDF %s",
TIFFFileName(output));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
written = t2p->outputwritten;
return(written);
}
#ifdef OJPEG_SUPPORT
int t2p_process_ojpeg_tables(T2P* t2p, TIFF* input){
uint16 proc=0;
void* q;
uint32 q_length=0;
void* dc;
uint32 dc_length=0;
void* ac;
uint32 ac_length=0;
uint16* lp;
uint16* pt;
uint16 h_samp=1;
uint16 v_samp=1;
unsigned char* ojpegdata;
uint16 table_count;
uint32 offset_table;
uint32 offset_ms_l;
uint32 code_count;
uint32 i=0;
uint32 dest=0;
uint16 ri=0;
uint32 rows=0;
if(!TIFFGetField(input, TIFFTAG_JPEGPROC, &proc)){
TIFFError(TIFF2PDF_MODULE,
"Missing JPEGProc field in OJPEG image %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(proc!=JPEGPROC_BASELINE && proc!=JPEGPROC_LOSSLESS){
TIFFError(TIFF2PDF_MODULE,
"Bad JPEGProc field in OJPEG image %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(!TIFFGetField(input, TIFFTAG_JPEGQTABLES, &q_length, &q)){
TIFFError(TIFF2PDF_MODULE,
"Missing JPEGQTables field in OJPEG image %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(q_length < (64U * t2p->tiff_samplesperpixel)){
TIFFError(TIFF2PDF_MODULE,
"Bad JPEGQTables field in OJPEG image %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(!TIFFGetField(input, TIFFTAG_JPEGDCTABLES, &dc_length, &dc)){
TIFFError(TIFF2PDF_MODULE,
"Missing JPEGDCTables field in OJPEG image %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(proc==JPEGPROC_BASELINE){
if(!TIFFGetField(input, TIFFTAG_JPEGACTABLES, &ac_length, &ac)){
TIFFError(TIFF2PDF_MODULE,
"Missing JPEGACTables field in OJPEG image %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
} else {
if(!TIFFGetField(input, TIFFTAG_JPEGLOSSLESSPREDICTORS, &lp)){
TIFFError(TIFF2PDF_MODULE,
"Missing JPEGLosslessPredictors field in OJPEG image %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(!TIFFGetField(input, TIFFTAG_JPEGPOINTTRANSFORM, &pt)){
TIFFError(TIFF2PDF_MODULE,
"Missing JPEGPointTransform field in OJPEG image %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
}
if(!TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &h_samp, &v_samp)){
h_samp=1;
v_samp=1;
}
if(t2p->pdf_ojpegdata != NULL){
_TIFFfree(t2p->pdf_ojpegdata);
t2p->pdf_ojpegdata=NULL;
}
t2p->pdf_ojpegdata = _TIFFmalloc(2048);
if(t2p->pdf_ojpegdata == NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_process_ojpeg_tables, %s",
2048,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
_TIFFmemset(t2p->pdf_ojpegdata, 0x00, 2048);
t2p->pdf_ojpegdatalength = 0;
table_count=t2p->tiff_samplesperpixel;
if(proc==JPEGPROC_BASELINE){
if(table_count>2) table_count=2;
}
ojpegdata=(unsigned char*)t2p->pdf_ojpegdata;
ojpegdata[t2p->pdf_ojpegdatalength++]=0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=0xd8;
ojpegdata[t2p->pdf_ojpegdatalength++]=0xff;
if(proc==JPEGPROC_BASELINE){
ojpegdata[t2p->pdf_ojpegdatalength++]=0xc0;
} else {
ojpegdata[t2p->pdf_ojpegdatalength++]=0xc3;
}
ojpegdata[t2p->pdf_ojpegdatalength++]=0x00;
ojpegdata[t2p->pdf_ojpegdatalength++]=(8 + 3*t2p->tiff_samplesperpixel);
ojpegdata[t2p->pdf_ojpegdatalength++]=(t2p->tiff_bitspersample & 0xff);
if(TIFFIsTiled(input)){
ojpegdata[t2p->pdf_ojpegdatalength++]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength >> 8) & 0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength ) & 0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth >> 8) & 0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth ) & 0xff;
} else {
ojpegdata[t2p->pdf_ojpegdatalength++]=
(t2p->tiff_length >> 8) & 0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=
(t2p->tiff_length ) & 0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=
(t2p->tiff_width >> 8) & 0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=
(t2p->tiff_width ) & 0xff;
}
ojpegdata[t2p->pdf_ojpegdatalength++]=(t2p->tiff_samplesperpixel & 0xff);
for(i=0;i<t2p->tiff_samplesperpixel;i++){
ojpegdata[t2p->pdf_ojpegdatalength++]=i;
if(i==0){
ojpegdata[t2p->pdf_ojpegdatalength] |= h_samp<<4 & 0xf0;;
ojpegdata[t2p->pdf_ojpegdatalength++] |= v_samp & 0x0f;
} else {
ojpegdata[t2p->pdf_ojpegdatalength++]= 0x11;
}
ojpegdata[t2p->pdf_ojpegdatalength++]=i;
}
for(dest=0;dest<t2p->tiff_samplesperpixel;dest++){
ojpegdata[t2p->pdf_ojpegdatalength++]=0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=0xdb;
ojpegdata[t2p->pdf_ojpegdatalength++]=0x00;
ojpegdata[t2p->pdf_ojpegdatalength++]=0x43;
ojpegdata[t2p->pdf_ojpegdatalength++]=dest;
_TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength++]),
&(((unsigned char*)q)[64*dest]), 64);
t2p->pdf_ojpegdatalength+=64;
}
offset_table=0;
for(dest=0;dest<table_count;dest++){
ojpegdata[t2p->pdf_ojpegdatalength++]=0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=0xc4;
offset_ms_l=t2p->pdf_ojpegdatalength;
t2p->pdf_ojpegdatalength+=2;
ojpegdata[t2p->pdf_ojpegdatalength++]=dest & 0x0f;
_TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]),
&(((unsigned char*)dc)[offset_table]), 16);
code_count=0;
offset_table+=16;
for(i=0;i<16;i++){
code_count+=ojpegdata[t2p->pdf_ojpegdatalength++];
}
ojpegdata[offset_ms_l]=((19+code_count)>>8) & 0xff;
ojpegdata[offset_ms_l+1]=(19+code_count) & 0xff;
_TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]),
&(((unsigned char*)dc)[offset_table]), code_count);
offset_table+=code_count;
t2p->pdf_ojpegdatalength+=code_count;
}
if(proc==JPEGPROC_BASELINE){
offset_table=0;
for(dest=0;dest<table_count;dest++){
ojpegdata[t2p->pdf_ojpegdatalength++]=0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=0xc4;
offset_ms_l=t2p->pdf_ojpegdatalength;
t2p->pdf_ojpegdatalength+=2;
ojpegdata[t2p->pdf_ojpegdatalength] |= 0x10;
ojpegdata[t2p->pdf_ojpegdatalength++] |=dest & 0x0f;
_TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]),
&(((unsigned char*)ac)[offset_table]), 16);
code_count=0;
offset_table+=16;
for(i=0;i<16;i++){
code_count+=ojpegdata[t2p->pdf_ojpegdatalength++];
}
ojpegdata[offset_ms_l]=((19+code_count)>>8) & 0xff;
ojpegdata[offset_ms_l+1]=(19+code_count) & 0xff;
_TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]),
&(((unsigned char*)ac)[offset_table]), code_count);
offset_table+=code_count;
t2p->pdf_ojpegdatalength+=code_count;
}
}
if(TIFFNumberOfStrips(input)>1){
ojpegdata[t2p->pdf_ojpegdatalength++]=0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=0xdd;
ojpegdata[t2p->pdf_ojpegdatalength++]=0x00;
ojpegdata[t2p->pdf_ojpegdatalength++]=0x04;
h_samp*=8;
v_samp*=8;
ri=(t2p->tiff_width+h_samp-1) / h_samp;
TIFFGetField(input, TIFFTAG_ROWSPERSTRIP, &rows);
ri*=(rows+v_samp-1)/v_samp;
ojpegdata[t2p->pdf_ojpegdatalength++]= (ri>>8) & 0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]= ri & 0xff;
}
ojpegdata[t2p->pdf_ojpegdatalength++]=0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=0xda;
ojpegdata[t2p->pdf_ojpegdatalength++]=0x00;
ojpegdata[t2p->pdf_ojpegdatalength++]=(6 + 2*t2p->tiff_samplesperpixel);
ojpegdata[t2p->pdf_ojpegdatalength++]=t2p->tiff_samplesperpixel & 0xff;
for(i=0;i<t2p->tiff_samplesperpixel;i++){
ojpegdata[t2p->pdf_ojpegdatalength++]= i & 0xff;
if(proc==JPEGPROC_BASELINE){
ojpegdata[t2p->pdf_ojpegdatalength] |=
( ( (i>(table_count-1U)) ? (table_count-1U) : i) << 4U) & 0xf0;
ojpegdata[t2p->pdf_ojpegdatalength++] |=
( (i>(table_count-1U)) ? (table_count-1U) : i) & 0x0f;
} else {
ojpegdata[t2p->pdf_ojpegdatalength++] = (i << 4) & 0xf0;
}
}
if(proc==JPEGPROC_BASELINE){
t2p->pdf_ojpegdatalength++;
ojpegdata[t2p->pdf_ojpegdatalength++]=0x3f;
t2p->pdf_ojpegdatalength++;
} else {
ojpegdata[t2p->pdf_ojpegdatalength++]= (lp[0] & 0xff);
t2p->pdf_ojpegdatalength++;
ojpegdata[t2p->pdf_ojpegdatalength++]= (pt[0] & 0x0f);
}
return(1);
}
#endif
#ifdef JPEG_SUPPORT
int t2p_process_jpeg_strip(
unsigned char* strip,
tsize_t* striplength,
unsigned char* buffer,
tsize_t* bufferoffset,
tstrip_t no,
uint32 height){
tsize_t i=0;
while (i < *striplength) {
tsize_t datalen;
uint16 ri;
uint16 v_samp;
uint16 h_samp;
int j;
int ncomp;
/* marker header: one or more FFs */
if (strip[i] != 0xff)
return(0);
i++;
while (i < *striplength && strip[i] == 0xff)
i++;
if (i >= *striplength)
return(0);
/* SOI is the only pre-SOS marker without a length word */
if (strip[i] == 0xd8)
datalen = 0;
else {
if ((*striplength - i) <= 2)
return(0);
datalen = (strip[i+1] << 8) | strip[i+2];
if (datalen < 2 || datalen >= (*striplength - i))
return(0);
}
switch( strip[i] ){
case 0xd8: /* SOI - start of image */
_TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), 2);
*bufferoffset+=2;
break;
case 0xc0: /* SOF0 */
case 0xc1: /* SOF1 */
case 0xc3: /* SOF3 */
case 0xc9: /* SOF9 */
case 0xca: /* SOF10 */
if(no==0){
_TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2);
ncomp = buffer[*bufferoffset+9];
if (ncomp < 1 || ncomp > 4)
return(0);
v_samp=1;
h_samp=1;
for(j=0;j<ncomp;j++){
uint16 samp = buffer[*bufferoffset+11+(3*j)];
if( (samp>>4) > h_samp)
h_samp = (samp>>4);
if( (samp & 0x0f) > v_samp)
v_samp = (samp & 0x0f);
}
v_samp*=8;
h_samp*=8;
ri=((( ((uint16)(buffer[*bufferoffset+5])<<8) |
(uint16)(buffer[*bufferoffset+6]) )+v_samp-1)/
v_samp);
ri*=((( ((uint16)(buffer[*bufferoffset+7])<<8) |
(uint16)(buffer[*bufferoffset+8]) )+h_samp-1)/
h_samp);
buffer[*bufferoffset+5]=
(unsigned char) ((height>>8) & 0xff);
buffer[*bufferoffset+6]=
(unsigned char) (height & 0xff);
*bufferoffset+=datalen+2;
/* insert a DRI marker */
buffer[(*bufferoffset)++]=0xff;
buffer[(*bufferoffset)++]=0xdd;
buffer[(*bufferoffset)++]=0x00;
buffer[(*bufferoffset)++]=0x04;
buffer[(*bufferoffset)++]=(ri >> 8) & 0xff;
buffer[(*bufferoffset)++]= ri & 0xff;
}
break;
case 0xc4: /* DHT */
case 0xdb: /* DQT */
_TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2);
*bufferoffset+=datalen+2;
break;
case 0xda: /* SOS */
if(no==0){
_TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2);
*bufferoffset+=datalen+2;
} else {
buffer[(*bufferoffset)++]=0xff;
buffer[(*bufferoffset)++]=
(unsigned char)(0xd0 | ((no-1)%8));
}
i += datalen + 1;
/* copy remainder of strip */
_TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i]), *striplength - i);
*bufferoffset+= *striplength - i;
return(1);
default:
/* ignore any other marker */
break;
}
i += datalen + 1;
}
/* failed to find SOS marker */
return(0);
}
#endif
/*
This functions converts a tilewidth x tilelength buffer of samples into an edgetilewidth x
tilelength buffer of samples.
*/
void t2p_tile_collapse_left(
tdata_t buffer,
tsize_t scanwidth,
uint32 tilewidth,
uint32 edgetilewidth,
uint32 tilelength){
uint32 i;
tsize_t edgescanwidth=0;
edgescanwidth = (scanwidth * edgetilewidth + (tilewidth - 1))/ tilewidth;
for(i=0;i<tilelength;i++){
_TIFFmemcpy(
&(((char*)buffer)[edgescanwidth*i]),
&(((char*)buffer)[scanwidth*i]),
edgescanwidth);
}
return;
}
/*
* This function calls TIFFWriteDirectory on the output after blanking its
* output by replacing the read, write, and seek procedures with empty
* implementations, then it replaces the original implementations.
*/
void
t2p_write_advance_directory(T2P* t2p, TIFF* output)
{
t2p_disable(output);
if(!TIFFWriteDirectory(output)){
TIFFError(TIFF2PDF_MODULE,
"Error writing virtual directory to output PDF %s",
TIFFFileName(output));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
t2p_enable(output);
return;
}
tsize_t t2p_sample_planar_separate_to_contig(
T2P* t2p,
unsigned char* buffer,
unsigned char* samplebuffer,
tsize_t samplebuffersize){
tsize_t stride=0;
tsize_t i=0;
tsize_t j=0;
stride=samplebuffersize/t2p->tiff_samplesperpixel;
for(i=0;i<stride;i++){
for(j=0;j<t2p->tiff_samplesperpixel;j++){
buffer[i*t2p->tiff_samplesperpixel + j] = samplebuffer[i + j*stride];
}
}
return(samplebuffersize);
}
tsize_t t2p_sample_realize_palette(T2P* t2p, unsigned char* buffer){
uint32 sample_count=0;
uint16 component_count=0;
uint32 palette_offset=0;
uint32 sample_offset=0;
uint32 i=0;
uint32 j=0;
sample_count=t2p->tiff_width*t2p->tiff_length;
component_count=t2p->tiff_samplesperpixel;
for(i=sample_count;i>0;i--){
palette_offset=buffer[i-1] * component_count;
sample_offset= (i-1) * component_count;
for(j=0;j<component_count;j++){
buffer[sample_offset+j]=t2p->pdf_palette[palette_offset+j];
}
}
return(0);
}
/*
This functions converts in place a buffer of ABGR interleaved data
into RGB interleaved data, discarding A.
*/
tsize_t t2p_sample_abgr_to_rgb(tdata_t data, uint32 samplecount)
{
uint32 i=0;
uint32 sample=0;
for(i=0;i<samplecount;i++){
sample=((uint32*)data)[i];
((char*)data)[i*3]= (char) (sample & 0xff);
((char*)data)[i*3+1]= (char) ((sample>>8) & 0xff);
((char*)data)[i*3+2]= (char) ((sample>>16) & 0xff);
}
return(i*3);
}
/*
* This functions converts in place a buffer of RGBA interleaved data
* into RGB interleaved data, discarding A.
*/
tsize_t
t2p_sample_rgbaa_to_rgb(tdata_t data, uint32 samplecount)
{
uint32 i;
for(i = 0; i < samplecount; i++)
memcpy((uint8*)data + i * 3, (uint8*)data + i * 4, 3);
return(i * 3);
}
/*
* This functions converts in place a buffer of RGBA interleaved data
* into RGB interleaved data, adding 255-A to each component sample.
*/
tsize_t
t2p_sample_rgba_to_rgb(tdata_t data, uint32 samplecount)
{
uint32 i = 0;
uint32 sample = 0;
uint8 alpha = 0;
for (i = 0; i < samplecount; i++) {
sample=((uint32*)data)[i];
alpha=(uint8)((255 - ((sample >> 24) & 0xff)));
((uint8 *)data)[i * 3] = (uint8) ((sample >> 16) & 0xff) + alpha;
((uint8 *)data)[i * 3 + 1] = (uint8) ((sample >> 8) & 0xff) + alpha;
((uint8 *)data)[i * 3 + 2] = (uint8) (sample & 0xff) + alpha;
}
return (i * 3);
}
/*
This function converts the a and b samples of Lab data from signed
to unsigned.
*/
tsize_t t2p_sample_lab_signed_to_unsigned(tdata_t buffer, uint32 samplecount){
uint32 i=0;
for(i=0;i<samplecount;i++){
if( (((unsigned char*)buffer)[(i*3)+1] & 0x80) !=0){
((unsigned char*)buffer)[(i*3)+1] =
(unsigned char)(0x80 + ((char*)buffer)[(i*3)+1]);
} else {
((unsigned char*)buffer)[(i*3)+1] |= 0x80;
}
if( (((unsigned char*)buffer)[(i*3)+2] & 0x80) !=0){
((unsigned char*)buffer)[(i*3)+2] =
(unsigned char)(0x80 + ((char*)buffer)[(i*3)+2]);
} else {
((unsigned char*)buffer)[(i*3)+2] |= 0x80;
}
}
return(samplecount*3);
}
/*
This function writes the PDF header to output.
*/
tsize_t t2p_write_pdf_header(T2P* t2p, TIFF* output){
tsize_t written=0;
char buffer[16];
int buflen=0;
buflen = snprintf(buffer, sizeof(buffer), "%%PDF-%u.%u ",
t2p->pdf_majorversion&0xff,
t2p->pdf_minorversion&0xff);
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t)"\n%\342\343\317\323\n", 7);
return(written);
}
/*
This function writes the beginning of a PDF object to output.
*/
tsize_t t2p_write_pdf_obj_start(uint32 number, TIFF* output){
tsize_t written=0;
char buffer[32];
int buflen=0;
buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)number);
check_snprintf_ret((T2P*)NULL, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen );
written += t2pWriteFile(output, (tdata_t) " 0 obj\n", 7);
return(written);
}
/*
This function writes the end of a PDF object to output.
*/
tsize_t t2p_write_pdf_obj_end(TIFF* output){
tsize_t written=0;
written += t2pWriteFile(output, (tdata_t) "endobj\n", 7);
return(written);
}
/*
This function writes a PDF name object to output.
*/
tsize_t t2p_write_pdf_name(unsigned char* name, TIFF* output){
tsize_t written=0;
uint32 i=0;
char buffer[64];
uint16 nextchar=0;
size_t namelen=0;
namelen = strlen((char *)name);
if (namelen>126) {
namelen=126;
}
written += t2pWriteFile(output, (tdata_t) "/", 1);
for (i=0;i<namelen;i++){
if ( ((unsigned char)name[i]) < 0x21){
snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
buffer[sizeof(buffer) - 1] = '\0';
written += t2pWriteFile(output, (tdata_t) buffer, 3);
nextchar=1;
}
if ( ((unsigned char)name[i]) > 0x7E){
snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
buffer[sizeof(buffer) - 1] = '\0';
written += t2pWriteFile(output, (tdata_t) buffer, 3);
nextchar=1;
}
if (nextchar==0){
switch (name[i]){
case 0x23:
snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
buffer[sizeof(buffer) - 1] = '\0';
written += t2pWriteFile(output, (tdata_t) buffer, 3);
break;
case 0x25:
snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
buffer[sizeof(buffer) - 1] = '\0';
written += t2pWriteFile(output, (tdata_t) buffer, 3);
break;
case 0x28:
snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
buffer[sizeof(buffer) - 1] = '\0';
written += t2pWriteFile(output, (tdata_t) buffer, 3);
break;
case 0x29:
snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
buffer[sizeof(buffer) - 1] = '\0';
written += t2pWriteFile(output, (tdata_t) buffer, 3);
break;
case 0x2F:
snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
buffer[sizeof(buffer) - 1] = '\0';
written += t2pWriteFile(output, (tdata_t) buffer, 3);
break;
case 0x3C:
snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
buffer[sizeof(buffer) - 1] = '\0';
written += t2pWriteFile(output, (tdata_t) buffer, 3);
break;
case 0x3E:
snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
buffer[sizeof(buffer) - 1] = '\0';
written += t2pWriteFile(output, (tdata_t) buffer, 3);
break;
case 0x5B:
snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
buffer[sizeof(buffer) - 1] = '\0';
written += t2pWriteFile(output, (tdata_t) buffer, 3);
break;
case 0x5D:
snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
buffer[sizeof(buffer) - 1] = '\0';
written += t2pWriteFile(output, (tdata_t) buffer, 3);
break;
case 0x7B:
snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
buffer[sizeof(buffer) - 1] = '\0';
written += t2pWriteFile(output, (tdata_t) buffer, 3);
break;
case 0x7D:
snprintf(buffer, sizeof(buffer), "#%.2X", name[i]);
buffer[sizeof(buffer) - 1] = '\0';
written += t2pWriteFile(output, (tdata_t) buffer, 3);
break;
default:
written += t2pWriteFile(output, (tdata_t) &name[i], 1);
}
}
nextchar=0;
}
written += t2pWriteFile(output, (tdata_t) " ", 1);
return(written);
}
/*
* This function writes a PDF string object to output.
*/
tsize_t t2p_write_pdf_string(char* pdfstr, TIFF* output)
{
tsize_t written = 0;
uint32 i = 0;
char buffer[64];
size_t len = 0;
len = strlen(pdfstr);
written += t2pWriteFile(output, (tdata_t) "(", 1);
for (i=0; i<len; i++) {
if((pdfstr[i]&0x80) || (pdfstr[i]==127) || (pdfstr[i]<32)){
snprintf(buffer, sizeof(buffer), "\\%.3o", ((unsigned char)pdfstr[i]));
written += t2pWriteFile(output, (tdata_t)buffer, 4);
} else {
switch (pdfstr[i]){
case 0x08:
written += t2pWriteFile(output, (tdata_t) "\\b", 2);
break;
case 0x09:
written += t2pWriteFile(output, (tdata_t) "\\t", 2);
break;
case 0x0A:
written += t2pWriteFile(output, (tdata_t) "\\n", 2);
break;
case 0x0C:
written += t2pWriteFile(output, (tdata_t) "\\f", 2);
break;
case 0x0D:
written += t2pWriteFile(output, (tdata_t) "\\r", 2);
break;
case 0x28:
written += t2pWriteFile(output, (tdata_t) "\\(", 2);
break;
case 0x29:
written += t2pWriteFile(output, (tdata_t) "\\)", 2);
break;
case 0x5C:
written += t2pWriteFile(output, (tdata_t) "\\\\", 2);
break;
default:
written += t2pWriteFile(output, (tdata_t) &pdfstr[i], 1);
}
}
}
written += t2pWriteFile(output, (tdata_t) ") ", 1);
return(written);
}
/*
This function writes a buffer of data to output.
*/
tsize_t t2p_write_pdf_stream(tdata_t buffer, tsize_t len, TIFF* output){
tsize_t written=0;
written += t2pWriteFile(output, (tdata_t) buffer, len);
return(written);
}
/*
This functions writes the beginning of a PDF stream to output.
*/
tsize_t t2p_write_pdf_stream_start(TIFF* output){
tsize_t written=0;
written += t2pWriteFile(output, (tdata_t) "stream\n", 7);
return(written);
}
/*
This function writes the end of a PDF stream to output.
*/
tsize_t t2p_write_pdf_stream_end(TIFF* output){
tsize_t written=0;
written += t2pWriteFile(output, (tdata_t) "\nendstream\n", 11);
return(written);
}
/*
This function writes a stream dictionary for a PDF stream to output.
*/
tsize_t t2p_write_pdf_stream_dict(tsize_t len, uint32 number, TIFF* output){
tsize_t written=0;
char buffer[32];
int buflen=0;
written += t2pWriteFile(output, (tdata_t) "/Length ", 8);
if(len!=0){
written += t2p_write_pdf_stream_length(len, output);
} else {
buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)number);
check_snprintf_ret((T2P*)NULL, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6);
}
return(written);
}
/*
This functions writes the beginning of a PDF stream dictionary to output.
*/
tsize_t t2p_write_pdf_stream_dict_start(TIFF* output){
tsize_t written=0;
written += t2pWriteFile(output, (tdata_t) "<< \n", 4);
return(written);
}
/*
This function writes the end of a PDF stream dictionary to output.
*/
tsize_t t2p_write_pdf_stream_dict_end(TIFF* output){
tsize_t written=0;
written += t2pWriteFile(output, (tdata_t) " >>\n", 4);
return(written);
}
/*
This function writes a number to output.
*/
tsize_t t2p_write_pdf_stream_length(tsize_t len, TIFF* output){
tsize_t written=0;
char buffer[32];
int buflen=0;
buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)len);
check_snprintf_ret((T2P*)NULL, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) "\n", 1);
return(written);
}
/*
* This function writes the PDF Catalog structure to output.
*/
tsize_t t2p_write_pdf_catalog(T2P* t2p, TIFF* output)
{
tsize_t written = 0;
char buffer[32];
int buflen = 0;
written += t2pWriteFile(output,
(tdata_t)"<< \n/Type /Catalog \n/Pages ",
27);
buflen = snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_pages);
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer,
TIFFmin((size_t)buflen, sizeof(buffer) - 1));
written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6);
if(t2p->pdf_fitwindow){
written += t2pWriteFile(output,
(tdata_t) "/ViewerPreferences <</FitWindow true>>\n",
39);
}
written += t2pWriteFile(output, (tdata_t)">>\n", 3);
return(written);
}
/*
This function writes the PDF Info structure to output.
*/
tsize_t t2p_write_pdf_info(T2P* t2p, TIFF* input, TIFF* output)
{
tsize_t written = 0;
char* info;
char buffer[512];
if(t2p->pdf_datetime[0] == '\0')
t2p_pdf_tifftime(t2p, input);
if (strlen(t2p->pdf_datetime) > 0) {
written += t2pWriteFile(output, (tdata_t) "<< \n/CreationDate ", 18);
written += t2p_write_pdf_string(t2p->pdf_datetime, output);
written += t2pWriteFile(output, (tdata_t) "\n/ModDate ", 10);
written += t2p_write_pdf_string(t2p->pdf_datetime, output);
}
written += t2pWriteFile(output, (tdata_t) "\n/Producer ", 11);
snprintf(buffer, sizeof(buffer), "libtiff / tiff2pdf - %d", TIFFLIB_VERSION);
written += t2p_write_pdf_string(buffer, output);
written += t2pWriteFile(output, (tdata_t) "\n", 1);
if (t2p->pdf_creator[0] != '\0') {
written += t2pWriteFile(output, (tdata_t) "/Creator ", 9);
written += t2p_write_pdf_string(t2p->pdf_creator, output);
written += t2pWriteFile(output, (tdata_t) "\n", 1);
} else {
if (TIFFGetField(input, TIFFTAG_SOFTWARE, &info) != 0 && info) {
if(strlen(info) >= sizeof(t2p->pdf_creator))
info[sizeof(t2p->pdf_creator) - 1] = '\0';
written += t2pWriteFile(output, (tdata_t) "/Creator ", 9);
written += t2p_write_pdf_string(info, output);
written += t2pWriteFile(output, (tdata_t) "\n", 1);
}
}
if (t2p->pdf_author[0] != '\0') {
written += t2pWriteFile(output, (tdata_t) "/Author ", 8);
written += t2p_write_pdf_string(t2p->pdf_author, output);
written += t2pWriteFile(output, (tdata_t) "\n", 1);
} else {
if ((TIFFGetField(input, TIFFTAG_ARTIST, &info) != 0
|| TIFFGetField(input, TIFFTAG_COPYRIGHT, &info) != 0)
&& info) {
if (strlen(info) >= sizeof(t2p->pdf_author))
info[sizeof(t2p->pdf_author) - 1] = '\0';
written += t2pWriteFile(output, (tdata_t) "/Author ", 8);
written += t2p_write_pdf_string(info, output);
written += t2pWriteFile(output, (tdata_t) "\n", 1);
}
}
if (t2p->pdf_title[0] != '\0') {
written += t2pWriteFile(output, (tdata_t) "/Title ", 7);
written += t2p_write_pdf_string(t2p->pdf_title, output);
written += t2pWriteFile(output, (tdata_t) "\n", 1);
} else {
if (TIFFGetField(input, TIFFTAG_DOCUMENTNAME, &info) != 0){
if(strlen(info) > 511) {
info[512] = '\0';
}
written += t2pWriteFile(output, (tdata_t) "/Title ", 7);
written += t2p_write_pdf_string(info, output);
written += t2pWriteFile(output, (tdata_t) "\n", 1);
}
}
if (t2p->pdf_subject[0] != '\0') {
written += t2pWriteFile(output, (tdata_t) "/Subject ", 9);
written += t2p_write_pdf_string(t2p->pdf_subject, output);
written += t2pWriteFile(output, (tdata_t) "\n", 1);
} else {
if (TIFFGetField(input, TIFFTAG_IMAGEDESCRIPTION, &info) != 0 && info) {
if (strlen(info) >= sizeof(t2p->pdf_subject))
info[sizeof(t2p->pdf_subject) - 1] = '\0';
written += t2pWriteFile(output, (tdata_t) "/Subject ", 9);
written += t2p_write_pdf_string(info, output);
written += t2pWriteFile(output, (tdata_t) "\n", 1);
}
}
if (t2p->pdf_keywords[0] != '\0') {
written += t2pWriteFile(output, (tdata_t) "/Keywords ", 10);
written += t2p_write_pdf_string(t2p->pdf_keywords, output);
written += t2pWriteFile(output, (tdata_t) "\n", 1);
}
written += t2pWriteFile(output, (tdata_t) ">> \n", 4);
return(written);
}
/*
* This function fills a string of a T2P struct with the current time as a PDF
* date string, it is called by t2p_pdf_tifftime.
*/
void t2p_pdf_currenttime(T2P* t2p)
{
struct tm* currenttime;
time_t timenow;
if (time(&timenow) == (time_t) -1) {
TIFFError(TIFF2PDF_MODULE,
"Can't get the current time: %s", strerror(errno));
timenow = (time_t) 0;
}
currenttime = localtime(&timenow);
snprintf(t2p->pdf_datetime, sizeof(t2p->pdf_datetime),
"D:%.4d%.2d%.2d%.2d%.2d%.2d",
(currenttime->tm_year + 1900) % 65536,
(currenttime->tm_mon + 1) % 256,
(currenttime->tm_mday) % 256,
(currenttime->tm_hour) % 256,
(currenttime->tm_min) % 256,
(currenttime->tm_sec) % 256);
return;
}
/*
* This function fills a string of a T2P struct with the date and time of a
* TIFF file if it exists or the current time as a PDF date string.
*/
void t2p_pdf_tifftime(T2P* t2p, TIFF* input)
{
char* datetime;
if (TIFFGetField(input, TIFFTAG_DATETIME, &datetime) != 0
&& (strlen(datetime) >= 19) ){
t2p->pdf_datetime[0]='D';
t2p->pdf_datetime[1]=':';
t2p->pdf_datetime[2]=datetime[0];
t2p->pdf_datetime[3]=datetime[1];
t2p->pdf_datetime[4]=datetime[2];
t2p->pdf_datetime[5]=datetime[3];
t2p->pdf_datetime[6]=datetime[5];
t2p->pdf_datetime[7]=datetime[6];
t2p->pdf_datetime[8]=datetime[8];
t2p->pdf_datetime[9]=datetime[9];
t2p->pdf_datetime[10]=datetime[11];
t2p->pdf_datetime[11]=datetime[12];
t2p->pdf_datetime[12]=datetime[14];
t2p->pdf_datetime[13]=datetime[15];
t2p->pdf_datetime[14]=datetime[17];
t2p->pdf_datetime[15]=datetime[18];
t2p->pdf_datetime[16] = '\0';
} else {
t2p_pdf_currenttime(t2p);
}
return;
}
/*
* This function writes a PDF Pages Tree structure to output.
*/
tsize_t t2p_write_pdf_pages(T2P* t2p, TIFF* output)
{
tsize_t written=0;
tdir_t i=0;
char buffer[32];
int buflen=0;
int page=0;
written += t2pWriteFile(output,
(tdata_t) "<< \n/Type /Pages \n/Kids [ ", 26);
page = t2p->pdf_pages+1;
for (i=0;i<t2p->tiff_pagecount;i++){
buflen=snprintf(buffer, sizeof(buffer), "%d", page);
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) " 0 R ", 5);
if ( ((i+1)%8)==0 ) {
written += t2pWriteFile(output, (tdata_t) "\n", 1);
}
page +=3;
page += t2p->tiff_pages[i].page_extra;
if(t2p->tiff_pages[i].page_tilecount>0){
page += (2 * t2p->tiff_pages[i].page_tilecount);
} else {
page +=2;
}
}
written += t2pWriteFile(output, (tdata_t) "] \n/Count ", 10);
buflen=snprintf(buffer, sizeof(buffer), "%d", t2p->tiff_pagecount);
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) " \n>> \n", 6);
return(written);
}
/*
This function writes a PDF Page structure to output.
*/
tsize_t t2p_write_pdf_page(uint32 object, T2P* t2p, TIFF* output){
unsigned int i=0;
tsize_t written=0;
char buffer[256];
int buflen=0;
written += t2pWriteFile(output, (tdata_t) "<<\n/Type /Page \n/Parent ", 24);
buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_pages);
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6);
written += t2pWriteFile(output, (tdata_t) "/MediaBox [", 11);
buflen=snprintf(buffer, sizeof(buffer), "%.4f",t2p->pdf_mediabox.x1);
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) " ", 1);
buflen=snprintf(buffer, sizeof(buffer), "%.4f",t2p->pdf_mediabox.y1);
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) " ", 1);
buflen=snprintf(buffer, sizeof(buffer), "%.4f",t2p->pdf_mediabox.x2);
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) " ", 1);
buflen=snprintf(buffer, sizeof(buffer), "%.4f",t2p->pdf_mediabox.y2);
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) "] \n", 3);
written += t2pWriteFile(output, (tdata_t) "/Contents ", 10);
buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(object + 1));
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6);
written += t2pWriteFile(output, (tdata_t) "/Resources << \n", 15);
if( t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount != 0 ){
written += t2pWriteFile(output, (tdata_t) "/XObject <<\n", 12);
for(i=0;i<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount;i++){
written += t2pWriteFile(output, (tdata_t) "/Im", 3);
buflen = snprintf(buffer, sizeof(buffer), "%u", t2p->pdf_page+1);
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) "_", 1);
buflen = snprintf(buffer, sizeof(buffer), "%u", i+1);
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) " ", 1);
buflen = snprintf(buffer, sizeof(buffer), "%lu",
(unsigned long)(object+3+(2*i)+t2p->tiff_pages[t2p->pdf_page].page_extra));
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) " 0 R ", 5);
if(i%4==3){
written += t2pWriteFile(output, (tdata_t) "\n", 1);
}
}
written += t2pWriteFile(output, (tdata_t) ">>\n", 3);
} else {
written += t2pWriteFile(output, (tdata_t) "/XObject <<\n", 12);
written += t2pWriteFile(output, (tdata_t) "/Im", 3);
buflen = snprintf(buffer, sizeof(buffer), "%u", t2p->pdf_page+1);
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) " ", 1);
buflen = snprintf(buffer, sizeof(buffer), "%lu",
(unsigned long)(object+3+(2*i)+t2p->tiff_pages[t2p->pdf_page].page_extra));
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) " 0 R ", 5);
written += t2pWriteFile(output, (tdata_t) ">>\n", 3);
}
if(t2p->tiff_transferfunctioncount != 0) {
written += t2pWriteFile(output, (tdata_t) "/ExtGState <<", 13);
t2pWriteFile(output, (tdata_t) "/GS1 ", 5);
buflen = snprintf(buffer, sizeof(buffer), "%lu",
(unsigned long)(object + 3));
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) " 0 R ", 5);
written += t2pWriteFile(output, (tdata_t) ">> \n", 4);
}
written += t2pWriteFile(output, (tdata_t) "/ProcSet [ ", 11);
if(t2p->pdf_colorspace & T2P_CS_BILEVEL
|| t2p->pdf_colorspace & T2P_CS_GRAY
){
written += t2pWriteFile(output, (tdata_t) "/ImageB ", 8);
} else {
written += t2pWriteFile(output, (tdata_t) "/ImageC ", 8);
if(t2p->pdf_colorspace & T2P_CS_PALETTE){
written += t2pWriteFile(output, (tdata_t) "/ImageI ", 8);
}
}
written += t2pWriteFile(output, (tdata_t) "]\n>>\n>>\n", 8);
return(written);
}
/*
This function composes the page size and image and tile locations on a page.
*/
void t2p_compose_pdf_page(T2P* t2p){
uint32 i=0;
uint32 i2=0;
T2P_TILE* tiles=NULL;
T2P_BOX* boxp=NULL;
uint32 tilecountx=0;
uint32 tilecounty=0;
uint32 tilewidth=0;
uint32 tilelength=0;
int istiled=0;
float f=0;
float width_ratio=0;
float length_ratio=0;
t2p->pdf_xres = t2p->tiff_xres;
t2p->pdf_yres = t2p->tiff_yres;
if(t2p->pdf_overrideres) {
t2p->pdf_xres = t2p->pdf_defaultxres;
t2p->pdf_yres = t2p->pdf_defaultyres;
}
if(t2p->pdf_xres == 0.0)
t2p->pdf_xres = t2p->pdf_defaultxres;
if(t2p->pdf_yres == 0.0)
t2p->pdf_yres = t2p->pdf_defaultyres;
if (t2p->pdf_image_fillpage) {
width_ratio = t2p->pdf_defaultpagewidth/t2p->tiff_width;
length_ratio = t2p->pdf_defaultpagelength/t2p->tiff_length;
if (width_ratio < length_ratio ) {
t2p->pdf_imagewidth = t2p->pdf_defaultpagewidth;
t2p->pdf_imagelength = t2p->tiff_length * width_ratio;
} else {
t2p->pdf_imagewidth = t2p->tiff_width * length_ratio;
t2p->pdf_imagelength = t2p->pdf_defaultpagelength;
}
} else if (t2p->tiff_resunit != RESUNIT_CENTIMETER /* RESUNIT_NONE and */
&& t2p->tiff_resunit != RESUNIT_INCH) { /* other cases */
t2p->pdf_imagewidth = ((float)(t2p->tiff_width))/t2p->pdf_xres;
t2p->pdf_imagelength = ((float)(t2p->tiff_length))/t2p->pdf_yres;
} else {
t2p->pdf_imagewidth =
((float)(t2p->tiff_width))*PS_UNIT_SIZE/t2p->pdf_xres;
t2p->pdf_imagelength =
((float)(t2p->tiff_length))*PS_UNIT_SIZE/t2p->pdf_yres;
}
if(t2p->pdf_overridepagesize != 0) {
t2p->pdf_pagewidth = t2p->pdf_defaultpagewidth;
t2p->pdf_pagelength = t2p->pdf_defaultpagelength;
} else {
t2p->pdf_pagewidth = t2p->pdf_imagewidth;
t2p->pdf_pagelength = t2p->pdf_imagelength;
}
t2p->pdf_mediabox.x1=0.0;
t2p->pdf_mediabox.y1=0.0;
t2p->pdf_mediabox.x2=t2p->pdf_pagewidth;
t2p->pdf_mediabox.y2=t2p->pdf_pagelength;
t2p->pdf_imagebox.x1=0.0;
t2p->pdf_imagebox.y1=0.0;
t2p->pdf_imagebox.x2=t2p->pdf_imagewidth;
t2p->pdf_imagebox.y2=t2p->pdf_imagelength;
if(t2p->pdf_overridepagesize!=0){
t2p->pdf_imagebox.x1+=((t2p->pdf_pagewidth-t2p->pdf_imagewidth)/2.0F);
t2p->pdf_imagebox.y1+=((t2p->pdf_pagelength-t2p->pdf_imagelength)/2.0F);
t2p->pdf_imagebox.x2+=((t2p->pdf_pagewidth-t2p->pdf_imagewidth)/2.0F);
t2p->pdf_imagebox.y2+=((t2p->pdf_pagelength-t2p->pdf_imagelength)/2.0F);
}
if(t2p->tiff_orientation > 4){
f=t2p->pdf_mediabox.x2;
t2p->pdf_mediabox.x2=t2p->pdf_mediabox.y2;
t2p->pdf_mediabox.y2=f;
}
istiled=((t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount==0) ? 0 : 1;
if(istiled==0){
t2p_compose_pdf_page_orient(&(t2p->pdf_imagebox), t2p->tiff_orientation);
return;
} else {
tilewidth=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilewidth;
tilelength=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilelength;
if( tilewidth > INT_MAX ||
tilelength > INT_MAX ||
t2p->tiff_width > INT_MAX - tilewidth ||
t2p->tiff_length > INT_MAX - tilelength )
{
TIFFError(TIFF2PDF_MODULE, "Integer overflow");
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
tilecountx=(t2p->tiff_width +
tilewidth -1)/
tilewidth;
(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecountx=tilecountx;
tilecounty=(t2p->tiff_length +
tilelength -1)/
tilelength;
(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecounty=tilecounty;
(t2p->tiff_tiles[t2p->pdf_page]).tiles_edgetilewidth=
t2p->tiff_width % tilewidth;
(t2p->tiff_tiles[t2p->pdf_page]).tiles_edgetilelength=
t2p->tiff_length % tilelength;
tiles=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tiles;
for(i2=0;i2<tilecounty-1;i2++){
for(i=0;i<tilecountx-1;i++){
boxp=&(tiles[i2*tilecountx+i].tile_box);
boxp->x1 =
t2p->pdf_imagebox.x1
+ ((float)(t2p->pdf_imagewidth * i * tilewidth)
/ (float)t2p->tiff_width);
boxp->x2 =
t2p->pdf_imagebox.x1
+ ((float)(t2p->pdf_imagewidth * (i+1) * tilewidth)
/ (float)t2p->tiff_width);
boxp->y1 =
t2p->pdf_imagebox.y2
- ((float)(t2p->pdf_imagelength * (i2+1) * tilelength)
/ (float)t2p->tiff_length);
boxp->y2 =
t2p->pdf_imagebox.y2
- ((float)(t2p->pdf_imagelength * i2 * tilelength)
/ (float)t2p->tiff_length);
}
boxp=&(tiles[i2*tilecountx+i].tile_box);
boxp->x1 =
t2p->pdf_imagebox.x1
+ ((float)(t2p->pdf_imagewidth * i * tilewidth)
/ (float)t2p->tiff_width);
boxp->x2 = t2p->pdf_imagebox.x2;
boxp->y1 =
t2p->pdf_imagebox.y2
- ((float)(t2p->pdf_imagelength * (i2+1) * tilelength)
/ (float)t2p->tiff_length);
boxp->y2 =
t2p->pdf_imagebox.y2
- ((float)(t2p->pdf_imagelength * i2 * tilelength)
/ (float)t2p->tiff_length);
}
for(i=0;i<tilecountx-1;i++){
boxp=&(tiles[i2*tilecountx+i].tile_box);
boxp->x1 =
t2p->pdf_imagebox.x1
+ ((float)(t2p->pdf_imagewidth * i * tilewidth)
/ (float)t2p->tiff_width);
boxp->x2 =
t2p->pdf_imagebox.x1
+ ((float)(t2p->pdf_imagewidth * (i+1) * tilewidth)
/ (float)t2p->tiff_width);
boxp->y1 = t2p->pdf_imagebox.y1;
boxp->y2 =
t2p->pdf_imagebox.y2
- ((float)(t2p->pdf_imagelength * i2 * tilelength)
/ (float)t2p->tiff_length);
}
boxp=&(tiles[i2*tilecountx+i].tile_box);
boxp->x1 =
t2p->pdf_imagebox.x1
+ ((float)(t2p->pdf_imagewidth * i * tilewidth)
/ (float)t2p->tiff_width);
boxp->x2 = t2p->pdf_imagebox.x2;
boxp->y1 = t2p->pdf_imagebox.y1;
boxp->y2 =
t2p->pdf_imagebox.y2
- ((float)(t2p->pdf_imagelength * i2 * tilelength)
/ (float)t2p->tiff_length);
}
if(t2p->tiff_orientation==0 || t2p->tiff_orientation==1){
for(i=0;i<(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount;i++){
t2p_compose_pdf_page_orient( &(tiles[i].tile_box) , 0);
}
return;
}
for(i=0;i<(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount;i++){
boxp=&(tiles[i].tile_box);
boxp->x1 -= t2p->pdf_imagebox.x1;
boxp->x2 -= t2p->pdf_imagebox.x1;
boxp->y1 -= t2p->pdf_imagebox.y1;
boxp->y2 -= t2p->pdf_imagebox.y1;
if(t2p->tiff_orientation==2 || t2p->tiff_orientation==3){
boxp->x1 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x1;
boxp->x2 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x2;
}
if(t2p->tiff_orientation==3 || t2p->tiff_orientation==4){
boxp->y1 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y1;
boxp->y2 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y2;
}
if(t2p->tiff_orientation==8 || t2p->tiff_orientation==5){
boxp->y1 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y1;
boxp->y2 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y2;
}
if(t2p->tiff_orientation==5 || t2p->tiff_orientation==6){
boxp->x1 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x1;
boxp->x2 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x2;
}
if(t2p->tiff_orientation > 4){
f=boxp->x1;
boxp->x1 = boxp->y1;
boxp->y1 = f;
f=boxp->x2;
boxp->x2 = boxp->y2;
boxp->y2 = f;
t2p_compose_pdf_page_orient_flip(boxp, t2p->tiff_orientation);
} else {
t2p_compose_pdf_page_orient(boxp, t2p->tiff_orientation);
}
}
return;
}
void t2p_compose_pdf_page_orient(T2P_BOX* boxp, uint16 orientation){
float m1[9];
float f=0.0;
if( boxp->x1 > boxp->x2){
f=boxp->x1;
boxp->x1=boxp->x2;
boxp->x2 = f;
}
if( boxp->y1 > boxp->y2){
f=boxp->y1;
boxp->y1=boxp->y2;
boxp->y2 = f;
}
boxp->mat[0]=m1[0]=boxp->x2-boxp->x1;
boxp->mat[1]=m1[1]=0.0;
boxp->mat[2]=m1[2]=0.0;
boxp->mat[3]=m1[3]=0.0;
boxp->mat[4]=m1[4]=boxp->y2-boxp->y1;
boxp->mat[5]=m1[5]=0.0;
boxp->mat[6]=m1[6]=boxp->x1;
boxp->mat[7]=m1[7]=boxp->y1;
boxp->mat[8]=m1[8]=1.0;
switch(orientation){
case 0:
case 1:
break;
case 2:
boxp->mat[0]=0.0F-m1[0];
boxp->mat[6]+=m1[0];
break;
case 3:
boxp->mat[0]=0.0F-m1[0];
boxp->mat[4]=0.0F-m1[4];
boxp->mat[6]+=m1[0];
boxp->mat[7]+=m1[4];
break;
case 4:
boxp->mat[4]=0.0F-m1[4];
boxp->mat[7]+=m1[4];
break;
case 5:
boxp->mat[0]=0.0F;
boxp->mat[1]=0.0F-m1[0];
boxp->mat[3]=0.0F-m1[4];
boxp->mat[4]=0.0F;
boxp->mat[6]+=m1[4];
boxp->mat[7]+=m1[0];
break;
case 6:
boxp->mat[0]=0.0F;
boxp->mat[1]=0.0F-m1[0];
boxp->mat[3]=m1[4];
boxp->mat[4]=0.0F;
boxp->mat[7]+=m1[0];
break;
case 7:
boxp->mat[0]=0.0F;
boxp->mat[1]=m1[0];
boxp->mat[3]=m1[4];
boxp->mat[4]=0.0F;
break;
case 8:
boxp->mat[0]=0.0F;
boxp->mat[1]=m1[0];
boxp->mat[3]=0.0F-m1[4];
boxp->mat[4]=0.0F;
boxp->mat[6]+=m1[4];
break;
}
return;
}
void t2p_compose_pdf_page_orient_flip(T2P_BOX* boxp, uint16 orientation){
float m1[9];
float f=0.0;
if( boxp->x1 > boxp->x2){
f=boxp->x1;
boxp->x1=boxp->x2;
boxp->x2 = f;
}
if( boxp->y1 > boxp->y2){
f=boxp->y1;
boxp->y1=boxp->y2;
boxp->y2 = f;
}
boxp->mat[0]=m1[0]=boxp->x2-boxp->x1;
boxp->mat[1]=m1[1]=0.0F;
boxp->mat[2]=m1[2]=0.0F;
boxp->mat[3]=m1[3]=0.0F;
boxp->mat[4]=m1[4]=boxp->y2-boxp->y1;
boxp->mat[5]=m1[5]=0.0F;
boxp->mat[6]=m1[6]=boxp->x1;
boxp->mat[7]=m1[7]=boxp->y1;
boxp->mat[8]=m1[8]=1.0F;
switch(orientation){
case 5:
boxp->mat[0]=0.0F;
boxp->mat[1]=0.0F-m1[4];
boxp->mat[3]=0.0F-m1[0];
boxp->mat[4]=0.0F;
boxp->mat[6]+=m1[0];
boxp->mat[7]+=m1[4];
break;
case 6:
boxp->mat[0]=0.0F;
boxp->mat[1]=0.0F-m1[4];
boxp->mat[3]=m1[0];
boxp->mat[4]=0.0F;
boxp->mat[7]+=m1[4];
break;
case 7:
boxp->mat[0]=0.0F;
boxp->mat[1]=m1[4];
boxp->mat[3]=m1[0];
boxp->mat[4]=0.0F;
break;
case 8:
boxp->mat[0]=0.0F;
boxp->mat[1]=m1[4];
boxp->mat[3]=0.0F-m1[0];
boxp->mat[4]=0.0F;
boxp->mat[6]+=m1[0];
break;
}
return;
}
/*
This function writes a PDF Contents stream to output.
*/
tsize_t t2p_write_pdf_page_content_stream(T2P* t2p, TIFF* output){
tsize_t written=0;
ttile_t i=0;
char buffer[512];
int buflen=0;
T2P_BOX box;
if(t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount>0){
for(i=0;i<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount; i++){
box=t2p->tiff_tiles[t2p->pdf_page].tiles_tiles[i].tile_box;
buflen=snprintf(buffer, sizeof(buffer),
"q %s %.4f %.4f %.4f %.4f %.4f %.4f cm /Im%d_%ld Do Q\n",
t2p->tiff_transferfunctioncount?"/GS1 gs ":"",
box.mat[0],
box.mat[1],
box.mat[3],
box.mat[4],
box.mat[6],
box.mat[7],
t2p->pdf_page + 1,
(long)(i + 1));
check_snprintf_ret(t2p, buflen, buffer);
written += t2p_write_pdf_stream(buffer, buflen, output);
}
} else {
box=t2p->pdf_imagebox;
buflen=snprintf(buffer, sizeof(buffer),
"q %s %.4f %.4f %.4f %.4f %.4f %.4f cm /Im%d Do Q\n",
t2p->tiff_transferfunctioncount?"/GS1 gs ":"",
box.mat[0],
box.mat[1],
box.mat[3],
box.mat[4],
box.mat[6],
box.mat[7],
t2p->pdf_page+1);
check_snprintf_ret(t2p, buflen, buffer);
written += t2p_write_pdf_stream(buffer, buflen, output);
}
return(written);
}
/*
This function writes a PDF Image XObject stream dictionary to output.
*/
tsize_t t2p_write_pdf_xobject_stream_dict(ttile_t tile,
T2P* t2p,
TIFF* output){
tsize_t written=0;
char buffer[32];
int buflen=0;
written += t2p_write_pdf_stream_dict(0, t2p->pdf_xrefcount+1, output);
written += t2pWriteFile(output,
(tdata_t) "/Type /XObject \n/Subtype /Image \n/Name /Im",
42);
buflen=snprintf(buffer, sizeof(buffer), "%u", t2p->pdf_page+1);
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
if(tile != 0){
written += t2pWriteFile(output, (tdata_t) "_", 1);
buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)tile);
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
}
written += t2pWriteFile(output, (tdata_t) "\n/Width ", 8);
if(tile==0){
buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_width);
} else {
if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)!=0){
buflen=snprintf(buffer, sizeof(buffer), "%lu",
(unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth);
} else {
buflen=snprintf(buffer, sizeof(buffer), "%lu",
(unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth);
}
}
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) "\n/Height ", 9);
if(tile==0){
buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_length);
} else {
if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)!=0){
buflen=snprintf(buffer, sizeof(buffer), "%lu",
(unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength);
} else {
buflen=snprintf(buffer, sizeof(buffer), "%lu",
(unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
}
}
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) "\n/BitsPerComponent ", 19);
buflen=snprintf(buffer, sizeof(buffer), "%u", t2p->tiff_bitspersample);
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) "\n/ColorSpace ", 13);
written += t2p_write_pdf_xobject_cs(t2p, output);
if (t2p->pdf_image_interpolate)
written += t2pWriteFile(output,
(tdata_t) "\n/Interpolate true", 18);
if( (t2p->pdf_switchdecode != 0)
#ifdef CCITT_SUPPORT
&& ! (t2p->pdf_colorspace & T2P_CS_BILEVEL
&& t2p->pdf_compression == T2P_COMPRESS_G4)
#endif
){
written += t2p_write_pdf_xobject_decode(t2p, output);
}
written += t2p_write_pdf_xobject_stream_filter(tile, t2p, output);
return(written);
}
/*
* This function writes a PDF Image XObject Colorspace name to output.
*/
tsize_t t2p_write_pdf_xobject_cs(T2P* t2p, TIFF* output){
tsize_t written=0;
char buffer[128];
int buflen=0;
float X_W=1.0;
float Y_W=1.0;
float Z_W=1.0;
if( (t2p->pdf_colorspace & T2P_CS_ICCBASED) != 0){
written += t2p_write_pdf_xobject_icccs(t2p, output);
return(written);
}
if( (t2p->pdf_colorspace & T2P_CS_PALETTE) != 0){
written += t2pWriteFile(output, (tdata_t) "[ /Indexed ", 11);
t2p->pdf_colorspace ^= T2P_CS_PALETTE;
written += t2p_write_pdf_xobject_cs(t2p, output);
t2p->pdf_colorspace |= T2P_CS_PALETTE;
buflen=snprintf(buffer, sizeof(buffer), "%u", (0x0001 << t2p->tiff_bitspersample)-1 );
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) " ", 1);
buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_palettecs );
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) " 0 R ]\n", 7);
return(written);
}
if(t2p->pdf_colorspace & T2P_CS_BILEVEL){
written += t2pWriteFile(output, (tdata_t) "/DeviceGray \n", 13);
}
if(t2p->pdf_colorspace & T2P_CS_GRAY){
if(t2p->pdf_colorspace & T2P_CS_CALGRAY){
written += t2p_write_pdf_xobject_calcs(t2p, output);
} else {
written += t2pWriteFile(output, (tdata_t) "/DeviceGray \n", 13);
}
}
if(t2p->pdf_colorspace & T2P_CS_RGB){
if(t2p->pdf_colorspace & T2P_CS_CALRGB){
written += t2p_write_pdf_xobject_calcs(t2p, output);
} else {
written += t2pWriteFile(output, (tdata_t) "/DeviceRGB \n", 12);
}
}
if(t2p->pdf_colorspace & T2P_CS_CMYK){
written += t2pWriteFile(output, (tdata_t) "/DeviceCMYK \n", 13);
}
if(t2p->pdf_colorspace & T2P_CS_LAB){
written += t2pWriteFile(output, (tdata_t) "[/Lab << \n", 10);
written += t2pWriteFile(output, (tdata_t) "/WhitePoint ", 12);
X_W = t2p->tiff_whitechromaticities[0];
Y_W = t2p->tiff_whitechromaticities[1];
Z_W = 1.0F - (X_W + Y_W);
X_W /= Y_W;
Z_W /= Y_W;
Y_W = 1.0F;
buflen=snprintf(buffer, sizeof(buffer), "[%.4f %.4f %.4f] \n", X_W, Y_W, Z_W);
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) "/Range ", 7);
buflen=snprintf(buffer, sizeof(buffer), "[%d %d %d %d] \n",
t2p->pdf_labrange[0],
t2p->pdf_labrange[1],
t2p->pdf_labrange[2],
t2p->pdf_labrange[3]);
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) ">>] \n", 5);
}
return(written);
}
tsize_t t2p_write_pdf_transfer(T2P* t2p, TIFF* output){
tsize_t written=0;
char buffer[32];
int buflen=0;
written += t2pWriteFile(output, (tdata_t) "<< /Type /ExtGState \n/TR ", 25);
if(t2p->tiff_transferfunctioncount == 1){
buflen=snprintf(buffer, sizeof(buffer), "%lu",
(unsigned long)(t2p->pdf_xrefcount + 1));
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) " 0 R ", 5);
} else {
written += t2pWriteFile(output, (tdata_t) "[ ", 2);
buflen=snprintf(buffer, sizeof(buffer), "%lu",
(unsigned long)(t2p->pdf_xrefcount + 1));
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) " 0 R ", 5);
buflen=snprintf(buffer, sizeof(buffer), "%lu",
(unsigned long)(t2p->pdf_xrefcount + 2));
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) " 0 R ", 5);
buflen=snprintf(buffer, sizeof(buffer), "%lu",
(unsigned long)(t2p->pdf_xrefcount + 3));
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) " 0 R ", 5);
written += t2pWriteFile(output, (tdata_t) "/Identity ] ", 12);
}
written += t2pWriteFile(output, (tdata_t) " >> \n", 5);
return(written);
}
tsize_t t2p_write_pdf_transfer_dict(T2P* t2p, TIFF* output, uint16 i){
tsize_t written=0;
char buffer[32];
int buflen=0;
(void)i; /* XXX */
written += t2pWriteFile(output, (tdata_t) "/FunctionType 0 \n", 17);
written += t2pWriteFile(output, (tdata_t) "/Domain [0.0 1.0] \n", 19);
written += t2pWriteFile(output, (tdata_t) "/Range [0.0 1.0] \n", 18);
buflen=snprintf(buffer, sizeof(buffer), "/Size [%u] \n", (1<<t2p->tiff_bitspersample));
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) "/BitsPerSample 16 \n", 19);
written += t2p_write_pdf_stream_dict(((tsize_t)1)<<(t2p->tiff_bitspersample+1), 0, output);
return(written);
}
tsize_t t2p_write_pdf_transfer_stream(T2P* t2p, TIFF* output, uint16 i){
tsize_t written=0;
written += t2p_write_pdf_stream(
t2p->tiff_transferfunction[i],
(((tsize_t)1)<<(t2p->tiff_bitspersample+1)),
output);
return(written);
}
/*
This function writes a PDF Image XObject Colorspace array to output.
*/
tsize_t t2p_write_pdf_xobject_calcs(T2P* t2p, TIFF* output){
tsize_t written=0;
char buffer[256];
int buflen=0;
float X_W=0.0;
float Y_W=0.0;
float Z_W=0.0;
float X_R=0.0;
float Y_R=0.0;
float Z_R=0.0;
float X_G=0.0;
float Y_G=0.0;
float Z_G=0.0;
float X_B=0.0;
float Y_B=0.0;
float Z_B=0.0;
float x_w=0.0;
float y_w=0.0;
float z_w=0.0;
float x_r=0.0;
float y_r=0.0;
float x_g=0.0;
float y_g=0.0;
float x_b=0.0;
float y_b=0.0;
float R=1.0;
float G=1.0;
float B=1.0;
written += t2pWriteFile(output, (tdata_t) "[", 1);
if(t2p->pdf_colorspace & T2P_CS_CALGRAY){
written += t2pWriteFile(output, (tdata_t) "/CalGray ", 9);
X_W = t2p->tiff_whitechromaticities[0];
Y_W = t2p->tiff_whitechromaticities[1];
Z_W = 1.0F - (X_W + Y_W);
X_W /= Y_W;
Z_W /= Y_W;
Y_W = 1.0F;
}
if(t2p->pdf_colorspace & T2P_CS_CALRGB){
written += t2pWriteFile(output, (tdata_t) "/CalRGB ", 8);
x_w = t2p->tiff_whitechromaticities[0];
y_w = t2p->tiff_whitechromaticities[1];
x_r = t2p->tiff_primarychromaticities[0];
y_r = t2p->tiff_primarychromaticities[1];
x_g = t2p->tiff_primarychromaticities[2];
y_g = t2p->tiff_primarychromaticities[3];
x_b = t2p->tiff_primarychromaticities[4];
y_b = t2p->tiff_primarychromaticities[5];
z_w = y_w * ((x_g - x_b)*y_r - (x_r-x_b)*y_g + (x_r-x_g)*y_b);
Y_R = (y_r/R) * ((x_g-x_b)*y_w - (x_w-x_b)*y_g + (x_w-x_g)*y_b) / z_w;
X_R = Y_R * x_r / y_r;
Z_R = Y_R * (((1-x_r)/y_r)-1);
Y_G = ((0.0F-(y_g))/G) * ((x_r-x_b)*y_w - (x_w-x_b)*y_r + (x_w-x_r)*y_b) / z_w;
X_G = Y_G * x_g / y_g;
Z_G = Y_G * (((1-x_g)/y_g)-1);
Y_B = (y_b/B) * ((x_r-x_g)*y_w - (x_w-x_g)*y_r + (x_w-x_r)*y_g) / z_w;
X_B = Y_B * x_b / y_b;
Z_B = Y_B * (((1-x_b)/y_b)-1);
X_W = (X_R * R) + (X_G * G) + (X_B * B);
Y_W = (Y_R * R) + (Y_G * G) + (Y_B * B);
Z_W = (Z_R * R) + (Z_G * G) + (Z_B * B);
X_W /= Y_W;
Z_W /= Y_W;
Y_W = 1.0;
}
written += t2pWriteFile(output, (tdata_t) "<< \n", 4);
if(t2p->pdf_colorspace & T2P_CS_CALGRAY){
written += t2pWriteFile(output, (tdata_t) "/WhitePoint ", 12);
buflen=snprintf(buffer, sizeof(buffer), "[%.4f %.4f %.4f] \n", X_W, Y_W, Z_W);
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) "/Gamma 2.2 \n", 12);
}
if(t2p->pdf_colorspace & T2P_CS_CALRGB){
written += t2pWriteFile(output, (tdata_t) "/WhitePoint ", 12);
buflen=snprintf(buffer, sizeof(buffer), "[%.4f %.4f %.4f] \n", X_W, Y_W, Z_W);
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) "/Matrix ", 8);
buflen=snprintf(buffer, sizeof(buffer), "[%.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f] \n",
X_R, Y_R, Z_R,
X_G, Y_G, Z_G,
X_B, Y_B, Z_B);
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) "/Gamma [2.2 2.2 2.2] \n", 22);
}
written += t2pWriteFile(output, (tdata_t) ">>] \n", 5);
return(written);
}
/*
This function writes a PDF Image XObject Colorspace array to output.
*/
tsize_t t2p_write_pdf_xobject_icccs(T2P* t2p, TIFF* output){
tsize_t written=0;
char buffer[32];
int buflen=0;
written += t2pWriteFile(output, (tdata_t) "[/ICCBased ", 11);
buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_icccs);
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) " 0 R] \n", 7);
return(written);
}
tsize_t t2p_write_pdf_xobject_icccs_dict(T2P* t2p, TIFF* output){
tsize_t written=0;
char buffer[32];
int buflen=0;
written += t2pWriteFile(output, (tdata_t) "/N ", 3);
buflen=snprintf(buffer, sizeof(buffer), "%u \n", t2p->tiff_samplesperpixel);
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) "/Alternate ", 11);
t2p->pdf_colorspace ^= T2P_CS_ICCBASED;
written += t2p_write_pdf_xobject_cs(t2p, output);
t2p->pdf_colorspace |= T2P_CS_ICCBASED;
written += t2p_write_pdf_stream_dict(t2p->tiff_iccprofilelength, 0, output);
return(written);
}
tsize_t t2p_write_pdf_xobject_icccs_stream(T2P* t2p, TIFF* output){
tsize_t written=0;
written += t2p_write_pdf_stream(
(tdata_t) t2p->tiff_iccprofile,
(tsize_t) t2p->tiff_iccprofilelength,
output);
return(written);
}
/*
This function writes a palette stream for an indexed color space to output.
*/
tsize_t t2p_write_pdf_xobject_palettecs_stream(T2P* t2p, TIFF* output){
tsize_t written=0;
written += t2p_write_pdf_stream(
(tdata_t) t2p->pdf_palette,
(tsize_t) t2p->pdf_palettesize,
output);
return(written);
}
/*
This function writes a PDF Image XObject Decode array to output.
*/
tsize_t t2p_write_pdf_xobject_decode(T2P* t2p, TIFF* output){
tsize_t written=0;
int i=0;
written += t2pWriteFile(output, (tdata_t) "/Decode [ ", 10);
for (i=0;i<t2p->tiff_samplesperpixel;i++){
written += t2pWriteFile(output, (tdata_t) "1 0 ", 4);
}
written += t2pWriteFile(output, (tdata_t) "]\n", 2);
return(written);
}
/*
This function writes a PDF Image XObject stream filter name and parameters to
output.
*/
tsize_t t2p_write_pdf_xobject_stream_filter(ttile_t tile, T2P* t2p, TIFF* output){
tsize_t written=0;
char buffer[32];
int buflen=0;
if(t2p->pdf_compression==T2P_COMPRESS_NONE){
return(written);
}
written += t2pWriteFile(output, (tdata_t) "/Filter ", 8);
switch(t2p->pdf_compression){
#ifdef CCITT_SUPPORT
case T2P_COMPRESS_G4:
written += t2pWriteFile(output, (tdata_t) "/CCITTFaxDecode ", 16);
written += t2pWriteFile(output, (tdata_t) "/DecodeParms ", 13);
written += t2pWriteFile(output, (tdata_t) "<< /K -1 ", 9);
if(tile==0){
written += t2pWriteFile(output, (tdata_t) "/Columns ", 9);
buflen=snprintf(buffer, sizeof(buffer), "%lu",
(unsigned long)t2p->tiff_width);
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) " /Rows ", 7);
buflen=snprintf(buffer, sizeof(buffer), "%lu",
(unsigned long)t2p->tiff_length);
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
} else {
if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)==0){
written += t2pWriteFile(output, (tdata_t) "/Columns ", 9);
buflen=snprintf(buffer, sizeof(buffer), "%lu",
(unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth);
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
} else {
written += t2pWriteFile(output, (tdata_t) "/Columns ", 9);
buflen=snprintf(buffer, sizeof(buffer), "%lu",
(unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth);
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
}
if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)==0){
written += t2pWriteFile(output, (tdata_t) " /Rows ", 7);
buflen=snprintf(buffer, sizeof(buffer), "%lu",
(unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
} else {
written += t2pWriteFile(output, (tdata_t) " /Rows ", 7);
buflen=snprintf(buffer, sizeof(buffer), "%lu",
(unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength);
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
}
}
if(t2p->pdf_switchdecode == 0){
written += t2pWriteFile(output, (tdata_t) " /BlackIs1 true ", 16);
}
written += t2pWriteFile(output, (tdata_t) ">>\n", 3);
break;
#endif
#ifdef JPEG_SUPPORT
case T2P_COMPRESS_JPEG:
written += t2pWriteFile(output, (tdata_t) "/DCTDecode ", 11);
if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR) {
written += t2pWriteFile(output, (tdata_t) "/DecodeParms ", 13);
written += t2pWriteFile(output, (tdata_t) "<< /ColorTransform 1 >>\n", 24);
}
break;
#endif
#ifdef ZIP_SUPPORT
case T2P_COMPRESS_ZIP:
written += t2pWriteFile(output, (tdata_t) "/FlateDecode ", 13);
if(t2p->pdf_compressionquality%100){
written += t2pWriteFile(output, (tdata_t) "/DecodeParms ", 13);
written += t2pWriteFile(output, (tdata_t) "<< /Predictor ", 14);
buflen=snprintf(buffer, sizeof(buffer), "%u", t2p->pdf_compressionquality%100);
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) " /Columns ", 10);
buflen = snprintf(buffer, sizeof(buffer), "%lu",
(unsigned long)t2p->tiff_width);
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) " /Colors ", 9);
buflen=snprintf(buffer, sizeof(buffer), "%u", t2p->tiff_samplesperpixel);
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) " /BitsPerComponent ", 19);
buflen=snprintf(buffer, sizeof(buffer), "%u", t2p->tiff_bitspersample);
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) ">>\n", 3);
}
break;
#endif
default:
break;
}
return(written);
}
/*
This function writes a PDF xref table to output.
*/
tsize_t t2p_write_pdf_xreftable(T2P* t2p, TIFF* output){
tsize_t written=0;
char buffer[64];
int buflen=0;
uint32 i=0;
written += t2pWriteFile(output, (tdata_t) "xref\n0 ", 7);
buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(t2p->pdf_xrefcount + 1));
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) " \n0000000000 65535 f \n", 22);
for (i=0;i<t2p->pdf_xrefcount;i++){
snprintf(buffer, sizeof(buffer), "%.10lu 00000 n \n",
(unsigned long)t2p->pdf_xrefoffsets[i]);
written += t2pWriteFile(output, (tdata_t) buffer, 20);
}
return(written);
}
/*
* This function writes a PDF trailer to output.
*/
tsize_t t2p_write_pdf_trailer(T2P* t2p, TIFF* output)
{
tsize_t written = 0;
char buffer[32];
int buflen = 0;
size_t i = 0;
for (i = 0; i < sizeof(t2p->pdf_fileid) - 8; i += 8)
snprintf(t2p->pdf_fileid + i, 9, "%.8X", rand());
written += t2pWriteFile(output, (tdata_t) "trailer\n<<\n/Size ", 17);
buflen = snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(t2p->pdf_xrefcount+1));
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) "\n/Root ", 7);
buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_catalog);
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) " 0 R \n/Info ", 12);
buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_info);
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) " 0 R \n/ID[<", 11);
written += t2pWriteFile(output, (tdata_t) t2p->pdf_fileid,
sizeof(t2p->pdf_fileid) - 1);
written += t2pWriteFile(output, (tdata_t) "><", 2);
written += t2pWriteFile(output, (tdata_t) t2p->pdf_fileid,
sizeof(t2p->pdf_fileid) - 1);
written += t2pWriteFile(output, (tdata_t) ">]\n>>\nstartxref\n", 16);
buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_startxref);
check_snprintf_ret(t2p, buflen, buffer);
written += t2pWriteFile(output, (tdata_t) buffer, buflen);
written += t2pWriteFile(output, (tdata_t) "\n%%EOF\n", 7);
return(written);
}
/*
This function writes a PDF to a file given a pointer to a TIFF.
The idea with using a TIFF* as output for a PDF file is that the file
can be created with TIFFClientOpen for memory-mapped use within the TIFF
library, and TIFFWriteEncodedStrip can be used to write compressed data to
the output. The output is not actually a TIFF file, it is a PDF file.
This function uses only t2pWriteFile and TIFFWriteEncodedStrip to write to
the output TIFF file. When libtiff would otherwise be writing data to the
output file, the write procedure of the TIFF structure is replaced with an
empty implementation.
The first argument to the function is an initialized and validated T2P
context struct pointer.
The second argument to the function is the TIFF* that is the input that has
been opened for reading and no other functions have been called upon it.
The third argument to the function is the TIFF* that is the output that has
been opened for writing. It has to be opened so that it hasn't written any
data to the output. If the output is seekable then it's OK to seek to the
beginning of the file. The function only writes to the output PDF and does
not seek. See the example usage in the main() function.
TIFF* output = TIFFOpen("output.pdf", "w");
assert(output != NULL);
if(output->tif_seekproc != NULL){
t2pSeekFile(output, (toff_t) 0, SEEK_SET);
}
This function returns the file size of the output PDF file. On error it
returns zero and the t2p->t2p_error variable is set to T2P_ERR_ERROR.
After this function completes, call t2p_free on t2p, TIFFClose on input,
and TIFFClose on output.
*/
tsize_t t2p_write_pdf(T2P* t2p, TIFF* input, TIFF* output){
tsize_t written=0;
ttile_t i2=0;
tsize_t streamlen=0;
uint16 i=0;
t2p_read_tiff_init(t2p, input);
if(t2p->t2p_error!=T2P_ERR_OK){return(0);}
t2p->pdf_xrefoffsets= (uint32*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,t2p->pdf_xrefcount,sizeof(uint32)) );
if(t2p->pdf_xrefoffsets==NULL){
TIFFError(
TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_write_pdf",
(unsigned int) (t2p->pdf_xrefcount * sizeof(uint32)) );
t2p->t2p_error = T2P_ERR_ERROR;
return(written);
}
t2p->pdf_xrefcount=0;
t2p->pdf_catalog=1;
t2p->pdf_info=2;
t2p->pdf_pages=3;
written += t2p_write_pdf_header(t2p, output);
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
t2p->pdf_catalog=t2p->pdf_xrefcount;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_catalog(t2p, output);
written += t2p_write_pdf_obj_end(output);
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
t2p->pdf_info=t2p->pdf_xrefcount;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_info(t2p, input, output);
written += t2p_write_pdf_obj_end(output);
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
t2p->pdf_pages=t2p->pdf_xrefcount;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_pages(t2p, output);
written += t2p_write_pdf_obj_end(output);
for(t2p->pdf_page=0;t2p->pdf_page<t2p->tiff_pagecount;t2p->pdf_page++){
t2p_read_tiff_data(t2p, input);
if(t2p->t2p_error!=T2P_ERR_OK){return(0);}
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_page(t2p->pdf_xrefcount, t2p, output);
written += t2p_write_pdf_obj_end(output);
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_stream_dict_start(output);
written += t2p_write_pdf_stream_dict(0, t2p->pdf_xrefcount+1, output);
written += t2p_write_pdf_stream_dict_end(output);
written += t2p_write_pdf_stream_start(output);
streamlen=written;
written += t2p_write_pdf_page_content_stream(t2p, output);
streamlen=written-streamlen;
written += t2p_write_pdf_stream_end(output);
written += t2p_write_pdf_obj_end(output);
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_stream_length(streamlen, output);
written += t2p_write_pdf_obj_end(output);
if(t2p->tiff_transferfunctioncount != 0){
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_transfer(t2p, output);
written += t2p_write_pdf_obj_end(output);
for(i=0; i < t2p->tiff_transferfunctioncount; i++){
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_stream_dict_start(output);
written += t2p_write_pdf_transfer_dict(t2p, output, i);
written += t2p_write_pdf_stream_dict_end(output);
written += t2p_write_pdf_stream_start(output);
/* streamlen=written; */ /* value not used */
written += t2p_write_pdf_transfer_stream(t2p, output, i);
/* streamlen=written-streamlen; */ /* value not used */
written += t2p_write_pdf_stream_end(output);
written += t2p_write_pdf_obj_end(output);
}
}
if( (t2p->pdf_colorspace & T2P_CS_PALETTE) != 0){
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
t2p->pdf_palettecs=t2p->pdf_xrefcount;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_stream_dict_start(output);
written += t2p_write_pdf_stream_dict(t2p->pdf_palettesize, 0, output);
written += t2p_write_pdf_stream_dict_end(output);
written += t2p_write_pdf_stream_start(output);
/* streamlen=written; */ /* value not used */
written += t2p_write_pdf_xobject_palettecs_stream(t2p, output);
/* streamlen=written-streamlen; */ /* value not used */
written += t2p_write_pdf_stream_end(output);
written += t2p_write_pdf_obj_end(output);
}
if( (t2p->pdf_colorspace & T2P_CS_ICCBASED) != 0){
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
t2p->pdf_icccs=t2p->pdf_xrefcount;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_stream_dict_start(output);
written += t2p_write_pdf_xobject_icccs_dict(t2p, output);
written += t2p_write_pdf_stream_dict_end(output);
written += t2p_write_pdf_stream_start(output);
/* streamlen=written; */ /* value not used */
written += t2p_write_pdf_xobject_icccs_stream(t2p, output);
/* streamlen=written-streamlen; */ /* value not used */
written += t2p_write_pdf_stream_end(output);
written += t2p_write_pdf_obj_end(output);
}
if(t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount !=0){
for(i2=0;i2<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount;i2++){
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_stream_dict_start(output);
written += t2p_write_pdf_xobject_stream_dict(
i2+1,
t2p,
output);
written += t2p_write_pdf_stream_dict_end(output);
written += t2p_write_pdf_stream_start(output);
streamlen=written;
t2p_read_tiff_size_tile(t2p, input, i2);
written += t2p_readwrite_pdf_image_tile(t2p, input, output, i2);
t2p_write_advance_directory(t2p, output);
if(t2p->t2p_error!=T2P_ERR_OK){return(0);}
streamlen=written-streamlen;
written += t2p_write_pdf_stream_end(output);
written += t2p_write_pdf_obj_end(output);
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_stream_length(streamlen, output);
written += t2p_write_pdf_obj_end(output);
}
} else {
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_stream_dict_start(output);
written += t2p_write_pdf_xobject_stream_dict(
0,
t2p,
output);
written += t2p_write_pdf_stream_dict_end(output);
written += t2p_write_pdf_stream_start(output);
streamlen=written;
t2p_read_tiff_size(t2p, input);
written += t2p_readwrite_pdf_image(t2p, input, output);
t2p_write_advance_directory(t2p, output);
if(t2p->t2p_error!=T2P_ERR_OK){return(0);}
streamlen=written-streamlen;
written += t2p_write_pdf_stream_end(output);
written += t2p_write_pdf_obj_end(output);
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_stream_length(streamlen, output);
written += t2p_write_pdf_obj_end(output);
}
}
t2p->pdf_startxref = written;
written += t2p_write_pdf_xreftable(t2p, output);
written += t2p_write_pdf_trailer(t2p, output);
t2p_disable(output);
return(written);
}
/* 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-787/c/bad_5479_3 |
crossvul-cpp_data_bad_5499_1 | /* (C) 1999-2001 Paul `Rusty' Russell
* (C) 2002-2004 Netfilter Core Team <coreteam@netfilter.org>
*
* 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.
*/
#include <linux/types.h>
#include <linux/ipv6.h>
#include <linux/in6.h>
#include <linux/netfilter.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/icmp.h>
#include <linux/sysctl.h>
#include <net/ipv6.h>
#include <net/inet_frag.h>
#include <linux/netfilter_ipv6.h>
#include <linux/netfilter_bridge.h>
#if IS_ENABLED(CONFIG_NF_CONNTRACK)
#include <net/netfilter/nf_conntrack.h>
#include <net/netfilter/nf_conntrack_helper.h>
#include <net/netfilter/nf_conntrack_l4proto.h>
#include <net/netfilter/nf_conntrack_l3proto.h>
#include <net/netfilter/nf_conntrack_core.h>
#include <net/netfilter/ipv6/nf_conntrack_ipv6.h>
#endif
#include <net/netfilter/nf_conntrack_zones.h>
#include <net/netfilter/ipv6/nf_defrag_ipv6.h>
static enum ip6_defrag_users nf_ct6_defrag_user(unsigned int hooknum,
struct sk_buff *skb)
{
u16 zone_id = NF_CT_DEFAULT_ZONE_ID;
#if IS_ENABLED(CONFIG_NF_CONNTRACK)
if (skb->nfct) {
enum ip_conntrack_info ctinfo;
const struct nf_conn *ct = nf_ct_get(skb, &ctinfo);
zone_id = nf_ct_zone_id(nf_ct_zone(ct), CTINFO2DIR(ctinfo));
}
#endif
if (nf_bridge_in_prerouting(skb))
return IP6_DEFRAG_CONNTRACK_BRIDGE_IN + zone_id;
if (hooknum == NF_INET_PRE_ROUTING)
return IP6_DEFRAG_CONNTRACK_IN + zone_id;
else
return IP6_DEFRAG_CONNTRACK_OUT + zone_id;
}
static unsigned int ipv6_defrag(void *priv,
struct sk_buff *skb,
const struct nf_hook_state *state)
{
int err;
#if IS_ENABLED(CONFIG_NF_CONNTRACK)
/* Previously seen (loopback)? */
if (skb->nfct && !nf_ct_is_template((struct nf_conn *)skb->nfct))
return NF_ACCEPT;
#endif
err = nf_ct_frag6_gather(state->net, skb,
nf_ct6_defrag_user(state->hook, skb));
/* queued */
if (err == -EINPROGRESS)
return NF_STOLEN;
return NF_ACCEPT;
}
static struct nf_hook_ops ipv6_defrag_ops[] = {
{
.hook = ipv6_defrag,
.pf = NFPROTO_IPV6,
.hooknum = NF_INET_PRE_ROUTING,
.priority = NF_IP6_PRI_CONNTRACK_DEFRAG,
},
{
.hook = ipv6_defrag,
.pf = NFPROTO_IPV6,
.hooknum = NF_INET_LOCAL_OUT,
.priority = NF_IP6_PRI_CONNTRACK_DEFRAG,
},
};
static int __init nf_defrag_init(void)
{
int ret = 0;
ret = nf_ct_frag6_init();
if (ret < 0) {
pr_err("nf_defrag_ipv6: can't initialize frag6.\n");
return ret;
}
ret = nf_register_hooks(ipv6_defrag_ops, ARRAY_SIZE(ipv6_defrag_ops));
if (ret < 0) {
pr_err("nf_defrag_ipv6: can't register hooks\n");
goto cleanup_frag6;
}
return ret;
cleanup_frag6:
nf_ct_frag6_cleanup();
return ret;
}
static void __exit nf_defrag_fini(void)
{
nf_unregister_hooks(ipv6_defrag_ops, ARRAY_SIZE(ipv6_defrag_ops));
nf_ct_frag6_cleanup();
}
void nf_defrag_ipv6_enable(void)
{
}
EXPORT_SYMBOL_GPL(nf_defrag_ipv6_enable);
module_init(nf_defrag_init);
module_exit(nf_defrag_fini);
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_5499_1 |
crossvul-cpp_data_bad_5479_2 | /* $Id$ */
/*
* Copyright (c) 1988-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.
*
* Scanline-oriented Write Support
*/
#include "tiffiop.h"
#include <stdio.h>
#define STRIPINCR 20 /* expansion factor on strip array */
#define WRITECHECKSTRIPS(tif, module) \
(((tif)->tif_flags&TIFF_BEENWRITING) || TIFFWriteCheck((tif),0,module))
#define WRITECHECKTILES(tif, module) \
(((tif)->tif_flags&TIFF_BEENWRITING) || TIFFWriteCheck((tif),1,module))
#define BUFFERCHECK(tif) \
((((tif)->tif_flags & TIFF_BUFFERSETUP) && tif->tif_rawdata) || \
TIFFWriteBufferSetup((tif), NULL, (tmsize_t) -1))
static int TIFFGrowStrips(TIFF* tif, uint32 delta, const char* module);
static int TIFFAppendToStrip(TIFF* tif, uint32 strip, uint8* data, tmsize_t cc);
int
TIFFWriteScanline(TIFF* tif, void* buf, uint32 row, uint16 sample)
{
static const char module[] = "TIFFWriteScanline";
register TIFFDirectory *td;
int status, imagegrew = 0;
uint32 strip;
if (!WRITECHECKSTRIPS(tif, module))
return (-1);
/*
* Handle delayed allocation of data buffer. This
* permits it to be sized more intelligently (using
* directory information).
*/
if (!BUFFERCHECK(tif))
return (-1);
tif->tif_flags |= TIFF_BUF4WRITE; /* not strictly sure this is right*/
td = &tif->tif_dir;
/*
* Extend image length if needed
* (but only for PlanarConfig=1).
*/
if (row >= td->td_imagelength) { /* extend image */
if (td->td_planarconfig == PLANARCONFIG_SEPARATE) {
TIFFErrorExt(tif->tif_clientdata, module,
"Can not change \"ImageLength\" when using separate planes");
return (-1);
}
td->td_imagelength = row+1;
imagegrew = 1;
}
/*
* Calculate strip and check for crossings.
*/
if (td->td_planarconfig == PLANARCONFIG_SEPARATE) {
if (sample >= td->td_samplesperpixel) {
TIFFErrorExt(tif->tif_clientdata, module,
"%lu: Sample out of range, max %lu",
(unsigned long) sample, (unsigned long) td->td_samplesperpixel);
return (-1);
}
strip = sample*td->td_stripsperimage + row/td->td_rowsperstrip;
} else
strip = row / td->td_rowsperstrip;
/*
* Check strip array to make sure there's space. We don't support
* dynamically growing files that have data organized in separate
* bitplanes because it's too painful. In that case we require that
* the imagelength be set properly before the first write (so that the
* strips array will be fully allocated above).
*/
if (strip >= td->td_nstrips && !TIFFGrowStrips(tif, 1, module))
return (-1);
if (strip != tif->tif_curstrip) {
/*
* Changing strips -- flush any data present.
*/
if (!TIFFFlushData(tif))
return (-1);
tif->tif_curstrip = strip;
/*
* Watch out for a growing image. The value of strips/image
* will initially be 1 (since it can't be deduced until the
* imagelength is known).
*/
if (strip >= td->td_stripsperimage && imagegrew)
td->td_stripsperimage =
TIFFhowmany_32(td->td_imagelength,td->td_rowsperstrip);
if (td->td_stripsperimage == 0) {
TIFFErrorExt(tif->tif_clientdata, module, "Zero strips per image");
return (-1);
}
tif->tif_row =
(strip % td->td_stripsperimage) * td->td_rowsperstrip;
if ((tif->tif_flags & TIFF_CODERSETUP) == 0) {
if (!(*tif->tif_setupencode)(tif))
return (-1);
tif->tif_flags |= TIFF_CODERSETUP;
}
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
if( td->td_stripbytecount[strip] > 0 )
{
/* if we are writing over existing tiles, zero length */
td->td_stripbytecount[strip] = 0;
/* this forces TIFFAppendToStrip() to do a seek */
tif->tif_curoff = 0;
}
if (!(*tif->tif_preencode)(tif, sample))
return (-1);
tif->tif_flags |= TIFF_POSTENCODE;
}
/*
* Ensure the write is either sequential or at the
* beginning of a strip (or that we can randomly
* access the data -- i.e. no encoding).
*/
if (row != tif->tif_row) {
if (row < tif->tif_row) {
/*
* Moving backwards within the same strip:
* backup to the start and then decode
* forward (below).
*/
tif->tif_row = (strip % td->td_stripsperimage) *
td->td_rowsperstrip;
tif->tif_rawcp = tif->tif_rawdata;
}
/*
* Seek forward to the desired row.
*/
if (!(*tif->tif_seek)(tif, row - tif->tif_row))
return (-1);
tif->tif_row = row;
}
/* swab if needed - note that source buffer will be altered */
tif->tif_postdecode( tif, (uint8*) buf, tif->tif_scanlinesize );
status = (*tif->tif_encoderow)(tif, (uint8*) buf,
tif->tif_scanlinesize, sample);
/* we are now poised at the beginning of the next row */
tif->tif_row = row + 1;
return (status);
}
/*
* Encode the supplied data and write it to the
* specified strip.
*
* NB: Image length must be setup before writing.
*/
tmsize_t
TIFFWriteEncodedStrip(TIFF* tif, uint32 strip, void* data, tmsize_t cc)
{
static const char module[] = "TIFFWriteEncodedStrip";
TIFFDirectory *td = &tif->tif_dir;
uint16 sample;
if (!WRITECHECKSTRIPS(tif, module))
return ((tmsize_t) -1);
/*
* Check strip array to make sure there's space.
* We don't support dynamically growing files that
* have data organized in separate bitplanes because
* it's too painful. In that case we require that
* the imagelength be set properly before the first
* write (so that the strips array will be fully
* allocated above).
*/
if (strip >= td->td_nstrips) {
if (td->td_planarconfig == PLANARCONFIG_SEPARATE) {
TIFFErrorExt(tif->tif_clientdata, module,
"Can not grow image by strips when using separate planes");
return ((tmsize_t) -1);
}
if (!TIFFGrowStrips(tif, 1, module))
return ((tmsize_t) -1);
td->td_stripsperimage =
TIFFhowmany_32(td->td_imagelength, td->td_rowsperstrip);
}
/*
* Handle delayed allocation of data buffer. This
* permits it to be sized according to the directory
* info.
*/
if (!BUFFERCHECK(tif))
return ((tmsize_t) -1);
tif->tif_flags |= TIFF_BUF4WRITE;
tif->tif_curstrip = strip;
if (td->td_stripsperimage == 0) {
TIFFErrorExt(tif->tif_clientdata, module, "Zero strips per image");
return ((tmsize_t) -1);
}
tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip;
if ((tif->tif_flags & TIFF_CODERSETUP) == 0) {
if (!(*tif->tif_setupencode)(tif))
return ((tmsize_t) -1);
tif->tif_flags |= TIFF_CODERSETUP;
}
if( td->td_stripbytecount[strip] > 0 )
{
/* Make sure that at the first attempt of rewriting the tile, we will have */
/* more bytes available in the output buffer than the previous byte count, */
/* so that TIFFAppendToStrip() will detect the overflow when it is called the first */
/* time if the new compressed tile is bigger than the older one. (GDAL #4771) */
if( tif->tif_rawdatasize <= (tmsize_t)td->td_stripbytecount[strip] )
{
if( !(TIFFWriteBufferSetup(tif, NULL,
(tmsize_t)TIFFroundup_64((uint64)(td->td_stripbytecount[strip] + 1), 1024))) )
return ((tmsize_t)(-1));
}
/* Force TIFFAppendToStrip() to consider placing data at end
of file. */
tif->tif_curoff = 0;
}
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
tif->tif_flags &= ~TIFF_POSTENCODE;
/* shortcut to avoid an extra memcpy() */
if( td->td_compression == COMPRESSION_NONE )
{
/* swab if needed - note that source buffer will be altered */
tif->tif_postdecode( tif, (uint8*) data, cc );
if (!isFillOrder(tif, td->td_fillorder) &&
(tif->tif_flags & TIFF_NOBITREV) == 0)
TIFFReverseBits((uint8*) data, cc);
if (cc > 0 &&
!TIFFAppendToStrip(tif, strip, (uint8*) data, cc))
return ((tmsize_t) -1);
return (cc);
}
sample = (uint16)(strip / td->td_stripsperimage);
if (!(*tif->tif_preencode)(tif, sample))
return ((tmsize_t) -1);
/* swab if needed - note that source buffer will be altered */
tif->tif_postdecode( tif, (uint8*) data, cc );
if (!(*tif->tif_encodestrip)(tif, (uint8*) data, cc, sample))
return ((tmsize_t) -1);
if (!(*tif->tif_postencode)(tif))
return ((tmsize_t) -1);
if (!isFillOrder(tif, td->td_fillorder) &&
(tif->tif_flags & TIFF_NOBITREV) == 0)
TIFFReverseBits(tif->tif_rawdata, tif->tif_rawcc);
if (tif->tif_rawcc > 0 &&
!TIFFAppendToStrip(tif, strip, tif->tif_rawdata, tif->tif_rawcc))
return ((tmsize_t) -1);
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
return (cc);
}
/*
* Write the supplied data to the specified strip.
*
* NB: Image length must be setup before writing.
*/
tmsize_t
TIFFWriteRawStrip(TIFF* tif, uint32 strip, void* data, tmsize_t cc)
{
static const char module[] = "TIFFWriteRawStrip";
TIFFDirectory *td = &tif->tif_dir;
if (!WRITECHECKSTRIPS(tif, module))
return ((tmsize_t) -1);
/*
* Check strip array to make sure there's space.
* We don't support dynamically growing files that
* have data organized in separate bitplanes because
* it's too painful. In that case we require that
* the imagelength be set properly before the first
* write (so that the strips array will be fully
* allocated above).
*/
if (strip >= td->td_nstrips) {
if (td->td_planarconfig == PLANARCONFIG_SEPARATE) {
TIFFErrorExt(tif->tif_clientdata, module,
"Can not grow image by strips when using separate planes");
return ((tmsize_t) -1);
}
/*
* Watch out for a growing image. The value of
* strips/image will initially be 1 (since it
* can't be deduced until the imagelength is known).
*/
if (strip >= td->td_stripsperimage)
td->td_stripsperimage =
TIFFhowmany_32(td->td_imagelength,td->td_rowsperstrip);
if (!TIFFGrowStrips(tif, 1, module))
return ((tmsize_t) -1);
}
tif->tif_curstrip = strip;
if (td->td_stripsperimage == 0) {
TIFFErrorExt(tif->tif_clientdata, module,"Zero strips per image");
return ((tmsize_t) -1);
}
tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip;
return (TIFFAppendToStrip(tif, strip, (uint8*) data, cc) ?
cc : (tmsize_t) -1);
}
/*
* Write and compress a tile of data. The
* tile is selected by the (x,y,z,s) coordinates.
*/
tmsize_t
TIFFWriteTile(TIFF* tif, void* buf, uint32 x, uint32 y, uint32 z, uint16 s)
{
if (!TIFFCheckTile(tif, x, y, z, s))
return ((tmsize_t)(-1));
/*
* NB: A tile size of -1 is used instead of tif_tilesize knowing
* that TIFFWriteEncodedTile will clamp this to the tile size.
* This is done because the tile size may not be defined until
* after the output buffer is setup in TIFFWriteBufferSetup.
*/
return (TIFFWriteEncodedTile(tif,
TIFFComputeTile(tif, x, y, z, s), buf, (tmsize_t)(-1)));
}
/*
* Encode the supplied data and write it to the
* specified tile. There must be space for the
* data. The function clamps individual writes
* to a tile to the tile size, but does not (and
* can not) check that multiple writes to the same
* tile do not write more than tile size data.
*
* NB: Image length must be setup before writing; this
* interface does not support automatically growing
* the image on each write (as TIFFWriteScanline does).
*/
tmsize_t
TIFFWriteEncodedTile(TIFF* tif, uint32 tile, void* data, tmsize_t cc)
{
static const char module[] = "TIFFWriteEncodedTile";
TIFFDirectory *td;
uint16 sample;
uint32 howmany32;
if (!WRITECHECKTILES(tif, module))
return ((tmsize_t)(-1));
td = &tif->tif_dir;
if (tile >= td->td_nstrips) {
TIFFErrorExt(tif->tif_clientdata, module, "Tile %lu out of range, max %lu",
(unsigned long) tile, (unsigned long) td->td_nstrips);
return ((tmsize_t)(-1));
}
/*
* Handle delayed allocation of data buffer. This
* permits it to be sized more intelligently (using
* directory information).
*/
if (!BUFFERCHECK(tif))
return ((tmsize_t)(-1));
tif->tif_flags |= TIFF_BUF4WRITE;
tif->tif_curtile = tile;
if( td->td_stripbytecount[tile] > 0 )
{
/* Make sure that at the first attempt of rewriting the tile, we will have */
/* more bytes available in the output buffer than the previous byte count, */
/* so that TIFFAppendToStrip() will detect the overflow when it is called the first */
/* time if the new compressed tile is bigger than the older one. (GDAL #4771) */
if( tif->tif_rawdatasize <= (tmsize_t) td->td_stripbytecount[tile] )
{
if( !(TIFFWriteBufferSetup(tif, NULL,
(tmsize_t)TIFFroundup_64((uint64)(td->td_stripbytecount[tile] + 1), 1024))) )
return ((tmsize_t)(-1));
}
/* Force TIFFAppendToStrip() to consider placing data at end
of file. */
tif->tif_curoff = 0;
}
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
/*
* Compute tiles per row & per column to compute
* current row and column
*/
howmany32=TIFFhowmany_32(td->td_imagelength, td->td_tilelength);
if (howmany32 == 0) {
TIFFErrorExt(tif->tif_clientdata,module,"Zero tiles");
return ((tmsize_t)(-1));
}
tif->tif_row = (tile % howmany32) * td->td_tilelength;
howmany32=TIFFhowmany_32(td->td_imagewidth, td->td_tilewidth);
if (howmany32 == 0) {
TIFFErrorExt(tif->tif_clientdata,module,"Zero tiles");
return ((tmsize_t)(-1));
}
tif->tif_col = (tile % howmany32) * td->td_tilewidth;
if ((tif->tif_flags & TIFF_CODERSETUP) == 0) {
if (!(*tif->tif_setupencode)(tif))
return ((tmsize_t)(-1));
tif->tif_flags |= TIFF_CODERSETUP;
}
tif->tif_flags &= ~TIFF_POSTENCODE;
/*
* Clamp write amount to the tile size. This is mostly
* done so that callers can pass in some large number
* (e.g. -1) and have the tile size used instead.
*/
if ( cc < 1 || cc > tif->tif_tilesize)
cc = tif->tif_tilesize;
/* shortcut to avoid an extra memcpy() */
if( td->td_compression == COMPRESSION_NONE )
{
/* swab if needed - note that source buffer will be altered */
tif->tif_postdecode( tif, (uint8*) data, cc );
if (!isFillOrder(tif, td->td_fillorder) &&
(tif->tif_flags & TIFF_NOBITREV) == 0)
TIFFReverseBits((uint8*) data, cc);
if (cc > 0 &&
!TIFFAppendToStrip(tif, tile, (uint8*) data, cc))
return ((tmsize_t) -1);
return (cc);
}
sample = (uint16)(tile/td->td_stripsperimage);
if (!(*tif->tif_preencode)(tif, sample))
return ((tmsize_t)(-1));
/* swab if needed - note that source buffer will be altered */
tif->tif_postdecode( tif, (uint8*) data, cc );
if (!(*tif->tif_encodetile)(tif, (uint8*) data, cc, sample))
return ((tmsize_t) -1);
if (!(*tif->tif_postencode)(tif))
return ((tmsize_t)(-1));
if (!isFillOrder(tif, td->td_fillorder) &&
(tif->tif_flags & TIFF_NOBITREV) == 0)
TIFFReverseBits((uint8*)tif->tif_rawdata, tif->tif_rawcc);
if (tif->tif_rawcc > 0 && !TIFFAppendToStrip(tif, tile,
tif->tif_rawdata, tif->tif_rawcc))
return ((tmsize_t)(-1));
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
return (cc);
}
/*
* Write the supplied data to the specified strip.
* There must be space for the data; we don't check
* if strips overlap!
*
* NB: Image length must be setup before writing; this
* interface does not support automatically growing
* the image on each write (as TIFFWriteScanline does).
*/
tmsize_t
TIFFWriteRawTile(TIFF* tif, uint32 tile, void* data, tmsize_t cc)
{
static const char module[] = "TIFFWriteRawTile";
if (!WRITECHECKTILES(tif, module))
return ((tmsize_t)(-1));
if (tile >= tif->tif_dir.td_nstrips) {
TIFFErrorExt(tif->tif_clientdata, module, "Tile %lu out of range, max %lu",
(unsigned long) tile,
(unsigned long) tif->tif_dir.td_nstrips);
return ((tmsize_t)(-1));
}
return (TIFFAppendToStrip(tif, tile, (uint8*) data, cc) ?
cc : (tmsize_t)(-1));
}
#define isUnspecified(tif, f) \
(TIFFFieldSet(tif,f) && (tif)->tif_dir.td_imagelength == 0)
int
TIFFSetupStrips(TIFF* tif)
{
TIFFDirectory* td = &tif->tif_dir;
if (isTiled(tif))
td->td_stripsperimage =
isUnspecified(tif, FIELD_TILEDIMENSIONS) ?
td->td_samplesperpixel : TIFFNumberOfTiles(tif);
else
td->td_stripsperimage =
isUnspecified(tif, FIELD_ROWSPERSTRIP) ?
td->td_samplesperpixel : TIFFNumberOfStrips(tif);
td->td_nstrips = td->td_stripsperimage;
if (td->td_planarconfig == PLANARCONFIG_SEPARATE)
td->td_stripsperimage /= td->td_samplesperpixel;
td->td_stripoffset = (uint64 *)
_TIFFmalloc(td->td_nstrips * sizeof (uint64));
td->td_stripbytecount = (uint64 *)
_TIFFmalloc(td->td_nstrips * sizeof (uint64));
if (td->td_stripoffset == NULL || td->td_stripbytecount == NULL)
return (0);
/*
* Place data at the end-of-file
* (by setting offsets to zero).
*/
_TIFFmemset(td->td_stripoffset, 0, td->td_nstrips*sizeof (uint64));
_TIFFmemset(td->td_stripbytecount, 0, td->td_nstrips*sizeof (uint64));
TIFFSetFieldBit(tif, FIELD_STRIPOFFSETS);
TIFFSetFieldBit(tif, FIELD_STRIPBYTECOUNTS);
return (1);
}
#undef isUnspecified
/*
* Verify file is writable and that the directory
* information is setup properly. In doing the latter
* we also "freeze" the state of the directory so
* that important information is not changed.
*/
int
TIFFWriteCheck(TIFF* tif, int tiles, const char* module)
{
if (tif->tif_mode == O_RDONLY) {
TIFFErrorExt(tif->tif_clientdata, module, "File not open for writing");
return (0);
}
if (tiles ^ isTiled(tif)) {
TIFFErrorExt(tif->tif_clientdata, module, tiles ?
"Can not write tiles to a stripped image" :
"Can not write scanlines to a tiled image");
return (0);
}
_TIFFFillStriles( tif );
/*
* On the first write verify all the required information
* has been setup and initialize any data structures that
* had to wait until directory information was set.
* Note that a lot of our work is assumed to remain valid
* because we disallow any of the important parameters
* from changing after we start writing (i.e. once
* TIFF_BEENWRITING is set, TIFFSetField will only allow
* the image's length to be changed).
*/
if (!TIFFFieldSet(tif, FIELD_IMAGEDIMENSIONS)) {
TIFFErrorExt(tif->tif_clientdata, module,
"Must set \"ImageWidth\" before writing data");
return (0);
}
if (tif->tif_dir.td_samplesperpixel == 1) {
/*
* Planarconfiguration is irrelevant in case of single band
* images and need not be included. We will set it anyway,
* because this field is used in other parts of library even
* in the single band case.
*/
if (!TIFFFieldSet(tif, FIELD_PLANARCONFIG))
tif->tif_dir.td_planarconfig = PLANARCONFIG_CONTIG;
} else {
if (!TIFFFieldSet(tif, FIELD_PLANARCONFIG)) {
TIFFErrorExt(tif->tif_clientdata, module,
"Must set \"PlanarConfiguration\" before writing data");
return (0);
}
}
if (tif->tif_dir.td_stripoffset == NULL && !TIFFSetupStrips(tif)) {
tif->tif_dir.td_nstrips = 0;
TIFFErrorExt(tif->tif_clientdata, module, "No space for %s arrays",
isTiled(tif) ? "tile" : "strip");
return (0);
}
if (isTiled(tif))
{
tif->tif_tilesize = TIFFTileSize(tif);
if (tif->tif_tilesize == 0)
return (0);
}
else
tif->tif_tilesize = (tmsize_t)(-1);
tif->tif_scanlinesize = TIFFScanlineSize(tif);
if (tif->tif_scanlinesize == 0)
return (0);
tif->tif_flags |= TIFF_BEENWRITING;
return (1);
}
/*
* Setup the raw data buffer used for encoding.
*/
int
TIFFWriteBufferSetup(TIFF* tif, void* bp, tmsize_t size)
{
static const char module[] = "TIFFWriteBufferSetup";
if (tif->tif_rawdata) {
if (tif->tif_flags & TIFF_MYBUFFER) {
_TIFFfree(tif->tif_rawdata);
tif->tif_flags &= ~TIFF_MYBUFFER;
}
tif->tif_rawdata = NULL;
}
if (size == (tmsize_t)(-1)) {
size = (isTiled(tif) ?
tif->tif_tilesize : TIFFStripSize(tif));
/*
* Make raw data buffer at least 8K
*/
if (size < 8*1024)
size = 8*1024;
bp = NULL; /* NB: force malloc */
}
if (bp == NULL) {
bp = _TIFFmalloc(size);
if (bp == NULL) {
TIFFErrorExt(tif->tif_clientdata, module, "No space for output buffer");
return (0);
}
tif->tif_flags |= TIFF_MYBUFFER;
} else
tif->tif_flags &= ~TIFF_MYBUFFER;
tif->tif_rawdata = (uint8*) bp;
tif->tif_rawdatasize = size;
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
tif->tif_flags |= TIFF_BUFFERSETUP;
return (1);
}
/*
* Grow the strip data structures by delta strips.
*/
static int
TIFFGrowStrips(TIFF* tif, uint32 delta, const char* module)
{
TIFFDirectory *td = &tif->tif_dir;
uint64* new_stripoffset;
uint64* new_stripbytecount;
assert(td->td_planarconfig == PLANARCONFIG_CONTIG);
new_stripoffset = (uint64*)_TIFFrealloc(td->td_stripoffset,
(td->td_nstrips + delta) * sizeof (uint64));
new_stripbytecount = (uint64*)_TIFFrealloc(td->td_stripbytecount,
(td->td_nstrips + delta) * sizeof (uint64));
if (new_stripoffset == NULL || new_stripbytecount == NULL) {
if (new_stripoffset)
_TIFFfree(new_stripoffset);
if (new_stripbytecount)
_TIFFfree(new_stripbytecount);
td->td_nstrips = 0;
TIFFErrorExt(tif->tif_clientdata, module, "No space to expand strip arrays");
return (0);
}
td->td_stripoffset = new_stripoffset;
td->td_stripbytecount = new_stripbytecount;
_TIFFmemset(td->td_stripoffset + td->td_nstrips,
0, delta*sizeof (uint64));
_TIFFmemset(td->td_stripbytecount + td->td_nstrips,
0, delta*sizeof (uint64));
td->td_nstrips += delta;
tif->tif_flags |= TIFF_DIRTYDIRECT;
return (1);
}
/*
* Append the data to the specified strip.
*/
static int
TIFFAppendToStrip(TIFF* tif, uint32 strip, uint8* data, tmsize_t cc)
{
static const char module[] = "TIFFAppendToStrip";
TIFFDirectory *td = &tif->tif_dir;
uint64 m;
int64 old_byte_count = -1;
if (td->td_stripoffset[strip] == 0 || tif->tif_curoff == 0) {
assert(td->td_nstrips > 0);
if( td->td_stripbytecount[strip] != 0
&& td->td_stripoffset[strip] != 0
&& td->td_stripbytecount[strip] >= (uint64) cc )
{
/*
* There is already tile data on disk, and the new tile
* data we have will fit in the same space. The only
* aspect of this that is risky is that there could be
* more data to append to this strip before we are done
* depending on how we are getting called.
*/
if (!SeekOK(tif, td->td_stripoffset[strip])) {
TIFFErrorExt(tif->tif_clientdata, module,
"Seek error at scanline %lu",
(unsigned long)tif->tif_row);
return (0);
}
}
else
{
/*
* Seek to end of file, and set that as our location to
* write this strip.
*/
td->td_stripoffset[strip] = TIFFSeekFile(tif, 0, SEEK_END);
tif->tif_flags |= TIFF_DIRTYSTRIP;
}
tif->tif_curoff = td->td_stripoffset[strip];
/*
* We are starting a fresh strip/tile, so set the size to zero.
*/
old_byte_count = td->td_stripbytecount[strip];
td->td_stripbytecount[strip] = 0;
}
m = tif->tif_curoff+cc;
if (!(tif->tif_flags&TIFF_BIGTIFF))
m = (uint32)m;
if ((m<tif->tif_curoff)||(m<(uint64)cc))
{
TIFFErrorExt(tif->tif_clientdata, module, "Maximum TIFF file size exceeded");
return (0);
}
if (!WriteOK(tif, data, cc)) {
TIFFErrorExt(tif->tif_clientdata, module, "Write error at scanline %lu",
(unsigned long) tif->tif_row);
return (0);
}
tif->tif_curoff = m;
td->td_stripbytecount[strip] += cc;
if( (int64) td->td_stripbytecount[strip] != old_byte_count )
tif->tif_flags |= TIFF_DIRTYSTRIP;
return (1);
}
/*
* Internal version of TIFFFlushData that can be
* called by ``encodestrip routines'' w/o concern
* for infinite recursion.
*/
int
TIFFFlushData1(TIFF* tif)
{
if (tif->tif_rawcc > 0 && tif->tif_flags & TIFF_BUF4WRITE ) {
if (!isFillOrder(tif, tif->tif_dir.td_fillorder) &&
(tif->tif_flags & TIFF_NOBITREV) == 0)
TIFFReverseBits((uint8*)tif->tif_rawdata,
tif->tif_rawcc);
if (!TIFFAppendToStrip(tif,
isTiled(tif) ? tif->tif_curtile : tif->tif_curstrip,
tif->tif_rawdata, tif->tif_rawcc))
return (0);
tif->tif_rawcc = 0;
tif->tif_rawcp = tif->tif_rawdata;
}
return (1);
}
/*
* Set the current write offset. This should only be
* used to set the offset to a known previous location
* (very carefully), or to 0 so that the next write gets
* appended to the end of the file.
*/
void
TIFFSetWriteOffset(TIFF* tif, toff_t off)
{
tif->tif_curoff = off;
}
/* 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-787/c/bad_5479_2 |
crossvul-cpp_data_bad_4318_0 | /**********************************************************************
regcomp.c - Oniguruma (regular expression library)
**********************************************************************/
/*-
* Copyright (c) 2002-2020 K.Kosako
* 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 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 AUTHOR 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 "regparse.h"
#define OPS_INIT_SIZE 8
typedef struct {
OnigLen min;
OnigLen max;
} MinMaxLen;
typedef struct {
OnigLen min;
OnigLen max;
int min_is_sure;
} MinMaxCharLen;
OnigCaseFoldType OnigDefaultCaseFoldFlag = ONIGENC_CASE_FOLD_MIN;
static OnigLen node_min_byte_len(Node* node, ScanEnv* env);
#if 0
typedef struct {
int n;
int alloc;
int* v;
} int_stack;
static int
make_int_stack(int_stack** rs, int init_size)
{
int_stack* s;
int* v;
*rs = 0;
s = xmalloc(sizeof(*s));
if (IS_NULL(s)) return ONIGERR_MEMORY;
v = (int* )xmalloc(sizeof(int) * init_size);
if (IS_NULL(v)) {
xfree(s);
return ONIGERR_MEMORY;
}
s->n = 0;
s->alloc = init_size;
s->v = v;
*rs = s;
return ONIG_NORMAL;
}
static void
free_int_stack(int_stack* s)
{
if (IS_NOT_NULL(s)) {
if (IS_NOT_NULL(s->v))
xfree(s->v);
xfree(s);
}
}
static int
int_stack_push(int_stack* s, int v)
{
if (s->n >= s->alloc) {
int new_size = s->alloc * 2;
int* nv = (int* )xrealloc(s->v, sizeof(int) * new_size);
if (IS_NULL(nv)) return ONIGERR_MEMORY;
s->alloc = new_size;
s->v = nv;
}
s->v[s->n] = v;
s->n++;
return ONIG_NORMAL;
}
static int
int_stack_pop(int_stack* s)
{
int v;
#ifdef ONIG_DEBUG
if (s->n <= 0) {
fprintf(DBGFP, "int_stack_pop: fail empty. %p\n", s);
return 0;
}
#endif
v = s->v[s->n];
s->n--;
return v;
}
#endif
static int
ops_init(regex_t* reg, int init_alloc_size)
{
Operation* p;
size_t size;
if (init_alloc_size > 0) {
size = sizeof(Operation) * init_alloc_size;
p = (Operation* )xrealloc(reg->ops, size);
CHECK_NULL_RETURN_MEMERR(p);
reg->ops = p;
#ifdef USE_DIRECT_THREADED_CODE
{
enum OpCode* cp;
size = sizeof(enum OpCode) * init_alloc_size;
cp = (enum OpCode* )xrealloc(reg->ocs, size);
CHECK_NULL_RETURN_MEMERR(cp);
reg->ocs = cp;
}
#endif
}
else {
reg->ops = (Operation* )0;
#ifdef USE_DIRECT_THREADED_CODE
reg->ocs = (enum OpCode* )0;
#endif
}
reg->ops_curr = 0; /* !!! not yet done ops_new() */
reg->ops_alloc = init_alloc_size;
reg->ops_used = 0;
return ONIG_NORMAL;
}
static int
ops_expand(regex_t* reg, int n)
{
#define MIN_OPS_EXPAND_SIZE 4
#ifdef USE_DIRECT_THREADED_CODE
enum OpCode* cp;
#endif
Operation* p;
size_t size;
if (n <= 0) n = MIN_OPS_EXPAND_SIZE;
n += reg->ops_alloc;
size = sizeof(Operation) * n;
p = (Operation* )xrealloc(reg->ops, size);
CHECK_NULL_RETURN_MEMERR(p);
reg->ops = p;
#ifdef USE_DIRECT_THREADED_CODE
size = sizeof(enum OpCode) * n;
cp = (enum OpCode* )xrealloc(reg->ocs, size);
CHECK_NULL_RETURN_MEMERR(cp);
reg->ocs = cp;
#endif
reg->ops_alloc = n;
if (reg->ops_used == 0)
reg->ops_curr = 0;
else
reg->ops_curr = reg->ops + (reg->ops_used - 1);
return ONIG_NORMAL;
}
static int
ops_new(regex_t* reg)
{
int r;
if (reg->ops_used >= reg->ops_alloc) {
r = ops_expand(reg, reg->ops_alloc);
if (r != ONIG_NORMAL) return r;
}
reg->ops_curr = reg->ops + reg->ops_used;
reg->ops_used++;
xmemset(reg->ops_curr, 0, sizeof(Operation));
return ONIG_NORMAL;
}
static int
is_in_string_pool(regex_t* reg, UChar* s)
{
return (s >= reg->string_pool && s < reg->string_pool_end);
}
static void
ops_free(regex_t* reg)
{
int i;
if (IS_NULL(reg->ops)) return ;
for (i = 0; i < (int )reg->ops_used; i++) {
enum OpCode opcode;
Operation* op;
op = reg->ops + i;
#ifdef USE_DIRECT_THREADED_CODE
opcode = *(reg->ocs + i);
#else
opcode = op->opcode;
#endif
switch (opcode) {
case OP_STR_MBN:
if (! is_in_string_pool(reg, op->exact_len_n.s))
xfree(op->exact_len_n.s);
break;
case OP_STR_N: case OP_STR_MB2N: case OP_STR_MB3N:
if (! is_in_string_pool(reg, op->exact_n.s))
xfree(op->exact_n.s);
break;
case OP_STR_1: case OP_STR_2: case OP_STR_3: case OP_STR_4:
case OP_STR_5: case OP_STR_MB2N1: case OP_STR_MB2N2:
case OP_STR_MB2N3:
break;
case OP_CCLASS_NOT: case OP_CCLASS:
xfree(op->cclass.bsp);
break;
case OP_CCLASS_MB_NOT: case OP_CCLASS_MB:
xfree(op->cclass_mb.mb);
break;
case OP_CCLASS_MIX_NOT: case OP_CCLASS_MIX:
xfree(op->cclass_mix.mb);
xfree(op->cclass_mix.bsp);
break;
case OP_BACKREF1: case OP_BACKREF2: case OP_BACKREF_N: case OP_BACKREF_N_IC:
break;
case OP_BACKREF_MULTI: case OP_BACKREF_MULTI_IC:
case OP_BACKREF_CHECK:
#ifdef USE_BACKREF_WITH_LEVEL
case OP_BACKREF_WITH_LEVEL:
case OP_BACKREF_WITH_LEVEL_IC:
case OP_BACKREF_CHECK_WITH_LEVEL:
#endif
if (op->backref_general.num != 1)
xfree(op->backref_general.ns);
break;
default:
break;
}
}
xfree(reg->ops);
#ifdef USE_DIRECT_THREADED_CODE
xfree(reg->ocs);
reg->ocs = 0;
#endif
reg->ops = 0;
reg->ops_curr = 0;
reg->ops_alloc = 0;
reg->ops_used = 0;
}
static int
ops_calc_size_of_string_pool(regex_t* reg)
{
int i;
int total;
if (IS_NULL(reg->ops)) return 0;
total = 0;
for (i = 0; i < (int )reg->ops_used; i++) {
enum OpCode opcode;
Operation* op;
op = reg->ops + i;
#ifdef USE_DIRECT_THREADED_CODE
opcode = *(reg->ocs + i);
#else
opcode = op->opcode;
#endif
switch (opcode) {
case OP_STR_MBN:
total += op->exact_len_n.len * op->exact_len_n.n;
break;
case OP_STR_N:
case OP_STR_MB2N:
total += op->exact_n.n * 2;
break;
case OP_STR_MB3N:
total += op->exact_n.n * 3;
break;
default:
break;
}
}
return total;
}
static int
ops_make_string_pool(regex_t* reg)
{
int i;
int len;
int size;
UChar* pool;
UChar* curr;
size = ops_calc_size_of_string_pool(reg);
if (size <= 0) {
return 0;
}
curr = pool = (UChar* )xmalloc((size_t )size);
CHECK_NULL_RETURN_MEMERR(pool);
for (i = 0; i < (int )reg->ops_used; i++) {
enum OpCode opcode;
Operation* op;
op = reg->ops + i;
#ifdef USE_DIRECT_THREADED_CODE
opcode = *(reg->ocs + i);
#else
opcode = op->opcode;
#endif
switch (opcode) {
case OP_STR_MBN:
len = op->exact_len_n.len * op->exact_len_n.n;
xmemcpy(curr, op->exact_len_n.s, len);
xfree(op->exact_len_n.s);
op->exact_len_n.s = curr;
curr += len;
break;
case OP_STR_N:
len = op->exact_n.n;
copy:
xmemcpy(curr, op->exact_n.s, len);
xfree(op->exact_n.s);
op->exact_n.s = curr;
curr += len;
break;
case OP_STR_MB2N:
len = op->exact_n.n * 2;
goto copy;
break;
case OP_STR_MB3N:
len = op->exact_n.n * 3;
goto copy;
break;
default:
break;
}
}
reg->string_pool = pool;
reg->string_pool_end = pool + size;
return 0;
}
extern OnigCaseFoldType
onig_get_default_case_fold_flag(void)
{
return OnigDefaultCaseFoldFlag;
}
extern int
onig_set_default_case_fold_flag(OnigCaseFoldType case_fold_flag)
{
OnigDefaultCaseFoldFlag = case_fold_flag;
return 0;
}
static int
len_multiply_cmp(OnigLen x, int y, OnigLen v)
{
if (x == 0 || y == 0) return -1;
if (x < INFINITE_LEN / y) {
OnigLen xy = x * (OnigLen )y;
if (xy > v) return 1;
else {
if (xy == v) return 0;
else return -1;
}
}
else
return v == INFINITE_LEN ? 0 : 1;
}
extern int
onig_positive_int_multiply(int x, int y)
{
if (x == 0 || y == 0) return 0;
if (x < ONIG_INT_MAX / y)
return x * y;
else
return -1;
}
static void
node_swap(Node* a, Node* b)
{
Node c;
c = *a; *a = *b; *b = c;
if (NODE_TYPE(a) == NODE_STRING) {
StrNode* sn = STR_(a);
if (sn->capacity == 0) {
int len = (int )(sn->end - sn->s);
sn->s = sn->buf;
sn->end = sn->s + len;
}
}
if (NODE_TYPE(b) == NODE_STRING) {
StrNode* sn = STR_(b);
if (sn->capacity == 0) {
int len = (int )(sn->end - sn->s);
sn->s = sn->buf;
sn->end = sn->s + len;
}
}
}
static int
node_list_len(Node* list)
{
int len;
len = 1;
while (IS_NOT_NULL(NODE_CDR(list))) {
list = NODE_CDR(list);
len++;
}
return len;
}
static Node*
node_list_add(Node* list, Node* x)
{
Node *n;
n = onig_node_new_list(x, NULL);
if (IS_NULL(n)) return NULL_NODE;
if (IS_NOT_NULL(list)) {
while (IS_NOT_NULL(NODE_CDR(list)))
list = NODE_CDR(list);
NODE_CDR(list) = n;
}
return n;
}
static int
node_str_node_cat(Node* node, Node* add)
{
int r;
if (NODE_STATUS(node) != NODE_STATUS(add))
return ONIGERR_TYPE_BUG;
if (STR_(node)->flag != STR_(add)->flag)
return ONIGERR_TYPE_BUG;
r = onig_node_str_cat(node, STR_(add)->s, STR_(add)->end);
if (r != 0) return r;
return 0;
}
static void
node_conv_to_str_node(Node* node, Node* ref_node)
{
xmemset(node, 0, sizeof(*node));
NODE_SET_TYPE(node, NODE_STRING);
NODE_STATUS(node) = NODE_STATUS(ref_node);
STR_(node)->flag = STR_(ref_node)->flag;
STR_(node)->s = STR_(node)->buf;
STR_(node)->end = STR_(node)->buf;
STR_(node)->capacity = 0;
}
static OnigLen
distance_add(OnigLen d1, OnigLen d2)
{
if (d1 == INFINITE_LEN || d2 == INFINITE_LEN)
return INFINITE_LEN;
else {
if (d1 <= INFINITE_LEN - d2) return d1 + d2;
else return INFINITE_LEN;
}
}
static OnigLen
distance_multiply(OnigLen d, int m)
{
if (m == 0) return 0;
if (d < INFINITE_LEN / m)
return d * m;
else
return INFINITE_LEN;
}
static int
bitset_is_empty(BitSetRef bs)
{
int i;
for (i = 0; i < (int )BITSET_REAL_SIZE; i++) {
if (bs[i] != 0) return 0;
}
return 1;
}
#ifdef USE_CALL
static int
unset_addr_list_init(UnsetAddrList* list, int size)
{
UnsetAddr* p = (UnsetAddr* )xmalloc(sizeof(UnsetAddr)* size);
CHECK_NULL_RETURN_MEMERR(p);
list->num = 0;
list->alloc = size;
list->us = p;
return 0;
}
static void
unset_addr_list_end(UnsetAddrList* list)
{
if (IS_NOT_NULL(list->us))
xfree(list->us);
}
static int
unset_addr_list_add(UnsetAddrList* list, int offset, struct _Node* node)
{
UnsetAddr* p;
int size;
if (list->num >= list->alloc) {
size = list->alloc * 2;
p = (UnsetAddr* )xrealloc(list->us, sizeof(UnsetAddr) * size);
CHECK_NULL_RETURN_MEMERR(p);
list->alloc = size;
list->us = p;
}
list->us[list->num].offset = offset;
list->us[list->num].target = node;
list->num++;
return 0;
}
#endif /* USE_CALL */
enum CharLenReturnType {
CHAR_LEN_NORMAL = 0, /* fixed or variable */
CHAR_LEN_TOP_ALT_FIXED = 1
};
static int
mmcl_fixed(MinMaxCharLen* c)
{
return (c->min == c->max && c->min != INFINITE_LEN);
}
static void
mmcl_set(MinMaxCharLen* l, OnigLen len)
{
l->min = len;
l->max = len;
l->min_is_sure = TRUE;
}
static void
mmcl_set_min_max(MinMaxCharLen* l, OnigLen min, OnigLen max, int min_is_sure)
{
l->min = min;
l->max = max;
l->min_is_sure = min_is_sure;
}
static void
mmcl_add(MinMaxCharLen* to, MinMaxCharLen* add)
{
to->min = distance_add(to->min, add->min);
to->max = distance_add(to->max, add->max);
to->min_is_sure = add->min_is_sure != FALSE && to->min_is_sure != FALSE;
}
static void
mmcl_multiply(MinMaxCharLen* to, int m)
{
to->min = distance_multiply(to->min, m);
to->max = distance_multiply(to->max, m);
}
static void
mmcl_repeat_range_multiply(MinMaxCharLen* to, int mlow, int mhigh)
{
to->min = distance_multiply(to->min, mlow);
if (IS_INFINITE_REPEAT(mhigh))
to->max = INFINITE_LEN;
else
to->max = distance_multiply(to->max, mhigh);
}
static void
mmcl_alt_merge(MinMaxCharLen* to, MinMaxCharLen* alt)
{
if (to->min > alt->min) {
to->min = alt->min;
to->min_is_sure = alt->min_is_sure;
}
else if (to->min == alt->min) {
if (alt->min_is_sure != FALSE)
to->min_is_sure = TRUE;
}
if (to->max < alt->max) to->max = alt->max;
}
static int
mml_is_equal(MinMaxLen* a, MinMaxLen* b)
{
return a->min == b->min && a->max == b->max;
}
static void
mml_set_min_max(MinMaxLen* l, OnigLen min, OnigLen max)
{
l->min = min;
l->max = max;
}
static void
mml_clear(MinMaxLen* l)
{
l->min = l->max = 0;
}
static void
mml_copy(MinMaxLen* to, MinMaxLen* from)
{
to->min = from->min;
to->max = from->max;
}
static void
mml_add(MinMaxLen* to, MinMaxLen* add)
{
to->min = distance_add(to->min, add->min);
to->max = distance_add(to->max, add->max);
}
static void
mml_alt_merge(MinMaxLen* to, MinMaxLen* alt)
{
if (to->min > alt->min) to->min = alt->min;
if (to->max < alt->max) to->max = alt->max;
}
/* fixed size pattern node only */
static int
node_char_len1(Node* node, regex_t* reg, MinMaxCharLen* ci, ScanEnv* env,
int level)
{
MinMaxCharLen tci;
int r = CHAR_LEN_NORMAL;
level++;
switch (NODE_TYPE(node)) {
case NODE_LIST:
{
int first = TRUE;
do {
r = node_char_len1(NODE_CAR(node), reg, &tci, env, level);
if (r < 0) break;
if (first == TRUE) {
*ci = tci;
first = FALSE;
}
else
mmcl_add(ci, &tci);
} while (IS_NOT_NULL(node = NODE_CDR(node)));
}
break;
case NODE_ALT:
{
int fixed;
r = node_char_len1(NODE_CAR(node), reg, ci, env, level);
if (r < 0) break;
fixed = TRUE;
while (IS_NOT_NULL(node = NODE_CDR(node))) {
r = node_char_len1(NODE_CAR(node), reg, &tci, env, level);
if (r < 0) break;
if (! mmcl_fixed(&tci))
fixed = FALSE;
mmcl_alt_merge(ci, &tci);
}
if (r < 0) break;
r = CHAR_LEN_NORMAL;
if (mmcl_fixed(ci)) break;
if (fixed == TRUE && level == 1) {
r = CHAR_LEN_TOP_ALT_FIXED;
}
}
break;
case NODE_STRING:
{
OnigLen clen;
StrNode* sn = STR_(node);
UChar *s = sn->s;
if (NODE_IS_IGNORECASE(node) && ! NODE_STRING_IS_CRUDE(node)) {
/* Such a case is possible.
ex. /(?i)(?<=\1)(a)/
Backref node refer to capture group, but it doesn't tune yet.
*/
r = ONIGERR_INVALID_LOOK_BEHIND_PATTERN;
break;
}
clen = 0;
while (s < sn->end) {
s += enclen(reg->enc, s);
clen = distance_add(clen, 1);
}
mmcl_set(ci, clen);
}
break;
case NODE_QUANT:
{
QuantNode* qn = QUANT_(node);
if (qn->lower == qn->upper) {
if (qn->upper == 0) {
mmcl_set(ci, 0);
}
else {
r = node_char_len1(NODE_BODY(node), reg, ci, env, level);
if (r < 0) break;
mmcl_multiply(ci, qn->lower);
}
}
else {
r = node_char_len1(NODE_BODY(node), reg, ci, env, level);
if (r < 0) break;
mmcl_repeat_range_multiply(ci, qn->lower, qn->upper);
}
}
break;
#ifdef USE_CALL
case NODE_CALL:
if (NODE_IS_RECURSION(node))
mmcl_set_min_max(ci, 0, INFINITE_LEN, FALSE);
else
r = node_char_len1(NODE_BODY(node), reg, ci, env, level);
break;
#endif
case NODE_CTYPE:
case NODE_CCLASS:
mmcl_set(ci, 1);
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
switch (en->type) {
case BAG_MEMORY:
if (NODE_IS_FIXED_CLEN(node)) {
mmcl_set_min_max(ci, en->min_char_len, en->max_char_len,
NODE_IS_FIXED_CLEN_MIN_SURE(node));
}
else {
if (NODE_IS_MARK1(node)) {
mmcl_set_min_max(ci, 0, INFINITE_LEN, FALSE);
}
else {
NODE_STATUS_ADD(node, MARK1);
r = node_char_len1(NODE_BODY(node), reg, ci, env, level);
NODE_STATUS_REMOVE(node, MARK1);
if (r < 0) break;
en->min_char_len = ci->min;
en->max_char_len = ci->max;
NODE_STATUS_ADD(node, FIXED_CLEN);
if (ci->min_is_sure != FALSE)
NODE_STATUS_ADD(node, FIXED_CLEN_MIN_SURE);
}
}
/* can't optimize look-behind if capture exists. */
ci->min_is_sure = FALSE;
break;
case BAG_OPTION:
case BAG_STOP_BACKTRACK:
r = node_char_len1(NODE_BODY(node), reg, ci, env, level);
break;
case BAG_IF_ELSE:
{
MinMaxCharLen eci;
r = node_char_len1(NODE_BODY(node), reg, ci, env, level);
if (r < 0) break;
if (IS_NOT_NULL(en->te.Then)) {
r = node_char_len1(en->te.Then, reg, &tci, env, level);
if (r < 0) break;
mmcl_add(ci, &tci);
}
if (IS_NOT_NULL(en->te.Else)) {
r = node_char_len1(en->te.Else, reg, &eci, env, level);
if (r < 0) break;
}
else {
mmcl_set(&eci, 0);
}
mmcl_alt_merge(ci, &eci);
}
break;
default: /* never come here */
r = ONIGERR_PARSER_BUG;
break;
}
}
break;
case NODE_GIMMICK:
mmcl_set(ci, 0);
break;
case NODE_ANCHOR:
zero:
mmcl_set(ci, 0);
/* can't optimize look-behind if anchor exists. */
ci->min_is_sure = FALSE;
break;
case NODE_BACKREF:
if (NODE_IS_CHECKER(node))
goto zero;
if (NODE_IS_RECURSION(node)) {
#ifdef USE_BACKREF_WITH_LEVEL
if (NODE_IS_NEST_LEVEL(node)) {
mmcl_set_min_max(ci, 0, INFINITE_LEN, FALSE);
break;
}
#endif
mmcl_set_min_max(ci, 0, 0, FALSE);
break;
}
{
int i;
int* backs;
MemEnv* mem_env = SCANENV_MEMENV(env);
BackRefNode* br = BACKREF_(node);
backs = BACKREFS_P(br);
r = node_char_len1(mem_env[backs[0]].mem_node, reg, ci, env, level);
if (r < 0) break;
if (! mmcl_fixed(ci)) ci->min_is_sure = FALSE;
for (i = 1; i < br->back_num; i++) {
r = node_char_len1(mem_env[backs[i]].mem_node, reg, &tci, env, level);
if (r < 0) break;
if (! mmcl_fixed(&tci)) tci.min_is_sure = FALSE;
mmcl_alt_merge(ci, &tci);
}
}
break;
default: /* never come here */
r = ONIGERR_PARSER_BUG;
break;
}
return r;
}
static int
node_char_len(Node* node, regex_t* reg, MinMaxCharLen* ci, ScanEnv* env)
{
return node_char_len1(node, reg, ci, env, 0);
}
static int
add_op(regex_t* reg, int opcode)
{
int r;
r = ops_new(reg);
if (r != ONIG_NORMAL) return r;
#ifdef USE_DIRECT_THREADED_CODE
*(reg->ocs + (reg->ops_curr - reg->ops)) = opcode;
#else
reg->ops_curr->opcode = opcode;
#endif
return 0;
}
static int compile_length_tree(Node* node, regex_t* reg);
static int compile_tree(Node* node, regex_t* reg, ScanEnv* env);
#define IS_NEED_STR_LEN_OP(op) \
((op) == OP_STR_N || (op) == OP_STR_MB2N ||\
(op) == OP_STR_MB3N || (op) == OP_STR_MBN)
static int
select_str_opcode(int mb_len, int str_len)
{
int op;
switch (mb_len) {
case 1:
switch (str_len) {
case 1: op = OP_STR_1; break;
case 2: op = OP_STR_2; break;
case 3: op = OP_STR_3; break;
case 4: op = OP_STR_4; break;
case 5: op = OP_STR_5; break;
default: op = OP_STR_N; break;
}
break;
case 2:
switch (str_len) {
case 1: op = OP_STR_MB2N1; break;
case 2: op = OP_STR_MB2N2; break;
case 3: op = OP_STR_MB2N3; break;
default: op = OP_STR_MB2N; break;
}
break;
case 3:
op = OP_STR_MB3N;
break;
default:
op = OP_STR_MBN;
break;
}
return op;
}
static int
is_strict_real_node(Node* node)
{
switch (NODE_TYPE(node)) {
case NODE_STRING:
{
StrNode* sn = STR_(node);
return (sn->end != sn->s);
}
break;
case NODE_CCLASS:
case NODE_CTYPE:
return 1;
break;
default:
return 0;
break;
}
}
static int
compile_quant_body_with_empty_check(QuantNode* qn, regex_t* reg, ScanEnv* env)
{
int r;
int saved_num_empty_check;
int emptiness;
Node* body;
body = NODE_BODY((Node* )qn);
emptiness = qn->emptiness;
saved_num_empty_check = reg->num_empty_check;
if (emptiness != BODY_IS_NOT_EMPTY) {
r = add_op(reg, OP_EMPTY_CHECK_START);
if (r != 0) return r;
COP(reg)->empty_check_start.mem = reg->num_empty_check; /* NULL CHECK ID */
reg->num_empty_check++;
}
r = compile_tree(body, reg, env);
if (r != 0) return r;
if (emptiness != BODY_IS_NOT_EMPTY) {
if (emptiness == BODY_MAY_BE_EMPTY)
r = add_op(reg, OP_EMPTY_CHECK_END);
else if (emptiness == BODY_MAY_BE_EMPTY_MEM) {
if (NODE_IS_EMPTY_STATUS_CHECK(qn) != 0)
r = add_op(reg, OP_EMPTY_CHECK_END_MEMST);
else
r = add_op(reg, OP_EMPTY_CHECK_END);
}
#ifdef USE_CALL
else if (emptiness == BODY_MAY_BE_EMPTY_REC)
r = add_op(reg, OP_EMPTY_CHECK_END_MEMST_PUSH);
#endif
if (r != 0) return r;
COP(reg)->empty_check_end.mem = saved_num_empty_check; /* NULL CHECK ID */
}
return r;
}
#ifdef USE_CALL
static int
compile_call(CallNode* node, regex_t* reg, ScanEnv* env)
{
int r;
int offset;
r = add_op(reg, OP_CALL);
if (r != 0) return r;
COP(reg)->call.addr = 0; /* dummy addr. */
#ifdef ONIG_DEBUG_MATCH_COUNTER
COP(reg)->call.called_mem = node->called_gnum;
#endif
offset = COP_CURR_OFFSET_BYTES(reg, call.addr);
r = unset_addr_list_add(env->unset_addr_list, offset, NODE_CALL_BODY(node));
return r;
}
#endif
static int
compile_tree_n_times(Node* node, int n, regex_t* reg, ScanEnv* env)
{
int i, r;
for (i = 0; i < n; i++) {
r = compile_tree(node, reg, env);
if (r != 0) return r;
}
return 0;
}
static int
add_compile_string_length(UChar* s ARG_UNUSED, int mb_len, int str_len,
regex_t* reg ARG_UNUSED)
{
return 1;
}
static int
add_compile_string(UChar* s, int mb_len, int str_len, regex_t* reg)
{
int op;
int r;
int byte_len;
UChar* p;
UChar* end;
op = select_str_opcode(mb_len, str_len);
r = add_op(reg, op);
if (r != 0) return r;
byte_len = mb_len * str_len;
end = s + byte_len;
if (op == OP_STR_MBN) {
p = onigenc_strdup(reg->enc, s, end);
CHECK_NULL_RETURN_MEMERR(p);
COP(reg)->exact_len_n.len = mb_len;
COP(reg)->exact_len_n.n = str_len;
COP(reg)->exact_len_n.s = p;
}
else if (IS_NEED_STR_LEN_OP(op)) {
p = onigenc_strdup(reg->enc, s, end);
CHECK_NULL_RETURN_MEMERR(p);
COP(reg)->exact_n.n = str_len;
COP(reg)->exact_n.s = p;
}
else {
xmemset(COP(reg)->exact.s, 0, sizeof(COP(reg)->exact.s));
xmemcpy(COP(reg)->exact.s, s, (size_t )byte_len);
}
return 0;
}
static int
compile_length_string_node(Node* node, regex_t* reg)
{
int rlen, r, len, prev_len, slen;
UChar *p, *prev;
StrNode* sn;
OnigEncoding enc = reg->enc;
sn = STR_(node);
if (sn->end <= sn->s)
return 0;
p = prev = sn->s;
prev_len = enclen(enc, p);
p += prev_len;
slen = 1;
rlen = 0;
for (; p < sn->end; ) {
len = enclen(enc, p);
if (len == prev_len) {
slen++;
}
else {
r = add_compile_string_length(prev, prev_len, slen, reg);
rlen += r;
prev = p;
slen = 1;
prev_len = len;
}
p += len;
}
r = add_compile_string_length(prev, prev_len, slen, reg);
rlen += r;
return rlen;
}
static int
compile_length_string_crude_node(StrNode* sn, regex_t* reg)
{
if (sn->end <= sn->s)
return 0;
return add_compile_string_length(sn->s, 1 /* sb */, (int )(sn->end - sn->s),
reg);
}
static int
compile_string_node(Node* node, regex_t* reg)
{
int r, len, prev_len, slen;
UChar *p, *prev, *end;
StrNode* sn;
OnigEncoding enc = reg->enc;
sn = STR_(node);
if (sn->end <= sn->s)
return 0;
end = sn->end;
p = prev = sn->s;
prev_len = enclen(enc, p);
p += prev_len;
slen = 1;
for (; p < end; ) {
len = enclen(enc, p);
if (len == prev_len) {
slen++;
}
else {
r = add_compile_string(prev, prev_len, slen, reg);
if (r != 0) return r;
prev = p;
slen = 1;
prev_len = len;
}
p += len;
}
return add_compile_string(prev, prev_len, slen, reg);
}
static int
compile_string_crude_node(StrNode* sn, regex_t* reg)
{
if (sn->end <= sn->s)
return 0;
return add_compile_string(sn->s, 1 /* sb */, (int )(sn->end - sn->s), reg);
}
static void*
set_multi_byte_cclass(BBuf* mbuf, regex_t* reg)
{
size_t len;
void* p;
len = (size_t )mbuf->used;
p = xmalloc(len);
if (IS_NULL(p)) return NULL;
xmemcpy(p, mbuf->p, len);
return p;
}
static int
compile_length_cclass_node(CClassNode* cc, regex_t* reg)
{
return 1;
}
static int
compile_cclass_node(CClassNode* cc, regex_t* reg)
{
int r;
if (IS_NULL(cc->mbuf)) {
r = add_op(reg, IS_NCCLASS_NOT(cc) ? OP_CCLASS_NOT : OP_CCLASS);
if (r != 0) return r;
COP(reg)->cclass.bsp = xmalloc(SIZE_BITSET);
CHECK_NULL_RETURN_MEMERR(COP(reg)->cclass.bsp);
xmemcpy(COP(reg)->cclass.bsp, cc->bs, SIZE_BITSET);
}
else {
void* p;
if (ONIGENC_MBC_MINLEN(reg->enc) > 1 || bitset_is_empty(cc->bs)) {
r = add_op(reg, IS_NCCLASS_NOT(cc) ? OP_CCLASS_MB_NOT : OP_CCLASS_MB);
if (r != 0) return r;
p = set_multi_byte_cclass(cc->mbuf, reg);
CHECK_NULL_RETURN_MEMERR(p);
COP(reg)->cclass_mb.mb = p;
}
else {
r = add_op(reg, IS_NCCLASS_NOT(cc) ? OP_CCLASS_MIX_NOT : OP_CCLASS_MIX);
if (r != 0) return r;
COP(reg)->cclass_mix.bsp = xmalloc(SIZE_BITSET);
CHECK_NULL_RETURN_MEMERR(COP(reg)->cclass_mix.bsp);
xmemcpy(COP(reg)->cclass_mix.bsp, cc->bs, SIZE_BITSET);
p = set_multi_byte_cclass(cc->mbuf, reg);
CHECK_NULL_RETURN_MEMERR(p);
COP(reg)->cclass_mix.mb = p;
}
}
return 0;
}
static void
set_addr_in_repeat_range(regex_t* reg)
{
int i;
for (i = 0; i < reg->num_repeat; i++) {
RepeatRange* p = reg->repeat_range + i;
int offset = p->u.offset;
p->u.pcode = reg->ops + offset;
}
}
static int
entry_repeat_range(regex_t* reg, int id, int lower, int upper, int ops_index)
{
#define REPEAT_RANGE_ALLOC 4
RepeatRange* p;
if (reg->repeat_range_alloc == 0) {
p = (RepeatRange* )xmalloc(sizeof(RepeatRange) * REPEAT_RANGE_ALLOC);
CHECK_NULL_RETURN_MEMERR(p);
reg->repeat_range = p;
reg->repeat_range_alloc = REPEAT_RANGE_ALLOC;
}
else if (reg->repeat_range_alloc <= id) {
int n;
n = reg->repeat_range_alloc + REPEAT_RANGE_ALLOC;
p = (RepeatRange* )xrealloc(reg->repeat_range, sizeof(RepeatRange) * n);
CHECK_NULL_RETURN_MEMERR(p);
reg->repeat_range = p;
reg->repeat_range_alloc = n;
}
else {
p = reg->repeat_range;
}
p[id].lower = lower;
p[id].upper = (IS_INFINITE_REPEAT(upper) ? 0x7fffffff : upper);
p[id].u.offset = ops_index;
return 0;
}
static int
compile_range_repeat_node(QuantNode* qn, int target_len, int emptiness,
regex_t* reg, ScanEnv* env)
{
int r;
int num_repeat = reg->num_repeat++;
r = add_op(reg, qn->greedy ? OP_REPEAT : OP_REPEAT_NG);
if (r != 0) return r;
COP(reg)->repeat.id = num_repeat;
COP(reg)->repeat.addr = SIZE_INC + target_len + OPSIZE_REPEAT_INC;
r = entry_repeat_range(reg, num_repeat, qn->lower, qn->upper,
COP_CURR_OFFSET(reg) + OPSIZE_REPEAT);
if (r != 0) return r;
r = compile_quant_body_with_empty_check(qn, reg, env);
if (r != 0) return r;
r = add_op(reg, qn->greedy ? OP_REPEAT_INC : OP_REPEAT_INC_NG);
if (r != 0) return r;
COP(reg)->repeat_inc.id = num_repeat;
return r;
}
static int
is_anychar_infinite_greedy(QuantNode* qn)
{
if (qn->greedy && IS_INFINITE_REPEAT(qn->upper) &&
NODE_IS_ANYCHAR(NODE_QUANT_BODY(qn)))
return 1;
else
return 0;
}
#define QUANTIFIER_EXPAND_LIMIT_SIZE 10
#define CKN_ON (ckn > 0)
static int
compile_length_quantifier_node(QuantNode* qn, regex_t* reg)
{
int len, mod_tlen;
int infinite = IS_INFINITE_REPEAT(qn->upper);
enum BodyEmptyType emptiness = qn->emptiness;
int tlen = compile_length_tree(NODE_QUANT_BODY(qn), reg);
if (tlen < 0) return tlen;
if (tlen == 0) return 0;
/* anychar repeat */
if (is_anychar_infinite_greedy(qn)) {
if (qn->lower <= 1 ||
len_multiply_cmp((OnigLen )tlen, qn->lower, QUANTIFIER_EXPAND_LIMIT_SIZE) <= 0) {
if (IS_NOT_NULL(qn->next_head_exact))
return OPSIZE_ANYCHAR_STAR_PEEK_NEXT + tlen * qn->lower;
else
return OPSIZE_ANYCHAR_STAR + tlen * qn->lower;
}
}
mod_tlen = tlen;
if (emptiness != BODY_IS_NOT_EMPTY)
mod_tlen += OPSIZE_EMPTY_CHECK_START + OPSIZE_EMPTY_CHECK_END;
if (infinite &&
(qn->lower <= 1 ||
len_multiply_cmp(tlen, qn->lower, QUANTIFIER_EXPAND_LIMIT_SIZE) <= 0)) {
if (qn->lower == 1 && tlen > QUANTIFIER_EXPAND_LIMIT_SIZE) {
len = OPSIZE_JUMP;
}
else {
len = tlen * qn->lower;
}
if (qn->greedy) {
#ifdef USE_OP_PUSH_OR_JUMP_EXACT
if (IS_NOT_NULL(qn->head_exact))
len += OPSIZE_PUSH_OR_JUMP_EXACT1 + mod_tlen + OPSIZE_JUMP;
else
#endif
if (IS_NOT_NULL(qn->next_head_exact))
len += OPSIZE_PUSH_IF_PEEK_NEXT + mod_tlen + OPSIZE_JUMP;
else
len += OPSIZE_PUSH + mod_tlen + OPSIZE_JUMP;
}
else
len += OPSIZE_JUMP + mod_tlen + OPSIZE_PUSH;
}
else if (qn->upper == 0) {
if (qn->include_referred != 0) { /* /(?<n>..){0}/ */
len = OPSIZE_JUMP + tlen;
}
else
len = 0;
}
else if (!infinite && qn->greedy &&
(qn->upper == 1 ||
len_multiply_cmp((OnigLen )tlen + OPSIZE_PUSH, qn->upper,
QUANTIFIER_EXPAND_LIMIT_SIZE) <= 0)) {
len = tlen * qn->lower;
len += (OPSIZE_PUSH + tlen) * (qn->upper - qn->lower);
}
else if (!qn->greedy && qn->upper == 1 && qn->lower == 0) { /* '??' */
len = OPSIZE_PUSH + OPSIZE_JUMP + tlen;
}
else {
len = OPSIZE_REPEAT_INC + mod_tlen + OPSIZE_REPEAT;
}
return len;
}
static int
compile_quantifier_node(QuantNode* qn, regex_t* reg, ScanEnv* env)
{
int i, r, mod_tlen;
int infinite = IS_INFINITE_REPEAT(qn->upper);
enum BodyEmptyType emptiness = qn->emptiness;
int tlen = compile_length_tree(NODE_QUANT_BODY(qn), reg);
if (tlen < 0) return tlen;
if (tlen == 0) return 0;
if (is_anychar_infinite_greedy(qn) &&
(qn->lower <= 1 ||
len_multiply_cmp((OnigLen )tlen, qn->lower,
QUANTIFIER_EXPAND_LIMIT_SIZE) <= 0)) {
r = compile_tree_n_times(NODE_QUANT_BODY(qn), qn->lower, reg, env);
if (r != 0) return r;
if (IS_NOT_NULL(qn->next_head_exact)) {
r = add_op(reg, NODE_IS_MULTILINE(NODE_QUANT_BODY(qn)) ?
OP_ANYCHAR_ML_STAR_PEEK_NEXT : OP_ANYCHAR_STAR_PEEK_NEXT);
if (r != 0) return r;
COP(reg)->anychar_star_peek_next.c = STR_(qn->next_head_exact)->s[0];
return 0;
}
else {
r = add_op(reg, NODE_IS_MULTILINE(NODE_QUANT_BODY(qn)) ?
OP_ANYCHAR_ML_STAR : OP_ANYCHAR_STAR);
return r;
}
}
mod_tlen = tlen;
if (emptiness != BODY_IS_NOT_EMPTY)
mod_tlen += OPSIZE_EMPTY_CHECK_START + OPSIZE_EMPTY_CHECK_END;
if (infinite &&
(qn->lower <= 1 ||
len_multiply_cmp((OnigLen )tlen, qn->lower,
QUANTIFIER_EXPAND_LIMIT_SIZE) <= 0)) {
int addr;
if (qn->lower == 1 && tlen > QUANTIFIER_EXPAND_LIMIT_SIZE) {
r = add_op(reg, OP_JUMP);
if (r != 0) return r;
if (qn->greedy) {
#ifdef USE_OP_PUSH_OR_JUMP_EXACT
if (IS_NOT_NULL(qn->head_exact))
COP(reg)->jump.addr = OPSIZE_PUSH_OR_JUMP_EXACT1 + SIZE_INC;
else
#endif
if (IS_NOT_NULL(qn->next_head_exact))
COP(reg)->jump.addr = OPSIZE_PUSH_IF_PEEK_NEXT + SIZE_INC;
else
COP(reg)->jump.addr = OPSIZE_PUSH + SIZE_INC;
}
else {
COP(reg)->jump.addr = OPSIZE_JUMP + SIZE_INC;
}
}
else {
r = compile_tree_n_times(NODE_QUANT_BODY(qn), qn->lower, reg, env);
if (r != 0) return r;
}
if (qn->greedy) {
#ifdef USE_OP_PUSH_OR_JUMP_EXACT
if (IS_NOT_NULL(qn->head_exact)) {
r = add_op(reg, OP_PUSH_OR_JUMP_EXACT1);
if (r != 0) return r;
COP(reg)->push_or_jump_exact1.addr = SIZE_INC + mod_tlen + OPSIZE_JUMP;
COP(reg)->push_or_jump_exact1.c = STR_(qn->head_exact)->s[0];
r = compile_quant_body_with_empty_check(qn, reg, env);
if (r != 0) return r;
addr = -(mod_tlen + (int )OPSIZE_PUSH_OR_JUMP_EXACT1);
}
else
#endif
if (IS_NOT_NULL(qn->next_head_exact)) {
r = add_op(reg, OP_PUSH_IF_PEEK_NEXT);
if (r != 0) return r;
COP(reg)->push_if_peek_next.addr = SIZE_INC + mod_tlen + OPSIZE_JUMP;
COP(reg)->push_if_peek_next.c = STR_(qn->next_head_exact)->s[0];
r = compile_quant_body_with_empty_check(qn, reg, env);
if (r != 0) return r;
addr = -(mod_tlen + (int )OPSIZE_PUSH_IF_PEEK_NEXT);
}
else {
r = add_op(reg, OP_PUSH);
if (r != 0) return r;
COP(reg)->push.addr = SIZE_INC + mod_tlen + OPSIZE_JUMP;
r = compile_quant_body_with_empty_check(qn, reg, env);
if (r != 0) return r;
addr = -(mod_tlen + (int )OPSIZE_PUSH);
}
r = add_op(reg, OP_JUMP);
if (r != 0) return r;
COP(reg)->jump.addr = addr;
}
else {
r = add_op(reg, OP_JUMP);
if (r != 0) return r;
COP(reg)->jump.addr = mod_tlen + SIZE_INC;
r = compile_quant_body_with_empty_check(qn, reg, env);
if (r != 0) return r;
r = add_op(reg, OP_PUSH);
if (r != 0) return r;
COP(reg)->push.addr = -mod_tlen;
}
}
else if (qn->upper == 0) {
if (qn->include_referred != 0) { /* /(?<n>..){0}/ */
r = add_op(reg, OP_JUMP);
if (r != 0) return r;
COP(reg)->jump.addr = tlen + SIZE_INC;
r = compile_tree(NODE_QUANT_BODY(qn), reg, env);
}
else {
/* Nothing output */
r = 0;
}
}
else if (! infinite && qn->greedy &&
(qn->upper == 1 ||
len_multiply_cmp((OnigLen )tlen + OPSIZE_PUSH, qn->upper,
QUANTIFIER_EXPAND_LIMIT_SIZE) <= 0)) {
int n = qn->upper - qn->lower;
r = compile_tree_n_times(NODE_QUANT_BODY(qn), qn->lower, reg, env);
if (r != 0) return r;
for (i = 0; i < n; i++) {
int v = onig_positive_int_multiply(n - i, tlen + OPSIZE_PUSH);
if (v < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE;
r = add_op(reg, OP_PUSH);
if (r != 0) return r;
COP(reg)->push.addr = v;
r = compile_tree(NODE_QUANT_BODY(qn), reg, env);
if (r != 0) return r;
}
}
else if (! qn->greedy && qn->upper == 1 && qn->lower == 0) { /* '??' */
r = add_op(reg, OP_PUSH);
if (r != 0) return r;
COP(reg)->push.addr = SIZE_INC + OPSIZE_JUMP;
r = add_op(reg, OP_JUMP);
if (r != 0) return r;
COP(reg)->jump.addr = tlen + SIZE_INC;
r = compile_tree(NODE_QUANT_BODY(qn), reg, env);
}
else {
r = compile_range_repeat_node(qn, mod_tlen, emptiness, reg, env);
}
return r;
}
static int
compile_length_option_node(BagNode* node, regex_t* reg)
{
int tlen;
tlen = compile_length_tree(NODE_BAG_BODY(node), reg);
return tlen;
}
static int
compile_option_node(BagNode* node, regex_t* reg, ScanEnv* env)
{
int r;
r = compile_tree(NODE_BAG_BODY(node), reg, env);
return r;
}
static int
compile_length_bag_node(BagNode* node, regex_t* reg)
{
int len;
int tlen;
if (node->type == BAG_OPTION)
return compile_length_option_node(node, reg);
if (NODE_BAG_BODY(node)) {
tlen = compile_length_tree(NODE_BAG_BODY(node), reg);
if (tlen < 0) return tlen;
}
else
tlen = 0;
switch (node->type) {
case BAG_MEMORY:
#ifdef USE_CALL
if (node->m.regnum == 0 && NODE_IS_CALLED(node)) {
len = tlen + OPSIZE_CALL + OPSIZE_JUMP + OPSIZE_RETURN;
return len;
}
if (NODE_IS_CALLED(node)) {
len = OPSIZE_MEM_START_PUSH + tlen
+ OPSIZE_CALL + OPSIZE_JUMP + OPSIZE_RETURN;
if (MEM_STATUS_AT0(reg->push_mem_end, node->m.regnum))
len += (NODE_IS_RECURSION(node)
? OPSIZE_MEM_END_PUSH_REC : OPSIZE_MEM_END_PUSH);
else
len += (NODE_IS_RECURSION(node)
? OPSIZE_MEM_END_REC : OPSIZE_MEM_END);
}
else if (NODE_IS_RECURSION(node)) {
len = OPSIZE_MEM_START_PUSH;
len += tlen + (MEM_STATUS_AT0(reg->push_mem_end, node->m.regnum)
? OPSIZE_MEM_END_PUSH_REC : OPSIZE_MEM_END_REC);
}
else
#endif
{
if (MEM_STATUS_AT0(reg->push_mem_start, node->m.regnum))
len = OPSIZE_MEM_START_PUSH;
else
len = OPSIZE_MEM_START;
len += tlen + (MEM_STATUS_AT0(reg->push_mem_end, node->m.regnum)
? OPSIZE_MEM_END_PUSH : OPSIZE_MEM_END);
}
break;
case BAG_STOP_BACKTRACK:
if (NODE_IS_STRICT_REAL_REPEAT(node)) {
int v;
QuantNode* qn;
qn = QUANT_(NODE_BAG_BODY(node));
tlen = compile_length_tree(NODE_QUANT_BODY(qn), reg);
if (tlen < 0) return tlen;
v = onig_positive_int_multiply(qn->lower, tlen);
if (v < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE;
len = v + OPSIZE_PUSH + tlen + OPSIZE_POP + OPSIZE_JUMP;
}
else {
len = OPSIZE_MARK + tlen + OPSIZE_CUT_TO_MARK;
}
break;
case BAG_IF_ELSE:
{
Node* cond = NODE_BAG_BODY(node);
Node* Then = node->te.Then;
Node* Else = node->te.Else;
len = compile_length_tree(cond, reg);
if (len < 0) return len;
len += OPSIZE_PUSH + OPSIZE_MARK + OPSIZE_CUT_TO_MARK;
if (IS_NOT_NULL(Then)) {
tlen = compile_length_tree(Then, reg);
if (tlen < 0) return tlen;
len += tlen;
}
len += OPSIZE_JUMP + OPSIZE_CUT_TO_MARK;
if (IS_NOT_NULL(Else)) {
tlen = compile_length_tree(Else, reg);
if (tlen < 0) return tlen;
len += tlen;
}
}
break;
case BAG_OPTION:
/* never come here, but set for escape warning */
len = 0;
break;
}
return len;
}
static int
compile_bag_memory_node(BagNode* node, regex_t* reg, ScanEnv* env)
{
int r;
#ifdef USE_CALL
if (NODE_IS_CALLED(node)) {
int len;
r = add_op(reg, OP_CALL);
if (r != 0) return r;
node->m.called_addr = COP_CURR_OFFSET(reg) + 1 + OPSIZE_JUMP;
NODE_STATUS_ADD(node, FIXED_ADDR);
COP(reg)->call.addr = (int )node->m.called_addr;
if (node->m.regnum == 0) {
len = compile_length_tree(NODE_BAG_BODY(node), reg);
len += OPSIZE_RETURN;
r = add_op(reg, OP_JUMP);
if (r != 0) return r;
COP(reg)->jump.addr = len + SIZE_INC;
r = compile_tree(NODE_BAG_BODY(node), reg, env);
if (r != 0) return r;
r = add_op(reg, OP_RETURN);
return r;
}
else {
len = compile_length_tree(NODE_BAG_BODY(node), reg);
len += (OPSIZE_MEM_START_PUSH + OPSIZE_RETURN);
if (MEM_STATUS_AT0(reg->push_mem_end, node->m.regnum))
len += (NODE_IS_RECURSION(node)
? OPSIZE_MEM_END_PUSH_REC : OPSIZE_MEM_END_PUSH);
else
len += (NODE_IS_RECURSION(node) ? OPSIZE_MEM_END_REC : OPSIZE_MEM_END);
r = add_op(reg, OP_JUMP);
if (r != 0) return r;
COP(reg)->jump.addr = len + SIZE_INC;
}
}
#endif
if (MEM_STATUS_AT0(reg->push_mem_start, node->m.regnum))
r = add_op(reg, OP_MEM_START_PUSH);
else
r = add_op(reg, OP_MEM_START);
if (r != 0) return r;
COP(reg)->memory_start.num = node->m.regnum;
r = compile_tree(NODE_BAG_BODY(node), reg, env);
if (r != 0) return r;
#ifdef USE_CALL
if (MEM_STATUS_AT0(reg->push_mem_end, node->m.regnum))
r = add_op(reg, (NODE_IS_RECURSION(node)
? OP_MEM_END_PUSH_REC : OP_MEM_END_PUSH));
else
r = add_op(reg, (NODE_IS_RECURSION(node) ? OP_MEM_END_REC : OP_MEM_END));
if (r != 0) return r;
COP(reg)->memory_end.num = node->m.regnum;
if (NODE_IS_CALLED(node)) {
r = add_op(reg, OP_RETURN);
}
#else
if (MEM_STATUS_AT0(reg->push_mem_end, node->m.regnum))
r = add_op(reg, OP_MEM_END_PUSH);
else
r = add_op(reg, OP_MEM_END);
if (r != 0) return r;
COP(reg)->memory_end.num = node->m.regnum;
#endif
return r;
}
static int
compile_bag_node(BagNode* node, regex_t* reg, ScanEnv* env)
{
int r, len;
switch (node->type) {
case BAG_MEMORY:
r = compile_bag_memory_node(node, reg, env);
break;
case BAG_OPTION:
r = compile_option_node(node, reg, env);
break;
case BAG_STOP_BACKTRACK:
if (NODE_IS_STRICT_REAL_REPEAT(node)) {
QuantNode* qn = QUANT_(NODE_BAG_BODY(node));
r = compile_tree_n_times(NODE_QUANT_BODY(qn), qn->lower, reg, env);
if (r != 0) return r;
len = compile_length_tree(NODE_QUANT_BODY(qn), reg);
if (len < 0) return len;
r = add_op(reg, OP_PUSH);
if (r != 0) return r;
COP(reg)->push.addr = SIZE_INC + len + OPSIZE_POP + OPSIZE_JUMP;
r = compile_tree(NODE_QUANT_BODY(qn), reg, env);
if (r != 0) return r;
r = add_op(reg, OP_POP);
if (r != 0) return r;
r = add_op(reg, OP_JUMP);
if (r != 0) return r;
COP(reg)->jump.addr = -((int )OPSIZE_PUSH + len + (int )OPSIZE_POP);
}
else {
MemNumType mid;
ID_ENTRY(env, mid);
r = add_op(reg, OP_MARK);
if (r != 0) return r;
COP(reg)->mark.id = mid;
COP(reg)->mark.save_pos = 0;
r = compile_tree(NODE_BAG_BODY(node), reg, env);
if (r != 0) return r;
r = add_op(reg, OP_CUT_TO_MARK);
if (r != 0) return r;
COP(reg)->cut_to_mark.id = mid;
COP(reg)->cut_to_mark.restore_pos = 0;
}
break;
case BAG_IF_ELSE:
{
int cond_len, then_len, else_len, jump_len;
MemNumType mid;
Node* cond = NODE_BAG_BODY(node);
Node* Then = node->te.Then;
Node* Else = node->te.Else;
ID_ENTRY(env, mid);
r = add_op(reg, OP_MARK);
if (r != 0) return r;
COP(reg)->mark.id = mid;
COP(reg)->mark.save_pos = 0;
cond_len = compile_length_tree(cond, reg);
if (cond_len < 0) return cond_len;
if (IS_NOT_NULL(Then)) {
then_len = compile_length_tree(Then, reg);
if (then_len < 0) return then_len;
}
else
then_len = 0;
jump_len = cond_len + then_len + OPSIZE_CUT_TO_MARK + OPSIZE_JUMP;
r = add_op(reg, OP_PUSH);
if (r != 0) return r;
COP(reg)->push.addr = SIZE_INC + jump_len;
r = compile_tree(cond, reg, env);
if (r != 0) return r;
r = add_op(reg, OP_CUT_TO_MARK);
if (r != 0) return r;
COP(reg)->cut_to_mark.id = mid;
COP(reg)->cut_to_mark.restore_pos = 0;
if (IS_NOT_NULL(Then)) {
r = compile_tree(Then, reg, env);
if (r != 0) return r;
}
if (IS_NOT_NULL(Else)) {
else_len = compile_length_tree(Else, reg);
if (else_len < 0) return else_len;
}
else
else_len = 0;
r = add_op(reg, OP_JUMP);
if (r != 0) return r;
COP(reg)->jump.addr = OPSIZE_CUT_TO_MARK + else_len + SIZE_INC;
r = add_op(reg, OP_CUT_TO_MARK);
if (r != 0) return r;
COP(reg)->cut_to_mark.id = mid;
COP(reg)->cut_to_mark.restore_pos = 0;
if (IS_NOT_NULL(Else)) {
r = compile_tree(Else, reg, env);
}
}
break;
}
return r;
}
static int
compile_length_anchor_node(AnchorNode* node, regex_t* reg)
{
int len;
int tlen = 0;
if (IS_NOT_NULL(NODE_ANCHOR_BODY(node))) {
tlen = compile_length_tree(NODE_ANCHOR_BODY(node), reg);
if (tlen < 0) return tlen;
}
switch (node->type) {
case ANCR_PREC_READ:
len = OPSIZE_MARK + tlen + OPSIZE_CUT_TO_MARK;
break;
case ANCR_PREC_READ_NOT:
len = OPSIZE_PUSH + OPSIZE_MARK + tlen + OPSIZE_POP_TO_MARK + OPSIZE_POP + OPSIZE_FAIL;
break;
case ANCR_LOOK_BEHIND:
if (node->char_min_len == node->char_max_len)
len = OPSIZE_MARK + OPSIZE_STEP_BACK_START + tlen + OPSIZE_CUT_TO_MARK;
else {
len = OPSIZE_SAVE_VAL + OPSIZE_UPDATE_VAR + OPSIZE_MARK + OPSIZE_PUSH + OPSIZE_UPDATE_VAR + OPSIZE_FAIL + OPSIZE_JUMP + OPSIZE_STEP_BACK_START + OPSIZE_STEP_BACK_NEXT + tlen + OPSIZE_CHECK_POSITION + OPSIZE_CUT_TO_MARK + OPSIZE_UPDATE_VAR;
if (IS_NOT_NULL(node->lead_node)) {
int llen = compile_length_tree(node->lead_node, reg);
if (llen < 0) return llen;
len += OPSIZE_MOVE + llen;
}
}
break;
case ANCR_LOOK_BEHIND_NOT:
if (node->char_min_len == node->char_max_len)
len = OPSIZE_MARK + OPSIZE_PUSH + OPSIZE_STEP_BACK_START + tlen + OPSIZE_POP_TO_MARK + OPSIZE_FAIL + OPSIZE_POP;
else {
len = OPSIZE_SAVE_VAL + OPSIZE_UPDATE_VAR + OPSIZE_MARK + OPSIZE_PUSH + OPSIZE_STEP_BACK_START + OPSIZE_STEP_BACK_NEXT + tlen + OPSIZE_CHECK_POSITION + OPSIZE_POP_TO_MARK + OPSIZE_UPDATE_VAR + OPSIZE_POP + OPSIZE_FAIL + OPSIZE_UPDATE_VAR + OPSIZE_POP + OPSIZE_POP;
if (IS_NOT_NULL(node->lead_node)) {
int llen = compile_length_tree(node->lead_node, reg);
if (llen < 0) return llen;
len += OPSIZE_MOVE + llen;
}
}
break;
case ANCR_WORD_BOUNDARY:
case ANCR_NO_WORD_BOUNDARY:
#ifdef USE_WORD_BEGIN_END
case ANCR_WORD_BEGIN:
case ANCR_WORD_END:
#endif
len = OPSIZE_WORD_BOUNDARY;
break;
case ANCR_TEXT_SEGMENT_BOUNDARY:
case ANCR_NO_TEXT_SEGMENT_BOUNDARY:
len = SIZE_OPCODE;
break;
default:
len = SIZE_OPCODE;
break;
}
return len;
}
static int
compile_anchor_look_behind_node(AnchorNode* node, regex_t* reg, ScanEnv* env)
{
int r;
if (node->char_min_len == node->char_max_len) {
MemNumType mid;
ID_ENTRY(env, mid);
r = add_op(reg, OP_MARK);
if (r != 0) return r;
COP(reg)->mark.id = mid;
COP(reg)->mark.save_pos = FALSE;
r = add_op(reg, OP_STEP_BACK_START);
if (r != 0) return r;
COP(reg)->step_back_start.initial = node->char_min_len;
COP(reg)->step_back_start.remaining = 0;
COP(reg)->step_back_start.addr = 1;
r = compile_tree(NODE_ANCHOR_BODY(node), reg, env);
if (r != 0) return r;
r = add_op(reg, OP_CUT_TO_MARK);
if (r != 0) return r;
COP(reg)->cut_to_mark.id = mid;
COP(reg)->cut_to_mark.restore_pos = FALSE;
}
else {
MemNumType mid1, mid2;
OnigLen diff;
if (IS_NOT_NULL(node->lead_node)) {
MinMaxCharLen ci;
r = node_char_len(node->lead_node, reg, &ci, env);
if (r < 0) return r;
r = add_op(reg, OP_MOVE);
if (r != 0) return r;
COP(reg)->move.n = -((RelPositionType )ci.min);
r = compile_tree(node->lead_node, reg, env);
if (r != 0) return r;
}
ID_ENTRY(env, mid1);
r = add_op(reg, OP_SAVE_VAL);
if (r != 0) return r;
COP(reg)->save_val.type = SAVE_RIGHT_RANGE;
COP(reg)->save_val.id = mid1;
r = add_op(reg, OP_UPDATE_VAR);
if (r != 0) return r;
COP(reg)->update_var.type = UPDATE_VAR_RIGHT_RANGE_TO_S;
ID_ENTRY(env, mid2);
r = add_op(reg, OP_MARK);
if (r != 0) return r;
COP(reg)->mark.id = mid2;
COP(reg)->mark.save_pos = FALSE;
r = add_op(reg, OP_PUSH);
if (r != 0) return r;
COP(reg)->push.addr = SIZE_INC + OPSIZE_JUMP;
r = add_op(reg, OP_JUMP);
if (r != 0) return r;
COP(reg)->jump.addr = SIZE_INC + OPSIZE_UPDATE_VAR + OPSIZE_FAIL;
r = add_op(reg, OP_UPDATE_VAR);
if (r != 0) return r;
COP(reg)->update_var.type = UPDATE_VAR_RIGHT_RANGE_FROM_STACK;
COP(reg)->update_var.id = mid1;
COP(reg)->update_var.clear = FALSE;
r = add_op(reg, OP_FAIL);
if (r != 0) return r;
r = add_op(reg, OP_STEP_BACK_START);
if (r != 0) return r;
if (node->char_max_len != INFINITE_LEN)
diff = node->char_max_len - node->char_min_len;
else
diff = INFINITE_LEN;
COP(reg)->step_back_start.initial = node->char_min_len;
COP(reg)->step_back_start.remaining = diff;
COP(reg)->step_back_start.addr = 2;
r = add_op(reg, OP_STEP_BACK_NEXT);
if (r != 0) return r;
r = compile_tree(NODE_ANCHOR_BODY(node), reg, env);
if (r != 0) return r;
r = add_op(reg, OP_CHECK_POSITION);
if (r != 0) return r;
COP(reg)->check_position.type = CHECK_POSITION_CURRENT_RIGHT_RANGE;
r = add_op(reg, OP_CUT_TO_MARK);
if (r != 0) return r;
COP(reg)->cut_to_mark.id = mid2;
COP(reg)->cut_to_mark.restore_pos = FALSE;
r = add_op(reg, OP_UPDATE_VAR);
if (r != 0) return r;
COP(reg)->update_var.type = UPDATE_VAR_RIGHT_RANGE_FROM_STACK;
COP(reg)->update_var.id = mid1;
COP(reg)->update_var.clear = TRUE;
}
return r;
}
static int
compile_anchor_look_behind_not_node(AnchorNode* node, regex_t* reg,
ScanEnv* env)
{
int r;
int len;
len = compile_length_tree(NODE_ANCHOR_BODY(node), reg);
if (node->char_min_len == node->char_max_len) {
MemNumType mid;
ID_ENTRY(env, mid);
r = add_op(reg, OP_MARK);
if (r != 0) return r;
COP(reg)->mark.id = mid;
COP(reg)->mark.save_pos = FALSE;
r = add_op(reg, OP_PUSH);
if (r != 0) return r;
COP(reg)->push.addr = SIZE_INC + OPSIZE_STEP_BACK_START + len + OPSIZE_POP_TO_MARK + OPSIZE_FAIL;
r = add_op(reg, OP_STEP_BACK_START);
if (r != 0) return r;
COP(reg)->step_back_start.initial = node->char_min_len;
COP(reg)->step_back_start.remaining = 0;
COP(reg)->step_back_start.addr = 1;
r = compile_tree(NODE_ANCHOR_BODY(node), reg, env);
if (r != 0) return r;
r = add_op(reg, OP_POP_TO_MARK);
if (r != 0) return r;
COP(reg)->pop_to_mark.id = mid;
r = add_op(reg, OP_FAIL);
if (r != 0) return r;
r = add_op(reg, OP_POP);
}
else {
MemNumType mid1, mid2;
OnigLen diff;
ID_ENTRY(env, mid1);
r = add_op(reg, OP_SAVE_VAL);
if (r != 0) return r;
COP(reg)->save_val.type = SAVE_RIGHT_RANGE;
COP(reg)->save_val.id = mid1;
r = add_op(reg, OP_UPDATE_VAR);
if (r != 0) return r;
COP(reg)->update_var.type = UPDATE_VAR_RIGHT_RANGE_TO_S;
ID_ENTRY(env, mid2);
r = add_op(reg, OP_MARK);
if (r != 0) return r;
COP(reg)->mark.id = mid2;
COP(reg)->mark.save_pos = FALSE;
r = add_op(reg, OP_PUSH);
if (r != 0) return r;
COP(reg)->push.addr = SIZE_INC + OPSIZE_STEP_BACK_START + OPSIZE_STEP_BACK_NEXT + len + OPSIZE_CHECK_POSITION + OPSIZE_POP_TO_MARK + OPSIZE_UPDATE_VAR + OPSIZE_POP + OPSIZE_FAIL;
if (IS_NOT_NULL(node->lead_node)) {
int clen;
MinMaxCharLen ci;
clen = compile_length_tree(node->lead_node, reg);
COP(reg)->push.addr += OPSIZE_MOVE + clen;
r = node_char_len(node->lead_node, reg, &ci, env);
if (r < 0) return r;
r = add_op(reg, OP_MOVE);
if (r != 0) return r;
COP(reg)->move.n = -((RelPositionType )ci.min);
r = compile_tree(node->lead_node, reg, env);
if (r != 0) return r;
}
r = add_op(reg, OP_STEP_BACK_START);
if (r != 0) return r;
if (node->char_max_len != INFINITE_LEN)
diff = node->char_max_len - node->char_min_len;
else
diff = INFINITE_LEN;
COP(reg)->step_back_start.initial = node->char_min_len;
COP(reg)->step_back_start.remaining = diff;
COP(reg)->step_back_start.addr = 2;
r = add_op(reg, OP_STEP_BACK_NEXT);
if (r != 0) return r;
r = compile_tree(NODE_ANCHOR_BODY(node), reg, env);
if (r != 0) return r;
r = add_op(reg, OP_CHECK_POSITION);
if (r != 0) return r;
COP(reg)->check_position.type = CHECK_POSITION_CURRENT_RIGHT_RANGE;
r = add_op(reg, OP_POP_TO_MARK);
if (r != 0) return r;
COP(reg)->pop_to_mark.id = mid2;
r = add_op(reg, OP_UPDATE_VAR);
if (r != 0) return r;
COP(reg)->update_var.type = UPDATE_VAR_RIGHT_RANGE_FROM_STACK;
COP(reg)->update_var.id = mid1;
COP(reg)->update_var.clear = FALSE;
r = add_op(reg, OP_POP); /* pop save val */
if (r != 0) return r;
r = add_op(reg, OP_FAIL);
if (r != 0) return r;
r = add_op(reg, OP_UPDATE_VAR);
if (r != 0) return r;
COP(reg)->update_var.type = UPDATE_VAR_RIGHT_RANGE_FROM_STACK;
COP(reg)->update_var.id = mid1;
COP(reg)->update_var.clear = FALSE;
r = add_op(reg, OP_POP); /* pop mark */
if (r != 0) return r;
r = add_op(reg, OP_POP); /* pop save val */
}
return r;
}
static int
compile_anchor_node(AnchorNode* node, regex_t* reg, ScanEnv* env)
{
int r, len;
enum OpCode op;
MemNumType mid;
switch (node->type) {
case ANCR_BEGIN_BUF: r = add_op(reg, OP_BEGIN_BUF); break;
case ANCR_END_BUF: r = add_op(reg, OP_END_BUF); break;
case ANCR_BEGIN_LINE: r = add_op(reg, OP_BEGIN_LINE); break;
case ANCR_END_LINE: r = add_op(reg, OP_END_LINE); break;
case ANCR_SEMI_END_BUF: r = add_op(reg, OP_SEMI_END_BUF); break;
case ANCR_BEGIN_POSITION:
r = add_op(reg, OP_CHECK_POSITION);
if (r != 0) return r;
COP(reg)->check_position.type = CHECK_POSITION_SEARCH_START;
break;
case ANCR_WORD_BOUNDARY:
op = OP_WORD_BOUNDARY;
word:
r = add_op(reg, op);
if (r != 0) return r;
COP(reg)->word_boundary.mode = (ModeType )node->ascii_mode;
break;
case ANCR_NO_WORD_BOUNDARY:
op = OP_NO_WORD_BOUNDARY; goto word;
break;
#ifdef USE_WORD_BEGIN_END
case ANCR_WORD_BEGIN:
op = OP_WORD_BEGIN; goto word;
break;
case ANCR_WORD_END:
op = OP_WORD_END; goto word;
break;
#endif
case ANCR_TEXT_SEGMENT_BOUNDARY:
case ANCR_NO_TEXT_SEGMENT_BOUNDARY:
{
enum TextSegmentBoundaryType type;
r = add_op(reg, OP_TEXT_SEGMENT_BOUNDARY);
if (r != 0) return r;
type = EXTENDED_GRAPHEME_CLUSTER_BOUNDARY;
#ifdef USE_UNICODE_WORD_BREAK
if (NODE_IS_TEXT_SEGMENT_WORD(node))
type = WORD_BOUNDARY;
#endif
COP(reg)->text_segment_boundary.type = type;
COP(reg)->text_segment_boundary.not =
(node->type == ANCR_NO_TEXT_SEGMENT_BOUNDARY ? 1 : 0);
}
break;
case ANCR_PREC_READ:
{
ID_ENTRY(env, mid);
r = add_op(reg, OP_MARK);
if (r != 0) return r;
COP(reg)->mark.id = mid;
COP(reg)->mark.save_pos = TRUE;
r = compile_tree(NODE_ANCHOR_BODY(node), reg, env);
if (r != 0) return r;
r = add_op(reg, OP_CUT_TO_MARK);
if (r != 0) return r;
COP(reg)->cut_to_mark.id = mid;
COP(reg)->cut_to_mark.restore_pos = TRUE;
}
break;
case ANCR_PREC_READ_NOT:
{
len = compile_length_tree(NODE_ANCHOR_BODY(node), reg);
if (len < 0) return len;
ID_ENTRY(env, mid);
r = add_op(reg, OP_PUSH);
if (r != 0) return r;
COP(reg)->push.addr = SIZE_INC + OPSIZE_MARK + len +
OPSIZE_POP_TO_MARK + OPSIZE_POP + OPSIZE_FAIL;
r = add_op(reg, OP_MARK);
if (r != 0) return r;
COP(reg)->mark.id = mid;
COP(reg)->mark.save_pos = FALSE;
r = compile_tree(NODE_ANCHOR_BODY(node), reg, env);
if (r != 0) return r;
r = add_op(reg, OP_POP_TO_MARK);
if (r != 0) return r;
COP(reg)->pop_to_mark.id = mid;
r = add_op(reg, OP_POP);
if (r != 0) return r;
r = add_op(reg, OP_FAIL);
}
break;
case ANCR_LOOK_BEHIND:
r = compile_anchor_look_behind_node(node, reg, env);
break;
case ANCR_LOOK_BEHIND_NOT:
r = compile_anchor_look_behind_not_node(node, reg, env);
break;
default:
return ONIGERR_TYPE_BUG;
break;
}
return r;
}
static int
compile_gimmick_node(GimmickNode* node, regex_t* reg)
{
int r = 0;
switch (node->type) {
case GIMMICK_FAIL:
r = add_op(reg, OP_FAIL);
break;
case GIMMICK_SAVE:
r = add_op(reg, OP_SAVE_VAL);
if (r != 0) return r;
COP(reg)->save_val.type = node->detail_type;
COP(reg)->save_val.id = node->id;
break;
case GIMMICK_UPDATE_VAR:
r = add_op(reg, OP_UPDATE_VAR);
if (r != 0) return r;
COP(reg)->update_var.type = node->detail_type;
COP(reg)->update_var.id = node->id;
COP(reg)->update_var.clear = FALSE;
break;
#ifdef USE_CALLOUT
case GIMMICK_CALLOUT:
switch (node->detail_type) {
case ONIG_CALLOUT_OF_CONTENTS:
case ONIG_CALLOUT_OF_NAME:
{
if (node->detail_type == ONIG_CALLOUT_OF_NAME) {
r = add_op(reg, OP_CALLOUT_NAME);
if (r != 0) return r;
COP(reg)->callout_name.id = node->id;
COP(reg)->callout_name.num = node->num;
}
else {
r = add_op(reg, OP_CALLOUT_CONTENTS);
if (r != 0) return r;
COP(reg)->callout_contents.num = node->num;
}
}
break;
default:
r = ONIGERR_TYPE_BUG;
break;
}
#endif
}
return r;
}
static int
compile_length_gimmick_node(GimmickNode* node, regex_t* reg)
{
int len;
switch (node->type) {
case GIMMICK_FAIL:
len = OPSIZE_FAIL;
break;
case GIMMICK_SAVE:
len = OPSIZE_SAVE_VAL;
break;
case GIMMICK_UPDATE_VAR:
len = OPSIZE_UPDATE_VAR;
break;
#ifdef USE_CALLOUT
case GIMMICK_CALLOUT:
switch (node->detail_type) {
case ONIG_CALLOUT_OF_CONTENTS:
len = OPSIZE_CALLOUT_CONTENTS;
break;
case ONIG_CALLOUT_OF_NAME:
len = OPSIZE_CALLOUT_NAME;
break;
default:
len = ONIGERR_TYPE_BUG;
break;
}
break;
#endif
}
return len;
}
static int
compile_length_tree(Node* node, regex_t* reg)
{
int len, r;
switch (NODE_TYPE(node)) {
case NODE_LIST:
len = 0;
do {
r = compile_length_tree(NODE_CAR(node), reg);
if (r < 0) return r;
len += r;
} while (IS_NOT_NULL(node = NODE_CDR(node)));
r = len;
break;
case NODE_ALT:
{
int n;
n = r = 0;
do {
r += compile_length_tree(NODE_CAR(node), reg);
n++;
} while (IS_NOT_NULL(node = NODE_CDR(node)));
r += (OPSIZE_PUSH + OPSIZE_JUMP) * (n - 1);
}
break;
case NODE_STRING:
if (NODE_STRING_IS_CRUDE(node))
r = compile_length_string_crude_node(STR_(node), reg);
else
r = compile_length_string_node(node, reg);
break;
case NODE_CCLASS:
r = compile_length_cclass_node(CCLASS_(node), reg);
break;
case NODE_CTYPE:
r = SIZE_OPCODE;
break;
case NODE_BACKREF:
r = OPSIZE_BACKREF;
break;
#ifdef USE_CALL
case NODE_CALL:
r = OPSIZE_CALL;
break;
#endif
case NODE_QUANT:
r = compile_length_quantifier_node(QUANT_(node), reg);
break;
case NODE_BAG:
r = compile_length_bag_node(BAG_(node), reg);
break;
case NODE_ANCHOR:
r = compile_length_anchor_node(ANCHOR_(node), reg);
break;
case NODE_GIMMICK:
r = compile_length_gimmick_node(GIMMICK_(node), reg);
break;
default:
return ONIGERR_TYPE_BUG;
break;
}
return r;
}
static int
compile_tree(Node* node, regex_t* reg, ScanEnv* env)
{
int n, len, pos, r = 0;
switch (NODE_TYPE(node)) {
case NODE_LIST:
do {
r = compile_tree(NODE_CAR(node), reg, env);
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_ALT:
{
Node* x = node;
len = 0;
do {
len += compile_length_tree(NODE_CAR(x), reg);
if (IS_NOT_NULL(NODE_CDR(x))) {
len += OPSIZE_PUSH + OPSIZE_JUMP;
}
} while (IS_NOT_NULL(x = NODE_CDR(x)));
pos = COP_CURR_OFFSET(reg) + 1 + len; /* goal position */
do {
len = compile_length_tree(NODE_CAR(node), reg);
if (IS_NOT_NULL(NODE_CDR(node))) {
enum OpCode push = NODE_IS_SUPER(node) ? OP_PUSH_SUPER : OP_PUSH;
r = add_op(reg, push);
if (r != 0) break;
COP(reg)->push.addr = SIZE_INC + len + OPSIZE_JUMP;
}
r = compile_tree(NODE_CAR(node), reg, env);
if (r != 0) break;
if (IS_NOT_NULL(NODE_CDR(node))) {
len = pos - (COP_CURR_OFFSET(reg) + 1);
r = add_op(reg, OP_JUMP);
if (r != 0) break;
COP(reg)->jump.addr = len;
}
} while (IS_NOT_NULL(node = NODE_CDR(node)));
}
break;
case NODE_STRING:
if (NODE_STRING_IS_CRUDE(node))
r = compile_string_crude_node(STR_(node), reg);
else
r = compile_string_node(node, reg);
break;
case NODE_CCLASS:
r = compile_cclass_node(CCLASS_(node), reg);
break;
case NODE_CTYPE:
{
int op;
switch (CTYPE_(node)->ctype) {
case CTYPE_ANYCHAR:
r = add_op(reg, NODE_IS_MULTILINE(node) ? OP_ANYCHAR_ML : OP_ANYCHAR);
break;
case ONIGENC_CTYPE_WORD:
if (CTYPE_(node)->ascii_mode == 0) {
op = CTYPE_(node)->not != 0 ? OP_NO_WORD : OP_WORD;
}
else {
op = CTYPE_(node)->not != 0 ? OP_NO_WORD_ASCII : OP_WORD_ASCII;
}
r = add_op(reg, op);
break;
default:
return ONIGERR_TYPE_BUG;
break;
}
}
break;
case NODE_BACKREF:
{
BackRefNode* br = BACKREF_(node);
if (NODE_IS_CHECKER(node)) {
#ifdef USE_BACKREF_WITH_LEVEL
if (NODE_IS_NEST_LEVEL(node)) {
r = add_op(reg, OP_BACKREF_CHECK_WITH_LEVEL);
if (r != 0) return r;
COP(reg)->backref_general.nest_level = br->nest_level;
}
else
#endif
{
r = add_op(reg, OP_BACKREF_CHECK);
if (r != 0) return r;
}
goto add_bacref_mems;
}
else {
#ifdef USE_BACKREF_WITH_LEVEL
if (NODE_IS_NEST_LEVEL(node)) {
if (NODE_IS_IGNORECASE(node))
r = add_op(reg, OP_BACKREF_WITH_LEVEL_IC);
else
r = add_op(reg, OP_BACKREF_WITH_LEVEL);
if (r != 0) return r;
COP(reg)->backref_general.nest_level = br->nest_level;
goto add_bacref_mems;
}
else
#endif
if (br->back_num == 1) {
n = br->back_static[0];
if (NODE_IS_IGNORECASE(node)) {
r = add_op(reg, OP_BACKREF_N_IC);
if (r != 0) return r;
COP(reg)->backref_n.n1 = n;
}
else {
switch (n) {
case 1: r = add_op(reg, OP_BACKREF1); break;
case 2: r = add_op(reg, OP_BACKREF2); break;
default:
r = add_op(reg, OP_BACKREF_N);
if (r != 0) return r;
COP(reg)->backref_n.n1 = n;
break;
}
}
}
else {
int num;
int* p;
r = add_op(reg, NODE_IS_IGNORECASE(node) ?
OP_BACKREF_MULTI_IC : OP_BACKREF_MULTI);
if (r != 0) return r;
add_bacref_mems:
num = br->back_num;
COP(reg)->backref_general.num = num;
if (num == 1) {
COP(reg)->backref_general.n1 = br->back_static[0];
}
else {
int i, j;
MemNumType* ns;
ns = xmalloc(sizeof(MemNumType) * num);
CHECK_NULL_RETURN_MEMERR(ns);
COP(reg)->backref_general.ns = ns;
p = BACKREFS_P(br);
for (i = num - 1, j = 0; i >= 0; i--, j++) {
ns[j] = p[i];
}
}
}
}
}
break;
#ifdef USE_CALL
case NODE_CALL:
r = compile_call(CALL_(node), reg, env);
break;
#endif
case NODE_QUANT:
r = compile_quantifier_node(QUANT_(node), reg, env);
break;
case NODE_BAG:
r = compile_bag_node(BAG_(node), reg, env);
break;
case NODE_ANCHOR:
r = compile_anchor_node(ANCHOR_(node), reg, env);
break;
case NODE_GIMMICK:
r = compile_gimmick_node(GIMMICK_(node), reg);
break;
default:
#ifdef ONIG_DEBUG
fprintf(DBGFP, "compile_tree: undefined node type %d\n", NODE_TYPE(node));
#endif
break;
}
return r;
}
static int
make_named_capture_number_map(Node** plink, GroupNumMap* map, int* counter)
{
int r = 0;
Node* node = *plink;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
do {
r = make_named_capture_number_map(&(NODE_CAR(node)), map, counter);
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_QUANT:
{
Node** ptarget = &(NODE_BODY(node));
Node* old = *ptarget;
r = make_named_capture_number_map(ptarget, map, counter);
if (r != 0) return r;
if (*ptarget != old && NODE_TYPE(*ptarget) == NODE_QUANT) {
r = onig_reduce_nested_quantifier(node);
}
}
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
if (en->type == BAG_MEMORY) {
if (NODE_IS_NAMED_GROUP(node)) {
(*counter)++;
map[en->m.regnum].new_val = *counter;
en->m.regnum = *counter;
r = make_named_capture_number_map(&(NODE_BODY(node)), map, counter);
}
else {
*plink = NODE_BODY(node);
NODE_BODY(node) = NULL_NODE;
onig_node_free(node);
r = make_named_capture_number_map(plink, map, counter);
}
}
else if (en->type == BAG_IF_ELSE) {
r = make_named_capture_number_map(&(NODE_BAG_BODY(en)), map, counter);
if (r != 0) return r;
if (IS_NOT_NULL(en->te.Then)) {
r = make_named_capture_number_map(&(en->te.Then), map, counter);
if (r != 0) return r;
}
if (IS_NOT_NULL(en->te.Else)) {
r = make_named_capture_number_map(&(en->te.Else), map, counter);
if (r != 0) return r;
}
}
else
r = make_named_capture_number_map(&(NODE_BODY(node)), map, counter);
}
break;
case NODE_ANCHOR:
if (IS_NOT_NULL(NODE_BODY(node)))
r = make_named_capture_number_map(&(NODE_BODY(node)), map, counter);
break;
default:
break;
}
return r;
}
static int
renumber_backref_node(Node* node, GroupNumMap* map)
{
int i, pos, n, old_num;
int *backs;
BackRefNode* bn = BACKREF_(node);
if (! NODE_IS_BY_NAME(node))
return ONIGERR_NUMBERED_BACKREF_OR_CALL_NOT_ALLOWED;
old_num = bn->back_num;
if (IS_NULL(bn->back_dynamic))
backs = bn->back_static;
else
backs = bn->back_dynamic;
for (i = 0, pos = 0; i < old_num; i++) {
n = map[backs[i]].new_val;
if (n > 0) {
backs[pos] = n;
pos++;
}
}
bn->back_num = pos;
return 0;
}
static int
renumber_backref_traverse(Node* node, GroupNumMap* map)
{
int r = 0;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
do {
r = renumber_backref_traverse(NODE_CAR(node), map);
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_QUANT:
r = renumber_backref_traverse(NODE_BODY(node), map);
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
r = renumber_backref_traverse(NODE_BODY(node), map);
if (r != 0) return r;
if (en->type == BAG_IF_ELSE) {
if (IS_NOT_NULL(en->te.Then)) {
r = renumber_backref_traverse(en->te.Then, map);
if (r != 0) return r;
}
if (IS_NOT_NULL(en->te.Else)) {
r = renumber_backref_traverse(en->te.Else, map);
if (r != 0) return r;
}
}
}
break;
case NODE_BACKREF:
r = renumber_backref_node(node, map);
break;
case NODE_ANCHOR:
if (IS_NOT_NULL(NODE_BODY(node)))
r = renumber_backref_traverse(NODE_BODY(node), map);
break;
default:
break;
}
return r;
}
static int
numbered_ref_check(Node* node)
{
int r = 0;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
do {
r = numbered_ref_check(NODE_CAR(node));
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_ANCHOR:
if (IS_NULL(NODE_BODY(node)))
break;
/* fall */
case NODE_QUANT:
r = numbered_ref_check(NODE_BODY(node));
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
r = numbered_ref_check(NODE_BODY(node));
if (r != 0) return r;
if (en->type == BAG_IF_ELSE) {
if (IS_NOT_NULL(en->te.Then)) {
r = numbered_ref_check(en->te.Then);
if (r != 0) return r;
}
if (IS_NOT_NULL(en->te.Else)) {
r = numbered_ref_check(en->te.Else);
if (r != 0) return r;
}
}
}
break;
case NODE_BACKREF:
if (! NODE_IS_BY_NAME(node))
return ONIGERR_NUMBERED_BACKREF_OR_CALL_NOT_ALLOWED;
break;
default:
break;
}
return r;
}
static int
disable_noname_group_capture(Node** root, regex_t* reg, ScanEnv* env)
{
int r, i, pos, counter;
MemStatusType loc;
GroupNumMap* map;
map = (GroupNumMap* )xalloca(sizeof(GroupNumMap) * (env->num_mem + 1));
CHECK_NULL_RETURN_MEMERR(map);
for (i = 1; i <= env->num_mem; i++) {
map[i].new_val = 0;
}
counter = 0;
r = make_named_capture_number_map(root, map, &counter);
if (r != 0) return r;
r = renumber_backref_traverse(*root, map);
if (r != 0) return r;
for (i = 1, pos = 1; i <= env->num_mem; i++) {
if (map[i].new_val > 0) {
SCANENV_MEMENV(env)[pos] = SCANENV_MEMENV(env)[i];
pos++;
}
}
loc = env->cap_history;
MEM_STATUS_CLEAR(env->cap_history);
for (i = 1; i <= ONIG_MAX_CAPTURE_HISTORY_GROUP; i++) {
if (MEM_STATUS_AT(loc, i)) {
MEM_STATUS_ON_SIMPLE(env->cap_history, map[i].new_val);
}
}
env->num_mem = env->num_named;
reg->num_mem = env->num_named;
return onig_renumber_name_table(reg, map);
}
#ifdef USE_CALL
static int
fix_unset_addr_list(UnsetAddrList* uslist, regex_t* reg)
{
int i, offset;
BagNode* en;
AbsAddrType addr;
AbsAddrType* paddr;
for (i = 0; i < uslist->num; i++) {
if (! NODE_IS_FIXED_ADDR(uslist->us[i].target)) {
if (NODE_IS_CALLED(uslist->us[i].target))
return ONIGERR_PARSER_BUG;
else {
/* CASE: called node doesn't have called address.
ex. /((|a\g<1>)(.){0}){0}\g<3>/
group-1 doesn't called, but compiled into bytecodes,
because group-3 is referred from outside.
*/
continue;
}
}
en = BAG_(uslist->us[i].target);
addr = en->m.called_addr;
offset = uslist->us[i].offset;
paddr = (AbsAddrType* )((char* )reg->ops + offset);
*paddr = addr;
}
return 0;
}
#endif
/* x is not included y ==> 1 : 0 */
static int
is_exclusive(Node* x, Node* y, regex_t* reg)
{
int i, len;
OnigCodePoint code;
UChar *p;
NodeType ytype;
retry:
ytype = NODE_TYPE(y);
switch (NODE_TYPE(x)) {
case NODE_CTYPE:
{
if (CTYPE_(x)->ctype == CTYPE_ANYCHAR ||
CTYPE_(y)->ctype == CTYPE_ANYCHAR)
break;
switch (ytype) {
case NODE_CTYPE:
if (CTYPE_(y)->ctype == CTYPE_(x)->ctype &&
CTYPE_(y)->not != CTYPE_(x)->not &&
CTYPE_(y)->ascii_mode == CTYPE_(x)->ascii_mode)
return 1;
else
return 0;
break;
case NODE_CCLASS:
swap:
{
Node* tmp;
tmp = x; x = y; y = tmp;
goto retry;
}
break;
case NODE_STRING:
goto swap;
break;
default:
break;
}
}
break;
case NODE_CCLASS:
{
int range;
CClassNode* xc = CCLASS_(x);
switch (ytype) {
case NODE_CTYPE:
switch (CTYPE_(y)->ctype) {
case CTYPE_ANYCHAR:
return 0;
break;
case ONIGENC_CTYPE_WORD:
if (CTYPE_(y)->not == 0) {
if (IS_NULL(xc->mbuf) && !IS_NCCLASS_NOT(xc)) {
range = CTYPE_(y)->ascii_mode != 0 ? 128 : SINGLE_BYTE_SIZE;
for (i = 0; i < range; i++) {
if (BITSET_AT(xc->bs, i)) {
if (ONIGENC_IS_CODE_WORD(reg->enc, i)) return 0;
}
}
return 1;
}
return 0;
}
else {
if (IS_NOT_NULL(xc->mbuf)) return 0;
if (IS_NCCLASS_NOT(xc)) return 0;
range = CTYPE_(y)->ascii_mode != 0 ? 128 : SINGLE_BYTE_SIZE;
for (i = 0; i < range; i++) {
if (! ONIGENC_IS_CODE_WORD(reg->enc, i)) {
if (BITSET_AT(xc->bs, i))
return 0;
}
}
for (i = range; i < SINGLE_BYTE_SIZE; i++) {
if (BITSET_AT(xc->bs, i)) return 0;
}
return 1;
}
break;
default:
break;
}
break;
case NODE_CCLASS:
{
int v;
CClassNode* yc = CCLASS_(y);
for (i = 0; i < SINGLE_BYTE_SIZE; i++) {
v = BITSET_AT(xc->bs, i);
if ((v != 0 && !IS_NCCLASS_NOT(xc)) || (v == 0 && IS_NCCLASS_NOT(xc))) {
v = BITSET_AT(yc->bs, i);
if ((v != 0 && !IS_NCCLASS_NOT(yc)) ||
(v == 0 && IS_NCCLASS_NOT(yc)))
return 0;
}
}
if ((IS_NULL(xc->mbuf) && !IS_NCCLASS_NOT(xc)) ||
(IS_NULL(yc->mbuf) && !IS_NCCLASS_NOT(yc)))
return 1;
return 0;
}
break;
case NODE_STRING:
goto swap;
break;
default:
break;
}
}
break;
case NODE_STRING:
{
StrNode* xs = STR_(x);
if (NODE_STRING_LEN(x) == 0)
break;
switch (ytype) {
case NODE_CTYPE:
switch (CTYPE_(y)->ctype) {
case CTYPE_ANYCHAR:
break;
case ONIGENC_CTYPE_WORD:
if (CTYPE_(y)->ascii_mode == 0) {
if (ONIGENC_IS_MBC_WORD(reg->enc, xs->s, xs->end))
return CTYPE_(y)->not;
else
return !(CTYPE_(y)->not);
}
else {
if (ONIGENC_IS_MBC_WORD_ASCII(reg->enc, xs->s, xs->end))
return CTYPE_(y)->not;
else
return !(CTYPE_(y)->not);
}
break;
default:
break;
}
break;
case NODE_CCLASS:
{
CClassNode* cc = CCLASS_(y);
code = ONIGENC_MBC_TO_CODE(reg->enc, xs->s,
xs->s + ONIGENC_MBC_MAXLEN(reg->enc));
return onig_is_code_in_cc(reg->enc, code, cc) == 0;
}
break;
case NODE_STRING:
{
UChar *q;
StrNode* ys = STR_(y);
len = NODE_STRING_LEN(x);
if (len > NODE_STRING_LEN(y)) len = NODE_STRING_LEN(y);
for (i = 0, p = ys->s, q = xs->s; i < len; i++, p++, q++) {
if (*p != *q) return 1;
}
}
break;
default:
break;
}
}
break;
default:
break;
}
return 0;
}
static Node*
get_tree_head_literal(Node* node, int exact, regex_t* reg)
{
Node* n = NULL_NODE;
switch (NODE_TYPE(node)) {
case NODE_BACKREF:
case NODE_ALT:
#ifdef USE_CALL
case NODE_CALL:
#endif
break;
case NODE_CTYPE:
if (CTYPE_(node)->ctype == CTYPE_ANYCHAR)
break;
/* fall */
case NODE_CCLASS:
if (exact == 0) {
n = node;
}
break;
case NODE_LIST:
n = get_tree_head_literal(NODE_CAR(node), exact, reg);
break;
case NODE_STRING:
{
StrNode* sn = STR_(node);
if (sn->end <= sn->s)
break;
if (exact == 0 ||
! NODE_IS_IGNORECASE(node) || NODE_STRING_IS_CRUDE(node)) {
n = node;
}
}
break;
case NODE_QUANT:
{
QuantNode* qn = QUANT_(node);
if (qn->lower > 0) {
if (IS_NOT_NULL(qn->head_exact))
n = qn->head_exact;
else
n = get_tree_head_literal(NODE_BODY(node), exact, reg);
}
}
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
switch (en->type) {
case BAG_OPTION:
case BAG_MEMORY:
case BAG_STOP_BACKTRACK:
case BAG_IF_ELSE:
n = get_tree_head_literal(NODE_BODY(node), exact, reg);
break;
}
}
break;
case NODE_ANCHOR:
if (ANCHOR_(node)->type == ANCR_PREC_READ)
n = get_tree_head_literal(NODE_BODY(node), exact, reg);
break;
case NODE_GIMMICK:
default:
break;
}
return n;
}
enum GetValue {
GET_VALUE_NONE = -1,
GET_VALUE_IGNORE = 0,
GET_VALUE_FOUND = 1
};
static int
get_tree_tail_literal(Node* node, Node** rnode, regex_t* reg)
{
int r;
switch (NODE_TYPE(node)) {
case NODE_LIST:
if (IS_NULL(NODE_CDR(node))) {
r = get_tree_tail_literal(NODE_CAR(node), rnode, reg);
}
else {
r = get_tree_tail_literal(NODE_CDR(node), rnode, reg);
if (r == GET_VALUE_IGNORE) {
r = get_tree_tail_literal(NODE_CAR(node), rnode, reg);
}
}
break;
#ifdef USE_CALL
case NODE_CALL:
r = get_tree_tail_literal(NODE_BODY(node), rnode, reg);
break;
#endif
case NODE_CTYPE:
if (CTYPE_(node)->ctype == CTYPE_ANYCHAR) {
r = GET_VALUE_NONE;
break;
}
/* fall */
case NODE_CCLASS:
*rnode = node;
r = GET_VALUE_FOUND;
break;
case NODE_STRING:
{
StrNode* sn = STR_(node);
if (sn->end <= sn->s) {
r = GET_VALUE_IGNORE;
break;
}
if (NODE_IS_IGNORECASE(node) && ! NODE_STRING_IS_CRUDE(node)) {
r = GET_VALUE_NONE;
break;
}
*rnode = node;
r = GET_VALUE_FOUND;
}
break;
case NODE_QUANT:
{
QuantNode* qn = QUANT_(node);
if (qn->lower != 0) {
r = get_tree_tail_literal(NODE_BODY(node), rnode, reg);
}
else
r = GET_VALUE_NONE;
}
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
if (en->type == BAG_MEMORY) {
if (NODE_IS_MARK1(node))
r = GET_VALUE_NONE;
else {
NODE_STATUS_ADD(node, MARK1);
r = get_tree_tail_literal(NODE_BODY(node), rnode, reg);
NODE_STATUS_REMOVE(node, MARK1);
}
}
else {
r = get_tree_tail_literal(NODE_BODY(node), rnode, reg);
}
}
break;
case NODE_ANCHOR:
case NODE_GIMMICK:
r = GET_VALUE_IGNORE;
break;
case NODE_ALT:
case NODE_BACKREF:
default:
r = GET_VALUE_NONE;
break;
}
return r;
}
static int
check_called_node_in_look_behind(Node* node, int not)
{
int r;
r = 0;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
do {
r = check_called_node_in_look_behind(NODE_CAR(node), not);
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_QUANT:
r = check_called_node_in_look_behind(NODE_BODY(node), not);
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
if (en->type == BAG_MEMORY) {
if (NODE_IS_MARK1(node))
return 0;
else {
NODE_STATUS_ADD(node, MARK1);
r = check_called_node_in_look_behind(NODE_BODY(node), not);
NODE_STATUS_REMOVE(node, MARK1);
}
}
else {
r = check_called_node_in_look_behind(NODE_BODY(node), not);
if (r == 0 && en->type == BAG_IF_ELSE) {
if (IS_NOT_NULL(en->te.Then)) {
r = check_called_node_in_look_behind(en->te.Then, not);
if (r != 0) break;
}
if (IS_NOT_NULL(en->te.Else)) {
r = check_called_node_in_look_behind(en->te.Else, not);
}
}
}
}
break;
case NODE_ANCHOR:
if (IS_NOT_NULL(NODE_BODY(node)))
r = check_called_node_in_look_behind(NODE_BODY(node), not);
break;
case NODE_GIMMICK:
if (NODE_IS_ABSENT_WITH_SIDE_EFFECTS(node) != 0)
return 1;
break;
default:
break;
}
return r;
}
/* allowed node types in look-behind */
#define ALLOWED_TYPE_IN_LB \
( NODE_BIT_LIST | NODE_BIT_ALT | NODE_BIT_STRING | NODE_BIT_CCLASS \
| NODE_BIT_CTYPE | NODE_BIT_ANCHOR | NODE_BIT_BAG | NODE_BIT_QUANT \
| NODE_BIT_CALL | NODE_BIT_BACKREF | NODE_BIT_GIMMICK)
#define ALLOWED_BAG_IN_LB ( 1<<BAG_MEMORY | 1<<BAG_OPTION | 1<<BAG_STOP_BACKTRACK | 1<<BAG_IF_ELSE )
#define ALLOWED_BAG_IN_LB_NOT ( 1<<BAG_OPTION | 1<<BAG_STOP_BACKTRACK | 1<<BAG_IF_ELSE )
#define ALLOWED_ANCHOR_IN_LB \
( ANCR_LOOK_BEHIND | ANCR_BEGIN_LINE | ANCR_END_LINE | ANCR_BEGIN_BUF \
| ANCR_BEGIN_POSITION | ANCR_WORD_BOUNDARY | ANCR_NO_WORD_BOUNDARY \
| ANCR_WORD_BEGIN | ANCR_WORD_END \
| ANCR_TEXT_SEGMENT_BOUNDARY | ANCR_NO_TEXT_SEGMENT_BOUNDARY )
#define ALLOWED_ANCHOR_IN_LB_NOT \
( ANCR_LOOK_BEHIND | ANCR_LOOK_BEHIND_NOT | ANCR_BEGIN_LINE \
| ANCR_END_LINE | ANCR_BEGIN_BUF | ANCR_BEGIN_POSITION | ANCR_WORD_BOUNDARY \
| ANCR_NO_WORD_BOUNDARY | ANCR_WORD_BEGIN | ANCR_WORD_END \
| ANCR_TEXT_SEGMENT_BOUNDARY | ANCR_NO_TEXT_SEGMENT_BOUNDARY )
static int
check_node_in_look_behind(Node* node, int not, int* used)
{
static unsigned int
bag_mask[2] = { ALLOWED_BAG_IN_LB, ALLOWED_BAG_IN_LB_NOT };
static unsigned int
anchor_mask[2] = { ALLOWED_ANCHOR_IN_LB, ALLOWED_ANCHOR_IN_LB_NOT };
NodeType type;
int r = 0;
type = NODE_TYPE(node);
if ((NODE_TYPE2BIT(type) & ALLOWED_TYPE_IN_LB) == 0)
return 1;
switch (type) {
case NODE_LIST:
case NODE_ALT:
do {
r = check_node_in_look_behind(NODE_CAR(node), not, used);
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_QUANT:
r = check_node_in_look_behind(NODE_BODY(node), not, used);
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
if (((1<<en->type) & bag_mask[not]) == 0)
return 1;
r = check_node_in_look_behind(NODE_BODY(node), not, used);
if (r != 0) break;
if (en->type == BAG_MEMORY) {
if (NODE_IS_BACKREF(node) || NODE_IS_CALLED(node)
|| NODE_IS_REFERENCED(node))
*used = TRUE;
}
else if (en->type == BAG_IF_ELSE) {
if (IS_NOT_NULL(en->te.Then)) {
r = check_node_in_look_behind(en->te.Then, not, used);
if (r != 0) break;
}
if (IS_NOT_NULL(en->te.Else)) {
r = check_node_in_look_behind(en->te.Else, not, used);
}
}
}
break;
case NODE_ANCHOR:
type = ANCHOR_(node)->type;
if ((type & anchor_mask[not]) == 0)
return 1;
if (IS_NOT_NULL(NODE_BODY(node)))
r = check_node_in_look_behind(NODE_BODY(node), not, used);
break;
case NODE_GIMMICK:
if (NODE_IS_ABSENT_WITH_SIDE_EFFECTS(node) != 0)
return 1;
break;
case NODE_CALL:
r = check_called_node_in_look_behind(NODE_BODY(node), not);
break;
default:
break;
}
return r;
}
static OnigLen
node_min_byte_len(Node* node, ScanEnv* env)
{
OnigLen len;
OnigLen tmin;
len = 0;
switch (NODE_TYPE(node)) {
case NODE_BACKREF:
if (! NODE_IS_CHECKER(node)) {
int i;
int* backs;
MemEnv* mem_env = SCANENV_MEMENV(env);
BackRefNode* br = BACKREF_(node);
if (NODE_IS_RECURSION(node)) break;
backs = BACKREFS_P(br);
len = node_min_byte_len(mem_env[backs[0]].mem_node, env);
for (i = 1; i < br->back_num; i++) {
tmin = node_min_byte_len(mem_env[backs[i]].mem_node, env);
if (len > tmin) len = tmin;
}
}
break;
#ifdef USE_CALL
case NODE_CALL:
{
Node* t = NODE_BODY(node);
if (NODE_IS_RECURSION(node)) {
if (NODE_IS_FIXED_MIN(t))
len = BAG_(t)->min_len;
}
else
len = node_min_byte_len(t, env);
}
break;
#endif
case NODE_LIST:
do {
tmin = node_min_byte_len(NODE_CAR(node), env);
len = distance_add(len, tmin);
} while (IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_ALT:
{
Node *x, *y;
y = node;
do {
x = NODE_CAR(y);
tmin = node_min_byte_len(x, env);
if (y == node) len = tmin;
else if (len > tmin) len = tmin;
} while (IS_NOT_NULL(y = NODE_CDR(y)));
}
break;
case NODE_STRING:
{
StrNode* sn = STR_(node);
len = (int )(sn->end - sn->s);
}
break;
case NODE_CTYPE:
case NODE_CCLASS:
len = ONIGENC_MBC_MINLEN(env->enc);
break;
case NODE_QUANT:
{
QuantNode* qn = QUANT_(node);
if (qn->lower > 0) {
len = node_min_byte_len(NODE_BODY(node), env);
len = distance_multiply(len, qn->lower);
}
}
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
switch (en->type) {
case BAG_MEMORY:
if (NODE_IS_FIXED_MIN(node))
len = en->min_len;
else {
if (NODE_IS_MARK1(node))
len = 0; /* recursive */
else {
NODE_STATUS_ADD(node, MARK1);
len = node_min_byte_len(NODE_BODY(node), env);
NODE_STATUS_REMOVE(node, MARK1);
en->min_len = len;
NODE_STATUS_ADD(node, FIXED_MIN);
}
}
break;
case BAG_OPTION:
case BAG_STOP_BACKTRACK:
len = node_min_byte_len(NODE_BODY(node), env);
break;
case BAG_IF_ELSE:
{
OnigLen elen;
len = node_min_byte_len(NODE_BODY(node), env);
if (IS_NOT_NULL(en->te.Then))
len += node_min_byte_len(en->te.Then, env);
if (IS_NOT_NULL(en->te.Else))
elen = node_min_byte_len(en->te.Else, env);
else elen = 0;
if (elen < len) len = elen;
}
break;
}
}
break;
case NODE_GIMMICK:
{
GimmickNode* g = GIMMICK_(node);
if (g->type == GIMMICK_FAIL) {
len = INFINITE_LEN;
break;
}
}
/* fall */
case NODE_ANCHOR:
default:
break;
}
return len;
}
static OnigLen
node_max_byte_len(Node* node, ScanEnv* env)
{
OnigLen len;
OnigLen tmax;
len = 0;
switch (NODE_TYPE(node)) {
case NODE_LIST:
do {
tmax = node_max_byte_len(NODE_CAR(node), env);
len = distance_add(len, tmax);
} while (IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_ALT:
do {
tmax = node_max_byte_len(NODE_CAR(node), env);
if (len < tmax) len = tmax;
} while (IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_STRING:
{
StrNode* sn = STR_(node);
len = (OnigLen )(sn->end - sn->s);
}
break;
case NODE_CTYPE:
case NODE_CCLASS:
len = ONIGENC_MBC_MAXLEN_DIST(env->enc);
break;
case NODE_BACKREF:
if (! NODE_IS_CHECKER(node)) {
int i;
int* backs;
MemEnv* mem_env = SCANENV_MEMENV(env);
BackRefNode* br = BACKREF_(node);
if (NODE_IS_RECURSION(node)) {
#ifdef USE_BACKREF_WITH_LEVEL
if (NODE_IS_NEST_LEVEL(node)) {
len = INFINITE_LEN;
}
#endif
break;
}
backs = BACKREFS_P(br);
for (i = 0; i < br->back_num; i++) {
tmax = node_max_byte_len(mem_env[backs[i]].mem_node, env);
if (len < tmax) len = tmax;
}
}
break;
#ifdef USE_CALL
case NODE_CALL:
if (! NODE_IS_RECURSION(node))
len = node_max_byte_len(NODE_BODY(node), env);
else
len = INFINITE_LEN;
break;
#endif
case NODE_QUANT:
{
QuantNode* qn = QUANT_(node);
if (qn->upper != 0) {
len = node_max_byte_len(NODE_BODY(node), env);
if (len != 0) {
if (! IS_INFINITE_REPEAT(qn->upper))
len = distance_multiply(len, qn->upper);
else
len = INFINITE_LEN;
}
}
}
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
switch (en->type) {
case BAG_MEMORY:
if (NODE_IS_FIXED_MAX(node))
len = en->max_len;
else {
if (NODE_IS_MARK1(node))
len = INFINITE_LEN;
else {
NODE_STATUS_ADD(node, MARK1);
len = node_max_byte_len(NODE_BODY(node), env);
NODE_STATUS_REMOVE(node, MARK1);
en->max_len = len;
NODE_STATUS_ADD(node, FIXED_MAX);
}
}
break;
case BAG_OPTION:
case BAG_STOP_BACKTRACK:
len = node_max_byte_len(NODE_BODY(node), env);
break;
case BAG_IF_ELSE:
{
OnigLen tlen, elen;
len = node_max_byte_len(NODE_BODY(node), env);
if (IS_NOT_NULL(en->te.Then)) {
tlen = node_max_byte_len(en->te.Then, env);
len = distance_add(len, tlen);
}
if (IS_NOT_NULL(en->te.Else))
elen = node_max_byte_len(en->te.Else, env);
else elen = 0;
if (elen > len) len = elen;
}
break;
}
}
break;
case NODE_ANCHOR:
case NODE_GIMMICK:
default:
break;
}
return len;
}
static int
check_backrefs(Node* node, ScanEnv* env)
{
int r;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
do {
r = check_backrefs(NODE_CAR(node), env);
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_ANCHOR:
if (! ANCHOR_HAS_BODY(ANCHOR_(node))) {
r = 0;
break;
}
/* fall */
case NODE_QUANT:
r = check_backrefs(NODE_BODY(node), env);
break;
case NODE_BAG:
r = check_backrefs(NODE_BODY(node), env);
{
BagNode* en = BAG_(node);
if (en->type == BAG_IF_ELSE) {
if (r != 0) return r;
if (IS_NOT_NULL(en->te.Then)) {
r = check_backrefs(en->te.Then, env);
if (r != 0) return r;
}
if (IS_NOT_NULL(en->te.Else)) {
r = check_backrefs(en->te.Else, env);
}
}
}
break;
case NODE_BACKREF:
{
int i;
BackRefNode* br = BACKREF_(node);
int* backs = BACKREFS_P(br);
MemEnv* mem_env = SCANENV_MEMENV(env);
for (i = 0; i < br->back_num; i++) {
if (backs[i] > env->num_mem)
return ONIGERR_INVALID_BACKREF;
NODE_STATUS_ADD(mem_env[backs[i]].mem_node, BACKREF);
}
r = 0;
}
break;
default:
r = 0;
break;
}
return r;
}
static int
set_empty_repeat_node_trav(Node* node, Node* empty, ScanEnv* env)
{
int r;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
do {
r = set_empty_repeat_node_trav(NODE_CAR(node), empty, env);
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_ANCHOR:
{
AnchorNode* an = ANCHOR_(node);
if (! ANCHOR_HAS_BODY(an)) {
r = 0;
break;
}
switch (an->type) {
case ANCR_PREC_READ:
case ANCR_LOOK_BEHIND:
empty = NULL_NODE;
break;
default:
break;
}
r = set_empty_repeat_node_trav(NODE_BODY(node), empty, env);
}
break;
case NODE_QUANT:
{
QuantNode* qn = QUANT_(node);
if (qn->emptiness != BODY_IS_NOT_EMPTY) empty = node;
r = set_empty_repeat_node_trav(NODE_BODY(node), empty, env);
}
break;
case NODE_BAG:
if (IS_NOT_NULL(NODE_BODY(node))) {
r = set_empty_repeat_node_trav(NODE_BODY(node), empty, env);
if (r != 0) return r;
}
{
BagNode* en = BAG_(node);
r = 0;
if (en->type == BAG_MEMORY) {
if (NODE_IS_BACKREF(node)) {
if (IS_NOT_NULL(empty))
SCANENV_MEMENV(env)[en->m.regnum].empty_repeat_node = empty;
}
}
else if (en->type == BAG_IF_ELSE) {
if (IS_NOT_NULL(en->te.Then)) {
r = set_empty_repeat_node_trav(en->te.Then, empty, env);
if (r != 0) return r;
}
if (IS_NOT_NULL(en->te.Else)) {
r = set_empty_repeat_node_trav(en->te.Else, empty, env);
}
}
}
break;
default:
r = 0;
break;
}
return r;
}
static int
is_ancestor_node(Node* node, Node* me)
{
Node* parent;
while ((parent = NODE_PARENT(me)) != NULL_NODE) {
if (parent == node) return 1;
me = parent;
}
return 0;
}
static void
set_empty_status_check_trav(Node* node, ScanEnv* env)
{
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
do {
set_empty_status_check_trav(NODE_CAR(node), env);
} while (IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_ANCHOR:
{
AnchorNode* an = ANCHOR_(node);
if (! ANCHOR_HAS_BODY(an)) break;
set_empty_status_check_trav(NODE_BODY(node), env);
}
break;
case NODE_QUANT:
set_empty_status_check_trav(NODE_BODY(node), env);
break;
case NODE_BAG:
if (IS_NOT_NULL(NODE_BODY(node)))
set_empty_status_check_trav(NODE_BODY(node), env);
{
BagNode* en = BAG_(node);
if (en->type == BAG_IF_ELSE) {
if (IS_NOT_NULL(en->te.Then)) {
set_empty_status_check_trav(en->te.Then, env);
}
if (IS_NOT_NULL(en->te.Else)) {
set_empty_status_check_trav(en->te.Else, env);
}
}
}
break;
case NODE_BACKREF:
{
int i;
int* backs;
MemEnv* mem_env = SCANENV_MEMENV(env);
BackRefNode* br = BACKREF_(node);
backs = BACKREFS_P(br);
for (i = 0; i < br->back_num; i++) {
Node* ernode = mem_env[backs[i]].empty_repeat_node;
if (IS_NOT_NULL(ernode)) {
if (! is_ancestor_node(ernode, node)) {
MEM_STATUS_LIMIT_ON(env->reg->empty_status_mem, backs[i]);
NODE_STATUS_ADD(ernode, EMPTY_STATUS_CHECK);
NODE_STATUS_ADD(mem_env[backs[i]].mem_node, EMPTY_STATUS_CHECK);
}
}
}
}
break;
default:
break;
}
}
static void
set_parent_node_trav(Node* node, Node* parent)
{
NODE_PARENT(node) = parent;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
do {
set_parent_node_trav(NODE_CAR(node), node);
} while (IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_ANCHOR:
if (! ANCHOR_HAS_BODY(ANCHOR_(node))) break;
set_parent_node_trav(NODE_BODY(node), node);
break;
case NODE_QUANT:
set_parent_node_trav(NODE_BODY(node), node);
break;
case NODE_BAG:
if (IS_NOT_NULL(NODE_BODY(node)))
set_parent_node_trav(NODE_BODY(node), node);
{
BagNode* en = BAG_(node);
if (en->type == BAG_IF_ELSE) {
if (IS_NOT_NULL(en->te.Then))
set_parent_node_trav(en->te.Then, node);
if (IS_NOT_NULL(en->te.Else)) {
set_parent_node_trav(en->te.Else, node);
}
}
}
break;
default:
break;
}
}
#ifdef USE_CALL
#define RECURSION_EXIST (1<<0)
#define RECURSION_MUST (1<<1)
#define RECURSION_INFINITE (1<<2)
static int
infinite_recursive_call_check(Node* node, ScanEnv* env, int head)
{
int ret;
int r = 0;
switch (NODE_TYPE(node)) {
case NODE_LIST:
{
Node *x;
OnigLen min;
x = node;
do {
ret = infinite_recursive_call_check(NODE_CAR(x), env, head);
if (ret < 0 || (ret & RECURSION_INFINITE) != 0) return ret;
r |= ret;
if (head != 0) {
min = node_min_byte_len(NODE_CAR(x), env);
if (min != 0) head = 0;
}
} while (IS_NOT_NULL(x = NODE_CDR(x)));
}
break;
case NODE_ALT:
{
int must;
must = RECURSION_MUST;
do {
ret = infinite_recursive_call_check(NODE_CAR(node), env, head);
if (ret < 0 || (ret & RECURSION_INFINITE) != 0) return ret;
r |= (ret & RECURSION_EXIST);
must &= ret;
} while (IS_NOT_NULL(node = NODE_CDR(node)));
r |= must;
}
break;
case NODE_QUANT:
r = infinite_recursive_call_check(NODE_BODY(node), env, head);
if (r < 0) return r;
if ((r & RECURSION_MUST) != 0) {
if (QUANT_(node)->lower == 0)
r &= ~RECURSION_MUST;
}
break;
case NODE_ANCHOR:
if (! ANCHOR_HAS_BODY(ANCHOR_(node)))
break;
/* fall */
case NODE_CALL:
r = infinite_recursive_call_check(NODE_BODY(node), env, head);
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
if (en->type == BAG_MEMORY) {
if (NODE_IS_MARK2(node))
return 0;
else if (NODE_IS_MARK1(node))
return (head == 0 ? RECURSION_EXIST | RECURSION_MUST
: RECURSION_EXIST | RECURSION_MUST | RECURSION_INFINITE);
else {
NODE_STATUS_ADD(node, MARK2);
r = infinite_recursive_call_check(NODE_BODY(node), env, head);
NODE_STATUS_REMOVE(node, MARK2);
}
}
else if (en->type == BAG_IF_ELSE) {
int eret;
ret = infinite_recursive_call_check(NODE_BODY(node), env, head);
if (ret < 0 || (ret & RECURSION_INFINITE) != 0) return ret;
r |= ret;
if (IS_NOT_NULL(en->te.Then)) {
OnigLen min;
if (head != 0) {
min = node_min_byte_len(NODE_BODY(node), env);
}
else min = 0;
ret = infinite_recursive_call_check(en->te.Then, env, min != 0 ? 0:head);
if (ret < 0 || (ret & RECURSION_INFINITE) != 0) return ret;
r |= ret;
}
if (IS_NOT_NULL(en->te.Else)) {
eret = infinite_recursive_call_check(en->te.Else, env, head);
if (eret < 0 || (eret & RECURSION_INFINITE) != 0) return eret;
r |= (eret & RECURSION_EXIST);
if ((eret & RECURSION_MUST) == 0)
r &= ~RECURSION_MUST;
}
else {
r &= ~RECURSION_MUST;
}
}
else {
r = infinite_recursive_call_check(NODE_BODY(node), env, head);
}
}
break;
default:
break;
}
return r;
}
static int
infinite_recursive_call_check_trav(Node* node, ScanEnv* env)
{
int r;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
do {
r = infinite_recursive_call_check_trav(NODE_CAR(node), env);
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_ANCHOR:
if (! ANCHOR_HAS_BODY(ANCHOR_(node))) {
r = 0;
break;
}
/* fall */
case NODE_QUANT:
r = infinite_recursive_call_check_trav(NODE_BODY(node), env);
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
if (en->type == BAG_MEMORY) {
if (NODE_IS_RECURSION(node) && NODE_IS_CALLED(node)) {
int ret;
NODE_STATUS_ADD(node, MARK1);
ret = infinite_recursive_call_check(NODE_BODY(node), env, 1);
if (ret < 0) return ret;
else if ((ret & (RECURSION_MUST | RECURSION_INFINITE)) != 0)
return ONIGERR_NEVER_ENDING_RECURSION;
NODE_STATUS_REMOVE(node, MARK1);
}
}
else if (en->type == BAG_IF_ELSE) {
if (IS_NOT_NULL(en->te.Then)) {
r = infinite_recursive_call_check_trav(en->te.Then, env);
if (r != 0) return r;
}
if (IS_NOT_NULL(en->te.Else)) {
r = infinite_recursive_call_check_trav(en->te.Else, env);
if (r != 0) return r;
}
}
}
r = infinite_recursive_call_check_trav(NODE_BODY(node), env);
break;
default:
r = 0;
break;
}
return r;
}
static int
recursive_call_check(Node* node)
{
int r;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
r = 0;
do {
r |= recursive_call_check(NODE_CAR(node));
} while (IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_ANCHOR:
if (! ANCHOR_HAS_BODY(ANCHOR_(node))) {
r = 0;
break;
}
/* fall */
case NODE_QUANT:
r = recursive_call_check(NODE_BODY(node));
break;
case NODE_CALL:
r = recursive_call_check(NODE_BODY(node));
if (r != 0) {
if (NODE_IS_MARK1(NODE_BODY(node)))
NODE_STATUS_ADD(node, RECURSION);
}
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
if (en->type == BAG_MEMORY) {
if (NODE_IS_MARK2(node))
return 0;
else if (NODE_IS_MARK1(node))
return 1; /* recursion */
else {
NODE_STATUS_ADD(node, MARK2);
r = recursive_call_check(NODE_BODY(node));
NODE_STATUS_REMOVE(node, MARK2);
}
}
else if (en->type == BAG_IF_ELSE) {
r = 0;
if (IS_NOT_NULL(en->te.Then)) {
r |= recursive_call_check(en->te.Then);
}
if (IS_NOT_NULL(en->te.Else)) {
r |= recursive_call_check(en->te.Else);
}
r |= recursive_call_check(NODE_BODY(node));
}
else {
r = recursive_call_check(NODE_BODY(node));
}
}
break;
default:
r = 0;
break;
}
return r;
}
#define IN_RECURSION (1<<0)
#define FOUND_CALLED_NODE 1
static int
recursive_call_check_trav(Node* node, ScanEnv* env, int state)
{
int r = 0;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
{
int ret;
do {
ret = recursive_call_check_trav(NODE_CAR(node), env, state);
if (ret == FOUND_CALLED_NODE) r = FOUND_CALLED_NODE;
else if (ret < 0) return ret;
} while (IS_NOT_NULL(node = NODE_CDR(node)));
}
break;
case NODE_QUANT:
r = recursive_call_check_trav(NODE_BODY(node), env, state);
if (QUANT_(node)->upper == 0) {
if (r == FOUND_CALLED_NODE)
QUANT_(node)->include_referred = 1;
}
break;
case NODE_ANCHOR:
{
AnchorNode* an = ANCHOR_(node);
if (ANCHOR_HAS_BODY(an))
r = recursive_call_check_trav(NODE_ANCHOR_BODY(an), env, state);
}
break;
case NODE_BAG:
{
int ret;
int state1;
BagNode* en = BAG_(node);
if (en->type == BAG_MEMORY) {
if (NODE_IS_CALLED(node) || (state & IN_RECURSION) != 0) {
if (! NODE_IS_RECURSION(node)) {
NODE_STATUS_ADD(node, MARK1);
r = recursive_call_check(NODE_BODY(node));
if (r != 0) {
NODE_STATUS_ADD(node, RECURSION);
MEM_STATUS_ON(env->backtrack_mem, en->m.regnum);
}
NODE_STATUS_REMOVE(node, MARK1);
}
if (NODE_IS_CALLED(node))
r = FOUND_CALLED_NODE;
}
}
state1 = state;
if (NODE_IS_RECURSION(node))
state1 |= IN_RECURSION;
ret = recursive_call_check_trav(NODE_BODY(node), env, state1);
if (ret == FOUND_CALLED_NODE)
r = FOUND_CALLED_NODE;
if (en->type == BAG_IF_ELSE) {
if (IS_NOT_NULL(en->te.Then)) {
ret = recursive_call_check_trav(en->te.Then, env, state1);
if (ret == FOUND_CALLED_NODE)
r = FOUND_CALLED_NODE;
}
if (IS_NOT_NULL(en->te.Else)) {
ret = recursive_call_check_trav(en->te.Else, env, state1);
if (ret == FOUND_CALLED_NODE)
r = FOUND_CALLED_NODE;
}
}
}
break;
default:
break;
}
return r;
}
#endif
static void
remove_from_list(Node* prev, Node* a)
{
if (NODE_CDR(prev) != a) return ;
NODE_CDR(prev) = NODE_CDR(a);
NODE_CDR(a) = NULL_NODE;
}
static int
reduce_string_list(Node* node, OnigEncoding enc)
{
int r = 0;
switch (NODE_TYPE(node)) {
case NODE_LIST:
{
Node* prev;
Node* curr;
Node* prev_node;
Node* next_node;
prev = NULL_NODE;
do {
next_node = NODE_CDR(node);
curr = NODE_CAR(node);
if (NODE_TYPE(curr) == NODE_STRING) {
if (IS_NULL(prev)
|| STR_(curr)->flag != STR_(prev)->flag
|| NODE_STATUS(curr) != NODE_STATUS(prev)) {
prev = curr;
prev_node = node;
}
else {
r = node_str_node_cat(prev, curr);
if (r != 0) return r;
remove_from_list(prev_node, node);
onig_node_free(node);
}
}
else {
if (IS_NOT_NULL(prev)) {
#ifdef USE_CHECK_VALIDITY_OF_STRING_IN_TREE
StrNode* sn = STR_(prev);
if (! ONIGENC_IS_VALID_MBC_STRING(enc, sn->s, sn->end))
return ONIGERR_INVALID_WIDE_CHAR_VALUE;
#endif
prev = NULL_NODE;
}
r = reduce_string_list(curr, enc);
if (r != 0) return r;
prev_node = node;
}
node = next_node;
} while (r == 0 && IS_NOT_NULL(node));
#ifdef USE_CHECK_VALIDITY_OF_STRING_IN_TREE
if (IS_NOT_NULL(prev)) {
StrNode* sn = STR_(prev);
if (! ONIGENC_IS_VALID_MBC_STRING(enc, sn->s, sn->end))
return ONIGERR_INVALID_WIDE_CHAR_VALUE;
}
#endif
}
break;
case NODE_ALT:
do {
r = reduce_string_list(NODE_CAR(node), enc);
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
#ifdef USE_CHECK_VALIDITY_OF_STRING_IN_TREE
case NODE_STRING:
{
StrNode* sn = STR_(node);
if (! ONIGENC_IS_VALID_MBC_STRING(enc, sn->s, sn->end))
return ONIGERR_INVALID_WIDE_CHAR_VALUE;
}
break;
#endif
case NODE_ANCHOR:
if (IS_NULL(NODE_BODY(node)))
break;
/* fall */
case NODE_QUANT:
r = reduce_string_list(NODE_BODY(node), enc);
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
r = reduce_string_list(NODE_BODY(node), enc);
if (r != 0) return r;
if (en->type == BAG_IF_ELSE) {
if (IS_NOT_NULL(en->te.Then)) {
r = reduce_string_list(en->te.Then, enc);
if (r != 0) return r;
}
if (IS_NOT_NULL(en->te.Else)) {
r = reduce_string_list(en->te.Else, enc);
if (r != 0) return r;
}
}
}
break;
default:
break;
}
return r;
}
#define IN_ALT (1<<0)
#define IN_NOT (1<<1)
#define IN_REAL_REPEAT (1<<2)
#define IN_VAR_REPEAT (1<<3)
#define IN_ZERO_REPEAT (1<<4)
#define IN_MULTI_ENTRY (1<<5)
#define IN_LOOK_BEHIND (1<<6)
/* divide different length alternatives in look-behind.
(?<=A|B) ==> (?<=A)|(?<=B)
(?<!A|B) ==> (?<!A)(?<!B)
*/
static int
divide_look_behind_alternatives(Node* node)
{
int r;
int anc_type;
Node *head, *np, *insert_node;
AnchorNode* an;
an = ANCHOR_(node);
anc_type = an->type;
head = NODE_ANCHOR_BODY(an);
np = NODE_CAR(head);
node_swap(node, head);
NODE_CAR(node) = head;
NODE_BODY(head) = np;
np = node;
while (IS_NOT_NULL(np = NODE_CDR(np))) {
r = onig_node_copy(&insert_node, head);
if (r != 0) return r;
CHECK_NULL_RETURN_MEMERR(insert_node);
NODE_BODY(insert_node) = NODE_CAR(np);
NODE_CAR(np) = insert_node;
}
if (anc_type == ANCR_LOOK_BEHIND_NOT) {
np = node;
do {
NODE_SET_TYPE(np, NODE_LIST); /* alt -> list */
} while (IS_NOT_NULL(np = NODE_CDR(np)));
}
return 0;
}
static int
node_reduce_in_look_behind(Node* node)
{
NodeType type;
Node* body;
if (NODE_TYPE(node) != NODE_QUANT) return 0;
body = NODE_BODY(node);
type = NODE_TYPE(body);
if (type == NODE_STRING || type == NODE_CTYPE ||
type == NODE_CCLASS || type == NODE_BACKREF) {
QuantNode* qn = QUANT_(node);
qn->upper = qn->lower;
if (qn->upper == 0)
return 1; /* removed */
}
return 0;
}
static int
list_reduce_in_look_behind(Node* node)
{
int r;
switch (NODE_TYPE(node)) {
case NODE_QUANT:
r = node_reduce_in_look_behind(node);
if (r > 0) r = 0;
break;
case NODE_LIST:
do {
r = node_reduce_in_look_behind(NODE_CAR(node));
if (r <= 0) break;
} while (IS_NOT_NULL(node = NODE_CDR(node)));
break;
default:
r = 0;
break;
}
return r;
}
static int
alt_reduce_in_look_behind(Node* node, regex_t* reg, ScanEnv* env)
{
int r;
switch (NODE_TYPE(node)) {
case NODE_ALT:
do {
r = list_reduce_in_look_behind(NODE_CAR(node));
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
default:
r = list_reduce_in_look_behind(node);
break;
}
return r;
}
static int tune_tree(Node* node, regex_t* reg, int state, ScanEnv* env);
static int
tune_look_behind(Node* node, regex_t* reg, int state, ScanEnv* env)
{
int r;
int state1;
int used;
MinMaxCharLen ci;
Node* body;
AnchorNode* an = ANCHOR_(node);
used = FALSE;
r = check_node_in_look_behind(NODE_ANCHOR_BODY(an),
an->type == ANCR_LOOK_BEHIND_NOT ? 1 : 0,
&used);
if (r < 0) return r;
if (r > 0) return ONIGERR_INVALID_LOOK_BEHIND_PATTERN;
if (an->type == ANCR_LOOK_BEHIND_NOT)
state1 = state | IN_NOT | IN_LOOK_BEHIND;
else
state1 = state | IN_LOOK_BEHIND;
body = NODE_ANCHOR_BODY(an);
/* Execute tune_tree(body) before call node_char_len().
Because case-fold expansion must be done before node_char_len().
*/
r = tune_tree(body, reg, state1, env);
if (r != 0) return r;
r = alt_reduce_in_look_behind(body, reg, env);
if (r != 0) return r;
r = node_char_len(body, reg, &ci, env);
if (r >= 0) {
/* #177: overflow in onigenc_step_back() */
if ((ci.max != INFINITE_LEN && ci.max > LOOK_BEHIND_MAX_CHAR_LEN)
|| ci.min > LOOK_BEHIND_MAX_CHAR_LEN) {
return ONIGERR_INVALID_LOOK_BEHIND_PATTERN;
}
if (ci.min == 0 && ci.min_is_sure != FALSE && used == FALSE) {
if (an->type == ANCR_LOOK_BEHIND_NOT)
r = onig_node_reset_fail(node);
else
r = onig_node_reset_empty(node);
return r;
}
if (r == CHAR_LEN_TOP_ALT_FIXED) {
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_DIFFERENT_LEN_ALT_LOOK_BEHIND)) {
r = divide_look_behind_alternatives(node);
if (r == 0)
r = tune_tree(node, reg, state, env);
}
else if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_VARIABLE_LEN_LOOK_BEHIND))
goto normal;
else
r = ONIGERR_INVALID_LOOK_BEHIND_PATTERN;
}
else { /* CHAR_LEN_NORMAL */
normal:
if (ci.min == INFINITE_LEN) {
r = ONIGERR_INVALID_LOOK_BEHIND_PATTERN;
}
else {
if (ci.min != ci.max &&
! IS_SYNTAX_BV(env->syntax, ONIG_SYN_VARIABLE_LEN_LOOK_BEHIND)) {
r = ONIGERR_INVALID_LOOK_BEHIND_PATTERN;
}
else {
Node* tail;
/* check lead_node is already set by double call after
divide_look_behind_alternatives() */
if (IS_NULL(an->lead_node)) {
an->char_min_len = ci.min;
an->char_max_len = ci.max;
r = get_tree_tail_literal(body, &tail, reg);
if (r == GET_VALUE_FOUND) {
r = onig_node_copy(&(an->lead_node), tail);
if (r != 0) return r;
}
}
r = ONIG_NORMAL;
}
}
}
}
return r;
}
static int
tune_next(Node* node, Node* next_node, regex_t* reg)
{
int called;
NodeType type;
called = FALSE;
retry:
type = NODE_TYPE(node);
if (type == NODE_QUANT) {
QuantNode* qn = QUANT_(node);
if (qn->greedy && IS_INFINITE_REPEAT(qn->upper)) {
#ifdef USE_QUANT_PEEK_NEXT
if (called == FALSE) {
Node* n = get_tree_head_literal(next_node, 1, reg);
/* '\0': for UTF-16BE etc... */
if (IS_NOT_NULL(n) && STR_(n)->s[0] != '\0') {
qn->next_head_exact = n;
}
}
#endif
/* automatic posseivation a*b ==> (?>a*)b */
if (qn->lower <= 1) {
if (is_strict_real_node(NODE_BODY(node))) {
Node *x, *y;
x = get_tree_head_literal(NODE_BODY(node), 0, reg);
if (IS_NOT_NULL(x)) {
y = get_tree_head_literal(next_node, 0, reg);
if (IS_NOT_NULL(y) && is_exclusive(x, y, reg)) {
Node* en = onig_node_new_bag(BAG_STOP_BACKTRACK);
CHECK_NULL_RETURN_MEMERR(en);
NODE_STATUS_ADD(en, STRICT_REAL_REPEAT);
node_swap(node, en);
NODE_BODY(node) = en;
}
}
}
}
}
}
else if (type == NODE_BAG) {
BagNode* en = BAG_(node);
if (en->type == BAG_MEMORY) {
if (NODE_IS_CALLED(node))
called = TRUE;
node = NODE_BODY(node);
goto retry;
}
}
return 0;
}
static int
is_all_code_len_1_items(int n, OnigCaseFoldCodeItem items[])
{
int i;
for (i = 0; i < n; i++) {
OnigCaseFoldCodeItem* item = items + i;
if (item->code_len != 1) return 0;
}
return 1;
}
static int
get_min_max_byte_len_case_fold_items(int n, OnigCaseFoldCodeItem items[],
OnigLen* rmin, OnigLen* rmax)
{
int i;
OnigLen len, minlen, maxlen;
minlen = INFINITE_LEN;
maxlen = 0;
for (i = 0; i < n; i++) {
OnigCaseFoldCodeItem* item = items + i;
len = item->byte_len;
if (len < minlen) minlen = len;
if (len > maxlen) maxlen = len;
}
*rmin = minlen;
*rmax = maxlen;
return 0;
}
static int
make_code_list_to_string(Node** rnode, OnigEncoding enc,
int n, OnigCodePoint codes[])
{
int r, i, len;
Node* node;
UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN];
*rnode = NULL_NODE;
node = onig_node_new_str(NULL, NULL);
CHECK_NULL_RETURN_MEMERR(node);
for (i = 0; i < n; i++) {
len = ONIGENC_CODE_TO_MBC(enc, codes[i], buf);
if (len < 0) {
r = len;
goto err;
}
r = onig_node_str_cat(node, buf, buf + len);
if (r != 0) goto err;
}
*rnode = node;
return 0;
err:
onig_node_free(node);
return r;
}
static int
unravel_cf_node_add(Node** rlist, Node* add)
{
Node *list;
list = *rlist;
if (IS_NULL(list)) {
list = onig_node_new_list(add, NULL);
CHECK_NULL_RETURN_MEMERR(list);
*rlist = list;
}
else {
Node* r = node_list_add(list, add);
CHECK_NULL_RETURN_MEMERR(r);
}
return 0;
}
static int
unravel_cf_string_add(Node** rlist, Node** rsn, UChar* s, UChar* end,
unsigned int flag)
{
int r;
Node *sn, *list;
list = *rlist;
sn = *rsn;
if (IS_NOT_NULL(sn) && STR_(sn)->flag == flag) {
r = onig_node_str_cat(sn, s, end);
}
else {
sn = onig_node_new_str(s, end);
CHECK_NULL_RETURN_MEMERR(sn);
STR_(sn)->flag = flag;
r = unravel_cf_node_add(&list, sn);
}
if (r == 0) {
*rlist = list;
*rsn = sn;
}
return r;
}
static int
unravel_cf_string_alt_or_cc_add(Node** rlist, int n,
OnigCaseFoldCodeItem items[], OnigEncoding enc,
OnigCaseFoldType case_fold_flag, UChar* s, UChar* end)
{
int r, i;
Node* node;
if (is_all_code_len_1_items(n, items)) {
OnigCodePoint codes[14];/* least ONIGENC_GET_CASE_FOLD_CODES_MAX_NUM + 1 */
codes[0] = ONIGENC_MBC_TO_CODE(enc, s, end);
for (i = 0; i < n; i++) {
OnigCaseFoldCodeItem* item = items + i;
codes[i+1] = item->code[0];
}
r = onig_new_cclass_with_code_list(&node, enc, n + 1, codes);
if (r != 0) return r;
}
else {
Node *snode, *alt, *curr;
snode = onig_node_new_str(s, end);
CHECK_NULL_RETURN_MEMERR(snode);
node = curr = onig_node_new_alt(snode, NULL_NODE);
if (IS_NULL(curr)) {
onig_node_free(snode);
return ONIGERR_MEMORY;
}
r = 0;
for (i = 0; i < n; i++) {
OnigCaseFoldCodeItem* item = items + i;
r = make_code_list_to_string(&snode, enc, item->code_len, item->code);
if (r != 0) {
onig_node_free(node);
return r;
}
alt = onig_node_new_alt(snode, NULL_NODE);
if (IS_NULL(alt)) {
onig_node_free(snode);
onig_node_free(node);
return ONIGERR_MEMORY;
}
NODE_CDR(curr) = alt;
curr = alt;
}
}
r = unravel_cf_node_add(rlist, node);
if (r != 0) onig_node_free(node);
return r;
}
static int
unravel_cf_look_behind_add(Node** rlist, Node** rsn,
int n, OnigCaseFoldCodeItem items[], OnigEncoding enc,
UChar* s, OnigLen one_len)
{
int r, i, found;
found = FALSE;
for (i = 0; i < n; i++) {
OnigCaseFoldCodeItem* item = items + i;
if (item->byte_len == one_len) {
if (item->code_len == 1) {
found = TRUE;
break;
}
}
}
if (found == FALSE) {
r = unravel_cf_string_add(rlist, rsn, s, s + one_len, 0 /* flag */);
}
else {
Node* node;
OnigCodePoint codes[14];/* least ONIGENC_GET_CASE_FOLD_CODES_MAX_NUM + 1 */
found = 0;
codes[found++] = ONIGENC_MBC_TO_CODE(enc, s, s + one_len);
for (i = 0; i < n; i++) {
OnigCaseFoldCodeItem* item = items + i;
if (item->byte_len == one_len) {
if (item->code_len == 1) {
codes[found++] = item->code[0];
}
}
}
r = onig_new_cclass_with_code_list(&node, enc, found, codes);
if (r != 0) return r;
r = unravel_cf_node_add(rlist, node);
if (r != 0) onig_node_free(node);
*rsn = NULL_NODE;
}
return r;
}
static int
unravel_case_fold_string(Node* node, regex_t* reg, int state)
{
int r, n, in_look_behind;
OnigLen min_len, max_len, one_len;
UChar *start, *end, *p, *q;
StrNode* snode;
Node *sn, *list;
OnigEncoding enc;
OnigCaseFoldCodeItem items[ONIGENC_GET_CASE_FOLD_CODES_MAX_NUM];
if (NODE_STRING_IS_CASE_EXPANDED(node)) return 0;
NODE_STATUS_REMOVE(node, IGNORECASE);
snode = STR_(node);
start = snode->s;
end = snode->end;
if (start >= end) return 0;
in_look_behind = (state & IN_LOOK_BEHIND) != 0;
enc = reg->enc;
list = sn = NULL_NODE;
p = start;
while (p < end) {
n = ONIGENC_GET_CASE_FOLD_CODES_BY_STR(enc, reg->case_fold_flag, p, end,
items);
if (n < 0) {
r = n;
goto err;
}
one_len = (OnigLen )enclen(enc, p);
if (n == 0) {
q = p + one_len;
if (q > end) q = end;
r = unravel_cf_string_add(&list, &sn, p, q, 0 /* flag */);
if (r != 0) goto err;
}
else {
if (in_look_behind != 0) {
q = p + one_len;
if (items[0].byte_len != one_len) {
r = ONIGENC_GET_CASE_FOLD_CODES_BY_STR(enc, reg->case_fold_flag, p, q,
items);
if (r < 0) goto err;
n = r;
}
r = unravel_cf_look_behind_add(&list, &sn, n, items, enc, p, one_len);
if (r != 0) goto err;
}
else {
get_min_max_byte_len_case_fold_items(n, items, &min_len, &max_len);
if (min_len != max_len) {
r = ONIGERR_PARSER_BUG;
goto err;
}
q = p + max_len;
r = unravel_cf_string_alt_or_cc_add(&list, n, items, enc,
reg->case_fold_flag, p, q);
if (r != 0) goto err;
sn = NULL_NODE;
}
}
p = q;
}
if (IS_NOT_NULL(list)) {
if (node_list_len(list) == 1) {
node_swap(node, NODE_CAR(list));
}
else {
node_swap(node, list);
}
onig_node_free(list);
}
else {
node_swap(node, sn);
onig_node_free(sn);
}
return 0;
err:
if (IS_NOT_NULL(list))
onig_node_free(list);
else if (IS_NOT_NULL(sn))
onig_node_free(sn);
return r;
}
#ifdef USE_STUBBORN_CHECK_CAPTURES_IN_EMPTY_REPEAT
static enum BodyEmptyType
quantifiers_memory_node_info(Node* node)
{
int r = BODY_MAY_BE_EMPTY;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
{
int v;
do {
v = quantifiers_memory_node_info(NODE_CAR(node));
if (v > r) r = v;
} while (IS_NOT_NULL(node = NODE_CDR(node)));
}
break;
#ifdef USE_CALL
case NODE_CALL:
if (NODE_IS_RECURSION(node)) {
return BODY_MAY_BE_EMPTY_REC; /* tiny version */
}
else
r = quantifiers_memory_node_info(NODE_BODY(node));
break;
#endif
case NODE_QUANT:
{
QuantNode* qn = QUANT_(node);
if (qn->upper != 0) {
r = quantifiers_memory_node_info(NODE_BODY(node));
}
}
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
switch (en->type) {
case BAG_MEMORY:
if (NODE_IS_RECURSION(node)) {
return BODY_MAY_BE_EMPTY_REC;
}
return BODY_MAY_BE_EMPTY_MEM;
break;
case BAG_OPTION:
case BAG_STOP_BACKTRACK:
r = quantifiers_memory_node_info(NODE_BODY(node));
break;
case BAG_IF_ELSE:
{
int v;
r = quantifiers_memory_node_info(NODE_BODY(node));
if (IS_NOT_NULL(en->te.Then)) {
v = quantifiers_memory_node_info(en->te.Then);
if (v > r) r = v;
}
if (IS_NOT_NULL(en->te.Else)) {
v = quantifiers_memory_node_info(en->te.Else);
if (v > r) r = v;
}
}
break;
}
}
break;
case NODE_BACKREF:
case NODE_STRING:
case NODE_CTYPE:
case NODE_CCLASS:
case NODE_ANCHOR:
case NODE_GIMMICK:
default:
break;
}
return r;
}
#endif /* USE_STUBBORN_CHECK_CAPTURES_IN_EMPTY_REPEAT */
#ifdef USE_CALL
#ifdef __GNUC__
__inline
#endif
static int
check_call_reference(CallNode* cn, ScanEnv* env, int state)
{
MemEnv* mem_env = SCANENV_MEMENV(env);
if (cn->by_number != 0) {
int gnum = cn->called_gnum;
if (env->num_named > 0 &&
IS_SYNTAX_BV(env->syntax, ONIG_SYN_CAPTURE_ONLY_NAMED_GROUP) &&
! OPTON_CAPTURE_GROUP(env->options)) {
return ONIGERR_NUMBERED_BACKREF_OR_CALL_NOT_ALLOWED;
}
if (gnum > env->num_mem) {
onig_scan_env_set_error_string(env, ONIGERR_UNDEFINED_GROUP_REFERENCE,
cn->name, cn->name_end);
return ONIGERR_UNDEFINED_GROUP_REFERENCE;
}
set_call_attr:
NODE_CALL_BODY(cn) = mem_env[cn->called_gnum].mem_node;
if (IS_NULL(NODE_CALL_BODY(cn))) {
onig_scan_env_set_error_string(env, ONIGERR_UNDEFINED_NAME_REFERENCE,
cn->name, cn->name_end);
return ONIGERR_UNDEFINED_NAME_REFERENCE;
}
NODE_STATUS_ADD(NODE_CALL_BODY(cn), REFERENCED);
}
else {
int *refs;
int n = onig_name_to_group_numbers(env->reg, cn->name, cn->name_end, &refs);
if (n <= 0) {
onig_scan_env_set_error_string(env, ONIGERR_UNDEFINED_NAME_REFERENCE,
cn->name, cn->name_end);
return ONIGERR_UNDEFINED_NAME_REFERENCE;
}
else if (n > 1) {
onig_scan_env_set_error_string(env, ONIGERR_MULTIPLEX_DEFINITION_NAME_CALL,
cn->name, cn->name_end);
return ONIGERR_MULTIPLEX_DEFINITION_NAME_CALL;
}
else {
cn->called_gnum = refs[0];
goto set_call_attr;
}
}
return 0;
}
static void
tune_call2_call(Node* node)
{
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
do {
tune_call2_call(NODE_CAR(node));
} while (IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_QUANT:
tune_call2_call(NODE_BODY(node));
break;
case NODE_ANCHOR:
if (ANCHOR_HAS_BODY(ANCHOR_(node)))
tune_call2_call(NODE_BODY(node));
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
if (en->type == BAG_MEMORY) {
if (! NODE_IS_MARK1(node)) {
NODE_STATUS_ADD(node, MARK1);
tune_call2_call(NODE_BODY(node));
NODE_STATUS_REMOVE(node, MARK1);
}
}
else if (en->type == BAG_IF_ELSE) {
tune_call2_call(NODE_BODY(node));
if (IS_NOT_NULL(en->te.Then))
tune_call2_call(en->te.Then);
if (IS_NOT_NULL(en->te.Else))
tune_call2_call(en->te.Else);
}
else {
tune_call2_call(NODE_BODY(node));
}
}
break;
case NODE_CALL:
if (! NODE_IS_MARK1(node)) {
NODE_STATUS_ADD(node, MARK1);
{
CallNode* cn = CALL_(node);
Node* called = NODE_CALL_BODY(cn);
cn->entry_count++;
NODE_STATUS_ADD(called, CALLED);
BAG_(called)->m.entry_count++;
tune_call2_call(called);
}
NODE_STATUS_REMOVE(node, MARK1);
}
break;
default:
break;
}
}
static int
tune_call(Node* node, ScanEnv* env, int state)
{
int r;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
do {
r = tune_call(NODE_CAR(node), env, state);
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_QUANT:
if (QUANT_(node)->upper == 0)
state |= IN_ZERO_REPEAT;
r = tune_call(NODE_BODY(node), env, state);
break;
case NODE_ANCHOR:
if (ANCHOR_HAS_BODY(ANCHOR_(node)))
r = tune_call(NODE_BODY(node), env, state);
else
r = 0;
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
if (en->type == BAG_MEMORY) {
if ((state & IN_ZERO_REPEAT) != 0) {
NODE_STATUS_ADD(node, IN_ZERO_REPEAT);
BAG_(node)->m.entry_count--;
}
r = tune_call(NODE_BODY(node), env, state);
}
else if (en->type == BAG_IF_ELSE) {
r = tune_call(NODE_BODY(node), env, state);
if (r != 0) return r;
if (IS_NOT_NULL(en->te.Then)) {
r = tune_call(en->te.Then, env, state);
if (r != 0) return r;
}
if (IS_NOT_NULL(en->te.Else))
r = tune_call(en->te.Else, env, state);
}
else
r = tune_call(NODE_BODY(node), env, state);
}
break;
case NODE_CALL:
if ((state & IN_ZERO_REPEAT) != 0) {
NODE_STATUS_ADD(node, IN_ZERO_REPEAT);
CALL_(node)->entry_count--;
}
r = check_call_reference(CALL_(node), env, state);
break;
default:
r = 0;
break;
}
return r;
}
static int
tune_call2(Node* node)
{
int r = 0;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
do {
r = tune_call2(NODE_CAR(node));
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_QUANT:
if (QUANT_(node)->upper != 0)
r = tune_call2(NODE_BODY(node));
break;
case NODE_ANCHOR:
if (ANCHOR_HAS_BODY(ANCHOR_(node)))
r = tune_call2(NODE_BODY(node));
break;
case NODE_BAG:
if (! NODE_IS_IN_ZERO_REPEAT(node))
r = tune_call2(NODE_BODY(node));
{
BagNode* en = BAG_(node);
if (r != 0) return r;
if (en->type == BAG_IF_ELSE) {
if (IS_NOT_NULL(en->te.Then)) {
r = tune_call2(en->te.Then);
if (r != 0) return r;
}
if (IS_NOT_NULL(en->te.Else))
r = tune_call2(en->te.Else);
}
}
break;
case NODE_CALL:
if (! NODE_IS_IN_ZERO_REPEAT(node)) {
tune_call2_call(node);
}
break;
default:
break;
}
return r;
}
static void
tune_called_state_call(Node* node, int state)
{
switch (NODE_TYPE(node)) {
case NODE_ALT:
state |= IN_ALT;
/* fall */
case NODE_LIST:
do {
tune_called_state_call(NODE_CAR(node), state);
} while (IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_QUANT:
{
QuantNode* qn = QUANT_(node);
if (IS_INFINITE_REPEAT(qn->upper) || qn->upper >= 2)
state |= IN_REAL_REPEAT;
if (qn->lower != qn->upper)
state |= IN_VAR_REPEAT;
tune_called_state_call(NODE_QUANT_BODY(qn), state);
}
break;
case NODE_ANCHOR:
{
AnchorNode* an = ANCHOR_(node);
switch (an->type) {
case ANCR_PREC_READ_NOT:
case ANCR_LOOK_BEHIND_NOT:
state |= IN_NOT;
/* fall */
case ANCR_PREC_READ:
case ANCR_LOOK_BEHIND:
tune_called_state_call(NODE_ANCHOR_BODY(an), state);
break;
default:
break;
}
}
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
if (en->type == BAG_MEMORY) {
if (NODE_IS_MARK1(node)) {
if ((~en->m.called_state & state) != 0) {
en->m.called_state |= state;
tune_called_state_call(NODE_BODY(node), state);
}
}
else {
NODE_STATUS_ADD(node, MARK1);
en->m.called_state |= state;
tune_called_state_call(NODE_BODY(node), state);
NODE_STATUS_REMOVE(node, MARK1);
}
}
else if (en->type == BAG_IF_ELSE) {
state |= IN_ALT;
tune_called_state_call(NODE_BODY(node), state);
if (IS_NOT_NULL(en->te.Then)) {
tune_called_state_call(en->te.Then, state);
}
if (IS_NOT_NULL(en->te.Else))
tune_called_state_call(en->te.Else, state);
}
else {
tune_called_state_call(NODE_BODY(node), state);
}
}
break;
case NODE_CALL:
tune_called_state_call(NODE_BODY(node), state);
break;
default:
break;
}
}
static void
tune_called_state(Node* node, int state)
{
switch (NODE_TYPE(node)) {
case NODE_ALT:
state |= IN_ALT;
/* fall */
case NODE_LIST:
do {
tune_called_state(NODE_CAR(node), state);
} while (IS_NOT_NULL(node = NODE_CDR(node)));
break;
#ifdef USE_CALL
case NODE_CALL:
tune_called_state_call(node, state);
break;
#endif
case NODE_BAG:
{
BagNode* en = BAG_(node);
switch (en->type) {
case BAG_MEMORY:
if (en->m.entry_count > 1)
state |= IN_MULTI_ENTRY;
en->m.called_state |= state;
/* fall */
case BAG_OPTION:
case BAG_STOP_BACKTRACK:
tune_called_state(NODE_BODY(node), state);
break;
case BAG_IF_ELSE:
state |= IN_ALT;
tune_called_state(NODE_BODY(node), state);
if (IS_NOT_NULL(en->te.Then))
tune_called_state(en->te.Then, state);
if (IS_NOT_NULL(en->te.Else))
tune_called_state(en->te.Else, state);
break;
}
}
break;
case NODE_QUANT:
{
QuantNode* qn = QUANT_(node);
if (IS_INFINITE_REPEAT(qn->upper) || qn->upper >= 2)
state |= IN_REAL_REPEAT;
if (qn->lower != qn->upper)
state |= IN_VAR_REPEAT;
tune_called_state(NODE_QUANT_BODY(qn), state);
}
break;
case NODE_ANCHOR:
{
AnchorNode* an = ANCHOR_(node);
switch (an->type) {
case ANCR_PREC_READ_NOT:
case ANCR_LOOK_BEHIND_NOT:
state |= IN_NOT;
/* fall */
case ANCR_PREC_READ:
case ANCR_LOOK_BEHIND:
tune_called_state(NODE_ANCHOR_BODY(an), state);
break;
default:
break;
}
}
break;
case NODE_BACKREF:
case NODE_STRING:
case NODE_CTYPE:
case NODE_CCLASS:
case NODE_GIMMICK:
default:
break;
}
}
#endif /* USE_CALL */
#ifdef __GNUC__
__inline
#endif
static int
tune_anchor(Node* node, regex_t* reg, int state, ScanEnv* env)
{
int r;
AnchorNode* an = ANCHOR_(node);
switch (an->type) {
case ANCR_PREC_READ:
r = tune_tree(NODE_ANCHOR_BODY(an), reg, state, env);
break;
case ANCR_PREC_READ_NOT:
r = tune_tree(NODE_ANCHOR_BODY(an), reg, (state | IN_NOT), env);
break;
case ANCR_LOOK_BEHIND:
case ANCR_LOOK_BEHIND_NOT:
r = tune_look_behind(node, reg, state, env);
break;
default:
r = 0;
break;
}
return r;
}
#ifdef __GNUC__
__inline
#endif
static int
tune_quant(Node* node, regex_t* reg, int state, ScanEnv* env)
{
int r;
QuantNode* qn = QUANT_(node);
Node* body = NODE_BODY(node);
if ((state & IN_REAL_REPEAT) != 0) {
NODE_STATUS_ADD(node, IN_REAL_REPEAT);
}
if ((state & IN_MULTI_ENTRY) != 0) {
NODE_STATUS_ADD(node, IN_MULTI_ENTRY);
}
if (IS_INFINITE_REPEAT(qn->upper) || qn->upper >= 1) {
OnigLen d = node_min_byte_len(body, env);
if (d == 0) {
#ifdef USE_STUBBORN_CHECK_CAPTURES_IN_EMPTY_REPEAT
qn->emptiness = quantifiers_memory_node_info(body);
#else
qn->emptiness = BODY_MAY_BE_EMPTY;
#endif
}
}
if (IS_INFINITE_REPEAT(qn->upper) || qn->upper >= 2)
state |= IN_REAL_REPEAT;
if (qn->lower != qn->upper)
state |= IN_VAR_REPEAT;
r = tune_tree(body, reg, state, env);
if (r != 0) return r;
/* expand string */
#define EXPAND_STRING_MAX_LENGTH 100
if (NODE_TYPE(body) == NODE_STRING) {
if (!IS_INFINITE_REPEAT(qn->lower) && qn->lower == qn->upper &&
qn->lower > 1 && qn->lower <= EXPAND_STRING_MAX_LENGTH) {
int len = NODE_STRING_LEN(body);
if (len * qn->lower <= EXPAND_STRING_MAX_LENGTH) {
int i, n = qn->lower;
node_conv_to_str_node(node, body);
for (i = 0; i < n; i++) {
r = node_str_node_cat(node, body);
if (r != 0) return r;
}
onig_node_free(body);
return r;
}
}
}
if (qn->greedy && (qn->emptiness == BODY_IS_NOT_EMPTY)) {
if (NODE_TYPE(body) == NODE_QUANT) {
QuantNode* tqn = QUANT_(body);
if (IS_NOT_NULL(tqn->head_exact)) {
qn->head_exact = tqn->head_exact;
tqn->head_exact = NULL;
}
}
else {
qn->head_exact = get_tree_head_literal(NODE_BODY(node), 1, reg);
}
}
return r;
}
/* tune_tree does the following work.
1. check empty loop. (set qn->emptiness)
2. expand ignore-case in char class.
3. set memory status bit flags. (reg->mem_stats)
4. set qn->head_exact for [push, exact] -> [push_or_jump_exact1, exact].
5. find invalid patterns in look-behind.
6. expand repeated string.
*/
static int
tune_tree(Node* node, regex_t* reg, int state, ScanEnv* env)
{
int r = 0;
switch (NODE_TYPE(node)) {
case NODE_LIST:
{
Node* prev = NULL_NODE;
do {
r = tune_tree(NODE_CAR(node), reg, state, env);
if (IS_NOT_NULL(prev) && r == 0) {
r = tune_next(prev, NODE_CAR(node), reg);
}
prev = NODE_CAR(node);
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
}
break;
case NODE_ALT:
do {
r = tune_tree(NODE_CAR(node), reg, (state | IN_ALT), env);
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_STRING:
if (NODE_IS_IGNORECASE(node) && ! NODE_STRING_IS_CRUDE(node)) {
r = unravel_case_fold_string(node, reg, state);
}
break;
case NODE_BACKREF:
{
int i;
int* p;
BackRefNode* br = BACKREF_(node);
p = BACKREFS_P(br);
for (i = 0; i < br->back_num; i++) {
if (p[i] > env->num_mem) return ONIGERR_INVALID_BACKREF;
MEM_STATUS_ON(env->backrefed_mem, p[i]);
#if 0
#ifdef USE_BACKREF_WITH_LEVEL
if (NODE_IS_NEST_LEVEL(node)) {
MEM_STATUS_ON(env->backtrack_mem, p[i]);
}
#endif
#else
/* More precisely, it should be checked whether alt/repeat exists before
the subject capture node, and then this backreference position
exists before (or in) the capture node. */
MEM_STATUS_ON(env->backtrack_mem, p[i]);
#endif
}
}
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
switch (en->type) {
case BAG_OPTION:
{
OnigOptionType options = reg->options;
reg->options = BAG_(node)->o.options;
r = tune_tree(NODE_BODY(node), reg, state, env);
reg->options = options;
}
break;
case BAG_MEMORY:
#ifdef USE_CALL
state |= en->m.called_state;
#endif
if ((state & (IN_ALT | IN_NOT | IN_VAR_REPEAT | IN_MULTI_ENTRY)) != 0
|| NODE_IS_RECURSION(node)) {
MEM_STATUS_ON(env->backtrack_mem, en->m.regnum);
}
r = tune_tree(NODE_BODY(node), reg, state, env);
break;
case BAG_STOP_BACKTRACK:
{
Node* target = NODE_BODY(node);
r = tune_tree(target, reg, state, env);
if (NODE_TYPE(target) == NODE_QUANT) {
QuantNode* tqn = QUANT_(target);
if (IS_INFINITE_REPEAT(tqn->upper) && tqn->lower <= 1 &&
tqn->greedy != 0) { /* (?>a*), a*+ etc... */
if (is_strict_real_node(NODE_BODY(target)))
NODE_STATUS_ADD(node, STRICT_REAL_REPEAT);
}
}
}
break;
case BAG_IF_ELSE:
r = tune_tree(NODE_BODY(node), reg, (state | IN_ALT), env);
if (r != 0) return r;
if (IS_NOT_NULL(en->te.Then)) {
r = tune_tree(en->te.Then, reg, (state | IN_ALT), env);
if (r != 0) return r;
}
if (IS_NOT_NULL(en->te.Else))
r = tune_tree(en->te.Else, reg, (state | IN_ALT), env);
break;
}
}
break;
case NODE_QUANT:
r = tune_quant(node, reg, state, env);
break;
case NODE_ANCHOR:
r = tune_anchor(node, reg, state, env);
break;
#ifdef USE_CALL
case NODE_CALL:
#endif
case NODE_CTYPE:
case NODE_CCLASS:
case NODE_GIMMICK:
default:
break;
}
return r;
}
static int
set_sunday_quick_search_or_bmh_skip_table(regex_t* reg, int case_expand,
UChar* s, UChar* end,
UChar skip[], int* roffset)
{
int i, j, k, len, offset;
int n, clen;
UChar* p;
OnigEncoding enc;
OnigCaseFoldCodeItem items[ONIGENC_GET_CASE_FOLD_CODES_MAX_NUM];
UChar buf[ONIGENC_MBC_CASE_FOLD_MAXLEN];
enc = reg->enc;
offset = ENC_GET_SKIP_OFFSET(enc);
if (offset == ENC_SKIP_OFFSET_1_OR_0) {
UChar* p = s;
while (1) {
len = enclen(enc, p);
if (p + len >= end) {
if (len == 1) offset = 1;
else offset = 0;
break;
}
p += len;
}
}
len = (int )(end - s);
if (len + offset >= UCHAR_MAX)
return ONIGERR_PARSER_BUG;
*roffset = offset;
for (i = 0; i < CHAR_MAP_SIZE; i++) {
skip[i] = (UChar )(len + offset);
}
for (p = s; p < end; ) {
int z;
clen = enclen(enc, p);
if (p + clen > end) clen = (int )(end - p);
len = (int )(end - p);
for (j = 0; j < clen; j++) {
z = len - j + (offset - 1);
if (z <= 0) break;
skip[p[j]] = z;
}
if (case_expand != 0) {
n = ONIGENC_GET_CASE_FOLD_CODES_BY_STR(enc, reg->case_fold_flag,
p, end, items);
for (k = 0; k < n; k++) {
ONIGENC_CODE_TO_MBC(enc, items[k].code[0], buf);
for (j = 0; j < clen; j++) {
z = len - j + (offset - 1);
if (z <= 0) break;
if (skip[buf[j]] > z)
skip[buf[j]] = z;
}
}
}
p += clen;
}
return 0;
}
#define OPT_EXACT_MAXLEN 24
#if OPT_EXACT_MAXLEN >= UCHAR_MAX
#error Too big OPT_EXACT_MAXLEN
#endif
typedef struct {
MinMaxLen mm;
OnigEncoding enc;
OnigCaseFoldType case_fold_flag;
ScanEnv* scan_env;
} OptEnv;
typedef struct {
int left;
int right;
} OptAnc;
typedef struct {
MinMaxLen mm; /* position */
OptAnc anc;
int reach_end;
int len;
UChar s[OPT_EXACT_MAXLEN];
} OptStr;
typedef struct {
MinMaxLen mm; /* position */
OptAnc anc;
int value; /* weighted value */
UChar map[CHAR_MAP_SIZE];
} OptMap;
typedef struct {
MinMaxLen len;
OptAnc anc;
OptStr sb; /* boundary */
OptStr sm; /* middle */
OptStr spr; /* prec read (?=...) */
OptMap map; /* boundary */
} OptNode;
static int
map_position_value(OnigEncoding enc, int i)
{
static const short int Vals[] = {
5, 1, 1, 1, 1, 1, 1, 1, 1, 10, 10, 1, 1, 10, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
12, 4, 7, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5,
5, 6, 6, 6, 6, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 6, 5, 5, 5,
5, 6, 6, 6, 6, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 1
};
if (i < (int )(sizeof(Vals)/sizeof(Vals[0]))) {
if (i == 0 && ONIGENC_MBC_MINLEN(enc) > 1)
return 20;
else
return (int )Vals[i];
}
else
return 4; /* Take it easy. */
}
static int
distance_value(MinMaxLen* mm)
{
/* 1000 / (min-max-dist + 1) */
static const short int dist_vals[] = {
1000, 500, 333, 250, 200, 167, 143, 125, 111, 100,
91, 83, 77, 71, 67, 63, 59, 56, 53, 50,
48, 45, 43, 42, 40, 38, 37, 36, 34, 33,
32, 31, 30, 29, 29, 28, 27, 26, 26, 25,
24, 24, 23, 23, 22, 22, 21, 21, 20, 20,
20, 19, 19, 19, 18, 18, 18, 17, 17, 17,
16, 16, 16, 16, 15, 15, 15, 15, 14, 14,
14, 14, 14, 14, 13, 13, 13, 13, 13, 13,
12, 12, 12, 12, 12, 12, 11, 11, 11, 11,
11, 11, 11, 11, 11, 10, 10, 10, 10, 10
};
OnigLen d;
if (mm->max == INFINITE_LEN) return 0;
d = mm->max - mm->min;
if (d < (OnigLen )(sizeof(dist_vals)/sizeof(dist_vals[0])))
/* return dist_vals[d] * 16 / (mm->min + 12); */
return (int )dist_vals[d];
else
return 1;
}
static int
comp_distance_value(MinMaxLen* d1, MinMaxLen* d2, int v1, int v2)
{
if (v2 <= 0) return -1;
if (v1 <= 0) return 1;
v1 *= distance_value(d1);
v2 *= distance_value(d2);
if (v2 > v1) return 1;
if (v2 < v1) return -1;
if (d2->min < d1->min) return 1;
if (d2->min > d1->min) return -1;
return 0;
}
static void
copy_opt_env(OptEnv* to, OptEnv* from)
{
*to = *from;
}
static void
clear_opt_anc_info(OptAnc* a)
{
a->left = 0;
a->right = 0;
}
static void
copy_opt_anc_info(OptAnc* to, OptAnc* from)
{
*to = *from;
}
static void
concat_opt_anc_info(OptAnc* to, OptAnc* left, OptAnc* right,
OnigLen left_len, OnigLen right_len)
{
clear_opt_anc_info(to);
to->left = left->left;
if (left_len == 0) {
to->left |= right->left;
}
to->right = right->right;
if (right_len == 0) {
to->right |= left->right;
}
else {
to->right |= (left->right & ANCR_PREC_READ_NOT);
}
}
static int
is_left(int a)
{
if (a == ANCR_END_BUF || a == ANCR_SEMI_END_BUF ||
a == ANCR_END_LINE || a == ANCR_PREC_READ || a == ANCR_PREC_READ_NOT)
return 0;
return 1;
}
static int
is_set_opt_anc_info(OptAnc* to, int anc)
{
if ((to->left & anc) != 0) return 1;
return ((to->right & anc) != 0 ? 1 : 0);
}
static void
add_opt_anc_info(OptAnc* to, int anc)
{
if (is_left(anc))
to->left |= anc;
else
to->right |= anc;
}
static void
remove_opt_anc_info(OptAnc* to, int anc)
{
if (is_left(anc))
to->left &= ~anc;
else
to->right &= ~anc;
}
static void
alt_merge_opt_anc_info(OptAnc* to, OptAnc* add)
{
to->left &= add->left;
to->right &= add->right;
}
static int
is_full_opt_exact(OptStr* e)
{
return e->len >= OPT_EXACT_MAXLEN;
}
static void
clear_opt_exact(OptStr* e)
{
mml_clear(&e->mm);
clear_opt_anc_info(&e->anc);
e->reach_end = 0;
e->len = 0;
e->s[0] = '\0';
}
static void
copy_opt_exact(OptStr* to, OptStr* from)
{
*to = *from;
}
static int
concat_opt_exact(OptStr* to, OptStr* add, OnigEncoding enc)
{
int i, j, len, r;
UChar *p, *end;
OptAnc tanc;
r = 0;
p = add->s;
end = p + add->len;
for (i = to->len; p < end; ) {
len = enclen(enc, p);
if (i + len > OPT_EXACT_MAXLEN) {
r = 1; /* 1:full */
break;
}
for (j = 0; j < len && p < end; j++)
to->s[i++] = *p++;
}
to->len = i;
to->reach_end = (p == end ? add->reach_end : 0);
concat_opt_anc_info(&tanc, &to->anc, &add->anc, 1, 1);
if (! to->reach_end) tanc.right = 0;
copy_opt_anc_info(&to->anc, &tanc);
return r;
}
static void
concat_opt_exact_str(OptStr* to, UChar* s, UChar* end, OnigEncoding enc)
{
int i, j, len;
UChar *p;
for (i = to->len, p = s; p < end && i < OPT_EXACT_MAXLEN; ) {
len = enclen(enc, p);
if (i + len > OPT_EXACT_MAXLEN) break;
for (j = 0; j < len && p < end; j++)
to->s[i++] = *p++;
}
to->len = i;
if (p >= end)
to->reach_end = 1;
}
static void
alt_merge_opt_exact(OptStr* to, OptStr* add, OptEnv* env)
{
int i, j, len;
if (add->len == 0 || to->len == 0) {
clear_opt_exact(to);
return ;
}
if (! mml_is_equal(&to->mm, &add->mm)) {
clear_opt_exact(to);
return ;
}
for (i = 0; i < to->len && i < add->len; ) {
if (to->s[i] != add->s[i]) break;
len = enclen(env->enc, to->s + i);
for (j = 1; j < len; j++) {
if (to->s[i+j] != add->s[i+j]) break;
}
if (j < len) break;
i += len;
}
if (! add->reach_end || i < add->len || i < to->len) {
to->reach_end = 0;
}
to->len = i;
alt_merge_opt_anc_info(&to->anc, &add->anc);
if (! to->reach_end) to->anc.right = 0;
}
static void
select_opt_exact(OnigEncoding enc, OptStr* now, OptStr* alt)
{
int vn, va;
vn = now->len;
va = alt->len;
if (va == 0) {
return ;
}
else if (vn == 0) {
copy_opt_exact(now, alt);
return ;
}
else if (vn <= 2 && va <= 2) {
/* ByteValTable[x] is big value --> low price */
va = map_position_value(enc, now->s[0]);
vn = map_position_value(enc, alt->s[0]);
if (now->len > 1) vn += 5;
if (alt->len > 1) va += 5;
}
vn *= 2;
va *= 2;
if (comp_distance_value(&now->mm, &alt->mm, vn, va) > 0)
copy_opt_exact(now, alt);
}
static void
clear_opt_map(OptMap* map)
{
static const OptMap clean_info = {
{0, 0}, {0, 0}, 0,
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
}
};
xmemcpy(map, &clean_info, sizeof(OptMap));
}
static void
copy_opt_map(OptMap* to, OptMap* from)
{
*to = *from;
}
static void
add_char_opt_map(OptMap* m, UChar c, OnigEncoding enc)
{
if (m->map[c] == 0) {
m->map[c] = 1;
m->value += map_position_value(enc, c);
}
}
static void
select_opt_map(OptMap* now, OptMap* alt)
{
static int z = 1<<15; /* 32768: something big value */
int vn, va;
if (alt->value == 0) return ;
if (now->value == 0) {
copy_opt_map(now, alt);
return ;
}
vn = z / now->value;
va = z / alt->value;
if (comp_distance_value(&now->mm, &alt->mm, vn, va) > 0)
copy_opt_map(now, alt);
}
static int
comp_opt_exact_or_map(OptStr* e, OptMap* m)
{
#define COMP_EM_BASE 20
int ae, am;
int case_value;
if (m->value <= 0) return -1;
case_value = 3;
ae = COMP_EM_BASE * e->len * case_value;
am = COMP_EM_BASE * 5 * 2 / m->value;
return comp_distance_value(&e->mm, &m->mm, ae, am);
}
static void
alt_merge_opt_map(OnigEncoding enc, OptMap* to, OptMap* add)
{
int i, val;
/* if (! mml_is_equal(&to->mm, &add->mm)) return ; */
if (to->value == 0) return ;
if (add->value == 0 || to->mm.max < add->mm.min) {
clear_opt_map(to);
return ;
}
mml_alt_merge(&to->mm, &add->mm);
val = 0;
for (i = 0; i < CHAR_MAP_SIZE; i++) {
if (add->map[i])
to->map[i] = 1;
if (to->map[i])
val += map_position_value(enc, i);
}
to->value = val;
alt_merge_opt_anc_info(&to->anc, &add->anc);
}
static void
set_bound_node_opt_info(OptNode* opt, MinMaxLen* plen)
{
mml_copy(&(opt->sb.mm), plen);
mml_copy(&(opt->spr.mm), plen);
mml_copy(&(opt->map.mm), plen);
}
static void
clear_node_opt_info(OptNode* opt)
{
mml_clear(&opt->len);
clear_opt_anc_info(&opt->anc);
clear_opt_exact(&opt->sb);
clear_opt_exact(&opt->sm);
clear_opt_exact(&opt->spr);
clear_opt_map(&opt->map);
}
static void
copy_node_opt_info(OptNode* to, OptNode* from)
{
*to = *from;
}
static void
concat_left_node_opt_info(OnigEncoding enc, OptNode* to, OptNode* add)
{
int sb_reach, sm_reach;
OptAnc tanc;
concat_opt_anc_info(&tanc, &to->anc, &add->anc, to->len.max, add->len.max);
copy_opt_anc_info(&to->anc, &tanc);
if (add->sb.len > 0 && to->len.max == 0) {
concat_opt_anc_info(&tanc, &to->anc, &add->sb.anc, to->len.max, add->len.max);
copy_opt_anc_info(&add->sb.anc, &tanc);
}
if (add->map.value > 0 && to->len.max == 0) {
if (add->map.mm.max == 0)
add->map.anc.left |= to->anc.left;
}
sb_reach = to->sb.reach_end;
sm_reach = to->sm.reach_end;
if (add->len.max != 0)
to->sb.reach_end = to->sm.reach_end = 0;
if (add->sb.len > 0) {
if (sb_reach) {
concat_opt_exact(&to->sb, &add->sb, enc);
clear_opt_exact(&add->sb);
}
else if (sm_reach) {
concat_opt_exact(&to->sm, &add->sb, enc);
clear_opt_exact(&add->sb);
}
}
select_opt_exact(enc, &to->sm, &add->sb);
select_opt_exact(enc, &to->sm, &add->sm);
if (to->spr.len > 0) {
if (add->len.max > 0) {
if (to->spr.mm.max == 0)
select_opt_exact(enc, &to->sb, &to->spr);
else
select_opt_exact(enc, &to->sm, &to->spr);
}
}
else if (add->spr.len > 0) {
copy_opt_exact(&to->spr, &add->spr);
}
select_opt_map(&to->map, &add->map);
mml_add(&to->len, &add->len);
}
static void
alt_merge_node_opt_info(OptNode* to, OptNode* add, OptEnv* env)
{
alt_merge_opt_anc_info(&to->anc, &add->anc);
alt_merge_opt_exact(&to->sb, &add->sb, env);
alt_merge_opt_exact(&to->sm, &add->sm, env);
alt_merge_opt_exact(&to->spr, &add->spr, env);
alt_merge_opt_map(env->enc, &to->map, &add->map);
mml_alt_merge(&to->len, &add->len);
}
#define MAX_NODE_OPT_INFO_REF_COUNT 5
static int
optimize_nodes(Node* node, OptNode* opt, OptEnv* env)
{
int i;
int r;
OptNode xo;
OnigEncoding enc;
r = 0;
enc = env->enc;
clear_node_opt_info(opt);
set_bound_node_opt_info(opt, &env->mm);
switch (NODE_TYPE(node)) {
case NODE_LIST:
{
OptEnv nenv;
Node* nd = node;
copy_opt_env(&nenv, env);
do {
r = optimize_nodes(NODE_CAR(nd), &xo, &nenv);
if (r == 0) {
mml_add(&nenv.mm, &xo.len);
concat_left_node_opt_info(enc, opt, &xo);
}
} while (r == 0 && IS_NOT_NULL(nd = NODE_CDR(nd)));
}
break;
case NODE_ALT:
{
Node* nd = node;
do {
r = optimize_nodes(NODE_CAR(nd), &xo, env);
if (r == 0) {
if (nd == node) copy_node_opt_info(opt, &xo);
else alt_merge_node_opt_info(opt, &xo, env);
}
} while ((r == 0) && IS_NOT_NULL(nd = NODE_CDR(nd)));
}
break;
case NODE_STRING:
{
StrNode* sn = STR_(node);
int slen = (int )(sn->end - sn->s);
concat_opt_exact_str(&opt->sb, sn->s, sn->end, enc);
if (slen > 0) {
add_char_opt_map(&opt->map, *(sn->s), enc);
}
mml_set_min_max(&opt->len, slen, slen);
}
break;
case NODE_CCLASS:
{
int z;
CClassNode* cc = CCLASS_(node);
/* no need to check ignore case. (set in tune_tree()) */
if (IS_NOT_NULL(cc->mbuf) || IS_NCCLASS_NOT(cc)) {
OnigLen min = ONIGENC_MBC_MINLEN(enc);
OnigLen max = ONIGENC_MBC_MAXLEN_DIST(enc);
mml_set_min_max(&opt->len, min, max);
}
else {
for (i = 0; i < SINGLE_BYTE_SIZE; i++) {
z = BITSET_AT(cc->bs, i);
if ((z && ! IS_NCCLASS_NOT(cc)) || (! z && IS_NCCLASS_NOT(cc))) {
add_char_opt_map(&opt->map, (UChar )i, enc);
}
}
mml_set_min_max(&opt->len, 1, 1);
}
}
break;
case NODE_CTYPE:
{
int min, max;
int range;
max = ONIGENC_MBC_MAXLEN_DIST(enc);
if (max == 1) {
min = 1;
switch (CTYPE_(node)->ctype) {
case CTYPE_ANYCHAR:
break;
case ONIGENC_CTYPE_WORD:
range = CTYPE_(node)->ascii_mode != 0 ? 128 : SINGLE_BYTE_SIZE;
if (CTYPE_(node)->not != 0) {
for (i = 0; i < range; i++) {
if (! ONIGENC_IS_CODE_WORD(enc, i)) {
add_char_opt_map(&opt->map, (UChar )i, enc);
}
}
for (i = range; i < SINGLE_BYTE_SIZE; i++) {
add_char_opt_map(&opt->map, (UChar )i, enc);
}
}
else {
for (i = 0; i < range; i++) {
if (ONIGENC_IS_CODE_WORD(enc, i)) {
add_char_opt_map(&opt->map, (UChar )i, enc);
}
}
}
break;
}
}
else {
min = ONIGENC_MBC_MINLEN(enc);
}
mml_set_min_max(&opt->len, min, max);
}
break;
case NODE_ANCHOR:
switch (ANCHOR_(node)->type) {
case ANCR_BEGIN_BUF:
case ANCR_BEGIN_POSITION:
case ANCR_BEGIN_LINE:
case ANCR_END_BUF:
case ANCR_SEMI_END_BUF:
case ANCR_END_LINE:
case ANCR_PREC_READ_NOT:
case ANCR_LOOK_BEHIND:
add_opt_anc_info(&opt->anc, ANCHOR_(node)->type);
break;
case ANCR_PREC_READ:
{
r = optimize_nodes(NODE_BODY(node), &xo, env);
if (r == 0) {
if (xo.sb.len > 0)
copy_opt_exact(&opt->spr, &xo.sb);
else if (xo.sm.len > 0)
copy_opt_exact(&opt->spr, &xo.sm);
opt->spr.reach_end = 0;
if (xo.map.value > 0)
copy_opt_map(&opt->map, &xo.map);
}
}
break;
case ANCR_LOOK_BEHIND_NOT:
break;
}
break;
case NODE_BACKREF:
if (! NODE_IS_CHECKER(node)) {
OnigLen min, max;
min = node_min_byte_len(node, env->scan_env);
max = node_max_byte_len(node, env->scan_env);
mml_set_min_max(&opt->len, min, max);
}
break;
#ifdef USE_CALL
case NODE_CALL:
if (NODE_IS_RECURSION(node))
mml_set_min_max(&opt->len, 0, INFINITE_LEN);
else {
r = optimize_nodes(NODE_BODY(node), opt, env);
}
break;
#endif
case NODE_QUANT:
{
OnigLen min, max;
QuantNode* qn = QUANT_(node);
/* Issue #175
ex. /\g<1>{0}(?<=|())/
Empty and unused nodes in look-behind is removed in
tune_look_behind().
Called group nodes are assigned to be not called if the caller side is
inside of zero-repetition.
As a result, the nodes are considered unused.
*/
if (qn->upper == 0) {
mml_set_min_max(&opt->len, 0, 0);
break;
}
r = optimize_nodes(NODE_BODY(node), &xo, env);
if (r != 0) break;
if (qn->lower > 0) {
copy_node_opt_info(opt, &xo);
if (xo.sb.len > 0) {
if (xo.sb.reach_end) {
for (i = 2; i <= qn->lower && ! is_full_opt_exact(&opt->sb); i++) {
int rc = concat_opt_exact(&opt->sb, &xo.sb, enc);
if (rc > 0) break;
}
if (i < qn->lower) opt->sb.reach_end = 0;
}
}
if (qn->lower != qn->upper) {
opt->sb.reach_end = 0;
opt->sm.reach_end = 0;
}
if (qn->lower > 1)
opt->sm.reach_end = 0;
}
if (IS_INFINITE_REPEAT(qn->upper)) {
if (env->mm.max == 0 &&
NODE_IS_ANYCHAR(NODE_BODY(node)) && qn->greedy != 0) {
if (NODE_IS_MULTILINE(NODE_QUANT_BODY(qn)))
add_opt_anc_info(&opt->anc, ANCR_ANYCHAR_INF_ML);
else
add_opt_anc_info(&opt->anc, ANCR_ANYCHAR_INF);
}
max = (xo.len.max > 0 ? INFINITE_LEN : 0);
}
else {
max = distance_multiply(xo.len.max, qn->upper);
}
min = distance_multiply(xo.len.min, qn->lower);
mml_set_min_max(&opt->len, min, max);
}
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
switch (en->type) {
case BAG_STOP_BACKTRACK:
case BAG_OPTION:
r = optimize_nodes(NODE_BODY(node), opt, env);
break;
case BAG_MEMORY:
#ifdef USE_CALL
en->opt_count++;
if (en->opt_count > MAX_NODE_OPT_INFO_REF_COUNT) {
OnigLen min, max;
min = 0;
max = INFINITE_LEN;
if (NODE_IS_FIXED_MIN(node)) min = en->min_len;
if (NODE_IS_FIXED_MAX(node)) max = en->max_len;
mml_set_min_max(&opt->len, min, max);
}
else
#endif
{
r = optimize_nodes(NODE_BODY(node), opt, env);
if (is_set_opt_anc_info(&opt->anc, ANCR_ANYCHAR_INF_MASK)) {
if (MEM_STATUS_AT0(env->scan_env->backrefed_mem, en->m.regnum))
remove_opt_anc_info(&opt->anc, ANCR_ANYCHAR_INF_MASK);
}
}
break;
case BAG_IF_ELSE:
{
OptEnv nenv;
copy_opt_env(&nenv, env);
r = optimize_nodes(NODE_BAG_BODY(en), &xo, &nenv);
if (r == 0) {
mml_add(&nenv.mm, &xo.len);
concat_left_node_opt_info(enc, opt, &xo);
if (IS_NOT_NULL(en->te.Then)) {
r = optimize_nodes(en->te.Then, &xo, &nenv);
if (r == 0) {
concat_left_node_opt_info(enc, opt, &xo);
}
}
if (IS_NOT_NULL(en->te.Else)) {
r = optimize_nodes(en->te.Else, &xo, env);
if (r == 0)
alt_merge_node_opt_info(opt, &xo, env);
}
}
}
break;
}
}
break;
case NODE_GIMMICK:
break;
default:
#ifdef ONIG_DEBUG
fprintf(DBGFP, "optimize_nodes: undefined node type %d\n", NODE_TYPE(node));
#endif
r = ONIGERR_TYPE_BUG;
break;
}
return r;
}
static int
set_optimize_exact(regex_t* reg, OptStr* e)
{
int r;
int allow_reverse;
if (e->len == 0) return 0;
reg->exact = (UChar* )xmalloc(e->len);
CHECK_NULL_RETURN_MEMERR(reg->exact);
xmemcpy(reg->exact, e->s, e->len);
reg->exact_end = reg->exact + e->len;
allow_reverse =
ONIGENC_IS_ALLOWED_REVERSE_MATCH(reg->enc, reg->exact, reg->exact_end);
if (e->len >= 2 || (e->len >= 1 && allow_reverse)) {
r = set_sunday_quick_search_or_bmh_skip_table(reg, 0,
reg->exact, reg->exact_end,
reg->map, &(reg->map_offset));
if (r != 0) return r;
reg->optimize = (allow_reverse != 0
? OPTIMIZE_STR_FAST
: OPTIMIZE_STR_FAST_STEP_FORWARD);
}
else {
reg->optimize = OPTIMIZE_STR;
}
reg->dist_min = e->mm.min;
reg->dist_max = e->mm.max;
if (reg->dist_min != INFINITE_LEN) {
int n = (int )(reg->exact_end - reg->exact);
reg->threshold_len = reg->dist_min + n;
}
return 0;
}
static void
set_optimize_map(regex_t* reg, OptMap* m)
{
int i;
for (i = 0; i < CHAR_MAP_SIZE; i++)
reg->map[i] = m->map[i];
reg->optimize = OPTIMIZE_MAP;
reg->dist_min = m->mm.min;
reg->dist_max = m->mm.max;
if (reg->dist_min != INFINITE_LEN) {
reg->threshold_len = reg->dist_min + ONIGENC_MBC_MINLEN(reg->enc);
}
}
static void
set_sub_anchor(regex_t* reg, OptAnc* anc)
{
reg->sub_anchor |= anc->left & ANCR_BEGIN_LINE;
reg->sub_anchor |= anc->right & ANCR_END_LINE;
}
#if defined(ONIG_DEBUG_COMPILE) || defined(ONIG_DEBUG_MATCH)
static void print_optimize_info(FILE* f, regex_t* reg);
#endif
static int
set_optimize_info_from_tree(Node* node, regex_t* reg, ScanEnv* scan_env)
{
int r;
OptNode opt;
OptEnv env;
env.enc = reg->enc;
env.case_fold_flag = reg->case_fold_flag;
env.scan_env = scan_env;
mml_clear(&env.mm);
r = optimize_nodes(node, &opt, &env);
if (r != 0) return r;
reg->anchor = opt.anc.left & (ANCR_BEGIN_BUF |
ANCR_BEGIN_POSITION | ANCR_ANYCHAR_INF | ANCR_ANYCHAR_INF_ML |
ANCR_LOOK_BEHIND);
if ((opt.anc.left & (ANCR_LOOK_BEHIND | ANCR_PREC_READ_NOT)) != 0)
reg->anchor &= ~ANCR_ANYCHAR_INF_ML;
reg->anchor |= opt.anc.right & (ANCR_END_BUF | ANCR_SEMI_END_BUF |
ANCR_PREC_READ_NOT);
if (reg->anchor & (ANCR_END_BUF | ANCR_SEMI_END_BUF)) {
reg->anc_dist_min = opt.len.min;
reg->anc_dist_max = opt.len.max;
}
if (opt.sb.len > 0 || opt.sm.len > 0) {
select_opt_exact(reg->enc, &opt.sb, &opt.sm);
if (opt.map.value > 0 && comp_opt_exact_or_map(&opt.sb, &opt.map) > 0) {
goto set_map;
}
else {
r = set_optimize_exact(reg, &opt.sb);
set_sub_anchor(reg, &opt.sb.anc);
}
}
else if (opt.map.value > 0) {
set_map:
set_optimize_map(reg, &opt.map);
set_sub_anchor(reg, &opt.map.anc);
}
else {
reg->sub_anchor |= opt.anc.left & ANCR_BEGIN_LINE;
if (opt.len.max == 0)
reg->sub_anchor |= opt.anc.right & ANCR_END_LINE;
}
#if defined(ONIG_DEBUG_COMPILE) || defined(ONIG_DEBUG_MATCH)
print_optimize_info(DBGFP, reg);
#endif
return r;
}
static void
clear_optimize_info(regex_t* reg)
{
reg->optimize = OPTIMIZE_NONE;
reg->anchor = 0;
reg->anc_dist_min = 0;
reg->anc_dist_max = 0;
reg->sub_anchor = 0;
reg->exact_end = (UChar* )NULL;
reg->map_offset = 0;
reg->threshold_len = 0;
if (IS_NOT_NULL(reg->exact)) {
xfree(reg->exact);
reg->exact = (UChar* )NULL;
}
}
#ifdef ONIG_DEBUG
static void print_enc_string(FILE* fp, OnigEncoding enc,
const UChar *s, const UChar *end)
{
if (ONIGENC_MBC_MINLEN(enc) > 1) {
const UChar *p;
OnigCodePoint code;
p = s;
while (p < end) {
code = ONIGENC_MBC_TO_CODE(enc, p, end);
if (code >= 0x80) {
fprintf(fp, " 0x%04x ", (int )code);
}
else {
fputc((int )code, fp);
}
p += enclen(enc, p);
}
}
else {
while (s < end) {
fputc((int )*s, fp);
s++;
}
}
fprintf(fp, "/\n");
}
#endif /* ONIG_DEBUG */
#if defined(ONIG_DEBUG_COMPILE) || defined(ONIG_DEBUG_MATCH)
static void
print_distance_range(FILE* f, OnigLen a, OnigLen b)
{
if (a == INFINITE_LEN)
fputs("inf", f);
else
fprintf(f, "(%u)", a);
fputs("-", f);
if (b == INFINITE_LEN)
fputs("inf", f);
else
fprintf(f, "(%u)", b);
}
static void
print_anchor(FILE* f, int anchor)
{
int q = 0;
fprintf(f, "[");
if (anchor & ANCR_BEGIN_BUF) {
fprintf(f, "begin-buf");
q = 1;
}
if (anchor & ANCR_BEGIN_LINE) {
if (q) fprintf(f, ", ");
q = 1;
fprintf(f, "begin-line");
}
if (anchor & ANCR_BEGIN_POSITION) {
if (q) fprintf(f, ", ");
q = 1;
fprintf(f, "begin-pos");
}
if (anchor & ANCR_END_BUF) {
if (q) fprintf(f, ", ");
q = 1;
fprintf(f, "end-buf");
}
if (anchor & ANCR_SEMI_END_BUF) {
if (q) fprintf(f, ", ");
q = 1;
fprintf(f, "semi-end-buf");
}
if (anchor & ANCR_END_LINE) {
if (q) fprintf(f, ", ");
q = 1;
fprintf(f, "end-line");
}
if (anchor & ANCR_ANYCHAR_INF) {
if (q) fprintf(f, ", ");
q = 1;
fprintf(f, "anychar-inf");
}
if (anchor & ANCR_ANYCHAR_INF_ML) {
if (q) fprintf(f, ", ");
fprintf(f, "anychar-inf-ml");
}
fprintf(f, "]");
}
static void
print_optimize_info(FILE* f, regex_t* reg)
{
static const char* on[] =
{ "NONE", "STR", "STR_FAST", "STR_FAST_STEP_FORWARD", "MAP" };
fprintf(f, "optimize: %s\n", on[reg->optimize]);
fprintf(f, " anchor: "); print_anchor(f, reg->anchor);
if ((reg->anchor & ANCR_END_BUF_MASK) != 0)
print_distance_range(f, reg->anc_dist_min, reg->anc_dist_max);
fprintf(f, "\n");
if (reg->optimize) {
fprintf(f, " sub anchor: "); print_anchor(f, reg->sub_anchor);
fprintf(f, "\n");
}
fprintf(f, "\n");
if (reg->exact) {
UChar *p;
fprintf(f, "exact: [");
for (p = reg->exact; p < reg->exact_end; p++) {
fputc(*p, f);
}
fprintf(f, "]: length: %ld, dmin: %u, ",
(reg->exact_end - reg->exact), reg->dist_min);
if (reg->dist_max == INFINITE_LEN)
fprintf(f, "dmax: inf.\n");
else
fprintf(f, "dmax: %u\n", reg->dist_max);
}
else if (reg->optimize & OPTIMIZE_MAP) {
int c, i, n = 0;
for (i = 0; i < CHAR_MAP_SIZE; i++)
if (reg->map[i]) n++;
fprintf(f, "map: n=%d, dmin: %u, dmax: %u\n",
n, reg->dist_min, reg->dist_max);
if (n > 0) {
c = 0;
fputc('[', f);
for (i = 0; i < CHAR_MAP_SIZE; i++) {
if (reg->map[i] != 0) {
if (c > 0) fputs(", ", f);
c++;
if (ONIGENC_MBC_MAXLEN(reg->enc) == 1 &&
ONIGENC_IS_CODE_PRINT(reg->enc, (OnigCodePoint )i))
fputc(i, f);
else
fprintf(f, "%d", i);
}
}
fprintf(f, "]\n");
}
}
}
#endif
extern RegexExt*
onig_get_regex_ext(regex_t* reg)
{
if (IS_NULL(reg->extp)) {
RegexExt* ext = (RegexExt* )xmalloc(sizeof(*ext));
if (IS_NULL(ext)) return 0;
ext->pattern = 0;
ext->pattern_end = 0;
#ifdef USE_CALLOUT
ext->tag_table = 0;
ext->callout_num = 0;
ext->callout_list_alloc = 0;
ext->callout_list = 0;
#endif
reg->extp = ext;
}
return reg->extp;
}
static void
free_regex_ext(RegexExt* ext)
{
if (IS_NOT_NULL(ext)) {
if (IS_NOT_NULL(ext->pattern))
xfree((void* )ext->pattern);
#ifdef USE_CALLOUT
if (IS_NOT_NULL(ext->tag_table))
onig_callout_tag_table_free(ext->tag_table);
if (IS_NOT_NULL(ext->callout_list))
onig_free_reg_callout_list(ext->callout_num, ext->callout_list);
#endif
xfree(ext);
}
}
extern int
onig_ext_set_pattern(regex_t* reg, const UChar* pattern, const UChar* pattern_end)
{
RegexExt* ext;
UChar* s;
ext = onig_get_regex_ext(reg);
CHECK_NULL_RETURN_MEMERR(ext);
s = onigenc_strdup(reg->enc, pattern, pattern_end);
CHECK_NULL_RETURN_MEMERR(s);
ext->pattern = s;
ext->pattern_end = s + (pattern_end - pattern);
return ONIG_NORMAL;
}
extern void
onig_free_body(regex_t* reg)
{
if (IS_NOT_NULL(reg)) {
ops_free(reg);
if (IS_NOT_NULL(reg->string_pool)) {
xfree(reg->string_pool);
reg->string_pool_end = reg->string_pool = 0;
}
if (IS_NOT_NULL(reg->exact)) xfree(reg->exact);
if (IS_NOT_NULL(reg->repeat_range)) xfree(reg->repeat_range);
if (IS_NOT_NULL(reg->extp)) {
free_regex_ext(reg->extp);
reg->extp = 0;
}
onig_names_free(reg);
}
}
extern void
onig_free(regex_t* reg)
{
if (IS_NOT_NULL(reg)) {
onig_free_body(reg);
xfree(reg);
}
}
#ifdef ONIG_DEBUG_PARSE
static void print_tree P_((FILE* f, Node* node));
#endif
extern int onig_init_for_match_at(regex_t* reg);
extern int
onig_compile(regex_t* reg, const UChar* pattern, const UChar* pattern_end,
OnigErrorInfo* einfo)
{
int r;
Node* root;
ScanEnv scan_env;
#ifdef USE_CALL
UnsetAddrList uslist = {0};
#endif
root = 0;
if (IS_NOT_NULL(einfo)) {
einfo->enc = reg->enc;
einfo->par = (UChar* )NULL;
}
#ifdef ONIG_DEBUG
fprintf(DBGFP, "\nPATTERN: /");
print_enc_string(DBGFP, reg->enc, pattern, pattern_end);
#endif
if (reg->ops_alloc == 0) {
r = ops_init(reg, OPS_INIT_SIZE);
if (r != 0) goto end;
}
else
reg->ops_used = 0;
r = onig_parse_tree(&root, pattern, pattern_end, reg, &scan_env);
if (r != 0) goto err;
r = reduce_string_list(root, reg->enc);
if (r != 0) goto err;
/* mixed use named group and no-named group */
if (scan_env.num_named > 0 &&
IS_SYNTAX_BV(scan_env.syntax, ONIG_SYN_CAPTURE_ONLY_NAMED_GROUP) &&
! OPTON_CAPTURE_GROUP(reg->options)) {
if (scan_env.num_named != scan_env.num_mem)
r = disable_noname_group_capture(&root, reg, &scan_env);
else
r = numbered_ref_check(root);
if (r != 0) goto err;
}
r = check_backrefs(root, &scan_env);
if (r != 0) goto err;
#ifdef USE_CALL
if (scan_env.num_call > 0) {
r = unset_addr_list_init(&uslist, scan_env.num_call);
if (r != 0) goto err;
scan_env.unset_addr_list = &uslist;
r = tune_call(root, &scan_env, 0);
if (r != 0) goto err_unset;
r = tune_call2(root);
if (r != 0) goto err_unset;
r = recursive_call_check_trav(root, &scan_env, 0);
if (r < 0) goto err_unset;
r = infinite_recursive_call_check_trav(root, &scan_env);
if (r != 0) goto err_unset;
tune_called_state(root, 0);
}
reg->num_call = scan_env.num_call;
#endif
#ifdef ONIG_DEBUG_PARSE
fprintf(DBGFP, "MAX PARSE DEPTH: %d\n", scan_env.max_parse_depth);
fprintf(DBGFP, "TREE (parsed)\n");
print_tree(DBGFP, root);
fprintf(DBGFP, "\n");
#endif
r = tune_tree(root, reg, 0, &scan_env);
if (r != 0) goto err_unset;
if (scan_env.backref_num != 0) {
set_parent_node_trav(root, NULL_NODE);
r = set_empty_repeat_node_trav(root, NULL_NODE, &scan_env);
if (r != 0) goto err_unset;
set_empty_status_check_trav(root, &scan_env);
}
#ifdef ONIG_DEBUG_PARSE
fprintf(DBGFP, "TREE (after tune)\n");
print_tree(DBGFP, root);
fprintf(DBGFP, "\n");
#endif
reg->capture_history = scan_env.cap_history;
reg->push_mem_start = scan_env.backtrack_mem | scan_env.cap_history;
#ifdef USE_CALLOUT
if (IS_NOT_NULL(reg->extp) && reg->extp->callout_num != 0) {
reg->push_mem_end = reg->push_mem_start;
}
else {
if (MEM_STATUS_IS_ALL_ON(reg->push_mem_start))
reg->push_mem_end = scan_env.backrefed_mem | scan_env.cap_history;
else
reg->push_mem_end = reg->push_mem_start &
(scan_env.backrefed_mem | scan_env.cap_history);
}
#else
if (MEM_STATUS_IS_ALL_ON(reg->push_mem_start))
reg->push_mem_end = scan_env.backrefed_mem | scan_env.cap_history;
else
reg->push_mem_end = reg->push_mem_start &
(scan_env.backrefed_mem | scan_env.cap_history);
#endif
clear_optimize_info(reg);
#ifndef ONIG_DONT_OPTIMIZE
r = set_optimize_info_from_tree(root, reg, &scan_env);
if (r != 0) goto err_unset;
#endif
if (IS_NOT_NULL(scan_env.mem_env_dynamic)) {
xfree(scan_env.mem_env_dynamic);
scan_env.mem_env_dynamic = (MemEnv* )NULL;
}
r = compile_tree(root, reg, &scan_env);
if (r == 0) {
if (scan_env.keep_num > 0) {
r = add_op(reg, OP_UPDATE_VAR);
if (r != 0) goto err;
COP(reg)->update_var.type = UPDATE_VAR_KEEP_FROM_STACK_LAST;
COP(reg)->update_var.id = 0; /* not used */
COP(reg)->update_var.clear = FALSE;
}
r = add_op(reg, OP_END);
if (r != 0) goto err;
#ifdef USE_CALL
if (scan_env.num_call > 0) {
r = fix_unset_addr_list(&uslist, reg);
unset_addr_list_end(&uslist);
if (r != 0) goto err;
}
#endif
set_addr_in_repeat_range(reg);
if ((reg->push_mem_end != 0)
#ifdef USE_REPEAT_AND_EMPTY_CHECK_LOCAL_VAR
|| (reg->num_repeat != 0)
|| (reg->num_empty_check != 0)
#endif
#ifdef USE_CALLOUT
|| (IS_NOT_NULL(reg->extp) && reg->extp->callout_num != 0)
#endif
#ifdef USE_CALL
|| scan_env.num_call > 0
#endif
)
reg->stack_pop_level = STACK_POP_LEVEL_ALL;
else {
if (reg->push_mem_start != 0)
reg->stack_pop_level = STACK_POP_LEVEL_MEM_START;
else
reg->stack_pop_level = STACK_POP_LEVEL_FREE;
}
r = ops_make_string_pool(reg);
if (r != 0) goto err;
}
#ifdef USE_CALL
else if (scan_env.num_call > 0) {
unset_addr_list_end(&uslist);
}
#endif
onig_node_free(root);
#ifdef ONIG_DEBUG_COMPILE
onig_print_names(DBGFP, reg);
onig_print_compiled_byte_code_list(DBGFP, reg);
#endif
#ifdef USE_DIRECT_THREADED_CODE
/* opcode -> opaddr */
onig_init_for_match_at(reg);
#endif
end:
return r;
err_unset:
#ifdef USE_CALL
if (scan_env.num_call > 0) {
unset_addr_list_end(&uslist);
}
#endif
err:
if (IS_NOT_NULL(scan_env.error)) {
if (IS_NOT_NULL(einfo)) {
einfo->par = scan_env.error;
einfo->par_end = scan_env.error_end;
}
}
onig_node_free(root);
if (IS_NOT_NULL(scan_env.mem_env_dynamic))
xfree(scan_env.mem_env_dynamic);
return r;
}
static int onig_inited = 0;
extern int
onig_reg_init(regex_t* reg, OnigOptionType option, OnigCaseFoldType case_fold_flag,
OnigEncoding enc, OnigSyntaxType* syntax)
{
int r;
xmemset(reg, 0, sizeof(*reg));
if (onig_inited == 0) {
#if 0
return ONIGERR_LIBRARY_IS_NOT_INITIALIZED;
#else
r = onig_initialize(&enc, 1);
if (r != 0)
return ONIGERR_FAIL_TO_INITIALIZE;
onig_warning("You didn't call onig_initialize() explicitly");
#endif
}
if (IS_NULL(reg))
return ONIGERR_INVALID_ARGUMENT;
if (ONIGENC_IS_UNDEF(enc))
return ONIGERR_DEFAULT_ENCODING_IS_NOT_SETTED;
if ((option & (ONIG_OPTION_DONT_CAPTURE_GROUP|ONIG_OPTION_CAPTURE_GROUP))
== (ONIG_OPTION_DONT_CAPTURE_GROUP|ONIG_OPTION_CAPTURE_GROUP)) {
return ONIGERR_INVALID_COMBINATION_OF_OPTIONS;
}
if ((option & ONIG_OPTION_NEGATE_SINGLELINE) != 0) {
option |= syntax->options;
option &= ~ONIG_OPTION_SINGLELINE;
}
else
option |= syntax->options;
(reg)->enc = enc;
(reg)->options = option;
(reg)->syntax = syntax;
(reg)->optimize = 0;
(reg)->exact = (UChar* )NULL;
(reg)->extp = (RegexExt* )NULL;
(reg)->ops = (Operation* )NULL;
(reg)->ops_curr = (Operation* )NULL;
(reg)->ops_used = 0;
(reg)->ops_alloc = 0;
(reg)->name_table = (void* )NULL;
(reg)->case_fold_flag = case_fold_flag;
return 0;
}
extern int
onig_new_without_alloc(regex_t* reg,
const UChar* pattern, const UChar* pattern_end,
OnigOptionType option, OnigEncoding enc,
OnigSyntaxType* syntax, OnigErrorInfo* einfo)
{
int r;
r = onig_reg_init(reg, option, ONIGENC_CASE_FOLD_DEFAULT, enc, syntax);
if (r != 0) return r;
r = onig_compile(reg, pattern, pattern_end, einfo);
return r;
}
extern int
onig_new(regex_t** reg, const UChar* pattern, const UChar* pattern_end,
OnigOptionType option, OnigEncoding enc, OnigSyntaxType* syntax,
OnigErrorInfo* einfo)
{
int r;
*reg = (regex_t* )xmalloc(sizeof(regex_t));
if (IS_NULL(*reg)) return ONIGERR_MEMORY;
r = onig_reg_init(*reg, option, ONIGENC_CASE_FOLD_DEFAULT, enc, syntax);
if (r != 0) {
xfree(*reg);
*reg = NULL;
return r;
}
r = onig_compile(*reg, pattern, pattern_end, einfo);
if (r != 0) {
onig_free(*reg);
*reg = NULL;
}
return r;
}
extern int
onig_initialize(OnigEncoding encodings[], int n)
{
int i;
int r;
if (onig_inited != 0)
return 0;
onigenc_init();
onig_inited = 1;
for (i = 0; i < n; i++) {
OnigEncoding enc = encodings[i];
r = onig_initialize_encoding(enc);
if (r != 0)
return r;
}
return ONIG_NORMAL;
}
typedef struct EndCallListItem {
struct EndCallListItem* next;
void (*func)(void);
} EndCallListItemType;
static EndCallListItemType* EndCallTop;
extern void onig_add_end_call(void (*func)(void))
{
EndCallListItemType* item;
item = (EndCallListItemType* )xmalloc(sizeof(*item));
if (item == 0) return ;
item->next = EndCallTop;
item->func = func;
EndCallTop = item;
}
static void
exec_end_call_list(void)
{
EndCallListItemType* prev;
void (*func)(void);
while (EndCallTop != 0) {
func = EndCallTop->func;
(*func)();
prev = EndCallTop;
EndCallTop = EndCallTop->next;
xfree(prev);
}
}
extern int
onig_end(void)
{
exec_end_call_list();
#ifdef USE_CALLOUT
onig_global_callout_names_free();
#endif
onigenc_end();
onig_inited = 0;
return 0;
}
extern int
onig_is_in_code_range(const UChar* p, OnigCodePoint code)
{
OnigCodePoint n, *data;
OnigCodePoint low, high, x;
GET_CODE_POINT(n, p);
data = (OnigCodePoint* )p;
data++;
for (low = 0, high = n; low < high; ) {
x = (low + high) >> 1;
if (code > data[x * 2 + 1])
low = x + 1;
else
high = x;
}
return ((low < n && code >= data[low * 2]) ? 1 : 0);
}
extern int
onig_is_code_in_cc_len(int elen, OnigCodePoint code, /* CClassNode* */ void* cc_arg)
{
int found;
CClassNode* cc = (CClassNode* )cc_arg;
if (elen > 1 || (code >= SINGLE_BYTE_SIZE)) {
if (IS_NULL(cc->mbuf)) {
found = 0;
}
else {
found = onig_is_in_code_range(cc->mbuf->p, code) != 0;
}
}
else {
found = BITSET_AT(cc->bs, code) != 0;
}
if (IS_NCCLASS_NOT(cc))
return !found;
else
return found;
}
extern int
onig_is_code_in_cc(OnigEncoding enc, OnigCodePoint code, CClassNode* cc)
{
int len;
if (ONIGENC_MBC_MINLEN(enc) > 1) {
len = 2;
}
else {
len = ONIGENC_CODE_TO_MBCLEN(enc, code);
if (len < 0) return 0;
}
return onig_is_code_in_cc_len(len, code, cc);
}
typedef struct {
int prec_read;
int look_behind;
int backref_with_level;
int call;
} SlowElementCount;
static int
node_detect_can_be_slow(Node* node, SlowElementCount* ct)
{
int r;
r = 0;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
do {
r = node_detect_can_be_slow(NODE_CAR(node), ct);
if (r != 0) return r;
} while (IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_QUANT:
r = node_detect_can_be_slow(NODE_BODY(node), ct);
break;
case NODE_ANCHOR:
switch (ANCHOR_(node)->type) {
case ANCR_PREC_READ:
case ANCR_PREC_READ_NOT:
ct->prec_read++;
break;
case ANCR_LOOK_BEHIND:
case ANCR_LOOK_BEHIND_NOT:
ct->look_behind++;
break;
default:
break;
}
if (ANCHOR_HAS_BODY(ANCHOR_(node)))
r = node_detect_can_be_slow(NODE_BODY(node), ct);
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
r = node_detect_can_be_slow(NODE_BODY(node), ct);
if (r != 0) return r;
if (en->type == BAG_IF_ELSE) {
if (IS_NOT_NULL(en->te.Then)) {
r = node_detect_can_be_slow(en->te.Then, ct);
if (r != 0) return r;
}
if (IS_NOT_NULL(en->te.Else)) {
r = node_detect_can_be_slow(en->te.Else, ct);
if (r != 0) return r;
}
}
}
break;
#ifdef USE_BACKREF_WITH_LEVEL
case NODE_BACKREF:
if (NODE_IS_NEST_LEVEL(node))
ct->backref_with_level++;
break;
#endif
#ifdef USE_CALL
case NODE_CALL:
ct->call++;
break;
#endif
default:
break;
}
return r;
}
extern int
onig_detect_can_be_slow_pattern(const UChar* pattern,
const UChar* pattern_end, OnigOptionType option, OnigEncoding enc,
OnigSyntaxType* syntax)
{
int r;
regex_t* reg;
Node* root;
ScanEnv scan_env;
SlowElementCount count;
reg = (regex_t* )xmalloc(sizeof(regex_t));
if (IS_NULL(reg)) return ONIGERR_MEMORY;
r = onig_reg_init(reg, option, ONIGENC_CASE_FOLD_DEFAULT, enc, syntax);
if (r != 0) {
xfree(reg);
return r;
}
root = 0;
r = onig_parse_tree(&root, pattern, pattern_end, reg, &scan_env);
if (r == 0) {
count.prec_read = 0;
count.look_behind = 0;
count.backref_with_level = 0;
count.call = 0;
r = node_detect_can_be_slow(root, &count);
if (r == 0) {
int n = count.prec_read + count.look_behind
+ count.backref_with_level + count.call;
r = n;
}
}
if (IS_NOT_NULL(scan_env.mem_env_dynamic))
xfree(scan_env.mem_env_dynamic);
onig_node_free(root);
onig_free(reg);
return r;
}
#ifdef ONIG_DEBUG_PARSE
#ifdef USE_CALL
static void
p_string(FILE* f, int len, UChar* s)
{
fputs(":", f);
while (len-- > 0) { fputc(*s++, f); }
}
#endif
static void
Indent(FILE* f, int indent)
{
int i;
for (i = 0; i < indent; i++) putc(' ', f);
}
static void
print_indent_tree(FILE* f, Node* node, int indent)
{
int i;
NodeType type;
UChar* p;
int add = 3;
Indent(f, indent);
if (IS_NULL(node)) {
fprintf(f, "ERROR: null node!!!\n");
exit(0);
}
type = NODE_TYPE(node);
switch (type) {
case NODE_LIST:
case NODE_ALT:
if (type == NODE_LIST)
fprintf(f, "<list:%p>\n", node);
else
fprintf(f, "<alt:%p>\n", node);
print_indent_tree(f, NODE_CAR(node), indent + add);
while (IS_NOT_NULL(node = NODE_CDR(node))) {
if (NODE_TYPE(node) != type) {
fprintf(f, "ERROR: list/alt right is not a cons. %d\n", NODE_TYPE(node));
exit(0);
}
print_indent_tree(f, NODE_CAR(node), indent + add);
}
break;
case NODE_STRING:
{
char* str;
char* mode;
if (NODE_STRING_IS_CRUDE(node))
mode = "-crude";
else if (NODE_IS_IGNORECASE(node))
mode = "-ignorecase";
else
mode = "";
if (STR_(node)->s == STR_(node)->end)
str = "empty-string";
else
str = "string";
fprintf(f, "<%s%s:%p>", str, mode, node);
for (p = STR_(node)->s; p < STR_(node)->end; p++) {
if (*p >= 0x20 && *p < 0x7f)
fputc(*p, f);
else {
fprintf(f, " 0x%02x", *p);
}
}
}
break;
case NODE_CCLASS:
#define CCLASS_MBUF_MAX_OUTPUT_NUM 10
fprintf(f, "<cclass:%p>", node);
if (IS_NCCLASS_NOT(CCLASS_(node))) fputs(" not", f);
if (CCLASS_(node)->mbuf) {
BBuf* bbuf = CCLASS_(node)->mbuf;
fprintf(f, " mbuf(%u) ", bbuf->used);
for (i = 0; i < bbuf->used && i < CCLASS_MBUF_MAX_OUTPUT_NUM; i++) {
if (i > 0) fprintf(f, ",");
fprintf(f, "%0x", bbuf->p[i]);
}
if (i < bbuf->used) fprintf(f, "...");
}
break;
case NODE_CTYPE:
fprintf(f, "<ctype:%p> ", node);
switch (CTYPE_(node)->ctype) {
case CTYPE_ANYCHAR:
fprintf(f, "anychar");
break;
case ONIGENC_CTYPE_WORD:
if (CTYPE_(node)->not != 0)
fputs("not word", f);
else
fputs("word", f);
if (CTYPE_(node)->ascii_mode != 0)
fputs(" (ascii)", f);
break;
default:
fprintf(f, "ERROR: undefined ctype.\n");
exit(0);
}
break;
case NODE_ANCHOR:
fprintf(f, "<anchor:%p> ", node);
switch (ANCHOR_(node)->type) {
case ANCR_BEGIN_BUF: fputs("begin buf", f); break;
case ANCR_END_BUF: fputs("end buf", f); break;
case ANCR_BEGIN_LINE: fputs("begin line", f); break;
case ANCR_END_LINE: fputs("end line", f); break;
case ANCR_SEMI_END_BUF: fputs("semi end buf", f); break;
case ANCR_BEGIN_POSITION: fputs("begin position", f); break;
case ANCR_WORD_BOUNDARY: fputs("word boundary", f); break;
case ANCR_NO_WORD_BOUNDARY: fputs("not word boundary", f); break;
#ifdef USE_WORD_BEGIN_END
case ANCR_WORD_BEGIN: fputs("word begin", f); break;
case ANCR_WORD_END: fputs("word end", f); break;
#endif
case ANCR_TEXT_SEGMENT_BOUNDARY:
fputs("text-segment boundary", f); break;
case ANCR_NO_TEXT_SEGMENT_BOUNDARY:
fputs("no text-segment boundary", f); break;
case ANCR_PREC_READ:
fprintf(f, "prec read\n");
print_indent_tree(f, NODE_BODY(node), indent + add);
break;
case ANCR_PREC_READ_NOT:
fprintf(f, "prec read not\n");
print_indent_tree(f, NODE_BODY(node), indent + add);
break;
case ANCR_LOOK_BEHIND:
fprintf(f, "look behind\n");
print_indent_tree(f, NODE_BODY(node), indent + add);
break;
case ANCR_LOOK_BEHIND_NOT:
fprintf(f, "look behind not\n");
print_indent_tree(f, NODE_BODY(node), indent + add);
break;
default:
fprintf(f, "ERROR: undefined anchor type.\n");
break;
}
break;
case NODE_BACKREF:
{
int* p;
BackRefNode* br = BACKREF_(node);
p = BACKREFS_P(br);
fprintf(f, "<backref%s:%p>", NODE_IS_CHECKER(node) ? "-checker" : "", node);
for (i = 0; i < br->back_num; i++) {
if (i > 0) fputs(", ", f);
fprintf(f, "%d", p[i]);
}
#ifdef USE_BACKREF_WITH_LEVEL
if (NODE_IS_NEST_LEVEL(node)) {
fprintf(f, ", level: %d", br->nest_level);
}
#endif
}
break;
#ifdef USE_CALL
case NODE_CALL:
{
CallNode* cn = CALL_(node);
fprintf(f, "<call:%p>", node);
fprintf(f, " num: %d, name", cn->called_gnum);
p_string(f, cn->name_end - cn->name, cn->name);
}
break;
#endif
case NODE_QUANT:
fprintf(f, "<quantifier:%p>{%d,%d}%s%s\n", node,
QUANT_(node)->lower, QUANT_(node)->upper,
(QUANT_(node)->greedy ? "" : "?"),
QUANT_(node)->include_referred == 0 ? "" : " referred");
print_indent_tree(f, NODE_BODY(node), indent + add);
break;
case NODE_BAG:
fprintf(f, "<bag:%p> ", node);
if (BAG_(node)->type == BAG_IF_ELSE) {
Node* Then;
Node* Else;
BagNode* bn;
bn = BAG_(node);
fprintf(f, "if-else\n");
print_indent_tree(f, NODE_BODY(node), indent + add);
Then = bn->te.Then;
Else = bn->te.Else;
if (IS_NULL(Then)) {
Indent(f, indent + add);
fprintf(f, "THEN empty\n");
}
else
print_indent_tree(f, Then, indent + add);
if (IS_NULL(Else)) {
Indent(f, indent + add);
fprintf(f, "ELSE empty\n");
}
else
print_indent_tree(f, Else, indent + add);
break;
}
switch (BAG_(node)->type) {
case BAG_OPTION:
fprintf(f, "option:%d", BAG_(node)->o.options);
break;
case BAG_MEMORY:
fprintf(f, "memory:%d", BAG_(node)->m.regnum);
if (NODE_IS_CALLED(node))
fprintf(f, ", called");
else if (NODE_IS_REFERENCED(node))
fprintf(f, ", referenced");
if (NODE_IS_FIXED_ADDR(node))
fprintf(f, ", fixed-addr");
break;
case BAG_STOP_BACKTRACK:
fprintf(f, "stop-bt");
break;
default:
break;
}
fprintf(f, "\n");
print_indent_tree(f, NODE_BODY(node), indent + add);
break;
case NODE_GIMMICK:
fprintf(f, "<gimmick:%p> ", node);
switch (GIMMICK_(node)->type) {
case GIMMICK_FAIL:
fprintf(f, "fail");
break;
case GIMMICK_SAVE:
fprintf(f, "save:%d:%d", GIMMICK_(node)->detail_type, GIMMICK_(node)->id);
break;
case GIMMICK_UPDATE_VAR:
fprintf(f, "update_var:%d:%d", GIMMICK_(node)->detail_type, GIMMICK_(node)->id);
break;
#ifdef USE_CALLOUT
case GIMMICK_CALLOUT:
switch (GIMMICK_(node)->detail_type) {
case ONIG_CALLOUT_OF_CONTENTS:
fprintf(f, "callout:contents:%d", GIMMICK_(node)->num);
break;
case ONIG_CALLOUT_OF_NAME:
fprintf(f, "callout:name:%d:%d", GIMMICK_(node)->id, GIMMICK_(node)->num);
break;
}
#endif
}
break;
default:
fprintf(f, "print_indent_tree: undefined node type %d\n", NODE_TYPE(node));
break;
}
if (type != NODE_LIST && type != NODE_ALT && type != NODE_QUANT &&
type != NODE_BAG)
fprintf(f, "\n");
fflush(f);
}
static void
print_tree(FILE* f, Node* node)
{
print_indent_tree(f, node, 0);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_4318_0 |
crossvul-cpp_data_bad_96_0 | ////////////////////////////////////////////////////////////////////////////
// **** WAVPACK **** //
// Hybrid Lossless Wavefile Compressor //
// Copyright (c) 1998 - 2016 David Bryant. //
// All Rights Reserved. //
// Distributed under the BSD Software License (see license.txt) //
////////////////////////////////////////////////////////////////////////////
// dsdiff.c
// This module is a helper to the WavPack command-line programs to support DFF files.
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <math.h>
#include <stdio.h>
#include <ctype.h>
#include "wavpack.h"
#include "utils.h"
#include "md5.h"
#ifdef _WIN32
#define strdup(x) _strdup(x)
#endif
#define WAVPACK_NO_ERROR 0
#define WAVPACK_SOFT_ERROR 1
#define WAVPACK_HARD_ERROR 2
extern int debug_logging_mode;
#pragma pack(push,2)
typedef struct {
char ckID [4];
int64_t ckDataSize;
} DFFChunkHeader;
typedef struct {
char ckID [4];
int64_t ckDataSize;
char formType [4];
} DFFFileHeader;
typedef struct {
char ckID [4];
int64_t ckDataSize;
uint32_t version;
} DFFVersionChunk;
typedef struct {
char ckID [4];
int64_t ckDataSize;
uint32_t sampleRate;
} DFFSampleRateChunk;
typedef struct {
char ckID [4];
int64_t ckDataSize;
uint16_t numChannels;
} DFFChannelsHeader;
typedef struct {
char ckID [4];
int64_t ckDataSize;
char compressionType [4];
} DFFCompressionHeader;
#pragma pack(pop)
#define DFFChunkHeaderFormat "4D"
#define DFFFileHeaderFormat "4D4"
#define DFFVersionChunkFormat "4DL"
#define DFFSampleRateChunkFormat "4DL"
#define DFFChannelsHeaderFormat "4DS"
#define DFFCompressionHeaderFormat "4D4"
int ParseDsdiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config)
{
int64_t infilesize, total_samples;
DFFFileHeader dff_file_header;
DFFChunkHeader dff_chunk_header;
uint32_t bcount;
infilesize = DoGetFileSize (infile);
memcpy (&dff_file_header, fourcc, 4);
if ((!DoReadFile (infile, ((char *) &dff_file_header) + 4, sizeof (DFFFileHeader) - 4, &bcount) ||
bcount != sizeof (DFFFileHeader) - 4) || strncmp (dff_file_header.formType, "DSD ", 4)) {
error_line ("%s is not a valid .DFF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &dff_file_header, sizeof (DFFFileHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
#if 1 // this might be a little too picky...
WavpackBigEndianToNative (&dff_file_header, DFFFileHeaderFormat);
if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) &&
dff_file_header.ckDataSize && dff_file_header.ckDataSize + 1 && dff_file_header.ckDataSize + 12 != infilesize) {
error_line ("%s is not a valid .DFF file (by total size)!", infilename);
return WAVPACK_SOFT_ERROR;
}
if (debug_logging_mode)
error_line ("file header indicated length = %lld", dff_file_header.ckDataSize);
#endif
// loop through all elements of the DSDIFF header
// (until the data chuck) and copy them to the output file
while (1) {
if (!DoReadFile (infile, &dff_chunk_header, sizeof (DFFChunkHeader), &bcount) ||
bcount != sizeof (DFFChunkHeader)) {
error_line ("%s is not a valid .DFF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &dff_chunk_header, sizeof (DFFChunkHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat);
if (debug_logging_mode)
error_line ("chunk header indicated length = %lld", dff_chunk_header.ckDataSize);
if (!strncmp (dff_chunk_header.ckID, "FVER", 4)) {
uint32_t version;
if (dff_chunk_header.ckDataSize != sizeof (version) ||
!DoReadFile (infile, &version, sizeof (version), &bcount) ||
bcount != sizeof (version)) {
error_line ("%s is not a valid .DFF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &version, sizeof (version))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackBigEndianToNative (&version, "L");
if (debug_logging_mode)
error_line ("dsdiff file version = 0x%08x", version);
}
else if (!strncmp (dff_chunk_header.ckID, "PROP", 4)) {
char *prop_chunk;
if (dff_chunk_header.ckDataSize < 4 || dff_chunk_header.ckDataSize > 1024) {
error_line ("%s is not a valid .DFF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
if (debug_logging_mode)
error_line ("got PROP chunk of %d bytes total", (int) dff_chunk_header.ckDataSize);
prop_chunk = malloc ((size_t) dff_chunk_header.ckDataSize);
if (!DoReadFile (infile, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize, &bcount) ||
bcount != dff_chunk_header.ckDataSize) {
error_line ("%s is not a valid .DFF file!", infilename);
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize)) {
error_line ("%s", WavpackGetErrorMessage (wpc));
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
if (!strncmp (prop_chunk, "SND ", 4)) {
char *cptr = prop_chunk + 4, *eptr = prop_chunk + dff_chunk_header.ckDataSize;
uint16_t numChannels, chansSpecified, chanMask = 0;
uint32_t sampleRate;
while (eptr - cptr >= sizeof (dff_chunk_header)) {
memcpy (&dff_chunk_header, cptr, sizeof (dff_chunk_header));
cptr += sizeof (dff_chunk_header);
WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat);
if (eptr - cptr >= dff_chunk_header.ckDataSize) {
if (!strncmp (dff_chunk_header.ckID, "FS ", 4) && dff_chunk_header.ckDataSize == 4) {
memcpy (&sampleRate, cptr, sizeof (sampleRate));
WavpackBigEndianToNative (&sampleRate, "L");
cptr += dff_chunk_header.ckDataSize;
if (debug_logging_mode)
error_line ("got sample rate of %u Hz", sampleRate);
}
else if (!strncmp (dff_chunk_header.ckID, "CHNL", 4) && dff_chunk_header.ckDataSize >= 2) {
memcpy (&numChannels, cptr, sizeof (numChannels));
WavpackBigEndianToNative (&numChannels, "S");
cptr += sizeof (numChannels);
chansSpecified = (int)(dff_chunk_header.ckDataSize - sizeof (numChannels)) / 4;
while (chansSpecified--) {
if (!strncmp (cptr, "SLFT", 4) || !strncmp (cptr, "MLFT", 4))
chanMask |= 0x1;
else if (!strncmp (cptr, "SRGT", 4) || !strncmp (cptr, "MRGT", 4))
chanMask |= 0x2;
else if (!strncmp (cptr, "LS ", 4))
chanMask |= 0x10;
else if (!strncmp (cptr, "RS ", 4))
chanMask |= 0x20;
else if (!strncmp (cptr, "C ", 4))
chanMask |= 0x4;
else if (!strncmp (cptr, "LFE ", 4))
chanMask |= 0x8;
else
if (debug_logging_mode)
error_line ("undefined channel ID %c%c%c%c", cptr [0], cptr [1], cptr [2], cptr [3]);
cptr += 4;
}
if (debug_logging_mode)
error_line ("%d channels, mask = 0x%08x", numChannels, chanMask);
}
else if (!strncmp (dff_chunk_header.ckID, "CMPR", 4) && dff_chunk_header.ckDataSize >= 4) {
if (strncmp (cptr, "DSD ", 4)) {
error_line ("DSDIFF files must be uncompressed, not \"%c%c%c%c\"!",
cptr [0], cptr [1], cptr [2], cptr [3]);
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
cptr += dff_chunk_header.ckDataSize;
}
else {
if (debug_logging_mode)
error_line ("got PROP/SND chunk type \"%c%c%c%c\" of %d bytes", dff_chunk_header.ckID [0],
dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize);
cptr += dff_chunk_header.ckDataSize;
}
}
else {
error_line ("%s is not a valid .DFF file!", infilename);
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
}
if (chanMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) {
error_line ("this DSDIFF file already has channel order information!");
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
else if (chanMask)
config->channel_mask = chanMask;
config->bits_per_sample = 8;
config->bytes_per_sample = 1;
config->num_channels = numChannels;
config->sample_rate = sampleRate / 8;
config->qmode |= QMODE_DSD_MSB_FIRST;
}
else if (debug_logging_mode)
error_line ("got unknown PROP chunk type \"%c%c%c%c\" of %d bytes",
prop_chunk [0], prop_chunk [1], prop_chunk [2], prop_chunk [3], dff_chunk_header.ckDataSize);
free (prop_chunk);
}
else if (!strncmp (dff_chunk_header.ckID, "DSD ", 4)) {
total_samples = dff_chunk_header.ckDataSize / config->num_channels;
break;
}
else { // just copy unknown chunks to output file
int bytes_to_copy = (int)(((dff_chunk_header.ckDataSize) + 1) & ~(int64_t)1);
char *buff = malloc (bytes_to_copy);
if (debug_logging_mode)
error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes",
dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2],
dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize);
if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) ||
bcount != bytes_to_copy ||
(!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, buff, bytes_to_copy))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
free (buff);
return WAVPACK_SOFT_ERROR;
}
free (buff);
}
}
if (debug_logging_mode)
error_line ("setting configuration with %lld samples", total_samples);
if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) {
error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
return WAVPACK_NO_ERROR;
}
int WriteDsdiffHeader (FILE *outfile, WavpackContext *wpc, int64_t total_samples, int qmode)
{
uint32_t chan_mask = WavpackGetChannelMask (wpc);
int num_channels = WavpackGetNumChannels (wpc);
DFFFileHeader file_header, prop_header;
DFFChunkHeader data_header;
DFFVersionChunk ver_chunk;
DFFSampleRateChunk fs_chunk;
DFFChannelsHeader chan_header;
DFFCompressionHeader cmpr_header;
char *cmpr_name = "\016not compressed", *chan_ids;
int64_t file_size, prop_chunk_size, data_size;
int cmpr_name_size, chan_ids_size;
uint32_t bcount;
if (debug_logging_mode)
error_line ("WriteDsdiffHeader (), total samples = %lld, qmode = 0x%02x\n",
(long long) total_samples, qmode);
cmpr_name_size = (strlen (cmpr_name) + 1) & ~1;
chan_ids_size = num_channels * 4;
chan_ids = malloc (chan_ids_size);
if (chan_ids) {
uint32_t scan_mask = 0x1;
char *cptr = chan_ids;
int ci, uci = 0;
for (ci = 0; ci < num_channels; ++ci) {
while (scan_mask && !(scan_mask & chan_mask))
scan_mask <<= 1;
if (scan_mask & 0x1)
memcpy (cptr, num_channels <= 2 ? "SLFT" : "MLFT", 4);
else if (scan_mask & 0x2)
memcpy (cptr, num_channels <= 2 ? "SRGT" : "MRGT", 4);
else if (scan_mask & 0x4)
memcpy (cptr, "C ", 4);
else if (scan_mask & 0x8)
memcpy (cptr, "LFE ", 4);
else if (scan_mask & 0x10)
memcpy (cptr, "LS ", 4);
else if (scan_mask & 0x20)
memcpy (cptr, "RS ", 4);
else {
cptr [0] = 'C';
cptr [1] = (uci / 100) + '0';
cptr [2] = ((uci % 100) / 10) + '0';
cptr [3] = (uci % 10) + '0';
uci++;
}
scan_mask <<= 1;
cptr += 4;
}
}
else {
error_line ("can't allocate memory!");
return FALSE;
}
data_size = total_samples * num_channels;
prop_chunk_size = sizeof (prop_header) + sizeof (fs_chunk) + sizeof (chan_header) + chan_ids_size + sizeof (cmpr_header) + cmpr_name_size;
file_size = sizeof (file_header) + sizeof (ver_chunk) + prop_chunk_size + sizeof (data_header) + ((data_size + 1) & ~(int64_t)1);
memcpy (file_header.ckID, "FRM8", 4);
file_header.ckDataSize = file_size - 12;
memcpy (file_header.formType, "DSD ", 4);
memcpy (prop_header.ckID, "PROP", 4);
prop_header.ckDataSize = prop_chunk_size - 12;
memcpy (prop_header.formType, "SND ", 4);
memcpy (ver_chunk.ckID, "FVER", 4);
ver_chunk.ckDataSize = sizeof (ver_chunk) - 12;
ver_chunk.version = 0x01050000;
memcpy (fs_chunk.ckID, "FS ", 4);
fs_chunk.ckDataSize = sizeof (fs_chunk) - 12;
fs_chunk.sampleRate = WavpackGetSampleRate (wpc) * 8;
memcpy (chan_header.ckID, "CHNL", 4);
chan_header.ckDataSize = sizeof (chan_header) + chan_ids_size - 12;
chan_header.numChannels = num_channels;
memcpy (cmpr_header.ckID, "CMPR", 4);
cmpr_header.ckDataSize = sizeof (cmpr_header) + cmpr_name_size - 12;
memcpy (cmpr_header.compressionType, "DSD ", 4);
memcpy (data_header.ckID, "DSD ", 4);
data_header.ckDataSize = data_size;
WavpackNativeToBigEndian (&file_header, DFFFileHeaderFormat);
WavpackNativeToBigEndian (&ver_chunk, DFFVersionChunkFormat);
WavpackNativeToBigEndian (&prop_header, DFFFileHeaderFormat);
WavpackNativeToBigEndian (&fs_chunk, DFFSampleRateChunkFormat);
WavpackNativeToBigEndian (&chan_header, DFFChannelsHeaderFormat);
WavpackNativeToBigEndian (&cmpr_header, DFFCompressionHeaderFormat);
WavpackNativeToBigEndian (&data_header, DFFChunkHeaderFormat);
if (!DoWriteFile (outfile, &file_header, sizeof (file_header), &bcount) || bcount != sizeof (file_header) ||
!DoWriteFile (outfile, &ver_chunk, sizeof (ver_chunk), &bcount) || bcount != sizeof (ver_chunk) ||
!DoWriteFile (outfile, &prop_header, sizeof (prop_header), &bcount) || bcount != sizeof (prop_header) ||
!DoWriteFile (outfile, &fs_chunk, sizeof (fs_chunk), &bcount) || bcount != sizeof (fs_chunk) ||
!DoWriteFile (outfile, &chan_header, sizeof (chan_header), &bcount) || bcount != sizeof (chan_header) ||
!DoWriteFile (outfile, chan_ids, chan_ids_size, &bcount) || bcount != chan_ids_size ||
!DoWriteFile (outfile, &cmpr_header, sizeof (cmpr_header), &bcount) || bcount != sizeof (cmpr_header) ||
!DoWriteFile (outfile, cmpr_name, cmpr_name_size, &bcount) || bcount != cmpr_name_size ||
!DoWriteFile (outfile, &data_header, sizeof (data_header), &bcount) || bcount != sizeof (data_header)) {
error_line ("can't write .DSF data, disk probably full!");
free (chan_ids);
return FALSE;
}
free (chan_ids);
return TRUE;
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_96_0 |
crossvul-cpp_data_good_5305_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% W W PPPP GGGG %
% W W P P G %
% W W W PPPP G GGG %
% WW WW P G G %
% W W P GGG %
% %
% %
% Read WordPerfect Image Format %
% %
% Software Design %
% Jaroslav Fojtik %
% June 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 "magick/studio.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/colormap-private.h"
#include "magick/constitute.h"
#include "magick/distort.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/cache.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magic.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/pixel-accessor.h"
#include "magick/quantum-private.h"
#include "magick/resource_.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"
#include "magick/transform.h"
#include "magick/utility.h"
#include "magick/utility-private.h"
typedef struct
{
unsigned char Red;
unsigned char Blue;
unsigned char Green;
} RGB_Record;
/* Default palette for WPG level 1 */
static const RGB_Record WPG1_Palette[256]={
{ 0, 0, 0}, { 0, 0,168},
{ 0,168, 0}, { 0,168,168},
{168, 0, 0}, {168, 0,168},
{168, 84, 0}, {168,168,168},
{ 84, 84, 84}, { 84, 84,252},
{ 84,252, 84}, { 84,252,252},
{252, 84, 84}, {252, 84,252},
{252,252, 84}, {252,252,252}, /*16*/
{ 0, 0, 0}, { 20, 20, 20},
{ 32, 32, 32}, { 44, 44, 44},
{ 56, 56, 56}, { 68, 68, 68},
{ 80, 80, 80}, { 96, 96, 96},
{112,112,112}, {128,128,128},
{144,144,144}, {160,160,160},
{180,180,180}, {200,200,200},
{224,224,224}, {252,252,252}, /*32*/
{ 0, 0,252}, { 64, 0,252},
{124, 0,252}, {188, 0,252},
{252, 0,252}, {252, 0,188},
{252, 0,124}, {252, 0, 64},
{252, 0, 0}, {252, 64, 0},
{252,124, 0}, {252,188, 0},
{252,252, 0}, {188,252, 0},
{124,252, 0}, { 64,252, 0}, /*48*/
{ 0,252, 0}, { 0,252, 64},
{ 0,252,124}, { 0,252,188},
{ 0,252,252}, { 0,188,252},
{ 0,124,252}, { 0, 64,252},
{124,124,252}, {156,124,252},
{188,124,252}, {220,124,252},
{252,124,252}, {252,124,220},
{252,124,188}, {252,124,156}, /*64*/
{252,124,124}, {252,156,124},
{252,188,124}, {252,220,124},
{252,252,124}, {220,252,124},
{188,252,124}, {156,252,124},
{124,252,124}, {124,252,156},
{124,252,188}, {124,252,220},
{124,252,252}, {124,220,252},
{124,188,252}, {124,156,252}, /*80*/
{180,180,252}, {196,180,252},
{216,180,252}, {232,180,252},
{252,180,252}, {252,180,232},
{252,180,216}, {252,180,196},
{252,180,180}, {252,196,180},
{252,216,180}, {252,232,180},
{252,252,180}, {232,252,180},
{216,252,180}, {196,252,180}, /*96*/
{180,220,180}, {180,252,196},
{180,252,216}, {180,252,232},
{180,252,252}, {180,232,252},
{180,216,252}, {180,196,252},
{0,0,112}, {28,0,112},
{56,0,112}, {84,0,112},
{112,0,112}, {112,0,84},
{112,0,56}, {112,0,28}, /*112*/
{112,0,0}, {112,28,0},
{112,56,0}, {112,84,0},
{112,112,0}, {84,112,0},
{56,112,0}, {28,112,0},
{0,112,0}, {0,112,28},
{0,112,56}, {0,112,84},
{0,112,112}, {0,84,112},
{0,56,112}, {0,28,112}, /*128*/
{56,56,112}, {68,56,112},
{84,56,112}, {96,56,112},
{112,56,112}, {112,56,96},
{112,56,84}, {112,56,68},
{112,56,56}, {112,68,56},
{112,84,56}, {112,96,56},
{112,112,56}, {96,112,56},
{84,112,56}, {68,112,56}, /*144*/
{56,112,56}, {56,112,69},
{56,112,84}, {56,112,96},
{56,112,112}, {56,96,112},
{56,84,112}, {56,68,112},
{80,80,112}, {88,80,112},
{96,80,112}, {104,80,112},
{112,80,112}, {112,80,104},
{112,80,96}, {112,80,88}, /*160*/
{112,80,80}, {112,88,80},
{112,96,80}, {112,104,80},
{112,112,80}, {104,112,80},
{96,112,80}, {88,112,80},
{80,112,80}, {80,112,88},
{80,112,96}, {80,112,104},
{80,112,112}, {80,114,112},
{80,96,112}, {80,88,112}, /*176*/
{0,0,64}, {16,0,64},
{32,0,64}, {48,0,64},
{64,0,64}, {64,0,48},
{64,0,32}, {64,0,16},
{64,0,0}, {64,16,0},
{64,32,0}, {64,48,0},
{64,64,0}, {48,64,0},
{32,64,0}, {16,64,0}, /*192*/
{0,64,0}, {0,64,16},
{0,64,32}, {0,64,48},
{0,64,64}, {0,48,64},
{0,32,64}, {0,16,64},
{32,32,64}, {40,32,64},
{48,32,64}, {56,32,64},
{64,32,64}, {64,32,56},
{64,32,48}, {64,32,40}, /*208*/
{64,32,32}, {64,40,32},
{64,48,32}, {64,56,32},
{64,64,32}, {56,64,32},
{48,64,32}, {40,64,32},
{32,64,32}, {32,64,40},
{32,64,48}, {32,64,56},
{32,64,64}, {32,56,64},
{32,48,64}, {32,40,64}, /*224*/
{44,44,64}, {48,44,64},
{52,44,64}, {60,44,64},
{64,44,64}, {64,44,60},
{64,44,52}, {64,44,48},
{64,44,44}, {64,48,44},
{64,52,44}, {64,60,44},
{64,64,44}, {60,64,44},
{52,64,44}, {48,64,44}, /*240*/
{44,64,44}, {44,64,48},
{44,64,52}, {44,64,60},
{44,64,64}, {44,60,64},
{44,55,64}, {44,48,64},
{0,0,0}, {0,0,0},
{0,0,0}, {0,0,0},
{0,0,0}, {0,0,0},
{0,0,0}, {0,0,0} /*256*/
};
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s W P G %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsWPG() returns True if the image format type, identified by the magick
% string, is WPG.
%
% The format of the IsWPG method is:
%
% unsigned int IsWPG(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o status: Method IsWPG returns True if the image format type is WPG.
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static unsigned int IsWPG(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (memcmp(magick,"\377WPC",4) == 0)
return(MagickTrue);
return(MagickFalse);
}
static void Rd_WP_DWORD(Image *image,size_t *d)
{
unsigned char
b;
b=ReadBlobByte(image);
*d=b;
if (b < 0xFFU)
return;
b=ReadBlobByte(image);
*d=(size_t) b;
b=ReadBlobByte(image);
*d+=(size_t) b*256l;
if (*d < 0x8000)
return;
*d=(*d & 0x7FFF) << 16;
b=ReadBlobByte(image);
*d+=(size_t) b;
b=ReadBlobByte(image);
*d+=(size_t) b*256l;
return;
}
static void InsertRow(unsigned char *p,ssize_t y,Image *image, int bpp)
{
ExceptionInfo
*exception;
int
bit;
ssize_t
x;
register PixelPacket
*q;
IndexPacket
index;
register IndexPacket
*indexes;
exception=(&image->exception);
switch (bpp)
{
case 1: /* Convert bitmap scanline. */
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < ((ssize_t) image->columns-7); x+=8)
{
for (bit=0; bit < 8; bit++)
{
index=((*p) & (0x80 >> bit) ? 0x01 : 0x00);
SetPixelIndex(indexes+x+bit,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
}
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=0; bit < (ssize_t) (image->columns % 8); bit++)
{
index=((*p) & (0x80 >> bit) ? 0x01 : 0x00);
SetPixelIndex(indexes+x+bit,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
}
p++;
}
if (!SyncAuthenticPixels(image,exception))
break;
break;
}
case 2: /* Convert PseudoColor scanline. */
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < ((ssize_t) image->columns-3); x+=4)
{
index=ConstrainColormapIndex(image,(*p >> 6) & 0x3);
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
index=ConstrainColormapIndex(image,(*p >> 4) & 0x3);
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
index=ConstrainColormapIndex(image,(*p >> 2) & 0x3);
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
index=ConstrainColormapIndex(image,(*p) & 0x3);
SetPixelIndex(indexes+x+1,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
p++;
}
if ((image->columns % 4) != 0)
{
index=ConstrainColormapIndex(image,(*p >> 6) & 0x3);
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
if ((image->columns % 4) > 1)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0x3);
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
if ((image->columns % 4) > 2)
{
index=ConstrainColormapIndex(image,(*p >> 2) & 0x3);
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
}
}
p++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
break;
}
case 4: /* Convert PseudoColor scanline. */
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < ((ssize_t) image->columns-1); x+=2)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f);
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
index=ConstrainColormapIndex(image,(*p) & 0x0f);
SetPixelIndex(indexes+x+1,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
p++;
q++;
}
if ((image->columns % 2) != 0)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f);
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
p++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
break;
}
case 8: /* Convert PseudoColor scanline. */
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL) break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ConstrainColormapIndex(image,*p);
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
p++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
break;
case 24: /* Convert DirectColor scanline. */
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(*p++));
SetPixelGreen(q,ScaleCharToQuantum(*p++));
SetPixelBlue(q,ScaleCharToQuantum(*p++));
q++;
}
if (!SyncAuthenticPixels(image,exception))
break;
break;
}
}
/* Helper for WPG1 raster reader. */
#define InsertByte(b) \
{ \
BImgBuff[x]=b; \
x++; \
if((ssize_t) x>=ldblk) \
{ \
InsertRow(BImgBuff,(ssize_t) y,image,bpp); \
x=0; \
y++; \
} \
}
/* WPG1 raster reader. */
static int UnpackWPGRaster(Image *image,int bpp)
{
int
x,
y,
i;
unsigned char
bbuf,
*BImgBuff,
RunCount;
ssize_t
ldblk;
x=0;
y=0;
ldblk=(ssize_t) ((bpp*image->columns+7)/8);
BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk,
8*sizeof(*BImgBuff));
if(BImgBuff==NULL) return(-2);
while(y<(ssize_t) image->rows)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
bbuf=(unsigned char) c;
RunCount=bbuf & 0x7F;
if(bbuf & 0x80)
{
if(RunCount) /* repeat next byte runcount * */
{
bbuf=ReadBlobByte(image);
for(i=0;i<(int) RunCount;i++) InsertByte(bbuf);
}
else { /* read next byte as RunCount; repeat 0xFF runcount* */
c=ReadBlobByte(image);
if (c < 0)
break;
RunCount=(unsigned char) c;
for(i=0;i<(int) RunCount;i++) InsertByte(0xFF);
}
}
else {
if(RunCount) /* next runcount byte are readed directly */
{
for(i=0;i < (int) RunCount;i++)
{
bbuf=ReadBlobByte(image);
InsertByte(bbuf);
}
}
else { /* repeat previous line runcount* */
c=ReadBlobByte(image);
if (c < 0)
break;
RunCount=(unsigned char) c;
if(x) { /* attempt to duplicate row from x position: */
/* I do not know what to do here */
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
return(-3);
}
for(i=0;i < (int) RunCount;i++)
{
x=0;
y++; /* Here I need to duplicate previous row RUNCOUNT* */
if(y<2) continue;
if(y>(ssize_t) image->rows)
{
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
return(-4);
}
InsertRow(BImgBuff,y-1,image,bpp);
}
}
}
}
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
return(y < (ssize_t) image->rows ? -5 : 0);
}
/* Helper for WPG2 reader. */
#define InsertByte6(b) \
{ \
DisableMSCWarning(4310) \
if(XorMe)\
BImgBuff[x] = (unsigned char)~b;\
else\
BImgBuff[x] = b;\
RestoreMSCWarning \
x++; \
if((ssize_t) x >= ldblk) \
{ \
InsertRow(BImgBuff,(ssize_t) y,image,bpp); \
x=0; \
y++; \
} \
}
/* WPG2 raster reader. */
static int UnpackWPG2Raster(Image *image,int bpp)
{
int XorMe = 0;
int
RunCount;
size_t
x,
y;
ssize_t
i,
ldblk;
unsigned int
SampleSize=1;
unsigned char
bbuf,
*BImgBuff,
SampleBuffer[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
x=0;
y=0;
ldblk=(ssize_t) ((bpp*image->columns+7)/8);
BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk,
sizeof(*BImgBuff));
if(BImgBuff==NULL)
return(-2);
while( y< image->rows)
{
bbuf=ReadBlobByte(image);
switch(bbuf)
{
case 0x7D:
SampleSize=ReadBlobByte(image); /* DSZ */
if(SampleSize>8)
return(-2);
if(SampleSize<1)
return(-2);
break;
case 0x7E:
(void) FormatLocaleFile(stderr,
"\nUnsupported WPG token XOR, please report!");
XorMe=!XorMe;
break;
case 0x7F:
RunCount=ReadBlobByte(image); /* BLK */
if (RunCount < 0)
break;
for(i=0; i < SampleSize*(RunCount+1); i++)
{
InsertByte6(0);
}
break;
case 0xFD:
RunCount=ReadBlobByte(image); /* EXT */
if (RunCount < 0)
break;
for(i=0; i<= RunCount;i++)
for(bbuf=0; bbuf < SampleSize; bbuf++)
InsertByte6(SampleBuffer[bbuf]);
break;
case 0xFE:
RunCount=ReadBlobByte(image); /* RST */
if (RunCount < 0)
break;
if(x!=0)
{
(void) FormatLocaleFile(stderr,
"\nUnsupported WPG2 unaligned token RST x=%.20g, please report!\n"
,(double) x);
return(-3);
}
{
/* duplicate the previous row RunCount x */
for(i=0;i<=RunCount;i++)
{
InsertRow(BImgBuff,(ssize_t) (image->rows >= y ? y : image->rows-1),
image,bpp);
y++;
}
}
break;
case 0xFF:
RunCount=ReadBlobByte(image); /* WHT */
if (RunCount < 0)
break;
for (i=0; i < SampleSize*(RunCount+1); i++)
{
InsertByte6(0xFF);
}
break;
default:
RunCount=bbuf & 0x7F;
if(bbuf & 0x80) /* REP */
{
for(i=0; i < SampleSize; i++)
SampleBuffer[i]=ReadBlobByte(image);
for(i=0;i<=RunCount;i++)
for(bbuf=0;bbuf<SampleSize;bbuf++)
InsertByte6(SampleBuffer[bbuf]);
}
else { /* NRP */
for(i=0; i< SampleSize*(RunCount+1);i++)
{
bbuf=ReadBlobByte(image);
InsertByte6(bbuf);
}
}
}
}
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
return(0);
}
typedef float tCTM[3][3];
static unsigned LoadWPG2Flags(Image *image,char Precision,float *Angle,tCTM *CTM)
{
const unsigned char TPR=1,TRN=2,SKW=4,SCL=8,ROT=0x10,OID=0x20,LCK=0x80;
ssize_t x;
unsigned DenX;
unsigned Flags;
(void) memset(*CTM,0,sizeof(*CTM)); /*CTM.erase();CTM.resize(3,3);*/
(*CTM)[0][0]=1;
(*CTM)[1][1]=1;
(*CTM)[2][2]=1;
Flags=ReadBlobLSBShort(image);
if(Flags & LCK) (void) ReadBlobLSBLong(image); /*Edit lock*/
if(Flags & OID)
{
if(Precision==0)
{(void) ReadBlobLSBShort(image);} /*ObjectID*/
else
{(void) ReadBlobLSBLong(image);} /*ObjectID (Double precision)*/
}
if(Flags & ROT)
{
x=ReadBlobLSBLong(image); /*Rot Angle*/
if(Angle) *Angle=x/65536.0;
}
if(Flags & (ROT|SCL))
{
x=ReadBlobLSBLong(image); /*Sx*cos()*/
(*CTM)[0][0] = (float)x/0x10000;
x=ReadBlobLSBLong(image); /*Sy*cos()*/
(*CTM)[1][1] = (float)x/0x10000;
}
if(Flags & (ROT|SKW))
{
x=ReadBlobLSBLong(image); /*Kx*sin()*/
(*CTM)[1][0] = (float)x/0x10000;
x=ReadBlobLSBLong(image); /*Ky*sin()*/
(*CTM)[0][1] = (float)x/0x10000;
}
if(Flags & TRN)
{
x=ReadBlobLSBLong(image); DenX=ReadBlobLSBShort(image); /*Tx*/
if(x>=0) (*CTM)[0][2] = (float)x+(float)DenX/0x10000;
else (*CTM)[0][2] = (float)x-(float)DenX/0x10000;
x=ReadBlobLSBLong(image); DenX=ReadBlobLSBShort(image); /*Ty*/
(*CTM)[1][2]=(float)x + ((x>=0)?1:-1)*(float)DenX/0x10000;
if(x>=0) (*CTM)[1][2] = (float)x+(float)DenX/0x10000;
else (*CTM)[1][2] = (float)x-(float)DenX/0x10000;
}
if(Flags & TPR)
{
x=ReadBlobLSBShort(image); DenX=ReadBlobLSBShort(image); /*Px*/
(*CTM)[2][0] = x + (float)DenX/0x10000;;
x=ReadBlobLSBShort(image); DenX=ReadBlobLSBShort(image); /*Py*/
(*CTM)[2][1] = x + (float)DenX/0x10000;
}
return(Flags);
}
static Image *ExtractPostscript(Image *image,const ImageInfo *image_info,
MagickOffsetType PS_Offset,ssize_t PS_Size,ExceptionInfo *exception)
{
char
postscript_file[MaxTextExtent];
const MagicInfo
*magic_info;
FILE
*ps_file;
ImageInfo
*clone_info;
Image
*image2;
unsigned char
magick[2*MaxTextExtent];
if ((clone_info=CloneImageInfo(image_info)) == NULL)
return(image);
clone_info->blob=(void *) NULL;
clone_info->length=0;
/* Obtain temporary file */
(void) AcquireUniqueFilename(postscript_file);
ps_file=fopen_utf8(postscript_file,"wb");
if (ps_file == (FILE *) NULL)
goto FINISH;
/* Copy postscript to temporary file */
(void) SeekBlob(image,PS_Offset,SEEK_SET);
(void) ReadBlob(image, 2*MaxTextExtent, magick);
(void) SeekBlob(image,PS_Offset,SEEK_SET);
while(PS_Size-- > 0)
{
(void) fputc(ReadBlobByte(image),ps_file);
}
(void) fclose(ps_file);
/* Detect file format - Check magic.mgk configuration file. */
magic_info=GetMagicInfo(magick,2*MaxTextExtent,exception);
if(magic_info == (const MagicInfo *) NULL) goto FINISH_UNL;
/* printf("Detected:%s \n",magic_info->name); */
if(exception->severity != UndefinedException) goto FINISH_UNL;
if(magic_info->name == (char *) NULL) goto FINISH_UNL;
(void) strncpy(clone_info->magick,magic_info->name,MaxTextExtent);
/* Read nested image */
/*FormatString(clone_info->filename,"%s:%s",magic_info->name,postscript_file);*/
FormatLocaleString(clone_info->filename,MaxTextExtent,"%s",postscript_file);
image2=ReadImage(clone_info,exception);
if (!image2)
goto FINISH_UNL;
/*
Replace current image with new image while copying base image
attributes.
*/
(void) CopyMagickMemory(image2->filename,image->filename,MaxTextExtent);
(void) CopyMagickMemory(image2->magick_filename,image->magick_filename,MaxTextExtent);
(void) CopyMagickMemory(image2->magick,image->magick,MaxTextExtent);
image2->depth=image->depth;
DestroyBlob(image2);
image2->blob=ReferenceBlob(image->blob);
if ((image->rows == 0) || (image->columns == 0))
DeleteImageFromList(&image);
AppendImageToList(&image,image2);
FINISH_UNL:
(void) RelinquishUniqueFileResource(postscript_file);
FINISH:
DestroyImageInfo(clone_info);
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d W P G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method ReadWPGImage reads an WPG X 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 ReadWPGImage method is:
%
% Image *ReadWPGImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: Method ReadWPGImage returns a pointer to the image after
% reading. A null image is returned if there is a memory shortage or if
% the image cannot be read.
%
% o image_info: Specifies a pointer to a ImageInfo structure.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadWPGImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
typedef struct
{
size_t FileId;
MagickOffsetType DataOffset;
unsigned int ProductType;
unsigned int FileType;
unsigned char MajorVersion;
unsigned char MinorVersion;
unsigned int EncryptKey;
unsigned int Reserved;
} WPGHeader;
typedef struct
{
unsigned char RecType;
size_t RecordLength;
} WPGRecord;
typedef struct
{
unsigned char Class;
unsigned char RecType;
size_t Extension;
size_t RecordLength;
} WPG2Record;
typedef struct
{
unsigned HorizontalUnits;
unsigned VerticalUnits;
unsigned char PosSizePrecision;
} WPG2Start;
typedef struct
{
unsigned int Width;
unsigned int Height;
unsigned int Depth;
unsigned int HorzRes;
unsigned int VertRes;
} WPGBitmapType1;
typedef struct
{
unsigned int Width;
unsigned int Height;
unsigned char Depth;
unsigned char Compression;
} WPG2BitmapType1;
typedef struct
{
unsigned int RotAngle;
unsigned int LowLeftX;
unsigned int LowLeftY;
unsigned int UpRightX;
unsigned int UpRightY;
unsigned int Width;
unsigned int Height;
unsigned int Depth;
unsigned int HorzRes;
unsigned int VertRes;
} WPGBitmapType2;
typedef struct
{
unsigned int StartIndex;
unsigned int NumOfEntries;
} WPGColorMapRec;
/*
typedef struct {
size_t PS_unknown1;
unsigned int PS_unknown2;
unsigned int PS_unknown3;
} WPGPSl1Record;
*/
Image
*image;
unsigned int
status;
WPGHeader
Header;
WPGRecord
Rec;
WPG2Record
Rec2;
WPG2Start StartWPG;
WPGBitmapType1
BitmapHeader1;
WPG2BitmapType1
Bitmap2Header1;
WPGBitmapType2
BitmapHeader2;
WPGColorMapRec
WPG_Palette;
int
i,
bpp,
WPG2Flags;
ssize_t
ldblk;
size_t
one;
unsigned char
*BImgBuff;
tCTM CTM; /*current transform matrix*/
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
one=1;
image=AcquireImage(image_info);
image->depth=8;
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read WPG image.
*/
Header.FileId=ReadBlobLSBLong(image);
Header.DataOffset=(MagickOffsetType) ReadBlobLSBLong(image);
Header.ProductType=ReadBlobLSBShort(image);
Header.FileType=ReadBlobLSBShort(image);
Header.MajorVersion=ReadBlobByte(image);
Header.MinorVersion=ReadBlobByte(image);
Header.EncryptKey=ReadBlobLSBShort(image);
Header.Reserved=ReadBlobLSBShort(image);
if (Header.FileId!=0x435057FF || (Header.ProductType>>8)!=0x16)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (Header.EncryptKey!=0)
ThrowReaderException(CoderError,"EncryptedWPGImageFileNotSupported");
image->columns = 1;
image->rows = 1;
image->colors = 0;
bpp=0;
BitmapHeader2.RotAngle=0;
switch(Header.FileType)
{
case 1: /* WPG level 1 */
while(!EOFBlob(image)) /* object parser loop */
{
(void) SeekBlob(image,Header.DataOffset,SEEK_SET);
if(EOFBlob(image))
break;
Rec.RecType=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rd_WP_DWORD(image,&Rec.RecordLength);
if(EOFBlob(image))
break;
Header.DataOffset=TellBlob(image)+Rec.RecordLength;
switch(Rec.RecType)
{
case 0x0B: /* bitmap type 1 */
BitmapHeader1.Width=ReadBlobLSBShort(image);
BitmapHeader1.Height=ReadBlobLSBShort(image);
if ((BitmapHeader1.Width == 0) || (BitmapHeader1.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
BitmapHeader1.Depth=ReadBlobLSBShort(image);
BitmapHeader1.HorzRes=ReadBlobLSBShort(image);
BitmapHeader1.VertRes=ReadBlobLSBShort(image);
if(BitmapHeader1.HorzRes && BitmapHeader1.VertRes)
{
image->units=PixelsPerCentimeterResolution;
image->x_resolution=BitmapHeader1.HorzRes/470.0;
image->y_resolution=BitmapHeader1.VertRes/470.0;
}
image->columns=BitmapHeader1.Width;
image->rows=BitmapHeader1.Height;
bpp=BitmapHeader1.Depth;
goto UnpackRaster;
case 0x0E: /*Color palette */
WPG_Palette.StartIndex=ReadBlobLSBShort(image);
WPG_Palette.NumOfEntries=ReadBlobLSBShort(image);
image->colors=WPG_Palette.NumOfEntries;
if (!AcquireImageColormap(image,image->colors))
goto NoMemory;
for (i=WPG_Palette.StartIndex;
i < (int)WPG_Palette.NumOfEntries; i++)
{
image->colormap[i].red=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->colormap[i].green=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->colormap[i].blue=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
}
break;
case 0x11: /* Start PS l1 */
if(Rec.RecordLength > 8)
image=ExtractPostscript(image,image_info,
TellBlob(image)+8, /* skip PS header in the wpg */
(ssize_t) Rec.RecordLength-8,exception);
break;
case 0x14: /* bitmap type 2 */
BitmapHeader2.RotAngle=ReadBlobLSBShort(image);
BitmapHeader2.LowLeftX=ReadBlobLSBShort(image);
BitmapHeader2.LowLeftY=ReadBlobLSBShort(image);
BitmapHeader2.UpRightX=ReadBlobLSBShort(image);
BitmapHeader2.UpRightY=ReadBlobLSBShort(image);
BitmapHeader2.Width=ReadBlobLSBShort(image);
BitmapHeader2.Height=ReadBlobLSBShort(image);
if ((BitmapHeader2.Width == 0) || (BitmapHeader2.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
BitmapHeader2.Depth=ReadBlobLSBShort(image);
BitmapHeader2.HorzRes=ReadBlobLSBShort(image);
BitmapHeader2.VertRes=ReadBlobLSBShort(image);
image->units=PixelsPerCentimeterResolution;
image->page.width=(unsigned int)
((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightX)/470.0);
image->page.height=(unsigned int)
((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightY)/470.0);
image->page.x=(int) (BitmapHeader2.LowLeftX/470.0);
image->page.y=(int) (BitmapHeader2.LowLeftX/470.0);
if(BitmapHeader2.HorzRes && BitmapHeader2.VertRes)
{
image->x_resolution=BitmapHeader2.HorzRes/470.0;
image->y_resolution=BitmapHeader2.VertRes/470.0;
}
image->columns=BitmapHeader2.Width;
image->rows=BitmapHeader2.Height;
bpp=BitmapHeader2.Depth;
UnpackRaster:
if ((image->colors == 0) && (bpp != 24))
{
image->colors=one << bpp;
if (!AcquireImageColormap(image,image->colors))
{
NoMemory:
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
/* printf("Load default colormap \n"); */
for (i=0; (i < (int) image->colors) && (i < 256); i++)
{
image->colormap[i].red=ScaleCharToQuantum(WPG1_Palette[i].Red);
image->colormap[i].green=ScaleCharToQuantum(WPG1_Palette[i].Green);
image->colormap[i].blue=ScaleCharToQuantum(WPG1_Palette[i].Blue);
}
}
else
{
if (bpp < 24)
if ( (image->colors < (one << bpp)) && (bpp != 24) )
image->colormap=(PixelPacket *) ResizeQuantumMemory(
image->colormap,(size_t) (one << bpp),
sizeof(*image->colormap));
}
if (bpp == 1)
{
if(image->colormap[0].red==0 &&
image->colormap[0].green==0 &&
image->colormap[0].blue==0 &&
image->colormap[1].red==0 &&
image->colormap[1].green==0 &&
image->colormap[1].blue==0)
{ /* fix crippled monochrome palette */
image->colormap[1].red =
image->colormap[1].green =
image->colormap[1].blue = QuantumRange;
}
}
if(UnpackWPGRaster(image,bpp) < 0)
/* The raster cannot be unpacked */
{
DecompressionFailed:
ThrowReaderException(CoderError,"UnableToDecompressImage");
}
if(Rec.RecType==0x14 && BitmapHeader2.RotAngle!=0 && !image_info->ping)
{
/* flop command */
if(BitmapHeader2.RotAngle & 0x8000)
{
Image
*flop_image;
flop_image = FlopImage(image, exception);
if (flop_image != (Image *) NULL) {
DuplicateBlob(flop_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flop_image);
}
}
/* flip command */
if(BitmapHeader2.RotAngle & 0x2000)
{
Image
*flip_image;
flip_image = FlipImage(image, exception);
if (flip_image != (Image *) NULL) {
DuplicateBlob(flip_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flip_image);
}
}
/* rotate command */
if(BitmapHeader2.RotAngle & 0x0FFF)
{
Image
*rotate_image;
rotate_image=RotateImage(image,(BitmapHeader2.RotAngle &
0x0FFF), exception);
if (rotate_image != (Image *) NULL) {
DuplicateBlob(rotate_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,rotate_image);
}
}
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image);
image->depth=8;
if (image->next == (Image *) NULL)
goto Finish;
image=SyncNextImageInList(image);
image->columns=image->rows=1;
image->colors=0;
break;
case 0x1B: /* Postscript l2 */
if(Rec.RecordLength>0x3C)
image=ExtractPostscript(image,image_info,
TellBlob(image)+0x3C, /* skip PS l2 header in the wpg */
(ssize_t) Rec.RecordLength-0x3C,exception);
break;
}
}
break;
case 2: /* WPG level 2 */
(void) memset(CTM,0,sizeof(CTM));
StartWPG.PosSizePrecision = 0;
while(!EOFBlob(image)) /* object parser loop */
{
(void) SeekBlob(image,Header.DataOffset,SEEK_SET);
if(EOFBlob(image))
break;
Rec2.Class=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rec2.RecType=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rd_WP_DWORD(image,&Rec2.Extension);
Rd_WP_DWORD(image,&Rec2.RecordLength);
if(EOFBlob(image))
break;
Header.DataOffset=TellBlob(image)+Rec2.RecordLength;
switch(Rec2.RecType)
{
case 1:
StartWPG.HorizontalUnits=ReadBlobLSBShort(image);
StartWPG.VerticalUnits=ReadBlobLSBShort(image);
StartWPG.PosSizePrecision=ReadBlobByte(image);
break;
case 0x0C: /* Color palette */
WPG_Palette.StartIndex=ReadBlobLSBShort(image);
WPG_Palette.NumOfEntries=ReadBlobLSBShort(image);
image->colors=WPG_Palette.NumOfEntries;
if (AcquireImageColormap(image,image->colors) == MagickFalse)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
for (i=WPG_Palette.StartIndex;
i < (int)WPG_Palette.NumOfEntries; i++)
{
image->colormap[i].red=ScaleCharToQuantum((char)
ReadBlobByte(image));
image->colormap[i].green=ScaleCharToQuantum((char)
ReadBlobByte(image));
image->colormap[i].blue=ScaleCharToQuantum((char)
ReadBlobByte(image));
(void) ReadBlobByte(image); /*Opacity??*/
}
break;
case 0x0E:
Bitmap2Header1.Width=ReadBlobLSBShort(image);
Bitmap2Header1.Height=ReadBlobLSBShort(image);
if ((Bitmap2Header1.Width == 0) || (Bitmap2Header1.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
Bitmap2Header1.Depth=ReadBlobByte(image);
Bitmap2Header1.Compression=ReadBlobByte(image);
if(Bitmap2Header1.Compression > 1)
continue; /*Unknown compression method */
switch(Bitmap2Header1.Depth)
{
case 1:
bpp=1;
break;
case 2:
bpp=2;
break;
case 3:
bpp=4;
break;
case 4:
bpp=8;
break;
case 8:
bpp=24;
break;
default:
continue; /*Ignore raster with unknown depth*/
}
image->columns=Bitmap2Header1.Width;
image->rows=Bitmap2Header1.Height;
if ((image->colors == 0) && (bpp != 24))
{
size_t
one;
one=1;
image->colors=one << bpp;
if (!AcquireImageColormap(image,image->colors))
goto NoMemory;
}
else
{
if(bpp < 24)
if( image->colors<(one << bpp) && bpp!=24 )
image->colormap=(PixelPacket *) ResizeQuantumMemory(
image->colormap,(size_t) (one << bpp),
sizeof(*image->colormap));
}
switch(Bitmap2Header1.Compression)
{
case 0: /*Uncompressed raster*/
{
ldblk=(ssize_t) ((bpp*image->columns+7)/8);
BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t)
ldblk,sizeof(*BImgBuff));
if (BImgBuff == (unsigned char *) NULL)
goto NoMemory;
for(i=0; i< (ssize_t) image->rows; i++)
{
(void) ReadBlob(image,ldblk,BImgBuff);
InsertRow(BImgBuff,i,image,bpp);
}
if(BImgBuff)
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
break;
}
case 1: /*RLE for WPG2 */
{
if( UnpackWPG2Raster(image,bpp) < 0)
goto DecompressionFailed;
break;
}
}
if(CTM[0][0]<0 && !image_info->ping)
{ /*?? RotAngle=360-RotAngle;*/
Image
*flop_image;
flop_image = FlopImage(image, exception);
if (flop_image != (Image *) NULL) {
DuplicateBlob(flop_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flop_image);
}
/* Try to change CTM according to Flip - I am not sure, must be checked.
Tx(0,0)=-1; Tx(1,0)=0; Tx(2,0)=0;
Tx(0,1)= 0; Tx(1,1)=1; Tx(2,1)=0;
Tx(0,2)=(WPG._2Rect.X_ur+WPG._2Rect.X_ll);
Tx(1,2)=0; Tx(2,2)=1; */
}
if(CTM[1][1]<0 && !image_info->ping)
{ /*?? RotAngle=360-RotAngle;*/
Image
*flip_image;
flip_image = FlipImage(image, exception);
if (flip_image != (Image *) NULL) {
DuplicateBlob(flip_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flip_image);
}
/* Try to change CTM according to Flip - I am not sure, must be checked.
float_matrix Tx(3,3);
Tx(0,0)= 1; Tx(1,0)= 0; Tx(2,0)=0;
Tx(0,1)= 0; Tx(1,1)=-1; Tx(2,1)=0;
Tx(0,2)= 0; Tx(1,2)=(WPG._2Rect.Y_ur+WPG._2Rect.Y_ll);
Tx(2,2)=1; */
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image);
image->depth=8;
if (image->next == (Image *) NULL)
goto Finish;
image=SyncNextImageInList(image);
image->columns=image->rows=1;
image->colors=0;
break;
case 0x12: /* Postscript WPG2*/
i=ReadBlobLSBShort(image);
if(Rec2.RecordLength > (unsigned int) i)
image=ExtractPostscript(image,image_info,
TellBlob(image)+i, /*skip PS header in the wpg2*/
(ssize_t) (Rec2.RecordLength-i-2),exception);
break;
case 0x1B: /*bitmap rectangle*/
WPG2Flags = LoadWPG2Flags(image,StartWPG.PosSizePrecision,NULL,&CTM);
(void) WPG2Flags;
break;
}
}
break;
default:
{
ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported");
}
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
Finish:
(void) CloseBlob(image);
{
Image
*p;
ssize_t
scene=0;
/*
Rewind list, removing any empty images while rewinding.
*/
p=image;
image=NULL;
while (p != (Image *) NULL)
{
Image *tmp=p;
if ((p->rows == 0) || (p->columns == 0)) {
p=p->previous;
DeleteImageFromList(&tmp);
} else {
image=p;
p=p->previous;
}
}
/*
Fix scene numbers.
*/
for (p=image; p != (Image *) NULL; p=p->next)
p->scene=(size_t) scene++;
}
if (image == (Image *) NULL)
ThrowReaderException(CorruptImageError,
"ImageFileDoesNotContainAnyImageData");
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r W P G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method RegisterWPGImage adds attributes for the WPG 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 RegisterWPGImage method is:
%
% size_t RegisterWPGImage(void)
%
*/
ModuleExport size_t RegisterWPGImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("WPG");
entry->decoder=(DecodeImageHandler *) ReadWPGImage;
entry->magick=(IsImageFormatHandler *) IsWPG;
entry->description=AcquireString("Word Perfect Graphics");
entry->module=ConstantString("WPG");
entry->seekable_stream=MagickTrue;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r W P G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method UnregisterWPGImage removes format registrations made by the
% WPG module from the list of supported formats.
%
% The format of the UnregisterWPGImage method is:
%
% UnregisterWPGImage(void)
%
*/
ModuleExport void UnregisterWPGImage(void)
{
(void) UnregisterMagickInfo("WPG");
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_5305_0 |
crossvul-cpp_data_good_526_1 | /*
* GPAC - Multimedia Framework C SDK
*
* Authors: Jean Le Feuvre
* Copyright (c) Telecom ParisTech 2000-2012
* All rights reserved
*
* This file is part of GPAC / Media Tools sub-project
*
* GPAC 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, or (at your option)
* any later version.
*
* GPAC 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; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
#include <gpac/constants.h>
#include <gpac/utf.h>
#include <gpac/xml.h>
#include <gpac/token.h>
#include <gpac/color.h>
#include <gpac/internal/media_dev.h>
#include <gpac/internal/isomedia_dev.h>
#ifndef GPAC_DISABLE_ISOM_WRITE
void gf_media_update_bitrate(GF_ISOFile *file, u32 track);
enum
{
GF_TEXT_IMPORT_NONE = 0,
GF_TEXT_IMPORT_SRT,
GF_TEXT_IMPORT_SUB,
GF_TEXT_IMPORT_TTXT,
GF_TEXT_IMPORT_TEXML,
GF_TEXT_IMPORT_WEBVTT,
GF_TEXT_IMPORT_TTML,
GF_TEXT_IMPORT_SWF_SVG,
};
#define REM_TRAIL_MARKS(__str, __sep) while (1) { \
u32 _len = (u32) strlen(__str); \
if (!_len) break; \
_len--; \
if (strchr(__sep, __str[_len])) __str[_len] = 0; \
else break; \
} \
s32 gf_text_get_utf_type(FILE *in_src)
{
u32 read;
unsigned char BOM[5];
read = (u32) fread(BOM, sizeof(char), 5, in_src);
if ((s32) read < 1)
return -1;
if ((BOM[0]==0xFF) && (BOM[1]==0xFE)) {
/*UTF32 not supported*/
if (!BOM[2] && !BOM[3]) return -1;
gf_fseek(in_src, 2, SEEK_SET);
return 3;
}
if ((BOM[0]==0xFE) && (BOM[1]==0xFF)) {
/*UTF32 not supported*/
if (!BOM[2] && !BOM[3]) return -1;
gf_fseek(in_src, 2, SEEK_SET);
return 2;
} else if ((BOM[0]==0xEF) && (BOM[1]==0xBB) && (BOM[2]==0xBF)) {
gf_fseek(in_src, 3, SEEK_SET);
return 1;
}
if (BOM[0]<0x80) {
gf_fseek(in_src, 0, SEEK_SET);
return 0;
}
return -1;
}
static GF_Err gf_text_guess_format(char *filename, u32 *fmt)
{
char szLine[2048];
u32 val;
s32 uni_type;
FILE *test = gf_fopen(filename, "rb");
if (!test) return GF_URL_ERROR;
uni_type = gf_text_get_utf_type(test);
if (uni_type>1) {
const u16 *sptr;
char szUTF[1024];
u32 read = (u32) fread(szUTF, 1, 1023, test);
if ((s32) read < 0) {
gf_fclose(test);
return GF_IO_ERR;
}
szUTF[read]=0;
sptr = (u16*)szUTF;
/*read = (u32) */gf_utf8_wcstombs(szLine, read, &sptr);
} else {
val = (u32) fread(szLine, 1, 1024, test);
if ((s32) val<0) return GF_IO_ERR;
szLine[val]=0;
}
REM_TRAIL_MARKS(szLine, "\r\n\t ")
*fmt = GF_TEXT_IMPORT_NONE;
if ((szLine[0]=='{') && strstr(szLine, "}{")) *fmt = GF_TEXT_IMPORT_SUB;
else if (szLine[0] == '<') {
char *ext = strrchr(filename, '.');
if (!strnicmp(ext, ".ttxt", 5)) *fmt = GF_TEXT_IMPORT_TTXT;
else if (!strnicmp(ext, ".ttml", 5)) *fmt = GF_TEXT_IMPORT_TTML;
ext = strstr(szLine, "?>");
if (ext) ext += 2;
if (ext && !ext[0]) {
if (!fgets(szLine, 2048, test))
szLine[0] = '\0';
}
if (strstr(szLine, "x-quicktime-tx3g") || strstr(szLine, "text3GTrack")) *fmt = GF_TEXT_IMPORT_TEXML;
else if (strstr(szLine, "TextStream")) *fmt = GF_TEXT_IMPORT_TTXT;
else if (strstr(szLine, "tt")) *fmt = GF_TEXT_IMPORT_TTML;
}
else if (strstr(szLine, "WEBVTT") )
*fmt = GF_TEXT_IMPORT_WEBVTT;
else if (strstr(szLine, " --> ") )
*fmt = GF_TEXT_IMPORT_SRT; /* might want to change the default to WebVTT */
gf_fclose(test);
return GF_OK;
}
#define TTXT_DEFAULT_WIDTH 400
#define TTXT_DEFAULT_HEIGHT 60
#define TTXT_DEFAULT_FONT_SIZE 18
#ifndef GPAC_DISABLE_MEDIA_IMPORT
void gf_text_get_video_size(GF_MediaImporter *import, u32 *width, u32 *height)
{
u32 w, h, f_w, f_h, i;
GF_ISOFile *dest = import->dest;
if (import->text_track_width && import->text_track_height) {
(*width) = import->text_track_width;
(*height) = import->text_track_height;
return;
}
f_w = f_h = 0;
for (i=0; i<gf_isom_get_track_count(dest); i++) {
switch (gf_isom_get_media_type(dest, i+1)) {
case GF_ISOM_MEDIA_SCENE:
case GF_ISOM_MEDIA_VISUAL:
case GF_ISOM_MEDIA_AUXV:
case GF_ISOM_MEDIA_PICT:
gf_isom_get_visual_info(dest, i+1, 1, &w, &h);
if (w > f_w) f_w = w;
if (h > f_h) f_h = h;
gf_isom_get_track_layout_info(dest, i+1, &w, &h, NULL, NULL, NULL);
if (w > f_w) f_w = w;
if (h > f_h) f_h = h;
break;
}
}
(*width) = f_w ? f_w : TTXT_DEFAULT_WIDTH;
(*height) = f_h ? f_h : TTXT_DEFAULT_HEIGHT;
}
void gf_text_import_set_language(GF_MediaImporter *import, u32 track)
{
if (import->esd && import->esd->langDesc) {
char lang[4];
lang[0] = (import->esd->langDesc->langCode>>16) & 0xFF;
lang[1] = (import->esd->langDesc->langCode>>8) & 0xFF;
lang[2] = (import->esd->langDesc->langCode) & 0xFF;
lang[3] = 0;
gf_isom_set_media_language(import->dest, track, lang);
}
}
#endif
char *gf_text_get_utf8_line(char *szLine, u32 lineSize, FILE *txt_in, s32 unicode_type)
{
u32 i, j, len;
char *sOK;
char szLineConv[1024];
unsigned short *sptr;
memset(szLine, 0, sizeof(char)*lineSize);
sOK = fgets(szLine, lineSize, txt_in);
if (!sOK) return NULL;
if (unicode_type<=1) {
j=0;
len = (u32) strlen(szLine);
for (i=0; i<len && j < sizeof(szLineConv) - 1; i++, j++) {
if (!unicode_type && (szLine[i] & 0x80)) {
/*non UTF8 (likely some win-CP)*/
if ((szLine[i+1] & 0xc0) != 0x80) {
if (j + 1 < sizeof(szLineConv) - 1) {
szLineConv[j] = 0xc0 | ((szLine[i] >> 6) & 0x3);
j++;
szLine[i] &= 0xbf;
}
else
break;
}
/*UTF8 2 bytes char*/
else if ( (szLine[i] & 0xe0) == 0xc0) {
// don't cut multibyte in the middle in there is no more room in dest
if (j + 1 < sizeof(szLineConv) - 1 && i + 1 < len) {
szLineConv[j] = szLine[i];
i++;
j++;
}
else {
break;
}
}
/*UTF8 3 bytes char*/
else if ( (szLine[i] & 0xf0) == 0xe0) {
if (j + 2 < sizeof(szLineConv) - 1 && i + 2 < len) {
szLineConv[j] = szLine[i];
i++;
j++;
szLineConv[j] = szLine[i];
i++;
j++;
}
else {
break;
}
}
/*UTF8 4 bytes char*/
else if ( (szLine[i] & 0xf8) == 0xf0) {
if (j + 3 < sizeof(szLineConv) - 1 && i + 3 < len) {
szLineConv[j] = szLine[i];
i++;
j++;
szLineConv[j] = szLine[i];
i++;
j++;
szLineConv[j] = szLine[i];
i++;
j++;
}
else {
break;
}
} else {
i+=1;
continue;
}
}
if (j < sizeof(szLineConv)-1 && i<len)
szLineConv[j] = szLine[i];
}
if (j >= sizeof(szLineConv))
szLineConv[sizeof(szLineConv) - 1] = 0;
else
szLineConv[j] = 0;
strcpy(szLine, szLineConv);
return sOK;
}
#ifdef GPAC_BIG_ENDIAN
if (unicode_type==3) {
#else
if (unicode_type==2) {
#endif
i=0;
while (1) {
char c;
if (!szLine[i] && !szLine[i+1]) break;
c = szLine[i+1];
szLine[i+1] = szLine[i];
szLine[i] = c;
i+=2;
}
}
sptr = (u16 *)szLine;
i = (u32) gf_utf8_wcstombs(szLineConv, 1024, (const unsigned short **) &sptr);
if (i >= (u32)ARRAY_LENGTH(szLineConv))
return NULL;
szLineConv[i] = 0;
strcpy(szLine, szLineConv);
/*this is ugly indeed: since input is UTF16-LE, there are many chances the fgets never reads the \0 after a \n*/
if (unicode_type==3) fgetc(txt_in);
return sOK;
}
#ifndef GPAC_DISABLE_MEDIA_IMPORT
static GF_Err gf_text_import_srt(GF_MediaImporter *import)
{
FILE *srt_in;
u32 track, timescale, i, count;
GF_TextConfig*cfg;
GF_Err e;
GF_StyleRecord rec;
GF_TextSample * samp;
GF_ISOSample *s;
u32 sh, sm, ss, sms, eh, em, es, ems, txt_line, char_len, char_line, nb_samp, j, duration, rem_styles;
Bool set_start_char, set_end_char, first_samp, rem_color;
u64 start, end, prev_end, file_size;
u32 state, curLine, line, len, ID, OCR_ES_ID, default_color;
s32 unicode_type;
char szLine[2048], szText[2048], *ptr;
unsigned short uniLine[5000], uniText[5000], *sptr;
srt_in = gf_fopen(import->in_name, "rt");
gf_fseek(srt_in, 0, SEEK_END);
file_size = gf_ftell(srt_in);
gf_fseek(srt_in, 0, SEEK_SET);
unicode_type = gf_text_get_utf_type(srt_in);
if (unicode_type<0) {
gf_fclose(srt_in);
return gf_import_message(import, GF_NOT_SUPPORTED, "Unsupported SRT UTF encoding");
}
cfg = NULL;
if (import->esd) {
if (!import->esd->slConfig) {
import->esd->slConfig = (GF_SLConfig *) gf_odf_desc_new(GF_ODF_SLC_TAG);
import->esd->slConfig->predefined = 2;
import->esd->slConfig->timestampResolution = 1000;
}
timescale = import->esd->slConfig->timestampResolution;
if (!timescale) timescale = 1000;
/*explicit text config*/
if (import->esd->decoderConfig && import->esd->decoderConfig->decoderSpecificInfo->tag == GF_ODF_TEXT_CFG_TAG) {
cfg = (GF_TextConfig *) import->esd->decoderConfig->decoderSpecificInfo;
import->esd->decoderConfig->decoderSpecificInfo = NULL;
}
ID = import->esd->ESID;
OCR_ES_ID = import->esd->OCRESID;
} else {
timescale = 1000;
OCR_ES_ID = ID = 0;
}
if (cfg && cfg->timescale) timescale = cfg->timescale;
track = gf_isom_new_track(import->dest, ID, GF_ISOM_MEDIA_TEXT, timescale);
if (!track) {
gf_fclose(srt_in);
return gf_import_message(import, gf_isom_last_error(import->dest), "Error creating text track");
}
gf_isom_set_track_enabled(import->dest, track, 1);
import->final_trackID = gf_isom_get_track_id(import->dest, track);
if (import->esd && !import->esd->ESID) import->esd->ESID = import->final_trackID;
if (OCR_ES_ID) gf_isom_set_track_reference(import->dest, track, GF_ISOM_REF_OCR, OCR_ES_ID);
/*setup track*/
if (cfg) {
char *firstFont = NULL;
/*set track info*/
gf_isom_set_track_layout_info(import->dest, track, cfg->text_width<<16, cfg->text_height<<16, 0, 0, cfg->layer);
/*and set sample descriptions*/
count = gf_list_count(cfg->sample_descriptions);
for (i=0; i<count; i++) {
GF_TextSampleDescriptor *sd= (GF_TextSampleDescriptor *)gf_list_get(cfg->sample_descriptions, i);
if (!sd->font_count) {
sd->fonts = (GF_FontRecord*)gf_malloc(sizeof(GF_FontRecord));
sd->font_count = 1;
sd->fonts[0].fontID = 1;
sd->fonts[0].fontName = gf_strdup("Serif");
}
if (!sd->default_style.fontID) sd->default_style.fontID = sd->fonts[0].fontID;
if (!sd->default_style.font_size) sd->default_style.font_size = 16;
if (!sd->default_style.text_color) sd->default_style.text_color = 0xFF000000;
/*store attribs*/
if (!i) rec = sd->default_style;
gf_isom_new_text_description(import->dest, track, sd, NULL, NULL, &state);
if (!firstFont) firstFont = sd->fonts[0].fontName;
}
gf_import_message(import, GF_OK, "Timed Text (SRT) import - text track %d x %d, font %s (size %d)", cfg->text_width, cfg->text_height, firstFont, rec.font_size);
gf_odf_desc_del((GF_Descriptor *)cfg);
} else {
u32 w, h;
GF_TextSampleDescriptor *sd;
gf_text_get_video_size(import, &w, &h);
/*have to work with default - use max size (if only one video, this means the text region is the
entire display, and with bottom alignment things should be fine...*/
gf_isom_set_track_layout_info(import->dest, track, w<<16, h<<16, 0, 0, 0);
sd = (GF_TextSampleDescriptor*)gf_odf_desc_new(GF_ODF_TX3G_TAG);
sd->fonts = (GF_FontRecord*)gf_malloc(sizeof(GF_FontRecord));
sd->font_count = 1;
sd->fonts[0].fontID = 1;
sd->fonts[0].fontName = gf_strdup(import->fontName ? import->fontName : "Serif");
sd->back_color = 0x00000000; /*transparent*/
sd->default_style.fontID = 1;
sd->default_style.font_size = import->fontSize ? import->fontSize : TTXT_DEFAULT_FONT_SIZE;
sd->default_style.text_color = 0xFFFFFFFF; /*white*/
sd->default_style.style_flags = 0;
sd->horiz_justif = 1; /*center of scene*/
sd->vert_justif = (s8) -1; /*bottom of scene*/
if (import->flags & GF_IMPORT_SKIP_TXT_BOX) {
sd->default_pos.top = sd->default_pos.left = sd->default_pos.right = sd->default_pos.bottom = 0;
} else {
if ((sd->default_pos.bottom==sd->default_pos.top) || (sd->default_pos.right==sd->default_pos.left)) {
sd->default_pos.left = import->text_x;
sd->default_pos.top = import->text_y;
sd->default_pos.right = (import->text_width ? import->text_width : w) + sd->default_pos.left;
sd->default_pos.bottom = (import->text_height ? import->text_height : h) + sd->default_pos.top;
}
}
/*store attribs*/
rec = sd->default_style;
gf_isom_new_text_description(import->dest, track, sd, NULL, NULL, &state);
gf_import_message(import, GF_OK, "Timed Text (SRT) import - text track %d x %d, font %s (size %d)", w, h, sd->fonts[0].fontName, rec.font_size);
gf_odf_desc_del((GF_Descriptor *)sd);
}
gf_text_import_set_language(import, track);
duration = (u32) (((Double) import->duration)*timescale/1000.0);
default_color = rec.text_color;
e = GF_OK;
state = 0;
end = prev_end = 0;
curLine = 0;
txt_line = 0;
set_start_char = set_end_char = GF_FALSE;
char_len = 0;
start = 0;
nb_samp = 0;
samp = gf_isom_new_text_sample();
first_samp = GF_TRUE;
while (1) {
char *sOK = gf_text_get_utf8_line(szLine, 2048, srt_in, unicode_type);
if (sOK) REM_TRAIL_MARKS(szLine, "\r\n\t ")
if (!sOK || !strlen(szLine)) {
rec.style_flags = 0;
rec.startCharOffset = rec.endCharOffset = 0;
if (txt_line) {
if (prev_end && (start != prev_end)) {
GF_TextSample * empty_samp = gf_isom_new_text_sample();
s = gf_isom_text_to_sample(empty_samp);
gf_isom_delete_text_sample(empty_samp);
if (state<=2) {
s->DTS = (u64) ((timescale*prev_end)/1000);
s->IsRAP = RAP;
gf_isom_add_sample(import->dest, track, 1, s);
nb_samp++;
}
gf_isom_sample_del(&s);
}
s = gf_isom_text_to_sample(samp);
if (state<=2) {
s->DTS = (u64) ((timescale*start)/1000);
s->IsRAP = RAP;
gf_isom_add_sample(import->dest, track, 1, s);
gf_isom_sample_del(&s);
nb_samp++;
prev_end = end;
}
txt_line = 0;
char_len = 0;
set_start_char = set_end_char = GF_FALSE;
rec.startCharOffset = rec.endCharOffset = 0;
gf_isom_text_reset(samp);
//gf_import_progress(import, nb_samp, nb_samp+1);
gf_set_progress("Importing SRT", gf_ftell(srt_in), file_size);
if (duration && (end >= duration)) break;
}
state = 0;
if (!sOK) break;
continue;
}
switch (state) {
case 0:
if (sscanf(szLine, "%u", &line) != 1) {
e = gf_import_message(import, GF_CORRUPTED_DATA, "Bad SRT formatting - expecting number got \"%s\"", szLine);
goto exit;
}
if (line != curLine + 1) gf_import_message(import, GF_OK, "WARNING: corrupted SRT frame %d after frame %d", line, curLine);
curLine = line;
state = 1;
break;
case 1:
if (sscanf(szLine, "%u:%u:%u,%u --> %u:%u:%u,%u", &sh, &sm, &ss, &sms, &eh, &em, &es, &ems) != 8) {
sh = eh = 0;
if (sscanf(szLine, "%u:%u,%u --> %u:%u,%u", &sm, &ss, &sms, &em, &es, &ems) != 6) {
e = gf_import_message(import, GF_CORRUPTED_DATA, "Error scanning SRT frame %d timing", curLine);
goto exit;
}
}
start = (3600*sh + 60*sm + ss)*1000 + sms;
if (start<end) {
gf_import_message(import, GF_OK, "WARNING: overlapping SRT frame %d - starts "LLD" ms is before end of previous one "LLD" ms - adjusting time stamps", curLine, start, end);
start = end;
}
end = (3600*eh + 60*em + es)*1000 + ems;
/*make stream start at 0 by inserting a fake AU*/
if (first_samp && (start>0)) {
s = gf_isom_text_to_sample(samp);
s->DTS = 0;
gf_isom_add_sample(import->dest, track, 1, s);
gf_isom_sample_del(&s);
nb_samp++;
}
rec.style_flags = 0;
state = 2;
if (end<=prev_end) {
gf_import_message(import, GF_OK, "WARNING: overlapping SRT frame %d end "LLD" is at or before previous end "LLD" - removing", curLine, end, prev_end);
start = end;
state = 3;
}
break;
default:
/*reset only when text is present*/
first_samp = GF_FALSE;
/*go to line*/
if (txt_line) {
gf_isom_text_add_text(samp, "\n", 1);
char_len += 1;
}
ptr = (char *) szLine;
{
size_t _len = gf_utf8_mbstowcs(uniLine, 5000, (const char **) &ptr);
if (_len == (size_t) -1) {
e = gf_import_message(import, GF_CORRUPTED_DATA, "Invalid UTF data (line %d)", curLine);
goto exit;
}
len = (u32) _len;
}
i=j=0;
rem_styles = 0;
rem_color = 0;
while (i<len) {
u32 font_style = 0;
u32 style_nb_chars = 0;
u32 style_def_type = 0;
if ( (uniLine[i]=='<') && (uniLine[i+2]=='>')) {
style_nb_chars = 3;
style_def_type = 1;
}
else if ( (uniLine[i]=='<') && (uniLine[i+1]=='/') && (uniLine[i+3]=='>')) {
style_def_type = 2;
style_nb_chars = 4;
}
else if (uniLine[i]=='<') {
const unsigned short* src = uniLine + i;
size_t alen = gf_utf8_wcstombs(szLine, 2048, (const unsigned short**) & src);
szLine[alen] = 0;
strlwr(szLine);
if (!strncmp(szLine, "<font ", 6) ) {
char *a_sep = strstr(szLine, "color");
if (a_sep) a_sep = strchr(a_sep, '"');
if (a_sep) {
char *e_sep = strchr(a_sep+1, '"');
if (e_sep) {
e_sep[0] = 0;
font_style = gf_color_parse(a_sep+1);
e_sep[0] = '"';
e_sep = strchr(e_sep+1, '>');
if (e_sep) {
style_nb_chars = (u32) (1 + e_sep - szLine);
style_def_type = 1;
}
}
}
}
else if (!strncmp(szLine, "</font>", 7) ) {
style_nb_chars = 7;
style_def_type = 2;
font_style = 0xFFFFFFFF;
}
//skip unknown
else {
char *a_sep = strstr(szLine, ">");
if (a_sep) {
style_nb_chars = (u32) (a_sep - szLine);
i += style_nb_chars;
continue;
}
}
}
/*start of new style*/
if (style_def_type==1) {
/*store prev style*/
if (set_end_char) {
assert(set_start_char);
gf_isom_text_add_style(samp, &rec);
set_end_char = set_start_char = GF_FALSE;
rec.style_flags &= ~rem_styles;
rem_styles = 0;
if (rem_color) {
rec.text_color = default_color;
rem_color = 0;
}
}
if (set_start_char && (rec.startCharOffset != j)) {
rec.endCharOffset = char_len + j;
if (rec.style_flags) gf_isom_text_add_style(samp, &rec);
}
switch (uniLine[i+1]) {
case 'b':
case 'B':
rec.style_flags |= GF_TXT_STYLE_BOLD;
set_start_char = GF_TRUE;
rec.startCharOffset = char_len + j;
break;
case 'i':
case 'I':
rec.style_flags |= GF_TXT_STYLE_ITALIC;
set_start_char = GF_TRUE;
rec.startCharOffset = char_len + j;
break;
case 'u':
case 'U':
rec.style_flags |= GF_TXT_STYLE_UNDERLINED;
set_start_char = GF_TRUE;
rec.startCharOffset = char_len + j;
break;
case 'f':
case 'F':
if (font_style) {
rec.text_color = font_style;
set_start_char = GF_TRUE;
rec.startCharOffset = char_len + j;
}
break;
}
i += style_nb_chars;
continue;
}
/*end of prev style*/
if (style_def_type==2) {
switch (uniLine[i+2]) {
case 'b':
case 'B':
rem_styles |= GF_TXT_STYLE_BOLD;
set_end_char = GF_TRUE;
rec.endCharOffset = char_len + j;
break;
case 'i':
case 'I':
rem_styles |= GF_TXT_STYLE_ITALIC;
set_end_char = GF_TRUE;
rec.endCharOffset = char_len + j;
break;
case 'u':
case 'U':
rem_styles |= GF_TXT_STYLE_UNDERLINED;
set_end_char = GF_TRUE;
rec.endCharOffset = char_len + j;
break;
case 'f':
case 'F':
if (font_style) {
rem_color = 1;
set_end_char = GF_TRUE;
rec.endCharOffset = char_len + j;
}
}
i+=style_nb_chars;
continue;
}
/*store style*/
if (set_end_char) {
gf_isom_text_add_style(samp, &rec);
set_end_char = GF_FALSE;
set_start_char = GF_TRUE;
rec.startCharOffset = char_len + j;
rec.style_flags &= ~rem_styles;
rem_styles = 0;
rec.text_color = default_color;
rem_color = 0;
}
uniText[j] = uniLine[i];
j++;
i++;
}
/*store last style*/
if (set_end_char) {
gf_isom_text_add_style(samp, &rec);
set_end_char = GF_FALSE;
set_start_char = GF_TRUE;
rec.startCharOffset = char_len + j;
rec.style_flags &= ~rem_styles;
}
char_line = j;
uniText[j] = 0;
sptr = (u16 *) uniText;
len = (u32) gf_utf8_wcstombs(szText, 5000, (const u16 **) &sptr);
gf_isom_text_add_text(samp, szText, len);
char_len += char_line;
txt_line ++;
break;
}
if (duration && (start >= duration)) {
end = 0;
break;
}
}
/*final flush*/
if (end && !(import->flags & GF_IMPORT_NO_TEXT_FLUSH ) ) {
gf_isom_text_reset(samp);
s = gf_isom_text_to_sample(samp);
s->DTS = (u64) ((timescale*end)/1000);
s->IsRAP = RAP;
gf_isom_add_sample(import->dest, track, 1, s);
gf_isom_sample_del(&s);
nb_samp++;
gf_isom_set_last_sample_duration(import->dest, track, 0);
} else {
if (duration && (start >= duration)) {
gf_isom_set_last_sample_duration(import->dest, track, (timescale*duration)/1000);
} else {
gf_isom_set_last_sample_duration(import->dest, track, 0);
}
}
gf_isom_delete_text_sample(samp);
gf_set_progress("Importing SRT", nb_samp, nb_samp);
exit:
if (e) gf_isom_remove_track(import->dest, track);
gf_fclose(srt_in);
return e;
}
/* Structure used to pass importer and track data to the parsers without exposing the GF_MediaImporter structure
used by WebVTT and Flash->SVG */
typedef struct {
GF_MediaImporter *import;
u32 timescale;
u32 track;
u32 descriptionIndex;
} GF_ISOFlusher;
#ifndef GPAC_DISABLE_VTT
static GF_Err gf_webvtt_import_report(void *user, GF_Err e, char *message, const char *line)
{
GF_ISOFlusher *flusher = (GF_ISOFlusher *)user;
return gf_import_message(flusher->import, e, message, line);
}
static void gf_webvtt_import_header(void *user, const char *config)
{
GF_ISOFlusher *flusher = (GF_ISOFlusher *)user;
gf_isom_update_webvtt_description(flusher->import->dest, flusher->track, flusher->descriptionIndex, config);
}
static void gf_webvtt_flush_sample_to_iso(void *user, GF_WebVTTSample *samp)
{
GF_ISOSample *s;
GF_ISOFlusher *flusher = (GF_ISOFlusher *)user;
//gf_webvtt_dump_sample(stdout, samp);
s = gf_isom_webvtt_to_sample(samp);
if (s) {
s->DTS = (u64) (flusher->timescale*gf_webvtt_sample_get_start(samp)/1000);
s->IsRAP = RAP;
gf_isom_add_sample(flusher->import->dest, flusher->track, flusher->descriptionIndex, s);
gf_isom_sample_del(&s);
}
gf_webvtt_sample_del(samp);
}
static GF_Err gf_text_import_webvtt(GF_MediaImporter *import)
{
GF_Err e;
u32 track;
u32 timescale;
u32 duration;
u32 descIndex=1;
u32 ID;
u32 OCR_ES_ID;
GF_GenericSubtitleConfig *cfg;
GF_WebVTTParser *vttparser;
GF_ISOFlusher flusher;
cfg = NULL;
if (import->esd) {
if (!import->esd->slConfig) {
import->esd->slConfig = (GF_SLConfig *) gf_odf_desc_new(GF_ODF_SLC_TAG);
import->esd->slConfig->predefined = 2;
import->esd->slConfig->timestampResolution = 1000;
}
timescale = import->esd->slConfig->timestampResolution;
if (!timescale) timescale = 1000;
/*explicit text config*/
if (import->esd->decoderConfig && import->esd->decoderConfig->decoderSpecificInfo->tag == GF_ODF_GEN_SUB_CFG_TAG) {
cfg = (GF_GenericSubtitleConfig *) import->esd->decoderConfig->decoderSpecificInfo;
import->esd->decoderConfig->decoderSpecificInfo = NULL;
}
ID = import->esd->ESID;
OCR_ES_ID = import->esd->OCRESID;
} else {
timescale = 1000;
OCR_ES_ID = ID = 0;
}
if (cfg && cfg->timescale) timescale = cfg->timescale;
track = gf_isom_new_track(import->dest, ID, GF_ISOM_MEDIA_TEXT, timescale);
if (!track) {
return gf_import_message(import, gf_isom_last_error(import->dest), "Error creating WebVTT track");
}
gf_isom_set_track_enabled(import->dest, track, 1);
import->final_trackID = gf_isom_get_track_id(import->dest, track);
if (import->esd && !import->esd->ESID) import->esd->ESID = import->final_trackID;
if (OCR_ES_ID) gf_isom_set_track_reference(import->dest, track, GF_ISOM_REF_OCR, OCR_ES_ID);
/*setup track*/
if (cfg) {
u32 i;
u32 count;
/*set track info*/
gf_isom_set_track_layout_info(import->dest, track, cfg->text_width<<16, cfg->text_height<<16, 0, 0, cfg->layer);
/*and set sample descriptions*/
count = gf_list_count(cfg->sample_descriptions);
for (i=0; i<count; i++) {
gf_isom_new_webvtt_description(import->dest, track, NULL, NULL, NULL, &descIndex);
}
gf_import_message(import, GF_OK, "WebVTT import - text track %d x %d", cfg->text_width, cfg->text_height);
gf_odf_desc_del((GF_Descriptor *)cfg);
} else {
u32 w;
u32 h;
gf_text_get_video_size(import, &w, &h);
gf_isom_set_track_layout_info(import->dest, track, w<<16, h<<16, 0, 0, 0);
gf_isom_new_webvtt_description(import->dest, track, NULL, NULL, NULL, &descIndex);
gf_import_message(import, GF_OK, "WebVTT import");
}
gf_text_import_set_language(import, track);
duration = (u32) (((Double) import->duration)*timescale/1000.0);
vttparser = gf_webvtt_parser_new();
flusher.import = import;
flusher.timescale = timescale;
flusher.track = track;
flusher.descriptionIndex = descIndex;
e = gf_webvtt_parser_init(vttparser, import->in_name, &flusher, gf_webvtt_import_report, gf_webvtt_flush_sample_to_iso, gf_webvtt_import_header);
if (e != GF_OK) {
gf_webvtt_parser_del(vttparser);
return gf_import_message(import, GF_NOT_SUPPORTED, "Unsupported WebVTT UTF encoding");
}
e = gf_webvtt_parser_parse(vttparser, duration);
if (e != GF_OK) {
gf_isom_remove_track(import->dest, track);
}
/*do not add any empty sample at the end since it modifies track duration and is not needed - it is the player job
to figure out when to stop displaying the last text sample
However update the last sample duration*/
gf_isom_set_last_sample_duration(import->dest, track, (u32) gf_webvtt_parser_last_duration(vttparser));
gf_webvtt_parser_del(vttparser);
return e;
}
#endif /*GPAC_DISABLE_VTT*/
static char *ttxt_parse_string(GF_MediaImporter *import, char *str, Bool strip_lines)
{
u32 i=0;
u32 k=0;
u32 len = (u32) strlen(str);
u32 state = 0;
if (!strip_lines) {
for (i=0; i<len; i++) {
if ((str[i] == '\r') && (str[i+1] == '\n')) {
i++;
}
str[k] = str[i];
k++;
}
str[k]=0;
return str;
}
if (str[0]!='\'') return str;
for (i=0; i<len; i++) {
if (str[i] == '\'') {
if (!state) {
if (k) {
str[k]='\n';
k++;
}
state = !state;
} else if (state) {
if ( (i+1==len) ||
((str[i+1]==' ') || (str[i+1]=='\n') || (str[i+1]=='\r') || (str[i+1]=='\t') || (str[i+1]=='\''))
) {
state = !state;
} else {
str[k] = str[i];
k++;
}
}
} else if (state) {
str[k] = str[i];
k++;
}
}
str[k]=0;
return str;
}
static void ttml_import_progress(void *cbk, u64 cur_samp, u64 count)
{
gf_set_progress("TTML Loading", cur_samp, count);
}
static void gf_text_import_ebu_ttd_remove_samples(GF_XMLNode *root, GF_XMLNode **sample_list_node)
{
u32 idx = 0, body_num = 0;
GF_XMLNode *node = NULL;
*sample_list_node = NULL;
while ( (node = (GF_XMLNode*)gf_list_enum(root->content, &idx))) {
if (!strcmp(node->name, "body")) {
GF_XMLNode *body_node;
u32 body_idx = 0;
while ( (body_node = (GF_XMLNode*)gf_list_enum(node->content, &body_idx))) {
if (!strcmp(body_node->name, "div")) {
*sample_list_node = body_node;
body_num = gf_list_count(body_node->content);
while (body_num--) {
GF_XMLNode *content_node = (GF_XMLNode*)gf_list_get(body_node->content, 0);
assert(gf_list_find(body_node->content, content_node) == 0);
gf_list_rem(body_node->content, 0);
gf_xml_dom_node_del(content_node);
}
return;
}
}
}
}
}
#define TTML_NAMESPACE "http://www.w3.org/ns/ttml"
static GF_Err gf_text_import_ebu_ttd(GF_MediaImporter *import, GF_DOMParser *parser, GF_XMLNode *root)
{
GF_Err e, e_opt;
u32 i, track, ID, desc_idx, nb_samples, nb_children;
u64 last_sample_duration, last_sample_end;
GF_XMLAttribute *att;
GF_XMLNode *node, *root_working_copy, *sample_list_node;
GF_DOMParser *parser_working_copy;
char *samp_text;
Bool has_body;
samp_text = NULL;
root_working_copy = NULL;
parser_working_copy = NULL;
/*setup track in 3GP format directly (no ES desc)*/
ID = (import->esd) ? import->esd->ESID : 0;
track = gf_isom_new_track(import->dest, ID, GF_ISOM_MEDIA_MPEG_SUBT, 1000);
if (!track) {
e = gf_isom_last_error(import->dest);
goto exit;
}
gf_isom_set_track_enabled(import->dest, track, 1);
/*some MPEG-4 setup*/
if (import->esd) {
if (!import->esd->ESID) import->esd->ESID = gf_isom_get_track_id(import->dest, track);
if (!import->esd->decoderConfig) import->esd->decoderConfig = (GF_DecoderConfig *) gf_odf_desc_new(GF_ODF_DCD_TAG);
if (!import->esd->slConfig) import->esd->slConfig = (GF_SLConfig *) gf_odf_desc_new(GF_ODF_SLC_TAG);
import->esd->slConfig->timestampResolution = 1000;
import->esd->decoderConfig->streamType = GF_STREAM_TEXT;
import->esd->decoderConfig->objectTypeIndication = GPAC_OTI_TEXT_MPEG4;
if (import->esd->OCRESID) gf_isom_set_track_reference(import->dest, track, GF_ISOM_REF_OCR, import->esd->OCRESID);
}
gf_import_message(import, GF_OK, "TTML EBU-TTD Import");
/*** root (including language) ***/
i=0;
while ( (att = (GF_XMLAttribute *)gf_list_enum(root->attributes, &i))) {
GF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, ("Found root attribute name %s, value %s\n", att->name, att->value));
if (!strcmp(att->name, "xmlns")) {
if (strcmp(att->value, TTML_NAMESPACE)) {
e = gf_import_message(import, GF_BAD_PARAM, "Found invalid EBU-TTD root attribute name %s, value %s (shall be \"%s\")\n", att->name, att->value, TTML_NAMESPACE);
goto exit;
}
} else if (!strcmp(att->name, "xml:lang")) {
if (import->esd && !import->esd->langDesc) {
char *lang;
lang = gf_strdup(att->value);
import->esd->langDesc = (GF_Language *) gf_odf_desc_new(GF_ODF_LANG_TAG);
gf_isom_set_media_language(import->dest, track, lang);
} else {
gf_isom_set_media_language(import->dest, track, att->value);
}
}
}
/*** style ***/
#if 0
{
Bool has_styling, has_style;
GF_TextSampleDescriptor *sd;
has_styling = GF_FALSE;
has_style = GF_FALSE;
sd = (GF_TextSampleDescriptor*)gf_odf_desc_new(GF_ODF_TX3G_TAG);
i=0;
while ( (node = (GF_XMLNode*)gf_list_enum(root->content, &i))) {
if (node->type) {
continue;
} else if (gf_xml_get_element_check_namespace(node, "head", root->ns) == GF_OK) {
GF_XMLNode *head_node;
u32 head_idx = 0;
while ( (head_node = (GF_XMLNode*)gf_list_enum(node->content, &head_idx))) {
if (gf_xml_get_element_check_namespace(head_node, "styling", root->ns) == GF_OK) {
GF_XMLNode *styling_node;
u32 styling_idx;
if (has_styling) {
e = gf_import_message(import, GF_BAD_PARAM, "[TTML EBU-TTD] duplicated \"styling\" element. Abort.\n");
goto exit;
}
has_styling = GF_TRUE;
styling_idx = 0;
while ( (styling_node = (GF_XMLNode*)gf_list_enum(head_node->content, &styling_idx))) {
if (gf_xml_get_element_check_namespace(styling_node, "style", root->ns) == GF_OK) {
GF_XMLAttribute *p_att;
u32 style_idx = 0;
while ( (p_att = (GF_XMLAttribute*)gf_list_enum(styling_node->attributes, &style_idx))) {
if (!strcmp(p_att->name, "tts:direction")) {
} else if (!strcmp(p_att->name, "tts:fontFamily")) {
sd->fonts = (GF_FontRecord*)gf_malloc(sizeof(GF_FontRecord));
sd->font_count = 1;
sd->fonts[0].fontID = 1;
sd->fonts[0].fontName = gf_strdup(p_att->value);
} else if (!strcmp(p_att->name, "tts:backgroundColor")) {
GF_LOG(GF_LOG_INFO, GF_LOG_PARSER, ("EBU-TTD style attribute \"%s\" ignored.\n", p_att->name));
//sd->back_color = ;
} else {
if ( !strcmp(p_att->name, "tts:fontSize")
|| !strcmp(p_att->name, "tts:lineHeight")
|| !strcmp(p_att->name, "tts:textAlign")
|| !strcmp(p_att->name, "tts:color")
|| !strcmp(p_att->name, "tts:fontStyle")
|| !strcmp(p_att->name, "tts:fontWeight")
|| !strcmp(p_att->name, "tts:textDecoration")
|| !strcmp(p_att->name, "tts:unicodeBidi")
|| !strcmp(p_att->name, "tts:wrapOption")
|| !strcmp(p_att->name, "tts:multiRowAlign")
|| !strcmp(p_att->name, "tts:linePadding")) {
GF_LOG(GF_LOG_INFO, GF_LOG_PARSER, ("EBU-TTD style attribute \"%s\" ignored.\n", p_att->name));
} else {
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("EBU-TTD unknown style attribute: \"%s\". Ignoring.\n", p_att->name));
}
}
}
break; //TODO: we only take care of the first style
}
}
}
}
}
}
if (!has_styling) {
e = gf_import_message(import, GF_BAD_PARAM, "[TTML EBU-TTD] missing \"styling\" element. Abort.\n");
goto exit;
}
if (!has_style) {
e = gf_import_message(import, GF_BAD_PARAM, "[TTML EBU-TTD] missing \"style\" element. Abort.\n");
goto exit;
}
e = gf_isom_new_text_description(import->dest, track, sd, NULL, NULL, &desc_idx);
gf_odf_desc_del((GF_Descriptor*)sd);
}
#else
e = gf_isom_new_xml_subtitle_description(import->dest, track, TTML_NAMESPACE, NULL, NULL, &desc_idx);
#endif
if (e != GF_OK) {
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTML EBU-TTD] incorrect sample description. Abort.\n"));
e = gf_isom_last_error(import->dest);
goto exit;
}
/*** body ***/
parser_working_copy = gf_xml_dom_new();
e = gf_xml_dom_parse(parser_working_copy, import->in_name, NULL, NULL);
assert (e == GF_OK);
root_working_copy = gf_xml_dom_get_root(parser_working_copy);
assert(root_working_copy);
last_sample_duration = 0;
last_sample_end = 0;
nb_samples = 0;
nb_children = gf_list_count(root->content);
has_body = GF_FALSE;
i=0;
while ( (node = (GF_XMLNode*)gf_list_enum(root->content, &i))) {
if (node->type) {
nb_children--;
continue;
}
e_opt = gf_xml_get_element_check_namespace(node, "body", root->ns);
if (e_opt == GF_BAD_PARAM) {
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTML EBU-TTD] ignored \"%s\" node, check your namespaces\n", node->name));
} else if (e_opt == GF_OK) {
GF_XMLNode *body_node;
u32 body_idx = 0;
if (has_body) {
e = gf_import_message(import, GF_BAD_PARAM, "[TTML EBU-TTD] duplicated \"body\" element. Abort.\n");
goto exit;
}
has_body = GF_TRUE;
/*remove all the entries from the working copy, we'll add samples one to one to create full XML samples*/
gf_text_import_ebu_ttd_remove_samples(root_working_copy, &sample_list_node);
while ( (body_node = (GF_XMLNode*)gf_list_enum(node->content, &body_idx))) {
e_opt = gf_xml_get_element_check_namespace(body_node, "div", root->ns);
if (e_opt == GF_BAD_PARAM) {
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTML EBU-TTD] ignored \"%s\" node, check your namespaces\n", node->name));
} else if (e_opt == GF_OK) {
GF_XMLNode *div_node;
u32 div_idx = 0, nb_p_found = 0;
while ( (div_node = (GF_XMLNode*)gf_list_enum(body_node->content, &div_idx))) {
e_opt = gf_xml_get_element_check_namespace(div_node, "p", root->ns);
if (e_opt != GF_OK) {
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTML] ignored \"%s\" node, check your namespaces\n", node->name));
} else if (e_opt == GF_OK) {
GF_XMLNode *p_node;
GF_XMLAttribute *p_att;
u32 p_idx = 0, h, m, s, f, ms;
s64 ts_begin = -1, ts_end = -1;
//sample is either in the <p> ...
while ( (p_att = (GF_XMLAttribute*)gf_list_enum(div_node->attributes, &p_idx))) {
if (!p_att) continue;
if (!strcmp(p_att->name, "begin")) {
if (ts_begin != -1) {
e = gf_import_message(import, GF_BAD_PARAM, "[TTML] duplicated \"begin\" attribute. Abort.\n");
goto exit;
}
if (sscanf(p_att->value, "%u:%u:%u.%u", &h, &m, &s, &ms) == 4) {
ts_begin = (h*3600 + m*60+s)*1000+ms;
} else if (sscanf(p_att->value, "%u:%u:%u:%u", &h, &m, &s, &f) == 4) {
ts_begin = (h*3600 + m*60+s)*1000+f*40;
} else if (sscanf(p_att->value, "%u:%u:%u", &h, &m, &s) == 3) {
ts_begin = (h*3600 + m*60+s)*1000;
}
} else if (!strcmp(p_att->name, "end")) {
if (ts_end != -1) {
e = gf_import_message(import, GF_BAD_PARAM, "[TTML] duplicated \"end\" attribute. Abort.\n");
goto exit;
}
if (sscanf(p_att->value, "%u:%u:%u.%u", &h, &m, &s, &ms) == 4) {
ts_end = (h*3600 + m*60+s)*1000+ms;
} else if (sscanf(p_att->value, "%u:%u:%u:%u", &h, &m, &s, &f) == 4) {
ts_end = (h*3600 + m*60+s)*1000+f*40;
} else if (sscanf(p_att->value, "%u:%u:%u", &h, &m, &s) == 3) {
ts_end = (h*3600 + m*60+s)*1000;
}
}
if ((ts_begin != -1) && (ts_end != -1) && !samp_text && sample_list_node) {
e = gf_xml_dom_append_child(sample_list_node, div_node);
assert(e == GF_OK);
assert(!samp_text);
samp_text = gf_xml_dom_serialize((GF_XMLNode*)root_working_copy, GF_FALSE);
e = gf_xml_dom_rem_child(sample_list_node, div_node);
assert(e == GF_OK);
}
}
//or under a <span>
p_idx = 0;
while ( (p_node = (GF_XMLNode*)gf_list_enum(div_node->content, &p_idx))) {
e_opt = gf_xml_get_element_check_namespace(p_node, "span", root->ns);
if (e_opt == GF_BAD_PARAM) {
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTML] ignored \"%s\" node, check your namespaces\n", node->name));
} else if (e_opt == GF_OK) {
u32 span_idx = 0;
GF_XMLAttribute *span_att;
while ( (span_att = (GF_XMLAttribute*)gf_list_enum(p_node->attributes, &span_idx))) {
if (!span_att) continue;
if (!strcmp(span_att->name, "begin")) {
if (ts_begin != -1) {
e = gf_import_message(import, GF_BAD_PARAM, "[TTML] duplicated \"begin\" attribute under <span>. Abort.\n");
goto exit;
}
if (sscanf(span_att->value, "%u:%u:%u.%u", &h, &m, &s, &ms) == 4) {
ts_begin = (h*3600 + m*60+s)*1000+ms;
} else if (sscanf(p_att->value, "%u:%u:%u:%u", &h, &m, &s, &f) == 4) {
ts_begin = (h*3600 + m*60+s)*1000+f*40;
} else if (sscanf(span_att->value, "%u:%u:%u", &h, &m, &s) == 3) {
ts_begin = (h*3600 + m*60+s)*1000;
}
} else if (!strcmp(span_att->name, "end")) {
if (ts_end != -1) {
e = gf_import_message(import, GF_BAD_PARAM, "[TTML] duplicated \"end\" attribute under <span>. Abort.\n");
goto exit;
}
if (sscanf(span_att->value, "%u:%u:%u.%u", &h, &m, &s, &ms) == 4) {
ts_end = (h*3600 + m*60+s)*1000+ms;
} else if (sscanf(p_att->value, "%u:%u:%u:%u", &h, &m, &s, &f) == 4) {
ts_end = (h*3600 + m*60+s)*1000+f*40;
} else if (sscanf(span_att->value, "%u:%u:%u", &h, &m, &s) == 3) {
ts_end = (h*3600 + m*60+s)*1000;
}
}
if ((ts_begin != -1) && (ts_end != -1) && !samp_text && sample_list_node) {
if (samp_text) {
e = gf_import_message(import, GF_BAD_PARAM, "[TTML] duplicated sample text under <span>. Abort.\n");
goto exit;
}
/*append the sample*/
e = gf_xml_dom_append_child(sample_list_node, div_node);
assert(e == GF_OK);
assert(!samp_text);
samp_text = gf_xml_dom_serialize((GF_XMLNode*)root_working_copy, GF_FALSE);
e = gf_xml_dom_rem_child(sample_list_node, div_node);
assert(e == GF_OK);
}
}
}
}
if ((ts_begin != -1) && (ts_end != -1) && samp_text) {
GF_ISOSample *s;
GF_GenericSubtitleSample *samp;
u32 len;
char *str;
if (ts_end < ts_begin) {
e = gf_import_message(import, GF_BAD_PARAM, "[TTML] invalid timings: \"begin\"="LLD" , \"end\"="LLD". Abort.\n", ts_begin, ts_end);
goto exit;
}
if (ts_begin < (s64)last_sample_end) {
e = gf_import_message(import, GF_BAD_PARAM, "[TTML] timing overlapping not supported: \"begin\" is "LLD" , last \"end\" was "LLD". Abort.\n", ts_begin, last_sample_end);
goto exit;
}
str = ttxt_parse_string(import, samp_text, GF_TRUE);
len = (u32) strlen(str);
samp = gf_isom_new_xml_subtitle_sample();
/*each sample consists of a full valid XML file*/
e = gf_isom_xml_subtitle_sample_add_text(samp, str, len);
if (e) {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[TTML] ISOM - sample add text: %s", gf_error_to_string(e)));
goto exit;
}
gf_free(samp_text);
samp_text = NULL;
s = gf_isom_xml_subtitle_to_sample(samp);
gf_isom_delete_xml_subtitle_sample(samp);
if (!nb_samples) {
s->DTS = 0; /*in MP4 we must start at T=0*/
last_sample_duration = ts_end;
} else {
s->DTS = ts_begin;
last_sample_duration = ts_end - ts_begin;
}
last_sample_end = ts_end;
GF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, ("ts_begin="LLD", ts_end="LLD", last_sample_duration="LLU" (real duration: "LLU"), last_sample_end="LLU"\n", ts_begin, ts_end, ts_end - last_sample_end, last_sample_duration, last_sample_end));
e = gf_isom_add_sample(import->dest, track, desc_idx, s);
if (e) {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[TTML] ISOM - Add Sample: %s", gf_error_to_string(e)));
goto exit;
}
gf_isom_sample_del(&s);
nb_samples++;
nb_p_found++;
gf_set_progress("Importing TTML", nb_samples, nb_children);
if (import->duration && (ts_end > import->duration))
break;
} else {
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTML] incomplete sample (begin="LLD", end="LLD", text=\"%s\"). Skip.\n", ts_begin, ts_end, samp_text ? samp_text : "NULL"));
}
}
}
if (!nb_p_found) {
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTML EBU-TTD] \"%s\" div node has no <p> elements. Aborting.\n", node->name));
goto exit;
}
}
}
}
}
if (!has_body) {
e = gf_import_message(import, GF_BAD_PARAM, "[TTML EBU-TTD] missing \"body\" element. Abort.\n");
goto exit;
}
GF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, ("last_sample_duration="LLU", last_sample_end="LLU"\n", last_sample_duration, last_sample_end));
gf_isom_set_last_sample_duration(import->dest, track, (u32) last_sample_duration);
gf_media_update_bitrate(import->dest, track);
gf_set_progress("Importing TTML EBU-TTD", nb_samples, nb_samples);
exit:
gf_free(samp_text);
gf_xml_dom_del(parser_working_copy);
if (!gf_isom_get_sample_count(import->dest, track)) {
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTML EBU-TTD] No sample imported. Might be an error. Check your content.\n"));
}
return e;
}
static GF_Err gf_text_import_ttml(GF_MediaImporter *import)
{
GF_Err e;
GF_DOMParser *parser;
GF_XMLNode *root;
if (import->flags == GF_IMPORT_PROBE_ONLY)
return GF_OK;
parser = gf_xml_dom_new();
e = gf_xml_dom_parse(parser, import->in_name, ttml_import_progress, import);
if (e) {
gf_import_message(import, e, "Error parsing TTML file: Line %d - %s. Abort.", gf_xml_dom_get_line(parser), gf_xml_dom_get_error(parser));
gf_xml_dom_del(parser);
return e;
}
root = gf_xml_dom_get_root(parser);
if (!root) {
gf_import_message(import, e, "Error parsing TTML file: no \"root\" found. Abort.");
gf_xml_dom_del(parser);
return e;
}
/*look for TTML*/
if (gf_xml_get_element_check_namespace(root, "tt", NULL) == GF_OK) {
e = gf_text_import_ebu_ttd(import, parser, root);
if (e == GF_OK) {
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("Note: TTML import - EBU-TTD detected\n"));
} else {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("Parsing TTML file with error: %s\n", gf_error_to_string(e)));
GF_LOG(GF_LOG_INFO, GF_LOG_PARSER, ("Unsupported TTML file - only EBU-TTD is supported (root shall be \"tt\", got \"%s\")\n", root->name));
GF_LOG(GF_LOG_INFO, GF_LOG_PARSER, ("Importing as generic TTML\n"));
e = GF_OK;
}
} else {
if (root->ns) {
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("TTML file not recognized: root element is \"%s:%s\" (check your namespaces)\n", root->ns, root->name));
} else {
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("TTML file not recognized: root element is \"%s\"\n", root->name));
}
e = GF_BAD_PARAM;
}
gf_xml_dom_del(parser);
return e;
}
/* SimpleText Text tracks -related functions */
GF_Box *boxstring_new_with_data(u32 type, const char *string);
#ifndef GPAC_DISABLE_SWF_IMPORT
/* SWF Importer */
#include <gpac/internal/swf_dev.h>
static GF_Err swf_svg_add_iso_sample(void *user, const char *data, u32 length, u64 timestamp, Bool isRap)
{
GF_Err e = GF_OK;
GF_ISOFlusher *flusher = (GF_ISOFlusher *)user;
GF_ISOSample *s;
GF_BitStream *bs;
bs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);
if (!bs) return GF_BAD_PARAM;
gf_bs_write_data(bs, data, length);
s = gf_isom_sample_new();
if (s) {
gf_bs_get_content(bs, &s->data, &s->dataLength);
s->DTS = (u64) (flusher->timescale*timestamp/1000);
s->IsRAP = isRap ? RAP : RAP_NO;
gf_isom_add_sample(flusher->import->dest, flusher->track, flusher->descriptionIndex, s);
gf_isom_sample_del(&s);
} else {
e = GF_BAD_PARAM;
}
gf_bs_del(bs);
return e;
}
static GF_Err swf_svg_add_iso_header(void *user, const char *data, u32 length, Bool isHeader)
{
GF_ISOFlusher *flusher = (GF_ISOFlusher *)user;
if (!flusher) return GF_BAD_PARAM;
if (isHeader) {
return gf_isom_update_stxt_description(flusher->import->dest, flusher->track, NULL, data, flusher->descriptionIndex);
} else {
return gf_isom_append_sample_data(flusher->import->dest, flusher->track, (char *)data, length);
}
}
GF_EXPORT
GF_Err gf_text_import_swf(GF_MediaImporter *import)
{
GF_Err e = GF_OK;
u32 track;
u32 timescale;
//u32 duration;
u32 descIndex;
u32 ID;
u32 OCR_ES_ID;
GF_GenericSubtitleConfig *cfg;
SWFReader *read;
GF_ISOFlusher flusher;
char *mime;
if (import->flags & GF_IMPORT_PROBE_ONLY) {
import->nb_tracks = 1;
return GF_OK;
}
cfg = NULL;
if (import->esd) {
if (!import->esd->slConfig) {
import->esd->slConfig = (GF_SLConfig *) gf_odf_desc_new(GF_ODF_SLC_TAG);
import->esd->slConfig->predefined = 2;
import->esd->slConfig->timestampResolution = 1000;
}
timescale = import->esd->slConfig->timestampResolution;
if (!timescale) timescale = 1000;
/*explicit text config*/
if (import->esd->decoderConfig && import->esd->decoderConfig->decoderSpecificInfo->tag == GF_ODF_GEN_SUB_CFG_TAG) {
cfg = (GF_GenericSubtitleConfig *) import->esd->decoderConfig->decoderSpecificInfo;
import->esd->decoderConfig->decoderSpecificInfo = NULL;
}
ID = import->esd->ESID;
OCR_ES_ID = import->esd->OCRESID;
} else {
timescale = 1000;
OCR_ES_ID = ID = 0;
}
if (cfg && cfg->timescale) timescale = cfg->timescale;
track = gf_isom_new_track(import->dest, ID, GF_ISOM_MEDIA_TEXT, timescale);
if (!track) {
return gf_import_message(import, gf_isom_last_error(import->dest), "Error creating text track");
}
gf_isom_set_track_enabled(import->dest, track, 1);
if (import->esd && !import->esd->ESID) import->esd->ESID = gf_isom_get_track_id(import->dest, track);
if (OCR_ES_ID) gf_isom_set_track_reference(import->dest, track, GF_ISOM_REF_OCR, OCR_ES_ID);
if (!stricmp(import->streamFormat, "SVG")) {
mime = "image/svg+xml";
} else {
mime = "application/octet-stream";
}
read = gf_swf_reader_new(NULL, import->in_name);
gf_swf_read_header(read);
/*setup track*/
if (cfg) {
u32 i;
u32 count;
/*set track info*/
gf_isom_set_track_layout_info(import->dest, track, cfg->text_width<<16, cfg->text_height<<16, 0, 0, cfg->layer);
/*and set sample descriptions*/
count = gf_list_count(cfg->sample_descriptions);
for (i=0; i<count; i++) {
gf_isom_new_stxt_description(import->dest, track, GF_ISOM_SUBTYPE_STXT, mime, NULL, NULL, &descIndex);
}
gf_import_message(import, GF_OK, "SWF import - text track %d x %d", cfg->text_width, cfg->text_height);
gf_odf_desc_del((GF_Descriptor *)cfg);
} else {
u32 w = (u32)read->width;
u32 h = (u32)read->height;
if (!w || !h)
gf_text_get_video_size(import, &w, &h);
gf_isom_set_track_layout_info(import->dest, track, w<<16, h<<16, 0, 0, 0);
gf_isom_new_stxt_description(import->dest, track, GF_ISOM_SUBTYPE_STXT, mime, NULL, NULL, &descIndex);
gf_import_message(import, GF_OK, "SWF import (as text - type: %s)", import->streamFormat);
}
gf_text_import_set_language(import, track);
//duration = (u32) (((Double) import->duration)*timescale/1000.0);
flusher.import = import;
flusher.track = track;
flusher.timescale = timescale;
flusher.descriptionIndex = descIndex;
gf_swf_reader_set_user_mode(read, &flusher, swf_svg_add_iso_sample, swf_svg_add_iso_header);
if (!import->streamFormat || (import->streamFormat && !stricmp(import->streamFormat, "SVG"))) {
#ifndef GPAC_DISABLE_SVG
e = swf_to_svg_init(read, import->swf_flags, import->swf_flatten_angle);
#endif
} else { /*if (import->streamFormat && !strcmp(import->streamFormat, "BIFS"))*/
#ifndef GPAC_DISABLE_VRML
e = swf_to_bifs_init(read);
#endif
}
if (e) {
goto exit;
}
/*parse all tags*/
while (e == GF_OK) {
e = swf_parse_tag(read);
}
if (e==GF_EOS) e = GF_OK;
exit:
gf_swf_reader_del(read);
gf_media_update_bitrate(import->dest, track);
return e;
}
/* end of SWF Importer */
#else
GF_EXPORT
GF_Err gf_text_import_swf(GF_MediaImporter *import)
{
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("Warning: GPAC was compiled without SWF import support, can't import track.\n"));
return GF_NOT_SUPPORTED;
}
#endif /*GPAC_DISABLE_SWF_IMPORT*/
static GF_Err gf_text_import_sub(GF_MediaImporter *import)
{
FILE *sub_in;
u32 track, ID, timescale, i, j, desc_idx, start, end, prev_end, nb_samp, duration, len, line;
u64 file_size;
GF_TextConfig*cfg;
GF_Err e;
Double FPS;
GF_TextSample * samp;
Bool first_samp;
s32 unicode_type;
char szLine[2048], szTime[20], szText[2048];
GF_ISOSample *s;
sub_in = gf_fopen(import->in_name, "rt");
unicode_type = gf_text_get_utf_type(sub_in);
if (unicode_type<0) {
gf_fclose(sub_in);
return gf_import_message(import, GF_NOT_SUPPORTED, "Unsupported SUB UTF encoding");
}
FPS = GF_IMPORT_DEFAULT_FPS;
if (import->video_fps) FPS = import->video_fps;
cfg = NULL;
if (import->esd) {
if (!import->esd->slConfig) {
import->esd->slConfig = (GF_SLConfig *) gf_odf_desc_new(GF_ODF_SLC_TAG);
import->esd->slConfig->predefined = 2;
import->esd->slConfig->timestampResolution = 1000;
}
timescale = import->esd->slConfig->timestampResolution;
if (!timescale) timescale = 1000;
/*explicit text config*/
if (import->esd->decoderConfig && import->esd->decoderConfig->decoderSpecificInfo->tag == GF_ODF_TEXT_CFG_TAG) {
cfg = (GF_TextConfig *) import->esd->decoderConfig->decoderSpecificInfo;
import->esd->decoderConfig->decoderSpecificInfo = NULL;
}
ID = import->esd->ESID;
} else {
timescale = 1000;
ID = 0;
}
if (cfg && cfg->timescale) timescale = cfg->timescale;
track = gf_isom_new_track(import->dest, ID, GF_ISOM_MEDIA_TEXT, timescale);
if (!track) {
gf_fclose(sub_in);
return gf_import_message(import, gf_isom_last_error(import->dest), "Error creating text track");
}
gf_isom_set_track_enabled(import->dest, track, 1);
if (import->esd && !import->esd->ESID) import->esd->ESID = gf_isom_get_track_id(import->dest, track);
gf_text_import_set_language(import, track);
file_size = 0;
/*setup track*/
if (cfg) {
u32 count;
char *firstFont = NULL;
/*set track info*/
gf_isom_set_track_layout_info(import->dest, track, cfg->text_width<<16, cfg->text_height<<16, 0, 0, cfg->layer);
/*and set sample descriptions*/
count = gf_list_count(cfg->sample_descriptions);
for (i=0; i<count; i++) {
GF_TextSampleDescriptor *sd= (GF_TextSampleDescriptor *)gf_list_get(cfg->sample_descriptions, i);
if (!sd->font_count) {
sd->fonts = (GF_FontRecord*)gf_malloc(sizeof(GF_FontRecord));
sd->font_count = 1;
sd->fonts[0].fontID = 1;
sd->fonts[0].fontName = gf_strdup("Serif");
}
if (!sd->default_style.fontID) sd->default_style.fontID = sd->fonts[0].fontID;
if (!sd->default_style.font_size) sd->default_style.font_size = 16;
if (!sd->default_style.text_color) sd->default_style.text_color = 0xFF000000;
file_size = sd->default_style.font_size;
gf_isom_new_text_description(import->dest, track, sd, NULL, NULL, &desc_idx);
if (!firstFont) firstFont = sd->fonts[0].fontName;
}
gf_import_message(import, GF_OK, "Timed Text (SUB @ %02.2f) import - text track %d x %d, font %s (size %d)", FPS, cfg->text_width, cfg->text_height, firstFont, file_size);
gf_odf_desc_del((GF_Descriptor *)cfg);
} else {
u32 w, h;
GF_TextSampleDescriptor *sd;
gf_text_get_video_size(import, &w, &h);
/*have to work with default - use max size (if only one video, this means the text region is the
entire display, and with bottom alignment things should be fine...*/
gf_isom_set_track_layout_info(import->dest, track, w<<16, h<<16, 0, 0, 0);
sd = (GF_TextSampleDescriptor*)gf_odf_desc_new(GF_ODF_TX3G_TAG);
sd->fonts = (GF_FontRecord*)gf_malloc(sizeof(GF_FontRecord));
sd->font_count = 1;
sd->fonts[0].fontID = 1;
sd->fonts[0].fontName = gf_strdup("Serif");
sd->back_color = 0x00000000; /*transparent*/
sd->default_style.fontID = 1;
sd->default_style.font_size = TTXT_DEFAULT_FONT_SIZE;
sd->default_style.text_color = 0xFFFFFFFF; /*white*/
sd->default_style.style_flags = 0;
sd->horiz_justif = 1; /*center of scene*/
sd->vert_justif = (s8) -1; /*bottom of scene*/
if (import->flags & GF_IMPORT_SKIP_TXT_BOX) {
sd->default_pos.top = sd->default_pos.left = sd->default_pos.right = sd->default_pos.bottom = 0;
} else {
if ((sd->default_pos.bottom==sd->default_pos.top) || (sd->default_pos.right==sd->default_pos.left)) {
sd->default_pos.left = import->text_x;
sd->default_pos.top = import->text_y;
sd->default_pos.right = (import->text_width ? import->text_width : w) + sd->default_pos.left;
sd->default_pos.bottom = (import->text_height ? import->text_height : h) + sd->default_pos.top;
}
}
gf_isom_new_text_description(import->dest, track, sd, NULL, NULL, &desc_idx);
gf_import_message(import, GF_OK, "Timed Text (SUB @ %02.2f) import - text track %d x %d, font %s (size %d)", FPS, w, h, sd->fonts[0].fontName, TTXT_DEFAULT_FONT_SIZE);
gf_odf_desc_del((GF_Descriptor *)sd);
}
duration = (u32) (((Double) import->duration)*timescale/1000.0);
e = GF_OK;
nb_samp = 0;
samp = gf_isom_new_text_sample();
FPS = ((Double) timescale ) / FPS;
end = prev_end = 0;
line = 0;
first_samp = GF_TRUE;
while (1) {
char *sOK = gf_text_get_utf8_line(szLine, 2048, sub_in, unicode_type);
if (!sOK) break;
REM_TRAIL_MARKS(szLine, "\r\n\t ")
line++;
len = (u32) strlen(szLine);
if (!len) continue;
i=0;
if (szLine[i] != '{') {
e = gf_import_message(import, GF_NON_COMPLIANT_BITSTREAM, "Bad SUB file (line %d): expecting \"{\" got \"%c\"", line, szLine[i]);
goto exit;
}
while (szLine[i+1] && szLine[i+1]!='}') {
szTime[i] = szLine[i+1];
i++;
}
szTime[i] = 0;
start = atoi(szTime);
if (start<end) {
gf_import_message(import, GF_OK, "WARNING: corrupted SUB frame (line %d) - starts (at %d ms) before end of previous one (%d ms) - adjusting time stamps", line, start, end);
start = end;
}
j=i+2;
i=0;
if (szLine[i+j] != '{') {
e = gf_import_message(import, GF_NON_COMPLIANT_BITSTREAM, "Bad SUB file - expecting \"{\" got \"%c\"", szLine[i]);
goto exit;
}
while (szLine[i+1+j] && szLine[i+1+j]!='}') {
szTime[i] = szLine[i+1+j];
i++;
}
szTime[i] = 0;
end = atoi(szTime);
j+=i+2;
if (start>end) {
gf_import_message(import, GF_OK, "WARNING: corrupted SUB frame (line %d) - ends (at %d ms) before start of current frame (%d ms) - skipping", line, end, start);
continue;
}
gf_isom_text_reset(samp);
if (start && first_samp) {
s = gf_isom_text_to_sample(samp);
s->DTS = 0;
s->IsRAP = RAP;
gf_isom_add_sample(import->dest, track, 1, s);
gf_isom_sample_del(&s);
first_samp = GF_FALSE;
nb_samp++;
}
for (i=j; i<len; i++) {
if (szLine[i]=='|') {
szText[i-j] = '\n';
} else {
szText[i-j] = szLine[i];
}
}
szText[i-j] = 0;
gf_isom_text_add_text(samp, szText, (u32) strlen(szText) );
if (prev_end) {
GF_TextSample * empty_samp = gf_isom_new_text_sample();
s = gf_isom_text_to_sample(empty_samp);
s->DTS = (u64) (FPS*(s64)prev_end);
gf_isom_add_sample(import->dest, track, 1, s);
gf_isom_sample_del(&s);
nb_samp++;
gf_isom_delete_text_sample(empty_samp);
}
s = gf_isom_text_to_sample(samp);
s->DTS = (u64) (FPS*(s64)start);
gf_isom_add_sample(import->dest, track, 1, s);
gf_isom_sample_del(&s);
nb_samp++;
gf_isom_text_reset(samp);
prev_end = end;
gf_set_progress("Importing SUB", gf_ftell(sub_in), file_size);
if (duration && (end >= duration)) break;
}
/*final flush*/
if (end && !(import->flags & GF_IMPORT_NO_TEXT_FLUSH ) ) {
gf_isom_text_reset(samp);
s = gf_isom_text_to_sample(samp);
s->DTS = (u64)(FPS*(s64)end);
gf_isom_add_sample(import->dest, track, 1, s);
gf_isom_sample_del(&s);
nb_samp++;
}
gf_isom_delete_text_sample(samp);
gf_isom_set_last_sample_duration(import->dest, track, 0);
gf_set_progress("Importing SUB", nb_samp, nb_samp);
exit:
if (e) gf_isom_remove_track(import->dest, track);
gf_fclose(sub_in);
return e;
}
#define CHECK_STR(__str) \
if (!__str) { \
e = gf_import_message(import, GF_BAD_PARAM, "Invalid XML formatting (line %d)", parser.line); \
goto exit; \
} \
u32 ttxt_get_color(GF_MediaImporter *import, char *val)
{
u32 r, g, b, a, res;
r = g = b = a = 0;
if (sscanf(val, "%x %x %x %x", &r, &g, &b, &a) != 4) {
gf_import_message(import, GF_OK, "Warning: color badly formatted");
}
res = (a&0xFF);
res<<=8;
res |= (r&0xFF);
res<<=8;
res |= (g&0xFF);
res<<=8;
res |= (b&0xFF);
return res;
}
void ttxt_parse_text_box(GF_MediaImporter *import, GF_XMLNode *n, GF_BoxRecord *box)
{
u32 i=0;
GF_XMLAttribute *att;
memset(box, 0, sizeof(GF_BoxRecord));
while ( (att=(GF_XMLAttribute *)gf_list_enum(n->attributes, &i))) {
if (!stricmp(att->name, "top")) box->top = atoi(att->value);
else if (!stricmp(att->name, "bottom")) box->bottom = atoi(att->value);
else if (!stricmp(att->name, "left")) box->left = atoi(att->value);
else if (!stricmp(att->name, "right")) box->right = atoi(att->value);
}
}
void ttxt_parse_text_style(GF_MediaImporter *import, GF_XMLNode *n, GF_StyleRecord *style)
{
u32 i=0;
GF_XMLAttribute *att;
memset(style, 0, sizeof(GF_StyleRecord));
style->fontID = 1;
style->font_size = TTXT_DEFAULT_FONT_SIZE;
style->text_color = 0xFFFFFFFF;
while ( (att=(GF_XMLAttribute *)gf_list_enum(n->attributes, &i))) {
if (!stricmp(att->name, "fromChar")) style->startCharOffset = atoi(att->value);
else if (!stricmp(att->name, "toChar")) style->endCharOffset = atoi(att->value);
else if (!stricmp(att->name, "fontID")) style->fontID = atoi(att->value);
else if (!stricmp(att->name, "fontSize")) style->font_size = atoi(att->value);
else if (!stricmp(att->name, "color")) style->text_color = ttxt_get_color(import, att->value);
else if (!stricmp(att->name, "styles")) {
if (strstr(att->value, "Bold")) style->style_flags |= GF_TXT_STYLE_BOLD;
if (strstr(att->value, "Italic")) style->style_flags |= GF_TXT_STYLE_ITALIC;
if (strstr(att->value, "Underlined")) style->style_flags |= GF_TXT_STYLE_UNDERLINED;
}
}
}
static void ttxt_import_progress(void *cbk, u64 cur_samp, u64 count)
{
gf_set_progress("TTXT Loading", cur_samp, count);
}
static GF_Err gf_text_import_ttxt(GF_MediaImporter *import)
{
GF_Err e;
Bool last_sample_empty;
u32 i, j, k, track, ID, nb_samples, nb_descs, nb_children;
u64 last_sample_duration;
GF_XMLAttribute *att;
GF_DOMParser *parser;
GF_XMLNode *root, *node, *ext;
if (import->flags==GF_IMPORT_PROBE_ONLY) return GF_OK;
parser = gf_xml_dom_new();
e = gf_xml_dom_parse(parser, import->in_name, ttxt_import_progress, import);
if (e) {
gf_import_message(import, e, "Error parsing TTXT file: Line %d - %s", gf_xml_dom_get_line(parser), gf_xml_dom_get_error(parser));
gf_xml_dom_del(parser);
return e;
}
root = gf_xml_dom_get_root(parser);
e = GF_OK;
if (strcmp(root->name, "TextStream")) {
e = gf_import_message(import, GF_BAD_PARAM, "Invalid Timed Text file - expecting \"TextStream\" got %s", "TextStream", root->name);
goto exit;
}
/*setup track in 3GP format directly (no ES desc)*/
ID = (import->esd) ? import->esd->ESID : 0;
track = gf_isom_new_track(import->dest, ID, GF_ISOM_MEDIA_TEXT, 1000);
if (!track) {
e = gf_isom_last_error(import->dest);
goto exit;
}
gf_isom_set_track_enabled(import->dest, track, 1);
/*some MPEG-4 setup*/
if (import->esd) {
if (!import->esd->ESID) import->esd->ESID = gf_isom_get_track_id(import->dest, track);
if (!import->esd->decoderConfig) import->esd->decoderConfig = (GF_DecoderConfig *) gf_odf_desc_new(GF_ODF_DCD_TAG);
if (!import->esd->slConfig) import->esd->slConfig = (GF_SLConfig *) gf_odf_desc_new(GF_ODF_SLC_TAG);
import->esd->slConfig->timestampResolution = 1000;
import->esd->decoderConfig->streamType = GF_STREAM_TEXT;
import->esd->decoderConfig->objectTypeIndication = GPAC_OTI_TEXT_MPEG4;
if (import->esd->OCRESID) gf_isom_set_track_reference(import->dest, track, GF_ISOM_REF_OCR, import->esd->OCRESID);
}
gf_text_import_set_language(import, track);
gf_import_message(import, GF_OK, "Timed Text (GPAC TTXT) Import");
last_sample_empty = GF_FALSE;
last_sample_duration = 0;
nb_descs = 0;
nb_samples = 0;
nb_children = gf_list_count(root->content);
i=0;
while ( (node = (GF_XMLNode*)gf_list_enum(root->content, &i))) {
if (node->type) {
nb_children--;
continue;
}
if (!strcmp(node->name, "TextStreamHeader")) {
GF_XMLNode *sdesc;
s32 w, h, tx, ty, layer;
u32 tref_id;
w = TTXT_DEFAULT_WIDTH;
h = TTXT_DEFAULT_HEIGHT;
tx = ty = layer = 0;
nb_children--;
tref_id = 0;
j=0;
while ( (att=(GF_XMLAttribute *)gf_list_enum(node->attributes, &j))) {
if (!strcmp(att->name, "width")) w = atoi(att->value);
else if (!strcmp(att->name, "height")) h = atoi(att->value);
else if (!strcmp(att->name, "layer")) layer = atoi(att->value);
else if (!strcmp(att->name, "translation_x")) tx = atoi(att->value);
else if (!strcmp(att->name, "translation_y")) ty = atoi(att->value);
else if (!strcmp(att->name, "trefID")) tref_id = atoi(att->value);
}
if (tref_id)
gf_isom_set_track_reference(import->dest, track, GF_ISOM_BOX_TYPE_CHAP, tref_id);
gf_isom_set_track_layout_info(import->dest, track, w<<16, h<<16, tx<<16, ty<<16, (s16) layer);
j=0;
while ( (sdesc=(GF_XMLNode*)gf_list_enum(node->content, &j))) {
if (sdesc->type) continue;
if (!strcmp(sdesc->name, "TextSampleDescription")) {
GF_TextSampleDescriptor td;
u32 idx;
memset(&td, 0, sizeof(GF_TextSampleDescriptor));
td.tag = GF_ODF_TEXT_CFG_TAG;
td.vert_justif = (s8) -1;
td.default_style.fontID = 1;
td.default_style.font_size = TTXT_DEFAULT_FONT_SIZE;
k=0;
while ( (att=(GF_XMLAttribute *)gf_list_enum(sdesc->attributes, &k))) {
if (!strcmp(att->name, "horizontalJustification")) {
if (!stricmp(att->value, "center")) td.horiz_justif = 1;
else if (!stricmp(att->value, "right")) td.horiz_justif = (s8) -1;
else if (!stricmp(att->value, "left")) td.horiz_justif = 0;
}
else if (!strcmp(att->name, "verticalJustification")) {
if (!stricmp(att->value, "center")) td.vert_justif = 1;
else if (!stricmp(att->value, "bottom")) td.vert_justif = (s8) -1;
else if (!stricmp(att->value, "top")) td.vert_justif = 0;
}
else if (!strcmp(att->name, "backColor")) td.back_color = ttxt_get_color(import, att->value);
else if (!strcmp(att->name, "verticalText") && !stricmp(att->value, "yes") ) td.displayFlags |= GF_TXT_VERTICAL;
else if (!strcmp(att->name, "fillTextRegion") && !stricmp(att->value, "yes") ) td.displayFlags |= GF_TXT_FILL_REGION;
else if (!strcmp(att->name, "continuousKaraoke") && !stricmp(att->value, "yes") ) td.displayFlags |= GF_TXT_KARAOKE;
else if (!strcmp(att->name, "scroll")) {
if (!stricmp(att->value, "inout")) td.displayFlags |= GF_TXT_SCROLL_IN | GF_TXT_SCROLL_OUT;
else if (!stricmp(att->value, "in")) td.displayFlags |= GF_TXT_SCROLL_IN;
else if (!stricmp(att->value, "out")) td.displayFlags |= GF_TXT_SCROLL_OUT;
}
else if (!strcmp(att->name, "scrollMode")) {
u32 scroll_mode = GF_TXT_SCROLL_CREDITS;
if (!stricmp(att->value, "Credits")) scroll_mode = GF_TXT_SCROLL_CREDITS;
else if (!stricmp(att->value, "Marquee")) scroll_mode = GF_TXT_SCROLL_MARQUEE;
else if (!stricmp(att->value, "Right")) scroll_mode = GF_TXT_SCROLL_RIGHT;
else if (!stricmp(att->value, "Down")) scroll_mode = GF_TXT_SCROLL_DOWN;
td.displayFlags |= ((scroll_mode<<7) & GF_TXT_SCROLL_DIRECTION);
}
}
k=0;
while ( (ext=(GF_XMLNode*)gf_list_enum(sdesc->content, &k))) {
if (ext->type) continue;
if (!strcmp(ext->name, "TextBox")) ttxt_parse_text_box(import, ext, &td.default_pos);
else if (!strcmp(ext->name, "Style")) ttxt_parse_text_style(import, ext, &td.default_style);
else if (!strcmp(ext->name, "FontTable")) {
GF_XMLNode *ftable;
u32 z=0;
while ( (ftable=(GF_XMLNode*)gf_list_enum(ext->content, &z))) {
u32 m;
if (ftable->type || strcmp(ftable->name, "FontTableEntry")) continue;
td.font_count += 1;
td.fonts = (GF_FontRecord*)gf_realloc(td.fonts, sizeof(GF_FontRecord)*td.font_count);
m=0;
while ( (att=(GF_XMLAttribute *)gf_list_enum(ftable->attributes, &m))) {
if (!stricmp(att->name, "fontID")) td.fonts[td.font_count-1].fontID = atoi(att->value);
else if (!stricmp(att->name, "fontName")) td.fonts[td.font_count-1].fontName = gf_strdup(att->value);
}
}
}
}
if (import->flags & GF_IMPORT_SKIP_TXT_BOX) {
td.default_pos.top = td.default_pos.left = td.default_pos.right = td.default_pos.bottom = 0;
} else {
if ((td.default_pos.bottom==td.default_pos.top) || (td.default_pos.right==td.default_pos.left)) {
td.default_pos.top = td.default_pos.left = 0;
td.default_pos.right = w;
td.default_pos.bottom = h;
}
}
if (!td.fonts) {
td.font_count = 1;
td.fonts = (GF_FontRecord*)gf_malloc(sizeof(GF_FontRecord));
td.fonts[0].fontID = 1;
td.fonts[0].fontName = gf_strdup("Serif");
}
gf_isom_new_text_description(import->dest, track, &td, NULL, NULL, &idx);
for (k=0; k<td.font_count; k++) gf_free(td.fonts[k].fontName);
gf_free(td.fonts);
nb_descs ++;
}
}
}
/*sample text*/
else if (!strcmp(node->name, "TextSample")) {
GF_ISOSample *s;
GF_TextSample * samp;
u32 ts, descIndex;
Bool has_text = GF_FALSE;
if (!nb_descs) {
e = gf_import_message(import, GF_BAD_PARAM, "Invalid Timed Text file - text stream header not found or empty");
goto exit;
}
samp = gf_isom_new_text_sample();
ts = 0;
descIndex = 1;
last_sample_empty = GF_TRUE;
j=0;
while ( (att=(GF_XMLAttribute*)gf_list_enum(node->attributes, &j))) {
if (!strcmp(att->name, "sampleTime")) {
u32 h, m, s, ms;
if (sscanf(att->value, "%u:%u:%u.%u", &h, &m, &s, &ms) == 4) {
ts = (h*3600 + m*60 + s)*1000 + ms;
} else {
ts = (u32) (atof(att->value) * 1000);
}
}
else if (!strcmp(att->name, "sampleDescriptionIndex")) descIndex = atoi(att->value);
else if (!strcmp(att->name, "text")) {
u32 len;
char *str = ttxt_parse_string(import, att->value, GF_TRUE);
len = (u32) strlen(str);
gf_isom_text_add_text(samp, str, len);
last_sample_empty = len ? GF_FALSE : GF_TRUE;
has_text = GF_TRUE;
}
else if (!strcmp(att->name, "scrollDelay")) gf_isom_text_set_scroll_delay(samp, (u32) (1000*atoi(att->value)));
else if (!strcmp(att->name, "highlightColor")) gf_isom_text_set_highlight_color_argb(samp, ttxt_get_color(import, att->value));
else if (!strcmp(att->name, "wrap") && !strcmp(att->value, "Automatic")) gf_isom_text_set_wrap(samp, 0x01);
}
/*get all modifiers*/
j=0;
while ( (ext=(GF_XMLNode*)gf_list_enum(node->content, &j))) {
if (!has_text && (ext->type==GF_XML_TEXT_TYPE)) {
u32 len;
char *str = ttxt_parse_string(import, ext->name, GF_FALSE);
len = (u32) strlen(str);
gf_isom_text_add_text(samp, str, len);
last_sample_empty = len ? GF_FALSE : GF_TRUE;
has_text = GF_TRUE;
}
if (ext->type) continue;
if (!stricmp(ext->name, "Style")) {
GF_StyleRecord r;
ttxt_parse_text_style(import, ext, &r);
gf_isom_text_add_style(samp, &r);
}
else if (!stricmp(ext->name, "TextBox")) {
GF_BoxRecord r;
ttxt_parse_text_box(import, ext, &r);
gf_isom_text_set_box(samp, r.top, r.left, r.bottom, r.right);
}
else if (!stricmp(ext->name, "Highlight")) {
u16 start, end;
start = end = 0;
k=0;
while ( (att=(GF_XMLAttribute *)gf_list_enum(ext->attributes, &k))) {
if (!strcmp(att->name, "fromChar")) start = atoi(att->value);
else if (!strcmp(att->name, "toChar")) end = atoi(att->value);
}
gf_isom_text_add_highlight(samp, start, end);
}
else if (!stricmp(ext->name, "Blinking")) {
u16 start, end;
start = end = 0;
k=0;
while ( (att=(GF_XMLAttribute *)gf_list_enum(ext->attributes, &k))) {
if (!strcmp(att->name, "fromChar")) start = atoi(att->value);
else if (!strcmp(att->name, "toChar")) end = atoi(att->value);
}
gf_isom_text_add_blink(samp, start, end);
}
else if (!stricmp(ext->name, "HyperLink")) {
u16 start, end;
char *url, *url_tt;
start = end = 0;
url = url_tt = NULL;
k=0;
while ( (att=(GF_XMLAttribute *)gf_list_enum(ext->attributes, &k))) {
if (!strcmp(att->name, "fromChar")) start = atoi(att->value);
else if (!strcmp(att->name, "toChar")) end = atoi(att->value);
else if (!strcmp(att->name, "URL")) url = gf_strdup(att->value);
else if (!strcmp(att->name, "URLToolTip")) url_tt = gf_strdup(att->value);
}
gf_isom_text_add_hyperlink(samp, url, url_tt, start, end);
if (url) gf_free(url);
if (url_tt) gf_free(url_tt);
}
else if (!stricmp(ext->name, "Karaoke")) {
u32 startTime;
GF_XMLNode *krok;
startTime = 0;
k=0;
while ( (att=(GF_XMLAttribute *)gf_list_enum(ext->attributes, &k))) {
if (!strcmp(att->name, "startTime")) startTime = (u32) (1000*atof(att->value));
}
gf_isom_text_add_karaoke(samp, startTime);
k=0;
while ( (krok=(GF_XMLNode*)gf_list_enum(ext->content, &k))) {
u16 start, end;
u32 endTime, m;
if (krok->type) continue;
if (strcmp(krok->name, "KaraokeRange")) continue;
start = end = 0;
endTime = 0;
m=0;
while ( (att=(GF_XMLAttribute *)gf_list_enum(krok->attributes, &m))) {
if (!strcmp(att->name, "fromChar")) start = atoi(att->value);
else if (!strcmp(att->name, "toChar")) end = atoi(att->value);
else if (!strcmp(att->name, "endTime")) endTime = (u32) (1000*atof(att->value));
}
gf_isom_text_set_karaoke_segment(samp, endTime, start, end);
}
}
}
/*in MP4 we must start at T=0, so add an empty sample*/
if (ts && !nb_samples) {
GF_TextSample * firstsamp = gf_isom_new_text_sample();
s = gf_isom_text_to_sample(firstsamp);
s->DTS = 0;
gf_isom_add_sample(import->dest, track, 1, s);
nb_samples++;
gf_isom_delete_text_sample(firstsamp);
gf_isom_sample_del(&s);
}
s = gf_isom_text_to_sample(samp);
gf_isom_delete_text_sample(samp);
s->DTS = ts;
if (last_sample_empty) {
last_sample_duration = s->DTS - last_sample_duration;
} else {
last_sample_duration = s->DTS;
}
e = gf_isom_add_sample(import->dest, track, descIndex, s);
if (e) goto exit;
gf_isom_sample_del(&s);
nb_samples++;
gf_set_progress("Importing TTXT", nb_samples, nb_children);
if (import->duration && (ts>import->duration)) break;
}
}
if (last_sample_empty) {
gf_isom_remove_sample(import->dest, track, nb_samples);
gf_isom_set_last_sample_duration(import->dest, track, (u32) last_sample_duration);
}
gf_set_progress("Importing TTXT", nb_samples, nb_samples);
exit:
gf_xml_dom_del(parser);
return e;
}
u32 tx3g_get_color(GF_MediaImporter *import, char *value)
{
u32 r, g, b, a;
u32 res, v;
r = g = b = a = 0;
if (sscanf(value, "%u%%, %u%%, %u%%, %u%%", &r, &g, &b, &a) != 4) {
gf_import_message(import, GF_OK, "Warning: color badly formatted");
}
v = (u32) (a*255/100);
res = (v&0xFF);
res<<=8;
v = (u32) (r*255/100);
res |= (v&0xFF);
res<<=8;
v = (u32) (g*255/100);
res |= (v&0xFF);
res<<=8;
v = (u32) (b*255/100);
res |= (v&0xFF);
return res;
}
void tx3g_parse_text_box(GF_MediaImporter *import, GF_XMLNode *n, GF_BoxRecord *box)
{
u32 i=0;
GF_XMLAttribute *att;
memset(box, 0, sizeof(GF_BoxRecord));
while ((att=(GF_XMLAttribute *)gf_list_enum(n->attributes, &i))) {
if (!stricmp(att->name, "x")) box->left = atoi(att->value);
else if (!stricmp(att->name, "y")) box->top = atoi(att->value);
else if (!stricmp(att->name, "height")) box->bottom = atoi(att->value);
else if (!stricmp(att->name, "width")) box->right = atoi(att->value);
}
}
typedef struct
{
u32 id;
u32 pos;
} Marker;
#define GET_MARKER_POS(_val, __isend) \
{ \
u32 i, __m = atoi(att->value); \
_val = 0; \
for (i=0; i<nb_marks; i++) { if (__m==marks[i].id) { _val = marks[i].pos; /*if (__isend) _val--; */break; } } \
}
static void texml_import_progress(void *cbk, u64 cur_samp, u64 count)
{
gf_set_progress("TeXML Loading", cur_samp, count);
}
static GF_Err gf_text_import_texml(GF_MediaImporter *import)
{
GF_Err e;
u32 track, ID, nb_samples, nb_children, nb_descs, timescale, w, h, i, j, k;
u64 DTS;
s32 tx, ty, layer;
GF_StyleRecord styles[50];
Marker marks[50];
GF_XMLAttribute *att;
GF_DOMParser *parser;
GF_XMLNode *root, *node;
if (import->flags==GF_IMPORT_PROBE_ONLY) return GF_OK;
parser = gf_xml_dom_new();
e = gf_xml_dom_parse(parser, import->in_name, texml_import_progress, import);
if (e) {
gf_import_message(import, e, "Error parsing TeXML file: Line %d - %s", gf_xml_dom_get_line(parser), gf_xml_dom_get_error(parser));
gf_xml_dom_del(parser);
return e;
}
root = gf_xml_dom_get_root(parser);
if (strcmp(root->name, "text3GTrack")) {
e = gf_import_message(import, GF_BAD_PARAM, "Invalid QT TeXML file - expecting root \"text3GTrack\" got \"%s\"", root->name);
goto exit;
}
w = TTXT_DEFAULT_WIDTH;
h = TTXT_DEFAULT_HEIGHT;
tx = ty = 0;
layer = 0;
timescale = 1000;
i=0;
while ( (att=(GF_XMLAttribute *)gf_list_enum(root->attributes, &i))) {
if (!strcmp(att->name, "trackWidth")) w = atoi(att->value);
else if (!strcmp(att->name, "trackHeight")) h = atoi(att->value);
else if (!strcmp(att->name, "layer")) layer = atoi(att->value);
else if (!strcmp(att->name, "timescale")) timescale = atoi(att->value);
else if (!strcmp(att->name, "transform")) {
Float fx, fy;
sscanf(att->value, "translate(%f,%f)", &fx, &fy);
tx = (u32) fx;
ty = (u32) fy;
}
}
/*setup track in 3GP format directly (no ES desc)*/
ID = (import->esd) ? import->esd->ESID : 0;
track = gf_isom_new_track(import->dest, ID, GF_ISOM_MEDIA_TEXT, timescale);
if (!track) {
e = gf_isom_last_error(import->dest);
goto exit;
}
gf_isom_set_track_enabled(import->dest, track, 1);
/*some MPEG-4 setup*/
if (import->esd) {
if (!import->esd->ESID) import->esd->ESID = gf_isom_get_track_id(import->dest, track);
if (!import->esd->decoderConfig) import->esd->decoderConfig = (GF_DecoderConfig *) gf_odf_desc_new(GF_ODF_DCD_TAG);
if (!import->esd->slConfig) import->esd->slConfig = (GF_SLConfig *) gf_odf_desc_new(GF_ODF_SLC_TAG);
import->esd->slConfig->timestampResolution = timescale;
import->esd->decoderConfig->streamType = GF_STREAM_TEXT;
import->esd->decoderConfig->objectTypeIndication = GPAC_OTI_TEXT_MPEG4;
if (import->esd->OCRESID) gf_isom_set_track_reference(import->dest, track, GF_ISOM_REF_OCR, import->esd->OCRESID);
}
DTS = 0;
gf_isom_set_track_layout_info(import->dest, track, w<<16, h<<16, tx<<16, ty<<16, (s16) layer);
gf_text_import_set_language(import, track);
e = GF_OK;
gf_import_message(import, GF_OK, "Timed Text (QT TeXML) Import - Track Size %d x %d", w, h);
nb_children = gf_list_count(root->content);
nb_descs = 0;
nb_samples = 0;
i=0;
while ( (node=(GF_XMLNode*)gf_list_enum(root->content, &i))) {
GF_XMLNode *desc;
GF_TextSampleDescriptor td;
GF_TextSample * samp = NULL;
GF_ISOSample *s;
u32 duration, descIndex, nb_styles, nb_marks;
Bool isRAP, same_style, same_box;
if (node->type) continue;
if (strcmp(node->name, "sample")) continue;
isRAP = GF_FALSE;
duration = 1000;
j=0;
while ((att=(GF_XMLAttribute *)gf_list_enum(node->attributes, &j))) {
if (!strcmp(att->name, "duration")) duration = atoi(att->value);
else if (!strcmp(att->name, "keyframe")) isRAP = (!stricmp(att->value, "true") ? GF_TRUE : GF_FALSE);
}
nb_styles = 0;
nb_marks = 0;
same_style = same_box = GF_FALSE;
descIndex = 1;
j=0;
while ((desc=(GF_XMLNode*)gf_list_enum(node->content, &j))) {
if (desc->type) continue;
if (!strcmp(desc->name, "description")) {
GF_XMLNode *sub;
memset(&td, 0, sizeof(GF_TextSampleDescriptor));
td.tag = GF_ODF_TEXT_CFG_TAG;
td.vert_justif = (s8) -1;
td.default_style.fontID = 1;
td.default_style.font_size = TTXT_DEFAULT_FONT_SIZE;
k=0;
while ((att=(GF_XMLAttribute *)gf_list_enum(desc->attributes, &k))) {
if (!strcmp(att->name, "horizontalJustification")) {
if (!stricmp(att->value, "center")) td.horiz_justif = 1;
else if (!stricmp(att->value, "right")) td.horiz_justif = (s8) -1;
else if (!stricmp(att->value, "left")) td.horiz_justif = 0;
}
else if (!strcmp(att->name, "verticalJustification")) {
if (!stricmp(att->value, "center")) td.vert_justif = 1;
else if (!stricmp(att->value, "bottom")) td.vert_justif = (s8) -1;
else if (!stricmp(att->value, "top")) td.vert_justif = 0;
}
else if (!strcmp(att->name, "backgroundColor")) td.back_color = tx3g_get_color(import, att->value);
else if (!strcmp(att->name, "displayFlags")) {
Bool rev_scroll = GF_FALSE;
if (strstr(att->value, "scroll")) {
u32 scroll_mode = 0;
if (strstr(att->value, "scrollIn")) td.displayFlags |= GF_TXT_SCROLL_IN;
if (strstr(att->value, "scrollOut")) td.displayFlags |= GF_TXT_SCROLL_OUT;
if (strstr(att->value, "reverse")) rev_scroll = GF_TRUE;
if (strstr(att->value, "horizontal")) scroll_mode = rev_scroll ? GF_TXT_SCROLL_RIGHT : GF_TXT_SCROLL_MARQUEE;
else scroll_mode = (rev_scroll ? GF_TXT_SCROLL_DOWN : GF_TXT_SCROLL_CREDITS);
td.displayFlags |= (scroll_mode<<7) & GF_TXT_SCROLL_DIRECTION;
}
/*TODO FIXME: check in QT doc !!*/
if (strstr(att->value, "writeTextVertically")) td.displayFlags |= GF_TXT_VERTICAL;
if (!strcmp(att->name, "continuousKaraoke")) td.displayFlags |= GF_TXT_KARAOKE;
}
}
k=0;
while ((sub=(GF_XMLNode*)gf_list_enum(desc->content, &k))) {
if (sub->type) continue;
if (!strcmp(sub->name, "defaultTextBox")) tx3g_parse_text_box(import, sub, &td.default_pos);
else if (!strcmp(sub->name, "fontTable")) {
GF_XMLNode *ftable;
u32 m=0;
while ((ftable=(GF_XMLNode*)gf_list_enum(sub->content, &m))) {
if (ftable->type) continue;
if (!strcmp(ftable->name, "font")) {
u32 n=0;
td.font_count += 1;
td.fonts = (GF_FontRecord*)gf_realloc(td.fonts, sizeof(GF_FontRecord)*td.font_count);
while ((att=(GF_XMLAttribute *)gf_list_enum(ftable->attributes, &n))) {
if (!stricmp(att->name, "id")) td.fonts[td.font_count-1].fontID = atoi(att->value);
else if (!stricmp(att->name, "name")) td.fonts[td.font_count-1].fontName = gf_strdup(att->value);
}
}
}
}
else if (!strcmp(sub->name, "sharedStyles")) {
GF_XMLNode *style, *ftable;
u32 m=0;
while ((style=(GF_XMLNode*)gf_list_enum(sub->content, &m))) {
if (style->type) continue;
if (!strcmp(style->name, "style")) break;
}
if (style) {
char *cur;
s32 start=0;
char css_style[1024], css_val[1024];
memset(&styles[nb_styles], 0, sizeof(GF_StyleRecord));
m=0;
while ( (att=(GF_XMLAttribute *)gf_list_enum(style->attributes, &m))) {
if (!strcmp(att->name, "id")) styles[nb_styles].startCharOffset = atoi(att->value);
}
m=0;
while ( (ftable=(GF_XMLNode*)gf_list_enum(style->content, &m))) {
if (ftable->type) break;
}
cur = ftable->name;
while (cur) {
start = gf_token_get_strip(cur, 0, "{:", " ", css_style, 1024);
if (start <0) break;
start = gf_token_get_strip(cur, start, ":}", " ", css_val, 1024);
if (start <0) break;
cur = strchr(cur+start, '{');
if (!strcmp(css_style, "font-table")) {
u32 z;
styles[nb_styles].fontID = atoi(css_val);
for (z=0; z<td.font_count; z++) {
if (td.fonts[z].fontID == styles[nb_styles].fontID)
break;
}
}
else if (!strcmp(css_style, "font-size")) styles[nb_styles].font_size = atoi(css_val);
else if (!strcmp(css_style, "font-style") && !strcmp(css_val, "italic")) styles[nb_styles].style_flags |= GF_TXT_STYLE_ITALIC;
else if (!strcmp(css_style, "font-weight") && !strcmp(css_val, "bold")) styles[nb_styles].style_flags |= GF_TXT_STYLE_BOLD;
else if (!strcmp(css_style, "text-decoration") && !strcmp(css_val, "underline")) styles[nb_styles].style_flags |= GF_TXT_STYLE_UNDERLINED;
else if (!strcmp(css_style, "color")) styles[nb_styles].text_color = tx3g_get_color(import, css_val);
}
if (!nb_styles) td.default_style = styles[0];
nb_styles++;
}
}
}
if ((td.default_pos.bottom==td.default_pos.top) || (td.default_pos.right==td.default_pos.left)) {
td.default_pos.top = td.default_pos.left = 0;
td.default_pos.right = w;
td.default_pos.bottom = h;
}
if (!td.fonts) {
td.font_count = 1;
td.fonts = (GF_FontRecord*)gf_malloc(sizeof(GF_FontRecord));
td.fonts[0].fontID = 1;
td.fonts[0].fontName = gf_strdup("Serif");
}
gf_isom_text_has_similar_description(import->dest, track, &td, &descIndex, &same_box, &same_style);
if (!descIndex) {
gf_isom_new_text_description(import->dest, track, &td, NULL, NULL, &descIndex);
same_style = same_box = GF_TRUE;
}
for (k=0; k<td.font_count; k++) gf_free(td.fonts[k].fontName);
gf_free(td.fonts);
nb_descs ++;
}
else if (!strcmp(desc->name, "sampleData")) {
GF_XMLNode *sub;
u16 start, end;
u32 styleID;
u32 nb_chars, txt_len, m;
nb_chars = 0;
samp = gf_isom_new_text_sample();
k=0;
while ((att=(GF_XMLAttribute *)gf_list_enum(desc->attributes, &k))) {
if (!strcmp(att->name, "targetEncoding") && !strcmp(att->value, "utf16")) ;//is_utf16 = 1;
else if (!strcmp(att->name, "scrollDelay")) gf_isom_text_set_scroll_delay(samp, atoi(att->value) );
else if (!strcmp(att->name, "highlightColor")) gf_isom_text_set_highlight_color_argb(samp, tx3g_get_color(import, att->value));
}
start = end = 0;
k=0;
while ((sub=(GF_XMLNode*)gf_list_enum(desc->content, &k))) {
if (sub->type) continue;
if (!strcmp(sub->name, "text")) {
GF_XMLNode *text;
styleID = 0;
m=0;
while ((att=(GF_XMLAttribute *)gf_list_enum(sub->attributes, &m))) {
if (!strcmp(att->name, "styleID")) styleID = atoi(att->value);
}
txt_len = 0;
m=0;
while ((text=(GF_XMLNode*)gf_list_enum(sub->content, &m))) {
if (!text->type) {
if (!strcmp(text->name, "marker")) {
u32 z;
memset(&marks[nb_marks], 0, sizeof(Marker));
marks[nb_marks].pos = nb_chars+txt_len;
z = 0;
while ( (att=(GF_XMLAttribute *)gf_list_enum(text->attributes, &z))) {
if (!strcmp(att->name, "id")) marks[nb_marks].id = atoi(att->value);
}
nb_marks++;
}
} else if (text->type==GF_XML_TEXT_TYPE) {
txt_len += (u32) strlen(text->name);
gf_isom_text_add_text(samp, text->name, (u32) strlen(text->name));
}
}
if (styleID && (!same_style || (td.default_style.startCharOffset != styleID))) {
GF_StyleRecord st = td.default_style;
for (m=0; m<nb_styles; m++) {
if (styles[m].startCharOffset==styleID) {
st = styles[m];
break;
}
}
st.startCharOffset = nb_chars;
st.endCharOffset = nb_chars + txt_len;
gf_isom_text_add_style(samp, &st);
}
nb_chars += txt_len;
}
else if (!stricmp(sub->name, "highlight")) {
m=0;
while ((att=(GF_XMLAttribute *)gf_list_enum(sub->attributes, &m))) {
if (!strcmp(att->name, "startMarker")) GET_MARKER_POS(start, 0)
else if (!strcmp(att->name, "endMarker")) GET_MARKER_POS(end, 1)
}
gf_isom_text_add_highlight(samp, start, end);
}
else if (!stricmp(sub->name, "blink")) {
m=0;
while ((att=(GF_XMLAttribute *)gf_list_enum(sub->attributes, &m))) {
if (!strcmp(att->name, "startMarker")) GET_MARKER_POS(start, 0)
else if (!strcmp(att->name, "endMarker")) GET_MARKER_POS(end, 1)
}
gf_isom_text_add_blink(samp, start, end);
}
else if (!stricmp(sub->name, "link")) {
char *url, *url_tt;
url = url_tt = NULL;
m=0;
while ((att=(GF_XMLAttribute *)gf_list_enum(sub->attributes, &m))) {
if (!strcmp(att->name, "startMarker")) GET_MARKER_POS(start, 0)
else if (!strcmp(att->name, "endMarker")) GET_MARKER_POS(end, 1)
else if (!strcmp(att->name, "URL") || !strcmp(att->name, "href")) url = gf_strdup(att->value);
else if (!strcmp(att->name, "URLToolTip") || !strcmp(att->name, "altString")) url_tt = gf_strdup(att->value);
}
gf_isom_text_add_hyperlink(samp, url, url_tt, start, end);
if (url) gf_free(url);
if (url_tt) gf_free(url_tt);
}
else if (!stricmp(sub->name, "karaoke")) {
u32 time = 0;
GF_XMLNode *krok;
m=0;
while ((att=(GF_XMLAttribute *)gf_list_enum(sub->attributes, &m))) {
if (!strcmp(att->name, "startTime")) time = atoi(att->value);
}
gf_isom_text_add_karaoke(samp, time);
m=0;
while ((krok=(GF_XMLNode*)gf_list_enum(sub->content, &m))) {
u32 u=0;
if (krok->type) continue;
if (strcmp(krok->name, "run")) continue;
start = end = 0;
while ((att=(GF_XMLAttribute *)gf_list_enum(krok->attributes, &u))) {
if (!strcmp(att->name, "startMarker")) GET_MARKER_POS(start, 0)
else if (!strcmp(att->name, "endMarker")) GET_MARKER_POS(end, 1)
else if (!strcmp(att->name, "duration")) time += atoi(att->value);
}
gf_isom_text_set_karaoke_segment(samp, time, start, end);
}
}
}
}
}
/*OK, let's add the sample*/
if (samp) {
if (!same_box) gf_isom_text_set_box(samp, td.default_pos.top, td.default_pos.left, td.default_pos.bottom, td.default_pos.right);
// if (!same_style) gf_isom_text_add_style(samp, &td.default_style);
s = gf_isom_text_to_sample(samp);
gf_isom_delete_text_sample(samp);
s->IsRAP = isRAP ? RAP : RAP_NO;
s->DTS = DTS;
gf_isom_add_sample(import->dest, track, descIndex, s);
gf_isom_sample_del(&s);
nb_samples++;
DTS += duration;
gf_set_progress("Importing TeXML", nb_samples, nb_children);
if (import->duration && (DTS*1000> timescale*import->duration)) break;
}
}
gf_isom_set_last_sample_duration(import->dest, track, 0);
gf_set_progress("Importing TeXML", nb_samples, nb_samples);
exit:
gf_xml_dom_del(parser);
return e;
}
GF_Err gf_import_timed_text(GF_MediaImporter *import)
{
GF_Err e;
u32 fmt;
e = gf_text_guess_format(import->in_name, &fmt);
if (e) return e;
if (import->streamFormat) {
if (!strcmp(import->streamFormat, "VTT")) fmt = GF_TEXT_IMPORT_WEBVTT;
else if (!strcmp(import->streamFormat, "TTML")) fmt = GF_TEXT_IMPORT_TTML;
if ((strstr(import->in_name, ".swf") || strstr(import->in_name, ".SWF")) && !stricmp(import->streamFormat, "SVG")) fmt = GF_TEXT_IMPORT_SWF_SVG;
}
if (!fmt) {
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTXT Import] Input %s does not look like a supported text format - ignoring\n", import->in_name));
return GF_NOT_SUPPORTED;
}
if (import->flags & GF_IMPORT_PROBE_ONLY) {
if (fmt==GF_TEXT_IMPORT_SUB) import->flags |= GF_IMPORT_OVERRIDE_FPS;
return GF_OK;
}
switch (fmt) {
case GF_TEXT_IMPORT_SRT:
return gf_text_import_srt(import);
case GF_TEXT_IMPORT_SUB:
return gf_text_import_sub(import);
case GF_TEXT_IMPORT_TTXT:
return gf_text_import_ttxt(import);
case GF_TEXT_IMPORT_TEXML:
return gf_text_import_texml(import);
#ifndef GPAC_DISABLE_VTT
case GF_TEXT_IMPORT_WEBVTT:
return gf_text_import_webvtt(import);
#endif
case GF_TEXT_IMPORT_SWF_SVG:
return gf_text_import_swf(import);
case GF_TEXT_IMPORT_TTML:
return gf_text_import_ttml(import);
default:
return GF_BAD_PARAM;
}
}
#endif /*GPAC_DISABLE_MEDIA_IMPORT*/
#endif /*GPAC_DISABLE_ISOM_WRITE*/
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_526_1 |
crossvul-cpp_data_bad_2759_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_apps_config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include "openjpeg.h"
#include "convert.h"
/*
* Get logarithm of an integer and round downwards.
*
* log2(a)
*/
static int int_floorlog2(int a)
{
int l;
for (l = 0; a > 1; l++) {
a >>= 1;
}
return l;
}
/* Component precision scaling */
void clip_component(opj_image_comp_t* component, OPJ_UINT32 precision)
{
OPJ_SIZE_T i;
OPJ_SIZE_T len;
OPJ_UINT32 umax = (OPJ_UINT32)((OPJ_INT32) - 1);
len = (OPJ_SIZE_T)component->w * (OPJ_SIZE_T)component->h;
if (precision < 32) {
umax = (1U << precision) - 1U;
}
if (component->sgnd) {
OPJ_INT32* l_data = component->data;
OPJ_INT32 max = (OPJ_INT32)(umax / 2U);
OPJ_INT32 min = -max - 1;
for (i = 0; i < len; ++i) {
if (l_data[i] > max) {
l_data[i] = max;
} else if (l_data[i] < min) {
l_data[i] = min;
}
}
} else {
OPJ_UINT32* l_data = (OPJ_UINT32*)component->data;
for (i = 0; i < len; ++i) {
if (l_data[i] > umax) {
l_data[i] = umax;
}
}
}
component->prec = precision;
}
/* Component precision scaling */
static void scale_component_up(opj_image_comp_t* component,
OPJ_UINT32 precision)
{
OPJ_SIZE_T i, len;
len = (OPJ_SIZE_T)component->w * (OPJ_SIZE_T)component->h;
if (component->sgnd) {
OPJ_INT64 newMax = (OPJ_INT64)(1U << (precision - 1));
OPJ_INT64 oldMax = (OPJ_INT64)(1U << (component->prec - 1));
OPJ_INT32* l_data = component->data;
for (i = 0; i < len; ++i) {
l_data[i] = (OPJ_INT32)(((OPJ_INT64)l_data[i] * newMax) / oldMax);
}
} else {
OPJ_UINT64 newMax = (OPJ_UINT64)((1U << precision) - 1U);
OPJ_UINT64 oldMax = (OPJ_UINT64)((1U << component->prec) - 1U);
OPJ_UINT32* l_data = (OPJ_UINT32*)component->data;
for (i = 0; i < len; ++i) {
l_data[i] = (OPJ_UINT32)(((OPJ_UINT64)l_data[i] * newMax) / oldMax);
}
}
component->prec = precision;
component->bpp = precision;
}
void scale_component(opj_image_comp_t* component, OPJ_UINT32 precision)
{
int shift;
OPJ_SIZE_T i, len;
if (component->prec == precision) {
return;
}
if (component->prec < precision) {
scale_component_up(component, precision);
return;
}
shift = (int)(component->prec - precision);
len = (OPJ_SIZE_T)component->w * (OPJ_SIZE_T)component->h;
if (component->sgnd) {
OPJ_INT32* l_data = component->data;
for (i = 0; i < len; ++i) {
l_data[i] >>= shift;
}
} else {
OPJ_UINT32* l_data = (OPJ_UINT32*)component->data;
for (i = 0; i < len; ++i) {
l_data[i] >>= shift;
}
}
component->bpp = precision;
component->prec = precision;
}
/* planar / interleaved conversions */
/* used by PNG/TIFF */
static void convert_32s_C1P1(const OPJ_INT32* pSrc, OPJ_INT32* const* pDst,
OPJ_SIZE_T length)
{
memcpy(pDst[0], pSrc, length * sizeof(OPJ_INT32));
}
static void convert_32s_C2P2(const OPJ_INT32* pSrc, OPJ_INT32* const* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
OPJ_INT32* pDst0 = pDst[0];
OPJ_INT32* pDst1 = pDst[1];
for (i = 0; i < length; i++) {
pDst0[i] = pSrc[2 * i + 0];
pDst1[i] = pSrc[2 * i + 1];
}
}
static void convert_32s_C3P3(const OPJ_INT32* pSrc, OPJ_INT32* const* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
OPJ_INT32* pDst0 = pDst[0];
OPJ_INT32* pDst1 = pDst[1];
OPJ_INT32* pDst2 = pDst[2];
for (i = 0; i < length; i++) {
pDst0[i] = pSrc[3 * i + 0];
pDst1[i] = pSrc[3 * i + 1];
pDst2[i] = pSrc[3 * i + 2];
}
}
static void convert_32s_C4P4(const OPJ_INT32* pSrc, OPJ_INT32* const* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
OPJ_INT32* pDst0 = pDst[0];
OPJ_INT32* pDst1 = pDst[1];
OPJ_INT32* pDst2 = pDst[2];
OPJ_INT32* pDst3 = pDst[3];
for (i = 0; i < length; i++) {
pDst0[i] = pSrc[4 * i + 0];
pDst1[i] = pSrc[4 * i + 1];
pDst2[i] = pSrc[4 * i + 2];
pDst3[i] = pSrc[4 * i + 3];
}
}
const convert_32s_CXPX convert_32s_CXPX_LUT[5] = {
NULL,
convert_32s_C1P1,
convert_32s_C2P2,
convert_32s_C3P3,
convert_32s_C4P4
};
static void convert_32s_P1C1(OPJ_INT32 const* const* pSrc, OPJ_INT32* pDst,
OPJ_SIZE_T length, OPJ_INT32 adjust)
{
OPJ_SIZE_T i;
const OPJ_INT32* pSrc0 = pSrc[0];
for (i = 0; i < length; i++) {
pDst[i] = pSrc0[i] + adjust;
}
}
static void convert_32s_P2C2(OPJ_INT32 const* const* pSrc, OPJ_INT32* pDst,
OPJ_SIZE_T length, OPJ_INT32 adjust)
{
OPJ_SIZE_T i;
const OPJ_INT32* pSrc0 = pSrc[0];
const OPJ_INT32* pSrc1 = pSrc[1];
for (i = 0; i < length; i++) {
pDst[2 * i + 0] = pSrc0[i] + adjust;
pDst[2 * i + 1] = pSrc1[i] + adjust;
}
}
static void convert_32s_P3C3(OPJ_INT32 const* const* pSrc, OPJ_INT32* pDst,
OPJ_SIZE_T length, OPJ_INT32 adjust)
{
OPJ_SIZE_T i;
const OPJ_INT32* pSrc0 = pSrc[0];
const OPJ_INT32* pSrc1 = pSrc[1];
const OPJ_INT32* pSrc2 = pSrc[2];
for (i = 0; i < length; i++) {
pDst[3 * i + 0] = pSrc0[i] + adjust;
pDst[3 * i + 1] = pSrc1[i] + adjust;
pDst[3 * i + 2] = pSrc2[i] + adjust;
}
}
static void convert_32s_P4C4(OPJ_INT32 const* const* pSrc, OPJ_INT32* pDst,
OPJ_SIZE_T length, OPJ_INT32 adjust)
{
OPJ_SIZE_T i;
const OPJ_INT32* pSrc0 = pSrc[0];
const OPJ_INT32* pSrc1 = pSrc[1];
const OPJ_INT32* pSrc2 = pSrc[2];
const OPJ_INT32* pSrc3 = pSrc[3];
for (i = 0; i < length; i++) {
pDst[4 * i + 0] = pSrc0[i] + adjust;
pDst[4 * i + 1] = pSrc1[i] + adjust;
pDst[4 * i + 2] = pSrc2[i] + adjust;
pDst[4 * i + 3] = pSrc3[i] + adjust;
}
}
const convert_32s_PXCX convert_32s_PXCX_LUT[5] = {
NULL,
convert_32s_P1C1,
convert_32s_P2C2,
convert_32s_P3C3,
convert_32s_P4C4
};
/* bit depth conversions */
/* used by PNG/TIFF up to 8bpp */
static void convert_1u32s_C1R(const OPJ_BYTE* pSrc, OPJ_INT32* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
for (i = 0; i < (length & ~(OPJ_SIZE_T)7U); i += 8U) {
OPJ_UINT32 val = *pSrc++;
pDst[i + 0] = (OPJ_INT32)(val >> 7);
pDst[i + 1] = (OPJ_INT32)((val >> 6) & 0x1U);
pDst[i + 2] = (OPJ_INT32)((val >> 5) & 0x1U);
pDst[i + 3] = (OPJ_INT32)((val >> 4) & 0x1U);
pDst[i + 4] = (OPJ_INT32)((val >> 3) & 0x1U);
pDst[i + 5] = (OPJ_INT32)((val >> 2) & 0x1U);
pDst[i + 6] = (OPJ_INT32)((val >> 1) & 0x1U);
pDst[i + 7] = (OPJ_INT32)(val & 0x1U);
}
if (length & 7U) {
OPJ_UINT32 val = *pSrc++;
length = length & 7U;
pDst[i + 0] = (OPJ_INT32)(val >> 7);
if (length > 1U) {
pDst[i + 1] = (OPJ_INT32)((val >> 6) & 0x1U);
if (length > 2U) {
pDst[i + 2] = (OPJ_INT32)((val >> 5) & 0x1U);
if (length > 3U) {
pDst[i + 3] = (OPJ_INT32)((val >> 4) & 0x1U);
if (length > 4U) {
pDst[i + 4] = (OPJ_INT32)((val >> 3) & 0x1U);
if (length > 5U) {
pDst[i + 5] = (OPJ_INT32)((val >> 2) & 0x1U);
if (length > 6U) {
pDst[i + 6] = (OPJ_INT32)((val >> 1) & 0x1U);
}
}
}
}
}
}
}
}
static void convert_2u32s_C1R(const OPJ_BYTE* pSrc, OPJ_INT32* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
for (i = 0; i < (length & ~(OPJ_SIZE_T)3U); i += 4U) {
OPJ_UINT32 val = *pSrc++;
pDst[i + 0] = (OPJ_INT32)(val >> 6);
pDst[i + 1] = (OPJ_INT32)((val >> 4) & 0x3U);
pDst[i + 2] = (OPJ_INT32)((val >> 2) & 0x3U);
pDst[i + 3] = (OPJ_INT32)(val & 0x3U);
}
if (length & 3U) {
OPJ_UINT32 val = *pSrc++;
length = length & 3U;
pDst[i + 0] = (OPJ_INT32)(val >> 6);
if (length > 1U) {
pDst[i + 1] = (OPJ_INT32)((val >> 4) & 0x3U);
if (length > 2U) {
pDst[i + 2] = (OPJ_INT32)((val >> 2) & 0x3U);
}
}
}
}
static void convert_4u32s_C1R(const OPJ_BYTE* pSrc, OPJ_INT32* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
for (i = 0; i < (length & ~(OPJ_SIZE_T)1U); i += 2U) {
OPJ_UINT32 val = *pSrc++;
pDst[i + 0] = (OPJ_INT32)(val >> 4);
pDst[i + 1] = (OPJ_INT32)(val & 0xFU);
}
if (length & 1U) {
OPJ_UINT8 val = *pSrc++;
pDst[i + 0] = (OPJ_INT32)(val >> 4);
}
}
static void convert_6u32s_C1R(const OPJ_BYTE* pSrc, OPJ_INT32* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
for (i = 0; i < (length & ~(OPJ_SIZE_T)3U); i += 4U) {
OPJ_UINT32 val0 = *pSrc++;
OPJ_UINT32 val1 = *pSrc++;
OPJ_UINT32 val2 = *pSrc++;
pDst[i + 0] = (OPJ_INT32)(val0 >> 2);
pDst[i + 1] = (OPJ_INT32)(((val0 & 0x3U) << 4) | (val1 >> 4));
pDst[i + 2] = (OPJ_INT32)(((val1 & 0xFU) << 2) | (val2 >> 6));
pDst[i + 3] = (OPJ_INT32)(val2 & 0x3FU);
}
if (length & 3U) {
OPJ_UINT32 val0 = *pSrc++;
length = length & 3U;
pDst[i + 0] = (OPJ_INT32)(val0 >> 2);
if (length > 1U) {
OPJ_UINT32 val1 = *pSrc++;
pDst[i + 1] = (OPJ_INT32)(((val0 & 0x3U) << 4) | (val1 >> 4));
if (length > 2U) {
OPJ_UINT32 val2 = *pSrc++;
pDst[i + 2] = (OPJ_INT32)(((val1 & 0xFU) << 2) | (val2 >> 6));
}
}
}
}
static void convert_8u32s_C1R(const OPJ_BYTE* pSrc, OPJ_INT32* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
for (i = 0; i < length; i++) {
pDst[i] = pSrc[i];
}
}
const convert_XXx32s_C1R convert_XXu32s_C1R_LUT[9] = {
NULL,
convert_1u32s_C1R,
convert_2u32s_C1R,
NULL,
convert_4u32s_C1R,
NULL,
convert_6u32s_C1R,
NULL,
convert_8u32s_C1R
};
static void convert_32s1u_C1R(const OPJ_INT32* pSrc, OPJ_BYTE* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
for (i = 0; i < (length & ~(OPJ_SIZE_T)7U); i += 8U) {
OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i + 0];
OPJ_UINT32 src1 = (OPJ_UINT32)pSrc[i + 1];
OPJ_UINT32 src2 = (OPJ_UINT32)pSrc[i + 2];
OPJ_UINT32 src3 = (OPJ_UINT32)pSrc[i + 3];
OPJ_UINT32 src4 = (OPJ_UINT32)pSrc[i + 4];
OPJ_UINT32 src5 = (OPJ_UINT32)pSrc[i + 5];
OPJ_UINT32 src6 = (OPJ_UINT32)pSrc[i + 6];
OPJ_UINT32 src7 = (OPJ_UINT32)pSrc[i + 7];
*pDst++ = (OPJ_BYTE)((src0 << 7) | (src1 << 6) | (src2 << 5) | (src3 << 4) |
(src4 << 3) | (src5 << 2) | (src6 << 1) | src7);
}
if (length & 7U) {
OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i + 0];
OPJ_UINT32 src1 = 0U;
OPJ_UINT32 src2 = 0U;
OPJ_UINT32 src3 = 0U;
OPJ_UINT32 src4 = 0U;
OPJ_UINT32 src5 = 0U;
OPJ_UINT32 src6 = 0U;
length = length & 7U;
if (length > 1U) {
src1 = (OPJ_UINT32)pSrc[i + 1];
if (length > 2U) {
src2 = (OPJ_UINT32)pSrc[i + 2];
if (length > 3U) {
src3 = (OPJ_UINT32)pSrc[i + 3];
if (length > 4U) {
src4 = (OPJ_UINT32)pSrc[i + 4];
if (length > 5U) {
src5 = (OPJ_UINT32)pSrc[i + 5];
if (length > 6U) {
src6 = (OPJ_UINT32)pSrc[i + 6];
}
}
}
}
}
}
*pDst++ = (OPJ_BYTE)((src0 << 7) | (src1 << 6) | (src2 << 5) | (src3 << 4) |
(src4 << 3) | (src5 << 2) | (src6 << 1));
}
}
static void convert_32s2u_C1R(const OPJ_INT32* pSrc, OPJ_BYTE* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
for (i = 0; i < (length & ~(OPJ_SIZE_T)3U); i += 4U) {
OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i + 0];
OPJ_UINT32 src1 = (OPJ_UINT32)pSrc[i + 1];
OPJ_UINT32 src2 = (OPJ_UINT32)pSrc[i + 2];
OPJ_UINT32 src3 = (OPJ_UINT32)pSrc[i + 3];
*pDst++ = (OPJ_BYTE)((src0 << 6) | (src1 << 4) | (src2 << 2) | src3);
}
if (length & 3U) {
OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i + 0];
OPJ_UINT32 src1 = 0U;
OPJ_UINT32 src2 = 0U;
length = length & 3U;
if (length > 1U) {
src1 = (OPJ_UINT32)pSrc[i + 1];
if (length > 2U) {
src2 = (OPJ_UINT32)pSrc[i + 2];
}
}
*pDst++ = (OPJ_BYTE)((src0 << 6) | (src1 << 4) | (src2 << 2));
}
}
static void convert_32s4u_C1R(const OPJ_INT32* pSrc, OPJ_BYTE* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
for (i = 0; i < (length & ~(OPJ_SIZE_T)1U); i += 2U) {
OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i + 0];
OPJ_UINT32 src1 = (OPJ_UINT32)pSrc[i + 1];
*pDst++ = (OPJ_BYTE)((src0 << 4) | src1);
}
if (length & 1U) {
OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i + 0];
*pDst++ = (OPJ_BYTE)((src0 << 4));
}
}
static void convert_32s6u_C1R(const OPJ_INT32* pSrc, OPJ_BYTE* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
for (i = 0; i < (length & ~(OPJ_SIZE_T)3U); i += 4U) {
OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i + 0];
OPJ_UINT32 src1 = (OPJ_UINT32)pSrc[i + 1];
OPJ_UINT32 src2 = (OPJ_UINT32)pSrc[i + 2];
OPJ_UINT32 src3 = (OPJ_UINT32)pSrc[i + 3];
*pDst++ = (OPJ_BYTE)((src0 << 2) | (src1 >> 4));
*pDst++ = (OPJ_BYTE)(((src1 & 0xFU) << 4) | (src2 >> 2));
*pDst++ = (OPJ_BYTE)(((src2 & 0x3U) << 6) | src3);
}
if (length & 3U) {
OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i + 0];
OPJ_UINT32 src1 = 0U;
OPJ_UINT32 src2 = 0U;
length = length & 3U;
if (length > 1U) {
src1 = (OPJ_UINT32)pSrc[i + 1];
if (length > 2U) {
src2 = (OPJ_UINT32)pSrc[i + 2];
}
}
*pDst++ = (OPJ_BYTE)((src0 << 2) | (src1 >> 4));
if (length > 1U) {
*pDst++ = (OPJ_BYTE)(((src1 & 0xFU) << 4) | (src2 >> 2));
if (length > 2U) {
*pDst++ = (OPJ_BYTE)(((src2 & 0x3U) << 6));
}
}
}
}
static void convert_32s8u_C1R(const OPJ_INT32* pSrc, OPJ_BYTE* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
for (i = 0; i < length; ++i) {
pDst[i] = (OPJ_BYTE)pSrc[i];
}
}
const convert_32sXXx_C1R convert_32sXXu_C1R_LUT[9] = {
NULL,
convert_32s1u_C1R,
convert_32s2u_C1R,
NULL,
convert_32s4u_C1R,
NULL,
convert_32s6u_C1R,
NULL,
convert_32s8u_C1R
};
/* -->> -->> -->> -->>
TGA IMAGE FORMAT
<<-- <<-- <<-- <<-- */
#ifdef INFORMATION_ONLY
/* TGA header definition. */
struct tga_header {
unsigned char id_length; /* Image id field length */
unsigned char colour_map_type; /* Colour map type */
unsigned char image_type; /* Image type */
/*
** Colour map specification
*/
unsigned short colour_map_index; /* First entry index */
unsigned short colour_map_length; /* Colour map length */
unsigned char colour_map_entry_size; /* Colour map entry size */
/*
** Image specification
*/
unsigned short x_origin; /* x origin of image */
unsigned short y_origin; /* u origin of image */
unsigned short image_width; /* Image width */
unsigned short image_height; /* Image height */
unsigned char pixel_depth; /* Pixel depth */
unsigned char image_desc; /* Image descriptor */
};
#endif /* INFORMATION_ONLY */
static unsigned short get_ushort(const unsigned char *data)
{
unsigned short val = *(const unsigned short *)data;
#ifdef OPJ_BIG_ENDIAN
val = ((val & 0xffU) << 8) | (val >> 8);
#endif
return val;
}
#define TGA_HEADER_SIZE 18
static int tga_readheader(FILE *fp, unsigned int *bits_per_pixel,
unsigned int *width, unsigned int *height, int *flip_image)
{
int palette_size;
unsigned char tga[TGA_HEADER_SIZE];
unsigned char id_len, /*cmap_type,*/ image_type;
unsigned char pixel_depth, image_desc;
unsigned short /*cmap_index,*/ cmap_len, cmap_entry_size;
unsigned short /*x_origin, y_origin,*/ image_w, image_h;
if (!bits_per_pixel || !width || !height || !flip_image) {
return 0;
}
if (fread(tga, TGA_HEADER_SIZE, 1, fp) != 1) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
return 0 ;
}
id_len = tga[0];
/*cmap_type = tga[1];*/
image_type = tga[2];
/*cmap_index = get_ushort(&tga[3]);*/
cmap_len = get_ushort(&tga[5]);
cmap_entry_size = tga[7];
#if 0
x_origin = get_ushort(&tga[8]);
y_origin = get_ushort(&tga[10]);
#endif
image_w = get_ushort(&tga[12]);
image_h = get_ushort(&tga[14]);
pixel_depth = tga[16];
image_desc = tga[17];
*bits_per_pixel = (unsigned int)pixel_depth;
*width = (unsigned int)image_w;
*height = (unsigned int)image_h;
/* Ignore tga identifier, if present ... */
if (id_len) {
unsigned char *id = (unsigned char *) malloc(id_len);
if (id == 0) {
fprintf(stderr, "tga_readheader: memory out\n");
return 0;
}
if (!fread(id, id_len, 1, fp)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
free(id);
return 0 ;
}
free(id);
}
/* Test for compressed formats ... not yet supported ...
// Note :- 9 - RLE encoded palettized.
// 10 - RLE encoded RGB. */
if (image_type > 8) {
fprintf(stderr, "Sorry, compressed tga files are not currently supported.\n");
return 0 ;
}
*flip_image = !(image_desc & 32);
/* Palettized formats are not yet supported, skip over the palette, if present ... */
palette_size = cmap_len * (cmap_entry_size / 8);
if (palette_size > 0) {
fprintf(stderr, "File contains a palette - not yet supported.");
fseek(fp, palette_size, SEEK_CUR);
}
return 1;
}
#ifdef OPJ_BIG_ENDIAN
static INLINE OPJ_UINT16 swap16(OPJ_UINT16 x)
{
return (OPJ_UINT16)(((x & 0x00ffU) << 8) | ((x & 0xff00U) >> 8));
}
#endif
static int tga_writeheader(FILE *fp, int bits_per_pixel, int width, int height,
OPJ_BOOL flip_image)
{
OPJ_UINT16 image_w, image_h, us0;
unsigned char uc0, image_type;
unsigned char pixel_depth, image_desc;
if (!bits_per_pixel || !width || !height) {
return 0;
}
pixel_depth = 0;
if (bits_per_pixel < 256) {
pixel_depth = (unsigned char)bits_per_pixel;
} else {
fprintf(stderr, "ERROR: Wrong bits per pixel inside tga_header");
return 0;
}
uc0 = 0;
if (fwrite(&uc0, 1, 1, fp) != 1) {
goto fails; /* id_length */
}
if (fwrite(&uc0, 1, 1, fp) != 1) {
goto fails; /* colour_map_type */
}
image_type = 2; /* Uncompressed. */
if (fwrite(&image_type, 1, 1, fp) != 1) {
goto fails;
}
us0 = 0;
if (fwrite(&us0, 2, 1, fp) != 1) {
goto fails; /* colour_map_index */
}
if (fwrite(&us0, 2, 1, fp) != 1) {
goto fails; /* colour_map_length */
}
if (fwrite(&uc0, 1, 1, fp) != 1) {
goto fails; /* colour_map_entry_size */
}
if (fwrite(&us0, 2, 1, fp) != 1) {
goto fails; /* x_origin */
}
if (fwrite(&us0, 2, 1, fp) != 1) {
goto fails; /* y_origin */
}
image_w = (unsigned short)width;
image_h = (unsigned short) height;
#ifndef OPJ_BIG_ENDIAN
if (fwrite(&image_w, 2, 1, fp) != 1) {
goto fails;
}
if (fwrite(&image_h, 2, 1, fp) != 1) {
goto fails;
}
#else
image_w = swap16(image_w);
image_h = swap16(image_h);
if (fwrite(&image_w, 2, 1, fp) != 1) {
goto fails;
}
if (fwrite(&image_h, 2, 1, fp) != 1) {
goto fails;
}
#endif
if (fwrite(&pixel_depth, 1, 1, fp) != 1) {
goto fails;
}
image_desc = 8; /* 8 bits per component. */
if (flip_image) {
image_desc |= 32;
}
if (fwrite(&image_desc, 1, 1, fp) != 1) {
goto fails;
}
return 1;
fails:
fputs("\nwrite_tgaheader: write ERROR\n", stderr);
return 0;
}
opj_image_t* tgatoimage(const char *filename, opj_cparameters_t *parameters)
{
FILE *f;
opj_image_t *image;
unsigned int image_width, image_height, pixel_bit_depth;
unsigned int x, y;
int flip_image = 0;
opj_image_cmptparm_t cmptparm[4]; /* maximum 4 components */
int numcomps;
OPJ_COLOR_SPACE color_space;
OPJ_BOOL mono ;
OPJ_BOOL save_alpha;
int subsampling_dx, subsampling_dy;
int i;
f = fopen(filename, "rb");
if (!f) {
fprintf(stderr, "Failed to open %s for reading !!\n", filename);
return 0;
}
if (!tga_readheader(f, &pixel_bit_depth, &image_width, &image_height,
&flip_image)) {
fclose(f);
return NULL;
}
/* We currently only support 24 & 32 bit tga's ... */
if (!((pixel_bit_depth == 24) || (pixel_bit_depth == 32))) {
fclose(f);
return NULL;
}
/* initialize image components */
memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));
mono = (pixel_bit_depth == 8) ||
(pixel_bit_depth == 16); /* Mono with & without alpha. */
save_alpha = (pixel_bit_depth == 16) ||
(pixel_bit_depth == 32); /* Mono with alpha, or RGB with alpha */
if (mono) {
color_space = OPJ_CLRSPC_GRAY;
numcomps = save_alpha ? 2 : 1;
} else {
numcomps = save_alpha ? 4 : 3;
color_space = OPJ_CLRSPC_SRGB;
}
subsampling_dx = parameters->subsampling_dx;
subsampling_dy = parameters->subsampling_dy;
for (i = 0; i < numcomps; i++) {
cmptparm[i].prec = 8;
cmptparm[i].bpp = 8;
cmptparm[i].sgnd = 0;
cmptparm[i].dx = (OPJ_UINT32)subsampling_dx;
cmptparm[i].dy = (OPJ_UINT32)subsampling_dy;
cmptparm[i].w = image_width;
cmptparm[i].h = image_height;
}
/* create the image */
image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
if (!image) {
fclose(f);
return NULL;
}
/* set image offset and reference grid */
image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
image->x1 = !image->x0 ? (OPJ_UINT32)(image_width - 1) *
(OPJ_UINT32)subsampling_dx + 1 : image->x0 + (OPJ_UINT32)(image_width - 1) *
(OPJ_UINT32)subsampling_dx + 1;
image->y1 = !image->y0 ? (OPJ_UINT32)(image_height - 1) *
(OPJ_UINT32)subsampling_dy + 1 : image->y0 + (OPJ_UINT32)(image_height - 1) *
(OPJ_UINT32)subsampling_dy + 1;
/* set image data */
for (y = 0; y < image_height; y++) {
int index;
if (flip_image) {
index = (int)((image_height - y - 1) * image_width);
} else {
index = (int)(y * image_width);
}
if (numcomps == 3) {
for (x = 0; x < image_width; x++) {
unsigned char r, g, b;
if (!fread(&b, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&g, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&r, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
image->comps[0].data[index] = r;
image->comps[1].data[index] = g;
image->comps[2].data[index] = b;
index++;
}
} else if (numcomps == 4) {
for (x = 0; x < image_width; x++) {
unsigned char r, g, b, a;
if (!fread(&b, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&g, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&r, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&a, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
image->comps[0].data[index] = r;
image->comps[1].data[index] = g;
image->comps[2].data[index] = b;
image->comps[3].data[index] = a;
index++;
}
} else {
fprintf(stderr, "Currently unsupported bit depth : %s\n", filename);
}
}
fclose(f);
return image;
}
int imagetotga(opj_image_t * image, const char *outfile)
{
int width, height, bpp, x, y;
OPJ_BOOL write_alpha;
unsigned int i;
int adjustR, adjustG = 0, adjustB = 0, fails;
unsigned int alpha_channel;
float r, g, b, a;
unsigned char value;
float scale;
FILE *fdest;
size_t res;
fails = 1;
fdest = fopen(outfile, "wb");
if (!fdest) {
fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
return 1;
}
for (i = 0; i < image->numcomps - 1; i++) {
if ((image->comps[0].dx != image->comps[i + 1].dx)
|| (image->comps[0].dy != image->comps[i + 1].dy)
|| (image->comps[0].prec != image->comps[i + 1].prec)
|| (image->comps[0].sgnd != image->comps[i + 1].sgnd)) {
fclose(fdest);
fprintf(stderr,
"Unable to create a tga file with such J2K image charateristics.\n");
return 1;
}
}
width = (int)image->comps[0].w;
height = (int)image->comps[0].h;
/* Mono with alpha, or RGB with alpha. */
write_alpha = (image->numcomps == 2) || (image->numcomps == 4);
/* Write TGA header */
bpp = write_alpha ? 32 : 24;
if (!tga_writeheader(fdest, bpp, width, height, OPJ_TRUE)) {
goto fin;
}
alpha_channel = image->numcomps - 1;
scale = 255.0f / (float)((1 << image->comps[0].prec) - 1);
adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
if (image->numcomps >= 3) {
adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
}
for (y = 0; y < height; y++) {
unsigned int index = (unsigned int)(y * width);
for (x = 0; x < width; x++, index++) {
r = (float)(image->comps[0].data[index] + adjustR);
if (image->numcomps > 2) {
g = (float)(image->comps[1].data[index] + adjustG);
b = (float)(image->comps[2].data[index] + adjustB);
} else {
/* Greyscale ... */
g = r;
b = r;
}
/* TGA format writes BGR ... */
if (b > 255.) {
b = 255.;
} else if (b < 0.) {
b = 0.;
}
value = (unsigned char)(b * scale);
res = fwrite(&value, 1, 1, fdest);
if (res < 1) {
fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
goto fin;
}
if (g > 255.) {
g = 255.;
} else if (g < 0.) {
g = 0.;
}
value = (unsigned char)(g * scale);
res = fwrite(&value, 1, 1, fdest);
if (res < 1) {
fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
goto fin;
}
if (r > 255.) {
r = 255.;
} else if (r < 0.) {
r = 0.;
}
value = (unsigned char)(r * scale);
res = fwrite(&value, 1, 1, fdest);
if (res < 1) {
fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
goto fin;
}
if (write_alpha) {
a = (float)(image->comps[alpha_channel].data[index]);
if (a > 255.) {
a = 255.;
} else if (a < 0.) {
a = 0.;
}
value = (unsigned char)(a * scale);
res = fwrite(&value, 1, 1, fdest);
if (res < 1) {
fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
goto fin;
}
}
}
}
fails = 0;
fin:
fclose(fdest);
return fails;
}
/* -->> -->> -->> -->>
PGX IMAGE FORMAT
<<-- <<-- <<-- <<-- */
static unsigned char readuchar(FILE * f)
{
unsigned char c1;
if (!fread(&c1, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
return 0;
}
return c1;
}
static unsigned short readushort(FILE * f, int bigendian)
{
unsigned char c1, c2;
if (!fread(&c1, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
return 0;
}
if (!fread(&c2, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
return 0;
}
if (bigendian) {
return (unsigned short)((c1 << 8) + c2);
} else {
return (unsigned short)((c2 << 8) + c1);
}
}
static unsigned int readuint(FILE * f, int bigendian)
{
unsigned char c1, c2, c3, c4;
if (!fread(&c1, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
return 0;
}
if (!fread(&c2, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
return 0;
}
if (!fread(&c3, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
return 0;
}
if (!fread(&c4, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
return 0;
}
if (bigendian) {
return (unsigned int)(c1 << 24) + (unsigned int)(c2 << 16) + (unsigned int)(
c3 << 8) + c4;
} else {
return (unsigned int)(c4 << 24) + (unsigned int)(c3 << 16) + (unsigned int)(
c2 << 8) + c1;
}
}
opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters)
{
FILE *f = NULL;
int w, h, prec;
int i, numcomps, max;
OPJ_COLOR_SPACE color_space;
opj_image_cmptparm_t cmptparm; /* maximum of 1 component */
opj_image_t * image = NULL;
int adjustS, ushift, dshift, force8;
char endian1, endian2, sign;
char signtmp[32];
char temp[32];
int bigendian;
opj_image_comp_t *comp = NULL;
numcomps = 1;
color_space = OPJ_CLRSPC_GRAY;
memset(&cmptparm, 0, sizeof(opj_image_cmptparm_t));
max = 0;
f = fopen(filename, "rb");
if (!f) {
fprintf(stderr, "Failed to open %s for reading !\n", filename);
return NULL;
}
fseek(f, 0, SEEK_SET);
if (fscanf(f, "PG%[ \t]%c%c%[ \t+-]%d%[ \t]%d%[ \t]%d", temp, &endian1,
&endian2, signtmp, &prec, temp, &w, temp, &h) != 9) {
fclose(f);
fprintf(stderr,
"ERROR: Failed to read the right number of element from the fscanf() function!\n");
return NULL;
}
i = 0;
sign = '+';
while (signtmp[i] != '\0') {
if (signtmp[i] == '-') {
sign = '-';
}
i++;
}
fgetc(f);
if (endian1 == 'M' && endian2 == 'L') {
bigendian = 1;
} else if (endian2 == 'M' && endian1 == 'L') {
bigendian = 0;
} else {
fclose(f);
fprintf(stderr, "Bad pgx header, please check input file\n");
return NULL;
}
/* initialize image component */
cmptparm.x0 = (OPJ_UINT32)parameters->image_offset_x0;
cmptparm.y0 = (OPJ_UINT32)parameters->image_offset_y0;
cmptparm.w = !cmptparm.x0 ? (OPJ_UINT32)((w - 1) * parameters->subsampling_dx +
1) : cmptparm.x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)parameters->subsampling_dx
+ 1;
cmptparm.h = !cmptparm.y0 ? (OPJ_UINT32)((h - 1) * parameters->subsampling_dy +
1) : cmptparm.y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)parameters->subsampling_dy
+ 1;
if (sign == '-') {
cmptparm.sgnd = 1;
} else {
cmptparm.sgnd = 0;
}
if (prec < 8) {
force8 = 1;
ushift = 8 - prec;
dshift = prec - ushift;
if (cmptparm.sgnd) {
adjustS = (1 << (prec - 1));
} else {
adjustS = 0;
}
cmptparm.sgnd = 0;
prec = 8;
} else {
ushift = dshift = force8 = adjustS = 0;
}
cmptparm.prec = (OPJ_UINT32)prec;
cmptparm.bpp = (OPJ_UINT32)prec;
cmptparm.dx = (OPJ_UINT32)parameters->subsampling_dx;
cmptparm.dy = (OPJ_UINT32)parameters->subsampling_dy;
/* create the image */
image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm, color_space);
if (!image) {
fclose(f);
return NULL;
}
/* set image offset and reference grid */
image->x0 = cmptparm.x0;
image->y0 = cmptparm.x0;
image->x1 = cmptparm.w;
image->y1 = cmptparm.h;
/* set image data */
comp = &image->comps[0];
for (i = 0; i < w * h; i++) {
int v;
if (force8) {
v = readuchar(f) + adjustS;
v = (v << ushift) + (v >> dshift);
comp->data[i] = (unsigned char)v;
if (v > max) {
max = v;
}
continue;
}
if (comp->prec == 8) {
if (!comp->sgnd) {
v = readuchar(f);
} else {
v = (char) readuchar(f);
}
} else if (comp->prec <= 16) {
if (!comp->sgnd) {
v = readushort(f, bigendian);
} else {
v = (short) readushort(f, bigendian);
}
} else {
if (!comp->sgnd) {
v = (int)readuint(f, bigendian);
} else {
v = (int) readuint(f, bigendian);
}
}
if (v > max) {
max = v;
}
comp->data[i] = v;
}
fclose(f);
comp->bpp = (OPJ_UINT32)int_floorlog2(max) + 1;
return image;
}
#define CLAMP(x,a,b) x < a ? a : (x > b ? b : x)
static INLINE int clamp(const int value, const int prec, const int sgnd)
{
if (sgnd) {
if (prec <= 8) {
return CLAMP(value, -128, 127);
} else if (prec <= 16) {
return CLAMP(value, -32768, 32767);
} else {
return CLAMP(value, -2147483647 - 1, 2147483647);
}
} else {
if (prec <= 8) {
return CLAMP(value, 0, 255);
} else if (prec <= 16) {
return CLAMP(value, 0, 65535);
} else {
return value; /*CLAMP(value,0,4294967295);*/
}
}
}
int imagetopgx(opj_image_t * image, const char *outfile)
{
int w, h;
int i, j, fails = 1;
unsigned int compno;
FILE *fdest = NULL;
for (compno = 0; compno < image->numcomps; compno++) {
opj_image_comp_t *comp = &image->comps[compno];
char bname[256]; /* buffer for name */
char *name = bname; /* pointer */
int nbytes = 0;
size_t res;
const size_t olen = strlen(outfile);
const size_t dotpos = olen - 4;
const size_t total = dotpos + 1 + 1 + 4; /* '-' + '[1-3]' + '.pgx' */
if (outfile[dotpos] != '.') {
/* `pgx` was recognized but there is no dot at expected position */
fprintf(stderr, "ERROR -> Impossible happen.");
goto fin;
}
if (total > 256) {
name = (char*)malloc(total + 1);
if (name == NULL) {
fprintf(stderr, "imagetopgx: memory out\n");
goto fin;
}
}
strncpy(name, outfile, dotpos);
sprintf(name + dotpos, "_%u.pgx", compno);
fdest = fopen(name, "wb");
/* don't need name anymore */
if (!fdest) {
fprintf(stderr, "ERROR -> failed to open %s for writing\n", name);
if (total > 256) {
free(name);
}
goto fin;
}
w = (int)image->comps[compno].w;
h = (int)image->comps[compno].h;
fprintf(fdest, "PG ML %c %d %d %d\n", comp->sgnd ? '-' : '+', comp->prec,
w, h);
if (comp->prec <= 8) {
nbytes = 1;
} else if (comp->prec <= 16) {
nbytes = 2;
} else {
nbytes = 4;
}
for (i = 0; i < w * h; i++) {
/* FIXME: clamp func is being called within a loop */
const int val = clamp(image->comps[compno].data[i],
(int)comp->prec, (int)comp->sgnd);
for (j = nbytes - 1; j >= 0; j--) {
int v = (int)(val >> (j * 8));
unsigned char byte = (unsigned char)v;
res = fwrite(&byte, 1, 1, fdest);
if (res < 1) {
fprintf(stderr, "failed to write 1 byte for %s\n", name);
if (total > 256) {
free(name);
}
goto fin;
}
}
}
if (total > 256) {
free(name);
}
fclose(fdest);
fdest = NULL;
}
fails = 0;
fin:
if (fdest) {
fclose(fdest);
}
return fails;
}
/* -->> -->> -->> -->>
PNM IMAGE FORMAT
<<-- <<-- <<-- <<-- */
struct pnm_header {
int width, height, maxval, depth, format;
char rgb, rgba, gray, graya, bw;
char ok;
};
static char *skip_white(char *s)
{
if (s != NULL) {
while (*s) {
if (*s == '\n' || *s == '\r') {
return NULL;
}
if (isspace(*s)) {
++s;
continue;
}
return s;
}
}
return NULL;
}
static char *skip_int(char *start, int *out_n)
{
char *s;
char c;
*out_n = 0;
s = skip_white(start);
if (s == NULL) {
return NULL;
}
start = s;
while (*s) {
if (!isdigit(*s)) {
break;
}
++s;
}
c = *s;
*s = 0;
*out_n = atoi(start);
*s = c;
return s;
}
static char *skip_idf(char *start, char out_idf[256])
{
char *s;
char c;
s = skip_white(start);
if (s == NULL) {
return NULL;
}
start = s;
while (*s) {
if (isalpha(*s) || *s == '_') {
++s;
continue;
}
break;
}
c = *s;
*s = 0;
strncpy(out_idf, start, 255);
*s = c;
return s;
}
static void read_pnm_header(FILE *reader, struct pnm_header *ph)
{
int format, end, ttype;
char idf[256], type[256];
char line[256];
if (fgets(line, 250, reader) == NULL) {
fprintf(stderr, "\nWARNING: fgets return a NULL value");
return;
}
if (line[0] != 'P') {
fprintf(stderr, "read_pnm_header:PNM:magic P missing\n");
return;
}
format = atoi(line + 1);
if (format < 1 || format > 7) {
fprintf(stderr, "read_pnm_header:magic format %d invalid\n", format);
return;
}
ph->format = format;
ttype = end = 0;
while (fgets(line, 250, reader)) {
char *s;
int allow_null = 0;
if (*line == '#') {
continue;
}
s = line;
if (format == 7) {
s = skip_idf(s, idf);
if (s == NULL || *s == 0) {
return;
}
if (strcmp(idf, "ENDHDR") == 0) {
end = 1;
break;
}
if (strcmp(idf, "WIDTH") == 0) {
s = skip_int(s, &ph->width);
if (s == NULL || *s == 0) {
return;
}
continue;
}
if (strcmp(idf, "HEIGHT") == 0) {
s = skip_int(s, &ph->height);
if (s == NULL || *s == 0) {
return;
}
continue;
}
if (strcmp(idf, "DEPTH") == 0) {
s = skip_int(s, &ph->depth);
if (s == NULL || *s == 0) {
return;
}
continue;
}
if (strcmp(idf, "MAXVAL") == 0) {
s = skip_int(s, &ph->maxval);
if (s == NULL || *s == 0) {
return;
}
continue;
}
if (strcmp(idf, "TUPLTYPE") == 0) {
s = skip_idf(s, type);
if (s == NULL || *s == 0) {
return;
}
if (strcmp(type, "BLACKANDWHITE") == 0) {
ph->bw = 1;
ttype = 1;
continue;
}
if (strcmp(type, "GRAYSCALE") == 0) {
ph->gray = 1;
ttype = 1;
continue;
}
if (strcmp(type, "GRAYSCALE_ALPHA") == 0) {
ph->graya = 1;
ttype = 1;
continue;
}
if (strcmp(type, "RGB") == 0) {
ph->rgb = 1;
ttype = 1;
continue;
}
if (strcmp(type, "RGB_ALPHA") == 0) {
ph->rgba = 1;
ttype = 1;
continue;
}
fprintf(stderr, "read_pnm_header:unknown P7 TUPLTYPE %s\n", type);
return;
}
fprintf(stderr, "read_pnm_header:unknown P7 idf %s\n", idf);
return;
} /* if(format == 7) */
/* Here format is in range [1,6] */
if (ph->width == 0) {
s = skip_int(s, &ph->width);
if ((s == NULL) || (*s == 0) || (ph->width < 1)) {
return;
}
allow_null = 1;
}
if (ph->height == 0) {
s = skip_int(s, &ph->height);
if ((s == NULL) && allow_null) {
continue;
}
if ((s == NULL) || (*s == 0) || (ph->height < 1)) {
return;
}
if (format == 1 || format == 4) {
break;
}
allow_null = 1;
}
/* here, format is in P2, P3, P5, P6 */
s = skip_int(s, &ph->maxval);
if ((s == NULL) && allow_null) {
continue;
}
if ((s == NULL) || (*s == 0)) {
return;
}
break;
}/* while(fgets( ) */
if (format == 2 || format == 3 || format > 4) {
if (ph->maxval < 1 || ph->maxval > 65535) {
return;
}
}
if (ph->width < 1 || ph->height < 1) {
return;
}
if (format == 7) {
if (!end) {
fprintf(stderr, "read_pnm_header:P7 without ENDHDR\n");
return;
}
if (ph->depth < 1 || ph->depth > 4) {
return;
}
if (ttype) {
ph->ok = 1;
}
} else {
ph->ok = 1;
if (format == 1 || format == 4) {
ph->maxval = 255;
}
}
}
static int has_prec(int val)
{
if (val < 2) {
return 1;
}
if (val < 4) {
return 2;
}
if (val < 8) {
return 3;
}
if (val < 16) {
return 4;
}
if (val < 32) {
return 5;
}
if (val < 64) {
return 6;
}
if (val < 128) {
return 7;
}
if (val < 256) {
return 8;
}
if (val < 512) {
return 9;
}
if (val < 1024) {
return 10;
}
if (val < 2048) {
return 11;
}
if (val < 4096) {
return 12;
}
if (val < 8192) {
return 13;
}
if (val < 16384) {
return 14;
}
if (val < 32768) {
return 15;
}
return 16;
}
opj_image_t* pnmtoimage(const char *filename, opj_cparameters_t *parameters)
{
int subsampling_dx = parameters->subsampling_dx;
int subsampling_dy = parameters->subsampling_dy;
FILE *fp = NULL;
int i, compno, numcomps, w, h, prec, format;
OPJ_COLOR_SPACE color_space;
opj_image_cmptparm_t cmptparm[4]; /* RGBA: max. 4 components */
opj_image_t * image = NULL;
struct pnm_header header_info;
if ((fp = fopen(filename, "rb")) == NULL) {
fprintf(stderr, "pnmtoimage:Failed to open %s for reading!\n", filename);
return NULL;
}
memset(&header_info, 0, sizeof(struct pnm_header));
read_pnm_header(fp, &header_info);
if (!header_info.ok) {
fclose(fp);
return NULL;
}
/* This limitation could be removed by making sure to use size_t below */
if (header_info.height != 0 &&
header_info.width > INT_MAX / header_info.height) {
fprintf(stderr, "pnmtoimage:Image %dx%d too big!\n",
header_info.width, header_info.height);
fclose(fp);
return NULL;
}
format = header_info.format;
switch (format) {
case 1: /* ascii bitmap */
case 4: /* raw bitmap */
numcomps = 1;
break;
case 2: /* ascii greymap */
case 5: /* raw greymap */
numcomps = 1;
break;
case 3: /* ascii pixmap */
case 6: /* raw pixmap */
numcomps = 3;
break;
case 7: /* arbitrary map */
numcomps = header_info.depth;
break;
default:
fclose(fp);
return NULL;
}
if (numcomps < 3) {
color_space = OPJ_CLRSPC_GRAY; /* GRAY, GRAYA */
} else {
color_space = OPJ_CLRSPC_SRGB; /* RGB, RGBA */
}
prec = has_prec(header_info.maxval);
if (prec < 8) {
prec = 8;
}
w = header_info.width;
h = header_info.height;
subsampling_dx = parameters->subsampling_dx;
subsampling_dy = parameters->subsampling_dy;
memset(&cmptparm[0], 0, (size_t)numcomps * sizeof(opj_image_cmptparm_t));
for (i = 0; i < numcomps; i++) {
cmptparm[i].prec = (OPJ_UINT32)prec;
cmptparm[i].bpp = (OPJ_UINT32)prec;
cmptparm[i].sgnd = 0;
cmptparm[i].dx = (OPJ_UINT32)subsampling_dx;
cmptparm[i].dy = (OPJ_UINT32)subsampling_dy;
cmptparm[i].w = (OPJ_UINT32)w;
cmptparm[i].h = (OPJ_UINT32)h;
}
image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
if (!image) {
fclose(fp);
return NULL;
}
/* set image offset and reference grid */
image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
image->x1 = (OPJ_UINT32)(parameters->image_offset_x0 + (w - 1) * subsampling_dx
+ 1);
image->y1 = (OPJ_UINT32)(parameters->image_offset_y0 + (h - 1) * subsampling_dy
+ 1);
if ((format == 2) || (format == 3)) { /* ascii pixmap */
unsigned int index;
for (i = 0; i < w * h; i++) {
for (compno = 0; compno < numcomps; compno++) {
index = 0;
if (fscanf(fp, "%u", &index) != 1) {
fprintf(stderr,
"\nWARNING: fscanf return a number of element different from the expected.\n");
}
image->comps[compno].data[i] = (OPJ_INT32)(index * 255) / header_info.maxval;
}
}
} else if ((format == 5)
|| (format == 6)
|| ((format == 7)
&& (header_info.gray || header_info.graya
|| header_info.rgb || header_info.rgba))) { /* binary pixmap */
unsigned char c0, c1, one;
one = (prec < 9);
for (i = 0; i < w * h; i++) {
for (compno = 0; compno < numcomps; compno++) {
if (!fread(&c0, 1, 1, fp)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(fp);
return NULL;
}
if (one) {
image->comps[compno].data[i] = c0;
} else {
if (!fread(&c1, 1, 1, fp)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
}
/* netpbm: */
image->comps[compno].data[i] = ((c0 << 8) | c1);
}
}
}
} else if (format == 1) { /* ascii bitmap */
for (i = 0; i < w * h; i++) {
unsigned int index;
if (fscanf(fp, "%u", &index) != 1) {
fprintf(stderr,
"\nWARNING: fscanf return a number of element different from the expected.\n");
}
image->comps[0].data[i] = (index ? 0 : 255);
}
} else if (format == 4) {
int x, y, bit;
unsigned char uc;
i = 0;
for (y = 0; y < h; ++y) {
bit = -1;
uc = 0;
for (x = 0; x < w; ++x) {
if (bit == -1) {
bit = 7;
uc = (unsigned char)getc(fp);
}
image->comps[0].data[i] = (((uc >> bit) & 1) ? 0 : 255);
--bit;
++i;
}
}
} else if ((format == 7 && header_info.bw)) { /*MONO*/
unsigned char uc;
for (i = 0; i < w * h; ++i) {
if (!fread(&uc, 1, 1, fp)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
}
image->comps[0].data[i] = (uc & 1) ? 0 : 255;
}
}
fclose(fp);
return image;
}/* pnmtoimage() */
static int are_comps_similar(opj_image_t * image)
{
unsigned int i;
for (i = 1; i < image->numcomps; i++) {
if (image->comps[0].dx != image->comps[i].dx ||
image->comps[0].dy != image->comps[i].dy ||
(i <= 2 &&
(image->comps[0].prec != image->comps[i].prec ||
image->comps[0].sgnd != image->comps[i].sgnd))) {
return OPJ_FALSE;
}
}
return OPJ_TRUE;
}
int imagetopnm(opj_image_t * image, const char *outfile, int force_split)
{
int *red, *green, *blue, *alpha;
int wr, hr, max;
int i;
unsigned int compno, ncomp;
int adjustR, adjustG, adjustB, adjustA;
int fails, two, want_gray, has_alpha, triple;
int prec, v;
FILE *fdest = NULL;
const char *tmp = outfile;
char *destname;
alpha = NULL;
if ((prec = (int)image->comps[0].prec) > 16) {
fprintf(stderr, "%s:%d:imagetopnm\n\tprecision %d is larger than 16"
"\n\t: refused.\n", __FILE__, __LINE__, prec);
return 1;
}
two = has_alpha = 0;
fails = 1;
ncomp = image->numcomps;
while (*tmp) {
++tmp;
}
tmp -= 2;
want_gray = (*tmp == 'g' || *tmp == 'G');
ncomp = image->numcomps;
if (want_gray) {
ncomp = 1;
}
if ((force_split == 0) && ncomp >= 2 &&
are_comps_similar(image)) {
fdest = fopen(outfile, "wb");
if (!fdest) {
fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
return fails;
}
two = (prec > 8);
triple = (ncomp > 2);
wr = (int)image->comps[0].w;
hr = (int)image->comps[0].h;
max = (1 << prec) - 1;
has_alpha = (ncomp == 4 || ncomp == 2);
red = image->comps[0].data;
if (triple) {
green = image->comps[1].data;
blue = image->comps[2].data;
} else {
green = blue = NULL;
}
if (has_alpha) {
const char *tt = (triple ? "RGB_ALPHA" : "GRAYSCALE_ALPHA");
fprintf(fdest, "P7\n# OpenJPEG-%s\nWIDTH %d\nHEIGHT %d\nDEPTH %u\n"
"MAXVAL %d\nTUPLTYPE %s\nENDHDR\n", opj_version(),
wr, hr, ncomp, max, tt);
alpha = image->comps[ncomp - 1].data;
adjustA = (image->comps[ncomp - 1].sgnd ?
1 << (image->comps[ncomp - 1].prec - 1) : 0);
} else {
fprintf(fdest, "P6\n# OpenJPEG-%s\n%d %d\n%d\n",
opj_version(), wr, hr, max);
adjustA = 0;
}
adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
if (triple) {
adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
} else {
adjustG = adjustB = 0;
}
for (i = 0; i < wr * hr; ++i) {
if (two) {
v = *red + adjustR;
++red;
if (v > 65535) {
v = 65535;
} else if (v < 0) {
v = 0;
}
/* netpbm: */
fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);
if (triple) {
v = *green + adjustG;
++green;
if (v > 65535) {
v = 65535;
} else if (v < 0) {
v = 0;
}
/* netpbm: */
fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);
v = *blue + adjustB;
++blue;
if (v > 65535) {
v = 65535;
} else if (v < 0) {
v = 0;
}
/* netpbm: */
fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);
}/* if(triple) */
if (has_alpha) {
v = *alpha + adjustA;
++alpha;
if (v > 65535) {
v = 65535;
} else if (v < 0) {
v = 0;
}
/* netpbm: */
fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);
}
continue;
} /* if(two) */
/* prec <= 8: */
v = *red++;
if (v > 255) {
v = 255;
} else if (v < 0) {
v = 0;
}
fprintf(fdest, "%c", (unsigned char)v);
if (triple) {
v = *green++;
if (v > 255) {
v = 255;
} else if (v < 0) {
v = 0;
}
fprintf(fdest, "%c", (unsigned char)v);
v = *blue++;
if (v > 255) {
v = 255;
} else if (v < 0) {
v = 0;
}
fprintf(fdest, "%c", (unsigned char)v);
}
if (has_alpha) {
v = *alpha++;
if (v > 255) {
v = 255;
} else if (v < 0) {
v = 0;
}
fprintf(fdest, "%c", (unsigned char)v);
}
} /* for(i */
fclose(fdest);
return 0;
}
/* YUV or MONO: */
if (image->numcomps > ncomp) {
fprintf(stderr, "WARNING -> [PGM file] Only the first component\n");
fprintf(stderr, " is written to the file\n");
}
destname = (char*)malloc(strlen(outfile) + 8);
if (destname == NULL) {
fprintf(stderr, "imagetopnm: memory out\n");
return 1;
}
for (compno = 0; compno < ncomp; compno++) {
if (ncomp > 1) {
/*sprintf(destname, "%d.%s", compno, outfile);*/
const size_t olen = strlen(outfile);
const size_t dotpos = olen - 4;
strncpy(destname, outfile, dotpos);
sprintf(destname + dotpos, "_%u.pgm", compno);
} else {
sprintf(destname, "%s", outfile);
}
fdest = fopen(destname, "wb");
if (!fdest) {
fprintf(stderr, "ERROR -> failed to open %s for writing\n", destname);
free(destname);
return 1;
}
wr = (int)image->comps[compno].w;
hr = (int)image->comps[compno].h;
prec = (int)image->comps[compno].prec;
max = (1 << prec) - 1;
fprintf(fdest, "P5\n#OpenJPEG-%s\n%d %d\n%d\n",
opj_version(), wr, hr, max);
red = image->comps[compno].data;
adjustR =
(image->comps[compno].sgnd ? 1 << (image->comps[compno].prec - 1) : 0);
if (prec > 8) {
for (i = 0; i < wr * hr; i++) {
v = *red + adjustR;
++red;
if (v > 65535) {
v = 65535;
} else if (v < 0) {
v = 0;
}
/* netpbm: */
fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);
if (has_alpha) {
v = *alpha++;
if (v > 65535) {
v = 65535;
} else if (v < 0) {
v = 0;
}
/* netpbm: */
fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);
}
}/* for(i */
} else { /* prec <= 8 */
for (i = 0; i < wr * hr; ++i) {
v = *red + adjustR;
++red;
if (v > 255) {
v = 255;
} else if (v < 0) {
v = 0;
}
fprintf(fdest, "%c", (unsigned char)v);
}
}
fclose(fdest);
} /* for (compno */
free(destname);
return 0;
}/* imagetopnm() */
/* -->> -->> -->> -->>
RAW IMAGE FORMAT
<<-- <<-- <<-- <<-- */
static opj_image_t* rawtoimage_common(const char *filename,
opj_cparameters_t *parameters, raw_cparameters_t *raw_cp, OPJ_BOOL big_endian)
{
int subsampling_dx = parameters->subsampling_dx;
int subsampling_dy = parameters->subsampling_dy;
FILE *f = NULL;
int i, compno, numcomps, w, h;
OPJ_COLOR_SPACE color_space;
opj_image_cmptparm_t *cmptparm;
opj_image_t * image = NULL;
unsigned short ch;
if ((!(raw_cp->rawWidth & raw_cp->rawHeight & raw_cp->rawComp &
raw_cp->rawBitDepth)) == 0) {
fprintf(stderr, "\nError: invalid raw image parameters\n");
fprintf(stderr, "Please use the Format option -F:\n");
fprintf(stderr,
"-F <width>,<height>,<ncomp>,<bitdepth>,{s,u}@<dx1>x<dy1>:...:<dxn>x<dyn>\n");
fprintf(stderr,
"If subsampling is omitted, 1x1 is assumed for all components\n");
fprintf(stderr,
"Example: -i image.raw -o image.j2k -F 512,512,3,8,u@1x1:2x2:2x2\n");
fprintf(stderr, " for raw 512x512 image with 4:2:0 subsampling\n");
fprintf(stderr, "Aborting.\n");
return NULL;
}
f = fopen(filename, "rb");
if (!f) {
fprintf(stderr, "Failed to open %s for reading !!\n", filename);
fprintf(stderr, "Aborting\n");
return NULL;
}
numcomps = raw_cp->rawComp;
/* FIXME ADE at this point, tcp_mct has not been properly set in calling function */
if (numcomps == 1) {
color_space = OPJ_CLRSPC_GRAY;
} else if ((numcomps >= 3) && (parameters->tcp_mct == 0)) {
color_space = OPJ_CLRSPC_SYCC;
} else if ((numcomps >= 3) && (parameters->tcp_mct != 2)) {
color_space = OPJ_CLRSPC_SRGB;
} else {
color_space = OPJ_CLRSPC_UNKNOWN;
}
w = raw_cp->rawWidth;
h = raw_cp->rawHeight;
cmptparm = (opj_image_cmptparm_t*) calloc((OPJ_UINT32)numcomps,
sizeof(opj_image_cmptparm_t));
if (!cmptparm) {
fprintf(stderr, "Failed to allocate image components parameters !!\n");
fprintf(stderr, "Aborting\n");
fclose(f);
return NULL;
}
/* initialize image components */
for (i = 0; i < numcomps; i++) {
cmptparm[i].prec = (OPJ_UINT32)raw_cp->rawBitDepth;
cmptparm[i].bpp = (OPJ_UINT32)raw_cp->rawBitDepth;
cmptparm[i].sgnd = (OPJ_UINT32)raw_cp->rawSigned;
cmptparm[i].dx = (OPJ_UINT32)(subsampling_dx * raw_cp->rawComps[i].dx);
cmptparm[i].dy = (OPJ_UINT32)(subsampling_dy * raw_cp->rawComps[i].dy);
cmptparm[i].w = (OPJ_UINT32)w;
cmptparm[i].h = (OPJ_UINT32)h;
}
/* create the image */
image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
free(cmptparm);
if (!image) {
fclose(f);
return NULL;
}
/* set image offset and reference grid */
image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
image->x1 = (OPJ_UINT32)parameters->image_offset_x0 + (OPJ_UINT32)(w - 1) *
(OPJ_UINT32)subsampling_dx + 1;
image->y1 = (OPJ_UINT32)parameters->image_offset_y0 + (OPJ_UINT32)(h - 1) *
(OPJ_UINT32)subsampling_dy + 1;
if (raw_cp->rawBitDepth <= 8) {
unsigned char value = 0;
for (compno = 0; compno < numcomps; compno++) {
int nloop = (w * h) / (raw_cp->rawComps[compno].dx *
raw_cp->rawComps[compno].dy);
for (i = 0; i < nloop; i++) {
if (!fread(&value, 1, 1, f)) {
fprintf(stderr, "Error reading raw file. End of file probably reached.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
image->comps[compno].data[i] = raw_cp->rawSigned ? (char)value : value;
}
}
} else if (raw_cp->rawBitDepth <= 16) {
unsigned short value;
for (compno = 0; compno < numcomps; compno++) {
int nloop = (w * h) / (raw_cp->rawComps[compno].dx *
raw_cp->rawComps[compno].dy);
for (i = 0; i < nloop; i++) {
unsigned char temp1;
unsigned char temp2;
if (!fread(&temp1, 1, 1, f)) {
fprintf(stderr, "Error reading raw file. End of file probably reached.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&temp2, 1, 1, f)) {
fprintf(stderr, "Error reading raw file. End of file probably reached.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (big_endian) {
value = (unsigned short)((temp1 << 8) + temp2);
} else {
value = (unsigned short)((temp2 << 8) + temp1);
}
image->comps[compno].data[i] = raw_cp->rawSigned ? (short)value : value;
}
}
} else {
fprintf(stderr,
"OpenJPEG cannot encode raw components with bit depth higher than 16 bits.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (fread(&ch, 1, 1, f)) {
fprintf(stderr, "Warning. End of raw file not reached... processing anyway\n");
}
fclose(f);
return image;
}
opj_image_t* rawltoimage(const char *filename, opj_cparameters_t *parameters,
raw_cparameters_t *raw_cp)
{
return rawtoimage_common(filename, parameters, raw_cp, OPJ_FALSE);
}
opj_image_t* rawtoimage(const char *filename, opj_cparameters_t *parameters,
raw_cparameters_t *raw_cp)
{
return rawtoimage_common(filename, parameters, raw_cp, OPJ_TRUE);
}
static int imagetoraw_common(opj_image_t * image, const char *outfile,
OPJ_BOOL big_endian)
{
FILE *rawFile = NULL;
size_t res;
unsigned int compno, numcomps;
int w, h, fails;
int line, row, curr, mask;
int *ptr;
unsigned char uc;
(void)big_endian;
if ((image->numcomps * image->x1 * image->y1) == 0) {
fprintf(stderr, "\nError: invalid raw image parameters\n");
return 1;
}
numcomps = image->numcomps;
if (numcomps > 4) {
numcomps = 4;
}
for (compno = 1; compno < numcomps; ++compno) {
if (image->comps[0].dx != image->comps[compno].dx) {
break;
}
if (image->comps[0].dy != image->comps[compno].dy) {
break;
}
if (image->comps[0].prec != image->comps[compno].prec) {
break;
}
if (image->comps[0].sgnd != image->comps[compno].sgnd) {
break;
}
}
if (compno != numcomps) {
fprintf(stderr,
"imagetoraw_common: All components shall have the same subsampling, same bit depth, same sign.\n");
fprintf(stderr, "\tAborting\n");
return 1;
}
rawFile = fopen(outfile, "wb");
if (!rawFile) {
fprintf(stderr, "Failed to open %s for writing !!\n", outfile);
return 1;
}
fails = 1;
fprintf(stdout, "Raw image characteristics: %d components\n", image->numcomps);
for (compno = 0; compno < image->numcomps; compno++) {
fprintf(stdout, "Component %u characteristics: %dx%dx%d %s\n", compno,
image->comps[compno].w,
image->comps[compno].h, image->comps[compno].prec,
image->comps[compno].sgnd == 1 ? "signed" : "unsigned");
w = (int)image->comps[compno].w;
h = (int)image->comps[compno].h;
if (image->comps[compno].prec <= 8) {
if (image->comps[compno].sgnd == 1) {
mask = (1 << image->comps[compno].prec) - 1;
ptr = image->comps[compno].data;
for (line = 0; line < h; line++) {
for (row = 0; row < w; row++) {
curr = *ptr;
if (curr > 127) {
curr = 127;
} else if (curr < -128) {
curr = -128;
}
uc = (unsigned char)(curr & mask);
res = fwrite(&uc, 1, 1, rawFile);
if (res < 1) {
fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
goto fin;
}
ptr++;
}
}
} else if (image->comps[compno].sgnd == 0) {
mask = (1 << image->comps[compno].prec) - 1;
ptr = image->comps[compno].data;
for (line = 0; line < h; line++) {
for (row = 0; row < w; row++) {
curr = *ptr;
if (curr > 255) {
curr = 255;
} else if (curr < 0) {
curr = 0;
}
uc = (unsigned char)(curr & mask);
res = fwrite(&uc, 1, 1, rawFile);
if (res < 1) {
fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
goto fin;
}
ptr++;
}
}
}
} else if (image->comps[compno].prec <= 16) {
if (image->comps[compno].sgnd == 1) {
union {
signed short val;
signed char vals[2];
} uc16;
mask = (1 << image->comps[compno].prec) - 1;
ptr = image->comps[compno].data;
for (line = 0; line < h; line++) {
for (row = 0; row < w; row++) {
curr = *ptr;
if (curr > 32767) {
curr = 32767;
} else if (curr < -32768) {
curr = -32768;
}
uc16.val = (signed short)(curr & mask);
res = fwrite(uc16.vals, 1, 2, rawFile);
if (res < 2) {
fprintf(stderr, "failed to write 2 byte for %s\n", outfile);
goto fin;
}
ptr++;
}
}
} else if (image->comps[compno].sgnd == 0) {
union {
unsigned short val;
unsigned char vals[2];
} uc16;
mask = (1 << image->comps[compno].prec) - 1;
ptr = image->comps[compno].data;
for (line = 0; line < h; line++) {
for (row = 0; row < w; row++) {
curr = *ptr;
if (curr > 65535) {
curr = 65535;
} else if (curr < 0) {
curr = 0;
}
uc16.val = (unsigned short)(curr & mask);
res = fwrite(uc16.vals, 1, 2, rawFile);
if (res < 2) {
fprintf(stderr, "failed to write 2 byte for %s\n", outfile);
goto fin;
}
ptr++;
}
}
}
} else if (image->comps[compno].prec <= 32) {
fprintf(stderr, "More than 16 bits per component not handled yet\n");
goto fin;
} else {
fprintf(stderr, "Error: invalid precision: %d\n", image->comps[compno].prec);
goto fin;
}
}
fails = 0;
fin:
fclose(rawFile);
return fails;
}
int imagetoraw(opj_image_t * image, const char *outfile)
{
return imagetoraw_common(image, outfile, OPJ_TRUE);
}
int imagetorawl(opj_image_t * image, const char *outfile)
{
return imagetoraw_common(image, outfile, OPJ_FALSE);
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_2759_0 |
crossvul-cpp_data_good_3368_1 | // imagew-main.c
// Part of ImageWorsener, Copyright (c) 2011 by Jason Summers.
// For more information, see the readme.txt file.
#include "imagew-config.h"
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "imagew-internals.h"
// Given a color type having an alpha channel, returns the index of the
// alpha channel.
// Return value is not meaningful if type does not have an alpha channel.
static int iw_imgtype_alpha_channel_index(int t)
{
switch(t) {
case IW_IMGTYPE_RGBA:
return 3;
case IW_IMGTYPE_GRAYA:
return 1;
}
return 0;
}
static IW_INLINE iw_tmpsample srgb_to_linear_sample(iw_tmpsample v_srgb)
{
if(v_srgb<=0.04045) {
return v_srgb/12.92;
}
else {
return pow( (v_srgb+0.055)/(1.055) , 2.4);
}
}
static IW_INLINE iw_tmpsample rec709_to_linear_sample(iw_tmpsample v_rec709)
{
if(v_rec709 < 4.5*0.020) {
return v_rec709/4.5;
}
else {
return pow( (v_rec709+0.099)/1.099 , 1.0/0.45);
}
}
static IW_INLINE iw_tmpsample gamma_to_linear_sample(iw_tmpsample v, double gamma)
{
return pow(v,gamma);
}
static iw_tmpsample x_to_linear_sample(iw_tmpsample v, const struct iw_csdescr *csdescr)
{
switch(csdescr->cstype) {
case IW_CSTYPE_SRGB:
return srgb_to_linear_sample(v);
case IW_CSTYPE_LINEAR:
return v;
case IW_CSTYPE_GAMMA:
return gamma_to_linear_sample(v,csdescr->gamma);
case IW_CSTYPE_REC709:
return rec709_to_linear_sample(v);
}
return srgb_to_linear_sample(v);
}
// Public version of x_to_linear_sample().
IW_IMPL(double) iw_convert_sample_to_linear(double v, const struct iw_csdescr *csdescr)
{
return (double)x_to_linear_sample(v,csdescr);
}
static IW_INLINE iw_tmpsample linear_to_srgb_sample(iw_tmpsample v_linear)
{
if(v_linear <= 0.0031308) {
return 12.92*v_linear;
}
return 1.055*pow(v_linear,1.0/2.4) - 0.055;
}
static IW_INLINE iw_tmpsample linear_to_rec709_sample(iw_tmpsample v_linear)
{
// The cutoff point is supposed to be 0.018, but that doesn't make sense,
// because the curves don't intersect there. They intersect at almost exactly
// 0.020.
if(v_linear < 0.020) {
return 4.5*v_linear;
}
return 1.099*pow(v_linear,0.45) - 0.099;
}
static IW_INLINE iw_tmpsample linear_to_gamma_sample(iw_tmpsample v_linear, double gamma)
{
return pow(v_linear,1.0/gamma);
}
static iw_float32 iw_get_float32(const iw_byte *m)
{
int k;
// !!! Portability warning: Using a union in this way may be nonportable.
union su_union {
iw_byte c[4];
iw_float32 f;
} volatile su;
for(k=0;k<4;k++) {
su.c[k] = m[k];
}
return su.f;
}
static void iw_put_float32(iw_byte *m, iw_float32 s)
{
int k;
// !!! Portability warning: Using a union in this way may be nonportable.
union su_union {
iw_byte c[4];
iw_float32 f;
} volatile su;
su.f = s;
for(k=0;k<4;k++) {
m[k] = su.c[k];
}
}
static iw_tmpsample get_raw_sample_flt32(struct iw_context *ctx,
int x, int y, int channel)
{
size_t z;
z = y*ctx->img1.bpr + (ctx->img1_numchannels_physical*x + channel)*4;
return (iw_tmpsample)iw_get_float32(&ctx->img1.pixels[z]);
}
static IW_INLINE unsigned int get_raw_sample_16(struct iw_context *ctx,
int x, int y, int channel)
{
size_t z;
unsigned short tmpui16;
z = y*ctx->img1.bpr + (ctx->img1_numchannels_physical*x + channel)*2;
tmpui16 = ( ((unsigned short)(ctx->img1.pixels[z+0])) <<8) | ctx->img1.pixels[z+1];
return tmpui16;
}
static IW_INLINE unsigned int get_raw_sample_8(struct iw_context *ctx,
int x, int y, int channel)
{
unsigned short tmpui8;
tmpui8 = ctx->img1.pixels[y*ctx->img1.bpr + ctx->img1_numchannels_physical*x + channel];
return tmpui8;
}
// 4 bits/pixel
static IW_INLINE unsigned int get_raw_sample_4(struct iw_context *ctx,
int x, int y)
{
unsigned short tmpui8;
tmpui8 = ctx->img1.pixels[y*ctx->img1.bpr + x/2];
if(x&0x1)
tmpui8 = tmpui8&0x0f;
else
tmpui8 = tmpui8>>4;
return tmpui8;
}
// 2 bits/pixel
static IW_INLINE unsigned int get_raw_sample_2(struct iw_context *ctx,
int x, int y)
{
unsigned short tmpui8;
tmpui8 = ctx->img1.pixels[y*ctx->img1.bpr + x/4];
tmpui8 = ( tmpui8 >> ((3-x%4)*2) ) & 0x03;
return tmpui8;
}
// 1 bit/pixel
static IW_INLINE unsigned int get_raw_sample_1(struct iw_context *ctx,
int x, int y)
{
unsigned short tmpui8;
tmpui8 = ctx->img1.pixels[y*ctx->img1.bpr + x/8];
if(tmpui8 & (1<<(7-x%8))) return 1;
return 0;
}
// Translate a pixel position from logical to physical coordinates.
static IW_INLINE void translate_coords(struct iw_context *ctx,
int x, int y, int *prx, int *pry)
{
if(ctx->img1.orient_transform==0) {
// The fast path
*prx = ctx->input_start_x+x;
*pry = ctx->input_start_y+y;
return;
}
switch(ctx->img1.orient_transform) {
case 1: // mirror-x
*prx = ctx->img1.width - 1 - (ctx->input_start_x+x);
*pry = ctx->input_start_y+y;
break;
case 2: // mirror-y
*prx = ctx->input_start_x+x;
*pry = ctx->img1.height - 1 - (ctx->input_start_y+y);
break;
case 3: // mirror-x, mirror-y
*prx = ctx->img1.width - 1 - (ctx->input_start_x+x);
*pry = ctx->img1.height - 1 - (ctx->input_start_y+y);
break;
case 4:
// transpose
*prx = ctx->input_start_y+y;
*pry = ctx->input_start_x+x;
break;
case 5:
*prx = ctx->input_start_y+y;
*pry = ctx->img1.width - 1 - (ctx->input_start_x+x);
break;
case 6:
*prx = ctx->img1.height - 1 - (ctx->input_start_y+y);
*pry = ctx->input_start_x+x;
break;
case 7:
*prx = ctx->img1.height - 1 - (ctx->input_start_y+y);
*pry = ctx->img1.width - 1 - (ctx->input_start_x+x);
break;
default:
*prx = 0;
*pry = 0;
break;
}
}
// Returns a value from 0 to 2^(ctx->img1.bit_depth)-1.
// x and y are logical coordinates.
static unsigned int get_raw_sample_int(struct iw_context *ctx,
int x, int y, int channel)
{
int rx,ry; // physical coordinates
translate_coords(ctx,x,y,&rx,&ry);
switch(ctx->img1.bit_depth) {
case 8: return get_raw_sample_8(ctx,rx,ry,channel);
case 1: return get_raw_sample_1(ctx,rx,ry);
case 16: return get_raw_sample_16(ctx,rx,ry,channel);
case 4: return get_raw_sample_4(ctx,rx,ry);
case 2: return get_raw_sample_2(ctx,rx,ry);
}
return 0;
}
// Channel is the input channel number.
// x and y are logical coordinates.
static iw_tmpsample get_raw_sample(struct iw_context *ctx,
int x, int y, int channel)
{
unsigned int v;
if(channel>=ctx->img1_numchannels_physical) {
// This is a virtual alpha channel. Return "opaque".
return 1.0;
}
if(ctx->img1.sampletype==IW_SAMPLETYPE_FLOATINGPOINT) {
int rx, ry;
translate_coords(ctx,x,y,&rx,&ry);
if(ctx->img1.bit_depth!=32) return 0.0;
return get_raw_sample_flt32(ctx,rx,ry,channel);
}
v = get_raw_sample_int(ctx,x,y,channel);
return ((double)v) / ctx->img1_ci[channel].maxcolorcode_dbl;
}
static iw_tmpsample iw_color_to_grayscale(struct iw_context *ctx,
iw_tmpsample r, iw_tmpsample g, iw_tmpsample b)
{
iw_tmpsample v0,v1,v2;
switch(ctx->grayscale_formula) {
case IW_GSF_WEIGHTED:
return ctx->grayscale_weight[0]*r +
ctx->grayscale_weight[1]*g +
ctx->grayscale_weight[2]*b;
case IW_GSF_ORDERBYVALUE:
// Sort the R, G, and B values, then use the corresponding weights.
if(g<=r) { v0=r; v1=g; }
else { v0=g; v1=r; }
if(b<=v1) {
v2=b;
}
else {
v2=v1;
if(b<=v0) { v1=b; }
else { v1=v0; v0=b; }
}
return ctx->grayscale_weight[0]*v0 +
ctx->grayscale_weight[1]*v1 +
ctx->grayscale_weight[2]*v2;
}
return 0.0;
}
// Based on color depth of the input image.
// Assumes this channel's maxcolorcode == ctx->input_maxcolorcode
static iw_tmpsample cvt_int_sample_to_linear(struct iw_context *ctx,
unsigned int v, const struct iw_csdescr *csdescr)
{
iw_tmpsample s;
if(csdescr->cstype==IW_CSTYPE_LINEAR) {
// Sort of a hack: This is not just an optimization for linear colorspaces,
// but is necessary to handle alpha channels correctly.
// The lookup table is not correct for alpha channels.
return ((double)v) / ctx->input_maxcolorcode;
}
else if(ctx->input_color_corr_table) {
// If the colorspace is not linear, assume we can use the lookup table.
return ctx->input_color_corr_table[v];
}
s = ((double)v) / ctx->input_maxcolorcode;
return x_to_linear_sample(s,csdescr);
}
// Based on color depth of the output image.
static iw_tmpsample cvt_int_sample_to_linear_output(struct iw_context *ctx,
unsigned int v, const struct iw_csdescr *csdescr, double overall_maxcolorcode)
{
iw_tmpsample s;
if(csdescr->cstype==IW_CSTYPE_LINEAR) {
return ((double)v) / overall_maxcolorcode;
}
else if(ctx->output_rev_color_corr_table) {
return ctx->output_rev_color_corr_table[v];
}
s = ((double)v) / overall_maxcolorcode;
return x_to_linear_sample(s,csdescr);
}
// Return a sample, converted to a linear colorspace if it isn't already in one.
// Channel is the output channel number.
static iw_tmpsample get_sample_cvt_to_linear(struct iw_context *ctx,
int x, int y, int channel, const struct iw_csdescr *csdescr)
{
unsigned int v1,v2,v3;
iw_tmpsample r,g,b;
int ch;
ch = ctx->intermed_ci[channel].corresponding_input_channel;
if(ctx->img1_ci[ch].disable_fast_get_sample) {
// The slow way...
if(ctx->intermed_ci[channel].cvt_to_grayscale) {
r = x_to_linear_sample(get_raw_sample(ctx,x,y,ch+0),csdescr);
g = x_to_linear_sample(get_raw_sample(ctx,x,y,ch+1),csdescr);
b = x_to_linear_sample(get_raw_sample(ctx,x,y,ch+2),csdescr);
return iw_color_to_grayscale(ctx,r,g,b);
}
return x_to_linear_sample(get_raw_sample(ctx,x,y,ch),csdescr);
}
// This method is faster, because it may use a gamma lookup table.
// But all channels have to have the nominal input bitdepth, and it doesn't
// support floating point samples, or a virtual alpha channel.
if(ctx->intermed_ci[channel].cvt_to_grayscale) {
v1 = get_raw_sample_int(ctx,x,y,ch+0);
v2 = get_raw_sample_int(ctx,x,y,ch+1);
v3 = get_raw_sample_int(ctx,x,y,ch+2);
r = cvt_int_sample_to_linear(ctx,v1,csdescr);
g = cvt_int_sample_to_linear(ctx,v2,csdescr);
b = cvt_int_sample_to_linear(ctx,v3,csdescr);
return iw_color_to_grayscale(ctx,r,g,b);
}
v1 = get_raw_sample_int(ctx,x,y,ch);
return cvt_int_sample_to_linear(ctx,v1,csdescr);
}
// s is from 0.0 to 65535.0
static IW_INLINE void put_raw_sample_16(struct iw_context *ctx, double s,
int x, int y, int channel)
{
size_t z;
unsigned short tmpui16;
tmpui16 = (unsigned short)(0.5+s);
z = y*ctx->img2.bpr + (ctx->img2_numchannels*x + channel)*2;
ctx->img2.pixels[z+0] = (iw_byte)(tmpui16>>8);
ctx->img2.pixels[z+1] = (iw_byte)(tmpui16&0xff);
}
// s is from 0.0 to 255.0
static IW_INLINE void put_raw_sample_8(struct iw_context *ctx, double s,
int x, int y, int channel)
{
iw_byte tmpui8;
tmpui8 = (iw_byte)(0.5+s);
ctx->img2.pixels[y*ctx->img2.bpr + ctx->img2_numchannels*x + channel] = tmpui8;
}
// Sample must already be scaled and in the target colorspace. E.g. 255.0 might be white.
static void put_raw_sample(struct iw_context *ctx, double s,
int x, int y, int channel)
{
switch(ctx->img2.bit_depth) {
case 8: put_raw_sample_8(ctx,s,x,y,channel); break;
case 16: put_raw_sample_16(ctx,s,x,y,channel); break;
}
}
// s is from 0.0 to 1.0
static void put_raw_sample_flt32(struct iw_context *ctx, double s,
int x, int y, int channel)
{
size_t pos;
pos = y*ctx->img2.bpr + (ctx->img2_numchannels*x + channel)*4;
iw_put_float32(&ctx->img2.pixels[pos], (iw_float32)s);
}
static iw_tmpsample linear_to_x_sample(iw_tmpsample samp_lin, const struct iw_csdescr *csdescr)
{
if(samp_lin > 0.999999999) {
// This check is done mostly because glibc's pow() function may be
// very slow for some arguments near 1.
return 1.0;
}
switch(csdescr->cstype) {
case IW_CSTYPE_SRGB:
return linear_to_srgb_sample(samp_lin);
case IW_CSTYPE_LINEAR:
return samp_lin;
case IW_CSTYPE_GAMMA:
return linear_to_gamma_sample(samp_lin,csdescr->gamma);
case IW_CSTYPE_REC709:
return linear_to_rec709_sample(samp_lin);
}
return linear_to_srgb_sample(samp_lin);
}
// Public version of linear_to_x_sample().
IW_IMPL(double) iw_convert_sample_from_linear(double v, const struct iw_csdescr *csdescr)
{
return (double)linear_to_x_sample(v,csdescr);
}
// Returns 0 if we should round down, 1 if we should round up.
// TODO: It might be good to use a different-sized matrix for alpha channels
// (e.g. 9x7), but I don't know how to make a good one.
static int iw_ordered_dither(int dithersubtype, double fraction, int x, int y)
{
double threshold;
static const float pattern[2][64] = {
{ // Dispersed ordered dither
0.5/64,48.5/64,12.5/64,60.5/64, 3.5/64,51.5/64,15.5/64,63.5/64,
32.5/64,16.5/64,44.5/64,28.5/64,35.5/64,19.5/64,47.5/64,31.5/64,
8.5/64,56.5/64, 4.5/64,52.5/64,11.5/64,59.5/64, 7.5/64,55.5/64,
40.5/64,24.5/64,36.5/64,20.5/64,43.5/64,27.5/64,39.5/64,23.5/64,
2.5/64,50.5/64,14.5/64,62.5/64, 1.5/64,49.5/64,13.5/64,61.5/64,
34.5/64,18.5/64,46.5/64,30.5/64,33.5/64,17.5/64,45.5/64,29.5/64,
10.5/64,58.5/64, 6.5/64,54.5/64, 9.5/64,57.5/64, 5.5/64,53.5/64,
42.5/64,26.5/64,38.5/64,22.5/64,41.5/64,25.5/64,37.5/64,21.5/64
},
{ // Halftone ordered dither
3.5/64, 9.5/64,17.5/64,27.5/64,25.5/64,15.5/64, 7.5/64, 1.5/64,
11.5/64,29.5/64,37.5/64,45.5/64,43.5/64,35.5/64,23.5/64, 5.5/64,
19.5/64,39.5/64,51.5/64,57.5/64,55.5/64,49.5/64,33.5/64,13.5/64,
31.5/64,47.5/64,59.5/64,63.5/64,61.5/64,53.5/64,41.5/64,21.5/64,
30.5/64,46.5/64,58.5/64,62.5/64,60.5/64,52.5/64,40.5/64,20.5/64,
18.5/64,38.5/64,50.5/64,56.5/64,54.5/64,48.5/64,32.5/64,12.5/64,
10.5/64,28.5/64,36.5/64,44.5/64,42.5/64,34.5/64,22.5/64, 4.5/64,
2.5/64, 8.5/64,16.5/64,26.5/64,24.5/64,14.5/64, 6.5/64, 0.5/64
}};
threshold = pattern[dithersubtype][(x%8) + 8*(y%8)];
return (fraction >= threshold);
}
// Returns 0 if we should round down, 1 if we should round up.
static int iw_random_dither(struct iw_context *ctx, double fraction, int x, int y,
int dithersubtype, int channel)
{
double threshold;
threshold = ((double)iwpvt_prng_rand(ctx->prng)) / (double)0xffffffff;
if(fraction>=threshold) return 1;
return 0;
}
static void iw_errdiff_dither(struct iw_context *ctx,int dithersubtype,
double err,int x,int y)
{
int fwd;
const double *m;
// x 0 1
// 2 3 4 5 6
// 7 8 9 10 11
static const double matrix_list[][12] = {
{ 7.0/16, 0.0, // 0 = Floyd-Steinberg
0.0 , 3.0/16, 5.0/16, 1.0/16, 0.0,
0.0 , 0.0, 0.0, 0.0 , 0.0 },
{ 7.0/48, 5.0/48, // 1 = JJN
3.0/48, 5.0/48, 7.0/48, 5.0/48, 3.0/48,
1.0/48, 3.0/48, 5.0/48, 3.0/48, 1.0/48 },
{ 8.0/42, 4.0/42, // 2 = Stucki
2.0/42, 4.0/42, 8.0/42, 4.0/42, 2.0/42,
1.0/42, 2.0/42, 4.0/42, 2.0/42, 1.0/42 },
{ 8.0/32, 4.0/32, // 3 = Burkes
2.0/32, 4.0/32, 8.0/32, 4.0/32, 2.0/32,
0.0 , 0.0 , 0.0 , 0.0 , 0.0 },
{ 5.0/32, 3.0/32, // 4 = Sierra3
2.0/32, 4.0/32, 5.0/32, 4.0/32, 2.0/32,
0.0, 2.0/32, 3.0/32, 2.0/32, 0.0 },
{ 4.0/16, 3.0/16, // 5 = Sierra2
1.0/16, 2.0/16, 3.0/16, 2.0/16, 1.0/16,
0.0 , 0.0 , 0.0 , 0.0 , 0.0 },
{ 2.0/4 , 0.0, // 6 = Sierra42a
0.0 , 1.0/4 , 1.0/4 , 0.0 , 0.0,
0.0 , 0.0 , 0.0 , 0.0 , 0.0 },
{ 1.0/8 , 1.0/8, // 7 = Atkinson
0.0 , 1.0/8 , 1.0/8 , 1.0/8 , 0.0,
0.0 , 0.0 , 1.0/8 , 0.0 , 0.0 }
};
if(dithersubtype<=7)
m = matrix_list[dithersubtype];
else
m = matrix_list[0];
fwd = (y%2)?(-1):1;
if((x-fwd)>=0 && (x-fwd)<ctx->img2.width) {
if((x-2*fwd)>=0 && (x-2*fwd)<ctx->img2.width) {
ctx->dither_errors[1][x-2*fwd] += err*(m[2]);
ctx->dither_errors[2][x-2*fwd] += err*(m[7]);
}
ctx->dither_errors[1][x-fwd] += err*(m[3]);
ctx->dither_errors[2][x-fwd] += err*(m[8]);
}
ctx->dither_errors[1][x] += err*(m[4]);
ctx->dither_errors[2][x] += err*(m[9]);
if((x+fwd)>=0 && (x+fwd)<ctx->img2.width) {
ctx->dither_errors[0][x+fwd] += err*(m[0]);
ctx->dither_errors[1][x+fwd] += err*(m[5]);
ctx->dither_errors[2][x+fwd] += err*(m[10]);
if((x+2*fwd)>=0 && (x+2*fwd)<ctx->img2.width) {
ctx->dither_errors[0][x+2*fwd] += err*(m[1]);
ctx->dither_errors[1][x+2*fwd] += err*(m[6]);
ctx->dither_errors[2][x+2*fwd] += err*(m[11]);
}
}
}
// 'channel' is the output channel.
static int get_nearest_valid_colors(struct iw_context *ctx, iw_tmpsample samp_lin,
const struct iw_csdescr *csdescr,
double *s_lin_floor_1, double *s_lin_ceil_1,
double *s_cvt_floor_full, double *s_cvt_ceil_full,
double overall_maxcolorcode, int color_count)
{
iw_tmpsample samp_cvt;
double samp_cvt_expanded;
unsigned int floor_int, ceil_int;
// A prelimary conversion to the target color space.
samp_cvt = linear_to_x_sample(samp_lin,csdescr);
if(color_count==0) {
// The normal case: we want to use this channel's full available depth.
samp_cvt_expanded = samp_cvt * overall_maxcolorcode;
if(samp_cvt_expanded>overall_maxcolorcode) samp_cvt_expanded=overall_maxcolorcode;
if(samp_cvt_expanded<0.0) samp_cvt_expanded=0.0;
// Find the next-smallest and next-largest valid values that
// can be stored in this image.
// We will use one of them, but in order to figure out *which* one,
// we have to compare their distances in the *linear* color space.
*s_cvt_floor_full = floor(samp_cvt_expanded);
*s_cvt_ceil_full = ceil(samp_cvt_expanded);
}
else {
// We're "posterizing": restricting to a certain number of color shades.
double posterized_maxcolorcode;
// Example: color_count = 4, bit_depth = 8;
// Colors are from 0.0 to 3.0, mapped to 0.0 to 255.0.
// Reduction factor is 255.0/3.0 = 85.0
posterized_maxcolorcode = (double)(color_count-1);
samp_cvt_expanded = samp_cvt * posterized_maxcolorcode;
if(samp_cvt_expanded>posterized_maxcolorcode) samp_cvt_expanded=posterized_maxcolorcode;
if(samp_cvt_expanded<0.0) samp_cvt_expanded=0.0;
// If the number of shades is not 2, 4, 6, 16, 18, 52, 86, or 256 (assuming 8-bit depth),
// then the shades will not be exactly evenly spaced. For example, if there are 3 shades,
// they will be 0, 128, and 255. It will often be the case that the shade we want is exactly
// halfway between the nearest two available shades, and the "0.5000000001" fudge factor is my
// attempt to make sure it rounds consistently in the same direction.
*s_cvt_floor_full = floor(0.5000000001 + floor(samp_cvt_expanded) * (overall_maxcolorcode/posterized_maxcolorcode));
*s_cvt_ceil_full = floor(0.5000000001 + ceil (samp_cvt_expanded) * (overall_maxcolorcode/posterized_maxcolorcode));
}
floor_int = (unsigned int)(*s_cvt_floor_full);
ceil_int = (unsigned int)(*s_cvt_ceil_full);
if(floor_int == ceil_int) {
return 1;
}
// Convert the candidates to our linear color space
*s_lin_floor_1 = cvt_int_sample_to_linear_output(ctx,floor_int,csdescr,overall_maxcolorcode);
*s_lin_ceil_1 = cvt_int_sample_to_linear_output(ctx,ceil_int ,csdescr,overall_maxcolorcode);
return 0;
}
// channel is the output channel
static void put_sample_convert_from_linear_flt(struct iw_context *ctx, iw_tmpsample samp_lin,
int x, int y, int channel, const struct iw_csdescr *csdescr)
{
put_raw_sample_flt32(ctx,(double)samp_lin,x,y,channel);
}
static double get_final_sample_using_nc_tbl(struct iw_context *ctx, iw_tmpsample samp_lin)
{
unsigned int x;
unsigned int d;
// For numbers 0 through 254, find the smallest one for which the
// corresponding table value is larger than samp_lin.
// Do a binary search.
x = 127;
d = 64;
while(1) {
if(x>254 || ctx->nearest_color_table[x] > samp_lin)
x -= d;
else
x += d;
if(d==1) {
if(x>254 || ctx->nearest_color_table[x] > samp_lin)
return (double)(x);
else
return (double)(x+1);
}
d = d/2;
}
}
// channel is the output channel
static void put_sample_convert_from_linear(struct iw_context *ctx, iw_tmpsample samp_lin,
int x, int y, int channel, const struct iw_csdescr *csdescr)
{
double s_lin_floor_1, s_lin_ceil_1;
double s_cvt_floor_full, s_cvt_ceil_full;
double d_floor, d_ceil;
int is_exact;
double s_full;
int ditherfamily;
int dd; // Dither decision: 0 to use floor, 1 to use ceil.
// Clamp to the [0.0,1.0] range.
// The sample type is UINT, so out-of-range samples can't be represented.
// TODO: I think that out-of-range samples could still have a meaningful
// effect if we are dithering. More investigation is needed here.
if(samp_lin<0.0) samp_lin=0.0;
if(samp_lin>1.0) samp_lin=1.0;
// TODO: This is getting messy. The conditions under which we use lookup
// tables are too complicated, and we still don't use them as often as we
// should. For example, if we are not dithering, we can use a table optimized
// for telling us the single nearest color. But if we are dithering, then we
// instead need to know both the next-highest and next-lowest colors, which
// would require a different table. The same table could be used for both,
// but not quite as efficiently. Currently, we don't use use a lookup table
// when dithering, except that we may still use one to do some of the
// intermediate computations. Etc.
if(ctx->img2_ci[channel].use_nearest_color_table) {
s_full = get_final_sample_using_nc_tbl(ctx,samp_lin);
goto okay;
}
ditherfamily=ctx->img2_ci[channel].ditherfamily;
if(ditherfamily==IW_DITHERFAMILY_ERRDIFF) {
samp_lin += ctx->dither_errors[0][x];
// If the prior error makes the ideal brightness out of the available range,
// just throw away any extra.
if(samp_lin>1.0) samp_lin=1.0;
else if(samp_lin<0.0) samp_lin=0.0;
}
is_exact = get_nearest_valid_colors(ctx,samp_lin,csdescr,
&s_lin_floor_1, &s_lin_ceil_1,
&s_cvt_floor_full, &s_cvt_ceil_full,
ctx->img2_ci[channel].maxcolorcode_dbl, ctx->img2_ci[channel].color_count);
if(is_exact) {
s_full = s_cvt_floor_full;
// Hack to keep the PRNG in sync. We have to generate exactly one random
// number per sample, regardless of whether we use it.
if(ditherfamily==IW_DITHERFAMILY_RANDOM) {
(void)iwpvt_prng_rand(ctx->prng);
}
goto okay;
}
// samp_lin should be between s_lin_floor_1 and s_lin_ceil_1. Figure out
// which is closer, and use the final pixel value we figured out earlier
// (either s_cvt_floor_full or s_cvt_ceil_full).
d_floor = samp_lin-s_lin_floor_1;
d_ceil = s_lin_ceil_1-samp_lin;
if(ditherfamily==IW_DITHERFAMILY_NONE) {
// Not dithering. Just choose closest value.
if(d_ceil<=d_floor) s_full=s_cvt_ceil_full;
else s_full=s_cvt_floor_full;
}
else if(ditherfamily==IW_DITHERFAMILY_ERRDIFF) {
if(d_ceil<=d_floor) {
// Ceiling is closer. This pixel will be lighter than ideal.
// so the error is negative, to make other pixels darker.
iw_errdiff_dither(ctx,ctx->img2_ci[channel].dithersubtype,-d_ceil,x,y);
s_full=s_cvt_ceil_full;
}
else {
iw_errdiff_dither(ctx,ctx->img2_ci[channel].dithersubtype,d_floor,x,y);
s_full=s_cvt_floor_full;
}
}
else if(ditherfamily==IW_DITHERFAMILY_ORDERED) {
dd=iw_ordered_dither(ctx->img2_ci[channel].dithersubtype, d_floor/(d_floor+d_ceil),x,y);
s_full = dd ? s_cvt_ceil_full : s_cvt_floor_full;
}
else if(ditherfamily==IW_DITHERFAMILY_RANDOM) {
dd=iw_random_dither(ctx,d_floor/(d_floor+d_ceil),x,y,ctx->img2_ci[channel].dithersubtype,channel);
s_full = dd ? s_cvt_ceil_full : s_cvt_floor_full;
}
else {
// Unsupported dither method.
s_full = 0.0;
}
okay:
put_raw_sample(ctx,s_full,x,y,channel);
}
// A stripped-down version of put_sample_convert_from_linear(),
// intended for use with background colors.
static unsigned int calc_sample_convert_from_linear(struct iw_context *ctx, iw_tmpsample samp_lin,
const struct iw_csdescr *csdescr, double overall_maxcolorcode)
{
double s_lin_floor_1, s_lin_ceil_1;
double s_cvt_floor_full, s_cvt_ceil_full;
double d_floor, d_ceil;
int is_exact;
double s_full;
if(samp_lin<0.0) samp_lin=0.0;
if(samp_lin>1.0) samp_lin=1.0;
is_exact = get_nearest_valid_colors(ctx,samp_lin,csdescr,
&s_lin_floor_1, &s_lin_ceil_1,
&s_cvt_floor_full, &s_cvt_ceil_full,
overall_maxcolorcode, 0);
if(is_exact) {
s_full = s_cvt_floor_full;
goto okay;
}
d_floor = samp_lin-s_lin_floor_1;
d_ceil = s_lin_ceil_1-samp_lin;
if(d_ceil<=d_floor) s_full=s_cvt_ceil_full;
else s_full=s_cvt_floor_full;
okay:
return (unsigned int)(0.5+s_full);
}
static void clamp_output_samples(struct iw_context *ctx, iw_tmpsample *out_pix, int num_out_pix)
{
int i;
for(i=0;i<num_out_pix;i++) {
if(out_pix[i]<0.0) out_pix[i]=0.0;
else if(out_pix[i]>1.0) out_pix[i]=1.0;
}
}
// TODO: Maybe this should be a flag in ctx, instead of a function that is
// called repeatedly.
static int iw_bkgd_has_transparency(struct iw_context *ctx)
{
if(!ctx->apply_bkgd) return 0;
if(!(ctx->output_profile&IW_PROFILE_TRANSPARENCY)) return 0;
if(ctx->apply_bkgd_strategy==IW_BKGD_STRATEGY_EARLY) return 0;
if(ctx->bkgd_color_source==IW_BKGD_COLOR_SOURCE_FILE) {
if(ctx->img1_bkgd_label_inputcs.c[3]<1.0) return 1;
}
else if(ctx->bkgd_color_source==IW_BKGD_COLOR_SOURCE_REQ) {
if(ctx->bkgd_checkerboard) {
if(ctx->req.bkgd2.c[3]<1.0) return 1;
}
if(ctx->req.bkgd.c[3]<1.0) return 1;
}
return 0;
}
// 'channel' is an intermediate channel number.
static int iw_process_cols_to_intermediate(struct iw_context *ctx, int channel,
const struct iw_csdescr *in_csdescr)
{
int i,j;
int retval=0;
iw_tmpsample tmp_alpha;
iw_tmpsample *inpix_tofree = NULL;
iw_tmpsample *outpix_tofree = NULL;
int is_alpha_channel;
struct iw_resize_settings *rs = NULL;
struct iw_channelinfo_intermed *int_ci;
iw_tmpsample *in_pix;
iw_tmpsample *out_pix;
int num_in_pix;
int num_out_pix;
int_ci = &ctx->intermed_ci[channel];
is_alpha_channel = (int_ci->channeltype==IW_CHANNELTYPE_ALPHA);
num_in_pix = ctx->input_h;
inpix_tofree = (iw_tmpsample*)iw_malloc(ctx, num_in_pix * sizeof(iw_tmpsample));
if(!inpix_tofree) goto done;
in_pix = inpix_tofree;
num_out_pix = ctx->intermed_canvas_height;
outpix_tofree = (iw_tmpsample*)iw_malloc(ctx, num_out_pix * sizeof(iw_tmpsample));
if(!outpix_tofree) goto done;
out_pix = outpix_tofree;
rs=&ctx->resize_settings[IW_DIMENSION_V];
// If the resize context for this dimension already exists, we should be
// able to reuse it. Otherwise, create a new one.
if(!rs->rrctx) {
// TODO: The use of the word "rows" here is misleading, because we are
// actually resizing columns.
rs->rrctx = iwpvt_resize_rows_init(ctx,rs,int_ci->channeltype,
num_in_pix, num_out_pix);
if(!rs->rrctx) goto done;
}
for(i=0;i<ctx->input_w;i++) {
// Read a column of pixels into ctx->in_pix
for(j=0;j<ctx->input_h;j++) {
in_pix[j] = get_sample_cvt_to_linear(ctx,i,j,channel,in_csdescr);
if(int_ci->need_unassoc_alpha_processing) { // We need opacity information also
tmp_alpha = get_raw_sample(ctx,i,j,ctx->img1_alpha_channel_index);
// Multiply color amount by opacity
in_pix[j] *= tmp_alpha;
}
else if(ctx->apply_bkgd && ctx->apply_bkgd_strategy==IW_BKGD_STRATEGY_EARLY) {
// We're doing "Early" background color application.
// All intermediate channels will need the background color
// applied to them.
tmp_alpha = get_raw_sample(ctx,i,j,ctx->img1_alpha_channel_index);
in_pix[j] = (tmp_alpha)*(in_pix[j]) +
(1.0-tmp_alpha)*(int_ci->bkgd_color_lin);
}
}
// Now we have a row in the right format.
// Resize it and store it in the right place in the intermediate array.
iwpvt_resize_row_main(rs->rrctx,in_pix,out_pix);
if(ctx->intclamp)
clamp_output_samples(ctx,out_pix,num_out_pix);
// The intermediate pixels are in ctx->out_pix. Copy them to the intermediate array.
for(j=0;j<ctx->intermed_canvas_height;j++) {
if(is_alpha_channel) {
ctx->intermediate_alpha32[((size_t)j)*ctx->intermed_canvas_width + i] = (iw_float32)out_pix[j];
}
else {
ctx->intermediate32[((size_t)j)*ctx->intermed_canvas_width + i] = (iw_float32)out_pix[j];
}
}
}
retval=1;
done:
if(rs && rs->disable_rrctx_cache && rs->rrctx) {
// In some cases, the channels may need different resize contexts.
// Delete the current context, so that it doesn't get reused.
iwpvt_resize_rows_done(rs->rrctx);
rs->rrctx = NULL;
}
if(inpix_tofree) iw_free(ctx,inpix_tofree);
if(outpix_tofree) iw_free(ctx,outpix_tofree);
return retval;
}
static int iw_process_rows_intermediate_to_final(struct iw_context *ctx, int intermed_channel,
const struct iw_csdescr *out_csdescr)
{
int i,j;
int z;
int k;
int retval=0;
iw_tmpsample tmpsamp;
iw_tmpsample alphasamp = 0.0;
iw_tmpsample *inpix_tofree = NULL; // Used if we need a separate temp buffer for input samples
iw_tmpsample *outpix_tofree = NULL; // Used if we need a separate temp buffer for output samples
// Do any of the output channels use error-diffusion dithering?
int using_errdiffdither = 0;
int output_channel;
int is_alpha_channel;
int bkgd_has_transparency;
double tmpbkgdalpha=0.0;
int alt_bkgd = 0; // Nonzero if we should use bkgd2 for this sample
struct iw_resize_settings *rs = NULL;
int ditherfamily, dithersubtype;
struct iw_channelinfo_intermed *int_ci;
struct iw_channelinfo_out *out_ci;
iw_tmpsample *in_pix = NULL;
iw_tmpsample *out_pix = NULL;
int num_in_pix;
int num_out_pix;
struct iw_channelinfo_out default_ci_out;
num_in_pix = ctx->intermed_canvas_width;
num_out_pix = ctx->img2.width;
int_ci = &ctx->intermed_ci[intermed_channel];
output_channel = int_ci->corresponding_output_channel;
if(output_channel>=0) {
out_ci = &ctx->img2_ci[output_channel];
}
else {
// If there is no output channelinfo struct, create a temporary one to
// use.
// TODO: This is admittedly ugly, but we use these settings for a few
// things even when there is no corresponding output channel, and I
// don't remember exactly why.
iw_zeromem(&default_ci_out, sizeof(struct iw_channelinfo_out));
default_ci_out.channeltype = IW_CHANNELTYPE_NONALPHA;
out_ci = &default_ci_out;
}
is_alpha_channel = (int_ci->channeltype==IW_CHANNELTYPE_ALPHA);
bkgd_has_transparency = iw_bkgd_has_transparency(ctx);
inpix_tofree = (iw_tmpsample*)iw_malloc(ctx, num_in_pix * sizeof(iw_tmpsample));
in_pix = inpix_tofree;
// We need an output buffer.
outpix_tofree = (iw_tmpsample*)iw_malloc(ctx, num_out_pix * sizeof(iw_tmpsample));
if(!outpix_tofree) goto done;
out_pix = outpix_tofree;
// Decide if the 'nearest color table' optimization can be used
if(ctx->nearest_color_table && !is_alpha_channel &&
out_ci->ditherfamily==IW_DITHERFAMILY_NONE &&
out_ci->color_count==0)
{
out_ci->use_nearest_color_table = 1;
}
else {
out_ci->use_nearest_color_table = 0;
}
// Seed the PRNG, if necessary.
ditherfamily = out_ci->ditherfamily;
dithersubtype = out_ci->dithersubtype;
if(ditherfamily==IW_DITHERFAMILY_RANDOM) {
// Decide what random seed to use. The alpha channel always has its own
// seed. If using "r" (not "r2") dithering, every channel has its own seed.
if(dithersubtype==IW_DITHERSUBTYPE_SAMEPATTERN && out_ci->channeltype!=IW_CHANNELTYPE_ALPHA)
{
iwpvt_prng_set_random_seed(ctx->prng,ctx->random_seed);
}
else {
iwpvt_prng_set_random_seed(ctx->prng,ctx->random_seed+out_ci->channeltype);
}
}
// Initialize Floyd-Steinberg dithering.
if(output_channel>=0 && out_ci->ditherfamily==IW_DITHERFAMILY_ERRDIFF) {
using_errdiffdither = 1;
for(i=0;i<ctx->img2.width;i++) {
for(k=0;k<IW_DITHER_MAXROWS;k++) {
ctx->dither_errors[k][i] = 0.0;
}
}
}
rs=&ctx->resize_settings[IW_DIMENSION_H];
// If the resize context for this dimension already exists, we should be
// able to reuse it. Otherwise, create a new one.
if(!rs->rrctx) {
rs->rrctx = iwpvt_resize_rows_init(ctx,rs,int_ci->channeltype,
num_in_pix, num_out_pix);
if(!rs->rrctx) goto done;
}
for(j=0;j<ctx->intermed_canvas_height;j++) {
// As needed, either copy the input pixels to a temp buffer (inpix, which
// ctx->in_pix already points to), or point ctx->in_pix directly to the
// intermediate data.
if(is_alpha_channel) {
for(i=0;i<num_in_pix;i++) {
inpix_tofree[i] = ctx->intermediate_alpha32[((size_t)j)*ctx->intermed_canvas_width+i];
}
}
else {
for(i=0;i<num_in_pix;i++) {
inpix_tofree[i] = ctx->intermediate32[((size_t)j)*ctx->intermed_canvas_width+i];
}
}
// Resize ctx->in_pix to ctx->out_pix.
iwpvt_resize_row_main(rs->rrctx,in_pix,out_pix);
if(ctx->intclamp)
clamp_output_samples(ctx,out_pix,num_out_pix);
// If necessary, copy the resized samples to the final_alpha image
if(is_alpha_channel && outpix_tofree && ctx->final_alpha32) {
for(i=0;i<num_out_pix;i++) {
ctx->final_alpha32[((size_t)j)*ctx->img2.width+i] = (iw_float32)outpix_tofree[i];
}
}
// Now convert the out_pix and put them in the final image.
if(output_channel == -1) {
// No corresponding output channel.
// (Presumably because this is an alpha channel that's being
// removed because we're applying a background.)
goto here;
}
for(z=0;z<ctx->img2.width;z++) {
// For decent Floyd-Steinberg dithering, we need to process alternate
// rows in reverse order.
if(using_errdiffdither && (j%2))
i=ctx->img2.width-1-z;
else
i=z;
tmpsamp = out_pix[i];
if(ctx->bkgd_checkerboard) {
alt_bkgd = (((ctx->bkgd_check_origin[IW_DIMENSION_H]+i)/ctx->bkgd_check_size)%2) !=
(((ctx->bkgd_check_origin[IW_DIMENSION_V]+j)/ctx->bkgd_check_size)%2);
}
if(bkgd_has_transparency) {
tmpbkgdalpha = alt_bkgd ? ctx->bkgd2alpha : ctx->bkgd1alpha;
}
if(int_ci->need_unassoc_alpha_processing) {
// Convert color samples back to unassociated alpha.
alphasamp = ctx->final_alpha32[((size_t)j)*ctx->img2.width + i];
if(alphasamp!=0.0) {
tmpsamp /= alphasamp;
}
if(ctx->apply_bkgd && ctx->apply_bkgd_strategy==IW_BKGD_STRATEGY_LATE) {
// Apply a background color (or checkerboard pattern).
double bkcolor;
bkcolor = alt_bkgd ? out_ci->bkgd2_color_lin : out_ci->bkgd1_color_lin;
if(bkgd_has_transparency) {
tmpsamp = tmpsamp*alphasamp + bkcolor*tmpbkgdalpha*(1.0-alphasamp);
}
else {
tmpsamp = tmpsamp*alphasamp + bkcolor*(1.0-alphasamp);
}
}
}
else if(is_alpha_channel && bkgd_has_transparency) {
// Composite the alpha of the foreground over the alpha of the background.
tmpsamp = tmpsamp + tmpbkgdalpha*(1.0-tmpsamp);
}
if(ctx->img2.sampletype==IW_SAMPLETYPE_FLOATINGPOINT)
put_sample_convert_from_linear_flt(ctx,tmpsamp,i,j,output_channel,out_csdescr);
else
put_sample_convert_from_linear(ctx,tmpsamp,i,j,output_channel,out_csdescr);
}
if(using_errdiffdither) {
// Move "next row" error data to "this row", and clear the "next row".
// TODO: Obviously, it would be more efficient to just swap pointers
// to the rows.
for(i=0;i<ctx->img2.width;i++) {
// Move data in all rows but the first row up one row.
for(k=0;k<IW_DITHER_MAXROWS-1;k++) {
ctx->dither_errors[k][i] = ctx->dither_errors[k+1][i];
}
// Clear the last row.
ctx->dither_errors[IW_DITHER_MAXROWS-1][i] = 0.0;
}
}
here:
;
}
retval=1;
done:
if(rs && rs->disable_rrctx_cache && rs->rrctx) {
// In some cases, the channels may need different resize contexts.
// Delete the current context, so that it doesn't get reused.
iwpvt_resize_rows_done(rs->rrctx);
rs->rrctx = NULL;
}
if(inpix_tofree) iw_free(ctx,inpix_tofree);
if(outpix_tofree) iw_free(ctx,outpix_tofree);
return retval;
}
static int iw_process_one_channel(struct iw_context *ctx, int intermed_channel,
const struct iw_csdescr *in_csdescr, const struct iw_csdescr *out_csdescr)
{
if(!iw_process_cols_to_intermediate(ctx,intermed_channel,in_csdescr)) {
return 0;
}
if(!iw_process_rows_intermediate_to_final(ctx,intermed_channel,out_csdescr)) {
return 0;
}
return 1;
}
// Potentially make a lookup table for color correction.
static void iw_make_x_to_linear_table(struct iw_context *ctx, double **ptable,
const struct iw_image *img, const struct iw_csdescr *csdescr)
{
int ncolors;
int i;
double *tbl;
if(csdescr->cstype==IW_CSTYPE_LINEAR) return;
ncolors = (1 << img->bit_depth);
if(ncolors>256) return;
// Don't make a table if the image is really small.
if( ((size_t)img->width)*img->height <= 512 ) return;
tbl = iw_malloc(ctx,ncolors*sizeof(double));
if(!tbl) return;
for(i=0;i<ncolors;i++) {
tbl[i] = x_to_linear_sample(((double)i)/(ncolors-1), csdescr);
}
*ptable = tbl;
}
static void iw_make_nearest_color_table(struct iw_context *ctx, double **ptable,
const struct iw_image *img, const struct iw_csdescr *csdescr)
{
int ncolors;
int nentries;
int i;
double *tbl;
double prev;
double curr;
if(ctx->no_gamma) return;
if(csdescr->cstype==IW_CSTYPE_LINEAR) return;
if(img->sampletype==IW_SAMPLETYPE_FLOATINGPOINT) return;
if(img->bit_depth != ctx->img2.bit_depth) return;
ncolors = (1 << img->bit_depth);
if(ncolors>256) return;
nentries = ncolors-1;
// Don't make a table if the image is really small.
if( ((size_t)img->width)*img->height <= 512 ) return;
tbl = iw_malloc(ctx,nentries*sizeof(double));
if(!tbl) return;
// Table stores the maximum value for the given entry.
// The final entry is omitted, since there is no maximum value.
prev = 0.0;
for(i=0;i<nentries;i++) {
// This conversion may appear to be going in the wrong direction
// (we're coverting *from* linear), but it's correct because we will
// search through its contents to find the corresponding index,
// instead of vice versa.
curr = x_to_linear_sample( ((double)(i+1))/(ncolors-1), csdescr);
tbl[i] = (prev + curr)/2.0;
prev = curr;
}
*ptable = tbl;
}
// Label is returned in linear colorspace.
// Returns 0 if no label available.
static int get_output_bkgd_label_lin(struct iw_context *ctx, struct iw_color *clr)
{
clr->c[0] = 1.0; clr->c[1] = 0.0; clr->c[2] = 1.0; clr->c[3] = 1.0;
if(ctx->req.suppress_output_bkgd_label) return 0;
if(ctx->req.output_bkgd_label_valid) {
*clr = ctx->req.output_bkgd_label;
return 1;
}
// If the user didn't specify a label, but the input file had one, copy the
// input file's label.
if(ctx->img1_bkgd_label_set) {
*clr = ctx->img1_bkgd_label_lin;
return 1;
}
return 0;
}
static unsigned int iw_scale_to_int(double s, unsigned int maxcolor)
{
if(s<=0.0) return 0;
if(s>=1.0) return maxcolor;
return (unsigned int)(0.5+s*maxcolor);
}
// Quantize the background color label, and store in ctx->img2.bkgdlabel.
// Also convert it to grayscale if needed.
static void iw_process_bkgd_label(struct iw_context *ctx)
{
int ret;
int k;
struct iw_color clr;
double maxcolor;
unsigned int tmpu;
if(!(ctx->output_profile&IW_PROFILE_PNG_BKGD) &&
!(ctx->output_profile&IW_PROFILE_RGB8_BKGD) &&
!(ctx->output_profile&IW_PROFILE_RGB16_BKGD))
{
return;
}
ret = get_output_bkgd_label_lin(ctx,&clr);
if(!ret) return;
if(ctx->to_grayscale) {
iw_tmpsample g;
g = iw_color_to_grayscale(ctx, clr.c[0], clr.c[1], clr.c[2]);
clr.c[0] = clr.c[1] = clr.c[2] = g;
}
if(ctx->output_profile&IW_PROFILE_RGB8_BKGD) {
maxcolor=255.0;
}
else if(ctx->output_profile&IW_PROFILE_RGB16_BKGD) {
maxcolor=65535.0;
}
else if(ctx->img2.bit_depth==8) {
maxcolor=255.0;
}
else if(ctx->img2.bit_depth==16) {
maxcolor=65535.0;
}
else {
return;
}
// Although the bkgd label is stored as floating point, we're responsible for
// making sure that, when scaled and rounded to a format suitable for the output
// format, it will be the correct color.
for(k=0;k<3;k++) {
tmpu = calc_sample_convert_from_linear(ctx, clr.c[k], &ctx->img2cs, maxcolor);
ctx->img2.bkgdlabel.c[k] = ((double)tmpu)/maxcolor;
}
// Alpha sample
tmpu = iw_scale_to_int(clr.c[3],(unsigned int)maxcolor);
ctx->img2.bkgdlabel.c[3] = ((double)tmpu)/maxcolor;
ctx->img2.has_bkgdlabel = 1;
}
static void negate_target_image(struct iw_context *ctx)
{
int channel;
struct iw_channelinfo_out *ci;
int i,j;
size_t pos;
iw_float32 s;
unsigned int n;
for(channel=0; channel<ctx->img2_numchannels; channel++) {
ci = &ctx->img2_ci[channel];
if(ci->channeltype == IW_CHANNELTYPE_ALPHA) continue; // Don't negate alpha channels
if(ctx->img2.sampletype==IW_SAMPLETYPE_FLOATINGPOINT) {
for(j=0; j<ctx->img2.height; j++) {
for(i=0; i<ctx->img2.width; i++) {
pos = j*ctx->img2.bpr + ctx->img2_numchannels*i*4 + channel*4;
s = iw_get_float32(&ctx->img2.pixels[pos]);
iw_put_float32(&ctx->img2.pixels[pos], ((iw_float32)1.0)-s);
}
}
}
else if(ctx->img2.bit_depth==8) {
for(j=0; j<ctx->img2.height; j++) {
for(i=0; i<ctx->img2.width; i++) {
pos = j*ctx->img2.bpr + ctx->img2_numchannels*i + channel;
ctx->img2.pixels[pos] = ci->maxcolorcode_int-ctx->img2.pixels[pos];
}
}
}
else if(ctx->img2.bit_depth==16) {
for(j=0; j<ctx->img2.height; j++) {
for(i=0; i<ctx->img2.width; i++) {
pos = j*ctx->img2.bpr + ctx->img2_numchannels*i*2 + channel*2;
n = ctx->img2.pixels[pos]*256 + ctx->img2.pixels[pos+1];
n = ci->maxcolorcode_int - n;
ctx->img2.pixels[pos] = (n&0xff00)>>8;
ctx->img2.pixels[pos+1] = n&0x00ff;
}
}
}
}
}
static int iw_process_internal(struct iw_context *ctx)
{
int channel;
int retval=0;
int i,k;
int ret;
// A linear color-correction descriptor to use with alpha channels.
struct iw_csdescr csdescr_linear;
ctx->intermediate32=NULL;
ctx->intermediate_alpha32=NULL;
ctx->final_alpha32=NULL;
ctx->intermed_canvas_width = ctx->input_w;
ctx->intermed_canvas_height = ctx->img2.height;
iw_make_linear_csdescr(&csdescr_linear);
ctx->img2.bpr = iw_calc_bytesperrow(ctx->img2.width,ctx->img2.bit_depth*ctx->img2_numchannels);
ctx->img2.pixels = iw_malloc_large(ctx, ctx->img2.bpr, ctx->img2.height);
if(!ctx->img2.pixels) {
goto done;
}
ctx->intermediate32 = (iw_float32*)iw_malloc_large(ctx, ctx->intermed_canvas_width * ctx->intermed_canvas_height, sizeof(iw_float32));
if(!ctx->intermediate32) {
goto done;
}
if(ctx->uses_errdiffdither) {
for(k=0;k<IW_DITHER_MAXROWS;k++) {
ctx->dither_errors[k] = (double*)iw_malloc(ctx, ctx->img2.width * sizeof(double));
if(!ctx->dither_errors[k]) goto done;
}
}
if(!ctx->disable_output_lookup_tables) {
iw_make_x_to_linear_table(ctx,&ctx->output_rev_color_corr_table,&ctx->img2,&ctx->img2cs);
iw_make_nearest_color_table(ctx,&ctx->nearest_color_table,&ctx->img2,&ctx->img2cs);
}
// If an alpha channel is present, we have to process it first.
if(IW_IMGTYPE_HAS_ALPHA(ctx->intermed_imgtype)) {
ctx->intermediate_alpha32 = (iw_float32*)iw_malloc_large(ctx, ctx->intermed_canvas_width * ctx->intermed_canvas_height, sizeof(iw_float32));
if(!ctx->intermediate_alpha32) {
goto done;
}
ctx->final_alpha32 = (iw_float32*)iw_malloc_large(ctx, ctx->img2.width * ctx->img2.height, sizeof(iw_float32));
if(!ctx->final_alpha32) {
goto done;
}
if(!iw_process_one_channel(ctx,ctx->intermed_alpha_channel_index,&csdescr_linear,&csdescr_linear)) goto done;
}
// Process the non-alpha channels.
for(channel=0;channel<ctx->intermed_numchannels;channel++) {
if(ctx->intermed_ci[channel].channeltype!=IW_CHANNELTYPE_ALPHA) {
if(ctx->no_gamma)
ret=iw_process_one_channel(ctx,channel,&csdescr_linear,&csdescr_linear);
else
ret=iw_process_one_channel(ctx,channel,&ctx->img1cs,&ctx->img2cs);
if(!ret) goto done;
}
}
iw_process_bkgd_label(ctx);
if(ctx->req.negate_target) {
negate_target_image(ctx);
}
retval=1;
done:
if(ctx->intermediate32) { iw_free(ctx,ctx->intermediate32); ctx->intermediate32=NULL; }
if(ctx->intermediate_alpha32) { iw_free(ctx,ctx->intermediate_alpha32); ctx->intermediate_alpha32=NULL; }
if(ctx->final_alpha32) { iw_free(ctx,ctx->final_alpha32); ctx->final_alpha32=NULL; }
for(k=0;k<IW_DITHER_MAXROWS;k++) {
if(ctx->dither_errors[k]) { iw_free(ctx,ctx->dither_errors[k]); ctx->dither_errors[k]=NULL; }
}
// The 'resize contexts' are usually kept around so that they can be reused.
// Now that we're done with everything, free them.
for(i=0;i<2;i++) { // horizontal, vertical
if(ctx->resize_settings[i].rrctx) {
iwpvt_resize_rows_done(ctx->resize_settings[i].rrctx);
ctx->resize_settings[i].rrctx = NULL;
}
}
return retval;
}
static int iw_get_channeltype(int imgtype, int channel)
{
switch(imgtype) {
case IW_IMGTYPE_GRAY:
if(channel==0) return IW_CHANNELTYPE_GRAY;
break;
case IW_IMGTYPE_GRAYA:
if(channel==0) return IW_CHANNELTYPE_GRAY;
if(channel==1) return IW_CHANNELTYPE_ALPHA;
break;
case IW_IMGTYPE_RGB:
if(channel==0) return IW_CHANNELTYPE_RED;
if(channel==1) return IW_CHANNELTYPE_GREEN;
if(channel==2) return IW_CHANNELTYPE_BLUE;
break;
case IW_IMGTYPE_RGBA:
if(channel==0) return IW_CHANNELTYPE_RED;
if(channel==1) return IW_CHANNELTYPE_GREEN;
if(channel==2) return IW_CHANNELTYPE_BLUE;
if(channel==3) return IW_CHANNELTYPE_ALPHA;
break;
}
return 0;
}
static void iw_set_input_channeltypes(struct iw_context *ctx)
{
int i;
for(i=0;i<ctx->img1_numchannels_logical;i++) {
ctx->img1_ci[i].channeltype = iw_get_channeltype(ctx->img1_imgtype_logical,i);
}
}
static void iw_set_intermed_channeltypes(struct iw_context *ctx)
{
int i;
for(i=0;i<ctx->intermed_numchannels;i++) {
ctx->intermed_ci[i].channeltype = iw_get_channeltype(ctx->intermed_imgtype,i);
}
}
static void iw_set_out_channeltypes(struct iw_context *ctx)
{
int i;
for(i=0;i<ctx->img2_numchannels;i++) {
ctx->img2_ci[i].channeltype = iw_get_channeltype(ctx->img2.imgtype,i);
}
}
// Set img2.bit_depth based on output_depth_req, etc.
// Set img2.sampletype.
static void decide_output_bit_depth(struct iw_context *ctx)
{
if(ctx->output_profile&IW_PROFILE_HDRI) {
ctx->img2.sampletype=IW_SAMPLETYPE_FLOATINGPOINT;
}
else {
ctx->img2.sampletype=IW_SAMPLETYPE_UINT;
}
if(ctx->img2.sampletype==IW_SAMPLETYPE_FLOATINGPOINT) {
// Floating point output.
ctx->img2.bit_depth=32;
return;
}
// Below this point, sample type is UINT.
if(ctx->req.output_depth>8 && (ctx->output_profile&IW_PROFILE_16BPS)) {
ctx->img2.bit_depth=16;
}
else {
if(ctx->req.output_depth>8) {
// Caller requested a depth higher than this format can handle.
iw_warning(ctx,"Reducing depth to 8; required by the output format.");
}
ctx->img2.bit_depth=8;
}
}
// Set the background color samples that will be used when processing the
// image. (All the logic about how to apply a background color is in
// decide_how_to_apply_bkgd(), not here.)
static void prepare_apply_bkgd(struct iw_context *ctx)
{
struct iw_color bkgd1; // Main background color in linear colorspace
struct iw_color bkgd2; // Secondary background color ...
int i;
if(!ctx->apply_bkgd) return;
// Start with a default background color.
bkgd1.c[0]=1.0; bkgd1.c[1]=0.0; bkgd1.c[2]=1.0; bkgd1.c[3]=1.0;
bkgd2.c[0]=0.0; bkgd2.c[1]=0.0; bkgd2.c[2]=0.0; bkgd2.c[3]=1.0;
// Possibly overwrite it with the background color from the appropriate
// source.
if(ctx->bkgd_color_source == IW_BKGD_COLOR_SOURCE_FILE) {
bkgd1 = ctx->img1_bkgd_label_lin; // sructure copy
ctx->bkgd_checkerboard = 0;
}
else if(ctx->bkgd_color_source == IW_BKGD_COLOR_SOURCE_REQ) {
bkgd1 = ctx->req.bkgd;
if(ctx->req.bkgd_checkerboard) {
bkgd2 = ctx->req.bkgd2;
}
}
// Set up the channelinfo (and ctx->bkgd*alpha) as needed according to the
// target image type, and whether we are applying the background before or
// after resizing.
if(ctx->apply_bkgd_strategy==IW_BKGD_STRATEGY_EARLY) {
ctx->bkgd1alpha = 1.0;
}
else {
ctx->bkgd1alpha = bkgd1.c[3];
ctx->bkgd2alpha = bkgd2.c[3];
}
if(ctx->apply_bkgd_strategy==IW_BKGD_STRATEGY_LATE && (ctx->img2.imgtype==IW_IMGTYPE_RGB ||
ctx->img2.imgtype==IW_IMGTYPE_RGBA))
{
for(i=0;i<3;i++) {
ctx->img2_ci[i].bkgd1_color_lin = bkgd1.c[i];
}
if(ctx->bkgd_checkerboard) {
for(i=0;i<3;i++) {
ctx->img2_ci[i].bkgd2_color_lin = bkgd2.c[i];
}
}
}
else if(ctx->apply_bkgd_strategy==IW_BKGD_STRATEGY_LATE && (ctx->img2.imgtype==IW_IMGTYPE_GRAY ||
ctx->img2.imgtype==IW_IMGTYPE_GRAYA))
{
ctx->img2_ci[0].bkgd1_color_lin = iw_color_to_grayscale(ctx,bkgd1.c[0],bkgd1.c[1],bkgd1.c[2]);
if(ctx->bkgd_checkerboard) {
ctx->img2_ci[0].bkgd2_color_lin = iw_color_to_grayscale(ctx,bkgd2.c[0],bkgd2.c[1],bkgd2.c[2]);
}
}
else if(ctx->apply_bkgd_strategy==IW_BKGD_STRATEGY_EARLY && ctx->img2.imgtype==IW_IMGTYPE_RGB) {
for(i=0;i<3;i++) {
ctx->intermed_ci[i].bkgd_color_lin = bkgd1.c[i];
}
}
else if(ctx->apply_bkgd_strategy==IW_BKGD_STRATEGY_EARLY && ctx->img2.imgtype==IW_IMGTYPE_GRAY) {
ctx->intermed_ci[0].bkgd_color_lin = iw_color_to_grayscale(ctx,bkgd1.c[0],bkgd1.c[1],bkgd1.c[2]);
}
}
#define IW_STRAT1_G_G 0x011 // -grayscale
#define IW_STRAT1_G_RGB 0x013 // default
#define IW_STRAT1_GA_G 0x021 // -grayscale, BKGD_STRATEGY_EARLY (never happens?)
#define IW_STRAT1_GA_GA 0x022 // -grayscale
#define IW_STRAT1_GA_RGB 0x023 // BKGD_STRATEGY_EARLY
#define IW_STRAT1_GA_RGBA 0x024 // default
#define IW_STRAT1_RGB_G 0x031 // -grayscale
#define IW_STRAT1_RGB_RGB 0x033 // default
#define IW_STRAT1_RGBA_G 0x041 // -grayscale, BKGD_STRATEGY_EARLY (never happens?)
#define IW_STRAT1_RGBA_GA 0x042 // -grayscale
#define IW_STRAT1_RGBA_RGB 0x043 // BKGD_STRATEGY_EARLY
#define IW_STRAT1_RGBA_RGBA 0x044 // default
#define IW_STRAT2_G_G 0x111 // -grayscale
#define IW_STRAT2_GA_G 0x121 // -grayscale, BKGD_STRATEGY_LATE
#define IW_STRAT2_GA_GA 0x122 // -grayscale
#define IW_STRAT2_RGB_RGB 0x133 // default
#define IW_STRAT2_RGBA_RGB 0x143 // BKGD_STRATEGY_LATE
#define IW_STRAT2_RGBA_RGBA 0x144 // default
static void iw_restrict_to_range(int r1, int r2, int *pvar)
{
if(*pvar < r1) *pvar = r1;
else if(*pvar > r2) *pvar = r2;
}
static void decide_strategy(struct iw_context *ctx, int *ps1, int *ps2)
{
int s1, s2;
// Start with a default strategy
switch(ctx->img1_imgtype_logical) {
case IW_IMGTYPE_RGBA:
if(ctx->to_grayscale) {
s1=IW_STRAT1_RGBA_GA;
s2=IW_STRAT2_GA_GA;
}
else {
s1=IW_STRAT1_RGBA_RGBA;
s2=IW_STRAT2_RGBA_RGBA;
}
break;
case IW_IMGTYPE_RGB:
if(ctx->to_grayscale) {
s1=IW_STRAT1_RGB_G;
s2=IW_STRAT2_G_G;
}
else {
s1=IW_STRAT1_RGB_RGB;
s2=IW_STRAT2_RGB_RGB;
}
break;
case IW_IMGTYPE_GRAYA:
if(ctx->to_grayscale) {
s1=IW_STRAT1_GA_GA;
s2=IW_STRAT2_GA_GA;
}
else {
s1=IW_STRAT1_GA_RGBA;
s2=IW_STRAT2_RGBA_RGBA;
}
break;
default:
if(ctx->to_grayscale) {
s1=IW_STRAT1_G_G;
s2=IW_STRAT2_G_G;
}
else {
s1=IW_STRAT1_G_RGB;
s2=IW_STRAT2_RGB_RGB;
}
}
if(ctx->apply_bkgd && ctx->apply_bkgd_strategy==IW_BKGD_STRATEGY_EARLY) {
// Applying background before resizing
if(s1==IW_STRAT1_RGBA_RGBA) {
s1=IW_STRAT1_RGBA_RGB;
s2=IW_STRAT2_RGB_RGB;
}
else if(s1==IW_STRAT1_GA_GA) {
s1=IW_STRAT1_GA_G;
s2=IW_STRAT2_G_G;
}
else if(s1==IW_STRAT1_GA_RGBA) {
s1=IW_STRAT1_GA_RGB;
s2=IW_STRAT2_RGB_RGB;
}
else if(s1==IW_STRAT1_RGBA_GA) {
s1=IW_STRAT1_RGBA_G;
s2=IW_STRAT2_G_G;
}
}
if(ctx->apply_bkgd && !iw_bkgd_has_transparency(ctx)) {
if(s2==IW_STRAT2_GA_GA) {
s2=IW_STRAT2_GA_G;
}
else if(s2==IW_STRAT2_RGBA_RGBA) {
s2=IW_STRAT2_RGBA_RGB;
}
}
*ps1 = s1;
*ps2 = s2;
}
// Choose our strategy for applying a background to the image.
// Uses:
// - ctx->img1_imgtype_logical (set by init_channel_info())
// - ctx->req.bkgd_valid (was background set by caller?)
// - ctx->req.bkgd_checkerboard (set by caller)
// - ctx->bkgd_check_size (set by caller)
// - ctx->resize_settings[d].use_offset
// Sets:
// - ctx->apply_bkgd (flag indicating whether we'll apply a background)
// - ctx->apply_bkgd_strategy (flag indicating *when* we'll apply a background)
// - ctx->bkgd_color_source (where to get the background color)
// - ctx->bkgd_checkerboard
// - ctx->bkgd_check_size (sanitized)
// May emit a warning if the caller's settings can't be honored.
static void decide_how_to_apply_bkgd(struct iw_context *ctx)
{
if(!IW_IMGTYPE_HAS_ALPHA(ctx->img1_imgtype_logical)) {
// If we know the image does not have any transparency,
// we don't have to do anything.
ctx->apply_bkgd=0;
return;
}
// Figure out where to get the background color from, on the assumption
// that we'll use one.
if(ctx->img1_bkgd_label_set &&
(ctx->req.use_bkgd_label_from_file || !ctx->req.bkgd_valid))
{
// The input file has a background color label, and either we are
// requested to prefer it to the caller's background color, or
// the caller did not give us a background color.
// Use the color from the input file.
ctx->bkgd_color_source = IW_BKGD_COLOR_SOURCE_FILE;
}
else if(ctx->req.bkgd_valid) {
// Use the background color given by the caller.
ctx->bkgd_color_source = IW_BKGD_COLOR_SOURCE_REQ;
// Tentatively use the caller's checkerboard setting.
// This may be overridden if we can't support checkerboard backgrounds
// for some reason.
ctx->bkgd_checkerboard = ctx->req.bkgd_checkerboard;
}
else {
// No background color available. If we need one, we'll have to invent one.
ctx->bkgd_color_source = IW_BKGD_COLOR_SOURCE_NONE;
}
if(ctx->bkgd_checkerboard) {
if(ctx->bkgd_check_size<1) ctx->bkgd_check_size=1;
}
if(ctx->req.bkgd_valid) {
// Caller told us to apply a background.
ctx->apply_bkgd=1;
}
if(!(ctx->output_profile&IW_PROFILE_TRANSPARENCY)) {
if(!ctx->req.bkgd_valid && !ctx->apply_bkgd) {
iw_warning(ctx,"This image may have transparency, which is incompatible with the output format. A background color will be applied.");
}
ctx->apply_bkgd=1;
}
if(ctx->resize_settings[IW_DIMENSION_H].use_offset ||
ctx->resize_settings[IW_DIMENSION_V].use_offset)
{
// If channel offset is enabled, and the image has transparency, we
// must apply a solid color background (and we must apply it before
// resizing), regardless of whether the user asked for it. It's the
// only strategy we support.
if(!ctx->req.bkgd_valid && !ctx->apply_bkgd) {
iw_warning(ctx,"This image may have transparency, which is incompatible with a channel offset. A background color will be applied.");
}
ctx->apply_bkgd=1;
if(ctx->bkgd_checkerboard && ctx->req.bkgd_checkerboard) {
iw_warning(ctx,"Checkerboard backgrounds are not supported when using a channel offset.");
ctx->bkgd_checkerboard=0;
}
ctx->apply_bkgd_strategy=IW_BKGD_STRATEGY_EARLY;
return;
}
if(!ctx->apply_bkgd) {
// No reason to apply a background color.
return;
}
if(ctx->bkgd_checkerboard) {
// Non-solid-color backgrounds must be applied after resizing.
ctx->apply_bkgd_strategy=IW_BKGD_STRATEGY_LATE;
return;
}
// At this point, either Early or Late background application is possible,
// and (I think) would, in an idealized situation, yield the same result.
// Things that can cause it to be different include
// * using a different resampling algorithm for the alpha channel (this is
// no longer supported)
// * 'intermediate clamping'
//
// Setting this to Late is the safe, though it is slower than Early.
ctx->apply_bkgd_strategy=IW_BKGD_STRATEGY_LATE;
}
static void iw_set_auto_resizetype(struct iw_context *ctx, int size1, int size2,
int dimension)
{
// If not changing the size, default to "null" resize if we can.
// (We can't do that if using a translation or channel offset.)
if(size2==size1 && !ctx->resize_settings[dimension].use_offset &&
!ctx->req.out_true_valid &&
ctx->resize_settings[dimension].translate==0.0)
{
iw_set_resize_alg(ctx, dimension, IW_RESIZETYPE_NULL, 1.0, 0.0, 0.0);
return;
}
// Otherwise, default to Catmull-Rom
iw_set_resize_alg(ctx, dimension, IW_RESIZETYPE_CUBIC, 1.0, 0.0, 0.5);
}
static void init_channel_info(struct iw_context *ctx)
{
int i;
ctx->img1_imgtype_logical = ctx->img1.imgtype;
if(ctx->resize_settings[IW_DIMENSION_H].edge_policy==IW_EDGE_POLICY_TRANSPARENT ||
ctx->resize_settings[IW_DIMENSION_V].edge_policy==IW_EDGE_POLICY_TRANSPARENT)
{
// Add a virtual alpha channel
if(ctx->img1.imgtype==IW_IMGTYPE_GRAY) {
ctx->img1_imgtype_logical = IW_IMGTYPE_GRAYA;
}
else if(ctx->img1.imgtype==IW_IMGTYPE_RGB)
ctx->img1_imgtype_logical = IW_IMGTYPE_RGBA;
}
ctx->img1_numchannels_physical = iw_imgtype_num_channels(ctx->img1.imgtype);
ctx->img1_numchannels_logical = iw_imgtype_num_channels(ctx->img1_imgtype_logical);
ctx->img1_alpha_channel_index = iw_imgtype_alpha_channel_index(ctx->img1_imgtype_logical);
iw_set_input_channeltypes(ctx);
ctx->img2.imgtype = ctx->img1_imgtype_logical; // default
ctx->img2_numchannels = ctx->img1_numchannels_logical; // default
ctx->intermed_numchannels = ctx->img1_numchannels_logical; // default
for(i=0;i<ctx->img1_numchannels_logical;i++) {
ctx->intermed_ci[i].channeltype = ctx->img1_ci[i].channeltype;
ctx->intermed_ci[i].corresponding_input_channel = i;
ctx->img2_ci[i].channeltype = ctx->img1_ci[i].channeltype;
if(i>=ctx->img1_numchannels_physical) {
// This is a virtual channel, which is handled by get_raw_sample().
// But some optimizations cause that function to be bypassed, so we
// have to disable those optimizations.
ctx->img1_ci[i].disable_fast_get_sample = 1;
}
}
}
// Set the weights for the grayscale algorithm, if needed.
static void prepare_grayscale(struct iw_context *ctx)
{
switch(ctx->grayscale_formula) {
case IW_GSF_STANDARD:
ctx->grayscale_formula = IW_GSF_WEIGHTED;
iw_set_grayscale_weights(ctx,0.212655,0.715158,0.072187);
break;
case IW_GSF_COMPATIBLE:
ctx->grayscale_formula = IW_GSF_WEIGHTED;
iw_set_grayscale_weights(ctx,0.299,0.587,0.114);
break;
}
}
// Set up some things before we do the resize, and check to make
// sure everything looks okay.
static int iw_prepare_processing(struct iw_context *ctx, int w, int h)
{
int i,j;
int output_maxcolorcode_int;
int strategy1, strategy2;
int flag;
if(ctx->output_profile==0) {
iw_set_error(ctx,"Output profile not set");
return 0;
}
if(!ctx->prng) {
// TODO: It would be better to only create the random number generator
// if we will need it.
ctx->prng = iwpvt_prng_create(ctx);
}
if(ctx->randomize) {
// Acquire and record a random seed. This also seeds the PRNG, but
// that's irrelevant. It will be re-seeded before it is used.
ctx->random_seed = iwpvt_util_randomize(ctx->prng);
}
if(ctx->req.out_true_valid) {
ctx->resize_settings[IW_DIMENSION_H].out_true_size = ctx->req.out_true_width;
ctx->resize_settings[IW_DIMENSION_V].out_true_size = ctx->req.out_true_height;
}
else {
ctx->resize_settings[IW_DIMENSION_H].out_true_size = (double)w;
ctx->resize_settings[IW_DIMENSION_V].out_true_size = (double)h;
}
if(!iw_check_image_dimensions(ctx,ctx->img1.width,ctx->img1.height)) {
return 0;
}
if(!iw_check_image_dimensions(ctx,w,h)) {
return 0;
}
if(ctx->to_grayscale) {
prepare_grayscale(ctx);
}
init_channel_info(ctx);
ctx->img2.width = w;
ctx->img2.height = h;
// Figure out the region of the source image to read from.
if(ctx->input_start_x<0) ctx->input_start_x=0;
if(ctx->input_start_y<0) ctx->input_start_y=0;
if(ctx->input_start_x>ctx->img1.width-1) ctx->input_start_x=ctx->img1.width-1;
if(ctx->input_start_y>ctx->img1.height-1) ctx->input_start_x=ctx->img1.height-1;
if(ctx->input_w<0) ctx->input_w = ctx->img1.width - ctx->input_start_x;
if(ctx->input_h<0) ctx->input_h = ctx->img1.height - ctx->input_start_y;
if(ctx->input_w<1) ctx->input_w = 1;
if(ctx->input_h<1) ctx->input_h = 1;
if(ctx->input_w>(ctx->img1.width-ctx->input_start_x)) ctx->input_w=ctx->img1.width-ctx->input_start_x;
if(ctx->input_h>(ctx->img1.height-ctx->input_start_y)) ctx->input_h=ctx->img1.height-ctx->input_start_y;
// Decide on the output colorspace.
if(ctx->req.output_cs_valid) {
// Try to use colorspace requested by caller.
ctx->img2cs = ctx->req.output_cs;
if(ctx->output_profile&IW_PROFILE_ALWAYSLINEAR) {
if(ctx->img2cs.cstype!=IW_CSTYPE_LINEAR) {
iw_warning(ctx,"Forcing output colorspace to linear; required by the output format.");
iw_make_linear_csdescr(&ctx->img2cs);
}
}
}
else {
// By default, set the output colorspace to sRGB in most cases.
if(ctx->output_profile&IW_PROFILE_ALWAYSLINEAR) {
iw_make_linear_csdescr(&ctx->img2cs);
}
else {
iw_make_srgb_csdescr_2(&ctx->img2cs);
}
}
// Make sure maxcolorcodes are set.
if(ctx->img1.sampletype!=IW_SAMPLETYPE_FLOATINGPOINT) {
ctx->input_maxcolorcode_int = (1 << ctx->img1.bit_depth)-1;
ctx->input_maxcolorcode = (double)ctx->input_maxcolorcode_int;
for(i=0;i<IW_CI_COUNT;i++) {
if(ctx->img1_ci[i].maxcolorcode_int<=0) {
ctx->img1_ci[i].maxcolorcode_int = ctx->input_maxcolorcode_int;
}
ctx->img1_ci[i].maxcolorcode_dbl = (double)ctx->img1_ci[i].maxcolorcode_int;
if(ctx->img1_ci[i].maxcolorcode_int != ctx->input_maxcolorcode_int) {
// This is overzealous: We could enable it per-channel.
// But it's probably not worth the trouble.
ctx->support_reduced_input_bitdepths = 1;
}
}
}
if(ctx->support_reduced_input_bitdepths ||
ctx->img1.sampletype==IW_SAMPLETYPE_FLOATINGPOINT)
{
for(i=0;i<ctx->img1_numchannels_physical;i++) {
ctx->img1_ci[i].disable_fast_get_sample=1;
}
}
// Set the .use_offset flags, based on whether the caller set any
// .channel_offset[]s.
for(i=0;i<2;i++) { // horizontal, vertical
for(j=0;j<3;j++) { // red, green, blue
if(fabs(ctx->resize_settings[i].channel_offset[j])>0.00001) {
ctx->resize_settings[i].use_offset=1;
}
}
}
if(ctx->to_grayscale &&
(ctx->resize_settings[IW_DIMENSION_H].use_offset ||
ctx->resize_settings[IW_DIMENSION_V].use_offset) )
{
iw_warning(ctx,"Disabling channel offset, due to grayscale output.");
ctx->resize_settings[IW_DIMENSION_H].use_offset=0;
ctx->resize_settings[IW_DIMENSION_V].use_offset=0;
}
decide_how_to_apply_bkgd(ctx);
// Decide if we can cache the resize settings.
for(i=0;i<2;i++) {
if(ctx->resize_settings[i].use_offset ||
(ctx->apply_bkgd &&
ctx->apply_bkgd_strategy==IW_BKGD_STRATEGY_EARLY &&
ctx->resize_settings[i].edge_policy==IW_EDGE_POLICY_TRANSPARENT))
{
// If a channel offset is used, we have to disable caching, because the
// offset is stored in the cache, and it won't be the same for all channels.
// If transparent virtual pixels will be converted to the background color
// during the resize, we have to disable caching, because the background
// sample value is stored in the cache, and it may be different for each
// channel.
ctx->resize_settings[i].disable_rrctx_cache=1;
}
}
decide_strategy(ctx,&strategy1,&strategy2);
switch(strategy1) { // input-to-intermediate
case IW_STRAT1_RGBA_RGBA:
ctx->intermed_imgtype = IW_IMGTYPE_RGBA;
break;
case IW_STRAT1_GA_RGBA:
ctx->intermed_imgtype = IW_IMGTYPE_RGBA;
ctx->intermed_ci[0].corresponding_input_channel=0;
ctx->intermed_ci[1].corresponding_input_channel=0;
ctx->intermed_ci[2].corresponding_input_channel=0;
ctx->intermed_ci[3].corresponding_input_channel=1;
break;
case IW_STRAT1_RGB_RGB:
case IW_STRAT1_RGBA_RGB:
ctx->intermed_imgtype = IW_IMGTYPE_RGB;
break;
case IW_STRAT1_G_RGB:
case IW_STRAT1_GA_RGB:
ctx->intermed_imgtype = IW_IMGTYPE_RGB;
ctx->intermed_ci[0].corresponding_input_channel=0;
ctx->intermed_ci[1].corresponding_input_channel=0;
ctx->intermed_ci[2].corresponding_input_channel=0;
break;
case IW_STRAT1_RGBA_GA:
ctx->intermed_imgtype = IW_IMGTYPE_GRAYA;
ctx->intermed_ci[0].cvt_to_grayscale=1;
ctx->intermed_ci[0].corresponding_input_channel=0;
ctx->intermed_ci[1].corresponding_input_channel=3;
break;
case IW_STRAT1_GA_GA:
ctx->intermed_imgtype = IW_IMGTYPE_GRAYA;
break;
case IW_STRAT1_RGB_G:
ctx->intermed_imgtype = IW_IMGTYPE_GRAY;
ctx->intermed_ci[0].cvt_to_grayscale=1;
ctx->intermed_ci[0].corresponding_input_channel=0;
break;
case IW_STRAT1_G_G:
ctx->intermed_imgtype = IW_IMGTYPE_GRAY;
ctx->intermed_ci[0].corresponding_input_channel=0;
break;
default:
iw_set_errorf(ctx,"Internal error, unknown strategy %d",strategy1);
return 0;
}
ctx->intermed_numchannels = iw_imgtype_num_channels(ctx->intermed_imgtype);
ctx->intermed_alpha_channel_index = iw_imgtype_alpha_channel_index(ctx->intermed_imgtype);
// Start with default mapping:
for(i=0;i<ctx->intermed_numchannels;i++) {
ctx->intermed_ci[i].corresponding_output_channel = i;
}
switch(strategy2) { // intermediate-to-output
case IW_STRAT2_RGBA_RGBA:
ctx->img2.imgtype = IW_IMGTYPE_RGBA;
break;
case IW_STRAT2_RGB_RGB:
ctx->img2.imgtype = IW_IMGTYPE_RGB;
break;
case IW_STRAT2_RGBA_RGB:
ctx->img2.imgtype = IW_IMGTYPE_RGB;
ctx->intermed_ci[3].corresponding_output_channel= -1;
break;
case IW_STRAT2_GA_GA:
ctx->img2.imgtype = IW_IMGTYPE_GRAYA;
break;
case IW_STRAT2_G_G:
ctx->img2.imgtype = IW_IMGTYPE_GRAY;
break;
case IW_STRAT2_GA_G:
ctx->img2.imgtype = IW_IMGTYPE_GRAY;
ctx->intermed_ci[1].corresponding_output_channel= -1;
break;
default:
iw_set_error(ctx,"Internal error");
return 0;
}
ctx->img2_numchannels = iw_imgtype_num_channels(ctx->img2.imgtype);
iw_set_intermed_channeltypes(ctx);
iw_set_out_channeltypes(ctx);
// If an alpha channel is present, set a flag on the other channels to indicate
// that we have to process them differently.
if(IW_IMGTYPE_HAS_ALPHA(ctx->intermed_imgtype)) {
for(i=0;i<ctx->intermed_numchannels;i++) {
if(ctx->intermed_ci[i].channeltype!=IW_CHANNELTYPE_ALPHA)
ctx->intermed_ci[i].need_unassoc_alpha_processing = 1;
}
}
decide_output_bit_depth(ctx);
if(ctx->img2.sampletype==IW_SAMPLETYPE_FLOATINGPOINT) {
flag=0;
for(i=0;i<IW_NUM_CHANNELTYPES;i++) {
if(ctx->req.color_count[i]) flag=1;
}
if(flag) {
iw_warning(ctx,"Posterization is not supported with floating point output.");
}
}
else {
output_maxcolorcode_int = (1 << ctx->img2.bit_depth)-1;
// Set the default maxcolorcodes
for(i=0;i<ctx->img2_numchannels;i++) {
ctx->img2_ci[i].maxcolorcode_int = output_maxcolorcode_int;
}
// Check for special "reduced" colorcodes.
if((ctx->output_profile&IW_PROFILE_REDUCEDBITDEPTHS)) {
for(i=0;i<ctx->img2_numchannels;i++) {
int mccr;
mccr = ctx->req.output_maxcolorcode[ctx->img2_ci[i].channeltype];
if(mccr>0) {
if(mccr>output_maxcolorcode_int) mccr=output_maxcolorcode_int;
ctx->img2_ci[i].maxcolorcode_int = mccr;
}
}
}
// Set some flags, and set the floating-point versions of the maxcolorcodes.
for(i=0;i<ctx->img2_numchannels;i++) {
if(ctx->img2_ci[i].maxcolorcode_int != output_maxcolorcode_int) {
ctx->reduced_output_maxcolor_flag = 1;
ctx->disable_output_lookup_tables = 1;
}
ctx->img2_ci[i].maxcolorcode_dbl = (double)ctx->img2_ci[i].maxcolorcode_int;
}
}
for(i=0;i<ctx->img2_numchannels;i++) {
ctx->img2_ci[i].color_count = ctx->req.color_count[ctx->img2_ci[i].channeltype];
if(ctx->img2_ci[i].color_count) {
iw_restrict_to_range(2,ctx->img2_ci[i].maxcolorcode_int,&ctx->img2_ci[i].color_count);
}
if(ctx->img2_ci[i].color_count==1+ctx->img2_ci[i].maxcolorcode_int) {
ctx->img2_ci[i].color_count = 0;
}
ctx->img2_ci[i].ditherfamily = ctx->ditherfamily_by_channeltype[ctx->img2_ci[i].channeltype];
ctx->img2_ci[i].dithersubtype = ctx->dithersubtype_by_channeltype[ctx->img2_ci[i].channeltype];
}
// Scan the output channels to see whether certain types of dithering are used.
for(i=0;i<ctx->img2_numchannels;i++) {
if(ctx->img2_ci[i].ditherfamily==IW_DITHERFAMILY_ERRDIFF) {
ctx->uses_errdiffdither=1;
}
}
if(!ctx->support_reduced_input_bitdepths && ctx->img1.sampletype==IW_SAMPLETYPE_UINT) {
iw_make_x_to_linear_table(ctx,&ctx->input_color_corr_table,&ctx->img1,&ctx->img1cs);
}
if(ctx->img1_bkgd_label_set) {
// Convert the background color to a linear colorspace.
for(i=0;i<3;i++) {
ctx->img1_bkgd_label_lin.c[i] = x_to_linear_sample(ctx->img1_bkgd_label_inputcs.c[i],&ctx->img1cs);
}
ctx->img1_bkgd_label_lin.c[3] = ctx->img1_bkgd_label_inputcs.c[3];
}
if(ctx->apply_bkgd) {
prepare_apply_bkgd(ctx);
}
if(ctx->req.output_rendering_intent==IW_INTENT_UNKNOWN) {
// User didn't request a specific intent; copy from input file.
ctx->img2.rendering_intent = ctx->img1.rendering_intent;
}
else {
ctx->img2.rendering_intent = ctx->req.output_rendering_intent;
}
if(ctx->resize_settings[IW_DIMENSION_H].family==IW_RESIZETYPE_AUTO) {
iw_set_auto_resizetype(ctx,ctx->input_w,ctx->img2.width,IW_DIMENSION_H);
}
if(ctx->resize_settings[IW_DIMENSION_V].family==IW_RESIZETYPE_AUTO) {
iw_set_auto_resizetype(ctx,ctx->input_h,ctx->img2.height,IW_DIMENSION_V);
}
if(IW_IMGTYPE_HAS_ALPHA(ctx->img2.imgtype)) {
if(!ctx->opt_strip_alpha) {
// If we're not allowed to strip the alpha channel, also disable
// other optimizations that would implicitly remove the alpha
// channel. (The optimization routines may do weird things if we
// were to allow this.)
ctx->opt_palette = 0;
ctx->opt_binary_trns = 0;
}
}
return 1;
}
IW_IMPL(int) iw_process_image(struct iw_context *ctx)
{
int ret;
int retval = 0;
if(ctx->use_count>0) {
iw_set_error(ctx,"Internal: Incorrect attempt to reprocess image");
goto done;
}
ctx->use_count++;
ret = iw_prepare_processing(ctx,ctx->canvas_width,ctx->canvas_height);
if(!ret) goto done;
ret = iw_process_internal(ctx);
if(!ret) goto done;
iwpvt_optimize_image(ctx);
retval = 1;
done:
return retval;
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_3368_1 |
crossvul-cpp_data_bad_4265_0 | /*-
* Copyright (c) 2003-2011 Tim Kientzle
* Copyright (c) 2011-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_string.c 201095 2009-12-28 02:33:22Z kientzle $");
/*
* Basic resizable string support, to simplify manipulating arbitrary-sized
* strings while minimizing heap activity.
*
* In particular, the buffer used by a string object is only grown, it
* never shrinks, so you can clear and reuse the same string object
* without incurring additional memory allocations.
*/
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
#ifdef HAVE_ICONV_H
#include <iconv.h>
#endif
#ifdef HAVE_LANGINFO_H
#include <langinfo.h>
#endif
#ifdef HAVE_LOCALCHARSET_H
#include <localcharset.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#ifdef HAVE_WCHAR_H
#include <wchar.h>
#endif
#if defined(_WIN32) && !defined(__CYGWIN__)
#include <windows.h>
#include <locale.h>
#endif
#include "archive_endian.h"
#include "archive_private.h"
#include "archive_string.h"
#include "archive_string_composition.h"
#if !defined(HAVE_WMEMCPY) && !defined(wmemcpy)
#define wmemcpy(a,b,i) (wchar_t *)memcpy((a), (b), (i) * sizeof(wchar_t))
#endif
#if !defined(HAVE_WMEMMOVE) && !defined(wmemmove)
#define wmemmove(a,b,i) (wchar_t *)memmove((a), (b), (i) * sizeof(wchar_t))
#endif
struct archive_string_conv {
struct archive_string_conv *next;
char *from_charset;
char *to_charset;
unsigned from_cp;
unsigned to_cp;
/* Set 1 if from_charset and to_charset are the same. */
int same;
int flag;
#define SCONV_TO_CHARSET 1 /* MBS is being converted to specified
* charset. */
#define SCONV_FROM_CHARSET (1<<1) /* MBS is being converted from
* specified charset. */
#define SCONV_BEST_EFFORT (1<<2) /* Copy at least ASCII code. */
#define SCONV_WIN_CP (1<<3) /* Use Windows API for converting
* MBS. */
#define SCONV_UTF8_LIBARCHIVE_2 (1<<4) /* Incorrect UTF-8 made by libarchive
* 2.x in the wrong assumption. */
#define SCONV_NORMALIZATION_C (1<<6) /* Need normalization to be Form C.
* Before UTF-8 characters are actually
* processed. */
#define SCONV_NORMALIZATION_D (1<<7) /* Need normalization to be Form D.
* Before UTF-8 characters are actually
* processed.
* Currently this only for MAC OS X. */
#define SCONV_TO_UTF8 (1<<8) /* "to charset" side is UTF-8. */
#define SCONV_FROM_UTF8 (1<<9) /* "from charset" side is UTF-8. */
#define SCONV_TO_UTF16BE (1<<10) /* "to charset" side is UTF-16BE. */
#define SCONV_FROM_UTF16BE (1<<11) /* "from charset" side is UTF-16BE. */
#define SCONV_TO_UTF16LE (1<<12) /* "to charset" side is UTF-16LE. */
#define SCONV_FROM_UTF16LE (1<<13) /* "from charset" side is UTF-16LE. */
#define SCONV_TO_UTF16 (SCONV_TO_UTF16BE | SCONV_TO_UTF16LE)
#define SCONV_FROM_UTF16 (SCONV_FROM_UTF16BE | SCONV_FROM_UTF16LE)
#if HAVE_ICONV
iconv_t cd;
iconv_t cd_w;/* Use at archive_mstring on
* Windows. */
#endif
/* A temporary buffer for normalization. */
struct archive_string utftmp;
int (*converter[2])(struct archive_string *, const void *, size_t,
struct archive_string_conv *);
int nconverter;
};
#define CP_C_LOCALE 0 /* "C" locale only for this file. */
#define CP_UTF16LE 1200
#define CP_UTF16BE 1201
#define IS_HIGH_SURROGATE_LA(uc) ((uc) >= 0xD800 && (uc) <= 0xDBFF)
#define IS_LOW_SURROGATE_LA(uc) ((uc) >= 0xDC00 && (uc) <= 0xDFFF)
#define IS_SURROGATE_PAIR_LA(uc) ((uc) >= 0xD800 && (uc) <= 0xDFFF)
#define UNICODE_MAX 0x10FFFF
#define UNICODE_R_CHAR 0xFFFD /* Replacement character. */
/* Set U+FFFD(Replacement character) in UTF-8. */
static const char utf8_replacement_char[] = {0xef, 0xbf, 0xbd};
static struct archive_string_conv *find_sconv_object(struct archive *,
const char *, const char *);
static void add_sconv_object(struct archive *, struct archive_string_conv *);
static struct archive_string_conv *create_sconv_object(const char *,
const char *, unsigned, int);
static void free_sconv_object(struct archive_string_conv *);
static struct archive_string_conv *get_sconv_object(struct archive *,
const char *, const char *, int);
static unsigned make_codepage_from_charset(const char *);
static unsigned get_current_codepage(void);
static unsigned get_current_oemcp(void);
static size_t mbsnbytes(const void *, size_t);
static size_t utf16nbytes(const void *, size_t);
#if defined(_WIN32) && !defined(__CYGWIN__)
static int archive_wstring_append_from_mbs_in_codepage(
struct archive_wstring *, const char *, size_t,
struct archive_string_conv *);
static int archive_string_append_from_wcs_in_codepage(struct archive_string *,
const wchar_t *, size_t, struct archive_string_conv *);
static int is_big_endian(void);
static int strncat_in_codepage(struct archive_string *, const void *,
size_t, struct archive_string_conv *);
static int win_strncat_from_utf16be(struct archive_string *, const void *,
size_t, struct archive_string_conv *);
static int win_strncat_from_utf16le(struct archive_string *, const void *,
size_t, struct archive_string_conv *);
static int win_strncat_to_utf16be(struct archive_string *, const void *,
size_t, struct archive_string_conv *);
static int win_strncat_to_utf16le(struct archive_string *, const void *,
size_t, struct archive_string_conv *);
#endif
static int best_effort_strncat_from_utf16be(struct archive_string *,
const void *, size_t, struct archive_string_conv *);
static int best_effort_strncat_from_utf16le(struct archive_string *,
const void *, size_t, struct archive_string_conv *);
static int best_effort_strncat_to_utf16be(struct archive_string *,
const void *, size_t, struct archive_string_conv *);
static int best_effort_strncat_to_utf16le(struct archive_string *,
const void *, size_t, struct archive_string_conv *);
#if defined(HAVE_ICONV)
static int iconv_strncat_in_locale(struct archive_string *, const void *,
size_t, struct archive_string_conv *);
#endif
static int best_effort_strncat_in_locale(struct archive_string *,
const void *, size_t, struct archive_string_conv *);
static int _utf8_to_unicode(uint32_t *, const char *, size_t);
static int utf8_to_unicode(uint32_t *, const char *, size_t);
static inline uint32_t combine_surrogate_pair(uint32_t, uint32_t);
static int cesu8_to_unicode(uint32_t *, const char *, size_t);
static size_t unicode_to_utf8(char *, size_t, uint32_t);
static int utf16_to_unicode(uint32_t *, const char *, size_t, int);
static size_t unicode_to_utf16be(char *, size_t, uint32_t);
static size_t unicode_to_utf16le(char *, size_t, uint32_t);
static int strncat_from_utf8_libarchive2(struct archive_string *,
const void *, size_t, struct archive_string_conv *);
static int strncat_from_utf8_to_utf8(struct archive_string *, const void *,
size_t, struct archive_string_conv *);
static int archive_string_normalize_C(struct archive_string *, const void *,
size_t, struct archive_string_conv *);
static int archive_string_normalize_D(struct archive_string *, const void *,
size_t, struct archive_string_conv *);
static int archive_string_append_unicode(struct archive_string *,
const void *, size_t, struct archive_string_conv *);
static struct archive_string *
archive_string_append(struct archive_string *as, const char *p, size_t s)
{
if (archive_string_ensure(as, as->length + s + 1) == NULL)
return (NULL);
if (s)
memmove(as->s + as->length, p, s);
as->length += s;
as->s[as->length] = 0;
return (as);
}
static struct archive_wstring *
archive_wstring_append(struct archive_wstring *as, const wchar_t *p, size_t s)
{
if (archive_wstring_ensure(as, as->length + s + 1) == NULL)
return (NULL);
if (s)
wmemmove(as->s + as->length, p, s);
as->length += s;
as->s[as->length] = 0;
return (as);
}
struct archive_string *
archive_array_append(struct archive_string *as, const char *p, size_t s)
{
return archive_string_append(as, p, s);
}
void
archive_string_concat(struct archive_string *dest, struct archive_string *src)
{
if (archive_string_append(dest, src->s, src->length) == NULL)
__archive_errx(1, "Out of memory");
}
void
archive_wstring_concat(struct archive_wstring *dest,
struct archive_wstring *src)
{
if (archive_wstring_append(dest, src->s, src->length) == NULL)
__archive_errx(1, "Out of memory");
}
void
archive_string_free(struct archive_string *as)
{
as->length = 0;
as->buffer_length = 0;
free(as->s);
as->s = NULL;
}
void
archive_wstring_free(struct archive_wstring *as)
{
as->length = 0;
as->buffer_length = 0;
free(as->s);
as->s = NULL;
}
struct archive_wstring *
archive_wstring_ensure(struct archive_wstring *as, size_t s)
{
return (struct archive_wstring *)
archive_string_ensure((struct archive_string *)as,
s * sizeof(wchar_t));
}
/* Returns NULL on any allocation failure. */
struct archive_string *
archive_string_ensure(struct archive_string *as, size_t s)
{
char *p;
size_t new_length;
/* If buffer is already big enough, don't reallocate. */
if (as->s && (s <= as->buffer_length))
return (as);
/*
* Growing the buffer at least exponentially ensures that
* append operations are always linear in the number of
* characters appended. Using a smaller growth rate for
* larger buffers reduces memory waste somewhat at the cost of
* a larger constant factor.
*/
if (as->buffer_length < 32)
/* Start with a minimum 32-character buffer. */
new_length = 32;
else if (as->buffer_length < 8192)
/* Buffers under 8k are doubled for speed. */
new_length = as->buffer_length + as->buffer_length;
else {
/* Buffers 8k and over grow by at least 25% each time. */
new_length = as->buffer_length + as->buffer_length / 4;
/* Be safe: If size wraps, fail. */
if (new_length < as->buffer_length) {
/* On failure, wipe the string and return NULL. */
archive_string_free(as);
errno = ENOMEM;/* Make sure errno has ENOMEM. */
return (NULL);
}
}
/*
* The computation above is a lower limit to how much we'll
* grow the buffer. In any case, we have to grow it enough to
* hold the request.
*/
if (new_length < s)
new_length = s;
/* Now we can reallocate the buffer. */
p = (char *)realloc(as->s, new_length);
if (p == NULL) {
/* On failure, wipe the string and return NULL. */
archive_string_free(as);
errno = ENOMEM;/* Make sure errno has ENOMEM. */
return (NULL);
}
as->s = p;
as->buffer_length = new_length;
return (as);
}
/*
* TODO: See if there's a way to avoid scanning
* the source string twice. Then test to see
* if it actually helps (remember that we're almost
* always called with pretty short arguments, so
* such an optimization might not help).
*/
struct archive_string *
archive_strncat(struct archive_string *as, const void *_p, size_t n)
{
size_t s;
const char *p, *pp;
p = (const char *)_p;
/* Like strlen(p), except won't examine positions beyond p[n]. */
s = 0;
pp = p;
while (s < n && *pp) {
pp++;
s++;
}
if ((as = archive_string_append(as, p, s)) == NULL)
__archive_errx(1, "Out of memory");
return (as);
}
struct archive_wstring *
archive_wstrncat(struct archive_wstring *as, const wchar_t *p, size_t n)
{
size_t s;
const wchar_t *pp;
/* Like strlen(p), except won't examine positions beyond p[n]. */
s = 0;
pp = p;
while (s < n && *pp) {
pp++;
s++;
}
if ((as = archive_wstring_append(as, p, s)) == NULL)
__archive_errx(1, "Out of memory");
return (as);
}
struct archive_string *
archive_strcat(struct archive_string *as, const void *p)
{
/* strcat is just strncat without an effective limit.
* Assert that we'll never get called with a source
* string over 16MB.
* TODO: Review all uses of strcat in the source
* and try to replace them with strncat().
*/
return archive_strncat(as, p, 0x1000000);
}
struct archive_wstring *
archive_wstrcat(struct archive_wstring *as, const wchar_t *p)
{
/* Ditto. */
return archive_wstrncat(as, p, 0x1000000);
}
struct archive_string *
archive_strappend_char(struct archive_string *as, char c)
{
if ((as = archive_string_append(as, &c, 1)) == NULL)
__archive_errx(1, "Out of memory");
return (as);
}
struct archive_wstring *
archive_wstrappend_wchar(struct archive_wstring *as, wchar_t c)
{
if ((as = archive_wstring_append(as, &c, 1)) == NULL)
__archive_errx(1, "Out of memory");
return (as);
}
/*
* Get the "current character set" name to use with iconv.
* On FreeBSD, the empty character set name "" chooses
* the correct character encoding for the current locale,
* so this isn't necessary.
* But iconv on Mac OS 10.6 doesn't seem to handle this correctly;
* on that system, we have to explicitly call nl_langinfo()
* to get the right name. Not sure about other platforms.
*
* NOTE: GNU libiconv does not recognize the character-set name
* which some platform nl_langinfo(CODESET) returns, so we should
* use locale_charset() instead of nl_langinfo(CODESET) for GNU libiconv.
*/
static const char *
default_iconv_charset(const char *charset) {
if (charset != NULL && charset[0] != '\0')
return charset;
#if HAVE_LOCALE_CHARSET && !defined(__APPLE__)
/* locale_charset() is broken on Mac OS */
return locale_charset();
#elif HAVE_NL_LANGINFO
return nl_langinfo(CODESET);
#else
return "";
#endif
}
#if defined(_WIN32) && !defined(__CYGWIN__)
/*
* Convert MBS to WCS.
* Note: returns -1 if conversion fails.
*/
int
archive_wstring_append_from_mbs(struct archive_wstring *dest,
const char *p, size_t len)
{
return archive_wstring_append_from_mbs_in_codepage(dest, p, len, NULL);
}
static int
archive_wstring_append_from_mbs_in_codepage(struct archive_wstring *dest,
const char *s, size_t length, struct archive_string_conv *sc)
{
int count, ret = 0;
UINT from_cp;
if (sc != NULL)
from_cp = sc->from_cp;
else
from_cp = get_current_codepage();
if (from_cp == CP_C_LOCALE) {
/*
* "C" locale special processing.
*/
wchar_t *ws;
const unsigned char *mp;
if (NULL == archive_wstring_ensure(dest,
dest->length + length + 1))
return (-1);
ws = dest->s + dest->length;
mp = (const unsigned char *)s;
count = 0;
while (count < (int)length && *mp) {
*ws++ = (wchar_t)*mp++;
count++;
}
} else if (sc != NULL &&
(sc->flag & (SCONV_NORMALIZATION_C | SCONV_NORMALIZATION_D))) {
/*
* Normalize UTF-8 and UTF-16BE and convert it directly
* to UTF-16 as wchar_t.
*/
struct archive_string u16;
int saved_flag = sc->flag;/* save current flag. */
if (is_big_endian())
sc->flag |= SCONV_TO_UTF16BE;
else
sc->flag |= SCONV_TO_UTF16LE;
if (sc->flag & SCONV_FROM_UTF16) {
/*
* UTF-16BE/LE NFD ===> UTF-16 NFC
* UTF-16BE/LE NFC ===> UTF-16 NFD
*/
count = (int)utf16nbytes(s, length);
} else {
/*
* UTF-8 NFD ===> UTF-16 NFC
* UTF-8 NFC ===> UTF-16 NFD
*/
count = (int)mbsnbytes(s, length);
}
u16.s = (char *)dest->s;
u16.length = dest->length << 1;;
u16.buffer_length = dest->buffer_length;
if (sc->flag & SCONV_NORMALIZATION_C)
ret = archive_string_normalize_C(&u16, s, count, sc);
else
ret = archive_string_normalize_D(&u16, s, count, sc);
dest->s = (wchar_t *)u16.s;
dest->length = u16.length >> 1;
dest->buffer_length = u16.buffer_length;
sc->flag = saved_flag;/* restore the saved flag. */
return (ret);
} else if (sc != NULL && (sc->flag & SCONV_FROM_UTF16)) {
count = (int)utf16nbytes(s, length);
count >>= 1; /* to be WCS length */
/* Allocate memory for WCS. */
if (NULL == archive_wstring_ensure(dest,
dest->length + count + 1))
return (-1);
wmemcpy(dest->s + dest->length, (const wchar_t *)s, count);
if ((sc->flag & SCONV_FROM_UTF16BE) && !is_big_endian()) {
uint16_t *u16 = (uint16_t *)(dest->s + dest->length);
int b;
for (b = 0; b < count; b++) {
uint16_t val = archive_le16dec(u16+b);
archive_be16enc(u16+b, val);
}
} else if ((sc->flag & SCONV_FROM_UTF16LE) && is_big_endian()) {
uint16_t *u16 = (uint16_t *)(dest->s + dest->length);
int b;
for (b = 0; b < count; b++) {
uint16_t val = archive_be16dec(u16+b);
archive_le16enc(u16+b, val);
}
}
} else {
DWORD mbflag;
size_t buffsize;
if (sc == NULL)
mbflag = 0;
else if (sc->flag & SCONV_FROM_CHARSET) {
/* Do not trust the length which comes from
* an archive file. */
length = mbsnbytes(s, length);
mbflag = 0;
} else
mbflag = MB_PRECOMPOSED;
buffsize = dest->length + length + 1;
do {
/* Allocate memory for WCS. */
if (NULL == archive_wstring_ensure(dest, buffsize))
return (-1);
/* Convert MBS to WCS. */
count = MultiByteToWideChar(from_cp,
mbflag, s, (int)length, dest->s + dest->length,
(int)(dest->buffer_length >> 1) -1);
if (count == 0 &&
GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
/* Expand the WCS buffer. */
buffsize = dest->buffer_length << 1;
continue;
}
if (count == 0 && length != 0)
ret = -1;
break;
} while (1);
}
dest->length += count;
dest->s[dest->length] = L'\0';
return (ret);
}
#else
/*
* Convert MBS to WCS.
* Note: returns -1 if conversion fails.
*/
int
archive_wstring_append_from_mbs(struct archive_wstring *dest,
const char *p, size_t len)
{
size_t r;
int ret_val = 0;
/*
* No single byte will be more than one wide character,
* so this length estimate will always be big enough.
*/
// size_t wcs_length = len;
size_t mbs_length = len;
const char *mbs = p;
wchar_t *wcs;
#if HAVE_MBRTOWC
mbstate_t shift_state;
memset(&shift_state, 0, sizeof(shift_state));
#endif
/*
* As we decided to have wcs_length == mbs_length == len
* we can use len here instead of wcs_length
*/
if (NULL == archive_wstring_ensure(dest, dest->length + len + 1))
return (-1);
wcs = dest->s + dest->length;
/*
* We cannot use mbsrtowcs/mbstowcs here because those may convert
* extra MBS when strlen(p) > len and one wide character consists of
* multi bytes.
*/
while (*mbs && mbs_length > 0) {
/*
* The buffer we allocated is always big enough.
* Keep this code path in a comment if we decide to choose
* smaller wcs_length in the future
*/
/*
if (wcs_length == 0) {
dest->length = wcs - dest->s;
dest->s[dest->length] = L'\0';
wcs_length = mbs_length;
if (NULL == archive_wstring_ensure(dest,
dest->length + wcs_length + 1))
return (-1);
wcs = dest->s + dest->length;
}
*/
#if HAVE_MBRTOWC
r = mbrtowc(wcs, mbs, mbs_length, &shift_state);
#else
r = mbtowc(wcs, mbs, mbs_length);
#endif
if (r == (size_t)-1 || r == (size_t)-2) {
ret_val = -1;
break;
}
if (r == 0 || r > mbs_length)
break;
wcs++;
// wcs_length--;
mbs += r;
mbs_length -= r;
}
dest->length = wcs - dest->s;
dest->s[dest->length] = L'\0';
return (ret_val);
}
#endif
#if defined(_WIN32) && !defined(__CYGWIN__)
/*
* WCS ==> MBS.
* Note: returns -1 if conversion fails.
*
* Win32 builds use WideCharToMultiByte from the Windows API.
* (Maybe Cygwin should too? WideCharToMultiByte will know a
* lot more about local character encodings than the wcrtomb()
* wrapper is going to know.)
*/
int
archive_string_append_from_wcs(struct archive_string *as,
const wchar_t *w, size_t len)
{
return archive_string_append_from_wcs_in_codepage(as, w, len, NULL);
}
static int
archive_string_append_from_wcs_in_codepage(struct archive_string *as,
const wchar_t *ws, size_t len, struct archive_string_conv *sc)
{
BOOL defchar_used, *dp;
int count, ret = 0;
UINT to_cp;
int wslen = (int)len;
if (sc != NULL)
to_cp = sc->to_cp;
else
to_cp = get_current_codepage();
if (to_cp == CP_C_LOCALE) {
/*
* "C" locale special processing.
*/
const wchar_t *wp = ws;
char *p;
if (NULL == archive_string_ensure(as,
as->length + wslen +1))
return (-1);
p = as->s + as->length;
count = 0;
defchar_used = 0;
while (count < wslen && *wp) {
if (*wp > 255) {
*p++ = '?';
wp++;
defchar_used = 1;
} else
*p++ = (char)*wp++;
count++;
}
} else if (sc != NULL && (sc->flag & SCONV_TO_UTF16)) {
uint16_t *u16;
if (NULL ==
archive_string_ensure(as, as->length + len * 2 + 2))
return (-1);
u16 = (uint16_t *)(as->s + as->length);
count = 0;
defchar_used = 0;
if (sc->flag & SCONV_TO_UTF16BE) {
while (count < (int)len && *ws) {
archive_be16enc(u16+count, *ws);
ws++;
count++;
}
} else {
while (count < (int)len && *ws) {
archive_le16enc(u16+count, *ws);
ws++;
count++;
}
}
count <<= 1; /* to be byte size */
} else {
/* Make sure the MBS buffer has plenty to set. */
if (NULL ==
archive_string_ensure(as, as->length + len * 2 + 1))
return (-1);
do {
defchar_used = 0;
if (to_cp == CP_UTF8 || sc == NULL)
dp = NULL;
else
dp = &defchar_used;
count = WideCharToMultiByte(to_cp, 0, ws, wslen,
as->s + as->length, (int)as->buffer_length-1, NULL, dp);
if (count == 0 &&
GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
/* Expand the MBS buffer and retry. */
if (NULL == archive_string_ensure(as,
as->buffer_length + len))
return (-1);
continue;
}
if (count == 0)
ret = -1;
break;
} while (1);
}
as->length += count;
as->s[as->length] = '\0';
return (defchar_used?-1:ret);
}
#elif defined(HAVE_WCTOMB) || defined(HAVE_WCRTOMB)
/*
* Translates a wide character string into current locale character set
* and appends to the archive_string. Note: returns -1 if conversion
* fails.
*/
int
archive_string_append_from_wcs(struct archive_string *as,
const wchar_t *w, size_t len)
{
/* We cannot use the standard wcstombs() here because it
* cannot tell us how big the output buffer should be. So
* I've built a loop around wcrtomb() or wctomb() that
* converts a character at a time and resizes the string as
* needed. We prefer wcrtomb() when it's available because
* it's thread-safe. */
int n, ret_val = 0;
char *p;
char *end;
#if HAVE_WCRTOMB
mbstate_t shift_state;
memset(&shift_state, 0, sizeof(shift_state));
#else
/* Clear the shift state before starting. */
wctomb(NULL, L'\0');
#endif
/*
* Allocate buffer for MBS.
* We need this allocation here since it is possible that
* as->s is still NULL.
*/
if (archive_string_ensure(as, as->length + len + 1) == NULL)
return (-1);
p = as->s + as->length;
end = as->s + as->buffer_length - MB_CUR_MAX -1;
while (*w != L'\0' && len > 0) {
if (p >= end) {
as->length = p - as->s;
as->s[as->length] = '\0';
/* Re-allocate buffer for MBS. */
if (archive_string_ensure(as,
as->length + len * 2 + 1) == NULL)
return (-1);
p = as->s + as->length;
end = as->s + as->buffer_length - MB_CUR_MAX -1;
}
#if HAVE_WCRTOMB
n = wcrtomb(p, *w++, &shift_state);
#else
n = wctomb(p, *w++);
#endif
if (n == -1) {
if (errno == EILSEQ) {
/* Skip an illegal wide char. */
*p++ = '?';
ret_val = -1;
} else {
ret_val = -1;
break;
}
} else
p += n;
len--;
}
as->length = p - as->s;
as->s[as->length] = '\0';
return (ret_val);
}
#else /* HAVE_WCTOMB || HAVE_WCRTOMB */
/*
* TODO: Test if __STDC_ISO_10646__ is defined.
* Non-Windows uses ISO C wcrtomb() or wctomb() to perform the conversion
* one character at a time. If a non-Windows platform doesn't have
* either of these, fall back to the built-in UTF8 conversion.
*/
int
archive_string_append_from_wcs(struct archive_string *as,
const wchar_t *w, size_t len)
{
(void)as;/* UNUSED */
(void)w;/* UNUSED */
(void)len;/* UNUSED */
errno = ENOSYS;
return (-1);
}
#endif /* HAVE_WCTOMB || HAVE_WCRTOMB */
/*
* Find a string conversion object by a pair of 'from' charset name
* and 'to' charset name from an archive object.
* Return NULL if not found.
*/
static struct archive_string_conv *
find_sconv_object(struct archive *a, const char *fc, const char *tc)
{
struct archive_string_conv *sc;
if (a == NULL)
return (NULL);
for (sc = a->sconv; sc != NULL; sc = sc->next) {
if (strcmp(sc->from_charset, fc) == 0 &&
strcmp(sc->to_charset, tc) == 0)
break;
}
return (sc);
}
/*
* Register a string object to an archive object.
*/
static void
add_sconv_object(struct archive *a, struct archive_string_conv *sc)
{
struct archive_string_conv **psc;
/* Add a new sconv to sconv list. */
psc = &(a->sconv);
while (*psc != NULL)
psc = &((*psc)->next);
*psc = sc;
}
static void
add_converter(struct archive_string_conv *sc, int (*converter)
(struct archive_string *, const void *, size_t,
struct archive_string_conv *))
{
if (sc == NULL || sc->nconverter >= 2)
__archive_errx(1, "Programming error");
sc->converter[sc->nconverter++] = converter;
}
static void
setup_converter(struct archive_string_conv *sc)
{
/* Reset. */
sc->nconverter = 0;
/*
* Perform special sequence for the incorrect UTF-8 filenames
* made by libarchive2.x.
*/
if (sc->flag & SCONV_UTF8_LIBARCHIVE_2) {
add_converter(sc, strncat_from_utf8_libarchive2);
return;
}
/*
* Convert a string to UTF-16BE/LE.
*/
if (sc->flag & SCONV_TO_UTF16) {
/*
* If the current locale is UTF-8, we can translate
* a UTF-8 string into a UTF-16BE string.
*/
if (sc->flag & SCONV_FROM_UTF8) {
add_converter(sc, archive_string_append_unicode);
return;
}
#if defined(_WIN32) && !defined(__CYGWIN__)
if (sc->flag & SCONV_WIN_CP) {
if (sc->flag & SCONV_TO_UTF16BE)
add_converter(sc, win_strncat_to_utf16be);
else
add_converter(sc, win_strncat_to_utf16le);
return;
}
#endif
#if defined(HAVE_ICONV)
if (sc->cd != (iconv_t)-1) {
add_converter(sc, iconv_strncat_in_locale);
return;
}
#endif
if (sc->flag & SCONV_BEST_EFFORT) {
if (sc->flag & SCONV_TO_UTF16BE)
add_converter(sc,
best_effort_strncat_to_utf16be);
else
add_converter(sc,
best_effort_strncat_to_utf16le);
} else
/* Make sure we have no converter. */
sc->nconverter = 0;
return;
}
/*
* Convert a string from UTF-16BE/LE.
*/
if (sc->flag & SCONV_FROM_UTF16) {
/*
* At least we should normalize a UTF-16BE string.
*/
if (sc->flag & SCONV_NORMALIZATION_D)
add_converter(sc,archive_string_normalize_D);
else if (sc->flag & SCONV_NORMALIZATION_C)
add_converter(sc, archive_string_normalize_C);
if (sc->flag & SCONV_TO_UTF8) {
/*
* If the current locale is UTF-8, we can translate
* a UTF-16BE/LE string into a UTF-8 string directly.
*/
if (!(sc->flag &
(SCONV_NORMALIZATION_D |SCONV_NORMALIZATION_C)))
add_converter(sc,
archive_string_append_unicode);
return;
}
#if defined(_WIN32) && !defined(__CYGWIN__)
if (sc->flag & SCONV_WIN_CP) {
if (sc->flag & SCONV_FROM_UTF16BE)
add_converter(sc, win_strncat_from_utf16be);
else
add_converter(sc, win_strncat_from_utf16le);
return;
}
#endif
#if defined(HAVE_ICONV)
if (sc->cd != (iconv_t)-1) {
add_converter(sc, iconv_strncat_in_locale);
return;
}
#endif
if ((sc->flag & (SCONV_BEST_EFFORT | SCONV_FROM_UTF16BE))
== (SCONV_BEST_EFFORT | SCONV_FROM_UTF16BE))
add_converter(sc, best_effort_strncat_from_utf16be);
else if ((sc->flag & (SCONV_BEST_EFFORT | SCONV_FROM_UTF16LE))
== (SCONV_BEST_EFFORT | SCONV_FROM_UTF16LE))
add_converter(sc, best_effort_strncat_from_utf16le);
else
/* Make sure we have no converter. */
sc->nconverter = 0;
return;
}
if (sc->flag & SCONV_FROM_UTF8) {
/*
* At least we should normalize a UTF-8 string.
*/
if (sc->flag & SCONV_NORMALIZATION_D)
add_converter(sc,archive_string_normalize_D);
else if (sc->flag & SCONV_NORMALIZATION_C)
add_converter(sc, archive_string_normalize_C);
/*
* Copy UTF-8 string with a check of CESU-8.
* Apparently, iconv does not check surrogate pairs in UTF-8
* when both from-charset and to-charset are UTF-8, and then
* we use our UTF-8 copy code.
*/
if (sc->flag & SCONV_TO_UTF8) {
/*
* If the current locale is UTF-8, we can translate
* a UTF-16BE string into a UTF-8 string directly.
*/
if (!(sc->flag &
(SCONV_NORMALIZATION_D |SCONV_NORMALIZATION_C)))
add_converter(sc, strncat_from_utf8_to_utf8);
return;
}
}
#if defined(_WIN32) && !defined(__CYGWIN__)
/*
* On Windows we can use Windows API for a string conversion.
*/
if (sc->flag & SCONV_WIN_CP) {
add_converter(sc, strncat_in_codepage);
return;
}
#endif
#if HAVE_ICONV
if (sc->cd != (iconv_t)-1) {
add_converter(sc, iconv_strncat_in_locale);
/*
* iconv generally does not support UTF-8-MAC and so
* we have to the output of iconv from NFC to NFD if
* need.
*/
if ((sc->flag & SCONV_FROM_CHARSET) &&
(sc->flag & SCONV_TO_UTF8)) {
if (sc->flag & SCONV_NORMALIZATION_D)
add_converter(sc, archive_string_normalize_D);
}
return;
}
#endif
/*
* Try conversion in the best effort or no conversion.
*/
if ((sc->flag & SCONV_BEST_EFFORT) || sc->same)
add_converter(sc, best_effort_strncat_in_locale);
else
/* Make sure we have no converter. */
sc->nconverter = 0;
}
/*
* Return canonicalized charset-name but this supports just UTF-8, UTF-16BE
* and CP932 which are referenced in create_sconv_object().
*/
static const char *
canonical_charset_name(const char *charset)
{
char cs[16];
char *p;
const char *s;
if (charset == NULL || charset[0] == '\0'
|| strlen(charset) > 15)
return (charset);
/* Copy name to uppercase. */
p = cs;
s = charset;
while (*s) {
char c = *s++;
if (c >= 'a' && c <= 'z')
c -= 'a' - 'A';
*p++ = c;
}
*p++ = '\0';
if (strcmp(cs, "UTF-8") == 0 ||
strcmp(cs, "UTF8") == 0)
return ("UTF-8");
if (strcmp(cs, "UTF-16BE") == 0 ||
strcmp(cs, "UTF16BE") == 0)
return ("UTF-16BE");
if (strcmp(cs, "UTF-16LE") == 0 ||
strcmp(cs, "UTF16LE") == 0)
return ("UTF-16LE");
if (strcmp(cs, "CP932") == 0)
return ("CP932");
return (charset);
}
/*
* Create a string conversion object.
*/
static struct archive_string_conv *
create_sconv_object(const char *fc, const char *tc,
unsigned current_codepage, int flag)
{
struct archive_string_conv *sc;
sc = calloc(1, sizeof(*sc));
if (sc == NULL)
return (NULL);
sc->next = NULL;
sc->from_charset = strdup(fc);
if (sc->from_charset == NULL) {
free(sc);
return (NULL);
}
sc->to_charset = strdup(tc);
if (sc->to_charset == NULL) {
free(sc->from_charset);
free(sc);
return (NULL);
}
archive_string_init(&sc->utftmp);
if (flag & SCONV_TO_CHARSET) {
/*
* Convert characters from the current locale charset to
* a specified charset.
*/
sc->from_cp = current_codepage;
sc->to_cp = make_codepage_from_charset(tc);
#if defined(_WIN32) && !defined(__CYGWIN__)
if (IsValidCodePage(sc->to_cp))
flag |= SCONV_WIN_CP;
#endif
} else if (flag & SCONV_FROM_CHARSET) {
/*
* Convert characters from a specified charset to
* the current locale charset.
*/
sc->to_cp = current_codepage;
sc->from_cp = make_codepage_from_charset(fc);
#if defined(_WIN32) && !defined(__CYGWIN__)
if (IsValidCodePage(sc->from_cp))
flag |= SCONV_WIN_CP;
#endif
}
/*
* Check if "from charset" and "to charset" are the same.
*/
if (strcmp(fc, tc) == 0 ||
(sc->from_cp != (unsigned)-1 && sc->from_cp == sc->to_cp))
sc->same = 1;
else
sc->same = 0;
/*
* Mark if "from charset" or "to charset" are UTF-8 or UTF-16BE/LE.
*/
if (strcmp(tc, "UTF-8") == 0)
flag |= SCONV_TO_UTF8;
else if (strcmp(tc, "UTF-16BE") == 0)
flag |= SCONV_TO_UTF16BE;
else if (strcmp(tc, "UTF-16LE") == 0)
flag |= SCONV_TO_UTF16LE;
if (strcmp(fc, "UTF-8") == 0)
flag |= SCONV_FROM_UTF8;
else if (strcmp(fc, "UTF-16BE") == 0)
flag |= SCONV_FROM_UTF16BE;
else if (strcmp(fc, "UTF-16LE") == 0)
flag |= SCONV_FROM_UTF16LE;
#if defined(_WIN32) && !defined(__CYGWIN__)
if (sc->to_cp == CP_UTF8)
flag |= SCONV_TO_UTF8;
else if (sc->to_cp == CP_UTF16BE)
flag |= SCONV_TO_UTF16BE | SCONV_WIN_CP;
else if (sc->to_cp == CP_UTF16LE)
flag |= SCONV_TO_UTF16LE | SCONV_WIN_CP;
if (sc->from_cp == CP_UTF8)
flag |= SCONV_FROM_UTF8;
else if (sc->from_cp == CP_UTF16BE)
flag |= SCONV_FROM_UTF16BE | SCONV_WIN_CP;
else if (sc->from_cp == CP_UTF16LE)
flag |= SCONV_FROM_UTF16LE | SCONV_WIN_CP;
#endif
/*
* Set a flag for Unicode NFD. Usually iconv cannot correctly
* handle it. So we have to translate NFD characters to NFC ones
* ourselves before iconv handles. Another reason is to prevent
* that the same sight of two filenames, one is NFC and other
* is NFD, would be in its directory.
* On Mac OS X, although its filesystem layer automatically
* convert filenames to NFD, it would be useful for filename
* comparing to find out the same filenames that we normalize
* that to be NFD ourselves.
*/
if ((flag & SCONV_FROM_CHARSET) &&
(flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8))) {
#if defined(__APPLE__)
if (flag & SCONV_TO_UTF8)
flag |= SCONV_NORMALIZATION_D;
else
#endif
flag |= SCONV_NORMALIZATION_C;
}
#if defined(__APPLE__)
/*
* In case writing an archive file, make sure that a filename
* going to be passed to iconv is a Unicode NFC string since
* a filename in HFS Plus filesystem is a Unicode NFD one and
* iconv cannot handle it with "UTF-8" charset. It is simpler
* than a use of "UTF-8-MAC" charset.
*/
if ((flag & SCONV_TO_CHARSET) &&
(flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8)) &&
!(flag & (SCONV_TO_UTF16 | SCONV_TO_UTF8)))
flag |= SCONV_NORMALIZATION_C;
/*
* In case reading an archive file. make sure that a filename
* will be passed to users is a Unicode NFD string in order to
* correctly compare the filename with other one which comes
* from HFS Plus filesystem.
*/
if ((flag & SCONV_FROM_CHARSET) &&
!(flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8)) &&
(flag & SCONV_TO_UTF8))
flag |= SCONV_NORMALIZATION_D;
#endif
#if defined(HAVE_ICONV)
sc->cd_w = (iconv_t)-1;
/*
* Create an iconv object.
*/
if (((flag & (SCONV_TO_UTF8 | SCONV_TO_UTF16)) &&
(flag & (SCONV_FROM_UTF8 | SCONV_FROM_UTF16))) ||
(flag & SCONV_WIN_CP)) {
/* This case we won't use iconv. */
sc->cd = (iconv_t)-1;
} else {
sc->cd = iconv_open(tc, fc);
if (sc->cd == (iconv_t)-1 && (sc->flag & SCONV_BEST_EFFORT)) {
/*
* Unfortunately, all of iconv implements do support
* "CP932" character-set, so we should use "SJIS"
* instead if iconv_open failed.
*/
if (strcmp(tc, "CP932") == 0)
sc->cd = iconv_open("SJIS", fc);
else if (strcmp(fc, "CP932") == 0)
sc->cd = iconv_open(tc, "SJIS");
}
#if defined(_WIN32) && !defined(__CYGWIN__)
/*
* archive_mstring on Windows directly convert multi-bytes
* into archive_wstring in order not to depend on locale
* so that you can do a I18N programming. This will be
* used only in archive_mstring_copy_mbs_len_l so far.
*/
if (flag & SCONV_FROM_CHARSET) {
sc->cd_w = iconv_open("UTF-8", fc);
if (sc->cd_w == (iconv_t)-1 &&
(sc->flag & SCONV_BEST_EFFORT)) {
if (strcmp(fc, "CP932") == 0)
sc->cd_w = iconv_open("UTF-8", "SJIS");
}
}
#endif /* _WIN32 && !__CYGWIN__ */
}
#endif /* HAVE_ICONV */
sc->flag = flag;
/*
* Set up converters.
*/
setup_converter(sc);
return (sc);
}
/*
* Free a string conversion object.
*/
static void
free_sconv_object(struct archive_string_conv *sc)
{
free(sc->from_charset);
free(sc->to_charset);
archive_string_free(&sc->utftmp);
#if HAVE_ICONV
if (sc->cd != (iconv_t)-1)
iconv_close(sc->cd);
if (sc->cd_w != (iconv_t)-1)
iconv_close(sc->cd_w);
#endif
free(sc);
}
#if defined(_WIN32) && !defined(__CYGWIN__)
static unsigned
my_atoi(const char *p)
{
unsigned cp;
cp = 0;
while (*p) {
if (*p >= '0' && *p <= '9')
cp = cp * 10 + (*p - '0');
else
return (-1);
p++;
}
return (cp);
}
/*
* Translate Charset name (as used by iconv) into CodePage (as used by Windows)
* Return -1 if failed.
*
* Note: This translation code may be insufficient.
*/
static struct charset {
const char *name;
unsigned cp;
} charsets[] = {
/* MUST BE SORTED! */
{"ASCII", 1252},
{"ASMO-708", 708},
{"BIG5", 950},
{"CHINESE", 936},
{"CP367", 1252},
{"CP819", 1252},
{"CP1025", 21025},
{"DOS-720", 720},
{"DOS-862", 862},
{"EUC-CN", 51936},
{"EUC-JP", 51932},
{"EUC-KR", 949},
{"EUCCN", 51936},
{"EUCJP", 51932},
{"EUCKR", 949},
{"GB18030", 54936},
{"GB2312", 936},
{"HEBREW", 1255},
{"HZ-GB-2312", 52936},
{"IBM273", 20273},
{"IBM277", 20277},
{"IBM278", 20278},
{"IBM280", 20280},
{"IBM284", 20284},
{"IBM285", 20285},
{"IBM290", 20290},
{"IBM297", 20297},
{"IBM367", 1252},
{"IBM420", 20420},
{"IBM423", 20423},
{"IBM424", 20424},
{"IBM819", 1252},
{"IBM871", 20871},
{"IBM880", 20880},
{"IBM905", 20905},
{"IBM924", 20924},
{"ISO-8859-1", 28591},
{"ISO-8859-13", 28603},
{"ISO-8859-15", 28605},
{"ISO-8859-2", 28592},
{"ISO-8859-3", 28593},
{"ISO-8859-4", 28594},
{"ISO-8859-5", 28595},
{"ISO-8859-6", 28596},
{"ISO-8859-7", 28597},
{"ISO-8859-8", 28598},
{"ISO-8859-9", 28599},
{"ISO8859-1", 28591},
{"ISO8859-13", 28603},
{"ISO8859-15", 28605},
{"ISO8859-2", 28592},
{"ISO8859-3", 28593},
{"ISO8859-4", 28594},
{"ISO8859-5", 28595},
{"ISO8859-6", 28596},
{"ISO8859-7", 28597},
{"ISO8859-8", 28598},
{"ISO8859-9", 28599},
{"JOHAB", 1361},
{"KOI8-R", 20866},
{"KOI8-U", 21866},
{"KS_C_5601-1987", 949},
{"LATIN1", 1252},
{"LATIN2", 28592},
{"MACINTOSH", 10000},
{"SHIFT-JIS", 932},
{"SHIFT_JIS", 932},
{"SJIS", 932},
{"US", 1252},
{"US-ASCII", 1252},
{"UTF-16", 1200},
{"UTF-16BE", 1201},
{"UTF-16LE", 1200},
{"UTF-8", CP_UTF8},
{"X-EUROPA", 29001},
{"X-MAC-ARABIC", 10004},
{"X-MAC-CE", 10029},
{"X-MAC-CHINESEIMP", 10008},
{"X-MAC-CHINESETRAD", 10002},
{"X-MAC-CROATIAN", 10082},
{"X-MAC-CYRILLIC", 10007},
{"X-MAC-GREEK", 10006},
{"X-MAC-HEBREW", 10005},
{"X-MAC-ICELANDIC", 10079},
{"X-MAC-JAPANESE", 10001},
{"X-MAC-KOREAN", 10003},
{"X-MAC-ROMANIAN", 10010},
{"X-MAC-THAI", 10021},
{"X-MAC-TURKISH", 10081},
{"X-MAC-UKRAINIAN", 10017},
};
static unsigned
make_codepage_from_charset(const char *charset)
{
char cs[16];
char *p;
unsigned cp;
int a, b;
if (charset == NULL || strlen(charset) > 15)
return -1;
/* Copy name to uppercase. */
p = cs;
while (*charset) {
char c = *charset++;
if (c >= 'a' && c <= 'z')
c -= 'a' - 'A';
*p++ = c;
}
*p++ = '\0';
cp = -1;
/* Look it up in the table first, so that we can easily
* override CP367, which we map to 1252 instead of 367. */
a = 0;
b = sizeof(charsets)/sizeof(charsets[0]);
while (b > a) {
int c = (b + a) / 2;
int r = strcmp(charsets[c].name, cs);
if (r < 0)
a = c + 1;
else if (r > 0)
b = c;
else
return charsets[c].cp;
}
/* If it's not in the table, try to parse it. */
switch (*cs) {
case 'C':
if (cs[1] == 'P' && cs[2] >= '0' && cs[2] <= '9') {
cp = my_atoi(cs + 2);
} else if (strcmp(cs, "CP_ACP") == 0)
cp = get_current_codepage();
else if (strcmp(cs, "CP_OEMCP") == 0)
cp = get_current_oemcp();
break;
case 'I':
if (cs[1] == 'B' && cs[2] == 'M' &&
cs[3] >= '0' && cs[3] <= '9') {
cp = my_atoi(cs + 3);
}
break;
case 'W':
if (strncmp(cs, "WINDOWS-", 8) == 0) {
cp = my_atoi(cs + 8);
if (cp != 874 && (cp < 1250 || cp > 1258))
cp = -1;/* This may invalid code. */
}
break;
}
return (cp);
}
/*
* Return ANSI Code Page of current locale set by setlocale().
*/
static unsigned
get_current_codepage(void)
{
char *locale, *p;
unsigned cp;
locale = setlocale(LC_CTYPE, NULL);
if (locale == NULL)
return (GetACP());
if (locale[0] == 'C' && locale[1] == '\0')
return (CP_C_LOCALE);
p = strrchr(locale, '.');
if (p == NULL)
return (GetACP());
if (strcmp(p+1, "utf8") == 0)
return CP_UTF8;
cp = my_atoi(p+1);
if ((int)cp <= 0)
return (GetACP());
return (cp);
}
/*
* Translation table between Locale Name and ACP/OEMCP.
*/
static struct {
unsigned acp;
unsigned ocp;
const char *locale;
} acp_ocp_map[] = {
{ 950, 950, "Chinese_Taiwan" },
{ 936, 936, "Chinese_People's Republic of China" },
{ 950, 950, "Chinese_Taiwan" },
{ 1250, 852, "Czech_Czech Republic" },
{ 1252, 850, "Danish_Denmark" },
{ 1252, 850, "Dutch_Netherlands" },
{ 1252, 850, "Dutch_Belgium" },
{ 1252, 437, "English_United States" },
{ 1252, 850, "English_Australia" },
{ 1252, 850, "English_Canada" },
{ 1252, 850, "English_New Zealand" },
{ 1252, 850, "English_United Kingdom" },
{ 1252, 437, "English_United States" },
{ 1252, 850, "Finnish_Finland" },
{ 1252, 850, "French_France" },
{ 1252, 850, "French_Belgium" },
{ 1252, 850, "French_Canada" },
{ 1252, 850, "French_Switzerland" },
{ 1252, 850, "German_Germany" },
{ 1252, 850, "German_Austria" },
{ 1252, 850, "German_Switzerland" },
{ 1253, 737, "Greek_Greece" },
{ 1250, 852, "Hungarian_Hungary" },
{ 1252, 850, "Icelandic_Iceland" },
{ 1252, 850, "Italian_Italy" },
{ 1252, 850, "Italian_Switzerland" },
{ 932, 932, "Japanese_Japan" },
{ 949, 949, "Korean_Korea" },
{ 1252, 850, "Norwegian (BokmOl)_Norway" },
{ 1252, 850, "Norwegian (BokmOl)_Norway" },
{ 1252, 850, "Norwegian-Nynorsk_Norway" },
{ 1250, 852, "Polish_Poland" },
{ 1252, 850, "Portuguese_Portugal" },
{ 1252, 850, "Portuguese_Brazil" },
{ 1251, 866, "Russian_Russia" },
{ 1250, 852, "Slovak_Slovakia" },
{ 1252, 850, "Spanish_Spain" },
{ 1252, 850, "Spanish_Mexico" },
{ 1252, 850, "Spanish_Spain" },
{ 1252, 850, "Swedish_Sweden" },
{ 1254, 857, "Turkish_Turkey" },
{ 0, 0, NULL}
};
/*
* Return OEM Code Page of current locale set by setlocale().
*/
static unsigned
get_current_oemcp(void)
{
int i;
char *locale, *p;
size_t len;
locale = setlocale(LC_CTYPE, NULL);
if (locale == NULL)
return (GetOEMCP());
if (locale[0] == 'C' && locale[1] == '\0')
return (CP_C_LOCALE);
p = strrchr(locale, '.');
if (p == NULL)
return (GetOEMCP());
len = p - locale;
for (i = 0; acp_ocp_map[i].acp; i++) {
if (strncmp(acp_ocp_map[i].locale, locale, len) == 0)
return (acp_ocp_map[i].ocp);
}
return (GetOEMCP());
}
#else
/*
* POSIX platform does not use CodePage.
*/
static unsigned
get_current_codepage(void)
{
return (-1);/* Unknown */
}
static unsigned
make_codepage_from_charset(const char *charset)
{
(void)charset; /* UNUSED */
return (-1);/* Unknown */
}
static unsigned
get_current_oemcp(void)
{
return (-1);/* Unknown */
}
#endif /* defined(_WIN32) && !defined(__CYGWIN__) */
/*
* Return a string conversion object.
*/
static struct archive_string_conv *
get_sconv_object(struct archive *a, const char *fc, const char *tc, int flag)
{
struct archive_string_conv *sc;
unsigned current_codepage;
/* Check if we have made the sconv object. */
sc = find_sconv_object(a, fc, tc);
if (sc != NULL)
return (sc);
if (a == NULL)
current_codepage = get_current_codepage();
else
current_codepage = a->current_codepage;
sc = create_sconv_object(canonical_charset_name(fc),
canonical_charset_name(tc), current_codepage, flag);
if (sc == NULL) {
if (a != NULL)
archive_set_error(a, ENOMEM,
"Could not allocate memory for "
"a string conversion object");
return (NULL);
}
/*
* If there is no converter for current string conversion object,
* we cannot handle this conversion.
*/
if (sc->nconverter == 0) {
if (a != NULL) {
#if HAVE_ICONV
archive_set_error(a, ARCHIVE_ERRNO_MISC,
"iconv_open failed : Cannot handle ``%s''",
(flag & SCONV_TO_CHARSET)?tc:fc);
#else
archive_set_error(a, ARCHIVE_ERRNO_MISC,
"A character-set conversion not fully supported "
"on this platform");
#endif
}
/* Failed; free a sconv object. */
free_sconv_object(sc);
return (NULL);
}
/*
* Success!
*/
if (a != NULL)
add_sconv_object(a, sc);
return (sc);
}
static const char *
get_current_charset(struct archive *a)
{
const char *cur_charset;
if (a == NULL)
cur_charset = default_iconv_charset("");
else {
cur_charset = default_iconv_charset(a->current_code);
if (a->current_code == NULL) {
a->current_code = strdup(cur_charset);
a->current_codepage = get_current_codepage();
a->current_oemcp = get_current_oemcp();
}
}
return (cur_charset);
}
/*
* Make and Return a string conversion object.
* Return NULL if the platform does not support the specified conversion
* and best_effort is 0.
* If best_effort is set, A string conversion object must be returned
* unless memory allocation for the object fails, but the conversion
* might fail when non-ASCII code is found.
*/
struct archive_string_conv *
archive_string_conversion_to_charset(struct archive *a, const char *charset,
int best_effort)
{
int flag = SCONV_TO_CHARSET;
if (best_effort)
flag |= SCONV_BEST_EFFORT;
return (get_sconv_object(a, get_current_charset(a), charset, flag));
}
struct archive_string_conv *
archive_string_conversion_from_charset(struct archive *a, const char *charset,
int best_effort)
{
int flag = SCONV_FROM_CHARSET;
if (best_effort)
flag |= SCONV_BEST_EFFORT;
return (get_sconv_object(a, charset, get_current_charset(a), flag));
}
/*
* archive_string_default_conversion_*_archive() are provided for Windows
* platform because other archiver application use CP_OEMCP for
* MultiByteToWideChar() and WideCharToMultiByte() for the filenames
* in tar or zip files. But mbstowcs/wcstombs(CRT) usually use CP_ACP
* unless you use setlocale(LC_ALL, ".OCP")(specify CP_OEMCP).
* So we should make a string conversion between CP_ACP and CP_OEMCP
* for compatibility.
*/
#if defined(_WIN32) && !defined(__CYGWIN__)
struct archive_string_conv *
archive_string_default_conversion_for_read(struct archive *a)
{
const char *cur_charset = get_current_charset(a);
char oemcp[16];
/* NOTE: a check of cur_charset is unneeded but we need
* that get_current_charset() has been surely called at
* this time whatever C compiler optimized. */
if (cur_charset != NULL &&
(a->current_codepage == CP_C_LOCALE ||
a->current_codepage == a->current_oemcp))
return (NULL);/* no conversion. */
_snprintf(oemcp, sizeof(oemcp)-1, "CP%d", a->current_oemcp);
/* Make sure a null termination must be set. */
oemcp[sizeof(oemcp)-1] = '\0';
return (get_sconv_object(a, oemcp, cur_charset,
SCONV_FROM_CHARSET));
}
struct archive_string_conv *
archive_string_default_conversion_for_write(struct archive *a)
{
const char *cur_charset = get_current_charset(a);
char oemcp[16];
/* NOTE: a check of cur_charset is unneeded but we need
* that get_current_charset() has been surely called at
* this time whatever C compiler optimized. */
if (cur_charset != NULL &&
(a->current_codepage == CP_C_LOCALE ||
a->current_codepage == a->current_oemcp))
return (NULL);/* no conversion. */
_snprintf(oemcp, sizeof(oemcp)-1, "CP%d", a->current_oemcp);
/* Make sure a null termination must be set. */
oemcp[sizeof(oemcp)-1] = '\0';
return (get_sconv_object(a, cur_charset, oemcp,
SCONV_TO_CHARSET));
}
#else
struct archive_string_conv *
archive_string_default_conversion_for_read(struct archive *a)
{
(void)a; /* UNUSED */
return (NULL);
}
struct archive_string_conv *
archive_string_default_conversion_for_write(struct archive *a)
{
(void)a; /* UNUSED */
return (NULL);
}
#endif
/*
* Dispose of all character conversion objects in the archive object.
*/
void
archive_string_conversion_free(struct archive *a)
{
struct archive_string_conv *sc;
struct archive_string_conv *sc_next;
for (sc = a->sconv; sc != NULL; sc = sc_next) {
sc_next = sc->next;
free_sconv_object(sc);
}
a->sconv = NULL;
free(a->current_code);
a->current_code = NULL;
}
/*
* Return a conversion charset name.
*/
const char *
archive_string_conversion_charset_name(struct archive_string_conv *sc)
{
if (sc->flag & SCONV_TO_CHARSET)
return (sc->to_charset);
else
return (sc->from_charset);
}
/*
* Change the behavior of a string conversion.
*/
void
archive_string_conversion_set_opt(struct archive_string_conv *sc, int opt)
{
switch (opt) {
/*
* A filename in UTF-8 was made with libarchive 2.x in a wrong
* assumption that wchar_t was Unicode.
* This option enables simulating the assumption in order to read
* that filename correctly.
*/
case SCONV_SET_OPT_UTF8_LIBARCHIVE2X:
#if (defined(_WIN32) && !defined(__CYGWIN__)) \
|| defined(__STDC_ISO_10646__) || defined(__APPLE__)
/*
* Nothing to do for it since wchar_t on these platforms
* is really Unicode.
*/
(void)sc; /* UNUSED */
#else
if ((sc->flag & SCONV_UTF8_LIBARCHIVE_2) == 0) {
sc->flag |= SCONV_UTF8_LIBARCHIVE_2;
/* Set up string converters. */
setup_converter(sc);
}
#endif
break;
case SCONV_SET_OPT_NORMALIZATION_C:
if ((sc->flag & SCONV_NORMALIZATION_C) == 0) {
sc->flag |= SCONV_NORMALIZATION_C;
sc->flag &= ~SCONV_NORMALIZATION_D;
/* Set up string converters. */
setup_converter(sc);
}
break;
case SCONV_SET_OPT_NORMALIZATION_D:
#if defined(HAVE_ICONV)
/*
* If iconv will take the string, do not change the
* setting of the normalization.
*/
if (!(sc->flag & SCONV_WIN_CP) &&
(sc->flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8)) &&
!(sc->flag & (SCONV_TO_UTF16 | SCONV_TO_UTF8)))
break;
#endif
if ((sc->flag & SCONV_NORMALIZATION_D) == 0) {
sc->flag |= SCONV_NORMALIZATION_D;
sc->flag &= ~SCONV_NORMALIZATION_C;
/* Set up string converters. */
setup_converter(sc);
}
break;
default:
break;
}
}
/*
*
* Copy one archive_string to another in locale conversion.
*
* archive_strncat_l();
* archive_strncpy_l();
*
*/
static size_t
mbsnbytes(const void *_p, size_t n)
{
size_t s;
const char *p, *pp;
if (_p == NULL)
return (0);
p = (const char *)_p;
/* Like strlen(p), except won't examine positions beyond p[n]. */
s = 0;
pp = p;
while (s < n && *pp) {
pp++;
s++;
}
return (s);
}
static size_t
utf16nbytes(const void *_p, size_t n)
{
size_t s;
const char *p, *pp;
if (_p == NULL)
return (0);
p = (const char *)_p;
/* Like strlen(p), except won't examine positions beyond p[n]. */
s = 0;
pp = p;
n >>= 1;
while (s < n && (pp[0] || pp[1])) {
pp += 2;
s++;
}
return (s<<1);
}
int
archive_strncpy_l(struct archive_string *as, const void *_p, size_t n,
struct archive_string_conv *sc)
{
as->length = 0;
return (archive_strncat_l(as, _p, n, sc));
}
int
archive_strncat_l(struct archive_string *as, const void *_p, size_t n,
struct archive_string_conv *sc)
{
const void *s;
size_t length = 0;
int i, r = 0, r2;
if (_p != NULL && n > 0) {
if (sc != NULL && (sc->flag & SCONV_FROM_UTF16))
length = utf16nbytes(_p, n);
else
length = mbsnbytes(_p, n);
}
/* We must allocate memory even if there is no data for conversion
* or copy. This simulates archive_string_append behavior. */
if (length == 0) {
int tn = 1;
if (sc != NULL && (sc->flag & SCONV_TO_UTF16))
tn = 2;
if (archive_string_ensure(as, as->length + tn) == NULL)
return (-1);
as->s[as->length] = 0;
if (tn == 2)
as->s[as->length+1] = 0;
return (0);
}
/*
* If sc is NULL, we just make a copy.
*/
if (sc == NULL) {
if (archive_string_append(as, _p, length) == NULL)
return (-1);/* No memory */
return (0);
}
s = _p;
i = 0;
if (sc->nconverter > 1) {
sc->utftmp.length = 0;
r2 = sc->converter[0](&(sc->utftmp), s, length, sc);
if (r2 != 0 && errno == ENOMEM)
return (r2);
if (r > r2)
r = r2;
s = sc->utftmp.s;
length = sc->utftmp.length;
++i;
}
r2 = sc->converter[i](as, s, length, sc);
if (r > r2)
r = r2;
return (r);
}
#if HAVE_ICONV
/*
* Return -1 if conversion fails.
*/
static int
iconv_strncat_in_locale(struct archive_string *as, const void *_p,
size_t length, struct archive_string_conv *sc)
{
ICONV_CONST char *itp;
size_t remaining;
iconv_t cd;
char *outp;
size_t avail, bs;
int return_value = 0; /* success */
int to_size, from_size;
if (sc->flag & SCONV_TO_UTF16)
to_size = 2;
else
to_size = 1;
if (sc->flag & SCONV_FROM_UTF16)
from_size = 2;
else
from_size = 1;
if (archive_string_ensure(as, as->length + length*2+to_size) == NULL)
return (-1);
cd = sc->cd;
itp = (char *)(uintptr_t)_p;
remaining = length;
outp = as->s + as->length;
avail = as->buffer_length - as->length - to_size;
while (remaining >= (size_t)from_size) {
size_t result = iconv(cd, &itp, &remaining, &outp, &avail);
if (result != (size_t)-1)
break; /* Conversion completed. */
if (errno == EILSEQ || errno == EINVAL) {
/*
* If an output charset is UTF-8 or UTF-16BE/LE,
* unknown character should be U+FFFD
* (replacement character).
*/
if (sc->flag & (SCONV_TO_UTF8 | SCONV_TO_UTF16)) {
size_t rbytes;
if (sc->flag & SCONV_TO_UTF8)
rbytes = sizeof(utf8_replacement_char);
else
rbytes = 2;
if (avail < rbytes) {
as->length = outp - as->s;
bs = as->buffer_length +
(remaining * to_size) + rbytes;
if (NULL ==
archive_string_ensure(as, bs))
return (-1);
outp = as->s + as->length;
avail = as->buffer_length
- as->length - to_size;
}
if (sc->flag & SCONV_TO_UTF8)
memcpy(outp, utf8_replacement_char, sizeof(utf8_replacement_char));
else if (sc->flag & SCONV_TO_UTF16BE)
archive_be16enc(outp, UNICODE_R_CHAR);
else
archive_le16enc(outp, UNICODE_R_CHAR);
outp += rbytes;
avail -= rbytes;
} else {
/* Skip the illegal input bytes. */
*outp++ = '?';
avail--;
}
itp += from_size;
remaining -= from_size;
return_value = -1; /* failure */
} else {
/* E2BIG no output buffer,
* Increase an output buffer. */
as->length = outp - as->s;
bs = as->buffer_length + remaining * 2;
if (NULL == archive_string_ensure(as, bs))
return (-1);
outp = as->s + as->length;
avail = as->buffer_length - as->length - to_size;
}
}
as->length = outp - as->s;
as->s[as->length] = 0;
if (to_size == 2)
as->s[as->length+1] = 0;
return (return_value);
}
#endif /* HAVE_ICONV */
#if defined(_WIN32) && !defined(__CYGWIN__)
/*
* Translate a string from a some CodePage to an another CodePage by
* Windows APIs, and copy the result. Return -1 if conversion fails.
*/
static int
strncat_in_codepage(struct archive_string *as,
const void *_p, size_t length, struct archive_string_conv *sc)
{
const char *s = (const char *)_p;
struct archive_wstring aws;
size_t l;
int r, saved_flag;
archive_string_init(&aws);
saved_flag = sc->flag;
sc->flag &= ~(SCONV_NORMALIZATION_D | SCONV_NORMALIZATION_C);
r = archive_wstring_append_from_mbs_in_codepage(&aws, s, length, sc);
sc->flag = saved_flag;
if (r != 0) {
archive_wstring_free(&aws);
if (errno != ENOMEM)
archive_string_append(as, s, length);
return (-1);
}
l = as->length;
r = archive_string_append_from_wcs_in_codepage(
as, aws.s, aws.length, sc);
if (r != 0 && errno != ENOMEM && l == as->length)
archive_string_append(as, s, length);
archive_wstring_free(&aws);
return (r);
}
/*
* Test whether MBS ==> WCS is okay.
*/
static int
invalid_mbs(const void *_p, size_t n, struct archive_string_conv *sc)
{
const char *p = (const char *)_p;
unsigned codepage;
DWORD mbflag = MB_ERR_INVALID_CHARS;
if (sc->flag & SCONV_FROM_CHARSET)
codepage = sc->to_cp;
else
codepage = sc->from_cp;
if (codepage == CP_C_LOCALE)
return (0);
if (codepage != CP_UTF8)
mbflag |= MB_PRECOMPOSED;
if (MultiByteToWideChar(codepage, mbflag, p, (int)n, NULL, 0) == 0)
return (-1); /* Invalid */
return (0); /* Okay */
}
#else
/*
* Test whether MBS ==> WCS is okay.
*/
static int
invalid_mbs(const void *_p, size_t n, struct archive_string_conv *sc)
{
const char *p = (const char *)_p;
size_t r;
#if HAVE_MBRTOWC
mbstate_t shift_state;
memset(&shift_state, 0, sizeof(shift_state));
#else
/* Clear the shift state before starting. */
mbtowc(NULL, NULL, 0);
#endif
while (n) {
wchar_t wc;
#if HAVE_MBRTOWC
r = mbrtowc(&wc, p, n, &shift_state);
#else
r = mbtowc(&wc, p, n);
#endif
if (r == (size_t)-1 || r == (size_t)-2)
return (-1);/* Invalid. */
if (r == 0)
break;
p += r;
n -= r;
}
(void)sc; /* UNUSED */
return (0); /* All Okey. */
}
#endif /* defined(_WIN32) && !defined(__CYGWIN__) */
/*
* Basically returns -1 because we cannot make a conversion of charset
* without iconv but in some cases this would return 0.
* Returns 0 if all copied characters are ASCII.
* Returns 0 if both from-locale and to-locale are the same and those
* can be WCS with no error.
*/
static int
best_effort_strncat_in_locale(struct archive_string *as, const void *_p,
size_t length, struct archive_string_conv *sc)
{
size_t remaining;
const uint8_t *itp;
int return_value = 0; /* success */
/*
* If both from-locale and to-locale is the same, this makes a copy.
* And then this checks all copied MBS can be WCS if so returns 0.
*/
if (sc->same) {
if (archive_string_append(as, _p, length) == NULL)
return (-1);/* No memory */
return (invalid_mbs(_p, length, sc));
}
/*
* If a character is ASCII, this just copies it. If not, this
* assigns '?' character instead but in UTF-8 locale this assigns
* byte sequence 0xEF 0xBD 0xBD, which are code point U+FFFD,
* a Replacement Character in Unicode.
*/
remaining = length;
itp = (const uint8_t *)_p;
while (*itp && remaining > 0) {
if (*itp > 127) {
// Non-ASCII: Substitute with suitable replacement
if (sc->flag & SCONV_TO_UTF8) {
if (archive_string_append(as, utf8_replacement_char, sizeof(utf8_replacement_char)) == NULL) {
__archive_errx(1, "Out of memory");
}
} else {
archive_strappend_char(as, '?');
}
return_value = -1;
} else {
archive_strappend_char(as, *itp);
}
++itp;
}
return (return_value);
}
/*
* Unicode conversion functions.
* - UTF-8 <===> UTF-8 in removing surrogate pairs.
* - UTF-8 NFD ===> UTF-8 NFC in removing surrogate pairs.
* - UTF-8 made by libarchive 2.x ===> UTF-8.
* - UTF-16BE <===> UTF-8.
*
*/
/*
* Utility to convert a single UTF-8 sequence.
*
* Usually return used bytes, return used byte in negative value when
* a unicode character is replaced with U+FFFD.
* See also http://unicode.org/review/pr-121.html Public Review Issue #121
* Recommended Practice for Replacement Characters.
*/
static int
_utf8_to_unicode(uint32_t *pwc, const char *s, size_t n)
{
static const char utf8_count[256] = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 00 - 0F */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 10 - 1F */
1, 1, 1, 1, 1, 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 */
1, 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, 1, 1, 1, 1, 1,/* 50 - 5F */
1, 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, 1, 1, 1, 1, 1,/* 70 - 7F */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 80 - 8F */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 90 - 9F */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* A0 - AF */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* B0 - BF */
0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/* C0 - CF */
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/* D0 - DF */
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,/* E0 - EF */
4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* F0 - FF */
};
int ch, i;
int cnt;
uint32_t wc;
/* Sanity check. */
if (n == 0)
return (0);
/*
* Decode 1-4 bytes depending on the value of the first byte.
*/
ch = (unsigned char)*s;
if (ch == 0)
return (0); /* Standard: return 0 for end-of-string. */
cnt = utf8_count[ch];
/* Invalid sequence or there are not plenty bytes. */
if ((int)n < cnt) {
cnt = (int)n;
for (i = 1; i < cnt; i++) {
if ((s[i] & 0xc0) != 0x80) {
cnt = i;
break;
}
}
goto invalid_sequence;
}
/* Make a Unicode code point from a single UTF-8 sequence. */
switch (cnt) {
case 1: /* 1 byte sequence. */
*pwc = ch & 0x7f;
return (cnt);
case 2: /* 2 bytes sequence. */
if ((s[1] & 0xc0) != 0x80) {
cnt = 1;
goto invalid_sequence;
}
*pwc = ((ch & 0x1f) << 6) | (s[1] & 0x3f);
return (cnt);
case 3: /* 3 bytes sequence. */
if ((s[1] & 0xc0) != 0x80) {
cnt = 1;
goto invalid_sequence;
}
if ((s[2] & 0xc0) != 0x80) {
cnt = 2;
goto invalid_sequence;
}
wc = ((ch & 0x0f) << 12)
| ((s[1] & 0x3f) << 6)
| (s[2] & 0x3f);
if (wc < 0x800)
goto invalid_sequence;/* Overlong sequence. */
break;
case 4: /* 4 bytes sequence. */
if ((s[1] & 0xc0) != 0x80) {
cnt = 1;
goto invalid_sequence;
}
if ((s[2] & 0xc0) != 0x80) {
cnt = 2;
goto invalid_sequence;
}
if ((s[3] & 0xc0) != 0x80) {
cnt = 3;
goto invalid_sequence;
}
wc = ((ch & 0x07) << 18)
| ((s[1] & 0x3f) << 12)
| ((s[2] & 0x3f) << 6)
| (s[3] & 0x3f);
if (wc < 0x10000)
goto invalid_sequence;/* Overlong sequence. */
break;
default: /* Others are all invalid sequence. */
if (ch == 0xc0 || ch == 0xc1)
cnt = 2;
else if (ch >= 0xf5 && ch <= 0xf7)
cnt = 4;
else if (ch >= 0xf8 && ch <= 0xfb)
cnt = 5;
else if (ch == 0xfc || ch == 0xfd)
cnt = 6;
else
cnt = 1;
if ((int)n < cnt)
cnt = (int)n;
for (i = 1; i < cnt; i++) {
if ((s[i] & 0xc0) != 0x80) {
cnt = i;
break;
}
}
goto invalid_sequence;
}
/* The code point larger than 0x10FFFF is not legal
* Unicode values. */
if (wc > UNICODE_MAX)
goto invalid_sequence;
/* Correctly gets a Unicode, returns used bytes. */
*pwc = wc;
return (cnt);
invalid_sequence:
*pwc = UNICODE_R_CHAR;/* set the Replacement Character instead. */
return (cnt * -1);
}
static int
utf8_to_unicode(uint32_t *pwc, const char *s, size_t n)
{
int cnt;
cnt = _utf8_to_unicode(pwc, s, n);
/* Any of Surrogate pair is not legal Unicode values. */
if (cnt == 3 && IS_SURROGATE_PAIR_LA(*pwc))
return (-3);
return (cnt);
}
static inline uint32_t
combine_surrogate_pair(uint32_t uc, uint32_t uc2)
{
uc -= 0xD800;
uc *= 0x400;
uc += uc2 - 0xDC00;
uc += 0x10000;
return (uc);
}
/*
* Convert a single UTF-8/CESU-8 sequence to a Unicode code point in
* removing surrogate pairs.
*
* CESU-8: The Compatibility Encoding Scheme for UTF-16.
*
* Usually return used bytes, return used byte in negative value when
* a unicode character is replaced with U+FFFD.
*/
static int
cesu8_to_unicode(uint32_t *pwc, const char *s, size_t n)
{
uint32_t wc = 0;
int cnt;
cnt = _utf8_to_unicode(&wc, s, n);
if (cnt == 3 && IS_HIGH_SURROGATE_LA(wc)) {
uint32_t wc2 = 0;
if (n - 3 < 3) {
/* Invalid byte sequence. */
goto invalid_sequence;
}
cnt = _utf8_to_unicode(&wc2, s+3, n-3);
if (cnt != 3 || !IS_LOW_SURROGATE_LA(wc2)) {
/* Invalid byte sequence. */
goto invalid_sequence;
}
wc = combine_surrogate_pair(wc, wc2);
cnt = 6;
} else if (cnt == 3 && IS_LOW_SURROGATE_LA(wc)) {
/* Invalid byte sequence. */
goto invalid_sequence;
}
*pwc = wc;
return (cnt);
invalid_sequence:
*pwc = UNICODE_R_CHAR;/* set the Replacement Character instead. */
if (cnt > 0)
cnt *= -1;
return (cnt);
}
/*
* Convert a Unicode code point to a single UTF-8 sequence.
*
* NOTE:This function does not check if the Unicode is legal or not.
* Please you definitely check it before calling this.
*/
static size_t
unicode_to_utf8(char *p, size_t remaining, uint32_t uc)
{
char *_p = p;
/* Invalid Unicode char maps to Replacement character */
if (uc > UNICODE_MAX)
uc = UNICODE_R_CHAR;
/* Translate code point to UTF8 */
if (uc <= 0x7f) {
if (remaining == 0)
return (0);
*p++ = (char)uc;
} else if (uc <= 0x7ff) {
if (remaining < 2)
return (0);
*p++ = 0xc0 | ((uc >> 6) & 0x1f);
*p++ = 0x80 | (uc & 0x3f);
} else if (uc <= 0xffff) {
if (remaining < 3)
return (0);
*p++ = 0xe0 | ((uc >> 12) & 0x0f);
*p++ = 0x80 | ((uc >> 6) & 0x3f);
*p++ = 0x80 | (uc & 0x3f);
} else {
if (remaining < 4)
return (0);
*p++ = 0xf0 | ((uc >> 18) & 0x07);
*p++ = 0x80 | ((uc >> 12) & 0x3f);
*p++ = 0x80 | ((uc >> 6) & 0x3f);
*p++ = 0x80 | (uc & 0x3f);
}
return (p - _p);
}
static int
utf16be_to_unicode(uint32_t *pwc, const char *s, size_t n)
{
return (utf16_to_unicode(pwc, s, n, 1));
}
static int
utf16le_to_unicode(uint32_t *pwc, const char *s, size_t n)
{
return (utf16_to_unicode(pwc, s, n, 0));
}
static int
utf16_to_unicode(uint32_t *pwc, const char *s, size_t n, int be)
{
const char *utf16 = s;
unsigned uc;
if (n == 0)
return (0);
if (n == 1) {
/* set the Replacement Character instead. */
*pwc = UNICODE_R_CHAR;
return (-1);
}
if (be)
uc = archive_be16dec(utf16);
else
uc = archive_le16dec(utf16);
utf16 += 2;
/* If this is a surrogate pair, assemble the full code point.*/
if (IS_HIGH_SURROGATE_LA(uc)) {
unsigned uc2;
if (n >= 4) {
if (be)
uc2 = archive_be16dec(utf16);
else
uc2 = archive_le16dec(utf16);
} else
uc2 = 0;
if (IS_LOW_SURROGATE_LA(uc2)) {
uc = combine_surrogate_pair(uc, uc2);
utf16 += 2;
} else {
/* Undescribed code point should be U+FFFD
* (replacement character). */
*pwc = UNICODE_R_CHAR;
return (-2);
}
}
/*
* Surrogate pair values(0xd800 through 0xdfff) are only
* used by UTF-16, so, after above calculation, the code
* must not be surrogate values, and Unicode has no codes
* larger than 0x10ffff. Thus, those are not legal Unicode
* values.
*/
if (IS_SURROGATE_PAIR_LA(uc) || uc > UNICODE_MAX) {
/* Undescribed code point should be U+FFFD
* (replacement character). */
*pwc = UNICODE_R_CHAR;
return (((int)(utf16 - s)) * -1);
}
*pwc = uc;
return ((int)(utf16 - s));
}
static size_t
unicode_to_utf16be(char *p, size_t remaining, uint32_t uc)
{
char *utf16 = p;
if (uc > 0xffff) {
/* We have a code point that won't fit into a
* wchar_t; convert it to a surrogate pair. */
if (remaining < 4)
return (0);
uc -= 0x10000;
archive_be16enc(utf16, ((uc >> 10) & 0x3ff) + 0xD800);
archive_be16enc(utf16+2, (uc & 0x3ff) + 0xDC00);
return (4);
} else {
if (remaining < 2)
return (0);
archive_be16enc(utf16, uc);
return (2);
}
}
static size_t
unicode_to_utf16le(char *p, size_t remaining, uint32_t uc)
{
char *utf16 = p;
if (uc > 0xffff) {
/* We have a code point that won't fit into a
* wchar_t; convert it to a surrogate pair. */
if (remaining < 4)
return (0);
uc -= 0x10000;
archive_le16enc(utf16, ((uc >> 10) & 0x3ff) + 0xD800);
archive_le16enc(utf16+2, (uc & 0x3ff) + 0xDC00);
return (4);
} else {
if (remaining < 2)
return (0);
archive_le16enc(utf16, uc);
return (2);
}
}
/*
* Copy UTF-8 string in checking surrogate pair.
* If any surrogate pair are found, it would be canonicalized.
*/
static int
strncat_from_utf8_to_utf8(struct archive_string *as, const void *_p,
size_t len, struct archive_string_conv *sc)
{
const char *s;
char *p, *endp;
int n, ret = 0;
(void)sc; /* UNUSED */
if (archive_string_ensure(as, as->length + len + 1) == NULL)
return (-1);
s = (const char *)_p;
p = as->s + as->length;
endp = as->s + as->buffer_length -1;
do {
uint32_t uc;
const char *ss = s;
size_t w;
/*
* Forward byte sequence until a conversion of that is needed.
*/
while ((n = utf8_to_unicode(&uc, s, len)) > 0) {
s += n;
len -= n;
}
if (ss < s) {
if (p + (s - ss) > endp) {
as->length = p - as->s;
if (archive_string_ensure(as,
as->buffer_length + len + 1) == NULL)
return (-1);
p = as->s + as->length;
endp = as->s + as->buffer_length -1;
}
memcpy(p, ss, s - ss);
p += s - ss;
}
/*
* If n is negative, current byte sequence needs a replacement.
*/
if (n < 0) {
if (n == -3 && IS_SURROGATE_PAIR_LA(uc)) {
/* Current byte sequence may be CESU-8. */
n = cesu8_to_unicode(&uc, s, len);
}
if (n < 0) {
ret = -1;
n *= -1;/* Use a replaced unicode character. */
}
/* Rebuild UTF-8 byte sequence. */
while ((w = unicode_to_utf8(p, endp - p, uc)) == 0) {
as->length = p - as->s;
if (archive_string_ensure(as,
as->buffer_length + len + 1) == NULL)
return (-1);
p = as->s + as->length;
endp = as->s + as->buffer_length -1;
}
p += w;
s += n;
len -= n;
}
} while (n > 0);
as->length = p - as->s;
as->s[as->length] = '\0';
return (ret);
}
static int
archive_string_append_unicode(struct archive_string *as, const void *_p,
size_t len, struct archive_string_conv *sc)
{
const char *s;
char *p, *endp;
uint32_t uc;
size_t w;
int n, ret = 0, ts, tm;
int (*parse)(uint32_t *, const char *, size_t);
size_t (*unparse)(char *, size_t, uint32_t);
if (sc->flag & SCONV_TO_UTF16BE) {
unparse = unicode_to_utf16be;
ts = 2;
} else if (sc->flag & SCONV_TO_UTF16LE) {
unparse = unicode_to_utf16le;
ts = 2;
} else if (sc->flag & SCONV_TO_UTF8) {
unparse = unicode_to_utf8;
ts = 1;
} else {
/*
* This case is going to be converted to another
* character-set through iconv.
*/
if (sc->flag & SCONV_FROM_UTF16BE) {
unparse = unicode_to_utf16be;
ts = 2;
} else if (sc->flag & SCONV_FROM_UTF16LE) {
unparse = unicode_to_utf16le;
ts = 2;
} else {
unparse = unicode_to_utf8;
ts = 1;
}
}
if (sc->flag & SCONV_FROM_UTF16BE) {
parse = utf16be_to_unicode;
tm = 1;
} else if (sc->flag & SCONV_FROM_UTF16LE) {
parse = utf16le_to_unicode;
tm = 1;
} else {
parse = cesu8_to_unicode;
tm = ts;
}
if (archive_string_ensure(as, as->length + len * tm + ts) == NULL)
return (-1);
s = (const char *)_p;
p = as->s + as->length;
endp = as->s + as->buffer_length - ts;
while ((n = parse(&uc, s, len)) != 0) {
if (n < 0) {
/* Use a replaced unicode character. */
n *= -1;
ret = -1;
}
s += n;
len -= n;
while ((w = unparse(p, endp - p, uc)) == 0) {
/* There is not enough output buffer so
* we have to expand it. */
as->length = p - as->s;
if (archive_string_ensure(as,
as->buffer_length + len * tm + ts) == NULL)
return (-1);
p = as->s + as->length;
endp = as->s + as->buffer_length - ts;
}
p += w;
}
as->length = p - as->s;
as->s[as->length] = '\0';
if (ts == 2)
as->s[as->length+1] = '\0';
return (ret);
}
/*
* Following Constants for Hangul compositions this information comes from
* Unicode Standard Annex #15 http://unicode.org/reports/tr15/
*/
#define HC_SBASE 0xAC00
#define HC_LBASE 0x1100
#define HC_VBASE 0x1161
#define HC_TBASE 0x11A7
#define HC_LCOUNT 19
#define HC_VCOUNT 21
#define HC_TCOUNT 28
#define HC_NCOUNT (HC_VCOUNT * HC_TCOUNT)
#define HC_SCOUNT (HC_LCOUNT * HC_NCOUNT)
static uint32_t
get_nfc(uint32_t uc, uint32_t uc2)
{
int t, b;
t = 0;
b = sizeof(u_composition_table)/sizeof(u_composition_table[0]) -1;
while (b >= t) {
int m = (t + b) / 2;
if (u_composition_table[m].cp1 < uc)
t = m + 1;
else if (u_composition_table[m].cp1 > uc)
b = m - 1;
else if (u_composition_table[m].cp2 < uc2)
t = m + 1;
else if (u_composition_table[m].cp2 > uc2)
b = m - 1;
else
return (u_composition_table[m].nfc);
}
return (0);
}
#define FDC_MAX 10 /* The maximum number of Following Decomposable
* Characters. */
/*
* Update first code point.
*/
#define UPDATE_UC(new_uc) do { \
uc = new_uc; \
ucptr = NULL; \
} while (0)
/*
* Replace first code point with second code point.
*/
#define REPLACE_UC_WITH_UC2() do { \
uc = uc2; \
ucptr = uc2ptr; \
n = n2; \
} while (0)
#define EXPAND_BUFFER() do { \
as->length = p - as->s; \
if (archive_string_ensure(as, \
as->buffer_length + len * tm + ts) == NULL)\
return (-1); \
p = as->s + as->length; \
endp = as->s + as->buffer_length - ts; \
} while (0)
#define UNPARSE(p, endp, uc) do { \
while ((w = unparse(p, (endp) - (p), uc)) == 0) {\
EXPAND_BUFFER(); \
} \
p += w; \
} while (0)
/*
* Write first code point.
* If the code point has not be changed from its original code,
* this just copies it from its original buffer pointer.
* If not, this converts it to UTF-8 byte sequence and copies it.
*/
#define WRITE_UC() do { \
if (ucptr) { \
if (p + n > endp) \
EXPAND_BUFFER(); \
switch (n) { \
case 4: \
*p++ = *ucptr++; \
/* FALL THROUGH */ \
case 3: \
*p++ = *ucptr++; \
/* FALL THROUGH */ \
case 2: \
*p++ = *ucptr++; \
/* FALL THROUGH */ \
case 1: \
*p++ = *ucptr; \
break; \
} \
ucptr = NULL; \
} else { \
UNPARSE(p, endp, uc); \
} \
} while (0)
/*
* Collect following decomposable code points.
*/
#define COLLECT_CPS(start) do { \
int _i; \
for (_i = start; _i < FDC_MAX ; _i++) { \
nx = parse(&ucx[_i], s, len); \
if (nx <= 0) \
break; \
cx = CCC(ucx[_i]); \
if (cl >= cx && cl != 228 && cx != 228)\
break; \
s += nx; \
len -= nx; \
cl = cx; \
ccx[_i] = cx; \
} \
if (_i >= FDC_MAX) { \
ret = -1; \
ucx_size = FDC_MAX; \
} else \
ucx_size = _i; \
} while (0)
/*
* Normalize UTF-8/UTF-16BE characters to Form C and copy the result.
*
* TODO: Convert composition exclusions, which are never converted
* from NFC,NFD,NFKC and NFKD, to Form C.
*/
static int
archive_string_normalize_C(struct archive_string *as, const void *_p,
size_t len, struct archive_string_conv *sc)
{
const char *s = (const char *)_p;
char *p, *endp;
uint32_t uc, uc2;
size_t w;
int always_replace, n, n2, ret = 0, spair, ts, tm;
int (*parse)(uint32_t *, const char *, size_t);
size_t (*unparse)(char *, size_t, uint32_t);
always_replace = 1;
ts = 1;/* text size. */
if (sc->flag & SCONV_TO_UTF16BE) {
unparse = unicode_to_utf16be;
ts = 2;
if (sc->flag & SCONV_FROM_UTF16BE)
always_replace = 0;
} else if (sc->flag & SCONV_TO_UTF16LE) {
unparse = unicode_to_utf16le;
ts = 2;
if (sc->flag & SCONV_FROM_UTF16LE)
always_replace = 0;
} else if (sc->flag & SCONV_TO_UTF8) {
unparse = unicode_to_utf8;
if (sc->flag & SCONV_FROM_UTF8)
always_replace = 0;
} else {
/*
* This case is going to be converted to another
* character-set through iconv.
*/
always_replace = 0;
if (sc->flag & SCONV_FROM_UTF16BE) {
unparse = unicode_to_utf16be;
ts = 2;
} else if (sc->flag & SCONV_FROM_UTF16LE) {
unparse = unicode_to_utf16le;
ts = 2;
} else {
unparse = unicode_to_utf8;
}
}
if (sc->flag & SCONV_FROM_UTF16BE) {
parse = utf16be_to_unicode;
tm = 1;
spair = 4;/* surrogate pair size in UTF-16. */
} else if (sc->flag & SCONV_FROM_UTF16LE) {
parse = utf16le_to_unicode;
tm = 1;
spair = 4;/* surrogate pair size in UTF-16. */
} else {
parse = cesu8_to_unicode;
tm = ts;
spair = 6;/* surrogate pair size in UTF-8. */
}
if (archive_string_ensure(as, as->length + len * tm + ts) == NULL)
return (-1);
p = as->s + as->length;
endp = as->s + as->buffer_length - ts;
while ((n = parse(&uc, s, len)) != 0) {
const char *ucptr, *uc2ptr;
if (n < 0) {
/* Use a replaced unicode character. */
UNPARSE(p, endp, uc);
s += n*-1;
len -= n*-1;
ret = -1;
continue;
} else if (n == spair || always_replace)
/* uc is converted from a surrogate pair.
* this should be treated as a changed code. */
ucptr = NULL;
else
ucptr = s;
s += n;
len -= n;
/* Read second code point. */
while ((n2 = parse(&uc2, s, len)) > 0) {
uint32_t ucx[FDC_MAX];
int ccx[FDC_MAX];
int cl, cx, i, nx, ucx_size;
int LIndex,SIndex;
uint32_t nfc;
if (n2 == spair || always_replace)
/* uc2 is converted from a surrogate pair.
* this should be treated as a changed code. */
uc2ptr = NULL;
else
uc2ptr = s;
s += n2;
len -= n2;
/*
* If current second code point is out of decomposable
* code points, finding compositions is unneeded.
*/
if (!IS_DECOMPOSABLE_BLOCK(uc2)) {
WRITE_UC();
REPLACE_UC_WITH_UC2();
continue;
}
/*
* Try to combine current code points.
*/
/*
* We have to combine Hangul characters according to
* http://uniicode.org/reports/tr15/#Hangul
*/
if (0 <= (LIndex = uc - HC_LBASE) &&
LIndex < HC_LCOUNT) {
/*
* Hangul Composition.
* 1. Two current code points are L and V.
*/
int VIndex = uc2 - HC_VBASE;
if (0 <= VIndex && VIndex < HC_VCOUNT) {
/* Make syllable of form LV. */
UPDATE_UC(HC_SBASE +
(LIndex * HC_VCOUNT + VIndex) *
HC_TCOUNT);
} else {
WRITE_UC();
REPLACE_UC_WITH_UC2();
}
continue;
} else if (0 <= (SIndex = uc - HC_SBASE) &&
SIndex < HC_SCOUNT && (SIndex % HC_TCOUNT) == 0) {
/*
* Hangul Composition.
* 2. Two current code points are LV and T.
*/
int TIndex = uc2 - HC_TBASE;
if (0 < TIndex && TIndex < HC_TCOUNT) {
/* Make syllable of form LVT. */
UPDATE_UC(uc + TIndex);
} else {
WRITE_UC();
REPLACE_UC_WITH_UC2();
}
continue;
} else if ((nfc = get_nfc(uc, uc2)) != 0) {
/* A composition to current code points
* is found. */
UPDATE_UC(nfc);
continue;
} else if ((cl = CCC(uc2)) == 0) {
/* Clearly 'uc2' the second code point is not
* a decomposable code. */
WRITE_UC();
REPLACE_UC_WITH_UC2();
continue;
}
/*
* Collect following decomposable code points.
*/
cx = 0;
ucx[0] = uc2;
ccx[0] = cl;
COLLECT_CPS(1);
/*
* Find a composed code in the collected code points.
*/
i = 1;
while (i < ucx_size) {
int j;
if ((nfc = get_nfc(uc, ucx[i])) == 0) {
i++;
continue;
}
/*
* nfc is composed of uc and ucx[i].
*/
UPDATE_UC(nfc);
/*
* Remove ucx[i] by shifting
* following code points.
*/
for (j = i; j+1 < ucx_size; j++) {
ucx[j] = ucx[j+1];
ccx[j] = ccx[j+1];
}
ucx_size --;
/*
* Collect following code points blocked
* by ucx[i] the removed code point.
*/
if (ucx_size > 0 && i == ucx_size &&
nx > 0 && cx == cl) {
cl = ccx[ucx_size-1];
COLLECT_CPS(ucx_size);
}
/*
* Restart finding a composed code with
* the updated uc from the top of the
* collected code points.
*/
i = 0;
}
/*
* Apparently the current code points are not
* decomposed characters or already composed.
*/
WRITE_UC();
for (i = 0; i < ucx_size; i++)
UNPARSE(p, endp, ucx[i]);
/*
* Flush out remaining canonical combining characters.
*/
if (nx > 0 && cx == cl && len > 0) {
while ((nx = parse(&ucx[0], s, len))
> 0) {
cx = CCC(ucx[0]);
if (cl > cx)
break;
s += nx;
len -= nx;
cl = cx;
UNPARSE(p, endp, ucx[0]);
}
}
break;
}
if (n2 < 0) {
WRITE_UC();
/* Use a replaced unicode character. */
UNPARSE(p, endp, uc2);
s += n2*-1;
len -= n2*-1;
ret = -1;
continue;
} else if (n2 == 0) {
WRITE_UC();
break;
}
}
as->length = p - as->s;
as->s[as->length] = '\0';
if (ts == 2)
as->s[as->length+1] = '\0';
return (ret);
}
static int
get_nfd(uint32_t *cp1, uint32_t *cp2, uint32_t uc)
{
int t, b;
/*
* These are not converted to NFD on Mac OS.
*/
if ((uc >= 0x2000 && uc <= 0x2FFF) ||
(uc >= 0xF900 && uc <= 0xFAFF) ||
(uc >= 0x2F800 && uc <= 0x2FAFF))
return (0);
/*
* Those code points are not converted to NFD on Mac OS.
* I do not know the reason because it is undocumented.
* NFC NFD
* 1109A ==> 11099 110BA
* 1109C ==> 1109B 110BA
* 110AB ==> 110A5 110BA
*/
if (uc == 0x1109A || uc == 0x1109C || uc == 0x110AB)
return (0);
t = 0;
b = sizeof(u_decomposition_table)/sizeof(u_decomposition_table[0]) -1;
while (b >= t) {
int m = (t + b) / 2;
if (u_decomposition_table[m].nfc < uc)
t = m + 1;
else if (u_decomposition_table[m].nfc > uc)
b = m - 1;
else {
*cp1 = u_decomposition_table[m].cp1;
*cp2 = u_decomposition_table[m].cp2;
return (1);
}
}
return (0);
}
#define REPLACE_UC_WITH(cp) do { \
uc = cp; \
ucptr = NULL; \
} while (0)
/*
* Normalize UTF-8 characters to Form D and copy the result.
*/
static int
archive_string_normalize_D(struct archive_string *as, const void *_p,
size_t len, struct archive_string_conv *sc)
{
const char *s = (const char *)_p;
char *p, *endp;
uint32_t uc, uc2;
size_t w;
int always_replace, n, n2, ret = 0, spair, ts, tm;
int (*parse)(uint32_t *, const char *, size_t);
size_t (*unparse)(char *, size_t, uint32_t);
always_replace = 1;
ts = 1;/* text size. */
if (sc->flag & SCONV_TO_UTF16BE) {
unparse = unicode_to_utf16be;
ts = 2;
if (sc->flag & SCONV_FROM_UTF16BE)
always_replace = 0;
} else if (sc->flag & SCONV_TO_UTF16LE) {
unparse = unicode_to_utf16le;
ts = 2;
if (sc->flag & SCONV_FROM_UTF16LE)
always_replace = 0;
} else if (sc->flag & SCONV_TO_UTF8) {
unparse = unicode_to_utf8;
if (sc->flag & SCONV_FROM_UTF8)
always_replace = 0;
} else {
/*
* This case is going to be converted to another
* character-set through iconv.
*/
always_replace = 0;
if (sc->flag & SCONV_FROM_UTF16BE) {
unparse = unicode_to_utf16be;
ts = 2;
} else if (sc->flag & SCONV_FROM_UTF16LE) {
unparse = unicode_to_utf16le;
ts = 2;
} else {
unparse = unicode_to_utf8;
}
}
if (sc->flag & SCONV_FROM_UTF16BE) {
parse = utf16be_to_unicode;
tm = 1;
spair = 4;/* surrogate pair size in UTF-16. */
} else if (sc->flag & SCONV_FROM_UTF16LE) {
parse = utf16le_to_unicode;
tm = 1;
spair = 4;/* surrogate pair size in UTF-16. */
} else {
parse = cesu8_to_unicode;
tm = ts;
spair = 6;/* surrogate pair size in UTF-8. */
}
if (archive_string_ensure(as, as->length + len * tm + ts) == NULL)
return (-1);
p = as->s + as->length;
endp = as->s + as->buffer_length - ts;
while ((n = parse(&uc, s, len)) != 0) {
const char *ucptr;
uint32_t cp1, cp2;
int SIndex;
struct {
uint32_t uc;
int ccc;
} fdc[FDC_MAX];
int fdi, fdj;
int ccc;
check_first_code:
if (n < 0) {
/* Use a replaced unicode character. */
UNPARSE(p, endp, uc);
s += n*-1;
len -= n*-1;
ret = -1;
continue;
} else if (n == spair || always_replace)
/* uc is converted from a surrogate pair.
* this should be treated as a changed code. */
ucptr = NULL;
else
ucptr = s;
s += n;
len -= n;
/* Hangul Decomposition. */
if ((SIndex = uc - HC_SBASE) >= 0 && SIndex < HC_SCOUNT) {
int L = HC_LBASE + SIndex / HC_NCOUNT;
int V = HC_VBASE + (SIndex % HC_NCOUNT) / HC_TCOUNT;
int T = HC_TBASE + SIndex % HC_TCOUNT;
REPLACE_UC_WITH(L);
WRITE_UC();
REPLACE_UC_WITH(V);
WRITE_UC();
if (T != HC_TBASE) {
REPLACE_UC_WITH(T);
WRITE_UC();
}
continue;
}
if (IS_DECOMPOSABLE_BLOCK(uc) && CCC(uc) != 0) {
WRITE_UC();
continue;
}
fdi = 0;
while (get_nfd(&cp1, &cp2, uc) && fdi < FDC_MAX) {
int k;
for (k = fdi; k > 0; k--)
fdc[k] = fdc[k-1];
fdc[0].ccc = CCC(cp2);
fdc[0].uc = cp2;
fdi++;
REPLACE_UC_WITH(cp1);
}
/* Read following code points. */
while ((n2 = parse(&uc2, s, len)) > 0 &&
(ccc = CCC(uc2)) != 0 && fdi < FDC_MAX) {
int j, k;
s += n2;
len -= n2;
for (j = 0; j < fdi; j++) {
if (fdc[j].ccc > ccc)
break;
}
if (j < fdi) {
for (k = fdi; k > j; k--)
fdc[k] = fdc[k-1];
fdc[j].ccc = ccc;
fdc[j].uc = uc2;
} else {
fdc[fdi].ccc = ccc;
fdc[fdi].uc = uc2;
}
fdi++;
}
WRITE_UC();
for (fdj = 0; fdj < fdi; fdj++) {
REPLACE_UC_WITH(fdc[fdj].uc);
WRITE_UC();
}
if (n2 == 0)
break;
REPLACE_UC_WITH(uc2);
n = n2;
goto check_first_code;
}
as->length = p - as->s;
as->s[as->length] = '\0';
if (ts == 2)
as->s[as->length+1] = '\0';
return (ret);
}
/*
* libarchive 2.x made incorrect UTF-8 strings in the wrong assumption
* that WCS is Unicode. It is true for several platforms but some are false.
* And then people who did not use UTF-8 locale on the non Unicode WCS
* platform and made a tar file with libarchive(mostly bsdtar) 2.x. Those
* now cannot get right filename from libarchive 3.x and later since we
* fixed the wrong assumption and it is incompatible to older its versions.
* So we provide special option, "compat-2x.x", for resolving it.
* That option enable the string conversion of libarchive 2.x.
*
* Translates the wrong UTF-8 string made by libarchive 2.x into current
* locale character set and appends to the archive_string.
* Note: returns -1 if conversion fails.
*/
static int
strncat_from_utf8_libarchive2(struct archive_string *as,
const void *_p, size_t len, struct archive_string_conv *sc)
{
const char *s;
int n;
char *p;
char *end;
uint32_t unicode;
#if HAVE_WCRTOMB
mbstate_t shift_state;
memset(&shift_state, 0, sizeof(shift_state));
#else
/* Clear the shift state before starting. */
wctomb(NULL, L'\0');
#endif
(void)sc; /* UNUSED */
/*
* Allocate buffer for MBS.
* We need this allocation here since it is possible that
* as->s is still NULL.
*/
if (archive_string_ensure(as, as->length + len + 1) == NULL)
return (-1);
s = (const char *)_p;
p = as->s + as->length;
end = as->s + as->buffer_length - MB_CUR_MAX -1;
while ((n = _utf8_to_unicode(&unicode, s, len)) != 0) {
wchar_t wc;
if (p >= end) {
as->length = p - as->s;
/* Re-allocate buffer for MBS. */
if (archive_string_ensure(as,
as->length + len * 2 + 1) == NULL)
return (-1);
p = as->s + as->length;
end = as->s + as->buffer_length - MB_CUR_MAX -1;
}
/*
* As libarchive 2.x, translates the UTF-8 characters into
* wide-characters in the assumption that WCS is Unicode.
*/
if (n < 0) {
n *= -1;
wc = L'?';
} else
wc = (wchar_t)unicode;
s += n;
len -= n;
/*
* Translates the wide-character into the current locale MBS.
*/
#if HAVE_WCRTOMB
n = (int)wcrtomb(p, wc, &shift_state);
#else
n = (int)wctomb(p, wc);
#endif
if (n == -1)
return (-1);
p += n;
}
as->length = p - as->s;
as->s[as->length] = '\0';
return (0);
}
/*
* Conversion functions between current locale dependent MBS and UTF-16BE.
* strncat_from_utf16be() : UTF-16BE --> MBS
* strncat_to_utf16be() : MBS --> UTF16BE
*/
#if defined(_WIN32) && !defined(__CYGWIN__)
/*
* Convert a UTF-16BE/LE string to current locale and copy the result.
* Return -1 if conversion fails.
*/
static int
win_strncat_from_utf16(struct archive_string *as, const void *_p, size_t bytes,
struct archive_string_conv *sc, int be)
{
struct archive_string tmp;
const char *u16;
int ll;
BOOL defchar;
char *mbs;
size_t mbs_size, b;
int ret = 0;
bytes &= ~1;
if (archive_string_ensure(as, as->length + bytes +1) == NULL)
return (-1);
mbs = as->s + as->length;
mbs_size = as->buffer_length - as->length -1;
if (sc->to_cp == CP_C_LOCALE) {
/*
* "C" locale special process.
*/
u16 = _p;
ll = 0;
for (b = 0; b < bytes; b += 2) {
uint16_t val;
if (be)
val = archive_be16dec(u16+b);
else
val = archive_le16dec(u16+b);
if (val > 255) {
*mbs++ = '?';
ret = -1;
} else
*mbs++ = (char)(val&0xff);
ll++;
}
as->length += ll;
as->s[as->length] = '\0';
return (ret);
}
archive_string_init(&tmp);
if (be) {
if (is_big_endian()) {
u16 = _p;
} else {
if (archive_string_ensure(&tmp, bytes+2) == NULL)
return (-1);
memcpy(tmp.s, _p, bytes);
for (b = 0; b < bytes; b += 2) {
uint16_t val = archive_be16dec(tmp.s+b);
archive_le16enc(tmp.s+b, val);
}
u16 = tmp.s;
}
} else {
if (!is_big_endian()) {
u16 = _p;
} else {
if (archive_string_ensure(&tmp, bytes+2) == NULL)
return (-1);
memcpy(tmp.s, _p, bytes);
for (b = 0; b < bytes; b += 2) {
uint16_t val = archive_le16dec(tmp.s+b);
archive_be16enc(tmp.s+b, val);
}
u16 = tmp.s;
}
}
do {
defchar = 0;
ll = WideCharToMultiByte(sc->to_cp, 0,
(LPCWSTR)u16, (int)bytes>>1, mbs, (int)mbs_size,
NULL, &defchar);
/* Exit loop if we succeeded */
if (ll != 0 ||
GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
break;
}
/* Else expand buffer and loop to try again. */
ll = WideCharToMultiByte(sc->to_cp, 0,
(LPCWSTR)u16, (int)bytes, NULL, 0, NULL, NULL);
if (archive_string_ensure(as, ll +1) == NULL)
return (-1);
mbs = as->s + as->length;
mbs_size = as->buffer_length - as->length -1;
} while (1);
archive_string_free(&tmp);
as->length += ll;
as->s[as->length] = '\0';
if (ll == 0 || defchar)
ret = -1;
return (ret);
}
static int
win_strncat_from_utf16be(struct archive_string *as, const void *_p,
size_t bytes, struct archive_string_conv *sc)
{
return (win_strncat_from_utf16(as, _p, bytes, sc, 1));
}
static int
win_strncat_from_utf16le(struct archive_string *as, const void *_p,
size_t bytes, struct archive_string_conv *sc)
{
return (win_strncat_from_utf16(as, _p, bytes, sc, 0));
}
static int
is_big_endian(void)
{
uint16_t d = 1;
return (archive_be16dec(&d) == 1);
}
/*
* Convert a current locale string to UTF-16BE/LE and copy the result.
* Return -1 if conversion fails.
*/
static int
win_strncat_to_utf16(struct archive_string *as16, const void *_p,
size_t length, struct archive_string_conv *sc, int bigendian)
{
const char *s = (const char *)_p;
char *u16;
size_t count, avail;
if (archive_string_ensure(as16,
as16->length + (length + 1) * 2) == NULL)
return (-1);
u16 = as16->s + as16->length;
avail = as16->buffer_length - 2;
if (sc->from_cp == CP_C_LOCALE) {
/*
* "C" locale special process.
*/
count = 0;
while (count < length && *s) {
if (bigendian)
archive_be16enc(u16, *s);
else
archive_le16enc(u16, *s);
u16 += 2;
s++;
count++;
}
as16->length += count << 1;
as16->s[as16->length] = 0;
as16->s[as16->length+1] = 0;
return (0);
}
do {
count = MultiByteToWideChar(sc->from_cp,
MB_PRECOMPOSED, s, (int)length, (LPWSTR)u16, (int)avail>>1);
/* Exit loop if we succeeded */
if (count != 0 ||
GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
break;
}
/* Expand buffer and try again */
count = MultiByteToWideChar(sc->from_cp,
MB_PRECOMPOSED, s, (int)length, NULL, 0);
if (archive_string_ensure(as16, (count +1) * 2)
== NULL)
return (-1);
u16 = as16->s + as16->length;
avail = as16->buffer_length - 2;
} while (1);
as16->length += count * 2;
as16->s[as16->length] = 0;
as16->s[as16->length+1] = 0;
if (count == 0)
return (-1);
if (is_big_endian()) {
if (!bigendian) {
while (count > 0) {
uint16_t v = archive_be16dec(u16);
archive_le16enc(u16, v);
u16 += 2;
count--;
}
}
} else {
if (bigendian) {
while (count > 0) {
uint16_t v = archive_le16dec(u16);
archive_be16enc(u16, v);
u16 += 2;
count--;
}
}
}
return (0);
}
static int
win_strncat_to_utf16be(struct archive_string *as16, const void *_p,
size_t length, struct archive_string_conv *sc)
{
return (win_strncat_to_utf16(as16, _p, length, sc, 1));
}
static int
win_strncat_to_utf16le(struct archive_string *as16, const void *_p,
size_t length, struct archive_string_conv *sc)
{
return (win_strncat_to_utf16(as16, _p, length, sc, 0));
}
#endif /* _WIN32 && !__CYGWIN__ */
/*
* Do the best effort for conversions.
* We cannot handle UTF-16BE character-set without such iconv,
* but there is a chance if a string consists just ASCII code or
* a current locale is UTF-8.
*/
/*
* Convert a UTF-16BE string to current locale and copy the result.
* Return -1 if conversion fails.
*/
static int
best_effort_strncat_from_utf16(struct archive_string *as, const void *_p,
size_t bytes, struct archive_string_conv *sc, int be)
{
const char *utf16 = (const char *)_p;
char *mbs;
uint32_t uc;
int n, ret;
(void)sc; /* UNUSED */
/*
* Other case, we should do the best effort.
* If all character are ASCII(<0x7f), we can convert it.
* if not , we set a alternative character and return -1.
*/
ret = 0;
if (archive_string_ensure(as, as->length + bytes +1) == NULL)
return (-1);
mbs = as->s + as->length;
while ((n = utf16_to_unicode(&uc, utf16, bytes, be)) != 0) {
if (n < 0) {
n *= -1;
ret = -1;
}
bytes -= n;
utf16 += n;
if (uc > 127) {
/* We cannot handle it. */
*mbs++ = '?';
ret = -1;
} else
*mbs++ = (char)uc;
}
as->length = mbs - as->s;
as->s[as->length] = '\0';
return (ret);
}
static int
best_effort_strncat_from_utf16be(struct archive_string *as, const void *_p,
size_t bytes, struct archive_string_conv *sc)
{
return (best_effort_strncat_from_utf16(as, _p, bytes, sc, 1));
}
static int
best_effort_strncat_from_utf16le(struct archive_string *as, const void *_p,
size_t bytes, struct archive_string_conv *sc)
{
return (best_effort_strncat_from_utf16(as, _p, bytes, sc, 0));
}
/*
* Convert a current locale string to UTF-16BE/LE and copy the result.
* Return -1 if conversion fails.
*/
static int
best_effort_strncat_to_utf16(struct archive_string *as16, const void *_p,
size_t length, struct archive_string_conv *sc, int bigendian)
{
const char *s = (const char *)_p;
char *utf16;
size_t remaining;
int ret;
(void)sc; /* UNUSED */
/*
* Other case, we should do the best effort.
* If all character are ASCII(<0x7f), we can convert it.
* if not , we set a alternative character and return -1.
*/
ret = 0;
remaining = length;
if (archive_string_ensure(as16,
as16->length + (length + 1) * 2) == NULL)
return (-1);
utf16 = as16->s + as16->length;
while (remaining--) {
unsigned c = *s++;
if (c > 127) {
/* We cannot handle it. */
c = UNICODE_R_CHAR;
ret = -1;
}
if (bigendian)
archive_be16enc(utf16, c);
else
archive_le16enc(utf16, c);
utf16 += 2;
}
as16->length = utf16 - as16->s;
as16->s[as16->length] = 0;
as16->s[as16->length+1] = 0;
return (ret);
}
static int
best_effort_strncat_to_utf16be(struct archive_string *as16, const void *_p,
size_t length, struct archive_string_conv *sc)
{
return (best_effort_strncat_to_utf16(as16, _p, length, sc, 1));
}
static int
best_effort_strncat_to_utf16le(struct archive_string *as16, const void *_p,
size_t length, struct archive_string_conv *sc)
{
return (best_effort_strncat_to_utf16(as16, _p, length, sc, 0));
}
/*
* Multistring operations.
*/
void
archive_mstring_clean(struct archive_mstring *aes)
{
archive_wstring_free(&(aes->aes_wcs));
archive_string_free(&(aes->aes_mbs));
archive_string_free(&(aes->aes_utf8));
archive_string_free(&(aes->aes_mbs_in_locale));
aes->aes_set = 0;
}
void
archive_mstring_copy(struct archive_mstring *dest, struct archive_mstring *src)
{
dest->aes_set = src->aes_set;
archive_string_copy(&(dest->aes_mbs), &(src->aes_mbs));
archive_string_copy(&(dest->aes_utf8), &(src->aes_utf8));
archive_wstring_copy(&(dest->aes_wcs), &(src->aes_wcs));
}
int
archive_mstring_get_utf8(struct archive *a, struct archive_mstring *aes,
const char **p)
{
struct archive_string_conv *sc;
int r;
/* If we already have a UTF8 form, return that immediately. */
if (aes->aes_set & AES_SET_UTF8) {
*p = aes->aes_utf8.s;
return (0);
}
*p = NULL;
if (aes->aes_set & AES_SET_MBS) {
sc = archive_string_conversion_to_charset(a, "UTF-8", 1);
if (sc == NULL)
return (-1);/* Couldn't allocate memory for sc. */
r = archive_strncpy_l(&(aes->aes_utf8), aes->aes_mbs.s,
aes->aes_mbs.length, sc);
if (a == NULL)
free_sconv_object(sc);
if (r == 0) {
aes->aes_set |= AES_SET_UTF8;
*p = aes->aes_utf8.s;
return (0);/* success. */
} else
return (-1);/* failure. */
}
return (0);/* success. */
}
int
archive_mstring_get_mbs(struct archive *a, struct archive_mstring *aes,
const char **p)
{
int r, ret = 0;
(void)a; /* UNUSED */
/* If we already have an MBS form, return that immediately. */
if (aes->aes_set & AES_SET_MBS) {
*p = aes->aes_mbs.s;
return (ret);
}
*p = NULL;
/* If there's a WCS form, try converting with the native locale. */
if (aes->aes_set & AES_SET_WCS) {
archive_string_empty(&(aes->aes_mbs));
r = archive_string_append_from_wcs(&(aes->aes_mbs),
aes->aes_wcs.s, aes->aes_wcs.length);
*p = aes->aes_mbs.s;
if (r == 0) {
aes->aes_set |= AES_SET_MBS;
return (ret);
} else
ret = -1;
}
/*
* Only a UTF-8 form cannot avail because its conversion already
* failed at archive_mstring_update_utf8().
*/
return (ret);
}
int
archive_mstring_get_wcs(struct archive *a, struct archive_mstring *aes,
const wchar_t **wp)
{
int r, ret = 0;
(void)a;/* UNUSED */
/* Return WCS form if we already have it. */
if (aes->aes_set & AES_SET_WCS) {
*wp = aes->aes_wcs.s;
return (ret);
}
*wp = NULL;
/* Try converting MBS to WCS using native locale. */
if (aes->aes_set & AES_SET_MBS) {
archive_wstring_empty(&(aes->aes_wcs));
r = archive_wstring_append_from_mbs(&(aes->aes_wcs),
aes->aes_mbs.s, aes->aes_mbs.length);
if (r == 0) {
aes->aes_set |= AES_SET_WCS;
*wp = aes->aes_wcs.s;
} else
ret = -1;/* failure. */
}
return (ret);
}
int
archive_mstring_get_mbs_l(struct archive_mstring *aes,
const char **p, size_t *length, struct archive_string_conv *sc)
{
int r, ret = 0;
#if defined(_WIN32) && !defined(__CYGWIN__)
/*
* Internationalization programming on Windows must use Wide
* characters because Windows platform cannot make locale UTF-8.
*/
if (sc != NULL && (aes->aes_set & AES_SET_WCS) != 0) {
archive_string_empty(&(aes->aes_mbs_in_locale));
r = archive_string_append_from_wcs_in_codepage(
&(aes->aes_mbs_in_locale), aes->aes_wcs.s,
aes->aes_wcs.length, sc);
if (r == 0) {
*p = aes->aes_mbs_in_locale.s;
if (length != NULL)
*length = aes->aes_mbs_in_locale.length;
return (0);
} else if (errno == ENOMEM)
return (-1);
else
ret = -1;
}
#endif
/* If there is not an MBS form but is a WCS form, try converting
* with the native locale to be used for translating it to specified
* character-set. */
if ((aes->aes_set & AES_SET_MBS) == 0 &&
(aes->aes_set & AES_SET_WCS) != 0) {
archive_string_empty(&(aes->aes_mbs));
r = archive_string_append_from_wcs(&(aes->aes_mbs),
aes->aes_wcs.s, aes->aes_wcs.length);
if (r == 0)
aes->aes_set |= AES_SET_MBS;
else if (errno == ENOMEM)
return (-1);
else
ret = -1;
}
/* If we already have an MBS form, use it to be translated to
* specified character-set. */
if (aes->aes_set & AES_SET_MBS) {
if (sc == NULL) {
/* Conversion is unneeded. */
*p = aes->aes_mbs.s;
if (length != NULL)
*length = aes->aes_mbs.length;
return (0);
}
ret = archive_strncpy_l(&(aes->aes_mbs_in_locale),
aes->aes_mbs.s, aes->aes_mbs.length, sc);
*p = aes->aes_mbs_in_locale.s;
if (length != NULL)
*length = aes->aes_mbs_in_locale.length;
} else {
*p = NULL;
if (length != NULL)
*length = 0;
}
return (ret);
}
int
archive_mstring_copy_mbs(struct archive_mstring *aes, const char *mbs)
{
if (mbs == NULL) {
aes->aes_set = 0;
return (0);
}
return (archive_mstring_copy_mbs_len(aes, mbs, strlen(mbs)));
}
int
archive_mstring_copy_mbs_len(struct archive_mstring *aes, const char *mbs,
size_t len)
{
if (mbs == NULL) {
aes->aes_set = 0;
return (0);
}
aes->aes_set = AES_SET_MBS; /* Only MBS form is set now. */
archive_strncpy(&(aes->aes_mbs), mbs, len);
archive_string_empty(&(aes->aes_utf8));
archive_wstring_empty(&(aes->aes_wcs));
return (0);
}
int
archive_mstring_copy_wcs(struct archive_mstring *aes, const wchar_t *wcs)
{
return archive_mstring_copy_wcs_len(aes, wcs,
wcs == NULL ? 0 : wcslen(wcs));
}
int
archive_mstring_copy_utf8(struct archive_mstring *aes, const char *utf8)
{
if (utf8 == NULL) {
aes->aes_set = 0;
return (0);
}
aes->aes_set = AES_SET_UTF8;
archive_string_empty(&(aes->aes_mbs));
archive_string_empty(&(aes->aes_wcs));
archive_strncpy(&(aes->aes_utf8), utf8, strlen(utf8));
return (int)strlen(utf8);
}
int
archive_mstring_copy_wcs_len(struct archive_mstring *aes, const wchar_t *wcs,
size_t len)
{
if (wcs == NULL) {
aes->aes_set = 0;
return (0);
}
aes->aes_set = AES_SET_WCS; /* Only WCS form set. */
archive_string_empty(&(aes->aes_mbs));
archive_string_empty(&(aes->aes_utf8));
archive_wstrncpy(&(aes->aes_wcs), wcs, len);
return (0);
}
int
archive_mstring_copy_mbs_len_l(struct archive_mstring *aes,
const char *mbs, size_t len, struct archive_string_conv *sc)
{
int r;
if (mbs == NULL) {
aes->aes_set = 0;
return (0);
}
archive_string_empty(&(aes->aes_mbs));
archive_wstring_empty(&(aes->aes_wcs));
archive_string_empty(&(aes->aes_utf8));
#if defined(_WIN32) && !defined(__CYGWIN__)
/*
* Internationalization programming on Windows must use Wide
* characters because Windows platform cannot make locale UTF-8.
*/
if (sc == NULL) {
if (archive_string_append(&(aes->aes_mbs),
mbs, mbsnbytes(mbs, len)) == NULL) {
aes->aes_set = 0;
r = -1;
} else {
aes->aes_set = AES_SET_MBS;
r = 0;
}
#if defined(HAVE_ICONV)
} else if (sc != NULL && sc->cd_w != (iconv_t)-1) {
/*
* This case happens only when MultiByteToWideChar() cannot
* handle sc->from_cp, and we have to iconv in order to
* translate character-set to wchar_t,UTF-16.
*/
iconv_t cd = sc->cd;
unsigned from_cp;
int flag;
/*
* Translate multi-bytes from some character-set to UTF-8.
*/
sc->cd = sc->cd_w;
r = archive_strncpy_l(&(aes->aes_utf8), mbs, len, sc);
sc->cd = cd;
if (r != 0) {
aes->aes_set = 0;
return (r);
}
aes->aes_set = AES_SET_UTF8;
/*
* Append the UTF-8 string into wstring.
*/
flag = sc->flag;
sc->flag &= ~(SCONV_NORMALIZATION_C
| SCONV_TO_UTF16| SCONV_FROM_UTF16);
from_cp = sc->from_cp;
sc->from_cp = CP_UTF8;
r = archive_wstring_append_from_mbs_in_codepage(&(aes->aes_wcs),
aes->aes_utf8.s, aes->aes_utf8.length, sc);
sc->flag = flag;
sc->from_cp = from_cp;
if (r == 0)
aes->aes_set |= AES_SET_WCS;
#endif
} else {
r = archive_wstring_append_from_mbs_in_codepage(
&(aes->aes_wcs), mbs, len, sc);
if (r == 0)
aes->aes_set = AES_SET_WCS;
else
aes->aes_set = 0;
}
#else
r = archive_strncpy_l(&(aes->aes_mbs), mbs, len, sc);
if (r == 0)
aes->aes_set = AES_SET_MBS; /* Only MBS form is set now. */
else
aes->aes_set = 0;
#endif
return (r);
}
/*
* The 'update' form tries to proactively update all forms of
* this string (WCS and MBS) and returns an error if any of
* them fail. This is used by the 'pax' handler, for instance,
* to detect and report character-conversion failures early while
* still allowing clients to get potentially useful values from
* the more tolerant lazy conversions. (get_mbs and get_wcs will
* strive to give the user something useful, so you can get hopefully
* usable values even if some of the character conversions are failing.)
*/
int
archive_mstring_update_utf8(struct archive *a, struct archive_mstring *aes,
const char *utf8)
{
struct archive_string_conv *sc;
int r;
if (utf8 == NULL) {
aes->aes_set = 0;
return (0); /* Succeeded in clearing everything. */
}
/* Save the UTF8 string. */
archive_strcpy(&(aes->aes_utf8), utf8);
/* Empty the mbs and wcs strings. */
archive_string_empty(&(aes->aes_mbs));
archive_wstring_empty(&(aes->aes_wcs));
aes->aes_set = AES_SET_UTF8; /* Only UTF8 is set now. */
/* Try converting UTF-8 to MBS, return false on failure. */
sc = archive_string_conversion_from_charset(a, "UTF-8", 1);
if (sc == NULL)
return (-1);/* Couldn't allocate memory for sc. */
r = archive_strcpy_l(&(aes->aes_mbs), utf8, sc);
if (a == NULL)
free_sconv_object(sc);
if (r != 0)
return (-1);
aes->aes_set = AES_SET_UTF8 | AES_SET_MBS; /* Both UTF8 and MBS set. */
/* Try converting MBS to WCS, return false on failure. */
if (archive_wstring_append_from_mbs(&(aes->aes_wcs), aes->aes_mbs.s,
aes->aes_mbs.length))
return (-1);
aes->aes_set = AES_SET_UTF8 | AES_SET_WCS | AES_SET_MBS;
/* All conversions succeeded. */
return (0);
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_4265_0 |
crossvul-cpp_data_good_4036_0 | /*
* QEMU Executable loader
*
* Copyright (c) 2006 Fabrice Bellard
*
* 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.
*
* Gunzip functionality in this file is derived from u-boot:
*
* (C) Copyright 2008 Semihalf
*
* (C) Copyright 2000-2005
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include "qemu/osdep.h"
#include "qapi/error.h"
#include "hw/hw.h"
#include "disas/disas.h"
#include "monitor/monitor.h"
#include "sysemu/sysemu.h"
#include "uboot_image.h"
#include "hw/loader.h"
#include "hw/nvram/fw_cfg.h"
#include "exec/memory.h"
#include "exec/address-spaces.h"
#include "hw/boards.h"
#include "qemu/cutils.h"
#include <zlib.h>
static int roms_loaded;
/* return the size or -1 if error */
int64_t get_image_size(const char *filename)
{
int fd;
int64_t size;
fd = open(filename, O_RDONLY | O_BINARY);
if (fd < 0)
return -1;
size = lseek(fd, 0, SEEK_END);
close(fd);
return size;
}
/* return the size or -1 if error */
ssize_t load_image_size(const char *filename, void *addr, size_t size)
{
int fd;
ssize_t actsize, l = 0;
fd = open(filename, O_RDONLY | O_BINARY);
if (fd < 0) {
return -1;
}
while ((actsize = read(fd, addr + l, size - l)) > 0) {
l += actsize;
}
close(fd);
return actsize < 0 ? -1 : l;
}
/* read()-like version */
ssize_t read_targphys(const char *name,
int fd, hwaddr dst_addr, size_t nbytes)
{
uint8_t *buf;
ssize_t did;
buf = g_malloc(nbytes);
did = read(fd, buf, nbytes);
if (did > 0)
rom_add_blob_fixed("read", buf, did, dst_addr);
g_free(buf);
return did;
}
int load_image_targphys(const char *filename,
hwaddr addr, uint64_t max_sz)
{
return load_image_targphys_as(filename, addr, max_sz, NULL);
}
/* return the size or -1 if error */
int load_image_targphys_as(const char *filename,
hwaddr addr, uint64_t max_sz, AddressSpace *as)
{
int size;
size = get_image_size(filename);
if (size < 0 || size > max_sz) {
return -1;
}
if (size > 0) {
if (rom_add_file_fixed_as(filename, addr, -1, as) < 0) {
return -1;
}
}
return size;
}
int load_image_mr(const char *filename, MemoryRegion *mr)
{
int size;
if (!memory_access_is_direct(mr, false)) {
/* Can only load an image into RAM or ROM */
return -1;
}
size = get_image_size(filename);
if (size < 0 || size > memory_region_size(mr)) {
return -1;
}
if (size > 0) {
if (rom_add_file_mr(filename, mr, -1) < 0) {
return -1;
}
}
return size;
}
void pstrcpy_targphys(const char *name, hwaddr dest, int buf_size,
const char *source)
{
const char *nulp;
char *ptr;
if (buf_size <= 0) return;
nulp = memchr(source, 0, buf_size);
if (nulp) {
rom_add_blob_fixed(name, source, (nulp - source) + 1, dest);
} else {
rom_add_blob_fixed(name, source, buf_size, dest);
ptr = rom_ptr(dest + buf_size - 1, sizeof(*ptr));
*ptr = 0;
}
}
/* A.OUT loader */
struct exec
{
uint32_t a_info; /* Use macros N_MAGIC, etc for access */
uint32_t a_text; /* length of text, in bytes */
uint32_t a_data; /* length of data, in bytes */
uint32_t a_bss; /* length of uninitialized data area, in bytes */
uint32_t a_syms; /* length of symbol table data in file, in bytes */
uint32_t a_entry; /* start address */
uint32_t a_trsize; /* length of relocation info for text, in bytes */
uint32_t a_drsize; /* length of relocation info for data, in bytes */
};
static void bswap_ahdr(struct exec *e)
{
bswap32s(&e->a_info);
bswap32s(&e->a_text);
bswap32s(&e->a_data);
bswap32s(&e->a_bss);
bswap32s(&e->a_syms);
bswap32s(&e->a_entry);
bswap32s(&e->a_trsize);
bswap32s(&e->a_drsize);
}
#define N_MAGIC(exec) ((exec).a_info & 0xffff)
#define OMAGIC 0407
#define NMAGIC 0410
#define ZMAGIC 0413
#define QMAGIC 0314
#define _N_HDROFF(x) (1024 - sizeof (struct exec))
#define N_TXTOFF(x) \
(N_MAGIC(x) == ZMAGIC ? _N_HDROFF((x)) + sizeof (struct exec) : \
(N_MAGIC(x) == QMAGIC ? 0 : sizeof (struct exec)))
#define N_TXTADDR(x, target_page_size) (N_MAGIC(x) == QMAGIC ? target_page_size : 0)
#define _N_SEGMENT_ROUND(x, target_page_size) (((x) + target_page_size - 1) & ~(target_page_size - 1))
#define _N_TXTENDADDR(x, target_page_size) (N_TXTADDR(x, target_page_size)+(x).a_text)
#define N_DATADDR(x, target_page_size) \
(N_MAGIC(x)==OMAGIC? (_N_TXTENDADDR(x, target_page_size)) \
: (_N_SEGMENT_ROUND (_N_TXTENDADDR(x, target_page_size), target_page_size)))
int load_aout(const char *filename, hwaddr addr, int max_sz,
int bswap_needed, hwaddr target_page_size)
{
int fd;
ssize_t size, ret;
struct exec e;
uint32_t magic;
fd = open(filename, O_RDONLY | O_BINARY);
if (fd < 0)
return -1;
size = read(fd, &e, sizeof(e));
if (size < 0)
goto fail;
if (bswap_needed) {
bswap_ahdr(&e);
}
magic = N_MAGIC(e);
switch (magic) {
case ZMAGIC:
case QMAGIC:
case OMAGIC:
if (e.a_text + e.a_data > max_sz)
goto fail;
lseek(fd, N_TXTOFF(e), SEEK_SET);
size = read_targphys(filename, fd, addr, e.a_text + e.a_data);
if (size < 0)
goto fail;
break;
case NMAGIC:
if (N_DATADDR(e, target_page_size) + e.a_data > max_sz)
goto fail;
lseek(fd, N_TXTOFF(e), SEEK_SET);
size = read_targphys(filename, fd, addr, e.a_text);
if (size < 0)
goto fail;
ret = read_targphys(filename, fd, addr + N_DATADDR(e, target_page_size),
e.a_data);
if (ret < 0)
goto fail;
size += ret;
break;
default:
goto fail;
}
close(fd);
return size;
fail:
close(fd);
return -1;
}
/* ELF loader */
static void *load_at(int fd, off_t offset, size_t size)
{
void *ptr;
if (lseek(fd, offset, SEEK_SET) < 0)
return NULL;
ptr = g_malloc(size);
if (read(fd, ptr, size) != size) {
g_free(ptr);
return NULL;
}
return ptr;
}
#ifdef ELF_CLASS
#undef ELF_CLASS
#endif
#define ELF_CLASS ELFCLASS32
#include "elf.h"
#define SZ 32
#define elf_word uint32_t
#define elf_sword int32_t
#define bswapSZs bswap32s
#include "hw/elf_ops.h"
#undef elfhdr
#undef elf_phdr
#undef elf_shdr
#undef elf_sym
#undef elf_rela
#undef elf_note
#undef elf_word
#undef elf_sword
#undef bswapSZs
#undef SZ
#define elfhdr elf64_hdr
#define elf_phdr elf64_phdr
#define elf_note elf64_note
#define elf_shdr elf64_shdr
#define elf_sym elf64_sym
#define elf_rela elf64_rela
#define elf_word uint64_t
#define elf_sword int64_t
#define bswapSZs bswap64s
#define SZ 64
#include "hw/elf_ops.h"
const char *load_elf_strerror(int error)
{
switch (error) {
case 0:
return "No error";
case ELF_LOAD_FAILED:
return "Failed to load ELF";
case ELF_LOAD_NOT_ELF:
return "The image is not ELF";
case ELF_LOAD_WRONG_ARCH:
return "The image is from incompatible architecture";
case ELF_LOAD_WRONG_ENDIAN:
return "The image has incorrect endianness";
default:
return "Unknown error";
}
}
void load_elf_hdr(const char *filename, void *hdr, bool *is64, Error **errp)
{
int fd;
uint8_t e_ident_local[EI_NIDENT];
uint8_t *e_ident;
size_t hdr_size, off;
bool is64l;
if (!hdr) {
hdr = e_ident_local;
}
e_ident = hdr;
fd = open(filename, O_RDONLY | O_BINARY);
if (fd < 0) {
error_setg_errno(errp, errno, "Failed to open file: %s", filename);
return;
}
if (read(fd, hdr, EI_NIDENT) != EI_NIDENT) {
error_setg_errno(errp, errno, "Failed to read file: %s", filename);
goto fail;
}
if (e_ident[0] != ELFMAG0 ||
e_ident[1] != ELFMAG1 ||
e_ident[2] != ELFMAG2 ||
e_ident[3] != ELFMAG3) {
error_setg(errp, "Bad ELF magic");
goto fail;
}
is64l = e_ident[EI_CLASS] == ELFCLASS64;
hdr_size = is64l ? sizeof(Elf64_Ehdr) : sizeof(Elf32_Ehdr);
if (is64) {
*is64 = is64l;
}
off = EI_NIDENT;
while (hdr != e_ident_local && off < hdr_size) {
size_t br = read(fd, hdr + off, hdr_size - off);
switch (br) {
case 0:
error_setg(errp, "File too short: %s", filename);
goto fail;
case -1:
error_setg_errno(errp, errno, "Failed to read file: %s",
filename);
goto fail;
}
off += br;
}
fail:
close(fd);
}
/* return < 0 if error, otherwise the number of bytes loaded in memory */
int load_elf(const char *filename,
uint64_t (*elf_note_fn)(void *, void *, bool),
uint64_t (*translate_fn)(void *, uint64_t),
void *translate_opaque, uint64_t *pentry, uint64_t *lowaddr,
uint64_t *highaddr, int big_endian, int elf_machine,
int clear_lsb, int data_swab)
{
return load_elf_as(filename, elf_note_fn, translate_fn, translate_opaque,
pentry, lowaddr, highaddr, big_endian, elf_machine,
clear_lsb, data_swab, NULL);
}
/* return < 0 if error, otherwise the number of bytes loaded in memory */
int load_elf_as(const char *filename,
uint64_t (*elf_note_fn)(void *, void *, bool),
uint64_t (*translate_fn)(void *, uint64_t),
void *translate_opaque, uint64_t *pentry, uint64_t *lowaddr,
uint64_t *highaddr, int big_endian, int elf_machine,
int clear_lsb, int data_swab, AddressSpace *as)
{
return load_elf_ram(filename, elf_note_fn, translate_fn, translate_opaque,
pentry, lowaddr, highaddr, big_endian, elf_machine,
clear_lsb, data_swab, as, true);
}
/* return < 0 if error, otherwise the number of bytes loaded in memory */
int load_elf_ram(const char *filename,
uint64_t (*elf_note_fn)(void *, void *, bool),
uint64_t (*translate_fn)(void *, uint64_t),
void *translate_opaque, uint64_t *pentry, uint64_t *lowaddr,
uint64_t *highaddr, int big_endian, int elf_machine,
int clear_lsb, int data_swab, AddressSpace *as,
bool load_rom)
{
return load_elf_ram_sym(filename, elf_note_fn,
translate_fn, translate_opaque,
pentry, lowaddr, highaddr, big_endian,
elf_machine, clear_lsb, data_swab, as,
load_rom, NULL);
}
/* return < 0 if error, otherwise the number of bytes loaded in memory */
int load_elf_ram_sym(const char *filename,
uint64_t (*elf_note_fn)(void *, void *, bool),
uint64_t (*translate_fn)(void *, uint64_t),
void *translate_opaque, uint64_t *pentry,
uint64_t *lowaddr, uint64_t *highaddr, int big_endian,
int elf_machine, int clear_lsb, int data_swab,
AddressSpace *as, bool load_rom, symbol_fn_t sym_cb)
{
int fd, data_order, target_data_order, must_swab, ret = ELF_LOAD_FAILED;
uint8_t e_ident[EI_NIDENT];
fd = open(filename, O_RDONLY | O_BINARY);
if (fd < 0) {
perror(filename);
return -1;
}
if (read(fd, e_ident, sizeof(e_ident)) != sizeof(e_ident))
goto fail;
if (e_ident[0] != ELFMAG0 ||
e_ident[1] != ELFMAG1 ||
e_ident[2] != ELFMAG2 ||
e_ident[3] != ELFMAG3) {
ret = ELF_LOAD_NOT_ELF;
goto fail;
}
#ifdef HOST_WORDS_BIGENDIAN
data_order = ELFDATA2MSB;
#else
data_order = ELFDATA2LSB;
#endif
must_swab = data_order != e_ident[EI_DATA];
if (big_endian) {
target_data_order = ELFDATA2MSB;
} else {
target_data_order = ELFDATA2LSB;
}
if (target_data_order != e_ident[EI_DATA]) {
ret = ELF_LOAD_WRONG_ENDIAN;
goto fail;
}
lseek(fd, 0, SEEK_SET);
if (e_ident[EI_CLASS] == ELFCLASS64) {
ret = load_elf64(filename, fd, elf_note_fn,
translate_fn, translate_opaque, must_swab,
pentry, lowaddr, highaddr, elf_machine, clear_lsb,
data_swab, as, load_rom, sym_cb);
} else {
ret = load_elf32(filename, fd, elf_note_fn,
translate_fn, translate_opaque, must_swab,
pentry, lowaddr, highaddr, elf_machine, clear_lsb,
data_swab, as, load_rom, sym_cb);
}
fail:
close(fd);
return ret;
}
static void bswap_uboot_header(uboot_image_header_t *hdr)
{
#ifndef HOST_WORDS_BIGENDIAN
bswap32s(&hdr->ih_magic);
bswap32s(&hdr->ih_hcrc);
bswap32s(&hdr->ih_time);
bswap32s(&hdr->ih_size);
bswap32s(&hdr->ih_load);
bswap32s(&hdr->ih_ep);
bswap32s(&hdr->ih_dcrc);
#endif
}
#define ZALLOC_ALIGNMENT 16
static void *zalloc(void *x, unsigned items, unsigned size)
{
void *p;
size *= items;
size = (size + ZALLOC_ALIGNMENT - 1) & ~(ZALLOC_ALIGNMENT - 1);
p = g_malloc(size);
return (p);
}
static void zfree(void *x, void *addr)
{
g_free(addr);
}
#define HEAD_CRC 2
#define EXTRA_FIELD 4
#define ORIG_NAME 8
#define COMMENT 0x10
#define RESERVED 0xe0
#define DEFLATED 8
ssize_t gunzip(void *dst, size_t dstlen, uint8_t *src, size_t srclen)
{
z_stream s;
ssize_t dstbytes;
int r, i, flags;
/* skip header */
i = 10;
flags = src[3];
if (src[2] != DEFLATED || (flags & RESERVED) != 0) {
puts ("Error: Bad gzipped data\n");
return -1;
}
if ((flags & EXTRA_FIELD) != 0)
i = 12 + src[10] + (src[11] << 8);
if ((flags & ORIG_NAME) != 0)
while (src[i++] != 0)
;
if ((flags & COMMENT) != 0)
while (src[i++] != 0)
;
if ((flags & HEAD_CRC) != 0)
i += 2;
if (i >= srclen) {
puts ("Error: gunzip out of data in header\n");
return -1;
}
s.zalloc = zalloc;
s.zfree = zfree;
r = inflateInit2(&s, -MAX_WBITS);
if (r != Z_OK) {
printf ("Error: inflateInit2() returned %d\n", r);
return (-1);
}
s.next_in = src + i;
s.avail_in = srclen - i;
s.next_out = dst;
s.avail_out = dstlen;
r = inflate(&s, Z_FINISH);
if (r != Z_OK && r != Z_STREAM_END) {
printf ("Error: inflate() returned %d\n", r);
return -1;
}
dstbytes = s.next_out - (unsigned char *) dst;
inflateEnd(&s);
return dstbytes;
}
/* Load a U-Boot image. */
static int load_uboot_image(const char *filename, hwaddr *ep, hwaddr *loadaddr,
int *is_linux, uint8_t image_type,
uint64_t (*translate_fn)(void *, uint64_t),
void *translate_opaque, AddressSpace *as)
{
int fd;
int size;
hwaddr address;
uboot_image_header_t h;
uboot_image_header_t *hdr = &h;
uint8_t *data = NULL;
int ret = -1;
int do_uncompress = 0;
fd = open(filename, O_RDONLY | O_BINARY);
if (fd < 0)
return -1;
size = read(fd, hdr, sizeof(uboot_image_header_t));
if (size < sizeof(uboot_image_header_t)) {
goto out;
}
bswap_uboot_header(hdr);
if (hdr->ih_magic != IH_MAGIC)
goto out;
if (hdr->ih_type != image_type) {
if (!(image_type == IH_TYPE_KERNEL &&
hdr->ih_type == IH_TYPE_KERNEL_NOLOAD)) {
fprintf(stderr, "Wrong image type %d, expected %d\n", hdr->ih_type,
image_type);
goto out;
}
}
/* TODO: Implement other image types. */
switch (hdr->ih_type) {
case IH_TYPE_KERNEL_NOLOAD:
if (!loadaddr || *loadaddr == LOAD_UIMAGE_LOADADDR_INVALID) {
fprintf(stderr, "this image format (kernel_noload) cannot be "
"loaded on this machine type");
goto out;
}
hdr->ih_load = *loadaddr + sizeof(*hdr);
hdr->ih_ep += hdr->ih_load;
/* fall through */
case IH_TYPE_KERNEL:
address = hdr->ih_load;
if (translate_fn) {
address = translate_fn(translate_opaque, address);
}
if (loadaddr) {
*loadaddr = hdr->ih_load;
}
switch (hdr->ih_comp) {
case IH_COMP_NONE:
break;
case IH_COMP_GZIP:
do_uncompress = 1;
break;
default:
fprintf(stderr,
"Unable to load u-boot images with compression type %d\n",
hdr->ih_comp);
goto out;
}
if (ep) {
*ep = hdr->ih_ep;
}
/* TODO: Check CPU type. */
if (is_linux) {
if (hdr->ih_os == IH_OS_LINUX) {
*is_linux = 1;
} else {
*is_linux = 0;
}
}
break;
case IH_TYPE_RAMDISK:
address = *loadaddr;
break;
default:
fprintf(stderr, "Unsupported u-boot image type %d\n", hdr->ih_type);
goto out;
}
data = g_malloc(hdr->ih_size);
if (read(fd, data, hdr->ih_size) != hdr->ih_size) {
fprintf(stderr, "Error reading file\n");
goto out;
}
if (do_uncompress) {
uint8_t *compressed_data;
size_t max_bytes;
ssize_t bytes;
compressed_data = data;
max_bytes = UBOOT_MAX_GUNZIP_BYTES;
data = g_malloc(max_bytes);
bytes = gunzip(data, max_bytes, compressed_data, hdr->ih_size);
g_free(compressed_data);
if (bytes < 0) {
fprintf(stderr, "Unable to decompress gzipped image!\n");
goto out;
}
hdr->ih_size = bytes;
}
rom_add_blob_fixed_as(filename, data, hdr->ih_size, address, as);
ret = hdr->ih_size;
out:
g_free(data);
close(fd);
return ret;
}
int load_uimage(const char *filename, hwaddr *ep, hwaddr *loadaddr,
int *is_linux,
uint64_t (*translate_fn)(void *, uint64_t),
void *translate_opaque)
{
return load_uboot_image(filename, ep, loadaddr, is_linux, IH_TYPE_KERNEL,
translate_fn, translate_opaque, NULL);
}
int load_uimage_as(const char *filename, hwaddr *ep, hwaddr *loadaddr,
int *is_linux,
uint64_t (*translate_fn)(void *, uint64_t),
void *translate_opaque, AddressSpace *as)
{
return load_uboot_image(filename, ep, loadaddr, is_linux, IH_TYPE_KERNEL,
translate_fn, translate_opaque, as);
}
/* Load a ramdisk. */
int load_ramdisk(const char *filename, hwaddr addr, uint64_t max_sz)
{
return load_ramdisk_as(filename, addr, max_sz, NULL);
}
int load_ramdisk_as(const char *filename, hwaddr addr, uint64_t max_sz,
AddressSpace *as)
{
return load_uboot_image(filename, NULL, &addr, NULL, IH_TYPE_RAMDISK,
NULL, NULL, as);
}
/* Load a gzip-compressed kernel to a dynamically allocated buffer. */
int load_image_gzipped_buffer(const char *filename, uint64_t max_sz,
uint8_t **buffer)
{
uint8_t *compressed_data = NULL;
uint8_t *data = NULL;
gsize len;
ssize_t bytes;
int ret = -1;
if (!g_file_get_contents(filename, (char **) &compressed_data, &len,
NULL)) {
goto out;
}
/* Is it a gzip-compressed file? */
if (len < 2 ||
compressed_data[0] != 0x1f ||
compressed_data[1] != 0x8b) {
goto out;
}
if (max_sz > LOAD_IMAGE_MAX_GUNZIP_BYTES) {
max_sz = LOAD_IMAGE_MAX_GUNZIP_BYTES;
}
data = g_malloc(max_sz);
bytes = gunzip(data, max_sz, compressed_data, len);
if (bytes < 0) {
fprintf(stderr, "%s: unable to decompress gzipped kernel file\n",
filename);
goto out;
}
/* trim to actual size and return to caller */
*buffer = g_realloc(data, bytes);
ret = bytes;
/* ownership has been transferred to caller */
data = NULL;
out:
g_free(compressed_data);
g_free(data);
return ret;
}
/* Load a gzip-compressed kernel. */
int load_image_gzipped(const char *filename, hwaddr addr, uint64_t max_sz)
{
int bytes;
uint8_t *data;
bytes = load_image_gzipped_buffer(filename, max_sz, &data);
if (bytes != -1) {
rom_add_blob_fixed(filename, data, bytes, addr);
g_free(data);
}
return bytes;
}
/*
* Functions for reboot-persistent memory regions.
* - used for vga bios and option roms.
* - also linux kernel (-kernel / -initrd).
*/
typedef struct Rom Rom;
struct Rom {
char *name;
char *path;
/* datasize is the amount of memory allocated in "data". If datasize is less
* than romsize, it means that the area from datasize to romsize is filled
* with zeros.
*/
size_t romsize;
size_t datasize;
uint8_t *data;
MemoryRegion *mr;
AddressSpace *as;
int isrom;
char *fw_dir;
char *fw_file;
bool committed;
hwaddr addr;
QTAILQ_ENTRY(Rom) next;
};
static FWCfgState *fw_cfg;
static QTAILQ_HEAD(, Rom) roms = QTAILQ_HEAD_INITIALIZER(roms);
/* rom->data must be heap-allocated (do not use with rom_add_elf_program()) */
static void rom_free(Rom *rom)
{
g_free(rom->data);
g_free(rom->path);
g_free(rom->name);
g_free(rom->fw_dir);
g_free(rom->fw_file);
g_free(rom);
}
static inline bool rom_order_compare(Rom *rom, Rom *item)
{
return ((uintptr_t)(void *)rom->as > (uintptr_t)(void *)item->as) ||
(rom->as == item->as && rom->addr >= item->addr);
}
static void rom_insert(Rom *rom)
{
Rom *item;
if (roms_loaded) {
hw_error ("ROM images must be loaded at startup\n");
}
/* The user didn't specify an address space, this is the default */
if (!rom->as) {
rom->as = &address_space_memory;
}
rom->committed = false;
/* List is ordered by load address in the same address space */
QTAILQ_FOREACH(item, &roms, next) {
if (rom_order_compare(rom, item)) {
continue;
}
QTAILQ_INSERT_BEFORE(item, rom, next);
return;
}
QTAILQ_INSERT_TAIL(&roms, rom, next);
}
static void fw_cfg_resized(const char *id, uint64_t length, void *host)
{
if (fw_cfg) {
fw_cfg_modify_file(fw_cfg, id + strlen("/rom@"), host, length);
}
}
static void *rom_set_mr(Rom *rom, Object *owner, const char *name, bool ro)
{
void *data;
rom->mr = g_malloc(sizeof(*rom->mr));
memory_region_init_resizeable_ram(rom->mr, owner, name,
rom->datasize, rom->romsize,
fw_cfg_resized,
&error_fatal);
memory_region_set_readonly(rom->mr, ro);
vmstate_register_ram_global(rom->mr);
data = memory_region_get_ram_ptr(rom->mr);
memcpy(data, rom->data, rom->datasize);
return data;
}
int rom_add_file(const char *file, const char *fw_dir,
hwaddr addr, int32_t bootindex,
bool option_rom, MemoryRegion *mr,
AddressSpace *as)
{
MachineClass *mc = MACHINE_GET_CLASS(qdev_get_machine());
Rom *rom;
int rc, fd = -1;
char devpath[100];
if (as && mr) {
fprintf(stderr, "Specifying an Address Space and Memory Region is " \
"not valid when loading a rom\n");
/* We haven't allocated anything so we don't need any cleanup */
return -1;
}
rom = g_malloc0(sizeof(*rom));
rom->name = g_strdup(file);
rom->path = qemu_find_file(QEMU_FILE_TYPE_BIOS, rom->name);
rom->as = as;
if (rom->path == NULL) {
rom->path = g_strdup(file);
}
fd = open(rom->path, O_RDONLY | O_BINARY);
if (fd == -1) {
fprintf(stderr, "Could not open option rom '%s': %s\n",
rom->path, strerror(errno));
goto err;
}
if (fw_dir) {
rom->fw_dir = g_strdup(fw_dir);
rom->fw_file = g_strdup(file);
}
rom->addr = addr;
rom->romsize = lseek(fd, 0, SEEK_END);
if (rom->romsize == -1) {
fprintf(stderr, "rom: file %-20s: get size error: %s\n",
rom->name, strerror(errno));
goto err;
}
rom->datasize = rom->romsize;
rom->data = g_malloc0(rom->datasize);
lseek(fd, 0, SEEK_SET);
rc = read(fd, rom->data, rom->datasize);
if (rc != rom->datasize) {
fprintf(stderr, "rom: file %-20s: read error: rc=%d (expected %zd)\n",
rom->name, rc, rom->datasize);
goto err;
}
close(fd);
rom_insert(rom);
if (rom->fw_file && fw_cfg) {
const char *basename;
char fw_file_name[FW_CFG_MAX_FILE_PATH];
void *data;
basename = strrchr(rom->fw_file, '/');
if (basename) {
basename++;
} else {
basename = rom->fw_file;
}
snprintf(fw_file_name, sizeof(fw_file_name), "%s/%s", rom->fw_dir,
basename);
snprintf(devpath, sizeof(devpath), "/rom@%s", fw_file_name);
if ((!option_rom || mc->option_rom_has_mr) && mc->rom_file_has_mr) {
data = rom_set_mr(rom, OBJECT(fw_cfg), devpath, true);
} else {
data = rom->data;
}
fw_cfg_add_file(fw_cfg, fw_file_name, data, rom->romsize);
} else {
if (mr) {
rom->mr = mr;
snprintf(devpath, sizeof(devpath), "/rom@%s", file);
} else {
snprintf(devpath, sizeof(devpath), "/rom@" TARGET_FMT_plx, addr);
}
}
add_boot_device_path(bootindex, NULL, devpath);
return 0;
err:
if (fd != -1)
close(fd);
rom_free(rom);
return -1;
}
MemoryRegion *rom_add_blob(const char *name, const void *blob, size_t len,
size_t max_len, hwaddr addr, const char *fw_file_name,
FWCfgCallback fw_callback, void *callback_opaque,
AddressSpace *as, bool read_only)
{
MachineClass *mc = MACHINE_GET_CLASS(qdev_get_machine());
Rom *rom;
MemoryRegion *mr = NULL;
rom = g_malloc0(sizeof(*rom));
rom->name = g_strdup(name);
rom->as = as;
rom->addr = addr;
rom->romsize = max_len ? max_len : len;
rom->datasize = len;
rom->data = g_malloc0(rom->datasize);
memcpy(rom->data, blob, len);
rom_insert(rom);
if (fw_file_name && fw_cfg) {
char devpath[100];
void *data;
if (read_only) {
snprintf(devpath, sizeof(devpath), "/rom@%s", fw_file_name);
} else {
snprintf(devpath, sizeof(devpath), "/ram@%s", fw_file_name);
}
if (mc->rom_file_has_mr) {
data = rom_set_mr(rom, OBJECT(fw_cfg), devpath, read_only);
mr = rom->mr;
} else {
data = rom->data;
}
fw_cfg_add_file_callback(fw_cfg, fw_file_name,
fw_callback, NULL, callback_opaque,
data, rom->datasize, read_only);
}
return mr;
}
/* This function is specific for elf program because we don't need to allocate
* all the rom. We just allocate the first part and the rest is just zeros. This
* is why romsize and datasize are different. Also, this function seize the
* memory ownership of "data", so we don't have to allocate and copy the buffer.
*/
int rom_add_elf_program(const char *name, void *data, size_t datasize,
size_t romsize, hwaddr addr, AddressSpace *as)
{
Rom *rom;
rom = g_malloc0(sizeof(*rom));
rom->name = g_strdup(name);
rom->addr = addr;
rom->datasize = datasize;
rom->romsize = romsize;
rom->data = data;
rom->as = as;
rom_insert(rom);
return 0;
}
int rom_add_vga(const char *file)
{
return rom_add_file(file, "vgaroms", 0, -1, true, NULL, NULL);
}
int rom_add_option(const char *file, int32_t bootindex)
{
return rom_add_file(file, "genroms", 0, bootindex, true, NULL, NULL);
}
static void rom_reset(void *unused)
{
Rom *rom;
QTAILQ_FOREACH(rom, &roms, next) {
if (rom->fw_file) {
continue;
}
if (rom->data == NULL) {
continue;
}
if (rom->mr) {
void *host = memory_region_get_ram_ptr(rom->mr);
memcpy(host, rom->data, rom->datasize);
} else {
address_space_write_rom(rom->as, rom->addr, MEMTXATTRS_UNSPECIFIED,
rom->data, rom->datasize);
}
if (rom->isrom) {
/* rom needs to be written only once */
g_free(rom->data);
rom->data = NULL;
}
/*
* The rom loader is really on the same level as firmware in the guest
* shadowing a ROM into RAM. Such a shadowing mechanism needs to ensure
* that the instruction cache for that new region is clear, so that the
* CPU definitely fetches its instructions from the just written data.
*/
cpu_flush_icache_range(rom->addr, rom->datasize);
}
}
int rom_check_and_register_reset(void)
{
hwaddr addr = 0;
MemoryRegionSection section;
Rom *rom;
AddressSpace *as = NULL;
QTAILQ_FOREACH(rom, &roms, next) {
if (rom->fw_file) {
continue;
}
if (!rom->mr) {
if ((addr > rom->addr) && (as == rom->as)) {
fprintf(stderr, "rom: requested regions overlap "
"(rom %s. free=0x" TARGET_FMT_plx
", addr=0x" TARGET_FMT_plx ")\n",
rom->name, addr, rom->addr);
return -1;
}
addr = rom->addr;
addr += rom->romsize;
as = rom->as;
}
section = memory_region_find(rom->mr ? rom->mr : get_system_memory(),
rom->addr, 1);
rom->isrom = int128_nz(section.size) && memory_region_is_rom(section.mr);
memory_region_unref(section.mr);
}
qemu_register_reset(rom_reset, NULL);
roms_loaded = 1;
return 0;
}
void rom_set_fw(FWCfgState *f)
{
fw_cfg = f;
}
void rom_set_order_override(int order)
{
if (!fw_cfg)
return;
fw_cfg_set_order_override(fw_cfg, order);
}
void rom_reset_order_override(void)
{
if (!fw_cfg)
return;
fw_cfg_reset_order_override(fw_cfg);
}
void rom_transaction_begin(void)
{
Rom *rom;
/* Ignore ROMs added without the transaction API */
QTAILQ_FOREACH(rom, &roms, next) {
rom->committed = true;
}
}
void rom_transaction_end(bool commit)
{
Rom *rom;
Rom *tmp;
QTAILQ_FOREACH_SAFE(rom, &roms, next, tmp) {
if (rom->committed) {
continue;
}
if (commit) {
rom->committed = true;
} else {
QTAILQ_REMOVE(&roms, rom, next);
rom_free(rom);
}
}
}
static Rom *find_rom(hwaddr addr, size_t size)
{
Rom *rom;
QTAILQ_FOREACH(rom, &roms, next) {
if (rom->fw_file) {
continue;
}
if (rom->mr) {
continue;
}
if (rom->addr > addr) {
continue;
}
if (rom->addr + rom->romsize < addr + size) {
continue;
}
return rom;
}
return NULL;
}
/*
* Copies memory from registered ROMs to dest. Any memory that is contained in
* a ROM between addr and addr + size is copied. Note that this can involve
* multiple ROMs, which need not start at addr and need not end at addr + size.
*/
int rom_copy(uint8_t *dest, hwaddr addr, size_t size)
{
hwaddr end = addr + size;
uint8_t *s, *d = dest;
size_t l = 0;
Rom *rom;
QTAILQ_FOREACH(rom, &roms, next) {
if (rom->fw_file) {
continue;
}
if (rom->mr) {
continue;
}
if (rom->addr + rom->romsize < addr) {
continue;
}
if (rom->addr > end || rom->addr < addr) {
break;
}
d = dest + (rom->addr - addr);
s = rom->data;
l = rom->datasize;
if ((d + l) > (dest + size)) {
l = dest - d;
}
if (l > 0) {
memcpy(d, s, l);
}
if (rom->romsize > rom->datasize) {
/* If datasize is less than romsize, it means that we didn't
* allocate all the ROM because the trailing data are only zeros.
*/
d += l;
l = rom->romsize - rom->datasize;
if ((d + l) > (dest + size)) {
/* Rom size doesn't fit in the destination area. Adjust to avoid
* overflow.
*/
l = dest - d;
}
if (l > 0) {
memset(d, 0x0, l);
}
}
}
return (d + l) - dest;
}
void *rom_ptr(hwaddr addr, size_t size)
{
Rom *rom;
rom = find_rom(addr, size);
if (!rom || !rom->data)
return NULL;
return rom->data + (addr - rom->addr);
}
void hmp_info_roms(Monitor *mon, const QDict *qdict)
{
Rom *rom;
QTAILQ_FOREACH(rom, &roms, next) {
if (rom->mr) {
monitor_printf(mon, "%s"
" size=0x%06zx name=\"%s\"\n",
memory_region_name(rom->mr),
rom->romsize,
rom->name);
} else if (!rom->fw_file) {
monitor_printf(mon, "addr=" TARGET_FMT_plx
" size=0x%06zx mem=%s name=\"%s\"\n",
rom->addr, rom->romsize,
rom->isrom ? "rom" : "ram",
rom->name);
} else {
monitor_printf(mon, "fw=%s/%s"
" size=0x%06zx name=\"%s\"\n",
rom->fw_dir,
rom->fw_file,
rom->romsize,
rom->name);
}
}
}
typedef enum HexRecord HexRecord;
enum HexRecord {
DATA_RECORD = 0,
EOF_RECORD,
EXT_SEG_ADDR_RECORD,
START_SEG_ADDR_RECORD,
EXT_LINEAR_ADDR_RECORD,
START_LINEAR_ADDR_RECORD,
};
/* Each record contains a 16-bit address which is combined with the upper 16
* bits of the implicit "next address" to form a 32-bit address.
*/
#define NEXT_ADDR_MASK 0xffff0000
#define DATA_FIELD_MAX_LEN 0xff
#define LEN_EXCEPT_DATA 0x5
/* 0x5 = sizeof(byte_count) + sizeof(address) + sizeof(record_type) +
* sizeof(checksum) */
typedef struct {
uint8_t byte_count;
uint16_t address;
uint8_t record_type;
uint8_t data[DATA_FIELD_MAX_LEN];
uint8_t checksum;
} HexLine;
/* return 0 or -1 if error */
static bool parse_record(HexLine *line, uint8_t *our_checksum, const uint8_t c,
uint32_t *index, const bool in_process)
{
/* +-------+---------------+-------+---------------------+--------+
* | byte | |record | | |
* | count | address | type | data |checksum|
* +-------+---------------+-------+---------------------+--------+
* ^ ^ ^ ^ ^ ^
* |1 byte | 2 bytes |1 byte | 0-255 bytes | 1 byte |
*/
uint8_t value = 0;
uint32_t idx = *index;
/* ignore space */
if (g_ascii_isspace(c)) {
return true;
}
if (!g_ascii_isxdigit(c) || !in_process) {
return false;
}
value = g_ascii_xdigit_value(c);
value = (idx & 0x1) ? (value & 0xf) : (value << 4);
if (idx < 2) {
line->byte_count |= value;
} else if (2 <= idx && idx < 6) {
line->address <<= 4;
line->address += g_ascii_xdigit_value(c);
} else if (6 <= idx && idx < 8) {
line->record_type |= value;
} else if (8 <= idx && idx < 8 + 2 * line->byte_count) {
line->data[(idx - 8) >> 1] |= value;
} else if (8 + 2 * line->byte_count <= idx &&
idx < 10 + 2 * line->byte_count) {
line->checksum |= value;
} else {
return false;
}
*our_checksum += value;
++(*index);
return true;
}
typedef struct {
const char *filename;
HexLine line;
uint8_t *bin_buf;
hwaddr *start_addr;
int total_size;
uint32_t next_address_to_write;
uint32_t current_address;
uint32_t current_rom_index;
uint32_t rom_start_address;
AddressSpace *as;
} HexParser;
/* return size or -1 if error */
static int handle_record_type(HexParser *parser)
{
HexLine *line = &(parser->line);
switch (line->record_type) {
case DATA_RECORD:
parser->current_address =
(parser->next_address_to_write & NEXT_ADDR_MASK) | line->address;
/* verify this is a contiguous block of memory */
if (parser->current_address != parser->next_address_to_write) {
if (parser->current_rom_index != 0) {
rom_add_blob_fixed_as(parser->filename, parser->bin_buf,
parser->current_rom_index,
parser->rom_start_address, parser->as);
}
parser->rom_start_address = parser->current_address;
parser->current_rom_index = 0;
}
/* copy from line buffer to output bin_buf */
memcpy(parser->bin_buf + parser->current_rom_index, line->data,
line->byte_count);
parser->current_rom_index += line->byte_count;
parser->total_size += line->byte_count;
/* save next address to write */
parser->next_address_to_write =
parser->current_address + line->byte_count;
break;
case EOF_RECORD:
if (parser->current_rom_index != 0) {
rom_add_blob_fixed_as(parser->filename, parser->bin_buf,
parser->current_rom_index,
parser->rom_start_address, parser->as);
}
return parser->total_size;
case EXT_SEG_ADDR_RECORD:
case EXT_LINEAR_ADDR_RECORD:
if (line->byte_count != 2 && line->address != 0) {
return -1;
}
if (parser->current_rom_index != 0) {
rom_add_blob_fixed_as(parser->filename, parser->bin_buf,
parser->current_rom_index,
parser->rom_start_address, parser->as);
}
/* save next address to write,
* in case of non-contiguous block of memory */
parser->next_address_to_write = (line->data[0] << 12) |
(line->data[1] << 4);
if (line->record_type == EXT_LINEAR_ADDR_RECORD) {
parser->next_address_to_write <<= 12;
}
parser->rom_start_address = parser->next_address_to_write;
parser->current_rom_index = 0;
break;
case START_SEG_ADDR_RECORD:
if (line->byte_count != 4 && line->address != 0) {
return -1;
}
/* x86 16-bit CS:IP segmented addressing */
*(parser->start_addr) = (((line->data[0] << 8) | line->data[1]) << 4) +
((line->data[2] << 8) | line->data[3]);
break;
case START_LINEAR_ADDR_RECORD:
if (line->byte_count != 4 && line->address != 0) {
return -1;
}
*(parser->start_addr) = ldl_be_p(line->data);
break;
default:
return -1;
}
return parser->total_size;
}
/* return size or -1 if error */
static int parse_hex_blob(const char *filename, hwaddr *addr, uint8_t *hex_blob,
size_t hex_blob_size, AddressSpace *as)
{
bool in_process = false; /* avoid re-enter and
* check whether record begin with ':' */
uint8_t *end = hex_blob + hex_blob_size;
uint8_t our_checksum = 0;
uint32_t record_index = 0;
HexParser parser = {
.filename = filename,
.bin_buf = g_malloc(hex_blob_size),
.start_addr = addr,
.as = as,
};
rom_transaction_begin();
for (; hex_blob < end; ++hex_blob) {
switch (*hex_blob) {
case '\r':
case '\n':
if (!in_process) {
break;
}
in_process = false;
if ((LEN_EXCEPT_DATA + parser.line.byte_count) * 2 !=
record_index ||
our_checksum != 0) {
parser.total_size = -1;
goto out;
}
if (handle_record_type(&parser) == -1) {
parser.total_size = -1;
goto out;
}
break;
/* start of a new record. */
case ':':
memset(&parser.line, 0, sizeof(HexLine));
in_process = true;
record_index = 0;
break;
/* decoding lines */
default:
if (!parse_record(&parser.line, &our_checksum, *hex_blob,
&record_index, in_process)) {
parser.total_size = -1;
goto out;
}
break;
}
}
out:
g_free(parser.bin_buf);
rom_transaction_end(parser.total_size != -1);
return parser.total_size;
}
/* return size or -1 if error */
int load_targphys_hex_as(const char *filename, hwaddr *entry, AddressSpace *as)
{
gsize hex_blob_size;
gchar *hex_blob;
int total_size = 0;
if (!g_file_get_contents(filename, &hex_blob, &hex_blob_size, NULL)) {
return -1;
}
total_size = parse_hex_blob(filename, entry, (uint8_t *)hex_blob,
hex_blob_size, as);
g_free(hex_blob);
return total_size;
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_4036_0 |
crossvul-cpp_data_good_5317_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP SSSSS DDDD %
% P P SS D D %
% PPPP SSS D D %
% P SS D D %
% P SSSSS DDDD %
% %
% %
% Read/Write Adobe Photoshop Image Format %
% %
% Software Design %
% Cristy %
% Leonard Rosenthol %
% July 1992 %
% Dirk Lemstra %
% December 2013 %
% %
% %
% 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 "magick/studio.h"
#include "magick/artifact.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/channel.h"
#include "magick/colormap.h"
#include "magick/colormap-private.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/constitute.h"
#include "magick/enhance.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/log.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/module.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/pixel.h"
#include "magick/pixel-accessor.h"
#include "magick/profile.h"
#include "magick/property.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/thread-private.h"
#ifdef MAGICKCORE_ZLIB_DELEGATE
#include <zlib.h>
#endif
#include "psd-private.h"
/*
Define declaractions.
*/
#define MaxPSDChannels 56
#define PSDQuantum(x) (((ssize_t) (x)+1) & -2)
/*
Enumerated declaractions.
*/
typedef enum
{
Raw = 0,
RLE = 1,
ZipWithoutPrediction = 2,
ZipWithPrediction = 3
} PSDCompressionType;
typedef enum
{
BitmapMode = 0,
GrayscaleMode = 1,
IndexedMode = 2,
RGBMode = 3,
CMYKMode = 4,
MultichannelMode = 7,
DuotoneMode = 8,
LabMode = 9
} PSDImageType;
/*
Typedef declaractions.
*/
typedef struct _ChannelInfo
{
short int
type;
size_t
size;
} ChannelInfo;
typedef struct _MaskInfo
{
Image
*image;
RectangleInfo
page;
unsigned char
background,
flags;
} MaskInfo;
typedef struct _LayerInfo
{
ChannelInfo
channel_info[MaxPSDChannels];
char
blendkey[4];
Image
*image;
MaskInfo
mask;
Quantum
opacity;
RectangleInfo
page;
size_t
offset_x,
offset_y;
unsigned char
clipping,
flags,
name[256],
visible;
unsigned short
channels;
} LayerInfo;
/*
Forward declarations.
*/
static MagickBooleanType
WritePSDImage(const ImageInfo *,Image *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s P S D %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsPSD()() returns MagickTrue if the image format type, identified by the
% magick string, is PSD.
%
% The format of the IsPSD method is:
%
% MagickBooleanType IsPSD(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsPSD(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (LocaleNCompare((const char *) magick,"8BPS",4) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadPSDImage() reads an Adobe Photoshop 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 ReadPSDImage method is:
%
% Image *ReadPSDImage(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 const char *CompositeOperatorToPSDBlendMode(CompositeOperator op)
{
const char
*blend_mode;
switch (op)
{
case ColorBurnCompositeOp: blend_mode = "idiv"; break;
case ColorDodgeCompositeOp: blend_mode = "div "; break;
case ColorizeCompositeOp: blend_mode = "colr"; break;
case DarkenCompositeOp: blend_mode = "dark"; break;
case DifferenceCompositeOp: blend_mode = "diff"; break;
case DissolveCompositeOp: blend_mode = "diss"; break;
case ExclusionCompositeOp: blend_mode = "smud"; break;
case HardLightCompositeOp: blend_mode = "hLit"; break;
case HardMixCompositeOp: blend_mode = "hMix"; break;
case HueCompositeOp: blend_mode = "hue "; break;
case LightenCompositeOp: blend_mode = "lite"; break;
case LinearBurnCompositeOp: blend_mode = "lbrn"; break;
case LinearDodgeCompositeOp:blend_mode = "lddg"; break;
case LinearLightCompositeOp:blend_mode = "lLit"; break;
case LuminizeCompositeOp: blend_mode = "lum "; break;
case MultiplyCompositeOp: blend_mode = "mul "; break;
case OverCompositeOp: blend_mode = "norm"; break;
case OverlayCompositeOp: blend_mode = "over"; break;
case PinLightCompositeOp: blend_mode = "pLit"; break;
case SaturateCompositeOp: blend_mode = "sat "; break;
case ScreenCompositeOp: blend_mode = "scrn"; break;
case SoftLightCompositeOp: blend_mode = "sLit"; break;
case VividLightCompositeOp: blend_mode = "vLit"; break;
default: blend_mode = "norm"; break;
}
return(blend_mode);
}
/*
For some reason Photoshop seems to blend semi-transparent pixels with white.
This method reverts the blending. This can be disabled by setting the
option 'psd:alpha-unblend' to off.
*/
static MagickBooleanType CorrectPSDAlphaBlend(const ImageInfo *image_info,
Image *image, ExceptionInfo* exception)
{
const char
*option;
MagickBooleanType
status;
ssize_t
y;
if (image->matte == MagickFalse || image->colorspace != sRGBColorspace)
return(MagickTrue);
option=GetImageOption(image_info,"psd:alpha-unblend");
if (IsStringNotFalse(option) == MagickFalse)
return(MagickTrue);
status=MagickTrue;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
gamma;
gamma=QuantumScale*GetPixelAlpha(q);
if (gamma != 0.0 && gamma != 1.0)
{
SetPixelRed(q,(GetPixelRed(q)-((1.0-gamma)*QuantumRange))/gamma);
SetPixelGreen(q,(GetPixelGreen(q)-((1.0-gamma)*QuantumRange))/gamma);
SetPixelBlue(q,(GetPixelBlue(q)-((1.0-gamma)*QuantumRange))/gamma);
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
status=MagickFalse;
}
return(status);
}
static inline CompressionType ConvertPSDCompression(
PSDCompressionType compression)
{
switch (compression)
{
case RLE:
return RLECompression;
case ZipWithPrediction:
case ZipWithoutPrediction:
return ZipCompression;
default:
return NoCompression;
}
}
static MagickBooleanType CorrectPSDOpacity(LayerInfo* layer_info,
ExceptionInfo *exception)
{
MagickBooleanType
status;
ssize_t
y;
if (layer_info->opacity == OpaqueOpacity)
return(MagickTrue);
layer_info->image->matte=MagickTrue;
status=MagickTrue;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(layer_info->image,layer_info->image,layer_info->image->rows,1)
#endif
for (y=0; y < (ssize_t) layer_info->image->rows; y++)
{
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetAuthenticPixels(layer_info->image,0,y,layer_info->image->columns,1,
exception);
if (q == (PixelPacket *)NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) layer_info->image->columns; x++)
{
q->opacity=(Quantum) (QuantumRange-(Quantum) (QuantumScale*(
(QuantumRange-q->opacity)*(QuantumRange-layer_info->opacity))));
q++;
}
if (SyncAuthenticPixels(layer_info->image,exception) == MagickFalse)
status=MagickFalse;
}
return(status);
}
static ssize_t DecodePSDPixels(const size_t number_compact_pixels,
const unsigned char *compact_pixels,const ssize_t depth,
const size_t number_pixels,unsigned char *pixels)
{
#define CheckNumberCompactPixels \
if (packets == 0) \
return(i); \
packets--
#define CheckNumberPixels(count) \
if (((ssize_t) i + count) > (ssize_t) number_pixels) \
return(i); \
i+=count
int
pixel;
register ssize_t
i,
j;
size_t
length;
ssize_t
packets;
packets=(ssize_t) number_compact_pixels;
for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); )
{
packets--;
length=(size_t) (*compact_pixels++);
if (length == 128)
continue;
if (length > 128)
{
length=256-length+1;
CheckNumberCompactPixels;
pixel=(*compact_pixels++);
for (j=0; j < (ssize_t) length; j++)
{
switch (depth)
{
case 1:
{
CheckNumberPixels(8);
*pixels++=(pixel >> 7) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 6) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 5) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 4) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 3) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 2) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 1) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 0) & 0x01 ? 0U : 255U;
break;
}
case 2:
{
CheckNumberPixels(4);
*pixels++=(unsigned char) ((pixel >> 6) & 0x03);
*pixels++=(unsigned char) ((pixel >> 4) & 0x03);
*pixels++=(unsigned char) ((pixel >> 2) & 0x03);
*pixels++=(unsigned char) ((pixel & 0x03) & 0x03);
break;
}
case 4:
{
CheckNumberPixels(2);
*pixels++=(unsigned char) ((pixel >> 4) & 0xff);
*pixels++=(unsigned char) ((pixel & 0x0f) & 0xff);
break;
}
default:
{
CheckNumberPixels(1);
*pixels++=(unsigned char) pixel;
break;
}
}
}
continue;
}
length++;
for (j=0; j < (ssize_t) length; j++)
{
CheckNumberCompactPixels;
switch (depth)
{
case 1:
{
CheckNumberPixels(8);
*pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U;
break;
}
case 2:
{
CheckNumberPixels(4);
*pixels++=(*compact_pixels >> 6) & 0x03;
*pixels++=(*compact_pixels >> 4) & 0x03;
*pixels++=(*compact_pixels >> 2) & 0x03;
*pixels++=(*compact_pixels & 0x03) & 0x03;
break;
}
case 4:
{
CheckNumberPixels(2);
*pixels++=(*compact_pixels >> 4) & 0xff;
*pixels++=(*compact_pixels & 0x0f) & 0xff;
break;
}
default:
{
CheckNumberPixels(1);
*pixels++=(*compact_pixels);
break;
}
}
compact_pixels++;
}
}
return(i);
}
static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info,
const ssize_t number_layers)
{
ssize_t
i;
for (i=0; i<number_layers; i++)
{
if (layer_info[i].image != (Image *) NULL)
layer_info[i].image=DestroyImage(layer_info[i].image);
if (layer_info[i].mask.image != (Image *) NULL)
layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image);
}
return (LayerInfo *) RelinquishMagickMemory(layer_info);
}
static inline size_t GetPSDPacketSize(Image *image)
{
if (image->storage_class == PseudoClass)
{
if (image->colors > 256)
return(2);
else if (image->depth > 8)
return(2);
}
else
if (image->depth > 8)
return(2);
return(1);
}
static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image)
{
if (psd_info->version == 1)
return((MagickSizeType) ReadBlobLong(image));
return((MagickSizeType) ReadBlobLongLong(image));
}
static inline size_t GetPSDRowSize(Image *image)
{
if (image->depth == 1)
return(((image->columns+7)/8)*GetPSDPacketSize(image));
else
return(image->columns*GetPSDPacketSize(image));
}
static const char *ModeToString(PSDImageType type)
{
switch (type)
{
case BitmapMode: return "Bitmap";
case GrayscaleMode: return "Grayscale";
case IndexedMode: return "Indexed";
case RGBMode: return "RGB";
case CMYKMode: return "CMYK";
case MultichannelMode: return "Multichannel";
case DuotoneMode: return "Duotone";
case LabMode: return "L*A*B";
default: return "unknown";
}
}
static void ParseImageResourceBlocks(Image *image,
const unsigned char *blocks,size_t length,
MagickBooleanType *has_merged_image)
{
const unsigned char
*p;
StringInfo
*profile;
unsigned int
count,
long_sans;
unsigned short
id,
short_sans;
if (length < 16)
return;
profile=BlobToStringInfo((const void *) NULL,length);
SetStringInfoDatum(profile,blocks);
(void) SetImageProfile(image,"8bim",profile);
profile=DestroyStringInfo(profile);
for (p=blocks; (p >= blocks) && (p < (blocks+length-16)); )
{
if (LocaleNCompare((const char *) p,"8BIM",4) != 0)
break;
p=PushLongPixel(MSBEndian,p,&long_sans);
p=PushShortPixel(MSBEndian,p,&id);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushLongPixel(MSBEndian,p,&count);
if (p+count > blocks+length)
return;
switch (id)
{
case 0x03ed:
{
char
value[MaxTextExtent];
unsigned short
resolution;
/*
Resolution info.
*/
p=PushShortPixel(MSBEndian,p,&resolution);
image->x_resolution=(double) resolution;
(void) FormatLocaleString(value,MaxTextExtent,"%g",
image->x_resolution);
(void) SetImageProperty(image,"tiff:XResolution",value);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&resolution);
image->y_resolution=(double) resolution;
(void) FormatLocaleString(value,MaxTextExtent,"%g",
image->y_resolution);
(void) SetImageProperty(image,"tiff:YResolution",value);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
image->units=PixelsPerInchResolution;
break;
}
case 0x0421:
{
if (*(p+4) == 0)
*has_merged_image=MagickFalse;
p+=count;
break;
}
default:
{
p+=count;
break;
}
}
if ((count & 0x01) != 0)
p++;
}
return;
}
static CompositeOperator PSDBlendModeToCompositeOperator(const char *mode)
{
if (mode == (const char *) NULL)
return(OverCompositeOp);
if (LocaleNCompare(mode,"norm",4) == 0)
return(OverCompositeOp);
if (LocaleNCompare(mode,"mul ",4) == 0)
return(MultiplyCompositeOp);
if (LocaleNCompare(mode,"diss",4) == 0)
return(DissolveCompositeOp);
if (LocaleNCompare(mode,"diff",4) == 0)
return(DifferenceCompositeOp);
if (LocaleNCompare(mode,"dark",4) == 0)
return(DarkenCompositeOp);
if (LocaleNCompare(mode,"lite",4) == 0)
return(LightenCompositeOp);
if (LocaleNCompare(mode,"hue ",4) == 0)
return(HueCompositeOp);
if (LocaleNCompare(mode,"sat ",4) == 0)
return(SaturateCompositeOp);
if (LocaleNCompare(mode,"colr",4) == 0)
return(ColorizeCompositeOp);
if (LocaleNCompare(mode,"lum ",4) == 0)
return(LuminizeCompositeOp);
if (LocaleNCompare(mode,"scrn",4) == 0)
return(ScreenCompositeOp);
if (LocaleNCompare(mode,"over",4) == 0)
return(OverlayCompositeOp);
if (LocaleNCompare(mode,"hLit",4) == 0)
return(HardLightCompositeOp);
if (LocaleNCompare(mode,"sLit",4) == 0)
return(SoftLightCompositeOp);
if (LocaleNCompare(mode,"smud",4) == 0)
return(ExclusionCompositeOp);
if (LocaleNCompare(mode,"div ",4) == 0)
return(ColorDodgeCompositeOp);
if (LocaleNCompare(mode,"idiv",4) == 0)
return(ColorBurnCompositeOp);
if (LocaleNCompare(mode,"lbrn",4) == 0)
return(LinearBurnCompositeOp);
if (LocaleNCompare(mode,"lddg",4) == 0)
return(LinearDodgeCompositeOp);
if (LocaleNCompare(mode,"lLit",4) == 0)
return(LinearLightCompositeOp);
if (LocaleNCompare(mode,"vLit",4) == 0)
return(VividLightCompositeOp);
if (LocaleNCompare(mode,"pLit",4) == 0)
return(PinLightCompositeOp);
if (LocaleNCompare(mode,"hMix",4) == 0)
return(HardMixCompositeOp);
return(OverCompositeOp);
}
static inline void ReversePSDString(Image *image,char *p,size_t length)
{
char
*q;
if (image->endian == MSBEndian)
return;
q=p+length;
for(--q; p < q; ++p, --q)
{
*p = *p ^ *q,
*q = *p ^ *q,
*p = *p ^ *q;
}
}
static inline void SetPSDPixel(Image *image,const size_t channels,
const ssize_t type,const size_t packet_size,const Quantum pixel,
PixelPacket *q,IndexPacket *indexes,ssize_t x,ExceptionInfo *exception)
{
if (image->storage_class == PseudoClass)
{
if (packet_size == 1)
SetPixelIndex(indexes+x,ScaleQuantumToChar(pixel));
else
SetPixelIndex(indexes+x,ScaleQuantumToShort(pixel));
SetPixelRGBO(q,image->colormap+(ssize_t)
ConstrainColormapIndex(image,GetPixelIndex(indexes+x)));
return;
}
switch (type)
{
case -1:
{
SetPixelAlpha(q,pixel);
break;
}
case -2:
case 0:
{
SetPixelRed(q,pixel);
if (channels == 1 || type == -2)
{
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
}
break;
}
case 1:
{
if (image->storage_class == PseudoClass)
SetPixelAlpha(q,pixel);
else
SetPixelGreen(q,pixel);
break;
}
case 2:
{
if (image->storage_class == PseudoClass)
SetPixelAlpha(q,pixel);
else
SetPixelBlue(q,pixel);
break;
}
case 3:
{
if (image->colorspace == CMYKColorspace)
SetPixelIndex(indexes+x,pixel);
else
if (image->matte != MagickFalse)
SetPixelAlpha(q,pixel);
break;
}
case 4:
{
if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) &&
(channels > 3))
break;
if (image->matte != MagickFalse)
SetPixelAlpha(q,pixel);
break;
}
}
}
static MagickBooleanType ReadPSDChannelPixels(Image *image,const size_t channels,
const size_t row,const ssize_t type,const unsigned char *pixels,
ExceptionInfo *exception)
{
Quantum
pixel;
register const unsigned char
*p;
register IndexPacket
*indexes;
register PixelPacket
*q;
register ssize_t
x;
size_t
packet_size;
unsigned short
nibble;
p=pixels;
q=GetAuthenticPixels(image,0,row,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
indexes=GetAuthenticIndexQueue(image);
packet_size=GetPSDPacketSize(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (packet_size == 1)
pixel=ScaleCharToQuantum(*p++);
else
{
p=PushShortPixel(MSBEndian,p,&nibble);
pixel=ScaleShortToQuantum(nibble);
}
if (image->depth > 1)
{
SetPSDPixel(image,channels,type,packet_size,pixel,q++,indexes,x,
exception);
}
else
{
ssize_t
bit,
number_bits;
number_bits=image->columns-x;
if (number_bits > 8)
number_bits=8;
for (bit=0; bit < number_bits; bit++)
{
SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel)
& (0x01 << (7-bit))) != 0 ? 0 : QuantumRange,q++,indexes,x++,
exception);
}
if (x != image->columns)
x--;
continue;
}
}
return(SyncAuthenticPixels(image,exception));
}
static MagickBooleanType ReadPSDChannelRaw(Image *image,const size_t channels,
const ssize_t type,ExceptionInfo *exception)
{
MagickBooleanType
status;
size_t
count,
row_size;
ssize_t
y;
unsigned char
*pixels;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is RAW");
row_size=GetPSDRowSize(image);
pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=MagickTrue;
for (y=0; y < (ssize_t) image->rows; y++)
{
status=MagickFalse;
count=ReadBlob(image,row_size,pixels);
if (count != row_size)
break;
status=ReadPSDChannelPixels(image,channels,y,type,pixels,exception);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(status);
}
static inline MagickOffsetType *ReadPSDRLEOffsets(Image *image,
const PSDInfo *psd_info,const size_t size)
{
MagickOffsetType
*offsets;
ssize_t
y;
offsets=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*offsets));
if(offsets != (MagickOffsetType *) NULL)
{
for (y=0; y < (ssize_t) size; y++)
{
if (psd_info->version == 1)
offsets[y]=(MagickOffsetType) ReadBlobShort(image);
else
offsets[y]=(MagickOffsetType) ReadBlobLong(image);
}
}
return offsets;
}
static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info,
const ssize_t type,MagickOffsetType *offsets,ExceptionInfo *exception)
{
MagickBooleanType
status;
size_t
length,
row_size;
ssize_t
count,
y;
unsigned char
*compact_pixels,
*pixels;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is RLE compressed");
row_size=GetPSDRowSize(image);
pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
length=0;
for (y=0; y < (ssize_t) image->rows; y++)
if ((MagickOffsetType) length < offsets[y])
length=(size_t) offsets[y];
compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels));
if (compact_pixels == (unsigned char *) NULL)
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
(void) ResetMagickMemory(compact_pixels,0,length*sizeof(*compact_pixels));
status=MagickTrue;
for (y=0; y < (ssize_t) image->rows; y++)
{
status=MagickFalse;
count=ReadBlob(image,(size_t) offsets[y],compact_pixels);
if (count != (ssize_t) offsets[y])
break;
count=DecodePSDPixels((size_t) offsets[y],compact_pixels,
(ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels);
if (count != (ssize_t) row_size)
break;
status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels,
exception);
if (status == MagickFalse)
break;
}
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(status);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels,
const ssize_t type,const PSDCompressionType compression,
const size_t compact_size,ExceptionInfo *exception)
{
MagickBooleanType
status;
register unsigned char
*p;
size_t
count,
length,
packet_size,
row_size;
ssize_t
y;
unsigned char
*compact_pixels,
*pixels;
z_stream
stream;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is ZIP compressed");
compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size,
sizeof(*compact_pixels));
if (compact_pixels == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
packet_size=GetPSDPacketSize(image);
row_size=image->columns*packet_size;
count=image->rows*row_size;
pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
{
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
ResetMagickMemory(&stream, 0, sizeof(z_stream));
stream.data_type=Z_BINARY;
(void) ReadBlob(image,compact_size,compact_pixels);
stream.next_in=(Bytef *)compact_pixels;
stream.avail_in=(unsigned int) compact_size;
stream.next_out=(Bytef *)pixels;
stream.avail_out=(unsigned int) count;
if(inflateInit(&stream) == Z_OK)
{
int
ret;
while (stream.avail_out > 0)
{
ret=inflate(&stream, Z_SYNC_FLUSH);
if (ret != Z_OK && ret != Z_STREAM_END)
{
compact_pixels=(unsigned char *) RelinquishMagickMemory(
compact_pixels);
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(MagickFalse);
}
}
}
if (compression == ZipWithPrediction)
{
p=pixels;
while(count > 0)
{
length=image->columns;
while(--length)
{
if (packet_size == 2)
{
p[2]+=p[0]+((p[1]+p[3]) >> 8);
p[3]+=p[1];
}
else
*(p+1)+=*p;
p+=packet_size;
}
p+=packet_size;
count-=row_size;
}
}
status=MagickTrue;
p=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
status=ReadPSDChannelPixels(image,channels,y,type,p,exception);
if (status == MagickFalse)
break;
p+=row_size;
}
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(status);
}
#endif
static MagickBooleanType ReadPSDChannel(Image *image,const PSDInfo *psd_info,
LayerInfo* layer_info,const size_t channel,
const PSDCompressionType compression,ExceptionInfo *exception)
{
Image
*channel_image,
*mask;
MagickOffsetType
offset;
MagickBooleanType
status;
channel_image=image;
mask=(Image *) NULL;
if (layer_info->channel_info[channel].type < -1)
{
/*
Ignore mask that is not a user supplied layer mask, if the mask is
disabled or if the flags have unsupported values.
*/
if (layer_info->channel_info[channel].type != -2 ||
(layer_info->mask.flags > 3) || (layer_info->mask.flags & 0x02))
{
SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR);
return(MagickTrue);
}
mask=CloneImage(image,layer_info->mask.page.width,
layer_info->mask.page.height,MagickFalse,exception);
mask->matte=MagickFalse;
channel_image=mask;
}
offset=TellBlob(channel_image);
status=MagickTrue;
switch(compression)
{
case Raw:
status=ReadPSDChannelRaw(channel_image,psd_info->channels,
layer_info->channel_info[channel].type,exception);
break;
case RLE:
{
MagickOffsetType
*offsets;
offsets=ReadPSDRLEOffsets(channel_image,psd_info,channel_image->rows);
if (offsets == (MagickOffsetType *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=ReadPSDChannelRLE(channel_image,psd_info,
layer_info->channel_info[channel].type,offsets,exception);
offsets=(MagickOffsetType *) RelinquishMagickMemory(offsets);
}
break;
case ZipWithPrediction:
case ZipWithoutPrediction:
#ifdef MAGICKCORE_ZLIB_DELEGATE
status=ReadPSDChannelZip(channel_image,layer_info->channels,
layer_info->channel_info[channel].type,compression,
layer_info->channel_info[channel].size-2,exception);
#else
SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET);
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn",
"'%s' (ZLIB)",image->filename);
#endif
break;
default:
SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET);
(void) ThrowMagickException(exception,GetMagickModule(),TypeWarning,
"CompressionNotSupported","'%.20g'",(double) compression);
break;
}
if (status == MagickFalse)
{
if (mask != (Image *) NULL)
DestroyImage(mask);
SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET);
ThrowBinaryException(CoderError,"UnableToDecompressImage",
image->filename);
}
if (mask != (Image *) NULL)
{
if (status != MagickFalse)
{
MagickPixelPacket
color;
layer_info->mask.image=CloneImage(image,image->columns,image->rows,
MagickTrue,exception);
layer_info->mask.image->matte=MagickFalse;
GetMagickPixelPacket(layer_info->mask.image,&color);
color.red=layer_info->mask.background == 0 ? 0 : QuantumRange;
color.green=color.red;
color.blue=color.red;
color.index=color.red;
SetImageColor(layer_info->mask.image,&color);
(void) CompositeImage(layer_info->mask.image,OverCompositeOp,mask,
layer_info->mask.page.x,layer_info->mask.page.y);
}
DestroyImage(mask);
}
return(status);
}
static MagickBooleanType ReadPSDLayer(Image *image,const PSDInfo *psd_info,
LayerInfo* layer_info,ExceptionInfo *exception)
{
char
message[MaxTextExtent];
MagickBooleanType
status;
PSDCompressionType
compression;
ssize_t
j;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" setting up new layer image");
(void) SetImageBackgroundColor(layer_info->image);
layer_info->image->compose=PSDBlendModeToCompositeOperator(
layer_info->blendkey);
if (layer_info->visible == MagickFalse)
{
layer_info->image->compose=NoCompositeOp;
(void) SetImageArtifact(layer_info->image,"psd:layer.invisible","true");
}
if (psd_info->mode == CMYKMode)
SetImageColorspace(layer_info->image,CMYKColorspace);
if ((psd_info->mode == BitmapMode) || (psd_info->mode == GrayscaleMode) ||
(psd_info->mode == DuotoneMode))
SetImageColorspace(layer_info->image,GRAYColorspace);
/*
Set up some hidden attributes for folks that need them.
*/
(void) FormatLocaleString(message,MaxTextExtent,"%.20g",
(double) layer_info->page.x);
(void) SetImageArtifact(layer_info->image,"psd:layer.x",message);
(void) FormatLocaleString(message,MaxTextExtent,"%.20g",
(double) layer_info->page.y);
(void) SetImageArtifact(layer_info->image,"psd:layer.y",message);
(void) FormatLocaleString(message,MaxTextExtent,"%.20g",(double)
layer_info->opacity);
(void) SetImageArtifact(layer_info->image,"psd:layer.opacity",message);
(void) SetImageProperty(layer_info->image,"label",(char *) layer_info->name);
status=MagickTrue;
for (j=0; j < (ssize_t) layer_info->channels; j++)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading data for channel %.20g",(double) j);
compression=(PSDCompressionType) ReadBlobShort(layer_info->image);
layer_info->image->compression=ConvertPSDCompression(compression);
if (layer_info->channel_info[j].type == -1)
layer_info->image->matte=MagickTrue;
status=ReadPSDChannel(layer_info->image,psd_info,layer_info,j,
compression,exception);
InheritException(exception,&layer_info->image->exception);
if (status == MagickFalse)
break;
}
if (status != MagickFalse)
status=CorrectPSDOpacity(layer_info,exception);
if ((status != MagickFalse) &&
(layer_info->image->colorspace == CMYKColorspace))
status=NegateImage(layer_info->image,MagickFalse);
if (status != MagickFalse && layer_info->mask.image != (Image *) NULL)
{
status=CompositeImage(layer_info->image,CopyOpacityCompositeOp,
layer_info->mask.image,0,0);
layer_info->mask.image=DestroyImage(layer_info->mask.image);
}
return(status);
}
ModuleExport MagickBooleanType ReadPSDLayers(Image *image,
const ImageInfo *image_info,const PSDInfo *psd_info,
const MagickBooleanType skip_layers,ExceptionInfo *exception)
{
char
type[4];
LayerInfo
*layer_info;
MagickSizeType
size;
MagickBooleanType
status;
register ssize_t
i;
ssize_t
count,
j,
number_layers;
size=GetPSDSize(psd_info,image);
if (size == 0)
{
/*
Skip layers & masks.
*/
(void) ReadBlobLong(image);
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
status=MagickFalse;
if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0))
return(MagickTrue);
else
{
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
if ((count != 0) && (LocaleNCompare(type,"Lr16",4) == 0))
size=GetPSDSize(psd_info,image);
else
return(MagickTrue);
}
}
status=MagickTrue;
if (size != 0)
{
layer_info=(LayerInfo *) NULL;
number_layers=(short) ReadBlobShort(image);
if (number_layers < 0)
{
/*
The first alpha channel in the merged result contains the
transparency data for the merged result.
*/
number_layers=MagickAbsoluteValue(number_layers);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" negative layer count corrected for");
image->matte=MagickTrue;
}
/*
We only need to know if the image has an alpha channel
*/
if (skip_layers != MagickFalse)
return(MagickTrue);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image contains %.20g layers",(double) number_layers);
if (number_layers == 0)
ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers",
image->filename);
layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers,
sizeof(*layer_info));
if (layer_info == (LayerInfo *) NULL)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" allocation of LayerInfo failed");
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
(void) ResetMagickMemory(layer_info,0,(size_t) number_layers*
sizeof(*layer_info));
for (i=0; i < number_layers; i++)
{
ssize_t
x,
y;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading layer #%.20g",(double) i+1);
layer_info[i].page.y=(int) ReadBlobLong(image);
layer_info[i].page.x=(int) ReadBlobLong(image);
y=(int) ReadBlobLong(image);
x=(int) ReadBlobLong(image);
layer_info[i].page.width=(size_t) (x-layer_info[i].page.x);
layer_info[i].page.height=(size_t) (y-layer_info[i].page.y);
layer_info[i].channels=ReadBlobShort(image);
if (layer_info[i].channels > MaxPSDChannels)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded",
image->filename);
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g",
(double) layer_info[i].page.x,(double) layer_info[i].page.y,
(double) layer_info[i].page.height,(double)
layer_info[i].page.width,(double) layer_info[i].channels);
for (j=0; j < (ssize_t) layer_info[i].channels; j++)
{
layer_info[i].channel_info[j].type=(short) ReadBlobShort(image);
layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info,
image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" channel[%.20g]: type=%.20g, size=%.20g",(double) j,
(double) layer_info[i].channel_info[j].type,
(double) layer_info[i].channel_info[j].size);
}
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer type was %.4s instead of 8BIM", type);
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"ImproperImageHeader",
image->filename);
}
(void) ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey);
ReversePSDString(image,layer_info[i].blendkey,4);
layer_info[i].opacity=(Quantum) (QuantumRange-ScaleCharToQuantum(
(unsigned char) ReadBlobByte(image)));
layer_info[i].clipping=(unsigned char) ReadBlobByte(image);
layer_info[i].flags=(unsigned char) ReadBlobByte(image);
layer_info[i].visible=!(layer_info[i].flags & 0x02);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s",
layer_info[i].blendkey,(double) layer_info[i].opacity,
layer_info[i].clipping ? "true" : "false",layer_info[i].flags,
layer_info[i].visible ? "true" : "false");
(void) ReadBlobByte(image); /* filler */
size=ReadBlobLong(image);
if (size != 0)
{
MagickSizeType
combined_length,
length;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer contains additional info");
length=ReadBlobLong(image);
combined_length=length+4;
if (length != 0)
{
/*
Layer mask info.
*/
layer_info[i].mask.page.y=(int) ReadBlobLong(image);
layer_info[i].mask.page.x=(int) ReadBlobLong(image);
layer_info[i].mask.page.height=(size_t) (ReadBlobLong(image)-
layer_info[i].mask.page.y);
layer_info[i].mask.page.width=(size_t) (ReadBlobLong(image)-
layer_info[i].mask.page.x);
layer_info[i].mask.background=(unsigned char) ReadBlobByte(
image);
layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image);
if (!(layer_info[i].mask.flags & 0x01))
{
layer_info[i].mask.page.y=layer_info[i].mask.page.y-
layer_info[i].page.y;
layer_info[i].mask.page.x=layer_info[i].mask.page.x-
layer_info[i].page.x;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g",
(double) layer_info[i].mask.page.x,(double)
layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width,
(double) layer_info[i].mask.page.height,(double)
((MagickOffsetType) length)-18);
/*
Skip over the rest of the layer mask information.
*/
if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile",
image->filename);
}
}
length=ReadBlobLong(image);
combined_length+=length+4;
if (length != 0)
{
/*
Layer blending ranges info.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer blending ranges: length=%.20g",(double)
((MagickOffsetType) length));
/*
We read it, but don't use it...
*/
for (j=0; j < (ssize_t) (length); j+=8)
{
size_t blend_source=ReadBlobLong(image);
size_t blend_dest=ReadBlobLong(image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" source(%x), dest(%x)",(unsigned int)
blend_source,(unsigned int) blend_dest);
}
}
/*
Layer name.
*/
length=(size_t) ReadBlobByte(image);
combined_length+=length+1;
if (length > 0)
(void) ReadBlob(image,(size_t) length++,layer_info[i].name);
layer_info[i].name[length]='\0';
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer name: %s",layer_info[i].name);
/*
Skip the rest of the variable data until we support it.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" unsupported data: length=%.20g",(double)
((MagickOffsetType) (size-combined_length)));
if (DiscardBlobBytes(image,(MagickSizeType) (size-combined_length)) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
}
}
for (i=0; i < number_layers; i++)
{
if ((layer_info[i].page.width == 0) ||
(layer_info[i].page.height == 0))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is empty");
continue;
}
/*
Allocate layered image.
*/
layer_info[i].image=CloneImage(image,layer_info[i].page.width,
layer_info[i].page.height,MagickFalse,exception);
if (layer_info[i].image == (Image *) NULL)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" allocation of image for layer %.20g failed",(double) i);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
}
if (image_info->ping == MagickFalse)
{
for (i=0; i < number_layers; i++)
{
if (layer_info[i].image == (Image *) NULL)
{
for (j=0; j < layer_info[i].channels; j++)
{
if (DiscardBlobBytes(image,(MagickSizeType)
layer_info[i].channel_info[j].size) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
}
continue;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading data for layer %.20g",(double) i);
status=ReadPSDLayer(image,psd_info,&layer_info[i],exception);
if (status == MagickFalse)
break;
status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType)
number_layers);
if (status == MagickFalse)
break;
}
}
if (status != MagickFalse)
{
for (i=0; i < number_layers; i++)
{
if (layer_info[i].image == (Image *) NULL)
{
for (j=i; j < number_layers - 1; j++)
layer_info[j] = layer_info[j+1];
number_layers--;
i--;
}
}
if (number_layers > 0)
{
for (i=0; i < number_layers; i++)
{
if (i > 0)
layer_info[i].image->previous=layer_info[i-1].image;
if (i < (number_layers-1))
layer_info[i].image->next=layer_info[i+1].image;
layer_info[i].image->page=layer_info[i].page;
}
image->next=layer_info[0].image;
layer_info[0].image->previous=image;
}
layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info);
}
else
layer_info=DestroyLayerInfo(layer_info,number_layers);
}
return(status);
}
static MagickBooleanType ReadPSDMergedImage(const ImageInfo *image_info,Image* image,
const PSDInfo* psd_info,ExceptionInfo *exception)
{
MagickOffsetType
*offsets;
MagickBooleanType
status;
PSDCompressionType
compression;
register ssize_t
i;
compression=(PSDCompressionType) ReadBlobMSBShort(image);
image->compression=ConvertPSDCompression(compression);
if (compression != Raw && compression != RLE)
{
(void) ThrowMagickException(exception,GetMagickModule(),
TypeWarning,"CompressionNotSupported","'%.20g'",(double) compression);
return(MagickFalse);
}
offsets=(MagickOffsetType *) NULL;
if (compression == RLE)
{
offsets=ReadPSDRLEOffsets(image,psd_info,image->rows*psd_info->channels);
if (offsets == (MagickOffsetType *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
status=MagickTrue;
for (i=0; i < (ssize_t) psd_info->channels; i++)
{
if (compression == RLE)
status=ReadPSDChannelRLE(image,psd_info,i,offsets+(i*image->rows),
exception);
else
status=ReadPSDChannelRaw(image,psd_info->channels,i,exception);
if (status != MagickFalse)
status=SetImageProgress(image,LoadImagesTag,i,psd_info->channels);
if (status == MagickFalse)
break;
}
if ((status != MagickFalse) && (image->colorspace == CMYKColorspace))
status=NegateImage(image,MagickFalse);
if (status != MagickFalse)
status=CorrectPSDAlphaBlend(image_info,image,exception);
if (offsets != (MagickOffsetType *) NULL)
offsets=(MagickOffsetType *) RelinquishMagickMemory(offsets);
return(status);
}
static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
has_merged_image,
skip_layers;
MagickOffsetType
offset;
MagickSizeType
length;
MagickBooleanType
status;
PSDInfo
psd_info;
register ssize_t
i;
ssize_t
count;
unsigned char
*data;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read image header.
*/
image->endian=MSBEndian;
count=ReadBlob(image,4,(unsigned char *) psd_info.signature);
psd_info.version=ReadBlobMSBShort(image);
if ((count == 0) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) ||
((psd_info.version != 1) && (psd_info.version != 2)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
(void) ReadBlob(image,6,psd_info.reserved);
psd_info.channels=ReadBlobMSBShort(image);
if (psd_info.channels > MaxPSDChannels)
ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded");
psd_info.rows=ReadBlobMSBLong(image);
psd_info.columns=ReadBlobMSBLong(image);
if ((psd_info.version == 1) && ((psd_info.rows > 30000) ||
(psd_info.columns > 30000)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
psd_info.depth=ReadBlobMSBShort(image);
if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
psd_info.mode=ReadBlobMSBShort(image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s",
(double) psd_info.columns,(double) psd_info.rows,(double)
psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType)
psd_info.mode));
/*
Initialize image.
*/
image->depth=psd_info.depth;
image->columns=psd_info.columns;
image->rows=psd_info.rows;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if (SetImageBackgroundColor(image) == MagickFalse)
{
InheritException(exception,&image->exception);
image=DestroyImageList(image);
return((Image *) NULL);
}
if (psd_info.mode == LabMode)
SetImageColorspace(image,LabColorspace);
if (psd_info.mode == CMYKMode)
{
SetImageColorspace(image,CMYKColorspace);
image->matte=psd_info.channels > 4 ? MagickTrue : MagickFalse;
}
else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) ||
(psd_info.mode == DuotoneMode))
{
status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536);
if (status == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image colormap allocated");
SetImageColorspace(image,GRAYColorspace);
image->matte=psd_info.channels > 1 ? MagickTrue : MagickFalse;
}
else
image->matte=psd_info.channels > 3 ? MagickTrue : MagickFalse;
/*
Read PSD raster colormap only present for indexed and duotone images.
*/
length=ReadBlobMSBLong(image);
if (length != 0)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading colormap");
if (psd_info.mode == DuotoneMode)
{
/*
Duotone image data; the format of this data is undocumented.
*/
data=(unsigned char *) AcquireQuantumMemory((size_t) length,
sizeof(*data));
if (data == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ReadBlob(image,(size_t) length,data);
data=(unsigned char *) RelinquishMagickMemory(data);
}
else
{
size_t
number_colors;
/*
Read PSD raster colormap.
*/
number_colors=length/3;
if (number_colors > 65536)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (AcquireImageColormap(image,number_colors) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].red=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].green=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].blue=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->matte=MagickFalse;
}
}
if ((image->depth == 1) && (image->storage_class != PseudoClass))
ThrowReaderException(CorruptImageError, "ImproperImageHeader");
has_merged_image=MagickTrue;
length=ReadBlobMSBLong(image);
if (length != 0)
{
unsigned char
*blocks;
/*
Image resources block.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading image resource blocks - %.20g bytes",(double)
((MagickOffsetType) length));
blocks=(unsigned char *) AcquireQuantumMemory((size_t) length,
sizeof(*blocks));
if (blocks == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,(size_t) length,blocks);
if ((count != (ssize_t) length) || (length < 4) ||
(LocaleNCompare((char *) blocks,"8BIM",4) != 0))
{
blocks=(unsigned char *) RelinquishMagickMemory(blocks);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image);
blocks=(unsigned char *) RelinquishMagickMemory(blocks);
}
/*
Layer and mask block.
*/
length=GetPSDSize(&psd_info,image);
if (length == 8)
{
length=ReadBlobMSBLong(image);
length=ReadBlobMSBLong(image);
}
offset=TellBlob(image);
skip_layers=MagickFalse;
if ((image_info->number_scenes == 1) && (image_info->scene == 0) &&
(has_merged_image != MagickFalse))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" read composite only");
skip_layers=MagickTrue;
}
if (length == 0)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image has no layers");
}
else
{
if (ReadPSDLayers(image,image_info,&psd_info,skip_layers,exception) !=
MagickTrue)
{
(void) CloseBlob(image);
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Skip the rest of the layer and mask information.
*/
SeekBlob(image,offset+length,SEEK_SET);
}
/*
If we are only "pinging" the image, then we're done - so return.
*/
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
Read the precombined layer, present for PSD < 4 compatibility.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading the precombined layer");
if (has_merged_image != MagickFalse || GetImageListLength(image) == 1)
has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image,
&psd_info,exception);
if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) &&
(length != 0))
{
SeekBlob(image,offset,SEEK_SET);
status=ReadPSDLayers(image,image_info,&psd_info,MagickFalse,exception);
if (status != MagickTrue)
{
(void) CloseBlob(image);
image=DestroyImageList(image);
return((Image *) NULL);
}
}
if ((has_merged_image == MagickFalse) && (GetImageListLength(image) > 1))
{
Image
*merged;
SetImageAlphaChannel(image,TransparentAlphaChannel);
image->background_color.opacity=TransparentOpacity;
merged=MergeImageLayers(image,FlattenLayer,exception);
ReplaceImageInList(&image,merged);
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterPSDImage() adds properties for the PSD image format to
% the list of supported formats. The properties 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 RegisterPSDImage method is:
%
% size_t RegisterPSDImage(void)
%
*/
ModuleExport size_t RegisterPSDImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("PSB");
entry->decoder=(DecodeImageHandler *) ReadPSDImage;
entry->encoder=(EncodeImageHandler *) WritePSDImage;
entry->magick=(IsImageFormatHandler *) IsPSD;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString("Adobe Large Document Format");
entry->module=ConstantString("PSD");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PSD");
entry->decoder=(DecodeImageHandler *) ReadPSDImage;
entry->encoder=(EncodeImageHandler *) WritePSDImage;
entry->magick=(IsImageFormatHandler *) IsPSD;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString("Adobe Photoshop bitmap");
entry->module=ConstantString("PSD");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterPSDImage() removes format registrations made by the
% PSD module from the list of supported formats.
%
% The format of the UnregisterPSDImage method is:
%
% UnregisterPSDImage(void)
%
*/
ModuleExport void UnregisterPSDImage(void)
{
(void) UnregisterMagickInfo("PSB");
(void) UnregisterMagickInfo("PSD");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WritePSDImage() writes an image in the Adobe Photoshop encoded image format.
%
% The format of the WritePSDImage method is:
%
% MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static inline ssize_t SetPSDOffset(const PSDInfo *psd_info,Image *image,
const size_t offset)
{
if (psd_info->version == 1)
return(WriteBlobMSBShort(image,(unsigned short) offset));
return(WriteBlobMSBLong(image,(unsigned short) offset));
}
static inline ssize_t SetPSDSize(const PSDInfo *psd_info,Image *image,
const MagickSizeType size)
{
if (psd_info->version == 1)
return(WriteBlobMSBLong(image,(unsigned int) size));
return(WriteBlobMSBLongLong(image,size));
}
static size_t PSDPackbitsEncodeImage(Image *image,const size_t length,
const unsigned char *pixels,unsigned char *compact_pixels)
{
int
count;
register ssize_t
i,
j;
register unsigned char
*q;
unsigned char
*packbits;
/*
Compress pixels with Packbits encoding.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(pixels != (unsigned char *) NULL);
packbits=(unsigned char *) AcquireQuantumMemory(128UL,sizeof(*packbits));
if (packbits == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
q=compact_pixels;
for (i=(ssize_t) length; i != 0; )
{
switch (i)
{
case 1:
{
i--;
*q++=(unsigned char) 0;
*q++=(*pixels);
break;
}
case 2:
{
i-=2;
*q++=(unsigned char) 1;
*q++=(*pixels);
*q++=pixels[1];
break;
}
case 3:
{
i-=3;
if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2)))
{
*q++=(unsigned char) ((256-3)+1);
*q++=(*pixels);
break;
}
*q++=(unsigned char) 2;
*q++=(*pixels);
*q++=pixels[1];
*q++=pixels[2];
break;
}
default:
{
if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2)))
{
/*
Packed run.
*/
count=3;
while (((ssize_t) count < i) && (*pixels == *(pixels+count)))
{
count++;
if (count >= 127)
break;
}
i-=count;
*q++=(unsigned char) ((256-count)+1);
*q++=(*pixels);
pixels+=count;
break;
}
/*
Literal run.
*/
count=0;
while ((*(pixels+count) != *(pixels+count+1)) ||
(*(pixels+count+1) != *(pixels+count+2)))
{
packbits[count+1]=pixels[count];
count++;
if (((ssize_t) count >= (i-3)) || (count >= 127))
break;
}
i-=count;
*packbits=(unsigned char) (count-1);
for (j=0; j <= (ssize_t) count; j++)
*q++=packbits[j];
pixels+=count;
break;
}
}
}
*q++=(unsigned char) 128; /* EOD marker */
packbits=(unsigned char *) RelinquishMagickMemory(packbits);
return((size_t) (q-compact_pixels));
}
static void WritePackbitsLength(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
unsigned char *compact_pixels,const QuantumType quantum_type)
{
QuantumInfo
*quantum_info;
register const PixelPacket
*p;
size_t
length,
packet_size;
ssize_t
y;
unsigned char
*pixels;
if (next_image->depth > 8)
next_image->depth=16;
packet_size=next_image->depth > 8UL ? 2UL : 1UL;
(void) packet_size;
quantum_info=AcquireQuantumInfo(image_info,image);
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) next_image->rows; y++)
{
p=GetVirtualPixels(next_image,0,y,next_image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,&image->exception);
length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels);
(void) SetPSDOffset(psd_info,image,length);
}
quantum_info=DestroyQuantumInfo(quantum_info);
}
static void WriteOneChannel(const PSDInfo *psd_info,const ImageInfo *image_info,
Image *image,Image *next_image,unsigned char *compact_pixels,
const QuantumType quantum_type,const MagickBooleanType compression_flag)
{
int
y;
MagickBooleanType
monochrome;
QuantumInfo
*quantum_info;
register const PixelPacket
*p;
register ssize_t
i;
size_t
length,
packet_size;
unsigned char
*pixels;
(void) psd_info;
if ((compression_flag != MagickFalse) &&
(next_image->compression != RLECompression))
(void) WriteBlobMSBShort(image,0);
if (next_image->depth > 8)
next_image->depth=16;
monochrome=IsMonochromeImage(image,&image->exception) && (image->depth == 1)
? MagickTrue : MagickFalse;
packet_size=next_image->depth > 8UL ? 2UL : 1UL;
(void) packet_size;
quantum_info=AcquireQuantumInfo(image_info,image);
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) next_image->rows; y++)
{
p=GetVirtualPixels(next_image,0,y,next_image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,&image->exception);
if (monochrome != MagickFalse)
for (i=0; i < (ssize_t) length; i++)
pixels[i]=(~pixels[i]);
if (next_image->compression != RLECompression)
(void) WriteBlob(image,length,pixels);
else
{
length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels);
(void) WriteBlob(image,length,compact_pixels);
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
}
static MagickBooleanType WriteImageChannels(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
const MagickBooleanType separate)
{
size_t
channels,
packet_size;
unsigned char
*compact_pixels;
/*
Write uncompressed pixels as separate planes.
*/
channels=1;
packet_size=next_image->depth > 8UL ? 2UL : 1UL;
compact_pixels=(unsigned char *) NULL;
if (next_image->compression == RLECompression)
{
compact_pixels=(unsigned char *) AcquireQuantumMemory((9*channels*
next_image->columns)+1,packet_size*sizeof(*compact_pixels));
if (compact_pixels == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
if (IsGrayImage(next_image,&next_image->exception) != MagickFalse)
{
if (next_image->compression == RLECompression)
{
/*
Packbits compression.
*/
(void) WriteBlobMSBShort(image,1);
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,GrayQuantum);
if (next_image->matte != MagickFalse)
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,AlphaQuantum);
}
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
GrayQuantum,MagickTrue);
if (next_image->matte != MagickFalse)
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
AlphaQuantum,separate);
(void) SetImageProgress(image,SaveImagesTag,0,1);
}
else
if (next_image->storage_class == PseudoClass)
{
if (next_image->compression == RLECompression)
{
/*
Packbits compression.
*/
(void) WriteBlobMSBShort(image,1);
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,IndexQuantum);
if (next_image->matte != MagickFalse)
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,AlphaQuantum);
}
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
IndexQuantum,MagickTrue);
if (next_image->matte != MagickFalse)
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
AlphaQuantum,separate);
(void) SetImageProgress(image,SaveImagesTag,0,1);
}
else
{
if (next_image->colorspace == CMYKColorspace)
(void) NegateImage(next_image,MagickFalse);
if (next_image->compression == RLECompression)
{
/*
Packbits compression.
*/
(void) WriteBlobMSBShort(image,1);
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,RedQuantum);
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,GreenQuantum);
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,BlueQuantum);
if (next_image->colorspace == CMYKColorspace)
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,BlackQuantum);
if (next_image->matte != MagickFalse)
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,AlphaQuantum);
}
(void) SetImageProgress(image,SaveImagesTag,0,6);
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
RedQuantum,MagickTrue);
(void) SetImageProgress(image,SaveImagesTag,1,6);
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
GreenQuantum,separate);
(void) SetImageProgress(image,SaveImagesTag,2,6);
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
BlueQuantum,separate);
(void) SetImageProgress(image,SaveImagesTag,3,6);
if (next_image->colorspace == CMYKColorspace)
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
BlackQuantum,separate);
(void) SetImageProgress(image,SaveImagesTag,4,6);
if (next_image->matte != MagickFalse)
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
AlphaQuantum,separate);
(void) SetImageProgress(image,SaveImagesTag,5,6);
if (next_image->colorspace == CMYKColorspace)
(void) NegateImage(next_image,MagickFalse);
}
if (next_image->compression == RLECompression)
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
return(MagickTrue);
}
static void WritePascalString(Image* inImage,const char *inString,int inPad)
{
size_t
length;
register ssize_t
i;
/*
Max length is 255.
*/
length=(strlen(inString) > 255UL ) ? 255UL : strlen(inString);
if (length == 0)
(void) WriteBlobByte(inImage,0);
else
{
(void) WriteBlobByte(inImage,(unsigned char) length);
(void) WriteBlob(inImage, length, (const unsigned char *) inString);
}
length++;
if ((length % inPad) == 0)
return;
for (i=0; i < (ssize_t) (inPad-(length % inPad)); i++)
(void) WriteBlobByte(inImage,0);
}
static void WriteResolutionResourceBlock(Image *image)
{
double
x_resolution,
y_resolution;
unsigned short
units;
if (image->units == PixelsPerCentimeterResolution)
{
x_resolution=2.54*65536.0*image->x_resolution+0.5;
y_resolution=2.54*65536.0*image->y_resolution+0.5;
units=2;
}
else
{
x_resolution=65536.0*image->x_resolution+0.5;
y_resolution=65536.0*image->y_resolution+0.5;
units=1;
}
(void) WriteBlob(image,4,(const unsigned char *) "8BIM");
(void) WriteBlobMSBShort(image,0x03ED);
(void) WriteBlobMSBShort(image,0);
(void) WriteBlobMSBLong(image,16); /* resource size */
(void) WriteBlobMSBLong(image,(unsigned int) (x_resolution+0.5));
(void) WriteBlobMSBShort(image,units); /* horizontal resolution unit */
(void) WriteBlobMSBShort(image,units); /* width unit */
(void) WriteBlobMSBLong(image,(unsigned int) (y_resolution+0.5));
(void) WriteBlobMSBShort(image,units); /* vertical resolution unit */
(void) WriteBlobMSBShort(image,units); /* height unit */
}
static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile)
{
register const unsigned char
*p;
size_t
length;
unsigned char
*datum;
unsigned int
count,
long_sans;
unsigned short
id,
short_sans;
length=GetStringInfoLength(bim_profile);
if (length < 16)
return;
datum=GetStringInfoDatum(bim_profile);
for (p=datum; (p >= datum) && (p < (datum+length-16)); )
{
register unsigned char
*q;
q=(unsigned char *) p;
if (LocaleNCompare((const char *) p,"8BIM",4) != 0)
break;
p=PushLongPixel(MSBEndian,p,&long_sans);
p=PushShortPixel(MSBEndian,p,&id);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushLongPixel(MSBEndian,p,&count);
if (id == 0x0000040f)
{
if ((q+PSDQuantum(count)+12) < (datum+length-16))
{
(void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length-
(PSDQuantum(count)+12)-(q-datum));
SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12));
}
break;
}
p+=count;
if ((count & 0x01) != 0)
p++;
}
}
static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile)
{
register const unsigned char
*p;
size_t
length;
unsigned char
*datum;
unsigned int
count,
long_sans;
unsigned short
id,
short_sans;
length=GetStringInfoLength(bim_profile);
if (length < 16)
return;
datum=GetStringInfoDatum(bim_profile);
for (p=datum; (p >= datum) && (p < (datum+length-16)); )
{
register unsigned char
*q;
ssize_t
cnt;
q=(unsigned char *) p;
if (LocaleNCompare((const char *) p,"8BIM",4) != 0)
return;
p=PushLongPixel(MSBEndian,p,&long_sans);
p=PushShortPixel(MSBEndian,p,&id);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushLongPixel(MSBEndian,p,&count);
cnt=PSDQuantum(count);
if (cnt < 0)
return;
if ((id == 0x000003ed) && (cnt < (ssize_t) (length-12)))
{
(void) CopyMagickMemory(q,q+cnt+12,length-(cnt+12)-(q-datum));
SetStringInfoLength(bim_profile,length-(cnt+12));
break;
}
p+=count;
if ((count & 0x01) != 0)
p++;
}
}
static MagickBooleanType WritePSDImage(const ImageInfo *image_info,
Image *image)
{
const char
*property;
const StringInfo
*icc_profile;
Image
*base_image,
*next_image;
MagickBooleanType
status;
PSDInfo
psd_info;
register ssize_t
i;
size_t
channel_size,
channelLength,
layer_count,
layer_info_size,
length,
num_channels,
packet_size,
rounded_layer_info_size;
StringInfo
*bim_profile;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
packet_size=(size_t) (image->depth > 8 ? 6 : 3);
if (image->matte != MagickFalse)
packet_size+=image->depth > 8 ? 2 : 1;
psd_info.version=1;
if ((LocaleCompare(image_info->magick,"PSB") == 0) ||
(image->columns > 30000) || (image->rows > 30000))
psd_info.version=2;
(void) WriteBlob(image,4,(const unsigned char *) "8BPS");
(void) WriteBlobMSBShort(image,psd_info.version); /* version */
for (i=1; i <= 6; i++)
(void) WriteBlobByte(image, 0); /* 6 bytes of reserved */
if (SetImageGray(image,&image->exception) != MagickFalse)
num_channels=(image->matte != MagickFalse ? 2UL : 1UL);
else
if ((image_info->type != TrueColorType) && (image_info->type !=
TrueColorMatteType) && (image->storage_class == PseudoClass))
num_channels=(image->matte != MagickFalse ? 2UL : 1UL);
else
{
if (image->storage_class == PseudoClass)
(void) SetImageStorageClass(image,DirectClass);
if (image->colorspace != CMYKColorspace)
num_channels=(image->matte != MagickFalse ? 4UL : 3UL);
else
num_channels=(image->matte != MagickFalse ? 5UL : 4UL);
}
(void) WriteBlobMSBShort(image,(unsigned short) num_channels);
(void) WriteBlobMSBLong(image,(unsigned int) image->rows);
(void) WriteBlobMSBLong(image,(unsigned int) image->columns);
if (IsGrayImage(image,&image->exception) != MagickFalse)
{
MagickBooleanType
monochrome;
/*
Write depth & mode.
*/
monochrome=IsMonochromeImage(image,&image->exception) &&
(image->depth == 1) ? MagickTrue : MagickFalse;
(void) WriteBlobMSBShort(image,(unsigned short)
(monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8));
(void) WriteBlobMSBShort(image,(unsigned short)
(monochrome != MagickFalse ? BitmapMode : GrayscaleMode));
}
else
{
(void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class ==
PseudoClass ? 8 : image->depth > 8 ? 16 : 8));
if (((image_info->colorspace != UndefinedColorspace) ||
(image->colorspace != CMYKColorspace)) &&
(image_info->colorspace != CMYKColorspace))
{
(void) TransformImageColorspace(image,sRGBColorspace);
(void) WriteBlobMSBShort(image,(unsigned short)
(image->storage_class == PseudoClass ? IndexedMode : RGBMode));
}
else
{
if (image->colorspace != CMYKColorspace)
(void) TransformImageColorspace(image,CMYKColorspace);
(void) WriteBlobMSBShort(image,CMYKMode);
}
}
if ((IsGrayImage(image,&image->exception) != MagickFalse) ||
(image->storage_class == DirectClass) || (image->colors > 256))
(void) WriteBlobMSBLong(image,0);
else
{
/*
Write PSD raster colormap.
*/
(void) WriteBlobMSBLong(image,768);
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].red));
for ( ; i < 256; i++)
(void) WriteBlobByte(image,0);
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(
image->colormap[i].green));
for ( ; i < 256; i++)
(void) WriteBlobByte(image,0);
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].blue));
for ( ; i < 256; i++)
(void) WriteBlobByte(image,0);
}
/*
Image resource block.
*/
length=28; /* 0x03EB */
bim_profile=(StringInfo *) GetImageProfile(image,"8bim");
icc_profile=GetImageProfile(image,"icc");
if (bim_profile != (StringInfo *) NULL)
{
bim_profile=CloneStringInfo(bim_profile);
if (icc_profile != (StringInfo *) NULL)
RemoveICCProfileFromResourceBlock(bim_profile);
RemoveResolutionFromResourceBlock(bim_profile);
length+=PSDQuantum(GetStringInfoLength(bim_profile));
}
if (icc_profile != (const StringInfo *) NULL)
length+=PSDQuantum(GetStringInfoLength(icc_profile))+12;
(void) WriteBlobMSBLong(image,(unsigned int) length);
WriteResolutionResourceBlock(image);
if (bim_profile != (StringInfo *) NULL)
{
(void) WriteBlob(image,GetStringInfoLength(bim_profile),
GetStringInfoDatum(bim_profile));
bim_profile=DestroyStringInfo(bim_profile);
}
if (icc_profile != (StringInfo *) NULL)
{
(void) WriteBlob(image,4,(const unsigned char *) "8BIM");
(void) WriteBlobMSBShort(image,0x0000040F);
(void) WriteBlobMSBShort(image,0);
(void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength(
icc_profile));
(void) WriteBlob(image,GetStringInfoLength(icc_profile),
GetStringInfoDatum(icc_profile));
if ((MagickOffsetType) GetStringInfoLength(icc_profile) !=
PSDQuantum(GetStringInfoLength(icc_profile)))
(void) WriteBlobByte(image,0);
}
layer_count=0;
layer_info_size=2;
base_image=GetNextImageInList(image);
if (base_image == (Image *) NULL)
base_image=image;
next_image=base_image;
while (next_image != (Image *) NULL)
{
packet_size=next_image->depth > 8 ? 2UL : 1UL;
if (IsGrayImage(next_image,&image->exception) != MagickFalse)
num_channels=next_image->matte != MagickFalse ? 2UL : 1UL;
else
if (next_image->storage_class == PseudoClass)
num_channels=next_image->matte != MagickFalse ? 2UL : 1UL;
else
if (next_image->colorspace != CMYKColorspace)
num_channels=next_image->matte != MagickFalse ? 4UL : 3UL;
else
num_channels=next_image->matte != MagickFalse ? 5UL : 4UL;
channelLength=(size_t) (next_image->columns*next_image->rows*packet_size+2);
layer_info_size+=(size_t) (4*4+2+num_channels*6+(psd_info.version == 1 ? 8 :
16)+4*1+4+num_channels*channelLength);
property=(const char *) GetImageProperty(next_image,"label");
if (property == (const char *) NULL)
layer_info_size+=16;
else
{
size_t
length;
length=strlen(property);
layer_info_size+=8+length+(4-(length % 4));
}
layer_count++;
next_image=GetNextImageInList(next_image);
}
if (layer_count == 0)
(void) SetPSDSize(&psd_info,image,0);
else
{
CompressionType
compression;
(void) SetPSDSize(&psd_info,image,layer_info_size+
(psd_info.version == 1 ? 8 : 16));
if ((layer_info_size/2) != ((layer_info_size+1)/2))
rounded_layer_info_size=layer_info_size+1;
else
rounded_layer_info_size=layer_info_size;
(void) SetPSDSize(&psd_info,image,rounded_layer_info_size);
if (image->matte != MagickFalse)
(void) WriteBlobMSBShort(image,-(unsigned short) layer_count);
else
(void) WriteBlobMSBShort(image,(unsigned short) layer_count);
layer_count=1;
compression=base_image->compression;
for (next_image=base_image; next_image != NULL; )
{
next_image->compression=NoCompression;
(void) WriteBlobMSBLong(image,(unsigned int) next_image->page.y);
(void) WriteBlobMSBLong(image,(unsigned int) next_image->page.x);
(void) WriteBlobMSBLong(image,(unsigned int) (next_image->page.y+
next_image->rows));
(void) WriteBlobMSBLong(image,(unsigned int) (next_image->page.x+
next_image->columns));
packet_size=next_image->depth > 8 ? 2UL : 1UL;
channel_size=(unsigned int) ((packet_size*next_image->rows*
next_image->columns)+2);
if ((IsGrayImage(next_image,&image->exception) != MagickFalse) ||
(next_image->storage_class == PseudoClass))
{
(void) WriteBlobMSBShort(image,(unsigned short)
(next_image->matte != MagickFalse ? 2 : 1));
(void) WriteBlobMSBShort(image,0);
(void) SetPSDSize(&psd_info,image,channel_size);
if (next_image->matte != MagickFalse)
{
(void) WriteBlobMSBShort(image,(unsigned short) -1);
(void) SetPSDSize(&psd_info,image,channel_size);
}
}
else
if (next_image->colorspace != CMYKColorspace)
{
(void) WriteBlobMSBShort(image,(unsigned short)
(next_image->matte != MagickFalse ? 4 : 3));
(void) WriteBlobMSBShort(image,0);
(void) SetPSDSize(&psd_info,image,channel_size);
(void) WriteBlobMSBShort(image,1);
(void) SetPSDSize(&psd_info,image,channel_size);
(void) WriteBlobMSBShort(image,2);
(void) SetPSDSize(&psd_info,image,channel_size);
if (next_image->matte!= MagickFalse )
{
(void) WriteBlobMSBShort(image,(unsigned short) -1);
(void) SetPSDSize(&psd_info,image,channel_size);
}
}
else
{
(void) WriteBlobMSBShort(image,(unsigned short)
(next_image->matte ? 5 : 4));
(void) WriteBlobMSBShort(image,0);
(void) SetPSDSize(&psd_info,image,channel_size);
(void) WriteBlobMSBShort(image,1);
(void) SetPSDSize(&psd_info,image,channel_size);
(void) WriteBlobMSBShort(image,2);
(void) SetPSDSize(&psd_info,image,channel_size);
(void) WriteBlobMSBShort(image,3);
(void) SetPSDSize(&psd_info,image,channel_size);
if (next_image->matte)
{
(void) WriteBlobMSBShort(image,(unsigned short) -1);
(void) SetPSDSize(&psd_info,image,channel_size);
}
}
(void) WriteBlob(image,4,(const unsigned char *) "8BIM");
(void) WriteBlob(image,4,(const unsigned char *)
CompositeOperatorToPSDBlendMode(next_image->compose));
(void) WriteBlobByte(image,255); /* layer opacity */
(void) WriteBlobByte(image,0);
(void) WriteBlobByte(image,next_image->compose==NoCompositeOp ?
1 << 0x02 : 1); /* layer properties - visible, etc. */
(void) WriteBlobByte(image,0);
property=(const char *) GetImageProperty(next_image,"label");
if (property == (const char *) NULL)
{
char
layer_name[MaxTextExtent];
(void) WriteBlobMSBLong(image,16);
(void) WriteBlobMSBLong(image,0);
(void) WriteBlobMSBLong(image,0);
(void) FormatLocaleString(layer_name,MaxTextExtent,"L%04ld",(long)
layer_count++);
WritePascalString(image,layer_name,4);
}
else
{
size_t
length;
length=strlen(property);
(void) WriteBlobMSBLong(image,(unsigned int) (length+(4-
(length % 4))+8));
(void) WriteBlobMSBLong(image,0);
(void) WriteBlobMSBLong(image,0);
WritePascalString(image,property,4);
}
next_image=GetNextImageInList(next_image);
}
/*
Now the image data!
*/
next_image=base_image;
while (next_image != NULL)
{
status=WriteImageChannels(&psd_info,image_info,image,next_image,
MagickTrue);
next_image=GetNextImageInList(next_image);
}
(void) WriteBlobMSBLong(image,0); /* user mask data */
base_image->compression=compression;
}
/*
Write composite image.
*/
if (status != MagickFalse)
status=WriteImageChannels(&psd_info,image_info,image,image,MagickFalse);
(void) CloseBlob(image);
return(status);
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_5317_0 |
crossvul-cpp_data_good_1287_0 | /**
* @file parser.c
* @author Radek Krejci <rkrejci@cesnet.cz>
* @brief common libyang parsers routines implementations
*
* Copyright (c) 2015-2017 CESNET, z.s.p.o.
*
* This source code is licensed under BSD 3-Clause License (the "License").
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*/
#define _GNU_SOURCE
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <pcre.h>
#include <time.h>
#include "common.h"
#include "context.h"
#include "libyang.h"
#include "parser.h"
#include "resolve.h"
#include "tree_internal.h"
#include "parser_yang.h"
#include "xpath.h"
#define LYP_URANGE_LEN 19
static char *lyp_ublock2urange[][2] = {
{"BasicLatin", "[\\x{0000}-\\x{007F}]"},
{"Latin-1Supplement", "[\\x{0080}-\\x{00FF}]"},
{"LatinExtended-A", "[\\x{0100}-\\x{017F}]"},
{"LatinExtended-B", "[\\x{0180}-\\x{024F}]"},
{"IPAExtensions", "[\\x{0250}-\\x{02AF}]"},
{"SpacingModifierLetters", "[\\x{02B0}-\\x{02FF}]"},
{"CombiningDiacriticalMarks", "[\\x{0300}-\\x{036F}]"},
{"Greek", "[\\x{0370}-\\x{03FF}]"},
{"Cyrillic", "[\\x{0400}-\\x{04FF}]"},
{"Armenian", "[\\x{0530}-\\x{058F}]"},
{"Hebrew", "[\\x{0590}-\\x{05FF}]"},
{"Arabic", "[\\x{0600}-\\x{06FF}]"},
{"Syriac", "[\\x{0700}-\\x{074F}]"},
{"Thaana", "[\\x{0780}-\\x{07BF}]"},
{"Devanagari", "[\\x{0900}-\\x{097F}]"},
{"Bengali", "[\\x{0980}-\\x{09FF}]"},
{"Gurmukhi", "[\\x{0A00}-\\x{0A7F}]"},
{"Gujarati", "[\\x{0A80}-\\x{0AFF}]"},
{"Oriya", "[\\x{0B00}-\\x{0B7F}]"},
{"Tamil", "[\\x{0B80}-\\x{0BFF}]"},
{"Telugu", "[\\x{0C00}-\\x{0C7F}]"},
{"Kannada", "[\\x{0C80}-\\x{0CFF}]"},
{"Malayalam", "[\\x{0D00}-\\x{0D7F}]"},
{"Sinhala", "[\\x{0D80}-\\x{0DFF}]"},
{"Thai", "[\\x{0E00}-\\x{0E7F}]"},
{"Lao", "[\\x{0E80}-\\x{0EFF}]"},
{"Tibetan", "[\\x{0F00}-\\x{0FFF}]"},
{"Myanmar", "[\\x{1000}-\\x{109F}]"},
{"Georgian", "[\\x{10A0}-\\x{10FF}]"},
{"HangulJamo", "[\\x{1100}-\\x{11FF}]"},
{"Ethiopic", "[\\x{1200}-\\x{137F}]"},
{"Cherokee", "[\\x{13A0}-\\x{13FF}]"},
{"UnifiedCanadianAboriginalSyllabics", "[\\x{1400}-\\x{167F}]"},
{"Ogham", "[\\x{1680}-\\x{169F}]"},
{"Runic", "[\\x{16A0}-\\x{16FF}]"},
{"Khmer", "[\\x{1780}-\\x{17FF}]"},
{"Mongolian", "[\\x{1800}-\\x{18AF}]"},
{"LatinExtendedAdditional", "[\\x{1E00}-\\x{1EFF}]"},
{"GreekExtended", "[\\x{1F00}-\\x{1FFF}]"},
{"GeneralPunctuation", "[\\x{2000}-\\x{206F}]"},
{"SuperscriptsandSubscripts", "[\\x{2070}-\\x{209F}]"},
{"CurrencySymbols", "[\\x{20A0}-\\x{20CF}]"},
{"CombiningMarksforSymbols", "[\\x{20D0}-\\x{20FF}]"},
{"LetterlikeSymbols", "[\\x{2100}-\\x{214F}]"},
{"NumberForms", "[\\x{2150}-\\x{218F}]"},
{"Arrows", "[\\x{2190}-\\x{21FF}]"},
{"MathematicalOperators", "[\\x{2200}-\\x{22FF}]"},
{"MiscellaneousTechnical", "[\\x{2300}-\\x{23FF}]"},
{"ControlPictures", "[\\x{2400}-\\x{243F}]"},
{"OpticalCharacterRecognition", "[\\x{2440}-\\x{245F}]"},
{"EnclosedAlphanumerics", "[\\x{2460}-\\x{24FF}]"},
{"BoxDrawing", "[\\x{2500}-\\x{257F}]"},
{"BlockElements", "[\\x{2580}-\\x{259F}]"},
{"GeometricShapes", "[\\x{25A0}-\\x{25FF}]"},
{"MiscellaneousSymbols", "[\\x{2600}-\\x{26FF}]"},
{"Dingbats", "[\\x{2700}-\\x{27BF}]"},
{"BraillePatterns", "[\\x{2800}-\\x{28FF}]"},
{"CJKRadicalsSupplement", "[\\x{2E80}-\\x{2EFF}]"},
{"KangxiRadicals", "[\\x{2F00}-\\x{2FDF}]"},
{"IdeographicDescriptionCharacters", "[\\x{2FF0}-\\x{2FFF}]"},
{"CJKSymbolsandPunctuation", "[\\x{3000}-\\x{303F}]"},
{"Hiragana", "[\\x{3040}-\\x{309F}]"},
{"Katakana", "[\\x{30A0}-\\x{30FF}]"},
{"Bopomofo", "[\\x{3100}-\\x{312F}]"},
{"HangulCompatibilityJamo", "[\\x{3130}-\\x{318F}]"},
{"Kanbun", "[\\x{3190}-\\x{319F}]"},
{"BopomofoExtended", "[\\x{31A0}-\\x{31BF}]"},
{"EnclosedCJKLettersandMonths", "[\\x{3200}-\\x{32FF}]"},
{"CJKCompatibility", "[\\x{3300}-\\x{33FF}]"},
{"CJKUnifiedIdeographsExtensionA", "[\\x{3400}-\\x{4DB5}]"},
{"CJKUnifiedIdeographs", "[\\x{4E00}-\\x{9FFF}]"},
{"YiSyllables", "[\\x{A000}-\\x{A48F}]"},
{"YiRadicals", "[\\x{A490}-\\x{A4CF}]"},
{"HangulSyllables", "[\\x{AC00}-\\x{D7A3}]"},
{"PrivateUse", "[\\x{E000}-\\x{F8FF}]"},
{"CJKCompatibilityIdeographs", "[\\x{F900}-\\x{FAFF}]"},
{"AlphabeticPresentationForms", "[\\x{FB00}-\\x{FB4F}]"},
{"ArabicPresentationForms-A", "[\\x{FB50}-\\x{FDFF}]"},
{"CombiningHalfMarks", "[\\x{FE20}-\\x{FE2F}]"},
{"CJKCompatibilityForms", "[\\x{FE30}-\\x{FE4F}]"},
{"SmallFormVariants", "[\\x{FE50}-\\x{FE6F}]"},
{"ArabicPresentationForms-B", "[\\x{FE70}-\\x{FEFE}]"},
{"HalfwidthandFullwidthForms", "[\\x{FF00}-\\x{FFEF}]"},
{NULL, NULL}
};
const char *ly_stmt_str[] = {
[LY_STMT_UNKNOWN] = "",
[LY_STMT_ARGUMENT] = "argument",
[LY_STMT_BASE] = "base",
[LY_STMT_BELONGSTO] = "belongs-to",
[LY_STMT_CONTACT] = "contact",
[LY_STMT_DEFAULT] = "default",
[LY_STMT_DESCRIPTION] = "description",
[LY_STMT_ERRTAG] = "error-app-tag",
[LY_STMT_ERRMSG] = "error-message",
[LY_STMT_KEY] = "key",
[LY_STMT_NAMESPACE] = "namespace",
[LY_STMT_ORGANIZATION] = "organization",
[LY_STMT_PATH] = "path",
[LY_STMT_PREFIX] = "prefix",
[LY_STMT_PRESENCE] = "presence",
[LY_STMT_REFERENCE] = "reference",
[LY_STMT_REVISIONDATE] = "revision-date",
[LY_STMT_UNITS] = "units",
[LY_STMT_VALUE] = "value",
[LY_STMT_VERSION] = "yang-version",
[LY_STMT_MODIFIER] = "modifier",
[LY_STMT_REQINSTANCE] = "require-instance",
[LY_STMT_YINELEM] = "yin-element",
[LY_STMT_CONFIG] = "config",
[LY_STMT_MANDATORY] = "mandatory",
[LY_STMT_ORDEREDBY] = "ordered-by",
[LY_STMT_STATUS] = "status",
[LY_STMT_DIGITS] = "fraction-digits",
[LY_STMT_MAX] = "max-elements",
[LY_STMT_MIN] = "min-elements",
[LY_STMT_POSITION] = "position",
[LY_STMT_UNIQUE] = "unique",
[LY_STMT_MODULE] = "module",
[LY_STMT_SUBMODULE] = "submodule",
[LY_STMT_ACTION] = "action",
[LY_STMT_ANYDATA] = "anydata",
[LY_STMT_ANYXML] = "anyxml",
[LY_STMT_CASE] = "case",
[LY_STMT_CHOICE] = "choice",
[LY_STMT_CONTAINER] = "container",
[LY_STMT_GROUPING] = "grouping",
[LY_STMT_INPUT] = "input",
[LY_STMT_LEAF] = "leaf",
[LY_STMT_LEAFLIST] = "leaf-list",
[LY_STMT_LIST] = "list",
[LY_STMT_NOTIFICATION] = "notification",
[LY_STMT_OUTPUT] = "output",
[LY_STMT_RPC] = "rpc",
[LY_STMT_USES] = "uses",
[LY_STMT_TYPEDEF] = "typedef",
[LY_STMT_TYPE] = "type",
[LY_STMT_BIT] = "bit",
[LY_STMT_ENUM] = "enum",
[LY_STMT_REFINE] = "refine",
[LY_STMT_AUGMENT] = "augment",
[LY_STMT_DEVIATE] = "deviate",
[LY_STMT_DEVIATION] = "deviation",
[LY_STMT_EXTENSION] = "extension",
[LY_STMT_FEATURE] = "feature",
[LY_STMT_IDENTITY] = "identity",
[LY_STMT_IFFEATURE] = "if-feature",
[LY_STMT_IMPORT] = "import",
[LY_STMT_INCLUDE] = "include",
[LY_STMT_LENGTH] = "length",
[LY_STMT_MUST] = "must",
[LY_STMT_PATTERN] = "pattern",
[LY_STMT_RANGE] = "range",
[LY_STMT_WHEN] = "when",
[LY_STMT_REVISION] = "revision"
};
int
lyp_is_rpc_action(struct lys_node *node)
{
assert(node);
while (lys_parent(node)) {
node = lys_parent(node);
if (node->nodetype == LYS_ACTION) {
break;
}
}
if (node->nodetype & (LYS_RPC | LYS_ACTION)) {
return 1;
} else {
return 0;
}
}
int
lyp_data_check_options(struct ly_ctx *ctx, int options, const char *func)
{
int x = options & LYD_OPT_TYPEMASK;
/* LYD_OPT_WHENAUTODEL can be used only with LYD_OPT_DATA or LYD_OPT_CONFIG */
if (options & LYD_OPT_WHENAUTODEL) {
if ((x == LYD_OPT_EDIT) || (x == LYD_OPT_NOTIF_FILTER)) {
LOGERR(ctx, LY_EINVAL, "%s: Invalid options 0x%x (LYD_OPT_DATA_WHENAUTODEL can be used only with LYD_OPT_DATA or LYD_OPT_CONFIG)",
func, options);
return 1;
}
}
if (options & (LYD_OPT_DATA_ADD_YANGLIB | LYD_OPT_DATA_NO_YANGLIB)) {
if (x != LYD_OPT_DATA) {
LOGERR(ctx, LY_EINVAL, "%s: Invalid options 0x%x (LYD_OPT_DATA_*_YANGLIB can be used only with LYD_OPT_DATA)",
func, options);
return 1;
}
}
/* "is power of 2" algorithm, with 0 exception */
if (x && !(x && !(x & (x - 1)))) {
LOGERR(ctx, LY_EINVAL, "%s: Invalid options 0x%x (multiple data type flags set).", func, options);
return 1;
}
return 0;
}
int
lyp_mmap(struct ly_ctx *ctx, int fd, size_t addsize, size_t *length, void **addr)
{
struct stat sb;
long pagesize;
size_t m;
assert(fd >= 0);
if (fstat(fd, &sb) == -1) {
LOGERR(ctx, LY_ESYS, "Failed to stat the file descriptor (%s) for the mmap().", strerror(errno));
return 1;
}
if (!S_ISREG(sb.st_mode)) {
LOGERR(ctx, LY_EINVAL, "File to mmap() is not a regular file.");
return 1;
}
if (!sb.st_size) {
*addr = NULL;
return 0;
}
pagesize = sysconf(_SC_PAGESIZE);
++addsize; /* at least one additional byte for terminating NULL byte */
m = sb.st_size % pagesize;
if (m && pagesize - m >= addsize) {
/* there will be enough space after the file content mapping to provide zeroed additional bytes */
*length = sb.st_size + addsize;
*addr = mmap(NULL, *length, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
} else {
/* there will not be enough bytes after the file content mapping for the additional bytes and some of them
* would overflow into another page that would not be zeroed and any access into it would generate SIGBUS.
* Therefore we have to do the following hack with double mapping. First, the required number of bytes
* (including the additional bytes) is required as anonymous and thus they will be really provided (actually more
* because of using whole pages) and also initialized by zeros. Then, the file is mapped to the same address
* where the anonymous mapping starts. */
*length = sb.st_size + pagesize;
*addr = mmap(NULL, *length, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
*addr = mmap(*addr, sb.st_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED, fd, 0);
}
if (*addr == MAP_FAILED) {
LOGERR(ctx, LY_ESYS, "mmap() failed (%s).", strerror(errno));
return 1;
}
return 0;
}
int
lyp_munmap(void *addr, size_t length)
{
return munmap(addr, length);
}
int
lyp_add_ietf_netconf_annotations_config(struct lys_module *mod)
{
void *reallocated;
struct lys_ext_instance_complex *op;
struct lys_type **type;
struct lys_node_anydata *anyxml;
int i;
struct ly_ctx *ctx = mod->ctx; /* shortcut */
reallocated = realloc(mod->ext, (mod->ext_size + 3) * sizeof *mod->ext);
LY_CHECK_ERR_RETURN(!reallocated, LOGMEM(ctx), EXIT_FAILURE);
mod->ext = reallocated;
/* 1) edit-config's operation */
op = calloc(1, (sizeof(struct lys_ext_instance_complex) - 1) + 5 * sizeof(void*) + sizeof(uint16_t));
LY_CHECK_ERR_RETURN(!op, LOGMEM(ctx), EXIT_FAILURE);
mod->ext[mod->ext_size] = (struct lys_ext_instance *)op;
op->arg_value = lydict_insert(ctx, "operation", 9);
op->def = &ctx->models.list[0]->extensions[0];
op->ext_type = LYEXT_COMPLEX;
op->module = op->parent = mod;
op->parent_type = LYEXT_PAR_MODULE;
op->substmt = ((struct lyext_plugin_complex *)op->def->plugin)->substmt;
op->nodetype = LYS_EXT;
type = (struct lys_type**)&op->content; /* type is stored at offset 0 */
*type = calloc(1, sizeof(struct lys_type));
LY_CHECK_ERR_RETURN(!*type, LOGMEM(ctx), EXIT_FAILURE);
(*type)->base = LY_TYPE_ENUM;
(*type)->der = ly_types[LY_TYPE_ENUM];
(*type)->parent = (struct lys_tpdf *)op;
(*type)->info.enums.count = 5;
(*type)->info.enums.enm = calloc(5, sizeof *(*type)->info.enums.enm);
LY_CHECK_ERR_RETURN(!(*type)->info.enums.enm, LOGMEM(ctx), EXIT_FAILURE);
(*type)->info.enums.enm[0].value = 0;
(*type)->info.enums.enm[0].name = lydict_insert(ctx, "merge", 5);
(*type)->info.enums.enm[1].value = 1;
(*type)->info.enums.enm[1].name = lydict_insert(ctx, "replace", 7);
(*type)->info.enums.enm[2].value = 2;
(*type)->info.enums.enm[2].name = lydict_insert(ctx, "create", 6);
(*type)->info.enums.enm[3].value = 3;
(*type)->info.enums.enm[3].name = lydict_insert(ctx, "delete", 6);
(*type)->info.enums.enm[4].value = 4;
(*type)->info.enums.enm[4].name = lydict_insert(ctx, "remove", 6);
mod->ext_size++;
/* 2) filter's type */
op = calloc(1, (sizeof(struct lys_ext_instance_complex) - 1) + 5 * sizeof(void*) + sizeof(uint16_t));
LY_CHECK_ERR_RETURN(!op, LOGMEM(ctx), EXIT_FAILURE);
mod->ext[mod->ext_size] = (struct lys_ext_instance *)op;
op->arg_value = lydict_insert(ctx, "type", 4);
op->def = &ctx->models.list[0]->extensions[0];
op->ext_type = LYEXT_COMPLEX;
op->module = op->parent = mod;
op->parent_type = LYEXT_PAR_MODULE;
op->substmt = ((struct lyext_plugin_complex *)op->def->plugin)->substmt;
op->nodetype = LYS_EXT;
type = (struct lys_type**)&op->content; /* type is stored at offset 0 */
*type = calloc(1, sizeof(struct lys_type));
LY_CHECK_ERR_RETURN(!*type, LOGMEM(ctx), EXIT_FAILURE);
(*type)->base = LY_TYPE_ENUM;
(*type)->der = ly_types[LY_TYPE_ENUM];
(*type)->parent = (struct lys_tpdf *)op;
(*type)->info.enums.count = 2;
(*type)->info.enums.enm = calloc(2, sizeof *(*type)->info.enums.enm);
LY_CHECK_ERR_RETURN(!(*type)->info.enums.enm, LOGMEM(ctx), EXIT_FAILURE);
(*type)->info.enums.enm[0].value = 0;
(*type)->info.enums.enm[0].name = lydict_insert(ctx, "subtree", 7);
(*type)->info.enums.enm[1].value = 1;
(*type)->info.enums.enm[1].name = lydict_insert(ctx, "xpath", 5);
for (i = mod->features_size; i > 0; i--) {
if (!strcmp(mod->features[i - 1].name, "xpath")) {
(*type)->info.enums.enm[1].iffeature_size = 1;
(*type)->info.enums.enm[1].iffeature = calloc(1, sizeof(struct lys_feature));
LY_CHECK_ERR_RETURN(!(*type)->info.enums.enm[1].iffeature, LOGMEM(ctx), EXIT_FAILURE);
(*type)->info.enums.enm[1].iffeature[0].expr = malloc(sizeof(uint8_t));
LY_CHECK_ERR_RETURN(!(*type)->info.enums.enm[1].iffeature[0].expr, LOGMEM(ctx), EXIT_FAILURE);
*(*type)->info.enums.enm[1].iffeature[0].expr = 3; /* LYS_IFF_F */
(*type)->info.enums.enm[1].iffeature[0].features = malloc(sizeof(struct lys_feature*));
LY_CHECK_ERR_RETURN(!(*type)->info.enums.enm[1].iffeature[0].features, LOGMEM(ctx), EXIT_FAILURE);
(*type)->info.enums.enm[1].iffeature[0].features[0] = &mod->features[i - 1];
break;
}
}
mod->ext_size++;
/* 3) filter's select */
op = calloc(1, (sizeof(struct lys_ext_instance_complex) - 1) + 5 * sizeof(void*) + sizeof(uint16_t));
LY_CHECK_ERR_RETURN(!op, LOGMEM(ctx), EXIT_FAILURE);
mod->ext[mod->ext_size] = (struct lys_ext_instance *)op;
op->arg_value = lydict_insert(ctx, "select", 6);
op->def = &ctx->models.list[0]->extensions[0];
op->ext_type = LYEXT_COMPLEX;
op->module = op->parent = mod;
op->parent_type = LYEXT_PAR_MODULE;
op->substmt = ((struct lyext_plugin_complex *)op->def->plugin)->substmt;
op->nodetype = LYS_EXT;
type = (struct lys_type**)&op->content; /* type is stored at offset 0 */
*type = calloc(1, sizeof(struct lys_type));
LY_CHECK_ERR_RETURN(!*type, LOGMEM(ctx), EXIT_FAILURE);
(*type)->base = LY_TYPE_STRING;
(*type)->der = ly_types[LY_TYPE_STRING];
(*type)->parent = (struct lys_tpdf *)op;
mod->ext_size++;
/* 4) URL config */
anyxml = calloc(1, sizeof *anyxml);
LY_CHECK_ERR_RETURN(!anyxml, LOGMEM(ctx), EXIT_FAILURE);
anyxml->nodetype = LYS_ANYXML;
anyxml->prev = (struct lys_node *)anyxml;
anyxml->name = lydict_insert(ctx, "config", 0);
anyxml->module = mod;
anyxml->flags = LYS_CONFIG_W;
if (lys_node_addchild(NULL, mod, (struct lys_node *)anyxml, 0)) {
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
/* logs directly
* base: 0 - to accept decimal, octal, hexadecimal (in default value)
* 10 - to accept only decimal (instance value)
*/
static int
parse_int(const char *val_str, int64_t min, int64_t max, int base, int64_t *ret, struct lyd_node *node)
{
char *strptr;
assert(node);
if (!val_str || !val_str[0]) {
goto error;
}
/* convert to 64-bit integer, all the redundant characters are handled */
errno = 0;
strptr = NULL;
/* parse the value */
*ret = strtoll(val_str, &strptr, base);
if (errno || (*ret < min) || (*ret > max)) {
goto error;
} else if (strptr && *strptr) {
while (isspace(*strptr)) {
++strptr;
}
if (*strptr) {
goto error;
}
}
return EXIT_SUCCESS;
error:
LOGVAL(node->schema->module->ctx, LYE_INVAL, LY_VLOG_LYD, node, val_str ? val_str : "", node->schema->name);
return EXIT_FAILURE;
}
/* logs directly
* base: 0 - to accept decimal, octal, hexadecimal (in default value)
* 10 - to accept only decimal (instance value)
*/
static int
parse_uint(const char *val_str, uint64_t max, int base, uint64_t *ret, struct lyd_node *node)
{
char *strptr;
uint64_t u;
assert(node);
if (!val_str || !val_str[0]) {
goto error;
}
errno = 0;
strptr = NULL;
u = strtoull(val_str, &strptr, base);
if (errno || (u > max)) {
goto error;
} else if (strptr && *strptr) {
while (isspace(*strptr)) {
++strptr;
}
if (*strptr) {
goto error;
}
} else if (u != 0 && val_str[0] == '-') {
goto error;
}
*ret = u;
return EXIT_SUCCESS;
error:
LOGVAL(node->schema->module->ctx, LYE_INVAL, LY_VLOG_LYD, node, val_str ? val_str : "", node->schema->name);
return EXIT_FAILURE;
}
/* logs directly
*
* kind == 0 - unsigned (unum used), 1 - signed (snum used), 2 - floating point (fnum used)
*/
static int
validate_length_range(uint8_t kind, uint64_t unum, int64_t snum, int64_t fnum, uint8_t fnum_dig, struct lys_type *type,
const char *val_str, struct lyd_node *node)
{
struct lys_restr *restr = NULL;
struct len_ran_intv *intv = NULL, *tmp_intv;
struct lys_type *cur_type;
struct ly_ctx *ctx = type->parent->module->ctx;
int match;
if (resolve_len_ran_interval(ctx, NULL, type, &intv)) {
/* already done during schema parsing */
LOGINT(ctx);
return EXIT_FAILURE;
}
if (!intv) {
return EXIT_SUCCESS;
}
/* I know that all intervals belonging to a single restriction share one type pointer */
tmp_intv = intv;
cur_type = intv->type;
do {
match = 0;
for (; tmp_intv && (tmp_intv->type == cur_type); tmp_intv = tmp_intv->next) {
if (match) {
/* just iterate through the rest of this restriction intervals */
continue;
}
if (((kind == 0) && (unum < tmp_intv->value.uval.min))
|| ((kind == 1) && (snum < tmp_intv->value.sval.min))
|| ((kind == 2) && (dec64cmp(fnum, fnum_dig, tmp_intv->value.fval.min, cur_type->info.dec64.dig) < 0))) {
break;
}
if (((kind == 0) && (unum >= tmp_intv->value.uval.min) && (unum <= tmp_intv->value.uval.max))
|| ((kind == 1) && (snum >= tmp_intv->value.sval.min) && (snum <= tmp_intv->value.sval.max))
|| ((kind == 2) && (dec64cmp(fnum, fnum_dig, tmp_intv->value.fval.min, cur_type->info.dec64.dig) > -1)
&& (dec64cmp(fnum, fnum_dig, tmp_intv->value.fval.max, cur_type->info.dec64.dig) < 1))) {
match = 1;
}
}
if (!match) {
break;
} else if (tmp_intv) {
cur_type = tmp_intv->type;
}
} while (tmp_intv);
while (intv) {
tmp_intv = intv->next;
free(intv);
intv = tmp_intv;
}
if (!match) {
switch (cur_type->base) {
case LY_TYPE_BINARY:
restr = cur_type->info.binary.length;
break;
case LY_TYPE_DEC64:
restr = cur_type->info.dec64.range;
break;
case LY_TYPE_INT8:
case LY_TYPE_INT16:
case LY_TYPE_INT32:
case LY_TYPE_INT64:
case LY_TYPE_UINT8:
case LY_TYPE_UINT16:
case LY_TYPE_UINT32:
case LY_TYPE_UINT64:
restr = cur_type->info.num.range;
break;
case LY_TYPE_STRING:
restr = cur_type->info.str.length;
break;
default:
LOGINT(ctx);
return EXIT_FAILURE;
}
LOGVAL(ctx, LYE_NOCONSTR, LY_VLOG_LYD, node, (val_str ? val_str : ""), restr ? restr->expr : "");
if (restr && restr->emsg) {
ly_vlog_str(ctx, LY_VLOG_PREV, restr->emsg);
}
if (restr && restr->eapptag) {
ly_err_last_set_apptag(ctx, restr->eapptag);
}
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
/* logs directly */
static int
validate_pattern(struct ly_ctx *ctx, const char *val_str, struct lys_type *type, struct lyd_node *node)
{
int rc;
unsigned int i;
#ifndef LY_ENABLED_CACHE
pcre *precomp;
#endif
assert(ctx && (type->base == LY_TYPE_STRING));
if (!val_str) {
val_str = "";
}
if (type->der && validate_pattern(ctx, val_str, &type->der->type, node)) {
return EXIT_FAILURE;
}
#ifdef LY_ENABLED_CACHE
/* there is no cache, build it */
if (!type->info.str.patterns_pcre && type->info.str.pat_count) {
type->info.str.patterns_pcre = malloc(2 * type->info.str.pat_count * sizeof *type->info.str.patterns_pcre);
LY_CHECK_ERR_RETURN(!type->info.str.patterns_pcre, LOGMEM(ctx), -1);
for (i = 0; i < type->info.str.pat_count; ++i) {
if (lyp_precompile_pattern(ctx, &type->info.str.patterns[i].expr[1],
(pcre**)&type->info.str.patterns_pcre[i * 2],
(pcre_extra**)&type->info.str.patterns_pcre[i * 2 + 1])) {
return EXIT_FAILURE;
}
}
}
#endif
for (i = 0; i < type->info.str.pat_count; ++i) {
#ifdef LY_ENABLED_CACHE
rc = pcre_exec((pcre *)type->info.str.patterns_pcre[2 * i], (pcre_extra *)type->info.str.patterns_pcre[2 * i + 1],
val_str, strlen(val_str), 0, 0, NULL, 0);
#else
if (lyp_check_pattern(ctx, &type->info.str.patterns[i].expr[1], &precomp)) {
return EXIT_FAILURE;
}
rc = pcre_exec(precomp, NULL, val_str, strlen(val_str), 0, 0, NULL, 0);
free(precomp);
#endif
if ((rc && type->info.str.patterns[i].expr[0] == 0x06) || (!rc && type->info.str.patterns[i].expr[0] == 0x15)) {
LOGVAL(ctx, LYE_NOCONSTR, LY_VLOG_LYD, node, val_str, &type->info.str.patterns[i].expr[1]);
if (type->info.str.patterns[i].emsg) {
ly_vlog_str(ctx, LY_VLOG_PREV, type->info.str.patterns[i].emsg);
}
if (type->info.str.patterns[i].eapptag) {
ly_err_last_set_apptag(ctx, type->info.str.patterns[i].eapptag);
}
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
static void
check_number(const char *str_num, const char **num_end, LY_DATA_TYPE base)
{
if (!isdigit(str_num[0]) && (str_num[0] != '-') && (str_num[0] != '+')) {
*num_end = str_num;
return;
}
if ((str_num[0] == '-') || (str_num[0] == '+')) {
++str_num;
}
while (isdigit(str_num[0])) {
++str_num;
}
if ((base != LY_TYPE_DEC64) || (str_num[0] != '.') || !isdigit(str_num[1])) {
*num_end = str_num;
return;
}
++str_num;
while (isdigit(str_num[0])) {
++str_num;
}
*num_end = str_num;
}
/**
* @brief Checks the syntax of length or range statement,
* on success checks the semantics as well. Does not log.
*
* @param[in] expr Length or range expression.
* @param[in] type Type with the restriction.
*
* @return EXIT_SUCCESS on success, EXIT_FAILURE otherwise.
*/
int
lyp_check_length_range(struct ly_ctx *ctx, const char *expr, struct lys_type *type)
{
struct len_ran_intv *intv = NULL, *tmp_intv;
const char *c = expr, *tail;
int ret = EXIT_FAILURE, flg = 1; /* first run flag */
assert(expr);
lengthpart:
while (isspace(*c)) {
c++;
}
/* lower boundary or explicit number */
if (!strncmp(c, "max", 3)) {
max:
c += 3;
while (isspace(*c)) {
c++;
}
if (*c != '\0') {
goto error;
}
goto syntax_ok;
} else if (!strncmp(c, "min", 3)) {
if (!flg) {
/* min cannot be used elsewhere than in the first length-part */
goto error;
} else {
flg = 0;
}
c += 3;
while (isspace(*c)) {
c++;
}
if (*c == '|') {
c++;
/* process next length-part */
goto lengthpart;
} else if (*c == '\0') {
goto syntax_ok;
} else if (!strncmp(c, "..", 2)) {
upper:
c += 2;
while (isspace(*c)) {
c++;
}
if (*c == '\0') {
goto error;
}
/* upper boundary */
if (!strncmp(c, "max", 3)) {
goto max;
}
check_number(c, &tail, type->base);
if (c == tail) {
goto error;
}
c = tail;
while (isspace(*c)) {
c++;
}
if (*c == '\0') {
goto syntax_ok;
} else if (*c == '|') {
c++;
/* process next length-part */
goto lengthpart;
} else {
goto error;
}
} else {
goto error;
}
} else if (isdigit(*c) || (*c == '-') || (*c == '+')) {
/* number */
check_number(c, &tail, type->base);
if (c == tail) {
goto error;
}
c = tail;
while (isspace(*c)) {
c++;
}
if (*c == '|') {
c++;
/* process next length-part */
goto lengthpart;
} else if (*c == '\0') {
goto syntax_ok;
} else if (!strncmp(c, "..", 2)) {
goto upper;
}
} else {
goto error;
}
syntax_ok:
if (resolve_len_ran_interval(ctx, expr, type, &intv)) {
goto error;
}
ret = EXIT_SUCCESS;
error:
while (intv) {
tmp_intv = intv->next;
free(intv);
intv = tmp_intv;
}
return ret;
}
/**
* @brief Checks pattern syntax. Logs directly.
*
* @param[in] pattern Pattern to check.
* @param[out] pcre_precomp Precompiled PCRE pattern. Can be NULL.
* @return EXIT_SUCCESS on success, EXIT_FAILURE otherwise.
*/
int
lyp_check_pattern(struct ly_ctx *ctx, const char *pattern, pcre **pcre_precomp)
{
int idx, idx2, start, end, err_offset, count;
char *perl_regex, *ptr;
const char *err_msg, *orig_ptr;
pcre *precomp;
/*
* adjust the expression to a Perl equivalent
*
* http://www.w3.org/TR/2004/REC-xmlschema-2-20041028/#regexs
*/
/* we need to replace all "$" with "\$", count them now */
for (count = 0, ptr = strchr(pattern, '$'); ptr; ++count, ptr = strchr(ptr + 1, '$'));
perl_regex = malloc((strlen(pattern) + 4 + count) * sizeof(char));
LY_CHECK_ERR_RETURN(!perl_regex, LOGMEM(ctx), EXIT_FAILURE);
perl_regex[0] = '\0';
ptr = perl_regex;
if (strncmp(pattern + strlen(pattern) - 2, ".*", 2)) {
/* we wil add line-end anchoring */
ptr[0] = '(';
++ptr;
}
for (orig_ptr = pattern; orig_ptr[0]; ++orig_ptr) {
if (orig_ptr[0] == '$') {
ptr += sprintf(ptr, "\\$");
} else {
ptr[0] = orig_ptr[0];
++ptr;
}
}
if (strncmp(pattern + strlen(pattern) - 2, ".*", 2)) {
ptr += sprintf(ptr, ")$");
} else {
ptr[0] = '\0';
++ptr;
}
/* substitute Unicode Character Blocks with exact Character Ranges */
while ((ptr = strstr(perl_regex, "\\p{Is"))) {
start = ptr - perl_regex;
ptr = strchr(ptr, '}');
if (!ptr) {
LOGVAL(ctx, LYE_INREGEX, LY_VLOG_NONE, NULL, pattern, perl_regex + start + 2, "unterminated character property");
free(perl_regex);
return EXIT_FAILURE;
}
end = (ptr - perl_regex) + 1;
/* need more space */
if (end - start < LYP_URANGE_LEN) {
perl_regex = ly_realloc(perl_regex, strlen(perl_regex) + (LYP_URANGE_LEN - (end - start)) + 1);
LY_CHECK_ERR_RETURN(!perl_regex, LOGMEM(ctx); free(perl_regex), EXIT_FAILURE);
}
/* find our range */
for (idx = 0; lyp_ublock2urange[idx][0]; ++idx) {
if (!strncmp(perl_regex + start + 5, lyp_ublock2urange[idx][0], strlen(lyp_ublock2urange[idx][0]))) {
break;
}
}
if (!lyp_ublock2urange[idx][0]) {
LOGVAL(ctx, LYE_INREGEX, LY_VLOG_NONE, NULL, pattern, perl_regex + start + 5, "unknown block name");
free(perl_regex);
return EXIT_FAILURE;
}
/* make the space in the string and replace the block (but we cannot include brackets if it was already enclosed in them) */
for (idx2 = 0, count = 0; idx2 < start; ++idx2) {
if ((perl_regex[idx2] == '[') && (!idx2 || (perl_regex[idx2 - 1] != '\\'))) {
++count;
}
if ((perl_regex[idx2] == ']') && (!idx2 || (perl_regex[idx2 - 1] != '\\'))) {
--count;
}
}
if (count) {
/* skip brackets */
memmove(perl_regex + start + (LYP_URANGE_LEN - 2), perl_regex + end, strlen(perl_regex + end) + 1);
memcpy(perl_regex + start, lyp_ublock2urange[idx][1] + 1, LYP_URANGE_LEN - 2);
} else {
memmove(perl_regex + start + LYP_URANGE_LEN, perl_regex + end, strlen(perl_regex + end) + 1);
memcpy(perl_regex + start, lyp_ublock2urange[idx][1], LYP_URANGE_LEN);
}
}
/* must return 0, already checked during parsing */
precomp = pcre_compile(perl_regex, PCRE_ANCHORED | PCRE_DOLLAR_ENDONLY | PCRE_NO_AUTO_CAPTURE,
&err_msg, &err_offset, NULL);
if (!precomp) {
LOGVAL(ctx, LYE_INREGEX, LY_VLOG_NONE, NULL, pattern, perl_regex + err_offset, err_msg);
free(perl_regex);
return EXIT_FAILURE;
}
free(perl_regex);
if (pcre_precomp) {
*pcre_precomp = precomp;
} else {
free(precomp);
}
return EXIT_SUCCESS;
}
int
lyp_precompile_pattern(struct ly_ctx *ctx, const char *pattern, pcre** pcre_cmp, pcre_extra **pcre_std)
{
const char *err_msg = NULL;
if (lyp_check_pattern(ctx, pattern, pcre_cmp)) {
return EXIT_FAILURE;
}
if (pcre_std && pcre_cmp) {
(*pcre_std) = pcre_study(*pcre_cmp, 0, &err_msg);
if (err_msg) {
LOGWRN(ctx, "Studying pattern \"%s\" failed (%s).", pattern, err_msg);
}
}
return EXIT_SUCCESS;
}
/**
* @brief Change the value into its canonical form. In libyang, additionally to the RFC,
* all identities have their module as a prefix in their canonical form.
*
* @param[in] ctx
* @param[in] type Type of the value.
* @param[in,out] value Original and then canonical value.
* @param[in] data1 If \p type is #LY_TYPE_BITS: (struct lys_type_bit **) type bit field,
* #LY_TYPE_DEC64: (int64_t *) parsed digits of the number itself without floating point,
* #LY_TYPE_IDENT: (const char *) local module name (identityref node module),
* #LY_TYPE_INT*: (int64_t *) parsed int number itself,
* #LY_TYPE_UINT*: (uint64_t *) parsed uint number itself,
* otherwise ignored.
* @param[in] data2 If \p type is #LY_TYPE_BITS: (int *) type bit field length,
* #LY_TYPE_DEC64: (uint8_t *) number of fraction digits (position of the floating point),
* otherwise ignored.
* @return 1 if a conversion took place, 0 if the value was kept the same, -1 on error.
*/
static int
make_canonical(struct ly_ctx *ctx, int type, const char **value, void *data1, void *data2)
{
const uint16_t buf_len = 511;
char buf[buf_len + 1];
struct lys_type_bit **bits = NULL;
struct lyxp_expr *exp;
const char *module_name, *cur_expr, *end;
int i, j, count;
int64_t num;
uint64_t unum;
uint8_t c;
#define LOGBUF(str) LOGERR(ctx, LY_EINVAL, "Value \"%s\" is too long.", str)
switch (type) {
case LY_TYPE_BITS:
bits = (struct lys_type_bit **)data1;
count = *((int *)data2);
/* in canonical form, the bits are ordered by their position */
buf[0] = '\0';
for (i = 0; i < count; i++) {
if (!bits[i]) {
/* bit not set */
continue;
}
if (buf[0]) {
LY_CHECK_ERR_RETURN(strlen(buf) + 1 + strlen(bits[i]->name) > buf_len, LOGBUF(bits[i]->name), -1);
sprintf(buf + strlen(buf), " %s", bits[i]->name);
} else {
LY_CHECK_ERR_RETURN(strlen(bits[i]->name) > buf_len, LOGBUF(bits[i]->name), -1);
strcpy(buf, bits[i]->name);
}
}
break;
case LY_TYPE_IDENT:
module_name = (const char *)data1;
/* identity must always have a prefix */
if (!strchr(*value, ':')) {
sprintf(buf, "%s:%s", module_name, *value);
} else {
strcpy(buf, *value);
}
break;
case LY_TYPE_INST:
exp = lyxp_parse_expr(ctx, *value);
LY_CHECK_ERR_RETURN(!exp, LOGINT(ctx), -1);
module_name = NULL;
count = 0;
for (i = 0; (unsigned)i < exp->used; ++i) {
cur_expr = &exp->expr[exp->expr_pos[i]];
/* copy WS */
if (i && ((end = exp->expr + exp->expr_pos[i - 1] + exp->tok_len[i - 1]) != cur_expr)) {
if (count + (cur_expr - end) > buf_len) {
lyxp_expr_free(exp);
LOGBUF(end);
return -1;
}
strncpy(&buf[count], end, cur_expr - end);
count += cur_expr - end;
}
if ((exp->tokens[i] == LYXP_TOKEN_NAMETEST) && (end = strnchr(cur_expr, ':', exp->tok_len[i]))) {
/* get the module name with ":" */
++end;
j = end - cur_expr;
if (!module_name || strncmp(cur_expr, module_name, j)) {
/* print module name with colon, it does not equal to the parent one */
if (count + j > buf_len) {
lyxp_expr_free(exp);
LOGBUF(cur_expr);
return -1;
}
strncpy(&buf[count], cur_expr, j);
count += j;
}
module_name = cur_expr;
/* copy the rest */
if (count + (exp->tok_len[i] - j) > buf_len) {
lyxp_expr_free(exp);
LOGBUF(end);
return -1;
}
strncpy(&buf[count], end, exp->tok_len[i] - j);
count += exp->tok_len[i] - j;
} else {
if (count + exp->tok_len[i] > buf_len) {
lyxp_expr_free(exp);
LOGBUF(&exp->expr[exp->expr_pos[i]]);
return -1;
}
strncpy(&buf[count], &exp->expr[exp->expr_pos[i]], exp->tok_len[i]);
count += exp->tok_len[i];
}
}
if (count > buf_len) {
LOGINT(ctx);
lyxp_expr_free(exp);
return -1;
}
buf[count] = '\0';
lyxp_expr_free(exp);
break;
case LY_TYPE_DEC64:
num = *((int64_t *)data1);
c = *((uint8_t *)data2);
if (num) {
count = sprintf(buf, "%"PRId64" ", num);
if ( (num > 0 && (count - 1) <= c)
|| (count - 2) <= c ) {
/* we have 0. value, print the value with the leading zeros
* (one for 0. and also keep the correct with of num according
* to fraction-digits value)
* for (num<0) - extra character for '-' sign */
count = sprintf(buf, "%0*"PRId64" ", (num > 0) ? (c + 1) : (c + 2), num);
}
for (i = c, j = 1; i > 0 ; i--) {
if (j && i > 1 && buf[count - 2] == '0') {
/* we have trailing zero to skip */
buf[count - 1] = '\0';
} else {
j = 0;
buf[count - 1] = buf[count - 2];
}
count--;
}
buf[count - 1] = '.';
} else {
/* zero */
sprintf(buf, "0.0");
}
break;
case LY_TYPE_INT8:
case LY_TYPE_INT16:
case LY_TYPE_INT32:
case LY_TYPE_INT64:
num = *((int64_t *)data1);
sprintf(buf, "%"PRId64, num);
break;
case LY_TYPE_UINT8:
case LY_TYPE_UINT16:
case LY_TYPE_UINT32:
case LY_TYPE_UINT64:
unum = *((uint64_t *)data1);
sprintf(buf, "%"PRIu64, unum);
break;
default:
/* should not be even called - just do nothing */
return 0;
}
if (strcmp(buf, *value)) {
lydict_remove(ctx, *value);
*value = lydict_insert(ctx, buf, 0);
return 1;
}
return 0;
#undef LOGBUF
}
static const char *
ident_val_add_module_prefix(const char *value, const struct lyxml_elem *xml, struct ly_ctx *ctx)
{
const struct lyxml_ns *ns;
const struct lys_module *mod;
char *str;
do {
LY_TREE_FOR((struct lyxml_ns *)xml->attr, ns) {
if ((ns->type == LYXML_ATTR_NS) && !ns->prefix) {
/* match */
break;
}
}
if (!ns) {
xml = xml->parent;
}
} while (!ns && xml);
if (!ns) {
/* no default namespace */
LOGINT(ctx);
return NULL;
}
/* find module */
mod = ly_ctx_get_module_by_ns(ctx, ns->value, NULL, 1);
if (!mod) {
LOGINT(ctx);
return NULL;
}
if (asprintf(&str, "%s:%s", mod->name, value) == -1) {
LOGMEM(ctx);
return NULL;
}
lydict_remove(ctx, value);
return lydict_insert_zc(ctx, str);
}
/*
* xml - optional for converting instance-identifier and identityref into JSON format
* leaf - mandatory to know the context (necessary e.g. for prefixes in idenitytref values)
* attr - alternative to leaf in case of parsing value in annotations (attributes)
* local_mod - optional if the local module dos not match the module of leaf/attr
* store - flag for union resolution - we do not want to store the result, we are just learning the type
* dflt - whether the value is a default value from the schema
* trusted - whether the value is trusted to be valid (but may not be canonical, so it is canonized)
*/
struct lys_type *
lyp_parse_value(struct lys_type *type, const char **value_, struct lyxml_elem *xml,
struct lyd_node_leaf_list *leaf, struct lyd_attr *attr, struct lys_module *local_mod,
int store, int dflt, int trusted)
{
struct lys_type *ret = NULL, *t;
struct lys_tpdf *tpdf;
enum int_log_opts prev_ilo;
int c, len, found = 0;
unsigned int i, j;
int64_t num;
uint64_t unum, uind, u = 0;
const char *ptr, *value = *value_, *itemname, *old_val_str = NULL;
struct lys_type_bit **bits = NULL;
struct lys_ident *ident;
lyd_val *val, old_val;
LY_DATA_TYPE *val_type, old_val_type;
uint8_t *val_flags, old_val_flags;
struct lyd_node *contextnode;
struct ly_ctx *ctx = type->parent->module->ctx;
assert(leaf || attr);
if (leaf) {
assert(!attr);
if (!local_mod) {
local_mod = leaf->schema->module;
}
val = &leaf->value;
val_type = &leaf->value_type;
val_flags = &leaf->value_flags;
contextnode = (struct lyd_node *)leaf;
itemname = leaf->schema->name;
} else {
assert(!leaf);
if (!local_mod) {
local_mod = attr->annotation->module;
}
val = &attr->value;
val_type = &attr->value_type;
val_flags = &attr->value_flags;
contextnode = attr->parent;
itemname = attr->name;
}
/* fully clear the value */
if (store) {
old_val_str = lydict_insert(ctx, *value_, 0);
lyd_free_value(*val, *val_type, *val_flags, type, old_val_str, &old_val, &old_val_type, &old_val_flags);
*val_flags &= ~LY_VALUE_UNRES;
}
switch (type->base) {
case LY_TYPE_BINARY:
/* get number of octets for length validation */
unum = 0;
ptr = NULL;
if (value) {
/* silently skip leading/trailing whitespaces */
for (uind = 0; isspace(value[uind]); ++uind);
ptr = &value[uind];
u = strlen(ptr);
while (u && isspace(ptr[u - 1])) {
--u;
}
unum = u;
for (uind = 0; uind < u; ++uind) {
if (ptr[uind] == '\n') {
unum--;
} else if ((ptr[uind] < '/' && ptr[uind] != '+') ||
(ptr[uind] > '9' && ptr[uind] < 'A') ||
(ptr[uind] > 'Z' && ptr[uind] < 'a') || ptr[uind] > 'z') {
if (ptr[uind] == '=') {
/* padding */
if (uind == u - 2 && ptr[uind + 1] == '=') {
found = 2;
uind++;
} else if (uind == u - 1) {
found = 1;
}
}
if (!found) {
/* error */
LOGVAL(ctx, LYE_INCHAR, LY_VLOG_LYD, contextnode, ptr[uind], &ptr[uind]);
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Invalid Base64 character.");
goto error;
}
}
}
}
if (unum & 3) {
/* base64 length must be multiple of 4 chars */
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value);
}
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Base64 encoded value length must be divisible by 4.");
goto error;
}
/* length of the encoded string */
len = ((unum / 4) * 3) - found;
if (!trusted && validate_length_range(0, len, 0, 0, 0, type, value, contextnode)) {
goto error;
}
if (value && (ptr != value || ptr[u] != '\0')) {
/* update the changed value */
ptr = lydict_insert(ctx, ptr, u);
lydict_remove(ctx, *value_);
*value_ = ptr;
}
if (store) {
/* store the result */
val->binary = value;
*val_type = LY_TYPE_BINARY;
}
break;
case LY_TYPE_BITS:
/* locate bits structure with the bits definitions
* since YANG 1.1 allows restricted bits, it is the first
* bits type with some explicit bit specification */
for (; !type->info.bits.count; type = &type->der->type);
if (value || store) {
/* allocate the array of pointers to bits definition */
bits = calloc(type->info.bits.count, sizeof *bits);
LY_CHECK_ERR_GOTO(!bits, LOGMEM(ctx), error);
}
if (!value) {
/* no bits set */
if (store) {
/* store empty array */
val->bit = bits;
*val_type = LY_TYPE_BITS;
}
break;
}
c = 0;
i = 0;
while (value[c]) {
/* skip leading whitespaces */
while (isspace(value[c])) {
c++;
}
if (!value[c]) {
/* trailing white spaces */
break;
}
/* get the length of the bit identifier */
for (len = 0; value[c] && !isspace(value[c]); c++, len++);
/* go back to the beginning of the identifier */
c = c - len;
/* find bit definition, identifiers appear ordered by their position */
for (found = i = 0; i < type->info.bits.count; i++) {
if (!strncmp(type->info.bits.bit[i].name, &value[c], len) && !type->info.bits.bit[i].name[len]) {
/* we have match, check if the value is enabled ... */
for (j = 0; !trusted && (j < type->info.bits.bit[i].iffeature_size); j++) {
if (!resolve_iffeature(&type->info.bits.bit[i].iffeature[j])) {
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value);
}
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL,
"Bit \"%s\" is disabled by its %d. if-feature condition.",
type->info.bits.bit[i].name, j + 1);
free(bits);
goto error;
}
}
/* check that the value was not already set */
if (bits[i]) {
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value);
}
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Bit \"%s\" used multiple times.",
type->info.bits.bit[i].name);
free(bits);
goto error;
}
/* ... and then store the pointer */
bits[i] = &type->info.bits.bit[i];
/* stop searching */
found = 1;
break;
}
}
if (!found) {
/* referenced bit value does not exist */
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value);
}
free(bits);
goto error;
}
c = c + len;
}
if (make_canonical(ctx, LY_TYPE_BITS, value_, bits, &type->info.bits.count) == -1) {
free(bits);
goto error;
}
if (store) {
/* store the result */
val->bit = bits;
*val_type = LY_TYPE_BITS;
} else {
free(bits);
}
break;
case LY_TYPE_BOOL:
if (value && !strcmp(value, "true")) {
if (store) {
val->bln = 1;
}
} else if (!value || strcmp(value, "false")) {
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value ? value : "", itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value ? value : "");
}
goto error;
} else {
if (store) {
val->bln = 0;
}
}
if (store) {
*val_type = LY_TYPE_BOOL;
}
break;
case LY_TYPE_DEC64:
if (!value || !value[0]) {
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, "", itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, "");
}
goto error;
}
ptr = value;
if (parse_range_dec64(&ptr, type->info.dec64.dig, &num) || ptr[0]) {
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value);
}
goto error;
}
if (!trusted && validate_length_range(2, 0, 0, num, type->info.dec64.dig, type, value, contextnode)) {
goto error;
}
if (make_canonical(ctx, LY_TYPE_DEC64, value_, &num, &type->info.dec64.dig) == -1) {
goto error;
}
if (store) {
/* store the result */
val->dec64 = num;
*val_type = LY_TYPE_DEC64;
}
break;
case LY_TYPE_EMPTY:
if (value && value[0]) {
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value);
}
goto error;
}
if (store) {
*val_type = LY_TYPE_EMPTY;
}
break;
case LY_TYPE_ENUM:
/* locate enums structure with the enumeration definitions,
* since YANG 1.1 allows restricted enums, it is the first
* enum type with some explicit enum specification */
for (; !type->info.enums.count; type = &type->der->type);
/* find matching enumeration value */
for (i = found = 0; i < type->info.enums.count; i++) {
if (value && !strcmp(value, type->info.enums.enm[i].name)) {
/* we have match, check if the value is enabled ... */
for (j = 0; !trusted && (j < type->info.enums.enm[i].iffeature_size); j++) {
if (!resolve_iffeature(&type->info.enums.enm[i].iffeature[j])) {
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value);
}
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Enum \"%s\" is disabled by its %d. if-feature condition.",
value, j + 1);
goto error;
}
}
/* ... and store pointer to the definition */
if (store) {
val->enm = &type->info.enums.enm[i];
*val_type = LY_TYPE_ENUM;
}
found = 1;
break;
}
}
if (!found) {
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value ? value : "", itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value ? value : "");
}
goto error;
}
break;
case LY_TYPE_IDENT:
if (!value) {
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, "", itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, "");
}
goto error;
}
if (xml) {
ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL);
/* first, convert value into the json format, silently */
value = transform_xml2json(ctx, value, xml, 0, 0);
ly_ilo_restore(NULL, prev_ilo, NULL, 0);
if (!value) {
/* invalid identityref format */
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, *value_, itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, *value_);
}
goto error;
}
/* the value has no prefix (default namespace), but the element's namespace has a prefix, find default namespace */
if (!strchr(value, ':') && xml->ns->prefix) {
value = ident_val_add_module_prefix(value, xml, ctx);
if (!value) {
goto error;
}
}
} else if (dflt) {
ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL);
/* the value actually uses module's prefixes instead of the module names as in JSON format,
* we have to convert it */
value = transform_schema2json(local_mod, value);
ly_ilo_restore(NULL, prev_ilo, NULL, 0);
if (!value) {
/* invalid identityref format or it was already transformed, so ignore the error here */
value = lydict_insert(ctx, *value_, 0);
}
} else {
value = lydict_insert(ctx, *value_, 0);
}
/* value is now in the dictionary, whether it differs from *value_ or not */
ident = resolve_identref(type, value, contextnode, local_mod, dflt);
if (!ident) {
lydict_remove(ctx, value);
goto error;
} else if (store) {
/* store the result */
val->ident = ident;
*val_type = LY_TYPE_IDENT;
}
/* the value is always changed and includes prefix */
if (dflt) {
type->parent->flags |= LYS_DFLTJSON;
}
if (make_canonical(ctx, LY_TYPE_IDENT, &value, (void*)lys_main_module(local_mod)->name, NULL) == -1) {
lydict_remove(ctx, value);
goto error;
}
/* replace the old value with the new one (even if they may be the same) */
lydict_remove(ctx, *value_);
*value_ = value;
break;
case LY_TYPE_INST:
if (!value) {
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, "", itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, "");
}
goto error;
}
if (xml) {
ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL);
/* first, convert value into the json format, silently */
value = transform_xml2json(ctx, value, xml, 1, 1);
ly_ilo_restore(NULL, prev_ilo, NULL, 0);
if (!value) {
/* invalid instance-identifier format */
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, *value_, itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, *value_);
}
goto error;
} else if (ly_strequal(value, *value_, 1)) {
/* we have actually created the same expression (prefixes are the same as the module names)
* so we have just increased dictionary's refcount - fix it */
lydict_remove(ctx, value);
}
} else if (dflt) {
/* turn logging off */
ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL);
/* the value actually uses module's prefixes instead of the module names as in JSON format,
* we have to convert it */
value = transform_schema2json(local_mod, value);
if (!value) {
/* invalid identityref format or it was already transformed, so ignore the error here */
value = *value_;
} else if (ly_strequal(value, *value_, 1)) {
/* we have actually created the same expression (prefixes are the same as the module names)
* so we have just increased dictionary's refcount - fix it */
lydict_remove(ctx, value);
}
/* turn logging back on */
ly_ilo_restore(NULL, prev_ilo, NULL, 0);
} else {
if ((c = make_canonical(ctx, LY_TYPE_INST, &value, NULL, NULL))) {
if (c == -1) {
goto error;
}
/* if a change occurred, value was removed from the dictionary so fix the pointers */
*value_ = value;
}
}
if (store) {
/* note that the data node is an unresolved instance-identifier */
val->instance = NULL;
*val_type = LY_TYPE_INST;
*val_flags |= LY_VALUE_UNRES;
}
if (!ly_strequal(value, *value_, 1)) {
/* update the changed value */
lydict_remove(ctx, *value_);
*value_ = value;
/* we have to remember the conversion into JSON format to be able to print it in correct form */
if (dflt) {
type->parent->flags |= LYS_DFLTJSON;
}
}
break;
case LY_TYPE_LEAFREF:
if (!value) {
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, "", itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, "");
}
goto error;
}
/* it is called not only to get the final type, but mainly to update value to canonical or JSON form
* if needed */
t = lyp_parse_value(&type->info.lref.target->type, value_, xml, leaf, attr, NULL, store, dflt, trusted);
value = *value_; /* refresh possibly changed value */
if (!t) {
/* already logged */
goto error;
}
if (store) {
/* make the note that the data node is an unresolved leafref (value union was already filled) */
*val_flags |= LY_VALUE_UNRES;
}
type = t;
break;
case LY_TYPE_STRING:
if (!trusted && validate_length_range(0, (value ? ly_strlen_utf8(value) : 0), 0, 0, 0, type, value, contextnode)) {
goto error;
}
if (!trusted && validate_pattern(ctx, value, type, contextnode)) {
goto error;
}
/* special handling of ietf-yang-types xpath1.0 */
for (tpdf = type->der;
tpdf->module && (strcmp(tpdf->name, "xpath1.0") || strcmp(tpdf->module->name, "ietf-yang-types"));
tpdf = tpdf->type.der);
if (tpdf->module && xml) {
/* convert value into the json format */
value = transform_xml2json(ctx, value ? value : "", xml, 1, 1);
if (!value) {
/* invalid instance-identifier format */
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, *value_, itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, *value_);
}
goto error;
}
if (!ly_strequal(value, *value_, 1)) {
/* update the changed value */
lydict_remove(ctx, *value_);
*value_ = value;
}
}
if (store) {
/* store the result */
val->string = value;
*val_type = LY_TYPE_STRING;
}
break;
case LY_TYPE_INT8:
if (parse_int(value, __INT64_C(-128), __INT64_C(127), dflt ? 0 : 10, &num, contextnode)
|| (!trusted && validate_length_range(1, 0, num, 0, 0, type, value, contextnode))) {
goto error;
}
if (make_canonical(ctx, LY_TYPE_INT8, value_, &num, NULL) == -1) {
goto error;
}
if (store) {
/* store the result */
val->int8 = (int8_t)num;
*val_type = LY_TYPE_INT8;
}
break;
case LY_TYPE_INT16:
if (parse_int(value, __INT64_C(-32768), __INT64_C(32767), dflt ? 0 : 10, &num, contextnode)
|| (!trusted && validate_length_range(1, 0, num, 0, 0, type, value, contextnode))) {
goto error;
}
if (make_canonical(ctx, LY_TYPE_INT16, value_, &num, NULL) == -1) {
goto error;
}
if (store) {
/* store the result */
val->int16 = (int16_t)num;
*val_type = LY_TYPE_INT16;
}
break;
case LY_TYPE_INT32:
if (parse_int(value, __INT64_C(-2147483648), __INT64_C(2147483647), dflt ? 0 : 10, &num, contextnode)
|| (!trusted && validate_length_range(1, 0, num, 0, 0, type, value, contextnode))) {
goto error;
}
if (make_canonical(ctx, LY_TYPE_INT32, value_, &num, NULL) == -1) {
goto error;
}
if (store) {
/* store the result */
val->int32 = (int32_t)num;
*val_type = LY_TYPE_INT32;
}
break;
case LY_TYPE_INT64:
if (parse_int(value, __INT64_C(-9223372036854775807) - __INT64_C(1), __INT64_C(9223372036854775807),
dflt ? 0 : 10, &num, contextnode)
|| (!trusted && validate_length_range(1, 0, num, 0, 0, type, value, contextnode))) {
goto error;
}
if (make_canonical(ctx, LY_TYPE_INT64, value_, &num, NULL) == -1) {
goto error;
}
if (store) {
/* store the result */
val->int64 = num;
*val_type = LY_TYPE_INT64;
}
break;
case LY_TYPE_UINT8:
if (parse_uint(value, __UINT64_C(255), dflt ? 0 : 10, &unum, contextnode)
|| (!trusted && validate_length_range(0, unum, 0, 0, 0, type, value, contextnode))) {
goto error;
}
if (make_canonical(ctx, LY_TYPE_UINT8, value_, &unum, NULL) == -1) {
goto error;
}
if (store) {
/* store the result */
val->uint8 = (uint8_t)unum;
*val_type = LY_TYPE_UINT8;
}
break;
case LY_TYPE_UINT16:
if (parse_uint(value, __UINT64_C(65535), dflt ? 0 : 10, &unum, contextnode)
|| (!trusted && validate_length_range(0, unum, 0, 0, 0, type, value, contextnode))) {
goto error;
}
if (make_canonical(ctx, LY_TYPE_UINT16, value_, &unum, NULL) == -1) {
goto error;
}
if (store) {
/* store the result */
val->uint16 = (uint16_t)unum;
*val_type = LY_TYPE_UINT16;
}
break;
case LY_TYPE_UINT32:
if (parse_uint(value, __UINT64_C(4294967295), dflt ? 0 : 10, &unum, contextnode)
|| (!trusted && validate_length_range(0, unum, 0, 0, 0, type, value, contextnode))) {
goto error;
}
if (make_canonical(ctx, LY_TYPE_UINT32, value_, &unum, NULL) == -1) {
goto error;
}
if (store) {
/* store the result */
val->uint32 = (uint32_t)unum;
*val_type = LY_TYPE_UINT32;
}
break;
case LY_TYPE_UINT64:
if (parse_uint(value, __UINT64_C(18446744073709551615), dflt ? 0 : 10, &unum, contextnode)
|| (!trusted && validate_length_range(0, unum, 0, 0, 0, type, value, contextnode))) {
goto error;
}
if (make_canonical(ctx, LY_TYPE_UINT64, value_, &unum, NULL) == -1) {
goto error;
}
if (store) {
/* store the result */
val->uint64 = unum;
*val_type = LY_TYPE_UINT64;
}
break;
case LY_TYPE_UNION:
if (store) {
/* unresolved union type */
memset(val, 0, sizeof(lyd_val));
*val_type = LY_TYPE_UNION;
}
if (type->info.uni.has_ptr_type) {
/* we are not resolving anything here, only parsing, and in this case we cannot decide
* the type without resolving it -> we return the union type (resolve it with resolve_union()) */
if (xml) {
/* in case it should resolve into a instance-identifier, we can only do the JSON conversion here */
ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL);
val->string = transform_xml2json(ctx, value, xml, 1, 1);
ly_ilo_restore(NULL, prev_ilo, NULL, 0);
if (!val->string) {
/* invalid instance-identifier format, likely some other type */
val->string = lydict_insert(ctx, value, 0);
}
}
break;
}
t = NULL;
found = 0;
/* turn logging off, we are going to try to validate the value with all the types in order */
ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL);
while ((t = lyp_get_next_union_type(type, t, &found))) {
found = 0;
ret = lyp_parse_value(t, value_, xml, leaf, attr, NULL, store, dflt, 0);
if (ret) {
/* we have the result */
type = ret;
break;
}
if (store) {
/* erase possible present and invalid value data */
lyd_free_value(*val, *val_type, *val_flags, t, *value_, NULL, NULL, NULL);
memset(val, 0, sizeof(lyd_val));
}
}
/* turn logging back on */
ly_ilo_restore(NULL, prev_ilo, NULL, 0);
if (!t) {
/* not found */
if (store) {
*val_type = 0;
}
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, *value_ ? *value_ : "", itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, *value_);
}
goto error;
}
break;
default:
LOGINT(ctx);
goto error;
}
/* search user types in case this value is supposed to be stored in a custom way */
if (store && type->der && type->der->module) {
c = lytype_store(type->der->module, type->der->name, value_, val);
if (c == -1) {
goto error;
} else if (!c) {
*val_flags |= LY_VALUE_USER;
}
}
/* free backup */
if (store) {
lyd_free_value(old_val, old_val_type, old_val_flags, type, old_val_str, NULL, NULL, NULL);
lydict_remove(ctx, old_val_str);
}
return type;
error:
/* restore the backup */
if (store) {
*val = old_val;
*val_type = old_val_type;
*val_flags = old_val_flags;
lydict_remove(ctx, old_val_str);
}
return NULL;
}
/* does not log, cannot fail */
struct lys_type *
lyp_get_next_union_type(struct lys_type *type, struct lys_type *prev_type, int *found)
{
unsigned int i;
struct lys_type *ret = NULL;
while (!type->info.uni.count) {
assert(type->der); /* at least the direct union type has to have type specified */
type = &type->der->type;
}
for (i = 0; i < type->info.uni.count; ++i) {
if (type->info.uni.types[i].base == LY_TYPE_UNION) {
ret = lyp_get_next_union_type(&type->info.uni.types[i], prev_type, found);
if (ret) {
break;
}
continue;
}
if (!prev_type || *found) {
ret = &type->info.uni.types[i];
break;
}
if (&type->info.uni.types[i] == prev_type) {
*found = 1;
}
}
return ret;
}
/* ret 0 - ret set, ret 1 - ret not set, no log, ret -1 - ret not set, fatal error */
int
lyp_fill_attr(struct ly_ctx *ctx, struct lyd_node *parent, const char *module_ns, const char *module_name,
const char *attr_name, const char *attr_value, struct lyxml_elem *xml, int options, struct lyd_attr **ret)
{
const struct lys_module *mod = NULL;
const struct lys_submodule *submod = NULL;
struct lys_type **type;
struct lyd_attr *dattr;
int pos, i, j, k;
/* first, get module where the annotation should be defined */
if (module_ns) {
mod = (struct lys_module *)ly_ctx_get_module_by_ns(ctx, module_ns, NULL, 0);
} else if (module_name) {
mod = (struct lys_module *)ly_ctx_get_module(ctx, module_name, NULL, 0);
} else {
LOGINT(ctx);
return -1;
}
if (!mod) {
return 1;
}
/* then, find the appropriate annotation definition */
pos = -1;
for (i = 0, j = 0; i < mod->ext_size; i = i + j + 1) {
j = lys_ext_instance_presence(&ctx->models.list[0]->extensions[0], &mod->ext[i], mod->ext_size - i);
if (j == -1) {
break;
}
if (ly_strequal(mod->ext[i + j]->arg_value, attr_name, 0)) {
pos = i + j;
break;
}
}
/* try submodules */
if (pos == -1) {
for (k = 0; k < mod->inc_size; ++k) {
submod = mod->inc[k].submodule;
for (i = 0, j = 0; i < submod->ext_size; i = i + j + 1) {
j = lys_ext_instance_presence(&ctx->models.list[0]->extensions[0], &submod->ext[i], submod->ext_size - i);
if (j == -1) {
break;
}
if (ly_strequal(submod->ext[i + j]->arg_value, attr_name, 0)) {
pos = i + j;
break;
}
}
}
}
if (pos == -1) {
return 1;
}
/* allocate and fill the data attribute structure */
dattr = calloc(1, sizeof *dattr);
LY_CHECK_ERR_RETURN(!dattr, LOGMEM(ctx), -1);
dattr->parent = parent;
dattr->next = NULL;
dattr->annotation = submod ? (struct lys_ext_instance_complex *)submod->ext[pos] :
(struct lys_ext_instance_complex *)mod->ext[pos];
dattr->name = lydict_insert(ctx, attr_name, 0);
dattr->value_str = lydict_insert(ctx, attr_value, 0);
/* the value is here converted to a JSON format if needed in case of LY_TYPE_IDENT and LY_TYPE_INST or to a
* canonical form of the value */
type = lys_ext_complex_get_substmt(LY_STMT_TYPE, dattr->annotation, NULL);
if (!type || !lyp_parse_value(*type, &dattr->value_str, xml, NULL, dattr, NULL, 1, 0, options & LYD_OPT_TRUSTED)) {
lydict_remove(ctx, dattr->name);
lydict_remove(ctx, dattr->value_str);
free(dattr);
return -1;
}
*ret = dattr;
return 0;
}
int
lyp_check_edit_attr(struct ly_ctx *ctx, struct lyd_attr *attr, struct lyd_node *parent, int *editbits)
{
struct lyd_attr *last = NULL;
int bits = 0;
/* 0x01 - insert attribute present
* 0x02 - insert is relative (before or after)
* 0x04 - value attribute present
* 0x08 - key attribute present
* 0x10 - operation attribute present
* 0x20 - operation not allowing insert attribute (delete or remove)
*/
LY_TREE_FOR(attr, attr) {
last = NULL;
if (!strcmp(attr->annotation->arg_value, "operation") &&
!strcmp(attr->annotation->module->name, "ietf-netconf")) {
if (bits & 0x10) {
LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYD, parent, "operation attributes", parent->schema->name);
return -1;
}
bits |= 0x10;
if (attr->value.enm->value >= 3) {
/* delete or remove */
bits |= 0x20;
}
} else if (attr->annotation->module == ctx->models.list[1] && /* internal YANG schema */
!strcmp(attr->annotation->arg_value, "insert")) {
/* 'insert' attribute present */
if (!(parent->schema->flags & LYS_USERORDERED)) {
/* ... but it is not expected */
LOGVAL(ctx, LYE_INATTR, LY_VLOG_LYD, parent, "insert");
return -1;
}
if (bits & 0x01) {
LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYD, parent, "insert attributes", parent->schema->name);
return -1;
}
bits |= 0x01;
if (attr->value.enm->value >= 2) {
/* before or after */
bits |= 0x02;
}
last = attr;
} else if (attr->annotation->module == ctx->models.list[1] && /* internal YANG schema */
!strcmp(attr->annotation->arg_value, "value")) {
if (bits & 0x04) {
LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYD, parent, "value attributes", parent->schema->name);
return -1;
} else if (parent->schema->nodetype & LYS_LIST) {
LOGVAL(ctx, LYE_INATTR, LY_VLOG_LYD, parent, attr->name);
return -1;
}
bits |= 0x04;
last = attr;
} else if (attr->annotation->module == ctx->models.list[1] && /* internal YANG schema */
!strcmp(attr->annotation->arg_value, "key")) {
if (bits & 0x08) {
LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYD, parent, "key attributes", parent->schema->name);
return -1;
} else if (parent->schema->nodetype & LYS_LEAFLIST) {
LOGVAL(ctx, LYE_INATTR, LY_VLOG_LYD, parent, attr->name);
return -1;
}
bits |= 0x08;
last = attr;
}
}
/* report errors */
if (last && (!(parent->schema->nodetype & (LYS_LEAFLIST | LYS_LIST)) || !(parent->schema->flags & LYS_USERORDERED))) {
/* moving attributes in wrong elements (not an user ordered list or not a list at all) */
LOGVAL(ctx, LYE_INATTR, LY_VLOG_LYD, parent, last->name);
return -1;
} else if (bits == 3) {
/* 0x01 | 0x02 - relative position, but value/key is missing */
if (parent->schema->nodetype & LYS_LIST) {
LOGVAL(ctx, LYE_MISSATTR, LY_VLOG_LYD, parent, "key", parent->schema->name);
} else { /* LYS_LEAFLIST */
LOGVAL(ctx, LYE_MISSATTR, LY_VLOG_LYD, parent, "value", parent->schema->name);
}
return -1;
} else if ((bits & (0x04 | 0x08)) && !(bits & 0x02)) {
/* key/value without relative position */
LOGVAL(ctx, LYE_INATTR, LY_VLOG_LYD, parent, (bits & 0x04) ? "value" : "key");
return -1;
} else if ((bits & 0x21) == 0x21) {
/* insert in delete/remove */
LOGVAL(ctx, LYE_INATTR, LY_VLOG_LYD, parent, "insert");
return -1;
}
if (editbits) {
*editbits = bits;
}
return 0;
}
/* does not log */
static int
dup_identity_check(const char *id, struct lys_ident *ident, uint32_t size)
{
uint32_t i;
for (i = 0; i < size; i++) {
if (ly_strequal(id, ident[i].name, 1)) {
/* name collision */
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
int
dup_identities_check(const char *id, struct lys_module *module)
{
struct lys_module *mainmod;
int i;
if (dup_identity_check(id, module->ident, module->ident_size)) {
LOGVAL(module->ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "identity", id);
return EXIT_FAILURE;
}
/* check identity in submodules */
mainmod = lys_main_module(module);
for (i = 0; i < mainmod->inc_size && mainmod->inc[i].submodule; ++i) {
if (dup_identity_check(id, mainmod->inc[i].submodule->ident, mainmod->inc[i].submodule->ident_size)) {
LOGVAL(module->ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "identity", id);
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
/* does not log */
int
dup_typedef_check(const char *type, struct lys_tpdf *tpdf, int size)
{
int i;
for (i = 0; i < size; i++) {
if (!strcmp(type, tpdf[i].name)) {
/* name collision */
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
/* does not log */
static int
dup_feature_check(const char *id, struct lys_module *module)
{
int i;
for (i = 0; i < module->features_size; i++) {
if (!strcmp(id, module->features[i].name)) {
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
/* does not log */
static int
dup_prefix_check(const char *prefix, struct lys_module *module)
{
int i;
if (module->prefix && !strcmp(module->prefix, prefix)) {
return EXIT_FAILURE;
}
for (i = 0; i < module->imp_size; i++) {
if (!strcmp(module->imp[i].prefix, prefix)) {
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
/* logs directly */
int
lyp_check_identifier(struct ly_ctx *ctx, const char *id, enum LY_IDENT type, struct lys_module *module,
struct lys_node *parent)
{
int i, j;
int size;
struct lys_tpdf *tpdf;
struct lys_node *node;
struct lys_module *mainmod;
struct lys_submodule *submod;
assert(ctx && id);
/* check id syntax */
if (!(id[0] >= 'A' && id[0] <= 'Z') && !(id[0] >= 'a' && id[0] <= 'z') && id[0] != '_') {
LOGVAL(ctx, LYE_INID, LY_VLOG_NONE, NULL, id, "invalid start character");
return EXIT_FAILURE;
}
for (i = 1; id[i]; i++) {
if (!(id[i] >= 'A' && id[i] <= 'Z') && !(id[i] >= 'a' && id[i] <= 'z')
&& !(id[i] >= '0' && id[i] <= '9') && id[i] != '_' && id[i] != '-' && id[i] != '.') {
LOGVAL(ctx, LYE_INID, LY_VLOG_NONE, NULL, id, "invalid character");
return EXIT_FAILURE;
}
}
if (i > 64) {
LOGWRN(ctx, "Identifier \"%s\" is long, you should use something shorter.", id);
}
switch (type) {
case LY_IDENT_NAME:
/* check uniqueness of the node within its siblings */
if (!parent) {
break;
}
LY_TREE_FOR(parent->child, node) {
if (ly_strequal(node->name, id, 1)) {
LOGVAL(ctx, LYE_INID, LY_VLOG_NONE, NULL, id, "name duplication");
return EXIT_FAILURE;
}
}
break;
case LY_IDENT_TYPE:
assert(module);
mainmod = lys_main_module(module);
/* check collision with the built-in types */
if (!strcmp(id, "binary") || !strcmp(id, "bits") ||
!strcmp(id, "boolean") || !strcmp(id, "decimal64") ||
!strcmp(id, "empty") || !strcmp(id, "enumeration") ||
!strcmp(id, "identityref") || !strcmp(id, "instance-identifier") ||
!strcmp(id, "int8") || !strcmp(id, "int16") ||
!strcmp(id, "int32") || !strcmp(id, "int64") ||
!strcmp(id, "leafref") || !strcmp(id, "string") ||
!strcmp(id, "uint8") || !strcmp(id, "uint16") ||
!strcmp(id, "uint32") || !strcmp(id, "uint64") || !strcmp(id, "union")) {
LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, id, "typedef");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Typedef name duplicates a built-in type.");
return EXIT_FAILURE;
}
/* check locally scoped typedefs (avoid name shadowing) */
for (; parent; parent = lys_parent(parent)) {
switch (parent->nodetype) {
case LYS_CONTAINER:
size = ((struct lys_node_container *)parent)->tpdf_size;
tpdf = ((struct lys_node_container *)parent)->tpdf;
break;
case LYS_LIST:
size = ((struct lys_node_list *)parent)->tpdf_size;
tpdf = ((struct lys_node_list *)parent)->tpdf;
break;
case LYS_GROUPING:
size = ((struct lys_node_grp *)parent)->tpdf_size;
tpdf = ((struct lys_node_grp *)parent)->tpdf;
break;
default:
continue;
}
if (dup_typedef_check(id, tpdf, size)) {
LOGVAL(ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "typedef", id);
return EXIT_FAILURE;
}
}
/* check top-level names */
if (dup_typedef_check(id, module->tpdf, module->tpdf_size)) {
LOGVAL(ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "typedef", id);
return EXIT_FAILURE;
}
/* check submodule's top-level names */
for (i = 0; i < mainmod->inc_size && mainmod->inc[i].submodule; i++) {
if (dup_typedef_check(id, mainmod->inc[i].submodule->tpdf, mainmod->inc[i].submodule->tpdf_size)) {
LOGVAL(ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "typedef", id);
return EXIT_FAILURE;
}
}
break;
case LY_IDENT_PREFIX:
assert(module);
/* check the module itself */
if (dup_prefix_check(id, module)) {
LOGVAL(ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "prefix", id);
return EXIT_FAILURE;
}
break;
case LY_IDENT_FEATURE:
assert(module);
mainmod = lys_main_module(module);
/* check feature name uniqueness*/
/* check features in the current module */
if (dup_feature_check(id, module)) {
LOGVAL(ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "feature", id);
return EXIT_FAILURE;
}
/* and all its submodules */
for (i = 0; i < mainmod->inc_size && mainmod->inc[i].submodule; i++) {
if (dup_feature_check(id, (struct lys_module *)mainmod->inc[i].submodule)) {
LOGVAL(ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "feature", id);
return EXIT_FAILURE;
}
}
break;
case LY_IDENT_EXTENSION:
assert(module);
mainmod = lys_main_module(module);
/* check extension name uniqueness in the main module ... */
for (i = 0; i < mainmod->extensions_size; i++) {
if (ly_strequal(id, mainmod->extensions[i].name, 1)) {
LOGVAL(ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "extension", id);
return EXIT_FAILURE;
}
}
/* ... and all its submodules */
for (j = 0; j < mainmod->inc_size && mainmod->inc[j].submodule; j++) {
submod = mainmod->inc[j].submodule; /* shortcut */
for (i = 0; i < submod->extensions_size; i++) {
if (ly_strequal(id, submod->extensions[i].name, 1)) {
LOGVAL(ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "extension", id);
return EXIT_FAILURE;
}
}
}
break;
default:
/* no check required */
break;
}
return EXIT_SUCCESS;
}
/* logs directly */
int
lyp_check_date(struct ly_ctx *ctx, const char *date)
{
int i;
struct tm tm, tm_;
char *r;
assert(date);
/* check format */
for (i = 0; i < LY_REV_SIZE - 1; i++) {
if (i == 4 || i == 7) {
if (date[i] != '-') {
goto error;
}
} else if (!isdigit(date[i])) {
goto error;
}
}
/* check content, e.g. 2018-02-31 */
memset(&tm, 0, sizeof tm);
r = strptime(date, "%Y-%m-%d", &tm);
if (!r || r != &date[LY_REV_SIZE - 1]) {
goto error;
}
/* set some arbitrary non-0 value in case DST changes, it could move the day otherwise */
tm.tm_hour = 12;
memcpy(&tm_, &tm, sizeof tm);
mktime(&tm_); /* mktime modifies tm_ if it refers invalid date */
if (tm.tm_mday != tm_.tm_mday) { /* e.g 2018-02-29 -> 2018-03-01 */
/* checking days is enough, since other errors
* have been checked by strptime() */
goto error;
}
return EXIT_SUCCESS;
error:
LOGVAL(ctx, LYE_INDATE, LY_VLOG_NONE, NULL, date);
return EXIT_FAILURE;
}
/**
* @return
* NULL - success
* root - not yet resolvable
* other node - mandatory node under the root
*/
static const struct lys_node *
lyp_check_mandatory_(const struct lys_node *root)
{
int mand_flag = 0;
const struct lys_node *iter = NULL;
while ((iter = lys_getnext(iter, root, NULL, LYS_GETNEXT_WITHCHOICE | LYS_GETNEXT_WITHUSES | LYS_GETNEXT_INTOUSES
| LYS_GETNEXT_INTONPCONT | LYS_GETNEXT_NOSTATECHECK))) {
if (iter->nodetype == LYS_USES) {
if (!((struct lys_node_uses *)iter)->grp) {
/* not yet resolved uses */
return root;
} else {
/* go into uses */
continue;
}
}
if (iter->nodetype == LYS_CHOICE) {
/* skip it, it was already checked for direct mandatory node in default */
continue;
}
if (iter->nodetype == LYS_LIST) {
if (((struct lys_node_list *)iter)->min) {
mand_flag = 1;
}
} else if (iter->nodetype == LYS_LEAFLIST) {
if (((struct lys_node_leaflist *)iter)->min) {
mand_flag = 1;
}
} else if (iter->flags & LYS_MAND_TRUE) {
mand_flag = 1;
}
if (mand_flag) {
return iter;
}
}
return NULL;
}
/* logs directly */
int
lyp_check_mandatory_augment(struct lys_node_augment *aug, const struct lys_node *target)
{
const struct lys_node *node;
if (aug->when || target->nodetype == LYS_CHOICE) {
/* - mandatory nodes in new cases are ok;
* clarification from YANG 1.1 - augmentation can add mandatory nodes when it is
* conditional with a when statement */
return EXIT_SUCCESS;
}
if ((node = lyp_check_mandatory_((struct lys_node *)aug))) {
if (node != (struct lys_node *)aug) {
LOGVAL(target->module->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "mandatory");
LOGVAL(target->module->ctx, LYE_SPEC, LY_VLOG_NONE, NULL,
"Mandatory node \"%s\" appears in augment of \"%s\" without when condition.",
node->name, aug->target_name);
return -1;
}
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
/**
* @brief check that a mandatory node is not directly under the default case.
* @param[in] node choice with default node
* @return EXIT_SUCCESS if the constraint is fulfilled, EXIT_FAILURE otherwise
*/
int
lyp_check_mandatory_choice(struct lys_node *node)
{
const struct lys_node *mand, *dflt = ((struct lys_node_choice *)node)->dflt;
if ((mand = lyp_check_mandatory_(dflt))) {
if (mand != dflt) {
LOGVAL(node->module->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "mandatory");
LOGVAL(node->module->ctx, LYE_SPEC, LY_VLOG_NONE, NULL,
"Mandatory node \"%s\" is directly under the default case \"%s\" of the \"%s\" choice.",
mand->name, dflt->name, node->name);
return -1;
}
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
/**
* @brief Check status for invalid combination.
*
* @param[in] flags1 Flags of the referencing node.
* @param[in] mod1 Module of the referencing node,
* @param[in] name1 Schema node name of the referencing node.
* @param[in] flags2 Flags of the referenced node.
* @param[in] mod2 Module of the referenced node,
* @param[in] name2 Schema node name of the referenced node.
* @return EXIT_SUCCES on success, EXIT_FAILURE on invalid reference.
*/
int
lyp_check_status(uint16_t flags1, struct lys_module *mod1, const char *name1,
uint16_t flags2, struct lys_module *mod2, const char *name2,
const struct lys_node *node)
{
uint16_t flg1, flg2;
flg1 = (flags1 & LYS_STATUS_MASK) ? (flags1 & LYS_STATUS_MASK) : LYS_STATUS_CURR;
flg2 = (flags2 & LYS_STATUS_MASK) ? (flags2 & LYS_STATUS_MASK) : LYS_STATUS_CURR;
if ((flg1 < flg2) && (lys_main_module(mod1) == lys_main_module(mod2))) {
LOGVAL(mod1->ctx, LYE_INSTATUS, node ? LY_VLOG_LYS : LY_VLOG_NONE, node,
flg1 == LYS_STATUS_CURR ? "current" : "deprecated", name1, "references",
flg2 == LYS_STATUS_OBSLT ? "obsolete" : "deprecated", name2);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
void
lyp_del_includedup(struct lys_module *mod, int free_subs)
{
struct ly_modules_list *models = &mod->ctx->models;
uint8_t i;
assert(mod && !mod->type);
if (models->parsed_submodules_count) {
for (i = models->parsed_submodules_count - 1; models->parsed_submodules[i]->type; --i);
if (models->parsed_submodules[i] == mod) {
if (free_subs) {
for (i = models->parsed_submodules_count - 1; models->parsed_submodules[i]->type; --i) {
lys_sub_module_remove_devs_augs((struct lys_module *)models->parsed_submodules[i]);
lys_submodule_module_data_free((struct lys_submodule *)models->parsed_submodules[i]);
lys_submodule_free((struct lys_submodule *)models->parsed_submodules[i], NULL);
}
}
models->parsed_submodules_count = i;
if (!models->parsed_submodules_count) {
free(models->parsed_submodules);
models->parsed_submodules = NULL;
}
}
}
}
static void
lyp_add_includedup(struct lys_module *sub_mod, struct lys_submodule *parsed_submod)
{
struct ly_modules_list *models = &sub_mod->ctx->models;
int16_t i;
/* store main module if first include */
if (models->parsed_submodules_count) {
for (i = models->parsed_submodules_count - 1; models->parsed_submodules[i]->type; --i);
} else {
i = -1;
}
if ((i == -1) || (models->parsed_submodules[i] != lys_main_module(sub_mod))) {
++models->parsed_submodules_count;
models->parsed_submodules = ly_realloc(models->parsed_submodules,
models->parsed_submodules_count * sizeof *models->parsed_submodules);
LY_CHECK_ERR_RETURN(!models->parsed_submodules, LOGMEM(sub_mod->ctx), );
models->parsed_submodules[models->parsed_submodules_count - 1] = lys_main_module(sub_mod);
}
/* store parsed submodule */
++models->parsed_submodules_count;
models->parsed_submodules = ly_realloc(models->parsed_submodules,
models->parsed_submodules_count * sizeof *models->parsed_submodules);
LY_CHECK_ERR_RETURN(!models->parsed_submodules, LOGMEM(sub_mod->ctx), );
models->parsed_submodules[models->parsed_submodules_count - 1] = (struct lys_module *)parsed_submod;
}
/*
* types: 0 - include, 1 - import
*/
static int
lyp_check_circmod(struct lys_module *module, const char *value, int type)
{
LY_ECODE code = type ? LYE_CIRC_IMPORTS : LYE_CIRC_INCLUDES;
struct ly_modules_list *models = &module->ctx->models;
uint8_t i;
/* include/import itself */
if (ly_strequal(module->name, value, 1)) {
LOGVAL(module->ctx, code, LY_VLOG_NONE, NULL, value);
return -1;
}
/* currently parsed modules */
for (i = 0; i < models->parsing_sub_modules_count; i++) {
if (ly_strequal(models->parsing_sub_modules[i]->name, value, 1)) {
LOGVAL(module->ctx, code, LY_VLOG_NONE, NULL, value);
return -1;
}
}
return 0;
}
int
lyp_check_circmod_add(struct lys_module *module)
{
struct ly_modules_list *models = &module->ctx->models;
/* storing - enlarge the list of modules being currently parsed */
++models->parsing_sub_modules_count;
models->parsing_sub_modules = ly_realloc(models->parsing_sub_modules,
models->parsing_sub_modules_count * sizeof *models->parsing_sub_modules);
LY_CHECK_ERR_RETURN(!models->parsing_sub_modules, LOGMEM(module->ctx), -1);
models->parsing_sub_modules[models->parsing_sub_modules_count - 1] = module;
return 0;
}
void
lyp_check_circmod_pop(struct ly_ctx *ctx)
{
if (!ctx->models.parsing_sub_modules_count) {
LOGINT(ctx);
return;
}
/* update the list of currently being parsed modules */
ctx->models.parsing_sub_modules_count--;
if (!ctx->models.parsing_sub_modules_count) {
free(ctx->models.parsing_sub_modules);
ctx->models.parsing_sub_modules = NULL;
}
}
/*
* -1 - error - invalid duplicities)
* 0 - success, no duplicity
* 1 - success, valid duplicity found and stored in *sub
*/
static int
lyp_check_includedup(struct lys_module *mod, const char *name, struct lys_include *inc, struct lys_submodule **sub)
{
struct lys_module **parsed_sub = mod->ctx->models.parsed_submodules;
uint8_t i, parsed_sub_count = mod->ctx->models.parsed_submodules_count;
assert(sub);
for (i = 0; i < mod->inc_size; ++i) {
if (ly_strequal(mod->inc[i].submodule->name, name, 1)) {
/* the same module is already included in the same module - error */
LOGVAL(mod->ctx, LYE_INARG, LY_VLOG_NONE, NULL, name, "include");
LOGVAL(mod->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Submodule \"%s\" included twice in the same module \"%s\".",
name, mod->name);
return -1;
}
}
if (parsed_sub_count) {
assert(!parsed_sub[0]->type);
for (i = parsed_sub_count - 1; parsed_sub[i]->type; --i) {
if (ly_strequal(parsed_sub[i]->name, name, 1)) {
/* check revisions, including multiple revisions of a single module is error */
if (inc->rev[0] && (!parsed_sub[i]->rev_size || strcmp(parsed_sub[i]->rev[0].date, inc->rev))) {
/* the already included submodule has
* - no revision, but here we require some
* - different revision than the one required here */
LOGVAL(mod->ctx, LYE_INARG, LY_VLOG_NONE, NULL, name, "include");
LOGVAL(mod->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Including multiple revisions of submodule \"%s\".", name);
return -1;
}
/* the same module is already included in some other submodule, return it */
(*sub) = (struct lys_submodule *)parsed_sub[i];
return 1;
}
}
}
/* no duplicity found */
return 0;
}
/* returns:
* 0 - inc successfully filled
* -1 - error
*/
int
lyp_check_include(struct lys_module *module, const char *value, struct lys_include *inc, struct unres_schema *unres)
{
int i;
/* check that the submodule was not included yet */
i = lyp_check_includedup(module, value, inc, &inc->submodule);
if (i == -1) {
return -1;
} else if (i == 1) {
return 0;
}
/* submodule is not yet loaded */
/* circular include check */
if (lyp_check_circmod(module, value, 0)) {
return -1;
}
/* try to load the submodule */
inc->submodule = (struct lys_submodule *)ly_ctx_load_sub_module(module->ctx, module, value,
inc->rev[0] ? inc->rev : NULL, 1, unres);
/* check the result */
if (!inc->submodule) {
if (ly_errno != LY_EVALID) {
LOGVAL(module->ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "include");
}
LOGERR(module->ctx, LY_EVALID, "Including \"%s\" module into \"%s\" failed.", value, module->name);
return -1;
}
/* check the revision */
if (inc->rev[0] && inc->submodule->rev_size && strcmp(inc->rev, inc->submodule->rev[0].date)) {
LOGERR(module->ctx, LY_EVALID, "\"%s\" include of submodule \"%s\" in revision \"%s\" not found.",
module->name, value, inc->rev);
unres_schema_free((struct lys_module *)inc->submodule, &unres, 0);
lys_sub_module_remove_devs_augs((struct lys_module *)inc->submodule);
lys_submodule_module_data_free((struct lys_submodule *)inc->submodule);
lys_submodule_free(inc->submodule, NULL);
inc->submodule = NULL;
return -1;
}
/* store the submodule as successfully parsed */
lyp_add_includedup(module, inc->submodule);
return 0;
}
static int
lyp_check_include_missing_recursive(struct lys_module *main_module, struct lys_submodule *sub)
{
uint8_t i, j;
void *reallocated;
int ret = 0, tmp;
struct ly_ctx *ctx = main_module->ctx;
for (i = 0; i < sub->inc_size; i++) {
/* check that the include is also present in the main module */
for (j = 0; j < main_module->inc_size; j++) {
if (main_module->inc[j].submodule == sub->inc[i].submodule) {
break;
}
}
if (j == main_module->inc_size) {
/* match not found */
if (main_module->version >= LYS_VERSION_1_1) {
LOGVAL(ctx, LYE_MISSSTMT, LY_VLOG_NONE, NULL, "include");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL,
"The main module \"%s\" misses include of the \"%s\" submodule used in another submodule \"%s\".",
main_module->name, sub->inc[i].submodule->name, sub->name);
/* now we should return error, but due to the issues with freeing the module, we actually have
* to go through the all includes and, as in case of 1.0, add them into the main module and fail
* at the end when all the includes are in the main module and we can free them */
ret = 1;
} else {
/* not strictly an error in YANG 1.0 */
LOGWRN(ctx, "The main module \"%s\" misses include of the \"%s\" submodule used in another submodule \"%s\".",
main_module->name, sub->inc[i].submodule->name, sub->name);
LOGWRN(ctx, "To avoid further issues, adding submodule \"%s\" into the main module \"%s\".",
sub->inc[i].submodule->name, main_module->name);
/* but since it is a good practise and because we expect all the includes in the main module
* when searching it and also when freeing the module, put it into it */
}
main_module->inc_size++;
reallocated = realloc(main_module->inc, main_module->inc_size * sizeof *main_module->inc);
LY_CHECK_ERR_RETURN(!reallocated, LOGMEM(ctx), 1);
main_module->inc = reallocated;
memset(&main_module->inc[main_module->inc_size - 1], 0, sizeof *main_module->inc);
/* to avoid unexpected consequences, copy just a link to the submodule and the revision,
* all other substatements of the include are ignored */
memcpy(&main_module->inc[main_module->inc_size - 1].rev, sub->inc[i].rev, LY_REV_SIZE - 1);
main_module->inc[main_module->inc_size - 1].submodule = sub->inc[i].submodule;
}
/* recursion */
tmp = lyp_check_include_missing_recursive(main_module, sub->inc[i].submodule);
if (!ret && tmp) {
ret = 1;
}
}
return ret;
}
int
lyp_check_include_missing(struct lys_module *main_module)
{
int ret = 0;
uint8_t i;
/* in YANG 1.1, all the submodules must be in the main module, check it even for
* 1.0 where it will be printed as warning and the include will be added into the main module */
for (i = 0; i < main_module->inc_size; i++) {
if (lyp_check_include_missing_recursive(main_module, main_module->inc[i].submodule)) {
ret = 1;
}
}
return ret;
}
/* returns:
* 0 - imp successfully filled
* -1 - error, imp not cleaned
*/
int
lyp_check_import(struct lys_module *module, const char *value, struct lys_import *imp)
{
int i;
struct lys_module *dup = NULL;
struct ly_ctx *ctx = module->ctx;
/* check for importing a single module in multiple revisions */
for (i = 0; i < module->imp_size; i++) {
if (!module->imp[i].module) {
/* skip the not yet filled records */
continue;
}
if (ly_strequal(module->imp[i].module->name, value, 1)) {
/* check revisions, including multiple revisions of a single module is error */
if (imp->rev[0] && (!module->imp[i].module->rev_size || strcmp(module->imp[i].module->rev[0].date, imp->rev))) {
/* the already imported module has
* - no revision, but here we require some
* - different revision than the one required here */
LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "import");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Importing multiple revisions of module \"%s\".", value);
return -1;
} else if (!imp->rev[0]) {
/* no revision, remember the duplication, but check revisions after loading the module
* because the current revision can be the same (then it is ok) or it can differ (then it
* is error */
dup = module->imp[i].module;
break;
}
/* there is duplication, but since prefixes differs (checked in caller of this function),
* it is ok */
imp->module = module->imp[i].module;
return 0;
}
}
/* circular import check */
if (lyp_check_circmod(module, value, 1)) {
return -1;
}
/* load module - in specific situations it tries to get the module from the context */
imp->module = (struct lys_module *)ly_ctx_load_sub_module(module->ctx, NULL, value, imp->rev[0] ? imp->rev : NULL,
module->ctx->models.flags & LY_CTX_ALLIMPLEMENTED ? 1 : 0,
NULL);
/* check the result */
if (!imp->module) {
LOGERR(ctx, LY_EVALID, "Importing \"%s\" module into \"%s\" failed.", value, module->name);
return -1;
}
if (imp->rev[0] && imp->module->rev_size && strcmp(imp->rev, imp->module->rev[0].date)) {
LOGERR(ctx, LY_EVALID, "\"%s\" import of module \"%s\" in revision \"%s\" not found.",
module->name, value, imp->rev);
return -1;
}
if (dup) {
/* check the revisions */
if ((dup != imp->module) ||
(dup->rev_size != imp->module->rev_size && (!dup->rev_size || imp->module->rev_size)) ||
(dup->rev_size && strcmp(dup->rev[0].date, imp->module->rev[0].date))) {
/* - modules are not the same
* - one of modules has no revision (except they both has no revision)
* - revisions of the modules are not the same */
LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "import");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Importing multiple revisions of module \"%s\".", value);
return -1;
} else {
LOGWRN(ctx, "Module \"%s\" is imported by \"%s\" multiple times with different prefixes.", dup->name, module->name);
}
}
return 0;
}
/*
* put the newest revision to the first position
*/
void
lyp_sort_revisions(struct lys_module *module)
{
uint8_t i, r;
struct lys_revision rev;
for (i = 1, r = 0; i < module->rev_size; i++) {
if (strcmp(module->rev[i].date, module->rev[r].date) > 0) {
r = i;
}
}
if (r) {
/* the newest revision is not on position 0, switch them */
memcpy(&rev, &module->rev[0], sizeof rev);
memcpy(&module->rev[0], &module->rev[r], sizeof rev);
memcpy(&module->rev[r], &rev, sizeof rev);
}
}
void
lyp_ext_instance_rm(struct ly_ctx *ctx, struct lys_ext_instance ***ext, uint8_t *size, uint8_t index)
{
uint8_t i;
lys_extension_instances_free(ctx, (*ext)[index]->ext, (*ext)[index]->ext_size, NULL);
lydict_remove(ctx, (*ext)[index]->arg_value);
free((*ext)[index]);
/* move the rest of the array */
for (i = index + 1; i < (*size); i++) {
(*ext)[i - 1] = (*ext)[i];
}
/* clean the last cell in the array structure */
(*ext)[(*size) - 1] = NULL;
/* the array is not reallocated here, just change its size */
(*size) = (*size) - 1;
if (!(*size)) {
/* ext array is empty */
free((*ext));
ext = NULL;
}
}
static int
lyp_rfn_apply_ext_(struct lys_refine *rfn, struct lys_node *target, LYEXT_SUBSTMT substmt, struct lys_ext *extdef)
{
struct ly_ctx *ctx;
int m, n;
struct lys_ext_instance *new;
void *reallocated;
ctx = target->module->ctx; /* shortcut */
m = n = -1;
while ((m = lys_ext_iter(rfn->ext, rfn->ext_size, m + 1, substmt)) != -1) {
/* refine's substatement includes extensions, copy them to the target, replacing the previous
* substatement's extensions if any. In case of refining the extension itself, we are going to
* replace only the same extension (pointing to the same definition) */
if (substmt == LYEXT_SUBSTMT_SELF && rfn->ext[m]->def != extdef) {
continue;
}
/* get the index of the extension to replace in the target node */
do {
n = lys_ext_iter(target->ext, target->ext_size, n + 1, substmt);
} while (n != -1 && substmt == LYEXT_SUBSTMT_SELF && target->ext[n]->def != extdef);
/* TODO cover complex extension instances */
if (n == -1) {
/* nothing to replace, we are going to add it - reallocate */
new = malloc(sizeof **target->ext);
LY_CHECK_ERR_RETURN(!new, LOGMEM(ctx), EXIT_FAILURE);
reallocated = realloc(target->ext, (target->ext_size + 1) * sizeof *target->ext);
LY_CHECK_ERR_RETURN(!reallocated, LOGMEM(ctx); free(new), EXIT_FAILURE);
target->ext = reallocated;
target->ext_size++;
/* init */
n = target->ext_size - 1;
target->ext[n] = new;
target->ext[n]->parent = target;
target->ext[n]->parent_type = LYEXT_PAR_NODE;
target->ext[n]->flags = 0;
target->ext[n]->insubstmt = substmt;
target->ext[n]->priv = NULL;
target->ext[n]->nodetype = LYS_EXT;
target->ext[n]->module = target->module;
} else {
/* replacing - first remove the allocated data from target */
lys_extension_instances_free(ctx, target->ext[n]->ext, target->ext[n]->ext_size, NULL);
lydict_remove(ctx, target->ext[n]->arg_value);
}
/* common part for adding and replacing */
target->ext[n]->def = rfn->ext[m]->def;
/* parent and parent_type do not change */
target->ext[n]->arg_value = lydict_insert(ctx, rfn->ext[m]->arg_value, 0);
/* flags do not change */
target->ext[n]->ext_size = rfn->ext[m]->ext_size;
lys_ext_dup(ctx, target->module, rfn->ext[m]->ext, rfn->ext[m]->ext_size, target, LYEXT_PAR_NODE,
&target->ext[n]->ext, 0, NULL);
/* substmt does not change, but the index must be taken from the refine */
target->ext[n]->insubstmt_index = rfn->ext[m]->insubstmt_index;
}
/* remove the rest of extensions belonging to the original substatement in the target node */
while ((n = lys_ext_iter(target->ext, target->ext_size, n + 1, substmt)) != -1) {
if (substmt == LYEXT_SUBSTMT_SELF && target->ext[n]->def != extdef) {
/* keep this extension */
continue;
}
/* remove the item */
lyp_ext_instance_rm(ctx, &target->ext, &target->ext_size, n);
--n;
}
return EXIT_SUCCESS;
}
/*
* apply extension instances defined under refine's substatements.
* It cannot be done immediately when applying the refine because there can be
* still unresolved data (e.g. type) and mainly the targeted extension instances.
*/
int
lyp_rfn_apply_ext(struct lys_module *module)
{
int i, k, a = 0;
struct lys_node *root, *nextroot, *next, *node;
struct lys_node *target;
struct lys_node_uses *uses;
struct lys_refine *rfn;
struct ly_set *extset;
/* refines in uses */
LY_TREE_FOR_SAFE(module->data, nextroot, root) {
/* go through the data tree of the module and all the defined augments */
LY_TREE_DFS_BEGIN(root, next, node) {
if (node->nodetype == LYS_USES) {
uses = (struct lys_node_uses *)node;
for (i = 0; i < uses->refine_size; i++) {
if (!uses->refine[i].ext_size) {
/* no extensions in refine */
continue;
}
rfn = &uses->refine[i]; /* shortcut */
/* get the target node */
target = NULL;
resolve_descendant_schema_nodeid(rfn->target_name, uses->child,
LYS_NO_RPC_NOTIF_NODE | LYS_ACTION | LYS_NOTIF,
0, (const struct lys_node **)&target);
if (!target) {
/* it should always succeed since the target_name was already resolved at least
* once when the refine itself was being resolved */
LOGINT(module->ctx);;
return EXIT_FAILURE;
}
/* extensions */
extset = ly_set_new();
k = -1;
while ((k = lys_ext_iter(rfn->ext, rfn->ext_size, k + 1, LYEXT_SUBSTMT_SELF)) != -1) {
ly_set_add(extset, rfn->ext[k]->def, 0);
}
for (k = 0; (unsigned int)k < extset->number; k++) {
if (lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_SELF, (struct lys_ext *)extset->set.g[k])) {
ly_set_free(extset);
return EXIT_FAILURE;
}
}
ly_set_free(extset);
/* description */
if (rfn->dsc && lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_DESCRIPTION, NULL)) {
return EXIT_FAILURE;
}
/* reference */
if (rfn->ref && lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_REFERENCE, NULL)) {
return EXIT_FAILURE;
}
/* config, in case of notification or rpc/action{notif, the config is not applicable
* (there is no config status) */
if ((rfn->flags & LYS_CONFIG_MASK) && (target->flags & LYS_CONFIG_MASK)) {
if (lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_CONFIG, NULL)) {
return EXIT_FAILURE;
}
}
/* default value */
if (rfn->dflt_size && lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_DEFAULT, NULL)) {
return EXIT_FAILURE;
}
/* mandatory */
if (rfn->flags & LYS_MAND_MASK) {
if (lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_MANDATORY, NULL)) {
return EXIT_FAILURE;
}
}
/* presence */
if ((target->nodetype & LYS_CONTAINER) && rfn->mod.presence) {
if (lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_PRESENCE, NULL)) {
return EXIT_FAILURE;
}
}
/* min/max */
if (rfn->flags & LYS_RFN_MINSET) {
if (lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_MIN, NULL)) {
return EXIT_FAILURE;
}
}
if (rfn->flags & LYS_RFN_MAXSET) {
if (lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_MAX, NULL)) {
return EXIT_FAILURE;
}
}
/* must and if-feature contain extensions on their own, not needed to be solved here */
if (target->ext_size) {
/* the allocated target's extension array can be now longer than needed in case
* there is less refine substatement's extensions than in original. Since we are
* going to reduce or keep the same memory, it is not necessary to test realloc's result */
target->ext = realloc(target->ext, target->ext_size * sizeof *target->ext);
}
}
}
LY_TREE_DFS_END(root, next, node)
}
if (!nextroot && a < module->augment_size) {
nextroot = module->augment[a].child;
a++;
}
}
return EXIT_SUCCESS;
}
/*
* check mandatory substatements defined under extension instances.
*/
int
lyp_mand_check_ext(struct lys_ext_instance_complex *ext, const char *ext_name)
{
void *p;
int i;
struct ly_ctx *ctx = ext->module->ctx;
/* check for mandatory substatements */
for (i = 0; ext->substmt[i].stmt; i++) {
if (ext->substmt[i].cardinality == LY_STMT_CARD_OPT || ext->substmt[i].cardinality == LY_STMT_CARD_ANY) {
/* not a mandatory */
continue;
} else if (ext->substmt[i].cardinality == LY_STMT_CARD_SOME) {
goto array;
}
/*
* LY_STMT_ORDEREDBY - not checked, has a default value which is the same as explicit system order
* LY_STMT_MODIFIER, LY_STMT_STATUS, LY_STMT_MANDATORY, LY_STMT_CONFIG - checked, but mandatory requirement
* does not make sense since there is also a default value specified
*/
switch(ext->substmt[i].stmt) {
case LY_STMT_ORDEREDBY:
/* always ok */
break;
case LY_STMT_REQINSTANCE:
case LY_STMT_DIGITS:
case LY_STMT_MODIFIER:
p = lys_ext_complex_get_substmt(ext->substmt[i].stmt, ext, NULL);
if (!*(uint8_t*)p) {
LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, ly_stmt_str[ext->substmt[i].stmt], ext_name);
goto error;
}
break;
case LY_STMT_STATUS:
p = lys_ext_complex_get_substmt(ext->substmt[i].stmt, ext, NULL);
if (!(*(uint16_t*)p & LYS_STATUS_MASK)) {
LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, ly_stmt_str[ext->substmt[i].stmt], ext_name);
goto error;
}
break;
case LY_STMT_MANDATORY:
p = lys_ext_complex_get_substmt(ext->substmt[i].stmt, ext, NULL);
if (!(*(uint16_t*)p & LYS_MAND_MASK)) {
LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, ly_stmt_str[ext->substmt[i].stmt], ext_name);
goto error;
}
break;
case LY_STMT_CONFIG:
p = lys_ext_complex_get_substmt(ext->substmt[i].stmt, ext, NULL);
if (!(*(uint16_t*)p & LYS_CONFIG_MASK)) {
LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, ly_stmt_str[ext->substmt[i].stmt], ext_name);
goto error;
}
break;
default:
array:
/* stored as a pointer */
p = lys_ext_complex_get_substmt(ext->substmt[i].stmt, ext, NULL);
if (!(*(void**)p)) {
LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, ly_stmt_str[ext->substmt[i].stmt], ext_name);
goto error;
}
break;
}
}
return EXIT_SUCCESS;
error:
return EXIT_FAILURE;
}
static int
lyp_deviate_del_ext(struct lys_node *target, struct lys_ext_instance *ext)
{
int n = -1, found = 0;
char *path;
while ((n = lys_ext_iter(target->ext, target->ext_size, n + 1, ext->insubstmt)) != -1) {
if (target->ext[n]->def != ext->def) {
continue;
}
if (ext->def->argument) {
/* check matching arguments */
if (!ly_strequal(target->ext[n]->arg_value, ext->arg_value, 1)) {
continue;
}
}
/* we have the matching extension - remove it */
++found;
lyp_ext_instance_rm(target->module->ctx, &target->ext, &target->ext_size, n);
--n;
}
if (!found) {
path = lys_path(target, LYS_PATH_FIRST_PREFIX);
LOGERR(target->module->ctx, LY_EVALID, "Extension deviation: extension \"%s\" to delete not found in \"%s\".",
ext->def->name, path)
free(path);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
static int
lyp_deviate_apply_ext(struct lys_deviate *dev, struct lys_node *target, LYEXT_SUBSTMT substmt, struct lys_ext *extdef)
{
struct ly_ctx *ctx;
int m, n;
struct lys_ext_instance *new;
void *reallocated;
/* LY_DEVIATE_ADD and LY_DEVIATE_RPL are very similar so they are implement the same way - in replacing,
* there can be some extension instances in the target, in case of adding, there should not be any so we
* will be just adding. */
ctx = target->module->ctx; /* shortcut */
m = n = -1;
while ((m = lys_ext_iter(dev->ext, dev->ext_size, m + 1, substmt)) != -1) {
/* deviate and its substatements include extensions, copy them to the target, replacing the previous
* extensions if any. In case of deviating extension itself, we have to deviate only the same type
* of the extension as specified in the deviation */
if (substmt == LYEXT_SUBSTMT_SELF && dev->ext[m]->def != extdef) {
continue;
}
if (substmt == LYEXT_SUBSTMT_SELF && dev->mod == LY_DEVIATE_ADD) {
/* in case of adding extension, we will be replacing only the inherited extensions */
do {
n = lys_ext_iter(target->ext, target->ext_size, n + 1, substmt);
} while (n != -1 && (target->ext[n]->def != extdef || !(target->ext[n]->flags & LYEXT_OPT_INHERIT)));
} else {
/* get the index of the extension to replace in the target node */
do {
n = lys_ext_iter(target->ext, target->ext_size, n + 1, substmt);
/* if we are applying extension deviation, we have to deviate only the same type of the extension */
} while (n != -1 && substmt == LYEXT_SUBSTMT_SELF && target->ext[n]->def != extdef);
}
if (n == -1) {
/* nothing to replace, we are going to add it - reallocate */
new = malloc(sizeof **target->ext);
LY_CHECK_ERR_RETURN(!new, LOGMEM(ctx), EXIT_FAILURE);
reallocated = realloc(target->ext, (target->ext_size + 1) * sizeof *target->ext);
LY_CHECK_ERR_RETURN(!reallocated, LOGMEM(ctx); free(new), EXIT_FAILURE);
target->ext = reallocated;
target->ext_size++;
n = target->ext_size - 1;
} else {
/* replacing - the original set of extensions is actually backuped together with the
* node itself, so we are supposed only to free the allocated data here ... */
lys_extension_instances_free(ctx, target->ext[n]->ext, target->ext[n]->ext_size, NULL);
lydict_remove(ctx, target->ext[n]->arg_value);
free(target->ext[n]);
/* and prepare the new structure */
new = malloc(sizeof **target->ext);
LY_CHECK_ERR_RETURN(!new, LOGMEM(ctx), EXIT_FAILURE);
}
/* common part for adding and replacing - fill the newly created / replaced cell */
target->ext[n] = new;
target->ext[n]->def = dev->ext[m]->def;
target->ext[n]->arg_value = lydict_insert(ctx, dev->ext[m]->arg_value, 0);
target->ext[n]->flags = 0;
target->ext[n]->parent = target;
target->ext[n]->parent_type = LYEXT_PAR_NODE;
target->ext[n]->insubstmt = substmt;
target->ext[n]->insubstmt_index = dev->ext[m]->insubstmt_index;
target->ext[n]->ext_size = dev->ext[m]->ext_size;
lys_ext_dup(ctx, target->module, dev->ext[m]->ext, dev->ext[m]->ext_size, target, LYEXT_PAR_NODE,
&target->ext[n]->ext, 1, NULL);
target->ext[n]->nodetype = LYS_EXT;
target->ext[n]->module = target->module;
target->ext[n]->priv = NULL;
/* TODO cover complex extension instances */
}
/* remove the rest of extensions belonging to the original substatement in the target node,
* due to possible reverting of the deviation effect, they are actually not removed, just moved
* to the backup of the original node when the original node is backuped, here we just have to
* free the replaced / deleted originals */
while ((n = lys_ext_iter(target->ext, target->ext_size, n + 1, substmt)) != -1) {
if (substmt == LYEXT_SUBSTMT_SELF) {
/* if we are applying extension deviation, we are going to remove only
* - the same type of the extension in case of replacing
* - the same type of the extension which was inherited in case of adding
* note - delete deviation is covered in lyp_deviate_del_ext */
if (target->ext[n]->def != extdef ||
(dev->mod == LY_DEVIATE_ADD && !(target->ext[n]->flags & LYEXT_OPT_INHERIT))) {
/* keep this extension */
continue;
}
}
/* remove the item */
lyp_ext_instance_rm(ctx, &target->ext, &target->ext_size, n);
--n;
}
return EXIT_SUCCESS;
}
/*
* not-supported deviations are not processed since they affect the complete node, not just their substatements
*/
int
lyp_deviation_apply_ext(struct lys_module *module)
{
int i, j, k;
struct lys_deviate *dev;
struct lys_node *target;
struct ly_set *extset;
for (i = 0; i < module->deviation_size; i++) {
target = NULL;
extset = NULL;
j = resolve_schema_nodeid(module->deviation[i].target_name, NULL, module, &extset, 0, 0);
if (j == -1) {
return EXIT_FAILURE;
} else if (!extset) {
/* LY_DEVIATE_NO */
ly_set_free(extset);
continue;
}
target = extset->set.s[0];
ly_set_free(extset);
for (j = 0; j < module->deviation[i].deviate_size; j++) {
dev = &module->deviation[i].deviate[j];
if (!dev->ext_size) {
/* no extensions in deviate and its substatement, nothing to do here */
continue;
}
/* extensions */
if (dev->mod == LY_DEVIATE_DEL) {
k = -1;
while ((k = lys_ext_iter(dev->ext, dev->ext_size, k + 1, LYEXT_SUBSTMT_SELF)) != -1) {
if (lyp_deviate_del_ext(target, dev->ext[k])) {
return EXIT_FAILURE;
}
}
/* In case of LY_DEVIATE_DEL, we are applying only extension deviation, removing
* of the substatement's extensions was already done when the substatement was applied.
* Extension deviation could not be applied by the parser since the extension could be unresolved,
* which is not the issue of the other substatements. */
continue;
} else {
extset = ly_set_new();
k = -1;
while ((k = lys_ext_iter(dev->ext, dev->ext_size, k + 1, LYEXT_SUBSTMT_SELF)) != -1) {
ly_set_add(extset, dev->ext[k]->def, 0);
}
for (k = 0; (unsigned int)k < extset->number; k++) {
if (lyp_deviate_apply_ext(dev, target, LYEXT_SUBSTMT_SELF, (struct lys_ext *)extset->set.g[k])) {
ly_set_free(extset);
return EXIT_FAILURE;
}
}
ly_set_free(extset);
}
/* unique */
if (dev->unique_size && lyp_deviate_apply_ext(dev, target, LYEXT_SUBSTMT_UNIQUE, NULL)) {
return EXIT_FAILURE;
}
/* units */
if (dev->units && lyp_deviate_apply_ext(dev, target, LYEXT_SUBSTMT_UNITS, NULL)) {
return EXIT_FAILURE;
}
/* default */
if (dev->dflt_size && lyp_deviate_apply_ext(dev, target, LYEXT_SUBSTMT_DEFAULT, NULL)) {
return EXIT_FAILURE;
}
/* config */
if ((dev->flags & LYS_CONFIG_MASK) && lyp_deviate_apply_ext(dev, target, LYEXT_SUBSTMT_CONFIG, NULL)) {
return EXIT_FAILURE;
}
/* mandatory */
if ((dev->flags & LYS_MAND_MASK) && lyp_deviate_apply_ext(dev, target, LYEXT_SUBSTMT_MANDATORY, NULL)) {
return EXIT_FAILURE;
}
/* min/max */
if (dev->min_set && lyp_deviate_apply_ext(dev, target, LYEXT_SUBSTMT_MIN, NULL)) {
return EXIT_FAILURE;
}
if (dev->min_set && lyp_deviate_apply_ext(dev, target, LYEXT_SUBSTMT_MAX, NULL)) {
return EXIT_FAILURE;
}
/* type and must contain extension instances in their structures */
}
}
return EXIT_SUCCESS;
}
int
lyp_ctx_check_module(struct lys_module *module)
{
struct ly_ctx *ctx;
int i, match_i = -1, to_implement;
const char *last_rev = NULL;
assert(module);
to_implement = 0;
ctx = module->ctx;
/* find latest revision */
for (i = 0; i < module->rev_size; ++i) {
if (!last_rev || (strcmp(last_rev, module->rev[i].date) < 0)) {
last_rev = module->rev[i].date;
}
}
for (i = 0; i < ctx->models.used; i++) {
/* check name (name/revision) and namespace uniqueness */
if (!strcmp(ctx->models.list[i]->name, module->name)) {
if (to_implement) {
if (i == match_i) {
continue;
}
LOGERR(ctx, LY_EINVAL, "Module \"%s@%s\" in another revision \"%s\" already implemented.",
module->name, last_rev ? last_rev : "<latest>", ctx->models.list[i]->rev[0].date);
return -1;
} else if (!ctx->models.list[i]->rev_size && module->rev_size) {
LOGERR(ctx, LY_EINVAL, "Module \"%s\" without revision already in context.", module->name);
return -1;
} else if (ctx->models.list[i]->rev_size && !module->rev_size) {
LOGERR(ctx, LY_EINVAL, "Module \"%s\" with revision \"%s\" already in context.",
module->name, ctx->models.list[i]->rev[0].date);
return -1;
} else if ((!module->rev_size && !ctx->models.list[i]->rev_size)
|| !strcmp(ctx->models.list[i]->rev[0].date, last_rev)) {
LOGVRB("Module \"%s@%s\" already in context.", module->name, last_rev ? last_rev : "<latest>");
/* if disabled, enable first */
if (ctx->models.list[i]->disabled) {
lys_set_enabled(ctx->models.list[i]);
}
to_implement = module->implemented;
match_i = i;
if (to_implement && !ctx->models.list[i]->implemented) {
/* check first that it is okay to change it to implemented */
i = -1;
continue;
}
return 1;
} else if (module->implemented && ctx->models.list[i]->implemented) {
LOGERR(ctx, LY_EINVAL, "Module \"%s@%s\" in another revision \"%s\" already implemented.",
module->name, last_rev ? last_rev : "<latest>", ctx->models.list[i]->rev[0].date);
return -1;
}
/* else keep searching, for now the caller is just adding
* another revision of an already present schema
*/
} else if (!strcmp(ctx->models.list[i]->ns, module->ns)) {
LOGERR(ctx, LY_EINVAL, "Two different modules (\"%s\" and \"%s\") have the same namespace \"%s\".",
ctx->models.list[i]->name, module->name, module->ns);
return -1;
}
}
if (to_implement) {
if (lys_set_implemented(ctx->models.list[match_i])) {
return -1;
}
return 1;
}
return 0;
}
int
lyp_ctx_add_module(struct lys_module *module)
{
struct lys_module **newlist = NULL;
int i;
assert(!lyp_ctx_check_module(module));
#ifndef NDEBUG
int j;
/* check that all augments are resolved */
for (i = 0; i < module->augment_size; ++i) {
assert(module->augment[i].target);
}
for (i = 0; i < module->inc_size; ++i) {
for (j = 0; j < module->inc[i].submodule->augment_size; ++j) {
assert(module->inc[i].submodule->augment[j].target);
}
}
#endif
/* add to the context's list of modules */
if (module->ctx->models.used == module->ctx->models.size) {
newlist = realloc(module->ctx->models.list, (2 * module->ctx->models.size) * sizeof *newlist);
LY_CHECK_ERR_RETURN(!newlist, LOGMEM(module->ctx), -1);
for (i = module->ctx->models.size; i < module->ctx->models.size * 2; i++) {
newlist[i] = NULL;
}
module->ctx->models.size *= 2;
module->ctx->models.list = newlist;
}
module->ctx->models.list[module->ctx->models.used++] = module;
module->ctx->models.module_set_id++;
return 0;
}
/**
* Store UTF-8 character specified as 4byte integer into the dst buffer.
* Returns number of written bytes (4 max), expects that dst has enough space.
*
* UTF-8 mapping:
* 00000000 -- 0000007F: 0xxxxxxx
* 00000080 -- 000007FF: 110xxxxx 10xxxxxx
* 00000800 -- 0000FFFF: 1110xxxx 10xxxxxx 10xxxxxx
* 00010000 -- 001FFFFF: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
*
* Includes checking for valid characters (following RFC 7950, sec 9.4)
*/
unsigned int
pututf8(struct ly_ctx *ctx, char *dst, int32_t value)
{
if (value < 0x80) {
/* one byte character */
if (value < 0x20 &&
value != 0x09 &&
value != 0x0a &&
value != 0x0d) {
goto error;
}
dst[0] = value;
return 1;
} else if (value < 0x800) {
/* two bytes character */
dst[0] = 0xc0 | (value >> 6);
dst[1] = 0x80 | (value & 0x3f);
return 2;
} else if (value < 0xfffe) {
/* three bytes character */
if (((value & 0xf800) == 0xd800) ||
(value >= 0xfdd0 && value <= 0xfdef)) {
/* exclude surrogate blocks %xD800-DFFF */
/* exclude noncharacters %xFDD0-FDEF */
goto error;
}
dst[0] = 0xe0 | (value >> 12);
dst[1] = 0x80 | ((value >> 6) & 0x3f);
dst[2] = 0x80 | (value & 0x3f);
return 3;
} else if (value < 0x10fffe) {
if ((value & 0xffe) == 0xffe) {
/* exclude noncharacters %xFFFE-FFFF, %x1FFFE-1FFFF, %x2FFFE-2FFFF, %x3FFFE-3FFFF, %x4FFFE-4FFFF,
* %x5FFFE-5FFFF, %x6FFFE-6FFFF, %x7FFFE-7FFFF, %x8FFFE-8FFFF, %x9FFFE-9FFFF, %xAFFFE-AFFFF,
* %xBFFFE-BFFFF, %xCFFFE-CFFFF, %xDFFFE-DFFFF, %xEFFFE-EFFFF, %xFFFFE-FFFFF, %x10FFFE-10FFFF */
goto error;
}
/* four bytes character */
dst[0] = 0xf0 | (value >> 18);
dst[1] = 0x80 | ((value >> 12) & 0x3f);
dst[2] = 0x80 | ((value >> 6) & 0x3f);
dst[3] = 0x80 | (value & 0x3f);
return 4;
}
error:
/* out of range */
LOGVAL(ctx, LYE_XML_INCHAR, LY_VLOG_NONE, NULL, NULL);
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid UTF-8 value 0x%08x", value);
return 0;
}
unsigned int
copyutf8(struct ly_ctx *ctx, char *dst, const char *src)
{
uint32_t value;
/* unicode characters */
if (!(src[0] & 0x80)) {
/* one byte character */
if (src[0] < 0x20 &&
src[0] != 0x09 &&
src[0] != 0x0a &&
src[0] != 0x0d) {
LOGVAL(ctx, LYE_XML_INCHAR, LY_VLOG_NONE, NULL, src);
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid UTF-8 value 0x%02x", src[0]);
return 0;
}
dst[0] = src[0];
return 1;
} else if (!(src[0] & 0x20)) {
/* two bytes character */
dst[0] = src[0];
dst[1] = src[1];
return 2;
} else if (!(src[0] & 0x10)) {
/* three bytes character */
value = ((uint32_t)(src[0] & 0xf) << 12) | ((uint32_t)(src[1] & 0x3f) << 6) | (src[2] & 0x3f);
if (((value & 0xf800) == 0xd800) ||
(value >= 0xfdd0 && value <= 0xfdef) ||
(value & 0xffe) == 0xffe) {
/* exclude surrogate blocks %xD800-DFFF */
/* exclude noncharacters %xFDD0-FDEF */
/* exclude noncharacters %xFFFE-FFFF */
LOGVAL(ctx, LYE_XML_INCHAR, LY_VLOG_NONE, NULL, src);
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid UTF-8 value 0x%08x", value);
return 0;
}
dst[0] = src[0];
dst[1] = src[1];
dst[2] = src[2];
return 3;
} else if (!(src[0] & 0x08)) {
/* four bytes character */
value = ((uint32_t)(src[0] & 0x7) << 18) | ((uint32_t)(src[1] & 0x3f) << 12) | ((uint32_t)(src[2] & 0x3f) << 6) | (src[3] & 0x3f);
if ((value & 0xffe) == 0xffe) {
/* exclude noncharacters %x1FFFE-1FFFF, %x2FFFE-2FFFF, %x3FFFE-3FFFF, %x4FFFE-4FFFF,
* %x5FFFE-5FFFF, %x6FFFE-6FFFF, %x7FFFE-7FFFF, %x8FFFE-8FFFF, %x9FFFE-9FFFF, %xAFFFE-AFFFF,
* %xBFFFE-BFFFF, %xCFFFE-CFFFF, %xDFFFE-DFFFF, %xEFFFE-EFFFF, %xFFFFE-FFFFF, %x10FFFE-10FFFF */
LOGVAL(ctx, LYE_XML_INCHAR, LY_VLOG_NONE, NULL, src);
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid UTF-8 value 0x%08x", value);
return 0;
}
dst[0] = src[0];
dst[1] = src[1];
dst[2] = src[2];
dst[3] = src[3];
return 4;
} else {
LOGVAL(ctx, LYE_XML_INCHAR, LY_VLOG_NONE, NULL, src);
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid UTF-8 leading byte 0x%02x", src[0]);
return 0;
}
}
const struct lys_module *
lyp_get_module(const struct lys_module *module, const char *prefix, int pref_len, const char *name, int name_len, int in_data)
{
const struct lys_module *main_module;
char *str;
int i;
assert(!prefix || !name);
if (prefix && !pref_len) {
pref_len = strlen(prefix);
}
if (name && !name_len) {
name_len = strlen(name);
}
main_module = lys_main_module(module);
/* module own prefix, submodule own prefix, (sub)module own name */
if ((!prefix || (!module->type && !strncmp(main_module->prefix, prefix, pref_len) && !main_module->prefix[pref_len])
|| (module->type && !strncmp(module->prefix, prefix, pref_len) && !module->prefix[pref_len]))
&& (!name || (!strncmp(main_module->name, name, name_len) && !main_module->name[name_len]))) {
return main_module;
}
/* standard import */
for (i = 0; i < module->imp_size; ++i) {
if ((!prefix || (!strncmp(module->imp[i].prefix, prefix, pref_len) && !module->imp[i].prefix[pref_len]))
&& (!name || (!strncmp(module->imp[i].module->name, name, name_len) && !module->imp[i].module->name[name_len]))) {
return module->imp[i].module;
}
}
/* module required by a foreign grouping, deviation, or submodule */
if (name) {
str = strndup(name, name_len);
if (!str) {
LOGMEM(module->ctx);
return NULL;
}
main_module = ly_ctx_get_module(module->ctx, str, NULL, 0);
/* try data callback */
if (!main_module && in_data && module->ctx->data_clb) {
main_module = module->ctx->data_clb(module->ctx, str, NULL, 0, module->ctx->data_clb_data);
}
free(str);
return main_module;
}
return NULL;
}
const struct lys_module *
lyp_get_import_module_ns(const struct lys_module *module, const char *ns)
{
int i;
const struct lys_module *mod = NULL;
assert(module && ns);
if (module->type) {
/* the module is actually submodule and to get the namespace, we need the main module */
if (ly_strequal(((struct lys_submodule *)module)->belongsto->ns, ns, 0)) {
return ((struct lys_submodule *)module)->belongsto;
}
} else {
/* module's own namespace */
if (ly_strequal(module->ns, ns, 0)) {
return module;
}
}
/* imported modules */
for (i = 0; i < module->imp_size; ++i) {
if (ly_strequal(module->imp[i].module->ns, ns, 0)) {
return module->imp[i].module;
}
}
return mod;
}
const char *
lyp_get_yang_data_template_name(const struct lyd_node *node)
{
struct lys_node *snode;
snode = lys_parent(node->schema);
while (snode && snode->nodetype & (LYS_USES | LYS_CASE | LYS_CHOICE)) {
snode = lys_parent(snode);
}
if (snode && snode->nodetype == LYS_EXT && strcmp(((struct lys_ext_instance_complex *)snode)->def->name, "yang-data") == 0) {
return ((struct lys_ext_instance_complex *)snode)->arg_value;
} else {
return NULL;
}
}
const struct lys_node *
lyp_get_yang_data_template(const struct lys_module *module, const char *yang_data_name, int yang_data_name_len)
{
int i, j;
const struct lys_node *ret = NULL;
const struct lys_submodule *submodule;
for(i = 0; i < module->ext_size; ++i) {
if (!strcmp(module->ext[i]->def->name, "yang-data") && !strncmp(module->ext[i]->arg_value, yang_data_name, yang_data_name_len)
&& !module->ext[i]->arg_value[yang_data_name_len]) {
ret = (struct lys_node *)module->ext[i];
break;
}
}
for(j = 0; !ret && j < module->inc_size; ++j) {
submodule = module->inc[j].submodule;
for(i = 0; i < submodule->ext_size; ++i) {
if (!strcmp(submodule->ext[i]->def->name, "yang-data") && !strncmp(submodule->ext[i]->arg_value, yang_data_name, yang_data_name_len)
&& !submodule->ext[i]->arg_value[yang_data_name_len]) {
ret = (struct lys_node *)submodule->ext[i];
break;
}
}
}
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_1287_0 |
crossvul-cpp_data_good_4318_0 | /**********************************************************************
regcomp.c - Oniguruma (regular expression library)
**********************************************************************/
/*-
* Copyright (c) 2002-2020 K.Kosako
* 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 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 AUTHOR 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 "regparse.h"
#define OPS_INIT_SIZE 8
typedef struct {
OnigLen min;
OnigLen max;
} MinMaxLen;
typedef struct {
OnigLen min;
OnigLen max;
int min_is_sure;
} MinMaxCharLen;
OnigCaseFoldType OnigDefaultCaseFoldFlag = ONIGENC_CASE_FOLD_MIN;
static OnigLen node_min_byte_len(Node* node, ScanEnv* env);
#if 0
typedef struct {
int n;
int alloc;
int* v;
} int_stack;
static int
make_int_stack(int_stack** rs, int init_size)
{
int_stack* s;
int* v;
*rs = 0;
s = xmalloc(sizeof(*s));
if (IS_NULL(s)) return ONIGERR_MEMORY;
v = (int* )xmalloc(sizeof(int) * init_size);
if (IS_NULL(v)) {
xfree(s);
return ONIGERR_MEMORY;
}
s->n = 0;
s->alloc = init_size;
s->v = v;
*rs = s;
return ONIG_NORMAL;
}
static void
free_int_stack(int_stack* s)
{
if (IS_NOT_NULL(s)) {
if (IS_NOT_NULL(s->v))
xfree(s->v);
xfree(s);
}
}
static int
int_stack_push(int_stack* s, int v)
{
if (s->n >= s->alloc) {
int new_size = s->alloc * 2;
int* nv = (int* )xrealloc(s->v, sizeof(int) * new_size);
if (IS_NULL(nv)) return ONIGERR_MEMORY;
s->alloc = new_size;
s->v = nv;
}
s->v[s->n] = v;
s->n++;
return ONIG_NORMAL;
}
static int
int_stack_pop(int_stack* s)
{
int v;
#ifdef ONIG_DEBUG
if (s->n <= 0) {
fprintf(DBGFP, "int_stack_pop: fail empty. %p\n", s);
return 0;
}
#endif
v = s->v[s->n];
s->n--;
return v;
}
#endif
static int
ops_init(regex_t* reg, int init_alloc_size)
{
Operation* p;
size_t size;
if (init_alloc_size > 0) {
size = sizeof(Operation) * init_alloc_size;
p = (Operation* )xrealloc(reg->ops, size);
CHECK_NULL_RETURN_MEMERR(p);
reg->ops = p;
#ifdef USE_DIRECT_THREADED_CODE
{
enum OpCode* cp;
size = sizeof(enum OpCode) * init_alloc_size;
cp = (enum OpCode* )xrealloc(reg->ocs, size);
CHECK_NULL_RETURN_MEMERR(cp);
reg->ocs = cp;
}
#endif
}
else {
reg->ops = (Operation* )0;
#ifdef USE_DIRECT_THREADED_CODE
reg->ocs = (enum OpCode* )0;
#endif
}
reg->ops_curr = 0; /* !!! not yet done ops_new() */
reg->ops_alloc = init_alloc_size;
reg->ops_used = 0;
return ONIG_NORMAL;
}
static int
ops_expand(regex_t* reg, int n)
{
#define MIN_OPS_EXPAND_SIZE 4
#ifdef USE_DIRECT_THREADED_CODE
enum OpCode* cp;
#endif
Operation* p;
size_t size;
if (n <= 0) n = MIN_OPS_EXPAND_SIZE;
n += reg->ops_alloc;
size = sizeof(Operation) * n;
p = (Operation* )xrealloc(reg->ops, size);
CHECK_NULL_RETURN_MEMERR(p);
reg->ops = p;
#ifdef USE_DIRECT_THREADED_CODE
size = sizeof(enum OpCode) * n;
cp = (enum OpCode* )xrealloc(reg->ocs, size);
CHECK_NULL_RETURN_MEMERR(cp);
reg->ocs = cp;
#endif
reg->ops_alloc = n;
if (reg->ops_used == 0)
reg->ops_curr = 0;
else
reg->ops_curr = reg->ops + (reg->ops_used - 1);
return ONIG_NORMAL;
}
static int
ops_new(regex_t* reg)
{
int r;
if (reg->ops_used >= reg->ops_alloc) {
r = ops_expand(reg, reg->ops_alloc);
if (r != ONIG_NORMAL) return r;
}
reg->ops_curr = reg->ops + reg->ops_used;
reg->ops_used++;
xmemset(reg->ops_curr, 0, sizeof(Operation));
return ONIG_NORMAL;
}
static int
is_in_string_pool(regex_t* reg, UChar* s)
{
return (s >= reg->string_pool && s < reg->string_pool_end);
}
static void
ops_free(regex_t* reg)
{
int i;
if (IS_NULL(reg->ops)) return ;
for (i = 0; i < (int )reg->ops_used; i++) {
enum OpCode opcode;
Operation* op;
op = reg->ops + i;
#ifdef USE_DIRECT_THREADED_CODE
opcode = *(reg->ocs + i);
#else
opcode = op->opcode;
#endif
switch (opcode) {
case OP_STR_MBN:
if (! is_in_string_pool(reg, op->exact_len_n.s))
xfree(op->exact_len_n.s);
break;
case OP_STR_N: case OP_STR_MB2N: case OP_STR_MB3N:
if (! is_in_string_pool(reg, op->exact_n.s))
xfree(op->exact_n.s);
break;
case OP_STR_1: case OP_STR_2: case OP_STR_3: case OP_STR_4:
case OP_STR_5: case OP_STR_MB2N1: case OP_STR_MB2N2:
case OP_STR_MB2N3:
break;
case OP_CCLASS_NOT: case OP_CCLASS:
xfree(op->cclass.bsp);
break;
case OP_CCLASS_MB_NOT: case OP_CCLASS_MB:
xfree(op->cclass_mb.mb);
break;
case OP_CCLASS_MIX_NOT: case OP_CCLASS_MIX:
xfree(op->cclass_mix.mb);
xfree(op->cclass_mix.bsp);
break;
case OP_BACKREF1: case OP_BACKREF2: case OP_BACKREF_N: case OP_BACKREF_N_IC:
break;
case OP_BACKREF_MULTI: case OP_BACKREF_MULTI_IC:
case OP_BACKREF_CHECK:
#ifdef USE_BACKREF_WITH_LEVEL
case OP_BACKREF_WITH_LEVEL:
case OP_BACKREF_WITH_LEVEL_IC:
case OP_BACKREF_CHECK_WITH_LEVEL:
#endif
if (op->backref_general.num != 1)
xfree(op->backref_general.ns);
break;
default:
break;
}
}
xfree(reg->ops);
#ifdef USE_DIRECT_THREADED_CODE
xfree(reg->ocs);
reg->ocs = 0;
#endif
reg->ops = 0;
reg->ops_curr = 0;
reg->ops_alloc = 0;
reg->ops_used = 0;
}
static int
ops_calc_size_of_string_pool(regex_t* reg)
{
int i;
int total;
if (IS_NULL(reg->ops)) return 0;
total = 0;
for (i = 0; i < (int )reg->ops_used; i++) {
enum OpCode opcode;
Operation* op;
op = reg->ops + i;
#ifdef USE_DIRECT_THREADED_CODE
opcode = *(reg->ocs + i);
#else
opcode = op->opcode;
#endif
switch (opcode) {
case OP_STR_MBN:
total += op->exact_len_n.len * op->exact_len_n.n;
break;
case OP_STR_N:
case OP_STR_MB2N:
total += op->exact_n.n * 2;
break;
case OP_STR_MB3N:
total += op->exact_n.n * 3;
break;
default:
break;
}
}
return total;
}
static int
ops_make_string_pool(regex_t* reg)
{
int i;
int len;
int size;
UChar* pool;
UChar* curr;
size = ops_calc_size_of_string_pool(reg);
if (size <= 0) {
return 0;
}
curr = pool = (UChar* )xmalloc((size_t )size);
CHECK_NULL_RETURN_MEMERR(pool);
for (i = 0; i < (int )reg->ops_used; i++) {
enum OpCode opcode;
Operation* op;
op = reg->ops + i;
#ifdef USE_DIRECT_THREADED_CODE
opcode = *(reg->ocs + i);
#else
opcode = op->opcode;
#endif
switch (opcode) {
case OP_STR_MBN:
len = op->exact_len_n.len * op->exact_len_n.n;
xmemcpy(curr, op->exact_len_n.s, len);
xfree(op->exact_len_n.s);
op->exact_len_n.s = curr;
curr += len;
break;
case OP_STR_N:
len = op->exact_n.n;
copy:
xmemcpy(curr, op->exact_n.s, len);
xfree(op->exact_n.s);
op->exact_n.s = curr;
curr += len;
break;
case OP_STR_MB2N:
len = op->exact_n.n * 2;
goto copy;
break;
case OP_STR_MB3N:
len = op->exact_n.n * 3;
goto copy;
break;
default:
break;
}
}
reg->string_pool = pool;
reg->string_pool_end = pool + size;
return 0;
}
extern OnigCaseFoldType
onig_get_default_case_fold_flag(void)
{
return OnigDefaultCaseFoldFlag;
}
extern int
onig_set_default_case_fold_flag(OnigCaseFoldType case_fold_flag)
{
OnigDefaultCaseFoldFlag = case_fold_flag;
return 0;
}
static int
len_multiply_cmp(OnigLen x, int y, OnigLen v)
{
if (x == 0 || y == 0) return -1;
if (x < INFINITE_LEN / y) {
OnigLen xy = x * (OnigLen )y;
if (xy > v) return 1;
else {
if (xy == v) return 0;
else return -1;
}
}
else
return v == INFINITE_LEN ? 0 : 1;
}
extern int
onig_positive_int_multiply(int x, int y)
{
if (x == 0 || y == 0) return 0;
if (x < ONIG_INT_MAX / y)
return x * y;
else
return -1;
}
static void
node_swap(Node* a, Node* b)
{
Node c;
c = *a; *a = *b; *b = c;
if (NODE_TYPE(a) == NODE_STRING) {
StrNode* sn = STR_(a);
if (sn->capacity == 0) {
int len = (int )(sn->end - sn->s);
sn->s = sn->buf;
sn->end = sn->s + len;
}
}
if (NODE_TYPE(b) == NODE_STRING) {
StrNode* sn = STR_(b);
if (sn->capacity == 0) {
int len = (int )(sn->end - sn->s);
sn->s = sn->buf;
sn->end = sn->s + len;
}
}
}
static int
node_list_len(Node* list)
{
int len;
len = 1;
while (IS_NOT_NULL(NODE_CDR(list))) {
list = NODE_CDR(list);
len++;
}
return len;
}
static Node*
node_list_add(Node* list, Node* x)
{
Node *n;
n = onig_node_new_list(x, NULL);
if (IS_NULL(n)) return NULL_NODE;
if (IS_NOT_NULL(list)) {
while (IS_NOT_NULL(NODE_CDR(list)))
list = NODE_CDR(list);
NODE_CDR(list) = n;
}
return n;
}
static int
node_str_node_cat(Node* node, Node* add)
{
int r;
if (NODE_STATUS(node) != NODE_STATUS(add))
return ONIGERR_TYPE_BUG;
if (STR_(node)->flag != STR_(add)->flag)
return ONIGERR_TYPE_BUG;
r = onig_node_str_cat(node, STR_(add)->s, STR_(add)->end);
if (r != 0) return r;
return 0;
}
static void
node_conv_to_str_node(Node* node, Node* ref_node)
{
xmemset(node, 0, sizeof(*node));
NODE_SET_TYPE(node, NODE_STRING);
NODE_STATUS(node) = NODE_STATUS(ref_node);
STR_(node)->flag = STR_(ref_node)->flag;
STR_(node)->s = STR_(node)->buf;
STR_(node)->end = STR_(node)->buf;
STR_(node)->capacity = 0;
}
static OnigLen
distance_add(OnigLen d1, OnigLen d2)
{
if (d1 == INFINITE_LEN || d2 == INFINITE_LEN)
return INFINITE_LEN;
else {
if (d1 <= INFINITE_LEN - d2) return d1 + d2;
else return INFINITE_LEN;
}
}
static OnigLen
distance_multiply(OnigLen d, int m)
{
if (m == 0) return 0;
if (d < INFINITE_LEN / m)
return d * m;
else
return INFINITE_LEN;
}
static int
bitset_is_empty(BitSetRef bs)
{
int i;
for (i = 0; i < (int )BITSET_REAL_SIZE; i++) {
if (bs[i] != 0) return 0;
}
return 1;
}
#ifdef USE_CALL
static int
unset_addr_list_init(UnsetAddrList* list, int size)
{
UnsetAddr* p = (UnsetAddr* )xmalloc(sizeof(UnsetAddr)* size);
CHECK_NULL_RETURN_MEMERR(p);
list->num = 0;
list->alloc = size;
list->us = p;
return 0;
}
static void
unset_addr_list_end(UnsetAddrList* list)
{
if (IS_NOT_NULL(list->us))
xfree(list->us);
}
static int
unset_addr_list_add(UnsetAddrList* list, int offset, struct _Node* node)
{
UnsetAddr* p;
int size;
if (list->num >= list->alloc) {
size = list->alloc * 2;
p = (UnsetAddr* )xrealloc(list->us, sizeof(UnsetAddr) * size);
CHECK_NULL_RETURN_MEMERR(p);
list->alloc = size;
list->us = p;
}
list->us[list->num].offset = offset;
list->us[list->num].target = node;
list->num++;
return 0;
}
#endif /* USE_CALL */
enum CharLenReturnType {
CHAR_LEN_NORMAL = 0, /* fixed or variable */
CHAR_LEN_TOP_ALT_FIXED = 1
};
static int
mmcl_fixed(MinMaxCharLen* c)
{
return (c->min == c->max && c->min != INFINITE_LEN);
}
static void
mmcl_set(MinMaxCharLen* l, OnigLen len)
{
l->min = len;
l->max = len;
l->min_is_sure = TRUE;
}
static void
mmcl_set_min_max(MinMaxCharLen* l, OnigLen min, OnigLen max, int min_is_sure)
{
l->min = min;
l->max = max;
l->min_is_sure = min_is_sure;
}
static void
mmcl_add(MinMaxCharLen* to, MinMaxCharLen* add)
{
to->min = distance_add(to->min, add->min);
to->max = distance_add(to->max, add->max);
to->min_is_sure = add->min_is_sure != FALSE && to->min_is_sure != FALSE;
}
static void
mmcl_multiply(MinMaxCharLen* to, int m)
{
to->min = distance_multiply(to->min, m);
to->max = distance_multiply(to->max, m);
}
static void
mmcl_repeat_range_multiply(MinMaxCharLen* to, int mlow, int mhigh)
{
to->min = distance_multiply(to->min, mlow);
if (IS_INFINITE_REPEAT(mhigh))
to->max = INFINITE_LEN;
else
to->max = distance_multiply(to->max, mhigh);
}
static void
mmcl_alt_merge(MinMaxCharLen* to, MinMaxCharLen* alt)
{
if (to->min > alt->min) {
to->min = alt->min;
to->min_is_sure = alt->min_is_sure;
}
else if (to->min == alt->min) {
if (alt->min_is_sure != FALSE)
to->min_is_sure = TRUE;
}
if (to->max < alt->max) to->max = alt->max;
}
static int
mml_is_equal(MinMaxLen* a, MinMaxLen* b)
{
return a->min == b->min && a->max == b->max;
}
static void
mml_set_min_max(MinMaxLen* l, OnigLen min, OnigLen max)
{
l->min = min;
l->max = max;
}
static void
mml_clear(MinMaxLen* l)
{
l->min = l->max = 0;
}
static void
mml_copy(MinMaxLen* to, MinMaxLen* from)
{
to->min = from->min;
to->max = from->max;
}
static void
mml_add(MinMaxLen* to, MinMaxLen* add)
{
to->min = distance_add(to->min, add->min);
to->max = distance_add(to->max, add->max);
}
static void
mml_alt_merge(MinMaxLen* to, MinMaxLen* alt)
{
if (to->min > alt->min) to->min = alt->min;
if (to->max < alt->max) to->max = alt->max;
}
/* fixed size pattern node only */
static int
node_char_len1(Node* node, regex_t* reg, MinMaxCharLen* ci, ScanEnv* env,
int level)
{
MinMaxCharLen tci;
int r = CHAR_LEN_NORMAL;
level++;
switch (NODE_TYPE(node)) {
case NODE_LIST:
{
int first = TRUE;
do {
r = node_char_len1(NODE_CAR(node), reg, &tci, env, level);
if (r < 0) break;
if (first == TRUE) {
*ci = tci;
first = FALSE;
}
else
mmcl_add(ci, &tci);
} while (IS_NOT_NULL(node = NODE_CDR(node)));
}
break;
case NODE_ALT:
{
int fixed;
r = node_char_len1(NODE_CAR(node), reg, ci, env, level);
if (r < 0) break;
fixed = TRUE;
while (IS_NOT_NULL(node = NODE_CDR(node))) {
r = node_char_len1(NODE_CAR(node), reg, &tci, env, level);
if (r < 0) break;
if (! mmcl_fixed(&tci))
fixed = FALSE;
mmcl_alt_merge(ci, &tci);
}
if (r < 0) break;
r = CHAR_LEN_NORMAL;
if (mmcl_fixed(ci)) break;
if (fixed == TRUE && level == 1) {
r = CHAR_LEN_TOP_ALT_FIXED;
}
}
break;
case NODE_STRING:
{
OnigLen clen;
StrNode* sn = STR_(node);
UChar *s = sn->s;
if (NODE_IS_IGNORECASE(node) && ! NODE_STRING_IS_CRUDE(node)) {
/* Such a case is possible.
ex. /(?i)(?<=\1)(a)/
Backref node refer to capture group, but it doesn't tune yet.
*/
r = ONIGERR_INVALID_LOOK_BEHIND_PATTERN;
break;
}
clen = 0;
while (s < sn->end) {
s += enclen(reg->enc, s);
clen = distance_add(clen, 1);
}
mmcl_set(ci, clen);
}
break;
case NODE_QUANT:
{
QuantNode* qn = QUANT_(node);
if (qn->lower == qn->upper) {
if (qn->upper == 0) {
mmcl_set(ci, 0);
}
else {
r = node_char_len1(NODE_BODY(node), reg, ci, env, level);
if (r < 0) break;
mmcl_multiply(ci, qn->lower);
}
}
else {
r = node_char_len1(NODE_BODY(node), reg, ci, env, level);
if (r < 0) break;
mmcl_repeat_range_multiply(ci, qn->lower, qn->upper);
}
}
break;
#ifdef USE_CALL
case NODE_CALL:
if (NODE_IS_RECURSION(node))
mmcl_set_min_max(ci, 0, INFINITE_LEN, FALSE);
else
r = node_char_len1(NODE_BODY(node), reg, ci, env, level);
break;
#endif
case NODE_CTYPE:
case NODE_CCLASS:
mmcl_set(ci, 1);
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
switch (en->type) {
case BAG_MEMORY:
if (NODE_IS_FIXED_CLEN(node)) {
mmcl_set_min_max(ci, en->min_char_len, en->max_char_len,
NODE_IS_FIXED_CLEN_MIN_SURE(node));
}
else {
if (NODE_IS_MARK1(node)) {
mmcl_set_min_max(ci, 0, INFINITE_LEN, FALSE);
}
else {
NODE_STATUS_ADD(node, MARK1);
r = node_char_len1(NODE_BODY(node), reg, ci, env, level);
NODE_STATUS_REMOVE(node, MARK1);
if (r < 0) break;
en->min_char_len = ci->min;
en->max_char_len = ci->max;
NODE_STATUS_ADD(node, FIXED_CLEN);
if (ci->min_is_sure != FALSE)
NODE_STATUS_ADD(node, FIXED_CLEN_MIN_SURE);
}
}
/* can't optimize look-behind if capture exists. */
ci->min_is_sure = FALSE;
break;
case BAG_OPTION:
case BAG_STOP_BACKTRACK:
r = node_char_len1(NODE_BODY(node), reg, ci, env, level);
break;
case BAG_IF_ELSE:
{
MinMaxCharLen eci;
r = node_char_len1(NODE_BODY(node), reg, ci, env, level);
if (r < 0) break;
if (IS_NOT_NULL(en->te.Then)) {
r = node_char_len1(en->te.Then, reg, &tci, env, level);
if (r < 0) break;
mmcl_add(ci, &tci);
}
if (IS_NOT_NULL(en->te.Else)) {
r = node_char_len1(en->te.Else, reg, &eci, env, level);
if (r < 0) break;
}
else {
mmcl_set(&eci, 0);
}
mmcl_alt_merge(ci, &eci);
}
break;
default: /* never come here */
r = ONIGERR_PARSER_BUG;
break;
}
}
break;
case NODE_GIMMICK:
mmcl_set(ci, 0);
break;
case NODE_ANCHOR:
zero:
mmcl_set(ci, 0);
/* can't optimize look-behind if anchor exists. */
ci->min_is_sure = FALSE;
break;
case NODE_BACKREF:
if (NODE_IS_CHECKER(node))
goto zero;
if (NODE_IS_RECURSION(node)) {
#ifdef USE_BACKREF_WITH_LEVEL
if (NODE_IS_NEST_LEVEL(node)) {
mmcl_set_min_max(ci, 0, INFINITE_LEN, FALSE);
break;
}
#endif
mmcl_set_min_max(ci, 0, 0, FALSE);
break;
}
{
int i;
int* backs;
MemEnv* mem_env = SCANENV_MEMENV(env);
BackRefNode* br = BACKREF_(node);
backs = BACKREFS_P(br);
r = node_char_len1(mem_env[backs[0]].mem_node, reg, ci, env, level);
if (r < 0) break;
if (! mmcl_fixed(ci)) ci->min_is_sure = FALSE;
for (i = 1; i < br->back_num; i++) {
r = node_char_len1(mem_env[backs[i]].mem_node, reg, &tci, env, level);
if (r < 0) break;
if (! mmcl_fixed(&tci)) tci.min_is_sure = FALSE;
mmcl_alt_merge(ci, &tci);
}
}
break;
default: /* never come here */
r = ONIGERR_PARSER_BUG;
break;
}
return r;
}
static int
node_char_len(Node* node, regex_t* reg, MinMaxCharLen* ci, ScanEnv* env)
{
return node_char_len1(node, reg, ci, env, 0);
}
static int
add_op(regex_t* reg, int opcode)
{
int r;
r = ops_new(reg);
if (r != ONIG_NORMAL) return r;
#ifdef USE_DIRECT_THREADED_CODE
*(reg->ocs + (reg->ops_curr - reg->ops)) = opcode;
#else
reg->ops_curr->opcode = opcode;
#endif
return 0;
}
static int compile_length_tree(Node* node, regex_t* reg);
static int compile_tree(Node* node, regex_t* reg, ScanEnv* env);
#define IS_NEED_STR_LEN_OP(op) \
((op) == OP_STR_N || (op) == OP_STR_MB2N ||\
(op) == OP_STR_MB3N || (op) == OP_STR_MBN)
static int
select_str_opcode(int mb_len, int str_len)
{
int op;
switch (mb_len) {
case 1:
switch (str_len) {
case 1: op = OP_STR_1; break;
case 2: op = OP_STR_2; break;
case 3: op = OP_STR_3; break;
case 4: op = OP_STR_4; break;
case 5: op = OP_STR_5; break;
default: op = OP_STR_N; break;
}
break;
case 2:
switch (str_len) {
case 1: op = OP_STR_MB2N1; break;
case 2: op = OP_STR_MB2N2; break;
case 3: op = OP_STR_MB2N3; break;
default: op = OP_STR_MB2N; break;
}
break;
case 3:
op = OP_STR_MB3N;
break;
default:
op = OP_STR_MBN;
break;
}
return op;
}
static int
is_strict_real_node(Node* node)
{
switch (NODE_TYPE(node)) {
case NODE_STRING:
{
StrNode* sn = STR_(node);
return (sn->end != sn->s);
}
break;
case NODE_CCLASS:
case NODE_CTYPE:
return 1;
break;
default:
return 0;
break;
}
}
static int
compile_quant_body_with_empty_check(QuantNode* qn, regex_t* reg, ScanEnv* env)
{
int r;
int saved_num_empty_check;
int emptiness;
Node* body;
body = NODE_BODY((Node* )qn);
emptiness = qn->emptiness;
saved_num_empty_check = reg->num_empty_check;
if (emptiness != BODY_IS_NOT_EMPTY) {
r = add_op(reg, OP_EMPTY_CHECK_START);
if (r != 0) return r;
COP(reg)->empty_check_start.mem = reg->num_empty_check; /* NULL CHECK ID */
reg->num_empty_check++;
}
r = compile_tree(body, reg, env);
if (r != 0) return r;
if (emptiness != BODY_IS_NOT_EMPTY) {
if (emptiness == BODY_MAY_BE_EMPTY)
r = add_op(reg, OP_EMPTY_CHECK_END);
else if (emptiness == BODY_MAY_BE_EMPTY_MEM) {
if (NODE_IS_EMPTY_STATUS_CHECK(qn) != 0)
r = add_op(reg, OP_EMPTY_CHECK_END_MEMST);
else
r = add_op(reg, OP_EMPTY_CHECK_END);
}
#ifdef USE_CALL
else if (emptiness == BODY_MAY_BE_EMPTY_REC)
r = add_op(reg, OP_EMPTY_CHECK_END_MEMST_PUSH);
#endif
if (r != 0) return r;
COP(reg)->empty_check_end.mem = saved_num_empty_check; /* NULL CHECK ID */
}
return r;
}
#ifdef USE_CALL
static int
compile_call(CallNode* node, regex_t* reg, ScanEnv* env)
{
int r;
int offset;
r = add_op(reg, OP_CALL);
if (r != 0) return r;
COP(reg)->call.addr = 0; /* dummy addr. */
#ifdef ONIG_DEBUG_MATCH_COUNTER
COP(reg)->call.called_mem = node->called_gnum;
#endif
offset = COP_CURR_OFFSET_BYTES(reg, call.addr);
r = unset_addr_list_add(env->unset_addr_list, offset, NODE_CALL_BODY(node));
return r;
}
#endif
static int
compile_tree_n_times(Node* node, int n, regex_t* reg, ScanEnv* env)
{
int i, r;
for (i = 0; i < n; i++) {
r = compile_tree(node, reg, env);
if (r != 0) return r;
}
return 0;
}
static int
add_compile_string_length(UChar* s ARG_UNUSED, int mb_len, int str_len,
regex_t* reg ARG_UNUSED)
{
return 1;
}
static int
add_compile_string(UChar* s, int mb_len, int str_len, regex_t* reg)
{
int op;
int r;
int byte_len;
UChar* p;
UChar* end;
op = select_str_opcode(mb_len, str_len);
r = add_op(reg, op);
if (r != 0) return r;
byte_len = mb_len * str_len;
end = s + byte_len;
if (op == OP_STR_MBN) {
p = onigenc_strdup(reg->enc, s, end);
CHECK_NULL_RETURN_MEMERR(p);
COP(reg)->exact_len_n.len = mb_len;
COP(reg)->exact_len_n.n = str_len;
COP(reg)->exact_len_n.s = p;
}
else if (IS_NEED_STR_LEN_OP(op)) {
p = onigenc_strdup(reg->enc, s, end);
CHECK_NULL_RETURN_MEMERR(p);
COP(reg)->exact_n.n = str_len;
COP(reg)->exact_n.s = p;
}
else {
xmemset(COP(reg)->exact.s, 0, sizeof(COP(reg)->exact.s));
xmemcpy(COP(reg)->exact.s, s, (size_t )byte_len);
}
return 0;
}
static int
compile_length_string_node(Node* node, regex_t* reg)
{
int rlen, r, len, prev_len, slen;
UChar *p, *prev;
StrNode* sn;
OnigEncoding enc = reg->enc;
sn = STR_(node);
if (sn->end <= sn->s)
return 0;
p = prev = sn->s;
prev_len = enclen(enc, p);
p += prev_len;
slen = 1;
rlen = 0;
for (; p < sn->end; ) {
len = enclen(enc, p);
if (len == prev_len) {
slen++;
}
else {
r = add_compile_string_length(prev, prev_len, slen, reg);
rlen += r;
prev = p;
slen = 1;
prev_len = len;
}
p += len;
}
r = add_compile_string_length(prev, prev_len, slen, reg);
rlen += r;
return rlen;
}
static int
compile_length_string_crude_node(StrNode* sn, regex_t* reg)
{
if (sn->end <= sn->s)
return 0;
return add_compile_string_length(sn->s, 1 /* sb */, (int )(sn->end - sn->s),
reg);
}
static int
compile_string_node(Node* node, regex_t* reg)
{
int r, len, prev_len, slen;
UChar *p, *prev, *end;
StrNode* sn;
OnigEncoding enc = reg->enc;
sn = STR_(node);
if (sn->end <= sn->s)
return 0;
end = sn->end;
p = prev = sn->s;
prev_len = enclen(enc, p);
p += prev_len;
slen = 1;
for (; p < end; ) {
len = enclen(enc, p);
if (len == prev_len) {
slen++;
}
else {
r = add_compile_string(prev, prev_len, slen, reg);
if (r != 0) return r;
prev = p;
slen = 1;
prev_len = len;
}
p += len;
}
return add_compile_string(prev, prev_len, slen, reg);
}
static int
compile_string_crude_node(StrNode* sn, regex_t* reg)
{
if (sn->end <= sn->s)
return 0;
return add_compile_string(sn->s, 1 /* sb */, (int )(sn->end - sn->s), reg);
}
static void*
set_multi_byte_cclass(BBuf* mbuf, regex_t* reg)
{
size_t len;
void* p;
len = (size_t )mbuf->used;
p = xmalloc(len);
if (IS_NULL(p)) return NULL;
xmemcpy(p, mbuf->p, len);
return p;
}
static int
compile_length_cclass_node(CClassNode* cc, regex_t* reg)
{
return 1;
}
static int
compile_cclass_node(CClassNode* cc, regex_t* reg)
{
int r;
if (IS_NULL(cc->mbuf)) {
r = add_op(reg, IS_NCCLASS_NOT(cc) ? OP_CCLASS_NOT : OP_CCLASS);
if (r != 0) return r;
COP(reg)->cclass.bsp = xmalloc(SIZE_BITSET);
CHECK_NULL_RETURN_MEMERR(COP(reg)->cclass.bsp);
xmemcpy(COP(reg)->cclass.bsp, cc->bs, SIZE_BITSET);
}
else {
void* p;
if (ONIGENC_MBC_MINLEN(reg->enc) > 1 || bitset_is_empty(cc->bs)) {
r = add_op(reg, IS_NCCLASS_NOT(cc) ? OP_CCLASS_MB_NOT : OP_CCLASS_MB);
if (r != 0) return r;
p = set_multi_byte_cclass(cc->mbuf, reg);
CHECK_NULL_RETURN_MEMERR(p);
COP(reg)->cclass_mb.mb = p;
}
else {
r = add_op(reg, IS_NCCLASS_NOT(cc) ? OP_CCLASS_MIX_NOT : OP_CCLASS_MIX);
if (r != 0) return r;
COP(reg)->cclass_mix.bsp = xmalloc(SIZE_BITSET);
CHECK_NULL_RETURN_MEMERR(COP(reg)->cclass_mix.bsp);
xmemcpy(COP(reg)->cclass_mix.bsp, cc->bs, SIZE_BITSET);
p = set_multi_byte_cclass(cc->mbuf, reg);
CHECK_NULL_RETURN_MEMERR(p);
COP(reg)->cclass_mix.mb = p;
}
}
return 0;
}
static void
set_addr_in_repeat_range(regex_t* reg)
{
int i;
for (i = 0; i < reg->num_repeat; i++) {
RepeatRange* p = reg->repeat_range + i;
int offset = p->u.offset;
p->u.pcode = reg->ops + offset;
}
}
static int
entry_repeat_range(regex_t* reg, int id, int lower, int upper, int ops_index)
{
#define REPEAT_RANGE_ALLOC 4
RepeatRange* p;
if (reg->repeat_range_alloc == 0) {
p = (RepeatRange* )xmalloc(sizeof(RepeatRange) * REPEAT_RANGE_ALLOC);
CHECK_NULL_RETURN_MEMERR(p);
reg->repeat_range = p;
reg->repeat_range_alloc = REPEAT_RANGE_ALLOC;
}
else if (reg->repeat_range_alloc <= id) {
int n;
n = reg->repeat_range_alloc + REPEAT_RANGE_ALLOC;
p = (RepeatRange* )xrealloc(reg->repeat_range, sizeof(RepeatRange) * n);
CHECK_NULL_RETURN_MEMERR(p);
reg->repeat_range = p;
reg->repeat_range_alloc = n;
}
else {
p = reg->repeat_range;
}
p[id].lower = lower;
p[id].upper = (IS_INFINITE_REPEAT(upper) ? 0x7fffffff : upper);
p[id].u.offset = ops_index;
return 0;
}
static int
compile_range_repeat_node(QuantNode* qn, int target_len, int emptiness,
regex_t* reg, ScanEnv* env)
{
int r;
int num_repeat = reg->num_repeat++;
r = add_op(reg, qn->greedy ? OP_REPEAT : OP_REPEAT_NG);
if (r != 0) return r;
COP(reg)->repeat.id = num_repeat;
COP(reg)->repeat.addr = SIZE_INC + target_len + OPSIZE_REPEAT_INC;
r = entry_repeat_range(reg, num_repeat, qn->lower, qn->upper,
COP_CURR_OFFSET(reg) + OPSIZE_REPEAT);
if (r != 0) return r;
r = compile_quant_body_with_empty_check(qn, reg, env);
if (r != 0) return r;
r = add_op(reg, qn->greedy ? OP_REPEAT_INC : OP_REPEAT_INC_NG);
if (r != 0) return r;
COP(reg)->repeat_inc.id = num_repeat;
return r;
}
static int
is_anychar_infinite_greedy(QuantNode* qn)
{
if (qn->greedy && IS_INFINITE_REPEAT(qn->upper) &&
NODE_IS_ANYCHAR(NODE_QUANT_BODY(qn)))
return 1;
else
return 0;
}
#define QUANTIFIER_EXPAND_LIMIT_SIZE 10
#define CKN_ON (ckn > 0)
static int
compile_length_quantifier_node(QuantNode* qn, regex_t* reg)
{
int len, mod_tlen;
int infinite = IS_INFINITE_REPEAT(qn->upper);
enum BodyEmptyType emptiness = qn->emptiness;
int tlen = compile_length_tree(NODE_QUANT_BODY(qn), reg);
if (tlen < 0) return tlen;
if (tlen == 0) return 0;
/* anychar repeat */
if (is_anychar_infinite_greedy(qn)) {
if (qn->lower <= 1 ||
len_multiply_cmp((OnigLen )tlen, qn->lower, QUANTIFIER_EXPAND_LIMIT_SIZE) <= 0) {
if (IS_NOT_NULL(qn->next_head_exact))
return OPSIZE_ANYCHAR_STAR_PEEK_NEXT + tlen * qn->lower;
else
return OPSIZE_ANYCHAR_STAR + tlen * qn->lower;
}
}
mod_tlen = tlen;
if (emptiness != BODY_IS_NOT_EMPTY)
mod_tlen += OPSIZE_EMPTY_CHECK_START + OPSIZE_EMPTY_CHECK_END;
if (infinite &&
(qn->lower <= 1 ||
len_multiply_cmp(tlen, qn->lower, QUANTIFIER_EXPAND_LIMIT_SIZE) <= 0)) {
if (qn->lower == 1 && tlen > QUANTIFIER_EXPAND_LIMIT_SIZE) {
len = OPSIZE_JUMP;
}
else {
len = tlen * qn->lower;
}
if (qn->greedy) {
#ifdef USE_OP_PUSH_OR_JUMP_EXACT
if (IS_NOT_NULL(qn->head_exact))
len += OPSIZE_PUSH_OR_JUMP_EXACT1 + mod_tlen + OPSIZE_JUMP;
else
#endif
if (IS_NOT_NULL(qn->next_head_exact))
len += OPSIZE_PUSH_IF_PEEK_NEXT + mod_tlen + OPSIZE_JUMP;
else
len += OPSIZE_PUSH + mod_tlen + OPSIZE_JUMP;
}
else
len += OPSIZE_JUMP + mod_tlen + OPSIZE_PUSH;
}
else if (qn->upper == 0) {
if (qn->include_referred != 0) { /* /(?<n>..){0}/ */
len = OPSIZE_JUMP + tlen;
}
else
len = 0;
}
else if (!infinite && qn->greedy &&
(qn->upper == 1 ||
len_multiply_cmp((OnigLen )tlen + OPSIZE_PUSH, qn->upper,
QUANTIFIER_EXPAND_LIMIT_SIZE) <= 0)) {
len = tlen * qn->lower;
len += (OPSIZE_PUSH + tlen) * (qn->upper - qn->lower);
}
else if (!qn->greedy && qn->upper == 1 && qn->lower == 0) { /* '??' */
len = OPSIZE_PUSH + OPSIZE_JUMP + tlen;
}
else {
len = OPSIZE_REPEAT_INC + mod_tlen + OPSIZE_REPEAT;
}
return len;
}
static int
compile_quantifier_node(QuantNode* qn, regex_t* reg, ScanEnv* env)
{
int i, r, mod_tlen;
int infinite = IS_INFINITE_REPEAT(qn->upper);
enum BodyEmptyType emptiness = qn->emptiness;
int tlen = compile_length_tree(NODE_QUANT_BODY(qn), reg);
if (tlen < 0) return tlen;
if (tlen == 0) return 0;
if (is_anychar_infinite_greedy(qn) &&
(qn->lower <= 1 ||
len_multiply_cmp((OnigLen )tlen, qn->lower,
QUANTIFIER_EXPAND_LIMIT_SIZE) <= 0)) {
r = compile_tree_n_times(NODE_QUANT_BODY(qn), qn->lower, reg, env);
if (r != 0) return r;
if (IS_NOT_NULL(qn->next_head_exact)) {
r = add_op(reg, NODE_IS_MULTILINE(NODE_QUANT_BODY(qn)) ?
OP_ANYCHAR_ML_STAR_PEEK_NEXT : OP_ANYCHAR_STAR_PEEK_NEXT);
if (r != 0) return r;
COP(reg)->anychar_star_peek_next.c = STR_(qn->next_head_exact)->s[0];
return 0;
}
else {
r = add_op(reg, NODE_IS_MULTILINE(NODE_QUANT_BODY(qn)) ?
OP_ANYCHAR_ML_STAR : OP_ANYCHAR_STAR);
return r;
}
}
mod_tlen = tlen;
if (emptiness != BODY_IS_NOT_EMPTY)
mod_tlen += OPSIZE_EMPTY_CHECK_START + OPSIZE_EMPTY_CHECK_END;
if (infinite &&
(qn->lower <= 1 ||
len_multiply_cmp((OnigLen )tlen, qn->lower,
QUANTIFIER_EXPAND_LIMIT_SIZE) <= 0)) {
int addr;
if (qn->lower == 1 && tlen > QUANTIFIER_EXPAND_LIMIT_SIZE) {
r = add_op(reg, OP_JUMP);
if (r != 0) return r;
if (qn->greedy) {
#ifdef USE_OP_PUSH_OR_JUMP_EXACT
if (IS_NOT_NULL(qn->head_exact))
COP(reg)->jump.addr = OPSIZE_PUSH_OR_JUMP_EXACT1 + SIZE_INC;
else
#endif
if (IS_NOT_NULL(qn->next_head_exact))
COP(reg)->jump.addr = OPSIZE_PUSH_IF_PEEK_NEXT + SIZE_INC;
else
COP(reg)->jump.addr = OPSIZE_PUSH + SIZE_INC;
}
else {
COP(reg)->jump.addr = OPSIZE_JUMP + SIZE_INC;
}
}
else {
r = compile_tree_n_times(NODE_QUANT_BODY(qn), qn->lower, reg, env);
if (r != 0) return r;
}
if (qn->greedy) {
#ifdef USE_OP_PUSH_OR_JUMP_EXACT
if (IS_NOT_NULL(qn->head_exact)) {
r = add_op(reg, OP_PUSH_OR_JUMP_EXACT1);
if (r != 0) return r;
COP(reg)->push_or_jump_exact1.addr = SIZE_INC + mod_tlen + OPSIZE_JUMP;
COP(reg)->push_or_jump_exact1.c = STR_(qn->head_exact)->s[0];
r = compile_quant_body_with_empty_check(qn, reg, env);
if (r != 0) return r;
addr = -(mod_tlen + (int )OPSIZE_PUSH_OR_JUMP_EXACT1);
}
else
#endif
if (IS_NOT_NULL(qn->next_head_exact)) {
r = add_op(reg, OP_PUSH_IF_PEEK_NEXT);
if (r != 0) return r;
COP(reg)->push_if_peek_next.addr = SIZE_INC + mod_tlen + OPSIZE_JUMP;
COP(reg)->push_if_peek_next.c = STR_(qn->next_head_exact)->s[0];
r = compile_quant_body_with_empty_check(qn, reg, env);
if (r != 0) return r;
addr = -(mod_tlen + (int )OPSIZE_PUSH_IF_PEEK_NEXT);
}
else {
r = add_op(reg, OP_PUSH);
if (r != 0) return r;
COP(reg)->push.addr = SIZE_INC + mod_tlen + OPSIZE_JUMP;
r = compile_quant_body_with_empty_check(qn, reg, env);
if (r != 0) return r;
addr = -(mod_tlen + (int )OPSIZE_PUSH);
}
r = add_op(reg, OP_JUMP);
if (r != 0) return r;
COP(reg)->jump.addr = addr;
}
else {
r = add_op(reg, OP_JUMP);
if (r != 0) return r;
COP(reg)->jump.addr = mod_tlen + SIZE_INC;
r = compile_quant_body_with_empty_check(qn, reg, env);
if (r != 0) return r;
r = add_op(reg, OP_PUSH);
if (r != 0) return r;
COP(reg)->push.addr = -mod_tlen;
}
}
else if (qn->upper == 0) {
if (qn->include_referred != 0) { /* /(?<n>..){0}/ */
r = add_op(reg, OP_JUMP);
if (r != 0) return r;
COP(reg)->jump.addr = tlen + SIZE_INC;
r = compile_tree(NODE_QUANT_BODY(qn), reg, env);
}
else {
/* Nothing output */
r = 0;
}
}
else if (! infinite && qn->greedy &&
(qn->upper == 1 ||
len_multiply_cmp((OnigLen )tlen + OPSIZE_PUSH, qn->upper,
QUANTIFIER_EXPAND_LIMIT_SIZE) <= 0)) {
int n = qn->upper - qn->lower;
r = compile_tree_n_times(NODE_QUANT_BODY(qn), qn->lower, reg, env);
if (r != 0) return r;
for (i = 0; i < n; i++) {
int v = onig_positive_int_multiply(n - i, tlen + OPSIZE_PUSH);
if (v < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE;
r = add_op(reg, OP_PUSH);
if (r != 0) return r;
COP(reg)->push.addr = v;
r = compile_tree(NODE_QUANT_BODY(qn), reg, env);
if (r != 0) return r;
}
}
else if (! qn->greedy && qn->upper == 1 && qn->lower == 0) { /* '??' */
r = add_op(reg, OP_PUSH);
if (r != 0) return r;
COP(reg)->push.addr = SIZE_INC + OPSIZE_JUMP;
r = add_op(reg, OP_JUMP);
if (r != 0) return r;
COP(reg)->jump.addr = tlen + SIZE_INC;
r = compile_tree(NODE_QUANT_BODY(qn), reg, env);
}
else {
r = compile_range_repeat_node(qn, mod_tlen, emptiness, reg, env);
}
return r;
}
static int
compile_length_option_node(BagNode* node, regex_t* reg)
{
int tlen;
tlen = compile_length_tree(NODE_BAG_BODY(node), reg);
return tlen;
}
static int
compile_option_node(BagNode* node, regex_t* reg, ScanEnv* env)
{
int r;
r = compile_tree(NODE_BAG_BODY(node), reg, env);
return r;
}
static int
compile_length_bag_node(BagNode* node, regex_t* reg)
{
int len;
int tlen;
if (node->type == BAG_OPTION)
return compile_length_option_node(node, reg);
if (NODE_BAG_BODY(node)) {
tlen = compile_length_tree(NODE_BAG_BODY(node), reg);
if (tlen < 0) return tlen;
}
else
tlen = 0;
switch (node->type) {
case BAG_MEMORY:
#ifdef USE_CALL
if (node->m.regnum == 0 && NODE_IS_CALLED(node)) {
len = tlen + OPSIZE_CALL + OPSIZE_JUMP + OPSIZE_RETURN;
return len;
}
if (NODE_IS_CALLED(node)) {
len = OPSIZE_MEM_START_PUSH + tlen
+ OPSIZE_CALL + OPSIZE_JUMP + OPSIZE_RETURN;
if (MEM_STATUS_AT0(reg->push_mem_end, node->m.regnum))
len += (NODE_IS_RECURSION(node)
? OPSIZE_MEM_END_PUSH_REC : OPSIZE_MEM_END_PUSH);
else
len += (NODE_IS_RECURSION(node)
? OPSIZE_MEM_END_REC : OPSIZE_MEM_END);
}
else if (NODE_IS_RECURSION(node)) {
len = OPSIZE_MEM_START_PUSH;
len += tlen + (MEM_STATUS_AT0(reg->push_mem_end, node->m.regnum)
? OPSIZE_MEM_END_PUSH_REC : OPSIZE_MEM_END_REC);
}
else
#endif
{
if (MEM_STATUS_AT0(reg->push_mem_start, node->m.regnum))
len = OPSIZE_MEM_START_PUSH;
else
len = OPSIZE_MEM_START;
len += tlen + (MEM_STATUS_AT0(reg->push_mem_end, node->m.regnum)
? OPSIZE_MEM_END_PUSH : OPSIZE_MEM_END);
}
break;
case BAG_STOP_BACKTRACK:
if (NODE_IS_STRICT_REAL_REPEAT(node)) {
int v;
QuantNode* qn;
qn = QUANT_(NODE_BAG_BODY(node));
tlen = compile_length_tree(NODE_QUANT_BODY(qn), reg);
if (tlen < 0) return tlen;
v = onig_positive_int_multiply(qn->lower, tlen);
if (v < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE;
len = v + OPSIZE_PUSH + tlen + OPSIZE_POP + OPSIZE_JUMP;
}
else {
len = OPSIZE_MARK + tlen + OPSIZE_CUT_TO_MARK;
}
break;
case BAG_IF_ELSE:
{
Node* cond = NODE_BAG_BODY(node);
Node* Then = node->te.Then;
Node* Else = node->te.Else;
len = compile_length_tree(cond, reg);
if (len < 0) return len;
len += OPSIZE_PUSH + OPSIZE_MARK + OPSIZE_CUT_TO_MARK;
if (IS_NOT_NULL(Then)) {
tlen = compile_length_tree(Then, reg);
if (tlen < 0) return tlen;
len += tlen;
}
len += OPSIZE_JUMP + OPSIZE_CUT_TO_MARK;
if (IS_NOT_NULL(Else)) {
tlen = compile_length_tree(Else, reg);
if (tlen < 0) return tlen;
len += tlen;
}
}
break;
case BAG_OPTION:
/* never come here, but set for escape warning */
len = 0;
break;
}
return len;
}
static int
compile_bag_memory_node(BagNode* node, regex_t* reg, ScanEnv* env)
{
int r;
#ifdef USE_CALL
if (NODE_IS_CALLED(node)) {
int len;
r = add_op(reg, OP_CALL);
if (r != 0) return r;
node->m.called_addr = COP_CURR_OFFSET(reg) + 1 + OPSIZE_JUMP;
NODE_STATUS_ADD(node, FIXED_ADDR);
COP(reg)->call.addr = (int )node->m.called_addr;
if (node->m.regnum == 0) {
len = compile_length_tree(NODE_BAG_BODY(node), reg);
len += OPSIZE_RETURN;
r = add_op(reg, OP_JUMP);
if (r != 0) return r;
COP(reg)->jump.addr = len + SIZE_INC;
r = compile_tree(NODE_BAG_BODY(node), reg, env);
if (r != 0) return r;
r = add_op(reg, OP_RETURN);
return r;
}
else {
len = compile_length_tree(NODE_BAG_BODY(node), reg);
len += (OPSIZE_MEM_START_PUSH + OPSIZE_RETURN);
if (MEM_STATUS_AT0(reg->push_mem_end, node->m.regnum))
len += (NODE_IS_RECURSION(node)
? OPSIZE_MEM_END_PUSH_REC : OPSIZE_MEM_END_PUSH);
else
len += (NODE_IS_RECURSION(node) ? OPSIZE_MEM_END_REC : OPSIZE_MEM_END);
r = add_op(reg, OP_JUMP);
if (r != 0) return r;
COP(reg)->jump.addr = len + SIZE_INC;
}
}
#endif
if (MEM_STATUS_AT0(reg->push_mem_start, node->m.regnum))
r = add_op(reg, OP_MEM_START_PUSH);
else
r = add_op(reg, OP_MEM_START);
if (r != 0) return r;
COP(reg)->memory_start.num = node->m.regnum;
r = compile_tree(NODE_BAG_BODY(node), reg, env);
if (r != 0) return r;
#ifdef USE_CALL
if (MEM_STATUS_AT0(reg->push_mem_end, node->m.regnum))
r = add_op(reg, (NODE_IS_RECURSION(node)
? OP_MEM_END_PUSH_REC : OP_MEM_END_PUSH));
else
r = add_op(reg, (NODE_IS_RECURSION(node) ? OP_MEM_END_REC : OP_MEM_END));
if (r != 0) return r;
COP(reg)->memory_end.num = node->m.regnum;
if (NODE_IS_CALLED(node)) {
r = add_op(reg, OP_RETURN);
}
#else
if (MEM_STATUS_AT0(reg->push_mem_end, node->m.regnum))
r = add_op(reg, OP_MEM_END_PUSH);
else
r = add_op(reg, OP_MEM_END);
if (r != 0) return r;
COP(reg)->memory_end.num = node->m.regnum;
#endif
return r;
}
static int
compile_bag_node(BagNode* node, regex_t* reg, ScanEnv* env)
{
int r, len;
switch (node->type) {
case BAG_MEMORY:
r = compile_bag_memory_node(node, reg, env);
break;
case BAG_OPTION:
r = compile_option_node(node, reg, env);
break;
case BAG_STOP_BACKTRACK:
if (NODE_IS_STRICT_REAL_REPEAT(node)) {
QuantNode* qn = QUANT_(NODE_BAG_BODY(node));
r = compile_tree_n_times(NODE_QUANT_BODY(qn), qn->lower, reg, env);
if (r != 0) return r;
len = compile_length_tree(NODE_QUANT_BODY(qn), reg);
if (len < 0) return len;
r = add_op(reg, OP_PUSH);
if (r != 0) return r;
COP(reg)->push.addr = SIZE_INC + len + OPSIZE_POP + OPSIZE_JUMP;
r = compile_tree(NODE_QUANT_BODY(qn), reg, env);
if (r != 0) return r;
r = add_op(reg, OP_POP);
if (r != 0) return r;
r = add_op(reg, OP_JUMP);
if (r != 0) return r;
COP(reg)->jump.addr = -((int )OPSIZE_PUSH + len + (int )OPSIZE_POP);
}
else {
MemNumType mid;
ID_ENTRY(env, mid);
r = add_op(reg, OP_MARK);
if (r != 0) return r;
COP(reg)->mark.id = mid;
COP(reg)->mark.save_pos = 0;
r = compile_tree(NODE_BAG_BODY(node), reg, env);
if (r != 0) return r;
r = add_op(reg, OP_CUT_TO_MARK);
if (r != 0) return r;
COP(reg)->cut_to_mark.id = mid;
COP(reg)->cut_to_mark.restore_pos = 0;
}
break;
case BAG_IF_ELSE:
{
int cond_len, then_len, else_len, jump_len;
MemNumType mid;
Node* cond = NODE_BAG_BODY(node);
Node* Then = node->te.Then;
Node* Else = node->te.Else;
ID_ENTRY(env, mid);
r = add_op(reg, OP_MARK);
if (r != 0) return r;
COP(reg)->mark.id = mid;
COP(reg)->mark.save_pos = 0;
cond_len = compile_length_tree(cond, reg);
if (cond_len < 0) return cond_len;
if (IS_NOT_NULL(Then)) {
then_len = compile_length_tree(Then, reg);
if (then_len < 0) return then_len;
}
else
then_len = 0;
jump_len = cond_len + then_len + OPSIZE_CUT_TO_MARK + OPSIZE_JUMP;
r = add_op(reg, OP_PUSH);
if (r != 0) return r;
COP(reg)->push.addr = SIZE_INC + jump_len;
r = compile_tree(cond, reg, env);
if (r != 0) return r;
r = add_op(reg, OP_CUT_TO_MARK);
if (r != 0) return r;
COP(reg)->cut_to_mark.id = mid;
COP(reg)->cut_to_mark.restore_pos = 0;
if (IS_NOT_NULL(Then)) {
r = compile_tree(Then, reg, env);
if (r != 0) return r;
}
if (IS_NOT_NULL(Else)) {
else_len = compile_length_tree(Else, reg);
if (else_len < 0) return else_len;
}
else
else_len = 0;
r = add_op(reg, OP_JUMP);
if (r != 0) return r;
COP(reg)->jump.addr = OPSIZE_CUT_TO_MARK + else_len + SIZE_INC;
r = add_op(reg, OP_CUT_TO_MARK);
if (r != 0) return r;
COP(reg)->cut_to_mark.id = mid;
COP(reg)->cut_to_mark.restore_pos = 0;
if (IS_NOT_NULL(Else)) {
r = compile_tree(Else, reg, env);
}
}
break;
}
return r;
}
static int
compile_length_anchor_node(AnchorNode* node, regex_t* reg)
{
int len;
int tlen = 0;
if (IS_NOT_NULL(NODE_ANCHOR_BODY(node))) {
tlen = compile_length_tree(NODE_ANCHOR_BODY(node), reg);
if (tlen < 0) return tlen;
}
switch (node->type) {
case ANCR_PREC_READ:
len = OPSIZE_MARK + tlen + OPSIZE_CUT_TO_MARK;
break;
case ANCR_PREC_READ_NOT:
len = OPSIZE_PUSH + OPSIZE_MARK + tlen + OPSIZE_POP_TO_MARK + OPSIZE_POP + OPSIZE_FAIL;
break;
case ANCR_LOOK_BEHIND:
if (node->char_min_len == node->char_max_len)
len = OPSIZE_MARK + OPSIZE_STEP_BACK_START + tlen + OPSIZE_CUT_TO_MARK;
else {
len = OPSIZE_SAVE_VAL + OPSIZE_UPDATE_VAR + OPSIZE_MARK + OPSIZE_PUSH + OPSIZE_UPDATE_VAR + OPSIZE_FAIL + OPSIZE_JUMP + OPSIZE_STEP_BACK_START + OPSIZE_STEP_BACK_NEXT + tlen + OPSIZE_CHECK_POSITION + OPSIZE_CUT_TO_MARK + OPSIZE_UPDATE_VAR;
if (IS_NOT_NULL(node->lead_node)) {
int llen = compile_length_tree(node->lead_node, reg);
if (llen < 0) return llen;
len += OPSIZE_MOVE + llen;
}
}
break;
case ANCR_LOOK_BEHIND_NOT:
if (node->char_min_len == node->char_max_len)
len = OPSIZE_MARK + OPSIZE_PUSH + OPSIZE_STEP_BACK_START + tlen + OPSIZE_POP_TO_MARK + OPSIZE_FAIL + OPSIZE_POP;
else {
len = OPSIZE_SAVE_VAL + OPSIZE_UPDATE_VAR + OPSIZE_MARK + OPSIZE_PUSH + OPSIZE_STEP_BACK_START + OPSIZE_STEP_BACK_NEXT + tlen + OPSIZE_CHECK_POSITION + OPSIZE_POP_TO_MARK + OPSIZE_UPDATE_VAR + OPSIZE_POP + OPSIZE_FAIL + OPSIZE_UPDATE_VAR + OPSIZE_POP + OPSIZE_POP;
if (IS_NOT_NULL(node->lead_node)) {
int llen = compile_length_tree(node->lead_node, reg);
if (llen < 0) return llen;
len += OPSIZE_MOVE + llen;
}
}
break;
case ANCR_WORD_BOUNDARY:
case ANCR_NO_WORD_BOUNDARY:
#ifdef USE_WORD_BEGIN_END
case ANCR_WORD_BEGIN:
case ANCR_WORD_END:
#endif
len = OPSIZE_WORD_BOUNDARY;
break;
case ANCR_TEXT_SEGMENT_BOUNDARY:
case ANCR_NO_TEXT_SEGMENT_BOUNDARY:
len = SIZE_OPCODE;
break;
default:
len = SIZE_OPCODE;
break;
}
return len;
}
static int
compile_anchor_look_behind_node(AnchorNode* node, regex_t* reg, ScanEnv* env)
{
int r;
if (node->char_min_len == node->char_max_len) {
MemNumType mid;
ID_ENTRY(env, mid);
r = add_op(reg, OP_MARK);
if (r != 0) return r;
COP(reg)->mark.id = mid;
COP(reg)->mark.save_pos = FALSE;
r = add_op(reg, OP_STEP_BACK_START);
if (r != 0) return r;
COP(reg)->step_back_start.initial = node->char_min_len;
COP(reg)->step_back_start.remaining = 0;
COP(reg)->step_back_start.addr = 1;
r = compile_tree(NODE_ANCHOR_BODY(node), reg, env);
if (r != 0) return r;
r = add_op(reg, OP_CUT_TO_MARK);
if (r != 0) return r;
COP(reg)->cut_to_mark.id = mid;
COP(reg)->cut_to_mark.restore_pos = FALSE;
}
else {
MemNumType mid1, mid2;
OnigLen diff;
if (IS_NOT_NULL(node->lead_node)) {
MinMaxCharLen ci;
r = node_char_len(node->lead_node, reg, &ci, env);
if (r < 0) return r;
r = add_op(reg, OP_MOVE);
if (r != 0) return r;
COP(reg)->move.n = -((RelPositionType )ci.min);
r = compile_tree(node->lead_node, reg, env);
if (r != 0) return r;
}
ID_ENTRY(env, mid1);
r = add_op(reg, OP_SAVE_VAL);
if (r != 0) return r;
COP(reg)->save_val.type = SAVE_RIGHT_RANGE;
COP(reg)->save_val.id = mid1;
r = add_op(reg, OP_UPDATE_VAR);
if (r != 0) return r;
COP(reg)->update_var.type = UPDATE_VAR_RIGHT_RANGE_TO_S;
ID_ENTRY(env, mid2);
r = add_op(reg, OP_MARK);
if (r != 0) return r;
COP(reg)->mark.id = mid2;
COP(reg)->mark.save_pos = FALSE;
r = add_op(reg, OP_PUSH);
if (r != 0) return r;
COP(reg)->push.addr = SIZE_INC + OPSIZE_JUMP;
r = add_op(reg, OP_JUMP);
if (r != 0) return r;
COP(reg)->jump.addr = SIZE_INC + OPSIZE_UPDATE_VAR + OPSIZE_FAIL;
r = add_op(reg, OP_UPDATE_VAR);
if (r != 0) return r;
COP(reg)->update_var.type = UPDATE_VAR_RIGHT_RANGE_FROM_STACK;
COP(reg)->update_var.id = mid1;
COP(reg)->update_var.clear = FALSE;
r = add_op(reg, OP_FAIL);
if (r != 0) return r;
r = add_op(reg, OP_STEP_BACK_START);
if (r != 0) return r;
if (node->char_max_len != INFINITE_LEN)
diff = node->char_max_len - node->char_min_len;
else
diff = INFINITE_LEN;
COP(reg)->step_back_start.initial = node->char_min_len;
COP(reg)->step_back_start.remaining = diff;
COP(reg)->step_back_start.addr = 2;
r = add_op(reg, OP_STEP_BACK_NEXT);
if (r != 0) return r;
r = compile_tree(NODE_ANCHOR_BODY(node), reg, env);
if (r != 0) return r;
r = add_op(reg, OP_CHECK_POSITION);
if (r != 0) return r;
COP(reg)->check_position.type = CHECK_POSITION_CURRENT_RIGHT_RANGE;
r = add_op(reg, OP_CUT_TO_MARK);
if (r != 0) return r;
COP(reg)->cut_to_mark.id = mid2;
COP(reg)->cut_to_mark.restore_pos = FALSE;
r = add_op(reg, OP_UPDATE_VAR);
if (r != 0) return r;
COP(reg)->update_var.type = UPDATE_VAR_RIGHT_RANGE_FROM_STACK;
COP(reg)->update_var.id = mid1;
COP(reg)->update_var.clear = TRUE;
}
return r;
}
static int
compile_anchor_look_behind_not_node(AnchorNode* node, regex_t* reg,
ScanEnv* env)
{
int r;
int len;
len = compile_length_tree(NODE_ANCHOR_BODY(node), reg);
if (node->char_min_len == node->char_max_len) {
MemNumType mid;
ID_ENTRY(env, mid);
r = add_op(reg, OP_MARK);
if (r != 0) return r;
COP(reg)->mark.id = mid;
COP(reg)->mark.save_pos = FALSE;
r = add_op(reg, OP_PUSH);
if (r != 0) return r;
COP(reg)->push.addr = SIZE_INC + OPSIZE_STEP_BACK_START + len + OPSIZE_POP_TO_MARK + OPSIZE_FAIL;
r = add_op(reg, OP_STEP_BACK_START);
if (r != 0) return r;
COP(reg)->step_back_start.initial = node->char_min_len;
COP(reg)->step_back_start.remaining = 0;
COP(reg)->step_back_start.addr = 1;
r = compile_tree(NODE_ANCHOR_BODY(node), reg, env);
if (r != 0) return r;
r = add_op(reg, OP_POP_TO_MARK);
if (r != 0) return r;
COP(reg)->pop_to_mark.id = mid;
r = add_op(reg, OP_FAIL);
if (r != 0) return r;
r = add_op(reg, OP_POP);
}
else {
MemNumType mid1, mid2;
OnigLen diff;
ID_ENTRY(env, mid1);
r = add_op(reg, OP_SAVE_VAL);
if (r != 0) return r;
COP(reg)->save_val.type = SAVE_RIGHT_RANGE;
COP(reg)->save_val.id = mid1;
r = add_op(reg, OP_UPDATE_VAR);
if (r != 0) return r;
COP(reg)->update_var.type = UPDATE_VAR_RIGHT_RANGE_TO_S;
ID_ENTRY(env, mid2);
r = add_op(reg, OP_MARK);
if (r != 0) return r;
COP(reg)->mark.id = mid2;
COP(reg)->mark.save_pos = FALSE;
r = add_op(reg, OP_PUSH);
if (r != 0) return r;
COP(reg)->push.addr = SIZE_INC + OPSIZE_STEP_BACK_START + OPSIZE_STEP_BACK_NEXT + len + OPSIZE_CHECK_POSITION + OPSIZE_POP_TO_MARK + OPSIZE_UPDATE_VAR + OPSIZE_POP + OPSIZE_FAIL;
if (IS_NOT_NULL(node->lead_node)) {
int clen;
MinMaxCharLen ci;
clen = compile_length_tree(node->lead_node, reg);
COP(reg)->push.addr += OPSIZE_MOVE + clen;
r = node_char_len(node->lead_node, reg, &ci, env);
if (r < 0) return r;
r = add_op(reg, OP_MOVE);
if (r != 0) return r;
COP(reg)->move.n = -((RelPositionType )ci.min);
r = compile_tree(node->lead_node, reg, env);
if (r != 0) return r;
}
r = add_op(reg, OP_STEP_BACK_START);
if (r != 0) return r;
if (node->char_max_len != INFINITE_LEN)
diff = node->char_max_len - node->char_min_len;
else
diff = INFINITE_LEN;
COP(reg)->step_back_start.initial = node->char_min_len;
COP(reg)->step_back_start.remaining = diff;
COP(reg)->step_back_start.addr = 2;
r = add_op(reg, OP_STEP_BACK_NEXT);
if (r != 0) return r;
r = compile_tree(NODE_ANCHOR_BODY(node), reg, env);
if (r != 0) return r;
r = add_op(reg, OP_CHECK_POSITION);
if (r != 0) return r;
COP(reg)->check_position.type = CHECK_POSITION_CURRENT_RIGHT_RANGE;
r = add_op(reg, OP_POP_TO_MARK);
if (r != 0) return r;
COP(reg)->pop_to_mark.id = mid2;
r = add_op(reg, OP_UPDATE_VAR);
if (r != 0) return r;
COP(reg)->update_var.type = UPDATE_VAR_RIGHT_RANGE_FROM_STACK;
COP(reg)->update_var.id = mid1;
COP(reg)->update_var.clear = FALSE;
r = add_op(reg, OP_POP); /* pop save val */
if (r != 0) return r;
r = add_op(reg, OP_FAIL);
if (r != 0) return r;
r = add_op(reg, OP_UPDATE_VAR);
if (r != 0) return r;
COP(reg)->update_var.type = UPDATE_VAR_RIGHT_RANGE_FROM_STACK;
COP(reg)->update_var.id = mid1;
COP(reg)->update_var.clear = FALSE;
r = add_op(reg, OP_POP); /* pop mark */
if (r != 0) return r;
r = add_op(reg, OP_POP); /* pop save val */
}
return r;
}
static int
compile_anchor_node(AnchorNode* node, regex_t* reg, ScanEnv* env)
{
int r, len;
enum OpCode op;
MemNumType mid;
switch (node->type) {
case ANCR_BEGIN_BUF: r = add_op(reg, OP_BEGIN_BUF); break;
case ANCR_END_BUF: r = add_op(reg, OP_END_BUF); break;
case ANCR_BEGIN_LINE: r = add_op(reg, OP_BEGIN_LINE); break;
case ANCR_END_LINE: r = add_op(reg, OP_END_LINE); break;
case ANCR_SEMI_END_BUF: r = add_op(reg, OP_SEMI_END_BUF); break;
case ANCR_BEGIN_POSITION:
r = add_op(reg, OP_CHECK_POSITION);
if (r != 0) return r;
COP(reg)->check_position.type = CHECK_POSITION_SEARCH_START;
break;
case ANCR_WORD_BOUNDARY:
op = OP_WORD_BOUNDARY;
word:
r = add_op(reg, op);
if (r != 0) return r;
COP(reg)->word_boundary.mode = (ModeType )node->ascii_mode;
break;
case ANCR_NO_WORD_BOUNDARY:
op = OP_NO_WORD_BOUNDARY; goto word;
break;
#ifdef USE_WORD_BEGIN_END
case ANCR_WORD_BEGIN:
op = OP_WORD_BEGIN; goto word;
break;
case ANCR_WORD_END:
op = OP_WORD_END; goto word;
break;
#endif
case ANCR_TEXT_SEGMENT_BOUNDARY:
case ANCR_NO_TEXT_SEGMENT_BOUNDARY:
{
enum TextSegmentBoundaryType type;
r = add_op(reg, OP_TEXT_SEGMENT_BOUNDARY);
if (r != 0) return r;
type = EXTENDED_GRAPHEME_CLUSTER_BOUNDARY;
#ifdef USE_UNICODE_WORD_BREAK
if (NODE_IS_TEXT_SEGMENT_WORD(node))
type = WORD_BOUNDARY;
#endif
COP(reg)->text_segment_boundary.type = type;
COP(reg)->text_segment_boundary.not =
(node->type == ANCR_NO_TEXT_SEGMENT_BOUNDARY ? 1 : 0);
}
break;
case ANCR_PREC_READ:
{
ID_ENTRY(env, mid);
r = add_op(reg, OP_MARK);
if (r != 0) return r;
COP(reg)->mark.id = mid;
COP(reg)->mark.save_pos = TRUE;
r = compile_tree(NODE_ANCHOR_BODY(node), reg, env);
if (r != 0) return r;
r = add_op(reg, OP_CUT_TO_MARK);
if (r != 0) return r;
COP(reg)->cut_to_mark.id = mid;
COP(reg)->cut_to_mark.restore_pos = TRUE;
}
break;
case ANCR_PREC_READ_NOT:
{
len = compile_length_tree(NODE_ANCHOR_BODY(node), reg);
if (len < 0) return len;
ID_ENTRY(env, mid);
r = add_op(reg, OP_PUSH);
if (r != 0) return r;
COP(reg)->push.addr = SIZE_INC + OPSIZE_MARK + len +
OPSIZE_POP_TO_MARK + OPSIZE_POP + OPSIZE_FAIL;
r = add_op(reg, OP_MARK);
if (r != 0) return r;
COP(reg)->mark.id = mid;
COP(reg)->mark.save_pos = FALSE;
r = compile_tree(NODE_ANCHOR_BODY(node), reg, env);
if (r != 0) return r;
r = add_op(reg, OP_POP_TO_MARK);
if (r != 0) return r;
COP(reg)->pop_to_mark.id = mid;
r = add_op(reg, OP_POP);
if (r != 0) return r;
r = add_op(reg, OP_FAIL);
}
break;
case ANCR_LOOK_BEHIND:
r = compile_anchor_look_behind_node(node, reg, env);
break;
case ANCR_LOOK_BEHIND_NOT:
r = compile_anchor_look_behind_not_node(node, reg, env);
break;
default:
return ONIGERR_TYPE_BUG;
break;
}
return r;
}
static int
compile_gimmick_node(GimmickNode* node, regex_t* reg)
{
int r = 0;
switch (node->type) {
case GIMMICK_FAIL:
r = add_op(reg, OP_FAIL);
break;
case GIMMICK_SAVE:
r = add_op(reg, OP_SAVE_VAL);
if (r != 0) return r;
COP(reg)->save_val.type = node->detail_type;
COP(reg)->save_val.id = node->id;
break;
case GIMMICK_UPDATE_VAR:
r = add_op(reg, OP_UPDATE_VAR);
if (r != 0) return r;
COP(reg)->update_var.type = node->detail_type;
COP(reg)->update_var.id = node->id;
COP(reg)->update_var.clear = FALSE;
break;
#ifdef USE_CALLOUT
case GIMMICK_CALLOUT:
switch (node->detail_type) {
case ONIG_CALLOUT_OF_CONTENTS:
case ONIG_CALLOUT_OF_NAME:
{
if (node->detail_type == ONIG_CALLOUT_OF_NAME) {
r = add_op(reg, OP_CALLOUT_NAME);
if (r != 0) return r;
COP(reg)->callout_name.id = node->id;
COP(reg)->callout_name.num = node->num;
}
else {
r = add_op(reg, OP_CALLOUT_CONTENTS);
if (r != 0) return r;
COP(reg)->callout_contents.num = node->num;
}
}
break;
default:
r = ONIGERR_TYPE_BUG;
break;
}
#endif
}
return r;
}
static int
compile_length_gimmick_node(GimmickNode* node, regex_t* reg)
{
int len;
switch (node->type) {
case GIMMICK_FAIL:
len = OPSIZE_FAIL;
break;
case GIMMICK_SAVE:
len = OPSIZE_SAVE_VAL;
break;
case GIMMICK_UPDATE_VAR:
len = OPSIZE_UPDATE_VAR;
break;
#ifdef USE_CALLOUT
case GIMMICK_CALLOUT:
switch (node->detail_type) {
case ONIG_CALLOUT_OF_CONTENTS:
len = OPSIZE_CALLOUT_CONTENTS;
break;
case ONIG_CALLOUT_OF_NAME:
len = OPSIZE_CALLOUT_NAME;
break;
default:
len = ONIGERR_TYPE_BUG;
break;
}
break;
#endif
}
return len;
}
static int
compile_length_tree(Node* node, regex_t* reg)
{
int len, r;
switch (NODE_TYPE(node)) {
case NODE_LIST:
len = 0;
do {
r = compile_length_tree(NODE_CAR(node), reg);
if (r < 0) return r;
len += r;
} while (IS_NOT_NULL(node = NODE_CDR(node)));
r = len;
break;
case NODE_ALT:
{
int n;
n = r = 0;
do {
r += compile_length_tree(NODE_CAR(node), reg);
n++;
} while (IS_NOT_NULL(node = NODE_CDR(node)));
r += (OPSIZE_PUSH + OPSIZE_JUMP) * (n - 1);
}
break;
case NODE_STRING:
if (NODE_STRING_IS_CRUDE(node))
r = compile_length_string_crude_node(STR_(node), reg);
else
r = compile_length_string_node(node, reg);
break;
case NODE_CCLASS:
r = compile_length_cclass_node(CCLASS_(node), reg);
break;
case NODE_CTYPE:
r = SIZE_OPCODE;
break;
case NODE_BACKREF:
r = OPSIZE_BACKREF;
break;
#ifdef USE_CALL
case NODE_CALL:
r = OPSIZE_CALL;
break;
#endif
case NODE_QUANT:
r = compile_length_quantifier_node(QUANT_(node), reg);
break;
case NODE_BAG:
r = compile_length_bag_node(BAG_(node), reg);
break;
case NODE_ANCHOR:
r = compile_length_anchor_node(ANCHOR_(node), reg);
break;
case NODE_GIMMICK:
r = compile_length_gimmick_node(GIMMICK_(node), reg);
break;
default:
return ONIGERR_TYPE_BUG;
break;
}
return r;
}
static int
compile_tree(Node* node, regex_t* reg, ScanEnv* env)
{
int n, len, pos, r = 0;
switch (NODE_TYPE(node)) {
case NODE_LIST:
do {
r = compile_tree(NODE_CAR(node), reg, env);
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_ALT:
{
Node* x = node;
len = 0;
do {
len += compile_length_tree(NODE_CAR(x), reg);
if (IS_NOT_NULL(NODE_CDR(x))) {
len += OPSIZE_PUSH + OPSIZE_JUMP;
}
} while (IS_NOT_NULL(x = NODE_CDR(x)));
pos = COP_CURR_OFFSET(reg) + 1 + len; /* goal position */
do {
len = compile_length_tree(NODE_CAR(node), reg);
if (IS_NOT_NULL(NODE_CDR(node))) {
enum OpCode push = NODE_IS_SUPER(node) ? OP_PUSH_SUPER : OP_PUSH;
r = add_op(reg, push);
if (r != 0) break;
COP(reg)->push.addr = SIZE_INC + len + OPSIZE_JUMP;
}
r = compile_tree(NODE_CAR(node), reg, env);
if (r != 0) break;
if (IS_NOT_NULL(NODE_CDR(node))) {
len = pos - (COP_CURR_OFFSET(reg) + 1);
r = add_op(reg, OP_JUMP);
if (r != 0) break;
COP(reg)->jump.addr = len;
}
} while (IS_NOT_NULL(node = NODE_CDR(node)));
}
break;
case NODE_STRING:
if (NODE_STRING_IS_CRUDE(node))
r = compile_string_crude_node(STR_(node), reg);
else
r = compile_string_node(node, reg);
break;
case NODE_CCLASS:
r = compile_cclass_node(CCLASS_(node), reg);
break;
case NODE_CTYPE:
{
int op;
switch (CTYPE_(node)->ctype) {
case CTYPE_ANYCHAR:
r = add_op(reg, NODE_IS_MULTILINE(node) ? OP_ANYCHAR_ML : OP_ANYCHAR);
break;
case ONIGENC_CTYPE_WORD:
if (CTYPE_(node)->ascii_mode == 0) {
op = CTYPE_(node)->not != 0 ? OP_NO_WORD : OP_WORD;
}
else {
op = CTYPE_(node)->not != 0 ? OP_NO_WORD_ASCII : OP_WORD_ASCII;
}
r = add_op(reg, op);
break;
default:
return ONIGERR_TYPE_BUG;
break;
}
}
break;
case NODE_BACKREF:
{
BackRefNode* br = BACKREF_(node);
if (NODE_IS_CHECKER(node)) {
#ifdef USE_BACKREF_WITH_LEVEL
if (NODE_IS_NEST_LEVEL(node)) {
r = add_op(reg, OP_BACKREF_CHECK_WITH_LEVEL);
if (r != 0) return r;
COP(reg)->backref_general.nest_level = br->nest_level;
}
else
#endif
{
r = add_op(reg, OP_BACKREF_CHECK);
if (r != 0) return r;
}
goto add_bacref_mems;
}
else {
#ifdef USE_BACKREF_WITH_LEVEL
if (NODE_IS_NEST_LEVEL(node)) {
if (NODE_IS_IGNORECASE(node))
r = add_op(reg, OP_BACKREF_WITH_LEVEL_IC);
else
r = add_op(reg, OP_BACKREF_WITH_LEVEL);
if (r != 0) return r;
COP(reg)->backref_general.nest_level = br->nest_level;
goto add_bacref_mems;
}
else
#endif
if (br->back_num == 1) {
n = br->back_static[0];
if (NODE_IS_IGNORECASE(node)) {
r = add_op(reg, OP_BACKREF_N_IC);
if (r != 0) return r;
COP(reg)->backref_n.n1 = n;
}
else {
switch (n) {
case 1: r = add_op(reg, OP_BACKREF1); break;
case 2: r = add_op(reg, OP_BACKREF2); break;
default:
r = add_op(reg, OP_BACKREF_N);
if (r != 0) return r;
COP(reg)->backref_n.n1 = n;
break;
}
}
}
else {
int num;
int* p;
r = add_op(reg, NODE_IS_IGNORECASE(node) ?
OP_BACKREF_MULTI_IC : OP_BACKREF_MULTI);
if (r != 0) return r;
add_bacref_mems:
num = br->back_num;
COP(reg)->backref_general.num = num;
if (num == 1) {
COP(reg)->backref_general.n1 = br->back_static[0];
}
else {
int i, j;
MemNumType* ns;
ns = xmalloc(sizeof(MemNumType) * num);
CHECK_NULL_RETURN_MEMERR(ns);
COP(reg)->backref_general.ns = ns;
p = BACKREFS_P(br);
for (i = num - 1, j = 0; i >= 0; i--, j++) {
ns[j] = p[i];
}
}
}
}
}
break;
#ifdef USE_CALL
case NODE_CALL:
r = compile_call(CALL_(node), reg, env);
break;
#endif
case NODE_QUANT:
r = compile_quantifier_node(QUANT_(node), reg, env);
break;
case NODE_BAG:
r = compile_bag_node(BAG_(node), reg, env);
break;
case NODE_ANCHOR:
r = compile_anchor_node(ANCHOR_(node), reg, env);
break;
case NODE_GIMMICK:
r = compile_gimmick_node(GIMMICK_(node), reg);
break;
default:
#ifdef ONIG_DEBUG
fprintf(DBGFP, "compile_tree: undefined node type %d\n", NODE_TYPE(node));
#endif
break;
}
return r;
}
static int
make_named_capture_number_map(Node** plink, GroupNumMap* map, int* counter)
{
int r = 0;
Node* node = *plink;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
do {
r = make_named_capture_number_map(&(NODE_CAR(node)), map, counter);
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_QUANT:
{
Node** ptarget = &(NODE_BODY(node));
Node* old = *ptarget;
r = make_named_capture_number_map(ptarget, map, counter);
if (r != 0) return r;
if (*ptarget != old && NODE_TYPE(*ptarget) == NODE_QUANT) {
r = onig_reduce_nested_quantifier(node);
}
}
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
if (en->type == BAG_MEMORY) {
if (NODE_IS_NAMED_GROUP(node)) {
(*counter)++;
map[en->m.regnum].new_val = *counter;
en->m.regnum = *counter;
r = make_named_capture_number_map(&(NODE_BODY(node)), map, counter);
}
else {
*plink = NODE_BODY(node);
NODE_BODY(node) = NULL_NODE;
onig_node_free(node);
r = make_named_capture_number_map(plink, map, counter);
}
}
else if (en->type == BAG_IF_ELSE) {
r = make_named_capture_number_map(&(NODE_BAG_BODY(en)), map, counter);
if (r != 0) return r;
if (IS_NOT_NULL(en->te.Then)) {
r = make_named_capture_number_map(&(en->te.Then), map, counter);
if (r != 0) return r;
}
if (IS_NOT_NULL(en->te.Else)) {
r = make_named_capture_number_map(&(en->te.Else), map, counter);
if (r != 0) return r;
}
}
else
r = make_named_capture_number_map(&(NODE_BODY(node)), map, counter);
}
break;
case NODE_ANCHOR:
if (IS_NOT_NULL(NODE_BODY(node)))
r = make_named_capture_number_map(&(NODE_BODY(node)), map, counter);
break;
default:
break;
}
return r;
}
static int
renumber_backref_node(Node* node, GroupNumMap* map)
{
int i, pos, n, old_num;
int *backs;
BackRefNode* bn = BACKREF_(node);
if (! NODE_IS_BY_NAME(node))
return ONIGERR_NUMBERED_BACKREF_OR_CALL_NOT_ALLOWED;
old_num = bn->back_num;
if (IS_NULL(bn->back_dynamic))
backs = bn->back_static;
else
backs = bn->back_dynamic;
for (i = 0, pos = 0; i < old_num; i++) {
n = map[backs[i]].new_val;
if (n > 0) {
backs[pos] = n;
pos++;
}
}
bn->back_num = pos;
return 0;
}
static int
renumber_backref_traverse(Node* node, GroupNumMap* map)
{
int r = 0;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
do {
r = renumber_backref_traverse(NODE_CAR(node), map);
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_QUANT:
r = renumber_backref_traverse(NODE_BODY(node), map);
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
r = renumber_backref_traverse(NODE_BODY(node), map);
if (r != 0) return r;
if (en->type == BAG_IF_ELSE) {
if (IS_NOT_NULL(en->te.Then)) {
r = renumber_backref_traverse(en->te.Then, map);
if (r != 0) return r;
}
if (IS_NOT_NULL(en->te.Else)) {
r = renumber_backref_traverse(en->te.Else, map);
if (r != 0) return r;
}
}
}
break;
case NODE_BACKREF:
r = renumber_backref_node(node, map);
break;
case NODE_ANCHOR:
if (IS_NOT_NULL(NODE_BODY(node)))
r = renumber_backref_traverse(NODE_BODY(node), map);
break;
default:
break;
}
return r;
}
static int
numbered_ref_check(Node* node)
{
int r = 0;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
do {
r = numbered_ref_check(NODE_CAR(node));
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_ANCHOR:
if (IS_NULL(NODE_BODY(node)))
break;
/* fall */
case NODE_QUANT:
r = numbered_ref_check(NODE_BODY(node));
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
r = numbered_ref_check(NODE_BODY(node));
if (r != 0) return r;
if (en->type == BAG_IF_ELSE) {
if (IS_NOT_NULL(en->te.Then)) {
r = numbered_ref_check(en->te.Then);
if (r != 0) return r;
}
if (IS_NOT_NULL(en->te.Else)) {
r = numbered_ref_check(en->te.Else);
if (r != 0) return r;
}
}
}
break;
case NODE_BACKREF:
if (! NODE_IS_BY_NAME(node))
return ONIGERR_NUMBERED_BACKREF_OR_CALL_NOT_ALLOWED;
break;
default:
break;
}
return r;
}
static int
disable_noname_group_capture(Node** root, regex_t* reg, ScanEnv* env)
{
int r, i, pos, counter;
MemStatusType loc;
GroupNumMap* map;
map = (GroupNumMap* )xalloca(sizeof(GroupNumMap) * (env->num_mem + 1));
CHECK_NULL_RETURN_MEMERR(map);
for (i = 1; i <= env->num_mem; i++) {
map[i].new_val = 0;
}
counter = 0;
r = make_named_capture_number_map(root, map, &counter);
if (r != 0) return r;
r = renumber_backref_traverse(*root, map);
if (r != 0) return r;
for (i = 1, pos = 1; i <= env->num_mem; i++) {
if (map[i].new_val > 0) {
SCANENV_MEMENV(env)[pos] = SCANENV_MEMENV(env)[i];
pos++;
}
}
loc = env->cap_history;
MEM_STATUS_CLEAR(env->cap_history);
for (i = 1; i <= ONIG_MAX_CAPTURE_HISTORY_GROUP; i++) {
if (MEM_STATUS_AT(loc, i)) {
MEM_STATUS_ON_SIMPLE(env->cap_history, map[i].new_val);
}
}
env->num_mem = env->num_named;
reg->num_mem = env->num_named;
return onig_renumber_name_table(reg, map);
}
#ifdef USE_CALL
static int
fix_unset_addr_list(UnsetAddrList* uslist, regex_t* reg)
{
int i, offset;
BagNode* en;
AbsAddrType addr;
AbsAddrType* paddr;
for (i = 0; i < uslist->num; i++) {
if (! NODE_IS_FIXED_ADDR(uslist->us[i].target)) {
if (NODE_IS_CALLED(uslist->us[i].target))
return ONIGERR_PARSER_BUG;
else {
/* CASE: called node doesn't have called address.
ex. /((|a\g<1>)(.){0}){0}\g<3>/
group-1 doesn't called, but compiled into bytecodes,
because group-3 is referred from outside.
*/
continue;
}
}
en = BAG_(uslist->us[i].target);
addr = en->m.called_addr;
offset = uslist->us[i].offset;
paddr = (AbsAddrType* )((char* )reg->ops + offset);
*paddr = addr;
}
return 0;
}
#endif
/* x is not included y ==> 1 : 0 */
static int
is_exclusive(Node* x, Node* y, regex_t* reg)
{
int i, len;
OnigCodePoint code;
UChar *p;
NodeType ytype;
retry:
ytype = NODE_TYPE(y);
switch (NODE_TYPE(x)) {
case NODE_CTYPE:
{
if (CTYPE_(x)->ctype == CTYPE_ANYCHAR ||
CTYPE_(y)->ctype == CTYPE_ANYCHAR)
break;
switch (ytype) {
case NODE_CTYPE:
if (CTYPE_(y)->ctype == CTYPE_(x)->ctype &&
CTYPE_(y)->not != CTYPE_(x)->not &&
CTYPE_(y)->ascii_mode == CTYPE_(x)->ascii_mode)
return 1;
else
return 0;
break;
case NODE_CCLASS:
swap:
{
Node* tmp;
tmp = x; x = y; y = tmp;
goto retry;
}
break;
case NODE_STRING:
goto swap;
break;
default:
break;
}
}
break;
case NODE_CCLASS:
{
int range;
CClassNode* xc = CCLASS_(x);
switch (ytype) {
case NODE_CTYPE:
switch (CTYPE_(y)->ctype) {
case CTYPE_ANYCHAR:
return 0;
break;
case ONIGENC_CTYPE_WORD:
if (CTYPE_(y)->not == 0) {
if (IS_NULL(xc->mbuf) && !IS_NCCLASS_NOT(xc)) {
range = CTYPE_(y)->ascii_mode != 0 ? 128 : SINGLE_BYTE_SIZE;
for (i = 0; i < range; i++) {
if (BITSET_AT(xc->bs, i)) {
if (ONIGENC_IS_CODE_WORD(reg->enc, i)) return 0;
}
}
return 1;
}
return 0;
}
else {
if (IS_NOT_NULL(xc->mbuf)) return 0;
if (IS_NCCLASS_NOT(xc)) return 0;
range = CTYPE_(y)->ascii_mode != 0 ? 128 : SINGLE_BYTE_SIZE;
for (i = 0; i < range; i++) {
if (! ONIGENC_IS_CODE_WORD(reg->enc, i)) {
if (BITSET_AT(xc->bs, i))
return 0;
}
}
for (i = range; i < SINGLE_BYTE_SIZE; i++) {
if (BITSET_AT(xc->bs, i)) return 0;
}
return 1;
}
break;
default:
break;
}
break;
case NODE_CCLASS:
{
int v;
CClassNode* yc = CCLASS_(y);
for (i = 0; i < SINGLE_BYTE_SIZE; i++) {
v = BITSET_AT(xc->bs, i);
if ((v != 0 && !IS_NCCLASS_NOT(xc)) || (v == 0 && IS_NCCLASS_NOT(xc))) {
v = BITSET_AT(yc->bs, i);
if ((v != 0 && !IS_NCCLASS_NOT(yc)) ||
(v == 0 && IS_NCCLASS_NOT(yc)))
return 0;
}
}
if ((IS_NULL(xc->mbuf) && !IS_NCCLASS_NOT(xc)) ||
(IS_NULL(yc->mbuf) && !IS_NCCLASS_NOT(yc)))
return 1;
return 0;
}
break;
case NODE_STRING:
goto swap;
break;
default:
break;
}
}
break;
case NODE_STRING:
{
StrNode* xs = STR_(x);
if (NODE_STRING_LEN(x) == 0)
break;
switch (ytype) {
case NODE_CTYPE:
switch (CTYPE_(y)->ctype) {
case CTYPE_ANYCHAR:
break;
case ONIGENC_CTYPE_WORD:
if (CTYPE_(y)->ascii_mode == 0) {
if (ONIGENC_IS_MBC_WORD(reg->enc, xs->s, xs->end))
return CTYPE_(y)->not;
else
return !(CTYPE_(y)->not);
}
else {
if (ONIGENC_IS_MBC_WORD_ASCII(reg->enc, xs->s, xs->end))
return CTYPE_(y)->not;
else
return !(CTYPE_(y)->not);
}
break;
default:
break;
}
break;
case NODE_CCLASS:
{
CClassNode* cc = CCLASS_(y);
code = ONIGENC_MBC_TO_CODE(reg->enc, xs->s,
xs->s + ONIGENC_MBC_MAXLEN(reg->enc));
return onig_is_code_in_cc(reg->enc, code, cc) == 0;
}
break;
case NODE_STRING:
{
UChar *q;
StrNode* ys = STR_(y);
len = NODE_STRING_LEN(x);
if (len > NODE_STRING_LEN(y)) len = NODE_STRING_LEN(y);
for (i = 0, p = ys->s, q = xs->s; i < len; i++, p++, q++) {
if (*p != *q) return 1;
}
}
break;
default:
break;
}
}
break;
default:
break;
}
return 0;
}
static Node*
get_tree_head_literal(Node* node, int exact, regex_t* reg)
{
Node* n = NULL_NODE;
switch (NODE_TYPE(node)) {
case NODE_BACKREF:
case NODE_ALT:
#ifdef USE_CALL
case NODE_CALL:
#endif
break;
case NODE_CTYPE:
if (CTYPE_(node)->ctype == CTYPE_ANYCHAR)
break;
/* fall */
case NODE_CCLASS:
if (exact == 0) {
n = node;
}
break;
case NODE_LIST:
n = get_tree_head_literal(NODE_CAR(node), exact, reg);
break;
case NODE_STRING:
{
StrNode* sn = STR_(node);
if (sn->end <= sn->s)
break;
if (exact == 0 ||
! NODE_IS_IGNORECASE(node) || NODE_STRING_IS_CRUDE(node)) {
n = node;
}
}
break;
case NODE_QUANT:
{
QuantNode* qn = QUANT_(node);
if (qn->lower > 0) {
if (IS_NOT_NULL(qn->head_exact))
n = qn->head_exact;
else
n = get_tree_head_literal(NODE_BODY(node), exact, reg);
}
}
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
switch (en->type) {
case BAG_OPTION:
case BAG_MEMORY:
case BAG_STOP_BACKTRACK:
case BAG_IF_ELSE:
n = get_tree_head_literal(NODE_BODY(node), exact, reg);
break;
}
}
break;
case NODE_ANCHOR:
if (ANCHOR_(node)->type == ANCR_PREC_READ)
n = get_tree_head_literal(NODE_BODY(node), exact, reg);
break;
case NODE_GIMMICK:
default:
break;
}
return n;
}
enum GetValue {
GET_VALUE_NONE = -1,
GET_VALUE_IGNORE = 0,
GET_VALUE_FOUND = 1
};
static int
get_tree_tail_literal(Node* node, Node** rnode, regex_t* reg)
{
int r;
switch (NODE_TYPE(node)) {
case NODE_LIST:
if (IS_NULL(NODE_CDR(node))) {
r = get_tree_tail_literal(NODE_CAR(node), rnode, reg);
}
else {
r = get_tree_tail_literal(NODE_CDR(node), rnode, reg);
if (r == GET_VALUE_IGNORE) {
r = get_tree_tail_literal(NODE_CAR(node), rnode, reg);
}
}
break;
#ifdef USE_CALL
case NODE_CALL:
r = get_tree_tail_literal(NODE_BODY(node), rnode, reg);
break;
#endif
case NODE_CTYPE:
if (CTYPE_(node)->ctype == CTYPE_ANYCHAR) {
r = GET_VALUE_NONE;
break;
}
/* fall */
case NODE_CCLASS:
*rnode = node;
r = GET_VALUE_FOUND;
break;
case NODE_STRING:
{
StrNode* sn = STR_(node);
if (sn->end <= sn->s) {
r = GET_VALUE_IGNORE;
break;
}
if (NODE_IS_IGNORECASE(node) && ! NODE_STRING_IS_CRUDE(node)) {
r = GET_VALUE_NONE;
break;
}
*rnode = node;
r = GET_VALUE_FOUND;
}
break;
case NODE_QUANT:
{
QuantNode* qn = QUANT_(node);
if (qn->lower != 0) {
r = get_tree_tail_literal(NODE_BODY(node), rnode, reg);
}
else
r = GET_VALUE_NONE;
}
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
if (en->type == BAG_MEMORY) {
if (NODE_IS_MARK1(node))
r = GET_VALUE_NONE;
else {
NODE_STATUS_ADD(node, MARK1);
r = get_tree_tail_literal(NODE_BODY(node), rnode, reg);
NODE_STATUS_REMOVE(node, MARK1);
}
}
else {
r = get_tree_tail_literal(NODE_BODY(node), rnode, reg);
}
}
break;
case NODE_ANCHOR:
case NODE_GIMMICK:
r = GET_VALUE_IGNORE;
break;
case NODE_ALT:
case NODE_BACKREF:
default:
r = GET_VALUE_NONE;
break;
}
return r;
}
static int
check_called_node_in_look_behind(Node* node, int not)
{
int r;
r = 0;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
do {
r = check_called_node_in_look_behind(NODE_CAR(node), not);
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_QUANT:
r = check_called_node_in_look_behind(NODE_BODY(node), not);
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
if (en->type == BAG_MEMORY) {
if (NODE_IS_MARK1(node))
return 0;
else {
NODE_STATUS_ADD(node, MARK1);
r = check_called_node_in_look_behind(NODE_BODY(node), not);
NODE_STATUS_REMOVE(node, MARK1);
}
}
else {
r = check_called_node_in_look_behind(NODE_BODY(node), not);
if (r == 0 && en->type == BAG_IF_ELSE) {
if (IS_NOT_NULL(en->te.Then)) {
r = check_called_node_in_look_behind(en->te.Then, not);
if (r != 0) break;
}
if (IS_NOT_NULL(en->te.Else)) {
r = check_called_node_in_look_behind(en->te.Else, not);
}
}
}
}
break;
case NODE_ANCHOR:
if (IS_NOT_NULL(NODE_BODY(node)))
r = check_called_node_in_look_behind(NODE_BODY(node), not);
break;
case NODE_GIMMICK:
if (NODE_IS_ABSENT_WITH_SIDE_EFFECTS(node) != 0)
return 1;
break;
default:
break;
}
return r;
}
/* allowed node types in look-behind */
#define ALLOWED_TYPE_IN_LB \
( NODE_BIT_LIST | NODE_BIT_ALT | NODE_BIT_STRING | NODE_BIT_CCLASS \
| NODE_BIT_CTYPE | NODE_BIT_ANCHOR | NODE_BIT_BAG | NODE_BIT_QUANT \
| NODE_BIT_CALL | NODE_BIT_BACKREF | NODE_BIT_GIMMICK)
#define ALLOWED_BAG_IN_LB ( 1<<BAG_MEMORY | 1<<BAG_OPTION | 1<<BAG_STOP_BACKTRACK | 1<<BAG_IF_ELSE )
#define ALLOWED_BAG_IN_LB_NOT ( 1<<BAG_OPTION | 1<<BAG_STOP_BACKTRACK | 1<<BAG_IF_ELSE )
#define ALLOWED_ANCHOR_IN_LB \
( ANCR_LOOK_BEHIND | ANCR_BEGIN_LINE | ANCR_END_LINE | ANCR_BEGIN_BUF \
| ANCR_BEGIN_POSITION | ANCR_WORD_BOUNDARY | ANCR_NO_WORD_BOUNDARY \
| ANCR_WORD_BEGIN | ANCR_WORD_END \
| ANCR_TEXT_SEGMENT_BOUNDARY | ANCR_NO_TEXT_SEGMENT_BOUNDARY )
#define ALLOWED_ANCHOR_IN_LB_NOT \
( ANCR_LOOK_BEHIND | ANCR_LOOK_BEHIND_NOT | ANCR_BEGIN_LINE \
| ANCR_END_LINE | ANCR_BEGIN_BUF | ANCR_BEGIN_POSITION | ANCR_WORD_BOUNDARY \
| ANCR_NO_WORD_BOUNDARY | ANCR_WORD_BEGIN | ANCR_WORD_END \
| ANCR_TEXT_SEGMENT_BOUNDARY | ANCR_NO_TEXT_SEGMENT_BOUNDARY )
static int
check_node_in_look_behind(Node* node, int not, int* used)
{
static unsigned int
bag_mask[2] = { ALLOWED_BAG_IN_LB, ALLOWED_BAG_IN_LB_NOT };
static unsigned int
anchor_mask[2] = { ALLOWED_ANCHOR_IN_LB, ALLOWED_ANCHOR_IN_LB_NOT };
NodeType type;
int r = 0;
type = NODE_TYPE(node);
if ((NODE_TYPE2BIT(type) & ALLOWED_TYPE_IN_LB) == 0)
return 1;
switch (type) {
case NODE_LIST:
case NODE_ALT:
do {
r = check_node_in_look_behind(NODE_CAR(node), not, used);
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_QUANT:
r = check_node_in_look_behind(NODE_BODY(node), not, used);
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
if (((1<<en->type) & bag_mask[not]) == 0)
return 1;
r = check_node_in_look_behind(NODE_BODY(node), not, used);
if (r != 0) break;
if (en->type == BAG_MEMORY) {
if (NODE_IS_BACKREF(node) || NODE_IS_CALLED(node)
|| NODE_IS_REFERENCED(node))
*used = TRUE;
}
else if (en->type == BAG_IF_ELSE) {
if (IS_NOT_NULL(en->te.Then)) {
r = check_node_in_look_behind(en->te.Then, not, used);
if (r != 0) break;
}
if (IS_NOT_NULL(en->te.Else)) {
r = check_node_in_look_behind(en->te.Else, not, used);
}
}
}
break;
case NODE_ANCHOR:
type = ANCHOR_(node)->type;
if ((type & anchor_mask[not]) == 0)
return 1;
if (IS_NOT_NULL(NODE_BODY(node)))
r = check_node_in_look_behind(NODE_BODY(node), not, used);
break;
case NODE_GIMMICK:
if (NODE_IS_ABSENT_WITH_SIDE_EFFECTS(node) != 0)
return 1;
break;
case NODE_CALL:
r = check_called_node_in_look_behind(NODE_BODY(node), not);
break;
default:
break;
}
return r;
}
static OnigLen
node_min_byte_len(Node* node, ScanEnv* env)
{
OnigLen len;
OnigLen tmin;
len = 0;
switch (NODE_TYPE(node)) {
case NODE_BACKREF:
if (! NODE_IS_CHECKER(node)) {
int i;
int* backs;
MemEnv* mem_env = SCANENV_MEMENV(env);
BackRefNode* br = BACKREF_(node);
if (NODE_IS_RECURSION(node)) break;
backs = BACKREFS_P(br);
len = node_min_byte_len(mem_env[backs[0]].mem_node, env);
for (i = 1; i < br->back_num; i++) {
tmin = node_min_byte_len(mem_env[backs[i]].mem_node, env);
if (len > tmin) len = tmin;
}
}
break;
#ifdef USE_CALL
case NODE_CALL:
{
Node* t = NODE_BODY(node);
if (NODE_IS_RECURSION(node)) {
if (NODE_IS_FIXED_MIN(t))
len = BAG_(t)->min_len;
}
else
len = node_min_byte_len(t, env);
}
break;
#endif
case NODE_LIST:
do {
tmin = node_min_byte_len(NODE_CAR(node), env);
len = distance_add(len, tmin);
} while (IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_ALT:
{
Node *x, *y;
y = node;
do {
x = NODE_CAR(y);
tmin = node_min_byte_len(x, env);
if (y == node) len = tmin;
else if (len > tmin) len = tmin;
} while (IS_NOT_NULL(y = NODE_CDR(y)));
}
break;
case NODE_STRING:
{
StrNode* sn = STR_(node);
len = (int )(sn->end - sn->s);
}
break;
case NODE_CTYPE:
case NODE_CCLASS:
len = ONIGENC_MBC_MINLEN(env->enc);
break;
case NODE_QUANT:
{
QuantNode* qn = QUANT_(node);
if (qn->lower > 0) {
len = node_min_byte_len(NODE_BODY(node), env);
len = distance_multiply(len, qn->lower);
}
}
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
switch (en->type) {
case BAG_MEMORY:
if (NODE_IS_FIXED_MIN(node))
len = en->min_len;
else {
if (NODE_IS_MARK1(node))
len = 0; /* recursive */
else {
NODE_STATUS_ADD(node, MARK1);
len = node_min_byte_len(NODE_BODY(node), env);
NODE_STATUS_REMOVE(node, MARK1);
en->min_len = len;
NODE_STATUS_ADD(node, FIXED_MIN);
}
}
break;
case BAG_OPTION:
case BAG_STOP_BACKTRACK:
len = node_min_byte_len(NODE_BODY(node), env);
break;
case BAG_IF_ELSE:
{
OnigLen elen;
len = node_min_byte_len(NODE_BODY(node), env);
if (IS_NOT_NULL(en->te.Then))
len += node_min_byte_len(en->te.Then, env);
if (IS_NOT_NULL(en->te.Else))
elen = node_min_byte_len(en->te.Else, env);
else elen = 0;
if (elen < len) len = elen;
}
break;
}
}
break;
case NODE_GIMMICK:
{
GimmickNode* g = GIMMICK_(node);
if (g->type == GIMMICK_FAIL) {
len = INFINITE_LEN;
break;
}
}
/* fall */
case NODE_ANCHOR:
default:
break;
}
return len;
}
static OnigLen
node_max_byte_len(Node* node, ScanEnv* env)
{
OnigLen len;
OnigLen tmax;
len = 0;
switch (NODE_TYPE(node)) {
case NODE_LIST:
do {
tmax = node_max_byte_len(NODE_CAR(node), env);
len = distance_add(len, tmax);
} while (IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_ALT:
do {
tmax = node_max_byte_len(NODE_CAR(node), env);
if (len < tmax) len = tmax;
} while (IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_STRING:
{
StrNode* sn = STR_(node);
len = (OnigLen )(sn->end - sn->s);
}
break;
case NODE_CTYPE:
case NODE_CCLASS:
len = ONIGENC_MBC_MAXLEN_DIST(env->enc);
break;
case NODE_BACKREF:
if (! NODE_IS_CHECKER(node)) {
int i;
int* backs;
MemEnv* mem_env = SCANENV_MEMENV(env);
BackRefNode* br = BACKREF_(node);
if (NODE_IS_RECURSION(node)) {
#ifdef USE_BACKREF_WITH_LEVEL
if (NODE_IS_NEST_LEVEL(node)) {
len = INFINITE_LEN;
}
#endif
break;
}
backs = BACKREFS_P(br);
for (i = 0; i < br->back_num; i++) {
tmax = node_max_byte_len(mem_env[backs[i]].mem_node, env);
if (len < tmax) len = tmax;
}
}
break;
#ifdef USE_CALL
case NODE_CALL:
if (! NODE_IS_RECURSION(node))
len = node_max_byte_len(NODE_BODY(node), env);
else
len = INFINITE_LEN;
break;
#endif
case NODE_QUANT:
{
QuantNode* qn = QUANT_(node);
if (qn->upper != 0) {
len = node_max_byte_len(NODE_BODY(node), env);
if (len != 0) {
if (! IS_INFINITE_REPEAT(qn->upper))
len = distance_multiply(len, qn->upper);
else
len = INFINITE_LEN;
}
}
}
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
switch (en->type) {
case BAG_MEMORY:
if (NODE_IS_FIXED_MAX(node))
len = en->max_len;
else {
if (NODE_IS_MARK1(node))
len = INFINITE_LEN;
else {
NODE_STATUS_ADD(node, MARK1);
len = node_max_byte_len(NODE_BODY(node), env);
NODE_STATUS_REMOVE(node, MARK1);
en->max_len = len;
NODE_STATUS_ADD(node, FIXED_MAX);
}
}
break;
case BAG_OPTION:
case BAG_STOP_BACKTRACK:
len = node_max_byte_len(NODE_BODY(node), env);
break;
case BAG_IF_ELSE:
{
OnigLen tlen, elen;
len = node_max_byte_len(NODE_BODY(node), env);
if (IS_NOT_NULL(en->te.Then)) {
tlen = node_max_byte_len(en->te.Then, env);
len = distance_add(len, tlen);
}
if (IS_NOT_NULL(en->te.Else))
elen = node_max_byte_len(en->te.Else, env);
else elen = 0;
if (elen > len) len = elen;
}
break;
}
}
break;
case NODE_ANCHOR:
case NODE_GIMMICK:
default:
break;
}
return len;
}
static int
check_backrefs(Node* node, ScanEnv* env)
{
int r;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
do {
r = check_backrefs(NODE_CAR(node), env);
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_ANCHOR:
if (! ANCHOR_HAS_BODY(ANCHOR_(node))) {
r = 0;
break;
}
/* fall */
case NODE_QUANT:
r = check_backrefs(NODE_BODY(node), env);
break;
case NODE_BAG:
r = check_backrefs(NODE_BODY(node), env);
{
BagNode* en = BAG_(node);
if (en->type == BAG_IF_ELSE) {
if (r != 0) return r;
if (IS_NOT_NULL(en->te.Then)) {
r = check_backrefs(en->te.Then, env);
if (r != 0) return r;
}
if (IS_NOT_NULL(en->te.Else)) {
r = check_backrefs(en->te.Else, env);
}
}
}
break;
case NODE_BACKREF:
{
int i;
BackRefNode* br = BACKREF_(node);
int* backs = BACKREFS_P(br);
MemEnv* mem_env = SCANENV_MEMENV(env);
for (i = 0; i < br->back_num; i++) {
if (backs[i] > env->num_mem)
return ONIGERR_INVALID_BACKREF;
NODE_STATUS_ADD(mem_env[backs[i]].mem_node, BACKREF);
}
r = 0;
}
break;
default:
r = 0;
break;
}
return r;
}
static int
set_empty_repeat_node_trav(Node* node, Node* empty, ScanEnv* env)
{
int r;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
do {
r = set_empty_repeat_node_trav(NODE_CAR(node), empty, env);
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_ANCHOR:
{
AnchorNode* an = ANCHOR_(node);
if (! ANCHOR_HAS_BODY(an)) {
r = 0;
break;
}
switch (an->type) {
case ANCR_PREC_READ:
case ANCR_LOOK_BEHIND:
empty = NULL_NODE;
break;
default:
break;
}
r = set_empty_repeat_node_trav(NODE_BODY(node), empty, env);
}
break;
case NODE_QUANT:
{
QuantNode* qn = QUANT_(node);
if (qn->emptiness != BODY_IS_NOT_EMPTY) empty = node;
r = set_empty_repeat_node_trav(NODE_BODY(node), empty, env);
}
break;
case NODE_BAG:
if (IS_NOT_NULL(NODE_BODY(node))) {
r = set_empty_repeat_node_trav(NODE_BODY(node), empty, env);
if (r != 0) return r;
}
{
BagNode* en = BAG_(node);
r = 0;
if (en->type == BAG_MEMORY) {
if (NODE_IS_BACKREF(node)) {
if (IS_NOT_NULL(empty))
SCANENV_MEMENV(env)[en->m.regnum].empty_repeat_node = empty;
}
}
else if (en->type == BAG_IF_ELSE) {
if (IS_NOT_NULL(en->te.Then)) {
r = set_empty_repeat_node_trav(en->te.Then, empty, env);
if (r != 0) return r;
}
if (IS_NOT_NULL(en->te.Else)) {
r = set_empty_repeat_node_trav(en->te.Else, empty, env);
}
}
}
break;
default:
r = 0;
break;
}
return r;
}
static int
is_ancestor_node(Node* node, Node* me)
{
Node* parent;
while ((parent = NODE_PARENT(me)) != NULL_NODE) {
if (parent == node) return 1;
me = parent;
}
return 0;
}
static void
set_empty_status_check_trav(Node* node, ScanEnv* env)
{
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
do {
set_empty_status_check_trav(NODE_CAR(node), env);
} while (IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_ANCHOR:
{
AnchorNode* an = ANCHOR_(node);
if (! ANCHOR_HAS_BODY(an)) break;
set_empty_status_check_trav(NODE_BODY(node), env);
}
break;
case NODE_QUANT:
set_empty_status_check_trav(NODE_BODY(node), env);
break;
case NODE_BAG:
if (IS_NOT_NULL(NODE_BODY(node)))
set_empty_status_check_trav(NODE_BODY(node), env);
{
BagNode* en = BAG_(node);
if (en->type == BAG_IF_ELSE) {
if (IS_NOT_NULL(en->te.Then)) {
set_empty_status_check_trav(en->te.Then, env);
}
if (IS_NOT_NULL(en->te.Else)) {
set_empty_status_check_trav(en->te.Else, env);
}
}
}
break;
case NODE_BACKREF:
{
int i;
int* backs;
MemEnv* mem_env = SCANENV_MEMENV(env);
BackRefNode* br = BACKREF_(node);
backs = BACKREFS_P(br);
for (i = 0; i < br->back_num; i++) {
Node* ernode = mem_env[backs[i]].empty_repeat_node;
if (IS_NOT_NULL(ernode)) {
if (! is_ancestor_node(ernode, node)) {
MEM_STATUS_LIMIT_ON(env->reg->empty_status_mem, backs[i]);
NODE_STATUS_ADD(ernode, EMPTY_STATUS_CHECK);
NODE_STATUS_ADD(mem_env[backs[i]].mem_node, EMPTY_STATUS_CHECK);
}
}
}
}
break;
default:
break;
}
}
static void
set_parent_node_trav(Node* node, Node* parent)
{
NODE_PARENT(node) = parent;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
do {
set_parent_node_trav(NODE_CAR(node), node);
} while (IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_ANCHOR:
if (! ANCHOR_HAS_BODY(ANCHOR_(node))) break;
set_parent_node_trav(NODE_BODY(node), node);
break;
case NODE_QUANT:
set_parent_node_trav(NODE_BODY(node), node);
break;
case NODE_BAG:
if (IS_NOT_NULL(NODE_BODY(node)))
set_parent_node_trav(NODE_BODY(node), node);
{
BagNode* en = BAG_(node);
if (en->type == BAG_IF_ELSE) {
if (IS_NOT_NULL(en->te.Then))
set_parent_node_trav(en->te.Then, node);
if (IS_NOT_NULL(en->te.Else)) {
set_parent_node_trav(en->te.Else, node);
}
}
}
break;
default:
break;
}
}
#ifdef USE_CALL
#define RECURSION_EXIST (1<<0)
#define RECURSION_MUST (1<<1)
#define RECURSION_INFINITE (1<<2)
static int
infinite_recursive_call_check(Node* node, ScanEnv* env, int head)
{
int ret;
int r = 0;
switch (NODE_TYPE(node)) {
case NODE_LIST:
{
Node *x;
OnigLen min;
x = node;
do {
ret = infinite_recursive_call_check(NODE_CAR(x), env, head);
if (ret < 0 || (ret & RECURSION_INFINITE) != 0) return ret;
r |= ret;
if (head != 0) {
min = node_min_byte_len(NODE_CAR(x), env);
if (min != 0) head = 0;
}
} while (IS_NOT_NULL(x = NODE_CDR(x)));
}
break;
case NODE_ALT:
{
int must;
must = RECURSION_MUST;
do {
ret = infinite_recursive_call_check(NODE_CAR(node), env, head);
if (ret < 0 || (ret & RECURSION_INFINITE) != 0) return ret;
r |= (ret & RECURSION_EXIST);
must &= ret;
} while (IS_NOT_NULL(node = NODE_CDR(node)));
r |= must;
}
break;
case NODE_QUANT:
r = infinite_recursive_call_check(NODE_BODY(node), env, head);
if (r < 0) return r;
if ((r & RECURSION_MUST) != 0) {
if (QUANT_(node)->lower == 0)
r &= ~RECURSION_MUST;
}
break;
case NODE_ANCHOR:
if (! ANCHOR_HAS_BODY(ANCHOR_(node)))
break;
/* fall */
case NODE_CALL:
r = infinite_recursive_call_check(NODE_BODY(node), env, head);
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
if (en->type == BAG_MEMORY) {
if (NODE_IS_MARK2(node))
return 0;
else if (NODE_IS_MARK1(node))
return (head == 0 ? RECURSION_EXIST | RECURSION_MUST
: RECURSION_EXIST | RECURSION_MUST | RECURSION_INFINITE);
else {
NODE_STATUS_ADD(node, MARK2);
r = infinite_recursive_call_check(NODE_BODY(node), env, head);
NODE_STATUS_REMOVE(node, MARK2);
}
}
else if (en->type == BAG_IF_ELSE) {
int eret;
ret = infinite_recursive_call_check(NODE_BODY(node), env, head);
if (ret < 0 || (ret & RECURSION_INFINITE) != 0) return ret;
r |= ret;
if (IS_NOT_NULL(en->te.Then)) {
OnigLen min;
if (head != 0) {
min = node_min_byte_len(NODE_BODY(node), env);
}
else min = 0;
ret = infinite_recursive_call_check(en->te.Then, env, min != 0 ? 0:head);
if (ret < 0 || (ret & RECURSION_INFINITE) != 0) return ret;
r |= ret;
}
if (IS_NOT_NULL(en->te.Else)) {
eret = infinite_recursive_call_check(en->te.Else, env, head);
if (eret < 0 || (eret & RECURSION_INFINITE) != 0) return eret;
r |= (eret & RECURSION_EXIST);
if ((eret & RECURSION_MUST) == 0)
r &= ~RECURSION_MUST;
}
else {
r &= ~RECURSION_MUST;
}
}
else {
r = infinite_recursive_call_check(NODE_BODY(node), env, head);
}
}
break;
default:
break;
}
return r;
}
static int
infinite_recursive_call_check_trav(Node* node, ScanEnv* env)
{
int r;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
do {
r = infinite_recursive_call_check_trav(NODE_CAR(node), env);
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_ANCHOR:
if (! ANCHOR_HAS_BODY(ANCHOR_(node))) {
r = 0;
break;
}
/* fall */
case NODE_QUANT:
r = infinite_recursive_call_check_trav(NODE_BODY(node), env);
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
if (en->type == BAG_MEMORY) {
if (NODE_IS_RECURSION(node) && NODE_IS_CALLED(node)) {
int ret;
NODE_STATUS_ADD(node, MARK1);
ret = infinite_recursive_call_check(NODE_BODY(node), env, 1);
if (ret < 0) return ret;
else if ((ret & (RECURSION_MUST | RECURSION_INFINITE)) != 0)
return ONIGERR_NEVER_ENDING_RECURSION;
NODE_STATUS_REMOVE(node, MARK1);
}
}
else if (en->type == BAG_IF_ELSE) {
if (IS_NOT_NULL(en->te.Then)) {
r = infinite_recursive_call_check_trav(en->te.Then, env);
if (r != 0) return r;
}
if (IS_NOT_NULL(en->te.Else)) {
r = infinite_recursive_call_check_trav(en->te.Else, env);
if (r != 0) return r;
}
}
}
r = infinite_recursive_call_check_trav(NODE_BODY(node), env);
break;
default:
r = 0;
break;
}
return r;
}
static int
recursive_call_check(Node* node)
{
int r;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
r = 0;
do {
r |= recursive_call_check(NODE_CAR(node));
} while (IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_ANCHOR:
if (! ANCHOR_HAS_BODY(ANCHOR_(node))) {
r = 0;
break;
}
/* fall */
case NODE_QUANT:
r = recursive_call_check(NODE_BODY(node));
break;
case NODE_CALL:
r = recursive_call_check(NODE_BODY(node));
if (r != 0) {
if (NODE_IS_MARK1(NODE_BODY(node)))
NODE_STATUS_ADD(node, RECURSION);
}
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
if (en->type == BAG_MEMORY) {
if (NODE_IS_MARK2(node))
return 0;
else if (NODE_IS_MARK1(node))
return 1; /* recursion */
else {
NODE_STATUS_ADD(node, MARK2);
r = recursive_call_check(NODE_BODY(node));
NODE_STATUS_REMOVE(node, MARK2);
}
}
else if (en->type == BAG_IF_ELSE) {
r = 0;
if (IS_NOT_NULL(en->te.Then)) {
r |= recursive_call_check(en->te.Then);
}
if (IS_NOT_NULL(en->te.Else)) {
r |= recursive_call_check(en->te.Else);
}
r |= recursive_call_check(NODE_BODY(node));
}
else {
r = recursive_call_check(NODE_BODY(node));
}
}
break;
default:
r = 0;
break;
}
return r;
}
#define IN_RECURSION (1<<0)
#define FOUND_CALLED_NODE 1
static int
recursive_call_check_trav(Node* node, ScanEnv* env, int state)
{
int r = 0;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
{
int ret;
do {
ret = recursive_call_check_trav(NODE_CAR(node), env, state);
if (ret == FOUND_CALLED_NODE) r = FOUND_CALLED_NODE;
else if (ret < 0) return ret;
} while (IS_NOT_NULL(node = NODE_CDR(node)));
}
break;
case NODE_QUANT:
r = recursive_call_check_trav(NODE_BODY(node), env, state);
if (QUANT_(node)->upper == 0) {
if (r == FOUND_CALLED_NODE)
QUANT_(node)->include_referred = 1;
}
break;
case NODE_ANCHOR:
{
AnchorNode* an = ANCHOR_(node);
if (ANCHOR_HAS_BODY(an))
r = recursive_call_check_trav(NODE_ANCHOR_BODY(an), env, state);
}
break;
case NODE_BAG:
{
int ret;
int state1;
BagNode* en = BAG_(node);
if (en->type == BAG_MEMORY) {
if (NODE_IS_CALLED(node) || (state & IN_RECURSION) != 0) {
if (! NODE_IS_RECURSION(node)) {
NODE_STATUS_ADD(node, MARK1);
r = recursive_call_check(NODE_BODY(node));
if (r != 0) {
NODE_STATUS_ADD(node, RECURSION);
MEM_STATUS_ON(env->backtrack_mem, en->m.regnum);
}
NODE_STATUS_REMOVE(node, MARK1);
}
if (NODE_IS_CALLED(node))
r = FOUND_CALLED_NODE;
}
}
state1 = state;
if (NODE_IS_RECURSION(node))
state1 |= IN_RECURSION;
ret = recursive_call_check_trav(NODE_BODY(node), env, state1);
if (ret == FOUND_CALLED_NODE)
r = FOUND_CALLED_NODE;
if (en->type == BAG_IF_ELSE) {
if (IS_NOT_NULL(en->te.Then)) {
ret = recursive_call_check_trav(en->te.Then, env, state1);
if (ret == FOUND_CALLED_NODE)
r = FOUND_CALLED_NODE;
}
if (IS_NOT_NULL(en->te.Else)) {
ret = recursive_call_check_trav(en->te.Else, env, state1);
if (ret == FOUND_CALLED_NODE)
r = FOUND_CALLED_NODE;
}
}
}
break;
default:
break;
}
return r;
}
#endif
static void
remove_from_list(Node* prev, Node* a)
{
if (NODE_CDR(prev) != a) return ;
NODE_CDR(prev) = NODE_CDR(a);
NODE_CDR(a) = NULL_NODE;
}
static int
reduce_string_list(Node* node, OnigEncoding enc)
{
int r = 0;
switch (NODE_TYPE(node)) {
case NODE_LIST:
{
Node* prev;
Node* curr;
Node* prev_node;
Node* next_node;
prev = NULL_NODE;
do {
next_node = NODE_CDR(node);
curr = NODE_CAR(node);
if (NODE_TYPE(curr) == NODE_STRING) {
if (IS_NULL(prev)
|| STR_(curr)->flag != STR_(prev)->flag
|| NODE_STATUS(curr) != NODE_STATUS(prev)) {
prev = curr;
prev_node = node;
}
else {
r = node_str_node_cat(prev, curr);
if (r != 0) return r;
remove_from_list(prev_node, node);
onig_node_free(node);
}
}
else {
if (IS_NOT_NULL(prev)) {
#ifdef USE_CHECK_VALIDITY_OF_STRING_IN_TREE
StrNode* sn = STR_(prev);
if (! ONIGENC_IS_VALID_MBC_STRING(enc, sn->s, sn->end))
return ONIGERR_INVALID_WIDE_CHAR_VALUE;
#endif
prev = NULL_NODE;
}
r = reduce_string_list(curr, enc);
if (r != 0) return r;
prev_node = node;
}
node = next_node;
} while (r == 0 && IS_NOT_NULL(node));
#ifdef USE_CHECK_VALIDITY_OF_STRING_IN_TREE
if (IS_NOT_NULL(prev)) {
StrNode* sn = STR_(prev);
if (! ONIGENC_IS_VALID_MBC_STRING(enc, sn->s, sn->end))
return ONIGERR_INVALID_WIDE_CHAR_VALUE;
}
#endif
}
break;
case NODE_ALT:
do {
r = reduce_string_list(NODE_CAR(node), enc);
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
#ifdef USE_CHECK_VALIDITY_OF_STRING_IN_TREE
case NODE_STRING:
{
StrNode* sn = STR_(node);
if (! ONIGENC_IS_VALID_MBC_STRING(enc, sn->s, sn->end))
return ONIGERR_INVALID_WIDE_CHAR_VALUE;
}
break;
#endif
case NODE_ANCHOR:
if (IS_NULL(NODE_BODY(node)))
break;
/* fall */
case NODE_QUANT:
r = reduce_string_list(NODE_BODY(node), enc);
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
r = reduce_string_list(NODE_BODY(node), enc);
if (r != 0) return r;
if (en->type == BAG_IF_ELSE) {
if (IS_NOT_NULL(en->te.Then)) {
r = reduce_string_list(en->te.Then, enc);
if (r != 0) return r;
}
if (IS_NOT_NULL(en->te.Else)) {
r = reduce_string_list(en->te.Else, enc);
if (r != 0) return r;
}
}
}
break;
default:
break;
}
return r;
}
#define IN_ALT (1<<0)
#define IN_NOT (1<<1)
#define IN_REAL_REPEAT (1<<2)
#define IN_VAR_REPEAT (1<<3)
#define IN_ZERO_REPEAT (1<<4)
#define IN_MULTI_ENTRY (1<<5)
#define IN_LOOK_BEHIND (1<<6)
/* divide different length alternatives in look-behind.
(?<=A|B) ==> (?<=A)|(?<=B)
(?<!A|B) ==> (?<!A)(?<!B)
*/
static int
divide_look_behind_alternatives(Node* node)
{
int r;
int anc_type;
Node *head, *np, *insert_node;
AnchorNode* an;
an = ANCHOR_(node);
anc_type = an->type;
head = NODE_ANCHOR_BODY(an);
np = NODE_CAR(head);
node_swap(node, head);
NODE_CAR(node) = head;
NODE_BODY(head) = np;
np = node;
while (IS_NOT_NULL(np = NODE_CDR(np))) {
r = onig_node_copy(&insert_node, head);
if (r != 0) return r;
CHECK_NULL_RETURN_MEMERR(insert_node);
NODE_BODY(insert_node) = NODE_CAR(np);
NODE_CAR(np) = insert_node;
}
if (anc_type == ANCR_LOOK_BEHIND_NOT) {
np = node;
do {
NODE_SET_TYPE(np, NODE_LIST); /* alt -> list */
} while (IS_NOT_NULL(np = NODE_CDR(np)));
}
return 0;
}
static int
node_reduce_in_look_behind(Node* node)
{
NodeType type;
Node* body;
if (NODE_TYPE(node) != NODE_QUANT) return 0;
body = NODE_BODY(node);
type = NODE_TYPE(body);
if (type == NODE_STRING || type == NODE_CTYPE ||
type == NODE_CCLASS || type == NODE_BACKREF) {
QuantNode* qn = QUANT_(node);
qn->upper = qn->lower;
if (qn->upper == 0)
return 1; /* removed */
}
return 0;
}
static int
list_reduce_in_look_behind(Node* node)
{
int r;
switch (NODE_TYPE(node)) {
case NODE_QUANT:
r = node_reduce_in_look_behind(node);
if (r > 0) r = 0;
break;
case NODE_LIST:
do {
r = node_reduce_in_look_behind(NODE_CAR(node));
if (r <= 0) break;
} while (IS_NOT_NULL(node = NODE_CDR(node)));
break;
default:
r = 0;
break;
}
return r;
}
static int
alt_reduce_in_look_behind(Node* node, regex_t* reg, ScanEnv* env)
{
int r;
switch (NODE_TYPE(node)) {
case NODE_ALT:
do {
r = list_reduce_in_look_behind(NODE_CAR(node));
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
default:
r = list_reduce_in_look_behind(node);
break;
}
return r;
}
static int tune_tree(Node* node, regex_t* reg, int state, ScanEnv* env);
static int
tune_look_behind(Node* node, regex_t* reg, int state, ScanEnv* env)
{
int r;
int state1;
int used;
MinMaxCharLen ci;
Node* body;
AnchorNode* an = ANCHOR_(node);
used = FALSE;
r = check_node_in_look_behind(NODE_ANCHOR_BODY(an),
an->type == ANCR_LOOK_BEHIND_NOT ? 1 : 0,
&used);
if (r < 0) return r;
if (r > 0) return ONIGERR_INVALID_LOOK_BEHIND_PATTERN;
if (an->type == ANCR_LOOK_BEHIND_NOT)
state1 = state | IN_NOT | IN_LOOK_BEHIND;
else
state1 = state | IN_LOOK_BEHIND;
body = NODE_ANCHOR_BODY(an);
/* Execute tune_tree(body) before call node_char_len().
Because case-fold expansion must be done before node_char_len().
*/
r = tune_tree(body, reg, state1, env);
if (r != 0) return r;
r = alt_reduce_in_look_behind(body, reg, env);
if (r != 0) return r;
r = node_char_len(body, reg, &ci, env);
if (r >= 0) {
/* #177: overflow in onigenc_step_back() */
if ((ci.max != INFINITE_LEN && ci.max > LOOK_BEHIND_MAX_CHAR_LEN)
|| ci.min > LOOK_BEHIND_MAX_CHAR_LEN) {
return ONIGERR_INVALID_LOOK_BEHIND_PATTERN;
}
if (ci.min == 0 && ci.min_is_sure != FALSE && used == FALSE) {
if (an->type == ANCR_LOOK_BEHIND_NOT)
r = onig_node_reset_fail(node);
else
r = onig_node_reset_empty(node);
return r;
}
if (r == CHAR_LEN_TOP_ALT_FIXED) {
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_DIFFERENT_LEN_ALT_LOOK_BEHIND)) {
r = divide_look_behind_alternatives(node);
if (r == 0)
r = tune_tree(node, reg, state, env);
}
else if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_VARIABLE_LEN_LOOK_BEHIND))
goto normal;
else
r = ONIGERR_INVALID_LOOK_BEHIND_PATTERN;
}
else { /* CHAR_LEN_NORMAL */
normal:
if (ci.min == INFINITE_LEN) {
r = ONIGERR_INVALID_LOOK_BEHIND_PATTERN;
}
else {
if (ci.min != ci.max &&
! IS_SYNTAX_BV(env->syntax, ONIG_SYN_VARIABLE_LEN_LOOK_BEHIND)) {
r = ONIGERR_INVALID_LOOK_BEHIND_PATTERN;
}
else {
Node* tail;
/* check lead_node is already set by double call after
divide_look_behind_alternatives() */
if (IS_NULL(an->lead_node)) {
an->char_min_len = ci.min;
an->char_max_len = ci.max;
r = get_tree_tail_literal(body, &tail, reg);
if (r == GET_VALUE_FOUND) {
r = onig_node_copy(&(an->lead_node), tail);
if (r != 0) return r;
}
}
r = ONIG_NORMAL;
}
}
}
}
return r;
}
static int
tune_next(Node* node, Node* next_node, regex_t* reg)
{
int called;
NodeType type;
called = FALSE;
retry:
type = NODE_TYPE(node);
if (type == NODE_QUANT) {
QuantNode* qn = QUANT_(node);
if (qn->greedy && IS_INFINITE_REPEAT(qn->upper)) {
#ifdef USE_QUANT_PEEK_NEXT
if (called == FALSE) {
Node* n = get_tree_head_literal(next_node, 1, reg);
/* '\0': for UTF-16BE etc... */
if (IS_NOT_NULL(n) && STR_(n)->s[0] != '\0') {
qn->next_head_exact = n;
}
}
#endif
/* automatic posseivation a*b ==> (?>a*)b */
if (qn->lower <= 1) {
if (is_strict_real_node(NODE_BODY(node))) {
Node *x, *y;
x = get_tree_head_literal(NODE_BODY(node), 0, reg);
if (IS_NOT_NULL(x)) {
y = get_tree_head_literal(next_node, 0, reg);
if (IS_NOT_NULL(y) && is_exclusive(x, y, reg)) {
Node* en = onig_node_new_bag(BAG_STOP_BACKTRACK);
CHECK_NULL_RETURN_MEMERR(en);
NODE_STATUS_ADD(en, STRICT_REAL_REPEAT);
node_swap(node, en);
NODE_BODY(node) = en;
}
}
}
}
}
}
else if (type == NODE_BAG) {
BagNode* en = BAG_(node);
if (en->type == BAG_MEMORY) {
if (NODE_IS_CALLED(node))
called = TRUE;
node = NODE_BODY(node);
goto retry;
}
}
return 0;
}
static int
is_all_code_len_1_items(int n, OnigCaseFoldCodeItem items[])
{
int i;
for (i = 0; i < n; i++) {
OnigCaseFoldCodeItem* item = items + i;
if (item->code_len != 1) return 0;
}
return 1;
}
static int
get_min_max_byte_len_case_fold_items(int n, OnigCaseFoldCodeItem items[],
OnigLen* rmin, OnigLen* rmax)
{
int i;
OnigLen len, minlen, maxlen;
minlen = INFINITE_LEN;
maxlen = 0;
for (i = 0; i < n; i++) {
OnigCaseFoldCodeItem* item = items + i;
len = item->byte_len;
if (len < minlen) minlen = len;
if (len > maxlen) maxlen = len;
}
*rmin = minlen;
*rmax = maxlen;
return 0;
}
static int
make_code_list_to_string(Node** rnode, OnigEncoding enc,
int n, OnigCodePoint codes[])
{
int r, i, len;
Node* node;
UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN];
*rnode = NULL_NODE;
node = onig_node_new_str(NULL, NULL);
CHECK_NULL_RETURN_MEMERR(node);
for (i = 0; i < n; i++) {
len = ONIGENC_CODE_TO_MBC(enc, codes[i], buf);
if (len < 0) {
r = len;
goto err;
}
r = onig_node_str_cat(node, buf, buf + len);
if (r != 0) goto err;
}
*rnode = node;
return 0;
err:
onig_node_free(node);
return r;
}
static int
unravel_cf_node_add(Node** rlist, Node* add)
{
Node *list;
list = *rlist;
if (IS_NULL(list)) {
list = onig_node_new_list(add, NULL);
CHECK_NULL_RETURN_MEMERR(list);
*rlist = list;
}
else {
Node* r = node_list_add(list, add);
CHECK_NULL_RETURN_MEMERR(r);
}
return 0;
}
static int
unravel_cf_string_add(Node** rlist, Node** rsn, UChar* s, UChar* end,
unsigned int flag)
{
int r;
Node *sn, *list;
list = *rlist;
sn = *rsn;
if (IS_NOT_NULL(sn) && STR_(sn)->flag == flag) {
r = onig_node_str_cat(sn, s, end);
}
else {
sn = onig_node_new_str(s, end);
CHECK_NULL_RETURN_MEMERR(sn);
STR_(sn)->flag = flag;
r = unravel_cf_node_add(&list, sn);
}
if (r == 0) {
*rlist = list;
*rsn = sn;
}
return r;
}
static int
unravel_cf_string_alt_or_cc_add(Node** rlist, int n,
OnigCaseFoldCodeItem items[], OnigEncoding enc,
OnigCaseFoldType case_fold_flag, UChar* s, UChar* end)
{
int r, i;
Node* node;
if (is_all_code_len_1_items(n, items)) {
OnigCodePoint codes[14];/* least ONIGENC_GET_CASE_FOLD_CODES_MAX_NUM + 1 */
codes[0] = ONIGENC_MBC_TO_CODE(enc, s, end);
for (i = 0; i < n; i++) {
OnigCaseFoldCodeItem* item = items + i;
codes[i+1] = item->code[0];
}
r = onig_new_cclass_with_code_list(&node, enc, n + 1, codes);
if (r != 0) return r;
}
else {
Node *snode, *alt, *curr;
snode = onig_node_new_str(s, end);
CHECK_NULL_RETURN_MEMERR(snode);
node = curr = onig_node_new_alt(snode, NULL_NODE);
if (IS_NULL(curr)) {
onig_node_free(snode);
return ONIGERR_MEMORY;
}
r = 0;
for (i = 0; i < n; i++) {
OnigCaseFoldCodeItem* item = items + i;
r = make_code_list_to_string(&snode, enc, item->code_len, item->code);
if (r != 0) {
onig_node_free(node);
return r;
}
alt = onig_node_new_alt(snode, NULL_NODE);
if (IS_NULL(alt)) {
onig_node_free(snode);
onig_node_free(node);
return ONIGERR_MEMORY;
}
NODE_CDR(curr) = alt;
curr = alt;
}
}
r = unravel_cf_node_add(rlist, node);
if (r != 0) onig_node_free(node);
return r;
}
static int
unravel_cf_look_behind_add(Node** rlist, Node** rsn,
int n, OnigCaseFoldCodeItem items[], OnigEncoding enc,
UChar* s, OnigLen one_len)
{
int r, i, found;
found = FALSE;
for (i = 0; i < n; i++) {
OnigCaseFoldCodeItem* item = items + i;
if (item->byte_len == one_len) {
if (item->code_len == 1) {
found = TRUE;
break;
}
}
}
if (found == FALSE) {
r = unravel_cf_string_add(rlist, rsn, s, s + one_len, 0 /* flag */);
}
else {
Node* node;
OnigCodePoint codes[14];/* least ONIGENC_GET_CASE_FOLD_CODES_MAX_NUM + 1 */
found = 0;
codes[found++] = ONIGENC_MBC_TO_CODE(enc, s, s + one_len);
for (i = 0; i < n; i++) {
OnigCaseFoldCodeItem* item = items + i;
if (item->byte_len == one_len) {
if (item->code_len == 1) {
codes[found++] = item->code[0];
}
}
}
r = onig_new_cclass_with_code_list(&node, enc, found, codes);
if (r != 0) return r;
r = unravel_cf_node_add(rlist, node);
if (r != 0) onig_node_free(node);
*rsn = NULL_NODE;
}
return r;
}
static int
unravel_case_fold_string(Node* node, regex_t* reg, int state)
{
int r, n, in_look_behind;
OnigLen min_len, max_len, one_len;
UChar *start, *end, *p, *q;
StrNode* snode;
Node *sn, *list;
OnigEncoding enc;
OnigCaseFoldCodeItem items[ONIGENC_GET_CASE_FOLD_CODES_MAX_NUM];
if (NODE_STRING_IS_CASE_EXPANDED(node)) return 0;
NODE_STATUS_REMOVE(node, IGNORECASE);
snode = STR_(node);
start = snode->s;
end = snode->end;
if (start >= end) return 0;
in_look_behind = (state & IN_LOOK_BEHIND) != 0;
enc = reg->enc;
list = sn = NULL_NODE;
p = start;
while (p < end) {
n = ONIGENC_GET_CASE_FOLD_CODES_BY_STR(enc, reg->case_fold_flag, p, end,
items);
if (n < 0) {
r = n;
goto err;
}
one_len = (OnigLen )enclen(enc, p);
if (n == 0) {
q = p + one_len;
if (q > end) q = end;
r = unravel_cf_string_add(&list, &sn, p, q, 0 /* flag */);
if (r != 0) goto err;
}
else {
if (in_look_behind != 0) {
q = p + one_len;
if (items[0].byte_len != one_len) {
r = ONIGENC_GET_CASE_FOLD_CODES_BY_STR(enc, reg->case_fold_flag, p, q,
items);
if (r < 0) goto err;
n = r;
}
r = unravel_cf_look_behind_add(&list, &sn, n, items, enc, p, one_len);
if (r != 0) goto err;
}
else {
get_min_max_byte_len_case_fold_items(n, items, &min_len, &max_len);
if (min_len != max_len) {
r = ONIGERR_PARSER_BUG;
goto err;
}
q = p + max_len;
r = unravel_cf_string_alt_or_cc_add(&list, n, items, enc,
reg->case_fold_flag, p, q);
if (r != 0) goto err;
sn = NULL_NODE;
}
}
p = q;
}
if (IS_NOT_NULL(list)) {
if (node_list_len(list) == 1) {
node_swap(node, NODE_CAR(list));
}
else {
node_swap(node, list);
}
onig_node_free(list);
}
else {
node_swap(node, sn);
onig_node_free(sn);
}
return 0;
err:
if (IS_NOT_NULL(list))
onig_node_free(list);
else if (IS_NOT_NULL(sn))
onig_node_free(sn);
return r;
}
#ifdef USE_STUBBORN_CHECK_CAPTURES_IN_EMPTY_REPEAT
static enum BodyEmptyType
quantifiers_memory_node_info(Node* node)
{
int r = BODY_MAY_BE_EMPTY;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
{
int v;
do {
v = quantifiers_memory_node_info(NODE_CAR(node));
if (v > r) r = v;
} while (IS_NOT_NULL(node = NODE_CDR(node)));
}
break;
#ifdef USE_CALL
case NODE_CALL:
if (NODE_IS_RECURSION(node)) {
return BODY_MAY_BE_EMPTY_REC; /* tiny version */
}
else
r = quantifiers_memory_node_info(NODE_BODY(node));
break;
#endif
case NODE_QUANT:
{
QuantNode* qn = QUANT_(node);
if (qn->upper != 0) {
r = quantifiers_memory_node_info(NODE_BODY(node));
}
}
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
switch (en->type) {
case BAG_MEMORY:
if (NODE_IS_RECURSION(node)) {
return BODY_MAY_BE_EMPTY_REC;
}
return BODY_MAY_BE_EMPTY_MEM;
break;
case BAG_OPTION:
case BAG_STOP_BACKTRACK:
r = quantifiers_memory_node_info(NODE_BODY(node));
break;
case BAG_IF_ELSE:
{
int v;
r = quantifiers_memory_node_info(NODE_BODY(node));
if (IS_NOT_NULL(en->te.Then)) {
v = quantifiers_memory_node_info(en->te.Then);
if (v > r) r = v;
}
if (IS_NOT_NULL(en->te.Else)) {
v = quantifiers_memory_node_info(en->te.Else);
if (v > r) r = v;
}
}
break;
}
}
break;
case NODE_BACKREF:
case NODE_STRING:
case NODE_CTYPE:
case NODE_CCLASS:
case NODE_ANCHOR:
case NODE_GIMMICK:
default:
break;
}
return r;
}
#endif /* USE_STUBBORN_CHECK_CAPTURES_IN_EMPTY_REPEAT */
#ifdef USE_CALL
#ifdef __GNUC__
__inline
#endif
static int
check_call_reference(CallNode* cn, ScanEnv* env, int state)
{
MemEnv* mem_env = SCANENV_MEMENV(env);
if (cn->by_number != 0) {
int gnum = cn->called_gnum;
if (env->num_named > 0 &&
IS_SYNTAX_BV(env->syntax, ONIG_SYN_CAPTURE_ONLY_NAMED_GROUP) &&
! OPTON_CAPTURE_GROUP(env->options)) {
return ONIGERR_NUMBERED_BACKREF_OR_CALL_NOT_ALLOWED;
}
if (gnum > env->num_mem) {
onig_scan_env_set_error_string(env, ONIGERR_UNDEFINED_GROUP_REFERENCE,
cn->name, cn->name_end);
return ONIGERR_UNDEFINED_GROUP_REFERENCE;
}
set_call_attr:
NODE_CALL_BODY(cn) = mem_env[cn->called_gnum].mem_node;
if (IS_NULL(NODE_CALL_BODY(cn))) {
onig_scan_env_set_error_string(env, ONIGERR_UNDEFINED_NAME_REFERENCE,
cn->name, cn->name_end);
return ONIGERR_UNDEFINED_NAME_REFERENCE;
}
NODE_STATUS_ADD(NODE_CALL_BODY(cn), REFERENCED);
}
else {
int *refs;
int n = onig_name_to_group_numbers(env->reg, cn->name, cn->name_end, &refs);
if (n <= 0) {
onig_scan_env_set_error_string(env, ONIGERR_UNDEFINED_NAME_REFERENCE,
cn->name, cn->name_end);
return ONIGERR_UNDEFINED_NAME_REFERENCE;
}
else if (n > 1) {
onig_scan_env_set_error_string(env, ONIGERR_MULTIPLEX_DEFINITION_NAME_CALL,
cn->name, cn->name_end);
return ONIGERR_MULTIPLEX_DEFINITION_NAME_CALL;
}
else {
cn->called_gnum = refs[0];
goto set_call_attr;
}
}
return 0;
}
static void
tune_call2_call(Node* node)
{
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
do {
tune_call2_call(NODE_CAR(node));
} while (IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_QUANT:
tune_call2_call(NODE_BODY(node));
break;
case NODE_ANCHOR:
if (ANCHOR_HAS_BODY(ANCHOR_(node)))
tune_call2_call(NODE_BODY(node));
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
if (en->type == BAG_MEMORY) {
if (! NODE_IS_MARK1(node)) {
NODE_STATUS_ADD(node, MARK1);
tune_call2_call(NODE_BODY(node));
NODE_STATUS_REMOVE(node, MARK1);
}
}
else if (en->type == BAG_IF_ELSE) {
tune_call2_call(NODE_BODY(node));
if (IS_NOT_NULL(en->te.Then))
tune_call2_call(en->te.Then);
if (IS_NOT_NULL(en->te.Else))
tune_call2_call(en->te.Else);
}
else {
tune_call2_call(NODE_BODY(node));
}
}
break;
case NODE_CALL:
if (! NODE_IS_MARK1(node)) {
NODE_STATUS_ADD(node, MARK1);
{
CallNode* cn = CALL_(node);
Node* called = NODE_CALL_BODY(cn);
cn->entry_count++;
NODE_STATUS_ADD(called, CALLED);
BAG_(called)->m.entry_count++;
tune_call2_call(called);
}
NODE_STATUS_REMOVE(node, MARK1);
}
break;
default:
break;
}
}
static int
tune_call(Node* node, ScanEnv* env, int state)
{
int r;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
do {
r = tune_call(NODE_CAR(node), env, state);
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_QUANT:
if (QUANT_(node)->upper == 0)
state |= IN_ZERO_REPEAT;
r = tune_call(NODE_BODY(node), env, state);
break;
case NODE_ANCHOR:
if (ANCHOR_HAS_BODY(ANCHOR_(node)))
r = tune_call(NODE_BODY(node), env, state);
else
r = 0;
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
if (en->type == BAG_MEMORY) {
if ((state & IN_ZERO_REPEAT) != 0) {
NODE_STATUS_ADD(node, IN_ZERO_REPEAT);
BAG_(node)->m.entry_count--;
}
r = tune_call(NODE_BODY(node), env, state);
}
else if (en->type == BAG_IF_ELSE) {
r = tune_call(NODE_BODY(node), env, state);
if (r != 0) return r;
if (IS_NOT_NULL(en->te.Then)) {
r = tune_call(en->te.Then, env, state);
if (r != 0) return r;
}
if (IS_NOT_NULL(en->te.Else))
r = tune_call(en->te.Else, env, state);
}
else
r = tune_call(NODE_BODY(node), env, state);
}
break;
case NODE_CALL:
if ((state & IN_ZERO_REPEAT) != 0) {
NODE_STATUS_ADD(node, IN_ZERO_REPEAT);
CALL_(node)->entry_count--;
}
r = check_call_reference(CALL_(node), env, state);
break;
default:
r = 0;
break;
}
return r;
}
static int
tune_call2(Node* node)
{
int r = 0;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
do {
r = tune_call2(NODE_CAR(node));
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_QUANT:
if (QUANT_(node)->upper != 0)
r = tune_call2(NODE_BODY(node));
break;
case NODE_ANCHOR:
if (ANCHOR_HAS_BODY(ANCHOR_(node)))
r = tune_call2(NODE_BODY(node));
break;
case NODE_BAG:
if (! NODE_IS_IN_ZERO_REPEAT(node))
r = tune_call2(NODE_BODY(node));
{
BagNode* en = BAG_(node);
if (r != 0) return r;
if (en->type == BAG_IF_ELSE) {
if (IS_NOT_NULL(en->te.Then)) {
r = tune_call2(en->te.Then);
if (r != 0) return r;
}
if (IS_NOT_NULL(en->te.Else))
r = tune_call2(en->te.Else);
}
}
break;
case NODE_CALL:
if (! NODE_IS_IN_ZERO_REPEAT(node)) {
tune_call2_call(node);
}
break;
default:
break;
}
return r;
}
static void
tune_called_state_call(Node* node, int state)
{
switch (NODE_TYPE(node)) {
case NODE_ALT:
state |= IN_ALT;
/* fall */
case NODE_LIST:
do {
tune_called_state_call(NODE_CAR(node), state);
} while (IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_QUANT:
{
QuantNode* qn = QUANT_(node);
if (IS_INFINITE_REPEAT(qn->upper) || qn->upper >= 2)
state |= IN_REAL_REPEAT;
if (qn->lower != qn->upper)
state |= IN_VAR_REPEAT;
tune_called_state_call(NODE_QUANT_BODY(qn), state);
}
break;
case NODE_ANCHOR:
{
AnchorNode* an = ANCHOR_(node);
switch (an->type) {
case ANCR_PREC_READ_NOT:
case ANCR_LOOK_BEHIND_NOT:
state |= IN_NOT;
/* fall */
case ANCR_PREC_READ:
case ANCR_LOOK_BEHIND:
tune_called_state_call(NODE_ANCHOR_BODY(an), state);
break;
default:
break;
}
}
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
if (en->type == BAG_MEMORY) {
if (NODE_IS_MARK1(node)) {
if ((~en->m.called_state & state) != 0) {
en->m.called_state |= state;
tune_called_state_call(NODE_BODY(node), state);
}
}
else {
NODE_STATUS_ADD(node, MARK1);
en->m.called_state |= state;
tune_called_state_call(NODE_BODY(node), state);
NODE_STATUS_REMOVE(node, MARK1);
}
}
else if (en->type == BAG_IF_ELSE) {
state |= IN_ALT;
tune_called_state_call(NODE_BODY(node), state);
if (IS_NOT_NULL(en->te.Then)) {
tune_called_state_call(en->te.Then, state);
}
if (IS_NOT_NULL(en->te.Else))
tune_called_state_call(en->te.Else, state);
}
else {
tune_called_state_call(NODE_BODY(node), state);
}
}
break;
case NODE_CALL:
tune_called_state_call(NODE_BODY(node), state);
break;
default:
break;
}
}
static void
tune_called_state(Node* node, int state)
{
switch (NODE_TYPE(node)) {
case NODE_ALT:
state |= IN_ALT;
/* fall */
case NODE_LIST:
do {
tune_called_state(NODE_CAR(node), state);
} while (IS_NOT_NULL(node = NODE_CDR(node)));
break;
#ifdef USE_CALL
case NODE_CALL:
tune_called_state_call(node, state);
break;
#endif
case NODE_BAG:
{
BagNode* en = BAG_(node);
switch (en->type) {
case BAG_MEMORY:
if (en->m.entry_count > 1)
state |= IN_MULTI_ENTRY;
en->m.called_state |= state;
/* fall */
case BAG_OPTION:
case BAG_STOP_BACKTRACK:
tune_called_state(NODE_BODY(node), state);
break;
case BAG_IF_ELSE:
state |= IN_ALT;
tune_called_state(NODE_BODY(node), state);
if (IS_NOT_NULL(en->te.Then))
tune_called_state(en->te.Then, state);
if (IS_NOT_NULL(en->te.Else))
tune_called_state(en->te.Else, state);
break;
}
}
break;
case NODE_QUANT:
{
QuantNode* qn = QUANT_(node);
if (IS_INFINITE_REPEAT(qn->upper) || qn->upper >= 2)
state |= IN_REAL_REPEAT;
if (qn->lower != qn->upper)
state |= IN_VAR_REPEAT;
tune_called_state(NODE_QUANT_BODY(qn), state);
}
break;
case NODE_ANCHOR:
{
AnchorNode* an = ANCHOR_(node);
switch (an->type) {
case ANCR_PREC_READ_NOT:
case ANCR_LOOK_BEHIND_NOT:
state |= IN_NOT;
/* fall */
case ANCR_PREC_READ:
case ANCR_LOOK_BEHIND:
tune_called_state(NODE_ANCHOR_BODY(an), state);
break;
default:
break;
}
}
break;
case NODE_BACKREF:
case NODE_STRING:
case NODE_CTYPE:
case NODE_CCLASS:
case NODE_GIMMICK:
default:
break;
}
}
#endif /* USE_CALL */
#ifdef __GNUC__
__inline
#endif
static int
tune_anchor(Node* node, regex_t* reg, int state, ScanEnv* env)
{
int r;
AnchorNode* an = ANCHOR_(node);
switch (an->type) {
case ANCR_PREC_READ:
r = tune_tree(NODE_ANCHOR_BODY(an), reg, state, env);
break;
case ANCR_PREC_READ_NOT:
r = tune_tree(NODE_ANCHOR_BODY(an), reg, (state | IN_NOT), env);
break;
case ANCR_LOOK_BEHIND:
case ANCR_LOOK_BEHIND_NOT:
r = tune_look_behind(node, reg, state, env);
break;
default:
r = 0;
break;
}
return r;
}
#ifdef __GNUC__
__inline
#endif
static int
tune_quant(Node* node, regex_t* reg, int state, ScanEnv* env)
{
int r;
QuantNode* qn = QUANT_(node);
Node* body = NODE_BODY(node);
if ((state & IN_REAL_REPEAT) != 0) {
NODE_STATUS_ADD(node, IN_REAL_REPEAT);
}
if ((state & IN_MULTI_ENTRY) != 0) {
NODE_STATUS_ADD(node, IN_MULTI_ENTRY);
}
if (IS_INFINITE_REPEAT(qn->upper) || qn->upper >= 1) {
OnigLen d = node_min_byte_len(body, env);
if (d == 0) {
#ifdef USE_STUBBORN_CHECK_CAPTURES_IN_EMPTY_REPEAT
qn->emptiness = quantifiers_memory_node_info(body);
#else
qn->emptiness = BODY_MAY_BE_EMPTY;
#endif
}
}
if (IS_INFINITE_REPEAT(qn->upper) || qn->upper >= 2)
state |= IN_REAL_REPEAT;
if (qn->lower != qn->upper)
state |= IN_VAR_REPEAT;
r = tune_tree(body, reg, state, env);
if (r != 0) return r;
/* expand string */
#define EXPAND_STRING_MAX_LENGTH 100
if (NODE_TYPE(body) == NODE_STRING) {
if (!IS_INFINITE_REPEAT(qn->lower) && qn->lower == qn->upper &&
qn->lower > 1 && qn->lower <= EXPAND_STRING_MAX_LENGTH) {
int len = NODE_STRING_LEN(body);
if (len * qn->lower <= EXPAND_STRING_MAX_LENGTH) {
int i, n = qn->lower;
node_conv_to_str_node(node, body);
for (i = 0; i < n; i++) {
r = node_str_node_cat(node, body);
if (r != 0) return r;
}
onig_node_free(body);
return r;
}
}
}
if (qn->greedy && (qn->emptiness == BODY_IS_NOT_EMPTY)) {
if (NODE_TYPE(body) == NODE_QUANT) {
QuantNode* tqn = QUANT_(body);
if (IS_NOT_NULL(tqn->head_exact)) {
qn->head_exact = tqn->head_exact;
tqn->head_exact = NULL;
}
}
else {
qn->head_exact = get_tree_head_literal(NODE_BODY(node), 1, reg);
}
}
return r;
}
/* tune_tree does the following work.
1. check empty loop. (set qn->emptiness)
2. expand ignore-case in char class.
3. set memory status bit flags. (reg->mem_stats)
4. set qn->head_exact for [push, exact] -> [push_or_jump_exact1, exact].
5. find invalid patterns in look-behind.
6. expand repeated string.
*/
static int
tune_tree(Node* node, regex_t* reg, int state, ScanEnv* env)
{
int r = 0;
switch (NODE_TYPE(node)) {
case NODE_LIST:
{
Node* prev = NULL_NODE;
do {
r = tune_tree(NODE_CAR(node), reg, state, env);
if (IS_NOT_NULL(prev) && r == 0) {
r = tune_next(prev, NODE_CAR(node), reg);
}
prev = NODE_CAR(node);
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
}
break;
case NODE_ALT:
do {
r = tune_tree(NODE_CAR(node), reg, (state | IN_ALT), env);
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_STRING:
if (NODE_IS_IGNORECASE(node) && ! NODE_STRING_IS_CRUDE(node)) {
r = unravel_case_fold_string(node, reg, state);
}
break;
case NODE_BACKREF:
{
int i;
int* p;
BackRefNode* br = BACKREF_(node);
p = BACKREFS_P(br);
for (i = 0; i < br->back_num; i++) {
if (p[i] > env->num_mem) return ONIGERR_INVALID_BACKREF;
MEM_STATUS_ON(env->backrefed_mem, p[i]);
#if 0
#ifdef USE_BACKREF_WITH_LEVEL
if (NODE_IS_NEST_LEVEL(node)) {
MEM_STATUS_ON(env->backtrack_mem, p[i]);
}
#endif
#else
/* More precisely, it should be checked whether alt/repeat exists before
the subject capture node, and then this backreference position
exists before (or in) the capture node. */
MEM_STATUS_ON(env->backtrack_mem, p[i]);
#endif
}
}
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
switch (en->type) {
case BAG_OPTION:
{
OnigOptionType options = reg->options;
reg->options = BAG_(node)->o.options;
r = tune_tree(NODE_BODY(node), reg, state, env);
reg->options = options;
}
break;
case BAG_MEMORY:
#ifdef USE_CALL
state |= en->m.called_state;
#endif
if ((state & (IN_ALT | IN_NOT | IN_VAR_REPEAT | IN_MULTI_ENTRY)) != 0
|| NODE_IS_RECURSION(node)) {
MEM_STATUS_ON(env->backtrack_mem, en->m.regnum);
}
r = tune_tree(NODE_BODY(node), reg, state, env);
break;
case BAG_STOP_BACKTRACK:
{
Node* target = NODE_BODY(node);
r = tune_tree(target, reg, state, env);
if (NODE_TYPE(target) == NODE_QUANT) {
QuantNode* tqn = QUANT_(target);
if (IS_INFINITE_REPEAT(tqn->upper) && tqn->lower <= 1 &&
tqn->greedy != 0) { /* (?>a*), a*+ etc... */
if (is_strict_real_node(NODE_BODY(target)))
NODE_STATUS_ADD(node, STRICT_REAL_REPEAT);
}
}
}
break;
case BAG_IF_ELSE:
r = tune_tree(NODE_BODY(node), reg, (state | IN_ALT), env);
if (r != 0) return r;
if (IS_NOT_NULL(en->te.Then)) {
r = tune_tree(en->te.Then, reg, (state | IN_ALT), env);
if (r != 0) return r;
}
if (IS_NOT_NULL(en->te.Else))
r = tune_tree(en->te.Else, reg, (state | IN_ALT), env);
break;
}
}
break;
case NODE_QUANT:
r = tune_quant(node, reg, state, env);
break;
case NODE_ANCHOR:
r = tune_anchor(node, reg, state, env);
break;
#ifdef USE_CALL
case NODE_CALL:
#endif
case NODE_CTYPE:
case NODE_CCLASS:
case NODE_GIMMICK:
default:
break;
}
return r;
}
static int
set_sunday_quick_search_or_bmh_skip_table(regex_t* reg, int case_expand,
UChar* s, UChar* end,
UChar skip[], int* roffset)
{
int i, j, k, len, offset;
int n, clen;
UChar* p;
OnigEncoding enc;
OnigCaseFoldCodeItem items[ONIGENC_GET_CASE_FOLD_CODES_MAX_NUM];
UChar buf[ONIGENC_MBC_CASE_FOLD_MAXLEN];
enc = reg->enc;
offset = ENC_GET_SKIP_OFFSET(enc);
if (offset == ENC_SKIP_OFFSET_1_OR_0) {
UChar* p = s;
while (1) {
len = enclen(enc, p);
if (p + len >= end) {
if (len == 1) offset = 1;
else offset = 0;
break;
}
p += len;
}
}
len = (int )(end - s);
if (len + offset >= UCHAR_MAX)
return ONIGERR_PARSER_BUG;
*roffset = offset;
for (i = 0; i < CHAR_MAP_SIZE; i++) {
skip[i] = (UChar )(len + offset);
}
for (p = s; p < end; ) {
int z;
clen = enclen(enc, p);
if (p + clen > end) clen = (int )(end - p);
len = (int )(end - p);
for (j = 0; j < clen; j++) {
z = len - j + (offset - 1);
if (z <= 0) break;
skip[p[j]] = z;
}
if (case_expand != 0) {
n = ONIGENC_GET_CASE_FOLD_CODES_BY_STR(enc, reg->case_fold_flag,
p, end, items);
for (k = 0; k < n; k++) {
ONIGENC_CODE_TO_MBC(enc, items[k].code[0], buf);
for (j = 0; j < clen; j++) {
z = len - j + (offset - 1);
if (z <= 0) break;
if (skip[buf[j]] > z)
skip[buf[j]] = z;
}
}
}
p += clen;
}
return 0;
}
#define OPT_EXACT_MAXLEN 24
#if OPT_EXACT_MAXLEN >= UCHAR_MAX
#error Too big OPT_EXACT_MAXLEN
#endif
typedef struct {
MinMaxLen mm;
OnigEncoding enc;
OnigCaseFoldType case_fold_flag;
ScanEnv* scan_env;
} OptEnv;
typedef struct {
int left;
int right;
} OptAnc;
typedef struct {
MinMaxLen mm; /* position */
OptAnc anc;
int reach_end;
int len;
UChar s[OPT_EXACT_MAXLEN];
} OptStr;
typedef struct {
MinMaxLen mm; /* position */
OptAnc anc;
int value; /* weighted value */
UChar map[CHAR_MAP_SIZE];
} OptMap;
typedef struct {
MinMaxLen len;
OptAnc anc;
OptStr sb; /* boundary */
OptStr sm; /* middle */
OptStr spr; /* prec read (?=...) */
OptMap map; /* boundary */
} OptNode;
static int
map_position_value(OnigEncoding enc, int i)
{
static const short int Vals[] = {
5, 1, 1, 1, 1, 1, 1, 1, 1, 10, 10, 1, 1, 10, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
12, 4, 7, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5,
5, 6, 6, 6, 6, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 6, 5, 5, 5,
5, 6, 6, 6, 6, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 1
};
if (i < (int )(sizeof(Vals)/sizeof(Vals[0]))) {
if (i == 0 && ONIGENC_MBC_MINLEN(enc) > 1)
return 20;
else
return (int )Vals[i];
}
else
return 4; /* Take it easy. */
}
static int
distance_value(MinMaxLen* mm)
{
/* 1000 / (min-max-dist + 1) */
static const short int dist_vals[] = {
1000, 500, 333, 250, 200, 167, 143, 125, 111, 100,
91, 83, 77, 71, 67, 63, 59, 56, 53, 50,
48, 45, 43, 42, 40, 38, 37, 36, 34, 33,
32, 31, 30, 29, 29, 28, 27, 26, 26, 25,
24, 24, 23, 23, 22, 22, 21, 21, 20, 20,
20, 19, 19, 19, 18, 18, 18, 17, 17, 17,
16, 16, 16, 16, 15, 15, 15, 15, 14, 14,
14, 14, 14, 14, 13, 13, 13, 13, 13, 13,
12, 12, 12, 12, 12, 12, 11, 11, 11, 11,
11, 11, 11, 11, 11, 10, 10, 10, 10, 10
};
OnigLen d;
if (mm->max == INFINITE_LEN) return 0;
d = mm->max - mm->min;
if (d < (OnigLen )(sizeof(dist_vals)/sizeof(dist_vals[0])))
/* return dist_vals[d] * 16 / (mm->min + 12); */
return (int )dist_vals[d];
else
return 1;
}
static int
comp_distance_value(MinMaxLen* d1, MinMaxLen* d2, int v1, int v2)
{
if (v2 <= 0) return -1;
if (v1 <= 0) return 1;
v1 *= distance_value(d1);
v2 *= distance_value(d2);
if (v2 > v1) return 1;
if (v2 < v1) return -1;
if (d2->min < d1->min) return 1;
if (d2->min > d1->min) return -1;
return 0;
}
static void
copy_opt_env(OptEnv* to, OptEnv* from)
{
*to = *from;
}
static void
clear_opt_anc_info(OptAnc* a)
{
a->left = 0;
a->right = 0;
}
static void
copy_opt_anc_info(OptAnc* to, OptAnc* from)
{
*to = *from;
}
static void
concat_opt_anc_info(OptAnc* to, OptAnc* left, OptAnc* right,
OnigLen left_len, OnigLen right_len)
{
clear_opt_anc_info(to);
to->left = left->left;
if (left_len == 0) {
to->left |= right->left;
}
to->right = right->right;
if (right_len == 0) {
to->right |= left->right;
}
else {
to->right |= (left->right & ANCR_PREC_READ_NOT);
}
}
static int
is_left(int a)
{
if (a == ANCR_END_BUF || a == ANCR_SEMI_END_BUF ||
a == ANCR_END_LINE || a == ANCR_PREC_READ || a == ANCR_PREC_READ_NOT)
return 0;
return 1;
}
static int
is_set_opt_anc_info(OptAnc* to, int anc)
{
if ((to->left & anc) != 0) return 1;
return ((to->right & anc) != 0 ? 1 : 0);
}
static void
add_opt_anc_info(OptAnc* to, int anc)
{
if (is_left(anc))
to->left |= anc;
else
to->right |= anc;
}
static void
remove_opt_anc_info(OptAnc* to, int anc)
{
if (is_left(anc))
to->left &= ~anc;
else
to->right &= ~anc;
}
static void
alt_merge_opt_anc_info(OptAnc* to, OptAnc* add)
{
to->left &= add->left;
to->right &= add->right;
}
static int
is_full_opt_exact(OptStr* e)
{
return e->len >= OPT_EXACT_MAXLEN;
}
static void
clear_opt_exact(OptStr* e)
{
mml_clear(&e->mm);
clear_opt_anc_info(&e->anc);
e->reach_end = 0;
e->len = 0;
e->s[0] = '\0';
}
static void
copy_opt_exact(OptStr* to, OptStr* from)
{
*to = *from;
}
static int
concat_opt_exact(OptStr* to, OptStr* add, OnigEncoding enc)
{
int i, j, len, r;
UChar *p, *end;
OptAnc tanc;
r = 0;
p = add->s;
end = p + add->len;
for (i = to->len; p < end; ) {
len = enclen(enc, p);
if (i + len > OPT_EXACT_MAXLEN) {
r = 1; /* 1:full */
break;
}
for (j = 0; j < len && p < end; j++)
to->s[i++] = *p++;
}
to->len = i;
to->reach_end = (p == end ? add->reach_end : 0);
concat_opt_anc_info(&tanc, &to->anc, &add->anc, 1, 1);
if (! to->reach_end) tanc.right = 0;
copy_opt_anc_info(&to->anc, &tanc);
return r;
}
static void
concat_opt_exact_str(OptStr* to, UChar* s, UChar* end, OnigEncoding enc)
{
int i, j, len;
UChar *p;
for (i = to->len, p = s; p < end && i < OPT_EXACT_MAXLEN; ) {
len = enclen(enc, p);
if (i + len >= OPT_EXACT_MAXLEN) break;
for (j = 0; j < len && p < end; j++)
to->s[i++] = *p++;
}
to->len = i;
if (p >= end)
to->reach_end = 1;
}
static void
alt_merge_opt_exact(OptStr* to, OptStr* add, OptEnv* env)
{
int i, j, len;
if (add->len == 0 || to->len == 0) {
clear_opt_exact(to);
return ;
}
if (! mml_is_equal(&to->mm, &add->mm)) {
clear_opt_exact(to);
return ;
}
for (i = 0; i < to->len && i < add->len; ) {
if (to->s[i] != add->s[i]) break;
len = enclen(env->enc, to->s + i);
for (j = 1; j < len; j++) {
if (to->s[i+j] != add->s[i+j]) break;
}
if (j < len) break;
i += len;
}
if (! add->reach_end || i < add->len || i < to->len) {
to->reach_end = 0;
}
to->len = i;
alt_merge_opt_anc_info(&to->anc, &add->anc);
if (! to->reach_end) to->anc.right = 0;
}
static void
select_opt_exact(OnigEncoding enc, OptStr* now, OptStr* alt)
{
int vn, va;
vn = now->len;
va = alt->len;
if (va == 0) {
return ;
}
else if (vn == 0) {
copy_opt_exact(now, alt);
return ;
}
else if (vn <= 2 && va <= 2) {
/* ByteValTable[x] is big value --> low price */
va = map_position_value(enc, now->s[0]);
vn = map_position_value(enc, alt->s[0]);
if (now->len > 1) vn += 5;
if (alt->len > 1) va += 5;
}
vn *= 2;
va *= 2;
if (comp_distance_value(&now->mm, &alt->mm, vn, va) > 0)
copy_opt_exact(now, alt);
}
static void
clear_opt_map(OptMap* map)
{
static const OptMap clean_info = {
{0, 0}, {0, 0}, 0,
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
}
};
xmemcpy(map, &clean_info, sizeof(OptMap));
}
static void
copy_opt_map(OptMap* to, OptMap* from)
{
*to = *from;
}
static void
add_char_opt_map(OptMap* m, UChar c, OnigEncoding enc)
{
if (m->map[c] == 0) {
m->map[c] = 1;
m->value += map_position_value(enc, c);
}
}
static void
select_opt_map(OptMap* now, OptMap* alt)
{
static int z = 1<<15; /* 32768: something big value */
int vn, va;
if (alt->value == 0) return ;
if (now->value == 0) {
copy_opt_map(now, alt);
return ;
}
vn = z / now->value;
va = z / alt->value;
if (comp_distance_value(&now->mm, &alt->mm, vn, va) > 0)
copy_opt_map(now, alt);
}
static int
comp_opt_exact_or_map(OptStr* e, OptMap* m)
{
#define COMP_EM_BASE 20
int ae, am;
int case_value;
if (m->value <= 0) return -1;
case_value = 3;
ae = COMP_EM_BASE * e->len * case_value;
am = COMP_EM_BASE * 5 * 2 / m->value;
return comp_distance_value(&e->mm, &m->mm, ae, am);
}
static void
alt_merge_opt_map(OnigEncoding enc, OptMap* to, OptMap* add)
{
int i, val;
/* if (! mml_is_equal(&to->mm, &add->mm)) return ; */
if (to->value == 0) return ;
if (add->value == 0 || to->mm.max < add->mm.min) {
clear_opt_map(to);
return ;
}
mml_alt_merge(&to->mm, &add->mm);
val = 0;
for (i = 0; i < CHAR_MAP_SIZE; i++) {
if (add->map[i])
to->map[i] = 1;
if (to->map[i])
val += map_position_value(enc, i);
}
to->value = val;
alt_merge_opt_anc_info(&to->anc, &add->anc);
}
static void
set_bound_node_opt_info(OptNode* opt, MinMaxLen* plen)
{
mml_copy(&(opt->sb.mm), plen);
mml_copy(&(opt->spr.mm), plen);
mml_copy(&(opt->map.mm), plen);
}
static void
clear_node_opt_info(OptNode* opt)
{
mml_clear(&opt->len);
clear_opt_anc_info(&opt->anc);
clear_opt_exact(&opt->sb);
clear_opt_exact(&opt->sm);
clear_opt_exact(&opt->spr);
clear_opt_map(&opt->map);
}
static void
copy_node_opt_info(OptNode* to, OptNode* from)
{
*to = *from;
}
static void
concat_left_node_opt_info(OnigEncoding enc, OptNode* to, OptNode* add)
{
int sb_reach, sm_reach;
OptAnc tanc;
concat_opt_anc_info(&tanc, &to->anc, &add->anc, to->len.max, add->len.max);
copy_opt_anc_info(&to->anc, &tanc);
if (add->sb.len > 0 && to->len.max == 0) {
concat_opt_anc_info(&tanc, &to->anc, &add->sb.anc, to->len.max, add->len.max);
copy_opt_anc_info(&add->sb.anc, &tanc);
}
if (add->map.value > 0 && to->len.max == 0) {
if (add->map.mm.max == 0)
add->map.anc.left |= to->anc.left;
}
sb_reach = to->sb.reach_end;
sm_reach = to->sm.reach_end;
if (add->len.max != 0)
to->sb.reach_end = to->sm.reach_end = 0;
if (add->sb.len > 0) {
if (sb_reach) {
concat_opt_exact(&to->sb, &add->sb, enc);
clear_opt_exact(&add->sb);
}
else if (sm_reach) {
concat_opt_exact(&to->sm, &add->sb, enc);
clear_opt_exact(&add->sb);
}
}
select_opt_exact(enc, &to->sm, &add->sb);
select_opt_exact(enc, &to->sm, &add->sm);
if (to->spr.len > 0) {
if (add->len.max > 0) {
if (to->spr.mm.max == 0)
select_opt_exact(enc, &to->sb, &to->spr);
else
select_opt_exact(enc, &to->sm, &to->spr);
}
}
else if (add->spr.len > 0) {
copy_opt_exact(&to->spr, &add->spr);
}
select_opt_map(&to->map, &add->map);
mml_add(&to->len, &add->len);
}
static void
alt_merge_node_opt_info(OptNode* to, OptNode* add, OptEnv* env)
{
alt_merge_opt_anc_info(&to->anc, &add->anc);
alt_merge_opt_exact(&to->sb, &add->sb, env);
alt_merge_opt_exact(&to->sm, &add->sm, env);
alt_merge_opt_exact(&to->spr, &add->spr, env);
alt_merge_opt_map(env->enc, &to->map, &add->map);
mml_alt_merge(&to->len, &add->len);
}
#define MAX_NODE_OPT_INFO_REF_COUNT 5
static int
optimize_nodes(Node* node, OptNode* opt, OptEnv* env)
{
int i;
int r;
OptNode xo;
OnigEncoding enc;
r = 0;
enc = env->enc;
clear_node_opt_info(opt);
set_bound_node_opt_info(opt, &env->mm);
switch (NODE_TYPE(node)) {
case NODE_LIST:
{
OptEnv nenv;
Node* nd = node;
copy_opt_env(&nenv, env);
do {
r = optimize_nodes(NODE_CAR(nd), &xo, &nenv);
if (r == 0) {
mml_add(&nenv.mm, &xo.len);
concat_left_node_opt_info(enc, opt, &xo);
}
} while (r == 0 && IS_NOT_NULL(nd = NODE_CDR(nd)));
}
break;
case NODE_ALT:
{
Node* nd = node;
do {
r = optimize_nodes(NODE_CAR(nd), &xo, env);
if (r == 0) {
if (nd == node) copy_node_opt_info(opt, &xo);
else alt_merge_node_opt_info(opt, &xo, env);
}
} while ((r == 0) && IS_NOT_NULL(nd = NODE_CDR(nd)));
}
break;
case NODE_STRING:
{
StrNode* sn = STR_(node);
int slen = (int )(sn->end - sn->s);
concat_opt_exact_str(&opt->sb, sn->s, sn->end, enc);
if (slen > 0) {
add_char_opt_map(&opt->map, *(sn->s), enc);
}
mml_set_min_max(&opt->len, slen, slen);
}
break;
case NODE_CCLASS:
{
int z;
CClassNode* cc = CCLASS_(node);
/* no need to check ignore case. (set in tune_tree()) */
if (IS_NOT_NULL(cc->mbuf) || IS_NCCLASS_NOT(cc)) {
OnigLen min = ONIGENC_MBC_MINLEN(enc);
OnigLen max = ONIGENC_MBC_MAXLEN_DIST(enc);
mml_set_min_max(&opt->len, min, max);
}
else {
for (i = 0; i < SINGLE_BYTE_SIZE; i++) {
z = BITSET_AT(cc->bs, i);
if ((z && ! IS_NCCLASS_NOT(cc)) || (! z && IS_NCCLASS_NOT(cc))) {
add_char_opt_map(&opt->map, (UChar )i, enc);
}
}
mml_set_min_max(&opt->len, 1, 1);
}
}
break;
case NODE_CTYPE:
{
int min, max;
int range;
max = ONIGENC_MBC_MAXLEN_DIST(enc);
if (max == 1) {
min = 1;
switch (CTYPE_(node)->ctype) {
case CTYPE_ANYCHAR:
break;
case ONIGENC_CTYPE_WORD:
range = CTYPE_(node)->ascii_mode != 0 ? 128 : SINGLE_BYTE_SIZE;
if (CTYPE_(node)->not != 0) {
for (i = 0; i < range; i++) {
if (! ONIGENC_IS_CODE_WORD(enc, i)) {
add_char_opt_map(&opt->map, (UChar )i, enc);
}
}
for (i = range; i < SINGLE_BYTE_SIZE; i++) {
add_char_opt_map(&opt->map, (UChar )i, enc);
}
}
else {
for (i = 0; i < range; i++) {
if (ONIGENC_IS_CODE_WORD(enc, i)) {
add_char_opt_map(&opt->map, (UChar )i, enc);
}
}
}
break;
}
}
else {
min = ONIGENC_MBC_MINLEN(enc);
}
mml_set_min_max(&opt->len, min, max);
}
break;
case NODE_ANCHOR:
switch (ANCHOR_(node)->type) {
case ANCR_BEGIN_BUF:
case ANCR_BEGIN_POSITION:
case ANCR_BEGIN_LINE:
case ANCR_END_BUF:
case ANCR_SEMI_END_BUF:
case ANCR_END_LINE:
case ANCR_PREC_READ_NOT:
case ANCR_LOOK_BEHIND:
add_opt_anc_info(&opt->anc, ANCHOR_(node)->type);
break;
case ANCR_PREC_READ:
{
r = optimize_nodes(NODE_BODY(node), &xo, env);
if (r == 0) {
if (xo.sb.len > 0)
copy_opt_exact(&opt->spr, &xo.sb);
else if (xo.sm.len > 0)
copy_opt_exact(&opt->spr, &xo.sm);
opt->spr.reach_end = 0;
if (xo.map.value > 0)
copy_opt_map(&opt->map, &xo.map);
}
}
break;
case ANCR_LOOK_BEHIND_NOT:
break;
}
break;
case NODE_BACKREF:
if (! NODE_IS_CHECKER(node)) {
OnigLen min, max;
min = node_min_byte_len(node, env->scan_env);
max = node_max_byte_len(node, env->scan_env);
mml_set_min_max(&opt->len, min, max);
}
break;
#ifdef USE_CALL
case NODE_CALL:
if (NODE_IS_RECURSION(node))
mml_set_min_max(&opt->len, 0, INFINITE_LEN);
else {
r = optimize_nodes(NODE_BODY(node), opt, env);
}
break;
#endif
case NODE_QUANT:
{
OnigLen min, max;
QuantNode* qn = QUANT_(node);
/* Issue #175
ex. /\g<1>{0}(?<=|())/
Empty and unused nodes in look-behind is removed in
tune_look_behind().
Called group nodes are assigned to be not called if the caller side is
inside of zero-repetition.
As a result, the nodes are considered unused.
*/
if (qn->upper == 0) {
mml_set_min_max(&opt->len, 0, 0);
break;
}
r = optimize_nodes(NODE_BODY(node), &xo, env);
if (r != 0) break;
if (qn->lower > 0) {
copy_node_opt_info(opt, &xo);
if (xo.sb.len > 0) {
if (xo.sb.reach_end) {
for (i = 2; i <= qn->lower && ! is_full_opt_exact(&opt->sb); i++) {
int rc = concat_opt_exact(&opt->sb, &xo.sb, enc);
if (rc > 0) break;
}
if (i < qn->lower) opt->sb.reach_end = 0;
}
}
if (qn->lower != qn->upper) {
opt->sb.reach_end = 0;
opt->sm.reach_end = 0;
}
if (qn->lower > 1)
opt->sm.reach_end = 0;
}
if (IS_INFINITE_REPEAT(qn->upper)) {
if (env->mm.max == 0 &&
NODE_IS_ANYCHAR(NODE_BODY(node)) && qn->greedy != 0) {
if (NODE_IS_MULTILINE(NODE_QUANT_BODY(qn)))
add_opt_anc_info(&opt->anc, ANCR_ANYCHAR_INF_ML);
else
add_opt_anc_info(&opt->anc, ANCR_ANYCHAR_INF);
}
max = (xo.len.max > 0 ? INFINITE_LEN : 0);
}
else {
max = distance_multiply(xo.len.max, qn->upper);
}
min = distance_multiply(xo.len.min, qn->lower);
mml_set_min_max(&opt->len, min, max);
}
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
switch (en->type) {
case BAG_STOP_BACKTRACK:
case BAG_OPTION:
r = optimize_nodes(NODE_BODY(node), opt, env);
break;
case BAG_MEMORY:
#ifdef USE_CALL
en->opt_count++;
if (en->opt_count > MAX_NODE_OPT_INFO_REF_COUNT) {
OnigLen min, max;
min = 0;
max = INFINITE_LEN;
if (NODE_IS_FIXED_MIN(node)) min = en->min_len;
if (NODE_IS_FIXED_MAX(node)) max = en->max_len;
mml_set_min_max(&opt->len, min, max);
}
else
#endif
{
r = optimize_nodes(NODE_BODY(node), opt, env);
if (is_set_opt_anc_info(&opt->anc, ANCR_ANYCHAR_INF_MASK)) {
if (MEM_STATUS_AT0(env->scan_env->backrefed_mem, en->m.regnum))
remove_opt_anc_info(&opt->anc, ANCR_ANYCHAR_INF_MASK);
}
}
break;
case BAG_IF_ELSE:
{
OptEnv nenv;
copy_opt_env(&nenv, env);
r = optimize_nodes(NODE_BAG_BODY(en), &xo, &nenv);
if (r == 0) {
mml_add(&nenv.mm, &xo.len);
concat_left_node_opt_info(enc, opt, &xo);
if (IS_NOT_NULL(en->te.Then)) {
r = optimize_nodes(en->te.Then, &xo, &nenv);
if (r == 0) {
concat_left_node_opt_info(enc, opt, &xo);
}
}
if (IS_NOT_NULL(en->te.Else)) {
r = optimize_nodes(en->te.Else, &xo, env);
if (r == 0)
alt_merge_node_opt_info(opt, &xo, env);
}
}
}
break;
}
}
break;
case NODE_GIMMICK:
break;
default:
#ifdef ONIG_DEBUG
fprintf(DBGFP, "optimize_nodes: undefined node type %d\n", NODE_TYPE(node));
#endif
r = ONIGERR_TYPE_BUG;
break;
}
return r;
}
static int
set_optimize_exact(regex_t* reg, OptStr* e)
{
int r;
int allow_reverse;
if (e->len == 0) return 0;
reg->exact = (UChar* )xmalloc(e->len);
CHECK_NULL_RETURN_MEMERR(reg->exact);
xmemcpy(reg->exact, e->s, e->len);
reg->exact_end = reg->exact + e->len;
allow_reverse =
ONIGENC_IS_ALLOWED_REVERSE_MATCH(reg->enc, reg->exact, reg->exact_end);
if (e->len >= 2 || (e->len >= 1 && allow_reverse)) {
r = set_sunday_quick_search_or_bmh_skip_table(reg, 0,
reg->exact, reg->exact_end,
reg->map, &(reg->map_offset));
if (r != 0) return r;
reg->optimize = (allow_reverse != 0
? OPTIMIZE_STR_FAST
: OPTIMIZE_STR_FAST_STEP_FORWARD);
}
else {
reg->optimize = OPTIMIZE_STR;
}
reg->dist_min = e->mm.min;
reg->dist_max = e->mm.max;
if (reg->dist_min != INFINITE_LEN) {
int n = (int )(reg->exact_end - reg->exact);
reg->threshold_len = reg->dist_min + n;
}
return 0;
}
static void
set_optimize_map(regex_t* reg, OptMap* m)
{
int i;
for (i = 0; i < CHAR_MAP_SIZE; i++)
reg->map[i] = m->map[i];
reg->optimize = OPTIMIZE_MAP;
reg->dist_min = m->mm.min;
reg->dist_max = m->mm.max;
if (reg->dist_min != INFINITE_LEN) {
reg->threshold_len = reg->dist_min + ONIGENC_MBC_MINLEN(reg->enc);
}
}
static void
set_sub_anchor(regex_t* reg, OptAnc* anc)
{
reg->sub_anchor |= anc->left & ANCR_BEGIN_LINE;
reg->sub_anchor |= anc->right & ANCR_END_LINE;
}
#if defined(ONIG_DEBUG_COMPILE) || defined(ONIG_DEBUG_MATCH)
static void print_optimize_info(FILE* f, regex_t* reg);
#endif
static int
set_optimize_info_from_tree(Node* node, regex_t* reg, ScanEnv* scan_env)
{
int r;
OptNode opt;
OptEnv env;
env.enc = reg->enc;
env.case_fold_flag = reg->case_fold_flag;
env.scan_env = scan_env;
mml_clear(&env.mm);
r = optimize_nodes(node, &opt, &env);
if (r != 0) return r;
reg->anchor = opt.anc.left & (ANCR_BEGIN_BUF |
ANCR_BEGIN_POSITION | ANCR_ANYCHAR_INF | ANCR_ANYCHAR_INF_ML |
ANCR_LOOK_BEHIND);
if ((opt.anc.left & (ANCR_LOOK_BEHIND | ANCR_PREC_READ_NOT)) != 0)
reg->anchor &= ~ANCR_ANYCHAR_INF_ML;
reg->anchor |= opt.anc.right & (ANCR_END_BUF | ANCR_SEMI_END_BUF |
ANCR_PREC_READ_NOT);
if (reg->anchor & (ANCR_END_BUF | ANCR_SEMI_END_BUF)) {
reg->anc_dist_min = opt.len.min;
reg->anc_dist_max = opt.len.max;
}
if (opt.sb.len > 0 || opt.sm.len > 0) {
select_opt_exact(reg->enc, &opt.sb, &opt.sm);
if (opt.map.value > 0 && comp_opt_exact_or_map(&opt.sb, &opt.map) > 0) {
goto set_map;
}
else {
r = set_optimize_exact(reg, &opt.sb);
set_sub_anchor(reg, &opt.sb.anc);
}
}
else if (opt.map.value > 0) {
set_map:
set_optimize_map(reg, &opt.map);
set_sub_anchor(reg, &opt.map.anc);
}
else {
reg->sub_anchor |= opt.anc.left & ANCR_BEGIN_LINE;
if (opt.len.max == 0)
reg->sub_anchor |= opt.anc.right & ANCR_END_LINE;
}
#if defined(ONIG_DEBUG_COMPILE) || defined(ONIG_DEBUG_MATCH)
print_optimize_info(DBGFP, reg);
#endif
return r;
}
static void
clear_optimize_info(regex_t* reg)
{
reg->optimize = OPTIMIZE_NONE;
reg->anchor = 0;
reg->anc_dist_min = 0;
reg->anc_dist_max = 0;
reg->sub_anchor = 0;
reg->exact_end = (UChar* )NULL;
reg->map_offset = 0;
reg->threshold_len = 0;
if (IS_NOT_NULL(reg->exact)) {
xfree(reg->exact);
reg->exact = (UChar* )NULL;
}
}
#ifdef ONIG_DEBUG
static void print_enc_string(FILE* fp, OnigEncoding enc,
const UChar *s, const UChar *end)
{
if (ONIGENC_MBC_MINLEN(enc) > 1) {
const UChar *p;
OnigCodePoint code;
p = s;
while (p < end) {
code = ONIGENC_MBC_TO_CODE(enc, p, end);
if (code >= 0x80) {
fprintf(fp, " 0x%04x ", (int )code);
}
else {
fputc((int )code, fp);
}
p += enclen(enc, p);
}
}
else {
while (s < end) {
fputc((int )*s, fp);
s++;
}
}
fprintf(fp, "/\n");
}
#endif /* ONIG_DEBUG */
#if defined(ONIG_DEBUG_COMPILE) || defined(ONIG_DEBUG_MATCH)
static void
print_distance_range(FILE* f, OnigLen a, OnigLen b)
{
if (a == INFINITE_LEN)
fputs("inf", f);
else
fprintf(f, "(%u)", a);
fputs("-", f);
if (b == INFINITE_LEN)
fputs("inf", f);
else
fprintf(f, "(%u)", b);
}
static void
print_anchor(FILE* f, int anchor)
{
int q = 0;
fprintf(f, "[");
if (anchor & ANCR_BEGIN_BUF) {
fprintf(f, "begin-buf");
q = 1;
}
if (anchor & ANCR_BEGIN_LINE) {
if (q) fprintf(f, ", ");
q = 1;
fprintf(f, "begin-line");
}
if (anchor & ANCR_BEGIN_POSITION) {
if (q) fprintf(f, ", ");
q = 1;
fprintf(f, "begin-pos");
}
if (anchor & ANCR_END_BUF) {
if (q) fprintf(f, ", ");
q = 1;
fprintf(f, "end-buf");
}
if (anchor & ANCR_SEMI_END_BUF) {
if (q) fprintf(f, ", ");
q = 1;
fprintf(f, "semi-end-buf");
}
if (anchor & ANCR_END_LINE) {
if (q) fprintf(f, ", ");
q = 1;
fprintf(f, "end-line");
}
if (anchor & ANCR_ANYCHAR_INF) {
if (q) fprintf(f, ", ");
q = 1;
fprintf(f, "anychar-inf");
}
if (anchor & ANCR_ANYCHAR_INF_ML) {
if (q) fprintf(f, ", ");
fprintf(f, "anychar-inf-ml");
}
fprintf(f, "]");
}
static void
print_optimize_info(FILE* f, regex_t* reg)
{
static const char* on[] =
{ "NONE", "STR", "STR_FAST", "STR_FAST_STEP_FORWARD", "MAP" };
fprintf(f, "optimize: %s\n", on[reg->optimize]);
fprintf(f, " anchor: "); print_anchor(f, reg->anchor);
if ((reg->anchor & ANCR_END_BUF_MASK) != 0)
print_distance_range(f, reg->anc_dist_min, reg->anc_dist_max);
fprintf(f, "\n");
if (reg->optimize) {
fprintf(f, " sub anchor: "); print_anchor(f, reg->sub_anchor);
fprintf(f, "\n");
}
fprintf(f, "\n");
if (reg->exact) {
UChar *p;
fprintf(f, "exact: [");
for (p = reg->exact; p < reg->exact_end; p++) {
fputc(*p, f);
}
fprintf(f, "]: length: %ld, dmin: %u, ",
(reg->exact_end - reg->exact), reg->dist_min);
if (reg->dist_max == INFINITE_LEN)
fprintf(f, "dmax: inf.\n");
else
fprintf(f, "dmax: %u\n", reg->dist_max);
}
else if (reg->optimize & OPTIMIZE_MAP) {
int c, i, n = 0;
for (i = 0; i < CHAR_MAP_SIZE; i++)
if (reg->map[i]) n++;
fprintf(f, "map: n=%d, dmin: %u, dmax: %u\n",
n, reg->dist_min, reg->dist_max);
if (n > 0) {
c = 0;
fputc('[', f);
for (i = 0; i < CHAR_MAP_SIZE; i++) {
if (reg->map[i] != 0) {
if (c > 0) fputs(", ", f);
c++;
if (ONIGENC_MBC_MAXLEN(reg->enc) == 1 &&
ONIGENC_IS_CODE_PRINT(reg->enc, (OnigCodePoint )i))
fputc(i, f);
else
fprintf(f, "%d", i);
}
}
fprintf(f, "]\n");
}
}
}
#endif
extern RegexExt*
onig_get_regex_ext(regex_t* reg)
{
if (IS_NULL(reg->extp)) {
RegexExt* ext = (RegexExt* )xmalloc(sizeof(*ext));
if (IS_NULL(ext)) return 0;
ext->pattern = 0;
ext->pattern_end = 0;
#ifdef USE_CALLOUT
ext->tag_table = 0;
ext->callout_num = 0;
ext->callout_list_alloc = 0;
ext->callout_list = 0;
#endif
reg->extp = ext;
}
return reg->extp;
}
static void
free_regex_ext(RegexExt* ext)
{
if (IS_NOT_NULL(ext)) {
if (IS_NOT_NULL(ext->pattern))
xfree((void* )ext->pattern);
#ifdef USE_CALLOUT
if (IS_NOT_NULL(ext->tag_table))
onig_callout_tag_table_free(ext->tag_table);
if (IS_NOT_NULL(ext->callout_list))
onig_free_reg_callout_list(ext->callout_num, ext->callout_list);
#endif
xfree(ext);
}
}
extern int
onig_ext_set_pattern(regex_t* reg, const UChar* pattern, const UChar* pattern_end)
{
RegexExt* ext;
UChar* s;
ext = onig_get_regex_ext(reg);
CHECK_NULL_RETURN_MEMERR(ext);
s = onigenc_strdup(reg->enc, pattern, pattern_end);
CHECK_NULL_RETURN_MEMERR(s);
ext->pattern = s;
ext->pattern_end = s + (pattern_end - pattern);
return ONIG_NORMAL;
}
extern void
onig_free_body(regex_t* reg)
{
if (IS_NOT_NULL(reg)) {
ops_free(reg);
if (IS_NOT_NULL(reg->string_pool)) {
xfree(reg->string_pool);
reg->string_pool_end = reg->string_pool = 0;
}
if (IS_NOT_NULL(reg->exact)) xfree(reg->exact);
if (IS_NOT_NULL(reg->repeat_range)) xfree(reg->repeat_range);
if (IS_NOT_NULL(reg->extp)) {
free_regex_ext(reg->extp);
reg->extp = 0;
}
onig_names_free(reg);
}
}
extern void
onig_free(regex_t* reg)
{
if (IS_NOT_NULL(reg)) {
onig_free_body(reg);
xfree(reg);
}
}
#ifdef ONIG_DEBUG_PARSE
static void print_tree P_((FILE* f, Node* node));
#endif
extern int onig_init_for_match_at(regex_t* reg);
extern int
onig_compile(regex_t* reg, const UChar* pattern, const UChar* pattern_end,
OnigErrorInfo* einfo)
{
int r;
Node* root;
ScanEnv scan_env;
#ifdef USE_CALL
UnsetAddrList uslist = {0};
#endif
root = 0;
if (IS_NOT_NULL(einfo)) {
einfo->enc = reg->enc;
einfo->par = (UChar* )NULL;
}
#ifdef ONIG_DEBUG
fprintf(DBGFP, "\nPATTERN: /");
print_enc_string(DBGFP, reg->enc, pattern, pattern_end);
#endif
if (reg->ops_alloc == 0) {
r = ops_init(reg, OPS_INIT_SIZE);
if (r != 0) goto end;
}
else
reg->ops_used = 0;
r = onig_parse_tree(&root, pattern, pattern_end, reg, &scan_env);
if (r != 0) goto err;
r = reduce_string_list(root, reg->enc);
if (r != 0) goto err;
/* mixed use named group and no-named group */
if (scan_env.num_named > 0 &&
IS_SYNTAX_BV(scan_env.syntax, ONIG_SYN_CAPTURE_ONLY_NAMED_GROUP) &&
! OPTON_CAPTURE_GROUP(reg->options)) {
if (scan_env.num_named != scan_env.num_mem)
r = disable_noname_group_capture(&root, reg, &scan_env);
else
r = numbered_ref_check(root);
if (r != 0) goto err;
}
r = check_backrefs(root, &scan_env);
if (r != 0) goto err;
#ifdef USE_CALL
if (scan_env.num_call > 0) {
r = unset_addr_list_init(&uslist, scan_env.num_call);
if (r != 0) goto err;
scan_env.unset_addr_list = &uslist;
r = tune_call(root, &scan_env, 0);
if (r != 0) goto err_unset;
r = tune_call2(root);
if (r != 0) goto err_unset;
r = recursive_call_check_trav(root, &scan_env, 0);
if (r < 0) goto err_unset;
r = infinite_recursive_call_check_trav(root, &scan_env);
if (r != 0) goto err_unset;
tune_called_state(root, 0);
}
reg->num_call = scan_env.num_call;
#endif
#ifdef ONIG_DEBUG_PARSE
fprintf(DBGFP, "MAX PARSE DEPTH: %d\n", scan_env.max_parse_depth);
fprintf(DBGFP, "TREE (parsed)\n");
print_tree(DBGFP, root);
fprintf(DBGFP, "\n");
#endif
r = tune_tree(root, reg, 0, &scan_env);
if (r != 0) goto err_unset;
if (scan_env.backref_num != 0) {
set_parent_node_trav(root, NULL_NODE);
r = set_empty_repeat_node_trav(root, NULL_NODE, &scan_env);
if (r != 0) goto err_unset;
set_empty_status_check_trav(root, &scan_env);
}
#ifdef ONIG_DEBUG_PARSE
fprintf(DBGFP, "TREE (after tune)\n");
print_tree(DBGFP, root);
fprintf(DBGFP, "\n");
#endif
reg->capture_history = scan_env.cap_history;
reg->push_mem_start = scan_env.backtrack_mem | scan_env.cap_history;
#ifdef USE_CALLOUT
if (IS_NOT_NULL(reg->extp) && reg->extp->callout_num != 0) {
reg->push_mem_end = reg->push_mem_start;
}
else {
if (MEM_STATUS_IS_ALL_ON(reg->push_mem_start))
reg->push_mem_end = scan_env.backrefed_mem | scan_env.cap_history;
else
reg->push_mem_end = reg->push_mem_start &
(scan_env.backrefed_mem | scan_env.cap_history);
}
#else
if (MEM_STATUS_IS_ALL_ON(reg->push_mem_start))
reg->push_mem_end = scan_env.backrefed_mem | scan_env.cap_history;
else
reg->push_mem_end = reg->push_mem_start &
(scan_env.backrefed_mem | scan_env.cap_history);
#endif
clear_optimize_info(reg);
#ifndef ONIG_DONT_OPTIMIZE
r = set_optimize_info_from_tree(root, reg, &scan_env);
if (r != 0) goto err_unset;
#endif
if (IS_NOT_NULL(scan_env.mem_env_dynamic)) {
xfree(scan_env.mem_env_dynamic);
scan_env.mem_env_dynamic = (MemEnv* )NULL;
}
r = compile_tree(root, reg, &scan_env);
if (r == 0) {
if (scan_env.keep_num > 0) {
r = add_op(reg, OP_UPDATE_VAR);
if (r != 0) goto err;
COP(reg)->update_var.type = UPDATE_VAR_KEEP_FROM_STACK_LAST;
COP(reg)->update_var.id = 0; /* not used */
COP(reg)->update_var.clear = FALSE;
}
r = add_op(reg, OP_END);
if (r != 0) goto err;
#ifdef USE_CALL
if (scan_env.num_call > 0) {
r = fix_unset_addr_list(&uslist, reg);
unset_addr_list_end(&uslist);
if (r != 0) goto err;
}
#endif
set_addr_in_repeat_range(reg);
if ((reg->push_mem_end != 0)
#ifdef USE_REPEAT_AND_EMPTY_CHECK_LOCAL_VAR
|| (reg->num_repeat != 0)
|| (reg->num_empty_check != 0)
#endif
#ifdef USE_CALLOUT
|| (IS_NOT_NULL(reg->extp) && reg->extp->callout_num != 0)
#endif
#ifdef USE_CALL
|| scan_env.num_call > 0
#endif
)
reg->stack_pop_level = STACK_POP_LEVEL_ALL;
else {
if (reg->push_mem_start != 0)
reg->stack_pop_level = STACK_POP_LEVEL_MEM_START;
else
reg->stack_pop_level = STACK_POP_LEVEL_FREE;
}
r = ops_make_string_pool(reg);
if (r != 0) goto err;
}
#ifdef USE_CALL
else if (scan_env.num_call > 0) {
unset_addr_list_end(&uslist);
}
#endif
onig_node_free(root);
#ifdef ONIG_DEBUG_COMPILE
onig_print_names(DBGFP, reg);
onig_print_compiled_byte_code_list(DBGFP, reg);
#endif
#ifdef USE_DIRECT_THREADED_CODE
/* opcode -> opaddr */
onig_init_for_match_at(reg);
#endif
end:
return r;
err_unset:
#ifdef USE_CALL
if (scan_env.num_call > 0) {
unset_addr_list_end(&uslist);
}
#endif
err:
if (IS_NOT_NULL(scan_env.error)) {
if (IS_NOT_NULL(einfo)) {
einfo->par = scan_env.error;
einfo->par_end = scan_env.error_end;
}
}
onig_node_free(root);
if (IS_NOT_NULL(scan_env.mem_env_dynamic))
xfree(scan_env.mem_env_dynamic);
return r;
}
static int onig_inited = 0;
extern int
onig_reg_init(regex_t* reg, OnigOptionType option, OnigCaseFoldType case_fold_flag,
OnigEncoding enc, OnigSyntaxType* syntax)
{
int r;
xmemset(reg, 0, sizeof(*reg));
if (onig_inited == 0) {
#if 0
return ONIGERR_LIBRARY_IS_NOT_INITIALIZED;
#else
r = onig_initialize(&enc, 1);
if (r != 0)
return ONIGERR_FAIL_TO_INITIALIZE;
onig_warning("You didn't call onig_initialize() explicitly");
#endif
}
if (IS_NULL(reg))
return ONIGERR_INVALID_ARGUMENT;
if (ONIGENC_IS_UNDEF(enc))
return ONIGERR_DEFAULT_ENCODING_IS_NOT_SETTED;
if ((option & (ONIG_OPTION_DONT_CAPTURE_GROUP|ONIG_OPTION_CAPTURE_GROUP))
== (ONIG_OPTION_DONT_CAPTURE_GROUP|ONIG_OPTION_CAPTURE_GROUP)) {
return ONIGERR_INVALID_COMBINATION_OF_OPTIONS;
}
if ((option & ONIG_OPTION_NEGATE_SINGLELINE) != 0) {
option |= syntax->options;
option &= ~ONIG_OPTION_SINGLELINE;
}
else
option |= syntax->options;
(reg)->enc = enc;
(reg)->options = option;
(reg)->syntax = syntax;
(reg)->optimize = 0;
(reg)->exact = (UChar* )NULL;
(reg)->extp = (RegexExt* )NULL;
(reg)->ops = (Operation* )NULL;
(reg)->ops_curr = (Operation* )NULL;
(reg)->ops_used = 0;
(reg)->ops_alloc = 0;
(reg)->name_table = (void* )NULL;
(reg)->case_fold_flag = case_fold_flag;
return 0;
}
extern int
onig_new_without_alloc(regex_t* reg,
const UChar* pattern, const UChar* pattern_end,
OnigOptionType option, OnigEncoding enc,
OnigSyntaxType* syntax, OnigErrorInfo* einfo)
{
int r;
r = onig_reg_init(reg, option, ONIGENC_CASE_FOLD_DEFAULT, enc, syntax);
if (r != 0) return r;
r = onig_compile(reg, pattern, pattern_end, einfo);
return r;
}
extern int
onig_new(regex_t** reg, const UChar* pattern, const UChar* pattern_end,
OnigOptionType option, OnigEncoding enc, OnigSyntaxType* syntax,
OnigErrorInfo* einfo)
{
int r;
*reg = (regex_t* )xmalloc(sizeof(regex_t));
if (IS_NULL(*reg)) return ONIGERR_MEMORY;
r = onig_reg_init(*reg, option, ONIGENC_CASE_FOLD_DEFAULT, enc, syntax);
if (r != 0) {
xfree(*reg);
*reg = NULL;
return r;
}
r = onig_compile(*reg, pattern, pattern_end, einfo);
if (r != 0) {
onig_free(*reg);
*reg = NULL;
}
return r;
}
extern int
onig_initialize(OnigEncoding encodings[], int n)
{
int i;
int r;
if (onig_inited != 0)
return 0;
onigenc_init();
onig_inited = 1;
for (i = 0; i < n; i++) {
OnigEncoding enc = encodings[i];
r = onig_initialize_encoding(enc);
if (r != 0)
return r;
}
return ONIG_NORMAL;
}
typedef struct EndCallListItem {
struct EndCallListItem* next;
void (*func)(void);
} EndCallListItemType;
static EndCallListItemType* EndCallTop;
extern void onig_add_end_call(void (*func)(void))
{
EndCallListItemType* item;
item = (EndCallListItemType* )xmalloc(sizeof(*item));
if (item == 0) return ;
item->next = EndCallTop;
item->func = func;
EndCallTop = item;
}
static void
exec_end_call_list(void)
{
EndCallListItemType* prev;
void (*func)(void);
while (EndCallTop != 0) {
func = EndCallTop->func;
(*func)();
prev = EndCallTop;
EndCallTop = EndCallTop->next;
xfree(prev);
}
}
extern int
onig_end(void)
{
exec_end_call_list();
#ifdef USE_CALLOUT
onig_global_callout_names_free();
#endif
onigenc_end();
onig_inited = 0;
return 0;
}
extern int
onig_is_in_code_range(const UChar* p, OnigCodePoint code)
{
OnigCodePoint n, *data;
OnigCodePoint low, high, x;
GET_CODE_POINT(n, p);
data = (OnigCodePoint* )p;
data++;
for (low = 0, high = n; low < high; ) {
x = (low + high) >> 1;
if (code > data[x * 2 + 1])
low = x + 1;
else
high = x;
}
return ((low < n && code >= data[low * 2]) ? 1 : 0);
}
extern int
onig_is_code_in_cc_len(int elen, OnigCodePoint code, /* CClassNode* */ void* cc_arg)
{
int found;
CClassNode* cc = (CClassNode* )cc_arg;
if (elen > 1 || (code >= SINGLE_BYTE_SIZE)) {
if (IS_NULL(cc->mbuf)) {
found = 0;
}
else {
found = onig_is_in_code_range(cc->mbuf->p, code) != 0;
}
}
else {
found = BITSET_AT(cc->bs, code) != 0;
}
if (IS_NCCLASS_NOT(cc))
return !found;
else
return found;
}
extern int
onig_is_code_in_cc(OnigEncoding enc, OnigCodePoint code, CClassNode* cc)
{
int len;
if (ONIGENC_MBC_MINLEN(enc) > 1) {
len = 2;
}
else {
len = ONIGENC_CODE_TO_MBCLEN(enc, code);
if (len < 0) return 0;
}
return onig_is_code_in_cc_len(len, code, cc);
}
typedef struct {
int prec_read;
int look_behind;
int backref_with_level;
int call;
} SlowElementCount;
static int
node_detect_can_be_slow(Node* node, SlowElementCount* ct)
{
int r;
r = 0;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
do {
r = node_detect_can_be_slow(NODE_CAR(node), ct);
if (r != 0) return r;
} while (IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_QUANT:
r = node_detect_can_be_slow(NODE_BODY(node), ct);
break;
case NODE_ANCHOR:
switch (ANCHOR_(node)->type) {
case ANCR_PREC_READ:
case ANCR_PREC_READ_NOT:
ct->prec_read++;
break;
case ANCR_LOOK_BEHIND:
case ANCR_LOOK_BEHIND_NOT:
ct->look_behind++;
break;
default:
break;
}
if (ANCHOR_HAS_BODY(ANCHOR_(node)))
r = node_detect_can_be_slow(NODE_BODY(node), ct);
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
r = node_detect_can_be_slow(NODE_BODY(node), ct);
if (r != 0) return r;
if (en->type == BAG_IF_ELSE) {
if (IS_NOT_NULL(en->te.Then)) {
r = node_detect_can_be_slow(en->te.Then, ct);
if (r != 0) return r;
}
if (IS_NOT_NULL(en->te.Else)) {
r = node_detect_can_be_slow(en->te.Else, ct);
if (r != 0) return r;
}
}
}
break;
#ifdef USE_BACKREF_WITH_LEVEL
case NODE_BACKREF:
if (NODE_IS_NEST_LEVEL(node))
ct->backref_with_level++;
break;
#endif
#ifdef USE_CALL
case NODE_CALL:
ct->call++;
break;
#endif
default:
break;
}
return r;
}
extern int
onig_detect_can_be_slow_pattern(const UChar* pattern,
const UChar* pattern_end, OnigOptionType option, OnigEncoding enc,
OnigSyntaxType* syntax)
{
int r;
regex_t* reg;
Node* root;
ScanEnv scan_env;
SlowElementCount count;
reg = (regex_t* )xmalloc(sizeof(regex_t));
if (IS_NULL(reg)) return ONIGERR_MEMORY;
r = onig_reg_init(reg, option, ONIGENC_CASE_FOLD_DEFAULT, enc, syntax);
if (r != 0) {
xfree(reg);
return r;
}
root = 0;
r = onig_parse_tree(&root, pattern, pattern_end, reg, &scan_env);
if (r == 0) {
count.prec_read = 0;
count.look_behind = 0;
count.backref_with_level = 0;
count.call = 0;
r = node_detect_can_be_slow(root, &count);
if (r == 0) {
int n = count.prec_read + count.look_behind
+ count.backref_with_level + count.call;
r = n;
}
}
if (IS_NOT_NULL(scan_env.mem_env_dynamic))
xfree(scan_env.mem_env_dynamic);
onig_node_free(root);
onig_free(reg);
return r;
}
#ifdef ONIG_DEBUG_PARSE
#ifdef USE_CALL
static void
p_string(FILE* f, int len, UChar* s)
{
fputs(":", f);
while (len-- > 0) { fputc(*s++, f); }
}
#endif
static void
Indent(FILE* f, int indent)
{
int i;
for (i = 0; i < indent; i++) putc(' ', f);
}
static void
print_indent_tree(FILE* f, Node* node, int indent)
{
int i;
NodeType type;
UChar* p;
int add = 3;
Indent(f, indent);
if (IS_NULL(node)) {
fprintf(f, "ERROR: null node!!!\n");
exit(0);
}
type = NODE_TYPE(node);
switch (type) {
case NODE_LIST:
case NODE_ALT:
if (type == NODE_LIST)
fprintf(f, "<list:%p>\n", node);
else
fprintf(f, "<alt:%p>\n", node);
print_indent_tree(f, NODE_CAR(node), indent + add);
while (IS_NOT_NULL(node = NODE_CDR(node))) {
if (NODE_TYPE(node) != type) {
fprintf(f, "ERROR: list/alt right is not a cons. %d\n", NODE_TYPE(node));
exit(0);
}
print_indent_tree(f, NODE_CAR(node), indent + add);
}
break;
case NODE_STRING:
{
char* str;
char* mode;
if (NODE_STRING_IS_CRUDE(node))
mode = "-crude";
else if (NODE_IS_IGNORECASE(node))
mode = "-ignorecase";
else
mode = "";
if (STR_(node)->s == STR_(node)->end)
str = "empty-string";
else
str = "string";
fprintf(f, "<%s%s:%p>", str, mode, node);
for (p = STR_(node)->s; p < STR_(node)->end; p++) {
if (*p >= 0x20 && *p < 0x7f)
fputc(*p, f);
else {
fprintf(f, " 0x%02x", *p);
}
}
}
break;
case NODE_CCLASS:
#define CCLASS_MBUF_MAX_OUTPUT_NUM 10
fprintf(f, "<cclass:%p>", node);
if (IS_NCCLASS_NOT(CCLASS_(node))) fputs(" not", f);
if (CCLASS_(node)->mbuf) {
BBuf* bbuf = CCLASS_(node)->mbuf;
fprintf(f, " mbuf(%u) ", bbuf->used);
for (i = 0; i < bbuf->used && i < CCLASS_MBUF_MAX_OUTPUT_NUM; i++) {
if (i > 0) fprintf(f, ",");
fprintf(f, "%0x", bbuf->p[i]);
}
if (i < bbuf->used) fprintf(f, "...");
}
break;
case NODE_CTYPE:
fprintf(f, "<ctype:%p> ", node);
switch (CTYPE_(node)->ctype) {
case CTYPE_ANYCHAR:
fprintf(f, "anychar");
break;
case ONIGENC_CTYPE_WORD:
if (CTYPE_(node)->not != 0)
fputs("not word", f);
else
fputs("word", f);
if (CTYPE_(node)->ascii_mode != 0)
fputs(" (ascii)", f);
break;
default:
fprintf(f, "ERROR: undefined ctype.\n");
exit(0);
}
break;
case NODE_ANCHOR:
fprintf(f, "<anchor:%p> ", node);
switch (ANCHOR_(node)->type) {
case ANCR_BEGIN_BUF: fputs("begin buf", f); break;
case ANCR_END_BUF: fputs("end buf", f); break;
case ANCR_BEGIN_LINE: fputs("begin line", f); break;
case ANCR_END_LINE: fputs("end line", f); break;
case ANCR_SEMI_END_BUF: fputs("semi end buf", f); break;
case ANCR_BEGIN_POSITION: fputs("begin position", f); break;
case ANCR_WORD_BOUNDARY: fputs("word boundary", f); break;
case ANCR_NO_WORD_BOUNDARY: fputs("not word boundary", f); break;
#ifdef USE_WORD_BEGIN_END
case ANCR_WORD_BEGIN: fputs("word begin", f); break;
case ANCR_WORD_END: fputs("word end", f); break;
#endif
case ANCR_TEXT_SEGMENT_BOUNDARY:
fputs("text-segment boundary", f); break;
case ANCR_NO_TEXT_SEGMENT_BOUNDARY:
fputs("no text-segment boundary", f); break;
case ANCR_PREC_READ:
fprintf(f, "prec read\n");
print_indent_tree(f, NODE_BODY(node), indent + add);
break;
case ANCR_PREC_READ_NOT:
fprintf(f, "prec read not\n");
print_indent_tree(f, NODE_BODY(node), indent + add);
break;
case ANCR_LOOK_BEHIND:
fprintf(f, "look behind\n");
print_indent_tree(f, NODE_BODY(node), indent + add);
break;
case ANCR_LOOK_BEHIND_NOT:
fprintf(f, "look behind not\n");
print_indent_tree(f, NODE_BODY(node), indent + add);
break;
default:
fprintf(f, "ERROR: undefined anchor type.\n");
break;
}
break;
case NODE_BACKREF:
{
int* p;
BackRefNode* br = BACKREF_(node);
p = BACKREFS_P(br);
fprintf(f, "<backref%s:%p>", NODE_IS_CHECKER(node) ? "-checker" : "", node);
for (i = 0; i < br->back_num; i++) {
if (i > 0) fputs(", ", f);
fprintf(f, "%d", p[i]);
}
#ifdef USE_BACKREF_WITH_LEVEL
if (NODE_IS_NEST_LEVEL(node)) {
fprintf(f, ", level: %d", br->nest_level);
}
#endif
}
break;
#ifdef USE_CALL
case NODE_CALL:
{
CallNode* cn = CALL_(node);
fprintf(f, "<call:%p>", node);
fprintf(f, " num: %d, name", cn->called_gnum);
p_string(f, cn->name_end - cn->name, cn->name);
}
break;
#endif
case NODE_QUANT:
fprintf(f, "<quantifier:%p>{%d,%d}%s%s\n", node,
QUANT_(node)->lower, QUANT_(node)->upper,
(QUANT_(node)->greedy ? "" : "?"),
QUANT_(node)->include_referred == 0 ? "" : " referred");
print_indent_tree(f, NODE_BODY(node), indent + add);
break;
case NODE_BAG:
fprintf(f, "<bag:%p> ", node);
if (BAG_(node)->type == BAG_IF_ELSE) {
Node* Then;
Node* Else;
BagNode* bn;
bn = BAG_(node);
fprintf(f, "if-else\n");
print_indent_tree(f, NODE_BODY(node), indent + add);
Then = bn->te.Then;
Else = bn->te.Else;
if (IS_NULL(Then)) {
Indent(f, indent + add);
fprintf(f, "THEN empty\n");
}
else
print_indent_tree(f, Then, indent + add);
if (IS_NULL(Else)) {
Indent(f, indent + add);
fprintf(f, "ELSE empty\n");
}
else
print_indent_tree(f, Else, indent + add);
break;
}
switch (BAG_(node)->type) {
case BAG_OPTION:
fprintf(f, "option:%d", BAG_(node)->o.options);
break;
case BAG_MEMORY:
fprintf(f, "memory:%d", BAG_(node)->m.regnum);
if (NODE_IS_CALLED(node))
fprintf(f, ", called");
else if (NODE_IS_REFERENCED(node))
fprintf(f, ", referenced");
if (NODE_IS_FIXED_ADDR(node))
fprintf(f, ", fixed-addr");
break;
case BAG_STOP_BACKTRACK:
fprintf(f, "stop-bt");
break;
default:
break;
}
fprintf(f, "\n");
print_indent_tree(f, NODE_BODY(node), indent + add);
break;
case NODE_GIMMICK:
fprintf(f, "<gimmick:%p> ", node);
switch (GIMMICK_(node)->type) {
case GIMMICK_FAIL:
fprintf(f, "fail");
break;
case GIMMICK_SAVE:
fprintf(f, "save:%d:%d", GIMMICK_(node)->detail_type, GIMMICK_(node)->id);
break;
case GIMMICK_UPDATE_VAR:
fprintf(f, "update_var:%d:%d", GIMMICK_(node)->detail_type, GIMMICK_(node)->id);
break;
#ifdef USE_CALLOUT
case GIMMICK_CALLOUT:
switch (GIMMICK_(node)->detail_type) {
case ONIG_CALLOUT_OF_CONTENTS:
fprintf(f, "callout:contents:%d", GIMMICK_(node)->num);
break;
case ONIG_CALLOUT_OF_NAME:
fprintf(f, "callout:name:%d:%d", GIMMICK_(node)->id, GIMMICK_(node)->num);
break;
}
#endif
}
break;
default:
fprintf(f, "print_indent_tree: undefined node type %d\n", NODE_TYPE(node));
break;
}
if (type != NODE_LIST && type != NODE_ALT && type != NODE_QUANT &&
type != NODE_BAG)
fprintf(f, "\n");
fflush(f);
}
static void
print_tree(FILE* f, Node* node)
{
print_indent_tree(f, node, 0);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_4318_0 |
crossvul-cpp_data_bad_5102_1 | /* $Id$ */
/*
* Copyright (c) 1996-1997 Sam Leffler
* Copyright (c) 1996 Pixar
*
* 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
* Pixar, 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 Pixar, 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 PIXAR, 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 "tiffiop.h"
#ifdef PIXARLOG_SUPPORT
/*
* TIFF Library.
* PixarLog Compression Support
*
* Contributed by Dan McCoy.
*
* PixarLog film support uses the TIFF library to store companded
* 11 bit values into a tiff file, which are compressed using the
* zip compressor.
*
* The codec can take as input and produce as output 32-bit IEEE float values
* as well as 16-bit or 8-bit unsigned integer values.
*
* On writing any of the above are converted into the internal
* 11-bit log format. In the case of 8 and 16 bit values, the
* input is assumed to be unsigned linear color values that represent
* the range 0-1. In the case of IEEE values, the 0-1 range is assumed to
* be the normal linear color range, in addition over 1 values are
* accepted up to a value of about 25.0 to encode "hot" highlights and such.
* The encoding is lossless for 8-bit values, slightly lossy for the
* other bit depths. The actual color precision should be better
* than the human eye can perceive with extra room to allow for
* error introduced by further image computation. As with any quantized
* color format, it is possible to perform image calculations which
* expose the quantization error. This format should certainly be less
* susceptible to such errors than standard 8-bit encodings, but more
* susceptible than straight 16-bit or 32-bit encodings.
*
* On reading the internal format is converted to the desired output format.
* The program can request which format it desires by setting the internal
* pseudo tag TIFFTAG_PIXARLOGDATAFMT to one of these possible values:
* PIXARLOGDATAFMT_FLOAT = provide IEEE float values.
* PIXARLOGDATAFMT_16BIT = provide unsigned 16-bit integer values
* PIXARLOGDATAFMT_8BIT = provide unsigned 8-bit integer values
*
* alternately PIXARLOGDATAFMT_8BITABGR provides unsigned 8-bit integer
* values with the difference that if there are exactly three or four channels
* (rgb or rgba) it swaps the channel order (bgr or abgr).
*
* PIXARLOGDATAFMT_11BITLOG provides the internal encoding directly
* packed in 16-bit values. However no tools are supplied for interpreting
* these values.
*
* "hot" (over 1.0) areas written in floating point get clamped to
* 1.0 in the integer data types.
*
* When the file is closed after writing, the bit depth and sample format
* are set always to appear as if 8-bit data has been written into it.
* That way a naive program unaware of the particulars of the encoding
* gets the format it is most likely able to handle.
*
* The codec does it's own horizontal differencing step on the coded
* values so the libraries predictor stuff should be turned off.
* The codec also handle byte swapping the encoded values as necessary
* since the library does not have the information necessary
* to know the bit depth of the raw unencoded buffer.
*
* NOTE: This decoder does not appear to update tif_rawcp, and tif_rawcc.
* This can cause problems with the implementation of CHUNKY_STRIP_READ_SUPPORT
* as noted in http://trac.osgeo.org/gdal/ticket/3894. FrankW - Jan'11
*/
#include "tif_predict.h"
#include "zlib.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* Tables for converting to/from 11 bit coded values */
#define TSIZE 2048 /* decode table size (11-bit tokens) */
#define TSIZEP1 2049 /* Plus one for slop */
#define ONE 1250 /* token value of 1.0 exactly */
#define RATIO 1.004 /* nominal ratio for log part */
#define CODE_MASK 0x7ff /* 11 bits. */
static float Fltsize;
static float LogK1, LogK2;
#define REPEAT(n, op) { int i; i=n; do { i--; op; } while (i>0); }
static void
horizontalAccumulateF(uint16 *wp, int n, int stride, float *op,
float *ToLinearF)
{
register unsigned int cr, cg, cb, ca, mask;
register float t0, t1, t2, t3;
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
t0 = ToLinearF[cr = (wp[0] & mask)];
t1 = ToLinearF[cg = (wp[1] & mask)];
t2 = ToLinearF[cb = (wp[2] & mask)];
op[0] = t0;
op[1] = t1;
op[2] = t2;
n -= 3;
while (n > 0) {
wp += 3;
op += 3;
n -= 3;
t0 = ToLinearF[(cr += wp[0]) & mask];
t1 = ToLinearF[(cg += wp[1]) & mask];
t2 = ToLinearF[(cb += wp[2]) & mask];
op[0] = t0;
op[1] = t1;
op[2] = t2;
}
} else if (stride == 4) {
t0 = ToLinearF[cr = (wp[0] & mask)];
t1 = ToLinearF[cg = (wp[1] & mask)];
t2 = ToLinearF[cb = (wp[2] & mask)];
t3 = ToLinearF[ca = (wp[3] & mask)];
op[0] = t0;
op[1] = t1;
op[2] = t2;
op[3] = t3;
n -= 4;
while (n > 0) {
wp += 4;
op += 4;
n -= 4;
t0 = ToLinearF[(cr += wp[0]) & mask];
t1 = ToLinearF[(cg += wp[1]) & mask];
t2 = ToLinearF[(cb += wp[2]) & mask];
t3 = ToLinearF[(ca += wp[3]) & mask];
op[0] = t0;
op[1] = t1;
op[2] = t2;
op[3] = t3;
}
} else {
REPEAT(stride, *op = ToLinearF[*wp&mask]; wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; *op = ToLinearF[*wp&mask]; wp++; op++)
n -= stride;
}
}
}
}
static void
horizontalAccumulate12(uint16 *wp, int n, int stride, int16 *op,
float *ToLinearF)
{
register unsigned int cr, cg, cb, ca, mask;
register float t0, t1, t2, t3;
#define SCALE12 2048.0F
#define CLAMP12(t) (((t) < 3071) ? (uint16) (t) : 3071)
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
t0 = ToLinearF[cr = (wp[0] & mask)] * SCALE12;
t1 = ToLinearF[cg = (wp[1] & mask)] * SCALE12;
t2 = ToLinearF[cb = (wp[2] & mask)] * SCALE12;
op[0] = CLAMP12(t0);
op[1] = CLAMP12(t1);
op[2] = CLAMP12(t2);
n -= 3;
while (n > 0) {
wp += 3;
op += 3;
n -= 3;
t0 = ToLinearF[(cr += wp[0]) & mask] * SCALE12;
t1 = ToLinearF[(cg += wp[1]) & mask] * SCALE12;
t2 = ToLinearF[(cb += wp[2]) & mask] * SCALE12;
op[0] = CLAMP12(t0);
op[1] = CLAMP12(t1);
op[2] = CLAMP12(t2);
}
} else if (stride == 4) {
t0 = ToLinearF[cr = (wp[0] & mask)] * SCALE12;
t1 = ToLinearF[cg = (wp[1] & mask)] * SCALE12;
t2 = ToLinearF[cb = (wp[2] & mask)] * SCALE12;
t3 = ToLinearF[ca = (wp[3] & mask)] * SCALE12;
op[0] = CLAMP12(t0);
op[1] = CLAMP12(t1);
op[2] = CLAMP12(t2);
op[3] = CLAMP12(t3);
n -= 4;
while (n > 0) {
wp += 4;
op += 4;
n -= 4;
t0 = ToLinearF[(cr += wp[0]) & mask] * SCALE12;
t1 = ToLinearF[(cg += wp[1]) & mask] * SCALE12;
t2 = ToLinearF[(cb += wp[2]) & mask] * SCALE12;
t3 = ToLinearF[(ca += wp[3]) & mask] * SCALE12;
op[0] = CLAMP12(t0);
op[1] = CLAMP12(t1);
op[2] = CLAMP12(t2);
op[3] = CLAMP12(t3);
}
} else {
REPEAT(stride, t0 = ToLinearF[*wp&mask] * SCALE12;
*op = CLAMP12(t0); wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; t0 = ToLinearF[wp[stride]&mask]*SCALE12;
*op = CLAMP12(t0); wp++; op++)
n -= stride;
}
}
}
}
static void
horizontalAccumulate16(uint16 *wp, int n, int stride, uint16 *op,
uint16 *ToLinear16)
{
register unsigned int cr, cg, cb, ca, mask;
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
op[0] = ToLinear16[cr = (wp[0] & mask)];
op[1] = ToLinear16[cg = (wp[1] & mask)];
op[2] = ToLinear16[cb = (wp[2] & mask)];
n -= 3;
while (n > 0) {
wp += 3;
op += 3;
n -= 3;
op[0] = ToLinear16[(cr += wp[0]) & mask];
op[1] = ToLinear16[(cg += wp[1]) & mask];
op[2] = ToLinear16[(cb += wp[2]) & mask];
}
} else if (stride == 4) {
op[0] = ToLinear16[cr = (wp[0] & mask)];
op[1] = ToLinear16[cg = (wp[1] & mask)];
op[2] = ToLinear16[cb = (wp[2] & mask)];
op[3] = ToLinear16[ca = (wp[3] & mask)];
n -= 4;
while (n > 0) {
wp += 4;
op += 4;
n -= 4;
op[0] = ToLinear16[(cr += wp[0]) & mask];
op[1] = ToLinear16[(cg += wp[1]) & mask];
op[2] = ToLinear16[(cb += wp[2]) & mask];
op[3] = ToLinear16[(ca += wp[3]) & mask];
}
} else {
REPEAT(stride, *op = ToLinear16[*wp&mask]; wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; *op = ToLinear16[*wp&mask]; wp++; op++)
n -= stride;
}
}
}
}
/*
* Returns the log encoded 11-bit values with the horizontal
* differencing undone.
*/
static void
horizontalAccumulate11(uint16 *wp, int n, int stride, uint16 *op)
{
register unsigned int cr, cg, cb, ca, mask;
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
op[0] = wp[0]; op[1] = wp[1]; op[2] = wp[2];
cr = wp[0]; cg = wp[1]; cb = wp[2];
n -= 3;
while (n > 0) {
wp += 3;
op += 3;
n -= 3;
op[0] = (uint16)((cr += wp[0]) & mask);
op[1] = (uint16)((cg += wp[1]) & mask);
op[2] = (uint16)((cb += wp[2]) & mask);
}
} else if (stride == 4) {
op[0] = wp[0]; op[1] = wp[1];
op[2] = wp[2]; op[3] = wp[3];
cr = wp[0]; cg = wp[1]; cb = wp[2]; ca = wp[3];
n -= 4;
while (n > 0) {
wp += 4;
op += 4;
n -= 4;
op[0] = (uint16)((cr += wp[0]) & mask);
op[1] = (uint16)((cg += wp[1]) & mask);
op[2] = (uint16)((cb += wp[2]) & mask);
op[3] = (uint16)((ca += wp[3]) & mask);
}
} else {
REPEAT(stride, *op = *wp&mask; wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; *op = *wp&mask; wp++; op++)
n -= stride;
}
}
}
}
static void
horizontalAccumulate8(uint16 *wp, int n, int stride, unsigned char *op,
unsigned char *ToLinear8)
{
register unsigned int cr, cg, cb, ca, mask;
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
op[0] = ToLinear8[cr = (wp[0] & mask)];
op[1] = ToLinear8[cg = (wp[1] & mask)];
op[2] = ToLinear8[cb = (wp[2] & mask)];
n -= 3;
while (n > 0) {
n -= 3;
wp += 3;
op += 3;
op[0] = ToLinear8[(cr += wp[0]) & mask];
op[1] = ToLinear8[(cg += wp[1]) & mask];
op[2] = ToLinear8[(cb += wp[2]) & mask];
}
} else if (stride == 4) {
op[0] = ToLinear8[cr = (wp[0] & mask)];
op[1] = ToLinear8[cg = (wp[1] & mask)];
op[2] = ToLinear8[cb = (wp[2] & mask)];
op[3] = ToLinear8[ca = (wp[3] & mask)];
n -= 4;
while (n > 0) {
n -= 4;
wp += 4;
op += 4;
op[0] = ToLinear8[(cr += wp[0]) & mask];
op[1] = ToLinear8[(cg += wp[1]) & mask];
op[2] = ToLinear8[(cb += wp[2]) & mask];
op[3] = ToLinear8[(ca += wp[3]) & mask];
}
} else {
REPEAT(stride, *op = ToLinear8[*wp&mask]; wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; *op = ToLinear8[*wp&mask]; wp++; op++)
n -= stride;
}
}
}
}
static void
horizontalAccumulate8abgr(uint16 *wp, int n, int stride, unsigned char *op,
unsigned char *ToLinear8)
{
register unsigned int cr, cg, cb, ca, mask;
register unsigned char t0, t1, t2, t3;
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
op[0] = 0;
t1 = ToLinear8[cb = (wp[2] & mask)];
t2 = ToLinear8[cg = (wp[1] & mask)];
t3 = ToLinear8[cr = (wp[0] & mask)];
op[1] = t1;
op[2] = t2;
op[3] = t3;
n -= 3;
while (n > 0) {
n -= 3;
wp += 3;
op += 4;
op[0] = 0;
t1 = ToLinear8[(cb += wp[2]) & mask];
t2 = ToLinear8[(cg += wp[1]) & mask];
t3 = ToLinear8[(cr += wp[0]) & mask];
op[1] = t1;
op[2] = t2;
op[3] = t3;
}
} else if (stride == 4) {
t0 = ToLinear8[ca = (wp[3] & mask)];
t1 = ToLinear8[cb = (wp[2] & mask)];
t2 = ToLinear8[cg = (wp[1] & mask)];
t3 = ToLinear8[cr = (wp[0] & mask)];
op[0] = t0;
op[1] = t1;
op[2] = t2;
op[3] = t3;
n -= 4;
while (n > 0) {
n -= 4;
wp += 4;
op += 4;
t0 = ToLinear8[(ca += wp[3]) & mask];
t1 = ToLinear8[(cb += wp[2]) & mask];
t2 = ToLinear8[(cg += wp[1]) & mask];
t3 = ToLinear8[(cr += wp[0]) & mask];
op[0] = t0;
op[1] = t1;
op[2] = t2;
op[3] = t3;
}
} else {
REPEAT(stride, *op = ToLinear8[*wp&mask]; wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; *op = ToLinear8[*wp&mask]; wp++; op++)
n -= stride;
}
}
}
}
/*
* State block for each open TIFF
* file using PixarLog compression/decompression.
*/
typedef struct {
TIFFPredictorState predict;
z_stream stream;
uint16 *tbuf;
uint16 stride;
int state;
int user_datafmt;
int quality;
#define PLSTATE_INIT 1
TIFFVSetMethod vgetparent; /* super-class method */
TIFFVSetMethod vsetparent; /* super-class method */
float *ToLinearF;
uint16 *ToLinear16;
unsigned char *ToLinear8;
uint16 *FromLT2;
uint16 *From14; /* Really for 16-bit data, but we shift down 2 */
uint16 *From8;
} PixarLogState;
static int
PixarLogMakeTables(PixarLogState *sp)
{
/*
* We make several tables here to convert between various external
* representations (float, 16-bit, and 8-bit) and the internal
* 11-bit companded representation. The 11-bit representation has two
* distinct regions. A linear bottom end up through .018316 in steps
* of about .000073, and a region of constant ratio up to about 25.
* These floating point numbers are stored in the main table ToLinearF.
* All other tables are derived from this one. The tables (and the
* ratios) are continuous at the internal seam.
*/
int nlin, lt2size;
int i, j;
double b, c, linstep, v;
float *ToLinearF;
uint16 *ToLinear16;
unsigned char *ToLinear8;
uint16 *FromLT2;
uint16 *From14; /* Really for 16-bit data, but we shift down 2 */
uint16 *From8;
c = log(RATIO);
nlin = (int)(1./c); /* nlin must be an integer */
c = 1./nlin;
b = exp(-c*ONE); /* multiplicative scale factor [b*exp(c*ONE) = 1] */
linstep = b*c*exp(1.);
LogK1 = (float)(1./c); /* if (v >= 2) token = k1*log(v*k2) */
LogK2 = (float)(1./b);
lt2size = (int)(2./linstep) + 1;
FromLT2 = (uint16 *)_TIFFmalloc(lt2size*sizeof(uint16));
From14 = (uint16 *)_TIFFmalloc(16384*sizeof(uint16));
From8 = (uint16 *)_TIFFmalloc(256*sizeof(uint16));
ToLinearF = (float *)_TIFFmalloc(TSIZEP1 * sizeof(float));
ToLinear16 = (uint16 *)_TIFFmalloc(TSIZEP1 * sizeof(uint16));
ToLinear8 = (unsigned char *)_TIFFmalloc(TSIZEP1 * sizeof(unsigned char));
if (FromLT2 == NULL || From14 == NULL || From8 == NULL ||
ToLinearF == NULL || ToLinear16 == NULL || ToLinear8 == NULL) {
if (FromLT2) _TIFFfree(FromLT2);
if (From14) _TIFFfree(From14);
if (From8) _TIFFfree(From8);
if (ToLinearF) _TIFFfree(ToLinearF);
if (ToLinear16) _TIFFfree(ToLinear16);
if (ToLinear8) _TIFFfree(ToLinear8);
sp->FromLT2 = NULL;
sp->From14 = NULL;
sp->From8 = NULL;
sp->ToLinearF = NULL;
sp->ToLinear16 = NULL;
sp->ToLinear8 = NULL;
return 0;
}
j = 0;
for (i = 0; i < nlin; i++) {
v = i * linstep;
ToLinearF[j++] = (float)v;
}
for (i = nlin; i < TSIZE; i++)
ToLinearF[j++] = (float)(b*exp(c*i));
ToLinearF[2048] = ToLinearF[2047];
for (i = 0; i < TSIZEP1; i++) {
v = ToLinearF[i]*65535.0 + 0.5;
ToLinear16[i] = (v > 65535.0) ? 65535 : (uint16)v;
v = ToLinearF[i]*255.0 + 0.5;
ToLinear8[i] = (v > 255.0) ? 255 : (unsigned char)v;
}
j = 0;
for (i = 0; i < lt2size; i++) {
if ((i*linstep)*(i*linstep) > ToLinearF[j]*ToLinearF[j+1])
j++;
FromLT2[i] = (uint16)j;
}
/*
* Since we lose info anyway on 16-bit data, we set up a 14-bit
* table and shift 16-bit values down two bits on input.
* saves a little table space.
*/
j = 0;
for (i = 0; i < 16384; i++) {
while ((i/16383.)*(i/16383.) > ToLinearF[j]*ToLinearF[j+1])
j++;
From14[i] = (uint16)j;
}
j = 0;
for (i = 0; i < 256; i++) {
while ((i/255.)*(i/255.) > ToLinearF[j]*ToLinearF[j+1])
j++;
From8[i] = (uint16)j;
}
Fltsize = (float)(lt2size/2);
sp->ToLinearF = ToLinearF;
sp->ToLinear16 = ToLinear16;
sp->ToLinear8 = ToLinear8;
sp->FromLT2 = FromLT2;
sp->From14 = From14;
sp->From8 = From8;
return 1;
}
#define DecoderState(tif) ((PixarLogState*) (tif)->tif_data)
#define EncoderState(tif) ((PixarLogState*) (tif)->tif_data)
static int PixarLogEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s);
static int PixarLogDecode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s);
#define PIXARLOGDATAFMT_UNKNOWN -1
static int
PixarLogGuessDataFmt(TIFFDirectory *td)
{
int guess = PIXARLOGDATAFMT_UNKNOWN;
int format = td->td_sampleformat;
/* If the user didn't tell us his datafmt,
* take our best guess from the bitspersample.
*/
switch (td->td_bitspersample) {
case 32:
if (format == SAMPLEFORMAT_IEEEFP)
guess = PIXARLOGDATAFMT_FLOAT;
break;
case 16:
if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT)
guess = PIXARLOGDATAFMT_16BIT;
break;
case 12:
if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_INT)
guess = PIXARLOGDATAFMT_12BITPICIO;
break;
case 11:
if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT)
guess = PIXARLOGDATAFMT_11BITLOG;
break;
case 8:
if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT)
guess = PIXARLOGDATAFMT_8BIT;
break;
}
return guess;
}
static tmsize_t
multiply_ms(tmsize_t m1, tmsize_t m2)
{
tmsize_t bytes = m1 * m2;
if (m1 && bytes / m1 != m2)
bytes = 0;
return bytes;
}
static tmsize_t
add_ms(tmsize_t m1, tmsize_t m2)
{
tmsize_t bytes = m1 + m2;
/* if either input is zero, assume overflow already occurred */
if (m1 == 0 || m2 == 0)
bytes = 0;
else if (bytes <= m1 || bytes <= m2)
bytes = 0;
return bytes;
}
static int
PixarLogFixupTags(TIFF* tif)
{
(void) tif;
return (1);
}
static int
PixarLogSetupDecode(TIFF* tif)
{
static const char module[] = "PixarLogSetupDecode";
TIFFDirectory *td = &tif->tif_dir;
PixarLogState* sp = DecoderState(tif);
tmsize_t tbuf_size;
assert(sp != NULL);
/* Make sure no byte swapping happens on the data
* after decompression. */
tif->tif_postdecode = _TIFFNoPostDecode;
/* for some reason, we can't do this in TIFFInitPixarLog */
sp->stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ?
td->td_samplesperpixel : 1);
tbuf_size = multiply_ms(multiply_ms(multiply_ms(sp->stride, td->td_imagewidth),
td->td_rowsperstrip), sizeof(uint16));
/* add one more stride in case input ends mid-stride */
tbuf_size = add_ms(tbuf_size, sizeof(uint16) * sp->stride);
if (tbuf_size == 0)
return (0); /* TODO: this is an error return without error report through TIFFErrorExt */
sp->tbuf = (uint16 *) _TIFFmalloc(tbuf_size);
if (sp->tbuf == NULL)
return (0);
if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN)
sp->user_datafmt = PixarLogGuessDataFmt(td);
if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) {
TIFFErrorExt(tif->tif_clientdata, module,
"PixarLog compression can't handle bits depth/data format combination (depth: %d)",
td->td_bitspersample);
return (0);
}
if (inflateInit(&sp->stream) != Z_OK) {
TIFFErrorExt(tif->tif_clientdata, module, "%s", sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
} else {
sp->state |= PLSTATE_INIT;
return (1);
}
}
/*
* Setup state for decoding a strip.
*/
static int
PixarLogPreDecode(TIFF* tif, uint16 s)
{
static const char module[] = "PixarLogPreDecode";
PixarLogState* sp = DecoderState(tif);
(void) s;
assert(sp != NULL);
sp->stream.next_in = tif->tif_rawdata;
assert(sizeof(sp->stream.avail_in)==4); /* if this assert gets raised,
we need to simplify this code to reflect a ZLib that is likely updated
to deal with 8byte memory sizes, though this code will respond
appropriately even before we simplify it */
sp->stream.avail_in = (uInt) tif->tif_rawcc;
if ((tmsize_t)sp->stream.avail_in != tif->tif_rawcc)
{
TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size");
return (0);
}
return (inflateReset(&sp->stream) == Z_OK);
}
static int
PixarLogDecode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s)
{
static const char module[] = "PixarLogDecode";
TIFFDirectory *td = &tif->tif_dir;
PixarLogState* sp = DecoderState(tif);
tmsize_t i;
tmsize_t nsamples;
int llen;
uint16 *up;
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_FLOAT:
nsamples = occ / sizeof(float); /* XXX float == 32 bits */
break;
case PIXARLOGDATAFMT_16BIT:
case PIXARLOGDATAFMT_12BITPICIO:
case PIXARLOGDATAFMT_11BITLOG:
nsamples = occ / sizeof(uint16); /* XXX uint16 == 16 bits */
break;
case PIXARLOGDATAFMT_8BIT:
case PIXARLOGDATAFMT_8BITABGR:
nsamples = occ;
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"%d bit input not supported in PixarLog",
td->td_bitspersample);
return 0;
}
llen = sp->stride * td->td_imagewidth;
(void) s;
assert(sp != NULL);
sp->stream.next_out = (unsigned char *) sp->tbuf;
assert(sizeof(sp->stream.avail_out)==4); /* if this assert gets raised,
we need to simplify this code to reflect a ZLib that is likely updated
to deal with 8byte memory sizes, though this code will respond
appropriately even before we simplify it */
sp->stream.avail_out = (uInt) (nsamples * sizeof(uint16));
if (sp->stream.avail_out != nsamples * sizeof(uint16))
{
TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size");
return (0);
}
do {
int state = inflate(&sp->stream, Z_PARTIAL_FLUSH);
if (state == Z_STREAM_END) {
break; /* XXX */
}
if (state == Z_DATA_ERROR) {
TIFFErrorExt(tif->tif_clientdata, module,
"Decoding error at scanline %lu, %s",
(unsigned long) tif->tif_row, sp->stream.msg ? sp->stream.msg : "(null)");
if (inflateSync(&sp->stream) != Z_OK)
return (0);
continue;
}
if (state != Z_OK) {
TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s",
sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
}
} while (sp->stream.avail_out > 0);
/* hopefully, we got all the bytes we needed */
if (sp->stream.avail_out != 0) {
TIFFErrorExt(tif->tif_clientdata, module,
"Not enough data at scanline %lu (short " TIFF_UINT64_FORMAT " bytes)",
(unsigned long) tif->tif_row, (TIFF_UINT64_T) sp->stream.avail_out);
return (0);
}
up = sp->tbuf;
/* Swap bytes in the data if from a different endian machine. */
if (tif->tif_flags & TIFF_SWAB)
TIFFSwabArrayOfShort(up, nsamples);
/*
* if llen is not an exact multiple of nsamples, the decode operation
* may overflow the output buffer, so truncate it enough to prevent
* that but still salvage as much data as possible.
*/
if (nsamples % llen) {
TIFFWarningExt(tif->tif_clientdata, module,
"stride %lu is not a multiple of sample count, "
"%lu, data truncated.", (unsigned long) llen, (unsigned long) nsamples);
nsamples -= nsamples % llen;
}
for (i = 0; i < nsamples; i += llen, up += llen) {
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_FLOAT:
horizontalAccumulateF(up, llen, sp->stride,
(float *)op, sp->ToLinearF);
op += llen * sizeof(float);
break;
case PIXARLOGDATAFMT_16BIT:
horizontalAccumulate16(up, llen, sp->stride,
(uint16 *)op, sp->ToLinear16);
op += llen * sizeof(uint16);
break;
case PIXARLOGDATAFMT_12BITPICIO:
horizontalAccumulate12(up, llen, sp->stride,
(int16 *)op, sp->ToLinearF);
op += llen * sizeof(int16);
break;
case PIXARLOGDATAFMT_11BITLOG:
horizontalAccumulate11(up, llen, sp->stride,
(uint16 *)op);
op += llen * sizeof(uint16);
break;
case PIXARLOGDATAFMT_8BIT:
horizontalAccumulate8(up, llen, sp->stride,
(unsigned char *)op, sp->ToLinear8);
op += llen * sizeof(unsigned char);
break;
case PIXARLOGDATAFMT_8BITABGR:
horizontalAccumulate8abgr(up, llen, sp->stride,
(unsigned char *)op, sp->ToLinear8);
op += llen * sizeof(unsigned char);
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"Unsupported bits/sample: %d",
td->td_bitspersample);
return (0);
}
}
return (1);
}
static int
PixarLogSetupEncode(TIFF* tif)
{
static const char module[] = "PixarLogSetupEncode";
TIFFDirectory *td = &tif->tif_dir;
PixarLogState* sp = EncoderState(tif);
tmsize_t tbuf_size;
assert(sp != NULL);
/* for some reason, we can't do this in TIFFInitPixarLog */
sp->stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ?
td->td_samplesperpixel : 1);
tbuf_size = multiply_ms(multiply_ms(multiply_ms(sp->stride, td->td_imagewidth),
td->td_rowsperstrip), sizeof(uint16));
if (tbuf_size == 0)
return (0); /* TODO: this is an error return without error report through TIFFErrorExt */
sp->tbuf = (uint16 *) _TIFFmalloc(tbuf_size);
if (sp->tbuf == NULL)
return (0);
if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN)
sp->user_datafmt = PixarLogGuessDataFmt(td);
if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) {
TIFFErrorExt(tif->tif_clientdata, module, "PixarLog compression can't handle %d bit linear encodings", td->td_bitspersample);
return (0);
}
if (deflateInit(&sp->stream, sp->quality) != Z_OK) {
TIFFErrorExt(tif->tif_clientdata, module, "%s", sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
} else {
sp->state |= PLSTATE_INIT;
return (1);
}
}
/*
* Reset encoding state at the start of a strip.
*/
static int
PixarLogPreEncode(TIFF* tif, uint16 s)
{
static const char module[] = "PixarLogPreEncode";
PixarLogState *sp = EncoderState(tif);
(void) s;
assert(sp != NULL);
sp->stream.next_out = tif->tif_rawdata;
assert(sizeof(sp->stream.avail_out)==4); /* if this assert gets raised,
we need to simplify this code to reflect a ZLib that is likely updated
to deal with 8byte memory sizes, though this code will respond
appropriately even before we simplify it */
sp->stream.avail_out = (uInt)tif->tif_rawdatasize;
if ((tmsize_t)sp->stream.avail_out != tif->tif_rawdatasize)
{
TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size");
return (0);
}
return (deflateReset(&sp->stream) == Z_OK);
}
static void
horizontalDifferenceF(float *ip, int n, int stride, uint16 *wp, uint16 *FromLT2)
{
int32 r1, g1, b1, a1, r2, g2, b2, a2, mask;
float fltsize = Fltsize;
#define CLAMP(v) ( (v<(float)0.) ? 0 \
: (v<(float)2.) ? FromLT2[(int)(v*fltsize)] \
: (v>(float)24.2) ? 2047 \
: LogK1*log(v*LogK2) + 0.5 )
mask = CODE_MASK;
if (n >= stride) {
if (stride == 3) {
r2 = wp[0] = (uint16) CLAMP(ip[0]);
g2 = wp[1] = (uint16) CLAMP(ip[1]);
b2 = wp[2] = (uint16) CLAMP(ip[2]);
n -= 3;
while (n > 0) {
n -= 3;
wp += 3;
ip += 3;
r1 = (int32) CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = (int32) CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = (int32) CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
}
} else if (stride == 4) {
r2 = wp[0] = (uint16) CLAMP(ip[0]);
g2 = wp[1] = (uint16) CLAMP(ip[1]);
b2 = wp[2] = (uint16) CLAMP(ip[2]);
a2 = wp[3] = (uint16) CLAMP(ip[3]);
n -= 4;
while (n > 0) {
n -= 4;
wp += 4;
ip += 4;
r1 = (int32) CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = (int32) CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = (int32) CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
a1 = (int32) CLAMP(ip[3]); wp[3] = (uint16)((a1-a2) & mask); a2 = a1;
}
} else {
ip += n - 1; /* point to last one */
wp += n - 1; /* point to last one */
n -= stride;
while (n > 0) {
REPEAT(stride, wp[0] = (uint16) CLAMP(ip[0]);
wp[stride] -= wp[0];
wp[stride] &= mask;
wp--; ip--)
n -= stride;
}
REPEAT(stride, wp[0] = (uint16) CLAMP(ip[0]); wp--; ip--)
}
}
}
static void
horizontalDifference16(unsigned short *ip, int n, int stride,
unsigned short *wp, uint16 *From14)
{
register int r1, g1, b1, a1, r2, g2, b2, a2, mask;
/* assumption is unsigned pixel values */
#undef CLAMP
#define CLAMP(v) From14[(v) >> 2]
mask = CODE_MASK;
if (n >= stride) {
if (stride == 3) {
r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);
b2 = wp[2] = CLAMP(ip[2]);
n -= 3;
while (n > 0) {
n -= 3;
wp += 3;
ip += 3;
r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
}
} else if (stride == 4) {
r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);
b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]);
n -= 4;
while (n > 0) {
n -= 4;
wp += 4;
ip += 4;
r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
a1 = CLAMP(ip[3]); wp[3] = (uint16)((a1-a2) & mask); a2 = a1;
}
} else {
ip += n - 1; /* point to last one */
wp += n - 1; /* point to last one */
n -= stride;
while (n > 0) {
REPEAT(stride, wp[0] = CLAMP(ip[0]);
wp[stride] -= wp[0];
wp[stride] &= mask;
wp--; ip--)
n -= stride;
}
REPEAT(stride, wp[0] = CLAMP(ip[0]); wp--; ip--)
}
}
}
static void
horizontalDifference8(unsigned char *ip, int n, int stride,
unsigned short *wp, uint16 *From8)
{
register int r1, g1, b1, a1, r2, g2, b2, a2, mask;
#undef CLAMP
#define CLAMP(v) (From8[(v)])
mask = CODE_MASK;
if (n >= stride) {
if (stride == 3) {
r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);
b2 = wp[2] = CLAMP(ip[2]);
n -= 3;
while (n > 0) {
n -= 3;
r1 = CLAMP(ip[3]); wp[3] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = CLAMP(ip[4]); wp[4] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = CLAMP(ip[5]); wp[5] = (uint16)((b1-b2) & mask); b2 = b1;
wp += 3;
ip += 3;
}
} else if (stride == 4) {
r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);
b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]);
n -= 4;
while (n > 0) {
n -= 4;
r1 = CLAMP(ip[4]); wp[4] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = CLAMP(ip[5]); wp[5] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = CLAMP(ip[6]); wp[6] = (uint16)((b1-b2) & mask); b2 = b1;
a1 = CLAMP(ip[7]); wp[7] = (uint16)((a1-a2) & mask); a2 = a1;
wp += 4;
ip += 4;
}
} else {
wp += n + stride - 1; /* point to last one */
ip += n + stride - 1; /* point to last one */
n -= stride;
while (n > 0) {
REPEAT(stride, wp[0] = CLAMP(ip[0]);
wp[stride] -= wp[0];
wp[stride] &= mask;
wp--; ip--)
n -= stride;
}
REPEAT(stride, wp[0] = CLAMP(ip[0]); wp--; ip--)
}
}
}
/*
* Encode a chunk of pixels.
*/
static int
PixarLogEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
{
static const char module[] = "PixarLogEncode";
TIFFDirectory *td = &tif->tif_dir;
PixarLogState *sp = EncoderState(tif);
tmsize_t i;
tmsize_t n;
int llen;
unsigned short * up;
(void) s;
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_FLOAT:
n = cc / sizeof(float); /* XXX float == 32 bits */
break;
case PIXARLOGDATAFMT_16BIT:
case PIXARLOGDATAFMT_12BITPICIO:
case PIXARLOGDATAFMT_11BITLOG:
n = cc / sizeof(uint16); /* XXX uint16 == 16 bits */
break;
case PIXARLOGDATAFMT_8BIT:
case PIXARLOGDATAFMT_8BITABGR:
n = cc;
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"%d bit input not supported in PixarLog",
td->td_bitspersample);
return 0;
}
llen = sp->stride * td->td_imagewidth;
for (i = 0, up = sp->tbuf; i < n; i += llen, up += llen) {
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_FLOAT:
horizontalDifferenceF((float *)bp, llen,
sp->stride, up, sp->FromLT2);
bp += llen * sizeof(float);
break;
case PIXARLOGDATAFMT_16BIT:
horizontalDifference16((uint16 *)bp, llen,
sp->stride, up, sp->From14);
bp += llen * sizeof(uint16);
break;
case PIXARLOGDATAFMT_8BIT:
horizontalDifference8((unsigned char *)bp, llen,
sp->stride, up, sp->From8);
bp += llen * sizeof(unsigned char);
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"%d bit input not supported in PixarLog",
td->td_bitspersample);
return 0;
}
}
sp->stream.next_in = (unsigned char *) sp->tbuf;
assert(sizeof(sp->stream.avail_in)==4); /* if this assert gets raised,
we need to simplify this code to reflect a ZLib that is likely updated
to deal with 8byte memory sizes, though this code will respond
appropriately even before we simplify it */
sp->stream.avail_in = (uInt) (n * sizeof(uint16));
if ((sp->stream.avail_in / sizeof(uint16)) != (uInt) n)
{
TIFFErrorExt(tif->tif_clientdata, module,
"ZLib cannot deal with buffers this size");
return (0);
}
do {
if (deflate(&sp->stream, Z_NO_FLUSH) != Z_OK) {
TIFFErrorExt(tif->tif_clientdata, module, "Encoder error: %s",
sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
}
if (sp->stream.avail_out == 0) {
tif->tif_rawcc = tif->tif_rawdatasize;
TIFFFlushData1(tif);
sp->stream.next_out = tif->tif_rawdata;
sp->stream.avail_out = (uInt) tif->tif_rawdatasize; /* this is a safe typecast, as check is made already in PixarLogPreEncode */
}
} while (sp->stream.avail_in > 0);
return (1);
}
/*
* Finish off an encoded strip by flushing the last
* string and tacking on an End Of Information code.
*/
static int
PixarLogPostEncode(TIFF* tif)
{
static const char module[] = "PixarLogPostEncode";
PixarLogState *sp = EncoderState(tif);
int state;
sp->stream.avail_in = 0;
do {
state = deflate(&sp->stream, Z_FINISH);
switch (state) {
case Z_STREAM_END:
case Z_OK:
if ((tmsize_t)sp->stream.avail_out != tif->tif_rawdatasize) {
tif->tif_rawcc =
tif->tif_rawdatasize - sp->stream.avail_out;
TIFFFlushData1(tif);
sp->stream.next_out = tif->tif_rawdata;
sp->stream.avail_out = (uInt) tif->tif_rawdatasize; /* this is a safe typecast, as check is made already in PixarLogPreEncode */
}
break;
default:
TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s",
sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
}
} while (state != Z_STREAM_END);
return (1);
}
static void
PixarLogClose(TIFF* tif)
{
TIFFDirectory *td = &tif->tif_dir;
/* In a really sneaky (and really incorrect, and untruthful, and
* troublesome, and error-prone) maneuver that completely goes against
* the spirit of TIFF, and breaks TIFF, on close, we covertly
* modify both bitspersample and sampleformat in the directory to
* indicate 8-bit linear. This way, the decode "just works" even for
* readers that don't know about PixarLog, or how to set
* the PIXARLOGDATFMT pseudo-tag.
*/
td->td_bitspersample = 8;
td->td_sampleformat = SAMPLEFORMAT_UINT;
}
static void
PixarLogCleanup(TIFF* tif)
{
PixarLogState* sp = (PixarLogState*) tif->tif_data;
assert(sp != 0);
(void)TIFFPredictorCleanup(tif);
tif->tif_tagmethods.vgetfield = sp->vgetparent;
tif->tif_tagmethods.vsetfield = sp->vsetparent;
if (sp->FromLT2) _TIFFfree(sp->FromLT2);
if (sp->From14) _TIFFfree(sp->From14);
if (sp->From8) _TIFFfree(sp->From8);
if (sp->ToLinearF) _TIFFfree(sp->ToLinearF);
if (sp->ToLinear16) _TIFFfree(sp->ToLinear16);
if (sp->ToLinear8) _TIFFfree(sp->ToLinear8);
if (sp->state&PLSTATE_INIT) {
if (tif->tif_mode == O_RDONLY)
inflateEnd(&sp->stream);
else
deflateEnd(&sp->stream);
}
if (sp->tbuf)
_TIFFfree(sp->tbuf);
_TIFFfree(sp);
tif->tif_data = NULL;
_TIFFSetDefaultCompressionState(tif);
}
static int
PixarLogVSetField(TIFF* tif, uint32 tag, va_list ap)
{
static const char module[] = "PixarLogVSetField";
PixarLogState *sp = (PixarLogState *)tif->tif_data;
int result;
switch (tag) {
case TIFFTAG_PIXARLOGQUALITY:
sp->quality = (int) va_arg(ap, int);
if (tif->tif_mode != O_RDONLY && (sp->state&PLSTATE_INIT)) {
if (deflateParams(&sp->stream,
sp->quality, Z_DEFAULT_STRATEGY) != Z_OK) {
TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s",
sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
}
}
return (1);
case TIFFTAG_PIXARLOGDATAFMT:
sp->user_datafmt = (int) va_arg(ap, int);
/* Tweak the TIFF header so that the rest of libtiff knows what
* size of data will be passed between app and library, and
* assume that the app knows what it is doing and is not
* confused by these header manipulations...
*/
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_8BIT:
case PIXARLOGDATAFMT_8BITABGR:
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 8);
TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
break;
case PIXARLOGDATAFMT_11BITLOG:
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16);
TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
break;
case PIXARLOGDATAFMT_12BITPICIO:
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16);
TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_INT);
break;
case PIXARLOGDATAFMT_16BIT:
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16);
TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
break;
case PIXARLOGDATAFMT_FLOAT:
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 32);
TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP);
break;
}
/*
* Must recalculate sizes should bits/sample change.
*/
tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tmsize_t)(-1);
tif->tif_scanlinesize = TIFFScanlineSize(tif);
result = 1; /* NB: pseudo tag */
break;
default:
result = (*sp->vsetparent)(tif, tag, ap);
}
return (result);
}
static int
PixarLogVGetField(TIFF* tif, uint32 tag, va_list ap)
{
PixarLogState *sp = (PixarLogState *)tif->tif_data;
switch (tag) {
case TIFFTAG_PIXARLOGQUALITY:
*va_arg(ap, int*) = sp->quality;
break;
case TIFFTAG_PIXARLOGDATAFMT:
*va_arg(ap, int*) = sp->user_datafmt;
break;
default:
return (*sp->vgetparent)(tif, tag, ap);
}
return (1);
}
static const TIFFField pixarlogFields[] = {
{TIFFTAG_PIXARLOGDATAFMT, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL},
{TIFFTAG_PIXARLOGQUALITY, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL}
};
int
TIFFInitPixarLog(TIFF* tif, int scheme)
{
static const char module[] = "TIFFInitPixarLog";
PixarLogState* sp;
assert(scheme == COMPRESSION_PIXARLOG);
/*
* Merge codec-specific tag information.
*/
if (!_TIFFMergeFields(tif, pixarlogFields,
TIFFArrayCount(pixarlogFields))) {
TIFFErrorExt(tif->tif_clientdata, module,
"Merging PixarLog codec-specific tags failed");
return 0;
}
/*
* Allocate state block so tag methods have storage to record values.
*/
tif->tif_data = (uint8*) _TIFFmalloc(sizeof (PixarLogState));
if (tif->tif_data == NULL)
goto bad;
sp = (PixarLogState*) tif->tif_data;
_TIFFmemset(sp, 0, sizeof (*sp));
sp->stream.data_type = Z_BINARY;
sp->user_datafmt = PIXARLOGDATAFMT_UNKNOWN;
/*
* Install codec methods.
*/
tif->tif_fixuptags = PixarLogFixupTags;
tif->tif_setupdecode = PixarLogSetupDecode;
tif->tif_predecode = PixarLogPreDecode;
tif->tif_decoderow = PixarLogDecode;
tif->tif_decodestrip = PixarLogDecode;
tif->tif_decodetile = PixarLogDecode;
tif->tif_setupencode = PixarLogSetupEncode;
tif->tif_preencode = PixarLogPreEncode;
tif->tif_postencode = PixarLogPostEncode;
tif->tif_encoderow = PixarLogEncode;
tif->tif_encodestrip = PixarLogEncode;
tif->tif_encodetile = PixarLogEncode;
tif->tif_close = PixarLogClose;
tif->tif_cleanup = PixarLogCleanup;
/* Override SetField so we can handle our private pseudo-tag */
sp->vgetparent = tif->tif_tagmethods.vgetfield;
tif->tif_tagmethods.vgetfield = PixarLogVGetField; /* hook for codec tags */
sp->vsetparent = tif->tif_tagmethods.vsetfield;
tif->tif_tagmethods.vsetfield = PixarLogVSetField; /* hook for codec tags */
/* Default values for codec-specific fields */
sp->quality = Z_DEFAULT_COMPRESSION; /* default comp. level */
sp->state = 0;
/* we don't wish to use the predictor,
* the default is none, which predictor value 1
*/
(void) TIFFPredictorInit(tif);
/*
* build the companding tables
*/
PixarLogMakeTables(sp);
return (1);
bad:
TIFFErrorExt(tif->tif_clientdata, module,
"No space for PixarLog state block");
return (0);
}
#endif /* PIXARLOG_SUPPORT */
/* 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-787/c/bad_5102_1 |
crossvul-cpp_data_bad_3411_3 | /* fshelp.c -- Filesystem helper functions */
/*
* GRUB -- GRand Unified Bootloader
* Copyright (C) 2004,2005,2006,2007,2008 Free Software Foundation, Inc.
*
* GRUB 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 3 of the License, or
* (at your option) any later version.
*
* GRUB 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 GRUB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <grub/err.h>
#include <grub/mm.h>
#include <grub/misc.h>
#include <grub/disk.h>
#include <grub/fshelp.h>
GRUB_EXPORT(grub_fshelp_view);
GRUB_EXPORT(grub_fshelp_find_file);
GRUB_EXPORT(grub_fshelp_log2blksize);
GRUB_EXPORT(grub_fshelp_read_file);
int grub_fshelp_view = 0;
struct grub_fshelp_find_file_closure
{
grub_fshelp_node_t rootnode;
int (*iterate_dir) (grub_fshelp_node_t dir,
int (*hook)
(const char *filename,
enum grub_fshelp_filetype filetype,
grub_fshelp_node_t node, void *closure),
void *closure);
void *closure;
char *(*read_symlink) (grub_fshelp_node_t node);
int symlinknest;
enum grub_fshelp_filetype foundtype;
grub_fshelp_node_t currroot;
};
static void
free_node (grub_fshelp_node_t node, struct grub_fshelp_find_file_closure *c)
{
if (node != c->rootnode && node != c->currroot)
grub_free (node);
}
struct find_file_closure
{
char *name;
enum grub_fshelp_filetype *type;
grub_fshelp_node_t *oldnode;
grub_fshelp_node_t *currnode;
};
static int
iterate (const char *filename,
enum grub_fshelp_filetype filetype,
grub_fshelp_node_t node,
void *closure)
{
struct find_file_closure *c = closure;
if (filetype == GRUB_FSHELP_UNKNOWN ||
(grub_strcmp (c->name, filename) &&
(! (filetype & GRUB_FSHELP_CASE_INSENSITIVE) ||
grub_strncasecmp (c->name, filename, GRUB_LONG_MAX))))
{
grub_free (node);
return 0;
}
/* The node is found, stop iterating over the nodes. */
*(c->type) = filetype & ~GRUB_FSHELP_CASE_INSENSITIVE;
*(c->oldnode) = *(c->currnode);
*(c->currnode) = node;
return 1;
}
static grub_err_t
find_file (const char *currpath, grub_fshelp_node_t currroot,
grub_fshelp_node_t *currfound,
struct grub_fshelp_find_file_closure *c)
{
#ifndef _MSC_VER
char fpath[grub_strlen (currpath) + 1];
#else
char *fpath = grub_malloc (grub_strlen (currpath) + 1);
#endif
char *name = fpath;
char *next;
enum grub_fshelp_filetype type = GRUB_FSHELP_DIR;
grub_fshelp_node_t currnode = currroot;
grub_fshelp_node_t oldnode = currroot;
c->currroot = currroot;
grub_strncpy (fpath, currpath, grub_strlen (currpath) + 1);
/* Remove all leading slashes. */
while (*name == '/')
name++;
if (! *name)
{
*currfound = currnode;
return 0;
}
for (;;)
{
int found;
struct find_file_closure cc;
/* Extract the actual part from the pathname. */
next = grub_strchr (name, '/');
if (next)
{
/* Remove all leading slashes. */
while (*next == '/')
*(next++) = '\0';
}
/* At this point it is expected that the current node is a
directory, check if this is true. */
if (type != GRUB_FSHELP_DIR)
{
free_node (currnode, c);
return grub_error (GRUB_ERR_BAD_FILE_TYPE, "not a directory");
}
cc.name = name;
cc.type = &type;
cc.oldnode = &oldnode;
cc.currnode = &currnode;
/* Iterate over the directory. */
found = c->iterate_dir (currnode, iterate, &cc);
if (! found)
{
if (grub_errno)
return grub_errno;
break;
}
/* Read in the symlink and follow it. */
if (type == GRUB_FSHELP_SYMLINK)
{
char *symlink;
/* Test if the symlink does not loop. */
if (++(c->symlinknest) == 8)
{
free_node (currnode, c);
free_node (oldnode, c);
return grub_error (GRUB_ERR_SYMLINK_LOOP,
"too deep nesting of symlinks");
}
symlink = c->read_symlink (currnode);
free_node (currnode, c);
if (!symlink)
{
free_node (oldnode, c);
return grub_errno;
}
/* The symlink is an absolute path, go back to the root inode. */
if (symlink[0] == '/')
{
free_node (oldnode, c);
oldnode = c->rootnode;
}
/* Lookup the node the symlink points to. */
find_file (symlink, oldnode, &currnode, c);
type = c->foundtype;
grub_free (symlink);
if (grub_errno)
{
free_node (oldnode, c);
return grub_errno;
}
}
free_node (oldnode, c);
/* Found the node! */
if (! next || *next == '\0')
{
*currfound = currnode;
c->foundtype = type;
return 0;
}
name = next;
}
return grub_error (GRUB_ERR_FILE_NOT_FOUND, "file not found");
}
/* Lookup the node PATH. The node ROOTNODE describes the root of the
directory tree. The node found is returned in FOUNDNODE, which is
either a ROOTNODE or a new malloc'ed node. ITERATE_DIR is used to
iterate over all directory entries in the current node.
READ_SYMLINK is used to read the symlink if a node is a symlink.
EXPECTTYPE is the type node that is expected by the called, an
error is generated if the node is not of the expected type. Make
sure you use the NESTED_FUNC_ATTR macro for HOOK, this is required
because GCC has a nasty bug when using regparm=3. */
grub_err_t
grub_fshelp_find_file (const char *path, grub_fshelp_node_t rootnode,
grub_fshelp_node_t *foundnode,
int (*iterate_dir) (grub_fshelp_node_t dir,
int (*hook)
(const char *filename,
enum grub_fshelp_filetype filetype,
grub_fshelp_node_t node,
void *closure),
void *closure),
void *closure,
char *(*read_symlink) (grub_fshelp_node_t node),
enum grub_fshelp_filetype expecttype)
{
grub_err_t err;
struct grub_fshelp_find_file_closure c;
c.rootnode = rootnode;
c.iterate_dir = iterate_dir;
c.closure = closure;
c.read_symlink = read_symlink;
c.symlinknest = 0;
c.foundtype = GRUB_FSHELP_DIR;
if (!path || path[0] != '/')
{
grub_error (GRUB_ERR_BAD_FILENAME, "bad filename");
return grub_errno;
}
err = find_file (path, rootnode, foundnode, &c);
if (err)
return err;
/* Check if the node that was found was of the expected type. */
if (expecttype == GRUB_FSHELP_REG && c.foundtype != expecttype)
return grub_error (GRUB_ERR_BAD_FILE_TYPE, "not a regular file");
else if (expecttype == GRUB_FSHELP_DIR && c.foundtype != expecttype)
return grub_error (GRUB_ERR_BAD_FILE_TYPE, "not a directory");
return 0;
}
unsigned long long grub_hack_lastoff = 0;
/* Read LEN bytes from the file NODE on disk DISK into the buffer BUF,
beginning with the block POS. READ_HOOK should be set before
reading a block from the file. GET_BLOCK is used to translate file
blocks to disk blocks. The file is FILESIZE bytes big and the
blocks have a size of LOG2BLOCKSIZE (in log2). */
grub_ssize_t
grub_fshelp_read_file (grub_disk_t disk, grub_fshelp_node_t node,
void (*read_hook) (grub_disk_addr_t sector,
unsigned offset,
unsigned length,
void *closure),
void *closure, int flags,
grub_off_t pos, grub_size_t len, char *buf,
grub_disk_addr_t (*get_block) (grub_fshelp_node_t node,
grub_disk_addr_t block),
grub_off_t filesize, int log2blocksize)
{
grub_disk_addr_t i, blockcnt;
int blocksize = 1 << (log2blocksize + GRUB_DISK_SECTOR_BITS);
/* Adjust LEN so it we can't read past the end of the file. */
if (pos + len > filesize)
len = filesize - pos;
blockcnt = ((len + pos) + blocksize - 1) >>
(log2blocksize + GRUB_DISK_SECTOR_BITS);
for (i = pos >> (log2blocksize + GRUB_DISK_SECTOR_BITS); i < blockcnt; i++)
{
grub_disk_addr_t blknr;
int blockoff = pos & (blocksize - 1);
int blockend = blocksize;
int skipfirst = 0;
blknr = get_block (node, i);
if (grub_errno)
return -1;
blknr = blknr << log2blocksize;
/* Last block. */
if (i == blockcnt - 1)
{
blockend = (len + pos) & (blocksize - 1);
/* The last portion is exactly blocksize. */
if (! blockend)
blockend = blocksize;
}
/* First block. */
if (i == (pos >> (log2blocksize + GRUB_DISK_SECTOR_BITS)))
{
skipfirst = blockoff;
blockend -= skipfirst;
}
/* If the block number is 0 this block is not stored on disk but
is zero filled instead. */
if (blknr)
{
disk->read_hook = read_hook;
disk->closure = closure;
//printf ("blknr: %d\n", blknr);
grub_hack_lastoff = blknr * 512;
grub_disk_read_ex (disk, blknr, skipfirst, blockend, buf, flags);
disk->read_hook = 0;
if (grub_errno)
return -1;
}
else if (buf)
grub_memset (buf, 0, blockend);
if (buf)
buf += blocksize - skipfirst;
}
return len;
}
unsigned int
grub_fshelp_log2blksize (unsigned int blksize, unsigned int *pow)
{
int mod;
*pow = 0;
while (blksize > 1)
{
mod = blksize - ((blksize >> 1) << 1);
blksize >>= 1;
/* Check if it really is a power of two. */
if (mod)
return grub_error (GRUB_ERR_BAD_NUMBER,
"the blocksize is not a power of two");
(*pow)++;
}
return GRUB_ERR_NONE;
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_3411_3 |
crossvul-cpp_data_bad_3107_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP SSSSS DDDD %
% P P SS D D %
% PPPP SSS D D %
% P SS D D %
% P SSSSS DDDD %
% %
% %
% Read/Write Adobe Photoshop Image Format %
% %
% Software Design %
% Cristy %
% Leonard Rosenthol %
% July 1992 %
% Dirk Lemstra %
% December 2013 %
% %
% %
% Copyright 1999-2017 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/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/channel.h"
#include "MagickCore/colormap.h"
#include "MagickCore/colormap-private.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/constitute.h"
#include "MagickCore/enhance.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/module.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/profile.h"
#include "MagickCore/property.h"
#include "MagickCore/registry.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
#ifdef MAGICKCORE_ZLIB_DELEGATE
#include <zlib.h>
#endif
#include "psd-private.h"
/*
Define declaractions.
*/
#define MaxPSDChannels 56
#define PSDQuantum(x) (((ssize_t) (x)+1) & -2)
/*
Enumerated declaractions.
*/
typedef enum
{
Raw = 0,
RLE = 1,
ZipWithoutPrediction = 2,
ZipWithPrediction = 3
} PSDCompressionType;
typedef enum
{
BitmapMode = 0,
GrayscaleMode = 1,
IndexedMode = 2,
RGBMode = 3,
CMYKMode = 4,
MultichannelMode = 7,
DuotoneMode = 8,
LabMode = 9
} PSDImageType;
/*
Typedef declaractions.
*/
typedef struct _ChannelInfo
{
short int
type;
size_t
size;
} ChannelInfo;
typedef struct _MaskInfo
{
Image
*image;
RectangleInfo
page;
unsigned char
background,
flags;
} MaskInfo;
typedef struct _LayerInfo
{
ChannelInfo
channel_info[MaxPSDChannels];
char
blendkey[4];
Image
*image;
MaskInfo
mask;
Quantum
opacity;
RectangleInfo
page;
size_t
offset_x,
offset_y;
unsigned char
clipping,
flags,
name[256],
visible;
unsigned short
channels;
StringInfo
*info;
} LayerInfo;
/*
Forward declarations.
*/
static MagickBooleanType
WritePSDImage(const ImageInfo *,Image *,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s P S D %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsPSD()() returns MagickTrue if the image format type, identified by the
% magick string, is PSD.
%
% The format of the IsPSD method is:
%
% MagickBooleanType IsPSD(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsPSD(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (LocaleNCompare((const char *) magick,"8BPS",4) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadPSDImage() reads an Adobe Photoshop 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 ReadPSDImage method is:
%
% Image *ReadPSDImage(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 const char *CompositeOperatorToPSDBlendMode(CompositeOperator op)
{
const char
*blend_mode;
switch (op)
{
case ColorBurnCompositeOp: blend_mode = "idiv"; break;
case ColorDodgeCompositeOp: blend_mode = "div "; break;
case ColorizeCompositeOp: blend_mode = "colr"; break;
case DarkenCompositeOp: blend_mode = "dark"; break;
case DifferenceCompositeOp: blend_mode = "diff"; break;
case DissolveCompositeOp: blend_mode = "diss"; break;
case ExclusionCompositeOp: blend_mode = "smud"; break;
case HardLightCompositeOp: blend_mode = "hLit"; break;
case HardMixCompositeOp: blend_mode = "hMix"; break;
case HueCompositeOp: blend_mode = "hue "; break;
case LightenCompositeOp: blend_mode = "lite"; break;
case LinearBurnCompositeOp: blend_mode = "lbrn"; break;
case LinearDodgeCompositeOp:blend_mode = "lddg"; break;
case LinearLightCompositeOp:blend_mode = "lLit"; break;
case LuminizeCompositeOp: blend_mode = "lum "; break;
case MultiplyCompositeOp: blend_mode = "mul "; break;
case OverCompositeOp: blend_mode = "norm"; break;
case OverlayCompositeOp: blend_mode = "over"; break;
case PinLightCompositeOp: blend_mode = "pLit"; break;
case SaturateCompositeOp: blend_mode = "sat "; break;
case ScreenCompositeOp: blend_mode = "scrn"; break;
case SoftLightCompositeOp: blend_mode = "sLit"; break;
case VividLightCompositeOp: blend_mode = "vLit"; break;
default: blend_mode = "norm";
}
return(blend_mode);
}
/*
For some reason Photoshop seems to blend semi-transparent pixels with white.
This method reverts the blending. This can be disabled by setting the
option 'psd:alpha-unblend' to off.
*/
static MagickBooleanType CorrectPSDAlphaBlend(const ImageInfo *image_info,
Image *image,ExceptionInfo* exception)
{
const char
*option;
MagickBooleanType
status;
ssize_t
y;
if (image->alpha_trait != BlendPixelTrait || image->colorspace != sRGBColorspace)
return(MagickTrue);
option=GetImageOption(image_info,"psd:alpha-unblend");
if (IsStringFalse(option) != MagickFalse)
return(MagickTrue);
status=MagickTrue;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
gamma;
register ssize_t
i;
gamma=QuantumScale*GetPixelAlpha(image, q);
if (gamma != 0.0 && gamma != 1.0)
{
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
if (channel != AlphaPixelChannel)
q[i]=ClampToQuantum((q[i]-((1.0-gamma)*QuantumRange))/gamma);
}
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
status=MagickFalse;
}
return(status);
}
static inline CompressionType ConvertPSDCompression(
PSDCompressionType compression)
{
switch (compression)
{
case RLE:
return RLECompression;
case ZipWithPrediction:
case ZipWithoutPrediction:
return ZipCompression;
default:
return NoCompression;
}
}
static MagickBooleanType ApplyPSDLayerOpacity(Image *image,Quantum opacity,
MagickBooleanType revert,ExceptionInfo *exception)
{
MagickBooleanType
status;
ssize_t
y;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" applying layer opacity %.20g", (double) opacity);
if (opacity == OpaqueAlpha)
return(MagickTrue);
image->alpha_trait=BlendPixelTrait;
status=MagickTrue;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (revert == MagickFalse)
SetPixelAlpha(image,(Quantum) (QuantumScale*(GetPixelAlpha(image,q))*
opacity),q);
else if (opacity > 0)
SetPixelAlpha(image,(Quantum) (QuantumRange*(GetPixelAlpha(image,q)/
(MagickRealType) opacity)),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
status=MagickFalse;
}
return(status);
}
static MagickBooleanType ApplyPSDOpacityMask(Image *image,const Image *mask,
Quantum background,MagickBooleanType revert,ExceptionInfo *exception)
{
Image
*complete_mask;
MagickBooleanType
status;
PixelInfo
color;
ssize_t
y;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" applying opacity mask");
complete_mask=CloneImage(image,image->columns,image->rows,MagickTrue,
exception);
complete_mask->alpha_trait=BlendPixelTrait;
GetPixelInfo(complete_mask,&color);
color.red=background;
SetImageColor(complete_mask,&color,exception);
status=CompositeImage(complete_mask,mask,OverCompositeOp,MagickTrue,
mask->page.x-image->page.x,mask->page.y-image->page.y,exception);
if (status == MagickFalse)
{
complete_mask=DestroyImage(complete_mask);
return(status);
}
image->alpha_trait=BlendPixelTrait;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register Quantum
*p;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
p=GetAuthenticPixels(complete_mask,0,y,complete_mask->columns,1,exception);
if ((q == (Quantum *) NULL) || (p == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
MagickRealType
alpha,
intensity;
alpha=GetPixelAlpha(image,q);
intensity=GetPixelIntensity(complete_mask,p);
if (revert == MagickFalse)
SetPixelAlpha(image,ClampToQuantum(intensity*(QuantumScale*alpha)),q);
else if (intensity > 0)
SetPixelAlpha(image,ClampToQuantum((alpha/intensity)*QuantumRange),q);
q+=GetPixelChannels(image);
p+=GetPixelChannels(complete_mask);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
status=MagickFalse;
}
complete_mask=DestroyImage(complete_mask);
return(status);
}
static void PreservePSDOpacityMask(Image *image,LayerInfo* layer_info,
ExceptionInfo *exception)
{
char
*key;
RandomInfo
*random_info;
StringInfo
*key_info;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" preserving opacity mask");
random_info=AcquireRandomInfo();
key_info=GetRandomKey(random_info,2+1);
key=(char *) GetStringInfoDatum(key_info);
key[8]=layer_info->mask.background;
key[9]='\0';
layer_info->mask.image->page.x+=layer_info->page.x;
layer_info->mask.image->page.y+=layer_info->page.y;
(void) SetImageRegistry(ImageRegistryType,(const char *) key,
layer_info->mask.image,exception);
(void) SetImageArtifact(layer_info->image,"psd:opacity-mask",
(const char *) key);
key_info=DestroyStringInfo(key_info);
random_info=DestroyRandomInfo(random_info);
}
static ssize_t DecodePSDPixels(const size_t number_compact_pixels,
const unsigned char *compact_pixels,const ssize_t depth,
const size_t number_pixels,unsigned char *pixels)
{
#define CheckNumberCompactPixels \
if (packets == 0) \
return(i); \
packets--
#define CheckNumberPixels(count) \
if (((ssize_t) i + count) > (ssize_t) number_pixels) \
return(i); \
i+=count
int
pixel;
register ssize_t
i,
j;
size_t
length;
ssize_t
packets;
packets=(ssize_t) number_compact_pixels;
for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); )
{
packets--;
length=(size_t) (*compact_pixels++);
if (length == 128)
continue;
if (length > 128)
{
length=256-length+1;
CheckNumberCompactPixels;
pixel=(*compact_pixels++);
for (j=0; j < (ssize_t) length; j++)
{
switch (depth)
{
case 1:
{
CheckNumberPixels(8);
*pixels++=(pixel >> 7) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 6) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 5) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 4) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 3) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 2) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 1) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 0) & 0x01 ? 0U : 255U;
break;
}
case 2:
{
CheckNumberPixels(4);
*pixels++=(unsigned char) ((pixel >> 6) & 0x03);
*pixels++=(unsigned char) ((pixel >> 4) & 0x03);
*pixels++=(unsigned char) ((pixel >> 2) & 0x03);
*pixels++=(unsigned char) ((pixel & 0x03) & 0x03);
break;
}
case 4:
{
CheckNumberPixels(2);
*pixels++=(unsigned char) ((pixel >> 4) & 0xff);
*pixels++=(unsigned char) ((pixel & 0x0f) & 0xff);
break;
}
default:
{
CheckNumberPixels(1);
*pixels++=(unsigned char) pixel;
break;
}
}
}
continue;
}
length++;
for (j=0; j < (ssize_t) length; j++)
{
CheckNumberCompactPixels;
switch (depth)
{
case 1:
{
CheckNumberPixels(8);
*pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U;
break;
}
case 2:
{
CheckNumberPixels(4);
*pixels++=(*compact_pixels >> 6) & 0x03;
*pixels++=(*compact_pixels >> 4) & 0x03;
*pixels++=(*compact_pixels >> 2) & 0x03;
*pixels++=(*compact_pixels & 0x03) & 0x03;
break;
}
case 4:
{
CheckNumberPixels(2);
*pixels++=(*compact_pixels >> 4) & 0xff;
*pixels++=(*compact_pixels & 0x0f) & 0xff;
break;
}
default:
{
CheckNumberPixels(1);
*pixels++=(*compact_pixels);
break;
}
}
compact_pixels++;
}
}
return(i);
}
static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info,
const ssize_t number_layers)
{
ssize_t
i;
for (i=0; i<number_layers; i++)
{
if (layer_info[i].image != (Image *) NULL)
layer_info[i].image=DestroyImage(layer_info[i].image);
if (layer_info[i].mask.image != (Image *) NULL)
layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image);
if (layer_info[i].info != (StringInfo *) NULL)
layer_info[i].info=DestroyStringInfo(layer_info[i].info);
}
return (LayerInfo *) RelinquishMagickMemory(layer_info);
}
static inline size_t GetPSDPacketSize(Image *image)
{
if (image->storage_class == PseudoClass)
{
if (image->colors > 256)
return(2);
else if (image->depth > 8)
return(2);
}
else
if (image->depth > 8)
return(2);
return(1);
}
static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image)
{
if (psd_info->version == 1)
return((MagickSizeType) ReadBlobLong(image));
return((MagickSizeType) ReadBlobLongLong(image));
}
static inline size_t GetPSDRowSize(Image *image)
{
if (image->depth == 1)
return(((image->columns+7)/8)*GetPSDPacketSize(image));
else
return(image->columns*GetPSDPacketSize(image));
}
static const char *ModeToString(PSDImageType type)
{
switch (type)
{
case BitmapMode: return "Bitmap";
case GrayscaleMode: return "Grayscale";
case IndexedMode: return "Indexed";
case RGBMode: return "RGB";
case CMYKMode: return "CMYK";
case MultichannelMode: return "Multichannel";
case DuotoneMode: return "Duotone";
case LabMode: return "L*A*B";
default: return "unknown";
}
}
static MagickBooleanType NegateCMYK(Image *image,ExceptionInfo *exception)
{
ChannelType
channel_mask;
MagickBooleanType
status;
channel_mask=SetImageChannelMask(image,(ChannelType)(AllChannels &~
AlphaChannel));
status=NegateImage(image,MagickFalse,exception);
(void) SetImageChannelMask(image,channel_mask);
return(status);
}
static void ParseImageResourceBlocks(Image *image,
const unsigned char *blocks,size_t length,
MagickBooleanType *has_merged_image,ExceptionInfo *exception)
{
const unsigned char
*p;
StringInfo
*profile;
unsigned int
count,
long_sans;
unsigned short
id,
short_sans;
if (length < 16)
return;
profile=BlobToStringInfo((const unsigned char *) NULL,length);
SetStringInfoDatum(profile,blocks);
(void) SetImageProfile(image,"8bim",profile,exception);
profile=DestroyStringInfo(profile);
for (p=blocks; (p >= blocks) && (p < (blocks+length-16)); )
{
if (LocaleNCompare((const char *) p,"8BIM",4) != 0)
break;
p=PushLongPixel(MSBEndian,p,&long_sans);
p=PushShortPixel(MSBEndian,p,&id);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushLongPixel(MSBEndian,p,&count);
if ((p+count) > (blocks+length-16))
return;
switch (id)
{
case 0x03ed:
{
char
value[MagickPathExtent];
unsigned short
resolution;
/*
Resolution info.
*/
p=PushShortPixel(MSBEndian,p,&resolution);
image->resolution.x=(double) resolution;
(void) FormatLocaleString(value,MagickPathExtent,"%g",image->resolution.x);
(void) SetImageProperty(image,"tiff:XResolution",value,exception);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&resolution);
image->resolution.y=(double) resolution;
(void) FormatLocaleString(value,MagickPathExtent,"%g",image->resolution.y);
(void) SetImageProperty(image,"tiff:YResolution",value,exception);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
image->units=PixelsPerInchResolution;
break;
}
case 0x0421:
{
if (*(p+4) == 0)
*has_merged_image=MagickFalse;
p+=count;
break;
}
default:
{
p+=count;
break;
}
}
if ((count & 0x01) != 0)
p++;
}
return;
}
static CompositeOperator PSDBlendModeToCompositeOperator(const char *mode)
{
if (mode == (const char *) NULL)
return(OverCompositeOp);
if (LocaleNCompare(mode,"norm",4) == 0)
return(OverCompositeOp);
if (LocaleNCompare(mode,"mul ",4) == 0)
return(MultiplyCompositeOp);
if (LocaleNCompare(mode,"diss",4) == 0)
return(DissolveCompositeOp);
if (LocaleNCompare(mode,"diff",4) == 0)
return(DifferenceCompositeOp);
if (LocaleNCompare(mode,"dark",4) == 0)
return(DarkenCompositeOp);
if (LocaleNCompare(mode,"lite",4) == 0)
return(LightenCompositeOp);
if (LocaleNCompare(mode,"hue ",4) == 0)
return(HueCompositeOp);
if (LocaleNCompare(mode,"sat ",4) == 0)
return(SaturateCompositeOp);
if (LocaleNCompare(mode,"colr",4) == 0)
return(ColorizeCompositeOp);
if (LocaleNCompare(mode,"lum ",4) == 0)
return(LuminizeCompositeOp);
if (LocaleNCompare(mode,"scrn",4) == 0)
return(ScreenCompositeOp);
if (LocaleNCompare(mode,"over",4) == 0)
return(OverlayCompositeOp);
if (LocaleNCompare(mode,"hLit",4) == 0)
return(HardLightCompositeOp);
if (LocaleNCompare(mode,"sLit",4) == 0)
return(SoftLightCompositeOp);
if (LocaleNCompare(mode,"smud",4) == 0)
return(ExclusionCompositeOp);
if (LocaleNCompare(mode,"div ",4) == 0)
return(ColorDodgeCompositeOp);
if (LocaleNCompare(mode,"idiv",4) == 0)
return(ColorBurnCompositeOp);
if (LocaleNCompare(mode,"lbrn",4) == 0)
return(LinearBurnCompositeOp);
if (LocaleNCompare(mode,"lddg",4) == 0)
return(LinearDodgeCompositeOp);
if (LocaleNCompare(mode,"lLit",4) == 0)
return(LinearLightCompositeOp);
if (LocaleNCompare(mode,"vLit",4) == 0)
return(VividLightCompositeOp);
if (LocaleNCompare(mode,"pLit",4) == 0)
return(PinLightCompositeOp);
if (LocaleNCompare(mode,"hMix",4) == 0)
return(HardMixCompositeOp);
return(OverCompositeOp);
}
static inline void ReversePSDString(Image *image,char *p,size_t length)
{
char
*q;
if (image->endian == MSBEndian)
return;
q=p+length;
for(--q; p < q; ++p, --q)
{
*p = *p ^ *q,
*q = *p ^ *q,
*p = *p ^ *q;
}
}
static inline void SetPSDPixel(Image *image,const size_t channels,
const ssize_t type,const size_t packet_size,const Quantum pixel,Quantum *q,
ExceptionInfo *exception)
{
if (image->storage_class == PseudoClass)
{
if (packet_size == 1)
SetPixelIndex(image,ScaleQuantumToChar(pixel),q);
else
SetPixelIndex(image,ScaleQuantumToShort(pixel),q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
ConstrainColormapIndex(image,GetPixelIndex(image,q),exception),q);
return;
}
switch (type)
{
case -1:
{
SetPixelAlpha(image, pixel,q);
break;
}
case -2:
case 0:
{
SetPixelRed(image,pixel,q);
if (channels == 1 || type == -2)
SetPixelGray(image,pixel,q);
break;
}
case 1:
{
if (image->storage_class == PseudoClass)
SetPixelAlpha(image,pixel,q);
else
SetPixelGreen(image,pixel,q);
break;
}
case 2:
{
if (image->storage_class == PseudoClass)
SetPixelAlpha(image,pixel,q);
else
SetPixelBlue(image,pixel,q);
break;
}
case 3:
{
if (image->colorspace == CMYKColorspace)
SetPixelBlack(image,pixel,q);
else
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,pixel,q);
break;
}
case 4:
{
if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) &&
(channels > 3))
break;
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,pixel,q);
break;
}
}
}
static MagickBooleanType ReadPSDChannelPixels(Image *image,
const size_t channels,const size_t row,const ssize_t type,
const unsigned char *pixels,ExceptionInfo *exception)
{
Quantum
pixel;
register const unsigned char
*p;
register Quantum
*q;
register ssize_t
x;
size_t
packet_size;
unsigned short
nibble;
p=pixels;
q=GetAuthenticPixels(image,0,row,image->columns,1,exception);
if (q == (Quantum *) NULL)
return MagickFalse;
packet_size=GetPSDPacketSize(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (packet_size == 1)
pixel=ScaleCharToQuantum(*p++);
else
{
p=PushShortPixel(MSBEndian,p,&nibble);
pixel=ScaleShortToQuantum(nibble);
}
if (image->depth > 1)
{
SetPSDPixel(image,channels,type,packet_size,pixel,q,exception);
q+=GetPixelChannels(image);
}
else
{
ssize_t
bit,
number_bits;
number_bits=image->columns-x;
if (number_bits > 8)
number_bits=8;
for (bit = 0; bit < number_bits; bit++)
{
SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel)
& (0x01 << (7-bit))) != 0 ? 0 : QuantumRange,q,exception);
q+=GetPixelChannels(image);
x++;
}
if (x != (ssize_t) image->columns)
x--;
continue;
}
}
return(SyncAuthenticPixels(image,exception));
}
static MagickBooleanType ReadPSDChannelRaw(Image *image,const size_t channels,
const ssize_t type,ExceptionInfo *exception)
{
MagickBooleanType
status;
size_t
count,
row_size;
ssize_t
y;
unsigned char
*pixels;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is RAW");
row_size=GetPSDRowSize(image);
pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=MagickTrue;
for (y=0; y < (ssize_t) image->rows; y++)
{
status=MagickFalse;
count=ReadBlob(image,row_size,pixels);
if (count != row_size)
break;
status=ReadPSDChannelPixels(image,channels,y,type,pixels,exception);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(status);
}
static inline MagickOffsetType *ReadPSDRLESizes(Image *image,
const PSDInfo *psd_info,const size_t size)
{
MagickOffsetType
*sizes;
ssize_t
y;
sizes=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*sizes));
if(sizes != (MagickOffsetType *) NULL)
{
for (y=0; y < (ssize_t) size; y++)
{
if (psd_info->version == 1)
sizes[y]=(MagickOffsetType) ReadBlobShort(image);
else
sizes[y]=(MagickOffsetType) ReadBlobLong(image);
}
}
return sizes;
}
static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info,
const ssize_t type,MagickOffsetType *sizes,ExceptionInfo *exception)
{
MagickBooleanType
status;
size_t
length,
row_size;
ssize_t
count,
y;
unsigned char
*compact_pixels,
*pixels;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is RLE compressed");
row_size=GetPSDRowSize(image);
pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
length=0;
for (y=0; y < (ssize_t) image->rows; y++)
if ((MagickOffsetType) length < sizes[y])
length=(size_t) sizes[y];
if (length > row_size + 256) // arbitrary number
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
ThrowBinaryException(ResourceLimitError,"InvalidLength",
image->filename);
}
compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels));
if (compact_pixels == (unsigned char *) NULL)
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
(void) ResetMagickMemory(compact_pixels,0,length*sizeof(*compact_pixels));
status=MagickTrue;
for (y=0; y < (ssize_t) image->rows; y++)
{
status=MagickFalse;
count=ReadBlob(image,(size_t) sizes[y],compact_pixels);
if (count != (ssize_t) sizes[y])
break;
count=DecodePSDPixels((size_t) sizes[y],compact_pixels,
(ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels);
if (count != (ssize_t) row_size)
break;
status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels,
exception);
if (status == MagickFalse)
break;
}
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(status);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels,
const ssize_t type,const PSDCompressionType compression,
const size_t compact_size,ExceptionInfo *exception)
{
MagickBooleanType
status;
register unsigned char
*p;
size_t
count,
length,
packet_size,
row_size;
ssize_t
y;
unsigned char
*compact_pixels,
*pixels;
z_stream
stream;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is ZIP compressed");
compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size,
sizeof(*compact_pixels));
if (compact_pixels == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
packet_size=GetPSDPacketSize(image);
row_size=image->columns*packet_size;
count=image->rows*row_size;
pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
{
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
ResetMagickMemory(&stream,0,sizeof(stream));
stream.data_type=Z_BINARY;
(void) ReadBlob(image,compact_size,compact_pixels);
stream.next_in=(Bytef *)compact_pixels;
stream.avail_in=(uInt) compact_size;
stream.next_out=(Bytef *)pixels;
stream.avail_out=(uInt) count;
if (inflateInit(&stream) == Z_OK)
{
int
ret;
while (stream.avail_out > 0)
{
ret=inflate(&stream,Z_SYNC_FLUSH);
if ((ret != Z_OK) && (ret != Z_STREAM_END))
{
compact_pixels=(unsigned char *) RelinquishMagickMemory(
compact_pixels);
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(MagickFalse);
}
}
}
if (compression == ZipWithPrediction)
{
p=pixels;
while (count > 0)
{
length=image->columns;
while (--length)
{
if (packet_size == 2)
{
p[2]+=p[0]+((p[1]+p[3]) >> 8);
p[3]+=p[1];
}
else
*(p+1)+=*p;
p+=packet_size;
}
p+=packet_size;
count-=row_size;
}
}
status=MagickTrue;
p=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
status=ReadPSDChannelPixels(image,channels,y,type,p,exception);
if (status == MagickFalse)
break;
p+=row_size;
}
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(status);
}
#endif
static MagickBooleanType ReadPSDChannel(Image *image,
const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info,
const size_t channel,const PSDCompressionType compression,
ExceptionInfo *exception)
{
Image
*channel_image,
*mask;
MagickOffsetType
offset;
MagickBooleanType
status;
channel_image=image;
mask=(Image *) NULL;
if (layer_info->channel_info[channel].type < -1)
{
const char
*option;
/*
Ignore mask that is not a user supplied layer mask, if the mask is
disabled or if the flags have unsupported values.
*/
option=GetImageOption(image_info,"psd:preserve-opacity-mask");
if ((layer_info->channel_info[channel].type != -2) ||
(layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) &&
(IsStringTrue(option) == MagickFalse)))
{
SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR);
return(MagickTrue);
}
mask=CloneImage(image,layer_info->mask.page.width,
layer_info->mask.page.height,MagickFalse,exception);
SetImageType(mask,GrayscaleType,exception);
channel_image=mask;
}
offset=TellBlob(image);
status=MagickTrue;
switch(compression)
{
case Raw:
status=ReadPSDChannelRaw(channel_image,psd_info->channels,
layer_info->channel_info[channel].type,exception);
break;
case RLE:
{
MagickOffsetType
*sizes;
sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows);
if (sizes == (MagickOffsetType *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=ReadPSDChannelRLE(channel_image,psd_info,
layer_info->channel_info[channel].type,sizes,exception);
sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes);
}
break;
case ZipWithPrediction:
case ZipWithoutPrediction:
#ifdef MAGICKCORE_ZLIB_DELEGATE
status=ReadPSDChannelZip(channel_image,layer_info->channels,
layer_info->channel_info[channel].type,compression,
layer_info->channel_info[channel].size-2,exception);
#else
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn",
"'%s' (ZLIB)",image->filename);
#endif
break;
default:
(void) ThrowMagickException(exception,GetMagickModule(),TypeWarning,
"CompressionNotSupported","'%.20g'",(double) compression);
break;
}
SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET);
if (status == MagickFalse)
{
if (mask != (Image *) NULL)
DestroyImage(mask);
ThrowBinaryException(CoderError,"UnableToDecompressImage",
image->filename);
}
layer_info->mask.image=mask;
return(status);
}
static MagickBooleanType ReadPSDLayer(Image *image,const ImageInfo *image_info,
const PSDInfo *psd_info,LayerInfo* layer_info,ExceptionInfo *exception)
{
char
message[MagickPathExtent];
MagickBooleanType
status;
PSDCompressionType
compression;
ssize_t
j;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" setting up new layer image");
if (psd_info->mode != IndexedMode)
(void) SetImageBackgroundColor(layer_info->image,exception);
layer_info->image->compose=PSDBlendModeToCompositeOperator(
layer_info->blendkey);
if (layer_info->visible == MagickFalse)
layer_info->image->compose=NoCompositeOp;
if (psd_info->mode == CMYKMode)
SetImageColorspace(layer_info->image,CMYKColorspace,exception);
else if ((psd_info->mode == BitmapMode) || (psd_info->mode == DuotoneMode) ||
(psd_info->mode == GrayscaleMode))
SetImageColorspace(layer_info->image,GRAYColorspace,exception);
/*
Set up some hidden attributes for folks that need them.
*/
(void) FormatLocaleString(message,MagickPathExtent,"%.20g",
(double) layer_info->page.x);
(void) SetImageArtifact(layer_info->image,"psd:layer.x",message);
(void) FormatLocaleString(message,MagickPathExtent,"%.20g",
(double) layer_info->page.y);
(void) SetImageArtifact(layer_info->image,"psd:layer.y",message);
(void) FormatLocaleString(message,MagickPathExtent,"%.20g",(double)
layer_info->opacity);
(void) SetImageArtifact(layer_info->image,"psd:layer.opacity",message);
(void) SetImageProperty(layer_info->image,"label",(char *) layer_info->name,
exception);
status=MagickTrue;
for (j=0; j < (ssize_t) layer_info->channels; j++)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading data for channel %.20g",(double) j);
compression=(PSDCompressionType) ReadBlobShort(layer_info->image);
layer_info->image->compression=ConvertPSDCompression(compression);
if (layer_info->channel_info[j].type == -1)
layer_info->image->alpha_trait=BlendPixelTrait;
status=ReadPSDChannel(layer_info->image,image_info,psd_info,layer_info,j,
compression,exception);
if (status == MagickFalse)
break;
}
if (status != MagickFalse)
status=ApplyPSDLayerOpacity(layer_info->image,layer_info->opacity,
MagickFalse,exception);
if ((status != MagickFalse) &&
(layer_info->image->colorspace == CMYKColorspace))
status=NegateCMYK(layer_info->image,exception);
if ((status != MagickFalse) && (layer_info->mask.image != (Image *) NULL))
{
const char
*option;
layer_info->mask.image->page.x=layer_info->mask.page.x;
layer_info->mask.image->page.y=layer_info->mask.page.y;
/* Do not composite the mask when it is disabled */
if ((layer_info->mask.flags & 0x02) == 0x02)
layer_info->mask.image->compose=NoCompositeOp;
else
status=ApplyPSDOpacityMask(layer_info->image,layer_info->mask.image,
layer_info->mask.background == 0 ? 0 : QuantumRange,MagickFalse,
exception);
option=GetImageOption(image_info,"psd:preserve-opacity-mask");
if (IsStringTrue(option) != MagickFalse)
PreservePSDOpacityMask(image,layer_info,exception);
layer_info->mask.image=DestroyImage(layer_info->mask.image);
}
return(status);
}
ModuleExport MagickBooleanType ReadPSDLayers(Image *image,
const ImageInfo *image_info,const PSDInfo *psd_info,
const MagickBooleanType skip_layers,ExceptionInfo *exception)
{
char
type[4];
LayerInfo
*layer_info;
MagickSizeType
size;
MagickBooleanType
status;
register ssize_t
i;
ssize_t
count,
j,
number_layers;
size=GetPSDSize(psd_info,image);
if (size == 0)
{
/*
Skip layers & masks.
*/
(void) ReadBlobLong(image);
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
status=MagickFalse;
if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0))
return(MagickTrue);
else
{
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
if ((count != 0) && (LocaleNCompare(type,"Lr16",4) == 0))
size=GetPSDSize(psd_info,image);
else
return(MagickTrue);
}
}
status=MagickTrue;
if (size != 0)
{
layer_info=(LayerInfo *) NULL;
number_layers=(short) ReadBlobShort(image);
if (number_layers < 0)
{
/*
The first alpha channel in the merged result contains the
transparency data for the merged result.
*/
number_layers=MagickAbsoluteValue(number_layers);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" negative layer count corrected for");
image->alpha_trait=BlendPixelTrait;
}
/*
We only need to know if the image has an alpha channel
*/
if (skip_layers != MagickFalse)
return(MagickTrue);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image contains %.20g layers",(double) number_layers);
if (number_layers == 0)
ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers",
image->filename);
layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers,
sizeof(*layer_info));
if (layer_info == (LayerInfo *) NULL)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" allocation of LayerInfo failed");
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
(void) ResetMagickMemory(layer_info,0,(size_t) number_layers*
sizeof(*layer_info));
for (i=0; i < number_layers; i++)
{
ssize_t
x,
y;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading layer #%.20g",(double) i+1);
layer_info[i].page.y=ReadBlobSignedLong(image);
layer_info[i].page.x=ReadBlobSignedLong(image);
y=ReadBlobSignedLong(image);
x=ReadBlobSignedLong(image);
layer_info[i].page.width=(size_t) (x-layer_info[i].page.x);
layer_info[i].page.height=(size_t) (y-layer_info[i].page.y);
layer_info[i].channels=ReadBlobShort(image);
if (layer_info[i].channels > MaxPSDChannels)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded",
image->filename);
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g",
(double) layer_info[i].page.x,(double) layer_info[i].page.y,
(double) layer_info[i].page.height,(double)
layer_info[i].page.width,(double) layer_info[i].channels);
for (j=0; j < (ssize_t) layer_info[i].channels; j++)
{
layer_info[i].channel_info[j].type=(short) ReadBlobShort(image);
layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info,
image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" channel[%.20g]: type=%.20g, size=%.20g",(double) j,
(double) layer_info[i].channel_info[j].type,
(double) layer_info[i].channel_info[j].size);
}
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer type was %.4s instead of 8BIM", type);
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"ImproperImageHeader",
image->filename);
}
count=ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey);
ReversePSDString(image,layer_info[i].blendkey,4);
layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
layer_info[i].clipping=(unsigned char) ReadBlobByte(image);
layer_info[i].flags=(unsigned char) ReadBlobByte(image);
layer_info[i].visible=!(layer_info[i].flags & 0x02);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s",
layer_info[i].blendkey,(double) layer_info[i].opacity,
layer_info[i].clipping ? "true" : "false",layer_info[i].flags,
layer_info[i].visible ? "true" : "false");
(void) ReadBlobByte(image); /* filler */
size=ReadBlobLong(image);
if (size != 0)
{
MagickSizeType
combined_length,
length;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer contains additional info");
length=ReadBlobLong(image);
combined_length=length+4;
if (length != 0)
{
/*
Layer mask info.
*/
layer_info[i].mask.page.y=ReadBlobSignedLong(image);
layer_info[i].mask.page.x=ReadBlobSignedLong(image);
layer_info[i].mask.page.height=(size_t) (ReadBlobLong(image)-
layer_info[i].mask.page.y);
layer_info[i].mask.page.width=(size_t) (ReadBlobLong(image)-
layer_info[i].mask.page.x);
layer_info[i].mask.background=(unsigned char) ReadBlobByte(
image);
layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image);
if (!(layer_info[i].mask.flags & 0x01))
{
layer_info[i].mask.page.y=layer_info[i].mask.page.y-
layer_info[i].page.y;
layer_info[i].mask.page.x=layer_info[i].mask.page.x-
layer_info[i].page.x;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g",
(double) layer_info[i].mask.page.x,(double)
layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width,
(double) layer_info[i].mask.page.height,(double)
((MagickOffsetType) length)-18);
/*
Skip over the rest of the layer mask information.
*/
if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile",
image->filename);
}
}
length=ReadBlobLong(image);
combined_length+=length+4;
if (length != 0)
{
/*
Layer blending ranges info.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer blending ranges: length=%.20g",(double)
((MagickOffsetType) length));
/*
We read it, but don't use it...
*/
for (j=0; j < (ssize_t) length; j+=8)
{
size_t blend_source=ReadBlobLong(image);
size_t blend_dest=ReadBlobLong(image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" source(%x), dest(%x)",(unsigned int)
blend_source,(unsigned int) blend_dest);
}
}
/*
Layer name.
*/
length=(MagickSizeType) (unsigned char) ReadBlobByte(image);
combined_length+=length+1;
if (length > 0)
(void) ReadBlob(image,(size_t) length++,layer_info[i].name);
layer_info[i].name[length]='\0';
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer name: %s",layer_info[i].name);
if ((length % 4) != 0)
{
length=4-(length % 4);
combined_length+=length;
/* Skip over the padding of the layer name */
if (DiscardBlobBytes(image,length) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
}
length=(MagickSizeType) size-combined_length;
if (length > 0)
{
unsigned char
*info;
layer_info[i].info=AcquireStringInfo((const size_t) length);
info=GetStringInfoDatum(layer_info[i].info);
(void) ReadBlob(image,(const size_t) length,info);
}
}
}
for (i=0; i < number_layers; i++)
{
if ((layer_info[i].page.width == 0) ||
(layer_info[i].page.height == 0))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is empty");
if (layer_info[i].info != (StringInfo *) NULL)
layer_info[i].info=DestroyStringInfo(layer_info[i].info);
continue;
}
/*
Allocate layered image.
*/
layer_info[i].image=CloneImage(image,layer_info[i].page.width,
layer_info[i].page.height,MagickFalse,exception);
if (layer_info[i].image == (Image *) NULL)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" allocation of image for layer %.20g failed",(double) i);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
if (layer_info[i].info != (StringInfo *) NULL)
{
(void) SetImageProfile(layer_info[i].image,"psd:additional-info",
layer_info[i].info,exception);
layer_info[i].info=DestroyStringInfo(layer_info[i].info);
}
}
if (image_info->ping == MagickFalse)
{
for (i=0; i < number_layers; i++)
{
if (layer_info[i].image == (Image *) NULL)
{
for (j=0; j < layer_info[i].channels; j++)
{
if (DiscardBlobBytes(image,(MagickSizeType)
layer_info[i].channel_info[j].size) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
}
continue;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading data for layer %.20g",(double) i);
status=ReadPSDLayer(image,image_info,psd_info,&layer_info[i],
exception);
if (status == MagickFalse)
break;
status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType)
number_layers);
if (status == MagickFalse)
break;
}
}
if (status != MagickFalse)
{
for (i=0; i < number_layers; i++)
{
if (layer_info[i].image == (Image *) NULL)
{
for (j=i; j < number_layers - 1; j++)
layer_info[j] = layer_info[j+1];
number_layers--;
i--;
}
}
if (number_layers > 0)
{
for (i=0; i < number_layers; i++)
{
if (i > 0)
layer_info[i].image->previous=layer_info[i-1].image;
if (i < (number_layers-1))
layer_info[i].image->next=layer_info[i+1].image;
layer_info[i].image->page=layer_info[i].page;
}
image->next=layer_info[0].image;
layer_info[0].image->previous=image;
}
layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info);
}
else
layer_info=DestroyLayerInfo(layer_info,number_layers);
}
return(status);
}
static MagickBooleanType ReadPSDMergedImage(const ImageInfo *image_info,
Image *image,const PSDInfo *psd_info,ExceptionInfo *exception)
{
MagickOffsetType
*sizes;
MagickBooleanType
status;
PSDCompressionType
compression;
register ssize_t
i;
compression=(PSDCompressionType) ReadBlobMSBShort(image);
image->compression=ConvertPSDCompression(compression);
if (compression != Raw && compression != RLE)
{
(void) ThrowMagickException(exception,GetMagickModule(),
TypeWarning,"CompressionNotSupported","'%.20g'",(double) compression);
return(MagickFalse);
}
sizes=(MagickOffsetType *) NULL;
if (compression == RLE)
{
sizes=ReadPSDRLESizes(image,psd_info,image->rows*psd_info->channels);
if (sizes == (MagickOffsetType *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
status=MagickTrue;
for (i=0; i < (ssize_t) psd_info->channels; i++)
{
if (compression == RLE)
status=ReadPSDChannelRLE(image,psd_info,i,sizes+(i*image->rows),
exception);
else
status=ReadPSDChannelRaw(image,psd_info->channels,i,exception);
if (status != MagickFalse)
status=SetImageProgress(image,LoadImagesTag,i,psd_info->channels);
if (status == MagickFalse)
break;
}
if ((status != MagickFalse) && (image->colorspace == CMYKColorspace))
status=NegateCMYK(image,exception);
if (status != MagickFalse)
status=CorrectPSDAlphaBlend(image_info,image,exception);
sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes);
return(status);
}
static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
has_merged_image,
skip_layers;
MagickOffsetType
offset;
MagickSizeType
length;
MagickBooleanType
status;
PSDInfo
psd_info;
register ssize_t
i;
ssize_t
count;
unsigned char
*data;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read image header.
*/
image->endian=MSBEndian;
count=ReadBlob(image,4,(unsigned char *) psd_info.signature);
psd_info.version=ReadBlobMSBShort(image);
if ((count == 0) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) ||
((psd_info.version != 1) && (psd_info.version != 2)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
(void) ReadBlob(image,6,psd_info.reserved);
psd_info.channels=ReadBlobMSBShort(image);
if (psd_info.channels > MaxPSDChannels)
ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded");
psd_info.rows=ReadBlobMSBLong(image);
psd_info.columns=ReadBlobMSBLong(image);
if ((psd_info.version == 1) && ((psd_info.rows > 30000) ||
(psd_info.columns > 30000)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
psd_info.depth=ReadBlobMSBShort(image);
if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
psd_info.mode=ReadBlobMSBShort(image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s",
(double) psd_info.columns,(double) psd_info.rows,(double)
psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType)
psd_info.mode));
/*
Initialize image.
*/
image->depth=psd_info.depth;
image->columns=psd_info.columns;
image->rows=psd_info.rows;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
if (SetImageBackgroundColor(image,exception) == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
if (psd_info.mode == LabMode)
SetImageColorspace(image,LabColorspace,exception);
if (psd_info.mode == CMYKMode)
{
SetImageColorspace(image,CMYKColorspace,exception);
if (psd_info.channels > 4)
SetImageAlphaChannel(image,ActivateAlphaChannel,exception);
}
else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) ||
(psd_info.mode == DuotoneMode))
{
status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536,
exception);
if (status == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image colormap allocated");
SetImageColorspace(image,GRAYColorspace,exception);
if (psd_info.channels > 1)
SetImageAlphaChannel(image,ActivateAlphaChannel,exception);
}
else
if (psd_info.channels > 3)
SetImageAlphaChannel(image,ActivateAlphaChannel,exception);
/*
Read PSD raster colormap only present for indexed and duotone images.
*/
length=ReadBlobMSBLong(image);
if (length != 0)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading colormap");
if (psd_info.mode == DuotoneMode)
{
/*
Duotone image data; the format of this data is undocumented.
*/
data=(unsigned char *) AcquireQuantumMemory((size_t) length,
sizeof(*data));
if (data == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ReadBlob(image,(size_t) length,data);
data=(unsigned char *) RelinquishMagickMemory(data);
}
else
{
size_t
number_colors;
/*
Read PSD raster colormap.
*/
number_colors=length/3;
if (number_colors > 65536)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (AcquireImageColormap(image,number_colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].red=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].green=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].blue=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->alpha_trait=UndefinedPixelTrait;
}
}
if ((image->depth == 1) && (image->storage_class != PseudoClass))
ThrowReaderException(CorruptImageError, "ImproperImageHeader");
has_merged_image=MagickTrue;
length=ReadBlobMSBLong(image);
if (length != 0)
{
unsigned char
*blocks;
/*
Image resources block.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading image resource blocks - %.20g bytes",(double)
((MagickOffsetType) length));
blocks=(unsigned char *) AcquireQuantumMemory((size_t) length,
sizeof(*blocks));
if (blocks == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,(size_t) length,blocks);
if ((count != (ssize_t) length) || (length < 4) ||
(LocaleNCompare((char *) blocks,"8BIM",4) != 0))
{
blocks=(unsigned char *) RelinquishMagickMemory(blocks);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image,
exception);
blocks=(unsigned char *) RelinquishMagickMemory(blocks);
}
/*
Layer and mask block.
*/
length=GetPSDSize(&psd_info,image);
if (length == 8)
{
length=ReadBlobMSBLong(image);
length=ReadBlobMSBLong(image);
}
offset=TellBlob(image);
skip_layers=MagickFalse;
if ((image_info->number_scenes == 1) && (image_info->scene == 0) &&
(has_merged_image != MagickFalse))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" read composite only");
skip_layers=MagickTrue;
}
if (length == 0)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image has no layers");
}
else
{
if (ReadPSDLayers(image,image_info,&psd_info,skip_layers,exception) !=
MagickTrue)
{
(void) CloseBlob(image);
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Skip the rest of the layer and mask information.
*/
SeekBlob(image,offset+length,SEEK_SET);
}
/*
If we are only "pinging" the image, then we're done - so return.
*/
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
Read the precombined layer, present for PSD < 4 compatibility.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading the precombined layer");
if ((has_merged_image != MagickFalse) || (GetImageListLength(image) == 1))
has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image,
&psd_info,exception);
if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) &&
(length != 0))
{
SeekBlob(image,offset,SEEK_SET);
status=ReadPSDLayers(image,image_info,&psd_info,MagickFalse,exception);
if (status != MagickTrue)
{
(void) CloseBlob(image);
image=DestroyImageList(image);
return((Image *) NULL);
}
}
if (has_merged_image == MagickFalse)
{
Image
*merged;
if (GetImageListLength(image) == 1)
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
SetImageAlphaChannel(image,TransparentAlphaChannel,exception);
image->background_color.alpha=TransparentAlpha;
image->background_color.alpha_trait=BlendPixelTrait;
merged=MergeImageLayers(image,FlattenLayer,exception);
ReplaceImageInList(&image,merged);
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterPSDImage() adds properties for the PSD image format to
% the list of supported formats. The properties 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 RegisterPSDImage method is:
%
% size_t RegisterPSDImage(void)
%
*/
ModuleExport size_t RegisterPSDImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("PSD","PSB","Adobe Large Document Format");
entry->decoder=(DecodeImageHandler *) ReadPSDImage;
entry->encoder=(EncodeImageHandler *) WritePSDImage;
entry->magick=(IsImageFormatHandler *) IsPSD;
entry->flags|=CoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("PSD","PSD","Adobe Photoshop bitmap");
entry->decoder=(DecodeImageHandler *) ReadPSDImage;
entry->encoder=(EncodeImageHandler *) WritePSDImage;
entry->magick=(IsImageFormatHandler *) IsPSD;
entry->flags|=CoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterPSDImage() removes format registrations made by the
% PSD module from the list of supported formats.
%
% The format of the UnregisterPSDImage method is:
%
% UnregisterPSDImage(void)
%
*/
ModuleExport void UnregisterPSDImage(void)
{
(void) UnregisterMagickInfo("PSB");
(void) UnregisterMagickInfo("PSD");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WritePSDImage() writes an image in the Adobe Photoshop encoded image format.
%
% The format of the WritePSDImage method is:
%
% MagickBooleanType WritePSDImage(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 inline ssize_t SetPSDOffset(const PSDInfo *psd_info,Image *image,
const size_t offset)
{
if (psd_info->version == 1)
return(WriteBlobMSBShort(image,(unsigned short) offset));
return(WriteBlobMSBLong(image,(unsigned short) offset));
}
static inline ssize_t WritePSDOffset(const PSDInfo *psd_info,Image *image,
const MagickSizeType size,const MagickSizeType offset)
{
MagickSizeType
current_offset;
ssize_t
result;
current_offset=TellBlob(image);
SeekBlob(image,offset,SEEK_SET);
if (psd_info->version == 1)
result=WriteBlobMSBShort(image,(unsigned short) size);
else
result=(WriteBlobMSBLong(image,(unsigned short) size));
SeekBlob(image,current_offset,SEEK_SET);
return(result);
}
static inline ssize_t SetPSDSize(const PSDInfo *psd_info,Image *image,
const MagickSizeType size)
{
if (psd_info->version == 1)
return(WriteBlobMSBLong(image,(unsigned int) size));
return(WriteBlobMSBLongLong(image,size));
}
static inline ssize_t WritePSDSize(const PSDInfo *psd_info,Image *image,
const MagickSizeType size,const MagickSizeType offset)
{
MagickSizeType
current_offset;
ssize_t
result;
current_offset=TellBlob(image);
SeekBlob(image,offset,SEEK_SET);
if (psd_info->version == 1)
result=WriteBlobMSBLong(image,(unsigned int) size);
else
result=WriteBlobMSBLongLong(image,size);
SeekBlob(image,current_offset,SEEK_SET);
return(result);
}
static size_t PSDPackbitsEncodeImage(Image *image,const size_t length,
const unsigned char *pixels,unsigned char *compact_pixels,
ExceptionInfo *exception)
{
int
count;
register ssize_t
i,
j;
register unsigned char
*q;
unsigned char
*packbits;
/*
Compress pixels with Packbits encoding.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(pixels != (unsigned char *) NULL);
assert(compact_pixels != (unsigned char *) NULL);
packbits=(unsigned char *) AcquireQuantumMemory(128UL,sizeof(*packbits));
if (packbits == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
q=compact_pixels;
for (i=(ssize_t) length; i != 0; )
{
switch (i)
{
case 1:
{
i--;
*q++=(unsigned char) 0;
*q++=(*pixels);
break;
}
case 2:
{
i-=2;
*q++=(unsigned char) 1;
*q++=(*pixels);
*q++=pixels[1];
break;
}
case 3:
{
i-=3;
if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2)))
{
*q++=(unsigned char) ((256-3)+1);
*q++=(*pixels);
break;
}
*q++=(unsigned char) 2;
*q++=(*pixels);
*q++=pixels[1];
*q++=pixels[2];
break;
}
default:
{
if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2)))
{
/*
Packed run.
*/
count=3;
while (((ssize_t) count < i) && (*pixels == *(pixels+count)))
{
count++;
if (count >= 127)
break;
}
i-=count;
*q++=(unsigned char) ((256-count)+1);
*q++=(*pixels);
pixels+=count;
break;
}
/*
Literal run.
*/
count=0;
while ((*(pixels+count) != *(pixels+count+1)) ||
(*(pixels+count+1) != *(pixels+count+2)))
{
packbits[count+1]=pixels[count];
count++;
if (((ssize_t) count >= (i-3)) || (count >= 127))
break;
}
i-=count;
*packbits=(unsigned char) (count-1);
for (j=0; j <= (ssize_t) count; j++)
*q++=packbits[j];
pixels+=count;
break;
}
}
}
*q++=(unsigned char) 128; /* EOD marker */
packbits=(unsigned char *) RelinquishMagickMemory(packbits);
return((size_t) (q-compact_pixels));
}
static size_t WriteCompressionStart(const PSDInfo *psd_info,Image *image,
const Image *next_image,const ssize_t channels)
{
size_t
length;
ssize_t
i,
y;
if (next_image->compression == RLECompression)
{
length=WriteBlobMSBShort(image,RLE);
for (i=0; i < channels; i++)
for (y=0; y < (ssize_t) next_image->rows; y++)
length+=SetPSDOffset(psd_info,image,0);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
else if (next_image->compression == ZipCompression)
length=WriteBlobMSBShort(image,ZipWithoutPrediction);
#endif
else
length=WriteBlobMSBShort(image,Raw);
return(length);
}
static size_t WritePSDChannel(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
const QuantumType quantum_type, unsigned char *compact_pixels,
MagickOffsetType size_offset,const MagickBooleanType separate,
ExceptionInfo *exception)
{
int
y;
MagickBooleanType
monochrome;
QuantumInfo
*quantum_info;
register const Quantum
*p;
register ssize_t
i;
size_t
count,
length;
unsigned char
*pixels;
#ifdef MAGICKCORE_ZLIB_DELEGATE
#define CHUNK 16384
int
flush,
level;
unsigned char
*compressed_pixels;
z_stream
stream;
compressed_pixels=(unsigned char *) NULL;
flush=Z_NO_FLUSH;
#endif
count=0;
if (separate != MagickFalse)
{
size_offset=TellBlob(image)+2;
count+=WriteCompressionStart(psd_info,image,next_image,1);
}
if (next_image->depth > 8)
next_image->depth=16;
monochrome=IsImageMonochrome(image) && (image->depth == 1) ?
MagickTrue : MagickFalse;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
return(0);
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
#ifdef MAGICKCORE_ZLIB_DELEGATE
if (next_image->compression == ZipCompression)
{
compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK,
sizeof(*compressed_pixels));
if (compressed_pixels == (unsigned char *) NULL)
{
quantum_info=DestroyQuantumInfo(quantum_info);
return(0);
}
ResetMagickMemory(&stream,0,sizeof(stream));
stream.data_type=Z_BINARY;
level=Z_DEFAULT_COMPRESSION;
if ((image_info->quality > 0 && image_info->quality < 10))
level=(int) image_info->quality;
if (deflateInit(&stream,level) != Z_OK)
{
quantum_info=DestroyQuantumInfo(quantum_info);
return(0);
}
}
#endif
for (y=0; y < (ssize_t) next_image->rows; y++)
{
p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (monochrome != MagickFalse)
for (i=0; i < (ssize_t) length; i++)
pixels[i]=(~pixels[i]);
if (next_image->compression == RLECompression)
{
length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels,
exception);
count+=WriteBlob(image,length,compact_pixels);
size_offset+=WritePSDOffset(psd_info,image,length,size_offset);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
else if (next_image->compression == ZipCompression)
{
stream.avail_in=(uInt) length;
stream.next_in=(Bytef *) pixels;
if (y == (ssize_t) next_image->rows-1)
flush=Z_FINISH;
do {
stream.avail_out=(uInt) CHUNK;
stream.next_out=(Bytef *) compressed_pixels;
if (deflate(&stream,flush) == Z_STREAM_ERROR)
break;
length=(size_t) CHUNK-stream.avail_out;
if (length > 0)
count+=WriteBlob(image,length,compressed_pixels);
} while (stream.avail_out == 0);
}
#endif
else
count+=WriteBlob(image,length,pixels);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
if (next_image->compression == ZipCompression)
{
(void) deflateEnd(&stream);
compressed_pixels=(unsigned char *) RelinquishMagickMemory(
compressed_pixels);
}
#endif
quantum_info=DestroyQuantumInfo(quantum_info);
return(count);
}
static unsigned char *AcquireCompactPixels(const Image *image,
ExceptionInfo *exception)
{
size_t
packet_size;
unsigned char
*compact_pixels;
packet_size=image->depth > 8UL ? 2UL : 1UL;
compact_pixels=(unsigned char *) AcquireQuantumMemory((9*
image->columns)+1,packet_size*sizeof(*compact_pixels));
if (compact_pixels == (unsigned char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
image->filename);
}
return(compact_pixels);
}
static size_t WritePSDChannels(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
MagickOffsetType size_offset,const MagickBooleanType separate,
ExceptionInfo *exception)
{
Image
*mask;
MagickOffsetType
rows_offset;
size_t
channels,
count,
length,
offset_length;
unsigned char
*compact_pixels;
count=0;
offset_length=0;
rows_offset=0;
compact_pixels=(unsigned char *) NULL;
if (next_image->compression == RLECompression)
{
compact_pixels=AcquireCompactPixels(image,exception);
if (compact_pixels == (unsigned char *) NULL)
return(0);
}
channels=1;
if (separate == MagickFalse)
{
if (next_image->storage_class != PseudoClass)
{
if (IsImageGray(next_image) == MagickFalse)
channels=next_image->colorspace == CMYKColorspace ? 4 : 3;
if (next_image->alpha_trait != UndefinedPixelTrait)
channels++;
}
rows_offset=TellBlob(image)+2;
count+=WriteCompressionStart(psd_info,image,next_image,channels);
offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4));
}
size_offset+=2;
if (next_image->storage_class == PseudoClass)
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
IndexQuantum,compact_pixels,rows_offset,separate,exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
else
{
if (IsImageGray(next_image) != MagickFalse)
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
GrayQuantum,compact_pixels,rows_offset,separate,exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
else
{
if (next_image->colorspace == CMYKColorspace)
(void) NegateCMYK(next_image,exception);
length=WritePSDChannel(psd_info,image_info,image,next_image,
RedQuantum,compact_pixels,rows_offset,separate,exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
length=WritePSDChannel(psd_info,image_info,image,next_image,
GreenQuantum,compact_pixels,rows_offset,separate,exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
length=WritePSDChannel(psd_info,image_info,image,next_image,
BlueQuantum,compact_pixels,rows_offset,separate,exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
if (next_image->colorspace == CMYKColorspace)
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
BlackQuantum,compact_pixels,rows_offset,separate,exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
}
if (next_image->alpha_trait != UndefinedPixelTrait)
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
AlphaQuantum,compact_pixels,rows_offset,separate,exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
}
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
if (next_image->colorspace == CMYKColorspace)
(void) NegateCMYK(next_image,exception);
if (separate != MagickFalse)
{
const char
*property;
property=GetImageArtifact(next_image,"psd:opacity-mask");
if (property != (const char *) NULL)
{
mask=(Image *) GetImageRegistry(ImageRegistryType,property,
exception);
if (mask != (Image *) NULL)
{
if (mask->compression == RLECompression)
{
compact_pixels=AcquireCompactPixels(mask,exception);
if (compact_pixels == (unsigned char *) NULL)
return(0);
}
length=WritePSDChannel(psd_info,image_info,image,mask,
RedQuantum,compact_pixels,rows_offset,MagickTrue,exception);
(void) WritePSDSize(psd_info,image,length,size_offset);
count+=length;
compact_pixels=(unsigned char *) RelinquishMagickMemory(
compact_pixels);
}
}
}
return(count);
}
static size_t WritePascalString(Image *image,const char *value,size_t padding)
{
size_t
count,
length;
register ssize_t
i;
/*
Max length is 255.
*/
count=0;
length=(strlen(value) > 255UL ) ? 255UL : strlen(value);
if (length == 0)
count+=WriteBlobByte(image,0);
else
{
count+=WriteBlobByte(image,(unsigned char) length);
count+=WriteBlob(image,length,(const unsigned char *) value);
}
length++;
if ((length % padding) == 0)
return(count);
for (i=0; i < (ssize_t) (padding-(length % padding)); i++)
count+=WriteBlobByte(image,0);
return(count);
}
static void WriteResolutionResourceBlock(Image *image)
{
double
x_resolution,
y_resolution;
unsigned short
units;
if (image->units == PixelsPerCentimeterResolution)
{
x_resolution=2.54*65536.0*image->resolution.x+0.5;
y_resolution=2.54*65536.0*image->resolution.y+0.5;
units=2;
}
else
{
x_resolution=65536.0*image->resolution.x+0.5;
y_resolution=65536.0*image->resolution.y+0.5;
units=1;
}
(void) WriteBlob(image,4,(const unsigned char *) "8BIM");
(void) WriteBlobMSBShort(image,0x03ED);
(void) WriteBlobMSBShort(image,0);
(void) WriteBlobMSBLong(image,16); /* resource size */
(void) WriteBlobMSBLong(image,(unsigned int) (x_resolution+0.5));
(void) WriteBlobMSBShort(image,units); /* horizontal resolution unit */
(void) WriteBlobMSBShort(image,units); /* width unit */
(void) WriteBlobMSBLong(image,(unsigned int) (y_resolution+0.5));
(void) WriteBlobMSBShort(image,units); /* vertical resolution unit */
(void) WriteBlobMSBShort(image,units); /* height unit */
}
static inline size_t WriteChannelSize(const PSDInfo *psd_info,Image *image,
const signed short channel)
{
size_t
count;
count=WriteBlobMSBSignedShort(image,channel);
count+=SetPSDSize(psd_info,image,0);
return(count);
}
static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile)
{
register const unsigned char
*p;
size_t
length;
unsigned char
*datum;
unsigned int
count,
long_sans;
unsigned short
id,
short_sans;
length=GetStringInfoLength(bim_profile);
if (length < 16)
return;
datum=GetStringInfoDatum(bim_profile);
for (p=datum; (p >= datum) && (p < (datum+length-16)); )
{
register unsigned char
*q;
q=(unsigned char *) p;
if (LocaleNCompare((const char *) p,"8BIM",4) != 0)
break;
p=PushLongPixel(MSBEndian,p,&long_sans);
p=PushShortPixel(MSBEndian,p,&id);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushLongPixel(MSBEndian,p,&count);
if (id == 0x0000040f)
{
ssize_t
quantum;
quantum=PSDQuantum(count)+12;
if ((quantum >= 12) && (quantum < (ssize_t) length))
{
if ((q+quantum < (datum+length-16)))
(void) CopyMagickMemory(q,q+quantum,length-quantum-(q-datum));
SetStringInfoLength(bim_profile,length-quantum);
}
break;
}
p+=count;
if ((count & 0x01) != 0)
p++;
}
}
static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile)
{
register const unsigned char
*p;
size_t
length;
unsigned char
*datum;
unsigned int
count,
long_sans;
unsigned short
id,
short_sans;
length=GetStringInfoLength(bim_profile);
if (length < 16)
return;
datum=GetStringInfoDatum(bim_profile);
for (p=datum; (p >= datum) && (p < (datum+length-16)); )
{
register unsigned char
*q;
ssize_t
cnt;
q=(unsigned char *) p;
if (LocaleNCompare((const char *) p,"8BIM",4) != 0)
return;
p=PushLongPixel(MSBEndian,p,&long_sans);
p=PushShortPixel(MSBEndian,p,&id);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushLongPixel(MSBEndian,p,&count);
cnt=PSDQuantum(count);
if (cnt < 0)
return;
if ((id == 0x000003ed) && (cnt < (ssize_t) (length-12)))
{
(void) CopyMagickMemory(q,q+cnt+12,length-(cnt+12)-(q-datum));
SetStringInfoLength(bim_profile,length-(cnt+12));
break;
}
p+=count;
if ((count & 0x01) != 0)
p++;
}
}
static const StringInfo *GetAdditionalInformation(const ImageInfo *image_info,
Image *image,ExceptionInfo *exception)
{
#define PSDKeySize 5
#define PSDAllowedLength 36
char
key[PSDKeySize];
/* Whitelist of keys from: https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/ */
const char
allowed[PSDAllowedLength][PSDKeySize] = {
"blnc", "blwh", "brit", "brst", "clbl", "clrL", "curv", "expA", "FMsk",
"GdFl", "grdm", "hue ", "hue2", "infx", "knko", "lclr", "levl", "lnsr",
"lfx2", "luni", "lrFX", "lspf", "lyid", "lyvr", "mixr", "nvrt", "phfl",
"post", "PtFl", "selc", "shpa", "sn2P", "SoCo", "thrs", "tsly", "vibA"
},
*option;
const StringInfo
*info;
MagickBooleanType
found;
register size_t
i;
size_t
remaining_length,
length;
StringInfo
*profile;
unsigned char
*p;
unsigned int
size;
info=GetImageProfile(image,"psd:additional-info");
if (info == (const StringInfo *) NULL)
return((const StringInfo *) NULL);
option=GetImageOption(image_info,"psd:additional-info");
if (LocaleCompare(option,"all") == 0)
return(info);
if (LocaleCompare(option,"selective") != 0)
{
profile=RemoveImageProfile(image,"psd:additional-info");
return(DestroyStringInfo(profile));
}
length=GetStringInfoLength(info);
p=GetStringInfoDatum(info);
remaining_length=length;
length=0;
while (remaining_length >= 12)
{
/* skip over signature */
p+=4;
key[0]=(*p++);
key[1]=(*p++);
key[2]=(*p++);
key[3]=(*p++);
key[4]='\0';
size=(unsigned int) (*p++) << 24;
size|=(unsigned int) (*p++) << 16;
size|=(unsigned int) (*p++) << 8;
size|=(unsigned int) (*p++);
size=size & 0xffffffff;
remaining_length-=12;
if ((size_t) size > remaining_length)
return((const StringInfo *) NULL);
found=MagickFalse;
for (i=0; i < PSDAllowedLength; i++)
{
if (LocaleNCompare(key,allowed[i],PSDKeySize) != 0)
continue;
found=MagickTrue;
break;
}
remaining_length-=(size_t) size;
if (found == MagickFalse)
{
if (remaining_length > 0)
p=(unsigned char *) CopyMagickMemory(p-12,p+size,remaining_length);
continue;
}
length+=(size_t) size+12;
p+=size;
}
profile=RemoveImageProfile(image,"psd:additional-info");
if (length == 0)
return(DestroyStringInfo(profile));
SetStringInfoLength(profile,(const size_t) length);
SetImageProfile(image,"psd:additional-info",info,exception);
return(profile);
}
static MagickBooleanType WritePSDImage(const ImageInfo *image_info,
Image *image,ExceptionInfo *exception)
{
char
layer_name[MagickPathExtent];
const char
*property;
const StringInfo
*icc_profile,
*info;
Image
*base_image,
*next_image;
MagickBooleanType
status;
MagickOffsetType
*layer_size_offsets,
size_offset;
PSDInfo
psd_info;
register ssize_t
i;
size_t
layer_count,
layer_index,
length,
name_length,
num_channels,
packet_size,
rounded_size,
size;
StringInfo
*bim_profile;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
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);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
packet_size=(size_t) (image->depth > 8 ? 6 : 3);
if (image->alpha_trait != UndefinedPixelTrait)
packet_size+=image->depth > 8 ? 2 : 1;
psd_info.version=1;
if ((LocaleCompare(image_info->magick,"PSB") == 0) ||
(image->columns > 30000) || (image->rows > 30000))
psd_info.version=2;
(void) WriteBlob(image,4,(const unsigned char *) "8BPS");
(void) WriteBlobMSBShort(image,psd_info.version); /* version */
for (i=1; i <= 6; i++)
(void) WriteBlobByte(image, 0); /* 6 bytes of reserved */
if (SetImageGray(image,exception) != MagickFalse)
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL);
else
if ((image_info->type != TrueColorType) && (image_info->type !=
TrueColorAlphaType) && (image->storage_class == PseudoClass))
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL);
else
{
if (image->storage_class == PseudoClass)
(void) SetImageStorageClass(image,DirectClass,exception);
if (image->colorspace != CMYKColorspace)
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL);
else
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL);
}
(void) WriteBlobMSBShort(image,(unsigned short) num_channels);
(void) WriteBlobMSBLong(image,(unsigned int) image->rows);
(void) WriteBlobMSBLong(image,(unsigned int) image->columns);
if (IsImageGray(image) != MagickFalse)
{
MagickBooleanType
monochrome;
/*
Write depth & mode.
*/
monochrome=IsImageMonochrome(image) && (image->depth == 1) ?
MagickTrue : MagickFalse;
(void) WriteBlobMSBShort(image,(unsigned short)
(monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8));
(void) WriteBlobMSBShort(image,(unsigned short)
(monochrome != MagickFalse ? BitmapMode : GrayscaleMode));
}
else
{
(void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class ==
PseudoClass ? 8 : image->depth > 8 ? 16 : 8));
if (((image_info->colorspace != UndefinedColorspace) ||
(image->colorspace != CMYKColorspace)) &&
(image_info->colorspace != CMYKColorspace))
{
(void) TransformImageColorspace(image,sRGBColorspace,exception);
(void) WriteBlobMSBShort(image,(unsigned short)
(image->storage_class == PseudoClass ? IndexedMode : RGBMode));
}
else
{
if (image->colorspace != CMYKColorspace)
(void) TransformImageColorspace(image,CMYKColorspace,exception);
(void) WriteBlobMSBShort(image,CMYKMode);
}
}
if ((IsImageGray(image) != MagickFalse) ||
(image->storage_class == DirectClass) || (image->colors > 256))
(void) WriteBlobMSBLong(image,0);
else
{
/*
Write PSD raster colormap.
*/
(void) WriteBlobMSBLong(image,768);
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].red));
for ( ; i < 256; i++)
(void) WriteBlobByte(image,0);
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(
image->colormap[i].green));
for ( ; i < 256; i++)
(void) WriteBlobByte(image,0);
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].blue));
for ( ; i < 256; i++)
(void) WriteBlobByte(image,0);
}
/*
Image resource block.
*/
length=28; /* 0x03EB */
bim_profile=(StringInfo *) GetImageProfile(image,"8bim");
icc_profile=GetImageProfile(image,"icc");
if (bim_profile != (StringInfo *) NULL)
{
bim_profile=CloneStringInfo(bim_profile);
if (icc_profile != (StringInfo *) NULL)
RemoveICCProfileFromResourceBlock(bim_profile);
RemoveResolutionFromResourceBlock(bim_profile);
length+=PSDQuantum(GetStringInfoLength(bim_profile));
}
if (icc_profile != (const StringInfo *) NULL)
length+=PSDQuantum(GetStringInfoLength(icc_profile))+12;
(void) WriteBlobMSBLong(image,(unsigned int) length);
WriteResolutionResourceBlock(image);
if (bim_profile != (StringInfo *) NULL)
{
(void) WriteBlob(image,GetStringInfoLength(bim_profile),
GetStringInfoDatum(bim_profile));
bim_profile=DestroyStringInfo(bim_profile);
}
if (icc_profile != (StringInfo *) NULL)
{
(void) WriteBlob(image,4,(const unsigned char *) "8BIM");
(void) WriteBlobMSBShort(image,0x0000040F);
(void) WriteBlobMSBShort(image,0);
(void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength(
icc_profile));
(void) WriteBlob(image,GetStringInfoLength(icc_profile),
GetStringInfoDatum(icc_profile));
if ((MagickOffsetType) GetStringInfoLength(icc_profile) !=
PSDQuantum(GetStringInfoLength(icc_profile)))
(void) WriteBlobByte(image,0);
}
base_image=GetNextImageInList(image);
if (base_image == (Image *) NULL)
base_image=image;
size=0;
size_offset=TellBlob(image);
SetPSDSize(&psd_info,image,0);
SetPSDSize(&psd_info,image,0);
layer_count=0;
for (next_image=base_image; next_image != NULL; )
{
layer_count++;
next_image=GetNextImageInList(next_image);
}
if (image->alpha_trait != UndefinedPixelTrait)
size+=WriteBlobMSBShort(image,-(unsigned short) layer_count);
else
size+=WriteBlobMSBShort(image,(unsigned short) layer_count);
layer_size_offsets=(MagickOffsetType *) AcquireQuantumMemory(
(size_t) layer_count,sizeof(MagickOffsetType));
if (layer_size_offsets == (MagickOffsetType *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
layer_index=0;
for (next_image=base_image; next_image != NULL; )
{
Image
*mask;
unsigned char
default_color;
unsigned short
channels,
total_channels;
mask=(Image *) NULL;
property=GetImageArtifact(next_image,"psd:opacity-mask");
default_color=0;
if (property != (const char *) NULL)
{
mask=(Image *) GetImageRegistry(ImageRegistryType,property,exception);
default_color=strlen(property) == 9 ? 255 : 0;
}
size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.y);
size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.x);
size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.y+
next_image->rows));
size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.x+
next_image->columns));
channels=1U;
if ((next_image->storage_class != PseudoClass) &&
(IsImageGray(next_image) == MagickFalse))
channels=next_image->colorspace == CMYKColorspace ? 4U : 3U;
total_channels=channels;
if (next_image->alpha_trait != UndefinedPixelTrait)
total_channels++;
if (mask != (Image *) NULL)
total_channels++;
size+=WriteBlobMSBShort(image,total_channels);
layer_size_offsets[layer_index++]=TellBlob(image);
for (i=0; i < (ssize_t) channels; i++)
size+=WriteChannelSize(&psd_info,image,(signed short) i);
if (next_image->alpha_trait != UndefinedPixelTrait)
size+=WriteChannelSize(&psd_info,image,-1);
if (mask != (Image *) NULL)
size+=WriteChannelSize(&psd_info,image,-2);
size+=WriteBlob(image,4,(const unsigned char *) "8BIM");
size+=WriteBlob(image,4,(const unsigned char *)
CompositeOperatorToPSDBlendMode(next_image->compose));
property=GetImageArtifact(next_image,"psd:layer.opacity");
if (property != (const char *) NULL)
{
Quantum
opacity;
opacity=(Quantum) StringToInteger(property);
size+=WriteBlobByte(image,ScaleQuantumToChar(opacity));
(void) ApplyPSDLayerOpacity(next_image,opacity,MagickTrue,exception);
}
else
size+=WriteBlobByte(image,255);
size+=WriteBlobByte(image,0);
size+=WriteBlobByte(image,next_image->compose==NoCompositeOp ?
1 << 0x02 : 1); /* layer properties - visible, etc. */
size+=WriteBlobByte(image,0);
info=GetAdditionalInformation(image_info,next_image,exception);
property=(const char *) GetImageProperty(next_image,"label",exception);
if (property == (const char *) NULL)
{
(void) FormatLocaleString(layer_name,MagickPathExtent,"L%.20g",
(double) layer_index);
property=layer_name;
}
name_length=strlen(property)+1;
if ((name_length % 4) != 0)
name_length+=(4-(name_length % 4));
if (info != (const StringInfo *) NULL)
name_length+=GetStringInfoLength(info);
name_length+=8;
if (mask != (Image *) NULL)
name_length+=20;
size+=WriteBlobMSBLong(image,(unsigned int) name_length);
if (mask == (Image *) NULL)
size+=WriteBlobMSBLong(image,0);
else
{
if (mask->compose != NoCompositeOp)
(void) ApplyPSDOpacityMask(next_image,mask,ScaleCharToQuantum(
default_color),MagickTrue,exception);
mask->page.y+=image->page.y;
mask->page.x+=image->page.x;
size+=WriteBlobMSBLong(image,20);
size+=WriteBlobMSBSignedLong(image,mask->page.y);
size+=WriteBlobMSBSignedLong(image,mask->page.x);
size+=WriteBlobMSBLong(image,(const unsigned int) mask->rows+
mask->page.y);
size+=WriteBlobMSBLong(image,(const unsigned int) mask->columns+
mask->page.x);
size+=WriteBlobByte(image,default_color);
size+=WriteBlobByte(image,mask->compose == NoCompositeOp ? 2 : 0);
size+=WriteBlobMSBShort(image,0);
}
size+=WriteBlobMSBLong(image,0);
size+=WritePascalString(image,property,4);
if (info != (const StringInfo *) NULL)
size+=WriteBlob(image,GetStringInfoLength(info),
GetStringInfoDatum(info));
next_image=GetNextImageInList(next_image);
}
/*
Now the image data!
*/
next_image=base_image;
layer_index=0;
while (next_image != NULL)
{
length=WritePSDChannels(&psd_info,image_info,image,next_image,
layer_size_offsets[layer_index++],MagickTrue,exception);
if (length == 0)
{
status=MagickFalse;
break;
}
size+=length;
next_image=GetNextImageInList(next_image);
}
(void) WriteBlobMSBLong(image,0); /* user mask data */
/*
Write the total size
*/
size_offset+=WritePSDSize(&psd_info,image,size+
(psd_info.version == 1 ? 8 : 16),size_offset);
if ((size/2) != ((size+1)/2))
rounded_size=size+1;
else
rounded_size=size;
(void) WritePSDSize(&psd_info,image,rounded_size,size_offset);
layer_size_offsets=(MagickOffsetType *) RelinquishMagickMemory(
layer_size_offsets);
/*
Remove the opacity mask from the registry
*/
next_image=base_image;
while (next_image != (Image *) NULL)
{
property=GetImageArtifact(next_image,"psd:opacity-mask");
if (property != (const char *) NULL)
DeleteImageRegistry(property);
next_image=GetNextImageInList(next_image);
}
/*
Write composite image.
*/
if (status != MagickFalse)
{
CompressionType
compression;
compression=image->compression;
if (image->compression == ZipCompression)
image->compression=RLECompression;
if (WritePSDChannels(&psd_info,image_info,image,image,0,MagickFalse,
exception) == 0)
status=MagickFalse;
image->compression=compression;
}
(void) CloseBlob(image);
return(status);
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_3107_0 |
crossvul-cpp_data_bad_4028_0 | /**
* FreeRDP: A Remote Desktop Protocol Implementation
* Cryptographic Abstraction Layer
*
* Copyright 2011-2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* 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 <winpr/crypto.h>
#include <freerdp/log.h>
#include <freerdp/crypto/crypto.h>
#define TAG FREERDP_TAG("crypto")
CryptoCert crypto_cert_read(BYTE* data, UINT32 length)
{
CryptoCert cert = malloc(sizeof(*cert));
if (!cert)
return NULL;
/* this will move the data pointer but we don't care, we don't use it again */
cert->px509 = d2i_X509(NULL, (D2I_X509_CONST BYTE**)&data, length);
return cert;
}
void crypto_cert_free(CryptoCert cert)
{
if (cert == NULL)
return;
X509_free(cert->px509);
free(cert);
}
BOOL crypto_cert_get_public_key(CryptoCert cert, BYTE** PublicKey, DWORD* PublicKeyLength)
{
BYTE* ptr;
int length;
BOOL status = TRUE;
EVP_PKEY* pkey = NULL;
pkey = X509_get_pubkey(cert->px509);
if (!pkey)
{
WLog_ERR(TAG, "X509_get_pubkey() failed");
status = FALSE;
goto exit;
}
length = i2d_PublicKey(pkey, NULL);
if (length < 1)
{
WLog_ERR(TAG, "i2d_PublicKey() failed");
status = FALSE;
goto exit;
}
*PublicKeyLength = (DWORD)length;
*PublicKey = (BYTE*)malloc(length);
ptr = (BYTE*)(*PublicKey);
if (!ptr)
{
status = FALSE;
goto exit;
}
i2d_PublicKey(pkey, &ptr);
exit:
if (pkey)
EVP_PKEY_free(pkey);
return status;
}
static int crypto_rsa_common(const BYTE* input, int length, UINT32 key_length, const BYTE* modulus,
const BYTE* exponent, int exponent_size, BYTE* output)
{
BN_CTX* ctx;
int output_length = -1;
BYTE* input_reverse;
BYTE* modulus_reverse;
BYTE* exponent_reverse;
BIGNUM *mod, *exp, *x, *y;
input_reverse = (BYTE*)malloc(2 * key_length + exponent_size);
if (!input_reverse)
return -1;
modulus_reverse = input_reverse + key_length;
exponent_reverse = modulus_reverse + key_length;
memcpy(modulus_reverse, modulus, key_length);
crypto_reverse(modulus_reverse, key_length);
memcpy(exponent_reverse, exponent, exponent_size);
crypto_reverse(exponent_reverse, exponent_size);
memcpy(input_reverse, input, length);
crypto_reverse(input_reverse, length);
if (!(ctx = BN_CTX_new()))
goto fail_bn_ctx;
if (!(mod = BN_new()))
goto fail_bn_mod;
if (!(exp = BN_new()))
goto fail_bn_exp;
if (!(x = BN_new()))
goto fail_bn_x;
if (!(y = BN_new()))
goto fail_bn_y;
BN_bin2bn(modulus_reverse, key_length, mod);
BN_bin2bn(exponent_reverse, exponent_size, exp);
BN_bin2bn(input_reverse, length, x);
BN_mod_exp(y, x, exp, mod, ctx);
output_length = BN_bn2bin(y, output);
crypto_reverse(output, output_length);
if (output_length < (int)key_length)
memset(output + output_length, 0, key_length - output_length);
BN_free(y);
fail_bn_y:
BN_clear_free(x);
fail_bn_x:
BN_free(exp);
fail_bn_exp:
BN_free(mod);
fail_bn_mod:
BN_CTX_free(ctx);
fail_bn_ctx:
free(input_reverse);
return output_length;
}
static int crypto_rsa_public(const BYTE* input, int length, UINT32 key_length, const BYTE* modulus,
const BYTE* exponent, BYTE* output)
{
return crypto_rsa_common(input, length, key_length, modulus, exponent, EXPONENT_MAX_SIZE,
output);
}
static int crypto_rsa_private(const BYTE* input, int length, UINT32 key_length, const BYTE* modulus,
const BYTE* private_exponent, BYTE* output)
{
return crypto_rsa_common(input, length, key_length, modulus, private_exponent, key_length,
output);
}
int crypto_rsa_public_encrypt(const BYTE* input, int length, UINT32 key_length, const BYTE* modulus,
const BYTE* exponent, BYTE* output)
{
return crypto_rsa_public(input, length, key_length, modulus, exponent, output);
}
int crypto_rsa_public_decrypt(const BYTE* input, int length, UINT32 key_length, const BYTE* modulus,
const BYTE* exponent, BYTE* output)
{
return crypto_rsa_public(input, length, key_length, modulus, exponent, output);
}
int crypto_rsa_private_encrypt(const BYTE* input, int length, UINT32 key_length,
const BYTE* modulus, const BYTE* private_exponent, BYTE* output)
{
return crypto_rsa_private(input, length, key_length, modulus, private_exponent, output);
}
int crypto_rsa_private_decrypt(const BYTE* input, int length, UINT32 key_length,
const BYTE* modulus, const BYTE* private_exponent, BYTE* output)
{
return crypto_rsa_private(input, length, key_length, modulus, private_exponent, output);
}
static int crypto_rsa_decrypt(const BYTE* input, int length, UINT32 key_length, const BYTE* modulus,
const BYTE* private_exponent, BYTE* output)
{
return crypto_rsa_common(input, length, key_length, modulus, private_exponent, key_length,
output);
}
void crypto_reverse(BYTE* data, int length)
{
int i, j;
BYTE temp;
for (i = 0, j = length - 1; i < j; i++, j--)
{
temp = data[i];
data[i] = data[j];
data[j] = temp;
}
}
char* crypto_cert_fingerprint(X509* xcert)
{
return crypto_cert_fingerprint_by_hash(xcert, "sha256");
}
BYTE* crypto_cert_hash(X509* xcert, const char* hash, UINT32* length)
{
UINT32 fp_len = EVP_MAX_MD_SIZE;
BYTE* fp;
const EVP_MD* md = EVP_get_digestbyname(hash);
if (!md)
return NULL;
if (!length)
return NULL;
if (!xcert)
return NULL;
fp = calloc(fp_len, sizeof(BYTE));
if (!fp)
return NULL;
if (X509_digest(xcert, md, fp, &fp_len) != 1)
{
free(fp);
return NULL;
}
*length = fp_len;
return fp;
}
char* crypto_cert_fingerprint_by_hash(X509* xcert, const char* hash)
{
UINT32 fp_len, i;
BYTE* fp;
char* p;
char* fp_buffer;
fp = crypto_cert_hash(xcert, hash, &fp_len);
if (!fp)
return NULL;
fp_buffer = calloc(fp_len * 3 + 1, sizeof(char));
if (!fp_buffer)
goto fail;
p = fp_buffer;
for (i = 0; i < (fp_len - 1); i++)
{
sprintf_s(p, (fp_len - i) * 3, "%02" PRIx8 ":", fp[i]);
p = &fp_buffer[(i + 1) * 3];
}
sprintf_s(p, (fp_len - i) * 3, "%02" PRIx8 "", fp[i]);
fail:
free(fp);
return fp_buffer;
}
static char* crypto_print_name(X509_NAME* name)
{
char* buffer = NULL;
BIO* outBIO = BIO_new(BIO_s_mem());
if (X509_NAME_print_ex(outBIO, name, 0, XN_FLAG_ONELINE) > 0)
{
unsigned long size = BIO_number_written(outBIO);
buffer = calloc(1, size + 1);
if (!buffer)
return NULL;
BIO_read(outBIO, buffer, size);
}
BIO_free_all(outBIO);
return buffer;
}
char* crypto_cert_subject(X509* xcert)
{
return crypto_print_name(X509_get_subject_name(xcert));
}
char* crypto_cert_subject_common_name(X509* xcert, int* length)
{
int index;
BYTE* common_name_raw;
char* common_name;
X509_NAME* subject_name;
X509_NAME_ENTRY* entry;
ASN1_STRING* entry_data;
subject_name = X509_get_subject_name(xcert);
if (subject_name == NULL)
return NULL;
index = X509_NAME_get_index_by_NID(subject_name, NID_commonName, -1);
if (index < 0)
return NULL;
entry = X509_NAME_get_entry(subject_name, index);
if (entry == NULL)
return NULL;
entry_data = X509_NAME_ENTRY_get_data(entry);
if (entry_data == NULL)
return NULL;
*length = ASN1_STRING_to_UTF8(&common_name_raw, entry_data);
if (*length < 0)
return NULL;
common_name = _strdup((char*)common_name_raw);
OPENSSL_free(common_name_raw);
return (char*)common_name;
}
/* GENERAL_NAME type labels */
static const char* general_name_type_labels[] = { "OTHERNAME", "EMAIL ", "DNS ",
"X400 ", "DIRNAME ", "EDIPARTY ",
"URI ", "IPADD ", "RID " };
static const char* general_name_type_label(int general_name_type)
{
if ((0 <= general_name_type) &&
((size_t)general_name_type < ARRAYSIZE(general_name_type_labels)))
{
return general_name_type_labels[general_name_type];
}
else
{
static char buffer[80];
sprintf(buffer, "Unknown general name type (%d)", general_name_type);
return buffer;
}
}
/*
map_subject_alt_name(x509, general_name_type, mapper, data)
Call the function mapper with subjectAltNames found in the x509
certificate and data. if generate_name_type is GEN_ALL, the the
mapper is called for all the names, else it's called only for names
of the given type.
We implement two extractors:
- a string extractor that can be used to get the subjectAltNames of
the following types: GEN_URI, GEN_DNS, GEN_EMAIL
- a ASN1_OBJECT filter/extractor that can be used to get the
subjectAltNames of OTHERNAME type.
Note: usually, it's a string, but some type of otherNames can be
associated with different classes of objects. eg. a KPN may be a
sequence of realm and principal name, instead of a single string
object.
Not implemented yet: extractors for the types: GEN_X400, GEN_DIRNAME,
GEN_EDIPARTY, GEN_RID, GEN_IPADD (the later can contain nul-bytes).
mapper(name, data, index, count)
The mapper is passed:
- the GENERAL_NAME selected,
- the data,
- the index of the general name in the subjectAltNames,
- the total number of names in the subjectAltNames.
The last parameter let's the mapper allocate arrays to collect objects.
Note: if names are filtered, not all the indices from 0 to count-1 are
passed to mapper, only the indices selected.
When the mapper returns 0, map_subject_alt_name stops the iteration immediately.
*/
#define GEN_ALL (-1)
typedef int (*general_name_mapper_pr)(GENERAL_NAME* name, void* data, int index, int count);
static void map_subject_alt_name(X509* x509, int general_name_type, general_name_mapper_pr mapper,
void* data)
{
int i;
int num;
STACK_OF(GENERAL_NAME) * gens;
gens = X509_get_ext_d2i(x509, NID_subject_alt_name, NULL, NULL);
if (!gens)
{
return;
}
num = sk_GENERAL_NAME_num(gens);
for (i = 0; (i < num); i++)
{
GENERAL_NAME* name = sk_GENERAL_NAME_value(gens, i);
if (name)
{
if ((general_name_type == GEN_ALL) || (general_name_type == name->type))
{
if (!mapper(name, data, i, num))
{
break;
}
}
}
}
sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free);
}
/*
extract_string -- string extractor
- the strings array is allocated lazily, when we first have to store a
string.
- allocated contains the size of the strings array, or -1 if
allocation failed.
- count contains the actual count of strings in the strings array.
- maximum limits the number of strings we can store in the strings
array: beyond, the extractor returns 0 to short-cut the search.
extract_string stores in the string list OPENSSL strings,
that must be freed with OPENSSL_free.
*/
typedef struct string_list
{
char** strings;
int allocated;
int count;
int maximum;
} string_list;
static void string_list_initialize(string_list* list)
{
list->strings = 0;
list->allocated = 0;
list->count = 0;
list->maximum = INT_MAX;
}
static void string_list_allocate(string_list* list, int allocate_count)
{
if (!list->strings && list->allocated == 0)
{
list->strings = calloc((size_t)allocate_count, sizeof(char*));
list->allocated = list->strings ? allocate_count : -1;
list->count = 0;
}
}
static void string_list_free(string_list* list)
{
/* Note: we don't free the contents of the strings array: this */
/* is handled by the caller, either by returning this */
/* content, or freeing it itself. */
free(list->strings);
}
static int extract_string(GENERAL_NAME* name, void* data, int index, int count)
{
string_list* list = data;
unsigned char* cstring = 0;
ASN1_STRING* str;
switch (name->type)
{
case GEN_URI:
str = name->d.uniformResourceIdentifier;
break;
case GEN_DNS:
str = name->d.dNSName;
break;
case GEN_EMAIL:
str = name->d.rfc822Name;
break;
default:
return 1;
}
if ((ASN1_STRING_to_UTF8(&cstring, str)) < 0)
{
WLog_ERR(TAG, "ASN1_STRING_to_UTF8() failed for %s: %s",
general_name_type_label(name->type), ERR_error_string(ERR_get_error(), NULL));
return 1;
}
string_list_allocate(list, count);
if (list->allocated <= 0)
{
OPENSSL_free(cstring);
return 0;
}
list->strings[list->count] = (char*)cstring;
list->count++;
if (list->count >= list->maximum)
{
return 0;
}
return 1;
}
/*
extract_othername_object -- object extractor.
- the objects array is allocated lazily, when we first have to store a
string.
- allocated contains the size of the objects array, or -1 if
allocation failed.
- count contains the actual count of objects in the objects array.
- maximum limits the number of objects we can store in the objects
array: beyond, the extractor returns 0 to short-cut the search.
extract_othername_objects stores in the objects array ASN1_TYPE *
pointers directly obtained from the GENERAL_NAME.
*/
typedef struct object_list
{
ASN1_OBJECT* type_id;
char** strings;
int allocated;
int count;
int maximum;
} object_list;
static void object_list_initialize(object_list* list)
{
list->type_id = 0;
list->strings = 0;
list->allocated = 0;
list->count = 0;
list->maximum = INT_MAX;
}
static void object_list_allocate(object_list* list, int allocate_count)
{
if (!list->strings && list->allocated == 0)
{
list->strings = calloc(allocate_count, sizeof(list->strings[0]));
list->allocated = list->strings ? allocate_count : -1;
list->count = 0;
}
}
static char* object_string(ASN1_TYPE* object)
{
char* result;
unsigned char* utf8String;
int length;
/* TODO: check that object.type is a string type. */
length = ASN1_STRING_to_UTF8(&utf8String, object->value.asn1_string);
if (length < 0)
{
return 0;
}
result = (char*)_strdup((char*)utf8String);
OPENSSL_free(utf8String);
return result;
}
static void object_list_free(object_list* list)
{
free(list->strings);
}
static int extract_othername_object_as_string(GENERAL_NAME* name, void* data, int index, int count)
{
object_list* list = data;
if (name->type != GEN_OTHERNAME)
{
return 1;
}
if (0 != OBJ_cmp(name->d.otherName->type_id, list->type_id))
{
return 1;
}
object_list_allocate(list, count);
if (list->allocated <= 0)
{
return 0;
}
list->strings[list->count] = object_string(name->d.otherName->value);
if (list->strings[list->count])
{
list->count++;
}
if (list->count >= list->maximum)
{
return 0;
}
return 1;
}
/*
crypto_cert_get_email returns a dynamically allocated copy of the
first email found in the subjectAltNames (use free to free it).
*/
char* crypto_cert_get_email(X509* x509)
{
char* result = 0;
string_list list;
string_list_initialize(&list);
list.maximum = 1;
map_subject_alt_name(x509, GEN_EMAIL, extract_string, &list);
if (list.count == 0)
{
string_list_free(&list);
return 0;
}
result = _strdup(list.strings[0]);
OPENSSL_free(list.strings[0]);
string_list_free(&list);
return result;
}
/*
crypto_cert_get_upn returns a dynamically allocated copy of the
first UPN otherNames in the subjectAltNames (use free to free it).
Note: if this first UPN otherName is not a string, then 0 is returned,
instead of searching for another UPN that would be a string.
*/
char* crypto_cert_get_upn(X509* x509)
{
char* result = 0;
object_list list;
object_list_initialize(&list);
list.type_id = OBJ_nid2obj(NID_ms_upn);
list.maximum = 1;
map_subject_alt_name(x509, GEN_OTHERNAME, extract_othername_object_as_string, &list);
if (list.count == 0)
{
object_list_free(&list);
return 0;
}
result = list.strings[0];
object_list_free(&list);
return result;
}
/* Deprecated name.*/
void crypto_cert_subject_alt_name_free(int count, int* lengths, char** alt_names)
{
crypto_cert_dns_names_free(count, lengths, alt_names);
}
void crypto_cert_dns_names_free(int count, int* lengths, char** dns_names)
{
free(lengths);
if (dns_names)
{
int i;
for (i = 0; i < count; i++)
{
if (dns_names[i])
{
OPENSSL_free(dns_names[i]);
}
}
free(dns_names);
}
}
/* Deprecated name.*/
char** crypto_cert_subject_alt_name(X509* xcert, int* count, int** lengths)
{
return crypto_cert_get_dns_names(xcert, count, lengths);
}
char** crypto_cert_get_dns_names(X509* x509, int* count, int** lengths)
{
int i;
char** result = 0;
string_list list;
string_list_initialize(&list);
map_subject_alt_name(x509, GEN_DNS, extract_string, &list);
(*count) = list.count;
if (list.count == 0)
{
string_list_free(&list);
return NULL;
}
/* lengths are not useful, since we converted the
strings to utf-8, there cannot be nul-bytes in them. */
result = calloc(list.count, sizeof(*result));
(*lengths) = calloc(list.count, sizeof(**lengths));
if (!result || !(*lengths))
{
string_list_free(&list);
free(result);
free(*lengths);
(*lengths) = 0;
(*count) = 0;
return NULL;
}
for (i = 0; i < list.count; i++)
{
result[i] = list.strings[i];
(*lengths)[i] = strlen(result[i]);
}
string_list_free(&list);
return result;
}
char* crypto_cert_issuer(X509* xcert)
{
return crypto_print_name(X509_get_issuer_name(xcert));
}
static int verify_cb(int ok, X509_STORE_CTX* csc)
{
if (ok != 1)
{
int err = X509_STORE_CTX_get_error(csc);
int derr = X509_STORE_CTX_get_error_depth(csc);
X509* where = X509_STORE_CTX_get_current_cert(csc);
const char* what = X509_verify_cert_error_string(err);
char* name = crypto_cert_subject(where);
WLog_WARN(TAG, "Certificate verification failure '%s (%d)' at stack position %d", what, err,
derr);
WLog_WARN(TAG, "%s", name);
free(name);
}
return ok;
}
BOOL x509_verify_certificate(CryptoCert cert, const char* certificate_store_path)
{
size_t i;
const int purposes[3] = { X509_PURPOSE_SSL_SERVER, X509_PURPOSE_SSL_CLIENT, X509_PURPOSE_ANY };
X509_STORE_CTX* csc;
BOOL status = FALSE;
X509_STORE* cert_ctx = NULL;
X509_LOOKUP* lookup = NULL;
cert_ctx = X509_STORE_new();
if (cert_ctx == NULL)
goto end;
#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
OpenSSL_add_all_algorithms();
#else
OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS | OPENSSL_INIT_ADD_ALL_DIGESTS |
OPENSSL_INIT_LOAD_CONFIG,
NULL);
#endif
lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_file());
if (lookup == NULL)
goto end;
lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_hash_dir());
if (lookup == NULL)
goto end;
X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
if (certificate_store_path != NULL)
{
X509_LOOKUP_add_dir(lookup, certificate_store_path, X509_FILETYPE_PEM);
}
X509_STORE_set_flags(cert_ctx, 0);
for (i = 0; i < ARRAYSIZE(purposes); i++)
{
int rc = -1;
int purpose = purposes[i];
csc = X509_STORE_CTX_new();
if (csc == NULL)
goto skip;
if (!X509_STORE_CTX_init(csc, cert_ctx, cert->px509, cert->px509chain))
goto skip;
X509_STORE_CTX_set_purpose(csc, purpose);
X509_STORE_CTX_set_verify_cb(csc, verify_cb);
rc = X509_verify_cert(csc);
skip:
X509_STORE_CTX_free(csc);
if (rc == 1)
{
status = TRUE;
break;
}
}
X509_STORE_free(cert_ctx);
end:
return status;
}
rdpCertificateData* crypto_get_certificate_data(X509* xcert, const char* hostname, UINT16 port)
{
char* issuer;
char* subject;
char* fp;
rdpCertificateData* certdata;
fp = crypto_cert_fingerprint(xcert);
if (!fp)
return NULL;
issuer = crypto_cert_issuer(xcert);
subject = crypto_cert_subject(xcert);
certdata = certificate_data_new(hostname, port, issuer, subject, fp);
free(subject);
free(issuer);
free(fp);
return certdata;
}
void crypto_cert_print_info(X509* xcert)
{
char* fp;
char* issuer;
char* subject;
subject = crypto_cert_subject(xcert);
issuer = crypto_cert_issuer(xcert);
fp = crypto_cert_fingerprint(xcert);
if (!fp)
{
WLog_ERR(TAG, "error computing fingerprint");
goto out_free_issuer;
}
WLog_INFO(TAG, "Certificate details:");
WLog_INFO(TAG, "\tSubject: %s", subject);
WLog_INFO(TAG, "\tIssuer: %s", issuer);
WLog_INFO(TAG, "\tThumbprint: %s", fp);
WLog_INFO(TAG,
"The above X.509 certificate could not be verified, possibly because you do not have "
"the CA certificate in your certificate store, or the certificate has expired. "
"Please look at the OpenSSL documentation on how to add a private CA to the store.");
free(fp);
out_free_issuer:
free(issuer);
free(subject);
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_4028_0 |
crossvul-cpp_data_good_978_0 | /*
3APA3A simpliest proxy server
(c) 2002-2008 by ZARAZA <3APA3A@security.nnov.ru>
please read License Agreement
*/
#include "proxy.h"
#define RETURN(xxx) { param->res = xxx; goto CLEANRET; }
#define LINESIZE 65536
extern FILE *writable;
FILE * confopen();
extern void decodeurl(unsigned char *s, int filter);
struct printparam {
char buf[1024];
int inbuf;
struct clientparam *cp;
};
static void stdpr(struct printparam* pp, char *buf, int inbuf){
if((pp->inbuf + inbuf > 1024) || !buf) {
socksend(pp->cp->clisock, (unsigned char *)pp->buf, pp->inbuf, conf.timeouts[STRING_S]);
pp->inbuf = 0;
if(!buf) return;
}
if(inbuf >= 1000){
socksend(pp->cp->clisock, (unsigned char *)buf, inbuf, conf.timeouts[STRING_S]);
}
else {
memcpy(pp->buf + pp->inbuf, buf, inbuf);
pp->inbuf += inbuf;
}
}
static void stdcbf(void *cb, char *buf, int inbuf){
int delay = 0;
int i;
for(i = 0; i < inbuf; i++){
switch(buf[i]){
case '&':
if(delay){
stdpr((struct printparam*)cb, buf+i-delay, delay);
delay = 0;
}
stdpr((struct printparam*)cb, "&", 5);
break;
case '<':
if(delay){
stdpr((struct printparam*)cb, buf+i-delay, delay);
delay = 0;
}
stdpr((struct printparam*)cb, "<", 4);
break;
case '>':
if(delay){
stdpr((struct printparam*)cb, buf+i-delay, delay);
delay = 0;
}
stdpr((struct printparam*)cb, ">", 4);
break;
default:
delay++;
break;
}
}
if(delay){
stdpr((struct printparam*)cb, buf+i-delay, delay);
}
}
/*
static char * templateprint(struct printparam* pp, int *level, struct dictionary *dict, char * template){
char *s, *s2;
for(; template && *template; ){
if(!( s = strchr(template, '<'))){
stdpr(pp, template, (int)strlen(template));
return template + strlen(template);
}
if(s[1] != '%' || s[2] == '%'){
stdpr(pp, template, (int)(s - template) + 1);
template = s + 1;
continue;
}
if(s[2] == '/' && (s2 = strchr(s + 2, '>')) && *(s2 - 1) == '%'){
if(--*level < 0) return NULL;
return s2 + 1;
}
}
return template;
}
*/
static void printstr(struct printparam* pp, char* str){
stdpr(pp, str, str?(int)strlen(str):0);
}
static void printval(void *value, int type, int level, struct printparam* pp){
struct node pn, cn;
struct property *p;
int i;
pn.iteration = NULL;
pn.parent = NULL;
pn.type = type;
pn.value = value;
printstr(pp, "<item>");
for(p = datatypes[type].properties; p; ) {
cn.iteration = NULL;
cn.parent = &pn;
cn.type = p->type;
cn.value = (*p->e_f)(&pn);
if(cn.value){
for(i = 0; i < level; i++) printstr(pp, "\t");
if(strcmp(p->name, "next")){
printstr(pp, "<parameter>");
printstr(pp, "<name>");
printstr(pp, p->name);
printstr(pp, "</name>");
printstr(pp, "<type>");
printstr(pp, datatypes[p->type].type);
printstr(pp, "</type>");
printstr(pp, "<description>");
printstr(pp, p->description);
printstr(pp, "</description>");
}
if(datatypes[p->type].p_f){
printstr(pp, "<value><![CDATA[");
(*datatypes[p->type].p_f)(&cn, stdcbf, pp);
printstr(pp, "]]></value>\n");
printstr(pp, "</parameter>");
}
else {
if(!strcmp(p->name, "next")){
/* printstr(pp, "<!-- -------------------- -->\n"); */
printstr(pp, "</item>\n<item>");
p = datatypes[type].properties;
pn.value = value = cn.value;
continue;
}
else {
printstr(pp, "\n");
printval(cn.value, cn.type, level+1, pp);
printstr(pp, "</parameter>");
}
}
}
p=p->next;
}
printstr(pp, "</item>");
}
char * admin_stringtable[]={
"HTTP/1.0 401 Authentication Required\r\n"
"WWW-Authenticate: Basic realm=\"proxy\"\r\n"
"Connection: close\r\n"
"Content-type: text/html; charset=us-ascii\r\n"
"\r\n"
"<html><head><title>401 Authentication Required</title></head>\r\n"
"<body><h2>401 Authentication Required</h2><h3>Access to requested resource disallowed by administrator or you need valid username/password to use this resource</h3></body></html>\r\n",
"HTTP/1.0 200 OK\r\n"
"Connection: close\r\n"
"Expires: Thu, 01 Dec 1994 16:00:00 GMT\r\n"
"Cache-Control: no-cache\r\n"
"Content-type: text/html\r\n"
"\r\n"
"<http><head><title>%s configuration page</title></head>\r\n"
"<table width=\'100%%\' border=\'0\'>\r\n"
"<tr><td width=\'150\' valign=\'top\'>\r\n"
"<h2> "
" </h2>\r\n"
"<A HREF=\'/C'>Counters</A><br>\r\n"
"<A HREF=\'/R'>Reload</A><br>\r\n"
"<A HREF=\'/S'>Running Services</A><br>\r\n"
"<A HREF=\'/F'>Config</A>\r\n"
"</td><td>"
"<h2>%s %s configuration</h2>",
"HTTP/1.0 200 OK\r\n"
"Connection: close\r\n"
"Cache-Control: no-cache\r\n"
"Content-type: text/xml\r\n"
"\r\n"
"<?xml version=\"1.0\"?>\r\n"
"<?xml-stylesheet href=\"/SX\" type=\"text/css\"?>\r\n"
"<services>\r\n"
"<description>Services currently running and connected clients</description>\r\n",
"</services>\r\n",
"HTTP/1.0 200 OK\r\n"
"Connection: close\r\n"
"Cache-Control: no-cache\r\n"
"Content-type: text/css\r\n"
"\r\n"
"services {\r\n"
" display: block;\r\n"
" margin: 10px auto 10px auto;\r\n"
" width: 80%;\r\n"
" background: black;\r\n"
" font-family: sans-serif;\r\n"
" font-size: small;\r\n"
" color: silver;\r\n"
" }\r\n"
"item {\r\n"
" display: block;\r\n"
" margin-bottom: 10px;\r\n"
" border: 2px solid #CCC;\r\n"
" padding: 10px;\r\n"
" spacing: 2px;\r\n"
" }\r\n"
"parameter {\r\n"
" display: block;\r\n"
" padding: 2px;\r\n"
" margin-top: 10px;\r\n"
" border: 1px solid grey;\r\n"
" background: #EEE;\r\n"
" color: black;\r\n"
" }\r\n"
"name {\r\n"
" display: inline;\r\n"
" float: left;\r\n"
" margin-right: 5px;\r\n"
" font-weight: bold;\r\n"
" }\r\n"
"type {\r\n"
" display: inline;\r\n"
" font-size: x-small;\r\n"
" margin-right: 5px;\r\n"
" color: #666;\r\n"
" white-space: nowrap;\r\n"
" font-style: italic;\r\n"
" }\r\n"
"description {\r\n"
" display: inline;\r\n"
" margin-right: 5px;\r\n"
" white-space: nowrap;\r\n"
" }\r\n"
"value {\r\n"
" display: block;\r\n"
" margin-right: 5px;\r\n"
" }\r\n",
"<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />\r\n"
"<pre><font size=\'-2\'><b>"
COPYRIGHT
"</b></font>\r\n"
"</td></tr></table></body></html>",
"<h3>Counters</h3>\r\n"
"<table border = \'1\'>\r\n"
"<tr align=\'center\'><td>Description</td><td>Active</td>"
"<td>Users</td><td>Source Address</td><td>Destination Address</td>"
"<td>Port</td>"
"<td>Limit</td><td>Units</td><td>Value</td>"
"<td>Reset</td><td>Updated</td><td>Num</td></tr>\r\n",
"</table>\r\n",
NULL
};
#define authreq admin_stringtable[0]
#define ok admin_stringtable[1]
#define xml admin_stringtable[2]
#define postxml admin_stringtable[3]
#define style admin_stringtable[4]
#define tail admin_stringtable[5]
#define counters admin_stringtable[6]
#define counterstail admin_stringtable[7]
static int printportlist(char *buf, int bufsize, struct portlist* pl, char * delim){
int printed = 0;
for(; pl; pl = pl->next){
if(printed > (bufsize - 64)) break;
if(pl->startport != pl->endport)
printed += sprintf(buf+printed, "%hu-%hu%s", pl->startport, pl->endport, pl->next?delim:"");
else {
/*
struct servent *se=NULL;
if(pl->startport)se = getservbyport((int)ntohs(pl->startport), NULL);
printed += sprintf(buf+printed, "%hu(%s)%s", pl->startport, se?se->s_name:"unknown", pl->next?delim:"");
*/
printed += sprintf(buf+printed, "%hu%s", pl->startport, pl->next?delim:"");
}
if(printed > (bufsize - 64)) {
printed += sprintf(buf+printed, "...");
break;
}
}
return printed;
}
static int printuserlist(char *buf, int bufsize, struct userlist* ul, char * delim){
int printed = 0;
for(; ul; ul = ul->next){
if(printed > (bufsize - 64)) break;
printed += sprintf(buf+printed, "%s%s", ul->user, ul->next?delim:"");
if(printed > (bufsize - 64)) {
printed += sprintf(buf+printed, "...");
break;
}
}
return printed;
}
int printiple(char *buf, struct iplist* ipl);
static int printiplist(char *buf, int bufsize, struct iplist* ipl, char * delim){
int printed = 0;
for(; ipl; ipl = ipl->next){
if(printed > (bufsize - 128)) break;
printed += printiple(buf+printed, ipl);
if(printed > (bufsize - 128)) {
printed += sprintf(buf+printed, "...");
break;
}
}
return printed;
}
void * adminchild(struct clientparam* param) {
int i, res;
char * buf;
char username[256];
char *sb;
char *req = NULL;
struct printparam pp;
unsigned contentlen = 0;
int isform = 0;
pp.inbuf = 0;
pp.cp = param;
buf = myalloc(LINESIZE);
if(!buf) {RETURN(555);}
i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, LINESIZE - 1, '\n', conf.timeouts[STRING_S]);
if(i<5 || ((buf[0]!='G' || buf[1]!='E' || buf[2]!='T' || buf[3]!=' ' || buf[4]!='/') &&
(buf[0]!='P' || buf[1]!='O' || buf[2]!='S' || buf[3]!='T' || buf[4]!=' ' || buf[5]!='/')))
{
RETURN(701);
}
buf[i] = 0;
sb = strchr(buf+5, ' ');
if(!sb){
RETURN(702);
}
*sb = 0;
req = mystrdup(buf + ((*buf == 'P')? 6 : 5));
while((i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, LINESIZE - 1, '\n', conf.timeouts[STRING_S])) > 2){
buf[i] = 0;
if(i > 19 && (!strncasecmp(buf, "authorization", 13))){
sb = strchr(buf, ':');
if(!sb)continue;
++sb;
while(isspace(*sb))sb++;
if(!*sb || strncasecmp(sb, "basic", 5)){
continue;
}
sb+=5;
while(isspace(*sb))sb++;
i = de64((unsigned char *)sb, (unsigned char *)username, 255);
if(i<=0)continue;
username[i] = 0;
sb = strchr((char *)username, ':');
if(sb){
*sb = 0;
if(param->password)myfree(param->password);
param->password = (unsigned char *)mystrdup(sb+1);
}
if(param->username) myfree(param->username);
param->username = (unsigned char *)mystrdup(username);
continue;
}
else if(i > 15 && (!strncasecmp(buf, "content-length:", 15))){
sb = buf + 15;
while(isspace(*sb))sb++;
sscanf(sb, "%u", &contentlen);
if(contentlen > LINESIZE*1024) contentlen = 0;
}
else if(i > 13 && (!strncasecmp(buf, "content-type:", 13))){
sb = buf + 13;
while(isspace(*sb))sb++;
if(!strncasecmp(sb, "x-www-form-urlencoded", 21)) isform = 1;
}
}
param->operation = ADMIN;
if(isform && contentlen) {
printstr(&pp, "HTTP/1.0 100 Continue\r\n\r\n");
stdpr(&pp, NULL, 0);
}
res = (*param->srv->authfunc)(param);
if(res && res != 10) {
printstr(&pp, authreq);
RETURN(res);
}
if(param->srv->singlepacket || param->redirected){
if(*req == 'C') req[1] = 0;
else *req = 0;
}
sprintf(buf, ok, conf.stringtable?(char *)conf.stringtable[2]:"3proxy", conf.stringtable?(char *)conf.stringtable[2]:"3[APA3A] tiny proxy", conf.stringtable?(char *)conf.stringtable[3]:"");
if(*req != 'S') printstr(&pp, buf);
switch(*req){
case 'C':
printstr(&pp, counters);
{
struct trafcount *cp;
int num = 0;
for(cp = conf.trafcounter; cp; cp = cp->next, num++){
int inbuf = 0;
if(cp->ace && (param->srv->singlepacket || param->redirected)){
if(!ACLmatches(cp->ace, param))continue;
}
if(req[1] == 'S' && atoi(req+2) == num) cp->disabled=0;
if(req[1] == 'D' && atoi(req+2) == num) cp->disabled=1;
inbuf += sprintf(buf, "<tr>"
"<td>%s</td><td><A HREF=\'/C%c%d\'>%s</A></td><td>",
(cp->comment)?cp->comment:" ",
(cp->disabled)?'S':'D',
num,
(cp->disabled)?"NO":"YES"
);
if(!cp->ace || !cp->ace->users){
inbuf += sprintf(buf+inbuf, "<center>ANY</center>");
}
else {
inbuf += printuserlist(buf+inbuf, LINESIZE-800, cp->ace->users, ",<br />\r\n");
}
inbuf += sprintf(buf+inbuf, "</td><td>");
if(!cp->ace || !cp->ace->src){
inbuf += sprintf(buf+inbuf, "<center>ANY</center>");
}
else {
inbuf += printiplist(buf+inbuf, LINESIZE-512, cp->ace->src, ",<br />\r\n");
}
inbuf += sprintf(buf+inbuf, "</td><td>");
if(!cp->ace || !cp->ace->dst){
inbuf += sprintf(buf+inbuf, "<center>ANY</center>");
}
else {
inbuf += printiplist(buf+inbuf, LINESIZE-512, cp->ace->dst, ",<br />\r\n");
}
inbuf += sprintf(buf+inbuf, "</td><td>");
if(!cp->ace || !cp->ace->ports){
inbuf += sprintf(buf+inbuf, "<center>ANY</center>");
}
else {
inbuf += printportlist(buf+inbuf, LINESIZE-128, cp->ace->ports, ",<br />\r\n");
}
if(cp->type == NONE) {
inbuf += sprintf(buf+inbuf,
"</td><td colspan=\'6\' align=\'center\'>exclude from limitation</td></tr>\r\n"
);
}
else {
inbuf += sprintf(buf+inbuf,
"</td><td>%"PRINTF_INT64_MODIFIER"u</td>"
"<td>MB%s</td>"
"<td>%"PRINTF_INT64_MODIFIER"u</td>"
"<td>%s</td>",
cp->traflim64 / (1024 * 1024),
rotations[cp->type],
cp->traf64,
cp->cleared?ctime(&cp->cleared):"never"
);
inbuf += sprintf(buf + inbuf,
"<td>%s</td>"
"<td>%i</td>"
"</tr>\r\n",
cp->updated?ctime(&cp->updated):"never",
cp->number
);
}
printstr(&pp, buf);
}
}
printstr(&pp, counterstail);
break;
case 'R':
conf.needreload = 1;
printstr(&pp, "<h3>Reload scheduled</h3>");
break;
case 'S':
{
if(req[1] == 'X'){
printstr(&pp, style);
break;
}
printstr(&pp, xml);
printval(conf.services, TYPE_SERVER, 0, &pp);
printstr(&pp, postxml);
}
break;
case 'F':
{
FILE *fp;
char buf[256];
fp = confopen();
if(!fp){
printstr(&pp, "<h3><font color=\"red\">Failed to open config file</font></h3>");
break;
}
printstr(&pp, "<h3>Please be careful editing config file remotely</h3>");
printstr(&pp, "<form method=\"POST\" action=\"/U\" enctype=\"application/x-www-form-urlencoded\"><textarea cols=\"80\" rows=\"30\" name=\"conffile\">");
while(fgets(buf, 256, fp)){
printstr(&pp, buf);
}
if(!writable) fclose(fp);
printstr(&pp, "</textarea><br><input type=\"Submit\"></form>");
break;
}
case 'U':
{
unsigned l=0;
int error = 0;
if(!writable || !contentlen || fseek(writable, 0, 0)){
error = 1;
}
while(l < contentlen && (i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, (contentlen - l) > LINESIZE - 1?LINESIZE - 1:contentlen - l, '+', conf.timeouts[STRING_S])) > 0){
if(i > (contentlen - l)) i = (contentlen - l);
if(!l){
if(i<9 || strncasecmp(buf, "conffile=", 9)) error = 1;
}
if(!error){
buf[i] = 0;
decodeurl((unsigned char *)buf, 1);
fprintf(writable, "%s", l? buf : buf + 9);
}
l += i;
}
if(writable && !error){
fflush(writable);
#ifndef _WINCE
ftruncate(fileno(writable), ftell(writable));
#endif
}
printstr(&pp, error? "<h3><font color=\"red\">Config file is not writable</font></h3>Make sure you have \"writable\" command in configuration file":
"<h3>Configuration updated</h3>");
}
break;
default:
printstr(&pp, (char *)conf.stringtable[WEBBANNERS]);
break;
}
if(*req != 'S') printstr(&pp, tail);
CLEANRET:
printstr(&pp, NULL);
if(buf) myfree(buf);
(*param->srv->logfunc)(param, (unsigned char *)req);
if(req)myfree(req);
freeparam(param);
return (NULL);
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_978_0 |
crossvul-cpp_data_good_443_0 | /*
* 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) {
if (firstItem == URI_TRUE) {
ampersandLen = 1;
firstItem = URI_FALSE;
}
(*charsRequired) += ampersandLen + keyRequiredChars + ((value == NULL)
? 0
: 1 + valueRequiredChars);
} else {
URI_CHAR * afterKey;
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++;
}
afterKey = URI_FUNC(EscapeEx)(key, key + keyLen,
write, spaceToPlus, normalizeBreaks);
write += (afterKey - write);
if (value != NULL) {
URI_CHAR * afterValue;
if ((write - dest) + 1 + valueRequiredChars > maxChars) {
return URI_ERROR_OUTPUT_TOO_LARGE;
}
/* Copy value */
write[0] = _UT('=');
write++;
afterValue = URI_FUNC(EscapeEx)(value, value + valueLen,
write, spaceToPlus, normalizeBreaks);
write += (afterValue - write);
}
}
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-787/c/good_443_0 |
crossvul-cpp_data_good_2758_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) 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"
#include "opj_common.h"
/** @defgroup T2 T2 - Implementation of a tier-2 coding */
/*@{*/
/** @name Local static functions */
/*@{*/
static void opj_t2_putcommacode(opj_bio_t *bio, OPJ_INT32 n);
static OPJ_UINT32 opj_t2_getcommacode(opj_bio_t *bio);
/**
Variable length code for signalling delta Zil (truncation point)
@param bio Bit Input/Output component
@param n delta Zil
*/
static void opj_t2_putnumpasses(opj_bio_t *bio, OPJ_UINT32 n);
static OPJ_UINT32 opj_t2_getnumpasses(opj_bio_t *bio);
/**
Encode a packet of a tile to a destination buffer
@param tileno Number of the tile encoded
@param tile Tile for which to write the packets
@param tcp Tile coding parameters
@param pi Packet identity
@param dest Destination buffer
@param p_data_written FIXME DOC
@param len Length of the destination buffer
@param cstr_info Codestream information structure
@param p_t2_mode If == THRESH_CALC In Threshold calculation ,If == FINAL_PASS Final pass
@param p_manager the user event manager
@return
*/
static OPJ_BOOL opj_t2_encode_packet(OPJ_UINT32 tileno,
opj_tcd_tile_t *tile,
opj_tcp_t *tcp,
opj_pi_iterator_t *pi,
OPJ_BYTE *dest,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 len,
opj_codestream_info_t *cstr_info,
J2K_T2_MODE p_t2_mode,
opj_event_mgr_t *p_manager);
/**
Decode a packet of a tile from a source buffer
@param t2 T2 handle
@param tile Tile for which to write the packets
@param tcp Tile coding parameters
@param pi Packet identity
@param src Source buffer
@param data_read FIXME DOC
@param max_length FIXME DOC
@param pack_info Packet information
@param p_manager the user event manager
@return FIXME DOC
*/
static OPJ_BOOL opj_t2_decode_packet(opj_t2_t* t2,
opj_tcd_tile_t *tile,
opj_tcp_t *tcp,
opj_pi_iterator_t *pi,
OPJ_BYTE *src,
OPJ_UINT32 * data_read,
OPJ_UINT32 max_length,
opj_packet_info_t *pack_info,
opj_event_mgr_t *p_manager);
static OPJ_BOOL opj_t2_skip_packet(opj_t2_t* p_t2,
opj_tcd_tile_t *p_tile,
opj_tcp_t *p_tcp,
opj_pi_iterator_t *p_pi,
OPJ_BYTE *p_src,
OPJ_UINT32 * p_data_read,
OPJ_UINT32 p_max_length,
opj_packet_info_t *p_pack_info,
opj_event_mgr_t *p_manager);
static OPJ_BOOL opj_t2_read_packet_header(opj_t2_t* p_t2,
opj_tcd_tile_t *p_tile,
opj_tcp_t *p_tcp,
opj_pi_iterator_t *p_pi,
OPJ_BOOL * p_is_data_present,
OPJ_BYTE *p_src_data,
OPJ_UINT32 * p_data_read,
OPJ_UINT32 p_max_length,
opj_packet_info_t *p_pack_info,
opj_event_mgr_t *p_manager);
static OPJ_BOOL opj_t2_read_packet_data(opj_t2_t* p_t2,
opj_tcd_tile_t *p_tile,
opj_pi_iterator_t *p_pi,
OPJ_BYTE *p_src_data,
OPJ_UINT32 * p_data_read,
OPJ_UINT32 p_max_length,
opj_packet_info_t *pack_info,
opj_event_mgr_t *p_manager);
static OPJ_BOOL opj_t2_skip_packet_data(opj_t2_t* p_t2,
opj_tcd_tile_t *p_tile,
opj_pi_iterator_t *p_pi,
OPJ_UINT32 * p_data_read,
OPJ_UINT32 p_max_length,
opj_packet_info_t *pack_info,
opj_event_mgr_t *p_manager);
/**
@param cblk
@param index
@param cblksty
@param first
*/
static OPJ_BOOL opj_t2_init_seg(opj_tcd_cblk_dec_t* cblk,
OPJ_UINT32 index,
OPJ_UINT32 cblksty,
OPJ_UINT32 first);
/*@}*/
/*@}*/
/* ----------------------------------------------------------------------- */
/* #define RESTART 0x04 */
static void opj_t2_putcommacode(opj_bio_t *bio, OPJ_INT32 n)
{
while (--n >= 0) {
opj_bio_write(bio, 1, 1);
}
opj_bio_write(bio, 0, 1);
}
static OPJ_UINT32 opj_t2_getcommacode(opj_bio_t *bio)
{
OPJ_UINT32 n = 0;
while (opj_bio_read(bio, 1)) {
++n;
}
return n;
}
static void opj_t2_putnumpasses(opj_bio_t *bio, OPJ_UINT32 n)
{
if (n == 1) {
opj_bio_write(bio, 0, 1);
} else if (n == 2) {
opj_bio_write(bio, 2, 2);
} else if (n <= 5) {
opj_bio_write(bio, 0xc | (n - 3), 4);
} else if (n <= 36) {
opj_bio_write(bio, 0x1e0 | (n - 6), 9);
} else if (n <= 164) {
opj_bio_write(bio, 0xff80 | (n - 37), 16);
}
}
static OPJ_UINT32 opj_t2_getnumpasses(opj_bio_t *bio)
{
OPJ_UINT32 n;
if (!opj_bio_read(bio, 1)) {
return 1;
}
if (!opj_bio_read(bio, 1)) {
return 2;
}
if ((n = opj_bio_read(bio, 2)) != 3) {
return (3 + n);
}
if ((n = opj_bio_read(bio, 5)) != 31) {
return (6 + n);
}
return (37 + opj_bio_read(bio, 7));
}
/* ----------------------------------------------------------------------- */
OPJ_BOOL opj_t2_encode_packets(opj_t2_t* p_t2,
OPJ_UINT32 p_tile_no,
opj_tcd_tile_t *p_tile,
OPJ_UINT32 p_maxlayers,
OPJ_BYTE *p_dest,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_max_len,
opj_codestream_info_t *cstr_info,
OPJ_UINT32 p_tp_num,
OPJ_INT32 p_tp_pos,
OPJ_UINT32 p_pino,
J2K_T2_MODE p_t2_mode,
opj_event_mgr_t *p_manager)
{
OPJ_BYTE *l_current_data = p_dest;
OPJ_UINT32 l_nb_bytes = 0;
OPJ_UINT32 compno;
OPJ_UINT32 poc;
opj_pi_iterator_t *l_pi = 00;
opj_pi_iterator_t *l_current_pi = 00;
opj_image_t *l_image = p_t2->image;
opj_cp_t *l_cp = p_t2->cp;
opj_tcp_t *l_tcp = &l_cp->tcps[p_tile_no];
OPJ_UINT32 pocno = (l_cp->rsiz == OPJ_PROFILE_CINEMA_4K) ? 2 : 1;
OPJ_UINT32 l_max_comp = l_cp->m_specific_param.m_enc.m_max_comp_size > 0 ?
l_image->numcomps : 1;
OPJ_UINT32 l_nb_pocs = l_tcp->numpocs + 1;
l_pi = opj_pi_initialise_encode(l_image, l_cp, p_tile_no, p_t2_mode);
if (!l_pi) {
return OPJ_FALSE;
}
* p_data_written = 0;
if (p_t2_mode == THRESH_CALC) { /* Calculating threshold */
l_current_pi = l_pi;
for (compno = 0; compno < l_max_comp; ++compno) {
OPJ_UINT32 l_comp_len = 0;
l_current_pi = l_pi;
for (poc = 0; poc < pocno ; ++poc) {
OPJ_UINT32 l_tp_num = compno;
/* TODO MSD : check why this function cannot fail (cf. v1) */
opj_pi_create_encode(l_pi, l_cp, p_tile_no, poc, l_tp_num, p_tp_pos, p_t2_mode);
if (l_current_pi->poc.prg == OPJ_PROG_UNKNOWN) {
/* TODO ADE : add an error */
opj_pi_destroy(l_pi, l_nb_pocs);
return OPJ_FALSE;
}
while (opj_pi_next(l_current_pi)) {
if (l_current_pi->layno < p_maxlayers) {
l_nb_bytes = 0;
if (! opj_t2_encode_packet(p_tile_no, p_tile, l_tcp, l_current_pi,
l_current_data, &l_nb_bytes,
p_max_len, cstr_info,
p_t2_mode,
p_manager)) {
opj_pi_destroy(l_pi, l_nb_pocs);
return OPJ_FALSE;
}
l_comp_len += l_nb_bytes;
l_current_data += l_nb_bytes;
p_max_len -= l_nb_bytes;
* p_data_written += l_nb_bytes;
}
}
if (l_cp->m_specific_param.m_enc.m_max_comp_size) {
if (l_comp_len > l_cp->m_specific_param.m_enc.m_max_comp_size) {
opj_pi_destroy(l_pi, l_nb_pocs);
return OPJ_FALSE;
}
}
++l_current_pi;
}
}
} else { /* t2_mode == FINAL_PASS */
opj_pi_create_encode(l_pi, l_cp, p_tile_no, p_pino, p_tp_num, p_tp_pos,
p_t2_mode);
l_current_pi = &l_pi[p_pino];
if (l_current_pi->poc.prg == OPJ_PROG_UNKNOWN) {
/* TODO ADE : add an error */
opj_pi_destroy(l_pi, l_nb_pocs);
return OPJ_FALSE;
}
while (opj_pi_next(l_current_pi)) {
if (l_current_pi->layno < p_maxlayers) {
l_nb_bytes = 0;
if (! opj_t2_encode_packet(p_tile_no, p_tile, l_tcp, l_current_pi,
l_current_data, &l_nb_bytes, p_max_len,
cstr_info, p_t2_mode, p_manager)) {
opj_pi_destroy(l_pi, l_nb_pocs);
return OPJ_FALSE;
}
l_current_data += l_nb_bytes;
p_max_len -= l_nb_bytes;
* p_data_written += l_nb_bytes;
/* INDEX >> */
if (cstr_info) {
if (cstr_info->index_write) {
opj_tile_info_t *info_TL = &cstr_info->tile[p_tile_no];
opj_packet_info_t *info_PK = &info_TL->packet[cstr_info->packno];
if (!cstr_info->packno) {
info_PK->start_pos = info_TL->end_header + 1;
} else {
info_PK->start_pos = ((l_cp->m_specific_param.m_enc.m_tp_on | l_tcp->POC) &&
info_PK->start_pos) ? info_PK->start_pos : info_TL->packet[cstr_info->packno -
1].end_pos + 1;
}
info_PK->end_pos = info_PK->start_pos + l_nb_bytes - 1;
info_PK->end_ph_pos += info_PK->start_pos -
1; /* End of packet header which now only represents the distance
to start of packet is incremented by value of start of packet*/
}
cstr_info->packno++;
}
/* << INDEX */
++p_tile->packno;
}
}
}
opj_pi_destroy(l_pi, l_nb_pocs);
return OPJ_TRUE;
}
/* see issue 80 */
#if 0
#define JAS_FPRINTF fprintf
#else
/* issue 290 */
static void opj_null_jas_fprintf(FILE* file, const char * format, ...)
{
(void)file;
(void)format;
}
#define JAS_FPRINTF opj_null_jas_fprintf
#endif
OPJ_BOOL opj_t2_decode_packets(opj_t2_t *p_t2,
OPJ_UINT32 p_tile_no,
opj_tcd_tile_t *p_tile,
OPJ_BYTE *p_src,
OPJ_UINT32 * p_data_read,
OPJ_UINT32 p_max_len,
opj_codestream_index_t *p_cstr_index,
opj_event_mgr_t *p_manager)
{
OPJ_BYTE *l_current_data = p_src;
opj_pi_iterator_t *l_pi = 00;
OPJ_UINT32 pino;
opj_image_t *l_image = p_t2->image;
opj_cp_t *l_cp = p_t2->cp;
opj_tcp_t *l_tcp = &(p_t2->cp->tcps[p_tile_no]);
OPJ_UINT32 l_nb_bytes_read;
OPJ_UINT32 l_nb_pocs = l_tcp->numpocs + 1;
opj_pi_iterator_t *l_current_pi = 00;
#ifdef TODO_MSD
OPJ_UINT32 curtp = 0;
OPJ_UINT32 tp_start_packno;
#endif
opj_packet_info_t *l_pack_info = 00;
opj_image_comp_t* l_img_comp = 00;
OPJ_ARG_NOT_USED(p_cstr_index);
#ifdef TODO_MSD
if (p_cstr_index) {
l_pack_info = p_cstr_index->tile_index[p_tile_no].packet;
}
#endif
/* create a packet iterator */
l_pi = opj_pi_create_decode(l_image, l_cp, p_tile_no);
if (!l_pi) {
return OPJ_FALSE;
}
l_current_pi = l_pi;
for (pino = 0; pino <= l_tcp->numpocs; ++pino) {
/* if the resolution needed is too low, one dim of the tilec could be equal to zero
* and no packets are used to decode this resolution and
* l_current_pi->resno is always >= p_tile->comps[l_current_pi->compno].minimum_num_resolutions
* and no l_img_comp->resno_decoded are computed
*/
OPJ_BOOL* first_pass_failed = NULL;
if (l_current_pi->poc.prg == OPJ_PROG_UNKNOWN) {
/* TODO ADE : add an error */
opj_pi_destroy(l_pi, l_nb_pocs);
return OPJ_FALSE;
}
first_pass_failed = (OPJ_BOOL*)opj_malloc(l_image->numcomps * sizeof(OPJ_BOOL));
if (!first_pass_failed) {
opj_pi_destroy(l_pi, l_nb_pocs);
return OPJ_FALSE;
}
memset(first_pass_failed, OPJ_TRUE, l_image->numcomps * sizeof(OPJ_BOOL));
while (opj_pi_next(l_current_pi)) {
JAS_FPRINTF(stderr,
"packet offset=00000166 prg=%d cmptno=%02d rlvlno=%02d prcno=%03d lyrno=%02d\n\n",
l_current_pi->poc.prg1, l_current_pi->compno, l_current_pi->resno,
l_current_pi->precno, l_current_pi->layno);
if (l_tcp->num_layers_to_decode > l_current_pi->layno
&& l_current_pi->resno <
p_tile->comps[l_current_pi->compno].minimum_num_resolutions) {
l_nb_bytes_read = 0;
first_pass_failed[l_current_pi->compno] = OPJ_FALSE;
if (! opj_t2_decode_packet(p_t2, p_tile, l_tcp, l_current_pi, l_current_data,
&l_nb_bytes_read, p_max_len, l_pack_info, p_manager)) {
opj_pi_destroy(l_pi, l_nb_pocs);
opj_free(first_pass_failed);
return OPJ_FALSE;
}
l_img_comp = &(l_image->comps[l_current_pi->compno]);
l_img_comp->resno_decoded = opj_uint_max(l_current_pi->resno,
l_img_comp->resno_decoded);
} else {
l_nb_bytes_read = 0;
if (! opj_t2_skip_packet(p_t2, p_tile, l_tcp, l_current_pi, l_current_data,
&l_nb_bytes_read, p_max_len, l_pack_info, p_manager)) {
opj_pi_destroy(l_pi, l_nb_pocs);
opj_free(first_pass_failed);
return OPJ_FALSE;
}
}
if (first_pass_failed[l_current_pi->compno]) {
l_img_comp = &(l_image->comps[l_current_pi->compno]);
if (l_img_comp->resno_decoded == 0) {
l_img_comp->resno_decoded =
p_tile->comps[l_current_pi->compno].minimum_num_resolutions - 1;
}
}
l_current_data += l_nb_bytes_read;
p_max_len -= l_nb_bytes_read;
/* INDEX >> */
#ifdef TODO_MSD
if (p_cstr_info) {
opj_tile_info_v2_t *info_TL = &p_cstr_info->tile[p_tile_no];
opj_packet_info_t *info_PK = &info_TL->packet[p_cstr_info->packno];
tp_start_packno = 0;
if (!p_cstr_info->packno) {
info_PK->start_pos = info_TL->end_header + 1;
} else if (info_TL->packet[p_cstr_info->packno - 1].end_pos >=
(OPJ_INT32)
p_cstr_info->tile[p_tile_no].tp[curtp].tp_end_pos) { /* New tile part */
info_TL->tp[curtp].tp_numpacks = p_cstr_info->packno -
tp_start_packno; /* Number of packets in previous tile-part */
tp_start_packno = p_cstr_info->packno;
curtp++;
info_PK->start_pos = p_cstr_info->tile[p_tile_no].tp[curtp].tp_end_header + 1;
} else {
info_PK->start_pos = (l_cp->m_specific_param.m_enc.m_tp_on &&
info_PK->start_pos) ? info_PK->start_pos : info_TL->packet[p_cstr_info->packno -
1].end_pos + 1;
}
info_PK->end_pos = info_PK->start_pos + l_nb_bytes_read - 1;
info_PK->end_ph_pos += info_PK->start_pos -
1; /* End of packet header which now only represents the distance */
++p_cstr_info->packno;
}
#endif
/* << INDEX */
}
++l_current_pi;
opj_free(first_pass_failed);
}
/* INDEX >> */
#ifdef TODO_MSD
if
(p_cstr_info) {
p_cstr_info->tile[p_tile_no].tp[curtp].tp_numpacks = p_cstr_info->packno -
tp_start_packno; /* Number of packets in last tile-part */
}
#endif
/* << INDEX */
/* don't forget to release pi */
opj_pi_destroy(l_pi, l_nb_pocs);
*p_data_read = (OPJ_UINT32)(l_current_data - p_src);
return OPJ_TRUE;
}
/* ----------------------------------------------------------------------- */
/**
* Creates a Tier 2 handle
*
* @param p_image Source or destination image
* @param p_cp Image coding parameters.
* @return a new T2 handle if successful, NULL otherwise.
*/
opj_t2_t* opj_t2_create(opj_image_t *p_image, opj_cp_t *p_cp)
{
/* create the t2 structure */
opj_t2_t *l_t2 = (opj_t2_t*)opj_calloc(1, sizeof(opj_t2_t));
if (!l_t2) {
return NULL;
}
l_t2->image = p_image;
l_t2->cp = p_cp;
return l_t2;
}
void opj_t2_destroy(opj_t2_t *t2)
{
if (t2) {
opj_free(t2);
}
}
static OPJ_BOOL opj_t2_decode_packet(opj_t2_t* p_t2,
opj_tcd_tile_t *p_tile,
opj_tcp_t *p_tcp,
opj_pi_iterator_t *p_pi,
OPJ_BYTE *p_src,
OPJ_UINT32 * p_data_read,
OPJ_UINT32 p_max_length,
opj_packet_info_t *p_pack_info,
opj_event_mgr_t *p_manager)
{
OPJ_BOOL l_read_data;
OPJ_UINT32 l_nb_bytes_read = 0;
OPJ_UINT32 l_nb_total_bytes_read = 0;
*p_data_read = 0;
if (! opj_t2_read_packet_header(p_t2, p_tile, p_tcp, p_pi, &l_read_data, p_src,
&l_nb_bytes_read, p_max_length, p_pack_info, p_manager)) {
return OPJ_FALSE;
}
p_src += l_nb_bytes_read;
l_nb_total_bytes_read += l_nb_bytes_read;
p_max_length -= l_nb_bytes_read;
/* we should read data for the packet */
if (l_read_data) {
l_nb_bytes_read = 0;
if (! opj_t2_read_packet_data(p_t2, p_tile, p_pi, p_src, &l_nb_bytes_read,
p_max_length, p_pack_info, p_manager)) {
return OPJ_FALSE;
}
l_nb_total_bytes_read += l_nb_bytes_read;
}
*p_data_read = l_nb_total_bytes_read;
return OPJ_TRUE;
}
static OPJ_BOOL opj_t2_encode_packet(OPJ_UINT32 tileno,
opj_tcd_tile_t * tile,
opj_tcp_t * tcp,
opj_pi_iterator_t *pi,
OPJ_BYTE *dest,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 length,
opj_codestream_info_t *cstr_info,
J2K_T2_MODE p_t2_mode,
opj_event_mgr_t *p_manager)
{
OPJ_UINT32 bandno, cblkno;
OPJ_BYTE* c = dest;
OPJ_UINT32 l_nb_bytes;
OPJ_UINT32 compno = pi->compno; /* component value */
OPJ_UINT32 resno = pi->resno; /* resolution level value */
OPJ_UINT32 precno = pi->precno; /* precinct value */
OPJ_UINT32 layno = pi->layno; /* quality layer value */
OPJ_UINT32 l_nb_blocks;
opj_tcd_band_t *band = 00;
opj_tcd_cblk_enc_t* cblk = 00;
opj_tcd_pass_t *pass = 00;
opj_tcd_tilecomp_t *tilec = &tile->comps[compno];
opj_tcd_resolution_t *res = &tilec->resolutions[resno];
opj_bio_t *bio = 00; /* BIO component */
OPJ_BOOL packet_empty = OPJ_TRUE;
/* <SOP 0xff91> */
if (tcp->csty & J2K_CP_CSTY_SOP) {
if (length < 6) {
if (p_t2_mode == FINAL_PASS) {
opj_event_msg(p_manager, EVT_ERROR,
"opj_t2_encode_packet(): only %u bytes remaining in "
"output buffer. %u needed.\n",
length, 6);
}
return OPJ_FALSE;
}
c[0] = 255;
c[1] = 145;
c[2] = 0;
c[3] = 4;
#if 0
c[4] = (tile->packno % 65536) / 256;
c[5] = (tile->packno % 65536) % 256;
#else
c[4] = (tile->packno >> 8) & 0xff; /* packno is uint32_t */
c[5] = tile->packno & 0xff;
#endif
c += 6;
length -= 6;
}
/* </SOP> */
if (!layno) {
band = res->bands;
for (bandno = 0; bandno < res->numbands; ++bandno, ++band) {
opj_tcd_precinct_t *prc;
/* Skip empty bands */
if (opj_tcd_is_band_empty(band)) {
continue;
}
prc = &band->precincts[precno];
opj_tgt_reset(prc->incltree);
opj_tgt_reset(prc->imsbtree);
l_nb_blocks = prc->cw * prc->ch;
for (cblkno = 0; cblkno < l_nb_blocks; ++cblkno) {
cblk = &prc->cblks.enc[cblkno];
cblk->numpasses = 0;
opj_tgt_setvalue(prc->imsbtree, cblkno, band->numbps - (OPJ_INT32)cblk->numbps);
}
}
}
bio = opj_bio_create();
if (!bio) {
/* FIXME event manager error callback */
return OPJ_FALSE;
}
opj_bio_init_enc(bio, c, length);
/* Check if the packet is empty */
/* Note: we could also skip that step and always write a packet header */
band = res->bands;
for (bandno = 0; bandno < res->numbands; ++bandno, ++band) {
opj_tcd_precinct_t *prc;
/* Skip empty bands */
if (opj_tcd_is_band_empty(band)) {
continue;
}
prc = &band->precincts[precno];
l_nb_blocks = prc->cw * prc->ch;
cblk = prc->cblks.enc;
for (cblkno = 0; cblkno < l_nb_blocks; cblkno++, ++cblk) {
opj_tcd_layer_t *layer = &cblk->layers[layno];
/* if cblk not included, go to the next cblk */
if (!layer->numpasses) {
continue;
}
packet_empty = OPJ_FALSE;
break;
}
if (!packet_empty) {
break;
}
}
opj_bio_write(bio, packet_empty ? 0 : 1, 1); /* Empty header bit */
/* Writing Packet header */
band = res->bands;
for (bandno = 0; !packet_empty &&
bandno < res->numbands; ++bandno, ++band) {
opj_tcd_precinct_t *prc;
/* Skip empty bands */
if (opj_tcd_is_band_empty(band)) {
continue;
}
prc = &band->precincts[precno];
l_nb_blocks = prc->cw * prc->ch;
cblk = prc->cblks.enc;
for (cblkno = 0; cblkno < l_nb_blocks; ++cblkno) {
opj_tcd_layer_t *layer = &cblk->layers[layno];
if (!cblk->numpasses && layer->numpasses) {
opj_tgt_setvalue(prc->incltree, cblkno, (OPJ_INT32)layno);
}
++cblk;
}
cblk = prc->cblks.enc;
for (cblkno = 0; cblkno < l_nb_blocks; cblkno++) {
opj_tcd_layer_t *layer = &cblk->layers[layno];
OPJ_UINT32 increment = 0;
OPJ_UINT32 nump = 0;
OPJ_UINT32 len = 0, passno;
OPJ_UINT32 l_nb_passes;
/* cblk inclusion bits */
if (!cblk->numpasses) {
opj_tgt_encode(bio, prc->incltree, cblkno, (OPJ_INT32)(layno + 1));
} else {
opj_bio_write(bio, layer->numpasses != 0, 1);
}
/* if cblk not included, go to the next cblk */
if (!layer->numpasses) {
++cblk;
continue;
}
/* if first instance of cblk --> zero bit-planes information */
if (!cblk->numpasses) {
cblk->numlenbits = 3;
opj_tgt_encode(bio, prc->imsbtree, cblkno, 999);
}
/* number of coding passes included */
opj_t2_putnumpasses(bio, layer->numpasses);
l_nb_passes = cblk->numpasses + layer->numpasses;
pass = cblk->passes + cblk->numpasses;
/* computation of the increase of the length indicator and insertion in the header */
for (passno = cblk->numpasses; passno < l_nb_passes; ++passno) {
++nump;
len += pass->len;
if (pass->term || passno == (cblk->numpasses + layer->numpasses) - 1) {
increment = (OPJ_UINT32)opj_int_max((OPJ_INT32)increment,
opj_int_floorlog2((OPJ_INT32)len) + 1
- ((OPJ_INT32)cblk->numlenbits + opj_int_floorlog2((OPJ_INT32)nump)));
len = 0;
nump = 0;
}
++pass;
}
opj_t2_putcommacode(bio, (OPJ_INT32)increment);
/* computation of the new Length indicator */
cblk->numlenbits += increment;
pass = cblk->passes + cblk->numpasses;
/* insertion of the codeword segment length */
for (passno = cblk->numpasses; passno < l_nb_passes; ++passno) {
nump++;
len += pass->len;
if (pass->term || passno == (cblk->numpasses + layer->numpasses) - 1) {
opj_bio_write(bio, (OPJ_UINT32)len,
cblk->numlenbits + (OPJ_UINT32)opj_int_floorlog2((OPJ_INT32)nump));
len = 0;
nump = 0;
}
++pass;
}
++cblk;
}
}
if (!opj_bio_flush(bio)) {
opj_bio_destroy(bio);
return OPJ_FALSE; /* modified to eliminate longjmp !! */
}
l_nb_bytes = (OPJ_UINT32)opj_bio_numbytes(bio);
c += l_nb_bytes;
length -= l_nb_bytes;
opj_bio_destroy(bio);
/* <EPH 0xff92> */
if (tcp->csty & J2K_CP_CSTY_EPH) {
if (length < 2) {
if (p_t2_mode == FINAL_PASS) {
opj_event_msg(p_manager, EVT_ERROR,
"opj_t2_encode_packet(): only %u bytes remaining in "
"output buffer. %u needed.\n",
length, 2);
}
return OPJ_FALSE;
}
c[0] = 255;
c[1] = 146;
c += 2;
length -= 2;
}
/* </EPH> */
/* << INDEX */
/* End of packet header position. Currently only represents the distance to start of packet
Will be updated later by incrementing with packet start value*/
if (cstr_info && cstr_info->index_write) {
opj_packet_info_t *info_PK = &cstr_info->tile[tileno].packet[cstr_info->packno];
info_PK->end_ph_pos = (OPJ_INT32)(c - dest);
}
/* INDEX >> */
/* Writing the packet body */
band = res->bands;
for (bandno = 0; !packet_empty && bandno < res->numbands; bandno++, ++band) {
opj_tcd_precinct_t *prc;
/* Skip empty bands */
if (opj_tcd_is_band_empty(band)) {
continue;
}
prc = &band->precincts[precno];
l_nb_blocks = prc->cw * prc->ch;
cblk = prc->cblks.enc;
for (cblkno = 0; cblkno < l_nb_blocks; ++cblkno) {
opj_tcd_layer_t *layer = &cblk->layers[layno];
if (!layer->numpasses) {
++cblk;
continue;
}
if (layer->len > length) {
if (p_t2_mode == FINAL_PASS) {
opj_event_msg(p_manager, EVT_ERROR,
"opj_t2_encode_packet(): only %u bytes remaining in "
"output buffer. %u needed.\n",
length, layer->len);
}
return OPJ_FALSE;
}
memcpy(c, layer->data, layer->len);
cblk->numpasses += layer->numpasses;
c += layer->len;
length -= layer->len;
/* << INDEX */
if (cstr_info && cstr_info->index_write) {
opj_packet_info_t *info_PK = &cstr_info->tile[tileno].packet[cstr_info->packno];
info_PK->disto += layer->disto;
if (cstr_info->D_max < info_PK->disto) {
cstr_info->D_max = info_PK->disto;
}
}
++cblk;
/* INDEX >> */
}
}
assert(c >= dest);
* p_data_written += (OPJ_UINT32)(c - dest);
return OPJ_TRUE;
}
static OPJ_BOOL opj_t2_skip_packet(opj_t2_t* p_t2,
opj_tcd_tile_t *p_tile,
opj_tcp_t *p_tcp,
opj_pi_iterator_t *p_pi,
OPJ_BYTE *p_src,
OPJ_UINT32 * p_data_read,
OPJ_UINT32 p_max_length,
opj_packet_info_t *p_pack_info,
opj_event_mgr_t *p_manager)
{
OPJ_BOOL l_read_data;
OPJ_UINT32 l_nb_bytes_read = 0;
OPJ_UINT32 l_nb_total_bytes_read = 0;
*p_data_read = 0;
if (! opj_t2_read_packet_header(p_t2, p_tile, p_tcp, p_pi, &l_read_data, p_src,
&l_nb_bytes_read, p_max_length, p_pack_info, p_manager)) {
return OPJ_FALSE;
}
p_src += l_nb_bytes_read;
l_nb_total_bytes_read += l_nb_bytes_read;
p_max_length -= l_nb_bytes_read;
/* we should read data for the packet */
if (l_read_data) {
l_nb_bytes_read = 0;
if (! opj_t2_skip_packet_data(p_t2, p_tile, p_pi, &l_nb_bytes_read,
p_max_length, p_pack_info, p_manager)) {
return OPJ_FALSE;
}
l_nb_total_bytes_read += l_nb_bytes_read;
}
*p_data_read = l_nb_total_bytes_read;
return OPJ_TRUE;
}
static OPJ_BOOL opj_t2_read_packet_header(opj_t2_t* p_t2,
opj_tcd_tile_t *p_tile,
opj_tcp_t *p_tcp,
opj_pi_iterator_t *p_pi,
OPJ_BOOL * p_is_data_present,
OPJ_BYTE *p_src_data,
OPJ_UINT32 * p_data_read,
OPJ_UINT32 p_max_length,
opj_packet_info_t *p_pack_info,
opj_event_mgr_t *p_manager)
{
/* loop */
OPJ_UINT32 bandno, cblkno;
OPJ_UINT32 l_nb_code_blocks;
OPJ_UINT32 l_remaining_length;
OPJ_UINT32 l_header_length;
OPJ_UINT32 * l_modified_length_ptr = 00;
OPJ_BYTE *l_current_data = p_src_data;
opj_cp_t *l_cp = p_t2->cp;
opj_bio_t *l_bio = 00; /* BIO component */
opj_tcd_band_t *l_band = 00;
opj_tcd_cblk_dec_t* l_cblk = 00;
opj_tcd_resolution_t* l_res =
&p_tile->comps[p_pi->compno].resolutions[p_pi->resno];
OPJ_BYTE *l_header_data = 00;
OPJ_BYTE **l_header_data_start = 00;
OPJ_UINT32 l_present;
if (p_pi->layno == 0) {
l_band = l_res->bands;
/* reset tagtrees */
for (bandno = 0; bandno < l_res->numbands; ++bandno) {
if (!opj_tcd_is_band_empty(l_band)) {
opj_tcd_precinct_t *l_prc = &l_band->precincts[p_pi->precno];
if (!(p_pi->precno < (l_band->precincts_data_size / sizeof(
opj_tcd_precinct_t)))) {
opj_event_msg(p_manager, EVT_ERROR, "Invalid precinct\n");
return OPJ_FALSE;
}
opj_tgt_reset(l_prc->incltree);
opj_tgt_reset(l_prc->imsbtree);
l_cblk = l_prc->cblks.dec;
l_nb_code_blocks = l_prc->cw * l_prc->ch;
for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) {
l_cblk->numsegs = 0;
l_cblk->real_num_segs = 0;
++l_cblk;
}
}
++l_band;
}
}
/* SOP markers */
if (p_tcp->csty & J2K_CP_CSTY_SOP) {
if (p_max_length < 6) {
opj_event_msg(p_manager, EVT_WARNING,
"Not enough space for expected SOP marker\n");
} else if ((*l_current_data) != 0xff || (*(l_current_data + 1) != 0x91)) {
opj_event_msg(p_manager, EVT_WARNING, "Expected SOP marker\n");
} else {
l_current_data += 6;
}
/** TODO : check the Nsop value */
}
/*
When the marker PPT/PPM is used the packet header are store in PPT/PPM marker
This part deal with this caracteristic
step 1: Read packet header in the saved structure
step 2: Return to codestream for decoding
*/
l_bio = opj_bio_create();
if (! l_bio) {
return OPJ_FALSE;
}
if (l_cp->ppm == 1) { /* PPM */
l_header_data_start = &l_cp->ppm_data;
l_header_data = *l_header_data_start;
l_modified_length_ptr = &(l_cp->ppm_len);
} else if (p_tcp->ppt == 1) { /* PPT */
l_header_data_start = &(p_tcp->ppt_data);
l_header_data = *l_header_data_start;
l_modified_length_ptr = &(p_tcp->ppt_len);
} else { /* Normal Case */
l_header_data_start = &(l_current_data);
l_header_data = *l_header_data_start;
l_remaining_length = (OPJ_UINT32)(p_src_data + p_max_length - l_header_data);
l_modified_length_ptr = &(l_remaining_length);
}
opj_bio_init_dec(l_bio, l_header_data, *l_modified_length_ptr);
l_present = opj_bio_read(l_bio, 1);
JAS_FPRINTF(stderr, "present=%d \n", l_present);
if (!l_present) {
/* TODO MSD: no test to control the output of this function*/
opj_bio_inalign(l_bio);
l_header_data += opj_bio_numbytes(l_bio);
opj_bio_destroy(l_bio);
/* EPH markers */
if (p_tcp->csty & J2K_CP_CSTY_EPH) {
if ((*l_modified_length_ptr - (OPJ_UINT32)(l_header_data -
*l_header_data_start)) < 2U) {
opj_event_msg(p_manager, EVT_WARNING,
"Not enough space for expected EPH marker\n");
} else if ((*l_header_data) != 0xff || (*(l_header_data + 1) != 0x92)) {
opj_event_msg(p_manager, EVT_WARNING, "Expected EPH marker\n");
} else {
l_header_data += 2;
}
}
l_header_length = (OPJ_UINT32)(l_header_data - *l_header_data_start);
*l_modified_length_ptr -= l_header_length;
*l_header_data_start += l_header_length;
/* << INDEX */
/* End of packet header position. Currently only represents the distance to start of packet
Will be updated later by incrementing with packet start value */
if (p_pack_info) {
p_pack_info->end_ph_pos = (OPJ_INT32)(l_current_data - p_src_data);
}
/* INDEX >> */
* p_is_data_present = OPJ_FALSE;
*p_data_read = (OPJ_UINT32)(l_current_data - p_src_data);
return OPJ_TRUE;
}
l_band = l_res->bands;
for (bandno = 0; bandno < l_res->numbands; ++bandno, ++l_band) {
opj_tcd_precinct_t *l_prc = &(l_band->precincts[p_pi->precno]);
if (opj_tcd_is_band_empty(l_band)) {
continue;
}
l_nb_code_blocks = l_prc->cw * l_prc->ch;
l_cblk = l_prc->cblks.dec;
for (cblkno = 0; cblkno < l_nb_code_blocks; cblkno++) {
OPJ_UINT32 l_included, l_increment, l_segno;
OPJ_INT32 n;
/* if cblk not yet included before --> inclusion tagtree */
if (!l_cblk->numsegs) {
l_included = opj_tgt_decode(l_bio, l_prc->incltree, cblkno,
(OPJ_INT32)(p_pi->layno + 1));
/* else one bit */
} else {
l_included = opj_bio_read(l_bio, 1);
}
/* if cblk not included */
if (!l_included) {
l_cblk->numnewpasses = 0;
++l_cblk;
JAS_FPRINTF(stderr, "included=%d \n", l_included);
continue;
}
/* if cblk not yet included --> zero-bitplane tagtree */
if (!l_cblk->numsegs) {
OPJ_UINT32 i = 0;
while (!opj_tgt_decode(l_bio, l_prc->imsbtree, cblkno, (OPJ_INT32)i)) {
++i;
}
l_cblk->numbps = (OPJ_UINT32)l_band->numbps + 1 - i;
l_cblk->numlenbits = 3;
}
/* number of coding passes */
l_cblk->numnewpasses = opj_t2_getnumpasses(l_bio);
l_increment = opj_t2_getcommacode(l_bio);
/* length indicator increment */
l_cblk->numlenbits += l_increment;
l_segno = 0;
if (!l_cblk->numsegs) {
if (! opj_t2_init_seg(l_cblk, l_segno, p_tcp->tccps[p_pi->compno].cblksty, 1)) {
opj_bio_destroy(l_bio);
return OPJ_FALSE;
}
} else {
l_segno = l_cblk->numsegs - 1;
if (l_cblk->segs[l_segno].numpasses == l_cblk->segs[l_segno].maxpasses) {
++l_segno;
if (! opj_t2_init_seg(l_cblk, l_segno, p_tcp->tccps[p_pi->compno].cblksty, 0)) {
opj_bio_destroy(l_bio);
return OPJ_FALSE;
}
}
}
n = (OPJ_INT32)l_cblk->numnewpasses;
do {
OPJ_UINT32 bit_number;
l_cblk->segs[l_segno].numnewpasses = (OPJ_UINT32)opj_int_min((OPJ_INT32)(
l_cblk->segs[l_segno].maxpasses - l_cblk->segs[l_segno].numpasses), n);
bit_number = l_cblk->numlenbits + opj_uint_floorlog2(
l_cblk->segs[l_segno].numnewpasses);
if (bit_number > 32) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid bit number %d in opj_t2_read_packet_header()\n",
bit_number);
opj_bio_destroy(l_bio);
return OPJ_FALSE;
}
l_cblk->segs[l_segno].newlen = opj_bio_read(l_bio, bit_number);
JAS_FPRINTF(stderr, "included=%d numnewpasses=%d increment=%d len=%d \n",
l_included, l_cblk->segs[l_segno].numnewpasses, l_increment,
l_cblk->segs[l_segno].newlen);
n -= (OPJ_INT32)l_cblk->segs[l_segno].numnewpasses;
if (n > 0) {
++l_segno;
if (! opj_t2_init_seg(l_cblk, l_segno, p_tcp->tccps[p_pi->compno].cblksty, 0)) {
opj_bio_destroy(l_bio);
return OPJ_FALSE;
}
}
} while (n > 0);
++l_cblk;
}
}
if (!opj_bio_inalign(l_bio)) {
opj_bio_destroy(l_bio);
return OPJ_FALSE;
}
l_header_data += opj_bio_numbytes(l_bio);
opj_bio_destroy(l_bio);
/* EPH markers */
if (p_tcp->csty & J2K_CP_CSTY_EPH) {
if ((*l_modified_length_ptr - (OPJ_UINT32)(l_header_data -
*l_header_data_start)) < 2U) {
opj_event_msg(p_manager, EVT_WARNING,
"Not enough space for expected EPH marker\n");
} else if ((*l_header_data) != 0xff || (*(l_header_data + 1) != 0x92)) {
opj_event_msg(p_manager, EVT_WARNING, "Expected EPH marker\n");
} else {
l_header_data += 2;
}
}
l_header_length = (OPJ_UINT32)(l_header_data - *l_header_data_start);
JAS_FPRINTF(stderr, "hdrlen=%d \n", l_header_length);
JAS_FPRINTF(stderr, "packet body\n");
*l_modified_length_ptr -= l_header_length;
*l_header_data_start += l_header_length;
/* << INDEX */
/* End of packet header position. Currently only represents the distance to start of packet
Will be updated later by incrementing with packet start value */
if (p_pack_info) {
p_pack_info->end_ph_pos = (OPJ_INT32)(l_current_data - p_src_data);
}
/* INDEX >> */
*p_is_data_present = OPJ_TRUE;
*p_data_read = (OPJ_UINT32)(l_current_data - p_src_data);
return OPJ_TRUE;
}
static OPJ_BOOL opj_t2_read_packet_data(opj_t2_t* p_t2,
opj_tcd_tile_t *p_tile,
opj_pi_iterator_t *p_pi,
OPJ_BYTE *p_src_data,
OPJ_UINT32 * p_data_read,
OPJ_UINT32 p_max_length,
opj_packet_info_t *pack_info,
opj_event_mgr_t* p_manager)
{
OPJ_UINT32 bandno, cblkno;
OPJ_UINT32 l_nb_code_blocks;
OPJ_BYTE *l_current_data = p_src_data;
opj_tcd_band_t *l_band = 00;
opj_tcd_cblk_dec_t* l_cblk = 00;
opj_tcd_resolution_t* l_res =
&p_tile->comps[p_pi->compno].resolutions[p_pi->resno];
OPJ_ARG_NOT_USED(p_t2);
OPJ_ARG_NOT_USED(pack_info);
l_band = l_res->bands;
for (bandno = 0; bandno < l_res->numbands; ++bandno) {
opj_tcd_precinct_t *l_prc = &l_band->precincts[p_pi->precno];
if ((l_band->x1 - l_band->x0 == 0) || (l_band->y1 - l_band->y0 == 0)) {
++l_band;
continue;
}
l_nb_code_blocks = l_prc->cw * l_prc->ch;
l_cblk = l_prc->cblks.dec;
for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) {
opj_tcd_seg_t *l_seg = 00;
if (!l_cblk->numnewpasses) {
/* nothing to do */
++l_cblk;
continue;
}
if (!l_cblk->numsegs) {
l_seg = l_cblk->segs;
++l_cblk->numsegs;
} else {
l_seg = &l_cblk->segs[l_cblk->numsegs - 1];
if (l_seg->numpasses == l_seg->maxpasses) {
++l_seg;
++l_cblk->numsegs;
}
}
do {
/* Check possible overflow (on l_current_data only, assumes input args already checked) then size */
if ((((OPJ_SIZE_T)l_current_data + (OPJ_SIZE_T)l_seg->newlen) <
(OPJ_SIZE_T)l_current_data) ||
(l_current_data + l_seg->newlen > p_src_data + p_max_length)) {
opj_event_msg(p_manager, EVT_ERROR,
"read: segment too long (%d) with max (%d) for codeblock %d (p=%d, b=%d, r=%d, c=%d)\n",
l_seg->newlen, p_max_length, cblkno, p_pi->precno, bandno, p_pi->resno,
p_pi->compno);
return OPJ_FALSE;
}
#ifdef USE_JPWL
/* we need here a j2k handle to verify if making a check to
the validity of cblocks parameters is selected from user (-W) */
/* let's check that we are not exceeding */
if ((l_cblk->len + l_seg->newlen) > 8192) {
opj_event_msg(p_manager, EVT_WARNING,
"JPWL: segment too long (%d) for codeblock %d (p=%d, b=%d, r=%d, c=%d)\n",
l_seg->newlen, cblkno, p_pi->precno, bandno, p_pi->resno, p_pi->compno);
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
l_seg->newlen = 8192 - l_cblk->len;
opj_event_msg(p_manager, EVT_WARNING, " - truncating segment to %d\n",
l_seg->newlen);
break;
};
#endif /* USE_JPWL */
if (l_cblk->numchunks == l_cblk->numchunksalloc) {
OPJ_UINT32 l_numchunksalloc = l_cblk->numchunksalloc * 2 + 1;
opj_tcd_seg_data_chunk_t* l_chunks =
(opj_tcd_seg_data_chunk_t*)opj_realloc(l_cblk->chunks,
l_numchunksalloc * sizeof(opj_tcd_seg_data_chunk_t));
if (l_chunks == NULL) {
opj_event_msg(p_manager, EVT_ERROR,
"cannot allocate opj_tcd_seg_data_chunk_t* array");
return OPJ_FALSE;
}
l_cblk->chunks = l_chunks;
l_cblk->numchunksalloc = l_numchunksalloc;
}
l_cblk->chunks[l_cblk->numchunks].data = l_current_data;
l_cblk->chunks[l_cblk->numchunks].len = l_seg->newlen;
l_cblk->numchunks ++;
l_current_data += l_seg->newlen;
l_seg->len += l_seg->newlen;
l_seg->numpasses += l_seg->numnewpasses;
l_cblk->numnewpasses -= l_seg->numnewpasses;
l_seg->real_num_passes = l_seg->numpasses;
if (l_cblk->numnewpasses > 0) {
++l_seg;
++l_cblk->numsegs;
}
} while (l_cblk->numnewpasses > 0);
l_cblk->real_num_segs = l_cblk->numsegs;
++l_cblk;
} /* next code_block */
++l_band;
}
*(p_data_read) = (OPJ_UINT32)(l_current_data - p_src_data);
return OPJ_TRUE;
}
static OPJ_BOOL opj_t2_skip_packet_data(opj_t2_t* p_t2,
opj_tcd_tile_t *p_tile,
opj_pi_iterator_t *p_pi,
OPJ_UINT32 * p_data_read,
OPJ_UINT32 p_max_length,
opj_packet_info_t *pack_info,
opj_event_mgr_t *p_manager)
{
OPJ_UINT32 bandno, cblkno;
OPJ_UINT32 l_nb_code_blocks;
opj_tcd_band_t *l_band = 00;
opj_tcd_cblk_dec_t* l_cblk = 00;
opj_tcd_resolution_t* l_res =
&p_tile->comps[p_pi->compno].resolutions[p_pi->resno];
OPJ_ARG_NOT_USED(p_t2);
OPJ_ARG_NOT_USED(pack_info);
*p_data_read = 0;
l_band = l_res->bands;
for (bandno = 0; bandno < l_res->numbands; ++bandno) {
opj_tcd_precinct_t *l_prc = &l_band->precincts[p_pi->precno];
if ((l_band->x1 - l_band->x0 == 0) || (l_band->y1 - l_band->y0 == 0)) {
++l_band;
continue;
}
l_nb_code_blocks = l_prc->cw * l_prc->ch;
l_cblk = l_prc->cblks.dec;
for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) {
opj_tcd_seg_t *l_seg = 00;
if (!l_cblk->numnewpasses) {
/* nothing to do */
++l_cblk;
continue;
}
if (!l_cblk->numsegs) {
l_seg = l_cblk->segs;
++l_cblk->numsegs;
} else {
l_seg = &l_cblk->segs[l_cblk->numsegs - 1];
if (l_seg->numpasses == l_seg->maxpasses) {
++l_seg;
++l_cblk->numsegs;
}
}
do {
/* Check possible overflow then size */
if (((*p_data_read + l_seg->newlen) < (*p_data_read)) ||
((*p_data_read + l_seg->newlen) > p_max_length)) {
opj_event_msg(p_manager, EVT_ERROR,
"skip: segment too long (%d) with max (%d) for codeblock %d (p=%d, b=%d, r=%d, c=%d)\n",
l_seg->newlen, p_max_length, cblkno, p_pi->precno, bandno, p_pi->resno,
p_pi->compno);
return OPJ_FALSE;
}
#ifdef USE_JPWL
/* we need here a j2k handle to verify if making a check to
the validity of cblocks parameters is selected from user (-W) */
/* let's check that we are not exceeding */
if ((l_cblk->len + l_seg->newlen) > 8192) {
opj_event_msg(p_manager, EVT_WARNING,
"JPWL: segment too long (%d) for codeblock %d (p=%d, b=%d, r=%d, c=%d)\n",
l_seg->newlen, cblkno, p_pi->precno, bandno, p_pi->resno, p_pi->compno);
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return -999;
}
l_seg->newlen = 8192 - l_cblk->len;
opj_event_msg(p_manager, EVT_WARNING, " - truncating segment to %d\n",
l_seg->newlen);
break;
};
#endif /* USE_JPWL */
JAS_FPRINTF(stderr, "p_data_read (%d) newlen (%d) \n", *p_data_read,
l_seg->newlen);
*(p_data_read) += l_seg->newlen;
l_seg->numpasses += l_seg->numnewpasses;
l_cblk->numnewpasses -= l_seg->numnewpasses;
if (l_cblk->numnewpasses > 0) {
++l_seg;
++l_cblk->numsegs;
}
} while (l_cblk->numnewpasses > 0);
++l_cblk;
}
++l_band;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_t2_init_seg(opj_tcd_cblk_dec_t* cblk,
OPJ_UINT32 index,
OPJ_UINT32 cblksty,
OPJ_UINT32 first)
{
opj_tcd_seg_t* seg = 00;
OPJ_UINT32 l_nb_segs = index + 1;
if (l_nb_segs > cblk->m_current_max_segs) {
opj_tcd_seg_t* new_segs;
OPJ_UINT32 l_m_current_max_segs = cblk->m_current_max_segs +
OPJ_J2K_DEFAULT_NB_SEGS;
new_segs = (opj_tcd_seg_t*) opj_realloc(cblk->segs,
l_m_current_max_segs * sizeof(opj_tcd_seg_t));
if (! new_segs) {
/* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to initialize segment %d\n", l_nb_segs); */
return OPJ_FALSE;
}
cblk->segs = new_segs;
memset(new_segs + cblk->m_current_max_segs,
0, OPJ_J2K_DEFAULT_NB_SEGS * sizeof(opj_tcd_seg_t));
cblk->m_current_max_segs = l_m_current_max_segs;
}
seg = &cblk->segs[index];
opj_tcd_reinit_segment(seg);
if (cblksty & J2K_CCP_CBLKSTY_TERMALL) {
seg->maxpasses = 1;
} else if (cblksty & J2K_CCP_CBLKSTY_LAZY) {
if (first) {
seg->maxpasses = 10;
} else {
seg->maxpasses = (((seg - 1)->maxpasses == 1) ||
((seg - 1)->maxpasses == 10)) ? 2 : 1;
}
} else {
/* See paragraph "B.10.6 Number of coding passes" of the standard.
* Probably that 109 must be interpreted a (Mb-1)*3 + 1 with Mb=37,
* Mb being the maximum number of bit-planes available for the
* representation of coefficients in the sub-band */
seg->maxpasses = 109;
}
return OPJ_TRUE;
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_2758_1 |
crossvul-cpp_data_good_205_3 | /*
* trace_events_filter - generic event filtering
*
* 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.
*
* Copyright (C) 2009 Tom Zanussi <tzanussi@gmail.com>
*/
#include <linux/module.h>
#include <linux/ctype.h>
#include <linux/mutex.h>
#include <linux/perf_event.h>
#include <linux/slab.h>
#include "trace.h"
#include "trace_output.h"
#define DEFAULT_SYS_FILTER_MESSAGE \
"### global filter ###\n" \
"# Use this to set filters for multiple events.\n" \
"# Only events with the given fields will be affected.\n" \
"# If no events are modified, an error message will be displayed here"
/* Due to token parsing '<=' must be before '<' and '>=' must be before '>' */
#define OPS \
C( OP_GLOB, "~" ), \
C( OP_NE, "!=" ), \
C( OP_EQ, "==" ), \
C( OP_LE, "<=" ), \
C( OP_LT, "<" ), \
C( OP_GE, ">=" ), \
C( OP_GT, ">" ), \
C( OP_BAND, "&" ), \
C( OP_MAX, NULL )
#undef C
#define C(a, b) a
enum filter_op_ids { OPS };
#undef C
#define C(a, b) b
static const char * ops[] = { OPS };
/*
* pred functions are OP_LE, OP_LT, OP_GE, OP_GT, and OP_BAND
* pred_funcs_##type below must match the order of them above.
*/
#define PRED_FUNC_START OP_LE
#define PRED_FUNC_MAX (OP_BAND - PRED_FUNC_START)
#define ERRORS \
C(NONE, "No error"), \
C(INVALID_OP, "Invalid operator"), \
C(TOO_MANY_OPEN, "Too many '('"), \
C(TOO_MANY_CLOSE, "Too few '('"), \
C(MISSING_QUOTE, "Missing matching quote"), \
C(OPERAND_TOO_LONG, "Operand too long"), \
C(EXPECT_STRING, "Expecting string field"), \
C(EXPECT_DIGIT, "Expecting numeric field"), \
C(ILLEGAL_FIELD_OP, "Illegal operation for field type"), \
C(FIELD_NOT_FOUND, "Field not found"), \
C(ILLEGAL_INTVAL, "Illegal integer value"), \
C(BAD_SUBSYS_FILTER, "Couldn't find or set field in one of a subsystem's events"), \
C(TOO_MANY_PREDS, "Too many terms in predicate expression"), \
C(INVALID_FILTER, "Meaningless filter expression"), \
C(IP_FIELD_ONLY, "Only 'ip' field is supported for function trace"), \
C(INVALID_VALUE, "Invalid value (did you forget quotes)?"), \
C(NO_FILTER, "No filter found"),
#undef C
#define C(a, b) FILT_ERR_##a
enum { ERRORS };
#undef C
#define C(a, b) b
static char *err_text[] = { ERRORS };
/* Called after a '!' character but "!=" and "!~" are not "not"s */
static bool is_not(const char *str)
{
switch (str[1]) {
case '=':
case '~':
return false;
}
return true;
}
/**
* prog_entry - a singe entry in the filter program
* @target: Index to jump to on a branch (actually one minus the index)
* @when_to_branch: The value of the result of the predicate to do a branch
* @pred: The predicate to execute.
*/
struct prog_entry {
int target;
int when_to_branch;
struct filter_pred *pred;
};
/**
* update_preds- assign a program entry a label target
* @prog: The program array
* @N: The index of the current entry in @prog
* @when_to_branch: What to assign a program entry for its branch condition
*
* The program entry at @N has a target that points to the index of a program
* entry that can have its target and when_to_branch fields updated.
* Update the current program entry denoted by index @N target field to be
* that of the updated entry. This will denote the entry to update if
* we are processing an "||" after an "&&"
*/
static void update_preds(struct prog_entry *prog, int N, int invert)
{
int t, s;
t = prog[N].target;
s = prog[t].target;
prog[t].when_to_branch = invert;
prog[t].target = N;
prog[N].target = s;
}
struct filter_parse_error {
int lasterr;
int lasterr_pos;
};
static void parse_error(struct filter_parse_error *pe, int err, int pos)
{
pe->lasterr = err;
pe->lasterr_pos = pos;
}
typedef int (*parse_pred_fn)(const char *str, void *data, int pos,
struct filter_parse_error *pe,
struct filter_pred **pred);
enum {
INVERT = 1,
PROCESS_AND = 2,
PROCESS_OR = 4,
};
/*
* Without going into a formal proof, this explains the method that is used in
* parsing the logical expressions.
*
* For example, if we have: "a && !(!b || (c && g)) || d || e && !f"
* The first pass will convert it into the following program:
*
* n1: r=a; l1: if (!r) goto l4;
* n2: r=b; l2: if (!r) goto l4;
* n3: r=c; r=!r; l3: if (r) goto l4;
* n4: r=g; r=!r; l4: if (r) goto l5;
* n5: r=d; l5: if (r) goto T
* n6: r=e; l6: if (!r) goto l7;
* n7: r=f; r=!r; l7: if (!r) goto F
* T: return TRUE
* F: return FALSE
*
* To do this, we use a data structure to represent each of the above
* predicate and conditions that has:
*
* predicate, when_to_branch, invert, target
*
* The "predicate" will hold the function to determine the result "r".
* The "when_to_branch" denotes what "r" should be if a branch is to be taken
* "&&" would contain "!r" or (0) and "||" would contain "r" or (1).
* The "invert" holds whether the value should be reversed before testing.
* The "target" contains the label "l#" to jump to.
*
* A stack is created to hold values when parentheses are used.
*
* To simplify the logic, the labels will start at 0 and not 1.
*
* The possible invert values are 1 and 0. The number of "!"s that are in scope
* before the predicate determines the invert value, if the number is odd then
* the invert value is 1 and 0 otherwise. This means the invert value only
* needs to be toggled when a new "!" is introduced compared to what is stored
* on the stack, where parentheses were used.
*
* The top of the stack and "invert" are initialized to zero.
*
* ** FIRST PASS **
*
* #1 A loop through all the tokens is done:
*
* #2 If the token is an "(", the stack is push, and the current stack value
* gets the current invert value, and the loop continues to the next token.
* The top of the stack saves the "invert" value to keep track of what
* the current inversion is. As "!(a && !b || c)" would require all
* predicates being affected separately by the "!" before the parentheses.
* And that would end up being equivalent to "(!a || b) && !c"
*
* #3 If the token is an "!", the current "invert" value gets inverted, and
* the loop continues. Note, if the next token is a predicate, then
* this "invert" value is only valid for the current program entry,
* and does not affect other predicates later on.
*
* The only other acceptable token is the predicate string.
*
* #4 A new entry into the program is added saving: the predicate and the
* current value of "invert". The target is currently assigned to the
* previous program index (this will not be its final value).
*
* #5 We now enter another loop and look at the next token. The only valid
* tokens are ")", "&&", "||" or end of the input string "\0".
*
* #6 The invert variable is reset to the current value saved on the top of
* the stack.
*
* #7 The top of the stack holds not only the current invert value, but also
* if a "&&" or "||" needs to be processed. Note, the "&&" takes higher
* precedence than "||". That is "a && b || c && d" is equivalent to
* "(a && b) || (c && d)". Thus the first thing to do is to see if "&&" needs
* to be processed. This is the case if an "&&" was the last token. If it was
* then we call update_preds(). This takes the program, the current index in
* the program, and the current value of "invert". More will be described
* below about this function.
*
* #8 If the next token is "&&" then we set a flag in the top of the stack
* that denotes that "&&" needs to be processed, break out of this loop
* and continue with the outer loop.
*
* #9 Otherwise, if a "||" needs to be processed then update_preds() is called.
* This is called with the program, the current index in the program, but
* this time with an inverted value of "invert" (that is !invert). This is
* because the value taken will become the "when_to_branch" value of the
* program.
* Note, this is called when the next token is not an "&&". As stated before,
* "&&" takes higher precedence, and "||" should not be processed yet if the
* next logical operation is "&&".
*
* #10 If the next token is "||" then we set a flag in the top of the stack
* that denotes that "||" needs to be processed, break out of this loop
* and continue with the outer loop.
*
* #11 If this is the end of the input string "\0" then we break out of both
* loops.
*
* #12 Otherwise, the next token is ")", where we pop the stack and continue
* this inner loop.
*
* Now to discuss the update_pred() function, as that is key to the setting up
* of the program. Remember the "target" of the program is initialized to the
* previous index and not the "l" label. The target holds the index into the
* program that gets affected by the operand. Thus if we have something like
* "a || b && c", when we process "a" the target will be "-1" (undefined).
* When we process "b", its target is "0", which is the index of "a", as that's
* the predicate that is affected by "||". But because the next token after "b"
* is "&&" we don't call update_preds(). Instead continue to "c". As the
* next token after "c" is not "&&" but the end of input, we first process the
* "&&" by calling update_preds() for the "&&" then we process the "||" by
* callin updates_preds() with the values for processing "||".
*
* What does that mean? What update_preds() does is to first save the "target"
* of the program entry indexed by the current program entry's "target"
* (remember the "target" is initialized to previous program entry), and then
* sets that "target" to the current index which represents the label "l#".
* That entry's "when_to_branch" is set to the value passed in (the "invert"
* or "!invert"). Then it sets the current program entry's target to the saved
* "target" value (the old value of the program that had its "target" updated
* to the label).
*
* Looking back at "a || b && c", we have the following steps:
* "a" - prog[0] = { "a", X, -1 } // pred, when_to_branch, target
* "||" - flag that we need to process "||"; continue outer loop
* "b" - prog[1] = { "b", X, 0 }
* "&&" - flag that we need to process "&&"; continue outer loop
* (Notice we did not process "||")
* "c" - prog[2] = { "c", X, 1 }
* update_preds(prog, 2, 0); // invert = 0 as we are processing "&&"
* t = prog[2].target; // t = 1
* s = prog[t].target; // s = 0
* prog[t].target = 2; // Set target to "l2"
* prog[t].when_to_branch = 0;
* prog[2].target = s;
* update_preds(prog, 2, 1); // invert = 1 as we are now processing "||"
* t = prog[2].target; // t = 0
* s = prog[t].target; // s = -1
* prog[t].target = 2; // Set target to "l2"
* prog[t].when_to_branch = 1;
* prog[2].target = s;
*
* #13 Which brings us to the final step of the first pass, which is to set
* the last program entry's when_to_branch and target, which will be
* when_to_branch = 0; target = N; ( the label after the program entry after
* the last program entry processed above).
*
* If we denote "TRUE" to be the entry after the last program entry processed,
* and "FALSE" the program entry after that, we are now done with the first
* pass.
*
* Making the above "a || b && c" have a progam of:
* prog[0] = { "a", 1, 2 }
* prog[1] = { "b", 0, 2 }
* prog[2] = { "c", 0, 3 }
*
* Which translates into:
* n0: r = a; l0: if (r) goto l2;
* n1: r = b; l1: if (!r) goto l2;
* n2: r = c; l2: if (!r) goto l3; // Which is the same as "goto F;"
* T: return TRUE; l3:
* F: return FALSE
*
* Although, after the first pass, the program is correct, it is
* inefficient. The simple sample of "a || b && c" could be easily been
* converted into:
* n0: r = a; if (r) goto T
* n1: r = b; if (!r) goto F
* n2: r = c; if (!r) goto F
* T: return TRUE;
* F: return FALSE;
*
* The First Pass is over the input string. The next too passes are over
* the program itself.
*
* ** SECOND PASS **
*
* Which brings us to the second pass. If a jump to a label has the
* same condition as that label, it can instead jump to its target.
* The original example of "a && !(!b || (c && g)) || d || e && !f"
* where the first pass gives us:
*
* n1: r=a; l1: if (!r) goto l4;
* n2: r=b; l2: if (!r) goto l4;
* n3: r=c; r=!r; l3: if (r) goto l4;
* n4: r=g; r=!r; l4: if (r) goto l5;
* n5: r=d; l5: if (r) goto T
* n6: r=e; l6: if (!r) goto l7;
* n7: r=f; r=!r; l7: if (!r) goto F:
* T: return TRUE;
* F: return FALSE
*
* We can see that "l3: if (r) goto l4;" and at l4, we have "if (r) goto l5;".
* And "l5: if (r) goto T", we could optimize this by converting l3 and l4
* to go directly to T. To accomplish this, we start from the last
* entry in the program and work our way back. If the target of the entry
* has the same "when_to_branch" then we could use that entry's target.
* Doing this, the above would end up as:
*
* n1: r=a; l1: if (!r) goto l4;
* n2: r=b; l2: if (!r) goto l4;
* n3: r=c; r=!r; l3: if (r) goto T;
* n4: r=g; r=!r; l4: if (r) goto T;
* n5: r=d; l5: if (r) goto T;
* n6: r=e; l6: if (!r) goto F;
* n7: r=f; r=!r; l7: if (!r) goto F;
* T: return TRUE
* F: return FALSE
*
* In that same pass, if the "when_to_branch" doesn't match, we can simply
* go to the program entry after the label. That is, "l2: if (!r) goto l4;"
* where "l4: if (r) goto T;", then we can convert l2 to be:
* "l2: if (!r) goto n5;".
*
* This will have the second pass give us:
* n1: r=a; l1: if (!r) goto n5;
* n2: r=b; l2: if (!r) goto n5;
* n3: r=c; r=!r; l3: if (r) goto T;
* n4: r=g; r=!r; l4: if (r) goto T;
* n5: r=d; l5: if (r) goto T
* n6: r=e; l6: if (!r) goto F;
* n7: r=f; r=!r; l7: if (!r) goto F
* T: return TRUE
* F: return FALSE
*
* Notice, all the "l#" labels are no longer used, and they can now
* be discarded.
*
* ** THIRD PASS **
*
* For the third pass we deal with the inverts. As they simply just
* make the "when_to_branch" get inverted, a simple loop over the
* program to that does: "when_to_branch ^= invert;" will do the
* job, leaving us with:
* n1: r=a; if (!r) goto n5;
* n2: r=b; if (!r) goto n5;
* n3: r=c: if (!r) goto T;
* n4: r=g; if (!r) goto T;
* n5: r=d; if (r) goto T
* n6: r=e; if (!r) goto F;
* n7: r=f; if (r) goto F
* T: return TRUE
* F: return FALSE
*
* As "r = a; if (!r) goto n5;" is obviously the same as
* "if (!a) goto n5;" without doing anything we can interperate the
* program as:
* n1: if (!a) goto n5;
* n2: if (!b) goto n5;
* n3: if (!c) goto T;
* n4: if (!g) goto T;
* n5: if (d) goto T
* n6: if (!e) goto F;
* n7: if (f) goto F
* T: return TRUE
* F: return FALSE
*
* Since the inverts are discarded at the end, there's no reason to store
* them in the program array (and waste memory). A separate array to hold
* the inverts is used and freed at the end.
*/
static struct prog_entry *
predicate_parse(const char *str, int nr_parens, int nr_preds,
parse_pred_fn parse_pred, void *data,
struct filter_parse_error *pe)
{
struct prog_entry *prog_stack;
struct prog_entry *prog;
const char *ptr = str;
char *inverts = NULL;
int *op_stack;
int *top;
int invert = 0;
int ret = -ENOMEM;
int len;
int N = 0;
int i;
nr_preds += 2; /* For TRUE and FALSE */
op_stack = kmalloc_array(nr_parens, sizeof(*op_stack), GFP_KERNEL);
if (!op_stack)
return ERR_PTR(-ENOMEM);
prog_stack = kmalloc_array(nr_preds, sizeof(*prog_stack), GFP_KERNEL);
if (!prog_stack) {
parse_error(pe, -ENOMEM, 0);
goto out_free;
}
inverts = kmalloc_array(nr_preds, sizeof(*inverts), GFP_KERNEL);
if (!inverts) {
parse_error(pe, -ENOMEM, 0);
goto out_free;
}
top = op_stack;
prog = prog_stack;
*top = 0;
/* First pass */
while (*ptr) { /* #1 */
const char *next = ptr++;
if (isspace(*next))
continue;
switch (*next) {
case '(': /* #2 */
if (top - op_stack > nr_parens)
return ERR_PTR(-EINVAL);
*(++top) = invert;
continue;
case '!': /* #3 */
if (!is_not(next))
break;
invert = !invert;
continue;
}
if (N >= nr_preds) {
parse_error(pe, FILT_ERR_TOO_MANY_PREDS, next - str);
goto out_free;
}
inverts[N] = invert; /* #4 */
prog[N].target = N-1;
len = parse_pred(next, data, ptr - str, pe, &prog[N].pred);
if (len < 0) {
ret = len;
goto out_free;
}
ptr = next + len;
N++;
ret = -1;
while (1) { /* #5 */
next = ptr++;
if (isspace(*next))
continue;
switch (*next) {
case ')':
case '\0':
break;
case '&':
case '|':
if (next[1] == next[0]) {
ptr++;
break;
}
default:
parse_error(pe, FILT_ERR_TOO_MANY_PREDS,
next - str);
goto out_free;
}
invert = *top & INVERT;
if (*top & PROCESS_AND) { /* #7 */
update_preds(prog, N - 1, invert);
*top &= ~PROCESS_AND;
}
if (*next == '&') { /* #8 */
*top |= PROCESS_AND;
break;
}
if (*top & PROCESS_OR) { /* #9 */
update_preds(prog, N - 1, !invert);
*top &= ~PROCESS_OR;
}
if (*next == '|') { /* #10 */
*top |= PROCESS_OR;
break;
}
if (!*next) /* #11 */
goto out;
if (top == op_stack) {
ret = -1;
/* Too few '(' */
parse_error(pe, FILT_ERR_TOO_MANY_CLOSE, ptr - str);
goto out_free;
}
top--; /* #12 */
}
}
out:
if (top != op_stack) {
/* Too many '(' */
parse_error(pe, FILT_ERR_TOO_MANY_OPEN, ptr - str);
goto out_free;
}
if (!N) {
/* No program? */
ret = -EINVAL;
parse_error(pe, FILT_ERR_NO_FILTER, ptr - str);
goto out_free;
}
prog[N].pred = NULL; /* #13 */
prog[N].target = 1; /* TRUE */
prog[N+1].pred = NULL;
prog[N+1].target = 0; /* FALSE */
prog[N-1].target = N;
prog[N-1].when_to_branch = false;
/* Second Pass */
for (i = N-1 ; i--; ) {
int target = prog[i].target;
if (prog[i].when_to_branch == prog[target].when_to_branch)
prog[i].target = prog[target].target;
}
/* Third Pass */
for (i = 0; i < N; i++) {
invert = inverts[i] ^ prog[i].when_to_branch;
prog[i].when_to_branch = invert;
/* Make sure the program always moves forward */
if (WARN_ON(prog[i].target <= i)) {
ret = -EINVAL;
goto out_free;
}
}
return prog;
out_free:
kfree(op_stack);
kfree(prog_stack);
kfree(inverts);
return ERR_PTR(ret);
}
#define DEFINE_COMPARISON_PRED(type) \
static int filter_pred_LT_##type(struct filter_pred *pred, void *event) \
{ \
type *addr = (type *)(event + pred->offset); \
type val = (type)pred->val; \
return *addr < val; \
} \
static int filter_pred_LE_##type(struct filter_pred *pred, void *event) \
{ \
type *addr = (type *)(event + pred->offset); \
type val = (type)pred->val; \
return *addr <= val; \
} \
static int filter_pred_GT_##type(struct filter_pred *pred, void *event) \
{ \
type *addr = (type *)(event + pred->offset); \
type val = (type)pred->val; \
return *addr > val; \
} \
static int filter_pred_GE_##type(struct filter_pred *pred, void *event) \
{ \
type *addr = (type *)(event + pred->offset); \
type val = (type)pred->val; \
return *addr >= val; \
} \
static int filter_pred_BAND_##type(struct filter_pred *pred, void *event) \
{ \
type *addr = (type *)(event + pred->offset); \
type val = (type)pred->val; \
return !!(*addr & val); \
} \
static const filter_pred_fn_t pred_funcs_##type[] = { \
filter_pred_LE_##type, \
filter_pred_LT_##type, \
filter_pred_GE_##type, \
filter_pred_GT_##type, \
filter_pred_BAND_##type, \
};
#define DEFINE_EQUALITY_PRED(size) \
static int filter_pred_##size(struct filter_pred *pred, void *event) \
{ \
u##size *addr = (u##size *)(event + pred->offset); \
u##size val = (u##size)pred->val; \
int match; \
\
match = (val == *addr) ^ pred->not; \
\
return match; \
}
DEFINE_COMPARISON_PRED(s64);
DEFINE_COMPARISON_PRED(u64);
DEFINE_COMPARISON_PRED(s32);
DEFINE_COMPARISON_PRED(u32);
DEFINE_COMPARISON_PRED(s16);
DEFINE_COMPARISON_PRED(u16);
DEFINE_COMPARISON_PRED(s8);
DEFINE_COMPARISON_PRED(u8);
DEFINE_EQUALITY_PRED(64);
DEFINE_EQUALITY_PRED(32);
DEFINE_EQUALITY_PRED(16);
DEFINE_EQUALITY_PRED(8);
/* Filter predicate for fixed sized arrays of characters */
static int filter_pred_string(struct filter_pred *pred, void *event)
{
char *addr = (char *)(event + pred->offset);
int cmp, match;
cmp = pred->regex.match(addr, &pred->regex, pred->regex.field_len);
match = cmp ^ pred->not;
return match;
}
/* Filter predicate for char * pointers */
static int filter_pred_pchar(struct filter_pred *pred, void *event)
{
char **addr = (char **)(event + pred->offset);
int cmp, match;
int len = strlen(*addr) + 1; /* including tailing '\0' */
cmp = pred->regex.match(*addr, &pred->regex, len);
match = cmp ^ pred->not;
return match;
}
/*
* Filter predicate for dynamic sized arrays of characters.
* These are implemented through a list of strings at the end
* of the entry.
* Also each of these strings have a field in the entry which
* contains its offset from the beginning of the entry.
* We have then first to get this field, dereference it
* and add it to the address of the entry, and at last we have
* the address of the string.
*/
static int filter_pred_strloc(struct filter_pred *pred, void *event)
{
u32 str_item = *(u32 *)(event + pred->offset);
int str_loc = str_item & 0xffff;
int str_len = str_item >> 16;
char *addr = (char *)(event + str_loc);
int cmp, match;
cmp = pred->regex.match(addr, &pred->regex, str_len);
match = cmp ^ pred->not;
return match;
}
/* Filter predicate for CPUs. */
static int filter_pred_cpu(struct filter_pred *pred, void *event)
{
int cpu, cmp;
cpu = raw_smp_processor_id();
cmp = pred->val;
switch (pred->op) {
case OP_EQ:
return cpu == cmp;
case OP_NE:
return cpu != cmp;
case OP_LT:
return cpu < cmp;
case OP_LE:
return cpu <= cmp;
case OP_GT:
return cpu > cmp;
case OP_GE:
return cpu >= cmp;
default:
return 0;
}
}
/* Filter predicate for COMM. */
static int filter_pred_comm(struct filter_pred *pred, void *event)
{
int cmp;
cmp = pred->regex.match(current->comm, &pred->regex,
TASK_COMM_LEN);
return cmp ^ pred->not;
}
static int filter_pred_none(struct filter_pred *pred, void *event)
{
return 0;
}
/*
* regex_match_foo - Basic regex callbacks
*
* @str: the string to be searched
* @r: the regex structure containing the pattern string
* @len: the length of the string to be searched (including '\0')
*
* Note:
* - @str might not be NULL-terminated if it's of type DYN_STRING
* or STATIC_STRING, unless @len is zero.
*/
static int regex_match_full(char *str, struct regex *r, int len)
{
/* len of zero means str is dynamic and ends with '\0' */
if (!len)
return strcmp(str, r->pattern) == 0;
return strncmp(str, r->pattern, len) == 0;
}
static int regex_match_front(char *str, struct regex *r, int len)
{
if (len && len < r->len)
return 0;
return strncmp(str, r->pattern, r->len) == 0;
}
static int regex_match_middle(char *str, struct regex *r, int len)
{
if (!len)
return strstr(str, r->pattern) != NULL;
return strnstr(str, r->pattern, len) != NULL;
}
static int regex_match_end(char *str, struct regex *r, int len)
{
int strlen = len - 1;
if (strlen >= r->len &&
memcmp(str + strlen - r->len, r->pattern, r->len) == 0)
return 1;
return 0;
}
static int regex_match_glob(char *str, struct regex *r, int len __maybe_unused)
{
if (glob_match(r->pattern, str))
return 1;
return 0;
}
/**
* filter_parse_regex - parse a basic regex
* @buff: the raw regex
* @len: length of the regex
* @search: will point to the beginning of the string to compare
* @not: tell whether the match will have to be inverted
*
* This passes in a buffer containing a regex and this function will
* set search to point to the search part of the buffer and
* return the type of search it is (see enum above).
* This does modify buff.
*
* Returns enum type.
* search returns the pointer to use for comparison.
* not returns 1 if buff started with a '!'
* 0 otherwise.
*/
enum regex_type filter_parse_regex(char *buff, int len, char **search, int *not)
{
int type = MATCH_FULL;
int i;
if (buff[0] == '!') {
*not = 1;
buff++;
len--;
} else
*not = 0;
*search = buff;
for (i = 0; i < len; i++) {
if (buff[i] == '*') {
if (!i) {
type = MATCH_END_ONLY;
} else if (i == len - 1) {
if (type == MATCH_END_ONLY)
type = MATCH_MIDDLE_ONLY;
else
type = MATCH_FRONT_ONLY;
buff[i] = 0;
break;
} else { /* pattern continues, use full glob */
return MATCH_GLOB;
}
} else if (strchr("[?\\", buff[i])) {
return MATCH_GLOB;
}
}
if (buff[0] == '*')
*search = buff + 1;
return type;
}
static void filter_build_regex(struct filter_pred *pred)
{
struct regex *r = &pred->regex;
char *search;
enum regex_type type = MATCH_FULL;
if (pred->op == OP_GLOB) {
type = filter_parse_regex(r->pattern, r->len, &search, &pred->not);
r->len = strlen(search);
memmove(r->pattern, search, r->len+1);
}
switch (type) {
case MATCH_FULL:
r->match = regex_match_full;
break;
case MATCH_FRONT_ONLY:
r->match = regex_match_front;
break;
case MATCH_MIDDLE_ONLY:
r->match = regex_match_middle;
break;
case MATCH_END_ONLY:
r->match = regex_match_end;
break;
case MATCH_GLOB:
r->match = regex_match_glob;
break;
}
}
/* return 1 if event matches, 0 otherwise (discard) */
int filter_match_preds(struct event_filter *filter, void *rec)
{
struct prog_entry *prog;
int i;
/* no filter is considered a match */
if (!filter)
return 1;
prog = rcu_dereference_sched(filter->prog);
if (!prog)
return 1;
for (i = 0; prog[i].pred; i++) {
struct filter_pred *pred = prog[i].pred;
int match = pred->fn(pred, rec);
if (match == prog[i].when_to_branch)
i = prog[i].target;
}
return prog[i].target;
}
EXPORT_SYMBOL_GPL(filter_match_preds);
static void remove_filter_string(struct event_filter *filter)
{
if (!filter)
return;
kfree(filter->filter_string);
filter->filter_string = NULL;
}
static void append_filter_err(struct filter_parse_error *pe,
struct event_filter *filter)
{
struct trace_seq *s;
int pos = pe->lasterr_pos;
char *buf;
int len;
if (WARN_ON(!filter->filter_string))
return;
s = kmalloc(sizeof(*s), GFP_KERNEL);
if (!s)
return;
trace_seq_init(s);
len = strlen(filter->filter_string);
if (pos > len)
pos = len;
/* indexing is off by one */
if (pos)
pos++;
trace_seq_puts(s, filter->filter_string);
if (pe->lasterr > 0) {
trace_seq_printf(s, "\n%*s", pos, "^");
trace_seq_printf(s, "\nparse_error: %s\n", err_text[pe->lasterr]);
} else {
trace_seq_printf(s, "\nError: (%d)\n", pe->lasterr);
}
trace_seq_putc(s, 0);
buf = kmemdup_nul(s->buffer, s->seq.len, GFP_KERNEL);
if (buf) {
kfree(filter->filter_string);
filter->filter_string = buf;
}
kfree(s);
}
static inline struct event_filter *event_filter(struct trace_event_file *file)
{
return file->filter;
}
/* caller must hold event_mutex */
void print_event_filter(struct trace_event_file *file, struct trace_seq *s)
{
struct event_filter *filter = event_filter(file);
if (filter && filter->filter_string)
trace_seq_printf(s, "%s\n", filter->filter_string);
else
trace_seq_puts(s, "none\n");
}
void print_subsystem_event_filter(struct event_subsystem *system,
struct trace_seq *s)
{
struct event_filter *filter;
mutex_lock(&event_mutex);
filter = system->filter;
if (filter && filter->filter_string)
trace_seq_printf(s, "%s\n", filter->filter_string);
else
trace_seq_puts(s, DEFAULT_SYS_FILTER_MESSAGE "\n");
mutex_unlock(&event_mutex);
}
static void free_prog(struct event_filter *filter)
{
struct prog_entry *prog;
int i;
prog = rcu_access_pointer(filter->prog);
if (!prog)
return;
for (i = 0; prog[i].pred; i++)
kfree(prog[i].pred);
kfree(prog);
}
static void filter_disable(struct trace_event_file *file)
{
unsigned long old_flags = file->flags;
file->flags &= ~EVENT_FILE_FL_FILTERED;
if (old_flags != file->flags)
trace_buffered_event_disable();
}
static void __free_filter(struct event_filter *filter)
{
if (!filter)
return;
free_prog(filter);
kfree(filter->filter_string);
kfree(filter);
}
void free_event_filter(struct event_filter *filter)
{
__free_filter(filter);
}
static inline void __remove_filter(struct trace_event_file *file)
{
filter_disable(file);
remove_filter_string(file->filter);
}
static void filter_free_subsystem_preds(struct trace_subsystem_dir *dir,
struct trace_array *tr)
{
struct trace_event_file *file;
list_for_each_entry(file, &tr->events, list) {
if (file->system != dir)
continue;
__remove_filter(file);
}
}
static inline void __free_subsystem_filter(struct trace_event_file *file)
{
__free_filter(file->filter);
file->filter = NULL;
}
static void filter_free_subsystem_filters(struct trace_subsystem_dir *dir,
struct trace_array *tr)
{
struct trace_event_file *file;
list_for_each_entry(file, &tr->events, list) {
if (file->system != dir)
continue;
__free_subsystem_filter(file);
}
}
int filter_assign_type(const char *type)
{
if (strstr(type, "__data_loc") && strstr(type, "char"))
return FILTER_DYN_STRING;
if (strchr(type, '[') && strstr(type, "char"))
return FILTER_STATIC_STRING;
return FILTER_OTHER;
}
static filter_pred_fn_t select_comparison_fn(enum filter_op_ids op,
int field_size, int field_is_signed)
{
filter_pred_fn_t fn = NULL;
int pred_func_index = -1;
switch (op) {
case OP_EQ:
case OP_NE:
break;
default:
if (WARN_ON_ONCE(op < PRED_FUNC_START))
return NULL;
pred_func_index = op - PRED_FUNC_START;
if (WARN_ON_ONCE(pred_func_index > PRED_FUNC_MAX))
return NULL;
}
switch (field_size) {
case 8:
if (pred_func_index < 0)
fn = filter_pred_64;
else if (field_is_signed)
fn = pred_funcs_s64[pred_func_index];
else
fn = pred_funcs_u64[pred_func_index];
break;
case 4:
if (pred_func_index < 0)
fn = filter_pred_32;
else if (field_is_signed)
fn = pred_funcs_s32[pred_func_index];
else
fn = pred_funcs_u32[pred_func_index];
break;
case 2:
if (pred_func_index < 0)
fn = filter_pred_16;
else if (field_is_signed)
fn = pred_funcs_s16[pred_func_index];
else
fn = pred_funcs_u16[pred_func_index];
break;
case 1:
if (pred_func_index < 0)
fn = filter_pred_8;
else if (field_is_signed)
fn = pred_funcs_s8[pred_func_index];
else
fn = pred_funcs_u8[pred_func_index];
break;
}
return fn;
}
/* Called when a predicate is encountered by predicate_parse() */
static int parse_pred(const char *str, void *data,
int pos, struct filter_parse_error *pe,
struct filter_pred **pred_ptr)
{
struct trace_event_call *call = data;
struct ftrace_event_field *field;
struct filter_pred *pred = NULL;
char num_buf[24]; /* Big enough to hold an address */
char *field_name;
char q;
u64 val;
int len;
int ret;
int op;
int s;
int i = 0;
/* First find the field to associate to */
while (isspace(str[i]))
i++;
s = i;
while (isalnum(str[i]) || str[i] == '_')
i++;
len = i - s;
if (!len)
return -1;
field_name = kmemdup_nul(str + s, len, GFP_KERNEL);
if (!field_name)
return -ENOMEM;
/* Make sure that the field exists */
field = trace_find_event_field(call, field_name);
kfree(field_name);
if (!field) {
parse_error(pe, FILT_ERR_FIELD_NOT_FOUND, pos + i);
return -EINVAL;
}
while (isspace(str[i]))
i++;
/* Make sure this op is supported */
for (op = 0; ops[op]; op++) {
/* This is why '<=' must come before '<' in ops[] */
if (strncmp(str + i, ops[op], strlen(ops[op])) == 0)
break;
}
if (!ops[op]) {
parse_error(pe, FILT_ERR_INVALID_OP, pos + i);
goto err_free;
}
i += strlen(ops[op]);
while (isspace(str[i]))
i++;
s = i;
pred = kzalloc(sizeof(*pred), GFP_KERNEL);
if (!pred)
return -ENOMEM;
pred->field = field;
pred->offset = field->offset;
pred->op = op;
if (ftrace_event_is_function(call)) {
/*
* Perf does things different with function events.
* It only allows an "ip" field, and expects a string.
* But the string does not need to be surrounded by quotes.
* If it is a string, the assigned function as a nop,
* (perf doesn't use it) and grab everything.
*/
if (strcmp(field->name, "ip") != 0) {
parse_error(pe, FILT_ERR_IP_FIELD_ONLY, pos + i);
goto err_free;
}
pred->fn = filter_pred_none;
/*
* Quotes are not required, but if they exist then we need
* to read them till we hit a matching one.
*/
if (str[i] == '\'' || str[i] == '"')
q = str[i];
else
q = 0;
for (i++; str[i]; i++) {
if (q && str[i] == q)
break;
if (!q && (str[i] == ')' || str[i] == '&' ||
str[i] == '|'))
break;
}
/* Skip quotes */
if (q)
s++;
len = i - s;
if (len >= MAX_FILTER_STR_VAL) {
parse_error(pe, FILT_ERR_OPERAND_TOO_LONG, pos + i);
goto err_free;
}
pred->regex.len = len;
strncpy(pred->regex.pattern, str + s, len);
pred->regex.pattern[len] = 0;
/* This is either a string, or an integer */
} else if (str[i] == '\'' || str[i] == '"') {
char q = str[i];
/* Make sure the op is OK for strings */
switch (op) {
case OP_NE:
pred->not = 1;
/* Fall through */
case OP_GLOB:
case OP_EQ:
break;
default:
parse_error(pe, FILT_ERR_ILLEGAL_FIELD_OP, pos + i);
goto err_free;
}
/* Make sure the field is OK for strings */
if (!is_string_field(field)) {
parse_error(pe, FILT_ERR_EXPECT_DIGIT, pos + i);
goto err_free;
}
for (i++; str[i]; i++) {
if (str[i] == q)
break;
}
if (!str[i]) {
parse_error(pe, FILT_ERR_MISSING_QUOTE, pos + i);
goto err_free;
}
/* Skip quotes */
s++;
len = i - s;
if (len >= MAX_FILTER_STR_VAL) {
parse_error(pe, FILT_ERR_OPERAND_TOO_LONG, pos + i);
goto err_free;
}
pred->regex.len = len;
strncpy(pred->regex.pattern, str + s, len);
pred->regex.pattern[len] = 0;
filter_build_regex(pred);
if (field->filter_type == FILTER_COMM) {
pred->fn = filter_pred_comm;
} else if (field->filter_type == FILTER_STATIC_STRING) {
pred->fn = filter_pred_string;
pred->regex.field_len = field->size;
} else if (field->filter_type == FILTER_DYN_STRING)
pred->fn = filter_pred_strloc;
else
pred->fn = filter_pred_pchar;
/* go past the last quote */
i++;
} else if (isdigit(str[i])) {
/* Make sure the field is not a string */
if (is_string_field(field)) {
parse_error(pe, FILT_ERR_EXPECT_STRING, pos + i);
goto err_free;
}
if (op == OP_GLOB) {
parse_error(pe, FILT_ERR_ILLEGAL_FIELD_OP, pos + i);
goto err_free;
}
/* We allow 0xDEADBEEF */
while (isalnum(str[i]))
i++;
len = i - s;
/* 0xfeedfacedeadbeef is 18 chars max */
if (len >= sizeof(num_buf)) {
parse_error(pe, FILT_ERR_OPERAND_TOO_LONG, pos + i);
goto err_free;
}
strncpy(num_buf, str + s, len);
num_buf[len] = 0;
/* Make sure it is a value */
if (field->is_signed)
ret = kstrtoll(num_buf, 0, &val);
else
ret = kstrtoull(num_buf, 0, &val);
if (ret) {
parse_error(pe, FILT_ERR_ILLEGAL_INTVAL, pos + s);
goto err_free;
}
pred->val = val;
if (field->filter_type == FILTER_CPU)
pred->fn = filter_pred_cpu;
else {
pred->fn = select_comparison_fn(pred->op, field->size,
field->is_signed);
if (pred->op == OP_NE)
pred->not = 1;
}
} else {
parse_error(pe, FILT_ERR_INVALID_VALUE, pos + i);
goto err_free;
}
*pred_ptr = pred;
return i;
err_free:
kfree(pred);
return -EINVAL;
}
enum {
TOO_MANY_CLOSE = -1,
TOO_MANY_OPEN = -2,
MISSING_QUOTE = -3,
};
/*
* Read the filter string once to calculate the number of predicates
* as well as how deep the parentheses go.
*
* Returns:
* 0 - everything is fine (err is undefined)
* -1 - too many ')'
* -2 - too many '('
* -3 - No matching quote
*/
static int calc_stack(const char *str, int *parens, int *preds, int *err)
{
bool is_pred = false;
int nr_preds = 0;
int open = 1; /* Count the expression as "(E)" */
int last_quote = 0;
int max_open = 1;
int quote = 0;
int i;
*err = 0;
for (i = 0; str[i]; i++) {
if (isspace(str[i]))
continue;
if (quote) {
if (str[i] == quote)
quote = 0;
continue;
}
switch (str[i]) {
case '\'':
case '"':
quote = str[i];
last_quote = i;
break;
case '|':
case '&':
if (str[i+1] != str[i])
break;
is_pred = false;
continue;
case '(':
is_pred = false;
open++;
if (open > max_open)
max_open = open;
continue;
case ')':
is_pred = false;
if (open == 1) {
*err = i;
return TOO_MANY_CLOSE;
}
open--;
continue;
}
if (!is_pred) {
nr_preds++;
is_pred = true;
}
}
if (quote) {
*err = last_quote;
return MISSING_QUOTE;
}
if (open != 1) {
int level = open;
/* find the bad open */
for (i--; i; i--) {
if (quote) {
if (str[i] == quote)
quote = 0;
continue;
}
switch (str[i]) {
case '(':
if (level == open) {
*err = i;
return TOO_MANY_OPEN;
}
level--;
break;
case ')':
level++;
break;
case '\'':
case '"':
quote = str[i];
break;
}
}
/* First character is the '(' with missing ')' */
*err = 0;
return TOO_MANY_OPEN;
}
/* Set the size of the required stacks */
*parens = max_open;
*preds = nr_preds;
return 0;
}
static int process_preds(struct trace_event_call *call,
const char *filter_string,
struct event_filter *filter,
struct filter_parse_error *pe)
{
struct prog_entry *prog;
int nr_parens;
int nr_preds;
int index;
int ret;
ret = calc_stack(filter_string, &nr_parens, &nr_preds, &index);
if (ret < 0) {
switch (ret) {
case MISSING_QUOTE:
parse_error(pe, FILT_ERR_MISSING_QUOTE, index);
break;
case TOO_MANY_OPEN:
parse_error(pe, FILT_ERR_TOO_MANY_OPEN, index);
break;
default:
parse_error(pe, FILT_ERR_TOO_MANY_CLOSE, index);
}
return ret;
}
if (!nr_preds)
return -EINVAL;
prog = predicate_parse(filter_string, nr_parens, nr_preds,
parse_pred, call, pe);
if (IS_ERR(prog))
return PTR_ERR(prog);
rcu_assign_pointer(filter->prog, prog);
return 0;
}
static inline void event_set_filtered_flag(struct trace_event_file *file)
{
unsigned long old_flags = file->flags;
file->flags |= EVENT_FILE_FL_FILTERED;
if (old_flags != file->flags)
trace_buffered_event_enable();
}
static inline void event_set_filter(struct trace_event_file *file,
struct event_filter *filter)
{
rcu_assign_pointer(file->filter, filter);
}
static inline void event_clear_filter(struct trace_event_file *file)
{
RCU_INIT_POINTER(file->filter, NULL);
}
static inline void
event_set_no_set_filter_flag(struct trace_event_file *file)
{
file->flags |= EVENT_FILE_FL_NO_SET_FILTER;
}
static inline void
event_clear_no_set_filter_flag(struct trace_event_file *file)
{
file->flags &= ~EVENT_FILE_FL_NO_SET_FILTER;
}
static inline bool
event_no_set_filter_flag(struct trace_event_file *file)
{
if (file->flags & EVENT_FILE_FL_NO_SET_FILTER)
return true;
return false;
}
struct filter_list {
struct list_head list;
struct event_filter *filter;
};
static int process_system_preds(struct trace_subsystem_dir *dir,
struct trace_array *tr,
struct filter_parse_error *pe,
char *filter_string)
{
struct trace_event_file *file;
struct filter_list *filter_item;
struct event_filter *filter = NULL;
struct filter_list *tmp;
LIST_HEAD(filter_list);
bool fail = true;
int err;
list_for_each_entry(file, &tr->events, list) {
if (file->system != dir)
continue;
filter = kzalloc(sizeof(*filter), GFP_KERNEL);
if (!filter)
goto fail_mem;
filter->filter_string = kstrdup(filter_string, GFP_KERNEL);
if (!filter->filter_string)
goto fail_mem;
err = process_preds(file->event_call, filter_string, filter, pe);
if (err) {
filter_disable(file);
parse_error(pe, FILT_ERR_BAD_SUBSYS_FILTER, 0);
append_filter_err(pe, filter);
} else
event_set_filtered_flag(file);
filter_item = kzalloc(sizeof(*filter_item), GFP_KERNEL);
if (!filter_item)
goto fail_mem;
list_add_tail(&filter_item->list, &filter_list);
/*
* Regardless of if this returned an error, we still
* replace the filter for the call.
*/
filter_item->filter = event_filter(file);
event_set_filter(file, filter);
filter = NULL;
fail = false;
}
if (fail)
goto fail;
/*
* The calls can still be using the old filters.
* Do a synchronize_sched() to ensure all calls are
* done with them before we free them.
*/
synchronize_sched();
list_for_each_entry_safe(filter_item, tmp, &filter_list, list) {
__free_filter(filter_item->filter);
list_del(&filter_item->list);
kfree(filter_item);
}
return 0;
fail:
/* No call succeeded */
list_for_each_entry_safe(filter_item, tmp, &filter_list, list) {
list_del(&filter_item->list);
kfree(filter_item);
}
parse_error(pe, FILT_ERR_BAD_SUBSYS_FILTER, 0);
return -EINVAL;
fail_mem:
kfree(filter);
/* If any call succeeded, we still need to sync */
if (!fail)
synchronize_sched();
list_for_each_entry_safe(filter_item, tmp, &filter_list, list) {
__free_filter(filter_item->filter);
list_del(&filter_item->list);
kfree(filter_item);
}
return -ENOMEM;
}
static int create_filter_start(char *filter_string, bool set_str,
struct filter_parse_error **pse,
struct event_filter **filterp)
{
struct event_filter *filter;
struct filter_parse_error *pe = NULL;
int err = 0;
if (WARN_ON_ONCE(*pse || *filterp))
return -EINVAL;
filter = kzalloc(sizeof(*filter), GFP_KERNEL);
if (filter && set_str) {
filter->filter_string = kstrdup(filter_string, GFP_KERNEL);
if (!filter->filter_string)
err = -ENOMEM;
}
pe = kzalloc(sizeof(*pe), GFP_KERNEL);
if (!filter || !pe || err) {
kfree(pe);
__free_filter(filter);
return -ENOMEM;
}
/* we're committed to creating a new filter */
*filterp = filter;
*pse = pe;
return 0;
}
static void create_filter_finish(struct filter_parse_error *pe)
{
kfree(pe);
}
/**
* create_filter - create a filter for a trace_event_call
* @call: trace_event_call to create a filter for
* @filter_str: filter string
* @set_str: remember @filter_str and enable detailed error in filter
* @filterp: out param for created filter (always updated on return)
*
* Creates a filter for @call with @filter_str. If @set_str is %true,
* @filter_str is copied and recorded in the new filter.
*
* On success, returns 0 and *@filterp points to the new filter. On
* failure, returns -errno and *@filterp may point to %NULL or to a new
* filter. In the latter case, the returned filter contains error
* information if @set_str is %true and the caller is responsible for
* freeing it.
*/
static int create_filter(struct trace_event_call *call,
char *filter_string, bool set_str,
struct event_filter **filterp)
{
struct filter_parse_error *pe = NULL;
int err;
err = create_filter_start(filter_string, set_str, &pe, filterp);
if (err)
return err;
err = process_preds(call, filter_string, *filterp, pe);
if (err && set_str)
append_filter_err(pe, *filterp);
return err;
}
int create_event_filter(struct trace_event_call *call,
char *filter_str, bool set_str,
struct event_filter **filterp)
{
return create_filter(call, filter_str, set_str, filterp);
}
/**
* create_system_filter - create a filter for an event_subsystem
* @system: event_subsystem to create a filter for
* @filter_str: filter string
* @filterp: out param for created filter (always updated on return)
*
* Identical to create_filter() except that it creates a subsystem filter
* and always remembers @filter_str.
*/
static int create_system_filter(struct trace_subsystem_dir *dir,
struct trace_array *tr,
char *filter_str, struct event_filter **filterp)
{
struct filter_parse_error *pe = NULL;
int err;
err = create_filter_start(filter_str, true, &pe, filterp);
if (!err) {
err = process_system_preds(dir, tr, pe, filter_str);
if (!err) {
/* System filters just show a default message */
kfree((*filterp)->filter_string);
(*filterp)->filter_string = NULL;
} else {
append_filter_err(pe, *filterp);
}
}
create_filter_finish(pe);
return err;
}
/* caller must hold event_mutex */
int apply_event_filter(struct trace_event_file *file, char *filter_string)
{
struct trace_event_call *call = file->event_call;
struct event_filter *filter = NULL;
int err;
if (!strcmp(strstrip(filter_string), "0")) {
filter_disable(file);
filter = event_filter(file);
if (!filter)
return 0;
event_clear_filter(file);
/* Make sure the filter is not being used */
synchronize_sched();
__free_filter(filter);
return 0;
}
err = create_filter(call, filter_string, true, &filter);
/*
* Always swap the call filter with the new filter
* even if there was an error. If there was an error
* in the filter, we disable the filter and show the error
* string
*/
if (filter) {
struct event_filter *tmp;
tmp = event_filter(file);
if (!err)
event_set_filtered_flag(file);
else
filter_disable(file);
event_set_filter(file, filter);
if (tmp) {
/* Make sure the call is done with the filter */
synchronize_sched();
__free_filter(tmp);
}
}
return err;
}
int apply_subsystem_event_filter(struct trace_subsystem_dir *dir,
char *filter_string)
{
struct event_subsystem *system = dir->subsystem;
struct trace_array *tr = dir->tr;
struct event_filter *filter = NULL;
int err = 0;
mutex_lock(&event_mutex);
/* Make sure the system still has events */
if (!dir->nr_events) {
err = -ENODEV;
goto out_unlock;
}
if (!strcmp(strstrip(filter_string), "0")) {
filter_free_subsystem_preds(dir, tr);
remove_filter_string(system->filter);
filter = system->filter;
system->filter = NULL;
/* Ensure all filters are no longer used */
synchronize_sched();
filter_free_subsystem_filters(dir, tr);
__free_filter(filter);
goto out_unlock;
}
err = create_system_filter(dir, tr, filter_string, &filter);
if (filter) {
/*
* No event actually uses the system filter
* we can free it without synchronize_sched().
*/
__free_filter(system->filter);
system->filter = filter;
}
out_unlock:
mutex_unlock(&event_mutex);
return err;
}
#ifdef CONFIG_PERF_EVENTS
void ftrace_profile_free_filter(struct perf_event *event)
{
struct event_filter *filter = event->filter;
event->filter = NULL;
__free_filter(filter);
}
struct function_filter_data {
struct ftrace_ops *ops;
int first_filter;
int first_notrace;
};
#ifdef CONFIG_FUNCTION_TRACER
static char **
ftrace_function_filter_re(char *buf, int len, int *count)
{
char *str, **re;
str = kstrndup(buf, len, GFP_KERNEL);
if (!str)
return NULL;
/*
* The argv_split function takes white space
* as a separator, so convert ',' into spaces.
*/
strreplace(str, ',', ' ');
re = argv_split(GFP_KERNEL, str, count);
kfree(str);
return re;
}
static int ftrace_function_set_regexp(struct ftrace_ops *ops, int filter,
int reset, char *re, int len)
{
int ret;
if (filter)
ret = ftrace_set_filter(ops, re, len, reset);
else
ret = ftrace_set_notrace(ops, re, len, reset);
return ret;
}
static int __ftrace_function_set_filter(int filter, char *buf, int len,
struct function_filter_data *data)
{
int i, re_cnt, ret = -EINVAL;
int *reset;
char **re;
reset = filter ? &data->first_filter : &data->first_notrace;
/*
* The 'ip' field could have multiple filters set, separated
* either by space or comma. We first cut the filter and apply
* all pieces separatelly.
*/
re = ftrace_function_filter_re(buf, len, &re_cnt);
if (!re)
return -EINVAL;
for (i = 0; i < re_cnt; i++) {
ret = ftrace_function_set_regexp(data->ops, filter, *reset,
re[i], strlen(re[i]));
if (ret)
break;
if (*reset)
*reset = 0;
}
argv_free(re);
return ret;
}
static int ftrace_function_check_pred(struct filter_pred *pred)
{
struct ftrace_event_field *field = pred->field;
/*
* Check the predicate for function trace, verify:
* - only '==' and '!=' is used
* - the 'ip' field is used
*/
if ((pred->op != OP_EQ) && (pred->op != OP_NE))
return -EINVAL;
if (strcmp(field->name, "ip"))
return -EINVAL;
return 0;
}
static int ftrace_function_set_filter_pred(struct filter_pred *pred,
struct function_filter_data *data)
{
int ret;
/* Checking the node is valid for function trace. */
ret = ftrace_function_check_pred(pred);
if (ret)
return ret;
return __ftrace_function_set_filter(pred->op == OP_EQ,
pred->regex.pattern,
pred->regex.len,
data);
}
static bool is_or(struct prog_entry *prog, int i)
{
int target;
/*
* Only "||" is allowed for function events, thus,
* all true branches should jump to true, and any
* false branch should jump to false.
*/
target = prog[i].target + 1;
/* True and false have NULL preds (all prog entries should jump to one */
if (prog[target].pred)
return false;
/* prog[target].target is 1 for TRUE, 0 for FALSE */
return prog[i].when_to_branch == prog[target].target;
}
static int ftrace_function_set_filter(struct perf_event *event,
struct event_filter *filter)
{
struct prog_entry *prog = rcu_dereference_protected(filter->prog,
lockdep_is_held(&event_mutex));
struct function_filter_data data = {
.first_filter = 1,
.first_notrace = 1,
.ops = &event->ftrace_ops,
};
int i;
for (i = 0; prog[i].pred; i++) {
struct filter_pred *pred = prog[i].pred;
if (!is_or(prog, i))
return -EINVAL;
if (ftrace_function_set_filter_pred(pred, &data) < 0)
return -EINVAL;
}
return 0;
}
#else
static int ftrace_function_set_filter(struct perf_event *event,
struct event_filter *filter)
{
return -ENODEV;
}
#endif /* CONFIG_FUNCTION_TRACER */
int ftrace_profile_set_filter(struct perf_event *event, int event_id,
char *filter_str)
{
int err;
struct event_filter *filter = NULL;
struct trace_event_call *call;
mutex_lock(&event_mutex);
call = event->tp_event;
err = -EINVAL;
if (!call)
goto out_unlock;
err = -EEXIST;
if (event->filter)
goto out_unlock;
err = create_filter(call, filter_str, false, &filter);
if (err)
goto free_filter;
if (ftrace_event_is_function(call))
err = ftrace_function_set_filter(event, filter);
else
event->filter = filter;
free_filter:
if (err || ftrace_event_is_function(call))
__free_filter(filter);
out_unlock:
mutex_unlock(&event_mutex);
return err;
}
#endif /* CONFIG_PERF_EVENTS */
#ifdef CONFIG_FTRACE_STARTUP_TEST
#include <linux/types.h>
#include <linux/tracepoint.h>
#define CREATE_TRACE_POINTS
#include "trace_events_filter_test.h"
#define DATA_REC(m, va, vb, vc, vd, ve, vf, vg, vh, nvisit) \
{ \
.filter = FILTER, \
.rec = { .a = va, .b = vb, .c = vc, .d = vd, \
.e = ve, .f = vf, .g = vg, .h = vh }, \
.match = m, \
.not_visited = nvisit, \
}
#define YES 1
#define NO 0
static struct test_filter_data_t {
char *filter;
struct trace_event_raw_ftrace_test_filter rec;
int match;
char *not_visited;
} test_filter_data[] = {
#define FILTER "a == 1 && b == 1 && c == 1 && d == 1 && " \
"e == 1 && f == 1 && g == 1 && h == 1"
DATA_REC(YES, 1, 1, 1, 1, 1, 1, 1, 1, ""),
DATA_REC(NO, 0, 1, 1, 1, 1, 1, 1, 1, "bcdefgh"),
DATA_REC(NO, 1, 1, 1, 1, 1, 1, 1, 0, ""),
#undef FILTER
#define FILTER "a == 1 || b == 1 || c == 1 || d == 1 || " \
"e == 1 || f == 1 || g == 1 || h == 1"
DATA_REC(NO, 0, 0, 0, 0, 0, 0, 0, 0, ""),
DATA_REC(YES, 0, 0, 0, 0, 0, 0, 0, 1, ""),
DATA_REC(YES, 1, 0, 0, 0, 0, 0, 0, 0, "bcdefgh"),
#undef FILTER
#define FILTER "(a == 1 || b == 1) && (c == 1 || d == 1) && " \
"(e == 1 || f == 1) && (g == 1 || h == 1)"
DATA_REC(NO, 0, 0, 1, 1, 1, 1, 1, 1, "dfh"),
DATA_REC(YES, 0, 1, 0, 1, 0, 1, 0, 1, ""),
DATA_REC(YES, 1, 0, 1, 0, 0, 1, 0, 1, "bd"),
DATA_REC(NO, 1, 0, 1, 0, 0, 1, 0, 0, "bd"),
#undef FILTER
#define FILTER "(a == 1 && b == 1) || (c == 1 && d == 1) || " \
"(e == 1 && f == 1) || (g == 1 && h == 1)"
DATA_REC(YES, 1, 0, 1, 1, 1, 1, 1, 1, "efgh"),
DATA_REC(YES, 0, 0, 0, 0, 0, 0, 1, 1, ""),
DATA_REC(NO, 0, 0, 0, 0, 0, 0, 0, 1, ""),
#undef FILTER
#define FILTER "(a == 1 && b == 1) && (c == 1 && d == 1) && " \
"(e == 1 && f == 1) || (g == 1 && h == 1)"
DATA_REC(YES, 1, 1, 1, 1, 1, 1, 0, 0, "gh"),
DATA_REC(NO, 0, 0, 0, 0, 0, 0, 0, 1, ""),
DATA_REC(YES, 1, 1, 1, 1, 1, 0, 1, 1, ""),
#undef FILTER
#define FILTER "((a == 1 || b == 1) || (c == 1 || d == 1) || " \
"(e == 1 || f == 1)) && (g == 1 || h == 1)"
DATA_REC(YES, 1, 1, 1, 1, 1, 1, 0, 1, "bcdef"),
DATA_REC(NO, 0, 0, 0, 0, 0, 0, 0, 0, ""),
DATA_REC(YES, 1, 1, 1, 1, 1, 0, 1, 1, "h"),
#undef FILTER
#define FILTER "((((((((a == 1) && (b == 1)) || (c == 1)) && (d == 1)) || " \
"(e == 1)) && (f == 1)) || (g == 1)) && (h == 1))"
DATA_REC(YES, 1, 1, 1, 1, 1, 1, 1, 1, "ceg"),
DATA_REC(NO, 0, 1, 0, 1, 0, 1, 0, 1, ""),
DATA_REC(NO, 1, 0, 1, 0, 1, 0, 1, 0, ""),
#undef FILTER
#define FILTER "((((((((a == 1) || (b == 1)) && (c == 1)) || (d == 1)) && " \
"(e == 1)) || (f == 1)) && (g == 1)) || (h == 1))"
DATA_REC(YES, 1, 1, 1, 1, 1, 1, 1, 1, "bdfh"),
DATA_REC(YES, 0, 1, 0, 1, 0, 1, 0, 1, ""),
DATA_REC(YES, 1, 0, 1, 0, 1, 0, 1, 0, "bdfh"),
};
#undef DATA_REC
#undef FILTER
#undef YES
#undef NO
#define DATA_CNT ARRAY_SIZE(test_filter_data)
static int test_pred_visited;
static int test_pred_visited_fn(struct filter_pred *pred, void *event)
{
struct ftrace_event_field *field = pred->field;
test_pred_visited = 1;
printk(KERN_INFO "\npred visited %s\n", field->name);
return 1;
}
static void update_pred_fn(struct event_filter *filter, char *fields)
{
struct prog_entry *prog = rcu_dereference_protected(filter->prog,
lockdep_is_held(&event_mutex));
int i;
for (i = 0; prog[i].pred; i++) {
struct filter_pred *pred = prog[i].pred;
struct ftrace_event_field *field = pred->field;
WARN_ON_ONCE(!pred->fn);
if (!field) {
WARN_ONCE(1, "all leafs should have field defined %d", i);
continue;
}
if (!strchr(fields, *field->name))
continue;
pred->fn = test_pred_visited_fn;
}
}
static __init int ftrace_test_event_filter(void)
{
int i;
printk(KERN_INFO "Testing ftrace filter: ");
for (i = 0; i < DATA_CNT; i++) {
struct event_filter *filter = NULL;
struct test_filter_data_t *d = &test_filter_data[i];
int err;
err = create_filter(&event_ftrace_test_filter, d->filter,
false, &filter);
if (err) {
printk(KERN_INFO
"Failed to get filter for '%s', err %d\n",
d->filter, err);
__free_filter(filter);
break;
}
/* Needed to dereference filter->prog */
mutex_lock(&event_mutex);
/*
* The preemption disabling is not really needed for self
* tests, but the rcu dereference will complain without it.
*/
preempt_disable();
if (*d->not_visited)
update_pred_fn(filter, d->not_visited);
test_pred_visited = 0;
err = filter_match_preds(filter, &d->rec);
preempt_enable();
mutex_unlock(&event_mutex);
__free_filter(filter);
if (test_pred_visited) {
printk(KERN_INFO
"Failed, unwanted pred visited for filter %s\n",
d->filter);
break;
}
if (err != d->match) {
printk(KERN_INFO
"Failed to match filter '%s', expected %d\n",
d->filter, d->match);
break;
}
}
if (i == DATA_CNT)
printk(KERN_CONT "OK\n");
return 0;
}
late_initcall(ftrace_test_event_filter);
#endif /* CONFIG_FTRACE_STARTUP_TEST */
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_205_3 |
crossvul-cpp_data_bad_1288_0 | /**
* @file parser.c
* @author Radek Krejci <rkrejci@cesnet.cz>
* @brief common libyang parsers routines implementations
*
* Copyright (c) 2015-2017 CESNET, z.s.p.o.
*
* This source code is licensed under BSD 3-Clause License (the "License").
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*/
#define _GNU_SOURCE
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <pcre.h>
#include <time.h>
#include "common.h"
#include "context.h"
#include "libyang.h"
#include "parser.h"
#include "resolve.h"
#include "tree_internal.h"
#include "parser_yang.h"
#include "xpath.h"
#define LYP_URANGE_LEN 19
static char *lyp_ublock2urange[][2] = {
{"BasicLatin", "[\\x{0000}-\\x{007F}]"},
{"Latin-1Supplement", "[\\x{0080}-\\x{00FF}]"},
{"LatinExtended-A", "[\\x{0100}-\\x{017F}]"},
{"LatinExtended-B", "[\\x{0180}-\\x{024F}]"},
{"IPAExtensions", "[\\x{0250}-\\x{02AF}]"},
{"SpacingModifierLetters", "[\\x{02B0}-\\x{02FF}]"},
{"CombiningDiacriticalMarks", "[\\x{0300}-\\x{036F}]"},
{"Greek", "[\\x{0370}-\\x{03FF}]"},
{"Cyrillic", "[\\x{0400}-\\x{04FF}]"},
{"Armenian", "[\\x{0530}-\\x{058F}]"},
{"Hebrew", "[\\x{0590}-\\x{05FF}]"},
{"Arabic", "[\\x{0600}-\\x{06FF}]"},
{"Syriac", "[\\x{0700}-\\x{074F}]"},
{"Thaana", "[\\x{0780}-\\x{07BF}]"},
{"Devanagari", "[\\x{0900}-\\x{097F}]"},
{"Bengali", "[\\x{0980}-\\x{09FF}]"},
{"Gurmukhi", "[\\x{0A00}-\\x{0A7F}]"},
{"Gujarati", "[\\x{0A80}-\\x{0AFF}]"},
{"Oriya", "[\\x{0B00}-\\x{0B7F}]"},
{"Tamil", "[\\x{0B80}-\\x{0BFF}]"},
{"Telugu", "[\\x{0C00}-\\x{0C7F}]"},
{"Kannada", "[\\x{0C80}-\\x{0CFF}]"},
{"Malayalam", "[\\x{0D00}-\\x{0D7F}]"},
{"Sinhala", "[\\x{0D80}-\\x{0DFF}]"},
{"Thai", "[\\x{0E00}-\\x{0E7F}]"},
{"Lao", "[\\x{0E80}-\\x{0EFF}]"},
{"Tibetan", "[\\x{0F00}-\\x{0FFF}]"},
{"Myanmar", "[\\x{1000}-\\x{109F}]"},
{"Georgian", "[\\x{10A0}-\\x{10FF}]"},
{"HangulJamo", "[\\x{1100}-\\x{11FF}]"},
{"Ethiopic", "[\\x{1200}-\\x{137F}]"},
{"Cherokee", "[\\x{13A0}-\\x{13FF}]"},
{"UnifiedCanadianAboriginalSyllabics", "[\\x{1400}-\\x{167F}]"},
{"Ogham", "[\\x{1680}-\\x{169F}]"},
{"Runic", "[\\x{16A0}-\\x{16FF}]"},
{"Khmer", "[\\x{1780}-\\x{17FF}]"},
{"Mongolian", "[\\x{1800}-\\x{18AF}]"},
{"LatinExtendedAdditional", "[\\x{1E00}-\\x{1EFF}]"},
{"GreekExtended", "[\\x{1F00}-\\x{1FFF}]"},
{"GeneralPunctuation", "[\\x{2000}-\\x{206F}]"},
{"SuperscriptsandSubscripts", "[\\x{2070}-\\x{209F}]"},
{"CurrencySymbols", "[\\x{20A0}-\\x{20CF}]"},
{"CombiningMarksforSymbols", "[\\x{20D0}-\\x{20FF}]"},
{"LetterlikeSymbols", "[\\x{2100}-\\x{214F}]"},
{"NumberForms", "[\\x{2150}-\\x{218F}]"},
{"Arrows", "[\\x{2190}-\\x{21FF}]"},
{"MathematicalOperators", "[\\x{2200}-\\x{22FF}]"},
{"MiscellaneousTechnical", "[\\x{2300}-\\x{23FF}]"},
{"ControlPictures", "[\\x{2400}-\\x{243F}]"},
{"OpticalCharacterRecognition", "[\\x{2440}-\\x{245F}]"},
{"EnclosedAlphanumerics", "[\\x{2460}-\\x{24FF}]"},
{"BoxDrawing", "[\\x{2500}-\\x{257F}]"},
{"BlockElements", "[\\x{2580}-\\x{259F}]"},
{"GeometricShapes", "[\\x{25A0}-\\x{25FF}]"},
{"MiscellaneousSymbols", "[\\x{2600}-\\x{26FF}]"},
{"Dingbats", "[\\x{2700}-\\x{27BF}]"},
{"BraillePatterns", "[\\x{2800}-\\x{28FF}]"},
{"CJKRadicalsSupplement", "[\\x{2E80}-\\x{2EFF}]"},
{"KangxiRadicals", "[\\x{2F00}-\\x{2FDF}]"},
{"IdeographicDescriptionCharacters", "[\\x{2FF0}-\\x{2FFF}]"},
{"CJKSymbolsandPunctuation", "[\\x{3000}-\\x{303F}]"},
{"Hiragana", "[\\x{3040}-\\x{309F}]"},
{"Katakana", "[\\x{30A0}-\\x{30FF}]"},
{"Bopomofo", "[\\x{3100}-\\x{312F}]"},
{"HangulCompatibilityJamo", "[\\x{3130}-\\x{318F}]"},
{"Kanbun", "[\\x{3190}-\\x{319F}]"},
{"BopomofoExtended", "[\\x{31A0}-\\x{31BF}]"},
{"EnclosedCJKLettersandMonths", "[\\x{3200}-\\x{32FF}]"},
{"CJKCompatibility", "[\\x{3300}-\\x{33FF}]"},
{"CJKUnifiedIdeographsExtensionA", "[\\x{3400}-\\x{4DB5}]"},
{"CJKUnifiedIdeographs", "[\\x{4E00}-\\x{9FFF}]"},
{"YiSyllables", "[\\x{A000}-\\x{A48F}]"},
{"YiRadicals", "[\\x{A490}-\\x{A4CF}]"},
{"HangulSyllables", "[\\x{AC00}-\\x{D7A3}]"},
{"PrivateUse", "[\\x{E000}-\\x{F8FF}]"},
{"CJKCompatibilityIdeographs", "[\\x{F900}-\\x{FAFF}]"},
{"AlphabeticPresentationForms", "[\\x{FB00}-\\x{FB4F}]"},
{"ArabicPresentationForms-A", "[\\x{FB50}-\\x{FDFF}]"},
{"CombiningHalfMarks", "[\\x{FE20}-\\x{FE2F}]"},
{"CJKCompatibilityForms", "[\\x{FE30}-\\x{FE4F}]"},
{"SmallFormVariants", "[\\x{FE50}-\\x{FE6F}]"},
{"ArabicPresentationForms-B", "[\\x{FE70}-\\x{FEFE}]"},
{"HalfwidthandFullwidthForms", "[\\x{FF00}-\\x{FFEF}]"},
{NULL, NULL}
};
const char *ly_stmt_str[] = {
[LY_STMT_UNKNOWN] = "",
[LY_STMT_ARGUMENT] = "argument",
[LY_STMT_BASE] = "base",
[LY_STMT_BELONGSTO] = "belongs-to",
[LY_STMT_CONTACT] = "contact",
[LY_STMT_DEFAULT] = "default",
[LY_STMT_DESCRIPTION] = "description",
[LY_STMT_ERRTAG] = "error-app-tag",
[LY_STMT_ERRMSG] = "error-message",
[LY_STMT_KEY] = "key",
[LY_STMT_NAMESPACE] = "namespace",
[LY_STMT_ORGANIZATION] = "organization",
[LY_STMT_PATH] = "path",
[LY_STMT_PREFIX] = "prefix",
[LY_STMT_PRESENCE] = "presence",
[LY_STMT_REFERENCE] = "reference",
[LY_STMT_REVISIONDATE] = "revision-date",
[LY_STMT_UNITS] = "units",
[LY_STMT_VALUE] = "value",
[LY_STMT_VERSION] = "yang-version",
[LY_STMT_MODIFIER] = "modifier",
[LY_STMT_REQINSTANCE] = "require-instance",
[LY_STMT_YINELEM] = "yin-element",
[LY_STMT_CONFIG] = "config",
[LY_STMT_MANDATORY] = "mandatory",
[LY_STMT_ORDEREDBY] = "ordered-by",
[LY_STMT_STATUS] = "status",
[LY_STMT_DIGITS] = "fraction-digits",
[LY_STMT_MAX] = "max-elements",
[LY_STMT_MIN] = "min-elements",
[LY_STMT_POSITION] = "position",
[LY_STMT_UNIQUE] = "unique",
[LY_STMT_MODULE] = "module",
[LY_STMT_SUBMODULE] = "submodule",
[LY_STMT_ACTION] = "action",
[LY_STMT_ANYDATA] = "anydata",
[LY_STMT_ANYXML] = "anyxml",
[LY_STMT_CASE] = "case",
[LY_STMT_CHOICE] = "choice",
[LY_STMT_CONTAINER] = "container",
[LY_STMT_GROUPING] = "grouping",
[LY_STMT_INPUT] = "input",
[LY_STMT_LEAF] = "leaf",
[LY_STMT_LEAFLIST] = "leaf-list",
[LY_STMT_LIST] = "list",
[LY_STMT_NOTIFICATION] = "notification",
[LY_STMT_OUTPUT] = "output",
[LY_STMT_RPC] = "rpc",
[LY_STMT_USES] = "uses",
[LY_STMT_TYPEDEF] = "typedef",
[LY_STMT_TYPE] = "type",
[LY_STMT_BIT] = "bit",
[LY_STMT_ENUM] = "enum",
[LY_STMT_REFINE] = "refine",
[LY_STMT_AUGMENT] = "augment",
[LY_STMT_DEVIATE] = "deviate",
[LY_STMT_DEVIATION] = "deviation",
[LY_STMT_EXTENSION] = "extension",
[LY_STMT_FEATURE] = "feature",
[LY_STMT_IDENTITY] = "identity",
[LY_STMT_IFFEATURE] = "if-feature",
[LY_STMT_IMPORT] = "import",
[LY_STMT_INCLUDE] = "include",
[LY_STMT_LENGTH] = "length",
[LY_STMT_MUST] = "must",
[LY_STMT_PATTERN] = "pattern",
[LY_STMT_RANGE] = "range",
[LY_STMT_WHEN] = "when",
[LY_STMT_REVISION] = "revision"
};
int
lyp_is_rpc_action(struct lys_node *node)
{
assert(node);
while (lys_parent(node)) {
node = lys_parent(node);
if (node->nodetype == LYS_ACTION) {
break;
}
}
if (node->nodetype & (LYS_RPC | LYS_ACTION)) {
return 1;
} else {
return 0;
}
}
int
lyp_data_check_options(struct ly_ctx *ctx, int options, const char *func)
{
int x = options & LYD_OPT_TYPEMASK;
/* LYD_OPT_WHENAUTODEL can be used only with LYD_OPT_DATA or LYD_OPT_CONFIG */
if (options & LYD_OPT_WHENAUTODEL) {
if ((x == LYD_OPT_EDIT) || (x == LYD_OPT_NOTIF_FILTER)) {
LOGERR(ctx, LY_EINVAL, "%s: Invalid options 0x%x (LYD_OPT_DATA_WHENAUTODEL can be used only with LYD_OPT_DATA or LYD_OPT_CONFIG)",
func, options);
return 1;
}
}
if (options & (LYD_OPT_DATA_ADD_YANGLIB | LYD_OPT_DATA_NO_YANGLIB)) {
if (x != LYD_OPT_DATA) {
LOGERR(ctx, LY_EINVAL, "%s: Invalid options 0x%x (LYD_OPT_DATA_*_YANGLIB can be used only with LYD_OPT_DATA)",
func, options);
return 1;
}
}
/* "is power of 2" algorithm, with 0 exception */
if (x && !(x && !(x & (x - 1)))) {
LOGERR(ctx, LY_EINVAL, "%s: Invalid options 0x%x (multiple data type flags set).", func, options);
return 1;
}
return 0;
}
int
lyp_mmap(struct ly_ctx *ctx, int fd, size_t addsize, size_t *length, void **addr)
{
struct stat sb;
long pagesize;
size_t m;
assert(fd >= 0);
if (fstat(fd, &sb) == -1) {
LOGERR(ctx, LY_ESYS, "Failed to stat the file descriptor (%s) for the mmap().", strerror(errno));
return 1;
}
if (!S_ISREG(sb.st_mode)) {
LOGERR(ctx, LY_EINVAL, "File to mmap() is not a regular file.");
return 1;
}
if (!sb.st_size) {
*addr = NULL;
return 0;
}
pagesize = sysconf(_SC_PAGESIZE);
++addsize; /* at least one additional byte for terminating NULL byte */
m = sb.st_size % pagesize;
if (m && pagesize - m >= addsize) {
/* there will be enough space after the file content mapping to provide zeroed additional bytes */
*length = sb.st_size + addsize;
*addr = mmap(NULL, *length, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
} else {
/* there will not be enough bytes after the file content mapping for the additional bytes and some of them
* would overflow into another page that would not be zeroed and any access into it would generate SIGBUS.
* Therefore we have to do the following hack with double mapping. First, the required number of bytes
* (including the additional bytes) is required as anonymous and thus they will be really provided (actually more
* because of using whole pages) and also initialized by zeros. Then, the file is mapped to the same address
* where the anonymous mapping starts. */
*length = sb.st_size + pagesize;
*addr = mmap(NULL, *length, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
*addr = mmap(*addr, sb.st_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED, fd, 0);
}
if (*addr == MAP_FAILED) {
LOGERR(ctx, LY_ESYS, "mmap() failed (%s).", strerror(errno));
return 1;
}
return 0;
}
int
lyp_munmap(void *addr, size_t length)
{
return munmap(addr, length);
}
int
lyp_add_ietf_netconf_annotations_config(struct lys_module *mod)
{
void *reallocated;
struct lys_ext_instance_complex *op;
struct lys_type **type;
struct lys_node_anydata *anyxml;
int i;
struct ly_ctx *ctx = mod->ctx; /* shortcut */
reallocated = realloc(mod->ext, (mod->ext_size + 3) * sizeof *mod->ext);
LY_CHECK_ERR_RETURN(!reallocated, LOGMEM(ctx), EXIT_FAILURE);
mod->ext = reallocated;
/* 1) edit-config's operation */
op = calloc(1, (sizeof(struct lys_ext_instance_complex) - 1) + 5 * sizeof(void*) + sizeof(uint16_t));
LY_CHECK_ERR_RETURN(!op, LOGMEM(ctx), EXIT_FAILURE);
mod->ext[mod->ext_size] = (struct lys_ext_instance *)op;
op->arg_value = lydict_insert(ctx, "operation", 9);
op->def = &ctx->models.list[0]->extensions[0];
op->ext_type = LYEXT_COMPLEX;
op->module = op->parent = mod;
op->parent_type = LYEXT_PAR_MODULE;
op->substmt = ((struct lyext_plugin_complex *)op->def->plugin)->substmt;
op->nodetype = LYS_EXT;
type = (struct lys_type**)&op->content; /* type is stored at offset 0 */
*type = calloc(1, sizeof(struct lys_type));
LY_CHECK_ERR_RETURN(!*type, LOGMEM(ctx), EXIT_FAILURE);
(*type)->base = LY_TYPE_ENUM;
(*type)->der = ly_types[LY_TYPE_ENUM];
(*type)->parent = (struct lys_tpdf *)op;
(*type)->info.enums.count = 5;
(*type)->info.enums.enm = calloc(5, sizeof *(*type)->info.enums.enm);
LY_CHECK_ERR_RETURN(!(*type)->info.enums.enm, LOGMEM(ctx), EXIT_FAILURE);
(*type)->info.enums.enm[0].value = 0;
(*type)->info.enums.enm[0].name = lydict_insert(ctx, "merge", 5);
(*type)->info.enums.enm[1].value = 1;
(*type)->info.enums.enm[1].name = lydict_insert(ctx, "replace", 7);
(*type)->info.enums.enm[2].value = 2;
(*type)->info.enums.enm[2].name = lydict_insert(ctx, "create", 6);
(*type)->info.enums.enm[3].value = 3;
(*type)->info.enums.enm[3].name = lydict_insert(ctx, "delete", 6);
(*type)->info.enums.enm[4].value = 4;
(*type)->info.enums.enm[4].name = lydict_insert(ctx, "remove", 6);
mod->ext_size++;
/* 2) filter's type */
op = calloc(1, (sizeof(struct lys_ext_instance_complex) - 1) + 5 * sizeof(void*) + sizeof(uint16_t));
LY_CHECK_ERR_RETURN(!op, LOGMEM(ctx), EXIT_FAILURE);
mod->ext[mod->ext_size] = (struct lys_ext_instance *)op;
op->arg_value = lydict_insert(ctx, "type", 4);
op->def = &ctx->models.list[0]->extensions[0];
op->ext_type = LYEXT_COMPLEX;
op->module = op->parent = mod;
op->parent_type = LYEXT_PAR_MODULE;
op->substmt = ((struct lyext_plugin_complex *)op->def->plugin)->substmt;
op->nodetype = LYS_EXT;
type = (struct lys_type**)&op->content; /* type is stored at offset 0 */
*type = calloc(1, sizeof(struct lys_type));
LY_CHECK_ERR_RETURN(!*type, LOGMEM(ctx), EXIT_FAILURE);
(*type)->base = LY_TYPE_ENUM;
(*type)->der = ly_types[LY_TYPE_ENUM];
(*type)->parent = (struct lys_tpdf *)op;
(*type)->info.enums.count = 2;
(*type)->info.enums.enm = calloc(2, sizeof *(*type)->info.enums.enm);
LY_CHECK_ERR_RETURN(!(*type)->info.enums.enm, LOGMEM(ctx), EXIT_FAILURE);
(*type)->info.enums.enm[0].value = 0;
(*type)->info.enums.enm[0].name = lydict_insert(ctx, "subtree", 7);
(*type)->info.enums.enm[1].value = 1;
(*type)->info.enums.enm[1].name = lydict_insert(ctx, "xpath", 5);
for (i = mod->features_size; i > 0; i--) {
if (!strcmp(mod->features[i - 1].name, "xpath")) {
(*type)->info.enums.enm[1].iffeature_size = 1;
(*type)->info.enums.enm[1].iffeature = calloc(1, sizeof(struct lys_feature));
LY_CHECK_ERR_RETURN(!(*type)->info.enums.enm[1].iffeature, LOGMEM(ctx), EXIT_FAILURE);
(*type)->info.enums.enm[1].iffeature[0].expr = malloc(sizeof(uint8_t));
LY_CHECK_ERR_RETURN(!(*type)->info.enums.enm[1].iffeature[0].expr, LOGMEM(ctx), EXIT_FAILURE);
*(*type)->info.enums.enm[1].iffeature[0].expr = 3; /* LYS_IFF_F */
(*type)->info.enums.enm[1].iffeature[0].features = malloc(sizeof(struct lys_feature*));
LY_CHECK_ERR_RETURN(!(*type)->info.enums.enm[1].iffeature[0].features, LOGMEM(ctx), EXIT_FAILURE);
(*type)->info.enums.enm[1].iffeature[0].features[0] = &mod->features[i - 1];
break;
}
}
mod->ext_size++;
/* 3) filter's select */
op = calloc(1, (sizeof(struct lys_ext_instance_complex) - 1) + 5 * sizeof(void*) + sizeof(uint16_t));
LY_CHECK_ERR_RETURN(!op, LOGMEM(ctx), EXIT_FAILURE);
mod->ext[mod->ext_size] = (struct lys_ext_instance *)op;
op->arg_value = lydict_insert(ctx, "select", 6);
op->def = &ctx->models.list[0]->extensions[0];
op->ext_type = LYEXT_COMPLEX;
op->module = op->parent = mod;
op->parent_type = LYEXT_PAR_MODULE;
op->substmt = ((struct lyext_plugin_complex *)op->def->plugin)->substmt;
op->nodetype = LYS_EXT;
type = (struct lys_type**)&op->content; /* type is stored at offset 0 */
*type = calloc(1, sizeof(struct lys_type));
LY_CHECK_ERR_RETURN(!*type, LOGMEM(ctx), EXIT_FAILURE);
(*type)->base = LY_TYPE_STRING;
(*type)->der = ly_types[LY_TYPE_STRING];
(*type)->parent = (struct lys_tpdf *)op;
mod->ext_size++;
/* 4) URL config */
anyxml = calloc(1, sizeof *anyxml);
LY_CHECK_ERR_RETURN(!anyxml, LOGMEM(ctx), EXIT_FAILURE);
anyxml->nodetype = LYS_ANYXML;
anyxml->prev = (struct lys_node *)anyxml;
anyxml->name = lydict_insert(ctx, "config", 0);
anyxml->module = mod;
anyxml->flags = LYS_CONFIG_W;
if (lys_node_addchild(NULL, mod, (struct lys_node *)anyxml, 0)) {
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
/* logs directly
* base: 0 - to accept decimal, octal, hexadecimal (in default value)
* 10 - to accept only decimal (instance value)
*/
static int
parse_int(const char *val_str, int64_t min, int64_t max, int base, int64_t *ret, struct lyd_node *node)
{
char *strptr;
assert(node);
if (!val_str || !val_str[0]) {
goto error;
}
/* convert to 64-bit integer, all the redundant characters are handled */
errno = 0;
strptr = NULL;
/* parse the value */
*ret = strtoll(val_str, &strptr, base);
if (errno || (*ret < min) || (*ret > max)) {
goto error;
} else if (strptr && *strptr) {
while (isspace(*strptr)) {
++strptr;
}
if (*strptr) {
goto error;
}
}
return EXIT_SUCCESS;
error:
LOGVAL(node->schema->module->ctx, LYE_INVAL, LY_VLOG_LYD, node, val_str ? val_str : "", node->schema->name);
return EXIT_FAILURE;
}
/* logs directly
* base: 0 - to accept decimal, octal, hexadecimal (in default value)
* 10 - to accept only decimal (instance value)
*/
static int
parse_uint(const char *val_str, uint64_t max, int base, uint64_t *ret, struct lyd_node *node)
{
char *strptr;
uint64_t u;
assert(node);
if (!val_str || !val_str[0]) {
goto error;
}
errno = 0;
strptr = NULL;
u = strtoull(val_str, &strptr, base);
if (errno || (u > max)) {
goto error;
} else if (strptr && *strptr) {
while (isspace(*strptr)) {
++strptr;
}
if (*strptr) {
goto error;
}
} else if (u != 0 && val_str[0] == '-') {
goto error;
}
*ret = u;
return EXIT_SUCCESS;
error:
LOGVAL(node->schema->module->ctx, LYE_INVAL, LY_VLOG_LYD, node, val_str ? val_str : "", node->schema->name);
return EXIT_FAILURE;
}
/* logs directly
*
* kind == 0 - unsigned (unum used), 1 - signed (snum used), 2 - floating point (fnum used)
*/
static int
validate_length_range(uint8_t kind, uint64_t unum, int64_t snum, int64_t fnum, uint8_t fnum_dig, struct lys_type *type,
const char *val_str, struct lyd_node *node)
{
struct lys_restr *restr = NULL;
struct len_ran_intv *intv = NULL, *tmp_intv;
struct lys_type *cur_type;
struct ly_ctx *ctx = type->parent->module->ctx;
int match;
if (resolve_len_ran_interval(ctx, NULL, type, &intv)) {
/* already done during schema parsing */
LOGINT(ctx);
return EXIT_FAILURE;
}
if (!intv) {
return EXIT_SUCCESS;
}
/* I know that all intervals belonging to a single restriction share one type pointer */
tmp_intv = intv;
cur_type = intv->type;
do {
match = 0;
for (; tmp_intv && (tmp_intv->type == cur_type); tmp_intv = tmp_intv->next) {
if (match) {
/* just iterate through the rest of this restriction intervals */
continue;
}
if (((kind == 0) && (unum < tmp_intv->value.uval.min))
|| ((kind == 1) && (snum < tmp_intv->value.sval.min))
|| ((kind == 2) && (dec64cmp(fnum, fnum_dig, tmp_intv->value.fval.min, cur_type->info.dec64.dig) < 0))) {
break;
}
if (((kind == 0) && (unum >= tmp_intv->value.uval.min) && (unum <= tmp_intv->value.uval.max))
|| ((kind == 1) && (snum >= tmp_intv->value.sval.min) && (snum <= tmp_intv->value.sval.max))
|| ((kind == 2) && (dec64cmp(fnum, fnum_dig, tmp_intv->value.fval.min, cur_type->info.dec64.dig) > -1)
&& (dec64cmp(fnum, fnum_dig, tmp_intv->value.fval.max, cur_type->info.dec64.dig) < 1))) {
match = 1;
}
}
if (!match) {
break;
} else if (tmp_intv) {
cur_type = tmp_intv->type;
}
} while (tmp_intv);
while (intv) {
tmp_intv = intv->next;
free(intv);
intv = tmp_intv;
}
if (!match) {
switch (cur_type->base) {
case LY_TYPE_BINARY:
restr = cur_type->info.binary.length;
break;
case LY_TYPE_DEC64:
restr = cur_type->info.dec64.range;
break;
case LY_TYPE_INT8:
case LY_TYPE_INT16:
case LY_TYPE_INT32:
case LY_TYPE_INT64:
case LY_TYPE_UINT8:
case LY_TYPE_UINT16:
case LY_TYPE_UINT32:
case LY_TYPE_UINT64:
restr = cur_type->info.num.range;
break;
case LY_TYPE_STRING:
restr = cur_type->info.str.length;
break;
default:
LOGINT(ctx);
return EXIT_FAILURE;
}
LOGVAL(ctx, LYE_NOCONSTR, LY_VLOG_LYD, node, (val_str ? val_str : ""), restr ? restr->expr : "");
if (restr && restr->emsg) {
ly_vlog_str(ctx, LY_VLOG_PREV, restr->emsg);
}
if (restr && restr->eapptag) {
ly_err_last_set_apptag(ctx, restr->eapptag);
}
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
/* logs directly */
static int
validate_pattern(struct ly_ctx *ctx, const char *val_str, struct lys_type *type, struct lyd_node *node)
{
int rc;
unsigned int i;
#ifndef LY_ENABLED_CACHE
pcre *precomp;
#endif
assert(ctx && (type->base == LY_TYPE_STRING));
if (!val_str) {
val_str = "";
}
if (type->der && validate_pattern(ctx, val_str, &type->der->type, node)) {
return EXIT_FAILURE;
}
#ifdef LY_ENABLED_CACHE
/* there is no cache, build it */
if (!type->info.str.patterns_pcre && type->info.str.pat_count) {
type->info.str.patterns_pcre = malloc(2 * type->info.str.pat_count * sizeof *type->info.str.patterns_pcre);
LY_CHECK_ERR_RETURN(!type->info.str.patterns_pcre, LOGMEM(ctx), -1);
for (i = 0; i < type->info.str.pat_count; ++i) {
if (lyp_precompile_pattern(ctx, &type->info.str.patterns[i].expr[1],
(pcre**)&type->info.str.patterns_pcre[i * 2],
(pcre_extra**)&type->info.str.patterns_pcre[i * 2 + 1])) {
return EXIT_FAILURE;
}
}
}
#endif
for (i = 0; i < type->info.str.pat_count; ++i) {
#ifdef LY_ENABLED_CACHE
rc = pcre_exec((pcre *)type->info.str.patterns_pcre[2 * i], (pcre_extra *)type->info.str.patterns_pcre[2 * i + 1],
val_str, strlen(val_str), 0, 0, NULL, 0);
#else
if (lyp_check_pattern(ctx, &type->info.str.patterns[i].expr[1], &precomp)) {
return EXIT_FAILURE;
}
rc = pcre_exec(precomp, NULL, val_str, strlen(val_str), 0, 0, NULL, 0);
free(precomp);
#endif
if ((rc && type->info.str.patterns[i].expr[0] == 0x06) || (!rc && type->info.str.patterns[i].expr[0] == 0x15)) {
LOGVAL(ctx, LYE_NOCONSTR, LY_VLOG_LYD, node, val_str, &type->info.str.patterns[i].expr[1]);
if (type->info.str.patterns[i].emsg) {
ly_vlog_str(ctx, LY_VLOG_PREV, type->info.str.patterns[i].emsg);
}
if (type->info.str.patterns[i].eapptag) {
ly_err_last_set_apptag(ctx, type->info.str.patterns[i].eapptag);
}
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
static void
check_number(const char *str_num, const char **num_end, LY_DATA_TYPE base)
{
if (!isdigit(str_num[0]) && (str_num[0] != '-') && (str_num[0] != '+')) {
*num_end = str_num;
return;
}
if ((str_num[0] == '-') || (str_num[0] == '+')) {
++str_num;
}
while (isdigit(str_num[0])) {
++str_num;
}
if ((base != LY_TYPE_DEC64) || (str_num[0] != '.') || !isdigit(str_num[1])) {
*num_end = str_num;
return;
}
++str_num;
while (isdigit(str_num[0])) {
++str_num;
}
*num_end = str_num;
}
/**
* @brief Checks the syntax of length or range statement,
* on success checks the semantics as well. Does not log.
*
* @param[in] expr Length or range expression.
* @param[in] type Type with the restriction.
*
* @return EXIT_SUCCESS on success, EXIT_FAILURE otherwise.
*/
int
lyp_check_length_range(struct ly_ctx *ctx, const char *expr, struct lys_type *type)
{
struct len_ran_intv *intv = NULL, *tmp_intv;
const char *c = expr, *tail;
int ret = EXIT_FAILURE, flg = 1; /* first run flag */
assert(expr);
lengthpart:
while (isspace(*c)) {
c++;
}
/* lower boundary or explicit number */
if (!strncmp(c, "max", 3)) {
max:
c += 3;
while (isspace(*c)) {
c++;
}
if (*c != '\0') {
goto error;
}
goto syntax_ok;
} else if (!strncmp(c, "min", 3)) {
if (!flg) {
/* min cannot be used elsewhere than in the first length-part */
goto error;
} else {
flg = 0;
}
c += 3;
while (isspace(*c)) {
c++;
}
if (*c == '|') {
c++;
/* process next length-part */
goto lengthpart;
} else if (*c == '\0') {
goto syntax_ok;
} else if (!strncmp(c, "..", 2)) {
upper:
c += 2;
while (isspace(*c)) {
c++;
}
if (*c == '\0') {
goto error;
}
/* upper boundary */
if (!strncmp(c, "max", 3)) {
goto max;
}
check_number(c, &tail, type->base);
if (c == tail) {
goto error;
}
c = tail;
while (isspace(*c)) {
c++;
}
if (*c == '\0') {
goto syntax_ok;
} else if (*c == '|') {
c++;
/* process next length-part */
goto lengthpart;
} else {
goto error;
}
} else {
goto error;
}
} else if (isdigit(*c) || (*c == '-') || (*c == '+')) {
/* number */
check_number(c, &tail, type->base);
if (c == tail) {
goto error;
}
c = tail;
while (isspace(*c)) {
c++;
}
if (*c == '|') {
c++;
/* process next length-part */
goto lengthpart;
} else if (*c == '\0') {
goto syntax_ok;
} else if (!strncmp(c, "..", 2)) {
goto upper;
}
} else {
goto error;
}
syntax_ok:
if (resolve_len_ran_interval(ctx, expr, type, &intv)) {
goto error;
}
ret = EXIT_SUCCESS;
error:
while (intv) {
tmp_intv = intv->next;
free(intv);
intv = tmp_intv;
}
return ret;
}
/**
* @brief Checks pattern syntax. Logs directly.
*
* @param[in] pattern Pattern to check.
* @param[out] pcre_precomp Precompiled PCRE pattern. Can be NULL.
* @return EXIT_SUCCESS on success, EXIT_FAILURE otherwise.
*/
int
lyp_check_pattern(struct ly_ctx *ctx, const char *pattern, pcre **pcre_precomp)
{
int idx, idx2, start, end, err_offset, count;
char *perl_regex, *ptr;
const char *err_msg, *orig_ptr;
pcre *precomp;
/*
* adjust the expression to a Perl equivalent
*
* http://www.w3.org/TR/2004/REC-xmlschema-2-20041028/#regexs
*/
/* we need to replace all "$" with "\$", count them now */
for (count = 0, ptr = strchr(pattern, '$'); ptr; ++count, ptr = strchr(ptr + 1, '$'));
perl_regex = malloc((strlen(pattern) + 4 + count) * sizeof(char));
LY_CHECK_ERR_RETURN(!perl_regex, LOGMEM(ctx), EXIT_FAILURE);
perl_regex[0] = '\0';
ptr = perl_regex;
if (strncmp(pattern + strlen(pattern) - 2, ".*", 2)) {
/* we wil add line-end anchoring */
ptr[0] = '(';
++ptr;
}
for (orig_ptr = pattern; orig_ptr[0]; ++orig_ptr) {
if (orig_ptr[0] == '$') {
ptr += sprintf(ptr, "\\$");
} else {
ptr[0] = orig_ptr[0];
++ptr;
}
}
if (strncmp(pattern + strlen(pattern) - 2, ".*", 2)) {
ptr += sprintf(ptr, ")$");
} else {
ptr[0] = '\0';
++ptr;
}
/* substitute Unicode Character Blocks with exact Character Ranges */
while ((ptr = strstr(perl_regex, "\\p{Is"))) {
start = ptr - perl_regex;
ptr = strchr(ptr, '}');
if (!ptr) {
LOGVAL(ctx, LYE_INREGEX, LY_VLOG_NONE, NULL, pattern, perl_regex + start + 2, "unterminated character property");
free(perl_regex);
return EXIT_FAILURE;
}
end = (ptr - perl_regex) + 1;
/* need more space */
if (end - start < LYP_URANGE_LEN) {
perl_regex = ly_realloc(perl_regex, strlen(perl_regex) + (LYP_URANGE_LEN - (end - start)) + 1);
LY_CHECK_ERR_RETURN(!perl_regex, LOGMEM(ctx); free(perl_regex), EXIT_FAILURE);
}
/* find our range */
for (idx = 0; lyp_ublock2urange[idx][0]; ++idx) {
if (!strncmp(perl_regex + start + 5, lyp_ublock2urange[idx][0], strlen(lyp_ublock2urange[idx][0]))) {
break;
}
}
if (!lyp_ublock2urange[idx][0]) {
LOGVAL(ctx, LYE_INREGEX, LY_VLOG_NONE, NULL, pattern, perl_regex + start + 5, "unknown block name");
free(perl_regex);
return EXIT_FAILURE;
}
/* make the space in the string and replace the block (but we cannot include brackets if it was already enclosed in them) */
for (idx2 = 0, count = 0; idx2 < start; ++idx2) {
if ((perl_regex[idx2] == '[') && (!idx2 || (perl_regex[idx2 - 1] != '\\'))) {
++count;
}
if ((perl_regex[idx2] == ']') && (!idx2 || (perl_regex[idx2 - 1] != '\\'))) {
--count;
}
}
if (count) {
/* skip brackets */
memmove(perl_regex + start + (LYP_URANGE_LEN - 2), perl_regex + end, strlen(perl_regex + end) + 1);
memcpy(perl_regex + start, lyp_ublock2urange[idx][1] + 1, LYP_URANGE_LEN - 2);
} else {
memmove(perl_regex + start + LYP_URANGE_LEN, perl_regex + end, strlen(perl_regex + end) + 1);
memcpy(perl_regex + start, lyp_ublock2urange[idx][1], LYP_URANGE_LEN);
}
}
/* must return 0, already checked during parsing */
precomp = pcre_compile(perl_regex, PCRE_ANCHORED | PCRE_DOLLAR_ENDONLY | PCRE_NO_AUTO_CAPTURE,
&err_msg, &err_offset, NULL);
if (!precomp) {
LOGVAL(ctx, LYE_INREGEX, LY_VLOG_NONE, NULL, pattern, perl_regex + err_offset, err_msg);
free(perl_regex);
return EXIT_FAILURE;
}
free(perl_regex);
if (pcre_precomp) {
*pcre_precomp = precomp;
} else {
free(precomp);
}
return EXIT_SUCCESS;
}
int
lyp_precompile_pattern(struct ly_ctx *ctx, const char *pattern, pcre** pcre_cmp, pcre_extra **pcre_std)
{
const char *err_msg = NULL;
if (lyp_check_pattern(ctx, pattern, pcre_cmp)) {
return EXIT_FAILURE;
}
if (pcre_std && pcre_cmp) {
(*pcre_std) = pcre_study(*pcre_cmp, 0, &err_msg);
if (err_msg) {
LOGWRN(ctx, "Studying pattern \"%s\" failed (%s).", pattern, err_msg);
}
}
return EXIT_SUCCESS;
}
/**
* @brief Change the value into its canonical form. In libyang, additionally to the RFC,
* all identities have their module as a prefix in their canonical form.
*
* @param[in] ctx
* @param[in] type Type of the value.
* @param[in,out] value Original and then canonical value.
* @param[in] data1 If \p type is #LY_TYPE_BITS: (struct lys_type_bit **) type bit field,
* #LY_TYPE_DEC64: (int64_t *) parsed digits of the number itself without floating point,
* #LY_TYPE_IDENT: (const char *) local module name (identityref node module),
* #LY_TYPE_INT*: (int64_t *) parsed int number itself,
* #LY_TYPE_UINT*: (uint64_t *) parsed uint number itself,
* otherwise ignored.
* @param[in] data2 If \p type is #LY_TYPE_BITS: (int *) type bit field length,
* #LY_TYPE_DEC64: (uint8_t *) number of fraction digits (position of the floating point),
* otherwise ignored.
* @return 1 if a conversion took place, 0 if the value was kept the same, -1 on error.
*/
static int
make_canonical(struct ly_ctx *ctx, int type, const char **value, void *data1, void *data2)
{
const uint16_t buf_len = 511;
char buf[buf_len + 1];
struct lys_type_bit **bits = NULL;
struct lyxp_expr *exp;
const char *module_name, *cur_expr, *end;
int i, j, count;
int64_t num;
uint64_t unum;
uint8_t c;
#define LOGBUF(str) LOGERR(ctx, LY_EINVAL, "Value \"%s\" is too long.", str)
switch (type) {
case LY_TYPE_BITS:
bits = (struct lys_type_bit **)data1;
count = *((int *)data2);
/* in canonical form, the bits are ordered by their position */
buf[0] = '\0';
for (i = 0; i < count; i++) {
if (!bits[i]) {
/* bit not set */
continue;
}
if (buf[0]) {
LY_CHECK_ERR_RETURN(strlen(buf) + 1 + strlen(bits[i]->name) > buf_len, LOGBUF(bits[i]->name), -1);
sprintf(buf + strlen(buf), " %s", bits[i]->name);
} else {
LY_CHECK_ERR_RETURN(strlen(bits[i]->name) > buf_len, LOGBUF(bits[i]->name), -1);
strcpy(buf, bits[i]->name);
}
}
break;
case LY_TYPE_IDENT:
module_name = (const char *)data1;
/* identity must always have a prefix */
if (!strchr(*value, ':')) {
sprintf(buf, "%s:%s", module_name, *value);
} else {
strcpy(buf, *value);
}
break;
case LY_TYPE_INST:
exp = lyxp_parse_expr(ctx, *value);
LY_CHECK_ERR_RETURN(!exp, LOGINT(ctx), -1);
module_name = NULL;
count = 0;
for (i = 0; (unsigned)i < exp->used; ++i) {
cur_expr = &exp->expr[exp->expr_pos[i]];
/* copy WS */
if (i && ((end = exp->expr + exp->expr_pos[i - 1] + exp->tok_len[i - 1]) != cur_expr)) {
if (count + (cur_expr - end) > buf_len) {
lyxp_expr_free(exp);
LOGBUF(end);
return -1;
}
strncpy(&buf[count], end, cur_expr - end);
count += cur_expr - end;
}
if ((exp->tokens[i] == LYXP_TOKEN_NAMETEST) && (end = strnchr(cur_expr, ':', exp->tok_len[i]))) {
/* get the module name with ":" */
++end;
j = end - cur_expr;
if (!module_name || strncmp(cur_expr, module_name, j)) {
/* print module name with colon, it does not equal to the parent one */
if (count + j > buf_len) {
lyxp_expr_free(exp);
LOGBUF(cur_expr);
return -1;
}
strncpy(&buf[count], cur_expr, j);
count += j;
}
module_name = cur_expr;
/* copy the rest */
if (count + (exp->tok_len[i] - j) > buf_len) {
lyxp_expr_free(exp);
LOGBUF(end);
return -1;
}
strncpy(&buf[count], end, exp->tok_len[i] - j);
count += exp->tok_len[i] - j;
} else {
if (count + exp->tok_len[i] > buf_len) {
lyxp_expr_free(exp);
LOGBUF(&exp->expr[exp->expr_pos[i]]);
return -1;
}
strncpy(&buf[count], &exp->expr[exp->expr_pos[i]], exp->tok_len[i]);
count += exp->tok_len[i];
}
}
if (count > buf_len) {
LOGINT(ctx);
lyxp_expr_free(exp);
return -1;
}
buf[count] = '\0';
lyxp_expr_free(exp);
break;
case LY_TYPE_DEC64:
num = *((int64_t *)data1);
c = *((uint8_t *)data2);
if (num) {
count = sprintf(buf, "%"PRId64" ", num);
if ( (num > 0 && (count - 1) <= c)
|| (count - 2) <= c ) {
/* we have 0. value, print the value with the leading zeros
* (one for 0. and also keep the correct with of num according
* to fraction-digits value)
* for (num<0) - extra character for '-' sign */
count = sprintf(buf, "%0*"PRId64" ", (num > 0) ? (c + 1) : (c + 2), num);
}
for (i = c, j = 1; i > 0 ; i--) {
if (j && i > 1 && buf[count - 2] == '0') {
/* we have trailing zero to skip */
buf[count - 1] = '\0';
} else {
j = 0;
buf[count - 1] = buf[count - 2];
}
count--;
}
buf[count - 1] = '.';
} else {
/* zero */
sprintf(buf, "0.0");
}
break;
case LY_TYPE_INT8:
case LY_TYPE_INT16:
case LY_TYPE_INT32:
case LY_TYPE_INT64:
num = *((int64_t *)data1);
sprintf(buf, "%"PRId64, num);
break;
case LY_TYPE_UINT8:
case LY_TYPE_UINT16:
case LY_TYPE_UINT32:
case LY_TYPE_UINT64:
unum = *((uint64_t *)data1);
sprintf(buf, "%"PRIu64, unum);
break;
default:
/* should not be even called - just do nothing */
return 0;
}
if (strcmp(buf, *value)) {
lydict_remove(ctx, *value);
*value = lydict_insert(ctx, buf, 0);
return 1;
}
return 0;
#undef LOGBUF
}
static const char *
ident_val_add_module_prefix(const char *value, const struct lyxml_elem *xml, struct ly_ctx *ctx)
{
const struct lyxml_ns *ns;
const struct lys_module *mod;
char *str;
do {
LY_TREE_FOR((struct lyxml_ns *)xml->attr, ns) {
if ((ns->type == LYXML_ATTR_NS) && !ns->prefix) {
/* match */
break;
}
}
if (!ns) {
xml = xml->parent;
}
} while (!ns && xml);
if (!ns) {
/* no default namespace */
LOGINT(ctx);
return NULL;
}
/* find module */
mod = ly_ctx_get_module_by_ns(ctx, ns->value, NULL, 1);
if (!mod) {
LOGINT(ctx);
return NULL;
}
if (asprintf(&str, "%s:%s", mod->name, value) == -1) {
LOGMEM(ctx);
return NULL;
}
lydict_remove(ctx, value);
return lydict_insert_zc(ctx, str);
}
/*
* xml - optional for converting instance-identifier and identityref into JSON format
* leaf - mandatory to know the context (necessary e.g. for prefixes in idenitytref values)
* attr - alternative to leaf in case of parsing value in annotations (attributes)
* local_mod - optional if the local module dos not match the module of leaf/attr
* store - flag for union resolution - we do not want to store the result, we are just learning the type
* dflt - whether the value is a default value from the schema
* trusted - whether the value is trusted to be valid (but may not be canonical, so it is canonized)
*/
struct lys_type *
lyp_parse_value(struct lys_type *type, const char **value_, struct lyxml_elem *xml,
struct lyd_node_leaf_list *leaf, struct lyd_attr *attr, struct lys_module *local_mod,
int store, int dflt, int trusted)
{
struct lys_type *ret = NULL, *t;
struct lys_tpdf *tpdf;
enum int_log_opts prev_ilo;
int c, len, found = 0;
unsigned int i, j;
int64_t num;
uint64_t unum, uind, u = 0;
const char *ptr, *value = *value_, *itemname, *old_val_str = NULL;
struct lys_type_bit **bits = NULL;
struct lys_ident *ident;
lyd_val *val, old_val;
LY_DATA_TYPE *val_type, old_val_type;
uint8_t *val_flags, old_val_flags;
struct lyd_node *contextnode;
struct ly_ctx *ctx = type->parent->module->ctx;
assert(leaf || attr);
if (leaf) {
assert(!attr);
if (!local_mod) {
local_mod = leaf->schema->module;
}
val = &leaf->value;
val_type = &leaf->value_type;
val_flags = &leaf->value_flags;
contextnode = (struct lyd_node *)leaf;
itemname = leaf->schema->name;
} else {
assert(!leaf);
if (!local_mod) {
local_mod = attr->annotation->module;
}
val = &attr->value;
val_type = &attr->value_type;
val_flags = &attr->value_flags;
contextnode = attr->parent;
itemname = attr->name;
}
/* fully clear the value */
if (store) {
old_val_str = lydict_insert(ctx, *value_, 0);
lyd_free_value(*val, *val_type, *val_flags, type, old_val_str, &old_val, &old_val_type, &old_val_flags);
*val_flags &= ~LY_VALUE_UNRES;
}
switch (type->base) {
case LY_TYPE_BINARY:
/* get number of octets for length validation */
unum = 0;
ptr = NULL;
if (value) {
/* silently skip leading/trailing whitespaces */
for (uind = 0; isspace(value[uind]); ++uind);
ptr = &value[uind];
u = strlen(ptr);
while (u && isspace(ptr[u - 1])) {
--u;
}
unum = u;
for (uind = 0; uind < u; ++uind) {
if (ptr[uind] == '\n') {
unum--;
} else if ((ptr[uind] < '/' && ptr[uind] != '+') ||
(ptr[uind] > '9' && ptr[uind] < 'A') ||
(ptr[uind] > 'Z' && ptr[uind] < 'a') || ptr[uind] > 'z') {
if (ptr[uind] == '=') {
/* padding */
if (uind == u - 2 && ptr[uind + 1] == '=') {
found = 2;
uind++;
} else if (uind == u - 1) {
found = 1;
}
}
if (!found) {
/* error */
LOGVAL(ctx, LYE_INCHAR, LY_VLOG_LYD, contextnode, ptr[uind], &ptr[uind]);
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Invalid Base64 character.");
goto error;
}
}
}
}
if (unum & 3) {
/* base64 length must be multiple of 4 chars */
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value);
}
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Base64 encoded value length must be divisible by 4.");
goto error;
}
/* length of the encoded string */
len = ((unum / 4) * 3) - found;
if (!trusted && validate_length_range(0, len, 0, 0, 0, type, value, contextnode)) {
goto error;
}
if (value && (ptr != value || ptr[u] != '\0')) {
/* update the changed value */
ptr = lydict_insert(ctx, ptr, u);
lydict_remove(ctx, *value_);
*value_ = ptr;
}
if (store) {
/* store the result */
val->binary = value;
*val_type = LY_TYPE_BINARY;
}
break;
case LY_TYPE_BITS:
/* locate bits structure with the bits definitions
* since YANG 1.1 allows restricted bits, it is the first
* bits type with some explicit bit specification */
for (; !type->info.bits.count; type = &type->der->type);
if (value || store) {
/* allocate the array of pointers to bits definition */
bits = calloc(type->info.bits.count, sizeof *bits);
LY_CHECK_ERR_GOTO(!bits, LOGMEM(ctx), error);
}
if (!value) {
/* no bits set */
if (store) {
/* store empty array */
val->bit = bits;
*val_type = LY_TYPE_BITS;
}
break;
}
c = 0;
i = 0;
while (value[c]) {
/* skip leading whitespaces */
while (isspace(value[c])) {
c++;
}
if (!value[c]) {
/* trailing white spaces */
break;
}
/* get the length of the bit identifier */
for (len = 0; value[c] && !isspace(value[c]); c++, len++);
/* go back to the beginning of the identifier */
c = c - len;
/* find bit definition, identifiers appear ordered by their position */
for (found = i = 0; i < type->info.bits.count; i++) {
if (!strncmp(type->info.bits.bit[i].name, &value[c], len) && !type->info.bits.bit[i].name[len]) {
/* we have match, check if the value is enabled ... */
for (j = 0; !trusted && (j < type->info.bits.bit[i].iffeature_size); j++) {
if (!resolve_iffeature(&type->info.bits.bit[i].iffeature[j])) {
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value);
}
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL,
"Bit \"%s\" is disabled by its %d. if-feature condition.",
type->info.bits.bit[i].name, j + 1);
free(bits);
goto error;
}
}
/* check that the value was not already set */
if (bits[i]) {
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value);
}
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Bit \"%s\" used multiple times.",
type->info.bits.bit[i].name);
free(bits);
goto error;
}
/* ... and then store the pointer */
bits[i] = &type->info.bits.bit[i];
/* stop searching */
found = 1;
break;
}
}
if (!found) {
/* referenced bit value does not exist */
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value);
}
free(bits);
goto error;
}
c = c + len;
}
if (make_canonical(ctx, LY_TYPE_BITS, value_, bits, &type->info.bits.count) == -1) {
free(bits);
goto error;
}
if (store) {
/* store the result */
val->bit = bits;
*val_type = LY_TYPE_BITS;
} else {
free(bits);
}
break;
case LY_TYPE_BOOL:
if (value && !strcmp(value, "true")) {
if (store) {
val->bln = 1;
}
} else if (!value || strcmp(value, "false")) {
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value ? value : "", itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value ? value : "");
}
goto error;
} else {
if (store) {
val->bln = 0;
}
}
if (store) {
*val_type = LY_TYPE_BOOL;
}
break;
case LY_TYPE_DEC64:
if (!value || !value[0]) {
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, "", itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, "");
}
goto error;
}
ptr = value;
if (parse_range_dec64(&ptr, type->info.dec64.dig, &num) || ptr[0]) {
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value);
}
goto error;
}
if (!trusted && validate_length_range(2, 0, 0, num, type->info.dec64.dig, type, value, contextnode)) {
goto error;
}
if (make_canonical(ctx, LY_TYPE_DEC64, value_, &num, &type->info.dec64.dig) == -1) {
goto error;
}
if (store) {
/* store the result */
val->dec64 = num;
*val_type = LY_TYPE_DEC64;
}
break;
case LY_TYPE_EMPTY:
if (value && value[0]) {
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value);
}
goto error;
}
if (store) {
*val_type = LY_TYPE_EMPTY;
}
break;
case LY_TYPE_ENUM:
/* locate enums structure with the enumeration definitions,
* since YANG 1.1 allows restricted enums, it is the first
* enum type with some explicit enum specification */
for (; !type->info.enums.count; type = &type->der->type);
/* find matching enumeration value */
for (i = found = 0; i < type->info.enums.count; i++) {
if (value && !strcmp(value, type->info.enums.enm[i].name)) {
/* we have match, check if the value is enabled ... */
for (j = 0; !trusted && (j < type->info.enums.enm[i].iffeature_size); j++) {
if (!resolve_iffeature(&type->info.enums.enm[i].iffeature[j])) {
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value);
}
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Enum \"%s\" is disabled by its %d. if-feature condition.",
value, j + 1);
goto error;
}
}
/* ... and store pointer to the definition */
if (store) {
val->enm = &type->info.enums.enm[i];
*val_type = LY_TYPE_ENUM;
}
found = 1;
break;
}
}
if (!found) {
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value ? value : "", itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value ? value : "");
}
goto error;
}
break;
case LY_TYPE_IDENT:
if (!value) {
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, "", itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, "");
}
goto error;
}
if (xml) {
ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL);
/* first, convert value into the json format, silently */
value = transform_xml2json(ctx, value, xml, 0, 0);
ly_ilo_restore(NULL, prev_ilo, NULL, 0);
if (!value) {
/* invalid identityref format */
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, *value_, itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, *value_);
}
goto error;
}
/* the value has no prefix (default namespace), but the element's namespace has a prefix, find default namespace */
if (!strchr(value, ':') && xml->ns->prefix) {
value = ident_val_add_module_prefix(value, xml, ctx);
if (!value) {
goto error;
}
}
} else if (dflt) {
ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL);
/* the value actually uses module's prefixes instead of the module names as in JSON format,
* we have to convert it */
value = transform_schema2json(local_mod, value);
ly_ilo_restore(NULL, prev_ilo, NULL, 0);
if (!value) {
/* invalid identityref format or it was already transformed, so ignore the error here */
value = lydict_insert(ctx, *value_, 0);
}
} else {
value = lydict_insert(ctx, *value_, 0);
}
/* value is now in the dictionary, whether it differs from *value_ or not */
ident = resolve_identref(type, value, contextnode, local_mod, dflt);
if (!ident) {
lydict_remove(ctx, value);
goto error;
} else if (store) {
/* store the result */
val->ident = ident;
*val_type = LY_TYPE_IDENT;
}
/* the value is always changed and includes prefix */
if (dflt) {
type->parent->flags |= LYS_DFLTJSON;
}
if (make_canonical(ctx, LY_TYPE_IDENT, &value, (void*)lys_main_module(local_mod)->name, NULL) == -1) {
lydict_remove(ctx, value);
goto error;
}
/* replace the old value with the new one (even if they may be the same) */
lydict_remove(ctx, *value_);
*value_ = value;
break;
case LY_TYPE_INST:
if (!value) {
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, "", itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, "");
}
goto error;
}
if (xml) {
ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL);
/* first, convert value into the json format, silently */
value = transform_xml2json(ctx, value, xml, 1, 1);
ly_ilo_restore(NULL, prev_ilo, NULL, 0);
if (!value) {
/* invalid instance-identifier format */
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, *value_, itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, *value_);
}
goto error;
} else if (ly_strequal(value, *value_, 1)) {
/* we have actually created the same expression (prefixes are the same as the module names)
* so we have just increased dictionary's refcount - fix it */
lydict_remove(ctx, value);
}
} else if (dflt) {
/* turn logging off */
ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL);
/* the value actually uses module's prefixes instead of the module names as in JSON format,
* we have to convert it */
value = transform_schema2json(local_mod, value);
if (!value) {
/* invalid identityref format or it was already transformed, so ignore the error here */
value = *value_;
} else if (ly_strequal(value, *value_, 1)) {
/* we have actually created the same expression (prefixes are the same as the module names)
* so we have just increased dictionary's refcount - fix it */
lydict_remove(ctx, value);
}
/* turn logging back on */
ly_ilo_restore(NULL, prev_ilo, NULL, 0);
} else {
if ((c = make_canonical(ctx, LY_TYPE_INST, &value, NULL, NULL))) {
if (c == -1) {
goto error;
}
/* if a change occurred, value was removed from the dictionary so fix the pointers */
*value_ = value;
}
}
if (store) {
/* note that the data node is an unresolved instance-identifier */
val->instance = NULL;
*val_type = LY_TYPE_INST;
*val_flags |= LY_VALUE_UNRES;
}
if (!ly_strequal(value, *value_, 1)) {
/* update the changed value */
lydict_remove(ctx, *value_);
*value_ = value;
/* we have to remember the conversion into JSON format to be able to print it in correct form */
if (dflt) {
type->parent->flags |= LYS_DFLTJSON;
}
}
break;
case LY_TYPE_LEAFREF:
if (!value) {
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, "", itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, "");
}
goto error;
}
/* it is called not only to get the final type, but mainly to update value to canonical or JSON form
* if needed */
t = lyp_parse_value(&type->info.lref.target->type, value_, xml, leaf, attr, NULL, store, dflt, trusted);
value = *value_; /* refresh possibly changed value */
if (!t) {
/* already logged */
goto error;
}
if (store) {
/* make the note that the data node is an unresolved leafref (value union was already filled) */
*val_flags |= LY_VALUE_UNRES;
}
type = t;
break;
case LY_TYPE_STRING:
if (!trusted && validate_length_range(0, (value ? ly_strlen_utf8(value) : 0), 0, 0, 0, type, value, contextnode)) {
goto error;
}
if (!trusted && validate_pattern(ctx, value, type, contextnode)) {
goto error;
}
/* special handling of ietf-yang-types xpath1.0 */
for (tpdf = type->der;
tpdf->module && (strcmp(tpdf->name, "xpath1.0") || strcmp(tpdf->module->name, "ietf-yang-types"));
tpdf = tpdf->type.der);
if (tpdf->module && xml) {
/* convert value into the json format */
value = transform_xml2json(ctx, value ? value : "", xml, 1, 1);
if (!value) {
/* invalid instance-identifier format */
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, *value_, itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, *value_);
}
goto error;
}
if (!ly_strequal(value, *value_, 1)) {
/* update the changed value */
lydict_remove(ctx, *value_);
*value_ = value;
}
}
if (store) {
/* store the result */
val->string = value;
*val_type = LY_TYPE_STRING;
}
break;
case LY_TYPE_INT8:
if (parse_int(value, __INT64_C(-128), __INT64_C(127), dflt ? 0 : 10, &num, contextnode)
|| (!trusted && validate_length_range(1, 0, num, 0, 0, type, value, contextnode))) {
goto error;
}
if (make_canonical(ctx, LY_TYPE_INT8, value_, &num, NULL) == -1) {
goto error;
}
if (store) {
/* store the result */
val->int8 = (int8_t)num;
*val_type = LY_TYPE_INT8;
}
break;
case LY_TYPE_INT16:
if (parse_int(value, __INT64_C(-32768), __INT64_C(32767), dflt ? 0 : 10, &num, contextnode)
|| (!trusted && validate_length_range(1, 0, num, 0, 0, type, value, contextnode))) {
goto error;
}
if (make_canonical(ctx, LY_TYPE_INT16, value_, &num, NULL) == -1) {
goto error;
}
if (store) {
/* store the result */
val->int16 = (int16_t)num;
*val_type = LY_TYPE_INT16;
}
break;
case LY_TYPE_INT32:
if (parse_int(value, __INT64_C(-2147483648), __INT64_C(2147483647), dflt ? 0 : 10, &num, contextnode)
|| (!trusted && validate_length_range(1, 0, num, 0, 0, type, value, contextnode))) {
goto error;
}
if (make_canonical(ctx, LY_TYPE_INT32, value_, &num, NULL) == -1) {
goto error;
}
if (store) {
/* store the result */
val->int32 = (int32_t)num;
*val_type = LY_TYPE_INT32;
}
break;
case LY_TYPE_INT64:
if (parse_int(value, __INT64_C(-9223372036854775807) - __INT64_C(1), __INT64_C(9223372036854775807),
dflt ? 0 : 10, &num, contextnode)
|| (!trusted && validate_length_range(1, 0, num, 0, 0, type, value, contextnode))) {
goto error;
}
if (make_canonical(ctx, LY_TYPE_INT64, value_, &num, NULL) == -1) {
goto error;
}
if (store) {
/* store the result */
val->int64 = num;
*val_type = LY_TYPE_INT64;
}
break;
case LY_TYPE_UINT8:
if (parse_uint(value, __UINT64_C(255), dflt ? 0 : 10, &unum, contextnode)
|| (!trusted && validate_length_range(0, unum, 0, 0, 0, type, value, contextnode))) {
goto error;
}
if (make_canonical(ctx, LY_TYPE_UINT8, value_, &unum, NULL) == -1) {
goto error;
}
if (store) {
/* store the result */
val->uint8 = (uint8_t)unum;
*val_type = LY_TYPE_UINT8;
}
break;
case LY_TYPE_UINT16:
if (parse_uint(value, __UINT64_C(65535), dflt ? 0 : 10, &unum, contextnode)
|| (!trusted && validate_length_range(0, unum, 0, 0, 0, type, value, contextnode))) {
goto error;
}
if (make_canonical(ctx, LY_TYPE_UINT16, value_, &unum, NULL) == -1) {
goto error;
}
if (store) {
/* store the result */
val->uint16 = (uint16_t)unum;
*val_type = LY_TYPE_UINT16;
}
break;
case LY_TYPE_UINT32:
if (parse_uint(value, __UINT64_C(4294967295), dflt ? 0 : 10, &unum, contextnode)
|| (!trusted && validate_length_range(0, unum, 0, 0, 0, type, value, contextnode))) {
goto error;
}
if (make_canonical(ctx, LY_TYPE_UINT32, value_, &unum, NULL) == -1) {
goto error;
}
if (store) {
/* store the result */
val->uint32 = (uint32_t)unum;
*val_type = LY_TYPE_UINT32;
}
break;
case LY_TYPE_UINT64:
if (parse_uint(value, __UINT64_C(18446744073709551615), dflt ? 0 : 10, &unum, contextnode)
|| (!trusted && validate_length_range(0, unum, 0, 0, 0, type, value, contextnode))) {
goto error;
}
if (make_canonical(ctx, LY_TYPE_UINT64, value_, &unum, NULL) == -1) {
goto error;
}
if (store) {
/* store the result */
val->uint64 = unum;
*val_type = LY_TYPE_UINT64;
}
break;
case LY_TYPE_UNION:
if (store) {
/* unresolved union type */
memset(val, 0, sizeof(lyd_val));
*val_type = LY_TYPE_UNION;
}
if (type->info.uni.has_ptr_type) {
/* we are not resolving anything here, only parsing, and in this case we cannot decide
* the type without resolving it -> we return the union type (resolve it with resolve_union()) */
if (xml) {
/* in case it should resolve into a instance-identifier, we can only do the JSON conversion here */
ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL);
val->string = transform_xml2json(ctx, value, xml, 1, 1);
ly_ilo_restore(NULL, prev_ilo, NULL, 0);
if (!val->string) {
/* invalid instance-identifier format, likely some other type */
val->string = lydict_insert(ctx, value, 0);
}
}
break;
}
t = NULL;
found = 0;
/* turn logging off, we are going to try to validate the value with all the types in order */
ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL);
while ((t = lyp_get_next_union_type(type, t, &found))) {
found = 0;
ret = lyp_parse_value(t, value_, xml, leaf, attr, NULL, store, dflt, 0);
if (ret) {
/* we have the result */
type = ret;
break;
}
if (store) {
/* erase possible present and invalid value data */
lyd_free_value(*val, *val_type, *val_flags, t, *value_, NULL, NULL, NULL);
memset(val, 0, sizeof(lyd_val));
}
}
/* turn logging back on */
ly_ilo_restore(NULL, prev_ilo, NULL, 0);
if (!t) {
/* not found */
if (store) {
*val_type = 0;
}
if (leaf) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, *value_ ? *value_ : "", itemname);
} else {
LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, *value_);
}
goto error;
}
break;
default:
LOGINT(ctx);
goto error;
}
/* search user types in case this value is supposed to be stored in a custom way */
if (store && type->der && type->der->module) {
c = lytype_store(type->der->module, type->der->name, value_, val);
if (c == -1) {
goto error;
} else if (!c) {
*val_flags |= LY_VALUE_USER;
}
}
/* free backup */
if (store) {
lyd_free_value(old_val, old_val_type, old_val_flags, type, old_val_str, NULL, NULL, NULL);
lydict_remove(ctx, old_val_str);
}
return type;
error:
/* restore the backup */
if (store) {
*val = old_val;
*val_type = old_val_type;
*val_flags = old_val_flags;
lydict_remove(ctx, old_val_str);
}
return NULL;
}
/* does not log, cannot fail */
struct lys_type *
lyp_get_next_union_type(struct lys_type *type, struct lys_type *prev_type, int *found)
{
unsigned int i;
struct lys_type *ret = NULL;
while (!type->info.uni.count) {
assert(type->der); /* at least the direct union type has to have type specified */
type = &type->der->type;
}
for (i = 0; i < type->info.uni.count; ++i) {
if (type->info.uni.types[i].base == LY_TYPE_UNION) {
ret = lyp_get_next_union_type(&type->info.uni.types[i], prev_type, found);
if (ret) {
break;
}
continue;
}
if (!prev_type || *found) {
ret = &type->info.uni.types[i];
break;
}
if (&type->info.uni.types[i] == prev_type) {
*found = 1;
}
}
return ret;
}
/* ret 0 - ret set, ret 1 - ret not set, no log, ret -1 - ret not set, fatal error */
int
lyp_fill_attr(struct ly_ctx *ctx, struct lyd_node *parent, const char *module_ns, const char *module_name,
const char *attr_name, const char *attr_value, struct lyxml_elem *xml, int options, struct lyd_attr **ret)
{
const struct lys_module *mod = NULL;
const struct lys_submodule *submod = NULL;
struct lys_type **type;
struct lyd_attr *dattr;
int pos, i, j, k;
/* first, get module where the annotation should be defined */
if (module_ns) {
mod = (struct lys_module *)ly_ctx_get_module_by_ns(ctx, module_ns, NULL, 0);
} else if (module_name) {
mod = (struct lys_module *)ly_ctx_get_module(ctx, module_name, NULL, 0);
} else {
LOGINT(ctx);
return -1;
}
if (!mod) {
return 1;
}
/* then, find the appropriate annotation definition */
pos = -1;
for (i = 0, j = 0; i < mod->ext_size; i = i + j + 1) {
j = lys_ext_instance_presence(&ctx->models.list[0]->extensions[0], &mod->ext[i], mod->ext_size - i);
if (j == -1) {
break;
}
if (ly_strequal(mod->ext[i + j]->arg_value, attr_name, 0)) {
pos = i + j;
break;
}
}
/* try submodules */
if (pos == -1) {
for (k = 0; k < mod->inc_size; ++k) {
submod = mod->inc[k].submodule;
for (i = 0, j = 0; i < submod->ext_size; i = i + j + 1) {
j = lys_ext_instance_presence(&ctx->models.list[0]->extensions[0], &submod->ext[i], submod->ext_size - i);
if (j == -1) {
break;
}
if (ly_strequal(submod->ext[i + j]->arg_value, attr_name, 0)) {
pos = i + j;
break;
}
}
}
}
if (pos == -1) {
return 1;
}
/* allocate and fill the data attribute structure */
dattr = calloc(1, sizeof *dattr);
LY_CHECK_ERR_RETURN(!dattr, LOGMEM(ctx), -1);
dattr->parent = parent;
dattr->next = NULL;
dattr->annotation = submod ? (struct lys_ext_instance_complex *)submod->ext[pos] :
(struct lys_ext_instance_complex *)mod->ext[pos];
dattr->name = lydict_insert(ctx, attr_name, 0);
dattr->value_str = lydict_insert(ctx, attr_value, 0);
/* the value is here converted to a JSON format if needed in case of LY_TYPE_IDENT and LY_TYPE_INST or to a
* canonical form of the value */
type = lys_ext_complex_get_substmt(LY_STMT_TYPE, dattr->annotation, NULL);
if (!type || !lyp_parse_value(*type, &dattr->value_str, xml, NULL, dattr, NULL, 1, 0, options & LYD_OPT_TRUSTED)) {
lydict_remove(ctx, dattr->name);
lydict_remove(ctx, dattr->value_str);
free(dattr);
return -1;
}
*ret = dattr;
return 0;
}
int
lyp_check_edit_attr(struct ly_ctx *ctx, struct lyd_attr *attr, struct lyd_node *parent, int *editbits)
{
struct lyd_attr *last = NULL;
int bits = 0;
/* 0x01 - insert attribute present
* 0x02 - insert is relative (before or after)
* 0x04 - value attribute present
* 0x08 - key attribute present
* 0x10 - operation attribute present
* 0x20 - operation not allowing insert attribute (delete or remove)
*/
LY_TREE_FOR(attr, attr) {
last = NULL;
if (!strcmp(attr->annotation->arg_value, "operation") &&
!strcmp(attr->annotation->module->name, "ietf-netconf")) {
if (bits & 0x10) {
LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYD, parent, "operation attributes", parent->schema->name);
return -1;
}
bits |= 0x10;
if (attr->value.enm->value >= 3) {
/* delete or remove */
bits |= 0x20;
}
} else if (attr->annotation->module == ctx->models.list[1] && /* internal YANG schema */
!strcmp(attr->annotation->arg_value, "insert")) {
/* 'insert' attribute present */
if (!(parent->schema->flags & LYS_USERORDERED)) {
/* ... but it is not expected */
LOGVAL(ctx, LYE_INATTR, LY_VLOG_LYD, parent, "insert");
return -1;
}
if (bits & 0x01) {
LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYD, parent, "insert attributes", parent->schema->name);
return -1;
}
bits |= 0x01;
if (attr->value.enm->value >= 2) {
/* before or after */
bits |= 0x02;
}
last = attr;
} else if (attr->annotation->module == ctx->models.list[1] && /* internal YANG schema */
!strcmp(attr->annotation->arg_value, "value")) {
if (bits & 0x04) {
LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYD, parent, "value attributes", parent->schema->name);
return -1;
} else if (parent->schema->nodetype & LYS_LIST) {
LOGVAL(ctx, LYE_INATTR, LY_VLOG_LYD, parent, attr->name);
return -1;
}
bits |= 0x04;
last = attr;
} else if (attr->annotation->module == ctx->models.list[1] && /* internal YANG schema */
!strcmp(attr->annotation->arg_value, "key")) {
if (bits & 0x08) {
LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYD, parent, "key attributes", parent->schema->name);
return -1;
} else if (parent->schema->nodetype & LYS_LEAFLIST) {
LOGVAL(ctx, LYE_INATTR, LY_VLOG_LYD, parent, attr->name);
return -1;
}
bits |= 0x08;
last = attr;
}
}
/* report errors */
if (last && (!(parent->schema->nodetype & (LYS_LEAFLIST | LYS_LIST)) || !(parent->schema->flags & LYS_USERORDERED))) {
/* moving attributes in wrong elements (not an user ordered list or not a list at all) */
LOGVAL(ctx, LYE_INATTR, LY_VLOG_LYD, parent, last->name);
return -1;
} else if (bits == 3) {
/* 0x01 | 0x02 - relative position, but value/key is missing */
if (parent->schema->nodetype & LYS_LIST) {
LOGVAL(ctx, LYE_MISSATTR, LY_VLOG_LYD, parent, "key", parent->schema->name);
} else { /* LYS_LEAFLIST */
LOGVAL(ctx, LYE_MISSATTR, LY_VLOG_LYD, parent, "value", parent->schema->name);
}
return -1;
} else if ((bits & (0x04 | 0x08)) && !(bits & 0x02)) {
/* key/value without relative position */
LOGVAL(ctx, LYE_INATTR, LY_VLOG_LYD, parent, (bits & 0x04) ? "value" : "key");
return -1;
} else if ((bits & 0x21) == 0x21) {
/* insert in delete/remove */
LOGVAL(ctx, LYE_INATTR, LY_VLOG_LYD, parent, "insert");
return -1;
}
if (editbits) {
*editbits = bits;
}
return 0;
}
/* does not log */
static int
dup_identity_check(const char *id, struct lys_ident *ident, uint32_t size)
{
uint32_t i;
for (i = 0; i < size; i++) {
if (ly_strequal(id, ident[i].name, 1)) {
/* name collision */
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
int
dup_identities_check(const char *id, struct lys_module *module)
{
struct lys_module *mainmod;
int i;
if (dup_identity_check(id, module->ident, module->ident_size)) {
LOGVAL(module->ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "identity", id);
return EXIT_FAILURE;
}
/* check identity in submodules */
mainmod = lys_main_module(module);
for (i = 0; i < mainmod->inc_size && mainmod->inc[i].submodule; ++i) {
if (dup_identity_check(id, mainmod->inc[i].submodule->ident, mainmod->inc[i].submodule->ident_size)) {
LOGVAL(module->ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "identity", id);
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
/* does not log */
int
dup_typedef_check(const char *type, struct lys_tpdf *tpdf, int size)
{
int i;
for (i = 0; i < size; i++) {
if (!strcmp(type, tpdf[i].name)) {
/* name collision */
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
/* does not log */
static int
dup_feature_check(const char *id, struct lys_module *module)
{
int i;
for (i = 0; i < module->features_size; i++) {
if (!strcmp(id, module->features[i].name)) {
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
/* does not log */
static int
dup_prefix_check(const char *prefix, struct lys_module *module)
{
int i;
if (module->prefix && !strcmp(module->prefix, prefix)) {
return EXIT_FAILURE;
}
for (i = 0; i < module->imp_size; i++) {
if (!strcmp(module->imp[i].prefix, prefix)) {
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
/* logs directly */
int
lyp_check_identifier(struct ly_ctx *ctx, const char *id, enum LY_IDENT type, struct lys_module *module,
struct lys_node *parent)
{
int i, j;
int size;
struct lys_tpdf *tpdf;
struct lys_node *node;
struct lys_module *mainmod;
struct lys_submodule *submod;
assert(ctx && id);
/* check id syntax */
if (!(id[0] >= 'A' && id[0] <= 'Z') && !(id[0] >= 'a' && id[0] <= 'z') && id[0] != '_') {
LOGVAL(ctx, LYE_INID, LY_VLOG_NONE, NULL, id, "invalid start character");
return EXIT_FAILURE;
}
for (i = 1; id[i]; i++) {
if (!(id[i] >= 'A' && id[i] <= 'Z') && !(id[i] >= 'a' && id[i] <= 'z')
&& !(id[i] >= '0' && id[i] <= '9') && id[i] != '_' && id[i] != '-' && id[i] != '.') {
LOGVAL(ctx, LYE_INID, LY_VLOG_NONE, NULL, id, "invalid character");
return EXIT_FAILURE;
}
}
if (i > 64) {
LOGWRN(ctx, "Identifier \"%s\" is long, you should use something shorter.", id);
}
switch (type) {
case LY_IDENT_NAME:
/* check uniqueness of the node within its siblings */
if (!parent) {
break;
}
LY_TREE_FOR(parent->child, node) {
if (ly_strequal(node->name, id, 1)) {
LOGVAL(ctx, LYE_INID, LY_VLOG_NONE, NULL, id, "name duplication");
return EXIT_FAILURE;
}
}
break;
case LY_IDENT_TYPE:
assert(module);
mainmod = lys_main_module(module);
/* check collision with the built-in types */
if (!strcmp(id, "binary") || !strcmp(id, "bits") ||
!strcmp(id, "boolean") || !strcmp(id, "decimal64") ||
!strcmp(id, "empty") || !strcmp(id, "enumeration") ||
!strcmp(id, "identityref") || !strcmp(id, "instance-identifier") ||
!strcmp(id, "int8") || !strcmp(id, "int16") ||
!strcmp(id, "int32") || !strcmp(id, "int64") ||
!strcmp(id, "leafref") || !strcmp(id, "string") ||
!strcmp(id, "uint8") || !strcmp(id, "uint16") ||
!strcmp(id, "uint32") || !strcmp(id, "uint64") || !strcmp(id, "union")) {
LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, id, "typedef");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Typedef name duplicates a built-in type.");
return EXIT_FAILURE;
}
/* check locally scoped typedefs (avoid name shadowing) */
for (; parent; parent = lys_parent(parent)) {
switch (parent->nodetype) {
case LYS_CONTAINER:
size = ((struct lys_node_container *)parent)->tpdf_size;
tpdf = ((struct lys_node_container *)parent)->tpdf;
break;
case LYS_LIST:
size = ((struct lys_node_list *)parent)->tpdf_size;
tpdf = ((struct lys_node_list *)parent)->tpdf;
break;
case LYS_GROUPING:
size = ((struct lys_node_grp *)parent)->tpdf_size;
tpdf = ((struct lys_node_grp *)parent)->tpdf;
break;
default:
continue;
}
if (dup_typedef_check(id, tpdf, size)) {
LOGVAL(ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "typedef", id);
return EXIT_FAILURE;
}
}
/* check top-level names */
if (dup_typedef_check(id, module->tpdf, module->tpdf_size)) {
LOGVAL(ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "typedef", id);
return EXIT_FAILURE;
}
/* check submodule's top-level names */
for (i = 0; i < mainmod->inc_size && mainmod->inc[i].submodule; i++) {
if (dup_typedef_check(id, mainmod->inc[i].submodule->tpdf, mainmod->inc[i].submodule->tpdf_size)) {
LOGVAL(ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "typedef", id);
return EXIT_FAILURE;
}
}
break;
case LY_IDENT_PREFIX:
assert(module);
/* check the module itself */
if (dup_prefix_check(id, module)) {
LOGVAL(ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "prefix", id);
return EXIT_FAILURE;
}
break;
case LY_IDENT_FEATURE:
assert(module);
mainmod = lys_main_module(module);
/* check feature name uniqueness*/
/* check features in the current module */
if (dup_feature_check(id, module)) {
LOGVAL(ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "feature", id);
return EXIT_FAILURE;
}
/* and all its submodules */
for (i = 0; i < mainmod->inc_size && mainmod->inc[i].submodule; i++) {
if (dup_feature_check(id, (struct lys_module *)mainmod->inc[i].submodule)) {
LOGVAL(ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "feature", id);
return EXIT_FAILURE;
}
}
break;
case LY_IDENT_EXTENSION:
assert(module);
mainmod = lys_main_module(module);
/* check extension name uniqueness in the main module ... */
for (i = 0; i < mainmod->extensions_size; i++) {
if (ly_strequal(id, mainmod->extensions[i].name, 1)) {
LOGVAL(ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "extension", id);
return EXIT_FAILURE;
}
}
/* ... and all its submodules */
for (j = 0; j < mainmod->inc_size && mainmod->inc[j].submodule; j++) {
submod = mainmod->inc[j].submodule; /* shortcut */
for (i = 0; i < submod->extensions_size; i++) {
if (ly_strequal(id, submod->extensions[i].name, 1)) {
LOGVAL(ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "extension", id);
return EXIT_FAILURE;
}
}
}
break;
default:
/* no check required */
break;
}
return EXIT_SUCCESS;
}
/* logs directly */
int
lyp_check_date(struct ly_ctx *ctx, const char *date)
{
int i;
struct tm tm, tm_;
char *r;
assert(date);
/* check format */
for (i = 0; i < LY_REV_SIZE - 1; i++) {
if (i == 4 || i == 7) {
if (date[i] != '-') {
goto error;
}
} else if (!isdigit(date[i])) {
goto error;
}
}
/* check content, e.g. 2018-02-31 */
memset(&tm, 0, sizeof tm);
r = strptime(date, "%Y-%m-%d", &tm);
if (!r || r != &date[LY_REV_SIZE - 1]) {
goto error;
}
/* set some arbitrary non-0 value in case DST changes, it could move the day otherwise */
tm.tm_hour = 12;
memcpy(&tm_, &tm, sizeof tm);
mktime(&tm_); /* mktime modifies tm_ if it refers invalid date */
if (tm.tm_mday != tm_.tm_mday) { /* e.g 2018-02-29 -> 2018-03-01 */
/* checking days is enough, since other errors
* have been checked by strptime() */
goto error;
}
return EXIT_SUCCESS;
error:
LOGVAL(ctx, LYE_INDATE, LY_VLOG_NONE, NULL, date);
return EXIT_FAILURE;
}
/**
* @return
* NULL - success
* root - not yet resolvable
* other node - mandatory node under the root
*/
static const struct lys_node *
lyp_check_mandatory_(const struct lys_node *root)
{
int mand_flag = 0;
const struct lys_node *iter = NULL;
while ((iter = lys_getnext(iter, root, NULL, LYS_GETNEXT_WITHCHOICE | LYS_GETNEXT_WITHUSES | LYS_GETNEXT_INTOUSES
| LYS_GETNEXT_INTONPCONT | LYS_GETNEXT_NOSTATECHECK))) {
if (iter->nodetype == LYS_USES) {
if (!((struct lys_node_uses *)iter)->grp) {
/* not yet resolved uses */
return root;
} else {
/* go into uses */
continue;
}
}
if (iter->nodetype == LYS_CHOICE) {
/* skip it, it was already checked for direct mandatory node in default */
continue;
}
if (iter->nodetype == LYS_LIST) {
if (((struct lys_node_list *)iter)->min) {
mand_flag = 1;
}
} else if (iter->nodetype == LYS_LEAFLIST) {
if (((struct lys_node_leaflist *)iter)->min) {
mand_flag = 1;
}
} else if (iter->flags & LYS_MAND_TRUE) {
mand_flag = 1;
}
if (mand_flag) {
return iter;
}
}
return NULL;
}
/* logs directly */
int
lyp_check_mandatory_augment(struct lys_node_augment *aug, const struct lys_node *target)
{
const struct lys_node *node;
if (aug->when || target->nodetype == LYS_CHOICE) {
/* - mandatory nodes in new cases are ok;
* clarification from YANG 1.1 - augmentation can add mandatory nodes when it is
* conditional with a when statement */
return EXIT_SUCCESS;
}
if ((node = lyp_check_mandatory_((struct lys_node *)aug))) {
if (node != (struct lys_node *)aug) {
LOGVAL(target->module->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "mandatory");
LOGVAL(target->module->ctx, LYE_SPEC, LY_VLOG_NONE, NULL,
"Mandatory node \"%s\" appears in augment of \"%s\" without when condition.",
node->name, aug->target_name);
return -1;
}
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
/**
* @brief check that a mandatory node is not directly under the default case.
* @param[in] node choice with default node
* @return EXIT_SUCCESS if the constraint is fulfilled, EXIT_FAILURE otherwise
*/
int
lyp_check_mandatory_choice(struct lys_node *node)
{
const struct lys_node *mand, *dflt = ((struct lys_node_choice *)node)->dflt;
if ((mand = lyp_check_mandatory_(dflt))) {
if (mand != dflt) {
LOGVAL(node->module->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "mandatory");
LOGVAL(node->module->ctx, LYE_SPEC, LY_VLOG_NONE, NULL,
"Mandatory node \"%s\" is directly under the default case \"%s\" of the \"%s\" choice.",
mand->name, dflt->name, node->name);
return -1;
}
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
/**
* @brief Check status for invalid combination.
*
* @param[in] flags1 Flags of the referencing node.
* @param[in] mod1 Module of the referencing node,
* @param[in] name1 Schema node name of the referencing node.
* @param[in] flags2 Flags of the referenced node.
* @param[in] mod2 Module of the referenced node,
* @param[in] name2 Schema node name of the referenced node.
* @return EXIT_SUCCES on success, EXIT_FAILURE on invalid reference.
*/
int
lyp_check_status(uint16_t flags1, struct lys_module *mod1, const char *name1,
uint16_t flags2, struct lys_module *mod2, const char *name2,
const struct lys_node *node)
{
uint16_t flg1, flg2;
flg1 = (flags1 & LYS_STATUS_MASK) ? (flags1 & LYS_STATUS_MASK) : LYS_STATUS_CURR;
flg2 = (flags2 & LYS_STATUS_MASK) ? (flags2 & LYS_STATUS_MASK) : LYS_STATUS_CURR;
if ((flg1 < flg2) && (lys_main_module(mod1) == lys_main_module(mod2))) {
LOGVAL(mod1->ctx, LYE_INSTATUS, node ? LY_VLOG_LYS : LY_VLOG_NONE, node,
flg1 == LYS_STATUS_CURR ? "current" : "deprecated", name1, "references",
flg2 == LYS_STATUS_OBSLT ? "obsolete" : "deprecated", name2);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
void
lyp_del_includedup(struct lys_module *mod, int free_subs)
{
struct ly_modules_list *models = &mod->ctx->models;
uint8_t i;
assert(mod && !mod->type);
if (models->parsed_submodules_count) {
for (i = models->parsed_submodules_count - 1; models->parsed_submodules[i]->type; --i);
if (models->parsed_submodules[i] == mod) {
if (free_subs) {
for (i = models->parsed_submodules_count - 1; models->parsed_submodules[i]->type; --i) {
lys_sub_module_remove_devs_augs((struct lys_module *)models->parsed_submodules[i]);
lys_submodule_module_data_free((struct lys_submodule *)models->parsed_submodules[i]);
lys_submodule_free((struct lys_submodule *)models->parsed_submodules[i], NULL);
}
}
models->parsed_submodules_count = i;
if (!models->parsed_submodules_count) {
free(models->parsed_submodules);
models->parsed_submodules = NULL;
}
}
}
}
static void
lyp_add_includedup(struct lys_module *sub_mod, struct lys_submodule *parsed_submod)
{
struct ly_modules_list *models = &sub_mod->ctx->models;
int16_t i;
/* store main module if first include */
if (models->parsed_submodules_count) {
for (i = models->parsed_submodules_count - 1; models->parsed_submodules[i]->type; --i);
} else {
i = -1;
}
if ((i == -1) || (models->parsed_submodules[i] != lys_main_module(sub_mod))) {
++models->parsed_submodules_count;
models->parsed_submodules = ly_realloc(models->parsed_submodules,
models->parsed_submodules_count * sizeof *models->parsed_submodules);
LY_CHECK_ERR_RETURN(!models->parsed_submodules, LOGMEM(sub_mod->ctx), );
models->parsed_submodules[models->parsed_submodules_count - 1] = lys_main_module(sub_mod);
}
/* store parsed submodule */
++models->parsed_submodules_count;
models->parsed_submodules = ly_realloc(models->parsed_submodules,
models->parsed_submodules_count * sizeof *models->parsed_submodules);
LY_CHECK_ERR_RETURN(!models->parsed_submodules, LOGMEM(sub_mod->ctx), );
models->parsed_submodules[models->parsed_submodules_count - 1] = (struct lys_module *)parsed_submod;
}
/*
* types: 0 - include, 1 - import
*/
static int
lyp_check_circmod(struct lys_module *module, const char *value, int type)
{
LY_ECODE code = type ? LYE_CIRC_IMPORTS : LYE_CIRC_INCLUDES;
struct ly_modules_list *models = &module->ctx->models;
uint8_t i;
/* include/import itself */
if (ly_strequal(module->name, value, 1)) {
LOGVAL(module->ctx, code, LY_VLOG_NONE, NULL, value);
return -1;
}
/* currently parsed modules */
for (i = 0; i < models->parsing_sub_modules_count; i++) {
if (ly_strequal(models->parsing_sub_modules[i]->name, value, 1)) {
LOGVAL(module->ctx, code, LY_VLOG_NONE, NULL, value);
return -1;
}
}
return 0;
}
int
lyp_check_circmod_add(struct lys_module *module)
{
struct ly_modules_list *models = &module->ctx->models;
/* storing - enlarge the list of modules being currently parsed */
++models->parsing_sub_modules_count;
models->parsing_sub_modules = ly_realloc(models->parsing_sub_modules,
models->parsing_sub_modules_count * sizeof *models->parsing_sub_modules);
LY_CHECK_ERR_RETURN(!models->parsing_sub_modules, LOGMEM(module->ctx), -1);
models->parsing_sub_modules[models->parsing_sub_modules_count - 1] = module;
return 0;
}
void
lyp_check_circmod_pop(struct ly_ctx *ctx)
{
if (!ctx->models.parsing_sub_modules_count) {
LOGINT(ctx);
return;
}
/* update the list of currently being parsed modules */
ctx->models.parsing_sub_modules_count--;
if (!ctx->models.parsing_sub_modules_count) {
free(ctx->models.parsing_sub_modules);
ctx->models.parsing_sub_modules = NULL;
}
}
/*
* -1 - error - invalid duplicities)
* 0 - success, no duplicity
* 1 - success, valid duplicity found and stored in *sub
*/
static int
lyp_check_includedup(struct lys_module *mod, const char *name, struct lys_include *inc, struct lys_submodule **sub)
{
struct lys_module **parsed_sub = mod->ctx->models.parsed_submodules;
uint8_t i, parsed_sub_count = mod->ctx->models.parsed_submodules_count;
assert(sub);
for (i = 0; i < mod->inc_size; ++i) {
if (ly_strequal(mod->inc[i].submodule->name, name, 1)) {
/* the same module is already included in the same module - error */
LOGVAL(mod->ctx, LYE_INARG, LY_VLOG_NONE, NULL, name, "include");
LOGVAL(mod->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Submodule \"%s\" included twice in the same module \"%s\".",
name, mod->name);
return -1;
}
}
if (parsed_sub_count) {
assert(!parsed_sub[0]->type);
for (i = parsed_sub_count - 1; parsed_sub[i]->type; --i) {
if (ly_strequal(parsed_sub[i]->name, name, 1)) {
/* check revisions, including multiple revisions of a single module is error */
if (inc->rev[0] && (!parsed_sub[i]->rev_size || strcmp(parsed_sub[i]->rev[0].date, inc->rev))) {
/* the already included submodule has
* - no revision, but here we require some
* - different revision than the one required here */
LOGVAL(mod->ctx, LYE_INARG, LY_VLOG_NONE, NULL, name, "include");
LOGVAL(mod->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Including multiple revisions of submodule \"%s\".", name);
return -1;
}
/* the same module is already included in some other submodule, return it */
(*sub) = (struct lys_submodule *)parsed_sub[i];
return 1;
}
}
}
/* no duplicity found */
return 0;
}
/* returns:
* 0 - inc successfully filled
* -1 - error
*/
int
lyp_check_include(struct lys_module *module, const char *value, struct lys_include *inc, struct unres_schema *unres)
{
int i;
/* check that the submodule was not included yet */
i = lyp_check_includedup(module, value, inc, &inc->submodule);
if (i == -1) {
return -1;
} else if (i == 1) {
return 0;
}
/* submodule is not yet loaded */
/* circular include check */
if (lyp_check_circmod(module, value, 0)) {
return -1;
}
/* try to load the submodule */
inc->submodule = (struct lys_submodule *)ly_ctx_load_sub_module(module->ctx, module, value,
inc->rev[0] ? inc->rev : NULL, 1, unres);
/* check the result */
if (!inc->submodule) {
if (ly_errno != LY_EVALID) {
LOGVAL(module->ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "include");
}
LOGERR(module->ctx, LY_EVALID, "Including \"%s\" module into \"%s\" failed.", value, module->name);
return -1;
}
/* check the revision */
if (inc->rev[0] && inc->submodule->rev_size && strcmp(inc->rev, inc->submodule->rev[0].date)) {
LOGERR(module->ctx, LY_EVALID, "\"%s\" include of submodule \"%s\" in revision \"%s\" not found.",
module->name, value, inc->rev);
unres_schema_free((struct lys_module *)inc->submodule, &unres, 0);
lys_sub_module_remove_devs_augs((struct lys_module *)inc->submodule);
lys_submodule_module_data_free((struct lys_submodule *)inc->submodule);
lys_submodule_free(inc->submodule, NULL);
inc->submodule = NULL;
return -1;
}
/* store the submodule as successfully parsed */
lyp_add_includedup(module, inc->submodule);
return 0;
}
static int
lyp_check_include_missing_recursive(struct lys_module *main_module, struct lys_submodule *sub)
{
uint8_t i, j;
void *reallocated;
int ret = 0, tmp;
struct ly_ctx *ctx = main_module->ctx;
for (i = 0; i < sub->inc_size; i++) {
/* check that the include is also present in the main module */
for (j = 0; j < main_module->inc_size; j++) {
if (main_module->inc[j].submodule == sub->inc[i].submodule) {
break;
}
}
if (j == main_module->inc_size) {
/* match not found */
if (main_module->version >= LYS_VERSION_1_1) {
LOGVAL(ctx, LYE_MISSSTMT, LY_VLOG_NONE, NULL, "include");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL,
"The main module \"%s\" misses include of the \"%s\" submodule used in another submodule \"%s\".",
main_module->name, sub->inc[i].submodule->name, sub->name);
/* now we should return error, but due to the issues with freeing the module, we actually have
* to go through the all includes and, as in case of 1.0, add them into the main module and fail
* at the end when all the includes are in the main module and we can free them */
ret = 1;
} else {
/* not strictly an error in YANG 1.0 */
LOGWRN(ctx, "The main module \"%s\" misses include of the \"%s\" submodule used in another submodule \"%s\".",
main_module->name, sub->inc[i].submodule->name, sub->name);
LOGWRN(ctx, "To avoid further issues, adding submodule \"%s\" into the main module \"%s\".",
sub->inc[i].submodule->name, main_module->name);
/* but since it is a good practise and because we expect all the includes in the main module
* when searching it and also when freeing the module, put it into it */
}
main_module->inc_size++;
reallocated = realloc(main_module->inc, main_module->inc_size * sizeof *main_module->inc);
LY_CHECK_ERR_RETURN(!reallocated, LOGMEM(ctx), 1);
main_module->inc = reallocated;
memset(&main_module->inc[main_module->inc_size - 1], 0, sizeof *main_module->inc);
/* to avoid unexpected consequences, copy just a link to the submodule and the revision,
* all other substatements of the include are ignored */
memcpy(&main_module->inc[main_module->inc_size - 1].rev, sub->inc[i].rev, LY_REV_SIZE - 1);
main_module->inc[main_module->inc_size - 1].submodule = sub->inc[i].submodule;
}
/* recursion */
tmp = lyp_check_include_missing_recursive(main_module, sub->inc[i].submodule);
if (!ret && tmp) {
ret = 1;
}
}
return ret;
}
int
lyp_check_include_missing(struct lys_module *main_module)
{
int ret = 0;
uint8_t i;
/* in YANG 1.1, all the submodules must be in the main module, check it even for
* 1.0 where it will be printed as warning and the include will be added into the main module */
for (i = 0; i < main_module->inc_size; i++) {
if (lyp_check_include_missing_recursive(main_module, main_module->inc[i].submodule)) {
ret = 1;
}
}
return ret;
}
/* returns:
* 0 - imp successfully filled
* -1 - error, imp not cleaned
*/
int
lyp_check_import(struct lys_module *module, const char *value, struct lys_import *imp)
{
int i;
struct lys_module *dup = NULL;
struct ly_ctx *ctx = module->ctx;
/* check for importing a single module in multiple revisions */
for (i = 0; i < module->imp_size; i++) {
if (!module->imp[i].module) {
/* skip the not yet filled records */
continue;
}
if (ly_strequal(module->imp[i].module->name, value, 1)) {
/* check revisions, including multiple revisions of a single module is error */
if (imp->rev[0] && (!module->imp[i].module->rev_size || strcmp(module->imp[i].module->rev[0].date, imp->rev))) {
/* the already imported module has
* - no revision, but here we require some
* - different revision than the one required here */
LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "import");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Importing multiple revisions of module \"%s\".", value);
return -1;
} else if (!imp->rev[0]) {
/* no revision, remember the duplication, but check revisions after loading the module
* because the current revision can be the same (then it is ok) or it can differ (then it
* is error */
dup = module->imp[i].module;
break;
}
/* there is duplication, but since prefixes differs (checked in caller of this function),
* it is ok */
imp->module = module->imp[i].module;
return 0;
}
}
/* circular import check */
if (lyp_check_circmod(module, value, 1)) {
return -1;
}
/* load module - in specific situations it tries to get the module from the context */
imp->module = (struct lys_module *)ly_ctx_load_sub_module(module->ctx, NULL, value, imp->rev[0] ? imp->rev : NULL,
module->ctx->models.flags & LY_CTX_ALLIMPLEMENTED ? 1 : 0,
NULL);
/* check the result */
if (!imp->module) {
LOGERR(ctx, LY_EVALID, "Importing \"%s\" module into \"%s\" failed.", value, module->name);
return -1;
}
if (imp->rev[0] && imp->module->rev_size && strcmp(imp->rev, imp->module->rev[0].date)) {
LOGERR(ctx, LY_EVALID, "\"%s\" import of module \"%s\" in revision \"%s\" not found.",
module->name, value, imp->rev);
return -1;
}
if (dup) {
/* check the revisions */
if ((dup != imp->module) ||
(dup->rev_size != imp->module->rev_size && (!dup->rev_size || imp->module->rev_size)) ||
(dup->rev_size && strcmp(dup->rev[0].date, imp->module->rev[0].date))) {
/* - modules are not the same
* - one of modules has no revision (except they both has no revision)
* - revisions of the modules are not the same */
LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "import");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Importing multiple revisions of module \"%s\".", value);
return -1;
} else {
LOGWRN(ctx, "Module \"%s\" is imported by \"%s\" multiple times with different prefixes.", dup->name, module->name);
}
}
return 0;
}
/*
* put the newest revision to the first position
*/
void
lyp_sort_revisions(struct lys_module *module)
{
uint8_t i, r;
struct lys_revision rev;
for (i = 1, r = 0; i < module->rev_size; i++) {
if (strcmp(module->rev[i].date, module->rev[r].date) > 0) {
r = i;
}
}
if (r) {
/* the newest revision is not on position 0, switch them */
memcpy(&rev, &module->rev[0], sizeof rev);
memcpy(&module->rev[0], &module->rev[r], sizeof rev);
memcpy(&module->rev[r], &rev, sizeof rev);
}
}
void
lyp_ext_instance_rm(struct ly_ctx *ctx, struct lys_ext_instance ***ext, uint8_t *size, uint8_t index)
{
uint8_t i;
lys_extension_instances_free(ctx, (*ext)[index]->ext, (*ext)[index]->ext_size, NULL);
lydict_remove(ctx, (*ext)[index]->arg_value);
free((*ext)[index]);
/* move the rest of the array */
for (i = index + 1; i < (*size); i++) {
(*ext)[i - 1] = (*ext)[i];
}
/* clean the last cell in the array structure */
(*ext)[(*size) - 1] = NULL;
/* the array is not reallocated here, just change its size */
(*size) = (*size) - 1;
if (!(*size)) {
/* ext array is empty */
free((*ext));
ext = NULL;
}
}
static int
lyp_rfn_apply_ext_(struct lys_refine *rfn, struct lys_node *target, LYEXT_SUBSTMT substmt, struct lys_ext *extdef)
{
struct ly_ctx *ctx;
int m, n;
struct lys_ext_instance *new;
void *reallocated;
ctx = target->module->ctx; /* shortcut */
m = n = -1;
while ((m = lys_ext_iter(rfn->ext, rfn->ext_size, m + 1, substmt)) != -1) {
/* refine's substatement includes extensions, copy them to the target, replacing the previous
* substatement's extensions if any. In case of refining the extension itself, we are going to
* replace only the same extension (pointing to the same definition) */
if (substmt == LYEXT_SUBSTMT_SELF && rfn->ext[m]->def != extdef) {
continue;
}
/* get the index of the extension to replace in the target node */
do {
n = lys_ext_iter(target->ext, target->ext_size, n + 1, substmt);
} while (n != -1 && substmt == LYEXT_SUBSTMT_SELF && target->ext[n]->def != extdef);
/* TODO cover complex extension instances */
if (n == -1) {
/* nothing to replace, we are going to add it - reallocate */
new = malloc(sizeof **target->ext);
LY_CHECK_ERR_RETURN(!new, LOGMEM(ctx), EXIT_FAILURE);
reallocated = realloc(target->ext, (target->ext_size + 1) * sizeof *target->ext);
LY_CHECK_ERR_RETURN(!reallocated, LOGMEM(ctx); free(new), EXIT_FAILURE);
target->ext = reallocated;
target->ext_size++;
/* init */
n = target->ext_size - 1;
target->ext[n] = new;
target->ext[n]->parent = target;
target->ext[n]->parent_type = LYEXT_PAR_NODE;
target->ext[n]->flags = 0;
target->ext[n]->insubstmt = substmt;
target->ext[n]->priv = NULL;
target->ext[n]->nodetype = LYS_EXT;
target->ext[n]->module = target->module;
} else {
/* replacing - first remove the allocated data from target */
lys_extension_instances_free(ctx, target->ext[n]->ext, target->ext[n]->ext_size, NULL);
lydict_remove(ctx, target->ext[n]->arg_value);
}
/* common part for adding and replacing */
target->ext[n]->def = rfn->ext[m]->def;
/* parent and parent_type do not change */
target->ext[n]->arg_value = lydict_insert(ctx, rfn->ext[m]->arg_value, 0);
/* flags do not change */
target->ext[n]->ext_size = rfn->ext[m]->ext_size;
lys_ext_dup(ctx, target->module, rfn->ext[m]->ext, rfn->ext[m]->ext_size, target, LYEXT_PAR_NODE,
&target->ext[n]->ext, 0, NULL);
/* substmt does not change, but the index must be taken from the refine */
target->ext[n]->insubstmt_index = rfn->ext[m]->insubstmt_index;
}
/* remove the rest of extensions belonging to the original substatement in the target node */
while ((n = lys_ext_iter(target->ext, target->ext_size, n + 1, substmt)) != -1) {
if (substmt == LYEXT_SUBSTMT_SELF && target->ext[n]->def != extdef) {
/* keep this extension */
continue;
}
/* remove the item */
lyp_ext_instance_rm(ctx, &target->ext, &target->ext_size, n);
--n;
}
return EXIT_SUCCESS;
}
/*
* apply extension instances defined under refine's substatements.
* It cannot be done immediately when applying the refine because there can be
* still unresolved data (e.g. type) and mainly the targeted extension instances.
*/
int
lyp_rfn_apply_ext(struct lys_module *module)
{
int i, k, a = 0;
struct lys_node *root, *nextroot, *next, *node;
struct lys_node *target;
struct lys_node_uses *uses;
struct lys_refine *rfn;
struct ly_set *extset;
/* refines in uses */
LY_TREE_FOR_SAFE(module->data, nextroot, root) {
/* go through the data tree of the module and all the defined augments */
LY_TREE_DFS_BEGIN(root, next, node) {
if (node->nodetype == LYS_USES) {
uses = (struct lys_node_uses *)node;
for (i = 0; i < uses->refine_size; i++) {
if (!uses->refine[i].ext_size) {
/* no extensions in refine */
continue;
}
rfn = &uses->refine[i]; /* shortcut */
/* get the target node */
target = NULL;
resolve_descendant_schema_nodeid(rfn->target_name, uses->child,
LYS_NO_RPC_NOTIF_NODE | LYS_ACTION | LYS_NOTIF,
0, (const struct lys_node **)&target);
if (!target) {
/* it should always succeed since the target_name was already resolved at least
* once when the refine itself was being resolved */
LOGINT(module->ctx);;
return EXIT_FAILURE;
}
/* extensions */
extset = ly_set_new();
k = -1;
while ((k = lys_ext_iter(rfn->ext, rfn->ext_size, k + 1, LYEXT_SUBSTMT_SELF)) != -1) {
ly_set_add(extset, rfn->ext[k]->def, 0);
}
for (k = 0; (unsigned int)k < extset->number; k++) {
if (lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_SELF, (struct lys_ext *)extset->set.g[k])) {
ly_set_free(extset);
return EXIT_FAILURE;
}
}
ly_set_free(extset);
/* description */
if (rfn->dsc && lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_DESCRIPTION, NULL)) {
return EXIT_FAILURE;
}
/* reference */
if (rfn->ref && lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_REFERENCE, NULL)) {
return EXIT_FAILURE;
}
/* config, in case of notification or rpc/action{notif, the config is not applicable
* (there is no config status) */
if ((rfn->flags & LYS_CONFIG_MASK) && (target->flags & LYS_CONFIG_MASK)) {
if (lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_CONFIG, NULL)) {
return EXIT_FAILURE;
}
}
/* default value */
if (rfn->dflt_size && lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_DEFAULT, NULL)) {
return EXIT_FAILURE;
}
/* mandatory */
if (rfn->flags & LYS_MAND_MASK) {
if (lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_MANDATORY, NULL)) {
return EXIT_FAILURE;
}
}
/* presence */
if ((target->nodetype & LYS_CONTAINER) && rfn->mod.presence) {
if (lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_PRESENCE, NULL)) {
return EXIT_FAILURE;
}
}
/* min/max */
if (rfn->flags & LYS_RFN_MINSET) {
if (lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_MIN, NULL)) {
return EXIT_FAILURE;
}
}
if (rfn->flags & LYS_RFN_MAXSET) {
if (lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_MAX, NULL)) {
return EXIT_FAILURE;
}
}
/* must and if-feature contain extensions on their own, not needed to be solved here */
if (target->ext_size) {
/* the allocated target's extension array can be now longer than needed in case
* there is less refine substatement's extensions than in original. Since we are
* going to reduce or keep the same memory, it is not necessary to test realloc's result */
target->ext = realloc(target->ext, target->ext_size * sizeof *target->ext);
}
}
}
LY_TREE_DFS_END(root, next, node)
}
if (!nextroot && a < module->augment_size) {
nextroot = module->augment[a].child;
a++;
}
}
return EXIT_SUCCESS;
}
/*
* check mandatory substatements defined under extension instances.
*/
int
lyp_mand_check_ext(struct lys_ext_instance_complex *ext, const char *ext_name)
{
void *p;
int i;
struct ly_ctx *ctx = ext->module->ctx;
/* check for mandatory substatements */
for (i = 0; ext->substmt[i].stmt; i++) {
if (ext->substmt[i].cardinality == LY_STMT_CARD_OPT || ext->substmt[i].cardinality == LY_STMT_CARD_ANY) {
/* not a mandatory */
continue;
} else if (ext->substmt[i].cardinality == LY_STMT_CARD_SOME) {
goto array;
}
/*
* LY_STMT_ORDEREDBY - not checked, has a default value which is the same as explicit system order
* LY_STMT_MODIFIER, LY_STMT_STATUS, LY_STMT_MANDATORY, LY_STMT_CONFIG - checked, but mandatory requirement
* does not make sense since there is also a default value specified
*/
switch(ext->substmt[i].stmt) {
case LY_STMT_ORDEREDBY:
/* always ok */
break;
case LY_STMT_REQINSTANCE:
case LY_STMT_DIGITS:
case LY_STMT_MODIFIER:
p = lys_ext_complex_get_substmt(ext->substmt[i].stmt, ext, NULL);
if (!*(uint8_t*)p) {
LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, ly_stmt_str[ext->substmt[i].stmt], ext_name);
goto error;
}
break;
case LY_STMT_STATUS:
p = lys_ext_complex_get_substmt(ext->substmt[i].stmt, ext, NULL);
if (!(*(uint16_t*)p & LYS_STATUS_MASK)) {
LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, ly_stmt_str[ext->substmt[i].stmt], ext_name);
goto error;
}
break;
case LY_STMT_MANDATORY:
p = lys_ext_complex_get_substmt(ext->substmt[i].stmt, ext, NULL);
if (!(*(uint16_t*)p & LYS_MAND_MASK)) {
LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, ly_stmt_str[ext->substmt[i].stmt], ext_name);
goto error;
}
break;
case LY_STMT_CONFIG:
p = lys_ext_complex_get_substmt(ext->substmt[i].stmt, ext, NULL);
if (!(*(uint16_t*)p & LYS_CONFIG_MASK)) {
LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, ly_stmt_str[ext->substmt[i].stmt], ext_name);
goto error;
}
break;
default:
array:
/* stored as a pointer */
p = lys_ext_complex_get_substmt(ext->substmt[i].stmt, ext, NULL);
if (!(*(void**)p)) {
LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, ly_stmt_str[ext->substmt[i].stmt], ext_name);
goto error;
}
break;
}
}
return EXIT_SUCCESS;
error:
return EXIT_FAILURE;
}
static int
lyp_deviate_del_ext(struct lys_node *target, struct lys_ext_instance *ext)
{
int n = -1, found = 0;
char *path;
while ((n = lys_ext_iter(target->ext, target->ext_size, n + 1, ext->insubstmt)) != -1) {
if (target->ext[n]->def != ext->def) {
continue;
}
if (ext->def->argument) {
/* check matching arguments */
if (!ly_strequal(target->ext[n]->arg_value, ext->arg_value, 1)) {
continue;
}
}
/* we have the matching extension - remove it */
++found;
lyp_ext_instance_rm(target->module->ctx, &target->ext, &target->ext_size, n);
--n;
}
if (!found) {
path = lys_path(target, LYS_PATH_FIRST_PREFIX);
LOGERR(target->module->ctx, LY_EVALID, "Extension deviation: extension \"%s\" to delete not found in \"%s\".",
ext->def->name, path)
free(path);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
static int
lyp_deviate_apply_ext(struct lys_deviate *dev, struct lys_node *target, LYEXT_SUBSTMT substmt, struct lys_ext *extdef)
{
struct ly_ctx *ctx;
int m, n;
struct lys_ext_instance *new;
void *reallocated;
/* LY_DEVIATE_ADD and LY_DEVIATE_RPL are very similar so they are implement the same way - in replacing,
* there can be some extension instances in the target, in case of adding, there should not be any so we
* will be just adding. */
ctx = target->module->ctx; /* shortcut */
m = n = -1;
while ((m = lys_ext_iter(dev->ext, dev->ext_size, m + 1, substmt)) != -1) {
/* deviate and its substatements include extensions, copy them to the target, replacing the previous
* extensions if any. In case of deviating extension itself, we have to deviate only the same type
* of the extension as specified in the deviation */
if (substmt == LYEXT_SUBSTMT_SELF && dev->ext[m]->def != extdef) {
continue;
}
if (substmt == LYEXT_SUBSTMT_SELF && dev->mod == LY_DEVIATE_ADD) {
/* in case of adding extension, we will be replacing only the inherited extensions */
do {
n = lys_ext_iter(target->ext, target->ext_size, n + 1, substmt);
} while (n != -1 && (target->ext[n]->def != extdef || !(target->ext[n]->flags & LYEXT_OPT_INHERIT)));
} else {
/* get the index of the extension to replace in the target node */
do {
n = lys_ext_iter(target->ext, target->ext_size, n + 1, substmt);
/* if we are applying extension deviation, we have to deviate only the same type of the extension */
} while (n != -1 && substmt == LYEXT_SUBSTMT_SELF && target->ext[n]->def != extdef);
}
if (n == -1) {
/* nothing to replace, we are going to add it - reallocate */
new = malloc(sizeof **target->ext);
LY_CHECK_ERR_RETURN(!new, LOGMEM(ctx), EXIT_FAILURE);
reallocated = realloc(target->ext, (target->ext_size + 1) * sizeof *target->ext);
LY_CHECK_ERR_RETURN(!reallocated, LOGMEM(ctx); free(new), EXIT_FAILURE);
target->ext = reallocated;
target->ext_size++;
n = target->ext_size - 1;
} else {
/* replacing - the original set of extensions is actually backuped together with the
* node itself, so we are supposed only to free the allocated data here ... */
lys_extension_instances_free(ctx, target->ext[n]->ext, target->ext[n]->ext_size, NULL);
lydict_remove(ctx, target->ext[n]->arg_value);
free(target->ext[n]);
/* and prepare the new structure */
new = malloc(sizeof **target->ext);
LY_CHECK_ERR_RETURN(!new, LOGMEM(ctx), EXIT_FAILURE);
}
/* common part for adding and replacing - fill the newly created / replaced cell */
target->ext[n] = new;
target->ext[n]->def = dev->ext[m]->def;
target->ext[n]->arg_value = lydict_insert(ctx, dev->ext[m]->arg_value, 0);
target->ext[n]->flags = 0;
target->ext[n]->parent = target;
target->ext[n]->parent_type = LYEXT_PAR_NODE;
target->ext[n]->insubstmt = substmt;
target->ext[n]->insubstmt_index = dev->ext[m]->insubstmt_index;
target->ext[n]->ext_size = dev->ext[m]->ext_size;
lys_ext_dup(ctx, target->module, dev->ext[m]->ext, dev->ext[m]->ext_size, target, LYEXT_PAR_NODE,
&target->ext[n]->ext, 1, NULL);
target->ext[n]->nodetype = LYS_EXT;
target->ext[n]->module = target->module;
target->ext[n]->priv = NULL;
/* TODO cover complex extension instances */
}
/* remove the rest of extensions belonging to the original substatement in the target node,
* due to possible reverting of the deviation effect, they are actually not removed, just moved
* to the backup of the original node when the original node is backuped, here we just have to
* free the replaced / deleted originals */
while ((n = lys_ext_iter(target->ext, target->ext_size, n + 1, substmt)) != -1) {
if (substmt == LYEXT_SUBSTMT_SELF) {
/* if we are applying extension deviation, we are going to remove only
* - the same type of the extension in case of replacing
* - the same type of the extension which was inherited in case of adding
* note - delete deviation is covered in lyp_deviate_del_ext */
if (target->ext[n]->def != extdef ||
(dev->mod == LY_DEVIATE_ADD && !(target->ext[n]->flags & LYEXT_OPT_INHERIT))) {
/* keep this extension */
continue;
}
}
/* remove the item */
lyp_ext_instance_rm(ctx, &target->ext, &target->ext_size, n);
--n;
}
return EXIT_SUCCESS;
}
/*
* not-supported deviations are not processed since they affect the complete node, not just their substatements
*/
int
lyp_deviation_apply_ext(struct lys_module *module)
{
int i, j, k;
struct lys_deviate *dev;
struct lys_node *target;
struct ly_set *extset;
for (i = 0; i < module->deviation_size; i++) {
target = NULL;
extset = NULL;
j = resolve_schema_nodeid(module->deviation[i].target_name, NULL, module, &extset, 0, 0);
if (j == -1) {
return EXIT_FAILURE;
} else if (!extset) {
/* LY_DEVIATE_NO */
ly_set_free(extset);
continue;
}
target = extset->set.s[0];
ly_set_free(extset);
for (j = 0; j < module->deviation[i].deviate_size; j++) {
dev = &module->deviation[i].deviate[j];
if (!dev->ext_size) {
/* no extensions in deviate and its substatement, nothing to do here */
continue;
}
/* extensions */
if (dev->mod == LY_DEVIATE_DEL) {
k = -1;
while ((k = lys_ext_iter(dev->ext, dev->ext_size, k + 1, LYEXT_SUBSTMT_SELF)) != -1) {
if (lyp_deviate_del_ext(target, dev->ext[k])) {
return EXIT_FAILURE;
}
}
/* In case of LY_DEVIATE_DEL, we are applying only extension deviation, removing
* of the substatement's extensions was already done when the substatement was applied.
* Extension deviation could not be applied by the parser since the extension could be unresolved,
* which is not the issue of the other substatements. */
continue;
} else {
extset = ly_set_new();
k = -1;
while ((k = lys_ext_iter(dev->ext, dev->ext_size, k + 1, LYEXT_SUBSTMT_SELF)) != -1) {
ly_set_add(extset, dev->ext[k]->def, 0);
}
for (k = 0; (unsigned int)k < extset->number; k++) {
if (lyp_deviate_apply_ext(dev, target, LYEXT_SUBSTMT_SELF, (struct lys_ext *)extset->set.g[k])) {
ly_set_free(extset);
return EXIT_FAILURE;
}
}
ly_set_free(extset);
}
/* unique */
if (dev->unique_size && lyp_deviate_apply_ext(dev, target, LYEXT_SUBSTMT_UNIQUE, NULL)) {
return EXIT_FAILURE;
}
/* units */
if (dev->units && lyp_deviate_apply_ext(dev, target, LYEXT_SUBSTMT_UNITS, NULL)) {
return EXIT_FAILURE;
}
/* default */
if (dev->dflt_size && lyp_deviate_apply_ext(dev, target, LYEXT_SUBSTMT_DEFAULT, NULL)) {
return EXIT_FAILURE;
}
/* config */
if ((dev->flags & LYS_CONFIG_MASK) && lyp_deviate_apply_ext(dev, target, LYEXT_SUBSTMT_CONFIG, NULL)) {
return EXIT_FAILURE;
}
/* mandatory */
if ((dev->flags & LYS_MAND_MASK) && lyp_deviate_apply_ext(dev, target, LYEXT_SUBSTMT_MANDATORY, NULL)) {
return EXIT_FAILURE;
}
/* min/max */
if (dev->min_set && lyp_deviate_apply_ext(dev, target, LYEXT_SUBSTMT_MIN, NULL)) {
return EXIT_FAILURE;
}
if (dev->min_set && lyp_deviate_apply_ext(dev, target, LYEXT_SUBSTMT_MAX, NULL)) {
return EXIT_FAILURE;
}
/* type and must contain extension instances in their structures */
}
}
return EXIT_SUCCESS;
}
int
lyp_ctx_check_module(struct lys_module *module)
{
struct ly_ctx *ctx;
int i, match_i = -1, to_implement;
const char *last_rev = NULL;
assert(module);
to_implement = 0;
ctx = module->ctx;
/* find latest revision */
for (i = 0; i < module->rev_size; ++i) {
if (!last_rev || (strcmp(last_rev, module->rev[i].date) < 0)) {
last_rev = module->rev[i].date;
}
}
for (i = 0; i < ctx->models.used; i++) {
/* check name (name/revision) and namespace uniqueness */
if (!strcmp(ctx->models.list[i]->name, module->name)) {
if (to_implement) {
if (i == match_i) {
continue;
}
LOGERR(ctx, LY_EINVAL, "Module \"%s@%s\" in another revision \"%s\" already implemented.",
module->name, last_rev ? last_rev : "<latest>", ctx->models.list[i]->rev[0].date);
return -1;
} else if (!ctx->models.list[i]->rev_size && module->rev_size) {
LOGERR(ctx, LY_EINVAL, "Module \"%s\" without revision already in context.", module->name);
return -1;
} else if (ctx->models.list[i]->rev_size && !module->rev_size) {
LOGERR(ctx, LY_EINVAL, "Module \"%s\" with revision \"%s\" already in context.",
module->name, ctx->models.list[i]->rev[0].date);
return -1;
} else if ((!module->rev_size && !ctx->models.list[i]->rev_size)
|| !strcmp(ctx->models.list[i]->rev[0].date, last_rev)) {
LOGVRB("Module \"%s@%s\" already in context.", module->name, last_rev ? last_rev : "<latest>");
/* if disabled, enable first */
if (ctx->models.list[i]->disabled) {
lys_set_enabled(ctx->models.list[i]);
}
to_implement = module->implemented;
match_i = i;
if (to_implement && !ctx->models.list[i]->implemented) {
/* check first that it is okay to change it to implemented */
i = -1;
continue;
}
return 1;
} else if (module->implemented && ctx->models.list[i]->implemented) {
LOGERR(ctx, LY_EINVAL, "Module \"%s@%s\" in another revision \"%s\" already implemented.",
module->name, last_rev ? last_rev : "<latest>", ctx->models.list[i]->rev[0].date);
return -1;
}
/* else keep searching, for now the caller is just adding
* another revision of an already present schema
*/
} else if (!strcmp(ctx->models.list[i]->ns, module->ns)) {
LOGERR(ctx, LY_EINVAL, "Two different modules (\"%s\" and \"%s\") have the same namespace \"%s\".",
ctx->models.list[i]->name, module->name, module->ns);
return -1;
}
}
if (to_implement) {
if (lys_set_implemented(ctx->models.list[match_i])) {
return -1;
}
return 1;
}
return 0;
}
int
lyp_ctx_add_module(struct lys_module *module)
{
struct lys_module **newlist = NULL;
int i;
assert(!lyp_ctx_check_module(module));
#ifndef NDEBUG
int j;
/* check that all augments are resolved */
for (i = 0; i < module->augment_size; ++i) {
assert(module->augment[i].target);
}
for (i = 0; i < module->inc_size; ++i) {
for (j = 0; j < module->inc[i].submodule->augment_size; ++j) {
assert(module->inc[i].submodule->augment[j].target);
}
}
#endif
/* add to the context's list of modules */
if (module->ctx->models.used == module->ctx->models.size) {
newlist = realloc(module->ctx->models.list, (2 * module->ctx->models.size) * sizeof *newlist);
LY_CHECK_ERR_RETURN(!newlist, LOGMEM(module->ctx), -1);
for (i = module->ctx->models.size; i < module->ctx->models.size * 2; i++) {
newlist[i] = NULL;
}
module->ctx->models.size *= 2;
module->ctx->models.list = newlist;
}
module->ctx->models.list[module->ctx->models.used++] = module;
module->ctx->models.module_set_id++;
return 0;
}
/**
* Store UTF-8 character specified as 4byte integer into the dst buffer.
* Returns number of written bytes (4 max), expects that dst has enough space.
*
* UTF-8 mapping:
* 00000000 -- 0000007F: 0xxxxxxx
* 00000080 -- 000007FF: 110xxxxx 10xxxxxx
* 00000800 -- 0000FFFF: 1110xxxx 10xxxxxx 10xxxxxx
* 00010000 -- 001FFFFF: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
*
* Includes checking for valid characters (following RFC 7950, sec 9.4)
*/
unsigned int
pututf8(struct ly_ctx *ctx, char *dst, int32_t value)
{
if (value < 0x80) {
/* one byte character */
if (value < 0x20 &&
value != 0x09 &&
value != 0x0a &&
value != 0x0d) {
goto error;
}
dst[0] = value;
return 1;
} else if (value < 0x800) {
/* two bytes character */
dst[0] = 0xc0 | (value >> 6);
dst[1] = 0x80 | (value & 0x3f);
return 2;
} else if (value < 0xfffe) {
/* three bytes character */
if (((value & 0xf800) == 0xd800) ||
(value >= 0xfdd0 && value <= 0xfdef)) {
/* exclude surrogate blocks %xD800-DFFF */
/* exclude noncharacters %xFDD0-FDEF */
goto error;
}
dst[0] = 0xe0 | (value >> 12);
dst[1] = 0x80 | ((value >> 6) & 0x3f);
dst[2] = 0x80 | (value & 0x3f);
return 3;
} else if (value < 0x10fffe) {
if ((value & 0xffe) == 0xffe) {
/* exclude noncharacters %xFFFE-FFFF, %x1FFFE-1FFFF, %x2FFFE-2FFFF, %x3FFFE-3FFFF, %x4FFFE-4FFFF,
* %x5FFFE-5FFFF, %x6FFFE-6FFFF, %x7FFFE-7FFFF, %x8FFFE-8FFFF, %x9FFFE-9FFFF, %xAFFFE-AFFFF,
* %xBFFFE-BFFFF, %xCFFFE-CFFFF, %xDFFFE-DFFFF, %xEFFFE-EFFFF, %xFFFFE-FFFFF, %x10FFFE-10FFFF */
goto error;
}
/* four bytes character */
dst[0] = 0xf0 | (value >> 18);
dst[1] = 0x80 | ((value >> 12) & 0x3f);
dst[2] = 0x80 | ((value >> 6) & 0x3f);
dst[3] = 0x80 | (value & 0x3f);
return 4;
}
error:
/* out of range */
LOGVAL(ctx, LYE_XML_INCHAR, LY_VLOG_NONE, NULL, NULL);
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid UTF-8 value 0x%08x", value);
return 0;
}
unsigned int
copyutf8(struct ly_ctx *ctx, char *dst, const char *src)
{
uint32_t value;
/* unicode characters */
if (!(src[0] & 0x80)) {
/* one byte character */
if (src[0] < 0x20 &&
src[0] != 0x09 &&
src[0] != 0x0a &&
src[0] != 0x0d) {
LOGVAL(ctx, LYE_XML_INCHAR, LY_VLOG_NONE, NULL, src);
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid UTF-8 value 0x%02x", src[0]);
return 0;
}
dst[0] = src[0];
return 1;
} else if (!(src[0] & 0x20)) {
/* two bytes character */
dst[0] = src[0];
dst[1] = src[1];
return 2;
} else if (!(src[0] & 0x10)) {
/* three bytes character */
value = ((uint32_t)(src[0] & 0xf) << 12) | ((uint32_t)(src[1] & 0x3f) << 6) | (src[2] & 0x3f);
if (((value & 0xf800) == 0xd800) ||
(value >= 0xfdd0 && value <= 0xfdef) ||
(value & 0xffe) == 0xffe) {
/* exclude surrogate blocks %xD800-DFFF */
/* exclude noncharacters %xFDD0-FDEF */
/* exclude noncharacters %xFFFE-FFFF */
LOGVAL(ctx, LYE_XML_INCHAR, LY_VLOG_NONE, NULL, src);
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid UTF-8 value 0x%08x", value);
return 0;
}
dst[0] = src[0];
dst[1] = src[1];
dst[2] = src[2];
return 3;
} else if (!(src[0] & 0x08)) {
/* four bytes character */
value = ((uint32_t)(src[0] & 0x7) << 18) | ((uint32_t)(src[1] & 0x3f) << 12) | ((uint32_t)(src[2] & 0x3f) << 6) | (src[3] & 0x3f);
if ((value & 0xffe) == 0xffe) {
/* exclude noncharacters %x1FFFE-1FFFF, %x2FFFE-2FFFF, %x3FFFE-3FFFF, %x4FFFE-4FFFF,
* %x5FFFE-5FFFF, %x6FFFE-6FFFF, %x7FFFE-7FFFF, %x8FFFE-8FFFF, %x9FFFE-9FFFF, %xAFFFE-AFFFF,
* %xBFFFE-BFFFF, %xCFFFE-CFFFF, %xDFFFE-DFFFF, %xEFFFE-EFFFF, %xFFFFE-FFFFF, %x10FFFE-10FFFF */
LOGVAL(ctx, LYE_XML_INCHAR, LY_VLOG_NONE, NULL, src);
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid UTF-8 value 0x%08x", value);
return 0;
}
dst[0] = src[0];
dst[1] = src[1];
dst[2] = src[2];
dst[3] = src[3];
return 4;
} else {
LOGVAL(ctx, LYE_XML_INCHAR, LY_VLOG_NONE, NULL, src);
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid UTF-8 leading byte 0x%02x", src[0]);
return 0;
}
}
const struct lys_module *
lyp_get_module(const struct lys_module *module, const char *prefix, int pref_len, const char *name, int name_len, int in_data)
{
const struct lys_module *main_module;
char *str;
int i;
assert(!prefix || !name);
if (prefix && !pref_len) {
pref_len = strlen(prefix);
}
if (name && !name_len) {
name_len = strlen(name);
}
main_module = lys_main_module(module);
/* module own prefix, submodule own prefix, (sub)module own name */
if ((!prefix || (!module->type && !strncmp(main_module->prefix, prefix, pref_len) && !main_module->prefix[pref_len])
|| (module->type && !strncmp(module->prefix, prefix, pref_len) && !module->prefix[pref_len]))
&& (!name || (!strncmp(main_module->name, name, name_len) && !main_module->name[name_len]))) {
return main_module;
}
/* standard import */
for (i = 0; i < module->imp_size; ++i) {
if ((!prefix || (!strncmp(module->imp[i].prefix, prefix, pref_len) && !module->imp[i].prefix[pref_len]))
&& (!name || (!strncmp(module->imp[i].module->name, name, name_len) && !module->imp[i].module->name[name_len]))) {
return module->imp[i].module;
}
}
/* module required by a foreign grouping, deviation, or submodule */
if (name) {
str = strndup(name, name_len);
if (!str) {
LOGMEM(module->ctx);
return NULL;
}
main_module = ly_ctx_get_module(module->ctx, str, NULL, 0);
/* try data callback */
if (!main_module && in_data && module->ctx->data_clb) {
main_module = module->ctx->data_clb(module->ctx, str, NULL, 0, module->ctx->data_clb_data);
}
free(str);
return main_module;
}
return NULL;
}
const struct lys_module *
lyp_get_import_module_ns(const struct lys_module *module, const char *ns)
{
int i;
const struct lys_module *mod = NULL;
assert(module && ns);
if (module->type) {
/* the module is actually submodule and to get the namespace, we need the main module */
if (ly_strequal(((struct lys_submodule *)module)->belongsto->ns, ns, 0)) {
return ((struct lys_submodule *)module)->belongsto;
}
} else {
/* module's own namespace */
if (ly_strequal(module->ns, ns, 0)) {
return module;
}
}
/* imported modules */
for (i = 0; i < module->imp_size; ++i) {
if (ly_strequal(module->imp[i].module->ns, ns, 0)) {
return module->imp[i].module;
}
}
return mod;
}
const char *
lyp_get_yang_data_template_name(const struct lyd_node *node)
{
struct lys_node *snode;
snode = lys_parent(node->schema);
while (snode && snode->nodetype & (LYS_USES | LYS_CASE | LYS_CHOICE)) {
snode = lys_parent(snode);
}
if (snode && snode->nodetype == LYS_EXT && strcmp(((struct lys_ext_instance_complex *)snode)->def->name, "yang-data") == 0) {
return ((struct lys_ext_instance_complex *)snode)->arg_value;
} else {
return NULL;
}
}
const struct lys_node *
lyp_get_yang_data_template(const struct lys_module *module, const char *yang_data_name, int yang_data_name_len)
{
int i, j;
const struct lys_node *ret = NULL;
const struct lys_submodule *submodule;
for(i = 0; i < module->ext_size; ++i) {
if (!strcmp(module->ext[i]->def->name, "yang-data") && !strncmp(module->ext[i]->arg_value, yang_data_name, yang_data_name_len)
&& !module->ext[i]->arg_value[yang_data_name_len]) {
ret = (struct lys_node *)module->ext[i];
break;
}
}
for(j = 0; !ret && j < module->inc_size; ++j) {
submodule = module->inc[j].submodule;
for(i = 0; i < submodule->ext_size; ++i) {
if (!strcmp(submodule->ext[i]->def->name, "yang-data") && !strncmp(submodule->ext[i]->arg_value, yang_data_name, yang_data_name_len)
&& !submodule->ext[i]->arg_value[yang_data_name_len]) {
ret = (struct lys_node *)submodule->ext[i];
break;
}
}
}
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_1288_0 |
crossvul-cpp_data_bad_2775_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) 2008, Jerome Fimes, Communications & Systemes <jerome.fimes@c-s.fr>
* Copyright (c) 2006-2007, Parvatha Elangovan
* Copyright (c) 2010-2011, Kaori Hagihara
* Copyright (c) 2011-2012, Centre National d'Etudes Spatiales (CNES), France
* 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"
/** @defgroup J2K J2K - JPEG-2000 codestream reader/writer */
/*@{*/
/** @name Local static functions */
/*@{*/
#define OPJ_UNUSED(x) (void)x
/**
* Sets up the procedures to do on reading header. Developpers wanting to extend the library can add their own reading procedures.
*/
static OPJ_BOOL opj_j2k_setup_header_reading(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager);
/**
* The read header procedure.
*/
static OPJ_BOOL opj_j2k_read_header_procedure(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* The default encoding validation procedure without any extension.
*
* @param p_j2k the jpeg2000 codec to validate.
* @param p_stream the input stream to validate.
* @param p_manager the user event manager.
*
* @return true if the parameters are correct.
*/
static OPJ_BOOL opj_j2k_encoding_validation(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* The default decoding validation procedure without any extension.
*
* @param p_j2k the jpeg2000 codec to validate.
* @param p_stream the input stream to validate.
* @param p_manager the user event manager.
*
* @return true if the parameters are correct.
*/
static OPJ_BOOL opj_j2k_decoding_validation(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Sets up the validation ,i.e. adds the procedures to lauch to make sure the codec parameters
* are valid. Developpers wanting to extend the library can add their own validation procedures.
*/
static OPJ_BOOL opj_j2k_setup_encoding_validation(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager);
/**
* Sets up the validation ,i.e. adds the procedures to lauch to make sure the codec parameters
* are valid. Developpers wanting to extend the library can add their own validation procedures.
*/
static OPJ_BOOL opj_j2k_setup_decoding_validation(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager);
/**
* Sets up the validation ,i.e. adds the procedures to lauch to make sure the codec parameters
* are valid. Developpers wanting to extend the library can add their own validation procedures.
*/
static OPJ_BOOL opj_j2k_setup_end_compress(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager);
/**
* The mct encoding validation procedure.
*
* @param p_j2k the jpeg2000 codec to validate.
* @param p_stream the input stream to validate.
* @param p_manager the user event manager.
*
* @return true if the parameters are correct.
*/
static OPJ_BOOL opj_j2k_mct_validation(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Builds the tcd decoder to use to decode tile.
*/
static OPJ_BOOL opj_j2k_build_decoder(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Builds the tcd encoder to use to encode tile.
*/
static OPJ_BOOL opj_j2k_build_encoder(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Creates a tile-coder decoder.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_create_tcd(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Excutes the given procedures on the given codec.
*
* @param p_procedure_list the list of procedures to execute
* @param p_j2k the jpeg2000 codec to execute the procedures on.
* @param p_stream the stream to execute the procedures on.
* @param p_manager the user manager.
*
* @return true if all the procedures were successfully executed.
*/
static OPJ_BOOL opj_j2k_exec(opj_j2k_t * p_j2k,
opj_procedure_list_t * p_procedure_list,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Updates the rates of the tcp.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_update_rates(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Copies the decoding tile parameters onto all the tile parameters.
* Creates also the tile decoder.
*/
static OPJ_BOOL opj_j2k_copy_default_tcp_and_create_tcd(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Destroys the memory associated with the decoding of headers.
*/
static OPJ_BOOL opj_j2k_destroy_header_memory(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads the lookup table containing all the marker, status and action, and returns the handler associated
* with the marker value.
* @param p_id Marker value to look up
*
* @return the handler associated with the id.
*/
static const struct opj_dec_memory_marker_handler * opj_j2k_get_marker_handler(
OPJ_UINT32 p_id);
/**
* Destroys a tile coding parameter structure.
*
* @param p_tcp the tile coding parameter to destroy.
*/
static void opj_j2k_tcp_destroy(opj_tcp_t *p_tcp);
/**
* Destroys the data inside a tile coding parameter structure.
*
* @param p_tcp the tile coding parameter which contain data to destroy.
*/
static void opj_j2k_tcp_data_destroy(opj_tcp_t *p_tcp);
/**
* Destroys a coding parameter structure.
*
* @param p_cp the coding parameter to destroy.
*/
static void opj_j2k_cp_destroy(opj_cp_t *p_cp);
/**
* Compare 2 a SPCod/ SPCoc elements, i.e. the coding style of a given component of a tile.
*
* @param p_j2k J2K codec.
* @param p_tile_no Tile number
* @param p_first_comp_no The 1st component number to compare.
* @param p_second_comp_no The 1st component number to compare.
*
* @return OPJ_TRUE if SPCdod are equals.
*/
static OPJ_BOOL opj_j2k_compare_SPCod_SPCoc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no);
/**
* Writes a SPCod or SPCoc element, i.e. the coding style of a given component of a tile.
*
* @param p_j2k J2K codec.
* @param p_tile_no FIXME DOC
* @param p_comp_no the component number to output.
* @param p_data FIXME DOC
* @param p_header_size FIXME DOC
* @param p_manager the user event manager.
*
* @return FIXME DOC
*/
static OPJ_BOOL opj_j2k_write_SPCod_SPCoc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_header_size,
opj_event_mgr_t * p_manager);
/**
* Gets the size taken by writing a SPCod or SPCoc for the given tile and component.
*
* @param p_j2k the J2K codec.
* @param p_tile_no the tile index.
* @param p_comp_no the component being outputted.
*
* @return the number of bytes taken by the SPCod element.
*/
static OPJ_UINT32 opj_j2k_get_SPCod_SPCoc_size(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no);
/**
* Reads a SPCod or SPCoc element, i.e. the coding style of a given component of a tile.
* @param p_j2k the jpeg2000 codec.
* @param compno FIXME DOC
* @param p_header_data the data contained in the COM box.
* @param p_header_size the size of the data contained in the COM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_SPCod_SPCoc(opj_j2k_t *p_j2k,
OPJ_UINT32 compno,
OPJ_BYTE * p_header_data,
OPJ_UINT32 * p_header_size,
opj_event_mgr_t * p_manager);
/**
* Gets the size taken by writing SQcd or SQcc element, i.e. the quantization values of a band in the QCD or QCC.
*
* @param p_tile_no the tile index.
* @param p_comp_no the component being outputted.
* @param p_j2k the J2K codec.
*
* @return the number of bytes taken by the SPCod element.
*/
static OPJ_UINT32 opj_j2k_get_SQcd_SQcc_size(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no);
/**
* Compares 2 SQcd or SQcc element, i.e. the quantization values of a band in the QCD or QCC.
*
* @param p_j2k J2K codec.
* @param p_tile_no the tile to output.
* @param p_first_comp_no the first component number to compare.
* @param p_second_comp_no the second component number to compare.
*
* @return OPJ_TRUE if equals.
*/
static OPJ_BOOL opj_j2k_compare_SQcd_SQcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no);
/**
* Writes a SQcd or SQcc element, i.e. the quantization values of a band in the QCD or QCC.
*
* @param p_tile_no the tile to output.
* @param p_comp_no the component number to output.
* @param p_data the data buffer.
* @param p_header_size pointer to the size of the data buffer, it is changed by the function.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*
*/
static OPJ_BOOL opj_j2k_write_SQcd_SQcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_header_size,
opj_event_mgr_t * p_manager);
/**
* Updates the Tile Length Marker.
*/
static void opj_j2k_update_tlm(opj_j2k_t * p_j2k, OPJ_UINT32 p_tile_part_size);
/**
* Reads a SQcd or SQcc element, i.e. the quantization values of a band in the QCD or QCC.
*
* @param p_j2k J2K codec.
* @param compno the component number to output.
* @param p_header_data the data buffer.
* @param p_header_size pointer to the size of the data buffer, it is changed by the function.
* @param p_manager the user event manager.
*
*/
static OPJ_BOOL opj_j2k_read_SQcd_SQcc(opj_j2k_t *p_j2k,
OPJ_UINT32 compno,
OPJ_BYTE * p_header_data,
OPJ_UINT32 * p_header_size,
opj_event_mgr_t * p_manager);
/**
* Copies the tile component parameters of all the component from the first tile component.
*
* @param p_j2k the J2k codec.
*/
static void opj_j2k_copy_tile_component_parameters(opj_j2k_t *p_j2k);
/**
* Copies the tile quantization parameters of all the component from the first tile component.
*
* @param p_j2k the J2k codec.
*/
static void opj_j2k_copy_tile_quantization_parameters(opj_j2k_t *p_j2k);
/**
* Reads the tiles.
*/
static OPJ_BOOL opj_j2k_decode_tiles(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
static OPJ_BOOL opj_j2k_pre_write_tile(opj_j2k_t * p_j2k,
OPJ_UINT32 p_tile_index,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
static OPJ_BOOL opj_j2k_update_image_data(opj_tcd_t * p_tcd, OPJ_BYTE * p_data,
opj_image_t* p_output_image);
static void opj_get_tile_dimensions(opj_image_t * l_image,
opj_tcd_tilecomp_t * l_tilec,
opj_image_comp_t * l_img_comp,
OPJ_UINT32* l_size_comp,
OPJ_UINT32* l_width,
OPJ_UINT32* l_height,
OPJ_UINT32* l_offset_x,
OPJ_UINT32* l_offset_y,
OPJ_UINT32* l_image_width,
OPJ_UINT32* l_stride,
OPJ_UINT32* l_tile_offset);
static void opj_j2k_get_tile_data(opj_tcd_t * p_tcd, OPJ_BYTE * p_data);
static OPJ_BOOL opj_j2k_post_write_tile(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Sets up the procedures to do on writing header.
* Developers wanting to extend the library can add their own writing procedures.
*/
static OPJ_BOOL opj_j2k_setup_header_writing(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager);
static OPJ_BOOL opj_j2k_write_first_tile_part(opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_total_data_size,
opj_stream_private_t *p_stream,
struct opj_event_mgr * p_manager);
static OPJ_BOOL opj_j2k_write_all_tile_parts(opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_total_data_size,
opj_stream_private_t *p_stream,
struct opj_event_mgr * p_manager);
/**
* Gets the offset of the header.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_get_end_header(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
static OPJ_BOOL opj_j2k_allocate_tile_element_cstr_index(opj_j2k_t *p_j2k);
/*
* -----------------------------------------------------------------------
* -----------------------------------------------------------------------
* -----------------------------------------------------------------------
*/
/**
* Writes the SOC marker (Start Of Codestream)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_soc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a SOC marker (Start of Codestream)
* @param p_j2k the jpeg2000 file codec.
* @param p_stream XXX needs data
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_soc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes the SIZ marker (image and tile size)
*
* @param p_j2k J2K codec.
* @param p_stream the stream to write data to.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_siz(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a SIZ marker (image and tile size)
* @param p_j2k the jpeg2000 file codec.
* @param p_header_data the data contained in the SIZ box.
* @param p_header_size the size of the data contained in the SIZ marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_siz(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the COM marker (comment)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_com(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a COM marker (comments)
* @param p_j2k the jpeg2000 file codec.
* @param p_header_data the data contained in the COM box.
* @param p_header_size the size of the data contained in the COM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_com(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the COD marker (Coding style default)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_cod(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a COD marker (Coding Styke defaults)
* @param p_header_data the data contained in the COD box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the COD marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_cod(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Compares 2 COC markers (Coding style component)
*
* @param p_j2k J2K codec.
* @param p_first_comp_no the index of the first component to compare.
* @param p_second_comp_no the index of the second component to compare.
*
* @return OPJ_TRUE if equals
*/
static OPJ_BOOL opj_j2k_compare_coc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no);
/**
* Writes the COC marker (Coding style component)
*
* @param p_j2k J2K codec.
* @param p_comp_no the index of the component to output.
* @param p_stream the stream to write data to.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_coc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes the COC marker (Coding style component)
*
* @param p_j2k J2K codec.
* @param p_comp_no the index of the component to output.
* @param p_data FIXME DOC
* @param p_data_written FIXME DOC
* @param p_manager the user event manager.
*/
static void opj_j2k_write_coc_in_memory(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
opj_event_mgr_t * p_manager);
/**
* Gets the maximum size taken by a coc.
*
* @param p_j2k the jpeg2000 codec to use.
*/
static OPJ_UINT32 opj_j2k_get_max_coc_size(opj_j2k_t *p_j2k);
/**
* Reads a COC marker (Coding Style Component)
* @param p_header_data the data contained in the COC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the COC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_coc(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the QCD marker (quantization default)
*
* @param p_j2k J2K codec.
* @param p_stream the stream to write data to.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_qcd(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a QCD marker (Quantization defaults)
* @param p_header_data the data contained in the QCD box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the QCD marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_qcd(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Compare QCC markers (quantization component)
*
* @param p_j2k J2K codec.
* @param p_first_comp_no the index of the first component to compare.
* @param p_second_comp_no the index of the second component to compare.
*
* @return OPJ_TRUE if equals.
*/
static OPJ_BOOL opj_j2k_compare_qcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no);
/**
* Writes the QCC marker (quantization component)
*
* @param p_comp_no the index of the component to output.
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_qcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes the QCC marker (quantization component)
*
* @param p_j2k J2K codec.
* @param p_comp_no the index of the component to output.
* @param p_data FIXME DOC
* @param p_data_written the stream to write data to.
* @param p_manager the user event manager.
*/
static void opj_j2k_write_qcc_in_memory(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
opj_event_mgr_t * p_manager);
/**
* Gets the maximum size taken by a qcc.
*/
static OPJ_UINT32 opj_j2k_get_max_qcc_size(opj_j2k_t *p_j2k);
/**
* Reads a QCC marker (Quantization component)
* @param p_header_data the data contained in the QCC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the QCC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_qcc(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the POC marker (Progression Order Change)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_poc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes the POC marker (Progression Order Change)
*
* @param p_j2k J2K codec.
* @param p_data FIXME DOC
* @param p_data_written the stream to write data to.
* @param p_manager the user event manager.
*/
static void opj_j2k_write_poc_in_memory(opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
opj_event_mgr_t * p_manager);
/**
* Gets the maximum size taken by the writing of a POC.
*/
static OPJ_UINT32 opj_j2k_get_max_poc_size(opj_j2k_t *p_j2k);
/**
* Reads a POC marker (Progression Order Change)
*
* @param p_header_data the data contained in the POC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the POC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_poc(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Gets the maximum size taken by the toc headers of all the tile parts of any given tile.
*/
static OPJ_UINT32 opj_j2k_get_max_toc_size(opj_j2k_t *p_j2k);
/**
* Gets the maximum size taken by the headers of the SOT.
*
* @param p_j2k the jpeg2000 codec to use.
*/
static OPJ_UINT32 opj_j2k_get_specific_header_sizes(opj_j2k_t *p_j2k);
/**
* Reads a CRG marker (Component registration)
*
* @param p_header_data the data contained in the TLM box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the TLM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_crg(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Reads a TLM marker (Tile Length Marker)
*
* @param p_header_data the data contained in the TLM box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the TLM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_tlm(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the updated tlm.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_updated_tlm(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a PLM marker (Packet length, main header marker)
*
* @param p_header_data the data contained in the TLM box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the TLM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_plm(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Reads a PLT marker (Packet length, tile-part header)
*
* @param p_header_data the data contained in the PLT box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the PLT marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_plt(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Reads a PPM marker (Packed headers, main header)
*
* @param p_header_data the data contained in the POC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the POC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_ppm(
opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Merges all PPM markers read (Packed headers, main header)
*
* @param p_cp main coding parameters.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_merge_ppm(opj_cp_t *p_cp, opj_event_mgr_t * p_manager);
/**
* Reads a PPT marker (Packed packet headers, tile-part header)
*
* @param p_header_data the data contained in the PPT box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the PPT marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_ppt(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Merges all PPT markers read (Packed headers, tile-part header)
*
* @param p_tcp the tile.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_merge_ppt(opj_tcp_t *p_tcp,
opj_event_mgr_t * p_manager);
/**
* Writes the TLM marker (Tile Length Marker)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_tlm(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes the SOT marker (Start of tile-part)
*
* @param p_j2k J2K codec.
* @param p_data FIXME DOC
* @param p_data_written FIXME DOC
* @param p_stream the stream to write data to.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_sot(opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
const opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads values from a SOT marker (Start of tile-part)
*
* the j2k decoder state is not affected. No side effects, no checks except for p_header_size.
*
* @param p_header_data the data contained in the SOT marker.
* @param p_header_size the size of the data contained in the SOT marker.
* @param p_tile_no Isot.
* @param p_tot_len Psot.
* @param p_current_part TPsot.
* @param p_num_parts TNsot.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_get_sot_values(OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
OPJ_UINT32* p_tile_no,
OPJ_UINT32* p_tot_len,
OPJ_UINT32* p_current_part,
OPJ_UINT32* p_num_parts,
opj_event_mgr_t * p_manager);
/**
* Reads a SOT marker (Start of tile-part)
*
* @param p_header_data the data contained in the SOT marker.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the PPT marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_sot(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the SOD marker (Start of data)
*
* @param p_j2k J2K codec.
* @param p_tile_coder FIXME DOC
* @param p_data FIXME DOC
* @param p_data_written FIXME DOC
* @param p_total_data_size FIXME DOC
* @param p_stream the stream to write data to.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_sod(opj_j2k_t *p_j2k,
opj_tcd_t * p_tile_coder,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_total_data_size,
const opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a SOD marker (Start Of Data)
*
* @param p_j2k the jpeg2000 codec.
* @param p_stream FIXME DOC
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_sod(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
static void opj_j2k_update_tlm(opj_j2k_t * p_j2k, OPJ_UINT32 p_tile_part_size)
{
opj_write_bytes(p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current,
p_j2k->m_current_tile_number, 1); /* PSOT */
++p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current;
opj_write_bytes(p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current,
p_tile_part_size, 4); /* PSOT */
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current += 4;
}
/**
* Writes the RGN marker (Region Of Interest)
*
* @param p_tile_no the tile to output
* @param p_comp_no the component to output
* @param nb_comps the number of components
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_rgn(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no,
OPJ_UINT32 nb_comps,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a RGN marker (Region Of Interest)
*
* @param p_header_data the data contained in the POC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the POC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_rgn(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the EOC marker (End of Codestream)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_eoc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
#if 0
/**
* Reads a EOC marker (End Of Codestream)
*
* @param p_j2k the jpeg2000 codec.
* @param p_stream FIXME DOC
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_eoc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
#endif
/**
* Writes the CBD-MCT-MCC-MCO markers (Multi components transform)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_mct_data_group(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Inits the Info
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_init_info(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
Add main header marker information
@param cstr_index Codestream information structure
@param type marker type
@param pos byte offset of marker segment
@param len length of marker segment
*/
static OPJ_BOOL opj_j2k_add_mhmarker(opj_codestream_index_t *cstr_index,
OPJ_UINT32 type, OPJ_OFF_T pos, OPJ_UINT32 len) ;
/**
Add tile header marker information
@param tileno tile index number
@param cstr_index Codestream information structure
@param type marker type
@param pos byte offset of marker segment
@param len length of marker segment
*/
static OPJ_BOOL opj_j2k_add_tlmarker(OPJ_UINT32 tileno,
opj_codestream_index_t *cstr_index, OPJ_UINT32 type, OPJ_OFF_T pos,
OPJ_UINT32 len);
/**
* Reads an unknown marker
*
* @param p_j2k the jpeg2000 codec.
* @param p_stream the stream object to read from.
* @param output_marker FIXME DOC
* @param p_manager the user event manager.
*
* @return true if the marker could be deduced.
*/
static OPJ_BOOL opj_j2k_read_unk(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
OPJ_UINT32 *output_marker,
opj_event_mgr_t * p_manager);
/**
* Writes the MCT marker (Multiple Component Transform)
*
* @param p_j2k J2K codec.
* @param p_mct_record FIXME DOC
* @param p_stream the stream to write data to.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_mct_record(opj_j2k_t *p_j2k,
opj_mct_data_t * p_mct_record,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a MCT marker (Multiple Component Transform)
*
* @param p_header_data the data contained in the MCT box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the MCT marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_mct(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the MCC marker (Multiple Component Collection)
*
* @param p_j2k J2K codec.
* @param p_mcc_record FIXME DOC
* @param p_stream the stream to write data to.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_mcc_record(opj_j2k_t *p_j2k,
opj_simple_mcc_decorrelation_data_t * p_mcc_record,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a MCC marker (Multiple Component Collection)
*
* @param p_header_data the data contained in the MCC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the MCC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_mcc(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the MCO marker (Multiple component transformation ordering)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_mco(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a MCO marker (Multiple Component Transform Ordering)
*
* @param p_header_data the data contained in the MCO box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the MCO marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_mco(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
static OPJ_BOOL opj_j2k_add_mct(opj_tcp_t * p_tcp, opj_image_t * p_image,
OPJ_UINT32 p_index);
static void opj_j2k_read_int16_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_read_int32_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_read_float32_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_read_float64_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_read_int16_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_read_int32_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_read_float32_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_read_float64_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_write_float_to_int16(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_write_float_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_write_float_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_write_float_to_float64(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
/**
* Ends the encoding, i.e. frees memory.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_end_encoding(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes the CBD marker (Component bit depth definition)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_cbd(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a CBD marker (Component bit depth definition)
* @param p_header_data the data contained in the CBD box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the CBD marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_cbd(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes COC marker for each component.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_all_coc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes QCC marker for each component.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_all_qcc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes regions of interests.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_regions(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes EPC ????
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_epc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Checks the progression order changes values. Tells of the poc given as input are valid.
* A nice message is outputted at errors.
*
* @param p_pocs the progression order changes.
* @param p_nb_pocs the number of progression order changes.
* @param p_nb_resolutions the number of resolutions.
* @param numcomps the number of components
* @param numlayers the number of layers.
* @param p_manager the user event manager.
*
* @return true if the pocs are valid.
*/
static OPJ_BOOL opj_j2k_check_poc_val(const opj_poc_t *p_pocs,
OPJ_UINT32 p_nb_pocs,
OPJ_UINT32 p_nb_resolutions,
OPJ_UINT32 numcomps,
OPJ_UINT32 numlayers,
opj_event_mgr_t * p_manager);
/**
* Gets the number of tile parts used for the given change of progression (if any) and the given tile.
*
* @param cp the coding parameters.
* @param pino the offset of the given poc (i.e. its position in the coding parameter).
* @param tileno the given tile.
*
* @return the number of tile parts.
*/
static OPJ_UINT32 opj_j2k_get_num_tp(opj_cp_t *cp, OPJ_UINT32 pino,
OPJ_UINT32 tileno);
/**
* Calculates the total number of tile parts needed by the encoder to
* encode such an image. If not enough memory is available, then the function return false.
*
* @param p_nb_tiles pointer that will hold the number of tile parts.
* @param cp the coding parameters for the image.
* @param image the image to encode.
* @param p_j2k the p_j2k encoder.
* @param p_manager the user event manager.
*
* @return true if the function was successful, false else.
*/
static OPJ_BOOL opj_j2k_calculate_tp(opj_j2k_t *p_j2k,
opj_cp_t *cp,
OPJ_UINT32 * p_nb_tiles,
opj_image_t *image,
opj_event_mgr_t * p_manager);
static void opj_j2k_dump_MH_info(opj_j2k_t* p_j2k, FILE* out_stream);
static void opj_j2k_dump_MH_index(opj_j2k_t* p_j2k, FILE* out_stream);
static opj_codestream_index_t* opj_j2k_create_cstr_index(void);
static OPJ_FLOAT32 opj_j2k_get_tp_stride(opj_tcp_t * p_tcp);
static OPJ_FLOAT32 opj_j2k_get_default_stride(opj_tcp_t * p_tcp);
static int opj_j2k_initialise_4K_poc(opj_poc_t *POC, int numres);
static void opj_j2k_set_cinema_parameters(opj_cparameters_t *parameters,
opj_image_t *image, opj_event_mgr_t *p_manager);
static OPJ_BOOL opj_j2k_is_cinema_compliant(opj_image_t *image, OPJ_UINT16 rsiz,
opj_event_mgr_t *p_manager);
/**
* Checks for invalid number of tile-parts in SOT marker (TPsot==TNsot). See issue 254.
*
* @param p_stream the stream to read data from.
* @param tile_no tile number we're looking for.
* @param p_correction_needed output value. if true, non conformant codestream needs TNsot correction.
* @param p_manager the user event manager.
*
* @return true if the function was successful, false else.
*/
static OPJ_BOOL opj_j2k_need_nb_tile_parts_correction(opj_stream_private_t
*p_stream, OPJ_UINT32 tile_no, OPJ_BOOL* p_correction_needed,
opj_event_mgr_t * p_manager);
/*@}*/
/*@}*/
/* ----------------------------------------------------------------------- */
typedef struct j2k_prog_order {
OPJ_PROG_ORDER enum_prog;
char str_prog[5];
} j2k_prog_order_t;
static const j2k_prog_order_t j2k_prog_order_list[] = {
{OPJ_CPRL, "CPRL"},
{OPJ_LRCP, "LRCP"},
{OPJ_PCRL, "PCRL"},
{OPJ_RLCP, "RLCP"},
{OPJ_RPCL, "RPCL"},
{(OPJ_PROG_ORDER) - 1, ""}
};
/**
* FIXME DOC
*/
static const OPJ_UINT32 MCT_ELEMENT_SIZE [] = {
2,
4,
4,
8
};
typedef void (* opj_j2k_mct_function)(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static const opj_j2k_mct_function j2k_mct_read_functions_to_float [] = {
opj_j2k_read_int16_to_float,
opj_j2k_read_int32_to_float,
opj_j2k_read_float32_to_float,
opj_j2k_read_float64_to_float
};
static const opj_j2k_mct_function j2k_mct_read_functions_to_int32 [] = {
opj_j2k_read_int16_to_int32,
opj_j2k_read_int32_to_int32,
opj_j2k_read_float32_to_int32,
opj_j2k_read_float64_to_int32
};
static const opj_j2k_mct_function j2k_mct_write_functions_from_float [] = {
opj_j2k_write_float_to_int16,
opj_j2k_write_float_to_int32,
opj_j2k_write_float_to_float,
opj_j2k_write_float_to_float64
};
typedef struct opj_dec_memory_marker_handler {
/** marker value */
OPJ_UINT32 id;
/** value of the state when the marker can appear */
OPJ_UINT32 states;
/** action linked to the marker */
OPJ_BOOL(*handler)(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
}
opj_dec_memory_marker_handler_t;
static const opj_dec_memory_marker_handler_t j2k_memory_marker_handler_tab [] =
{
{J2K_MS_SOT, J2K_STATE_MH | J2K_STATE_TPHSOT, opj_j2k_read_sot},
{J2K_MS_COD, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_cod},
{J2K_MS_COC, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_coc},
{J2K_MS_RGN, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_rgn},
{J2K_MS_QCD, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_qcd},
{J2K_MS_QCC, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_qcc},
{J2K_MS_POC, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_poc},
{J2K_MS_SIZ, J2K_STATE_MHSIZ, opj_j2k_read_siz},
{J2K_MS_TLM, J2K_STATE_MH, opj_j2k_read_tlm},
{J2K_MS_PLM, J2K_STATE_MH, opj_j2k_read_plm},
{J2K_MS_PLT, J2K_STATE_TPH, opj_j2k_read_plt},
{J2K_MS_PPM, J2K_STATE_MH, opj_j2k_read_ppm},
{J2K_MS_PPT, J2K_STATE_TPH, opj_j2k_read_ppt},
{J2K_MS_SOP, 0, 0},
{J2K_MS_CRG, J2K_STATE_MH, opj_j2k_read_crg},
{J2K_MS_COM, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_com},
{J2K_MS_MCT, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_mct},
{J2K_MS_CBD, J2K_STATE_MH, opj_j2k_read_cbd},
{J2K_MS_MCC, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_mcc},
{J2K_MS_MCO, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_mco},
#ifdef USE_JPWL
#ifdef TODO_MS /* remove these functions which are not commpatible with the v2 API */
{J2K_MS_EPC, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_epc},
{J2K_MS_EPB, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_epb},
{J2K_MS_ESD, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_esd},
{J2K_MS_RED, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_red},
#endif
#endif /* USE_JPWL */
#ifdef USE_JPSEC
{J2K_MS_SEC, J2K_DEC_STATE_MH, j2k_read_sec},
{J2K_MS_INSEC, 0, j2k_read_insec}
#endif /* USE_JPSEC */
{J2K_MS_UNK, J2K_STATE_MH | J2K_STATE_TPH, 0}/*opj_j2k_read_unk is directly used*/
};
static void opj_j2k_read_int16_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_FLOAT32 * l_dest_data = (OPJ_FLOAT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_UINT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
opj_read_bytes(l_src_data, &l_temp, 2);
l_src_data += sizeof(OPJ_INT16);
*(l_dest_data++) = (OPJ_FLOAT32) l_temp;
}
}
static void opj_j2k_read_int32_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_FLOAT32 * l_dest_data = (OPJ_FLOAT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_UINT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
opj_read_bytes(l_src_data, &l_temp, 4);
l_src_data += sizeof(OPJ_INT32);
*(l_dest_data++) = (OPJ_FLOAT32) l_temp;
}
}
static void opj_j2k_read_float32_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_FLOAT32 * l_dest_data = (OPJ_FLOAT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_FLOAT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
opj_read_float(l_src_data, &l_temp);
l_src_data += sizeof(OPJ_FLOAT32);
*(l_dest_data++) = l_temp;
}
}
static void opj_j2k_read_float64_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_FLOAT32 * l_dest_data = (OPJ_FLOAT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_FLOAT64 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
opj_read_double(l_src_data, &l_temp);
l_src_data += sizeof(OPJ_FLOAT64);
*(l_dest_data++) = (OPJ_FLOAT32) l_temp;
}
}
static void opj_j2k_read_int16_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_INT32 * l_dest_data = (OPJ_INT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_UINT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
opj_read_bytes(l_src_data, &l_temp, 2);
l_src_data += sizeof(OPJ_INT16);
*(l_dest_data++) = (OPJ_INT32) l_temp;
}
}
static void opj_j2k_read_int32_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_INT32 * l_dest_data = (OPJ_INT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_UINT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
opj_read_bytes(l_src_data, &l_temp, 4);
l_src_data += sizeof(OPJ_INT32);
*(l_dest_data++) = (OPJ_INT32) l_temp;
}
}
static void opj_j2k_read_float32_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_INT32 * l_dest_data = (OPJ_INT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_FLOAT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
opj_read_float(l_src_data, &l_temp);
l_src_data += sizeof(OPJ_FLOAT32);
*(l_dest_data++) = (OPJ_INT32) l_temp;
}
}
static void opj_j2k_read_float64_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_INT32 * l_dest_data = (OPJ_INT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_FLOAT64 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
opj_read_double(l_src_data, &l_temp);
l_src_data += sizeof(OPJ_FLOAT64);
*(l_dest_data++) = (OPJ_INT32) l_temp;
}
}
static void opj_j2k_write_float_to_int16(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_dest_data = (OPJ_BYTE *) p_dest_data;
OPJ_FLOAT32 * l_src_data = (OPJ_FLOAT32 *) p_src_data;
OPJ_UINT32 i;
OPJ_UINT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
l_temp = (OPJ_UINT32) * (l_src_data++);
opj_write_bytes(l_dest_data, l_temp, sizeof(OPJ_INT16));
l_dest_data += sizeof(OPJ_INT16);
}
}
static void opj_j2k_write_float_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_dest_data = (OPJ_BYTE *) p_dest_data;
OPJ_FLOAT32 * l_src_data = (OPJ_FLOAT32 *) p_src_data;
OPJ_UINT32 i;
OPJ_UINT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
l_temp = (OPJ_UINT32) * (l_src_data++);
opj_write_bytes(l_dest_data, l_temp, sizeof(OPJ_INT32));
l_dest_data += sizeof(OPJ_INT32);
}
}
static void opj_j2k_write_float_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_dest_data = (OPJ_BYTE *) p_dest_data;
OPJ_FLOAT32 * l_src_data = (OPJ_FLOAT32 *) p_src_data;
OPJ_UINT32 i;
OPJ_FLOAT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
l_temp = (OPJ_FLOAT32) * (l_src_data++);
opj_write_float(l_dest_data, l_temp);
l_dest_data += sizeof(OPJ_FLOAT32);
}
}
static void opj_j2k_write_float_to_float64(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_dest_data = (OPJ_BYTE *) p_dest_data;
OPJ_FLOAT32 * l_src_data = (OPJ_FLOAT32 *) p_src_data;
OPJ_UINT32 i;
OPJ_FLOAT64 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
l_temp = (OPJ_FLOAT64) * (l_src_data++);
opj_write_double(l_dest_data, l_temp);
l_dest_data += sizeof(OPJ_FLOAT64);
}
}
const char *opj_j2k_convert_progression_order(OPJ_PROG_ORDER prg_order)
{
const j2k_prog_order_t *po;
for (po = j2k_prog_order_list; po->enum_prog != -1; po++) {
if (po->enum_prog == prg_order) {
return po->str_prog;
}
}
return po->str_prog;
}
static OPJ_BOOL opj_j2k_check_poc_val(const opj_poc_t *p_pocs,
OPJ_UINT32 p_nb_pocs,
OPJ_UINT32 p_nb_resolutions,
OPJ_UINT32 p_num_comps,
OPJ_UINT32 p_num_layers,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32* packet_array;
OPJ_UINT32 index, resno, compno, layno;
OPJ_UINT32 i;
OPJ_UINT32 step_c = 1;
OPJ_UINT32 step_r = p_num_comps * step_c;
OPJ_UINT32 step_l = p_nb_resolutions * step_r;
OPJ_BOOL loss = OPJ_FALSE;
OPJ_UINT32 layno0 = 0;
packet_array = (OPJ_UINT32*) opj_calloc(step_l * p_num_layers,
sizeof(OPJ_UINT32));
if (packet_array == 00) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory for checking the poc values.\n");
return OPJ_FALSE;
}
if (p_nb_pocs == 0) {
opj_free(packet_array);
return OPJ_TRUE;
}
index = step_r * p_pocs->resno0;
/* take each resolution for each poc */
for (resno = p_pocs->resno0 ; resno < p_pocs->resno1 ; ++resno) {
OPJ_UINT32 res_index = index + p_pocs->compno0 * step_c;
/* take each comp of each resolution for each poc */
for (compno = p_pocs->compno0 ; compno < p_pocs->compno1 ; ++compno) {
OPJ_UINT32 comp_index = res_index + layno0 * step_l;
/* and finally take each layer of each res of ... */
for (layno = layno0; layno < p_pocs->layno1 ; ++layno) {
/*index = step_r * resno + step_c * compno + step_l * layno;*/
packet_array[comp_index] = 1;
comp_index += step_l;
}
res_index += step_c;
}
index += step_r;
}
++p_pocs;
/* iterate through all the pocs */
for (i = 1; i < p_nb_pocs ; ++i) {
OPJ_UINT32 l_last_layno1 = (p_pocs - 1)->layno1 ;
layno0 = (p_pocs->layno1 > l_last_layno1) ? l_last_layno1 : 0;
index = step_r * p_pocs->resno0;
/* take each resolution for each poc */
for (resno = p_pocs->resno0 ; resno < p_pocs->resno1 ; ++resno) {
OPJ_UINT32 res_index = index + p_pocs->compno0 * step_c;
/* take each comp of each resolution for each poc */
for (compno = p_pocs->compno0 ; compno < p_pocs->compno1 ; ++compno) {
OPJ_UINT32 comp_index = res_index + layno0 * step_l;
/* and finally take each layer of each res of ... */
for (layno = layno0; layno < p_pocs->layno1 ; ++layno) {
/*index = step_r * resno + step_c * compno + step_l * layno;*/
packet_array[comp_index] = 1;
comp_index += step_l;
}
res_index += step_c;
}
index += step_r;
}
++p_pocs;
}
index = 0;
for (layno = 0; layno < p_num_layers ; ++layno) {
for (resno = 0; resno < p_nb_resolutions; ++resno) {
for (compno = 0; compno < p_num_comps; ++compno) {
loss |= (packet_array[index] != 1);
/*index = step_r * resno + step_c * compno + step_l * layno;*/
index += step_c;
}
}
}
if (loss) {
opj_event_msg(p_manager, EVT_ERROR, "Missing packets possible loss of data\n");
}
opj_free(packet_array);
return !loss;
}
/* ----------------------------------------------------------------------- */
static OPJ_UINT32 opj_j2k_get_num_tp(opj_cp_t *cp, OPJ_UINT32 pino,
OPJ_UINT32 tileno)
{
const OPJ_CHAR *prog = 00;
OPJ_INT32 i;
OPJ_UINT32 tpnum = 1;
opj_tcp_t *tcp = 00;
opj_poc_t * l_current_poc = 00;
/* preconditions */
assert(tileno < (cp->tw * cp->th));
assert(pino < (cp->tcps[tileno].numpocs + 1));
/* get the given tile coding parameter */
tcp = &cp->tcps[tileno];
assert(tcp != 00);
l_current_poc = &(tcp->pocs[pino]);
assert(l_current_poc != 0);
/* get the progression order as a character string */
prog = opj_j2k_convert_progression_order(tcp->prg);
assert(strlen(prog) > 0);
if (cp->m_specific_param.m_enc.m_tp_on == 1) {
for (i = 0; i < 4; ++i) {
switch (prog[i]) {
/* component wise */
case 'C':
tpnum *= l_current_poc->compE;
break;
/* resolution wise */
case 'R':
tpnum *= l_current_poc->resE;
break;
/* precinct wise */
case 'P':
tpnum *= l_current_poc->prcE;
break;
/* layer wise */
case 'L':
tpnum *= l_current_poc->layE;
break;
}
/* whould we split here ? */
if (cp->m_specific_param.m_enc.m_tp_flag == prog[i]) {
cp->m_specific_param.m_enc.m_tp_pos = i;
break;
}
}
} else {
tpnum = 1;
}
return tpnum;
}
static OPJ_BOOL opj_j2k_calculate_tp(opj_j2k_t *p_j2k,
opj_cp_t *cp,
OPJ_UINT32 * p_nb_tiles,
opj_image_t *image,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 pino, tileno;
OPJ_UINT32 l_nb_tiles;
opj_tcp_t *tcp;
/* preconditions */
assert(p_nb_tiles != 00);
assert(cp != 00);
assert(image != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_j2k);
OPJ_UNUSED(p_manager);
l_nb_tiles = cp->tw * cp->th;
* p_nb_tiles = 0;
tcp = cp->tcps;
/* INDEX >> */
/* TODO mergeV2: check this part which use cstr_info */
/*if (p_j2k->cstr_info) {
opj_tile_info_t * l_info_tile_ptr = p_j2k->cstr_info->tile;
for (tileno = 0; tileno < l_nb_tiles; ++tileno) {
OPJ_UINT32 cur_totnum_tp = 0;
opj_pi_update_encoding_parameters(image,cp,tileno);
for (pino = 0; pino <= tcp->numpocs; ++pino)
{
OPJ_UINT32 tp_num = opj_j2k_get_num_tp(cp,pino,tileno);
*p_nb_tiles = *p_nb_tiles + tp_num;
cur_totnum_tp += tp_num;
}
tcp->m_nb_tile_parts = cur_totnum_tp;
l_info_tile_ptr->tp = (opj_tp_info_t *) opj_malloc(cur_totnum_tp * sizeof(opj_tp_info_t));
if (l_info_tile_ptr->tp == 00) {
return OPJ_FALSE;
}
memset(l_info_tile_ptr->tp,0,cur_totnum_tp * sizeof(opj_tp_info_t));
l_info_tile_ptr->num_tps = cur_totnum_tp;
++l_info_tile_ptr;
++tcp;
}
}
else */{
for (tileno = 0; tileno < l_nb_tiles; ++tileno) {
OPJ_UINT32 cur_totnum_tp = 0;
opj_pi_update_encoding_parameters(image, cp, tileno);
for (pino = 0; pino <= tcp->numpocs; ++pino) {
OPJ_UINT32 tp_num = opj_j2k_get_num_tp(cp, pino, tileno);
*p_nb_tiles = *p_nb_tiles + tp_num;
cur_totnum_tp += tp_num;
}
tcp->m_nb_tile_parts = cur_totnum_tp;
++tcp;
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_soc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
/* 2 bytes will be written */
OPJ_BYTE * l_start_stream = 00;
/* preconditions */
assert(p_stream != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_start_stream = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
/* write SOC identifier */
opj_write_bytes(l_start_stream, J2K_MS_SOC, 2);
if (opj_stream_write_data(p_stream, l_start_stream, 2, p_manager) != 2) {
return OPJ_FALSE;
}
/* UniPG>> */
#ifdef USE_JPWL
/* update markers struct */
/*
OPJ_BOOL res = j2k_add_marker(p_j2k->cstr_info, J2K_MS_SOC, p_stream_tell(p_stream) - 2, 2);
*/
assert(0 && "TODO");
#endif /* USE_JPWL */
/* <<UniPG */
return OPJ_TRUE;
}
/**
* Reads a SOC marker (Start of Codestream)
* @param p_j2k the jpeg2000 file codec.
* @param p_stream FIXME DOC
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_soc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_BYTE l_data [2];
OPJ_UINT32 l_marker;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
if (opj_stream_read_data(p_stream, l_data, 2, p_manager) != 2) {
return OPJ_FALSE;
}
opj_read_bytes(l_data, &l_marker, 2);
if (l_marker != J2K_MS_SOC) {
return OPJ_FALSE;
}
/* Next marker should be a SIZ marker in the main header */
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_MHSIZ;
/* FIXME move it in a index structure included in p_j2k*/
p_j2k->cstr_index->main_head_start = opj_stream_tell(p_stream) - 2;
opj_event_msg(p_manager, EVT_INFO, "Start to read j2k main header (%d).\n",
p_j2k->cstr_index->main_head_start);
/* Add the marker to the codestream index*/
if (OPJ_FALSE == opj_j2k_add_mhmarker(p_j2k->cstr_index, J2K_MS_SOC,
p_j2k->cstr_index->main_head_start, 2)) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add mh marker\n");
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_siz(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 i;
OPJ_UINT32 l_size_len;
OPJ_BYTE * l_current_ptr;
opj_image_t * l_image = 00;
opj_cp_t *cp = 00;
opj_image_comp_t * l_img_comp = 00;
/* preconditions */
assert(p_stream != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_image = p_j2k->m_private_image;
cp = &(p_j2k->m_cp);
l_size_len = 40 + 3 * l_image->numcomps;
l_img_comp = l_image->comps;
if (l_size_len > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_size_len);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory for the SIZ marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_size_len;
}
l_current_ptr = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
/* write SOC identifier */
opj_write_bytes(l_current_ptr, J2K_MS_SIZ, 2); /* SIZ */
l_current_ptr += 2;
opj_write_bytes(l_current_ptr, l_size_len - 2, 2); /* L_SIZ */
l_current_ptr += 2;
opj_write_bytes(l_current_ptr, cp->rsiz, 2); /* Rsiz (capabilities) */
l_current_ptr += 2;
opj_write_bytes(l_current_ptr, l_image->x1, 4); /* Xsiz */
l_current_ptr += 4;
opj_write_bytes(l_current_ptr, l_image->y1, 4); /* Ysiz */
l_current_ptr += 4;
opj_write_bytes(l_current_ptr, l_image->x0, 4); /* X0siz */
l_current_ptr += 4;
opj_write_bytes(l_current_ptr, l_image->y0, 4); /* Y0siz */
l_current_ptr += 4;
opj_write_bytes(l_current_ptr, cp->tdx, 4); /* XTsiz */
l_current_ptr += 4;
opj_write_bytes(l_current_ptr, cp->tdy, 4); /* YTsiz */
l_current_ptr += 4;
opj_write_bytes(l_current_ptr, cp->tx0, 4); /* XT0siz */
l_current_ptr += 4;
opj_write_bytes(l_current_ptr, cp->ty0, 4); /* YT0siz */
l_current_ptr += 4;
opj_write_bytes(l_current_ptr, l_image->numcomps, 2); /* Csiz */
l_current_ptr += 2;
for (i = 0; i < l_image->numcomps; ++i) {
/* TODO here with MCT ? */
opj_write_bytes(l_current_ptr, l_img_comp->prec - 1 + (l_img_comp->sgnd << 7),
1); /* Ssiz_i */
++l_current_ptr;
opj_write_bytes(l_current_ptr, l_img_comp->dx, 1); /* XRsiz_i */
++l_current_ptr;
opj_write_bytes(l_current_ptr, l_img_comp->dy, 1); /* YRsiz_i */
++l_current_ptr;
++l_img_comp;
}
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_size_len,
p_manager) != l_size_len) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a SIZ marker (image and tile size)
* @param p_j2k the jpeg2000 file codec.
* @param p_header_data the data contained in the SIZ box.
* @param p_header_size the size of the data contained in the SIZ marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_siz(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 i;
OPJ_UINT32 l_nb_comp;
OPJ_UINT32 l_nb_comp_remain;
OPJ_UINT32 l_remaining_size;
OPJ_UINT32 l_nb_tiles;
OPJ_UINT32 l_tmp, l_tx1, l_ty1;
OPJ_UINT32 l_prec0, l_sgnd0;
opj_image_t *l_image = 00;
opj_cp_t *l_cp = 00;
opj_image_comp_t * l_img_comp = 00;
opj_tcp_t * l_current_tile_param = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_header_data != 00);
l_image = p_j2k->m_private_image;
l_cp = &(p_j2k->m_cp);
/* minimum size == 39 - 3 (= minimum component parameter) */
if (p_header_size < 36) {
opj_event_msg(p_manager, EVT_ERROR, "Error with SIZ marker size\n");
return OPJ_FALSE;
}
l_remaining_size = p_header_size - 36;
l_nb_comp = l_remaining_size / 3;
l_nb_comp_remain = l_remaining_size % 3;
if (l_nb_comp_remain != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error with SIZ marker size\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_tmp,
2); /* Rsiz (capabilities) */
p_header_data += 2;
l_cp->rsiz = (OPJ_UINT16) l_tmp;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_image->x1, 4); /* Xsiz */
p_header_data += 4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_image->y1, 4); /* Ysiz */
p_header_data += 4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_image->x0, 4); /* X0siz */
p_header_data += 4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_image->y0, 4); /* Y0siz */
p_header_data += 4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_cp->tdx,
4); /* XTsiz */
p_header_data += 4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_cp->tdy,
4); /* YTsiz */
p_header_data += 4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_cp->tx0,
4); /* XT0siz */
p_header_data += 4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_cp->ty0,
4); /* YT0siz */
p_header_data += 4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_tmp,
2); /* Csiz */
p_header_data += 2;
if (l_tmp < 16385) {
l_image->numcomps = (OPJ_UINT16) l_tmp;
} else {
opj_event_msg(p_manager, EVT_ERROR,
"Error with SIZ marker: number of component is illegal -> %d\n", l_tmp);
return OPJ_FALSE;
}
if (l_image->numcomps != l_nb_comp) {
opj_event_msg(p_manager, EVT_ERROR,
"Error with SIZ marker: number of component is not compatible with the remaining number of parameters ( %d vs %d)\n",
l_image->numcomps, l_nb_comp);
return OPJ_FALSE;
}
/* testcase 4035.pdf.SIGSEGV.d8b.3375 */
/* testcase issue427-null-image-size.jp2 */
if ((l_image->x0 >= l_image->x1) || (l_image->y0 >= l_image->y1)) {
opj_event_msg(p_manager, EVT_ERROR,
"Error with SIZ marker: negative or zero image size (%" PRId64 " x %" PRId64
")\n", (OPJ_INT64)l_image->x1 - l_image->x0,
(OPJ_INT64)l_image->y1 - l_image->y0);
return OPJ_FALSE;
}
/* testcase 2539.pdf.SIGFPE.706.1712 (also 3622.pdf.SIGFPE.706.2916 and 4008.pdf.SIGFPE.706.3345 and maybe more) */
if ((l_cp->tdx == 0U) || (l_cp->tdy == 0U)) {
opj_event_msg(p_manager, EVT_ERROR,
"Error with SIZ marker: invalid tile size (tdx: %d, tdy: %d)\n", l_cp->tdx,
l_cp->tdy);
return OPJ_FALSE;
}
/* testcase 1610.pdf.SIGSEGV.59c.681 */
if ((0xFFFFFFFFU / l_image->x1) < l_image->y1) {
opj_event_msg(p_manager, EVT_ERROR,
"Prevent buffer overflow (x1: %d, y1: %d)\n", l_image->x1, l_image->y1);
return OPJ_FALSE;
}
/* testcase issue427-illegal-tile-offset.jp2 */
l_tx1 = opj_uint_adds(l_cp->tx0, l_cp->tdx); /* manage overflow */
l_ty1 = opj_uint_adds(l_cp->ty0, l_cp->tdy); /* manage overflow */
if ((l_cp->tx0 > l_image->x0) || (l_cp->ty0 > l_image->y0) ||
(l_tx1 <= l_image->x0) || (l_ty1 <= l_image->y0)) {
opj_event_msg(p_manager, EVT_ERROR,
"Error with SIZ marker: illegal tile offset\n");
return OPJ_FALSE;
}
if (!p_j2k->dump_state) {
OPJ_UINT32 siz_w, siz_h;
siz_w = l_image->x1 - l_image->x0;
siz_h = l_image->y1 - l_image->y0;
if (p_j2k->ihdr_w > 0 && p_j2k->ihdr_h > 0
&& (p_j2k->ihdr_w != siz_w || p_j2k->ihdr_h != siz_h)) {
opj_event_msg(p_manager, EVT_ERROR,
"Error with SIZ marker: IHDR w(%u) h(%u) vs. SIZ w(%u) h(%u)\n", p_j2k->ihdr_w,
p_j2k->ihdr_h, siz_w, siz_h);
return OPJ_FALSE;
}
}
#ifdef USE_JPWL
if (l_cp->correct) {
/* if JPWL is on, we check whether TX errors have damaged
too much the SIZ parameters */
if (!(l_image->x1 * l_image->y1)) {
opj_event_msg(p_manager, EVT_ERROR,
"JPWL: bad image size (%d x %d)\n",
l_image->x1, l_image->y1);
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
}
/* FIXME check previously in the function so why keep this piece of code ? Need by the norm ?
if (l_image->numcomps != ((len - 38) / 3)) {
opj_event_msg(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
"JPWL: Csiz is %d => space in SIZ only for %d comps.!!!\n",
l_image->numcomps, ((len - 38) / 3));
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
*/ /* we try to correct */
/* opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust this\n");
if (l_image->numcomps < ((len - 38) / 3)) {
len = 38 + 3 * l_image->numcomps;
opj_event_msg(p_manager, EVT_WARNING, "- setting Lsiz to %d => HYPOTHESIS!!!\n",
len);
} else {
l_image->numcomps = ((len - 38) / 3);
opj_event_msg(p_manager, EVT_WARNING, "- setting Csiz to %d => HYPOTHESIS!!!\n",
l_image->numcomps);
}
}
*/
/* update components number in the jpwl_exp_comps filed */
l_cp->exp_comps = l_image->numcomps;
}
#endif /* USE_JPWL */
/* Allocate the resulting image components */
l_image->comps = (opj_image_comp_t*) opj_calloc(l_image->numcomps,
sizeof(opj_image_comp_t));
if (l_image->comps == 00) {
l_image->numcomps = 0;
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to take in charge SIZ marker\n");
return OPJ_FALSE;
}
l_img_comp = l_image->comps;
l_prec0 = 0;
l_sgnd0 = 0;
/* Read the component information */
for (i = 0; i < l_image->numcomps; ++i) {
OPJ_UINT32 tmp;
opj_read_bytes(p_header_data, &tmp, 1); /* Ssiz_i */
++p_header_data;
l_img_comp->prec = (tmp & 0x7f) + 1;
l_img_comp->sgnd = tmp >> 7;
if (p_j2k->dump_state == 0) {
if (i == 0) {
l_prec0 = l_img_comp->prec;
l_sgnd0 = l_img_comp->sgnd;
} else if (!l_cp->allow_different_bit_depth_sign
&& (l_img_comp->prec != l_prec0 || l_img_comp->sgnd != l_sgnd0)) {
opj_event_msg(p_manager, EVT_WARNING,
"Despite JP2 BPC!=255, precision and/or sgnd values for comp[%d] is different than comp[0]:\n"
" [0] prec(%d) sgnd(%d) [%d] prec(%d) sgnd(%d)\n", i, l_prec0, l_sgnd0,
i, l_img_comp->prec, l_img_comp->sgnd);
}
/* TODO: we should perhaps also check against JP2 BPCC values */
}
opj_read_bytes(p_header_data, &tmp, 1); /* XRsiz_i */
++p_header_data;
l_img_comp->dx = (OPJ_UINT32)tmp; /* should be between 1 and 255 */
opj_read_bytes(p_header_data, &tmp, 1); /* YRsiz_i */
++p_header_data;
l_img_comp->dy = (OPJ_UINT32)tmp; /* should be between 1 and 255 */
if (l_img_comp->dx < 1 || l_img_comp->dx > 255 ||
l_img_comp->dy < 1 || l_img_comp->dy > 255) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid values for comp = %d : dx=%u dy=%u (should be between 1 and 255 according to the JPEG2000 norm)\n",
i, l_img_comp->dx, l_img_comp->dy);
return OPJ_FALSE;
}
/* Avoids later undefined shift in computation of */
/* p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps[i].m_dc_level_shift = 1
<< (l_image->comps[i].prec - 1); */
if (l_img_comp->prec > 31) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid values for comp = %d : prec=%u (should be between 1 and 38 according to the JPEG2000 norm. OpenJpeg only supports up to 31)\n",
i, l_img_comp->prec);
return OPJ_FALSE;
}
#ifdef USE_JPWL
if (l_cp->correct) {
/* if JPWL is on, we check whether TX errors have damaged
too much the SIZ parameters, again */
if (!(l_image->comps[i].dx * l_image->comps[i].dy)) {
opj_event_msg(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
"JPWL: bad XRsiz_%d/YRsiz_%d (%d x %d)\n",
i, i, l_image->comps[i].dx, l_image->comps[i].dy);
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
/* we try to correct */
opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust them\n");
if (!l_image->comps[i].dx) {
l_image->comps[i].dx = 1;
opj_event_msg(p_manager, EVT_WARNING,
"- setting XRsiz_%d to %d => HYPOTHESIS!!!\n",
i, l_image->comps[i].dx);
}
if (!l_image->comps[i].dy) {
l_image->comps[i].dy = 1;
opj_event_msg(p_manager, EVT_WARNING,
"- setting YRsiz_%d to %d => HYPOTHESIS!!!\n",
i, l_image->comps[i].dy);
}
}
}
#endif /* USE_JPWL */
l_img_comp->resno_decoded =
0; /* number of resolution decoded */
l_img_comp->factor =
l_cp->m_specific_param.m_dec.m_reduce; /* reducing factor per component */
++l_img_comp;
}
if (l_cp->tdx == 0 || l_cp->tdy == 0) {
return OPJ_FALSE;
}
/* Compute the number of tiles */
l_cp->tw = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)(l_image->x1 - l_cp->tx0),
(OPJ_INT32)l_cp->tdx);
l_cp->th = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)(l_image->y1 - l_cp->ty0),
(OPJ_INT32)l_cp->tdy);
/* Check that the number of tiles is valid */
if (l_cp->tw == 0 || l_cp->th == 0 || l_cp->tw > 65535 / l_cp->th) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid number of tiles : %u x %u (maximum fixed by jpeg2000 norm is 65535 tiles)\n",
l_cp->tw, l_cp->th);
return OPJ_FALSE;
}
l_nb_tiles = l_cp->tw * l_cp->th;
/* Define the tiles which will be decoded */
if (p_j2k->m_specific_param.m_decoder.m_discard_tiles) {
p_j2k->m_specific_param.m_decoder.m_start_tile_x =
(p_j2k->m_specific_param.m_decoder.m_start_tile_x - l_cp->tx0) / l_cp->tdx;
p_j2k->m_specific_param.m_decoder.m_start_tile_y =
(p_j2k->m_specific_param.m_decoder.m_start_tile_y - l_cp->ty0) / l_cp->tdy;
p_j2k->m_specific_param.m_decoder.m_end_tile_x = (OPJ_UINT32)opj_int_ceildiv((
OPJ_INT32)(p_j2k->m_specific_param.m_decoder.m_end_tile_x - l_cp->tx0),
(OPJ_INT32)l_cp->tdx);
p_j2k->m_specific_param.m_decoder.m_end_tile_y = (OPJ_UINT32)opj_int_ceildiv((
OPJ_INT32)(p_j2k->m_specific_param.m_decoder.m_end_tile_y - l_cp->ty0),
(OPJ_INT32)l_cp->tdy);
} else {
p_j2k->m_specific_param.m_decoder.m_start_tile_x = 0;
p_j2k->m_specific_param.m_decoder.m_start_tile_y = 0;
p_j2k->m_specific_param.m_decoder.m_end_tile_x = l_cp->tw;
p_j2k->m_specific_param.m_decoder.m_end_tile_y = l_cp->th;
}
#ifdef USE_JPWL
if (l_cp->correct) {
/* if JPWL is on, we check whether TX errors have damaged
too much the SIZ parameters */
if ((l_cp->tw < 1) || (l_cp->th < 1) || (l_cp->tw > l_cp->max_tiles) ||
(l_cp->th > l_cp->max_tiles)) {
opj_event_msg(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
"JPWL: bad number of tiles (%d x %d)\n",
l_cp->tw, l_cp->th);
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
/* we try to correct */
opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust them\n");
if (l_cp->tw < 1) {
l_cp->tw = 1;
opj_event_msg(p_manager, EVT_WARNING,
"- setting %d tiles in x => HYPOTHESIS!!!\n",
l_cp->tw);
}
if (l_cp->tw > l_cp->max_tiles) {
l_cp->tw = 1;
opj_event_msg(p_manager, EVT_WARNING,
"- too large x, increase expectance of %d\n"
"- setting %d tiles in x => HYPOTHESIS!!!\n",
l_cp->max_tiles, l_cp->tw);
}
if (l_cp->th < 1) {
l_cp->th = 1;
opj_event_msg(p_manager, EVT_WARNING,
"- setting %d tiles in y => HYPOTHESIS!!!\n",
l_cp->th);
}
if (l_cp->th > l_cp->max_tiles) {
l_cp->th = 1;
opj_event_msg(p_manager, EVT_WARNING,
"- too large y, increase expectance of %d to continue\n",
"- setting %d tiles in y => HYPOTHESIS!!!\n",
l_cp->max_tiles, l_cp->th);
}
}
}
#endif /* USE_JPWL */
/* memory allocations */
l_cp->tcps = (opj_tcp_t*) opj_calloc(l_nb_tiles, sizeof(opj_tcp_t));
if (l_cp->tcps == 00) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to take in charge SIZ marker\n");
return OPJ_FALSE;
}
#ifdef USE_JPWL
if (l_cp->correct) {
if (!l_cp->tcps) {
opj_event_msg(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
"JPWL: could not alloc tcps field of cp\n");
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
}
}
#endif /* USE_JPWL */
p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps =
(opj_tccp_t*) opj_calloc(l_image->numcomps, sizeof(opj_tccp_t));
if (p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps == 00) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to take in charge SIZ marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mct_records =
(opj_mct_data_t*)opj_calloc(OPJ_J2K_MCT_DEFAULT_NB_RECORDS,
sizeof(opj_mct_data_t));
if (! p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mct_records) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to take in charge SIZ marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_decoder.m_default_tcp->m_nb_max_mct_records =
OPJ_J2K_MCT_DEFAULT_NB_RECORDS;
p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mcc_records =
(opj_simple_mcc_decorrelation_data_t*)
opj_calloc(OPJ_J2K_MCC_DEFAULT_NB_RECORDS,
sizeof(opj_simple_mcc_decorrelation_data_t));
if (! p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mcc_records) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to take in charge SIZ marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_decoder.m_default_tcp->m_nb_max_mcc_records =
OPJ_J2K_MCC_DEFAULT_NB_RECORDS;
/* set up default dc level shift */
for (i = 0; i < l_image->numcomps; ++i) {
if (! l_image->comps[i].sgnd) {
p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps[i].m_dc_level_shift = 1
<< (l_image->comps[i].prec - 1);
}
}
l_current_tile_param = l_cp->tcps;
for (i = 0; i < l_nb_tiles; ++i) {
l_current_tile_param->tccps = (opj_tccp_t*) opj_calloc(l_image->numcomps,
sizeof(opj_tccp_t));
if (l_current_tile_param->tccps == 00) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to take in charge SIZ marker\n");
return OPJ_FALSE;
}
++l_current_tile_param;
}
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_MH;
opj_image_comp_header_update(l_image, l_cp);
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_com(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_comment_size;
OPJ_UINT32 l_total_com_size;
const OPJ_CHAR *l_comment;
OPJ_BYTE * l_current_ptr = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
l_comment = p_j2k->m_cp.comment;
l_comment_size = (OPJ_UINT32)strlen(l_comment);
l_total_com_size = l_comment_size + 6;
if (l_total_com_size >
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_total_com_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to write the COM marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_total_com_size;
}
l_current_ptr = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_ptr, J2K_MS_COM, 2); /* COM */
l_current_ptr += 2;
opj_write_bytes(l_current_ptr, l_total_com_size - 2, 2); /* L_COM */
l_current_ptr += 2;
opj_write_bytes(l_current_ptr, 1,
2); /* General use (IS 8859-15:1999 (Latin) values) */
l_current_ptr += 2;
memcpy(l_current_ptr, l_comment, l_comment_size);
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_total_com_size,
p_manager) != l_total_com_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a COM marker (comments)
* @param p_j2k the jpeg2000 file codec.
* @param p_header_data the data contained in the COM box.
* @param p_header_size the size of the data contained in the COM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_com(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_header_data != 00);
OPJ_UNUSED(p_j2k);
OPJ_UNUSED(p_header_data);
OPJ_UNUSED(p_header_size);
OPJ_UNUSED(p_manager);
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_cod(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
OPJ_UINT32 l_code_size, l_remaining_size;
OPJ_BYTE * l_current_data = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_j2k->m_current_tile_number];
l_code_size = 9 + opj_j2k_get_SPCod_SPCoc_size(p_j2k,
p_j2k->m_current_tile_number, 0);
l_remaining_size = l_code_size;
if (l_code_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_code_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write COD marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_code_size;
}
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_data, J2K_MS_COD, 2); /* COD */
l_current_data += 2;
opj_write_bytes(l_current_data, l_code_size - 2, 2); /* L_COD */
l_current_data += 2;
opj_write_bytes(l_current_data, l_tcp->csty, 1); /* Scod */
++l_current_data;
opj_write_bytes(l_current_data, (OPJ_UINT32)l_tcp->prg, 1); /* SGcod (A) */
++l_current_data;
opj_write_bytes(l_current_data, l_tcp->numlayers, 2); /* SGcod (B) */
l_current_data += 2;
opj_write_bytes(l_current_data, l_tcp->mct, 1); /* SGcod (C) */
++l_current_data;
l_remaining_size -= 9;
if (! opj_j2k_write_SPCod_SPCoc(p_j2k, p_j2k->m_current_tile_number, 0,
l_current_data, &l_remaining_size, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing COD marker\n");
return OPJ_FALSE;
}
if (l_remaining_size != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing COD marker\n");
return OPJ_FALSE;
}
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_code_size,
p_manager) != l_code_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a COD marker (Coding Styke defaults)
* @param p_header_data the data contained in the COD box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the COD marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_cod(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
/* loop */
OPJ_UINT32 i;
OPJ_UINT32 l_tmp;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_image_t *l_image = 00;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_image = p_j2k->m_private_image;
l_cp = &(p_j2k->m_cp);
/* If we are in the first tile-part header of the current tile */
l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
/* Only one COD per tile */
if (l_tcp->cod) {
opj_event_msg(p_manager, EVT_ERROR,
"COD marker already read. No more than one COD marker per tile.\n");
return OPJ_FALSE;
}
l_tcp->cod = 1;
/* Make sure room is sufficient */
if (p_header_size < 5) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading COD marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_tcp->csty, 1); /* Scod */
++p_header_data;
/* Make sure we know how to decode this */
if ((l_tcp->csty & ~(OPJ_UINT32)(J2K_CP_CSTY_PRT | J2K_CP_CSTY_SOP |
J2K_CP_CSTY_EPH)) != 0U) {
opj_event_msg(p_manager, EVT_ERROR, "Unknown Scod value in COD marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_tmp, 1); /* SGcod (A) */
++p_header_data;
l_tcp->prg = (OPJ_PROG_ORDER) l_tmp;
/* Make sure progression order is valid */
if (l_tcp->prg > OPJ_CPRL) {
opj_event_msg(p_manager, EVT_ERROR,
"Unknown progression order in COD marker\n");
l_tcp->prg = OPJ_PROG_UNKNOWN;
}
opj_read_bytes(p_header_data, &l_tcp->numlayers, 2); /* SGcod (B) */
p_header_data += 2;
if ((l_tcp->numlayers < 1U) || (l_tcp->numlayers > 65535U)) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid number of layers in COD marker : %d not in range [1-65535]\n",
l_tcp->numlayers);
return OPJ_FALSE;
}
/* If user didn't set a number layer to decode take the max specify in the codestream. */
if (l_cp->m_specific_param.m_dec.m_layer) {
l_tcp->num_layers_to_decode = l_cp->m_specific_param.m_dec.m_layer;
} else {
l_tcp->num_layers_to_decode = l_tcp->numlayers;
}
opj_read_bytes(p_header_data, &l_tcp->mct, 1); /* SGcod (C) */
++p_header_data;
p_header_size -= 5;
for (i = 0; i < l_image->numcomps; ++i) {
l_tcp->tccps[i].csty = l_tcp->csty & J2K_CCP_CSTY_PRT;
}
if (! opj_j2k_read_SPCod_SPCoc(p_j2k, 0, p_header_data, &p_header_size,
p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading COD marker\n");
return OPJ_FALSE;
}
if (p_header_size != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading COD marker\n");
return OPJ_FALSE;
}
/* Apply the coding style to other components of the current tile or the m_default_tcp*/
opj_j2k_copy_tile_component_parameters(p_j2k);
/* Index */
#ifdef WIP_REMOVE_MSD
if (p_j2k->cstr_info) {
/*opj_codestream_info_t *l_cstr_info = p_j2k->cstr_info;*/
p_j2k->cstr_info->prog = l_tcp->prg;
p_j2k->cstr_info->numlayers = l_tcp->numlayers;
p_j2k->cstr_info->numdecompos = (OPJ_INT32*) opj_malloc(
l_image->numcomps * sizeof(OPJ_UINT32));
if (!p_j2k->cstr_info->numdecompos) {
return OPJ_FALSE;
}
for (i = 0; i < l_image->numcomps; ++i) {
p_j2k->cstr_info->numdecompos[i] = l_tcp->tccps[i].numresolutions - 1;
}
}
#endif
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_coc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 l_coc_size, l_remaining_size;
OPJ_UINT32 l_comp_room;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_comp_room = (p_j2k->m_private_image->numcomps <= 256) ? 1 : 2;
l_coc_size = 5 + l_comp_room + opj_j2k_get_SPCod_SPCoc_size(p_j2k,
p_j2k->m_current_tile_number, p_comp_no);
if (l_coc_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data;
/*p_j2k->m_specific_param.m_encoder.m_header_tile_data
= (OPJ_BYTE*)opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data,
l_coc_size);*/
new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_coc_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write COC marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_coc_size;
}
opj_j2k_write_coc_in_memory(p_j2k, p_comp_no,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, &l_remaining_size,
p_manager);
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_coc_size,
p_manager) != l_coc_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_compare_coc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no)
{
opj_cp_t *l_cp = NULL;
opj_tcp_t *l_tcp = NULL;
/* preconditions */
assert(p_j2k != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_j2k->m_current_tile_number];
if (l_tcp->tccps[p_first_comp_no].csty != l_tcp->tccps[p_second_comp_no].csty) {
return OPJ_FALSE;
}
return opj_j2k_compare_SPCod_SPCoc(p_j2k, p_j2k->m_current_tile_number,
p_first_comp_no, p_second_comp_no);
}
static void opj_j2k_write_coc_in_memory(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
opj_event_mgr_t * p_manager
)
{
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
OPJ_UINT32 l_coc_size, l_remaining_size;
OPJ_BYTE * l_current_data = 00;
opj_image_t *l_image = 00;
OPJ_UINT32 l_comp_room;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_j2k->m_current_tile_number];
l_image = p_j2k->m_private_image;
l_comp_room = (l_image->numcomps <= 256) ? 1 : 2;
l_coc_size = 5 + l_comp_room + opj_j2k_get_SPCod_SPCoc_size(p_j2k,
p_j2k->m_current_tile_number, p_comp_no);
l_remaining_size = l_coc_size;
l_current_data = p_data;
opj_write_bytes(l_current_data, J2K_MS_COC,
2); /* COC */
l_current_data += 2;
opj_write_bytes(l_current_data, l_coc_size - 2,
2); /* L_COC */
l_current_data += 2;
opj_write_bytes(l_current_data, p_comp_no, l_comp_room); /* Ccoc */
l_current_data += l_comp_room;
opj_write_bytes(l_current_data, l_tcp->tccps[p_comp_no].csty,
1); /* Scoc */
++l_current_data;
l_remaining_size -= (5 + l_comp_room);
opj_j2k_write_SPCod_SPCoc(p_j2k, p_j2k->m_current_tile_number, 0,
l_current_data, &l_remaining_size, p_manager);
* p_data_written = l_coc_size;
}
static OPJ_UINT32 opj_j2k_get_max_coc_size(opj_j2k_t *p_j2k)
{
OPJ_UINT32 i, j;
OPJ_UINT32 l_nb_comp;
OPJ_UINT32 l_nb_tiles;
OPJ_UINT32 l_max = 0;
/* preconditions */
l_nb_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th ;
l_nb_comp = p_j2k->m_private_image->numcomps;
for (i = 0; i < l_nb_tiles; ++i) {
for (j = 0; j < l_nb_comp; ++j) {
l_max = opj_uint_max(l_max, opj_j2k_get_SPCod_SPCoc_size(p_j2k, i, j));
}
}
return 6 + l_max;
}
/**
* Reads a COC marker (Coding Style Component)
* @param p_header_data the data contained in the COC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the COC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_coc(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
opj_cp_t *l_cp = NULL;
opj_tcp_t *l_tcp = NULL;
opj_image_t *l_image = NULL;
OPJ_UINT32 l_comp_room;
OPJ_UINT32 l_comp_no;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH)
?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
l_image = p_j2k->m_private_image;
l_comp_room = l_image->numcomps <= 256 ? 1 : 2;
/* make sure room is sufficient*/
if (p_header_size < l_comp_room + 1) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading COC marker\n");
return OPJ_FALSE;
}
p_header_size -= l_comp_room + 1;
opj_read_bytes(p_header_data, &l_comp_no,
l_comp_room); /* Ccoc */
p_header_data += l_comp_room;
if (l_comp_no >= l_image->numcomps) {
opj_event_msg(p_manager, EVT_ERROR,
"Error reading COC marker (bad number of components)\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_tcp->tccps[l_comp_no].csty,
1); /* Scoc */
++p_header_data ;
if (! opj_j2k_read_SPCod_SPCoc(p_j2k, l_comp_no, p_header_data, &p_header_size,
p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading COC marker\n");
return OPJ_FALSE;
}
if (p_header_size != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading COC marker\n");
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_qcd(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_qcd_size, l_remaining_size;
OPJ_BYTE * l_current_data = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_qcd_size = 4 + opj_j2k_get_SQcd_SQcc_size(p_j2k, p_j2k->m_current_tile_number,
0);
l_remaining_size = l_qcd_size;
if (l_qcd_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_qcd_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write QCD marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_qcd_size;
}
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_data, J2K_MS_QCD, 2); /* QCD */
l_current_data += 2;
opj_write_bytes(l_current_data, l_qcd_size - 2, 2); /* L_QCD */
l_current_data += 2;
l_remaining_size -= 4;
if (! opj_j2k_write_SQcd_SQcc(p_j2k, p_j2k->m_current_tile_number, 0,
l_current_data, &l_remaining_size, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing QCD marker\n");
return OPJ_FALSE;
}
if (l_remaining_size != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing QCD marker\n");
return OPJ_FALSE;
}
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_qcd_size,
p_manager) != l_qcd_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a QCD marker (Quantization defaults)
* @param p_header_data the data contained in the QCD box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the QCD marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_qcd(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_j2k_read_SQcd_SQcc(p_j2k, 0, p_header_data, &p_header_size,
p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading QCD marker\n");
return OPJ_FALSE;
}
if (p_header_size != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading QCD marker\n");
return OPJ_FALSE;
}
/* Apply the quantization parameters to other components of the current tile or the m_default_tcp */
opj_j2k_copy_tile_quantization_parameters(p_j2k);
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_qcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_qcc_size, l_remaining_size;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_qcc_size = 5 + opj_j2k_get_SQcd_SQcc_size(p_j2k, p_j2k->m_current_tile_number,
p_comp_no);
l_qcc_size += p_j2k->m_private_image->numcomps <= 256 ? 0 : 1;
l_remaining_size = l_qcc_size;
if (l_qcc_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_qcc_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write QCC marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_qcc_size;
}
opj_j2k_write_qcc_in_memory(p_j2k, p_comp_no,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, &l_remaining_size,
p_manager);
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_qcc_size,
p_manager) != l_qcc_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_compare_qcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no)
{
return opj_j2k_compare_SQcd_SQcc(p_j2k, p_j2k->m_current_tile_number,
p_first_comp_no, p_second_comp_no);
}
static void opj_j2k_write_qcc_in_memory(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_qcc_size, l_remaining_size;
OPJ_BYTE * l_current_data = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
l_qcc_size = 6 + opj_j2k_get_SQcd_SQcc_size(p_j2k, p_j2k->m_current_tile_number,
p_comp_no);
l_remaining_size = l_qcc_size;
l_current_data = p_data;
opj_write_bytes(l_current_data, J2K_MS_QCC, 2); /* QCC */
l_current_data += 2;
if (p_j2k->m_private_image->numcomps <= 256) {
--l_qcc_size;
opj_write_bytes(l_current_data, l_qcc_size - 2, 2); /* L_QCC */
l_current_data += 2;
opj_write_bytes(l_current_data, p_comp_no, 1); /* Cqcc */
++l_current_data;
/* in the case only one byte is sufficient the last byte allocated is useless -> still do -6 for available */
l_remaining_size -= 6;
} else {
opj_write_bytes(l_current_data, l_qcc_size - 2, 2); /* L_QCC */
l_current_data += 2;
opj_write_bytes(l_current_data, p_comp_no, 2); /* Cqcc */
l_current_data += 2;
l_remaining_size -= 6;
}
opj_j2k_write_SQcd_SQcc(p_j2k, p_j2k->m_current_tile_number, p_comp_no,
l_current_data, &l_remaining_size, p_manager);
*p_data_written = l_qcc_size;
}
static OPJ_UINT32 opj_j2k_get_max_qcc_size(opj_j2k_t *p_j2k)
{
return opj_j2k_get_max_coc_size(p_j2k);
}
/**
* Reads a QCC marker (Quantization component)
* @param p_header_data the data contained in the QCC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the QCC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_qcc(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_num_comp, l_comp_no;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_num_comp = p_j2k->m_private_image->numcomps;
if (l_num_comp <= 256) {
if (p_header_size < 1) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading QCC marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_comp_no, 1);
++p_header_data;
--p_header_size;
} else {
if (p_header_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading QCC marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_comp_no, 2);
p_header_data += 2;
p_header_size -= 2;
}
#ifdef USE_JPWL
if (p_j2k->m_cp.correct) {
static OPJ_UINT32 backup_compno = 0;
/* compno is negative or larger than the number of components!!! */
if (/*(l_comp_no < 0) ||*/ (l_comp_no >= l_num_comp)) {
opj_event_msg(p_manager, EVT_ERROR,
"JPWL: bad component number in QCC (%d out of a maximum of %d)\n",
l_comp_no, l_num_comp);
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
/* we try to correct */
l_comp_no = backup_compno % l_num_comp;
opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust this\n"
"- setting component number to %d\n",
l_comp_no);
}
/* keep your private count of tiles */
backup_compno++;
};
#endif /* USE_JPWL */
if (l_comp_no >= p_j2k->m_private_image->numcomps) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid component number: %d, regarding the number of components %d\n",
l_comp_no, p_j2k->m_private_image->numcomps);
return OPJ_FALSE;
}
if (! opj_j2k_read_SQcd_SQcc(p_j2k, l_comp_no, p_header_data, &p_header_size,
p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading QCC marker\n");
return OPJ_FALSE;
}
if (p_header_size != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading QCC marker\n");
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_poc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_nb_comp;
OPJ_UINT32 l_nb_poc;
OPJ_UINT32 l_poc_size;
OPJ_UINT32 l_written_size = 0;
opj_tcp_t *l_tcp = 00;
OPJ_UINT32 l_poc_room;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_tcp = &p_j2k->m_cp.tcps[p_j2k->m_current_tile_number];
l_nb_comp = p_j2k->m_private_image->numcomps;
l_nb_poc = 1 + l_tcp->numpocs;
if (l_nb_comp <= 256) {
l_poc_room = 1;
} else {
l_poc_room = 2;
}
l_poc_size = 4 + (5 + 2 * l_poc_room) * l_nb_poc;
if (l_poc_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_poc_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write POC marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_poc_size;
}
opj_j2k_write_poc_in_memory(p_j2k,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, &l_written_size,
p_manager);
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_poc_size,
p_manager) != l_poc_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static void opj_j2k_write_poc_in_memory(opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 i;
OPJ_BYTE * l_current_data = 00;
OPJ_UINT32 l_nb_comp;
OPJ_UINT32 l_nb_poc;
OPJ_UINT32 l_poc_size;
opj_image_t *l_image = 00;
opj_tcp_t *l_tcp = 00;
opj_tccp_t *l_tccp = 00;
opj_poc_t *l_current_poc = 00;
OPJ_UINT32 l_poc_room;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_manager);
l_tcp = &p_j2k->m_cp.tcps[p_j2k->m_current_tile_number];
l_tccp = &l_tcp->tccps[0];
l_image = p_j2k->m_private_image;
l_nb_comp = l_image->numcomps;
l_nb_poc = 1 + l_tcp->numpocs;
if (l_nb_comp <= 256) {
l_poc_room = 1;
} else {
l_poc_room = 2;
}
l_poc_size = 4 + (5 + 2 * l_poc_room) * l_nb_poc;
l_current_data = p_data;
opj_write_bytes(l_current_data, J2K_MS_POC,
2); /* POC */
l_current_data += 2;
opj_write_bytes(l_current_data, l_poc_size - 2,
2); /* Lpoc */
l_current_data += 2;
l_current_poc = l_tcp->pocs;
for (i = 0; i < l_nb_poc; ++i) {
opj_write_bytes(l_current_data, l_current_poc->resno0,
1); /* RSpoc_i */
++l_current_data;
opj_write_bytes(l_current_data, l_current_poc->compno0,
l_poc_room); /* CSpoc_i */
l_current_data += l_poc_room;
opj_write_bytes(l_current_data, l_current_poc->layno1,
2); /* LYEpoc_i */
l_current_data += 2;
opj_write_bytes(l_current_data, l_current_poc->resno1,
1); /* REpoc_i */
++l_current_data;
opj_write_bytes(l_current_data, l_current_poc->compno1,
l_poc_room); /* CEpoc_i */
l_current_data += l_poc_room;
opj_write_bytes(l_current_data, (OPJ_UINT32)l_current_poc->prg,
1); /* Ppoc_i */
++l_current_data;
/* change the value of the max layer according to the actual number of layers in the file, components and resolutions*/
l_current_poc->layno1 = (OPJ_UINT32)opj_int_min((OPJ_INT32)
l_current_poc->layno1, (OPJ_INT32)l_tcp->numlayers);
l_current_poc->resno1 = (OPJ_UINT32)opj_int_min((OPJ_INT32)
l_current_poc->resno1, (OPJ_INT32)l_tccp->numresolutions);
l_current_poc->compno1 = (OPJ_UINT32)opj_int_min((OPJ_INT32)
l_current_poc->compno1, (OPJ_INT32)l_nb_comp);
++l_current_poc;
}
*p_data_written = l_poc_size;
}
static OPJ_UINT32 opj_j2k_get_max_poc_size(opj_j2k_t *p_j2k)
{
opj_tcp_t * l_tcp = 00;
OPJ_UINT32 l_nb_tiles = 0;
OPJ_UINT32 l_max_poc = 0;
OPJ_UINT32 i;
l_tcp = p_j2k->m_cp.tcps;
l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
for (i = 0; i < l_nb_tiles; ++i) {
l_max_poc = opj_uint_max(l_max_poc, l_tcp->numpocs);
++l_tcp;
}
++l_max_poc;
return 4 + 9 * l_max_poc;
}
static OPJ_UINT32 opj_j2k_get_max_toc_size(opj_j2k_t *p_j2k)
{
OPJ_UINT32 i;
OPJ_UINT32 l_nb_tiles;
OPJ_UINT32 l_max = 0;
opj_tcp_t * l_tcp = 00;
l_tcp = p_j2k->m_cp.tcps;
l_nb_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th ;
for (i = 0; i < l_nb_tiles; ++i) {
l_max = opj_uint_max(l_max, l_tcp->m_nb_tile_parts);
++l_tcp;
}
return 12 * l_max;
}
static OPJ_UINT32 opj_j2k_get_specific_header_sizes(opj_j2k_t *p_j2k)
{
OPJ_UINT32 l_nb_bytes = 0;
OPJ_UINT32 l_nb_comps;
OPJ_UINT32 l_coc_bytes, l_qcc_bytes;
l_nb_comps = p_j2k->m_private_image->numcomps - 1;
l_nb_bytes += opj_j2k_get_max_toc_size(p_j2k);
if (!(OPJ_IS_CINEMA(p_j2k->m_cp.rsiz))) {
l_coc_bytes = opj_j2k_get_max_coc_size(p_j2k);
l_nb_bytes += l_nb_comps * l_coc_bytes;
l_qcc_bytes = opj_j2k_get_max_qcc_size(p_j2k);
l_nb_bytes += l_nb_comps * l_qcc_bytes;
}
l_nb_bytes += opj_j2k_get_max_poc_size(p_j2k);
/*** DEVELOPER CORNER, Add room for your headers ***/
return l_nb_bytes;
}
/**
* Reads a POC marker (Progression Order Change)
*
* @param p_header_data the data contained in the POC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the POC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_poc(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 i, l_nb_comp, l_tmp;
opj_image_t * l_image = 00;
OPJ_UINT32 l_old_poc_nb, l_current_poc_nb, l_current_poc_remaining;
OPJ_UINT32 l_chunk_size, l_comp_room;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_poc_t *l_current_poc = 00;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_image = p_j2k->m_private_image;
l_nb_comp = l_image->numcomps;
if (l_nb_comp <= 256) {
l_comp_room = 1;
} else {
l_comp_room = 2;
}
l_chunk_size = 5 + 2 * l_comp_room;
l_current_poc_nb = p_header_size / l_chunk_size;
l_current_poc_remaining = p_header_size % l_chunk_size;
if ((l_current_poc_nb <= 0) || (l_current_poc_remaining != 0)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading POC marker\n");
return OPJ_FALSE;
}
l_cp = &(p_j2k->m_cp);
l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
l_old_poc_nb = l_tcp->POC ? l_tcp->numpocs + 1 : 0;
l_current_poc_nb += l_old_poc_nb;
if (l_current_poc_nb >= 32) {
opj_event_msg(p_manager, EVT_ERROR, "Too many POCs %d\n", l_current_poc_nb);
return OPJ_FALSE;
}
assert(l_current_poc_nb < 32);
/* now poc is in use.*/
l_tcp->POC = 1;
l_current_poc = &l_tcp->pocs[l_old_poc_nb];
for (i = l_old_poc_nb; i < l_current_poc_nb; ++i) {
opj_read_bytes(p_header_data, &(l_current_poc->resno0),
1); /* RSpoc_i */
++p_header_data;
opj_read_bytes(p_header_data, &(l_current_poc->compno0),
l_comp_room); /* CSpoc_i */
p_header_data += l_comp_room;
opj_read_bytes(p_header_data, &(l_current_poc->layno1),
2); /* LYEpoc_i */
/* make sure layer end is in acceptable bounds */
l_current_poc->layno1 = opj_uint_min(l_current_poc->layno1, l_tcp->numlayers);
p_header_data += 2;
opj_read_bytes(p_header_data, &(l_current_poc->resno1),
1); /* REpoc_i */
++p_header_data;
opj_read_bytes(p_header_data, &(l_current_poc->compno1),
l_comp_room); /* CEpoc_i */
p_header_data += l_comp_room;
opj_read_bytes(p_header_data, &l_tmp,
1); /* Ppoc_i */
++p_header_data;
l_current_poc->prg = (OPJ_PROG_ORDER) l_tmp;
/* make sure comp is in acceptable bounds */
l_current_poc->compno1 = opj_uint_min(l_current_poc->compno1, l_nb_comp);
++l_current_poc;
}
l_tcp->numpocs = l_current_poc_nb - 1;
return OPJ_TRUE;
}
/**
* Reads a CRG marker (Component registration)
*
* @param p_header_data the data contained in the TLM box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the TLM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_crg(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_nb_comp;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_header_data);
l_nb_comp = p_j2k->m_private_image->numcomps;
if (p_header_size != l_nb_comp * 4) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading CRG marker\n");
return OPJ_FALSE;
}
/* Do not care of this at the moment since only local variables are set here */
/*
for
(i = 0; i < l_nb_comp; ++i)
{
opj_read_bytes(p_header_data,&l_Xcrg_i,2); // Xcrg_i
p_header_data+=2;
opj_read_bytes(p_header_data,&l_Ycrg_i,2); // Xcrg_i
p_header_data+=2;
}
*/
return OPJ_TRUE;
}
/**
* Reads a TLM marker (Tile Length Marker)
*
* @param p_header_data the data contained in the TLM box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the TLM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_tlm(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_Ztlm, l_Stlm, l_ST, l_SP, l_tot_num_tp_remaining, l_quotient,
l_Ptlm_size;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_j2k);
if (p_header_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading TLM marker\n");
return OPJ_FALSE;
}
p_header_size -= 2;
opj_read_bytes(p_header_data, &l_Ztlm,
1); /* Ztlm */
++p_header_data;
opj_read_bytes(p_header_data, &l_Stlm,
1); /* Stlm */
++p_header_data;
l_ST = ((l_Stlm >> 4) & 0x3);
l_SP = (l_Stlm >> 6) & 0x1;
l_Ptlm_size = (l_SP + 1) * 2;
l_quotient = l_Ptlm_size + l_ST;
l_tot_num_tp_remaining = p_header_size % l_quotient;
if (l_tot_num_tp_remaining != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading TLM marker\n");
return OPJ_FALSE;
}
/* FIXME Do not care of this at the moment since only local variables are set here */
/*
for
(i = 0; i < l_tot_num_tp; ++i)
{
opj_read_bytes(p_header_data,&l_Ttlm_i,l_ST); // Ttlm_i
p_header_data += l_ST;
opj_read_bytes(p_header_data,&l_Ptlm_i,l_Ptlm_size); // Ptlm_i
p_header_data += l_Ptlm_size;
}*/
return OPJ_TRUE;
}
/**
* Reads a PLM marker (Packet length, main header marker)
*
* @param p_header_data the data contained in the TLM box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the TLM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_plm(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_j2k);
OPJ_UNUSED(p_header_data);
if (p_header_size < 1) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading PLM marker\n");
return OPJ_FALSE;
}
/* Do not care of this at the moment since only local variables are set here */
/*
opj_read_bytes(p_header_data,&l_Zplm,1); // Zplm
++p_header_data;
--p_header_size;
while
(p_header_size > 0)
{
opj_read_bytes(p_header_data,&l_Nplm,1); // Nplm
++p_header_data;
p_header_size -= (1+l_Nplm);
if
(p_header_size < 0)
{
opj_event_msg(p_manager, EVT_ERROR, "Error reading PLM marker\n");
return false;
}
for
(i = 0; i < l_Nplm; ++i)
{
opj_read_bytes(p_header_data,&l_tmp,1); // Iplm_ij
++p_header_data;
// take only the last seven bytes
l_packet_len |= (l_tmp & 0x7f);
if
(l_tmp & 0x80)
{
l_packet_len <<= 7;
}
else
{
// store packet length and proceed to next packet
l_packet_len = 0;
}
}
if
(l_packet_len != 0)
{
opj_event_msg(p_manager, EVT_ERROR, "Error reading PLM marker\n");
return false;
}
}
*/
return OPJ_TRUE;
}
/**
* Reads a PLT marker (Packet length, tile-part header)
*
* @param p_header_data the data contained in the PLT box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the PLT marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_plt(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_Zplt, l_tmp, l_packet_len = 0, i;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_j2k);
if (p_header_size < 1) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading PLT marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_Zplt, 1); /* Zplt */
++p_header_data;
--p_header_size;
for (i = 0; i < p_header_size; ++i) {
opj_read_bytes(p_header_data, &l_tmp, 1); /* Iplt_ij */
++p_header_data;
/* take only the last seven bytes */
l_packet_len |= (l_tmp & 0x7f);
if (l_tmp & 0x80) {
l_packet_len <<= 7;
} else {
/* store packet length and proceed to next packet */
l_packet_len = 0;
}
}
if (l_packet_len != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading PLT marker\n");
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a PPM marker (Packed packet headers, main header)
*
* @param p_header_data the data contained in the POC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the POC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_ppm(
opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager)
{
opj_cp_t *l_cp = 00;
OPJ_UINT32 l_Z_ppm;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
/* We need to have the Z_ppm element + 1 byte of Nppm/Ippm at minimum */
if (p_header_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading PPM marker\n");
return OPJ_FALSE;
}
l_cp = &(p_j2k->m_cp);
l_cp->ppm = 1;
opj_read_bytes(p_header_data, &l_Z_ppm, 1); /* Z_ppm */
++p_header_data;
--p_header_size;
/* check allocation needed */
if (l_cp->ppm_markers == NULL) { /* first PPM marker */
OPJ_UINT32 l_newCount = l_Z_ppm + 1U; /* can't overflow, l_Z_ppm is UINT8 */
assert(l_cp->ppm_markers_count == 0U);
l_cp->ppm_markers = (opj_ppx *) opj_calloc(l_newCount, sizeof(opj_ppx));
if (l_cp->ppm_markers == NULL) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPM marker\n");
return OPJ_FALSE;
}
l_cp->ppm_markers_count = l_newCount;
} else if (l_cp->ppm_markers_count <= l_Z_ppm) {
OPJ_UINT32 l_newCount = l_Z_ppm + 1U; /* can't overflow, l_Z_ppm is UINT8 */
opj_ppx *new_ppm_markers;
new_ppm_markers = (opj_ppx *) opj_realloc(l_cp->ppm_markers,
l_newCount * sizeof(opj_ppx));
if (new_ppm_markers == NULL) {
/* clean up to be done on l_cp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPM marker\n");
return OPJ_FALSE;
}
l_cp->ppm_markers = new_ppm_markers;
memset(l_cp->ppm_markers + l_cp->ppm_markers_count, 0,
(l_newCount - l_cp->ppm_markers_count) * sizeof(opj_ppx));
l_cp->ppm_markers_count = l_newCount;
}
if (l_cp->ppm_markers[l_Z_ppm].m_data != NULL) {
/* clean up to be done on l_cp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Zppm %u already read\n", l_Z_ppm);
return OPJ_FALSE;
}
l_cp->ppm_markers[l_Z_ppm].m_data = (OPJ_BYTE *) opj_malloc(p_header_size);
if (l_cp->ppm_markers[l_Z_ppm].m_data == NULL) {
/* clean up to be done on l_cp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPM marker\n");
return OPJ_FALSE;
}
l_cp->ppm_markers[l_Z_ppm].m_data_size = p_header_size;
memcpy(l_cp->ppm_markers[l_Z_ppm].m_data, p_header_data, p_header_size);
return OPJ_TRUE;
}
/**
* Merges all PPM markers read (Packed headers, main header)
*
* @param p_cp main coding parameters.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_merge_ppm(opj_cp_t *p_cp, opj_event_mgr_t * p_manager)
{
OPJ_UINT32 i, l_ppm_data_size, l_N_ppm_remaining;
/* preconditions */
assert(p_cp != 00);
assert(p_manager != 00);
assert(p_cp->ppm_buffer == NULL);
if (p_cp->ppm == 0U) {
return OPJ_TRUE;
}
l_ppm_data_size = 0U;
l_N_ppm_remaining = 0U;
for (i = 0U; i < p_cp->ppm_markers_count; ++i) {
if (p_cp->ppm_markers[i].m_data !=
NULL) { /* standard doesn't seem to require contiguous Zppm */
OPJ_UINT32 l_N_ppm;
OPJ_UINT32 l_data_size = p_cp->ppm_markers[i].m_data_size;
const OPJ_BYTE* l_data = p_cp->ppm_markers[i].m_data;
if (l_N_ppm_remaining >= l_data_size) {
l_N_ppm_remaining -= l_data_size;
l_data_size = 0U;
} else {
l_data += l_N_ppm_remaining;
l_data_size -= l_N_ppm_remaining;
l_N_ppm_remaining = 0U;
}
if (l_data_size > 0U) {
do {
/* read Nppm */
if (l_data_size < 4U) {
/* clean up to be done on l_cp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Not enough bytes to read Nppm\n");
return OPJ_FALSE;
}
opj_read_bytes(l_data, &l_N_ppm, 4);
l_data += 4;
l_data_size -= 4;
l_ppm_data_size +=
l_N_ppm; /* can't overflow, max 256 markers of max 65536 bytes, that is when PPM markers are not corrupted which is checked elsewhere */
if (l_data_size >= l_N_ppm) {
l_data_size -= l_N_ppm;
l_data += l_N_ppm;
} else {
l_N_ppm_remaining = l_N_ppm - l_data_size;
l_data_size = 0U;
}
} while (l_data_size > 0U);
}
}
}
if (l_N_ppm_remaining != 0U) {
/* clean up to be done on l_cp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Corrupted PPM markers\n");
return OPJ_FALSE;
}
p_cp->ppm_buffer = (OPJ_BYTE *) opj_malloc(l_ppm_data_size);
if (p_cp->ppm_buffer == 00) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPM marker\n");
return OPJ_FALSE;
}
p_cp->ppm_len = l_ppm_data_size;
l_ppm_data_size = 0U;
l_N_ppm_remaining = 0U;
for (i = 0U; i < p_cp->ppm_markers_count; ++i) {
if (p_cp->ppm_markers[i].m_data !=
NULL) { /* standard doesn't seem to require contiguous Zppm */
OPJ_UINT32 l_N_ppm;
OPJ_UINT32 l_data_size = p_cp->ppm_markers[i].m_data_size;
const OPJ_BYTE* l_data = p_cp->ppm_markers[i].m_data;
if (l_N_ppm_remaining >= l_data_size) {
memcpy(p_cp->ppm_buffer + l_ppm_data_size, l_data, l_data_size);
l_ppm_data_size += l_data_size;
l_N_ppm_remaining -= l_data_size;
l_data_size = 0U;
} else {
memcpy(p_cp->ppm_buffer + l_ppm_data_size, l_data, l_N_ppm_remaining);
l_ppm_data_size += l_N_ppm_remaining;
l_data += l_N_ppm_remaining;
l_data_size -= l_N_ppm_remaining;
l_N_ppm_remaining = 0U;
}
if (l_data_size > 0U) {
do {
/* read Nppm */
if (l_data_size < 4U) {
/* clean up to be done on l_cp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Not enough bytes to read Nppm\n");
return OPJ_FALSE;
}
opj_read_bytes(l_data, &l_N_ppm, 4);
l_data += 4;
l_data_size -= 4;
if (l_data_size >= l_N_ppm) {
memcpy(p_cp->ppm_buffer + l_ppm_data_size, l_data, l_N_ppm);
l_ppm_data_size += l_N_ppm;
l_data_size -= l_N_ppm;
l_data += l_N_ppm;
} else {
memcpy(p_cp->ppm_buffer + l_ppm_data_size, l_data, l_data_size);
l_ppm_data_size += l_data_size;
l_N_ppm_remaining = l_N_ppm - l_data_size;
l_data_size = 0U;
}
} while (l_data_size > 0U);
}
opj_free(p_cp->ppm_markers[i].m_data);
p_cp->ppm_markers[i].m_data = NULL;
p_cp->ppm_markers[i].m_data_size = 0U;
}
}
p_cp->ppm_data = p_cp->ppm_buffer;
p_cp->ppm_data_size = p_cp->ppm_len;
p_cp->ppm_markers_count = 0U;
opj_free(p_cp->ppm_markers);
p_cp->ppm_markers = NULL;
return OPJ_TRUE;
}
/**
* Reads a PPT marker (Packed packet headers, tile-part header)
*
* @param p_header_data the data contained in the PPT box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the PPT marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_ppt(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
OPJ_UINT32 l_Z_ppt;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
/* We need to have the Z_ppt element + 1 byte of Ippt at minimum */
if (p_header_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading PPT marker\n");
return OPJ_FALSE;
}
l_cp = &(p_j2k->m_cp);
if (l_cp->ppm) {
opj_event_msg(p_manager, EVT_ERROR,
"Error reading PPT marker: packet header have been previously found in the main header (PPM marker).\n");
return OPJ_FALSE;
}
l_tcp = &(l_cp->tcps[p_j2k->m_current_tile_number]);
l_tcp->ppt = 1;
opj_read_bytes(p_header_data, &l_Z_ppt, 1); /* Z_ppt */
++p_header_data;
--p_header_size;
/* check allocation needed */
if (l_tcp->ppt_markers == NULL) { /* first PPT marker */
OPJ_UINT32 l_newCount = l_Z_ppt + 1U; /* can't overflow, l_Z_ppt is UINT8 */
assert(l_tcp->ppt_markers_count == 0U);
l_tcp->ppt_markers = (opj_ppx *) opj_calloc(l_newCount, sizeof(opj_ppx));
if (l_tcp->ppt_markers == NULL) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPT marker\n");
return OPJ_FALSE;
}
l_tcp->ppt_markers_count = l_newCount;
} else if (l_tcp->ppt_markers_count <= l_Z_ppt) {
OPJ_UINT32 l_newCount = l_Z_ppt + 1U; /* can't overflow, l_Z_ppt is UINT8 */
opj_ppx *new_ppt_markers;
new_ppt_markers = (opj_ppx *) opj_realloc(l_tcp->ppt_markers,
l_newCount * sizeof(opj_ppx));
if (new_ppt_markers == NULL) {
/* clean up to be done on l_tcp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPT marker\n");
return OPJ_FALSE;
}
l_tcp->ppt_markers = new_ppt_markers;
memset(l_tcp->ppt_markers + l_tcp->ppt_markers_count, 0,
(l_newCount - l_tcp->ppt_markers_count) * sizeof(opj_ppx));
l_tcp->ppt_markers_count = l_newCount;
}
if (l_tcp->ppt_markers[l_Z_ppt].m_data != NULL) {
/* clean up to be done on l_tcp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Zppt %u already read\n", l_Z_ppt);
return OPJ_FALSE;
}
l_tcp->ppt_markers[l_Z_ppt].m_data = (OPJ_BYTE *) opj_malloc(p_header_size);
if (l_tcp->ppt_markers[l_Z_ppt].m_data == NULL) {
/* clean up to be done on l_tcp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPT marker\n");
return OPJ_FALSE;
}
l_tcp->ppt_markers[l_Z_ppt].m_data_size = p_header_size;
memcpy(l_tcp->ppt_markers[l_Z_ppt].m_data, p_header_data, p_header_size);
return OPJ_TRUE;
}
/**
* Merges all PPT markers read (Packed packet headers, tile-part header)
*
* @param p_tcp the tile.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_merge_ppt(opj_tcp_t *p_tcp, opj_event_mgr_t * p_manager)
{
OPJ_UINT32 i, l_ppt_data_size;
/* preconditions */
assert(p_tcp != 00);
assert(p_manager != 00);
assert(p_tcp->ppt_buffer == NULL);
if (p_tcp->ppt == 0U) {
return OPJ_TRUE;
}
l_ppt_data_size = 0U;
for (i = 0U; i < p_tcp->ppt_markers_count; ++i) {
l_ppt_data_size +=
p_tcp->ppt_markers[i].m_data_size; /* can't overflow, max 256 markers of max 65536 bytes */
}
p_tcp->ppt_buffer = (OPJ_BYTE *) opj_malloc(l_ppt_data_size);
if (p_tcp->ppt_buffer == 00) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPT marker\n");
return OPJ_FALSE;
}
p_tcp->ppt_len = l_ppt_data_size;
l_ppt_data_size = 0U;
for (i = 0U; i < p_tcp->ppt_markers_count; ++i) {
if (p_tcp->ppt_markers[i].m_data !=
NULL) { /* standard doesn't seem to require contiguous Zppt */
memcpy(p_tcp->ppt_buffer + l_ppt_data_size, p_tcp->ppt_markers[i].m_data,
p_tcp->ppt_markers[i].m_data_size);
l_ppt_data_size +=
p_tcp->ppt_markers[i].m_data_size; /* can't overflow, max 256 markers of max 65536 bytes */
opj_free(p_tcp->ppt_markers[i].m_data);
p_tcp->ppt_markers[i].m_data = NULL;
p_tcp->ppt_markers[i].m_data_size = 0U;
}
}
p_tcp->ppt_markers_count = 0U;
opj_free(p_tcp->ppt_markers);
p_tcp->ppt_markers = NULL;
p_tcp->ppt_data = p_tcp->ppt_buffer;
p_tcp->ppt_data_size = p_tcp->ppt_len;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_tlm(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_BYTE * l_current_data = 00;
OPJ_UINT32 l_tlm_size;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_tlm_size = 6 + (5 * p_j2k->m_specific_param.m_encoder.m_total_tile_parts);
if (l_tlm_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_tlm_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write TLM marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_tlm_size;
}
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
/* change the way data is written to avoid seeking if possible */
/* TODO */
p_j2k->m_specific_param.m_encoder.m_tlm_start = opj_stream_tell(p_stream);
opj_write_bytes(l_current_data, J2K_MS_TLM,
2); /* TLM */
l_current_data += 2;
opj_write_bytes(l_current_data, l_tlm_size - 2,
2); /* Lpoc */
l_current_data += 2;
opj_write_bytes(l_current_data, 0,
1); /* Ztlm=0*/
++l_current_data;
opj_write_bytes(l_current_data, 0x50,
1); /* Stlm ST=1(8bits-255 tiles max),SP=1(Ptlm=32bits) */
++l_current_data;
/* do nothing on the 5 * l_j2k->m_specific_param.m_encoder.m_total_tile_parts remaining data */
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_tlm_size,
p_manager) != l_tlm_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_sot(opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
const opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
OPJ_UNUSED(p_stream);
OPJ_UNUSED(p_manager);
opj_write_bytes(p_data, J2K_MS_SOT,
2); /* SOT */
p_data += 2;
opj_write_bytes(p_data, 10,
2); /* Lsot */
p_data += 2;
opj_write_bytes(p_data, p_j2k->m_current_tile_number,
2); /* Isot */
p_data += 2;
/* Psot */
p_data += 4;
opj_write_bytes(p_data,
p_j2k->m_specific_param.m_encoder.m_current_tile_part_number,
1); /* TPsot */
++p_data;
opj_write_bytes(p_data,
p_j2k->m_cp.tcps[p_j2k->m_current_tile_number].m_nb_tile_parts,
1); /* TNsot */
++p_data;
/* UniPG>> */
#ifdef USE_JPWL
/* update markers struct */
/*
OPJ_BOOL res = j2k_add_marker(p_j2k->cstr_info, J2K_MS_SOT, p_j2k->sot_start, len + 2);
*/
assert(0 && "TODO");
#endif /* USE_JPWL */
* p_data_written = 12;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_get_sot_values(OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
OPJ_UINT32* p_tile_no,
OPJ_UINT32* p_tot_len,
OPJ_UINT32* p_current_part,
OPJ_UINT32* p_num_parts,
opj_event_mgr_t * p_manager)
{
/* preconditions */
assert(p_header_data != 00);
assert(p_manager != 00);
/* Size of this marker is fixed = 12 (we have already read marker and its size)*/
if (p_header_size != 8) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading SOT marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, p_tile_no, 2); /* Isot */
p_header_data += 2;
opj_read_bytes(p_header_data, p_tot_len, 4); /* Psot */
p_header_data += 4;
opj_read_bytes(p_header_data, p_current_part, 1); /* TPsot */
++p_header_data;
opj_read_bytes(p_header_data, p_num_parts, 1); /* TNsot */
++p_header_data;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_read_sot(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager)
{
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
OPJ_UINT32 l_tot_len, l_num_parts = 0;
OPJ_UINT32 l_current_part;
OPJ_UINT32 l_tile_x, l_tile_y;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_j2k_get_sot_values(p_header_data, p_header_size,
&(p_j2k->m_current_tile_number), &l_tot_len, &l_current_part, &l_num_parts,
p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading SOT marker\n");
return OPJ_FALSE;
}
l_cp = &(p_j2k->m_cp);
/* testcase 2.pdf.SIGFPE.706.1112 */
if (p_j2k->m_current_tile_number >= l_cp->tw * l_cp->th) {
opj_event_msg(p_manager, EVT_ERROR, "Invalid tile number %d\n",
p_j2k->m_current_tile_number);
return OPJ_FALSE;
}
l_tcp = &l_cp->tcps[p_j2k->m_current_tile_number];
l_tile_x = p_j2k->m_current_tile_number % l_cp->tw;
l_tile_y = p_j2k->m_current_tile_number / l_cp->tw;
/* Fixes issue with id_000020,sig_06,src_001958,op_flip4,pos_149 */
/* of https://github.com/uclouvain/openjpeg/issues/939 */
/* We must avoid reading twice the same tile part number for a given tile */
/* so as to avoid various issues, like opj_j2k_merge_ppt being called */
/* several times. */
/* ISO 15444-1 A.4.2 Start of tile-part (SOT) mandates that tile parts */
/* should appear in increasing order. */
if (l_tcp->m_current_tile_part_number + 1 != (OPJ_INT32)l_current_part) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid tile part index for tile number %d. "
"Got %d, expected %d\n",
p_j2k->m_current_tile_number,
l_current_part,
l_tcp->m_current_tile_part_number + 1);
return OPJ_FALSE;
}
++ l_tcp->m_current_tile_part_number;
#ifdef USE_JPWL
if (l_cp->correct) {
OPJ_UINT32 tileno = p_j2k->m_current_tile_number;
static OPJ_UINT32 backup_tileno = 0;
/* tileno is negative or larger than the number of tiles!!! */
if (tileno > (l_cp->tw * l_cp->th)) {
opj_event_msg(p_manager, EVT_ERROR,
"JPWL: bad tile number (%d out of a maximum of %d)\n",
tileno, (l_cp->tw * l_cp->th));
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
/* we try to correct */
tileno = backup_tileno;
opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust this\n"
"- setting tile number to %d\n",
tileno);
}
/* keep your private count of tiles */
backup_tileno++;
};
#endif /* USE_JPWL */
/* look for the tile in the list of already processed tile (in parts). */
/* Optimization possible here with a more complex data structure and with the removing of tiles */
/* since the time taken by this function can only grow at the time */
/* PSot should be equal to zero or >=14 or <= 2^32-1 */
if ((l_tot_len != 0) && (l_tot_len < 14)) {
if (l_tot_len ==
12) { /* MSD: Special case for the PHR data which are read by kakadu*/
opj_event_msg(p_manager, EVT_WARNING, "Empty SOT marker detected: Psot=%d.\n",
l_tot_len);
} else {
opj_event_msg(p_manager, EVT_ERROR,
"Psot value is not correct regards to the JPEG2000 norm: %d.\n", l_tot_len);
return OPJ_FALSE;
}
}
#ifdef USE_JPWL
if (l_cp->correct) {
/* totlen is negative or larger than the bytes left!!! */
if (/*(l_tot_len < 0) ||*/ (l_tot_len >
p_header_size)) { /* FIXME it seems correct; for info in V1 -> (p_stream_numbytesleft(p_stream) + 8))) { */
opj_event_msg(p_manager, EVT_ERROR,
"JPWL: bad tile byte size (%d bytes against %d bytes left)\n",
l_tot_len,
p_header_size); /* FIXME it seems correct; for info in V1 -> p_stream_numbytesleft(p_stream) + 8); */
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
/* we try to correct */
l_tot_len = 0;
opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust this\n"
"- setting Psot to %d => assuming it is the last tile\n",
l_tot_len);
}
};
#endif /* USE_JPWL */
/* Ref A.4.2: Psot could be equal zero if it is the last tile-part of the codestream.*/
if (!l_tot_len) {
opj_event_msg(p_manager, EVT_INFO,
"Psot value of the current tile-part is equal to zero, "
"we assuming it is the last tile-part of the codestream.\n");
p_j2k->m_specific_param.m_decoder.m_last_tile_part = 1;
}
if (l_tcp->m_nb_tile_parts != 0 && l_current_part >= l_tcp->m_nb_tile_parts) {
/* Fixes https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=2851 */
opj_event_msg(p_manager, EVT_ERROR,
"In SOT marker, TPSot (%d) is not valid regards to the previous "
"number of tile-part (%d), giving up\n", l_current_part,
l_tcp->m_nb_tile_parts);
p_j2k->m_specific_param.m_decoder.m_last_tile_part = 1;
return OPJ_FALSE;
}
if (l_num_parts !=
0) { /* Number of tile-part header is provided by this tile-part header */
l_num_parts += p_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction;
/* Useful to manage the case of textGBR.jp2 file because two values of TNSot are allowed: the correct numbers of
* tile-parts for that tile and zero (A.4.2 of 15444-1 : 2002). */
if (l_tcp->m_nb_tile_parts) {
if (l_current_part >= l_tcp->m_nb_tile_parts) {
opj_event_msg(p_manager, EVT_ERROR,
"In SOT marker, TPSot (%d) is not valid regards to the current "
"number of tile-part (%d), giving up\n", l_current_part,
l_tcp->m_nb_tile_parts);
p_j2k->m_specific_param.m_decoder.m_last_tile_part = 1;
return OPJ_FALSE;
}
}
if (l_current_part >= l_num_parts) {
/* testcase 451.pdf.SIGSEGV.ce9.3723 */
opj_event_msg(p_manager, EVT_ERROR,
"In SOT marker, TPSot (%d) is not valid regards to the current "
"number of tile-part (header) (%d), giving up\n", l_current_part, l_num_parts);
p_j2k->m_specific_param.m_decoder.m_last_tile_part = 1;
return OPJ_FALSE;
}
l_tcp->m_nb_tile_parts = l_num_parts;
}
/* If know the number of tile part header we will check if we didn't read the last*/
if (l_tcp->m_nb_tile_parts) {
if (l_tcp->m_nb_tile_parts == (l_current_part + 1)) {
p_j2k->m_specific_param.m_decoder.m_can_decode =
1; /* Process the last tile-part header*/
}
}
if (!p_j2k->m_specific_param.m_decoder.m_last_tile_part) {
/* Keep the size of data to skip after this marker */
p_j2k->m_specific_param.m_decoder.m_sot_length = l_tot_len -
12; /* SOT_marker_size = 12 */
} else {
/* FIXME: need to be computed from the number of bytes remaining in the codestream */
p_j2k->m_specific_param.m_decoder.m_sot_length = 0;
}
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPH;
/* Check if the current tile is outside the area we want decode or not corresponding to the tile index*/
if (p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec == -1) {
p_j2k->m_specific_param.m_decoder.m_skip_data =
(l_tile_x < p_j2k->m_specific_param.m_decoder.m_start_tile_x)
|| (l_tile_x >= p_j2k->m_specific_param.m_decoder.m_end_tile_x)
|| (l_tile_y < p_j2k->m_specific_param.m_decoder.m_start_tile_y)
|| (l_tile_y >= p_j2k->m_specific_param.m_decoder.m_end_tile_y);
} else {
assert(p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec >= 0);
p_j2k->m_specific_param.m_decoder.m_skip_data =
(p_j2k->m_current_tile_number != (OPJ_UINT32)
p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec);
}
/* Index */
if (p_j2k->cstr_index) {
assert(p_j2k->cstr_index->tile_index != 00);
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tileno =
p_j2k->m_current_tile_number;
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_tpsno =
l_current_part;
if (l_num_parts != 0) {
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].nb_tps =
l_num_parts;
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps =
l_num_parts;
if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index) {
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index =
(opj_tp_index_t*)opj_calloc(l_num_parts, sizeof(opj_tp_index_t));
if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to read SOT marker. Tile index allocation failed\n");
return OPJ_FALSE;
}
} else {
opj_tp_index_t *new_tp_index = (opj_tp_index_t *) opj_realloc(
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index,
l_num_parts * sizeof(opj_tp_index_t));
if (! new_tp_index) {
opj_free(p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index);
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index = NULL;
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to read SOT marker. Tile index allocation failed\n");
return OPJ_FALSE;
}
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index =
new_tp_index;
}
} else {
/*if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index)*/ {
if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index) {
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps = 10;
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index =
(opj_tp_index_t*)opj_calloc(
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps,
sizeof(opj_tp_index_t));
if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index) {
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps = 0;
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to read SOT marker. Tile index allocation failed\n");
return OPJ_FALSE;
}
}
if (l_current_part >=
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps) {
opj_tp_index_t *new_tp_index;
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps =
l_current_part + 1;
new_tp_index = (opj_tp_index_t *) opj_realloc(
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index,
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps *
sizeof(opj_tp_index_t));
if (! new_tp_index) {
opj_free(p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index);
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index = NULL;
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps = 0;
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to read SOT marker. Tile index allocation failed\n");
return OPJ_FALSE;
}
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index =
new_tp_index;
}
}
}
}
/* FIXME move this onto a separate method to call before reading any SOT, remove part about main_end header, use a index struct inside p_j2k */
/* if (p_j2k->cstr_info) {
if (l_tcp->first) {
if (tileno == 0) {
p_j2k->cstr_info->main_head_end = p_stream_tell(p_stream) - 13;
}
p_j2k->cstr_info->tile[tileno].tileno = tileno;
p_j2k->cstr_info->tile[tileno].start_pos = p_stream_tell(p_stream) - 12;
p_j2k->cstr_info->tile[tileno].end_pos = p_j2k->cstr_info->tile[tileno].start_pos + totlen - 1;
p_j2k->cstr_info->tile[tileno].num_tps = numparts;
if (numparts) {
p_j2k->cstr_info->tile[tileno].tp = (opj_tp_info_t *) opj_malloc(numparts * sizeof(opj_tp_info_t));
}
else {
p_j2k->cstr_info->tile[tileno].tp = (opj_tp_info_t *) opj_malloc(10 * sizeof(opj_tp_info_t)); // Fixme (10)
}
}
else {
p_j2k->cstr_info->tile[tileno].end_pos += totlen;
}
p_j2k->cstr_info->tile[tileno].tp[partno].tp_start_pos = p_stream_tell(p_stream) - 12;
p_j2k->cstr_info->tile[tileno].tp[partno].tp_end_pos =
p_j2k->cstr_info->tile[tileno].tp[partno].tp_start_pos + totlen - 1;
}*/
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_sod(opj_j2k_t *p_j2k,
opj_tcd_t * p_tile_coder,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_total_data_size,
const opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
opj_codestream_info_t *l_cstr_info = 00;
OPJ_UINT32 l_remaining_data;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
OPJ_UNUSED(p_stream);
opj_write_bytes(p_data, J2K_MS_SOD,
2); /* SOD */
p_data += 2;
/* make room for the EOF marker */
l_remaining_data = p_total_data_size - 4;
/* update tile coder */
p_tile_coder->tp_num =
p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number ;
p_tile_coder->cur_tp_num =
p_j2k->m_specific_param.m_encoder.m_current_tile_part_number;
/* INDEX >> */
/* TODO mergeV2: check this part which use cstr_info */
/*l_cstr_info = p_j2k->cstr_info;
if (l_cstr_info) {
if (!p_j2k->m_specific_param.m_encoder.m_current_tile_part_number ) {
//TODO cstr_info->tile[p_j2k->m_current_tile_number].end_header = p_stream_tell(p_stream) + p_j2k->pos_correction - 1;
l_cstr_info->tile[p_j2k->m_current_tile_number].tileno = p_j2k->m_current_tile_number;
}
else {*/
/*
TODO
if
(cstr_info->tile[p_j2k->m_current_tile_number].packet[cstr_info->packno - 1].end_pos < p_stream_tell(p_stream))
{
cstr_info->tile[p_j2k->m_current_tile_number].packet[cstr_info->packno].start_pos = p_stream_tell(p_stream);
}*/
/*}*/
/* UniPG>> */
#ifdef USE_JPWL
/* update markers struct */
/*OPJ_BOOL res = j2k_add_marker(p_j2k->cstr_info, J2K_MS_SOD, p_j2k->sod_start, 2);
*/
assert(0 && "TODO");
#endif /* USE_JPWL */
/* <<UniPG */
/*}*/
/* << INDEX */
if (p_j2k->m_specific_param.m_encoder.m_current_tile_part_number == 0) {
p_tile_coder->tcd_image->tiles->packno = 0;
if (l_cstr_info) {
l_cstr_info->packno = 0;
}
}
*p_data_written = 0;
if (! opj_tcd_encode_tile(p_tile_coder, p_j2k->m_current_tile_number, p_data,
p_data_written, l_remaining_data, l_cstr_info,
p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Cannot encode tile\n");
return OPJ_FALSE;
}
*p_data_written += 2;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_read_sod(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_SIZE_T l_current_read_size;
opj_codestream_index_t * l_cstr_index = 00;
OPJ_BYTE ** l_current_data = 00;
opj_tcp_t * l_tcp = 00;
OPJ_UINT32 * l_tile_len = 00;
OPJ_BOOL l_sot_length_pb_detected = OPJ_FALSE;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_tcp = &(p_j2k->m_cp.tcps[p_j2k->m_current_tile_number]);
if (p_j2k->m_specific_param.m_decoder.m_last_tile_part) {
/* opj_stream_get_number_byte_left returns OPJ_OFF_T
// but we are in the last tile part,
// so its result will fit on OPJ_UINT32 unless we find
// a file with a single tile part of more than 4 GB...*/
p_j2k->m_specific_param.m_decoder.m_sot_length = (OPJ_UINT32)(
opj_stream_get_number_byte_left(p_stream) - 2);
} else {
/* Check to avoid pass the limit of OPJ_UINT32 */
if (p_j2k->m_specific_param.m_decoder.m_sot_length >= 2) {
p_j2k->m_specific_param.m_decoder.m_sot_length -= 2;
} else {
/* MSD: case commented to support empty SOT marker (PHR data) */
}
}
l_current_data = &(l_tcp->m_data);
l_tile_len = &l_tcp->m_data_size;
/* Patch to support new PHR data */
if (p_j2k->m_specific_param.m_decoder.m_sot_length) {
/* If we are here, we'll try to read the data after allocation */
/* Check enough bytes left in stream before allocation */
if ((OPJ_OFF_T)p_j2k->m_specific_param.m_decoder.m_sot_length >
opj_stream_get_number_byte_left(p_stream)) {
opj_event_msg(p_manager, EVT_ERROR,
"Tile part length size inconsistent with stream length\n");
return OPJ_FALSE;
}
if (p_j2k->m_specific_param.m_decoder.m_sot_length >
UINT_MAX - OPJ_COMMON_CBLK_DATA_EXTRA) {
opj_event_msg(p_manager, EVT_ERROR,
"p_j2k->m_specific_param.m_decoder.m_sot_length > "
"UINT_MAX - OPJ_COMMON_CBLK_DATA_EXTRA");
return OPJ_FALSE;
}
/* Add a margin of OPJ_COMMON_CBLK_DATA_EXTRA to the allocation we */
/* do so that opj_mqc_init_dec_common() can safely add a synthetic */
/* 0xFFFF marker. */
if (! *l_current_data) {
/* LH: oddly enough, in this path, l_tile_len!=0.
* TODO: If this was consistent, we could simplify the code to only use realloc(), as realloc(0,...) default to malloc(0,...).
*/
*l_current_data = (OPJ_BYTE*) opj_malloc(
p_j2k->m_specific_param.m_decoder.m_sot_length + OPJ_COMMON_CBLK_DATA_EXTRA);
} else {
OPJ_BYTE *l_new_current_data;
if (*l_tile_len > UINT_MAX - OPJ_COMMON_CBLK_DATA_EXTRA -
p_j2k->m_specific_param.m_decoder.m_sot_length) {
opj_event_msg(p_manager, EVT_ERROR,
"*l_tile_len > UINT_MAX - OPJ_COMMON_CBLK_DATA_EXTRA - "
"p_j2k->m_specific_param.m_decoder.m_sot_length");
return OPJ_FALSE;
}
l_new_current_data = (OPJ_BYTE *) opj_realloc(*l_current_data,
*l_tile_len + p_j2k->m_specific_param.m_decoder.m_sot_length +
OPJ_COMMON_CBLK_DATA_EXTRA);
if (! l_new_current_data) {
opj_free(*l_current_data);
/*nothing more is done as l_current_data will be set to null, and just
afterward we enter in the error path
and the actual tile_len is updated (committed) at the end of the
function. */
}
*l_current_data = l_new_current_data;
}
if (*l_current_data == 00) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to decode tile\n");
return OPJ_FALSE;
}
} else {
l_sot_length_pb_detected = OPJ_TRUE;
}
/* Index */
l_cstr_index = p_j2k->cstr_index;
if (l_cstr_index) {
OPJ_OFF_T l_current_pos = opj_stream_tell(p_stream) - 2;
OPJ_UINT32 l_current_tile_part =
l_cstr_index->tile_index[p_j2k->m_current_tile_number].current_tpsno;
l_cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index[l_current_tile_part].end_header
=
l_current_pos;
l_cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index[l_current_tile_part].end_pos
=
l_current_pos + p_j2k->m_specific_param.m_decoder.m_sot_length + 2;
if (OPJ_FALSE == opj_j2k_add_tlmarker(p_j2k->m_current_tile_number,
l_cstr_index,
J2K_MS_SOD,
l_current_pos,
p_j2k->m_specific_param.m_decoder.m_sot_length + 2)) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add tl marker\n");
return OPJ_FALSE;
}
/*l_cstr_index->packno = 0;*/
}
/* Patch to support new PHR data */
if (!l_sot_length_pb_detected) {
l_current_read_size = opj_stream_read_data(
p_stream,
*l_current_data + *l_tile_len,
p_j2k->m_specific_param.m_decoder.m_sot_length,
p_manager);
} else {
l_current_read_size = 0;
}
if (l_current_read_size != p_j2k->m_specific_param.m_decoder.m_sot_length) {
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_NEOC;
} else {
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPHSOT;
}
*l_tile_len += (OPJ_UINT32)l_current_read_size;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_rgn(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no,
OPJ_UINT32 nb_comps,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_BYTE * l_current_data = 00;
OPJ_UINT32 l_rgn_size;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_tccp_t *l_tccp = 00;
OPJ_UINT32 l_comp_room;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_tile_no];
l_tccp = &l_tcp->tccps[p_comp_no];
if (nb_comps <= 256) {
l_comp_room = 1;
} else {
l_comp_room = 2;
}
l_rgn_size = 6 + l_comp_room;
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_data, J2K_MS_RGN,
2); /* RGN */
l_current_data += 2;
opj_write_bytes(l_current_data, l_rgn_size - 2,
2); /* Lrgn */
l_current_data += 2;
opj_write_bytes(l_current_data, p_comp_no,
l_comp_room); /* Crgn */
l_current_data += l_comp_room;
opj_write_bytes(l_current_data, 0,
1); /* Srgn */
++l_current_data;
opj_write_bytes(l_current_data, (OPJ_UINT32)l_tccp->roishift,
1); /* SPrgn */
++l_current_data;
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_rgn_size,
p_manager) != l_rgn_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_eoc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
opj_write_bytes(p_j2k->m_specific_param.m_encoder.m_header_tile_data,
J2K_MS_EOC, 2); /* EOC */
/* UniPG>> */
#ifdef USE_JPWL
/* update markers struct */
/*
OPJ_BOOL res = j2k_add_marker(p_j2k->cstr_info, J2K_MS_EOC, p_stream_tell(p_stream) - 2, 2);
*/
#endif /* USE_JPWL */
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, 2, p_manager) != 2) {
return OPJ_FALSE;
}
if (! opj_stream_flush(p_stream, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a RGN marker (Region Of Interest)
*
* @param p_header_data the data contained in the POC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the POC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_rgn(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_nb_comp;
opj_image_t * l_image = 00;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
OPJ_UINT32 l_comp_room, l_comp_no, l_roi_sty;
/* preconditions*/
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_image = p_j2k->m_private_image;
l_nb_comp = l_image->numcomps;
if (l_nb_comp <= 256) {
l_comp_room = 1;
} else {
l_comp_room = 2;
}
if (p_header_size != 2 + l_comp_room) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading RGN marker\n");
return OPJ_FALSE;
}
l_cp = &(p_j2k->m_cp);
l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
opj_read_bytes(p_header_data, &l_comp_no, l_comp_room); /* Crgn */
p_header_data += l_comp_room;
opj_read_bytes(p_header_data, &l_roi_sty,
1); /* Srgn */
++p_header_data;
#ifdef USE_JPWL
if (l_cp->correct) {
/* totlen is negative or larger than the bytes left!!! */
if (l_comp_room >= l_nb_comp) {
opj_event_msg(p_manager, EVT_ERROR,
"JPWL: bad component number in RGN (%d when there are only %d)\n",
l_comp_room, l_nb_comp);
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
}
};
#endif /* USE_JPWL */
/* testcase 3635.pdf.asan.77.2930 */
if (l_comp_no >= l_nb_comp) {
opj_event_msg(p_manager, EVT_ERROR,
"bad component number in RGN (%d when there are only %d)\n",
l_comp_no, l_nb_comp);
return OPJ_FALSE;
}
opj_read_bytes(p_header_data,
(OPJ_UINT32 *)(&(l_tcp->tccps[l_comp_no].roishift)), 1); /* SPrgn */
++p_header_data;
return OPJ_TRUE;
}
static OPJ_FLOAT32 opj_j2k_get_tp_stride(opj_tcp_t * p_tcp)
{
return (OPJ_FLOAT32)((p_tcp->m_nb_tile_parts - 1) * 14);
}
static OPJ_FLOAT32 opj_j2k_get_default_stride(opj_tcp_t * p_tcp)
{
(void)p_tcp;
return 0;
}
static OPJ_BOOL opj_j2k_update_rates(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
opj_cp_t * l_cp = 00;
opj_image_t * l_image = 00;
opj_tcp_t * l_tcp = 00;
opj_image_comp_t * l_img_comp = 00;
OPJ_UINT32 i, j, k;
OPJ_INT32 l_x0, l_y0, l_x1, l_y1;
OPJ_FLOAT32 * l_rates = 0;
OPJ_FLOAT32 l_sot_remove;
OPJ_UINT32 l_bits_empty, l_size_pixel;
OPJ_UINT32 l_tile_size = 0;
OPJ_UINT32 l_last_res;
OPJ_FLOAT32(* l_tp_stride_func)(opj_tcp_t *) = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
OPJ_UNUSED(p_manager);
l_cp = &(p_j2k->m_cp);
l_image = p_j2k->m_private_image;
l_tcp = l_cp->tcps;
l_bits_empty = 8 * l_image->comps->dx * l_image->comps->dy;
l_size_pixel = l_image->numcomps * l_image->comps->prec;
l_sot_remove = (OPJ_FLOAT32) opj_stream_tell(p_stream) / (OPJ_FLOAT32)(
l_cp->th * l_cp->tw);
if (l_cp->m_specific_param.m_enc.m_tp_on) {
l_tp_stride_func = opj_j2k_get_tp_stride;
} else {
l_tp_stride_func = opj_j2k_get_default_stride;
}
for (i = 0; i < l_cp->th; ++i) {
for (j = 0; j < l_cp->tw; ++j) {
OPJ_FLOAT32 l_offset = (OPJ_FLOAT32)(*l_tp_stride_func)(l_tcp) /
(OPJ_FLOAT32)l_tcp->numlayers;
/* 4 borders of the tile rescale on the image if necessary */
l_x0 = opj_int_max((OPJ_INT32)(l_cp->tx0 + j * l_cp->tdx),
(OPJ_INT32)l_image->x0);
l_y0 = opj_int_max((OPJ_INT32)(l_cp->ty0 + i * l_cp->tdy),
(OPJ_INT32)l_image->y0);
l_x1 = opj_int_min((OPJ_INT32)(l_cp->tx0 + (j + 1) * l_cp->tdx),
(OPJ_INT32)l_image->x1);
l_y1 = opj_int_min((OPJ_INT32)(l_cp->ty0 + (i + 1) * l_cp->tdy),
(OPJ_INT32)l_image->y1);
l_rates = l_tcp->rates;
/* Modification of the RATE >> */
if (*l_rates > 0.0f) {
*l_rates = (((OPJ_FLOAT32)(l_size_pixel * (OPJ_UINT32)(l_x1 - l_x0) *
(OPJ_UINT32)(l_y1 - l_y0)))
/
((*l_rates) * (OPJ_FLOAT32)l_bits_empty)
)
-
l_offset;
}
++l_rates;
for (k = 1; k < l_tcp->numlayers; ++k) {
if (*l_rates > 0.0f) {
*l_rates = (((OPJ_FLOAT32)(l_size_pixel * (OPJ_UINT32)(l_x1 - l_x0) *
(OPJ_UINT32)(l_y1 - l_y0)))
/
((*l_rates) * (OPJ_FLOAT32)l_bits_empty)
)
-
l_offset;
}
++l_rates;
}
++l_tcp;
}
}
l_tcp = l_cp->tcps;
for (i = 0; i < l_cp->th; ++i) {
for (j = 0; j < l_cp->tw; ++j) {
l_rates = l_tcp->rates;
if (*l_rates > 0.0f) {
*l_rates -= l_sot_remove;
if (*l_rates < 30.0f) {
*l_rates = 30.0f;
}
}
++l_rates;
l_last_res = l_tcp->numlayers - 1;
for (k = 1; k < l_last_res; ++k) {
if (*l_rates > 0.0f) {
*l_rates -= l_sot_remove;
if (*l_rates < * (l_rates - 1) + 10.0f) {
*l_rates = (*(l_rates - 1)) + 20.0f;
}
}
++l_rates;
}
if (*l_rates > 0.0f) {
*l_rates -= (l_sot_remove + 2.f);
if (*l_rates < * (l_rates - 1) + 10.0f) {
*l_rates = (*(l_rates - 1)) + 20.0f;
}
}
++l_tcp;
}
}
l_img_comp = l_image->comps;
l_tile_size = 0;
for (i = 0; i < l_image->numcomps; ++i) {
l_tile_size += (opj_uint_ceildiv(l_cp->tdx, l_img_comp->dx)
*
opj_uint_ceildiv(l_cp->tdy, l_img_comp->dy)
*
l_img_comp->prec
);
++l_img_comp;
}
l_tile_size = (OPJ_UINT32)(l_tile_size * 0.1625); /* 1.3/8 = 0.1625 */
l_tile_size += opj_j2k_get_specific_header_sizes(p_j2k);
p_j2k->m_specific_param.m_encoder.m_encoded_tile_size = l_tile_size;
p_j2k->m_specific_param.m_encoder.m_encoded_tile_data =
(OPJ_BYTE *) opj_malloc(p_j2k->m_specific_param.m_encoder.m_encoded_tile_size);
if (p_j2k->m_specific_param.m_encoder.m_encoded_tile_data == 00) {
return OPJ_FALSE;
}
if (OPJ_IS_CINEMA(l_cp->rsiz)) {
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer =
(OPJ_BYTE *) opj_malloc(5 *
p_j2k->m_specific_param.m_encoder.m_total_tile_parts);
if (! p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer) {
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current =
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer;
}
return OPJ_TRUE;
}
#if 0
static OPJ_BOOL opj_j2k_read_eoc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 i;
opj_tcd_t * l_tcd = 00;
OPJ_UINT32 l_nb_tiles;
opj_tcp_t * l_tcp = 00;
OPJ_BOOL l_success;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
l_tcp = p_j2k->m_cp.tcps;
l_tcd = opj_tcd_create(OPJ_TRUE);
if (l_tcd == 00) {
opj_event_msg(p_manager, EVT_ERROR, "Cannot decode tile, memory error\n");
return OPJ_FALSE;
}
for (i = 0; i < l_nb_tiles; ++i) {
if (l_tcp->m_data) {
if (! opj_tcd_init_decode_tile(l_tcd, i)) {
opj_tcd_destroy(l_tcd);
opj_event_msg(p_manager, EVT_ERROR, "Cannot decode tile, memory error\n");
return OPJ_FALSE;
}
l_success = opj_tcd_decode_tile(l_tcd, l_tcp->m_data, l_tcp->m_data_size, i,
p_j2k->cstr_index);
/* cleanup */
if (! l_success) {
p_j2k->m_specific_param.m_decoder.m_state |= J2K_STATE_ERR;
break;
}
}
opj_j2k_tcp_destroy(l_tcp);
++l_tcp;
}
opj_tcd_destroy(l_tcd);
return OPJ_TRUE;
}
#endif
static OPJ_BOOL opj_j2k_get_end_header(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
OPJ_UNUSED(p_manager);
p_j2k->cstr_index->main_head_end = opj_stream_tell(p_stream);
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_mct_data_group(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 i;
opj_simple_mcc_decorrelation_data_t * l_mcc_record;
opj_mct_data_t * l_mct_record;
opj_tcp_t * l_tcp;
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
if (! opj_j2k_write_cbd(p_j2k, p_stream, p_manager)) {
return OPJ_FALSE;
}
l_tcp = &(p_j2k->m_cp.tcps[p_j2k->m_current_tile_number]);
l_mct_record = l_tcp->m_mct_records;
for (i = 0; i < l_tcp->m_nb_mct_records; ++i) {
if (! opj_j2k_write_mct_record(p_j2k, l_mct_record, p_stream, p_manager)) {
return OPJ_FALSE;
}
++l_mct_record;
}
l_mcc_record = l_tcp->m_mcc_records;
for (i = 0; i < l_tcp->m_nb_mcc_records; ++i) {
if (! opj_j2k_write_mcc_record(p_j2k, l_mcc_record, p_stream, p_manager)) {
return OPJ_FALSE;
}
++l_mcc_record;
}
if (! opj_j2k_write_mco(p_j2k, p_stream, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_all_coc(
opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 compno;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
for (compno = 1; compno < p_j2k->m_private_image->numcomps; ++compno) {
/* cod is first component of first tile */
if (! opj_j2k_compare_coc(p_j2k, 0, compno)) {
if (! opj_j2k_write_coc(p_j2k, compno, p_stream, p_manager)) {
return OPJ_FALSE;
}
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_all_qcc(
opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 compno;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
for (compno = 1; compno < p_j2k->m_private_image->numcomps; ++compno) {
/* qcd is first component of first tile */
if (! opj_j2k_compare_qcc(p_j2k, 0, compno)) {
if (! opj_j2k_write_qcc(p_j2k, compno, p_stream, p_manager)) {
return OPJ_FALSE;
}
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_regions(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 compno;
const opj_tccp_t *l_tccp = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_tccp = p_j2k->m_cp.tcps->tccps;
for (compno = 0; compno < p_j2k->m_private_image->numcomps; ++compno) {
if (l_tccp->roishift) {
if (! opj_j2k_write_rgn(p_j2k, 0, compno, p_j2k->m_private_image->numcomps,
p_stream, p_manager)) {
return OPJ_FALSE;
}
}
++l_tccp;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_epc(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
opj_codestream_index_t * l_cstr_index = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
OPJ_UNUSED(p_manager);
l_cstr_index = p_j2k->cstr_index;
if (l_cstr_index) {
l_cstr_index->codestream_size = (OPJ_UINT64)opj_stream_tell(p_stream);
/* UniPG>> */
/* The following adjustment is done to adjust the codestream size */
/* if SOD is not at 0 in the buffer. Useful in case of JP2, where */
/* the first bunch of bytes is not in the codestream */
l_cstr_index->codestream_size -= (OPJ_UINT64)l_cstr_index->main_head_start;
/* <<UniPG */
}
#ifdef USE_JPWL
/* preparation of JPWL marker segments */
#if 0
if (cp->epc_on) {
/* encode according to JPWL */
jpwl_encode(p_j2k, p_stream, image);
}
#endif
assert(0 && "TODO");
#endif /* USE_JPWL */
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_read_unk(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
OPJ_UINT32 *output_marker,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_unknown_marker;
const opj_dec_memory_marker_handler_t * l_marker_handler;
OPJ_UINT32 l_size_unk = 2;
/* preconditions*/
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
opj_event_msg(p_manager, EVT_WARNING, "Unknown marker\n");
for (;;) {
/* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer*/
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* read 2 bytes as the new marker ID*/
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,
&l_unknown_marker, 2);
if (!(l_unknown_marker < 0xff00)) {
/* Get the marker handler from the marker ID*/
l_marker_handler = opj_j2k_get_marker_handler(l_unknown_marker);
if (!(p_j2k->m_specific_param.m_decoder.m_state & l_marker_handler->states)) {
opj_event_msg(p_manager, EVT_ERROR,
"Marker is not compliant with its position\n");
return OPJ_FALSE;
} else {
if (l_marker_handler->id != J2K_MS_UNK) {
/* Add the marker to the codestream index*/
if (l_marker_handler->id != J2K_MS_SOT) {
OPJ_BOOL res = opj_j2k_add_mhmarker(p_j2k->cstr_index, J2K_MS_UNK,
(OPJ_UINT32) opj_stream_tell(p_stream) - l_size_unk,
l_size_unk);
if (res == OPJ_FALSE) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add mh marker\n");
return OPJ_FALSE;
}
}
break; /* next marker is known and well located */
} else {
l_size_unk += 2;
}
}
}
}
*output_marker = l_marker_handler->id ;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_mct_record(opj_j2k_t *p_j2k,
opj_mct_data_t * p_mct_record,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 l_mct_size;
OPJ_BYTE * l_current_data = 00;
OPJ_UINT32 l_tmp;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_mct_size = 10 + p_mct_record->m_data_size;
if (l_mct_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mct_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write MCT marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_mct_size;
}
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_data, J2K_MS_MCT,
2); /* MCT */
l_current_data += 2;
opj_write_bytes(l_current_data, l_mct_size - 2,
2); /* Lmct */
l_current_data += 2;
opj_write_bytes(l_current_data, 0,
2); /* Zmct */
l_current_data += 2;
/* only one marker atm */
l_tmp = (p_mct_record->m_index & 0xff) | (p_mct_record->m_array_type << 8) |
(p_mct_record->m_element_type << 10);
opj_write_bytes(l_current_data, l_tmp, 2);
l_current_data += 2;
opj_write_bytes(l_current_data, 0,
2); /* Ymct */
l_current_data += 2;
memcpy(l_current_data, p_mct_record->m_data, p_mct_record->m_data_size);
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mct_size,
p_manager) != l_mct_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a MCT marker (Multiple Component Transform)
*
* @param p_header_data the data contained in the MCT box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the MCT marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_mct(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 i;
opj_tcp_t *l_tcp = 00;
OPJ_UINT32 l_tmp;
OPJ_UINT32 l_indix;
opj_mct_data_t * l_mct_data;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
l_tcp = p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH ?
&p_j2k->m_cp.tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
if (p_header_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCT marker\n");
return OPJ_FALSE;
}
/* first marker */
opj_read_bytes(p_header_data, &l_tmp, 2); /* Zmct */
p_header_data += 2;
if (l_tmp != 0) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge mct data within multiple MCT records\n");
return OPJ_TRUE;
}
if (p_header_size <= 6) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCT marker\n");
return OPJ_FALSE;
}
/* Imct -> no need for other values, take the first, type is double with decorrelation x0000 1101 0000 0000*/
opj_read_bytes(p_header_data, &l_tmp, 2); /* Imct */
p_header_data += 2;
l_indix = l_tmp & 0xff;
l_mct_data = l_tcp->m_mct_records;
for (i = 0; i < l_tcp->m_nb_mct_records; ++i) {
if (l_mct_data->m_index == l_indix) {
break;
}
++l_mct_data;
}
/* NOT FOUND */
if (i == l_tcp->m_nb_mct_records) {
if (l_tcp->m_nb_mct_records == l_tcp->m_nb_max_mct_records) {
opj_mct_data_t *new_mct_records;
l_tcp->m_nb_max_mct_records += OPJ_J2K_MCT_DEFAULT_NB_RECORDS;
new_mct_records = (opj_mct_data_t *) opj_realloc(l_tcp->m_mct_records,
l_tcp->m_nb_max_mct_records * sizeof(opj_mct_data_t));
if (! new_mct_records) {
opj_free(l_tcp->m_mct_records);
l_tcp->m_mct_records = NULL;
l_tcp->m_nb_max_mct_records = 0;
l_tcp->m_nb_mct_records = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read MCT marker\n");
return OPJ_FALSE;
}
/* Update m_mcc_records[].m_offset_array and m_decorrelation_array
* to point to the new addresses */
if (new_mct_records != l_tcp->m_mct_records) {
for (i = 0; i < l_tcp->m_nb_mcc_records; ++i) {
opj_simple_mcc_decorrelation_data_t* l_mcc_record =
&(l_tcp->m_mcc_records[i]);
if (l_mcc_record->m_decorrelation_array) {
l_mcc_record->m_decorrelation_array =
new_mct_records +
(l_mcc_record->m_decorrelation_array -
l_tcp->m_mct_records);
}
if (l_mcc_record->m_offset_array) {
l_mcc_record->m_offset_array =
new_mct_records +
(l_mcc_record->m_offset_array -
l_tcp->m_mct_records);
}
}
}
l_tcp->m_mct_records = new_mct_records;
l_mct_data = l_tcp->m_mct_records + l_tcp->m_nb_mct_records;
memset(l_mct_data, 0, (l_tcp->m_nb_max_mct_records - l_tcp->m_nb_mct_records) *
sizeof(opj_mct_data_t));
}
l_mct_data = l_tcp->m_mct_records + l_tcp->m_nb_mct_records;
++l_tcp->m_nb_mct_records;
}
if (l_mct_data->m_data) {
opj_free(l_mct_data->m_data);
l_mct_data->m_data = 00;
l_mct_data->m_data_size = 0;
}
l_mct_data->m_index = l_indix;
l_mct_data->m_array_type = (J2K_MCT_ARRAY_TYPE)((l_tmp >> 8) & 3);
l_mct_data->m_element_type = (J2K_MCT_ELEMENT_TYPE)((l_tmp >> 10) & 3);
opj_read_bytes(p_header_data, &l_tmp, 2); /* Ymct */
p_header_data += 2;
if (l_tmp != 0) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge multiple MCT markers\n");
return OPJ_TRUE;
}
p_header_size -= 6;
l_mct_data->m_data = (OPJ_BYTE*)opj_malloc(p_header_size);
if (! l_mct_data->m_data) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCT marker\n");
return OPJ_FALSE;
}
memcpy(l_mct_data->m_data, p_header_data, p_header_size);
l_mct_data->m_data_size = p_header_size;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_mcc_record(opj_j2k_t *p_j2k,
struct opj_simple_mcc_decorrelation_data * p_mcc_record,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 i;
OPJ_UINT32 l_mcc_size;
OPJ_BYTE * l_current_data = 00;
OPJ_UINT32 l_nb_bytes_for_comp;
OPJ_UINT32 l_mask;
OPJ_UINT32 l_tmcc;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
if (p_mcc_record->m_nb_comps > 255) {
l_nb_bytes_for_comp = 2;
l_mask = 0x8000;
} else {
l_nb_bytes_for_comp = 1;
l_mask = 0;
}
l_mcc_size = p_mcc_record->m_nb_comps * 2 * l_nb_bytes_for_comp + 19;
if (l_mcc_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mcc_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write MCC marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_mcc_size;
}
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_data, J2K_MS_MCC,
2); /* MCC */
l_current_data += 2;
opj_write_bytes(l_current_data, l_mcc_size - 2,
2); /* Lmcc */
l_current_data += 2;
/* first marker */
opj_write_bytes(l_current_data, 0,
2); /* Zmcc */
l_current_data += 2;
opj_write_bytes(l_current_data, p_mcc_record->m_index,
1); /* Imcc -> no need for other values, take the first */
++l_current_data;
/* only one marker atm */
opj_write_bytes(l_current_data, 0,
2); /* Ymcc */
l_current_data += 2;
opj_write_bytes(l_current_data, 1,
2); /* Qmcc -> number of collections -> 1 */
l_current_data += 2;
opj_write_bytes(l_current_data, 0x1,
1); /* Xmcci type of component transformation -> array based decorrelation */
++l_current_data;
opj_write_bytes(l_current_data, p_mcc_record->m_nb_comps | l_mask,
2); /* Nmcci number of input components involved and size for each component offset = 8 bits */
l_current_data += 2;
for (i = 0; i < p_mcc_record->m_nb_comps; ++i) {
opj_write_bytes(l_current_data, i,
l_nb_bytes_for_comp); /* Cmccij Component offset*/
l_current_data += l_nb_bytes_for_comp;
}
opj_write_bytes(l_current_data, p_mcc_record->m_nb_comps | l_mask,
2); /* Mmcci number of output components involved and size for each component offset = 8 bits */
l_current_data += 2;
for (i = 0; i < p_mcc_record->m_nb_comps; ++i) {
opj_write_bytes(l_current_data, i,
l_nb_bytes_for_comp); /* Wmccij Component offset*/
l_current_data += l_nb_bytes_for_comp;
}
l_tmcc = ((!p_mcc_record->m_is_irreversible) & 1U) << 16;
if (p_mcc_record->m_decorrelation_array) {
l_tmcc |= p_mcc_record->m_decorrelation_array->m_index;
}
if (p_mcc_record->m_offset_array) {
l_tmcc |= ((p_mcc_record->m_offset_array->m_index) << 8);
}
opj_write_bytes(l_current_data, l_tmcc,
3); /* Tmcci : use MCT defined as number 1 and irreversible array based. */
l_current_data += 3;
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mcc_size,
p_manager) != l_mcc_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_read_mcc(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 i, j;
OPJ_UINT32 l_tmp;
OPJ_UINT32 l_indix;
opj_tcp_t * l_tcp;
opj_simple_mcc_decorrelation_data_t * l_mcc_record;
opj_mct_data_t * l_mct_data;
OPJ_UINT32 l_nb_collections;
OPJ_UINT32 l_nb_comps;
OPJ_UINT32 l_nb_bytes_by_comp;
OPJ_BOOL l_new_mcc = OPJ_FALSE;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_tcp = p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH ?
&p_j2k->m_cp.tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
if (p_header_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
/* first marker */
opj_read_bytes(p_header_data, &l_tmp, 2); /* Zmcc */
p_header_data += 2;
if (l_tmp != 0) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge multiple data spanning\n");
return OPJ_TRUE;
}
if (p_header_size < 7) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_indix,
1); /* Imcc -> no need for other values, take the first */
++p_header_data;
l_mcc_record = l_tcp->m_mcc_records;
for (i = 0; i < l_tcp->m_nb_mcc_records; ++i) {
if (l_mcc_record->m_index == l_indix) {
break;
}
++l_mcc_record;
}
/** NOT FOUND */
if (i == l_tcp->m_nb_mcc_records) {
if (l_tcp->m_nb_mcc_records == l_tcp->m_nb_max_mcc_records) {
opj_simple_mcc_decorrelation_data_t *new_mcc_records;
l_tcp->m_nb_max_mcc_records += OPJ_J2K_MCC_DEFAULT_NB_RECORDS;
new_mcc_records = (opj_simple_mcc_decorrelation_data_t *) opj_realloc(
l_tcp->m_mcc_records, l_tcp->m_nb_max_mcc_records * sizeof(
opj_simple_mcc_decorrelation_data_t));
if (! new_mcc_records) {
opj_free(l_tcp->m_mcc_records);
l_tcp->m_mcc_records = NULL;
l_tcp->m_nb_max_mcc_records = 0;
l_tcp->m_nb_mcc_records = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read MCC marker\n");
return OPJ_FALSE;
}
l_tcp->m_mcc_records = new_mcc_records;
l_mcc_record = l_tcp->m_mcc_records + l_tcp->m_nb_mcc_records;
memset(l_mcc_record, 0, (l_tcp->m_nb_max_mcc_records - l_tcp->m_nb_mcc_records)
* sizeof(opj_simple_mcc_decorrelation_data_t));
}
l_mcc_record = l_tcp->m_mcc_records + l_tcp->m_nb_mcc_records;
l_new_mcc = OPJ_TRUE;
}
l_mcc_record->m_index = l_indix;
/* only one marker atm */
opj_read_bytes(p_header_data, &l_tmp, 2); /* Ymcc */
p_header_data += 2;
if (l_tmp != 0) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge multiple data spanning\n");
return OPJ_TRUE;
}
opj_read_bytes(p_header_data, &l_nb_collections,
2); /* Qmcc -> number of collections -> 1 */
p_header_data += 2;
if (l_nb_collections > 1) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge multiple collections\n");
return OPJ_TRUE;
}
p_header_size -= 7;
for (i = 0; i < l_nb_collections; ++i) {
if (p_header_size < 3) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_tmp,
1); /* Xmcci type of component transformation -> array based decorrelation */
++p_header_data;
if (l_tmp != 1) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge collections other than array decorrelation\n");
return OPJ_TRUE;
}
opj_read_bytes(p_header_data, &l_nb_comps, 2);
p_header_data += 2;
p_header_size -= 3;
l_nb_bytes_by_comp = 1 + (l_nb_comps >> 15);
l_mcc_record->m_nb_comps = l_nb_comps & 0x7fff;
if (p_header_size < (l_nb_bytes_by_comp * l_mcc_record->m_nb_comps + 2)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
p_header_size -= (l_nb_bytes_by_comp * l_mcc_record->m_nb_comps + 2);
for (j = 0; j < l_mcc_record->m_nb_comps; ++j) {
opj_read_bytes(p_header_data, &l_tmp,
l_nb_bytes_by_comp); /* Cmccij Component offset*/
p_header_data += l_nb_bytes_by_comp;
if (l_tmp != j) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge collections with indix shuffle\n");
return OPJ_TRUE;
}
}
opj_read_bytes(p_header_data, &l_nb_comps, 2);
p_header_data += 2;
l_nb_bytes_by_comp = 1 + (l_nb_comps >> 15);
l_nb_comps &= 0x7fff;
if (l_nb_comps != l_mcc_record->m_nb_comps) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge collections without same number of indixes\n");
return OPJ_TRUE;
}
if (p_header_size < (l_nb_bytes_by_comp * l_mcc_record->m_nb_comps + 3)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
p_header_size -= (l_nb_bytes_by_comp * l_mcc_record->m_nb_comps + 3);
for (j = 0; j < l_mcc_record->m_nb_comps; ++j) {
opj_read_bytes(p_header_data, &l_tmp,
l_nb_bytes_by_comp); /* Wmccij Component offset*/
p_header_data += l_nb_bytes_by_comp;
if (l_tmp != j) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge collections with indix shuffle\n");
return OPJ_TRUE;
}
}
opj_read_bytes(p_header_data, &l_tmp, 3); /* Wmccij Component offset*/
p_header_data += 3;
l_mcc_record->m_is_irreversible = !((l_tmp >> 16) & 1);
l_mcc_record->m_decorrelation_array = 00;
l_mcc_record->m_offset_array = 00;
l_indix = l_tmp & 0xff;
if (l_indix != 0) {
l_mct_data = l_tcp->m_mct_records;
for (j = 0; j < l_tcp->m_nb_mct_records; ++j) {
if (l_mct_data->m_index == l_indix) {
l_mcc_record->m_decorrelation_array = l_mct_data;
break;
}
++l_mct_data;
}
if (l_mcc_record->m_decorrelation_array == 00) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
}
l_indix = (l_tmp >> 8) & 0xff;
if (l_indix != 0) {
l_mct_data = l_tcp->m_mct_records;
for (j = 0; j < l_tcp->m_nb_mct_records; ++j) {
if (l_mct_data->m_index == l_indix) {
l_mcc_record->m_offset_array = l_mct_data;
break;
}
++l_mct_data;
}
if (l_mcc_record->m_offset_array == 00) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
}
}
if (p_header_size != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
if (l_new_mcc) {
++l_tcp->m_nb_mcc_records;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_mco(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager
)
{
OPJ_BYTE * l_current_data = 00;
OPJ_UINT32 l_mco_size;
opj_tcp_t * l_tcp = 00;
opj_simple_mcc_decorrelation_data_t * l_mcc_record;
OPJ_UINT32 i;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_tcp = &(p_j2k->m_cp.tcps[p_j2k->m_current_tile_number]);
l_mco_size = 5 + l_tcp->m_nb_mcc_records;
if (l_mco_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mco_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write MCO marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_mco_size;
}
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_data, J2K_MS_MCO, 2); /* MCO */
l_current_data += 2;
opj_write_bytes(l_current_data, l_mco_size - 2, 2); /* Lmco */
l_current_data += 2;
opj_write_bytes(l_current_data, l_tcp->m_nb_mcc_records,
1); /* Nmco : only one transform stage*/
++l_current_data;
l_mcc_record = l_tcp->m_mcc_records;
for (i = 0; i < l_tcp->m_nb_mcc_records; ++i) {
opj_write_bytes(l_current_data, l_mcc_record->m_index,
1); /* Imco -> use the mcc indicated by 1*/
++l_current_data;
++l_mcc_record;
}
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mco_size,
p_manager) != l_mco_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a MCO marker (Multiple Component Transform Ordering)
*
* @param p_header_data the data contained in the MCO box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the MCO marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_mco(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_tmp, i;
OPJ_UINT32 l_nb_stages;
opj_tcp_t * l_tcp;
opj_tccp_t * l_tccp;
opj_image_t * l_image;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_image = p_j2k->m_private_image;
l_tcp = p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH ?
&p_j2k->m_cp.tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
if (p_header_size < 1) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCO marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_nb_stages,
1); /* Nmco : only one transform stage*/
++p_header_data;
if (l_nb_stages > 1) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge multiple transformation stages.\n");
return OPJ_TRUE;
}
if (p_header_size != l_nb_stages + 1) {
opj_event_msg(p_manager, EVT_WARNING, "Error reading MCO marker\n");
return OPJ_FALSE;
}
l_tccp = l_tcp->tccps;
for (i = 0; i < l_image->numcomps; ++i) {
l_tccp->m_dc_level_shift = 0;
++l_tccp;
}
if (l_tcp->m_mct_decoding_matrix) {
opj_free(l_tcp->m_mct_decoding_matrix);
l_tcp->m_mct_decoding_matrix = 00;
}
for (i = 0; i < l_nb_stages; ++i) {
opj_read_bytes(p_header_data, &l_tmp, 1);
++p_header_data;
if (! opj_j2k_add_mct(l_tcp, p_j2k->m_private_image, l_tmp)) {
return OPJ_FALSE;
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_add_mct(opj_tcp_t * p_tcp, opj_image_t * p_image,
OPJ_UINT32 p_index)
{
OPJ_UINT32 i;
opj_simple_mcc_decorrelation_data_t * l_mcc_record;
opj_mct_data_t * l_deco_array, * l_offset_array;
OPJ_UINT32 l_data_size, l_mct_size, l_offset_size;
OPJ_UINT32 l_nb_elem;
OPJ_UINT32 * l_offset_data, * l_current_offset_data;
opj_tccp_t * l_tccp;
/* preconditions */
assert(p_tcp != 00);
l_mcc_record = p_tcp->m_mcc_records;
for (i = 0; i < p_tcp->m_nb_mcc_records; ++i) {
if (l_mcc_record->m_index == p_index) {
break;
}
}
if (i == p_tcp->m_nb_mcc_records) {
/** element discarded **/
return OPJ_TRUE;
}
if (l_mcc_record->m_nb_comps != p_image->numcomps) {
/** do not support number of comps != image */
return OPJ_TRUE;
}
l_deco_array = l_mcc_record->m_decorrelation_array;
if (l_deco_array) {
l_data_size = MCT_ELEMENT_SIZE[l_deco_array->m_element_type] * p_image->numcomps
* p_image->numcomps;
if (l_deco_array->m_data_size != l_data_size) {
return OPJ_FALSE;
}
l_nb_elem = p_image->numcomps * p_image->numcomps;
l_mct_size = l_nb_elem * (OPJ_UINT32)sizeof(OPJ_FLOAT32);
p_tcp->m_mct_decoding_matrix = (OPJ_FLOAT32*)opj_malloc(l_mct_size);
if (! p_tcp->m_mct_decoding_matrix) {
return OPJ_FALSE;
}
j2k_mct_read_functions_to_float[l_deco_array->m_element_type](
l_deco_array->m_data, p_tcp->m_mct_decoding_matrix, l_nb_elem);
}
l_offset_array = l_mcc_record->m_offset_array;
if (l_offset_array) {
l_data_size = MCT_ELEMENT_SIZE[l_offset_array->m_element_type] *
p_image->numcomps;
if (l_offset_array->m_data_size != l_data_size) {
return OPJ_FALSE;
}
l_nb_elem = p_image->numcomps;
l_offset_size = l_nb_elem * (OPJ_UINT32)sizeof(OPJ_UINT32);
l_offset_data = (OPJ_UINT32*)opj_malloc(l_offset_size);
if (! l_offset_data) {
return OPJ_FALSE;
}
j2k_mct_read_functions_to_int32[l_offset_array->m_element_type](
l_offset_array->m_data, l_offset_data, l_nb_elem);
l_tccp = p_tcp->tccps;
l_current_offset_data = l_offset_data;
for (i = 0; i < p_image->numcomps; ++i) {
l_tccp->m_dc_level_shift = (OPJ_INT32) * (l_current_offset_data++);
++l_tccp;
}
opj_free(l_offset_data);
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_cbd(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 i;
OPJ_UINT32 l_cbd_size;
OPJ_BYTE * l_current_data = 00;
opj_image_t *l_image = 00;
opj_image_comp_t * l_comp = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_image = p_j2k->m_private_image;
l_cbd_size = 6 + p_j2k->m_private_image->numcomps;
if (l_cbd_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_cbd_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write CBD marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_cbd_size;
}
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_data, J2K_MS_CBD, 2); /* CBD */
l_current_data += 2;
opj_write_bytes(l_current_data, l_cbd_size - 2, 2); /* L_CBD */
l_current_data += 2;
opj_write_bytes(l_current_data, l_image->numcomps, 2); /* Ncbd */
l_current_data += 2;
l_comp = l_image->comps;
for (i = 0; i < l_image->numcomps; ++i) {
opj_write_bytes(l_current_data, (l_comp->sgnd << 7) | (l_comp->prec - 1),
1); /* Component bit depth */
++l_current_data;
++l_comp;
}
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_cbd_size,
p_manager) != l_cbd_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a CBD marker (Component bit depth definition)
* @param p_header_data the data contained in the CBD box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the CBD marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_cbd(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_nb_comp, l_num_comp;
OPJ_UINT32 l_comp_def;
OPJ_UINT32 i;
opj_image_comp_t * l_comp = 00;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_num_comp = p_j2k->m_private_image->numcomps;
if (p_header_size != (p_j2k->m_private_image->numcomps + 2)) {
opj_event_msg(p_manager, EVT_ERROR, "Crror reading CBD marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_nb_comp,
2); /* Ncbd */
p_header_data += 2;
if (l_nb_comp != l_num_comp) {
opj_event_msg(p_manager, EVT_ERROR, "Crror reading CBD marker\n");
return OPJ_FALSE;
}
l_comp = p_j2k->m_private_image->comps;
for (i = 0; i < l_num_comp; ++i) {
opj_read_bytes(p_header_data, &l_comp_def,
1); /* Component bit depth */
++p_header_data;
l_comp->sgnd = (l_comp_def >> 7) & 1;
l_comp->prec = (l_comp_def & 0x7f) + 1;
if (l_comp->prec > 31) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid values for comp = %d : prec=%u (should be between 1 and 38 according to the JPEG2000 norm. OpenJpeg only supports up to 31)\n",
i, l_comp->prec);
return OPJ_FALSE;
}
++l_comp;
}
return OPJ_TRUE;
}
/* ----------------------------------------------------------------------- */
/* J2K / JPT decoder interface */
/* ----------------------------------------------------------------------- */
void opj_j2k_setup_decoder(opj_j2k_t *j2k, opj_dparameters_t *parameters)
{
if (j2k && parameters) {
j2k->m_cp.m_specific_param.m_dec.m_layer = parameters->cp_layer;
j2k->m_cp.m_specific_param.m_dec.m_reduce = parameters->cp_reduce;
j2k->dump_state = (parameters->flags & OPJ_DPARAMETERS_DUMP_FLAG);
#ifdef USE_JPWL
j2k->m_cp.correct = parameters->jpwl_correct;
j2k->m_cp.exp_comps = parameters->jpwl_exp_comps;
j2k->m_cp.max_tiles = parameters->jpwl_max_tiles;
#endif /* USE_JPWL */
}
}
OPJ_BOOL opj_j2k_set_threads(opj_j2k_t *j2k, OPJ_UINT32 num_threads)
{
if (opj_has_thread_support()) {
opj_thread_pool_destroy(j2k->m_tp);
j2k->m_tp = NULL;
if (num_threads <= (OPJ_UINT32)INT_MAX) {
j2k->m_tp = opj_thread_pool_create((int)num_threads);
}
if (j2k->m_tp == NULL) {
j2k->m_tp = opj_thread_pool_create(0);
return OPJ_FALSE;
}
return OPJ_TRUE;
}
return OPJ_FALSE;
}
static int opj_j2k_get_default_thread_count()
{
const char* num_threads = getenv("OPJ_NUM_THREADS");
if (num_threads == NULL || !opj_has_thread_support()) {
return 0;
}
if (strcmp(num_threads, "ALL_CPUS") == 0) {
return opj_get_num_cpus();
}
return atoi(num_threads);
}
/* ----------------------------------------------------------------------- */
/* J2K encoder interface */
/* ----------------------------------------------------------------------- */
opj_j2k_t* opj_j2k_create_compress(void)
{
opj_j2k_t *l_j2k = (opj_j2k_t*) opj_calloc(1, sizeof(opj_j2k_t));
if (!l_j2k) {
return NULL;
}
l_j2k->m_is_decoder = 0;
l_j2k->m_cp.m_is_decoder = 0;
l_j2k->m_specific_param.m_encoder.m_header_tile_data = (OPJ_BYTE *) opj_malloc(
OPJ_J2K_DEFAULT_HEADER_SIZE);
if (! l_j2k->m_specific_param.m_encoder.m_header_tile_data) {
opj_j2k_destroy(l_j2k);
return NULL;
}
l_j2k->m_specific_param.m_encoder.m_header_tile_data_size =
OPJ_J2K_DEFAULT_HEADER_SIZE;
/* validation list creation*/
l_j2k->m_validation_list = opj_procedure_list_create();
if (! l_j2k->m_validation_list) {
opj_j2k_destroy(l_j2k);
return NULL;
}
/* execution list creation*/
l_j2k->m_procedure_list = opj_procedure_list_create();
if (! l_j2k->m_procedure_list) {
opj_j2k_destroy(l_j2k);
return NULL;
}
l_j2k->m_tp = opj_thread_pool_create(opj_j2k_get_default_thread_count());
if (!l_j2k->m_tp) {
l_j2k->m_tp = opj_thread_pool_create(0);
}
if (!l_j2k->m_tp) {
opj_j2k_destroy(l_j2k);
return NULL;
}
return l_j2k;
}
static int opj_j2k_initialise_4K_poc(opj_poc_t *POC, int numres)
{
POC[0].tile = 1;
POC[0].resno0 = 0;
POC[0].compno0 = 0;
POC[0].layno1 = 1;
POC[0].resno1 = (OPJ_UINT32)(numres - 1);
POC[0].compno1 = 3;
POC[0].prg1 = OPJ_CPRL;
POC[1].tile = 1;
POC[1].resno0 = (OPJ_UINT32)(numres - 1);
POC[1].compno0 = 0;
POC[1].layno1 = 1;
POC[1].resno1 = (OPJ_UINT32)numres;
POC[1].compno1 = 3;
POC[1].prg1 = OPJ_CPRL;
return 2;
}
static void opj_j2k_set_cinema_parameters(opj_cparameters_t *parameters,
opj_image_t *image, opj_event_mgr_t *p_manager)
{
/* Configure cinema parameters */
int i;
/* No tiling */
parameters->tile_size_on = OPJ_FALSE;
parameters->cp_tdx = 1;
parameters->cp_tdy = 1;
/* One tile part for each component */
parameters->tp_flag = 'C';
parameters->tp_on = 1;
/* Tile and Image shall be at (0,0) */
parameters->cp_tx0 = 0;
parameters->cp_ty0 = 0;
parameters->image_offset_x0 = 0;
parameters->image_offset_y0 = 0;
/* Codeblock size= 32*32 */
parameters->cblockw_init = 32;
parameters->cblockh_init = 32;
/* Codeblock style: no mode switch enabled */
parameters->mode = 0;
/* No ROI */
parameters->roi_compno = -1;
/* No subsampling */
parameters->subsampling_dx = 1;
parameters->subsampling_dy = 1;
/* 9-7 transform */
parameters->irreversible = 1;
/* Number of layers */
if (parameters->tcp_numlayers > 1) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
"1 single quality layer"
"-> Number of layers forced to 1 (rather than %d)\n"
"-> Rate of the last layer (%3.1f) will be used",
parameters->tcp_numlayers,
parameters->tcp_rates[parameters->tcp_numlayers - 1]);
parameters->tcp_rates[0] = parameters->tcp_rates[parameters->tcp_numlayers - 1];
parameters->tcp_numlayers = 1;
}
/* Resolution levels */
switch (parameters->rsiz) {
case OPJ_PROFILE_CINEMA_2K:
if (parameters->numresolution > 6) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 (2k dc profile) requires:\n"
"Number of decomposition levels <= 5\n"
"-> Number of decomposition levels forced to 5 (rather than %d)\n",
parameters->numresolution + 1);
parameters->numresolution = 6;
}
break;
case OPJ_PROFILE_CINEMA_4K:
if (parameters->numresolution < 2) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-4 (4k dc profile) requires:\n"
"Number of decomposition levels >= 1 && <= 6\n"
"-> Number of decomposition levels forced to 1 (rather than %d)\n",
parameters->numresolution + 1);
parameters->numresolution = 1;
} else if (parameters->numresolution > 7) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-4 (4k dc profile) requires:\n"
"Number of decomposition levels >= 1 && <= 6\n"
"-> Number of decomposition levels forced to 6 (rather than %d)\n",
parameters->numresolution + 1);
parameters->numresolution = 7;
}
break;
default :
break;
}
/* Precincts */
parameters->csty |= 0x01;
parameters->res_spec = parameters->numresolution - 1;
for (i = 0; i < parameters->res_spec; i++) {
parameters->prcw_init[i] = 256;
parameters->prch_init[i] = 256;
}
/* The progression order shall be CPRL */
parameters->prog_order = OPJ_CPRL;
/* Progression order changes for 4K, disallowed for 2K */
if (parameters->rsiz == OPJ_PROFILE_CINEMA_4K) {
parameters->numpocs = (OPJ_UINT32)opj_j2k_initialise_4K_poc(parameters->POC,
parameters->numresolution);
} else {
parameters->numpocs = 0;
}
/* Limited bit-rate */
parameters->cp_disto_alloc = 1;
if (parameters->max_cs_size <= 0) {
/* No rate has been introduced, 24 fps is assumed */
parameters->max_cs_size = OPJ_CINEMA_24_CS;
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
"Maximum 1302083 compressed bytes @ 24fps\n"
"As no rate has been given, this limit will be used.\n");
} else if (parameters->max_cs_size > OPJ_CINEMA_24_CS) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
"Maximum 1302083 compressed bytes @ 24fps\n"
"-> Specified rate exceeds this limit. Rate will be forced to 1302083 bytes.\n");
parameters->max_cs_size = OPJ_CINEMA_24_CS;
}
if (parameters->max_comp_size <= 0) {
/* No rate has been introduced, 24 fps is assumed */
parameters->max_comp_size = OPJ_CINEMA_24_COMP;
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
"Maximum 1041666 compressed bytes @ 24fps\n"
"As no rate has been given, this limit will be used.\n");
} else if (parameters->max_comp_size > OPJ_CINEMA_24_COMP) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
"Maximum 1041666 compressed bytes @ 24fps\n"
"-> Specified rate exceeds this limit. Rate will be forced to 1041666 bytes.\n");
parameters->max_comp_size = OPJ_CINEMA_24_COMP;
}
parameters->tcp_rates[0] = (OPJ_FLOAT32)(image->numcomps * image->comps[0].w *
image->comps[0].h * image->comps[0].prec) /
(OPJ_FLOAT32)(((OPJ_UINT32)parameters->max_cs_size) * 8 * image->comps[0].dx *
image->comps[0].dy);
}
static OPJ_BOOL opj_j2k_is_cinema_compliant(opj_image_t *image, OPJ_UINT16 rsiz,
opj_event_mgr_t *p_manager)
{
OPJ_UINT32 i;
/* Number of components */
if (image->numcomps != 3) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 (2k dc profile) requires:\n"
"3 components"
"-> Number of components of input image (%d) is not compliant\n"
"-> Non-profile-3 codestream will be generated\n",
image->numcomps);
return OPJ_FALSE;
}
/* Bitdepth */
for (i = 0; i < image->numcomps; i++) {
if ((image->comps[i].bpp != 12) | (image->comps[i].sgnd)) {
char signed_str[] = "signed";
char unsigned_str[] = "unsigned";
char *tmp_str = image->comps[i].sgnd ? signed_str : unsigned_str;
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 (2k dc profile) requires:\n"
"Precision of each component shall be 12 bits unsigned"
"-> At least component %d of input image (%d bits, %s) is not compliant\n"
"-> Non-profile-3 codestream will be generated\n",
i, image->comps[i].bpp, tmp_str);
return OPJ_FALSE;
}
}
/* Image size */
switch (rsiz) {
case OPJ_PROFILE_CINEMA_2K:
if (((image->comps[0].w > 2048) | (image->comps[0].h > 1080))) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 (2k dc profile) requires:\n"
"width <= 2048 and height <= 1080\n"
"-> Input image size %d x %d is not compliant\n"
"-> Non-profile-3 codestream will be generated\n",
image->comps[0].w, image->comps[0].h);
return OPJ_FALSE;
}
break;
case OPJ_PROFILE_CINEMA_4K:
if (((image->comps[0].w > 4096) | (image->comps[0].h > 2160))) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-4 (4k dc profile) requires:\n"
"width <= 4096 and height <= 2160\n"
"-> Image size %d x %d is not compliant\n"
"-> Non-profile-4 codestream will be generated\n",
image->comps[0].w, image->comps[0].h);
return OPJ_FALSE;
}
break;
default :
break;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_setup_encoder(opj_j2k_t *p_j2k,
opj_cparameters_t *parameters,
opj_image_t *image,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 i, j, tileno, numpocs_tile;
opj_cp_t *cp = 00;
if (!p_j2k || !parameters || ! image) {
return OPJ_FALSE;
}
if ((parameters->numresolution <= 0) ||
(parameters->numresolution > OPJ_J2K_MAXRLVLS)) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid number of resolutions : %d not in range [1,%d]\n",
parameters->numresolution, OPJ_J2K_MAXRLVLS);
return OPJ_FALSE;
}
/* keep a link to cp so that we can destroy it later in j2k_destroy_compress */
cp = &(p_j2k->m_cp);
/* set default values for cp */
cp->tw = 1;
cp->th = 1;
/* FIXME ADE: to be removed once deprecated cp_cinema and cp_rsiz have been removed */
if (parameters->rsiz ==
OPJ_PROFILE_NONE) { /* consider deprecated fields only if RSIZ has not been set */
OPJ_BOOL deprecated_used = OPJ_FALSE;
switch (parameters->cp_cinema) {
case OPJ_CINEMA2K_24:
parameters->rsiz = OPJ_PROFILE_CINEMA_2K;
parameters->max_cs_size = OPJ_CINEMA_24_CS;
parameters->max_comp_size = OPJ_CINEMA_24_COMP;
deprecated_used = OPJ_TRUE;
break;
case OPJ_CINEMA2K_48:
parameters->rsiz = OPJ_PROFILE_CINEMA_2K;
parameters->max_cs_size = OPJ_CINEMA_48_CS;
parameters->max_comp_size = OPJ_CINEMA_48_COMP;
deprecated_used = OPJ_TRUE;
break;
case OPJ_CINEMA4K_24:
parameters->rsiz = OPJ_PROFILE_CINEMA_4K;
parameters->max_cs_size = OPJ_CINEMA_24_CS;
parameters->max_comp_size = OPJ_CINEMA_24_COMP;
deprecated_used = OPJ_TRUE;
break;
case OPJ_OFF:
default:
break;
}
switch (parameters->cp_rsiz) {
case OPJ_CINEMA2K:
parameters->rsiz = OPJ_PROFILE_CINEMA_2K;
deprecated_used = OPJ_TRUE;
break;
case OPJ_CINEMA4K:
parameters->rsiz = OPJ_PROFILE_CINEMA_4K;
deprecated_used = OPJ_TRUE;
break;
case OPJ_MCT:
parameters->rsiz = OPJ_PROFILE_PART2 | OPJ_EXTENSION_MCT;
deprecated_used = OPJ_TRUE;
case OPJ_STD_RSIZ:
default:
break;
}
if (deprecated_used) {
opj_event_msg(p_manager, EVT_WARNING,
"Deprecated fields cp_cinema or cp_rsiz are used\n"
"Please consider using only the rsiz field\n"
"See openjpeg.h documentation for more details\n");
}
}
/* If no explicit layers are provided, use lossless settings */
if (parameters->tcp_numlayers == 0) {
parameters->tcp_numlayers = 1;
parameters->cp_disto_alloc = 1;
parameters->tcp_rates[0] = 0;
}
/* see if max_codestream_size does limit input rate */
if (parameters->max_cs_size <= 0) {
if (parameters->tcp_rates[parameters->tcp_numlayers - 1] > 0) {
OPJ_FLOAT32 temp_size;
temp_size = (OPJ_FLOAT32)(image->numcomps * image->comps[0].w *
image->comps[0].h * image->comps[0].prec) /
(parameters->tcp_rates[parameters->tcp_numlayers - 1] * 8 *
(OPJ_FLOAT32)image->comps[0].dx * (OPJ_FLOAT32)image->comps[0].dy);
parameters->max_cs_size = (int) floor(temp_size);
} else {
parameters->max_cs_size = 0;
}
} else {
OPJ_FLOAT32 temp_rate;
OPJ_BOOL cap = OPJ_FALSE;
temp_rate = (OPJ_FLOAT32)(image->numcomps * image->comps[0].w *
image->comps[0].h * image->comps[0].prec) /
(OPJ_FLOAT32)(((OPJ_UINT32)parameters->max_cs_size) * 8 * image->comps[0].dx *
image->comps[0].dy);
for (i = 0; i < (OPJ_UINT32) parameters->tcp_numlayers; i++) {
if (parameters->tcp_rates[i] < temp_rate) {
parameters->tcp_rates[i] = temp_rate;
cap = OPJ_TRUE;
}
}
if (cap) {
opj_event_msg(p_manager, EVT_WARNING,
"The desired maximum codestream size has limited\n"
"at least one of the desired quality layers\n");
}
}
/* Manage profiles and applications and set RSIZ */
/* set cinema parameters if required */
if (OPJ_IS_CINEMA(parameters->rsiz)) {
if ((parameters->rsiz == OPJ_PROFILE_CINEMA_S2K)
|| (parameters->rsiz == OPJ_PROFILE_CINEMA_S4K)) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Scalable Digital Cinema profiles not yet supported\n");
parameters->rsiz = OPJ_PROFILE_NONE;
} else {
opj_j2k_set_cinema_parameters(parameters, image, p_manager);
if (!opj_j2k_is_cinema_compliant(image, parameters->rsiz, p_manager)) {
parameters->rsiz = OPJ_PROFILE_NONE;
}
}
} else if (OPJ_IS_STORAGE(parameters->rsiz)) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Long Term Storage profile not yet supported\n");
parameters->rsiz = OPJ_PROFILE_NONE;
} else if (OPJ_IS_BROADCAST(parameters->rsiz)) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Broadcast profiles not yet supported\n");
parameters->rsiz = OPJ_PROFILE_NONE;
} else if (OPJ_IS_IMF(parameters->rsiz)) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 IMF profiles not yet supported\n");
parameters->rsiz = OPJ_PROFILE_NONE;
} else if (OPJ_IS_PART2(parameters->rsiz)) {
if (parameters->rsiz == ((OPJ_PROFILE_PART2) | (OPJ_EXTENSION_NONE))) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Part-2 profile defined\n"
"but no Part-2 extension enabled.\n"
"Profile set to NONE.\n");
parameters->rsiz = OPJ_PROFILE_NONE;
} else if (parameters->rsiz != ((OPJ_PROFILE_PART2) | (OPJ_EXTENSION_MCT))) {
opj_event_msg(p_manager, EVT_WARNING,
"Unsupported Part-2 extension enabled\n"
"Profile set to NONE.\n");
parameters->rsiz = OPJ_PROFILE_NONE;
}
}
/*
copy user encoding parameters
*/
cp->m_specific_param.m_enc.m_max_comp_size = (OPJ_UINT32)
parameters->max_comp_size;
cp->rsiz = parameters->rsiz;
cp->m_specific_param.m_enc.m_disto_alloc = (OPJ_UINT32)
parameters->cp_disto_alloc & 1u;
cp->m_specific_param.m_enc.m_fixed_alloc = (OPJ_UINT32)
parameters->cp_fixed_alloc & 1u;
cp->m_specific_param.m_enc.m_fixed_quality = (OPJ_UINT32)
parameters->cp_fixed_quality & 1u;
/* mod fixed_quality */
if (parameters->cp_fixed_alloc && parameters->cp_matrice) {
size_t array_size = (size_t)parameters->tcp_numlayers *
(size_t)parameters->numresolution * 3 * sizeof(OPJ_INT32);
cp->m_specific_param.m_enc.m_matrice = (OPJ_INT32 *) opj_malloc(array_size);
if (!cp->m_specific_param.m_enc.m_matrice) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate copy of user encoding parameters matrix \n");
return OPJ_FALSE;
}
memcpy(cp->m_specific_param.m_enc.m_matrice, parameters->cp_matrice,
array_size);
}
/* tiles */
cp->tdx = (OPJ_UINT32)parameters->cp_tdx;
cp->tdy = (OPJ_UINT32)parameters->cp_tdy;
/* tile offset */
cp->tx0 = (OPJ_UINT32)parameters->cp_tx0;
cp->ty0 = (OPJ_UINT32)parameters->cp_ty0;
/* comment string */
if (parameters->cp_comment) {
cp->comment = (char*)opj_malloc(strlen(parameters->cp_comment) + 1U);
if (!cp->comment) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate copy of comment string\n");
return OPJ_FALSE;
}
strcpy(cp->comment, parameters->cp_comment);
} else {
/* Create default comment for codestream */
const char comment[] = "Created by OpenJPEG version ";
const size_t clen = strlen(comment);
const char *version = opj_version();
/* UniPG>> */
#ifdef USE_JPWL
cp->comment = (char*)opj_malloc(clen + strlen(version) + 11);
if (!cp->comment) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate comment string\n");
return OPJ_FALSE;
}
sprintf(cp->comment, "%s%s with JPWL", comment, version);
#else
cp->comment = (char*)opj_malloc(clen + strlen(version) + 1);
if (!cp->comment) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate comment string\n");
return OPJ_FALSE;
}
sprintf(cp->comment, "%s%s", comment, version);
#endif
/* <<UniPG */
}
/*
calculate other encoding parameters
*/
if (parameters->tile_size_on) {
cp->tw = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)(image->x1 - cp->tx0),
(OPJ_INT32)cp->tdx);
cp->th = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)(image->y1 - cp->ty0),
(OPJ_INT32)cp->tdy);
} else {
cp->tdx = image->x1 - cp->tx0;
cp->tdy = image->y1 - cp->ty0;
}
if (parameters->tp_on) {
cp->m_specific_param.m_enc.m_tp_flag = (OPJ_BYTE)parameters->tp_flag;
cp->m_specific_param.m_enc.m_tp_on = 1;
}
#ifdef USE_JPWL
/*
calculate JPWL encoding parameters
*/
if (parameters->jpwl_epc_on) {
OPJ_INT32 i;
/* set JPWL on */
cp->epc_on = OPJ_TRUE;
cp->info_on = OPJ_FALSE; /* no informative technique */
/* set EPB on */
if ((parameters->jpwl_hprot_MH > 0) || (parameters->jpwl_hprot_TPH[0] > 0)) {
cp->epb_on = OPJ_TRUE;
cp->hprot_MH = parameters->jpwl_hprot_MH;
for (i = 0; i < JPWL_MAX_NO_TILESPECS; i++) {
cp->hprot_TPH_tileno[i] = parameters->jpwl_hprot_TPH_tileno[i];
cp->hprot_TPH[i] = parameters->jpwl_hprot_TPH[i];
}
/* if tile specs are not specified, copy MH specs */
if (cp->hprot_TPH[0] == -1) {
cp->hprot_TPH_tileno[0] = 0;
cp->hprot_TPH[0] = parameters->jpwl_hprot_MH;
}
for (i = 0; i < JPWL_MAX_NO_PACKSPECS; i++) {
cp->pprot_tileno[i] = parameters->jpwl_pprot_tileno[i];
cp->pprot_packno[i] = parameters->jpwl_pprot_packno[i];
cp->pprot[i] = parameters->jpwl_pprot[i];
}
}
/* set ESD writing */
if ((parameters->jpwl_sens_size == 1) || (parameters->jpwl_sens_size == 2)) {
cp->esd_on = OPJ_TRUE;
cp->sens_size = parameters->jpwl_sens_size;
cp->sens_addr = parameters->jpwl_sens_addr;
cp->sens_range = parameters->jpwl_sens_range;
cp->sens_MH = parameters->jpwl_sens_MH;
for (i = 0; i < JPWL_MAX_NO_TILESPECS; i++) {
cp->sens_TPH_tileno[i] = parameters->jpwl_sens_TPH_tileno[i];
cp->sens_TPH[i] = parameters->jpwl_sens_TPH[i];
}
}
/* always set RED writing to false: we are at the encoder */
cp->red_on = OPJ_FALSE;
} else {
cp->epc_on = OPJ_FALSE;
}
#endif /* USE_JPWL */
/* initialize the mutiple tiles */
/* ---------------------------- */
cp->tcps = (opj_tcp_t*) opj_calloc(cp->tw * cp->th, sizeof(opj_tcp_t));
if (!cp->tcps) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate tile coding parameters\n");
return OPJ_FALSE;
}
if (parameters->numpocs) {
/* initialisation of POC */
opj_j2k_check_poc_val(parameters->POC, parameters->numpocs,
(OPJ_UINT32)parameters->numresolution, image->numcomps,
(OPJ_UINT32)parameters->tcp_numlayers, p_manager);
/* TODO MSD use the return value*/
}
for (tileno = 0; tileno < cp->tw * cp->th; tileno++) {
opj_tcp_t *tcp = &cp->tcps[tileno];
tcp->numlayers = (OPJ_UINT32)parameters->tcp_numlayers;
for (j = 0; j < tcp->numlayers; j++) {
if (OPJ_IS_CINEMA(cp->rsiz)) {
if (cp->m_specific_param.m_enc.m_fixed_quality) {
tcp->distoratio[j] = parameters->tcp_distoratio[j];
}
tcp->rates[j] = parameters->tcp_rates[j];
} else {
if (cp->m_specific_param.m_enc.m_fixed_quality) { /* add fixed_quality */
tcp->distoratio[j] = parameters->tcp_distoratio[j];
} else {
tcp->rates[j] = parameters->tcp_rates[j];
}
}
}
tcp->csty = (OPJ_UINT32)parameters->csty;
tcp->prg = parameters->prog_order;
tcp->mct = (OPJ_UINT32)parameters->tcp_mct;
numpocs_tile = 0;
tcp->POC = 0;
if (parameters->numpocs) {
/* initialisation of POC */
tcp->POC = 1;
for (i = 0; i < parameters->numpocs; i++) {
if (tileno + 1 == parameters->POC[i].tile) {
opj_poc_t *tcp_poc = &tcp->pocs[numpocs_tile];
tcp_poc->resno0 = parameters->POC[numpocs_tile].resno0;
tcp_poc->compno0 = parameters->POC[numpocs_tile].compno0;
tcp_poc->layno1 = parameters->POC[numpocs_tile].layno1;
tcp_poc->resno1 = parameters->POC[numpocs_tile].resno1;
tcp_poc->compno1 = parameters->POC[numpocs_tile].compno1;
tcp_poc->prg1 = parameters->POC[numpocs_tile].prg1;
tcp_poc->tile = parameters->POC[numpocs_tile].tile;
numpocs_tile++;
}
}
tcp->numpocs = numpocs_tile - 1 ;
} else {
tcp->numpocs = 0;
}
tcp->tccps = (opj_tccp_t*) opj_calloc(image->numcomps, sizeof(opj_tccp_t));
if (!tcp->tccps) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate tile component coding parameters\n");
return OPJ_FALSE;
}
if (parameters->mct_data) {
OPJ_UINT32 lMctSize = image->numcomps * image->numcomps * (OPJ_UINT32)sizeof(
OPJ_FLOAT32);
OPJ_FLOAT32 * lTmpBuf = (OPJ_FLOAT32*)opj_malloc(lMctSize);
OPJ_INT32 * l_dc_shift = (OPJ_INT32 *)((OPJ_BYTE *) parameters->mct_data +
lMctSize);
if (!lTmpBuf) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate temp buffer\n");
return OPJ_FALSE;
}
tcp->mct = 2;
tcp->m_mct_coding_matrix = (OPJ_FLOAT32*)opj_malloc(lMctSize);
if (! tcp->m_mct_coding_matrix) {
opj_free(lTmpBuf);
lTmpBuf = NULL;
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate encoder MCT coding matrix \n");
return OPJ_FALSE;
}
memcpy(tcp->m_mct_coding_matrix, parameters->mct_data, lMctSize);
memcpy(lTmpBuf, parameters->mct_data, lMctSize);
tcp->m_mct_decoding_matrix = (OPJ_FLOAT32*)opj_malloc(lMctSize);
if (! tcp->m_mct_decoding_matrix) {
opj_free(lTmpBuf);
lTmpBuf = NULL;
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate encoder MCT decoding matrix \n");
return OPJ_FALSE;
}
if (opj_matrix_inversion_f(lTmpBuf, (tcp->m_mct_decoding_matrix),
image->numcomps) == OPJ_FALSE) {
opj_free(lTmpBuf);
lTmpBuf = NULL;
opj_event_msg(p_manager, EVT_ERROR,
"Failed to inverse encoder MCT decoding matrix \n");
return OPJ_FALSE;
}
tcp->mct_norms = (OPJ_FLOAT64*)
opj_malloc(image->numcomps * sizeof(OPJ_FLOAT64));
if (! tcp->mct_norms) {
opj_free(lTmpBuf);
lTmpBuf = NULL;
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate encoder MCT norms \n");
return OPJ_FALSE;
}
opj_calculate_norms(tcp->mct_norms, image->numcomps,
tcp->m_mct_decoding_matrix);
opj_free(lTmpBuf);
for (i = 0; i < image->numcomps; i++) {
opj_tccp_t *tccp = &tcp->tccps[i];
tccp->m_dc_level_shift = l_dc_shift[i];
}
if (opj_j2k_setup_mct_encoding(tcp, image) == OPJ_FALSE) {
/* free will be handled by opj_j2k_destroy */
opj_event_msg(p_manager, EVT_ERROR, "Failed to setup j2k mct encoding\n");
return OPJ_FALSE;
}
} else {
if (tcp->mct == 1 && image->numcomps >= 3) { /* RGB->YCC MCT is enabled */
if ((image->comps[0].dx != image->comps[1].dx) ||
(image->comps[0].dx != image->comps[2].dx) ||
(image->comps[0].dy != image->comps[1].dy) ||
(image->comps[0].dy != image->comps[2].dy)) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot perform MCT on components with different sizes. Disabling MCT.\n");
tcp->mct = 0;
}
}
for (i = 0; i < image->numcomps; i++) {
opj_tccp_t *tccp = &tcp->tccps[i];
opj_image_comp_t * l_comp = &(image->comps[i]);
if (! l_comp->sgnd) {
tccp->m_dc_level_shift = 1 << (l_comp->prec - 1);
}
}
}
for (i = 0; i < image->numcomps; i++) {
opj_tccp_t *tccp = &tcp->tccps[i];
tccp->csty = parameters->csty &
0x01; /* 0 => one precinct || 1 => custom precinct */
tccp->numresolutions = (OPJ_UINT32)parameters->numresolution;
tccp->cblkw = (OPJ_UINT32)opj_int_floorlog2(parameters->cblockw_init);
tccp->cblkh = (OPJ_UINT32)opj_int_floorlog2(parameters->cblockh_init);
tccp->cblksty = (OPJ_UINT32)parameters->mode;
tccp->qmfbid = parameters->irreversible ? 0 : 1;
tccp->qntsty = parameters->irreversible ? J2K_CCP_QNTSTY_SEQNT :
J2K_CCP_QNTSTY_NOQNT;
tccp->numgbits = 2;
if ((OPJ_INT32)i == parameters->roi_compno) {
tccp->roishift = parameters->roi_shift;
} else {
tccp->roishift = 0;
}
if (parameters->csty & J2K_CCP_CSTY_PRT) {
OPJ_INT32 p = 0, it_res;
assert(tccp->numresolutions > 0);
for (it_res = (OPJ_INT32)tccp->numresolutions - 1; it_res >= 0; it_res--) {
if (p < parameters->res_spec) {
if (parameters->prcw_init[p] < 1) {
tccp->prcw[it_res] = 1;
} else {
tccp->prcw[it_res] = (OPJ_UINT32)opj_int_floorlog2(parameters->prcw_init[p]);
}
if (parameters->prch_init[p] < 1) {
tccp->prch[it_res] = 1;
} else {
tccp->prch[it_res] = (OPJ_UINT32)opj_int_floorlog2(parameters->prch_init[p]);
}
} else {
OPJ_INT32 res_spec = parameters->res_spec;
OPJ_INT32 size_prcw = 0;
OPJ_INT32 size_prch = 0;
assert(res_spec > 0); /* issue 189 */
size_prcw = parameters->prcw_init[res_spec - 1] >> (p - (res_spec - 1));
size_prch = parameters->prch_init[res_spec - 1] >> (p - (res_spec - 1));
if (size_prcw < 1) {
tccp->prcw[it_res] = 1;
} else {
tccp->prcw[it_res] = (OPJ_UINT32)opj_int_floorlog2(size_prcw);
}
if (size_prch < 1) {
tccp->prch[it_res] = 1;
} else {
tccp->prch[it_res] = (OPJ_UINT32)opj_int_floorlog2(size_prch);
}
}
p++;
/*printf("\nsize precinct for level %d : %d,%d\n", it_res,tccp->prcw[it_res], tccp->prch[it_res]); */
} /*end for*/
} else {
for (j = 0; j < tccp->numresolutions; j++) {
tccp->prcw[j] = 15;
tccp->prch[j] = 15;
}
}
opj_dwt_calc_explicit_stepsizes(tccp, image->comps[i].prec);
}
}
if (parameters->mct_data) {
opj_free(parameters->mct_data);
parameters->mct_data = 00;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_add_mhmarker(opj_codestream_index_t *cstr_index,
OPJ_UINT32 type, OPJ_OFF_T pos, OPJ_UINT32 len)
{
assert(cstr_index != 00);
/* expand the list? */
if ((cstr_index->marknum + 1) > cstr_index->maxmarknum) {
opj_marker_info_t *new_marker;
cstr_index->maxmarknum = (OPJ_UINT32)(100 + (OPJ_FLOAT32)
cstr_index->maxmarknum);
new_marker = (opj_marker_info_t *) opj_realloc(cstr_index->marker,
cstr_index->maxmarknum * sizeof(opj_marker_info_t));
if (! new_marker) {
opj_free(cstr_index->marker);
cstr_index->marker = NULL;
cstr_index->maxmarknum = 0;
cstr_index->marknum = 0;
/* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add mh marker\n"); */
return OPJ_FALSE;
}
cstr_index->marker = new_marker;
}
/* add the marker */
cstr_index->marker[cstr_index->marknum].type = (OPJ_UINT16)type;
cstr_index->marker[cstr_index->marknum].pos = (OPJ_INT32)pos;
cstr_index->marker[cstr_index->marknum].len = (OPJ_INT32)len;
cstr_index->marknum++;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_add_tlmarker(OPJ_UINT32 tileno,
opj_codestream_index_t *cstr_index, OPJ_UINT32 type, OPJ_OFF_T pos,
OPJ_UINT32 len)
{
assert(cstr_index != 00);
assert(cstr_index->tile_index != 00);
/* expand the list? */
if ((cstr_index->tile_index[tileno].marknum + 1) >
cstr_index->tile_index[tileno].maxmarknum) {
opj_marker_info_t *new_marker;
cstr_index->tile_index[tileno].maxmarknum = (OPJ_UINT32)(100 +
(OPJ_FLOAT32) cstr_index->tile_index[tileno].maxmarknum);
new_marker = (opj_marker_info_t *) opj_realloc(
cstr_index->tile_index[tileno].marker,
cstr_index->tile_index[tileno].maxmarknum * sizeof(opj_marker_info_t));
if (! new_marker) {
opj_free(cstr_index->tile_index[tileno].marker);
cstr_index->tile_index[tileno].marker = NULL;
cstr_index->tile_index[tileno].maxmarknum = 0;
cstr_index->tile_index[tileno].marknum = 0;
/* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add tl marker\n"); */
return OPJ_FALSE;
}
cstr_index->tile_index[tileno].marker = new_marker;
}
/* add the marker */
cstr_index->tile_index[tileno].marker[cstr_index->tile_index[tileno].marknum].type
= (OPJ_UINT16)type;
cstr_index->tile_index[tileno].marker[cstr_index->tile_index[tileno].marknum].pos
= (OPJ_INT32)pos;
cstr_index->tile_index[tileno].marker[cstr_index->tile_index[tileno].marknum].len
= (OPJ_INT32)len;
cstr_index->tile_index[tileno].marknum++;
if (type == J2K_MS_SOT) {
OPJ_UINT32 l_current_tile_part = cstr_index->tile_index[tileno].current_tpsno;
if (cstr_index->tile_index[tileno].tp_index) {
cstr_index->tile_index[tileno].tp_index[l_current_tile_part].start_pos = pos;
}
}
return OPJ_TRUE;
}
/*
* -----------------------------------------------------------------------
* -----------------------------------------------------------------------
* -----------------------------------------------------------------------
*/
OPJ_BOOL opj_j2k_end_decompress(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
(void)p_j2k;
(void)p_stream;
(void)p_manager;
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_read_header(opj_stream_private_t *p_stream,
opj_j2k_t* p_j2k,
opj_image_t** p_image,
opj_event_mgr_t* p_manager)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
/* create an empty image header */
p_j2k->m_private_image = opj_image_create0();
if (! p_j2k->m_private_image) {
return OPJ_FALSE;
}
/* customization of the validation */
if (! opj_j2k_setup_decoding_validation(p_j2k, p_manager)) {
opj_image_destroy(p_j2k->m_private_image);
p_j2k->m_private_image = NULL;
return OPJ_FALSE;
}
/* validation of the parameters codec */
if (! opj_j2k_exec(p_j2k, p_j2k->m_validation_list, p_stream, p_manager)) {
opj_image_destroy(p_j2k->m_private_image);
p_j2k->m_private_image = NULL;
return OPJ_FALSE;
}
/* customization of the encoding */
if (! opj_j2k_setup_header_reading(p_j2k, p_manager)) {
opj_image_destroy(p_j2k->m_private_image);
p_j2k->m_private_image = NULL;
return OPJ_FALSE;
}
/* read header */
if (! opj_j2k_exec(p_j2k, p_j2k->m_procedure_list, p_stream, p_manager)) {
opj_image_destroy(p_j2k->m_private_image);
p_j2k->m_private_image = NULL;
return OPJ_FALSE;
}
*p_image = opj_image_create0();
if (!(*p_image)) {
return OPJ_FALSE;
}
/* Copy codestream image information to the output image */
opj_copy_image_header(p_j2k->m_private_image, *p_image);
/*Allocate and initialize some elements of codestrem index*/
if (!opj_j2k_allocate_tile_element_cstr_index(p_j2k)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_setup_header_reading(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager)
{
/* preconditions*/
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_read_header_procedure, p_manager)) {
return OPJ_FALSE;
}
/* DEVELOPER CORNER, add your custom procedures */
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_copy_default_tcp_and_create_tcd, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_setup_decoding_validation(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager)
{
/* preconditions*/
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list,
(opj_procedure)opj_j2k_build_decoder, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list,
(opj_procedure)opj_j2k_decoding_validation, p_manager)) {
return OPJ_FALSE;
}
/* DEVELOPER CORNER, add your custom validation procedure */
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_mct_validation(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_BOOL l_is_valid = OPJ_TRUE;
OPJ_UINT32 i, j;
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_stream);
OPJ_UNUSED(p_manager);
if ((p_j2k->m_cp.rsiz & 0x8200) == 0x8200) {
OPJ_UINT32 l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
opj_tcp_t * l_tcp = p_j2k->m_cp.tcps;
for (i = 0; i < l_nb_tiles; ++i) {
if (l_tcp->mct == 2) {
opj_tccp_t * l_tccp = l_tcp->tccps;
l_is_valid &= (l_tcp->m_mct_coding_matrix != 00);
for (j = 0; j < p_j2k->m_private_image->numcomps; ++j) {
l_is_valid &= !(l_tccp->qmfbid & 1);
++l_tccp;
}
}
++l_tcp;
}
}
return l_is_valid;
}
OPJ_BOOL opj_j2k_setup_mct_encoding(opj_tcp_t * p_tcp, opj_image_t * p_image)
{
OPJ_UINT32 i;
OPJ_UINT32 l_indix = 1;
opj_mct_data_t * l_mct_deco_data = 00, * l_mct_offset_data = 00;
opj_simple_mcc_decorrelation_data_t * l_mcc_data;
OPJ_UINT32 l_mct_size, l_nb_elem;
OPJ_FLOAT32 * l_data, * l_current_data;
opj_tccp_t * l_tccp;
/* preconditions */
assert(p_tcp != 00);
if (p_tcp->mct != 2) {
return OPJ_TRUE;
}
if (p_tcp->m_mct_decoding_matrix) {
if (p_tcp->m_nb_mct_records == p_tcp->m_nb_max_mct_records) {
opj_mct_data_t *new_mct_records;
p_tcp->m_nb_max_mct_records += OPJ_J2K_MCT_DEFAULT_NB_RECORDS;
new_mct_records = (opj_mct_data_t *) opj_realloc(p_tcp->m_mct_records,
p_tcp->m_nb_max_mct_records * sizeof(opj_mct_data_t));
if (! new_mct_records) {
opj_free(p_tcp->m_mct_records);
p_tcp->m_mct_records = NULL;
p_tcp->m_nb_max_mct_records = 0;
p_tcp->m_nb_mct_records = 0;
/* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to setup mct encoding\n"); */
return OPJ_FALSE;
}
p_tcp->m_mct_records = new_mct_records;
l_mct_deco_data = p_tcp->m_mct_records + p_tcp->m_nb_mct_records;
memset(l_mct_deco_data, 0,
(p_tcp->m_nb_max_mct_records - p_tcp->m_nb_mct_records) * sizeof(
opj_mct_data_t));
}
l_mct_deco_data = p_tcp->m_mct_records + p_tcp->m_nb_mct_records;
if (l_mct_deco_data->m_data) {
opj_free(l_mct_deco_data->m_data);
l_mct_deco_data->m_data = 00;
}
l_mct_deco_data->m_index = l_indix++;
l_mct_deco_data->m_array_type = MCT_TYPE_DECORRELATION;
l_mct_deco_data->m_element_type = MCT_TYPE_FLOAT;
l_nb_elem = p_image->numcomps * p_image->numcomps;
l_mct_size = l_nb_elem * MCT_ELEMENT_SIZE[l_mct_deco_data->m_element_type];
l_mct_deco_data->m_data = (OPJ_BYTE*)opj_malloc(l_mct_size);
if (! l_mct_deco_data->m_data) {
return OPJ_FALSE;
}
j2k_mct_write_functions_from_float[l_mct_deco_data->m_element_type](
p_tcp->m_mct_decoding_matrix, l_mct_deco_data->m_data, l_nb_elem);
l_mct_deco_data->m_data_size = l_mct_size;
++p_tcp->m_nb_mct_records;
}
if (p_tcp->m_nb_mct_records == p_tcp->m_nb_max_mct_records) {
opj_mct_data_t *new_mct_records;
p_tcp->m_nb_max_mct_records += OPJ_J2K_MCT_DEFAULT_NB_RECORDS;
new_mct_records = (opj_mct_data_t *) opj_realloc(p_tcp->m_mct_records,
p_tcp->m_nb_max_mct_records * sizeof(opj_mct_data_t));
if (! new_mct_records) {
opj_free(p_tcp->m_mct_records);
p_tcp->m_mct_records = NULL;
p_tcp->m_nb_max_mct_records = 0;
p_tcp->m_nb_mct_records = 0;
/* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to setup mct encoding\n"); */
return OPJ_FALSE;
}
p_tcp->m_mct_records = new_mct_records;
l_mct_offset_data = p_tcp->m_mct_records + p_tcp->m_nb_mct_records;
memset(l_mct_offset_data, 0,
(p_tcp->m_nb_max_mct_records - p_tcp->m_nb_mct_records) * sizeof(
opj_mct_data_t));
if (l_mct_deco_data) {
l_mct_deco_data = l_mct_offset_data - 1;
}
}
l_mct_offset_data = p_tcp->m_mct_records + p_tcp->m_nb_mct_records;
if (l_mct_offset_data->m_data) {
opj_free(l_mct_offset_data->m_data);
l_mct_offset_data->m_data = 00;
}
l_mct_offset_data->m_index = l_indix++;
l_mct_offset_data->m_array_type = MCT_TYPE_OFFSET;
l_mct_offset_data->m_element_type = MCT_TYPE_FLOAT;
l_nb_elem = p_image->numcomps;
l_mct_size = l_nb_elem * MCT_ELEMENT_SIZE[l_mct_offset_data->m_element_type];
l_mct_offset_data->m_data = (OPJ_BYTE*)opj_malloc(l_mct_size);
if (! l_mct_offset_data->m_data) {
return OPJ_FALSE;
}
l_data = (OPJ_FLOAT32*)opj_malloc(l_nb_elem * sizeof(OPJ_FLOAT32));
if (! l_data) {
opj_free(l_mct_offset_data->m_data);
l_mct_offset_data->m_data = 00;
return OPJ_FALSE;
}
l_tccp = p_tcp->tccps;
l_current_data = l_data;
for (i = 0; i < l_nb_elem; ++i) {
*(l_current_data++) = (OPJ_FLOAT32)(l_tccp->m_dc_level_shift);
++l_tccp;
}
j2k_mct_write_functions_from_float[l_mct_offset_data->m_element_type](l_data,
l_mct_offset_data->m_data, l_nb_elem);
opj_free(l_data);
l_mct_offset_data->m_data_size = l_mct_size;
++p_tcp->m_nb_mct_records;
if (p_tcp->m_nb_mcc_records == p_tcp->m_nb_max_mcc_records) {
opj_simple_mcc_decorrelation_data_t *new_mcc_records;
p_tcp->m_nb_max_mcc_records += OPJ_J2K_MCT_DEFAULT_NB_RECORDS;
new_mcc_records = (opj_simple_mcc_decorrelation_data_t *) opj_realloc(
p_tcp->m_mcc_records, p_tcp->m_nb_max_mcc_records * sizeof(
opj_simple_mcc_decorrelation_data_t));
if (! new_mcc_records) {
opj_free(p_tcp->m_mcc_records);
p_tcp->m_mcc_records = NULL;
p_tcp->m_nb_max_mcc_records = 0;
p_tcp->m_nb_mcc_records = 0;
/* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to setup mct encoding\n"); */
return OPJ_FALSE;
}
p_tcp->m_mcc_records = new_mcc_records;
l_mcc_data = p_tcp->m_mcc_records + p_tcp->m_nb_mcc_records;
memset(l_mcc_data, 0, (p_tcp->m_nb_max_mcc_records - p_tcp->m_nb_mcc_records) *
sizeof(opj_simple_mcc_decorrelation_data_t));
}
l_mcc_data = p_tcp->m_mcc_records + p_tcp->m_nb_mcc_records;
l_mcc_data->m_decorrelation_array = l_mct_deco_data;
l_mcc_data->m_is_irreversible = 1;
l_mcc_data->m_nb_comps = p_image->numcomps;
l_mcc_data->m_index = l_indix++;
l_mcc_data->m_offset_array = l_mct_offset_data;
++p_tcp->m_nb_mcc_records;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_build_decoder(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
/* add here initialization of cp
copy paste of setup_decoder */
(void)p_j2k;
(void)p_stream;
(void)p_manager;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_build_encoder(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
/* add here initialization of cp
copy paste of setup_encoder */
(void)p_j2k;
(void)p_stream;
(void)p_manager;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_encoding_validation(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_BOOL l_is_valid = OPJ_TRUE;
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_stream);
/* STATE checking */
/* make sure the state is at 0 */
l_is_valid &= (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_NONE);
/* POINTER validation */
/* make sure a p_j2k codec is present */
l_is_valid &= (p_j2k->m_procedure_list != 00);
/* make sure a validation list is present */
l_is_valid &= (p_j2k->m_validation_list != 00);
/* ISO 15444-1:2004 states between 1 & 33 (0 -> 32) */
/* 33 (32) would always fail the check below (if a cast to 64bits was done) */
/* FIXME Shall we change OPJ_J2K_MAXRLVLS to 32 ? */
if ((p_j2k->m_cp.tcps->tccps->numresolutions <= 0) ||
(p_j2k->m_cp.tcps->tccps->numresolutions > 32)) {
opj_event_msg(p_manager, EVT_ERROR,
"Number of resolutions is too high in comparison to the size of tiles\n");
return OPJ_FALSE;
}
if ((p_j2k->m_cp.tdx) < (OPJ_UINT32)(1 <<
(p_j2k->m_cp.tcps->tccps->numresolutions - 1U))) {
opj_event_msg(p_manager, EVT_ERROR,
"Number of resolutions is too high in comparison to the size of tiles\n");
return OPJ_FALSE;
}
if ((p_j2k->m_cp.tdy) < (OPJ_UINT32)(1 <<
(p_j2k->m_cp.tcps->tccps->numresolutions - 1U))) {
opj_event_msg(p_manager, EVT_ERROR,
"Number of resolutions is too high in comparison to the size of tiles\n");
return OPJ_FALSE;
}
/* PARAMETER VALIDATION */
return l_is_valid;
}
static OPJ_BOOL opj_j2k_decoding_validation(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_BOOL l_is_valid = OPJ_TRUE;
/* preconditions*/
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_stream);
OPJ_UNUSED(p_manager);
/* STATE checking */
/* make sure the state is at 0 */
#ifdef TODO_MSD
l_is_valid &= (p_j2k->m_specific_param.m_decoder.m_state == J2K_DEC_STATE_NONE);
#endif
l_is_valid &= (p_j2k->m_specific_param.m_decoder.m_state == 0x0000);
/* POINTER validation */
/* make sure a p_j2k codec is present */
/* make sure a procedure list is present */
l_is_valid &= (p_j2k->m_procedure_list != 00);
/* make sure a validation list is present */
l_is_valid &= (p_j2k->m_validation_list != 00);
/* PARAMETER VALIDATION */
return l_is_valid;
}
static OPJ_BOOL opj_j2k_read_header_procedure(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 l_current_marker;
OPJ_UINT32 l_marker_size;
const opj_dec_memory_marker_handler_t * l_marker_handler = 00;
OPJ_BOOL l_has_siz = 0;
OPJ_BOOL l_has_cod = 0;
OPJ_BOOL l_has_qcd = 0;
/* preconditions */
assert(p_stream != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
/* We enter in the main header */
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_MHSOC;
/* Try to read the SOC marker, the codestream must begin with SOC marker */
if (! opj_j2k_read_soc(p_j2k, p_stream, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Expected a SOC marker \n");
return OPJ_FALSE;
}
/* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* Read 2 bytes as the new marker ID */
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,
&l_current_marker, 2);
/* Try to read until the SOT is detected */
while (l_current_marker != J2K_MS_SOT) {
/* Check if the current marker ID is valid */
if (l_current_marker < 0xff00) {
opj_event_msg(p_manager, EVT_ERROR,
"A marker ID was expected (0xff--) instead of %.8x\n", l_current_marker);
return OPJ_FALSE;
}
/* Get the marker handler from the marker ID */
l_marker_handler = opj_j2k_get_marker_handler(l_current_marker);
/* Manage case where marker is unknown */
if (l_marker_handler->id == J2K_MS_UNK) {
if (! opj_j2k_read_unk(p_j2k, p_stream, &l_current_marker, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR,
"Unknow marker have been detected and generated error.\n");
return OPJ_FALSE;
}
if (l_current_marker == J2K_MS_SOT) {
break; /* SOT marker is detected main header is completely read */
} else { /* Get the marker handler from the marker ID */
l_marker_handler = opj_j2k_get_marker_handler(l_current_marker);
}
}
if (l_marker_handler->id == J2K_MS_SIZ) {
/* Mark required SIZ marker as found */
l_has_siz = 1;
}
if (l_marker_handler->id == J2K_MS_COD) {
/* Mark required COD marker as found */
l_has_cod = 1;
}
if (l_marker_handler->id == J2K_MS_QCD) {
/* Mark required QCD marker as found */
l_has_qcd = 1;
}
/* Check if the marker is known and if it is the right place to find it */
if (!(p_j2k->m_specific_param.m_decoder.m_state & l_marker_handler->states)) {
opj_event_msg(p_manager, EVT_ERROR,
"Marker is not compliant with its position\n");
return OPJ_FALSE;
}
/* Try to read 2 bytes (the marker size) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* read 2 bytes as the marker size */
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data, &l_marker_size,
2);
if (l_marker_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Invalid marker size\n");
return OPJ_FALSE;
}
l_marker_size -= 2; /* Subtract the size of the marker ID already read */
/* Check if the marker size is compatible with the header data size */
if (l_marker_size > p_j2k->m_specific_param.m_decoder.m_header_data_size) {
OPJ_BYTE *new_header_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size);
if (! new_header_data) {
opj_free(p_j2k->m_specific_param.m_decoder.m_header_data);
p_j2k->m_specific_param.m_decoder.m_header_data = NULL;
p_j2k->m_specific_param.m_decoder.m_header_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read header\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_decoder.m_header_data = new_header_data;
p_j2k->m_specific_param.m_decoder.m_header_data_size = l_marker_size;
}
/* Try to read the rest of the marker segment from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size,
p_manager) != l_marker_size) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* Read the marker segment with the correct marker handler */
if (!(*(l_marker_handler->handler))(p_j2k,
p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR,
"Marker handler function failed to read the marker segment\n");
return OPJ_FALSE;
}
/* Add the marker to the codestream index*/
if (OPJ_FALSE == opj_j2k_add_mhmarker(
p_j2k->cstr_index,
l_marker_handler->id,
(OPJ_UINT32) opj_stream_tell(p_stream) - l_marker_size - 4,
l_marker_size + 4)) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add mh marker\n");
return OPJ_FALSE;
}
/* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* read 2 bytes as the new marker ID */
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,
&l_current_marker, 2);
}
if (l_has_siz == 0) {
opj_event_msg(p_manager, EVT_ERROR,
"required SIZ marker not found in main header\n");
return OPJ_FALSE;
}
if (l_has_cod == 0) {
opj_event_msg(p_manager, EVT_ERROR,
"required COD marker not found in main header\n");
return OPJ_FALSE;
}
if (l_has_qcd == 0) {
opj_event_msg(p_manager, EVT_ERROR,
"required QCD marker not found in main header\n");
return OPJ_FALSE;
}
if (! opj_j2k_merge_ppm(&(p_j2k->m_cp), p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Failed to merge PPM data\n");
return OPJ_FALSE;
}
opj_event_msg(p_manager, EVT_INFO, "Main header has been correctly decoded.\n");
/* Position of the last element if the main header */
p_j2k->cstr_index->main_head_end = (OPJ_UINT32) opj_stream_tell(p_stream) - 2;
/* Next step: read a tile-part header */
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPHSOT;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_exec(opj_j2k_t * p_j2k,
opj_procedure_list_t * p_procedure_list,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_BOOL(** l_procedure)(opj_j2k_t *, opj_stream_private_t *,
opj_event_mgr_t *) = 00;
OPJ_BOOL l_result = OPJ_TRUE;
OPJ_UINT32 l_nb_proc, i;
/* preconditions*/
assert(p_procedure_list != 00);
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
l_nb_proc = opj_procedure_list_get_nb_procedures(p_procedure_list);
l_procedure = (OPJ_BOOL(**)(opj_j2k_t *, opj_stream_private_t *,
opj_event_mgr_t *)) opj_procedure_list_get_first_procedure(p_procedure_list);
for (i = 0; i < l_nb_proc; ++i) {
l_result = l_result && ((*l_procedure)(p_j2k, p_stream, p_manager));
++l_procedure;
}
/* and clear the procedure list at the end.*/
opj_procedure_list_clear(p_procedure_list);
return l_result;
}
/* FIXME DOC*/
static OPJ_BOOL opj_j2k_copy_default_tcp_and_create_tcd(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
opj_tcp_t * l_tcp = 00;
opj_tcp_t * l_default_tcp = 00;
OPJ_UINT32 l_nb_tiles;
OPJ_UINT32 i, j;
opj_tccp_t *l_current_tccp = 00;
OPJ_UINT32 l_tccp_size;
OPJ_UINT32 l_mct_size;
opj_image_t * l_image;
OPJ_UINT32 l_mcc_records_size, l_mct_records_size;
opj_mct_data_t * l_src_mct_rec, *l_dest_mct_rec;
opj_simple_mcc_decorrelation_data_t * l_src_mcc_rec, *l_dest_mcc_rec;
OPJ_UINT32 l_offset;
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_stream);
l_image = p_j2k->m_private_image;
l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
l_tcp = p_j2k->m_cp.tcps;
l_tccp_size = l_image->numcomps * (OPJ_UINT32)sizeof(opj_tccp_t);
l_default_tcp = p_j2k->m_specific_param.m_decoder.m_default_tcp;
l_mct_size = l_image->numcomps * l_image->numcomps * (OPJ_UINT32)sizeof(
OPJ_FLOAT32);
/* For each tile */
for (i = 0; i < l_nb_tiles; ++i) {
/* keep the tile-compo coding parameters pointer of the current tile coding parameters*/
l_current_tccp = l_tcp->tccps;
/*Copy default coding parameters into the current tile coding parameters*/
memcpy(l_tcp, l_default_tcp, sizeof(opj_tcp_t));
/* Initialize some values of the current tile coding parameters*/
l_tcp->cod = 0;
l_tcp->ppt = 0;
l_tcp->ppt_data = 00;
l_tcp->m_current_tile_part_number = -1;
/* Remove memory not owned by this tile in case of early error return. */
l_tcp->m_mct_decoding_matrix = 00;
l_tcp->m_nb_max_mct_records = 0;
l_tcp->m_mct_records = 00;
l_tcp->m_nb_max_mcc_records = 0;
l_tcp->m_mcc_records = 00;
/* Reconnect the tile-compo coding parameters pointer to the current tile coding parameters*/
l_tcp->tccps = l_current_tccp;
/* Get the mct_decoding_matrix of the dflt_tile_cp and copy them into the current tile cp*/
if (l_default_tcp->m_mct_decoding_matrix) {
l_tcp->m_mct_decoding_matrix = (OPJ_FLOAT32*)opj_malloc(l_mct_size);
if (! l_tcp->m_mct_decoding_matrix) {
return OPJ_FALSE;
}
memcpy(l_tcp->m_mct_decoding_matrix, l_default_tcp->m_mct_decoding_matrix,
l_mct_size);
}
/* Get the mct_record of the dflt_tile_cp and copy them into the current tile cp*/
l_mct_records_size = l_default_tcp->m_nb_max_mct_records * (OPJ_UINT32)sizeof(
opj_mct_data_t);
l_tcp->m_mct_records = (opj_mct_data_t*)opj_malloc(l_mct_records_size);
if (! l_tcp->m_mct_records) {
return OPJ_FALSE;
}
memcpy(l_tcp->m_mct_records, l_default_tcp->m_mct_records, l_mct_records_size);
/* Copy the mct record data from dflt_tile_cp to the current tile*/
l_src_mct_rec = l_default_tcp->m_mct_records;
l_dest_mct_rec = l_tcp->m_mct_records;
for (j = 0; j < l_default_tcp->m_nb_mct_records; ++j) {
if (l_src_mct_rec->m_data) {
l_dest_mct_rec->m_data = (OPJ_BYTE*) opj_malloc(l_src_mct_rec->m_data_size);
if (! l_dest_mct_rec->m_data) {
return OPJ_FALSE;
}
memcpy(l_dest_mct_rec->m_data, l_src_mct_rec->m_data,
l_src_mct_rec->m_data_size);
}
++l_src_mct_rec;
++l_dest_mct_rec;
/* Update with each pass to free exactly what has been allocated on early return. */
l_tcp->m_nb_max_mct_records += 1;
}
/* Get the mcc_record of the dflt_tile_cp and copy them into the current tile cp*/
l_mcc_records_size = l_default_tcp->m_nb_max_mcc_records * (OPJ_UINT32)sizeof(
opj_simple_mcc_decorrelation_data_t);
l_tcp->m_mcc_records = (opj_simple_mcc_decorrelation_data_t*) opj_malloc(
l_mcc_records_size);
if (! l_tcp->m_mcc_records) {
return OPJ_FALSE;
}
memcpy(l_tcp->m_mcc_records, l_default_tcp->m_mcc_records, l_mcc_records_size);
l_tcp->m_nb_max_mcc_records = l_default_tcp->m_nb_max_mcc_records;
/* Copy the mcc record data from dflt_tile_cp to the current tile*/
l_src_mcc_rec = l_default_tcp->m_mcc_records;
l_dest_mcc_rec = l_tcp->m_mcc_records;
for (j = 0; j < l_default_tcp->m_nb_max_mcc_records; ++j) {
if (l_src_mcc_rec->m_decorrelation_array) {
l_offset = (OPJ_UINT32)(l_src_mcc_rec->m_decorrelation_array -
l_default_tcp->m_mct_records);
l_dest_mcc_rec->m_decorrelation_array = l_tcp->m_mct_records + l_offset;
}
if (l_src_mcc_rec->m_offset_array) {
l_offset = (OPJ_UINT32)(l_src_mcc_rec->m_offset_array -
l_default_tcp->m_mct_records);
l_dest_mcc_rec->m_offset_array = l_tcp->m_mct_records + l_offset;
}
++l_src_mcc_rec;
++l_dest_mcc_rec;
}
/* Copy all the dflt_tile_compo_cp to the current tile cp */
memcpy(l_current_tccp, l_default_tcp->tccps, l_tccp_size);
/* Move to next tile cp*/
++l_tcp;
}
/* Create the current tile decoder*/
p_j2k->m_tcd = (opj_tcd_t*)opj_tcd_create(OPJ_TRUE); /* FIXME why a cast ? */
if (! p_j2k->m_tcd) {
return OPJ_FALSE;
}
if (!opj_tcd_init(p_j2k->m_tcd, l_image, &(p_j2k->m_cp), p_j2k->m_tp)) {
opj_tcd_destroy(p_j2k->m_tcd);
p_j2k->m_tcd = 00;
opj_event_msg(p_manager, EVT_ERROR, "Cannot decode tile, memory error\n");
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static const opj_dec_memory_marker_handler_t * opj_j2k_get_marker_handler(
OPJ_UINT32 p_id)
{
const opj_dec_memory_marker_handler_t *e;
for (e = j2k_memory_marker_handler_tab; e->id != 0; ++e) {
if (e->id == p_id) {
break; /* we find a handler corresponding to the marker ID*/
}
}
return e;
}
void opj_j2k_destroy(opj_j2k_t *p_j2k)
{
if (p_j2k == 00) {
return;
}
if (p_j2k->m_is_decoder) {
if (p_j2k->m_specific_param.m_decoder.m_default_tcp != 00) {
opj_j2k_tcp_destroy(p_j2k->m_specific_param.m_decoder.m_default_tcp);
opj_free(p_j2k->m_specific_param.m_decoder.m_default_tcp);
p_j2k->m_specific_param.m_decoder.m_default_tcp = 00;
}
if (p_j2k->m_specific_param.m_decoder.m_header_data != 00) {
opj_free(p_j2k->m_specific_param.m_decoder.m_header_data);
p_j2k->m_specific_param.m_decoder.m_header_data = 00;
p_j2k->m_specific_param.m_decoder.m_header_data_size = 0;
}
} else {
if (p_j2k->m_specific_param.m_encoder.m_encoded_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_encoded_tile_data);
p_j2k->m_specific_param.m_encoder.m_encoded_tile_data = 00;
}
if (p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer) {
opj_free(p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer);
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer = 00;
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current = 00;
}
if (p_j2k->m_specific_param.m_encoder.m_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = 00;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
}
}
opj_tcd_destroy(p_j2k->m_tcd);
opj_j2k_cp_destroy(&(p_j2k->m_cp));
memset(&(p_j2k->m_cp), 0, sizeof(opj_cp_t));
opj_procedure_list_destroy(p_j2k->m_procedure_list);
p_j2k->m_procedure_list = 00;
opj_procedure_list_destroy(p_j2k->m_validation_list);
p_j2k->m_procedure_list = 00;
j2k_destroy_cstr_index(p_j2k->cstr_index);
p_j2k->cstr_index = NULL;
opj_image_destroy(p_j2k->m_private_image);
p_j2k->m_private_image = NULL;
opj_image_destroy(p_j2k->m_output_image);
p_j2k->m_output_image = NULL;
opj_thread_pool_destroy(p_j2k->m_tp);
p_j2k->m_tp = NULL;
opj_free(p_j2k);
}
void j2k_destroy_cstr_index(opj_codestream_index_t *p_cstr_ind)
{
if (p_cstr_ind) {
if (p_cstr_ind->marker) {
opj_free(p_cstr_ind->marker);
p_cstr_ind->marker = NULL;
}
if (p_cstr_ind->tile_index) {
OPJ_UINT32 it_tile = 0;
for (it_tile = 0; it_tile < p_cstr_ind->nb_of_tiles; it_tile++) {
if (p_cstr_ind->tile_index[it_tile].packet_index) {
opj_free(p_cstr_ind->tile_index[it_tile].packet_index);
p_cstr_ind->tile_index[it_tile].packet_index = NULL;
}
if (p_cstr_ind->tile_index[it_tile].tp_index) {
opj_free(p_cstr_ind->tile_index[it_tile].tp_index);
p_cstr_ind->tile_index[it_tile].tp_index = NULL;
}
if (p_cstr_ind->tile_index[it_tile].marker) {
opj_free(p_cstr_ind->tile_index[it_tile].marker);
p_cstr_ind->tile_index[it_tile].marker = NULL;
}
}
opj_free(p_cstr_ind->tile_index);
p_cstr_ind->tile_index = NULL;
}
opj_free(p_cstr_ind);
}
}
static void opj_j2k_tcp_destroy(opj_tcp_t *p_tcp)
{
if (p_tcp == 00) {
return;
}
if (p_tcp->ppt_markers != 00) {
OPJ_UINT32 i;
for (i = 0U; i < p_tcp->ppt_markers_count; ++i) {
if (p_tcp->ppt_markers[i].m_data != NULL) {
opj_free(p_tcp->ppt_markers[i].m_data);
}
}
p_tcp->ppt_markers_count = 0U;
opj_free(p_tcp->ppt_markers);
p_tcp->ppt_markers = NULL;
}
if (p_tcp->ppt_buffer != 00) {
opj_free(p_tcp->ppt_buffer);
p_tcp->ppt_buffer = 00;
}
if (p_tcp->tccps != 00) {
opj_free(p_tcp->tccps);
p_tcp->tccps = 00;
}
if (p_tcp->m_mct_coding_matrix != 00) {
opj_free(p_tcp->m_mct_coding_matrix);
p_tcp->m_mct_coding_matrix = 00;
}
if (p_tcp->m_mct_decoding_matrix != 00) {
opj_free(p_tcp->m_mct_decoding_matrix);
p_tcp->m_mct_decoding_matrix = 00;
}
if (p_tcp->m_mcc_records) {
opj_free(p_tcp->m_mcc_records);
p_tcp->m_mcc_records = 00;
p_tcp->m_nb_max_mcc_records = 0;
p_tcp->m_nb_mcc_records = 0;
}
if (p_tcp->m_mct_records) {
opj_mct_data_t * l_mct_data = p_tcp->m_mct_records;
OPJ_UINT32 i;
for (i = 0; i < p_tcp->m_nb_mct_records; ++i) {
if (l_mct_data->m_data) {
opj_free(l_mct_data->m_data);
l_mct_data->m_data = 00;
}
++l_mct_data;
}
opj_free(p_tcp->m_mct_records);
p_tcp->m_mct_records = 00;
}
if (p_tcp->mct_norms != 00) {
opj_free(p_tcp->mct_norms);
p_tcp->mct_norms = 00;
}
opj_j2k_tcp_data_destroy(p_tcp);
}
static void opj_j2k_tcp_data_destroy(opj_tcp_t *p_tcp)
{
if (p_tcp->m_data) {
opj_free(p_tcp->m_data);
p_tcp->m_data = NULL;
p_tcp->m_data_size = 0;
}
}
static void opj_j2k_cp_destroy(opj_cp_t *p_cp)
{
OPJ_UINT32 l_nb_tiles;
opj_tcp_t * l_current_tile = 00;
if (p_cp == 00) {
return;
}
if (p_cp->tcps != 00) {
OPJ_UINT32 i;
l_current_tile = p_cp->tcps;
l_nb_tiles = p_cp->th * p_cp->tw;
for (i = 0U; i < l_nb_tiles; ++i) {
opj_j2k_tcp_destroy(l_current_tile);
++l_current_tile;
}
opj_free(p_cp->tcps);
p_cp->tcps = 00;
}
if (p_cp->ppm_markers != 00) {
OPJ_UINT32 i;
for (i = 0U; i < p_cp->ppm_markers_count; ++i) {
if (p_cp->ppm_markers[i].m_data != NULL) {
opj_free(p_cp->ppm_markers[i].m_data);
}
}
p_cp->ppm_markers_count = 0U;
opj_free(p_cp->ppm_markers);
p_cp->ppm_markers = NULL;
}
opj_free(p_cp->ppm_buffer);
p_cp->ppm_buffer = 00;
p_cp->ppm_data =
NULL; /* ppm_data belongs to the allocated buffer pointed by ppm_buffer */
opj_free(p_cp->comment);
p_cp->comment = 00;
if (! p_cp->m_is_decoder) {
opj_free(p_cp->m_specific_param.m_enc.m_matrice);
p_cp->m_specific_param.m_enc.m_matrice = 00;
}
}
static OPJ_BOOL opj_j2k_need_nb_tile_parts_correction(opj_stream_private_t
*p_stream, OPJ_UINT32 tile_no, OPJ_BOOL* p_correction_needed,
opj_event_mgr_t * p_manager)
{
OPJ_BYTE l_header_data[10];
OPJ_OFF_T l_stream_pos_backup;
OPJ_UINT32 l_current_marker;
OPJ_UINT32 l_marker_size;
OPJ_UINT32 l_tile_no, l_tot_len, l_current_part, l_num_parts;
/* initialize to no correction needed */
*p_correction_needed = OPJ_FALSE;
if (!opj_stream_has_seek(p_stream)) {
/* We can't do much in this case, seek is needed */
return OPJ_TRUE;
}
l_stream_pos_backup = opj_stream_tell(p_stream);
if (l_stream_pos_backup == -1) {
/* let's do nothing */
return OPJ_TRUE;
}
for (;;) {
/* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream, l_header_data, 2, p_manager) != 2) {
/* assume all is OK */
if (! opj_stream_seek(p_stream, l_stream_pos_backup, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/* Read 2 bytes from buffer as the new marker ID */
opj_read_bytes(l_header_data, &l_current_marker, 2);
if (l_current_marker != J2K_MS_SOT) {
/* assume all is OK */
if (! opj_stream_seek(p_stream, l_stream_pos_backup, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/* Try to read 2 bytes (the marker size) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream, l_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* Read 2 bytes from the buffer as the marker size */
opj_read_bytes(l_header_data, &l_marker_size, 2);
/* Check marker size for SOT Marker */
if (l_marker_size != 10) {
opj_event_msg(p_manager, EVT_ERROR, "Inconsistent marker size\n");
return OPJ_FALSE;
}
l_marker_size -= 2;
if (opj_stream_read_data(p_stream, l_header_data, l_marker_size,
p_manager) != l_marker_size) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
if (! opj_j2k_get_sot_values(l_header_data, l_marker_size, &l_tile_no,
&l_tot_len, &l_current_part, &l_num_parts, p_manager)) {
return OPJ_FALSE;
}
if (l_tile_no == tile_no) {
/* we found what we were looking for */
break;
}
if ((l_tot_len == 0U) || (l_tot_len < 14U)) {
/* last SOT until EOC or invalid Psot value */
/* assume all is OK */
if (! opj_stream_seek(p_stream, l_stream_pos_backup, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
l_tot_len -= 12U;
/* look for next SOT marker */
if (opj_stream_skip(p_stream, (OPJ_OFF_T)(l_tot_len),
p_manager) != (OPJ_OFF_T)(l_tot_len)) {
/* assume all is OK */
if (! opj_stream_seek(p_stream, l_stream_pos_backup, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
}
/* check for correction */
if (l_current_part == l_num_parts) {
*p_correction_needed = OPJ_TRUE;
}
if (! opj_stream_seek(p_stream, l_stream_pos_backup, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_read_tile_header(opj_j2k_t * p_j2k,
OPJ_UINT32 * p_tile_index,
OPJ_UINT32 * p_data_size,
OPJ_INT32 * p_tile_x0, OPJ_INT32 * p_tile_y0,
OPJ_INT32 * p_tile_x1, OPJ_INT32 * p_tile_y1,
OPJ_UINT32 * p_nb_comps,
OPJ_BOOL * p_go_on,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 l_current_marker = J2K_MS_SOT;
OPJ_UINT32 l_marker_size;
const opj_dec_memory_marker_handler_t * l_marker_handler = 00;
opj_tcp_t * l_tcp = NULL;
/* preconditions */
assert(p_stream != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
/* Reach the End Of Codestream ?*/
if (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_EOC) {
l_current_marker = J2K_MS_EOC;
}
/* We need to encounter a SOT marker (a new tile-part header) */
else if (p_j2k->m_specific_param.m_decoder.m_state != J2K_STATE_TPHSOT) {
return OPJ_FALSE;
}
/* Read into the codestream until reach the EOC or ! can_decode ??? FIXME */
while ((!p_j2k->m_specific_param.m_decoder.m_can_decode) &&
(l_current_marker != J2K_MS_EOC)) {
/* Try to read until the Start Of Data is detected */
while (l_current_marker != J2K_MS_SOD) {
if (opj_stream_get_number_byte_left(p_stream) == 0) {
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_NEOC;
break;
}
/* Try to read 2 bytes (the marker size) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* Read 2 bytes from the buffer as the marker size */
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data, &l_marker_size,
2);
/* Check marker size (does not include marker ID but includes marker size) */
if (l_marker_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Inconsistent marker size\n");
return OPJ_FALSE;
}
/* cf. https://code.google.com/p/openjpeg/issues/detail?id=226 */
if (l_current_marker == 0x8080 &&
opj_stream_get_number_byte_left(p_stream) == 0) {
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_NEOC;
break;
}
/* Why this condition? FIXME */
if (p_j2k->m_specific_param.m_decoder.m_state & J2K_STATE_TPH) {
p_j2k->m_specific_param.m_decoder.m_sot_length -= (l_marker_size + 2);
}
l_marker_size -= 2; /* Subtract the size of the marker ID already read */
/* Get the marker handler from the marker ID */
l_marker_handler = opj_j2k_get_marker_handler(l_current_marker);
/* Check if the marker is known and if it is the right place to find it */
if (!(p_j2k->m_specific_param.m_decoder.m_state & l_marker_handler->states)) {
opj_event_msg(p_manager, EVT_ERROR,
"Marker is not compliant with its position\n");
return OPJ_FALSE;
}
/* FIXME manage case of unknown marker as in the main header ? */
/* Check if the marker size is compatible with the header data size */
if (l_marker_size > p_j2k->m_specific_param.m_decoder.m_header_data_size) {
OPJ_BYTE *new_header_data = NULL;
/* If we are here, this means we consider this marker as known & we will read it */
/* Check enough bytes left in stream before allocation */
if ((OPJ_OFF_T)l_marker_size > opj_stream_get_number_byte_left(p_stream)) {
opj_event_msg(p_manager, EVT_ERROR,
"Marker size inconsistent with stream length\n");
return OPJ_FALSE;
}
new_header_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size);
if (! new_header_data) {
opj_free(p_j2k->m_specific_param.m_decoder.m_header_data);
p_j2k->m_specific_param.m_decoder.m_header_data = NULL;
p_j2k->m_specific_param.m_decoder.m_header_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read header\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_decoder.m_header_data = new_header_data;
p_j2k->m_specific_param.m_decoder.m_header_data_size = l_marker_size;
}
/* Try to read the rest of the marker segment from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size,
p_manager) != l_marker_size) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
if (!l_marker_handler->handler) {
/* See issue #175 */
opj_event_msg(p_manager, EVT_ERROR, "Not sure how that happened.\n");
return OPJ_FALSE;
}
/* Read the marker segment with the correct marker handler */
if (!(*(l_marker_handler->handler))(p_j2k,
p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR,
"Fail to read the current marker segment (%#x)\n", l_current_marker);
return OPJ_FALSE;
}
/* Add the marker to the codestream index*/
if (OPJ_FALSE == opj_j2k_add_tlmarker(p_j2k->m_current_tile_number,
p_j2k->cstr_index,
l_marker_handler->id,
(OPJ_UINT32) opj_stream_tell(p_stream) - l_marker_size - 4,
l_marker_size + 4)) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add tl marker\n");
return OPJ_FALSE;
}
/* Keep the position of the last SOT marker read */
if (l_marker_handler->id == J2K_MS_SOT) {
OPJ_UINT32 sot_pos = (OPJ_UINT32) opj_stream_tell(p_stream) - l_marker_size - 4
;
if (sot_pos > p_j2k->m_specific_param.m_decoder.m_last_sot_read_pos) {
p_j2k->m_specific_param.m_decoder.m_last_sot_read_pos = sot_pos;
}
}
if (p_j2k->m_specific_param.m_decoder.m_skip_data) {
/* Skip the rest of the tile part header*/
if (opj_stream_skip(p_stream, p_j2k->m_specific_param.m_decoder.m_sot_length,
p_manager) != p_j2k->m_specific_param.m_decoder.m_sot_length) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
l_current_marker = J2K_MS_SOD; /* Normally we reached a SOD */
} else {
/* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer*/
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* Read 2 bytes from the buffer as the new marker ID */
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,
&l_current_marker, 2);
}
}
if (opj_stream_get_number_byte_left(p_stream) == 0
&& p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_NEOC) {
break;
}
/* If we didn't skip data before, we need to read the SOD marker*/
if (! p_j2k->m_specific_param.m_decoder.m_skip_data) {
/* Try to read the SOD marker and skip data ? FIXME */
if (! opj_j2k_read_sod(p_j2k, p_stream, p_manager)) {
return OPJ_FALSE;
}
if (p_j2k->m_specific_param.m_decoder.m_can_decode &&
!p_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction_checked) {
/* Issue 254 */
OPJ_BOOL l_correction_needed;
p_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction_checked = 1;
if (!opj_j2k_need_nb_tile_parts_correction(p_stream,
p_j2k->m_current_tile_number, &l_correction_needed, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR,
"opj_j2k_apply_nb_tile_parts_correction error\n");
return OPJ_FALSE;
}
if (l_correction_needed) {
OPJ_UINT32 l_nb_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th;
OPJ_UINT32 l_tile_no;
p_j2k->m_specific_param.m_decoder.m_can_decode = 0;
p_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction = 1;
/* correct tiles */
for (l_tile_no = 0U; l_tile_no < l_nb_tiles; ++l_tile_no) {
if (p_j2k->m_cp.tcps[l_tile_no].m_nb_tile_parts != 0U) {
p_j2k->m_cp.tcps[l_tile_no].m_nb_tile_parts += 1;
}
}
opj_event_msg(p_manager, EVT_WARNING,
"Non conformant codestream TPsot==TNsot.\n");
}
}
if (! p_j2k->m_specific_param.m_decoder.m_can_decode) {
/* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* Read 2 bytes from buffer as the new marker ID */
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,
&l_current_marker, 2);
}
} else {
/* Indicate we will try to read a new tile-part header*/
p_j2k->m_specific_param.m_decoder.m_skip_data = 0;
p_j2k->m_specific_param.m_decoder.m_can_decode = 0;
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPHSOT;
/* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* Read 2 bytes from buffer as the new marker ID */
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,
&l_current_marker, 2);
}
}
/* Current marker is the EOC marker ?*/
if (l_current_marker == J2K_MS_EOC) {
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_EOC;
}
/* FIXME DOC ???*/
if (! p_j2k->m_specific_param.m_decoder.m_can_decode) {
OPJ_UINT32 l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
l_tcp = p_j2k->m_cp.tcps + p_j2k->m_current_tile_number;
while ((p_j2k->m_current_tile_number < l_nb_tiles) && (l_tcp->m_data == 00)) {
++p_j2k->m_current_tile_number;
++l_tcp;
}
if (p_j2k->m_current_tile_number == l_nb_tiles) {
*p_go_on = OPJ_FALSE;
return OPJ_TRUE;
}
}
if (! opj_j2k_merge_ppt(p_j2k->m_cp.tcps + p_j2k->m_current_tile_number,
p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Failed to merge PPT data\n");
return OPJ_FALSE;
}
/*FIXME ???*/
if (! opj_tcd_init_decode_tile(p_j2k->m_tcd, p_j2k->m_current_tile_number,
p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Cannot decode tile, memory error\n");
return OPJ_FALSE;
}
opj_event_msg(p_manager, EVT_INFO, "Header of tile %d / %d has been read.\n",
p_j2k->m_current_tile_number + 1, (p_j2k->m_cp.th * p_j2k->m_cp.tw));
*p_tile_index = p_j2k->m_current_tile_number;
*p_go_on = OPJ_TRUE;
*p_data_size = opj_tcd_get_decoded_tile_size(p_j2k->m_tcd);
if (*p_data_size == UINT_MAX) {
return OPJ_FALSE;
}
*p_tile_x0 = p_j2k->m_tcd->tcd_image->tiles->x0;
*p_tile_y0 = p_j2k->m_tcd->tcd_image->tiles->y0;
*p_tile_x1 = p_j2k->m_tcd->tcd_image->tiles->x1;
*p_tile_y1 = p_j2k->m_tcd->tcd_image->tiles->y1;
*p_nb_comps = p_j2k->m_tcd->tcd_image->tiles->numcomps;
p_j2k->m_specific_param.m_decoder.m_state |= J2K_STATE_DATA;
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_decode_tile(opj_j2k_t * p_j2k,
OPJ_UINT32 p_tile_index,
OPJ_BYTE * p_data,
OPJ_UINT32 p_data_size,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 l_current_marker;
OPJ_BYTE l_data [2];
opj_tcp_t * l_tcp;
/* preconditions */
assert(p_stream != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
if (!(p_j2k->m_specific_param.m_decoder.m_state & J2K_STATE_DATA)
|| (p_tile_index != p_j2k->m_current_tile_number)) {
return OPJ_FALSE;
}
l_tcp = &(p_j2k->m_cp.tcps[p_tile_index]);
if (! l_tcp->m_data) {
opj_j2k_tcp_destroy(l_tcp);
return OPJ_FALSE;
}
if (! opj_tcd_decode_tile(p_j2k->m_tcd,
l_tcp->m_data,
l_tcp->m_data_size,
p_tile_index,
p_j2k->cstr_index, p_manager)) {
opj_j2k_tcp_destroy(l_tcp);
p_j2k->m_specific_param.m_decoder.m_state |= J2K_STATE_ERR;
opj_event_msg(p_manager, EVT_ERROR, "Failed to decode.\n");
return OPJ_FALSE;
}
/* p_data can be set to NULL when the call will take care of using */
/* itself the TCD data. This is typically the case for whole single */
/* tile decoding optimization. */
if (p_data != NULL) {
if (! opj_tcd_update_tile_data(p_j2k->m_tcd, p_data, p_data_size)) {
return OPJ_FALSE;
}
/* To avoid to destroy the tcp which can be useful when we try to decode a tile decoded before (cf j2k_random_tile_access)
* we destroy just the data which will be re-read in read_tile_header*/
/*opj_j2k_tcp_destroy(l_tcp);
p_j2k->m_tcd->tcp = 0;*/
opj_j2k_tcp_data_destroy(l_tcp);
}
p_j2k->m_specific_param.m_decoder.m_can_decode = 0;
p_j2k->m_specific_param.m_decoder.m_state &= (~(OPJ_UINT32)J2K_STATE_DATA);
if (opj_stream_get_number_byte_left(p_stream) == 0
&& p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_NEOC) {
return OPJ_TRUE;
}
if (p_j2k->m_specific_param.m_decoder.m_state != J2K_STATE_EOC) {
if (opj_stream_read_data(p_stream, l_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
opj_read_bytes(l_data, &l_current_marker, 2);
if (l_current_marker == J2K_MS_EOC) {
p_j2k->m_current_tile_number = 0;
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_EOC;
} else if (l_current_marker != J2K_MS_SOT) {
if (opj_stream_get_number_byte_left(p_stream) == 0) {
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_NEOC;
opj_event_msg(p_manager, EVT_WARNING, "Stream does not end with EOC\n");
return OPJ_TRUE;
}
opj_event_msg(p_manager, EVT_ERROR, "Stream too short, expected SOT\n");
return OPJ_FALSE;
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_update_image_data(opj_tcd_t * p_tcd, OPJ_BYTE * p_data,
opj_image_t* p_output_image)
{
OPJ_UINT32 i, j, k = 0;
OPJ_UINT32 l_width_src, l_height_src;
OPJ_UINT32 l_width_dest, l_height_dest;
OPJ_INT32 l_offset_x0_src, l_offset_y0_src, l_offset_x1_src, l_offset_y1_src;
OPJ_SIZE_T l_start_offset_src, l_line_offset_src, l_end_offset_src ;
OPJ_UINT32 l_start_x_dest, l_start_y_dest;
OPJ_UINT32 l_x0_dest, l_y0_dest, l_x1_dest, l_y1_dest;
OPJ_SIZE_T l_start_offset_dest, l_line_offset_dest;
opj_image_comp_t * l_img_comp_src = 00;
opj_image_comp_t * l_img_comp_dest = 00;
opj_tcd_tilecomp_t * l_tilec = 00;
opj_image_t * l_image_src = 00;
OPJ_UINT32 l_size_comp, l_remaining;
OPJ_INT32 * l_dest_ptr;
opj_tcd_resolution_t* l_res = 00;
l_tilec = p_tcd->tcd_image->tiles->comps;
l_image_src = p_tcd->image;
l_img_comp_src = l_image_src->comps;
l_img_comp_dest = p_output_image->comps;
for (i = 0; i < l_image_src->numcomps; i++) {
/* Allocate output component buffer if necessary */
if (!l_img_comp_dest->data) {
OPJ_SIZE_T l_width = l_img_comp_dest->w;
OPJ_SIZE_T l_height = l_img_comp_dest->h;
if ((l_height == 0U) || (l_width > (SIZE_MAX / l_height)) ||
l_width * l_height > SIZE_MAX / sizeof(OPJ_INT32)) {
/* would overflow */
return OPJ_FALSE;
}
l_img_comp_dest->data = (OPJ_INT32*) opj_image_data_alloc(l_width * l_height *
sizeof(OPJ_INT32));
if (! l_img_comp_dest->data) {
return OPJ_FALSE;
}
/* Do we really need this memset ? */
memset(l_img_comp_dest->data, 0, l_width * l_height * sizeof(OPJ_INT32));
}
/* Copy info from decoded comp image to output image */
l_img_comp_dest->resno_decoded = l_img_comp_src->resno_decoded;
/*-----*/
/* Compute the precision of the output buffer */
l_size_comp = l_img_comp_src->prec >> 3; /*(/ 8)*/
l_remaining = l_img_comp_src->prec & 7; /* (%8) */
l_res = l_tilec->resolutions + l_img_comp_src->resno_decoded;
if (l_remaining) {
++l_size_comp;
}
if (l_size_comp == 3) {
l_size_comp = 4;
}
/*-----*/
/* Current tile component size*/
/*if (i == 0) {
fprintf(stdout, "SRC: l_res_x0=%d, l_res_x1=%d, l_res_y0=%d, l_res_y1=%d\n",
l_res->x0, l_res->x1, l_res->y0, l_res->y1);
}*/
l_width_src = (OPJ_UINT32)(l_res->x1 - l_res->x0);
l_height_src = (OPJ_UINT32)(l_res->y1 - l_res->y0);
/* Border of the current output component*/
l_x0_dest = opj_uint_ceildivpow2(l_img_comp_dest->x0, l_img_comp_dest->factor);
l_y0_dest = opj_uint_ceildivpow2(l_img_comp_dest->y0, l_img_comp_dest->factor);
l_x1_dest = l_x0_dest +
l_img_comp_dest->w; /* can't overflow given that image->x1 is uint32 */
l_y1_dest = l_y0_dest + l_img_comp_dest->h;
/*if (i == 0) {
fprintf(stdout, "DEST: l_x0_dest=%d, l_x1_dest=%d, l_y0_dest=%d, l_y1_dest=%d (%d)\n",
l_x0_dest, l_x1_dest, l_y0_dest, l_y1_dest, l_img_comp_dest->factor );
}*/
/*-----*/
/* Compute the area (l_offset_x0_src, l_offset_y0_src, l_offset_x1_src, l_offset_y1_src)
* of the input buffer (decoded tile component) which will be move
* in the output buffer. Compute the area of the output buffer (l_start_x_dest,
* l_start_y_dest, l_width_dest, l_height_dest) which will be modified
* by this input area.
* */
assert(l_res->x0 >= 0);
assert(l_res->x1 >= 0);
if (l_x0_dest < (OPJ_UINT32)l_res->x0) {
l_start_x_dest = (OPJ_UINT32)l_res->x0 - l_x0_dest;
l_offset_x0_src = 0;
if (l_x1_dest >= (OPJ_UINT32)l_res->x1) {
l_width_dest = l_width_src;
l_offset_x1_src = 0;
} else {
l_width_dest = l_x1_dest - (OPJ_UINT32)l_res->x0 ;
l_offset_x1_src = (OPJ_INT32)(l_width_src - l_width_dest);
}
} else {
l_start_x_dest = 0U;
l_offset_x0_src = (OPJ_INT32)l_x0_dest - l_res->x0;
if (l_x1_dest >= (OPJ_UINT32)l_res->x1) {
l_width_dest = l_width_src - (OPJ_UINT32)l_offset_x0_src;
l_offset_x1_src = 0;
} else {
l_width_dest = l_img_comp_dest->w ;
l_offset_x1_src = l_res->x1 - (OPJ_INT32)l_x1_dest;
}
}
if (l_y0_dest < (OPJ_UINT32)l_res->y0) {
l_start_y_dest = (OPJ_UINT32)l_res->y0 - l_y0_dest;
l_offset_y0_src = 0;
if (l_y1_dest >= (OPJ_UINT32)l_res->y1) {
l_height_dest = l_height_src;
l_offset_y1_src = 0;
} else {
l_height_dest = l_y1_dest - (OPJ_UINT32)l_res->y0 ;
l_offset_y1_src = (OPJ_INT32)(l_height_src - l_height_dest);
}
} else {
l_start_y_dest = 0U;
l_offset_y0_src = (OPJ_INT32)l_y0_dest - l_res->y0;
if (l_y1_dest >= (OPJ_UINT32)l_res->y1) {
l_height_dest = l_height_src - (OPJ_UINT32)l_offset_y0_src;
l_offset_y1_src = 0;
} else {
l_height_dest = l_img_comp_dest->h ;
l_offset_y1_src = l_res->y1 - (OPJ_INT32)l_y1_dest;
}
}
if ((l_offset_x0_src < 0) || (l_offset_y0_src < 0) || (l_offset_x1_src < 0) ||
(l_offset_y1_src < 0)) {
return OPJ_FALSE;
}
/* testcase 2977.pdf.asan.67.2198 */
if ((OPJ_INT32)l_width_dest < 0 || (OPJ_INT32)l_height_dest < 0) {
return OPJ_FALSE;
}
/*-----*/
/* Compute the input buffer offset */
l_start_offset_src = (OPJ_SIZE_T)l_offset_x0_src + (OPJ_SIZE_T)l_offset_y0_src
* (OPJ_SIZE_T)l_width_src;
l_line_offset_src = (OPJ_SIZE_T)l_offset_x1_src + (OPJ_SIZE_T)l_offset_x0_src;
l_end_offset_src = (OPJ_SIZE_T)l_offset_y1_src * (OPJ_SIZE_T)l_width_src -
(OPJ_SIZE_T)l_offset_x0_src;
/* Compute the output buffer offset */
l_start_offset_dest = (OPJ_SIZE_T)l_start_x_dest + (OPJ_SIZE_T)l_start_y_dest
* (OPJ_SIZE_T)l_img_comp_dest->w;
l_line_offset_dest = (OPJ_SIZE_T)l_img_comp_dest->w - (OPJ_SIZE_T)l_width_dest;
/* Move the output buffer to the first place where we will write*/
l_dest_ptr = l_img_comp_dest->data + l_start_offset_dest;
/*if (i == 0) {
fprintf(stdout, "COMPO[%d]:\n",i);
fprintf(stdout, "SRC: l_start_x_src=%d, l_start_y_src=%d, l_width_src=%d, l_height_src=%d\n"
"\t tile offset:%d, %d, %d, %d\n"
"\t buffer offset: %d; %d, %d\n",
l_res->x0, l_res->y0, l_width_src, l_height_src,
l_offset_x0_src, l_offset_y0_src, l_offset_x1_src, l_offset_y1_src,
l_start_offset_src, l_line_offset_src, l_end_offset_src);
fprintf(stdout, "DEST: l_start_x_dest=%d, l_start_y_dest=%d, l_width_dest=%d, l_height_dest=%d\n"
"\t start offset: %d, line offset= %d\n",
l_start_x_dest, l_start_y_dest, l_width_dest, l_height_dest, l_start_offset_dest, l_line_offset_dest);
}*/
switch (l_size_comp) {
case 1: {
OPJ_CHAR * l_src_ptr = (OPJ_CHAR*) p_data;
l_src_ptr += l_start_offset_src; /* Move to the first place where we will read*/
if (l_img_comp_src->sgnd) {
for (j = 0 ; j < l_height_dest ; ++j) {
for (k = 0 ; k < l_width_dest ; ++k) {
*(l_dest_ptr++) = (OPJ_INT32)(*
(l_src_ptr++)); /* Copy only the data needed for the output image */
}
l_dest_ptr +=
l_line_offset_dest; /* Move to the next place where we will write */
l_src_ptr += l_line_offset_src ; /* Move to the next place where we will read */
}
} else {
for (j = 0 ; j < l_height_dest ; ++j) {
for (k = 0 ; k < l_width_dest ; ++k) {
*(l_dest_ptr++) = (OPJ_INT32)((*(l_src_ptr++)) & 0xff);
}
l_dest_ptr += l_line_offset_dest;
l_src_ptr += l_line_offset_src;
}
}
l_src_ptr +=
l_end_offset_src; /* Move to the end of this component-part of the input buffer */
p_data = (OPJ_BYTE*)
l_src_ptr; /* Keep the current position for the next component-part */
}
break;
case 2: {
OPJ_INT16 * l_src_ptr = (OPJ_INT16 *) p_data;
l_src_ptr += l_start_offset_src;
if (l_img_comp_src->sgnd) {
for (j = 0; j < l_height_dest; ++j) {
for (k = 0; k < l_width_dest; ++k) {
OPJ_INT16 val;
memcpy(&val, l_src_ptr, sizeof(val));
l_src_ptr ++;
*(l_dest_ptr++) = val;
}
l_dest_ptr += l_line_offset_dest;
l_src_ptr += l_line_offset_src ;
}
} else {
for (j = 0; j < l_height_dest; ++j) {
for (k = 0; k < l_width_dest; ++k) {
OPJ_INT16 val;
memcpy(&val, l_src_ptr, sizeof(val));
l_src_ptr ++;
*(l_dest_ptr++) = val & 0xffff;
}
l_dest_ptr += l_line_offset_dest;
l_src_ptr += l_line_offset_src ;
}
}
l_src_ptr += l_end_offset_src;
p_data = (OPJ_BYTE*) l_src_ptr;
}
break;
case 4: {
OPJ_INT32 * l_src_ptr = (OPJ_INT32 *) p_data;
l_src_ptr += l_start_offset_src;
for (j = 0; j < l_height_dest; ++j) {
memcpy(l_dest_ptr, l_src_ptr, l_width_dest * sizeof(OPJ_INT32));
l_dest_ptr += l_width_dest + l_line_offset_dest;
l_src_ptr += l_width_dest + l_line_offset_src ;
}
l_src_ptr += l_end_offset_src;
p_data = (OPJ_BYTE*) l_src_ptr;
}
break;
}
++l_img_comp_dest;
++l_img_comp_src;
++l_tilec;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_set_decode_area(opj_j2k_t *p_j2k,
opj_image_t* p_image,
OPJ_INT32 p_start_x, OPJ_INT32 p_start_y,
OPJ_INT32 p_end_x, OPJ_INT32 p_end_y,
opj_event_mgr_t * p_manager)
{
opj_cp_t * l_cp = &(p_j2k->m_cp);
opj_image_t * l_image = p_j2k->m_private_image;
OPJ_UINT32 it_comp;
OPJ_INT32 l_comp_x1, l_comp_y1;
opj_image_comp_t* l_img_comp = NULL;
/* Check if we are read the main header */
if (p_j2k->m_specific_param.m_decoder.m_state != J2K_STATE_TPHSOT) {
opj_event_msg(p_manager, EVT_ERROR,
"Need to decode the main header before begin to decode the remaining codestream");
return OPJ_FALSE;
}
if (!p_start_x && !p_start_y && !p_end_x && !p_end_y) {
opj_event_msg(p_manager, EVT_INFO,
"No decoded area parameters, set the decoded area to the whole image\n");
p_j2k->m_specific_param.m_decoder.m_start_tile_x = 0;
p_j2k->m_specific_param.m_decoder.m_start_tile_y = 0;
p_j2k->m_specific_param.m_decoder.m_end_tile_x = l_cp->tw;
p_j2k->m_specific_param.m_decoder.m_end_tile_y = l_cp->th;
return OPJ_TRUE;
}
/* ----- */
/* Check if the positions provided by the user are correct */
/* Left */
if (p_start_x < 0) {
opj_event_msg(p_manager, EVT_ERROR,
"Left position of the decoded area (region_x0=%d) should be >= 0.\n",
p_start_x);
return OPJ_FALSE;
} else if ((OPJ_UINT32)p_start_x > l_image->x1) {
opj_event_msg(p_manager, EVT_ERROR,
"Left position of the decoded area (region_x0=%d) is outside the image area (Xsiz=%d).\n",
p_start_x, l_image->x1);
return OPJ_FALSE;
} else if ((OPJ_UINT32)p_start_x < l_image->x0) {
opj_event_msg(p_manager, EVT_WARNING,
"Left position of the decoded area (region_x0=%d) is outside the image area (XOsiz=%d).\n",
p_start_x, l_image->x0);
p_j2k->m_specific_param.m_decoder.m_start_tile_x = 0;
p_image->x0 = l_image->x0;
} else {
p_j2k->m_specific_param.m_decoder.m_start_tile_x = ((OPJ_UINT32)p_start_x -
l_cp->tx0) / l_cp->tdx;
p_image->x0 = (OPJ_UINT32)p_start_x;
}
/* Up */
if (p_start_x < 0) {
opj_event_msg(p_manager, EVT_ERROR,
"Up position of the decoded area (region_y0=%d) should be >= 0.\n",
p_start_y);
return OPJ_FALSE;
} else if ((OPJ_UINT32)p_start_y > l_image->y1) {
opj_event_msg(p_manager, EVT_ERROR,
"Up position of the decoded area (region_y0=%d) is outside the image area (Ysiz=%d).\n",
p_start_y, l_image->y1);
return OPJ_FALSE;
} else if ((OPJ_UINT32)p_start_y < l_image->y0) {
opj_event_msg(p_manager, EVT_WARNING,
"Up position of the decoded area (region_y0=%d) is outside the image area (YOsiz=%d).\n",
p_start_y, l_image->y0);
p_j2k->m_specific_param.m_decoder.m_start_tile_y = 0;
p_image->y0 = l_image->y0;
} else {
p_j2k->m_specific_param.m_decoder.m_start_tile_y = ((OPJ_UINT32)p_start_y -
l_cp->ty0) / l_cp->tdy;
p_image->y0 = (OPJ_UINT32)p_start_y;
}
/* Right */
if (p_end_x <= 0) {
opj_event_msg(p_manager, EVT_ERROR,
"Right position of the decoded area (region_x1=%d) should be > 0.\n",
p_end_x);
return OPJ_FALSE;
} else if ((OPJ_UINT32)p_end_x < l_image->x0) {
opj_event_msg(p_manager, EVT_ERROR,
"Right position of the decoded area (region_x1=%d) is outside the image area (XOsiz=%d).\n",
p_end_x, l_image->x0);
return OPJ_FALSE;
} else if ((OPJ_UINT32)p_end_x > l_image->x1) {
opj_event_msg(p_manager, EVT_WARNING,
"Right position of the decoded area (region_x1=%d) is outside the image area (Xsiz=%d).\n",
p_end_x, l_image->x1);
p_j2k->m_specific_param.m_decoder.m_end_tile_x = l_cp->tw;
p_image->x1 = l_image->x1;
} else {
p_j2k->m_specific_param.m_decoder.m_end_tile_x = (OPJ_UINT32)opj_int_ceildiv(
p_end_x - (OPJ_INT32)l_cp->tx0, (OPJ_INT32)l_cp->tdx);
p_image->x1 = (OPJ_UINT32)p_end_x;
}
/* Bottom */
if (p_end_y <= 0) {
opj_event_msg(p_manager, EVT_ERROR,
"Bottom position of the decoded area (region_y1=%d) should be > 0.\n",
p_end_y);
return OPJ_FALSE;
} else if ((OPJ_UINT32)p_end_y < l_image->y0) {
opj_event_msg(p_manager, EVT_ERROR,
"Bottom position of the decoded area (region_y1=%d) is outside the image area (YOsiz=%d).\n",
p_end_y, l_image->y0);
return OPJ_FALSE;
}
if ((OPJ_UINT32)p_end_y > l_image->y1) {
opj_event_msg(p_manager, EVT_WARNING,
"Bottom position of the decoded area (region_y1=%d) is outside the image area (Ysiz=%d).\n",
p_end_y, l_image->y1);
p_j2k->m_specific_param.m_decoder.m_end_tile_y = l_cp->th;
p_image->y1 = l_image->y1;
} else {
p_j2k->m_specific_param.m_decoder.m_end_tile_y = (OPJ_UINT32)opj_int_ceildiv(
p_end_y - (OPJ_INT32)l_cp->ty0, (OPJ_INT32)l_cp->tdy);
p_image->y1 = (OPJ_UINT32)p_end_y;
}
/* ----- */
p_j2k->m_specific_param.m_decoder.m_discard_tiles = 1;
l_img_comp = p_image->comps;
for (it_comp = 0; it_comp < p_image->numcomps; ++it_comp) {
OPJ_INT32 l_h, l_w;
l_img_comp->x0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->x0,
(OPJ_INT32)l_img_comp->dx);
l_img_comp->y0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->y0,
(OPJ_INT32)l_img_comp->dy);
l_comp_x1 = opj_int_ceildiv((OPJ_INT32)p_image->x1, (OPJ_INT32)l_img_comp->dx);
l_comp_y1 = opj_int_ceildiv((OPJ_INT32)p_image->y1, (OPJ_INT32)l_img_comp->dy);
l_w = opj_int_ceildivpow2(l_comp_x1, (OPJ_INT32)l_img_comp->factor)
- opj_int_ceildivpow2((OPJ_INT32)l_img_comp->x0, (OPJ_INT32)l_img_comp->factor);
if (l_w < 0) {
opj_event_msg(p_manager, EVT_ERROR,
"Size x of the decoded component image is incorrect (comp[%d].w=%d).\n",
it_comp, l_w);
return OPJ_FALSE;
}
l_img_comp->w = (OPJ_UINT32)l_w;
l_h = opj_int_ceildivpow2(l_comp_y1, (OPJ_INT32)l_img_comp->factor)
- opj_int_ceildivpow2((OPJ_INT32)l_img_comp->y0, (OPJ_INT32)l_img_comp->factor);
if (l_h < 0) {
opj_event_msg(p_manager, EVT_ERROR,
"Size y of the decoded component image is incorrect (comp[%d].h=%d).\n",
it_comp, l_h);
return OPJ_FALSE;
}
l_img_comp->h = (OPJ_UINT32)l_h;
l_img_comp++;
}
opj_event_msg(p_manager, EVT_INFO, "Setting decoding area to %d,%d,%d,%d\n",
p_image->x0, p_image->y0, p_image->x1, p_image->y1);
return OPJ_TRUE;
}
opj_j2k_t* opj_j2k_create_decompress(void)
{
opj_j2k_t *l_j2k = (opj_j2k_t*) opj_calloc(1, sizeof(opj_j2k_t));
if (!l_j2k) {
return 00;
}
l_j2k->m_is_decoder = 1;
l_j2k->m_cp.m_is_decoder = 1;
/* in the absence of JP2 boxes, consider different bit depth / sign */
/* per component is allowed */
l_j2k->m_cp.allow_different_bit_depth_sign = 1;
#ifdef OPJ_DISABLE_TPSOT_FIX
l_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction_checked = 1;
#endif
l_j2k->m_specific_param.m_decoder.m_default_tcp = (opj_tcp_t*) opj_calloc(1,
sizeof(opj_tcp_t));
if (!l_j2k->m_specific_param.m_decoder.m_default_tcp) {
opj_j2k_destroy(l_j2k);
return 00;
}
l_j2k->m_specific_param.m_decoder.m_header_data = (OPJ_BYTE *) opj_calloc(1,
OPJ_J2K_DEFAULT_HEADER_SIZE);
if (! l_j2k->m_specific_param.m_decoder.m_header_data) {
opj_j2k_destroy(l_j2k);
return 00;
}
l_j2k->m_specific_param.m_decoder.m_header_data_size =
OPJ_J2K_DEFAULT_HEADER_SIZE;
l_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec = -1 ;
l_j2k->m_specific_param.m_decoder.m_last_sot_read_pos = 0 ;
/* codestream index creation */
l_j2k->cstr_index = opj_j2k_create_cstr_index();
if (!l_j2k->cstr_index) {
opj_j2k_destroy(l_j2k);
return 00;
}
/* validation list creation */
l_j2k->m_validation_list = opj_procedure_list_create();
if (! l_j2k->m_validation_list) {
opj_j2k_destroy(l_j2k);
return 00;
}
/* execution list creation */
l_j2k->m_procedure_list = opj_procedure_list_create();
if (! l_j2k->m_procedure_list) {
opj_j2k_destroy(l_j2k);
return 00;
}
l_j2k->m_tp = opj_thread_pool_create(opj_j2k_get_default_thread_count());
if (!l_j2k->m_tp) {
l_j2k->m_tp = opj_thread_pool_create(0);
}
if (!l_j2k->m_tp) {
opj_j2k_destroy(l_j2k);
return NULL;
}
return l_j2k;
}
static opj_codestream_index_t* opj_j2k_create_cstr_index(void)
{
opj_codestream_index_t* cstr_index = (opj_codestream_index_t*)
opj_calloc(1, sizeof(opj_codestream_index_t));
if (!cstr_index) {
return NULL;
}
cstr_index->maxmarknum = 100;
cstr_index->marknum = 0;
cstr_index->marker = (opj_marker_info_t*)
opj_calloc(cstr_index->maxmarknum, sizeof(opj_marker_info_t));
if (!cstr_index-> marker) {
opj_free(cstr_index);
return NULL;
}
cstr_index->tile_index = NULL;
return cstr_index;
}
static OPJ_UINT32 opj_j2k_get_SPCod_SPCoc_size(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no)
{
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_tccp_t *l_tccp = 00;
/* preconditions */
assert(p_j2k != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_tile_no];
l_tccp = &l_tcp->tccps[p_comp_no];
/* preconditions again */
assert(p_tile_no < (l_cp->tw * l_cp->th));
assert(p_comp_no < p_j2k->m_private_image->numcomps);
if (l_tccp->csty & J2K_CCP_CSTY_PRT) {
return 5 + l_tccp->numresolutions;
} else {
return 5;
}
}
static OPJ_BOOL opj_j2k_compare_SPCod_SPCoc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no)
{
OPJ_UINT32 i;
opj_cp_t *l_cp = NULL;
opj_tcp_t *l_tcp = NULL;
opj_tccp_t *l_tccp0 = NULL;
opj_tccp_t *l_tccp1 = NULL;
/* preconditions */
assert(p_j2k != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_tile_no];
l_tccp0 = &l_tcp->tccps[p_first_comp_no];
l_tccp1 = &l_tcp->tccps[p_second_comp_no];
if (l_tccp0->numresolutions != l_tccp1->numresolutions) {
return OPJ_FALSE;
}
if (l_tccp0->cblkw != l_tccp1->cblkw) {
return OPJ_FALSE;
}
if (l_tccp0->cblkh != l_tccp1->cblkh) {
return OPJ_FALSE;
}
if (l_tccp0->cblksty != l_tccp1->cblksty) {
return OPJ_FALSE;
}
if (l_tccp0->qmfbid != l_tccp1->qmfbid) {
return OPJ_FALSE;
}
if ((l_tccp0->csty & J2K_CCP_CSTY_PRT) != (l_tccp1->csty & J2K_CCP_CSTY_PRT)) {
return OPJ_FALSE;
}
for (i = 0U; i < l_tccp0->numresolutions; ++i) {
if (l_tccp0->prcw[i] != l_tccp1->prcw[i]) {
return OPJ_FALSE;
}
if (l_tccp0->prch[i] != l_tccp1->prch[i]) {
return OPJ_FALSE;
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_SPCod_SPCoc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_header_size,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 i;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_tccp_t *l_tccp = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_header_size != 00);
assert(p_manager != 00);
assert(p_data != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_tile_no];
l_tccp = &l_tcp->tccps[p_comp_no];
/* preconditions again */
assert(p_tile_no < (l_cp->tw * l_cp->th));
assert(p_comp_no < (p_j2k->m_private_image->numcomps));
if (*p_header_size < 5) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing SPCod SPCoc element\n");
return OPJ_FALSE;
}
opj_write_bytes(p_data, l_tccp->numresolutions - 1, 1); /* SPcoc (D) */
++p_data;
opj_write_bytes(p_data, l_tccp->cblkw - 2, 1); /* SPcoc (E) */
++p_data;
opj_write_bytes(p_data, l_tccp->cblkh - 2, 1); /* SPcoc (F) */
++p_data;
opj_write_bytes(p_data, l_tccp->cblksty,
1); /* SPcoc (G) */
++p_data;
opj_write_bytes(p_data, l_tccp->qmfbid,
1); /* SPcoc (H) */
++p_data;
*p_header_size = *p_header_size - 5;
if (l_tccp->csty & J2K_CCP_CSTY_PRT) {
if (*p_header_size < l_tccp->numresolutions) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing SPCod SPCoc element\n");
return OPJ_FALSE;
}
for (i = 0; i < l_tccp->numresolutions; ++i) {
opj_write_bytes(p_data, l_tccp->prcw[i] + (l_tccp->prch[i] << 4),
1); /* SPcoc (I_i) */
++p_data;
}
*p_header_size = *p_header_size - l_tccp->numresolutions;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_read_SPCod_SPCoc(opj_j2k_t *p_j2k,
OPJ_UINT32 compno,
OPJ_BYTE * p_header_data,
OPJ_UINT32 * p_header_size,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 i, l_tmp;
opj_cp_t *l_cp = NULL;
opj_tcp_t *l_tcp = NULL;
opj_tccp_t *l_tccp = NULL;
OPJ_BYTE * l_current_ptr = NULL;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_header_data != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
/* precondition again */
assert(compno < p_j2k->m_private_image->numcomps);
l_tccp = &l_tcp->tccps[compno];
l_current_ptr = p_header_data;
/* make sure room is sufficient */
if (*p_header_size < 5) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading SPCod SPCoc element\n");
return OPJ_FALSE;
}
opj_read_bytes(l_current_ptr, &l_tccp->numresolutions,
1); /* SPcox (D) */
++l_tccp->numresolutions; /* tccp->numresolutions = read() + 1 */
if (l_tccp->numresolutions > OPJ_J2K_MAXRLVLS) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid value for numresolutions : %d, max value is set in openjpeg.h at %d\n",
l_tccp->numresolutions, OPJ_J2K_MAXRLVLS);
return OPJ_FALSE;
}
++l_current_ptr;
/* If user wants to remove more resolutions than the codestream contains, return error */
if (l_cp->m_specific_param.m_dec.m_reduce >= l_tccp->numresolutions) {
opj_event_msg(p_manager, EVT_ERROR,
"Error decoding component %d.\nThe number of resolutions to remove is higher than the number "
"of resolutions of this component\nModify the cp_reduce parameter.\n\n",
compno);
p_j2k->m_specific_param.m_decoder.m_state |=
0x8000;/* FIXME J2K_DEC_STATE_ERR;*/
return OPJ_FALSE;
}
opj_read_bytes(l_current_ptr, &l_tccp->cblkw, 1); /* SPcoc (E) */
++l_current_ptr;
l_tccp->cblkw += 2;
opj_read_bytes(l_current_ptr, &l_tccp->cblkh, 1); /* SPcoc (F) */
++l_current_ptr;
l_tccp->cblkh += 2;
if ((l_tccp->cblkw > 10) || (l_tccp->cblkh > 10) ||
((l_tccp->cblkw + l_tccp->cblkh) > 12)) {
opj_event_msg(p_manager, EVT_ERROR,
"Error reading SPCod SPCoc element, Invalid cblkw/cblkh combination\n");
return OPJ_FALSE;
}
opj_read_bytes(l_current_ptr, &l_tccp->cblksty, 1); /* SPcoc (G) */
++l_current_ptr;
if (l_tccp->cblksty & 0xC0U) { /* 2 msb are reserved, assume we can't read */
opj_event_msg(p_manager, EVT_ERROR,
"Error reading SPCod SPCoc element, Invalid code-block style found\n");
return OPJ_FALSE;
}
opj_read_bytes(l_current_ptr, &l_tccp->qmfbid, 1); /* SPcoc (H) */
++l_current_ptr;
*p_header_size = *p_header_size - 5;
/* use custom precinct size ? */
if (l_tccp->csty & J2K_CCP_CSTY_PRT) {
if (*p_header_size < l_tccp->numresolutions) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading SPCod SPCoc element\n");
return OPJ_FALSE;
}
for (i = 0; i < l_tccp->numresolutions; ++i) {
opj_read_bytes(l_current_ptr, &l_tmp, 1); /* SPcoc (I_i) */
++l_current_ptr;
/* Precinct exponent 0 is only allowed for lowest resolution level (Table A.21) */
if ((i != 0) && (((l_tmp & 0xf) == 0) || ((l_tmp >> 4) == 0))) {
opj_event_msg(p_manager, EVT_ERROR, "Invalid precinct size\n");
return OPJ_FALSE;
}
l_tccp->prcw[i] = l_tmp & 0xf;
l_tccp->prch[i] = l_tmp >> 4;
}
*p_header_size = *p_header_size - l_tccp->numresolutions;
} else {
/* set default size for the precinct width and height */
for (i = 0; i < l_tccp->numresolutions; ++i) {
l_tccp->prcw[i] = 15;
l_tccp->prch[i] = 15;
}
}
#ifdef WIP_REMOVE_MSD
/* INDEX >> */
if (p_j2k->cstr_info && compno == 0) {
OPJ_UINT32 l_data_size = l_tccp->numresolutions * sizeof(OPJ_UINT32);
p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].cblkh =
l_tccp->cblkh;
p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].cblkw =
l_tccp->cblkw;
p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].numresolutions
= l_tccp->numresolutions;
p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].cblksty =
l_tccp->cblksty;
p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].qmfbid =
l_tccp->qmfbid;
memcpy(p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].pdx, l_tccp->prcw,
l_data_size);
memcpy(p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].pdy, l_tccp->prch,
l_data_size);
}
/* << INDEX */
#endif
return OPJ_TRUE;
}
static void opj_j2k_copy_tile_component_parameters(opj_j2k_t *p_j2k)
{
/* loop */
OPJ_UINT32 i;
opj_cp_t *l_cp = NULL;
opj_tcp_t *l_tcp = NULL;
opj_tccp_t *l_ref_tccp = NULL, *l_copied_tccp = NULL;
OPJ_UINT32 l_prc_size;
/* preconditions */
assert(p_j2k != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH)
?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
l_ref_tccp = &l_tcp->tccps[0];
l_copied_tccp = l_ref_tccp + 1;
l_prc_size = l_ref_tccp->numresolutions * (OPJ_UINT32)sizeof(OPJ_UINT32);
for (i = 1; i < p_j2k->m_private_image->numcomps; ++i) {
l_copied_tccp->numresolutions = l_ref_tccp->numresolutions;
l_copied_tccp->cblkw = l_ref_tccp->cblkw;
l_copied_tccp->cblkh = l_ref_tccp->cblkh;
l_copied_tccp->cblksty = l_ref_tccp->cblksty;
l_copied_tccp->qmfbid = l_ref_tccp->qmfbid;
memcpy(l_copied_tccp->prcw, l_ref_tccp->prcw, l_prc_size);
memcpy(l_copied_tccp->prch, l_ref_tccp->prch, l_prc_size);
++l_copied_tccp;
}
}
static OPJ_UINT32 opj_j2k_get_SQcd_SQcc_size(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no)
{
OPJ_UINT32 l_num_bands;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_tccp_t *l_tccp = 00;
/* preconditions */
assert(p_j2k != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_tile_no];
l_tccp = &l_tcp->tccps[p_comp_no];
/* preconditions again */
assert(p_tile_no < l_cp->tw * l_cp->th);
assert(p_comp_no < p_j2k->m_private_image->numcomps);
l_num_bands = (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 1 :
(l_tccp->numresolutions * 3 - 2);
if (l_tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) {
return 1 + l_num_bands;
} else {
return 1 + 2 * l_num_bands;
}
}
static OPJ_BOOL opj_j2k_compare_SQcd_SQcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no)
{
opj_cp_t *l_cp = NULL;
opj_tcp_t *l_tcp = NULL;
opj_tccp_t *l_tccp0 = NULL;
opj_tccp_t *l_tccp1 = NULL;
OPJ_UINT32 l_band_no, l_num_bands;
/* preconditions */
assert(p_j2k != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_tile_no];
l_tccp0 = &l_tcp->tccps[p_first_comp_no];
l_tccp1 = &l_tcp->tccps[p_second_comp_no];
if (l_tccp0->qntsty != l_tccp1->qntsty) {
return OPJ_FALSE;
}
if (l_tccp0->numgbits != l_tccp1->numgbits) {
return OPJ_FALSE;
}
if (l_tccp0->qntsty == J2K_CCP_QNTSTY_SIQNT) {
l_num_bands = 1U;
} else {
l_num_bands = l_tccp0->numresolutions * 3U - 2U;
if (l_num_bands != (l_tccp1->numresolutions * 3U - 2U)) {
return OPJ_FALSE;
}
}
for (l_band_no = 0; l_band_no < l_num_bands; ++l_band_no) {
if (l_tccp0->stepsizes[l_band_no].expn != l_tccp1->stepsizes[l_band_no].expn) {
return OPJ_FALSE;
}
}
if (l_tccp0->qntsty != J2K_CCP_QNTSTY_NOQNT) {
for (l_band_no = 0; l_band_no < l_num_bands; ++l_band_no) {
if (l_tccp0->stepsizes[l_band_no].mant != l_tccp1->stepsizes[l_band_no].mant) {
return OPJ_FALSE;
}
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_SQcd_SQcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_header_size,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 l_header_size;
OPJ_UINT32 l_band_no, l_num_bands;
OPJ_UINT32 l_expn, l_mant;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_tccp_t *l_tccp = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_header_size != 00);
assert(p_manager != 00);
assert(p_data != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_tile_no];
l_tccp = &l_tcp->tccps[p_comp_no];
/* preconditions again */
assert(p_tile_no < l_cp->tw * l_cp->th);
assert(p_comp_no < p_j2k->m_private_image->numcomps);
l_num_bands = (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 1 :
(l_tccp->numresolutions * 3 - 2);
if (l_tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) {
l_header_size = 1 + l_num_bands;
if (*p_header_size < l_header_size) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing SQcd SQcc element\n");
return OPJ_FALSE;
}
opj_write_bytes(p_data, l_tccp->qntsty + (l_tccp->numgbits << 5),
1); /* Sqcx */
++p_data;
for (l_band_no = 0; l_band_no < l_num_bands; ++l_band_no) {
l_expn = (OPJ_UINT32)l_tccp->stepsizes[l_band_no].expn;
opj_write_bytes(p_data, l_expn << 3, 1); /* SPqcx_i */
++p_data;
}
} else {
l_header_size = 1 + 2 * l_num_bands;
if (*p_header_size < l_header_size) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing SQcd SQcc element\n");
return OPJ_FALSE;
}
opj_write_bytes(p_data, l_tccp->qntsty + (l_tccp->numgbits << 5),
1); /* Sqcx */
++p_data;
for (l_band_no = 0; l_band_no < l_num_bands; ++l_band_no) {
l_expn = (OPJ_UINT32)l_tccp->stepsizes[l_band_no].expn;
l_mant = (OPJ_UINT32)l_tccp->stepsizes[l_band_no].mant;
opj_write_bytes(p_data, (l_expn << 11) + l_mant, 2); /* SPqcx_i */
p_data += 2;
}
}
*p_header_size = *p_header_size - l_header_size;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_read_SQcd_SQcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
OPJ_BYTE* p_header_data,
OPJ_UINT32 * p_header_size,
opj_event_mgr_t * p_manager
)
{
/* loop*/
OPJ_UINT32 l_band_no;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_tccp_t *l_tccp = 00;
OPJ_BYTE * l_current_ptr = 00;
OPJ_UINT32 l_tmp, l_num_band;
/* preconditions*/
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_header_data != 00);
l_cp = &(p_j2k->m_cp);
/* come from tile part header or main header ?*/
l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH)
?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
/* precondition again*/
assert(p_comp_no < p_j2k->m_private_image->numcomps);
l_tccp = &l_tcp->tccps[p_comp_no];
l_current_ptr = p_header_data;
if (*p_header_size < 1) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading SQcd or SQcc element\n");
return OPJ_FALSE;
}
*p_header_size -= 1;
opj_read_bytes(l_current_ptr, &l_tmp, 1); /* Sqcx */
++l_current_ptr;
l_tccp->qntsty = l_tmp & 0x1f;
l_tccp->numgbits = l_tmp >> 5;
if (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) {
l_num_band = 1;
} else {
l_num_band = (l_tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) ?
(*p_header_size) :
(*p_header_size) / 2;
if (l_num_band > OPJ_J2K_MAXBANDS) {
opj_event_msg(p_manager, EVT_WARNING,
"While reading CCP_QNTSTY element inside QCD or QCC marker segment, "
"number of subbands (%d) is greater to OPJ_J2K_MAXBANDS (%d). So we limit the number of elements stored to "
"OPJ_J2K_MAXBANDS (%d) and skip the rest. \n", l_num_band, OPJ_J2K_MAXBANDS,
OPJ_J2K_MAXBANDS);
/*return OPJ_FALSE;*/
}
}
#ifdef USE_JPWL
if (l_cp->correct) {
/* if JPWL is on, we check whether there are too many subbands */
if (/*(l_num_band < 0) ||*/ (l_num_band >= OPJ_J2K_MAXBANDS)) {
opj_event_msg(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
"JPWL: bad number of subbands in Sqcx (%d)\n",
l_num_band);
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
/* we try to correct */
l_num_band = 1;
opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust them\n"
"- setting number of bands to %d => HYPOTHESIS!!!\n",
l_num_band);
};
};
#endif /* USE_JPWL */
if (l_tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) {
for (l_band_no = 0; l_band_no < l_num_band; l_band_no++) {
opj_read_bytes(l_current_ptr, &l_tmp, 1); /* SPqcx_i */
++l_current_ptr;
if (l_band_no < OPJ_J2K_MAXBANDS) {
l_tccp->stepsizes[l_band_no].expn = (OPJ_INT32)(l_tmp >> 3);
l_tccp->stepsizes[l_band_no].mant = 0;
}
}
*p_header_size = *p_header_size - l_num_band;
} else {
for (l_band_no = 0; l_band_no < l_num_band; l_band_no++) {
opj_read_bytes(l_current_ptr, &l_tmp, 2); /* SPqcx_i */
l_current_ptr += 2;
if (l_band_no < OPJ_J2K_MAXBANDS) {
l_tccp->stepsizes[l_band_no].expn = (OPJ_INT32)(l_tmp >> 11);
l_tccp->stepsizes[l_band_no].mant = l_tmp & 0x7ff;
}
}
*p_header_size = *p_header_size - 2 * l_num_band;
}
/* Add Antonin : if scalar_derived -> compute other stepsizes */
if (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) {
for (l_band_no = 1; l_band_no < OPJ_J2K_MAXBANDS; l_band_no++) {
l_tccp->stepsizes[l_band_no].expn =
((OPJ_INT32)(l_tccp->stepsizes[0].expn) - (OPJ_INT32)((l_band_no - 1) / 3) > 0)
?
(OPJ_INT32)(l_tccp->stepsizes[0].expn) - (OPJ_INT32)((l_band_no - 1) / 3) : 0;
l_tccp->stepsizes[l_band_no].mant = l_tccp->stepsizes[0].mant;
}
}
return OPJ_TRUE;
}
static void opj_j2k_copy_tile_quantization_parameters(opj_j2k_t *p_j2k)
{
OPJ_UINT32 i;
opj_cp_t *l_cp = NULL;
opj_tcp_t *l_tcp = NULL;
opj_tccp_t *l_ref_tccp = NULL;
opj_tccp_t *l_copied_tccp = NULL;
OPJ_UINT32 l_size;
/* preconditions */
assert(p_j2k != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH ?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
l_ref_tccp = &l_tcp->tccps[0];
l_copied_tccp = l_ref_tccp + 1;
l_size = OPJ_J2K_MAXBANDS * sizeof(opj_stepsize_t);
for (i = 1; i < p_j2k->m_private_image->numcomps; ++i) {
l_copied_tccp->qntsty = l_ref_tccp->qntsty;
l_copied_tccp->numgbits = l_ref_tccp->numgbits;
memcpy(l_copied_tccp->stepsizes, l_ref_tccp->stepsizes, l_size);
++l_copied_tccp;
}
}
static void opj_j2k_dump_tile_info(opj_tcp_t * l_default_tile,
OPJ_INT32 numcomps, FILE* out_stream)
{
if (l_default_tile) {
OPJ_INT32 compno;
fprintf(out_stream, "\t default tile {\n");
fprintf(out_stream, "\t\t csty=%#x\n", l_default_tile->csty);
fprintf(out_stream, "\t\t prg=%#x\n", l_default_tile->prg);
fprintf(out_stream, "\t\t numlayers=%d\n", l_default_tile->numlayers);
fprintf(out_stream, "\t\t mct=%x\n", l_default_tile->mct);
for (compno = 0; compno < numcomps; compno++) {
opj_tccp_t *l_tccp = &(l_default_tile->tccps[compno]);
OPJ_UINT32 resno;
OPJ_INT32 bandno, numbands;
/* coding style*/
fprintf(out_stream, "\t\t comp %d {\n", compno);
fprintf(out_stream, "\t\t\t csty=%#x\n", l_tccp->csty);
fprintf(out_stream, "\t\t\t numresolutions=%d\n", l_tccp->numresolutions);
fprintf(out_stream, "\t\t\t cblkw=2^%d\n", l_tccp->cblkw);
fprintf(out_stream, "\t\t\t cblkh=2^%d\n", l_tccp->cblkh);
fprintf(out_stream, "\t\t\t cblksty=%#x\n", l_tccp->cblksty);
fprintf(out_stream, "\t\t\t qmfbid=%d\n", l_tccp->qmfbid);
fprintf(out_stream, "\t\t\t preccintsize (w,h)=");
for (resno = 0; resno < l_tccp->numresolutions; resno++) {
fprintf(out_stream, "(%d,%d) ", l_tccp->prcw[resno], l_tccp->prch[resno]);
}
fprintf(out_stream, "\n");
/* quantization style*/
fprintf(out_stream, "\t\t\t qntsty=%d\n", l_tccp->qntsty);
fprintf(out_stream, "\t\t\t numgbits=%d\n", l_tccp->numgbits);
fprintf(out_stream, "\t\t\t stepsizes (m,e)=");
numbands = (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 1 :
(OPJ_INT32)l_tccp->numresolutions * 3 - 2;
for (bandno = 0; bandno < numbands; bandno++) {
fprintf(out_stream, "(%d,%d) ", l_tccp->stepsizes[bandno].mant,
l_tccp->stepsizes[bandno].expn);
}
fprintf(out_stream, "\n");
/* RGN value*/
fprintf(out_stream, "\t\t\t roishift=%d\n", l_tccp->roishift);
fprintf(out_stream, "\t\t }\n");
} /*end of component of default tile*/
fprintf(out_stream, "\t }\n"); /*end of default tile*/
}
}
void j2k_dump(opj_j2k_t* p_j2k, OPJ_INT32 flag, FILE* out_stream)
{
/* Check if the flag is compatible with j2k file*/
if ((flag & OPJ_JP2_INFO) || (flag & OPJ_JP2_IND)) {
fprintf(out_stream, "Wrong flag\n");
return;
}
/* Dump the image_header */
if (flag & OPJ_IMG_INFO) {
if (p_j2k->m_private_image) {
j2k_dump_image_header(p_j2k->m_private_image, 0, out_stream);
}
}
/* Dump the codestream info from main header */
if (flag & OPJ_J2K_MH_INFO) {
if (p_j2k->m_private_image) {
opj_j2k_dump_MH_info(p_j2k, out_stream);
}
}
/* Dump all tile/codestream info */
if (flag & OPJ_J2K_TCH_INFO) {
OPJ_UINT32 l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
OPJ_UINT32 i;
opj_tcp_t * l_tcp = p_j2k->m_cp.tcps;
if (p_j2k->m_private_image) {
for (i = 0; i < l_nb_tiles; ++i) {
opj_j2k_dump_tile_info(l_tcp, (OPJ_INT32)p_j2k->m_private_image->numcomps,
out_stream);
++l_tcp;
}
}
}
/* Dump the codestream info of the current tile */
if (flag & OPJ_J2K_TH_INFO) {
}
/* Dump the codestream index from main header */
if (flag & OPJ_J2K_MH_IND) {
opj_j2k_dump_MH_index(p_j2k, out_stream);
}
/* Dump the codestream index of the current tile */
if (flag & OPJ_J2K_TH_IND) {
}
}
static void opj_j2k_dump_MH_index(opj_j2k_t* p_j2k, FILE* out_stream)
{
opj_codestream_index_t* cstr_index = p_j2k->cstr_index;
OPJ_UINT32 it_marker, it_tile, it_tile_part;
fprintf(out_stream, "Codestream index from main header: {\n");
fprintf(out_stream, "\t Main header start position=%" PRIi64 "\n"
"\t Main header end position=%" PRIi64 "\n",
cstr_index->main_head_start, cstr_index->main_head_end);
fprintf(out_stream, "\t Marker list: {\n");
if (cstr_index->marker) {
for (it_marker = 0; it_marker < cstr_index->marknum ; it_marker++) {
fprintf(out_stream, "\t\t type=%#x, pos=%" PRIi64 ", len=%d\n",
cstr_index->marker[it_marker].type,
cstr_index->marker[it_marker].pos,
cstr_index->marker[it_marker].len);
}
}
fprintf(out_stream, "\t }\n");
if (cstr_index->tile_index) {
/* Simple test to avoid to write empty information*/
OPJ_UINT32 l_acc_nb_of_tile_part = 0;
for (it_tile = 0; it_tile < cstr_index->nb_of_tiles ; it_tile++) {
l_acc_nb_of_tile_part += cstr_index->tile_index[it_tile].nb_tps;
}
if (l_acc_nb_of_tile_part) {
fprintf(out_stream, "\t Tile index: {\n");
for (it_tile = 0; it_tile < cstr_index->nb_of_tiles ; it_tile++) {
OPJ_UINT32 nb_of_tile_part = cstr_index->tile_index[it_tile].nb_tps;
fprintf(out_stream, "\t\t nb of tile-part in tile [%d]=%d\n", it_tile,
nb_of_tile_part);
if (cstr_index->tile_index[it_tile].tp_index) {
for (it_tile_part = 0; it_tile_part < nb_of_tile_part; it_tile_part++) {
fprintf(out_stream, "\t\t\t tile-part[%d]: star_pos=%" PRIi64 ", end_header=%"
PRIi64 ", end_pos=%" PRIi64 ".\n",
it_tile_part,
cstr_index->tile_index[it_tile].tp_index[it_tile_part].start_pos,
cstr_index->tile_index[it_tile].tp_index[it_tile_part].end_header,
cstr_index->tile_index[it_tile].tp_index[it_tile_part].end_pos);
}
}
if (cstr_index->tile_index[it_tile].marker) {
for (it_marker = 0; it_marker < cstr_index->tile_index[it_tile].marknum ;
it_marker++) {
fprintf(out_stream, "\t\t type=%#x, pos=%" PRIi64 ", len=%d\n",
cstr_index->tile_index[it_tile].marker[it_marker].type,
cstr_index->tile_index[it_tile].marker[it_marker].pos,
cstr_index->tile_index[it_tile].marker[it_marker].len);
}
}
}
fprintf(out_stream, "\t }\n");
}
}
fprintf(out_stream, "}\n");
}
static void opj_j2k_dump_MH_info(opj_j2k_t* p_j2k, FILE* out_stream)
{
fprintf(out_stream, "Codestream info from main header: {\n");
fprintf(out_stream, "\t tx0=%d, ty0=%d\n", p_j2k->m_cp.tx0, p_j2k->m_cp.ty0);
fprintf(out_stream, "\t tdx=%d, tdy=%d\n", p_j2k->m_cp.tdx, p_j2k->m_cp.tdy);
fprintf(out_stream, "\t tw=%d, th=%d\n", p_j2k->m_cp.tw, p_j2k->m_cp.th);
opj_j2k_dump_tile_info(p_j2k->m_specific_param.m_decoder.m_default_tcp,
(OPJ_INT32)p_j2k->m_private_image->numcomps, out_stream);
fprintf(out_stream, "}\n");
}
void j2k_dump_image_header(opj_image_t* img_header, OPJ_BOOL dev_dump_flag,
FILE* out_stream)
{
char tab[2];
if (dev_dump_flag) {
fprintf(stdout, "[DEV] Dump an image_header struct {\n");
tab[0] = '\0';
} else {
fprintf(out_stream, "Image info {\n");
tab[0] = '\t';
tab[1] = '\0';
}
fprintf(out_stream, "%s x0=%d, y0=%d\n", tab, img_header->x0, img_header->y0);
fprintf(out_stream, "%s x1=%d, y1=%d\n", tab, img_header->x1,
img_header->y1);
fprintf(out_stream, "%s numcomps=%d\n", tab, img_header->numcomps);
if (img_header->comps) {
OPJ_UINT32 compno;
for (compno = 0; compno < img_header->numcomps; compno++) {
fprintf(out_stream, "%s\t component %d {\n", tab, compno);
j2k_dump_image_comp_header(&(img_header->comps[compno]), dev_dump_flag,
out_stream);
fprintf(out_stream, "%s}\n", tab);
}
}
fprintf(out_stream, "}\n");
}
void j2k_dump_image_comp_header(opj_image_comp_t* comp_header,
OPJ_BOOL dev_dump_flag, FILE* out_stream)
{
char tab[3];
if (dev_dump_flag) {
fprintf(stdout, "[DEV] Dump an image_comp_header struct {\n");
tab[0] = '\0';
} else {
tab[0] = '\t';
tab[1] = '\t';
tab[2] = '\0';
}
fprintf(out_stream, "%s dx=%d, dy=%d\n", tab, comp_header->dx, comp_header->dy);
fprintf(out_stream, "%s prec=%d\n", tab, comp_header->prec);
fprintf(out_stream, "%s sgnd=%d\n", tab, comp_header->sgnd);
if (dev_dump_flag) {
fprintf(out_stream, "}\n");
}
}
opj_codestream_info_v2_t* j2k_get_cstr_info(opj_j2k_t* p_j2k)
{
OPJ_UINT32 compno;
OPJ_UINT32 numcomps = p_j2k->m_private_image->numcomps;
opj_tcp_t *l_default_tile;
opj_codestream_info_v2_t* cstr_info = (opj_codestream_info_v2_t*) opj_calloc(1,
sizeof(opj_codestream_info_v2_t));
if (!cstr_info) {
return NULL;
}
cstr_info->nbcomps = p_j2k->m_private_image->numcomps;
cstr_info->tx0 = p_j2k->m_cp.tx0;
cstr_info->ty0 = p_j2k->m_cp.ty0;
cstr_info->tdx = p_j2k->m_cp.tdx;
cstr_info->tdy = p_j2k->m_cp.tdy;
cstr_info->tw = p_j2k->m_cp.tw;
cstr_info->th = p_j2k->m_cp.th;
cstr_info->tile_info = NULL; /* Not fill from the main header*/
l_default_tile = p_j2k->m_specific_param.m_decoder.m_default_tcp;
cstr_info->m_default_tile_info.csty = l_default_tile->csty;
cstr_info->m_default_tile_info.prg = l_default_tile->prg;
cstr_info->m_default_tile_info.numlayers = l_default_tile->numlayers;
cstr_info->m_default_tile_info.mct = l_default_tile->mct;
cstr_info->m_default_tile_info.tccp_info = (opj_tccp_info_t*) opj_calloc(
cstr_info->nbcomps, sizeof(opj_tccp_info_t));
if (!cstr_info->m_default_tile_info.tccp_info) {
opj_destroy_cstr_info(&cstr_info);
return NULL;
}
for (compno = 0; compno < numcomps; compno++) {
opj_tccp_t *l_tccp = &(l_default_tile->tccps[compno]);
opj_tccp_info_t *l_tccp_info = &
(cstr_info->m_default_tile_info.tccp_info[compno]);
OPJ_INT32 bandno, numbands;
/* coding style*/
l_tccp_info->csty = l_tccp->csty;
l_tccp_info->numresolutions = l_tccp->numresolutions;
l_tccp_info->cblkw = l_tccp->cblkw;
l_tccp_info->cblkh = l_tccp->cblkh;
l_tccp_info->cblksty = l_tccp->cblksty;
l_tccp_info->qmfbid = l_tccp->qmfbid;
if (l_tccp->numresolutions < OPJ_J2K_MAXRLVLS) {
memcpy(l_tccp_info->prch, l_tccp->prch, l_tccp->numresolutions);
memcpy(l_tccp_info->prcw, l_tccp->prcw, l_tccp->numresolutions);
}
/* quantization style*/
l_tccp_info->qntsty = l_tccp->qntsty;
l_tccp_info->numgbits = l_tccp->numgbits;
numbands = (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 1 :
(OPJ_INT32)l_tccp->numresolutions * 3 - 2;
if (numbands < OPJ_J2K_MAXBANDS) {
for (bandno = 0; bandno < numbands; bandno++) {
l_tccp_info->stepsizes_mant[bandno] = (OPJ_UINT32)
l_tccp->stepsizes[bandno].mant;
l_tccp_info->stepsizes_expn[bandno] = (OPJ_UINT32)
l_tccp->stepsizes[bandno].expn;
}
}
/* RGN value*/
l_tccp_info->roishift = l_tccp->roishift;
}
return cstr_info;
}
opj_codestream_index_t* j2k_get_cstr_index(opj_j2k_t* p_j2k)
{
opj_codestream_index_t* l_cstr_index = (opj_codestream_index_t*)
opj_calloc(1, sizeof(opj_codestream_index_t));
if (!l_cstr_index) {
return NULL;
}
l_cstr_index->main_head_start = p_j2k->cstr_index->main_head_start;
l_cstr_index->main_head_end = p_j2k->cstr_index->main_head_end;
l_cstr_index->codestream_size = p_j2k->cstr_index->codestream_size;
l_cstr_index->marknum = p_j2k->cstr_index->marknum;
l_cstr_index->marker = (opj_marker_info_t*)opj_malloc(l_cstr_index->marknum *
sizeof(opj_marker_info_t));
if (!l_cstr_index->marker) {
opj_free(l_cstr_index);
return NULL;
}
if (p_j2k->cstr_index->marker) {
memcpy(l_cstr_index->marker, p_j2k->cstr_index->marker,
l_cstr_index->marknum * sizeof(opj_marker_info_t));
} else {
opj_free(l_cstr_index->marker);
l_cstr_index->marker = NULL;
}
l_cstr_index->nb_of_tiles = p_j2k->cstr_index->nb_of_tiles;
l_cstr_index->tile_index = (opj_tile_index_t*)opj_calloc(
l_cstr_index->nb_of_tiles, sizeof(opj_tile_index_t));
if (!l_cstr_index->tile_index) {
opj_free(l_cstr_index->marker);
opj_free(l_cstr_index);
return NULL;
}
if (!p_j2k->cstr_index->tile_index) {
opj_free(l_cstr_index->tile_index);
l_cstr_index->tile_index = NULL;
} else {
OPJ_UINT32 it_tile = 0;
for (it_tile = 0; it_tile < l_cstr_index->nb_of_tiles; it_tile++) {
/* Tile Marker*/
l_cstr_index->tile_index[it_tile].marknum =
p_j2k->cstr_index->tile_index[it_tile].marknum;
l_cstr_index->tile_index[it_tile].marker =
(opj_marker_info_t*)opj_malloc(l_cstr_index->tile_index[it_tile].marknum *
sizeof(opj_marker_info_t));
if (!l_cstr_index->tile_index[it_tile].marker) {
OPJ_UINT32 it_tile_free;
for (it_tile_free = 0; it_tile_free < it_tile; it_tile_free++) {
opj_free(l_cstr_index->tile_index[it_tile_free].marker);
}
opj_free(l_cstr_index->tile_index);
opj_free(l_cstr_index->marker);
opj_free(l_cstr_index);
return NULL;
}
if (p_j2k->cstr_index->tile_index[it_tile].marker)
memcpy(l_cstr_index->tile_index[it_tile].marker,
p_j2k->cstr_index->tile_index[it_tile].marker,
l_cstr_index->tile_index[it_tile].marknum * sizeof(opj_marker_info_t));
else {
opj_free(l_cstr_index->tile_index[it_tile].marker);
l_cstr_index->tile_index[it_tile].marker = NULL;
}
/* Tile part index*/
l_cstr_index->tile_index[it_tile].nb_tps =
p_j2k->cstr_index->tile_index[it_tile].nb_tps;
l_cstr_index->tile_index[it_tile].tp_index =
(opj_tp_index_t*)opj_malloc(l_cstr_index->tile_index[it_tile].nb_tps * sizeof(
opj_tp_index_t));
if (!l_cstr_index->tile_index[it_tile].tp_index) {
OPJ_UINT32 it_tile_free;
for (it_tile_free = 0; it_tile_free < it_tile; it_tile_free++) {
opj_free(l_cstr_index->tile_index[it_tile_free].marker);
opj_free(l_cstr_index->tile_index[it_tile_free].tp_index);
}
opj_free(l_cstr_index->tile_index);
opj_free(l_cstr_index->marker);
opj_free(l_cstr_index);
return NULL;
}
if (p_j2k->cstr_index->tile_index[it_tile].tp_index) {
memcpy(l_cstr_index->tile_index[it_tile].tp_index,
p_j2k->cstr_index->tile_index[it_tile].tp_index,
l_cstr_index->tile_index[it_tile].nb_tps * sizeof(opj_tp_index_t));
} else {
opj_free(l_cstr_index->tile_index[it_tile].tp_index);
l_cstr_index->tile_index[it_tile].tp_index = NULL;
}
/* Packet index (NOT USED)*/
l_cstr_index->tile_index[it_tile].nb_packet = 0;
l_cstr_index->tile_index[it_tile].packet_index = NULL;
}
}
return l_cstr_index;
}
static OPJ_BOOL opj_j2k_allocate_tile_element_cstr_index(opj_j2k_t *p_j2k)
{
OPJ_UINT32 it_tile = 0;
p_j2k->cstr_index->nb_of_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th;
p_j2k->cstr_index->tile_index = (opj_tile_index_t*)opj_calloc(
p_j2k->cstr_index->nb_of_tiles, sizeof(opj_tile_index_t));
if (!p_j2k->cstr_index->tile_index) {
return OPJ_FALSE;
}
for (it_tile = 0; it_tile < p_j2k->cstr_index->nb_of_tiles; it_tile++) {
p_j2k->cstr_index->tile_index[it_tile].maxmarknum = 100;
p_j2k->cstr_index->tile_index[it_tile].marknum = 0;
p_j2k->cstr_index->tile_index[it_tile].marker = (opj_marker_info_t*)
opj_calloc(p_j2k->cstr_index->tile_index[it_tile].maxmarknum,
sizeof(opj_marker_info_t));
if (!p_j2k->cstr_index->tile_index[it_tile].marker) {
return OPJ_FALSE;
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_decode_tiles(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_BOOL l_go_on = OPJ_TRUE;
OPJ_UINT32 l_current_tile_no;
OPJ_UINT32 l_data_size, l_max_data_size;
OPJ_INT32 l_tile_x0, l_tile_y0, l_tile_x1, l_tile_y1;
OPJ_UINT32 l_nb_comps;
OPJ_BYTE * l_current_data;
OPJ_UINT32 nr_tiles = 0;
/* Particular case for whole single tile decoding */
/* We can avoid allocating intermediate tile buffers */
if (p_j2k->m_cp.tw == 1 && p_j2k->m_cp.th == 1 &&
p_j2k->m_cp.tx0 == 0 && p_j2k->m_cp.ty0 == 0 &&
p_j2k->m_output_image->x0 == 0 &&
p_j2k->m_output_image->y0 == 0 &&
p_j2k->m_output_image->x1 == p_j2k->m_cp.tdx &&
p_j2k->m_output_image->y1 == p_j2k->m_cp.tdy &&
p_j2k->m_output_image->comps[0].factor == 0) {
OPJ_UINT32 i;
if (! opj_j2k_read_tile_header(p_j2k,
&l_current_tile_no,
&l_data_size,
&l_tile_x0, &l_tile_y0,
&l_tile_x1, &l_tile_y1,
&l_nb_comps,
&l_go_on,
p_stream,
p_manager)) {
return OPJ_FALSE;
}
if (! opj_j2k_decode_tile(p_j2k, l_current_tile_no, NULL, 0,
p_stream, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Failed to decode tile 1/1\n");
return OPJ_FALSE;
}
/* Transfer TCD data to output image data */
for (i = 0; i < p_j2k->m_output_image->numcomps; i++) {
opj_image_data_free(p_j2k->m_output_image->comps[i].data);
p_j2k->m_output_image->comps[i].data =
p_j2k->m_tcd->tcd_image->tiles->comps[i].data;
p_j2k->m_output_image->comps[i].resno_decoded =
p_j2k->m_tcd->image->comps[i].resno_decoded;
p_j2k->m_tcd->tcd_image->tiles->comps[i].data = NULL;
}
return OPJ_TRUE;
}
l_current_data = (OPJ_BYTE*)opj_malloc(1000);
if (! l_current_data) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to decode tiles\n");
return OPJ_FALSE;
}
l_max_data_size = 1000;
for (;;) {
if (! opj_j2k_read_tile_header(p_j2k,
&l_current_tile_no,
&l_data_size,
&l_tile_x0, &l_tile_y0,
&l_tile_x1, &l_tile_y1,
&l_nb_comps,
&l_go_on,
p_stream,
p_manager)) {
opj_free(l_current_data);
return OPJ_FALSE;
}
if (! l_go_on) {
break;
}
if (l_data_size > l_max_data_size) {
OPJ_BYTE *l_new_current_data = (OPJ_BYTE *) opj_realloc(l_current_data,
l_data_size);
if (! l_new_current_data) {
opj_free(l_current_data);
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to decode tile %d/%d\n",
l_current_tile_no + 1, p_j2k->m_cp.th * p_j2k->m_cp.tw);
return OPJ_FALSE;
}
l_current_data = l_new_current_data;
l_max_data_size = l_data_size;
}
if (! opj_j2k_decode_tile(p_j2k, l_current_tile_no, l_current_data, l_data_size,
p_stream, p_manager)) {
opj_free(l_current_data);
opj_event_msg(p_manager, EVT_ERROR, "Failed to decode tile %d/%d\n",
l_current_tile_no + 1, p_j2k->m_cp.th * p_j2k->m_cp.tw);
return OPJ_FALSE;
}
opj_event_msg(p_manager, EVT_INFO, "Tile %d/%d has been decoded.\n",
l_current_tile_no + 1, p_j2k->m_cp.th * p_j2k->m_cp.tw);
if (! opj_j2k_update_image_data(p_j2k->m_tcd, l_current_data,
p_j2k->m_output_image)) {
opj_free(l_current_data);
return OPJ_FALSE;
}
opj_event_msg(p_manager, EVT_INFO,
"Image data has been updated with tile %d.\n\n", l_current_tile_no + 1);
if (opj_stream_get_number_byte_left(p_stream) == 0
&& p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_NEOC) {
break;
}
if (++nr_tiles == p_j2k->m_cp.th * p_j2k->m_cp.tw) {
break;
}
}
opj_free(l_current_data);
return OPJ_TRUE;
}
/**
* Sets up the procedures to do on decoding data. Developpers wanting to extend the library can add their own reading procedures.
*/
static OPJ_BOOL opj_j2k_setup_decoding(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager)
{
/* preconditions*/
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_decode_tiles, p_manager)) {
return OPJ_FALSE;
}
/* DEVELOPER CORNER, add your custom procedures */
return OPJ_TRUE;
}
/*
* Read and decode one tile.
*/
static OPJ_BOOL opj_j2k_decode_one_tile(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_BOOL l_go_on = OPJ_TRUE;
OPJ_UINT32 l_current_tile_no;
OPJ_UINT32 l_tile_no_to_dec;
OPJ_UINT32 l_data_size, l_max_data_size;
OPJ_INT32 l_tile_x0, l_tile_y0, l_tile_x1, l_tile_y1;
OPJ_UINT32 l_nb_comps;
OPJ_BYTE * l_current_data;
OPJ_UINT32 l_nb_tiles;
OPJ_UINT32 i;
l_current_data = (OPJ_BYTE*)opj_malloc(1000);
if (! l_current_data) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to decode one tile\n");
return OPJ_FALSE;
}
l_max_data_size = 1000;
/*Allocate and initialize some elements of codestrem index if not already done*/
if (!p_j2k->cstr_index->tile_index) {
if (!opj_j2k_allocate_tile_element_cstr_index(p_j2k)) {
opj_free(l_current_data);
return OPJ_FALSE;
}
}
/* Move into the codestream to the first SOT used to decode the desired tile */
l_tile_no_to_dec = (OPJ_UINT32)
p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec;
if (p_j2k->cstr_index->tile_index)
if (p_j2k->cstr_index->tile_index->tp_index) {
if (! p_j2k->cstr_index->tile_index[l_tile_no_to_dec].nb_tps) {
/* the index for this tile has not been built,
* so move to the last SOT read */
if (!(opj_stream_read_seek(p_stream,
p_j2k->m_specific_param.m_decoder.m_last_sot_read_pos + 2, p_manager))) {
opj_event_msg(p_manager, EVT_ERROR, "Problem with seek function\n");
opj_free(l_current_data);
return OPJ_FALSE;
}
} else {
if (!(opj_stream_read_seek(p_stream,
p_j2k->cstr_index->tile_index[l_tile_no_to_dec].tp_index[0].start_pos + 2,
p_manager))) {
opj_event_msg(p_manager, EVT_ERROR, "Problem with seek function\n");
opj_free(l_current_data);
return OPJ_FALSE;
}
}
/* Special case if we have previously read the EOC marker (if the previous tile getted is the last ) */
if (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_EOC) {
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPHSOT;
}
}
/* Reset current tile part number for all tiles, and not only the one */
/* of interest. */
/* Not completely sure this is always correct but required for */
/* ./build/bin/j2k_random_tile_access ./build/tests/tte1.j2k */
l_nb_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th;
for (i = 0; i < l_nb_tiles; ++i) {
p_j2k->m_cp.tcps[i].m_current_tile_part_number = -1;
}
for (;;) {
if (! opj_j2k_read_tile_header(p_j2k,
&l_current_tile_no,
&l_data_size,
&l_tile_x0, &l_tile_y0,
&l_tile_x1, &l_tile_y1,
&l_nb_comps,
&l_go_on,
p_stream,
p_manager)) {
opj_free(l_current_data);
return OPJ_FALSE;
}
if (! l_go_on) {
break;
}
if (l_data_size > l_max_data_size) {
OPJ_BYTE *l_new_current_data = (OPJ_BYTE *) opj_realloc(l_current_data,
l_data_size);
if (! l_new_current_data) {
opj_free(l_current_data);
l_current_data = NULL;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to decode tile %d/%d\n",
l_current_tile_no + 1, p_j2k->m_cp.th * p_j2k->m_cp.tw);
return OPJ_FALSE;
}
l_current_data = l_new_current_data;
l_max_data_size = l_data_size;
}
if (! opj_j2k_decode_tile(p_j2k, l_current_tile_no, l_current_data, l_data_size,
p_stream, p_manager)) {
opj_free(l_current_data);
return OPJ_FALSE;
}
opj_event_msg(p_manager, EVT_INFO, "Tile %d/%d has been decoded.\n",
l_current_tile_no + 1, p_j2k->m_cp.th * p_j2k->m_cp.tw);
if (! opj_j2k_update_image_data(p_j2k->m_tcd, l_current_data,
p_j2k->m_output_image)) {
opj_free(l_current_data);
return OPJ_FALSE;
}
opj_event_msg(p_manager, EVT_INFO,
"Image data has been updated with tile %d.\n\n", l_current_tile_no + 1);
if (l_current_tile_no == l_tile_no_to_dec) {
/* move into the codestream to the first SOT (FIXME or not move?)*/
if (!(opj_stream_read_seek(p_stream, p_j2k->cstr_index->main_head_end + 2,
p_manager))) {
opj_event_msg(p_manager, EVT_ERROR, "Problem with seek function\n");
opj_free(l_current_data);
return OPJ_FALSE;
}
break;
} else {
opj_event_msg(p_manager, EVT_WARNING,
"Tile read, decoded and updated is not the desired one (%d vs %d).\n",
l_current_tile_no + 1, l_tile_no_to_dec + 1);
}
}
opj_free(l_current_data);
return OPJ_TRUE;
}
/**
* Sets up the procedures to do on decoding one tile. Developpers wanting to extend the library can add their own reading procedures.
*/
static OPJ_BOOL opj_j2k_setup_decoding_tile(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager)
{
/* preconditions*/
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_decode_one_tile, p_manager)) {
return OPJ_FALSE;
}
/* DEVELOPER CORNER, add your custom procedures */
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_decode(opj_j2k_t * p_j2k,
opj_stream_private_t * p_stream,
opj_image_t * p_image,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 compno;
if (!p_image) {
return OPJ_FALSE;
}
p_j2k->m_output_image = opj_image_create0();
if (!(p_j2k->m_output_image)) {
return OPJ_FALSE;
}
opj_copy_image_header(p_image, p_j2k->m_output_image);
/* customization of the decoding */
if (!opj_j2k_setup_decoding(p_j2k, p_manager)) {
return OPJ_FALSE;
}
/* Decode the codestream */
if (! opj_j2k_exec(p_j2k, p_j2k->m_procedure_list, p_stream, p_manager)) {
opj_image_destroy(p_j2k->m_private_image);
p_j2k->m_private_image = NULL;
return OPJ_FALSE;
}
/* Move data and copy one information from codec to output image*/
for (compno = 0; compno < p_image->numcomps; compno++) {
p_image->comps[compno].resno_decoded =
p_j2k->m_output_image->comps[compno].resno_decoded;
p_image->comps[compno].data = p_j2k->m_output_image->comps[compno].data;
#if 0
char fn[256];
sprintf(fn, "/tmp/%d.raw", compno);
FILE *debug = fopen(fn, "wb");
fwrite(p_image->comps[compno].data, sizeof(OPJ_INT32),
p_image->comps[compno].w * p_image->comps[compno].h, debug);
fclose(debug);
#endif
p_j2k->m_output_image->comps[compno].data = NULL;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_get_tile(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_image_t* p_image,
opj_event_mgr_t * p_manager,
OPJ_UINT32 tile_index)
{
OPJ_UINT32 compno;
OPJ_UINT32 l_tile_x, l_tile_y;
opj_image_comp_t* l_img_comp;
if (!p_image) {
opj_event_msg(p_manager, EVT_ERROR, "We need an image previously created.\n");
return OPJ_FALSE;
}
if (/*(tile_index < 0) &&*/ (tile_index >= p_j2k->m_cp.tw * p_j2k->m_cp.th)) {
opj_event_msg(p_manager, EVT_ERROR,
"Tile index provided by the user is incorrect %d (max = %d) \n", tile_index,
(p_j2k->m_cp.tw * p_j2k->m_cp.th) - 1);
return OPJ_FALSE;
}
/* Compute the dimension of the desired tile*/
l_tile_x = tile_index % p_j2k->m_cp.tw;
l_tile_y = tile_index / p_j2k->m_cp.tw;
p_image->x0 = l_tile_x * p_j2k->m_cp.tdx + p_j2k->m_cp.tx0;
if (p_image->x0 < p_j2k->m_private_image->x0) {
p_image->x0 = p_j2k->m_private_image->x0;
}
p_image->x1 = (l_tile_x + 1) * p_j2k->m_cp.tdx + p_j2k->m_cp.tx0;
if (p_image->x1 > p_j2k->m_private_image->x1) {
p_image->x1 = p_j2k->m_private_image->x1;
}
p_image->y0 = l_tile_y * p_j2k->m_cp.tdy + p_j2k->m_cp.ty0;
if (p_image->y0 < p_j2k->m_private_image->y0) {
p_image->y0 = p_j2k->m_private_image->y0;
}
p_image->y1 = (l_tile_y + 1) * p_j2k->m_cp.tdy + p_j2k->m_cp.ty0;
if (p_image->y1 > p_j2k->m_private_image->y1) {
p_image->y1 = p_j2k->m_private_image->y1;
}
l_img_comp = p_image->comps;
for (compno = 0; compno < p_image->numcomps; ++compno) {
OPJ_INT32 l_comp_x1, l_comp_y1;
l_img_comp->factor = p_j2k->m_private_image->comps[compno].factor;
l_img_comp->x0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->x0,
(OPJ_INT32)l_img_comp->dx);
l_img_comp->y0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->y0,
(OPJ_INT32)l_img_comp->dy);
l_comp_x1 = opj_int_ceildiv((OPJ_INT32)p_image->x1, (OPJ_INT32)l_img_comp->dx);
l_comp_y1 = opj_int_ceildiv((OPJ_INT32)p_image->y1, (OPJ_INT32)l_img_comp->dy);
l_img_comp->w = (OPJ_UINT32)(opj_int_ceildivpow2(l_comp_x1,
(OPJ_INT32)l_img_comp->factor) - opj_int_ceildivpow2((OPJ_INT32)l_img_comp->x0,
(OPJ_INT32)l_img_comp->factor));
l_img_comp->h = (OPJ_UINT32)(opj_int_ceildivpow2(l_comp_y1,
(OPJ_INT32)l_img_comp->factor) - opj_int_ceildivpow2((OPJ_INT32)l_img_comp->y0,
(OPJ_INT32)l_img_comp->factor));
l_img_comp++;
}
/* Destroy the previous output image*/
if (p_j2k->m_output_image) {
opj_image_destroy(p_j2k->m_output_image);
}
/* Create the ouput image from the information previously computed*/
p_j2k->m_output_image = opj_image_create0();
if (!(p_j2k->m_output_image)) {
return OPJ_FALSE;
}
opj_copy_image_header(p_image, p_j2k->m_output_image);
p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec = (OPJ_INT32)tile_index;
/* customization of the decoding */
if (!opj_j2k_setup_decoding_tile(p_j2k, p_manager)) {
return OPJ_FALSE;
}
/* Decode the codestream */
if (! opj_j2k_exec(p_j2k, p_j2k->m_procedure_list, p_stream, p_manager)) {
opj_image_destroy(p_j2k->m_private_image);
p_j2k->m_private_image = NULL;
return OPJ_FALSE;
}
/* Move data and copy one information from codec to output image*/
for (compno = 0; compno < p_image->numcomps; compno++) {
p_image->comps[compno].resno_decoded =
p_j2k->m_output_image->comps[compno].resno_decoded;
if (p_image->comps[compno].data) {
opj_image_data_free(p_image->comps[compno].data);
}
p_image->comps[compno].data = p_j2k->m_output_image->comps[compno].data;
p_j2k->m_output_image->comps[compno].data = NULL;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_set_decoded_resolution_factor(opj_j2k_t *p_j2k,
OPJ_UINT32 res_factor,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 it_comp;
p_j2k->m_cp.m_specific_param.m_dec.m_reduce = res_factor;
if (p_j2k->m_private_image) {
if (p_j2k->m_private_image->comps) {
if (p_j2k->m_specific_param.m_decoder.m_default_tcp) {
if (p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps) {
for (it_comp = 0 ; it_comp < p_j2k->m_private_image->numcomps; it_comp++) {
OPJ_UINT32 max_res =
p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps[it_comp].numresolutions;
if (res_factor >= max_res) {
opj_event_msg(p_manager, EVT_ERROR,
"Resolution factor is greater than the maximum resolution in the component.\n");
return OPJ_FALSE;
}
p_j2k->m_private_image->comps[it_comp].factor = res_factor;
}
return OPJ_TRUE;
}
}
}
}
return OPJ_FALSE;
}
OPJ_BOOL opj_j2k_encode(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 i, j;
OPJ_UINT32 l_nb_tiles;
OPJ_UINT32 l_max_tile_size = 0, l_current_tile_size;
OPJ_BYTE * l_current_data = 00;
OPJ_BOOL l_reuse_data = OPJ_FALSE;
opj_tcd_t* p_tcd = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
p_tcd = p_j2k->m_tcd;
l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
if (l_nb_tiles == 1) {
l_reuse_data = OPJ_TRUE;
#ifdef __SSE__
for (j = 0; j < p_j2k->m_tcd->image->numcomps; ++j) {
opj_image_comp_t * l_img_comp = p_tcd->image->comps + j;
if (((size_t)l_img_comp->data & 0xFU) !=
0U) { /* tile data shall be aligned on 16 bytes */
l_reuse_data = OPJ_FALSE;
}
}
#endif
}
for (i = 0; i < l_nb_tiles; ++i) {
if (! opj_j2k_pre_write_tile(p_j2k, i, p_stream, p_manager)) {
if (l_current_data) {
opj_free(l_current_data);
}
return OPJ_FALSE;
}
/* if we only have one tile, then simply set tile component data equal to image component data */
/* otherwise, allocate the data */
for (j = 0; j < p_j2k->m_tcd->image->numcomps; ++j) {
opj_tcd_tilecomp_t* l_tilec = p_tcd->tcd_image->tiles->comps + j;
if (l_reuse_data) {
opj_image_comp_t * l_img_comp = p_tcd->image->comps + j;
l_tilec->data = l_img_comp->data;
l_tilec->ownsData = OPJ_FALSE;
} else {
if (! opj_alloc_tile_component_data(l_tilec)) {
opj_event_msg(p_manager, EVT_ERROR, "Error allocating tile component data.");
if (l_current_data) {
opj_free(l_current_data);
}
return OPJ_FALSE;
}
}
}
l_current_tile_size = opj_tcd_get_encoded_tile_size(p_j2k->m_tcd);
if (!l_reuse_data) {
if (l_current_tile_size > l_max_tile_size) {
OPJ_BYTE *l_new_current_data = (OPJ_BYTE *) opj_realloc(l_current_data,
l_current_tile_size);
if (! l_new_current_data) {
if (l_current_data) {
opj_free(l_current_data);
}
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to encode all tiles\n");
return OPJ_FALSE;
}
l_current_data = l_new_current_data;
l_max_tile_size = l_current_tile_size;
}
/* copy image data (32 bit) to l_current_data as contiguous, all-component, zero offset buffer */
/* 32 bit components @ 8 bit precision get converted to 8 bit */
/* 32 bit components @ 16 bit precision get converted to 16 bit */
opj_j2k_get_tile_data(p_j2k->m_tcd, l_current_data);
/* now copy this data into the tile component */
if (! opj_tcd_copy_tile_data(p_j2k->m_tcd, l_current_data,
l_current_tile_size)) {
opj_event_msg(p_manager, EVT_ERROR,
"Size mismatch between tile data and sent data.");
opj_free(l_current_data);
return OPJ_FALSE;
}
}
if (! opj_j2k_post_write_tile(p_j2k, p_stream, p_manager)) {
if (l_current_data) {
opj_free(l_current_data);
}
return OPJ_FALSE;
}
}
if (l_current_data) {
opj_free(l_current_data);
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_end_compress(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
/* customization of the encoding */
if (! opj_j2k_setup_end_compress(p_j2k, p_manager)) {
return OPJ_FALSE;
}
if (! opj_j2k_exec(p_j2k, p_j2k->m_procedure_list, p_stream, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_start_compress(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_image_t * p_image,
opj_event_mgr_t * p_manager)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
p_j2k->m_private_image = opj_image_create0();
if (! p_j2k->m_private_image) {
opj_event_msg(p_manager, EVT_ERROR, "Failed to allocate image header.");
return OPJ_FALSE;
}
opj_copy_image_header(p_image, p_j2k->m_private_image);
/* TODO_MSD: Find a better way */
if (p_image->comps) {
OPJ_UINT32 it_comp;
for (it_comp = 0 ; it_comp < p_image->numcomps; it_comp++) {
if (p_image->comps[it_comp].data) {
p_j2k->m_private_image->comps[it_comp].data = p_image->comps[it_comp].data;
p_image->comps[it_comp].data = NULL;
}
}
}
/* customization of the validation */
if (! opj_j2k_setup_encoding_validation(p_j2k, p_manager)) {
return OPJ_FALSE;
}
/* validation of the parameters codec */
if (! opj_j2k_exec(p_j2k, p_j2k->m_validation_list, p_stream, p_manager)) {
return OPJ_FALSE;
}
/* customization of the encoding */
if (! opj_j2k_setup_header_writing(p_j2k, p_manager)) {
return OPJ_FALSE;
}
/* write header */
if (! opj_j2k_exec(p_j2k, p_j2k->m_procedure_list, p_stream, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_pre_write_tile(opj_j2k_t * p_j2k,
OPJ_UINT32 p_tile_index,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
(void)p_stream;
if (p_tile_index != p_j2k->m_current_tile_number) {
opj_event_msg(p_manager, EVT_ERROR, "The given tile index does not match.");
return OPJ_FALSE;
}
opj_event_msg(p_manager, EVT_INFO, "tile number %d / %d\n",
p_j2k->m_current_tile_number + 1, p_j2k->m_cp.tw * p_j2k->m_cp.th);
p_j2k->m_specific_param.m_encoder.m_current_tile_part_number = 0;
p_j2k->m_tcd->cur_totnum_tp = p_j2k->m_cp.tcps[p_tile_index].m_nb_tile_parts;
p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = 0;
/* initialisation before tile encoding */
if (! opj_tcd_init_encode_tile(p_j2k->m_tcd, p_j2k->m_current_tile_number,
p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static void opj_get_tile_dimensions(opj_image_t * l_image,
opj_tcd_tilecomp_t * l_tilec,
opj_image_comp_t * l_img_comp,
OPJ_UINT32* l_size_comp,
OPJ_UINT32* l_width,
OPJ_UINT32* l_height,
OPJ_UINT32* l_offset_x,
OPJ_UINT32* l_offset_y,
OPJ_UINT32* l_image_width,
OPJ_UINT32* l_stride,
OPJ_UINT32* l_tile_offset)
{
OPJ_UINT32 l_remaining;
*l_size_comp = l_img_comp->prec >> 3; /* (/8) */
l_remaining = l_img_comp->prec & 7; /* (%8) */
if (l_remaining) {
*l_size_comp += 1;
}
if (*l_size_comp == 3) {
*l_size_comp = 4;
}
*l_width = (OPJ_UINT32)(l_tilec->x1 - l_tilec->x0);
*l_height = (OPJ_UINT32)(l_tilec->y1 - l_tilec->y0);
*l_offset_x = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)l_image->x0,
(OPJ_INT32)l_img_comp->dx);
*l_offset_y = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)l_image->y0,
(OPJ_INT32)l_img_comp->dy);
*l_image_width = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)l_image->x1 -
(OPJ_INT32)l_image->x0, (OPJ_INT32)l_img_comp->dx);
*l_stride = *l_image_width - *l_width;
*l_tile_offset = ((OPJ_UINT32)l_tilec->x0 - *l_offset_x) + ((
OPJ_UINT32)l_tilec->y0 - *l_offset_y) * *l_image_width;
}
static void opj_j2k_get_tile_data(opj_tcd_t * p_tcd, OPJ_BYTE * p_data)
{
OPJ_UINT32 i, j, k = 0;
for (i = 0; i < p_tcd->image->numcomps; ++i) {
opj_image_t * l_image = p_tcd->image;
OPJ_INT32 * l_src_ptr;
opj_tcd_tilecomp_t * l_tilec = p_tcd->tcd_image->tiles->comps + i;
opj_image_comp_t * l_img_comp = l_image->comps + i;
OPJ_UINT32 l_size_comp, l_width, l_height, l_offset_x, l_offset_y,
l_image_width, l_stride, l_tile_offset;
opj_get_tile_dimensions(l_image,
l_tilec,
l_img_comp,
&l_size_comp,
&l_width,
&l_height,
&l_offset_x,
&l_offset_y,
&l_image_width,
&l_stride,
&l_tile_offset);
l_src_ptr = l_img_comp->data + l_tile_offset;
switch (l_size_comp) {
case 1: {
OPJ_CHAR * l_dest_ptr = (OPJ_CHAR*) p_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_dest_ptr;
++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_dest_ptr;
++l_src_ptr;
}
l_src_ptr += l_stride;
}
}
p_data = (OPJ_BYTE*) l_dest_ptr;
}
break;
case 2: {
OPJ_INT16 * l_dest_ptr = (OPJ_INT16 *) p_data;
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_data = (OPJ_BYTE*) l_dest_ptr;
}
break;
case 4: {
OPJ_INT32 * l_dest_ptr = (OPJ_INT32 *) p_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_data = (OPJ_BYTE*) l_dest_ptr;
}
break;
}
}
}
static OPJ_BOOL opj_j2k_post_write_tile(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 l_nb_bytes_written;
OPJ_BYTE * l_current_data = 00;
OPJ_UINT32 l_tile_size = 0;
OPJ_UINT32 l_available_data;
/* preconditions */
assert(p_j2k->m_specific_param.m_encoder.m_encoded_tile_data);
l_tile_size = p_j2k->m_specific_param.m_encoder.m_encoded_tile_size;
l_available_data = l_tile_size;
l_current_data = p_j2k->m_specific_param.m_encoder.m_encoded_tile_data;
l_nb_bytes_written = 0;
if (! opj_j2k_write_first_tile_part(p_j2k, l_current_data, &l_nb_bytes_written,
l_available_data, p_stream, p_manager)) {
return OPJ_FALSE;
}
l_current_data += l_nb_bytes_written;
l_available_data -= l_nb_bytes_written;
l_nb_bytes_written = 0;
if (! opj_j2k_write_all_tile_parts(p_j2k, l_current_data, &l_nb_bytes_written,
l_available_data, p_stream, p_manager)) {
return OPJ_FALSE;
}
l_available_data -= l_nb_bytes_written;
l_nb_bytes_written = l_tile_size - l_available_data;
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_encoded_tile_data,
l_nb_bytes_written, p_manager) != l_nb_bytes_written) {
return OPJ_FALSE;
}
++p_j2k->m_current_tile_number;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_setup_end_compress(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
/* DEVELOPER CORNER, insert your custom procedures */
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_eoc, p_manager)) {
return OPJ_FALSE;
}
if (OPJ_IS_CINEMA(p_j2k->m_cp.rsiz)) {
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_updated_tlm, p_manager)) {
return OPJ_FALSE;
}
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_epc, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_end_encoding, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_destroy_header_memory, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_setup_encoding_validation(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list,
(opj_procedure)opj_j2k_build_encoder, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list,
(opj_procedure)opj_j2k_encoding_validation, p_manager)) {
return OPJ_FALSE;
}
/* DEVELOPER CORNER, add your custom validation procedure */
if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list,
(opj_procedure)opj_j2k_mct_validation, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_setup_header_writing(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_init_info, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_soc, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_siz, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_cod, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_qcd, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_all_coc, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_all_qcc, p_manager)) {
return OPJ_FALSE;
}
if (OPJ_IS_CINEMA(p_j2k->m_cp.rsiz)) {
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_tlm, p_manager)) {
return OPJ_FALSE;
}
if (p_j2k->m_cp.rsiz == OPJ_PROFILE_CINEMA_4K) {
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_poc, p_manager)) {
return OPJ_FALSE;
}
}
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_regions, p_manager)) {
return OPJ_FALSE;
}
if (p_j2k->m_cp.comment != 00) {
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_com, p_manager)) {
return OPJ_FALSE;
}
}
/* DEVELOPER CORNER, insert your custom procedures */
if (p_j2k->m_cp.rsiz & OPJ_EXTENSION_MCT) {
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_mct_data_group, p_manager)) {
return OPJ_FALSE;
}
}
/* End of Developer Corner */
if (p_j2k->cstr_index) {
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_get_end_header, p_manager)) {
return OPJ_FALSE;
}
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_create_tcd, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_update_rates, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_first_tile_part(opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_total_data_size,
opj_stream_private_t *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 l_nb_bytes_written = 0;
OPJ_UINT32 l_current_nb_bytes_written;
OPJ_BYTE * l_begin_data = 00;
opj_tcd_t * l_tcd = 00;
opj_cp_t * l_cp = 00;
l_tcd = p_j2k->m_tcd;
l_cp = &(p_j2k->m_cp);
l_tcd->cur_pino = 0;
/*Get number of tile parts*/
p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = 0;
/* INDEX >> */
/* << INDEX */
l_current_nb_bytes_written = 0;
l_begin_data = p_data;
if (! opj_j2k_write_sot(p_j2k, p_data, &l_current_nb_bytes_written, p_stream,
p_manager)) {
return OPJ_FALSE;
}
l_nb_bytes_written += l_current_nb_bytes_written;
p_data += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
if (!OPJ_IS_CINEMA(l_cp->rsiz)) {
#if 0
for (compno = 1; compno < p_j2k->m_private_image->numcomps; compno++) {
l_current_nb_bytes_written = 0;
opj_j2k_write_coc_in_memory(p_j2k, compno, p_data, &l_current_nb_bytes_written,
p_manager);
l_nb_bytes_written += l_current_nb_bytes_written;
p_data += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
l_current_nb_bytes_written = 0;
opj_j2k_write_qcc_in_memory(p_j2k, compno, p_data, &l_current_nb_bytes_written,
p_manager);
l_nb_bytes_written += l_current_nb_bytes_written;
p_data += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
}
#endif
if (l_cp->tcps[p_j2k->m_current_tile_number].numpocs) {
l_current_nb_bytes_written = 0;
opj_j2k_write_poc_in_memory(p_j2k, p_data, &l_current_nb_bytes_written,
p_manager);
l_nb_bytes_written += l_current_nb_bytes_written;
p_data += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
}
}
l_current_nb_bytes_written = 0;
if (! opj_j2k_write_sod(p_j2k, l_tcd, p_data, &l_current_nb_bytes_written,
p_total_data_size, p_stream, p_manager)) {
return OPJ_FALSE;
}
l_nb_bytes_written += l_current_nb_bytes_written;
* p_data_written = l_nb_bytes_written;
/* Writing Psot in SOT marker */
opj_write_bytes(l_begin_data + 6, l_nb_bytes_written,
4); /* PSOT */
if (OPJ_IS_CINEMA(l_cp->rsiz)) {
opj_j2k_update_tlm(p_j2k, l_nb_bytes_written);
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_all_tile_parts(opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_total_data_size,
opj_stream_private_t *p_stream,
struct opj_event_mgr * p_manager
)
{
OPJ_UINT32 tilepartno = 0;
OPJ_UINT32 l_nb_bytes_written = 0;
OPJ_UINT32 l_current_nb_bytes_written;
OPJ_UINT32 l_part_tile_size;
OPJ_UINT32 tot_num_tp;
OPJ_UINT32 pino;
OPJ_BYTE * l_begin_data;
opj_tcp_t *l_tcp = 00;
opj_tcd_t * l_tcd = 00;
opj_cp_t * l_cp = 00;
l_tcd = p_j2k->m_tcd;
l_cp = &(p_j2k->m_cp);
l_tcp = l_cp->tcps + p_j2k->m_current_tile_number;
/*Get number of tile parts*/
tot_num_tp = opj_j2k_get_num_tp(l_cp, 0, p_j2k->m_current_tile_number);
/* start writing remaining tile parts */
++p_j2k->m_specific_param.m_encoder.m_current_tile_part_number;
for (tilepartno = 1; tilepartno < tot_num_tp ; ++tilepartno) {
p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = tilepartno;
l_current_nb_bytes_written = 0;
l_part_tile_size = 0;
l_begin_data = p_data;
if (! opj_j2k_write_sot(p_j2k, p_data, &l_current_nb_bytes_written, p_stream,
p_manager)) {
return OPJ_FALSE;
}
l_nb_bytes_written += l_current_nb_bytes_written;
p_data += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
l_part_tile_size += l_current_nb_bytes_written;
l_current_nb_bytes_written = 0;
if (! opj_j2k_write_sod(p_j2k, l_tcd, p_data, &l_current_nb_bytes_written,
p_total_data_size, p_stream, p_manager)) {
return OPJ_FALSE;
}
p_data += l_current_nb_bytes_written;
l_nb_bytes_written += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
l_part_tile_size += l_current_nb_bytes_written;
/* Writing Psot in SOT marker */
opj_write_bytes(l_begin_data + 6, l_part_tile_size,
4); /* PSOT */
if (OPJ_IS_CINEMA(l_cp->rsiz)) {
opj_j2k_update_tlm(p_j2k, l_part_tile_size);
}
++p_j2k->m_specific_param.m_encoder.m_current_tile_part_number;
}
for (pino = 1; pino <= l_tcp->numpocs; ++pino) {
l_tcd->cur_pino = pino;
/*Get number of tile parts*/
tot_num_tp = opj_j2k_get_num_tp(l_cp, pino, p_j2k->m_current_tile_number);
for (tilepartno = 0; tilepartno < tot_num_tp ; ++tilepartno) {
p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = tilepartno;
l_current_nb_bytes_written = 0;
l_part_tile_size = 0;
l_begin_data = p_data;
if (! opj_j2k_write_sot(p_j2k, p_data, &l_current_nb_bytes_written, p_stream,
p_manager)) {
return OPJ_FALSE;
}
l_nb_bytes_written += l_current_nb_bytes_written;
p_data += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
l_part_tile_size += l_current_nb_bytes_written;
l_current_nb_bytes_written = 0;
if (! opj_j2k_write_sod(p_j2k, l_tcd, p_data, &l_current_nb_bytes_written,
p_total_data_size, p_stream, p_manager)) {
return OPJ_FALSE;
}
l_nb_bytes_written += l_current_nb_bytes_written;
p_data += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
l_part_tile_size += l_current_nb_bytes_written;
/* Writing Psot in SOT marker */
opj_write_bytes(l_begin_data + 6, l_part_tile_size,
4); /* PSOT */
if (OPJ_IS_CINEMA(l_cp->rsiz)) {
opj_j2k_update_tlm(p_j2k, l_part_tile_size);
}
++p_j2k->m_specific_param.m_encoder.m_current_tile_part_number;
}
}
*p_data_written = l_nb_bytes_written;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_updated_tlm(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 l_tlm_size;
OPJ_OFF_T l_tlm_position, l_current_position;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_tlm_size = 5 * p_j2k->m_specific_param.m_encoder.m_total_tile_parts;
l_tlm_position = 6 + p_j2k->m_specific_param.m_encoder.m_tlm_start;
l_current_position = opj_stream_tell(p_stream);
if (! opj_stream_seek(p_stream, l_tlm_position, p_manager)) {
return OPJ_FALSE;
}
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer, l_tlm_size,
p_manager) != l_tlm_size) {
return OPJ_FALSE;
}
if (! opj_stream_seek(p_stream, l_current_position, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_end_encoding(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
OPJ_UNUSED(p_stream);
OPJ_UNUSED(p_manager);
opj_tcd_destroy(p_j2k->m_tcd);
p_j2k->m_tcd = 00;
if (p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer) {
opj_free(p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer);
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer = 0;
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current = 0;
}
if (p_j2k->m_specific_param.m_encoder.m_encoded_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_encoded_tile_data);
p_j2k->m_specific_param.m_encoder.m_encoded_tile_data = 0;
}
p_j2k->m_specific_param.m_encoder.m_encoded_tile_size = 0;
return OPJ_TRUE;
}
/**
* Destroys the memory associated with the decoding of headers.
*/
static OPJ_BOOL opj_j2k_destroy_header_memory(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_stream);
OPJ_UNUSED(p_manager);
if (p_j2k->m_specific_param.m_encoder.m_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = 0;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_init_info(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
opj_codestream_info_t * l_cstr_info = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
(void)l_cstr_info;
OPJ_UNUSED(p_stream);
/* TODO mergeV2: check this part which use cstr_info */
/*l_cstr_info = p_j2k->cstr_info;
if (l_cstr_info) {
OPJ_UINT32 compno;
l_cstr_info->tile = (opj_tile_info_t *) opj_malloc(p_j2k->m_cp.tw * p_j2k->m_cp.th * sizeof(opj_tile_info_t));
l_cstr_info->image_w = p_j2k->m_image->x1 - p_j2k->m_image->x0;
l_cstr_info->image_h = p_j2k->m_image->y1 - p_j2k->m_image->y0;
l_cstr_info->prog = (&p_j2k->m_cp.tcps[0])->prg;
l_cstr_info->tw = p_j2k->m_cp.tw;
l_cstr_info->th = p_j2k->m_cp.th;
l_cstr_info->tile_x = p_j2k->m_cp.tdx;*/ /* new version parser */
/*l_cstr_info->tile_y = p_j2k->m_cp.tdy;*/ /* new version parser */
/*l_cstr_info->tile_Ox = p_j2k->m_cp.tx0;*/ /* new version parser */
/*l_cstr_info->tile_Oy = p_j2k->m_cp.ty0;*/ /* new version parser */
/*l_cstr_info->numcomps = p_j2k->m_image->numcomps;
l_cstr_info->numlayers = (&p_j2k->m_cp.tcps[0])->numlayers;
l_cstr_info->numdecompos = (OPJ_INT32*) opj_malloc(p_j2k->m_image->numcomps * sizeof(OPJ_INT32));
for (compno=0; compno < p_j2k->m_image->numcomps; compno++) {
l_cstr_info->numdecompos[compno] = (&p_j2k->m_cp.tcps[0])->tccps->numresolutions - 1;
}
l_cstr_info->D_max = 0.0; */ /* ADD Marcela */
/*l_cstr_info->main_head_start = opj_stream_tell(p_stream);*/ /* position of SOC */
/*l_cstr_info->maxmarknum = 100;
l_cstr_info->marker = (opj_marker_info_t *) opj_malloc(l_cstr_info->maxmarknum * sizeof(opj_marker_info_t));
l_cstr_info->marknum = 0;
}*/
return opj_j2k_calculate_tp(p_j2k, &(p_j2k->m_cp),
&p_j2k->m_specific_param.m_encoder.m_total_tile_parts, p_j2k->m_private_image,
p_manager);
}
/**
* Creates a tile-coder decoder.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_create_tcd(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
OPJ_UNUSED(p_stream);
p_j2k->m_tcd = opj_tcd_create(OPJ_FALSE);
if (! p_j2k->m_tcd) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to create Tile Coder\n");
return OPJ_FALSE;
}
if (!opj_tcd_init(p_j2k->m_tcd, p_j2k->m_private_image, &p_j2k->m_cp,
p_j2k->m_tp)) {
opj_tcd_destroy(p_j2k->m_tcd);
p_j2k->m_tcd = 00;
return OPJ_FALSE;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_write_tile(opj_j2k_t * p_j2k,
OPJ_UINT32 p_tile_index,
OPJ_BYTE * p_data,
OPJ_UINT32 p_data_size,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
if (! opj_j2k_pre_write_tile(p_j2k, p_tile_index, p_stream, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR,
"Error while opj_j2k_pre_write_tile with tile index = %d\n", p_tile_index);
return OPJ_FALSE;
} else {
OPJ_UINT32 j;
/* Allocate data */
for (j = 0; j < p_j2k->m_tcd->image->numcomps; ++j) {
opj_tcd_tilecomp_t* l_tilec = p_j2k->m_tcd->tcd_image->tiles->comps + j;
if (! opj_alloc_tile_component_data(l_tilec)) {
opj_event_msg(p_manager, EVT_ERROR, "Error allocating tile component data.");
return OPJ_FALSE;
}
}
/* now copy data into the tile component */
if (! opj_tcd_copy_tile_data(p_j2k->m_tcd, p_data, p_data_size)) {
opj_event_msg(p_manager, EVT_ERROR,
"Size mismatch between tile data and sent data.");
return OPJ_FALSE;
}
if (! opj_j2k_post_write_tile(p_j2k, p_stream, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR,
"Error while opj_j2k_post_write_tile with tile index = %d\n", p_tile_index);
return OPJ_FALSE;
}
}
return OPJ_TRUE;
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_2775_0 |
crossvul-cpp_data_good_205_1 | /*
* linux/kernel/softirq.c
*
* Copyright (C) 1992 Linus Torvalds
*
* Distribute under GPLv2.
*
* Rewritten. Old one was good in 2.2, but in 2.3 it was immoral. --ANK (990903)
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/export.h>
#include <linux/kernel_stat.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/notifier.h>
#include <linux/percpu.h>
#include <linux/cpu.h>
#include <linux/freezer.h>
#include <linux/kthread.h>
#include <linux/rcupdate.h>
#include <linux/ftrace.h>
#include <linux/smp.h>
#include <linux/smpboot.h>
#include <linux/tick.h>
#include <linux/irq.h>
#define CREATE_TRACE_POINTS
#include <trace/events/irq.h>
/*
- No shared variables, all the data are CPU local.
- If a softirq needs serialization, let it serialize itself
by its own spinlocks.
- Even if softirq is serialized, only local cpu is marked for
execution. Hence, we get something sort of weak cpu binding.
Though it is still not clear, will it result in better locality
or will not.
Examples:
- NET RX softirq. It is multithreaded and does not require
any global serialization.
- NET TX softirq. It kicks software netdevice queues, hence
it is logically serialized per device, but this serialization
is invisible to common code.
- Tasklets: serialized wrt itself.
*/
#ifndef __ARCH_IRQ_STAT
DEFINE_PER_CPU_ALIGNED(irq_cpustat_t, irq_stat);
EXPORT_PER_CPU_SYMBOL(irq_stat);
#endif
static struct softirq_action softirq_vec[NR_SOFTIRQS] __cacheline_aligned_in_smp;
DEFINE_PER_CPU(struct task_struct *, ksoftirqd);
const char * const softirq_to_name[NR_SOFTIRQS] = {
"HI", "TIMER", "NET_TX", "NET_RX", "BLOCK", "IRQ_POLL",
"TASKLET", "SCHED", "HRTIMER", "RCU"
};
/*
* we cannot loop indefinitely here to avoid userspace starvation,
* but we also don't want to introduce a worst case 1/HZ latency
* to the pending events, so lets the scheduler to balance
* the softirq load for us.
*/
static void wakeup_softirqd(void)
{
/* Interrupts are disabled: no need to stop preemption */
struct task_struct *tsk = __this_cpu_read(ksoftirqd);
if (tsk && tsk->state != TASK_RUNNING)
wake_up_process(tsk);
}
/*
* If ksoftirqd is scheduled, we do not want to process pending softirqs
* right now. Let ksoftirqd handle this at its own rate, to get fairness.
*/
static bool ksoftirqd_running(void)
{
struct task_struct *tsk = __this_cpu_read(ksoftirqd);
return tsk && (tsk->state == TASK_RUNNING);
}
/*
* preempt_count and SOFTIRQ_OFFSET usage:
* - preempt_count is changed by SOFTIRQ_OFFSET on entering or leaving
* softirq processing.
* - preempt_count is changed by SOFTIRQ_DISABLE_OFFSET (= 2 * SOFTIRQ_OFFSET)
* on local_bh_disable or local_bh_enable.
* This lets us distinguish between whether we are currently processing
* softirq and whether we just have bh disabled.
*/
/*
* This one is for softirq.c-internal use,
* where hardirqs are disabled legitimately:
*/
#ifdef CONFIG_TRACE_IRQFLAGS
void __local_bh_disable_ip(unsigned long ip, unsigned int cnt)
{
unsigned long flags;
WARN_ON_ONCE(in_irq());
raw_local_irq_save(flags);
/*
* The preempt tracer hooks into preempt_count_add and will break
* lockdep because it calls back into lockdep after SOFTIRQ_OFFSET
* is set and before current->softirq_enabled is cleared.
* We must manually increment preempt_count here and manually
* call the trace_preempt_off later.
*/
__preempt_count_add(cnt);
/*
* Were softirqs turned off above:
*/
if (softirq_count() == (cnt & SOFTIRQ_MASK))
trace_softirqs_off(ip);
raw_local_irq_restore(flags);
if (preempt_count() == cnt) {
#ifdef CONFIG_DEBUG_PREEMPT
current->preempt_disable_ip = get_lock_parent_ip();
#endif
trace_preempt_off(CALLER_ADDR0, get_lock_parent_ip());
}
}
EXPORT_SYMBOL(__local_bh_disable_ip);
#endif /* CONFIG_TRACE_IRQFLAGS */
static void __local_bh_enable(unsigned int cnt)
{
lockdep_assert_irqs_disabled();
if (preempt_count() == cnt)
trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip());
if (softirq_count() == (cnt & SOFTIRQ_MASK))
trace_softirqs_on(_RET_IP_);
__preempt_count_sub(cnt);
}
/*
* Special-case - softirqs can safely be enabled by __do_softirq(),
* without processing still-pending softirqs:
*/
void _local_bh_enable(void)
{
WARN_ON_ONCE(in_irq());
__local_bh_enable(SOFTIRQ_DISABLE_OFFSET);
}
EXPORT_SYMBOL(_local_bh_enable);
void __local_bh_enable_ip(unsigned long ip, unsigned int cnt)
{
WARN_ON_ONCE(in_irq());
lockdep_assert_irqs_enabled();
#ifdef CONFIG_TRACE_IRQFLAGS
local_irq_disable();
#endif
/*
* Are softirqs going to be turned on now:
*/
if (softirq_count() == SOFTIRQ_DISABLE_OFFSET)
trace_softirqs_on(ip);
/*
* Keep preemption disabled until we are done with
* softirq processing:
*/
preempt_count_sub(cnt - 1);
if (unlikely(!in_interrupt() && local_softirq_pending())) {
/*
* Run softirq if any pending. And do it in its own stack
* as we may be calling this deep in a task call stack already.
*/
do_softirq();
}
preempt_count_dec();
#ifdef CONFIG_TRACE_IRQFLAGS
local_irq_enable();
#endif
preempt_check_resched();
}
EXPORT_SYMBOL(__local_bh_enable_ip);
/*
* We restart softirq processing for at most MAX_SOFTIRQ_RESTART times,
* but break the loop if need_resched() is set or after 2 ms.
* The MAX_SOFTIRQ_TIME provides a nice upper bound in most cases, but in
* certain cases, such as stop_machine(), jiffies may cease to
* increment and so we need the MAX_SOFTIRQ_RESTART limit as
* well to make sure we eventually return from this method.
*
* These limits have been established via experimentation.
* The two things to balance is latency against fairness -
* we want to handle softirqs as soon as possible, but they
* should not be able to lock up the box.
*/
#define MAX_SOFTIRQ_TIME msecs_to_jiffies(2)
#define MAX_SOFTIRQ_RESTART 10
#ifdef CONFIG_TRACE_IRQFLAGS
/*
* When we run softirqs from irq_exit() and thus on the hardirq stack we need
* to keep the lockdep irq context tracking as tight as possible in order to
* not miss-qualify lock contexts and miss possible deadlocks.
*/
static inline bool lockdep_softirq_start(void)
{
bool in_hardirq = false;
if (trace_hardirq_context(current)) {
in_hardirq = true;
trace_hardirq_exit();
}
lockdep_softirq_enter();
return in_hardirq;
}
static inline void lockdep_softirq_end(bool in_hardirq)
{
lockdep_softirq_exit();
if (in_hardirq)
trace_hardirq_enter();
}
#else
static inline bool lockdep_softirq_start(void) { return false; }
static inline void lockdep_softirq_end(bool in_hardirq) { }
#endif
asmlinkage __visible void __softirq_entry __do_softirq(void)
{
unsigned long end = jiffies + MAX_SOFTIRQ_TIME;
unsigned long old_flags = current->flags;
int max_restart = MAX_SOFTIRQ_RESTART;
struct softirq_action *h;
bool in_hardirq;
__u32 pending;
int softirq_bit;
/*
* Mask out PF_MEMALLOC s current task context is borrowed for the
* softirq. A softirq handled such as network RX might set PF_MEMALLOC
* again if the socket is related to swap
*/
current->flags &= ~PF_MEMALLOC;
pending = local_softirq_pending();
account_irq_enter_time(current);
__local_bh_disable_ip(_RET_IP_, SOFTIRQ_OFFSET);
in_hardirq = lockdep_softirq_start();
restart:
/* Reset the pending bitmask before enabling irqs */
set_softirq_pending(0);
local_irq_enable();
h = softirq_vec;
while ((softirq_bit = ffs(pending))) {
unsigned int vec_nr;
int prev_count;
h += softirq_bit - 1;
vec_nr = h - softirq_vec;
prev_count = preempt_count();
kstat_incr_softirqs_this_cpu(vec_nr);
trace_softirq_entry(vec_nr);
h->action(h);
trace_softirq_exit(vec_nr);
if (unlikely(prev_count != preempt_count())) {
pr_err("huh, entered softirq %u %s %p with preempt_count %08x, exited with %08x?\n",
vec_nr, softirq_to_name[vec_nr], h->action,
prev_count, preempt_count());
preempt_count_set(prev_count);
}
h++;
pending >>= softirq_bit;
}
rcu_bh_qs();
local_irq_disable();
pending = local_softirq_pending();
if (pending) {
if (time_before(jiffies, end) && !need_resched() &&
--max_restart)
goto restart;
wakeup_softirqd();
}
lockdep_softirq_end(in_hardirq);
account_irq_exit_time(current);
__local_bh_enable(SOFTIRQ_OFFSET);
WARN_ON_ONCE(in_interrupt());
current_restore_flags(old_flags, PF_MEMALLOC);
}
asmlinkage __visible void do_softirq(void)
{
__u32 pending;
unsigned long flags;
if (in_interrupt())
return;
local_irq_save(flags);
pending = local_softirq_pending();
if (pending && !ksoftirqd_running())
do_softirq_own_stack();
local_irq_restore(flags);
}
/*
* Enter an interrupt context.
*/
void irq_enter(void)
{
rcu_irq_enter();
if (is_idle_task(current) && !in_interrupt()) {
/*
* Prevent raise_softirq from needlessly waking up ksoftirqd
* here, as softirq will be serviced on return from interrupt.
*/
local_bh_disable();
tick_irq_enter();
_local_bh_enable();
}
__irq_enter();
}
static inline void invoke_softirq(void)
{
if (ksoftirqd_running())
return;
if (!force_irqthreads) {
#ifdef CONFIG_HAVE_IRQ_EXIT_ON_IRQ_STACK
/*
* We can safely execute softirq on the current stack if
* it is the irq stack, because it should be near empty
* at this stage.
*/
__do_softirq();
#else
/*
* Otherwise, irq_exit() is called on the task stack that can
* be potentially deep already. So call softirq in its own stack
* to prevent from any overrun.
*/
do_softirq_own_stack();
#endif
} else {
wakeup_softirqd();
}
}
static inline void tick_irq_exit(void)
{
#ifdef CONFIG_NO_HZ_COMMON
int cpu = smp_processor_id();
/* Make sure that timer wheel updates are propagated */
if ((idle_cpu(cpu) && !need_resched()) || tick_nohz_full_cpu(cpu)) {
if (!in_interrupt())
tick_nohz_irq_exit();
}
#endif
}
/*
* Exit an interrupt context. Process softirqs if needed and possible:
*/
void irq_exit(void)
{
#ifndef __ARCH_IRQ_EXIT_IRQS_DISABLED
local_irq_disable();
#else
lockdep_assert_irqs_disabled();
#endif
account_irq_exit_time(current);
preempt_count_sub(HARDIRQ_OFFSET);
if (!in_interrupt() && local_softirq_pending())
invoke_softirq();
tick_irq_exit();
rcu_irq_exit();
trace_hardirq_exit(); /* must be last! */
}
/*
* This function must run with irqs disabled!
*/
inline void raise_softirq_irqoff(unsigned int nr)
{
__raise_softirq_irqoff(nr);
/*
* If we're in an interrupt or softirq, we're done
* (this also catches softirq-disabled code). We will
* actually run the softirq once we return from
* the irq or softirq.
*
* Otherwise we wake up ksoftirqd to make sure we
* schedule the softirq soon.
*/
if (!in_interrupt())
wakeup_softirqd();
}
void raise_softirq(unsigned int nr)
{
unsigned long flags;
local_irq_save(flags);
raise_softirq_irqoff(nr);
local_irq_restore(flags);
}
void __raise_softirq_irqoff(unsigned int nr)
{
trace_softirq_raise(nr);
or_softirq_pending(1UL << nr);
}
void open_softirq(int nr, void (*action)(struct softirq_action *))
{
softirq_vec[nr].action = action;
}
/*
* Tasklets
*/
struct tasklet_head {
struct tasklet_struct *head;
struct tasklet_struct **tail;
};
static DEFINE_PER_CPU(struct tasklet_head, tasklet_vec);
static DEFINE_PER_CPU(struct tasklet_head, tasklet_hi_vec);
static void __tasklet_schedule_common(struct tasklet_struct *t,
struct tasklet_head __percpu *headp,
unsigned int softirq_nr)
{
struct tasklet_head *head;
unsigned long flags;
local_irq_save(flags);
head = this_cpu_ptr(headp);
t->next = NULL;
*head->tail = t;
head->tail = &(t->next);
raise_softirq_irqoff(softirq_nr);
local_irq_restore(flags);
}
void __tasklet_schedule(struct tasklet_struct *t)
{
__tasklet_schedule_common(t, &tasklet_vec,
TASKLET_SOFTIRQ);
}
EXPORT_SYMBOL(__tasklet_schedule);
void __tasklet_hi_schedule(struct tasklet_struct *t)
{
__tasklet_schedule_common(t, &tasklet_hi_vec,
HI_SOFTIRQ);
}
EXPORT_SYMBOL(__tasklet_hi_schedule);
static void tasklet_action_common(struct softirq_action *a,
struct tasklet_head *tl_head,
unsigned int softirq_nr)
{
struct tasklet_struct *list;
local_irq_disable();
list = tl_head->head;
tl_head->head = NULL;
tl_head->tail = &tl_head->head;
local_irq_enable();
while (list) {
struct tasklet_struct *t = list;
list = list->next;
if (tasklet_trylock(t)) {
if (!atomic_read(&t->count)) {
if (!test_and_clear_bit(TASKLET_STATE_SCHED,
&t->state))
BUG();
t->func(t->data);
tasklet_unlock(t);
continue;
}
tasklet_unlock(t);
}
local_irq_disable();
t->next = NULL;
*tl_head->tail = t;
tl_head->tail = &t->next;
__raise_softirq_irqoff(softirq_nr);
local_irq_enable();
}
}
static __latent_entropy void tasklet_action(struct softirq_action *a)
{
tasklet_action_common(a, this_cpu_ptr(&tasklet_vec), TASKLET_SOFTIRQ);
}
static __latent_entropy void tasklet_hi_action(struct softirq_action *a)
{
tasklet_action_common(a, this_cpu_ptr(&tasklet_hi_vec), HI_SOFTIRQ);
}
void tasklet_init(struct tasklet_struct *t,
void (*func)(unsigned long), unsigned long data)
{
t->next = NULL;
t->state = 0;
atomic_set(&t->count, 0);
t->func = func;
t->data = data;
}
EXPORT_SYMBOL(tasklet_init);
void tasklet_kill(struct tasklet_struct *t)
{
if (in_interrupt())
pr_notice("Attempt to kill tasklet from interrupt\n");
while (test_and_set_bit(TASKLET_STATE_SCHED, &t->state)) {
do {
yield();
} while (test_bit(TASKLET_STATE_SCHED, &t->state));
}
tasklet_unlock_wait(t);
clear_bit(TASKLET_STATE_SCHED, &t->state);
}
EXPORT_SYMBOL(tasklet_kill);
/*
* tasklet_hrtimer
*/
/*
* The trampoline is called when the hrtimer expires. It schedules a tasklet
* to run __tasklet_hrtimer_trampoline() which in turn will call the intended
* hrtimer callback, but from softirq context.
*/
static enum hrtimer_restart __hrtimer_tasklet_trampoline(struct hrtimer *timer)
{
struct tasklet_hrtimer *ttimer =
container_of(timer, struct tasklet_hrtimer, timer);
tasklet_hi_schedule(&ttimer->tasklet);
return HRTIMER_NORESTART;
}
/*
* Helper function which calls the hrtimer callback from
* tasklet/softirq context
*/
static void __tasklet_hrtimer_trampoline(unsigned long data)
{
struct tasklet_hrtimer *ttimer = (void *)data;
enum hrtimer_restart restart;
restart = ttimer->function(&ttimer->timer);
if (restart != HRTIMER_NORESTART)
hrtimer_restart(&ttimer->timer);
}
/**
* tasklet_hrtimer_init - Init a tasklet/hrtimer combo for softirq callbacks
* @ttimer: tasklet_hrtimer which is initialized
* @function: hrtimer callback function which gets called from softirq context
* @which_clock: clock id (CLOCK_MONOTONIC/CLOCK_REALTIME)
* @mode: hrtimer mode (HRTIMER_MODE_ABS/HRTIMER_MODE_REL)
*/
void tasklet_hrtimer_init(struct tasklet_hrtimer *ttimer,
enum hrtimer_restart (*function)(struct hrtimer *),
clockid_t which_clock, enum hrtimer_mode mode)
{
hrtimer_init(&ttimer->timer, which_clock, mode);
ttimer->timer.function = __hrtimer_tasklet_trampoline;
tasklet_init(&ttimer->tasklet, __tasklet_hrtimer_trampoline,
(unsigned long)ttimer);
ttimer->function = function;
}
EXPORT_SYMBOL_GPL(tasklet_hrtimer_init);
void __init softirq_init(void)
{
int cpu;
for_each_possible_cpu(cpu) {
per_cpu(tasklet_vec, cpu).tail =
&per_cpu(tasklet_vec, cpu).head;
per_cpu(tasklet_hi_vec, cpu).tail =
&per_cpu(tasklet_hi_vec, cpu).head;
}
open_softirq(TASKLET_SOFTIRQ, tasklet_action);
open_softirq(HI_SOFTIRQ, tasklet_hi_action);
}
static int ksoftirqd_should_run(unsigned int cpu)
{
return local_softirq_pending();
}
static void run_ksoftirqd(unsigned int cpu)
{
local_irq_disable();
if (local_softirq_pending()) {
/*
* We can safely run softirq on inline stack, as we are not deep
* in the task stack here.
*/
__do_softirq();
local_irq_enable();
cond_resched();
return;
}
local_irq_enable();
}
#ifdef CONFIG_HOTPLUG_CPU
/*
* tasklet_kill_immediate is called to remove a tasklet which can already be
* scheduled for execution on @cpu.
*
* Unlike tasklet_kill, this function removes the tasklet
* _immediately_, even if the tasklet is in TASKLET_STATE_SCHED state.
*
* When this function is called, @cpu must be in the CPU_DEAD state.
*/
void tasklet_kill_immediate(struct tasklet_struct *t, unsigned int cpu)
{
struct tasklet_struct **i;
BUG_ON(cpu_online(cpu));
BUG_ON(test_bit(TASKLET_STATE_RUN, &t->state));
if (!test_bit(TASKLET_STATE_SCHED, &t->state))
return;
/* CPU is dead, so no lock needed. */
for (i = &per_cpu(tasklet_vec, cpu).head; *i; i = &(*i)->next) {
if (*i == t) {
*i = t->next;
/* If this was the tail element, move the tail ptr */
if (*i == NULL)
per_cpu(tasklet_vec, cpu).tail = i;
return;
}
}
BUG();
}
static int takeover_tasklets(unsigned int cpu)
{
/* CPU is dead, so no lock needed. */
local_irq_disable();
/* Find end, append list for that CPU. */
if (&per_cpu(tasklet_vec, cpu).head != per_cpu(tasklet_vec, cpu).tail) {
*__this_cpu_read(tasklet_vec.tail) = per_cpu(tasklet_vec, cpu).head;
this_cpu_write(tasklet_vec.tail, per_cpu(tasklet_vec, cpu).tail);
per_cpu(tasklet_vec, cpu).head = NULL;
per_cpu(tasklet_vec, cpu).tail = &per_cpu(tasklet_vec, cpu).head;
}
raise_softirq_irqoff(TASKLET_SOFTIRQ);
if (&per_cpu(tasklet_hi_vec, cpu).head != per_cpu(tasklet_hi_vec, cpu).tail) {
*__this_cpu_read(tasklet_hi_vec.tail) = per_cpu(tasklet_hi_vec, cpu).head;
__this_cpu_write(tasklet_hi_vec.tail, per_cpu(tasklet_hi_vec, cpu).tail);
per_cpu(tasklet_hi_vec, cpu).head = NULL;
per_cpu(tasklet_hi_vec, cpu).tail = &per_cpu(tasklet_hi_vec, cpu).head;
}
raise_softirq_irqoff(HI_SOFTIRQ);
local_irq_enable();
return 0;
}
#else
#define takeover_tasklets NULL
#endif /* CONFIG_HOTPLUG_CPU */
static struct smp_hotplug_thread softirq_threads = {
.store = &ksoftirqd,
.thread_should_run = ksoftirqd_should_run,
.thread_fn = run_ksoftirqd,
.thread_comm = "ksoftirqd/%u",
};
static __init int spawn_ksoftirqd(void)
{
cpuhp_setup_state_nocalls(CPUHP_SOFTIRQ_DEAD, "softirq:dead", NULL,
takeover_tasklets);
BUG_ON(smpboot_register_percpu_thread(&softirq_threads));
return 0;
}
early_initcall(spawn_ksoftirqd);
/*
* [ These __weak aliases are kept in a separate compilation unit, so that
* GCC does not inline them incorrectly. ]
*/
int __init __weak early_irq_init(void)
{
return 0;
}
int __init __weak arch_probe_nr_irqs(void)
{
return NR_IRQS_LEGACY;
}
int __init __weak arch_early_irq_init(void)
{
return 0;
}
unsigned int __weak arch_dynirq_lower_bound(unsigned int from)
{
return from;
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_205_1 |
crossvul-cpp_data_good_3298_0 | /*
* PNG image format
* Copyright (c) 2003 Fabrice Bellard
*
* This file is part of FFmpeg.
*
* FFmpeg 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.
*
* FFmpeg 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 FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
//#define DEBUG
#include "libavutil/avassert.h"
#include "libavutil/bprint.h"
#include "libavutil/imgutils.h"
#include "libavutil/stereo3d.h"
#include "avcodec.h"
#include "bytestream.h"
#include "internal.h"
#include "apng.h"
#include "png.h"
#include "pngdsp.h"
#include "thread.h"
#include <zlib.h>
typedef struct PNGDecContext {
PNGDSPContext dsp;
AVCodecContext *avctx;
GetByteContext gb;
ThreadFrame previous_picture;
ThreadFrame last_picture;
ThreadFrame picture;
int state;
int width, height;
int cur_w, cur_h;
int last_w, last_h;
int x_offset, y_offset;
int last_x_offset, last_y_offset;
uint8_t dispose_op, blend_op;
uint8_t last_dispose_op;
int bit_depth;
int color_type;
int compression_type;
int interlace_type;
int filter_type;
int channels;
int bits_per_pixel;
int bpp;
int has_trns;
uint8_t transparent_color_be[6];
uint8_t *image_buf;
int image_linesize;
uint32_t palette[256];
uint8_t *crow_buf;
uint8_t *last_row;
unsigned int last_row_size;
uint8_t *tmp_row;
unsigned int tmp_row_size;
uint8_t *buffer;
int buffer_size;
int pass;
int crow_size; /* compressed row size (include filter type) */
int row_size; /* decompressed row size */
int pass_row_size; /* decompress row size of the current pass */
int y;
z_stream zstream;
} PNGDecContext;
/* Mask to determine which pixels are valid in a pass */
static const uint8_t png_pass_mask[NB_PASSES] = {
0x01, 0x01, 0x11, 0x11, 0x55, 0x55, 0xff,
};
/* Mask to determine which y pixels can be written in a pass */
static const uint8_t png_pass_dsp_ymask[NB_PASSES] = {
0xff, 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
};
/* Mask to determine which pixels to overwrite while displaying */
static const uint8_t png_pass_dsp_mask[NB_PASSES] = {
0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff
};
/* NOTE: we try to construct a good looking image at each pass. width
* is the original image width. We also do pixel format conversion at
* this stage */
static void png_put_interlaced_row(uint8_t *dst, int width,
int bits_per_pixel, int pass,
int color_type, const uint8_t *src)
{
int x, mask, dsp_mask, j, src_x, b, bpp;
uint8_t *d;
const uint8_t *s;
mask = png_pass_mask[pass];
dsp_mask = png_pass_dsp_mask[pass];
switch (bits_per_pixel) {
case 1:
src_x = 0;
for (x = 0; x < width; x++) {
j = (x & 7);
if ((dsp_mask << j) & 0x80) {
b = (src[src_x >> 3] >> (7 - (src_x & 7))) & 1;
dst[x >> 3] &= 0xFF7F>>j;
dst[x >> 3] |= b << (7 - j);
}
if ((mask << j) & 0x80)
src_x++;
}
break;
case 2:
src_x = 0;
for (x = 0; x < width; x++) {
int j2 = 2 * (x & 3);
j = (x & 7);
if ((dsp_mask << j) & 0x80) {
b = (src[src_x >> 2] >> (6 - 2*(src_x & 3))) & 3;
dst[x >> 2] &= 0xFF3F>>j2;
dst[x >> 2] |= b << (6 - j2);
}
if ((mask << j) & 0x80)
src_x++;
}
break;
case 4:
src_x = 0;
for (x = 0; x < width; x++) {
int j2 = 4*(x&1);
j = (x & 7);
if ((dsp_mask << j) & 0x80) {
b = (src[src_x >> 1] >> (4 - 4*(src_x & 1))) & 15;
dst[x >> 1] &= 0xFF0F>>j2;
dst[x >> 1] |= b << (4 - j2);
}
if ((mask << j) & 0x80)
src_x++;
}
break;
default:
bpp = bits_per_pixel >> 3;
d = dst;
s = src;
for (x = 0; x < width; x++) {
j = x & 7;
if ((dsp_mask << j) & 0x80) {
memcpy(d, s, bpp);
}
d += bpp;
if ((mask << j) & 0x80)
s += bpp;
}
break;
}
}
void ff_add_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top,
int w, int bpp)
{
int i;
for (i = 0; i < w; i++) {
int a, b, c, p, pa, pb, pc;
a = dst[i - bpp];
b = top[i];
c = top[i - bpp];
p = b - c;
pc = a - c;
pa = abs(p);
pb = abs(pc);
pc = abs(p + pc);
if (pa <= pb && pa <= pc)
p = a;
else if (pb <= pc)
p = b;
else
p = c;
dst[i] = p + src[i];
}
}
#define UNROLL1(bpp, op) \
{ \
r = dst[0]; \
if (bpp >= 2) \
g = dst[1]; \
if (bpp >= 3) \
b = dst[2]; \
if (bpp >= 4) \
a = dst[3]; \
for (; i <= size - bpp; i += bpp) { \
dst[i + 0] = r = op(r, src[i + 0], last[i + 0]); \
if (bpp == 1) \
continue; \
dst[i + 1] = g = op(g, src[i + 1], last[i + 1]); \
if (bpp == 2) \
continue; \
dst[i + 2] = b = op(b, src[i + 2], last[i + 2]); \
if (bpp == 3) \
continue; \
dst[i + 3] = a = op(a, src[i + 3], last[i + 3]); \
} \
}
#define UNROLL_FILTER(op) \
if (bpp == 1) { \
UNROLL1(1, op) \
} else if (bpp == 2) { \
UNROLL1(2, op) \
} else if (bpp == 3) { \
UNROLL1(3, op) \
} else if (bpp == 4) { \
UNROLL1(4, op) \
} \
for (; i < size; i++) { \
dst[i] = op(dst[i - bpp], src[i], last[i]); \
}
/* NOTE: 'dst' can be equal to 'last' */
static void png_filter_row(PNGDSPContext *dsp, uint8_t *dst, int filter_type,
uint8_t *src, uint8_t *last, int size, int bpp)
{
int i, p, r, g, b, a;
switch (filter_type) {
case PNG_FILTER_VALUE_NONE:
memcpy(dst, src, size);
break;
case PNG_FILTER_VALUE_SUB:
for (i = 0; i < bpp; i++)
dst[i] = src[i];
if (bpp == 4) {
p = *(int *)dst;
for (; i < size; i += bpp) {
unsigned s = *(int *)(src + i);
p = ((s & 0x7f7f7f7f) + (p & 0x7f7f7f7f)) ^ ((s ^ p) & 0x80808080);
*(int *)(dst + i) = p;
}
} else {
#define OP_SUB(x, s, l) ((x) + (s))
UNROLL_FILTER(OP_SUB);
}
break;
case PNG_FILTER_VALUE_UP:
dsp->add_bytes_l2(dst, src, last, size);
break;
case PNG_FILTER_VALUE_AVG:
for (i = 0; i < bpp; i++) {
p = (last[i] >> 1);
dst[i] = p + src[i];
}
#define OP_AVG(x, s, l) (((((x) + (l)) >> 1) + (s)) & 0xff)
UNROLL_FILTER(OP_AVG);
break;
case PNG_FILTER_VALUE_PAETH:
for (i = 0; i < bpp; i++) {
p = last[i];
dst[i] = p + src[i];
}
if (bpp > 2 && size > 4) {
/* would write off the end of the array if we let it process
* the last pixel with bpp=3 */
int w = (bpp & 3) ? size - 3 : size;
if (w > i) {
dsp->add_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
i = w;
}
}
ff_add_png_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
break;
}
}
/* This used to be called "deloco" in FFmpeg
* and is actually an inverse reversible colorspace transformation */
#define YUV2RGB(NAME, TYPE) \
static void deloco_ ## NAME(TYPE *dst, int size, int alpha) \
{ \
int i; \
for (i = 0; i < size; i += 3 + alpha) { \
int g = dst [i + 1]; \
dst[i + 0] += g; \
dst[i + 2] += g; \
} \
}
YUV2RGB(rgb8, uint8_t)
YUV2RGB(rgb16, uint16_t)
/* process exactly one decompressed row */
static void png_handle_row(PNGDecContext *s)
{
uint8_t *ptr, *last_row;
int got_line;
if (!s->interlace_type) {
ptr = s->image_buf + s->image_linesize * (s->y + s->y_offset) + s->x_offset * s->bpp;
if (s->y == 0)
last_row = s->last_row;
else
last_row = ptr - s->image_linesize;
png_filter_row(&s->dsp, ptr, s->crow_buf[0], s->crow_buf + 1,
last_row, s->row_size, s->bpp);
/* loco lags by 1 row so that it doesn't interfere with top prediction */
if (s->filter_type == PNG_FILTER_TYPE_LOCO && s->y > 0) {
if (s->bit_depth == 16) {
deloco_rgb16((uint16_t *)(ptr - s->image_linesize), s->row_size / 2,
s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
} else {
deloco_rgb8(ptr - s->image_linesize, s->row_size,
s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
}
}
s->y++;
if (s->y == s->cur_h) {
s->state |= PNG_ALLIMAGE;
if (s->filter_type == PNG_FILTER_TYPE_LOCO) {
if (s->bit_depth == 16) {
deloco_rgb16((uint16_t *)ptr, s->row_size / 2,
s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
} else {
deloco_rgb8(ptr, s->row_size,
s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
}
}
}
} else {
got_line = 0;
for (;;) {
ptr = s->image_buf + s->image_linesize * (s->y + s->y_offset) + s->x_offset * s->bpp;
if ((ff_png_pass_ymask[s->pass] << (s->y & 7)) & 0x80) {
/* if we already read one row, it is time to stop to
* wait for the next one */
if (got_line)
break;
png_filter_row(&s->dsp, s->tmp_row, s->crow_buf[0], s->crow_buf + 1,
s->last_row, s->pass_row_size, s->bpp);
FFSWAP(uint8_t *, s->last_row, s->tmp_row);
FFSWAP(unsigned int, s->last_row_size, s->tmp_row_size);
got_line = 1;
}
if ((png_pass_dsp_ymask[s->pass] << (s->y & 7)) & 0x80) {
png_put_interlaced_row(ptr, s->cur_w, s->bits_per_pixel, s->pass,
s->color_type, s->last_row);
}
s->y++;
if (s->y == s->cur_h) {
memset(s->last_row, 0, s->row_size);
for (;;) {
if (s->pass == NB_PASSES - 1) {
s->state |= PNG_ALLIMAGE;
goto the_end;
} else {
s->pass++;
s->y = 0;
s->pass_row_size = ff_png_pass_row_size(s->pass,
s->bits_per_pixel,
s->cur_w);
s->crow_size = s->pass_row_size + 1;
if (s->pass_row_size != 0)
break;
/* skip pass if empty row */
}
}
}
}
the_end:;
}
}
static int png_decode_idat(PNGDecContext *s, int length)
{
int ret;
s->zstream.avail_in = FFMIN(length, bytestream2_get_bytes_left(&s->gb));
s->zstream.next_in = (unsigned char *)s->gb.buffer;
bytestream2_skip(&s->gb, length);
/* decode one line if possible */
while (s->zstream.avail_in > 0) {
ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
if (ret != Z_OK && ret != Z_STREAM_END) {
av_log(s->avctx, AV_LOG_ERROR, "inflate returned error %d\n", ret);
return AVERROR_EXTERNAL;
}
if (s->zstream.avail_out == 0) {
if (!(s->state & PNG_ALLIMAGE)) {
png_handle_row(s);
}
s->zstream.avail_out = s->crow_size;
s->zstream.next_out = s->crow_buf;
}
if (ret == Z_STREAM_END && s->zstream.avail_in > 0) {
av_log(NULL, AV_LOG_WARNING,
"%d undecompressed bytes left in buffer\n", s->zstream.avail_in);
return 0;
}
}
return 0;
}
static int decode_zbuf(AVBPrint *bp, const uint8_t *data,
const uint8_t *data_end)
{
z_stream zstream;
unsigned char *buf;
unsigned buf_size;
int ret;
zstream.zalloc = ff_png_zalloc;
zstream.zfree = ff_png_zfree;
zstream.opaque = NULL;
if (inflateInit(&zstream) != Z_OK)
return AVERROR_EXTERNAL;
zstream.next_in = (unsigned char *)data;
zstream.avail_in = data_end - data;
av_bprint_init(bp, 0, -1);
while (zstream.avail_in > 0) {
av_bprint_get_buffer(bp, 2, &buf, &buf_size);
if (buf_size < 2) {
ret = AVERROR(ENOMEM);
goto fail;
}
zstream.next_out = buf;
zstream.avail_out = buf_size - 1;
ret = inflate(&zstream, Z_PARTIAL_FLUSH);
if (ret != Z_OK && ret != Z_STREAM_END) {
ret = AVERROR_EXTERNAL;
goto fail;
}
bp->len += zstream.next_out - buf;
if (ret == Z_STREAM_END)
break;
}
inflateEnd(&zstream);
bp->str[bp->len] = 0;
return 0;
fail:
inflateEnd(&zstream);
av_bprint_finalize(bp, NULL);
return ret;
}
static uint8_t *iso88591_to_utf8(const uint8_t *in, size_t size_in)
{
size_t extra = 0, i;
uint8_t *out, *q;
for (i = 0; i < size_in; i++)
extra += in[i] >= 0x80;
if (size_in == SIZE_MAX || extra > SIZE_MAX - size_in - 1)
return NULL;
q = out = av_malloc(size_in + extra + 1);
if (!out)
return NULL;
for (i = 0; i < size_in; i++) {
if (in[i] >= 0x80) {
*(q++) = 0xC0 | (in[i] >> 6);
*(q++) = 0x80 | (in[i] & 0x3F);
} else {
*(q++) = in[i];
}
}
*(q++) = 0;
return out;
}
static int decode_text_chunk(PNGDecContext *s, uint32_t length, int compressed,
AVDictionary **dict)
{
int ret, method;
const uint8_t *data = s->gb.buffer;
const uint8_t *data_end = data + length;
const uint8_t *keyword = data;
const uint8_t *keyword_end = memchr(keyword, 0, data_end - keyword);
uint8_t *kw_utf8 = NULL, *text, *txt_utf8 = NULL;
unsigned text_len;
AVBPrint bp;
if (!keyword_end)
return AVERROR_INVALIDDATA;
data = keyword_end + 1;
if (compressed) {
if (data == data_end)
return AVERROR_INVALIDDATA;
method = *(data++);
if (method)
return AVERROR_INVALIDDATA;
if ((ret = decode_zbuf(&bp, data, data_end)) < 0)
return ret;
text_len = bp.len;
av_bprint_finalize(&bp, (char **)&text);
if (!text)
return AVERROR(ENOMEM);
} else {
text = (uint8_t *)data;
text_len = data_end - text;
}
kw_utf8 = iso88591_to_utf8(keyword, keyword_end - keyword);
txt_utf8 = iso88591_to_utf8(text, text_len);
if (text != data)
av_free(text);
if (!(kw_utf8 && txt_utf8)) {
av_free(kw_utf8);
av_free(txt_utf8);
return AVERROR(ENOMEM);
}
av_dict_set(dict, kw_utf8, txt_utf8,
AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
return 0;
}
static int decode_ihdr_chunk(AVCodecContext *avctx, PNGDecContext *s,
uint32_t length)
{
if (length != 13)
return AVERROR_INVALIDDATA;
if (s->state & PNG_IDAT) {
av_log(avctx, AV_LOG_ERROR, "IHDR after IDAT\n");
return AVERROR_INVALIDDATA;
}
if (s->state & PNG_IHDR) {
av_log(avctx, AV_LOG_ERROR, "Multiple IHDR\n");
return AVERROR_INVALIDDATA;
}
s->width = s->cur_w = bytestream2_get_be32(&s->gb);
s->height = s->cur_h = bytestream2_get_be32(&s->gb);
if (av_image_check_size(s->width, s->height, 0, avctx)) {
s->cur_w = s->cur_h = s->width = s->height = 0;
av_log(avctx, AV_LOG_ERROR, "Invalid image size\n");
return AVERROR_INVALIDDATA;
}
s->bit_depth = bytestream2_get_byte(&s->gb);
s->color_type = bytestream2_get_byte(&s->gb);
s->compression_type = bytestream2_get_byte(&s->gb);
s->filter_type = bytestream2_get_byte(&s->gb);
s->interlace_type = bytestream2_get_byte(&s->gb);
bytestream2_skip(&s->gb, 4); /* crc */
s->state |= PNG_IHDR;
if (avctx->debug & FF_DEBUG_PICT_INFO)
av_log(avctx, AV_LOG_DEBUG, "width=%d height=%d depth=%d color_type=%d "
"compression_type=%d filter_type=%d interlace_type=%d\n",
s->width, s->height, s->bit_depth, s->color_type,
s->compression_type, s->filter_type, s->interlace_type);
return 0;
}
static int decode_phys_chunk(AVCodecContext *avctx, PNGDecContext *s)
{
if (s->state & PNG_IDAT) {
av_log(avctx, AV_LOG_ERROR, "pHYs after IDAT\n");
return AVERROR_INVALIDDATA;
}
avctx->sample_aspect_ratio.num = bytestream2_get_be32(&s->gb);
avctx->sample_aspect_ratio.den = bytestream2_get_be32(&s->gb);
if (avctx->sample_aspect_ratio.num < 0 || avctx->sample_aspect_ratio.den < 0)
avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
bytestream2_skip(&s->gb, 1); /* unit specifier */
bytestream2_skip(&s->gb, 4); /* crc */
return 0;
}
static int decode_idat_chunk(AVCodecContext *avctx, PNGDecContext *s,
uint32_t length, AVFrame *p)
{
int ret;
size_t byte_depth = s->bit_depth > 8 ? 2 : 1;
if (!(s->state & PNG_IHDR)) {
av_log(avctx, AV_LOG_ERROR, "IDAT without IHDR\n");
return AVERROR_INVALIDDATA;
}
if (!(s->state & PNG_IDAT)) {
/* init image info */
avctx->width = s->width;
avctx->height = s->height;
s->channels = ff_png_get_nb_channels(s->color_type);
s->bits_per_pixel = s->bit_depth * s->channels;
s->bpp = (s->bits_per_pixel + 7) >> 3;
s->row_size = (s->cur_w * s->bits_per_pixel + 7) >> 3;
if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
s->color_type == PNG_COLOR_TYPE_RGB) {
avctx->pix_fmt = AV_PIX_FMT_RGB24;
} else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
avctx->pix_fmt = AV_PIX_FMT_RGBA;
} else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
s->color_type == PNG_COLOR_TYPE_GRAY) {
avctx->pix_fmt = AV_PIX_FMT_GRAY8;
} else if (s->bit_depth == 16 &&
s->color_type == PNG_COLOR_TYPE_GRAY) {
avctx->pix_fmt = AV_PIX_FMT_GRAY16BE;
} else if (s->bit_depth == 16 &&
s->color_type == PNG_COLOR_TYPE_RGB) {
avctx->pix_fmt = AV_PIX_FMT_RGB48BE;
} else if (s->bit_depth == 16 &&
s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
} else if ((s->bits_per_pixel == 1 || s->bits_per_pixel == 2 || s->bits_per_pixel == 4 || s->bits_per_pixel == 8) &&
s->color_type == PNG_COLOR_TYPE_PALETTE) {
avctx->pix_fmt = AV_PIX_FMT_PAL8;
} else if (s->bit_depth == 1 && s->bits_per_pixel == 1 && avctx->codec_id != AV_CODEC_ID_APNG) {
avctx->pix_fmt = AV_PIX_FMT_MONOBLACK;
} else if (s->bit_depth == 8 &&
s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
avctx->pix_fmt = AV_PIX_FMT_YA8;
} else if (s->bit_depth == 16 &&
s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
avctx->pix_fmt = AV_PIX_FMT_YA16BE;
} else {
av_log(avctx, AV_LOG_ERROR, "unsupported bit depth %d "
"and color type %d\n",
s->bit_depth, s->color_type);
return AVERROR_INVALIDDATA;
}
if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) {
switch (avctx->pix_fmt) {
case AV_PIX_FMT_RGB24:
avctx->pix_fmt = AV_PIX_FMT_RGBA;
break;
case AV_PIX_FMT_RGB48BE:
avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
break;
case AV_PIX_FMT_GRAY8:
avctx->pix_fmt = AV_PIX_FMT_YA8;
break;
case AV_PIX_FMT_GRAY16BE:
avctx->pix_fmt = AV_PIX_FMT_YA16BE;
break;
default:
avpriv_request_sample(avctx, "bit depth %d "
"and color type %d with TRNS",
s->bit_depth, s->color_type);
return AVERROR_INVALIDDATA;
}
s->bpp += byte_depth;
}
if ((ret = ff_thread_get_buffer(avctx, &s->picture, AV_GET_BUFFER_FLAG_REF)) < 0)
return ret;
if (avctx->codec_id == AV_CODEC_ID_APNG && s->last_dispose_op != APNG_DISPOSE_OP_PREVIOUS) {
ff_thread_release_buffer(avctx, &s->previous_picture);
if ((ret = ff_thread_get_buffer(avctx, &s->previous_picture, AV_GET_BUFFER_FLAG_REF)) < 0)
return ret;
}
ff_thread_finish_setup(avctx);
p->pict_type = AV_PICTURE_TYPE_I;
p->key_frame = 1;
p->interlaced_frame = !!s->interlace_type;
/* compute the compressed row size */
if (!s->interlace_type) {
s->crow_size = s->row_size + 1;
} else {
s->pass = 0;
s->pass_row_size = ff_png_pass_row_size(s->pass,
s->bits_per_pixel,
s->cur_w);
s->crow_size = s->pass_row_size + 1;
}
ff_dlog(avctx, "row_size=%d crow_size =%d\n",
s->row_size, s->crow_size);
s->image_buf = p->data[0];
s->image_linesize = p->linesize[0];
/* copy the palette if needed */
if (avctx->pix_fmt == AV_PIX_FMT_PAL8)
memcpy(p->data[1], s->palette, 256 * sizeof(uint32_t));
/* empty row is used if differencing to the first row */
av_fast_padded_mallocz(&s->last_row, &s->last_row_size, s->row_size);
if (!s->last_row)
return AVERROR_INVALIDDATA;
if (s->interlace_type ||
s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
av_fast_padded_malloc(&s->tmp_row, &s->tmp_row_size, s->row_size);
if (!s->tmp_row)
return AVERROR_INVALIDDATA;
}
/* compressed row */
av_fast_padded_malloc(&s->buffer, &s->buffer_size, s->row_size + 16);
if (!s->buffer)
return AVERROR(ENOMEM);
/* we want crow_buf+1 to be 16-byte aligned */
s->crow_buf = s->buffer + 15;
s->zstream.avail_out = s->crow_size;
s->zstream.next_out = s->crow_buf;
}
s->state |= PNG_IDAT;
/* set image to non-transparent bpp while decompressing */
if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE)
s->bpp -= byte_depth;
ret = png_decode_idat(s, length);
if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE)
s->bpp += byte_depth;
if (ret < 0)
return ret;
bytestream2_skip(&s->gb, 4); /* crc */
return 0;
}
static int decode_plte_chunk(AVCodecContext *avctx, PNGDecContext *s,
uint32_t length)
{
int n, i, r, g, b;
if ((length % 3) != 0 || length > 256 * 3)
return AVERROR_INVALIDDATA;
/* read the palette */
n = length / 3;
for (i = 0; i < n; i++) {
r = bytestream2_get_byte(&s->gb);
g = bytestream2_get_byte(&s->gb);
b = bytestream2_get_byte(&s->gb);
s->palette[i] = (0xFFU << 24) | (r << 16) | (g << 8) | b;
}
for (; i < 256; i++)
s->palette[i] = (0xFFU << 24);
s->state |= PNG_PLTE;
bytestream2_skip(&s->gb, 4); /* crc */
return 0;
}
static int decode_trns_chunk(AVCodecContext *avctx, PNGDecContext *s,
uint32_t length)
{
int v, i;
if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
if (length > 256 || !(s->state & PNG_PLTE))
return AVERROR_INVALIDDATA;
for (i = 0; i < length; i++) {
v = bytestream2_get_byte(&s->gb);
s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
}
} else if (s->color_type == PNG_COLOR_TYPE_GRAY || s->color_type == PNG_COLOR_TYPE_RGB) {
if ((s->color_type == PNG_COLOR_TYPE_GRAY && length != 2) ||
(s->color_type == PNG_COLOR_TYPE_RGB && length != 6))
return AVERROR_INVALIDDATA;
for (i = 0; i < length / 2; i++) {
/* only use the least significant bits */
v = av_mod_uintp2(bytestream2_get_be16(&s->gb), s->bit_depth);
if (s->bit_depth > 8)
AV_WB16(&s->transparent_color_be[2 * i], v);
else
s->transparent_color_be[i] = v;
}
} else {
return AVERROR_INVALIDDATA;
}
bytestream2_skip(&s->gb, 4); /* crc */
s->has_trns = 1;
return 0;
}
static void handle_small_bpp(PNGDecContext *s, AVFrame *p)
{
if (s->bits_per_pixel == 1 && s->color_type == PNG_COLOR_TYPE_PALETTE) {
int i, j, k;
uint8_t *pd = p->data[0];
for (j = 0; j < s->height; j++) {
i = s->width / 8;
for (k = 7; k >= 1; k--)
if ((s->width&7) >= k)
pd[8*i + k - 1] = (pd[i]>>8-k) & 1;
for (i--; i >= 0; i--) {
pd[8*i + 7]= pd[i] & 1;
pd[8*i + 6]= (pd[i]>>1) & 1;
pd[8*i + 5]= (pd[i]>>2) & 1;
pd[8*i + 4]= (pd[i]>>3) & 1;
pd[8*i + 3]= (pd[i]>>4) & 1;
pd[8*i + 2]= (pd[i]>>5) & 1;
pd[8*i + 1]= (pd[i]>>6) & 1;
pd[8*i + 0]= pd[i]>>7;
}
pd += s->image_linesize;
}
} else if (s->bits_per_pixel == 2) {
int i, j;
uint8_t *pd = p->data[0];
for (j = 0; j < s->height; j++) {
i = s->width / 4;
if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
if ((s->width&3) >= 3) pd[4*i + 2]= (pd[i] >> 2) & 3;
if ((s->width&3) >= 2) pd[4*i + 1]= (pd[i] >> 4) & 3;
if ((s->width&3) >= 1) pd[4*i + 0]= pd[i] >> 6;
for (i--; i >= 0; i--) {
pd[4*i + 3]= pd[i] & 3;
pd[4*i + 2]= (pd[i]>>2) & 3;
pd[4*i + 1]= (pd[i]>>4) & 3;
pd[4*i + 0]= pd[i]>>6;
}
} else {
if ((s->width&3) >= 3) pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
if ((s->width&3) >= 2) pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
if ((s->width&3) >= 1) pd[4*i + 0]= ( pd[i]>>6 )*0x55;
for (i--; i >= 0; i--) {
pd[4*i + 3]= ( pd[i] & 3)*0x55;
pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
pd[4*i + 0]= ( pd[i]>>6 )*0x55;
}
}
pd += s->image_linesize;
}
} else if (s->bits_per_pixel == 4) {
int i, j;
uint8_t *pd = p->data[0];
for (j = 0; j < s->height; j++) {
i = s->width/2;
if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
if (s->width&1) pd[2*i+0]= pd[i]>>4;
for (i--; i >= 0; i--) {
pd[2*i + 1] = pd[i] & 15;
pd[2*i + 0] = pd[i] >> 4;
}
} else {
if (s->width & 1) pd[2*i + 0]= (pd[i] >> 4) * 0x11;
for (i--; i >= 0; i--) {
pd[2*i + 1] = (pd[i] & 15) * 0x11;
pd[2*i + 0] = (pd[i] >> 4) * 0x11;
}
}
pd += s->image_linesize;
}
}
}
static int decode_fctl_chunk(AVCodecContext *avctx, PNGDecContext *s,
uint32_t length)
{
uint32_t sequence_number;
int cur_w, cur_h, x_offset, y_offset, dispose_op, blend_op;
if (length != 26)
return AVERROR_INVALIDDATA;
if (!(s->state & PNG_IHDR)) {
av_log(avctx, AV_LOG_ERROR, "fctl before IHDR\n");
return AVERROR_INVALIDDATA;
}
s->last_w = s->cur_w;
s->last_h = s->cur_h;
s->last_x_offset = s->x_offset;
s->last_y_offset = s->y_offset;
s->last_dispose_op = s->dispose_op;
sequence_number = bytestream2_get_be32(&s->gb);
cur_w = bytestream2_get_be32(&s->gb);
cur_h = bytestream2_get_be32(&s->gb);
x_offset = bytestream2_get_be32(&s->gb);
y_offset = bytestream2_get_be32(&s->gb);
bytestream2_skip(&s->gb, 4); /* delay_num (2), delay_den (2) */
dispose_op = bytestream2_get_byte(&s->gb);
blend_op = bytestream2_get_byte(&s->gb);
bytestream2_skip(&s->gb, 4); /* crc */
if (sequence_number == 0 &&
(cur_w != s->width ||
cur_h != s->height ||
x_offset != 0 ||
y_offset != 0) ||
cur_w <= 0 || cur_h <= 0 ||
x_offset < 0 || y_offset < 0 ||
cur_w > s->width - x_offset|| cur_h > s->height - y_offset)
return AVERROR_INVALIDDATA;
if (blend_op != APNG_BLEND_OP_OVER && blend_op != APNG_BLEND_OP_SOURCE) {
av_log(avctx, AV_LOG_ERROR, "Invalid blend_op %d\n", blend_op);
return AVERROR_INVALIDDATA;
}
if ((sequence_number == 0 || !s->previous_picture.f->data[0]) &&
dispose_op == APNG_DISPOSE_OP_PREVIOUS) {
// No previous frame to revert to for the first frame
// Spec says to just treat it as a APNG_DISPOSE_OP_BACKGROUND
dispose_op = APNG_DISPOSE_OP_BACKGROUND;
}
if (blend_op == APNG_BLEND_OP_OVER && !s->has_trns && (
avctx->pix_fmt == AV_PIX_FMT_RGB24 ||
avctx->pix_fmt == AV_PIX_FMT_RGB48BE ||
avctx->pix_fmt == AV_PIX_FMT_PAL8 ||
avctx->pix_fmt == AV_PIX_FMT_GRAY8 ||
avctx->pix_fmt == AV_PIX_FMT_GRAY16BE ||
avctx->pix_fmt == AV_PIX_FMT_MONOBLACK
)) {
// APNG_BLEND_OP_OVER is the same as APNG_BLEND_OP_SOURCE when there is no alpha channel
blend_op = APNG_BLEND_OP_SOURCE;
}
s->cur_w = cur_w;
s->cur_h = cur_h;
s->x_offset = x_offset;
s->y_offset = y_offset;
s->dispose_op = dispose_op;
s->blend_op = blend_op;
return 0;
}
static void handle_p_frame_png(PNGDecContext *s, AVFrame *p)
{
int i, j;
uint8_t *pd = p->data[0];
uint8_t *pd_last = s->last_picture.f->data[0];
int ls = FFMIN(av_image_get_linesize(p->format, s->width, 0), s->width * s->bpp);
ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
for (j = 0; j < s->height; j++) {
for (i = 0; i < ls; i++)
pd[i] += pd_last[i];
pd += s->image_linesize;
pd_last += s->image_linesize;
}
}
// divide by 255 and round to nearest
// apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
#define FAST_DIV255(x) ((((x) + 128) * 257) >> 16)
static int handle_p_frame_apng(AVCodecContext *avctx, PNGDecContext *s,
AVFrame *p)
{
size_t x, y;
uint8_t *buffer;
if (s->blend_op == APNG_BLEND_OP_OVER &&
avctx->pix_fmt != AV_PIX_FMT_RGBA &&
avctx->pix_fmt != AV_PIX_FMT_GRAY8A &&
avctx->pix_fmt != AV_PIX_FMT_PAL8) {
avpriv_request_sample(avctx, "Blending with pixel format %s",
av_get_pix_fmt_name(avctx->pix_fmt));
return AVERROR_PATCHWELCOME;
}
buffer = av_malloc_array(s->image_linesize, s->height);
if (!buffer)
return AVERROR(ENOMEM);
// Do the disposal operation specified by the last frame on the frame
if (s->last_dispose_op != APNG_DISPOSE_OP_PREVIOUS) {
ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
memcpy(buffer, s->last_picture.f->data[0], s->image_linesize * s->height);
if (s->last_dispose_op == APNG_DISPOSE_OP_BACKGROUND)
for (y = s->last_y_offset; y < s->last_y_offset + s->last_h; ++y)
memset(buffer + s->image_linesize * y + s->bpp * s->last_x_offset, 0, s->bpp * s->last_w);
memcpy(s->previous_picture.f->data[0], buffer, s->image_linesize * s->height);
ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
} else {
ff_thread_await_progress(&s->previous_picture, INT_MAX, 0);
memcpy(buffer, s->previous_picture.f->data[0], s->image_linesize * s->height);
}
// Perform blending
if (s->blend_op == APNG_BLEND_OP_SOURCE) {
for (y = s->y_offset; y < s->y_offset + s->cur_h; ++y) {
size_t row_start = s->image_linesize * y + s->bpp * s->x_offset;
memcpy(buffer + row_start, p->data[0] + row_start, s->bpp * s->cur_w);
}
} else { // APNG_BLEND_OP_OVER
for (y = s->y_offset; y < s->y_offset + s->cur_h; ++y) {
uint8_t *foreground = p->data[0] + s->image_linesize * y + s->bpp * s->x_offset;
uint8_t *background = buffer + s->image_linesize * y + s->bpp * s->x_offset;
for (x = s->x_offset; x < s->x_offset + s->cur_w; ++x, foreground += s->bpp, background += s->bpp) {
size_t b;
uint8_t foreground_alpha, background_alpha, output_alpha;
uint8_t output[10];
// Since we might be blending alpha onto alpha, we use the following equations:
// output_alpha = foreground_alpha + (1 - foreground_alpha) * background_alpha
// output = (foreground_alpha * foreground + (1 - foreground_alpha) * background_alpha * background) / output_alpha
switch (avctx->pix_fmt) {
case AV_PIX_FMT_RGBA:
foreground_alpha = foreground[3];
background_alpha = background[3];
break;
case AV_PIX_FMT_GRAY8A:
foreground_alpha = foreground[1];
background_alpha = background[1];
break;
case AV_PIX_FMT_PAL8:
foreground_alpha = s->palette[foreground[0]] >> 24;
background_alpha = s->palette[background[0]] >> 24;
break;
}
if (foreground_alpha == 0)
continue;
if (foreground_alpha == 255) {
memcpy(background, foreground, s->bpp);
continue;
}
if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
// TODO: Alpha blending with PAL8 will likely need the entire image converted over to RGBA first
avpriv_request_sample(avctx, "Alpha blending palette samples");
background[0] = foreground[0];
continue;
}
output_alpha = foreground_alpha + FAST_DIV255((255 - foreground_alpha) * background_alpha);
av_assert0(s->bpp <= 10);
for (b = 0; b < s->bpp - 1; ++b) {
if (output_alpha == 0) {
output[b] = 0;
} else if (background_alpha == 255) {
output[b] = FAST_DIV255(foreground_alpha * foreground[b] + (255 - foreground_alpha) * background[b]);
} else {
output[b] = (255 * foreground_alpha * foreground[b] + (255 - foreground_alpha) * background_alpha * background[b]) / (255 * output_alpha);
}
}
output[b] = output_alpha;
memcpy(background, output, s->bpp);
}
}
}
// Copy blended buffer into the frame and free
memcpy(p->data[0], buffer, s->image_linesize * s->height);
av_free(buffer);
return 0;
}
static int decode_frame_common(AVCodecContext *avctx, PNGDecContext *s,
AVFrame *p, AVPacket *avpkt)
{
AVDictionary *metadata = NULL;
uint32_t tag, length;
int decode_next_dat = 0;
int ret;
for (;;) {
length = bytestream2_get_bytes_left(&s->gb);
if (length <= 0) {
if (avctx->codec_id == AV_CODEC_ID_PNG &&
avctx->skip_frame == AVDISCARD_ALL) {
av_frame_set_metadata(p, metadata);
return 0;
}
if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && length == 0) {
if (!(s->state & PNG_IDAT))
return 0;
else
goto exit_loop;
}
av_log(avctx, AV_LOG_ERROR, "%d bytes left\n", length);
if ( s->state & PNG_ALLIMAGE
&& avctx->strict_std_compliance <= FF_COMPLIANCE_NORMAL)
goto exit_loop;
ret = AVERROR_INVALIDDATA;
goto fail;
}
length = bytestream2_get_be32(&s->gb);
if (length > 0x7fffffff || length > bytestream2_get_bytes_left(&s->gb)) {
av_log(avctx, AV_LOG_ERROR, "chunk too big\n");
ret = AVERROR_INVALIDDATA;
goto fail;
}
tag = bytestream2_get_le32(&s->gb);
if (avctx->debug & FF_DEBUG_STARTCODE)
av_log(avctx, AV_LOG_DEBUG, "png: tag=%c%c%c%c length=%u\n",
(tag & 0xff),
((tag >> 8) & 0xff),
((tag >> 16) & 0xff),
((tag >> 24) & 0xff), length);
if (avctx->codec_id == AV_CODEC_ID_PNG &&
avctx->skip_frame == AVDISCARD_ALL) {
switch(tag) {
case MKTAG('I', 'H', 'D', 'R'):
case MKTAG('p', 'H', 'Y', 's'):
case MKTAG('t', 'E', 'X', 't'):
case MKTAG('I', 'D', 'A', 'T'):
case MKTAG('t', 'R', 'N', 'S'):
break;
default:
goto skip_tag;
}
}
switch (tag) {
case MKTAG('I', 'H', 'D', 'R'):
if ((ret = decode_ihdr_chunk(avctx, s, length)) < 0)
goto fail;
break;
case MKTAG('p', 'H', 'Y', 's'):
if ((ret = decode_phys_chunk(avctx, s)) < 0)
goto fail;
break;
case MKTAG('f', 'c', 'T', 'L'):
if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
goto skip_tag;
if ((ret = decode_fctl_chunk(avctx, s, length)) < 0)
goto fail;
decode_next_dat = 1;
break;
case MKTAG('f', 'd', 'A', 'T'):
if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
goto skip_tag;
if (!decode_next_dat) {
ret = AVERROR_INVALIDDATA;
goto fail;
}
bytestream2_get_be32(&s->gb);
length -= 4;
/* fallthrough */
case MKTAG('I', 'D', 'A', 'T'):
if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && !decode_next_dat)
goto skip_tag;
if ((ret = decode_idat_chunk(avctx, s, length, p)) < 0)
goto fail;
break;
case MKTAG('P', 'L', 'T', 'E'):
if (decode_plte_chunk(avctx, s, length) < 0)
goto skip_tag;
break;
case MKTAG('t', 'R', 'N', 'S'):
if (decode_trns_chunk(avctx, s, length) < 0)
goto skip_tag;
break;
case MKTAG('t', 'E', 'X', 't'):
if (decode_text_chunk(s, length, 0, &metadata) < 0)
av_log(avctx, AV_LOG_WARNING, "Broken tEXt chunk\n");
bytestream2_skip(&s->gb, length + 4);
break;
case MKTAG('z', 'T', 'X', 't'):
if (decode_text_chunk(s, length, 1, &metadata) < 0)
av_log(avctx, AV_LOG_WARNING, "Broken zTXt chunk\n");
bytestream2_skip(&s->gb, length + 4);
break;
case MKTAG('s', 'T', 'E', 'R'): {
int mode = bytestream2_get_byte(&s->gb);
AVStereo3D *stereo3d = av_stereo3d_create_side_data(p);
if (!stereo3d)
goto fail;
if (mode == 0 || mode == 1) {
stereo3d->type = AV_STEREO3D_SIDEBYSIDE;
stereo3d->flags = mode ? 0 : AV_STEREO3D_FLAG_INVERT;
} else {
av_log(avctx, AV_LOG_WARNING,
"Unknown value in sTER chunk (%d)\n", mode);
}
bytestream2_skip(&s->gb, 4); /* crc */
break;
}
case MKTAG('I', 'E', 'N', 'D'):
if (!(s->state & PNG_ALLIMAGE))
av_log(avctx, AV_LOG_ERROR, "IEND without all image\n");
if (!(s->state & (PNG_ALLIMAGE|PNG_IDAT))) {
ret = AVERROR_INVALIDDATA;
goto fail;
}
bytestream2_skip(&s->gb, 4); /* crc */
goto exit_loop;
default:
/* skip tag */
skip_tag:
bytestream2_skip(&s->gb, length + 4);
break;
}
}
exit_loop:
if (avctx->codec_id == AV_CODEC_ID_PNG &&
avctx->skip_frame == AVDISCARD_ALL) {
av_frame_set_metadata(p, metadata);
return 0;
}
if (s->bits_per_pixel <= 4)
handle_small_bpp(s, p);
/* apply transparency if needed */
if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) {
size_t byte_depth = s->bit_depth > 8 ? 2 : 1;
size_t raw_bpp = s->bpp - byte_depth;
unsigned x, y;
for (y = 0; y < s->height; ++y) {
uint8_t *row = &s->image_buf[s->image_linesize * y];
/* since we're updating in-place, we have to go from right to left */
for (x = s->width; x > 0; --x) {
uint8_t *pixel = &row[s->bpp * (x - 1)];
memmove(pixel, &row[raw_bpp * (x - 1)], raw_bpp);
if (!memcmp(pixel, s->transparent_color_be, raw_bpp)) {
memset(&pixel[raw_bpp], 0, byte_depth);
} else {
memset(&pixel[raw_bpp], 0xff, byte_depth);
}
}
}
}
/* handle P-frames only if a predecessor frame is available */
if (s->last_picture.f->data[0]) {
if ( !(avpkt->flags & AV_PKT_FLAG_KEY) && avctx->codec_tag != AV_RL32("MPNG")
&& s->last_picture.f->width == p->width
&& s->last_picture.f->height== p->height
&& s->last_picture.f->format== p->format
) {
if (CONFIG_PNG_DECODER && avctx->codec_id != AV_CODEC_ID_APNG)
handle_p_frame_png(s, p);
else if (CONFIG_APNG_DECODER &&
avctx->codec_id == AV_CODEC_ID_APNG &&
(ret = handle_p_frame_apng(avctx, s, p)) < 0)
goto fail;
}
}
ff_thread_report_progress(&s->picture, INT_MAX, 0);
ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
av_frame_set_metadata(p, metadata);
metadata = NULL;
return 0;
fail:
av_dict_free(&metadata);
ff_thread_report_progress(&s->picture, INT_MAX, 0);
ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
return ret;
}
#if CONFIG_PNG_DECODER
static int decode_frame_png(AVCodecContext *avctx,
void *data, int *got_frame,
AVPacket *avpkt)
{
PNGDecContext *const s = avctx->priv_data;
const uint8_t *buf = avpkt->data;
int buf_size = avpkt->size;
AVFrame *p;
int64_t sig;
int ret;
ff_thread_release_buffer(avctx, &s->last_picture);
FFSWAP(ThreadFrame, s->picture, s->last_picture);
p = s->picture.f;
bytestream2_init(&s->gb, buf, buf_size);
/* check signature */
sig = bytestream2_get_be64(&s->gb);
if (sig != PNGSIG &&
sig != MNGSIG) {
av_log(avctx, AV_LOG_ERROR, "Invalid PNG signature 0x%08"PRIX64".\n", sig);
return AVERROR_INVALIDDATA;
}
s->y = s->state = s->has_trns = 0;
/* init the zlib */
s->zstream.zalloc = ff_png_zalloc;
s->zstream.zfree = ff_png_zfree;
s->zstream.opaque = NULL;
ret = inflateInit(&s->zstream);
if (ret != Z_OK) {
av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
return AVERROR_EXTERNAL;
}
if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
goto the_end;
if (avctx->skip_frame == AVDISCARD_ALL) {
*got_frame = 0;
ret = bytestream2_tell(&s->gb);
goto the_end;
}
if ((ret = av_frame_ref(data, s->picture.f)) < 0)
return ret;
*got_frame = 1;
ret = bytestream2_tell(&s->gb);
the_end:
inflateEnd(&s->zstream);
s->crow_buf = NULL;
return ret;
}
#endif
#if CONFIG_APNG_DECODER
static int decode_frame_apng(AVCodecContext *avctx,
void *data, int *got_frame,
AVPacket *avpkt)
{
PNGDecContext *const s = avctx->priv_data;
int ret;
AVFrame *p;
ff_thread_release_buffer(avctx, &s->last_picture);
FFSWAP(ThreadFrame, s->picture, s->last_picture);
p = s->picture.f;
if (!(s->state & PNG_IHDR)) {
if (!avctx->extradata_size)
return AVERROR_INVALIDDATA;
/* only init fields, there is no zlib use in extradata */
s->zstream.zalloc = ff_png_zalloc;
s->zstream.zfree = ff_png_zfree;
bytestream2_init(&s->gb, avctx->extradata, avctx->extradata_size);
if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
goto end;
}
/* reset state for a new frame */
if ((ret = inflateInit(&s->zstream)) != Z_OK) {
av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
ret = AVERROR_EXTERNAL;
goto end;
}
s->y = 0;
s->state &= ~(PNG_IDAT | PNG_ALLIMAGE);
bytestream2_init(&s->gb, avpkt->data, avpkt->size);
if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
goto end;
if (!(s->state & PNG_ALLIMAGE))
av_log(avctx, AV_LOG_WARNING, "Frame did not contain a complete image\n");
if (!(s->state & (PNG_ALLIMAGE|PNG_IDAT))) {
ret = AVERROR_INVALIDDATA;
goto end;
}
if ((ret = av_frame_ref(data, s->picture.f)) < 0)
goto end;
*got_frame = 1;
ret = bytestream2_tell(&s->gb);
end:
inflateEnd(&s->zstream);
return ret;
}
#endif
#if HAVE_THREADS
static int update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
{
PNGDecContext *psrc = src->priv_data;
PNGDecContext *pdst = dst->priv_data;
int ret;
if (dst == src)
return 0;
ff_thread_release_buffer(dst, &pdst->picture);
if (psrc->picture.f->data[0] &&
(ret = ff_thread_ref_frame(&pdst->picture, &psrc->picture)) < 0)
return ret;
if (CONFIG_APNG_DECODER && dst->codec_id == AV_CODEC_ID_APNG) {
pdst->width = psrc->width;
pdst->height = psrc->height;
pdst->bit_depth = psrc->bit_depth;
pdst->color_type = psrc->color_type;
pdst->compression_type = psrc->compression_type;
pdst->interlace_type = psrc->interlace_type;
pdst->filter_type = psrc->filter_type;
pdst->cur_w = psrc->cur_w;
pdst->cur_h = psrc->cur_h;
pdst->x_offset = psrc->x_offset;
pdst->y_offset = psrc->y_offset;
pdst->has_trns = psrc->has_trns;
memcpy(pdst->transparent_color_be, psrc->transparent_color_be, sizeof(pdst->transparent_color_be));
pdst->dispose_op = psrc->dispose_op;
memcpy(pdst->palette, psrc->palette, sizeof(pdst->palette));
pdst->state |= psrc->state & (PNG_IHDR | PNG_PLTE);
ff_thread_release_buffer(dst, &pdst->last_picture);
if (psrc->last_picture.f->data[0] &&
(ret = ff_thread_ref_frame(&pdst->last_picture, &psrc->last_picture)) < 0)
return ret;
ff_thread_release_buffer(dst, &pdst->previous_picture);
if (psrc->previous_picture.f->data[0] &&
(ret = ff_thread_ref_frame(&pdst->previous_picture, &psrc->previous_picture)) < 0)
return ret;
}
return 0;
}
#endif
static av_cold int png_dec_init(AVCodecContext *avctx)
{
PNGDecContext *s = avctx->priv_data;
avctx->color_range = AVCOL_RANGE_JPEG;
s->avctx = avctx;
s->previous_picture.f = av_frame_alloc();
s->last_picture.f = av_frame_alloc();
s->picture.f = av_frame_alloc();
if (!s->previous_picture.f || !s->last_picture.f || !s->picture.f) {
av_frame_free(&s->previous_picture.f);
av_frame_free(&s->last_picture.f);
av_frame_free(&s->picture.f);
return AVERROR(ENOMEM);
}
if (!avctx->internal->is_copy) {
avctx->internal->allocate_progress = 1;
ff_pngdsp_init(&s->dsp);
}
return 0;
}
static av_cold int png_dec_end(AVCodecContext *avctx)
{
PNGDecContext *s = avctx->priv_data;
ff_thread_release_buffer(avctx, &s->previous_picture);
av_frame_free(&s->previous_picture.f);
ff_thread_release_buffer(avctx, &s->last_picture);
av_frame_free(&s->last_picture.f);
ff_thread_release_buffer(avctx, &s->picture);
av_frame_free(&s->picture.f);
av_freep(&s->buffer);
s->buffer_size = 0;
av_freep(&s->last_row);
s->last_row_size = 0;
av_freep(&s->tmp_row);
s->tmp_row_size = 0;
return 0;
}
#if CONFIG_APNG_DECODER
AVCodec ff_apng_decoder = {
.name = "apng",
.long_name = NULL_IF_CONFIG_SMALL("APNG (Animated Portable Network Graphics) image"),
.type = AVMEDIA_TYPE_VIDEO,
.id = AV_CODEC_ID_APNG,
.priv_data_size = sizeof(PNGDecContext),
.init = png_dec_init,
.close = png_dec_end,
.decode = decode_frame_apng,
.init_thread_copy = ONLY_IF_THREADS_ENABLED(png_dec_init),
.update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
.capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
};
#endif
#if CONFIG_PNG_DECODER
AVCodec ff_png_decoder = {
.name = "png",
.long_name = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
.type = AVMEDIA_TYPE_VIDEO,
.id = AV_CODEC_ID_PNG,
.priv_data_size = sizeof(PNGDecContext),
.init = png_dec_init,
.close = png_dec_end,
.decode = decode_frame_png,
.init_thread_copy = ONLY_IF_THREADS_ENABLED(png_dec_init),
.update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
.capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
.caps_internal = FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM,
};
#endif
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_3298_0 |
crossvul-cpp_data_bad_2776_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) 2008, Jerome Fimes, Communications & Systemes <jerome.fimes@c-s.fr>
* Copyright (c) 2006-2007, Parvatha Elangovan
* Copyright (c) 2010-2011, Kaori Hagihara
* Copyright (c) 2011-2012, Centre National d'Etudes Spatiales (CNES), France
* 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"
/** @defgroup J2K J2K - JPEG-2000 codestream reader/writer */
/*@{*/
/** @name Local static functions */
/*@{*/
#define OPJ_UNUSED(x) (void)x
/**
* Sets up the procedures to do on reading header. Developpers wanting to extend the library can add their own reading procedures.
*/
static OPJ_BOOL opj_j2k_setup_header_reading(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager);
/**
* The read header procedure.
*/
static OPJ_BOOL opj_j2k_read_header_procedure(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* The default encoding validation procedure without any extension.
*
* @param p_j2k the jpeg2000 codec to validate.
* @param p_stream the input stream to validate.
* @param p_manager the user event manager.
*
* @return true if the parameters are correct.
*/
static OPJ_BOOL opj_j2k_encoding_validation(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* The default decoding validation procedure without any extension.
*
* @param p_j2k the jpeg2000 codec to validate.
* @param p_stream the input stream to validate.
* @param p_manager the user event manager.
*
* @return true if the parameters are correct.
*/
static OPJ_BOOL opj_j2k_decoding_validation(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Sets up the validation ,i.e. adds the procedures to lauch to make sure the codec parameters
* are valid. Developpers wanting to extend the library can add their own validation procedures.
*/
static OPJ_BOOL opj_j2k_setup_encoding_validation(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager);
/**
* Sets up the validation ,i.e. adds the procedures to lauch to make sure the codec parameters
* are valid. Developpers wanting to extend the library can add their own validation procedures.
*/
static OPJ_BOOL opj_j2k_setup_decoding_validation(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager);
/**
* Sets up the validation ,i.e. adds the procedures to lauch to make sure the codec parameters
* are valid. Developpers wanting to extend the library can add their own validation procedures.
*/
static OPJ_BOOL opj_j2k_setup_end_compress(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager);
/**
* The mct encoding validation procedure.
*
* @param p_j2k the jpeg2000 codec to validate.
* @param p_stream the input stream to validate.
* @param p_manager the user event manager.
*
* @return true if the parameters are correct.
*/
static OPJ_BOOL opj_j2k_mct_validation(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Builds the tcd decoder to use to decode tile.
*/
static OPJ_BOOL opj_j2k_build_decoder(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Builds the tcd encoder to use to encode tile.
*/
static OPJ_BOOL opj_j2k_build_encoder(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Creates a tile-coder decoder.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_create_tcd(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Excutes the given procedures on the given codec.
*
* @param p_procedure_list the list of procedures to execute
* @param p_j2k the jpeg2000 codec to execute the procedures on.
* @param p_stream the stream to execute the procedures on.
* @param p_manager the user manager.
*
* @return true if all the procedures were successfully executed.
*/
static OPJ_BOOL opj_j2k_exec(opj_j2k_t * p_j2k,
opj_procedure_list_t * p_procedure_list,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Updates the rates of the tcp.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_update_rates(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Copies the decoding tile parameters onto all the tile parameters.
* Creates also the tile decoder.
*/
static OPJ_BOOL opj_j2k_copy_default_tcp_and_create_tcd(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Destroys the memory associated with the decoding of headers.
*/
static OPJ_BOOL opj_j2k_destroy_header_memory(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads the lookup table containing all the marker, status and action, and returns the handler associated
* with the marker value.
* @param p_id Marker value to look up
*
* @return the handler associated with the id.
*/
static const struct opj_dec_memory_marker_handler * opj_j2k_get_marker_handler(
OPJ_UINT32 p_id);
/**
* Destroys a tile coding parameter structure.
*
* @param p_tcp the tile coding parameter to destroy.
*/
static void opj_j2k_tcp_destroy(opj_tcp_t *p_tcp);
/**
* Destroys the data inside a tile coding parameter structure.
*
* @param p_tcp the tile coding parameter which contain data to destroy.
*/
static void opj_j2k_tcp_data_destroy(opj_tcp_t *p_tcp);
/**
* Destroys a coding parameter structure.
*
* @param p_cp the coding parameter to destroy.
*/
static void opj_j2k_cp_destroy(opj_cp_t *p_cp);
/**
* Compare 2 a SPCod/ SPCoc elements, i.e. the coding style of a given component of a tile.
*
* @param p_j2k J2K codec.
* @param p_tile_no Tile number
* @param p_first_comp_no The 1st component number to compare.
* @param p_second_comp_no The 1st component number to compare.
*
* @return OPJ_TRUE if SPCdod are equals.
*/
static OPJ_BOOL opj_j2k_compare_SPCod_SPCoc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no);
/**
* Writes a SPCod or SPCoc element, i.e. the coding style of a given component of a tile.
*
* @param p_j2k J2K codec.
* @param p_tile_no FIXME DOC
* @param p_comp_no the component number to output.
* @param p_data FIXME DOC
* @param p_header_size FIXME DOC
* @param p_manager the user event manager.
*
* @return FIXME DOC
*/
static OPJ_BOOL opj_j2k_write_SPCod_SPCoc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_header_size,
opj_event_mgr_t * p_manager);
/**
* Gets the size taken by writing a SPCod or SPCoc for the given tile and component.
*
* @param p_j2k the J2K codec.
* @param p_tile_no the tile index.
* @param p_comp_no the component being outputted.
*
* @return the number of bytes taken by the SPCod element.
*/
static OPJ_UINT32 opj_j2k_get_SPCod_SPCoc_size(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no);
/**
* Reads a SPCod or SPCoc element, i.e. the coding style of a given component of a tile.
* @param p_j2k the jpeg2000 codec.
* @param compno FIXME DOC
* @param p_header_data the data contained in the COM box.
* @param p_header_size the size of the data contained in the COM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_SPCod_SPCoc(opj_j2k_t *p_j2k,
OPJ_UINT32 compno,
OPJ_BYTE * p_header_data,
OPJ_UINT32 * p_header_size,
opj_event_mgr_t * p_manager);
/**
* Gets the size taken by writing SQcd or SQcc element, i.e. the quantization values of a band in the QCD or QCC.
*
* @param p_tile_no the tile index.
* @param p_comp_no the component being outputted.
* @param p_j2k the J2K codec.
*
* @return the number of bytes taken by the SPCod element.
*/
static OPJ_UINT32 opj_j2k_get_SQcd_SQcc_size(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no);
/**
* Compares 2 SQcd or SQcc element, i.e. the quantization values of a band in the QCD or QCC.
*
* @param p_j2k J2K codec.
* @param p_tile_no the tile to output.
* @param p_first_comp_no the first component number to compare.
* @param p_second_comp_no the second component number to compare.
*
* @return OPJ_TRUE if equals.
*/
static OPJ_BOOL opj_j2k_compare_SQcd_SQcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no);
/**
* Writes a SQcd or SQcc element, i.e. the quantization values of a band in the QCD or QCC.
*
* @param p_tile_no the tile to output.
* @param p_comp_no the component number to output.
* @param p_data the data buffer.
* @param p_header_size pointer to the size of the data buffer, it is changed by the function.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*
*/
static OPJ_BOOL opj_j2k_write_SQcd_SQcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_header_size,
opj_event_mgr_t * p_manager);
/**
* Updates the Tile Length Marker.
*/
static void opj_j2k_update_tlm(opj_j2k_t * p_j2k, OPJ_UINT32 p_tile_part_size);
/**
* Reads a SQcd or SQcc element, i.e. the quantization values of a band in the QCD or QCC.
*
* @param p_j2k J2K codec.
* @param compno the component number to output.
* @param p_header_data the data buffer.
* @param p_header_size pointer to the size of the data buffer, it is changed by the function.
* @param p_manager the user event manager.
*
*/
static OPJ_BOOL opj_j2k_read_SQcd_SQcc(opj_j2k_t *p_j2k,
OPJ_UINT32 compno,
OPJ_BYTE * p_header_data,
OPJ_UINT32 * p_header_size,
opj_event_mgr_t * p_manager);
/**
* Copies the tile component parameters of all the component from the first tile component.
*
* @param p_j2k the J2k codec.
*/
static void opj_j2k_copy_tile_component_parameters(opj_j2k_t *p_j2k);
/**
* Copies the tile quantization parameters of all the component from the first tile component.
*
* @param p_j2k the J2k codec.
*/
static void opj_j2k_copy_tile_quantization_parameters(opj_j2k_t *p_j2k);
/**
* Reads the tiles.
*/
static OPJ_BOOL opj_j2k_decode_tiles(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
static OPJ_BOOL opj_j2k_pre_write_tile(opj_j2k_t * p_j2k,
OPJ_UINT32 p_tile_index,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
static OPJ_BOOL opj_j2k_update_image_data(opj_tcd_t * p_tcd, OPJ_BYTE * p_data,
opj_image_t* p_output_image);
static void opj_get_tile_dimensions(opj_image_t * l_image,
opj_tcd_tilecomp_t * l_tilec,
opj_image_comp_t * l_img_comp,
OPJ_UINT32* l_size_comp,
OPJ_UINT32* l_width,
OPJ_UINT32* l_height,
OPJ_UINT32* l_offset_x,
OPJ_UINT32* l_offset_y,
OPJ_UINT32* l_image_width,
OPJ_UINT32* l_stride,
OPJ_UINT32* l_tile_offset);
static void opj_j2k_get_tile_data(opj_tcd_t * p_tcd, OPJ_BYTE * p_data);
static OPJ_BOOL opj_j2k_post_write_tile(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Sets up the procedures to do on writing header.
* Developers wanting to extend the library can add their own writing procedures.
*/
static OPJ_BOOL opj_j2k_setup_header_writing(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager);
static OPJ_BOOL opj_j2k_write_first_tile_part(opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_total_data_size,
opj_stream_private_t *p_stream,
struct opj_event_mgr * p_manager);
static OPJ_BOOL opj_j2k_write_all_tile_parts(opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_total_data_size,
opj_stream_private_t *p_stream,
struct opj_event_mgr * p_manager);
/**
* Gets the offset of the header.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_get_end_header(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
static OPJ_BOOL opj_j2k_allocate_tile_element_cstr_index(opj_j2k_t *p_j2k);
/*
* -----------------------------------------------------------------------
* -----------------------------------------------------------------------
* -----------------------------------------------------------------------
*/
/**
* Writes the SOC marker (Start Of Codestream)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_soc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a SOC marker (Start of Codestream)
* @param p_j2k the jpeg2000 file codec.
* @param p_stream XXX needs data
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_soc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes the SIZ marker (image and tile size)
*
* @param p_j2k J2K codec.
* @param p_stream the stream to write data to.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_siz(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a SIZ marker (image and tile size)
* @param p_j2k the jpeg2000 file codec.
* @param p_header_data the data contained in the SIZ box.
* @param p_header_size the size of the data contained in the SIZ marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_siz(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the COM marker (comment)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_com(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a COM marker (comments)
* @param p_j2k the jpeg2000 file codec.
* @param p_header_data the data contained in the COM box.
* @param p_header_size the size of the data contained in the COM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_com(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the COD marker (Coding style default)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_cod(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a COD marker (Coding Styke defaults)
* @param p_header_data the data contained in the COD box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the COD marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_cod(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Compares 2 COC markers (Coding style component)
*
* @param p_j2k J2K codec.
* @param p_first_comp_no the index of the first component to compare.
* @param p_second_comp_no the index of the second component to compare.
*
* @return OPJ_TRUE if equals
*/
static OPJ_BOOL opj_j2k_compare_coc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no);
/**
* Writes the COC marker (Coding style component)
*
* @param p_j2k J2K codec.
* @param p_comp_no the index of the component to output.
* @param p_stream the stream to write data to.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_coc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes the COC marker (Coding style component)
*
* @param p_j2k J2K codec.
* @param p_comp_no the index of the component to output.
* @param p_data FIXME DOC
* @param p_data_written FIXME DOC
* @param p_manager the user event manager.
*/
static void opj_j2k_write_coc_in_memory(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
opj_event_mgr_t * p_manager);
/**
* Gets the maximum size taken by a coc.
*
* @param p_j2k the jpeg2000 codec to use.
*/
static OPJ_UINT32 opj_j2k_get_max_coc_size(opj_j2k_t *p_j2k);
/**
* Reads a COC marker (Coding Style Component)
* @param p_header_data the data contained in the COC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the COC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_coc(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the QCD marker (quantization default)
*
* @param p_j2k J2K codec.
* @param p_stream the stream to write data to.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_qcd(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a QCD marker (Quantization defaults)
* @param p_header_data the data contained in the QCD box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the QCD marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_qcd(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Compare QCC markers (quantization component)
*
* @param p_j2k J2K codec.
* @param p_first_comp_no the index of the first component to compare.
* @param p_second_comp_no the index of the second component to compare.
*
* @return OPJ_TRUE if equals.
*/
static OPJ_BOOL opj_j2k_compare_qcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no);
/**
* Writes the QCC marker (quantization component)
*
* @param p_comp_no the index of the component to output.
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_qcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes the QCC marker (quantization component)
*
* @param p_j2k J2K codec.
* @param p_comp_no the index of the component to output.
* @param p_data FIXME DOC
* @param p_data_written the stream to write data to.
* @param p_manager the user event manager.
*/
static void opj_j2k_write_qcc_in_memory(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
opj_event_mgr_t * p_manager);
/**
* Gets the maximum size taken by a qcc.
*/
static OPJ_UINT32 opj_j2k_get_max_qcc_size(opj_j2k_t *p_j2k);
/**
* Reads a QCC marker (Quantization component)
* @param p_header_data the data contained in the QCC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the QCC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_qcc(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the POC marker (Progression Order Change)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_poc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes the POC marker (Progression Order Change)
*
* @param p_j2k J2K codec.
* @param p_data FIXME DOC
* @param p_data_written the stream to write data to.
* @param p_manager the user event manager.
*/
static void opj_j2k_write_poc_in_memory(opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
opj_event_mgr_t * p_manager);
/**
* Gets the maximum size taken by the writing of a POC.
*/
static OPJ_UINT32 opj_j2k_get_max_poc_size(opj_j2k_t *p_j2k);
/**
* Reads a POC marker (Progression Order Change)
*
* @param p_header_data the data contained in the POC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the POC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_poc(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Gets the maximum size taken by the toc headers of all the tile parts of any given tile.
*/
static OPJ_UINT32 opj_j2k_get_max_toc_size(opj_j2k_t *p_j2k);
/**
* Gets the maximum size taken by the headers of the SOT.
*
* @param p_j2k the jpeg2000 codec to use.
*/
static OPJ_UINT32 opj_j2k_get_specific_header_sizes(opj_j2k_t *p_j2k);
/**
* Reads a CRG marker (Component registration)
*
* @param p_header_data the data contained in the TLM box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the TLM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_crg(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Reads a TLM marker (Tile Length Marker)
*
* @param p_header_data the data contained in the TLM box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the TLM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_tlm(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the updated tlm.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_updated_tlm(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a PLM marker (Packet length, main header marker)
*
* @param p_header_data the data contained in the TLM box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the TLM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_plm(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Reads a PLT marker (Packet length, tile-part header)
*
* @param p_header_data the data contained in the PLT box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the PLT marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_plt(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Reads a PPM marker (Packed headers, main header)
*
* @param p_header_data the data contained in the POC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the POC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_ppm(
opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Merges all PPM markers read (Packed headers, main header)
*
* @param p_cp main coding parameters.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_merge_ppm(opj_cp_t *p_cp, opj_event_mgr_t * p_manager);
/**
* Reads a PPT marker (Packed packet headers, tile-part header)
*
* @param p_header_data the data contained in the PPT box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the PPT marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_ppt(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Merges all PPT markers read (Packed headers, tile-part header)
*
* @param p_tcp the tile.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_merge_ppt(opj_tcp_t *p_tcp,
opj_event_mgr_t * p_manager);
/**
* Writes the TLM marker (Tile Length Marker)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_tlm(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes the SOT marker (Start of tile-part)
*
* @param p_j2k J2K codec.
* @param p_data FIXME DOC
* @param p_data_written FIXME DOC
* @param p_stream the stream to write data to.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_sot(opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
const opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads values from a SOT marker (Start of tile-part)
*
* the j2k decoder state is not affected. No side effects, no checks except for p_header_size.
*
* @param p_header_data the data contained in the SOT marker.
* @param p_header_size the size of the data contained in the SOT marker.
* @param p_tile_no Isot.
* @param p_tot_len Psot.
* @param p_current_part TPsot.
* @param p_num_parts TNsot.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_get_sot_values(OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
OPJ_UINT32* p_tile_no,
OPJ_UINT32* p_tot_len,
OPJ_UINT32* p_current_part,
OPJ_UINT32* p_num_parts,
opj_event_mgr_t * p_manager);
/**
* Reads a SOT marker (Start of tile-part)
*
* @param p_header_data the data contained in the SOT marker.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the PPT marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_sot(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the SOD marker (Start of data)
*
* @param p_j2k J2K codec.
* @param p_tile_coder FIXME DOC
* @param p_data FIXME DOC
* @param p_data_written FIXME DOC
* @param p_total_data_size FIXME DOC
* @param p_stream the stream to write data to.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_sod(opj_j2k_t *p_j2k,
opj_tcd_t * p_tile_coder,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_total_data_size,
const opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a SOD marker (Start Of Data)
*
* @param p_j2k the jpeg2000 codec.
* @param p_stream FIXME DOC
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_sod(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
static void opj_j2k_update_tlm(opj_j2k_t * p_j2k, OPJ_UINT32 p_tile_part_size)
{
opj_write_bytes(p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current,
p_j2k->m_current_tile_number, 1); /* PSOT */
++p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current;
opj_write_bytes(p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current,
p_tile_part_size, 4); /* PSOT */
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current += 4;
}
/**
* Writes the RGN marker (Region Of Interest)
*
* @param p_tile_no the tile to output
* @param p_comp_no the component to output
* @param nb_comps the number of components
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_rgn(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no,
OPJ_UINT32 nb_comps,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a RGN marker (Region Of Interest)
*
* @param p_header_data the data contained in the POC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the POC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_rgn(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the EOC marker (End of Codestream)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_eoc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
#if 0
/**
* Reads a EOC marker (End Of Codestream)
*
* @param p_j2k the jpeg2000 codec.
* @param p_stream FIXME DOC
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_eoc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
#endif
/**
* Writes the CBD-MCT-MCC-MCO markers (Multi components transform)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_mct_data_group(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Inits the Info
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_init_info(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
Add main header marker information
@param cstr_index Codestream information structure
@param type marker type
@param pos byte offset of marker segment
@param len length of marker segment
*/
static OPJ_BOOL opj_j2k_add_mhmarker(opj_codestream_index_t *cstr_index,
OPJ_UINT32 type, OPJ_OFF_T pos, OPJ_UINT32 len) ;
/**
Add tile header marker information
@param tileno tile index number
@param cstr_index Codestream information structure
@param type marker type
@param pos byte offset of marker segment
@param len length of marker segment
*/
static OPJ_BOOL opj_j2k_add_tlmarker(OPJ_UINT32 tileno,
opj_codestream_index_t *cstr_index, OPJ_UINT32 type, OPJ_OFF_T pos,
OPJ_UINT32 len);
/**
* Reads an unknown marker
*
* @param p_j2k the jpeg2000 codec.
* @param p_stream the stream object to read from.
* @param output_marker FIXME DOC
* @param p_manager the user event manager.
*
* @return true if the marker could be deduced.
*/
static OPJ_BOOL opj_j2k_read_unk(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
OPJ_UINT32 *output_marker,
opj_event_mgr_t * p_manager);
/**
* Writes the MCT marker (Multiple Component Transform)
*
* @param p_j2k J2K codec.
* @param p_mct_record FIXME DOC
* @param p_stream the stream to write data to.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_mct_record(opj_j2k_t *p_j2k,
opj_mct_data_t * p_mct_record,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a MCT marker (Multiple Component Transform)
*
* @param p_header_data the data contained in the MCT box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the MCT marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_mct(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the MCC marker (Multiple Component Collection)
*
* @param p_j2k J2K codec.
* @param p_mcc_record FIXME DOC
* @param p_stream the stream to write data to.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_mcc_record(opj_j2k_t *p_j2k,
opj_simple_mcc_decorrelation_data_t * p_mcc_record,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a MCC marker (Multiple Component Collection)
*
* @param p_header_data the data contained in the MCC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the MCC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_mcc(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the MCO marker (Multiple component transformation ordering)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_mco(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a MCO marker (Multiple Component Transform Ordering)
*
* @param p_header_data the data contained in the MCO box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the MCO marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_mco(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
static OPJ_BOOL opj_j2k_add_mct(opj_tcp_t * p_tcp, opj_image_t * p_image,
OPJ_UINT32 p_index);
static void opj_j2k_read_int16_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_read_int32_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_read_float32_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_read_float64_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_read_int16_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_read_int32_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_read_float32_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_read_float64_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_write_float_to_int16(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_write_float_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_write_float_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_write_float_to_float64(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
/**
* Ends the encoding, i.e. frees memory.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_end_encoding(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes the CBD marker (Component bit depth definition)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_cbd(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Reads a CBD marker (Component bit depth definition)
* @param p_header_data the data contained in the CBD box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the CBD marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_cbd(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes COC marker for each component.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_all_coc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes QCC marker for each component.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_all_qcc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes regions of interests.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_regions(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Writes EPC ????
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_epc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Checks the progression order changes values. Tells of the poc given as input are valid.
* A nice message is outputted at errors.
*
* @param p_pocs the progression order changes.
* @param p_nb_pocs the number of progression order changes.
* @param p_nb_resolutions the number of resolutions.
* @param numcomps the number of components
* @param numlayers the number of layers.
* @param p_manager the user event manager.
*
* @return true if the pocs are valid.
*/
static OPJ_BOOL opj_j2k_check_poc_val(const opj_poc_t *p_pocs,
OPJ_UINT32 p_nb_pocs,
OPJ_UINT32 p_nb_resolutions,
OPJ_UINT32 numcomps,
OPJ_UINT32 numlayers,
opj_event_mgr_t * p_manager);
/**
* Gets the number of tile parts used for the given change of progression (if any) and the given tile.
*
* @param cp the coding parameters.
* @param pino the offset of the given poc (i.e. its position in the coding parameter).
* @param tileno the given tile.
*
* @return the number of tile parts.
*/
static OPJ_UINT32 opj_j2k_get_num_tp(opj_cp_t *cp, OPJ_UINT32 pino,
OPJ_UINT32 tileno);
/**
* Calculates the total number of tile parts needed by the encoder to
* encode such an image. If not enough memory is available, then the function return false.
*
* @param p_nb_tiles pointer that will hold the number of tile parts.
* @param cp the coding parameters for the image.
* @param image the image to encode.
* @param p_j2k the p_j2k encoder.
* @param p_manager the user event manager.
*
* @return true if the function was successful, false else.
*/
static OPJ_BOOL opj_j2k_calculate_tp(opj_j2k_t *p_j2k,
opj_cp_t *cp,
OPJ_UINT32 * p_nb_tiles,
opj_image_t *image,
opj_event_mgr_t * p_manager);
static void opj_j2k_dump_MH_info(opj_j2k_t* p_j2k, FILE* out_stream);
static void opj_j2k_dump_MH_index(opj_j2k_t* p_j2k, FILE* out_stream);
static opj_codestream_index_t* opj_j2k_create_cstr_index(void);
static OPJ_FLOAT32 opj_j2k_get_tp_stride(opj_tcp_t * p_tcp);
static OPJ_FLOAT32 opj_j2k_get_default_stride(opj_tcp_t * p_tcp);
static int opj_j2k_initialise_4K_poc(opj_poc_t *POC, int numres);
static void opj_j2k_set_cinema_parameters(opj_cparameters_t *parameters,
opj_image_t *image, opj_event_mgr_t *p_manager);
static OPJ_BOOL opj_j2k_is_cinema_compliant(opj_image_t *image, OPJ_UINT16 rsiz,
opj_event_mgr_t *p_manager);
/**
* Checks for invalid number of tile-parts in SOT marker (TPsot==TNsot). See issue 254.
*
* @param p_stream the stream to read data from.
* @param tile_no tile number we're looking for.
* @param p_correction_needed output value. if true, non conformant codestream needs TNsot correction.
* @param p_manager the user event manager.
*
* @return true if the function was successful, false else.
*/
static OPJ_BOOL opj_j2k_need_nb_tile_parts_correction(opj_stream_private_t
*p_stream, OPJ_UINT32 tile_no, OPJ_BOOL* p_correction_needed,
opj_event_mgr_t * p_manager);
/*@}*/
/*@}*/
/* ----------------------------------------------------------------------- */
typedef struct j2k_prog_order {
OPJ_PROG_ORDER enum_prog;
char str_prog[5];
} j2k_prog_order_t;
static const j2k_prog_order_t j2k_prog_order_list[] = {
{OPJ_CPRL, "CPRL"},
{OPJ_LRCP, "LRCP"},
{OPJ_PCRL, "PCRL"},
{OPJ_RLCP, "RLCP"},
{OPJ_RPCL, "RPCL"},
{(OPJ_PROG_ORDER) - 1, ""}
};
/**
* FIXME DOC
*/
static const OPJ_UINT32 MCT_ELEMENT_SIZE [] = {
2,
4,
4,
8
};
typedef void (* opj_j2k_mct_function)(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem);
static const opj_j2k_mct_function j2k_mct_read_functions_to_float [] = {
opj_j2k_read_int16_to_float,
opj_j2k_read_int32_to_float,
opj_j2k_read_float32_to_float,
opj_j2k_read_float64_to_float
};
static const opj_j2k_mct_function j2k_mct_read_functions_to_int32 [] = {
opj_j2k_read_int16_to_int32,
opj_j2k_read_int32_to_int32,
opj_j2k_read_float32_to_int32,
opj_j2k_read_float64_to_int32
};
static const opj_j2k_mct_function j2k_mct_write_functions_from_float [] = {
opj_j2k_write_float_to_int16,
opj_j2k_write_float_to_int32,
opj_j2k_write_float_to_float,
opj_j2k_write_float_to_float64
};
typedef struct opj_dec_memory_marker_handler {
/** marker value */
OPJ_UINT32 id;
/** value of the state when the marker can appear */
OPJ_UINT32 states;
/** action linked to the marker */
OPJ_BOOL(*handler)(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
}
opj_dec_memory_marker_handler_t;
static const opj_dec_memory_marker_handler_t j2k_memory_marker_handler_tab [] =
{
{J2K_MS_SOT, J2K_STATE_MH | J2K_STATE_TPHSOT, opj_j2k_read_sot},
{J2K_MS_COD, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_cod},
{J2K_MS_COC, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_coc},
{J2K_MS_RGN, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_rgn},
{J2K_MS_QCD, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_qcd},
{J2K_MS_QCC, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_qcc},
{J2K_MS_POC, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_poc},
{J2K_MS_SIZ, J2K_STATE_MHSIZ, opj_j2k_read_siz},
{J2K_MS_TLM, J2K_STATE_MH, opj_j2k_read_tlm},
{J2K_MS_PLM, J2K_STATE_MH, opj_j2k_read_plm},
{J2K_MS_PLT, J2K_STATE_TPH, opj_j2k_read_plt},
{J2K_MS_PPM, J2K_STATE_MH, opj_j2k_read_ppm},
{J2K_MS_PPT, J2K_STATE_TPH, opj_j2k_read_ppt},
{J2K_MS_SOP, 0, 0},
{J2K_MS_CRG, J2K_STATE_MH, opj_j2k_read_crg},
{J2K_MS_COM, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_com},
{J2K_MS_MCT, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_mct},
{J2K_MS_CBD, J2K_STATE_MH, opj_j2k_read_cbd},
{J2K_MS_MCC, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_mcc},
{J2K_MS_MCO, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_mco},
#ifdef USE_JPWL
#ifdef TODO_MS /* remove these functions which are not commpatible with the v2 API */
{J2K_MS_EPC, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_epc},
{J2K_MS_EPB, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_epb},
{J2K_MS_ESD, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_esd},
{J2K_MS_RED, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_red},
#endif
#endif /* USE_JPWL */
#ifdef USE_JPSEC
{J2K_MS_SEC, J2K_DEC_STATE_MH, j2k_read_sec},
{J2K_MS_INSEC, 0, j2k_read_insec}
#endif /* USE_JPSEC */
{J2K_MS_UNK, J2K_STATE_MH | J2K_STATE_TPH, 0}/*opj_j2k_read_unk is directly used*/
};
static void opj_j2k_read_int16_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_FLOAT32 * l_dest_data = (OPJ_FLOAT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_UINT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
opj_read_bytes(l_src_data, &l_temp, 2);
l_src_data += sizeof(OPJ_INT16);
*(l_dest_data++) = (OPJ_FLOAT32) l_temp;
}
}
static void opj_j2k_read_int32_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_FLOAT32 * l_dest_data = (OPJ_FLOAT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_UINT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
opj_read_bytes(l_src_data, &l_temp, 4);
l_src_data += sizeof(OPJ_INT32);
*(l_dest_data++) = (OPJ_FLOAT32) l_temp;
}
}
static void opj_j2k_read_float32_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_FLOAT32 * l_dest_data = (OPJ_FLOAT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_FLOAT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
opj_read_float(l_src_data, &l_temp);
l_src_data += sizeof(OPJ_FLOAT32);
*(l_dest_data++) = l_temp;
}
}
static void opj_j2k_read_float64_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_FLOAT32 * l_dest_data = (OPJ_FLOAT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_FLOAT64 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
opj_read_double(l_src_data, &l_temp);
l_src_data += sizeof(OPJ_FLOAT64);
*(l_dest_data++) = (OPJ_FLOAT32) l_temp;
}
}
static void opj_j2k_read_int16_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_INT32 * l_dest_data = (OPJ_INT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_UINT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
opj_read_bytes(l_src_data, &l_temp, 2);
l_src_data += sizeof(OPJ_INT16);
*(l_dest_data++) = (OPJ_INT32) l_temp;
}
}
static void opj_j2k_read_int32_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_INT32 * l_dest_data = (OPJ_INT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_UINT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
opj_read_bytes(l_src_data, &l_temp, 4);
l_src_data += sizeof(OPJ_INT32);
*(l_dest_data++) = (OPJ_INT32) l_temp;
}
}
static void opj_j2k_read_float32_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_INT32 * l_dest_data = (OPJ_INT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_FLOAT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
opj_read_float(l_src_data, &l_temp);
l_src_data += sizeof(OPJ_FLOAT32);
*(l_dest_data++) = (OPJ_INT32) l_temp;
}
}
static void opj_j2k_read_float64_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_INT32 * l_dest_data = (OPJ_INT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_FLOAT64 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
opj_read_double(l_src_data, &l_temp);
l_src_data += sizeof(OPJ_FLOAT64);
*(l_dest_data++) = (OPJ_INT32) l_temp;
}
}
static void opj_j2k_write_float_to_int16(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_dest_data = (OPJ_BYTE *) p_dest_data;
OPJ_FLOAT32 * l_src_data = (OPJ_FLOAT32 *) p_src_data;
OPJ_UINT32 i;
OPJ_UINT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
l_temp = (OPJ_UINT32) * (l_src_data++);
opj_write_bytes(l_dest_data, l_temp, sizeof(OPJ_INT16));
l_dest_data += sizeof(OPJ_INT16);
}
}
static void opj_j2k_write_float_to_int32(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_dest_data = (OPJ_BYTE *) p_dest_data;
OPJ_FLOAT32 * l_src_data = (OPJ_FLOAT32 *) p_src_data;
OPJ_UINT32 i;
OPJ_UINT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
l_temp = (OPJ_UINT32) * (l_src_data++);
opj_write_bytes(l_dest_data, l_temp, sizeof(OPJ_INT32));
l_dest_data += sizeof(OPJ_INT32);
}
}
static void opj_j2k_write_float_to_float(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_dest_data = (OPJ_BYTE *) p_dest_data;
OPJ_FLOAT32 * l_src_data = (OPJ_FLOAT32 *) p_src_data;
OPJ_UINT32 i;
OPJ_FLOAT32 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
l_temp = (OPJ_FLOAT32) * (l_src_data++);
opj_write_float(l_dest_data, l_temp);
l_dest_data += sizeof(OPJ_FLOAT32);
}
}
static void opj_j2k_write_float_to_float64(const void * p_src_data,
void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_dest_data = (OPJ_BYTE *) p_dest_data;
OPJ_FLOAT32 * l_src_data = (OPJ_FLOAT32 *) p_src_data;
OPJ_UINT32 i;
OPJ_FLOAT64 l_temp;
for (i = 0; i < p_nb_elem; ++i) {
l_temp = (OPJ_FLOAT64) * (l_src_data++);
opj_write_double(l_dest_data, l_temp);
l_dest_data += sizeof(OPJ_FLOAT64);
}
}
const char *opj_j2k_convert_progression_order(OPJ_PROG_ORDER prg_order)
{
const j2k_prog_order_t *po;
for (po = j2k_prog_order_list; po->enum_prog != -1; po++) {
if (po->enum_prog == prg_order) {
return po->str_prog;
}
}
return po->str_prog;
}
static OPJ_BOOL opj_j2k_check_poc_val(const opj_poc_t *p_pocs,
OPJ_UINT32 p_nb_pocs,
OPJ_UINT32 p_nb_resolutions,
OPJ_UINT32 p_num_comps,
OPJ_UINT32 p_num_layers,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32* packet_array;
OPJ_UINT32 index, resno, compno, layno;
OPJ_UINT32 i;
OPJ_UINT32 step_c = 1;
OPJ_UINT32 step_r = p_num_comps * step_c;
OPJ_UINT32 step_l = p_nb_resolutions * step_r;
OPJ_BOOL loss = OPJ_FALSE;
OPJ_UINT32 layno0 = 0;
packet_array = (OPJ_UINT32*) opj_calloc(step_l * p_num_layers,
sizeof(OPJ_UINT32));
if (packet_array == 00) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory for checking the poc values.\n");
return OPJ_FALSE;
}
if (p_nb_pocs == 0) {
opj_free(packet_array);
return OPJ_TRUE;
}
index = step_r * p_pocs->resno0;
/* take each resolution for each poc */
for (resno = p_pocs->resno0 ; resno < p_pocs->resno1 ; ++resno) {
OPJ_UINT32 res_index = index + p_pocs->compno0 * step_c;
/* take each comp of each resolution for each poc */
for (compno = p_pocs->compno0 ; compno < p_pocs->compno1 ; ++compno) {
OPJ_UINT32 comp_index = res_index + layno0 * step_l;
/* and finally take each layer of each res of ... */
for (layno = layno0; layno < p_pocs->layno1 ; ++layno) {
/*index = step_r * resno + step_c * compno + step_l * layno;*/
packet_array[comp_index] = 1;
comp_index += step_l;
}
res_index += step_c;
}
index += step_r;
}
++p_pocs;
/* iterate through all the pocs */
for (i = 1; i < p_nb_pocs ; ++i) {
OPJ_UINT32 l_last_layno1 = (p_pocs - 1)->layno1 ;
layno0 = (p_pocs->layno1 > l_last_layno1) ? l_last_layno1 : 0;
index = step_r * p_pocs->resno0;
/* take each resolution for each poc */
for (resno = p_pocs->resno0 ; resno < p_pocs->resno1 ; ++resno) {
OPJ_UINT32 res_index = index + p_pocs->compno0 * step_c;
/* take each comp of each resolution for each poc */
for (compno = p_pocs->compno0 ; compno < p_pocs->compno1 ; ++compno) {
OPJ_UINT32 comp_index = res_index + layno0 * step_l;
/* and finally take each layer of each res of ... */
for (layno = layno0; layno < p_pocs->layno1 ; ++layno) {
/*index = step_r * resno + step_c * compno + step_l * layno;*/
packet_array[comp_index] = 1;
comp_index += step_l;
}
res_index += step_c;
}
index += step_r;
}
++p_pocs;
}
index = 0;
for (layno = 0; layno < p_num_layers ; ++layno) {
for (resno = 0; resno < p_nb_resolutions; ++resno) {
for (compno = 0; compno < p_num_comps; ++compno) {
loss |= (packet_array[index] != 1);
/*index = step_r * resno + step_c * compno + step_l * layno;*/
index += step_c;
}
}
}
if (loss) {
opj_event_msg(p_manager, EVT_ERROR, "Missing packets possible loss of data\n");
}
opj_free(packet_array);
return !loss;
}
/* ----------------------------------------------------------------------- */
static OPJ_UINT32 opj_j2k_get_num_tp(opj_cp_t *cp, OPJ_UINT32 pino,
OPJ_UINT32 tileno)
{
const OPJ_CHAR *prog = 00;
OPJ_INT32 i;
OPJ_UINT32 tpnum = 1;
opj_tcp_t *tcp = 00;
opj_poc_t * l_current_poc = 00;
/* preconditions */
assert(tileno < (cp->tw * cp->th));
assert(pino < (cp->tcps[tileno].numpocs + 1));
/* get the given tile coding parameter */
tcp = &cp->tcps[tileno];
assert(tcp != 00);
l_current_poc = &(tcp->pocs[pino]);
assert(l_current_poc != 0);
/* get the progression order as a character string */
prog = opj_j2k_convert_progression_order(tcp->prg);
assert(strlen(prog) > 0);
if (cp->m_specific_param.m_enc.m_tp_on == 1) {
for (i = 0; i < 4; ++i) {
switch (prog[i]) {
/* component wise */
case 'C':
tpnum *= l_current_poc->compE;
break;
/* resolution wise */
case 'R':
tpnum *= l_current_poc->resE;
break;
/* precinct wise */
case 'P':
tpnum *= l_current_poc->prcE;
break;
/* layer wise */
case 'L':
tpnum *= l_current_poc->layE;
break;
}
/* whould we split here ? */
if (cp->m_specific_param.m_enc.m_tp_flag == prog[i]) {
cp->m_specific_param.m_enc.m_tp_pos = i;
break;
}
}
} else {
tpnum = 1;
}
return tpnum;
}
static OPJ_BOOL opj_j2k_calculate_tp(opj_j2k_t *p_j2k,
opj_cp_t *cp,
OPJ_UINT32 * p_nb_tiles,
opj_image_t *image,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 pino, tileno;
OPJ_UINT32 l_nb_tiles;
opj_tcp_t *tcp;
/* preconditions */
assert(p_nb_tiles != 00);
assert(cp != 00);
assert(image != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_j2k);
OPJ_UNUSED(p_manager);
l_nb_tiles = cp->tw * cp->th;
* p_nb_tiles = 0;
tcp = cp->tcps;
/* INDEX >> */
/* TODO mergeV2: check this part which use cstr_info */
/*if (p_j2k->cstr_info) {
opj_tile_info_t * l_info_tile_ptr = p_j2k->cstr_info->tile;
for (tileno = 0; tileno < l_nb_tiles; ++tileno) {
OPJ_UINT32 cur_totnum_tp = 0;
opj_pi_update_encoding_parameters(image,cp,tileno);
for (pino = 0; pino <= tcp->numpocs; ++pino)
{
OPJ_UINT32 tp_num = opj_j2k_get_num_tp(cp,pino,tileno);
*p_nb_tiles = *p_nb_tiles + tp_num;
cur_totnum_tp += tp_num;
}
tcp->m_nb_tile_parts = cur_totnum_tp;
l_info_tile_ptr->tp = (opj_tp_info_t *) opj_malloc(cur_totnum_tp * sizeof(opj_tp_info_t));
if (l_info_tile_ptr->tp == 00) {
return OPJ_FALSE;
}
memset(l_info_tile_ptr->tp,0,cur_totnum_tp * sizeof(opj_tp_info_t));
l_info_tile_ptr->num_tps = cur_totnum_tp;
++l_info_tile_ptr;
++tcp;
}
}
else */{
for (tileno = 0; tileno < l_nb_tiles; ++tileno) {
OPJ_UINT32 cur_totnum_tp = 0;
opj_pi_update_encoding_parameters(image, cp, tileno);
for (pino = 0; pino <= tcp->numpocs; ++pino) {
OPJ_UINT32 tp_num = opj_j2k_get_num_tp(cp, pino, tileno);
*p_nb_tiles = *p_nb_tiles + tp_num;
cur_totnum_tp += tp_num;
}
tcp->m_nb_tile_parts = cur_totnum_tp;
++tcp;
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_soc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
/* 2 bytes will be written */
OPJ_BYTE * l_start_stream = 00;
/* preconditions */
assert(p_stream != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_start_stream = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
/* write SOC identifier */
opj_write_bytes(l_start_stream, J2K_MS_SOC, 2);
if (opj_stream_write_data(p_stream, l_start_stream, 2, p_manager) != 2) {
return OPJ_FALSE;
}
/* UniPG>> */
#ifdef USE_JPWL
/* update markers struct */
/*
OPJ_BOOL res = j2k_add_marker(p_j2k->cstr_info, J2K_MS_SOC, p_stream_tell(p_stream) - 2, 2);
*/
assert(0 && "TODO");
#endif /* USE_JPWL */
/* <<UniPG */
return OPJ_TRUE;
}
/**
* Reads a SOC marker (Start of Codestream)
* @param p_j2k the jpeg2000 file codec.
* @param p_stream FIXME DOC
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_soc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_BYTE l_data [2];
OPJ_UINT32 l_marker;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
if (opj_stream_read_data(p_stream, l_data, 2, p_manager) != 2) {
return OPJ_FALSE;
}
opj_read_bytes(l_data, &l_marker, 2);
if (l_marker != J2K_MS_SOC) {
return OPJ_FALSE;
}
/* Next marker should be a SIZ marker in the main header */
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_MHSIZ;
/* FIXME move it in a index structure included in p_j2k*/
p_j2k->cstr_index->main_head_start = opj_stream_tell(p_stream) - 2;
opj_event_msg(p_manager, EVT_INFO, "Start to read j2k main header (%d).\n",
p_j2k->cstr_index->main_head_start);
/* Add the marker to the codestream index*/
if (OPJ_FALSE == opj_j2k_add_mhmarker(p_j2k->cstr_index, J2K_MS_SOC,
p_j2k->cstr_index->main_head_start, 2)) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add mh marker\n");
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_siz(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 i;
OPJ_UINT32 l_size_len;
OPJ_BYTE * l_current_ptr;
opj_image_t * l_image = 00;
opj_cp_t *cp = 00;
opj_image_comp_t * l_img_comp = 00;
/* preconditions */
assert(p_stream != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_image = p_j2k->m_private_image;
cp = &(p_j2k->m_cp);
l_size_len = 40 + 3 * l_image->numcomps;
l_img_comp = l_image->comps;
if (l_size_len > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_size_len);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory for the SIZ marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_size_len;
}
l_current_ptr = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
/* write SOC identifier */
opj_write_bytes(l_current_ptr, J2K_MS_SIZ, 2); /* SIZ */
l_current_ptr += 2;
opj_write_bytes(l_current_ptr, l_size_len - 2, 2); /* L_SIZ */
l_current_ptr += 2;
opj_write_bytes(l_current_ptr, cp->rsiz, 2); /* Rsiz (capabilities) */
l_current_ptr += 2;
opj_write_bytes(l_current_ptr, l_image->x1, 4); /* Xsiz */
l_current_ptr += 4;
opj_write_bytes(l_current_ptr, l_image->y1, 4); /* Ysiz */
l_current_ptr += 4;
opj_write_bytes(l_current_ptr, l_image->x0, 4); /* X0siz */
l_current_ptr += 4;
opj_write_bytes(l_current_ptr, l_image->y0, 4); /* Y0siz */
l_current_ptr += 4;
opj_write_bytes(l_current_ptr, cp->tdx, 4); /* XTsiz */
l_current_ptr += 4;
opj_write_bytes(l_current_ptr, cp->tdy, 4); /* YTsiz */
l_current_ptr += 4;
opj_write_bytes(l_current_ptr, cp->tx0, 4); /* XT0siz */
l_current_ptr += 4;
opj_write_bytes(l_current_ptr, cp->ty0, 4); /* YT0siz */
l_current_ptr += 4;
opj_write_bytes(l_current_ptr, l_image->numcomps, 2); /* Csiz */
l_current_ptr += 2;
for (i = 0; i < l_image->numcomps; ++i) {
/* TODO here with MCT ? */
opj_write_bytes(l_current_ptr, l_img_comp->prec - 1 + (l_img_comp->sgnd << 7),
1); /* Ssiz_i */
++l_current_ptr;
opj_write_bytes(l_current_ptr, l_img_comp->dx, 1); /* XRsiz_i */
++l_current_ptr;
opj_write_bytes(l_current_ptr, l_img_comp->dy, 1); /* YRsiz_i */
++l_current_ptr;
++l_img_comp;
}
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_size_len,
p_manager) != l_size_len) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a SIZ marker (image and tile size)
* @param p_j2k the jpeg2000 file codec.
* @param p_header_data the data contained in the SIZ box.
* @param p_header_size the size of the data contained in the SIZ marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_siz(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 i;
OPJ_UINT32 l_nb_comp;
OPJ_UINT32 l_nb_comp_remain;
OPJ_UINT32 l_remaining_size;
OPJ_UINT32 l_nb_tiles;
OPJ_UINT32 l_tmp, l_tx1, l_ty1;
OPJ_UINT32 l_prec0, l_sgnd0;
opj_image_t *l_image = 00;
opj_cp_t *l_cp = 00;
opj_image_comp_t * l_img_comp = 00;
opj_tcp_t * l_current_tile_param = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_header_data != 00);
l_image = p_j2k->m_private_image;
l_cp = &(p_j2k->m_cp);
/* minimum size == 39 - 3 (= minimum component parameter) */
if (p_header_size < 36) {
opj_event_msg(p_manager, EVT_ERROR, "Error with SIZ marker size\n");
return OPJ_FALSE;
}
l_remaining_size = p_header_size - 36;
l_nb_comp = l_remaining_size / 3;
l_nb_comp_remain = l_remaining_size % 3;
if (l_nb_comp_remain != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error with SIZ marker size\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_tmp,
2); /* Rsiz (capabilities) */
p_header_data += 2;
l_cp->rsiz = (OPJ_UINT16) l_tmp;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_image->x1, 4); /* Xsiz */
p_header_data += 4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_image->y1, 4); /* Ysiz */
p_header_data += 4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_image->x0, 4); /* X0siz */
p_header_data += 4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_image->y0, 4); /* Y0siz */
p_header_data += 4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_cp->tdx,
4); /* XTsiz */
p_header_data += 4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_cp->tdy,
4); /* YTsiz */
p_header_data += 4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_cp->tx0,
4); /* XT0siz */
p_header_data += 4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_cp->ty0,
4); /* YT0siz */
p_header_data += 4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_tmp,
2); /* Csiz */
p_header_data += 2;
if (l_tmp < 16385) {
l_image->numcomps = (OPJ_UINT16) l_tmp;
} else {
opj_event_msg(p_manager, EVT_ERROR,
"Error with SIZ marker: number of component is illegal -> %d\n", l_tmp);
return OPJ_FALSE;
}
if (l_image->numcomps != l_nb_comp) {
opj_event_msg(p_manager, EVT_ERROR,
"Error with SIZ marker: number of component is not compatible with the remaining number of parameters ( %d vs %d)\n",
l_image->numcomps, l_nb_comp);
return OPJ_FALSE;
}
/* testcase 4035.pdf.SIGSEGV.d8b.3375 */
/* testcase issue427-null-image-size.jp2 */
if ((l_image->x0 >= l_image->x1) || (l_image->y0 >= l_image->y1)) {
opj_event_msg(p_manager, EVT_ERROR,
"Error with SIZ marker: negative or zero image size (%" PRId64 " x %" PRId64
")\n", (OPJ_INT64)l_image->x1 - l_image->x0,
(OPJ_INT64)l_image->y1 - l_image->y0);
return OPJ_FALSE;
}
/* testcase 2539.pdf.SIGFPE.706.1712 (also 3622.pdf.SIGFPE.706.2916 and 4008.pdf.SIGFPE.706.3345 and maybe more) */
if ((l_cp->tdx == 0U) || (l_cp->tdy == 0U)) {
opj_event_msg(p_manager, EVT_ERROR,
"Error with SIZ marker: invalid tile size (tdx: %d, tdy: %d)\n", l_cp->tdx,
l_cp->tdy);
return OPJ_FALSE;
}
/* testcase 1610.pdf.SIGSEGV.59c.681 */
if ((0xFFFFFFFFU / l_image->x1) < l_image->y1) {
opj_event_msg(p_manager, EVT_ERROR,
"Prevent buffer overflow (x1: %d, y1: %d)\n", l_image->x1, l_image->y1);
return OPJ_FALSE;
}
/* testcase issue427-illegal-tile-offset.jp2 */
l_tx1 = opj_uint_adds(l_cp->tx0, l_cp->tdx); /* manage overflow */
l_ty1 = opj_uint_adds(l_cp->ty0, l_cp->tdy); /* manage overflow */
if ((l_cp->tx0 > l_image->x0) || (l_cp->ty0 > l_image->y0) ||
(l_tx1 <= l_image->x0) || (l_ty1 <= l_image->y0)) {
opj_event_msg(p_manager, EVT_ERROR,
"Error with SIZ marker: illegal tile offset\n");
return OPJ_FALSE;
}
if (!p_j2k->dump_state) {
OPJ_UINT32 siz_w, siz_h;
siz_w = l_image->x1 - l_image->x0;
siz_h = l_image->y1 - l_image->y0;
if (p_j2k->ihdr_w > 0 && p_j2k->ihdr_h > 0
&& (p_j2k->ihdr_w != siz_w || p_j2k->ihdr_h != siz_h)) {
opj_event_msg(p_manager, EVT_ERROR,
"Error with SIZ marker: IHDR w(%u) h(%u) vs. SIZ w(%u) h(%u)\n", p_j2k->ihdr_w,
p_j2k->ihdr_h, siz_w, siz_h);
return OPJ_FALSE;
}
}
#ifdef USE_JPWL
if (l_cp->correct) {
/* if JPWL is on, we check whether TX errors have damaged
too much the SIZ parameters */
if (!(l_image->x1 * l_image->y1)) {
opj_event_msg(p_manager, EVT_ERROR,
"JPWL: bad image size (%d x %d)\n",
l_image->x1, l_image->y1);
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
}
/* FIXME check previously in the function so why keep this piece of code ? Need by the norm ?
if (l_image->numcomps != ((len - 38) / 3)) {
opj_event_msg(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
"JPWL: Csiz is %d => space in SIZ only for %d comps.!!!\n",
l_image->numcomps, ((len - 38) / 3));
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
*/ /* we try to correct */
/* opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust this\n");
if (l_image->numcomps < ((len - 38) / 3)) {
len = 38 + 3 * l_image->numcomps;
opj_event_msg(p_manager, EVT_WARNING, "- setting Lsiz to %d => HYPOTHESIS!!!\n",
len);
} else {
l_image->numcomps = ((len - 38) / 3);
opj_event_msg(p_manager, EVT_WARNING, "- setting Csiz to %d => HYPOTHESIS!!!\n",
l_image->numcomps);
}
}
*/
/* update components number in the jpwl_exp_comps filed */
l_cp->exp_comps = l_image->numcomps;
}
#endif /* USE_JPWL */
/* Allocate the resulting image components */
l_image->comps = (opj_image_comp_t*) opj_calloc(l_image->numcomps,
sizeof(opj_image_comp_t));
if (l_image->comps == 00) {
l_image->numcomps = 0;
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to take in charge SIZ marker\n");
return OPJ_FALSE;
}
l_img_comp = l_image->comps;
l_prec0 = 0;
l_sgnd0 = 0;
/* Read the component information */
for (i = 0; i < l_image->numcomps; ++i) {
OPJ_UINT32 tmp;
opj_read_bytes(p_header_data, &tmp, 1); /* Ssiz_i */
++p_header_data;
l_img_comp->prec = (tmp & 0x7f) + 1;
l_img_comp->sgnd = tmp >> 7;
if (p_j2k->dump_state == 0) {
if (i == 0) {
l_prec0 = l_img_comp->prec;
l_sgnd0 = l_img_comp->sgnd;
} else if (!l_cp->allow_different_bit_depth_sign
&& (l_img_comp->prec != l_prec0 || l_img_comp->sgnd != l_sgnd0)) {
opj_event_msg(p_manager, EVT_WARNING,
"Despite JP2 BPC!=255, precision and/or sgnd values for comp[%d] is different than comp[0]:\n"
" [0] prec(%d) sgnd(%d) [%d] prec(%d) sgnd(%d)\n", i, l_prec0, l_sgnd0,
i, l_img_comp->prec, l_img_comp->sgnd);
}
/* TODO: we should perhaps also check against JP2 BPCC values */
}
opj_read_bytes(p_header_data, &tmp, 1); /* XRsiz_i */
++p_header_data;
l_img_comp->dx = (OPJ_UINT32)tmp; /* should be between 1 and 255 */
opj_read_bytes(p_header_data, &tmp, 1); /* YRsiz_i */
++p_header_data;
l_img_comp->dy = (OPJ_UINT32)tmp; /* should be between 1 and 255 */
if (l_img_comp->dx < 1 || l_img_comp->dx > 255 ||
l_img_comp->dy < 1 || l_img_comp->dy > 255) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid values for comp = %d : dx=%u dy=%u (should be between 1 and 255 according to the JPEG2000 norm)\n",
i, l_img_comp->dx, l_img_comp->dy);
return OPJ_FALSE;
}
/* Avoids later undefined shift in computation of */
/* p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps[i].m_dc_level_shift = 1
<< (l_image->comps[i].prec - 1); */
if (l_img_comp->prec > 31) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid values for comp = %d : prec=%u (should be between 1 and 38 according to the JPEG2000 norm. OpenJpeg only supports up to 31)\n",
i, l_img_comp->prec);
return OPJ_FALSE;
}
#ifdef USE_JPWL
if (l_cp->correct) {
/* if JPWL is on, we check whether TX errors have damaged
too much the SIZ parameters, again */
if (!(l_image->comps[i].dx * l_image->comps[i].dy)) {
opj_event_msg(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
"JPWL: bad XRsiz_%d/YRsiz_%d (%d x %d)\n",
i, i, l_image->comps[i].dx, l_image->comps[i].dy);
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
/* we try to correct */
opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust them\n");
if (!l_image->comps[i].dx) {
l_image->comps[i].dx = 1;
opj_event_msg(p_manager, EVT_WARNING,
"- setting XRsiz_%d to %d => HYPOTHESIS!!!\n",
i, l_image->comps[i].dx);
}
if (!l_image->comps[i].dy) {
l_image->comps[i].dy = 1;
opj_event_msg(p_manager, EVT_WARNING,
"- setting YRsiz_%d to %d => HYPOTHESIS!!!\n",
i, l_image->comps[i].dy);
}
}
}
#endif /* USE_JPWL */
l_img_comp->resno_decoded =
0; /* number of resolution decoded */
l_img_comp->factor =
l_cp->m_specific_param.m_dec.m_reduce; /* reducing factor per component */
++l_img_comp;
}
if (l_cp->tdx == 0 || l_cp->tdy == 0) {
return OPJ_FALSE;
}
/* Compute the number of tiles */
l_cp->tw = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)(l_image->x1 - l_cp->tx0),
(OPJ_INT32)l_cp->tdx);
l_cp->th = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)(l_image->y1 - l_cp->ty0),
(OPJ_INT32)l_cp->tdy);
/* Check that the number of tiles is valid */
if (l_cp->tw == 0 || l_cp->th == 0 || l_cp->tw > 65535 / l_cp->th) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid number of tiles : %u x %u (maximum fixed by jpeg2000 norm is 65535 tiles)\n",
l_cp->tw, l_cp->th);
return OPJ_FALSE;
}
l_nb_tiles = l_cp->tw * l_cp->th;
/* Define the tiles which will be decoded */
if (p_j2k->m_specific_param.m_decoder.m_discard_tiles) {
p_j2k->m_specific_param.m_decoder.m_start_tile_x =
(p_j2k->m_specific_param.m_decoder.m_start_tile_x - l_cp->tx0) / l_cp->tdx;
p_j2k->m_specific_param.m_decoder.m_start_tile_y =
(p_j2k->m_specific_param.m_decoder.m_start_tile_y - l_cp->ty0) / l_cp->tdy;
p_j2k->m_specific_param.m_decoder.m_end_tile_x = (OPJ_UINT32)opj_int_ceildiv((
OPJ_INT32)(p_j2k->m_specific_param.m_decoder.m_end_tile_x - l_cp->tx0),
(OPJ_INT32)l_cp->tdx);
p_j2k->m_specific_param.m_decoder.m_end_tile_y = (OPJ_UINT32)opj_int_ceildiv((
OPJ_INT32)(p_j2k->m_specific_param.m_decoder.m_end_tile_y - l_cp->ty0),
(OPJ_INT32)l_cp->tdy);
} else {
p_j2k->m_specific_param.m_decoder.m_start_tile_x = 0;
p_j2k->m_specific_param.m_decoder.m_start_tile_y = 0;
p_j2k->m_specific_param.m_decoder.m_end_tile_x = l_cp->tw;
p_j2k->m_specific_param.m_decoder.m_end_tile_y = l_cp->th;
}
#ifdef USE_JPWL
if (l_cp->correct) {
/* if JPWL is on, we check whether TX errors have damaged
too much the SIZ parameters */
if ((l_cp->tw < 1) || (l_cp->th < 1) || (l_cp->tw > l_cp->max_tiles) ||
(l_cp->th > l_cp->max_tiles)) {
opj_event_msg(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
"JPWL: bad number of tiles (%d x %d)\n",
l_cp->tw, l_cp->th);
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
/* we try to correct */
opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust them\n");
if (l_cp->tw < 1) {
l_cp->tw = 1;
opj_event_msg(p_manager, EVT_WARNING,
"- setting %d tiles in x => HYPOTHESIS!!!\n",
l_cp->tw);
}
if (l_cp->tw > l_cp->max_tiles) {
l_cp->tw = 1;
opj_event_msg(p_manager, EVT_WARNING,
"- too large x, increase expectance of %d\n"
"- setting %d tiles in x => HYPOTHESIS!!!\n",
l_cp->max_tiles, l_cp->tw);
}
if (l_cp->th < 1) {
l_cp->th = 1;
opj_event_msg(p_manager, EVT_WARNING,
"- setting %d tiles in y => HYPOTHESIS!!!\n",
l_cp->th);
}
if (l_cp->th > l_cp->max_tiles) {
l_cp->th = 1;
opj_event_msg(p_manager, EVT_WARNING,
"- too large y, increase expectance of %d to continue\n",
"- setting %d tiles in y => HYPOTHESIS!!!\n",
l_cp->max_tiles, l_cp->th);
}
}
}
#endif /* USE_JPWL */
/* memory allocations */
l_cp->tcps = (opj_tcp_t*) opj_calloc(l_nb_tiles, sizeof(opj_tcp_t));
if (l_cp->tcps == 00) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to take in charge SIZ marker\n");
return OPJ_FALSE;
}
#ifdef USE_JPWL
if (l_cp->correct) {
if (!l_cp->tcps) {
opj_event_msg(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
"JPWL: could not alloc tcps field of cp\n");
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
}
}
#endif /* USE_JPWL */
p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps =
(opj_tccp_t*) opj_calloc(l_image->numcomps, sizeof(opj_tccp_t));
if (p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps == 00) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to take in charge SIZ marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mct_records =
(opj_mct_data_t*)opj_calloc(OPJ_J2K_MCT_DEFAULT_NB_RECORDS,
sizeof(opj_mct_data_t));
if (! p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mct_records) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to take in charge SIZ marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_decoder.m_default_tcp->m_nb_max_mct_records =
OPJ_J2K_MCT_DEFAULT_NB_RECORDS;
p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mcc_records =
(opj_simple_mcc_decorrelation_data_t*)
opj_calloc(OPJ_J2K_MCC_DEFAULT_NB_RECORDS,
sizeof(opj_simple_mcc_decorrelation_data_t));
if (! p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mcc_records) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to take in charge SIZ marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_decoder.m_default_tcp->m_nb_max_mcc_records =
OPJ_J2K_MCC_DEFAULT_NB_RECORDS;
/* set up default dc level shift */
for (i = 0; i < l_image->numcomps; ++i) {
if (! l_image->comps[i].sgnd) {
p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps[i].m_dc_level_shift = 1
<< (l_image->comps[i].prec - 1);
}
}
l_current_tile_param = l_cp->tcps;
for (i = 0; i < l_nb_tiles; ++i) {
l_current_tile_param->tccps = (opj_tccp_t*) opj_calloc(l_image->numcomps,
sizeof(opj_tccp_t));
if (l_current_tile_param->tccps == 00) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to take in charge SIZ marker\n");
return OPJ_FALSE;
}
++l_current_tile_param;
}
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_MH;
opj_image_comp_header_update(l_image, l_cp);
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_com(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_comment_size;
OPJ_UINT32 l_total_com_size;
const OPJ_CHAR *l_comment;
OPJ_BYTE * l_current_ptr = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
l_comment = p_j2k->m_cp.comment;
l_comment_size = (OPJ_UINT32)strlen(l_comment);
l_total_com_size = l_comment_size + 6;
if (l_total_com_size >
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_total_com_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to write the COM marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_total_com_size;
}
l_current_ptr = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_ptr, J2K_MS_COM, 2); /* COM */
l_current_ptr += 2;
opj_write_bytes(l_current_ptr, l_total_com_size - 2, 2); /* L_COM */
l_current_ptr += 2;
opj_write_bytes(l_current_ptr, 1,
2); /* General use (IS 8859-15:1999 (Latin) values) */
l_current_ptr += 2;
memcpy(l_current_ptr, l_comment, l_comment_size);
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_total_com_size,
p_manager) != l_total_com_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a COM marker (comments)
* @param p_j2k the jpeg2000 file codec.
* @param p_header_data the data contained in the COM box.
* @param p_header_size the size of the data contained in the COM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_com(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_header_data != 00);
OPJ_UNUSED(p_j2k);
OPJ_UNUSED(p_header_data);
OPJ_UNUSED(p_header_size);
OPJ_UNUSED(p_manager);
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_cod(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
OPJ_UINT32 l_code_size, l_remaining_size;
OPJ_BYTE * l_current_data = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_j2k->m_current_tile_number];
l_code_size = 9 + opj_j2k_get_SPCod_SPCoc_size(p_j2k,
p_j2k->m_current_tile_number, 0);
l_remaining_size = l_code_size;
if (l_code_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_code_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write COD marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_code_size;
}
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_data, J2K_MS_COD, 2); /* COD */
l_current_data += 2;
opj_write_bytes(l_current_data, l_code_size - 2, 2); /* L_COD */
l_current_data += 2;
opj_write_bytes(l_current_data, l_tcp->csty, 1); /* Scod */
++l_current_data;
opj_write_bytes(l_current_data, (OPJ_UINT32)l_tcp->prg, 1); /* SGcod (A) */
++l_current_data;
opj_write_bytes(l_current_data, l_tcp->numlayers, 2); /* SGcod (B) */
l_current_data += 2;
opj_write_bytes(l_current_data, l_tcp->mct, 1); /* SGcod (C) */
++l_current_data;
l_remaining_size -= 9;
if (! opj_j2k_write_SPCod_SPCoc(p_j2k, p_j2k->m_current_tile_number, 0,
l_current_data, &l_remaining_size, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing COD marker\n");
return OPJ_FALSE;
}
if (l_remaining_size != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing COD marker\n");
return OPJ_FALSE;
}
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_code_size,
p_manager) != l_code_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a COD marker (Coding Styke defaults)
* @param p_header_data the data contained in the COD box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the COD marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_cod(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
/* loop */
OPJ_UINT32 i;
OPJ_UINT32 l_tmp;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_image_t *l_image = 00;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_image = p_j2k->m_private_image;
l_cp = &(p_j2k->m_cp);
/* If we are in the first tile-part header of the current tile */
l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
/* Only one COD per tile */
if (l_tcp->cod) {
opj_event_msg(p_manager, EVT_ERROR,
"COD marker already read. No more than one COD marker per tile.\n");
return OPJ_FALSE;
}
l_tcp->cod = 1;
/* Make sure room is sufficient */
if (p_header_size < 5) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading COD marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_tcp->csty, 1); /* Scod */
++p_header_data;
/* Make sure we know how to decode this */
if ((l_tcp->csty & ~(OPJ_UINT32)(J2K_CP_CSTY_PRT | J2K_CP_CSTY_SOP |
J2K_CP_CSTY_EPH)) != 0U) {
opj_event_msg(p_manager, EVT_ERROR, "Unknown Scod value in COD marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_tmp, 1); /* SGcod (A) */
++p_header_data;
l_tcp->prg = (OPJ_PROG_ORDER) l_tmp;
/* Make sure progression order is valid */
if (l_tcp->prg > OPJ_CPRL) {
opj_event_msg(p_manager, EVT_ERROR,
"Unknown progression order in COD marker\n");
l_tcp->prg = OPJ_PROG_UNKNOWN;
}
opj_read_bytes(p_header_data, &l_tcp->numlayers, 2); /* SGcod (B) */
p_header_data += 2;
if ((l_tcp->numlayers < 1U) || (l_tcp->numlayers > 65535U)) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid number of layers in COD marker : %d not in range [1-65535]\n",
l_tcp->numlayers);
return OPJ_FALSE;
}
/* If user didn't set a number layer to decode take the max specify in the codestream. */
if (l_cp->m_specific_param.m_dec.m_layer) {
l_tcp->num_layers_to_decode = l_cp->m_specific_param.m_dec.m_layer;
} else {
l_tcp->num_layers_to_decode = l_tcp->numlayers;
}
opj_read_bytes(p_header_data, &l_tcp->mct, 1); /* SGcod (C) */
++p_header_data;
p_header_size -= 5;
for (i = 0; i < l_image->numcomps; ++i) {
l_tcp->tccps[i].csty = l_tcp->csty & J2K_CCP_CSTY_PRT;
}
if (! opj_j2k_read_SPCod_SPCoc(p_j2k, 0, p_header_data, &p_header_size,
p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading COD marker\n");
return OPJ_FALSE;
}
if (p_header_size != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading COD marker\n");
return OPJ_FALSE;
}
/* Apply the coding style to other components of the current tile or the m_default_tcp*/
opj_j2k_copy_tile_component_parameters(p_j2k);
/* Index */
#ifdef WIP_REMOVE_MSD
if (p_j2k->cstr_info) {
/*opj_codestream_info_t *l_cstr_info = p_j2k->cstr_info;*/
p_j2k->cstr_info->prog = l_tcp->prg;
p_j2k->cstr_info->numlayers = l_tcp->numlayers;
p_j2k->cstr_info->numdecompos = (OPJ_INT32*) opj_malloc(
l_image->numcomps * sizeof(OPJ_UINT32));
if (!p_j2k->cstr_info->numdecompos) {
return OPJ_FALSE;
}
for (i = 0; i < l_image->numcomps; ++i) {
p_j2k->cstr_info->numdecompos[i] = l_tcp->tccps[i].numresolutions - 1;
}
}
#endif
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_coc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 l_coc_size, l_remaining_size;
OPJ_UINT32 l_comp_room;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_comp_room = (p_j2k->m_private_image->numcomps <= 256) ? 1 : 2;
l_coc_size = 5 + l_comp_room + opj_j2k_get_SPCod_SPCoc_size(p_j2k,
p_j2k->m_current_tile_number, p_comp_no);
if (l_coc_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data;
/*p_j2k->m_specific_param.m_encoder.m_header_tile_data
= (OPJ_BYTE*)opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data,
l_coc_size);*/
new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_coc_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write COC marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_coc_size;
}
opj_j2k_write_coc_in_memory(p_j2k, p_comp_no,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, &l_remaining_size,
p_manager);
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_coc_size,
p_manager) != l_coc_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_compare_coc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no)
{
opj_cp_t *l_cp = NULL;
opj_tcp_t *l_tcp = NULL;
/* preconditions */
assert(p_j2k != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_j2k->m_current_tile_number];
if (l_tcp->tccps[p_first_comp_no].csty != l_tcp->tccps[p_second_comp_no].csty) {
return OPJ_FALSE;
}
return opj_j2k_compare_SPCod_SPCoc(p_j2k, p_j2k->m_current_tile_number,
p_first_comp_no, p_second_comp_no);
}
static void opj_j2k_write_coc_in_memory(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
opj_event_mgr_t * p_manager
)
{
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
OPJ_UINT32 l_coc_size, l_remaining_size;
OPJ_BYTE * l_current_data = 00;
opj_image_t *l_image = 00;
OPJ_UINT32 l_comp_room;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_j2k->m_current_tile_number];
l_image = p_j2k->m_private_image;
l_comp_room = (l_image->numcomps <= 256) ? 1 : 2;
l_coc_size = 5 + l_comp_room + opj_j2k_get_SPCod_SPCoc_size(p_j2k,
p_j2k->m_current_tile_number, p_comp_no);
l_remaining_size = l_coc_size;
l_current_data = p_data;
opj_write_bytes(l_current_data, J2K_MS_COC,
2); /* COC */
l_current_data += 2;
opj_write_bytes(l_current_data, l_coc_size - 2,
2); /* L_COC */
l_current_data += 2;
opj_write_bytes(l_current_data, p_comp_no, l_comp_room); /* Ccoc */
l_current_data += l_comp_room;
opj_write_bytes(l_current_data, l_tcp->tccps[p_comp_no].csty,
1); /* Scoc */
++l_current_data;
l_remaining_size -= (5 + l_comp_room);
opj_j2k_write_SPCod_SPCoc(p_j2k, p_j2k->m_current_tile_number, 0,
l_current_data, &l_remaining_size, p_manager);
* p_data_written = l_coc_size;
}
static OPJ_UINT32 opj_j2k_get_max_coc_size(opj_j2k_t *p_j2k)
{
OPJ_UINT32 i, j;
OPJ_UINT32 l_nb_comp;
OPJ_UINT32 l_nb_tiles;
OPJ_UINT32 l_max = 0;
/* preconditions */
l_nb_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th ;
l_nb_comp = p_j2k->m_private_image->numcomps;
for (i = 0; i < l_nb_tiles; ++i) {
for (j = 0; j < l_nb_comp; ++j) {
l_max = opj_uint_max(l_max, opj_j2k_get_SPCod_SPCoc_size(p_j2k, i, j));
}
}
return 6 + l_max;
}
/**
* Reads a COC marker (Coding Style Component)
* @param p_header_data the data contained in the COC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the COC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_coc(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
opj_cp_t *l_cp = NULL;
opj_tcp_t *l_tcp = NULL;
opj_image_t *l_image = NULL;
OPJ_UINT32 l_comp_room;
OPJ_UINT32 l_comp_no;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH)
?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
l_image = p_j2k->m_private_image;
l_comp_room = l_image->numcomps <= 256 ? 1 : 2;
/* make sure room is sufficient*/
if (p_header_size < l_comp_room + 1) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading COC marker\n");
return OPJ_FALSE;
}
p_header_size -= l_comp_room + 1;
opj_read_bytes(p_header_data, &l_comp_no,
l_comp_room); /* Ccoc */
p_header_data += l_comp_room;
if (l_comp_no >= l_image->numcomps) {
opj_event_msg(p_manager, EVT_ERROR,
"Error reading COC marker (bad number of components)\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_tcp->tccps[l_comp_no].csty,
1); /* Scoc */
++p_header_data ;
if (! opj_j2k_read_SPCod_SPCoc(p_j2k, l_comp_no, p_header_data, &p_header_size,
p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading COC marker\n");
return OPJ_FALSE;
}
if (p_header_size != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading COC marker\n");
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_qcd(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_qcd_size, l_remaining_size;
OPJ_BYTE * l_current_data = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_qcd_size = 4 + opj_j2k_get_SQcd_SQcc_size(p_j2k, p_j2k->m_current_tile_number,
0);
l_remaining_size = l_qcd_size;
if (l_qcd_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_qcd_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write QCD marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_qcd_size;
}
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_data, J2K_MS_QCD, 2); /* QCD */
l_current_data += 2;
opj_write_bytes(l_current_data, l_qcd_size - 2, 2); /* L_QCD */
l_current_data += 2;
l_remaining_size -= 4;
if (! opj_j2k_write_SQcd_SQcc(p_j2k, p_j2k->m_current_tile_number, 0,
l_current_data, &l_remaining_size, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing QCD marker\n");
return OPJ_FALSE;
}
if (l_remaining_size != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing QCD marker\n");
return OPJ_FALSE;
}
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_qcd_size,
p_manager) != l_qcd_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a QCD marker (Quantization defaults)
* @param p_header_data the data contained in the QCD box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the QCD marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_qcd(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_j2k_read_SQcd_SQcc(p_j2k, 0, p_header_data, &p_header_size,
p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading QCD marker\n");
return OPJ_FALSE;
}
if (p_header_size != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading QCD marker\n");
return OPJ_FALSE;
}
/* Apply the quantization parameters to other components of the current tile or the m_default_tcp */
opj_j2k_copy_tile_quantization_parameters(p_j2k);
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_qcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_qcc_size, l_remaining_size;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_qcc_size = 5 + opj_j2k_get_SQcd_SQcc_size(p_j2k, p_j2k->m_current_tile_number,
p_comp_no);
l_qcc_size += p_j2k->m_private_image->numcomps <= 256 ? 0 : 1;
l_remaining_size = l_qcc_size;
if (l_qcc_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_qcc_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write QCC marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_qcc_size;
}
opj_j2k_write_qcc_in_memory(p_j2k, p_comp_no,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, &l_remaining_size,
p_manager);
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_qcc_size,
p_manager) != l_qcc_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_compare_qcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no)
{
return opj_j2k_compare_SQcd_SQcc(p_j2k, p_j2k->m_current_tile_number,
p_first_comp_no, p_second_comp_no);
}
static void opj_j2k_write_qcc_in_memory(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_qcc_size, l_remaining_size;
OPJ_BYTE * l_current_data = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
l_qcc_size = 6 + opj_j2k_get_SQcd_SQcc_size(p_j2k, p_j2k->m_current_tile_number,
p_comp_no);
l_remaining_size = l_qcc_size;
l_current_data = p_data;
opj_write_bytes(l_current_data, J2K_MS_QCC, 2); /* QCC */
l_current_data += 2;
if (p_j2k->m_private_image->numcomps <= 256) {
--l_qcc_size;
opj_write_bytes(l_current_data, l_qcc_size - 2, 2); /* L_QCC */
l_current_data += 2;
opj_write_bytes(l_current_data, p_comp_no, 1); /* Cqcc */
++l_current_data;
/* in the case only one byte is sufficient the last byte allocated is useless -> still do -6 for available */
l_remaining_size -= 6;
} else {
opj_write_bytes(l_current_data, l_qcc_size - 2, 2); /* L_QCC */
l_current_data += 2;
opj_write_bytes(l_current_data, p_comp_no, 2); /* Cqcc */
l_current_data += 2;
l_remaining_size -= 6;
}
opj_j2k_write_SQcd_SQcc(p_j2k, p_j2k->m_current_tile_number, p_comp_no,
l_current_data, &l_remaining_size, p_manager);
*p_data_written = l_qcc_size;
}
static OPJ_UINT32 opj_j2k_get_max_qcc_size(opj_j2k_t *p_j2k)
{
return opj_j2k_get_max_coc_size(p_j2k);
}
/**
* Reads a QCC marker (Quantization component)
* @param p_header_data the data contained in the QCC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the QCC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_qcc(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_num_comp, l_comp_no;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_num_comp = p_j2k->m_private_image->numcomps;
if (l_num_comp <= 256) {
if (p_header_size < 1) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading QCC marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_comp_no, 1);
++p_header_data;
--p_header_size;
} else {
if (p_header_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading QCC marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_comp_no, 2);
p_header_data += 2;
p_header_size -= 2;
}
#ifdef USE_JPWL
if (p_j2k->m_cp.correct) {
static OPJ_UINT32 backup_compno = 0;
/* compno is negative or larger than the number of components!!! */
if (/*(l_comp_no < 0) ||*/ (l_comp_no >= l_num_comp)) {
opj_event_msg(p_manager, EVT_ERROR,
"JPWL: bad component number in QCC (%d out of a maximum of %d)\n",
l_comp_no, l_num_comp);
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
/* we try to correct */
l_comp_no = backup_compno % l_num_comp;
opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust this\n"
"- setting component number to %d\n",
l_comp_no);
}
/* keep your private count of tiles */
backup_compno++;
};
#endif /* USE_JPWL */
if (l_comp_no >= p_j2k->m_private_image->numcomps) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid component number: %d, regarding the number of components %d\n",
l_comp_no, p_j2k->m_private_image->numcomps);
return OPJ_FALSE;
}
if (! opj_j2k_read_SQcd_SQcc(p_j2k, l_comp_no, p_header_data, &p_header_size,
p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading QCC marker\n");
return OPJ_FALSE;
}
if (p_header_size != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading QCC marker\n");
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_poc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_nb_comp;
OPJ_UINT32 l_nb_poc;
OPJ_UINT32 l_poc_size;
OPJ_UINT32 l_written_size = 0;
opj_tcp_t *l_tcp = 00;
OPJ_UINT32 l_poc_room;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_tcp = &p_j2k->m_cp.tcps[p_j2k->m_current_tile_number];
l_nb_comp = p_j2k->m_private_image->numcomps;
l_nb_poc = 1 + l_tcp->numpocs;
if (l_nb_comp <= 256) {
l_poc_room = 1;
} else {
l_poc_room = 2;
}
l_poc_size = 4 + (5 + 2 * l_poc_room) * l_nb_poc;
if (l_poc_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_poc_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write POC marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_poc_size;
}
opj_j2k_write_poc_in_memory(p_j2k,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, &l_written_size,
p_manager);
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_poc_size,
p_manager) != l_poc_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static void opj_j2k_write_poc_in_memory(opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 i;
OPJ_BYTE * l_current_data = 00;
OPJ_UINT32 l_nb_comp;
OPJ_UINT32 l_nb_poc;
OPJ_UINT32 l_poc_size;
opj_image_t *l_image = 00;
opj_tcp_t *l_tcp = 00;
opj_tccp_t *l_tccp = 00;
opj_poc_t *l_current_poc = 00;
OPJ_UINT32 l_poc_room;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_manager);
l_tcp = &p_j2k->m_cp.tcps[p_j2k->m_current_tile_number];
l_tccp = &l_tcp->tccps[0];
l_image = p_j2k->m_private_image;
l_nb_comp = l_image->numcomps;
l_nb_poc = 1 + l_tcp->numpocs;
if (l_nb_comp <= 256) {
l_poc_room = 1;
} else {
l_poc_room = 2;
}
l_poc_size = 4 + (5 + 2 * l_poc_room) * l_nb_poc;
l_current_data = p_data;
opj_write_bytes(l_current_data, J2K_MS_POC,
2); /* POC */
l_current_data += 2;
opj_write_bytes(l_current_data, l_poc_size - 2,
2); /* Lpoc */
l_current_data += 2;
l_current_poc = l_tcp->pocs;
for (i = 0; i < l_nb_poc; ++i) {
opj_write_bytes(l_current_data, l_current_poc->resno0,
1); /* RSpoc_i */
++l_current_data;
opj_write_bytes(l_current_data, l_current_poc->compno0,
l_poc_room); /* CSpoc_i */
l_current_data += l_poc_room;
opj_write_bytes(l_current_data, l_current_poc->layno1,
2); /* LYEpoc_i */
l_current_data += 2;
opj_write_bytes(l_current_data, l_current_poc->resno1,
1); /* REpoc_i */
++l_current_data;
opj_write_bytes(l_current_data, l_current_poc->compno1,
l_poc_room); /* CEpoc_i */
l_current_data += l_poc_room;
opj_write_bytes(l_current_data, (OPJ_UINT32)l_current_poc->prg,
1); /* Ppoc_i */
++l_current_data;
/* change the value of the max layer according to the actual number of layers in the file, components and resolutions*/
l_current_poc->layno1 = (OPJ_UINT32)opj_int_min((OPJ_INT32)
l_current_poc->layno1, (OPJ_INT32)l_tcp->numlayers);
l_current_poc->resno1 = (OPJ_UINT32)opj_int_min((OPJ_INT32)
l_current_poc->resno1, (OPJ_INT32)l_tccp->numresolutions);
l_current_poc->compno1 = (OPJ_UINT32)opj_int_min((OPJ_INT32)
l_current_poc->compno1, (OPJ_INT32)l_nb_comp);
++l_current_poc;
}
*p_data_written = l_poc_size;
}
static OPJ_UINT32 opj_j2k_get_max_poc_size(opj_j2k_t *p_j2k)
{
opj_tcp_t * l_tcp = 00;
OPJ_UINT32 l_nb_tiles = 0;
OPJ_UINT32 l_max_poc = 0;
OPJ_UINT32 i;
l_tcp = p_j2k->m_cp.tcps;
l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
for (i = 0; i < l_nb_tiles; ++i) {
l_max_poc = opj_uint_max(l_max_poc, l_tcp->numpocs);
++l_tcp;
}
++l_max_poc;
return 4 + 9 * l_max_poc;
}
static OPJ_UINT32 opj_j2k_get_max_toc_size(opj_j2k_t *p_j2k)
{
OPJ_UINT32 i;
OPJ_UINT32 l_nb_tiles;
OPJ_UINT32 l_max = 0;
opj_tcp_t * l_tcp = 00;
l_tcp = p_j2k->m_cp.tcps;
l_nb_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th ;
for (i = 0; i < l_nb_tiles; ++i) {
l_max = opj_uint_max(l_max, l_tcp->m_nb_tile_parts);
++l_tcp;
}
return 12 * l_max;
}
static OPJ_UINT32 opj_j2k_get_specific_header_sizes(opj_j2k_t *p_j2k)
{
OPJ_UINT32 l_nb_bytes = 0;
OPJ_UINT32 l_nb_comps;
OPJ_UINT32 l_coc_bytes, l_qcc_bytes;
l_nb_comps = p_j2k->m_private_image->numcomps - 1;
l_nb_bytes += opj_j2k_get_max_toc_size(p_j2k);
if (!(OPJ_IS_CINEMA(p_j2k->m_cp.rsiz))) {
l_coc_bytes = opj_j2k_get_max_coc_size(p_j2k);
l_nb_bytes += l_nb_comps * l_coc_bytes;
l_qcc_bytes = opj_j2k_get_max_qcc_size(p_j2k);
l_nb_bytes += l_nb_comps * l_qcc_bytes;
}
l_nb_bytes += opj_j2k_get_max_poc_size(p_j2k);
/*** DEVELOPER CORNER, Add room for your headers ***/
return l_nb_bytes;
}
/**
* Reads a POC marker (Progression Order Change)
*
* @param p_header_data the data contained in the POC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the POC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_poc(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 i, l_nb_comp, l_tmp;
opj_image_t * l_image = 00;
OPJ_UINT32 l_old_poc_nb, l_current_poc_nb, l_current_poc_remaining;
OPJ_UINT32 l_chunk_size, l_comp_room;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_poc_t *l_current_poc = 00;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_image = p_j2k->m_private_image;
l_nb_comp = l_image->numcomps;
if (l_nb_comp <= 256) {
l_comp_room = 1;
} else {
l_comp_room = 2;
}
l_chunk_size = 5 + 2 * l_comp_room;
l_current_poc_nb = p_header_size / l_chunk_size;
l_current_poc_remaining = p_header_size % l_chunk_size;
if ((l_current_poc_nb <= 0) || (l_current_poc_remaining != 0)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading POC marker\n");
return OPJ_FALSE;
}
l_cp = &(p_j2k->m_cp);
l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
l_old_poc_nb = l_tcp->POC ? l_tcp->numpocs + 1 : 0;
l_current_poc_nb += l_old_poc_nb;
if (l_current_poc_nb >= 32) {
opj_event_msg(p_manager, EVT_ERROR, "Too many POCs %d\n", l_current_poc_nb);
return OPJ_FALSE;
}
assert(l_current_poc_nb < 32);
/* now poc is in use.*/
l_tcp->POC = 1;
l_current_poc = &l_tcp->pocs[l_old_poc_nb];
for (i = l_old_poc_nb; i < l_current_poc_nb; ++i) {
opj_read_bytes(p_header_data, &(l_current_poc->resno0),
1); /* RSpoc_i */
++p_header_data;
opj_read_bytes(p_header_data, &(l_current_poc->compno0),
l_comp_room); /* CSpoc_i */
p_header_data += l_comp_room;
opj_read_bytes(p_header_data, &(l_current_poc->layno1),
2); /* LYEpoc_i */
/* make sure layer end is in acceptable bounds */
l_current_poc->layno1 = opj_uint_min(l_current_poc->layno1, l_tcp->numlayers);
p_header_data += 2;
opj_read_bytes(p_header_data, &(l_current_poc->resno1),
1); /* REpoc_i */
++p_header_data;
opj_read_bytes(p_header_data, &(l_current_poc->compno1),
l_comp_room); /* CEpoc_i */
p_header_data += l_comp_room;
opj_read_bytes(p_header_data, &l_tmp,
1); /* Ppoc_i */
++p_header_data;
l_current_poc->prg = (OPJ_PROG_ORDER) l_tmp;
/* make sure comp is in acceptable bounds */
l_current_poc->compno1 = opj_uint_min(l_current_poc->compno1, l_nb_comp);
++l_current_poc;
}
l_tcp->numpocs = l_current_poc_nb - 1;
return OPJ_TRUE;
}
/**
* Reads a CRG marker (Component registration)
*
* @param p_header_data the data contained in the TLM box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the TLM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_crg(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_nb_comp;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_header_data);
l_nb_comp = p_j2k->m_private_image->numcomps;
if (p_header_size != l_nb_comp * 4) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading CRG marker\n");
return OPJ_FALSE;
}
/* Do not care of this at the moment since only local variables are set here */
/*
for
(i = 0; i < l_nb_comp; ++i)
{
opj_read_bytes(p_header_data,&l_Xcrg_i,2); // Xcrg_i
p_header_data+=2;
opj_read_bytes(p_header_data,&l_Ycrg_i,2); // Xcrg_i
p_header_data+=2;
}
*/
return OPJ_TRUE;
}
/**
* Reads a TLM marker (Tile Length Marker)
*
* @param p_header_data the data contained in the TLM box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the TLM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_tlm(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_Ztlm, l_Stlm, l_ST, l_SP, l_tot_num_tp_remaining, l_quotient,
l_Ptlm_size;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_j2k);
if (p_header_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading TLM marker\n");
return OPJ_FALSE;
}
p_header_size -= 2;
opj_read_bytes(p_header_data, &l_Ztlm,
1); /* Ztlm */
++p_header_data;
opj_read_bytes(p_header_data, &l_Stlm,
1); /* Stlm */
++p_header_data;
l_ST = ((l_Stlm >> 4) & 0x3);
l_SP = (l_Stlm >> 6) & 0x1;
l_Ptlm_size = (l_SP + 1) * 2;
l_quotient = l_Ptlm_size + l_ST;
l_tot_num_tp_remaining = p_header_size % l_quotient;
if (l_tot_num_tp_remaining != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading TLM marker\n");
return OPJ_FALSE;
}
/* FIXME Do not care of this at the moment since only local variables are set here */
/*
for
(i = 0; i < l_tot_num_tp; ++i)
{
opj_read_bytes(p_header_data,&l_Ttlm_i,l_ST); // Ttlm_i
p_header_data += l_ST;
opj_read_bytes(p_header_data,&l_Ptlm_i,l_Ptlm_size); // Ptlm_i
p_header_data += l_Ptlm_size;
}*/
return OPJ_TRUE;
}
/**
* Reads a PLM marker (Packet length, main header marker)
*
* @param p_header_data the data contained in the TLM box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the TLM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_plm(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_j2k);
OPJ_UNUSED(p_header_data);
if (p_header_size < 1) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading PLM marker\n");
return OPJ_FALSE;
}
/* Do not care of this at the moment since only local variables are set here */
/*
opj_read_bytes(p_header_data,&l_Zplm,1); // Zplm
++p_header_data;
--p_header_size;
while
(p_header_size > 0)
{
opj_read_bytes(p_header_data,&l_Nplm,1); // Nplm
++p_header_data;
p_header_size -= (1+l_Nplm);
if
(p_header_size < 0)
{
opj_event_msg(p_manager, EVT_ERROR, "Error reading PLM marker\n");
return false;
}
for
(i = 0; i < l_Nplm; ++i)
{
opj_read_bytes(p_header_data,&l_tmp,1); // Iplm_ij
++p_header_data;
// take only the last seven bytes
l_packet_len |= (l_tmp & 0x7f);
if
(l_tmp & 0x80)
{
l_packet_len <<= 7;
}
else
{
// store packet length and proceed to next packet
l_packet_len = 0;
}
}
if
(l_packet_len != 0)
{
opj_event_msg(p_manager, EVT_ERROR, "Error reading PLM marker\n");
return false;
}
}
*/
return OPJ_TRUE;
}
/**
* Reads a PLT marker (Packet length, tile-part header)
*
* @param p_header_data the data contained in the PLT box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the PLT marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_plt(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_Zplt, l_tmp, l_packet_len = 0, i;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_j2k);
if (p_header_size < 1) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading PLT marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_Zplt, 1); /* Zplt */
++p_header_data;
--p_header_size;
for (i = 0; i < p_header_size; ++i) {
opj_read_bytes(p_header_data, &l_tmp, 1); /* Iplt_ij */
++p_header_data;
/* take only the last seven bytes */
l_packet_len |= (l_tmp & 0x7f);
if (l_tmp & 0x80) {
l_packet_len <<= 7;
} else {
/* store packet length and proceed to next packet */
l_packet_len = 0;
}
}
if (l_packet_len != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading PLT marker\n");
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a PPM marker (Packed packet headers, main header)
*
* @param p_header_data the data contained in the POC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the POC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_ppm(
opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager)
{
opj_cp_t *l_cp = 00;
OPJ_UINT32 l_Z_ppm;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
/* We need to have the Z_ppm element + 1 byte of Nppm/Ippm at minimum */
if (p_header_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading PPM marker\n");
return OPJ_FALSE;
}
l_cp = &(p_j2k->m_cp);
l_cp->ppm = 1;
opj_read_bytes(p_header_data, &l_Z_ppm, 1); /* Z_ppm */
++p_header_data;
--p_header_size;
/* check allocation needed */
if (l_cp->ppm_markers == NULL) { /* first PPM marker */
OPJ_UINT32 l_newCount = l_Z_ppm + 1U; /* can't overflow, l_Z_ppm is UINT8 */
assert(l_cp->ppm_markers_count == 0U);
l_cp->ppm_markers = (opj_ppx *) opj_calloc(l_newCount, sizeof(opj_ppx));
if (l_cp->ppm_markers == NULL) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPM marker\n");
return OPJ_FALSE;
}
l_cp->ppm_markers_count = l_newCount;
} else if (l_cp->ppm_markers_count <= l_Z_ppm) {
OPJ_UINT32 l_newCount = l_Z_ppm + 1U; /* can't overflow, l_Z_ppm is UINT8 */
opj_ppx *new_ppm_markers;
new_ppm_markers = (opj_ppx *) opj_realloc(l_cp->ppm_markers,
l_newCount * sizeof(opj_ppx));
if (new_ppm_markers == NULL) {
/* clean up to be done on l_cp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPM marker\n");
return OPJ_FALSE;
}
l_cp->ppm_markers = new_ppm_markers;
memset(l_cp->ppm_markers + l_cp->ppm_markers_count, 0,
(l_newCount - l_cp->ppm_markers_count) * sizeof(opj_ppx));
l_cp->ppm_markers_count = l_newCount;
}
if (l_cp->ppm_markers[l_Z_ppm].m_data != NULL) {
/* clean up to be done on l_cp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Zppm %u already read\n", l_Z_ppm);
return OPJ_FALSE;
}
l_cp->ppm_markers[l_Z_ppm].m_data = (OPJ_BYTE *) opj_malloc(p_header_size);
if (l_cp->ppm_markers[l_Z_ppm].m_data == NULL) {
/* clean up to be done on l_cp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPM marker\n");
return OPJ_FALSE;
}
l_cp->ppm_markers[l_Z_ppm].m_data_size = p_header_size;
memcpy(l_cp->ppm_markers[l_Z_ppm].m_data, p_header_data, p_header_size);
return OPJ_TRUE;
}
/**
* Merges all PPM markers read (Packed headers, main header)
*
* @param p_cp main coding parameters.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_merge_ppm(opj_cp_t *p_cp, opj_event_mgr_t * p_manager)
{
OPJ_UINT32 i, l_ppm_data_size, l_N_ppm_remaining;
/* preconditions */
assert(p_cp != 00);
assert(p_manager != 00);
assert(p_cp->ppm_buffer == NULL);
if (p_cp->ppm == 0U) {
return OPJ_TRUE;
}
l_ppm_data_size = 0U;
l_N_ppm_remaining = 0U;
for (i = 0U; i < p_cp->ppm_markers_count; ++i) {
if (p_cp->ppm_markers[i].m_data !=
NULL) { /* standard doesn't seem to require contiguous Zppm */
OPJ_UINT32 l_N_ppm;
OPJ_UINT32 l_data_size = p_cp->ppm_markers[i].m_data_size;
const OPJ_BYTE* l_data = p_cp->ppm_markers[i].m_data;
if (l_N_ppm_remaining >= l_data_size) {
l_N_ppm_remaining -= l_data_size;
l_data_size = 0U;
} else {
l_data += l_N_ppm_remaining;
l_data_size -= l_N_ppm_remaining;
l_N_ppm_remaining = 0U;
}
if (l_data_size > 0U) {
do {
/* read Nppm */
if (l_data_size < 4U) {
/* clean up to be done on l_cp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Not enough bytes to read Nppm\n");
return OPJ_FALSE;
}
opj_read_bytes(l_data, &l_N_ppm, 4);
l_data += 4;
l_data_size -= 4;
l_ppm_data_size +=
l_N_ppm; /* can't overflow, max 256 markers of max 65536 bytes, that is when PPM markers are not corrupted which is checked elsewhere */
if (l_data_size >= l_N_ppm) {
l_data_size -= l_N_ppm;
l_data += l_N_ppm;
} else {
l_N_ppm_remaining = l_N_ppm - l_data_size;
l_data_size = 0U;
}
} while (l_data_size > 0U);
}
}
}
if (l_N_ppm_remaining != 0U) {
/* clean up to be done on l_cp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Corrupted PPM markers\n");
return OPJ_FALSE;
}
p_cp->ppm_buffer = (OPJ_BYTE *) opj_malloc(l_ppm_data_size);
if (p_cp->ppm_buffer == 00) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPM marker\n");
return OPJ_FALSE;
}
p_cp->ppm_len = l_ppm_data_size;
l_ppm_data_size = 0U;
l_N_ppm_remaining = 0U;
for (i = 0U; i < p_cp->ppm_markers_count; ++i) {
if (p_cp->ppm_markers[i].m_data !=
NULL) { /* standard doesn't seem to require contiguous Zppm */
OPJ_UINT32 l_N_ppm;
OPJ_UINT32 l_data_size = p_cp->ppm_markers[i].m_data_size;
const OPJ_BYTE* l_data = p_cp->ppm_markers[i].m_data;
if (l_N_ppm_remaining >= l_data_size) {
memcpy(p_cp->ppm_buffer + l_ppm_data_size, l_data, l_data_size);
l_ppm_data_size += l_data_size;
l_N_ppm_remaining -= l_data_size;
l_data_size = 0U;
} else {
memcpy(p_cp->ppm_buffer + l_ppm_data_size, l_data, l_N_ppm_remaining);
l_ppm_data_size += l_N_ppm_remaining;
l_data += l_N_ppm_remaining;
l_data_size -= l_N_ppm_remaining;
l_N_ppm_remaining = 0U;
}
if (l_data_size > 0U) {
do {
/* read Nppm */
if (l_data_size < 4U) {
/* clean up to be done on l_cp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Not enough bytes to read Nppm\n");
return OPJ_FALSE;
}
opj_read_bytes(l_data, &l_N_ppm, 4);
l_data += 4;
l_data_size -= 4;
if (l_data_size >= l_N_ppm) {
memcpy(p_cp->ppm_buffer + l_ppm_data_size, l_data, l_N_ppm);
l_ppm_data_size += l_N_ppm;
l_data_size -= l_N_ppm;
l_data += l_N_ppm;
} else {
memcpy(p_cp->ppm_buffer + l_ppm_data_size, l_data, l_data_size);
l_ppm_data_size += l_data_size;
l_N_ppm_remaining = l_N_ppm - l_data_size;
l_data_size = 0U;
}
} while (l_data_size > 0U);
}
opj_free(p_cp->ppm_markers[i].m_data);
p_cp->ppm_markers[i].m_data = NULL;
p_cp->ppm_markers[i].m_data_size = 0U;
}
}
p_cp->ppm_data = p_cp->ppm_buffer;
p_cp->ppm_data_size = p_cp->ppm_len;
p_cp->ppm_markers_count = 0U;
opj_free(p_cp->ppm_markers);
p_cp->ppm_markers = NULL;
return OPJ_TRUE;
}
/**
* Reads a PPT marker (Packed packet headers, tile-part header)
*
* @param p_header_data the data contained in the PPT box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the PPT marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_ppt(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
OPJ_UINT32 l_Z_ppt;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
/* We need to have the Z_ppt element + 1 byte of Ippt at minimum */
if (p_header_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading PPT marker\n");
return OPJ_FALSE;
}
l_cp = &(p_j2k->m_cp);
if (l_cp->ppm) {
opj_event_msg(p_manager, EVT_ERROR,
"Error reading PPT marker: packet header have been previously found in the main header (PPM marker).\n");
return OPJ_FALSE;
}
l_tcp = &(l_cp->tcps[p_j2k->m_current_tile_number]);
l_tcp->ppt = 1;
opj_read_bytes(p_header_data, &l_Z_ppt, 1); /* Z_ppt */
++p_header_data;
--p_header_size;
/* check allocation needed */
if (l_tcp->ppt_markers == NULL) { /* first PPT marker */
OPJ_UINT32 l_newCount = l_Z_ppt + 1U; /* can't overflow, l_Z_ppt is UINT8 */
assert(l_tcp->ppt_markers_count == 0U);
l_tcp->ppt_markers = (opj_ppx *) opj_calloc(l_newCount, sizeof(opj_ppx));
if (l_tcp->ppt_markers == NULL) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPT marker\n");
return OPJ_FALSE;
}
l_tcp->ppt_markers_count = l_newCount;
} else if (l_tcp->ppt_markers_count <= l_Z_ppt) {
OPJ_UINT32 l_newCount = l_Z_ppt + 1U; /* can't overflow, l_Z_ppt is UINT8 */
opj_ppx *new_ppt_markers;
new_ppt_markers = (opj_ppx *) opj_realloc(l_tcp->ppt_markers,
l_newCount * sizeof(opj_ppx));
if (new_ppt_markers == NULL) {
/* clean up to be done on l_tcp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPT marker\n");
return OPJ_FALSE;
}
l_tcp->ppt_markers = new_ppt_markers;
memset(l_tcp->ppt_markers + l_tcp->ppt_markers_count, 0,
(l_newCount - l_tcp->ppt_markers_count) * sizeof(opj_ppx));
l_tcp->ppt_markers_count = l_newCount;
}
if (l_tcp->ppt_markers[l_Z_ppt].m_data != NULL) {
/* clean up to be done on l_tcp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Zppt %u already read\n", l_Z_ppt);
return OPJ_FALSE;
}
l_tcp->ppt_markers[l_Z_ppt].m_data = (OPJ_BYTE *) opj_malloc(p_header_size);
if (l_tcp->ppt_markers[l_Z_ppt].m_data == NULL) {
/* clean up to be done on l_tcp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPT marker\n");
return OPJ_FALSE;
}
l_tcp->ppt_markers[l_Z_ppt].m_data_size = p_header_size;
memcpy(l_tcp->ppt_markers[l_Z_ppt].m_data, p_header_data, p_header_size);
return OPJ_TRUE;
}
/**
* Merges all PPT markers read (Packed packet headers, tile-part header)
*
* @param p_tcp the tile.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_merge_ppt(opj_tcp_t *p_tcp, opj_event_mgr_t * p_manager)
{
OPJ_UINT32 i, l_ppt_data_size;
/* preconditions */
assert(p_tcp != 00);
assert(p_manager != 00);
assert(p_tcp->ppt_buffer == NULL);
if (p_tcp->ppt == 0U) {
return OPJ_TRUE;
}
l_ppt_data_size = 0U;
for (i = 0U; i < p_tcp->ppt_markers_count; ++i) {
l_ppt_data_size +=
p_tcp->ppt_markers[i].m_data_size; /* can't overflow, max 256 markers of max 65536 bytes */
}
p_tcp->ppt_buffer = (OPJ_BYTE *) opj_malloc(l_ppt_data_size);
if (p_tcp->ppt_buffer == 00) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPT marker\n");
return OPJ_FALSE;
}
p_tcp->ppt_len = l_ppt_data_size;
l_ppt_data_size = 0U;
for (i = 0U; i < p_tcp->ppt_markers_count; ++i) {
if (p_tcp->ppt_markers[i].m_data !=
NULL) { /* standard doesn't seem to require contiguous Zppt */
memcpy(p_tcp->ppt_buffer + l_ppt_data_size, p_tcp->ppt_markers[i].m_data,
p_tcp->ppt_markers[i].m_data_size);
l_ppt_data_size +=
p_tcp->ppt_markers[i].m_data_size; /* can't overflow, max 256 markers of max 65536 bytes */
opj_free(p_tcp->ppt_markers[i].m_data);
p_tcp->ppt_markers[i].m_data = NULL;
p_tcp->ppt_markers[i].m_data_size = 0U;
}
}
p_tcp->ppt_markers_count = 0U;
opj_free(p_tcp->ppt_markers);
p_tcp->ppt_markers = NULL;
p_tcp->ppt_data = p_tcp->ppt_buffer;
p_tcp->ppt_data_size = p_tcp->ppt_len;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_tlm(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_BYTE * l_current_data = 00;
OPJ_UINT32 l_tlm_size;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_tlm_size = 6 + (5 * p_j2k->m_specific_param.m_encoder.m_total_tile_parts);
if (l_tlm_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_tlm_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write TLM marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_tlm_size;
}
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
/* change the way data is written to avoid seeking if possible */
/* TODO */
p_j2k->m_specific_param.m_encoder.m_tlm_start = opj_stream_tell(p_stream);
opj_write_bytes(l_current_data, J2K_MS_TLM,
2); /* TLM */
l_current_data += 2;
opj_write_bytes(l_current_data, l_tlm_size - 2,
2); /* Lpoc */
l_current_data += 2;
opj_write_bytes(l_current_data, 0,
1); /* Ztlm=0*/
++l_current_data;
opj_write_bytes(l_current_data, 0x50,
1); /* Stlm ST=1(8bits-255 tiles max),SP=1(Ptlm=32bits) */
++l_current_data;
/* do nothing on the 5 * l_j2k->m_specific_param.m_encoder.m_total_tile_parts remaining data */
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_tlm_size,
p_manager) != l_tlm_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_sot(opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
const opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
OPJ_UNUSED(p_stream);
OPJ_UNUSED(p_manager);
opj_write_bytes(p_data, J2K_MS_SOT,
2); /* SOT */
p_data += 2;
opj_write_bytes(p_data, 10,
2); /* Lsot */
p_data += 2;
opj_write_bytes(p_data, p_j2k->m_current_tile_number,
2); /* Isot */
p_data += 2;
/* Psot */
p_data += 4;
opj_write_bytes(p_data,
p_j2k->m_specific_param.m_encoder.m_current_tile_part_number,
1); /* TPsot */
++p_data;
opj_write_bytes(p_data,
p_j2k->m_cp.tcps[p_j2k->m_current_tile_number].m_nb_tile_parts,
1); /* TNsot */
++p_data;
/* UniPG>> */
#ifdef USE_JPWL
/* update markers struct */
/*
OPJ_BOOL res = j2k_add_marker(p_j2k->cstr_info, J2K_MS_SOT, p_j2k->sot_start, len + 2);
*/
assert(0 && "TODO");
#endif /* USE_JPWL */
* p_data_written = 12;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_get_sot_values(OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
OPJ_UINT32* p_tile_no,
OPJ_UINT32* p_tot_len,
OPJ_UINT32* p_current_part,
OPJ_UINT32* p_num_parts,
opj_event_mgr_t * p_manager)
{
/* preconditions */
assert(p_header_data != 00);
assert(p_manager != 00);
/* Size of this marker is fixed = 12 (we have already read marker and its size)*/
if (p_header_size != 8) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading SOT marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, p_tile_no, 2); /* Isot */
p_header_data += 2;
opj_read_bytes(p_header_data, p_tot_len, 4); /* Psot */
p_header_data += 4;
opj_read_bytes(p_header_data, p_current_part, 1); /* TPsot */
++p_header_data;
opj_read_bytes(p_header_data, p_num_parts, 1); /* TNsot */
++p_header_data;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_read_sot(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager)
{
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
OPJ_UINT32 l_tot_len, l_num_parts = 0;
OPJ_UINT32 l_current_part;
OPJ_UINT32 l_tile_x, l_tile_y;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_j2k_get_sot_values(p_header_data, p_header_size,
&(p_j2k->m_current_tile_number), &l_tot_len, &l_current_part, &l_num_parts,
p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading SOT marker\n");
return OPJ_FALSE;
}
l_cp = &(p_j2k->m_cp);
/* testcase 2.pdf.SIGFPE.706.1112 */
if (p_j2k->m_current_tile_number >= l_cp->tw * l_cp->th) {
opj_event_msg(p_manager, EVT_ERROR, "Invalid tile number %d\n",
p_j2k->m_current_tile_number);
return OPJ_FALSE;
}
l_tcp = &l_cp->tcps[p_j2k->m_current_tile_number];
l_tile_x = p_j2k->m_current_tile_number % l_cp->tw;
l_tile_y = p_j2k->m_current_tile_number / l_cp->tw;
/* Fixes issue with id_000020,sig_06,src_001958,op_flip4,pos_149 */
/* of https://github.com/uclouvain/openjpeg/issues/939 */
/* We must avoid reading twice the same tile part number for a given tile */
/* so as to avoid various issues, like opj_j2k_merge_ppt being called */
/* several times. */
/* ISO 15444-1 A.4.2 Start of tile-part (SOT) mandates that tile parts */
/* should appear in increasing order. */
if (l_tcp->m_current_tile_part_number + 1 != (OPJ_INT32)l_current_part) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid tile part index for tile number %d. "
"Got %d, expected %d\n",
p_j2k->m_current_tile_number,
l_current_part,
l_tcp->m_current_tile_part_number + 1);
return OPJ_FALSE;
}
++ l_tcp->m_current_tile_part_number;
#ifdef USE_JPWL
if (l_cp->correct) {
OPJ_UINT32 tileno = p_j2k->m_current_tile_number;
static OPJ_UINT32 backup_tileno = 0;
/* tileno is negative or larger than the number of tiles!!! */
if (tileno > (l_cp->tw * l_cp->th)) {
opj_event_msg(p_manager, EVT_ERROR,
"JPWL: bad tile number (%d out of a maximum of %d)\n",
tileno, (l_cp->tw * l_cp->th));
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
/* we try to correct */
tileno = backup_tileno;
opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust this\n"
"- setting tile number to %d\n",
tileno);
}
/* keep your private count of tiles */
backup_tileno++;
};
#endif /* USE_JPWL */
/* look for the tile in the list of already processed tile (in parts). */
/* Optimization possible here with a more complex data structure and with the removing of tiles */
/* since the time taken by this function can only grow at the time */
/* PSot should be equal to zero or >=14 or <= 2^32-1 */
if ((l_tot_len != 0) && (l_tot_len < 14)) {
if (l_tot_len ==
12) { /* MSD: Special case for the PHR data which are read by kakadu*/
opj_event_msg(p_manager, EVT_WARNING, "Empty SOT marker detected: Psot=%d.\n",
l_tot_len);
} else {
opj_event_msg(p_manager, EVT_ERROR,
"Psot value is not correct regards to the JPEG2000 norm: %d.\n", l_tot_len);
return OPJ_FALSE;
}
}
#ifdef USE_JPWL
if (l_cp->correct) {
/* totlen is negative or larger than the bytes left!!! */
if (/*(l_tot_len < 0) ||*/ (l_tot_len >
p_header_size)) { /* FIXME it seems correct; for info in V1 -> (p_stream_numbytesleft(p_stream) + 8))) { */
opj_event_msg(p_manager, EVT_ERROR,
"JPWL: bad tile byte size (%d bytes against %d bytes left)\n",
l_tot_len,
p_header_size); /* FIXME it seems correct; for info in V1 -> p_stream_numbytesleft(p_stream) + 8); */
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
/* we try to correct */
l_tot_len = 0;
opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust this\n"
"- setting Psot to %d => assuming it is the last tile\n",
l_tot_len);
}
};
#endif /* USE_JPWL */
/* Ref A.4.2: Psot could be equal zero if it is the last tile-part of the codestream.*/
if (!l_tot_len) {
opj_event_msg(p_manager, EVT_INFO,
"Psot value of the current tile-part is equal to zero, "
"we assuming it is the last tile-part of the codestream.\n");
p_j2k->m_specific_param.m_decoder.m_last_tile_part = 1;
}
if (l_tcp->m_nb_tile_parts != 0 && l_current_part >= l_tcp->m_nb_tile_parts) {
/* Fixes https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=2851 */
opj_event_msg(p_manager, EVT_ERROR,
"In SOT marker, TPSot (%d) is not valid regards to the previous "
"number of tile-part (%d), giving up\n", l_current_part,
l_tcp->m_nb_tile_parts);
p_j2k->m_specific_param.m_decoder.m_last_tile_part = 1;
return OPJ_FALSE;
}
if (l_num_parts !=
0) { /* Number of tile-part header is provided by this tile-part header */
l_num_parts += p_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction;
/* Useful to manage the case of textGBR.jp2 file because two values of TNSot are allowed: the correct numbers of
* tile-parts for that tile and zero (A.4.2 of 15444-1 : 2002). */
if (l_tcp->m_nb_tile_parts) {
if (l_current_part >= l_tcp->m_nb_tile_parts) {
opj_event_msg(p_manager, EVT_ERROR,
"In SOT marker, TPSot (%d) is not valid regards to the current "
"number of tile-part (%d), giving up\n", l_current_part,
l_tcp->m_nb_tile_parts);
p_j2k->m_specific_param.m_decoder.m_last_tile_part = 1;
return OPJ_FALSE;
}
}
if (l_current_part >= l_num_parts) {
/* testcase 451.pdf.SIGSEGV.ce9.3723 */
opj_event_msg(p_manager, EVT_ERROR,
"In SOT marker, TPSot (%d) is not valid regards to the current "
"number of tile-part (header) (%d), giving up\n", l_current_part, l_num_parts);
p_j2k->m_specific_param.m_decoder.m_last_tile_part = 1;
return OPJ_FALSE;
}
l_tcp->m_nb_tile_parts = l_num_parts;
}
/* If know the number of tile part header we will check if we didn't read the last*/
if (l_tcp->m_nb_tile_parts) {
if (l_tcp->m_nb_tile_parts == (l_current_part + 1)) {
p_j2k->m_specific_param.m_decoder.m_can_decode =
1; /* Process the last tile-part header*/
}
}
if (!p_j2k->m_specific_param.m_decoder.m_last_tile_part) {
/* Keep the size of data to skip after this marker */
p_j2k->m_specific_param.m_decoder.m_sot_length = l_tot_len -
12; /* SOT_marker_size = 12 */
} else {
/* FIXME: need to be computed from the number of bytes remaining in the codestream */
p_j2k->m_specific_param.m_decoder.m_sot_length = 0;
}
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPH;
/* Check if the current tile is outside the area we want decode or not corresponding to the tile index*/
if (p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec == -1) {
p_j2k->m_specific_param.m_decoder.m_skip_data =
(l_tile_x < p_j2k->m_specific_param.m_decoder.m_start_tile_x)
|| (l_tile_x >= p_j2k->m_specific_param.m_decoder.m_end_tile_x)
|| (l_tile_y < p_j2k->m_specific_param.m_decoder.m_start_tile_y)
|| (l_tile_y >= p_j2k->m_specific_param.m_decoder.m_end_tile_y);
} else {
assert(p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec >= 0);
p_j2k->m_specific_param.m_decoder.m_skip_data =
(p_j2k->m_current_tile_number != (OPJ_UINT32)
p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec);
}
/* Index */
if (p_j2k->cstr_index) {
assert(p_j2k->cstr_index->tile_index != 00);
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tileno =
p_j2k->m_current_tile_number;
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_tpsno =
l_current_part;
if (l_num_parts != 0) {
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].nb_tps =
l_num_parts;
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps =
l_num_parts;
if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index) {
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index =
(opj_tp_index_t*)opj_calloc(l_num_parts, sizeof(opj_tp_index_t));
if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to read SOT marker. Tile index allocation failed\n");
return OPJ_FALSE;
}
} else {
opj_tp_index_t *new_tp_index = (opj_tp_index_t *) opj_realloc(
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index,
l_num_parts * sizeof(opj_tp_index_t));
if (! new_tp_index) {
opj_free(p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index);
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index = NULL;
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to read SOT marker. Tile index allocation failed\n");
return OPJ_FALSE;
}
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index =
new_tp_index;
}
} else {
/*if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index)*/ {
if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index) {
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps = 10;
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index =
(opj_tp_index_t*)opj_calloc(
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps,
sizeof(opj_tp_index_t));
if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index) {
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps = 0;
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to read SOT marker. Tile index allocation failed\n");
return OPJ_FALSE;
}
}
if (l_current_part >=
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps) {
opj_tp_index_t *new_tp_index;
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps =
l_current_part + 1;
new_tp_index = (opj_tp_index_t *) opj_realloc(
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index,
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps *
sizeof(opj_tp_index_t));
if (! new_tp_index) {
opj_free(p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index);
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index = NULL;
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps = 0;
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to read SOT marker. Tile index allocation failed\n");
return OPJ_FALSE;
}
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index =
new_tp_index;
}
}
}
}
/* FIXME move this onto a separate method to call before reading any SOT, remove part about main_end header, use a index struct inside p_j2k */
/* if (p_j2k->cstr_info) {
if (l_tcp->first) {
if (tileno == 0) {
p_j2k->cstr_info->main_head_end = p_stream_tell(p_stream) - 13;
}
p_j2k->cstr_info->tile[tileno].tileno = tileno;
p_j2k->cstr_info->tile[tileno].start_pos = p_stream_tell(p_stream) - 12;
p_j2k->cstr_info->tile[tileno].end_pos = p_j2k->cstr_info->tile[tileno].start_pos + totlen - 1;
p_j2k->cstr_info->tile[tileno].num_tps = numparts;
if (numparts) {
p_j2k->cstr_info->tile[tileno].tp = (opj_tp_info_t *) opj_malloc(numparts * sizeof(opj_tp_info_t));
}
else {
p_j2k->cstr_info->tile[tileno].tp = (opj_tp_info_t *) opj_malloc(10 * sizeof(opj_tp_info_t)); // Fixme (10)
}
}
else {
p_j2k->cstr_info->tile[tileno].end_pos += totlen;
}
p_j2k->cstr_info->tile[tileno].tp[partno].tp_start_pos = p_stream_tell(p_stream) - 12;
p_j2k->cstr_info->tile[tileno].tp[partno].tp_end_pos =
p_j2k->cstr_info->tile[tileno].tp[partno].tp_start_pos + totlen - 1;
}*/
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_sod(opj_j2k_t *p_j2k,
opj_tcd_t * p_tile_coder,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_total_data_size,
const opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
opj_codestream_info_t *l_cstr_info = 00;
OPJ_UINT32 l_remaining_data;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
OPJ_UNUSED(p_stream);
opj_write_bytes(p_data, J2K_MS_SOD,
2); /* SOD */
p_data += 2;
/* make room for the EOF marker */
l_remaining_data = p_total_data_size - 4;
/* update tile coder */
p_tile_coder->tp_num =
p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number ;
p_tile_coder->cur_tp_num =
p_j2k->m_specific_param.m_encoder.m_current_tile_part_number;
/* INDEX >> */
/* TODO mergeV2: check this part which use cstr_info */
/*l_cstr_info = p_j2k->cstr_info;
if (l_cstr_info) {
if (!p_j2k->m_specific_param.m_encoder.m_current_tile_part_number ) {
//TODO cstr_info->tile[p_j2k->m_current_tile_number].end_header = p_stream_tell(p_stream) + p_j2k->pos_correction - 1;
l_cstr_info->tile[p_j2k->m_current_tile_number].tileno = p_j2k->m_current_tile_number;
}
else {*/
/*
TODO
if
(cstr_info->tile[p_j2k->m_current_tile_number].packet[cstr_info->packno - 1].end_pos < p_stream_tell(p_stream))
{
cstr_info->tile[p_j2k->m_current_tile_number].packet[cstr_info->packno].start_pos = p_stream_tell(p_stream);
}*/
/*}*/
/* UniPG>> */
#ifdef USE_JPWL
/* update markers struct */
/*OPJ_BOOL res = j2k_add_marker(p_j2k->cstr_info, J2K_MS_SOD, p_j2k->sod_start, 2);
*/
assert(0 && "TODO");
#endif /* USE_JPWL */
/* <<UniPG */
/*}*/
/* << INDEX */
if (p_j2k->m_specific_param.m_encoder.m_current_tile_part_number == 0) {
p_tile_coder->tcd_image->tiles->packno = 0;
if (l_cstr_info) {
l_cstr_info->packno = 0;
}
}
*p_data_written = 0;
if (! opj_tcd_encode_tile(p_tile_coder, p_j2k->m_current_tile_number, p_data,
p_data_written, l_remaining_data, l_cstr_info,
p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Cannot encode tile\n");
return OPJ_FALSE;
}
*p_data_written += 2;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_read_sod(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_SIZE_T l_current_read_size;
opj_codestream_index_t * l_cstr_index = 00;
OPJ_BYTE ** l_current_data = 00;
opj_tcp_t * l_tcp = 00;
OPJ_UINT32 * l_tile_len = 00;
OPJ_BOOL l_sot_length_pb_detected = OPJ_FALSE;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_tcp = &(p_j2k->m_cp.tcps[p_j2k->m_current_tile_number]);
if (p_j2k->m_specific_param.m_decoder.m_last_tile_part) {
/* opj_stream_get_number_byte_left returns OPJ_OFF_T
// but we are in the last tile part,
// so its result will fit on OPJ_UINT32 unless we find
// a file with a single tile part of more than 4 GB...*/
p_j2k->m_specific_param.m_decoder.m_sot_length = (OPJ_UINT32)(
opj_stream_get_number_byte_left(p_stream) - 2);
} else {
/* Check to avoid pass the limit of OPJ_UINT32 */
if (p_j2k->m_specific_param.m_decoder.m_sot_length >= 2) {
p_j2k->m_specific_param.m_decoder.m_sot_length -= 2;
} else {
/* MSD: case commented to support empty SOT marker (PHR data) */
}
}
l_current_data = &(l_tcp->m_data);
l_tile_len = &l_tcp->m_data_size;
/* Patch to support new PHR data */
if (p_j2k->m_specific_param.m_decoder.m_sot_length) {
/* If we are here, we'll try to read the data after allocation */
/* Check enough bytes left in stream before allocation */
if ((OPJ_OFF_T)p_j2k->m_specific_param.m_decoder.m_sot_length >
opj_stream_get_number_byte_left(p_stream)) {
opj_event_msg(p_manager, EVT_ERROR,
"Tile part length size inconsistent with stream length\n");
return OPJ_FALSE;
}
if (p_j2k->m_specific_param.m_decoder.m_sot_length >
UINT_MAX - OPJ_COMMON_CBLK_DATA_EXTRA) {
opj_event_msg(p_manager, EVT_ERROR,
"p_j2k->m_specific_param.m_decoder.m_sot_length > "
"UINT_MAX - OPJ_COMMON_CBLK_DATA_EXTRA");
return OPJ_FALSE;
}
/* Add a margin of OPJ_COMMON_CBLK_DATA_EXTRA to the allocation we */
/* do so that opj_mqc_init_dec_common() can safely add a synthetic */
/* 0xFFFF marker. */
if (! *l_current_data) {
/* LH: oddly enough, in this path, l_tile_len!=0.
* TODO: If this was consistent, we could simplify the code to only use realloc(), as realloc(0,...) default to malloc(0,...).
*/
*l_current_data = (OPJ_BYTE*) opj_malloc(
p_j2k->m_specific_param.m_decoder.m_sot_length + OPJ_COMMON_CBLK_DATA_EXTRA);
} else {
OPJ_BYTE *l_new_current_data;
if (*l_tile_len > UINT_MAX - OPJ_COMMON_CBLK_DATA_EXTRA -
p_j2k->m_specific_param.m_decoder.m_sot_length) {
opj_event_msg(p_manager, EVT_ERROR,
"*l_tile_len > UINT_MAX - OPJ_COMMON_CBLK_DATA_EXTRA - "
"p_j2k->m_specific_param.m_decoder.m_sot_length");
return OPJ_FALSE;
}
l_new_current_data = (OPJ_BYTE *) opj_realloc(*l_current_data,
*l_tile_len + p_j2k->m_specific_param.m_decoder.m_sot_length +
OPJ_COMMON_CBLK_DATA_EXTRA);
if (! l_new_current_data) {
opj_free(*l_current_data);
/*nothing more is done as l_current_data will be set to null, and just
afterward we enter in the error path
and the actual tile_len is updated (committed) at the end of the
function. */
}
*l_current_data = l_new_current_data;
}
if (*l_current_data == 00) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to decode tile\n");
return OPJ_FALSE;
}
} else {
l_sot_length_pb_detected = OPJ_TRUE;
}
/* Index */
l_cstr_index = p_j2k->cstr_index;
if (l_cstr_index) {
OPJ_OFF_T l_current_pos = opj_stream_tell(p_stream) - 2;
OPJ_UINT32 l_current_tile_part =
l_cstr_index->tile_index[p_j2k->m_current_tile_number].current_tpsno;
l_cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index[l_current_tile_part].end_header
=
l_current_pos;
l_cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index[l_current_tile_part].end_pos
=
l_current_pos + p_j2k->m_specific_param.m_decoder.m_sot_length + 2;
if (OPJ_FALSE == opj_j2k_add_tlmarker(p_j2k->m_current_tile_number,
l_cstr_index,
J2K_MS_SOD,
l_current_pos,
p_j2k->m_specific_param.m_decoder.m_sot_length + 2)) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add tl marker\n");
return OPJ_FALSE;
}
/*l_cstr_index->packno = 0;*/
}
/* Patch to support new PHR data */
if (!l_sot_length_pb_detected) {
l_current_read_size = opj_stream_read_data(
p_stream,
*l_current_data + *l_tile_len,
p_j2k->m_specific_param.m_decoder.m_sot_length,
p_manager);
} else {
l_current_read_size = 0;
}
if (l_current_read_size != p_j2k->m_specific_param.m_decoder.m_sot_length) {
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_NEOC;
} else {
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPHSOT;
}
*l_tile_len += (OPJ_UINT32)l_current_read_size;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_rgn(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no,
OPJ_UINT32 nb_comps,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_BYTE * l_current_data = 00;
OPJ_UINT32 l_rgn_size;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_tccp_t *l_tccp = 00;
OPJ_UINT32 l_comp_room;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_tile_no];
l_tccp = &l_tcp->tccps[p_comp_no];
if (nb_comps <= 256) {
l_comp_room = 1;
} else {
l_comp_room = 2;
}
l_rgn_size = 6 + l_comp_room;
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_data, J2K_MS_RGN,
2); /* RGN */
l_current_data += 2;
opj_write_bytes(l_current_data, l_rgn_size - 2,
2); /* Lrgn */
l_current_data += 2;
opj_write_bytes(l_current_data, p_comp_no,
l_comp_room); /* Crgn */
l_current_data += l_comp_room;
opj_write_bytes(l_current_data, 0,
1); /* Srgn */
++l_current_data;
opj_write_bytes(l_current_data, (OPJ_UINT32)l_tccp->roishift,
1); /* SPrgn */
++l_current_data;
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_rgn_size,
p_manager) != l_rgn_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_eoc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
opj_write_bytes(p_j2k->m_specific_param.m_encoder.m_header_tile_data,
J2K_MS_EOC, 2); /* EOC */
/* UniPG>> */
#ifdef USE_JPWL
/* update markers struct */
/*
OPJ_BOOL res = j2k_add_marker(p_j2k->cstr_info, J2K_MS_EOC, p_stream_tell(p_stream) - 2, 2);
*/
#endif /* USE_JPWL */
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, 2, p_manager) != 2) {
return OPJ_FALSE;
}
if (! opj_stream_flush(p_stream, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a RGN marker (Region Of Interest)
*
* @param p_header_data the data contained in the POC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the POC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_rgn(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_nb_comp;
opj_image_t * l_image = 00;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
OPJ_UINT32 l_comp_room, l_comp_no, l_roi_sty;
/* preconditions*/
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_image = p_j2k->m_private_image;
l_nb_comp = l_image->numcomps;
if (l_nb_comp <= 256) {
l_comp_room = 1;
} else {
l_comp_room = 2;
}
if (p_header_size != 2 + l_comp_room) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading RGN marker\n");
return OPJ_FALSE;
}
l_cp = &(p_j2k->m_cp);
l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
opj_read_bytes(p_header_data, &l_comp_no, l_comp_room); /* Crgn */
p_header_data += l_comp_room;
opj_read_bytes(p_header_data, &l_roi_sty,
1); /* Srgn */
++p_header_data;
#ifdef USE_JPWL
if (l_cp->correct) {
/* totlen is negative or larger than the bytes left!!! */
if (l_comp_room >= l_nb_comp) {
opj_event_msg(p_manager, EVT_ERROR,
"JPWL: bad component number in RGN (%d when there are only %d)\n",
l_comp_room, l_nb_comp);
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
}
};
#endif /* USE_JPWL */
/* testcase 3635.pdf.asan.77.2930 */
if (l_comp_no >= l_nb_comp) {
opj_event_msg(p_manager, EVT_ERROR,
"bad component number in RGN (%d when there are only %d)\n",
l_comp_no, l_nb_comp);
return OPJ_FALSE;
}
opj_read_bytes(p_header_data,
(OPJ_UINT32 *)(&(l_tcp->tccps[l_comp_no].roishift)), 1); /* SPrgn */
++p_header_data;
return OPJ_TRUE;
}
static OPJ_FLOAT32 opj_j2k_get_tp_stride(opj_tcp_t * p_tcp)
{
return (OPJ_FLOAT32)((p_tcp->m_nb_tile_parts - 1) * 14);
}
static OPJ_FLOAT32 opj_j2k_get_default_stride(opj_tcp_t * p_tcp)
{
(void)p_tcp;
return 0;
}
static OPJ_BOOL opj_j2k_update_rates(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
opj_cp_t * l_cp = 00;
opj_image_t * l_image = 00;
opj_tcp_t * l_tcp = 00;
opj_image_comp_t * l_img_comp = 00;
OPJ_UINT32 i, j, k;
OPJ_INT32 l_x0, l_y0, l_x1, l_y1;
OPJ_FLOAT32 * l_rates = 0;
OPJ_FLOAT32 l_sot_remove;
OPJ_UINT32 l_bits_empty, l_size_pixel;
OPJ_UINT32 l_tile_size = 0;
OPJ_UINT32 l_last_res;
OPJ_FLOAT32(* l_tp_stride_func)(opj_tcp_t *) = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
OPJ_UNUSED(p_manager);
l_cp = &(p_j2k->m_cp);
l_image = p_j2k->m_private_image;
l_tcp = l_cp->tcps;
l_bits_empty = 8 * l_image->comps->dx * l_image->comps->dy;
l_size_pixel = l_image->numcomps * l_image->comps->prec;
l_sot_remove = (OPJ_FLOAT32) opj_stream_tell(p_stream) / (OPJ_FLOAT32)(
l_cp->th * l_cp->tw);
if (l_cp->m_specific_param.m_enc.m_tp_on) {
l_tp_stride_func = opj_j2k_get_tp_stride;
} else {
l_tp_stride_func = opj_j2k_get_default_stride;
}
for (i = 0; i < l_cp->th; ++i) {
for (j = 0; j < l_cp->tw; ++j) {
OPJ_FLOAT32 l_offset = (OPJ_FLOAT32)(*l_tp_stride_func)(l_tcp) /
(OPJ_FLOAT32)l_tcp->numlayers;
/* 4 borders of the tile rescale on the image if necessary */
l_x0 = opj_int_max((OPJ_INT32)(l_cp->tx0 + j * l_cp->tdx),
(OPJ_INT32)l_image->x0);
l_y0 = opj_int_max((OPJ_INT32)(l_cp->ty0 + i * l_cp->tdy),
(OPJ_INT32)l_image->y0);
l_x1 = opj_int_min((OPJ_INT32)(l_cp->tx0 + (j + 1) * l_cp->tdx),
(OPJ_INT32)l_image->x1);
l_y1 = opj_int_min((OPJ_INT32)(l_cp->ty0 + (i + 1) * l_cp->tdy),
(OPJ_INT32)l_image->y1);
l_rates = l_tcp->rates;
/* Modification of the RATE >> */
if (*l_rates > 0.0f) {
*l_rates = (((OPJ_FLOAT32)(l_size_pixel * (OPJ_UINT32)(l_x1 - l_x0) *
(OPJ_UINT32)(l_y1 - l_y0)))
/
((*l_rates) * (OPJ_FLOAT32)l_bits_empty)
)
-
l_offset;
}
++l_rates;
for (k = 1; k < l_tcp->numlayers; ++k) {
if (*l_rates > 0.0f) {
*l_rates = (((OPJ_FLOAT32)(l_size_pixel * (OPJ_UINT32)(l_x1 - l_x0) *
(OPJ_UINT32)(l_y1 - l_y0)))
/
((*l_rates) * (OPJ_FLOAT32)l_bits_empty)
)
-
l_offset;
}
++l_rates;
}
++l_tcp;
}
}
l_tcp = l_cp->tcps;
for (i = 0; i < l_cp->th; ++i) {
for (j = 0; j < l_cp->tw; ++j) {
l_rates = l_tcp->rates;
if (*l_rates > 0.0f) {
*l_rates -= l_sot_remove;
if (*l_rates < 30.0f) {
*l_rates = 30.0f;
}
}
++l_rates;
l_last_res = l_tcp->numlayers - 1;
for (k = 1; k < l_last_res; ++k) {
if (*l_rates > 0.0f) {
*l_rates -= l_sot_remove;
if (*l_rates < * (l_rates - 1) + 10.0f) {
*l_rates = (*(l_rates - 1)) + 20.0f;
}
}
++l_rates;
}
if (*l_rates > 0.0f) {
*l_rates -= (l_sot_remove + 2.f);
if (*l_rates < * (l_rates - 1) + 10.0f) {
*l_rates = (*(l_rates - 1)) + 20.0f;
}
}
++l_tcp;
}
}
l_img_comp = l_image->comps;
l_tile_size = 0;
for (i = 0; i < l_image->numcomps; ++i) {
l_tile_size += (opj_uint_ceildiv(l_cp->tdx, l_img_comp->dx)
*
opj_uint_ceildiv(l_cp->tdy, l_img_comp->dy)
*
l_img_comp->prec
);
++l_img_comp;
}
l_tile_size = (OPJ_UINT32)(l_tile_size * 0.1625); /* 1.3/8 = 0.1625 */
l_tile_size += opj_j2k_get_specific_header_sizes(p_j2k);
p_j2k->m_specific_param.m_encoder.m_encoded_tile_size = l_tile_size;
p_j2k->m_specific_param.m_encoder.m_encoded_tile_data =
(OPJ_BYTE *) opj_malloc(p_j2k->m_specific_param.m_encoder.m_encoded_tile_size);
if (p_j2k->m_specific_param.m_encoder.m_encoded_tile_data == 00) {
return OPJ_FALSE;
}
if (OPJ_IS_CINEMA(l_cp->rsiz)) {
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer =
(OPJ_BYTE *) opj_malloc(5 *
p_j2k->m_specific_param.m_encoder.m_total_tile_parts);
if (! p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer) {
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current =
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer;
}
return OPJ_TRUE;
}
#if 0
static OPJ_BOOL opj_j2k_read_eoc(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 i;
opj_tcd_t * l_tcd = 00;
OPJ_UINT32 l_nb_tiles;
opj_tcp_t * l_tcp = 00;
OPJ_BOOL l_success;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
l_tcp = p_j2k->m_cp.tcps;
l_tcd = opj_tcd_create(OPJ_TRUE);
if (l_tcd == 00) {
opj_event_msg(p_manager, EVT_ERROR, "Cannot decode tile, memory error\n");
return OPJ_FALSE;
}
for (i = 0; i < l_nb_tiles; ++i) {
if (l_tcp->m_data) {
if (! opj_tcd_init_decode_tile(l_tcd, i)) {
opj_tcd_destroy(l_tcd);
opj_event_msg(p_manager, EVT_ERROR, "Cannot decode tile, memory error\n");
return OPJ_FALSE;
}
l_success = opj_tcd_decode_tile(l_tcd, l_tcp->m_data, l_tcp->m_data_size, i,
p_j2k->cstr_index);
/* cleanup */
if (! l_success) {
p_j2k->m_specific_param.m_decoder.m_state |= J2K_STATE_ERR;
break;
}
}
opj_j2k_tcp_destroy(l_tcp);
++l_tcp;
}
opj_tcd_destroy(l_tcd);
return OPJ_TRUE;
}
#endif
static OPJ_BOOL opj_j2k_get_end_header(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
OPJ_UNUSED(p_manager);
p_j2k->cstr_index->main_head_end = opj_stream_tell(p_stream);
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_mct_data_group(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 i;
opj_simple_mcc_decorrelation_data_t * l_mcc_record;
opj_mct_data_t * l_mct_record;
opj_tcp_t * l_tcp;
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
if (! opj_j2k_write_cbd(p_j2k, p_stream, p_manager)) {
return OPJ_FALSE;
}
l_tcp = &(p_j2k->m_cp.tcps[p_j2k->m_current_tile_number]);
l_mct_record = l_tcp->m_mct_records;
for (i = 0; i < l_tcp->m_nb_mct_records; ++i) {
if (! opj_j2k_write_mct_record(p_j2k, l_mct_record, p_stream, p_manager)) {
return OPJ_FALSE;
}
++l_mct_record;
}
l_mcc_record = l_tcp->m_mcc_records;
for (i = 0; i < l_tcp->m_nb_mcc_records; ++i) {
if (! opj_j2k_write_mcc_record(p_j2k, l_mcc_record, p_stream, p_manager)) {
return OPJ_FALSE;
}
++l_mcc_record;
}
if (! opj_j2k_write_mco(p_j2k, p_stream, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_all_coc(
opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 compno;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
for (compno = 1; compno < p_j2k->m_private_image->numcomps; ++compno) {
/* cod is first component of first tile */
if (! opj_j2k_compare_coc(p_j2k, 0, compno)) {
if (! opj_j2k_write_coc(p_j2k, compno, p_stream, p_manager)) {
return OPJ_FALSE;
}
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_all_qcc(
opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 compno;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
for (compno = 1; compno < p_j2k->m_private_image->numcomps; ++compno) {
/* qcd is first component of first tile */
if (! opj_j2k_compare_qcc(p_j2k, 0, compno)) {
if (! opj_j2k_write_qcc(p_j2k, compno, p_stream, p_manager)) {
return OPJ_FALSE;
}
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_regions(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 compno;
const opj_tccp_t *l_tccp = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_tccp = p_j2k->m_cp.tcps->tccps;
for (compno = 0; compno < p_j2k->m_private_image->numcomps; ++compno) {
if (l_tccp->roishift) {
if (! opj_j2k_write_rgn(p_j2k, 0, compno, p_j2k->m_private_image->numcomps,
p_stream, p_manager)) {
return OPJ_FALSE;
}
}
++l_tccp;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_epc(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
opj_codestream_index_t * l_cstr_index = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
OPJ_UNUSED(p_manager);
l_cstr_index = p_j2k->cstr_index;
if (l_cstr_index) {
l_cstr_index->codestream_size = (OPJ_UINT64)opj_stream_tell(p_stream);
/* UniPG>> */
/* The following adjustment is done to adjust the codestream size */
/* if SOD is not at 0 in the buffer. Useful in case of JP2, where */
/* the first bunch of bytes is not in the codestream */
l_cstr_index->codestream_size -= (OPJ_UINT64)l_cstr_index->main_head_start;
/* <<UniPG */
}
#ifdef USE_JPWL
/* preparation of JPWL marker segments */
#if 0
if (cp->epc_on) {
/* encode according to JPWL */
jpwl_encode(p_j2k, p_stream, image);
}
#endif
assert(0 && "TODO");
#endif /* USE_JPWL */
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_read_unk(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
OPJ_UINT32 *output_marker,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_unknown_marker;
const opj_dec_memory_marker_handler_t * l_marker_handler;
OPJ_UINT32 l_size_unk = 2;
/* preconditions*/
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
opj_event_msg(p_manager, EVT_WARNING, "Unknown marker\n");
for (;;) {
/* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer*/
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* read 2 bytes as the new marker ID*/
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,
&l_unknown_marker, 2);
if (!(l_unknown_marker < 0xff00)) {
/* Get the marker handler from the marker ID*/
l_marker_handler = opj_j2k_get_marker_handler(l_unknown_marker);
if (!(p_j2k->m_specific_param.m_decoder.m_state & l_marker_handler->states)) {
opj_event_msg(p_manager, EVT_ERROR,
"Marker is not compliant with its position\n");
return OPJ_FALSE;
} else {
if (l_marker_handler->id != J2K_MS_UNK) {
/* Add the marker to the codestream index*/
if (l_marker_handler->id != J2K_MS_SOT) {
OPJ_BOOL res = opj_j2k_add_mhmarker(p_j2k->cstr_index, J2K_MS_UNK,
(OPJ_UINT32) opj_stream_tell(p_stream) - l_size_unk,
l_size_unk);
if (res == OPJ_FALSE) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add mh marker\n");
return OPJ_FALSE;
}
}
break; /* next marker is known and well located */
} else {
l_size_unk += 2;
}
}
}
}
*output_marker = l_marker_handler->id ;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_mct_record(opj_j2k_t *p_j2k,
opj_mct_data_t * p_mct_record,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 l_mct_size;
OPJ_BYTE * l_current_data = 00;
OPJ_UINT32 l_tmp;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_mct_size = 10 + p_mct_record->m_data_size;
if (l_mct_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mct_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write MCT marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_mct_size;
}
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_data, J2K_MS_MCT,
2); /* MCT */
l_current_data += 2;
opj_write_bytes(l_current_data, l_mct_size - 2,
2); /* Lmct */
l_current_data += 2;
opj_write_bytes(l_current_data, 0,
2); /* Zmct */
l_current_data += 2;
/* only one marker atm */
l_tmp = (p_mct_record->m_index & 0xff) | (p_mct_record->m_array_type << 8) |
(p_mct_record->m_element_type << 10);
opj_write_bytes(l_current_data, l_tmp, 2);
l_current_data += 2;
opj_write_bytes(l_current_data, 0,
2); /* Ymct */
l_current_data += 2;
memcpy(l_current_data, p_mct_record->m_data, p_mct_record->m_data_size);
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mct_size,
p_manager) != l_mct_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a MCT marker (Multiple Component Transform)
*
* @param p_header_data the data contained in the MCT box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the MCT marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_mct(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 i;
opj_tcp_t *l_tcp = 00;
OPJ_UINT32 l_tmp;
OPJ_UINT32 l_indix;
opj_mct_data_t * l_mct_data;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
l_tcp = p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH ?
&p_j2k->m_cp.tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
if (p_header_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCT marker\n");
return OPJ_FALSE;
}
/* first marker */
opj_read_bytes(p_header_data, &l_tmp, 2); /* Zmct */
p_header_data += 2;
if (l_tmp != 0) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge mct data within multiple MCT records\n");
return OPJ_TRUE;
}
if (p_header_size <= 6) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCT marker\n");
return OPJ_FALSE;
}
/* Imct -> no need for other values, take the first, type is double with decorrelation x0000 1101 0000 0000*/
opj_read_bytes(p_header_data, &l_tmp, 2); /* Imct */
p_header_data += 2;
l_indix = l_tmp & 0xff;
l_mct_data = l_tcp->m_mct_records;
for (i = 0; i < l_tcp->m_nb_mct_records; ++i) {
if (l_mct_data->m_index == l_indix) {
break;
}
++l_mct_data;
}
/* NOT FOUND */
if (i == l_tcp->m_nb_mct_records) {
if (l_tcp->m_nb_mct_records == l_tcp->m_nb_max_mct_records) {
opj_mct_data_t *new_mct_records;
l_tcp->m_nb_max_mct_records += OPJ_J2K_MCT_DEFAULT_NB_RECORDS;
new_mct_records = (opj_mct_data_t *) opj_realloc(l_tcp->m_mct_records,
l_tcp->m_nb_max_mct_records * sizeof(opj_mct_data_t));
if (! new_mct_records) {
opj_free(l_tcp->m_mct_records);
l_tcp->m_mct_records = NULL;
l_tcp->m_nb_max_mct_records = 0;
l_tcp->m_nb_mct_records = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read MCT marker\n");
return OPJ_FALSE;
}
/* Update m_mcc_records[].m_offset_array and m_decorrelation_array
* to point to the new addresses */
if (new_mct_records != l_tcp->m_mct_records) {
for (i = 0; i < l_tcp->m_nb_mcc_records; ++i) {
opj_simple_mcc_decorrelation_data_t* l_mcc_record =
&(l_tcp->m_mcc_records[i]);
if (l_mcc_record->m_decorrelation_array) {
l_mcc_record->m_decorrelation_array =
new_mct_records +
(l_mcc_record->m_decorrelation_array -
l_tcp->m_mct_records);
}
if (l_mcc_record->m_offset_array) {
l_mcc_record->m_offset_array =
new_mct_records +
(l_mcc_record->m_offset_array -
l_tcp->m_mct_records);
}
}
}
l_tcp->m_mct_records = new_mct_records;
l_mct_data = l_tcp->m_mct_records + l_tcp->m_nb_mct_records;
memset(l_mct_data, 0, (l_tcp->m_nb_max_mct_records - l_tcp->m_nb_mct_records) *
sizeof(opj_mct_data_t));
}
l_mct_data = l_tcp->m_mct_records + l_tcp->m_nb_mct_records;
++l_tcp->m_nb_mct_records;
}
if (l_mct_data->m_data) {
opj_free(l_mct_data->m_data);
l_mct_data->m_data = 00;
l_mct_data->m_data_size = 0;
}
l_mct_data->m_index = l_indix;
l_mct_data->m_array_type = (J2K_MCT_ARRAY_TYPE)((l_tmp >> 8) & 3);
l_mct_data->m_element_type = (J2K_MCT_ELEMENT_TYPE)((l_tmp >> 10) & 3);
opj_read_bytes(p_header_data, &l_tmp, 2); /* Ymct */
p_header_data += 2;
if (l_tmp != 0) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge multiple MCT markers\n");
return OPJ_TRUE;
}
p_header_size -= 6;
l_mct_data->m_data = (OPJ_BYTE*)opj_malloc(p_header_size);
if (! l_mct_data->m_data) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCT marker\n");
return OPJ_FALSE;
}
memcpy(l_mct_data->m_data, p_header_data, p_header_size);
l_mct_data->m_data_size = p_header_size;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_mcc_record(opj_j2k_t *p_j2k,
struct opj_simple_mcc_decorrelation_data * p_mcc_record,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 i;
OPJ_UINT32 l_mcc_size;
OPJ_BYTE * l_current_data = 00;
OPJ_UINT32 l_nb_bytes_for_comp;
OPJ_UINT32 l_mask;
OPJ_UINT32 l_tmcc;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
if (p_mcc_record->m_nb_comps > 255) {
l_nb_bytes_for_comp = 2;
l_mask = 0x8000;
} else {
l_nb_bytes_for_comp = 1;
l_mask = 0;
}
l_mcc_size = p_mcc_record->m_nb_comps * 2 * l_nb_bytes_for_comp + 19;
if (l_mcc_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mcc_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write MCC marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_mcc_size;
}
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_data, J2K_MS_MCC,
2); /* MCC */
l_current_data += 2;
opj_write_bytes(l_current_data, l_mcc_size - 2,
2); /* Lmcc */
l_current_data += 2;
/* first marker */
opj_write_bytes(l_current_data, 0,
2); /* Zmcc */
l_current_data += 2;
opj_write_bytes(l_current_data, p_mcc_record->m_index,
1); /* Imcc -> no need for other values, take the first */
++l_current_data;
/* only one marker atm */
opj_write_bytes(l_current_data, 0,
2); /* Ymcc */
l_current_data += 2;
opj_write_bytes(l_current_data, 1,
2); /* Qmcc -> number of collections -> 1 */
l_current_data += 2;
opj_write_bytes(l_current_data, 0x1,
1); /* Xmcci type of component transformation -> array based decorrelation */
++l_current_data;
opj_write_bytes(l_current_data, p_mcc_record->m_nb_comps | l_mask,
2); /* Nmcci number of input components involved and size for each component offset = 8 bits */
l_current_data += 2;
for (i = 0; i < p_mcc_record->m_nb_comps; ++i) {
opj_write_bytes(l_current_data, i,
l_nb_bytes_for_comp); /* Cmccij Component offset*/
l_current_data += l_nb_bytes_for_comp;
}
opj_write_bytes(l_current_data, p_mcc_record->m_nb_comps | l_mask,
2); /* Mmcci number of output components involved and size for each component offset = 8 bits */
l_current_data += 2;
for (i = 0; i < p_mcc_record->m_nb_comps; ++i) {
opj_write_bytes(l_current_data, i,
l_nb_bytes_for_comp); /* Wmccij Component offset*/
l_current_data += l_nb_bytes_for_comp;
}
l_tmcc = ((!p_mcc_record->m_is_irreversible) & 1U) << 16;
if (p_mcc_record->m_decorrelation_array) {
l_tmcc |= p_mcc_record->m_decorrelation_array->m_index;
}
if (p_mcc_record->m_offset_array) {
l_tmcc |= ((p_mcc_record->m_offset_array->m_index) << 8);
}
opj_write_bytes(l_current_data, l_tmcc,
3); /* Tmcci : use MCT defined as number 1 and irreversible array based. */
l_current_data += 3;
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mcc_size,
p_manager) != l_mcc_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_read_mcc(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 i, j;
OPJ_UINT32 l_tmp;
OPJ_UINT32 l_indix;
opj_tcp_t * l_tcp;
opj_simple_mcc_decorrelation_data_t * l_mcc_record;
opj_mct_data_t * l_mct_data;
OPJ_UINT32 l_nb_collections;
OPJ_UINT32 l_nb_comps;
OPJ_UINT32 l_nb_bytes_by_comp;
OPJ_BOOL l_new_mcc = OPJ_FALSE;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_tcp = p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH ?
&p_j2k->m_cp.tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
if (p_header_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
/* first marker */
opj_read_bytes(p_header_data, &l_tmp, 2); /* Zmcc */
p_header_data += 2;
if (l_tmp != 0) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge multiple data spanning\n");
return OPJ_TRUE;
}
if (p_header_size < 7) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_indix,
1); /* Imcc -> no need for other values, take the first */
++p_header_data;
l_mcc_record = l_tcp->m_mcc_records;
for (i = 0; i < l_tcp->m_nb_mcc_records; ++i) {
if (l_mcc_record->m_index == l_indix) {
break;
}
++l_mcc_record;
}
/** NOT FOUND */
if (i == l_tcp->m_nb_mcc_records) {
if (l_tcp->m_nb_mcc_records == l_tcp->m_nb_max_mcc_records) {
opj_simple_mcc_decorrelation_data_t *new_mcc_records;
l_tcp->m_nb_max_mcc_records += OPJ_J2K_MCC_DEFAULT_NB_RECORDS;
new_mcc_records = (opj_simple_mcc_decorrelation_data_t *) opj_realloc(
l_tcp->m_mcc_records, l_tcp->m_nb_max_mcc_records * sizeof(
opj_simple_mcc_decorrelation_data_t));
if (! new_mcc_records) {
opj_free(l_tcp->m_mcc_records);
l_tcp->m_mcc_records = NULL;
l_tcp->m_nb_max_mcc_records = 0;
l_tcp->m_nb_mcc_records = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read MCC marker\n");
return OPJ_FALSE;
}
l_tcp->m_mcc_records = new_mcc_records;
l_mcc_record = l_tcp->m_mcc_records + l_tcp->m_nb_mcc_records;
memset(l_mcc_record, 0, (l_tcp->m_nb_max_mcc_records - l_tcp->m_nb_mcc_records)
* sizeof(opj_simple_mcc_decorrelation_data_t));
}
l_mcc_record = l_tcp->m_mcc_records + l_tcp->m_nb_mcc_records;
l_new_mcc = OPJ_TRUE;
}
l_mcc_record->m_index = l_indix;
/* only one marker atm */
opj_read_bytes(p_header_data, &l_tmp, 2); /* Ymcc */
p_header_data += 2;
if (l_tmp != 0) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge multiple data spanning\n");
return OPJ_TRUE;
}
opj_read_bytes(p_header_data, &l_nb_collections,
2); /* Qmcc -> number of collections -> 1 */
p_header_data += 2;
if (l_nb_collections > 1) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge multiple collections\n");
return OPJ_TRUE;
}
p_header_size -= 7;
for (i = 0; i < l_nb_collections; ++i) {
if (p_header_size < 3) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_tmp,
1); /* Xmcci type of component transformation -> array based decorrelation */
++p_header_data;
if (l_tmp != 1) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge collections other than array decorrelation\n");
return OPJ_TRUE;
}
opj_read_bytes(p_header_data, &l_nb_comps, 2);
p_header_data += 2;
p_header_size -= 3;
l_nb_bytes_by_comp = 1 + (l_nb_comps >> 15);
l_mcc_record->m_nb_comps = l_nb_comps & 0x7fff;
if (p_header_size < (l_nb_bytes_by_comp * l_mcc_record->m_nb_comps + 2)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
p_header_size -= (l_nb_bytes_by_comp * l_mcc_record->m_nb_comps + 2);
for (j = 0; j < l_mcc_record->m_nb_comps; ++j) {
opj_read_bytes(p_header_data, &l_tmp,
l_nb_bytes_by_comp); /* Cmccij Component offset*/
p_header_data += l_nb_bytes_by_comp;
if (l_tmp != j) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge collections with indix shuffle\n");
return OPJ_TRUE;
}
}
opj_read_bytes(p_header_data, &l_nb_comps, 2);
p_header_data += 2;
l_nb_bytes_by_comp = 1 + (l_nb_comps >> 15);
l_nb_comps &= 0x7fff;
if (l_nb_comps != l_mcc_record->m_nb_comps) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge collections without same number of indixes\n");
return OPJ_TRUE;
}
if (p_header_size < (l_nb_bytes_by_comp * l_mcc_record->m_nb_comps + 3)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
p_header_size -= (l_nb_bytes_by_comp * l_mcc_record->m_nb_comps + 3);
for (j = 0; j < l_mcc_record->m_nb_comps; ++j) {
opj_read_bytes(p_header_data, &l_tmp,
l_nb_bytes_by_comp); /* Wmccij Component offset*/
p_header_data += l_nb_bytes_by_comp;
if (l_tmp != j) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge collections with indix shuffle\n");
return OPJ_TRUE;
}
}
opj_read_bytes(p_header_data, &l_tmp, 3); /* Wmccij Component offset*/
p_header_data += 3;
l_mcc_record->m_is_irreversible = !((l_tmp >> 16) & 1);
l_mcc_record->m_decorrelation_array = 00;
l_mcc_record->m_offset_array = 00;
l_indix = l_tmp & 0xff;
if (l_indix != 0) {
l_mct_data = l_tcp->m_mct_records;
for (j = 0; j < l_tcp->m_nb_mct_records; ++j) {
if (l_mct_data->m_index == l_indix) {
l_mcc_record->m_decorrelation_array = l_mct_data;
break;
}
++l_mct_data;
}
if (l_mcc_record->m_decorrelation_array == 00) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
}
l_indix = (l_tmp >> 8) & 0xff;
if (l_indix != 0) {
l_mct_data = l_tcp->m_mct_records;
for (j = 0; j < l_tcp->m_nb_mct_records; ++j) {
if (l_mct_data->m_index == l_indix) {
l_mcc_record->m_offset_array = l_mct_data;
break;
}
++l_mct_data;
}
if (l_mcc_record->m_offset_array == 00) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
}
}
if (p_header_size != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
if (l_new_mcc) {
++l_tcp->m_nb_mcc_records;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_mco(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager
)
{
OPJ_BYTE * l_current_data = 00;
OPJ_UINT32 l_mco_size;
opj_tcp_t * l_tcp = 00;
opj_simple_mcc_decorrelation_data_t * l_mcc_record;
OPJ_UINT32 i;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_tcp = &(p_j2k->m_cp.tcps[p_j2k->m_current_tile_number]);
l_mco_size = 5 + l_tcp->m_nb_mcc_records;
if (l_mco_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mco_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write MCO marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_mco_size;
}
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_data, J2K_MS_MCO, 2); /* MCO */
l_current_data += 2;
opj_write_bytes(l_current_data, l_mco_size - 2, 2); /* Lmco */
l_current_data += 2;
opj_write_bytes(l_current_data, l_tcp->m_nb_mcc_records,
1); /* Nmco : only one transform stage*/
++l_current_data;
l_mcc_record = l_tcp->m_mcc_records;
for (i = 0; i < l_tcp->m_nb_mcc_records; ++i) {
opj_write_bytes(l_current_data, l_mcc_record->m_index,
1); /* Imco -> use the mcc indicated by 1*/
++l_current_data;
++l_mcc_record;
}
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mco_size,
p_manager) != l_mco_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a MCO marker (Multiple Component Transform Ordering)
*
* @param p_header_data the data contained in the MCO box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the MCO marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_mco(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_tmp, i;
OPJ_UINT32 l_nb_stages;
opj_tcp_t * l_tcp;
opj_tccp_t * l_tccp;
opj_image_t * l_image;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_image = p_j2k->m_private_image;
l_tcp = p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH ?
&p_j2k->m_cp.tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
if (p_header_size < 1) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCO marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_nb_stages,
1); /* Nmco : only one transform stage*/
++p_header_data;
if (l_nb_stages > 1) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot take in charge multiple transformation stages.\n");
return OPJ_TRUE;
}
if (p_header_size != l_nb_stages + 1) {
opj_event_msg(p_manager, EVT_WARNING, "Error reading MCO marker\n");
return OPJ_FALSE;
}
l_tccp = l_tcp->tccps;
for (i = 0; i < l_image->numcomps; ++i) {
l_tccp->m_dc_level_shift = 0;
++l_tccp;
}
if (l_tcp->m_mct_decoding_matrix) {
opj_free(l_tcp->m_mct_decoding_matrix);
l_tcp->m_mct_decoding_matrix = 00;
}
for (i = 0; i < l_nb_stages; ++i) {
opj_read_bytes(p_header_data, &l_tmp, 1);
++p_header_data;
if (! opj_j2k_add_mct(l_tcp, p_j2k->m_private_image, l_tmp)) {
return OPJ_FALSE;
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_add_mct(opj_tcp_t * p_tcp, opj_image_t * p_image,
OPJ_UINT32 p_index)
{
OPJ_UINT32 i;
opj_simple_mcc_decorrelation_data_t * l_mcc_record;
opj_mct_data_t * l_deco_array, * l_offset_array;
OPJ_UINT32 l_data_size, l_mct_size, l_offset_size;
OPJ_UINT32 l_nb_elem;
OPJ_UINT32 * l_offset_data, * l_current_offset_data;
opj_tccp_t * l_tccp;
/* preconditions */
assert(p_tcp != 00);
l_mcc_record = p_tcp->m_mcc_records;
for (i = 0; i < p_tcp->m_nb_mcc_records; ++i) {
if (l_mcc_record->m_index == p_index) {
break;
}
}
if (i == p_tcp->m_nb_mcc_records) {
/** element discarded **/
return OPJ_TRUE;
}
if (l_mcc_record->m_nb_comps != p_image->numcomps) {
/** do not support number of comps != image */
return OPJ_TRUE;
}
l_deco_array = l_mcc_record->m_decorrelation_array;
if (l_deco_array) {
l_data_size = MCT_ELEMENT_SIZE[l_deco_array->m_element_type] * p_image->numcomps
* p_image->numcomps;
if (l_deco_array->m_data_size != l_data_size) {
return OPJ_FALSE;
}
l_nb_elem = p_image->numcomps * p_image->numcomps;
l_mct_size = l_nb_elem * (OPJ_UINT32)sizeof(OPJ_FLOAT32);
p_tcp->m_mct_decoding_matrix = (OPJ_FLOAT32*)opj_malloc(l_mct_size);
if (! p_tcp->m_mct_decoding_matrix) {
return OPJ_FALSE;
}
j2k_mct_read_functions_to_float[l_deco_array->m_element_type](
l_deco_array->m_data, p_tcp->m_mct_decoding_matrix, l_nb_elem);
}
l_offset_array = l_mcc_record->m_offset_array;
if (l_offset_array) {
l_data_size = MCT_ELEMENT_SIZE[l_offset_array->m_element_type] *
p_image->numcomps;
if (l_offset_array->m_data_size != l_data_size) {
return OPJ_FALSE;
}
l_nb_elem = p_image->numcomps;
l_offset_size = l_nb_elem * (OPJ_UINT32)sizeof(OPJ_UINT32);
l_offset_data = (OPJ_UINT32*)opj_malloc(l_offset_size);
if (! l_offset_data) {
return OPJ_FALSE;
}
j2k_mct_read_functions_to_int32[l_offset_array->m_element_type](
l_offset_array->m_data, l_offset_data, l_nb_elem);
l_tccp = p_tcp->tccps;
l_current_offset_data = l_offset_data;
for (i = 0; i < p_image->numcomps; ++i) {
l_tccp->m_dc_level_shift = (OPJ_INT32) * (l_current_offset_data++);
++l_tccp;
}
opj_free(l_offset_data);
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_cbd(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 i;
OPJ_UINT32 l_cbd_size;
OPJ_BYTE * l_current_data = 00;
opj_image_t *l_image = 00;
opj_image_comp_t * l_comp = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_image = p_j2k->m_private_image;
l_cbd_size = 6 + p_j2k->m_private_image->numcomps;
if (l_cbd_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_cbd_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write CBD marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_cbd_size;
}
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_data, J2K_MS_CBD, 2); /* CBD */
l_current_data += 2;
opj_write_bytes(l_current_data, l_cbd_size - 2, 2); /* L_CBD */
l_current_data += 2;
opj_write_bytes(l_current_data, l_image->numcomps, 2); /* Ncbd */
l_current_data += 2;
l_comp = l_image->comps;
for (i = 0; i < l_image->numcomps; ++i) {
opj_write_bytes(l_current_data, (l_comp->sgnd << 7) | (l_comp->prec - 1),
1); /* Component bit depth */
++l_current_data;
++l_comp;
}
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_cbd_size,
p_manager) != l_cbd_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a CBD marker (Component bit depth definition)
* @param p_header_data the data contained in the CBD box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the CBD marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_cbd(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_nb_comp, l_num_comp;
OPJ_UINT32 l_comp_def;
OPJ_UINT32 i;
opj_image_comp_t * l_comp = 00;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_num_comp = p_j2k->m_private_image->numcomps;
if (p_header_size != (p_j2k->m_private_image->numcomps + 2)) {
opj_event_msg(p_manager, EVT_ERROR, "Crror reading CBD marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data, &l_nb_comp,
2); /* Ncbd */
p_header_data += 2;
if (l_nb_comp != l_num_comp) {
opj_event_msg(p_manager, EVT_ERROR, "Crror reading CBD marker\n");
return OPJ_FALSE;
}
l_comp = p_j2k->m_private_image->comps;
for (i = 0; i < l_num_comp; ++i) {
opj_read_bytes(p_header_data, &l_comp_def,
1); /* Component bit depth */
++p_header_data;
l_comp->sgnd = (l_comp_def >> 7) & 1;
l_comp->prec = (l_comp_def & 0x7f) + 1;
if (l_comp->prec > 31) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid values for comp = %d : prec=%u (should be between 1 and 38 according to the JPEG2000 norm. OpenJpeg only supports up to 31)\n",
i, l_comp->prec);
return OPJ_FALSE;
}
++l_comp;
}
return OPJ_TRUE;
}
/* ----------------------------------------------------------------------- */
/* J2K / JPT decoder interface */
/* ----------------------------------------------------------------------- */
void opj_j2k_setup_decoder(opj_j2k_t *j2k, opj_dparameters_t *parameters)
{
if (j2k && parameters) {
j2k->m_cp.m_specific_param.m_dec.m_layer = parameters->cp_layer;
j2k->m_cp.m_specific_param.m_dec.m_reduce = parameters->cp_reduce;
j2k->dump_state = (parameters->flags & OPJ_DPARAMETERS_DUMP_FLAG);
#ifdef USE_JPWL
j2k->m_cp.correct = parameters->jpwl_correct;
j2k->m_cp.exp_comps = parameters->jpwl_exp_comps;
j2k->m_cp.max_tiles = parameters->jpwl_max_tiles;
#endif /* USE_JPWL */
}
}
OPJ_BOOL opj_j2k_set_threads(opj_j2k_t *j2k, OPJ_UINT32 num_threads)
{
if (opj_has_thread_support()) {
opj_thread_pool_destroy(j2k->m_tp);
j2k->m_tp = NULL;
if (num_threads <= (OPJ_UINT32)INT_MAX) {
j2k->m_tp = opj_thread_pool_create((int)num_threads);
}
if (j2k->m_tp == NULL) {
j2k->m_tp = opj_thread_pool_create(0);
return OPJ_FALSE;
}
return OPJ_TRUE;
}
return OPJ_FALSE;
}
static int opj_j2k_get_default_thread_count()
{
const char* num_threads = getenv("OPJ_NUM_THREADS");
if (num_threads == NULL || !opj_has_thread_support()) {
return 0;
}
if (strcmp(num_threads, "ALL_CPUS") == 0) {
return opj_get_num_cpus();
}
return atoi(num_threads);
}
/* ----------------------------------------------------------------------- */
/* J2K encoder interface */
/* ----------------------------------------------------------------------- */
opj_j2k_t* opj_j2k_create_compress(void)
{
opj_j2k_t *l_j2k = (opj_j2k_t*) opj_calloc(1, sizeof(opj_j2k_t));
if (!l_j2k) {
return NULL;
}
l_j2k->m_is_decoder = 0;
l_j2k->m_cp.m_is_decoder = 0;
l_j2k->m_specific_param.m_encoder.m_header_tile_data = (OPJ_BYTE *) opj_malloc(
OPJ_J2K_DEFAULT_HEADER_SIZE);
if (! l_j2k->m_specific_param.m_encoder.m_header_tile_data) {
opj_j2k_destroy(l_j2k);
return NULL;
}
l_j2k->m_specific_param.m_encoder.m_header_tile_data_size =
OPJ_J2K_DEFAULT_HEADER_SIZE;
/* validation list creation*/
l_j2k->m_validation_list = opj_procedure_list_create();
if (! l_j2k->m_validation_list) {
opj_j2k_destroy(l_j2k);
return NULL;
}
/* execution list creation*/
l_j2k->m_procedure_list = opj_procedure_list_create();
if (! l_j2k->m_procedure_list) {
opj_j2k_destroy(l_j2k);
return NULL;
}
l_j2k->m_tp = opj_thread_pool_create(opj_j2k_get_default_thread_count());
if (!l_j2k->m_tp) {
l_j2k->m_tp = opj_thread_pool_create(0);
}
if (!l_j2k->m_tp) {
opj_j2k_destroy(l_j2k);
return NULL;
}
return l_j2k;
}
static int opj_j2k_initialise_4K_poc(opj_poc_t *POC, int numres)
{
POC[0].tile = 1;
POC[0].resno0 = 0;
POC[0].compno0 = 0;
POC[0].layno1 = 1;
POC[0].resno1 = (OPJ_UINT32)(numres - 1);
POC[0].compno1 = 3;
POC[0].prg1 = OPJ_CPRL;
POC[1].tile = 1;
POC[1].resno0 = (OPJ_UINT32)(numres - 1);
POC[1].compno0 = 0;
POC[1].layno1 = 1;
POC[1].resno1 = (OPJ_UINT32)numres;
POC[1].compno1 = 3;
POC[1].prg1 = OPJ_CPRL;
return 2;
}
static void opj_j2k_set_cinema_parameters(opj_cparameters_t *parameters,
opj_image_t *image, opj_event_mgr_t *p_manager)
{
/* Configure cinema parameters */
int i;
/* No tiling */
parameters->tile_size_on = OPJ_FALSE;
parameters->cp_tdx = 1;
parameters->cp_tdy = 1;
/* One tile part for each component */
parameters->tp_flag = 'C';
parameters->tp_on = 1;
/* Tile and Image shall be at (0,0) */
parameters->cp_tx0 = 0;
parameters->cp_ty0 = 0;
parameters->image_offset_x0 = 0;
parameters->image_offset_y0 = 0;
/* Codeblock size= 32*32 */
parameters->cblockw_init = 32;
parameters->cblockh_init = 32;
/* Codeblock style: no mode switch enabled */
parameters->mode = 0;
/* No ROI */
parameters->roi_compno = -1;
/* No subsampling */
parameters->subsampling_dx = 1;
parameters->subsampling_dy = 1;
/* 9-7 transform */
parameters->irreversible = 1;
/* Number of layers */
if (parameters->tcp_numlayers > 1) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
"1 single quality layer"
"-> Number of layers forced to 1 (rather than %d)\n"
"-> Rate of the last layer (%3.1f) will be used",
parameters->tcp_numlayers,
parameters->tcp_rates[parameters->tcp_numlayers - 1]);
parameters->tcp_rates[0] = parameters->tcp_rates[parameters->tcp_numlayers - 1];
parameters->tcp_numlayers = 1;
}
/* Resolution levels */
switch (parameters->rsiz) {
case OPJ_PROFILE_CINEMA_2K:
if (parameters->numresolution > 6) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 (2k dc profile) requires:\n"
"Number of decomposition levels <= 5\n"
"-> Number of decomposition levels forced to 5 (rather than %d)\n",
parameters->numresolution + 1);
parameters->numresolution = 6;
}
break;
case OPJ_PROFILE_CINEMA_4K:
if (parameters->numresolution < 2) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-4 (4k dc profile) requires:\n"
"Number of decomposition levels >= 1 && <= 6\n"
"-> Number of decomposition levels forced to 1 (rather than %d)\n",
parameters->numresolution + 1);
parameters->numresolution = 1;
} else if (parameters->numresolution > 7) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-4 (4k dc profile) requires:\n"
"Number of decomposition levels >= 1 && <= 6\n"
"-> Number of decomposition levels forced to 6 (rather than %d)\n",
parameters->numresolution + 1);
parameters->numresolution = 7;
}
break;
default :
break;
}
/* Precincts */
parameters->csty |= 0x01;
if (parameters->numresolution == 1) {
parameters->res_spec = 1;
parameters->prcw_init[0] = 128;
parameters->prch_init[0] = 128;
} else {
parameters->res_spec = parameters->numresolution - 1;
for (i = 0; i < parameters->res_spec; i++) {
parameters->prcw_init[i] = 256;
parameters->prch_init[i] = 256;
}
}
/* The progression order shall be CPRL */
parameters->prog_order = OPJ_CPRL;
/* Progression order changes for 4K, disallowed for 2K */
if (parameters->rsiz == OPJ_PROFILE_CINEMA_4K) {
parameters->numpocs = (OPJ_UINT32)opj_j2k_initialise_4K_poc(parameters->POC,
parameters->numresolution);
} else {
parameters->numpocs = 0;
}
/* Limited bit-rate */
parameters->cp_disto_alloc = 1;
if (parameters->max_cs_size <= 0) {
/* No rate has been introduced, 24 fps is assumed */
parameters->max_cs_size = OPJ_CINEMA_24_CS;
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
"Maximum 1302083 compressed bytes @ 24fps\n"
"As no rate has been given, this limit will be used.\n");
} else if (parameters->max_cs_size > OPJ_CINEMA_24_CS) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
"Maximum 1302083 compressed bytes @ 24fps\n"
"-> Specified rate exceeds this limit. Rate will be forced to 1302083 bytes.\n");
parameters->max_cs_size = OPJ_CINEMA_24_CS;
}
if (parameters->max_comp_size <= 0) {
/* No rate has been introduced, 24 fps is assumed */
parameters->max_comp_size = OPJ_CINEMA_24_COMP;
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
"Maximum 1041666 compressed bytes @ 24fps\n"
"As no rate has been given, this limit will be used.\n");
} else if (parameters->max_comp_size > OPJ_CINEMA_24_COMP) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
"Maximum 1041666 compressed bytes @ 24fps\n"
"-> Specified rate exceeds this limit. Rate will be forced to 1041666 bytes.\n");
parameters->max_comp_size = OPJ_CINEMA_24_COMP;
}
parameters->tcp_rates[0] = (OPJ_FLOAT32)(image->numcomps * image->comps[0].w *
image->comps[0].h * image->comps[0].prec) /
(OPJ_FLOAT32)(((OPJ_UINT32)parameters->max_cs_size) * 8 * image->comps[0].dx *
image->comps[0].dy);
}
static OPJ_BOOL opj_j2k_is_cinema_compliant(opj_image_t *image, OPJ_UINT16 rsiz,
opj_event_mgr_t *p_manager)
{
OPJ_UINT32 i;
/* Number of components */
if (image->numcomps != 3) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 (2k dc profile) requires:\n"
"3 components"
"-> Number of components of input image (%d) is not compliant\n"
"-> Non-profile-3 codestream will be generated\n",
image->numcomps);
return OPJ_FALSE;
}
/* Bitdepth */
for (i = 0; i < image->numcomps; i++) {
if ((image->comps[i].bpp != 12) | (image->comps[i].sgnd)) {
char signed_str[] = "signed";
char unsigned_str[] = "unsigned";
char *tmp_str = image->comps[i].sgnd ? signed_str : unsigned_str;
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 (2k dc profile) requires:\n"
"Precision of each component shall be 12 bits unsigned"
"-> At least component %d of input image (%d bits, %s) is not compliant\n"
"-> Non-profile-3 codestream will be generated\n",
i, image->comps[i].bpp, tmp_str);
return OPJ_FALSE;
}
}
/* Image size */
switch (rsiz) {
case OPJ_PROFILE_CINEMA_2K:
if (((image->comps[0].w > 2048) | (image->comps[0].h > 1080))) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 (2k dc profile) requires:\n"
"width <= 2048 and height <= 1080\n"
"-> Input image size %d x %d is not compliant\n"
"-> Non-profile-3 codestream will be generated\n",
image->comps[0].w, image->comps[0].h);
return OPJ_FALSE;
}
break;
case OPJ_PROFILE_CINEMA_4K:
if (((image->comps[0].w > 4096) | (image->comps[0].h > 2160))) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-4 (4k dc profile) requires:\n"
"width <= 4096 and height <= 2160\n"
"-> Image size %d x %d is not compliant\n"
"-> Non-profile-4 codestream will be generated\n",
image->comps[0].w, image->comps[0].h);
return OPJ_FALSE;
}
break;
default :
break;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_setup_encoder(opj_j2k_t *p_j2k,
opj_cparameters_t *parameters,
opj_image_t *image,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 i, j, tileno, numpocs_tile;
opj_cp_t *cp = 00;
if (!p_j2k || !parameters || ! image) {
return OPJ_FALSE;
}
if ((parameters->numresolution <= 0) ||
(parameters->numresolution > OPJ_J2K_MAXRLVLS)) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid number of resolutions : %d not in range [1,%d]\n",
parameters->numresolution, OPJ_J2K_MAXRLVLS);
return OPJ_FALSE;
}
/* keep a link to cp so that we can destroy it later in j2k_destroy_compress */
cp = &(p_j2k->m_cp);
/* set default values for cp */
cp->tw = 1;
cp->th = 1;
/* FIXME ADE: to be removed once deprecated cp_cinema and cp_rsiz have been removed */
if (parameters->rsiz ==
OPJ_PROFILE_NONE) { /* consider deprecated fields only if RSIZ has not been set */
OPJ_BOOL deprecated_used = OPJ_FALSE;
switch (parameters->cp_cinema) {
case OPJ_CINEMA2K_24:
parameters->rsiz = OPJ_PROFILE_CINEMA_2K;
parameters->max_cs_size = OPJ_CINEMA_24_CS;
parameters->max_comp_size = OPJ_CINEMA_24_COMP;
deprecated_used = OPJ_TRUE;
break;
case OPJ_CINEMA2K_48:
parameters->rsiz = OPJ_PROFILE_CINEMA_2K;
parameters->max_cs_size = OPJ_CINEMA_48_CS;
parameters->max_comp_size = OPJ_CINEMA_48_COMP;
deprecated_used = OPJ_TRUE;
break;
case OPJ_CINEMA4K_24:
parameters->rsiz = OPJ_PROFILE_CINEMA_4K;
parameters->max_cs_size = OPJ_CINEMA_24_CS;
parameters->max_comp_size = OPJ_CINEMA_24_COMP;
deprecated_used = OPJ_TRUE;
break;
case OPJ_OFF:
default:
break;
}
switch (parameters->cp_rsiz) {
case OPJ_CINEMA2K:
parameters->rsiz = OPJ_PROFILE_CINEMA_2K;
deprecated_used = OPJ_TRUE;
break;
case OPJ_CINEMA4K:
parameters->rsiz = OPJ_PROFILE_CINEMA_4K;
deprecated_used = OPJ_TRUE;
break;
case OPJ_MCT:
parameters->rsiz = OPJ_PROFILE_PART2 | OPJ_EXTENSION_MCT;
deprecated_used = OPJ_TRUE;
case OPJ_STD_RSIZ:
default:
break;
}
if (deprecated_used) {
opj_event_msg(p_manager, EVT_WARNING,
"Deprecated fields cp_cinema or cp_rsiz are used\n"
"Please consider using only the rsiz field\n"
"See openjpeg.h documentation for more details\n");
}
}
/* If no explicit layers are provided, use lossless settings */
if (parameters->tcp_numlayers == 0) {
parameters->tcp_numlayers = 1;
parameters->cp_disto_alloc = 1;
parameters->tcp_rates[0] = 0;
}
/* see if max_codestream_size does limit input rate */
if (parameters->max_cs_size <= 0) {
if (parameters->tcp_rates[parameters->tcp_numlayers - 1] > 0) {
OPJ_FLOAT32 temp_size;
temp_size = (OPJ_FLOAT32)(image->numcomps * image->comps[0].w *
image->comps[0].h * image->comps[0].prec) /
(parameters->tcp_rates[parameters->tcp_numlayers - 1] * 8 *
(OPJ_FLOAT32)image->comps[0].dx * (OPJ_FLOAT32)image->comps[0].dy);
parameters->max_cs_size = (int) floor(temp_size);
} else {
parameters->max_cs_size = 0;
}
} else {
OPJ_FLOAT32 temp_rate;
OPJ_BOOL cap = OPJ_FALSE;
temp_rate = (OPJ_FLOAT32)(image->numcomps * image->comps[0].w *
image->comps[0].h * image->comps[0].prec) /
(OPJ_FLOAT32)(((OPJ_UINT32)parameters->max_cs_size) * 8 * image->comps[0].dx *
image->comps[0].dy);
for (i = 0; i < (OPJ_UINT32) parameters->tcp_numlayers; i++) {
if (parameters->tcp_rates[i] < temp_rate) {
parameters->tcp_rates[i] = temp_rate;
cap = OPJ_TRUE;
}
}
if (cap) {
opj_event_msg(p_manager, EVT_WARNING,
"The desired maximum codestream size has limited\n"
"at least one of the desired quality layers\n");
}
}
/* Manage profiles and applications and set RSIZ */
/* set cinema parameters if required */
if (OPJ_IS_CINEMA(parameters->rsiz)) {
if ((parameters->rsiz == OPJ_PROFILE_CINEMA_S2K)
|| (parameters->rsiz == OPJ_PROFILE_CINEMA_S4K)) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Scalable Digital Cinema profiles not yet supported\n");
parameters->rsiz = OPJ_PROFILE_NONE;
} else {
opj_j2k_set_cinema_parameters(parameters, image, p_manager);
if (!opj_j2k_is_cinema_compliant(image, parameters->rsiz, p_manager)) {
parameters->rsiz = OPJ_PROFILE_NONE;
}
}
} else if (OPJ_IS_STORAGE(parameters->rsiz)) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Long Term Storage profile not yet supported\n");
parameters->rsiz = OPJ_PROFILE_NONE;
} else if (OPJ_IS_BROADCAST(parameters->rsiz)) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Broadcast profiles not yet supported\n");
parameters->rsiz = OPJ_PROFILE_NONE;
} else if (OPJ_IS_IMF(parameters->rsiz)) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 IMF profiles not yet supported\n");
parameters->rsiz = OPJ_PROFILE_NONE;
} else if (OPJ_IS_PART2(parameters->rsiz)) {
if (parameters->rsiz == ((OPJ_PROFILE_PART2) | (OPJ_EXTENSION_NONE))) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Part-2 profile defined\n"
"but no Part-2 extension enabled.\n"
"Profile set to NONE.\n");
parameters->rsiz = OPJ_PROFILE_NONE;
} else if (parameters->rsiz != ((OPJ_PROFILE_PART2) | (OPJ_EXTENSION_MCT))) {
opj_event_msg(p_manager, EVT_WARNING,
"Unsupported Part-2 extension enabled\n"
"Profile set to NONE.\n");
parameters->rsiz = OPJ_PROFILE_NONE;
}
}
/*
copy user encoding parameters
*/
cp->m_specific_param.m_enc.m_max_comp_size = (OPJ_UINT32)
parameters->max_comp_size;
cp->rsiz = parameters->rsiz;
cp->m_specific_param.m_enc.m_disto_alloc = (OPJ_UINT32)
parameters->cp_disto_alloc & 1u;
cp->m_specific_param.m_enc.m_fixed_alloc = (OPJ_UINT32)
parameters->cp_fixed_alloc & 1u;
cp->m_specific_param.m_enc.m_fixed_quality = (OPJ_UINT32)
parameters->cp_fixed_quality & 1u;
/* mod fixed_quality */
if (parameters->cp_fixed_alloc && parameters->cp_matrice) {
size_t array_size = (size_t)parameters->tcp_numlayers *
(size_t)parameters->numresolution * 3 * sizeof(OPJ_INT32);
cp->m_specific_param.m_enc.m_matrice = (OPJ_INT32 *) opj_malloc(array_size);
if (!cp->m_specific_param.m_enc.m_matrice) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate copy of user encoding parameters matrix \n");
return OPJ_FALSE;
}
memcpy(cp->m_specific_param.m_enc.m_matrice, parameters->cp_matrice,
array_size);
}
/* tiles */
cp->tdx = (OPJ_UINT32)parameters->cp_tdx;
cp->tdy = (OPJ_UINT32)parameters->cp_tdy;
/* tile offset */
cp->tx0 = (OPJ_UINT32)parameters->cp_tx0;
cp->ty0 = (OPJ_UINT32)parameters->cp_ty0;
/* comment string */
if (parameters->cp_comment) {
cp->comment = (char*)opj_malloc(strlen(parameters->cp_comment) + 1U);
if (!cp->comment) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate copy of comment string\n");
return OPJ_FALSE;
}
strcpy(cp->comment, parameters->cp_comment);
} else {
/* Create default comment for codestream */
const char comment[] = "Created by OpenJPEG version ";
const size_t clen = strlen(comment);
const char *version = opj_version();
/* UniPG>> */
#ifdef USE_JPWL
cp->comment = (char*)opj_malloc(clen + strlen(version) + 11);
if (!cp->comment) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate comment string\n");
return OPJ_FALSE;
}
sprintf(cp->comment, "%s%s with JPWL", comment, version);
#else
cp->comment = (char*)opj_malloc(clen + strlen(version) + 1);
if (!cp->comment) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate comment string\n");
return OPJ_FALSE;
}
sprintf(cp->comment, "%s%s", comment, version);
#endif
/* <<UniPG */
}
/*
calculate other encoding parameters
*/
if (parameters->tile_size_on) {
cp->tw = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)(image->x1 - cp->tx0),
(OPJ_INT32)cp->tdx);
cp->th = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)(image->y1 - cp->ty0),
(OPJ_INT32)cp->tdy);
} else {
cp->tdx = image->x1 - cp->tx0;
cp->tdy = image->y1 - cp->ty0;
}
if (parameters->tp_on) {
cp->m_specific_param.m_enc.m_tp_flag = (OPJ_BYTE)parameters->tp_flag;
cp->m_specific_param.m_enc.m_tp_on = 1;
}
#ifdef USE_JPWL
/*
calculate JPWL encoding parameters
*/
if (parameters->jpwl_epc_on) {
OPJ_INT32 i;
/* set JPWL on */
cp->epc_on = OPJ_TRUE;
cp->info_on = OPJ_FALSE; /* no informative technique */
/* set EPB on */
if ((parameters->jpwl_hprot_MH > 0) || (parameters->jpwl_hprot_TPH[0] > 0)) {
cp->epb_on = OPJ_TRUE;
cp->hprot_MH = parameters->jpwl_hprot_MH;
for (i = 0; i < JPWL_MAX_NO_TILESPECS; i++) {
cp->hprot_TPH_tileno[i] = parameters->jpwl_hprot_TPH_tileno[i];
cp->hprot_TPH[i] = parameters->jpwl_hprot_TPH[i];
}
/* if tile specs are not specified, copy MH specs */
if (cp->hprot_TPH[0] == -1) {
cp->hprot_TPH_tileno[0] = 0;
cp->hprot_TPH[0] = parameters->jpwl_hprot_MH;
}
for (i = 0; i < JPWL_MAX_NO_PACKSPECS; i++) {
cp->pprot_tileno[i] = parameters->jpwl_pprot_tileno[i];
cp->pprot_packno[i] = parameters->jpwl_pprot_packno[i];
cp->pprot[i] = parameters->jpwl_pprot[i];
}
}
/* set ESD writing */
if ((parameters->jpwl_sens_size == 1) || (parameters->jpwl_sens_size == 2)) {
cp->esd_on = OPJ_TRUE;
cp->sens_size = parameters->jpwl_sens_size;
cp->sens_addr = parameters->jpwl_sens_addr;
cp->sens_range = parameters->jpwl_sens_range;
cp->sens_MH = parameters->jpwl_sens_MH;
for (i = 0; i < JPWL_MAX_NO_TILESPECS; i++) {
cp->sens_TPH_tileno[i] = parameters->jpwl_sens_TPH_tileno[i];
cp->sens_TPH[i] = parameters->jpwl_sens_TPH[i];
}
}
/* always set RED writing to false: we are at the encoder */
cp->red_on = OPJ_FALSE;
} else {
cp->epc_on = OPJ_FALSE;
}
#endif /* USE_JPWL */
/* initialize the mutiple tiles */
/* ---------------------------- */
cp->tcps = (opj_tcp_t*) opj_calloc(cp->tw * cp->th, sizeof(opj_tcp_t));
if (!cp->tcps) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate tile coding parameters\n");
return OPJ_FALSE;
}
if (parameters->numpocs) {
/* initialisation of POC */
opj_j2k_check_poc_val(parameters->POC, parameters->numpocs,
(OPJ_UINT32)parameters->numresolution, image->numcomps,
(OPJ_UINT32)parameters->tcp_numlayers, p_manager);
/* TODO MSD use the return value*/
}
for (tileno = 0; tileno < cp->tw * cp->th; tileno++) {
opj_tcp_t *tcp = &cp->tcps[tileno];
tcp->numlayers = (OPJ_UINT32)parameters->tcp_numlayers;
for (j = 0; j < tcp->numlayers; j++) {
if (OPJ_IS_CINEMA(cp->rsiz)) {
if (cp->m_specific_param.m_enc.m_fixed_quality) {
tcp->distoratio[j] = parameters->tcp_distoratio[j];
}
tcp->rates[j] = parameters->tcp_rates[j];
} else {
if (cp->m_specific_param.m_enc.m_fixed_quality) { /* add fixed_quality */
tcp->distoratio[j] = parameters->tcp_distoratio[j];
} else {
tcp->rates[j] = parameters->tcp_rates[j];
}
}
}
tcp->csty = (OPJ_UINT32)parameters->csty;
tcp->prg = parameters->prog_order;
tcp->mct = (OPJ_UINT32)parameters->tcp_mct;
numpocs_tile = 0;
tcp->POC = 0;
if (parameters->numpocs) {
/* initialisation of POC */
tcp->POC = 1;
for (i = 0; i < parameters->numpocs; i++) {
if (tileno + 1 == parameters->POC[i].tile) {
opj_poc_t *tcp_poc = &tcp->pocs[numpocs_tile];
tcp_poc->resno0 = parameters->POC[numpocs_tile].resno0;
tcp_poc->compno0 = parameters->POC[numpocs_tile].compno0;
tcp_poc->layno1 = parameters->POC[numpocs_tile].layno1;
tcp_poc->resno1 = parameters->POC[numpocs_tile].resno1;
tcp_poc->compno1 = parameters->POC[numpocs_tile].compno1;
tcp_poc->prg1 = parameters->POC[numpocs_tile].prg1;
tcp_poc->tile = parameters->POC[numpocs_tile].tile;
numpocs_tile++;
}
}
tcp->numpocs = numpocs_tile - 1 ;
} else {
tcp->numpocs = 0;
}
tcp->tccps = (opj_tccp_t*) opj_calloc(image->numcomps, sizeof(opj_tccp_t));
if (!tcp->tccps) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate tile component coding parameters\n");
return OPJ_FALSE;
}
if (parameters->mct_data) {
OPJ_UINT32 lMctSize = image->numcomps * image->numcomps * (OPJ_UINT32)sizeof(
OPJ_FLOAT32);
OPJ_FLOAT32 * lTmpBuf = (OPJ_FLOAT32*)opj_malloc(lMctSize);
OPJ_INT32 * l_dc_shift = (OPJ_INT32 *)((OPJ_BYTE *) parameters->mct_data +
lMctSize);
if (!lTmpBuf) {
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate temp buffer\n");
return OPJ_FALSE;
}
tcp->mct = 2;
tcp->m_mct_coding_matrix = (OPJ_FLOAT32*)opj_malloc(lMctSize);
if (! tcp->m_mct_coding_matrix) {
opj_free(lTmpBuf);
lTmpBuf = NULL;
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate encoder MCT coding matrix \n");
return OPJ_FALSE;
}
memcpy(tcp->m_mct_coding_matrix, parameters->mct_data, lMctSize);
memcpy(lTmpBuf, parameters->mct_data, lMctSize);
tcp->m_mct_decoding_matrix = (OPJ_FLOAT32*)opj_malloc(lMctSize);
if (! tcp->m_mct_decoding_matrix) {
opj_free(lTmpBuf);
lTmpBuf = NULL;
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate encoder MCT decoding matrix \n");
return OPJ_FALSE;
}
if (opj_matrix_inversion_f(lTmpBuf, (tcp->m_mct_decoding_matrix),
image->numcomps) == OPJ_FALSE) {
opj_free(lTmpBuf);
lTmpBuf = NULL;
opj_event_msg(p_manager, EVT_ERROR,
"Failed to inverse encoder MCT decoding matrix \n");
return OPJ_FALSE;
}
tcp->mct_norms = (OPJ_FLOAT64*)
opj_malloc(image->numcomps * sizeof(OPJ_FLOAT64));
if (! tcp->mct_norms) {
opj_free(lTmpBuf);
lTmpBuf = NULL;
opj_event_msg(p_manager, EVT_ERROR,
"Not enough memory to allocate encoder MCT norms \n");
return OPJ_FALSE;
}
opj_calculate_norms(tcp->mct_norms, image->numcomps,
tcp->m_mct_decoding_matrix);
opj_free(lTmpBuf);
for (i = 0; i < image->numcomps; i++) {
opj_tccp_t *tccp = &tcp->tccps[i];
tccp->m_dc_level_shift = l_dc_shift[i];
}
if (opj_j2k_setup_mct_encoding(tcp, image) == OPJ_FALSE) {
/* free will be handled by opj_j2k_destroy */
opj_event_msg(p_manager, EVT_ERROR, "Failed to setup j2k mct encoding\n");
return OPJ_FALSE;
}
} else {
if (tcp->mct == 1 && image->numcomps >= 3) { /* RGB->YCC MCT is enabled */
if ((image->comps[0].dx != image->comps[1].dx) ||
(image->comps[0].dx != image->comps[2].dx) ||
(image->comps[0].dy != image->comps[1].dy) ||
(image->comps[0].dy != image->comps[2].dy)) {
opj_event_msg(p_manager, EVT_WARNING,
"Cannot perform MCT on components with different sizes. Disabling MCT.\n");
tcp->mct = 0;
}
}
for (i = 0; i < image->numcomps; i++) {
opj_tccp_t *tccp = &tcp->tccps[i];
opj_image_comp_t * l_comp = &(image->comps[i]);
if (! l_comp->sgnd) {
tccp->m_dc_level_shift = 1 << (l_comp->prec - 1);
}
}
}
for (i = 0; i < image->numcomps; i++) {
opj_tccp_t *tccp = &tcp->tccps[i];
tccp->csty = parameters->csty &
0x01; /* 0 => one precinct || 1 => custom precinct */
tccp->numresolutions = (OPJ_UINT32)parameters->numresolution;
tccp->cblkw = (OPJ_UINT32)opj_int_floorlog2(parameters->cblockw_init);
tccp->cblkh = (OPJ_UINT32)opj_int_floorlog2(parameters->cblockh_init);
tccp->cblksty = (OPJ_UINT32)parameters->mode;
tccp->qmfbid = parameters->irreversible ? 0 : 1;
tccp->qntsty = parameters->irreversible ? J2K_CCP_QNTSTY_SEQNT :
J2K_CCP_QNTSTY_NOQNT;
tccp->numgbits = 2;
if ((OPJ_INT32)i == parameters->roi_compno) {
tccp->roishift = parameters->roi_shift;
} else {
tccp->roishift = 0;
}
if (parameters->csty & J2K_CCP_CSTY_PRT) {
OPJ_INT32 p = 0, it_res;
assert(tccp->numresolutions > 0);
for (it_res = (OPJ_INT32)tccp->numresolutions - 1; it_res >= 0; it_res--) {
if (p < parameters->res_spec) {
if (parameters->prcw_init[p] < 1) {
tccp->prcw[it_res] = 1;
} else {
tccp->prcw[it_res] = (OPJ_UINT32)opj_int_floorlog2(parameters->prcw_init[p]);
}
if (parameters->prch_init[p] < 1) {
tccp->prch[it_res] = 1;
} else {
tccp->prch[it_res] = (OPJ_UINT32)opj_int_floorlog2(parameters->prch_init[p]);
}
} else {
OPJ_INT32 res_spec = parameters->res_spec;
OPJ_INT32 size_prcw = 0;
OPJ_INT32 size_prch = 0;
assert(res_spec > 0); /* issue 189 */
size_prcw = parameters->prcw_init[res_spec - 1] >> (p - (res_spec - 1));
size_prch = parameters->prch_init[res_spec - 1] >> (p - (res_spec - 1));
if (size_prcw < 1) {
tccp->prcw[it_res] = 1;
} else {
tccp->prcw[it_res] = (OPJ_UINT32)opj_int_floorlog2(size_prcw);
}
if (size_prch < 1) {
tccp->prch[it_res] = 1;
} else {
tccp->prch[it_res] = (OPJ_UINT32)opj_int_floorlog2(size_prch);
}
}
p++;
/*printf("\nsize precinct for level %d : %d,%d\n", it_res,tccp->prcw[it_res], tccp->prch[it_res]); */
} /*end for*/
} else {
for (j = 0; j < tccp->numresolutions; j++) {
tccp->prcw[j] = 15;
tccp->prch[j] = 15;
}
}
opj_dwt_calc_explicit_stepsizes(tccp, image->comps[i].prec);
}
}
if (parameters->mct_data) {
opj_free(parameters->mct_data);
parameters->mct_data = 00;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_add_mhmarker(opj_codestream_index_t *cstr_index,
OPJ_UINT32 type, OPJ_OFF_T pos, OPJ_UINT32 len)
{
assert(cstr_index != 00);
/* expand the list? */
if ((cstr_index->marknum + 1) > cstr_index->maxmarknum) {
opj_marker_info_t *new_marker;
cstr_index->maxmarknum = (OPJ_UINT32)(100 + (OPJ_FLOAT32)
cstr_index->maxmarknum);
new_marker = (opj_marker_info_t *) opj_realloc(cstr_index->marker,
cstr_index->maxmarknum * sizeof(opj_marker_info_t));
if (! new_marker) {
opj_free(cstr_index->marker);
cstr_index->marker = NULL;
cstr_index->maxmarknum = 0;
cstr_index->marknum = 0;
/* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add mh marker\n"); */
return OPJ_FALSE;
}
cstr_index->marker = new_marker;
}
/* add the marker */
cstr_index->marker[cstr_index->marknum].type = (OPJ_UINT16)type;
cstr_index->marker[cstr_index->marknum].pos = (OPJ_INT32)pos;
cstr_index->marker[cstr_index->marknum].len = (OPJ_INT32)len;
cstr_index->marknum++;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_add_tlmarker(OPJ_UINT32 tileno,
opj_codestream_index_t *cstr_index, OPJ_UINT32 type, OPJ_OFF_T pos,
OPJ_UINT32 len)
{
assert(cstr_index != 00);
assert(cstr_index->tile_index != 00);
/* expand the list? */
if ((cstr_index->tile_index[tileno].marknum + 1) >
cstr_index->tile_index[tileno].maxmarknum) {
opj_marker_info_t *new_marker;
cstr_index->tile_index[tileno].maxmarknum = (OPJ_UINT32)(100 +
(OPJ_FLOAT32) cstr_index->tile_index[tileno].maxmarknum);
new_marker = (opj_marker_info_t *) opj_realloc(
cstr_index->tile_index[tileno].marker,
cstr_index->tile_index[tileno].maxmarknum * sizeof(opj_marker_info_t));
if (! new_marker) {
opj_free(cstr_index->tile_index[tileno].marker);
cstr_index->tile_index[tileno].marker = NULL;
cstr_index->tile_index[tileno].maxmarknum = 0;
cstr_index->tile_index[tileno].marknum = 0;
/* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add tl marker\n"); */
return OPJ_FALSE;
}
cstr_index->tile_index[tileno].marker = new_marker;
}
/* add the marker */
cstr_index->tile_index[tileno].marker[cstr_index->tile_index[tileno].marknum].type
= (OPJ_UINT16)type;
cstr_index->tile_index[tileno].marker[cstr_index->tile_index[tileno].marknum].pos
= (OPJ_INT32)pos;
cstr_index->tile_index[tileno].marker[cstr_index->tile_index[tileno].marknum].len
= (OPJ_INT32)len;
cstr_index->tile_index[tileno].marknum++;
if (type == J2K_MS_SOT) {
OPJ_UINT32 l_current_tile_part = cstr_index->tile_index[tileno].current_tpsno;
if (cstr_index->tile_index[tileno].tp_index) {
cstr_index->tile_index[tileno].tp_index[l_current_tile_part].start_pos = pos;
}
}
return OPJ_TRUE;
}
/*
* -----------------------------------------------------------------------
* -----------------------------------------------------------------------
* -----------------------------------------------------------------------
*/
OPJ_BOOL opj_j2k_end_decompress(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
(void)p_j2k;
(void)p_stream;
(void)p_manager;
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_read_header(opj_stream_private_t *p_stream,
opj_j2k_t* p_j2k,
opj_image_t** p_image,
opj_event_mgr_t* p_manager)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
/* create an empty image header */
p_j2k->m_private_image = opj_image_create0();
if (! p_j2k->m_private_image) {
return OPJ_FALSE;
}
/* customization of the validation */
if (! opj_j2k_setup_decoding_validation(p_j2k, p_manager)) {
opj_image_destroy(p_j2k->m_private_image);
p_j2k->m_private_image = NULL;
return OPJ_FALSE;
}
/* validation of the parameters codec */
if (! opj_j2k_exec(p_j2k, p_j2k->m_validation_list, p_stream, p_manager)) {
opj_image_destroy(p_j2k->m_private_image);
p_j2k->m_private_image = NULL;
return OPJ_FALSE;
}
/* customization of the encoding */
if (! opj_j2k_setup_header_reading(p_j2k, p_manager)) {
opj_image_destroy(p_j2k->m_private_image);
p_j2k->m_private_image = NULL;
return OPJ_FALSE;
}
/* read header */
if (! opj_j2k_exec(p_j2k, p_j2k->m_procedure_list, p_stream, p_manager)) {
opj_image_destroy(p_j2k->m_private_image);
p_j2k->m_private_image = NULL;
return OPJ_FALSE;
}
*p_image = opj_image_create0();
if (!(*p_image)) {
return OPJ_FALSE;
}
/* Copy codestream image information to the output image */
opj_copy_image_header(p_j2k->m_private_image, *p_image);
/*Allocate and initialize some elements of codestrem index*/
if (!opj_j2k_allocate_tile_element_cstr_index(p_j2k)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_setup_header_reading(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager)
{
/* preconditions*/
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_read_header_procedure, p_manager)) {
return OPJ_FALSE;
}
/* DEVELOPER CORNER, add your custom procedures */
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_copy_default_tcp_and_create_tcd, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_setup_decoding_validation(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager)
{
/* preconditions*/
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list,
(opj_procedure)opj_j2k_build_decoder, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list,
(opj_procedure)opj_j2k_decoding_validation, p_manager)) {
return OPJ_FALSE;
}
/* DEVELOPER CORNER, add your custom validation procedure */
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_mct_validation(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_BOOL l_is_valid = OPJ_TRUE;
OPJ_UINT32 i, j;
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_stream);
OPJ_UNUSED(p_manager);
if ((p_j2k->m_cp.rsiz & 0x8200) == 0x8200) {
OPJ_UINT32 l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
opj_tcp_t * l_tcp = p_j2k->m_cp.tcps;
for (i = 0; i < l_nb_tiles; ++i) {
if (l_tcp->mct == 2) {
opj_tccp_t * l_tccp = l_tcp->tccps;
l_is_valid &= (l_tcp->m_mct_coding_matrix != 00);
for (j = 0; j < p_j2k->m_private_image->numcomps; ++j) {
l_is_valid &= !(l_tccp->qmfbid & 1);
++l_tccp;
}
}
++l_tcp;
}
}
return l_is_valid;
}
OPJ_BOOL opj_j2k_setup_mct_encoding(opj_tcp_t * p_tcp, opj_image_t * p_image)
{
OPJ_UINT32 i;
OPJ_UINT32 l_indix = 1;
opj_mct_data_t * l_mct_deco_data = 00, * l_mct_offset_data = 00;
opj_simple_mcc_decorrelation_data_t * l_mcc_data;
OPJ_UINT32 l_mct_size, l_nb_elem;
OPJ_FLOAT32 * l_data, * l_current_data;
opj_tccp_t * l_tccp;
/* preconditions */
assert(p_tcp != 00);
if (p_tcp->mct != 2) {
return OPJ_TRUE;
}
if (p_tcp->m_mct_decoding_matrix) {
if (p_tcp->m_nb_mct_records == p_tcp->m_nb_max_mct_records) {
opj_mct_data_t *new_mct_records;
p_tcp->m_nb_max_mct_records += OPJ_J2K_MCT_DEFAULT_NB_RECORDS;
new_mct_records = (opj_mct_data_t *) opj_realloc(p_tcp->m_mct_records,
p_tcp->m_nb_max_mct_records * sizeof(opj_mct_data_t));
if (! new_mct_records) {
opj_free(p_tcp->m_mct_records);
p_tcp->m_mct_records = NULL;
p_tcp->m_nb_max_mct_records = 0;
p_tcp->m_nb_mct_records = 0;
/* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to setup mct encoding\n"); */
return OPJ_FALSE;
}
p_tcp->m_mct_records = new_mct_records;
l_mct_deco_data = p_tcp->m_mct_records + p_tcp->m_nb_mct_records;
memset(l_mct_deco_data, 0,
(p_tcp->m_nb_max_mct_records - p_tcp->m_nb_mct_records) * sizeof(
opj_mct_data_t));
}
l_mct_deco_data = p_tcp->m_mct_records + p_tcp->m_nb_mct_records;
if (l_mct_deco_data->m_data) {
opj_free(l_mct_deco_data->m_data);
l_mct_deco_data->m_data = 00;
}
l_mct_deco_data->m_index = l_indix++;
l_mct_deco_data->m_array_type = MCT_TYPE_DECORRELATION;
l_mct_deco_data->m_element_type = MCT_TYPE_FLOAT;
l_nb_elem = p_image->numcomps * p_image->numcomps;
l_mct_size = l_nb_elem * MCT_ELEMENT_SIZE[l_mct_deco_data->m_element_type];
l_mct_deco_data->m_data = (OPJ_BYTE*)opj_malloc(l_mct_size);
if (! l_mct_deco_data->m_data) {
return OPJ_FALSE;
}
j2k_mct_write_functions_from_float[l_mct_deco_data->m_element_type](
p_tcp->m_mct_decoding_matrix, l_mct_deco_data->m_data, l_nb_elem);
l_mct_deco_data->m_data_size = l_mct_size;
++p_tcp->m_nb_mct_records;
}
if (p_tcp->m_nb_mct_records == p_tcp->m_nb_max_mct_records) {
opj_mct_data_t *new_mct_records;
p_tcp->m_nb_max_mct_records += OPJ_J2K_MCT_DEFAULT_NB_RECORDS;
new_mct_records = (opj_mct_data_t *) opj_realloc(p_tcp->m_mct_records,
p_tcp->m_nb_max_mct_records * sizeof(opj_mct_data_t));
if (! new_mct_records) {
opj_free(p_tcp->m_mct_records);
p_tcp->m_mct_records = NULL;
p_tcp->m_nb_max_mct_records = 0;
p_tcp->m_nb_mct_records = 0;
/* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to setup mct encoding\n"); */
return OPJ_FALSE;
}
p_tcp->m_mct_records = new_mct_records;
l_mct_offset_data = p_tcp->m_mct_records + p_tcp->m_nb_mct_records;
memset(l_mct_offset_data, 0,
(p_tcp->m_nb_max_mct_records - p_tcp->m_nb_mct_records) * sizeof(
opj_mct_data_t));
if (l_mct_deco_data) {
l_mct_deco_data = l_mct_offset_data - 1;
}
}
l_mct_offset_data = p_tcp->m_mct_records + p_tcp->m_nb_mct_records;
if (l_mct_offset_data->m_data) {
opj_free(l_mct_offset_data->m_data);
l_mct_offset_data->m_data = 00;
}
l_mct_offset_data->m_index = l_indix++;
l_mct_offset_data->m_array_type = MCT_TYPE_OFFSET;
l_mct_offset_data->m_element_type = MCT_TYPE_FLOAT;
l_nb_elem = p_image->numcomps;
l_mct_size = l_nb_elem * MCT_ELEMENT_SIZE[l_mct_offset_data->m_element_type];
l_mct_offset_data->m_data = (OPJ_BYTE*)opj_malloc(l_mct_size);
if (! l_mct_offset_data->m_data) {
return OPJ_FALSE;
}
l_data = (OPJ_FLOAT32*)opj_malloc(l_nb_elem * sizeof(OPJ_FLOAT32));
if (! l_data) {
opj_free(l_mct_offset_data->m_data);
l_mct_offset_data->m_data = 00;
return OPJ_FALSE;
}
l_tccp = p_tcp->tccps;
l_current_data = l_data;
for (i = 0; i < l_nb_elem; ++i) {
*(l_current_data++) = (OPJ_FLOAT32)(l_tccp->m_dc_level_shift);
++l_tccp;
}
j2k_mct_write_functions_from_float[l_mct_offset_data->m_element_type](l_data,
l_mct_offset_data->m_data, l_nb_elem);
opj_free(l_data);
l_mct_offset_data->m_data_size = l_mct_size;
++p_tcp->m_nb_mct_records;
if (p_tcp->m_nb_mcc_records == p_tcp->m_nb_max_mcc_records) {
opj_simple_mcc_decorrelation_data_t *new_mcc_records;
p_tcp->m_nb_max_mcc_records += OPJ_J2K_MCT_DEFAULT_NB_RECORDS;
new_mcc_records = (opj_simple_mcc_decorrelation_data_t *) opj_realloc(
p_tcp->m_mcc_records, p_tcp->m_nb_max_mcc_records * sizeof(
opj_simple_mcc_decorrelation_data_t));
if (! new_mcc_records) {
opj_free(p_tcp->m_mcc_records);
p_tcp->m_mcc_records = NULL;
p_tcp->m_nb_max_mcc_records = 0;
p_tcp->m_nb_mcc_records = 0;
/* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to setup mct encoding\n"); */
return OPJ_FALSE;
}
p_tcp->m_mcc_records = new_mcc_records;
l_mcc_data = p_tcp->m_mcc_records + p_tcp->m_nb_mcc_records;
memset(l_mcc_data, 0, (p_tcp->m_nb_max_mcc_records - p_tcp->m_nb_mcc_records) *
sizeof(opj_simple_mcc_decorrelation_data_t));
}
l_mcc_data = p_tcp->m_mcc_records + p_tcp->m_nb_mcc_records;
l_mcc_data->m_decorrelation_array = l_mct_deco_data;
l_mcc_data->m_is_irreversible = 1;
l_mcc_data->m_nb_comps = p_image->numcomps;
l_mcc_data->m_index = l_indix++;
l_mcc_data->m_offset_array = l_mct_offset_data;
++p_tcp->m_nb_mcc_records;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_build_decoder(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
/* add here initialization of cp
copy paste of setup_decoder */
(void)p_j2k;
(void)p_stream;
(void)p_manager;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_build_encoder(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
/* add here initialization of cp
copy paste of setup_encoder */
(void)p_j2k;
(void)p_stream;
(void)p_manager;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_encoding_validation(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_BOOL l_is_valid = OPJ_TRUE;
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_stream);
/* STATE checking */
/* make sure the state is at 0 */
l_is_valid &= (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_NONE);
/* POINTER validation */
/* make sure a p_j2k codec is present */
l_is_valid &= (p_j2k->m_procedure_list != 00);
/* make sure a validation list is present */
l_is_valid &= (p_j2k->m_validation_list != 00);
/* ISO 15444-1:2004 states between 1 & 33 (0 -> 32) */
/* 33 (32) would always fail the check below (if a cast to 64bits was done) */
/* FIXME Shall we change OPJ_J2K_MAXRLVLS to 32 ? */
if ((p_j2k->m_cp.tcps->tccps->numresolutions <= 0) ||
(p_j2k->m_cp.tcps->tccps->numresolutions > 32)) {
opj_event_msg(p_manager, EVT_ERROR,
"Number of resolutions is too high in comparison to the size of tiles\n");
return OPJ_FALSE;
}
if ((p_j2k->m_cp.tdx) < (OPJ_UINT32)(1 <<
(p_j2k->m_cp.tcps->tccps->numresolutions - 1U))) {
opj_event_msg(p_manager, EVT_ERROR,
"Number of resolutions is too high in comparison to the size of tiles\n");
return OPJ_FALSE;
}
if ((p_j2k->m_cp.tdy) < (OPJ_UINT32)(1 <<
(p_j2k->m_cp.tcps->tccps->numresolutions - 1U))) {
opj_event_msg(p_manager, EVT_ERROR,
"Number of resolutions is too high in comparison to the size of tiles\n");
return OPJ_FALSE;
}
/* PARAMETER VALIDATION */
return l_is_valid;
}
static OPJ_BOOL opj_j2k_decoding_validation(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_BOOL l_is_valid = OPJ_TRUE;
/* preconditions*/
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_stream);
OPJ_UNUSED(p_manager);
/* STATE checking */
/* make sure the state is at 0 */
#ifdef TODO_MSD
l_is_valid &= (p_j2k->m_specific_param.m_decoder.m_state == J2K_DEC_STATE_NONE);
#endif
l_is_valid &= (p_j2k->m_specific_param.m_decoder.m_state == 0x0000);
/* POINTER validation */
/* make sure a p_j2k codec is present */
/* make sure a procedure list is present */
l_is_valid &= (p_j2k->m_procedure_list != 00);
/* make sure a validation list is present */
l_is_valid &= (p_j2k->m_validation_list != 00);
/* PARAMETER VALIDATION */
return l_is_valid;
}
static OPJ_BOOL opj_j2k_read_header_procedure(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 l_current_marker;
OPJ_UINT32 l_marker_size;
const opj_dec_memory_marker_handler_t * l_marker_handler = 00;
OPJ_BOOL l_has_siz = 0;
OPJ_BOOL l_has_cod = 0;
OPJ_BOOL l_has_qcd = 0;
/* preconditions */
assert(p_stream != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
/* We enter in the main header */
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_MHSOC;
/* Try to read the SOC marker, the codestream must begin with SOC marker */
if (! opj_j2k_read_soc(p_j2k, p_stream, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Expected a SOC marker \n");
return OPJ_FALSE;
}
/* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* Read 2 bytes as the new marker ID */
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,
&l_current_marker, 2);
/* Try to read until the SOT is detected */
while (l_current_marker != J2K_MS_SOT) {
/* Check if the current marker ID is valid */
if (l_current_marker < 0xff00) {
opj_event_msg(p_manager, EVT_ERROR,
"A marker ID was expected (0xff--) instead of %.8x\n", l_current_marker);
return OPJ_FALSE;
}
/* Get the marker handler from the marker ID */
l_marker_handler = opj_j2k_get_marker_handler(l_current_marker);
/* Manage case where marker is unknown */
if (l_marker_handler->id == J2K_MS_UNK) {
if (! opj_j2k_read_unk(p_j2k, p_stream, &l_current_marker, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR,
"Unknow marker have been detected and generated error.\n");
return OPJ_FALSE;
}
if (l_current_marker == J2K_MS_SOT) {
break; /* SOT marker is detected main header is completely read */
} else { /* Get the marker handler from the marker ID */
l_marker_handler = opj_j2k_get_marker_handler(l_current_marker);
}
}
if (l_marker_handler->id == J2K_MS_SIZ) {
/* Mark required SIZ marker as found */
l_has_siz = 1;
}
if (l_marker_handler->id == J2K_MS_COD) {
/* Mark required COD marker as found */
l_has_cod = 1;
}
if (l_marker_handler->id == J2K_MS_QCD) {
/* Mark required QCD marker as found */
l_has_qcd = 1;
}
/* Check if the marker is known and if it is the right place to find it */
if (!(p_j2k->m_specific_param.m_decoder.m_state & l_marker_handler->states)) {
opj_event_msg(p_manager, EVT_ERROR,
"Marker is not compliant with its position\n");
return OPJ_FALSE;
}
/* Try to read 2 bytes (the marker size) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* read 2 bytes as the marker size */
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data, &l_marker_size,
2);
if (l_marker_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Invalid marker size\n");
return OPJ_FALSE;
}
l_marker_size -= 2; /* Subtract the size of the marker ID already read */
/* Check if the marker size is compatible with the header data size */
if (l_marker_size > p_j2k->m_specific_param.m_decoder.m_header_data_size) {
OPJ_BYTE *new_header_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size);
if (! new_header_data) {
opj_free(p_j2k->m_specific_param.m_decoder.m_header_data);
p_j2k->m_specific_param.m_decoder.m_header_data = NULL;
p_j2k->m_specific_param.m_decoder.m_header_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read header\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_decoder.m_header_data = new_header_data;
p_j2k->m_specific_param.m_decoder.m_header_data_size = l_marker_size;
}
/* Try to read the rest of the marker segment from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size,
p_manager) != l_marker_size) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* Read the marker segment with the correct marker handler */
if (!(*(l_marker_handler->handler))(p_j2k,
p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR,
"Marker handler function failed to read the marker segment\n");
return OPJ_FALSE;
}
/* Add the marker to the codestream index*/
if (OPJ_FALSE == opj_j2k_add_mhmarker(
p_j2k->cstr_index,
l_marker_handler->id,
(OPJ_UINT32) opj_stream_tell(p_stream) - l_marker_size - 4,
l_marker_size + 4)) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add mh marker\n");
return OPJ_FALSE;
}
/* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* read 2 bytes as the new marker ID */
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,
&l_current_marker, 2);
}
if (l_has_siz == 0) {
opj_event_msg(p_manager, EVT_ERROR,
"required SIZ marker not found in main header\n");
return OPJ_FALSE;
}
if (l_has_cod == 0) {
opj_event_msg(p_manager, EVT_ERROR,
"required COD marker not found in main header\n");
return OPJ_FALSE;
}
if (l_has_qcd == 0) {
opj_event_msg(p_manager, EVT_ERROR,
"required QCD marker not found in main header\n");
return OPJ_FALSE;
}
if (! opj_j2k_merge_ppm(&(p_j2k->m_cp), p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Failed to merge PPM data\n");
return OPJ_FALSE;
}
opj_event_msg(p_manager, EVT_INFO, "Main header has been correctly decoded.\n");
/* Position of the last element if the main header */
p_j2k->cstr_index->main_head_end = (OPJ_UINT32) opj_stream_tell(p_stream) - 2;
/* Next step: read a tile-part header */
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPHSOT;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_exec(opj_j2k_t * p_j2k,
opj_procedure_list_t * p_procedure_list,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_BOOL(** l_procedure)(opj_j2k_t *, opj_stream_private_t *,
opj_event_mgr_t *) = 00;
OPJ_BOOL l_result = OPJ_TRUE;
OPJ_UINT32 l_nb_proc, i;
/* preconditions*/
assert(p_procedure_list != 00);
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
l_nb_proc = opj_procedure_list_get_nb_procedures(p_procedure_list);
l_procedure = (OPJ_BOOL(**)(opj_j2k_t *, opj_stream_private_t *,
opj_event_mgr_t *)) opj_procedure_list_get_first_procedure(p_procedure_list);
for (i = 0; i < l_nb_proc; ++i) {
l_result = l_result && ((*l_procedure)(p_j2k, p_stream, p_manager));
++l_procedure;
}
/* and clear the procedure list at the end.*/
opj_procedure_list_clear(p_procedure_list);
return l_result;
}
/* FIXME DOC*/
static OPJ_BOOL opj_j2k_copy_default_tcp_and_create_tcd(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
opj_tcp_t * l_tcp = 00;
opj_tcp_t * l_default_tcp = 00;
OPJ_UINT32 l_nb_tiles;
OPJ_UINT32 i, j;
opj_tccp_t *l_current_tccp = 00;
OPJ_UINT32 l_tccp_size;
OPJ_UINT32 l_mct_size;
opj_image_t * l_image;
OPJ_UINT32 l_mcc_records_size, l_mct_records_size;
opj_mct_data_t * l_src_mct_rec, *l_dest_mct_rec;
opj_simple_mcc_decorrelation_data_t * l_src_mcc_rec, *l_dest_mcc_rec;
OPJ_UINT32 l_offset;
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_stream);
l_image = p_j2k->m_private_image;
l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
l_tcp = p_j2k->m_cp.tcps;
l_tccp_size = l_image->numcomps * (OPJ_UINT32)sizeof(opj_tccp_t);
l_default_tcp = p_j2k->m_specific_param.m_decoder.m_default_tcp;
l_mct_size = l_image->numcomps * l_image->numcomps * (OPJ_UINT32)sizeof(
OPJ_FLOAT32);
/* For each tile */
for (i = 0; i < l_nb_tiles; ++i) {
/* keep the tile-compo coding parameters pointer of the current tile coding parameters*/
l_current_tccp = l_tcp->tccps;
/*Copy default coding parameters into the current tile coding parameters*/
memcpy(l_tcp, l_default_tcp, sizeof(opj_tcp_t));
/* Initialize some values of the current tile coding parameters*/
l_tcp->cod = 0;
l_tcp->ppt = 0;
l_tcp->ppt_data = 00;
l_tcp->m_current_tile_part_number = -1;
/* Remove memory not owned by this tile in case of early error return. */
l_tcp->m_mct_decoding_matrix = 00;
l_tcp->m_nb_max_mct_records = 0;
l_tcp->m_mct_records = 00;
l_tcp->m_nb_max_mcc_records = 0;
l_tcp->m_mcc_records = 00;
/* Reconnect the tile-compo coding parameters pointer to the current tile coding parameters*/
l_tcp->tccps = l_current_tccp;
/* Get the mct_decoding_matrix of the dflt_tile_cp and copy them into the current tile cp*/
if (l_default_tcp->m_mct_decoding_matrix) {
l_tcp->m_mct_decoding_matrix = (OPJ_FLOAT32*)opj_malloc(l_mct_size);
if (! l_tcp->m_mct_decoding_matrix) {
return OPJ_FALSE;
}
memcpy(l_tcp->m_mct_decoding_matrix, l_default_tcp->m_mct_decoding_matrix,
l_mct_size);
}
/* Get the mct_record of the dflt_tile_cp and copy them into the current tile cp*/
l_mct_records_size = l_default_tcp->m_nb_max_mct_records * (OPJ_UINT32)sizeof(
opj_mct_data_t);
l_tcp->m_mct_records = (opj_mct_data_t*)opj_malloc(l_mct_records_size);
if (! l_tcp->m_mct_records) {
return OPJ_FALSE;
}
memcpy(l_tcp->m_mct_records, l_default_tcp->m_mct_records, l_mct_records_size);
/* Copy the mct record data from dflt_tile_cp to the current tile*/
l_src_mct_rec = l_default_tcp->m_mct_records;
l_dest_mct_rec = l_tcp->m_mct_records;
for (j = 0; j < l_default_tcp->m_nb_mct_records; ++j) {
if (l_src_mct_rec->m_data) {
l_dest_mct_rec->m_data = (OPJ_BYTE*) opj_malloc(l_src_mct_rec->m_data_size);
if (! l_dest_mct_rec->m_data) {
return OPJ_FALSE;
}
memcpy(l_dest_mct_rec->m_data, l_src_mct_rec->m_data,
l_src_mct_rec->m_data_size);
}
++l_src_mct_rec;
++l_dest_mct_rec;
/* Update with each pass to free exactly what has been allocated on early return. */
l_tcp->m_nb_max_mct_records += 1;
}
/* Get the mcc_record of the dflt_tile_cp and copy them into the current tile cp*/
l_mcc_records_size = l_default_tcp->m_nb_max_mcc_records * (OPJ_UINT32)sizeof(
opj_simple_mcc_decorrelation_data_t);
l_tcp->m_mcc_records = (opj_simple_mcc_decorrelation_data_t*) opj_malloc(
l_mcc_records_size);
if (! l_tcp->m_mcc_records) {
return OPJ_FALSE;
}
memcpy(l_tcp->m_mcc_records, l_default_tcp->m_mcc_records, l_mcc_records_size);
l_tcp->m_nb_max_mcc_records = l_default_tcp->m_nb_max_mcc_records;
/* Copy the mcc record data from dflt_tile_cp to the current tile*/
l_src_mcc_rec = l_default_tcp->m_mcc_records;
l_dest_mcc_rec = l_tcp->m_mcc_records;
for (j = 0; j < l_default_tcp->m_nb_max_mcc_records; ++j) {
if (l_src_mcc_rec->m_decorrelation_array) {
l_offset = (OPJ_UINT32)(l_src_mcc_rec->m_decorrelation_array -
l_default_tcp->m_mct_records);
l_dest_mcc_rec->m_decorrelation_array = l_tcp->m_mct_records + l_offset;
}
if (l_src_mcc_rec->m_offset_array) {
l_offset = (OPJ_UINT32)(l_src_mcc_rec->m_offset_array -
l_default_tcp->m_mct_records);
l_dest_mcc_rec->m_offset_array = l_tcp->m_mct_records + l_offset;
}
++l_src_mcc_rec;
++l_dest_mcc_rec;
}
/* Copy all the dflt_tile_compo_cp to the current tile cp */
memcpy(l_current_tccp, l_default_tcp->tccps, l_tccp_size);
/* Move to next tile cp*/
++l_tcp;
}
/* Create the current tile decoder*/
p_j2k->m_tcd = (opj_tcd_t*)opj_tcd_create(OPJ_TRUE); /* FIXME why a cast ? */
if (! p_j2k->m_tcd) {
return OPJ_FALSE;
}
if (!opj_tcd_init(p_j2k->m_tcd, l_image, &(p_j2k->m_cp), p_j2k->m_tp)) {
opj_tcd_destroy(p_j2k->m_tcd);
p_j2k->m_tcd = 00;
opj_event_msg(p_manager, EVT_ERROR, "Cannot decode tile, memory error\n");
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static const opj_dec_memory_marker_handler_t * opj_j2k_get_marker_handler(
OPJ_UINT32 p_id)
{
const opj_dec_memory_marker_handler_t *e;
for (e = j2k_memory_marker_handler_tab; e->id != 0; ++e) {
if (e->id == p_id) {
break; /* we find a handler corresponding to the marker ID*/
}
}
return e;
}
void opj_j2k_destroy(opj_j2k_t *p_j2k)
{
if (p_j2k == 00) {
return;
}
if (p_j2k->m_is_decoder) {
if (p_j2k->m_specific_param.m_decoder.m_default_tcp != 00) {
opj_j2k_tcp_destroy(p_j2k->m_specific_param.m_decoder.m_default_tcp);
opj_free(p_j2k->m_specific_param.m_decoder.m_default_tcp);
p_j2k->m_specific_param.m_decoder.m_default_tcp = 00;
}
if (p_j2k->m_specific_param.m_decoder.m_header_data != 00) {
opj_free(p_j2k->m_specific_param.m_decoder.m_header_data);
p_j2k->m_specific_param.m_decoder.m_header_data = 00;
p_j2k->m_specific_param.m_decoder.m_header_data_size = 0;
}
} else {
if (p_j2k->m_specific_param.m_encoder.m_encoded_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_encoded_tile_data);
p_j2k->m_specific_param.m_encoder.m_encoded_tile_data = 00;
}
if (p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer) {
opj_free(p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer);
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer = 00;
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current = 00;
}
if (p_j2k->m_specific_param.m_encoder.m_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = 00;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
}
}
opj_tcd_destroy(p_j2k->m_tcd);
opj_j2k_cp_destroy(&(p_j2k->m_cp));
memset(&(p_j2k->m_cp), 0, sizeof(opj_cp_t));
opj_procedure_list_destroy(p_j2k->m_procedure_list);
p_j2k->m_procedure_list = 00;
opj_procedure_list_destroy(p_j2k->m_validation_list);
p_j2k->m_procedure_list = 00;
j2k_destroy_cstr_index(p_j2k->cstr_index);
p_j2k->cstr_index = NULL;
opj_image_destroy(p_j2k->m_private_image);
p_j2k->m_private_image = NULL;
opj_image_destroy(p_j2k->m_output_image);
p_j2k->m_output_image = NULL;
opj_thread_pool_destroy(p_j2k->m_tp);
p_j2k->m_tp = NULL;
opj_free(p_j2k);
}
void j2k_destroy_cstr_index(opj_codestream_index_t *p_cstr_ind)
{
if (p_cstr_ind) {
if (p_cstr_ind->marker) {
opj_free(p_cstr_ind->marker);
p_cstr_ind->marker = NULL;
}
if (p_cstr_ind->tile_index) {
OPJ_UINT32 it_tile = 0;
for (it_tile = 0; it_tile < p_cstr_ind->nb_of_tiles; it_tile++) {
if (p_cstr_ind->tile_index[it_tile].packet_index) {
opj_free(p_cstr_ind->tile_index[it_tile].packet_index);
p_cstr_ind->tile_index[it_tile].packet_index = NULL;
}
if (p_cstr_ind->tile_index[it_tile].tp_index) {
opj_free(p_cstr_ind->tile_index[it_tile].tp_index);
p_cstr_ind->tile_index[it_tile].tp_index = NULL;
}
if (p_cstr_ind->tile_index[it_tile].marker) {
opj_free(p_cstr_ind->tile_index[it_tile].marker);
p_cstr_ind->tile_index[it_tile].marker = NULL;
}
}
opj_free(p_cstr_ind->tile_index);
p_cstr_ind->tile_index = NULL;
}
opj_free(p_cstr_ind);
}
}
static void opj_j2k_tcp_destroy(opj_tcp_t *p_tcp)
{
if (p_tcp == 00) {
return;
}
if (p_tcp->ppt_markers != 00) {
OPJ_UINT32 i;
for (i = 0U; i < p_tcp->ppt_markers_count; ++i) {
if (p_tcp->ppt_markers[i].m_data != NULL) {
opj_free(p_tcp->ppt_markers[i].m_data);
}
}
p_tcp->ppt_markers_count = 0U;
opj_free(p_tcp->ppt_markers);
p_tcp->ppt_markers = NULL;
}
if (p_tcp->ppt_buffer != 00) {
opj_free(p_tcp->ppt_buffer);
p_tcp->ppt_buffer = 00;
}
if (p_tcp->tccps != 00) {
opj_free(p_tcp->tccps);
p_tcp->tccps = 00;
}
if (p_tcp->m_mct_coding_matrix != 00) {
opj_free(p_tcp->m_mct_coding_matrix);
p_tcp->m_mct_coding_matrix = 00;
}
if (p_tcp->m_mct_decoding_matrix != 00) {
opj_free(p_tcp->m_mct_decoding_matrix);
p_tcp->m_mct_decoding_matrix = 00;
}
if (p_tcp->m_mcc_records) {
opj_free(p_tcp->m_mcc_records);
p_tcp->m_mcc_records = 00;
p_tcp->m_nb_max_mcc_records = 0;
p_tcp->m_nb_mcc_records = 0;
}
if (p_tcp->m_mct_records) {
opj_mct_data_t * l_mct_data = p_tcp->m_mct_records;
OPJ_UINT32 i;
for (i = 0; i < p_tcp->m_nb_mct_records; ++i) {
if (l_mct_data->m_data) {
opj_free(l_mct_data->m_data);
l_mct_data->m_data = 00;
}
++l_mct_data;
}
opj_free(p_tcp->m_mct_records);
p_tcp->m_mct_records = 00;
}
if (p_tcp->mct_norms != 00) {
opj_free(p_tcp->mct_norms);
p_tcp->mct_norms = 00;
}
opj_j2k_tcp_data_destroy(p_tcp);
}
static void opj_j2k_tcp_data_destroy(opj_tcp_t *p_tcp)
{
if (p_tcp->m_data) {
opj_free(p_tcp->m_data);
p_tcp->m_data = NULL;
p_tcp->m_data_size = 0;
}
}
static void opj_j2k_cp_destroy(opj_cp_t *p_cp)
{
OPJ_UINT32 l_nb_tiles;
opj_tcp_t * l_current_tile = 00;
if (p_cp == 00) {
return;
}
if (p_cp->tcps != 00) {
OPJ_UINT32 i;
l_current_tile = p_cp->tcps;
l_nb_tiles = p_cp->th * p_cp->tw;
for (i = 0U; i < l_nb_tiles; ++i) {
opj_j2k_tcp_destroy(l_current_tile);
++l_current_tile;
}
opj_free(p_cp->tcps);
p_cp->tcps = 00;
}
if (p_cp->ppm_markers != 00) {
OPJ_UINT32 i;
for (i = 0U; i < p_cp->ppm_markers_count; ++i) {
if (p_cp->ppm_markers[i].m_data != NULL) {
opj_free(p_cp->ppm_markers[i].m_data);
}
}
p_cp->ppm_markers_count = 0U;
opj_free(p_cp->ppm_markers);
p_cp->ppm_markers = NULL;
}
opj_free(p_cp->ppm_buffer);
p_cp->ppm_buffer = 00;
p_cp->ppm_data =
NULL; /* ppm_data belongs to the allocated buffer pointed by ppm_buffer */
opj_free(p_cp->comment);
p_cp->comment = 00;
if (! p_cp->m_is_decoder) {
opj_free(p_cp->m_specific_param.m_enc.m_matrice);
p_cp->m_specific_param.m_enc.m_matrice = 00;
}
}
static OPJ_BOOL opj_j2k_need_nb_tile_parts_correction(opj_stream_private_t
*p_stream, OPJ_UINT32 tile_no, OPJ_BOOL* p_correction_needed,
opj_event_mgr_t * p_manager)
{
OPJ_BYTE l_header_data[10];
OPJ_OFF_T l_stream_pos_backup;
OPJ_UINT32 l_current_marker;
OPJ_UINT32 l_marker_size;
OPJ_UINT32 l_tile_no, l_tot_len, l_current_part, l_num_parts;
/* initialize to no correction needed */
*p_correction_needed = OPJ_FALSE;
if (!opj_stream_has_seek(p_stream)) {
/* We can't do much in this case, seek is needed */
return OPJ_TRUE;
}
l_stream_pos_backup = opj_stream_tell(p_stream);
if (l_stream_pos_backup == -1) {
/* let's do nothing */
return OPJ_TRUE;
}
for (;;) {
/* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream, l_header_data, 2, p_manager) != 2) {
/* assume all is OK */
if (! opj_stream_seek(p_stream, l_stream_pos_backup, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/* Read 2 bytes from buffer as the new marker ID */
opj_read_bytes(l_header_data, &l_current_marker, 2);
if (l_current_marker != J2K_MS_SOT) {
/* assume all is OK */
if (! opj_stream_seek(p_stream, l_stream_pos_backup, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/* Try to read 2 bytes (the marker size) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream, l_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* Read 2 bytes from the buffer as the marker size */
opj_read_bytes(l_header_data, &l_marker_size, 2);
/* Check marker size for SOT Marker */
if (l_marker_size != 10) {
opj_event_msg(p_manager, EVT_ERROR, "Inconsistent marker size\n");
return OPJ_FALSE;
}
l_marker_size -= 2;
if (opj_stream_read_data(p_stream, l_header_data, l_marker_size,
p_manager) != l_marker_size) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
if (! opj_j2k_get_sot_values(l_header_data, l_marker_size, &l_tile_no,
&l_tot_len, &l_current_part, &l_num_parts, p_manager)) {
return OPJ_FALSE;
}
if (l_tile_no == tile_no) {
/* we found what we were looking for */
break;
}
if ((l_tot_len == 0U) || (l_tot_len < 14U)) {
/* last SOT until EOC or invalid Psot value */
/* assume all is OK */
if (! opj_stream_seek(p_stream, l_stream_pos_backup, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
l_tot_len -= 12U;
/* look for next SOT marker */
if (opj_stream_skip(p_stream, (OPJ_OFF_T)(l_tot_len),
p_manager) != (OPJ_OFF_T)(l_tot_len)) {
/* assume all is OK */
if (! opj_stream_seek(p_stream, l_stream_pos_backup, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
}
/* check for correction */
if (l_current_part == l_num_parts) {
*p_correction_needed = OPJ_TRUE;
}
if (! opj_stream_seek(p_stream, l_stream_pos_backup, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_read_tile_header(opj_j2k_t * p_j2k,
OPJ_UINT32 * p_tile_index,
OPJ_UINT32 * p_data_size,
OPJ_INT32 * p_tile_x0, OPJ_INT32 * p_tile_y0,
OPJ_INT32 * p_tile_x1, OPJ_INT32 * p_tile_y1,
OPJ_UINT32 * p_nb_comps,
OPJ_BOOL * p_go_on,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 l_current_marker = J2K_MS_SOT;
OPJ_UINT32 l_marker_size;
const opj_dec_memory_marker_handler_t * l_marker_handler = 00;
opj_tcp_t * l_tcp = NULL;
/* preconditions */
assert(p_stream != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
/* Reach the End Of Codestream ?*/
if (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_EOC) {
l_current_marker = J2K_MS_EOC;
}
/* We need to encounter a SOT marker (a new tile-part header) */
else if (p_j2k->m_specific_param.m_decoder.m_state != J2K_STATE_TPHSOT) {
return OPJ_FALSE;
}
/* Read into the codestream until reach the EOC or ! can_decode ??? FIXME */
while ((!p_j2k->m_specific_param.m_decoder.m_can_decode) &&
(l_current_marker != J2K_MS_EOC)) {
/* Try to read until the Start Of Data is detected */
while (l_current_marker != J2K_MS_SOD) {
if (opj_stream_get_number_byte_left(p_stream) == 0) {
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_NEOC;
break;
}
/* Try to read 2 bytes (the marker size) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* Read 2 bytes from the buffer as the marker size */
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data, &l_marker_size,
2);
/* Check marker size (does not include marker ID but includes marker size) */
if (l_marker_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Inconsistent marker size\n");
return OPJ_FALSE;
}
/* cf. https://code.google.com/p/openjpeg/issues/detail?id=226 */
if (l_current_marker == 0x8080 &&
opj_stream_get_number_byte_left(p_stream) == 0) {
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_NEOC;
break;
}
/* Why this condition? FIXME */
if (p_j2k->m_specific_param.m_decoder.m_state & J2K_STATE_TPH) {
p_j2k->m_specific_param.m_decoder.m_sot_length -= (l_marker_size + 2);
}
l_marker_size -= 2; /* Subtract the size of the marker ID already read */
/* Get the marker handler from the marker ID */
l_marker_handler = opj_j2k_get_marker_handler(l_current_marker);
/* Check if the marker is known and if it is the right place to find it */
if (!(p_j2k->m_specific_param.m_decoder.m_state & l_marker_handler->states)) {
opj_event_msg(p_manager, EVT_ERROR,
"Marker is not compliant with its position\n");
return OPJ_FALSE;
}
/* FIXME manage case of unknown marker as in the main header ? */
/* Check if the marker size is compatible with the header data size */
if (l_marker_size > p_j2k->m_specific_param.m_decoder.m_header_data_size) {
OPJ_BYTE *new_header_data = NULL;
/* If we are here, this means we consider this marker as known & we will read it */
/* Check enough bytes left in stream before allocation */
if ((OPJ_OFF_T)l_marker_size > opj_stream_get_number_byte_left(p_stream)) {
opj_event_msg(p_manager, EVT_ERROR,
"Marker size inconsistent with stream length\n");
return OPJ_FALSE;
}
new_header_data = (OPJ_BYTE *) opj_realloc(
p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size);
if (! new_header_data) {
opj_free(p_j2k->m_specific_param.m_decoder.m_header_data);
p_j2k->m_specific_param.m_decoder.m_header_data = NULL;
p_j2k->m_specific_param.m_decoder.m_header_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read header\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_decoder.m_header_data = new_header_data;
p_j2k->m_specific_param.m_decoder.m_header_data_size = l_marker_size;
}
/* Try to read the rest of the marker segment from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size,
p_manager) != l_marker_size) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
if (!l_marker_handler->handler) {
/* See issue #175 */
opj_event_msg(p_manager, EVT_ERROR, "Not sure how that happened.\n");
return OPJ_FALSE;
}
/* Read the marker segment with the correct marker handler */
if (!(*(l_marker_handler->handler))(p_j2k,
p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR,
"Fail to read the current marker segment (%#x)\n", l_current_marker);
return OPJ_FALSE;
}
/* Add the marker to the codestream index*/
if (OPJ_FALSE == opj_j2k_add_tlmarker(p_j2k->m_current_tile_number,
p_j2k->cstr_index,
l_marker_handler->id,
(OPJ_UINT32) opj_stream_tell(p_stream) - l_marker_size - 4,
l_marker_size + 4)) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add tl marker\n");
return OPJ_FALSE;
}
/* Keep the position of the last SOT marker read */
if (l_marker_handler->id == J2K_MS_SOT) {
OPJ_UINT32 sot_pos = (OPJ_UINT32) opj_stream_tell(p_stream) - l_marker_size - 4
;
if (sot_pos > p_j2k->m_specific_param.m_decoder.m_last_sot_read_pos) {
p_j2k->m_specific_param.m_decoder.m_last_sot_read_pos = sot_pos;
}
}
if (p_j2k->m_specific_param.m_decoder.m_skip_data) {
/* Skip the rest of the tile part header*/
if (opj_stream_skip(p_stream, p_j2k->m_specific_param.m_decoder.m_sot_length,
p_manager) != p_j2k->m_specific_param.m_decoder.m_sot_length) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
l_current_marker = J2K_MS_SOD; /* Normally we reached a SOD */
} else {
/* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer*/
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* Read 2 bytes from the buffer as the new marker ID */
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,
&l_current_marker, 2);
}
}
if (opj_stream_get_number_byte_left(p_stream) == 0
&& p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_NEOC) {
break;
}
/* If we didn't skip data before, we need to read the SOD marker*/
if (! p_j2k->m_specific_param.m_decoder.m_skip_data) {
/* Try to read the SOD marker and skip data ? FIXME */
if (! opj_j2k_read_sod(p_j2k, p_stream, p_manager)) {
return OPJ_FALSE;
}
if (p_j2k->m_specific_param.m_decoder.m_can_decode &&
!p_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction_checked) {
/* Issue 254 */
OPJ_BOOL l_correction_needed;
p_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction_checked = 1;
if (!opj_j2k_need_nb_tile_parts_correction(p_stream,
p_j2k->m_current_tile_number, &l_correction_needed, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR,
"opj_j2k_apply_nb_tile_parts_correction error\n");
return OPJ_FALSE;
}
if (l_correction_needed) {
OPJ_UINT32 l_nb_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th;
OPJ_UINT32 l_tile_no;
p_j2k->m_specific_param.m_decoder.m_can_decode = 0;
p_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction = 1;
/* correct tiles */
for (l_tile_no = 0U; l_tile_no < l_nb_tiles; ++l_tile_no) {
if (p_j2k->m_cp.tcps[l_tile_no].m_nb_tile_parts != 0U) {
p_j2k->m_cp.tcps[l_tile_no].m_nb_tile_parts += 1;
}
}
opj_event_msg(p_manager, EVT_WARNING,
"Non conformant codestream TPsot==TNsot.\n");
}
}
if (! p_j2k->m_specific_param.m_decoder.m_can_decode) {
/* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* Read 2 bytes from buffer as the new marker ID */
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,
&l_current_marker, 2);
}
} else {
/* Indicate we will try to read a new tile-part header*/
p_j2k->m_specific_param.m_decoder.m_skip_data = 0;
p_j2k->m_specific_param.m_decoder.m_can_decode = 0;
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPHSOT;
/* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,
p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* Read 2 bytes from buffer as the new marker ID */
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,
&l_current_marker, 2);
}
}
/* Current marker is the EOC marker ?*/
if (l_current_marker == J2K_MS_EOC) {
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_EOC;
}
/* FIXME DOC ???*/
if (! p_j2k->m_specific_param.m_decoder.m_can_decode) {
OPJ_UINT32 l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
l_tcp = p_j2k->m_cp.tcps + p_j2k->m_current_tile_number;
while ((p_j2k->m_current_tile_number < l_nb_tiles) && (l_tcp->m_data == 00)) {
++p_j2k->m_current_tile_number;
++l_tcp;
}
if (p_j2k->m_current_tile_number == l_nb_tiles) {
*p_go_on = OPJ_FALSE;
return OPJ_TRUE;
}
}
if (! opj_j2k_merge_ppt(p_j2k->m_cp.tcps + p_j2k->m_current_tile_number,
p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Failed to merge PPT data\n");
return OPJ_FALSE;
}
/*FIXME ???*/
if (! opj_tcd_init_decode_tile(p_j2k->m_tcd, p_j2k->m_current_tile_number,
p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Cannot decode tile, memory error\n");
return OPJ_FALSE;
}
opj_event_msg(p_manager, EVT_INFO, "Header of tile %d / %d has been read.\n",
p_j2k->m_current_tile_number + 1, (p_j2k->m_cp.th * p_j2k->m_cp.tw));
*p_tile_index = p_j2k->m_current_tile_number;
*p_go_on = OPJ_TRUE;
*p_data_size = opj_tcd_get_decoded_tile_size(p_j2k->m_tcd);
if (*p_data_size == UINT_MAX) {
return OPJ_FALSE;
}
*p_tile_x0 = p_j2k->m_tcd->tcd_image->tiles->x0;
*p_tile_y0 = p_j2k->m_tcd->tcd_image->tiles->y0;
*p_tile_x1 = p_j2k->m_tcd->tcd_image->tiles->x1;
*p_tile_y1 = p_j2k->m_tcd->tcd_image->tiles->y1;
*p_nb_comps = p_j2k->m_tcd->tcd_image->tiles->numcomps;
p_j2k->m_specific_param.m_decoder.m_state |= J2K_STATE_DATA;
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_decode_tile(opj_j2k_t * p_j2k,
OPJ_UINT32 p_tile_index,
OPJ_BYTE * p_data,
OPJ_UINT32 p_data_size,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 l_current_marker;
OPJ_BYTE l_data [2];
opj_tcp_t * l_tcp;
/* preconditions */
assert(p_stream != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
if (!(p_j2k->m_specific_param.m_decoder.m_state & J2K_STATE_DATA)
|| (p_tile_index != p_j2k->m_current_tile_number)) {
return OPJ_FALSE;
}
l_tcp = &(p_j2k->m_cp.tcps[p_tile_index]);
if (! l_tcp->m_data) {
opj_j2k_tcp_destroy(l_tcp);
return OPJ_FALSE;
}
if (! opj_tcd_decode_tile(p_j2k->m_tcd,
l_tcp->m_data,
l_tcp->m_data_size,
p_tile_index,
p_j2k->cstr_index, p_manager)) {
opj_j2k_tcp_destroy(l_tcp);
p_j2k->m_specific_param.m_decoder.m_state |= J2K_STATE_ERR;
opj_event_msg(p_manager, EVT_ERROR, "Failed to decode.\n");
return OPJ_FALSE;
}
/* p_data can be set to NULL when the call will take care of using */
/* itself the TCD data. This is typically the case for whole single */
/* tile decoding optimization. */
if (p_data != NULL) {
if (! opj_tcd_update_tile_data(p_j2k->m_tcd, p_data, p_data_size)) {
return OPJ_FALSE;
}
/* To avoid to destroy the tcp which can be useful when we try to decode a tile decoded before (cf j2k_random_tile_access)
* we destroy just the data which will be re-read in read_tile_header*/
/*opj_j2k_tcp_destroy(l_tcp);
p_j2k->m_tcd->tcp = 0;*/
opj_j2k_tcp_data_destroy(l_tcp);
}
p_j2k->m_specific_param.m_decoder.m_can_decode = 0;
p_j2k->m_specific_param.m_decoder.m_state &= (~(OPJ_UINT32)J2K_STATE_DATA);
if (opj_stream_get_number_byte_left(p_stream) == 0
&& p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_NEOC) {
return OPJ_TRUE;
}
if (p_j2k->m_specific_param.m_decoder.m_state != J2K_STATE_EOC) {
if (opj_stream_read_data(p_stream, l_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
opj_read_bytes(l_data, &l_current_marker, 2);
if (l_current_marker == J2K_MS_EOC) {
p_j2k->m_current_tile_number = 0;
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_EOC;
} else if (l_current_marker != J2K_MS_SOT) {
if (opj_stream_get_number_byte_left(p_stream) == 0) {
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_NEOC;
opj_event_msg(p_manager, EVT_WARNING, "Stream does not end with EOC\n");
return OPJ_TRUE;
}
opj_event_msg(p_manager, EVT_ERROR, "Stream too short, expected SOT\n");
return OPJ_FALSE;
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_update_image_data(opj_tcd_t * p_tcd, OPJ_BYTE * p_data,
opj_image_t* p_output_image)
{
OPJ_UINT32 i, j, k = 0;
OPJ_UINT32 l_width_src, l_height_src;
OPJ_UINT32 l_width_dest, l_height_dest;
OPJ_INT32 l_offset_x0_src, l_offset_y0_src, l_offset_x1_src, l_offset_y1_src;
OPJ_SIZE_T l_start_offset_src, l_line_offset_src, l_end_offset_src ;
OPJ_UINT32 l_start_x_dest, l_start_y_dest;
OPJ_UINT32 l_x0_dest, l_y0_dest, l_x1_dest, l_y1_dest;
OPJ_SIZE_T l_start_offset_dest, l_line_offset_dest;
opj_image_comp_t * l_img_comp_src = 00;
opj_image_comp_t * l_img_comp_dest = 00;
opj_tcd_tilecomp_t * l_tilec = 00;
opj_image_t * l_image_src = 00;
OPJ_UINT32 l_size_comp, l_remaining;
OPJ_INT32 * l_dest_ptr;
opj_tcd_resolution_t* l_res = 00;
l_tilec = p_tcd->tcd_image->tiles->comps;
l_image_src = p_tcd->image;
l_img_comp_src = l_image_src->comps;
l_img_comp_dest = p_output_image->comps;
for (i = 0; i < l_image_src->numcomps; i++) {
/* Allocate output component buffer if necessary */
if (!l_img_comp_dest->data) {
OPJ_SIZE_T l_width = l_img_comp_dest->w;
OPJ_SIZE_T l_height = l_img_comp_dest->h;
if ((l_height == 0U) || (l_width > (SIZE_MAX / l_height)) ||
l_width * l_height > SIZE_MAX / sizeof(OPJ_INT32)) {
/* would overflow */
return OPJ_FALSE;
}
l_img_comp_dest->data = (OPJ_INT32*) opj_image_data_alloc(l_width * l_height *
sizeof(OPJ_INT32));
if (! l_img_comp_dest->data) {
return OPJ_FALSE;
}
/* Do we really need this memset ? */
memset(l_img_comp_dest->data, 0, l_width * l_height * sizeof(OPJ_INT32));
}
/* Copy info from decoded comp image to output image */
l_img_comp_dest->resno_decoded = l_img_comp_src->resno_decoded;
/*-----*/
/* Compute the precision of the output buffer */
l_size_comp = l_img_comp_src->prec >> 3; /*(/ 8)*/
l_remaining = l_img_comp_src->prec & 7; /* (%8) */
l_res = l_tilec->resolutions + l_img_comp_src->resno_decoded;
if (l_remaining) {
++l_size_comp;
}
if (l_size_comp == 3) {
l_size_comp = 4;
}
/*-----*/
/* Current tile component size*/
/*if (i == 0) {
fprintf(stdout, "SRC: l_res_x0=%d, l_res_x1=%d, l_res_y0=%d, l_res_y1=%d\n",
l_res->x0, l_res->x1, l_res->y0, l_res->y1);
}*/
l_width_src = (OPJ_UINT32)(l_res->x1 - l_res->x0);
l_height_src = (OPJ_UINT32)(l_res->y1 - l_res->y0);
/* Border of the current output component*/
l_x0_dest = opj_uint_ceildivpow2(l_img_comp_dest->x0, l_img_comp_dest->factor);
l_y0_dest = opj_uint_ceildivpow2(l_img_comp_dest->y0, l_img_comp_dest->factor);
l_x1_dest = l_x0_dest +
l_img_comp_dest->w; /* can't overflow given that image->x1 is uint32 */
l_y1_dest = l_y0_dest + l_img_comp_dest->h;
/*if (i == 0) {
fprintf(stdout, "DEST: l_x0_dest=%d, l_x1_dest=%d, l_y0_dest=%d, l_y1_dest=%d (%d)\n",
l_x0_dest, l_x1_dest, l_y0_dest, l_y1_dest, l_img_comp_dest->factor );
}*/
/*-----*/
/* Compute the area (l_offset_x0_src, l_offset_y0_src, l_offset_x1_src, l_offset_y1_src)
* of the input buffer (decoded tile component) which will be move
* in the output buffer. Compute the area of the output buffer (l_start_x_dest,
* l_start_y_dest, l_width_dest, l_height_dest) which will be modified
* by this input area.
* */
assert(l_res->x0 >= 0);
assert(l_res->x1 >= 0);
if (l_x0_dest < (OPJ_UINT32)l_res->x0) {
l_start_x_dest = (OPJ_UINT32)l_res->x0 - l_x0_dest;
l_offset_x0_src = 0;
if (l_x1_dest >= (OPJ_UINT32)l_res->x1) {
l_width_dest = l_width_src;
l_offset_x1_src = 0;
} else {
l_width_dest = l_x1_dest - (OPJ_UINT32)l_res->x0 ;
l_offset_x1_src = (OPJ_INT32)(l_width_src - l_width_dest);
}
} else {
l_start_x_dest = 0U;
l_offset_x0_src = (OPJ_INT32)l_x0_dest - l_res->x0;
if (l_x1_dest >= (OPJ_UINT32)l_res->x1) {
l_width_dest = l_width_src - (OPJ_UINT32)l_offset_x0_src;
l_offset_x1_src = 0;
} else {
l_width_dest = l_img_comp_dest->w ;
l_offset_x1_src = l_res->x1 - (OPJ_INT32)l_x1_dest;
}
}
if (l_y0_dest < (OPJ_UINT32)l_res->y0) {
l_start_y_dest = (OPJ_UINT32)l_res->y0 - l_y0_dest;
l_offset_y0_src = 0;
if (l_y1_dest >= (OPJ_UINT32)l_res->y1) {
l_height_dest = l_height_src;
l_offset_y1_src = 0;
} else {
l_height_dest = l_y1_dest - (OPJ_UINT32)l_res->y0 ;
l_offset_y1_src = (OPJ_INT32)(l_height_src - l_height_dest);
}
} else {
l_start_y_dest = 0U;
l_offset_y0_src = (OPJ_INT32)l_y0_dest - l_res->y0;
if (l_y1_dest >= (OPJ_UINT32)l_res->y1) {
l_height_dest = l_height_src - (OPJ_UINT32)l_offset_y0_src;
l_offset_y1_src = 0;
} else {
l_height_dest = l_img_comp_dest->h ;
l_offset_y1_src = l_res->y1 - (OPJ_INT32)l_y1_dest;
}
}
if ((l_offset_x0_src < 0) || (l_offset_y0_src < 0) || (l_offset_x1_src < 0) ||
(l_offset_y1_src < 0)) {
return OPJ_FALSE;
}
/* testcase 2977.pdf.asan.67.2198 */
if ((OPJ_INT32)l_width_dest < 0 || (OPJ_INT32)l_height_dest < 0) {
return OPJ_FALSE;
}
/*-----*/
/* Compute the input buffer offset */
l_start_offset_src = (OPJ_SIZE_T)l_offset_x0_src + (OPJ_SIZE_T)l_offset_y0_src
* (OPJ_SIZE_T)l_width_src;
l_line_offset_src = (OPJ_SIZE_T)l_offset_x1_src + (OPJ_SIZE_T)l_offset_x0_src;
l_end_offset_src = (OPJ_SIZE_T)l_offset_y1_src * (OPJ_SIZE_T)l_width_src -
(OPJ_SIZE_T)l_offset_x0_src;
/* Compute the output buffer offset */
l_start_offset_dest = (OPJ_SIZE_T)l_start_x_dest + (OPJ_SIZE_T)l_start_y_dest
* (OPJ_SIZE_T)l_img_comp_dest->w;
l_line_offset_dest = (OPJ_SIZE_T)l_img_comp_dest->w - (OPJ_SIZE_T)l_width_dest;
/* Move the output buffer to the first place where we will write*/
l_dest_ptr = l_img_comp_dest->data + l_start_offset_dest;
/*if (i == 0) {
fprintf(stdout, "COMPO[%d]:\n",i);
fprintf(stdout, "SRC: l_start_x_src=%d, l_start_y_src=%d, l_width_src=%d, l_height_src=%d\n"
"\t tile offset:%d, %d, %d, %d\n"
"\t buffer offset: %d; %d, %d\n",
l_res->x0, l_res->y0, l_width_src, l_height_src,
l_offset_x0_src, l_offset_y0_src, l_offset_x1_src, l_offset_y1_src,
l_start_offset_src, l_line_offset_src, l_end_offset_src);
fprintf(stdout, "DEST: l_start_x_dest=%d, l_start_y_dest=%d, l_width_dest=%d, l_height_dest=%d\n"
"\t start offset: %d, line offset= %d\n",
l_start_x_dest, l_start_y_dest, l_width_dest, l_height_dest, l_start_offset_dest, l_line_offset_dest);
}*/
switch (l_size_comp) {
case 1: {
OPJ_CHAR * l_src_ptr = (OPJ_CHAR*) p_data;
l_src_ptr += l_start_offset_src; /* Move to the first place where we will read*/
if (l_img_comp_src->sgnd) {
for (j = 0 ; j < l_height_dest ; ++j) {
for (k = 0 ; k < l_width_dest ; ++k) {
*(l_dest_ptr++) = (OPJ_INT32)(*
(l_src_ptr++)); /* Copy only the data needed for the output image */
}
l_dest_ptr +=
l_line_offset_dest; /* Move to the next place where we will write */
l_src_ptr += l_line_offset_src ; /* Move to the next place where we will read */
}
} else {
for (j = 0 ; j < l_height_dest ; ++j) {
for (k = 0 ; k < l_width_dest ; ++k) {
*(l_dest_ptr++) = (OPJ_INT32)((*(l_src_ptr++)) & 0xff);
}
l_dest_ptr += l_line_offset_dest;
l_src_ptr += l_line_offset_src;
}
}
l_src_ptr +=
l_end_offset_src; /* Move to the end of this component-part of the input buffer */
p_data = (OPJ_BYTE*)
l_src_ptr; /* Keep the current position for the next component-part */
}
break;
case 2: {
OPJ_INT16 * l_src_ptr = (OPJ_INT16 *) p_data;
l_src_ptr += l_start_offset_src;
if (l_img_comp_src->sgnd) {
for (j = 0; j < l_height_dest; ++j) {
for (k = 0; k < l_width_dest; ++k) {
OPJ_INT16 val;
memcpy(&val, l_src_ptr, sizeof(val));
l_src_ptr ++;
*(l_dest_ptr++) = val;
}
l_dest_ptr += l_line_offset_dest;
l_src_ptr += l_line_offset_src ;
}
} else {
for (j = 0; j < l_height_dest; ++j) {
for (k = 0; k < l_width_dest; ++k) {
OPJ_INT16 val;
memcpy(&val, l_src_ptr, sizeof(val));
l_src_ptr ++;
*(l_dest_ptr++) = val & 0xffff;
}
l_dest_ptr += l_line_offset_dest;
l_src_ptr += l_line_offset_src ;
}
}
l_src_ptr += l_end_offset_src;
p_data = (OPJ_BYTE*) l_src_ptr;
}
break;
case 4: {
OPJ_INT32 * l_src_ptr = (OPJ_INT32 *) p_data;
l_src_ptr += l_start_offset_src;
for (j = 0; j < l_height_dest; ++j) {
memcpy(l_dest_ptr, l_src_ptr, l_width_dest * sizeof(OPJ_INT32));
l_dest_ptr += l_width_dest + l_line_offset_dest;
l_src_ptr += l_width_dest + l_line_offset_src ;
}
l_src_ptr += l_end_offset_src;
p_data = (OPJ_BYTE*) l_src_ptr;
}
break;
}
++l_img_comp_dest;
++l_img_comp_src;
++l_tilec;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_set_decode_area(opj_j2k_t *p_j2k,
opj_image_t* p_image,
OPJ_INT32 p_start_x, OPJ_INT32 p_start_y,
OPJ_INT32 p_end_x, OPJ_INT32 p_end_y,
opj_event_mgr_t * p_manager)
{
opj_cp_t * l_cp = &(p_j2k->m_cp);
opj_image_t * l_image = p_j2k->m_private_image;
OPJ_UINT32 it_comp;
OPJ_INT32 l_comp_x1, l_comp_y1;
opj_image_comp_t* l_img_comp = NULL;
/* Check if we are read the main header */
if (p_j2k->m_specific_param.m_decoder.m_state != J2K_STATE_TPHSOT) {
opj_event_msg(p_manager, EVT_ERROR,
"Need to decode the main header before begin to decode the remaining codestream");
return OPJ_FALSE;
}
if (!p_start_x && !p_start_y && !p_end_x && !p_end_y) {
opj_event_msg(p_manager, EVT_INFO,
"No decoded area parameters, set the decoded area to the whole image\n");
p_j2k->m_specific_param.m_decoder.m_start_tile_x = 0;
p_j2k->m_specific_param.m_decoder.m_start_tile_y = 0;
p_j2k->m_specific_param.m_decoder.m_end_tile_x = l_cp->tw;
p_j2k->m_specific_param.m_decoder.m_end_tile_y = l_cp->th;
return OPJ_TRUE;
}
/* ----- */
/* Check if the positions provided by the user are correct */
/* Left */
if (p_start_x < 0) {
opj_event_msg(p_manager, EVT_ERROR,
"Left position of the decoded area (region_x0=%d) should be >= 0.\n",
p_start_x);
return OPJ_FALSE;
} else if ((OPJ_UINT32)p_start_x > l_image->x1) {
opj_event_msg(p_manager, EVT_ERROR,
"Left position of the decoded area (region_x0=%d) is outside the image area (Xsiz=%d).\n",
p_start_x, l_image->x1);
return OPJ_FALSE;
} else if ((OPJ_UINT32)p_start_x < l_image->x0) {
opj_event_msg(p_manager, EVT_WARNING,
"Left position of the decoded area (region_x0=%d) is outside the image area (XOsiz=%d).\n",
p_start_x, l_image->x0);
p_j2k->m_specific_param.m_decoder.m_start_tile_x = 0;
p_image->x0 = l_image->x0;
} else {
p_j2k->m_specific_param.m_decoder.m_start_tile_x = ((OPJ_UINT32)p_start_x -
l_cp->tx0) / l_cp->tdx;
p_image->x0 = (OPJ_UINT32)p_start_x;
}
/* Up */
if (p_start_x < 0) {
opj_event_msg(p_manager, EVT_ERROR,
"Up position of the decoded area (region_y0=%d) should be >= 0.\n",
p_start_y);
return OPJ_FALSE;
} else if ((OPJ_UINT32)p_start_y > l_image->y1) {
opj_event_msg(p_manager, EVT_ERROR,
"Up position of the decoded area (region_y0=%d) is outside the image area (Ysiz=%d).\n",
p_start_y, l_image->y1);
return OPJ_FALSE;
} else if ((OPJ_UINT32)p_start_y < l_image->y0) {
opj_event_msg(p_manager, EVT_WARNING,
"Up position of the decoded area (region_y0=%d) is outside the image area (YOsiz=%d).\n",
p_start_y, l_image->y0);
p_j2k->m_specific_param.m_decoder.m_start_tile_y = 0;
p_image->y0 = l_image->y0;
} else {
p_j2k->m_specific_param.m_decoder.m_start_tile_y = ((OPJ_UINT32)p_start_y -
l_cp->ty0) / l_cp->tdy;
p_image->y0 = (OPJ_UINT32)p_start_y;
}
/* Right */
if (p_end_x <= 0) {
opj_event_msg(p_manager, EVT_ERROR,
"Right position of the decoded area (region_x1=%d) should be > 0.\n",
p_end_x);
return OPJ_FALSE;
} else if ((OPJ_UINT32)p_end_x < l_image->x0) {
opj_event_msg(p_manager, EVT_ERROR,
"Right position of the decoded area (region_x1=%d) is outside the image area (XOsiz=%d).\n",
p_end_x, l_image->x0);
return OPJ_FALSE;
} else if ((OPJ_UINT32)p_end_x > l_image->x1) {
opj_event_msg(p_manager, EVT_WARNING,
"Right position of the decoded area (region_x1=%d) is outside the image area (Xsiz=%d).\n",
p_end_x, l_image->x1);
p_j2k->m_specific_param.m_decoder.m_end_tile_x = l_cp->tw;
p_image->x1 = l_image->x1;
} else {
p_j2k->m_specific_param.m_decoder.m_end_tile_x = (OPJ_UINT32)opj_int_ceildiv(
p_end_x - (OPJ_INT32)l_cp->tx0, (OPJ_INT32)l_cp->tdx);
p_image->x1 = (OPJ_UINT32)p_end_x;
}
/* Bottom */
if (p_end_y <= 0) {
opj_event_msg(p_manager, EVT_ERROR,
"Bottom position of the decoded area (region_y1=%d) should be > 0.\n",
p_end_y);
return OPJ_FALSE;
} else if ((OPJ_UINT32)p_end_y < l_image->y0) {
opj_event_msg(p_manager, EVT_ERROR,
"Bottom position of the decoded area (region_y1=%d) is outside the image area (YOsiz=%d).\n",
p_end_y, l_image->y0);
return OPJ_FALSE;
}
if ((OPJ_UINT32)p_end_y > l_image->y1) {
opj_event_msg(p_manager, EVT_WARNING,
"Bottom position of the decoded area (region_y1=%d) is outside the image area (Ysiz=%d).\n",
p_end_y, l_image->y1);
p_j2k->m_specific_param.m_decoder.m_end_tile_y = l_cp->th;
p_image->y1 = l_image->y1;
} else {
p_j2k->m_specific_param.m_decoder.m_end_tile_y = (OPJ_UINT32)opj_int_ceildiv(
p_end_y - (OPJ_INT32)l_cp->ty0, (OPJ_INT32)l_cp->tdy);
p_image->y1 = (OPJ_UINT32)p_end_y;
}
/* ----- */
p_j2k->m_specific_param.m_decoder.m_discard_tiles = 1;
l_img_comp = p_image->comps;
for (it_comp = 0; it_comp < p_image->numcomps; ++it_comp) {
OPJ_INT32 l_h, l_w;
l_img_comp->x0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->x0,
(OPJ_INT32)l_img_comp->dx);
l_img_comp->y0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->y0,
(OPJ_INT32)l_img_comp->dy);
l_comp_x1 = opj_int_ceildiv((OPJ_INT32)p_image->x1, (OPJ_INT32)l_img_comp->dx);
l_comp_y1 = opj_int_ceildiv((OPJ_INT32)p_image->y1, (OPJ_INT32)l_img_comp->dy);
l_w = opj_int_ceildivpow2(l_comp_x1, (OPJ_INT32)l_img_comp->factor)
- opj_int_ceildivpow2((OPJ_INT32)l_img_comp->x0, (OPJ_INT32)l_img_comp->factor);
if (l_w < 0) {
opj_event_msg(p_manager, EVT_ERROR,
"Size x of the decoded component image is incorrect (comp[%d].w=%d).\n",
it_comp, l_w);
return OPJ_FALSE;
}
l_img_comp->w = (OPJ_UINT32)l_w;
l_h = opj_int_ceildivpow2(l_comp_y1, (OPJ_INT32)l_img_comp->factor)
- opj_int_ceildivpow2((OPJ_INT32)l_img_comp->y0, (OPJ_INT32)l_img_comp->factor);
if (l_h < 0) {
opj_event_msg(p_manager, EVT_ERROR,
"Size y of the decoded component image is incorrect (comp[%d].h=%d).\n",
it_comp, l_h);
return OPJ_FALSE;
}
l_img_comp->h = (OPJ_UINT32)l_h;
l_img_comp++;
}
opj_event_msg(p_manager, EVT_INFO, "Setting decoding area to %d,%d,%d,%d\n",
p_image->x0, p_image->y0, p_image->x1, p_image->y1);
return OPJ_TRUE;
}
opj_j2k_t* opj_j2k_create_decompress(void)
{
opj_j2k_t *l_j2k = (opj_j2k_t*) opj_calloc(1, sizeof(opj_j2k_t));
if (!l_j2k) {
return 00;
}
l_j2k->m_is_decoder = 1;
l_j2k->m_cp.m_is_decoder = 1;
/* in the absence of JP2 boxes, consider different bit depth / sign */
/* per component is allowed */
l_j2k->m_cp.allow_different_bit_depth_sign = 1;
#ifdef OPJ_DISABLE_TPSOT_FIX
l_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction_checked = 1;
#endif
l_j2k->m_specific_param.m_decoder.m_default_tcp = (opj_tcp_t*) opj_calloc(1,
sizeof(opj_tcp_t));
if (!l_j2k->m_specific_param.m_decoder.m_default_tcp) {
opj_j2k_destroy(l_j2k);
return 00;
}
l_j2k->m_specific_param.m_decoder.m_header_data = (OPJ_BYTE *) opj_calloc(1,
OPJ_J2K_DEFAULT_HEADER_SIZE);
if (! l_j2k->m_specific_param.m_decoder.m_header_data) {
opj_j2k_destroy(l_j2k);
return 00;
}
l_j2k->m_specific_param.m_decoder.m_header_data_size =
OPJ_J2K_DEFAULT_HEADER_SIZE;
l_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec = -1 ;
l_j2k->m_specific_param.m_decoder.m_last_sot_read_pos = 0 ;
/* codestream index creation */
l_j2k->cstr_index = opj_j2k_create_cstr_index();
if (!l_j2k->cstr_index) {
opj_j2k_destroy(l_j2k);
return 00;
}
/* validation list creation */
l_j2k->m_validation_list = opj_procedure_list_create();
if (! l_j2k->m_validation_list) {
opj_j2k_destroy(l_j2k);
return 00;
}
/* execution list creation */
l_j2k->m_procedure_list = opj_procedure_list_create();
if (! l_j2k->m_procedure_list) {
opj_j2k_destroy(l_j2k);
return 00;
}
l_j2k->m_tp = opj_thread_pool_create(opj_j2k_get_default_thread_count());
if (!l_j2k->m_tp) {
l_j2k->m_tp = opj_thread_pool_create(0);
}
if (!l_j2k->m_tp) {
opj_j2k_destroy(l_j2k);
return NULL;
}
return l_j2k;
}
static opj_codestream_index_t* opj_j2k_create_cstr_index(void)
{
opj_codestream_index_t* cstr_index = (opj_codestream_index_t*)
opj_calloc(1, sizeof(opj_codestream_index_t));
if (!cstr_index) {
return NULL;
}
cstr_index->maxmarknum = 100;
cstr_index->marknum = 0;
cstr_index->marker = (opj_marker_info_t*)
opj_calloc(cstr_index->maxmarknum, sizeof(opj_marker_info_t));
if (!cstr_index-> marker) {
opj_free(cstr_index);
return NULL;
}
cstr_index->tile_index = NULL;
return cstr_index;
}
static OPJ_UINT32 opj_j2k_get_SPCod_SPCoc_size(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no)
{
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_tccp_t *l_tccp = 00;
/* preconditions */
assert(p_j2k != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_tile_no];
l_tccp = &l_tcp->tccps[p_comp_no];
/* preconditions again */
assert(p_tile_no < (l_cp->tw * l_cp->th));
assert(p_comp_no < p_j2k->m_private_image->numcomps);
if (l_tccp->csty & J2K_CCP_CSTY_PRT) {
return 5 + l_tccp->numresolutions;
} else {
return 5;
}
}
static OPJ_BOOL opj_j2k_compare_SPCod_SPCoc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no)
{
OPJ_UINT32 i;
opj_cp_t *l_cp = NULL;
opj_tcp_t *l_tcp = NULL;
opj_tccp_t *l_tccp0 = NULL;
opj_tccp_t *l_tccp1 = NULL;
/* preconditions */
assert(p_j2k != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_tile_no];
l_tccp0 = &l_tcp->tccps[p_first_comp_no];
l_tccp1 = &l_tcp->tccps[p_second_comp_no];
if (l_tccp0->numresolutions != l_tccp1->numresolutions) {
return OPJ_FALSE;
}
if (l_tccp0->cblkw != l_tccp1->cblkw) {
return OPJ_FALSE;
}
if (l_tccp0->cblkh != l_tccp1->cblkh) {
return OPJ_FALSE;
}
if (l_tccp0->cblksty != l_tccp1->cblksty) {
return OPJ_FALSE;
}
if (l_tccp0->qmfbid != l_tccp1->qmfbid) {
return OPJ_FALSE;
}
if ((l_tccp0->csty & J2K_CCP_CSTY_PRT) != (l_tccp1->csty & J2K_CCP_CSTY_PRT)) {
return OPJ_FALSE;
}
for (i = 0U; i < l_tccp0->numresolutions; ++i) {
if (l_tccp0->prcw[i] != l_tccp1->prcw[i]) {
return OPJ_FALSE;
}
if (l_tccp0->prch[i] != l_tccp1->prch[i]) {
return OPJ_FALSE;
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_SPCod_SPCoc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_header_size,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 i;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_tccp_t *l_tccp = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_header_size != 00);
assert(p_manager != 00);
assert(p_data != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_tile_no];
l_tccp = &l_tcp->tccps[p_comp_no];
/* preconditions again */
assert(p_tile_no < (l_cp->tw * l_cp->th));
assert(p_comp_no < (p_j2k->m_private_image->numcomps));
if (*p_header_size < 5) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing SPCod SPCoc element\n");
return OPJ_FALSE;
}
opj_write_bytes(p_data, l_tccp->numresolutions - 1, 1); /* SPcoc (D) */
++p_data;
opj_write_bytes(p_data, l_tccp->cblkw - 2, 1); /* SPcoc (E) */
++p_data;
opj_write_bytes(p_data, l_tccp->cblkh - 2, 1); /* SPcoc (F) */
++p_data;
opj_write_bytes(p_data, l_tccp->cblksty,
1); /* SPcoc (G) */
++p_data;
opj_write_bytes(p_data, l_tccp->qmfbid,
1); /* SPcoc (H) */
++p_data;
*p_header_size = *p_header_size - 5;
if (l_tccp->csty & J2K_CCP_CSTY_PRT) {
if (*p_header_size < l_tccp->numresolutions) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing SPCod SPCoc element\n");
return OPJ_FALSE;
}
for (i = 0; i < l_tccp->numresolutions; ++i) {
opj_write_bytes(p_data, l_tccp->prcw[i] + (l_tccp->prch[i] << 4),
1); /* SPcoc (I_i) */
++p_data;
}
*p_header_size = *p_header_size - l_tccp->numresolutions;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_read_SPCod_SPCoc(opj_j2k_t *p_j2k,
OPJ_UINT32 compno,
OPJ_BYTE * p_header_data,
OPJ_UINT32 * p_header_size,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 i, l_tmp;
opj_cp_t *l_cp = NULL;
opj_tcp_t *l_tcp = NULL;
opj_tccp_t *l_tccp = NULL;
OPJ_BYTE * l_current_ptr = NULL;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_header_data != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
/* precondition again */
assert(compno < p_j2k->m_private_image->numcomps);
l_tccp = &l_tcp->tccps[compno];
l_current_ptr = p_header_data;
/* make sure room is sufficient */
if (*p_header_size < 5) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading SPCod SPCoc element\n");
return OPJ_FALSE;
}
opj_read_bytes(l_current_ptr, &l_tccp->numresolutions,
1); /* SPcox (D) */
++l_tccp->numresolutions; /* tccp->numresolutions = read() + 1 */
if (l_tccp->numresolutions > OPJ_J2K_MAXRLVLS) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid value for numresolutions : %d, max value is set in openjpeg.h at %d\n",
l_tccp->numresolutions, OPJ_J2K_MAXRLVLS);
return OPJ_FALSE;
}
++l_current_ptr;
/* If user wants to remove more resolutions than the codestream contains, return error */
if (l_cp->m_specific_param.m_dec.m_reduce >= l_tccp->numresolutions) {
opj_event_msg(p_manager, EVT_ERROR,
"Error decoding component %d.\nThe number of resolutions to remove is higher than the number "
"of resolutions of this component\nModify the cp_reduce parameter.\n\n",
compno);
p_j2k->m_specific_param.m_decoder.m_state |=
0x8000;/* FIXME J2K_DEC_STATE_ERR;*/
return OPJ_FALSE;
}
opj_read_bytes(l_current_ptr, &l_tccp->cblkw, 1); /* SPcoc (E) */
++l_current_ptr;
l_tccp->cblkw += 2;
opj_read_bytes(l_current_ptr, &l_tccp->cblkh, 1); /* SPcoc (F) */
++l_current_ptr;
l_tccp->cblkh += 2;
if ((l_tccp->cblkw > 10) || (l_tccp->cblkh > 10) ||
((l_tccp->cblkw + l_tccp->cblkh) > 12)) {
opj_event_msg(p_manager, EVT_ERROR,
"Error reading SPCod SPCoc element, Invalid cblkw/cblkh combination\n");
return OPJ_FALSE;
}
opj_read_bytes(l_current_ptr, &l_tccp->cblksty, 1); /* SPcoc (G) */
++l_current_ptr;
if (l_tccp->cblksty & 0xC0U) { /* 2 msb are reserved, assume we can't read */
opj_event_msg(p_manager, EVT_ERROR,
"Error reading SPCod SPCoc element, Invalid code-block style found\n");
return OPJ_FALSE;
}
opj_read_bytes(l_current_ptr, &l_tccp->qmfbid, 1); /* SPcoc (H) */
++l_current_ptr;
*p_header_size = *p_header_size - 5;
/* use custom precinct size ? */
if (l_tccp->csty & J2K_CCP_CSTY_PRT) {
if (*p_header_size < l_tccp->numresolutions) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading SPCod SPCoc element\n");
return OPJ_FALSE;
}
for (i = 0; i < l_tccp->numresolutions; ++i) {
opj_read_bytes(l_current_ptr, &l_tmp, 1); /* SPcoc (I_i) */
++l_current_ptr;
/* Precinct exponent 0 is only allowed for lowest resolution level (Table A.21) */
if ((i != 0) && (((l_tmp & 0xf) == 0) || ((l_tmp >> 4) == 0))) {
opj_event_msg(p_manager, EVT_ERROR, "Invalid precinct size\n");
return OPJ_FALSE;
}
l_tccp->prcw[i] = l_tmp & 0xf;
l_tccp->prch[i] = l_tmp >> 4;
}
*p_header_size = *p_header_size - l_tccp->numresolutions;
} else {
/* set default size for the precinct width and height */
for (i = 0; i < l_tccp->numresolutions; ++i) {
l_tccp->prcw[i] = 15;
l_tccp->prch[i] = 15;
}
}
#ifdef WIP_REMOVE_MSD
/* INDEX >> */
if (p_j2k->cstr_info && compno == 0) {
OPJ_UINT32 l_data_size = l_tccp->numresolutions * sizeof(OPJ_UINT32);
p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].cblkh =
l_tccp->cblkh;
p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].cblkw =
l_tccp->cblkw;
p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].numresolutions
= l_tccp->numresolutions;
p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].cblksty =
l_tccp->cblksty;
p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].qmfbid =
l_tccp->qmfbid;
memcpy(p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].pdx, l_tccp->prcw,
l_data_size);
memcpy(p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].pdy, l_tccp->prch,
l_data_size);
}
/* << INDEX */
#endif
return OPJ_TRUE;
}
static void opj_j2k_copy_tile_component_parameters(opj_j2k_t *p_j2k)
{
/* loop */
OPJ_UINT32 i;
opj_cp_t *l_cp = NULL;
opj_tcp_t *l_tcp = NULL;
opj_tccp_t *l_ref_tccp = NULL, *l_copied_tccp = NULL;
OPJ_UINT32 l_prc_size;
/* preconditions */
assert(p_j2k != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH)
?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
l_ref_tccp = &l_tcp->tccps[0];
l_copied_tccp = l_ref_tccp + 1;
l_prc_size = l_ref_tccp->numresolutions * (OPJ_UINT32)sizeof(OPJ_UINT32);
for (i = 1; i < p_j2k->m_private_image->numcomps; ++i) {
l_copied_tccp->numresolutions = l_ref_tccp->numresolutions;
l_copied_tccp->cblkw = l_ref_tccp->cblkw;
l_copied_tccp->cblkh = l_ref_tccp->cblkh;
l_copied_tccp->cblksty = l_ref_tccp->cblksty;
l_copied_tccp->qmfbid = l_ref_tccp->qmfbid;
memcpy(l_copied_tccp->prcw, l_ref_tccp->prcw, l_prc_size);
memcpy(l_copied_tccp->prch, l_ref_tccp->prch, l_prc_size);
++l_copied_tccp;
}
}
static OPJ_UINT32 opj_j2k_get_SQcd_SQcc_size(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no)
{
OPJ_UINT32 l_num_bands;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_tccp_t *l_tccp = 00;
/* preconditions */
assert(p_j2k != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_tile_no];
l_tccp = &l_tcp->tccps[p_comp_no];
/* preconditions again */
assert(p_tile_no < l_cp->tw * l_cp->th);
assert(p_comp_no < p_j2k->m_private_image->numcomps);
l_num_bands = (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 1 :
(l_tccp->numresolutions * 3 - 2);
if (l_tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) {
return 1 + l_num_bands;
} else {
return 1 + 2 * l_num_bands;
}
}
static OPJ_BOOL opj_j2k_compare_SQcd_SQcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no)
{
opj_cp_t *l_cp = NULL;
opj_tcp_t *l_tcp = NULL;
opj_tccp_t *l_tccp0 = NULL;
opj_tccp_t *l_tccp1 = NULL;
OPJ_UINT32 l_band_no, l_num_bands;
/* preconditions */
assert(p_j2k != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_tile_no];
l_tccp0 = &l_tcp->tccps[p_first_comp_no];
l_tccp1 = &l_tcp->tccps[p_second_comp_no];
if (l_tccp0->qntsty != l_tccp1->qntsty) {
return OPJ_FALSE;
}
if (l_tccp0->numgbits != l_tccp1->numgbits) {
return OPJ_FALSE;
}
if (l_tccp0->qntsty == J2K_CCP_QNTSTY_SIQNT) {
l_num_bands = 1U;
} else {
l_num_bands = l_tccp0->numresolutions * 3U - 2U;
if (l_num_bands != (l_tccp1->numresolutions * 3U - 2U)) {
return OPJ_FALSE;
}
}
for (l_band_no = 0; l_band_no < l_num_bands; ++l_band_no) {
if (l_tccp0->stepsizes[l_band_no].expn != l_tccp1->stepsizes[l_band_no].expn) {
return OPJ_FALSE;
}
}
if (l_tccp0->qntsty != J2K_CCP_QNTSTY_NOQNT) {
for (l_band_no = 0; l_band_no < l_num_bands; ++l_band_no) {
if (l_tccp0->stepsizes[l_band_no].mant != l_tccp1->stepsizes[l_band_no].mant) {
return OPJ_FALSE;
}
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_SQcd_SQcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_header_size,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 l_header_size;
OPJ_UINT32 l_band_no, l_num_bands;
OPJ_UINT32 l_expn, l_mant;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_tccp_t *l_tccp = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_header_size != 00);
assert(p_manager != 00);
assert(p_data != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_tile_no];
l_tccp = &l_tcp->tccps[p_comp_no];
/* preconditions again */
assert(p_tile_no < l_cp->tw * l_cp->th);
assert(p_comp_no < p_j2k->m_private_image->numcomps);
l_num_bands = (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 1 :
(l_tccp->numresolutions * 3 - 2);
if (l_tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) {
l_header_size = 1 + l_num_bands;
if (*p_header_size < l_header_size) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing SQcd SQcc element\n");
return OPJ_FALSE;
}
opj_write_bytes(p_data, l_tccp->qntsty + (l_tccp->numgbits << 5),
1); /* Sqcx */
++p_data;
for (l_band_no = 0; l_band_no < l_num_bands; ++l_band_no) {
l_expn = (OPJ_UINT32)l_tccp->stepsizes[l_band_no].expn;
opj_write_bytes(p_data, l_expn << 3, 1); /* SPqcx_i */
++p_data;
}
} else {
l_header_size = 1 + 2 * l_num_bands;
if (*p_header_size < l_header_size) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing SQcd SQcc element\n");
return OPJ_FALSE;
}
opj_write_bytes(p_data, l_tccp->qntsty + (l_tccp->numgbits << 5),
1); /* Sqcx */
++p_data;
for (l_band_no = 0; l_band_no < l_num_bands; ++l_band_no) {
l_expn = (OPJ_UINT32)l_tccp->stepsizes[l_band_no].expn;
l_mant = (OPJ_UINT32)l_tccp->stepsizes[l_band_no].mant;
opj_write_bytes(p_data, (l_expn << 11) + l_mant, 2); /* SPqcx_i */
p_data += 2;
}
}
*p_header_size = *p_header_size - l_header_size;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_read_SQcd_SQcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
OPJ_BYTE* p_header_data,
OPJ_UINT32 * p_header_size,
opj_event_mgr_t * p_manager
)
{
/* loop*/
OPJ_UINT32 l_band_no;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_tccp_t *l_tccp = 00;
OPJ_BYTE * l_current_ptr = 00;
OPJ_UINT32 l_tmp, l_num_band;
/* preconditions*/
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_header_data != 00);
l_cp = &(p_j2k->m_cp);
/* come from tile part header or main header ?*/
l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH)
?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
/* precondition again*/
assert(p_comp_no < p_j2k->m_private_image->numcomps);
l_tccp = &l_tcp->tccps[p_comp_no];
l_current_ptr = p_header_data;
if (*p_header_size < 1) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading SQcd or SQcc element\n");
return OPJ_FALSE;
}
*p_header_size -= 1;
opj_read_bytes(l_current_ptr, &l_tmp, 1); /* Sqcx */
++l_current_ptr;
l_tccp->qntsty = l_tmp & 0x1f;
l_tccp->numgbits = l_tmp >> 5;
if (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) {
l_num_band = 1;
} else {
l_num_band = (l_tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) ?
(*p_header_size) :
(*p_header_size) / 2;
if (l_num_band > OPJ_J2K_MAXBANDS) {
opj_event_msg(p_manager, EVT_WARNING,
"While reading CCP_QNTSTY element inside QCD or QCC marker segment, "
"number of subbands (%d) is greater to OPJ_J2K_MAXBANDS (%d). So we limit the number of elements stored to "
"OPJ_J2K_MAXBANDS (%d) and skip the rest. \n", l_num_band, OPJ_J2K_MAXBANDS,
OPJ_J2K_MAXBANDS);
/*return OPJ_FALSE;*/
}
}
#ifdef USE_JPWL
if (l_cp->correct) {
/* if JPWL is on, we check whether there are too many subbands */
if (/*(l_num_band < 0) ||*/ (l_num_band >= OPJ_J2K_MAXBANDS)) {
opj_event_msg(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
"JPWL: bad number of subbands in Sqcx (%d)\n",
l_num_band);
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
/* we try to correct */
l_num_band = 1;
opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust them\n"
"- setting number of bands to %d => HYPOTHESIS!!!\n",
l_num_band);
};
};
#endif /* USE_JPWL */
if (l_tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) {
for (l_band_no = 0; l_band_no < l_num_band; l_band_no++) {
opj_read_bytes(l_current_ptr, &l_tmp, 1); /* SPqcx_i */
++l_current_ptr;
if (l_band_no < OPJ_J2K_MAXBANDS) {
l_tccp->stepsizes[l_band_no].expn = (OPJ_INT32)(l_tmp >> 3);
l_tccp->stepsizes[l_band_no].mant = 0;
}
}
*p_header_size = *p_header_size - l_num_band;
} else {
for (l_band_no = 0; l_band_no < l_num_band; l_band_no++) {
opj_read_bytes(l_current_ptr, &l_tmp, 2); /* SPqcx_i */
l_current_ptr += 2;
if (l_band_no < OPJ_J2K_MAXBANDS) {
l_tccp->stepsizes[l_band_no].expn = (OPJ_INT32)(l_tmp >> 11);
l_tccp->stepsizes[l_band_no].mant = l_tmp & 0x7ff;
}
}
*p_header_size = *p_header_size - 2 * l_num_band;
}
/* Add Antonin : if scalar_derived -> compute other stepsizes */
if (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) {
for (l_band_no = 1; l_band_no < OPJ_J2K_MAXBANDS; l_band_no++) {
l_tccp->stepsizes[l_band_no].expn =
((OPJ_INT32)(l_tccp->stepsizes[0].expn) - (OPJ_INT32)((l_band_no - 1) / 3) > 0)
?
(OPJ_INT32)(l_tccp->stepsizes[0].expn) - (OPJ_INT32)((l_band_no - 1) / 3) : 0;
l_tccp->stepsizes[l_band_no].mant = l_tccp->stepsizes[0].mant;
}
}
return OPJ_TRUE;
}
static void opj_j2k_copy_tile_quantization_parameters(opj_j2k_t *p_j2k)
{
OPJ_UINT32 i;
opj_cp_t *l_cp = NULL;
opj_tcp_t *l_tcp = NULL;
opj_tccp_t *l_ref_tccp = NULL;
opj_tccp_t *l_copied_tccp = NULL;
OPJ_UINT32 l_size;
/* preconditions */
assert(p_j2k != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH ?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
l_ref_tccp = &l_tcp->tccps[0];
l_copied_tccp = l_ref_tccp + 1;
l_size = OPJ_J2K_MAXBANDS * sizeof(opj_stepsize_t);
for (i = 1; i < p_j2k->m_private_image->numcomps; ++i) {
l_copied_tccp->qntsty = l_ref_tccp->qntsty;
l_copied_tccp->numgbits = l_ref_tccp->numgbits;
memcpy(l_copied_tccp->stepsizes, l_ref_tccp->stepsizes, l_size);
++l_copied_tccp;
}
}
static void opj_j2k_dump_tile_info(opj_tcp_t * l_default_tile,
OPJ_INT32 numcomps, FILE* out_stream)
{
if (l_default_tile) {
OPJ_INT32 compno;
fprintf(out_stream, "\t default tile {\n");
fprintf(out_stream, "\t\t csty=%#x\n", l_default_tile->csty);
fprintf(out_stream, "\t\t prg=%#x\n", l_default_tile->prg);
fprintf(out_stream, "\t\t numlayers=%d\n", l_default_tile->numlayers);
fprintf(out_stream, "\t\t mct=%x\n", l_default_tile->mct);
for (compno = 0; compno < numcomps; compno++) {
opj_tccp_t *l_tccp = &(l_default_tile->tccps[compno]);
OPJ_UINT32 resno;
OPJ_INT32 bandno, numbands;
/* coding style*/
fprintf(out_stream, "\t\t comp %d {\n", compno);
fprintf(out_stream, "\t\t\t csty=%#x\n", l_tccp->csty);
fprintf(out_stream, "\t\t\t numresolutions=%d\n", l_tccp->numresolutions);
fprintf(out_stream, "\t\t\t cblkw=2^%d\n", l_tccp->cblkw);
fprintf(out_stream, "\t\t\t cblkh=2^%d\n", l_tccp->cblkh);
fprintf(out_stream, "\t\t\t cblksty=%#x\n", l_tccp->cblksty);
fprintf(out_stream, "\t\t\t qmfbid=%d\n", l_tccp->qmfbid);
fprintf(out_stream, "\t\t\t preccintsize (w,h)=");
for (resno = 0; resno < l_tccp->numresolutions; resno++) {
fprintf(out_stream, "(%d,%d) ", l_tccp->prcw[resno], l_tccp->prch[resno]);
}
fprintf(out_stream, "\n");
/* quantization style*/
fprintf(out_stream, "\t\t\t qntsty=%d\n", l_tccp->qntsty);
fprintf(out_stream, "\t\t\t numgbits=%d\n", l_tccp->numgbits);
fprintf(out_stream, "\t\t\t stepsizes (m,e)=");
numbands = (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 1 :
(OPJ_INT32)l_tccp->numresolutions * 3 - 2;
for (bandno = 0; bandno < numbands; bandno++) {
fprintf(out_stream, "(%d,%d) ", l_tccp->stepsizes[bandno].mant,
l_tccp->stepsizes[bandno].expn);
}
fprintf(out_stream, "\n");
/* RGN value*/
fprintf(out_stream, "\t\t\t roishift=%d\n", l_tccp->roishift);
fprintf(out_stream, "\t\t }\n");
} /*end of component of default tile*/
fprintf(out_stream, "\t }\n"); /*end of default tile*/
}
}
void j2k_dump(opj_j2k_t* p_j2k, OPJ_INT32 flag, FILE* out_stream)
{
/* Check if the flag is compatible with j2k file*/
if ((flag & OPJ_JP2_INFO) || (flag & OPJ_JP2_IND)) {
fprintf(out_stream, "Wrong flag\n");
return;
}
/* Dump the image_header */
if (flag & OPJ_IMG_INFO) {
if (p_j2k->m_private_image) {
j2k_dump_image_header(p_j2k->m_private_image, 0, out_stream);
}
}
/* Dump the codestream info from main header */
if (flag & OPJ_J2K_MH_INFO) {
if (p_j2k->m_private_image) {
opj_j2k_dump_MH_info(p_j2k, out_stream);
}
}
/* Dump all tile/codestream info */
if (flag & OPJ_J2K_TCH_INFO) {
OPJ_UINT32 l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
OPJ_UINT32 i;
opj_tcp_t * l_tcp = p_j2k->m_cp.tcps;
if (p_j2k->m_private_image) {
for (i = 0; i < l_nb_tiles; ++i) {
opj_j2k_dump_tile_info(l_tcp, (OPJ_INT32)p_j2k->m_private_image->numcomps,
out_stream);
++l_tcp;
}
}
}
/* Dump the codestream info of the current tile */
if (flag & OPJ_J2K_TH_INFO) {
}
/* Dump the codestream index from main header */
if (flag & OPJ_J2K_MH_IND) {
opj_j2k_dump_MH_index(p_j2k, out_stream);
}
/* Dump the codestream index of the current tile */
if (flag & OPJ_J2K_TH_IND) {
}
}
static void opj_j2k_dump_MH_index(opj_j2k_t* p_j2k, FILE* out_stream)
{
opj_codestream_index_t* cstr_index = p_j2k->cstr_index;
OPJ_UINT32 it_marker, it_tile, it_tile_part;
fprintf(out_stream, "Codestream index from main header: {\n");
fprintf(out_stream, "\t Main header start position=%" PRIi64 "\n"
"\t Main header end position=%" PRIi64 "\n",
cstr_index->main_head_start, cstr_index->main_head_end);
fprintf(out_stream, "\t Marker list: {\n");
if (cstr_index->marker) {
for (it_marker = 0; it_marker < cstr_index->marknum ; it_marker++) {
fprintf(out_stream, "\t\t type=%#x, pos=%" PRIi64 ", len=%d\n",
cstr_index->marker[it_marker].type,
cstr_index->marker[it_marker].pos,
cstr_index->marker[it_marker].len);
}
}
fprintf(out_stream, "\t }\n");
if (cstr_index->tile_index) {
/* Simple test to avoid to write empty information*/
OPJ_UINT32 l_acc_nb_of_tile_part = 0;
for (it_tile = 0; it_tile < cstr_index->nb_of_tiles ; it_tile++) {
l_acc_nb_of_tile_part += cstr_index->tile_index[it_tile].nb_tps;
}
if (l_acc_nb_of_tile_part) {
fprintf(out_stream, "\t Tile index: {\n");
for (it_tile = 0; it_tile < cstr_index->nb_of_tiles ; it_tile++) {
OPJ_UINT32 nb_of_tile_part = cstr_index->tile_index[it_tile].nb_tps;
fprintf(out_stream, "\t\t nb of tile-part in tile [%d]=%d\n", it_tile,
nb_of_tile_part);
if (cstr_index->tile_index[it_tile].tp_index) {
for (it_tile_part = 0; it_tile_part < nb_of_tile_part; it_tile_part++) {
fprintf(out_stream, "\t\t\t tile-part[%d]: star_pos=%" PRIi64 ", end_header=%"
PRIi64 ", end_pos=%" PRIi64 ".\n",
it_tile_part,
cstr_index->tile_index[it_tile].tp_index[it_tile_part].start_pos,
cstr_index->tile_index[it_tile].tp_index[it_tile_part].end_header,
cstr_index->tile_index[it_tile].tp_index[it_tile_part].end_pos);
}
}
if (cstr_index->tile_index[it_tile].marker) {
for (it_marker = 0; it_marker < cstr_index->tile_index[it_tile].marknum ;
it_marker++) {
fprintf(out_stream, "\t\t type=%#x, pos=%" PRIi64 ", len=%d\n",
cstr_index->tile_index[it_tile].marker[it_marker].type,
cstr_index->tile_index[it_tile].marker[it_marker].pos,
cstr_index->tile_index[it_tile].marker[it_marker].len);
}
}
}
fprintf(out_stream, "\t }\n");
}
}
fprintf(out_stream, "}\n");
}
static void opj_j2k_dump_MH_info(opj_j2k_t* p_j2k, FILE* out_stream)
{
fprintf(out_stream, "Codestream info from main header: {\n");
fprintf(out_stream, "\t tx0=%d, ty0=%d\n", p_j2k->m_cp.tx0, p_j2k->m_cp.ty0);
fprintf(out_stream, "\t tdx=%d, tdy=%d\n", p_j2k->m_cp.tdx, p_j2k->m_cp.tdy);
fprintf(out_stream, "\t tw=%d, th=%d\n", p_j2k->m_cp.tw, p_j2k->m_cp.th);
opj_j2k_dump_tile_info(p_j2k->m_specific_param.m_decoder.m_default_tcp,
(OPJ_INT32)p_j2k->m_private_image->numcomps, out_stream);
fprintf(out_stream, "}\n");
}
void j2k_dump_image_header(opj_image_t* img_header, OPJ_BOOL dev_dump_flag,
FILE* out_stream)
{
char tab[2];
if (dev_dump_flag) {
fprintf(stdout, "[DEV] Dump an image_header struct {\n");
tab[0] = '\0';
} else {
fprintf(out_stream, "Image info {\n");
tab[0] = '\t';
tab[1] = '\0';
}
fprintf(out_stream, "%s x0=%d, y0=%d\n", tab, img_header->x0, img_header->y0);
fprintf(out_stream, "%s x1=%d, y1=%d\n", tab, img_header->x1,
img_header->y1);
fprintf(out_stream, "%s numcomps=%d\n", tab, img_header->numcomps);
if (img_header->comps) {
OPJ_UINT32 compno;
for (compno = 0; compno < img_header->numcomps; compno++) {
fprintf(out_stream, "%s\t component %d {\n", tab, compno);
j2k_dump_image_comp_header(&(img_header->comps[compno]), dev_dump_flag,
out_stream);
fprintf(out_stream, "%s}\n", tab);
}
}
fprintf(out_stream, "}\n");
}
void j2k_dump_image_comp_header(opj_image_comp_t* comp_header,
OPJ_BOOL dev_dump_flag, FILE* out_stream)
{
char tab[3];
if (dev_dump_flag) {
fprintf(stdout, "[DEV] Dump an image_comp_header struct {\n");
tab[0] = '\0';
} else {
tab[0] = '\t';
tab[1] = '\t';
tab[2] = '\0';
}
fprintf(out_stream, "%s dx=%d, dy=%d\n", tab, comp_header->dx, comp_header->dy);
fprintf(out_stream, "%s prec=%d\n", tab, comp_header->prec);
fprintf(out_stream, "%s sgnd=%d\n", tab, comp_header->sgnd);
if (dev_dump_flag) {
fprintf(out_stream, "}\n");
}
}
opj_codestream_info_v2_t* j2k_get_cstr_info(opj_j2k_t* p_j2k)
{
OPJ_UINT32 compno;
OPJ_UINT32 numcomps = p_j2k->m_private_image->numcomps;
opj_tcp_t *l_default_tile;
opj_codestream_info_v2_t* cstr_info = (opj_codestream_info_v2_t*) opj_calloc(1,
sizeof(opj_codestream_info_v2_t));
if (!cstr_info) {
return NULL;
}
cstr_info->nbcomps = p_j2k->m_private_image->numcomps;
cstr_info->tx0 = p_j2k->m_cp.tx0;
cstr_info->ty0 = p_j2k->m_cp.ty0;
cstr_info->tdx = p_j2k->m_cp.tdx;
cstr_info->tdy = p_j2k->m_cp.tdy;
cstr_info->tw = p_j2k->m_cp.tw;
cstr_info->th = p_j2k->m_cp.th;
cstr_info->tile_info = NULL; /* Not fill from the main header*/
l_default_tile = p_j2k->m_specific_param.m_decoder.m_default_tcp;
cstr_info->m_default_tile_info.csty = l_default_tile->csty;
cstr_info->m_default_tile_info.prg = l_default_tile->prg;
cstr_info->m_default_tile_info.numlayers = l_default_tile->numlayers;
cstr_info->m_default_tile_info.mct = l_default_tile->mct;
cstr_info->m_default_tile_info.tccp_info = (opj_tccp_info_t*) opj_calloc(
cstr_info->nbcomps, sizeof(opj_tccp_info_t));
if (!cstr_info->m_default_tile_info.tccp_info) {
opj_destroy_cstr_info(&cstr_info);
return NULL;
}
for (compno = 0; compno < numcomps; compno++) {
opj_tccp_t *l_tccp = &(l_default_tile->tccps[compno]);
opj_tccp_info_t *l_tccp_info = &
(cstr_info->m_default_tile_info.tccp_info[compno]);
OPJ_INT32 bandno, numbands;
/* coding style*/
l_tccp_info->csty = l_tccp->csty;
l_tccp_info->numresolutions = l_tccp->numresolutions;
l_tccp_info->cblkw = l_tccp->cblkw;
l_tccp_info->cblkh = l_tccp->cblkh;
l_tccp_info->cblksty = l_tccp->cblksty;
l_tccp_info->qmfbid = l_tccp->qmfbid;
if (l_tccp->numresolutions < OPJ_J2K_MAXRLVLS) {
memcpy(l_tccp_info->prch, l_tccp->prch, l_tccp->numresolutions);
memcpy(l_tccp_info->prcw, l_tccp->prcw, l_tccp->numresolutions);
}
/* quantization style*/
l_tccp_info->qntsty = l_tccp->qntsty;
l_tccp_info->numgbits = l_tccp->numgbits;
numbands = (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 1 :
(OPJ_INT32)l_tccp->numresolutions * 3 - 2;
if (numbands < OPJ_J2K_MAXBANDS) {
for (bandno = 0; bandno < numbands; bandno++) {
l_tccp_info->stepsizes_mant[bandno] = (OPJ_UINT32)
l_tccp->stepsizes[bandno].mant;
l_tccp_info->stepsizes_expn[bandno] = (OPJ_UINT32)
l_tccp->stepsizes[bandno].expn;
}
}
/* RGN value*/
l_tccp_info->roishift = l_tccp->roishift;
}
return cstr_info;
}
opj_codestream_index_t* j2k_get_cstr_index(opj_j2k_t* p_j2k)
{
opj_codestream_index_t* l_cstr_index = (opj_codestream_index_t*)
opj_calloc(1, sizeof(opj_codestream_index_t));
if (!l_cstr_index) {
return NULL;
}
l_cstr_index->main_head_start = p_j2k->cstr_index->main_head_start;
l_cstr_index->main_head_end = p_j2k->cstr_index->main_head_end;
l_cstr_index->codestream_size = p_j2k->cstr_index->codestream_size;
l_cstr_index->marknum = p_j2k->cstr_index->marknum;
l_cstr_index->marker = (opj_marker_info_t*)opj_malloc(l_cstr_index->marknum *
sizeof(opj_marker_info_t));
if (!l_cstr_index->marker) {
opj_free(l_cstr_index);
return NULL;
}
if (p_j2k->cstr_index->marker) {
memcpy(l_cstr_index->marker, p_j2k->cstr_index->marker,
l_cstr_index->marknum * sizeof(opj_marker_info_t));
} else {
opj_free(l_cstr_index->marker);
l_cstr_index->marker = NULL;
}
l_cstr_index->nb_of_tiles = p_j2k->cstr_index->nb_of_tiles;
l_cstr_index->tile_index = (opj_tile_index_t*)opj_calloc(
l_cstr_index->nb_of_tiles, sizeof(opj_tile_index_t));
if (!l_cstr_index->tile_index) {
opj_free(l_cstr_index->marker);
opj_free(l_cstr_index);
return NULL;
}
if (!p_j2k->cstr_index->tile_index) {
opj_free(l_cstr_index->tile_index);
l_cstr_index->tile_index = NULL;
} else {
OPJ_UINT32 it_tile = 0;
for (it_tile = 0; it_tile < l_cstr_index->nb_of_tiles; it_tile++) {
/* Tile Marker*/
l_cstr_index->tile_index[it_tile].marknum =
p_j2k->cstr_index->tile_index[it_tile].marknum;
l_cstr_index->tile_index[it_tile].marker =
(opj_marker_info_t*)opj_malloc(l_cstr_index->tile_index[it_tile].marknum *
sizeof(opj_marker_info_t));
if (!l_cstr_index->tile_index[it_tile].marker) {
OPJ_UINT32 it_tile_free;
for (it_tile_free = 0; it_tile_free < it_tile; it_tile_free++) {
opj_free(l_cstr_index->tile_index[it_tile_free].marker);
}
opj_free(l_cstr_index->tile_index);
opj_free(l_cstr_index->marker);
opj_free(l_cstr_index);
return NULL;
}
if (p_j2k->cstr_index->tile_index[it_tile].marker)
memcpy(l_cstr_index->tile_index[it_tile].marker,
p_j2k->cstr_index->tile_index[it_tile].marker,
l_cstr_index->tile_index[it_tile].marknum * sizeof(opj_marker_info_t));
else {
opj_free(l_cstr_index->tile_index[it_tile].marker);
l_cstr_index->tile_index[it_tile].marker = NULL;
}
/* Tile part index*/
l_cstr_index->tile_index[it_tile].nb_tps =
p_j2k->cstr_index->tile_index[it_tile].nb_tps;
l_cstr_index->tile_index[it_tile].tp_index =
(opj_tp_index_t*)opj_malloc(l_cstr_index->tile_index[it_tile].nb_tps * sizeof(
opj_tp_index_t));
if (!l_cstr_index->tile_index[it_tile].tp_index) {
OPJ_UINT32 it_tile_free;
for (it_tile_free = 0; it_tile_free < it_tile; it_tile_free++) {
opj_free(l_cstr_index->tile_index[it_tile_free].marker);
opj_free(l_cstr_index->tile_index[it_tile_free].tp_index);
}
opj_free(l_cstr_index->tile_index);
opj_free(l_cstr_index->marker);
opj_free(l_cstr_index);
return NULL;
}
if (p_j2k->cstr_index->tile_index[it_tile].tp_index) {
memcpy(l_cstr_index->tile_index[it_tile].tp_index,
p_j2k->cstr_index->tile_index[it_tile].tp_index,
l_cstr_index->tile_index[it_tile].nb_tps * sizeof(opj_tp_index_t));
} else {
opj_free(l_cstr_index->tile_index[it_tile].tp_index);
l_cstr_index->tile_index[it_tile].tp_index = NULL;
}
/* Packet index (NOT USED)*/
l_cstr_index->tile_index[it_tile].nb_packet = 0;
l_cstr_index->tile_index[it_tile].packet_index = NULL;
}
}
return l_cstr_index;
}
static OPJ_BOOL opj_j2k_allocate_tile_element_cstr_index(opj_j2k_t *p_j2k)
{
OPJ_UINT32 it_tile = 0;
p_j2k->cstr_index->nb_of_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th;
p_j2k->cstr_index->tile_index = (opj_tile_index_t*)opj_calloc(
p_j2k->cstr_index->nb_of_tiles, sizeof(opj_tile_index_t));
if (!p_j2k->cstr_index->tile_index) {
return OPJ_FALSE;
}
for (it_tile = 0; it_tile < p_j2k->cstr_index->nb_of_tiles; it_tile++) {
p_j2k->cstr_index->tile_index[it_tile].maxmarknum = 100;
p_j2k->cstr_index->tile_index[it_tile].marknum = 0;
p_j2k->cstr_index->tile_index[it_tile].marker = (opj_marker_info_t*)
opj_calloc(p_j2k->cstr_index->tile_index[it_tile].maxmarknum,
sizeof(opj_marker_info_t));
if (!p_j2k->cstr_index->tile_index[it_tile].marker) {
return OPJ_FALSE;
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_decode_tiles(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_BOOL l_go_on = OPJ_TRUE;
OPJ_UINT32 l_current_tile_no;
OPJ_UINT32 l_data_size, l_max_data_size;
OPJ_INT32 l_tile_x0, l_tile_y0, l_tile_x1, l_tile_y1;
OPJ_UINT32 l_nb_comps;
OPJ_BYTE * l_current_data;
OPJ_UINT32 nr_tiles = 0;
/* Particular case for whole single tile decoding */
/* We can avoid allocating intermediate tile buffers */
if (p_j2k->m_cp.tw == 1 && p_j2k->m_cp.th == 1 &&
p_j2k->m_cp.tx0 == 0 && p_j2k->m_cp.ty0 == 0 &&
p_j2k->m_output_image->x0 == 0 &&
p_j2k->m_output_image->y0 == 0 &&
p_j2k->m_output_image->x1 == p_j2k->m_cp.tdx &&
p_j2k->m_output_image->y1 == p_j2k->m_cp.tdy &&
p_j2k->m_output_image->comps[0].factor == 0) {
OPJ_UINT32 i;
if (! opj_j2k_read_tile_header(p_j2k,
&l_current_tile_no,
&l_data_size,
&l_tile_x0, &l_tile_y0,
&l_tile_x1, &l_tile_y1,
&l_nb_comps,
&l_go_on,
p_stream,
p_manager)) {
return OPJ_FALSE;
}
if (! opj_j2k_decode_tile(p_j2k, l_current_tile_no, NULL, 0,
p_stream, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Failed to decode tile 1/1\n");
return OPJ_FALSE;
}
/* Transfer TCD data to output image data */
for (i = 0; i < p_j2k->m_output_image->numcomps; i++) {
opj_image_data_free(p_j2k->m_output_image->comps[i].data);
p_j2k->m_output_image->comps[i].data =
p_j2k->m_tcd->tcd_image->tiles->comps[i].data;
p_j2k->m_output_image->comps[i].resno_decoded =
p_j2k->m_tcd->image->comps[i].resno_decoded;
p_j2k->m_tcd->tcd_image->tiles->comps[i].data = NULL;
}
return OPJ_TRUE;
}
l_current_data = (OPJ_BYTE*)opj_malloc(1000);
if (! l_current_data) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to decode tiles\n");
return OPJ_FALSE;
}
l_max_data_size = 1000;
for (;;) {
if (! opj_j2k_read_tile_header(p_j2k,
&l_current_tile_no,
&l_data_size,
&l_tile_x0, &l_tile_y0,
&l_tile_x1, &l_tile_y1,
&l_nb_comps,
&l_go_on,
p_stream,
p_manager)) {
opj_free(l_current_data);
return OPJ_FALSE;
}
if (! l_go_on) {
break;
}
if (l_data_size > l_max_data_size) {
OPJ_BYTE *l_new_current_data = (OPJ_BYTE *) opj_realloc(l_current_data,
l_data_size);
if (! l_new_current_data) {
opj_free(l_current_data);
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to decode tile %d/%d\n",
l_current_tile_no + 1, p_j2k->m_cp.th * p_j2k->m_cp.tw);
return OPJ_FALSE;
}
l_current_data = l_new_current_data;
l_max_data_size = l_data_size;
}
if (! opj_j2k_decode_tile(p_j2k, l_current_tile_no, l_current_data, l_data_size,
p_stream, p_manager)) {
opj_free(l_current_data);
opj_event_msg(p_manager, EVT_ERROR, "Failed to decode tile %d/%d\n",
l_current_tile_no + 1, p_j2k->m_cp.th * p_j2k->m_cp.tw);
return OPJ_FALSE;
}
opj_event_msg(p_manager, EVT_INFO, "Tile %d/%d has been decoded.\n",
l_current_tile_no + 1, p_j2k->m_cp.th * p_j2k->m_cp.tw);
if (! opj_j2k_update_image_data(p_j2k->m_tcd, l_current_data,
p_j2k->m_output_image)) {
opj_free(l_current_data);
return OPJ_FALSE;
}
opj_event_msg(p_manager, EVT_INFO,
"Image data has been updated with tile %d.\n\n", l_current_tile_no + 1);
if (opj_stream_get_number_byte_left(p_stream) == 0
&& p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_NEOC) {
break;
}
if (++nr_tiles == p_j2k->m_cp.th * p_j2k->m_cp.tw) {
break;
}
}
opj_free(l_current_data);
return OPJ_TRUE;
}
/**
* Sets up the procedures to do on decoding data. Developpers wanting to extend the library can add their own reading procedures.
*/
static OPJ_BOOL opj_j2k_setup_decoding(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager)
{
/* preconditions*/
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_decode_tiles, p_manager)) {
return OPJ_FALSE;
}
/* DEVELOPER CORNER, add your custom procedures */
return OPJ_TRUE;
}
/*
* Read and decode one tile.
*/
static OPJ_BOOL opj_j2k_decode_one_tile(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_BOOL l_go_on = OPJ_TRUE;
OPJ_UINT32 l_current_tile_no;
OPJ_UINT32 l_tile_no_to_dec;
OPJ_UINT32 l_data_size, l_max_data_size;
OPJ_INT32 l_tile_x0, l_tile_y0, l_tile_x1, l_tile_y1;
OPJ_UINT32 l_nb_comps;
OPJ_BYTE * l_current_data;
OPJ_UINT32 l_nb_tiles;
OPJ_UINT32 i;
l_current_data = (OPJ_BYTE*)opj_malloc(1000);
if (! l_current_data) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to decode one tile\n");
return OPJ_FALSE;
}
l_max_data_size = 1000;
/*Allocate and initialize some elements of codestrem index if not already done*/
if (!p_j2k->cstr_index->tile_index) {
if (!opj_j2k_allocate_tile_element_cstr_index(p_j2k)) {
opj_free(l_current_data);
return OPJ_FALSE;
}
}
/* Move into the codestream to the first SOT used to decode the desired tile */
l_tile_no_to_dec = (OPJ_UINT32)
p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec;
if (p_j2k->cstr_index->tile_index)
if (p_j2k->cstr_index->tile_index->tp_index) {
if (! p_j2k->cstr_index->tile_index[l_tile_no_to_dec].nb_tps) {
/* the index for this tile has not been built,
* so move to the last SOT read */
if (!(opj_stream_read_seek(p_stream,
p_j2k->m_specific_param.m_decoder.m_last_sot_read_pos + 2, p_manager))) {
opj_event_msg(p_manager, EVT_ERROR, "Problem with seek function\n");
opj_free(l_current_data);
return OPJ_FALSE;
}
} else {
if (!(opj_stream_read_seek(p_stream,
p_j2k->cstr_index->tile_index[l_tile_no_to_dec].tp_index[0].start_pos + 2,
p_manager))) {
opj_event_msg(p_manager, EVT_ERROR, "Problem with seek function\n");
opj_free(l_current_data);
return OPJ_FALSE;
}
}
/* Special case if we have previously read the EOC marker (if the previous tile getted is the last ) */
if (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_EOC) {
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPHSOT;
}
}
/* Reset current tile part number for all tiles, and not only the one */
/* of interest. */
/* Not completely sure this is always correct but required for */
/* ./build/bin/j2k_random_tile_access ./build/tests/tte1.j2k */
l_nb_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th;
for (i = 0; i < l_nb_tiles; ++i) {
p_j2k->m_cp.tcps[i].m_current_tile_part_number = -1;
}
for (;;) {
if (! opj_j2k_read_tile_header(p_j2k,
&l_current_tile_no,
&l_data_size,
&l_tile_x0, &l_tile_y0,
&l_tile_x1, &l_tile_y1,
&l_nb_comps,
&l_go_on,
p_stream,
p_manager)) {
opj_free(l_current_data);
return OPJ_FALSE;
}
if (! l_go_on) {
break;
}
if (l_data_size > l_max_data_size) {
OPJ_BYTE *l_new_current_data = (OPJ_BYTE *) opj_realloc(l_current_data,
l_data_size);
if (! l_new_current_data) {
opj_free(l_current_data);
l_current_data = NULL;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to decode tile %d/%d\n",
l_current_tile_no + 1, p_j2k->m_cp.th * p_j2k->m_cp.tw);
return OPJ_FALSE;
}
l_current_data = l_new_current_data;
l_max_data_size = l_data_size;
}
if (! opj_j2k_decode_tile(p_j2k, l_current_tile_no, l_current_data, l_data_size,
p_stream, p_manager)) {
opj_free(l_current_data);
return OPJ_FALSE;
}
opj_event_msg(p_manager, EVT_INFO, "Tile %d/%d has been decoded.\n",
l_current_tile_no + 1, p_j2k->m_cp.th * p_j2k->m_cp.tw);
if (! opj_j2k_update_image_data(p_j2k->m_tcd, l_current_data,
p_j2k->m_output_image)) {
opj_free(l_current_data);
return OPJ_FALSE;
}
opj_event_msg(p_manager, EVT_INFO,
"Image data has been updated with tile %d.\n\n", l_current_tile_no + 1);
if (l_current_tile_no == l_tile_no_to_dec) {
/* move into the codestream to the first SOT (FIXME or not move?)*/
if (!(opj_stream_read_seek(p_stream, p_j2k->cstr_index->main_head_end + 2,
p_manager))) {
opj_event_msg(p_manager, EVT_ERROR, "Problem with seek function\n");
opj_free(l_current_data);
return OPJ_FALSE;
}
break;
} else {
opj_event_msg(p_manager, EVT_WARNING,
"Tile read, decoded and updated is not the desired one (%d vs %d).\n",
l_current_tile_no + 1, l_tile_no_to_dec + 1);
}
}
opj_free(l_current_data);
return OPJ_TRUE;
}
/**
* Sets up the procedures to do on decoding one tile. Developpers wanting to extend the library can add their own reading procedures.
*/
static OPJ_BOOL opj_j2k_setup_decoding_tile(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager)
{
/* preconditions*/
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_decode_one_tile, p_manager)) {
return OPJ_FALSE;
}
/* DEVELOPER CORNER, add your custom procedures */
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_decode(opj_j2k_t * p_j2k,
opj_stream_private_t * p_stream,
opj_image_t * p_image,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 compno;
if (!p_image) {
return OPJ_FALSE;
}
p_j2k->m_output_image = opj_image_create0();
if (!(p_j2k->m_output_image)) {
return OPJ_FALSE;
}
opj_copy_image_header(p_image, p_j2k->m_output_image);
/* customization of the decoding */
if (!opj_j2k_setup_decoding(p_j2k, p_manager)) {
return OPJ_FALSE;
}
/* Decode the codestream */
if (! opj_j2k_exec(p_j2k, p_j2k->m_procedure_list, p_stream, p_manager)) {
opj_image_destroy(p_j2k->m_private_image);
p_j2k->m_private_image = NULL;
return OPJ_FALSE;
}
/* Move data and copy one information from codec to output image*/
for (compno = 0; compno < p_image->numcomps; compno++) {
p_image->comps[compno].resno_decoded =
p_j2k->m_output_image->comps[compno].resno_decoded;
p_image->comps[compno].data = p_j2k->m_output_image->comps[compno].data;
#if 0
char fn[256];
sprintf(fn, "/tmp/%d.raw", compno);
FILE *debug = fopen(fn, "wb");
fwrite(p_image->comps[compno].data, sizeof(OPJ_INT32),
p_image->comps[compno].w * p_image->comps[compno].h, debug);
fclose(debug);
#endif
p_j2k->m_output_image->comps[compno].data = NULL;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_get_tile(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_image_t* p_image,
opj_event_mgr_t * p_manager,
OPJ_UINT32 tile_index)
{
OPJ_UINT32 compno;
OPJ_UINT32 l_tile_x, l_tile_y;
opj_image_comp_t* l_img_comp;
if (!p_image) {
opj_event_msg(p_manager, EVT_ERROR, "We need an image previously created.\n");
return OPJ_FALSE;
}
if (/*(tile_index < 0) &&*/ (tile_index >= p_j2k->m_cp.tw * p_j2k->m_cp.th)) {
opj_event_msg(p_manager, EVT_ERROR,
"Tile index provided by the user is incorrect %d (max = %d) \n", tile_index,
(p_j2k->m_cp.tw * p_j2k->m_cp.th) - 1);
return OPJ_FALSE;
}
/* Compute the dimension of the desired tile*/
l_tile_x = tile_index % p_j2k->m_cp.tw;
l_tile_y = tile_index / p_j2k->m_cp.tw;
p_image->x0 = l_tile_x * p_j2k->m_cp.tdx + p_j2k->m_cp.tx0;
if (p_image->x0 < p_j2k->m_private_image->x0) {
p_image->x0 = p_j2k->m_private_image->x0;
}
p_image->x1 = (l_tile_x + 1) * p_j2k->m_cp.tdx + p_j2k->m_cp.tx0;
if (p_image->x1 > p_j2k->m_private_image->x1) {
p_image->x1 = p_j2k->m_private_image->x1;
}
p_image->y0 = l_tile_y * p_j2k->m_cp.tdy + p_j2k->m_cp.ty0;
if (p_image->y0 < p_j2k->m_private_image->y0) {
p_image->y0 = p_j2k->m_private_image->y0;
}
p_image->y1 = (l_tile_y + 1) * p_j2k->m_cp.tdy + p_j2k->m_cp.ty0;
if (p_image->y1 > p_j2k->m_private_image->y1) {
p_image->y1 = p_j2k->m_private_image->y1;
}
l_img_comp = p_image->comps;
for (compno = 0; compno < p_image->numcomps; ++compno) {
OPJ_INT32 l_comp_x1, l_comp_y1;
l_img_comp->factor = p_j2k->m_private_image->comps[compno].factor;
l_img_comp->x0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->x0,
(OPJ_INT32)l_img_comp->dx);
l_img_comp->y0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->y0,
(OPJ_INT32)l_img_comp->dy);
l_comp_x1 = opj_int_ceildiv((OPJ_INT32)p_image->x1, (OPJ_INT32)l_img_comp->dx);
l_comp_y1 = opj_int_ceildiv((OPJ_INT32)p_image->y1, (OPJ_INT32)l_img_comp->dy);
l_img_comp->w = (OPJ_UINT32)(opj_int_ceildivpow2(l_comp_x1,
(OPJ_INT32)l_img_comp->factor) - opj_int_ceildivpow2((OPJ_INT32)l_img_comp->x0,
(OPJ_INT32)l_img_comp->factor));
l_img_comp->h = (OPJ_UINT32)(opj_int_ceildivpow2(l_comp_y1,
(OPJ_INT32)l_img_comp->factor) - opj_int_ceildivpow2((OPJ_INT32)l_img_comp->y0,
(OPJ_INT32)l_img_comp->factor));
l_img_comp++;
}
/* Destroy the previous output image*/
if (p_j2k->m_output_image) {
opj_image_destroy(p_j2k->m_output_image);
}
/* Create the ouput image from the information previously computed*/
p_j2k->m_output_image = opj_image_create0();
if (!(p_j2k->m_output_image)) {
return OPJ_FALSE;
}
opj_copy_image_header(p_image, p_j2k->m_output_image);
p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec = (OPJ_INT32)tile_index;
/* customization of the decoding */
if (!opj_j2k_setup_decoding_tile(p_j2k, p_manager)) {
return OPJ_FALSE;
}
/* Decode the codestream */
if (! opj_j2k_exec(p_j2k, p_j2k->m_procedure_list, p_stream, p_manager)) {
opj_image_destroy(p_j2k->m_private_image);
p_j2k->m_private_image = NULL;
return OPJ_FALSE;
}
/* Move data and copy one information from codec to output image*/
for (compno = 0; compno < p_image->numcomps; compno++) {
p_image->comps[compno].resno_decoded =
p_j2k->m_output_image->comps[compno].resno_decoded;
if (p_image->comps[compno].data) {
opj_image_data_free(p_image->comps[compno].data);
}
p_image->comps[compno].data = p_j2k->m_output_image->comps[compno].data;
p_j2k->m_output_image->comps[compno].data = NULL;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_set_decoded_resolution_factor(opj_j2k_t *p_j2k,
OPJ_UINT32 res_factor,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 it_comp;
p_j2k->m_cp.m_specific_param.m_dec.m_reduce = res_factor;
if (p_j2k->m_private_image) {
if (p_j2k->m_private_image->comps) {
if (p_j2k->m_specific_param.m_decoder.m_default_tcp) {
if (p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps) {
for (it_comp = 0 ; it_comp < p_j2k->m_private_image->numcomps; it_comp++) {
OPJ_UINT32 max_res =
p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps[it_comp].numresolutions;
if (res_factor >= max_res) {
opj_event_msg(p_manager, EVT_ERROR,
"Resolution factor is greater than the maximum resolution in the component.\n");
return OPJ_FALSE;
}
p_j2k->m_private_image->comps[it_comp].factor = res_factor;
}
return OPJ_TRUE;
}
}
}
}
return OPJ_FALSE;
}
OPJ_BOOL opj_j2k_encode(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 i, j;
OPJ_UINT32 l_nb_tiles;
OPJ_UINT32 l_max_tile_size = 0, l_current_tile_size;
OPJ_BYTE * l_current_data = 00;
OPJ_BOOL l_reuse_data = OPJ_FALSE;
opj_tcd_t* p_tcd = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
p_tcd = p_j2k->m_tcd;
l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
if (l_nb_tiles == 1) {
l_reuse_data = OPJ_TRUE;
#ifdef __SSE__
for (j = 0; j < p_j2k->m_tcd->image->numcomps; ++j) {
opj_image_comp_t * l_img_comp = p_tcd->image->comps + j;
if (((size_t)l_img_comp->data & 0xFU) !=
0U) { /* tile data shall be aligned on 16 bytes */
l_reuse_data = OPJ_FALSE;
}
}
#endif
}
for (i = 0; i < l_nb_tiles; ++i) {
if (! opj_j2k_pre_write_tile(p_j2k, i, p_stream, p_manager)) {
if (l_current_data) {
opj_free(l_current_data);
}
return OPJ_FALSE;
}
/* if we only have one tile, then simply set tile component data equal to image component data */
/* otherwise, allocate the data */
for (j = 0; j < p_j2k->m_tcd->image->numcomps; ++j) {
opj_tcd_tilecomp_t* l_tilec = p_tcd->tcd_image->tiles->comps + j;
if (l_reuse_data) {
opj_image_comp_t * l_img_comp = p_tcd->image->comps + j;
l_tilec->data = l_img_comp->data;
l_tilec->ownsData = OPJ_FALSE;
} else {
if (! opj_alloc_tile_component_data(l_tilec)) {
opj_event_msg(p_manager, EVT_ERROR, "Error allocating tile component data.");
if (l_current_data) {
opj_free(l_current_data);
}
return OPJ_FALSE;
}
}
}
l_current_tile_size = opj_tcd_get_encoded_tile_size(p_j2k->m_tcd);
if (!l_reuse_data) {
if (l_current_tile_size > l_max_tile_size) {
OPJ_BYTE *l_new_current_data = (OPJ_BYTE *) opj_realloc(l_current_data,
l_current_tile_size);
if (! l_new_current_data) {
if (l_current_data) {
opj_free(l_current_data);
}
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to encode all tiles\n");
return OPJ_FALSE;
}
l_current_data = l_new_current_data;
l_max_tile_size = l_current_tile_size;
}
/* copy image data (32 bit) to l_current_data as contiguous, all-component, zero offset buffer */
/* 32 bit components @ 8 bit precision get converted to 8 bit */
/* 32 bit components @ 16 bit precision get converted to 16 bit */
opj_j2k_get_tile_data(p_j2k->m_tcd, l_current_data);
/* now copy this data into the tile component */
if (! opj_tcd_copy_tile_data(p_j2k->m_tcd, l_current_data,
l_current_tile_size)) {
opj_event_msg(p_manager, EVT_ERROR,
"Size mismatch between tile data and sent data.");
opj_free(l_current_data);
return OPJ_FALSE;
}
}
if (! opj_j2k_post_write_tile(p_j2k, p_stream, p_manager)) {
if (l_current_data) {
opj_free(l_current_data);
}
return OPJ_FALSE;
}
}
if (l_current_data) {
opj_free(l_current_data);
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_end_compress(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
/* customization of the encoding */
if (! opj_j2k_setup_end_compress(p_j2k, p_manager)) {
return OPJ_FALSE;
}
if (! opj_j2k_exec(p_j2k, p_j2k->m_procedure_list, p_stream, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_start_compress(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_image_t * p_image,
opj_event_mgr_t * p_manager)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
p_j2k->m_private_image = opj_image_create0();
if (! p_j2k->m_private_image) {
opj_event_msg(p_manager, EVT_ERROR, "Failed to allocate image header.");
return OPJ_FALSE;
}
opj_copy_image_header(p_image, p_j2k->m_private_image);
/* TODO_MSD: Find a better way */
if (p_image->comps) {
OPJ_UINT32 it_comp;
for (it_comp = 0 ; it_comp < p_image->numcomps; it_comp++) {
if (p_image->comps[it_comp].data) {
p_j2k->m_private_image->comps[it_comp].data = p_image->comps[it_comp].data;
p_image->comps[it_comp].data = NULL;
}
}
}
/* customization of the validation */
if (! opj_j2k_setup_encoding_validation(p_j2k, p_manager)) {
return OPJ_FALSE;
}
/* validation of the parameters codec */
if (! opj_j2k_exec(p_j2k, p_j2k->m_validation_list, p_stream, p_manager)) {
return OPJ_FALSE;
}
/* customization of the encoding */
if (! opj_j2k_setup_header_writing(p_j2k, p_manager)) {
return OPJ_FALSE;
}
/* write header */
if (! opj_j2k_exec(p_j2k, p_j2k->m_procedure_list, p_stream, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_pre_write_tile(opj_j2k_t * p_j2k,
OPJ_UINT32 p_tile_index,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
(void)p_stream;
if (p_tile_index != p_j2k->m_current_tile_number) {
opj_event_msg(p_manager, EVT_ERROR, "The given tile index does not match.");
return OPJ_FALSE;
}
opj_event_msg(p_manager, EVT_INFO, "tile number %d / %d\n",
p_j2k->m_current_tile_number + 1, p_j2k->m_cp.tw * p_j2k->m_cp.th);
p_j2k->m_specific_param.m_encoder.m_current_tile_part_number = 0;
p_j2k->m_tcd->cur_totnum_tp = p_j2k->m_cp.tcps[p_tile_index].m_nb_tile_parts;
p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = 0;
/* initialisation before tile encoding */
if (! opj_tcd_init_encode_tile(p_j2k->m_tcd, p_j2k->m_current_tile_number,
p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static void opj_get_tile_dimensions(opj_image_t * l_image,
opj_tcd_tilecomp_t * l_tilec,
opj_image_comp_t * l_img_comp,
OPJ_UINT32* l_size_comp,
OPJ_UINT32* l_width,
OPJ_UINT32* l_height,
OPJ_UINT32* l_offset_x,
OPJ_UINT32* l_offset_y,
OPJ_UINT32* l_image_width,
OPJ_UINT32* l_stride,
OPJ_UINT32* l_tile_offset)
{
OPJ_UINT32 l_remaining;
*l_size_comp = l_img_comp->prec >> 3; /* (/8) */
l_remaining = l_img_comp->prec & 7; /* (%8) */
if (l_remaining) {
*l_size_comp += 1;
}
if (*l_size_comp == 3) {
*l_size_comp = 4;
}
*l_width = (OPJ_UINT32)(l_tilec->x1 - l_tilec->x0);
*l_height = (OPJ_UINT32)(l_tilec->y1 - l_tilec->y0);
*l_offset_x = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)l_image->x0,
(OPJ_INT32)l_img_comp->dx);
*l_offset_y = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)l_image->y0,
(OPJ_INT32)l_img_comp->dy);
*l_image_width = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)l_image->x1 -
(OPJ_INT32)l_image->x0, (OPJ_INT32)l_img_comp->dx);
*l_stride = *l_image_width - *l_width;
*l_tile_offset = ((OPJ_UINT32)l_tilec->x0 - *l_offset_x) + ((
OPJ_UINT32)l_tilec->y0 - *l_offset_y) * *l_image_width;
}
static void opj_j2k_get_tile_data(opj_tcd_t * p_tcd, OPJ_BYTE * p_data)
{
OPJ_UINT32 i, j, k = 0;
for (i = 0; i < p_tcd->image->numcomps; ++i) {
opj_image_t * l_image = p_tcd->image;
OPJ_INT32 * l_src_ptr;
opj_tcd_tilecomp_t * l_tilec = p_tcd->tcd_image->tiles->comps + i;
opj_image_comp_t * l_img_comp = l_image->comps + i;
OPJ_UINT32 l_size_comp, l_width, l_height, l_offset_x, l_offset_y,
l_image_width, l_stride, l_tile_offset;
opj_get_tile_dimensions(l_image,
l_tilec,
l_img_comp,
&l_size_comp,
&l_width,
&l_height,
&l_offset_x,
&l_offset_y,
&l_image_width,
&l_stride,
&l_tile_offset);
l_src_ptr = l_img_comp->data + l_tile_offset;
switch (l_size_comp) {
case 1: {
OPJ_CHAR * l_dest_ptr = (OPJ_CHAR*) p_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_dest_ptr;
++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_dest_ptr;
++l_src_ptr;
}
l_src_ptr += l_stride;
}
}
p_data = (OPJ_BYTE*) l_dest_ptr;
}
break;
case 2: {
OPJ_INT16 * l_dest_ptr = (OPJ_INT16 *) p_data;
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_data = (OPJ_BYTE*) l_dest_ptr;
}
break;
case 4: {
OPJ_INT32 * l_dest_ptr = (OPJ_INT32 *) p_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_data = (OPJ_BYTE*) l_dest_ptr;
}
break;
}
}
}
static OPJ_BOOL opj_j2k_post_write_tile(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 l_nb_bytes_written;
OPJ_BYTE * l_current_data = 00;
OPJ_UINT32 l_tile_size = 0;
OPJ_UINT32 l_available_data;
/* preconditions */
assert(p_j2k->m_specific_param.m_encoder.m_encoded_tile_data);
l_tile_size = p_j2k->m_specific_param.m_encoder.m_encoded_tile_size;
l_available_data = l_tile_size;
l_current_data = p_j2k->m_specific_param.m_encoder.m_encoded_tile_data;
l_nb_bytes_written = 0;
if (! opj_j2k_write_first_tile_part(p_j2k, l_current_data, &l_nb_bytes_written,
l_available_data, p_stream, p_manager)) {
return OPJ_FALSE;
}
l_current_data += l_nb_bytes_written;
l_available_data -= l_nb_bytes_written;
l_nb_bytes_written = 0;
if (! opj_j2k_write_all_tile_parts(p_j2k, l_current_data, &l_nb_bytes_written,
l_available_data, p_stream, p_manager)) {
return OPJ_FALSE;
}
l_available_data -= l_nb_bytes_written;
l_nb_bytes_written = l_tile_size - l_available_data;
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_encoded_tile_data,
l_nb_bytes_written, p_manager) != l_nb_bytes_written) {
return OPJ_FALSE;
}
++p_j2k->m_current_tile_number;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_setup_end_compress(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
/* DEVELOPER CORNER, insert your custom procedures */
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_eoc, p_manager)) {
return OPJ_FALSE;
}
if (OPJ_IS_CINEMA(p_j2k->m_cp.rsiz)) {
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_updated_tlm, p_manager)) {
return OPJ_FALSE;
}
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_epc, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_end_encoding, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_destroy_header_memory, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_setup_encoding_validation(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list,
(opj_procedure)opj_j2k_build_encoder, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list,
(opj_procedure)opj_j2k_encoding_validation, p_manager)) {
return OPJ_FALSE;
}
/* DEVELOPER CORNER, add your custom validation procedure */
if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list,
(opj_procedure)opj_j2k_mct_validation, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_setup_header_writing(opj_j2k_t *p_j2k,
opj_event_mgr_t * p_manager)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_init_info, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_soc, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_siz, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_cod, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_qcd, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_all_coc, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_all_qcc, p_manager)) {
return OPJ_FALSE;
}
if (OPJ_IS_CINEMA(p_j2k->m_cp.rsiz)) {
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_tlm, p_manager)) {
return OPJ_FALSE;
}
if (p_j2k->m_cp.rsiz == OPJ_PROFILE_CINEMA_4K) {
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_poc, p_manager)) {
return OPJ_FALSE;
}
}
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_regions, p_manager)) {
return OPJ_FALSE;
}
if (p_j2k->m_cp.comment != 00) {
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_com, p_manager)) {
return OPJ_FALSE;
}
}
/* DEVELOPER CORNER, insert your custom procedures */
if (p_j2k->m_cp.rsiz & OPJ_EXTENSION_MCT) {
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_write_mct_data_group, p_manager)) {
return OPJ_FALSE;
}
}
/* End of Developer Corner */
if (p_j2k->cstr_index) {
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_get_end_header, p_manager)) {
return OPJ_FALSE;
}
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_create_tcd, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
(opj_procedure)opj_j2k_update_rates, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_first_tile_part(opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_total_data_size,
opj_stream_private_t *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 l_nb_bytes_written = 0;
OPJ_UINT32 l_current_nb_bytes_written;
OPJ_BYTE * l_begin_data = 00;
opj_tcd_t * l_tcd = 00;
opj_cp_t * l_cp = 00;
l_tcd = p_j2k->m_tcd;
l_cp = &(p_j2k->m_cp);
l_tcd->cur_pino = 0;
/*Get number of tile parts*/
p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = 0;
/* INDEX >> */
/* << INDEX */
l_current_nb_bytes_written = 0;
l_begin_data = p_data;
if (! opj_j2k_write_sot(p_j2k, p_data, &l_current_nb_bytes_written, p_stream,
p_manager)) {
return OPJ_FALSE;
}
l_nb_bytes_written += l_current_nb_bytes_written;
p_data += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
if (!OPJ_IS_CINEMA(l_cp->rsiz)) {
#if 0
for (compno = 1; compno < p_j2k->m_private_image->numcomps; compno++) {
l_current_nb_bytes_written = 0;
opj_j2k_write_coc_in_memory(p_j2k, compno, p_data, &l_current_nb_bytes_written,
p_manager);
l_nb_bytes_written += l_current_nb_bytes_written;
p_data += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
l_current_nb_bytes_written = 0;
opj_j2k_write_qcc_in_memory(p_j2k, compno, p_data, &l_current_nb_bytes_written,
p_manager);
l_nb_bytes_written += l_current_nb_bytes_written;
p_data += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
}
#endif
if (l_cp->tcps[p_j2k->m_current_tile_number].numpocs) {
l_current_nb_bytes_written = 0;
opj_j2k_write_poc_in_memory(p_j2k, p_data, &l_current_nb_bytes_written,
p_manager);
l_nb_bytes_written += l_current_nb_bytes_written;
p_data += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
}
}
l_current_nb_bytes_written = 0;
if (! opj_j2k_write_sod(p_j2k, l_tcd, p_data, &l_current_nb_bytes_written,
p_total_data_size, p_stream, p_manager)) {
return OPJ_FALSE;
}
l_nb_bytes_written += l_current_nb_bytes_written;
* p_data_written = l_nb_bytes_written;
/* Writing Psot in SOT marker */
opj_write_bytes(l_begin_data + 6, l_nb_bytes_written,
4); /* PSOT */
if (OPJ_IS_CINEMA(l_cp->rsiz)) {
opj_j2k_update_tlm(p_j2k, l_nb_bytes_written);
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_all_tile_parts(opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_total_data_size,
opj_stream_private_t *p_stream,
struct opj_event_mgr * p_manager
)
{
OPJ_UINT32 tilepartno = 0;
OPJ_UINT32 l_nb_bytes_written = 0;
OPJ_UINT32 l_current_nb_bytes_written;
OPJ_UINT32 l_part_tile_size;
OPJ_UINT32 tot_num_tp;
OPJ_UINT32 pino;
OPJ_BYTE * l_begin_data;
opj_tcp_t *l_tcp = 00;
opj_tcd_t * l_tcd = 00;
opj_cp_t * l_cp = 00;
l_tcd = p_j2k->m_tcd;
l_cp = &(p_j2k->m_cp);
l_tcp = l_cp->tcps + p_j2k->m_current_tile_number;
/*Get number of tile parts*/
tot_num_tp = opj_j2k_get_num_tp(l_cp, 0, p_j2k->m_current_tile_number);
/* start writing remaining tile parts */
++p_j2k->m_specific_param.m_encoder.m_current_tile_part_number;
for (tilepartno = 1; tilepartno < tot_num_tp ; ++tilepartno) {
p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = tilepartno;
l_current_nb_bytes_written = 0;
l_part_tile_size = 0;
l_begin_data = p_data;
if (! opj_j2k_write_sot(p_j2k, p_data, &l_current_nb_bytes_written, p_stream,
p_manager)) {
return OPJ_FALSE;
}
l_nb_bytes_written += l_current_nb_bytes_written;
p_data += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
l_part_tile_size += l_current_nb_bytes_written;
l_current_nb_bytes_written = 0;
if (! opj_j2k_write_sod(p_j2k, l_tcd, p_data, &l_current_nb_bytes_written,
p_total_data_size, p_stream, p_manager)) {
return OPJ_FALSE;
}
p_data += l_current_nb_bytes_written;
l_nb_bytes_written += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
l_part_tile_size += l_current_nb_bytes_written;
/* Writing Psot in SOT marker */
opj_write_bytes(l_begin_data + 6, l_part_tile_size,
4); /* PSOT */
if (OPJ_IS_CINEMA(l_cp->rsiz)) {
opj_j2k_update_tlm(p_j2k, l_part_tile_size);
}
++p_j2k->m_specific_param.m_encoder.m_current_tile_part_number;
}
for (pino = 1; pino <= l_tcp->numpocs; ++pino) {
l_tcd->cur_pino = pino;
/*Get number of tile parts*/
tot_num_tp = opj_j2k_get_num_tp(l_cp, pino, p_j2k->m_current_tile_number);
for (tilepartno = 0; tilepartno < tot_num_tp ; ++tilepartno) {
p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = tilepartno;
l_current_nb_bytes_written = 0;
l_part_tile_size = 0;
l_begin_data = p_data;
if (! opj_j2k_write_sot(p_j2k, p_data, &l_current_nb_bytes_written, p_stream,
p_manager)) {
return OPJ_FALSE;
}
l_nb_bytes_written += l_current_nb_bytes_written;
p_data += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
l_part_tile_size += l_current_nb_bytes_written;
l_current_nb_bytes_written = 0;
if (! opj_j2k_write_sod(p_j2k, l_tcd, p_data, &l_current_nb_bytes_written,
p_total_data_size, p_stream, p_manager)) {
return OPJ_FALSE;
}
l_nb_bytes_written += l_current_nb_bytes_written;
p_data += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
l_part_tile_size += l_current_nb_bytes_written;
/* Writing Psot in SOT marker */
opj_write_bytes(l_begin_data + 6, l_part_tile_size,
4); /* PSOT */
if (OPJ_IS_CINEMA(l_cp->rsiz)) {
opj_j2k_update_tlm(p_j2k, l_part_tile_size);
}
++p_j2k->m_specific_param.m_encoder.m_current_tile_part_number;
}
}
*p_data_written = l_nb_bytes_written;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_updated_tlm(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
OPJ_UINT32 l_tlm_size;
OPJ_OFF_T l_tlm_position, l_current_position;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_tlm_size = 5 * p_j2k->m_specific_param.m_encoder.m_total_tile_parts;
l_tlm_position = 6 + p_j2k->m_specific_param.m_encoder.m_tlm_start;
l_current_position = opj_stream_tell(p_stream);
if (! opj_stream_seek(p_stream, l_tlm_position, p_manager)) {
return OPJ_FALSE;
}
if (opj_stream_write_data(p_stream,
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer, l_tlm_size,
p_manager) != l_tlm_size) {
return OPJ_FALSE;
}
if (! opj_stream_seek(p_stream, l_current_position, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_end_encoding(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
OPJ_UNUSED(p_stream);
OPJ_UNUSED(p_manager);
opj_tcd_destroy(p_j2k->m_tcd);
p_j2k->m_tcd = 00;
if (p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer) {
opj_free(p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer);
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer = 0;
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current = 0;
}
if (p_j2k->m_specific_param.m_encoder.m_encoded_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_encoded_tile_data);
p_j2k->m_specific_param.m_encoder.m_encoded_tile_data = 0;
}
p_j2k->m_specific_param.m_encoder.m_encoded_tile_size = 0;
return OPJ_TRUE;
}
/**
* Destroys the memory associated with the decoding of headers.
*/
static OPJ_BOOL opj_j2k_destroy_header_memory(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
OPJ_UNUSED(p_stream);
OPJ_UNUSED(p_manager);
if (p_j2k->m_specific_param.m_encoder.m_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = 0;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_init_info(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager)
{
opj_codestream_info_t * l_cstr_info = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
(void)l_cstr_info;
OPJ_UNUSED(p_stream);
/* TODO mergeV2: check this part which use cstr_info */
/*l_cstr_info = p_j2k->cstr_info;
if (l_cstr_info) {
OPJ_UINT32 compno;
l_cstr_info->tile = (opj_tile_info_t *) opj_malloc(p_j2k->m_cp.tw * p_j2k->m_cp.th * sizeof(opj_tile_info_t));
l_cstr_info->image_w = p_j2k->m_image->x1 - p_j2k->m_image->x0;
l_cstr_info->image_h = p_j2k->m_image->y1 - p_j2k->m_image->y0;
l_cstr_info->prog = (&p_j2k->m_cp.tcps[0])->prg;
l_cstr_info->tw = p_j2k->m_cp.tw;
l_cstr_info->th = p_j2k->m_cp.th;
l_cstr_info->tile_x = p_j2k->m_cp.tdx;*/ /* new version parser */
/*l_cstr_info->tile_y = p_j2k->m_cp.tdy;*/ /* new version parser */
/*l_cstr_info->tile_Ox = p_j2k->m_cp.tx0;*/ /* new version parser */
/*l_cstr_info->tile_Oy = p_j2k->m_cp.ty0;*/ /* new version parser */
/*l_cstr_info->numcomps = p_j2k->m_image->numcomps;
l_cstr_info->numlayers = (&p_j2k->m_cp.tcps[0])->numlayers;
l_cstr_info->numdecompos = (OPJ_INT32*) opj_malloc(p_j2k->m_image->numcomps * sizeof(OPJ_INT32));
for (compno=0; compno < p_j2k->m_image->numcomps; compno++) {
l_cstr_info->numdecompos[compno] = (&p_j2k->m_cp.tcps[0])->tccps->numresolutions - 1;
}
l_cstr_info->D_max = 0.0; */ /* ADD Marcela */
/*l_cstr_info->main_head_start = opj_stream_tell(p_stream);*/ /* position of SOC */
/*l_cstr_info->maxmarknum = 100;
l_cstr_info->marker = (opj_marker_info_t *) opj_malloc(l_cstr_info->maxmarknum * sizeof(opj_marker_info_t));
l_cstr_info->marknum = 0;
}*/
return opj_j2k_calculate_tp(p_j2k, &(p_j2k->m_cp),
&p_j2k->m_specific_param.m_encoder.m_total_tile_parts, p_j2k->m_private_image,
p_manager);
}
/**
* Creates a tile-coder decoder.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_create_tcd(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
OPJ_UNUSED(p_stream);
p_j2k->m_tcd = opj_tcd_create(OPJ_FALSE);
if (! p_j2k->m_tcd) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to create Tile Coder\n");
return OPJ_FALSE;
}
if (!opj_tcd_init(p_j2k->m_tcd, p_j2k->m_private_image, &p_j2k->m_cp,
p_j2k->m_tp)) {
opj_tcd_destroy(p_j2k->m_tcd);
p_j2k->m_tcd = 00;
return OPJ_FALSE;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_write_tile(opj_j2k_t * p_j2k,
OPJ_UINT32 p_tile_index,
OPJ_BYTE * p_data,
OPJ_UINT32 p_data_size,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
if (! opj_j2k_pre_write_tile(p_j2k, p_tile_index, p_stream, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR,
"Error while opj_j2k_pre_write_tile with tile index = %d\n", p_tile_index);
return OPJ_FALSE;
} else {
OPJ_UINT32 j;
/* Allocate data */
for (j = 0; j < p_j2k->m_tcd->image->numcomps; ++j) {
opj_tcd_tilecomp_t* l_tilec = p_j2k->m_tcd->tcd_image->tiles->comps + j;
if (! opj_alloc_tile_component_data(l_tilec)) {
opj_event_msg(p_manager, EVT_ERROR, "Error allocating tile component data.");
return OPJ_FALSE;
}
}
/* now copy data into the tile component */
if (! opj_tcd_copy_tile_data(p_j2k->m_tcd, p_data, p_data_size)) {
opj_event_msg(p_manager, EVT_ERROR,
"Size mismatch between tile data and sent data.");
return OPJ_FALSE;
}
if (! opj_j2k_post_write_tile(p_j2k, p_stream, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR,
"Error while opj_j2k_post_write_tile with tile index = %d\n", p_tile_index);
return OPJ_FALSE;
}
}
return OPJ_TRUE;
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_2776_0 |
crossvul-cpp_data_bad_1005_0 | /******************************************************************************
* main.c
*
* pdfresurrect - PDF history extraction tool
*
* Copyright (C) 2008-2010, 2012, 2017, 2019 Matt Davis (enferex).
*
* Special thanks to all of the contributors: See AUTHORS.
*
* Special thanks to 757labs (757 crew), they are a great group
* of people to hack on projects and brainstorm with.
*
* main.c is part of pdfresurrect.
* pdfresurrect 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 3 of the License, or
* (at your option) any later version.
*
* pdfresurrect 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 pdfresurrect. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "main.h"
#include "pdf.h"
static void usage(void)
{
printf(EXEC_NAME " Copyright (C) 2008-2010, 2012, 2013, 2017, 2019"
"Matt Davis (enferex)\n"
"Special thanks to all contributors and the 757 crew.\n"
"This program comes with ABSOLUTELY NO WARRANTY\n"
"This is free software, and you are welcome to redistribute it\n"
"under certain conditions. For details see the file 'LICENSE'\n"
"that came with this software or visit:\n"
"<http://www.gnu.org/licenses/gpl-3.0.txt>\n\n");
printf("-- " EXEC_NAME " v" VER" --\n"
"Usage: ./" EXEC_NAME " <file.pdf> [-i] [-w] [-q] [-s]\n"
"\t -i Display PDF creator information\n"
"\t -w Write the PDF versions and summary to disk\n"
"\t -q Display only the number of versions contained in the PDF\n"
"\t -s Scrub the previous history data from the specified PDF\n");
exit(0);
}
static void write_version(
FILE *fp,
const char *fname,
const char *dirname,
xref_t *xref)
{
long start;
char *c, *new_fname, data;
FILE *new_fp;
start = ftell(fp);
/* Create file */
if ((c = strstr(fname, ".pdf")))
*c = '\0';
new_fname = malloc(strlen(fname) + strlen(dirname) + 16);
snprintf(new_fname, strlen(fname) + strlen(dirname) + 16,
"%s/%s-version-%d.pdf", dirname, fname, xref->version);
if (!(new_fp = fopen(new_fname, "w")))
{
ERR("Could not create file '%s'\n", new_fname);
fseek(fp, start, SEEK_SET);
free(new_fname);
return;
}
/* Copy original PDF */
fseek(fp, 0, SEEK_SET);
while (fread(&data, 1, 1, fp))
fwrite(&data, 1, 1, new_fp);
/* Emit an older startxref, refering to an older version. */
fprintf(new_fp, "\r\nstartxref\r\n%ld\r\n%%%%EOF", xref->start);
/* Clean */
fclose(new_fp);
free(new_fname);
fseek(fp, start, SEEK_SET);
}
static void scrub_document(FILE *fp, const pdf_t *pdf)
{
FILE *new_fp;
int ch, i, j, last_version ;
char *new_name, *c;
const char *suffix = "-scrubbed.pdf";
/* Create a new name */
if (!(new_name = malloc(strlen(pdf->name) + strlen(suffix) + 1)))
{
ERR("Insufficient memory to create scrubbed file name\n");
return;
}
strcpy(new_name, pdf->name);
if ((c = strrchr(new_name, '.')))
*c = '\0';
strcat(new_name, suffix);
if ((new_fp = fopen(new_name, "r")))
{
ERR("File name already exists for saving scrubbed document\n");
free(new_name);
fclose(new_fp);
return;
}
if (!(new_fp = fopen(new_name, "w+")))
{
ERR("Could not create file for saving scrubbed document\n");
free(new_name);
fclose(new_fp);
return;
}
/* Copy */
fseek(fp, SEEK_SET, 0);
while ((ch = fgetc(fp)) != EOF)
fputc(ch, new_fp);
/* Find last version (dont zero these baddies) */
last_version = 0;
for (i=0; i<pdf->n_xrefs; i++)
if (pdf->xrefs[i].version)
last_version = pdf->xrefs[i].version;
/* Zero mod objects from all but the most recent version
* Zero del objects from all versions
*/
fseek(new_fp, 0, SEEK_SET);
for (i=0; i<pdf->n_xrefs; i++)
{
for (j=0; j<pdf->xrefs[i].n_entries; j++)
if (!pdf->xrefs[i].entries[j].obj_id)
continue;
else
{
switch (pdf_get_object_status(pdf, i, j))
{
case 'M':
if (pdf->xrefs[i].version != last_version)
pdf_zero_object(new_fp, pdf, i, j);
break;
case 'D':
pdf_zero_object(new_fp, pdf, i, j);
break;
default:
break;
}
}
}
/* Clean */
free(new_name);
fclose(new_fp);
}
static void display_creator(FILE *fp, const pdf_t *pdf)
{
int i;
printf("PDF Version: %d.%d\n",
pdf->pdf_major_version, pdf->pdf_minor_version);
for (i=0; i<pdf->n_xrefs; ++i)
{
if (!pdf->xrefs[i].version)
continue;
if (pdf_display_creator(pdf, i))
printf("\n");
}
}
static pdf_t *init_pdf(FILE *fp, const char *name)
{
pdf_t *pdf;
pdf = pdf_new(name);
pdf_get_version(fp, pdf);
if (pdf_load_xrefs(fp, pdf) == -1) {
pdf_delete(pdf);
return NULL;
}
pdf_load_pages_kids(fp, pdf);
return pdf;
}
int main(int argc, char **argv)
{
int i, n_valid, do_write, do_scrub;
char *c, *dname, *name;
DIR *dir;
FILE *fp;
pdf_t *pdf;
pdf_flag_t flags;
if (argc < 2)
usage();
/* Args */
do_write = do_scrub = flags = 0;
name = NULL;
for (i=1; i<argc; i++)
{
if (strncmp(argv[i], "-w", 2) == 0)
do_write = 1;
else if (strncmp(argv[i], "-i", 2) == 0)
flags |= PDF_FLAG_DISP_CREATOR;
else if (strncmp(argv[i], "-q", 2) == 0)
flags |= PDF_FLAG_QUIET;
else if (strncmp(argv[i], "-s", 2) == 0)
do_scrub = 1;
else if (argv[i][0] != '-')
name = argv[i];
else if (argv[i][0] == '-')
usage();
}
if (!name)
usage();
if (!(fp = fopen(name, "r")))
{
ERR("Could not open file '%s'\n", argv[1]);
return -1;
}
else if (!pdf_is_pdf(fp))
{
ERR("'%s' specified is not a valid PDF\n", name);
fclose(fp);
return -1;
}
/* Load PDF */
if (!(pdf = init_pdf(fp, name)))
{
fclose(fp);
return -1;
}
/* Count valid xrefs */
for (i=0, n_valid=0; i<pdf->n_xrefs; i++)
if (pdf->xrefs[i].version)
++n_valid;
/* Bail if we only have 1 valid */
if (n_valid < 2)
{
if (!(flags & (PDF_FLAG_QUIET | PDF_FLAG_DISP_CREATOR)))
printf("%s: There is only one version of this PDF\n", pdf->name);
if (do_write)
{
fclose(fp);
pdf_delete(pdf);
return 0;
}
}
dname = NULL;
if (do_write)
{
/* Create directory to place the various versions in */
if ((c = strrchr(name, '/')))
name = c + 1;
if ((c = strrchr(name, '.')))
*c = '\0';
dname = malloc(strlen(name) + 16);
sprintf(dname, "%s-versions", name);
if (!(dir = opendir(dname)))
mkdir(dname, S_IRWXU);
else
{
ERR("This directory already exists, PDF version extraction will "
"not occur.\n");
fclose(fp);
closedir(dir);
free(dname);
pdf_delete(pdf);
return -1;
}
/* Write the pdf as a pervious version */
for (i=0; i<pdf->n_xrefs; i++)
if (pdf->xrefs[i].version)
write_version(fp, name, dname, &pdf->xrefs[i]);
}
/* Generate a per-object summary */
pdf_summarize(fp, pdf, dname, flags);
/* Have we been summoned to scrub history from this PDF */
if (do_scrub)
scrub_document(fp, pdf);
/* Display extra information */
if (flags & PDF_FLAG_DISP_CREATOR)
display_creator(fp, pdf);
fclose(fp);
free(dname);
pdf_delete(pdf);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_1005_0 |
crossvul-cpp_data_bad_4484_0 | /*
* Vividas VIV format Demuxer
* Copyright (c) 2012 Krzysztof Klinikowski
* Copyright (c) 2010 Andrzej Szombierski
* based on vivparse Copyright (c) 2007 Måns Rullgård
*
* This file is part of FFmpeg.
*
* FFmpeg 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.
*
* FFmpeg 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 FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* @brief Vividas VIV (.viv) file demuxer
* @author Andrzej Szombierski [qq at kuku eu org] (2010-07)
* @sa http://wiki.multimedia.cx/index.php?title=Vividas_VIV
*/
#include "libavutil/intreadwrite.h"
#include "avio_internal.h"
#include "avformat.h"
#include "internal.h"
#define MAX_AUDIO_SUBPACKETS 100
typedef struct VIV_SB_block {
int size, n_packets;
int64_t byte_offset;
int64_t packet_offset;
} VIV_SB_block;
typedef struct VIV_SB_entry {
int size, flag;
} VIV_SB_entry;
typedef struct VIV_AudioSubpacket {
int start, pcm_bytes;
} VIV_AudioSubpacket;
typedef struct VividasDemuxContext {
int n_sb_blocks;
VIV_SB_block *sb_blocks;
int num_audio;
uint32_t sb_key;
int64_t sb_offset;
int current_sb, current_sb_entry;
uint8_t *sb_buf;
AVIOContext *sb_pb;
int n_sb_entries;
VIV_SB_entry *sb_entries;
int n_audio_subpackets;
int current_audio_subpacket;
int64_t audio_sample;
VIV_AudioSubpacket audio_subpackets[MAX_AUDIO_SUBPACKETS];
} VividasDemuxContext;
static int viv_probe(const AVProbeData *p)
{
if (memcmp(p->buf, "vividas03", 9))
return 0;
return AVPROBE_SCORE_MAX;
}
static const uint8_t keybits[32] = {
20, 52, 111, 10, 27, 71, 142, 53,
82, 138, 1, 78, 86, 121, 183, 85,
105, 152, 39, 140, 172, 11, 64, 144,
155, 6, 71, 163, 186, 49, 126, 43,
};
static uint32_t decode_key(uint8_t *buf)
{
uint32_t key = 0;
for (int i = 0; i < 32; i++) {
unsigned p = keybits[i];
key |= ((buf[p] >> ((i*5+3)&7)) & 1u) << i;
}
return key;
}
static void put_v(uint8_t *p, unsigned v)
{
if (v>>28)
*p++ = ((v>>28)&0x7f)|0x80;
if (v>>21)
*p++ = ((v>>21)&0x7f)|0x80;
if (v>>14)
*p++ = ((v>>14)&0x7f)|0x80;
if (v>>7)
*p++ = ((v>>7)&0x7f)|0x80;
}
static unsigned recover_key(unsigned char sample[4], unsigned expected_size)
{
unsigned char plaintext[8] = { 'S', 'B' };
put_v(plaintext+2, expected_size);
return AV_RL32(sample) ^ AV_RL32(plaintext);
}
static void xor_block(void *p1, void *p2, unsigned size, int key, unsigned *key_ptr)
{
unsigned *d1 = p1;
unsigned *d2 = p2;
unsigned k = *key_ptr;
size >>= 2;
while (size > 0) {
*d2 = *d1 ^ (HAVE_BIGENDIAN ? av_bswap32(k) : k);
k += key;
d1++;
d2++;
size--;
}
*key_ptr = k;
}
static void decode_block(uint8_t *src, uint8_t *dest, unsigned size,
uint32_t key, uint32_t *key_ptr,
int align)
{
unsigned s = size;
char tmp[4];
int a2;
if (!size)
return;
align &= 3;
a2 = (4 - align) & 3;
if (align) {
uint32_t tmpkey = *key_ptr - key;
if (a2 > s) {
a2 = s;
avpriv_request_sample(NULL, "tiny aligned block");
}
memcpy(tmp + align, src, a2);
xor_block(tmp, tmp, 4, key, &tmpkey);
memcpy(dest, tmp + align, a2);
s -= a2;
}
if (s >= 4) {
xor_block(src + a2, dest + a2, s & ~3,
key, key_ptr);
s &= 3;
}
if (s) {
size -= s;
memcpy(tmp, src + size, s);
xor_block(&tmp, &tmp, 4, key, key_ptr);
memcpy(dest + size, tmp, s);
}
}
static uint32_t get_v(uint8_t *p, int len)
{
uint32_t v = 0;
const uint8_t *end = p + len;
do {
if (p >= end || v >= UINT_MAX / 128 - *p)
return v;
v <<= 7;
v += *p & 0x7f;
} while (*p++ & 0x80);
return v;
}
static uint8_t *read_vblock(AVIOContext *src, uint32_t *size,
uint32_t key, uint32_t *k2, int align)
{
uint8_t tmp[4];
uint8_t *buf;
unsigned n;
if (avio_read(src, tmp, 4) != 4)
return NULL;
decode_block(tmp, tmp, 4, key, k2, align);
n = get_v(tmp, 4);
if (n < 4)
return NULL;
buf = av_malloc(n);
if (!buf)
return NULL;
*size = n;
n -= 4;
memcpy(buf, tmp, 4);
if (avio_read(src, buf + 4, n) == n) {
decode_block(buf + 4, buf + 4, n, key, k2, align);
} else {
av_free(buf);
buf = NULL;
}
return buf;
}
static uint8_t *read_sb_block(AVIOContext *src, unsigned *size,
uint32_t *key, unsigned expected_size)
{
uint8_t *buf;
uint8_t ibuf[8], sbuf[8];
uint32_t k2;
unsigned n;
if (avio_read(src, ibuf, 8) < 8)
return NULL;
k2 = *key;
decode_block(ibuf, sbuf, 8, *key, &k2, 0);
n = get_v(sbuf+2, 6);
if (sbuf[0] != 'S' || sbuf[1] != 'B' || (expected_size>0 && n != expected_size)) {
uint32_t tmpkey = recover_key(ibuf, expected_size);
k2 = tmpkey;
decode_block(ibuf, sbuf, 8, tmpkey, &k2, 0);
n = get_v(sbuf+2, 6);
if (sbuf[0] != 'S' || sbuf[1] != 'B' || expected_size != n)
return NULL;
*key = tmpkey;
}
if (n < 8)
return NULL;
buf = av_malloc(n);
if (!buf)
return NULL;
memcpy(buf, sbuf, 8);
*size = n;
n -= 8;
if (avio_read(src, buf+8, n) < n) {
av_free(buf);
return NULL;
}
decode_block(buf + 8, buf + 8, n, *key, &k2, 0);
return buf;
}
static int track_header(VividasDemuxContext *viv, AVFormatContext *s, uint8_t *buf, int size)
{
int i, j, ret;
int64_t off;
int val_1;
int num_video;
AVIOContext pb0, *pb = &pb0;
ffio_init_context(pb, buf, size, 0, NULL, NULL, NULL, NULL);
ffio_read_varlen(pb); // track_header_len
avio_r8(pb); // '1'
val_1 = ffio_read_varlen(pb);
for (i=0;i<val_1;i++) {
int c = avio_r8(pb);
if (avio_feof(pb))
return AVERROR_EOF;
for (j=0;j<c;j++) {
if (avio_feof(pb))
return AVERROR_EOF;
avio_r8(pb); // val_3
avio_r8(pb); // val_4
}
}
avio_r8(pb); // num_streams
off = avio_tell(pb);
off += ffio_read_varlen(pb); // val_5
avio_r8(pb); // '2'
num_video = avio_r8(pb);
avio_seek(pb, off, SEEK_SET);
if (num_video != 1) {
av_log(s, AV_LOG_ERROR, "number of video tracks %d is not 1\n", num_video);
return AVERROR_PATCHWELCOME;
}
for (i = 0; i < num_video; i++) {
AVStream *st = avformat_new_stream(s, NULL);
int num, den;
if (!st)
return AVERROR(ENOMEM);
st->id = i;
st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
st->codecpar->codec_id = AV_CODEC_ID_VP6;
off = avio_tell(pb);
off += ffio_read_varlen(pb);
avio_r8(pb); // '3'
avio_r8(pb); // val_7
num = avio_rl32(pb); // frame_time
den = avio_rl32(pb); // time_base
avpriv_set_pts_info(st, 64, num, den);
st->nb_frames = avio_rl32(pb); // n frames
st->codecpar->width = avio_rl16(pb); // width
st->codecpar->height = avio_rl16(pb); // height
avio_r8(pb); // val_8
avio_rl32(pb); // val_9
avio_seek(pb, off, SEEK_SET);
}
off = avio_tell(pb);
off += ffio_read_varlen(pb); // val_10
avio_r8(pb); // '4'
viv->num_audio = avio_r8(pb);
avio_seek(pb, off, SEEK_SET);
if (viv->num_audio != 1)
av_log(s, AV_LOG_WARNING, "number of audio tracks %d is not 1\n", viv->num_audio);
for(i=0;i<viv->num_audio;i++) {
int q;
AVStream *st = avformat_new_stream(s, NULL);
if (!st)
return AVERROR(ENOMEM);
st->id = num_video + i;
st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
st->codecpar->codec_id = AV_CODEC_ID_VORBIS;
off = avio_tell(pb);
off += ffio_read_varlen(pb); // length
avio_r8(pb); // '5'
avio_r8(pb); //codec_id
avio_rl16(pb); //codec_subid
st->codecpar->channels = avio_rl16(pb); // channels
st->codecpar->sample_rate = avio_rl32(pb); // sample_rate
avio_seek(pb, 10, SEEK_CUR); // data_1
q = avio_r8(pb);
avio_seek(pb, q, SEEK_CUR); // data_2
avio_r8(pb); // zeropad
if (avio_tell(pb) < off) {
int num_data;
int xd_size = 0;
int data_len[256];
int offset = 1;
uint8_t *p;
ffio_read_varlen(pb); // val_13
avio_r8(pb); // '19'
ffio_read_varlen(pb); // len_3
num_data = avio_r8(pb);
for (j = 0; j < num_data; j++) {
uint64_t len = ffio_read_varlen(pb);
if (len > INT_MAX/2 - xd_size) {
return AVERROR_INVALIDDATA;
}
data_len[j] = len;
xd_size += len;
}
ret = ff_alloc_extradata(st->codecpar, 64 + xd_size + xd_size / 255);
if (ret < 0)
return ret;
p = st->codecpar->extradata;
p[0] = 2;
for (j = 0; j < num_data - 1; j++) {
unsigned delta = av_xiphlacing(&p[offset], data_len[j]);
if (delta > data_len[j]) {
return AVERROR_INVALIDDATA;
}
offset += delta;
}
for (j = 0; j < num_data; j++) {
int ret = avio_read(pb, &p[offset], data_len[j]);
if (ret < data_len[j]) {
st->codecpar->extradata_size = 0;
av_freep(&st->codecpar->extradata);
break;
}
offset += data_len[j];
}
if (offset < st->codecpar->extradata_size)
st->codecpar->extradata_size = offset;
}
}
return 0;
}
static int track_index(VividasDemuxContext *viv, AVFormatContext *s, uint8_t *buf, unsigned size)
{
int64_t off;
int64_t poff;
int maxnp=0;
AVIOContext pb0, *pb = &pb0;
int i;
int64_t filesize = avio_size(s->pb);
uint64_t n_sb_blocks_tmp;
ffio_init_context(pb, buf, size, 0, NULL, NULL, NULL, NULL);
ffio_read_varlen(pb); // track_index_len
avio_r8(pb); // 'c'
n_sb_blocks_tmp = ffio_read_varlen(pb);
if (n_sb_blocks_tmp > size / 2)
return AVERROR_INVALIDDATA;
viv->sb_blocks = av_calloc(n_sb_blocks_tmp, sizeof(*viv->sb_blocks));
if (!viv->sb_blocks) {
return AVERROR(ENOMEM);
}
viv->n_sb_blocks = n_sb_blocks_tmp;
off = 0;
poff = 0;
for (i = 0; i < viv->n_sb_blocks; i++) {
uint64_t size_tmp = ffio_read_varlen(pb);
uint64_t n_packets_tmp = ffio_read_varlen(pb);
if (size_tmp > INT_MAX || n_packets_tmp > INT_MAX)
return AVERROR_INVALIDDATA;
viv->sb_blocks[i].byte_offset = off;
viv->sb_blocks[i].packet_offset = poff;
viv->sb_blocks[i].size = size_tmp;
viv->sb_blocks[i].n_packets = n_packets_tmp;
off += viv->sb_blocks[i].size;
poff += viv->sb_blocks[i].n_packets;
if (maxnp < viv->sb_blocks[i].n_packets)
maxnp = viv->sb_blocks[i].n_packets;
}
if (filesize > 0 && poff > filesize)
return AVERROR_INVALIDDATA;
viv->sb_entries = av_calloc(maxnp, sizeof(VIV_SB_entry));
if (!viv->sb_entries)
return AVERROR(ENOMEM);
return 0;
}
static void load_sb_block(AVFormatContext *s, VividasDemuxContext *viv, unsigned expected_size)
{
uint32_t size = 0;
int i;
AVIOContext *pb = 0;
if (viv->sb_pb) {
av_free(viv->sb_pb);
viv->sb_pb = NULL;
}
if (viv->sb_buf)
av_free(viv->sb_buf);
viv->sb_buf = read_sb_block(s->pb, &size, &viv->sb_key, expected_size);
if (!viv->sb_buf) {
return;
}
pb = avio_alloc_context(viv->sb_buf, size, 0, NULL, NULL, NULL, NULL);
if (!pb)
return;
viv->sb_pb = pb;
avio_r8(pb); // 'S'
avio_r8(pb); // 'B'
ffio_read_varlen(pb); // size
avio_r8(pb); // junk
ffio_read_varlen(pb); // first packet
viv->n_sb_entries = viv->sb_blocks[viv->current_sb].n_packets;
for (i = 0; i < viv->n_sb_entries; i++) {
viv->sb_entries[i].size = ffio_read_varlen(pb);
viv->sb_entries[i].flag = avio_r8(pb);
}
ffio_read_varlen(pb);
avio_r8(pb);
viv->current_sb_entry = 0;
}
static int viv_read_header(AVFormatContext *s)
{
VividasDemuxContext *viv = s->priv_data;
AVIOContext *pb = s->pb;
int64_t header_end;
int num_tracks;
uint32_t key, k2;
uint32_t v;
uint8_t keybuffer[187];
uint32_t b22_size = 0;
uint32_t b22_key = 0;
uint8_t *buf = 0;
int ret;
avio_skip(pb, 9);
header_end = avio_tell(pb);
header_end += ffio_read_varlen(pb);
num_tracks = avio_r8(pb);
if (num_tracks != 1) {
av_log(s, AV_LOG_ERROR, "number of tracks %d is not 1\n", num_tracks);
return AVERROR(EINVAL);
}
v = avio_r8(pb);
avio_seek(pb, v, SEEK_CUR);
avio_read(pb, keybuffer, 187);
key = decode_key(keybuffer);
viv->sb_key = key;
avio_rl32(pb);
for (;;) {
int64_t here = avio_tell(pb);
int block_len, block_type;
if (here >= header_end)
break;
block_len = ffio_read_varlen(pb);
if (avio_feof(pb) || block_len <= 0)
return AVERROR_INVALIDDATA;
block_type = avio_r8(pb);
if (block_type == 22) {
avio_read(pb, keybuffer, 187);
b22_key = decode_key(keybuffer);
b22_size = avio_rl32(pb);
}
avio_seek(pb, here + block_len, SEEK_SET);
}
if (b22_size) {
k2 = b22_key;
buf = read_vblock(pb, &v, b22_key, &k2, 0);
if (!buf)
return AVERROR(EIO);
av_free(buf);
}
k2 = key;
buf = read_vblock(pb, &v, key, &k2, 0);
if (!buf)
return AVERROR(EIO);
ret = track_header(viv, s, buf, v);
av_free(buf);
if (ret < 0)
return ret;
buf = read_vblock(pb, &v, key, &k2, v);
if (!buf)
return AVERROR(EIO);
ret = track_index(viv, s, buf, v);
av_free(buf);
if (ret < 0)
goto fail;
viv->sb_offset = avio_tell(pb);
if (viv->n_sb_blocks > 0) {
viv->current_sb = 0;
load_sb_block(s, viv, viv->sb_blocks[0].size);
} else {
viv->current_sb = -1;
}
return 0;
fail:
av_freep(&viv->sb_blocks);
return ret;
}
static int viv_read_packet(AVFormatContext *s,
AVPacket *pkt)
{
VividasDemuxContext *viv = s->priv_data;
AVIOContext *pb;
int64_t off;
int ret;
if (!viv->sb_pb)
return AVERROR(EIO);
if (avio_feof(viv->sb_pb))
return AVERROR_EOF;
if (viv->current_audio_subpacket < viv->n_audio_subpackets) {
AVStream *astream;
int size = viv->audio_subpackets[viv->current_audio_subpacket+1].start - viv->audio_subpackets[viv->current_audio_subpacket].start;
pb = viv->sb_pb;
ret = av_get_packet(pb, pkt, size);
if (ret < 0)
return ret;
pkt->pos += viv->sb_offset + viv->sb_blocks[viv->current_sb].byte_offset;
pkt->stream_index = 1;
astream = s->streams[pkt->stream_index];
pkt->pts = av_rescale_q(viv->audio_sample, av_make_q(1, astream->codecpar->sample_rate), astream->time_base);
viv->audio_sample += viv->audio_subpackets[viv->current_audio_subpacket].pcm_bytes / 2 / astream->codecpar->channels;
pkt->flags |= AV_PKT_FLAG_KEY;
viv->current_audio_subpacket++;
return 0;
}
if (viv->current_sb_entry >= viv->n_sb_entries) {
if (viv->current_sb+1 >= viv->n_sb_blocks)
return AVERROR(EIO);
viv->current_sb++;
load_sb_block(s, viv, 0);
viv->current_sb_entry = 0;
}
pb = viv->sb_pb;
if (!pb)
return AVERROR(EIO);
off = avio_tell(pb);
if (viv->current_sb_entry >= viv->n_sb_entries)
return AVERROR_INVALIDDATA;
off += viv->sb_entries[viv->current_sb_entry].size;
if (viv->sb_entries[viv->current_sb_entry].flag == 0) {
uint64_t v_size = ffio_read_varlen(pb);
if (!viv->num_audio)
return AVERROR_INVALIDDATA;
ffio_read_varlen(pb);
if (v_size > INT_MAX || !v_size)
return AVERROR_INVALIDDATA;
ret = av_get_packet(pb, pkt, v_size);
if (ret < 0)
return ret;
pkt->pos += viv->sb_offset + viv->sb_blocks[viv->current_sb].byte_offset;
pkt->pts = viv->sb_blocks[viv->current_sb].packet_offset + viv->current_sb_entry;
pkt->flags |= (pkt->data[0]&0x80)?0:AV_PKT_FLAG_KEY;
pkt->stream_index = 0;
for (int i = 0; i < MAX_AUDIO_SUBPACKETS - 1; i++) {
int start, pcm_bytes;
start = ffio_read_varlen(pb);
pcm_bytes = ffio_read_varlen(pb);
if (i > 0 && start == 0)
break;
viv->n_audio_subpackets = i + 1;
viv->audio_subpackets[i].start = start;
viv->audio_subpackets[i].pcm_bytes = pcm_bytes;
}
viv->audio_subpackets[viv->n_audio_subpackets].start = (int)(off - avio_tell(pb));
viv->current_audio_subpacket = 0;
} else {
uint64_t v_size = ffio_read_varlen(pb);
if (v_size > INT_MAX || !v_size)
return AVERROR_INVALIDDATA;
ret = av_get_packet(pb, pkt, v_size);
if (ret < 0)
return ret;
pkt->pos += viv->sb_offset + viv->sb_blocks[viv->current_sb].byte_offset;
pkt->pts = viv->sb_blocks[viv->current_sb].packet_offset + viv->current_sb_entry;
pkt->flags |= (pkt->data[0] & 0x80) ? 0 : AV_PKT_FLAG_KEY;
pkt->stream_index = 0;
}
viv->current_sb_entry++;
return 0;
}
static int viv_read_close(AVFormatContext *s)
{
VividasDemuxContext *viv = s->priv_data;
av_freep(&viv->sb_pb);
av_freep(&viv->sb_buf);
av_freep(&viv->sb_blocks);
av_freep(&viv->sb_entries);
return 0;
}
static int viv_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
{
VividasDemuxContext *viv = s->priv_data;
int64_t frame;
if (stream_index == 0)
frame = timestamp;
else
frame = av_rescale_q(timestamp, s->streams[0]->time_base, s->streams[stream_index]->time_base);
for (int i = 0; i < viv->n_sb_blocks; i++) {
if (frame >= viv->sb_blocks[i].packet_offset && frame < viv->sb_blocks[i].packet_offset + viv->sb_blocks[i].n_packets) {
// flush audio packet queue
viv->current_audio_subpacket = 0;
viv->n_audio_subpackets = 0;
viv->current_sb = i;
// seek to ith sb block
avio_seek(s->pb, viv->sb_offset + viv->sb_blocks[i].byte_offset, SEEK_SET);
// load the block
load_sb_block(s, viv, 0);
// most problematic part: guess audio offset
viv->audio_sample = av_rescale_q(viv->sb_blocks[i].packet_offset, av_make_q(s->streams[1]->codecpar->sample_rate, 1), av_inv_q(s->streams[0]->time_base));
// hand-tuned 1.s a/v offset
viv->audio_sample += s->streams[1]->codecpar->sample_rate;
viv->current_sb_entry = 0;
return 1;
}
}
return 0;
}
AVInputFormat ff_vividas_demuxer = {
.name = "vividas",
.long_name = NULL_IF_CONFIG_SMALL("Vividas VIV"),
.priv_data_size = sizeof(VividasDemuxContext),
.read_probe = viv_probe,
.read_header = viv_read_header,
.read_packet = viv_read_packet,
.read_close = viv_read_close,
.read_seek = viv_read_seek,
};
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_4484_0 |
crossvul-cpp_data_good_3411_1 | // Notes and useful links:
// This conversation (https://www.sourceware.org/ml/gdb/2009-02/msg00100.html) suggests GDB clients usually ignore error codes
// Useful, but not to be blindly trusted - http://www.embecosm.com/appnotes/ean4/embecosm-howto-rsp-server-ean4-issue-2.html
// https://github.com/llvm-mirror/lldb/blob/master/docs/lldb-gdb-remote.txt
// http://www.cygwin.com/ml/gdb/2008-05/msg00166.html
#include "gdbserver/core.h"
#include "gdbr_common.h"
#include "libgdbr.h"
#include "packet.h"
#include "utils.h"
#include "r_util/r_str.h"
static int _server_handle_qSupported(libgdbr_t *g) {
int ret;
char *buf;
if (!(buf = malloc (128))) {
return -1;
}
snprintf (buf, 127, "PacketSize=%x", (ut32) (g->read_max - 1));
if ((ret = handle_qSupported (g)) < 0) {
return -1;
}
ret = send_msg (g, buf);
free (buf);
return ret;
}
static int _server_handle_qTStatus(libgdbr_t *g) {
int ret;
// TODO Handle proper reporting of trace status
const char *message = "";
if ((ret = send_ack (g)) < 0) {
return -1;
}
return send_msg (g, message);
}
static int _server_handle_s(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) {
char message[64];
if (send_ack (g) < 0) {
return -1;
}
if (g->data_len > 1) {
// We don't handle s[addr] packet
return send_msg (g, "E01");
}
if (cmd_cb (core_ptr, "ds", NULL, 0) < 0) {
send_msg (g, "E01");
return -1;
}
// TODO This packet should specify why we stopped. Right now only for trap
snprintf (message, sizeof (message) - 1, "T05thread:%x;", cmd_cb (core_ptr, "dptr", NULL, 0));
return send_msg (g, message);
}
static int _server_handle_c(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) {
char message[64];
if (send_ack (g) < 0) {
return -1;
}
if (g->data_len > 1) {
// We don't handle s[addr] packet
return send_msg (g, "E01");
}
if (cmd_cb (core_ptr, "dc", NULL, 0) < 0) {
send_msg (g, "E01");
return -1;
}
// TODO This packet should specify why we stopped. Right now only for trap
snprintf (message, sizeof (message) - 1, "T05thread:%x;", cmd_cb (core_ptr, "dptr", NULL, 0));
return send_msg (g, message);
}
static int _server_handle_ques(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) {
// TODO This packet should specify why we stopped. Right now only for trap
char message[64];
if (send_ack (g) < 0) {
return -1;
}
snprintf (message, sizeof (message) - 1, "T05thread:%x;", cmd_cb (core_ptr, "dptr", NULL, 0));
return send_msg (g, message);
}
static int _server_handle_qC(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) {
char *buf;
int ret;
size_t buf_len = 80;
if ((ret = send_ack (g)) < 0) {
return -1;
}
if (!(buf = malloc (buf_len))) {
return -1;
}
if ((ret = cmd_cb (core_ptr, "dp", buf, buf_len)) < 0) {
free (buf);
return -1;
}
ret = send_msg (g, buf);
free (buf);
return ret;
}
static int _server_handle_k(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) {
send_ack (g);
return -1;
}
static int _server_handle_vKill(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) {
if (send_ack (g) < 0) {
return -1;
}
// TODO handle killing of pid
send_msg (g, "OK");
return -1;
}
static int _server_handle_z(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) {
if (send_ack (g) < 0) {
return -1;
}
char set; // Z = set, z = remove
int type;
ut64 addr;
char cmd[64];
sscanf (g->data, "%c%d,%"PFMT64x, &set, &type, &addr);
if (type != 0) {
// TODO handle hw breakpoints and watchpoints
return send_msg (g, "E01");
}
switch (set) {
case 'Z':
// Set
snprintf (cmd, sizeof (cmd) - 1, "db 0x%"PFMT64x, addr);
break;
case 'z':
// Remove
snprintf (cmd, sizeof (cmd) - 1, "db- 0x%"PFMT64x, addr);
break;
default:
return send_msg (g, "E01");
}
if (cmd_cb (core_ptr, cmd, NULL, 0) < 0) {
send_msg (g, "E01");
return -1;
}
return send_msg (g, "OK");
}
static int _server_handle_vCont(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) {
char *action = NULL;
if (send_ack (g) < 0) {
return -1;
}
g->data[g->data_len] = '\0';
if (g->data[5] == '?') {
// Query about everything we support
return send_msg (g, "vCont;c;s");
}
if (!(action = strtok (g->data, ";"))) {
return send_msg (g, "E01");
}
while (action = strtok (NULL, ";")) {
eprintf ("action: %s\n", action);
switch (action[0]) {
case 's':
// TODO handle thread selections
if (cmd_cb (core_ptr, "ds", NULL, 0) < 0) {
send_msg (g, "E01");
return -1;
}
return send_msg (g, "OK");
case 'c':
// TODO handle thread selections
if (cmd_cb (core_ptr, "dc", NULL, 0) < 0) {
send_msg (g, "E01");
return -1;
}
return send_msg (g, "OK");
default:
// TODO support others
return send_msg (g, "E01");
}
}
return -1;
}
static int _server_handle_qAttached(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) {
if (send_ack (g) < 0) {
return -1;
}
// TODO check if process was attached or created
// Right now, says that process was created
return send_msg (g, "0");
}
// TODO, proper handling of Hg and Hc (right now handled identically)
// Set thread for all operations other than "step" and "continue"
static int _server_handle_Hg(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) {
// We don't yet support multiprocess. Client is not supposed to send Hgp. If we receive it anyway,
// send error
char cmd[32];
int tid;
if (send_ack (g) < 0) {
return -1;
}
if (g->data_len <= 2 || isalpha (g->data[2])) {
return send_msg (g, "E01");
}
// Hg-1 = "all threads", Hg0 = "pick any thread"
if (g->data[2] == '0' || !strncmp (g->data + 2, "-1", 2)) {
return send_msg (g, "OK");
}
sscanf (g->data + 2, "%x", &tid);
snprintf (cmd, sizeof (cmd) - 1, "dpt=%d", tid);
// Set thread for future operations
if (cmd_cb (core_ptr, cmd, NULL, 0) < 0) {
send_msg (g, "E01");
return -1;
}
return send_msg (g, "OK");
}
// Set thread for "step" and "continue"
static int _server_handle_Hc(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) {
// Usually this is only sent with Hc-1. Still. Set the threads for next operations
char cmd[32];
int tid;
if (send_ack (g) < 0) {
return -1;
}
if (g->data_len <= 2 || isalpha (g->data[2])) {
return send_msg (g, "E01");
}
// Hc-1 = "all threads", Hc0 = "pick any thread"
if (g->data[2] == '0' || !strncmp (g->data + 2, "-1", 2)) {
return send_msg (g, "OK");
}
sscanf (g->data + 2, "%x", &tid);
snprintf (cmd, sizeof (cmd) - 1, "dpt=%d", tid);
// Set thread for future operations
if (cmd_cb (core_ptr, cmd, NULL, 0) < 0) {
send_msg (g, "E01");
return -1;
}
return send_msg (g, "OK");
}
static int _server_handle_qfThreadInfo(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) {
char *buf;
int ret;
size_t buf_len = 80;
if ((ret = send_ack (g)) < 0) {
return -1;
}
if (!(buf = malloc (buf_len))) {
return -1;
}
if ((ret = cmd_cb (core_ptr, "dpt", buf, buf_len)) < 0) {
free (buf);
return -1;
}
ret = send_msg (g, buf);
free (buf);
return ret;
}
static int _server_handle_qsThreadInfo(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) {
// TODO handle overflow from qfThreadInfo. Otherwise this won't work with programs with many threads
if (send_ack (g) < 0 || send_msg (g, "l") < 0) {
return -1;
}
return 0;
}
static int _server_handle_g(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) {
char *buf;
// To be very safe
int buf_len = 4096;
int ret;
if (send_ack (g) < 0) {
return -1;
}
if (!(buf = malloc (buf_len))) {
send_msg (g, "E01");
return -1;
}
memset (buf, 0, buf_len);
if ((buf_len = cmd_cb (core_ptr, "dr", buf, buf_len)) < 0) {
free (buf);
send_msg (g, "E01");
return -1;
}
ret = send_msg (g, buf);
free (buf);
return ret;
}
static int _server_handle_m(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) {
int ret;
ut64 addr;
int length;
char *buf1, *buf2, cmd[64];
int buf1_len, buf2_len;
if (send_ack (g) < 0) {
return -1;
}
g->data[g->data_len] = 0;
sscanf (g->data, "m%"PFMT64x",%d", &addr, &length);
if (g->data_len < 4 || !strchr (g->data, ',')) {
return send_msg (g, "E01");
}
buf1_len = length;
buf2_len = length * 2 + 1;
if (!(buf1 = malloc (buf1_len))) {
return -1;
}
if (!(buf2 = malloc (buf2_len))) {
free (buf1);
return -1;
}
memset (buf2, 0, buf2_len);
snprintf (cmd, sizeof (cmd) - 1, "m %"PFMT64x" %d", addr, length);
if ((buf1_len = cmd_cb (core_ptr, cmd, buf1, buf1_len)) < 0) {
free (buf1);
free (buf2);
send_msg (g, "E01");
return -1;
}
pack_hex (buf1, buf1_len, buf2);
ret = send_msg (g, buf2);
free (buf1);
free (buf2);
return ret;
}
static int _server_handle_vMustReplyEmpty(libgdbr_t *g) {
if (send_ack (g) < 0) {
return -1;
}
return send_msg (g, "");
}
static int _server_handle_qTfV(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) {
// TODO
if (send_ack (g) < 0) {
return -1;
}
return send_msg (g, "");
}
int gdbr_server_serve(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) {
int ret;
if (!g) {
return -1;
}
while (1) {
read_packet (g);
if (g->data_len == 0) {
continue;
}
if (r_str_startswith (g->data, "k")) {
return _server_handle_k (g, cmd_cb, core_ptr);
}
if (r_str_startswith (g->data, "vKill")) {
return _server_handle_vKill (g, cmd_cb, core_ptr);
}
if (r_str_startswith (g->data, "qSupported")) {
if ((ret = _server_handle_qSupported (g)) < 0) {
return ret;
}
continue;
}
if (r_str_startswith (g->data, "qTStatus")) {
if ((ret = _server_handle_qTStatus (g)) < 0) {
return ret;
}
continue;
}
if (r_str_startswith (g->data, "qC") && g->data_len == 2) {
if ((ret = _server_handle_qC (g, cmd_cb, core_ptr)) < 0) {
return ret;
}
continue;
}
if (r_str_startswith (g->data, "qAttached")) {
if ((ret = _server_handle_qAttached (g, cmd_cb, core_ptr)) < 0) {
return ret;
}
continue;
}
if (r_str_startswith (g->data, "vMustReplyEmpty")) {
if ((ret = _server_handle_vMustReplyEmpty (g)) < 0) {
return ret;
}
continue;
}
if (r_str_startswith (g->data, "qTfV")) {
if ((ret = _server_handle_qTfV (g, cmd_cb, core_ptr)) < 0) {
return ret;
}
continue;
}
if (r_str_startswith (g->data, "qfThreadInfo")) {
if ((ret = _server_handle_qfThreadInfo (g, cmd_cb, core_ptr)) < 0) {
return ret;
}
continue;
}
if (r_str_startswith (g->data, "qsThreadInfo")) {
if ((ret = _server_handle_qsThreadInfo (g, cmd_cb, core_ptr)) < 0) {
return ret;
}
continue;
}
if (r_str_startswith (g->data, "Hg")) {
if ((ret = _server_handle_Hg (g, cmd_cb, core_ptr)) < 0) {
return ret;
}
continue;
}
if (r_str_startswith (g->data, "Hc")) {
if ((ret = _server_handle_Hc (g, cmd_cb, core_ptr)) < 0) {
return ret;
}
continue;
}
if (r_str_startswith (g->data, "?")) {
if ((ret = _server_handle_ques (g, cmd_cb, core_ptr)) < 0) {
return ret;
}
continue;
}
if (r_str_startswith (g->data, "g") && g->data_len == 1) {
if ((ret = _server_handle_g (g, cmd_cb, core_ptr)) < 0) {
return ret;
}
continue;
}
if (r_str_startswith (g->data, "vCont")) {
if ((ret = _server_handle_vCont (g, cmd_cb, core_ptr)) < 0) {
return ret;
}
continue;
}
if (g->data[0] == 'z' || g->data[0] == 'Z') {
if ((ret = _server_handle_z (g, cmd_cb, core_ptr)) < 0) {
return ret;
}
continue;
}
if (g->data[0] == 's') {
if ((ret = _server_handle_s (g, cmd_cb, core_ptr)) < 0) {
return ret;
}
continue;
}
if (g->data[0] == 'c') {
if ((ret = _server_handle_c (g, cmd_cb, core_ptr)) < 0) {
return ret;
}
continue;
}
if (r_str_startswith (g->data, "m")) {
if ((ret = _server_handle_m (g, cmd_cb, core_ptr)) < 0) {
return ret;
}
continue;
}
// Unrecognized packet
if (send_ack (g) < 0 || send_msg (g, "") < 0) {
g->data[g->data_len] = '\0';
eprintf ("Unknown packet: %s\n", g->data);
return -1;
}
};
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/good_3411_1 |
crossvul-cpp_data_bad_1805_1 | /* $Id$ */
/*
* Copyright (c) 1988-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.
*/
#include "tiffiop.h"
#ifdef NEXT_SUPPORT
/*
* TIFF Library.
*
* NeXT 2-bit Grey Scale Compression Algorithm Support
*/
#define SETPIXEL(op, v) { \
switch (npixels++ & 3) { \
case 0: op[0] = (unsigned char) ((v) << 6); break; \
case 1: op[0] |= (v) << 4; break; \
case 2: op[0] |= (v) << 2; break; \
case 3: *op++ |= (v); break; \
} \
}
#define LITERALROW 0x00
#define LITERALSPAN 0x40
#define WHITE ((1<<2)-1)
static int
NeXTDecode(TIFF* tif, uint8* buf, tmsize_t occ, uint16 s)
{
static const char module[] = "NeXTDecode";
unsigned char *bp, *op;
tmsize_t cc;
uint8* row;
tmsize_t scanline, n;
(void) s;
/*
* Each scanline is assumed to start off as all
* white (we assume a PhotometricInterpretation
* of ``min-is-black'').
*/
for (op = (unsigned char*) buf, cc = occ; cc-- > 0;)
*op++ = 0xff;
bp = (unsigned char *)tif->tif_rawcp;
cc = tif->tif_rawcc;
scanline = tif->tif_scanlinesize;
if (occ % scanline)
{
TIFFErrorExt(tif->tif_clientdata, module, "Fractional scanlines cannot be read");
return (0);
}
for (row = buf; cc > 0 && occ > 0; occ -= scanline, row += scanline) {
n = *bp++, cc--;
switch (n) {
case LITERALROW:
/*
* The entire scanline is given as literal values.
*/
if (cc < scanline)
goto bad;
_TIFFmemcpy(row, bp, scanline);
bp += scanline;
cc -= scanline;
break;
case LITERALSPAN: {
tmsize_t off;
/*
* The scanline has a literal span that begins at some
* offset.
*/
if( cc < 4 )
goto bad;
off = (bp[0] * 256) + bp[1];
n = (bp[2] * 256) + bp[3];
if (cc < 4+n || off+n > scanline)
goto bad;
_TIFFmemcpy(row+off, bp+4, n);
bp += 4+n;
cc -= 4+n;
break;
}
default: {
uint32 npixels = 0, grey;
uint32 imagewidth = tif->tif_dir.td_imagewidth;
if( isTiled(tif) )
imagewidth = tif->tif_dir.td_tilewidth;
/*
* The scanline is composed of a sequence of constant
* color ``runs''. We shift into ``run mode'' and
* interpret bytes as codes of the form
* <color><npixels> until we've filled the scanline.
*/
op = row;
for (;;) {
grey = (uint32)((n>>6) & 0x3);
n &= 0x3f;
/*
* Ensure the run does not exceed the scanline
* bounds, potentially resulting in a security
* issue.
*/
while (n-- > 0 && npixels < imagewidth)
SETPIXEL(op, grey);
if (npixels >= imagewidth)
break;
if (cc == 0)
goto bad;
n = *bp++, cc--;
}
break;
}
}
}
tif->tif_rawcp = (uint8*) bp;
tif->tif_rawcc = cc;
return (1);
bad:
TIFFErrorExt(tif->tif_clientdata, module, "Not enough data for scanline %ld",
(long) tif->tif_row);
return (0);
}
static int
NeXTPreDecode(TIFF* tif, uint16 s)
{
static const char module[] = "NeXTPreDecode";
TIFFDirectory *td = &tif->tif_dir;
(void)s;
if( td->td_bitspersample != 2 )
{
TIFFErrorExt(tif->tif_clientdata, module, "Unsupported BitsPerSample = %d",
td->td_bitspersample);
return (0);
}
return (1);
}
int
TIFFInitNeXT(TIFF* tif, int scheme)
{
(void) scheme;
tif->tif_predecode = NeXTPreDecode;
tif->tif_decoderow = NeXTDecode;
tif->tif_decodestrip = NeXTDecode;
tif->tif_decodetile = NeXTDecode;
return (1);
}
#endif /* NEXT_SUPPORT */
/* 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-787/c/bad_1805_1 |
crossvul-cpp_data_bad_3295_0 | /*
* Pictor/PC Paint decoder
* Copyright (c) 2010 Peter Ross <pross@xvid.org>
*
* This file is part of FFmpeg.
*
* FFmpeg 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.
*
* FFmpeg 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 FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* Pictor/PC Paint decoder
*/
#include "libavutil/imgutils.h"
#include "avcodec.h"
#include "bytestream.h"
#include "cga_data.h"
#include "internal.h"
typedef struct PicContext {
int width, height;
int nb_planes;
GetByteContext g;
} PicContext;
static void picmemset_8bpp(PicContext *s, AVFrame *frame, int value, int run,
int *x, int *y)
{
while (run > 0) {
uint8_t *d = frame->data[0] + *y * frame->linesize[0];
if (*x + run >= s->width) {
int n = s->width - *x;
memset(d + *x, value, n);
run -= n;
*x = 0;
*y -= 1;
if (*y < 0)
break;
} else {
memset(d + *x, value, run);
*x += run;
break;
}
}
}
static void picmemset(PicContext *s, AVFrame *frame, int value, int run,
int *x, int *y, int *plane, int bits_per_plane)
{
uint8_t *d;
int shift = *plane * bits_per_plane;
int mask = ((1 << bits_per_plane) - 1) << shift;
value <<= shift;
while (run > 0) {
int j;
for (j = 8-bits_per_plane; j >= 0; j -= bits_per_plane) {
d = frame->data[0] + *y * frame->linesize[0];
d[*x] |= (value >> j) & mask;
*x += 1;
if (*x == s->width) {
*y -= 1;
*x = 0;
if (*y < 0) {
*y = s->height - 1;
*plane += 1;
value <<= bits_per_plane;
mask <<= bits_per_plane;
if (*plane >= s->nb_planes)
break;
}
}
}
run--;
}
}
static const uint8_t cga_mode45_index[6][4] = {
[0] = { 0, 3, 5, 7 }, // mode4, palette#1, low intensity
[1] = { 0, 2, 4, 6 }, // mode4, palette#2, low intensity
[2] = { 0, 3, 4, 7 }, // mode5, low intensity
[3] = { 0, 11, 13, 15 }, // mode4, palette#1, high intensity
[4] = { 0, 10, 12, 14 }, // mode4, palette#2, high intensity
[5] = { 0, 11, 12, 15 }, // mode5, high intensity
};
static int decode_frame(AVCodecContext *avctx,
void *data, int *got_frame,
AVPacket *avpkt)
{
PicContext *s = avctx->priv_data;
AVFrame *frame = data;
uint32_t *palette;
int bits_per_plane, bpp, etype, esize, npal, pos_after_pal;
int i, x, y, plane, tmp, ret, val;
bytestream2_init(&s->g, avpkt->data, avpkt->size);
if (bytestream2_get_bytes_left(&s->g) < 11)
return AVERROR_INVALIDDATA;
if (bytestream2_get_le16u(&s->g) != 0x1234)
return AVERROR_INVALIDDATA;
s->width = bytestream2_get_le16u(&s->g);
s->height = bytestream2_get_le16u(&s->g);
bytestream2_skip(&s->g, 4);
tmp = bytestream2_get_byteu(&s->g);
bits_per_plane = tmp & 0xF;
s->nb_planes = (tmp >> 4) + 1;
bpp = bits_per_plane * s->nb_planes;
if (bits_per_plane > 8 || bpp < 1 || bpp > 32) {
avpriv_request_sample(avctx, "Unsupported bit depth");
return AVERROR_PATCHWELCOME;
}
if (bytestream2_peek_byte(&s->g) == 0xFF || bpp == 1 || bpp == 4 || bpp == 8) {
bytestream2_skip(&s->g, 2);
etype = bytestream2_get_le16(&s->g);
esize = bytestream2_get_le16(&s->g);
if (bytestream2_get_bytes_left(&s->g) < esize)
return AVERROR_INVALIDDATA;
} else {
etype = -1;
esize = 0;
}
avctx->pix_fmt = AV_PIX_FMT_PAL8;
if (av_image_check_size(s->width, s->height, 0, avctx) < 0)
return -1;
if (s->width != avctx->width && s->height != avctx->height) {
ret = ff_set_dimensions(avctx, s->width, s->height);
if (ret < 0)
return ret;
}
if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
return ret;
memset(frame->data[0], 0, s->height * frame->linesize[0]);
frame->pict_type = AV_PICTURE_TYPE_I;
frame->palette_has_changed = 1;
pos_after_pal = bytestream2_tell(&s->g) + esize;
palette = (uint32_t*)frame->data[1];
if (etype == 1 && esize > 1 && bytestream2_peek_byte(&s->g) < 6) {
int idx = bytestream2_get_byte(&s->g);
npal = 4;
for (i = 0; i < npal; i++)
palette[i] = ff_cga_palette[ cga_mode45_index[idx][i] ];
} else if (etype == 2) {
npal = FFMIN(esize, 16);
for (i = 0; i < npal; i++) {
int pal_idx = bytestream2_get_byte(&s->g);
palette[i] = ff_cga_palette[FFMIN(pal_idx, 15)];
}
} else if (etype == 3) {
npal = FFMIN(esize, 16);
for (i = 0; i < npal; i++) {
int pal_idx = bytestream2_get_byte(&s->g);
palette[i] = ff_ega_palette[FFMIN(pal_idx, 63)];
}
} else if (etype == 4 || etype == 5) {
npal = FFMIN(esize / 3, 256);
for (i = 0; i < npal; i++) {
palette[i] = bytestream2_get_be24(&s->g) << 2;
palette[i] |= 0xFFU << 24 | palette[i] >> 6 & 0x30303;
}
} else {
if (bpp == 1) {
npal = 2;
palette[0] = 0xFF000000;
palette[1] = 0xFFFFFFFF;
} else if (bpp == 2) {
npal = 4;
for (i = 0; i < npal; i++)
palette[i] = ff_cga_palette[ cga_mode45_index[0][i] ];
} else {
npal = 16;
memcpy(palette, ff_cga_palette, npal * 4);
}
}
// fill remaining palette entries
memset(palette + npal, 0, AVPALETTE_SIZE - npal * 4);
// skip remaining palette bytes
bytestream2_seek(&s->g, pos_after_pal, SEEK_SET);
val = 0;
y = s->height - 1;
if (bytestream2_get_le16(&s->g)) {
x = 0;
plane = 0;
while (bytestream2_get_bytes_left(&s->g) >= 6) {
int stop_size, marker, t1, t2;
t1 = bytestream2_get_bytes_left(&s->g);
t2 = bytestream2_get_le16(&s->g);
stop_size = t1 - FFMIN(t1, t2);
// ignore uncompressed block size
bytestream2_skip(&s->g, 2);
marker = bytestream2_get_byte(&s->g);
while (plane < s->nb_planes &&
bytestream2_get_bytes_left(&s->g) > stop_size) {
int run = 1;
val = bytestream2_get_byte(&s->g);
if (val == marker) {
run = bytestream2_get_byte(&s->g);
if (run == 0)
run = bytestream2_get_le16(&s->g);
val = bytestream2_get_byte(&s->g);
}
if (!bytestream2_get_bytes_left(&s->g))
break;
if (bits_per_plane == 8) {
picmemset_8bpp(s, frame, val, run, &x, &y);
if (y < 0)
goto finish;
} else {
picmemset(s, frame, val, run, &x, &y, &plane, bits_per_plane);
}
}
}
if (x < avctx->width) {
int run = (y + 1) * avctx->width - x;
if (bits_per_plane == 8)
picmemset_8bpp(s, frame, val, run, &x, &y);
else
picmemset(s, frame, val, run / (8 / bits_per_plane), &x, &y, &plane, bits_per_plane);
}
} else {
while (y >= 0 && bytestream2_get_bytes_left(&s->g) > 0) {
memcpy(frame->data[0] + y * frame->linesize[0], s->g.buffer, FFMIN(avctx->width, bytestream2_get_bytes_left(&s->g)));
bytestream2_skip(&s->g, avctx->width);
y--;
}
}
finish:
*got_frame = 1;
return avpkt->size;
}
AVCodec ff_pictor_decoder = {
.name = "pictor",
.long_name = NULL_IF_CONFIG_SMALL("Pictor/PC Paint"),
.type = AVMEDIA_TYPE_VIDEO,
.id = AV_CODEC_ID_PICTOR,
.priv_data_size = sizeof(PicContext),
.decode = decode_frame,
.capabilities = AV_CODEC_CAP_DR1,
};
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_3295_0 |
crossvul-cpp_data_bad_3375_0 | /**********************************************************************
regparse.c - Oniguruma (regular expression library)
**********************************************************************/
/*-
* Copyright (c) 2002-2016 K.Kosako <sndgk393 AT ybb DOT ne DOT jp>
* 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 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 AUTHOR 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 "regparse.h"
#include "st.h"
#ifdef DEBUG_NODE_FREE
#include <stdio.h>
#endif
#define WARN_BUFSIZE 256
#define CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS
OnigSyntaxType OnigSyntaxRuby = {
(( SYN_GNU_REGEX_OP | ONIG_SYN_OP_QMARK_NON_GREEDY |
ONIG_SYN_OP_ESC_OCTAL3 | ONIG_SYN_OP_ESC_X_HEX2 |
ONIG_SYN_OP_ESC_X_BRACE_HEX8 | ONIG_SYN_OP_ESC_CONTROL_CHARS |
ONIG_SYN_OP_ESC_C_CONTROL )
& ~ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END )
, ( ONIG_SYN_OP2_QMARK_GROUP_EFFECT |
ONIG_SYN_OP2_OPTION_RUBY |
ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP | ONIG_SYN_OP2_ESC_K_NAMED_BACKREF |
ONIG_SYN_OP2_ESC_G_SUBEXP_CALL |
ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY |
ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT |
ONIG_SYN_OP2_PLUS_POSSESSIVE_REPEAT |
ONIG_SYN_OP2_CCLASS_SET_OP | ONIG_SYN_OP2_ESC_CAPITAL_C_BAR_CONTROL |
ONIG_SYN_OP2_ESC_CAPITAL_M_BAR_META | ONIG_SYN_OP2_ESC_V_VTAB |
ONIG_SYN_OP2_ESC_H_XDIGIT )
, ( SYN_GNU_REGEX_BV |
ONIG_SYN_ALLOW_INTERVAL_LOW_ABBREV |
ONIG_SYN_DIFFERENT_LEN_ALT_LOOK_BEHIND |
ONIG_SYN_CAPTURE_ONLY_NAMED_GROUP |
ONIG_SYN_ALLOW_MULTIPLEX_DEFINITION_NAME |
ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY |
ONIG_SYN_WARN_CC_OP_NOT_ESCAPED |
ONIG_SYN_WARN_REDUNDANT_NESTED_REPEAT )
, ONIG_OPTION_NONE
,
{
(OnigCodePoint )'\\' /* esc */
, (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* anychar '.' */
, (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* anytime '*' */
, (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* zero or one time '?' */
, (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* one or more time '+' */
, (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* anychar anytime */
}
};
OnigSyntaxType* OnigDefaultSyntax = ONIG_SYNTAX_RUBY;
extern void onig_null_warn(const char* s ARG_UNUSED) { }
#ifdef DEFAULT_WARN_FUNCTION
static OnigWarnFunc onig_warn = (OnigWarnFunc )DEFAULT_WARN_FUNCTION;
#else
static OnigWarnFunc onig_warn = onig_null_warn;
#endif
#ifdef DEFAULT_VERB_WARN_FUNCTION
static OnigWarnFunc onig_verb_warn = (OnigWarnFunc )DEFAULT_VERB_WARN_FUNCTION;
#else
static OnigWarnFunc onig_verb_warn = onig_null_warn;
#endif
extern void onig_set_warn_func(OnigWarnFunc f)
{
onig_warn = f;
}
extern void onig_set_verb_warn_func(OnigWarnFunc f)
{
onig_verb_warn = f;
}
extern void
onig_warning(const char* s)
{
if (onig_warn == onig_null_warn) return ;
(*onig_warn)(s);
}
#define DEFAULT_MAX_CAPTURE_NUM 32767
static int MaxCaptureNum = DEFAULT_MAX_CAPTURE_NUM;
extern int
onig_set_capture_num_limit(int num)
{
if (num < 0) return -1;
MaxCaptureNum = num;
return 0;
}
static unsigned int ParseDepthLimit = DEFAULT_PARSE_DEPTH_LIMIT;
extern unsigned int
onig_get_parse_depth_limit(void)
{
return ParseDepthLimit;
}
extern int
onig_set_parse_depth_limit(unsigned int depth)
{
if (depth == 0)
ParseDepthLimit = DEFAULT_PARSE_DEPTH_LIMIT;
else
ParseDepthLimit = depth;
return 0;
}
static void
bbuf_free(BBuf* bbuf)
{
if (IS_NOT_NULL(bbuf)) {
if (IS_NOT_NULL(bbuf->p)) xfree(bbuf->p);
xfree(bbuf);
}
}
static int
bbuf_clone(BBuf** rto, BBuf* from)
{
int r;
BBuf *to;
*rto = to = (BBuf* )xmalloc(sizeof(BBuf));
CHECK_NULL_RETURN_MEMERR(to);
r = BBUF_INIT(to, from->alloc);
if (r != 0) return r;
to->used = from->used;
xmemcpy(to->p, from->p, from->used);
return 0;
}
#define BACKREF_REL_TO_ABS(rel_no, env) \
((env)->num_mem + 1 + (rel_no))
#define ONOFF(v,f,negative) (negative) ? ((v) &= ~(f)) : ((v) |= (f))
#define MBCODE_START_POS(enc) \
(OnigCodePoint )(ONIGENC_MBC_MINLEN(enc) > 1 ? 0 : 0x80)
#define SET_ALL_MULTI_BYTE_RANGE(enc, pbuf) \
add_code_range_to_buf(pbuf, MBCODE_START_POS(enc), ~((OnigCodePoint )0))
#define ADD_ALL_MULTI_BYTE_RANGE(enc, mbuf) do {\
if (! ONIGENC_IS_SINGLEBYTE(enc)) {\
r = SET_ALL_MULTI_BYTE_RANGE(enc, &(mbuf));\
if (r) return r;\
}\
} while (0)
#define BITSET_IS_EMPTY(bs,empty) do {\
int i;\
empty = 1;\
for (i = 0; i < (int )BITSET_SIZE; i++) {\
if ((bs)[i] != 0) {\
empty = 0; break;\
}\
}\
} while (0)
static void
bitset_set_range(BitSetRef bs, int from, int to)
{
int i;
for (i = from; i <= to && i < SINGLE_BYTE_SIZE; i++) {
BITSET_SET_BIT(bs, i);
}
}
#if 0
static void
bitset_set_all(BitSetRef bs)
{
int i;
for (i = 0; i < BITSET_SIZE; i++) { bs[i] = ~((Bits )0); }
}
#endif
static void
bitset_invert(BitSetRef bs)
{
int i;
for (i = 0; i < (int )BITSET_SIZE; i++) { bs[i] = ~(bs[i]); }
}
static void
bitset_invert_to(BitSetRef from, BitSetRef to)
{
int i;
for (i = 0; i < (int )BITSET_SIZE; i++) { to[i] = ~(from[i]); }
}
static void
bitset_and(BitSetRef dest, BitSetRef bs)
{
int i;
for (i = 0; i < (int )BITSET_SIZE; i++) { dest[i] &= bs[i]; }
}
static void
bitset_or(BitSetRef dest, BitSetRef bs)
{
int i;
for (i = 0; i < (int )BITSET_SIZE; i++) { dest[i] |= bs[i]; }
}
static void
bitset_copy(BitSetRef dest, BitSetRef bs)
{
int i;
for (i = 0; i < (int )BITSET_SIZE; i++) { dest[i] = bs[i]; }
}
extern int
onig_strncmp(const UChar* s1, const UChar* s2, int n)
{
int x;
while (n-- > 0) {
x = *s2++ - *s1++;
if (x) return x;
}
return 0;
}
extern void
onig_strcpy(UChar* dest, const UChar* src, const UChar* end)
{
int len = end - src;
if (len > 0) {
xmemcpy(dest, src, len);
dest[len] = (UChar )0;
}
}
#ifdef USE_NAMED_GROUP
static UChar*
strdup_with_null(OnigEncoding enc, UChar* s, UChar* end)
{
int slen, term_len, i;
UChar *r;
slen = end - s;
term_len = ONIGENC_MBC_MINLEN(enc);
r = (UChar* )xmalloc(slen + term_len);
CHECK_NULL_RETURN(r);
xmemcpy(r, s, slen);
for (i = 0; i < term_len; i++)
r[slen + i] = (UChar )0;
return r;
}
#endif
/* scan pattern methods */
#define PEND_VALUE 0
#define PFETCH_READY UChar* pfetch_prev
#define PEND (p < end ? 0 : 1)
#define PUNFETCH p = pfetch_prev
#define PINC do { \
pfetch_prev = p; \
p += ONIGENC_MBC_ENC_LEN(enc, p); \
} while (0)
#define PFETCH(c) do { \
c = ONIGENC_MBC_TO_CODE(enc, p, end); \
pfetch_prev = p; \
p += ONIGENC_MBC_ENC_LEN(enc, p); \
} while (0)
#define PINC_S do { \
p += ONIGENC_MBC_ENC_LEN(enc, p); \
} while (0)
#define PFETCH_S(c) do { \
c = ONIGENC_MBC_TO_CODE(enc, p, end); \
p += ONIGENC_MBC_ENC_LEN(enc, p); \
} while (0)
#define PPEEK (p < end ? ONIGENC_MBC_TO_CODE(enc, p, end) : PEND_VALUE)
#define PPEEK_IS(c) (PPEEK == (OnigCodePoint )c)
static UChar*
strcat_capa(UChar* dest, UChar* dest_end, const UChar* src, const UChar* src_end,
int capa)
{
UChar* r;
if (dest)
r = (UChar* )xrealloc(dest, capa + 1);
else
r = (UChar* )xmalloc(capa + 1);
CHECK_NULL_RETURN(r);
onig_strcpy(r + (dest_end - dest), src, src_end);
return r;
}
/* dest on static area */
static UChar*
strcat_capa_from_static(UChar* dest, UChar* dest_end,
const UChar* src, const UChar* src_end, int capa)
{
UChar* r;
r = (UChar* )xmalloc(capa + 1);
CHECK_NULL_RETURN(r);
onig_strcpy(r, dest, dest_end);
onig_strcpy(r + (dest_end - dest), src, src_end);
return r;
}
#ifdef USE_ST_LIBRARY
typedef struct {
UChar* s;
UChar* end;
} st_str_end_key;
static int
str_end_cmp(st_str_end_key* x, st_str_end_key* y)
{
UChar *p, *q;
int c;
if ((x->end - x->s) != (y->end - y->s))
return 1;
p = x->s;
q = y->s;
while (p < x->end) {
c = (int )*p - (int )*q;
if (c != 0) return c;
p++; q++;
}
return 0;
}
static int
str_end_hash(st_str_end_key* x)
{
UChar *p;
int val = 0;
p = x->s;
while (p < x->end) {
val = val * 997 + (int )*p++;
}
return val + (val >> 5);
}
extern hash_table_type*
onig_st_init_strend_table_with_size(int size)
{
static struct st_hash_type hashType = {
str_end_cmp,
str_end_hash,
};
return (hash_table_type* )
onig_st_init_table_with_size(&hashType, size);
}
extern int
onig_st_lookup_strend(hash_table_type* table, const UChar* str_key,
const UChar* end_key, hash_data_type *value)
{
st_str_end_key key;
key.s = (UChar* )str_key;
key.end = (UChar* )end_key;
return onig_st_lookup(table, (st_data_t )(&key), value);
}
extern int
onig_st_insert_strend(hash_table_type* table, const UChar* str_key,
const UChar* end_key, hash_data_type value)
{
st_str_end_key* key;
int result;
key = (st_str_end_key* )xmalloc(sizeof(st_str_end_key));
key->s = (UChar* )str_key;
key->end = (UChar* )end_key;
result = onig_st_insert(table, (st_data_t )key, value);
if (result) {
xfree(key);
}
return result;
}
#endif /* USE_ST_LIBRARY */
#ifdef USE_NAMED_GROUP
#define INIT_NAME_BACKREFS_ALLOC_NUM 8
typedef struct {
UChar* name;
int name_len; /* byte length */
int back_num; /* number of backrefs */
int back_alloc;
int back_ref1;
int* back_refs;
} NameEntry;
#ifdef USE_ST_LIBRARY
typedef st_table NameTable;
typedef st_data_t HashDataType; /* 1.6 st.h doesn't define st_data_t type */
#define NAMEBUF_SIZE 24
#define NAMEBUF_SIZE_1 25
#ifdef ONIG_DEBUG
static int
i_print_name_entry(UChar* key, NameEntry* e, void* arg)
{
int i;
FILE* fp = (FILE* )arg;
fprintf(fp, "%s: ", e->name);
if (e->back_num == 0)
fputs("-", fp);
else if (e->back_num == 1)
fprintf(fp, "%d", e->back_ref1);
else {
for (i = 0; i < e->back_num; i++) {
if (i > 0) fprintf(fp, ", ");
fprintf(fp, "%d", e->back_refs[i]);
}
}
fputs("\n", fp);
return ST_CONTINUE;
}
extern int
onig_print_names(FILE* fp, regex_t* reg)
{
NameTable* t = (NameTable* )reg->name_table;
if (IS_NOT_NULL(t)) {
fprintf(fp, "name table\n");
onig_st_foreach(t, i_print_name_entry, (HashDataType )fp);
fputs("\n", fp);
}
return 0;
}
#endif /* ONIG_DEBUG */
static int
i_free_name_entry(UChar* key, NameEntry* e, void* arg ARG_UNUSED)
{
xfree(e->name);
if (IS_NOT_NULL(e->back_refs)) xfree(e->back_refs);
xfree(key);
xfree(e);
return ST_DELETE;
}
static int
names_clear(regex_t* reg)
{
NameTable* t = (NameTable* )reg->name_table;
if (IS_NOT_NULL(t)) {
onig_st_foreach(t, i_free_name_entry, 0);
}
return 0;
}
extern int
onig_names_free(regex_t* reg)
{
int r;
NameTable* t;
r = names_clear(reg);
if (r) return r;
t = (NameTable* )reg->name_table;
if (IS_NOT_NULL(t)) onig_st_free_table(t);
reg->name_table = (void* )NULL;
return 0;
}
static NameEntry*
name_find(regex_t* reg, const UChar* name, const UChar* name_end)
{
NameEntry* e;
NameTable* t = (NameTable* )reg->name_table;
e = (NameEntry* )NULL;
if (IS_NOT_NULL(t)) {
onig_st_lookup_strend(t, name, name_end, (HashDataType* )((void* )(&e)));
}
return e;
}
typedef struct {
int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*);
regex_t* reg;
void* arg;
int ret;
OnigEncoding enc;
} INamesArg;
static int
i_names(UChar* key ARG_UNUSED, NameEntry* e, INamesArg* arg)
{
int r = (*(arg->func))(e->name,
e->name + e->name_len,
e->back_num,
(e->back_num > 1 ? e->back_refs : &(e->back_ref1)),
arg->reg, arg->arg);
if (r != 0) {
arg->ret = r;
return ST_STOP;
}
return ST_CONTINUE;
}
extern int
onig_foreach_name(regex_t* reg,
int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*), void* arg)
{
INamesArg narg;
NameTable* t = (NameTable* )reg->name_table;
narg.ret = 0;
if (IS_NOT_NULL(t)) {
narg.func = func;
narg.reg = reg;
narg.arg = arg;
narg.enc = reg->enc; /* should be pattern encoding. */
onig_st_foreach(t, i_names, (HashDataType )&narg);
}
return narg.ret;
}
static int
i_renumber_name(UChar* key ARG_UNUSED, NameEntry* e, GroupNumRemap* map)
{
int i;
if (e->back_num > 1) {
for (i = 0; i < e->back_num; i++) {
e->back_refs[i] = map[e->back_refs[i]].new_val;
}
}
else if (e->back_num == 1) {
e->back_ref1 = map[e->back_ref1].new_val;
}
return ST_CONTINUE;
}
extern int
onig_renumber_name_table(regex_t* reg, GroupNumRemap* map)
{
NameTable* t = (NameTable* )reg->name_table;
if (IS_NOT_NULL(t)) {
onig_st_foreach(t, i_renumber_name, (HashDataType )map);
}
return 0;
}
extern int
onig_number_of_names(regex_t* reg)
{
NameTable* t = (NameTable* )reg->name_table;
if (IS_NOT_NULL(t))
return t->num_entries;
else
return 0;
}
#else /* USE_ST_LIBRARY */
#define INIT_NAMES_ALLOC_NUM 8
typedef struct {
NameEntry* e;
int num;
int alloc;
} NameTable;
#ifdef ONIG_DEBUG
extern int
onig_print_names(FILE* fp, regex_t* reg)
{
int i, j;
NameEntry* e;
NameTable* t = (NameTable* )reg->name_table;
if (IS_NOT_NULL(t) && t->num > 0) {
fprintf(fp, "name table\n");
for (i = 0; i < t->num; i++) {
e = &(t->e[i]);
fprintf(fp, "%s: ", e->name);
if (e->back_num == 0) {
fputs("-", fp);
}
else if (e->back_num == 1) {
fprintf(fp, "%d", e->back_ref1);
}
else {
for (j = 0; j < e->back_num; j++) {
if (j > 0) fprintf(fp, ", ");
fprintf(fp, "%d", e->back_refs[j]);
}
}
fputs("\n", fp);
}
fputs("\n", fp);
}
return 0;
}
#endif
static int
names_clear(regex_t* reg)
{
int i;
NameEntry* e;
NameTable* t = (NameTable* )reg->name_table;
if (IS_NOT_NULL(t)) {
for (i = 0; i < t->num; i++) {
e = &(t->e[i]);
if (IS_NOT_NULL(e->name)) {
xfree(e->name);
e->name = NULL;
e->name_len = 0;
e->back_num = 0;
e->back_alloc = 0;
if (IS_NOT_NULL(e->back_refs)) xfree(e->back_refs);
e->back_refs = (int* )NULL;
}
}
if (IS_NOT_NULL(t->e)) {
xfree(t->e);
t->e = NULL;
}
t->num = 0;
}
return 0;
}
extern int
onig_names_free(regex_t* reg)
{
int r;
NameTable* t;
r = names_clear(reg);
if (r) return r;
t = (NameTable* )reg->name_table;
if (IS_NOT_NULL(t)) xfree(t);
reg->name_table = NULL;
return 0;
}
static NameEntry*
name_find(regex_t* reg, UChar* name, UChar* name_end)
{
int i, len;
NameEntry* e;
NameTable* t = (NameTable* )reg->name_table;
if (IS_NOT_NULL(t)) {
len = name_end - name;
for (i = 0; i < t->num; i++) {
e = &(t->e[i]);
if (len == e->name_len && onig_strncmp(name, e->name, len) == 0)
return e;
}
}
return (NameEntry* )NULL;
}
extern int
onig_foreach_name(regex_t* reg,
int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*), void* arg)
{
int i, r;
NameEntry* e;
NameTable* t = (NameTable* )reg->name_table;
if (IS_NOT_NULL(t)) {
for (i = 0; i < t->num; i++) {
e = &(t->e[i]);
r = (*func)(e->name, e->name + e->name_len, e->back_num,
(e->back_num > 1 ? e->back_refs : &(e->back_ref1)),
reg, arg);
if (r != 0) return r;
}
}
return 0;
}
extern int
onig_number_of_names(regex_t* reg)
{
NameTable* t = (NameTable* )reg->name_table;
if (IS_NOT_NULL(t))
return t->num;
else
return 0;
}
#endif /* else USE_ST_LIBRARY */
static int
name_add(regex_t* reg, UChar* name, UChar* name_end, int backref, ScanEnv* env)
{
int alloc;
NameEntry* e;
NameTable* t = (NameTable* )reg->name_table;
if (name_end - name <= 0)
return ONIGERR_EMPTY_GROUP_NAME;
e = name_find(reg, name, name_end);
if (IS_NULL(e)) {
#ifdef USE_ST_LIBRARY
if (IS_NULL(t)) {
t = onig_st_init_strend_table_with_size(5);
reg->name_table = (void* )t;
}
e = (NameEntry* )xmalloc(sizeof(NameEntry));
CHECK_NULL_RETURN_MEMERR(e);
e->name = strdup_with_null(reg->enc, name, name_end);
if (IS_NULL(e->name)) {
xfree(e); return ONIGERR_MEMORY;
}
onig_st_insert_strend(t, e->name, (e->name + (name_end - name)),
(HashDataType )e);
e->name_len = name_end - name;
e->back_num = 0;
e->back_alloc = 0;
e->back_refs = (int* )NULL;
#else
if (IS_NULL(t)) {
alloc = INIT_NAMES_ALLOC_NUM;
t = (NameTable* )xmalloc(sizeof(NameTable));
CHECK_NULL_RETURN_MEMERR(t);
t->e = NULL;
t->alloc = 0;
t->num = 0;
t->e = (NameEntry* )xmalloc(sizeof(NameEntry) * alloc);
if (IS_NULL(t->e)) {
xfree(t);
return ONIGERR_MEMORY;
}
t->alloc = alloc;
reg->name_table = t;
goto clear;
}
else if (t->num == t->alloc) {
int i;
alloc = t->alloc * 2;
t->e = (NameEntry* )xrealloc(t->e, sizeof(NameEntry) * alloc);
CHECK_NULL_RETURN_MEMERR(t->e);
t->alloc = alloc;
clear:
for (i = t->num; i < t->alloc; i++) {
t->e[i].name = NULL;
t->e[i].name_len = 0;
t->e[i].back_num = 0;
t->e[i].back_alloc = 0;
t->e[i].back_refs = (int* )NULL;
}
}
e = &(t->e[t->num]);
t->num++;
e->name = strdup_with_null(reg->enc, name, name_end);
if (IS_NULL(e->name)) return ONIGERR_MEMORY;
e->name_len = name_end - name;
#endif
}
if (e->back_num >= 1 &&
! IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_MULTIPLEX_DEFINITION_NAME)) {
onig_scan_env_set_error_string(env, ONIGERR_MULTIPLEX_DEFINED_NAME,
name, name_end);
return ONIGERR_MULTIPLEX_DEFINED_NAME;
}
e->back_num++;
if (e->back_num == 1) {
e->back_ref1 = backref;
}
else {
if (e->back_num == 2) {
alloc = INIT_NAME_BACKREFS_ALLOC_NUM;
e->back_refs = (int* )xmalloc(sizeof(int) * alloc);
CHECK_NULL_RETURN_MEMERR(e->back_refs);
e->back_alloc = alloc;
e->back_refs[0] = e->back_ref1;
e->back_refs[1] = backref;
}
else {
if (e->back_num > e->back_alloc) {
alloc = e->back_alloc * 2;
e->back_refs = (int* )xrealloc(e->back_refs, sizeof(int) * alloc);
CHECK_NULL_RETURN_MEMERR(e->back_refs);
e->back_alloc = alloc;
}
e->back_refs[e->back_num - 1] = backref;
}
}
return 0;
}
extern int
onig_name_to_group_numbers(regex_t* reg, const UChar* name,
const UChar* name_end, int** nums)
{
NameEntry* e = name_find(reg, name, name_end);
if (IS_NULL(e)) return ONIGERR_UNDEFINED_NAME_REFERENCE;
switch (e->back_num) {
case 0:
break;
case 1:
*nums = &(e->back_ref1);
break;
default:
*nums = e->back_refs;
break;
}
return e->back_num;
}
extern int
onig_name_to_backref_number(regex_t* reg, const UChar* name,
const UChar* name_end, OnigRegion *region)
{
int i, n, *nums;
n = onig_name_to_group_numbers(reg, name, name_end, &nums);
if (n < 0)
return n;
else if (n == 0)
return ONIGERR_PARSER_BUG;
else if (n == 1)
return nums[0];
else {
if (IS_NOT_NULL(region)) {
for (i = n - 1; i >= 0; i--) {
if (region->beg[nums[i]] != ONIG_REGION_NOTPOS)
return nums[i];
}
}
return nums[n - 1];
}
}
#else /* USE_NAMED_GROUP */
extern int
onig_name_to_group_numbers(regex_t* reg, const UChar* name,
const UChar* name_end, int** nums)
{
return ONIG_NO_SUPPORT_CONFIG;
}
extern int
onig_name_to_backref_number(regex_t* reg, const UChar* name,
const UChar* name_end, OnigRegion* region)
{
return ONIG_NO_SUPPORT_CONFIG;
}
extern int
onig_foreach_name(regex_t* reg,
int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*), void* arg)
{
return ONIG_NO_SUPPORT_CONFIG;
}
extern int
onig_number_of_names(regex_t* reg)
{
return 0;
}
#endif /* else USE_NAMED_GROUP */
extern int
onig_noname_group_capture_is_active(regex_t* reg)
{
if (ONIG_IS_OPTION_ON(reg->options, ONIG_OPTION_DONT_CAPTURE_GROUP))
return 0;
#ifdef USE_NAMED_GROUP
if (onig_number_of_names(reg) > 0 &&
IS_SYNTAX_BV(reg->syntax, ONIG_SYN_CAPTURE_ONLY_NAMED_GROUP) &&
!ONIG_IS_OPTION_ON(reg->options, ONIG_OPTION_CAPTURE_GROUP)) {
return 0;
}
#endif
return 1;
}
#define INIT_SCANENV_MEMNODES_ALLOC_SIZE 16
static void
scan_env_clear(ScanEnv* env)
{
int i;
BIT_STATUS_CLEAR(env->capture_history);
BIT_STATUS_CLEAR(env->bt_mem_start);
BIT_STATUS_CLEAR(env->bt_mem_end);
BIT_STATUS_CLEAR(env->backrefed_mem);
env->error = (UChar* )NULL;
env->error_end = (UChar* )NULL;
env->num_call = 0;
env->num_mem = 0;
#ifdef USE_NAMED_GROUP
env->num_named = 0;
#endif
env->mem_alloc = 0;
env->mem_nodes_dynamic = (Node** )NULL;
for (i = 0; i < SCANENV_MEMNODES_SIZE; i++)
env->mem_nodes_static[i] = NULL_NODE;
#ifdef USE_COMBINATION_EXPLOSION_CHECK
env->num_comb_exp_check = 0;
env->comb_exp_max_regnum = 0;
env->curr_max_regnum = 0;
env->has_recursion = 0;
#endif
env->parse_depth = 0;
}
static int
scan_env_add_mem_entry(ScanEnv* env)
{
int i, need, alloc;
Node** p;
need = env->num_mem + 1;
if (need > MaxCaptureNum && MaxCaptureNum != 0)
return ONIGERR_TOO_MANY_CAPTURES;
if (need >= SCANENV_MEMNODES_SIZE) {
if (env->mem_alloc <= need) {
if (IS_NULL(env->mem_nodes_dynamic)) {
alloc = INIT_SCANENV_MEMNODES_ALLOC_SIZE;
p = (Node** )xmalloc(sizeof(Node*) * alloc);
xmemcpy(p, env->mem_nodes_static,
sizeof(Node*) * SCANENV_MEMNODES_SIZE);
}
else {
alloc = env->mem_alloc * 2;
p = (Node** )xrealloc(env->mem_nodes_dynamic, sizeof(Node*) * alloc);
}
CHECK_NULL_RETURN_MEMERR(p);
for (i = env->num_mem + 1; i < alloc; i++)
p[i] = NULL_NODE;
env->mem_nodes_dynamic = p;
env->mem_alloc = alloc;
}
}
env->num_mem++;
return env->num_mem;
}
static int
scan_env_set_mem_node(ScanEnv* env, int num, Node* node)
{
if (env->num_mem >= num)
SCANENV_MEM_NODES(env)[num] = node;
else
return ONIGERR_PARSER_BUG;
return 0;
}
extern void
onig_node_free(Node* node)
{
start:
if (IS_NULL(node)) return ;
#ifdef DEBUG_NODE_FREE
fprintf(stderr, "onig_node_free: %p\n", node);
#endif
switch (NTYPE(node)) {
case NT_STR:
if (NSTR(node)->capa != 0 &&
IS_NOT_NULL(NSTR(node)->s) && NSTR(node)->s != NSTR(node)->buf) {
xfree(NSTR(node)->s);
}
break;
case NT_LIST:
case NT_ALT:
onig_node_free(NCAR(node));
{
Node* next_node = NCDR(node);
xfree(node);
node = next_node;
goto start;
}
break;
case NT_CCLASS:
{
CClassNode* cc = NCCLASS(node);
if (IS_NCCLASS_SHARE(cc)) return ;
if (cc->mbuf)
bbuf_free(cc->mbuf);
}
break;
case NT_QTFR:
if (NQTFR(node)->target)
onig_node_free(NQTFR(node)->target);
break;
case NT_ENCLOSE:
if (NENCLOSE(node)->target)
onig_node_free(NENCLOSE(node)->target);
break;
case NT_BREF:
if (IS_NOT_NULL(NBREF(node)->back_dynamic))
xfree(NBREF(node)->back_dynamic);
break;
case NT_ANCHOR:
if (NANCHOR(node)->target)
onig_node_free(NANCHOR(node)->target);
break;
}
xfree(node);
}
static Node*
node_new(void)
{
Node* node;
node = (Node* )xmalloc(sizeof(Node));
/* xmemset(node, 0, sizeof(Node)); */
#ifdef DEBUG_NODE_FREE
fprintf(stderr, "node_new: %p\n", node);
#endif
return node;
}
static void
initialize_cclass(CClassNode* cc)
{
BITSET_CLEAR(cc->bs);
/* cc->base.flags = 0; */
cc->flags = 0;
cc->mbuf = NULL;
}
static Node*
node_new_cclass(void)
{
Node* node = node_new();
CHECK_NULL_RETURN(node);
SET_NTYPE(node, NT_CCLASS);
initialize_cclass(NCCLASS(node));
return node;
}
static Node*
node_new_ctype(int type, int not)
{
Node* node = node_new();
CHECK_NULL_RETURN(node);
SET_NTYPE(node, NT_CTYPE);
NCTYPE(node)->ctype = type;
NCTYPE(node)->not = not;
return node;
}
static Node*
node_new_anychar(void)
{
Node* node = node_new();
CHECK_NULL_RETURN(node);
SET_NTYPE(node, NT_CANY);
return node;
}
static Node*
node_new_list(Node* left, Node* right)
{
Node* node = node_new();
CHECK_NULL_RETURN(node);
SET_NTYPE(node, NT_LIST);
NCAR(node) = left;
NCDR(node) = right;
return node;
}
extern Node*
onig_node_new_list(Node* left, Node* right)
{
return node_new_list(left, right);
}
extern Node*
onig_node_list_add(Node* list, Node* x)
{
Node *n;
n = onig_node_new_list(x, NULL);
if (IS_NULL(n)) return NULL_NODE;
if (IS_NOT_NULL(list)) {
while (IS_NOT_NULL(NCDR(list)))
list = NCDR(list);
NCDR(list) = n;
}
return n;
}
extern Node*
onig_node_new_alt(Node* left, Node* right)
{
Node* node = node_new();
CHECK_NULL_RETURN(node);
SET_NTYPE(node, NT_ALT);
NCAR(node) = left;
NCDR(node) = right;
return node;
}
extern Node*
onig_node_new_anchor(int type)
{
Node* node = node_new();
CHECK_NULL_RETURN(node);
SET_NTYPE(node, NT_ANCHOR);
NANCHOR(node)->type = type;
NANCHOR(node)->target = NULL;
NANCHOR(node)->char_len = -1;
return node;
}
static Node*
node_new_backref(int back_num, int* backrefs, int by_name,
#ifdef USE_BACKREF_WITH_LEVEL
int exist_level, int nest_level,
#endif
ScanEnv* env)
{
int i;
Node* node = node_new();
CHECK_NULL_RETURN(node);
SET_NTYPE(node, NT_BREF);
NBREF(node)->state = 0;
NBREF(node)->back_num = back_num;
NBREF(node)->back_dynamic = (int* )NULL;
if (by_name != 0)
NBREF(node)->state |= NST_NAME_REF;
#ifdef USE_BACKREF_WITH_LEVEL
if (exist_level != 0) {
NBREF(node)->state |= NST_NEST_LEVEL;
NBREF(node)->nest_level = nest_level;
}
#endif
for (i = 0; i < back_num; i++) {
if (backrefs[i] <= env->num_mem &&
IS_NULL(SCANENV_MEM_NODES(env)[backrefs[i]])) {
NBREF(node)->state |= NST_RECURSION; /* /...(\1).../ */
break;
}
}
if (back_num <= NODE_BACKREFS_SIZE) {
for (i = 0; i < back_num; i++)
NBREF(node)->back_static[i] = backrefs[i];
}
else {
int* p = (int* )xmalloc(sizeof(int) * back_num);
if (IS_NULL(p)) {
onig_node_free(node);
return NULL;
}
NBREF(node)->back_dynamic = p;
for (i = 0; i < back_num; i++)
p[i] = backrefs[i];
}
return node;
}
#ifdef USE_SUBEXP_CALL
static Node*
node_new_call(UChar* name, UChar* name_end, int gnum)
{
Node* node = node_new();
CHECK_NULL_RETURN(node);
SET_NTYPE(node, NT_CALL);
NCALL(node)->state = 0;
NCALL(node)->target = NULL_NODE;
NCALL(node)->name = name;
NCALL(node)->name_end = name_end;
NCALL(node)->group_num = gnum; /* call by number if gnum != 0 */
return node;
}
#endif
static Node*
node_new_quantifier(int lower, int upper, int by_number)
{
Node* node = node_new();
CHECK_NULL_RETURN(node);
SET_NTYPE(node, NT_QTFR);
NQTFR(node)->state = 0;
NQTFR(node)->target = NULL;
NQTFR(node)->lower = lower;
NQTFR(node)->upper = upper;
NQTFR(node)->greedy = 1;
NQTFR(node)->target_empty_info = NQ_TARGET_ISNOT_EMPTY;
NQTFR(node)->head_exact = NULL_NODE;
NQTFR(node)->next_head_exact = NULL_NODE;
NQTFR(node)->is_refered = 0;
if (by_number != 0)
NQTFR(node)->state |= NST_BY_NUMBER;
#ifdef USE_COMBINATION_EXPLOSION_CHECK
NQTFR(node)->comb_exp_check_num = 0;
#endif
return node;
}
static Node*
node_new_enclose(int type)
{
Node* node = node_new();
CHECK_NULL_RETURN(node);
SET_NTYPE(node, NT_ENCLOSE);
NENCLOSE(node)->type = type;
NENCLOSE(node)->state = 0;
NENCLOSE(node)->regnum = 0;
NENCLOSE(node)->option = 0;
NENCLOSE(node)->target = NULL;
NENCLOSE(node)->call_addr = -1;
NENCLOSE(node)->opt_count = 0;
return node;
}
extern Node*
onig_node_new_enclose(int type)
{
return node_new_enclose(type);
}
static Node*
node_new_enclose_memory(OnigOptionType option, int is_named)
{
Node* node = node_new_enclose(ENCLOSE_MEMORY);
CHECK_NULL_RETURN(node);
if (is_named != 0)
SET_ENCLOSE_STATUS(node, NST_NAMED_GROUP);
#ifdef USE_SUBEXP_CALL
NENCLOSE(node)->option = option;
#endif
return node;
}
static Node*
node_new_option(OnigOptionType option)
{
Node* node = node_new_enclose(ENCLOSE_OPTION);
CHECK_NULL_RETURN(node);
NENCLOSE(node)->option = option;
return node;
}
extern int
onig_node_str_cat(Node* node, const UChar* s, const UChar* end)
{
int addlen = end - s;
if (addlen > 0) {
int len = NSTR(node)->end - NSTR(node)->s;
if (NSTR(node)->capa > 0 || (len + addlen > NODE_STR_BUF_SIZE - 1)) {
UChar* p;
int capa = len + addlen + NODE_STR_MARGIN;
if (capa <= NSTR(node)->capa) {
onig_strcpy(NSTR(node)->s + len, s, end);
}
else {
if (NSTR(node)->s == NSTR(node)->buf)
p = strcat_capa_from_static(NSTR(node)->s, NSTR(node)->end,
s, end, capa);
else
p = strcat_capa(NSTR(node)->s, NSTR(node)->end, s, end, capa);
CHECK_NULL_RETURN_MEMERR(p);
NSTR(node)->s = p;
NSTR(node)->capa = capa;
}
}
else {
onig_strcpy(NSTR(node)->s + len, s, end);
}
NSTR(node)->end = NSTR(node)->s + len + addlen;
}
return 0;
}
extern int
onig_node_str_set(Node* node, const UChar* s, const UChar* end)
{
onig_node_str_clear(node);
return onig_node_str_cat(node, s, end);
}
static int
node_str_cat_char(Node* node, UChar c)
{
UChar s[1];
s[0] = c;
return onig_node_str_cat(node, s, s + 1);
}
extern void
onig_node_conv_to_str_node(Node* node, int flag)
{
SET_NTYPE(node, NT_STR);
NSTR(node)->flag = flag;
NSTR(node)->capa = 0;
NSTR(node)->s = NSTR(node)->buf;
NSTR(node)->end = NSTR(node)->buf;
}
extern void
onig_node_str_clear(Node* node)
{
if (NSTR(node)->capa != 0 &&
IS_NOT_NULL(NSTR(node)->s) && NSTR(node)->s != NSTR(node)->buf) {
xfree(NSTR(node)->s);
}
NSTR(node)->capa = 0;
NSTR(node)->flag = 0;
NSTR(node)->s = NSTR(node)->buf;
NSTR(node)->end = NSTR(node)->buf;
}
static Node*
node_new_str(const UChar* s, const UChar* end)
{
Node* node = node_new();
CHECK_NULL_RETURN(node);
SET_NTYPE(node, NT_STR);
NSTR(node)->capa = 0;
NSTR(node)->flag = 0;
NSTR(node)->s = NSTR(node)->buf;
NSTR(node)->end = NSTR(node)->buf;
if (onig_node_str_cat(node, s, end)) {
onig_node_free(node);
return NULL;
}
return node;
}
extern Node*
onig_node_new_str(const UChar* s, const UChar* end)
{
return node_new_str(s, end);
}
static Node*
node_new_str_raw(UChar* s, UChar* end)
{
Node* node = node_new_str(s, end);
NSTRING_SET_RAW(node);
return node;
}
static Node*
node_new_empty(void)
{
return node_new_str(NULL, NULL);
}
static Node*
node_new_str_raw_char(UChar c)
{
UChar p[1];
p[0] = c;
return node_new_str_raw(p, p + 1);
}
static Node*
str_node_split_last_char(StrNode* sn, OnigEncoding enc)
{
const UChar *p;
Node* n = NULL_NODE;
if (sn->end > sn->s) {
p = onigenc_get_prev_char_head(enc, sn->s, sn->end);
if (p && p > sn->s) { /* can be split. */
n = node_new_str(p, sn->end);
if ((sn->flag & NSTR_RAW) != 0)
NSTRING_SET_RAW(n);
sn->end = (UChar* )p;
}
}
return n;
}
static int
str_node_can_be_split(StrNode* sn, OnigEncoding enc)
{
if (sn->end > sn->s) {
return ((enclen(enc, sn->s) < sn->end - sn->s) ? 1 : 0);
}
return 0;
}
#ifdef USE_PAD_TO_SHORT_BYTE_CHAR
static int
node_str_head_pad(StrNode* sn, int num, UChar val)
{
UChar buf[NODE_STR_BUF_SIZE];
int i, len;
len = sn->end - sn->s;
onig_strcpy(buf, sn->s, sn->end);
onig_strcpy(&(sn->s[num]), buf, buf + len);
sn->end += num;
for (i = 0; i < num; i++) {
sn->s[i] = val;
}
}
#endif
extern int
onig_scan_unsigned_number(UChar** src, const UChar* end, OnigEncoding enc)
{
unsigned int num, val;
OnigCodePoint c;
UChar* p = *src;
PFETCH_READY;
num = 0;
while (!PEND) {
PFETCH(c);
if (ONIGENC_IS_CODE_DIGIT(enc, c)) {
val = (unsigned int )DIGITVAL(c);
if ((INT_MAX_LIMIT - val) / 10UL < num)
return -1; /* overflow */
num = num * 10 + val;
}
else {
PUNFETCH;
break;
}
}
*src = p;
return num;
}
static int
scan_unsigned_hexadecimal_number(UChar** src, UChar* end, int maxlen,
OnigEncoding enc)
{
OnigCodePoint c;
unsigned int num, val;
UChar* p = *src;
PFETCH_READY;
num = 0;
while (! PEND && maxlen-- != 0) {
PFETCH(c);
if (ONIGENC_IS_CODE_XDIGIT(enc, c)) {
val = (unsigned int )XDIGITVAL(enc,c);
if ((INT_MAX_LIMIT - val) / 16UL < num)
return -1; /* overflow */
num = (num << 4) + XDIGITVAL(enc,c);
}
else {
PUNFETCH;
break;
}
}
*src = p;
return num;
}
static int
scan_unsigned_octal_number(UChar** src, UChar* end, int maxlen,
OnigEncoding enc)
{
OnigCodePoint c;
unsigned int num, val;
UChar* p = *src;
PFETCH_READY;
num = 0;
while (!PEND && maxlen-- != 0) {
PFETCH(c);
if (ONIGENC_IS_CODE_DIGIT(enc, c) && c < '8') {
val = ODIGITVAL(c);
if ((INT_MAX_LIMIT - val) / 8UL < num)
return -1; /* overflow */
num = (num << 3) + val;
}
else {
PUNFETCH;
break;
}
}
*src = p;
return num;
}
#define BBUF_WRITE_CODE_POINT(bbuf,pos,code) \
BBUF_WRITE(bbuf, pos, &(code), SIZE_CODE_POINT)
/* data format:
[n][from-1][to-1][from-2][to-2] ... [from-n][to-n]
(all data size is OnigCodePoint)
*/
static int
new_code_range(BBuf** pbuf)
{
#define INIT_MULTI_BYTE_RANGE_SIZE (SIZE_CODE_POINT * 5)
int r;
OnigCodePoint n;
BBuf* bbuf;
bbuf = *pbuf = (BBuf* )xmalloc(sizeof(BBuf));
CHECK_NULL_RETURN_MEMERR(*pbuf);
r = BBUF_INIT(*pbuf, INIT_MULTI_BYTE_RANGE_SIZE);
if (r) return r;
n = 0;
BBUF_WRITE_CODE_POINT(bbuf, 0, n);
return 0;
}
static int
add_code_range_to_buf(BBuf** pbuf, OnigCodePoint from, OnigCodePoint to)
{
int r, inc_n, pos;
int low, high, bound, x;
OnigCodePoint n, *data;
BBuf* bbuf;
if (from > to) {
n = from; from = to; to = n;
}
if (IS_NULL(*pbuf)) {
r = new_code_range(pbuf);
if (r) return r;
bbuf = *pbuf;
n = 0;
}
else {
bbuf = *pbuf;
GET_CODE_POINT(n, bbuf->p);
}
data = (OnigCodePoint* )(bbuf->p);
data++;
for (low = 0, bound = n; low < bound; ) {
x = (low + bound) >> 1;
if (from > data[x*2 + 1])
low = x + 1;
else
bound = x;
}
high = (to == ~((OnigCodePoint )0)) ? n : low;
for (bound = n; high < bound; ) {
x = (high + bound) >> 1;
if (to + 1 >= data[x*2])
high = x + 1;
else
bound = x;
}
inc_n = low + 1 - high;
if (n + inc_n > ONIG_MAX_MULTI_BYTE_RANGES_NUM)
return ONIGERR_TOO_MANY_MULTI_BYTE_RANGES;
if (inc_n != 1) {
if (from > data[low*2])
from = data[low*2];
if (to < data[(high - 1)*2 + 1])
to = data[(high - 1)*2 + 1];
}
if (inc_n != 0 && (OnigCodePoint )high < n) {
int from_pos = SIZE_CODE_POINT * (1 + high * 2);
int to_pos = SIZE_CODE_POINT * (1 + (low + 1) * 2);
int size = (n - high) * 2 * SIZE_CODE_POINT;
if (inc_n > 0) {
BBUF_MOVE_RIGHT(bbuf, from_pos, to_pos, size);
}
else {
BBUF_MOVE_LEFT_REDUCE(bbuf, from_pos, to_pos);
}
}
pos = SIZE_CODE_POINT * (1 + low * 2);
BBUF_ENSURE_SIZE(bbuf, pos + SIZE_CODE_POINT * 2);
BBUF_WRITE_CODE_POINT(bbuf, pos, from);
BBUF_WRITE_CODE_POINT(bbuf, pos + SIZE_CODE_POINT, to);
n += inc_n;
BBUF_WRITE_CODE_POINT(bbuf, 0, n);
return 0;
}
static int
add_code_range(BBuf** pbuf, ScanEnv* env, OnigCodePoint from, OnigCodePoint to)
{
if (from > to) {
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC))
return 0;
else
return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS;
}
return add_code_range_to_buf(pbuf, from, to);
}
static int
not_code_range_buf(OnigEncoding enc, BBuf* bbuf, BBuf** pbuf)
{
int r, i, n;
OnigCodePoint pre, from, *data, to = 0;
*pbuf = (BBuf* )NULL;
if (IS_NULL(bbuf)) {
set_all:
return SET_ALL_MULTI_BYTE_RANGE(enc, pbuf);
}
data = (OnigCodePoint* )(bbuf->p);
GET_CODE_POINT(n, data);
data++;
if (n <= 0) goto set_all;
r = 0;
pre = MBCODE_START_POS(enc);
for (i = 0; i < n; i++) {
from = data[i*2];
to = data[i*2+1];
if (pre <= from - 1) {
r = add_code_range_to_buf(pbuf, pre, from - 1);
if (r != 0) return r;
}
if (to == ~((OnigCodePoint )0)) break;
pre = to + 1;
}
if (to < ~((OnigCodePoint )0)) {
r = add_code_range_to_buf(pbuf, to + 1, ~((OnigCodePoint )0));
}
return r;
}
#define SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2) do {\
BBuf *tbuf; \
int tnot; \
tnot = not1; not1 = not2; not2 = tnot; \
tbuf = bbuf1; bbuf1 = bbuf2; bbuf2 = tbuf; \
} while (0)
static int
or_code_range_buf(OnigEncoding enc, BBuf* bbuf1, int not1,
BBuf* bbuf2, int not2, BBuf** pbuf)
{
int r;
OnigCodePoint i, n1, *data1;
OnigCodePoint from, to;
*pbuf = (BBuf* )NULL;
if (IS_NULL(bbuf1) && IS_NULL(bbuf2)) {
if (not1 != 0 || not2 != 0)
return SET_ALL_MULTI_BYTE_RANGE(enc, pbuf);
return 0;
}
r = 0;
if (IS_NULL(bbuf2))
SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2);
if (IS_NULL(bbuf1)) {
if (not1 != 0) {
return SET_ALL_MULTI_BYTE_RANGE(enc, pbuf);
}
else {
if (not2 == 0) {
return bbuf_clone(pbuf, bbuf2);
}
else {
return not_code_range_buf(enc, bbuf2, pbuf);
}
}
}
if (not1 != 0)
SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2);
data1 = (OnigCodePoint* )(bbuf1->p);
GET_CODE_POINT(n1, data1);
data1++;
if (not2 == 0 && not1 == 0) { /* 1 OR 2 */
r = bbuf_clone(pbuf, bbuf2);
}
else if (not1 == 0) { /* 1 OR (not 2) */
r = not_code_range_buf(enc, bbuf2, pbuf);
}
if (r != 0) return r;
for (i = 0; i < n1; i++) {
from = data1[i*2];
to = data1[i*2+1];
r = add_code_range_to_buf(pbuf, from, to);
if (r != 0) return r;
}
return 0;
}
static int
and_code_range1(BBuf** pbuf, OnigCodePoint from1, OnigCodePoint to1,
OnigCodePoint* data, int n)
{
int i, r;
OnigCodePoint from2, to2;
for (i = 0; i < n; i++) {
from2 = data[i*2];
to2 = data[i*2+1];
if (from2 < from1) {
if (to2 < from1) continue;
else {
from1 = to2 + 1;
}
}
else if (from2 <= to1) {
if (to2 < to1) {
if (from1 <= from2 - 1) {
r = add_code_range_to_buf(pbuf, from1, from2-1);
if (r != 0) return r;
}
from1 = to2 + 1;
}
else {
to1 = from2 - 1;
}
}
else {
from1 = from2;
}
if (from1 > to1) break;
}
if (from1 <= to1) {
r = add_code_range_to_buf(pbuf, from1, to1);
if (r != 0) return r;
}
return 0;
}
static int
and_code_range_buf(BBuf* bbuf1, int not1, BBuf* bbuf2, int not2, BBuf** pbuf)
{
int r;
OnigCodePoint i, j, n1, n2, *data1, *data2;
OnigCodePoint from, to, from1, to1, from2, to2;
*pbuf = (BBuf* )NULL;
if (IS_NULL(bbuf1)) {
if (not1 != 0 && IS_NOT_NULL(bbuf2)) /* not1 != 0 -> not2 == 0 */
return bbuf_clone(pbuf, bbuf2);
return 0;
}
else if (IS_NULL(bbuf2)) {
if (not2 != 0)
return bbuf_clone(pbuf, bbuf1);
return 0;
}
if (not1 != 0)
SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2);
data1 = (OnigCodePoint* )(bbuf1->p);
data2 = (OnigCodePoint* )(bbuf2->p);
GET_CODE_POINT(n1, data1);
GET_CODE_POINT(n2, data2);
data1++;
data2++;
if (not2 == 0 && not1 == 0) { /* 1 AND 2 */
for (i = 0; i < n1; i++) {
from1 = data1[i*2];
to1 = data1[i*2+1];
for (j = 0; j < n2; j++) {
from2 = data2[j*2];
to2 = data2[j*2+1];
if (from2 > to1) break;
if (to2 < from1) continue;
from = MAX(from1, from2);
to = MIN(to1, to2);
r = add_code_range_to_buf(pbuf, from, to);
if (r != 0) return r;
}
}
}
else if (not1 == 0) { /* 1 AND (not 2) */
for (i = 0; i < n1; i++) {
from1 = data1[i*2];
to1 = data1[i*2+1];
r = and_code_range1(pbuf, from1, to1, data2, n2);
if (r != 0) return r;
}
}
return 0;
}
static int
and_cclass(CClassNode* dest, CClassNode* cc, OnigEncoding enc)
{
int r, not1, not2;
BBuf *buf1, *buf2, *pbuf;
BitSetRef bsr1, bsr2;
BitSet bs1, bs2;
not1 = IS_NCCLASS_NOT(dest);
bsr1 = dest->bs;
buf1 = dest->mbuf;
not2 = IS_NCCLASS_NOT(cc);
bsr2 = cc->bs;
buf2 = cc->mbuf;
if (not1 != 0) {
bitset_invert_to(bsr1, bs1);
bsr1 = bs1;
}
if (not2 != 0) {
bitset_invert_to(bsr2, bs2);
bsr2 = bs2;
}
bitset_and(bsr1, bsr2);
if (bsr1 != dest->bs) {
bitset_copy(dest->bs, bsr1);
bsr1 = dest->bs;
}
if (not1 != 0) {
bitset_invert(dest->bs);
}
if (! ONIGENC_IS_SINGLEBYTE(enc)) {
if (not1 != 0 && not2 != 0) {
r = or_code_range_buf(enc, buf1, 0, buf2, 0, &pbuf);
}
else {
r = and_code_range_buf(buf1, not1, buf2, not2, &pbuf);
if (r == 0 && not1 != 0) {
BBuf *tbuf;
r = not_code_range_buf(enc, pbuf, &tbuf);
if (r != 0) {
bbuf_free(pbuf);
return r;
}
bbuf_free(pbuf);
pbuf = tbuf;
}
}
if (r != 0) return r;
dest->mbuf = pbuf;
bbuf_free(buf1);
return r;
}
return 0;
}
static int
or_cclass(CClassNode* dest, CClassNode* cc, OnigEncoding enc)
{
int r, not1, not2;
BBuf *buf1, *buf2, *pbuf;
BitSetRef bsr1, bsr2;
BitSet bs1, bs2;
not1 = IS_NCCLASS_NOT(dest);
bsr1 = dest->bs;
buf1 = dest->mbuf;
not2 = IS_NCCLASS_NOT(cc);
bsr2 = cc->bs;
buf2 = cc->mbuf;
if (not1 != 0) {
bitset_invert_to(bsr1, bs1);
bsr1 = bs1;
}
if (not2 != 0) {
bitset_invert_to(bsr2, bs2);
bsr2 = bs2;
}
bitset_or(bsr1, bsr2);
if (bsr1 != dest->bs) {
bitset_copy(dest->bs, bsr1);
bsr1 = dest->bs;
}
if (not1 != 0) {
bitset_invert(dest->bs);
}
if (! ONIGENC_IS_SINGLEBYTE(enc)) {
if (not1 != 0 && not2 != 0) {
r = and_code_range_buf(buf1, 0, buf2, 0, &pbuf);
}
else {
r = or_code_range_buf(enc, buf1, not1, buf2, not2, &pbuf);
if (r == 0 && not1 != 0) {
BBuf *tbuf;
r = not_code_range_buf(enc, pbuf, &tbuf);
if (r != 0) {
bbuf_free(pbuf);
return r;
}
bbuf_free(pbuf);
pbuf = tbuf;
}
}
if (r != 0) return r;
dest->mbuf = pbuf;
bbuf_free(buf1);
return r;
}
else
return 0;
}
static OnigCodePoint
conv_backslash_value(OnigCodePoint c, ScanEnv* env)
{
if (IS_SYNTAX_OP(env->syntax, ONIG_SYN_OP_ESC_CONTROL_CHARS)) {
switch (c) {
case 'n': return '\n';
case 't': return '\t';
case 'r': return '\r';
case 'f': return '\f';
case 'a': return '\007';
case 'b': return '\010';
case 'e': return '\033';
case 'v':
if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ESC_V_VTAB))
return '\v';
break;
default:
break;
}
}
return c;
}
static int
is_invalid_quantifier_target(Node* node)
{
switch (NTYPE(node)) {
case NT_ANCHOR:
return 1;
break;
case NT_ENCLOSE:
/* allow enclosed elements */
/* return is_invalid_quantifier_target(NENCLOSE(node)->target); */
break;
case NT_LIST:
do {
if (! is_invalid_quantifier_target(NCAR(node))) return 0;
} while (IS_NOT_NULL(node = NCDR(node)));
return 0;
break;
case NT_ALT:
do {
if (is_invalid_quantifier_target(NCAR(node))) return 1;
} while (IS_NOT_NULL(node = NCDR(node)));
break;
default:
break;
}
return 0;
}
/* ?:0, *:1, +:2, ??:3, *?:4, +?:5 */
static int
popular_quantifier_num(QtfrNode* q)
{
if (q->greedy) {
if (q->lower == 0) {
if (q->upper == 1) return 0;
else if (IS_REPEAT_INFINITE(q->upper)) return 1;
}
else if (q->lower == 1) {
if (IS_REPEAT_INFINITE(q->upper)) return 2;
}
}
else {
if (q->lower == 0) {
if (q->upper == 1) return 3;
else if (IS_REPEAT_INFINITE(q->upper)) return 4;
}
else if (q->lower == 1) {
if (IS_REPEAT_INFINITE(q->upper)) return 5;
}
}
return -1;
}
enum ReduceType {
RQ_ASIS = 0, /* as is */
RQ_DEL = 1, /* delete parent */
RQ_A, /* to '*' */
RQ_AQ, /* to '*?' */
RQ_QQ, /* to '??' */
RQ_P_QQ, /* to '+)??' */
RQ_PQ_Q /* to '+?)?' */
};
static enum ReduceType ReduceTypeTable[6][6] = {
{RQ_DEL, RQ_A, RQ_A, RQ_QQ, RQ_AQ, RQ_ASIS}, /* '?' */
{RQ_DEL, RQ_DEL, RQ_DEL, RQ_P_QQ, RQ_P_QQ, RQ_DEL}, /* '*' */
{RQ_A, RQ_A, RQ_DEL, RQ_ASIS, RQ_P_QQ, RQ_DEL}, /* '+' */
{RQ_DEL, RQ_AQ, RQ_AQ, RQ_DEL, RQ_AQ, RQ_AQ}, /* '??' */
{RQ_DEL, RQ_DEL, RQ_DEL, RQ_DEL, RQ_DEL, RQ_DEL}, /* '*?' */
{RQ_ASIS, RQ_PQ_Q, RQ_DEL, RQ_AQ, RQ_AQ, RQ_DEL} /* '+?' */
};
extern void
onig_reduce_nested_quantifier(Node* pnode, Node* cnode)
{
int pnum, cnum;
QtfrNode *p, *c;
p = NQTFR(pnode);
c = NQTFR(cnode);
pnum = popular_quantifier_num(p);
cnum = popular_quantifier_num(c);
if (pnum < 0 || cnum < 0) return ;
switch(ReduceTypeTable[cnum][pnum]) {
case RQ_DEL:
*pnode = *cnode;
break;
case RQ_A:
p->target = c->target;
p->lower = 0; p->upper = REPEAT_INFINITE; p->greedy = 1;
break;
case RQ_AQ:
p->target = c->target;
p->lower = 0; p->upper = REPEAT_INFINITE; p->greedy = 0;
break;
case RQ_QQ:
p->target = c->target;
p->lower = 0; p->upper = 1; p->greedy = 0;
break;
case RQ_P_QQ:
p->target = cnode;
p->lower = 0; p->upper = 1; p->greedy = 0;
c->lower = 1; c->upper = REPEAT_INFINITE; c->greedy = 1;
return ;
break;
case RQ_PQ_Q:
p->target = cnode;
p->lower = 0; p->upper = 1; p->greedy = 1;
c->lower = 1; c->upper = REPEAT_INFINITE; c->greedy = 0;
return ;
break;
case RQ_ASIS:
p->target = cnode;
return ;
break;
}
c->target = NULL_NODE;
onig_node_free(cnode);
}
enum TokenSyms {
TK_EOT = 0, /* end of token */
TK_RAW_BYTE = 1,
TK_CHAR,
TK_STRING,
TK_CODE_POINT,
TK_ANYCHAR,
TK_CHAR_TYPE,
TK_BACKREF,
TK_CALL,
TK_ANCHOR,
TK_OP_REPEAT,
TK_INTERVAL,
TK_ANYCHAR_ANYTIME, /* SQL '%' == .* */
TK_ALT,
TK_SUBEXP_OPEN,
TK_SUBEXP_CLOSE,
TK_CC_OPEN,
TK_QUOTE_OPEN,
TK_CHAR_PROPERTY, /* \p{...}, \P{...} */
/* in cc */
TK_CC_CLOSE,
TK_CC_RANGE,
TK_POSIX_BRACKET_OPEN,
TK_CC_AND, /* && */
TK_CC_CC_OPEN /* [ */
};
typedef struct {
enum TokenSyms type;
int escaped;
int base; /* is number: 8, 16 (used in [....]) */
UChar* backp;
union {
UChar* s;
int c;
OnigCodePoint code;
int anchor;
int subtype;
struct {
int lower;
int upper;
int greedy;
int possessive;
} repeat;
struct {
int num;
int ref1;
int* refs;
int by_name;
#ifdef USE_BACKREF_WITH_LEVEL
int exist_level;
int level; /* \k<name+n> */
#endif
} backref;
struct {
UChar* name;
UChar* name_end;
int gnum;
} call;
struct {
int ctype;
int not;
} prop;
} u;
} OnigToken;
static int
fetch_range_quantifier(UChar** src, UChar* end, OnigToken* tok, ScanEnv* env)
{
int low, up, syn_allow, non_low = 0;
int r = 0;
OnigCodePoint c;
OnigEncoding enc = env->enc;
UChar* p = *src;
PFETCH_READY;
syn_allow = IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_INVALID_INTERVAL);
if (PEND) {
if (syn_allow)
return 1; /* "....{" : OK! */
else
return ONIGERR_END_PATTERN_AT_LEFT_BRACE; /* "....{" syntax error */
}
if (! syn_allow) {
c = PPEEK;
if (c == ')' || c == '(' || c == '|') {
return ONIGERR_END_PATTERN_AT_LEFT_BRACE;
}
}
low = onig_scan_unsigned_number(&p, end, env->enc);
if (low < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE;
if (low > ONIG_MAX_REPEAT_NUM)
return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE;
if (p == *src) { /* can't read low */
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_INTERVAL_LOW_ABBREV)) {
/* allow {,n} as {0,n} */
low = 0;
non_low = 1;
}
else
goto invalid;
}
if (PEND) goto invalid;
PFETCH(c);
if (c == ',') {
UChar* prev = p;
up = onig_scan_unsigned_number(&p, end, env->enc);
if (up < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE;
if (up > ONIG_MAX_REPEAT_NUM)
return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE;
if (p == prev) {
if (non_low != 0)
goto invalid;
up = REPEAT_INFINITE; /* {n,} : {n,infinite} */
}
}
else {
if (non_low != 0)
goto invalid;
PUNFETCH;
up = low; /* {n} : exact n times */
r = 2; /* fixed */
}
if (PEND) goto invalid;
PFETCH(c);
if (IS_SYNTAX_OP(env->syntax, ONIG_SYN_OP_ESC_BRACE_INTERVAL)) {
if (c != MC_ESC(env->syntax)) goto invalid;
PFETCH(c);
}
if (c != '}') goto invalid;
if (!IS_REPEAT_INFINITE(up) && low > up) {
return ONIGERR_UPPER_SMALLER_THAN_LOWER_IN_REPEAT_RANGE;
}
tok->type = TK_INTERVAL;
tok->u.repeat.lower = low;
tok->u.repeat.upper = up;
*src = p;
return r; /* 0: normal {n,m}, 2: fixed {n} */
invalid:
if (syn_allow) {
/* *src = p; */ /* !!! Don't do this line !!! */
return 1; /* OK */
}
else
return ONIGERR_INVALID_REPEAT_RANGE_PATTERN;
}
/* \M-, \C-, \c, or \... */
static int
fetch_escaped_value(UChar** src, UChar* end, ScanEnv* env, OnigCodePoint* val)
{
int v;
OnigCodePoint c;
OnigEncoding enc = env->enc;
UChar* p = *src;
if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE;
PFETCH_S(c);
switch (c) {
case 'M':
if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ESC_CAPITAL_M_BAR_META)) {
if (PEND) return ONIGERR_END_PATTERN_AT_META;
PFETCH_S(c);
if (c != '-') return ONIGERR_META_CODE_SYNTAX;
if (PEND) return ONIGERR_END_PATTERN_AT_META;
PFETCH_S(c);
if (c == MC_ESC(env->syntax)) {
v = fetch_escaped_value(&p, end, env, &c);
if (v < 0) return v;
}
c = ((c & 0xff) | 0x80);
}
else
goto backslash;
break;
case 'C':
if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ESC_CAPITAL_C_BAR_CONTROL)) {
if (PEND) return ONIGERR_END_PATTERN_AT_CONTROL;
PFETCH_S(c);
if (c != '-') return ONIGERR_CONTROL_CODE_SYNTAX;
goto control;
}
else
goto backslash;
case 'c':
if (IS_SYNTAX_OP(env->syntax, ONIG_SYN_OP_ESC_C_CONTROL)) {
control:
if (PEND) return ONIGERR_END_PATTERN_AT_CONTROL;
PFETCH_S(c);
if (c == '?') {
c = 0177;
}
else {
if (c == MC_ESC(env->syntax)) {
v = fetch_escaped_value(&p, end, env, &c);
if (v < 0) return v;
}
c &= 0x9f;
}
break;
}
/* fall through */
default:
{
backslash:
c = conv_backslash_value(c, env);
}
break;
}
*src = p;
*val = c;
return 0;
}
static int fetch_token(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env);
static OnigCodePoint
get_name_end_code_point(OnigCodePoint start)
{
switch (start) {
case '<': return (OnigCodePoint )'>'; break;
case '\'': return (OnigCodePoint )'\''; break;
default:
break;
}
return (OnigCodePoint )0;
}
#ifdef USE_NAMED_GROUP
#ifdef USE_BACKREF_WITH_LEVEL
/*
\k<name+n>, \k<name-n>
\k<num+n>, \k<num-n>
\k<-num+n>, \k<-num-n>
*/
static int
fetch_name_with_level(OnigCodePoint start_code, UChar** src, UChar* end,
UChar** rname_end, ScanEnv* env,
int* rback_num, int* rlevel)
{
int r, sign, is_num, exist_level;
OnigCodePoint end_code;
OnigCodePoint c = 0;
OnigEncoding enc = env->enc;
UChar *name_end;
UChar *pnum_head;
UChar *p = *src;
PFETCH_READY;
*rback_num = 0;
is_num = exist_level = 0;
sign = 1;
pnum_head = *src;
end_code = get_name_end_code_point(start_code);
name_end = end;
r = 0;
if (PEND) {
return ONIGERR_EMPTY_GROUP_NAME;
}
else {
PFETCH(c);
if (c == end_code)
return ONIGERR_EMPTY_GROUP_NAME;
if (ONIGENC_IS_CODE_DIGIT(enc, c)) {
is_num = 1;
}
else if (c == '-') {
is_num = 2;
sign = -1;
pnum_head = p;
}
else if (!ONIGENC_IS_CODE_WORD(enc, c)) {
r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME;
}
}
while (!PEND) {
name_end = p;
PFETCH(c);
if (c == end_code || c == ')' || c == '+' || c == '-') {
if (is_num == 2) r = ONIGERR_INVALID_GROUP_NAME;
break;
}
if (is_num != 0) {
if (ONIGENC_IS_CODE_DIGIT(enc, c)) {
is_num = 1;
}
else {
r = ONIGERR_INVALID_GROUP_NAME;
is_num = 0;
}
}
else if (!ONIGENC_IS_CODE_WORD(enc, c)) {
r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME;
}
}
if (r == 0 && c != end_code) {
if (c == '+' || c == '-') {
int level;
int flag = (c == '-' ? -1 : 1);
if (PEND) {
r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME;
goto end;
}
PFETCH(c);
if (! ONIGENC_IS_CODE_DIGIT(enc, c)) goto err;
PUNFETCH;
level = onig_scan_unsigned_number(&p, end, enc);
if (level < 0) return ONIGERR_TOO_BIG_NUMBER;
*rlevel = (level * flag);
exist_level = 1;
if (!PEND) {
PFETCH(c);
if (c == end_code)
goto end;
}
}
err:
r = ONIGERR_INVALID_GROUP_NAME;
name_end = end;
}
end:
if (r == 0) {
if (is_num != 0) {
*rback_num = onig_scan_unsigned_number(&pnum_head, name_end, enc);
if (*rback_num < 0) return ONIGERR_TOO_BIG_NUMBER;
else if (*rback_num == 0) goto err;
*rback_num *= sign;
}
*rname_end = name_end;
*src = p;
return (exist_level ? 1 : 0);
}
else {
onig_scan_env_set_error_string(env, r, *src, name_end);
return r;
}
}
#endif /* USE_BACKREF_WITH_LEVEL */
/*
ref: 0 -> define name (don't allow number name)
1 -> reference name (allow number name)
*/
static int
fetch_name(OnigCodePoint start_code, UChar** src, UChar* end,
UChar** rname_end, ScanEnv* env, int* rback_num, int ref)
{
int r, is_num, sign;
OnigCodePoint end_code;
OnigCodePoint c = 0;
OnigEncoding enc = env->enc;
UChar *name_end;
UChar *pnum_head;
UChar *p = *src;
*rback_num = 0;
end_code = get_name_end_code_point(start_code);
name_end = end;
pnum_head = *src;
r = 0;
is_num = 0;
sign = 1;
if (PEND) {
return ONIGERR_EMPTY_GROUP_NAME;
}
else {
PFETCH_S(c);
if (c == end_code)
return ONIGERR_EMPTY_GROUP_NAME;
if (ONIGENC_IS_CODE_DIGIT(enc, c)) {
if (ref == 1)
is_num = 1;
else {
r = ONIGERR_INVALID_GROUP_NAME;
is_num = 0;
}
}
else if (c == '-') {
if (ref == 1) {
is_num = 2;
sign = -1;
pnum_head = p;
}
else {
r = ONIGERR_INVALID_GROUP_NAME;
is_num = 0;
}
}
else if (!ONIGENC_IS_CODE_WORD(enc, c)) {
r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME;
}
}
if (r == 0) {
while (!PEND) {
name_end = p;
PFETCH_S(c);
if (c == end_code || c == ')') {
if (is_num == 2) r = ONIGERR_INVALID_GROUP_NAME;
break;
}
if (is_num != 0) {
if (ONIGENC_IS_CODE_DIGIT(enc, c)) {
is_num = 1;
}
else {
if (!ONIGENC_IS_CODE_WORD(enc, c))
r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME;
else
r = ONIGERR_INVALID_GROUP_NAME;
is_num = 0;
}
}
else {
if (!ONIGENC_IS_CODE_WORD(enc, c)) {
r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME;
}
}
}
if (c != end_code) {
r = ONIGERR_INVALID_GROUP_NAME;
name_end = end;
}
if (is_num != 0) {
*rback_num = onig_scan_unsigned_number(&pnum_head, name_end, enc);
if (*rback_num < 0) return ONIGERR_TOO_BIG_NUMBER;
else if (*rback_num == 0) {
r = ONIGERR_INVALID_GROUP_NAME;
goto err;
}
*rback_num *= sign;
}
*rname_end = name_end;
*src = p;
return 0;
}
else {
while (!PEND) {
name_end = p;
PFETCH_S(c);
if (c == end_code || c == ')')
break;
}
if (PEND)
name_end = end;
err:
onig_scan_env_set_error_string(env, r, *src, name_end);
return r;
}
}
#else
static int
fetch_name(OnigCodePoint start_code, UChar** src, UChar* end,
UChar** rname_end, ScanEnv* env, int* rback_num, int ref)
{
int r, is_num, sign;
OnigCodePoint end_code;
OnigCodePoint c = 0;
UChar *name_end;
OnigEncoding enc = env->enc;
UChar *pnum_head;
UChar *p = *src;
PFETCH_READY;
*rback_num = 0;
end_code = get_name_end_code_point(start_code);
*rname_end = name_end = end;
r = 0;
pnum_head = *src;
is_num = 0;
sign = 1;
if (PEND) {
return ONIGERR_EMPTY_GROUP_NAME;
}
else {
PFETCH(c);
if (c == end_code)
return ONIGERR_EMPTY_GROUP_NAME;
if (ONIGENC_IS_CODE_DIGIT(enc, c)) {
is_num = 1;
}
else if (c == '-') {
is_num = 2;
sign = -1;
pnum_head = p;
}
else {
r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME;
}
}
while (!PEND) {
name_end = p;
PFETCH(c);
if (c == end_code || c == ')') break;
if (! ONIGENC_IS_CODE_DIGIT(enc, c))
r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME;
}
if (r == 0 && c != end_code) {
r = ONIGERR_INVALID_GROUP_NAME;
name_end = end;
}
if (r == 0) {
*rback_num = onig_scan_unsigned_number(&pnum_head, name_end, enc);
if (*rback_num < 0) return ONIGERR_TOO_BIG_NUMBER;
else if (*rback_num == 0) {
r = ONIGERR_INVALID_GROUP_NAME;
goto err;
}
*rback_num *= sign;
*rname_end = name_end;
*src = p;
return 0;
}
else {
err:
onig_scan_env_set_error_string(env, r, *src, name_end);
return r;
}
}
#endif /* USE_NAMED_GROUP */
static void
CC_ESC_WARN(ScanEnv* env, UChar *c)
{
if (onig_warn == onig_null_warn) return ;
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_WARN_CC_OP_NOT_ESCAPED) &&
IS_SYNTAX_BV(env->syntax, ONIG_SYN_BACKSLASH_ESCAPE_IN_CC)) {
UChar buf[WARN_BUFSIZE];
onig_snprintf_with_pattern(buf, WARN_BUFSIZE, env->enc,
env->pattern, env->pattern_end,
(UChar* )"character class has '%s' without escape", c);
(*onig_warn)((char* )buf);
}
}
static void
CLOSE_BRACKET_WITHOUT_ESC_WARN(ScanEnv* env, UChar* c)
{
if (onig_warn == onig_null_warn) return ;
if (IS_SYNTAX_BV((env)->syntax, ONIG_SYN_WARN_CC_OP_NOT_ESCAPED)) {
UChar buf[WARN_BUFSIZE];
onig_snprintf_with_pattern(buf, WARN_BUFSIZE, (env)->enc,
(env)->pattern, (env)->pattern_end,
(UChar* )"regular expression has '%s' without escape", c);
(*onig_warn)((char* )buf);
}
}
static UChar*
find_str_position(OnigCodePoint s[], int n, UChar* from, UChar* to,
UChar **next, OnigEncoding enc)
{
int i;
OnigCodePoint x;
UChar *q;
UChar *p = from;
while (p < to) {
x = ONIGENC_MBC_TO_CODE(enc, p, to);
q = p + enclen(enc, p);
if (x == s[0]) {
for (i = 1; i < n && q < to; i++) {
x = ONIGENC_MBC_TO_CODE(enc, q, to);
if (x != s[i]) break;
q += enclen(enc, q);
}
if (i >= n) {
if (IS_NOT_NULL(next))
*next = q;
return p;
}
}
p = q;
}
return NULL_UCHARP;
}
static int
str_exist_check_with_esc(OnigCodePoint s[], int n, UChar* from, UChar* to,
OnigCodePoint bad, OnigEncoding enc, OnigSyntaxType* syn)
{
int i, in_esc;
OnigCodePoint x;
UChar *q;
UChar *p = from;
in_esc = 0;
while (p < to) {
if (in_esc) {
in_esc = 0;
p += enclen(enc, p);
}
else {
x = ONIGENC_MBC_TO_CODE(enc, p, to);
q = p + enclen(enc, p);
if (x == s[0]) {
for (i = 1; i < n && q < to; i++) {
x = ONIGENC_MBC_TO_CODE(enc, q, to);
if (x != s[i]) break;
q += enclen(enc, q);
}
if (i >= n) return 1;
p += enclen(enc, p);
}
else {
x = ONIGENC_MBC_TO_CODE(enc, p, to);
if (x == bad) return 0;
else if (x == MC_ESC(syn)) in_esc = 1;
p = q;
}
}
}
return 0;
}
static int
fetch_token_in_cc(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env)
{
int num;
OnigCodePoint c, c2;
OnigSyntaxType* syn = env->syntax;
OnigEncoding enc = env->enc;
UChar* prev;
UChar* p = *src;
PFETCH_READY;
if (PEND) {
tok->type = TK_EOT;
return tok->type;
}
PFETCH(c);
tok->type = TK_CHAR;
tok->base = 0;
tok->u.c = c;
tok->escaped = 0;
if (c == ']') {
tok->type = TK_CC_CLOSE;
}
else if (c == '-') {
tok->type = TK_CC_RANGE;
}
else if (c == MC_ESC(syn)) {
if (! IS_SYNTAX_BV(syn, ONIG_SYN_BACKSLASH_ESCAPE_IN_CC))
goto end;
if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE;
PFETCH(c);
tok->escaped = 1;
tok->u.c = c;
switch (c) {
case 'w':
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_WORD;
tok->u.prop.not = 0;
break;
case 'W':
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_WORD;
tok->u.prop.not = 1;
break;
case 'd':
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT;
tok->u.prop.not = 0;
break;
case 'D':
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT;
tok->u.prop.not = 1;
break;
case 's':
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_SPACE;
tok->u.prop.not = 0;
break;
case 'S':
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_SPACE;
tok->u.prop.not = 1;
break;
case 'h':
if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT;
tok->u.prop.not = 0;
break;
case 'H':
if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT;
tok->u.prop.not = 1;
break;
case 'p':
case 'P':
if (PEND) break;
c2 = PPEEK;
if (c2 == '{' &&
IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY)) {
PINC;
tok->type = TK_CHAR_PROPERTY;
tok->u.prop.not = (c == 'P' ? 1 : 0);
if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT)) {
PFETCH(c2);
if (c2 == '^') {
tok->u.prop.not = (tok->u.prop.not == 0 ? 1 : 0);
}
else
PUNFETCH;
}
}
break;
case 'x':
if (PEND) break;
prev = p;
if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) {
PINC;
num = scan_unsigned_hexadecimal_number(&p, end, 8, enc);
if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE;
if (!PEND) {
c2 = PPEEK;
if (ONIGENC_IS_CODE_XDIGIT(enc, c2))
return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE;
}
if (p > prev + enclen(enc, prev) && !PEND && (PPEEK_IS('}'))) {
PINC;
tok->type = TK_CODE_POINT;
tok->base = 16;
tok->u.code = (OnigCodePoint )num;
}
else {
/* can't read nothing or invalid format */
p = prev;
}
}
else if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_HEX2)) {
num = scan_unsigned_hexadecimal_number(&p, end, 2, enc);
if (num < 0) return ONIGERR_TOO_BIG_NUMBER;
if (p == prev) { /* can't read nothing. */
num = 0; /* but, it's not error */
}
tok->type = TK_RAW_BYTE;
tok->base = 16;
tok->u.c = num;
}
break;
case 'u':
if (PEND) break;
prev = p;
if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) {
num = scan_unsigned_hexadecimal_number(&p, end, 4, enc);
if (num < 0) return ONIGERR_TOO_BIG_NUMBER;
if (p == prev) { /* can't read nothing. */
num = 0; /* but, it's not error */
}
tok->type = TK_CODE_POINT;
tok->base = 16;
tok->u.code = (OnigCodePoint )num;
}
break;
case '0':
case '1': case '2': case '3': case '4': case '5': case '6': case '7':
if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_OCTAL3)) {
PUNFETCH;
prev = p;
num = scan_unsigned_octal_number(&p, end, 3, enc);
if (num < 0) return ONIGERR_TOO_BIG_NUMBER;
if (p == prev) { /* can't read nothing. */
num = 0; /* but, it's not error */
}
tok->type = TK_RAW_BYTE;
tok->base = 8;
tok->u.c = num;
}
break;
default:
PUNFETCH;
num = fetch_escaped_value(&p, end, env, &c2);
if (num < 0) return num;
if (tok->u.c != c2) {
tok->u.code = c2;
tok->type = TK_CODE_POINT;
}
break;
}
}
else if (c == '[') {
if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_POSIX_BRACKET) && (PPEEK_IS(':'))) {
OnigCodePoint send[] = { (OnigCodePoint )':', (OnigCodePoint )']' };
tok->backp = p; /* point at '[' is read */
PINC;
if (str_exist_check_with_esc(send, 2, p, end,
(OnigCodePoint )']', enc, syn)) {
tok->type = TK_POSIX_BRACKET_OPEN;
}
else {
PUNFETCH;
goto cc_in_cc;
}
}
else {
cc_in_cc:
if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_CCLASS_SET_OP)) {
tok->type = TK_CC_CC_OPEN;
}
else {
CC_ESC_WARN(env, (UChar* )"[");
}
}
}
else if (c == '&') {
if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_CCLASS_SET_OP) &&
!PEND && (PPEEK_IS('&'))) {
PINC;
tok->type = TK_CC_AND;
}
}
end:
*src = p;
return tok->type;
}
static int
fetch_token(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env)
{
int r, num;
OnigCodePoint c;
OnigEncoding enc = env->enc;
OnigSyntaxType* syn = env->syntax;
UChar* prev;
UChar* p = *src;
PFETCH_READY;
start:
if (PEND) {
tok->type = TK_EOT;
return tok->type;
}
tok->type = TK_STRING;
tok->base = 0;
tok->backp = p;
PFETCH(c);
if (IS_MC_ESC_CODE(c, syn)) {
if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE;
tok->backp = p;
PFETCH(c);
tok->u.c = c;
tok->escaped = 1;
switch (c) {
case '*':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_ASTERISK_ZERO_INF)) break;
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 0;
tok->u.repeat.upper = REPEAT_INFINITE;
goto greedy_check;
break;
case '+':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_PLUS_ONE_INF)) break;
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 1;
tok->u.repeat.upper = REPEAT_INFINITE;
goto greedy_check;
break;
case '?':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_QMARK_ZERO_ONE)) break;
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 0;
tok->u.repeat.upper = 1;
greedy_check:
if (!PEND && PPEEK_IS('?') &&
IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_NON_GREEDY)) {
PFETCH(c);
tok->u.repeat.greedy = 0;
tok->u.repeat.possessive = 0;
}
else {
possessive_check:
if (!PEND && PPEEK_IS('+') &&
((IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_REPEAT) &&
tok->type != TK_INTERVAL) ||
(IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_INTERVAL) &&
tok->type == TK_INTERVAL))) {
PFETCH(c);
tok->u.repeat.greedy = 1;
tok->u.repeat.possessive = 1;
}
else {
tok->u.repeat.greedy = 1;
tok->u.repeat.possessive = 0;
}
}
break;
case '{':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_BRACE_INTERVAL)) break;
r = fetch_range_quantifier(&p, end, tok, env);
if (r < 0) return r; /* error */
if (r == 0) goto greedy_check;
else if (r == 2) { /* {n} */
if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY))
goto possessive_check;
goto greedy_check;
}
/* r == 1 : normal char */
break;
case '|':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_VBAR_ALT)) break;
tok->type = TK_ALT;
break;
case '(':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break;
tok->type = TK_SUBEXP_OPEN;
break;
case ')':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break;
tok->type = TK_SUBEXP_CLOSE;
break;
case 'w':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_WORD;
tok->u.prop.not = 0;
break;
case 'W':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_WORD;
tok->u.prop.not = 1;
break;
case 'b':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break;
tok->type = TK_ANCHOR;
tok->u.anchor = ANCHOR_WORD_BOUND;
break;
case 'B':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break;
tok->type = TK_ANCHOR;
tok->u.anchor = ANCHOR_NOT_WORD_BOUND;
break;
#ifdef USE_WORD_BEGIN_END
case '<':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break;
tok->type = TK_ANCHOR;
tok->u.anchor = ANCHOR_WORD_BEGIN;
break;
case '>':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break;
tok->type = TK_ANCHOR;
tok->u.anchor = ANCHOR_WORD_END;
break;
#endif
case 's':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_SPACE;
tok->u.prop.not = 0;
break;
case 'S':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_SPACE;
tok->u.prop.not = 1;
break;
case 'd':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT;
tok->u.prop.not = 0;
break;
case 'D':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT;
tok->u.prop.not = 1;
break;
case 'h':
if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT;
tok->u.prop.not = 0;
break;
case 'H':
if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT;
tok->u.prop.not = 1;
break;
case 'A':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break;
begin_buf:
tok->type = TK_ANCHOR;
tok->u.subtype = ANCHOR_BEGIN_BUF;
break;
case 'Z':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break;
tok->type = TK_ANCHOR;
tok->u.subtype = ANCHOR_SEMI_END_BUF;
break;
case 'z':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break;
end_buf:
tok->type = TK_ANCHOR;
tok->u.subtype = ANCHOR_END_BUF;
break;
case 'G':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_CAPITAL_G_BEGIN_ANCHOR)) break;
tok->type = TK_ANCHOR;
tok->u.subtype = ANCHOR_BEGIN_POSITION;
break;
case '`':
if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break;
goto begin_buf;
break;
case '\'':
if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break;
goto end_buf;
break;
case 'x':
if (PEND) break;
prev = p;
if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) {
PINC;
num = scan_unsigned_hexadecimal_number(&p, end, 8, enc);
if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE;
if (!PEND) {
if (ONIGENC_IS_CODE_XDIGIT(enc, PPEEK))
return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE;
}
if ((p > prev + enclen(enc, prev)) && !PEND && PPEEK_IS('}')) {
PINC;
tok->type = TK_CODE_POINT;
tok->u.code = (OnigCodePoint )num;
}
else {
/* can't read nothing or invalid format */
p = prev;
}
}
else if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_HEX2)) {
num = scan_unsigned_hexadecimal_number(&p, end, 2, enc);
if (num < 0) return ONIGERR_TOO_BIG_NUMBER;
if (p == prev) { /* can't read nothing. */
num = 0; /* but, it's not error */
}
tok->type = TK_RAW_BYTE;
tok->base = 16;
tok->u.c = num;
}
break;
case 'u':
if (PEND) break;
prev = p;
if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) {
num = scan_unsigned_hexadecimal_number(&p, end, 4, enc);
if (num < 0) return ONIGERR_TOO_BIG_NUMBER;
if (p == prev) { /* can't read nothing. */
num = 0; /* but, it's not error */
}
tok->type = TK_CODE_POINT;
tok->base = 16;
tok->u.code = (OnigCodePoint )num;
}
break;
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
PUNFETCH;
prev = p;
num = onig_scan_unsigned_number(&p, end, enc);
if (num < 0 || num > ONIG_MAX_BACKREF_NUM) {
goto skip_backref;
}
if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_DECIMAL_BACKREF) &&
(num <= env->num_mem || num <= 9)) { /* This spec. from GNU regex */
if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) {
if (num > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[num]))
return ONIGERR_INVALID_BACKREF;
}
tok->type = TK_BACKREF;
tok->u.backref.num = 1;
tok->u.backref.ref1 = num;
tok->u.backref.by_name = 0;
#ifdef USE_BACKREF_WITH_LEVEL
tok->u.backref.exist_level = 0;
#endif
break;
}
skip_backref:
if (c == '8' || c == '9') {
/* normal char */
p = prev; PINC;
break;
}
p = prev;
/* fall through */
case '0':
if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_OCTAL3)) {
prev = p;
num = scan_unsigned_octal_number(&p, end, (c == '0' ? 2:3), enc);
if (num < 0) return ONIGERR_TOO_BIG_NUMBER;
if (p == prev) { /* can't read nothing. */
num = 0; /* but, it's not error */
}
tok->type = TK_RAW_BYTE;
tok->base = 8;
tok->u.c = num;
}
else if (c != '0') {
PINC;
}
break;
#ifdef USE_NAMED_GROUP
case 'k':
if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_K_NAMED_BACKREF)) {
PFETCH(c);
if (c == '<' || c == '\'') {
UChar* name_end;
int* backs;
int back_num;
prev = p;
#ifdef USE_BACKREF_WITH_LEVEL
name_end = NULL_UCHARP; /* no need. escape gcc warning. */
r = fetch_name_with_level((OnigCodePoint )c, &p, end, &name_end,
env, &back_num, &tok->u.backref.level);
if (r == 1) tok->u.backref.exist_level = 1;
else tok->u.backref.exist_level = 0;
#else
r = fetch_name(&p, end, &name_end, env, &back_num, 1);
#endif
if (r < 0) return r;
if (back_num != 0) {
if (back_num < 0) {
back_num = BACKREF_REL_TO_ABS(back_num, env);
if (back_num <= 0)
return ONIGERR_INVALID_BACKREF;
}
if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) {
if (back_num > env->num_mem ||
IS_NULL(SCANENV_MEM_NODES(env)[back_num]))
return ONIGERR_INVALID_BACKREF;
}
tok->type = TK_BACKREF;
tok->u.backref.by_name = 0;
tok->u.backref.num = 1;
tok->u.backref.ref1 = back_num;
}
else {
num = onig_name_to_group_numbers(env->reg, prev, name_end, &backs);
if (num <= 0) {
onig_scan_env_set_error_string(env,
ONIGERR_UNDEFINED_NAME_REFERENCE, prev, name_end);
return ONIGERR_UNDEFINED_NAME_REFERENCE;
}
if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) {
int i;
for (i = 0; i < num; i++) {
if (backs[i] > env->num_mem ||
IS_NULL(SCANENV_MEM_NODES(env)[backs[i]]))
return ONIGERR_INVALID_BACKREF;
}
}
tok->type = TK_BACKREF;
tok->u.backref.by_name = 1;
if (num == 1) {
tok->u.backref.num = 1;
tok->u.backref.ref1 = backs[0];
}
else {
tok->u.backref.num = num;
tok->u.backref.refs = backs;
}
}
}
else
PUNFETCH;
}
break;
#endif
#ifdef USE_SUBEXP_CALL
case 'g':
if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_G_SUBEXP_CALL)) {
PFETCH(c);
if (c == '<' || c == '\'') {
int gnum;
UChar* name_end;
prev = p;
r = fetch_name((OnigCodePoint )c, &p, end, &name_end, env, &gnum, 1);
if (r < 0) return r;
tok->type = TK_CALL;
tok->u.call.name = prev;
tok->u.call.name_end = name_end;
tok->u.call.gnum = gnum;
}
else
PUNFETCH;
}
break;
#endif
case 'Q':
if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_Q_QUOTE)) {
tok->type = TK_QUOTE_OPEN;
}
break;
case 'p':
case 'P':
if (!PEND && PPEEK_IS('{') &&
IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY)) {
PINC;
tok->type = TK_CHAR_PROPERTY;
tok->u.prop.not = (c == 'P' ? 1 : 0);
if (!PEND &&
IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT)) {
PFETCH(c);
if (c == '^') {
tok->u.prop.not = (tok->u.prop.not == 0 ? 1 : 0);
}
else
PUNFETCH;
}
}
break;
default:
{
OnigCodePoint c2;
PUNFETCH;
num = fetch_escaped_value(&p, end, env, &c2);
if (num < 0) return num;
/* set_raw: */
if (tok->u.c != c2) {
tok->type = TK_CODE_POINT;
tok->u.code = c2;
}
else { /* string */
p = tok->backp + enclen(enc, tok->backp);
}
}
break;
}
}
else {
tok->u.c = c;
tok->escaped = 0;
#ifdef USE_VARIABLE_META_CHARS
if ((c != ONIG_INEFFECTIVE_META_CHAR) &&
IS_SYNTAX_OP(syn, ONIG_SYN_OP_VARIABLE_META_CHARACTERS)) {
if (c == MC_ANYCHAR(syn))
goto any_char;
else if (c == MC_ANYTIME(syn))
goto anytime;
else if (c == MC_ZERO_OR_ONE_TIME(syn))
goto zero_or_one_time;
else if (c == MC_ONE_OR_MORE_TIME(syn))
goto one_or_more_time;
else if (c == MC_ANYCHAR_ANYTIME(syn)) {
tok->type = TK_ANYCHAR_ANYTIME;
goto out;
}
}
#endif
switch (c) {
case '.':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_DOT_ANYCHAR)) break;
#ifdef USE_VARIABLE_META_CHARS
any_char:
#endif
tok->type = TK_ANYCHAR;
break;
case '*':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ASTERISK_ZERO_INF)) break;
#ifdef USE_VARIABLE_META_CHARS
anytime:
#endif
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 0;
tok->u.repeat.upper = REPEAT_INFINITE;
goto greedy_check;
break;
case '+':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_PLUS_ONE_INF)) break;
#ifdef USE_VARIABLE_META_CHARS
one_or_more_time:
#endif
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 1;
tok->u.repeat.upper = REPEAT_INFINITE;
goto greedy_check;
break;
case '?':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_ZERO_ONE)) break;
#ifdef USE_VARIABLE_META_CHARS
zero_or_one_time:
#endif
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 0;
tok->u.repeat.upper = 1;
goto greedy_check;
break;
case '{':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACE_INTERVAL)) break;
r = fetch_range_quantifier(&p, end, tok, env);
if (r < 0) return r; /* error */
if (r == 0) goto greedy_check;
else if (r == 2) { /* {n} */
if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY))
goto possessive_check;
goto greedy_check;
}
/* r == 1 : normal char */
break;
case '|':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_VBAR_ALT)) break;
tok->type = TK_ALT;
break;
case '(':
if (!PEND && PPEEK_IS('?') &&
IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_QMARK_GROUP_EFFECT)) {
PINC;
if (!PEND && PPEEK_IS('#')) {
PFETCH(c);
while (1) {
if (PEND) return ONIGERR_END_PATTERN_IN_GROUP;
PFETCH(c);
if (c == MC_ESC(syn)) {
if (!PEND) PFETCH(c);
}
else {
if (c == ')') break;
}
}
goto start;
}
PUNFETCH;
}
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break;
tok->type = TK_SUBEXP_OPEN;
break;
case ')':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break;
tok->type = TK_SUBEXP_CLOSE;
break;
case '^':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break;
tok->type = TK_ANCHOR;
tok->u.subtype = (IS_SINGLELINE(env->option)
? ANCHOR_BEGIN_BUF : ANCHOR_BEGIN_LINE);
break;
case '$':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break;
tok->type = TK_ANCHOR;
tok->u.subtype = (IS_SINGLELINE(env->option)
? ANCHOR_SEMI_END_BUF : ANCHOR_END_LINE);
break;
case '[':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACKET_CC)) break;
tok->type = TK_CC_OPEN;
break;
case ']':
if (*src > env->pattern) /* /].../ is allowed. */
CLOSE_BRACKET_WITHOUT_ESC_WARN(env, (UChar* )"]");
break;
case '#':
if (IS_EXTEND(env->option)) {
while (!PEND) {
PFETCH(c);
if (ONIGENC_IS_CODE_NEWLINE(enc, c))
break;
}
goto start;
break;
}
break;
case ' ': case '\t': case '\n': case '\r': case '\f':
if (IS_EXTEND(env->option))
goto start;
break;
default:
/* string */
break;
}
}
#ifdef USE_VARIABLE_META_CHARS
out:
#endif
*src = p;
return tok->type;
}
static int
add_ctype_to_cc_by_range(CClassNode* cc, int ctype ARG_UNUSED, int not,
OnigEncoding enc ARG_UNUSED,
OnigCodePoint sb_out, const OnigCodePoint mbr[])
{
int i, r;
OnigCodePoint j;
int n = ONIGENC_CODE_RANGE_NUM(mbr);
if (not == 0) {
for (i = 0; i < n; i++) {
for (j = ONIGENC_CODE_RANGE_FROM(mbr, i);
j <= ONIGENC_CODE_RANGE_TO(mbr, i); j++) {
if (j >= sb_out) {
if (j > ONIGENC_CODE_RANGE_FROM(mbr, i)) {
r = add_code_range_to_buf(&(cc->mbuf), j,
ONIGENC_CODE_RANGE_TO(mbr, i));
if (r != 0) return r;
i++;
}
goto sb_end;
}
BITSET_SET_BIT(cc->bs, j);
}
}
sb_end:
for ( ; i < n; i++) {
r = add_code_range_to_buf(&(cc->mbuf),
ONIGENC_CODE_RANGE_FROM(mbr, i),
ONIGENC_CODE_RANGE_TO(mbr, i));
if (r != 0) return r;
}
}
else {
OnigCodePoint prev = 0;
for (i = 0; i < n; i++) {
for (j = prev;
j < ONIGENC_CODE_RANGE_FROM(mbr, i); j++) {
if (j >= sb_out) {
goto sb_end2;
}
BITSET_SET_BIT(cc->bs, j);
}
prev = ONIGENC_CODE_RANGE_TO(mbr, i) + 1;
}
for (j = prev; j < sb_out; j++) {
BITSET_SET_BIT(cc->bs, j);
}
sb_end2:
prev = sb_out;
for (i = 0; i < n; i++) {
if (prev < ONIGENC_CODE_RANGE_FROM(mbr, i)) {
r = add_code_range_to_buf(&(cc->mbuf), prev,
ONIGENC_CODE_RANGE_FROM(mbr, i) - 1);
if (r != 0) return r;
}
prev = ONIGENC_CODE_RANGE_TO(mbr, i) + 1;
}
if (prev < 0x7fffffff) {
r = add_code_range_to_buf(&(cc->mbuf), prev, 0x7fffffff);
if (r != 0) return r;
}
}
return 0;
}
static int
add_ctype_to_cc(CClassNode* cc, int ctype, int not, ScanEnv* env)
{
int c, r;
const OnigCodePoint *ranges;
OnigCodePoint sb_out;
OnigEncoding enc = env->enc;
r = ONIGENC_GET_CTYPE_CODE_RANGE(enc, ctype, &sb_out, &ranges);
if (r == 0) {
return add_ctype_to_cc_by_range(cc, ctype, not, env->enc, sb_out, ranges);
}
else if (r != ONIG_NO_SUPPORT_CONFIG) {
return r;
}
r = 0;
switch (ctype) {
case ONIGENC_CTYPE_ALPHA:
case ONIGENC_CTYPE_BLANK:
case ONIGENC_CTYPE_CNTRL:
case ONIGENC_CTYPE_DIGIT:
case ONIGENC_CTYPE_LOWER:
case ONIGENC_CTYPE_PUNCT:
case ONIGENC_CTYPE_SPACE:
case ONIGENC_CTYPE_UPPER:
case ONIGENC_CTYPE_XDIGIT:
case ONIGENC_CTYPE_ASCII:
case ONIGENC_CTYPE_ALNUM:
if (not != 0) {
for (c = 0; c < SINGLE_BYTE_SIZE; c++) {
if (! ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype))
BITSET_SET_BIT(cc->bs, c);
}
ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf);
}
else {
for (c = 0; c < SINGLE_BYTE_SIZE; c++) {
if (ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype))
BITSET_SET_BIT(cc->bs, c);
}
}
break;
case ONIGENC_CTYPE_GRAPH:
case ONIGENC_CTYPE_PRINT:
if (not != 0) {
for (c = 0; c < SINGLE_BYTE_SIZE; c++) {
if (! ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype))
BITSET_SET_BIT(cc->bs, c);
}
}
else {
for (c = 0; c < SINGLE_BYTE_SIZE; c++) {
if (ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype))
BITSET_SET_BIT(cc->bs, c);
}
ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf);
}
break;
case ONIGENC_CTYPE_WORD:
if (not == 0) {
for (c = 0; c < SINGLE_BYTE_SIZE; c++) {
if (IS_CODE_SB_WORD(enc, c)) BITSET_SET_BIT(cc->bs, c);
}
ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf);
}
else {
for (c = 0; c < SINGLE_BYTE_SIZE; c++) {
if ((ONIGENC_CODE_TO_MBCLEN(enc, c) > 0) /* check invalid code point */
&& ! ONIGENC_IS_CODE_WORD(enc, c))
BITSET_SET_BIT(cc->bs, c);
}
}
break;
default:
return ONIGERR_PARSER_BUG;
break;
}
return r;
}
static int
parse_posix_bracket(CClassNode* cc, UChar** src, UChar* end, ScanEnv* env)
{
#define POSIX_BRACKET_CHECK_LIMIT_LENGTH 20
#define POSIX_BRACKET_NAME_MIN_LEN 4
static PosixBracketEntryType PBS[] = {
{ (UChar* )"alnum", ONIGENC_CTYPE_ALNUM, 5 },
{ (UChar* )"alpha", ONIGENC_CTYPE_ALPHA, 5 },
{ (UChar* )"blank", ONIGENC_CTYPE_BLANK, 5 },
{ (UChar* )"cntrl", ONIGENC_CTYPE_CNTRL, 5 },
{ (UChar* )"digit", ONIGENC_CTYPE_DIGIT, 5 },
{ (UChar* )"graph", ONIGENC_CTYPE_GRAPH, 5 },
{ (UChar* )"lower", ONIGENC_CTYPE_LOWER, 5 },
{ (UChar* )"print", ONIGENC_CTYPE_PRINT, 5 },
{ (UChar* )"punct", ONIGENC_CTYPE_PUNCT, 5 },
{ (UChar* )"space", ONIGENC_CTYPE_SPACE, 5 },
{ (UChar* )"upper", ONIGENC_CTYPE_UPPER, 5 },
{ (UChar* )"xdigit", ONIGENC_CTYPE_XDIGIT, 6 },
{ (UChar* )"ascii", ONIGENC_CTYPE_ASCII, 5 },
{ (UChar* )"word", ONIGENC_CTYPE_WORD, 4 },
{ (UChar* )NULL, -1, 0 }
};
PosixBracketEntryType *pb;
int not, i, r;
OnigCodePoint c;
OnigEncoding enc = env->enc;
UChar *p = *src;
if (PPEEK_IS('^')) {
PINC_S;
not = 1;
}
else
not = 0;
if (onigenc_strlen(enc, p, end) < POSIX_BRACKET_NAME_MIN_LEN + 3)
goto not_posix_bracket;
for (pb = PBS; IS_NOT_NULL(pb->name); pb++) {
if (onigenc_with_ascii_strncmp(enc, p, end, pb->name, pb->len) == 0) {
p = (UChar* )onigenc_step(enc, p, end, pb->len);
if (onigenc_with_ascii_strncmp(enc, p, end, (UChar* )":]", 2) != 0)
return ONIGERR_INVALID_POSIX_BRACKET_TYPE;
r = add_ctype_to_cc(cc, pb->ctype, not, env);
if (r != 0) return r;
PINC_S; PINC_S;
*src = p;
return 0;
}
}
not_posix_bracket:
c = 0;
i = 0;
while (!PEND && ((c = PPEEK) != ':') && c != ']') {
PINC_S;
if (++i > POSIX_BRACKET_CHECK_LIMIT_LENGTH) break;
}
if (c == ':' && ! PEND) {
PINC_S;
if (! PEND) {
PFETCH_S(c);
if (c == ']')
return ONIGERR_INVALID_POSIX_BRACKET_TYPE;
}
}
return 1; /* 1: is not POSIX bracket, but no error. */
}
static int
fetch_char_property_to_ctype(UChar** src, UChar* end, ScanEnv* env)
{
int r;
OnigCodePoint c;
OnigEncoding enc = env->enc;
UChar *prev, *start, *p = *src;
r = 0;
start = prev = p;
while (!PEND) {
prev = p;
PFETCH_S(c);
if (c == '}') {
r = ONIGENC_PROPERTY_NAME_TO_CTYPE(enc, start, prev);
if (r < 0) break;
*src = p;
return r;
}
else if (c == '(' || c == ')' || c == '{' || c == '|') {
r = ONIGERR_INVALID_CHAR_PROPERTY_NAME;
break;
}
}
onig_scan_env_set_error_string(env, r, *src, prev);
return r;
}
static int
parse_char_property(Node** np, OnigToken* tok, UChar** src, UChar* end,
ScanEnv* env)
{
int r, ctype;
CClassNode* cc;
ctype = fetch_char_property_to_ctype(src, end, env);
if (ctype < 0) return ctype;
*np = node_new_cclass();
CHECK_NULL_RETURN_MEMERR(*np);
cc = NCCLASS(*np);
r = add_ctype_to_cc(cc, ctype, 0, env);
if (r != 0) return r;
if (tok->u.prop.not != 0) NCCLASS_SET_NOT(cc);
return 0;
}
enum CCSTATE {
CCS_VALUE,
CCS_RANGE,
CCS_COMPLETE,
CCS_START
};
enum CCVALTYPE {
CCV_SB,
CCV_CODE_POINT,
CCV_CLASS
};
static int
next_state_class(CClassNode* cc, OnigCodePoint* vs, enum CCVALTYPE* type,
enum CCSTATE* state, ScanEnv* env)
{
int r;
if (*state == CCS_RANGE)
return ONIGERR_CHAR_CLASS_VALUE_AT_END_OF_RANGE;
if (*state == CCS_VALUE && *type != CCV_CLASS) {
if (*type == CCV_SB)
BITSET_SET_BIT(cc->bs, (int )(*vs));
else if (*type == CCV_CODE_POINT) {
r = add_code_range(&(cc->mbuf), env, *vs, *vs);
if (r < 0) return r;
}
}
*state = CCS_VALUE;
*type = CCV_CLASS;
return 0;
}
static int
next_state_val(CClassNode* cc, OnigCodePoint *vs, OnigCodePoint v,
int* vs_israw, int v_israw,
enum CCVALTYPE intype, enum CCVALTYPE* type,
enum CCSTATE* state, ScanEnv* env)
{
int r;
switch (*state) {
case CCS_VALUE:
if (*type == CCV_SB) {
if (*vs > 0xff)
return ONIGERR_INVALID_CODE_POINT_VALUE;
BITSET_SET_BIT(cc->bs, (int )(*vs));
}
else if (*type == CCV_CODE_POINT) {
r = add_code_range(&(cc->mbuf), env, *vs, *vs);
if (r < 0) return r;
}
break;
case CCS_RANGE:
if (intype == *type) {
if (intype == CCV_SB) {
if (*vs > 0xff || v > 0xff)
return ONIGERR_INVALID_CODE_POINT_VALUE;
if (*vs > v) {
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC))
goto ccs_range_end;
else
return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS;
}
bitset_set_range(cc->bs, (int )*vs, (int )v);
}
else {
r = add_code_range(&(cc->mbuf), env, *vs, v);
if (r < 0) return r;
}
}
else {
#if 0
if (intype == CCV_CODE_POINT && *type == CCV_SB) {
#endif
if (*vs > v) {
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC))
goto ccs_range_end;
else
return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS;
}
bitset_set_range(cc->bs, (int )*vs, (int )(v < 0xff ? v : 0xff));
r = add_code_range(&(cc->mbuf), env, (OnigCodePoint )*vs, v);
if (r < 0) return r;
#if 0
}
else
return ONIGERR_MISMATCH_CODE_LENGTH_IN_CLASS_RANGE;
#endif
}
ccs_range_end:
*state = CCS_COMPLETE;
break;
case CCS_COMPLETE:
case CCS_START:
*state = CCS_VALUE;
break;
default:
break;
}
*vs_israw = v_israw;
*vs = v;
*type = intype;
return 0;
}
static int
code_exist_check(OnigCodePoint c, UChar* from, UChar* end, int ignore_escaped,
ScanEnv* env)
{
int in_esc;
OnigCodePoint code;
OnigEncoding enc = env->enc;
UChar* p = from;
in_esc = 0;
while (! PEND) {
if (ignore_escaped && in_esc) {
in_esc = 0;
}
else {
PFETCH_S(code);
if (code == c) return 1;
if (code == MC_ESC(env->syntax)) in_esc = 1;
}
}
return 0;
}
static int
parse_char_class(Node** np, OnigToken* tok, UChar** src, UChar* end,
ScanEnv* env)
{
int r, neg, len, fetched, and_start;
OnigCodePoint v, vs;
UChar *p;
Node* node;
CClassNode *cc, *prev_cc;
CClassNode work_cc;
enum CCSTATE state;
enum CCVALTYPE val_type, in_type;
int val_israw, in_israw;
*np = NULL_NODE;
env->parse_depth++;
if (env->parse_depth > ParseDepthLimit)
return ONIGERR_PARSE_DEPTH_LIMIT_OVER;
prev_cc = (CClassNode* )NULL;
r = fetch_token_in_cc(tok, src, end, env);
if (r == TK_CHAR && tok->u.c == '^' && tok->escaped == 0) {
neg = 1;
r = fetch_token_in_cc(tok, src, end, env);
}
else {
neg = 0;
}
if (r < 0) return r;
if (r == TK_CC_CLOSE) {
if (! code_exist_check((OnigCodePoint )']',
*src, env->pattern_end, 1, env))
return ONIGERR_EMPTY_CHAR_CLASS;
CC_ESC_WARN(env, (UChar* )"]");
r = tok->type = TK_CHAR; /* allow []...] */
}
*np = node = node_new_cclass();
CHECK_NULL_RETURN_MEMERR(node);
cc = NCCLASS(node);
and_start = 0;
state = CCS_START;
p = *src;
while (r != TK_CC_CLOSE) {
fetched = 0;
switch (r) {
case TK_CHAR:
any_char_in:
len = ONIGENC_CODE_TO_MBCLEN(env->enc, tok->u.c);
if (len > 1) {
in_type = CCV_CODE_POINT;
}
else if (len < 0) {
r = len;
goto err;
}
else {
/* sb_char: */
in_type = CCV_SB;
}
v = (OnigCodePoint )tok->u.c;
in_israw = 0;
goto val_entry2;
break;
case TK_RAW_BYTE:
/* tok->base != 0 : octal or hexadec. */
if (! ONIGENC_IS_SINGLEBYTE(env->enc) && tok->base != 0) {
UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN];
UChar* bufe = buf + ONIGENC_CODE_TO_MBC_MAXLEN;
UChar* psave = p;
int i, base = tok->base;
buf[0] = tok->u.c;
for (i = 1; i < ONIGENC_MBC_MAXLEN(env->enc); i++) {
r = fetch_token_in_cc(tok, &p, end, env);
if (r < 0) goto err;
if (r != TK_RAW_BYTE || tok->base != base) {
fetched = 1;
break;
}
buf[i] = tok->u.c;
}
if (i < ONIGENC_MBC_MINLEN(env->enc)) {
r = ONIGERR_TOO_SHORT_MULTI_BYTE_STRING;
goto err;
}
len = enclen(env->enc, buf);
if (i < len) {
r = ONIGERR_TOO_SHORT_MULTI_BYTE_STRING;
goto err;
}
else if (i > len) { /* fetch back */
p = psave;
for (i = 1; i < len; i++) {
r = fetch_token_in_cc(tok, &p, end, env);
}
fetched = 0;
}
if (i == 1) {
v = (OnigCodePoint )buf[0];
goto raw_single;
}
else {
v = ONIGENC_MBC_TO_CODE(env->enc, buf, bufe);
in_type = CCV_CODE_POINT;
}
}
else {
v = (OnigCodePoint )tok->u.c;
raw_single:
in_type = CCV_SB;
}
in_israw = 1;
goto val_entry2;
break;
case TK_CODE_POINT:
v = tok->u.code;
in_israw = 1;
val_entry:
len = ONIGENC_CODE_TO_MBCLEN(env->enc, v);
if (len < 0) {
r = len;
goto err;
}
in_type = (len == 1 ? CCV_SB : CCV_CODE_POINT);
val_entry2:
r = next_state_val(cc, &vs, v, &val_israw, in_israw, in_type, &val_type,
&state, env);
if (r != 0) goto err;
break;
case TK_POSIX_BRACKET_OPEN:
r = parse_posix_bracket(cc, &p, end, env);
if (r < 0) goto err;
if (r == 1) { /* is not POSIX bracket */
CC_ESC_WARN(env, (UChar* )"[");
p = tok->backp;
v = (OnigCodePoint )tok->u.c;
in_israw = 0;
goto val_entry;
}
goto next_class;
break;
case TK_CHAR_TYPE:
r = add_ctype_to_cc(cc, tok->u.prop.ctype, tok->u.prop.not, env);
if (r != 0) return r;
next_class:
r = next_state_class(cc, &vs, &val_type, &state, env);
if (r != 0) goto err;
break;
case TK_CHAR_PROPERTY:
{
int ctype;
ctype = fetch_char_property_to_ctype(&p, end, env);
if (ctype < 0) return ctype;
r = add_ctype_to_cc(cc, ctype, tok->u.prop.not, env);
if (r != 0) return r;
goto next_class;
}
break;
case TK_CC_RANGE:
if (state == CCS_VALUE) {
r = fetch_token_in_cc(tok, &p, end, env);
if (r < 0) goto err;
fetched = 1;
if (r == TK_CC_CLOSE) { /* allow [x-] */
range_end_val:
v = (OnigCodePoint )'-';
in_israw = 0;
goto val_entry;
}
else if (r == TK_CC_AND) {
CC_ESC_WARN(env, (UChar* )"-");
goto range_end_val;
}
state = CCS_RANGE;
}
else if (state == CCS_START) {
/* [-xa] is allowed */
v = (OnigCodePoint )tok->u.c;
in_israw = 0;
r = fetch_token_in_cc(tok, &p, end, env);
if (r < 0) goto err;
fetched = 1;
/* [--x] or [a&&-x] is warned. */
if (r == TK_CC_RANGE || and_start != 0)
CC_ESC_WARN(env, (UChar* )"-");
goto val_entry;
}
else if (state == CCS_RANGE) {
CC_ESC_WARN(env, (UChar* )"-");
goto any_char_in; /* [!--x] is allowed */
}
else { /* CCS_COMPLETE */
r = fetch_token_in_cc(tok, &p, end, env);
if (r < 0) goto err;
fetched = 1;
if (r == TK_CC_CLOSE) goto range_end_val; /* allow [a-b-] */
else if (r == TK_CC_AND) {
CC_ESC_WARN(env, (UChar* )"-");
goto range_end_val;
}
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_DOUBLE_RANGE_OP_IN_CC)) {
CC_ESC_WARN(env, (UChar* )"-");
goto range_end_val; /* [0-9-a] is allowed as [0-9\-a] */
}
r = ONIGERR_UNMATCHED_RANGE_SPECIFIER_IN_CHAR_CLASS;
goto err;
}
break;
case TK_CC_CC_OPEN: /* [ */
{
Node *anode;
CClassNode* acc;
r = parse_char_class(&anode, tok, &p, end, env);
if (r != 0) {
onig_node_free(anode);
goto cc_open_err;
}
acc = NCCLASS(anode);
r = or_cclass(cc, acc, env->enc);
onig_node_free(anode);
cc_open_err:
if (r != 0) goto err;
}
break;
case TK_CC_AND: /* && */
{
if (state == CCS_VALUE) {
r = next_state_val(cc, &vs, 0, &val_israw, 0, val_type,
&val_type, &state, env);
if (r != 0) goto err;
}
/* initialize local variables */
and_start = 1;
state = CCS_START;
if (IS_NOT_NULL(prev_cc)) {
r = and_cclass(prev_cc, cc, env->enc);
if (r != 0) goto err;
bbuf_free(cc->mbuf);
}
else {
prev_cc = cc;
cc = &work_cc;
}
initialize_cclass(cc);
}
break;
case TK_EOT:
r = ONIGERR_PREMATURE_END_OF_CHAR_CLASS;
goto err;
break;
default:
r = ONIGERR_PARSER_BUG;
goto err;
break;
}
if (fetched)
r = tok->type;
else {
r = fetch_token_in_cc(tok, &p, end, env);
if (r < 0) goto err;
}
}
if (state == CCS_VALUE) {
r = next_state_val(cc, &vs, 0, &val_israw, 0, val_type,
&val_type, &state, env);
if (r != 0) goto err;
}
if (IS_NOT_NULL(prev_cc)) {
r = and_cclass(prev_cc, cc, env->enc);
if (r != 0) goto err;
bbuf_free(cc->mbuf);
cc = prev_cc;
}
if (neg != 0)
NCCLASS_SET_NOT(cc);
else
NCCLASS_CLEAR_NOT(cc);
if (IS_NCCLASS_NOT(cc) &&
IS_SYNTAX_BV(env->syntax, ONIG_SYN_NOT_NEWLINE_IN_NEGATIVE_CC)) {
int is_empty;
is_empty = (IS_NULL(cc->mbuf) ? 1 : 0);
if (is_empty != 0)
BITSET_IS_EMPTY(cc->bs, is_empty);
if (is_empty == 0) {
#define NEWLINE_CODE 0x0a
if (ONIGENC_IS_CODE_NEWLINE(env->enc, NEWLINE_CODE)) {
if (ONIGENC_CODE_TO_MBCLEN(env->enc, NEWLINE_CODE) == 1)
BITSET_SET_BIT(cc->bs, NEWLINE_CODE);
else
add_code_range(&(cc->mbuf), env, NEWLINE_CODE, NEWLINE_CODE);
}
}
}
*src = p;
env->parse_depth--;
return 0;
err:
if (cc != NCCLASS(*np))
bbuf_free(cc->mbuf);
return r;
}
static int parse_subexp(Node** top, OnigToken* tok, int term,
UChar** src, UChar* end, ScanEnv* env);
static int
parse_enclose(Node** np, OnigToken* tok, int term, UChar** src, UChar* end,
ScanEnv* env)
{
int r, num;
Node *target;
OnigOptionType option;
OnigCodePoint c;
OnigEncoding enc = env->enc;
#ifdef USE_NAMED_GROUP
int list_capture;
#endif
UChar* p = *src;
PFETCH_READY;
*np = NULL;
if (PEND) return ONIGERR_END_PATTERN_WITH_UNMATCHED_PARENTHESIS;
option = env->option;
if (PPEEK_IS('?') &&
IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_GROUP_EFFECT)) {
PINC;
if (PEND) return ONIGERR_END_PATTERN_IN_GROUP;
PFETCH(c);
switch (c) {
case ':': /* (?:...) grouping only */
group:
r = fetch_token(tok, &p, end, env);
if (r < 0) return r;
r = parse_subexp(np, tok, term, &p, end, env);
if (r < 0) return r;
*src = p;
return 1; /* group */
break;
case '=':
*np = onig_node_new_anchor(ANCHOR_PREC_READ);
break;
case '!': /* preceding read */
*np = onig_node_new_anchor(ANCHOR_PREC_READ_NOT);
break;
case '>': /* (?>...) stop backtrack */
*np = node_new_enclose(ENCLOSE_STOP_BACKTRACK);
break;
#ifdef USE_NAMED_GROUP
case '\'':
if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) {
goto named_group1;
}
else
return ONIGERR_UNDEFINED_GROUP_OPTION;
break;
#endif
case '<': /* look behind (?<=...), (?<!...) */
if (PEND) return ONIGERR_END_PATTERN_WITH_UNMATCHED_PARENTHESIS;
PFETCH(c);
if (c == '=')
*np = onig_node_new_anchor(ANCHOR_LOOK_BEHIND);
else if (c == '!')
*np = onig_node_new_anchor(ANCHOR_LOOK_BEHIND_NOT);
#ifdef USE_NAMED_GROUP
else {
if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) {
UChar *name;
UChar *name_end;
PUNFETCH;
c = '<';
named_group1:
list_capture = 0;
named_group2:
name = p;
r = fetch_name((OnigCodePoint )c, &p, end, &name_end, env, &num, 0);
if (r < 0) return r;
num = scan_env_add_mem_entry(env);
if (num < 0) return num;
if (list_capture != 0 && num >= (int )BIT_STATUS_BITS_NUM)
return ONIGERR_GROUP_NUMBER_OVER_FOR_CAPTURE_HISTORY;
r = name_add(env->reg, name, name_end, num, env);
if (r != 0) return r;
*np = node_new_enclose_memory(env->option, 1);
CHECK_NULL_RETURN_MEMERR(*np);
NENCLOSE(*np)->regnum = num;
if (list_capture != 0)
BIT_STATUS_ON_AT_SIMPLE(env->capture_history, num);
env->num_named++;
}
else {
return ONIGERR_UNDEFINED_GROUP_OPTION;
}
}
#else
else {
return ONIGERR_UNDEFINED_GROUP_OPTION;
}
#endif
break;
case '@':
if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ATMARK_CAPTURE_HISTORY)) {
#ifdef USE_NAMED_GROUP
if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) {
PFETCH(c);
if (c == '<' || c == '\'') {
list_capture = 1;
goto named_group2; /* (?@<name>...) */
}
PUNFETCH;
}
#endif
*np = node_new_enclose_memory(env->option, 0);
CHECK_NULL_RETURN_MEMERR(*np);
num = scan_env_add_mem_entry(env);
if (num < 0) {
return num;
}
else if (num >= (int )BIT_STATUS_BITS_NUM) {
return ONIGERR_GROUP_NUMBER_OVER_FOR_CAPTURE_HISTORY;
}
NENCLOSE(*np)->regnum = num;
BIT_STATUS_ON_AT_SIMPLE(env->capture_history, num);
}
else {
return ONIGERR_UNDEFINED_GROUP_OPTION;
}
break;
#ifdef USE_POSIXLINE_OPTION
case 'p':
#endif
case '-': case 'i': case 'm': case 's': case 'x':
{
int neg = 0;
while (1) {
switch (c) {
case ':':
case ')':
break;
case '-': neg = 1; break;
case 'x': ONOFF(option, ONIG_OPTION_EXTEND, neg); break;
case 'i': ONOFF(option, ONIG_OPTION_IGNORECASE, neg); break;
case 's':
if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_PERL)) {
ONOFF(option, ONIG_OPTION_MULTILINE, neg);
}
else
return ONIGERR_UNDEFINED_GROUP_OPTION;
break;
case 'm':
if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_PERL)) {
ONOFF(option, ONIG_OPTION_SINGLELINE, (neg == 0 ? 1 : 0));
}
else if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_RUBY)) {
ONOFF(option, ONIG_OPTION_MULTILINE, neg);
}
else
return ONIGERR_UNDEFINED_GROUP_OPTION;
break;
#ifdef USE_POSIXLINE_OPTION
case 'p':
ONOFF(option, ONIG_OPTION_MULTILINE|ONIG_OPTION_SINGLELINE, neg);
break;
#endif
default:
return ONIGERR_UNDEFINED_GROUP_OPTION;
}
if (c == ')') {
*np = node_new_option(option);
CHECK_NULL_RETURN_MEMERR(*np);
*src = p;
return 2; /* option only */
}
else if (c == ':') {
OnigOptionType prev = env->option;
env->option = option;
r = fetch_token(tok, &p, end, env);
if (r < 0) return r;
r = parse_subexp(&target, tok, term, &p, end, env);
env->option = prev;
if (r < 0) {
onig_node_free(target);
return r;
}
*np = node_new_option(option);
CHECK_NULL_RETURN_MEMERR(*np);
NENCLOSE(*np)->target = target;
*src = p;
return 0;
}
if (PEND) return ONIGERR_END_PATTERN_IN_GROUP;
PFETCH(c);
}
}
break;
default:
return ONIGERR_UNDEFINED_GROUP_OPTION;
}
}
else {
if (ONIG_IS_OPTION_ON(env->option, ONIG_OPTION_DONT_CAPTURE_GROUP))
goto group;
*np = node_new_enclose_memory(env->option, 0);
CHECK_NULL_RETURN_MEMERR(*np);
num = scan_env_add_mem_entry(env);
if (num < 0) return num;
NENCLOSE(*np)->regnum = num;
}
CHECK_NULL_RETURN_MEMERR(*np);
r = fetch_token(tok, &p, end, env);
if (r < 0) return r;
r = parse_subexp(&target, tok, term, &p, end, env);
if (r < 0) {
onig_node_free(target);
return r;
}
if (NTYPE(*np) == NT_ANCHOR)
NANCHOR(*np)->target = target;
else {
NENCLOSE(*np)->target = target;
if (NENCLOSE(*np)->type == ENCLOSE_MEMORY) {
/* Don't move this to previous of parse_subexp() */
r = scan_env_set_mem_node(env, NENCLOSE(*np)->regnum, *np);
if (r != 0) return r;
}
}
*src = p;
return 0;
}
static const char* PopularQStr[] = {
"?", "*", "+", "??", "*?", "+?"
};
static const char* ReduceQStr[] = {
"", "", "*", "*?", "??", "+ and ??", "+? and ?"
};
static int
set_quantifier(Node* qnode, Node* target, int group, ScanEnv* env)
{
QtfrNode* qn;
qn = NQTFR(qnode);
if (qn->lower == 1 && qn->upper == 1) {
return 1;
}
switch (NTYPE(target)) {
case NT_STR:
if (! group) {
StrNode* sn = NSTR(target);
if (str_node_can_be_split(sn, env->enc)) {
Node* n = str_node_split_last_char(sn, env->enc);
if (IS_NOT_NULL(n)) {
qn->target = n;
return 2;
}
}
}
break;
case NT_QTFR:
{ /* check redundant double repeat. */
/* verbose warn (?:.?)? etc... but not warn (.?)? etc... */
QtfrNode* qnt = NQTFR(target);
int nestq_num = popular_quantifier_num(qn);
int targetq_num = popular_quantifier_num(qnt);
#ifdef USE_WARNING_REDUNDANT_NESTED_REPEAT_OPERATOR
if (!IS_QUANTIFIER_BY_NUMBER(qn) && !IS_QUANTIFIER_BY_NUMBER(qnt) &&
IS_SYNTAX_BV(env->syntax, ONIG_SYN_WARN_REDUNDANT_NESTED_REPEAT)) {
UChar buf[WARN_BUFSIZE];
switch(ReduceTypeTable[targetq_num][nestq_num]) {
case RQ_ASIS:
break;
case RQ_DEL:
if (onig_verb_warn != onig_null_warn) {
onig_snprintf_with_pattern(buf, WARN_BUFSIZE, env->enc,
env->pattern, env->pattern_end,
(UChar* )"redundant nested repeat operator");
(*onig_verb_warn)((char* )buf);
}
goto warn_exit;
break;
default:
if (onig_verb_warn != onig_null_warn) {
onig_snprintf_with_pattern(buf, WARN_BUFSIZE, env->enc,
env->pattern, env->pattern_end,
(UChar* )"nested repeat operator %s and %s was replaced with '%s'",
PopularQStr[targetq_num], PopularQStr[nestq_num],
ReduceQStr[ReduceTypeTable[targetq_num][nestq_num]]);
(*onig_verb_warn)((char* )buf);
}
goto warn_exit;
break;
}
}
warn_exit:
#endif
if (targetq_num >= 0) {
if (nestq_num >= 0) {
onig_reduce_nested_quantifier(qnode, target);
goto q_exit;
}
else if (targetq_num == 1 || targetq_num == 2) { /* * or + */
/* (?:a*){n,m}, (?:a+){n,m} => (?:a*){n,n}, (?:a+){n,n} */
if (! IS_REPEAT_INFINITE(qn->upper) && qn->upper > 1 && qn->greedy) {
qn->upper = (qn->lower == 0 ? 1 : qn->lower);
}
}
}
}
break;
default:
break;
}
qn->target = target;
q_exit:
return 0;
}
#ifndef CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS
static int
clear_not_flag_cclass(CClassNode* cc, OnigEncoding enc)
{
BBuf *tbuf;
int r;
if (IS_NCCLASS_NOT(cc)) {
bitset_invert(cc->bs);
if (! ONIGENC_IS_SINGLEBYTE(enc)) {
r = not_code_range_buf(enc, cc->mbuf, &tbuf);
if (r != 0) return r;
bbuf_free(cc->mbuf);
cc->mbuf = tbuf;
}
NCCLASS_CLEAR_NOT(cc);
}
return 0;
}
#endif /* CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS */
typedef struct {
ScanEnv* env;
CClassNode* cc;
Node* alt_root;
Node** ptail;
} IApplyCaseFoldArg;
static int
i_apply_case_fold(OnigCodePoint from, OnigCodePoint to[],
int to_len, void* arg)
{
IApplyCaseFoldArg* iarg;
ScanEnv* env;
CClassNode* cc;
BitSetRef bs;
iarg = (IApplyCaseFoldArg* )arg;
env = iarg->env;
cc = iarg->cc;
bs = cc->bs;
if (to_len == 1) {
int is_in = onig_is_code_in_cc(env->enc, from, cc);
#ifdef CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS
if ((is_in != 0 && !IS_NCCLASS_NOT(cc)) ||
(is_in == 0 && IS_NCCLASS_NOT(cc))) {
if (ONIGENC_MBC_MINLEN(env->enc) > 1 || *to >= SINGLE_BYTE_SIZE) {
add_code_range(&(cc->mbuf), env, *to, *to);
}
else {
BITSET_SET_BIT(bs, *to);
}
}
#else
if (is_in != 0) {
if (ONIGENC_MBC_MINLEN(env->enc) > 1 || *to >= SINGLE_BYTE_SIZE) {
if (IS_NCCLASS_NOT(cc)) clear_not_flag_cclass(cc, env->enc);
add_code_range(&(cc->mbuf), env, *to, *to);
}
else {
if (IS_NCCLASS_NOT(cc)) {
BITSET_CLEAR_BIT(bs, *to);
}
else
BITSET_SET_BIT(bs, *to);
}
}
#endif /* CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS */
}
else {
int r, i, len;
UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN];
Node *snode = NULL_NODE;
if (onig_is_code_in_cc(env->enc, from, cc)
#ifdef CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS
&& !IS_NCCLASS_NOT(cc)
#endif
) {
for (i = 0; i < to_len; i++) {
len = ONIGENC_CODE_TO_MBC(env->enc, to[i], buf);
if (i == 0) {
snode = onig_node_new_str(buf, buf + len);
CHECK_NULL_RETURN_MEMERR(snode);
/* char-class expanded multi-char only
compare with string folded at match time. */
NSTRING_SET_AMBIG(snode);
}
else {
r = onig_node_str_cat(snode, buf, buf + len);
if (r < 0) {
onig_node_free(snode);
return r;
}
}
}
*(iarg->ptail) = onig_node_new_alt(snode, NULL_NODE);
CHECK_NULL_RETURN_MEMERR(*(iarg->ptail));
iarg->ptail = &(NCDR((*(iarg->ptail))));
}
}
return 0;
}
static int
parse_exp(Node** np, OnigToken* tok, int term,
UChar** src, UChar* end, ScanEnv* env)
{
int r, len, group = 0;
Node* qn;
Node** targetp;
*np = NULL;
if (tok->type == (enum TokenSyms )term)
goto end_of_token;
switch (tok->type) {
case TK_ALT:
case TK_EOT:
end_of_token:
*np = node_new_empty();
return tok->type;
break;
case TK_SUBEXP_OPEN:
r = parse_enclose(np, tok, TK_SUBEXP_CLOSE, src, end, env);
if (r < 0) return r;
if (r == 1) group = 1;
else if (r == 2) { /* option only */
Node* target;
OnigOptionType prev = env->option;
env->option = NENCLOSE(*np)->option;
r = fetch_token(tok, src, end, env);
if (r < 0) return r;
r = parse_subexp(&target, tok, term, src, end, env);
env->option = prev;
if (r < 0) {
onig_node_free(target);
return r;
}
NENCLOSE(*np)->target = target;
return tok->type;
}
break;
case TK_SUBEXP_CLOSE:
if (! IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_UNMATCHED_CLOSE_SUBEXP))
return ONIGERR_UNMATCHED_CLOSE_PARENTHESIS;
if (tok->escaped) goto tk_raw_byte;
else goto tk_byte;
break;
case TK_STRING:
tk_byte:
{
*np = node_new_str(tok->backp, *src);
CHECK_NULL_RETURN_MEMERR(*np);
while (1) {
r = fetch_token(tok, src, end, env);
if (r < 0) return r;
if (r != TK_STRING) break;
r = onig_node_str_cat(*np, tok->backp, *src);
if (r < 0) return r;
}
string_end:
targetp = np;
goto repeat;
}
break;
case TK_RAW_BYTE:
tk_raw_byte:
{
*np = node_new_str_raw_char((UChar )tok->u.c);
CHECK_NULL_RETURN_MEMERR(*np);
len = 1;
while (1) {
if (len >= ONIGENC_MBC_MINLEN(env->enc)) {
if (len == enclen(env->enc, NSTR(*np)->s)) {//should not enclen_end()
r = fetch_token(tok, src, end, env);
NSTRING_CLEAR_RAW(*np);
goto string_end;
}
}
r = fetch_token(tok, src, end, env);
if (r < 0) return r;
if (r != TK_RAW_BYTE) {
/* Don't use this, it is wrong for little endian encodings. */
#ifdef USE_PAD_TO_SHORT_BYTE_CHAR
int rem;
if (len < ONIGENC_MBC_MINLEN(env->enc)) {
rem = ONIGENC_MBC_MINLEN(env->enc) - len;
(void )node_str_head_pad(NSTR(*np), rem, (UChar )0);
if (len + rem == enclen(env->enc, NSTR(*np)->s)) {
NSTRING_CLEAR_RAW(*np);
goto string_end;
}
}
#endif
return ONIGERR_TOO_SHORT_MULTI_BYTE_STRING;
}
r = node_str_cat_char(*np, (UChar )tok->u.c);
if (r < 0) return r;
len++;
}
}
break;
case TK_CODE_POINT:
{
UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN];
int num = ONIGENC_CODE_TO_MBC(env->enc, tok->u.code, buf);
if (num < 0) return num;
#ifdef NUMBERED_CHAR_IS_NOT_CASE_AMBIG
*np = node_new_str_raw(buf, buf + num);
#else
*np = node_new_str(buf, buf + num);
#endif
CHECK_NULL_RETURN_MEMERR(*np);
}
break;
case TK_QUOTE_OPEN:
{
OnigCodePoint end_op[2];
UChar *qstart, *qend, *nextp;
end_op[0] = (OnigCodePoint )MC_ESC(env->syntax);
end_op[1] = (OnigCodePoint )'E';
qstart = *src;
qend = find_str_position(end_op, 2, qstart, end, &nextp, env->enc);
if (IS_NULL(qend)) {
nextp = qend = end;
}
*np = node_new_str(qstart, qend);
CHECK_NULL_RETURN_MEMERR(*np);
*src = nextp;
}
break;
case TK_CHAR_TYPE:
{
switch (tok->u.prop.ctype) {
case ONIGENC_CTYPE_WORD:
*np = node_new_ctype(tok->u.prop.ctype, tok->u.prop.not);
CHECK_NULL_RETURN_MEMERR(*np);
break;
case ONIGENC_CTYPE_SPACE:
case ONIGENC_CTYPE_DIGIT:
case ONIGENC_CTYPE_XDIGIT:
{
CClassNode* cc;
*np = node_new_cclass();
CHECK_NULL_RETURN_MEMERR(*np);
cc = NCCLASS(*np);
add_ctype_to_cc(cc, tok->u.prop.ctype, 0, env);
if (tok->u.prop.not != 0) NCCLASS_SET_NOT(cc);
}
break;
default:
return ONIGERR_PARSER_BUG;
break;
}
}
break;
case TK_CHAR_PROPERTY:
r = parse_char_property(np, tok, src, end, env);
if (r != 0) return r;
break;
case TK_CC_OPEN:
{
CClassNode* cc;
r = parse_char_class(np, tok, src, end, env);
if (r != 0) return r;
cc = NCCLASS(*np);
if (IS_IGNORECASE(env->option)) {
IApplyCaseFoldArg iarg;
iarg.env = env;
iarg.cc = cc;
iarg.alt_root = NULL_NODE;
iarg.ptail = &(iarg.alt_root);
r = ONIGENC_APPLY_ALL_CASE_FOLD(env->enc, env->case_fold_flag,
i_apply_case_fold, &iarg);
if (r != 0) {
onig_node_free(iarg.alt_root);
return r;
}
if (IS_NOT_NULL(iarg.alt_root)) {
Node* work = onig_node_new_alt(*np, iarg.alt_root);
if (IS_NULL(work)) {
onig_node_free(iarg.alt_root);
return ONIGERR_MEMORY;
}
*np = work;
}
}
}
break;
case TK_ANYCHAR:
*np = node_new_anychar();
CHECK_NULL_RETURN_MEMERR(*np);
break;
case TK_ANYCHAR_ANYTIME:
*np = node_new_anychar();
CHECK_NULL_RETURN_MEMERR(*np);
qn = node_new_quantifier(0, REPEAT_INFINITE, 0);
CHECK_NULL_RETURN_MEMERR(qn);
NQTFR(qn)->target = *np;
*np = qn;
break;
case TK_BACKREF:
len = tok->u.backref.num;
*np = node_new_backref(len,
(len > 1 ? tok->u.backref.refs : &(tok->u.backref.ref1)),
tok->u.backref.by_name,
#ifdef USE_BACKREF_WITH_LEVEL
tok->u.backref.exist_level,
tok->u.backref.level,
#endif
env);
CHECK_NULL_RETURN_MEMERR(*np);
break;
#ifdef USE_SUBEXP_CALL
case TK_CALL:
{
int gnum = tok->u.call.gnum;
if (gnum < 0) {
gnum = BACKREF_REL_TO_ABS(gnum, env);
if (gnum <= 0)
return ONIGERR_INVALID_BACKREF;
}
*np = node_new_call(tok->u.call.name, tok->u.call.name_end, gnum);
CHECK_NULL_RETURN_MEMERR(*np);
env->num_call++;
}
break;
#endif
case TK_ANCHOR:
*np = onig_node_new_anchor(tok->u.anchor);
break;
case TK_OP_REPEAT:
case TK_INTERVAL:
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_CONTEXT_INDEP_REPEAT_OPS)) {
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_CONTEXT_INVALID_REPEAT_OPS))
return ONIGERR_TARGET_OF_REPEAT_OPERATOR_NOT_SPECIFIED;
else
*np = node_new_empty();
}
else {
goto tk_byte;
}
break;
default:
return ONIGERR_PARSER_BUG;
break;
}
{
targetp = np;
re_entry:
r = fetch_token(tok, src, end, env);
if (r < 0) return r;
repeat:
if (r == TK_OP_REPEAT || r == TK_INTERVAL) {
if (is_invalid_quantifier_target(*targetp))
return ONIGERR_TARGET_OF_REPEAT_OPERATOR_INVALID;
qn = node_new_quantifier(tok->u.repeat.lower, tok->u.repeat.upper,
(r == TK_INTERVAL ? 1 : 0));
CHECK_NULL_RETURN_MEMERR(qn);
NQTFR(qn)->greedy = tok->u.repeat.greedy;
r = set_quantifier(qn, *targetp, group, env);
if (r < 0) {
onig_node_free(qn);
return r;
}
if (tok->u.repeat.possessive != 0) {
Node* en;
en = node_new_enclose(ENCLOSE_STOP_BACKTRACK);
if (IS_NULL(en)) {
onig_node_free(qn);
return ONIGERR_MEMORY;
}
NENCLOSE(en)->target = qn;
qn = en;
}
if (r == 0) {
*targetp = qn;
}
else if (r == 1) {
onig_node_free(qn);
}
else if (r == 2) { /* split case: /abc+/ */
Node *tmp;
*targetp = node_new_list(*targetp, NULL);
if (IS_NULL(*targetp)) {
onig_node_free(qn);
return ONIGERR_MEMORY;
}
tmp = NCDR(*targetp) = node_new_list(qn, NULL);
if (IS_NULL(tmp)) {
onig_node_free(qn);
return ONIGERR_MEMORY;
}
targetp = &(NCAR(tmp));
}
goto re_entry;
}
}
return r;
}
static int
parse_branch(Node** top, OnigToken* tok, int term,
UChar** src, UChar* end, ScanEnv* env)
{
int r;
Node *node, **headp;
*top = NULL;
r = parse_exp(&node, tok, term, src, end, env);
if (r < 0) {
onig_node_free(node);
return r;
}
if (r == TK_EOT || r == term || r == TK_ALT) {
*top = node;
}
else {
*top = node_new_list(node, NULL);
headp = &(NCDR(*top));
while (r != TK_EOT && r != term && r != TK_ALT) {
r = parse_exp(&node, tok, term, src, end, env);
if (r < 0) {
onig_node_free(node);
return r;
}
if (NTYPE(node) == NT_LIST) {
*headp = node;
while (IS_NOT_NULL(NCDR(node))) node = NCDR(node);
headp = &(NCDR(node));
}
else {
*headp = node_new_list(node, NULL);
headp = &(NCDR(*headp));
}
}
}
return r;
}
/* term_tok: TK_EOT or TK_SUBEXP_CLOSE */
static int
parse_subexp(Node** top, OnigToken* tok, int term,
UChar** src, UChar* end, ScanEnv* env)
{
int r;
Node *node, **headp;
*top = NULL;
env->parse_depth++;
if (env->parse_depth > ParseDepthLimit)
return ONIGERR_PARSE_DEPTH_LIMIT_OVER;
r = parse_branch(&node, tok, term, src, end, env);
if (r < 0) {
onig_node_free(node);
return r;
}
if (r == term) {
*top = node;
}
else if (r == TK_ALT) {
*top = onig_node_new_alt(node, NULL);
headp = &(NCDR(*top));
while (r == TK_ALT) {
r = fetch_token(tok, src, end, env);
if (r < 0) return r;
r = parse_branch(&node, tok, term, src, end, env);
if (r < 0) {
onig_node_free(node);
return r;
}
*headp = onig_node_new_alt(node, NULL);
headp = &(NCDR(*headp));
}
if (tok->type != (enum TokenSyms )term)
goto err;
}
else {
onig_node_free(node);
err:
if (term == TK_SUBEXP_CLOSE)
return ONIGERR_END_PATTERN_WITH_UNMATCHED_PARENTHESIS;
else
return ONIGERR_PARSER_BUG;
}
env->parse_depth--;
return r;
}
static int
parse_regexp(Node** top, UChar** src, UChar* end, ScanEnv* env)
{
int r;
OnigToken tok;
r = fetch_token(&tok, src, end, env);
if (r < 0) return r;
r = parse_subexp(top, &tok, TK_EOT, src, end, env);
if (r < 0) return r;
return 0;
}
extern int
onig_parse_make_tree(Node** root, const UChar* pattern, const UChar* end,
regex_t* reg, ScanEnv* env)
{
int r;
UChar* p;
#ifdef USE_NAMED_GROUP
names_clear(reg);
#endif
scan_env_clear(env);
env->option = reg->options;
env->case_fold_flag = reg->case_fold_flag;
env->enc = reg->enc;
env->syntax = reg->syntax;
env->pattern = (UChar* )pattern;
env->pattern_end = (UChar* )end;
env->reg = reg;
*root = NULL;
if (! ONIGENC_IS_VALID_MBC_STRING(env->enc, pattern, end))
return ONIGERR_INVALID_WIDE_CHAR_VALUE;
p = (UChar* )pattern;
r = parse_regexp(root, &p, (UChar* )end, env);
reg->num_mem = env->num_mem;
return r;
}
extern void
onig_scan_env_set_error_string(ScanEnv* env, int ecode ARG_UNUSED,
UChar* arg, UChar* arg_end)
{
env->error = arg;
env->error_end = arg_end;
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_3375_0 |
crossvul-cpp_data_bad_4401_0 | /*
* PKCS15 emulation layer for Oberthur card.
*
* Copyright (C) 2010, Viktor Tarasov <vtarasov@opentrust.com>
* Copyright (C) 2005, Andrea Frigido <andrea@frisoft.it>
* Copyright (C) 2005, Sirio Capizzi <graaf@virgilio.it>
* Copyright (C) 2004, Antonino Iacono <ant_iacono@tin.it>
* Copyright (C) 2003, Olaf Kirch <okir@suse.de>
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "../common/compat_strlcpy.h"
#include "pkcs15.h"
#include "log.h"
#include "asn1.h"
#include "internal.h"
#ifdef ENABLE_OPENSSL
#include <openssl/bio.h>
#include <openssl/crypto.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#endif
#define OBERTHUR_ATTR_MODIFIABLE 0x0001
#define OBERTHUR_ATTR_TRUSTED 0x0002
#define OBERTHUR_ATTR_LOCAL 0x0004
#define OBERTHUR_ATTR_ENCRYPT 0x0008
#define OBERTHUR_ATTR_DECRYPT 0x0010
#define OBERTHUR_ATTR_SIGN 0x0020
#define OBERTHUR_ATTR_VERIFY 0x0040
#define OBERTHUR_ATTR_RSIGN 0x0080
#define OBERTHUR_ATTR_RVERIFY 0x0100
#define OBERTHUR_ATTR_WRAP 0x0200
#define OBERTHUR_ATTR_UNWRAP 0x0400
#define OBERTHUR_ATTR_DERIVE 0x0800
#define USAGE_PRV_ENC (SC_PKCS15_PRKEY_USAGE_ENCRYPT | SC_PKCS15_PRKEY_USAGE_DECRYPT |\
SC_PKCS15_PRKEY_USAGE_WRAP | SC_PKCS15_PRKEY_USAGE_UNWRAP)
#define USAGE_PRV_AUT SC_PKCS15_PRKEY_USAGE_SIGN
#define USAGE_PRV_SIGN (SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_NONREPUDIATION)
#define USAGE_PUB_ENC (SC_PKCS15_PRKEY_USAGE_ENCRYPT | SC_PKCS15_PRKEY_USAGE_WRAP)
#define USAGE_PUB_AUT SC_PKCS15_PRKEY_USAGE_VERIFY
#define USAGE_PUB_SIGN (SC_PKCS15_PRKEY_USAGE_VERIFY | SC_PKCS15_PRKEY_USAGE_VERIFYRECOVER)
#define PIN_DOMAIN_LABEL "SCM"
const unsigned char PinDomainID[3] = {0x53, 0x43, 0x4D};
#define AWP_PIN_DF "3F005011"
#define AWP_TOKEN_INFO "3F0050111000"
#define AWP_PUK_FILE "3F0050112000"
#define AWP_CONTAINERS_MS "3F0050113000"
#define AWP_OBJECTS_LIST_PUB "3F0050114000"
#define AWP_OBJECTS_LIST_PRV "3F0050115000"
#define AWP_OBJECTS_DF_PUB "3F0050119001"
#define AWP_OBJECTS_DF_PRV "3F0050119002"
#define AWP_BASE_RSA_PRV "3F00501190023000"
#define AWP_BASE_RSA_PUB "3F00501190011000"
#define AWP_BASE_CERTIFICATE "3F00501190012000"
#define BASE_ID_PUB_RSA 0x10
#define BASE_ID_CERT 0x20
#define BASE_ID_PRV_RSA 0x30
#define BASE_ID_PRV_DES 0x40
#define BASE_ID_PUB_DATA 0x50
#define BASE_ID_PRV_DATA 0x60
#define BASE_ID_PUB_DES 0x70
static int sc_pkcs15emu_oberthur_add_prvkey(struct sc_pkcs15_card *, unsigned, unsigned);
static int sc_pkcs15emu_oberthur_add_pubkey(struct sc_pkcs15_card *, unsigned, unsigned);
static int sc_pkcs15emu_oberthur_add_cert(struct sc_pkcs15_card *, unsigned);
static int sc_pkcs15emu_oberthur_add_data(struct sc_pkcs15_card *, unsigned, unsigned, int);
static int sc_oberthur_parse_tokeninfo (struct sc_pkcs15_card *, unsigned char *, size_t, int);
static int sc_oberthur_parse_containers (struct sc_pkcs15_card *, unsigned char *, size_t, int);
static int sc_oberthur_parse_publicinfo (struct sc_pkcs15_card *, unsigned char *, size_t, int);
static int sc_oberthur_parse_privateinfo (struct sc_pkcs15_card *, unsigned char *, size_t, int);
static int sc_awp_parse_df(struct sc_pkcs15_card *, struct sc_pkcs15_df *);
static void sc_awp_clear(struct sc_pkcs15_card *);
struct crypto_container {
unsigned id_pub;
unsigned id_prv;
unsigned id_cert;
};
struct container {
char uuid[37];
struct crypto_container exchange;
struct crypto_container sign;
struct container *next;
struct container *prev;
};
struct container *Containers = NULL;
static struct {
const char *name;
const char *path;
unsigned char *content;
size_t len;
int (*parser)(struct sc_pkcs15_card *, unsigned char *, size_t, int);
int postpone_allowed;
} oberthur_infos[] = {
/* Never change the following order */
{ "Token info", AWP_TOKEN_INFO, NULL, 0, sc_oberthur_parse_tokeninfo, 0},
{ "Containers MS", AWP_CONTAINERS_MS, NULL, 0, sc_oberthur_parse_containers, 0},
{ "Public objects list", AWP_OBJECTS_LIST_PUB, NULL, 0, sc_oberthur_parse_publicinfo, 0},
{ "Private objects list", AWP_OBJECTS_LIST_PRV, NULL, 0, sc_oberthur_parse_privateinfo, 1},
{ NULL, NULL, NULL, 0, NULL, 0}
};
static unsigned
sc_oberthur_decode_usage(unsigned flags)
{
unsigned ret = 0;
if (flags & OBERTHUR_ATTR_ENCRYPT)
ret |= SC_PKCS15_PRKEY_USAGE_ENCRYPT;
if (flags & OBERTHUR_ATTR_DECRYPT)
ret |= SC_PKCS15_PRKEY_USAGE_DECRYPT;
if (flags & OBERTHUR_ATTR_SIGN)
ret |= SC_PKCS15_PRKEY_USAGE_SIGN;
if (flags & OBERTHUR_ATTR_RSIGN)
ret |= SC_PKCS15_PRKEY_USAGE_SIGNRECOVER;
if (flags & OBERTHUR_ATTR_WRAP)
ret |= SC_PKCS15_PRKEY_USAGE_WRAP;
if (flags & OBERTHUR_ATTR_UNWRAP)
ret |= SC_PKCS15_PRKEY_USAGE_UNWRAP;
if (flags & OBERTHUR_ATTR_VERIFY)
ret |= SC_PKCS15_PRKEY_USAGE_VERIFY;
if (flags & OBERTHUR_ATTR_RVERIFY)
ret |= SC_PKCS15_PRKEY_USAGE_VERIFYRECOVER;
if (flags & OBERTHUR_ATTR_DERIVE)
ret |= SC_PKCS15_PRKEY_USAGE_DERIVE;
return ret;
}
static int
sc_oberthur_get_friends (unsigned int id, struct crypto_container *ccont)
{
struct container *cont;
for (cont = Containers; cont; cont = cont->next) {
if (cont->exchange.id_pub == id || cont->exchange.id_prv == id || cont->exchange.id_cert == id) {
if (ccont)
memcpy(ccont, &cont->exchange, sizeof(struct crypto_container));
break;
}
if (cont->sign.id_pub == id || cont->sign.id_prv == id || cont->sign.id_cert == id) {
if (ccont)
memcpy(ccont, &cont->sign, sizeof(struct crypto_container));
break;
}
}
return cont ? 0 : SC_ERROR_TEMPLATE_NOT_FOUND;
}
static int
sc_oberthur_get_certificate_authority(struct sc_pkcs15_der *der, int *out_authority)
{
#ifdef ENABLE_OPENSSL
X509 *x;
BUF_MEM buf_mem;
BIO *bio = NULL;
BASIC_CONSTRAINTS *bs = NULL;
if (!der)
return SC_ERROR_INVALID_ARGUMENTS;
buf_mem.data = malloc(der->len);
if (!buf_mem.data)
return SC_ERROR_OUT_OF_MEMORY;
memcpy(buf_mem.data, der->value, der->len);
buf_mem.max = buf_mem.length = der->len;
bio = BIO_new(BIO_s_mem());
if (!bio) {
free(buf_mem.data);
return SC_ERROR_OUT_OF_MEMORY;
}
BIO_set_mem_buf(bio, &buf_mem, BIO_NOCLOSE);
x = d2i_X509_bio(bio, 0);
BIO_free(bio);
if (!x)
return SC_ERROR_INVALID_DATA;
bs = (BASIC_CONSTRAINTS *)X509_get_ext_d2i(x, NID_basic_constraints, NULL, NULL);
if (out_authority)
*out_authority = (bs && bs->ca);
X509_free(x);
return SC_SUCCESS;
#else
return SC_ERROR_NOT_SUPPORTED;
#endif
}
static int
sc_oberthur_read_file(struct sc_pkcs15_card *p15card, const char *in_path,
unsigned char **out, size_t *out_len,
int verify_pin)
{
struct sc_context *ctx = p15card->card->ctx;
struct sc_card *card = p15card->card;
struct sc_file *file = NULL;
struct sc_path path;
size_t sz;
int rv;
LOG_FUNC_CALLED(ctx);
if (!in_path || !out || !out_len)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Cannot read oberthur file");
sc_log(ctx, "read file '%s'; verify_pin:%i", in_path, verify_pin);
*out = NULL;
*out_len = 0;
sc_format_path(in_path, &path);
rv = sc_select_file(card, &path, &file);
if (rv != SC_SUCCESS) {
sc_file_free(file);
LOG_TEST_RET(ctx, rv, "Cannot select oberthur file to read");
}
if (file->ef_structure == SC_FILE_EF_TRANSPARENT)
sz = file->size;
else
sz = (file->record_length + 2) * file->record_count;
*out = calloc(sz, 1);
if (*out == NULL) {
sc_file_free(file);
LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot read oberthur file");
}
if (file->ef_structure == SC_FILE_EF_TRANSPARENT) {
rv = sc_read_binary(card, 0, *out, sz, 0);
}
else {
int rec;
int offs = 0;
int rec_len = file->record_length;
for (rec = 1; ; rec++) {
rv = sc_read_record(card, rec, *out + offs + 2, rec_len, SC_RECORD_BY_REC_NR);
if (rv == SC_ERROR_RECORD_NOT_FOUND) {
rv = 0;
break;
}
else if (rv < 0) {
break;
}
rec_len = rv;
*(*out + offs) = 'R';
*(*out + offs + 1) = rv;
offs += rv + 2;
}
sz = offs;
}
sc_log(ctx, "read oberthur file result %i", rv);
if (verify_pin && rv == SC_ERROR_SECURITY_STATUS_NOT_SATISFIED) {
struct sc_pkcs15_object *objs[0x10], *pin_obj = NULL;
const struct sc_acl_entry *acl = sc_file_get_acl_entry(file, SC_AC_OP_READ);
int ii;
rv = sc_pkcs15_get_objects(p15card, SC_PKCS15_TYPE_AUTH_PIN, objs, 0x10);
if (rv != SC_SUCCESS) {
sc_file_free(file);
LOG_TEST_RET(ctx, rv, "Cannot read oberthur file: get AUTH objects error");
}
for (ii=0; ii<rv; ii++) {
struct sc_pkcs15_auth_info *auth_info = (struct sc_pkcs15_auth_info *) objs[ii]->data;
sc_log(ctx, "compare PIN/ACL refs:%i/%i, method:%i/%i",
auth_info->attrs.pin.reference, acl->key_ref, auth_info->auth_method, acl->method);
if (auth_info->attrs.pin.reference == (int)acl->key_ref && auth_info->auth_method == (unsigned)acl->method) {
pin_obj = objs[ii];
break;
}
}
if (!pin_obj || !pin_obj->content.value) {
rv = SC_ERROR_SECURITY_STATUS_NOT_SATISFIED;
}
else {
rv = sc_pkcs15_verify_pin(p15card, pin_obj, pin_obj->content.value, pin_obj->content.len);
if (!rv)
rv = sc_oberthur_read_file(p15card, in_path, out, out_len, 0);
}
};
sc_file_free(file);
if (rv < 0) {
free(*out);
*out = NULL;
*out_len = 0;
}
*out_len = sz;
LOG_FUNC_RETURN(ctx, rv);
}
static int
sc_oberthur_parse_tokeninfo (struct sc_pkcs15_card *p15card,
unsigned char *buff, size_t len, int postpone_allowed)
{
struct sc_context *ctx = p15card->card->ctx;
char label[0x21];
unsigned flags;
int ii;
LOG_FUNC_CALLED(ctx);
if (!buff || len < 0x24)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Cannot parse token info");
memset(label, 0, sizeof(label));
memcpy(label, buff, 0x20);
ii = 0x20;
while (*(label + --ii)==' ' && ii)
;
*(label + ii + 1) = '\0';
flags = *(buff + 0x22) * 0x100 + *(buff + 0x23);
set_string(&p15card->tokeninfo->label, label);
set_string(&p15card->tokeninfo->manufacturer_id, "Oberthur/OpenSC");
if (flags & 0x01)
p15card->tokeninfo->flags |= SC_PKCS15_TOKEN_PRN_GENERATION;
sc_log(ctx, "label %s", p15card->tokeninfo->label);
sc_log(ctx, "manufacturer_id %s", p15card->tokeninfo->manufacturer_id);
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int
sc_oberthur_parse_containers (struct sc_pkcs15_card *p15card,
unsigned char *buff, size_t len, int postpone_allowed)
{
struct sc_context *ctx = p15card->card->ctx;
size_t offs;
LOG_FUNC_CALLED(ctx);
while (Containers) {
struct container *next = Containers->next;
free (Containers);
Containers = next;
}
for (offs=0; offs < len;) {
struct container *cont;
unsigned char *ptr = buff + offs + 2;
sc_log(ctx,
"parse contaniers offs:%"SC_FORMAT_LEN_SIZE_T"u, len:%"SC_FORMAT_LEN_SIZE_T"u",
offs, len);
if (*(buff + offs) != 'R')
return SC_ERROR_INVALID_DATA;
cont = (struct container *)calloc(sizeof(struct container), 1);
if (!cont)
return SC_ERROR_OUT_OF_MEMORY;
cont->exchange.id_pub = *ptr * 0x100 + *(ptr + 1); ptr += 2;
cont->exchange.id_prv = *ptr * 0x100 + *(ptr + 1); ptr += 2;
cont->exchange.id_cert = *ptr * 0x100 + *(ptr + 1); ptr += 2;
cont->sign.id_pub = *ptr * 0x100 + *(ptr + 1); ptr += 2;
cont->sign.id_prv = *ptr * 0x100 + *(ptr + 1); ptr += 2;
cont->sign.id_cert = *ptr * 0x100 + *(ptr + 1); ptr += 2;
memcpy(cont->uuid, ptr + 2, 36);
sc_log(ctx, "UUID: %s; 0x%X, 0x%X, 0x%X", cont->uuid,
cont->exchange.id_pub, cont->exchange.id_prv, cont->exchange.id_cert);
if (!Containers) {
Containers = cont;
}
else {
cont->next = Containers;
Containers->prev = (void *)cont;
Containers = cont;
}
offs += *(buff + offs + 1) + 2;
}
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int
sc_oberthur_parse_publicinfo (struct sc_pkcs15_card *p15card,
unsigned char *buff, size_t len, int postpone_allowed)
{
struct sc_context *ctx = p15card->card->ctx;
size_t ii;
int rv;
LOG_FUNC_CALLED(ctx);
for (ii=0; ii<len; ii+=5) {
unsigned int file_id, size;
if(*(buff+ii) != 0xFF)
continue;
file_id = 0x100 * *(buff+ii + 1) + *(buff+ii + 2);
size = 0x100 * *(buff+ii + 3) + *(buff+ii + 4);
sc_log(ctx, "add public object(file-id:%04X,size:%X)", file_id, size);
switch (*(buff+ii + 1)) {
case BASE_ID_PUB_RSA :
rv = sc_pkcs15emu_oberthur_add_pubkey(p15card, file_id, size);
LOG_TEST_RET(ctx, rv, "Cannot parse public key info");
break;
case BASE_ID_CERT :
rv = sc_pkcs15emu_oberthur_add_cert(p15card, file_id);
LOG_TEST_RET(ctx, rv, "Cannot parse certificate info");
break;
case BASE_ID_PUB_DES :
break;
case BASE_ID_PUB_DATA :
rv = sc_pkcs15emu_oberthur_add_data(p15card, file_id, size, 0);
LOG_TEST_RET(ctx, rv, "Cannot parse data info");
break;
default:
LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Public object parse error");
}
}
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int
sc_oberthur_parse_privateinfo (struct sc_pkcs15_card *p15card,
unsigned char *buff, size_t len, int postpone_allowed)
{
struct sc_context *ctx = p15card->card->ctx;
size_t ii;
int rv;
int no_more_private_keys = 0, no_more_private_data = 0;
LOG_FUNC_CALLED(ctx);
for (ii=0; ii<len; ii+=5) {
unsigned int file_id, size;
if(*(buff+ii) != 0xFF)
continue;
file_id = 0x100 * *(buff+ii + 1) + *(buff+ii + 2);
size = 0x100 * *(buff+ii + 3) + *(buff+ii + 4);
sc_log(ctx, "add private object (file-id:%04X, size:%X)", file_id, size);
switch (*(buff+ii + 1)) {
case BASE_ID_PRV_RSA :
if (no_more_private_keys)
break;
rv = sc_pkcs15emu_oberthur_add_prvkey(p15card, file_id, size);
if (rv == SC_ERROR_SECURITY_STATUS_NOT_SATISFIED && postpone_allowed) {
struct sc_path path;
sc_log(ctx, "postpone adding of the private keys");
sc_format_path("5011A5A5", &path);
rv = sc_pkcs15_add_df(p15card, SC_PKCS15_PRKDF, &path);
LOG_TEST_RET(ctx, rv, "Add PrkDF error");
no_more_private_keys = 1;
}
LOG_TEST_RET(ctx, rv, "Cannot parse private key info");
break;
case BASE_ID_PRV_DES :
break;
case BASE_ID_PRV_DATA :
sc_log(ctx, "*(buff+ii + 1):%X", *(buff+ii + 1));
if (no_more_private_data)
break;
rv = sc_pkcs15emu_oberthur_add_data(p15card, file_id, size, 1);
if (rv == SC_ERROR_SECURITY_STATUS_NOT_SATISFIED && postpone_allowed) {
struct sc_path path;
sc_log(ctx, "postpone adding of the private data");
sc_format_path("5011A6A6", &path);
rv = sc_pkcs15_add_df(p15card, SC_PKCS15_DODF, &path);
LOG_TEST_RET(ctx, rv, "Add DODF error");
no_more_private_data = 1;
}
LOG_TEST_RET(ctx, rv, "Cannot parse private data info");
break;
default:
LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Private object parse error");
}
}
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
/* Public key info:
* flags:2,
* CN(len:2,value:<variable length>),
* ID(len:2,value:(SHA1 value)),
* StartDate(Ascii:8)
* EndDate(Ascii:8)
* ??(0x00:2)
*/
static int
sc_pkcs15emu_oberthur_add_pubkey(struct sc_pkcs15_card *p15card,
unsigned int file_id, unsigned int size)
{
struct sc_context *ctx = p15card->card->ctx;
struct sc_pkcs15_pubkey_info key_info;
struct sc_pkcs15_object key_obj;
char ch_tmp[0x100];
unsigned char *info_blob;
size_t len, info_len, offs;
unsigned flags;
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "public key(file-id:%04X,size:%X)", file_id, size);
memset(&key_info, 0, sizeof(key_info));
memset(&key_obj, 0, sizeof(key_obj));
snprintf(ch_tmp, sizeof(ch_tmp), "%s%04X", AWP_OBJECTS_DF_PUB, file_id | 0x100);
rv = sc_oberthur_read_file(p15card, ch_tmp, &info_blob, &info_len, 1);
LOG_TEST_RET(ctx, rv, "Failed to add public key: read oberthur file error");
/* Flags */
offs = 2;
if (offs > info_len)
LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Failed to add public key: no 'tag'");
flags = *(info_blob + 0) * 0x100 + *(info_blob + 1);
key_info.usage = sc_oberthur_decode_usage(flags);
if (flags & OBERTHUR_ATTR_MODIFIABLE)
key_obj.flags = SC_PKCS15_CO_FLAG_MODIFIABLE;
sc_log(ctx, "Public key key-usage:%04X", key_info.usage);
/* Label */
if (offs + 2 > info_len)
LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Failed to add public key: no 'Label'");
len = *(info_blob + offs + 1) + *(info_blob + offs) * 0x100;
if (len) {
if (len > sizeof(key_obj.label) - 1)
len = sizeof(key_obj.label) - 1;
memcpy(key_obj.label, info_blob + offs + 2, len);
}
offs += 2 + len;
/* ID */
if (offs > info_len)
LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Failed to add public key: no 'ID'");
len = *(info_blob + offs + 1) + *(info_blob + offs) * 0x100;
if (!len || len > sizeof(key_info.id.value))
LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Failed to add public key: invalid 'ID' length");
memcpy(key_info.id.value, info_blob + offs + 2, len);
key_info.id.len = len;
/* Ignore Start/End dates */
snprintf(ch_tmp, sizeof(ch_tmp), "%s%04X", AWP_OBJECTS_DF_PUB, file_id);
sc_format_path(ch_tmp, &key_info.path);
key_info.native = 1;
key_info.key_reference = file_id & 0xFF;
key_info.modulus_length = size;
rv = sc_pkcs15emu_add_rsa_pubkey(p15card, &key_obj, &key_info);
LOG_FUNC_RETURN(ctx, rv);
}
/* Certificate info:
* flags:2,
* Label(len:2,value:),
* ID(len:2,value:(SHA1 value)),
* Subject in ASN.1(len:2,value:)
* Issuer in ASN.1(len:2,value:)
* Serial encoded in LV or ASN.1 FIXME
*/
static int
sc_pkcs15emu_oberthur_add_cert(struct sc_pkcs15_card *p15card, unsigned int file_id)
{
struct sc_context *ctx = p15card->card->ctx;
struct sc_pkcs15_cert_info cinfo;
struct sc_pkcs15_object cobj;
unsigned char *info_blob, *cert_blob;
size_t info_len, cert_len, len, offs;
unsigned flags;
int rv;
char ch_tmp[0x20];
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "add certificate(file-id:%04X)", file_id);
memset(&cinfo, 0, sizeof(cinfo));
memset(&cobj, 0, sizeof(cobj));
snprintf(ch_tmp, sizeof(ch_tmp), "%s%04X", AWP_OBJECTS_DF_PUB, file_id | 0x100);
rv = sc_oberthur_read_file(p15card, ch_tmp, &info_blob, &info_len, 1);
LOG_TEST_RET(ctx, rv, "Failed to add certificate: read oberthur file error");
if (info_len < 2)
LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Failed to add certificate: no 'tag'");
flags = *(info_blob + 0) * 0x100 + *(info_blob + 1);
offs = 2;
/* Label */
if (offs + 2 > info_len)
LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Failed to add certificate: no 'CN'");
len = *(info_blob + offs + 1) + *(info_blob + offs) * 0x100;
if (len) {
if (len > sizeof(cobj.label) - 1)
len = sizeof(cobj.label) - 1;
memcpy(cobj.label, info_blob + offs + 2, len);
}
offs += 2 + len;
/* ID */
if (offs > info_len)
LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Failed to add certificate: no 'ID'");
len = *(info_blob + offs + 1) + *(info_blob + offs) * 0x100;
if (len > sizeof(cinfo.id.value))
LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Failed to add certificate: invalid 'ID' length");
memcpy(cinfo.id.value, info_blob + offs + 2, len);
cinfo.id.len = len;
/* Ignore subject, issuer and serial */
snprintf(ch_tmp, sizeof(ch_tmp), "%s%04X", AWP_OBJECTS_DF_PUB, file_id);
sc_format_path(ch_tmp, &cinfo.path);
rv = sc_oberthur_read_file(p15card, ch_tmp, &cert_blob, &cert_len, 1);
LOG_TEST_RET(ctx, rv, "Failed to add certificate: read certificate error");
cinfo.value.value = cert_blob;
cinfo.value.len = cert_len;
rv = sc_oberthur_get_certificate_authority(&cinfo.value, &cinfo.authority);
LOG_TEST_RET(ctx, rv, "Failed to add certificate: get certificate attributes error");
if (flags & OBERTHUR_ATTR_MODIFIABLE)
cobj.flags |= SC_PKCS15_CO_FLAG_MODIFIABLE;
rv = sc_pkcs15emu_add_x509_cert(p15card, &cobj, &cinfo);
LOG_FUNC_RETURN(p15card->card->ctx, rv);
}
/* Private key info:
* flags:2,
* CN(len:2,value:),
* ID(len:2,value:(SHA1 value)),
* StartDate(Ascii:8)
* EndDate(Ascii:8)
* Subject in ASN.1(len:2,value:)
* modulus(value:)
* exponent(length:1, value:3)
*/
static int
sc_pkcs15emu_oberthur_add_prvkey(struct sc_pkcs15_card *p15card,
unsigned int file_id, unsigned int size)
{
struct sc_context *ctx = p15card->card->ctx;
struct sc_pkcs15_prkey_info kinfo;
struct sc_pkcs15_object kobj;
struct crypto_container ccont;
unsigned char *info_blob = NULL;
size_t info_len = 0;
unsigned flags;
size_t offs, len;
char ch_tmp[0x100];
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "add private key(file-id:%04X,size:%04X)", file_id, size);
memset(&kinfo, 0, sizeof(kinfo));
memset(&kobj, 0, sizeof(kobj));
memset(&ccont, 0, sizeof(ccont));
rv = sc_oberthur_get_friends (file_id, &ccont);
LOG_TEST_RET(ctx, rv, "Failed to add private key: get friends error");
if (ccont.id_cert) {
struct sc_pkcs15_object *objs[32];
int ii;
sc_log(ctx, "friend certificate %04X", ccont.id_cert);
rv = sc_pkcs15_get_objects(p15card, SC_PKCS15_TYPE_CERT_X509, objs, 32);
LOG_TEST_RET(ctx, rv, "Failed to add private key: get certificates error");
for (ii=0; ii<rv; ii++) {
struct sc_pkcs15_cert_info *cert = (struct sc_pkcs15_cert_info *)objs[ii]->data;
struct sc_path path = cert->path;
unsigned int id = path.value[path.len - 2] * 0x100 + path.value[path.len - 1];
if (id == ccont.id_cert) {
strlcpy(kobj.label, objs[ii]->label, sizeof(kobj.label));
break;
}
}
if (ii == rv)
LOG_TEST_RET(ctx, SC_ERROR_INCONSISTENT_PROFILE, "Failed to add private key: friend not found");
}
snprintf(ch_tmp, sizeof(ch_tmp), "%s%04X", AWP_OBJECTS_DF_PRV, file_id | 0x100);
rv = sc_oberthur_read_file(p15card, ch_tmp, &info_blob, &info_len, 1);
LOG_TEST_RET(ctx, rv, "Failed to add private key: read oberthur file error");
if (info_len < 2)
LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Failed to add private key: no 'tag'");
flags = *(info_blob + 0) * 0x100 + *(info_blob + 1);
offs = 2;
/* CN */
if (offs > info_len)
LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Failed to add private key: no 'CN'");
len = *(info_blob + offs + 1) + *(info_blob + offs) * 0x100;
if (len && !strlen(kobj.label)) {
if (len > sizeof(kobj.label) - 1)
len = sizeof(kobj.label) - 1;
strncpy(kobj.label, (char *)(info_blob + offs + 2), len);
}
offs += 2 + len;
/* ID */
if (offs > info_len)
LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Failed to add private key: no 'ID'");
len = *(info_blob + offs + 1) + *(info_blob + offs) * 0x100;
if (!len)
LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Failed to add private key: zero length ID");
else if (len > sizeof(kinfo.id.value))
LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Failed to add private key: invalid ID length");
memcpy(kinfo.id.value, info_blob + offs + 2, len);
kinfo.id.len = len;
offs += 2 + len;
/* Ignore Start/End dates */
offs += 16;
/* Subject encoded in ASN1 */
if (offs > info_len)
return SC_ERROR_UNKNOWN_DATA_RECEIVED;
len = *(info_blob + offs + 1) + *(info_blob + offs) * 0x100;
if (len) {
kinfo.subject.value = malloc(len);
if (!kinfo.subject.value)
LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Failed to add private key: memory allocation error");
kinfo.subject.len = len;
memcpy(kinfo.subject.value, info_blob + offs + 2, len);
}
/* Modulus and exponent are ignored */
snprintf(ch_tmp, sizeof(ch_tmp), "%s%04X", AWP_OBJECTS_DF_PRV, file_id);
sc_format_path(ch_tmp, &kinfo.path);
sc_log(ctx, "Private key info path %s", ch_tmp);
kinfo.modulus_length = size;
kinfo.native = 1;
kinfo.key_reference = file_id & 0xFF;
kinfo.usage = sc_oberthur_decode_usage(flags);
kobj.flags = SC_PKCS15_CO_FLAG_PRIVATE;
if (flags & OBERTHUR_ATTR_MODIFIABLE)
kobj.flags |= SC_PKCS15_CO_FLAG_MODIFIABLE;
kobj.auth_id.len = sizeof(PinDomainID) > sizeof(kobj.auth_id.value)
? sizeof(kobj.auth_id.value) : sizeof(PinDomainID);
memcpy(kobj.auth_id.value, PinDomainID, kobj.auth_id.len);
sc_log(ctx, "Parsed private key(reference:%i,usage:%X,flags:%X)", kinfo.key_reference, kinfo.usage, kobj.flags);
rv = sc_pkcs15emu_add_rsa_prkey(p15card, &kobj, &kinfo);
LOG_FUNC_RETURN(ctx, rv);
}
static int
sc_pkcs15emu_oberthur_add_data(struct sc_pkcs15_card *p15card,
unsigned int file_id, unsigned int size, int private)
{
struct sc_context *ctx = p15card->card->ctx;
struct sc_pkcs15_data_info dinfo;
struct sc_pkcs15_object dobj;
unsigned flags;
unsigned char *info_blob = NULL, *label = NULL, *app = NULL, *oid = NULL;
size_t info_len, label_len, app_len, oid_len, offs;
char ch_tmp[0x100];
int rv;
SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_VERBOSE);
sc_log(ctx, "Add data(file-id:%04X,size:%i,is-private:%i)", file_id, size, private);
memset(&dinfo, 0, sizeof(dinfo));
memset(&dobj, 0, sizeof(dobj));
snprintf(ch_tmp, sizeof(ch_tmp), "%s%04X", private ? AWP_OBJECTS_DF_PRV : AWP_OBJECTS_DF_PUB, file_id | 0x100);
rv = sc_oberthur_read_file(p15card, ch_tmp, &info_blob, &info_len, 1);
LOG_TEST_RET(ctx, rv, "Failed to add data: read oberthur file error");
if (info_len < 2)
LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Failed to add certificate: no 'tag'");
flags = *(info_blob + 0) * 0x100 + *(info_blob + 1);
offs = 2;
/* Label */
if (offs > info_len)
LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Failed to add data: no 'label'");
label = info_blob + offs + 2;
label_len = *(info_blob + offs + 1) + *(info_blob + offs) * 0x100;
if (label_len > sizeof(dobj.label) - 1)
label_len = sizeof(dobj.label) - 1;
offs += 2 + *(info_blob + offs + 1);
/* Application */
if (offs > info_len)
LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Failed to add data: no 'application'");
app = info_blob + offs + 2;
app_len = *(info_blob + offs + 1) + *(info_blob + offs) * 0x100;
if (app_len > sizeof(dinfo.app_label) - 1)
app_len = sizeof(dinfo.app_label) - 1;
offs += 2 + app_len;
/* OID encode like DER(ASN.1(oid)) */
if (offs > info_len)
LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Failed to add data: no 'OID'");
oid_len = *(info_blob + offs + 1) + *(info_blob + offs) * 0x100;
if (oid_len) {
oid = info_blob + offs + 2;
if (*oid != 0x06 || (*(oid + 1) != oid_len - 2))
LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Failed to add data: invalid 'OID' format");
oid += 2;
oid_len -= 2;
}
snprintf(ch_tmp, sizeof(ch_tmp), "%s%04X", private ? AWP_OBJECTS_DF_PRV : AWP_OBJECTS_DF_PUB, file_id);
sc_format_path(ch_tmp, &dinfo.path);
memcpy(dobj.label, label, label_len);
memcpy(dinfo.app_label, app, app_len);
if (oid_len)
sc_asn1_decode_object_id(oid, oid_len, &dinfo.app_oid);
if (flags & OBERTHUR_ATTR_MODIFIABLE)
dobj.flags |= SC_PKCS15_CO_FLAG_MODIFIABLE;
if (private) {
dobj.auth_id.len = sizeof(PinDomainID) > sizeof(dobj.auth_id.value)
? sizeof(dobj.auth_id.value) : sizeof(PinDomainID);
memcpy(dobj.auth_id.value, PinDomainID, dobj.auth_id.len);
dobj.flags |= SC_PKCS15_CO_FLAG_PRIVATE;
}
rv = sc_pkcs15emu_add_data_object(p15card, &dobj, &dinfo);
LOG_FUNC_RETURN(p15card->card->ctx, rv);
}
static int
sc_pkcs15emu_oberthur_init(struct sc_pkcs15_card * p15card)
{
struct sc_context *ctx = p15card->card->ctx;
struct sc_pkcs15_auth_info auth_info;
struct sc_pkcs15_object obj;
struct sc_card *card = p15card->card;
struct sc_path path;
int rv, ii, tries_left;
char serial[0x10];
unsigned char sopin_reference = 0x04;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_bin_to_hex(card->serialnr.value, card->serialnr.len, serial, sizeof(serial), 0);
set_string(&p15card->tokeninfo->serial_number, serial);
p15card->ops.parse_df = sc_awp_parse_df;
p15card->ops.clear = sc_awp_clear;
sc_log(ctx, "Oberthur init: serial %s", p15card->tokeninfo->serial_number);
sc_format_path(AWP_PIN_DF, &path);
rv = sc_select_file(card, &path, NULL);
LOG_TEST_RET(ctx, rv, "Oberthur init failed: cannot select PIN dir");
tries_left = -1;
rv = sc_verify(card, SC_AC_CHV, sopin_reference, (unsigned char *)"", 0, &tries_left);
if (rv && rv != SC_ERROR_PIN_CODE_INCORRECT) {
sopin_reference = 0x84;
rv = sc_verify(card, SC_AC_CHV, sopin_reference, (unsigned char *)"", 0, &tries_left);
}
if (rv && rv != SC_ERROR_PIN_CODE_INCORRECT)
LOG_TEST_RET(ctx, rv, "Invalid state of SO-PIN");
/* add PIN */
memset(&auth_info, 0, sizeof(auth_info));
memset(&obj, 0, sizeof(obj));
auth_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
auth_info.auth_method = SC_AC_CHV;
auth_info.auth_id.len = 1;
auth_info.auth_id.value[0] = 0xFF;
auth_info.attrs.pin.min_length = 4;
auth_info.attrs.pin.max_length = 64;
auth_info.attrs.pin.stored_length = 64;
auth_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC;
auth_info.attrs.pin.reference = sopin_reference;
auth_info.attrs.pin.pad_char = 0xFF;
auth_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_CASE_SENSITIVE
| SC_PKCS15_PIN_FLAG_INITIALIZED
| SC_PKCS15_PIN_FLAG_NEEDS_PADDING
| SC_PKCS15_PIN_FLAG_SO_PIN;
auth_info.tries_left = tries_left;
auth_info.logged_in = SC_PIN_STATE_UNKNOWN;
strncpy(obj.label, "SO PIN", SC_PKCS15_MAX_LABEL_SIZE-1);
obj.flags = SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE;
sc_log(ctx, "Add PIN(%s,auth_id:%s,reference:%i)", obj.label,
sc_pkcs15_print_id(&auth_info.auth_id), auth_info.attrs.pin.reference);
rv = sc_pkcs15emu_add_pin_obj(p15card, &obj, &auth_info);
LOG_TEST_RET(ctx, rv, "Oberthur init failed: cannot add PIN object");
tries_left = -1;
rv = sc_verify(card, SC_AC_CHV, 0x81, (unsigned char *)"", 0, &tries_left);
if (rv == SC_ERROR_PIN_CODE_INCORRECT) {
/* add PIN */
memset(&auth_info, 0, sizeof(auth_info));
memset(&obj, 0, sizeof(obj));
auth_info.auth_id.len = sizeof(PinDomainID) > sizeof(auth_info.auth_id.value)
? sizeof(auth_info.auth_id.value) : sizeof(PinDomainID);
memcpy(auth_info.auth_id.value, PinDomainID, auth_info.auth_id.len);
auth_info.auth_method = SC_AC_CHV;
auth_info.attrs.pin.min_length = 4;
auth_info.attrs.pin.max_length = 64;
auth_info.attrs.pin.stored_length = 64;
auth_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC;
auth_info.attrs.pin.reference = 0x81;
auth_info.attrs.pin.pad_char = 0xFF;
auth_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_CASE_SENSITIVE
| SC_PKCS15_PIN_FLAG_INITIALIZED
| SC_PKCS15_PIN_FLAG_NEEDS_PADDING
| SC_PKCS15_PIN_FLAG_LOCAL;
auth_info.tries_left = tries_left;
strncpy(obj.label, PIN_DOMAIN_LABEL, SC_PKCS15_MAX_LABEL_SIZE-1);
obj.flags = SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE;
if (sopin_reference == 0x84) {
/*
* auth_pin_reset_oberthur_style() in card-oberthur.c
* always uses PUK with reference 0x84 for
* unblocking of User PIN
*/
obj.auth_id.len = 1;
obj.auth_id.value[0] = 0xFF;
}
sc_format_path(AWP_PIN_DF, &auth_info.path);
auth_info.path.type = SC_PATH_TYPE_PATH;
sc_log(ctx, "Add PIN(%s,auth_id:%s,reference:%i)", obj.label,
sc_pkcs15_print_id(&auth_info.auth_id), auth_info.attrs.pin.reference);
rv = sc_pkcs15emu_add_pin_obj(p15card, &obj, &auth_info);
LOG_TEST_RET(ctx, rv, "Oberthur init failed: cannot add PIN object");
}
else if (rv != SC_ERROR_DATA_OBJECT_NOT_FOUND) {
LOG_TEST_RET(ctx, rv, "Oberthur init failed: cannot verify PIN");
}
for (ii=0; oberthur_infos[ii].name; ii++) {
sc_log(ctx, "Oberthur init: read %s file", oberthur_infos[ii].name);
rv = sc_oberthur_read_file(p15card, oberthur_infos[ii].path,
&oberthur_infos[ii].content, &oberthur_infos[ii].len, 1);
LOG_TEST_RET(ctx, rv, "Oberthur init failed: read oberthur file error");
sc_log(ctx,
"Oberthur init: parse %s file, content length %"SC_FORMAT_LEN_SIZE_T"u",
oberthur_infos[ii].name, oberthur_infos[ii].len);
rv = oberthur_infos[ii].parser(p15card, oberthur_infos[ii].content, oberthur_infos[ii].len,
oberthur_infos[ii].postpone_allowed);
LOG_TEST_RET(ctx, rv, "Oberthur init failed: parse error");
}
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int
oberthur_detect_card(struct sc_pkcs15_card * p15card)
{
struct sc_card *card = p15card->card;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
if (p15card->card->type != SC_CARD_TYPE_OBERTHUR_64K)
LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_WRONG_CARD);
LOG_FUNC_RETURN(p15card->card->ctx, SC_SUCCESS);
}
int
sc_pkcs15emu_oberthur_init_ex(struct sc_pkcs15_card * p15card, struct sc_aid *aid)
{
int rv;
LOG_FUNC_CALLED(p15card->card->ctx);
rv = oberthur_detect_card(p15card);
if (!rv)
rv = sc_pkcs15emu_oberthur_init(p15card);
LOG_FUNC_RETURN(p15card->card->ctx, rv);
}
static int
sc_awp_parse_df(struct sc_pkcs15_card *p15card, struct sc_pkcs15_df *df)
{
struct sc_context *ctx = p15card->card->ctx;
unsigned char *buf = NULL;
size_t buf_len;
int rv;
LOG_FUNC_CALLED(ctx);
if (df->type != SC_PKCS15_PRKDF && df->type != SC_PKCS15_DODF)
LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED);
if (df->enumerated)
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
rv = sc_oberthur_read_file(p15card, AWP_OBJECTS_LIST_PRV, &buf, &buf_len, 1);
LOG_TEST_RET(ctx, rv, "Parse DF: read private objects info failed");
rv = sc_oberthur_parse_privateinfo(p15card, buf, buf_len, 0);
if (buf)
free(buf);
if (rv == SC_ERROR_SECURITY_STATUS_NOT_SATISFIED)
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
LOG_TEST_RET(ctx, rv, "Parse DF: private info parse error");
df->enumerated = 1;
LOG_FUNC_RETURN(ctx, rv);
}
static void
sc_awp_clear(struct sc_pkcs15_card *p15card)
{
LOG_FUNC_CALLED(p15card->card->ctx);
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_4401_0 |
crossvul-cpp_data_bad_5479_1 | /* $Id$ */
/*
* Copyright (c) 1996-1997 Sam Leffler
* Copyright (c) 1996 Pixar
*
* 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
* Pixar, 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 Pixar, 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 PIXAR, 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 "tiffiop.h"
#ifdef PIXARLOG_SUPPORT
/*
* TIFF Library.
* PixarLog Compression Support
*
* Contributed by Dan McCoy.
*
* PixarLog film support uses the TIFF library to store companded
* 11 bit values into a tiff file, which are compressed using the
* zip compressor.
*
* The codec can take as input and produce as output 32-bit IEEE float values
* as well as 16-bit or 8-bit unsigned integer values.
*
* On writing any of the above are converted into the internal
* 11-bit log format. In the case of 8 and 16 bit values, the
* input is assumed to be unsigned linear color values that represent
* the range 0-1. In the case of IEEE values, the 0-1 range is assumed to
* be the normal linear color range, in addition over 1 values are
* accepted up to a value of about 25.0 to encode "hot" highlights and such.
* The encoding is lossless for 8-bit values, slightly lossy for the
* other bit depths. The actual color precision should be better
* than the human eye can perceive with extra room to allow for
* error introduced by further image computation. As with any quantized
* color format, it is possible to perform image calculations which
* expose the quantization error. This format should certainly be less
* susceptible to such errors than standard 8-bit encodings, but more
* susceptible than straight 16-bit or 32-bit encodings.
*
* On reading the internal format is converted to the desired output format.
* The program can request which format it desires by setting the internal
* pseudo tag TIFFTAG_PIXARLOGDATAFMT to one of these possible values:
* PIXARLOGDATAFMT_FLOAT = provide IEEE float values.
* PIXARLOGDATAFMT_16BIT = provide unsigned 16-bit integer values
* PIXARLOGDATAFMT_8BIT = provide unsigned 8-bit integer values
*
* alternately PIXARLOGDATAFMT_8BITABGR provides unsigned 8-bit integer
* values with the difference that if there are exactly three or four channels
* (rgb or rgba) it swaps the channel order (bgr or abgr).
*
* PIXARLOGDATAFMT_11BITLOG provides the internal encoding directly
* packed in 16-bit values. However no tools are supplied for interpreting
* these values.
*
* "hot" (over 1.0) areas written in floating point get clamped to
* 1.0 in the integer data types.
*
* When the file is closed after writing, the bit depth and sample format
* are set always to appear as if 8-bit data has been written into it.
* That way a naive program unaware of the particulars of the encoding
* gets the format it is most likely able to handle.
*
* The codec does it's own horizontal differencing step on the coded
* values so the libraries predictor stuff should be turned off.
* The codec also handle byte swapping the encoded values as necessary
* since the library does not have the information necessary
* to know the bit depth of the raw unencoded buffer.
*
* NOTE: This decoder does not appear to update tif_rawcp, and tif_rawcc.
* This can cause problems with the implementation of CHUNKY_STRIP_READ_SUPPORT
* as noted in http://trac.osgeo.org/gdal/ticket/3894. FrankW - Jan'11
*/
#include "tif_predict.h"
#include "zlib.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* Tables for converting to/from 11 bit coded values */
#define TSIZE 2048 /* decode table size (11-bit tokens) */
#define TSIZEP1 2049 /* Plus one for slop */
#define ONE 1250 /* token value of 1.0 exactly */
#define RATIO 1.004 /* nominal ratio for log part */
#define CODE_MASK 0x7ff /* 11 bits. */
static float Fltsize;
static float LogK1, LogK2;
#define REPEAT(n, op) { int i; i=n; do { i--; op; } while (i>0); }
static void
horizontalAccumulateF(uint16 *wp, int n, int stride, float *op,
float *ToLinearF)
{
register unsigned int cr, cg, cb, ca, mask;
register float t0, t1, t2, t3;
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
t0 = ToLinearF[cr = (wp[0] & mask)];
t1 = ToLinearF[cg = (wp[1] & mask)];
t2 = ToLinearF[cb = (wp[2] & mask)];
op[0] = t0;
op[1] = t1;
op[2] = t2;
n -= 3;
while (n > 0) {
wp += 3;
op += 3;
n -= 3;
t0 = ToLinearF[(cr += wp[0]) & mask];
t1 = ToLinearF[(cg += wp[1]) & mask];
t2 = ToLinearF[(cb += wp[2]) & mask];
op[0] = t0;
op[1] = t1;
op[2] = t2;
}
} else if (stride == 4) {
t0 = ToLinearF[cr = (wp[0] & mask)];
t1 = ToLinearF[cg = (wp[1] & mask)];
t2 = ToLinearF[cb = (wp[2] & mask)];
t3 = ToLinearF[ca = (wp[3] & mask)];
op[0] = t0;
op[1] = t1;
op[2] = t2;
op[3] = t3;
n -= 4;
while (n > 0) {
wp += 4;
op += 4;
n -= 4;
t0 = ToLinearF[(cr += wp[0]) & mask];
t1 = ToLinearF[(cg += wp[1]) & mask];
t2 = ToLinearF[(cb += wp[2]) & mask];
t3 = ToLinearF[(ca += wp[3]) & mask];
op[0] = t0;
op[1] = t1;
op[2] = t2;
op[3] = t3;
}
} else {
REPEAT(stride, *op = ToLinearF[*wp&mask]; wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; *op = ToLinearF[*wp&mask]; wp++; op++)
n -= stride;
}
}
}
}
static void
horizontalAccumulate12(uint16 *wp, int n, int stride, int16 *op,
float *ToLinearF)
{
register unsigned int cr, cg, cb, ca, mask;
register float t0, t1, t2, t3;
#define SCALE12 2048.0F
#define CLAMP12(t) (((t) < 3071) ? (uint16) (t) : 3071)
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
t0 = ToLinearF[cr = (wp[0] & mask)] * SCALE12;
t1 = ToLinearF[cg = (wp[1] & mask)] * SCALE12;
t2 = ToLinearF[cb = (wp[2] & mask)] * SCALE12;
op[0] = CLAMP12(t0);
op[1] = CLAMP12(t1);
op[2] = CLAMP12(t2);
n -= 3;
while (n > 0) {
wp += 3;
op += 3;
n -= 3;
t0 = ToLinearF[(cr += wp[0]) & mask] * SCALE12;
t1 = ToLinearF[(cg += wp[1]) & mask] * SCALE12;
t2 = ToLinearF[(cb += wp[2]) & mask] * SCALE12;
op[0] = CLAMP12(t0);
op[1] = CLAMP12(t1);
op[2] = CLAMP12(t2);
}
} else if (stride == 4) {
t0 = ToLinearF[cr = (wp[0] & mask)] * SCALE12;
t1 = ToLinearF[cg = (wp[1] & mask)] * SCALE12;
t2 = ToLinearF[cb = (wp[2] & mask)] * SCALE12;
t3 = ToLinearF[ca = (wp[3] & mask)] * SCALE12;
op[0] = CLAMP12(t0);
op[1] = CLAMP12(t1);
op[2] = CLAMP12(t2);
op[3] = CLAMP12(t3);
n -= 4;
while (n > 0) {
wp += 4;
op += 4;
n -= 4;
t0 = ToLinearF[(cr += wp[0]) & mask] * SCALE12;
t1 = ToLinearF[(cg += wp[1]) & mask] * SCALE12;
t2 = ToLinearF[(cb += wp[2]) & mask] * SCALE12;
t3 = ToLinearF[(ca += wp[3]) & mask] * SCALE12;
op[0] = CLAMP12(t0);
op[1] = CLAMP12(t1);
op[2] = CLAMP12(t2);
op[3] = CLAMP12(t3);
}
} else {
REPEAT(stride, t0 = ToLinearF[*wp&mask] * SCALE12;
*op = CLAMP12(t0); wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; t0 = ToLinearF[wp[stride]&mask]*SCALE12;
*op = CLAMP12(t0); wp++; op++)
n -= stride;
}
}
}
}
static void
horizontalAccumulate16(uint16 *wp, int n, int stride, uint16 *op,
uint16 *ToLinear16)
{
register unsigned int cr, cg, cb, ca, mask;
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
op[0] = ToLinear16[cr = (wp[0] & mask)];
op[1] = ToLinear16[cg = (wp[1] & mask)];
op[2] = ToLinear16[cb = (wp[2] & mask)];
n -= 3;
while (n > 0) {
wp += 3;
op += 3;
n -= 3;
op[0] = ToLinear16[(cr += wp[0]) & mask];
op[1] = ToLinear16[(cg += wp[1]) & mask];
op[2] = ToLinear16[(cb += wp[2]) & mask];
}
} else if (stride == 4) {
op[0] = ToLinear16[cr = (wp[0] & mask)];
op[1] = ToLinear16[cg = (wp[1] & mask)];
op[2] = ToLinear16[cb = (wp[2] & mask)];
op[3] = ToLinear16[ca = (wp[3] & mask)];
n -= 4;
while (n > 0) {
wp += 4;
op += 4;
n -= 4;
op[0] = ToLinear16[(cr += wp[0]) & mask];
op[1] = ToLinear16[(cg += wp[1]) & mask];
op[2] = ToLinear16[(cb += wp[2]) & mask];
op[3] = ToLinear16[(ca += wp[3]) & mask];
}
} else {
REPEAT(stride, *op = ToLinear16[*wp&mask]; wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; *op = ToLinear16[*wp&mask]; wp++; op++)
n -= stride;
}
}
}
}
/*
* Returns the log encoded 11-bit values with the horizontal
* differencing undone.
*/
static void
horizontalAccumulate11(uint16 *wp, int n, int stride, uint16 *op)
{
register unsigned int cr, cg, cb, ca, mask;
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
op[0] = wp[0]; op[1] = wp[1]; op[2] = wp[2];
cr = wp[0]; cg = wp[1]; cb = wp[2];
n -= 3;
while (n > 0) {
wp += 3;
op += 3;
n -= 3;
op[0] = (uint16)((cr += wp[0]) & mask);
op[1] = (uint16)((cg += wp[1]) & mask);
op[2] = (uint16)((cb += wp[2]) & mask);
}
} else if (stride == 4) {
op[0] = wp[0]; op[1] = wp[1];
op[2] = wp[2]; op[3] = wp[3];
cr = wp[0]; cg = wp[1]; cb = wp[2]; ca = wp[3];
n -= 4;
while (n > 0) {
wp += 4;
op += 4;
n -= 4;
op[0] = (uint16)((cr += wp[0]) & mask);
op[1] = (uint16)((cg += wp[1]) & mask);
op[2] = (uint16)((cb += wp[2]) & mask);
op[3] = (uint16)((ca += wp[3]) & mask);
}
} else {
REPEAT(stride, *op = *wp&mask; wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; *op = *wp&mask; wp++; op++)
n -= stride;
}
}
}
}
static void
horizontalAccumulate8(uint16 *wp, int n, int stride, unsigned char *op,
unsigned char *ToLinear8)
{
register unsigned int cr, cg, cb, ca, mask;
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
op[0] = ToLinear8[cr = (wp[0] & mask)];
op[1] = ToLinear8[cg = (wp[1] & mask)];
op[2] = ToLinear8[cb = (wp[2] & mask)];
n -= 3;
while (n > 0) {
n -= 3;
wp += 3;
op += 3;
op[0] = ToLinear8[(cr += wp[0]) & mask];
op[1] = ToLinear8[(cg += wp[1]) & mask];
op[2] = ToLinear8[(cb += wp[2]) & mask];
}
} else if (stride == 4) {
op[0] = ToLinear8[cr = (wp[0] & mask)];
op[1] = ToLinear8[cg = (wp[1] & mask)];
op[2] = ToLinear8[cb = (wp[2] & mask)];
op[3] = ToLinear8[ca = (wp[3] & mask)];
n -= 4;
while (n > 0) {
n -= 4;
wp += 4;
op += 4;
op[0] = ToLinear8[(cr += wp[0]) & mask];
op[1] = ToLinear8[(cg += wp[1]) & mask];
op[2] = ToLinear8[(cb += wp[2]) & mask];
op[3] = ToLinear8[(ca += wp[3]) & mask];
}
} else {
REPEAT(stride, *op = ToLinear8[*wp&mask]; wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; *op = ToLinear8[*wp&mask]; wp++; op++)
n -= stride;
}
}
}
}
static void
horizontalAccumulate8abgr(uint16 *wp, int n, int stride, unsigned char *op,
unsigned char *ToLinear8)
{
register unsigned int cr, cg, cb, ca, mask;
register unsigned char t0, t1, t2, t3;
if (n >= stride) {
mask = CODE_MASK;
if (stride == 3) {
op[0] = 0;
t1 = ToLinear8[cb = (wp[2] & mask)];
t2 = ToLinear8[cg = (wp[1] & mask)];
t3 = ToLinear8[cr = (wp[0] & mask)];
op[1] = t1;
op[2] = t2;
op[3] = t3;
n -= 3;
while (n > 0) {
n -= 3;
wp += 3;
op += 4;
op[0] = 0;
t1 = ToLinear8[(cb += wp[2]) & mask];
t2 = ToLinear8[(cg += wp[1]) & mask];
t3 = ToLinear8[(cr += wp[0]) & mask];
op[1] = t1;
op[2] = t2;
op[3] = t3;
}
} else if (stride == 4) {
t0 = ToLinear8[ca = (wp[3] & mask)];
t1 = ToLinear8[cb = (wp[2] & mask)];
t2 = ToLinear8[cg = (wp[1] & mask)];
t3 = ToLinear8[cr = (wp[0] & mask)];
op[0] = t0;
op[1] = t1;
op[2] = t2;
op[3] = t3;
n -= 4;
while (n > 0) {
n -= 4;
wp += 4;
op += 4;
t0 = ToLinear8[(ca += wp[3]) & mask];
t1 = ToLinear8[(cb += wp[2]) & mask];
t2 = ToLinear8[(cg += wp[1]) & mask];
t3 = ToLinear8[(cr += wp[0]) & mask];
op[0] = t0;
op[1] = t1;
op[2] = t2;
op[3] = t3;
}
} else {
REPEAT(stride, *op = ToLinear8[*wp&mask]; wp++; op++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[stride] += *wp; *op = ToLinear8[*wp&mask]; wp++; op++)
n -= stride;
}
}
}
}
/*
* State block for each open TIFF
* file using PixarLog compression/decompression.
*/
typedef struct {
TIFFPredictorState predict;
z_stream stream;
tmsize_t tbuf_size; /* only set/used on reading for now */
uint16 *tbuf;
uint16 stride;
int state;
int user_datafmt;
int quality;
#define PLSTATE_INIT 1
TIFFVSetMethod vgetparent; /* super-class method */
TIFFVSetMethod vsetparent; /* super-class method */
float *ToLinearF;
uint16 *ToLinear16;
unsigned char *ToLinear8;
uint16 *FromLT2;
uint16 *From14; /* Really for 16-bit data, but we shift down 2 */
uint16 *From8;
} PixarLogState;
static int
PixarLogMakeTables(PixarLogState *sp)
{
/*
* We make several tables here to convert between various external
* representations (float, 16-bit, and 8-bit) and the internal
* 11-bit companded representation. The 11-bit representation has two
* distinct regions. A linear bottom end up through .018316 in steps
* of about .000073, and a region of constant ratio up to about 25.
* These floating point numbers are stored in the main table ToLinearF.
* All other tables are derived from this one. The tables (and the
* ratios) are continuous at the internal seam.
*/
int nlin, lt2size;
int i, j;
double b, c, linstep, v;
float *ToLinearF;
uint16 *ToLinear16;
unsigned char *ToLinear8;
uint16 *FromLT2;
uint16 *From14; /* Really for 16-bit data, but we shift down 2 */
uint16 *From8;
c = log(RATIO);
nlin = (int)(1./c); /* nlin must be an integer */
c = 1./nlin;
b = exp(-c*ONE); /* multiplicative scale factor [b*exp(c*ONE) = 1] */
linstep = b*c*exp(1.);
LogK1 = (float)(1./c); /* if (v >= 2) token = k1*log(v*k2) */
LogK2 = (float)(1./b);
lt2size = (int)(2./linstep) + 1;
FromLT2 = (uint16 *)_TIFFmalloc(lt2size*sizeof(uint16));
From14 = (uint16 *)_TIFFmalloc(16384*sizeof(uint16));
From8 = (uint16 *)_TIFFmalloc(256*sizeof(uint16));
ToLinearF = (float *)_TIFFmalloc(TSIZEP1 * sizeof(float));
ToLinear16 = (uint16 *)_TIFFmalloc(TSIZEP1 * sizeof(uint16));
ToLinear8 = (unsigned char *)_TIFFmalloc(TSIZEP1 * sizeof(unsigned char));
if (FromLT2 == NULL || From14 == NULL || From8 == NULL ||
ToLinearF == NULL || ToLinear16 == NULL || ToLinear8 == NULL) {
if (FromLT2) _TIFFfree(FromLT2);
if (From14) _TIFFfree(From14);
if (From8) _TIFFfree(From8);
if (ToLinearF) _TIFFfree(ToLinearF);
if (ToLinear16) _TIFFfree(ToLinear16);
if (ToLinear8) _TIFFfree(ToLinear8);
sp->FromLT2 = NULL;
sp->From14 = NULL;
sp->From8 = NULL;
sp->ToLinearF = NULL;
sp->ToLinear16 = NULL;
sp->ToLinear8 = NULL;
return 0;
}
j = 0;
for (i = 0; i < nlin; i++) {
v = i * linstep;
ToLinearF[j++] = (float)v;
}
for (i = nlin; i < TSIZE; i++)
ToLinearF[j++] = (float)(b*exp(c*i));
ToLinearF[2048] = ToLinearF[2047];
for (i = 0; i < TSIZEP1; i++) {
v = ToLinearF[i]*65535.0 + 0.5;
ToLinear16[i] = (v > 65535.0) ? 65535 : (uint16)v;
v = ToLinearF[i]*255.0 + 0.5;
ToLinear8[i] = (v > 255.0) ? 255 : (unsigned char)v;
}
j = 0;
for (i = 0; i < lt2size; i++) {
if ((i*linstep)*(i*linstep) > ToLinearF[j]*ToLinearF[j+1])
j++;
FromLT2[i] = (uint16)j;
}
/*
* Since we lose info anyway on 16-bit data, we set up a 14-bit
* table and shift 16-bit values down two bits on input.
* saves a little table space.
*/
j = 0;
for (i = 0; i < 16384; i++) {
while ((i/16383.)*(i/16383.) > ToLinearF[j]*ToLinearF[j+1])
j++;
From14[i] = (uint16)j;
}
j = 0;
for (i = 0; i < 256; i++) {
while ((i/255.)*(i/255.) > ToLinearF[j]*ToLinearF[j+1])
j++;
From8[i] = (uint16)j;
}
Fltsize = (float)(lt2size/2);
sp->ToLinearF = ToLinearF;
sp->ToLinear16 = ToLinear16;
sp->ToLinear8 = ToLinear8;
sp->FromLT2 = FromLT2;
sp->From14 = From14;
sp->From8 = From8;
return 1;
}
#define DecoderState(tif) ((PixarLogState*) (tif)->tif_data)
#define EncoderState(tif) ((PixarLogState*) (tif)->tif_data)
static int PixarLogEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s);
static int PixarLogDecode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s);
#define PIXARLOGDATAFMT_UNKNOWN -1
static int
PixarLogGuessDataFmt(TIFFDirectory *td)
{
int guess = PIXARLOGDATAFMT_UNKNOWN;
int format = td->td_sampleformat;
/* If the user didn't tell us his datafmt,
* take our best guess from the bitspersample.
*/
switch (td->td_bitspersample) {
case 32:
if (format == SAMPLEFORMAT_IEEEFP)
guess = PIXARLOGDATAFMT_FLOAT;
break;
case 16:
if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT)
guess = PIXARLOGDATAFMT_16BIT;
break;
case 12:
if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_INT)
guess = PIXARLOGDATAFMT_12BITPICIO;
break;
case 11:
if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT)
guess = PIXARLOGDATAFMT_11BITLOG;
break;
case 8:
if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT)
guess = PIXARLOGDATAFMT_8BIT;
break;
}
return guess;
}
static tmsize_t
multiply_ms(tmsize_t m1, tmsize_t m2)
{
tmsize_t bytes = m1 * m2;
if (m1 && bytes / m1 != m2)
bytes = 0;
return bytes;
}
static tmsize_t
add_ms(tmsize_t m1, tmsize_t m2)
{
tmsize_t bytes = m1 + m2;
/* if either input is zero, assume overflow already occurred */
if (m1 == 0 || m2 == 0)
bytes = 0;
else if (bytes <= m1 || bytes <= m2)
bytes = 0;
return bytes;
}
static int
PixarLogFixupTags(TIFF* tif)
{
(void) tif;
return (1);
}
static int
PixarLogSetupDecode(TIFF* tif)
{
static const char module[] = "PixarLogSetupDecode";
TIFFDirectory *td = &tif->tif_dir;
PixarLogState* sp = DecoderState(tif);
tmsize_t tbuf_size;
assert(sp != NULL);
/* Make sure no byte swapping happens on the data
* after decompression. */
tif->tif_postdecode = _TIFFNoPostDecode;
/* for some reason, we can't do this in TIFFInitPixarLog */
sp->stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ?
td->td_samplesperpixel : 1);
tbuf_size = multiply_ms(multiply_ms(multiply_ms(sp->stride, td->td_imagewidth),
td->td_rowsperstrip), sizeof(uint16));
/* add one more stride in case input ends mid-stride */
tbuf_size = add_ms(tbuf_size, sizeof(uint16) * sp->stride);
if (tbuf_size == 0)
return (0); /* TODO: this is an error return without error report through TIFFErrorExt */
sp->tbuf = (uint16 *) _TIFFmalloc(tbuf_size);
if (sp->tbuf == NULL)
return (0);
sp->tbuf_size = tbuf_size;
if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN)
sp->user_datafmt = PixarLogGuessDataFmt(td);
if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) {
TIFFErrorExt(tif->tif_clientdata, module,
"PixarLog compression can't handle bits depth/data format combination (depth: %d)",
td->td_bitspersample);
return (0);
}
if (inflateInit(&sp->stream) != Z_OK) {
TIFFErrorExt(tif->tif_clientdata, module, "%s", sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
} else {
sp->state |= PLSTATE_INIT;
return (1);
}
}
/*
* Setup state for decoding a strip.
*/
static int
PixarLogPreDecode(TIFF* tif, uint16 s)
{
static const char module[] = "PixarLogPreDecode";
PixarLogState* sp = DecoderState(tif);
(void) s;
assert(sp != NULL);
sp->stream.next_in = tif->tif_rawdata;
assert(sizeof(sp->stream.avail_in)==4); /* if this assert gets raised,
we need to simplify this code to reflect a ZLib that is likely updated
to deal with 8byte memory sizes, though this code will respond
appropriately even before we simplify it */
sp->stream.avail_in = (uInt) tif->tif_rawcc;
if ((tmsize_t)sp->stream.avail_in != tif->tif_rawcc)
{
TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size");
return (0);
}
return (inflateReset(&sp->stream) == Z_OK);
}
static int
PixarLogDecode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s)
{
static const char module[] = "PixarLogDecode";
TIFFDirectory *td = &tif->tif_dir;
PixarLogState* sp = DecoderState(tif);
tmsize_t i;
tmsize_t nsamples;
int llen;
uint16 *up;
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_FLOAT:
nsamples = occ / sizeof(float); /* XXX float == 32 bits */
break;
case PIXARLOGDATAFMT_16BIT:
case PIXARLOGDATAFMT_12BITPICIO:
case PIXARLOGDATAFMT_11BITLOG:
nsamples = occ / sizeof(uint16); /* XXX uint16 == 16 bits */
break;
case PIXARLOGDATAFMT_8BIT:
case PIXARLOGDATAFMT_8BITABGR:
nsamples = occ;
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"%d bit input not supported in PixarLog",
td->td_bitspersample);
return 0;
}
llen = sp->stride * td->td_imagewidth;
(void) s;
assert(sp != NULL);
sp->stream.next_out = (unsigned char *) sp->tbuf;
assert(sizeof(sp->stream.avail_out)==4); /* if this assert gets raised,
we need to simplify this code to reflect a ZLib that is likely updated
to deal with 8byte memory sizes, though this code will respond
appropriately even before we simplify it */
sp->stream.avail_out = (uInt) (nsamples * sizeof(uint16));
if (sp->stream.avail_out != nsamples * sizeof(uint16))
{
TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size");
return (0);
}
/* Check that we will not fill more than what was allocated */
if ((tmsize_t)sp->stream.avail_out > sp->tbuf_size)
{
TIFFErrorExt(tif->tif_clientdata, module, "sp->stream.avail_out > sp->tbuf_size");
return (0);
}
do {
int state = inflate(&sp->stream, Z_PARTIAL_FLUSH);
if (state == Z_STREAM_END) {
break; /* XXX */
}
if (state == Z_DATA_ERROR) {
TIFFErrorExt(tif->tif_clientdata, module,
"Decoding error at scanline %lu, %s",
(unsigned long) tif->tif_row, sp->stream.msg ? sp->stream.msg : "(null)");
if (inflateSync(&sp->stream) != Z_OK)
return (0);
continue;
}
if (state != Z_OK) {
TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s",
sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
}
} while (sp->stream.avail_out > 0);
/* hopefully, we got all the bytes we needed */
if (sp->stream.avail_out != 0) {
TIFFErrorExt(tif->tif_clientdata, module,
"Not enough data at scanline %lu (short " TIFF_UINT64_FORMAT " bytes)",
(unsigned long) tif->tif_row, (TIFF_UINT64_T) sp->stream.avail_out);
return (0);
}
up = sp->tbuf;
/* Swap bytes in the data if from a different endian machine. */
if (tif->tif_flags & TIFF_SWAB)
TIFFSwabArrayOfShort(up, nsamples);
/*
* if llen is not an exact multiple of nsamples, the decode operation
* may overflow the output buffer, so truncate it enough to prevent
* that but still salvage as much data as possible.
*/
if (nsamples % llen) {
TIFFWarningExt(tif->tif_clientdata, module,
"stride %lu is not a multiple of sample count, "
"%lu, data truncated.", (unsigned long) llen, (unsigned long) nsamples);
nsamples -= nsamples % llen;
}
for (i = 0; i < nsamples; i += llen, up += llen) {
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_FLOAT:
horizontalAccumulateF(up, llen, sp->stride,
(float *)op, sp->ToLinearF);
op += llen * sizeof(float);
break;
case PIXARLOGDATAFMT_16BIT:
horizontalAccumulate16(up, llen, sp->stride,
(uint16 *)op, sp->ToLinear16);
op += llen * sizeof(uint16);
break;
case PIXARLOGDATAFMT_12BITPICIO:
horizontalAccumulate12(up, llen, sp->stride,
(int16 *)op, sp->ToLinearF);
op += llen * sizeof(int16);
break;
case PIXARLOGDATAFMT_11BITLOG:
horizontalAccumulate11(up, llen, sp->stride,
(uint16 *)op);
op += llen * sizeof(uint16);
break;
case PIXARLOGDATAFMT_8BIT:
horizontalAccumulate8(up, llen, sp->stride,
(unsigned char *)op, sp->ToLinear8);
op += llen * sizeof(unsigned char);
break;
case PIXARLOGDATAFMT_8BITABGR:
horizontalAccumulate8abgr(up, llen, sp->stride,
(unsigned char *)op, sp->ToLinear8);
op += llen * sizeof(unsigned char);
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"Unsupported bits/sample: %d",
td->td_bitspersample);
return (0);
}
}
return (1);
}
static int
PixarLogSetupEncode(TIFF* tif)
{
static const char module[] = "PixarLogSetupEncode";
TIFFDirectory *td = &tif->tif_dir;
PixarLogState* sp = EncoderState(tif);
tmsize_t tbuf_size;
assert(sp != NULL);
/* for some reason, we can't do this in TIFFInitPixarLog */
sp->stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ?
td->td_samplesperpixel : 1);
tbuf_size = multiply_ms(multiply_ms(multiply_ms(sp->stride, td->td_imagewidth),
td->td_rowsperstrip), sizeof(uint16));
if (tbuf_size == 0)
return (0); /* TODO: this is an error return without error report through TIFFErrorExt */
sp->tbuf = (uint16 *) _TIFFmalloc(tbuf_size);
if (sp->tbuf == NULL)
return (0);
if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN)
sp->user_datafmt = PixarLogGuessDataFmt(td);
if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) {
TIFFErrorExt(tif->tif_clientdata, module, "PixarLog compression can't handle %d bit linear encodings", td->td_bitspersample);
return (0);
}
if (deflateInit(&sp->stream, sp->quality) != Z_OK) {
TIFFErrorExt(tif->tif_clientdata, module, "%s", sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
} else {
sp->state |= PLSTATE_INIT;
return (1);
}
}
/*
* Reset encoding state at the start of a strip.
*/
static int
PixarLogPreEncode(TIFF* tif, uint16 s)
{
static const char module[] = "PixarLogPreEncode";
PixarLogState *sp = EncoderState(tif);
(void) s;
assert(sp != NULL);
sp->stream.next_out = tif->tif_rawdata;
assert(sizeof(sp->stream.avail_out)==4); /* if this assert gets raised,
we need to simplify this code to reflect a ZLib that is likely updated
to deal with 8byte memory sizes, though this code will respond
appropriately even before we simplify it */
sp->stream.avail_out = (uInt)tif->tif_rawdatasize;
if ((tmsize_t)sp->stream.avail_out != tif->tif_rawdatasize)
{
TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size");
return (0);
}
return (deflateReset(&sp->stream) == Z_OK);
}
static void
horizontalDifferenceF(float *ip, int n, int stride, uint16 *wp, uint16 *FromLT2)
{
int32 r1, g1, b1, a1, r2, g2, b2, a2, mask;
float fltsize = Fltsize;
#define CLAMP(v) ( (v<(float)0.) ? 0 \
: (v<(float)2.) ? FromLT2[(int)(v*fltsize)] \
: (v>(float)24.2) ? 2047 \
: LogK1*log(v*LogK2) + 0.5 )
mask = CODE_MASK;
if (n >= stride) {
if (stride == 3) {
r2 = wp[0] = (uint16) CLAMP(ip[0]);
g2 = wp[1] = (uint16) CLAMP(ip[1]);
b2 = wp[2] = (uint16) CLAMP(ip[2]);
n -= 3;
while (n > 0) {
n -= 3;
wp += 3;
ip += 3;
r1 = (int32) CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = (int32) CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = (int32) CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
}
} else if (stride == 4) {
r2 = wp[0] = (uint16) CLAMP(ip[0]);
g2 = wp[1] = (uint16) CLAMP(ip[1]);
b2 = wp[2] = (uint16) CLAMP(ip[2]);
a2 = wp[3] = (uint16) CLAMP(ip[3]);
n -= 4;
while (n > 0) {
n -= 4;
wp += 4;
ip += 4;
r1 = (int32) CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = (int32) CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = (int32) CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
a1 = (int32) CLAMP(ip[3]); wp[3] = (uint16)((a1-a2) & mask); a2 = a1;
}
} else {
ip += n - 1; /* point to last one */
wp += n - 1; /* point to last one */
n -= stride;
while (n > 0) {
REPEAT(stride, wp[0] = (uint16) CLAMP(ip[0]);
wp[stride] -= wp[0];
wp[stride] &= mask;
wp--; ip--)
n -= stride;
}
REPEAT(stride, wp[0] = (uint16) CLAMP(ip[0]); wp--; ip--)
}
}
}
static void
horizontalDifference16(unsigned short *ip, int n, int stride,
unsigned short *wp, uint16 *From14)
{
register int r1, g1, b1, a1, r2, g2, b2, a2, mask;
/* assumption is unsigned pixel values */
#undef CLAMP
#define CLAMP(v) From14[(v) >> 2]
mask = CODE_MASK;
if (n >= stride) {
if (stride == 3) {
r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);
b2 = wp[2] = CLAMP(ip[2]);
n -= 3;
while (n > 0) {
n -= 3;
wp += 3;
ip += 3;
r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
}
} else if (stride == 4) {
r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);
b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]);
n -= 4;
while (n > 0) {
n -= 4;
wp += 4;
ip += 4;
r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
a1 = CLAMP(ip[3]); wp[3] = (uint16)((a1-a2) & mask); a2 = a1;
}
} else {
ip += n - 1; /* point to last one */
wp += n - 1; /* point to last one */
n -= stride;
while (n > 0) {
REPEAT(stride, wp[0] = CLAMP(ip[0]);
wp[stride] -= wp[0];
wp[stride] &= mask;
wp--; ip--)
n -= stride;
}
REPEAT(stride, wp[0] = CLAMP(ip[0]); wp--; ip--)
}
}
}
static void
horizontalDifference8(unsigned char *ip, int n, int stride,
unsigned short *wp, uint16 *From8)
{
register int r1, g1, b1, a1, r2, g2, b2, a2, mask;
#undef CLAMP
#define CLAMP(v) (From8[(v)])
mask = CODE_MASK;
if (n >= stride) {
if (stride == 3) {
r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);
b2 = wp[2] = CLAMP(ip[2]);
n -= 3;
while (n > 0) {
n -= 3;
r1 = CLAMP(ip[3]); wp[3] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = CLAMP(ip[4]); wp[4] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = CLAMP(ip[5]); wp[5] = (uint16)((b1-b2) & mask); b2 = b1;
wp += 3;
ip += 3;
}
} else if (stride == 4) {
r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);
b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]);
n -= 4;
while (n > 0) {
n -= 4;
r1 = CLAMP(ip[4]); wp[4] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = CLAMP(ip[5]); wp[5] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = CLAMP(ip[6]); wp[6] = (uint16)((b1-b2) & mask); b2 = b1;
a1 = CLAMP(ip[7]); wp[7] = (uint16)((a1-a2) & mask); a2 = a1;
wp += 4;
ip += 4;
}
} else {
wp += n + stride - 1; /* point to last one */
ip += n + stride - 1; /* point to last one */
n -= stride;
while (n > 0) {
REPEAT(stride, wp[0] = CLAMP(ip[0]);
wp[stride] -= wp[0];
wp[stride] &= mask;
wp--; ip--)
n -= stride;
}
REPEAT(stride, wp[0] = CLAMP(ip[0]); wp--; ip--)
}
}
}
/*
* Encode a chunk of pixels.
*/
static int
PixarLogEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
{
static const char module[] = "PixarLogEncode";
TIFFDirectory *td = &tif->tif_dir;
PixarLogState *sp = EncoderState(tif);
tmsize_t i;
tmsize_t n;
int llen;
unsigned short * up;
(void) s;
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_FLOAT:
n = cc / sizeof(float); /* XXX float == 32 bits */
break;
case PIXARLOGDATAFMT_16BIT:
case PIXARLOGDATAFMT_12BITPICIO:
case PIXARLOGDATAFMT_11BITLOG:
n = cc / sizeof(uint16); /* XXX uint16 == 16 bits */
break;
case PIXARLOGDATAFMT_8BIT:
case PIXARLOGDATAFMT_8BITABGR:
n = cc;
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"%d bit input not supported in PixarLog",
td->td_bitspersample);
return 0;
}
llen = sp->stride * td->td_imagewidth;
/* Check against the number of elements (of size uint16) of sp->tbuf */
if( n > (tmsize_t)(td->td_rowsperstrip * llen) )
{
TIFFErrorExt(tif->tif_clientdata, module,
"Too many input bytes provided");
return 0;
}
for (i = 0, up = sp->tbuf; i < n; i += llen, up += llen) {
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_FLOAT:
horizontalDifferenceF((float *)bp, llen,
sp->stride, up, sp->FromLT2);
bp += llen * sizeof(float);
break;
case PIXARLOGDATAFMT_16BIT:
horizontalDifference16((uint16 *)bp, llen,
sp->stride, up, sp->From14);
bp += llen * sizeof(uint16);
break;
case PIXARLOGDATAFMT_8BIT:
horizontalDifference8((unsigned char *)bp, llen,
sp->stride, up, sp->From8);
bp += llen * sizeof(unsigned char);
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"%d bit input not supported in PixarLog",
td->td_bitspersample);
return 0;
}
}
sp->stream.next_in = (unsigned char *) sp->tbuf;
assert(sizeof(sp->stream.avail_in)==4); /* if this assert gets raised,
we need to simplify this code to reflect a ZLib that is likely updated
to deal with 8byte memory sizes, though this code will respond
appropriately even before we simplify it */
sp->stream.avail_in = (uInt) (n * sizeof(uint16));
if ((sp->stream.avail_in / sizeof(uint16)) != (uInt) n)
{
TIFFErrorExt(tif->tif_clientdata, module,
"ZLib cannot deal with buffers this size");
return (0);
}
do {
if (deflate(&sp->stream, Z_NO_FLUSH) != Z_OK) {
TIFFErrorExt(tif->tif_clientdata, module, "Encoder error: %s",
sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
}
if (sp->stream.avail_out == 0) {
tif->tif_rawcc = tif->tif_rawdatasize;
TIFFFlushData1(tif);
sp->stream.next_out = tif->tif_rawdata;
sp->stream.avail_out = (uInt) tif->tif_rawdatasize; /* this is a safe typecast, as check is made already in PixarLogPreEncode */
}
} while (sp->stream.avail_in > 0);
return (1);
}
/*
* Finish off an encoded strip by flushing the last
* string and tacking on an End Of Information code.
*/
static int
PixarLogPostEncode(TIFF* tif)
{
static const char module[] = "PixarLogPostEncode";
PixarLogState *sp = EncoderState(tif);
int state;
sp->stream.avail_in = 0;
do {
state = deflate(&sp->stream, Z_FINISH);
switch (state) {
case Z_STREAM_END:
case Z_OK:
if ((tmsize_t)sp->stream.avail_out != tif->tif_rawdatasize) {
tif->tif_rawcc =
tif->tif_rawdatasize - sp->stream.avail_out;
TIFFFlushData1(tif);
sp->stream.next_out = tif->tif_rawdata;
sp->stream.avail_out = (uInt) tif->tif_rawdatasize; /* this is a safe typecast, as check is made already in PixarLogPreEncode */
}
break;
default:
TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s",
sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
}
} while (state != Z_STREAM_END);
return (1);
}
static void
PixarLogClose(TIFF* tif)
{
TIFFDirectory *td = &tif->tif_dir;
/* In a really sneaky (and really incorrect, and untruthful, and
* troublesome, and error-prone) maneuver that completely goes against
* the spirit of TIFF, and breaks TIFF, on close, we covertly
* modify both bitspersample and sampleformat in the directory to
* indicate 8-bit linear. This way, the decode "just works" even for
* readers that don't know about PixarLog, or how to set
* the PIXARLOGDATFMT pseudo-tag.
*/
td->td_bitspersample = 8;
td->td_sampleformat = SAMPLEFORMAT_UINT;
}
static void
PixarLogCleanup(TIFF* tif)
{
PixarLogState* sp = (PixarLogState*) tif->tif_data;
assert(sp != 0);
(void)TIFFPredictorCleanup(tif);
tif->tif_tagmethods.vgetfield = sp->vgetparent;
tif->tif_tagmethods.vsetfield = sp->vsetparent;
if (sp->FromLT2) _TIFFfree(sp->FromLT2);
if (sp->From14) _TIFFfree(sp->From14);
if (sp->From8) _TIFFfree(sp->From8);
if (sp->ToLinearF) _TIFFfree(sp->ToLinearF);
if (sp->ToLinear16) _TIFFfree(sp->ToLinear16);
if (sp->ToLinear8) _TIFFfree(sp->ToLinear8);
if (sp->state&PLSTATE_INIT) {
if (tif->tif_mode == O_RDONLY)
inflateEnd(&sp->stream);
else
deflateEnd(&sp->stream);
}
if (sp->tbuf)
_TIFFfree(sp->tbuf);
_TIFFfree(sp);
tif->tif_data = NULL;
_TIFFSetDefaultCompressionState(tif);
}
static int
PixarLogVSetField(TIFF* tif, uint32 tag, va_list ap)
{
static const char module[] = "PixarLogVSetField";
PixarLogState *sp = (PixarLogState *)tif->tif_data;
int result;
switch (tag) {
case TIFFTAG_PIXARLOGQUALITY:
sp->quality = (int) va_arg(ap, int);
if (tif->tif_mode != O_RDONLY && (sp->state&PLSTATE_INIT)) {
if (deflateParams(&sp->stream,
sp->quality, Z_DEFAULT_STRATEGY) != Z_OK) {
TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s",
sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
}
}
return (1);
case TIFFTAG_PIXARLOGDATAFMT:
sp->user_datafmt = (int) va_arg(ap, int);
/* Tweak the TIFF header so that the rest of libtiff knows what
* size of data will be passed between app and library, and
* assume that the app knows what it is doing and is not
* confused by these header manipulations...
*/
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_8BIT:
case PIXARLOGDATAFMT_8BITABGR:
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 8);
TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
break;
case PIXARLOGDATAFMT_11BITLOG:
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16);
TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
break;
case PIXARLOGDATAFMT_12BITPICIO:
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16);
TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_INT);
break;
case PIXARLOGDATAFMT_16BIT:
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16);
TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
break;
case PIXARLOGDATAFMT_FLOAT:
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 32);
TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP);
break;
}
/*
* Must recalculate sizes should bits/sample change.
*/
tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tmsize_t)(-1);
tif->tif_scanlinesize = TIFFScanlineSize(tif);
result = 1; /* NB: pseudo tag */
break;
default:
result = (*sp->vsetparent)(tif, tag, ap);
}
return (result);
}
static int
PixarLogVGetField(TIFF* tif, uint32 tag, va_list ap)
{
PixarLogState *sp = (PixarLogState *)tif->tif_data;
switch (tag) {
case TIFFTAG_PIXARLOGQUALITY:
*va_arg(ap, int*) = sp->quality;
break;
case TIFFTAG_PIXARLOGDATAFMT:
*va_arg(ap, int*) = sp->user_datafmt;
break;
default:
return (*sp->vgetparent)(tif, tag, ap);
}
return (1);
}
static const TIFFField pixarlogFields[] = {
{TIFFTAG_PIXARLOGDATAFMT, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL},
{TIFFTAG_PIXARLOGQUALITY, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL}
};
int
TIFFInitPixarLog(TIFF* tif, int scheme)
{
static const char module[] = "TIFFInitPixarLog";
PixarLogState* sp;
assert(scheme == COMPRESSION_PIXARLOG);
/*
* Merge codec-specific tag information.
*/
if (!_TIFFMergeFields(tif, pixarlogFields,
TIFFArrayCount(pixarlogFields))) {
TIFFErrorExt(tif->tif_clientdata, module,
"Merging PixarLog codec-specific tags failed");
return 0;
}
/*
* Allocate state block so tag methods have storage to record values.
*/
tif->tif_data = (uint8*) _TIFFmalloc(sizeof (PixarLogState));
if (tif->tif_data == NULL)
goto bad;
sp = (PixarLogState*) tif->tif_data;
_TIFFmemset(sp, 0, sizeof (*sp));
sp->stream.data_type = Z_BINARY;
sp->user_datafmt = PIXARLOGDATAFMT_UNKNOWN;
/*
* Install codec methods.
*/
tif->tif_fixuptags = PixarLogFixupTags;
tif->tif_setupdecode = PixarLogSetupDecode;
tif->tif_predecode = PixarLogPreDecode;
tif->tif_decoderow = PixarLogDecode;
tif->tif_decodestrip = PixarLogDecode;
tif->tif_decodetile = PixarLogDecode;
tif->tif_setupencode = PixarLogSetupEncode;
tif->tif_preencode = PixarLogPreEncode;
tif->tif_postencode = PixarLogPostEncode;
tif->tif_encoderow = PixarLogEncode;
tif->tif_encodestrip = PixarLogEncode;
tif->tif_encodetile = PixarLogEncode;
tif->tif_close = PixarLogClose;
tif->tif_cleanup = PixarLogCleanup;
/* Override SetField so we can handle our private pseudo-tag */
sp->vgetparent = tif->tif_tagmethods.vgetfield;
tif->tif_tagmethods.vgetfield = PixarLogVGetField; /* hook for codec tags */
sp->vsetparent = tif->tif_tagmethods.vsetfield;
tif->tif_tagmethods.vsetfield = PixarLogVSetField; /* hook for codec tags */
/* Default values for codec-specific fields */
sp->quality = Z_DEFAULT_COMPRESSION; /* default comp. level */
sp->state = 0;
/* we don't wish to use the predictor,
* the default is none, which predictor value 1
*/
(void) TIFFPredictorInit(tif);
/*
* build the companding tables
*/
PixarLogMakeTables(sp);
return (1);
bad:
TIFFErrorExt(tif->tif_clientdata, module,
"No space for PixarLog state block");
return (0);
}
#endif /* PIXARLOG_SUPPORT */
/* 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-787/c/bad_5479_1 |
crossvul-cpp_data_bad_2457_0 | // SPDX-License-Identifier: GPL-2.0-only
/*
* Simple NUMA memory policy for the Linux kernel.
*
* Copyright 2003,2004 Andi Kleen, SuSE Labs.
* (C) Copyright 2005 Christoph Lameter, Silicon Graphics, Inc.
*
* NUMA policy allows the user to give hints in which node(s) memory should
* be allocated.
*
* Support four policies per VMA and per process:
*
* The VMA policy has priority over the process policy for a page fault.
*
* interleave Allocate memory interleaved over a set of nodes,
* with normal fallback if it fails.
* For VMA based allocations this interleaves based on the
* offset into the backing object or offset into the mapping
* for anonymous memory. For process policy an process counter
* is used.
*
* bind Only allocate memory on a specific set of nodes,
* no fallback.
* FIXME: memory is allocated starting with the first node
* to the last. It would be better if bind would truly restrict
* the allocation to memory nodes instead
*
* preferred Try a specific node first before normal fallback.
* As a special case NUMA_NO_NODE here means do the allocation
* on the local CPU. This is normally identical to default,
* but useful to set in a VMA when you have a non default
* process policy.
*
* default Allocate on the local node first, or when on a VMA
* use the process policy. This is what Linux always did
* in a NUMA aware kernel and still does by, ahem, default.
*
* The process policy is applied for most non interrupt memory allocations
* in that process' context. Interrupts ignore the policies and always
* try to allocate on the local CPU. The VMA policy is only applied for memory
* allocations for a VMA in the VM.
*
* Currently there are a few corner cases in swapping where the policy
* is not applied, but the majority should be handled. When process policy
* is used it is not remembered over swap outs/swap ins.
*
* Only the highest zone in the zone hierarchy gets policied. Allocations
* requesting a lower zone just use default policy. This implies that
* on systems with highmem kernel lowmem allocation don't get policied.
* Same with GFP_DMA allocations.
*
* For shmfs/tmpfs/hugetlbfs shared memory the policy is shared between
* all users and remembered even when nobody has memory mapped.
*/
/* Notebook:
fix mmap readahead to honour policy and enable policy for any page cache
object
statistics for bigpages
global policy for page cache? currently it uses process policy. Requires
first item above.
handle mremap for shared memory (currently ignored for the policy)
grows down?
make bind policy root only? It can trigger oom much faster and the
kernel is not always grateful with that.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/mempolicy.h>
#include <linux/pagewalk.h>
#include <linux/highmem.h>
#include <linux/hugetlb.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/sched/mm.h>
#include <linux/sched/numa_balancing.h>
#include <linux/sched/task.h>
#include <linux/nodemask.h>
#include <linux/cpuset.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/export.h>
#include <linux/nsproxy.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/compat.h>
#include <linux/ptrace.h>
#include <linux/swap.h>
#include <linux/seq_file.h>
#include <linux/proc_fs.h>
#include <linux/migrate.h>
#include <linux/ksm.h>
#include <linux/rmap.h>
#include <linux/security.h>
#include <linux/syscalls.h>
#include <linux/ctype.h>
#include <linux/mm_inline.h>
#include <linux/mmu_notifier.h>
#include <linux/printk.h>
#include <linux/swapops.h>
#include <asm/tlbflush.h>
#include <linux/uaccess.h>
#include "internal.h"
/* Internal flags */
#define MPOL_MF_DISCONTIG_OK (MPOL_MF_INTERNAL << 0) /* Skip checks for continuous vmas */
#define MPOL_MF_INVERT (MPOL_MF_INTERNAL << 1) /* Invert check for nodemask */
static struct kmem_cache *policy_cache;
static struct kmem_cache *sn_cache;
/* Highest zone. An specific allocation for a zone below that is not
policied. */
enum zone_type policy_zone = 0;
/*
* run-time system-wide default policy => local allocation
*/
static struct mempolicy default_policy = {
.refcnt = ATOMIC_INIT(1), /* never free it */
.mode = MPOL_PREFERRED,
.flags = MPOL_F_LOCAL,
};
static struct mempolicy preferred_node_policy[MAX_NUMNODES];
struct mempolicy *get_task_policy(struct task_struct *p)
{
struct mempolicy *pol = p->mempolicy;
int node;
if (pol)
return pol;
node = numa_node_id();
if (node != NUMA_NO_NODE) {
pol = &preferred_node_policy[node];
/* preferred_node_policy is not initialised early in boot */
if (pol->mode)
return pol;
}
return &default_policy;
}
static const struct mempolicy_operations {
int (*create)(struct mempolicy *pol, const nodemask_t *nodes);
void (*rebind)(struct mempolicy *pol, const nodemask_t *nodes);
} mpol_ops[MPOL_MAX];
static inline int mpol_store_user_nodemask(const struct mempolicy *pol)
{
return pol->flags & MPOL_MODE_FLAGS;
}
static void mpol_relative_nodemask(nodemask_t *ret, const nodemask_t *orig,
const nodemask_t *rel)
{
nodemask_t tmp;
nodes_fold(tmp, *orig, nodes_weight(*rel));
nodes_onto(*ret, tmp, *rel);
}
static int mpol_new_interleave(struct mempolicy *pol, const nodemask_t *nodes)
{
if (nodes_empty(*nodes))
return -EINVAL;
pol->v.nodes = *nodes;
return 0;
}
static int mpol_new_preferred(struct mempolicy *pol, const nodemask_t *nodes)
{
if (!nodes)
pol->flags |= MPOL_F_LOCAL; /* local allocation */
else if (nodes_empty(*nodes))
return -EINVAL; /* no allowed nodes */
else
pol->v.preferred_node = first_node(*nodes);
return 0;
}
static int mpol_new_bind(struct mempolicy *pol, const nodemask_t *nodes)
{
if (nodes_empty(*nodes))
return -EINVAL;
pol->v.nodes = *nodes;
return 0;
}
/*
* mpol_set_nodemask is called after mpol_new() to set up the nodemask, if
* any, for the new policy. mpol_new() has already validated the nodes
* parameter with respect to the policy mode and flags. But, we need to
* handle an empty nodemask with MPOL_PREFERRED here.
*
* Must be called holding task's alloc_lock to protect task's mems_allowed
* and mempolicy. May also be called holding the mmap_semaphore for write.
*/
static int mpol_set_nodemask(struct mempolicy *pol,
const nodemask_t *nodes, struct nodemask_scratch *nsc)
{
int ret;
/* if mode is MPOL_DEFAULT, pol is NULL. This is right. */
if (pol == NULL)
return 0;
/* Check N_MEMORY */
nodes_and(nsc->mask1,
cpuset_current_mems_allowed, node_states[N_MEMORY]);
VM_BUG_ON(!nodes);
if (pol->mode == MPOL_PREFERRED && nodes_empty(*nodes))
nodes = NULL; /* explicit local allocation */
else {
if (pol->flags & MPOL_F_RELATIVE_NODES)
mpol_relative_nodemask(&nsc->mask2, nodes, &nsc->mask1);
else
nodes_and(nsc->mask2, *nodes, nsc->mask1);
if (mpol_store_user_nodemask(pol))
pol->w.user_nodemask = *nodes;
else
pol->w.cpuset_mems_allowed =
cpuset_current_mems_allowed;
}
if (nodes)
ret = mpol_ops[pol->mode].create(pol, &nsc->mask2);
else
ret = mpol_ops[pol->mode].create(pol, NULL);
return ret;
}
/*
* This function just creates a new policy, does some check and simple
* initialization. You must invoke mpol_set_nodemask() to set nodes.
*/
static struct mempolicy *mpol_new(unsigned short mode, unsigned short flags,
nodemask_t *nodes)
{
struct mempolicy *policy;
pr_debug("setting mode %d flags %d nodes[0] %lx\n",
mode, flags, nodes ? nodes_addr(*nodes)[0] : NUMA_NO_NODE);
if (mode == MPOL_DEFAULT) {
if (nodes && !nodes_empty(*nodes))
return ERR_PTR(-EINVAL);
return NULL;
}
VM_BUG_ON(!nodes);
/*
* MPOL_PREFERRED cannot be used with MPOL_F_STATIC_NODES or
* MPOL_F_RELATIVE_NODES if the nodemask is empty (local allocation).
* All other modes require a valid pointer to a non-empty nodemask.
*/
if (mode == MPOL_PREFERRED) {
if (nodes_empty(*nodes)) {
if (((flags & MPOL_F_STATIC_NODES) ||
(flags & MPOL_F_RELATIVE_NODES)))
return ERR_PTR(-EINVAL);
}
} else if (mode == MPOL_LOCAL) {
if (!nodes_empty(*nodes) ||
(flags & MPOL_F_STATIC_NODES) ||
(flags & MPOL_F_RELATIVE_NODES))
return ERR_PTR(-EINVAL);
mode = MPOL_PREFERRED;
} else if (nodes_empty(*nodes))
return ERR_PTR(-EINVAL);
policy = kmem_cache_alloc(policy_cache, GFP_KERNEL);
if (!policy)
return ERR_PTR(-ENOMEM);
atomic_set(&policy->refcnt, 1);
policy->mode = mode;
policy->flags = flags;
return policy;
}
/* Slow path of a mpol destructor. */
void __mpol_put(struct mempolicy *p)
{
if (!atomic_dec_and_test(&p->refcnt))
return;
kmem_cache_free(policy_cache, p);
}
static void mpol_rebind_default(struct mempolicy *pol, const nodemask_t *nodes)
{
}
static void mpol_rebind_nodemask(struct mempolicy *pol, const nodemask_t *nodes)
{
nodemask_t tmp;
if (pol->flags & MPOL_F_STATIC_NODES)
nodes_and(tmp, pol->w.user_nodemask, *nodes);
else if (pol->flags & MPOL_F_RELATIVE_NODES)
mpol_relative_nodemask(&tmp, &pol->w.user_nodemask, nodes);
else {
nodes_remap(tmp, pol->v.nodes,pol->w.cpuset_mems_allowed,
*nodes);
pol->w.cpuset_mems_allowed = *nodes;
}
if (nodes_empty(tmp))
tmp = *nodes;
pol->v.nodes = tmp;
}
static void mpol_rebind_preferred(struct mempolicy *pol,
const nodemask_t *nodes)
{
nodemask_t tmp;
if (pol->flags & MPOL_F_STATIC_NODES) {
int node = first_node(pol->w.user_nodemask);
if (node_isset(node, *nodes)) {
pol->v.preferred_node = node;
pol->flags &= ~MPOL_F_LOCAL;
} else
pol->flags |= MPOL_F_LOCAL;
} else if (pol->flags & MPOL_F_RELATIVE_NODES) {
mpol_relative_nodemask(&tmp, &pol->w.user_nodemask, nodes);
pol->v.preferred_node = first_node(tmp);
} else if (!(pol->flags & MPOL_F_LOCAL)) {
pol->v.preferred_node = node_remap(pol->v.preferred_node,
pol->w.cpuset_mems_allowed,
*nodes);
pol->w.cpuset_mems_allowed = *nodes;
}
}
/*
* mpol_rebind_policy - Migrate a policy to a different set of nodes
*
* Per-vma policies are protected by mmap_sem. Allocations using per-task
* policies are protected by task->mems_allowed_seq to prevent a premature
* OOM/allocation failure due to parallel nodemask modification.
*/
static void mpol_rebind_policy(struct mempolicy *pol, const nodemask_t *newmask)
{
if (!pol)
return;
if (!mpol_store_user_nodemask(pol) && !(pol->flags & MPOL_F_LOCAL) &&
nodes_equal(pol->w.cpuset_mems_allowed, *newmask))
return;
mpol_ops[pol->mode].rebind(pol, newmask);
}
/*
* Wrapper for mpol_rebind_policy() that just requires task
* pointer, and updates task mempolicy.
*
* Called with task's alloc_lock held.
*/
void mpol_rebind_task(struct task_struct *tsk, const nodemask_t *new)
{
mpol_rebind_policy(tsk->mempolicy, new);
}
/*
* Rebind each vma in mm to new nodemask.
*
* Call holding a reference to mm. Takes mm->mmap_sem during call.
*/
void mpol_rebind_mm(struct mm_struct *mm, nodemask_t *new)
{
struct vm_area_struct *vma;
down_write(&mm->mmap_sem);
for (vma = mm->mmap; vma; vma = vma->vm_next)
mpol_rebind_policy(vma->vm_policy, new);
up_write(&mm->mmap_sem);
}
static const struct mempolicy_operations mpol_ops[MPOL_MAX] = {
[MPOL_DEFAULT] = {
.rebind = mpol_rebind_default,
},
[MPOL_INTERLEAVE] = {
.create = mpol_new_interleave,
.rebind = mpol_rebind_nodemask,
},
[MPOL_PREFERRED] = {
.create = mpol_new_preferred,
.rebind = mpol_rebind_preferred,
},
[MPOL_BIND] = {
.create = mpol_new_bind,
.rebind = mpol_rebind_nodemask,
},
};
static int migrate_page_add(struct page *page, struct list_head *pagelist,
unsigned long flags);
struct queue_pages {
struct list_head *pagelist;
unsigned long flags;
nodemask_t *nmask;
unsigned long start;
unsigned long end;
struct vm_area_struct *first;
};
/*
* Check if the page's nid is in qp->nmask.
*
* If MPOL_MF_INVERT is set in qp->flags, check if the nid is
* in the invert of qp->nmask.
*/
static inline bool queue_pages_required(struct page *page,
struct queue_pages *qp)
{
int nid = page_to_nid(page);
unsigned long flags = qp->flags;
return node_isset(nid, *qp->nmask) == !(flags & MPOL_MF_INVERT);
}
/*
* queue_pages_pmd() has four possible return values:
* 0 - pages are placed on the right node or queued successfully.
* 1 - there is unmovable page, and MPOL_MF_MOVE* & MPOL_MF_STRICT were
* specified.
* 2 - THP was split.
* -EIO - is migration entry or only MPOL_MF_STRICT was specified and an
* existing page was already on a node that does not follow the
* policy.
*/
static int queue_pages_pmd(pmd_t *pmd, spinlock_t *ptl, unsigned long addr,
unsigned long end, struct mm_walk *walk)
{
int ret = 0;
struct page *page;
struct queue_pages *qp = walk->private;
unsigned long flags;
if (unlikely(is_pmd_migration_entry(*pmd))) {
ret = -EIO;
goto unlock;
}
page = pmd_page(*pmd);
if (is_huge_zero_page(page)) {
spin_unlock(ptl);
__split_huge_pmd(walk->vma, pmd, addr, false, NULL);
ret = 2;
goto out;
}
if (!queue_pages_required(page, qp))
goto unlock;
flags = qp->flags;
/* go to thp migration */
if (flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL)) {
if (!vma_migratable(walk->vma) ||
migrate_page_add(page, qp->pagelist, flags)) {
ret = 1;
goto unlock;
}
} else
ret = -EIO;
unlock:
spin_unlock(ptl);
out:
return ret;
}
/*
* Scan through pages checking if pages follow certain conditions,
* and move them to the pagelist if they do.
*
* queue_pages_pte_range() has three possible return values:
* 0 - pages are placed on the right node or queued successfully.
* 1 - there is unmovable page, and MPOL_MF_MOVE* & MPOL_MF_STRICT were
* specified.
* -EIO - only MPOL_MF_STRICT was specified and an existing page was already
* on a node that does not follow the policy.
*/
static int queue_pages_pte_range(pmd_t *pmd, unsigned long addr,
unsigned long end, struct mm_walk *walk)
{
struct vm_area_struct *vma = walk->vma;
struct page *page;
struct queue_pages *qp = walk->private;
unsigned long flags = qp->flags;
int ret;
bool has_unmovable = false;
pte_t *pte;
spinlock_t *ptl;
ptl = pmd_trans_huge_lock(pmd, vma);
if (ptl) {
ret = queue_pages_pmd(pmd, ptl, addr, end, walk);
if (ret != 2)
return ret;
}
/* THP was split, fall through to pte walk */
if (pmd_trans_unstable(pmd))
return 0;
pte = pte_offset_map_lock(walk->mm, pmd, addr, &ptl);
for (; addr != end; pte++, addr += PAGE_SIZE) {
if (!pte_present(*pte))
continue;
page = vm_normal_page(vma, addr, *pte);
if (!page)
continue;
/*
* vm_normal_page() filters out zero pages, but there might
* still be PageReserved pages to skip, perhaps in a VDSO.
*/
if (PageReserved(page))
continue;
if (!queue_pages_required(page, qp))
continue;
if (flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL)) {
/* MPOL_MF_STRICT must be specified if we get here */
if (!vma_migratable(vma)) {
has_unmovable = true;
break;
}
/*
* Do not abort immediately since there may be
* temporary off LRU pages in the range. Still
* need migrate other LRU pages.
*/
if (migrate_page_add(page, qp->pagelist, flags))
has_unmovable = true;
} else
break;
}
pte_unmap_unlock(pte - 1, ptl);
cond_resched();
if (has_unmovable)
return 1;
return addr != end ? -EIO : 0;
}
static int queue_pages_hugetlb(pte_t *pte, unsigned long hmask,
unsigned long addr, unsigned long end,
struct mm_walk *walk)
{
int ret = 0;
#ifdef CONFIG_HUGETLB_PAGE
struct queue_pages *qp = walk->private;
unsigned long flags = (qp->flags & MPOL_MF_VALID);
struct page *page;
spinlock_t *ptl;
pte_t entry;
ptl = huge_pte_lock(hstate_vma(walk->vma), walk->mm, pte);
entry = huge_ptep_get(pte);
if (!pte_present(entry))
goto unlock;
page = pte_page(entry);
if (!queue_pages_required(page, qp))
goto unlock;
if (flags == MPOL_MF_STRICT) {
/*
* STRICT alone means only detecting misplaced page and no
* need to further check other vma.
*/
ret = -EIO;
goto unlock;
}
if (!vma_migratable(walk->vma)) {
/*
* Must be STRICT with MOVE*, otherwise .test_walk() have
* stopped walking current vma.
* Detecting misplaced page but allow migrating pages which
* have been queued.
*/
ret = 1;
goto unlock;
}
/* With MPOL_MF_MOVE, we migrate only unshared hugepage. */
if (flags & (MPOL_MF_MOVE_ALL) ||
(flags & MPOL_MF_MOVE && page_mapcount(page) == 1)) {
if (!isolate_huge_page(page, qp->pagelist) &&
(flags & MPOL_MF_STRICT))
/*
* Failed to isolate page but allow migrating pages
* which have been queued.
*/
ret = 1;
}
unlock:
spin_unlock(ptl);
#else
BUG();
#endif
return ret;
}
#ifdef CONFIG_NUMA_BALANCING
/*
* This is used to mark a range of virtual addresses to be inaccessible.
* These are later cleared by a NUMA hinting fault. Depending on these
* faults, pages may be migrated for better NUMA placement.
*
* This is assuming that NUMA faults are handled using PROT_NONE. If
* an architecture makes a different choice, it will need further
* changes to the core.
*/
unsigned long change_prot_numa(struct vm_area_struct *vma,
unsigned long addr, unsigned long end)
{
int nr_updated;
nr_updated = change_protection(vma, addr, end, PAGE_NONE, 0, 1);
if (nr_updated)
count_vm_numa_events(NUMA_PTE_UPDATES, nr_updated);
return nr_updated;
}
#else
static unsigned long change_prot_numa(struct vm_area_struct *vma,
unsigned long addr, unsigned long end)
{
return 0;
}
#endif /* CONFIG_NUMA_BALANCING */
static int queue_pages_test_walk(unsigned long start, unsigned long end,
struct mm_walk *walk)
{
struct vm_area_struct *vma = walk->vma;
struct queue_pages *qp = walk->private;
unsigned long endvma = vma->vm_end;
unsigned long flags = qp->flags;
/* range check first */
VM_BUG_ON_VMA((vma->vm_start > start) || (vma->vm_end < end), vma);
if (!qp->first) {
qp->first = vma;
if (!(flags & MPOL_MF_DISCONTIG_OK) &&
(qp->start < vma->vm_start))
/* hole at head side of range */
return -EFAULT;
}
if (!(flags & MPOL_MF_DISCONTIG_OK) &&
((vma->vm_end < qp->end) &&
(!vma->vm_next || vma->vm_end < vma->vm_next->vm_start)))
/* hole at middle or tail of range */
return -EFAULT;
/*
* Need check MPOL_MF_STRICT to return -EIO if possible
* regardless of vma_migratable
*/
if (!vma_migratable(vma) &&
!(flags & MPOL_MF_STRICT))
return 1;
if (endvma > end)
endvma = end;
if (flags & MPOL_MF_LAZY) {
/* Similar to task_numa_work, skip inaccessible VMAs */
if (!is_vm_hugetlb_page(vma) &&
(vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE)) &&
!(vma->vm_flags & VM_MIXEDMAP))
change_prot_numa(vma, start, endvma);
return 1;
}
/* queue pages from current vma */
if (flags & MPOL_MF_VALID)
return 0;
return 1;
}
static const struct mm_walk_ops queue_pages_walk_ops = {
.hugetlb_entry = queue_pages_hugetlb,
.pmd_entry = queue_pages_pte_range,
.test_walk = queue_pages_test_walk,
};
/*
* Walk through page tables and collect pages to be migrated.
*
* If pages found in a given range are on a set of nodes (determined by
* @nodes and @flags,) it's isolated and queued to the pagelist which is
* passed via @private.
*
* queue_pages_range() has three possible return values:
* 1 - there is unmovable page, but MPOL_MF_MOVE* & MPOL_MF_STRICT were
* specified.
* 0 - queue pages successfully or no misplaced page.
* errno - i.e. misplaced pages with MPOL_MF_STRICT specified (-EIO) or
* memory range specified by nodemask and maxnode points outside
* your accessible address space (-EFAULT)
*/
static int
queue_pages_range(struct mm_struct *mm, unsigned long start, unsigned long end,
nodemask_t *nodes, unsigned long flags,
struct list_head *pagelist)
{
int err;
struct queue_pages qp = {
.pagelist = pagelist,
.flags = flags,
.nmask = nodes,
.start = start,
.end = end,
.first = NULL,
};
err = walk_page_range(mm, start, end, &queue_pages_walk_ops, &qp);
if (!qp.first)
/* whole range in hole */
err = -EFAULT;
return err;
}
/*
* Apply policy to a single VMA
* This must be called with the mmap_sem held for writing.
*/
static int vma_replace_policy(struct vm_area_struct *vma,
struct mempolicy *pol)
{
int err;
struct mempolicy *old;
struct mempolicy *new;
pr_debug("vma %lx-%lx/%lx vm_ops %p vm_file %p set_policy %p\n",
vma->vm_start, vma->vm_end, vma->vm_pgoff,
vma->vm_ops, vma->vm_file,
vma->vm_ops ? vma->vm_ops->set_policy : NULL);
new = mpol_dup(pol);
if (IS_ERR(new))
return PTR_ERR(new);
if (vma->vm_ops && vma->vm_ops->set_policy) {
err = vma->vm_ops->set_policy(vma, new);
if (err)
goto err_out;
}
old = vma->vm_policy;
vma->vm_policy = new; /* protected by mmap_sem */
mpol_put(old);
return 0;
err_out:
mpol_put(new);
return err;
}
/* Step 2: apply policy to a range and do splits. */
static int mbind_range(struct mm_struct *mm, unsigned long start,
unsigned long end, struct mempolicy *new_pol)
{
struct vm_area_struct *next;
struct vm_area_struct *prev;
struct vm_area_struct *vma;
int err = 0;
pgoff_t pgoff;
unsigned long vmstart;
unsigned long vmend;
vma = find_vma(mm, start);
VM_BUG_ON(!vma);
prev = vma->vm_prev;
if (start > vma->vm_start)
prev = vma;
for (; vma && vma->vm_start < end; prev = vma, vma = next) {
next = vma->vm_next;
vmstart = max(start, vma->vm_start);
vmend = min(end, vma->vm_end);
if (mpol_equal(vma_policy(vma), new_pol))
continue;
pgoff = vma->vm_pgoff +
((vmstart - vma->vm_start) >> PAGE_SHIFT);
prev = vma_merge(mm, prev, vmstart, vmend, vma->vm_flags,
vma->anon_vma, vma->vm_file, pgoff,
new_pol, vma->vm_userfaultfd_ctx);
if (prev) {
vma = prev;
next = vma->vm_next;
if (mpol_equal(vma_policy(vma), new_pol))
continue;
/* vma_merge() joined vma && vma->next, case 8 */
goto replace;
}
if (vma->vm_start != vmstart) {
err = split_vma(vma->vm_mm, vma, vmstart, 1);
if (err)
goto out;
}
if (vma->vm_end != vmend) {
err = split_vma(vma->vm_mm, vma, vmend, 0);
if (err)
goto out;
}
replace:
err = vma_replace_policy(vma, new_pol);
if (err)
goto out;
}
out:
return err;
}
/* Set the process memory policy */
static long do_set_mempolicy(unsigned short mode, unsigned short flags,
nodemask_t *nodes)
{
struct mempolicy *new, *old;
NODEMASK_SCRATCH(scratch);
int ret;
if (!scratch)
return -ENOMEM;
new = mpol_new(mode, flags, nodes);
if (IS_ERR(new)) {
ret = PTR_ERR(new);
goto out;
}
task_lock(current);
ret = mpol_set_nodemask(new, nodes, scratch);
if (ret) {
task_unlock(current);
mpol_put(new);
goto out;
}
old = current->mempolicy;
current->mempolicy = new;
if (new && new->mode == MPOL_INTERLEAVE)
current->il_prev = MAX_NUMNODES-1;
task_unlock(current);
mpol_put(old);
ret = 0;
out:
NODEMASK_SCRATCH_FREE(scratch);
return ret;
}
/*
* Return nodemask for policy for get_mempolicy() query
*
* Called with task's alloc_lock held
*/
static void get_policy_nodemask(struct mempolicy *p, nodemask_t *nodes)
{
nodes_clear(*nodes);
if (p == &default_policy)
return;
switch (p->mode) {
case MPOL_BIND:
/* Fall through */
case MPOL_INTERLEAVE:
*nodes = p->v.nodes;
break;
case MPOL_PREFERRED:
if (!(p->flags & MPOL_F_LOCAL))
node_set(p->v.preferred_node, *nodes);
/* else return empty node mask for local allocation */
break;
default:
BUG();
}
}
static int lookup_node(struct mm_struct *mm, unsigned long addr)
{
struct page *p;
int err;
int locked = 1;
err = get_user_pages_locked(addr & PAGE_MASK, 1, 0, &p, &locked);
if (err >= 0) {
err = page_to_nid(p);
put_page(p);
}
if (locked)
up_read(&mm->mmap_sem);
return err;
}
/* Retrieve NUMA policy */
static long do_get_mempolicy(int *policy, nodemask_t *nmask,
unsigned long addr, unsigned long flags)
{
int err;
struct mm_struct *mm = current->mm;
struct vm_area_struct *vma = NULL;
struct mempolicy *pol = current->mempolicy, *pol_refcount = NULL;
if (flags &
~(unsigned long)(MPOL_F_NODE|MPOL_F_ADDR|MPOL_F_MEMS_ALLOWED))
return -EINVAL;
if (flags & MPOL_F_MEMS_ALLOWED) {
if (flags & (MPOL_F_NODE|MPOL_F_ADDR))
return -EINVAL;
*policy = 0; /* just so it's initialized */
task_lock(current);
*nmask = cpuset_current_mems_allowed;
task_unlock(current);
return 0;
}
if (flags & MPOL_F_ADDR) {
/*
* Do NOT fall back to task policy if the
* vma/shared policy at addr is NULL. We
* want to return MPOL_DEFAULT in this case.
*/
down_read(&mm->mmap_sem);
vma = find_vma_intersection(mm, addr, addr+1);
if (!vma) {
up_read(&mm->mmap_sem);
return -EFAULT;
}
if (vma->vm_ops && vma->vm_ops->get_policy)
pol = vma->vm_ops->get_policy(vma, addr);
else
pol = vma->vm_policy;
} else if (addr)
return -EINVAL;
if (!pol)
pol = &default_policy; /* indicates default behavior */
if (flags & MPOL_F_NODE) {
if (flags & MPOL_F_ADDR) {
/*
* Take a refcount on the mpol, lookup_node()
* wil drop the mmap_sem, so after calling
* lookup_node() only "pol" remains valid, "vma"
* is stale.
*/
pol_refcount = pol;
vma = NULL;
mpol_get(pol);
err = lookup_node(mm, addr);
if (err < 0)
goto out;
*policy = err;
} else if (pol == current->mempolicy &&
pol->mode == MPOL_INTERLEAVE) {
*policy = next_node_in(current->il_prev, pol->v.nodes);
} else {
err = -EINVAL;
goto out;
}
} else {
*policy = pol == &default_policy ? MPOL_DEFAULT :
pol->mode;
/*
* Internal mempolicy flags must be masked off before exposing
* the policy to userspace.
*/
*policy |= (pol->flags & MPOL_MODE_FLAGS);
}
err = 0;
if (nmask) {
if (mpol_store_user_nodemask(pol)) {
*nmask = pol->w.user_nodemask;
} else {
task_lock(current);
get_policy_nodemask(pol, nmask);
task_unlock(current);
}
}
out:
mpol_cond_put(pol);
if (vma)
up_read(&mm->mmap_sem);
if (pol_refcount)
mpol_put(pol_refcount);
return err;
}
#ifdef CONFIG_MIGRATION
/*
* page migration, thp tail pages can be passed.
*/
static int migrate_page_add(struct page *page, struct list_head *pagelist,
unsigned long flags)
{
struct page *head = compound_head(page);
/*
* Avoid migrating a page that is shared with others.
*/
if ((flags & MPOL_MF_MOVE_ALL) || page_mapcount(head) == 1) {
if (!isolate_lru_page(head)) {
list_add_tail(&head->lru, pagelist);
mod_node_page_state(page_pgdat(head),
NR_ISOLATED_ANON + page_is_file_cache(head),
hpage_nr_pages(head));
} else if (flags & MPOL_MF_STRICT) {
/*
* Non-movable page may reach here. And, there may be
* temporary off LRU pages or non-LRU movable pages.
* Treat them as unmovable pages since they can't be
* isolated, so they can't be moved at the moment. It
* should return -EIO for this case too.
*/
return -EIO;
}
}
return 0;
}
/* page allocation callback for NUMA node migration */
struct page *alloc_new_node_page(struct page *page, unsigned long node)
{
if (PageHuge(page))
return alloc_huge_page_node(page_hstate(compound_head(page)),
node);
else if (PageTransHuge(page)) {
struct page *thp;
thp = alloc_pages_node(node,
(GFP_TRANSHUGE | __GFP_THISNODE),
HPAGE_PMD_ORDER);
if (!thp)
return NULL;
prep_transhuge_page(thp);
return thp;
} else
return __alloc_pages_node(node, GFP_HIGHUSER_MOVABLE |
__GFP_THISNODE, 0);
}
/*
* Migrate pages from one node to a target node.
* Returns error or the number of pages not migrated.
*/
static int migrate_to_node(struct mm_struct *mm, int source, int dest,
int flags)
{
nodemask_t nmask;
LIST_HEAD(pagelist);
int err = 0;
nodes_clear(nmask);
node_set(source, nmask);
/*
* This does not "check" the range but isolates all pages that
* need migration. Between passing in the full user address
* space range and MPOL_MF_DISCONTIG_OK, this call can not fail.
*/
VM_BUG_ON(!(flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL)));
queue_pages_range(mm, mm->mmap->vm_start, mm->task_size, &nmask,
flags | MPOL_MF_DISCONTIG_OK, &pagelist);
if (!list_empty(&pagelist)) {
err = migrate_pages(&pagelist, alloc_new_node_page, NULL, dest,
MIGRATE_SYNC, MR_SYSCALL);
if (err)
putback_movable_pages(&pagelist);
}
return err;
}
/*
* Move pages between the two nodesets so as to preserve the physical
* layout as much as possible.
*
* Returns the number of page that could not be moved.
*/
int do_migrate_pages(struct mm_struct *mm, const nodemask_t *from,
const nodemask_t *to, int flags)
{
int busy = 0;
int err;
nodemask_t tmp;
err = migrate_prep();
if (err)
return err;
down_read(&mm->mmap_sem);
/*
* Find a 'source' bit set in 'tmp' whose corresponding 'dest'
* bit in 'to' is not also set in 'tmp'. Clear the found 'source'
* bit in 'tmp', and return that <source, dest> pair for migration.
* The pair of nodemasks 'to' and 'from' define the map.
*
* If no pair of bits is found that way, fallback to picking some
* pair of 'source' and 'dest' bits that are not the same. If the
* 'source' and 'dest' bits are the same, this represents a node
* that will be migrating to itself, so no pages need move.
*
* If no bits are left in 'tmp', or if all remaining bits left
* in 'tmp' correspond to the same bit in 'to', return false
* (nothing left to migrate).
*
* This lets us pick a pair of nodes to migrate between, such that
* if possible the dest node is not already occupied by some other
* source node, minimizing the risk of overloading the memory on a
* node that would happen if we migrated incoming memory to a node
* before migrating outgoing memory source that same node.
*
* A single scan of tmp is sufficient. As we go, we remember the
* most recent <s, d> pair that moved (s != d). If we find a pair
* that not only moved, but what's better, moved to an empty slot
* (d is not set in tmp), then we break out then, with that pair.
* Otherwise when we finish scanning from_tmp, we at least have the
* most recent <s, d> pair that moved. If we get all the way through
* the scan of tmp without finding any node that moved, much less
* moved to an empty node, then there is nothing left worth migrating.
*/
tmp = *from;
while (!nodes_empty(tmp)) {
int s,d;
int source = NUMA_NO_NODE;
int dest = 0;
for_each_node_mask(s, tmp) {
/*
* do_migrate_pages() tries to maintain the relative
* node relationship of the pages established between
* threads and memory areas.
*
* However if the number of source nodes is not equal to
* the number of destination nodes we can not preserve
* this node relative relationship. In that case, skip
* copying memory from a node that is in the destination
* mask.
*
* Example: [2,3,4] -> [3,4,5] moves everything.
* [0-7] - > [3,4,5] moves only 0,1,2,6,7.
*/
if ((nodes_weight(*from) != nodes_weight(*to)) &&
(node_isset(s, *to)))
continue;
d = node_remap(s, *from, *to);
if (s == d)
continue;
source = s; /* Node moved. Memorize */
dest = d;
/* dest not in remaining from nodes? */
if (!node_isset(dest, tmp))
break;
}
if (source == NUMA_NO_NODE)
break;
node_clear(source, tmp);
err = migrate_to_node(mm, source, dest, flags);
if (err > 0)
busy += err;
if (err < 0)
break;
}
up_read(&mm->mmap_sem);
if (err < 0)
return err;
return busy;
}
/*
* Allocate a new page for page migration based on vma policy.
* Start by assuming the page is mapped by the same vma as contains @start.
* Search forward from there, if not. N.B., this assumes that the
* list of pages handed to migrate_pages()--which is how we get here--
* is in virtual address order.
*/
static struct page *new_page(struct page *page, unsigned long start)
{
struct vm_area_struct *vma;
unsigned long uninitialized_var(address);
vma = find_vma(current->mm, start);
while (vma) {
address = page_address_in_vma(page, vma);
if (address != -EFAULT)
break;
vma = vma->vm_next;
}
if (PageHuge(page)) {
return alloc_huge_page_vma(page_hstate(compound_head(page)),
vma, address);
} else if (PageTransHuge(page)) {
struct page *thp;
thp = alloc_hugepage_vma(GFP_TRANSHUGE, vma, address,
HPAGE_PMD_ORDER);
if (!thp)
return NULL;
prep_transhuge_page(thp);
return thp;
}
/*
* if !vma, alloc_page_vma() will use task or system default policy
*/
return alloc_page_vma(GFP_HIGHUSER_MOVABLE | __GFP_RETRY_MAYFAIL,
vma, address);
}
#else
static int migrate_page_add(struct page *page, struct list_head *pagelist,
unsigned long flags)
{
return -EIO;
}
int do_migrate_pages(struct mm_struct *mm, const nodemask_t *from,
const nodemask_t *to, int flags)
{
return -ENOSYS;
}
static struct page *new_page(struct page *page, unsigned long start)
{
return NULL;
}
#endif
static long do_mbind(unsigned long start, unsigned long len,
unsigned short mode, unsigned short mode_flags,
nodemask_t *nmask, unsigned long flags)
{
struct mm_struct *mm = current->mm;
struct mempolicy *new;
unsigned long end;
int err;
int ret;
LIST_HEAD(pagelist);
if (flags & ~(unsigned long)MPOL_MF_VALID)
return -EINVAL;
if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
return -EPERM;
if (start & ~PAGE_MASK)
return -EINVAL;
if (mode == MPOL_DEFAULT)
flags &= ~MPOL_MF_STRICT;
len = (len + PAGE_SIZE - 1) & PAGE_MASK;
end = start + len;
if (end < start)
return -EINVAL;
if (end == start)
return 0;
new = mpol_new(mode, mode_flags, nmask);
if (IS_ERR(new))
return PTR_ERR(new);
if (flags & MPOL_MF_LAZY)
new->flags |= MPOL_F_MOF;
/*
* If we are using the default policy then operation
* on discontinuous address spaces is okay after all
*/
if (!new)
flags |= MPOL_MF_DISCONTIG_OK;
pr_debug("mbind %lx-%lx mode:%d flags:%d nodes:%lx\n",
start, start + len, mode, mode_flags,
nmask ? nodes_addr(*nmask)[0] : NUMA_NO_NODE);
if (flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL)) {
err = migrate_prep();
if (err)
goto mpol_out;
}
{
NODEMASK_SCRATCH(scratch);
if (scratch) {
down_write(&mm->mmap_sem);
task_lock(current);
err = mpol_set_nodemask(new, nmask, scratch);
task_unlock(current);
if (err)
up_write(&mm->mmap_sem);
} else
err = -ENOMEM;
NODEMASK_SCRATCH_FREE(scratch);
}
if (err)
goto mpol_out;
ret = queue_pages_range(mm, start, end, nmask,
flags | MPOL_MF_INVERT, &pagelist);
if (ret < 0) {
err = ret;
goto up_out;
}
err = mbind_range(mm, start, end, new);
if (!err) {
int nr_failed = 0;
if (!list_empty(&pagelist)) {
WARN_ON_ONCE(flags & MPOL_MF_LAZY);
nr_failed = migrate_pages(&pagelist, new_page, NULL,
start, MIGRATE_SYNC, MR_MEMPOLICY_MBIND);
if (nr_failed)
putback_movable_pages(&pagelist);
}
if ((ret > 0) || (nr_failed && (flags & MPOL_MF_STRICT)))
err = -EIO;
} else {
up_out:
if (!list_empty(&pagelist))
putback_movable_pages(&pagelist);
}
up_write(&mm->mmap_sem);
mpol_out:
mpol_put(new);
return err;
}
/*
* User space interface with variable sized bitmaps for nodelists.
*/
/* Copy a node mask from user space. */
static int get_nodes(nodemask_t *nodes, const unsigned long __user *nmask,
unsigned long maxnode)
{
unsigned long k;
unsigned long t;
unsigned long nlongs;
unsigned long endmask;
--maxnode;
nodes_clear(*nodes);
if (maxnode == 0 || !nmask)
return 0;
if (maxnode > PAGE_SIZE*BITS_PER_BYTE)
return -EINVAL;
nlongs = BITS_TO_LONGS(maxnode);
if ((maxnode % BITS_PER_LONG) == 0)
endmask = ~0UL;
else
endmask = (1UL << (maxnode % BITS_PER_LONG)) - 1;
/*
* When the user specified more nodes than supported just check
* if the non supported part is all zero.
*
* If maxnode have more longs than MAX_NUMNODES, check
* the bits in that area first. And then go through to
* check the rest bits which equal or bigger than MAX_NUMNODES.
* Otherwise, just check bits [MAX_NUMNODES, maxnode).
*/
if (nlongs > BITS_TO_LONGS(MAX_NUMNODES)) {
for (k = BITS_TO_LONGS(MAX_NUMNODES); k < nlongs; k++) {
if (get_user(t, nmask + k))
return -EFAULT;
if (k == nlongs - 1) {
if (t & endmask)
return -EINVAL;
} else if (t)
return -EINVAL;
}
nlongs = BITS_TO_LONGS(MAX_NUMNODES);
endmask = ~0UL;
}
if (maxnode > MAX_NUMNODES && MAX_NUMNODES % BITS_PER_LONG != 0) {
unsigned long valid_mask = endmask;
valid_mask &= ~((1UL << (MAX_NUMNODES % BITS_PER_LONG)) - 1);
if (get_user(t, nmask + nlongs - 1))
return -EFAULT;
if (t & valid_mask)
return -EINVAL;
}
if (copy_from_user(nodes_addr(*nodes), nmask, nlongs*sizeof(unsigned long)))
return -EFAULT;
nodes_addr(*nodes)[nlongs-1] &= endmask;
return 0;
}
/* Copy a kernel node mask to user space */
static int copy_nodes_to_user(unsigned long __user *mask, unsigned long maxnode,
nodemask_t *nodes)
{
unsigned long copy = ALIGN(maxnode-1, 64) / 8;
unsigned int nbytes = BITS_TO_LONGS(nr_node_ids) * sizeof(long);
if (copy > nbytes) {
if (copy > PAGE_SIZE)
return -EINVAL;
if (clear_user((char __user *)mask + nbytes, copy - nbytes))
return -EFAULT;
copy = nbytes;
}
return copy_to_user(mask, nodes_addr(*nodes), copy) ? -EFAULT : 0;
}
static long kernel_mbind(unsigned long start, unsigned long len,
unsigned long mode, const unsigned long __user *nmask,
unsigned long maxnode, unsigned int flags)
{
nodemask_t nodes;
int err;
unsigned short mode_flags;
start = untagged_addr(start);
mode_flags = mode & MPOL_MODE_FLAGS;
mode &= ~MPOL_MODE_FLAGS;
if (mode >= MPOL_MAX)
return -EINVAL;
if ((mode_flags & MPOL_F_STATIC_NODES) &&
(mode_flags & MPOL_F_RELATIVE_NODES))
return -EINVAL;
err = get_nodes(&nodes, nmask, maxnode);
if (err)
return err;
return do_mbind(start, len, mode, mode_flags, &nodes, flags);
}
SYSCALL_DEFINE6(mbind, unsigned long, start, unsigned long, len,
unsigned long, mode, const unsigned long __user *, nmask,
unsigned long, maxnode, unsigned int, flags)
{
return kernel_mbind(start, len, mode, nmask, maxnode, flags);
}
/* Set the process memory policy */
static long kernel_set_mempolicy(int mode, const unsigned long __user *nmask,
unsigned long maxnode)
{
int err;
nodemask_t nodes;
unsigned short flags;
flags = mode & MPOL_MODE_FLAGS;
mode &= ~MPOL_MODE_FLAGS;
if ((unsigned int)mode >= MPOL_MAX)
return -EINVAL;
if ((flags & MPOL_F_STATIC_NODES) && (flags & MPOL_F_RELATIVE_NODES))
return -EINVAL;
err = get_nodes(&nodes, nmask, maxnode);
if (err)
return err;
return do_set_mempolicy(mode, flags, &nodes);
}
SYSCALL_DEFINE3(set_mempolicy, int, mode, const unsigned long __user *, nmask,
unsigned long, maxnode)
{
return kernel_set_mempolicy(mode, nmask, maxnode);
}
static int kernel_migrate_pages(pid_t pid, unsigned long maxnode,
const unsigned long __user *old_nodes,
const unsigned long __user *new_nodes)
{
struct mm_struct *mm = NULL;
struct task_struct *task;
nodemask_t task_nodes;
int err;
nodemask_t *old;
nodemask_t *new;
NODEMASK_SCRATCH(scratch);
if (!scratch)
return -ENOMEM;
old = &scratch->mask1;
new = &scratch->mask2;
err = get_nodes(old, old_nodes, maxnode);
if (err)
goto out;
err = get_nodes(new, new_nodes, maxnode);
if (err)
goto out;
/* Find the mm_struct */
rcu_read_lock();
task = pid ? find_task_by_vpid(pid) : current;
if (!task) {
rcu_read_unlock();
err = -ESRCH;
goto out;
}
get_task_struct(task);
err = -EINVAL;
/*
* Check if this process has the right to modify the specified process.
* Use the regular "ptrace_may_access()" checks.
*/
if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) {
rcu_read_unlock();
err = -EPERM;
goto out_put;
}
rcu_read_unlock();
task_nodes = cpuset_mems_allowed(task);
/* Is the user allowed to access the target nodes? */
if (!nodes_subset(*new, task_nodes) && !capable(CAP_SYS_NICE)) {
err = -EPERM;
goto out_put;
}
task_nodes = cpuset_mems_allowed(current);
nodes_and(*new, *new, task_nodes);
if (nodes_empty(*new))
goto out_put;
err = security_task_movememory(task);
if (err)
goto out_put;
mm = get_task_mm(task);
put_task_struct(task);
if (!mm) {
err = -EINVAL;
goto out;
}
err = do_migrate_pages(mm, old, new,
capable(CAP_SYS_NICE) ? MPOL_MF_MOVE_ALL : MPOL_MF_MOVE);
mmput(mm);
out:
NODEMASK_SCRATCH_FREE(scratch);
return err;
out_put:
put_task_struct(task);
goto out;
}
SYSCALL_DEFINE4(migrate_pages, pid_t, pid, unsigned long, maxnode,
const unsigned long __user *, old_nodes,
const unsigned long __user *, new_nodes)
{
return kernel_migrate_pages(pid, maxnode, old_nodes, new_nodes);
}
/* Retrieve NUMA policy */
static int kernel_get_mempolicy(int __user *policy,
unsigned long __user *nmask,
unsigned long maxnode,
unsigned long addr,
unsigned long flags)
{
int err;
int uninitialized_var(pval);
nodemask_t nodes;
addr = untagged_addr(addr);
if (nmask != NULL && maxnode < nr_node_ids)
return -EINVAL;
err = do_get_mempolicy(&pval, &nodes, addr, flags);
if (err)
return err;
if (policy && put_user(pval, policy))
return -EFAULT;
if (nmask)
err = copy_nodes_to_user(nmask, maxnode, &nodes);
return err;
}
SYSCALL_DEFINE5(get_mempolicy, int __user *, policy,
unsigned long __user *, nmask, unsigned long, maxnode,
unsigned long, addr, unsigned long, flags)
{
return kernel_get_mempolicy(policy, nmask, maxnode, addr, flags);
}
#ifdef CONFIG_COMPAT
COMPAT_SYSCALL_DEFINE5(get_mempolicy, int __user *, policy,
compat_ulong_t __user *, nmask,
compat_ulong_t, maxnode,
compat_ulong_t, addr, compat_ulong_t, flags)
{
long err;
unsigned long __user *nm = NULL;
unsigned long nr_bits, alloc_size;
DECLARE_BITMAP(bm, MAX_NUMNODES);
nr_bits = min_t(unsigned long, maxnode-1, nr_node_ids);
alloc_size = ALIGN(nr_bits, BITS_PER_LONG) / 8;
if (nmask)
nm = compat_alloc_user_space(alloc_size);
err = kernel_get_mempolicy(policy, nm, nr_bits+1, addr, flags);
if (!err && nmask) {
unsigned long copy_size;
copy_size = min_t(unsigned long, sizeof(bm), alloc_size);
err = copy_from_user(bm, nm, copy_size);
/* ensure entire bitmap is zeroed */
err |= clear_user(nmask, ALIGN(maxnode-1, 8) / 8);
err |= compat_put_bitmap(nmask, bm, nr_bits);
}
return err;
}
COMPAT_SYSCALL_DEFINE3(set_mempolicy, int, mode, compat_ulong_t __user *, nmask,
compat_ulong_t, maxnode)
{
unsigned long __user *nm = NULL;
unsigned long nr_bits, alloc_size;
DECLARE_BITMAP(bm, MAX_NUMNODES);
nr_bits = min_t(unsigned long, maxnode-1, MAX_NUMNODES);
alloc_size = ALIGN(nr_bits, BITS_PER_LONG) / 8;
if (nmask) {
if (compat_get_bitmap(bm, nmask, nr_bits))
return -EFAULT;
nm = compat_alloc_user_space(alloc_size);
if (copy_to_user(nm, bm, alloc_size))
return -EFAULT;
}
return kernel_set_mempolicy(mode, nm, nr_bits+1);
}
COMPAT_SYSCALL_DEFINE6(mbind, compat_ulong_t, start, compat_ulong_t, len,
compat_ulong_t, mode, compat_ulong_t __user *, nmask,
compat_ulong_t, maxnode, compat_ulong_t, flags)
{
unsigned long __user *nm = NULL;
unsigned long nr_bits, alloc_size;
nodemask_t bm;
nr_bits = min_t(unsigned long, maxnode-1, MAX_NUMNODES);
alloc_size = ALIGN(nr_bits, BITS_PER_LONG) / 8;
if (nmask) {
if (compat_get_bitmap(nodes_addr(bm), nmask, nr_bits))
return -EFAULT;
nm = compat_alloc_user_space(alloc_size);
if (copy_to_user(nm, nodes_addr(bm), alloc_size))
return -EFAULT;
}
return kernel_mbind(start, len, mode, nm, nr_bits+1, flags);
}
COMPAT_SYSCALL_DEFINE4(migrate_pages, compat_pid_t, pid,
compat_ulong_t, maxnode,
const compat_ulong_t __user *, old_nodes,
const compat_ulong_t __user *, new_nodes)
{
unsigned long __user *old = NULL;
unsigned long __user *new = NULL;
nodemask_t tmp_mask;
unsigned long nr_bits;
unsigned long size;
nr_bits = min_t(unsigned long, maxnode - 1, MAX_NUMNODES);
size = ALIGN(nr_bits, BITS_PER_LONG) / 8;
if (old_nodes) {
if (compat_get_bitmap(nodes_addr(tmp_mask), old_nodes, nr_bits))
return -EFAULT;
old = compat_alloc_user_space(new_nodes ? size * 2 : size);
if (new_nodes)
new = old + size / sizeof(unsigned long);
if (copy_to_user(old, nodes_addr(tmp_mask), size))
return -EFAULT;
}
if (new_nodes) {
if (compat_get_bitmap(nodes_addr(tmp_mask), new_nodes, nr_bits))
return -EFAULT;
if (new == NULL)
new = compat_alloc_user_space(size);
if (copy_to_user(new, nodes_addr(tmp_mask), size))
return -EFAULT;
}
return kernel_migrate_pages(pid, nr_bits + 1, old, new);
}
#endif /* CONFIG_COMPAT */
bool vma_migratable(struct vm_area_struct *vma)
{
if (vma->vm_flags & (VM_IO | VM_PFNMAP))
return false;
/*
* DAX device mappings require predictable access latency, so avoid
* incurring periodic faults.
*/
if (vma_is_dax(vma))
return false;
if (is_vm_hugetlb_page(vma) &&
!hugepage_migration_supported(hstate_vma(vma)))
return false;
/*
* Migration allocates pages in the highest zone. If we cannot
* do so then migration (at least from node to node) is not
* possible.
*/
if (vma->vm_file &&
gfp_zone(mapping_gfp_mask(vma->vm_file->f_mapping))
< policy_zone)
return false;
return true;
}
struct mempolicy *__get_vma_policy(struct vm_area_struct *vma,
unsigned long addr)
{
struct mempolicy *pol = NULL;
if (vma) {
if (vma->vm_ops && vma->vm_ops->get_policy) {
pol = vma->vm_ops->get_policy(vma, addr);
} else if (vma->vm_policy) {
pol = vma->vm_policy;
/*
* shmem_alloc_page() passes MPOL_F_SHARED policy with
* a pseudo vma whose vma->vm_ops=NULL. Take a reference
* count on these policies which will be dropped by
* mpol_cond_put() later
*/
if (mpol_needs_cond_ref(pol))
mpol_get(pol);
}
}
return pol;
}
/*
* get_vma_policy(@vma, @addr)
* @vma: virtual memory area whose policy is sought
* @addr: address in @vma for shared policy lookup
*
* Returns effective policy for a VMA at specified address.
* Falls back to current->mempolicy or system default policy, as necessary.
* Shared policies [those marked as MPOL_F_SHARED] require an extra reference
* count--added by the get_policy() vm_op, as appropriate--to protect against
* freeing by another task. It is the caller's responsibility to free the
* extra reference for shared policies.
*/
static struct mempolicy *get_vma_policy(struct vm_area_struct *vma,
unsigned long addr)
{
struct mempolicy *pol = __get_vma_policy(vma, addr);
if (!pol)
pol = get_task_policy(current);
return pol;
}
bool vma_policy_mof(struct vm_area_struct *vma)
{
struct mempolicy *pol;
if (vma->vm_ops && vma->vm_ops->get_policy) {
bool ret = false;
pol = vma->vm_ops->get_policy(vma, vma->vm_start);
if (pol && (pol->flags & MPOL_F_MOF))
ret = true;
mpol_cond_put(pol);
return ret;
}
pol = vma->vm_policy;
if (!pol)
pol = get_task_policy(current);
return pol->flags & MPOL_F_MOF;
}
static int apply_policy_zone(struct mempolicy *policy, enum zone_type zone)
{
enum zone_type dynamic_policy_zone = policy_zone;
BUG_ON(dynamic_policy_zone == ZONE_MOVABLE);
/*
* if policy->v.nodes has movable memory only,
* we apply policy when gfp_zone(gfp) = ZONE_MOVABLE only.
*
* policy->v.nodes is intersect with node_states[N_MEMORY].
* so if the following test faile, it implies
* policy->v.nodes has movable memory only.
*/
if (!nodes_intersects(policy->v.nodes, node_states[N_HIGH_MEMORY]))
dynamic_policy_zone = ZONE_MOVABLE;
return zone >= dynamic_policy_zone;
}
/*
* Return a nodemask representing a mempolicy for filtering nodes for
* page allocation
*/
static nodemask_t *policy_nodemask(gfp_t gfp, struct mempolicy *policy)
{
/* Lower zones don't get a nodemask applied for MPOL_BIND */
if (unlikely(policy->mode == MPOL_BIND) &&
apply_policy_zone(policy, gfp_zone(gfp)) &&
cpuset_nodemask_valid_mems_allowed(&policy->v.nodes))
return &policy->v.nodes;
return NULL;
}
/* Return the node id preferred by the given mempolicy, or the given id */
static int policy_node(gfp_t gfp, struct mempolicy *policy,
int nd)
{
if (policy->mode == MPOL_PREFERRED && !(policy->flags & MPOL_F_LOCAL))
nd = policy->v.preferred_node;
else {
/*
* __GFP_THISNODE shouldn't even be used with the bind policy
* because we might easily break the expectation to stay on the
* requested node and not break the policy.
*/
WARN_ON_ONCE(policy->mode == MPOL_BIND && (gfp & __GFP_THISNODE));
}
return nd;
}
/* Do dynamic interleaving for a process */
static unsigned interleave_nodes(struct mempolicy *policy)
{
unsigned next;
struct task_struct *me = current;
next = next_node_in(me->il_prev, policy->v.nodes);
if (next < MAX_NUMNODES)
me->il_prev = next;
return next;
}
/*
* Depending on the memory policy provide a node from which to allocate the
* next slab entry.
*/
unsigned int mempolicy_slab_node(void)
{
struct mempolicy *policy;
int node = numa_mem_id();
if (in_interrupt())
return node;
policy = current->mempolicy;
if (!policy || policy->flags & MPOL_F_LOCAL)
return node;
switch (policy->mode) {
case MPOL_PREFERRED:
/*
* handled MPOL_F_LOCAL above
*/
return policy->v.preferred_node;
case MPOL_INTERLEAVE:
return interleave_nodes(policy);
case MPOL_BIND: {
struct zoneref *z;
/*
* Follow bind policy behavior and start allocation at the
* first node.
*/
struct zonelist *zonelist;
enum zone_type highest_zoneidx = gfp_zone(GFP_KERNEL);
zonelist = &NODE_DATA(node)->node_zonelists[ZONELIST_FALLBACK];
z = first_zones_zonelist(zonelist, highest_zoneidx,
&policy->v.nodes);
return z->zone ? zone_to_nid(z->zone) : node;
}
default:
BUG();
}
}
/*
* Do static interleaving for a VMA with known offset @n. Returns the n'th
* node in pol->v.nodes (starting from n=0), wrapping around if n exceeds the
* number of present nodes.
*/
static unsigned offset_il_node(struct mempolicy *pol, unsigned long n)
{
unsigned nnodes = nodes_weight(pol->v.nodes);
unsigned target;
int i;
int nid;
if (!nnodes)
return numa_node_id();
target = (unsigned int)n % nnodes;
nid = first_node(pol->v.nodes);
for (i = 0; i < target; i++)
nid = next_node(nid, pol->v.nodes);
return nid;
}
/* Determine a node number for interleave */
static inline unsigned interleave_nid(struct mempolicy *pol,
struct vm_area_struct *vma, unsigned long addr, int shift)
{
if (vma) {
unsigned long off;
/*
* for small pages, there is no difference between
* shift and PAGE_SHIFT, so the bit-shift is safe.
* for huge pages, since vm_pgoff is in units of small
* pages, we need to shift off the always 0 bits to get
* a useful offset.
*/
BUG_ON(shift < PAGE_SHIFT);
off = vma->vm_pgoff >> (shift - PAGE_SHIFT);
off += (addr - vma->vm_start) >> shift;
return offset_il_node(pol, off);
} else
return interleave_nodes(pol);
}
#ifdef CONFIG_HUGETLBFS
/*
* huge_node(@vma, @addr, @gfp_flags, @mpol)
* @vma: virtual memory area whose policy is sought
* @addr: address in @vma for shared policy lookup and interleave policy
* @gfp_flags: for requested zone
* @mpol: pointer to mempolicy pointer for reference counted mempolicy
* @nodemask: pointer to nodemask pointer for MPOL_BIND nodemask
*
* Returns a nid suitable for a huge page allocation and a pointer
* to the struct mempolicy for conditional unref after allocation.
* If the effective policy is 'BIND, returns a pointer to the mempolicy's
* @nodemask for filtering the zonelist.
*
* Must be protected by read_mems_allowed_begin()
*/
int huge_node(struct vm_area_struct *vma, unsigned long addr, gfp_t gfp_flags,
struct mempolicy **mpol, nodemask_t **nodemask)
{
int nid;
*mpol = get_vma_policy(vma, addr);
*nodemask = NULL; /* assume !MPOL_BIND */
if (unlikely((*mpol)->mode == MPOL_INTERLEAVE)) {
nid = interleave_nid(*mpol, vma, addr,
huge_page_shift(hstate_vma(vma)));
} else {
nid = policy_node(gfp_flags, *mpol, numa_node_id());
if ((*mpol)->mode == MPOL_BIND)
*nodemask = &(*mpol)->v.nodes;
}
return nid;
}
/*
* init_nodemask_of_mempolicy
*
* If the current task's mempolicy is "default" [NULL], return 'false'
* to indicate default policy. Otherwise, extract the policy nodemask
* for 'bind' or 'interleave' policy into the argument nodemask, or
* initialize the argument nodemask to contain the single node for
* 'preferred' or 'local' policy and return 'true' to indicate presence
* of non-default mempolicy.
*
* We don't bother with reference counting the mempolicy [mpol_get/put]
* because the current task is examining it's own mempolicy and a task's
* mempolicy is only ever changed by the task itself.
*
* N.B., it is the caller's responsibility to free a returned nodemask.
*/
bool init_nodemask_of_mempolicy(nodemask_t *mask)
{
struct mempolicy *mempolicy;
int nid;
if (!(mask && current->mempolicy))
return false;
task_lock(current);
mempolicy = current->mempolicy;
switch (mempolicy->mode) {
case MPOL_PREFERRED:
if (mempolicy->flags & MPOL_F_LOCAL)
nid = numa_node_id();
else
nid = mempolicy->v.preferred_node;
init_nodemask_of_node(mask, nid);
break;
case MPOL_BIND:
/* Fall through */
case MPOL_INTERLEAVE:
*mask = mempolicy->v.nodes;
break;
default:
BUG();
}
task_unlock(current);
return true;
}
#endif
/*
* mempolicy_nodemask_intersects
*
* If tsk's mempolicy is "default" [NULL], return 'true' to indicate default
* policy. Otherwise, check for intersection between mask and the policy
* nodemask for 'bind' or 'interleave' policy. For 'perferred' or 'local'
* policy, always return true since it may allocate elsewhere on fallback.
*
* Takes task_lock(tsk) to prevent freeing of its mempolicy.
*/
bool mempolicy_nodemask_intersects(struct task_struct *tsk,
const nodemask_t *mask)
{
struct mempolicy *mempolicy;
bool ret = true;
if (!mask)
return ret;
task_lock(tsk);
mempolicy = tsk->mempolicy;
if (!mempolicy)
goto out;
switch (mempolicy->mode) {
case MPOL_PREFERRED:
/*
* MPOL_PREFERRED and MPOL_F_LOCAL are only preferred nodes to
* allocate from, they may fallback to other nodes when oom.
* Thus, it's possible for tsk to have allocated memory from
* nodes in mask.
*/
break;
case MPOL_BIND:
case MPOL_INTERLEAVE:
ret = nodes_intersects(mempolicy->v.nodes, *mask);
break;
default:
BUG();
}
out:
task_unlock(tsk);
return ret;
}
/* Allocate a page in interleaved policy.
Own path because it needs to do special accounting. */
static struct page *alloc_page_interleave(gfp_t gfp, unsigned order,
unsigned nid)
{
struct page *page;
page = __alloc_pages(gfp, order, nid);
/* skip NUMA_INTERLEAVE_HIT counter update if numa stats is disabled */
if (!static_branch_likely(&vm_numa_stat_key))
return page;
if (page && page_to_nid(page) == nid) {
preempt_disable();
__inc_numa_state(page_zone(page), NUMA_INTERLEAVE_HIT);
preempt_enable();
}
return page;
}
/**
* alloc_pages_vma - Allocate a page for a VMA.
*
* @gfp:
* %GFP_USER user allocation.
* %GFP_KERNEL kernel allocations,
* %GFP_HIGHMEM highmem/user allocations,
* %GFP_FS allocation should not call back into a file system.
* %GFP_ATOMIC don't sleep.
*
* @order:Order of the GFP allocation.
* @vma: Pointer to VMA or NULL if not available.
* @addr: Virtual Address of the allocation. Must be inside the VMA.
* @node: Which node to prefer for allocation (modulo policy).
* @hugepage: for hugepages try only the preferred node if possible
*
* This function allocates a page from the kernel page pool and applies
* a NUMA policy associated with the VMA or the current process.
* When VMA is not NULL caller must hold down_read on the mmap_sem of the
* mm_struct of the VMA to prevent it from going away. Should be used for
* all allocations for pages that will be mapped into user space. Returns
* NULL when no page can be allocated.
*/
struct page *
alloc_pages_vma(gfp_t gfp, int order, struct vm_area_struct *vma,
unsigned long addr, int node, bool hugepage)
{
struct mempolicy *pol;
struct page *page;
int preferred_nid;
nodemask_t *nmask;
pol = get_vma_policy(vma, addr);
if (pol->mode == MPOL_INTERLEAVE) {
unsigned nid;
nid = interleave_nid(pol, vma, addr, PAGE_SHIFT + order);
mpol_cond_put(pol);
page = alloc_page_interleave(gfp, order, nid);
goto out;
}
if (unlikely(IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) && hugepage)) {
int hpage_node = node;
/*
* For hugepage allocation and non-interleave policy which
* allows the current node (or other explicitly preferred
* node) we only try to allocate from the current/preferred
* node and don't fall back to other nodes, as the cost of
* remote accesses would likely offset THP benefits.
*
* If the policy is interleave, or does not allow the current
* node in its nodemask, we allocate the standard way.
*/
if (pol->mode == MPOL_PREFERRED && !(pol->flags & MPOL_F_LOCAL))
hpage_node = pol->v.preferred_node;
nmask = policy_nodemask(gfp, pol);
if (!nmask || node_isset(hpage_node, *nmask)) {
mpol_cond_put(pol);
/*
* First, try to allocate THP only on local node, but
* don't reclaim unnecessarily, just compact.
*/
page = __alloc_pages_node(hpage_node,
gfp | __GFP_THISNODE | __GFP_NORETRY, order);
/*
* If hugepage allocations are configured to always
* synchronous compact or the vma has been madvised
* to prefer hugepage backing, retry allowing remote
* memory with both reclaim and compact as well.
*/
if (!page && (gfp & __GFP_DIRECT_RECLAIM))
page = __alloc_pages_node(hpage_node,
gfp, order);
goto out;
}
}
nmask = policy_nodemask(gfp, pol);
preferred_nid = policy_node(gfp, pol, node);
page = __alloc_pages_nodemask(gfp, order, preferred_nid, nmask);
mpol_cond_put(pol);
out:
return page;
}
EXPORT_SYMBOL(alloc_pages_vma);
/**
* alloc_pages_current - Allocate pages.
*
* @gfp:
* %GFP_USER user allocation,
* %GFP_KERNEL kernel allocation,
* %GFP_HIGHMEM highmem allocation,
* %GFP_FS don't call back into a file system.
* %GFP_ATOMIC don't sleep.
* @order: Power of two of allocation size in pages. 0 is a single page.
*
* Allocate a page from the kernel page pool. When not in
* interrupt context and apply the current process NUMA policy.
* Returns NULL when no page can be allocated.
*/
struct page *alloc_pages_current(gfp_t gfp, unsigned order)
{
struct mempolicy *pol = &default_policy;
struct page *page;
if (!in_interrupt() && !(gfp & __GFP_THISNODE))
pol = get_task_policy(current);
/*
* No reference counting needed for current->mempolicy
* nor system default_policy
*/
if (pol->mode == MPOL_INTERLEAVE)
page = alloc_page_interleave(gfp, order, interleave_nodes(pol));
else
page = __alloc_pages_nodemask(gfp, order,
policy_node(gfp, pol, numa_node_id()),
policy_nodemask(gfp, pol));
return page;
}
EXPORT_SYMBOL(alloc_pages_current);
int vma_dup_policy(struct vm_area_struct *src, struct vm_area_struct *dst)
{
struct mempolicy *pol = mpol_dup(vma_policy(src));
if (IS_ERR(pol))
return PTR_ERR(pol);
dst->vm_policy = pol;
return 0;
}
/*
* If mpol_dup() sees current->cpuset == cpuset_being_rebound, then it
* rebinds the mempolicy its copying by calling mpol_rebind_policy()
* with the mems_allowed returned by cpuset_mems_allowed(). This
* keeps mempolicies cpuset relative after its cpuset moves. See
* further kernel/cpuset.c update_nodemask().
*
* current's mempolicy may be rebinded by the other task(the task that changes
* cpuset's mems), so we needn't do rebind work for current task.
*/
/* Slow path of a mempolicy duplicate */
struct mempolicy *__mpol_dup(struct mempolicy *old)
{
struct mempolicy *new = kmem_cache_alloc(policy_cache, GFP_KERNEL);
if (!new)
return ERR_PTR(-ENOMEM);
/* task's mempolicy is protected by alloc_lock */
if (old == current->mempolicy) {
task_lock(current);
*new = *old;
task_unlock(current);
} else
*new = *old;
if (current_cpuset_is_being_rebound()) {
nodemask_t mems = cpuset_mems_allowed(current);
mpol_rebind_policy(new, &mems);
}
atomic_set(&new->refcnt, 1);
return new;
}
/* Slow path of a mempolicy comparison */
bool __mpol_equal(struct mempolicy *a, struct mempolicy *b)
{
if (!a || !b)
return false;
if (a->mode != b->mode)
return false;
if (a->flags != b->flags)
return false;
if (mpol_store_user_nodemask(a))
if (!nodes_equal(a->w.user_nodemask, b->w.user_nodemask))
return false;
switch (a->mode) {
case MPOL_BIND:
/* Fall through */
case MPOL_INTERLEAVE:
return !!nodes_equal(a->v.nodes, b->v.nodes);
case MPOL_PREFERRED:
/* a's ->flags is the same as b's */
if (a->flags & MPOL_F_LOCAL)
return true;
return a->v.preferred_node == b->v.preferred_node;
default:
BUG();
return false;
}
}
/*
* Shared memory backing store policy support.
*
* Remember policies even when nobody has shared memory mapped.
* The policies are kept in Red-Black tree linked from the inode.
* They are protected by the sp->lock rwlock, which should be held
* for any accesses to the tree.
*/
/*
* lookup first element intersecting start-end. Caller holds sp->lock for
* reading or for writing
*/
static struct sp_node *
sp_lookup(struct shared_policy *sp, unsigned long start, unsigned long end)
{
struct rb_node *n = sp->root.rb_node;
while (n) {
struct sp_node *p = rb_entry(n, struct sp_node, nd);
if (start >= p->end)
n = n->rb_right;
else if (end <= p->start)
n = n->rb_left;
else
break;
}
if (!n)
return NULL;
for (;;) {
struct sp_node *w = NULL;
struct rb_node *prev = rb_prev(n);
if (!prev)
break;
w = rb_entry(prev, struct sp_node, nd);
if (w->end <= start)
break;
n = prev;
}
return rb_entry(n, struct sp_node, nd);
}
/*
* Insert a new shared policy into the list. Caller holds sp->lock for
* writing.
*/
static void sp_insert(struct shared_policy *sp, struct sp_node *new)
{
struct rb_node **p = &sp->root.rb_node;
struct rb_node *parent = NULL;
struct sp_node *nd;
while (*p) {
parent = *p;
nd = rb_entry(parent, struct sp_node, nd);
if (new->start < nd->start)
p = &(*p)->rb_left;
else if (new->end > nd->end)
p = &(*p)->rb_right;
else
BUG();
}
rb_link_node(&new->nd, parent, p);
rb_insert_color(&new->nd, &sp->root);
pr_debug("inserting %lx-%lx: %d\n", new->start, new->end,
new->policy ? new->policy->mode : 0);
}
/* Find shared policy intersecting idx */
struct mempolicy *
mpol_shared_policy_lookup(struct shared_policy *sp, unsigned long idx)
{
struct mempolicy *pol = NULL;
struct sp_node *sn;
if (!sp->root.rb_node)
return NULL;
read_lock(&sp->lock);
sn = sp_lookup(sp, idx, idx+1);
if (sn) {
mpol_get(sn->policy);
pol = sn->policy;
}
read_unlock(&sp->lock);
return pol;
}
static void sp_free(struct sp_node *n)
{
mpol_put(n->policy);
kmem_cache_free(sn_cache, n);
}
/**
* mpol_misplaced - check whether current page node is valid in policy
*
* @page: page to be checked
* @vma: vm area where page mapped
* @addr: virtual address where page mapped
*
* Lookup current policy node id for vma,addr and "compare to" page's
* node id.
*
* Returns:
* -1 - not misplaced, page is in the right node
* node - node id where the page should be
*
* Policy determination "mimics" alloc_page_vma().
* Called from fault path where we know the vma and faulting address.
*/
int mpol_misplaced(struct page *page, struct vm_area_struct *vma, unsigned long addr)
{
struct mempolicy *pol;
struct zoneref *z;
int curnid = page_to_nid(page);
unsigned long pgoff;
int thiscpu = raw_smp_processor_id();
int thisnid = cpu_to_node(thiscpu);
int polnid = NUMA_NO_NODE;
int ret = -1;
pol = get_vma_policy(vma, addr);
if (!(pol->flags & MPOL_F_MOF))
goto out;
switch (pol->mode) {
case MPOL_INTERLEAVE:
pgoff = vma->vm_pgoff;
pgoff += (addr - vma->vm_start) >> PAGE_SHIFT;
polnid = offset_il_node(pol, pgoff);
break;
case MPOL_PREFERRED:
if (pol->flags & MPOL_F_LOCAL)
polnid = numa_node_id();
else
polnid = pol->v.preferred_node;
break;
case MPOL_BIND:
/*
* allows binding to multiple nodes.
* use current page if in policy nodemask,
* else select nearest allowed node, if any.
* If no allowed nodes, use current [!misplaced].
*/
if (node_isset(curnid, pol->v.nodes))
goto out;
z = first_zones_zonelist(
node_zonelist(numa_node_id(), GFP_HIGHUSER),
gfp_zone(GFP_HIGHUSER),
&pol->v.nodes);
polnid = zone_to_nid(z->zone);
break;
default:
BUG();
}
/* Migrate the page towards the node whose CPU is referencing it */
if (pol->flags & MPOL_F_MORON) {
polnid = thisnid;
if (!should_numa_migrate_memory(current, page, curnid, thiscpu))
goto out;
}
if (curnid != polnid)
ret = polnid;
out:
mpol_cond_put(pol);
return ret;
}
/*
* Drop the (possibly final) reference to task->mempolicy. It needs to be
* dropped after task->mempolicy is set to NULL so that any allocation done as
* part of its kmem_cache_free(), such as by KASAN, doesn't reference a freed
* policy.
*/
void mpol_put_task_policy(struct task_struct *task)
{
struct mempolicy *pol;
task_lock(task);
pol = task->mempolicy;
task->mempolicy = NULL;
task_unlock(task);
mpol_put(pol);
}
static void sp_delete(struct shared_policy *sp, struct sp_node *n)
{
pr_debug("deleting %lx-l%lx\n", n->start, n->end);
rb_erase(&n->nd, &sp->root);
sp_free(n);
}
static void sp_node_init(struct sp_node *node, unsigned long start,
unsigned long end, struct mempolicy *pol)
{
node->start = start;
node->end = end;
node->policy = pol;
}
static struct sp_node *sp_alloc(unsigned long start, unsigned long end,
struct mempolicy *pol)
{
struct sp_node *n;
struct mempolicy *newpol;
n = kmem_cache_alloc(sn_cache, GFP_KERNEL);
if (!n)
return NULL;
newpol = mpol_dup(pol);
if (IS_ERR(newpol)) {
kmem_cache_free(sn_cache, n);
return NULL;
}
newpol->flags |= MPOL_F_SHARED;
sp_node_init(n, start, end, newpol);
return n;
}
/* Replace a policy range. */
static int shared_policy_replace(struct shared_policy *sp, unsigned long start,
unsigned long end, struct sp_node *new)
{
struct sp_node *n;
struct sp_node *n_new = NULL;
struct mempolicy *mpol_new = NULL;
int ret = 0;
restart:
write_lock(&sp->lock);
n = sp_lookup(sp, start, end);
/* Take care of old policies in the same range. */
while (n && n->start < end) {
struct rb_node *next = rb_next(&n->nd);
if (n->start >= start) {
if (n->end <= end)
sp_delete(sp, n);
else
n->start = end;
} else {
/* Old policy spanning whole new range. */
if (n->end > end) {
if (!n_new)
goto alloc_new;
*mpol_new = *n->policy;
atomic_set(&mpol_new->refcnt, 1);
sp_node_init(n_new, end, n->end, mpol_new);
n->end = start;
sp_insert(sp, n_new);
n_new = NULL;
mpol_new = NULL;
break;
} else
n->end = start;
}
if (!next)
break;
n = rb_entry(next, struct sp_node, nd);
}
if (new)
sp_insert(sp, new);
write_unlock(&sp->lock);
ret = 0;
err_out:
if (mpol_new)
mpol_put(mpol_new);
if (n_new)
kmem_cache_free(sn_cache, n_new);
return ret;
alloc_new:
write_unlock(&sp->lock);
ret = -ENOMEM;
n_new = kmem_cache_alloc(sn_cache, GFP_KERNEL);
if (!n_new)
goto err_out;
mpol_new = kmem_cache_alloc(policy_cache, GFP_KERNEL);
if (!mpol_new)
goto err_out;
goto restart;
}
/**
* mpol_shared_policy_init - initialize shared policy for inode
* @sp: pointer to inode shared policy
* @mpol: struct mempolicy to install
*
* Install non-NULL @mpol in inode's shared policy rb-tree.
* On entry, the current task has a reference on a non-NULL @mpol.
* This must be released on exit.
* This is called at get_inode() calls and we can use GFP_KERNEL.
*/
void mpol_shared_policy_init(struct shared_policy *sp, struct mempolicy *mpol)
{
int ret;
sp->root = RB_ROOT; /* empty tree == default mempolicy */
rwlock_init(&sp->lock);
if (mpol) {
struct vm_area_struct pvma;
struct mempolicy *new;
NODEMASK_SCRATCH(scratch);
if (!scratch)
goto put_mpol;
/* contextualize the tmpfs mount point mempolicy */
new = mpol_new(mpol->mode, mpol->flags, &mpol->w.user_nodemask);
if (IS_ERR(new))
goto free_scratch; /* no valid nodemask intersection */
task_lock(current);
ret = mpol_set_nodemask(new, &mpol->w.user_nodemask, scratch);
task_unlock(current);
if (ret)
goto put_new;
/* Create pseudo-vma that contains just the policy */
vma_init(&pvma, NULL);
pvma.vm_end = TASK_SIZE; /* policy covers entire file */
mpol_set_shared_policy(sp, &pvma, new); /* adds ref */
put_new:
mpol_put(new); /* drop initial ref */
free_scratch:
NODEMASK_SCRATCH_FREE(scratch);
put_mpol:
mpol_put(mpol); /* drop our incoming ref on sb mpol */
}
}
int mpol_set_shared_policy(struct shared_policy *info,
struct vm_area_struct *vma, struct mempolicy *npol)
{
int err;
struct sp_node *new = NULL;
unsigned long sz = vma_pages(vma);
pr_debug("set_shared_policy %lx sz %lu %d %d %lx\n",
vma->vm_pgoff,
sz, npol ? npol->mode : -1,
npol ? npol->flags : -1,
npol ? nodes_addr(npol->v.nodes)[0] : NUMA_NO_NODE);
if (npol) {
new = sp_alloc(vma->vm_pgoff, vma->vm_pgoff + sz, npol);
if (!new)
return -ENOMEM;
}
err = shared_policy_replace(info, vma->vm_pgoff, vma->vm_pgoff+sz, new);
if (err && new)
sp_free(new);
return err;
}
/* Free a backing policy store on inode delete. */
void mpol_free_shared_policy(struct shared_policy *p)
{
struct sp_node *n;
struct rb_node *next;
if (!p->root.rb_node)
return;
write_lock(&p->lock);
next = rb_first(&p->root);
while (next) {
n = rb_entry(next, struct sp_node, nd);
next = rb_next(&n->nd);
sp_delete(p, n);
}
write_unlock(&p->lock);
}
#ifdef CONFIG_NUMA_BALANCING
static int __initdata numabalancing_override;
static void __init check_numabalancing_enable(void)
{
bool numabalancing_default = false;
if (IS_ENABLED(CONFIG_NUMA_BALANCING_DEFAULT_ENABLED))
numabalancing_default = true;
/* Parsed by setup_numabalancing. override == 1 enables, -1 disables */
if (numabalancing_override)
set_numabalancing_state(numabalancing_override == 1);
if (num_online_nodes() > 1 && !numabalancing_override) {
pr_info("%s automatic NUMA balancing. Configure with numa_balancing= or the kernel.numa_balancing sysctl\n",
numabalancing_default ? "Enabling" : "Disabling");
set_numabalancing_state(numabalancing_default);
}
}
static int __init setup_numabalancing(char *str)
{
int ret = 0;
if (!str)
goto out;
if (!strcmp(str, "enable")) {
numabalancing_override = 1;
ret = 1;
} else if (!strcmp(str, "disable")) {
numabalancing_override = -1;
ret = 1;
}
out:
if (!ret)
pr_warn("Unable to parse numa_balancing=\n");
return ret;
}
__setup("numa_balancing=", setup_numabalancing);
#else
static inline void __init check_numabalancing_enable(void)
{
}
#endif /* CONFIG_NUMA_BALANCING */
/* assumes fs == KERNEL_DS */
void __init numa_policy_init(void)
{
nodemask_t interleave_nodes;
unsigned long largest = 0;
int nid, prefer = 0;
policy_cache = kmem_cache_create("numa_policy",
sizeof(struct mempolicy),
0, SLAB_PANIC, NULL);
sn_cache = kmem_cache_create("shared_policy_node",
sizeof(struct sp_node),
0, SLAB_PANIC, NULL);
for_each_node(nid) {
preferred_node_policy[nid] = (struct mempolicy) {
.refcnt = ATOMIC_INIT(1),
.mode = MPOL_PREFERRED,
.flags = MPOL_F_MOF | MPOL_F_MORON,
.v = { .preferred_node = nid, },
};
}
/*
* Set interleaving policy for system init. Interleaving is only
* enabled across suitably sized nodes (default is >= 16MB), or
* fall back to the largest node if they're all smaller.
*/
nodes_clear(interleave_nodes);
for_each_node_state(nid, N_MEMORY) {
unsigned long total_pages = node_present_pages(nid);
/* Preserve the largest node */
if (largest < total_pages) {
largest = total_pages;
prefer = nid;
}
/* Interleave this node? */
if ((total_pages << PAGE_SHIFT) >= (16 << 20))
node_set(nid, interleave_nodes);
}
/* All too small, use the largest */
if (unlikely(nodes_empty(interleave_nodes)))
node_set(prefer, interleave_nodes);
if (do_set_mempolicy(MPOL_INTERLEAVE, 0, &interleave_nodes))
pr_err("%s: interleaving failed\n", __func__);
check_numabalancing_enable();
}
/* Reset policy of current process to default */
void numa_default_policy(void)
{
do_set_mempolicy(MPOL_DEFAULT, 0, NULL);
}
/*
* Parse and format mempolicy from/to strings
*/
/*
* "local" is implemented internally by MPOL_PREFERRED with MPOL_F_LOCAL flag.
*/
static const char * const policy_modes[] =
{
[MPOL_DEFAULT] = "default",
[MPOL_PREFERRED] = "prefer",
[MPOL_BIND] = "bind",
[MPOL_INTERLEAVE] = "interleave",
[MPOL_LOCAL] = "local",
};
#ifdef CONFIG_TMPFS
/**
* mpol_parse_str - parse string to mempolicy, for tmpfs mpol mount option.
* @str: string containing mempolicy to parse
* @mpol: pointer to struct mempolicy pointer, returned on success.
*
* Format of input:
* <mode>[=<flags>][:<nodelist>]
*
* On success, returns 0, else 1
*/
int mpol_parse_str(char *str, struct mempolicy **mpol)
{
struct mempolicy *new = NULL;
unsigned short mode_flags;
nodemask_t nodes;
char *nodelist = strchr(str, ':');
char *flags = strchr(str, '=');
int err = 1, mode;
if (flags)
*flags++ = '\0'; /* terminate mode string */
if (nodelist) {
/* NUL-terminate mode or flags string */
*nodelist++ = '\0';
if (nodelist_parse(nodelist, nodes))
goto out;
if (!nodes_subset(nodes, node_states[N_MEMORY]))
goto out;
} else
nodes_clear(nodes);
mode = match_string(policy_modes, MPOL_MAX, str);
if (mode < 0)
goto out;
switch (mode) {
case MPOL_PREFERRED:
/*
* Insist on a nodelist of one node only
*/
if (nodelist) {
char *rest = nodelist;
while (isdigit(*rest))
rest++;
if (*rest)
goto out;
}
break;
case MPOL_INTERLEAVE:
/*
* Default to online nodes with memory if no nodelist
*/
if (!nodelist)
nodes = node_states[N_MEMORY];
break;
case MPOL_LOCAL:
/*
* Don't allow a nodelist; mpol_new() checks flags
*/
if (nodelist)
goto out;
mode = MPOL_PREFERRED;
break;
case MPOL_DEFAULT:
/*
* Insist on a empty nodelist
*/
if (!nodelist)
err = 0;
goto out;
case MPOL_BIND:
/*
* Insist on a nodelist
*/
if (!nodelist)
goto out;
}
mode_flags = 0;
if (flags) {
/*
* Currently, we only support two mutually exclusive
* mode flags.
*/
if (!strcmp(flags, "static"))
mode_flags |= MPOL_F_STATIC_NODES;
else if (!strcmp(flags, "relative"))
mode_flags |= MPOL_F_RELATIVE_NODES;
else
goto out;
}
new = mpol_new(mode, mode_flags, &nodes);
if (IS_ERR(new))
goto out;
/*
* Save nodes for mpol_to_str() to show the tmpfs mount options
* for /proc/mounts, /proc/pid/mounts and /proc/pid/mountinfo.
*/
if (mode != MPOL_PREFERRED)
new->v.nodes = nodes;
else if (nodelist)
new->v.preferred_node = first_node(nodes);
else
new->flags |= MPOL_F_LOCAL;
/*
* Save nodes for contextualization: this will be used to "clone"
* the mempolicy in a specific context [cpuset] at a later time.
*/
new->w.user_nodemask = nodes;
err = 0;
out:
/* Restore string for error message */
if (nodelist)
*--nodelist = ':';
if (flags)
*--flags = '=';
if (!err)
*mpol = new;
return err;
}
#endif /* CONFIG_TMPFS */
/**
* mpol_to_str - format a mempolicy structure for printing
* @buffer: to contain formatted mempolicy string
* @maxlen: length of @buffer
* @pol: pointer to mempolicy to be formatted
*
* Convert @pol into a string. If @buffer is too short, truncate the string.
* Recommend a @maxlen of at least 32 for the longest mode, "interleave", the
* longest flag, "relative", and to display at least a few node ids.
*/
void mpol_to_str(char *buffer, int maxlen, struct mempolicy *pol)
{
char *p = buffer;
nodemask_t nodes = NODE_MASK_NONE;
unsigned short mode = MPOL_DEFAULT;
unsigned short flags = 0;
if (pol && pol != &default_policy && !(pol->flags & MPOL_F_MORON)) {
mode = pol->mode;
flags = pol->flags;
}
switch (mode) {
case MPOL_DEFAULT:
break;
case MPOL_PREFERRED:
if (flags & MPOL_F_LOCAL)
mode = MPOL_LOCAL;
else
node_set(pol->v.preferred_node, nodes);
break;
case MPOL_BIND:
case MPOL_INTERLEAVE:
nodes = pol->v.nodes;
break;
default:
WARN_ON_ONCE(1);
snprintf(p, maxlen, "unknown");
return;
}
p += snprintf(p, maxlen, "%s", policy_modes[mode]);
if (flags & MPOL_MODE_FLAGS) {
p += snprintf(p, buffer + maxlen - p, "=");
/*
* Currently, the only defined flags are mutually exclusive
*/
if (flags & MPOL_F_STATIC_NODES)
p += snprintf(p, buffer + maxlen - p, "static");
else if (flags & MPOL_F_RELATIVE_NODES)
p += snprintf(p, buffer + maxlen - p, "relative");
}
if (!nodes_empty(nodes))
p += scnprintf(p, buffer + maxlen - p, ":%*pbl",
nodemask_pr_args(&nodes));
}
| ./CrossVul/dataset_final_sorted/CWE-787/c/bad_2457_0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.