file
stringlengths 18
26
| data
stringlengths 3
1.04M
|
---|---|
the_stack_data/72012035.c | /**
* Copyright (c) 2015 - 2019, Nordic Semiconductor ASA
*
* 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, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, 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 Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifdef COMMISSIONING_ENABLED
#include <string.h>
#include "ble_ncfgs.h"
#include "app_error.h"
#include "ble.h"
#include "nordic_common.h"
/**@brief NCFGS database encapsulation. */
typedef struct
{
uint16_t service_handle;
ble_gatts_char_handles_t ssid_handles;
ble_gatts_char_handles_t keys_store_handles;
ble_gatts_char_handles_t ctrlp_handles;
} ble_database_t;
static ble_ncfgs_state_t m_service_state = NCFGS_STATE_IDLE; /**< Module state value. */
static ble_ncfgs_evt_handler_t m_app_evt_handler; /**< Parent module callback function. */
static ble_database_t m_database; /**< GATT handles database. */
static uint8_t m_ctrlp_value_buffer[NCFGS_CTRLP_VALUE_LEN]; /**< Stores received Control Point value before parsing. */
static ble_ncfgs_data_t m_ncfgs_data; /**< Stores all values written by the peer device. */
#if NCFGS_CONFIG_LOG_ENABLED
#define NRF_LOG_MODULE_NAME ble_ncfgs
#define NRF_LOG_LEVEL NCFGS_CONFIG_LOG_LEVEL
#define NRF_LOG_INFO_COLOR NCFGS_CONFIG_INFO_COLOR
#define NRF_LOG_DEBUG_COLOR NCFGS_CONFIG_DEBUG_COLOR
#include "nrf_log.h"
NRF_LOG_MODULE_REGISTER();
#define NCFGS_TRC NRF_LOG_DEBUG /**< Used for getting trace of execution in the module. */
#define NCFGS_ERR NRF_LOG_ERROR /**< Used for logging errors in the module. */
#define NCFGS_DUMP NRF_LOG_HEXDUMP_DEBUG /**< Used for dumping octet information to get details of bond information etc. */
#define NCFGS_ENTRY() NCFGS_TRC(">> %s", __func__)
#define NCFGS_EXIT() NCFGS_TRC("<< %s", __func__)
#else // NCFGS_CONFIG_LOG_ENABLED
#define NCFGS_TRC(...) /**< Disables traces. */
#define NCFGS_DUMP(...) /**< Disables dumping of octet streams. */
#define NCFGS_ERR(...) /**< Disables error logs. */
#define NCFGS_ENTRY(...)
#define NCFGS_EXIT(...)
#endif // NCFGS_CONFIG_LOG_ENABLED
/**@brief Function for adding the SSID Store characteristic.
*
* @return NRF_SUCCESS on success, otherwise an error code.
*/
static uint32_t add_ssid_characteristic(ble_uuid_t * p_srv_uuid)
{
ble_gatts_char_md_t char_md;
ble_gatts_attr_t attr_char_value;
ble_uuid_t char_uuid;
ble_gatts_attr_md_t attr_md;
memset(&char_md, 0x00, sizeof(char_md));
char_md.char_props.read = 1;
char_md.char_props.write = 1;
memset(&attr_md, 0x00, sizeof(attr_md));
BLE_GAP_CONN_SEC_MODE_SET_OPEN(&attr_md.read_perm);
BLE_GAP_CONN_SEC_MODE_SET_OPEN(&attr_md.write_perm);
attr_md.wr_auth = 1;
attr_md.vloc = BLE_GATTS_VLOC_USER;
memset(&attr_char_value, 0x00, sizeof(attr_char_value));
char_uuid.type = p_srv_uuid->type;
char_uuid.uuid = BLE_UUID_NCFGS_SSID_CHAR;
attr_char_value.p_uuid = &char_uuid;
attr_char_value.p_attr_md = &attr_md;
attr_char_value.init_len = NCFGS_SSID_MAX_LEN;
attr_char_value.init_offs = 0;
attr_char_value.max_len = NCFGS_SSID_MAX_LEN;
attr_char_value.p_value = &m_ncfgs_data.ssid_from_router.ssid[0];
return sd_ble_gatts_characteristic_add(m_database.service_handle,
&char_md,
&attr_char_value,
&m_database.ssid_handles);
}
/**@brief Function for adding the Keys Store characteristic.
*
* @return NRF_SUCCESS on success, otherwise an error code.
*/
static uint32_t add_keys_store_characteristic(ble_uuid_t * p_srv_uuid)
{
ble_gatts_char_md_t char_md;
ble_gatts_attr_t attr_char_value;
ble_uuid_t char_uuid;
ble_gatts_attr_md_t attr_md;
memset(&char_md, 0x00, sizeof(char_md));
char_md.char_props.read = 1;
char_md.char_props.write = 1;
memset(&attr_md, 0x00, sizeof(attr_md));
BLE_GAP_CONN_SEC_MODE_SET_OPEN(&attr_md.read_perm);
BLE_GAP_CONN_SEC_MODE_SET_OPEN(&attr_md.write_perm);
attr_md.wr_auth = 1;
attr_md.vloc = BLE_GATTS_VLOC_USER;
memset(&attr_char_value, 0x00, sizeof(attr_char_value));
char_uuid.type = p_srv_uuid->type;
char_uuid.uuid = BLE_UUID_NCFGS_KEYS_STORE_CHAR;
attr_char_value.p_uuid = &char_uuid;
attr_char_value.p_attr_md = &attr_md;
attr_char_value.init_len = NCFGS_KEYS_MAX_LEN;
attr_char_value.init_offs = 0;
attr_char_value.max_len = NCFGS_KEYS_MAX_LEN;
attr_char_value.p_value = &m_ncfgs_data.keys_from_router.keys[0];
return sd_ble_gatts_characteristic_add(m_database.service_handle,
&char_md,
&attr_char_value,
&m_database.keys_store_handles);
}
/**@brief Function for adding the Control Point characteristic.
*
* @return NRF_SUCCESS on success, otherwise an error code.
*/
static uint32_t add_ip_cfg_cp_characteristic(ble_uuid_t * p_srv_uuid)
{
ble_gatts_char_md_t char_md;
ble_gatts_attr_t attr_char_value;
ble_uuid_t char_uuid;
ble_gatts_attr_md_t attr_md;
memset(&char_md, 0x00, sizeof(char_md));
char_md.char_props.read = 1;
char_md.char_props.write = 1;
memset(&attr_md, 0x00, sizeof(attr_md));
BLE_GAP_CONN_SEC_MODE_SET_OPEN(&attr_md.read_perm);
BLE_GAP_CONN_SEC_MODE_SET_OPEN(&attr_md.write_perm);
attr_md.wr_auth = 1;
attr_md.vloc = BLE_GATTS_VLOC_USER;
memset(&attr_char_value, 0x00, sizeof(attr_char_value));
char_uuid.type = p_srv_uuid->type;
char_uuid.uuid = BLE_UUID_NCFGS_CTRLPT_CHAR;
attr_char_value.p_uuid = &char_uuid;
attr_char_value.p_attr_md = &attr_md;
attr_char_value.init_len = NCFGS_CTRLP_VALUE_LEN;
attr_char_value.init_offs = 0;
attr_char_value.max_len = NCFGS_CTRLP_VALUE_LEN;
attr_char_value.p_value = &m_ctrlp_value_buffer[0];
return sd_ble_gatts_characteristic_add(m_database.service_handle,
&char_md,
&attr_char_value,
&m_database.ctrlp_handles);
}
/**@brief Function for creating the GATT database.
*
* @return NRF_SUCCESS on success, otherwise an error code.
*/
static uint32_t ble_ncfgs_create_database(void)
{
uint32_t err_code = NRF_SUCCESS;
// Add service.
ble_uuid_t service_uuid;
const ble_uuid128_t base_uuid128 =
{
{
0x73, 0x3E, 0x2D, 0x02, 0xB7, 0x6B, 0xBE, 0xBE, \
0xE5, 0x4F, 0x40, 0x8F, 0x00, 0x00, 0x20, 0x54
}
};
service_uuid.uuid = BLE_UUID_NODE_CFG_SERVICE;
err_code = sd_ble_uuid_vs_add(&base_uuid128, &(service_uuid.type));
if (err_code != NRF_SUCCESS)
{
return err_code;
}
err_code = sd_ble_gatts_service_add(BLE_GATTS_SRVC_TYPE_PRIMARY, \
&service_uuid, \
&m_database.service_handle);
if (err_code != NRF_SUCCESS)
{
return err_code;
}
err_code = add_ssid_characteristic(&service_uuid);
if (err_code != NRF_SUCCESS)
{
return err_code;
}
err_code = add_keys_store_characteristic(&service_uuid);
if (err_code != NRF_SUCCESS)
{
return err_code;
}
err_code = add_ip_cfg_cp_characteristic(&service_uuid);
if (err_code != NRF_SUCCESS)
{
return err_code;
}
return err_code;
}
uint32_t ble_ncfgs_init(ble_ncfgs_evt_handler_t ble_ncfgs_cb)
{
NCFGS_ENTRY();
uint32_t err_code;
memset(&m_ncfgs_data, 0x00, sizeof(m_ncfgs_data));
m_app_evt_handler = ble_ncfgs_cb;
err_code = ble_ncfgs_create_database();
NCFGS_EXIT();
return err_code;
}
/**@brief Function for decoding the Control Point characteristic value.
*
* @return NRF_SUCCESS on success, otherwise an error code.
*/
static uint32_t ctrlp_value_decode(const ble_evt_t * p_ble_evt)
{
uint16_t wr_req_value_len = \
p_ble_evt->evt.gatts_evt.params.authorize_request.request.write.len;
memcpy(m_ctrlp_value_buffer, \
p_ble_evt->evt.gatts_evt.params.authorize_request.request.write.data, \
wr_req_value_len);
m_ncfgs_data.ctrlp_value.opcode = \
(ble_ncfgs_opcode_t)m_ctrlp_value_buffer[0];
memcpy((void *)&m_ncfgs_data.ctrlp_value.delay_sec, \
&m_ctrlp_value_buffer[NCFGS_CTRLP_OPCODE_LEN], \
sizeof(uint32_t));
m_ncfgs_data.ctrlp_value.delay_sec = \
HTONL(m_ncfgs_data.ctrlp_value.delay_sec);
memcpy((void *)&m_ncfgs_data.ctrlp_value.duration_sec, \
&m_ctrlp_value_buffer[NCFGS_CTRLP_OPCODE_LEN+NCFGS_CTRLP_DELAY_LEN], \
sizeof(uint32_t));
m_ncfgs_data.ctrlp_value.duration_sec = \
HTONL(m_ncfgs_data.ctrlp_value.duration_sec);
m_ncfgs_data.ctrlp_value.state_on_failure = \
(state_on_failure_t)m_ctrlp_value_buffer[NCFGS_CTRLP_OPCODE_LEN+ \
NCFGS_CTRLP_DELAY_LEN+ \
NCFGS_CTRLP_DURATION_LEN];
if ((m_ncfgs_data.ctrlp_value.state_on_failure != NCFGS_SOF_NO_CHANGE) && \
(m_ncfgs_data.ctrlp_value.state_on_failure != NCFGS_SOF_PWR_OFF) && \
(m_ncfgs_data.ctrlp_value.state_on_failure != NCFGS_SOF_CONFIG_MODE))
{
return NRF_ERROR_INVALID_DATA;
}
uint16_t id_data_len = wr_req_value_len - NCFGS_CTRLP_ALL_BUT_ID_DATA_LEN;
if (id_data_len != 0)
{
m_ncfgs_data.id_data.identity_data_len = id_data_len;
memcpy(m_ncfgs_data.id_data.identity_data, \
&m_ctrlp_value_buffer[NCFGS_CTRLP_ALL_BUT_ID_DATA_LEN], \
id_data_len);
}
return NRF_SUCCESS;
}
void ble_ncfgs_ble_evt_handler(const ble_evt_t * p_ble_evt)
{
switch (p_ble_evt->header.evt_id)
{
case BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST:
{
if (p_ble_evt->evt.gatts_evt.params.authorize_request.request.write.op == \
BLE_GATTS_OP_WRITE_REQ)
{
uint16_t wr_req_handle = \
p_ble_evt->evt.gatts_evt.params.authorize_request.request.write.handle;
uint16_t wr_req_value_len = \
p_ble_evt->evt.gatts_evt.params.authorize_request.request.write.len;
ble_gatts_rw_authorize_reply_params_t reply_params;
memset(&reply_params, 0x00, sizeof(reply_params));
reply_params.type = BLE_GATTS_AUTHORIZE_TYPE_WRITE;
reply_params.params.write.update = 1;
reply_params.params.write.offset = p_ble_evt->evt.gatts_evt.params.authorize_request.request.write.offset;
reply_params.params.write.len = p_ble_evt->evt.gatts_evt.params.authorize_request.request.write.len;
reply_params.params.write.p_data = p_ble_evt->evt.gatts_evt.params.authorize_request.request.write.data;
if (wr_req_handle == m_database.ssid_handles.value_handle)
{
NCFGS_TRC("> wr_req: ssid_handle");
if ((wr_req_value_len > NCFGS_SSID_MAX_LEN) || \
(wr_req_value_len < NCFGS_SSID_MIN_LEN))
{
reply_params.params.write.gatt_status = \
BLE_GATT_STATUS_ATTERR_INVALID_ATT_VAL_LENGTH;
}
else
{
m_ncfgs_data.ssid_from_router.ssid_len = wr_req_value_len;
m_service_state |= NCFGS_STATE_SSID_WRITTEN;
reply_params.params.write.gatt_status = BLE_GATT_STATUS_SUCCESS;
}
UNUSED_RETURN_VALUE( \
sd_ble_gatts_rw_authorize_reply(p_ble_evt->evt.gap_evt.conn_handle, \
&reply_params));
NCFGS_TRC("< wr_req: ssid_handle");
return;
}
else if (wr_req_handle == m_database.keys_store_handles.value_handle)
{
NCFGS_TRC("> wr_req: keys_store_handle");
if (wr_req_value_len > NCFGS_KEYS_MAX_LEN)
{
reply_params.params.write.gatt_status = \
BLE_GATT_STATUS_ATTERR_INVALID_ATT_VAL_LENGTH;
}
else
{
m_ncfgs_data.keys_from_router.keys_len = wr_req_value_len;
m_service_state |= NCFGS_STATE_KEYS_STORE_WRITTEN;
reply_params.params.write.gatt_status = BLE_GATT_STATUS_SUCCESS;
}
UNUSED_RETURN_VALUE( \
sd_ble_gatts_rw_authorize_reply(p_ble_evt->evt.gap_evt.conn_handle, \
&reply_params));
NCFGS_TRC("< wr_req: keys_store_handle");
return;
}
else if (wr_req_handle == m_database.ctrlp_handles.value_handle)
{
NCFGS_TRC("> wr_req: ctrlp_handle");
bool notify_app = false;
if ((wr_req_value_len > NCFGS_CTRLP_VALUE_LEN) || \
(wr_req_value_len < NCFGS_CTRLP_ALL_BUT_ID_DATA_LEN))
{
reply_params.params.write.gatt_status = \
BLE_GATT_STATUS_ATTERR_INVALID_ATT_VAL_LENGTH;
}
else
{
ble_ncfgs_opcode_t opcode_in = (ble_ncfgs_opcode_t) \
p_ble_evt->evt.gatts_evt.params.authorize_request.request.write.data[0];
reply_params.params.write.gatt_status = BLE_GATT_STATUS_SUCCESS;
if ((opcode_in != NCFGS_OPCODE_GOTO_JOINING_MODE) && \
(opcode_in != NCFGS_OPCODE_GOTO_CONFIG_MODE) && \
(opcode_in != NCFGS_OPCODE_GOTO_IDENTITY_MODE))
{
reply_params.params.write.gatt_status = APP_GATTERR_UNKNOWN_OPCODE;
}
if (opcode_in == NCFGS_OPCODE_GOTO_JOINING_MODE)
{
if (!((m_service_state & NCFGS_STATE_SSID_WRITTEN) && \
(m_service_state & NCFGS_STATE_KEYS_STORE_WRITTEN)))
{
reply_params.params.write.gatt_status = APP_GATTERR_NOT_CONFIGURED;
}
}
if (reply_params.params.write.gatt_status == BLE_GATT_STATUS_SUCCESS)
{
uint32_t err_code = ctrlp_value_decode(p_ble_evt);
if (err_code != NRF_SUCCESS)
{
reply_params.params.write.gatt_status = \
APP_GATTERR_INVALID_ATTR_VALUE;
}
else
{
notify_app = true;
}
}
}
UNUSED_RETURN_VALUE(sd_ble_gatts_rw_authorize_reply(
p_ble_evt->evt.gap_evt.conn_handle,
&reply_params));
if (notify_app == true)
{
NCFGS_TRC("> do notify parent");
m_app_evt_handler(&m_ncfgs_data);
NCFGS_TRC("< do notify parent");
}
NCFGS_TRC("< wr_req: ctrlp_handle");
}
else
{
// Invalid handle.
reply_params.params.write.gatt_status = BLE_GATT_STATUS_ATTERR_INVALID_HANDLE;
UNUSED_RETURN_VALUE(sd_ble_gatts_rw_authorize_reply(
p_ble_evt->evt.gap_evt.conn_handle, &reply_params));
}
}
break;
}
case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST:
{
ble_gap_data_length_params_t dl_params;
// Clearing the struct will effectively set members to @ref BLE_GAP_DATA_LENGTH_AUTO.
memset(&dl_params, 0, sizeof(ble_gap_data_length_params_t));
UNUSED_RETURN_VALUE(sd_ble_gap_data_length_update(p_ble_evt->evt.gap_evt.conn_handle, &dl_params, NULL));
break;
}
case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
{
NCFGS_TRC("> PHY update request.");
ble_gap_phys_t const phys =
{
.rx_phys = BLE_GAP_PHY_AUTO,
.tx_phys = BLE_GAP_PHY_AUTO,
};
UNUSED_RETURN_VALUE(sd_ble_gap_phy_update(p_ble_evt->evt.gap_evt.conn_handle, &phys);
NCFGS_TRC("< PHY update request.");
break;
}
default:
{
break;
}
}
}
#endif // COMMISSIONING_ENABLED
|
the_stack_data/1005135.c | #include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <errno.h>
void* thread1Print(void * params __attribute__ ((unused))){
printf("I am thread 1\n");
return NULL;
}
void* thread2Print(void * params __attribute__ ((unused))){
printf("I am thread 2\n");
return NULL;
}
int main(int argc __attribute__ ((unused)), char **argv __attribute__ ((unused))){
int err = 0;
void * ret;
pthread_t t1;
pthread_t t2;
err = pthread_create(&t1, NULL, thread1Print, NULL);
if(err) {
fprintf(stderr, "ERR: pthread_create returned %d\n", err);
exit(1);
}
err = pthread_create(&t2, NULL, thread2Print, NULL);
if(err) {
fprintf(stderr, "ERR: pthread_create returned %d\n", err);
exit(1);
}
err = pthread_join(t1, &ret);
if (err) {
fprintf(stderr, "ERR: pthread_join returned %d\n", err);
exit(1);
}
err = pthread_join(t2, &ret);
if (err) {
fprintf(stderr, "ERR: pthread_join returned %d\n", err);
exit(1);
}
printf("I am thread 0\n");
return 0;
}
|
the_stack_data/51699450.c | /* readtex.c */
/*
* Read an SGI .rgb image file and generate a mipmap texture set.
* Much of this code was borrowed from SGI's tk OpenGL toolkit.
*/
#include <GL/gl.h>
#include <GL/glu.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef SEEK_SET
# define SEEK_SET 0
#endif
/*
** RGB Image Structure
*/
typedef struct _TK_RGBImageRec {
GLint sizeX, sizeY;
GLint components;
unsigned char *data;
} TK_RGBImageRec;
/******************************************************************************/
typedef struct _rawImageRec {
unsigned short imagic;
unsigned short type;
unsigned short dim;
unsigned short sizeX, sizeY, sizeZ;
unsigned long min, max;
unsigned long wasteBytes;
char name[80];
unsigned long colorMap;
FILE *file;
unsigned char *tmp, *tmpR, *tmpG, *tmpB, *tmpA;
unsigned long rleEnd;
GLuint *rowStart;
GLint *rowSize;
} rawImageRec;
/******************************************************************************/
static void ConvertShort(unsigned short *array, long length)
{
unsigned long b1, b2;
unsigned char *ptr;
ptr = (unsigned char *)array;
while (length--) {
b1 = *ptr++;
b2 = *ptr++;
*array++ = (unsigned short) ((b1 << 8) | (b2));
}
}
static void ConvertLong(GLuint *array, long length)
{
unsigned long b1, b2, b3, b4;
unsigned char *ptr;
ptr = (unsigned char *)array;
while (length--) {
b1 = *ptr++;
b2 = *ptr++;
b3 = *ptr++;
b4 = *ptr++;
*array++ = (b1 << 24) | (b2 << 16) | (b3 << 8) | (b4);
}
}
static rawImageRec *RawImageOpen(const char *fileName)
{
union {
int testWord;
char testByte[4];
} endianTest;
rawImageRec *raw;
GLenum swapFlag;
int x;
endianTest.testWord = 1;
if (endianTest.testByte[0] == 1) {
swapFlag = GL_TRUE;
} else {
swapFlag = GL_FALSE;
}
raw = (rawImageRec *)malloc(sizeof(rawImageRec));
if (raw == NULL) {
fprintf(stderr, "Out of memory!\n");
return NULL;
}
if ((raw->file = fopen(fileName, "rb")) == NULL) {
perror(fileName);
return NULL;
}
fread(raw, 1, 12, raw->file);
if (swapFlag) {
ConvertShort(&raw->imagic, 6);
}
raw->tmp = (unsigned char *)malloc(raw->sizeX*256);
raw->tmpR = (unsigned char *)malloc(raw->sizeX*256);
raw->tmpG = (unsigned char *)malloc(raw->sizeX*256);
raw->tmpB = (unsigned char *)malloc(raw->sizeX*256);
if (raw->sizeZ==4) {
raw->tmpA = (unsigned char *)malloc(raw->sizeX*256);
}
if (raw->tmp == NULL || raw->tmpR == NULL || raw->tmpG == NULL ||
raw->tmpB == NULL) {
fprintf(stderr, "Out of memory!\n");
return NULL;
}
if ((raw->type & 0xFF00) == 0x0100) {
x = raw->sizeY * raw->sizeZ * sizeof(GLuint);
raw->rowStart = (GLuint *)malloc(x);
raw->rowSize = (GLint *)malloc(x);
if (raw->rowStart == NULL || raw->rowSize == NULL) {
fprintf(stderr, "Out of memory!\n");
return NULL;
}
raw->rleEnd = 512 + (2 * x);
fseek(raw->file, 512, SEEK_SET);
fread(raw->rowStart, 1, x, raw->file);
fread(raw->rowSize, 1, x, raw->file);
if (swapFlag) {
ConvertLong(raw->rowStart, (long) (x/sizeof(GLuint)));
ConvertLong((GLuint *)raw->rowSize, (long) (x/sizeof(GLint)));
}
}
return raw;
}
static void RawImageClose(rawImageRec *raw)
{
fclose(raw->file);
free(raw->tmp);
free(raw->tmpR);
free(raw->tmpG);
free(raw->tmpB);
if (raw->sizeZ>3) {
free(raw->tmpA);
}
free(raw);
}
static void RawImageGetRow(rawImageRec *raw, unsigned char *buf, int y, int z)
{
unsigned char *iPtr, *oPtr, pixel;
int count, done = 0;
if ((raw->type & 0xFF00) == 0x0100) {
fseek(raw->file, (long) raw->rowStart[y+z*raw->sizeY], SEEK_SET);
fread(raw->tmp, 1, (unsigned int)raw->rowSize[y+z*raw->sizeY],
raw->file);
iPtr = raw->tmp;
oPtr = buf;
while (!done) {
pixel = *iPtr++;
count = (int)(pixel & 0x7F);
if (!count) {
done = 1;
return;
}
if (pixel & 0x80) {
while (count--) {
*oPtr++ = *iPtr++;
}
} else {
pixel = *iPtr++;
while (count--) {
*oPtr++ = pixel;
}
}
}
} else {
fseek(raw->file, 512+(y*raw->sizeX)+(z*raw->sizeX*raw->sizeY),
SEEK_SET);
fread(buf, 1, raw->sizeX, raw->file);
}
}
static void RawImageGetData(rawImageRec *raw, TK_RGBImageRec *final)
{
unsigned char *ptr;
int i, j;
final->data = (unsigned char *)malloc((raw->sizeX+1)*(raw->sizeY+1)*4);
if (final->data == NULL) {
fprintf(stderr, "Out of memory!\n");
}
ptr = final->data;
for (i = 0; i < (int)(raw->sizeY); i++) {
RawImageGetRow(raw, raw->tmpR, i, 0);
RawImageGetRow(raw, raw->tmpG, i, 1);
RawImageGetRow(raw, raw->tmpB, i, 2);
if (raw->sizeZ>3) {
RawImageGetRow(raw, raw->tmpA, i, 3);
}
for (j = 0; j < (int)(raw->sizeX); j++) {
*ptr++ = *(raw->tmpR + j);
*ptr++ = *(raw->tmpG + j);
*ptr++ = *(raw->tmpB + j);
if (raw->sizeZ>3) {
*ptr++ = *(raw->tmpA + j);
}
}
}
}
static TK_RGBImageRec *tkRGBImageLoad(const char *fileName)
{
rawImageRec *raw;
TK_RGBImageRec *final;
raw = RawImageOpen(fileName);
if (!raw) {
fprintf(stderr, "File not found\n");
return NULL;
}
final = (TK_RGBImageRec *)malloc(sizeof(TK_RGBImageRec));
if (final == NULL) {
fprintf(stderr, "Out of memory!\n");
return NULL;
}
final->sizeX = raw->sizeX;
final->sizeY = raw->sizeY;
final->components = raw->sizeZ;
RawImageGetData(raw, final);
RawImageClose(raw);
return final;
}
static void FreeImage( TK_RGBImageRec *image )
{
free(image->data);
free(image);
}
/*
* Load an SGI .rgb file and generate a set of 2-D mipmaps from it.
* Input: imageFile - name of .rgb to read
* intFormat - internal texture format to use, or number of components
* Return: GL_TRUE if success, GL_FALSE if error.
*/
GLboolean LoadRGBMipmaps( const char *imageFile, GLint intFormat )
{
GLint error;
GLenum format;
TK_RGBImageRec *image;
image = tkRGBImageLoad( imageFile );
if (!image) {
return GL_FALSE;
}
if (image->components==3) {
format = GL_RGB;
}
else if (image->components==4) {
format = GL_RGBA;
}
else {
/* not implemented */
fprintf(stderr,
"Error in LoadRGBMipmaps %d-component images not implemented\n",
image->components );
return GL_FALSE;
}
error = gluBuild2DMipmaps( GL_TEXTURE_2D,
intFormat,
image->sizeX, image->sizeY,
format,
GL_UNSIGNED_BYTE,
image->data );
FreeImage(image);
return error ? GL_FALSE : GL_TRUE;
}
/*
* Load an SGI .rgb file and return a pointer to the image data.
* Input: imageFile - name of .rgb to read
* Output: width - width of image
* height - height of image
* format - format of image (GL_RGB or GL_RGBA)
* Return: pointer to image data or NULL if error
*/
GLubyte *LoadRGBImage( const char *imageFile, GLint *width, GLint *height,
GLenum *format )
{
TK_RGBImageRec *image;
GLint bytes;
GLubyte *buffer;
image = tkRGBImageLoad( imageFile );
if (!image) {
return NULL;
}
if (image->components==3) {
*format = GL_RGB;
}
else if (image->components==4) {
*format = GL_RGBA;
}
else {
/* not implemented */
fprintf(stderr,
"Error in LoadRGBImage %d-component images not implemented\n",
image->components );
return NULL;
}
*width = image->sizeX;
*height = image->sizeY;
bytes = image->sizeX * image->sizeY * image->components;
buffer = (GLubyte *) malloc(bytes);
if (!buffer)
return NULL;
memcpy( (void *) buffer, (void *) image->data, bytes );
FreeImage(image);
return buffer;
}
|
the_stack_data/140766826.c | /* ========================================================================= */
/* === amd_global ========================================================== */
/* ========================================================================= */
/* ------------------------------------------------------------------------- */
/* AMD, Copyright (c) Timothy A. Davis, */
/* Patrick R. Amestoy, and Iain S. Duff. See ../README.txt for License. */
/* email: davis at cise.ufl.edu CISE Department, Univ. of Florida. */
/* web: http://www.cise.ufl.edu/research/sparse/amd */
/* ------------------------------------------------------------------------- */
#include <stdlib.h>
#ifdef MATLAB_MEX_FILE
#include "mex.h"
#include "matrix.h"
#endif
#ifndef NULL
#define NULL 0
#endif
/* ========================================================================= */
/* === Default AMD memory manager ========================================== */
/* ========================================================================= */
/* The user can redefine these global pointers at run-time to change the memory
* manager used by AMD. AMD only uses malloc and free; realloc and calloc are
* include for completeness, in case another package wants to use the same
* memory manager as AMD.
*
* If compiling as a MATLAB mexFunction, the default memory manager is mxMalloc.
* You can also compile AMD as a standard ANSI-C library and link a mexFunction
* against it, and then redefine these pointers at run-time, in your
* mexFunction.
*
* If -DNMALLOC is defined at compile-time, no memory manager is specified at
* compile-time. You must then define these functions at run-time, before
* calling AMD, for AMD to work properly.
*/
#ifndef NMALLOC
#ifdef MATLAB_MEX_FILE
/* MATLAB mexFunction: */
void *(*amd_malloc) (size_t) = mxMalloc ;
void (*amd_free) (void *) = mxFree ;
void *(*amd_realloc) (void *, size_t) = mxRealloc ;
void *(*amd_calloc) (size_t, size_t) = mxCalloc ;
#else
/* standard ANSI-C: */
void *(*amd_malloc) (size_t) = malloc ;
void (*amd_free) (void *) = free ;
void *(*amd_realloc) (void *, size_t) = realloc ;
void *(*amd_calloc) (size_t, size_t) = calloc ;
#endif
#else
/* no memory manager defined at compile-time; you MUST define one at run-time */
void *(*amd_malloc) (size_t) = NULL ;
void (*amd_free) (void *) = NULL ;
void *(*amd_realloc) (void *, size_t) = NULL ;
void *(*amd_calloc) (size_t, size_t) = NULL ;
#endif
/* ========================================================================= */
/* === Default AMD printf routine ========================================== */
/* ========================================================================= */
/* The user can redefine this global pointer at run-time to change the printf
* routine used by AMD. If NULL, no printing occurs.
*
* If -DNPRINT is defined at compile-time, stdio.h is not included. Printing
* can then be enabled at run-time by setting amd_printf to a non-NULL function.
*/
#ifndef NPRINT
#ifdef MATLAB_MEX_FILE
int (*amd_printf) (const char *, ...) = mexPrintf ;
#else
#include <stdio.h>
int (*amd_printf) (const char *, ...) = printf ;
#endif
#else
int (*amd_printf) (const char *, ...) = NULL ;
#endif
|
the_stack_data/68887762.c | /*
# _____ ___ ____ ___ ____
# ____| | ____| | | |____|
# | ___| |____ ___| ____| | \ PS2DEV Open Source Project.
#-----------------------------------------------------------------------
# Copyright 2001-2004, ps2dev - http://www.ps2dev.org
# Licenced under Academic Free License version 2.0
# Review ps2sdk README & LICENSE files for further details.
#
# Convets any file into a PS2's .o file.
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef unsigned char u8;
typedef unsigned short u16;
typedef unsigned int u32;
static int alignment = 16;
static int have_size = 1;
static int have_irx = 0;
static short int put_payload_in_SDATA = 0, put_labels_in_SDATA = 0;
static int SDATA_size_limit = 0;
static u32 LE32(u32 b) {
u32 t = 0x12345678;
if (*((unsigned char*)(&t)) == 0x78) {
return b;
} else {
return ((b & 0xff000000) >> 24) |
((b & 0x00ff0000) >> 8 ) |
((b & 0x0000ff00) << 8 ) |
((b & 0x000000ff) << 24);
}
}
static u16 LE16(u16 b) {
u32 t = 0x12345678;
if (*((unsigned char*)(&t)) == 0x78) {
return b;
} else {
return ((b & 0xff00) >> 8) |
((b & 0x00ff) << 8);
}
}
static unsigned char elf_header[] = {
0x7f, 'E', 'L', 'F', 0x01, 0x01, 0x01, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // e_ident
0x01, 0x00, // e_type (relocatable)
0x08, 0x00, // e_machine (mips)
0x01, 0x00, 0x00, 0x00, // e_version
0x00, 0x00, 0x00, 0x00, // e_entry
0x00, 0x00, 0x00, 0x00, // e_phoff
0x34, 0x00, 0x00, 0x00, // e_shoff
0x01, 0x40, 0x92, 0x20, // e_flags
0x34, 0x00, // e_ehsize
0x00, 0x00, // e_phentsize
0x00, 0x00, // e_phnum
0x28, 0x00, // e_shentsize
0x05, 0x00, // e_shnum
0x01, 0x00, // e_shstrndx
};
// 0 = NULL
// 1 = .shstrtab
// 2 = .symtab
// 3 = .strtab
// 4 = .data
struct elf_section_t {
u32 sh_name, sh_type, sh_flags, sh_addr, sh_offset, sh_size;
u32 sh_link, sh_info, sh_addralign, sh_entsize;
};
struct elf_symbol_t {
u32 st_name, st_value, st_size;
u8 st_info, st_other;
u16 st_shndx;
};
// 0 0000000001 11111111 12222222 22233
// 0 1234567890 12345678 90123456 78901
static const char shstrtab[] = "\0.shstrtab\0.symtab\0.strtab\0.data";
static const char shstrtab_sdata[] = "\0.shstrtab\0.symtab\0.strtab\0.sdata\0.data";
static void create_elf(FILE * dest, const unsigned char * source, u32 size, const char * label) {
int i, l_size;
struct elf_section_t section;
struct elf_symbol_t symbol;
u32 strtab_size;
char strtab[512];
u32 data_size[4];
unsigned int shrtabSectionNameLength, NumSections;
const char *pshstrtab_ptr;
if (have_irx) {
elf_header[36] = 1;
elf_header[37] = 0;
elf_header[38] = 0;
elf_header[39] = 0;
}
NumSections=(put_payload_in_SDATA || put_labels_in_SDATA)?6:5;
elf_header[sizeof(elf_header)-4]=NumSections;
for (i = 0; i < sizeof(elf_header); i++) {
fputc(elf_header[i], dest);
}
l_size = strlen(label);
strtab[0] = 0;
strcpy(strtab + 1, label);
strcat(strtab + 1, "_start");
strcpy(strtab + 1 + l_size + 7, label);
strcat(strtab + 1 + l_size + 7, "_end");
if (have_size) {
strtab_size = (l_size * 3 + 1 + 7 + 5 + 6);
strcpy(strtab + 1 + l_size + 7 + l_size + 5, label);
strcat(strtab + 1 + l_size + 7 + l_size + 5, "_size");
} else {
strtab_size = (l_size * 2 + 1 + 7 + 5);
}
// section 0 (NULL)
section.sh_name = section.sh_type = section.sh_flags = section.sh_addr = section.sh_offset = section.sh_size =
section.sh_link = section.sh_info = section.sh_addralign = section.sh_entsize = 0;
fwrite(§ion, 1, sizeof(section), dest);
// section 1 (.shstrtab)
if(put_payload_in_SDATA || put_labels_in_SDATA){
pshstrtab_ptr=shstrtab_sdata;
shrtabSectionNameLength=sizeof(shstrtab_sdata);
}else{
pshstrtab_ptr=shstrtab;
shrtabSectionNameLength=sizeof(shstrtab);
}
section.sh_name = LE32(1);
section.sh_type = LE32(3); // STRTAB
section.sh_flags = 0;
section.sh_addr = 0;
section.sh_offset = LE32(40 * NumSections + 0x34);
section.sh_size = LE32(shrtabSectionNameLength);
section.sh_link = 0;
section.sh_info = 0;
section.sh_addralign = LE32(1);
section.sh_entsize = 0;
fwrite(§ion, 1, sizeof(section), dest);
// section 2 (.symtab)
section.sh_name = LE32(11);
section.sh_type = LE32(2); // SYMTAB
section.sh_flags = 0;
section.sh_addr = 0;
section.sh_offset = LE32(40 * NumSections + 0x34 + shrtabSectionNameLength);
section.sh_size = LE32(have_size ? 0x30 : 0x20);
section.sh_link = LE32(3);
section.sh_info = 0;
section.sh_addralign = LE32(4);
section.sh_entsize = LE32(0x10);
fwrite(§ion, 1, sizeof(section), dest);
// section 3 (.strtab)
section.sh_name = LE32(19);
section.sh_type = LE32(3); // STRTAB
section.sh_flags = 0;
section.sh_addr = 0;
section.sh_offset = LE32(40 * NumSections + 0x34 + shrtabSectionNameLength + (have_size ? 0x30 : 0x20));
section.sh_size = LE32(strtab_size);
section.sh_link = 0;
section.sh_info = 0;
section.sh_addralign = LE32(1);
section.sh_entsize = 0;
fwrite(§ion, 1, sizeof(section), dest);
if(put_payload_in_SDATA || put_labels_in_SDATA){
// section 4 (.sdata)
section.sh_name = LE32(27);
section.sh_type = LE32(1); // PROGBITS
section.sh_flags = LE32(0x10000003); // SHF_MIPS_GPREL + write + alloc
section.sh_addr = 0;
section.sh_offset = LE32(40 * NumSections + 0x34 + shrtabSectionNameLength + (have_size ? 0x30 : 0x20) + strtab_size);
section.sh_size = LE32(((put_payload_in_SDATA?size:0) + (put_labels_in_SDATA?have_size*16:0)));
section.sh_link = 0;
section.sh_addralign = LE32(alignment);
section.sh_entsize = 0;
fwrite(§ion, 1, sizeof(section), dest);
}
// section 4/5 (.data)
section.sh_name = LE32((put_payload_in_SDATA||put_labels_in_SDATA)?35:27);
section.sh_type = LE32(1); // PROGBITS
section.sh_flags = LE32(3); // Write + Alloc
section.sh_addr = 0;
if(!put_payload_in_SDATA || !put_labels_in_SDATA){
section.sh_offset = LE32(40 * NumSections + 0x34 + shrtabSectionNameLength + (have_size ? 0x30 : 0x20) + strtab_size + ((put_payload_in_SDATA?size:0) + (put_labels_in_SDATA?have_size*16:0)));
section.sh_size = LE32(((put_payload_in_SDATA?0:size) + (put_labels_in_SDATA?0:have_size*16)));
}
else{
section.sh_offset = 0;
section.sh_size = 0;
}
section.sh_link = 0;
section.sh_addralign = LE32(alignment);
section.sh_entsize = 0;
fwrite(§ion, 1, sizeof(section), dest);
fwrite(pshstrtab_ptr, 1, shrtabSectionNameLength, dest);
symbol.st_name = LE32(1);
symbol.st_value = LE32((have_size&&put_payload_in_SDATA==put_labels_in_SDATA)?16:0); //If the size label and the payload exist in the same section, the size label will exist before the payload.
symbol.st_shndx = LE16((put_labels_in_SDATA&&!put_payload_in_SDATA)?5:4);
symbol.st_size = LE32(size);
symbol.st_info = 0x11;
symbol.st_other = 0;
fwrite(&symbol, 1, sizeof(symbol), dest);
symbol.st_name = LE32(l_size + 1 + 7);
symbol.st_value = LE32(size + have_size * 16);
symbol.st_size = 0;
symbol.st_info = 0x11;
symbol.st_other = 0;
symbol.st_shndx = LE16(4);
fwrite(&symbol, 1, sizeof(symbol), dest);
if (have_size) {
symbol.st_name = LE32(l_size * 2 + 1 + 7 + 5);
symbol.st_value = 0;
symbol.st_size = LE32(4);
symbol.st_info = 0x11;
symbol.st_other = 0;
symbol.st_shndx = LE16(4);
fwrite(&symbol, 1, sizeof(symbol), dest);
}
fwrite(strtab, 1, strtab_size, dest);
if (have_size) {
data_size[0] = LE32(size);
data_size[1] = 0;
data_size[2] = 0;
data_size[3] = 0;
fwrite(data_size, 4, 4, dest);
}
fwrite(source, 1, size, dest);
}
static void usage(void) {
printf("bin2o - Converts a binary file into a .o file.\n"
"Usage: bin2o [-a XX] [-n] [-i] [-b XX] [-e XX] [-s XX] [-GXX] infile outfile label\n"
" -i - create an iop-compatible .o file.\n"
" -n - don't add label_size symbol.\n"
" -a XX - set .data section alignment to XX.\n"
" (has to be a power of two).\n"
" -b XX - start reading file at this offset.\n"
" -e XX - stop reading file at this offset.\n"
" -s XX - force output data to be of this size.\n"
" -GXX - Puts data smaller than XX bytes within the sdata section\n"
" (same as the -G option of GCC).\n"
"\n"
);
}
int main(int argc, char *argv[])
{
u32 fd_size, start = 0, end = 0xffffffff, size = 0xffffffff;
unsigned char * buffer;
FILE * source, * dest;
char * f_source = 0, * f_dest = 0, * f_label = 0;
int i;
for (i = 1; i < argc; i++) {
if (argv[i][0] == '-') {
switch (argv[i][1]) {
case 'a':
i++;
if (!argv[i]) {
usage();
printf("-a requires an argument.\n");
return 1;
}
if (argv[i][0] == '-') {
usage();
printf("-a requires an argument.\n");
return 1;
}
alignment = atoi(argv[i]);
if ((alignment - 1) & alignment) {
printf("Error: alignment must be a power of 2.\n");
return 1;
}
break;
case 'n':
have_size = 0;
break;
case 'i':
have_irx = 1;
break;
case 'G':
SDATA_size_limit = strtoul(&argv[i][2], NULL, 0);
break;
case 'b':
i++;
if (!argv[i]) {
usage();
printf("-b requires an argument.\n");
return 1;
}
if (argv[i][0] == '-') {
usage();
printf("-b requires an argument.\n");
return 1;
}
start = atoi(argv[i]);
break;
case 'e':
i++;
if (!argv[i]) {
usage();
printf("-e requires an argument.\n");
return 1;
}
if (argv[i][0] == '-') {
usage();
printf("-e requires an argument.\n");
return 1;
}
end = atoi(argv[i]);
break;
case 's':
i++;
if (!argv[i]) {
usage();
printf("-s requires an argument.\n");
return 1;
}
if (argv[i][0] == '-') {
usage();
printf("-s requires an argument.\n");
return 1;
}
size = atoi(argv[i]);
break;
default:
usage();
printf("Unknow option: %s.\n", argv[i]);
return 1;
}
} else {
if (!f_source) {
f_source = argv[i];
} else if (!f_dest) {
f_dest = argv[i];
} else if (!f_label) {
f_label = argv[i];
} else {
usage();
printf("Too many arguments.\n");
return 1;
}
}
}
if (!f_source || !f_dest || !f_label) {
usage();
printf("Not enough arguments.\n");
return 1;
}
if (!(source = fopen(f_source, "rb"))) {
printf("Error opening %s for reading.\n", f_source);
return 1;
}
fseek(source, 0, SEEK_END);
fd_size = ftell(source);
fseek(source, start, SEEK_SET);
if (fd_size < end)
end = fd_size;
if (end < (size - start))
size = end - start;
if(SDATA_size_limit>0){
put_payload_in_SDATA=(SDATA_size_limit>=size)?1:0;
put_labels_in_SDATA=(have_size && SDATA_size_limit>=16)?1:0;
}
else{
put_payload_in_SDATA = put_labels_in_SDATA = 0;
}
buffer = malloc(size);
if (buffer == NULL) {
printf("Failed to allocate memory.\n");
return 1;
}
if (fread(buffer, 1, size, source) != size) {
printf("Failed to read file.\n");
return 1;
}
fclose(source);
if (!(dest = fopen(f_dest, "wb+"))) {
printf("Failed to open/create %s.\n", f_dest);
return 1;
}
create_elf(dest, buffer, size, f_label);
fclose(dest);
free(buffer);
return 0;
}
|
the_stack_data/1022673.c | #include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int shmid;
int semid;
int *cal_num;
void *shared_memory = NULL;
struct sembuf semopen = {0, -1, SEM_UNDO};
struct sembuf semclose = {0, 1, SEM_UNDO};
shmid = shmget((key_t)1234, sizeof(int), 0666);
if (shmid == -1)
{
perror("shmget failed : ");
exit(0);
}
semid = semget((key_t)3477, 0, 0666);
if(semid == -1)
{
perror("semget failed : ");
return 1;
}
shared_memory = shmat(shmid, NULL, 0);
if (shared_memory == (void *)-1)
{
perror("shmat failed : ");
exit(0);
}
cal_num = (int *)shared_memory;
while(1)
{
int local_var=0;
if(semop(semid, &semopen, 1) == -1)
{
perror("semop error : ");
}
local_var = *cal_num+1;
sleep(2);
*cal_num = local_var;
printf("Consumer semaphore : %d\n", *cal_num);
semop(semid, &semclose, 1);
}
return 1;
}
|
the_stack_data/738630.c | #include<stdio.h>
int main()
{
int num, reverse=0, n, rem;
printf("Enter a number: ");
scanf("%d", &num);
n = num;
while(n != 0){
rem = n%10;
reverse = reverse*10 + rem;
n = n/10;
}
printf("The reversed Number is : %d",reverse);
// int difference=num-reverse;
// if (difference<0) {difference = -1*difference;}
// printf("Difference = %d", difference);
return 0;
} |
the_stack_data/243893801.c |
int main()
{
int n;
int a;
int b;
int c;
int d;
#pragma scop
{
int c1;
if (n >= 1) {
for (c1 = 0; c1 <= ((1 < n + -1?1 : n + -1)); c1++) {{
b = 0;
}
}
if (n >= 3) {
a = 0;
b = 0;
}
for (c1 = 3; c1 <= n + -2; c1++) {{
a = 0;
b = 0;
c = 0;
d = 0;
}
}
if (n >= 4) {
a = 0;
b = 0;
d = 0;
}
}
}
#pragma endscop
}
|
the_stack_data/3263922.c | // 2021-06-08 17:56:13
// pattern : Full Pyramid of Numbers.
#include <stdio.h>
int main()
{
int i, space, rows, k = 0, count = 0, count1 = 0;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i)
{
for (space = 1; space <= rows - i; ++space)
{
printf(" ");
++count;
}
while (k != 2 * i - 1)
{
if (count <= rows - 1)
{
printf("%d ", i + k);
++count;
}
else
{
++count1;
printf("%d ", (i + k - 2 * count1));
}
++k;
}
count1 = count = k = 0;
printf("\n");
}
return 0;
}
|
the_stack_data/119608.c | #include <unistd.h>
#include <string.h>
#define BUFLEN 200
char _execfullpath [ BUFLEN ]; // If the exec path doesn't start with a "/", append it to "/bin/"
char **environ = NULL;
extern int exec ( const char *path, char *const argv[] );
int execl ( const char *path, const char *arg, ... )
{
return exec( path, ( char * const * ) &arg );
}
int execlp ( const char *file, const char *arg, ... )
{
return exec( file, ( char * const * ) &arg );
}
int execle ( const char *path, const char *arg, ... )
{
return exec( path, ( char * const * ) &arg );
}
int execv ( const char *path, char *const argv[] )
{
const char *f = path;
if ( f[ 0 ] != '/' )
{
strcpy( _execfullpath, "/bin/" );
strncpy( &( _execfullpath[ 5 ] ), f, BUFLEN - 6 );
f = _execfullpath;
}
return ( exec( f, argv ) );
}
int execvp ( const char *file, char *const argv[] )
{
return ( execv( file, argv ) );
}
int execvpe ( const char *file, char *const argv[], char *const envp[] )
{
return ( execv( file, argv ) );
}
int execve ( const char *file, char *const argv[], char *const envp[] )
{
return ( execv( file, argv ) );
}
|
the_stack_data/140764575.c | #include <stdio.h>
int main()
{
int arr1[100], n,ctr=0;
int sum=0;
int i, j, k;
printf("Enter no. of Elements ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter element - %d : ",i);
scanf("%d",&arr1[i]);
}
printf("\nThe unique elements in the array are: ");
for(i=0; i<n; i++)
{
ctr=0;
for(j=0,k=n; j<k+1; j++)
{
/*Increment the counter when the seaarch value is duplicate.*/
if (i!=j)
{
if(arr1[i]==arr1[j])
{
ctr++;
}
}
}
if(ctr==0)
{
sum= sum+arr1[i];
printf("%d ",arr1[i]);
}
}
printf("\n");
printf("Sum of the unique element is %d",sum);
}
|
the_stack_data/118580.c | #if 0
#include "os.h"
#include <mp.h>
#include <libsec.h>
void
testcrt(mpint **p)
{
CRTpre *crt;
CRTres *res;
mpint *m, *x, *y;
int i;
fmtinstall('B', mpconv);
// get a modulus and a test number
m = mpnew(1024+160);
mpmul(p[0], p[1], m);
x = mpnew(1024+160);
mpadd(m, mpone, x);
// do the precomputation for crt conversion
crt = crtpre(2, p);
// convert x to residues
res = crtin(crt, x);
// convert back
y = mpnew(1024+160);
crtout(crt, res, y);
print("x %B\ny %B\n", x, y);
mpfree(m);
mpfree(x);
mpfree(y);
}
void
main(void)
{
int i;
mpint *p[2];
long start;
start = time(0);
for(i = 0; i < 10; i++){
p[0] = mpnew(1024);
p[1] = mpnew(1024);
DSAprimes(p[0], p[1], nil);
testcrt(p);
mpfree(p[0]);
mpfree(p[1]);
}
print("%d secs with more\n", time(0)-start);
exits(0);
}
#endif |
the_stack_data/37777.c | #include <stdio.h>
int getMax(int a, int b){
// Can use a variable to store returned value as follows
// int c = a > b ? a : b;
// return c;
// We can return value generated by an expression directly too
return a > b ? a : b;
}
int isLowerAlpha(char z){
return z >= 'a' && z <= 'z';
}
char toUpper(char c){
if(isLowerAlpha(c))
return c - 'a' + 'A';
else
return c;
}
void printHW(void){
// Takes no input, gives no output
// Could also have written void printHW(){ ... }
printf("Hello World\n");
// Empty return statement, does not return any value
// Simply terminates the function
return;
}
// Can omit empty return statements
// Another way to write the above function
// void printHW(){
// printf("Hello World\n");
// }
int isPrime(int n){
int i;
for(i = 2; i < n; i++)
if(n % i == 0)
return 0;
return 1;
}
void pointlessFunction(int a, int b){
// Functions enable function reuse
if(isPrime(getMax(a,b)))
printHW();
}
int getMax3(int a, int b, int c){
// Writing functions makes reusing code very convenient
return getMax(c, getMax(a,b));
}
int main(void){
int a = 20, b = 70;
int n = getMax(b, a);
// Could also have directly said
// n = getMax(20, 70);
// Functions can take expressions as input too
// n = getMax(a + 10, b * 2);
printf("Max is %d\n", n);
// Could have directly said
// printf("Max is %d", getMax(20, 70));
// Feel free to use values returned by functions everywhere
// in expressions, as inputs to other functions
if(isPrime(12+1))
printf("PRIME\n");
else
printf("NOT PRIME\n");
pointlessFunction(13, 12);
printf("Max of 3 numbers %d\n", getMax3(a-10,b,a+10));
printf("%c\n", toUpper('a'));
printf("%c\n", toUpper('P'));
printf("%c\n", toUpper('*'));
return 0;
} |
the_stack_data/10031.c | #include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
int
main() {
int sock;
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
printf("socket failed\n");
return 1;
}
return 0;
}
|
the_stack_data/242330356.c | #include <stdio.h>
#define ARRAY_SIZE 10
char array[ARRAY_SIZE] = "0123456789";
int main() {
int index;
for (index = 0; index < ARRAY_SIZE; ++index) {
printf("&array[index]=0x%p (array+index)=0x%p array[index]=0x%x\n",
&array[index], (array+index), array[index]);
}
return (0);
}
|
the_stack_data/813798.c | //
// Created by Sakura on 2020/10/30.
//
void delete_string(char str[],char ch)
{
int i,j;
for (i = j = 0; str[i] != '\0'; i++)
{
if (str[i] != ch)
{
str[j++] = str[i]; //str[j++] = str[i] 等于 str[j] = str[i]; j++
}
}
str[j] = '\0'; //将结束符'\o'也赋给str
}
|
the_stack_data/14199634.c | #include <stdio.h>
#include<stdlib.h>
#include <string.h>
void generateMatrix(const char* key, int keylen, char matrix[5][5])
{
char freq[26];
int nr = 0;
memset(freq, 0, sizeof(freq));
for (int i = 0; i < keylen; ++i)
{
if (freq[key[i] - 'A'] == 0)
{
freq[key[i] - 'A'] = 1;
if (key[i] == 'I')
{
freq['J' - 'A'] = 1;
}
else if (key[i] == 'J')
{
freq['I' - 'A'] = 1;
}
matrix[nr / 5][nr % 5] = key[i];
++nr;
}
}
if (freq['J' - 'A'] == 0 && freq['I' - 'A'] == 0)
freq['J' - 'A'] = 1;
for (int i = 0; i < 26; ++i)
{
if (freq[i] == 0)
{
matrix[nr / 5][nr % 5] = i + 'A';
++nr;
}
}
}
void encryptfoursquare(const char* plainText, char* encryptedText, int len, const char* key1, int keylen1, const char* key2, int keylen2)
{
char matrix1[5][5];
char matrix2[5][5];
char matrix3[5][5];
char matrix4[5][5];
char pos_letter[26][2];
generateMatrix("", 0, matrix1);
generateMatrix(key1, keylen1, matrix2);
generateMatrix(key2, keylen2, matrix3);
generateMatrix("", 0, matrix4);
for (int i = 0; i < len; i+=2)
{
int i1 = (plainText[i] >= 'J') ? ((plainText[i]-'A'-1)/5) : ((plainText[i]-'A')/5);
int j1 = (plainText[i] >= 'J') ? ((plainText[i]-'A' - 1) % 5) : ((plainText[i]-'A') % 5);
int i2 = (plainText[i + 1] >= 'J') ? ((plainText[i + 1]-'A' - 1) / 5) : ((plainText[i + 1]-'A') / 5);
int j2 = (plainText[i + 1] >= 'J') ? ((plainText[i + 1]-'A' - 1) % 5) : ((plainText[i + 1]-'A') % 5);
encryptedText[i] = matrix2[i1][j2];
encryptedText[i + 1] = matrix3[i2][j1];
}
}
void decryptfoursquare(const char* encryptedText, char* plainText, int len, const char* key1, int keylen1, const char* key2, int keylen2)
{
char matrix1[5][5];
char matrix2[5][5];
char matrix3[5][5];
char matrix4[5][5];
int position2[26][2];
int position3[26][2];
char pos_letter[26][2];
generateMatrix("", 0, matrix1);
generateMatrix(key1, keylen1, matrix2);
generateMatrix(key2, keylen2, matrix3);
generateMatrix("", 0, matrix4);
for(int i=0;i<5;++i)
for (int j = 0; j < 5; ++j)
{
position2[matrix2[i][j] - 'A'][0] = i;
position2[matrix2[i][j] - 'A'][1] = j;
}
for (int i = 0; i<5; ++i)
for (int j = 0; j < 5; ++j)
{
position3[matrix3[i][j] - 'A'][0] = i;
position3[matrix3[i][j] - 'A'][1] = j;
}
for (int i = 0; i < len; i += 2)
{
int i1 = position2[encryptedText[i]- 'A'][0];
int j1 = position2[encryptedText[i] - 'A'][1];
int i2 = position3[encryptedText[i+1] - 'A'][0];
int j2 = position3[encryptedText[i+1] - 'A'][1];
plainText[i] = matrix1[i1][j2];
plainText[i + 1] = matrix4[i2][j1];
}
}
int main()
{
char plainText[100];
char cipher[100];
char decipher[100];
char key1[100];
char key2[100];
printf("Plain Text: ");
gets_s(plainText, sizeof(plainText));
printf("Key1: ");
gets_s(key1, sizeof(plainText));
printf("Key2: ");
gets_s(key2, sizeof(plainText));
int length = strlen(plainText);
if (length % 2 == 1)
{
++length;
plainText[length] = '\0';
plainText[length - 1] = 'X';
}
encryptfoursquare(plainText, cipher, length, key1, strlen(key1), key2, strlen(key2));
cipher[length] = '\0';
printf("Encrypted Text: %s\n", cipher);
decryptfoursquare(cipher, decipher, length, key1, strlen(key1), key2, strlen(key2));
decipher[length] = '\0';
printf("Decrypted Text: %s", decipher);
return 0;
} |
the_stack_data/660985.c | #include <stdio.h>
int main(int argc, char *argv[]) {
int inputs[10] = {};
int i = 0;
for (i = 0; i < 10; i++) {
scanf("%d", &inputs[i]);
}
printf("Odd numbers were:");
i = 0;
for (i = 0; i < 10; i++) {
if (inputs[i] % 2 != 0) {
printf(" %d", inputs[i]);
}
}
printf("\n");
printf("Even numbers were:");
i = 0;
for (i = 0; i < 10; i++) {
if (inputs[i] % 2 == 0) {
printf(" %d", inputs[i]);
}
}
printf("\n");
return 0;
}
|
the_stack_data/121002.c | /*
* Copyright (c) 2016 Simon Schmidt
*
* Copyright(C) Caldera International Inc. 2001-2002. 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 and documentation 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.
*
* - All advertising materials mentioning features or use of this software must
* display the following acknowledgement: This product includes software developed
* or owned by Caldera International, Inc.
*
* - Neither the name of Caldera International, Inc. nor the names of other
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* USE OF THE SOFTWARE PROVIDED FOR UNDER THIS LICENSE BY CALDERA INTERNATIONAL, INC.
* 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 CALDERA INTERNATIONAL, INC. 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.
*/
/*
* fgrep -- print all lines containing any of a set of keywords
*
* status returns:
* 0 - ok, and some matches
* 1 - ok, but no matches
* 2 - some error
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#define MAXSIZ 6000
#define QSIZE 400
struct words {
char inp;
char out;
struct words *nst;
struct words *link;
struct words *fail;
} w[MAXSIZ], *smax, *q;
long lnum;
int bflag, cflag, fflag, lflag, nflag, vflag, xflag;
int hflag = 1;
int sflag;
int nfile;
long blkno;
int nsucc;
long tln;
FILE *wordf;
char *argptr;
void execute(char* file);
int getargc();
void cgotofn();
void overflo();
void cfail();
void
main(int argc,char **argv)
{
while (--argc > 0 && (++argv)[0][0]=='-')
switch (argv[0][1]) {
case 's':
sflag++;
continue;
case 'h':
hflag = 0;
continue;
case 'b':
bflag++;
continue;
case 'c':
cflag++;
continue;
case 'e':
argc--;
argv++;
goto out;
case 'f':
fflag++;
continue;
case 'l':
lflag++;
continue;
case 'n':
nflag++;
continue;
case 'v':
vflag++;
continue;
case 'x':
xflag++;
continue;
default:
fprintf(stderr, "egrep: unknown flag\n");
continue;
}
out:
if (argc<=0)
exit(2);
if (fflag) {
wordf = fopen(*argv, "r");
if (wordf==NULL) {
fprintf(stderr, "egrep: can't open %s\n", *argv);
exit(2);
}
}
else argptr = *argv;
argc--;
argv++;
cgotofn();
cfail();
nfile = argc;
if (argc<=0) {
if (lflag) exit(1);
execute((char *)NULL);
}
else while (--argc >= 0) {
execute(*argv);
argv++;
}
exit(nsucc == 0);
}
void execute(char* file)
{
register char *p;
register struct words *c;
register int ccount;
char buf[1024];
int f;
int failed;
char *nlp;
if (file) {
if ((f = open(file, 0)) < 0) {
fprintf(stderr, "fgrep: can't open %s\n", file);
exit(2);
}
}
else f = 0;
ccount = 0;
failed = 0;
lnum = 1;
tln = 0;
blkno = 0;
p = buf;
nlp = p;
c = w;
for (;;) {
if (--ccount <= 0) {
if (p == &buf[1024]) p = buf;
if (p > &buf[512]) {
if ((ccount = read(f, p, &buf[1024] - p)) <= 0) break;
}
else if ((ccount = read(f, p, 512)) <= 0) break;
blkno += ccount;
}
nstate:
if (c->inp == *p) {
c = c->nst;
}
else if (c->link != 0) {
c = c->link;
goto nstate;
}
else {
c = c->fail;
failed = 1;
if (c==0) {
c = w;
istate:
if (c->inp == *p) {
c = c->nst;
}
else if (c->link != 0) {
c = c->link;
goto istate;
}
}
else goto nstate;
}
if (c->out) {
while (*p++ != '\n') {
if (--ccount <= 0) {
if (p == &buf[1024]) p = buf;
if (p > &buf[512]) {
if ((ccount = read(f, p, &buf[1024] - p)) <= 0) break;
}
else if ((ccount = read(f, p, 512)) <= 0) break;
blkno += ccount;
}
}
if ( (vflag && (failed == 0 || xflag == 0)) || (vflag == 0 && xflag && failed) )
goto nomatch;
succeed: nsucc = 1;
if (cflag) tln++;
else if (sflag)
; /* ugh */
else if (lflag) {
printf("%s\n", file);
close(f);
return;
}
else {
if (nfile > 1 && hflag) printf("%s:", file);
if (bflag) printf("%ld:", (blkno-ccount-1)/512);
if (nflag) printf("%ld:", lnum);
if (p <= nlp) {
while (nlp < &buf[1024]) putchar(*nlp++);
nlp = buf;
}
while (nlp < p) putchar(*nlp++);
}
nomatch: lnum++;
nlp = p;
c = w;
failed = 0;
continue;
}
if (*p++ == '\n')
if (vflag) goto succeed;
else {
lnum++;
nlp = p;
c = w;
failed = 0;
}
}
close(f);
if (cflag) {
if (nfile > 1)
printf("%s:", file);
printf("%ld\n", tln);
}
}
int getargc()
{
register int c;
if (wordf)
return(getc(wordf));
if ((c = *argptr++) == '\0')
return(EOF);
return(c);
}
void cgotofn() {
register int c;
register struct words *s;
s = smax = w;
nword: for(;;) {
c = getargc();
if (c==EOF)
return;
if (c == '\n') {
if (xflag) {
for(;;) {
if (s->inp == c) {
s = s->nst;
break;
}
if (s->inp == 0) goto nenter;
if (s->link == 0) {
if (smax >= &w[MAXSIZ -1]) overflo();
s->link = ++smax;
s = smax;
goto nenter;
}
s = s->link;
}
}
s->out = 1;
s = w;
} else {
loop: if (s->inp == c) {
s = s->nst;
continue;
}
if (s->inp == 0) goto enter;
if (s->link == 0) {
if (smax >= &w[MAXSIZ - 1]) overflo();
s->link = ++smax;
s = smax;
goto enter;
}
s = s->link;
goto loop;
}
}
enter:
do {
s->inp = c;
if (smax >= &w[MAXSIZ - 1]) overflo();
s->nst = ++smax;
s = smax;
} while ((c = getargc()) != '\n' && c!=EOF);
if (xflag) {
nenter: s->inp = '\n';
if (smax >= &w[MAXSIZ -1]) overflo();
s->nst = ++smax;
}
smax->out = 1;
s = w;
if (c != EOF)
goto nword;
}
void overflo() {
fprintf(stderr, "wordlist too large\n");
exit(2);
}
void cfail() {
struct words *queue[QSIZE];
struct words **front, **rear;
struct words *state;
register char c;
register struct words *s;
s = w;
front = rear = queue;
init: if ((s->inp) != 0) {
*rear++ = s->nst;
if (rear >= &queue[QSIZE - 1]) overflo();
}
if ((s = s->link) != 0) {
goto init;
}
while (rear!=front) {
s = *front;
if (front == &queue[QSIZE-1])
front = queue;
else front++;
cloop: if ((c = s->inp) != 0) {
*rear = (q = s->nst);
if (front < rear)
if (rear >= &queue[QSIZE-1])
if (front == queue) overflo();
else rear = queue;
else rear++;
else
if (++rear == front) overflo();
state = s->fail;
floop: if (state == 0) state = w;
if (state->inp == c) {
q->fail = state->nst;
if ((state->nst)->out == 1) q->out = 1;
continue;
}
else if ((state = state->link) != 0)
goto floop;
}
if ((s = s->link) != 0)
goto cloop;
}
}
|
the_stack_data/31388749.c | #include <stdio.h>
int main(int argc, char const *argv[])
{
puts("请输入一个正整数,我们将计算它的阶乘。");
int i;
scanf("%d", &i);
int result = 1;
for (; i >= 1; i --) {
result *= i;
}
printf("%d的阶乘是:%d \n", i, result);
return 0;
}
|
the_stack_data/106744.c | #include <stdio.h>
int main()
{
int x, y;
while(2==scanf(" %d %d", &x, &y))
{
if(x==0||y==0)
{
break;
}
else if(x>0)
{
if(y>0)
{
printf("primeiro\n");
}
else
{
printf("quarto\n");
}
}
else{
if(y>0)
{
printf("segundo\n");
}
else
{
printf("terceiro\n");
}
}
}
return 0;
}
|
the_stack_data/82950145.c | #include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
#include <sys/syscall.h>
int SALDO = 0;
int KEY;
struct T_args {
pthread_t thread;
};
void interface();
// Funções de cada uma das threads
void *addMoneyUnit(void *arg);
void *removeMoneyUnit(void *arg);
void *printMoneyUnit(void *arg);
void *restartSystem(void *arg);
int main(){
interface();
pthread_t addMoneyUnitThread;
pthread_t removeMoneyUnitThread;
pthread_t printMoneyUnitThread;
pthread_t restartSystemThread;
// Captura do valor da tecla sem pressionar ENTER
system("/bin/stty raw");
// Argumentos das threads
struct T_args *threadPrint = (struct T_args *) malloc(sizeof(struct T_args));
struct T_args *threadAdd = (struct T_args *) malloc(sizeof(struct T_args));
struct T_args *threadRemove = (struct T_args *) malloc(sizeof(struct T_args));
threadPrint->thread = printMoneyUnitThread;
threadAdd->thread = addMoneyUnitThread;
threadRemove->thread = removeMoneyUnitThread;
// Cria threads de soma, remoção e impressão
pthread_create(&printMoneyUnitThread, NULL, printMoneyUnit, (void *) threadPrint);
pthread_create(&addMoneyUnitThread, NULL, addMoneyUnit, (void *) threadAdd);
pthread_create(&removeMoneyUnitThread, NULL, removeMoneyUnit, (void *) threadRemove);
do{
// Altera opções
KEY = getc(stdin);
// Mata threads
// k
if (KEY == 107){
pthread_kill(addMoneyUnitThread, 0);
pthread_kill(removeMoneyUnitThread, 0);
pthread_kill(printMoneyUnitThread, 0);
printf("\n=======================================\n");
printf("Terminando (kill) Threads... OK\n");
printf("=======================================\n");
}
// Reinicia o sistema limpando operações e tela
// r
else if(KEY == 114){
// Termina as thread em execução e cria novas
pthread_join(addMoneyUnitThread, NULL);
pthread_kill(addMoneyUnitThread, 0);
pthread_join(removeMoneyUnitThread, NULL);
pthread_kill(removeMoneyUnitThread, 0);
pthread_join(printMoneyUnitThread, NULL);
pthread_kill(printMoneyUnitThread, 0);
pthread_create(&restartSystemThread, NULL, restartSystem, NULL);
pthread_create(&printMoneyUnitThread, NULL, printMoneyUnit, (void *) threadPrint);
pthread_create(&addMoneyUnitThread, NULL, addMoneyUnit, (void *) threadAdd);
pthread_create(&removeMoneyUnitThread, NULL, removeMoneyUnit, (void *) threadRemove);
pthread_join(restartSystemThread, NULL);
interface();
}
// k
}while(KEY != 107);
system ("/bin/stty cooked");
return 0;
}
// Interface do menu
void interface(){
printf("--------------------------------------------\n");
printf("Pressione [+] Para adicionar 100 UD ao saldo\n");
printf("Pressione [-] Para retirar 50 UD do saldo \n");
printf("Pressione [s] Para imprimir o saldo \n");
printf("Pressione [k] Para matar as thread criadas \n");
printf("Pressione [r] Para limpar a tela e operações\n");
printf("--------------------------------------------\n\n");
}
// Deposita 100 unidadeds de dinheiro
void *addMoneyUnit(void *arg){
do{
if (KEY == 43){
printf("\nAdicionando 100 UD com TID: %ld\n", syscall(__NR_gettid));
SALDO += 100;
KEY = 0;
}
else if (KEY == 107 || KEY == 114){
pthread_exit(0);
}
}while(1);
}
// Retira 50 unidadeds de dinheiro
void *removeMoneyUnit(void *arg){
do{
if (KEY == 45){
printf("\nRemovendo 50 UD com TID : %ld\n", syscall(__NR_gettid));
SALDO -= 50;
KEY = 0;
}
else if (KEY == 107 || KEY == 114){
pthread_exit(0);
}
}while(1);
}
// Printa saldo
void *printMoneyUnit(void *arg){
do{
if (KEY == 115){
printf("\n----------------------------------------\n");
printf("Mostrando saldo UD com TID: %ld\n", syscall(__NR_gettid));
printf("Saldo em conta : %d UD\n", SALDO);
printf("----------------------------------------\n");
KEY = 0;
}
else if (KEY == 107 || KEY == 114){
pthread_exit(0);
}
}while(1);
}
// Reinicia
void *restartSystem(void *arg){
SALDO = 0;
KEY = 0;
system("clear");
pthread_exit(0);
}
|
the_stack_data/32949679.c | #include <stdio.h>
int main(void)
{
double x1 = 0.0, y1 = 0.0;
double x2 = 0.0, y2 = 0.0;
double a = 0.0, b = 0.0;
printf("첫 번째 점 x1, y1값을 입력하시오> ");
scanf(" %lf %lf", &x1, &y1);
printf("\n두 번째 점 x2, y2값을 입력하시오> ");
scanf(" %lf %lf", &x2, &y2);
a = (y2 - y1) / (x2 - x1);
b = y1 - (a * x1);
printf("\n\n기울기: %.2f, y절편: %.2f\n", a, b);
printf("두 점을 연결하는 직선의 방정식: Y = %.2fX + %-.2f\n", a, b);
return 0;
}
|
the_stack_data/95449382.c | //file: _insn_test_v1shrui_X1.c
//op=275
#include <stdio.h>
#include <stdlib.h>
void func_exit(void) {
printf("%s\n", __func__);
exit(0);
}
void func_call(void) {
printf("%s\n", __func__);
exit(0);
}
unsigned long mem[2] = { 0x420e29019dd4c946, 0x562bb4e51ed838f4 };
int main(void) {
unsigned long a[4] = { 0, 0 };
asm __volatile__ (
"moveli r11, -14185\n"
"shl16insli r11, r11, 11751\n"
"shl16insli r11, r11, 25109\n"
"shl16insli r11, r11, 30569\n"
"moveli r18, 3022\n"
"shl16insli r18, r18, -17758\n"
"shl16insli r18, r18, 25795\n"
"shl16insli r18, r18, 7417\n"
"{ fnop ; v1shrui r11, r18, 41 }\n"
"move %0, r11\n"
"move %1, r18\n"
:"=r"(a[0]),"=r"(a[1]));
printf("%016lx\n", a[0]);
printf("%016lx\n", a[1]);
return 0;
}
|
the_stack_data/76699634.c | /* Date: 12/07/2017
* Class: CS4900
* Function: Quadratic Solver Input (input.c)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int read_line(char* input, int length){
#ifdef DEBUG
fprintf(stderr, "DEBUG: Entering read_line\n");
fprintf(stderr, "DEBUG: input = %s | length = %d\n", input, length);
#endif
char* pos = fgets(input, length, stdin);
if (pos == NULL){
return -1;
}
return strlen(input);
}
int input_numbers(char* input, double returns[]){
#ifdef DEBUG
fprintf(stderr, "DEBUG: Entering input_numbers\n");
fprintf(stderr, "DEBUG: input = %s | &returns = %f\n", input, *returns);
#endif
char ch;
double a, b, c;
if (sscanf(input, "%lf %lf %lf %c", &a, &b, &c, &ch) != 3)
return -1;
returns[0] = a;
returns[1] = b;
returns[2] = c;
return 0;
} |
the_stack_data/9512945.c | /* $Id: strsep.c,v 1.3 2001/11/19 20:27:23 ragge Exp $ */
/* $NetBSD: strsep.c,v 1.10 1999/09/20 04:39:48 lukem Exp $ */
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. 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. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University 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 REGENTS 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 REGENTS 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.
*/
#if defined(SOLARIS) || defined(SUNOS4)
#include <stdio.h>
#include "rkomsupport.h"
/*
* Get next token from string *stringp, where tokens are possibly-empty
* strings separated by characters from delim.
*
* Writes NULs into the string at *stringp to end tokens.
* delim need not remain constant from call to call.
* On return, *stringp points past the last NUL written (if there might
* be further tokens), or is NULL (if there are definitely no more tokens).
*
* If *stringp is NULL, strsep returns NULL.
*/
char *
strsep(char **stringp, const char *delim)
{
char *s;
const char *spanp;
int c, sc;
char *tok;
if ((s = *stringp) == NULL)
return (NULL);
for (tok = s;;) {
c = *s++;
spanp = delim;
do {
if ((sc = *spanp++) == c) {
if (c == 0)
s = NULL;
else
s[-1] = 0;
*stringp = s;
return (tok);
}
} while (sc != 0);
}
/* NOTREACHED */
}
#endif
|
the_stack_data/173578060.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_fddel.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jodufour <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/10/09 00:56:40 by jodufour #+# #+# */
/* Updated: 2022/01/12 04:33:10 by jodufour ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
#include <unistd.h>
/*
Close the pointed file descriptor by the given pointer `fd`
and set its value to -1
In case of a negative pointed file descriptor, do nothing
*/
int ft_fddel(int *const fd)
{
if (*fd < 0)
return (EXIT_SUCCESS);
if (close(*fd) == -1)
return (EXIT_FAILURE);
*fd = -1;
return (EXIT_SUCCESS);
}
|
the_stack_data/234518664.c | int foo(int p, int a) { return (p ? a : a) == a; }
/*
* check-name: select-same-args
* check-command: test-linearize -Wno-decl $file
*
* check-output-ignore
* check-output-returns: 1
*/
|
the_stack_data/125139252.c | #include<stdio.h>
#include<string.h> //strlen
#include<sys/socket.h>
#include<arpa/inet.h>
#include<string.h>
// receive file name and destination address
// md5 the file
// encrypt it
//create a socket
//send the file
char* readFile(char* file_name)
{
// read the zip file
char *buffer;
FILE *f;
f=fopen(file_name,"r");
fscanf(f,"%s",buffer);
printf("the file was read successfully");
}
int main(int argc , char *argv[])
{
struct sockaddr_in server;
int socket_desc;
socket_desc = socket(AF_INET , SOCK_STREAM , 0);
// store data in key file
//MD5 calculation
{
//char *query="md5sum "+ argv[2] + " > md5sum.txt";
char *query="md5sum ";
strcat(query, argv[2]);
strcat(query, " > md5sum.txt");
system(&query);
}
// MD5 done
printf("md5 done");
// DES encryption
{
char *cmd="./run_des.o -e ";//+argv[2]+" "+argv[2]+".enc";
strcat(cmd, argv[3]);
strcat(cmd, " ");
strcat(cmd, argv[2]);
strcat(cmd, " ");
strcat(cmd, argv[2]);
strcat(cmd, ".enc");
//command formed
printf(cmd);
//debugging print
system(cmd);
}
// executed DES encryption
printf("DES executed successfully");
// creating a socket descriptor
server.sin_addr.s_addr = inet_addr(argv[1]);
server.sin_family = AF_INET;
server.sin_port = htons( 5678);
//adding config of destination
connect(socket_desc , (struct sockaddr *)&server , sizeof(server));
// create a connection
//zip the two files
{
char *cmd="zip ";//+argv[2]+".zip "+argv[2]+".enc md5sum.txt";
//start concatenation
strcat(cmd, argv[2]);
strcat(cmd, ".zip ");
strcat(cmd, argv[2]);
strcat(cmd, ".enc ");
//strcat(cmd, argv[2]);
strcat(cmd, "md5sum.txt");
//concatenation over
//debugging info
printf(cmd);
//execute commans
system();
}
// send this zip file
char *readcommand= argv[2];
strcat(readcommand,".zip");
char *message=readFile(readcommand) ;
//read encrypted file file1.
//write(sockfd,buffer,100);
send(socket_desc , message , strlen(message) , 0);
} |
the_stack_data/20002.c | #include <stdio.h>
int main ()
{
int m,d,f;
scanf("%d",&m);
d=m*m;
f=m*m*m;
printf("\n %d\n",d);
printf("\n %d\n",f);
return 0;
}
|
the_stack_data/22013900.c | #include <stdio.h>
#define s(x) (1U << ((x) - 'A'))
typedef unsigned int bitset;
int consolidate(bitset *x, int len)
{
int i, j;
for (i = len - 2; i >= 0; i--)
for (j = len - 1; j > i; j--)
if (x[i] & x[j])
x[i] |= x[j], x[j] = x[--len];
return len;
}
void show_sets(bitset *x, int len)
{
bitset b;
while(len--) {
for (b = 'A'; b <= 'Z'; b++)
if (x[len] & s(b)) printf("%c ", b);
putchar('\n');
}
}
int main(void)
{
bitset x[] = { s('A') | s('B'), s('C') | s('D'), s('B') | s('D'),
s('F') | s('G') | s('H'), s('H') | s('I') | s('K') };
int len = sizeof(x) / sizeof(x[0]);
puts("Before:"); show_sets(x, len);
puts("\nAfter:"); show_sets(x, consolidate(x, len));
return 0;
}
|
the_stack_data/151705045.c | #ifdef CS333_P3P4
// Credit to Jacob Collins <[email protected]> who developed this test
// program and gave me permission to use it
#include "types.h"
#include "user.h"
#include "param.h"
#ifndef TRUE
#define TRUE 1
#define FALSE 0
#endif
void test1();
void test2();
void test3();
void test4();
void test5();
void test6();
void cleanupProcs(int pid[], int max);
void sleepMessage(int time, char message[]);
int createInfiniteProc();
int createSetPrioProc(int prio);
/* Note:
You may need to change the names of MAXPRIO and BUDGET to match the
names you have defined in your code.
*/
const int plevels = MAXPRIO;
const int budget = BUDGET;
const int promo = TICKS_TO_PROMOTE;
void
printMenu(void)
{
int i = 0;
printf(1, "\n");
printf(1, "%d. exit program\n", i++);
printf(1, "%d. Round robin scheduling for %d queues.\n", i++, plevels);
printf(1, "%d. Promotion should change priority levels for sleeping and running processes.\n", i++);
printf(1, "%d. Test demotion resetting budget.\n", i++);
printf(1, "%d. Test scheduler operation.\n", i++);
printf(1, "%d. Test demotion setting priority level.\n", i++);
printf(1, "%d. Test scheduler selection, promotion, and demotion.\n", i++);
}
int
main(int argc, char* argv[])
{
int select, done;
char buf[5];
//void (*test[])() = {test1, test2, test3, test4, test5, test6};
while(1) {
done = FALSE;
printMenu();
printf(1, "Enter test number: ");
gets(buf, 5);
if ((buf[0] == '\n') || buf[0] == '\0') {
continue;
}
select = atoi(buf);
switch(select) {
case 0:
done = TRUE;
break;
case 1:
test1();
break;
case 2:
test2();
break;
case 3:
test3();
break;
case 4:
test4();
break;
case 5:
test5();
break;
case 6:
test6();
break;
default:
printf(1, "Error: invalid test number.\n");
}
if (done) {
break;
}
}
printf(1, "p4test starting with: MAXPRIO = %d, DEFAULT_BUDGET = %d, TICKS_TO_PROMOTE = %d\n\n", plevels, budget, promo);
/* for(i = 1; i <= test_num; i++) {
(*test[atoi(argv[i])-1])();
}
*/
exit();
}
void
test1()
{
printf(1, "+=+=+=+=+=+=+=+=+\n");
printf(1, "| Start: Test 1 |\n");
printf(1, "+=+=+=+=+=+=+=+=+\n");
int i;
int max = 8;
int pid[max];
for(i = 0; i < max; i++)
pid[i] = createInfiniteProc();
for(i = 0; i < 3; i++)
sleepMessage(5000, "Sleeping... ctrl-p\n");
cleanupProcs(pid, max);
printf(1, "+=+=+=+=+=+=+=+\n");
printf(1, "| End: Test 1 |\n");
printf(1, "+=+=+=+=+=+=+=+\n");
}
void
test2()
{
printf(1, "+=+=+=+=+=+=+=+=+=\n");
printf(1, "| Start: Test 2a |\n");
printf(1, "+=+=+=+=+=+=+=+=+=\n");
int i, start_time, elapsed_time;
int pid[2];
pid[0] = createInfiniteProc();
setpriority(getpid(), plevels);
start_time = uptime();
i = 0;
while(i <= plevels) {
elapsed_time = uptime() - start_time;
if(elapsed_time % promo-100 == 0) {
sleepMessage(promo/2, "Sleeping... ctrl-p\n");
i++;
}
}
printf(1, "+=+=+=+=+=+=+=+=\n");
printf(1, "| End: Test 2a |\n");
printf(1, "+=+=+=+=+=+=+=+=\n");
printf(1, "\n");
printf(1, "+=+=+=+=+=+=+=+=+=\n");
printf(1, "| Start: Test 2b |\n");
printf(1, "+=+=+=+=+=+=+=+=+=\n");
pid[1] = createSetPrioProc(0);
setpriority(pid[0], plevels);
start_time = uptime();
i = 0;
while(i <= plevels) {
elapsed_time = uptime() - start_time;
if(elapsed_time % promo-100 == 0) {
sleepMessage(promo-100, "Sleeping... ctrl-p\n");
i++;
}
}
cleanupProcs(pid, 2);
printf(1, "+=+=+=+=+=+=+=+=\n");
printf(1, "| End: Test 2b |\n");
printf(1, "+=+=+=+=+=+=+=+=\n");
}
void
test3()
{
printf(1, "+=+=+=+=+=+=+=+=+\n");
printf(1, "| Start: Test 3 |\n");
printf(1, "+=+=+=+=+=+=+=+=+\n");
int i;
int max = 8;
int pid[max];
for(i = 0; i < max; i++)
pid[i] = createInfiniteProc();
for(i = 0; i <= plevels; i++)
sleepMessage((budget*max)/2, "Sleeping... ctrl-p OR ctrl-r\n");
cleanupProcs(pid, max);
printf(1, "+=+=+=+=+=+=+=+\n");
printf(1, "| End: Test 3 |\n");
printf(1, "+=+=+=+=+=+=+=+\n");
}
void
test4()
{
if(plevels == 0) {
printf(1, "+=+=+=+=+=+=+=+=+=\n");
printf(1, "| Start: Test 6a |\n");
printf(1, "+=+=+=+=+=+=+=+=+=\n");
}
else if(plevels == 2) {
printf(1, "+=+=+=+=+=+=+=+=+=\n");
printf(1, "| Start: Test 4a |\n");
printf(1, "+=+=+=+=+=+=+=+=+=\n");
}
else if(plevels == 6) {
printf(1, "+=+=+=+=+=+=+=+=+=\n");
printf(1, "| Start: Test 5a |\n");
printf(1, "+=+=+=+=+=+=+=+=+=\n");
}
int i;
int max = 10;
int pid[max];
for(i = 0; i < max/2; i++)
pid[i] = createSetPrioProc(plevels);
for(i = max/2; i < max; i++)
pid[i] = createSetPrioProc(0);
for(i = 0; i < 2; i++)
sleepMessage(6000, "Sleeping... ctrl-p\n");
cleanupProcs(pid, max);
if(plevels == 0) {
printf(1, "+=+=+=+=+=+=+=+=\n");
printf(1, "| End: Test 6a |\n");
printf(1, "+=+=+=+=+=+=+=+=\n");
}
else if(plevels == 2) {
printf(1, "+=+=+=+=+=+=+=+=\n");
printf(1, "| End: Test 4a |\n");
printf(1, "+=+=+=+=+=+=+=+=\n");
}
else if(plevels == 6) {
printf(1, "+=+=+=+=+=+=+=+=\n");
printf(1, "| End: Test 5a |\n");
printf(1, "+=+=+=+=+=+=+=+=\n");
}
}
void
test6()
{
if(plevels == 0) {
printf(1, "+=+=+=+=+=+=+=+=+=\n");
printf(1, "| Start: Test 6b |\n");
printf(1, "+=+=+=+=+=+=+=+=+=\n");
}
else if(plevels == 2) {
printf(1, "+=+=+=+=+=+=+=+=+=\n");
printf(1, "| Start: Test 4b |\n");
printf(1, "+=+=+=+=+=+=+=+=+=\n");
}
else if(plevels == 6) {
printf(1, "+=+=+=+=+=+=+=+=+=\n");
printf(1, "| Start: Test 5b |\n");
printf(1, "+=+=+=+=+=+=+=+=+=\n");
}
int i;
int max = 8;
int pid[max];
for(i = 0; i < max/2; i++)
pid[i] = createInfiniteProc();
for(i = 0; i <= plevels; i++)
sleepMessage(2000, "Sleeping... ctrl-p OR ctrl-r\n");
if(plevels == 0)
sleepMessage(2000, "Sleeping... ctrl-p OR ctrl-r\n");
if(plevels == 0) {
printf(1, "+=+=+=+=+=+=+=+=\n");
printf(1, "| End: Test 6b |\n");
printf(1, "+=+=+=+=+=+=+=+=\n");
printf(1, "\n");
printf(1, "+=+=+=+=+=+=+=+=+=\n");
printf(1, "| Start: Test 6c |\n");
printf(1, "+=+=+=+=+=+=+=+=+=\n");
}
else if(plevels == 2) {
printf(1, "+=+=+=+=+=+=+=+=\n");
printf(1, "| End: Test 4b |\n");
printf(1, "+=+=+=+=+=+=+=+=\n");
printf(1, "\n");
printf(1, "+=+=+=+=+=+=+=+=+=\n");
printf(1, "| Start: Test 4c |\n");
printf(1, "+=+=+=+=+=+=+=+=+=\n");
}
else if(plevels == 6) {
printf(1, "+=+=+=+=+=+=+=+=\n");
printf(1, "| End: Test 5b |\n");
printf(1, "+=+=+=+=+=+=+=+=\n");
printf(1, "\n");
printf(1, "+=+=+=+=+=+=+=+=+=\n");
printf(1, "| Start: Test 5c |\n");
printf(1, "+=+=+=+=+=+=+=+=+=\n");
}
for(i = max/2; i < max; i++)
pid[i] = createInfiniteProc();
for(i = 0; i <= plevels+1; i++)
sleepMessage(1500, "Sleeping... ctrl-p OR ctrl-r\n");
cleanupProcs(pid, max);
if(plevels == 0) {
printf(1, "+=+=+=+=+=+=+=+=\n");
printf(1, "| End: Test 6c |\n");
printf(1, "+=+=+=+=+=+=+=+=\n");
}
else if(plevels == 2) {
printf(1, "+=+=+=+=+=+=+=+=\n");
printf(1, "| End: Test 4c |\n");
printf(1, "+=+=+=+=+=+=+=+=\n");
}
else if(plevels == 6) {
printf(1, "+=+=+=+=+=+=+=+=\n");
printf(1, "| End: Test 5c |\n");
printf(1, "+=+=+=+=+=+=+=+=\n");
}
}
void
test5()
{
printf(1, "+=+=+=+=+=+=+=+=+\n");
printf(1, "| Start: Test 5 |\n");
printf(1, "+=+=+=+=+=+=+=+=+\n");
int i, prio;
int max = 10;
int pid[max];
for(i = 0; i < max; i++) {
prio = i%(plevels+1);
pid[i] = createSetPrioProc(prio);
printf(1, "Process %d will be at priority level %d\n", pid[i], prio);
}
sleepMessage(5000, "Sleeping... ctrl-p\n");
sleepMessage(5000, "Sleeping... ctrl-r\n");
printf(1, "+=+=+=+=+=+=+=+=\n");
printf(1, "| End: Test 5 |\n");
printf(1, "+=+=+=+=+=+=+=+=\n");
}
void
sleepMessage(int time, char message[])
{
printf(1, message);
sleep(time);
}
int
createInfiniteProc()
{
int pid = fork();
if(pid == 0)
while(1);
printf(1, "Process %d created...\n", pid);
return pid;
}
int
createSetPrioProc(int prio)
{
int pid = fork();
if(pid == 0)
while(1)
setpriority(getpid(), prio);
return pid;
}
void
cleanupProcs(int pid[], int max)
{
int i;
for(i = 0; i < max; i++)
kill(pid[i]);
while(wait() > 0);
}
#endif
|
the_stack_data/7950777.c | #define VEC_SIZE 16
typedef float V __attribute__((vector_size(VEC_SIZE)));
V foo(V a, V b) {
return a+b*a;
} |
the_stack_data/1156662.c | #include <stdio.h>
/*
tableau : adresse du tableau
*tableau : premiere élément du tableau
*(tableau + x) : élement d'indice + x = tableau[x]
*/
#define Taille 5
void affiche(int tab[], int taille);
int *creer_tab(void);
int main (void)
{
int *tableau = creer_tab();
//int tableau[Taille] = {16,4,-5,22,100};
tableau[0] = 14;
affiche(tableau, Taille);
return 0;
}
int *creer_tab(void) {
static int tableau_entiers[5]; //static permet de renvoyer le tableau
for (int i=0; i < 5; i++)
tableau_entiers[i] = i * 3;
return tableau_entiers;
}
void affiche(int tab[], int taille)
{
for (int i = 0; i < 5; i++)
printf("[%d] ",tab[i]);
printf("\n");
}
|
the_stack_data/98575285.c | /* Generated by CIL v. 1.7.0 */
/* print_CIL_Input is false */
struct _IO_FILE;
struct timeval;
extern void signal(int sig , void *func ) ;
extern float strtof(char const *str , char const *endptr ) ;
typedef struct _IO_FILE FILE;
extern int atoi(char const *s ) ;
extern double strtod(char const *str , char const *endptr ) ;
extern int fclose(void *stream ) ;
extern void *fopen(char const *filename , char const *mode ) ;
extern void abort() ;
extern void exit(int status ) ;
extern int raise(int sig ) ;
extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ;
extern int strcmp(char const *a , char const *b ) ;
extern int rand() ;
extern unsigned long strtoul(char const *str , char const *endptr , int base ) ;
void RandomFunc(unsigned int input[1] , unsigned int output[1] ) ;
extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ;
extern int gettimeofday(struct timeval *tv , void *tz , ...) ;
extern int printf(char const *format , ...) ;
int main(int argc , char *argv[] ) ;
void megaInit(void) ;
extern unsigned long strlen(char const *s ) ;
extern long strtol(char const *str , char const *endptr , int base ) ;
extern unsigned long strnlen(char const *s , unsigned long maxlen ) ;
extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ;
struct timeval {
long tv_sec ;
long tv_usec ;
};
extern void *malloc(unsigned long size ) ;
extern int scanf(char const *format , ...) ;
int main(int argc , char *argv[] )
{
unsigned int input[1] ;
unsigned int output[1] ;
int randomFuns_i5 ;
unsigned int randomFuns_value6 ;
int randomFuns_main_i7 ;
{
megaInit();
if (argc != 2) {
printf("Call this program with %i arguments\n", 1);
exit(-1);
} else {
}
randomFuns_i5 = 0;
while (randomFuns_i5 < 1) {
randomFuns_value6 = (unsigned int )strtoul(argv[randomFuns_i5 + 1], 0, 10);
input[randomFuns_i5] = randomFuns_value6;
randomFuns_i5 ++;
}
RandomFunc(input, output);
if (output[0] == 242728959U) {
printf("You win!\n");
} else {
}
randomFuns_main_i7 = 0;
while (randomFuns_main_i7 < 1) {
printf("%u\n", output[randomFuns_main_i7]);
randomFuns_main_i7 ++;
}
}
}
void megaInit(void)
{
{
}
}
void RandomFunc(unsigned int input[1] , unsigned int output[1] )
{
unsigned int state[1] ;
unsigned int local2 ;
unsigned int local1 ;
{
state[0UL] = (input[0UL] | 51238316UL) >> 3U;
local1 = 0UL;
while (local1 < 0U) {
local2 = 0UL;
while (local2 < 0U) {
local2 += 2UL;
}
local1 += 2UL;
}
output[0UL] = state[0UL] | 238489436UL;
}
}
|
the_stack_data/14200166.c | #include <stdio.h>
#include <stdlib.h>
void ssu_out(void);
int main(int argc, char const *argv[])
{
// ssu_out함수를 atexit으로 등록한다.
if (atexit(ssu_out))
{
fprintf(stderr, "atexit error\n");
exit(1);
}
exit(0);
}
void ssu_out(void)
{
printf("atexit succeeded!\n");
} |
the_stack_data/56884.c | #include<stdio.h>
int main()
{int m,n,b;
scanf("%d%d",&m,&n);
int i=m;
int s=1;
int d=1;
for(b=n;b>0;b--)
{s=s*i;
i--;
}
for(b=1;b<=n;b++)
{d=d*b;
}
s=s/d;
printf("%d",s);
return 0;
} |
the_stack_data/339821.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
extern int find_char(char *, char *);
extern void reversal(char *);
int main()
{
char src[] = "abcdefghijklmnopqrstuvwxyz";
printf("src = [%s]\n", src);
reversal(src);
printf("reversal = [%s]\n", src);
char sub[] = "kl";
int ret = find_char(src, sub);
if (-1 == ret)
{
printf("can't find any code from this str.");
return EXIT_FAILURE;
}
printf("sub str is %d\n", ret);
char count[32] = {0};
int val = 4;
sprintf(count, "%d", val);
printf("buf=[%s]\n", count);
return EXIT_SUCCESS;
}
void reversal(char *str)
{
int start = 0;
int end = strlen(str) - 1;
while (start < end)
{
str[start] = str[start] ^ str[end];
str[end] = str[start] ^ str[end];
str[start] = str[start] ^ str[end];
start++;
end--;
}
// char *start = str;
// char *end = str + strlen(str) - 1;
// while (start < end)
// {
// start = *start ^ *end;
// end = *start ^ *end;
// start = *start ^ *end;
// start++;
// end--;
// }
}
int find_char(char *src, char *sub)
{
int index = -1;
while ('\0' != *src)
{
if (*src != *sub)
{
src++;
index++;
continue;
}
char *tmp_src = src;
char *tmp_sub = sub;
while ('\0' != *tmp_sub)
{
if (*tmp_sub != *tmp_src)
{
src++;
break;
}
tmp_src++;
tmp_sub++;
index++;
}
if (0 == *tmp_sub)
{
return index;
}
}
return index;
} |
the_stack_data/18608.c | int main()
{
int a;
a = ((((1 + 1) + 1) + 1) + 1);
return a;
} |
the_stack_data/212644463.c | /*BEGIN_LEGAL
Intel Open Source License
Copyright (c) 2002-2017 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
the 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 INTEL OR
ITS 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.
END_LEGAL */
extern unsigned int foo();
int main()
{
if (foo() == 0xf00) return 0;
return 1;
}
|
the_stack_data/150144464.c | #include <stdio.h>
#include <stdlib.h>
#define tamanho 10
int main(int argc, char *argv[]){
float vetor[tamanho];
float auxiliar;
for(int i = 0; i < tamanho; i++){
scanf("%f", &vetor[i]);
}
for(int j = 0; j < tamanho; j++){
for(int c = 0; c < tamanho; c++){
if(vetor[j] < vetor[c]){
auxiliar = vetor[c];
vetor[c] = vetor[j];
vetor[j] = auxiliar;
}
}
}
for(int k = 0; k < tamanho; k++){
printf("%f\n", vetor[k]);
}
return 0;
} |
the_stack_data/111031.c | /*
* Unix-style assembler for PIC17C4x processors.
* The mnemonics are taken from the old Soviet mainframe BESM-6.
*
* Copyright (C) 1997-2002 Serge Vakulenko <[email protected]>
*
* This file 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.
*
* You can redistribute this file and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software Foundation;
* either version 2 of the License, or (at your discretion) any later version.
* See the accompanying file "COPYING.txt" for more details.
*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <unistd.h>
#define STSIZE 2000 /* symbol table size */
#define TXTSIZE 8196 /* command segment size */
#define DATSIZE 256 /* data segment size */
#define DATSTART 0x20 /* data segment size */
#define OUTSIZE 20 /* hex output line size */
#define MAXCONS 4096 /* max constants */
#define MAXREL 10240 /* max relocated references */
#define MAXLIBS 10 /* max libraries */
#define MAXLABELS 1000 /* max relative (digit) labels */
/*
* Lexical items.
*/
#define LEOF 0 /* end of file */
#define LEOL 1 /* end of line */
#define LNUM 2 /* number */
#define LNAME 3 /* name */
#define LCMD 4 /* machine command */
#define LEQU 5 /* .equ */
#define LDATA 6 /* .data */
#define LCONST 7 /* .const */
#define LORG 8 /* .org */
#define LCONFIG 9 /* .config */
#define LLSHIFT 10 /* << */
#define LRSHIFT 11 /* >> */
/*
* Symbol/expression types.
*/
#define TUNDF 0 /* unknown symbol */
#define TABS 1 /* constant */
#define TDATA 2 /* variable or array */
#define TTEXT 3 /* label or function */
#define TCONST 4 /* far readonly data in text segment */
/*
* Command types.
*/
#define FNARG 1 /* no argument */
#define FLONG 2 /* long argument */
#define FBIT 3 /* additional bit argument */
#define FREG 4 /* additional register argument */
#define FLREG 5 /* additional register argument to left */
#define FSL4 6 /* shift argument left by 4 */
#define FCOND 0x40 /* conditional command */
#define FNOTR 0x80 /* next command not reached */
/*
* Relocation flags.
*/
#define RLONG 1 /* 13-bit address */
#define RHIGH 2 /* upper 8 bits of address */
#define RLAB 4 /* relative label */
/*
* Processor option flags.
*/
#define C_EXTMEM 1
#define C_EXT 2
#define C_PROT 3
#define C_CTLR 4
#define O_RC 1
#define O_CLK 2
#define O_CRYST 3
#define O_LOW 4
/*
* Processor configuration.
*/
#define CFGADDR 0xfe00
#define CFG_PMC_MODE 0x00AF
#define CFG_XMC_MODE 0xFFBF
#define CFG_MC_MODE 0xFFEF
#define CFG_MP_MODE 0xFFFF
#define CFG_WDT_OFF 0xFFF3
#define CFG_WDT_64 0xFFF7
#define CFG_WDT_256 0xFFFB
#define CFG_WDT_1 0xFFFF
#define CFG_LF_OSC 0xFFFC
#define CFG_RC_OSC 0xFFFD
#define CFG_XT_OSC 0xFFFE
#define CFG_EC_OSC 0xFFFF
struct stab {
char *name;
int len;
int type;
int value;
} stab [STSIZE];
struct labeltab {
int num;
int value;
} labeltab [MAXLABELS];
struct constab {
char *val;
int len;
int sym;
} constab [MAXCONS];
struct reltab {
int addr;
int sym;
int flags;
} reltab [MAXREL];
struct libtab {
char *name;
} libtab [MAXLIBS];
char *infile, *infile1, *outfile;
int debug;
int line;
int filenum;
int count;
int dcount = DATSTART;
int reached;
int optim;
int opt_atx_xta, opt_not_reached;
int lastcmd;
int blexflag, backlex, blextype;
char name [256];
int intval;
int extref;
int extflag;
int stabfree;
int config = C_CTLR;
int wdog = 0;
int osc = O_CLK;
int nconst;
int nrel;
int nlib;
int nlabels;
int outaddr;
unsigned char outbuf [OUTSIZE], *outptr = outbuf;
unsigned char data [2*DATSIZE];
unsigned short text [2*TXTSIZE];
unsigned char tbusy [2*TXTSIZE];
#define ISHEX(c) (ctype[(c)&0377] & 1)
#define ISOCTAL(c) (ctype[(c)&0377] & 2)
#define ISDIGIT(c) (ctype[(c)&0377] & 4)
#define ISLETTER(c) (ctype[(c)&0377] & 8)
short ctype [256] = {
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,8,0,7,7,7,7,7,7,7,7,5,5,0,0,0,0,0,0,
0,9,9,9,9,9,9,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,0,0,0,0,8,
0,9,9,9,9,9,9,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,0,0,0,0,0,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
};
void parse (void);
void relocate (void);
void libraries (void);
void listing (void);
void output (void);
void makecmd (int code, int type);
void makeconst (int sym);
void makecfg (void);
int getexpr (int *s);
struct table {
unsigned val;
char *name;
short type;
} table [] = {
/*
* PIC 17c4x instruction set.
*
- Opcode - Mnemonic - Flags --- Description -------------------- Old mnemonic */
#define ATX 0x0100
#define XTA 0x6a00
{ 0x0000, "nop", FNARG }, /* no operation nop */
{ 0x0002, "ret", FNARG | FNOTR }, /* return return */
{ 0x0003, "sleep", FNARG }, /* enter sleep mode sleep */
{ 0x0004, "awake", FNARG }, /* clear watchdog timer clrwdt */
{ 0x0005, "reti", FNARG | FNOTR }, /* return; enable interrupts retfie */
{ 0x0006, "dump", FNARG }, /* pseudo-command: dump register contents */
{ 0x0007, "halt", FNARG }, /* pseudo-command: halt simulation */
{ ATX, "atx", 0 }, /* f = w movwf f */
{ 0x0200, "a-bx", 0 }, /* w = f - (w + ~carry) subwfb f,w */
{ 0x0300, "x-ba", 0 }, /* f -= w + ~carry subwfb f */
{ 0x0400, "a-x", 0 }, /* w = f - w subwf f,w */
{ 0x0500, "x-a", 0 }, /* f -= w subwf f */
{ 0x0600, "x--a", 0 }, /* w = f-1 decf f,w */
{ 0x0700, "x--", 0 }, /* f = f-1 decf f */
{ 0x0800, "a|x", 0 }, /* w |= f iorwf f,w */
{ 0x0900, "x|a", 0 }, /* f |= w iorwf f */
{ 0x0a00, "a&x", 0 }, /* w &= f andwf f,w */
{ 0x0b00, "x&a", 0 }, /* f &= w andwf f */
{ 0x0c00, "a^x", 0 }, /* w ^= f xorwf f,w */
{ 0x0d00, "x^a", 0 }, /* f ^= w xorwf f */
{ 0x0e00, "a+x", 0 }, /* w += f addwf f,w */
{ 0x0f00, "x+a", 0 }, /* f += w addwf f */
{ 0x1000, "a+cx", 0 }, /* w += f + carry addwfc f,w */
{ 0x1100, "x+ca", 0 }, /* f += w + carry addwfc f */
{ 0x1200, "xca", 0 }, /* w = ~f comf f,w */
{ 0x1300, "xc", 0 }, /* f = ~f comf f */
{ 0x130a, "ac", FNARG }, /* w = ~w comf w */
{ 0x1400, "x++a", 0 }, /* w = f+1 incf f,w */
{ 0x1500, "x++", 0 }, /* f = f+1 incf f */
{ 0x150a, "a++", FNARG }, /* w = w+1 incf wreg */
{ 0x1600, "x--a?", FCOND }, /* w = f-1; if (w != 0) decfsz f,w */
{ 0x1700, "x--?", FCOND }, /* f = f-1; if (f != 0) decfsz f */
{ 0x170a, "a--?", FNARG | FCOND }, /* w = w-1; if (w != 0) decfsz wreg */
{ 0x1800, "xc>>a", 0 }, /* w = carry:f >> 1 rrcf f,w */
{ 0x1900, "xc>>x", 0 }, /* f = carry:f >> 1 rrcf f */
{ 0x1a00, "xc<<a", 0 }, /* w = carry:f << 1 rlcf f,w */
{ 0x1b00, "xc<<x", 0 }, /* f = carry:f << 1 rlcf f */
{ 0x1c00, "xwa", 0 }, /* w = swap(f) swapf f,w */
{ 0x1d00, "xw", 0 }, /* f = swap(f) swapf f */
{ 0x1d0a, "aw", FNARG }, /* w = swap(w) swapf wreg */
{ 0x1e00, "x++a?", FCOND }, /* w = f+1; if (w != 0) incfsz f,w */
{ 0x1f00, "x++?", FCOND }, /* f = f+1; if (f != 0) incfsz f */
{ 0x1f0a, "a++?", FNARG | FCOND }, /* w = w+1; if (w != 0) incfsz wreg */
{ 0x2000, "x>>a", 0 }, /* w = f >> 1 rrncf f,w */
{ 0x2100, "x>>x", 0 }, /* f = f >> 1 rrncf f */
{ 0x2200, "x<<a", 0 }, /* w = f << 1 rlncf f,w */
{ 0x2300, "x<<x", 0 }, /* f = f << 1 rlncf f */
{ 0x2400, "x++az?", FCOND }, /* w = f+1; if (w == 0) infsnz f,w */
{ 0x2500, "x++z?", FCOND }, /* f = f+1; if (f == 0) infsnz f */
{ 0x250a, "a++z?", FNARG | FCOND }, /* w = w+1; if (w == 0) infsnz wreg */
{ 0x2600, "x--az?", FCOND }, /* w = f-1; if (w == 0) dcfsnz f,w */
{ 0x2700, "x--z?", FCOND }, /* f = f-1; if (f == 0) dcfsnz f */
{ 0x270a, "a--z?", FNARG | FCOND }, /* w = w-1; if (w == 0) dcfsnz wreg */
{ 0x2800, "xza", 0 }, /* f = w = 0 clrf f,w */
{ 0x2900, "xz", 0 }, /* f = 0 clrf f */
{ 0x290a, "az", FNARG }, /* w = 0 clrf wreg */
{ 0x2a00, "xsa", 0 }, /* f = w = 0xff setf f,w */
{ 0x2b00, "xs", 0 }, /* f = 0xff setf f */
{ 0x2b0a, "as", FNARG }, /* w = 0xff setf wreg */
{ 0x2c00, "anax", 0 }, /* f = w = ~w+1 negw f,w */
{ 0x2d00, "anx", 0 }, /* f = ~w+1 negw f */
{ 0x2e00, "adax", 0 }, /* f = w = adjust(w) daw f,w */
{ 0x2f00, "adx", 0 }, /* f = adjust(w) daw f */
{ 0x3000, "x>=a?", FCOND }, /* if (x >= a) cpfslt f */
{ 0x3100, "x!=a?", FCOND }, /* if (x != a) cpfseq f */
{ 0x3200, "x<=a?", FCOND }, /* if (x <= a) cpfsgt f */
{ 0x3300, "x?", FCOND }, /* if (f != 0) tstfsz f */
{ 0x330a, "a?", FNARG | FCOND }, /* if (w != 0) tstfsz wreg */
{ 0x3400, "a*x", 0 }, /* prod = w*f mulwf f */
{ 0x3800, "bt", FBIT }, /* f.b ^= 1 btg f,b */
{ 0x4000, "rtx", FLREG }, /* f = p movpf p,f */
{ 0x6000, "xtr", FREG }, /* p = f movfp f,p */
{ XTA, "xta", 0 }, /* w = f movfp f,wreg */
{ 0x8000, "bs", FBIT }, /* f.b = 1 bsf f,b */
{ 0x8800, "bz", FBIT }, /* f.b = 0 bcf f,b */
{ 0x9000, "bz?", FBIT | FCOND }, /* if (f.b == 0) btfss f,b */
{ 0x9800, "bs?", FBIT | FCOND }, /* if (f.b != 0) btfsc f,b */
{ 0x9a04, "z?", FNARG | FCOND }, /* if (ALUSTA.Z) btfsc ALUSTA,Z */
{ 0x9204, "nz?", FNARG | FCOND }, /* if (! ALUSTA.Z) btfss ALUSTA,Z */
{ 0x9804, "c?", FNARG | FCOND }, /* if (ALUSTA.C) btfsc ALUSTA,C */
{ 0x9804, "nb?", FNARG | FCOND }, /* if (ALUSTA.C) btfsc ALUSTA,C */
{ 0x9004, "b?", FNARG | FCOND }, /* if (! ALUSTA.C) btfss ALUSTA,C */
{ 0x9004, "nc?", FNARG | FCOND }, /* if (! ALUSTA.C) btfss ALUSTA,C */
{ 0xa000, "llx", 0 }, /* f = low(latch) tlrd 0,f */
{ 0xa200, "lhx", 0 }, /* f = high(latch) tlrd 1,f */
{ 0xa400, "xll", 0 }, /* low(latch) = f tlwt 0,f */
{ 0xa600, "xhl", 0 }, /* high(latch) = f tlwt 1,f */
{ 0xa800, "plx", 0 }, /* f = low(latch); latch = *tptr tablrd 0,0,f */
{ 0xa900, "pl++x", 0 }, /* f = low(latch); latch = *tptr++ tablrd 0,1,f */
{ 0xae00, "xhp", 0 }, /* high(latch) = f; *tptr = latch tablwt 1,0,f */
{ 0xaf00, "xhp++", 0 }, /* high(latch) = f; *tptr++ = latch tablwt 1,1,f */
{ 0xb000, "cta", 0 }, /* w = c movlw k */
{ 0xb100, "a+c", 0 }, /* w += c addlw k */
{ 0xb200, "c-a", 0 }, /* w = c - w sublw k */
{ 0xb300, "a|c", 0 }, /* w |= c iorlw k */
{ 0xb400, "a^c", 0 }, /* w ^= c xorlw k */
{ 0xb500, "a&c", 0 }, /* w &= c andlw k */
{ 0xb600, "retc", FNOTR }, /* w = c; return retlw k */
{ 0xb700, "lcall", 0 }, /* lcall c() lcall k */
{ 0xb800, "reg", 0 }, /* low(bsr) = c movlb k */
{ 0xba00, "dat", FSL4 }, /* high(bsr) = c movlr k */
{ 0xbc00, "a*c", 0 }, /* prod = w * c mullw k */
{ 0xc000, "goto", FLONG | FNOTR }, /* goto goto */
{ 0xe000, "call", FLONG }, /* call call */
{ 0 }};
void uerror (char *s, ...)
{
va_list ap;
va_start (ap, s);
fprintf (stderr, "as: ");
if (infile)
fprintf (stderr, "%s, ", infile);
fprintf (stderr, "%d: ", line);
vfprintf (stderr, s, ap);
va_end (ap);
fprintf (stderr, "\n");
if (outfile)
unlink (outfile);
exit (1);
}
/*
* Look up the symbol.
*/
int lookname ()
{
int i, len;
struct stab *s;
len = strlen (name);
s = 0;
if (name[0] == 'L')
name[0] = '.';
for (i=0; i<stabfree; ++i) {
if (! stab[i].len && ! s) {
s = stab+i;
continue;
}
if (name[0] == '.' && stab[i].len == len+1 &&
stab[i].name[0] == 'A'+filenum &&
! strcmp (stab[i].name+1, name))
return i;
if (stab[i].len == len && ! strcmp (stab[i].name, name))
return i;
}
if (! s)
s = stab + stabfree++;
/* Add the new symbol. */
if (s >= stab + STSIZE)
uerror ("symbol table overflow");
s->name = malloc (2 + len);
if (! s->name)
uerror ("out of memory");
s->len = len;
if (name[0] == '.') {
s->name[0] = 'A' + filenum;
strcpy (s->name+1, name);
++s->len;
} else
strcpy (s->name, name);
s->value = 0;
s->type = 0;
return s - stab;
}
int main (int argc, char **argv)
{
int i;
char *cp;
for (i=1; i<argc; i++)
switch (argv[i][0]) {
case '-':
for (cp=argv[i]; *cp; cp++) switch (*cp) {
case 'd':
debug++;
break;
case 'O':
optim++;
break;
case 'o':
if (cp [1]) {
/* -ofile */
outfile = cp+1;
while (*++cp);
--cp;
} else if (i+1 < argc)
/* -o file */
outfile = argv[++i];
break;
case 'l':
if (nlib >= MAXLIBS)
uerror ("too many libraries");
if (cp [1]) {
/* -lname */
libtab[nlib++].name = cp+1;
while (*++cp);
--cp;
} else if (i+1 < argc)
/* -l name */
libtab[nlib++].name = argv[++i];
break;
}
break;
default:
infile = argv[i];
if (! infile1)
infile1 = infile;
if (! freopen (infile, "r", stdin))
uerror ("cannot open");
line = 1;
parse ();
infile = 0;
++filenum;
break;
}
if (! outfile) {
if (! infile1) {
printf ("PIC 17c4x Assembler, by Serge V.Vakulenko\n");
printf ("Copyright (C) 1997 Cronyx Engineering Ltd.\n\n");
printf ("Usage:\n\tas17 [-O] [-o outfile.hex] infile.s ...\n\n");
return -1;
}
outfile = malloc (4 + strlen (infile1));
if (! outfile)
uerror ("out of memory");
strcpy (outfile, infile1);
cp = strrchr (outfile, '.');
if (! cp)
cp = outfile + strlen (outfile);
strcpy (cp, ".hex");
}
if (! freopen (outfile, "w", stdout))
uerror ("cannot open %s", outfile);
if (! nlib)
libtab[nlib++].name = "/usr/local/lib/pic17";
libraries ();
relocate ();
listing ();
output ();
return 0;
}
int lookcmd ()
{
int i;
for (i=0; table[i].name; ++i)
if (! strcmp (table[i].name, name))
return i;
return -1;
}
int hexdig (int c)
{
if (c <= '9') return c - '0';
else if (c <= 'F') return c - 'A' + 10;
else return c - 'a' + 10;
}
/*
* Read the integer value.
* 1234 - decimal
* 01234 - octal
* 0x1234 - hexadecimal
* 0b1101 - binary
*/
void getnum (int c)
{
intval = 0;
if (c == '0') {
c = getchar ();
if (c == 'x' || c == 'X') {
while (ISHEX (c = getchar()))
intval = intval*16 + hexdig (c);
if (c >= 0)
ungetc (c, stdin);
return;
}
if (c == 'b' || c == 'B') {
while ((c = getchar()) == '0' || c == '1')
intval = intval*2 + c - '0';
if (c >= 0)
ungetc (c, stdin);
return;
}
if (c >= 0)
ungetc (c, stdin);
while (ISOCTAL (c = getchar()))
intval = intval*8 + hexdig (c);
if (c >= 0)
ungetc (c, stdin);
return;
}
if (c >= 0)
ungetc (c, stdin);
while (ISDIGIT (c = getchar()))
intval = intval*10 + hexdig (c);
if (c >= 0)
ungetc (c, stdin);
}
void getname (int c, int extname)
{
char *cp;
for (cp=name; c>' ' && c!=':'; c=getchar()) {
if (! extname && ! ISLETTER (c) && ! ISDIGIT (c))
break;
*cp++ = c;
}
*cp = 0;
ungetc (c, stdin);
}
/*
* Read the next lexical item from the input stream.
*/
int getlex (int *pval, int extname)
{
int c;
if (blexflag) {
blexflag = 0;
*pval = blextype;
return backlex;
}
for (;;) switch (c = getchar()) {
case ';':
case '#':
skiptoeol: while ((c = getchar()) != '\n')
if (c == EOF)
return LEOF;
case '\n':
++line;
c = getchar ();
if (c == '#')
goto skiptoeol;
ungetc (c, stdin);
*pval = line;
return LEOL;
case ' ':
case '\t':
continue;
case EOF:
return LEOF;
case '<':
if ((c = getchar()) == '<')
return LLSHIFT;
ungetc (c, stdin);
return '<';
case '>':
if ((c = getchar()) == '>')
return LRSHIFT;
ungetc (c, stdin);
return '>';
case '\'':
c = getchar ();
if (c == '\'')
uerror ("bad char constant");
if (c == '\\')
switch (c = getchar()) {
case 'a': c = 0x07; break;
case 'b': c = '\b'; break;
case 'f': c = '\f'; break;
case 'n': c = '\n'; break;
case 'r': c = '\r'; break;
case 't': c = '\t'; break;
case 'v': c = '\v'; break;
case '\'': break;
case '\\': break;
default: uerror ("bad char constant");
}
if (getchar() != '\'')
uerror ("bad char constant");
intval = c;
return LNUM;
case '*': case '/': case '%': case '\\':
case '^': case '&': case '|': case '~':
case '"': case ',': case '[': case ']':
case '(': case ')': case '{': case '}':
case '=': case ':': case '+': case '-':
case '@':
return c;
case '0': case '1': case '2': case '3':
case '4': case '5': case '6': case '7':
case '8': case '9':
getnum (c);
return LNUM;
default:
if (! ISLETTER (c))
uerror ("bad character: \\%o", c & 0377);
getname (c, extname);
if (name[0] == '.') {
if (! name[1]) return '.';
if (! strcmp (name, ".equ")) return LEQU;
if (! strcmp (name, ".data")) return LDATA;
if (! strcmp (name, ".org")) return LORG;
if (! strcmp (name, ".const")) return LCONST;
if (! strcmp (name, ".config")) return LCONFIG;
}
if ((*pval = lookcmd()) != -1)
return LCMD;
*pval = lookname ();
return LNAME;
}
}
#if 0
int getlex (int *pval, int extname)
{
int clex;
clex = getlex1 (pval, extname);
switch (clex) {
case LEOF: fprintf (stderr, "EOF\n"); break;
case LEOL: fprintf (stderr, "EOL\n"); break;
case LNUM: fprintf (stderr, "NUM %d\n", intval); break;
case LNAME: fprintf (stderr, "NAME %s\n", stab[*pval].name); break;
case LCMD: fprintf (stderr, "CMD %s\n", table[*pval].name); break;
case LEQU: fprintf (stderr, ".EQU\n"); break;
case LDATA: fprintf (stderr, ".DATA\n"); break;
case LCONST: fprintf (stderr, ".CONST\n"); break;
case LORG: fprintf (stderr, ".ORG\n"); break;
case LCONFIG: fprintf (stderr, ".CONFIG\n"); break;
default: fprintf (stderr, "LEX `%c'\n", clex); break;
}
return clex;
}
#endif
void ungetlex (int val, int type)
{
blexflag = 1;
backlex = val;
blextype = type;
}
/*
* Get the expression term.
*/
int getterm ()
{
int cval, s;
switch (getlex (&cval, 0)) {
default:
uerror ("operand missing");
case LNUM:
cval = getchar ();
if (cval == 'f' || cval == 'F' || cval == 'b' || cval == 'B') {
if (cval == 'b' || cval == 'B')
extref = -intval;
else
extref = intval;
extflag |= RLAB;
intval = 0;
return TUNDF;
}
ungetc (cval, stdin);
return TABS;
case '@':
extflag |= RHIGH;
if (getlex (&cval, 0) != LNAME)
uerror ("bad @ syntax");
case LNAME:
if (stab[cval].type == TUNDF || stab[cval].type == TCONST) {
intval = 0;
extref = cval;
} else
intval = stab[cval].value;
return stab[cval].type;
case '.':
intval = count;
return TTEXT;
case '(':
getexpr (&s);
if (getlex (&cval, 0) != ')')
uerror ("bad () syntax");
return s;
}
}
/*
* Read the expression.
* Put the type of expression into *s.
*
* expr = [term] {op term}...
* term = LNAME | LNUM | "." | "(" expr ")"
* op = "+" | "-" | "&" | "|" | "^" | "~" | "<<" | ">>" | "/" | "*" | "%"
*/
int getexpr (int *s)
{
int clex, cval, s2, rez;
/* Get the first item. */
switch (clex = getlex (&cval, 0)) {
default:
ungetlex (clex, cval);
rez = 0;
*s = TABS;
break;
case LNUM:
case LNAME:
case '.':
case '(':
case '@':
ungetlex (clex, cval);
*s = getterm ();
rez = intval;
break;
}
for (;;) {
switch (clex = getlex (&cval, 0)) {
case '+':
s2 = getterm ();
if (*s == TABS) *s = s2;
else if (s2 != TABS)
uerror ("too complex expression");
rez += intval;
break;
case '-':
s2 = getterm ();
if (s2 != TABS)
uerror ("too complex expression");
rez -= intval;
break;
case '&':
s2 = getterm ();
if (*s != TABS || s2 != TABS)
uerror ("too complex expression");
rez &= intval;
break;
case '|':
s2 = getterm ();
if (*s != TABS || s2 != TABS)
uerror ("too complex expression");
rez |= intval;
break;
case '^':
s2 = getterm ();
if (*s != TABS || s2 != TABS)
uerror ("too complex expression");
rez ^= intval;
break;
case '~':
s2 = getterm ();
if (*s != TABS || s2 != TABS)
uerror ("too complex expression");
rez ^= ~intval;
break;
case LLSHIFT:
s2 = getterm ();
if (*s != TABS || s2 != TABS)
uerror ("too complex expression");
rez <<= intval;
break;
case LRSHIFT:
s2 = getterm ();
if (*s != TABS || s2 != TABS)
uerror ("too complex expression");
rez >>= intval;
break;
case '*':
s2 = getterm ();
if (*s != TABS || s2 != TABS)
uerror ("too complex expression");
rez *= intval;
break;
case '/':
s2 = getterm ();
if (*s != TABS || s2 != TABS)
uerror ("too complex expression");
if (! intval)
uerror ("division by zero");
rez /= intval;
break;
case '%':
s2 = getterm ();
if (*s != TABS || s2 != TABS)
uerror ("too complex expression");
if (! intval)
uerror ("division (%%) by zero");
rez %= intval;
break;
default:
ungetlex (clex, cval);
intval = rez;
return rez;
}
}
}
void parse ()
{
int clex, cval, tval;
for (;;) {
clex = getlex (&cval, 1);
switch (clex) {
case LEOF:
return;
case LEOL:
continue;
case LCMD:
makecmd (table[cval].val, table[cval].type);
break;
case LNAME:
clex = getlex (&tval, 0);
switch (clex) {
case ':': /* name: */
if (stab[cval].type != TUNDF) {
uerror ("name redefined");
break;
}
stab[cval].value = count;
stab[cval].type = TTEXT;
if (! reached)
reached = 1;
lastcmd = 0;
continue;
case LEQU: /* name .equ val */
getexpr (&tval);
if (tval == TUNDF)
uerror ("bad value .equ");
if (stab[cval].type != TUNDF) {
if (stab[cval].type != tval ||
stab[cval].value != intval)
uerror ("name redefined");
break;
}
stab[cval].type = tval;
stab[cval].value = intval;
break;
case LDATA: /* name .data size */
getexpr (&tval);
if (tval != TABS || intval < 0)
uerror ("bad length .data");
if (stab[cval].type != TUNDF) {
if (stab[cval].type != TDATA)
uerror ("name already defined");
break;
}
stab[cval].type = TDATA;
stab[cval].value = dcount;
dcount += intval;
break;
case LCONST: /* name .const val,val... */
if (stab[cval].type != TUNDF)
uerror ("name already defined");
stab[cval].type = TCONST;
stab[cval].value = 0;
makeconst (cval);
break;
default:
uerror ("bad command");
}
break;
case LNUM:
if (nlabels >= MAXLABELS)
uerror ("too many digital labels");
labeltab[nlabels].num = intval;
labeltab[nlabels].value = count;
++nlabels;
clex = getlex (&tval, 0);
if (clex != ':')
uerror ("bad digital label");
if (! reached)
reached = 1;
lastcmd = 0;
continue;
case LORG:
getexpr (&tval);
if (tval != TABS)
uerror ("bad value .org");
count = intval;
break;
case LCONFIG:
makecfg ();
break;
default:
uerror ("syntax error");
}
clex = getlex (&cval, 0);
if (clex != LEOL) {
if (clex == LEOF)
return;
uerror ("bad command argument");
}
}
}
/*
* Flush the output buffer.
*/
void outflush (void)
{
unsigned char *p, sum = 0;
/* set byte count */
outbuf[0] = outptr - outbuf - 4;
putchar (':');
for (p=outbuf; p<outptr; ++p) {
printf ("%02X", *p);
sum += *p;
}
printf ("%02X\n", (unsigned char) -sum);
outptr = outbuf;
}
/*
* Put the word to the output buffer.
*/
void outhex (long addr, int val)
{
if (outptr >= outbuf + OUTSIZE ||
(outptr > outbuf && addr != outaddr+1))
outflush ();
if (outptr == outbuf) {
*outptr++ = 0;
*outptr++ = addr >> 7;
*outptr++ = addr << 1;
*outptr++ = 0;
}
*outptr++ = val;
*outptr++ = val >> 8;
outaddr = addr;
}
/*
* Write the resulting hex image.
*/
void output ()
{
int i, option;
printf (":020000040000FA\n");
for (i=0; i<TXTSIZE; ++i)
if (tbusy [i])
outhex (i, text[i]);
if (outptr > outbuf)
outflush ();
option = 0xffff;
switch (config) {
case C_PROT: option &= CFG_PMC_MODE; break;
case C_EXT: option &= CFG_XMC_MODE; break;
case C_CTLR: option &= CFG_MC_MODE; break;
case C_EXTMEM: option &= CFG_MP_MODE; break;
}
switch (wdog) {
case 0: option &= CFG_WDT_OFF; break;
case 64: option &= CFG_WDT_64; break;
case 256: option &= CFG_WDT_256; break;
case 1: option &= CFG_WDT_1; break;
}
switch (osc) {
case O_LOW: option &= CFG_LF_OSC; break;
case O_RC: option &= CFG_RC_OSC; break;
case O_CRYST: option &= CFG_XT_OSC; break;
case O_CLK: option &= CFG_EC_OSC; break;
}
printf (":020000040001F9\n");
outhex (CFGADDR, option);
outflush ();
printf (":00000001FF\n");
}
/*
* Compile the constant.
*/
void makeconst (int sym)
{
char buf [1024], *p = buf;
int len, tval, clex, cval;
if (nconst >= MAXCONS)
uerror ("too many constants");
for (;;) {
getexpr (&tval);
if (tval != TABS)
uerror ("bad value .const");
if (p >= buf + sizeof (buf))
uerror ("too long .const");
*p++ = intval;
clex = getlex (&cval, 0);
if (clex != ',') {
ungetlex (clex, cval);
break;
}
}
len = p - buf;
constab[nconst].val = malloc (len + 1);
if (! constab[nconst].val)
uerror ("out of memory");
memcpy (constab[nconst].val, buf, len);
constab[nconst].len = len;
constab[nconst].sym = sym;
++nconst;
}
/*
* Set the processor options.
*/
void makecfg ()
{
int c, clex, cval;
for (;;) {
while ((c = getchar()) == ' ' || c == '\t')
continue;
if (! ISLETTER (c))
uerror ("bad option .config");
getname (c, 0);
if (! strcasecmp (name, "microprocessor")) config = C_EXTMEM;
else if (! strcasecmp (name, "extended")) config = C_EXT;
else if (! strcasecmp (name, "protected")) config = C_PROT;
else if (! strcasecmp (name, "watchdog")) wdog = 1;
else if (! strcasecmp (name, "watchdog64")) wdog = 64;
else if (! strcasecmp (name, "watchdog256")) wdog = 256;
else if (! strcasecmp (name, "nowatchdog")) wdog = 0;
else if (! strcasecmp (name, "rc")) osc = O_RC;
else if (! strcasecmp (name, "extclock")) osc = O_CLK;
else if (! strcasecmp (name, "crystal")) osc = O_CRYST;
else if (! strcasecmp (name, "lowcrystal")) osc = O_LOW;
else
uerror ("bad option .config");
clex = getlex (&cval, 0);
if (clex != ',') {
ungetlex (clex, cval);
break;
}
}
}
/*
* Set text segment value.
*/
void settext (int addr, int val)
{
text [addr] = val;
tbusy [addr] = 1;
if (debug)
fprintf (stderr, "code %3d: %04x\n", addr, val);
lastcmd = val;
}
/*
* Resolve pending references, adding
* modules from libraries.
*/
void libraries ()
{
struct stab *s;
int n, undefined;
char name [256];
/* For every undefined reference,
* add the module from the library. */
undefined = 0;
for (s=stab; s<stab+stabfree; ++s) {
if (s->type != TUNDF)
continue;
for (n=0; n<nlib; ++n) {
sprintf (name, "%s/%s.lib", libtab[n].name, s->name);
if (freopen (name, "r", stdin)) {
infile = name;
line = 1;
parse ();
infile = 0;
++filenum;
break;
}
}
if (n >= nlib) {
fprintf (stderr, "as: undefined: %s\n", s->name);
++undefined;
}
}
if (undefined > 0) {
unlink (outfile);
exit (1);
}
}
/*
* Find the relative label address,
* by the reference address and the label number.
* Backward references have negative label numbers.
*/
int findlabel (int addr, int sym)
{
struct labeltab *p;
if (sym < 0) {
/* Backward reference. */
for (p=labeltab+nlabels-1; p>=labeltab; --p)
if (p->value <= addr && p->num == -sym)
return p->value;
uerror ("undefined label %db at address %d", -sym, addr);
} else {
/* Forward reference. */
for (p=labeltab; p<labeltab+nlabels; ++p)
if (p->value > addr && p->num == sym)
return p->value;
uerror ("undefined label %df at address %d", sym, addr);
}
return 0;
}
int compare_constab_len (const void *pa, const void *pb)
{
const struct constab *a = pa, *b = pb;
if (a->len > b->len)
return -1;
return (a->len < b->len);
}
/*
* Allocate constants and relocate references.
*/
void relocate ()
{
int n, v;
struct constab *c, *p;
struct reltab *r;
int tsize, csize, dsize;
tsize = csize = 0;
dsize = dcount - DATSTART;
for (n=0; n<TXTSIZE; ++n)
if (tbusy [n])
++tsize;
/* Place the constants at the end of text segment. */
qsort (constab, nconst, sizeof (constab[0]), compare_constab_len);
for (c=constab; c<constab+nconst; ++c) {
/* Try to find and reuse the constant. */
for (p=constab; p<c; ++p)
if (p->len >= c->len &&
memcmp (p->val + p->len - c->len, c->val, c->len) == 0) {
stab[c->sym].value = stab[p->sym].value + p->len - c->len;
stab[c->sym].type = TTEXT;
break;
}
if (p < c)
continue;
stab[c->sym].value = count;
stab[c->sym].type = TTEXT;
for (n=0; n<c->len; ++n) {
settext (count++, c->val[n]);
++csize;
}
}
/* Relocate pending references. */
for (r=reltab; r<reltab+nrel; ++r) {
if (r->flags & RLAB)
v = findlabel (r->addr, r->sym);
else
v = stab[r->sym].value;
if (r->flags & RHIGH)
v >>= 8;
if (r->flags & RLONG) {
v += text [r->addr] & 0x1fff;
text [r->addr] &= ~0x1fff;
text [r->addr] |= v & 0x1fff;
} else {
v += text [r->addr] & 0xff;
text [r->addr] &= ~0xff;
text [r->addr] |= v & 0xff;
}
}
if (opt_atx_xta || opt_not_reached)
fprintf (stderr, "Optimization: atx-xta: %d words, not-reached: %d words\n",
opt_atx_xta, opt_not_reached);
fprintf (stderr, "Total text %d words, const %d words, data %d bytes\n",
tsize, csize, dsize);
if (count > TXTSIZE)
uerror ("text segment overflow: %d words", count);
if (dcount > DATSIZE)
uerror ("data segment overflow: %d bytes", dsize);
fprintf (stderr, "Free text %d words, data %d bytes\n",
TXTSIZE - count, DATSIZE - dcount);
}
int compare_stab (const void *pa, const void *pb)
{
const struct stab *a = pa, *b = pb;
if (a->type == TDATA && b->type != TDATA)
return -1;
if (a->type != TDATA && b->type == TDATA)
return 1;
if (a->value < b->value)
return -1;
return (a->value > b->value);
}
int compare_constab (const void *pa, const void *pb)
{
const struct constab *a = pa, *b = pb;
if (a->sym < b->sym)
return -1;
return (a->sym > b->sym);
}
/*
* Print the table of symbols and text constants.
*/
void listing ()
{
struct stab *s;
struct constab *c;
char *p, *lstname;
FILE *lstfile;
int t, n;
lstname = malloc (4 + strlen (outfile));
if (! lstname)
uerror ("out of memory");
strcpy (lstname, outfile);
p = strrchr (lstname, '.');
if (! p)
p = lstname + strlen (lstname);
strcpy (p, ".lst");
lstfile = fopen (lstname, "w");
if (! lstfile)
uerror ("cannot write to %s", lstname);
/* Remember the addresses of constants. */
for (c=constab; c<constab+nconst; ++c)
c->sym = stab[c->sym].value;
/* Sort the symbol table. */
qsort (stab, stabfree, sizeof (stab[0]), compare_stab);
fprintf (lstfile, "Data symbols:\n");
#if 0
datamode = 1;
for (s=stab; s<stab+stabfree; ++s) {
if (s->name[1] == '.')
continue;
if (s->type != TDATA && datamode) {
fprintf (lstfile, "\nCode symbols:\n");
datamode = 0;
}
switch (s->type) {
case TUNDF: t = 'U'; break;
case TABS: t = 'A'; break;
case TDATA: t = 'D'; break;
case TTEXT: t = 'T'; break;
case TCONST: t = 'C'; break;
default: t = '?'; break;
}
fprintf (lstfile, "\t%04x %c %.*s\n",
s->value, t, s->len, s->name);
}
#else
for (s=stab; s<stab+stabfree; ++s) {
if (s->name[1] == '.')
continue;
switch (s->type) {
default: continue;
case TDATA: t = 'D'; break;
case TABS: t = 'A'; break;
}
fprintf (lstfile, "\t%04x %c %.*s\n",
s->value, t, s->len, s->name);
}
fprintf (lstfile, "\nCode symbols:\n");
for (s=stab; s<stab+stabfree; ++s) {
if (s->name[1] == '.')
continue;
switch (s->type) {
default: continue;
case TUNDF: t = 'U'; break;
case TTEXT: t = 'T'; break;
case TCONST: t = 'C'; break;
}
fprintf (lstfile, "\t%04x %c %.*s\n",
s->value, t, s->len, s->name);
}
t = 0;
for (n=TXTSIZE-1; n>=0; --n)
if (tbusy [n]) {
t = n;
break;
}
fprintf (lstfile, "\t%04x T <end>\n", t);
#endif
/* Sort the table of constants. */
qsort (constab, nconst, sizeof (constab[0]), compare_constab);
fprintf (lstfile, "\nText constants:\n");
for (c=constab; c<constab+nconst; ++c) {
/* Skip repeated constants. */
if (c > constab && c->sym < c[-1].sym + c[-1].len)
continue;
fprintf (lstfile, "\t%04x C \"", c->sym);
for (p=c->val; p<c->val+c->len; ++p) {
switch (*p) {
case '\n': fprintf (lstfile, "\\n"); break;
case '\r': fprintf (lstfile, "\\r"); break;
case '"': fprintf (lstfile, "\\\""); break;
case '\\': fprintf (lstfile, "\\\\"); break;
case '\0':
if (p < c->val+c->len-1)
fprintf (lstfile, "\\000");
break;
default:
if (*p < ' ' || *p > '~')
fprintf (lstfile, "\\%03o", *p);
else
fprintf (lstfile, "%c", *p);
}
}
fprintf (lstfile, "\"\n");
}
fprintf (lstfile, "\nDone.\n");
}
void addreloc (int addr, int sym, int flags)
{
if (nrel >= MAXREL)
uerror ("too many relocations");
reltab[nrel].addr = addr;
reltab[nrel].sym = sym;
reltab[nrel].flags = flags;
++nrel;
if (debug) {
fprintf (stderr, "reloc %d", addr);
if (sym)
fprintf (stderr, " %d", sym);
if (flags & RLAB)
fprintf (stderr, " RLAB");
if (flags & RHIGH)
fprintf (stderr, " RHIGH");
if (flags & RLONG)
fprintf (stderr, " RLONG");
fprintf (stderr, "\n");
}
}
/*
* Compile the command.
*/
void makecmd (int code, int type)
{
int tval, tval2, cval;
extflag = 0;
if (! reached && (count == 0 || count == 8 || count == 0x10 ||
count == 0x18 || count == 0x20))
reached = 1;
switch (type & ~(FCOND | FNOTR)) {
case FNARG: /* no argument */
if (! reached) {
++opt_not_reached;
break;
}
settext (count++, code);
break;
default:
getexpr (&tval);
if (! reached) {
++opt_not_reached;
break;
}
if (tval == TUNDF || tval == TCONST)
addreloc (count, extref, extflag);
intval &= 0xff;
if (optim && code == ATX && lastcmd == (XTA | intval)) {
/* fprintf (stderr, "atx-xta at 0x%x\n", count); */
++opt_atx_xta;
break;
}
settext (count++, code | intval);
break;
case FSL4:
getexpr (&tval);
if (tval != TABS)
uerror ("bad data page number");
if (! reached) {
++opt_not_reached;
break;
}
code |= intval << 4 & 0xf0;
settext (count++, code);
break;
case FLONG: /* long argument */
getexpr (&tval);
if (! reached) {
++opt_not_reached;
break;
}
if (tval == TUNDF || tval == TCONST)
addreloc (count, extref, extflag | RLONG);
code |= intval & 0x1fff;
settext (count++, code);
break;
case FBIT: /* additional bit argument */
getexpr (&tval);
code |= intval & 0xff;
if (getlex (&cval, 0) != ',')
uerror ("need bit number");
getexpr (&tval2);
if (tval2 != TABS)
uerror ("bad bit number");
if (! reached) {
++opt_not_reached;
break;
}
if (tval == TUNDF || tval == TCONST)
addreloc (count, extref, extflag);
code |= intval << 8 & 0x700;
settext (count++, code);
break;
case FREG: /* additional register argument */
getexpr (&tval);
code |= intval & 0xff;
if (getlex (&cval, 0) != ',')
uerror ("need register number");
getexpr (&tval2);
if (tval2 != TABS)
uerror ("bad register number");
if (! reached) {
++opt_not_reached;
break;
}
if (tval == TUNDF || tval == TCONST)
addreloc (count, extref, extflag);
code |= intval << 8 & 0x1f00;
settext (count++, code);
break;
case FLREG: /* additional register argument to left */
getexpr (&tval);
if (tval != TABS)
uerror ("bad register number");
code |= intval << 8 & 0x1f00;
if (getlex (&cval, 0) != ',')
uerror ("need register number");
getexpr (&tval);
if (! reached) {
++opt_not_reached;
break;
}
if (tval == TUNDF || tval == TCONST)
addreloc (count, extref, extflag);
code |= intval & 0xff;
settext (count++, code);
break;
}
if (optim && reached) {
if (type & FNOTR)
--reached;
else {
reached = 1;
if (type & FCOND)
reached = 2;
}
}
}
|
the_stack_data/136777.c | /*******************************************************************************
* This is a very simple ODP/OFP app that proxies all data between a client and
* server.
******************************************************************************/
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char **argv)
{
int so = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
printf("socket() returned %d.\n", so);
struct sockaddr_in listener_addr;
memset(&listener_addr, 0, sizeof(listener_addr));
listener_addr.sin_family = AF_INET;
listener_addr.sin_port = htons(760);
listener_addr.sin_addr.s_addr = inet_addr("172.17.0.1");
int rc = bind(so, (struct sockaddr *) &listener_addr, sizeof(listener_addr));
printf("bind() returned %d.\n", rc);
while(1) {
usleep(10000);
struct sockaddr_in dst_addr;
memset(&dst_addr, 0, sizeof(dst_addr));
dst_addr.sin_family = AF_INET;
dst_addr.sin_port = htons(2048);
dst_addr.sin_addr.s_addr = inet_addr("172.17.0.3");
const char *send_buf = "Hello world";
ssize_t s = sendto(so, send_buf, strlen(send_buf), 0, (struct sockaddr *) &dst_addr, sizeof(dst_addr));
printf("sendto() returned %ld.\n", s);
char recv_buf[1024];
struct sockaddr_in src_addr;
socklen_t src_addr_len;
src_addr_len = sizeof(src_addr);
ssize_t r = recvfrom(so, recv_buf, sizeof(recv_buf), 0, (struct sockaddr *) &src_addr, &src_addr_len);
printf("recvfrom() returned %ld.\n", r);
if(r > 0) {
recv_buf[r] = 0;
printf("Received '%s'.\n", recv_buf);
}
}
return rc;
}
|
the_stack_data/19580.c | /**
******************************************************************************
* @file stm32h7xx_hal_i2s_ex.c
* @author MCD Application Team
* @brief I2S HAL module driver.
* This file provides firmware functions to manage the following
* functionalities of I2S extension peripheral:
* + Extension features Functions
******************************************************************************
* @attention
*
* Copyright (c) 2017 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/**
******************************************************************************
===== I2S FULL DUPLEX FEATURE =====
I2S Full Duplex APIs are available in stm32h7xx_hal_i2s.c/.h
******************************************************************************
*/
|
the_stack_data/103265055.c | int main()
{
int i, a, b;
a = 0;
b = 1;
for(i=0; i<10; i++)
a = a+b;
return a;
}
|
the_stack_data/218892085.c | //*****************************************************************************
//
// startup_ccs.c - Startup code for use with TI's Code Composer Studio.
//
// Copyright (c) 2011-2013 Texas Instruments Incorporated. All rights reserved.
// Software License Agreement
//
// Texas Instruments (TI) is supplying this software for use solely and
// exclusively on TI's microcontroller products. The software is owned by
// TI and/or its suppliers, and is protected under applicable copyright
// laws. You may not combine this software with "viral" open-source
// software in order to form a larger program.
//
// THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS.
// NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT
// NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY
// CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
// DAMAGES, FOR ANY REASON WHATSOEVER.
//
// This is part of revision 10636 of the MDL-LM3S818CNCD Firmware Package.
//
//*****************************************************************************
//*****************************************************************************
//
// Forward declaration of the default fault handlers.
//
//*****************************************************************************
void ResetISR(void);
static void NmiSR(void);
static void FaultISR(void);
static void IntDefaultHandler(void);
//*****************************************************************************
//
// External declaration for the reset handler that is to be called when the
// processor is started
//
//*****************************************************************************
extern void _c_int00(void);
//*****************************************************************************
//
// Linker variable that marks the top of the stack.
//
//*****************************************************************************
extern unsigned long __STACK_TOP;
//*****************************************************************************
//
// External declarations for the interrupt handlers used by the application.
//
//*****************************************************************************
extern void Timer0IntHandler(void);
extern void Timer1IntHandler(void);
//*****************************************************************************
//
// The vector table. Note that the proper constructs must be placed on this to
// ensure that it ends up at physical address 0x0000.0000 or at the start of
// the program if located at a start address other than 0.
//
//*****************************************************************************
#pragma DATA_SECTION(g_pfnVectors, ".intvecs")
void (* const g_pfnVectors[])(void) =
{
(void (*)(void))((unsigned long)&__STACK_TOP),
// The initial stack pointer
ResetISR, // The reset handler
NmiSR, // The NMI handler
FaultISR, // The hard fault handler
IntDefaultHandler, // The MPU fault handler
IntDefaultHandler, // The bus fault handler
IntDefaultHandler, // The usage fault handler
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
IntDefaultHandler, // SVCall handler
IntDefaultHandler, // Debug monitor handler
0, // Reserved
IntDefaultHandler, // The PendSV handler
IntDefaultHandler, // The SysTick handler
IntDefaultHandler, // GPIO Port A
IntDefaultHandler, // GPIO Port B
IntDefaultHandler, // GPIO Port C
IntDefaultHandler, // GPIO Port D
IntDefaultHandler, // GPIO Port E
IntDefaultHandler, // UART0 Rx and Tx
IntDefaultHandler, // UART1 Rx and Tx
IntDefaultHandler, // SSI0 Rx and Tx
IntDefaultHandler, // I2C0 Master and Slave
IntDefaultHandler, // PWM Fault
IntDefaultHandler, // PWM Generator 0
IntDefaultHandler, // PWM Generator 1
IntDefaultHandler, // PWM Generator 2
IntDefaultHandler, // Quadrature Encoder 0
IntDefaultHandler, // ADC Sequence 0
IntDefaultHandler, // ADC Sequence 1
IntDefaultHandler, // ADC Sequence 2
IntDefaultHandler, // ADC Sequence 3
IntDefaultHandler, // Watchdog timer
Timer0IntHandler, // Timer 0 subtimer A
IntDefaultHandler, // Timer 0 subtimer B
Timer1IntHandler, // Timer 1 subtimer A
IntDefaultHandler, // Timer 1 subtimer B
IntDefaultHandler, // Timer 2 subtimer A
IntDefaultHandler, // Timer 2 subtimer B
IntDefaultHandler, // Analog Comparator 0
IntDefaultHandler, // Analog Comparator 1
IntDefaultHandler, // Analog Comparator 2
IntDefaultHandler, // System Control (PLL, OSC, BO)
IntDefaultHandler // FLASH Control
};
//*****************************************************************************
//
// This is the code that gets called when the processor first starts execution
// following a reset event. Only the absolutely necessary set is performed,
// after which the application supplied entry() routine is called. Any fancy
// actions (such as making decisions based on the reset cause register, and
// resetting the bits in that register) are left solely in the hands of the
// application.
//
//*****************************************************************************
void
ResetISR(void)
{
//
// Jump to the CCS C initialization routine.
//
__asm(" .global _c_int00\n"
" b.w _c_int00");
}
//*****************************************************************************
//
// This is the code that gets called when the processor receives a NMI. This
// simply enters an infinite loop, preserving the system state for examination
// by a debugger.
//
//*****************************************************************************
static void
NmiSR(void)
{
//
// Enter an infinite loop.
//
while(1)
{
}
}
//*****************************************************************************
//
// This is the code that gets called when the processor receives a fault
// interrupt. This simply enters an infinite loop, preserving the system state
// for examination by a debugger.
//
//*****************************************************************************
static void
FaultISR(void)
{
//
// Enter an infinite loop.
//
while(1)
{
}
}
//*****************************************************************************
//
// This is the code that gets called when the processor receives an unexpected
// interrupt. This simply enters an infinite loop, preserving the system state
// for examination by a debugger.
//
//*****************************************************************************
static void
IntDefaultHandler(void)
{
//
// Go into an infinite loop.
//
while(1)
{
}
}
|
the_stack_data/73291.c | extern int GET();
extern long MALLOC(int);
extern void FREE(long);
extern void PRINT(int);
int f(int x) {
return x + 10;
}
int main() {
int a;
int b;
a = 0;
b = f(a);
PRINT(b);
}
|
the_stack_data/72119.c | /*
* @@name: ordered.3c
* @@type: C
* @@compilable: yes
* @@linkable: no
* @@expect: success
*/
void work(int i) {}
void ordered_good(int n)
{
int i;
#pragma omp for ordered
for (i=0; i<n; i++) {
if (i <= 10) {
#pragma omp ordered
work(i);
}
if (i > 10) {
#pragma omp ordered
work(i+1);
}
}
}
|
the_stack_data/176705221.c | #include <stdio.h>
int main(int argc, char const *argv[])
{
int a = 0, i;
for (i = 9; i <= 7;i++)
{
printf("%d", i);
}
printf("%d", i);
} |
the_stack_data/11074696.c | /*
* Copyright (C) 2017-2019 Alibaba Group Holding Limited
*/
#ifdef AOS_COMP_UND
#include "und_log.h"
#include "und_types.h"
#include "und_utils.h"
#include "und_platform.h"
#if defined(__cplusplus) /* If this is a C++ compiler, use C linkage */
extern "C" {
#endif
struct und_sched_ctx_t {
void *mutex;
void *sched;
};
static struct und_sched_ctx_t g_und_sched_ctx = {0};
int und_sched_start(int cycle_ms)
{
struct und_sched_ctx_t *ctx = &g_und_sched_ctx;
UND_PTR_SANITY_CHECK(ctx->mutex, UND_ERR);
undp_mutex_lock(ctx->mutex);
aos_timer_stop(ctx->sched);
aos_timer_start(ctx->sched, cycle_ms);
undp_mutex_unlock(ctx->mutex);
return UND_SUCCESS;
}
int und_sched_deinit()
{
struct und_sched_ctx_t *ctx = &g_und_sched_ctx;
void *mutex = ctx->mutex;
UND_PTR_SANITY_CHECK(ctx->mutex, UND_ERR);
/* clear ctx, then release mutex */
undp_mutex_lock(mutex);
aos_timer_stop(ctx->sched);
aos_timer_delete(ctx->sched);
aos_memset(ctx, 0, sizeof(*ctx));
undp_mutex_unlock(mutex);
undp_mutex_free(mutex);
return UND_SUCCESS;
}
int und_sched_init(void *sched_task)
{
struct und_sched_ctx_t *ctx = &g_und_sched_ctx;
if (ctx->mutex) {
und_debug("und sched ctx is ready inited\n");
return UND_SUCCESS;
}
ctx->mutex = undp_mutex_new();
UND_PTR_SANITY_CHECK(ctx->mutex, UND_MEM_ERR);
undp_mutex_lock(ctx->mutex);
ctx->sched = aos_timer_create("und_sched", (void (*)(void *))sched_task, NULL);
if (ctx->sched == NULL) {
void *mutex = ctx->mutex;
und_err("und alloc sched fail\n");
aos_memset(ctx, 0, sizeof(*ctx));
undp_mutex_unlock(mutex);
undp_mutex_free(mutex);
return UND_MEM_ERR;
}
undp_mutex_unlock(ctx->mutex);
return UND_SUCCESS;
}
#if defined(__cplusplus) /* If this is a C++ compiler, use C linkage */
}
#endif
#endif /* end of AOS_COMP_UND */
|
the_stack_data/104828392.c | #include <stdio.h>
#include <string.h>
#include <ctype.h>
#define COIN_NUM 1000
#define COIN_PATTERNS 6
static const int l[COIN_PATTERNS] = {1, 5, 10, 20, 50, 100};
static int m[COIN_PATTERNS] = {0, 0, 0, 0, 0, 0};
int countyen(int rest, int idx)
{
int i, count = 0;
if (rest > 0) {
for (i = idx; i >= 0; i--) {
if (rest >= l[i]) {
m[i]++;
if (m[i] <= 1000) {
count += countyen(rest - l[i], i);
}
m[i]--;
}
}
return count;
} else {
//printf("%d,%d,%d,%d,%d,%d\n", m[0], m[1], m[2], m[3], m[4], m[5]);
return 1;
}
}
int main(void)
{
int i,l;
char s[80];
for (; ~scanf("%s",s); ) {
l = strlen(s);
for (i = 0; i < l; i++) {
s[i] = toupper(s[i]);
}
}
printf("%d\n", countyen(atoi(s), COIN_PATTERNS - 1));
return 0;
}
|
the_stack_data/92328882.c | #include<stdio.h>
int main()
{
int b[10],i,n,m,c=0,l,u,mid;
printf("enter the size of an array");
scanf("%d",&n);
printf("enter the element in ascending order");
for(i=0;i<n;i++)
{
scanf("%d",&b[i]);
}
printf("enter the number to be searched");
scanf("%d",&m);
l=0;
u=n-1;
while(l<=u)
{
mid=(l+u)/2;
if(m==b[mid])
{
c=1;
break;
}
else if(m<b[mid])
{
u=mid-1;
}
else
{
l=mid+1;
}
}
if(c==0)
{
printf("the number is not found");
}
else
{
printf("the number is found");
return 0;
}
}
|
the_stack_data/22011453.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <CL/cl.h>
unsigned char *read_buffer(char *file_name, size_t *size_ptr)
{
FILE *f;
unsigned char *buf;
size_t size;
/* Open file */
f = fopen(file_name, "rb");
if (!f)
return NULL;
/* Obtain file size */
fseek(f, 0, SEEK_END);
size = ftell(f);
fseek(f, 0, SEEK_SET);
/* Allocate and read buffer */
buf = malloc(size + 1);
fread(buf, 1, size, f);
buf[size] = '\0';
/* Return size of buffer */
if (size_ptr)
*size_ptr = size;
/* Return buffer */
return buf;
}
void write_buffer(char *file_name, const char *buffer, size_t buffer_size)
{
FILE *f;
/* Open file */
f = fopen(file_name, "w+");
/* Write buffer */
if(buffer)
fwrite(buffer, 1, buffer_size, f);
/* Close file */
fclose(f);
}
int main(int argc, char const *argv[])
{
/* Get platform */
cl_platform_id platform;
cl_uint num_platforms;
cl_int ret = clGetPlatformIDs(1, &platform, &num_platforms);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetPlatformIDs' failed\n");
exit(1);
}
printf("Number of platforms: %d\n", num_platforms);
printf("platform=%p\n", platform);
/* Get platform name */
char platform_name[100];
ret = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(platform_name), platform_name, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetPlatformInfo' failed\n");
exit(1);
}
printf("platform.name='%s'\n\n", platform_name);
/* Get device */
cl_device_id device;
cl_uint num_devices;
ret = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, &num_devices);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetDeviceIDs' failed\n");
exit(1);
}
printf("Number of devices: %d\n", num_devices);
printf("device=%p\n", device);
/* Get device name */
char device_name[100];
ret = clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(device_name),
device_name, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetDeviceInfo' failed\n");
exit(1);
}
printf("device.name='%s'\n", device_name);
printf("\n");
/* Create a Context Object */
cl_context context;
context = clCreateContext(NULL, 1, &device, NULL, NULL, &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clCreateContext' failed\n");
exit(1);
}
printf("context=%p\n", context);
/* Create a Command Queue Object*/
cl_command_queue command_queue;
command_queue = clCreateCommandQueue(context, device, 0, &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clCreateCommandQueue' failed\n");
exit(1);
}
printf("command_queue=%p\n", command_queue);
printf("\n");
/* Program source */
unsigned char *source_code;
size_t source_length;
/* Read program from 'bitselect_uchar2uchar2uchar2.cl' */
source_code = read_buffer("bitselect_uchar2uchar2uchar2.cl", &source_length);
/* Create a program */
cl_program program;
program = clCreateProgramWithSource(context, 1, (const char **)&source_code, &source_length, &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clCreateProgramWithSource' failed\n");
exit(1);
}
printf("program=%p\n", program);
/* Build program */
ret = clBuildProgram(program, 1, &device, NULL, NULL, NULL);
if (ret != CL_SUCCESS )
{
size_t size;
char *log;
/* Get log size */
clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,0, NULL, &size);
/* Allocate log and print */
log = malloc(size);
clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,size, log, NULL);
printf("error: call to 'clBuildProgram' failed:\n%s\n", log);
/* Free log and exit */
free(log);
exit(1);
}
printf("program built\n");
printf("\n");
/* Create a Kernel Object */
cl_kernel kernel;
kernel = clCreateKernel(program, "bitselect_uchar2uchar2uchar2", &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clCreateKernel' failed\n");
exit(1);
}
/* Create and allocate host buffers */
size_t num_elem = 10;
/* Create and init host side src buffer 0 */
cl_uchar2 *src_0_host_buffer;
src_0_host_buffer = malloc(num_elem * sizeof(cl_uchar2));
for (int i = 0; i < num_elem; i++)
src_0_host_buffer[i] = (cl_uchar2){{2, 2}};
/* Create and init device side src buffer 0 */
cl_mem src_0_device_buffer;
src_0_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_uchar2), NULL, &ret);
if (ret != CL_SUCCESS)
{
printf("error: could not create source buffer\n");
exit(1);
}
ret = clEnqueueWriteBuffer(command_queue, src_0_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_uchar2), src_0_host_buffer, 0, NULL, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clEnqueueWriteBuffer' failed\n");
exit(1);
}
/* Create and init host side src buffer 1 */
cl_uchar2 *src_1_host_buffer;
src_1_host_buffer = malloc(num_elem * sizeof(cl_uchar2));
for (int i = 0; i < num_elem; i++)
src_1_host_buffer[i] = (cl_uchar2){{2, 2}};
/* Create and init device side src buffer 1 */
cl_mem src_1_device_buffer;
src_1_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_uchar2), NULL, &ret);
if (ret != CL_SUCCESS)
{
printf("error: could not create source buffer\n");
exit(1);
}
ret = clEnqueueWriteBuffer(command_queue, src_1_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_uchar2), src_1_host_buffer, 0, NULL, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clEnqueueWriteBuffer' failed\n");
exit(1);
}
/* Create and init host side src buffer 2 */
cl_uchar2 *src_2_host_buffer;
src_2_host_buffer = malloc(num_elem * sizeof(cl_uchar2));
for (int i = 0; i < num_elem; i++)
src_2_host_buffer[i] = (cl_uchar2){{2, 2}};
/* Create and init device side src buffer 2 */
cl_mem src_2_device_buffer;
src_2_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_uchar2), NULL, &ret);
if (ret != CL_SUCCESS)
{
printf("error: could not create source buffer\n");
exit(1);
}
ret = clEnqueueWriteBuffer(command_queue, src_2_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_uchar2), src_2_host_buffer, 0, NULL, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clEnqueueWriteBuffer' failed\n");
exit(1);
}
/* Create host dst buffer */
cl_uchar2 *dst_host_buffer;
dst_host_buffer = malloc(num_elem * sizeof(cl_uchar2));
memset((void *)dst_host_buffer, 1, num_elem * sizeof(cl_uchar2));
/* Create device dst buffer */
cl_mem dst_device_buffer;
dst_device_buffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY, num_elem *sizeof(cl_uchar2), NULL, &ret);
if (ret != CL_SUCCESS)
{
printf("error: could not create dst buffer\n");
exit(1);
}
/* Set kernel arguments */
ret = CL_SUCCESS;
ret |= clSetKernelArg(kernel, 0, sizeof(cl_mem), &src_0_device_buffer);
ret |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &src_1_device_buffer);
ret |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &src_2_device_buffer);
ret |= clSetKernelArg(kernel, 3, sizeof(cl_mem), &dst_device_buffer);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clSetKernelArg' failed\n");
exit(1);
}
/* Launch the kernel */
size_t global_work_size = num_elem;
size_t local_work_size = num_elem;
ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clEnqueueNDRangeKernel' failed\n");
exit(1);
}
/* Wait for it to finish */
clFinish(command_queue);
/* Read results from GPU */
ret = clEnqueueReadBuffer(command_queue, dst_device_buffer, CL_TRUE,0, num_elem * sizeof(cl_uchar2), dst_host_buffer, 0, NULL, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clEnqueueReadBuffer' failed\n");
exit(1);
}
/* Dump dst buffer to file */
char dump_file[100];
sprintf((char *)&dump_file, "%s.result", argv[0]);
write_buffer(dump_file, (const char *)dst_host_buffer, num_elem * sizeof(cl_uchar2));
printf("Result dumped to %s\n", dump_file);
/* Free host dst buffer */
free(dst_host_buffer);
/* Free device dst buffer */
ret = clReleaseMemObject(dst_device_buffer);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseMemObject' failed\n");
exit(1);
}
/* Free host side src buffer 0 */
free(src_0_host_buffer);
/* Free device side src buffer 0 */
ret = clReleaseMemObject(src_0_device_buffer);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseMemObject' failed\n");
exit(1);
}
/* Free host side src buffer 1 */
free(src_1_host_buffer);
/* Free device side src buffer 1 */
ret = clReleaseMemObject(src_1_device_buffer);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseMemObject' failed\n");
exit(1);
}
/* Free host side src buffer 2 */
free(src_2_host_buffer);
/* Free device side src buffer 2 */
ret = clReleaseMemObject(src_2_device_buffer);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseMemObject' failed\n");
exit(1);
}
/* Release kernel */
ret = clReleaseKernel(kernel);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseKernel' failed\n");
exit(1);
}
/* Release program */
ret = clReleaseProgram(program);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseProgram' failed\n");
exit(1);
}
/* Release command queue */
ret = clReleaseCommandQueue(command_queue);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseCommandQueue' failed\n");
exit(1);
}
/* Release context */
ret = clReleaseContext(context);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseContext' failed\n");
exit(1);
}
return 0;
} |
the_stack_data/782454.c | /*
* Copyright 2014 The Emscripten Authors. All rights reserved.
* Emscripten is available under two separate licenses, the MIT license and the
* University of Illinois/NCSA Open Source License. Both these licenses can be
* found in the LICENSE file.
*/
#include <stdio.h>
#include <stdarg.h>
typedef struct {
int x;
int y;
} coords;
typedef struct {
int r;
int g;
int b;
} color;
void fun(int a, ...) {
(void)a;
va_list ap;
va_start(ap, a);
coords var1 = va_arg(ap, coords);
color var2 = va_arg(ap, color);
printf("va_arg coords: %d and %d\n", var1.x, var1.y);
printf("va_arg color: %d, %d, %d\n", var2.r, var2.g, var2.b);
va_end(ap);
}
int main(void) {
coords val1 = { .x = 42, .y = 21 };
color val2 = { .r = 37, .g = 19, .b = 253 };
fun(0, val1, val2);
return 0;
}
|
the_stack_data/15762071.c | #include <stdio.h>
#include <string.h>
#define MAXSIZE 5000005
unsigned long long Base = 29, base[MAXSIZE], hash[MAXSIZE];
void init(){
base[0] = 1ULL;
for(int i =1;i<MAXSIZE;i++){
base[i] = base[i-1] * Base;
}
}
void computeHash(char *str,int length){
hash[0] = 0;
for(int i = 0;i<length;i++){
hash[i+1] = hash[i]*Base + str[i]-'a'+1;
}
}
int okay(int length,int len,int p){
unsigned long long first = hash[length];
unsigned long long second = hash[p+length-1]-hash[p-1]*base[length];
return (first==second);
}
int min(int x,int y){
return (x<y)?x:y;
}
void Main(){
init();
char str[MAXSIZE];
scanf("%s",str);
int len = strlen(str);
computeHash(str, len);
int q; scanf("%d",&q);
while (q--)
{
int p;scanf("%d",&p);
p++;
int l = 1, r = min(p-1, len-p+1), Answer = 0;
while(l<=r){
int m = (l+r)>>1;
if(okay(m,len,p)){
Answer = m;
l = m+1;
}
else r = m-1;
}
printf("%d\n",Answer);
}
return;
}
int main(){
Main();
return 0;
} |
the_stack_data/198581916.c | #include <stdio.h>
#include <string.h>
int capicua(char *str)
{
char *head = str;
char *tail = str + strlen(str) - 1;
int isPalindrome = 1;
while(head < tail)
{
if(*head != *tail)
{
isPalindrome = 0;
break;
}
++head;
--tail;
}
return isPalindrome;
}
int main()
{
for(;;)
{
char buffer[256] = {0};
printf("Palavra? ");
if(scanf("%255s", buffer) != 1)
{
break;
}
if(capicua(buffer))
{
printf("%s é capicua\n", buffer);
}
else
{
printf("%s não é capicua\n", buffer);
}
}
return 0;
}
|
the_stack_data/225143594.c | /**
* @file chararr_outbnds.c
* @brief out of the "bounds" for char arrays
* @ref https://github.com/zedshaw/learn-c-the-hard-way-lectures/blob/master/ex13/ex13.c
* @details C treats strings as just arrays of bytes,
* string and array of bytes are the same thing
*
* gcc -Wall -g chararr_outbnds.c
* ./chararr_outbnds
* */
#include <stdio.h> // you don't even have to include it; it's noted by compiler
int main(int argc, char *argv[]) {
char* arr_states[] = {
"123", "124", "125", "126" };
int num_of_states = 6; // 6 will guarantee Segmentation Fault, outside of the End of Strings \00
int i=0;
// this for-loop exits normally
for (i=0; i<num_of_states;i++){
arr_states[i]; // it'll exit normally for num_of_states = 5,6
}
/* =============== Segmentation Fault =============== */
/* =============== this for-loop DOES NOT exit normally =============== */
for (i=0; i<num_of_states;i++){
printf("state %d %s \n",
i,
arr_states[i]); // it'll NOT exit normally for num_of_states = 5,6; segmentation fault
}
}
|
the_stack_data/92327894.c | //Program to create a simple pong file with the new file format
#include <stdio.h>
#include <stdint.h>
int main(int argc, char *argv[])
{
if(argc < 2 || argc > 2){
printf("usage: %s file\n", argv[0]);
return -1;
}
FILE *fp = fopen(argv[1], "w");
if(fp == NULL){
printf("Error opening file \"%s\"!\n", argv[1]);
return -1;
}
int delay=200, frames=600, leds=300, count, direction, tmp, pong = 0;
char r = 255, g = 255, b = 255;
fwrite(&frames, 4, 1, fp);
fwrite(&delay, 4, 1, fp);
fwrite(&leds, 4, 1, fp);
for(count = 0; count < frames; count++){
if(pong == leds-1)
if(direction == 0)
direction = 1;
else
direction = 0;
for(tmp = 0; tmp < leds; tmp++)
if(pong == tmp){
fputc(r, fp);
fputc(b, fp);
fputc(g, fp);
}else{
fputc(0, fp);
fputc(0, fp);
fputc(0, fp);
}
if(direction == 1)
pong++;
else
pong--;
}
fclose(fp);
return 0;
}
|
the_stack_data/62043.c | /*此程序计算第200个三角数
介绍for语句 */
#include <stdio.h>
int main(void)
{
int n, triangularNumber;
triangularNumber = 0;
for(n = 1; n <= 200; n = n + 1)
triangularNumber = triangularNumber + n;
printf("The 200th triangular number is %i\n",
triangularNumber);
return 0;
} |
the_stack_data/45705.c | int mx_strcmp(const char *s1, const char *s2);
int mx_strlen(const char *s);
int mx_selection_sort(char **arr, int size);
int mx_selection_sort(char **arr, int size){
int ops = 0;
for(int i = 0; i < size - 1; i++){
int m = i;
for(int j = i + 1; j < size; j++)
if(mx_strlen(arr[j]) < mx_strlen(arr[m]) || (mx_strlen(arr[j]) == mx_strlen(arr[m]) && mx_strcmp(arr[j], arr[m]) < 0))
m = j;
if(mx_strlen(arr[i]) > mx_strlen(arr[m]) || (mx_strlen(arr[i]) == mx_strlen(arr[m]) && mx_strcmp(arr[i], arr[m]) > 0)){
char *t = arr[i];
arr[i] = arr[m];
arr[m] = t;
ops++;
}
}
return ops;
}
|
the_stack_data/104827384.c | /*
* @Author: HuangYuhui
* @Date: 2019-01-19 21:46:09
* @Last Modified by: HuangYuhui
* @Last Modified time: 2019-01-27 18:26:45
*/
/*
* (づ ̄3 ̄)づ╭❤~
*
* 编写函数'fun',该函数的功能:统计一行字符串中单词的个数.
* 作为函数值返回,字符串在主函数中输入,规定所有单词由小写
* 字母组成,单词之间有若干个空格隔开,第一行的开始没有空格.
*/
#include <string.h>
#include <stdio.h>
#define N 100
/*
* Declare the method.
*/
static int fun(char *c);
/*
* Test the program.
*/
int main(int argc, char const *argv[])
{
char filename[] = "The basic part/Examination paper 01/Exam_3.dat";
FILE *file_pointer;
char line[N];
int num = 0;
printf("Please enter a string : \n");
gets(line);
num = fun(line);
printf("The number of world is : %d", num);
file_pointer = fopen(filename, "w");
/**
* todo : int fprintf (FILE* stream, const char*format, [argument]);
*/
fprintf(file_pointer, "%d", fun("Hi The lanuage of C !"));
fclose(file_pointer);
getchar();
return 0;
}
/**
* todo : Initialize the method of fun.
*/
static int fun(char *c)
{
int i, j = 0;
for (i = 0; c[i] != '\0'; i++)
{
//? warning: suggest parentheses around '&&' within '||' .
if ((c[i] != ' ') && (c[i + 1] == ' ' || c[i + 1] == '\0'))
{
j++;
}
}
return j;
}
|
the_stack_data/1212900.c | /* --- File integrate_sin_omp.c --- */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <omp.h>
int main(int argc, char **argv) {
struct timespec ts_start, ts_end;
float time_total;
int steps = 1e7;
double delta = M_PI/steps;
double total = 0.0;
int i;
printf("Using %.0e steps\n", (float)steps);
/* Get start time */
clock_gettime(CLOCK_MONOTONIC, &ts_start);
#pragma omp parallel for
for (i=0; i<steps; i++) {
/* pragma omp critical */
total += sin(delta*i) * delta;
}
/* Get end time */
clock_gettime(CLOCK_MONOTONIC, &ts_end);
time_total = (ts_end.tv_sec - ts_start.tv_sec)*1e9 + \
(ts_end.tv_nsec - ts_start.tv_nsec);
printf("Total time is %f ms\n", time_total/1e6);
printf("The integral of sine from 0 to Pi is %.12f\n", total);
}
|
the_stack_data/82505.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_str_is_printable.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lteresia <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/09/04 01:56:39 by lteresia #+# #+# */
/* Updated: 2021/09/04 02:00:26 by lteresia ### ########.fr */
/* */
/* ************************************************************************** */
int ft_str_is_printable(char *str)
{
int i;
i = 0;
while (str[i] != '\0')
{
if (str[i] < 32 || str[i] > 126)
return (0);
i++;
}
return (1);
}
|
the_stack_data/122016507.c | void test(int *a) {
for (int j = 0; j < 10; ++j) {
int b[2];
for (int i = 0; i < 2; ++i) {
b[i] = i;
}
a[0] = b[0];
}
}
//CHECK: Printing analysis 'Dependency Analysis (Metadata)' for function 'test':
//CHECK: loop at depth 1 private_array_8.c:2:5
//CHECK: private:
//CHECK: <b:3:13, 8> | <i:4[4:9], 4>
//CHECK: output:
//CHECK: <*a:{7:9|1:16}, ?> <a[0]:1, 4>
//CHECK: anti:
//CHECK: <*a:{7:9|1:16}, ?> <a[0]:1, 4>
//CHECK: flow:
//CHECK: <*a:{7:9|1:16}, ?> <a[0]:1, 4>
//CHECK: induction:
//CHECK: <j:2[2:5], 4>:[Int,0,10,1]
//CHECK: read only:
//CHECK: <a:1, 8>
//CHECK: redundant:
//CHECK: <*a:{7:9|1:16}, ?> <a[0]:1, 4>
//CHECK: lock:
//CHECK: <j:2[2:5], 4>
//CHECK: header access:
//CHECK: <j:2[2:5], 4>
//CHECK: explicit access:
//CHECK: <a:1, 8> | <i:4[4:9], 4> | <j:2[2:5], 4>
//CHECK: explicit access (separate):
//CHECK: <a:1, 8> <a[0]:1, 4> <i:4[4:9], 4> <j:2[2:5], 4>
//CHECK: redundant (separate):
//CHECK: <*a:{7:9|1:16}, ?>
//CHECK: lock (separate):
//CHECK: <j:2[2:5], 4>
//CHECK: direct access (separate):
//CHECK: <*a:{7:9|1:16}, ?> <a:1, 8> <a[0]:1, 4> <b:3:13, 8> <i:4[4:9], 4> <j:2[2:5], 4>
//CHECK: loop at depth 2 private_array_8.c:4:9
//CHECK: shared:
//CHECK: <b:3:13, 8>
//CHECK: first private:
//CHECK: <b:3:13, 8>
//CHECK: dynamic private:
//CHECK: <b:3:13, 8>
//CHECK: induction:
//CHECK: <i:4[4:9], 4>:[Int,0,2,1]
//CHECK: lock:
//CHECK: <i:4[4:9], 4>
//CHECK: header access:
//CHECK: <i:4[4:9], 4>
//CHECK: explicit access:
//CHECK: <i:4[4:9], 4>
//CHECK: explicit access (separate):
//CHECK: <i:4[4:9], 4>
//CHECK: lock (separate):
//CHECK: <i:4[4:9], 4>
//CHECK: direct access (separate):
//CHECK: <b:3:13, 8> <i:4[4:9], 4>
|
the_stack_data/115765125.c | /* -------------------------------------------------------------------------
@file count_characteres.c
@date 04/29/17 10:37:45
@author Martin Noblia
@email [email protected]
@brief
Count characters in a text stream
@detail
NOTE: for count the characters of a text file do:
less text.txt | ./count_characters
Licence:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 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 General Public License
---------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
long number_of_chars = 0;
while (getchar() != EOF) {
++number_of_chars;
}
printf("The number of characters in the text stream is: %ld", number_of_chars);
return 0;
}
|
the_stack_data/70450366.c | /**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/**
* Benchmark Cephes `sici`.
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <sys/time.h>
#define NAME "sici"
#define ITERATIONS 1000000
#define REPEATS 3
/**
* Define prototypes for external functions.
*/
extern int sici( double x, double *si, double *ci );
/**
* Prints the TAP version.
*/
void print_version() {
printf( "TAP version 13\n" );
}
/**
* Prints the TAP summary.
*
* @param total total number of tests
* @param passing total number of passing tests
*/
void print_summary( int total, int passing ) {
printf( "#\n" );
printf( "1..%d\n", total ); // TAP plan
printf( "# total %d\n", total );
printf( "# pass %d\n", passing );
printf( "#\n" );
printf( "# ok\n" );
}
/**
* Prints benchmarks results.
*
* @param elapsed elapsed time in seconds
*/
void print_results( double elapsed ) {
double rate = (double)ITERATIONS / elapsed;
printf( " ---\n" );
printf( " iterations: %d\n", ITERATIONS );
printf( " elapsed: %0.9f\n", elapsed );
printf( " rate: %0.9f\n", rate );
printf( " ...\n" );
}
/**
* Returns a clock time.
*
* @return clock time
*/
double tic() {
struct timeval now;
gettimeofday( &now, NULL );
return (double)now.tv_sec + (double)now.tv_usec/1.0e6;
}
/**
* Generates a random double on the interval [0,1].
*
* @return random double
*/
double rand_double() {
int r = rand();
return (double)r / ( (double)RAND_MAX + 1.0 );
}
/**
* Runs a benchmark.
*
* @return elapsed time in seconds
*/
double benchmark() {
double elapsed;
double x;
double y;
double z;
double t;
int i;
t = tic();
for ( i = 0; i < ITERATIONS; i++ ) {
x = ( 100.0*rand_double() ) - 50.0;
sici( x, &y, &z );
if ( y != y || z != z ) {
printf( "should not return NaN\n" );
break;
}
}
elapsed = tic() - t;
if ( y != y || z != z ) {
printf( "should not return NaN\n" );
}
return elapsed;
}
/**
* Main execution sequence.
*/
int main( void ) {
double elapsed;
int i;
// Use the current time to seed the random number generator:
srand( time( NULL ) );
print_version();
for ( i = 0; i < REPEATS; i++ ) {
printf( "# c::cephes::%s\n", NAME );
elapsed = benchmark();
print_results( elapsed );
printf( "ok %d benchmark finished\n", i+1 );
}
print_summary( REPEATS, REPEATS );
}
|
the_stack_data/57950661.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gasantos <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/02/10 19:54:24 by gasantos #+# #+# */
/* Updated: 2022/02/10 19:54:25 by gasantos ### ########.fr */
/* */
/* ************************************************************************** */
void ft_print_comb2(void);
int main(void)
{
ft_print_comb2();
}
|
the_stack_data/54824099.c | /*
* Produce a "generalized CRC" table. Assumes a platform with
* /dev/urandom -- otherwise reimplement get_random_byte().
*/
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
static uint8_t get_random_byte(void)
{
static int fd = -1;
uint8_t buf;
int rv;
if (fd < 0)
fd = open("/dev/urandom", O_RDONLY);
do {
errno = 0;
rv = read(fd, &buf, 1);
if (rv < 1 && errno != EAGAIN)
abort();
} while (rv < 1);
return buf;
}
static void random_permute(uint8_t *buf)
{
int i, j, k;
int m;
for (i = 0; i < 256; i++)
buf[i] = i;
m = 255;
for (i = 255; i > 0; i--) {
if (i <= (m >> 1))
m >>= 1;
do {
j = get_random_byte() & m;
} while (j > i);
k = buf[i];
buf[i] = buf[j];
buf[j] = k;
}
}
static void xcrc_table(uint64_t *buf)
{
uint8_t perm[256];
int i, j;
memset(buf, 0, 8*256); /* Make static checkers happy */
for (i = 0; i < 8; i++) {
random_permute(perm);
for (j = 0; j < 256; j++)
buf[j] = (buf[j] << 8) | perm[j];
}
}
int main(void)
{
int i;
uint64_t buf[256];
xcrc_table(buf);
for (i = 0; i < 256; i++) {
printf("%016"PRIx64"\n", buf[i]);
}
return 0;
}
|
the_stack_data/12638179.c | // Write a C program to find the length of a string using pointer
#include<stdio.h>
int str_len(char *str) // str=&c[0]
{
int len;
for(len=0;*str!='\0';len++,str++);
return len;
}
int main()
{
char c[50];
printf("Enter a string\n");
gets(c);
printf("Length of given string is %d",str_len(c));
}
/*Output:
Enter a string
Peaceful life
Length of given string is 13*/ |
the_stack_data/153070.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strlen.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jwinthei <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/10/26 14:35:02 by jwinthei #+# #+# */
/* Updated: 2018/11/21 17:23:21 by jwinthei ### ########.fr */
/* */
/* ************************************************************************** */
#include <string.h>
size_t ft_strlen(const char *src)
{
size_t i;
i = 0;
while (src[i])
i++;
return (i);
}
|
the_stack_data/89200906.c | #include <math.h>
struct T
{
int a;
int b;
};
float foo()
{
struct T xx[2] = {[0].a = 0, [0].b = 0, [1].a = 1, [1].b = 1};
int t1 = (xx[0].a - xx[1].b);
int t2 = (xx[0].b - xx[1].b);
return sqrt(t1*t1 + t2 * t2);
}
|
the_stack_data/34513870.c | // Copyright 2013 Google Inc. 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.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <pthread.h>
#define MAX_STRING 100
#define EXP_TABLE_SIZE 512
#define MAX_EXP 6
#define MAX_SENTENCE_LENGTH 1000
#define MAX_CODE_LENGTH 40
const int vocab_hash_size = 33554432; // Maximum 33.5M * 0.7 = ~23M words in the vocabulary
typedef float real; // Precision of float numbers
#define MAX_SHORT_WORD 24
struct __attribute__((packed)) vocab_word {
union __attribute__((packed)) {
char *word;
char shortword[MAX_SHORT_WORD];
} w;
long long count;
};
const long long SHORT_WORD = ((long long)1 << 62);
const long long max_count = (((long long)1 << 62) - 1);
struct vocab_word *vocab;
inline char * GetWordPtr(struct vocab_word *word)
{
return (word->count & SHORT_WORD) ? word->w.shortword : word->w.word;
}
inline char * GetWordPtrI(int index)
{
return GetWordPtr(&vocab[index]);
}
inline long long GetWordUsage(const void *w)
{
return ((struct vocab_word *)w)->count & max_count;
}
inline long long GetWordUsageI(const int i)
{
return vocab[i].count & max_count;
}
inline int ReadWordIndex(FILE *fin);
struct vocab_code {
char codelen;
int point[MAX_CODE_LENGTH];
char code[MAX_CODE_LENGTH];
};
char train_file[MAX_STRING], output_file[MAX_STRING];
char save_vocab_file[MAX_STRING], read_vocab_file[MAX_STRING];
struct vocab_word *vocab;
struct vocab_code *vocab_codes;
int binary = 0, cbow = 1, debug_mode = 2, window = 5, min_count = 5, num_threads = 12, min_reduce = 1;
int *vocab_hash;
long long vocab_max_size = 1000, vocab_size = 0;
// Making layer1_size const might drastically decrease # of instructions issued...
//#define CONST_LAYER1 256
#ifdef CONST_LAYER1
const long long layer1_size = CONST_LAYER1;
#else
long long layer1_size = 256;
#endif
long long train_words = 0, word_count_actual = 0, iter = 5, file_size = 0, classes = 0;
real alpha = 0.025, starting_alpha, sample = 1e-3;
real *syn0, *syn1, *syn1neg, *expTable;
clock_t start;
int hs = 0, negative = 5;
//const int table_size = 1e8;
const int table_size = 134217728; // 2^27
int *table;
void InitUnigramTable() {
int a, i;
double train_words_pow = 0;
double d1, power = 0.75;
printf("table size %d\n", table_size);
table = (int *)malloc(table_size * sizeof(int));
for (a = 0; a < vocab_size; a++) train_words_pow += pow(GetWordUsageI(a), power);
i = 0;
d1 = pow(GetWordUsageI(i), power) / train_words_pow;
for (a = 0; a < table_size; a++) {
table[a] = i;
if (a / (double)table_size > d1) {
i++;
d1 += pow(GetWordUsageI(i), power) / train_words_pow;
}
if (i >= vocab_size) i = vocab_size - 1;
}
}
// Reads a single word from a file, assuming space + tab + EOL to be word boundaries
void ReadWord(char *word, FILE *fin) {
int a = 0, ch;
while (!feof(fin)) {
ch = fgetc(fin);
if (ch == 13) continue;
if ((ch == ' ') || (ch == '\t') || (ch == '\n')) {
if (a > 0) {
if (ch == '\n') ungetc(ch, fin);
break;
}
if (ch == '\n') {
strcpy(word, (char *)"</s>");
return;
} else continue;
}
word[a] = ch;
a++;
if (a >= MAX_STRING - 1) a--; // Truncate too long words
}
word[a] = 0;
}
// Returns hash value of a word
inline int GetWordHash(char *word) {
unsigned long long a, hash = 0;
for (a = 0; a < strlen(word); a++) hash = hash * 257 + word[a];
hash = hash % vocab_hash_size;
return hash;
}
// Returns position of a word in the vocabulary; if the word is not found, returns -1
inline int SearchVocab(char *word) {
unsigned int hash = GetWordHash(word);
while (1) {
if (vocab_hash[hash] == -1) return -1;
if (!strcmp(word, GetWordPtrI(vocab_hash[hash]))) return vocab_hash[hash];
hash = (hash + 1) % vocab_hash_size;
}
return -1;
}
// Reads a word and returns its index in the vocabulary
int ReadWordIndex(FILE *fin) {
char word[MAX_STRING];
ReadWord(word, fin);
if (feof(fin)) return -1;
return SearchVocab(word);
}
// Adds a word to the vocabulary
int AddWordToVocab(char *word) {
unsigned int hash, length = strlen(word) + 1;
char *word_addr = NULL;
if (length < (MAX_SHORT_WORD - 1)) {
vocab[vocab_size].count = 1 | SHORT_WORD;
word_addr = vocab[vocab_size].w.shortword;
// printf("short word %d %s\n", vocab_size, word);
} else {
if (length > MAX_STRING) length = MAX_STRING;
vocab[vocab_size].count = 1;
vocab[vocab_size].w.word = (char *)calloc(length, sizeof(char));
word_addr = vocab[vocab_size].w.word;
// printf("long word %d %s\n", vocab_size, word);
}
strncpy(word_addr, word, length);
word_addr[length - 1] = 0;
// Reallocate memory if needed
if (vocab_size + 3 >= vocab_max_size) {
vocab_max_size += 1024;
vocab = (struct vocab_word *)realloc(vocab, vocab_max_size * sizeof(struct vocab_word));
}
// Find an empty hash spot.
hash = GetWordHash(word);
while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size;
vocab_hash[hash]=vocab_size;
return vocab_size++; // post-increment, won't actually go up until return value taken
}
// Used later for sorting by word counts
int VocabCompare(const void *a, const void *b) {
return GetWordUsage(b) - GetWordUsage(a);
}
// Sorts the vocabulary by frequency using word counts
void SortVocab() {
int a, size;
unsigned int hash;
// Sort the vocabulary and keep </s> at the first position
qsort(&vocab[1], vocab_size - 1, sizeof(struct vocab_word), VocabCompare);
for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1;
size = vocab_size;
train_words = 0;
for (a = 0; a < size; a++) {
// Words occuring less than min_count times will be discarded from the vocab
if ((GetWordUsageI(a) < min_count) && (a != 0)) {
vocab_size--;
if (!(vocab[a].count & SHORT_WORD)) free(vocab[a].w.word);
} else {
// Hash will be re-computed, as after the sorting it is not actual
hash=GetWordHash(GetWordPtrI(a));
while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size;
vocab_hash[hash] = a;
train_words += GetWordUsageI(a);
}
}
vocab = (struct vocab_word *)realloc(vocab, (vocab_size + 1) * sizeof(struct vocab_word));
// Allocate memory for the binary tree construction
vocab_codes = (struct vocab_code *)calloc(vocab_size + 1, sizeof(struct vocab_code));
}
// Reduces the vocabulary by removing infrequent tokens
void ReduceVocab() {
int a, b = 0;
unsigned int hash;
for (a = 0; a < vocab_size; a++) if (GetWordUsageI(a) > min_reduce) {
memmove(&vocab[b], &vocab[a], sizeof(struct vocab_word));
b++;
} else {
free(vocab[a].w.word);
}
vocab_size = b;
for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1;
for (a = 0; a < vocab_size; a++) {
// Hash will be re-computed, as it is not actual
hash = GetWordHash(GetWordPtrI(a));
while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size;
vocab_hash[hash] = a;
}
fflush(stdout);
min_reduce++;
}
// Create binary Huffman tree using the word counts
// Frequent words will have short uniqe binary codes
void CreateBinaryTree() {
long long a, b, i, min1i, min2i, pos1, pos2, point[MAX_CODE_LENGTH];
char code[MAX_CODE_LENGTH];
long long *count = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long));
long long *binary = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long));
long long *parent_node = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long));
for (a = 0; a < vocab_size; a++) count[a] = GetWordUsageI(a);
for (a = vocab_size; a < vocab_size * 2; a++) count[a] = 1e15;
pos1 = vocab_size - 1;
pos2 = vocab_size;
// Following algorithm constructs the Huffman tree by adding one node at a time
for (a = 0; a < vocab_size - 1; a++) {
// First, find two smallest nodes 'min1, min2'
if (pos1 >= 0) {
if (count[pos1] < count[pos2]) {
min1i = pos1;
pos1--;
} else {
min1i = pos2;
pos2++;
}
} else {
min1i = pos2;
pos2++;
}
if (pos1 >= 0) {
if (count[pos1] < count[pos2]) {
min2i = pos1;
pos1--;
} else {
min2i = pos2;
pos2++;
}
} else {
min2i = pos2;
pos2++;
}
count[vocab_size + a] = count[min1i] + count[min2i];
parent_node[min1i] = vocab_size + a;
parent_node[min2i] = vocab_size + a;
binary[min2i] = 1;
}
// Now assign binary code to each vocabulary word
for (a = 0; a < vocab_size; a++) {
b = a;
i = 0;
while (1) {
code[i] = binary[b];
point[i] = b;
i++;
b = parent_node[b];
if (b == vocab_size * 2 - 2) break;
}
vocab_codes[a].codelen = i;
vocab_codes[a].point[0] = vocab_size - 2;
for (b = 0; b < i; b++) {
vocab_codes[a].code[i - b - 1] = code[b];
vocab_codes[a].point[i - b] = point[b] - vocab_size;
}
}
free(count);
free(binary);
free(parent_node);
}
void LearnVocabFromTrainFile() {
char word[MAX_STRING];
FILE *fin;
long long a, i;
for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1;
fin = fopen(train_file, "rb");
if (fin == NULL) {
printf("ERROR: training data file not found!\n");
exit(1);
}
vocab_size = 0;
AddWordToVocab((char *)"</s>");
while (1) {
ReadWord(word, fin);
if (feof(fin)) break;
train_words++;
if ((debug_mode > 1) && (train_words % 100000 == 0)) {
printf("%lldK%c", train_words / 1000, 13);
fflush(stdout);
}
i = SearchVocab(word);
if (i == -1) {
a = AddWordToVocab(word);
} else vocab[i].count++;
if (vocab_size > vocab_hash_size * 0.7) ReduceVocab();
}
SortVocab();
if (debug_mode > 0) {
printf("Vocab size: %lld\n", vocab_size);
printf("Words in train file: %lld\n", train_words);
}
file_size = ftell(fin);
fclose(fin);
}
void SaveVocab() {
long long i;
FILE *fo = fopen(save_vocab_file, "wb");
for (i = 0; i < vocab_size; i++) fprintf(fo, "%s %lld\n", GetWordPtrI(i), GetWordUsageI(i));
fclose(fo);
}
inline real DoMAC(const int n, real * __restrict__ a, real * __restrict__ b)
{
real output = 0;
int i = 0;
if ((!((unsigned long)a & 0x3f)) && (!((unsigned long)b & 0x3f))) {
real *aa = __builtin_assume_aligned(a, 64), *ba = __builtin_assume_aligned(b, 64);
for (i = 0; i < n; i++) output += aa[i] * ba[i];
} else if ((!((unsigned long)a & 0x1f)) && (!((unsigned long)b & 0x1f))) {
real *aa = __builtin_assume_aligned(a, 32), *ba = __builtin_assume_aligned(b, 32);
for (i = 0; i < n; i++) output += aa[i] * ba[i];
} else if ((!((unsigned long)a & 0x0f)) && (!((unsigned long)b & 0x0f))) {
real *aa = __builtin_assume_aligned(a, 16), *ba = __builtin_assume_aligned(b, 16);
for (i = 0; i < n; i++) output += aa[i] * ba[i];
} else {
for (i = 0; i < n; i++) {
output += a[i] * b[i];
}
}
return output;
}
inline void DoAdd(const int n, real * __restrict__ a, real * __restrict__ b)
{
int i = 0;
if ((!((unsigned long)a & 0x3f)) && (!((unsigned long)b & 0x3f))) {
real *aa = __builtin_assume_aligned(a, 64), *ba = __builtin_assume_aligned(b, 64);
for (i = 0; i < n; i++) aa[i] += ba[i];
} else if ((!((unsigned long)a & 0x1f)) && (!((unsigned long)b & 0x1f))) {
real *aa = __builtin_assume_aligned(a, 32), *ba = __builtin_assume_aligned(b, 32);
for (i = 0; i < n; i++) aa[i] += ba[i];
} else if ((!((unsigned long)a & 0x0f)) && (!((unsigned long)b & 0x0f))) {
real *aa = __builtin_assume_aligned(a, 16), *ba = __builtin_assume_aligned(b, 16);
for (i = 0; i < n; i++) aa[i] += ba[i];
} else {
for (i = 0; i < n; i++) a[i] += b[i];
}
}
void DoMAC1(const int n, real * __restrict__ out, real c, real * __restrict__ b)
{
int i = 0;
// On Sandy Bridge w/hyperthreading, alignment > 16 may or may not cause pipeline stalls, slowing down perf.
// Seems to be an icache issue
/* if ((!((unsigned long)out & 0x3f)) && (!((unsigned long)b & 0x3f))) {
real *outa = __builtin_assume_aligned(out, 64), *ba = __builtin_assume_aligned(b, 64);
for (i = 0; i < n; i++) outa[i] += c * ba[i];
} else */ if ((!((unsigned long)out & 0x1f)) && (!((unsigned long)b & 0x1f))) {
real *outa = __builtin_assume_aligned(out, 32), *ba = __builtin_assume_aligned(b, 32);
for (i = 0; i < n; i++) outa[i] += c * ba[i];
} else if ((!((unsigned long)out & 0x0f)) && (!((unsigned long)b & 0x0f))) {
real *outa = __builtin_assume_aligned(out, 16), *ba = __builtin_assume_aligned(b, 16);
for (i = 0; i < n; i++) outa[i] += c * ba[i];
} else {
for (i = 0; i < n; i++) out[i] += c * b[i];
}
}
void ReadVocab() {
long long a, i = 0;
long long cn;
char c;
char word[MAX_STRING];
FILE *fin = fopen(read_vocab_file, "rb");
if (fin == NULL) {
printf("Vocabulary file not found\n");
exit(1);
}
for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1;
vocab_size = 0;
while (1) {
ReadWord(word, fin);
if (feof(fin)) break;
a = AddWordToVocab(word);
fscanf(fin, "%lld%c", &cn, &c);
vocab[a].count = (vocab[a].count & SHORT_WORD) | cn;
i++;
}
SortVocab();
if (debug_mode > 0) {
printf("Vocab size: %lld\n", vocab_size);
printf("Words in train file: %lld\n", train_words);
}
fin = fopen(train_file, "rb");
if (fin == NULL) {
printf("ERROR: training data file not found!\n");
exit(1);
}
fseek(fin, 0, SEEK_END);
file_size = ftell(fin);
fclose(fin);
}
void InitNet() {
long long a, b;
unsigned long long next_random = 1;
a = posix_memalign((void **)&syn0, 128, (long long)vocab_size * layer1_size * sizeof(real));
if (syn0 == NULL) {printf("Memory allocation failed\n"); exit(1);}
if (hs) {
a = posix_memalign((void **)&syn1, 128, (long long)vocab_size * layer1_size * sizeof(real));
if (syn1 == NULL) {printf("Memory allocation failed\n"); exit(1);}
memset(syn1, 0, (long long)vocab_size * layer1_size * sizeof(real));
}
if (negative>0) {
a = posix_memalign((void **)&syn1neg, 128, (long long)vocab_size * layer1_size * sizeof(real));
if (syn1neg == NULL) {printf("Memory allocation failed\n"); exit(1);}
memset(syn1neg, 0, (long long)vocab_size * layer1_size * sizeof(real));
}
for (a = 0; a < vocab_size; a++) for (b = 0; b < layer1_size; b++) {
next_random = (next_random + 11) * (unsigned long long)25214903917;
syn0[a * layer1_size + b] = (((next_random & 0xFFFF) / (real)65536) - 0.5) / layer1_size;
}
CreateBinaryTree();
}
const real EXP_SCALE = (real)EXP_TABLE_SIZE / (real)MAX_EXP;
inline real getExp(real r)
{
real rabs = fabs(r), rv = 0.5;
if (rabs < MAX_EXP) {
rv = expTable[(int)(rabs * EXP_SCALE)];
}
rv = (r > 0) ? (0.5 + rv) : (0.5 - rv);
return rv;
}
void *TrainModelThread(void *id) {
long long a, b, d, cw, word, last_word, sentence_length = 0, sentence_position = 0;
long long word_count = 0, last_word_count = 0, sen[MAX_SENTENCE_LENGTH + 1];
long long l1, l2, c, target, label, local_iter = iter;
unsigned long long next_random = (long long)id;
real f, g;
clock_t now;
real *neu1;
a = posix_memalign((void **)&neu1, 128, layer1_size * sizeof(real));
real *neu1e; // = (real *)calloc(layer1_size, sizeof(real));
a = posix_memalign((void **)&neu1e, 128, layer1_size * sizeof(real));
FILE *fi = fopen(train_file, "rb");
memset(sen, 0, sizeof(sen));
fseek(fi, file_size / (long long)num_threads * (long long)id, SEEK_SET);
while (1) {
if (word_count - last_word_count > 10000) {
word_count_actual += word_count - last_word_count;
last_word_count = word_count;
if ((debug_mode > 1)) {
now=clock();
printf("%cAlpha: %f Progress: %.2f%% Words/thread/sec: %.2fk ", 13, alpha,
word_count_actual / (real)(iter * train_words + 1) * 100,
word_count_actual / ((real)(now - start + 1) / (real)CLOCKS_PER_SEC * 1000));
fflush(stdout);
}
alpha = starting_alpha * (1 - word_count_actual / (real)(iter * train_words + 1));
if (alpha < starting_alpha * 0.0001) alpha = starting_alpha * 0.0001;
}
if (sentence_length == 0) {
while (1) {
real ran;
word = ReadWordIndex(fi);
if (feof(fi)) break;
if (word == -1) continue;
word_count++;
if (word == 0) break;
// The subsampling randomly discards frequent words while keeping the ranking same
if (sample > 0) {
next_random = (next_random + 11) * (unsigned long long)25214903917;
ran = (sqrt(GetWordUsageI(word) / (sample * train_words)) + 1) * (sample * train_words) / GetWordUsageI(word);
if (ran < (next_random & 0xFFFF) / (real)65536) continue;
}
sen[sentence_length] = word;
sentence_length++;
if (sentence_length >= MAX_SENTENCE_LENGTH) break;
}
sentence_position = 0;
}
if (feof(fi) || (word_count > train_words / num_threads)) {
word_count_actual += word_count - last_word_count;
local_iter--;
if (local_iter == 0) break;
word_count = 0;
last_word_count = 0;
sentence_length = 0;
fseek(fi, file_size / (long long)num_threads * (long long)id, SEEK_SET);
continue;
}
word = sen[sentence_position];
if (word == -1) continue;
for (c = 0; c < layer1_size; c++) neu1[c] = neu1e[c] = 0;
b = next_random % window;
next_random = (next_random + 11) * (unsigned long long)25214903917;
if (cbow) { //train the cbow architecture
// struct vocab_word *vocword = &vocab[word];
struct vocab_code *voccode = &vocab_codes[word];
// in -> hidden
cw = 0;
for (a = b; a < window * 2 + 1 - b; a++) if (a != window) {
c = sentence_position - window + a;
if ((c < 0) || (c >= sentence_length)) continue;
last_word = sen[c];
if (last_word == -1) continue;
for (c = 0; c < layer1_size; c++) neu1[c] += syn0[c + last_word * layer1_size];
cw++;
}
if (cw) {
for (c = 0; c < layer1_size; c++) neu1[c] /= cw;
if (hs) for (d = 0; d < voccode->codelen; d++) {
f = 0;
l2 = voccode->point[d] * layer1_size;
real *syn1_l2 = &syn1[l2];
// Propagate hidden -> output
//for (c = 0; c < layer1_size; c++) f += neu1[c] * syn1_l2[c];
f = DoMAC(layer1_size, neu1, syn1_l2);
f = getExp(f);
// 'g' is the gradient multiplied by the learning rate
g = (1 - voccode->code[d] - f) * alpha;
// Propagate errors output -> hidden
DoMAC1(layer1_size, neu1e, g, syn1_l2);
// Learn weights hidden -> output
DoMAC1(layer1_size, syn1_l2, g, neu1);
}
// NEGATIVE SAMPLING
if (negative > 0) for (d = 0; d < negative + 1; d++) {
register long long next_target;
if (d == 0) {
target = word;
label = 1;
next_target = table[(next_random >> 16) % table_size];
next_random = (next_random + 11) * (unsigned long long)25214903917;
} else {
next_target = table[(next_random >> 16) % table_size];
next_random = (next_random + 11) * (unsigned long long)25214903917;
if (target == 0) target = next_random % (vocab_size - 1) + 1;
if (target == word) {
target = next_target;
continue;
}
label = 0;
}
l2 = target * layer1_size;
real *syn1neg_l2 = &syn1neg[l2];
f = DoMAC(layer1_size, neu1, syn1neg_l2);
g = (label - getExp(f)) * alpha;
DoMAC1(layer1_size, neu1e, g, syn1neg_l2);
DoMAC1(layer1_size, syn1neg_l2, g, neu1);
target = next_target;
}
// hidden -> in
for (a = b; a < window * 2 + 1 - b; a++) if (a != window) {
c = sentence_position - window + a;
if ((c < 0) || (c >= sentence_length)) continue;
last_word = sen[c];
if (last_word == -1) continue;
for (c = 0; c < layer1_size; c++) syn0[c + last_word * layer1_size] += neu1e[c];
}
}
} else { //train skip-gram
register unsigned long long _next_random = next_random;
for (a = b; a < window * 2 + 1 - b; a++) if (a != window) {
c = sentence_position - window + a;
if ((c < 0) || (c >= sentence_length)) continue;
last_word = sen[c];
if (last_word == -1) continue;
l1 = last_word * layer1_size;
real *syn0_l1 = &syn0[l1];
for (c = 0; c < layer1_size; c++) neu1e[c] = 0;
// HIERARCHICAL SOFTMAX
if (hs) {
struct vocab_code *voccode = &vocab_codes[word];
for (d = 0; d < voccode->codelen; d++) {
l2 = voccode->point[d] * layer1_size;
real *syn1_l2 = &syn1[l2];
// Propagate hidden -> output
f = DoMAC(layer1_size, syn0_l1, syn1_l2);
f = getExp(f);
// 'g' is the gradient multiplied by the learning rate
g = (1 - voccode->code[d] - f) * alpha;
DoMAC1(layer1_size, neu1e, g, syn1_l2);
DoMAC1(layer1_size, syn1_l2, g, syn0_l1);
}
}
// NEGATIVE SAMPLING
if (negative > 0) {
register long long next_target;
for (d = 0; d < negative + 1; d++) {
if (d == 0) {
target = word;
label = 1;
next_target = table[(_next_random >> 16) % table_size];
_next_random = (_next_random + 11) * (unsigned long long)25214903917;
} else {
next_target = table[(_next_random >> 16) % table_size];
_next_random = (_next_random + 11) * (unsigned long long)25214903917;
if (target == 0) target = _next_random % (vocab_size - 1) + 1;
if (target == word) {
target = next_target;
continue;
}
label = 0;
}
l2 = target * layer1_size;
real *syn1neg_l2 = &syn1neg[l2];
f = DoMAC(layer1_size, syn0_l1, syn1neg_l2);
g = (label - getExp(f)) * alpha;
DoMAC1(layer1_size, neu1e, g, syn1neg_l2);
DoMAC1(layer1_size, syn1neg_l2, g, syn0_l1);
target = next_target;
}
// Learn weights input -> hidden
DoAdd(layer1_size, syn0_l1, neu1e);
// for (c = 0; c < layer1_size; c++) syn0[c + l1] += neu1e[c];
}
}
next_random = _next_random + 11;
}
sentence_position++;
if (sentence_position >= sentence_length) {
sentence_length = 0;
continue;
}
}
fclose(fi);
free(neu1);
free(neu1e);
pthread_exit(NULL);
}
void TrainModel() {
long a, b, c, d;
FILE *fo;
pthread_t *pt = (pthread_t *)malloc(num_threads * sizeof(pthread_t));
printf("Starting training using file %s\n", train_file);
starting_alpha = alpha;
if (read_vocab_file[0] != 0) ReadVocab(); else LearnVocabFromTrainFile();
if (save_vocab_file[0] != 0) SaveVocab();
if (output_file[0] == 0) return;
InitNet();
if (negative > 0) InitUnigramTable();
start = clock();
for (a = 0; a < num_threads; a++) pthread_create(&pt[a], NULL, TrainModelThread, (void *)a);
for (a = 0; a < num_threads; a++) pthread_join(pt[a], NULL);
fo = fopen(output_file, "wb");
if (classes == 0) {
// Save the word vectors
fprintf(fo, "%lld %lld\n", vocab_size, layer1_size);
for (a = 0; a < vocab_size; a++) {
fprintf(fo, "%s ", GetWordPtrI(a));
if (binary) for (b = 0; b < layer1_size; b++) fwrite(&syn0[a * layer1_size + b], sizeof(real), 1, fo);
else for (b = 0; b < layer1_size; b++) fprintf(fo, "%lf ", syn0[a * layer1_size + b]);
fprintf(fo, "\n");
}
} else {
// Run K-means on the word vectors
int clcn = classes, iter = 10, closeid;
int *centcn = (int *)malloc(classes * sizeof(int));
int *cl = (int *)calloc(vocab_size, sizeof(int));
real closev, x;
real *cent = (real *)calloc(classes * layer1_size, sizeof(real));
for (a = 0; a < vocab_size; a++) cl[a] = a % clcn;
for (a = 0; a < iter; a++) {
for (b = 0; b < clcn * layer1_size; b++) cent[b] = 0;
for (b = 0; b < clcn; b++) centcn[b] = 1;
for (c = 0; c < vocab_size; c++) {
for (d = 0; d < layer1_size; d++) cent[layer1_size * cl[c] + d] += syn0[c * layer1_size + d];
centcn[cl[c]]++;
}
for (b = 0; b < clcn; b++) {
closev = 0;
for (c = 0; c < layer1_size; c++) {
cent[layer1_size * b + c] /= centcn[b];
closev += cent[layer1_size * b + c] * cent[layer1_size * b + c];
}
closev = sqrt(closev);
for (c = 0; c < layer1_size; c++) cent[layer1_size * b + c] /= closev;
}
for (c = 0; c < vocab_size; c++) {
closev = -10;
closeid = 0;
for (d = 0; d < clcn; d++) {
x = 0;
for (b = 0; b < layer1_size; b++) x += cent[layer1_size * d + b] * syn0[c * layer1_size + b];
if (x > closev) {
closev = x;
closeid = d;
}
}
cl[c] = closeid;
}
}
// Save the K-means classes
for (a = 0; a < vocab_size; a++) fprintf(fo, "%s %d\n", GetWordPtrI(a), cl[a]);
free(centcn);
free(cent);
free(cl);
}
fclose(fo);
}
int ArgPos(char *str, int argc, char **argv) {
int a;
for (a = 1; a < argc; a++) if (!strcmp(str, argv[a])) {
if (a == argc - 1) {
printf("Argument missing for %s\n", str);
exit(1);
}
return a;
}
return -1;
}
int main(int argc, char **argv) {
int i;
if (argc == 1) {
printf("WORD VECTOR estimation toolkit v 0.1c\n\n");
printf("Options:\n");
printf("Parameters for training:\n");
printf("\t-train <file>\n");
printf("\t\tUse text data from <file> to train the model\n");
printf("\t-output <file>\n");
printf("\t\tUse <file> to save the resulting word vectors / word clusters\n");
printf("\t-size <int>\n");
printf("\t\tSet size of word vectors; default is 100\n");
printf("\t-window <int>\n");
printf("\t\tSet max skip length between words; default is 5\n");
printf("\t-sample <float>\n");
printf("\t\tSet threshold for occurrence of words. Those that appear with higher frequency in the training data\n");
printf("\t\twill be randomly down-sampled; default is 1e-3, useful range is (0, 1e-5)\n");
printf("\t-hs <int>\n");
printf("\t\tUse Hierarchical Softmax; default is 0 (not used)\n");
printf("\t-negative <int>\n");
printf("\t\tNumber of negative examples; default is 5, common values are 3 - 10 (0 = not used)\n");
printf("\t-threads <int>\n");
printf("\t\tUse <int> threads (default 12)\n");
printf("\t-iter <int>\n");
printf("\t\tRun more training iterations (default 5)\n");
printf("\t-min-count <int>\n");
printf("\t\tThis will discard words that appear less than <int> times; default is 5\n");
printf("\t-alpha <float>\n");
printf("\t\tSet the starting learning rate; default is 0.025 for skip-gram and 0.05 for CBOW\n");
printf("\t-classes <int>\n");
printf("\t\tOutput word classes rather than word vectors; default number of classes is 0 (vectors are written)\n");
printf("\t-debug <int>\n");
printf("\t\tSet the debug mode (default = 2 = more info during training)\n");
printf("\t-binary <int>\n");
printf("\t\tSave the resulting vectors in binary moded; default is 0 (off)\n");
printf("\t-save-vocab <file>\n");
printf("\t\tThe vocabulary will be saved to <file>\n");
printf("\t-read-vocab <file>\n");
printf("\t\tThe vocabulary will be read from <file>, not constructed from the training data\n");
printf("\t-cbow <int>\n");
printf("\t\tUse the continuous bag of words model; default is 1 (use 0 for skip-gram model)\n");
printf("\nExamples:\n");
printf("./word2vec -train data.txt -output vec.txt -size 200 -window 5 -sample 1e-4 -negative 5 -hs 0 -binary 0 -cbow 1 -iter 3\n\n");
return 0;
}
output_file[0] = 0;
save_vocab_file[0] = 0;
read_vocab_file[0] = 0;
#ifndef CONST_LAYER1
if ((i = ArgPos((char *)"-size", argc, argv)) > 0) layer1_size = atoi(argv[i + 1]);
#endif
if ((i = ArgPos((char *)"-train", argc, argv)) > 0) strcpy(train_file, argv[i + 1]);
if ((i = ArgPos((char *)"-save-vocab", argc, argv)) > 0) strcpy(save_vocab_file, argv[i + 1]);
if ((i = ArgPos((char *)"-read-vocab", argc, argv)) > 0) strcpy(read_vocab_file, argv[i + 1]);
if ((i = ArgPos((char *)"-debug", argc, argv)) > 0) debug_mode = atoi(argv[i + 1]);
if ((i = ArgPos((char *)"-binary", argc, argv)) > 0) binary = atoi(argv[i + 1]);
if ((i = ArgPos((char *)"-cbow", argc, argv)) > 0) cbow = atoi(argv[i + 1]);
if (cbow) alpha = 0.05;
if ((i = ArgPos((char *)"-alpha", argc, argv)) > 0) alpha = atof(argv[i + 1]);
if ((i = ArgPos((char *)"-output", argc, argv)) > 0) strcpy(output_file, argv[i + 1]);
if ((i = ArgPos((char *)"-window", argc, argv)) > 0) window = atoi(argv[i + 1]);
if ((i = ArgPos((char *)"-sample", argc, argv)) > 0) sample = atof(argv[i + 1]);
if ((i = ArgPos((char *)"-hs", argc, argv)) > 0) hs = atoi(argv[i + 1]);
if ((i = ArgPos((char *)"-negative", argc, argv)) > 0) negative = atoi(argv[i + 1]);
if ((i = ArgPos((char *)"-threads", argc, argv)) > 0) num_threads = atoi(argv[i + 1]);
if ((i = ArgPos((char *)"-iter", argc, argv)) > 0) iter = atoi(argv[i + 1]);
if ((i = ArgPos((char *)"-min-count", argc, argv)) > 0) min_count = atoi(argv[i + 1]);
if ((i = ArgPos((char *)"-classes", argc, argv)) > 0) classes = atoi(argv[i + 1]);
vocab = (struct vocab_word *)calloc(vocab_max_size, sizeof(struct vocab_word));
vocab_hash = (int *)calloc(vocab_hash_size, sizeof(int));
expTable = (real *)malloc((EXP_TABLE_SIZE + 1) * sizeof(real));
for (i = 0; i < EXP_TABLE_SIZE; i++) {
expTable[i] = exp((i / (real)EXP_TABLE_SIZE * 1 - 0) * MAX_EXP); // Precompute the exp() table
expTable[i] = (expTable[i] / (expTable[i] + 1)) - 0.5; // Precompute f(x) = x / (x + 1)
}
TrainModel();
return 0;
}
|
the_stack_data/54825311.c | unsigned int fib(unsigned int n) {
if (n == 0 || n == 1) {
return 1;
}
return fib(n-1) + fib(n-2);
}
int main() {
fib(40);
fib(40);
fib(40);
return 0;
}
|
the_stack_data/29824193.c | /*****************************************
Emitting C Generated Code
*******************************************/
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
/**************** Snippet ****************/
void Snippet(int x0) {
int x1 = x0;
x1 = 5;
foo(x1);
printf("Hello\n");
}
/*****************************************
End of C Generated Code
*******************************************/
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("usage: %s <arg>\n", argv[0]);
return 0;
}
Snippet(atoi(argv[1]));
return 0;
}
|
the_stack_data/193892045.c | /*
* Copyright (c) 2016 Simon Schmidt
*
* Copyright(C) Caldera International Inc. 2001-2002. 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 and documentation 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.
*
* - All advertising materials mentioning features or use of this software must
* display the following acknowledgement: This product includes software developed
* or owned by Caldera International, Inc.
*
* - Neither the name of Caldera International, Inc. nor the names of other
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* USE OF THE SOFTWARE PROVIDED FOR UNDER THIS LICENSE BY CALDERA INTERNATIONAL, INC.
* 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 CALDERA INTERNATIONAL, INC. 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.
*/
/*
* chown uid file ...
*/
#include <stdio.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <pwd.h>
#include <stdlib.h>
#include <unistd.h>
struct passwd *pwd;//,*getpwnam();
struct stat stbuf;
int uid;
int status;
int isnumber(char *s);
int main(int argc, char *argv[])
{
int c;
if(argc < 3) {
printf("usage: chown uid file ...\n");
exit(4);
}
if(isnumber(argv[1])) {
uid = atoi(argv[1]);
goto cho;
}
if((pwd=getpwnam(argv[1])) == NULL) {
printf("unknown user id: %s\n",argv[1]);
exit(4);
}
uid = pwd->pw_uid;
cho:
for(c=2; c<argc; c++) {
stat(argv[c], &stbuf);
if(chown(argv[c], uid, stbuf.st_gid) < 0) {
perror(argv[c]);
status = 1;
}
}
exit(status);
}
int isnumber(char *s)
{
int c;
while(c = *s++)
if(!isdigit(c))
return(0);
return(1);
}
|
the_stack_data/718759.c | /*
* Disk Array driver for HP Smart Array controllers, SCSI Tape module.
* (C) Copyright 2001, 2007 Hewlett-Packard Development Company, L.P.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 300, Boston, MA
* 02111-1307, USA.
*
* Questions/Comments/Bugfixes to [email protected]
*
* Author: Stephen M. Cameron
*/
#ifdef CONFIG_CISS_SCSI_TAPE
/* Here we have code to present the driver as a scsi driver
as it is simultaneously presented as a block driver. The
reason for doing this is to allow access to SCSI tape drives
through the array controller. Note in particular, neither
physical nor logical disks are presented through the scsi layer. */
#include <linux/timer.h>
#include <linux/completion.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/atomic.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_host.h>
#include "cciss_scsi.h"
#define CCISS_ABORT_MSG 0x00
#define CCISS_RESET_MSG 0x01
static int fill_cmd(ctlr_info_t *h, CommandList_struct *c, __u8 cmd, void *buff,
size_t size,
__u8 page_code, unsigned char *scsi3addr,
int cmd_type);
static CommandList_struct *cmd_alloc(ctlr_info_t *h);
static CommandList_struct *cmd_special_alloc(ctlr_info_t *h);
static void cmd_free(ctlr_info_t *h, CommandList_struct *c);
static void cmd_special_free(ctlr_info_t *h, CommandList_struct *c);
static int cciss_scsi_proc_info(
struct Scsi_Host *sh,
char *buffer, /* data buffer */
char **start, /* where data in buffer starts */
off_t offset, /* offset from start of imaginary file */
int length, /* length of data in buffer */
int func); /* 0 == read, 1 == write */
static int cciss_scsi_queue_command (struct Scsi_Host *h,
struct scsi_cmnd *cmd);
static int cciss_eh_device_reset_handler(struct scsi_cmnd *);
static int cciss_eh_abort_handler(struct scsi_cmnd *);
static struct cciss_scsi_hba_t ccissscsi[MAX_CTLR] = {
{ .name = "cciss0", .ndevices = 0 },
{ .name = "cciss1", .ndevices = 0 },
{ .name = "cciss2", .ndevices = 0 },
{ .name = "cciss3", .ndevices = 0 },
{ .name = "cciss4", .ndevices = 0 },
{ .name = "cciss5", .ndevices = 0 },
{ .name = "cciss6", .ndevices = 0 },
{ .name = "cciss7", .ndevices = 0 },
};
static struct scsi_host_template cciss_driver_template = {
.module = THIS_MODULE,
.name = "cciss",
.proc_name = "cciss",
.proc_info = cciss_scsi_proc_info,
.queuecommand = cciss_scsi_queue_command,
.this_id = 7,
.cmd_per_lun = 1,
.use_clustering = DISABLE_CLUSTERING,
/* Can't have eh_bus_reset_handler or eh_host_reset_handler for cciss */
.eh_device_reset_handler= cciss_eh_device_reset_handler,
.eh_abort_handler = cciss_eh_abort_handler,
};
#pragma pack(1)
#define SCSI_PAD_32 8
#define SCSI_PAD_64 8
struct cciss_scsi_cmd_stack_elem_t {
CommandList_struct cmd;
ErrorInfo_struct Err;
__u32 busaddr;
int cmdindex;
u8 pad[IS_32_BIT * SCSI_PAD_32 + IS_64_BIT * SCSI_PAD_64];
};
#pragma pack()
#pragma pack(1)
struct cciss_scsi_cmd_stack_t {
struct cciss_scsi_cmd_stack_elem_t *pool;
struct cciss_scsi_cmd_stack_elem_t **elem;
dma_addr_t cmd_pool_handle;
int top;
int nelems;
};
#pragma pack()
struct cciss_scsi_adapter_data_t {
struct Scsi_Host *scsi_host;
struct cciss_scsi_cmd_stack_t cmd_stack;
SGDescriptor_struct **cmd_sg_list;
int registered;
spinlock_t lock; // to protect ccissscsi[ctlr];
};
#define CPQ_TAPE_LOCK(h, flags) spin_lock_irqsave( \
&h->scsi_ctlr->lock, flags);
#define CPQ_TAPE_UNLOCK(h, flags) spin_unlock_irqrestore( \
&h->scsi_ctlr->lock, flags);
static CommandList_struct *
scsi_cmd_alloc(ctlr_info_t *h)
{
/* assume only one process in here at a time, locking done by caller. */
/* use h->lock */
/* might be better to rewrite how we allocate scsi commands in a way that */
/* needs no locking at all. */
/* take the top memory chunk off the stack and return it, if any. */
struct cciss_scsi_cmd_stack_elem_t *c;
struct cciss_scsi_adapter_data_t *sa;
struct cciss_scsi_cmd_stack_t *stk;
u64bit temp64;
sa = h->scsi_ctlr;
stk = &sa->cmd_stack;
if (stk->top < 0)
return NULL;
c = stk->elem[stk->top];
/* memset(c, 0, sizeof(*c)); */
memset(&c->cmd, 0, sizeof(c->cmd));
memset(&c->Err, 0, sizeof(c->Err));
/* set physical addr of cmd and addr of scsi parameters */
c->cmd.busaddr = c->busaddr;
c->cmd.cmdindex = c->cmdindex;
/* (__u32) (stk->cmd_pool_handle +
(sizeof(struct cciss_scsi_cmd_stack_elem_t)*stk->top)); */
temp64.val = (__u64) (c->busaddr + sizeof(CommandList_struct));
/* (__u64) (stk->cmd_pool_handle +
(sizeof(struct cciss_scsi_cmd_stack_elem_t)*stk->top) +
sizeof(CommandList_struct)); */
stk->top--;
c->cmd.ErrDesc.Addr.lower = temp64.val32.lower;
c->cmd.ErrDesc.Addr.upper = temp64.val32.upper;
c->cmd.ErrDesc.Len = sizeof(ErrorInfo_struct);
c->cmd.ctlr = h->ctlr;
c->cmd.err_info = &c->Err;
return (CommandList_struct *) c;
}
static void
scsi_cmd_free(ctlr_info_t *h, CommandList_struct *c)
{
/* assume only one process in here at a time, locking done by caller. */
/* use h->lock */
/* drop the free memory chunk on top of the stack. */
struct cciss_scsi_adapter_data_t *sa;
struct cciss_scsi_cmd_stack_t *stk;
sa = h->scsi_ctlr;
stk = &sa->cmd_stack;
stk->top++;
if (stk->top >= stk->nelems) {
dev_err(&h->pdev->dev,
"scsi_cmd_free called too many times.\n");
BUG();
}
stk->elem[stk->top] = (struct cciss_scsi_cmd_stack_elem_t *) c;
}
static int
scsi_cmd_stack_setup(ctlr_info_t *h, struct cciss_scsi_adapter_data_t *sa)
{
int i;
struct cciss_scsi_cmd_stack_t *stk;
size_t size;
stk = &sa->cmd_stack;
stk->nelems = cciss_tape_cmds + 2;
sa->cmd_sg_list = cciss_allocate_sg_chain_blocks(h,
h->chainsize, stk->nelems);
if (!sa->cmd_sg_list && h->chainsize > 0)
return -ENOMEM;
size = sizeof(struct cciss_scsi_cmd_stack_elem_t) * stk->nelems;
/* Check alignment, see cciss_cmd.h near CommandList_struct def. */
BUILD_BUG_ON((sizeof(*stk->pool) % COMMANDLIST_ALIGNMENT) != 0);
/* pci_alloc_consistent guarantees 32-bit DMA address will be used */
stk->pool = (struct cciss_scsi_cmd_stack_elem_t *)
pci_alloc_consistent(h->pdev, size, &stk->cmd_pool_handle);
if (stk->pool == NULL) {
cciss_free_sg_chain_blocks(sa->cmd_sg_list, stk->nelems);
sa->cmd_sg_list = NULL;
return -ENOMEM;
}
stk->elem = kmalloc(sizeof(stk->elem[0]) * stk->nelems, GFP_KERNEL);
if (!stk->elem) {
pci_free_consistent(h->pdev, size, stk->pool,
stk->cmd_pool_handle);
return -1;
}
for (i = 0; i < stk->nelems; i++) {
stk->elem[i] = &stk->pool[i];
stk->elem[i]->busaddr = (__u32) (stk->cmd_pool_handle +
(sizeof(struct cciss_scsi_cmd_stack_elem_t) * i));
stk->elem[i]->cmdindex = i;
}
stk->top = stk->nelems-1;
return 0;
}
static void
scsi_cmd_stack_free(ctlr_info_t *h)
{
struct cciss_scsi_adapter_data_t *sa;
struct cciss_scsi_cmd_stack_t *stk;
size_t size;
sa = h->scsi_ctlr;
stk = &sa->cmd_stack;
if (stk->top != stk->nelems-1) {
dev_warn(&h->pdev->dev,
"bug: %d scsi commands are still outstanding.\n",
stk->nelems - stk->top);
}
size = sizeof(struct cciss_scsi_cmd_stack_elem_t) * stk->nelems;
pci_free_consistent(h->pdev, size, stk->pool, stk->cmd_pool_handle);
stk->pool = NULL;
cciss_free_sg_chain_blocks(sa->cmd_sg_list, stk->nelems);
kfree(stk->elem);
stk->elem = NULL;
}
#if 0
static int xmargin=8;
static int amargin=60;
static void
print_bytes (unsigned char *c, int len, int hex, int ascii)
{
int i;
unsigned char *x;
if (hex)
{
x = c;
for (i=0;i<len;i++)
{
if ((i % xmargin) == 0 && i>0) printk("\n");
if ((i % xmargin) == 0) printk("0x%04x:", i);
printk(" %02x", *x);
x++;
}
printk("\n");
}
if (ascii)
{
x = c;
for (i=0;i<len;i++)
{
if ((i % amargin) == 0 && i>0) printk("\n");
if ((i % amargin) == 0) printk("0x%04x:", i);
if (*x > 26 && *x < 128) printk("%c", *x);
else printk(".");
x++;
}
printk("\n");
}
}
static void
print_cmd(CommandList_struct *cp)
{
printk("queue:%d\n", cp->Header.ReplyQueue);
printk("sglist:%d\n", cp->Header.SGList);
printk("sgtot:%d\n", cp->Header.SGTotal);
printk("Tag:0x%08x/0x%08x\n", cp->Header.Tag.upper,
cp->Header.Tag.lower);
printk("LUN:0x%02x%02x%02x%02x%02x%02x%02x%02x\n",
cp->Header.LUN.LunAddrBytes[0],
cp->Header.LUN.LunAddrBytes[1],
cp->Header.LUN.LunAddrBytes[2],
cp->Header.LUN.LunAddrBytes[3],
cp->Header.LUN.LunAddrBytes[4],
cp->Header.LUN.LunAddrBytes[5],
cp->Header.LUN.LunAddrBytes[6],
cp->Header.LUN.LunAddrBytes[7]);
printk("CDBLen:%d\n", cp->Request.CDBLen);
printk("Type:%d\n",cp->Request.Type.Type);
printk("Attr:%d\n",cp->Request.Type.Attribute);
printk(" Dir:%d\n",cp->Request.Type.Direction);
printk("Timeout:%d\n",cp->Request.Timeout);
printk( "CDB: %02x %02x %02x %02x %02x %02x %02x %02x"
" %02x %02x %02x %02x %02x %02x %02x %02x\n",
cp->Request.CDB[0], cp->Request.CDB[1],
cp->Request.CDB[2], cp->Request.CDB[3],
cp->Request.CDB[4], cp->Request.CDB[5],
cp->Request.CDB[6], cp->Request.CDB[7],
cp->Request.CDB[8], cp->Request.CDB[9],
cp->Request.CDB[10], cp->Request.CDB[11],
cp->Request.CDB[12], cp->Request.CDB[13],
cp->Request.CDB[14], cp->Request.CDB[15]),
printk("edesc.Addr: 0x%08x/0%08x, Len = %d\n",
cp->ErrDesc.Addr.upper, cp->ErrDesc.Addr.lower,
cp->ErrDesc.Len);
printk("sgs..........Errorinfo:\n");
printk("scsistatus:%d\n", cp->err_info->ScsiStatus);
printk("senselen:%d\n", cp->err_info->SenseLen);
printk("cmd status:%d\n", cp->err_info->CommandStatus);
printk("resid cnt:%d\n", cp->err_info->ResidualCnt);
printk("offense size:%d\n", cp->err_info->MoreErrInfo.Invalid_Cmd.offense_size);
printk("offense byte:%d\n", cp->err_info->MoreErrInfo.Invalid_Cmd.offense_num);
printk("offense value:%d\n", cp->err_info->MoreErrInfo.Invalid_Cmd.offense_value);
}
#endif
static int
find_bus_target_lun(ctlr_info_t *h, int *bus, int *target, int *lun)
{
/* finds an unused bus, target, lun for a new device */
/* assumes h->scsi_ctlr->lock is held */
int i, found=0;
unsigned char target_taken[CCISS_MAX_SCSI_DEVS_PER_HBA];
memset(&target_taken[0], 0, CCISS_MAX_SCSI_DEVS_PER_HBA);
target_taken[SELF_SCSI_ID] = 1;
for (i = 0; i < ccissscsi[h->ctlr].ndevices; i++)
target_taken[ccissscsi[h->ctlr].dev[i].target] = 1;
for (i = 0; i < CCISS_MAX_SCSI_DEVS_PER_HBA; i++) {
if (!target_taken[i]) {
*bus = 0; *target=i; *lun = 0; found=1;
break;
}
}
return (!found);
}
struct scsi2map {
char scsi3addr[8];
int bus, target, lun;
};
static int
cciss_scsi_add_entry(ctlr_info_t *h, int hostno,
struct cciss_scsi_dev_t *device,
struct scsi2map *added, int *nadded)
{
/* assumes h->scsi_ctlr->lock is held */
int n = ccissscsi[h->ctlr].ndevices;
struct cciss_scsi_dev_t *sd;
int i, bus, target, lun;
unsigned char addr1[8], addr2[8];
if (n >= CCISS_MAX_SCSI_DEVS_PER_HBA) {
dev_warn(&h->pdev->dev, "Too many devices, "
"some will be inaccessible.\n");
return -1;
}
bus = target = -1;
lun = 0;
/* Is this device a non-zero lun of a multi-lun device */
/* byte 4 of the 8-byte LUN addr will contain the logical unit no. */
if (device->scsi3addr[4] != 0) {
/* Search through our list and find the device which */
/* has the same 8 byte LUN address, excepting byte 4. */
/* Assign the same bus and target for this new LUN. */
/* Use the logical unit number from the firmware. */
memcpy(addr1, device->scsi3addr, 8);
addr1[4] = 0;
for (i = 0; i < n; i++) {
sd = &ccissscsi[h->ctlr].dev[i];
memcpy(addr2, sd->scsi3addr, 8);
addr2[4] = 0;
/* differ only in byte 4? */
if (memcmp(addr1, addr2, 8) == 0) {
bus = sd->bus;
target = sd->target;
lun = device->scsi3addr[4];
break;
}
}
}
sd = &ccissscsi[h->ctlr].dev[n];
if (lun == 0) {
if (find_bus_target_lun(h,
&sd->bus, &sd->target, &sd->lun) != 0)
return -1;
} else {
sd->bus = bus;
sd->target = target;
sd->lun = lun;
}
added[*nadded].bus = sd->bus;
added[*nadded].target = sd->target;
added[*nadded].lun = sd->lun;
(*nadded)++;
memcpy(sd->scsi3addr, device->scsi3addr, 8);
memcpy(sd->vendor, device->vendor, sizeof(sd->vendor));
memcpy(sd->revision, device->revision, sizeof(sd->revision));
memcpy(sd->device_id, device->device_id, sizeof(sd->device_id));
sd->devtype = device->devtype;
ccissscsi[h->ctlr].ndevices++;
/* initially, (before registering with scsi layer) we don't
know our hostno and we don't want to print anything first
time anyway (the scsi layer's inquiries will show that info) */
if (hostno != -1)
dev_info(&h->pdev->dev, "%s device c%db%dt%dl%d added.\n",
scsi_device_type(sd->devtype), hostno,
sd->bus, sd->target, sd->lun);
return 0;
}
static void
cciss_scsi_remove_entry(ctlr_info_t *h, int hostno, int entry,
struct scsi2map *removed, int *nremoved)
{
/* assumes h->ctlr]->scsi_ctlr->lock is held */
int i;
struct cciss_scsi_dev_t sd;
if (entry < 0 || entry >= CCISS_MAX_SCSI_DEVS_PER_HBA) return;
sd = ccissscsi[h->ctlr].dev[entry];
removed[*nremoved].bus = sd.bus;
removed[*nremoved].target = sd.target;
removed[*nremoved].lun = sd.lun;
(*nremoved)++;
for (i = entry; i < ccissscsi[h->ctlr].ndevices-1; i++)
ccissscsi[h->ctlr].dev[i] = ccissscsi[h->ctlr].dev[i+1];
ccissscsi[h->ctlr].ndevices--;
dev_info(&h->pdev->dev, "%s device c%db%dt%dl%d removed.\n",
scsi_device_type(sd.devtype), hostno,
sd.bus, sd.target, sd.lun);
}
#define SCSI3ADDR_EQ(a,b) ( \
(a)[7] == (b)[7] && \
(a)[6] == (b)[6] && \
(a)[5] == (b)[5] && \
(a)[4] == (b)[4] && \
(a)[3] == (b)[3] && \
(a)[2] == (b)[2] && \
(a)[1] == (b)[1] && \
(a)[0] == (b)[0])
static void fixup_botched_add(ctlr_info_t *h, char *scsi3addr)
{
/* called when scsi_add_device fails in order to re-adjust */
/* ccissscsi[] to match the mid layer's view. */
unsigned long flags;
int i, j;
CPQ_TAPE_LOCK(h, flags);
for (i = 0; i < ccissscsi[h->ctlr].ndevices; i++) {
if (memcmp(scsi3addr,
ccissscsi[h->ctlr].dev[i].scsi3addr, 8) == 0) {
for (j = i; j < ccissscsi[h->ctlr].ndevices-1; j++)
ccissscsi[h->ctlr].dev[j] =
ccissscsi[h->ctlr].dev[j+1];
ccissscsi[h->ctlr].ndevices--;
break;
}
}
CPQ_TAPE_UNLOCK(h, flags);
}
static int device_is_the_same(struct cciss_scsi_dev_t *dev1,
struct cciss_scsi_dev_t *dev2)
{
return dev1->devtype == dev2->devtype &&
memcmp(dev1->scsi3addr, dev2->scsi3addr,
sizeof(dev1->scsi3addr)) == 0 &&
memcmp(dev1->device_id, dev2->device_id,
sizeof(dev1->device_id)) == 0 &&
memcmp(dev1->vendor, dev2->vendor,
sizeof(dev1->vendor)) == 0 &&
memcmp(dev1->model, dev2->model,
sizeof(dev1->model)) == 0 &&
memcmp(dev1->revision, dev2->revision,
sizeof(dev1->revision)) == 0;
}
static int
adjust_cciss_scsi_table(ctlr_info_t *h, int hostno,
struct cciss_scsi_dev_t sd[], int nsds)
{
/* sd contains scsi3 addresses and devtypes, but
bus target and lun are not filled in. This funciton
takes what's in sd to be the current and adjusts
ccissscsi[] to be in line with what's in sd. */
int i,j, found, changes=0;
struct cciss_scsi_dev_t *csd;
unsigned long flags;
struct scsi2map *added, *removed;
int nadded, nremoved;
struct Scsi_Host *sh = NULL;
added = kzalloc(sizeof(*added) * CCISS_MAX_SCSI_DEVS_PER_HBA,
GFP_KERNEL);
removed = kzalloc(sizeof(*removed) * CCISS_MAX_SCSI_DEVS_PER_HBA,
GFP_KERNEL);
if (!added || !removed) {
dev_warn(&h->pdev->dev,
"Out of memory in adjust_cciss_scsi_table\n");
goto free_and_out;
}
CPQ_TAPE_LOCK(h, flags);
if (hostno != -1) /* if it's not the first time... */
sh = h->scsi_ctlr->scsi_host;
/* find any devices in ccissscsi[] that are not in
sd[] and remove them from ccissscsi[] */
i = 0;
nremoved = 0;
nadded = 0;
while (i < ccissscsi[h->ctlr].ndevices) {
csd = &ccissscsi[h->ctlr].dev[i];
found=0;
for (j=0;j<nsds;j++) {
if (SCSI3ADDR_EQ(sd[j].scsi3addr,
csd->scsi3addr)) {
if (device_is_the_same(&sd[j], csd))
found=2;
else
found=1;
break;
}
}
if (found == 0) { /* device no longer present. */
changes++;
cciss_scsi_remove_entry(h, hostno, i,
removed, &nremoved);
/* remove ^^^, hence i not incremented */
} else if (found == 1) { /* device is different in some way */
changes++;
dev_info(&h->pdev->dev,
"device c%db%dt%dl%d has changed.\n",
hostno, csd->bus, csd->target, csd->lun);
cciss_scsi_remove_entry(h, hostno, i,
removed, &nremoved);
/* remove ^^^, hence i not incremented */
if (cciss_scsi_add_entry(h, hostno, &sd[j],
added, &nadded) != 0)
/* we just removed one, so add can't fail. */
BUG();
csd->devtype = sd[j].devtype;
memcpy(csd->device_id, sd[j].device_id,
sizeof(csd->device_id));
memcpy(csd->vendor, sd[j].vendor,
sizeof(csd->vendor));
memcpy(csd->model, sd[j].model,
sizeof(csd->model));
memcpy(csd->revision, sd[j].revision,
sizeof(csd->revision));
} else /* device is same as it ever was, */
i++; /* so just move along. */
}
/* Now, make sure every device listed in sd[] is also
listed in ccissscsi[], adding them if they aren't found */
for (i=0;i<nsds;i++) {
found=0;
for (j = 0; j < ccissscsi[h->ctlr].ndevices; j++) {
csd = &ccissscsi[h->ctlr].dev[j];
if (SCSI3ADDR_EQ(sd[i].scsi3addr,
csd->scsi3addr)) {
if (device_is_the_same(&sd[i], csd))
found=2; /* found device */
else
found=1; /* found a bug. */
break;
}
}
if (!found) {
changes++;
if (cciss_scsi_add_entry(h, hostno, &sd[i],
added, &nadded) != 0)
break;
} else if (found == 1) {
/* should never happen... */
changes++;
dev_warn(&h->pdev->dev,
"device unexpectedly changed\n");
/* but if it does happen, we just ignore that device */
}
}
CPQ_TAPE_UNLOCK(h, flags);
/* Don't notify scsi mid layer of any changes the first time through */
/* (or if there are no changes) scsi_scan_host will do it later the */
/* first time through. */
if (hostno == -1 || !changes)
goto free_and_out;
/* Notify scsi mid layer of any removed devices */
for (i = 0; i < nremoved; i++) {
struct scsi_device *sdev =
scsi_device_lookup(sh, removed[i].bus,
removed[i].target, removed[i].lun);
if (sdev != NULL) {
scsi_remove_device(sdev);
scsi_device_put(sdev);
} else {
/* We don't expect to get here. */
/* future cmds to this device will get selection */
/* timeout as if the device was gone. */
dev_warn(&h->pdev->dev, "didn't find "
"c%db%dt%dl%d\n for removal.",
hostno, removed[i].bus,
removed[i].target, removed[i].lun);
}
}
/* Notify scsi mid layer of any added devices */
for (i = 0; i < nadded; i++) {
int rc;
rc = scsi_add_device(sh, added[i].bus,
added[i].target, added[i].lun);
if (rc == 0)
continue;
dev_warn(&h->pdev->dev, "scsi_add_device "
"c%db%dt%dl%d failed, device not added.\n",
hostno, added[i].bus, added[i].target, added[i].lun);
/* now we have to remove it from ccissscsi, */
/* since it didn't get added to scsi mid layer */
fixup_botched_add(h, added[i].scsi3addr);
}
free_and_out:
kfree(added);
kfree(removed);
return 0;
}
static int
lookup_scsi3addr(ctlr_info_t *h, int bus, int target, int lun, char *scsi3addr)
{
int i;
struct cciss_scsi_dev_t *sd;
unsigned long flags;
CPQ_TAPE_LOCK(h, flags);
for (i = 0; i < ccissscsi[h->ctlr].ndevices; i++) {
sd = &ccissscsi[h->ctlr].dev[i];
if (sd->bus == bus &&
sd->target == target &&
sd->lun == lun) {
memcpy(scsi3addr, &sd->scsi3addr[0], 8);
CPQ_TAPE_UNLOCK(h, flags);
return 0;
}
}
CPQ_TAPE_UNLOCK(h, flags);
return -1;
}
static void
cciss_scsi_setup(ctlr_info_t *h)
{
struct cciss_scsi_adapter_data_t * shba;
ccissscsi[h->ctlr].ndevices = 0;
shba = (struct cciss_scsi_adapter_data_t *)
kmalloc(sizeof(*shba), GFP_KERNEL);
if (shba == NULL)
return;
shba->scsi_host = NULL;
spin_lock_init(&shba->lock);
shba->registered = 0;
if (scsi_cmd_stack_setup(h, shba) != 0) {
kfree(shba);
shba = NULL;
}
h->scsi_ctlr = shba;
return;
}
static void complete_scsi_command(CommandList_struct *c, int timeout,
__u32 tag)
{
struct scsi_cmnd *cmd;
ctlr_info_t *h;
ErrorInfo_struct *ei;
ei = c->err_info;
/* First, see if it was a message rather than a command */
if (c->Request.Type.Type == TYPE_MSG) {
c->cmd_type = CMD_MSG_DONE;
return;
}
cmd = (struct scsi_cmnd *) c->scsi_cmd;
h = hba[c->ctlr];
scsi_dma_unmap(cmd);
if (c->Header.SGTotal > h->max_cmd_sgentries)
cciss_unmap_sg_chain_block(h, c);
cmd->result = (DID_OK << 16); /* host byte */
cmd->result |= (COMMAND_COMPLETE << 8); /* msg byte */
/* cmd->result |= (GOOD < 1); */ /* status byte */
cmd->result |= (ei->ScsiStatus);
/* printk("Scsistatus is 0x%02x\n", ei->ScsiStatus); */
/* copy the sense data whether we need to or not. */
memcpy(cmd->sense_buffer, ei->SenseInfo,
ei->SenseLen > SCSI_SENSE_BUFFERSIZE ?
SCSI_SENSE_BUFFERSIZE :
ei->SenseLen);
scsi_set_resid(cmd, ei->ResidualCnt);
if(ei->CommandStatus != 0)
{ /* an error has occurred */
switch(ei->CommandStatus)
{
case CMD_TARGET_STATUS:
/* Pass it up to the upper layers... */
if( ei->ScsiStatus)
{
#if 0
printk(KERN_WARNING "cciss: cmd %p "
"has SCSI Status = %x\n",
c, ei->ScsiStatus);
#endif
cmd->result |= (ei->ScsiStatus << 1);
}
else { /* scsi status is zero??? How??? */
/* Ordinarily, this case should never happen, but there is a bug
in some released firmware revisions that allows it to happen
if, for example, a 4100 backplane loses power and the tape
drive is in it. We assume that it's a fatal error of some
kind because we can't show that it wasn't. We will make it
look like selection timeout since that is the most common
reason for this to occur, and it's severe enough. */
cmd->result = DID_NO_CONNECT << 16;
}
break;
case CMD_DATA_UNDERRUN: /* let mid layer handle it. */
break;
case CMD_DATA_OVERRUN:
dev_warn(&h->pdev->dev, "%p has"
" completed with data overrun "
"reported\n", c);
break;
case CMD_INVALID: {
/* print_bytes(c, sizeof(*c), 1, 0);
print_cmd(c); */
/* We get CMD_INVALID if you address a non-existent tape drive instead
of a selection timeout (no response). You will see this if you yank
out a tape drive, then try to access it. This is kind of a shame
because it means that any other CMD_INVALID (e.g. driver bug) will
get interpreted as a missing target. */
cmd->result = DID_NO_CONNECT << 16;
}
break;
case CMD_PROTOCOL_ERR:
dev_warn(&h->pdev->dev,
"%p has protocol error\n", c);
break;
case CMD_HARDWARE_ERR:
cmd->result = DID_ERROR << 16;
dev_warn(&h->pdev->dev,
"%p had hardware error\n", c);
break;
case CMD_CONNECTION_LOST:
cmd->result = DID_ERROR << 16;
dev_warn(&h->pdev->dev,
"%p had connection lost\n", c);
break;
case CMD_ABORTED:
cmd->result = DID_ABORT << 16;
dev_warn(&h->pdev->dev, "%p was aborted\n", c);
break;
case CMD_ABORT_FAILED:
cmd->result = DID_ERROR << 16;
dev_warn(&h->pdev->dev,
"%p reports abort failed\n", c);
break;
case CMD_UNSOLICITED_ABORT:
cmd->result = DID_ABORT << 16;
dev_warn(&h->pdev->dev, "%p aborted due to an "
"unsolicited abort\n", c);
break;
case CMD_TIMEOUT:
cmd->result = DID_TIME_OUT << 16;
dev_warn(&h->pdev->dev, "%p timedout\n", c);
break;
case CMD_UNABORTABLE:
cmd->result = DID_ERROR << 16;
dev_warn(&h->pdev->dev, "c %p command "
"unabortable\n", c);
break;
default:
cmd->result = DID_ERROR << 16;
dev_warn(&h->pdev->dev,
"%p returned unknown status %x\n", c,
ei->CommandStatus);
}
}
cmd->scsi_done(cmd);
scsi_cmd_free(h, c);
}
static int
cciss_scsi_detect(ctlr_info_t *h)
{
struct Scsi_Host *sh;
int error;
sh = scsi_host_alloc(&cciss_driver_template, sizeof(struct ctlr_info *));
if (sh == NULL)
goto fail;
sh->io_port = 0; // good enough? FIXME,
sh->n_io_port = 0; // I don't think we use these two...
sh->this_id = SELF_SCSI_ID;
sh->can_queue = cciss_tape_cmds;
sh->sg_tablesize = h->maxsgentries;
sh->max_cmd_len = MAX_COMMAND_SIZE;
((struct cciss_scsi_adapter_data_t *)
h->scsi_ctlr)->scsi_host = sh;
sh->hostdata[0] = (unsigned long) h;
sh->irq = h->intr[SIMPLE_MODE_INT];
sh->unique_id = sh->irq;
error = scsi_add_host(sh, &h->pdev->dev);
if (error)
goto fail_host_put;
scsi_scan_host(sh);
return 1;
fail_host_put:
scsi_host_put(sh);
fail:
return 0;
}
static void
cciss_unmap_one(struct pci_dev *pdev,
CommandList_struct *c,
size_t buflen,
int data_direction)
{
u64bit addr64;
addr64.val32.lower = c->SG[0].Addr.lower;
addr64.val32.upper = c->SG[0].Addr.upper;
pci_unmap_single(pdev, (dma_addr_t) addr64.val, buflen, data_direction);
}
static void
cciss_map_one(struct pci_dev *pdev,
CommandList_struct *c,
unsigned char *buf,
size_t buflen,
int data_direction)
{
__u64 addr64;
addr64 = (__u64) pci_map_single(pdev, buf, buflen, data_direction);
c->SG[0].Addr.lower =
(__u32) (addr64 & (__u64) 0x00000000FFFFFFFF);
c->SG[0].Addr.upper =
(__u32) ((addr64 >> 32) & (__u64) 0x00000000FFFFFFFF);
c->SG[0].Len = buflen;
c->Header.SGList = (__u8) 1; /* no. SGs contig in this cmd */
c->Header.SGTotal = (__u16) 1; /* total sgs in this cmd list */
}
static int
cciss_scsi_do_simple_cmd(ctlr_info_t *h,
CommandList_struct *c,
unsigned char *scsi3addr,
unsigned char *cdb,
unsigned char cdblen,
unsigned char *buf, int bufsize,
int direction)
{
DECLARE_COMPLETION_ONSTACK(wait);
c->cmd_type = CMD_IOCTL_PEND; /* treat this like an ioctl */
c->scsi_cmd = NULL;
c->Header.ReplyQueue = 0; /* unused in simple mode */
memcpy(&c->Header.LUN, scsi3addr, sizeof(c->Header.LUN));
c->Header.Tag.lower = c->busaddr; /* Use k. address of cmd as tag */
// Fill in the request block...
/* printk("Using scsi3addr 0x%02x%0x2%0x2%0x2%0x2%0x2%0x2%0x2\n",
scsi3addr[0], scsi3addr[1], scsi3addr[2], scsi3addr[3],
scsi3addr[4], scsi3addr[5], scsi3addr[6], scsi3addr[7]); */
memset(c->Request.CDB, 0, sizeof(c->Request.CDB));
memcpy(c->Request.CDB, cdb, cdblen);
c->Request.Timeout = 0;
c->Request.CDBLen = cdblen;
c->Request.Type.Type = TYPE_CMD;
c->Request.Type.Attribute = ATTR_SIMPLE;
c->Request.Type.Direction = direction;
/* Fill in the SG list and do dma mapping */
cciss_map_one(h->pdev, c, (unsigned char *) buf,
bufsize, DMA_FROM_DEVICE);
c->waiting = &wait;
enqueue_cmd_and_start_io(h, c);
wait_for_completion(&wait);
/* undo the dma mapping */
cciss_unmap_one(h->pdev, c, bufsize, DMA_FROM_DEVICE);
return(0);
}
static void
cciss_scsi_interpret_error(ctlr_info_t *h, CommandList_struct *c)
{
ErrorInfo_struct *ei;
ei = c->err_info;
switch(ei->CommandStatus)
{
case CMD_TARGET_STATUS:
dev_warn(&h->pdev->dev,
"cmd %p has completed with errors\n", c);
dev_warn(&h->pdev->dev,
"cmd %p has SCSI Status = %x\n",
c, ei->ScsiStatus);
if (ei->ScsiStatus == 0)
dev_warn(&h->pdev->dev,
"SCSI status is abnormally zero. "
"(probably indicates selection timeout "
"reported incorrectly due to a known "
"firmware bug, circa July, 2001.)\n");
break;
case CMD_DATA_UNDERRUN: /* let mid layer handle it. */
dev_info(&h->pdev->dev, "UNDERRUN\n");
break;
case CMD_DATA_OVERRUN:
dev_warn(&h->pdev->dev, "%p has"
" completed with data overrun "
"reported\n", c);
break;
case CMD_INVALID: {
/* controller unfortunately reports SCSI passthru's */
/* to non-existent targets as invalid commands. */
dev_warn(&h->pdev->dev,
"%p is reported invalid (probably means "
"target device no longer present)\n", c);
/* print_bytes((unsigned char *) c, sizeof(*c), 1, 0);
print_cmd(c); */
}
break;
case CMD_PROTOCOL_ERR:
dev_warn(&h->pdev->dev, "%p has protocol error\n", c);
break;
case CMD_HARDWARE_ERR:
/* cmd->result = DID_ERROR << 16; */
dev_warn(&h->pdev->dev, "%p had hardware error\n", c);
break;
case CMD_CONNECTION_LOST:
dev_warn(&h->pdev->dev, "%p had connection lost\n", c);
break;
case CMD_ABORTED:
dev_warn(&h->pdev->dev, "%p was aborted\n", c);
break;
case CMD_ABORT_FAILED:
dev_warn(&h->pdev->dev,
"%p reports abort failed\n", c);
break;
case CMD_UNSOLICITED_ABORT:
dev_warn(&h->pdev->dev,
"%p aborted due to an unsolicited abort\n", c);
break;
case CMD_TIMEOUT:
dev_warn(&h->pdev->dev, "%p timedout\n", c);
break;
case CMD_UNABORTABLE:
dev_warn(&h->pdev->dev,
"%p unabortable\n", c);
break;
default:
dev_warn(&h->pdev->dev,
"%p returned unknown status %x\n",
c, ei->CommandStatus);
}
}
static int
cciss_scsi_do_inquiry(ctlr_info_t *h, unsigned char *scsi3addr,
unsigned char page, unsigned char *buf,
unsigned char bufsize)
{
int rc;
CommandList_struct *c;
char cdb[6];
ErrorInfo_struct *ei;
unsigned long flags;
spin_lock_irqsave(&h->lock, flags);
c = scsi_cmd_alloc(h);
spin_unlock_irqrestore(&h->lock, flags);
if (c == NULL) { /* trouble... */
printk("cmd_alloc returned NULL!\n");
return -1;
}
ei = c->err_info;
cdb[0] = CISS_INQUIRY;
cdb[1] = (page != 0);
cdb[2] = page;
cdb[3] = 0;
cdb[4] = bufsize;
cdb[5] = 0;
rc = cciss_scsi_do_simple_cmd(h, c, scsi3addr, cdb,
6, buf, bufsize, XFER_READ);
if (rc != 0) return rc; /* something went wrong */
if (ei->CommandStatus != 0 &&
ei->CommandStatus != CMD_DATA_UNDERRUN) {
cciss_scsi_interpret_error(h, c);
rc = -1;
}
spin_lock_irqsave(&h->lock, flags);
scsi_cmd_free(h, c);
spin_unlock_irqrestore(&h->lock, flags);
return rc;
}
/* Get the device id from inquiry page 0x83 */
static int cciss_scsi_get_device_id(ctlr_info_t *h, unsigned char *scsi3addr,
unsigned char *device_id, int buflen)
{
int rc;
unsigned char *buf;
if (buflen > 16)
buflen = 16;
buf = kzalloc(64, GFP_KERNEL);
if (!buf)
return -1;
rc = cciss_scsi_do_inquiry(h, scsi3addr, 0x83, buf, 64);
if (rc == 0)
memcpy(device_id, &buf[8], buflen);
kfree(buf);
return rc != 0;
}
static int
cciss_scsi_do_report_phys_luns(ctlr_info_t *h,
ReportLunData_struct *buf, int bufsize)
{
int rc;
CommandList_struct *c;
unsigned char cdb[12];
unsigned char scsi3addr[8];
ErrorInfo_struct *ei;
unsigned long flags;
spin_lock_irqsave(&h->lock, flags);
c = scsi_cmd_alloc(h);
spin_unlock_irqrestore(&h->lock, flags);
if (c == NULL) { /* trouble... */
printk("cmd_alloc returned NULL!\n");
return -1;
}
memset(&scsi3addr[0], 0, 8); /* address the controller */
cdb[0] = CISS_REPORT_PHYS;
cdb[1] = 0;
cdb[2] = 0;
cdb[3] = 0;
cdb[4] = 0;
cdb[5] = 0;
cdb[6] = (bufsize >> 24) & 0xFF; //MSB
cdb[7] = (bufsize >> 16) & 0xFF;
cdb[8] = (bufsize >> 8) & 0xFF;
cdb[9] = bufsize & 0xFF;
cdb[10] = 0;
cdb[11] = 0;
rc = cciss_scsi_do_simple_cmd(h, c, scsi3addr,
cdb, 12,
(unsigned char *) buf,
bufsize, XFER_READ);
if (rc != 0) return rc; /* something went wrong */
ei = c->err_info;
if (ei->CommandStatus != 0 &&
ei->CommandStatus != CMD_DATA_UNDERRUN) {
cciss_scsi_interpret_error(h, c);
rc = -1;
}
spin_lock_irqsave(&h->lock, flags);
scsi_cmd_free(h, c);
spin_unlock_irqrestore(&h->lock, flags);
return rc;
}
static void
cciss_update_non_disk_devices(ctlr_info_t *h, int hostno)
{
/* the idea here is we could get notified from /proc
that some devices have changed, so we do a report
physical luns cmd, and adjust our list of devices
accordingly. (We can't rely on the scsi-mid layer just
doing inquiries, because the "busses" that the scsi
mid-layer probes are totally fabricated by this driver,
so new devices wouldn't show up.
the scsi3addr's of devices won't change so long as the
adapter is not reset. That means we can rescan and
tell which devices we already know about, vs. new
devices, vs. disappearing devices.
Also, if you yank out a tape drive, then put in a disk
in it's place, (say, a configured volume from another
array controller for instance) _don't_ poke this driver
(so it thinks it's still a tape, but _do_ poke the scsi
mid layer, so it does an inquiry... the scsi mid layer
will see the physical disk. This would be bad. Need to
think about how to prevent that. One idea would be to
snoop all scsi responses and if an inquiry repsonse comes
back that reports a disk, chuck it an return selection
timeout instead and adjust our table... Not sure i like
that though.
*/
#define OBDR_TAPE_INQ_SIZE 49
#define OBDR_TAPE_SIG "$DR-10"
ReportLunData_struct *ld_buff;
unsigned char *inq_buff;
unsigned char scsi3addr[8];
__u32 num_luns=0;
unsigned char *ch;
struct cciss_scsi_dev_t *currentsd, *this_device;
int ncurrent=0;
int reportlunsize = sizeof(*ld_buff) + CISS_MAX_PHYS_LUN * 8;
int i;
ld_buff = kzalloc(reportlunsize, GFP_KERNEL);
inq_buff = kmalloc(OBDR_TAPE_INQ_SIZE, GFP_KERNEL);
currentsd = kzalloc(sizeof(*currentsd) *
(CCISS_MAX_SCSI_DEVS_PER_HBA+1), GFP_KERNEL);
if (ld_buff == NULL || inq_buff == NULL || currentsd == NULL) {
printk(KERN_ERR "cciss: out of memory\n");
goto out;
}
this_device = ¤tsd[CCISS_MAX_SCSI_DEVS_PER_HBA];
if (cciss_scsi_do_report_phys_luns(h, ld_buff, reportlunsize) == 0) {
ch = &ld_buff->LUNListLength[0];
num_luns = ((ch[0]<<24) | (ch[1]<<16) | (ch[2]<<8) | ch[3]) / 8;
if (num_luns > CISS_MAX_PHYS_LUN) {
printk(KERN_WARNING
"cciss: Maximum physical LUNs (%d) exceeded. "
"%d LUNs ignored.\n", CISS_MAX_PHYS_LUN,
num_luns - CISS_MAX_PHYS_LUN);
num_luns = CISS_MAX_PHYS_LUN;
}
}
else {
printk(KERN_ERR "cciss: Report physical LUNs failed.\n");
goto out;
}
/* adjust our table of devices */
for (i = 0; i < num_luns; i++) {
/* for each physical lun, do an inquiry */
if (ld_buff->LUN[i][3] & 0xC0) continue;
memset(inq_buff, 0, OBDR_TAPE_INQ_SIZE);
memcpy(&scsi3addr[0], &ld_buff->LUN[i][0], 8);
if (cciss_scsi_do_inquiry(h, scsi3addr, 0, inq_buff,
(unsigned char) OBDR_TAPE_INQ_SIZE) != 0)
/* Inquiry failed (msg printed already) */
continue; /* so we will skip this device. */
this_device->devtype = (inq_buff[0] & 0x1f);
this_device->bus = -1;
this_device->target = -1;
this_device->lun = -1;
memcpy(this_device->scsi3addr, scsi3addr, 8);
memcpy(this_device->vendor, &inq_buff[8],
sizeof(this_device->vendor));
memcpy(this_device->model, &inq_buff[16],
sizeof(this_device->model));
memcpy(this_device->revision, &inq_buff[32],
sizeof(this_device->revision));
memset(this_device->device_id, 0,
sizeof(this_device->device_id));
cciss_scsi_get_device_id(h, scsi3addr,
this_device->device_id, sizeof(this_device->device_id));
switch (this_device->devtype)
{
case 0x05: /* CD-ROM */ {
/* We don't *really* support actual CD-ROM devices,
* just this "One Button Disaster Recovery" tape drive
* which temporarily pretends to be a CD-ROM drive.
* So we check that the device is really an OBDR tape
* device by checking for "$DR-10" in bytes 43-48 of
* the inquiry data.
*/
char obdr_sig[7];
strncpy(obdr_sig, &inq_buff[43], 6);
obdr_sig[6] = '\0';
if (strncmp(obdr_sig, OBDR_TAPE_SIG, 6) != 0)
/* Not OBDR device, ignore it. */
break;
}
/* fall through . . . */
case 0x01: /* sequential access, (tape) */
case 0x08: /* medium changer */
if (ncurrent >= CCISS_MAX_SCSI_DEVS_PER_HBA) {
printk(KERN_INFO "cciss%d: %s ignored, "
"too many devices.\n", h->ctlr,
scsi_device_type(this_device->devtype));
break;
}
currentsd[ncurrent] = *this_device;
ncurrent++;
break;
default:
break;
}
}
adjust_cciss_scsi_table(h, hostno, currentsd, ncurrent);
out:
kfree(inq_buff);
kfree(ld_buff);
kfree(currentsd);
return;
}
static int
is_keyword(char *ptr, int len, char *verb) // Thanks to ncr53c8xx.c
{
int verb_len = strlen(verb);
if (len >= verb_len && !memcmp(verb,ptr,verb_len))
return verb_len;
else
return 0;
}
static int
cciss_scsi_user_command(ctlr_info_t *h, int hostno, char *buffer, int length)
{
int arg_len;
if ((arg_len = is_keyword(buffer, length, "rescan")) != 0)
cciss_update_non_disk_devices(h, hostno);
else
return -EINVAL;
return length;
}
static int
cciss_scsi_proc_info(struct Scsi_Host *sh,
char *buffer, /* data buffer */
char **start, /* where data in buffer starts */
off_t offset, /* offset from start of imaginary file */
int length, /* length of data in buffer */
int func) /* 0 == read, 1 == write */
{
int buflen, datalen;
ctlr_info_t *h;
int i;
h = (ctlr_info_t *) sh->hostdata[0];
if (h == NULL) /* This really shouldn't ever happen. */
return -EINVAL;
if (func == 0) { /* User is reading from /proc/scsi/ciss*?/?* */
buflen = sprintf(buffer, "cciss%d: SCSI host: %d\n",
h->ctlr, sh->host_no);
/* this information is needed by apps to know which cciss
device corresponds to which scsi host number without
having to open a scsi target device node. The device
information is not a duplicate of /proc/scsi/scsi because
the two may be out of sync due to scsi hotplug, rather
this info is for an app to be able to use to know how to
get them back in sync. */
for (i = 0; i < ccissscsi[h->ctlr].ndevices; i++) {
struct cciss_scsi_dev_t *sd =
&ccissscsi[h->ctlr].dev[i];
buflen += sprintf(&buffer[buflen], "c%db%dt%dl%d %02d "
"0x%02x%02x%02x%02x%02x%02x%02x%02x\n",
sh->host_no, sd->bus, sd->target, sd->lun,
sd->devtype,
sd->scsi3addr[0], sd->scsi3addr[1],
sd->scsi3addr[2], sd->scsi3addr[3],
sd->scsi3addr[4], sd->scsi3addr[5],
sd->scsi3addr[6], sd->scsi3addr[7]);
}
datalen = buflen - offset;
if (datalen < 0) { /* they're reading past EOF. */
datalen = 0;
*start = buffer+buflen;
} else
*start = buffer + offset;
return(datalen);
} else /* User is writing to /proc/scsi/cciss*?/?* ... */
return cciss_scsi_user_command(h, sh->host_no,
buffer, length);
}
/* cciss_scatter_gather takes a struct scsi_cmnd, (cmd), and does the pci
dma mapping and fills in the scatter gather entries of the
cciss command, c. */
static void cciss_scatter_gather(ctlr_info_t *h, CommandList_struct *c,
struct scsi_cmnd *cmd)
{
unsigned int len;
struct scatterlist *sg;
__u64 addr64;
int request_nsgs, i, chained, sg_index;
struct cciss_scsi_adapter_data_t *sa = h->scsi_ctlr;
SGDescriptor_struct *curr_sg;
BUG_ON(scsi_sg_count(cmd) > h->maxsgentries);
chained = 0;
sg_index = 0;
curr_sg = c->SG;
request_nsgs = scsi_dma_map(cmd);
if (request_nsgs) {
scsi_for_each_sg(cmd, sg, request_nsgs, i) {
if (sg_index + 1 == h->max_cmd_sgentries &&
!chained && request_nsgs - i > 1) {
chained = 1;
sg_index = 0;
curr_sg = sa->cmd_sg_list[c->cmdindex];
}
addr64 = (__u64) sg_dma_address(sg);
len = sg_dma_len(sg);
curr_sg[sg_index].Addr.lower =
(__u32) (addr64 & 0x0FFFFFFFFULL);
curr_sg[sg_index].Addr.upper =
(__u32) ((addr64 >> 32) & 0x0FFFFFFFFULL);
curr_sg[sg_index].Len = len;
curr_sg[sg_index].Ext = 0;
++sg_index;
}
if (chained)
cciss_map_sg_chain_block(h, c,
sa->cmd_sg_list[c->cmdindex],
(request_nsgs - (h->max_cmd_sgentries - 1)) *
sizeof(SGDescriptor_struct));
}
/* track how many SG entries we are using */
if (request_nsgs > h->maxSG)
h->maxSG = request_nsgs;
c->Header.SGTotal = (__u8) request_nsgs + chained;
if (request_nsgs > h->max_cmd_sgentries)
c->Header.SGList = h->max_cmd_sgentries;
else
c->Header.SGList = c->Header.SGTotal;
return;
}
static int
cciss_scsi_queue_command_lck(struct scsi_cmnd *cmd, void (*done)(struct scsi_cmnd *))
{
ctlr_info_t *h;
int rc;
unsigned char scsi3addr[8];
CommandList_struct *c;
unsigned long flags;
// Get the ptr to our adapter structure (hba[i]) out of cmd->host.
// We violate cmd->host privacy here. (Is there another way?)
h = (ctlr_info_t *) cmd->device->host->hostdata[0];
rc = lookup_scsi3addr(h, cmd->device->channel, cmd->device->id,
cmd->device->lun, scsi3addr);
if (rc != 0) {
/* the scsi nexus does not match any that we presented... */
/* pretend to mid layer that we got selection timeout */
cmd->result = DID_NO_CONNECT << 16;
done(cmd);
/* we might want to think about registering controller itself
as a processor device on the bus so sg binds to it. */
return 0;
}
/* Ok, we have a reasonable scsi nexus, so send the cmd down, and
see what the device thinks of it. */
spin_lock_irqsave(&h->lock, flags);
c = scsi_cmd_alloc(h);
spin_unlock_irqrestore(&h->lock, flags);
if (c == NULL) { /* trouble... */
dev_warn(&h->pdev->dev, "scsi_cmd_alloc returned NULL!\n");
/* FIXME: next 3 lines are -> BAD! <- */
cmd->result = DID_NO_CONNECT << 16;
done(cmd);
return 0;
}
// Fill in the command list header
cmd->scsi_done = done; // save this for use by completion code
/* save c in case we have to abort it */
cmd->host_scribble = (unsigned char *) c;
c->cmd_type = CMD_SCSI;
c->scsi_cmd = cmd;
c->Header.ReplyQueue = 0; /* unused in simple mode */
memcpy(&c->Header.LUN.LunAddrBytes[0], &scsi3addr[0], 8);
c->Header.Tag.lower = c->busaddr; /* Use k. address of cmd as tag */
// Fill in the request block...
c->Request.Timeout = 0;
memset(c->Request.CDB, 0, sizeof(c->Request.CDB));
BUG_ON(cmd->cmd_len > sizeof(c->Request.CDB));
c->Request.CDBLen = cmd->cmd_len;
memcpy(c->Request.CDB, cmd->cmnd, cmd->cmd_len);
c->Request.Type.Type = TYPE_CMD;
c->Request.Type.Attribute = ATTR_SIMPLE;
switch(cmd->sc_data_direction)
{
case DMA_TO_DEVICE:
c->Request.Type.Direction = XFER_WRITE;
break;
case DMA_FROM_DEVICE:
c->Request.Type.Direction = XFER_READ;
break;
case DMA_NONE:
c->Request.Type.Direction = XFER_NONE;
break;
case DMA_BIDIRECTIONAL:
// This can happen if a buggy application does a scsi passthru
// and sets both inlen and outlen to non-zero. ( see
// ../scsi/scsi_ioctl.c:scsi_ioctl_send_command() )
c->Request.Type.Direction = XFER_RSVD;
// This is technically wrong, and cciss controllers should
// reject it with CMD_INVALID, which is the most correct
// response, but non-fibre backends appear to let it
// slide by, and give the same results as if this field
// were set correctly. Either way is acceptable for
// our purposes here.
break;
default:
dev_warn(&h->pdev->dev, "unknown data direction: %d\n",
cmd->sc_data_direction);
BUG();
break;
}
cciss_scatter_gather(h, c, cmd);
enqueue_cmd_and_start_io(h, c);
/* the cmd'll come back via intr handler in complete_scsi_command() */
return 0;
}
static DEF_SCSI_QCMD(cciss_scsi_queue_command)
static void cciss_unregister_scsi(ctlr_info_t *h)
{
struct cciss_scsi_adapter_data_t *sa;
struct cciss_scsi_cmd_stack_t *stk;
unsigned long flags;
/* we are being forcibly unloaded, and may not refuse. */
spin_lock_irqsave(&h->lock, flags);
sa = h->scsi_ctlr;
stk = &sa->cmd_stack;
/* if we weren't ever actually registered, don't unregister */
if (sa->registered) {
spin_unlock_irqrestore(&h->lock, flags);
scsi_remove_host(sa->scsi_host);
scsi_host_put(sa->scsi_host);
spin_lock_irqsave(&h->lock, flags);
}
/* set scsi_host to NULL so our detect routine will
find us on register */
sa->scsi_host = NULL;
spin_unlock_irqrestore(&h->lock, flags);
scsi_cmd_stack_free(h);
kfree(sa);
}
static int cciss_engage_scsi(ctlr_info_t *h)
{
struct cciss_scsi_adapter_data_t *sa;
struct cciss_scsi_cmd_stack_t *stk;
unsigned long flags;
spin_lock_irqsave(&h->lock, flags);
sa = h->scsi_ctlr;
stk = &sa->cmd_stack;
if (sa->registered) {
dev_info(&h->pdev->dev, "SCSI subsystem already engaged.\n");
spin_unlock_irqrestore(&h->lock, flags);
return -ENXIO;
}
sa->registered = 1;
spin_unlock_irqrestore(&h->lock, flags);
cciss_update_non_disk_devices(h, -1);
cciss_scsi_detect(h);
return 0;
}
static void
cciss_seq_tape_report(struct seq_file *seq, ctlr_info_t *h)
{
unsigned long flags;
CPQ_TAPE_LOCK(h, flags);
seq_printf(seq,
"Sequential access devices: %d\n\n",
ccissscsi[h->ctlr].ndevices);
CPQ_TAPE_UNLOCK(h, flags);
}
static int wait_for_device_to_become_ready(ctlr_info_t *h,
unsigned char lunaddr[])
{
int rc;
int count = 0;
int waittime = HZ;
CommandList_struct *c;
c = cmd_alloc(h);
if (!c) {
dev_warn(&h->pdev->dev, "out of memory in "
"wait_for_device_to_become_ready.\n");
return IO_ERROR;
}
/* Send test unit ready until device ready, or give up. */
while (count < 20) {
/* Wait for a bit. do this first, because if we send
* the TUR right away, the reset will just abort it.
*/
schedule_timeout_uninterruptible(waittime);
count++;
/* Increase wait time with each try, up to a point. */
if (waittime < (HZ * 30))
waittime = waittime * 2;
/* Send the Test Unit Ready */
rc = fill_cmd(h, c, TEST_UNIT_READY, NULL, 0, 0,
lunaddr, TYPE_CMD);
if (rc == 0)
rc = sendcmd_withirq_core(h, c, 0);
(void) process_sendcmd_error(h, c);
if (rc != 0)
goto retry_tur;
if (c->err_info->CommandStatus == CMD_SUCCESS)
break;
if (c->err_info->CommandStatus == CMD_TARGET_STATUS &&
c->err_info->ScsiStatus == SAM_STAT_CHECK_CONDITION) {
if (c->err_info->SenseInfo[2] == NO_SENSE)
break;
if (c->err_info->SenseInfo[2] == UNIT_ATTENTION) {
unsigned char asc;
asc = c->err_info->SenseInfo[12];
check_for_unit_attention(h, c);
if (asc == POWER_OR_RESET)
break;
}
}
retry_tur:
dev_warn(&h->pdev->dev, "Waiting %d secs "
"for device to become ready.\n",
waittime / HZ);
rc = 1; /* device not ready. */
}
if (rc)
dev_warn(&h->pdev->dev, "giving up on device.\n");
else
dev_warn(&h->pdev->dev, "device is ready.\n");
cmd_free(h, c);
return rc;
}
/* Need at least one of these error handlers to keep ../scsi/hosts.c from
* complaining. Doing a host- or bus-reset can't do anything good here.
* Despite what it might say in scsi_error.c, there may well be commands
* on the controller, as the cciss driver registers twice, once as a block
* device for the logical drives, and once as a scsi device, for any tape
* drives. So we know there are no commands out on the tape drives, but we
* don't know there are no commands on the controller, and it is likely
* that there probably are, as the cciss block device is most commonly used
* as a boot device (embedded controller on HP/Compaq systems.)
*/
static int cciss_eh_device_reset_handler(struct scsi_cmnd *scsicmd)
{
int rc;
CommandList_struct *cmd_in_trouble;
unsigned char lunaddr[8];
ctlr_info_t *h;
/* find the controller to which the command to be aborted was sent */
h = (ctlr_info_t *) scsicmd->device->host->hostdata[0];
if (h == NULL) /* paranoia */
return FAILED;
dev_warn(&h->pdev->dev, "resetting tape drive or medium changer.\n");
/* find the command that's giving us trouble */
cmd_in_trouble = (CommandList_struct *) scsicmd->host_scribble;
if (cmd_in_trouble == NULL) /* paranoia */
return FAILED;
memcpy(lunaddr, &cmd_in_trouble->Header.LUN.LunAddrBytes[0], 8);
/* send a reset to the SCSI LUN which the command was sent to */
rc = sendcmd_withirq(h, CCISS_RESET_MSG, NULL, 0, 0, lunaddr,
TYPE_MSG);
if (rc == 0 && wait_for_device_to_become_ready(h, lunaddr) == 0)
return SUCCESS;
dev_warn(&h->pdev->dev, "resetting device failed.\n");
return FAILED;
}
static int cciss_eh_abort_handler(struct scsi_cmnd *scsicmd)
{
int rc;
CommandList_struct *cmd_to_abort;
unsigned char lunaddr[8];
ctlr_info_t *h;
/* find the controller to which the command to be aborted was sent */
h = (ctlr_info_t *) scsicmd->device->host->hostdata[0];
if (h == NULL) /* paranoia */
return FAILED;
dev_warn(&h->pdev->dev, "aborting tardy SCSI cmd\n");
/* find the command to be aborted */
cmd_to_abort = (CommandList_struct *) scsicmd->host_scribble;
if (cmd_to_abort == NULL) /* paranoia */
return FAILED;
memcpy(lunaddr, &cmd_to_abort->Header.LUN.LunAddrBytes[0], 8);
rc = sendcmd_withirq(h, CCISS_ABORT_MSG, &cmd_to_abort->Header.Tag,
0, 0, lunaddr, TYPE_MSG);
if (rc == 0)
return SUCCESS;
return FAILED;
}
#else /* no CONFIG_CISS_SCSI_TAPE */
/* If no tape support, then these become defined out of existence */
#define cciss_scsi_setup(cntl_num)
#define cciss_engage_scsi(h)
#endif /* CONFIG_CISS_SCSI_TAPE */
|
the_stack_data/32950292.c | #define N 30
int fn5_i(int a1, int a2){
int tmp_a1,tmp_a2;
int rtn = 0;
if(a1 > 1000 && a2 > 1000){
tmp_a1 = a1 % 1000;
tmp_a2 = a2 % 1000;
}else if(a1 > 1000 || a2 > 1000){
if(a1 > a2){
tmp_a1 = a1 % 1000;
}else{
tmp_a2 = a2 % 1000;
}
}else{
tmp_a1 = a1;
tmp_a2 = a2;
}
if(tmp_a1 < 0)
tmp_a1 = (-1) * tmp_a1;
if(tmp_a2 < 0)
tmp_a2 = (-1) * tmp_a2;
tmp_a1++;
while(rtn < 30){
rtn += tmp_a2 / tmp_a1;
tmp_a2++;
}
return rtn;
}
int main(){
int result_i[N];
int start_i = 3;
int tmp_i = 0;
int i,a1,a2;
for(i=0; i<N; i++){
if(i==0){
tmp_i = fn5_i(start_i,N);
result_i[i] = tmp_i;
}
else if(i==1){
a1 = result_i[0];
tmp_i = fn5_i(a1,a1);
result_i[i] = tmp_i;
}
else{
a1 = result_i[i-1] - 1;
a2 = result_i[i-2] - 2;
if(a1 > a2){
tmp_i = fn5_i(a2,a1);
}
else{
tmp_i = fn5_i(a1,a2);
}
result_i[i] = tmp_i;
}
}
return 0;
}
|
the_stack_data/16596.c | #include <assert.h>
#include <limits.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
typedef struct
{
unsigned id, value, weight;
} Item;
typedef struct
{
uint_least32_t items;
unsigned value, weight;
} Package;
static inline void packageAddItem(Package* const package,
const Item* const item)
{
assert(package && item && item->id);
package->items |= (1 << (item->id - 1));
package->value += item->value;
package->weight += item->weight;
}
static void doGetBestPackage(const Item* const items,
const size_t itemCount,
const size_t itemIndex,
const unsigned boxCapacity,
Package* const result)
{
assert(items && itemCount && boxCapacity && result);
if(itemIndex == itemCount) return;
const Item* const item = &items[itemIndex];
const size_t nextItemIndex = (itemIndex + 1);
if(boxCapacity < item->weight)
{
doGetBestPackage(items, itemCount, nextItemIndex, boxCapacity, result);
return;
}
Package take = {0}, pass = {0};
// Take the item.
{
const size_t newBoxCapacity = (boxCapacity - item->weight);
doGetBestPackage(items, itemCount, nextItemIndex, newBoxCapacity, &take);
packageAddItem(&take, item);
}
// Pass on the item.
doGetBestPackage(items, itemCount, nextItemIndex, boxCapacity, &pass);
// No difference in value.
if(take.value == pass.value)
{
// Keep the item with the smaller weight.
*result = ((take.weight < pass.weight) ? take : pass);
}
// Keep the item with the larger value.
else *result = ((take.value > pass.value) ? take : pass);
}
static void getBestPackage(const Item* const items,
const size_t itemCount,
const unsigned boxCapacity,
Package* const result)
{
assert(items && itemCount && boxCapacity && result);
doGetBestPackage(items, itemCount, 0, boxCapacity, result);
}
static void packageDumpContents(const Package* const package,
FILE* const outputStream)
{
assert(package && outputStream && !ferror(outputStream));
// No item IDs.
if(!package->items)
{
fputs("-\n", outputStream);
return;
}
static const size_t maskBitCount = (sizeof(uint_least32_t) * CHAR_BIT);
size_t i = 0;
// Advance to first item ID.
while(!(package->items & (1 << i))) ++i;
fprintf(outputStream, "%zu", (i + 1));
// Dump any remaining item IDs.
for(++i; i < maskBitCount; ++i) if(package->items & (1 << i))
{
fprintf(outputStream, ",%zu", (i + 1));
}
fputc('\n', outputStream);
}
int main(const int argc, const char* const argv[])
{
// Getting away with no error checking throughout because CodeEval makes some
// strong guarantees about our runtime environment. No need to pay when we're
// being benchmarked. Don't forget to define NDEBUG prior to submitting!
assert(argc >= 2 && "Expecting at least one command-line argument.");
static char stdoutBuffer[256] = "";
// Turn on full output buffering for stdout.
setvbuf(stdout, stdoutBuffer, _IOFBF, sizeof stdoutBuffer);
FILE* inputStream = fopen(argv[1], "r");
assert(inputStream && "Failed to open input stream.");
for(char lineBuffer[512] = "", * cursor = lineBuffer;
fgets(lineBuffer, sizeof lineBuffer, inputStream);
cursor = lineBuffer)
{
int bytesRead = 0;
unsigned boxCapacity = 0;
if(sscanf(lineBuffer, "%u", &boxCapacity) == 1)
{
boxCapacity *= 100;
// Advance to the head of the item list.
while(*cursor && *cursor++ != ':');
assert(*cursor);
Item items[32] = {{0}};
size_t itemCount = 0;
// Fetch item pool.
{
unsigned id = 0;
double value = 0, weight = 0;
static const char* const itemFormat = "%*[^(](%u,%lf,$%lf)%n";
for(int bytesRead = 0;
sscanf(cursor, itemFormat, &id, &weight, &value, &bytesRead) == 3;
cursor += bytesRead)
{
// As per the problem statement.
assert(id < 16);
assert(itemCount < (sizeof items / sizeof *items));
Item* const item = &items[itemCount++];
item->id = id;
item->weight = (weight * 100);
item->value = (value * 100);
}
// As per the problem statement.
assert(itemCount < 16);
}
Package optimalPackage = {0};
getBestPackage(items, itemCount, boxCapacity, &optimalPackage);
packageDumpContents(&optimalPackage, stdout);
}
}
// The CRT takes care of cleanup.
}
|
the_stack_data/139761.c | int main(){
int a,b,c;
a = 5;
b = 5;
c = a ^ b;
return c;
}
|
the_stack_data/95450769.c | #include <unistd.h>
#include "syscall.h"
int sethostname(const char *name, size_t len)
{
return syscall(SYS_sethostname, name, len);
}
|
the_stack_data/559683.c | /*
* @f ccnl-ext-http.c
* @b CCN lite extension: web server to display the relay's status
*
* Copyright (C) 2013, Christian Tschudin, University of Basel
*
* Permission to use, copy, modify, and/or 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.
*
* File history:
* 2013-04-11 created
*/
void null_func(void);
#ifdef USE_HTTP_STATUS
#include "ccnl-http-status.h"
#include "ccnl-os-time.h"
// ----------------------------------------------------------------------
struct ccnl_http_s*
ccnl_http_new(struct ccnl_relay_s *ccnl, int serverport)
{
int s, i = 1;
struct sockaddr_in me;
struct ccnl_http_s *http;
(void) ccnl;
s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (!s) {
DEBUGMSG(INFO, "could not create socket for http server\n");
return NULL;
}
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
me.sin_family = AF_INET;
me.sin_port = htons(serverport);
me.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(s, (struct sockaddr*) &me, sizeof(me)) < 0) {
close(s);
DEBUGMSG(INFO, "could not bind socket for http server\n");
return NULL;
}
listen(s, 2);
http = (struct ccnl_http_s*) ccnl_calloc(1, sizeof(*http));
if (!http) {
close(s);
return NULL;
}
http->server = s;
DEBUGMSG(INFO, "HTTP status server listening at TCP port %d\n", serverport);
return http;
}
struct ccnl_http_s*
ccnl_http_cleanup(struct ccnl_http_s *http)
{
if (!http)
return NULL;
if (http->server)
close(http->server);
if (http->client)
close(http->client);
ccnl_free(http);
return NULL;
}
int
ccnl_http_anteselect(struct ccnl_relay_s *ccnl, struct ccnl_http_s *http,
fd_set *readfs, fd_set *writefs, int *maxfd)
{
(void) ccnl;
if (!http)
return -1;
if (!http->client) {
FD_SET(http->server, readfs);
if (*maxfd <= http->server)
*maxfd = http->server + 1;
} else {
if ((unsigned long)http->inlen < sizeof(http->in))
FD_SET(http->client, readfs);
if (http->outlen > 0)
FD_SET(http->client, writefs);
if (*maxfd <= http->client)
*maxfd = http->client + 1;
}
return 0;
}
int
ccnl_http_postselect(struct ccnl_relay_s *ccnl, struct ccnl_http_s *http,
fd_set *readfs, fd_set *writefs)
{
if (!http)
return -1;
// accept only one client at the time:
if (!http->client && FD_ISSET(http->server, readfs)) {
struct sockaddr_in peer;
socklen_t len = sizeof(peer);
http->client = accept(http->server, (struct sockaddr*) &peer, &len);
if (http->client < 0)
http->client = 0;
else {
DEBUGMSG(INFO, "accepted web server client %s\n",
ccnl_addr2ascii((sockunion*)&peer));
http->inlen = http->outlen = http->inoffs = http->outoffs = 0;
}
}
if (http->client && FD_ISSET(http->client, readfs)) {
int len = sizeof(http->in) - http->inlen - 1;
len = recv(http->client, http->in + http->inlen, len, 0);
if (len == 0) {
DEBUGMSG(INFO, "web client went away\n");
close(http->client);
http->client = 0;
} else if (len > 0) {
http->in[len] = 0;
ccnl_http_status(ccnl, http);
}
}
if (http->client && FD_ISSET(http->client, writefs) && http->out) {
int len = send(http->client, http->out + http->outoffs,
http->outlen, 0);
if (len > 0) {
http->outlen -= len;
http->outoffs += len;
if (http->outlen == 0) {
close(http->client);
http->client = 0;
}
}
}
return 0;
}
int
ccnl_cmpfaceid(const void *a, const void *b)
{
int aa = (*(struct ccnl_face_s**)a)->faceid;
int bb = (*(struct ccnl_face_s**)b)->faceid;
return aa - bb;
}
int
ccnl_cmpfib(const void *a, const void *b)
{
struct ccnl_prefix_s *p1 = (*(struct ccnl_forward_s**)a)->prefix;
struct ccnl_prefix_s *p2 = (*(struct ccnl_forward_s**)b)->prefix;
int r;
size_t len;
uint32_t i; //TODO: Is uint32_t correct here?
for (i = 0; ; i++) {
if (p1->compcnt <= i) {
return p2->compcnt <= i ? 0 : -1;
}
if (p2->compcnt <= i) {
return 1;
}
len = p1->complen[i];
if (len > p2->complen[i]) {
len = p2->complen[i];
}
r = memcmp(p1->comp[i], p2->comp[i], len);
if (r) {
return r;
}
if (p1->complen[i] > len) {
return 1;
}
if (p2->complen[i] > len) {
return -1;
}
}
return 0;
}
int
ccnl_http_status(struct ccnl_relay_s *ccnl, struct ccnl_http_s *http)
{
static char txt[64000];
char *hdr =
"HTTP/1.1 200 OK\n\r"
"Content-Type: text/html; charset=utf-8\n\r"
"Connection: close\n\r\n\r", *cp;
size_t len = strlen(hdr);
int i, j, cnt;
time_t t;
//struct utsname uts;
struct ccnl_face_s *f;
struct ccnl_forward_s *fwd;
struct ccnl_interest_s *ipt;
struct ccnl_buf_s *bpt;
char s[CCNL_MAX_PREFIX_SIZE];
strcpy(txt, hdr);
len += sprintf(txt+len,
"<html><head><title>ccn-lite-relay status</title>\n"
"<style type=\"text/css\">\n"
"body {font-family: sans-serif;}\n"
"</style>\n"
"</head><body>\n");
len += sprintf(txt+len, "\n<table borders=0>\n<tr><td>"
"<a href=\"\">[refresh]</a> <td>"
"ccn-lite-relay Status Page ");
//uname(&uts);
//len += sprintf(txt+len, "node <strong>%s (%d)</strong>\n",
// uts.nodename, getpid());
t = time(NULL);
cp = ctime(&t);
cp[strlen(cp)-1] = 0;
len += sprintf(txt+len, "<tr><td><td><font size=-1>%s ", cp);
cp = ctime(&ccnl->startup_time);
cp[strlen(cp)-1] = 0;
len += sprintf(txt+len, " (started %s)</font>\n</table>\n", cp);
len += sprintf(txt+len, "\n<p><table borders=0 width=100%% bgcolor=#e0e0ff>"
"<tr><td><em>Forwarding table</em></table><ul>\n");
for (fwd = ccnl->fib, cnt = 0; fwd; fwd = fwd->next, cnt++);
if (cnt > 0) {
struct ccnl_forward_s **fwda;
fwda = (struct ccnl_forward_s**) ccnl_malloc(cnt * sizeof(fwd));
for (fwd = ccnl->fib, i = 0; fwd; fwd = fwd->next, i++)
fwda[i] = fwd;
qsort(fwda, cnt, sizeof(fwd), ccnl_cmpfib);
for (i = 0; i < cnt; i++) {
char fname[16];
#ifdef USE_ECHO
if (fwda[i]->tap)
strcpy(fname, "'echoserver'");
else
#endif
if(fwda[i]->face)
sprintf(fname, "f%d", fwda[i]->face->faceid);
else
sprintf(fname, "?");
len += sprintf(txt+len,
"<li>via %4s: <font face=courier>%s</font>\n",
fname, ccnl_prefix_to_str(fwda[i]->prefix,s,CCNL_MAX_PREFIX_SIZE));
}
ccnl_free(fwda);
}
len += sprintf(txt+len, "</ul>\n");
len += sprintf(txt+len, "\n<p><table borders=0 width=100%% bgcolor=#e0e0ff>"
"<tr><td><em>Faces</em></table><ul>\n");
for (f = ccnl->faces, cnt = 0; f; f = f->next, cnt++);
if (cnt > 0) {
struct ccnl_face_s **fa;
fa = (struct ccnl_face_s**) ccnl_malloc(cnt * sizeof(f));
for (f = ccnl->faces, i = 0; f; f = f->next, i++)
fa[i] = f;
qsort(fa, cnt, sizeof(f), ccnl_cmpfaceid);
for (i = 0; i < cnt; i++) {
len += sprintf(txt+len,
"<li><strong>f%d</strong> (via i%d) "
"peer=<font face=courier>%s</font> ttl=",
fa[i]->faceid, fa[i]->ifndx,
ccnl_addr2ascii(&(fa[i]->peer)));
if (fa[i]->flags & CCNL_FACE_FLAGS_STATIC)
len += sprintf(txt+len, "static");
else
len += sprintf(txt+len, "%.1fsec",
fa[i]->last_used + CCNL_FACE_TIMEOUT - CCNL_NOW());
for (j = 0, bpt = fa[i]->outq; bpt; bpt = bpt->next, j++);
len += sprintf(txt+len, " qlen=%d\n", j);
}
ccnl_free(fa);
}
len += sprintf(txt+len, "</ul>\n");
len += sprintf(txt+len, "\n<p><table borders=0 width=100%% bgcolor=#e0e0ff>"
"<tr><td><em>Interfaces</em></table><ul>\n");
for (i = 0; i < ccnl->ifcount; i++) {
#ifdef USE_STATS
len += sprintf(txt+len, "<li><strong>i%d</strong> "
"addr=<font face=courier>%s</font> "
"qlen=%zu/%d"
" rx=%u tx=%u"
"\n",
i, ccnl_addr2ascii(&ccnl->ifs[i].addr),
ccnl->ifs[i].qlen, CCNL_MAX_IF_QLEN,
ccnl->ifs[i].rx_cnt, ccnl->ifs[i].tx_cnt);
#else
len += sprintf(txt+len, "<li><strong>i%d</strong> "
"addr=<font face=courier>%s</font> "
"qlen=%d/%d"
"\n",
i, ccnl_addr2ascii(&ccnl->ifs[i].addr),
ccnl->ifs[i].qlen, CCNL_MAX_IF_QLEN);
#endif
}
len += sprintf(txt+len, "</ul>\n");
len += sprintf(txt+len, "\n<p><table borders=0 width=100%% bgcolor=#e0e0ff>"
"<tr><td><em>Misc stats</em></table><ul>\n");
for (cnt = 0, bpt = ccnl->nonces; bpt; bpt = bpt->next, cnt++);
len += sprintf(txt+len, "<li>Nonces: %d\n", cnt);
for (cnt = 0, ipt = ccnl->pit; ipt; ipt = ipt->next, cnt++);
len += sprintf(txt+len, "<li>Pending interests: %d\n", cnt);
len += sprintf(txt+len, "<li>Content chunks: %d (max=%d)\n",
ccnl->contentcnt, ccnl->max_cache_entries);
len += sprintf(txt+len, "</ul>\n");
len += sprintf(txt+len, "\n<p><table borders=0 width=100%% bgcolor=#e0e0ff>"
"<tr><td><em>Config</em></table><table borders=0>\n");
len += sprintf(txt+len, "<tr><td>content.timeout:"
"<td align=right> %d<td>\n", CCNL_CONTENT_TIMEOUT);
len += sprintf(txt+len, "<tr><td>face.timeout:"
"<td align=right> %d<td>\n", CCNL_FACE_TIMEOUT);
len += sprintf(txt+len, "<tr><td>interest.maxretransmit:"
"<td align=right> %d<td>\n", CCNL_MAX_INTEREST_RETRANSMIT);
len += sprintf(txt+len, "<tr><td>interest.timeout:"
"<td align=right> %d<td>\n", CCNL_INTEREST_TIMEOUT);
len += sprintf(txt+len, "<tr><td>nonces.max:"
"<td align=right> %d<td>\n", CCNL_MAX_NONCES);
//len += sprintf(txt+len, "<tr><td>compile.featureset:<td><td> %s\n",
// compile_string);
len += sprintf(txt+len, "<tr><td>compile.time:"
"<td><td>%s %s\n", __DATE__, __TIME__);
len += sprintf(txt+len, "<tr><td>compile.ccnl_core_version:"
"<td><td>%s\n", CCNL_VERSION);
len += sprintf(txt+len, "</table>\n");
len += sprintf(txt+len, "\n<p><hr></body></html>\n");
http->out = (unsigned char*) txt;
http->outoffs = 0;
http->outlen = len;
return 0;
}
#endif // USE_HTTP_STATUS
// eof
|
the_stack_data/1995.c | int main() {
unsigned long t1 = ((unsigned long long)-2) / 2;
return t1 == 9223372036854775807;
}
|
the_stack_data/30158.c | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
int Maximum(int a[], int f, int l)
{
int mid;
int m1, m2;
if(f==l)
return a[f];
else
{
mid=(f+l)/2;
m1=Maximum(a,f,mid);
m2=Maximum(a,mid+1,l);
if (m1>m2)
return m1;
else
return m2;
}
}
int Minimum(int a[], int f, int l)
{
int mid;
int m1, m2;
if(f==l)
return a[f];
else
{
mid=(f+l)/2;
m1=Minimum(a,f,mid);
m2=Minimum(a,mid+1,l);
if (m1<m2)
return m1;
else
return m2;
}
}
int check(char x[])
{
int l=strlen(x);
int i;
int f=1;
for(i=0;i<l && f==1;i++)
{
if(!isdigit(x[i]))
f=0;
}
return f;
}
void main()
{
int n, *a, i;
char x[100];
int max, min;
while(1)
{
printf("Enter the size of the array=> ");
scanf("%d",&n);
fflush(stdin);
if(n>0)
break;
else
{
printf("Invalid Input\n");
}
}
printf("Enter the datas in the Array\n");
for(i=0;i<n;i++)
{
while(1)
{
scanf("%100s",&x);
fflush(stdin);
if(check(x)==1)
break;
else
{
printf("Invalid Input\n");
}
}
int d=atoi(x);
a[i]=d;
}
max=Maximum(a,0,n-1);
min=Minimum(a,0,n-1);
printf("Maximum=>%d Minimum=>%d",max,min);
}
|
the_stack_data/34511523.c | int a[2 * 2];
int b[2 * 2];
int c[2 * 2];
int kP;
void Mult() {
int i, j, k;
i = 0;
while (i < 4) {
c[i] = 0;
i = i + 1;
}
i = 0;
while (i < 2) {
j = 0;
while (j < 2) {
k = 0;
while (k < 2) {
c[i * 2 + j] = c[i * 2 + j] + a[i * 2 + k] * b[k * 2 + j];
c[i * 2 + j] = c[i * 2 + j] - (c[i * 2 + j] / kP) * kP;
k = k + 1;
}
j = j + 1;
}
i = i + 1;
}
}
int n;
int Fib() {
int x[2 * 2], y[2 * 2], i;
x[0] = 1;
x[1] = 1;
x[2] = 1;
x[3] = 0;
y[0] = 1;
y[1] = 0;
y[2] = 0;
y[3] = 1;
while (n > 0) {
int bit;
bit = n - n / 2 * 2;
if (bit) {
i = 0;
while (i < 4) {
a[i] = y[i];
b[i] = x[i];
i = i + 1;
}
Mult();
i = 0;
while (i < 4) {
y[i] = c[i];
i = i + 1;
}
}
i = 0;
while (i < 4) {
a[i] = x[i];
b[i] = x[i];
i = i + 1;
}
Mult();
i = 0;
while (i < 4) {
x[i] = c[i];
i = i + 1;
}
n = n / 2;
}
return y[0];
}
int MAIN() {
int m;
kP = 10003;
m = 1;
while (m <= 10) {
n = m;
write(Fib());
write("\n");
m = m + 1;
}
while (m <= 1000000000) {
n = m;
write(Fib());
write("\n");
m = m * 10;
}
}
|
the_stack_data/399075.c | // 02. Write a program that displays the first 100 prime numbers.
#include <stdio.h>
int main()
{
int number = 2;
if (number < 4)
{
printf("%i, ", number);
number++;
}
while (number < 101)
{
printf("%i, ", number);
number = number + 2;
}
} |
the_stack_data/59892.c | #include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFLEN 255
int main(int argc, char **argv) {
struct sockaddr_in peeraddr, myaddr;
int sockfd;
char recmsg[BUFLEN + 1];
unsigned int socklen;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
printf("socket creating error\n");
exit(EXIT_FAILURE);
}
socklen = sizeof(struct sockaddr_in);
memset(&peeraddr, 0, socklen);
peeraddr.sin_family = AF_INET;
peeraddr.sin_port = htons(7838);
if (argv[1]) {
if (inet_pton(AF_INET, argv[1], &peeraddr.sin_addr) <= 0) {
printf("wrong group address!\n");
exit(EXIT_FAILURE);
}
} else {
printf("no group address!\n");
exit(EXIT_FAILURE);
}
memset(&myaddr, 0, socklen);
myaddr.sin_family = AF_INET;
myaddr.sin_port = htons(23456);
if (argv[2]) {
if (inet_pton(AF_INET, argv[2], &myaddr.sin_addr) <= 0) {
printf("self ip address error!\n");
exit(EXIT_FAILURE);
}
} else {
myaddr.sin_addr.s_addr = INADDR_ANY;
}
if (bind(sockfd, (struct sockaddr *) &myaddr, sizeof(struct sockaddr_in)) == -1) {
printf("Bind error\n");
exit(EXIT_FAILURE);
}
for (;;) {
bzero(recmsg, BUFLEN + 1);
printf("input message to send:");
if (fgets(recmsg, BUFLEN, stdin) == (char *) EOF) {
exit(EXIT_FAILURE);
};
if (sendto(sockfd, recmsg, strlen(recmsg), 0, (struct sockaddr *) &peeraddr,
sizeof(struct sockaddr_in)) < 0) {
printf("sendto error!\n");
exit(EXIT_FAILURE);;
}
printf("sned message:%s", recmsg);
}
}
|
the_stack_data/145453488.c | /*
* SDMMD_AFC.c
* SDMMobileDevice
*
* Copyright (c) 2014, Sam Marshall
* 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 Sam Marshall nor the names of its contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef _SDM_MD_AFC_C_
#define _SDM_MD_AFC_C_
#if 0
#include "SDMMD_Functions.h"
#include "SDMMD_AFC.h"
#include <string.h>
#include "Core.h"
sdmmd_return_t SDMMD_check_can_touch(SDMMD_AFCConnectionRef conn, CFDataRef *unknown) {
SDMMD_AFCOperationRef fileInfo = SDMMD_AFCOperationCreateGetFileInfo((CFStringRef)*unknown);
SDMMD_AFCOperationRef reply;
SDMMD_AFCProcessOperation(conn, fileInfo, &reply);
*unknown = SDMMD_GetDataResponseFromOperation(reply);
return kAMDSuccess;
}
SDMMD_AFCConnectionRef SDMMD_AFCConnectionCreate(SDMMD_AMConnectionRef conn) {
SDMMD_AFCConnectionRef afc = calloc(1, sizeof(struct sdmmd_AFCConnectionClass));
if (afc != NULL) {
afc->handle = conn;
CFStringRef udidString = SDMMD_AMDeviceCopyUDID(conn->ivars.device);
CFStringRef date_string = SDMCreateCurrentDateString();
char *dateString = SDMCFStringGetString(date_string);
CFSafeRelease(date_string);
CFStringRef name = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%s.%@.%s"), "com.samdmarshall.sdmmobiledevice.afc", udidString, dateString);
CFSafeRelease(udidString);
Safe(free, dateString);
char *queueName = SDMCFStringGetString(name);
afc->operationQueue = dispatch_queue_create(queueName, NULL);
Safe(free, queueName);
afc->operationCount = 0;
}
return afc;
}
void SDMMD_AFCConnectionRelease(SDMMD_AFCConnectionRef conn) {
if (conn) {
CFSafeRelease(conn->handle);
dispatch_release(conn->operationQueue);
}
}
void SDMMD_AFCHeaderInit(SDMMD_AFCPacketHeader *header, uint32_t command, uint32_t size, uint32_t data, uint32_t pack_num) {
header->signature = 0x4141504c36414643;
header->headerLen = size;
header->packetLen = data+size;
header->type = command;
if (pack_num) {
header->pid = pack_num;
} else {
header->pid = k64BitMask; // but not always? this is really weird
}
}
#pragma mark -
#pragma mark Operations
SDMMD_AFCOperationRef SDMMD_AFCOperationCreateReadDirectory(CFStringRef path) { // _AFCOperationCreateReadDirectory
SDMMD_AFCOperationRef op = calloc(1, sizeof(struct sdmmd_AFCOperation));
op->packet = calloc(1, sizeof(struct sdmmd_AFCPacket));
char *cpath = SDMCFStringGetString(path);
uint32_t data_length = (uint32_t)strlen(cpath)+1;
op->packet->data = calloc(data_length, sizeof(char));
memcpy(op->packet->data, cpath, data_length);
SDMMD_AFCHeaderInit(&(op->packet->header), SDMMD_AFC_Packet_ReadDirectory, data_length+sizeof(struct SDMMD_AFCPacketHeader), 0x0, 0x0);
free(cpath);
return op;
}
#if 0
SDMMD_AFCOperationRef SDMMD_AFCOperationCreateReadFile(CFStringRef path) {
SDMMD_AFCOperationRef op = calloc(1, sizeof(struct sdmmd_AFCOperation));
op->packet = calloc(1, sizeof(struct sdmmd_AFCPacket));
SDMMD_AFCHeaderInit(&(op->packet->header), SDMMD_AFC_Packet_ReadFile, sizeof(struct sdmmd_AFCPacket), 0x0, 0x0);
return op;
}
SDMMD_AFCOperationRef SDMMD_AFCOperationCreateWriteFile() {
SDMMD_AFCOperationRef op = calloc(1, sizeof(struct sdmmd_AFCOperation));
op->packet = calloc(1, sizeof(struct sdmmd_AFCPacket));
SDMMD_AFCHeaderInit(&(op->packet->header), SDMMD_AFC_Packet_WriteFile, sizeof(struct sdmmd_AFCPacket), 0x0, 0x0);
return op;
}
SDMMD_AFCOperationRef SDMMD_AFCOperationCreateWritePart() {
SDMMD_AFCOperationRef op = calloc(1, sizeof(struct sdmmd_AFCOperation));
op->packet = calloc(1, sizeof(struct sdmmd_AFCPacket));
SDMMD_AFCHeaderInit(&(op->packet->header), SDMMD_AFC_Packet_WritePart, sizeof(struct sdmmd_AFCPacket), 0x0, 0x0);
return op;
}
SDMMD_AFCOperationRef SDMMD_AFCOperationCreateTruncFile() {
SDMMD_AFCOperationRef op = calloc(1, sizeof(struct sdmmd_AFCOperation));
op->packet = calloc(1, sizeof(struct sdmmd_AFCPacket));
SDMMD_AFCHeaderInit(&(op->packet->header), SDMMD_AFC_Packet_TruncFile, sizeof(struct sdmmd_AFCPacket), 0x0, 0x0);
return op;
}
#endif
SDMMD_AFCOperationRef SDMMD_AFCOperationCreateRemovePath(CFStringRef path) {
SDMMD_AFCOperationRef op = calloc(1, sizeof(struct sdmmd_AFCOperation));
op->packet = calloc(1, sizeof(struct sdmmd_AFCPacket));
char *cpath = SDMCFStringGetString(path);
uint32_t data_length = (uint32_t)strlen(cpath)+1;
op->packet->data = calloc(data_length, sizeof(char));
memcpy(op->packet->data, cpath, data_length);
SDMMD_AFCHeaderInit(&(op->packet->header), SDMMD_AFC_Packet_RemovePath, data_length+sizeof(struct SDMMD_AFCPacketHeader), 0x0, 0x0);
free(cpath);
return op;
}
SDMMD_AFCOperationRef SDMMD_AFCOperationCreateMakeDirectory(CFStringRef path) {
SDMMD_AFCOperationRef op = calloc(1, sizeof(struct sdmmd_AFCOperation));
op->packet = calloc(1, sizeof(struct sdmmd_AFCPacket));
char *cpath = SDMCFStringGetString(path);
uint32_t data_length = (uint32_t)strlen(cpath)+1;
op->packet->data = calloc(data_length, sizeof(char));
memcpy(op->packet->data, cpath, data_length);
SDMMD_AFCHeaderInit(&(op->packet->header), SDMMD_AFC_Packet_MakeDirectory, data_length+sizeof(struct SDMMD_AFCPacketHeader), 0x0, 0x0);
free(cpath);
return op;
}
SDMMD_AFCOperationRef SDMMD_AFCOperationCreateGetFileInfo(CFStringRef path) {
SDMMD_AFCOperationRef op = calloc(1, sizeof(struct sdmmd_AFCOperation));
op->packet = calloc(1, sizeof(struct sdmmd_AFCPacket));
char *cpath = SDMCFStringGetString(path);
uint32_t data_length = (uint32_t)strlen(cpath)+1;
op->packet->data = calloc(data_length, sizeof(char));
memcpy(op->packet->data, cpath, data_length);
SDMMD_AFCHeaderInit(&(op->packet->header), SDMMD_AFC_Packet_GetFileInfo, data_length+sizeof(struct SDMMD_AFCPacketHeader), 0x0, 0x0);
free(cpath);
return op;
}
SDMMD_AFCOperationRef SDMMD_AFCOperationCreateGetDeviceInfo() {
SDMMD_AFCOperationRef op = calloc(1, sizeof(struct sdmmd_AFCOperation));
op->packet = calloc(1, sizeof(struct sdmmd_AFCPacket));
SDMMD_AFCHeaderInit(&(op->packet->header), SDMMD_AFC_Packet_GetDeviceInfo, sizeof(struct SDMMD_AFCPacketHeader), 0x0, 0x0);
op->timeout = dispatch_time(DISPATCH_TIME_NOW, 0);
return op;
}
#if 0
SDMMD_AFCOperationRef SDMMD_AFCOperationCreateWriteFileAtomic() {
SDMMD_AFCOperationRef op = calloc(1, sizeof(struct sdmmd_AFCOperation));
op->packet = calloc(1, sizeof(struct sdmmd_AFCPacket));
SDMMD_AFCHeaderInit(&(op->packet->header), SDMMD_AFC_Packet_WriteFileAtomic, sizeof(struct sdmmd_AFCPacket), 0x0, 0x0);
return op;
}
#endif
SDMMD_AFCOperationRef SDMMD_AFCOperationCreateFileRefOpen(CFStringRef path, uint16_t mode, void* *fileRef) {
SDMMD_AFCOperationRef op = calloc(1, sizeof(struct sdmmd_AFCOperation));
op->packet = calloc(1, sizeof(struct sdmmd_AFCPacket));
char *cpath = SDMCFStringGetString(path);
uint32_t data_length = (uint32_t)strlen(cpath)+1+8;
op->packet->data = calloc(data_length, sizeof(char));
memcpy(op->packet->data, &mode, sizeof(mode));
memcpy(&(op->packet->data[sizeof(mode)]), cpath, strlen(cpath));
SDMMD_AFCHeaderInit(&(op->packet->header), SDMMD_AFC_Packet_FileRefOpen, data_length+sizeof(struct SDMMD_AFCPacketHeader), 0x0, 0x0);
free(cpath);
return op;
}
// rdi, rsi, rdx, rcx, r8
SDMMD_AFCOperationRef SDMMD_AFCFileDescriptorCreateReadOperation(void* fileRef) { // _AFCFileDescriptorCreateReadOperation
SDMMD_AFCOperationRef op = calloc(1, sizeof(struct sdmmd_AFCOperation));
op->packet = calloc(1, sizeof(struct sdmmd_AFCPacket));
uint32_t data_length = 16;
op->packet->data = calloc(data_length, sizeof(char));
SDMMD_AFCHeaderInit(&(op->packet->header), SDMMD_AFC_Packet_FileRefRead, data_length+sizeof(struct SDMMD_AFCPacketHeader), 0x0, 0x0);
return op;
}
// rdi, rsi, rdx
SDMMD_AFCOperationRef SDMMD_AFCFileDescriptorCreateWriteOperation(void* thing, CFDataRef data, void* thing2) { // _AFCFileDescriptorCreateWriteOperation
SDMMD_AFCOperationRef op = calloc(1, sizeof(struct sdmmd_AFCOperation));
op->packet = calloc(1, sizeof(struct sdmmd_AFCPacket));
uint32_t data_length = 8;
uint32_t body_length = (uint32_t)CFDataGetLength(data);
op->packet->data = calloc(body_length, sizeof(char));
memcpy(op->packet->data, CFDataGetBytePtr(data), body_length);
SDMMD_AFCHeaderInit(&(op->packet->header), SDMMD_AFC_Packet_FileRefWrite, data_length+sizeof(struct SDMMD_AFCPacketHeader), body_length, 0x0);
return op;
}
// rdi, rsi, rdx, rcx
SDMMD_AFCOperationRef SDMMD_AFCFileDescriptorCreateSeekOperation() { // _AFCFileDescriptorCreateSetPositionOperation
SDMMD_AFCOperationRef op = calloc(1, sizeof(struct sdmmd_AFCOperation));
op->packet = calloc(1, sizeof(struct sdmmd_AFCPacket));
SDMMD_AFCHeaderInit(&(op->packet->header), SDMMD_AFC_Packet_FileRefSeek, sizeof(struct SDMMD_AFCPacketHeader), 0x0, 0x0);
return op;
}
// rdi, rsi
SDMMD_AFCOperationRef SDMMD_AFCFileDescriptorCreateTellOperation() { // _AFCFileDescriptorCreateGetPositionOperation
SDMMD_AFCOperationRef op = calloc(1, sizeof(struct sdmmd_AFCOperation));
op->packet = calloc(1, sizeof(struct sdmmd_AFCPacket));
SDMMD_AFCHeaderInit(&(op->packet->header), SDMMD_AFC_Packet_FileRefTell, sizeof(struct SDMMD_AFCPacketHeader), 0x0, 0x0);
return op;
}
#if 0
SDMMD_AFCOperationRef SDMMD_AFCFileDescriptorCreateTellResultOperation() {
SDMMD_AFCOperationRef op = calloc(1, sizeof(struct sdmmd_AFCOperation));
op->packet = calloc(1, sizeof(struct sdmmd_AFCPacket));
SDMMD_AFCHeaderInit(&(op->packet->header), SDMMD_AFC_Packet_FileRefTellResult, sizeof(struct SDMMD_AFCPacketHeader), 0x0, 0x0);
return op;
}
#endif
// rdi, rsi
SDMMD_AFCOperationRef SDMMD_AFCFileDescriptorCreateCloseOperation() { // _AFCFileDescriptorCreateCloseOperation
SDMMD_AFCOperationRef op = calloc(1, sizeof(struct sdmmd_AFCOperation));
op->packet = calloc(1, sizeof(struct sdmmd_AFCPacket));
uint32_t data_length = 8;
op->packet->data = calloc(data_length, sizeof(char));
SDMMD_AFCHeaderInit(&(op->packet->header), SDMMD_AFC_Packet_FileRefClose, data_length+sizeof(struct SDMMD_AFCPacketHeader), 0x0, 0x0);
return op;
}
// rdi, rsi, rdx
SDMMD_AFCOperationRef SDMMD_AFCFileDescriptorCreateSetFileSizeOperation() { // _AFCFileDescriptorCreateSetSizeOperation
SDMMD_AFCOperationRef op = calloc(1, sizeof(struct sdmmd_AFCOperation));
op->packet = calloc(1, sizeof(struct sdmmd_AFCPacket));
SDMMD_AFCHeaderInit(&(op->packet->header), SDMMD_AFC_Packet_FileRefSetFileSize, sizeof(struct SDMMD_AFCPacketHeader), 0x0, 0x0);
return op;
}
SDMMD_AFCOperationRef SDMMD_AFCOperationCreateGetConnectionInfo() { // _AFCOperationCreateGetConnectionInfo
SDMMD_AFCOperationRef op = calloc(1, sizeof(struct sdmmd_AFCOperation));
op->packet = calloc(1, sizeof(struct sdmmd_AFCPacket));
SDMMD_AFCHeaderInit(&(op->packet->header), SDMMD_AFC_Packet_GetConnectionInfo, sizeof(struct SDMMD_AFCPacketHeader), 0x0, 0x0);
return op;
}
// rdi, rsi, rdx
SDMMD_AFCOperationRef SDMMD_AFCOperationCreateSetConnectionOptions() { // _AFCOperationCreateSetConnectionOptions
SDMMD_AFCOperationRef op = calloc(1, sizeof(struct sdmmd_AFCOperation));
op->packet = calloc(1, sizeof(struct sdmmd_AFCPacket));
SDMMD_AFCHeaderInit(&(op->packet->header), SDMMD_AFC_Packet_SetConnectionOptions, sizeof(struct SDMMD_AFCPacketHeader), 0x0, 0x0);
return op;
}
SDMMD_AFCOperationRef SDMMD_AFCOperationCreateRenamePath(CFStringRef old, CFStringRef new) {
SDMMD_AFCOperationRef op = calloc(1, sizeof(struct sdmmd_AFCOperation));
op->packet = calloc(1, sizeof(struct sdmmd_AFCPacket));
char *oldPath = SDMCFStringGetString(old);
char *newPath = SDMCFStringGetString(new);
uint32_t path_length = (uint32_t)(strlen(oldPath)+1+(uint32_t)strlen(newPath)+1);
op->packet->data = calloc(1, sizeof(char[path_length]));
memcpy(&op->packet->data, oldPath, strlen(oldPath));
memcpy(&op->packet->data[strlen(oldPath)+1], newPath, strlen(newPath));
SDMMD_AFCHeaderInit(&(op->packet->header), SDMMD_AFC_Packet_RenamePath, path_length+sizeof(struct SDMMD_AFCPacketHeader), 0x0, 0x0);
free(oldPath);
free(newPath);
return op;
}
SDMMD_AFCOperationRef SDMMD_AFCOperationCreateSetFSBlockSize() { // ___AFCConnectionSetBlockSize
SDMMD_AFCOperationRef op = calloc(1, sizeof(struct sdmmd_AFCOperation));
op->packet = calloc(1, sizeof(struct sdmmd_AFCPacket));
uint32_t data_length = 8;
op->packet->data = calloc(data_length, sizeof(char));
SDMMD_AFCHeaderInit(&(op->packet->header), SDMMD_AFC_Packet_SetFSBlockSize, data_length+sizeof(struct SDMMD_AFCPacketHeader), 0x0, 0x0);
return op;
}
SDMMD_AFCOperationRef SDMMD_AFCOperationCreateSetSocketBlockSize() { // ___AFCConnectionSetBlockSize
SDMMD_AFCOperationRef op = calloc(1, sizeof(struct sdmmd_AFCOperation));
op->packet = calloc(1, sizeof(struct sdmmd_AFCPacket));
uint32_t data_length = 8;
op->packet->data = calloc(data_length, sizeof(char));
SDMMD_AFCHeaderInit(&(op->packet->header), SDMMD_AFC_Packet_SetSocketBlockSize, data_length+sizeof(struct SDMMD_AFCPacketHeader), 0x0, 0x0);
return op;
}
SDMMD_AFCOperationRef SDMMD_AFCFileDescriptorCreateLockOperation(void* fileRef) {
SDMMD_AFCOperationRef op = calloc(1, sizeof(struct sdmmd_AFCOperation));
op->packet = calloc(1, sizeof(struct sdmmd_AFCPacket));
uint32_t data_length = 16;
op->packet->data = calloc(data_length, sizeof(char));
SDMMD_AFCHeaderInit(&(op->packet->header), SDMMD_AFC_Packet_FileRefLock, data_length+sizeof(struct SDMMD_AFCPacketHeader), 0x0, 0x0);
return op;
}
SDMMD_AFCOperationRef SDMMD_AFCOperationCreateLinkPath(uint64_t linkType, CFStringRef target, CFStringRef link) {
SDMMD_AFCOperationRef op = calloc(1, sizeof(struct sdmmd_AFCOperation));
op->packet = calloc(1, sizeof(struct sdmmd_AFCPacket));
char *targetPath = SDMCFStringGetString(target);
char *linkPath = SDMCFStringGetString(link);
uint32_t path_length = (uint32_t)(strlen(targetPath)+strlen(linkPath)+2);
op->packet->data = calloc(1, sizeof(char[path_length]));
memcpy(&op->packet->data, targetPath, strlen(targetPath));
memcpy(&op->packet->data[strlen(targetPath)+1], linkPath, strlen(linkPath));
SDMMD_AFCHeaderInit(&(op->packet->header), SDMMD_AFC_Packet_MakeLink, path_length+sizeof(struct SDMMD_AFCPacketHeader), 0x0, 0x0);
free(targetPath);
free(linkPath);
return op;
}
SDMMD_AFCOperationRef SDMMD_AFCOperationCreateGetFileHash(CFStringRef path) {
SDMMD_AFCOperationRef op = calloc(1, sizeof(struct sdmmd_AFCOperation));
op->packet = calloc(1, sizeof(struct sdmmd_AFCPacket));
char *cpath = SDMCFStringGetString(path);
uint32_t data_length = (uint32_t)strlen(cpath)+1;
op->packet->data = calloc(data_length, sizeof(char));
memcpy(op->packet->data, cpath, data_length);
SDMMD_AFCHeaderInit(&(op->packet->header), SDMMD_AFC_Packet_GetFileHash, data_length+sizeof(struct SDMMD_AFCPacketHeader), 0x0, 0x0);
free(cpath);
return op;
}
SDMMD_AFCOperationRef SDMMD_AFCOperationCreateSetModTime(CFStringRef ref) {
SDMMD_AFCOperationRef op = calloc(1, sizeof(struct sdmmd_AFCOperation));
op->packet = calloc(1, sizeof(struct sdmmd_AFCPacket));
char *cref = SDMCFStringGetString(ref);
uint32_t data_length = (uint32_t)strlen(cref)+1+8;
op->packet->data = calloc(data_length, sizeof(char));
memcpy(op->packet->data, cref, strlen(cref));
SDMMD_AFCHeaderInit(&(op->packet->header), SDMMD_AFC_Packet_SetModTime, data_length+sizeof(struct SDMMD_AFCPacketHeader), 0x0, 0x0);
free(cref);
return op;
}
SDMMD_AFCOperationRef SDMMD_AFCOperationCreateGetFileHashWithRange(CFStringRef path, void* range) {
SDMMD_AFCOperationRef op = calloc(1, sizeof(struct sdmmd_AFCOperation));
op->packet = calloc(1, sizeof(struct sdmmd_AFCPacket));
char *cpath = SDMCFStringGetString(path);
uint32_t data_length = (uint32_t)strlen(cpath)+1+0x10;
op->packet->data = calloc(data_length, sizeof(char));
memcpy(&(op->packet->data[0x10]), cpath, strlen(cpath));
SDMMD_AFCHeaderInit(&(op->packet->header), SDMMD_AFC_Packet_GetFileHashWithRange, data_length+sizeof(struct SDMMD_AFCPacketHeader), 0x0, 0x0);
free(cpath);
return op;
}
SDMMD_AFCOperationRef SDMMD_AFCFileDescriptorCreateSetImmutableHintOperation() {
SDMMD_AFCOperationRef op = calloc(1, sizeof(struct sdmmd_AFCOperation));
op->packet = calloc(1, sizeof(struct sdmmd_AFCPacket));
SDMMD_AFCHeaderInit(&(op->packet->header), SDMMD_AFC_Packet_FileRefSetImmutableHint, sizeof(struct SDMMD_AFCPacketHeader), 0x0, 0x0);
return op;
}
SDMMD_AFCOperationRef SDMMD_AFCOperationCreateGetSizeOfPathContents() {
SDMMD_AFCOperationRef op = calloc(1, sizeof(struct sdmmd_AFCOperation));
op->packet = calloc(1, sizeof(struct sdmmd_AFCPacket));
SDMMD_AFCHeaderInit(&(op->packet->header), SDMMD_AFC_Packet_GetSizeOfPathContents, sizeof(struct SDMMD_AFCPacketHeader), 0x0, 0x0);
return op;
}
SDMMD_AFCOperationRef SDMMD_AFCOperationCreateRemovePathAndContents() {
SDMMD_AFCOperationRef op = calloc(1, sizeof(struct sdmmd_AFCOperation));
op->packet = calloc(1, sizeof(struct sdmmd_AFCPacket));
SDMMD_AFCHeaderInit(&(op->packet->header), SDMMD_AFC_Packet_RemovePathAndContents, sizeof(struct SDMMD_AFCPacketHeader), 0x0, 0x0);
return op;
}
//SDMMD_AFCOperationRef SDMMD_AFCOperationCreate() {
// SDMMD_AFCOperationRef op = calloc(1, sizeof(struct sdmmd_AFCOperation));
// op->packet = calloc(1, sizeof(struct sdmmd_AFCPacket));
// SDMMD_AFCHeaderInit(&(op->packet->header), , sizeof(struct SDMMD_AFCPacketHeader), 0x0, 0x0);
// return op;
//}
sdmmd_return_t SDMMD_AFCSendOperation(SDMMD_AFCConnectionRef conn, SDMMD_AFCOperationRef op);
sdmmd_return_t SDMMD_AFCReceiveOperation(SDMMD_AFCConnectionRef conn, SDMMD_AFCOperationRef *op);
sdmmd_return_t SDMMD_AFCConnectionPerformOperation(SDMMD_AFCConnectionRef conn, SDMMD_AFCOperationRef op) {
__block sdmmd_return_t result = kAMDSuccess;
dispatch_sync(conn->operationQueue, ^{
printf("Packet: %s\n",SDMMD_gAFCPacketTypeNames[op->packet->header.type]);
op->packet->header.pid = conn->operationCount;
result = SDMMD_AFCSendOperation(conn, op);
SDMMD_AFCOperationRef response;
result = SDMMD_AFCReceiveOperation(conn, &response);
printf("Response: %08x\n",result);
PrintCFType(response->packet->data);
});
conn->operationCount++;
return result;
}
sdmmd_return_t SDMMD_AFCSendOperation(SDMMD_AFCConnectionRef conn, SDMMD_AFCOperationRef op) {
sdmmd_return_t result = kAMDSuccess;
CFMutableDataRef headerData = CFDataCreateMutable(kCFAllocatorDefault, (CFIndex)op->packet->header.packetLen);//(kCFAllocatorDefault, (UInt8*)&op->packet->header, sizeof(SDMMD_AFCPacketHeader));
CFDataAppendBytes(headerData, (UInt8*)&(op->packet->header), sizeof(SDMMD_AFCPacketHeader));
if (op->packet->header.headerLen > sizeof(SDMMD_AFCPacketHeader)) {
CFDataAppendBytes(headerData, (UInt8*)(op->packet->data), (uint32_t)op->packet->header.packetLen - sizeof(SDMMD_AFCPacketHeader));
}
result = SDMMD_DirectServiceSend(SDMMD_TranslateConnectionToSocket(conn->handle), headerData);
printf("header sent status: %08x %s\n",result,SDMMD_AMDErrorString(result));
if (!(op->packet->header.headerLen == op->packet->header.packetLen && op->packet->data == NULL)) {
CFDataRef bodyData = CFDataCreate(kCFAllocatorDefault, (UInt8*)(op->packet->data), (uint32_t)op->packet->header.packetLen - sizeof(SDMMD_AFCPacketHeader));
result = SDMMD_DirectServiceSend(SDMMD_TranslateConnectionToSocket(conn->handle), bodyData);
printf("body sent status: %08x %s\n",result,SDMMD_AMDErrorString(result));
}
return result;
}
sdmmd_return_t SDMMD_AFCReceiveOperation(SDMMD_AFCConnectionRef conn, SDMMD_AFCOperationRef *op) {
sdmmd_return_t result = kAMDSuccess;
CFMutableDataRef headerData = CFDataCreateMutable(kCFAllocatorDefault, sizeof(SDMMD_AFCPacketHeader));
SDMMD_AFCPacketHeader *zeros = calloc(1, sizeof(SDMMD_AFCPacketHeader));
CFDataAppendBytes(headerData, (UInt8*)zeros, sizeof(SDMMD_AFCPacketHeader));
free(zeros);
result = SDMMD_DirectServiceReceive(SDMMD_TranslateConnectionToSocket(conn->handle), (CFDataRef*)&headerData);
SDMMD_AFCPacketHeader *header = (SDMMD_AFCPacketHeader *)CFDataGetBytePtr(headerData);
CFMutableDataRef bodyData = CFDataCreateMutable(kCFAllocatorDefault, (uint32_t)header->packetLen - sizeof(SDMMD_AFCPacketHeader));
char *body = calloc(1, (uint32_t)header->packetLen - sizeof(SDMMD_AFCPacketHeader));
CFDataAppendBytes(bodyData, (UInt8*)body, (uint32_t)header->packetLen - sizeof(SDMMD_AFCPacketHeader));
free(body);
result = SDMMD_DirectServiceReceive(SDMMD_TranslateConnectionToSocket(conn->handle), (CFDataRef*)&bodyData);
struct sdmmd_AFCPacket *packet = calloc(1, sizeof(struct sdmmd_AFCPacket));
packet->header = *header;
if (bodyData) {
packet->data = (void*)CFDataGetBytePtr(bodyData);
}
SDMMD_AFCOperationRef response = calloc(1, sizeof(struct sdmmd_AFCOperation));
response->packet = packet;
response->timeout = 0;
*op = response;
return result;
}
sdmmd_return_t SDMMD_AFCProcessOperation(SDMMD_AFCConnectionRef conn, SDMMD_AFCOperationRef op, SDMMD_AFCOperationRef *response) {
__block sdmmd_return_t result = kAMDSuccess;
__block SDMMD_AFCOperationRef blockReply;
dispatch_sync(conn->operationQueue, ^{
conn->semaphore = dispatch_semaphore_create(0x0);
op->packet->header.pid = k64BitMask; //conn->operationCount;
result = SDMMD_AFCSendOperation(conn, op);
dispatch_semaphore_wait(conn->semaphore, op->timeout);
SDMMD_AFCReceiveOperation(conn, &blockReply);
dispatch_release(conn->semaphore);
conn->operationCount++;
});
*response = blockReply;
return result;
}
CFDataRef SDMMD_GetDataResponseFromOperation(SDMMD_AFCOperationRef op) {
return CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, (UInt8*)op->packet->data, (uint32_t)op->packet->header.packetLen-(uint32_t)op->packet->header.headerLen, kCFAllocatorDefault);
}
sdmmd_return_t SDMMD_AMDeviceCopyFile(void *thing, void *thing2, void *thing3, SDMMD_AFCConnectionRef conn, char *local, char *remote) {
return kAMDSuccess;
}
/*CFMutableDataRef SDMMD___AFCCreateAFCDataWithDictionary(CFDictionaryRef dict) {
CFMutableDataRef data = CFDataCreateMutable(kCFAllocatorDefault, kCFAllocatorDefault);
if (data) {
CFDictionaryApplyFunction(dict, SDMMD___ConvertDictEntry, data);
}
return data;
}
void SDMMD_AFCLog(uint32_t level, const char *format, ...) {
va_list args;
va_start(args, format);
vprintf(format, args);
va_end(args);
}
sdmmd_return_t SDMMD_AFCSetErrorInfoWithArgs(uint32_t level, uint32_t mask, uint32_t code, char *file, uint32_t line, char *call) {
sdmmd_return_t result = kAMDSuccess;
CFTypeRef err;
SDMMD_AFCErrorInfoCreateWithArgs(err, mask, code, file, line, call);
if (err) {
}
return result;
}
sdmmd_return_t SDMMD__AFCSetErrorResult(uint32_t level, uint32_t code, uint32_t line, char *call) {
sdmmd_return_t result = kAMDSuccess;
SDMMD_AFCLog(0x5, "Setting error result %d, %d, %s, %d\n", 0xffffffff, code, __FILE__, line);
result = SDMMD_AFCSetErrorInfoWithArgs(level, 0xffffffff, code, __FILE__, line, call);
return result;
}
char* SDMMD_AFCStringCopy(char *dest, uint32_t destLength, char *source, uint32_t sourceLength) {
if (sourceLength) {
if (sourceLength < destLength) {
sourceLength = destLength;
}
strncpy(dest, source, sourceLength);
} else {
strlcpy(dest, source, destLength);
}
return dest;
}
char* SDMMD_AFCPacketTypeName(uint32_t packetType) {
char *name = "Unknown";
if (packetType != 0x0 && packetType <= 0x28) {
name = gAFCPacketTypeNames[packetType];
}
return name;
}
sdmmd_return_t SDMMD_AFCSendStatusExtended(SDMMD_AFCConnectionRef afcConn, void*b, uint32_t packetType, CFDictionaryRef ref) {
sdmmd_return_t result = kAMDSuccess;
SDMMD_AFCLog(0x5, "Writing status packet %d info %p\\n",packetType,ref);
if (afcConn && packetType >= 0x15) {
SDMMD_AFCLog(0x5, "Oh no!");
}
if (afcConn->ivars.e == 0x0) {
uint32_t length = 0x30;
CFDataRef afcData = NULL;
if (ref != 0x0 && (afcConn->ivars.j & 1) != 0x0) {
afcData = SDMMD___AFCCreateAFCDataWithDictionary(ref);
length += CFDataGetLength(afcData);
}
uint64_t header = 0x4141504c36414643;
uint32_t data24 = 0x30;
uint32_t data40 = 0x1;
uint32_t packetMask = packetType & 0x1fff;
uint32_t data32 = 0x0;
if (b != 0x0) {
data32 = (b+0x18);
} else {
data32 = 0xffffffff;
}
result = SDMMD_AFCSendHeader(afcConn, &header);
if (afcData != 0x0) {
if (result == 0x0) {
result = SDMMD_AFCSendData(afcConn, CFDataGetBytePtr(afcData), length);
}
}
CFSafeRelease(afcData);
} else {
result = afcConn->ivars.statusPtr;
}
return result;
}
sdmmd_return_t SDMMD_AFCSendStatus(SDMMD_AFCConnectionRef afcConn, void*b, void*c) {
CFTypeRef arg = SDMMD_AFCCopyAndClearLastErrorInfo();
sdmmd_return_t result = SDMMD_AFCSendStatusExtended(afcConn, b, c, arg);
CFSafeRelease(arg);
return result;
}
sdmmd_return_t SDMMD_AFCSendDataPacket(SDMMD_AFCConnectionRef afcConn, void*b, uint32_t *dataBytePtr, uint32_t dataLength) {
sdmmd_return_t result = kAMDSuccess;
SDMMD_AFCLog(0x5, "Writing data packet with data length %u\n",dataLength);
if (afcConn->ivars.e != 0x0) {
result = afcConn->ivars.statusPtr;
} else {
uint64_t header = 0x4141504c36414643;
uint32_t packetLength = dataLength + 0x28;
uint32_t data32 = 0x0;
if (b != 0x0) {
data32 = ((char*)b+0x18);
} else {
data32 = 0xffffffff;
}
result = SDMMD_AFCSendHeader(afcConn, &header);
if (result == 0x0) {
result = SDMMD_AFCSendData(afcConn, dataBytePtr, dataLength);
}
}
return result;
}
sdmmd_return_t SDMMD_AFCSendHeader(SDMMD_AFCConnectionRef afcConn, void*b) {
sdmmd_return_t result = kAMDSuccess;
if (afcConn->ivars.e != 0x0) {
result = afcConn->ivars.statusPtr;
} else {
SDMMD_AFCLogPacketInfo(0x4, "AFCSendHeader", b);
result = SDMMD_AFCSendData(afcConn, b, 0x10);
}
return result;
}
sdmmd_return_t SDMMD_AFCReadPacket(SDMMD_AFCConnectionRef afcConn, CFTypeRef* b, CFTypeRef* c, CFTypeRef* d) {
sdmmd_return_t result = 0xe800400b;
CFTypeRef packetHeader = NULL;
CFTypeRef packetBody0 = 0x0;
uint32_t packetBody1 = 0x0;
SDMMD_AFCLockLock(afcConn->ivars.lock1);
uint32_t packetHeaderUnknown = 0x0;
if (afcConn->ivars.state) {
result = SDMMD_AFCReadPacketHeader(afcConn, &packetHeaderUnknown, 0x80, packetHeader);
if (result == 0x0) {
result = SDMMD_AFCReadPacketBody(afcConn, packetHeader, &packetBody0, &packetBody1);
if (result == 0x0) {
*b = packetHeader;
*c = packetBody0;
*d = packetBody1;
result = 0x0;
} else {
if (packetBody0 != 0x0) {
CFTypeRef allocRef = CFGetAllocator(afcConn);
CFAllocatorDeallocate(allocRef, packetBody0);
}
}
} else {
if (packetHeader != 0x0) {
CFTypeRef allocRef = CFGetAllocator(afcConn);
CFAllocatorDeallocate(allocRef, packetHeader);
}
}
}
SDMMD_AFCLockUnlock(afcConn->ivars.lock1);
return result;
}
sdmmd_return_t SDMMD_AFCReadPacketBody(CFTypeRef a,void*b, CFDataRef* c, uint32_t *readLength) {
sdmmd_return_t result = kAMDSuccess;
if ((a+0x44) == 0x0) {
uint32_t dataLength = (b+0x8);
CFDataRef data = NULL;
if (dataLength-((uint32_t)(char*)b+0x10) != 0x0) {
CFTypeRef allocRef = CFGetAllocator(a);
data = CFAllocatorAllocate(allocRef, dataLength, 0x0);
if (result == 0x0) {
result = SDMMD__AFCSetErrorResult(0x0, 0xe8004003, __LINE__, "CFAllocatorAllocate");
}
result = SDMMD_AFCReadData(a, data, dataLength);
if (result == 0x0) {
} else {
result = (a+0x40);
}
}
*c = data;
*readLength = dataLength;
} else {
result = (a+0x40);
}
return result;
}
sdmmd_return_t SDMMD_AFCSendPacket(SDMMD_AFCConnectionRef afcConn, CFTypeRef b, void* c, uint32_t size) {
sdmmd_return_t result = 0xe800400b;
SDMMD_AFCLockLock(afcConn->ivars.lock1);
if (afcConn->ivars.state) {
if (c == 0x0)
result = 0xe8004007;
if (((char*)b+0x10) + size > 0x2000) {
result = SDMMD_AFCSendHeader(afcConn, b);
if (result == 0x0) {
result = SDMMD_AFCSendData(afcConn, c, size);
}
} else {
char *data = malloc(0x2000);
if (data) {
memcpy(data, c, size);
SDMMD_AFCLogPacketInfo(0x4, "AFCSendHeader", b);
result = SDMMD_AFCSendData(afcConn, data, size);
free(data);
} else {
result = SDMMD_AFCSendHeader(afcConn, b);
if (result == 0x0) {
result = SDMMD_AFCSendData(afcConn, c, size);
}
}
}
}
SDMMD_AFCLockUnlock(afcConn->ivars.lock1);
return result;
}
uint32_t SDMMD_AFCHeaderInit(SDMMD_AFCHeaderRef header, uint32_t command, uint32_t size, uint32_t data, uint32_t unknown) {
header->signature = 0x4141504c36414643;
header->headerLen = size;
header->packetLen = data+size;
header->type = command;
if (unknown) {
header->pid = unknown + 0x18;
} else {
header->pid = 0xffffffff;
}
return header->signature;
}
sdmmd_return_t SDMMD_AFCValidateHeader(SDMMD_AFCHeaderRef header, uint32_t command, void*b, void*c, uint64_t d) {
if (header->signature != 0x434641364c504141) {
if (d != 0x4141504c36414643) {
return SDMMD___AFCSetErrorResult();
} else {
}
} else {
}
}*/
#endif
#endif |
the_stack_data/1077147.c | #include<stdio.h>
char * cpOperation="Division";
int operate(int,int);
int main(int argc, char** argv)
{
int iNumber1, iNumber2 ,iResult;
printf("Give 1st number\n");
scanf("%d",&iNumber1);
printf("Give 2nd number\n");
scanf("%d",&iNumber2);
iResult=operate(iNumber1,iNumber2);
printf("%s of %d by %d is %d\n",cpOperation,iNumber1,iNumber2,iResult);
return(0);
}
int operate(iNumber1,iNumber2)
{
/* Here return Division of two number i.e. (iNumber1/iNumber2) */
}
|
the_stack_data/234517672.c | /* Ensure that we don't use 'rep stoX' in the presence of register globals. */
/* { dg-do compile } */
/* { dg-options "-Os -w" } */
extern void *memset (void *, int, __SIZE_TYPE__);
register int regvar asm("%edi");
int foo[10];
int bar[10];
char baz[15];
char quux[15];
void
do_copy ()
{
memset (foo, 0, sizeof foo);
memset (baz, 0, sizeof baz);
}
/* { dg-final { scan-assembler-not "rep stosl" } } */
/* { dg-final { scan-assembler-not "rep stosb" } } */
|
the_stack_data/122014854.c | #include<stdio.h>
int zhi(int);
int main()
{
int i,n;
scanf("%d",&n);
for(i=n+1;i<=100010;i++)
{
if(zhi(i)==1)
break;
}
printf("%d",i);
return 0;
}
int zhi(int i)
{
int j;
for(j=i-1;j>1;j--)
{if(i%j==0)
return 3;
}
return 1;
} |
the_stack_data/145452700.c | #ifdef MATLAB_MEX_FILE
#include "mex.h"
#include "matrix.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "string.h"
#include "math.h"
#include <stdint.h>
/*
cluster3ec.c
Purpose: Cluster points that are within a certain Euclidean distance to each
other.
Interface/Input: 3D points, [x1,y2,z1, x2,y2,z2, ...]
Output: A label for each points, indicating the cluster it belongs to
Worst case O(N^2), but usually a little better.
Is easy to adapt to other (symmetric) metrics.
Can be adapted to higher/lower dimensions in ed2()
Use with MATLAB:
mex cluster3ec.c CXXOPTIMFLAGS='-O3 -Wall' -largeArrayDims
Erik Wernersson, 2015 08 31
*/
double ed2(double * a, double *b)
{
// Euclidean distance, squared
return (a[0]-b[0])*(a[0]-b[0])
+ (a[1]-b[1])*(a[1]-b[1])
+ (a[2]-b[2])*(a[2]-b[2]);
}
size_t cluster3e(double * P, size_t N, double d2, uint32_t * C)
{
// Store indexes of all remaining dots
uint32_t * Q = (uint32_t*) malloc(N*sizeof(uint32_t));
for(int kk = 0; kk<N; kk++)
Q[kk] = kk;
uint32_t cNum = 1; // Current cluster
uint32_t cStart = 0; // First index of the cluster (in Q)
uint32_t cEnd = 0; // Last index of the cluster (in Q)
uint32_t cExp = 0; // Next point to expand from
uint32_t pp = 0; // Q[pp] is the next element to be compared to Q[cExp]
uint32_t t; // used for swapping
// printf("N: %lu\n", N);
while(cEnd<N) { // Until no more points
// printf("= cStart: %d, cExp: %d, cEnd: %d\n", cStart, cExp, cEnd);
while(cExp <= cEnd && cExp <N) // If there is something more to expand
{
pp = cEnd+1;
while(pp < N) // The points to compare to
{
// printf("cStart: %d, cExp: %d, cEnd: %d\n", cStart, cExp, cEnd);
if(ed2(P + 3*Q[pp], P + 3*Q[cExp])<d2)
{
// printf("pp: %d\n", pp);
cEnd++;
t = Q[cEnd];
Q[cEnd] = Q[pp];
Q[pp] = t;
}
pp++;
}
cExp++;
}
// Set cluster labels in C
for(int kk = cStart; kk<=cEnd; kk++)
C[Q[kk]] = cNum;
cNum++;
// Prepare for a new cluster
cStart = cEnd+1;
cEnd = cStart;
cExp = cStart;
}
free(Q);
return cNum-1;
}
#ifdef MATLAB_MEX_FILE
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray
*prhs[])
{
if (nrhs != 2)
mexErrMsgTxt("Requires two inputs");
int verbose = 0;
if( ! mxIsDouble(prhs[0]))
{ mexErrMsgTxt("Check the data type of the input arguments."); }
double * X = mxGetPr(prhs[0]);
double * r = mxGetPr(prhs[1]);
const mwSize * sizeX = mxGetDimensions(prhs[0]);
size_t M = sizeX[0];
size_t N = sizeX[1]; // get from X
size_t NN = mxGetNumberOfElements(prhs[0]);
if ((NN) % 3 != 0)
{ mexErrMsgTxt("3*N coordinates required"); }
if( M!=3)
{ mexErrMsgTxt("Only 3D vectors supported"); }
if(verbose)
printf("got %d points\n", N);
if( N == 0)
{ mexErrMsgTxt("Requires at least one point."); }
//printf("%lu, %lu\n", M, N);
uint32_t *C = malloc(N*sizeof(uint32_t));
//memset(C, 0, 3*N*sizeof(uint32));
for(int kk = 0; kk<N; kk++)
C[kk]=0;
size_t nC = cluster3e(X, N, r[0]*r[0], C);
mwSize ut_dim[]={ N, 1};
plhs[0] = mxCreateNumericArray(2, ut_dim, mxUINT32_CLASS, mxREAL);
uint32_t * C2 = (uint32_t *) mxGetPr(plhs[0]);
for(size_t kk=0; kk<N; kk++)
C2[kk]=C[kk];
free(C);
}
#else
int main(int argc, char ** argv)
{
size_t N = 23;
double * X = (double *) malloc(N*3*sizeof(double));
uint32_t * C = (uint32_t *) malloc(N*sizeof(uint32_t));
double d2 = 1;
size_t nC = cluster3e(X, N,d2,C);
free(C);
free(X);
}
#endif
|
the_stack_data/1097401.c | /*
* Copyright (c) 2020 Fingerprint Cards AB
*
* 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
*
* https://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.
*
* Modified by Andrey Perminov <[email protected]>
* for FPC BM-Lite applications
*/
/**
* @file hal_spi.c
* @brief SPI HAL functions
*/
#ifdef BMLITE_ON_SPI
#include "nrf_drv_spi.h"
#include "boards.h"
#include "nrf_gpio.h"
#include "nrf_gpiote.h"
#include "nrf_drv_gpiote.h"
#include "bmlite_hal.h"
#include "fpc_bep_types.h"
#define SPI_INSTANCE 0 /**< SPI instance index. */
#define BMLITE_CS_PIN ARDUINO_8_PIN
#define BMLITE_MISO_PIN ARDUINO_12_PIN
#define BMLITE_MOSI_PIN ARDUINO_11_PIN
#define BMLITE_CLK_PIN ARDUINO_13_PIN
static const nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE); /**< SPI instance. */
static volatile bool spi_xfer_done; /**< Flag used to indicate that SPI instance completed the transfer. */
static uint8_t *m_tx_buf;
static uint8_t *m_rx_buf;
nrf_drv_spi_config_t spi_config = NRF_DRV_SPI_DEFAULT_CONFIG;
/**
* @brief SPI user event handler.
* @param event
*/
static void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
void * p_context)
{
if( p_event->type == NRF_DRV_SPI_EVENT_DONE) {
spi_xfer_done = true;
}
}
static void spi_write_read(uint8_t *write, uint8_t *read, size_t size, bool leave_cs_asserted)
{
spi_xfer_done = false;
m_tx_buf = write;
m_rx_buf = read;
nrf_drv_gpiote_out_clear(BMLITE_CS_PIN);
nrf_drv_spi_transfer(&spi, m_tx_buf, size, m_rx_buf, size);
while (!spi_xfer_done)
{
__WFE();
}
if(!leave_cs_asserted)
nrf_drv_gpiote_out_set(BMLITE_CS_PIN);
}
fpc_bep_result_t hal_bmlite_spi_write_read(uint8_t *write, uint8_t *read, size_t size,
bool leave_cs_asserted)
{
uint8_t num_of_rounds = size/255, i;
uint8_t *p_write = write, *p_read = read;
for(i=0; i<num_of_rounds; i++){
spi_write_read(p_write, p_read, 255, true);
p_write += 255;
p_read += 255;
size -=255;
}
spi_write_read(p_write, p_read, size, leave_cs_asserted);
return FPC_BEP_RESULT_OK;
}
void nordic_bmlite_spi_init(uint32_t speed_hz)
{
//spi_config.ss_pin = BMLITE_CS_PIN;
spi_config.miso_pin = BMLITE_MISO_PIN;
spi_config.mosi_pin = BMLITE_MOSI_PIN;
spi_config.sck_pin = BMLITE_CLK_PIN;
spi_config.frequency = NRF_SPI_FREQ_8M;// default to 8M for now
nrf_drv_spi_init(&spi, &spi_config, spi_event_handler, NULL);
nrf_drv_gpiote_out_config_t out_config = GPIOTE_CONFIG_OUT_SIMPLE(true);
nrf_drv_gpiote_out_init(BMLITE_CS_PIN, &out_config);
}
#endif |
the_stack_data/148579172.c | #include <math.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <complex.h>
#ifdef complex
#undef complex
#endif
#ifdef I
#undef I
#endif
#if defined(_WIN64)
typedef long long BLASLONG;
typedef unsigned long long BLASULONG;
#else
typedef long BLASLONG;
typedef unsigned long BLASULONG;
#endif
#ifdef LAPACK_ILP64
typedef BLASLONG blasint;
#if defined(_WIN64)
#define blasabs(x) llabs(x)
#else
#define blasabs(x) labs(x)
#endif
#else
typedef int blasint;
#define blasabs(x) abs(x)
#endif
typedef blasint integer;
typedef unsigned int uinteger;
typedef char *address;
typedef short int shortint;
typedef float real;
typedef double doublereal;
typedef struct { real r, i; } complex;
typedef struct { doublereal r, i; } doublecomplex;
#ifdef _MSC_VER
static inline _Fcomplex Cf(complex *z) {_Fcomplex zz={z->r , z->i}; return zz;}
static inline _Dcomplex Cd(doublecomplex *z) {_Dcomplex zz={z->r , z->i};return zz;}
static inline _Fcomplex * _pCf(complex *z) {return (_Fcomplex*)z;}
static inline _Dcomplex * _pCd(doublecomplex *z) {return (_Dcomplex*)z;}
#else
static inline _Complex float Cf(complex *z) {return z->r + z->i*_Complex_I;}
static inline _Complex double Cd(doublecomplex *z) {return z->r + z->i*_Complex_I;}
static inline _Complex float * _pCf(complex *z) {return (_Complex float*)z;}
static inline _Complex double * _pCd(doublecomplex *z) {return (_Complex double*)z;}
#endif
#define pCf(z) (*_pCf(z))
#define pCd(z) (*_pCd(z))
typedef int logical;
typedef short int shortlogical;
typedef char logical1;
typedef char integer1;
#define TRUE_ (1)
#define FALSE_ (0)
/* Extern is for use with -E */
#ifndef Extern
#define Extern extern
#endif
/* I/O stuff */
typedef int flag;
typedef int ftnlen;
typedef int ftnint;
/*external read, write*/
typedef struct
{ flag cierr;
ftnint ciunit;
flag ciend;
char *cifmt;
ftnint cirec;
} cilist;
/*internal read, write*/
typedef struct
{ flag icierr;
char *iciunit;
flag iciend;
char *icifmt;
ftnint icirlen;
ftnint icirnum;
} icilist;
/*open*/
typedef struct
{ flag oerr;
ftnint ounit;
char *ofnm;
ftnlen ofnmlen;
char *osta;
char *oacc;
char *ofm;
ftnint orl;
char *oblnk;
} olist;
/*close*/
typedef struct
{ flag cerr;
ftnint cunit;
char *csta;
} cllist;
/*rewind, backspace, endfile*/
typedef struct
{ flag aerr;
ftnint aunit;
} alist;
/* inquire */
typedef struct
{ flag inerr;
ftnint inunit;
char *infile;
ftnlen infilen;
ftnint *inex; /*parameters in standard's order*/
ftnint *inopen;
ftnint *innum;
ftnint *innamed;
char *inname;
ftnlen innamlen;
char *inacc;
ftnlen inacclen;
char *inseq;
ftnlen inseqlen;
char *indir;
ftnlen indirlen;
char *infmt;
ftnlen infmtlen;
char *inform;
ftnint informlen;
char *inunf;
ftnlen inunflen;
ftnint *inrecl;
ftnint *innrec;
char *inblank;
ftnlen inblanklen;
} inlist;
#define VOID void
union Multitype { /* for multiple entry points */
integer1 g;
shortint h;
integer i;
/* longint j; */
real r;
doublereal d;
complex c;
doublecomplex z;
};
typedef union Multitype Multitype;
struct Vardesc { /* for Namelist */
char *name;
char *addr;
ftnlen *dims;
int type;
};
typedef struct Vardesc Vardesc;
struct Namelist {
char *name;
Vardesc **vars;
int nvars;
};
typedef struct Namelist Namelist;
#define abs(x) ((x) >= 0 ? (x) : -(x))
#define dabs(x) (fabs(x))
#define f2cmin(a,b) ((a) <= (b) ? (a) : (b))
#define f2cmax(a,b) ((a) >= (b) ? (a) : (b))
#define dmin(a,b) (f2cmin(a,b))
#define dmax(a,b) (f2cmax(a,b))
#define bit_test(a,b) ((a) >> (b) & 1)
#define bit_clear(a,b) ((a) & ~((uinteger)1 << (b)))
#define bit_set(a,b) ((a) | ((uinteger)1 << (b)))
#define abort_() { sig_die("Fortran abort routine called", 1); }
#define c_abs(z) (cabsf(Cf(z)))
#define c_cos(R,Z) { pCf(R)=ccos(Cf(Z)); }
#ifdef _MSC_VER
#define c_div(c, a, b) {Cf(c)._Val[0] = (Cf(a)._Val[0]/Cf(b)._Val[0]); Cf(c)._Val[1]=(Cf(a)._Val[1]/Cf(b)._Val[1]);}
#define z_div(c, a, b) {Cd(c)._Val[0] = (Cd(a)._Val[0]/Cd(b)._Val[0]); Cd(c)._Val[1]=(Cd(a)._Val[1]/df(b)._Val[1]);}
#else
#define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);}
#define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);}
#endif
#define c_exp(R, Z) {pCf(R) = cexpf(Cf(Z));}
#define c_log(R, Z) {pCf(R) = clogf(Cf(Z));}
#define c_sin(R, Z) {pCf(R) = csinf(Cf(Z));}
//#define c_sqrt(R, Z) {*(R) = csqrtf(Cf(Z));}
#define c_sqrt(R, Z) {pCf(R) = csqrtf(Cf(Z));}
#define d_abs(x) (fabs(*(x)))
#define d_acos(x) (acos(*(x)))
#define d_asin(x) (asin(*(x)))
#define d_atan(x) (atan(*(x)))
#define d_atn2(x, y) (atan2(*(x),*(y)))
#define d_cnjg(R, Z) { pCd(R) = conj(Cd(Z)); }
#define r_cnjg(R, Z) { pCf(R) = conjf(Cf(Z)); }
#define d_cos(x) (cos(*(x)))
#define d_cosh(x) (cosh(*(x)))
#define d_dim(__a, __b) ( *(__a) > *(__b) ? *(__a) - *(__b) : 0.0 )
#define d_exp(x) (exp(*(x)))
#define d_imag(z) (cimag(Cd(z)))
#define r_imag(z) (cimagf(Cf(z)))
#define d_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x)))
#define r_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x)))
#define d_lg10(x) ( 0.43429448190325182765 * log(*(x)) )
#define r_lg10(x) ( 0.43429448190325182765 * log(*(x)) )
#define d_log(x) (log(*(x)))
#define d_mod(x, y) (fmod(*(x), *(y)))
#define u_nint(__x) ((__x)>=0 ? floor((__x) + .5) : -floor(.5 - (__x)))
#define d_nint(x) u_nint(*(x))
#define u_sign(__a,__b) ((__b) >= 0 ? ((__a) >= 0 ? (__a) : -(__a)) : -((__a) >= 0 ? (__a) : -(__a)))
#define d_sign(a,b) u_sign(*(a),*(b))
#define r_sign(a,b) u_sign(*(a),*(b))
#define d_sin(x) (sin(*(x)))
#define d_sinh(x) (sinh(*(x)))
#define d_sqrt(x) (sqrt(*(x)))
#define d_tan(x) (tan(*(x)))
#define d_tanh(x) (tanh(*(x)))
#define i_abs(x) abs(*(x))
#define i_dnnt(x) ((integer)u_nint(*(x)))
#define i_len(s, n) (n)
#define i_nint(x) ((integer)u_nint(*(x)))
#define i_sign(a,b) ((integer)u_sign((integer)*(a),(integer)*(b)))
#define pow_dd(ap, bp) ( pow(*(ap), *(bp)))
#define pow_si(B,E) spow_ui(*(B),*(E))
#define pow_ri(B,E) spow_ui(*(B),*(E))
#define pow_di(B,E) dpow_ui(*(B),*(E))
#define pow_zi(p, a, b) {pCd(p) = zpow_ui(Cd(a), *(b));}
#define pow_ci(p, a, b) {pCf(p) = cpow_ui(Cf(a), *(b));}
#define pow_zz(R,A,B) {pCd(R) = cpow(Cd(A),*(B));}
#define s_cat(lpp, rpp, rnp, np, llp) { ftnlen i, nc, ll; char *f__rp, *lp; ll = (llp); lp = (lpp); for(i=0; i < (int)*(np); ++i) { nc = ll; if((rnp)[i] < nc) nc = (rnp)[i]; ll -= nc; f__rp = (rpp)[i]; while(--nc >= 0) *lp++ = *(f__rp)++; } while(--ll >= 0) *lp++ = ' '; }
#define s_cmp(a,b,c,d) ((integer)strncmp((a),(b),f2cmin((c),(d))))
#define s_copy(A,B,C,D) { int __i,__m; for (__i=0, __m=f2cmin((C),(D)); __i<__m && (B)[__i] != 0; ++__i) (A)[__i] = (B)[__i]; }
#define sig_die(s, kill) { exit(1); }
#define s_stop(s, n) {exit(0);}
static char junk[] = "\n@(#)LIBF77 VERSION 19990503\n";
#define z_abs(z) (cabs(Cd(z)))
#define z_exp(R, Z) {pCd(R) = cexp(Cd(Z));}
#define z_sqrt(R, Z) {pCd(R) = csqrt(Cd(Z));}
#define myexit_() break;
#define mycycle() continue;
#define myceiling(w) {ceil(w)}
#define myhuge(w) {HUGE_VAL}
//#define mymaxloc_(w,s,e,n) {if (sizeof(*(w)) == sizeof(double)) dmaxloc_((w),*(s),*(e),n); else dmaxloc_((w),*(s),*(e),n);}
#define mymaxloc(w,s,e,n) {dmaxloc_(w,*(s),*(e),n)}
/* procedure parameter types for -A and -C++ */
#define F2C_proc_par_types 1
#ifdef __cplusplus
typedef logical (*L_fp)(...);
#else
typedef logical (*L_fp)();
#endif
static float spow_ui(float x, integer n) {
float pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static double dpow_ui(double x, integer n) {
double pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
#ifdef _MSC_VER
static _Fcomplex cpow_ui(complex x, integer n) {
complex pow={1.0,0.0}; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x.r = 1/x.r, x.i=1/x.i;
for(u = n; ; ) {
if(u & 01) pow.r *= x.r, pow.i *= x.i;
if(u >>= 1) x.r *= x.r, x.i *= x.i;
else break;
}
}
_Fcomplex p={pow.r, pow.i};
return p;
}
#else
static _Complex float cpow_ui(_Complex float x, integer n) {
_Complex float pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
#endif
#ifdef _MSC_VER
static _Dcomplex zpow_ui(_Dcomplex x, integer n) {
_Dcomplex pow={1.0,0.0}; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x._Val[0] = 1/x._Val[0], x._Val[1] =1/x._Val[1];
for(u = n; ; ) {
if(u & 01) pow._Val[0] *= x._Val[0], pow._Val[1] *= x._Val[1];
if(u >>= 1) x._Val[0] *= x._Val[0], x._Val[1] *= x._Val[1];
else break;
}
}
_Dcomplex p = {pow._Val[0], pow._Val[1]};
return p;
}
#else
static _Complex double zpow_ui(_Complex double x, integer n) {
_Complex double pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
#endif
static integer pow_ii(integer x, integer n) {
integer pow; unsigned long int u;
if (n <= 0) {
if (n == 0 || x == 1) pow = 1;
else if (x != -1) pow = x == 0 ? 1/x : 0;
else n = -n;
}
if ((n > 0) || !(n == 0 || x == 1 || x != -1)) {
u = n;
for(pow = 1; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static integer dmaxloc_(double *w, integer s, integer e, integer *n)
{
double m; integer i, mi;
for(m=w[s-1], mi=s, i=s+1; i<=e; i++)
if (w[i-1]>m) mi=i ,m=w[i-1];
return mi-s+1;
}
static integer smaxloc_(float *w, integer s, integer e, integer *n)
{
float m; integer i, mi;
for(m=w[s-1], mi=s, i=s+1; i<=e; i++)
if (w[i-1]>m) mi=i ,m=w[i-1];
return mi-s+1;
}
static inline void cdotc_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Fcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conjf(Cf(&x[i]))._Val[0] * Cf(&y[i])._Val[0];
zdotc._Val[1] += conjf(Cf(&x[i]))._Val[1] * Cf(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conjf(Cf(&x[i*incx]))._Val[0] * Cf(&y[i*incy])._Val[0];
zdotc._Val[1] += conjf(Cf(&x[i*incx]))._Val[1] * Cf(&y[i*incy])._Val[1];
}
}
pCf(z) = zdotc;
}
#else
_Complex float zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conjf(Cf(&x[i])) * Cf(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conjf(Cf(&x[i*incx])) * Cf(&y[i*incy]);
}
}
pCf(z) = zdotc;
}
#endif
static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Dcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conj(Cd(&x[i]))._Val[0] * Cd(&y[i])._Val[0];
zdotc._Val[1] += conj(Cd(&x[i]))._Val[1] * Cd(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conj(Cd(&x[i*incx]))._Val[0] * Cd(&y[i*incy])._Val[0];
zdotc._Val[1] += conj(Cd(&x[i*incx]))._Val[1] * Cd(&y[i*incy])._Val[1];
}
}
pCd(z) = zdotc;
}
#else
_Complex double zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conj(Cd(&x[i])) * Cd(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conj(Cd(&x[i*incx])) * Cd(&y[i*incy]);
}
}
pCd(z) = zdotc;
}
#endif
static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Fcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cf(&x[i])._Val[0] * Cf(&y[i])._Val[0];
zdotc._Val[1] += Cf(&x[i])._Val[1] * Cf(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cf(&x[i*incx])._Val[0] * Cf(&y[i*incy])._Val[0];
zdotc._Val[1] += Cf(&x[i*incx])._Val[1] * Cf(&y[i*incy])._Val[1];
}
}
pCf(z) = zdotc;
}
#else
_Complex float zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cf(&x[i]) * Cf(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cf(&x[i*incx]) * Cf(&y[i*incy]);
}
}
pCf(z) = zdotc;
}
#endif
static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Dcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cd(&x[i])._Val[0] * Cd(&y[i])._Val[0];
zdotc._Val[1] += Cd(&x[i])._Val[1] * Cd(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cd(&x[i*incx])._Val[0] * Cd(&y[i*incy])._Val[0];
zdotc._Val[1] += Cd(&x[i*incx])._Val[1] * Cd(&y[i*incy])._Val[1];
}
}
pCd(z) = zdotc;
}
#else
_Complex double zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cd(&x[i]) * Cd(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cd(&x[i*incx]) * Cd(&y[i*incy]);
}
}
pCd(z) = zdotc;
}
#endif
/* -- translated by f2c (version 20000121).
You must link the resulting object file with the libraries:
-lf2c -lm (in that order)
*/
/* Table of constant values */
static integer c__1 = 1;
static integer c_n1 = -1;
static integer c__3 = 3;
static integer c__2 = 2;
/* > \brief \b DGEQRFP */
/* =========== DOCUMENTATION =========== */
/* Online html documentation available at */
/* http://www.netlib.org/lapack/explore-html/ */
/* > \htmlonly */
/* > Download DGEQRFP + dependencies */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/dgeqrfp
.f"> */
/* > [TGZ]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/dgeqrfp
.f"> */
/* > [ZIP]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/dgeqrfp
.f"> */
/* > [TXT]</a> */
/* > \endhtmlonly */
/* Definition: */
/* =========== */
/* SUBROUTINE DGEQRFP( M, N, A, LDA, TAU, WORK, LWORK, INFO ) */
/* INTEGER INFO, LDA, LWORK, M, N */
/* DOUBLE PRECISION A( LDA, * ), TAU( * ), WORK( * ) */
/* > \par Purpose: */
/* ============= */
/* > */
/* > \verbatim */
/* > */
/* > DGEQR2P computes a QR factorization of a real M-by-N matrix A: */
/* > */
/* > A = Q * ( R ), */
/* > ( 0 ) */
/* > */
/* > where: */
/* > */
/* > Q is a M-by-M orthogonal matrix; */
/* > R is an upper-triangular N-by-N matrix with nonnegative diagonal */
/* > entries; */
/* > 0 is a (M-N)-by-N zero matrix, if M > N. */
/* > */
/* > \endverbatim */
/* Arguments: */
/* ========== */
/* > \param[in] M */
/* > \verbatim */
/* > M is INTEGER */
/* > The number of rows of the matrix A. M >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in] N */
/* > \verbatim */
/* > N is INTEGER */
/* > The number of columns of the matrix A. N >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in,out] A */
/* > \verbatim */
/* > A is DOUBLE PRECISION array, dimension (LDA,N) */
/* > On entry, the M-by-N matrix A. */
/* > On exit, the elements on and above the diagonal of the array */
/* > contain the f2cmin(M,N)-by-N upper trapezoidal matrix R (R is */
/* > upper triangular if m >= n). The diagonal entries of R */
/* > are nonnegative; the elements below the diagonal, */
/* > with the array TAU, represent the orthogonal matrix Q as a */
/* > product of f2cmin(m,n) elementary reflectors (see Further */
/* > Details). */
/* > \endverbatim */
/* > */
/* > \param[in] LDA */
/* > \verbatim */
/* > LDA is INTEGER */
/* > The leading dimension of the array A. LDA >= f2cmax(1,M). */
/* > \endverbatim */
/* > */
/* > \param[out] TAU */
/* > \verbatim */
/* > TAU is DOUBLE PRECISION array, dimension (f2cmin(M,N)) */
/* > The scalar factors of the elementary reflectors (see Further */
/* > Details). */
/* > \endverbatim */
/* > */
/* > \param[out] WORK */
/* > \verbatim */
/* > WORK is DOUBLE PRECISION array, dimension (MAX(1,LWORK)) */
/* > On exit, if INFO = 0, WORK(1) returns the optimal LWORK. */
/* > \endverbatim */
/* > */
/* > \param[in] LWORK */
/* > \verbatim */
/* > LWORK is INTEGER */
/* > The dimension of the array WORK. LWORK >= f2cmax(1,N). */
/* > For optimum performance LWORK >= N*NB, where NB is */
/* > the optimal blocksize. */
/* > */
/* > If LWORK = -1, then a workspace query is assumed; the routine */
/* > only calculates the optimal size of the WORK array, returns */
/* > this value as the first entry of the WORK array, and no error */
/* > message related to LWORK is issued by XERBLA. */
/* > \endverbatim */
/* > */
/* > \param[out] INFO */
/* > \verbatim */
/* > INFO is INTEGER */
/* > = 0: successful exit */
/* > < 0: if INFO = -i, the i-th argument had an illegal value */
/* > \endverbatim */
/* Authors: */
/* ======== */
/* > \author Univ. of Tennessee */
/* > \author Univ. of California Berkeley */
/* > \author Univ. of Colorado Denver */
/* > \author NAG Ltd. */
/* > \date November 2019 */
/* > \ingroup doubleGEcomputational */
/* > \par Further Details: */
/* ===================== */
/* > */
/* > \verbatim */
/* > */
/* > The matrix Q is represented as a product of elementary reflectors */
/* > */
/* > Q = H(1) H(2) . . . H(k), where k = f2cmin(m,n). */
/* > */
/* > Each H(i) has the form */
/* > */
/* > H(i) = I - tau * v * v**T */
/* > */
/* > where tau is a real scalar, and v is a real vector with */
/* > v(1:i-1) = 0 and v(i) = 1; v(i+1:m) is stored on exit in A(i+1:m,i), */
/* > and tau in TAU(i). */
/* > */
/* > See Lapack Working Note 203 for details */
/* > \endverbatim */
/* > */
/* ===================================================================== */
/* Subroutine */ int dgeqrfp_(integer *m, integer *n, doublereal *a, integer *
lda, doublereal *tau, doublereal *work, integer *lwork, integer *info)
{
/* System generated locals */
integer a_dim1, a_offset, i__1, i__2, i__3, i__4;
/* Local variables */
integer i__, k, nbmin, iinfo, ib, nb;
extern /* Subroutine */ int dlarfb_(char *, char *, char *, char *,
integer *, integer *, integer *, doublereal *, integer *,
doublereal *, integer *, doublereal *, integer *, doublereal *,
integer *);
integer nx;
extern /* Subroutine */ int dlarft_(char *, char *, integer *, integer *,
doublereal *, integer *, doublereal *, doublereal *, integer *), xerbla_(char *, integer *, ftnlen);
extern integer ilaenv_(integer *, char *, char *, integer *, integer *,
integer *, integer *, ftnlen, ftnlen);
integer ldwork, lwkopt;
logical lquery;
extern /* Subroutine */ int dgeqr2p_(integer *, integer *, doublereal *,
integer *, doublereal *, doublereal *, integer *);
integer iws;
/* -- LAPACK computational routine (version 3.9.0) -- */
/* -- LAPACK is a software package provided by Univ. of Tennessee, -- */
/* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */
/* November 2019 */
/* ===================================================================== */
/* Test the input arguments */
/* Parameter adjustments */
a_dim1 = *lda;
a_offset = 1 + a_dim1 * 1;
a -= a_offset;
--tau;
--work;
/* Function Body */
*info = 0;
nb = ilaenv_(&c__1, "DGEQRF", " ", m, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen)
1);
lwkopt = *n * nb;
work[1] = (doublereal) lwkopt;
lquery = *lwork == -1;
if (*m < 0) {
*info = -1;
} else if (*n < 0) {
*info = -2;
} else if (*lda < f2cmax(1,*m)) {
*info = -4;
} else if (*lwork < f2cmax(1,*n) && ! lquery) {
*info = -7;
}
if (*info != 0) {
i__1 = -(*info);
xerbla_("DGEQRFP", &i__1, (ftnlen)7);
return 0;
} else if (lquery) {
return 0;
}
/* Quick return if possible */
k = f2cmin(*m,*n);
if (k == 0) {
work[1] = 1.;
return 0;
}
nbmin = 2;
nx = 0;
iws = *n;
if (nb > 1 && nb < k) {
/* Determine when to cross over from blocked to unblocked code. */
/* Computing MAX */
i__1 = 0, i__2 = ilaenv_(&c__3, "DGEQRF", " ", m, n, &c_n1, &c_n1, (
ftnlen)6, (ftnlen)1);
nx = f2cmax(i__1,i__2);
if (nx < k) {
/* Determine if workspace is large enough for blocked code. */
ldwork = *n;
iws = ldwork * nb;
if (*lwork < iws) {
/* Not enough workspace to use optimal NB: reduce NB and */
/* determine the minimum value of NB. */
nb = *lwork / ldwork;
/* Computing MAX */
i__1 = 2, i__2 = ilaenv_(&c__2, "DGEQRF", " ", m, n, &c_n1, &
c_n1, (ftnlen)6, (ftnlen)1);
nbmin = f2cmax(i__1,i__2);
}
}
}
if (nb >= nbmin && nb < k && nx < k) {
/* Use blocked code initially */
i__1 = k - nx;
i__2 = nb;
for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) {
/* Computing MIN */
i__3 = k - i__ + 1;
ib = f2cmin(i__3,nb);
/* Compute the QR factorization of the current block */
/* A(i:m,i:i+ib-1) */
i__3 = *m - i__ + 1;
dgeqr2p_(&i__3, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], &
work[1], &iinfo);
if (i__ + ib <= *n) {
/* Form the triangular factor of the block reflector */
/* H = H(i) H(i+1) . . . H(i+ib-1) */
i__3 = *m - i__ + 1;
dlarft_("Forward", "Columnwise", &i__3, &ib, &a[i__ + i__ *
a_dim1], lda, &tau[i__], &work[1], &ldwork);
/* Apply H**T to A(i:m,i+ib:n) from the left */
i__3 = *m - i__ + 1;
i__4 = *n - i__ - ib + 1;
dlarfb_("Left", "Transpose", "Forward", "Columnwise", &i__3, &
i__4, &ib, &a[i__ + i__ * a_dim1], lda, &work[1], &
ldwork, &a[i__ + (i__ + ib) * a_dim1], lda, &work[ib
+ 1], &ldwork);
}
/* L10: */
}
} else {
i__ = 1;
}
/* Use unblocked code to factor the last or only block. */
if (i__ <= k) {
i__2 = *m - i__ + 1;
i__1 = *n - i__ + 1;
dgeqr2p_(&i__2, &i__1, &a[i__ + i__ * a_dim1], lda, &tau[i__], &work[
1], &iinfo);
}
work[1] = (doublereal) iws;
return 0;
/* End of DGEQRFP */
} /* dgeqrfp_ */
|
the_stack_data/80856.c | #include <stdio.h>
//@cikey 67361819476f1ac99dde38b453a6db17
//@sid 2021157297
//@aid 6.1
int menor(int a, int b, int c);
int main(){
//begin_inputs
int A,B,C;
printf("Digite 3 numeros: \n");
scanf("%d%d%d",&A,&B,&C);
//end_inputs
menor(A,B,C);
printf("A: %d - B: %d - C: %d - menor: %d",A,B,C,menor(A,B,C));
return 0;
}
int menor(int a, int b, int c){
if (a <= b && a <= c) {
return a;
} else {
if (b <= a && b <= c) {
return b;
} else {
return c;
}
}
}
|
the_stack_data/190769271.c | #include <stdio.h>
struct date_t {
int year;
int month;
int day;
char separator;
};
void print_date(struct date_t);
int main() {
struct date_t today;
scanf("%d %d %d %c", &today.year, &today.month, &today.day, &today.separator);
print_date(today);
return 0;
}
void print_date(struct date_t date) {
printf("%d%c%d%c%d", date.year, date.separator, date.month, date.separator, date.day);
}
|
the_stack_data/73576485.c | #include <math.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <complex.h>
#ifdef complex
#undef complex
#endif
#ifdef I
#undef I
#endif
#if defined(_WIN64)
typedef long long BLASLONG;
typedef unsigned long long BLASULONG;
#else
typedef long BLASLONG;
typedef unsigned long BLASULONG;
#endif
#ifdef LAPACK_ILP64
typedef BLASLONG blasint;
#if defined(_WIN64)
#define blasabs(x) llabs(x)
#else
#define blasabs(x) labs(x)
#endif
#else
typedef int blasint;
#define blasabs(x) abs(x)
#endif
typedef blasint integer;
typedef unsigned int uinteger;
typedef char *address;
typedef short int shortint;
typedef float real;
typedef double doublereal;
typedef struct { real r, i; } complex;
typedef struct { doublereal r, i; } doublecomplex;
#ifdef _MSC_VER
static inline _Fcomplex Cf(complex *z) {_Fcomplex zz={z->r , z->i}; return zz;}
static inline _Dcomplex Cd(doublecomplex *z) {_Dcomplex zz={z->r , z->i};return zz;}
static inline _Fcomplex * _pCf(complex *z) {return (_Fcomplex*)z;}
static inline _Dcomplex * _pCd(doublecomplex *z) {return (_Dcomplex*)z;}
#else
static inline _Complex float Cf(complex *z) {return z->r + z->i*_Complex_I;}
static inline _Complex double Cd(doublecomplex *z) {return z->r + z->i*_Complex_I;}
static inline _Complex float * _pCf(complex *z) {return (_Complex float*)z;}
static inline _Complex double * _pCd(doublecomplex *z) {return (_Complex double*)z;}
#endif
#define pCf(z) (*_pCf(z))
#define pCd(z) (*_pCd(z))
typedef int logical;
typedef short int shortlogical;
typedef char logical1;
typedef char integer1;
#define TRUE_ (1)
#define FALSE_ (0)
/* Extern is for use with -E */
#ifndef Extern
#define Extern extern
#endif
/* I/O stuff */
typedef int flag;
typedef int ftnlen;
typedef int ftnint;
/*external read, write*/
typedef struct
{ flag cierr;
ftnint ciunit;
flag ciend;
char *cifmt;
ftnint cirec;
} cilist;
/*internal read, write*/
typedef struct
{ flag icierr;
char *iciunit;
flag iciend;
char *icifmt;
ftnint icirlen;
ftnint icirnum;
} icilist;
/*open*/
typedef struct
{ flag oerr;
ftnint ounit;
char *ofnm;
ftnlen ofnmlen;
char *osta;
char *oacc;
char *ofm;
ftnint orl;
char *oblnk;
} olist;
/*close*/
typedef struct
{ flag cerr;
ftnint cunit;
char *csta;
} cllist;
/*rewind, backspace, endfile*/
typedef struct
{ flag aerr;
ftnint aunit;
} alist;
/* inquire */
typedef struct
{ flag inerr;
ftnint inunit;
char *infile;
ftnlen infilen;
ftnint *inex; /*parameters in standard's order*/
ftnint *inopen;
ftnint *innum;
ftnint *innamed;
char *inname;
ftnlen innamlen;
char *inacc;
ftnlen inacclen;
char *inseq;
ftnlen inseqlen;
char *indir;
ftnlen indirlen;
char *infmt;
ftnlen infmtlen;
char *inform;
ftnint informlen;
char *inunf;
ftnlen inunflen;
ftnint *inrecl;
ftnint *innrec;
char *inblank;
ftnlen inblanklen;
} inlist;
#define VOID void
union Multitype { /* for multiple entry points */
integer1 g;
shortint h;
integer i;
/* longint j; */
real r;
doublereal d;
complex c;
doublecomplex z;
};
typedef union Multitype Multitype;
struct Vardesc { /* for Namelist */
char *name;
char *addr;
ftnlen *dims;
int type;
};
typedef struct Vardesc Vardesc;
struct Namelist {
char *name;
Vardesc **vars;
int nvars;
};
typedef struct Namelist Namelist;
#define abs(x) ((x) >= 0 ? (x) : -(x))
#define dabs(x) (fabs(x))
#define f2cmin(a,b) ((a) <= (b) ? (a) : (b))
#define f2cmax(a,b) ((a) >= (b) ? (a) : (b))
#define dmin(a,b) (f2cmin(a,b))
#define dmax(a,b) (f2cmax(a,b))
#define bit_test(a,b) ((a) >> (b) & 1)
#define bit_clear(a,b) ((a) & ~((uinteger)1 << (b)))
#define bit_set(a,b) ((a) | ((uinteger)1 << (b)))
#define abort_() { sig_die("Fortran abort routine called", 1); }
#define c_abs(z) (cabsf(Cf(z)))
#define c_cos(R,Z) { pCf(R)=ccos(Cf(Z)); }
#ifdef _MSC_VER
#define c_div(c, a, b) {Cf(c)._Val[0] = (Cf(a)._Val[0]/Cf(b)._Val[0]); Cf(c)._Val[1]=(Cf(a)._Val[1]/Cf(b)._Val[1]);}
#define z_div(c, a, b) {Cd(c)._Val[0] = (Cd(a)._Val[0]/Cd(b)._Val[0]); Cd(c)._Val[1]=(Cd(a)._Val[1]/Cd(b)._Val[1]);}
#else
#define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);}
#define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);}
#endif
#define c_exp(R, Z) {pCf(R) = cexpf(Cf(Z));}
#define c_log(R, Z) {pCf(R) = clogf(Cf(Z));}
#define c_sin(R, Z) {pCf(R) = csinf(Cf(Z));}
//#define c_sqrt(R, Z) {*(R) = csqrtf(Cf(Z));}
#define c_sqrt(R, Z) {pCf(R) = csqrtf(Cf(Z));}
#define d_abs(x) (fabs(*(x)))
#define d_acos(x) (acos(*(x)))
#define d_asin(x) (asin(*(x)))
#define d_atan(x) (atan(*(x)))
#define d_atn2(x, y) (atan2(*(x),*(y)))
#define d_cnjg(R, Z) { pCd(R) = conj(Cd(Z)); }
#define r_cnjg(R, Z) { pCf(R) = conjf(Cf(Z)); }
#define d_cos(x) (cos(*(x)))
#define d_cosh(x) (cosh(*(x)))
#define d_dim(__a, __b) ( *(__a) > *(__b) ? *(__a) - *(__b) : 0.0 )
#define d_exp(x) (exp(*(x)))
#define d_imag(z) (cimag(Cd(z)))
#define r_imag(z) (cimagf(Cf(z)))
#define d_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x)))
#define r_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x)))
#define d_lg10(x) ( 0.43429448190325182765 * log(*(x)) )
#define r_lg10(x) ( 0.43429448190325182765 * log(*(x)) )
#define d_log(x) (log(*(x)))
#define d_mod(x, y) (fmod(*(x), *(y)))
#define u_nint(__x) ((__x)>=0 ? floor((__x) + .5) : -floor(.5 - (__x)))
#define d_nint(x) u_nint(*(x))
#define u_sign(__a,__b) ((__b) >= 0 ? ((__a) >= 0 ? (__a) : -(__a)) : -((__a) >= 0 ? (__a) : -(__a)))
#define d_sign(a,b) u_sign(*(a),*(b))
#define r_sign(a,b) u_sign(*(a),*(b))
#define d_sin(x) (sin(*(x)))
#define d_sinh(x) (sinh(*(x)))
#define d_sqrt(x) (sqrt(*(x)))
#define d_tan(x) (tan(*(x)))
#define d_tanh(x) (tanh(*(x)))
#define i_abs(x) abs(*(x))
#define i_dnnt(x) ((integer)u_nint(*(x)))
#define i_len(s, n) (n)
#define i_nint(x) ((integer)u_nint(*(x)))
#define i_sign(a,b) ((integer)u_sign((integer)*(a),(integer)*(b)))
#define pow_dd(ap, bp) ( pow(*(ap), *(bp)))
#define pow_si(B,E) spow_ui(*(B),*(E))
#define pow_ri(B,E) spow_ui(*(B),*(E))
#define pow_di(B,E) dpow_ui(*(B),*(E))
#define pow_zi(p, a, b) {pCd(p) = zpow_ui(Cd(a), *(b));}
#define pow_ci(p, a, b) {pCf(p) = cpow_ui(Cf(a), *(b));}
#define pow_zz(R,A,B) {pCd(R) = cpow(Cd(A),*(B));}
#define s_cat(lpp, rpp, rnp, np, llp) { ftnlen i, nc, ll; char *f__rp, *lp; ll = (llp); lp = (lpp); for(i=0; i < (int)*(np); ++i) { nc = ll; if((rnp)[i] < nc) nc = (rnp)[i]; ll -= nc; f__rp = (rpp)[i]; while(--nc >= 0) *lp++ = *(f__rp)++; } while(--ll >= 0) *lp++ = ' '; }
#define s_cmp(a,b,c,d) ((integer)strncmp((a),(b),f2cmin((c),(d))))
#define s_copy(A,B,C,D) { int __i,__m; for (__i=0, __m=f2cmin((C),(D)); __i<__m && (B)[__i] != 0; ++__i) (A)[__i] = (B)[__i]; }
#define sig_die(s, kill) { exit(1); }
#define s_stop(s, n) {exit(0);}
static char junk[] = "\n@(#)LIBF77 VERSION 19990503\n";
#define z_abs(z) (cabs(Cd(z)))
#define z_exp(R, Z) {pCd(R) = cexp(Cd(Z));}
#define z_sqrt(R, Z) {pCd(R) = csqrt(Cd(Z));}
#define myexit_() break;
#define mycycle() continue;
#define myceiling(w) {ceil(w)}
#define myhuge(w) {HUGE_VAL}
//#define mymaxloc_(w,s,e,n) {if (sizeof(*(w)) == sizeof(double)) dmaxloc_((w),*(s),*(e),n); else dmaxloc_((w),*(s),*(e),n);}
#define mymaxloc(w,s,e,n) {dmaxloc_(w,*(s),*(e),n)}
/* procedure parameter types for -A and -C++ */
#define F2C_proc_par_types 1
#ifdef __cplusplus
typedef logical (*L_fp)(...);
#else
typedef logical (*L_fp)();
#endif
static float spow_ui(float x, integer n) {
float pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static double dpow_ui(double x, integer n) {
double pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
#ifdef _MSC_VER
static _Fcomplex cpow_ui(complex x, integer n) {
complex pow={1.0,0.0}; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x.r = 1/x.r, x.i=1/x.i;
for(u = n; ; ) {
if(u & 01) pow.r *= x.r, pow.i *= x.i;
if(u >>= 1) x.r *= x.r, x.i *= x.i;
else break;
}
}
_Fcomplex p={pow.r, pow.i};
return p;
}
#else
static _Complex float cpow_ui(_Complex float x, integer n) {
_Complex float pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
#endif
#ifdef _MSC_VER
static _Dcomplex zpow_ui(_Dcomplex x, integer n) {
_Dcomplex pow={1.0,0.0}; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x._Val[0] = 1/x._Val[0], x._Val[1] =1/x._Val[1];
for(u = n; ; ) {
if(u & 01) pow._Val[0] *= x._Val[0], pow._Val[1] *= x._Val[1];
if(u >>= 1) x._Val[0] *= x._Val[0], x._Val[1] *= x._Val[1];
else break;
}
}
_Dcomplex p = {pow._Val[0], pow._Val[1]};
return p;
}
#else
static _Complex double zpow_ui(_Complex double x, integer n) {
_Complex double pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
#endif
static integer pow_ii(integer x, integer n) {
integer pow; unsigned long int u;
if (n <= 0) {
if (n == 0 || x == 1) pow = 1;
else if (x != -1) pow = x == 0 ? 1/x : 0;
else n = -n;
}
if ((n > 0) || !(n == 0 || x == 1 || x != -1)) {
u = n;
for(pow = 1; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static integer dmaxloc_(double *w, integer s, integer e, integer *n)
{
double m; integer i, mi;
for(m=w[s-1], mi=s, i=s+1; i<=e; i++)
if (w[i-1]>m) mi=i ,m=w[i-1];
return mi-s+1;
}
static integer smaxloc_(float *w, integer s, integer e, integer *n)
{
float m; integer i, mi;
for(m=w[s-1], mi=s, i=s+1; i<=e; i++)
if (w[i-1]>m) mi=i ,m=w[i-1];
return mi-s+1;
}
static inline void cdotc_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Fcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conjf(Cf(&x[i]))._Val[0] * Cf(&y[i])._Val[0];
zdotc._Val[1] += conjf(Cf(&x[i]))._Val[1] * Cf(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conjf(Cf(&x[i*incx]))._Val[0] * Cf(&y[i*incy])._Val[0];
zdotc._Val[1] += conjf(Cf(&x[i*incx]))._Val[1] * Cf(&y[i*incy])._Val[1];
}
}
pCf(z) = zdotc;
}
#else
_Complex float zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conjf(Cf(&x[i])) * Cf(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conjf(Cf(&x[i*incx])) * Cf(&y[i*incy]);
}
}
pCf(z) = zdotc;
}
#endif
static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Dcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conj(Cd(&x[i]))._Val[0] * Cd(&y[i])._Val[0];
zdotc._Val[1] += conj(Cd(&x[i]))._Val[1] * Cd(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conj(Cd(&x[i*incx]))._Val[0] * Cd(&y[i*incy])._Val[0];
zdotc._Val[1] += conj(Cd(&x[i*incx]))._Val[1] * Cd(&y[i*incy])._Val[1];
}
}
pCd(z) = zdotc;
}
#else
_Complex double zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conj(Cd(&x[i])) * Cd(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conj(Cd(&x[i*incx])) * Cd(&y[i*incy]);
}
}
pCd(z) = zdotc;
}
#endif
static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Fcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cf(&x[i])._Val[0] * Cf(&y[i])._Val[0];
zdotc._Val[1] += Cf(&x[i])._Val[1] * Cf(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cf(&x[i*incx])._Val[0] * Cf(&y[i*incy])._Val[0];
zdotc._Val[1] += Cf(&x[i*incx])._Val[1] * Cf(&y[i*incy])._Val[1];
}
}
pCf(z) = zdotc;
}
#else
_Complex float zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cf(&x[i]) * Cf(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cf(&x[i*incx]) * Cf(&y[i*incy]);
}
}
pCf(z) = zdotc;
}
#endif
static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Dcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cd(&x[i])._Val[0] * Cd(&y[i])._Val[0];
zdotc._Val[1] += Cd(&x[i])._Val[1] * Cd(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cd(&x[i*incx])._Val[0] * Cd(&y[i*incy])._Val[0];
zdotc._Val[1] += Cd(&x[i*incx])._Val[1] * Cd(&y[i*incy])._Val[1];
}
}
pCd(z) = zdotc;
}
#else
_Complex double zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cd(&x[i]) * Cd(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cd(&x[i*incx]) * Cd(&y[i*incy]);
}
}
pCd(z) = zdotc;
}
#endif
/* -- translated by f2c (version 20000121).
You must link the resulting object file with the libraries:
-lf2c -lm (in that order)
*/
/* Table of constant values */
static doublecomplex c_b1 = {0.,0.};
static integer c__1 = 1;
/* > \brief \b ZLARZT forms the triangular factor T of a block reflector H = I - vtvH. */
/* =========== DOCUMENTATION =========== */
/* Online html documentation available at */
/* http://www.netlib.org/lapack/explore-html/ */
/* > \htmlonly */
/* > Download ZLARZT + dependencies */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/zlarzt.
f"> */
/* > [TGZ]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/zlarzt.
f"> */
/* > [ZIP]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/zlarzt.
f"> */
/* > [TXT]</a> */
/* > \endhtmlonly */
/* Definition: */
/* =========== */
/* SUBROUTINE ZLARZT( DIRECT, STOREV, N, K, V, LDV, TAU, T, LDT ) */
/* CHARACTER DIRECT, STOREV */
/* INTEGER K, LDT, LDV, N */
/* COMPLEX*16 T( LDT, * ), TAU( * ), V( LDV, * ) */
/* > \par Purpose: */
/* ============= */
/* > */
/* > \verbatim */
/* > */
/* > ZLARZT forms the triangular factor T of a complex block reflector */
/* > H of order > n, which is defined as a product of k elementary */
/* > reflectors. */
/* > */
/* > If DIRECT = 'F', H = H(1) H(2) . . . H(k) and T is upper triangular; */
/* > */
/* > If DIRECT = 'B', H = H(k) . . . H(2) H(1) and T is lower triangular. */
/* > */
/* > If STOREV = 'C', the vector which defines the elementary reflector */
/* > H(i) is stored in the i-th column of the array V, and */
/* > */
/* > H = I - V * T * V**H */
/* > */
/* > If STOREV = 'R', the vector which defines the elementary reflector */
/* > H(i) is stored in the i-th row of the array V, and */
/* > */
/* > H = I - V**H * T * V */
/* > */
/* > Currently, only STOREV = 'R' and DIRECT = 'B' are supported. */
/* > \endverbatim */
/* Arguments: */
/* ========== */
/* > \param[in] DIRECT */
/* > \verbatim */
/* > DIRECT is CHARACTER*1 */
/* > Specifies the order in which the elementary reflectors are */
/* > multiplied to form the block reflector: */
/* > = 'F': H = H(1) H(2) . . . H(k) (Forward, not supported yet) */
/* > = 'B': H = H(k) . . . H(2) H(1) (Backward) */
/* > \endverbatim */
/* > */
/* > \param[in] STOREV */
/* > \verbatim */
/* > STOREV is CHARACTER*1 */
/* > Specifies how the vectors which define the elementary */
/* > reflectors are stored (see also Further Details): */
/* > = 'C': columnwise (not supported yet) */
/* > = 'R': rowwise */
/* > \endverbatim */
/* > */
/* > \param[in] N */
/* > \verbatim */
/* > N is INTEGER */
/* > The order of the block reflector H. N >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in] K */
/* > \verbatim */
/* > K is INTEGER */
/* > The order of the triangular factor T (= the number of */
/* > elementary reflectors). K >= 1. */
/* > \endverbatim */
/* > */
/* > \param[in,out] V */
/* > \verbatim */
/* > V is COMPLEX*16 array, dimension */
/* > (LDV,K) if STOREV = 'C' */
/* > (LDV,N) if STOREV = 'R' */
/* > The matrix V. See further details. */
/* > \endverbatim */
/* > */
/* > \param[in] LDV */
/* > \verbatim */
/* > LDV is INTEGER */
/* > The leading dimension of the array V. */
/* > If STOREV = 'C', LDV >= f2cmax(1,N); if STOREV = 'R', LDV >= K. */
/* > \endverbatim */
/* > */
/* > \param[in] TAU */
/* > \verbatim */
/* > TAU is COMPLEX*16 array, dimension (K) */
/* > TAU(i) must contain the scalar factor of the elementary */
/* > reflector H(i). */
/* > \endverbatim */
/* > */
/* > \param[out] T */
/* > \verbatim */
/* > T is COMPLEX*16 array, dimension (LDT,K) */
/* > The k by k triangular factor T of the block reflector. */
/* > If DIRECT = 'F', T is upper triangular; if DIRECT = 'B', T is */
/* > lower triangular. The rest of the array is not used. */
/* > \endverbatim */
/* > */
/* > \param[in] LDT */
/* > \verbatim */
/* > LDT is INTEGER */
/* > The leading dimension of the array T. LDT >= K. */
/* > \endverbatim */
/* Authors: */
/* ======== */
/* > \author Univ. of Tennessee */
/* > \author Univ. of California Berkeley */
/* > \author Univ. of Colorado Denver */
/* > \author NAG Ltd. */
/* > \date December 2016 */
/* > \ingroup complex16OTHERcomputational */
/* > \par Contributors: */
/* ================== */
/* > */
/* > A. Petitet, Computer Science Dept., Univ. of Tenn., Knoxville, USA */
/* > \par Further Details: */
/* ===================== */
/* > */
/* > \verbatim */
/* > */
/* > The shape of the matrix V and the storage of the vectors which define */
/* > the H(i) is best illustrated by the following example with n = 5 and */
/* > k = 3. The elements equal to 1 are not stored; the corresponding */
/* > array elements are modified but restored on exit. The rest of the */
/* > array is not used. */
/* > */
/* > DIRECT = 'F' and STOREV = 'C': DIRECT = 'F' and STOREV = 'R': */
/* > */
/* > ______V_____ */
/* > ( v1 v2 v3 ) / \ */
/* > ( v1 v2 v3 ) ( v1 v1 v1 v1 v1 . . . . 1 ) */
/* > V = ( v1 v2 v3 ) ( v2 v2 v2 v2 v2 . . . 1 ) */
/* > ( v1 v2 v3 ) ( v3 v3 v3 v3 v3 . . 1 ) */
/* > ( v1 v2 v3 ) */
/* > . . . */
/* > . . . */
/* > 1 . . */
/* > 1 . */
/* > 1 */
/* > */
/* > DIRECT = 'B' and STOREV = 'C': DIRECT = 'B' and STOREV = 'R': */
/* > */
/* > ______V_____ */
/* > 1 / \ */
/* > . 1 ( 1 . . . . v1 v1 v1 v1 v1 ) */
/* > . . 1 ( . 1 . . . v2 v2 v2 v2 v2 ) */
/* > . . . ( . . 1 . . v3 v3 v3 v3 v3 ) */
/* > . . . */
/* > ( v1 v2 v3 ) */
/* > ( v1 v2 v3 ) */
/* > V = ( v1 v2 v3 ) */
/* > ( v1 v2 v3 ) */
/* > ( v1 v2 v3 ) */
/* > \endverbatim */
/* > */
/* ===================================================================== */
/* Subroutine */ int zlarzt_(char *direct, char *storev, integer *n, integer *
k, doublecomplex *v, integer *ldv, doublecomplex *tau, doublecomplex *
t, integer *ldt)
{
/* System generated locals */
integer t_dim1, t_offset, v_dim1, v_offset, i__1, i__2;
doublecomplex z__1;
/* Local variables */
integer info, i__, j;
extern logical lsame_(char *, char *);
extern /* Subroutine */ int zgemv_(char *, integer *, integer *,
doublecomplex *, doublecomplex *, integer *, doublecomplex *,
integer *, doublecomplex *, doublecomplex *, integer *),
ztrmv_(char *, char *, char *, integer *, doublecomplex *,
integer *, doublecomplex *, integer *),
xerbla_(char *, integer *, ftnlen), zlacgv_(integer *,
doublecomplex *, integer *);
/* -- LAPACK computational routine (version 3.7.0) -- */
/* -- LAPACK is a software package provided by Univ. of Tennessee, -- */
/* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */
/* December 2016 */
/* ===================================================================== */
/* Check for currently supported options */
/* Parameter adjustments */
v_dim1 = *ldv;
v_offset = 1 + v_dim1 * 1;
v -= v_offset;
--tau;
t_dim1 = *ldt;
t_offset = 1 + t_dim1 * 1;
t -= t_offset;
/* Function Body */
info = 0;
if (! lsame_(direct, "B")) {
info = -1;
} else if (! lsame_(storev, "R")) {
info = -2;
}
if (info != 0) {
i__1 = -info;
xerbla_("ZLARZT", &i__1, (ftnlen)6);
return 0;
}
for (i__ = *k; i__ >= 1; --i__) {
i__1 = i__;
if (tau[i__1].r == 0. && tau[i__1].i == 0.) {
/* H(i) = I */
i__1 = *k;
for (j = i__; j <= i__1; ++j) {
i__2 = j + i__ * t_dim1;
t[i__2].r = 0., t[i__2].i = 0.;
/* L10: */
}
} else {
/* general case */
if (i__ < *k) {
/* T(i+1:k,i) = - tau(i) * V(i+1:k,1:n) * V(i,1:n)**H */
zlacgv_(n, &v[i__ + v_dim1], ldv);
i__1 = *k - i__;
i__2 = i__;
z__1.r = -tau[i__2].r, z__1.i = -tau[i__2].i;
zgemv_("No transpose", &i__1, n, &z__1, &v[i__ + 1 + v_dim1],
ldv, &v[i__ + v_dim1], ldv, &c_b1, &t[i__ + 1 + i__ *
t_dim1], &c__1);
zlacgv_(n, &v[i__ + v_dim1], ldv);
/* T(i+1:k,i) = T(i+1:k,i+1:k) * T(i+1:k,i) */
i__1 = *k - i__;
ztrmv_("Lower", "No transpose", "Non-unit", &i__1, &t[i__ + 1
+ (i__ + 1) * t_dim1], ldt, &t[i__ + 1 + i__ * t_dim1]
, &c__1);
}
i__1 = i__ + i__ * t_dim1;
i__2 = i__;
t[i__1].r = tau[i__2].r, t[i__1].i = tau[i__2].i;
}
/* L20: */
}
return 0;
/* End of ZLARZT */
} /* zlarzt_ */
|
the_stack_data/63280.c | #include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
char z_ib[BUFSIZ], *z_ip = &z_ib[BUFSIZ];
char z_ob[BUFSIZ], *z_op = z_ob;
char z_nb[31], *z_np;
#define z_pc(x__) \
do { \
if (z_op == &z_ob[BUFSIZ]) { \
z_op = z_ob; \
fwrite(z_op, 1, BUFSIZ, stdout); \
} \
*z_op++ = x__; \
} while (0)
#define z_put(type__, x__, code__) \
do { \
register type__ x_ = (x__); \
z_np = z_nb; \
if (!x_) \
*++z_np = '0'; \
while (x_) { \
*++z_np = x_ % 10 + '0'; \
x_ /= 10; \
} \
while (z_np != z_nb) \
z_pc(*z_np--); \
code__; \
} while (0)
#define z_gc() \
(z_ip == &z_ib[BUFSIZ] ? \
z_ip = z_ib, fread(z_ip, 1, BUFSIZ, stdin), *z_ip++ : \
*z_ip++)
#define z_get(x__) \
do { \
register int f_ = 1, ch_; \
while (!isdigit(ch_ = z_gc())) \
if (ch_ == '-') \
f_ = -1; \
x__ = ch_ - '0'; \
while (isdigit(ch_ = z_gc())) \
x__ = x__ * 10 + ch_ - '0'; \
x__ *= f_; \
} while (0)
void z_flush(void)
{
fwrite(z_ob, z_op - z_ob, 1, stdout);
}
#define z_ini() \
atexit(z_flush);
#include <stdio.h>
long long f[309][309];
#define MOD 1000000007LL
int main(void)
{
register int i, j, k;
register int n, m;
z_ini();
#ifndef ONLINE_JUDGE
freopen("cake.in", "r", stdin);
#ifndef DEBUG
freopen("cake.out", "w", stdout);
#else
setvbuf(stdout, NULL, _IONBF, 0);
#endif
#endif
z_get(n);
z_get(m);
f[1][1] = 1;
for (i = 2; i <= m; ++i)
for (k = 1; k < i; ++k)
f[1][i] = (f[1][i] + f[1][i - k] * f[1][k] % MOD) % MOD;
for (i = 2; i <= n; ++i)
for (j = 1; j <= m; ++j) {
for (k = 1; k < i; ++k)
f[i][j] = (f[i][j] + f[i - k][j] *
f[k][j] % MOD) % MOD;
for (k = 1; k < j; ++k)
f[i][j] = (f[i][j] + f[i][j - k] *
f[i][k] % MOD) % MOD;
}
z_put(long long, f[n][m], z_pc('\n'));
return 0;
}
|
the_stack_data/424268.c | #include<stdio.h>
#include<string.h> |
the_stack_data/858323.c | /*Exercise 2 - Selection
Write a program to calculate the amount to be paid for a rented vehicle.
• Input the distance the van has travelled
• The first 30 km is at a rate of 50/= per km.
• The remaining distance is calculated at the rate of 40/= per km.
e.g.
Distance -> 20
Amount = 20 x 50 = 1000
Distance -> 50
Amount = 30 x 50 + (50-30) x 40 = 2300*/
#include <stdio.h>
int main() {
int dis;
float amt;
printf("Enter Distance : ");
scanf("%d", &dis);
if(dis < 30)
{
amt= 50 * dis;
printf("Amount :%.2f",amt);
}
else if(dis >= 30)
{
amt= 50 * 30 +(dis-30) * 40;
printf("Amount :%.2f",amt);
}
else{
printf("error");
}
return 0;
}
|
the_stack_data/145451890.c | #include <stdio.h>
#include <stdlib.h>
int FactorialFunction(int num)
{
int result = 1;
for(int i = 1;i <= num;i++)
{
result *= i;
}
return result;
}
int main()
{
int number, Print_Result;
int number2, Print_Result2;
printf("Enter the first number: ");
scanf("%d", &number);
printf("Enter the second number: ");
scanf("%d", &number2);
Print_Result = FactorialFunction(number);
Print_Result2 = FactorialFunction(number2);
printf("\n\nThe first factorial number of %d is %d", number, Print_Result);
printf("\nThe second factorial number of %d is %d\n", number2, Print_Result2);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.