diff --git a/pool/shard000/C/0008448_Timeout.c b/pool/shard000/C/0008448_Timeout.c new file mode 100644 index 0000000000000000000000000000000000000000..d4e5a37cccb4e0b2c33b7ff01855e0e53c5ecfd3 --- /dev/null +++ b/pool/shard000/C/0008448_Timeout.c @@ -0,0 +1,138 @@ +/* vim: set expandtab ts=4 sw=4: */ +/* + * You may redistribute this program 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 + * along with this program. If not, see . + */ +#include "util/events/libuv/UvWrapper.h" +#include "memory/Allocator.h" +#include "util/events/libuv/EventBase_pvt.h" +#include "util/events/Timeout.h" +#include "util/Identity.h" + +struct Timeout +{ + uv_timer_t timer; + + void (* callback)(void* callbackContext); + + void* callbackContext; + + uint64_t milliseconds; + + int isInterval; + + struct Allocator* alloc; + + Identity +}; + +/** + * The callback to be called by libuv. + */ +static void handleEvent(uv_timer_t* handle, int status) +{ + struct Timeout* timeout = Identity_check((struct Timeout*) handle); + if (!timeout->isInterval) { + Timeout_clearTimeout(timeout); + } + timeout->callback(timeout->callbackContext); +} + +static void onFree2(uv_handle_t* timer) +{ + Allocator_onFreeComplete(timer->data); +} + +static int onFree(struct Allocator_OnFreeJob* job) +{ + struct Timeout* t = Identity_check((struct Timeout*) job->userData); + t->timer.data = job; + uv_close((uv_handle_t*) &t->timer, onFree2); + return Allocator_ONFREE_ASYNC; +} + +/** + * Create a timeout event. + * The timeout event will be triggered after the given number of milliseconds. + * + * @param callback the functiont to call. + * @param callbackContext a pointer to pass to the called function. + * @param milliseconds the number of milliseconds to wait before the event happens. + * @param interval if non-zero, this event will repeat instead of triggering once. + * @param eventBase the libevent event base. + * @param allocator the memory allocator to use for allocating the event. + * if this is freed, the event will be safely deleted. + * @return a timeout struct which can be used to clear the timeout. + */ +static struct Timeout* setTimeout(void (* const callback)(void* callbackContext), + void* const callbackContext, + const uint64_t milliseconds, + const uint32_t interval, + struct EventBase* eventBase, + struct Allocator* allocator) +{ + struct EventBase_pvt* base = EventBase_privatize(eventBase); + struct Allocator* alloc = Allocator_child(allocator); + struct Timeout* timeout = Allocator_calloc(alloc, sizeof(struct Timeout), 1); + + timeout->callback = callback; + timeout->callbackContext = callbackContext; + timeout->milliseconds = milliseconds; + timeout->alloc = alloc; + timeout->isInterval = interval; + Identity_set(timeout); + + uv_timer_init(base->loop, &timeout->timer); + uv_timer_start(&timeout->timer, handleEvent, milliseconds, (interval) ? milliseconds : 0); + + timeout->timer.data = timeout; + + Allocator_onFree(alloc, onFree, timeout); + + return timeout; +} + +/** See: Timeout.h */ +struct Timeout* Timeout_setTimeout(void (* const callback)(void* callbackContext), + void* const callbackContext, + const uint64_t milliseconds, + struct EventBase* eventBase, + struct Allocator* allocator) +{ + return setTimeout(callback, callbackContext, milliseconds, 0, eventBase, allocator); +} + +/** See: Timeout.h */ +struct Timeout* Timeout_setInterval(void (* const callback)(void* callbackContext), + void* const callbackContext, + const uint64_t milliseconds, + struct EventBase* eventBase, + struct Allocator* allocator) +{ + return setTimeout(callback, callbackContext, milliseconds, 1, eventBase, allocator); +} + +/** See: Timeout.h */ +void Timeout_resetTimeout(struct Timeout* timeout, + const uint64_t milliseconds) +{ + Timeout_clearTimeout(timeout); + uv_timer_start(&timeout->timer, handleEvent, milliseconds, 0); +} + +/** See: Timeout.h */ +void Timeout_clearTimeout(struct Timeout* timeout) +{ + if (!uv_is_closing((uv_handle_t*) &timeout->timer)) { + uv_timer_stop(&timeout->timer); + } +} diff --git a/pool/shard000/C/0008450_en_clock.c b/pool/shard000/C/0008450_en_clock.c new file mode 100644 index 0000000000000000000000000000000000000000..015198c14fa8531589f4443cb770989d629f51e6 --- /dev/null +++ b/pool/shard000/C/0008450_en_clock.c @@ -0,0 +1,308 @@ +/* + * Copyright (c) 2012 Mellanox Technologies. All rights reserved. + * + * This software is available to you under a choice of one of two + * licenses. You may choose to be licensed under the terms of the GNU + * General Public License (GPL) Version 2, available from the file + * COPYING in the main directory of this source tree, or the + * OpenIB.org BSD license below: + * + * 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. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +#include +#include + +#include "mlx4_en.h" + +/* mlx4_en_read_clock - read raw cycle counter (to be used by time counter) + */ +static u64 mlx4_en_read_clock(const struct cyclecounter *tc) +{ + struct mlx4_en_dev *mdev = + container_of(tc, struct mlx4_en_dev, cycles); + struct mlx4_dev *dev = mdev->dev; + + return mlx4_read_clock(dev) & tc->mask; +} + +u64 mlx4_en_get_cqe_ts(struct mlx4_cqe *cqe) +{ + u64 hi, lo; + struct mlx4_ts_cqe *ts_cqe = (struct mlx4_ts_cqe *)cqe; + + lo = (u64)be16_to_cpu(ts_cqe->timestamp_lo); + hi = ((u64)be32_to_cpu(ts_cqe->timestamp_hi) + !lo) << 16; + + return hi | lo; +} + +void mlx4_en_fill_hwtstamps(struct mlx4_en_dev *mdev, + struct skb_shared_hwtstamps *hwts, + u64 timestamp) +{ + unsigned long flags; + u64 nsec; + + read_lock_irqsave(&mdev->clock_lock, flags); + nsec = timecounter_cyc2time(&mdev->clock, timestamp); + read_unlock_irqrestore(&mdev->clock_lock, flags); + + memset(hwts, 0, sizeof(struct skb_shared_hwtstamps)); + hwts->hwtstamp = ns_to_ktime(nsec); +} + +/** + * mlx4_en_remove_timestamp - disable PTP device + * @mdev: board private structure + * + * Stop the PTP support. + **/ +void mlx4_en_remove_timestamp(struct mlx4_en_dev *mdev) +{ + if (mdev->ptp_clock) { + ptp_clock_unregister(mdev->ptp_clock); + mdev->ptp_clock = NULL; + mlx4_info(mdev, "removed PHC\n"); + } +} + +void mlx4_en_ptp_overflow_check(struct mlx4_en_dev *mdev) +{ + bool timeout = time_is_before_jiffies(mdev->last_overflow_check + + mdev->overflow_period); + unsigned long flags; + + if (timeout) { + write_lock_irqsave(&mdev->clock_lock, flags); + timecounter_read(&mdev->clock); + write_unlock_irqrestore(&mdev->clock_lock, flags); + mdev->last_overflow_check = jiffies; + } +} + +/** + * mlx4_en_phc_adjfreq - adjust the frequency of the hardware clock + * @ptp: ptp clock structure + * @delta: Desired frequency change in parts per billion + * + * Adjust the frequency of the PHC cycle counter by the indicated delta from + * the base frequency. + **/ +static int mlx4_en_phc_adjfreq(struct ptp_clock_info *ptp, s32 delta) +{ + u64 adj; + u32 diff, mult; + int neg_adj = 0; + unsigned long flags; + struct mlx4_en_dev *mdev = container_of(ptp, struct mlx4_en_dev, + ptp_clock_info); + + if (delta < 0) { + neg_adj = 1; + delta = -delta; + } + mult = mdev->nominal_c_mult; + adj = mult; + adj *= delta; + diff = div_u64(adj, 1000000000ULL); + + write_lock_irqsave(&mdev->clock_lock, flags); + timecounter_read(&mdev->clock); + mdev->cycles.mult = neg_adj ? mult - diff : mult + diff; + write_unlock_irqrestore(&mdev->clock_lock, flags); + + return 0; +} + +/** + * mlx4_en_phc_adjtime - Shift the time of the hardware clock + * @ptp: ptp clock structure + * @delta: Desired change in nanoseconds + * + * Adjust the timer by resetting the timecounter structure. + **/ +static int mlx4_en_phc_adjtime(struct ptp_clock_info *ptp, s64 delta) +{ + struct mlx4_en_dev *mdev = container_of(ptp, struct mlx4_en_dev, + ptp_clock_info); + unsigned long flags; + + write_lock_irqsave(&mdev->clock_lock, flags); + timecounter_adjtime(&mdev->clock, delta); + write_unlock_irqrestore(&mdev->clock_lock, flags); + + return 0; +} + +/** + * mlx4_en_phc_gettime - Reads the current time from the hardware clock + * @ptp: ptp clock structure + * @ts: timespec structure to hold the current time value + * + * Read the timecounter and return the correct value in ns after converting + * it into a struct timespec. + **/ +static int mlx4_en_phc_gettime(struct ptp_clock_info *ptp, + struct timespec64 *ts) +{ + struct mlx4_en_dev *mdev = container_of(ptp, struct mlx4_en_dev, + ptp_clock_info); + unsigned long flags; + u64 ns; + + write_lock_irqsave(&mdev->clock_lock, flags); + ns = timecounter_read(&mdev->clock); + write_unlock_irqrestore(&mdev->clock_lock, flags); + + *ts = ns_to_timespec64(ns); + + return 0; +} + +/** + * mlx4_en_phc_settime - Set the current time on the hardware clock + * @ptp: ptp clock structure + * @ts: timespec containing the new time for the cycle counter + * + * Reset the timecounter to use a new base value instead of the kernel + * wall timer value. + **/ +static int mlx4_en_phc_settime(struct ptp_clock_info *ptp, + const struct timespec64 *ts) +{ + struct mlx4_en_dev *mdev = container_of(ptp, struct mlx4_en_dev, + ptp_clock_info); + u64 ns = timespec64_to_ns(ts); + unsigned long flags; + + /* reset the timecounter */ + write_lock_irqsave(&mdev->clock_lock, flags); + timecounter_init(&mdev->clock, &mdev->cycles, ns); + write_unlock_irqrestore(&mdev->clock_lock, flags); + + return 0; +} + +/** + * mlx4_en_phc_enable - enable or disable an ancillary feature + * @ptp: ptp clock structure + * @request: Desired resource to enable or disable + * @on: Caller passes one to enable or zero to disable + * + * Enable (or disable) ancillary features of the PHC subsystem. + * Currently, no ancillary features are supported. + **/ +static int mlx4_en_phc_enable(struct ptp_clock_info __always_unused *ptp, + struct ptp_clock_request __always_unused *request, + int __always_unused on) +{ + return -EOPNOTSUPP; +} + +static const struct ptp_clock_info mlx4_en_ptp_clock_info = { + .owner = THIS_MODULE, + .max_adj = 100000000, + .n_alarm = 0, + .n_ext_ts = 0, + .n_per_out = 0, + .n_pins = 0, + .pps = 0, + .adjfreq = mlx4_en_phc_adjfreq, + .adjtime = mlx4_en_phc_adjtime, + .gettime64 = mlx4_en_phc_gettime, + .settime64 = mlx4_en_phc_settime, + .enable = mlx4_en_phc_enable, +}; + +#define MLX4_EN_WRAP_AROUND_SEC 10ULL + +/* This function calculates the max shift that enables the user range + * of MLX4_EN_WRAP_AROUND_SEC values in the cycles register. + */ +static u32 freq_to_shift(u16 freq) +{ + u32 freq_khz = freq * 1000; + u64 max_val_cycles = freq_khz * 1000 * MLX4_EN_WRAP_AROUND_SEC; + u64 tmp_rounded = + roundup_pow_of_two(max_val_cycles) > max_val_cycles ? + roundup_pow_of_two(max_val_cycles) - 1 : UINT_MAX; + u64 max_val_cycles_rounded = is_power_of_2(max_val_cycles + 1) ? + max_val_cycles : tmp_rounded; + /* calculate max possible multiplier in order to fit in 64bit */ + u64 max_mul = div_u64(0xffffffffffffffffULL, max_val_cycles_rounded); + + /* This comes from the reverse of clocksource_khz2mult */ + return ilog2(div_u64(max_mul * freq_khz, 1000000)); +} + +void mlx4_en_init_timestamp(struct mlx4_en_dev *mdev) +{ + struct mlx4_dev *dev = mdev->dev; + unsigned long flags; + u64 ns, zero = 0; + + /* mlx4_en_init_timestamp is called for each netdev. + * mdev->ptp_clock is common for all ports, skip initialization if + * was done for other port. + */ + if (mdev->ptp_clock) + return; + + rwlock_init(&mdev->clock_lock); + + memset(&mdev->cycles, 0, sizeof(mdev->cycles)); + mdev->cycles.read = mlx4_en_read_clock; + mdev->cycles.mask = CLOCKSOURCE_MASK(48); + mdev->cycles.shift = freq_to_shift(dev->caps.hca_core_clock); + mdev->cycles.mult = + clocksource_khz2mult(1000 * dev->caps.hca_core_clock, mdev->cycles.shift); + mdev->nominal_c_mult = mdev->cycles.mult; + + write_lock_irqsave(&mdev->clock_lock, flags); + timecounter_init(&mdev->clock, &mdev->cycles, + ktime_to_ns(ktime_get_real())); + write_unlock_irqrestore(&mdev->clock_lock, flags); + + /* Calculate period in seconds to call the overflow watchdog - to make + * sure counter is checked at least once every wrap around. + */ + ns = cyclecounter_cyc2ns(&mdev->cycles, mdev->cycles.mask, zero, &zero); + do_div(ns, NSEC_PER_SEC / 2 / HZ); + mdev->overflow_period = ns; + + /* Configure the PHC */ + mdev->ptp_clock_info = mlx4_en_ptp_clock_info; + snprintf(mdev->ptp_clock_info.name, 16, "mlx4 ptp"); + + mdev->ptp_clock = ptp_clock_register(&mdev->ptp_clock_info, + &mdev->pdev->dev); + if (IS_ERR(mdev->ptp_clock)) { + mdev->ptp_clock = NULL; + mlx4_err(mdev, "ptp_clock_register failed\n"); + } else if (mdev->ptp_clock) { + mlx4_info(mdev, "registered PHC clock\n"); + } + +} diff --git a/pool/shard000/C/0008452_rpc_sign.c b/pool/shard000/C/0008452_rpc_sign.c new file mode 100644 index 0000000000000000000000000000000000000000..0bfdcee5ae5a55caf1687c3035d22a2e46853690 --- /dev/null +++ b/pool/shard000/C/0008452_rpc_sign.c @@ -0,0 +1,109 @@ + +/* + * Licensed Materials - Property of IBM + * + * trousers - An open source TCG Software Stack + * + * (C) Copyright International Business Machines Corp. 2004-2006 + * + */ + +#include +#include +#include +#include +#include + +#include "trousers/tss.h" +#include "trousers_types.h" +#include "tcs_tsp.h" +#include "tcs_utils.h" +#include "tcs_int_literals.h" +#include "capabilities.h" +#include "tcslog.h" +#include "tcsd_wrap.h" +#include "tcsd.h" +#include "tcs_utils.h" +#include "rpc_tcstp_tcs.h" + + +TSS_RESULT +tcs_wrap_Sign(struct tcsd_thread_data *data) +{ + TCS_CONTEXT_HANDLE hContext; + TCS_KEY_HANDLE hKey; + UINT32 areaToSignSize; + BYTE *areaToSign; + + TPM_AUTH auth; + TPM_AUTH *pAuth; + + UINT32 sigSize; + BYTE *sig; + TSS_RESULT result; + + int i; + + if (getData(TCSD_PACKET_TYPE_UINT32, 0, &hContext, 0, &data->comm)) + return TCSERR(TSS_E_INTERNAL_ERROR); + + if ((result = ctx_verify_context(hContext))) + goto done; + + LogDebugFn("thread %ld context %x", THREAD_ID, hContext); + + if (getData(TCSD_PACKET_TYPE_UINT32, 1, &hKey, 0, &data->comm)) + return TCSERR(TSS_E_INTERNAL_ERROR); + if (getData(TCSD_PACKET_TYPE_UINT32, 2, &areaToSignSize, 0, &data->comm)) + return TCSERR(TSS_E_INTERNAL_ERROR); + + areaToSign = calloc(1, areaToSignSize); + if (areaToSign == NULL) { + LogError("malloc of %d bytes failed.", areaToSignSize); + return TCSERR(TSS_E_OUTOFMEMORY); + } + if (getData(TCSD_PACKET_TYPE_PBYTE, 3, areaToSign, areaToSignSize, &data->comm)) { + free(areaToSign); + return TCSERR(TSS_E_INTERNAL_ERROR); + } + result = getData(TCSD_PACKET_TYPE_AUTH, 4, &auth, 0, &data->comm); + if (result == TSS_TCP_RPC_BAD_PACKET_TYPE) + pAuth = NULL; + else if (result) { + free(areaToSign); + return result; + } else + pAuth = &auth; + + MUTEX_LOCK(tcsp_lock); + + result = TCSP_Sign_Internal(hContext, hKey, areaToSignSize, areaToSign, pAuth, &sigSize, + &sig); + + MUTEX_UNLOCK(tcsp_lock); + free(areaToSign); + + if (result == TSS_SUCCESS) { + i = 0; + initData(&data->comm, 3); + if (pAuth != NULL) { + if (setData(TCSD_PACKET_TYPE_AUTH, i++, &auth, 0, &data->comm)) { + free(sig); + return TCSERR(TSS_E_INTERNAL_ERROR); + } + } + if (setData(TCSD_PACKET_TYPE_UINT32, i++, &sigSize, 0, &data->comm)) { + free(sig); + return TCSERR(TSS_E_INTERNAL_ERROR); + } + if (setData(TCSD_PACKET_TYPE_PBYTE, i++, sig, sigSize, &data->comm)) { + free(sig); + return TCSERR(TSS_E_INTERNAL_ERROR); + } + free(sig); + } else +done: initData(&data->comm, 0); + + data->comm.hdr.u.result = result; + return TSS_SUCCESS; +} diff --git a/pool/shard000/C/0008453_tcp_client.c b/pool/shard000/C/0008453_tcp_client.c new file mode 100644 index 0000000000000000000000000000000000000000..e0dafd076d15d776bc53ec55f7dcd29c23282b4a --- /dev/null +++ b/pool/shard000/C/0008453_tcp_client.c @@ -0,0 +1,61 @@ + +#include +#include +#include +#include +#include + +#include +#include + + +int +main(int argc, char *argv[]) +{ + int sockfd; + struct sockaddr_in serv_addr; + int str_len, read_len, i; + char msg[128]; + + if (argc != 3) { + fprintf(stderr, "Usage: ./%s \n", argv[0]); + exit(EXIT_FAILURE); + } + + // same as: socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { + perror("socket() failed"); + exit(EXIT_FAILURE); + } + + memset(&serv_addr, 0, sizeof(serv_addr)); + serv_addr.sin_family = AF_INET; + serv_addr.sin_addr.s_addr = inet_addr(argv[1]); + serv_addr.sin_port = htons(atoi(argv[2])); + + if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) == -1) { + fprintf(stderr, "connect() failed: %s\n", strerror(errno)); + exit(EXIT_FAILURE); + } + + + i = 0; + while ((read_len = read(sockfd, &msg[i++], 1))) { + if (read_len == -1) { + perror("read() failed"); + close(sockfd); + exit(EXIT_FAILURE); + } + + str_len += read_len; + } + + msg[str_len] = '\0'; + printf("[recv %d bytes] %s\n", str_len, msg); + + close(sockfd); + + return 0; +} + + diff --git a/pool/shard000/C/0008478_gimpimage-pick-color.c b/pool/shard000/C/0008478_gimpimage-pick-color.c new file mode 100644 index 0000000000000000000000000000000000000000..d6601b0ab7ebb79b196807fb476b67ee2f7925d9 --- /dev/null +++ b/pool/shard000/C/0008478_gimpimage-pick-color.c @@ -0,0 +1,86 @@ +/* GIMP - The GNU Image Manipulation Program + * Copyright (C) 1995-2001 Spencer Kimball, Peter Mattis, and others + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#include "config.h" + +#include + +#include "core-types.h" + +#include "gimpdrawable.h" +#include "gimpimage.h" +#include "gimpimage-pick-color.h" +#include "gimppickable.h" + + +gboolean +gimp_image_pick_color (GimpImage *image, + GimpDrawable *drawable, + gint x, + gint y, + gboolean sample_merged, + gboolean sample_average, + gdouble average_radius, + GimpImageType *sample_type, + GimpRGB *color, + gint *color_index) +{ + GimpPickable *pickable; + + g_return_val_if_fail (GIMP_IS_IMAGE (image), FALSE); + g_return_val_if_fail (drawable == NULL || GIMP_IS_DRAWABLE (drawable), FALSE); + g_return_val_if_fail (drawable == NULL || + gimp_item_get_image (GIMP_ITEM (drawable)) == image, + FALSE); + + if (! sample_merged) + { + if (! drawable) + drawable = gimp_image_get_active_drawable (image); + + if (! drawable) + return FALSE; + } + + if (sample_merged) + { + pickable = GIMP_PICKABLE (image->projection); + } + else + { + gint off_x, off_y; + + gimp_item_offsets (GIMP_ITEM (drawable), &off_x, &off_y); + x -= off_x; + y -= off_y; + + pickable = GIMP_PICKABLE (drawable); + } + + /* Do *not* call gimp_pickable_flush() here because it's too expensive + * to call it unconditionally each time e.g. the cursor view is updated. + * Instead, call gimp_pickable_flush() in the callers if needed. + */ + + if (sample_type) + *sample_type = gimp_pickable_get_image_type (pickable); + + return gimp_pickable_pick_color (pickable, x, y, + sample_average, average_radius, + color, color_index); +} diff --git a/pool/shard000/C/0008496_display.c b/pool/shard000/C/0008496_display.c new file mode 100644 index 0000000000000000000000000000000000000000..15f9edab45e03905fd58e52083bbbe4960b3f217 --- /dev/null +++ b/pool/shard000/C/0008496_display.c @@ -0,0 +1,315 @@ +/* + * Copyright (C) 2009 Arnaud "arnau" Fontaine + * + * 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 + * along with this program. If not, see + * . + */ + +/** \file + * \brief Display management run on startup + */ + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "structs.h" +#include "display.h" +#include "atoms.h" +#include "event.h" +#include "window.h" +#include "util.h" + +/** Structure holding cookies for QueryVersion requests of + extensions */ +typedef struct { + /** XFixes QueryVersion request cookie */ + xcb_xfixes_query_version_cookie_t xfixes; + /** Damage QueryVersion request cookie */ + xcb_damage_query_version_cookie_t damage; + /** Composite QueryVersion request cookie */ + xcb_composite_query_version_cookie_t composite; +} init_extensions_cookies_t; + +/** NOTICE: All above variables are not thread-safe, but well, we + don't care as they are only used during initialisation */ + +/** Initialise the QueryVersion extensions cookies with a 0 sequence + number, this is not thread-safe but we don't care here as it is + only used during initialisation */ +static init_extensions_cookies_t _init_extensions_cookies = { { 0 }, { 0 }, { 0 } }; + +/** Cookie request used when acquiring ownership on _NET_WM_CM_Sn */ +static xcb_get_selection_owner_cookie_t _get_wm_cm_owner_cookie = { 0 }; + +/** Cookie when querying the windows tree starting from the root + window */ +static xcb_query_tree_cookie_t _query_tree_cookie = { 0 }; + +/** Check whether the needed X extensions are present on the + * server-side (all the data have been previously pre-fetched in the + * extension cache). Then send requests to check their version by + * sending QueryVersion requests which is compulsory because the + * client MUST negotiate the version of the extension before + * executing extension requests + */ +void +display_init_extensions(void) +{ + globalconf.extensions.composite = xcb_get_extension_data(globalconf.connection, + &xcb_composite_id); + + globalconf.extensions.xfixes = xcb_get_extension_data(globalconf.connection, + &xcb_xfixes_id); + + globalconf.extensions.damage = xcb_get_extension_data(globalconf.connection, + &xcb_damage_id); + + if(!globalconf.extensions.composite || + !globalconf.extensions.composite->present) + fatal("No Composite extension"); + + debug("Composite: major_opcode=%ju", + (uintmax_t) globalconf.extensions.composite->major_opcode); + + if(!globalconf.extensions.xfixes || + !globalconf.extensions.xfixes->present) + fatal("No XFixes extension"); + + debug("XFixes: major_opcode=%ju", + (uintmax_t) globalconf.extensions.xfixes->major_opcode); + + if(!globalconf.extensions.damage || + !globalconf.extensions.damage->present) + fatal("No Damage extension"); + + debug("Damage: major_opcode=%ju", + (uintmax_t) globalconf.extensions.damage->major_opcode); + + _init_extensions_cookies.composite = + xcb_composite_query_version_unchecked(globalconf.connection, + XCB_COMPOSITE_MAJOR_VERSION, + XCB_COMPOSITE_MINOR_VERSION); + + _init_extensions_cookies.damage = + xcb_damage_query_version_unchecked(globalconf.connection, + XCB_DAMAGE_MAJOR_VERSION, + XCB_DAMAGE_MINOR_VERSION); + + _init_extensions_cookies.xfixes = + xcb_xfixes_query_version_unchecked(globalconf.connection, + XCB_XFIXES_MAJOR_VERSION, + XCB_XFIXES_MINOR_VERSION); +} + +/** Get the replies of the QueryVersion requests previously sent and + * check if their version actually matched the versions needed + * + * \see display_init_extensions + */ +void +display_init_extensions_finalise(void) +{ + assert(_init_extensions_cookies.composite.sequence); + + xcb_composite_query_version_reply_t *composite_version_reply = + xcb_composite_query_version_reply(globalconf.connection, + _init_extensions_cookies.composite, + NULL); + + /* Need NameWindowPixmap support introduced in version >= 0.2 */ + if(!composite_version_reply || composite_version_reply->minor_version < 2) + { + free(composite_version_reply); + fatal("Need Composite extension 0.2 at least"); + } + + free(composite_version_reply); + + assert(_init_extensions_cookies.damage.sequence); + + xcb_damage_query_version_reply_t *damage_version_reply = + xcb_damage_query_version_reply(globalconf.connection, + _init_extensions_cookies.damage, + NULL); + + if(!damage_version_reply) + fatal("Can't initialise Damage extension"); + + free(damage_version_reply); + + assert(_init_extensions_cookies.xfixes.sequence); + + xcb_xfixes_query_version_reply_t *xfixes_version_reply = + xcb_xfixes_query_version_reply(globalconf.connection, + _init_extensions_cookies.xfixes, + NULL); + + /* Need Region objects support introduced in version >= 2.0 */ + if(!xfixes_version_reply || xfixes_version_reply->major_version < 2) + { + free(xfixes_version_reply); + fatal("Need XFixes extension 2.0 at least"); + } + + free(xfixes_version_reply); +} + +/** Handler for PropertyNotify event meaningful to set the timestamp + * (given in the PropertyNotify event field) when acquiring the + * ownership of _NET_WM_CM_Sn using SetOwner request (as specified in + * ICCCM and EWMH) + * + * \see display_register_cm + * \param event The X PropertyNotify event + */ +static int +display_event_set_owner_property(void *data __attribute__((unused)), + xcb_connection_t *c __attribute__((unused)), + xcb_property_notify_event_t *event) +{ + debug("Set _NET_WM_CM_Sn ownership"); + + /* Set ownership on _NET_WM_CM_Sn giving the Compositing Manager window */ + xcb_ewmh_set_wm_cm_owner(&globalconf.ewmh, globalconf.screen_nbr, + globalconf.cm_window, event->time, 0, 0); + + /* Send request to check whether the ownership succeeded */ + _get_wm_cm_owner_cookie = xcb_ewmh_get_wm_cm_owner_unchecked(&globalconf.ewmh, + globalconf.screen_nbr); + + return 0; +} + +/** Register Compositing Manager, e.g. set ownership on EMWH + * _NET_WM_CM_Sn atom used to politely stating that a Compositing + * Manager is currently running. Acquiring ownership is done in the + * following steps (ICCCM explains the principles of selection + * ownership): + * + * 0/ Check whether this selection is already owned by another + * program + * + * 1/ Create a Window whose identifier is set as the _NET_WM_CM_Sn + * value + * + * 2/ Change a Window property to generate a PropertyNotify event + * used as the timestamp to SetOwner request as multiple attempts + * may be sent at the same time + * + * 3/ Send SetOwner request + * + * 4/ Check whether the SetOwner request succeeds + */ +void +display_register_cm(void) +{ + globalconf.cm_window = xcb_generate_id(globalconf.connection); + + /* Create a dummy window meaningful to set the ownership on + _NET_WM_CM_Sn atom */ + const uint32_t create_win_val[] = { true, XCB_EVENT_MASK_PROPERTY_CHANGE }; + + xcb_create_window(globalconf.connection, XCB_COPY_FROM_PARENT, + globalconf.cm_window, globalconf.screen->root, 0, 0, 1, 1, 0, + XCB_COPY_FROM_PARENT, XCB_COPY_FROM_PARENT, + XCB_CW_OVERRIDE_REDIRECT | XCB_CW_EVENT_MASK, + create_win_val); + + xcb_event_set_property_notify_handler(&globalconf.evenths, + display_event_set_owner_property, + NULL); + + xcb_change_property(globalconf.connection, XCB_PROP_MODE_REPLACE, + globalconf.cm_window, globalconf.ewmh._NET_WM_NAME, + globalconf.ewmh.UTF8_STRING, 8, + sizeof(PACKAGE_NAME), PACKAGE_NAME); +} + +/** Finish acquiring ownership by checking whether the SetOwner + * request succeeded + * + * \see display_register_cm + * \return bool true if it succeeded, false otherwise + */ +bool +display_register_cm_finalise(void) +{ + assert(_get_wm_cm_owner_cookie.sequence); + + xcb_window_t wm_cm_owner_win; + + /* Check whether the ownership of WM_CM_Sn succeeded */ + return (xcb_ewmh_get_wm_cm_owner_reply(&globalconf.ewmh, _get_wm_cm_owner_cookie, + &wm_cm_owner_win, NULL) && + wm_cm_owner_win == globalconf.cm_window); +} + +/** Redirect all the windows to the off-screen buffer starting from + * the root window and change root window attributes to make the + * server reporting meaningful events + */ +void +display_init_redirect(void) +{ + /* Manage all children windows from the root window */ + _query_tree_cookie = xcb_query_tree_unchecked(globalconf.connection, + globalconf.screen->root); + + xcb_composite_redirect_subwindows(globalconf.connection, + globalconf.screen->root, + XCB_COMPOSITE_REDIRECT_MANUAL); + + /* Declare interest in meaningful events */ + const uint32_t select_input_val = + XCB_EVENT_MASK_KEY_PRESS | + XCB_EVENT_MASK_KEY_RELEASE | + XCB_EVENT_MASK_BUTTON_RELEASE | + XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY | + XCB_EVENT_MASK_STRUCTURE_NOTIFY | + XCB_EVENT_MASK_PROPERTY_CHANGE; + + xcb_change_window_attributes(globalconf.connection, globalconf.screen->root, + XCB_CW_EVENT_MASK, &select_input_val); +} + +/** Finish redirection by adding all the existing windows in the + * hierarchy + */ +void +display_init_redirect_finalise(void) +{ + assert(_query_tree_cookie.sequence); + + /* Get all the windows below the root window */ + xcb_query_tree_reply_t *query_tree_reply = + xcb_query_tree_reply(globalconf.connection, + _query_tree_cookie, + NULL); + + /* Add all these windows excluding the root window of course */ + const int nwindows = xcb_query_tree_children_length(query_tree_reply); + if(nwindows) + window_manage_existing(nwindows, + xcb_query_tree_children(query_tree_reply)); + + free(query_tree_reply); +} diff --git a/pool/shard000/C/0008502_gnutls_global.c b/pool/shard000/C/0008502_gnutls_global.c new file mode 100644 index 0000000000000000000000000000000000000000..30828a3ab8eb9fe6b386aaae26c561f08255a531 --- /dev/null +++ b/pool/shard000/C/0008502_gnutls_global.c @@ -0,0 +1,341 @@ +/* + * Copyright (C) 2001-2012 Free Software Foundation, Inc. + * + * Author: Nikos Mavrogiannopoulos + * + * This file is part of GnuTLS. + * + * The GnuTLS is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License + * as published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + * + */ + +#include +#include +#include +#include +#include +#include + +#include /* for _gnutls_ext_init */ +#include +#include +#include +#include + +#include "sockets.h" +#include "gettext.h" + +/* Minimum library versions we accept. */ +#define GNUTLS_MIN_LIBTASN1_VERSION "0.3.4" + +/* created by asn1c */ +extern const ASN1_ARRAY_TYPE gnutls_asn1_tab[]; +extern const ASN1_ARRAY_TYPE pkix_asn1_tab[]; +void *_gnutls_file_mutex; + +ASN1_TYPE _gnutls_pkix1_asn; +ASN1_TYPE _gnutls_gnutls_asn; + +gnutls_log_func _gnutls_log_func = NULL; +gnutls_audit_log_func _gnutls_audit_log_func = NULL; +int _gnutls_log_level = 0; /* default log level */ + +static void default_log_func(int level, const char* str) +{ + fprintf(stderr, "gnutls[%d]: %s\n", level, str); +} + +/** + * gnutls_global_set_log_function: + * @log_func: it's a log function + * + * This is the function where you set the logging function gnutls is + * going to use. This function only accepts a character array. + * Normally you may not use this function since it is only used for + * debugging purposes. + * + * @gnutls_log_func is of the form, + * void (*gnutls_log_func)( int level, const char*); + **/ +void gnutls_global_set_log_function(gnutls_log_func log_func) +{ + _gnutls_log_func = log_func; +} + +/** + * gnutls_global_set_audit_log_function: + * @log_func: it is the audit log function + * + * This is the function to set the audit logging function. This + * is a function to report important issues, such as possible + * attacks in the protocol. This is different from gnutls_global_set_log_function() + * because it will report also session-specific events. The session + * parameter will be null if there is no corresponding TLS session. + * + * @gnutls_audit_log_func is of the form, + * void (*gnutls_audit_log_func)( gnutls_session_t, const char*); + * + * Since: 3.0 + **/ +void gnutls_global_set_audit_log_function(gnutls_audit_log_func log_func) +{ + _gnutls_audit_log_func = log_func; +} + +/** + * gnutls_global_set_time_function: + * @time_func: it's the system time function, a gnutls_time_func() callback. + * + * This is the function where you can override the default system time + * function. The application provided function should behave the same + * as the standard function. + * + * Since: 2.12.0 + **/ +void gnutls_global_set_time_function(gnutls_time_func time_func) +{ + gnutls_time = time_func; +} + +/** + * gnutls_global_set_log_level: + * @level: it's an integer from 0 to 9. + * + * This is the function that allows you to set the log level. The + * level is an integer between 0 and 9. Higher values mean more + * verbosity. The default value is 0. Larger values should only be + * used with care, since they may reveal sensitive information. + * + * Use a log level over 10 to enable all debugging options. + **/ +void gnutls_global_set_log_level(int level) +{ + _gnutls_log_level = level; +} + +/** + * gnutls_global_set_mem_functions: + * @alloc_func: it's the default memory allocation function. Like malloc(). + * @secure_alloc_func: This is the memory allocation function that will be used for sensitive data. + * @is_secure_func: a function that returns 0 if the memory given is not secure. May be NULL. + * @realloc_func: A realloc function + * @free_func: The function that frees allocated data. Must accept a NULL pointer. + * + * This is the function where you set the memory allocation functions + * gnutls is going to use. By default the libc's allocation functions + * (malloc(), free()), are used by gnutls, to allocate both sensitive + * and not sensitive data. This function is provided to set the + * memory allocation functions to something other than the defaults + * + * This function must be called before gnutls_global_init() is called. + * This function is not thread safe. + **/ +void +gnutls_global_set_mem_functions(gnutls_alloc_function alloc_func, + gnutls_alloc_function secure_alloc_func, + gnutls_is_secure_function is_secure_func, + gnutls_realloc_function realloc_func, + gnutls_free_function free_func) +{ + gnutls_secure_malloc = secure_alloc_func; + gnutls_malloc = alloc_func; + gnutls_realloc = realloc_func; + gnutls_free = free_func; + + /* if using the libc's default malloc + * use libc's calloc as well. + */ + if (gnutls_malloc == malloc) { + gnutls_calloc = calloc; + } else { /* use the included ones */ + gnutls_calloc = _gnutls_calloc; + } + gnutls_strdup = _gnutls_strdup; + +} + +static int _gnutls_init = 0; + +/** + * gnutls_global_init: + * + * This function performs any required precalculations, detects + * the supported CPU capabilities and initializes the underlying + * cryptographic backend. In order to free any resources + * taken by this call you should gnutls_global_deinit() + * when gnutls usage is no longer needed. + * + * This function increments a global counter, so that + * gnutls_global_deinit() only releases resources when it has been + * called as many times as gnutls_global_init(). This is useful when + * GnuTLS is used by more than one library in an application. This + * function can be called many times, but will only do something the + * first time. + * + * Note! This function is not thread safe. If two threads call this + * function simultaneously, they can cause a race between checking + * the global counter and incrementing it, causing both threads to + * execute the library initialization code. That could lead to a + * memory leak or even a crash. To handle this, your application should + * invoke this function after aquiring a thread mutex. + * + * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, + * otherwise a negative error code is returned. + **/ +int gnutls_global_init(void) +{ + int result = 0; + int res, level; + const char* e; + + if (_gnutls_init++) + goto out; + + e = getenv("GNUTLS_DEBUG_LEVEL"); + if (e != NULL) { + level = atoi(e); + gnutls_global_set_log_level(level); + if (_gnutls_log_func == NULL) + gnutls_global_set_log_function(default_log_func); + _gnutls_debug_log("Enabled GnuTLS logging...\n"); + } + + if (gl_sockets_startup(SOCKETS_1_1)) + return gnutls_assert_val(GNUTLS_E_FILE_ERROR); + + bindtextdomain(PACKAGE, LOCALEDIR); + + res = gnutls_crypto_init(); + if (res != 0) { + gnutls_assert(); + return GNUTLS_E_CRYPTO_INIT_FAILED; + } + + _gnutls_register_accel_crypto(); + + /* initialize ASN.1 parser + * This should not deal with files in the final + * version. + */ + if (asn1_check_version(GNUTLS_MIN_LIBTASN1_VERSION) == NULL) { + gnutls_assert(); + _gnutls_debug_log + ("Checking for libtasn1 failed: %s < %s\n", + asn1_check_version(NULL), + GNUTLS_MIN_LIBTASN1_VERSION); + return GNUTLS_E_INCOMPATIBLE_LIBTASN1_LIBRARY; + } + + res = asn1_array2tree(pkix_asn1_tab, &_gnutls_pkix1_asn, NULL); + if (res != ASN1_SUCCESS) { + result = _gnutls_asn2err(res); + goto out; + } + + res = asn1_array2tree(gnutls_asn1_tab, &_gnutls_gnutls_asn, NULL); + if (res != ASN1_SUCCESS) { + result = _gnutls_asn2err(res); + goto out; + } + + /* Initialize the random generator */ + result = _gnutls_rnd_init(); + if (result < 0) { + gnutls_assert(); + goto out; + } + + /* Initialize the default TLS extensions */ + result = _gnutls_ext_init(); + if (result < 0) { + gnutls_assert(); + goto out; + } + + result = gnutls_mutex_init(&_gnutls_file_mutex); + if (result < 0) { + gnutls_assert(); + goto out; + } + + result = gnutls_system_global_init(); + if (result < 0) { + gnutls_assert(); + goto out; + } +#ifdef ENABLE_PKCS11 + gnutls_pkcs11_init(GNUTLS_PKCS11_FLAG_AUTO, NULL); +#endif + + _gnutls_cryptodev_init(); + + out: + return result; +} + +/** + * gnutls_global_deinit: + * + * This function deinitializes the global data, that were initialized + * using gnutls_global_init(). + * + * Note! This function is not thread safe. See the discussion for + * gnutls_global_init() for more information. + **/ +void gnutls_global_deinit(void) +{ + if (_gnutls_init == 1) { + gl_sockets_cleanup(); + gnutls_crypto_deinit(); + _gnutls_rnd_deinit(); + _gnutls_ext_deinit(); + asn1_delete_structure(&_gnutls_gnutls_asn); + asn1_delete_structure(&_gnutls_pkix1_asn); + _gnutls_crypto_deregister(); + _gnutls_cryptodev_deinit(); + gnutls_system_global_deinit(); +#ifdef ENABLE_PKCS11 + gnutls_pkcs11_deinit(); +#endif + gnutls_mutex_deinit(&_gnutls_file_mutex); + } + _gnutls_init--; +} + +/* These functions should be elsewere. Kept here for + * historical reasons. + */ + + +/** + * gnutls_check_version: + * @req_version: version string to compare with, or %NULL. + * + * Check GnuTLS Library version. + * + * See %GNUTLS_VERSION for a suitable @req_version string. + * + * Returns: Check that the version of the library is at + * minimum the one given as a string in @req_version and return the + * actual version string of the library; return %NULL if the + * condition is not met. If %NULL is passed to this function no + * check is done and only the version string is returned. + **/ +const char *gnutls_check_version(const char *req_version) +{ + if (!req_version || strverscmp(req_version, VERSION) <= 0) + return VERSION; + + return NULL; +} diff --git a/pool/shard000/C/0008506_avic.c b/pool/shard000/C/0008506_avic.c new file mode 100644 index 0000000000000000000000000000000000000000..322caa21bcb36f76f94f77e930161b1df8572379 --- /dev/null +++ b/pool/shard000/C/0008506_avic.c @@ -0,0 +1,222 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* + * Copyright 2004-2007 Freescale Semiconductor, Inc. All Rights Reserved. + * Copyright 2008 Juergen Beisert, kernel@pengutronix.de + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "common.h" +#include "hardware.h" +#include "irq-common.h" + +#define AVIC_INTCNTL 0x00 /* int control reg */ +#define AVIC_NIMASK 0x04 /* int mask reg */ +#define AVIC_INTENNUM 0x08 /* int enable number reg */ +#define AVIC_INTDISNUM 0x0C /* int disable number reg */ +#define AVIC_INTENABLEH 0x10 /* int enable reg high */ +#define AVIC_INTENABLEL 0x14 /* int enable reg low */ +#define AVIC_INTTYPEH 0x18 /* int type reg high */ +#define AVIC_INTTYPEL 0x1C /* int type reg low */ +#define AVIC_NIPRIORITY(x) (0x20 + 4 * (7 - (x))) /* int priority */ +#define AVIC_NIVECSR 0x40 /* norm int vector/status */ +#define AVIC_FIVECSR 0x44 /* fast int vector/status */ +#define AVIC_INTSRCH 0x48 /* int source reg high */ +#define AVIC_INTSRCL 0x4C /* int source reg low */ +#define AVIC_INTFRCH 0x50 /* int force reg high */ +#define AVIC_INTFRCL 0x54 /* int force reg low */ +#define AVIC_NIPNDH 0x58 /* norm int pending high */ +#define AVIC_NIPNDL 0x5C /* norm int pending low */ +#define AVIC_FIPNDH 0x60 /* fast int pending high */ +#define AVIC_FIPNDL 0x64 /* fast int pending low */ + +#define AVIC_NUM_IRQS 64 + +/* low power interrupt mask registers */ +#define MX25_CCM_LPIMR0 0x68 +#define MX25_CCM_LPIMR1 0x6C + +static void __iomem *avic_base; +static void __iomem *mx25_ccm_base; +static struct irq_domain *domain; + +#ifdef CONFIG_FIQ +static int avic_set_irq_fiq(unsigned int hwirq, unsigned int type) +{ + unsigned int irqt; + + if (hwirq >= AVIC_NUM_IRQS) + return -EINVAL; + + if (hwirq < AVIC_NUM_IRQS / 2) { + irqt = imx_readl(avic_base + AVIC_INTTYPEL) & ~(1 << hwirq); + imx_writel(irqt | (!!type << hwirq), avic_base + AVIC_INTTYPEL); + } else { + hwirq -= AVIC_NUM_IRQS / 2; + irqt = imx_readl(avic_base + AVIC_INTTYPEH) & ~(1 << hwirq); + imx_writel(irqt | (!!type << hwirq), avic_base + AVIC_INTTYPEH); + } + + return 0; +} +#endif /* CONFIG_FIQ */ + + +static struct mxc_extra_irq avic_extra_irq = { +#ifdef CONFIG_FIQ + .set_irq_fiq = avic_set_irq_fiq, +#endif +}; + +#ifdef CONFIG_PM +static u32 avic_saved_mask_reg[2]; + +static void avic_irq_suspend(struct irq_data *d) +{ + struct irq_chip_generic *gc = irq_data_get_irq_chip_data(d); + struct irq_chip_type *ct = gc->chip_types; + int idx = d->hwirq >> 5; + + avic_saved_mask_reg[idx] = imx_readl(avic_base + ct->regs.mask); + imx_writel(gc->wake_active, avic_base + ct->regs.mask); + + if (mx25_ccm_base) { + u8 offs = d->hwirq < AVIC_NUM_IRQS / 2 ? + MX25_CCM_LPIMR0 : MX25_CCM_LPIMR1; + /* + * The interrupts which are still enabled will be used as wakeup + * sources. Allow those interrupts in low-power mode. + * The LPIMR registers use 0 to allow an interrupt, the AVIC + * registers use 1. + */ + imx_writel(~gc->wake_active, mx25_ccm_base + offs); + } +} + +static void avic_irq_resume(struct irq_data *d) +{ + struct irq_chip_generic *gc = irq_data_get_irq_chip_data(d); + struct irq_chip_type *ct = gc->chip_types; + int idx = d->hwirq >> 5; + + imx_writel(avic_saved_mask_reg[idx], avic_base + ct->regs.mask); + + if (mx25_ccm_base) { + u8 offs = d->hwirq < AVIC_NUM_IRQS / 2 ? + MX25_CCM_LPIMR0 : MX25_CCM_LPIMR1; + + imx_writel(0xffffffff, mx25_ccm_base + offs); + } +} + +#else +#define avic_irq_suspend NULL +#define avic_irq_resume NULL +#endif + +static __init void avic_init_gc(int idx, unsigned int irq_start) +{ + struct irq_chip_generic *gc; + struct irq_chip_type *ct; + + gc = irq_alloc_generic_chip("mxc-avic", 1, irq_start, avic_base, + handle_level_irq); + gc->private = &avic_extra_irq; + gc->wake_enabled = IRQ_MSK(32); + + ct = gc->chip_types; + ct->chip.irq_mask = irq_gc_mask_clr_bit; + ct->chip.irq_unmask = irq_gc_mask_set_bit; + ct->chip.irq_ack = irq_gc_mask_clr_bit; + ct->chip.irq_set_wake = irq_gc_set_wake; + ct->chip.irq_suspend = avic_irq_suspend; + ct->chip.irq_resume = avic_irq_resume; + ct->regs.mask = !idx ? AVIC_INTENABLEL : AVIC_INTENABLEH; + ct->regs.ack = ct->regs.mask; + + irq_setup_generic_chip(gc, IRQ_MSK(32), 0, IRQ_NOREQUEST, 0); +} + +static void __exception_irq_entry avic_handle_irq(struct pt_regs *regs) +{ + u32 nivector; + + do { + nivector = imx_readl(avic_base + AVIC_NIVECSR) >> 16; + if (nivector == 0xffff) + break; + + handle_domain_irq(domain, nivector, regs); + } while (1); +} + +/* + * This function initializes the AVIC hardware and disables all the + * interrupts. It registers the interrupt enable and disable functions + * to the kernel for each interrupt source. + */ +void __init mxc_init_irq(void __iomem *irqbase) +{ + struct device_node *np; + int irq_base; + int i; + + avic_base = irqbase; + + np = of_find_compatible_node(NULL, NULL, "fsl,imx25-ccm"); + mx25_ccm_base = of_iomap(np, 0); + + if (mx25_ccm_base) { + /* + * By default, we mask all interrupts. We set the actual mask + * before we go into low-power mode. + */ + imx_writel(0xffffffff, mx25_ccm_base + MX25_CCM_LPIMR0); + imx_writel(0xffffffff, mx25_ccm_base + MX25_CCM_LPIMR1); + } + + /* put the AVIC into the reset value with + * all interrupts disabled + */ + imx_writel(0, avic_base + AVIC_INTCNTL); + imx_writel(0x1f, avic_base + AVIC_NIMASK); + + /* disable all interrupts */ + imx_writel(0, avic_base + AVIC_INTENABLEH); + imx_writel(0, avic_base + AVIC_INTENABLEL); + + /* all IRQ no FIQ */ + imx_writel(0, avic_base + AVIC_INTTYPEH); + imx_writel(0, avic_base + AVIC_INTTYPEL); + + irq_base = irq_alloc_descs(-1, 0, AVIC_NUM_IRQS, numa_node_id()); + WARN_ON(irq_base < 0); + + np = of_find_compatible_node(NULL, NULL, "fsl,avic"); + domain = irq_domain_add_legacy(np, AVIC_NUM_IRQS, irq_base, 0, + &irq_domain_simple_ops, NULL); + WARN_ON(!domain); + + for (i = 0; i < AVIC_NUM_IRQS / 32; i++, irq_base += 32) + avic_init_gc(i, irq_base); + + /* Set default priority value (0) for all IRQ's */ + for (i = 0; i < 8; i++) + imx_writel(0, avic_base + AVIC_NIPRIORITY(i)); + + set_handle_irq(avic_handle_irq); + +#ifdef CONFIG_FIQ + /* Initialize FIQ */ + init_FIQ(FIQ_START); +#endif + + printk(KERN_INFO "MXC IRQ initialized\n"); +} diff --git a/pool/shard000/C/0008520_abspath.c b/pool/shard000/C/0008520_abspath.c new file mode 100644 index 0000000000000000000000000000000000000000..057b2b8933c1be98bf270645f9b2957b1959f51a --- /dev/null +++ b/pool/shard000/C/0008520_abspath.c @@ -0,0 +1,97 @@ +/* Copyright (c) 2009-2014 Dovecot authors, see the included COPYING file */ + +#include "lib.h" +#include "str.h" +#include "abspath.h" + +#include +#include + +const char *t_abspath(const char *path) +{ + const char *dir; + + if (*path == '/') + return path; + + if (t_get_current_dir(&dir) < 0) + i_fatal("getcwd() failed: %m"); + return t_strconcat(dir, "/", path, NULL); +} + +const char *t_abspath_to(const char *path, const char *root) +{ + if (*path == '/') + return path; + + return t_strconcat(root, "/", path, NULL); +} + +int t_get_current_dir(const char **dir_r) +{ + /* @UNSAFE */ + char *dir; + size_t size = 128; + + dir = t_buffer_get(size); + while (getcwd(dir, size) == NULL) { + if (errno != ERANGE) + return -1; + size = nearest_power(size+1); + dir = t_buffer_get(size); + } + t_buffer_alloc(strlen(dir) + 1); + *dir_r = dir; + return 0; +} + +int t_readlink(const char *path, const char **dest_r) +{ + /* @UNSAFE */ + ssize_t ret; + char *dest; + size_t size = 128; + + dest = t_buffer_get(size); + while ((ret = readlink(path, dest, size)) >= (ssize_t)size) { + size = nearest_power(size+1); + dest = t_buffer_get(size); + } + if (ret < 0) + return -1; + + dest[ret] = '\0'; + t_buffer_alloc(ret + 1); + *dest_r = dest; + return 0; +} + +bool t_binary_abspath(const char **binpath) +{ + const char *path_env, *const *paths; + string_t *path; + + if (**binpath == '/') { + /* already have absolute path */ + return TRUE; + } else if (strchr(*binpath, '/') != NULL) { + /* relative to current directory */ + *binpath = t_abspath(*binpath); + return TRUE; + } else if ((path_env = getenv("PATH")) != NULL) { + /* we have to find our executable from path */ + path = t_str_new(256); + paths = t_strsplit(path_env, ":"); + for (; *paths != NULL; paths++) { + str_append(path, *paths); + str_append_c(path, '/'); + str_append(path, *binpath); + if (access(str_c(path), X_OK) == 0) { + *binpath = str_c(path); + return TRUE; + } + str_truncate(path, 0); + } + } + return FALSE; +} diff --git a/pool/shard000/C/0008521_msm7kv2-dai.c b/pool/shard000/C/0008521_msm7kv2-dai.c new file mode 100644 index 0000000000000000000000000000000000000000..dbb4973f15f3ce1f07c63ac1e0ff3685af1b009c --- /dev/null +++ b/pool/shard000/C/0008521_msm7kv2-dai.c @@ -0,0 +1,121 @@ + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "msm7kv2-pcm.h" + +struct snd_soc_dai msm_dais[] = { +{ + .name = "CODEC_DAI", + .playback = { + .stream_name = "Playback", + .channels_min = USE_CHANNELS_MIN, + .channels_max = USE_CHANNELS_MAX, + .rates = USE_RATE, + .rate_min = USE_RATE_MIN, + .rate_max = USE_RATE_MAX, + .formats = USE_FORMATS, + }, + .capture = { + .stream_name = "Capture", + .channels_min = USE_CHANNELS_MIN, + .channels_max = USE_CHANNELS_MAX, + .rate_min = USE_RATE_MIN, + .rates = USE_RATE, + .formats = USE_FORMATS, + }, +}, +{ + .name = "CPU_DAI", + .id = 0, + .playback = { + .channels_min = USE_CHANNELS_MIN, + .channels_max = USE_CHANNELS_MAX, + .rates = USE_RATE, + .rate_min = USE_RATE_MIN, + .rate_max = USE_RATE_MAX, + .formats = USE_FORMATS, + }, + .capture = { + .channels_min = USE_CHANNELS_MIN, + .channels_max = USE_CHANNELS_MAX, + .rate_min = USE_RATE_MIN, + .rates = USE_RATE, + .formats = USE_FORMATS, + }, +}, +}; +EXPORT_SYMBOL_GPL(msm_dais); + +int msm_pcm_probe(struct platform_device *devptr) +{ + struct snd_soc_codec *codec; + int ret; + + struct snd_soc_device *socdev = platform_get_drvdata(devptr); + + printk(KERN_ERR "msm_soc: create pcms\n"); + codec = kzalloc(sizeof(struct snd_soc_codec), GFP_KERNEL); + if (codec == NULL) + return -ENOMEM; + + codec->name = "MSM-CARD"; + codec->owner = THIS_MODULE; + socdev->card->codec = codec; + mutex_init(&codec->mutex); + + INIT_LIST_HEAD(&codec->dapm_widgets); + INIT_LIST_HEAD(&codec->dapm_paths); + + + ret = snd_soc_new_pcms(socdev, SNDRV_DEFAULT_IDX1, SNDRV_DEFAULT_STR1); + if (ret < 0) { + printk(KERN_ERR "msm_soc: failed to create pcms\n"); + goto __nopcm; + } + + ret = snd_soc_init_card(socdev); + if (ret < 0) { + printk(KERN_ERR "msm_soc: failed to register card\n"); + goto __nodev; + } + + return 0; + +__nodev: + snd_soc_free_pcms(socdev); +__nopcm: + kfree(codec); + return ret; +} + +struct snd_soc_codec_device soc_codec_dev_msm = { + .probe = msm_pcm_probe, +}; +EXPORT_SYMBOL_GPL(soc_codec_dev_msm); + + +static int __init msm_dai_init(void) +{ + return snd_soc_register_dais(msm_dais, ARRAY_SIZE(msm_dais)); +} + +static void __exit msm_dai_exit(void) +{ + snd_soc_unregister_dais(msm_dais, ARRAY_SIZE(msm_dais)); +} + +module_init(msm_dai_init); +module_exit(msm_dai_exit); + + +MODULE_DESCRIPTION("MSM Codec/Cpu Dai driver"); +MODULE_LICENSE("GPL v2"); diff --git a/pool/shard000/C/0008538_10903.c b/pool/shard000/C/0008538_10903.c new file mode 100644 index 0000000000000000000000000000000000000000..18bca997ac207ad5267804170b3ea59377202f3b --- /dev/null +++ b/pool/shard000/C/0008538_10903.c @@ -0,0 +1,82 @@ +// [ACM] #10903 - Rock-Paper-Scissors Tournament +// Problem Status CPU Date&Time(UTC) ID Best CPU +// 10903 Accepted 1.203 2006-11-07 11:24:36 5114450 0.148 + +#include + +int main(void) +{ + int n, k, v , u, i = 0, pw[100], pl[100]; + float w; + char vt[9], ut[9]; + char type[3] = {'s', 'p', 'r'}; + + while(scanf("%d %d" , &n, &k) == 2) + { + if(i != 0) + printf("\n"); + for(i = 0; i < 100; i ++) + { + pw[i] = 0; + pl[i] = 0; + } + for(i = 0; i < k * n * (n - 1) / 2 ;i ++) + { + scanf("%d %s %d %s" , &v, vt, &u, ut); + if(vt[0] == type[0] && ut[0] == type[0]); + else if(vt[0] == type[1] && ut[0] == type[1]); + else if(vt[0] == type[2] && ut[0] == type[2]); + else if(vt[0] == type[0]) + { + if(ut[0] == type[1]) + { + pw[v - 1] ++; + pl[u - 1] ++; + } + else + { + pw[u - 1] ++; + pl[v - 1] ++; + } + } + else if(vt[0] == type[1]) + { + if(ut[0] == type[0]) + { + pw[u - 1] ++; + pl[v - 1] ++; + } + else + { + pw[v - 1] ++; + pl[u - 1] ++; + } + } + else + { + if(ut[0] == type[0]) + { + pw[v - 1] ++; + pl[u - 1] ++; + } + else + { + pw[u - 1] ++; + pl[v - 1] ++; + } + } + } + for(i = 0; i < n; i ++) + { + w = pw[i] + pl[i]; + if(w == 0) + printf("-\n"); + else + { + w = pw[i] / w; + printf("%.3f\n" , w); + } + } + } + return 0; +} diff --git a/pool/shard000/C/0008544_windir.c b/pool/shard000/C/0008544_windir.c new file mode 100644 index 0000000000000000000000000000000000000000..23ce8c221e411c9a6fe0884837c353b2cb82f168 --- /dev/null +++ b/pool/shard000/C/0008544_windir.c @@ -0,0 +1,80 @@ +/***********************************************************************/ +/* */ +/* Objective Caml */ +/* */ +/* Pascal Cuoq and Xavier Leroy, projet Cristal, INRIA Rocquencourt */ +/* */ +/* Copyright 1996 Institut National de Recherche en Informatique et */ +/* en Automatique. All rights reserved. This file is distributed */ +/* under the terms of the GNU Library General Public License, with */ +/* the special exception on linking described in file ../../LICENSE. */ +/* */ +/***********************************************************************/ + +/* $Id: windir.c 5029 2002-07-23 14:12:03Z doligez $ */ + +#include +#include +#include +#include +#include +#include "unixsupport.h" + +CAMLprim value win_findfirst(name) + value name; +{ + HANDLE h; + value v; + WIN32_FIND_DATA fileinfo; + value valname = Val_unit; + value valh = Val_unit; + + Begin_roots2 (valname,valh); + h = FindFirstFile(String_val(name),&fileinfo); + if (h == INVALID_HANDLE_VALUE) { + DWORD err = GetLastError(); + if (err == ERROR_NO_MORE_FILES) + raise_end_of_file(); + else { + win32_maperr(err); + uerror("opendir", Nothing); + } + } + valname = copy_string(fileinfo.cFileName); + valh = win_alloc_handle(h); + v = alloc_small(2, 0); + Field(v,0) = valname; + Field(v,1) = valh; + End_roots(); + return v; +} + +CAMLprim value win_findnext(valh) + value valh; +{ + WIN32_FIND_DATA fileinfo; + BOOL retcode; + + retcode = FindNextFile(Handle_val(valh), &fileinfo); + if (!retcode) { + DWORD err = GetLastError(); + if (err == ERROR_NO_MORE_FILES) + raise_end_of_file(); + else { + win32_maperr(err); + uerror("readdir", Nothing); + } + } + return copy_string(fileinfo.cFileName); +} + +CAMLprim value win_findclose(valh) + value valh; +{ + if (! FindClose(Handle_val(valh))) { + win32_maperr(GetLastError()); + uerror("closedir", Nothing); + } + return Val_unit; +} + diff --git a/pool/shard000/C/0008546_psychic.c b/pool/shard000/C/0008546_psychic.c new file mode 100644 index 0000000000000000000000000000000000000000..a12215bb0dccd9a0f44705accec0c02b1405981f --- /dev/null +++ b/pool/shard000/C/0008546_psychic.c @@ -0,0 +1,182 @@ + + +#include "internal.h" + +#include "account.h" +#include "blist.h" +#include "conversation.h" +#include "debug.h" +#include "signals.h" +#include "status.h" +#include "version.h" +#include "privacy.h" + +#include "plugin.h" +#include "pluginpref.h" +#include "prefs.h" + + +#define PLUGIN_ID "core-psychic" +#define PLUGIN_NAME N_("Psychic Mode") +#define PLUGIN_SUMMARY N_("Psychic mode for incoming conversation") +#define PLUGIN_DESC N_("Causes conversation windows to appear as other" \ + " users begin to message you. This works for" \ + " AIM, ICQ, XMPP, Sametime, and Yahoo!") +#define PLUGIN_AUTHOR "Christopher O'Brien " + + +#define PREFS_BASE "/plugins/core/psychic" +#define PREF_BUDDIES PREFS_BASE "/buddies_only" +#define PREF_NOTICE PREFS_BASE "/show_notice" +#define PREF_STATUS PREFS_BASE "/activate_online" +#define PREF_RAISE PREFS_BASE "/raise_conv" + + +static void +buddy_typing_cb(PurpleAccount *acct, const char *name, void *data) { + PurpleConversation *gconv; + + if(purple_prefs_get_bool(PREF_STATUS) && + ! purple_status_is_available(purple_account_get_active_status(acct))) { + purple_debug_info("psychic", "not available, doing nothing\n"); + return; + } + + if(purple_prefs_get_bool(PREF_BUDDIES) && + ! purple_find_buddy(acct, name)) { + purple_debug_info("psychic", "not in blist, doing nothing\n"); + return; + } + + if(FALSE == purple_privacy_check(acct, name)) { + purple_debug_info("psychic", "user %s is blocked\n", name); + return; + } + + gconv = purple_find_conversation_with_account(PURPLE_CONV_TYPE_IM, name, acct); + if(! gconv) { + purple_debug_info("psychic", "no previous conversation exists\n"); + gconv = purple_conversation_new(PURPLE_CONV_TYPE_IM, acct, name); + + if(purple_prefs_get_bool(PREF_RAISE)) { + purple_conversation_present(gconv); + } + + if(purple_prefs_get_bool(PREF_NOTICE)) { + + /* This is a quote from Star Wars. You should probably not + translate it literally. If you can't find a fitting cultural + reference in your language, consider translating something + like this instead: "You feel a new message coming." */ + purple_conversation_write(gconv, NULL, + _("You feel a disturbance in the force..."), + PURPLE_MESSAGE_SYSTEM | PURPLE_MESSAGE_NO_LOG | PURPLE_MESSAGE_ACTIVE_ONLY, + time(NULL)); + } + + purple_conv_im_set_typing_state(PURPLE_CONV_IM(gconv), PURPLE_TYPING); + } +} + + +static PurplePluginPrefFrame * +get_plugin_pref_frame(PurplePlugin *plugin) { + + PurplePluginPrefFrame *frame; + PurplePluginPref *pref; + + frame = purple_plugin_pref_frame_new(); + + pref = purple_plugin_pref_new_with_name(PREF_BUDDIES); + purple_plugin_pref_set_label(pref, _("Only enable for users on" + " the buddy list")); + purple_plugin_pref_frame_add(frame, pref); + + pref = purple_plugin_pref_new_with_name(PREF_STATUS); + purple_plugin_pref_set_label(pref, _("Disable when away")); + purple_plugin_pref_frame_add(frame, pref); + + pref = purple_plugin_pref_new_with_name(PREF_NOTICE); + purple_plugin_pref_set_label(pref, _("Display notification message in" + " conversations")); + purple_plugin_pref_frame_add(frame, pref); + + pref = purple_plugin_pref_new_with_name(PREF_RAISE); + purple_plugin_pref_set_label(pref, _("Raise psychic conversations")); + purple_plugin_pref_frame_add(frame, pref); + + return frame; +} + + +static gboolean +plugin_load(PurplePlugin *plugin) { + + void *convs_handle; + convs_handle = purple_conversations_get_handle(); + + purple_signal_connect(convs_handle, "buddy-typing", plugin, + PURPLE_CALLBACK(buddy_typing_cb), NULL); + + return TRUE; +} + + +static PurplePluginUiInfo prefs_info = { + get_plugin_pref_frame, + 0, /* page_num (Reserved) */ + NULL, /* frame (Reserved) */ + + /* padding */ + NULL, + NULL, + NULL, + NULL +}; + + +static PurplePluginInfo info = { + PURPLE_PLUGIN_MAGIC, + PURPLE_MAJOR_VERSION, + PURPLE_MINOR_VERSION, + PURPLE_PLUGIN_STANDARD, /**< type */ + NULL, /**< ui_requirement */ + 0, /**< flags */ + NULL, /**< dependencies */ + PURPLE_PRIORITY_DEFAULT, /**< priority */ + + PLUGIN_ID, /**< id */ + PLUGIN_NAME, /**< name */ + DISPLAY_VERSION, /**< version */ + PLUGIN_SUMMARY, /**< summary */ + PLUGIN_DESC, /**< description */ + PLUGIN_AUTHOR, /**< author */ + PURPLE_WEBSITE, /**< homepage */ + + plugin_load, /**< load */ + NULL, /**< unload */ + NULL, /**< destroy */ + + NULL, /**< ui_info */ + NULL, /**< extra_info */ + &prefs_info, /**< prefs_info */ + NULL, /**< actions */ + + /* padding */ + NULL, + NULL, + NULL, + NULL +}; + + +static void +init_plugin(PurplePlugin *plugin) { + purple_prefs_add_none(PREFS_BASE); + purple_prefs_add_bool(PREF_BUDDIES, FALSE); + purple_prefs_add_bool(PREF_NOTICE, TRUE); + purple_prefs_add_bool(PREF_STATUS, TRUE); +} + + +PURPLE_INIT_PLUGIN(psychic, init_plugin, info) diff --git a/pool/shard000/C/0008549_wolfevent.c b/pool/shard000/C/0008549_wolfevent.c new file mode 100644 index 0000000000000000000000000000000000000000..20848cddcdf56e3ccc47287b88940a67d73b993d --- /dev/null +++ b/pool/shard000/C/0008549_wolfevent.c @@ -0,0 +1,283 @@ +/* wolfevent.c + * + * Copyright (C) 2006-2020 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +#ifdef HAVE_CONFIG_H + #include +#endif + +#include + + +#ifdef HAVE_WOLF_EVENT + +#include +#include +#include + +#include + + +int wolfEvent_Init(WOLF_EVENT* event, WOLF_EVENT_TYPE type, void* context) +{ + if (event == NULL) { + return BAD_FUNC_ARG; + } + + if (event->state == WOLF_EVENT_STATE_PENDING) { + WOLFSSL_MSG("Event already pending!"); + return BAD_COND_E; + } + + XMEMSET(event, 0, sizeof(WOLF_EVENT)); + event->type = type; + event->context = context; + + return 0; +} + +int wolfEvent_Poll(WOLF_EVENT* event, WOLF_EVENT_FLAG flags) +{ + int ret = BAD_COND_E; + + /* Check hardware */ +#ifdef WOLFSSL_ASYNC_CRYPT + if (event->type >= WOLF_EVENT_TYPE_ASYNC_FIRST && + event->type <= WOLF_EVENT_TYPE_ASYNC_LAST) + { + ret = wolfAsync_EventPoll(event, flags); + } +#endif /* WOLFSSL_ASYNC_CRYPT */ + + return ret; +} + +int wolfEventQueue_Init(WOLF_EVENT_QUEUE* queue) +{ + int ret = 0; + + if (queue == NULL) { + return BAD_FUNC_ARG; + } + + XMEMSET(queue, 0, sizeof(WOLF_EVENT_QUEUE)); +#ifndef SINGLE_THREADED + ret = wc_InitMutex(&queue->lock); +#endif + return ret; +} + + +int wolfEventQueue_Push(WOLF_EVENT_QUEUE* queue, WOLF_EVENT* event) +{ + int ret; + + if (queue == NULL || event == NULL) { + return BAD_FUNC_ARG; + } + +#ifndef SINGLE_THREADED + if ((ret = wc_LockMutex(&queue->lock)) != 0) { + return ret; + } +#endif + + ret = wolfEventQueue_Add(queue, event); + +#ifndef SINGLE_THREADED + wc_UnLockMutex(&queue->lock); +#endif + + return ret; +} + +int wolfEventQueue_Pop(WOLF_EVENT_QUEUE* queue, WOLF_EVENT** event) +{ + int ret = 0; + + if (queue == NULL || event == NULL) { + return BAD_FUNC_ARG; + } + +#ifndef SINGLE_THREADED + /* In single threaded mode "event_queue.lock" doesn't exist */ + if ((ret = wc_LockMutex(&queue->lock)) != 0) { + return ret; + } +#endif + + /* Pop first item off queue */ + *event = queue->head; + ret = wolfEventQueue_Remove(queue, *event); + +#ifndef SINGLE_THREADED + wc_UnLockMutex(&queue->lock); +#endif + + return ret; +} + +/* assumes queue is locked by caller */ +int wolfEventQueue_Add(WOLF_EVENT_QUEUE* queue, WOLF_EVENT* event) +{ + if (queue == NULL || event == NULL) { + return BAD_FUNC_ARG; + } + + event->next = NULL; /* added to end */ + event->prev = NULL; + if (queue->tail == NULL) { + queue->head = event; + } + else { + queue->tail->next = event; + event->prev = queue->tail; + } + queue->tail = event; /* add to the end either way */ + queue->count++; + + return 0; +} + +/* assumes queue is locked by caller */ +int wolfEventQueue_Remove(WOLF_EVENT_QUEUE* queue, WOLF_EVENT* event) +{ + int ret = 0; + + if (queue == NULL || event == NULL) { + return BAD_FUNC_ARG; + } + + if (event == queue->head && event == queue->tail) { + queue->head = NULL; + queue->tail = NULL; + } + else if (event == queue->head) { + queue->head = event->next; + queue->head->prev = NULL; + } + else if (event == queue->tail) { + queue->tail = event->prev; + queue->tail->next = NULL; + } + else { + WOLF_EVENT* next = event->next; + WOLF_EVENT* prev = event->prev; + next->prev = prev; + prev->next = next; + } + queue->count--; + + return ret; +} + +int wolfEventQueue_Poll(WOLF_EVENT_QUEUE* queue, void* context_filter, + WOLF_EVENT** events, int maxEvents, WOLF_EVENT_FLAG flags, int* eventCount) +{ + WOLF_EVENT* event; + int ret = 0, count = 0; + + if (queue == NULL) { + return BAD_FUNC_ARG; + } + +#ifndef SINGLE_THREADED + /* In single threaded mode "event_queue.lock" doesn't exist */ + if ((ret = wc_LockMutex(&queue->lock)) != 0) { + return ret; + } +#endif + + /* itterate event queue */ + for (event = queue->head; event != NULL; event = event->next) + { + /* optional filter based on context */ + if (context_filter == NULL || event->context == context_filter) { + + /* poll event */ + ret = wolfEvent_Poll(event, flags); + if (ret < 0) break; /* exit for */ + + /* If event is done then process */ + if (event->state == WOLF_EVENT_STATE_DONE) { + /* remove from queue */ + ret = wolfEventQueue_Remove(queue, event); + if (ret < 0) break; /* exit for */ + + /* return pointer in 'events' arg */ + if (events) { + events[count] = event; /* return pointer */ + } + count++; + + /* check to make sure our event list isn't full */ + if (events && count >= maxEvents) { + break; /* exit for */ + } + } + } + } + +#ifndef SINGLE_THREADED + wc_UnLockMutex(&queue->lock); +#endif + + /* return number of properly populated events */ + if (eventCount) { + *eventCount = count; + } + + return ret; +} + +int wolfEventQueue_Count(WOLF_EVENT_QUEUE* queue) +{ + int ret; + + if (queue == NULL) { + return BAD_FUNC_ARG; + } + +#ifndef SINGLE_THREADED + /* In single threaded mode "event_queue.lock" doesn't exist */ + if ((ret = wc_LockMutex(&queue->lock)) != 0) { + return ret; + } +#endif + + ret = queue->count; + +#ifndef SINGLE_THREADED + wc_UnLockMutex(&queue->lock); +#endif + + return ret; +} + +void wolfEventQueue_Free(WOLF_EVENT_QUEUE* queue) +{ + if (queue) { + #ifndef SINGLE_THREADED + wc_FreeMutex(&queue->lock); + #endif + } +} + +#endif /* HAVE_WOLF_EVENT */ diff --git a/pool/shard000/C/0008555_pkcs11-list.c b/pool/shard000/C/0008555_pkcs11-list.c new file mode 100644 index 0000000000000000000000000000000000000000..4ef6a7a62dcbdbd00191ed911ee4dba30633f265 --- /dev/null +++ b/pool/shard000/C/0008555_pkcs11-list.c @@ -0,0 +1,264 @@ +/* + * Copyright (C) 2009, 2015 Internet Systems Consortium, Inc. ("ISC") + * + * 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 ISC AND NETWORK ASSOCIATES DISCLAIMS + * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC 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. + */ + +/* + * Portions copyright (c) 2008 Nominet UK. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/* $Id: pkcs11-list.c,v 1.7 2009/10/26 23:36:53 each Exp $ */ + +/* pkcs11-list [-P] [-m module] [-s slot] [-i $id | -l $label] [-p $pin] */ + +/*! \file */ + +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include + +#if !(defined(HAVE_GETPASSPHRASE) || (defined (__SVR4) && defined (__sun))) +#define getpassphrase(x) getpass(x) +#endif + +int +main(int argc, char *argv[]) { + isc_result_t result; + CK_RV rv; + CK_SLOT_ID slot = 0; + CK_SESSION_HANDLE hSession; + CK_BYTE attr_id[2]; + CK_OBJECT_HANDLE akey[50]; + pk11_context_t pctx; + char *lib_name = NULL; + char *label = NULL; + char *pin = NULL; + isc_boolean_t error = ISC_FALSE, logon = ISC_TRUE, all = ISC_FALSE; + unsigned int i = 0, id = 0; + int c, errflg = 0; + CK_ULONG ulObjectCount; + CK_ATTRIBUTE search_template[] = { + {CKA_ID, &attr_id, sizeof(attr_id)} + }; + + while ((c = isc_commandline_parse(argc, argv, ":m:s:i:l:p:P")) != -1) { + switch (c) { + case 'P': + logon = ISC_FALSE; + break; + case 'm': + lib_name = isc_commandline_argument; + break; + case 's': + slot = atoi(isc_commandline_argument); + break; + case 'i': + id = atoi(isc_commandline_argument); + id &= 0xffff; + break; + case 'l': + label = isc_commandline_argument; + break; + case 'p': + pin = isc_commandline_argument; + break; + case ':': + fprintf(stderr, "Option -%c requires an operand\n", + isc_commandline_option); + errflg++; + break; + case '?': + default: + fprintf(stderr, "Unrecognised option: -%c\n", + isc_commandline_option); + errflg++; + } + } + + if (errflg) { + fprintf(stderr, "Usage:\n"); + fprintf(stderr, "\tpkcs11-list [-P] [-m module] [-s slot] " + "[-i id | -l label] [-p pin]\n"); + exit(1); + } + + if (!id && (label == NULL)) + all = ISC_TRUE; + + if (slot) + printf("slot %lu\n", slot); + + if (id) { + printf("id %i\n", id); + attr_id[0] = (id >> 8) & 0xff; + attr_id[1] = id & 0xff; + } else if (label != NULL) { + printf("label %s\n", label); + search_template[0].type = CKA_LABEL; + search_template[0].pValue = label; + search_template[0].ulValueLen = strlen(label); + } + + pk11_result_register(); + + /* Initialize the CRYPTOKI library */ + if (lib_name != NULL) + pk11_set_lib_name(lib_name); + + if (logon && pin == NULL) + pin = getpassphrase("Enter Pin: "); + + result = pk11_get_session(&pctx, OP_ANY, ISC_FALSE, ISC_FALSE, + logon, pin, slot); + if (result == PK11_R_NORANDOMSERVICE || + result == PK11_R_NODIGESTSERVICE || + result == PK11_R_NOAESSERVICE) { + fprintf(stderr, "Warning: %s\n", isc_result_totext(result)); + fprintf(stderr, "This HSM will not work with BIND 9 " + "using native PKCS#11.\n"); + } else if (result != ISC_R_SUCCESS) { + fprintf(stderr, "Unrecoverable error initializing " + "PKCS#11: %s\n", isc_result_totext(result)); + fprintf(stderr, "Unrecoverable error initializing " + "PKCS#11: %s\n", isc_result_totext(result)); + exit(1); + } + + if (pin != NULL) + memset(pin, 0, strlen(pin)); + + hSession = pctx.session; + + rv = pkcs_C_FindObjectsInit(hSession, search_template, all ? 0 : 1); + if (rv != CKR_OK) { + fprintf(stderr, "C_FindObjectsInit: Error = 0x%.8lX\n", rv); + error = 1; + goto exit_session; + } + + ulObjectCount = 1; + while (ulObjectCount) { + rv = pkcs_C_FindObjects(hSession, akey, 50, &ulObjectCount); + if (rv != CKR_OK) { + fprintf(stderr, + "C_FindObjects: Error = 0x%.8lX\n", + rv); + error = 1; + goto exit_search; + } + for (i = 0; i < ulObjectCount; i++) { + unsigned int j, len; + + CK_OBJECT_CLASS oclass = 0; + CK_BYTE labelbuf[64 + 1]; + CK_BYTE idbuf[64]; + CK_ATTRIBUTE template[] = { + {CKA_CLASS, &oclass, sizeof(oclass)}, + {CKA_LABEL, labelbuf, sizeof(labelbuf) - 1}, + {CKA_ID, idbuf, sizeof(idbuf)} + }; + + memset(labelbuf, 0, sizeof(labelbuf)); + memset(idbuf, 0, sizeof(idbuf)); + + rv = pkcs_C_GetAttributeValue(hSession, akey[i], + template, 3); + if (rv != CKR_OK) { + fprintf(stderr, + "C_GetAttributeValue[%u]: " + "rv = 0x%.8lX\n", + i, rv); + if (rv == CKR_BUFFER_TOO_SMALL) + fprintf(stderr, + "%u too small: %lu %lu %lu\n", + i, + template[0].ulValueLen, + template[1].ulValueLen, + template[2].ulValueLen); + error = 1; + continue; + } + + len = template[2].ulValueLen; + printf("object[%u]: handle %lu class %lu " + "label[%lu] '%s' id[%lu] ", + i, akey[i], oclass, + template[1].ulValueLen, + labelbuf, + template[2].ulValueLen); + if (len == 2) { + id = (idbuf[0] << 8) & 0xff00; + id |= idbuf[1] & 0xff; + printf("%u\n", id); + } else { + if (len > 8) + len = 8; + if (len > 0) + printf("0x"); + for (j = 0; j < len; j++) + printf("%02x", idbuf[j]); + if (template[2].ulValueLen > len) + printf("...\n"); + else + printf("\n"); + } + } + } + + exit_search: + rv = pkcs_C_FindObjectsFinal(hSession); + if (rv != CKR_OK) { + fprintf(stderr, "C_FindObjectsFinal: Error = 0x%.8lX\n", rv); + error = 1; + } + + exit_session: + pk11_return_session(&pctx); + (void) pk11_finalize(); + + exit(error); +} diff --git a/pool/shard000/C/0008576_aigMffc.c b/pool/shard000/C/0008576_aigMffc.c new file mode 100644 index 0000000000000000000000000000000000000000..daeed2810d7ee41d70ef798d3064fdab5358924b --- /dev/null +++ b/pool/shard000/C/0008576_aigMffc.c @@ -0,0 +1,297 @@ +/**CFile**************************************************************** + + FileName [aigMffc.c] + + SystemName [ABC: Logic synthesis and verification system.] + + PackageName [AIG package.] + + Synopsis [Computation of MFFCs.] + + Author [Alan Mishchenko] + + Affiliation [UC Berkeley] + + Date [Ver. 1.0. Started - April 28, 2007.] + + Revision [$Id: aigMffc.c,v 1.00 2007/04/28 00:00:00 alanmi Exp $] + +***********************************************************************/ + +#include "aig.h" + +//////////////////////////////////////////////////////////////////////// +/// DECLARATIONS /// +//////////////////////////////////////////////////////////////////////// + +//////////////////////////////////////////////////////////////////////// +/// FUNCTION DEFINITIONS /// +//////////////////////////////////////////////////////////////////////// + +/**Function************************************************************* + + Synopsis [Dereferences the node's MFFC.] + + Description [] + + SideEffects [] + + SeeAlso [] + +***********************************************************************/ +int Aig_NodeDeref_rec( Aig_Obj_t * pNode, unsigned LevelMin ) +{ + Aig_Obj_t * pFanin; + int Counter = 0; + if ( Aig_ObjIsPi(pNode) ) + return 0; + // consider the first fanin + pFanin = Aig_ObjFanin0(pNode); + assert( pFanin->nRefs > 0 ); + if ( --pFanin->nRefs == 0 && (!LevelMin || pFanin->Level > LevelMin) ) + Counter += Aig_NodeDeref_rec( pFanin, LevelMin ); + // skip the buffer + if ( Aig_ObjIsBuf(pNode) ) + return Counter; + assert( Aig_ObjIsNode(pNode) ); + // consider the second fanin + pFanin = Aig_ObjFanin1(pNode); + assert( pFanin->nRefs > 0 ); + if ( --pFanin->nRefs == 0 && (!LevelMin || pFanin->Level > LevelMin) ) + Counter += Aig_NodeDeref_rec( pFanin, LevelMin ); + return Counter + 1; +} + +/**Function************************************************************* + + Synopsis [References the node's MFFC.] + + Description [] + + SideEffects [] + + SeeAlso [] + +***********************************************************************/ +int Aig_NodeRef_rec( Aig_Obj_t * pNode, unsigned LevelMin ) +{ + Aig_Obj_t * pFanin; + int Counter = 0; + if ( Aig_ObjIsPi(pNode) ) + return 0; + // consider the first fanin + pFanin = Aig_ObjFanin0(pNode); + if ( pFanin->nRefs++ == 0 && (!LevelMin || pFanin->Level > LevelMin) ) + Counter += Aig_NodeRef_rec( pFanin, LevelMin ); + // skip the buffer + if ( Aig_ObjIsBuf(pNode) ) + return Counter; + assert( Aig_ObjIsNode(pNode) ); + // consider the second fanin + pFanin = Aig_ObjFanin1(pNode); + if ( pFanin->nRefs++ == 0 && (!LevelMin || pFanin->Level > LevelMin) ) + Counter += Aig_NodeRef_rec( pFanin, LevelMin ); + return Counter + 1; +} + +/**Function************************************************************* + + Synopsis [References the node's MFFC.] + + Description [] + + SideEffects [] + + SeeAlso [] + +***********************************************************************/ +int Aig_NodeRefLabel_rec( Aig_Man_t * p, Aig_Obj_t * pNode, unsigned LevelMin ) +{ + Aig_Obj_t * pFanin; + int Counter = 0; + if ( Aig_ObjIsPi(pNode) ) + return 0; + Aig_ObjSetTravIdCurrent( p, pNode ); + // consider the first fanin + pFanin = Aig_ObjFanin0(pNode); + if ( pFanin->nRefs++ == 0 && (!LevelMin || pFanin->Level > LevelMin) ) + Counter += Aig_NodeRefLabel_rec( p, pFanin, LevelMin ); + if ( Aig_ObjIsBuf(pNode) ) + return Counter; + assert( Aig_ObjIsNode(pNode) ); + // consider the second fanin + pFanin = Aig_ObjFanin1(pNode); + if ( pFanin->nRefs++ == 0 && (!LevelMin || pFanin->Level > LevelMin) ) + Counter += Aig_NodeRefLabel_rec( p, pFanin, LevelMin ); + return Counter + 1; +} + +/**Function************************************************************* + + Synopsis [Collects the internal and boundary nodes in the derefed MFFC.] + + Description [] + + SideEffects [] + + SeeAlso [] + +***********************************************************************/ +void Aig_NodeMffsSupp_rec( Aig_Man_t * p, Aig_Obj_t * pNode, unsigned LevelMin, Vec_Ptr_t * vSupp, int fTopmost, Aig_Obj_t * pObjSkip ) +{ + // skip visited nodes + if ( Aig_ObjIsTravIdCurrent(p, pNode) ) + return; + Aig_ObjSetTravIdCurrent(p, pNode); + // add to the new support nodes + if ( !fTopmost && pNode != pObjSkip && (Aig_ObjIsPi(pNode) || pNode->nRefs > 0 || pNode->Level <= LevelMin) ) + { + if ( vSupp ) Vec_PtrPush( vSupp, pNode ); + return; + } + assert( Aig_ObjIsNode(pNode) ); + // recur on the children + Aig_NodeMffsSupp_rec( p, Aig_ObjFanin0(pNode), LevelMin, vSupp, 0, pObjSkip ); + Aig_NodeMffsSupp_rec( p, Aig_ObjFanin1(pNode), LevelMin, vSupp, 0, pObjSkip ); +} + +/**Function************************************************************* + + Synopsis [Collects the support of depth-limited MFFC.] + + Description [Returns the number of internal nodes in the MFFC.] + + SideEffects [] + + SeeAlso [] + +***********************************************************************/ +int Aig_NodeMffsSupp( Aig_Man_t * p, Aig_Obj_t * pNode, int LevelMin, Vec_Ptr_t * vSupp ) +{ + int ConeSize1, ConeSize2; + assert( !Aig_IsComplement(pNode) ); + assert( Aig_ObjIsNode(pNode) ); + if ( vSupp ) Vec_PtrClear( vSupp ); + Aig_ManIncrementTravId( p ); + ConeSize1 = Aig_NodeDeref_rec( pNode, LevelMin ); + Aig_NodeMffsSupp_rec( p, pNode, LevelMin, vSupp, 1, NULL ); + ConeSize2 = Aig_NodeRef_rec( pNode, LevelMin ); + assert( ConeSize1 == ConeSize2 ); + assert( ConeSize1 > 0 ); + return ConeSize1; +} + +/**Function************************************************************* + + Synopsis [Labels the nodes in the MFFC.] + + Description [Returns the number of internal nodes in the MFFC.] + + SideEffects [] + + SeeAlso [] + +***********************************************************************/ +int Aig_NodeMffsLabel( Aig_Man_t * p, Aig_Obj_t * pNode ) +{ + int ConeSize1, ConeSize2; + assert( !Aig_IsComplement(pNode) ); + assert( Aig_ObjIsNode(pNode) ); + Aig_ManIncrementTravId( p ); + ConeSize1 = Aig_NodeDeref_rec( pNode, 0 ); + ConeSize2 = Aig_NodeRefLabel_rec( p, pNode, 0 ); + assert( ConeSize1 == ConeSize2 ); + assert( ConeSize1 > 0 ); + return ConeSize1; +} + +/**Function************************************************************* + + Synopsis [Labels the nodes in the MFFC.] + + Description [Returns the number of internal nodes in the MFFC.] + + SideEffects [] + + SeeAlso [] + +***********************************************************************/ +int Aig_NodeMffsLabelCut( Aig_Man_t * p, Aig_Obj_t * pNode, Vec_Ptr_t * vLeaves ) +{ + Aig_Obj_t * pObj; + int i, ConeSize1, ConeSize2; + assert( !Aig_IsComplement(pNode) ); + assert( Aig_ObjIsNode(pNode) ); + Aig_ManIncrementTravId( p ); + Vec_PtrForEachEntry( vLeaves, pObj, i ) + pObj->nRefs++; + ConeSize1 = Aig_NodeDeref_rec( pNode, 0 ); + ConeSize2 = Aig_NodeRefLabel_rec( p, pNode, 0 ); + Vec_PtrForEachEntry( vLeaves, pObj, i ) + pObj->nRefs--; + assert( ConeSize1 == ConeSize2 ); + assert( ConeSize1 > 0 ); + return ConeSize1; +} + +/**Function************************************************************* + + Synopsis [Expands the cut by adding the most closely related node.] + + Description [Returns 1 if the cut exists.] + + SideEffects [] + + SeeAlso [] + +***********************************************************************/ +int Aig_NodeMffsExtendCut( Aig_Man_t * p, Aig_Obj_t * pNode, Vec_Ptr_t * vLeaves, Vec_Ptr_t * vResult ) +{ + Aig_Obj_t * pObj, * pLeafBest; + int i, LevelMax, ConeSize1, ConeSize2, ConeCur1, ConeCur2, ConeBest; + // dereference the current cut + LevelMax = 0; + Vec_PtrForEachEntry( vLeaves, pObj, i ) + LevelMax = AIG_MAX( LevelMax, (int)pObj->Level ); + if ( LevelMax == 0 ) + return 0; + // dereference the cut + ConeSize1 = Aig_NodeDeref_rec( pNode, 0 ); + // try expanding each node in the boundary + ConeBest = AIG_INFINITY; + pLeafBest = NULL; + Vec_PtrForEachEntry( vLeaves, pObj, i ) + { + if ( (int)pObj->Level != LevelMax ) + continue; + ConeCur1 = Aig_NodeDeref_rec( pObj, 0 ); + if ( ConeBest > ConeCur1 ) + { + ConeBest = ConeCur1; + pLeafBest = pObj; + } + ConeCur2 = Aig_NodeRef_rec( pObj, 0 ); + assert( ConeCur1 == ConeCur2 ); + } + assert( pLeafBest != NULL ); + assert( Aig_ObjIsNode(pLeafBest) ); + // deref the best leaf + ConeCur1 = Aig_NodeDeref_rec( pLeafBest, 0 ); + // collect the cut nodes + Vec_PtrClear( vResult ); + Aig_ManIncrementTravId( p ); + Aig_NodeMffsSupp_rec( p, pNode, 0, vResult, 1, pLeafBest ); + // ref the nodes + ConeCur2 = Aig_NodeRef_rec( pLeafBest, 0 ); + assert( ConeCur1 == ConeCur2 ); + // ref the original node + ConeSize2 = Aig_NodeRef_rec( pNode, 0 ); + assert( ConeSize1 == ConeSize2 ); + return 1; +} + +//////////////////////////////////////////////////////////////////////// +/// END OF FILE /// +//////////////////////////////////////////////////////////////////////// + + diff --git a/pool/shard000/C/0008609_logging.c b/pool/shard000/C/0008609_logging.c new file mode 100644 index 0000000000000000000000000000000000000000..7c09777448a0f70291e1f76d59ebe6a3b152a2bb --- /dev/null +++ b/pool/shard000/C/0008609_logging.c @@ -0,0 +1,211 @@ +/* + Copyright (C) 2010 ABRT team + Copyright (C) 2010, 2014 RedHat Inc + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ +#include +/* Suppress automatic CODE_* fields as we handle those here */ +#define SD_JOURNAL_SUPPRESS_LOCATION +#include +#include "internal_libreport.h" + +void (*libreport_g_custom_logger)(const char*); +const char *libreport_msg_prefix = ""; +const char *libreport_msg_eol = "\n"; +int libreport_logmode = LOGMODE_STDIO; +int libreport_xfunc_error_retval = EXIT_FAILURE; +static enum libreport_diemode xfunc_diemode = DIEMODE_EXIT; +int libreport_g_verbose; + +void libreport_set_xfunc_error_retval(int retval) +{ + libreport_xfunc_error_retval = retval; +} + +void libreport_set_xfunc_diemode(enum libreport_diemode mode) +{ + xfunc_diemode = mode; +} + +/* [p]error_msg[_and_die] must be safe after fork in multi-threaded programs. + * Therefore we avoid stdio, fflush(), and use _exit() instead of exit(). + * + */ +void libreport_xfunc_die(void) +{ + char *const envmode = getenv("LIBREPORT_DIEMODE"); + if ( xfunc_diemode == DIEMODE_ABORT + || (envmode != NULL && strcmp("abort", envmode) == 0)) + abort(); + + _exit(libreport_xfunc_error_retval); +} + +static bool should_log(int level) +{ + // LOG_DEBUG = 7, LOG_INFO = 6, LOG_NOTICE = 5, LOG_WARNING = 4, LOG_ERR = 3 + // output only messages with LOG_ERR by default, overridden by libreport_g_verbose + if( + (libreport_g_verbose == 0 && level <= LOG_WARNING) || + (libreport_g_verbose == 1 && level <= LOG_NOTICE) || + (libreport_g_verbose == 2 && level <= LOG_INFO) || + (libreport_g_verbose == 3) + ) + return true; + + return false; +} + + +static void log_handler(int level, + const char *format, + va_list p, + const char *strerr, /* perror messages */ + int flags, + const char *file, + int line, + const char *func) +{ + if (!libreport_logmode || !should_log(level)) + return; + + /* This is ugly and costs +60 bytes compared to multiple + * fprintf's, but is guaranteed to do a single write. + * This is needed for e.g. when multiple children + * can produce log messages simultaneously. */ + + int prefix_len = libreport_msg_prefix[0] ? strlen(libreport_msg_prefix) + 2 : 0; + int strerr_len = strerr ? strlen(strerr) : 0; + int msgeol_len = strlen(libreport_msg_eol); + int used; + + /* Try to format the message in a fixed buffer. + * This eliminates malloc. + * Main reason isn't the speed optimization, but to make + * short logging safe after fork in multithreaded libraries. + */ + char buf[1024]; + va_list p2; + va_copy(p2, p); + if (prefix_len < sizeof(buf)) + used = vsnprintf(buf + prefix_len, sizeof(buf) - prefix_len, format, p2); + else + used = vsnprintf(buf, 0, format, p2); + va_end(p2); + + char *msg = buf; + + /* +3 is for ": " before strerr and for terminating NUL */ + unsigned total_len = prefix_len + used + strerr_len + msgeol_len + 3; + + if (total_len >= sizeof(buf)) + { + msg = alloca(total_len); + used = vsnprintf(msg + prefix_len, total_len - prefix_len, format, p); + } + + if (prefix_len) { + char *p; + used += prefix_len; + p = stpcpy(msg, libreport_msg_prefix); + p[0] = ':'; + p[1] = ' '; + } + if (strerr) { + if (format[0]) { + msg[used++] = ':'; + msg[used++] = ' '; + } + strcpy(&msg[used], strerr); + used += strerr_len; + } + strcpy(&msg[used], libreport_msg_eol); + + if (flags & LOGMODE_STDIO) { + libreport_full_write(STDERR_FILENO, msg, used + msgeol_len); + } + msg[used] = '\0'; /* remove libreport_msg_eol (usually "\n") */ + if (flags & LOGMODE_SYSLOG) { + syslog(level, "%s", msg + prefix_len); + } + + if ((flags & LOGMODE_CUSTOM) && libreport_g_custom_logger) { + libreport_g_custom_logger(msg + prefix_len); + } + + if (flags & LOGMODE_JOURNAL) { + sd_journal_send("MESSAGE=%s", msg + prefix_len, + "PRIORITY=%d", level, + "CODE_FILE=%s", file, + "CODE_LINE=%d", line, + "CODE_FUNC=%s", func, + "SYSLOG_FACILITY=1", + NULL); + } +} + +void log_wrapper(int level, + const char *file, + int line, + const char *func, + bool process_perror, + bool use_custom_logger, + const char *format, + ...) +{ + va_list p; + + va_start(p, format); + log_handler(level, + format, + p, + (process_perror && errno) ? strerror(errno) : NULL, /* Guard against ": Success" */ + libreport_logmode | (use_custom_logger ? LOGMODE_CUSTOM : 0), + file, + line, + func); + va_end(p); +} + +void log_and_die_wrapper(int level, + const char *file, + int line, + const char *func, + bool process_perror, + bool use_custom_logger, + const char *format, + ...) +{ + va_list p; + + va_start(p, format); + log_handler(level, + format, + p, + (process_perror && errno) ? strerror(errno) : NULL, /* Guard against ": Success" */ + libreport_logmode | (use_custom_logger ? LOGMODE_CUSTOM : 0), + file, + line, + func); + va_end(p); + libreport_xfunc_die(); +} + + +void libreport_die_out_of_memory(void) +{ + error_msg_and_die("Out of memory, exiting"); +} diff --git a/pool/shard000/C/0008613_test-prioq.c b/pool/shard000/C/0008613_test-prioq.c new file mode 100644 index 0000000000000000000000000000000000000000..1e2e42cbca1713440533d8faf51393895db5bbfb --- /dev/null +++ b/pool/shard000/C/0008613_test-prioq.c @@ -0,0 +1,172 @@ +/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ + +/*** + This file is part of systemd. + + Copyright 2013 Lennart Poettering + + systemd is free software; you can redistribute it and/or modify it + under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation; either version 2.1 of the License, or + (at your option) any later version. + + systemd is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with systemd; If not, see . +***/ + +#include + +#include "util.h" +#include "set.h" +#include "prioq.h" +#include "siphash24.h" + +#define SET_SIZE 1024*4 + +static int unsigned_compare(const void *a, const void *b) { + const unsigned *x = a, *y = b; + + if (*x < *y) + return -1; + + if (*x > *y) + return 1; + + return 0; +} + +static void test_unsigned(void) { + unsigned buffer[SET_SIZE], i; + Prioq *q; + + srand(0); + + q = prioq_new(trivial_compare_func); + assert_se(q); + + for (i = 0; i < ELEMENTSOF(buffer); i++) { + unsigned u; + + u = (unsigned) rand(); + buffer[i] = u; + assert_se(prioq_put(q, UINT_TO_PTR(u), NULL) >= 0); + } + + qsort(buffer, ELEMENTSOF(buffer), sizeof(buffer[0]), unsigned_compare); + + for (i = 0; i < ELEMENTSOF(buffer); i++) { + unsigned u; + + assert_se(prioq_size(q) == ELEMENTSOF(buffer) - i); + + u = PTR_TO_UINT(prioq_pop(q)); + assert_se(buffer[i] == u); + } + + assert_se(prioq_isempty(q)); + prioq_free(q); +} + +struct test { + unsigned value; + unsigned idx; +}; + +static int test_compare(const void *a, const void *b) { + const struct test *x = a, *y = b; + + if (x->value < y->value) + return -1; + + if (x->value > y->value) + return 1; + + return 0; +} + +static void test_hash(const void *a, struct siphash *state) { + const struct test *x = a; + + siphash24_compress(&x->value, sizeof(x->value), state); +} + +static const struct hash_ops test_hash_ops = { + .hash = test_hash, + .compare = test_compare +}; + +static void test_struct(void) { + Prioq *q; + Set *s; + unsigned previous = 0, i; + int r; + + srand(0); + + q = prioq_new(test_compare); + assert_se(q); + + s = set_new(&test_hash_ops); + assert_se(s); + + for (i = 0; i < SET_SIZE; i++) { + struct test *t; + + t = new0(struct test, 1); + assert_se(t); + t->value = (unsigned) rand(); + + r = prioq_put(q, t, &t->idx); + assert_se(r >= 0); + + if (i % 4 == 0) { + r = set_consume(s, t); + assert_se(r >= 0); + } + } + + for (;;) { + struct test *t; + + t = set_steal_first(s); + if (!t) + break; + + r = prioq_remove(q, t, &t->idx); + assert_se(r > 0); + + free(t); + } + + for (i = 0; i < SET_SIZE * 3 / 4; i++) { + struct test *t; + + assert_se(prioq_size(q) == (SET_SIZE * 3 / 4) - i); + + t = prioq_pop(q); + assert_se(t); + + assert_se(previous <= t->value); + previous = t->value; + free(t); + } + + assert_se(prioq_isempty(q)); + prioq_free(q); + + assert_se(set_isempty(s)); + set_free(s); +} + +int main(int argc, char* argv[]) { + + test_unsigned(); + test_struct(); + + return 0; +} diff --git a/pool/shard000/C/0008639_lpc17xx_clkpwr.c b/pool/shard000/C/0008639_lpc17xx_clkpwr.c new file mode 100644 index 0000000000000000000000000000000000000000..944017ef086cd5b37eb52083dd2f4267863d4da5 --- /dev/null +++ b/pool/shard000/C/0008639_lpc17xx_clkpwr.c @@ -0,0 +1,327 @@ +/******************************************************************//** +* @file lpc17xx_clkpwr.c +* @brief Contains all functions support for Clock and Power Control +* firmware library on LPC17xx +* @version 1.0 +* @date 24. July. 2013 +* @author Dwijay.Edutech Learning Solutions +**********************************************************************/ + +/* Peripheral group ----------------------------------------------------------- */ +/** @addtogroup CLKPWR + * @{ + */ + +/* Includes ------------------------------------------------------------------- */ +#include "lpc17xx_clkpwr.h" + + +/* Public Functions ----------------------------------------------------------- */ +/** @addtogroup CLKPWR_Public_Functions + * @{ + */ + +/*********************************************************************//** + * @brief Set value of each Peripheral Clock Selection + * @param[in] ClkType Peripheral Clock Selection of each type, + * should be one of the following: + * - CLKPWR_PCLKSEL_WDT : WDT + - CLKPWR_PCLKSEL_TIMER0 : Timer 0 + - CLKPWR_PCLKSEL_TIMER1 : Timer 1 + - CLKPWR_PCLKSEL_UART0 : UART 0 + - CLKPWR_PCLKSEL_UART1 : UART 1 + - CLKPWR_PCLKSEL_PWM1 : PWM 1 + - CLKPWR_PCLKSEL_I2C0 : I2C 0 + - CLKPWR_PCLKSEL_SPI : SPI + - CLKPWR_PCLKSEL_SSP1 : SSP 1 + - CLKPWR_PCLKSEL_DAC : DAC + - CLKPWR_PCLKSEL_ADC : ADC + - CLKPWR_PCLKSEL_CAN1 : CAN 1 + - CLKPWR_PCLKSEL_CAN2 : CAN 2 + - CLKPWR_PCLKSEL_ACF : ACF + - CLKPWR_PCLKSEL_QEI : QEI + - CLKPWR_PCLKSEL_PCB : PCB + - CLKPWR_PCLKSEL_I2C1 : I2C 1 + - CLKPWR_PCLKSEL_SSP0 : SSP 0 + - CLKPWR_PCLKSEL_TIMER2 : Timer 2 + - CLKPWR_PCLKSEL_TIMER3 : Timer 3 + - CLKPWR_PCLKSEL_UART2 : UART 2 + - CLKPWR_PCLKSEL_UART3 : UART 3 + - CLKPWR_PCLKSEL_I2C2 : I2C 2 + - CLKPWR_PCLKSEL_I2S : I2S + - CLKPWR_PCLKSEL_RIT : RIT + - CLKPWR_PCLKSEL_SYSCON : SYSCON + - CLKPWR_PCLKSEL_MC : MC + + * @param[in] DivVal Value of divider, should be: + * - CLKPWR_PCLKSEL_CCLK_DIV_4 : PCLK_peripheral = CCLK/4 + * - CLKPWR_PCLKSEL_CCLK_DIV_1 : PCLK_peripheral = CCLK/1 + * - CLKPWR_PCLKSEL_CCLK_DIV_2 : PCLK_peripheral = CCLK/2 + * + * @return none + **********************************************************************/ +void CLKPWR_SetPCLKDiv (uint32_t ClkType, uint32_t DivVal) +{ + uint32_t bitpos; + + bitpos = (ClkType < 32) ? (ClkType) : (ClkType - 32); + + /* PCLKSEL0 selected */ + if (ClkType < 32) + { + /* Clear two bit at bit position */ + LPC_SC->PCLKSEL0 &= (~(CLKPWR_PCLKSEL_BITMASK(bitpos))); + + /* Set two selected bit */ + LPC_SC->PCLKSEL0 |= (CLKPWR_PCLKSEL_SET(bitpos, DivVal)); + } + /* PCLKSEL1 selected */ + else + { + /* Clear two bit at bit position */ + LPC_SC->PCLKSEL1 &= ~(CLKPWR_PCLKSEL_BITMASK(bitpos)); + + /* Set two selected bit */ + LPC_SC->PCLKSEL1 |= (CLKPWR_PCLKSEL_SET(bitpos, DivVal)); + } +} + + +/*********************************************************************//** + * @brief Get current value of each Peripheral Clock Selection + * @param[in] ClkType Peripheral Clock Selection of each type, + * should be one of the following: + * - CLKPWR_PCLKSEL_WDT : WDT + - CLKPWR_PCLKSEL_TIMER0 : Timer 0 + - CLKPWR_PCLKSEL_TIMER1 : Timer 1 + - CLKPWR_PCLKSEL_UART0 : UART 0 + - CLKPWR_PCLKSEL_UART1 : UART 1 + - CLKPWR_PCLKSEL_PWM1 : PWM 1 + - CLKPWR_PCLKSEL_I2C0 : I2C 0 + - CLKPWR_PCLKSEL_SPI : SPI + - CLKPWR_PCLKSEL_SSP1 : SSP 1 + - CLKPWR_PCLKSEL_DAC : DAC + - CLKPWR_PCLKSEL_ADC : ADC + - CLKPWR_PCLKSEL_CAN1 : CAN 1 + - CLKPWR_PCLKSEL_CAN2 : CAN 2 + - CLKPWR_PCLKSEL_ACF : ACF + - CLKPWR_PCLKSEL_QEI : QEI + - CLKPWR_PCLKSEL_PCB : PCB + - CLKPWR_PCLKSEL_I2C1 : I2C 1 + - CLKPWR_PCLKSEL_SSP0 : SSP 0 + - CLKPWR_PCLKSEL_TIMER2 : Timer 2 + - CLKPWR_PCLKSEL_TIMER3 : Timer 3 + - CLKPWR_PCLKSEL_UART2 : UART 2 + - CLKPWR_PCLKSEL_UART3 : UART 3 + - CLKPWR_PCLKSEL_I2C2 : I2C 2 + - CLKPWR_PCLKSEL_I2S : I2S + - CLKPWR_PCLKSEL_RIT : RIT + - CLKPWR_PCLKSEL_SYSCON : SYSCON + - CLKPWR_PCLKSEL_MC : MC + + * @return Value of Selected Peripheral Clock Selection + **********************************************************************/ +uint32_t CLKPWR_GetPCLKSEL (uint32_t ClkType) +{ + uint32_t bitpos, retval; + + if (ClkType < 32) + { + bitpos = ClkType; + retval = LPC_SC->PCLKSEL0; + } + else + { + bitpos = ClkType - 32; + retval = LPC_SC->PCLKSEL1; + } + + retval = CLKPWR_PCLKSEL_GET(bitpos, retval); + return retval; +} + + + +/*********************************************************************//** + * @brief Get current value of each Peripheral Clock + * @param[in] ClkType Peripheral Clock Selection of each type, + * should be one of the following: + * - CLKPWR_PCLKSEL_WDT : WDT + - CLKPWR_PCLKSEL_TIMER0 : Timer 0 + - CLKPWR_PCLKSEL_TIMER1 : Timer 1 + - CLKPWR_PCLKSEL_UART0 : UART 0 + - CLKPWR_PCLKSEL_UART1 : UART 1 + - CLKPWR_PCLKSEL_PWM1 : PWM 1 + - CLKPWR_PCLKSEL_I2C0 : I2C 0 + - CLKPWR_PCLKSEL_SPI : SPI + - CLKPWR_PCLKSEL_SSP1 : SSP 1 + - CLKPWR_PCLKSEL_DAC : DAC + - CLKPWR_PCLKSEL_ADC : ADC + - CLKPWR_PCLKSEL_CAN1 : CAN 1 + - CLKPWR_PCLKSEL_CAN2 : CAN 2 + - CLKPWR_PCLKSEL_ACF : ACF + - CLKPWR_PCLKSEL_QEI : QEI + - CLKPWR_PCLKSEL_PCB : PCB + - CLKPWR_PCLKSEL_I2C1 : I2C 1 + - CLKPWR_PCLKSEL_SSP0 : SSP 0 + - CLKPWR_PCLKSEL_TIMER2 : Timer 2 + - CLKPWR_PCLKSEL_TIMER3 : Timer 3 + - CLKPWR_PCLKSEL_UART2 : UART 2 + - CLKPWR_PCLKSEL_UART3 : UART 3 + - CLKPWR_PCLKSEL_I2C2 : I2C 2 + - CLKPWR_PCLKSEL_I2S : I2S + - CLKPWR_PCLKSEL_RIT : RIT + - CLKPWR_PCLKSEL_SYSCON : SYSCON + - CLKPWR_PCLKSEL_MC : MC + + * @return Value of Selected Peripheral Clock + **********************************************************************/ +uint32_t CLKPWR_GetPCLK (uint32_t ClkType) +{ + uint32_t retval, div; + + retval = SystemCoreClock; + div = CLKPWR_GetPCLKSEL(ClkType); + + switch (div) + { + case 0: + div = 4; + break; + + case 1: + div = 1; + break; + + case 2: + div = 2; + break; + + case 3: + div = 8; + break; + } + retval /= div; + + return retval; +} + + + +/*********************************************************************//** + * @brief Configure power supply for each peripheral according to NewState + * @param[in] PPType Type of peripheral used to enable power, + * should be one of the following: + * - CLKPWR_PCONP_PCTIM0 : Timer 0 + - CLKPWR_PCONP_PCTIM1 : Timer 1 + - CLKPWR_PCONP_PCUART0 : UART 0 + - CLKPWR_PCONP_PCUART1 : UART 1 + - CLKPWR_PCONP_PCPWM1 : PWM 1 + - CLKPWR_PCONP_PCI2C0 : I2C 0 + - CLKPWR_PCONP_PCSPI : SPI + - CLKPWR_PCONP_PCRTC : RTC + - CLKPWR_PCONP_PCSSP1 : SSP 1 + - CLKPWR_PCONP_PCAD : ADC + - CLKPWR_PCONP_PCAN1 : CAN 1 + - CLKPWR_PCONP_PCAN2 : CAN 2 + - CLKPWR_PCONP_PCGPIO : GPIO + - CLKPWR_PCONP_PCRIT : RIT + - CLKPWR_PCONP_PCMC : MC + - CLKPWR_PCONP_PCQEI : QEI + - CLKPWR_PCONP_PCI2C1 : I2C 1 + - CLKPWR_PCONP_PCSSP0 : SSP 0 + - CLKPWR_PCONP_PCTIM2 : Timer 2 + - CLKPWR_PCONP_PCTIM3 : Timer 3 + - CLKPWR_PCONP_PCUART2 : UART 2 + - CLKPWR_PCONP_PCUART3 : UART 3 + - CLKPWR_PCONP_PCI2C2 : I2C 2 + - CLKPWR_PCONP_PCI2S : I2S + - CLKPWR_PCONP_PCGPDMA : GPDMA + - CLKPWR_PCONP_PCENET : Ethernet + - CLKPWR_PCONP_PCUSB : USB + * + * @param[in] NewState New state of Peripheral Power, should be: + * - ENABLE : Enable power for this peripheral + * - DISABLE : Disable power for this peripheral + * + * @return none + **********************************************************************/ +void CLKPWR_ConfigPPWR (uint32_t PPType, FunctionalState NewState) +{ + if (NewState == ENABLE) + { + LPC_SC->PCONP |= PPType & CLKPWR_PCONP_BITMASK; + } + else if (NewState == DISABLE) + { + LPC_SC->PCONP &= (~PPType) & CLKPWR_PCONP_BITMASK; + } +} + + +/*********************************************************************//** + * @brief Enter Sleep mode with co-operated instruction by the Cortex-M3. + * @param[in] None + * @return None + **********************************************************************/ +void CLKPWR_Sleep(void) +{ + LPC_SC->PCON = 0x00; + /* Sleep Mode*/ + __WFI(); +} + + +/*********************************************************************//** + * @brief Enter Deep Sleep mode with co-operated instruction by the Cortex-M3. + * @param[in] None + * @return None + **********************************************************************/ +void CLKPWR_DeepSleep(void) +{ + /* Deep-Sleep Mode, set SLEEPDEEP bit */ + SCB->SCR = 0x4; + LPC_SC->PCON = 0x8; + /* Deep Sleep Mode*/ + __WFI(); +} + + +/*********************************************************************//** + * @brief Enter Power Down mode with co-operated instruction by the Cortex-M3. + * @param[in] None + * @return None + **********************************************************************/ +void CLKPWR_PowerDown(void) +{ + /* Deep-Sleep Mode, set SLEEPDEEP bit */ + SCB->SCR = 0x4; + LPC_SC->PCON = 0x09; + /* Power Down Mode*/ + __WFI(); +} + + +/*********************************************************************//** + * @brief Enter Deep Power Down mode with co-operated instruction by the Cortex-M3. + * @param[in] None + * @return None + **********************************************************************/ +void CLKPWR_DeepPowerDown(void) +{ + /* Deep-Sleep Mode, set SLEEPDEEP bit */ + SCB->SCR = 0x4; + LPC_SC->PCON = 0x03; + /* Deep Power Down Mode*/ + __WFI(); +} + +/** + * @} + */ + +/** + * @} + */ + +/* --------------------------------- End Of File ------------------------------ */ diff --git a/pool/shard000/C/0008652_init.c b/pool/shard000/C/0008652_init.c new file mode 100644 index 0000000000000000000000000000000000000000..cc273a91b83084bb1d7323874865fce6967e492e --- /dev/null +++ b/pool/shard000/C/0008652_init.c @@ -0,0 +1,98 @@ +#include"header.h" +#include"declarations.h" + + +int major_num; +unsigned int minor_num; +unsigned int num_dev; +int qset_size; +int quantum_size; +int device_size; +int data_size; +dev_t dev; +dev_t new_dev; +struct ScullDev *sculldev; + +module_param(num_dev,uint,S_IRUGO); + +struct file_operations fops = { + .owner = THIS_MODULE, + .open = open_dev, + .release = close_dev, + .write = write_dev, + .read = read_dev, + .llseek = llseek_dev, +}; + +void init_default(void) +{ + major_num = MAJOR_NUM; + minor_num = MINOR_NUM; + qset_size = QSET_SIZE; + quantum_size = QUANTUM_SIZE; + data_size = DATA_SIZE; + device_size = DEVICE_SIZE; +} + +static int __init initialization(void) +{ + int ret,i; + unsigned int ma,mi; + + #ifdef DEBUG + printk(KERN_INFO "START: %s \n",__func__); + #endif + init_default(); + + ret = alloc_chrdev_region(&dev,minor_num,num_dev,DEV_NAME); + if(ret < 0) { + printk(KERN_ERR "registration failure\n"); + goto ERR; + } + #ifdef DEBUG + printk(KERN_INFO "major number = %u ,minor number=%u\n",MAJOR(dev),MINOR(dev)); + #endif + + sculldev = kmalloc(sizeof(struct ScullDev)*num_dev,GFP_KERNEL); + if(!sculldev) { + printk(KERN_ERR "error in kmalloc\n"); + goto ERR; + } + + memset(sculldev,'\0',sizeof(struct ScullDev) * num_dev); + + ma = MAJOR(dev); + + for(i=0;i < num_dev ;i++) { + mi = MINOR(dev+i); + new_dev = MKDEV(ma,mi); + + cdev_init(&sculldev[i].c_dev,&fops); + sculldev[i].c_dev.owner = THIS_MODULE; + sculldev[i].c_dev.ops = &fops; + sculldev[i].qset_size = qset_size; + sculldev[i].quantum_size = quantum_size; + sculldev[i].data_size = data_size; + sculldev[i].device_size = device_size; + init_completion(&sculldev[i].my_completion); + ret = cdev_add(&sculldev[i].c_dev,new_dev,1); + if(ret != 0) { + printk(KERN_ERR "error in adding cdev\n"); + goto ERR; + } + #ifdef DEBUG + printk(KERN_INFO "cdev major num = %d,minor_num = %d \n",MAJOR(sculldev[i].c_dev.dev),MINOR(sculldev[i].c_dev.dev)); + #endif + } + + #ifdef DEBUG + printk(KERN_INFO "END: %s \n",__func__); + #endif + return 0; + +ERR: + return -1; +} + +MODULE_LICENSE("GPL"); +module_init(initialization); diff --git a/pool/shard000/C/0008653_myrg_locking.c b/pool/shard000/C/0008653_myrg_locking.c new file mode 100644 index 0000000000000000000000000000000000000000..fa77160421297b375707e16037e9e14b372da093 --- /dev/null +++ b/pool/shard000/C/0008653_myrg_locking.c @@ -0,0 +1,51 @@ +/* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. + + 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ + +/* + Lock blockchains against read or write. +*/ + +#include "myrg_def.h" + +int myrg_lock_blockchain(MYRG_INFO *info, int lock_type) +{ + int error,new_error; + MYRG_TABLE *file; + + error=0; + for (file=info->open_tables ; file != info->end_table ; file++) + { +#ifdef _WIN32 + /* + Make sure this table is marked as owned by a merge table. + The semaphore is never released as long as table remains + in memory. This should be refactored into a more generic + approach (observer pattern) + */ + (file->table)->owned_by_merge = TRUE; +#endif + if ((new_error=mi_lock_blockchain(file->table,lock_type))) + { + error=new_error; + if (lock_type != F_UNLCK) + { + while (--file >= info->open_tables) + mi_lock_blockchain(file->table, F_UNLCK); + break; + } + } + } + return(error); +} diff --git a/pool/shard000/C/0008670_mips_features.c b/pool/shard000/C/0008670_mips_features.c new file mode 100644 index 0000000000000000000000000000000000000000..5edb1207d574c00fbb4f9cb33f985868df8a09b6 --- /dev/null +++ b/pool/shard000/C/0008670_mips_features.c @@ -0,0 +1,125 @@ +// This file determines MIPS features a processor supports. +// +// We return: +// - 0 if the machine matches the asked-for feature. +// - 1 if the machine does not. +// - 2 if the asked-for feature isn't recognised (this will be the case for +// any feature if run on a non-MIPS machine). +// - 3 if there was a usage error (it also prints an error message). +#include +#include +#include +#include + +#define FEATURE_PRESENT 0 +#define FEATURE_NOT_PRESENT 1 +#define UNRECOGNISED_FEATURE 2 +#define USAGE_ERROR 3 + +#if defined(VGA_mips32) || defined(VGA_mips64) +static int mipsCPUInfo(const char *search_string) { + const char *file_name = "/proc/cpuinfo"; + /* Simple detection of MIPS DSP ASE at runtime for Linux. + * It is based on /proc/cpuinfo, which reveals hardware configuration + * to user-space applications. */ + + char cpuinfo_line[256]; + + FILE *f = NULL; + if ((f = fopen (file_name, "r")) == NULL) + return 0; + + while (fgets (cpuinfo_line, sizeof (cpuinfo_line), f) != NULL) + { + if (strstr (cpuinfo_line, search_string) != NULL) + { + fclose (f); + return 1; + } + } + + fclose (f); + + /* Did not find string in the /proc/cpuinfo file. */ + return 0; +} + +static int go(char *feature) +{ + int cpuinfo; + if (strcmp(feature, "fpu") == 0) { +#if defined(__mips_hard_float) + /* This is not a runtime detection. + If mips_features is built as hard-float, the assumption is that + the target MIPS platform has a floating-point unit. */ + return FEATURE_PRESENT; +#else + return FEATURE_NOT_PRESENT; +#endif + } + else if (strcmp(feature, "mips32-dsp") == 0) { + const char *dsp = "dsp"; + cpuinfo = mipsCPUInfo(dsp); + if (cpuinfo == 1) { + return FEATURE_PRESENT; + } else{ + return FEATURE_NOT_PRESENT; + } + } else if (strcmp(feature, "mips32-dspr2") == 0) { + const char *dsp2 = "dsp2"; + cpuinfo = mipsCPUInfo(dsp2); + if (cpuinfo == 1) { + return FEATURE_PRESENT; + } else{ + return FEATURE_NOT_PRESENT; + } + } else if (strcmp(feature, "cavium-octeon") == 0) { + const char *cavium = "Cavium Octeon"; + cpuinfo = mipsCPUInfo(cavium); + if (cpuinfo == 1) { + return FEATURE_PRESENT; + } else{ + return FEATURE_NOT_PRESENT; + } + } else if (strcmp(feature, "cavium-octeon2") == 0) { + const char *cavium2 = "Cavium Octeon II"; + cpuinfo = mipsCPUInfo(cavium2); + if (cpuinfo == 1) { + return FEATURE_PRESENT; + } else{ + return FEATURE_NOT_PRESENT; + } + } else if (strcmp(feature, "mips-be") == 0) { +#if defined (_MIPSEB) + return FEATURE_PRESENT; +#else + return FEATURE_NOT_PRESENT; +#endif + } else { + return UNRECOGNISED_FEATURE; + } + +} + +#else + +static int go(char *feature) +{ + /* Feature is not recognised. (non-MIPS machine!) */ + return UNRECOGNISED_FEATURE; +} + +#endif + + +//--------------------------------------------------------------------------- +// main +//--------------------------------------------------------------------------- +int main(int argc, char **argv) +{ + if (argc != 2) { + fprintf( stderr, "usage: mips_features \n" ); + exit(USAGE_ERROR); + } + return go(argv[1]); +} diff --git a/pool/shard000/C/0008685_stdio_test.c b/pool/shard000/C/0008685_stdio_test.c new file mode 100644 index 0000000000000000000000000000000000000000..1d177fc3b7303a0c39cd8768c1d39863907c283f --- /dev/null +++ b/pool/shard000/C/0008685_stdio_test.c @@ -0,0 +1,159 @@ +/* +** Copyright (C) 2001-2004 Erik de Castro Lopo +** +** This program is free software; you can redistribute it and/or modify +** it under the terms of the GNU General Public License as published by +** the Free Software Foundation; either version 2 of the License, or +** (at your option) any later version. +** +** This program is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +** GNU General Public License for more details. +** +** You should have received a copy of the GNU General Public License +** along with this program; if not, write to the Free Software +** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ + +/*========================================================================== +** This is a test program which tests reading from stdin and writing to +** stdout. +*/ + +#include "sfconfig.h" + +#include +#include +#include + +#if HAVE_UNISTD_H +#include +#endif + +#include +#include + +#if HAVE_SYS_WAIT_H +#include +#endif + +#include "utils.h" + +#if (OS_IS_WIN32) + +int +main (void) +{ + puts (" stdio_test : this test doesn't work on win32.") ; + return 0 ; +} /* main */ + +#else + +#ifndef WIFEXITED +#define WIFEXITED(s) (((s) & 0xff) == 0) +#endif +#ifndef WEXITSTATUS +#define WEXITSTATUS(s) (((s) & 0xff00) >> 8) +#endif + + +static size_t file_length (const char *filename) ; +static int file_exists (const char *filename) ; +static void stdio_test (const char *filetype) ; + +static const char *filetypes [] = +{ "raw", "wav", "aiff", "au", "paf", "svx", "nist", "ircam", + "voc", "w64", "mat4", "mat5", "pvf", + NULL +} ; + +int +main (void) +{ int k ; + + if (file_exists ("libsndfile.spec.in")) + chdir ("tests") ; + + for (k = 0 ; filetypes [k] ; k++) + stdio_test (filetypes [k]) ; + + return 0 ; +} /* main */ + + +static void +stdio_test (const char *filetype) +{ static char buffer [256] ; + + int file_size, retval ; + + print_test_name ("stdio_test", filetype) ; + + snprintf (buffer, sizeof (buffer), "./stdout_test %s > stdio.%s", filetype, filetype) ; + if ((retval = system (buffer))) + { retval = WIFEXITED (retval) ? WEXITSTATUS (retval) : 1 ; + printf ("%s : %s", buffer, (strerror (retval))) ; + exit (1) ; + } ; + + snprintf (buffer, sizeof (buffer), "stdio.%s", filetype) ; + if ((file_size = file_length (buffer)) < PIPE_TEST_LEN) + { printf ("\n Error : test file '%s' too small (%d).\n\n", buffer, file_size) ; + exit (1) ; + } ; + + snprintf (buffer, sizeof (buffer), "./stdin_test %s < stdio.%s", filetype, filetype) ; + if ((retval = system (buffer))) + { retval = WIFEXITED (retval) ? WEXITSTATUS (retval) : 1 ; + printf ("%s : %s", buffer, (strerror (retval))) ; + exit (1) ; + } ; + + snprintf (buffer, sizeof (buffer), "rm stdio.%s", filetype) ; + if ((retval = system (buffer))) + { retval = WIFEXITED (retval) ? WEXITSTATUS (retval) : 1 ; + printf ("%s : %s", buffer, (strerror (retval))) ; + exit (1) ; + } ; + + puts ("ok") ; + + return ; +} /* stdio_test */ + + + + +static size_t +file_length (const char *filename) +{ struct stat buf ; + + if (stat (filename, &buf)) + { perror (filename) ; + exit (1) ; + } ; + + return buf.st_size ; +} /* file_length */ + +static int +file_exists (const char *filename) +{ struct stat buf ; + + if (stat (filename, &buf)) + return 0 ; + + return 1 ; +} /* file_exists */ + +#endif + +/* +** Do not edit or modify anything in this comment block. +** The arch-tag line is a file identity tag for the GNU Arch +** revision control system. +** +** arch-tag: f46d84fd-d37b-4d08-b1ba-80f2f1e0cfb9 +*/ diff --git a/pool/shard000/C/0008695_CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int_memcpy_51b.c b/pool/shard000/C/0008695_CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int_memcpy_51b.c new file mode 100644 index 0000000000000000000000000000000000000000..b385549d26889946e6650f9011aa81f6fc4fb53e --- /dev/null +++ b/pool/shard000/C/0008695_CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int_memcpy_51b.c @@ -0,0 +1,50 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int_memcpy_51b.c +Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE805.label.xml +Template File: sources-sink-51b.tmpl.c +*/ +/* + * @description + * CWE: 122 Heap Based Buffer Overflow + * BadSource: Allocate using malloc() and set data pointer to a small buffer + * GoodSource: Allocate using malloc() and set data pointer to a large buffer + * Sink: memcpy + * BadSink : Copy int array to data using memcpy + * Flow Variant: 51 Data flow: data passed as an argument from one function to another in different source files + * + * */ + +#include "std_testcase.h" + +/* all the sinks are the same, we just want to know where the hit originated if a tool flags one */ + +#ifndef OMITBAD + +void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int_memcpy_51b_badSink(int * data) +{ + { + int source[100] = {0}; /* fill with 0's */ + /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ + memcpy(data, source, 100*sizeof(int)); + printIntLine(data[0]); + free(data); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int_memcpy_51b_goodG2BSink(int * data) +{ + { + int source[100] = {0}; /* fill with 0's */ + /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ + memcpy(data, source, 100*sizeof(int)); + printIntLine(data[0]); + free(data); + } +} + +#endif /* OMITGOOD */ diff --git a/pool/shard000/C/0008696_end_of_solution_writer.c b/pool/shard000/C/0008696_end_of_solution_writer.c new file mode 100644 index 0000000000000000000000000000000000000000..eec9178c5805ddf294479a135815507952a038c3 --- /dev/null +++ b/pool/shard000/C/0008696_end_of_solution_writer.c @@ -0,0 +1,59 @@ +#include "output/latex/tree/end_of_solution_writer.h" +#include "stipulation/stipulation.h" +#include "stipulation/pipe.h" +#include "solving/machinery/slack_length.h" +#include "solving/pipe.h" +#include "debugging/trace.h" + +/* Allocate a STOutputLaTeXTreeEndOfSolutionWriter slice. + * @return index of allocated slice + */ +slice_index alloc_output_latex_tree_end_of_solution_writer_slice(FILE *file) +{ + slice_index result; + + TraceFunctionEntry(__func__); + TraceFunctionParamListEnd(); + + result = alloc_pipe(STOutputLaTeXTreeEndOfSolutionWriter); + SLICE_U(result).writer.file = file; + + TraceFunctionExit(__func__); + TraceFunctionResult("%u",result); + TraceFunctionResultEnd(); + return result; +} + +/* Try to solve in solve_nr_remaining half-moves. + * @param si slice index + * @note assigns solve_result the length of solution found and written, i.e.: + * previous_move_is_illegal the move just played is illegal + * this_move_is_illegal the move being played is illegal + * immobility_on_next_move the moves just played led to an + * unintended immobility on the next move + * <=n+1 length of shortest solution found (n+1 only if in next + * branch) + * n+2 no solution found in this branch + * n+3 no solution found in next branch + * (with n denominating solve_nr_remaining) + */ +void output_latex_tree_end_of_solution_writer_solve(slice_index si) +{ + TraceFunctionEntry(__func__); + TraceFunctionParam("%u",si); + TraceFunctionParamListEnd(); + + pipe_solve_delegate(si); + + TraceValue("%u",slack_length); + TraceValue("%u",solve_result); + TraceValue("%u\n",MOVE_HAS_SOLVED_LENGTH()); + if (move_has_solved()) + { + TraceText("has solved\n"); + fputs("\n",SLICE_U(si).writer.file); + } + + TraceFunctionExit(__func__); + TraceFunctionResultEnd(); +} diff --git a/pool/shard000/C/0008697_1.6-String_Compression.c b/pool/shard000/C/0008697_1.6-String_Compression.c new file mode 100644 index 0000000000000000000000000000000000000000..56e119b600528fc826f85da688ca9c417c25f9f9 --- /dev/null +++ b/pool/shard000/C/0008697_1.6-String_Compression.c @@ -0,0 +1,100 @@ +/************************************************* + * Solution to question 1.6 - String Compression + * + * Status: COMPLETE + * + * Assumptions: + * - Strings are ASCII + * - Strings are alphabetical only + * - Case insensitive +*************************************************/ + +#include +#include +#include +#include + +#include "common.h" + + +static inline size_t ldigits(long number) { + return (size_t) (floor(log10(labs(number))) + 1); +} + + +static long lreverse(long num) { + long rev = 0; + + while (num > 0) { + rev = (rev * 10) + (num % 10); + num /= 10; + } + + return rev; +} + + +int main(int argc, char *argv[]) { + if (argc < 2 || !isstring(argv[1])) { + fprintf(stderr, "Please enter a string on the command line\n"); + return EXIT_FAILURE; + } + + fprintf(stdout, "Compressed string: "); + + struct str s1 = { + .data = argv[1], + .length = strlen(argv[1]) + }; + + // Determine how many chars pairs we'll need + size_t chars = 0, digits = 0, count = 1; + + for (size_t i = 1; i <= s1.length; i++) { + if (s1.data[i] != s1.data[i-1]) { + chars++; + digits += ldigits(count); + count = 1; + } else { + count++; + } + } + + // If new string is not smaller than original + if (chars + digits >= s1.length) { + fprintf(stdout, "%s\n", s1.data); + return EXIT_SUCCESS; + } + + // Allocate space for the pairs in a new string + struct str s2 = { + .data = calloc((chars + digits) + 1, sizeof(char)), + .length = chars + digits + }; + + size_t s = 0; + + // Create new string + for (size_t i = 1; i <= s1.length; i++) { + if (s1.data[i] != s1.data[i-1]) { + s2.data[s] = s1.data[i-1]; // Add the character + size_t reverse = lreverse(count); + + // Save each digit + for (size_t j = 0; j < ldigits(count); j++) { + s++; + s2.data[s] = (reverse % 10) + '0'; + reverse /= 10; + } + + count = 1; + s++; + } else { + count++; + } + } + + fprintf(stdout, "%s\n", s2.data); + free(s2.data); + return EXIT_SUCCESS; +} diff --git a/pool/shard000/C/0008698_nxeb500hmi.c b/pool/shard000/C/0008698_nxeb500hmi.c new file mode 100644 index 0000000000000000000000000000000000000000..7a00a712cfbdc5ec33da42f9861763001bd89ba1 --- /dev/null +++ b/pool/shard000/C/0008698_nxeb500hmi.c @@ -0,0 +1,188 @@ +/* + * arch/arm/mach-netx/nxeb500hmi.c + * + * Copyright (c) 2005 Sascha Hauer , Pengutronix + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "generic.h" +#include "fb.h" + +static struct clcd_panel qvga = { + .mode = { + .name = "QVGA", + .refresh = 60, + .xres = 240, + .yres = 320, + .pixclock = 187617, + .left_margin = 6, + .right_margin = 26, + .upper_margin = 0, + .lower_margin = 6, + .hsync_len = 6, + .vsync_len = 1, + .sync = 0, + .vmode = FB_VMODE_NONINTERLACED, + }, + .width = -1, + .height = -1, + .tim2 = 16, + .cntl = CNTL_LCDTFT | CNTL_BGR, + .bpp = 16, + .grayscale = 0, +}; + +static inline int nxeb500hmi_check(struct clcd_fb *fb, struct fb_var_screeninfo *var) +{ + var->green.length = 5; + var->green.msb_right = 0; + + return clcdfb_check(fb, var); +} + +static int nxeb500hmi_clcd_setup(struct clcd_fb *fb) +{ + unsigned int val; + + fb->fb.var.green.length = 5; + fb->fb.var.green.msb_right = 0; + + /* */ + val = readl(NETX_SYSTEM_IOC_ACCESS_KEY); + writel(val, NETX_SYSTEM_IOC_ACCESS_KEY); + + writel(3, NETX_SYSTEM_IOC_CR); + + /* */ + writel(9, NETX_GPIO_CFG(14)); + + val = readl(NETX_PIO_OUTPIO); + writel(val | 1, NETX_PIO_OUTPIO); + + val = readl(NETX_PIO_OEPIO); + writel(val | 1, NETX_PIO_OEPIO); + return netx_clcd_setup(fb); +} + +static struct clcd_board clcd_data = { + .name = "netX", + .check = nxeb500hmi_check, + .decode = clcdfb_decode, + .enable = netx_clcd_enable, + .setup = nxeb500hmi_clcd_setup, + .mmap = netx_clcd_mmap, + .remove = netx_clcd_remove, +}; + +static struct netxeth_platform_data eth0_platform_data = { + .xcno = 0, +}; + +static struct platform_device netx_eth0_device = { + .name = "netx-eth", + .id = 0, + .num_resources = 0, + .resource = NULL, + .dev = { + .platform_data = ð0_platform_data, + } +}; + +static struct netxeth_platform_data eth1_platform_data = { + .xcno = 1, +}; + +static struct platform_device netx_eth1_device = { + .name = "netx-eth", + .id = 1, + .num_resources = 0, + .resource = NULL, + .dev = { + .platform_data = ð1_platform_data, + } +}; + +static struct resource netx_cf_resources[] = { + [0] = { + .start = 0x20000000, + .end = 0x25ffffff, + .flags = IORESOURCE_MEM | IORESOURCE_MEM_8AND16BIT, + }, +}; + +static struct platform_device netx_cf_device = { + .name = "netx-cf", + .id = 0, + .resource = netx_cf_resources, + .num_resources = ARRAY_SIZE(netx_cf_resources), +}; + +static struct resource netx_uart0_resources[] = { + [0] = { + .start = 0x00100A00, + .end = 0x00100A3F, + .flags = IORESOURCE_MEM, + }, + [1] = { + .start = (NETX_IRQ_UART0), + .end = (NETX_IRQ_UART0), + .flags = IORESOURCE_IRQ, + }, +}; + +static struct platform_device netx_uart0_device = { + .name = "netx-uart", + .id = 0, + .num_resources = ARRAY_SIZE(netx_uart0_resources), + .resource = netx_uart0_resources, +}; + +static struct platform_device *devices[] __initdata = { + &netx_eth0_device, + &netx_eth1_device, + &netx_cf_device, + &netx_uart0_device, +}; + +static void __init nxeb500hmi_init(void) +{ + netx_fb_init(&clcd_data, &qvga); + platform_add_devices(devices, ARRAY_SIZE(devices)); +} + +MACHINE_START(NXEB500HMI, "Hilscher nxeb500hmi") + .atag_offset = 0x100, + .map_io = netx_map_io, + .init_irq = netx_init_irq, + .handle_irq = vic_handle_irq, + .timer = &netx_timer, + .init_machine = nxeb500hmi_init, + .restart = netx_restart, +MACHINE_END diff --git a/pool/shard000/C/0008717_heap-sort.c b/pool/shard000/C/0008717_heap-sort.c new file mode 100644 index 0000000000000000000000000000000000000000..5c7a2151dc61a16a595d6141cc0b699e2b0c4a0f --- /dev/null +++ b/pool/shard000/C/0008717_heap-sort.c @@ -0,0 +1,218 @@ +/* + * ===================================================================================== + * + * Filename: heap-sort.c + * + * Description: + * + * Version: 1.0 + * Created: 12/22/2016 07:35:56 PM + * Revision: none + * Compiler: gcc + * + * Author: YOUR NAME (), + * Organization: + * + * ===================================================================================== + */ +#include +#include +#include +#include +#include + +struct st_list { + int *pList; + int iLen; + int iCmpCount; + int iSwapCount; +}; + +void get_list(struct st_list * pstList, int len) { + if(NULL == pstList) { + return ; + } + bzero(pstList, sizeof(struct st_list)); + pstList -> pList = (int *)malloc(sizeof(int) * len); + if(NULL == pstList -> pList) { + printf("get mamory faild\n"); + return ; + } + pstList -> iLen = len; + srand(374677); + int i = 0; + for(i = 0; i < len; i++) { + pstList -> pList[i] = rand() % (len * 10); + } +} + +void delete_list(struct st_list * pstList) { + if(NULL == pstList) { + return; + } + if(NULL != pstList -> pList) { + free(pstList -> pList); + pstList -> pList = NULL; + } +} + +int check_list(struct st_list * pstList, int(*cmp)(void*, void*)) { + int *list = pstList -> pList; + int len = pstList -> iLen; + int i = 0; + int iRet = 0; + for(i = 0; i < len - 1; i++) { + if(!cmp(&list[i], &list[i + 1])) { + printf("\033[0;31mcompare faild on : [%d] and [%d] as : [%d] and [%d]\033[0m\n", + i, i + 1, list[i], list[i + 1]); + iRet ++; + } + } + + return iRet; +} + +/* **************************** */ + +int cmp_fun(void *a, void *b) { + return *(int*)a <= *(int*)b; +} + +int swap(void *a, void *b, int isize, void *t) { + if(NULL == a || NULL == b || NULL == t || isize <= 0) { + return 0; + } + memcpy(t, a, isize); + memcpy(a, b, isize); + memcpy(b, t, isize); + + return 3; +} + +int adjust_sort(struct st_list * pstList, int iLen, int (*cmp)(void *, void *)) { + if( NULL == pstList || + NULL == pstList -> pList || + NULL == cmp) { + printf("argu is empty\n"); + return -1; + } + int *list = pstList -> pList; + int len = iLen; + int iChild = 0; + int tmp = 0; + int i = 0; + for(i = len / 2; i >= 0; ) { + if((i * 2) < len && cmp(&list[i], &list[i * 2])) { + pstList -> iCmpCount += swap(&list[i], &list[i * 2], sizeof(int), &tmp); + } + if((i * 2 + 1) < len && cmp(&list[i], &list[i * 2 + 1])) { + pstList -> iCmpCount += swap(&list[i], &list[i * 2 + 1], sizeof(int), &tmp); + } + } + + return 0; +} + +int heap_sort(struct st_list *pstList, int (*cmp)(void *, void *)) { + int i = 0; + for(i = 0; i < pstList -> iLen / 2; i++) { + adjust_sort(pstList, pstList -> iLen - i, cmp); + } + + return 0; +} +/* ********************************* */ +//typedef int ElemType; +#define ElemType int + +void HeapAdjust(ElemType H[], int start, int end) +{ + + ElemType temp = H[start]; + + int i = 0; + for(i = 2 * start + 1; i <= end; i *= 2) + { + //因为假设根结点的序号为0而不是1,所以i结点左孩子和右孩子分别为2i+1和2i+2 + if(i < end && H[i] < H[i+1])//左右孩子的比较 + { + ++i;//i为较大的记录的下标 + } + + if(temp > H[i])//左右孩子中获胜者与父亲的比较 + { + break; + } + + //将孩子结点上位,则以孩子结点的位置进行下一轮的筛选 + H[start]= H[i]; + start = i; + } + + H[start]= temp; //插入最开始不和谐的元素 +} + +void HeapSort(ElemType A[], int n) +{ + int i = 0; + //先建立大顶堆 + for(i = n/2; i >= 0; --i) + { + HeapAdjust(A,i,n); + } + ElemType temp; + //进行排序 + for(i = n-1; i > 0; --i) + { + //最后一个元素和第一元素进行交换 + swap(&A[0], &A[i], sizeof(ElemType), &temp); + //ElemType temp = A[i]; + //A[i] = A[0]; + //A[0] = temp; + + //然后将剩下的无序元素继续调整为大顶堆 + HeapAdjust(A,0,i-1); + } +} + +int test_heap_sort(int n) { + struct st_list alist; + get_list(&alist, n); + //for(i = 0; i < n; i++) { + // printf("%2d ", list[i]); + //} + //printf("\n"); +#if 0 + HeapSort(alist.pList, alist.iLen); +#else + heap_sort(&alist, cmp_fun); +#endif + if(check_list(&alist, cmp_fun)) { + printf("\033[0;31msort faild\033[0m\n"); + } + //int i = 0; + //for(i = 0; i < n; i++) { + // printf("%2d ", alist.pList[i]); + //} + //printf("\n"); + double dThro = n * log(n) / log(2); + printf("compare times : [%d], theoretical times [%d], degree = [%lf]\n", + alist.iCmpCount, (int)dThro, alist.iCmpCount / dThro); + printf("sweap times : [%d], theoretical times [%d], degree = [%f]\n", + alist.iSwapCount, (int)dThro, alist.iSwapCount / dThro); + delete_list(&alist); + printf("\n"); + + return 0; +} + +/* ********************************* */ +int main() { + int i = 0; + for(i = 16; i <= 1024 * 1024; i *= 2) { + test_heap_sort(i); + } + + return 0; +} + diff --git a/pool/shard000/C/0008725_timecompare.c b/pool/shard000/C/0008725_timecompare.c new file mode 100644 index 0000000000000000000000000000000000000000..96ff643a5a59bdf1745e776434115cd430fa3935 --- /dev/null +++ b/pool/shard000/C/0008725_timecompare.c @@ -0,0 +1,191 @@ +/* + * Copyright (C) 2009 Intel Corporation. + * Author: Patrick Ohly + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include +#include +#include + +/* + * fixed point arithmetic scale factor for skew + * + * Usually one would measure skew in ppb (parts per billion, 1e9), but + * using a factor of 2 simplifies the math. + */ +#define TIMECOMPARE_SKEW_RESOLUTION (((s64)1)<<30) + +ktime_t timecompare_transform(struct timecompare *sync, + u64 source_tstamp) +{ + u64 nsec; + + nsec = source_tstamp + sync->offset; + nsec += (s64)(source_tstamp - sync->last_update) * sync->skew / + TIMECOMPARE_SKEW_RESOLUTION; + + return ns_to_ktime(nsec); +} +EXPORT_SYMBOL_GPL(timecompare_transform); + +int timecompare_offset(struct timecompare *sync, + s64 *offset, + u64 *source_tstamp) +{ + u64 start_source = 0, end_source = 0; + struct { + s64 offset; + s64 duration_target; + } buffer[10], sample, *samples; + int counter = 0, i; + int used; + int index; + int num_samples = sync->num_samples; + + if (num_samples > sizeof(buffer)/sizeof(buffer[0])) { + samples = kmalloc(sizeof(*samples) * num_samples, GFP_ATOMIC); + if (!samples) { + samples = buffer; + num_samples = sizeof(buffer)/sizeof(buffer[0]); + } + } else { + samples = buffer; + } + + /* run until we have enough valid samples, but do not try forever */ + i = 0; + counter = 0; + while (1) { + u64 ts; + ktime_t start, end; + + start = sync->target(); + ts = timecounter_read(sync->source); + end = sync->target(); + + if (!i) + start_source = ts; + + /* ignore negative durations */ + sample.duration_target = ktime_to_ns(ktime_sub(end, start)); + if (sample.duration_target >= 0) { + /* + * assume symetric delay to and from source: + * average target time corresponds to measured + * source time + */ + sample.offset = + ktime_to_ns(ktime_add(end, start)) / 2 - + ts; + + /* simple insertion sort based on duration */ + index = counter - 1; + while (index >= 0) { + if (samples[index].duration_target < + sample.duration_target) + break; + samples[index + 1] = samples[index]; + index--; + } + samples[index + 1] = sample; + counter++; + } + + i++; + if (counter >= num_samples || i >= 100000) { + end_source = ts; + break; + } + } + + *source_tstamp = (end_source + start_source) / 2; + + /* remove outliers by only using 75% of the samples */ + used = counter * 3 / 4; + if (!used) + used = counter; + if (used) { + /* calculate average */ + s64 off = 0; + for (index = 0; index < used; index++) + off += samples[index].offset; + *offset = div_s64(off, used); + } + + if (samples && samples != buffer) + kfree(samples); + + return used; +} +EXPORT_SYMBOL_GPL(timecompare_offset); + +void __timecompare_update(struct timecompare *sync, + u64 source_tstamp) +{ + s64 offset; + u64 average_time; + + if (!timecompare_offset(sync, &offset, &average_time)) + return; + + if (!sync->last_update) { + sync->last_update = average_time; + sync->offset = offset; + sync->skew = 0; + } else { + s64 delta_nsec = average_time - sync->last_update; + + /* avoid division by negative or small deltas */ + if (delta_nsec >= 10000) { + s64 delta_offset_nsec = offset - sync->offset; + s64 skew; /* delta_offset_nsec * + TIMECOMPARE_SKEW_RESOLUTION / + delta_nsec */ + u64 divisor; + + /* div_s64() is limited to 32 bit divisor */ + skew = delta_offset_nsec * TIMECOMPARE_SKEW_RESOLUTION; + divisor = delta_nsec; + while (unlikely(divisor >= ((s64)1) << 32)) { + /* divide both by 2; beware, right shift + of negative value has undefined + behavior and can only be used for + the positive divisor */ + skew = div_s64(skew, 2); + divisor >>= 1; + } + skew = div_s64(skew, divisor); + + /* + * Calculate new overall skew as 4/16 the + * old value and 12/16 the new one. This is + * a rather arbitrary tradeoff between + * only using the latest measurement (0/16 and + * 16/16) and even more weight on past measurements. + */ +#define TIMECOMPARE_NEW_SKEW_PER_16 12 + sync->skew = + div_s64((16 - TIMECOMPARE_NEW_SKEW_PER_16) * + sync->skew + + TIMECOMPARE_NEW_SKEW_PER_16 * skew, + 16); + sync->last_update = average_time; + sync->offset = offset; + } + } +} +EXPORT_SYMBOL_GPL(__timecompare_update); diff --git a/pool/shard000/C/0008729_dot.c b/pool/shard000/C/0008729_dot.c new file mode 100644 index 0000000000000000000000000000000000000000..808da43ba3bc4c921275417c532fd43f68a26e59 --- /dev/null +++ b/pool/shard000/C/0008729_dot.c @@ -0,0 +1,245 @@ +/* +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% % +% % +% % +% DDDD OOO TTTTT % +% D D O O T % +% D D O O T % +% D D O O T % +% DDDD OOO T % +% % +% % +% Read/Write Graphviz DOT Format % +% % +% Software Design % +% Cristy % +% July 1992 % +% % +% % +% Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization % +% dedicated to making software imaging solutions freely available. % +% % +% You may not use this file except in compliance with the License. You may % +% obtain a copy of the License at % +% % +% http://www.imagemagick.org/script/license.php % +% % +% Unless required by applicable law or agreed to in writing, software % +% distributed under the License is distributed on an "AS IS" BASIS, % +% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % +% See the License for the specific language governing permissions and % +% limitations under the License. % +% % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% +% +*/ + +/* + Include declarations. +*/ +#include "magick/studio.h" +#include "magick/blob.h" +#include "magick/blob-private.h" +#include "magick/client.h" +#include "magick/constitute.h" +#include "magick/exception.h" +#include "magick/exception-private.h" +#include "magick/image.h" +#include "magick/image-private.h" +#include "magick/list.h" +#include "magick/magick.h" +#include "magick/memory_.h" +#include "magick/monitor.h" +#include "magick/monitor-private.h" +#include "magick/option.h" +#include "magick/pixel-accessor.h" +#include "magick/quantum-private.h" +#include "magick/resource_.h" +#include "magick/static.h" +#include "magick/string_.h" +#include "magick/module.h" +#include "magick/utility.h" +#include "magick/xwindow-private.h" +#if defined(MAGICKCORE_GVC_DELEGATE) +#undef HAVE_CONFIG_H +#include +static GVC_t + *graphic_context; +#endif + +#if defined(MAGICKCORE_GVC_DELEGATE) +/* +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% % +% % +% % +% R e a d D O T I m a g e % +% % +% % +% % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% +% ReadDOTImage() reads a Graphviz image file and returns it. It allocates +% the memory necessary for the new Image structure and returns a pointer to +% the new image. +% +% The format of the ReadDOTImage method is: +% +% Image *ReadDOTImage(const ImageInfo *image_info,ExceptionInfo *exception) +% +% A description of each parameter follows: +% +% o image_info: the image info. +% +% o exception: return any errors or warnings in this structure. +% +*/ +static Image *ReadDOTImage(const ImageInfo *image_info,ExceptionInfo *exception) +{ + char + command[MaxTextExtent]; + + const char + *option; + + graph_t + *graph; + + Image + *image; + + ImageInfo + *read_info; + + MagickBooleanType + status; + + /* + Open image file. + */ + assert(image_info != (const ImageInfo *) NULL); + assert(image_info->signature == MagickSignature); + if (image_info->debug != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", + image_info->filename); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickSignature); + image=AcquireImage(image_info); + status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); + if (status == MagickFalse) + return((Image *) NULL); + read_info=CloneImageInfo(image_info); + SetImageInfoBlob(read_info,(void *) NULL,0); + (void) CopyMagickString(read_info->magick,"SVG",MaxTextExtent); + (void) AcquireUniqueFilename(read_info->filename); + (void) FormatLocaleString(command,MaxTextExtent,"-Tsvg -o%s %s", + read_info->filename,image_info->filename); +#if !defined(WITH_CGRAPH) + graph=agread(GetBlobFileHandle(image)); +#else + graph=agread(GetBlobFileHandle(image),(Agdisc_t *) NULL); +#endif + if (graph == (graph_t *) NULL) + { + (void) RelinquishUniqueFileResource(read_info->filename); + return ((Image *) NULL); + } + option=GetImageOption(image_info,"dot:layout-engine"); + if (option == (const char *) NULL) + gvLayout(graphic_context,graph,(char *) "dot"); + else + gvLayout(graphic_context,graph,(char *) option); + gvRenderFilename(graphic_context,graph,(char *) "svg",read_info->filename); + gvFreeLayout(graphic_context,graph); + agclose(graph); + /* + Read SVG graph. + */ + image=ReadImage(read_info,exception); + (void) RelinquishUniqueFileResource(read_info->filename); + read_info=DestroyImageInfo(read_info); + if (image == (Image *) NULL) + return((Image *) NULL); + return(GetFirstImageInList(image)); +} +#endif + +/* +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% % +% % +% % +% R e g i s t e r D O T I m a g e % +% % +% % +% % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% +% RegisterDOTImage() adds attributes for the Display Postscript image +% format to the list of supported formats. The attributes include the image +% format tag, a method to read and/or write the format, whether the format +% supports the saving of more than one frame to the same file or blob, +% whether the format supports native in-memory I/O, and a brief +% description of the format. +% +% The format of the RegisterDOTImage method is: +% +% size_t RegisterDOTImage(void) +% +*/ +ModuleExport size_t RegisterDOTImage(void) +{ + MagickInfo + *entry; + + entry=SetMagickInfo("DOT"); +#if defined(MAGICKCORE_GVC_DELEGATE) + entry->decoder=(DecodeImageHandler *) ReadDOTImage; +#endif + entry->blob_support=MagickFalse; + entry->description=ConstantString("Graphviz"); + entry->module=ConstantString("DOT"); + (void) RegisterMagickInfo(entry); + entry=SetMagickInfo("GV"); +#if defined(MAGICKCORE_GVC_DELEGATE) + entry->decoder=(DecodeImageHandler *) ReadDOTImage; +#endif + entry->blob_support=MagickFalse; + entry->description=ConstantString("Graphviz"); + entry->module=ConstantString("DOT"); + (void) RegisterMagickInfo(entry); +#if defined(MAGICKCORE_GVC_DELEGATE) + graphic_context=gvContext(); +#endif + return(MagickImageCoderSignature); +} + +/* +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% % +% % +% % +% U n r e g i s t e r D O T I m a g e % +% % +% % +% % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% +% UnregisterDOTImage() removes format registrations made by the +% DOT module from the list of supported formats. +% +% The format of the UnregisterDOTImage method is: +% +% UnregisterDOTImage(void) +% +*/ +ModuleExport void UnregisterDOTImage(void) +{ + (void) UnregisterMagickInfo("GV"); + (void) UnregisterMagickInfo("DOT"); +#if defined(MAGICKCORE_GVC_DELEGATE) + gvFreeContext(graphic_context); +#endif +} diff --git a/pool/shard000/C/0008746_CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_loop_66b.c b/pool/shard000/C/0008746_CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_loop_66b.c new file mode 100644 index 0000000000000000000000000000000000000000..b6027fc41c0b48ab66e4e90a6a258a94c4db273a --- /dev/null +++ b/pool/shard000/C/0008746_CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_loop_66b.c @@ -0,0 +1,63 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_loop_66b.c +Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE805.label.xml +Template File: sources-sink-66b.tmpl.c +*/ +/* + * @description + * CWE: 122 Heap Based Buffer Overflow + * BadSource: Allocate using malloc() and set data pointer to a small buffer + * GoodSource: Allocate using malloc() and set data pointer to a large buffer + * Sinks: loop + * BadSink : Copy int64_t array to data using a loop + * Flow Variant: 66 Data flow: data passed in an array from one function to another in different source files + * + * */ + +#include "std_testcase.h" + +#ifndef OMITBAD + +void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_loop_66b_badSink(int64_t * dataArray[]) +{ + /* copy data out of dataArray */ + int64_t * data = dataArray[2]; + { + int64_t source[100] = {0}; /* fill with 0's */ + { + size_t i; + /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ + for (i = 0; i < 100; i++) + { + data[i] = source[i]; + } + printLongLongLine(data[0]); + free(data); + } + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_loop_66b_goodG2BSink(int64_t * dataArray[]) +{ + int64_t * data = dataArray[2]; + { + int64_t source[100] = {0}; /* fill with 0's */ + { + size_t i; + /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ + for (i = 0; i < 100; i++) + { + data[i] = source[i]; + } + printLongLongLine(data[0]); + free(data); + } + } +} + +#endif /* OMITGOOD */ diff --git a/pool/shard000/C/0008767_test.c b/pool/shard000/C/0008767_test.c new file mode 100644 index 0000000000000000000000000000000000000000..13a82d6290cd9bcc9da2780aa52665c6c9a6c74f --- /dev/null +++ b/pool/shard000/C/0008767_test.c @@ -0,0 +1,215 @@ +// +// $Id: test.c 1682 2009-02-05 01:07:09Z shodan $ +// + +// +// Copyright (c) 2008, Andrew Aksyonoff. All rights reserved. +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU Library General Public License. You should +// have received a copy of the LGPL license along with this program; if you +// did not, you can find it at http://www.gnu.org/ +// + +#include +#include +#include + +#if _WIN32 +#include +#endif + +#include "sphinxclient.h" + +void die ( const char * template, ... ) +{ + va_list ap; + va_start ( ap, template ); + printf ( "FATAL: " ); + vprintf ( template, ap ); + printf ( "\n" ); + va_end ( ap ); + exit ( 1 ); +} + + +void net_init () +{ +#if _WIN32 + // init WSA on Windows + WSADATA wsa_data; + int wsa_startup_err; + + wsa_startup_err = WSAStartup ( WINSOCK_VERSION, &wsa_data ); + if ( wsa_startup_err ) + die ( "failed to initialize WinSock2: error %d", wsa_startup_err ); +#endif +} + + +void test_query ( sphinx_client * client, sphinx_bool test_extras ) +{ + sphinx_result * res; + const char *query, *index; + int i, j, k; + unsigned int * mva; + const char * field_names[2]; + int field_weights[2]; + + sphinx_uint64_t override_docid = 4; + unsigned int override_value = 456; + + query = "test"; + index = "test1"; + + field_names[0] = "title"; + field_names[1] = "content"; + field_weights[0] = 100; + field_weights[1] = 1; + sphinx_set_field_weights ( client, 2, field_names, field_weights ); + field_weights[0] = 1; + field_weights[1] = 1; + + if ( test_extras ) + { + sphinx_add_override ( client, "group_id", &override_docid, 1, &override_value ); + sphinx_set_select ( client, "*, group_id*1000+@id*10 AS q" ); + } + + res = sphinx_query ( client, query, index, NULL ); + if ( !res ) + die ( "query failed: %s", sphinx_error(client) ); + + printf ( "Query '%s' retrieved %d of %d matches in %d.%03d sec.\n", + query, res->total, res->total_found, res->time_msec/1000, res->time_msec%1000 ); + printf ( "Query stats:\n" ); + for ( i=0; inum_words; i++ ) + printf ( "\t'%s' found %d times in %d documents\n", + res->words[i].word, res->words[i].hits, res->words[i].docs ); + + printf ( "\nMatches:\n" ); + for ( i=0; inum_matches; i++ ) + { + printf ( "%d. doc_id=%d, weight=%d", 1+i, + (int)sphinx_get_id ( res, i ), sphinx_get_weight ( res, i ) ); + + for ( j=0; jnum_attrs; j++ ) + { + printf ( ", %s=", res->attr_names[j] ); + switch ( res->attr_types[j] ) + { + case SPH_ATTR_MULTI | SPH_ATTR_INTEGER: + mva = sphinx_get_mva ( res, i, j ); + printf ( "(" ); + for ( k=0; k<(int)mva[0]; k++ ) + printf ( k ? ",%u" : "%u", mva[1+k] ); + printf ( ")" ); + break; + + case SPH_ATTR_FLOAT: printf ( "%f", sphinx_get_float ( res, i, j ) ); break; + default: printf ( "%u", (unsigned int)sphinx_get_int ( res, i, j ) ); break; + } + } + + printf ( "\n" ); + } + printf ( "\n" ); +} + + +void test_excerpt ( sphinx_client * client ) +{ + const char * docs[] = + { + "this is my test text to be highlighted, and for the sake of the testing we need to pump its length somewhat", + "another test text to be highlighted, below limit", + "test number three, without phrase match", + "final test, not only without phrase match, but also above limit and with swapped phrase text test as well" + }; + const int ndocs = sizeof(docs)/sizeof(docs[0]); + const char * words = "test text"; + const char * index = "test1"; + sphinx_excerpt_options opts; + char ** res; + int i, j; + + sphinx_init_excerpt_options ( &opts ); + opts.limit = 60; + opts.around = 3; + + for ( j=0; j<2; j++ ) + { + opts.exact_phrase = j; + printf ( "exact_phrase=%d\n", j ); + + res = sphinx_build_excerpts ( client, ndocs, docs, index, words, &opts ); + if ( !res ) + die ( "query failed: %s", sphinx_error(client) ); + + for ( i=0; i + * + * Based on aesni-intel_glue.c by: + * Copyright (C) 2008, Intel Corp. + * Author: Huang Ying + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +int ablk_set_key(struct crypto_ablkcipher *tfm, const u8 *key, + unsigned int key_len) +{ + struct async_helper_ctx *ctx = crypto_ablkcipher_ctx(tfm); + struct crypto_ablkcipher *child = &ctx->cryptd_tfm->base; + int err; + + crypto_ablkcipher_clear_flags(child, CRYPTO_TFM_REQ_MASK); + crypto_ablkcipher_set_flags(child, crypto_ablkcipher_get_flags(tfm) + & CRYPTO_TFM_REQ_MASK); + err = crypto_ablkcipher_setkey(child, key, key_len); + crypto_ablkcipher_set_flags(tfm, crypto_ablkcipher_get_flags(child) + & CRYPTO_TFM_RES_MASK); + return err; +} +EXPORT_SYMBOL_GPL(ablk_set_key); + +int __ablk_encrypt(struct ablkcipher_request *req) +{ + struct crypto_ablkcipher *tfm = crypto_ablkcipher_reqtfm(req); + struct async_helper_ctx *ctx = crypto_ablkcipher_ctx(tfm); + struct blkcipher_desc desc; + + desc.tfm = cryptd_ablkcipher_child(ctx->cryptd_tfm); + desc.info = req->info; + desc.flags = 0; + + return crypto_blkcipher_crt(desc.tfm)->encrypt( + &desc, req->dst, req->src, req->nbytes); +} +EXPORT_SYMBOL_GPL(__ablk_encrypt); + +int ablk_encrypt(struct ablkcipher_request *req) +{ + struct crypto_ablkcipher *tfm = crypto_ablkcipher_reqtfm(req); + struct async_helper_ctx *ctx = crypto_ablkcipher_ctx(tfm); + + if (!may_use_simd()) { + struct ablkcipher_request *cryptd_req = + ablkcipher_request_ctx(req); + + memcpy(cryptd_req, req, sizeof(*req)); + ablkcipher_request_set_tfm(cryptd_req, &ctx->cryptd_tfm->base); + + return crypto_ablkcipher_encrypt(cryptd_req); + } else { + return __ablk_encrypt(req); + } +} +EXPORT_SYMBOL_GPL(ablk_encrypt); + +int ablk_decrypt(struct ablkcipher_request *req) +{ + struct crypto_ablkcipher *tfm = crypto_ablkcipher_reqtfm(req); + struct async_helper_ctx *ctx = crypto_ablkcipher_ctx(tfm); + + if (!may_use_simd()) { + struct ablkcipher_request *cryptd_req = + ablkcipher_request_ctx(req); + + memcpy(cryptd_req, req, sizeof(*req)); + ablkcipher_request_set_tfm(cryptd_req, &ctx->cryptd_tfm->base); + + return crypto_ablkcipher_decrypt(cryptd_req); + } else { + struct blkcipher_desc desc; + + desc.tfm = cryptd_ablkcipher_child(ctx->cryptd_tfm); + desc.info = req->info; + desc.flags = 0; + + return crypto_blkcipher_crt(desc.tfm)->decrypt( + &desc, req->dst, req->src, req->nbytes); + } +} +EXPORT_SYMBOL_GPL(ablk_decrypt); + +void ablk_exit(struct crypto_tfm *tfm) +{ + struct async_helper_ctx *ctx = crypto_tfm_ctx(tfm); + + cryptd_free_ablkcipher(ctx->cryptd_tfm); +} +EXPORT_SYMBOL_GPL(ablk_exit); + +int ablk_init_common(struct crypto_tfm *tfm, const char *drv_name) +{ + struct async_helper_ctx *ctx = crypto_tfm_ctx(tfm); + struct cryptd_ablkcipher *cryptd_tfm; + + cryptd_tfm = cryptd_alloc_ablkcipher(drv_name, 0, 0); + if (IS_ERR(cryptd_tfm)) + return PTR_ERR(cryptd_tfm); + + ctx->cryptd_tfm = cryptd_tfm; + tfm->crt_ablkcipher.reqsize = sizeof(struct ablkcipher_request) + + crypto_ablkcipher_reqsize(&cryptd_tfm->base); + + return 0; +} +EXPORT_SYMBOL_GPL(ablk_init_common); + +int ablk_init(struct crypto_tfm *tfm) +{ + char drv_name[CRYPTO_MAX_ALG_NAME]; + + snprintf(drv_name, sizeof(drv_name), "__driver-%s", + crypto_tfm_alg_driver_name(tfm)); + + return ablk_init_common(tfm, drv_name); +} +EXPORT_SYMBOL_GPL(ablk_init); + +MODULE_LICENSE("GPL"); diff --git a/pool/shard000/C/0008799_aotrigger.c b/pool/shard000/C/0008799_aotrigger.c new file mode 100644 index 0000000000000000000000000000000000000000..b568fc5c9e3fd3c91238ce17e48d588398a33736 --- /dev/null +++ b/pool/shard000/C/0008799_aotrigger.c @@ -0,0 +1,94 @@ +/* +gcc -DNIDAQ_MAJOR=254 -o aotrigger aotrigger.c -lm +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "nidaq.h" + + +#define MAXPOINTS 600 +#define MAXBUFFERS 40 +#define UPDATERATE 100000 +#define PERIOD 200 + + +void AO_add_channel( int fd, int channel, int bipolar, + int reglitch, int extref, int groundref ) +{ + unsigned int u = 0; + + if ( bipolar ) + u |= 0x0001; + + if ( reglitch ) + u |= 0x0002; + + if ( extref ) + u |= 0x0004; + + if ( groundref ) + u |= 0x0008; + + channel &= 0x1; + u |= channel << 8; + + fprintf( stderr, "added channel %d\n", channel ); + + ioctl( fd, NIDAQAOADDCHANNEL, u ); +} + + +void init_sine( signed short buf[], int n ) +{ + int k; + + for ( k=0; k= n) { + int orig_len = strlen(dest); + int n2=0; + + n2 = n-1; + buf = strncat(dest, src, n2); + dest[orig_len+n-1] = '\0'; + } + else { + buf = strncat(dest, src, n); + } + + + return buf; +} + +char *sz_strncpy(char *dest, const char *src, size_t n) +{ + char *buf=NULL; + + if (n < 0) { + warn("n is %d. setting it 0", (int)n); + n = 0; + } + + buf = strncpy(dest, src, n); + dest[n-1] = '\0'; + + return buf; +} + +int sz_snprintf(char *str, size_t size, const char *format, ...) +{ + int rv=0; + va_list args; + + if (size < 0) { + warn("size is %d. setting it 0", (int)size); + size = 0; + } + + va_start(args, format); + rv = vsnprintf(str, size, format, args); + va_end(args); + + str[size-1] = '\0'; + + return rv; +} diff --git a/pool/shard000/C/0008812_bigdict.c b/pool/shard000/C/0008812_bigdict.c new file mode 100644 index 0000000000000000000000000000000000000000..fb0892586908601d34c74b32e13f587e1ac5e5dc --- /dev/null +++ b/pool/shard000/C/0008812_bigdict.c @@ -0,0 +1,128 @@ +/* + * Copyright (c) Yann Collet, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +#include +#include +#include +#include +#include +#include "datagen.h" +#include "mem.h" +#define ZSTD_STATIC_LINKING_ONLY +#include "zstd.h" + +static int +compress(ZSTD_CCtx* cctx, ZSTD_DCtx* dctx, + void* dst, size_t dstCapacity, + void const* src, size_t srcSize, + void* roundtrip, ZSTD_EndDirective end) +{ + ZSTD_inBuffer in = {src, srcSize, 0}; + ZSTD_outBuffer out = {dst, dstCapacity, 0}; + int ended = 0; + + while (!ended && (in.pos < in.size || out.pos > 0)) { + size_t rc; + out.pos = 0; + rc = ZSTD_compressStream2(cctx, &out, &in, end); + if (ZSTD_isError(rc)) + return 1; + if (end == ZSTD_e_end && rc == 0) + ended = 1; + { + ZSTD_inBuffer rtIn = {dst, out.pos, 0}; + ZSTD_outBuffer rtOut = {roundtrip, srcSize, 0}; + rc = 1; + while (rtIn.pos < rtIn.size || rtOut.pos > 0) { + rtOut.pos = 0; + rc = ZSTD_decompressStream(dctx, &rtOut, &rtIn); + if (ZSTD_isError(rc)) { + fprintf(stderr, "Decompression error: %s\n", ZSTD_getErrorName(rc)); + return 1; + } + if (rc == 0) + break; + } + if (ended && rc != 0) { + fprintf(stderr, "Frame not finished!\n"); + return 1; + } + } + } + + return 0; +} + +int main(int argc, const char** argv) +{ + ZSTD_CCtx* cctx = ZSTD_createCCtx(); + ZSTD_DCtx* dctx = ZSTD_createDCtx(); + const size_t dataSize = (size_t)1 << 30; + const size_t outSize = ZSTD_compressBound(dataSize); + const size_t bufferSize = (size_t)1 << 31; + char* buffer = (char*)malloc(bufferSize); + void* out = malloc(outSize); + void* roundtrip = malloc(dataSize); + (void)argc; + (void)argv; + + if (!buffer || !out || !roundtrip || !cctx || !dctx) { + fprintf(stderr, "Allocation failure\n"); + return 1; + } + + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_windowLog, 31))) + return 1; + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_nbWorkers, 1))) + return 1; + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_overlapLog, 9))) + return 1; + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_checksumFlag, 1))) + return 1; + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_strategy, ZSTD_btopt))) + return 1; + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_targetLength, 7))) + return 1; + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_minMatch, 7))) + return 1; + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_searchLog, 1))) + return 1; + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_hashLog, 10))) + return 1; + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_chainLog, 10))) + return 1; + + if (ZSTD_isError(ZSTD_DCtx_setParameter(dctx, ZSTD_d_windowLogMax, 31))) + return 1; + + RDG_genBuffer(buffer, bufferSize, 1.0, 0.0, 0xbeefcafe); + + /* Compress 30 GB */ + { + int i; + for (i = 0; i < 10; ++i) { + fprintf(stderr, "Compressing 1 GB\n"); + if (compress(cctx, dctx, out, outSize, buffer, dataSize, roundtrip, ZSTD_e_continue)) + return 1; + } + } + fprintf(stderr, "Compressing 1 GB\n"); + if (compress(cctx, dctx, out, outSize, buffer, dataSize, roundtrip, ZSTD_e_end)) + return 1; + + fprintf(stderr, "Success!\n"); + + free(roundtrip); + free(out); + free(buffer); + ZSTD_freeDCtx(dctx); + ZSTD_freeCCtx(cctx); + return 0; +} diff --git a/pool/shard000/C/0008813_xsiget.c b/pool/shard000/C/0008813_xsiget.c new file mode 100644 index 0000000000000000000000000000000000000000..94cccee6c31ae3a9a6451625e2cd7f901d1617be --- /dev/null +++ b/pool/shard000/C/0008813_xsiget.c @@ -0,0 +1,60 @@ +#include "../apue.h" + +#define USE_EXCL +#define USE_FTOK + +#include +#include +#include + +int main (int argc, char *argv[]) +{ + if (argc < 3) + { + printf ("Usage: xsiget type projid\n"); + return -1; + } + + char const* type = argv[1]; + int id = atoi (argv[2]); + + key_t key = IPC_PRIVATE; +#ifdef USE_FTOK + key = ftok ("./xsiget.c", id); +#endif + + int flag = IPC_CREAT; +#ifdef USE_EXCL + flag |= IPC_EXCL; +#endif + + if (strcasecmp (type, "msg") == 0) + { + int ret = msgget (key, flag); + if (ret < 0) + err_sys ("msgget failed"); + + printf ("create msgqueue %d with key 0x%08x ok\n", ret, key); + } + else if (strcasecmp (type, "sem") == 0) + { + int ret = semget (key, 1, flag); + if (ret < 0) + err_sys ("semget failed"); + + printf ("create semphore %d with key 0x%08x ok\n", ret, key); + } + else if (strcasecmp (type, "shm") == 0) + { + int ret = shmget (key, 1024, flag); + if (ret < 0) + err_sys ("shmget failed"); + + printf ("create share memory %d with key 0x%08x ok\n", ret, key); + } + else + printf ("unknown type %s\n", type); + + //sleep (60); + return 0; +} diff --git a/pool/shard000/C/0008818_device.c b/pool/shard000/C/0008818_device.c new file mode 100644 index 0000000000000000000000000000000000000000..ec04477dcdc432a0b8b59011b6ae07c3035f2457 --- /dev/null +++ b/pool/shard000/C/0008818_device.c @@ -0,0 +1,157 @@ + + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include + +#define GPIO3_INTNUM 3 +#define UART_INTNUM 4 +#define GMAC_INTNUM 5 + +static const signed char gpio3_irq_mappings[] = { + S6_INTC_GPIO(3), + -1 +}; + +static const signed char uart_irq_mappings[] = { + S6_INTC_UART(0), + S6_INTC_UART(1), + -1, +}; + +static const signed char gmac_irq_mappings[] = { + S6_INTC_GMAC_STAT, + S6_INTC_GMAC_ERR, + S6_INTC_DMA_HOSTTERMCNT(0), + S6_INTC_DMA_HOSTTERMCNT(1), + -1 +}; + +const signed char *platform_irq_mappings[NR_IRQS] = { + [GPIO3_INTNUM] = gpio3_irq_mappings, + [UART_INTNUM] = uart_irq_mappings, + [GMAC_INTNUM] = gmac_irq_mappings, +}; + +static struct plat_serial8250_port serial_platform_data[] = { + { + .membase = (void *)S6_REG_UART + 0x0000, + .mapbase = S6_REG_UART + 0x0000, + .irq = UART_INTNUM, + .uartclk = S6_SCLK, + .regshift = 2, + .iotype = SERIAL_IO_MEM, + .flags = ASYNC_BOOT_AUTOCONF | ASYNC_SKIP_TEST, + }, + { + .membase = (void *)S6_REG_UART + 0x1000, + .mapbase = S6_REG_UART + 0x1000, + .irq = UART_INTNUM, + .uartclk = S6_SCLK, + .regshift = 2, + .iotype = SERIAL_IO_MEM, + .flags = ASYNC_BOOT_AUTOCONF | ASYNC_SKIP_TEST, + }, + { }, +}; + +static struct resource s6_gmac_resource[] = { + { + .name = "mem", + .start = (resource_size_t)S6_REG_GMAC, + .end = (resource_size_t)S6_REG_GMAC + 0x10000 - 1, + .flags = IORESOURCE_MEM, + }, + { + .name = "dma", + .start = (resource_size_t) + DMA_CHNL(S6_REG_HIFDMA, S6_HIFDMA_GMACTX), + .end = (resource_size_t) + DMA_CHNL(S6_REG_HIFDMA, S6_HIFDMA_GMACTX) + 0x100 - 1, + .flags = IORESOURCE_DMA, + }, + { + .name = "dma", + .start = (resource_size_t) + DMA_CHNL(S6_REG_HIFDMA, S6_HIFDMA_GMACRX), + .end = (resource_size_t) + DMA_CHNL(S6_REG_HIFDMA, S6_HIFDMA_GMACRX) + 0x100 - 1, + .flags = IORESOURCE_DMA, + }, + { + .name = "io", + .start = (resource_size_t)S6_MEM_GMAC, + .end = (resource_size_t)S6_MEM_GMAC + 0x2000000 - 1, + .flags = IORESOURCE_IO, + }, + { + .name = "irq", + .start = (resource_size_t)GMAC_INTNUM, + .flags = IORESOURCE_IRQ, + }, + { + .name = "irq", + .start = (resource_size_t)PHY_POLL, + .flags = IORESOURCE_IRQ, + }, +}; + +static int __init prepare_phy_irq(int pin) +{ + int irq; + if (gpio_request(pin, "s6gmac_phy") < 0) + goto fail; + if (gpio_direction_input(pin) < 0) + goto free; + irq = gpio_to_irq(pin); + if (irq < 0) + goto free; + if (set_irq_type(irq, IRQ_TYPE_LEVEL_LOW) < 0) + goto free; + return irq; +free: + gpio_free(pin); +fail: + return PHY_POLL; +} + +static struct platform_device platform_devices[] = { + { + .name = "serial8250", + .id = PLAT8250_DEV_PLATFORM, + .dev = { + .platform_data = serial_platform_data, + }, + }, + { + .name = "s6gmac", + .id = 0, + .resource = s6_gmac_resource, + .num_resources = ARRAY_SIZE(s6_gmac_resource), + }, + { + I2C_BOARD_INFO("m41t62", S6I2C_ADDR_M41T62), + }, +}; + +static int __init device_init(void) +{ + int i; + + s6_gmac_resource[5].start = prepare_phy_irq(GPIO_PHY_IRQ); + + for (i = 0; i < ARRAY_SIZE(platform_devices); i++) + platform_device_register(&platform_devices[i]); + return 0; +} +arch_initcall_sync(device_init); diff --git a/pool/shard000/C/0008825_autotools-notebook-tab.c b/pool/shard000/C/0008825_autotools-notebook-tab.c new file mode 100644 index 0000000000000000000000000000000000000000..978502ae3ad6fb2ad6c37c5b0bfdcfdd744f3b46 --- /dev/null +++ b/pool/shard000/C/0008825_autotools-notebook-tab.c @@ -0,0 +1,133 @@ +/* + * Copyright (C) 2010 - Jeff Johnston + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#include "autotools-notebook-tab.h" +#include + +static void autotools_notebook_tab_class_init (AutotoolsNotebookTabClass *klass); +static void autotools_notebook_tab_init (AutotoolsNotebookTab *notebook_tab); +static void autotools_notebook_tab_finalize (AutotoolsNotebookTab *notebook_tab); + +static void close_action (AutotoolsNotebookTab *notebook_tab); + +#define AUTOTOOLS_NOTEBOOK_TAB_GET_PRIVATE(obj) \ + (G_TYPE_INSTANCE_GET_PRIVATE ((obj), AUTOTOOLS_NOTEBOOK_TAB_TYPE, AutotoolsNotebookTabPrivate)) + +typedef struct _AutotoolsNotebookTabPrivate AutotoolsNotebookTabPrivate; + +struct _AutotoolsNotebookTabPrivate +{ + GtkWidget *notebook_page; + GtkWidget *notebook; +}; + +enum +{ + CLOSE, + LAST_SIGNAL +}; + +static guint autotools_notebook_tab_signals[LAST_SIGNAL] = { 0 }; + +G_DEFINE_TYPE (AutotoolsNotebookTab, autotools_notebook_tab, GTK_TYPE_HBOX) + +static void +autotools_notebook_tab_class_init (AutotoolsNotebookTabClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + + autotools_notebook_tab_signals[CLOSE] = + g_signal_new ("close", + G_TYPE_FROM_CLASS (klass), + G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS, + G_STRUCT_OFFSET (AutotoolsNotebookTabClass, close), + NULL, NULL, + g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); + + gobject_class->finalize = (GObjectFinalizeFunc) autotools_notebook_tab_finalize; + + g_type_class_add_private (klass, sizeof (AutotoolsNotebookTabPrivate)); +} + +static void +autotools_notebook_tab_init (AutotoolsNotebookTab *notebook_tab) +{ + gtk_box_set_homogeneous (GTK_BOX (notebook_tab), FALSE); + gtk_box_set_spacing (GTK_BOX (notebook_tab), 0); +} + +static void +autotools_notebook_tab_finalize (AutotoolsNotebookTab *notebook_tab) +{ + G_OBJECT_CLASS (autotools_notebook_tab_parent_class)->finalize ( G_OBJECT (notebook_tab)); +} + +GtkWidget* +autotools_notebook_tab_new (GtkWidget *notebook, + const gchar *label) +{ + AutotoolsNotebookTabPrivate *priv; + GtkWidget *notebook_tab; + GtkWidget *text; + GtkWidget *button; + GtkWidget *image; + + notebook_tab = g_object_new (autotools_notebook_tab_get_type (), NULL); + priv = AUTOTOOLS_NOTEBOOK_TAB_GET_PRIVATE (notebook_tab); + priv->notebook = notebook; + + text = gtk_label_new (label); + + button = gtk_button_new (); + + gtk_button_set_relief (GTK_BUTTON (button), GTK_RELIEF_NONE); + gtk_button_set_focus_on_click (GTK_BUTTON (button), FALSE); + image = gtk_image_new_from_stock (GTK_STOCK_CLOSE, GTK_ICON_SIZE_MENU); + gtk_container_add (GTK_CONTAINER (button), image); + codeslayer_utils_style_close_button (button); + + g_signal_connect_swapped (G_OBJECT (button), "clicked", + G_CALLBACK (close_action), notebook_tab); + + gtk_box_pack_start (GTK_BOX (notebook_tab), text, TRUE, TRUE, 1); + + gtk_box_pack_start (GTK_BOX (notebook_tab), button, FALSE, FALSE, 1); + + return notebook_tab; +} + +static void +close_action (AutotoolsNotebookTab *notebook_tab) +{ + g_signal_emit_by_name ((gpointer) notebook_tab, "close"); +} + +GtkWidget* +autotools_notebook_tab_get_notebook_page (AutotoolsNotebookTab *notebook_tab) +{ + return AUTOTOOLS_NOTEBOOK_TAB_GET_PRIVATE (notebook_tab)->notebook_page; +} + +void +autotools_notebook_tab_set_notebook_page (AutotoolsNotebookTab *notebook_tab, + GtkWidget *notebook_page) +{ + AutotoolsNotebookTabPrivate *priv; + priv = AUTOTOOLS_NOTEBOOK_TAB_GET_PRIVATE (notebook_tab); + priv->notebook_page = notebook_page; +} diff --git a/pool/shard000/C/0008837_discard.c b/pool/shard000/C/0008837_discard.c new file mode 100644 index 0000000000000000000000000000000000000000..8cf2fd1b5269add6a65db7a55e284971a9b03596 --- /dev/null +++ b/pool/shard000/C/0008837_discard.c @@ -0,0 +1,163 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * Map handling: We have flexible paging. Each map table consists of a set of pages + * with the last page repeated to fill any holes. + */ + +extern uint8_t internal32k; + +void pagemap_init(void) +{ + int i; + + /* kernel uses 4 5 6 7 0 1 2 3F */ + for (i = 0x3e; i > 7; i--) + pagemap_add(i); + pagemap_add(3); /* was used while loading, replaced by 3F */ + +#ifdef SWAPDEV + for (i = 0; i < MAX_SWAPS; i++) + swapmap_init(i); +#endif +} + +uint8_t platform_param(char *p) +{ + return 0; +} + +static const char *sysname[] = {"Dragon", "COCO", "COCO3", "Unknown"}; + +struct cart_rom_id { + uint16_t hash; + uint8_t id; + const char *name; +}; + +static const char empty[] = "(empty)"; + +struct cart_rom_id carts[] = { + { 0x72B0, CART_DRAGONDOS, "DragonDOS" }, + { 0x9063, CART_DELTADOS, "DeltaDOS" }, + { 0xB400, 0, empty }, + { 0xC248, CART_RSDOS, "RS-DOS" }, + /* This one is an oddity - we need to do more to know what it drives + The great thing is we can extract the MMIO addresses from it */ + { 0xB61B, CART_HDBDOS, "HDBDOS" }, + { 0xCF55, CART_HDBDOS, "HDBDOS" }, + { 0xE1BA, CART_ORCH90, "Orchestra-90 CC" }, + { 0x933E, CART_SDBOOT, "SDBOOT" }, + { 0x0000, 0, "No ROM" } +}; + +struct hdb_rom_id { + char key[2]; + uint8_t id; + const char *name; +}; + +static struct hdb_rom_id hdb[] = { + { "ID", CART_IDE, "IDE-CHS" }, + { "LB", CART_IDE, "IDE-LBA" }, + { "TC", CART_TC3, "TC^3" }, + { "KE", CART_KENTON, "KENTON" }, + { "LR", CART_LRTECH, "LRTECH" }, + { "HD", CART_HDII, "HD-II" }, + { "4-", CART_4N1, "4-N-1" }, + { "DW", CART_DRIVEWIRE, "Drivewire" }, + { "BE", CART_BECKER, "Becker" }, + { "J&", CART_JMCP, "J&M CP" }, + {} +}; + +/* Find a cartridge or it's slot */ +int cart_find(int id) +{ + int i; + for (i = 0; i < id; i++) { + if (carttype[i] == id) + return i; + } + return -1; +} + +static struct cart_rom_id *cart_lookup(uint16_t hash) +{ + struct cart_rom_id *cart = carts; + do { + if (cart->hash == hash) + return cart; + } while(cart++->hash); + return NULL; +} + +static inline int keycmp(uint16_t *k1, uint16_t *k2) +{ + return (*k1 == *k2); +} + +static struct hdb_rom_id *hdb_lookup(uint16_t key) +{ + struct hdb_rom_id *id = hdb; + do { + if (keycmp(&key, (uint16_t *)id->key)) + return id; + } while(id++->id); + return NULL; +} + +void map_init(void) +{ + uint8_t i; + uint8_t bslot = 0; + uint16_t hash; + struct cart_rom_id *rom; + + kprintf("%s system.\n", sysname[system_id]); + if (mpi_present()) { + kputs("MPI cartridge detected.\n"); + cartslots = 4; + bootslot = mpi_set_slot(0); + bslot = bootslot & 3; + } + for (i = 0; i < cartslots; i++) { + mpi_set_slot((i << 4) | i); + hash = cart_hash(); + rom = cart_lookup(hash); + if (rom) { + kprintf("%d:%c%s", + i, i == bslot ? '*':' ', + rom->name); + carttype[i] = rom->id; + } + else + kprintf("%d:%cUnknown(%x)", + i, i == bslot ? '*':' ', hash); + + /* The analysis needs to be in asm as we need to page in + the ROM to peer at it */ + if (rom->id == CART_HDBDOS) { + uint16_t t = cart_analyze_hdb(); + struct hdb_rom_id *hdb = hdb_lookup(t); + if (hdb) { + kprintf(" %s ID %d", + hdb->name, hdb_id); + if (hdb->id == CART_IDE) + kprintf(" MMIO %x", hdb_port); + carttype[i] = hdb->id; + cartaddr[i] = hdb_port; + } else + kprintf("??%x\n", t); + } + kputchar('\n'); + } + mpi_set_slot(bootslot); +} diff --git a/pool/shard000/C/0008848_demo.c b/pool/shard000/C/0008848_demo.c new file mode 100644 index 0000000000000000000000000000000000000000..cc396ea57ee2f4033270532eac487a84dcc9fedd --- /dev/null +++ b/pool/shard000/C/0008848_demo.c @@ -0,0 +1,106 @@ + /* + Õâ·ÝdemoÓÃÓÚÑÝʾ»·Ðλº³åÇø + */ +#include +#include "rtdevice.h" //for rt_ringbuffer +#ifdef RT_USING_FINSH +#include +#include +#endif + + + +static rt_sem_t sem = RT_NULL; + +static rt_uint8_t working_buffer[256]; +struct rt_ringbuffer rb; + +/* Ö¸ÏòÏ߳̿ØÖÆ¿éµÄÖ¸Õë */ +static rt_thread_t tid1 = RT_NULL; +static rt_thread_t tid2 = RT_NULL; + +/* Ïß³Ì1Èë¿Ú */ +static void thread1_entry(void* parameter) +{ + rt_bool_t result=RT_FALSE; + rt_uint8_t data_buffer[33]; + rt_uint32_t i = 1; + + while(1) + { + rt_sem_take (sem,RT_WAITING_FOREVER); + rt_kprintf("th1 take sem\n"); + result = rt_ringbuffer_get(&rb,&data_buffer[0],33); + rt_kprintf("th1 release sem\n"); + rt_sem_release(sem); + //if(RT_TRUE==result) + if(RT_FALSE!=result) + { + rt_kprintf(" th1 read data buffer: %s\n",data_buffer); + } + rt_thread_delay(5); + } + +} + +/* Ïß³Ì2Èë¿Ú£¬Ïß³Ì2µÄÓÅÏȼ¶±ÈÏß³Ì1µÍ£¬Ó¦¸ÃÏß³Ì1ÏÈ»ñµÃÖ´ÐС£*/ +static void thread2_entry(void *parameter) +{ + rt_bool_t result=RT_FALSE; + rt_uint32_t index,setchar,i = 1; + rt_uint8_t data_buffer[33]; + + setchar = 0x21; + while(1) + { + for (index = 0; index < 32; index++) + { + data_buffer[index] = setchar; + if (++setchar == 0x7f) + { + setchar = 0x21; + } + } + data_buffer[32] = '\0'; + + rt_sem_take(sem,RT_WAITING_FOREVER); + rt_kprintf("th2 take sem\n"); + result = rt_ringbuffer_put(&rb,&data_buffer[0],33); + // if(RT_TRUE==result) + if(RT_FALSE!=result) + { + rt_kprintf("th2 write buffer success!\n"); + } + rt_kprintf("th2 realease sem\n"); + rt_sem_release(sem); + + rt_thread_delay(10); + } +} + +int demo_init(void) +{ + rt_ringbuffer_init(&rb,working_buffer,256); + + sem = rt_sem_create("sem",1,RT_IPC_FLAG_FIFO); + if (sem == RT_NULL) + { + return 0; + } + + /* ´´½¨Ïß³Ì1 */ + tid1 = rt_thread_create("t1", + thread1_entry, RT_NULL, /* Ïß³ÌÈë¿ÚÊÇthread1_entry, Èë¿Ú²ÎÊýÊÇRT_NULL */ + 512, 8, 10); + if (tid1 != RT_NULL) + rt_thread_startup(tid1); + + /* ´´½¨Ïß³Ì2 */ + tid2 = rt_thread_create("t2", + thread2_entry, RT_NULL, /* Ïß³ÌÈë¿ÚÊÇthread2_entry, Èë¿Ú²ÎÊýÊÇRT_NULL */ + 512, 7, 10); + if (tid2 != RT_NULL) + rt_thread_startup(tid2); + + return 0; +} diff --git a/pool/shard000/C/0008854_mountpoints.c b/pool/shard000/C/0008854_mountpoints.c new file mode 100644 index 0000000000000000000000000000000000000000..f1d35dd13a2f2da61f34d2b860f6054d8e6f7d9b --- /dev/null +++ b/pool/shard000/C/0008854_mountpoints.c @@ -0,0 +1,121 @@ +#include +#include +#include +#include +#include + +#include "zdtmtst.h" + +const char *test_doc = "Check that mountpoints (in mount namespace) are supported"; +const char *test_author = "Pavel Emelianov "; + +#define MPTS_ROOT "/zdtm_mpts/" + +static char buf[1024]; + +static int test_fn(int argc, char **argv) +{ + FILE *f; + int fd, tmpfs_fd; + unsigned fs_cnt, fs_cnt_last = 0; + +again: + fs_cnt = 0; + f = fopen("/proc/self/mountinfo", "r"); + if (!f) { + fail("Can't open mountinfo"); + return -1; + } + + while (fgets(buf, sizeof(buf), f) != NULL) { + char *mp = buf, *end; + + mp = strchr(mp, ' ') + 1; + mp = strchr(mp, ' ') + 1; + mp = strchr(mp, ' ') + 1; + mp = strchr(mp, ' ') + 1; + end = strchr(mp, ' '); + *end = '\0'; + + if (!strcmp(mp, "/")) + continue; + if (!strcmp(mp, "/proc")) + continue; + + umount(mp); + fs_cnt++; + } + + fclose(f); + + if (fs_cnt == 0) + goto done; + + if (fs_cnt != fs_cnt_last) { + fs_cnt_last = fs_cnt; + goto again; + } + + fail("Can't umount all the filesystems"); + return -1; + +done: + rmdir(MPTS_ROOT); + if (mkdir(MPTS_ROOT, 0600) < 0) { + fail("Can't make zdtm_sys"); + return 1; + } + + if (mount("none", MPTS_ROOT, "sysfs", 0, "") < 0) { + fail("Can't mount sysfs"); + return 1; + } + + if (mount("none", MPTS_ROOT"/dev", "tmpfs", 0, "") < 0) { + fail("Can't mount tmpfs"); + return 1; + } + tmpfs_fd = open(MPTS_ROOT"/dev/test", O_WRONLY | O_CREAT); + if (write(tmpfs_fd, "hello", 5) <= 0) { + err("write() failed"); + return 1; + } + + if (mount("none", MPTS_ROOT"/kernel", "proc", 0, "") < 0) { + fail("Can't mount proc"); + return 1; + } + if (mount("none", MPTS_ROOT"/kernel/sys/fs/binfmt_misc", + "binfmt_misc", 0, "") < 0) { + fail("Can't mount proc"); + return 1; + } + + mknod("/dev/null", 0777 | S_IFCHR, makedev(1, 3)); + + setup_outfile(); + + fd = open(MPTS_ROOT"/kernel/meminfo", O_RDONLY); + if (fd == -1) + return 1; + + test_daemon(); + test_waitsig(); + + /* this checks both -- sys and proc presence */ + if (access(MPTS_ROOT"/kernel/meminfo", F_OK)) { + fail("No proc after restore"); + return 1; + } + + pass(); + return 0; +} + +#define CLONE_NEWNS 0x00020000 + +int main(int argc, char **argv) +{ + test_init_ns(argc, argv, CLONE_NEWNS, test_fn); + return 0; +} diff --git a/pool/shard000/C/0008864_itob.c b/pool/shard000/C/0008864_itob.c new file mode 100644 index 0000000000000000000000000000000000000000..0dc6a378db219a98362b734445d8395e60fd09c7 --- /dev/null +++ b/pool/shard000/C/0008864_itob.c @@ -0,0 +1,130 @@ +/* + * itob: converts an integer to a variable base character string representation + * + * "Portions of this work are derived from The Standard C Library, copyright (c) 1992 + * by P.J. Plauger, published by Prentice-Hall, and are used with permission." + */ + +// Includes + +#include +#include +#include +#include + +// Definitions + +#define MAXSTRING 256 + +/* + * reverse(): reverse string 's' in place + */ + +static void reverse(char s[]) { + + size_t i; + size_t j; + + for (i = 0, j = strlen(s) - 1; i < j; i++, j--) { + int c; + c = s[i]; + s[i] = s[j]; + s[j] = c; + } + +} + +/* + * iotb(): converts integer 'n' into a base 'b' string 's[]' + */ + +static void itob(int n, char s[], int b) { + + size_t i = 0; + int sign = n; // Save the sign and make it positive if its negative + + // generate digits in reverse order + do { + int d = abs(n % b); // gets the next digit + s[i++] = (d <= 9) ? (char)d + '0' : (char)d + 'A' - 10; // save it as a char--letters if num > 9 + } while ((n /= b) != 0); // and deletes it from the number + + // set the sign of the string (again in reverse) + if (sign < 0) + s[i++] = '-'; + + // termerate the string + s[i] = '\0'; + + // and reverse the string back + reverse(s); +} + +/* Main */ + +int main(void) { + int n; + int b; + char s[MAXSTRING] = ""; + + n = -255; + b = 10; + itob(n, s, b); + printf("Number %d converted to a string in base %d is: \"%s\"\n", n, b, s); + b = 2; + itob(n, s, b); + printf("Number %d converted to a string in base %d is: \"%s\"\n", n, b, s); + b = 8; + itob(n, s, b); + printf("Number %d converted to a string in base %d is: \"%s\"\n", n, b, s); + b = 16; + itob(n, s, b); + printf("Number %d converted to a string in base %d is: \"%s\"\n", n, b, s); + (void)putchar('\n'); + + n = 255; + b = 10; + itob(n, s, b); + printf("Number %d converted to a string in base %d is: \"%s\"\n", n, b, s); + b = 2; + itob(n, s, b); + printf("Number %d converted to a string in base %d is: \"%s\"\n", n, b, s); + b = 8; + itob(n, s, b); + printf("Number %d converted to a string in base %d is: \"%s\"\n", n, b, s); + b = 16; + itob(n, s, b); + printf("Number %d converted to a string in base %d is: \"%s\"\n", n, b, s); + (void)putchar('\n'); + + n = 1043; + b = 10; + itob(n, s, b); + printf("Number %d converted to a string in base %d is: \"%s\"\n", n, b, s); + b = 2; + itob(n, s, b); + printf("Number %d converted to a string in base %d is: \"%s\"\n", n, b, s); + b = 8; + itob(n, s, b); + printf("Number %d converted to a string in base %d is: \"%s\"\n", n, b, s); + b = 16; + itob(n, s, b); + printf("Number %d converted to a string in base %d is: \"%s\"\n", n, b, s); + (void)putchar('\n'); + + n = INT_MIN; + b = 10; + itob(n, s, b); + printf("Number %d converted to a string in base %d is: \"%s\"\n", n, b, s); + b = 2; + itob(n, s, b); + printf("Number %d converted to a string in base %d is: \"%s\"\n", n, b, s); + b = 8; + itob(n, s, b); + printf("Number %d converted to a string in base %d is: \"%s\"\n", n, b, s); + b = 16; + itob(n, s, b); + printf("Number %d converted to a string in base %d is: \"%s\"\n", n, b, s); + + return 0; +} diff --git a/pool/shard000/C/0008887_graphtest.c b/pool/shard000/C/0008887_graphtest.c new file mode 100644 index 0000000000000000000000000000000000000000..aeee91187d83209d3da6e47bc936b17b62d206b0 --- /dev/null +++ b/pool/shard000/C/0008887_graphtest.c @@ -0,0 +1,61 @@ +#include +#include +#include +#include +#include +#include +#include + +uint32_t bytes_in = 666; +uint32_t bytes_out = 666; + +void graphtest_write(void) +{ + struct graph *graph; + + graph = graph_new("traffic", 400, 160, GRAPH_TYPE_LINE); + +/* graph_colorize(graph, GRAPH_COLOR_DARK); + + graph_source_add(graph, GRAPH_MEASURE_DIFFTIME, + GRAPH_SOURCE_UINT, &bytes_in, "in"); + + graph_source_add(graph, GRAPH_MEASURE_DIFFTIME, + GRAPH_SOURCE_UINT, &bytes_out, "out"); + + graph_drain_add(graph, GRAPH_DATA_HOURLY); + graph_drain_add(graph, GRAPH_DATA_DAILY); + graph_drain_add(graph, GRAPH_DATA_WEEKLY); + graph_drain_add(graph, GRAPH_DATA_MONTHLY); + + graph_drain_render(graph, GRAPH_DATA_HOURLY); + graph_drain_save(graph, GRAPH_DATA_HOURLY); + */ + graph_delete(graph); +} + +int main() +{ + log_init(STDOUT_FILENO, LOG_ALL, L_status); + io_init_except(STDOUT_FILENO, STDOUT_FILENO, STDOUT_FILENO); + mem_init(); + dlink_init(); + gif_init(); + image_init(); + timer_init(); + graph_init(); + + graphtest_write(); + + graph_shutdown(); + timer_shutdown(); + image_shutdown(); + gif_shutdown(); + dlink_shutdown(); + mem_shutdown(); + log_shutdown(); + io_shutdown(); + + return 0; +} + diff --git a/pool/shard000/C/0008890_dvk_ebi.c b/pool/shard000/C/0008890_dvk_ebi.c new file mode 100644 index 0000000000000000000000000000000000000000..1d37f358cf7e76ca250a9d3be1390d789d75ef56 --- /dev/null +++ b/pool/shard000/C/0008890_dvk_ebi.c @@ -0,0 +1,237 @@ +/**************************************************************************//** + * @file + * @brief EBI implementation of Board Control interface + * This implementation works for devices w/o LCD display on the + * MCU module, specifically the EFM32_G2xx_DK development board + * @author Energy Micro AS + * @version 1.6.0 + ****************************************************************************** + * @section License + * (C) Copyright 2010 Energy Micro AS, http://www.energymicro.com + ****************************************************************************** + * + * This source code is the property of Energy Micro AS. The source and compiled + * code may only be used on Energy Micro "EFM32" microcontrollers. + * + * This copyright notice may not be removed from the source code nor changed. + * + * DISCLAIMER OF WARRANTY/LIMITATION OF REMEDIES: Energy Micro AS has no + * obligation to support this Software. Energy Micro AS is providing the + * Software "AS IS", with no express or implied warranties of any kind, + * including, but not limited to, any implied warranties of merchantability + * or fitness for any particular purpose or warranties against infringement + * of any proprietary rights of a third party. + * + * Energy Micro AS will not be liable for any consequential, incidental, or + * special damages, or any other relief, or for any claim by any third party, + * arising from your use of this Software. + * + *****************************************************************************/ +#include "efm32.h" +#include "efm32_ebi.h" +#include "efm32_cmu.h" +#include "efm32_gpio.h" +#include "dvk.h" +#include "dvk_bcregisters.h" + + +/**************************************************************************//** + * @brief Configure EBI (external bus interface) for Board Control register + * access + *****************************************************************************/ +void DVK_EBI_configure(void) +{ + EBI_Init_TypeDef ebiConfig = EBI_INIT_DEFAULT; + + /* Run time check if we have EBI on-chip capability on this device */ + switch ((DEVINFO->PART & _DEVINFO_PART_DEVICE_NUMBER_MASK) >> + _DEVINFO_PART_DEVICE_NUMBER_SHIFT) + { + /* Only device types EFM32G 280/290/880 and 890 have EBI capability */ + case 280: + case 290: + case 880: + case 890: + break; + default: + /* This device do not have EBI capability - use SPI to interface DVK */ + /* With high probability your project has been configured for an */ + /* incorrect part number. */ + while (1) ; + } + + /* Enable clocks */ + CMU_ClockEnable(cmuClock_EBI, true); + CMU_ClockEnable(cmuClock_GPIO, true); + + /* Configure bus connect PC bit 12 active low */ + GPIO_PinModeSet(gpioPortC, 12, gpioModePushPull, 0); + + /* Configure GPIO pins as push pull */ + /* EBI AD9..15 */ + GPIO_PinModeSet(gpioPortA, 0, gpioModePushPull, 0); + GPIO_PinModeSet(gpioPortA, 1, gpioModePushPull, 0); + GPIO_PinModeSet(gpioPortA, 2, gpioModePushPull, 0); + GPIO_PinModeSet(gpioPortA, 3, gpioModePushPull, 0); + GPIO_PinModeSet(gpioPortA, 4, gpioModePushPull, 0); + GPIO_PinModeSet(gpioPortA, 5, gpioModePushPull, 0); + GPIO_PinModeSet(gpioPortA, 6, gpioModePushPull, 0); + + /* EBI AD8 */ + GPIO_PinModeSet(gpioPortA, 15, gpioModePushPull, 0); + + /* EBI CS0-CS3 */ + GPIO_PinModeSet(gpioPortD, 9, gpioModePushPull, 0); + GPIO_PinModeSet(gpioPortD, 10, gpioModePushPull, 0); + GPIO_PinModeSet(gpioPortD, 11, gpioModePushPull, 0); + GPIO_PinModeSet(gpioPortD, 12, gpioModePushPull, 0); + + /* EBI AD0..7 */ + GPIO_PinModeSet(gpioPortE, 8, gpioModePushPull, 0); + GPIO_PinModeSet(gpioPortE, 9, gpioModePushPull, 0); + GPIO_PinModeSet(gpioPortE, 10, gpioModePushPull, 0); + GPIO_PinModeSet(gpioPortE, 11, gpioModePushPull, 0); + GPIO_PinModeSet(gpioPortE, 12, gpioModePushPull, 0); + GPIO_PinModeSet(gpioPortE, 13, gpioModePushPull, 0); + GPIO_PinModeSet(gpioPortE, 14, gpioModePushPull, 0); + GPIO_PinModeSet(gpioPortE, 15, gpioModePushPull, 0); + + /* EBI ARDY/ALEN/Wen/Ren */ + GPIO_PinModeSet(gpioPortF, 2, gpioModePushPull, 0); + GPIO_PinModeSet(gpioPortF, 3, gpioModePushPull, 0); + GPIO_PinModeSet(gpioPortF, 4, gpioModePushPull, 0); + GPIO_PinModeSet(gpioPortF, 5, gpioModePushPull, 0); + + /* Configure EBI controller, changing default values */ + ebiConfig.mode = ebiModeD16A16ALE; + /* Enable bank 0 address map 0x80000000, FPGA Flash */ + /* Enable bank 1 address map 0x84000000, FPGA SRAM */ + /* Enable bank 2 address map 0x88000000, FPGA TFT Display (SSD2119) */ + /* Enable bank 3 address map 0x8c000000, FPGA Board Control Registers */ + ebiConfig.banks = EBI_BANK0|EBI_BANK1|EBI_BANK2|EBI_BANK3; + ebiConfig.csLines = EBI_CS0|EBI_CS1|EBI_CS2|EBI_CS3; + + /* Address Setup and hold time */ + ebiConfig.addrHoldCycles = 3; + ebiConfig.addrSetupCycles = 3; + + /* Read cycle times */ + ebiConfig.readStrobeCycles = 7; + ebiConfig.readHoldCycles = 3; + ebiConfig.readSetupCycles = 3; + + /* Write cycle times */ + ebiConfig.writeStrobeCycles = 7; + ebiConfig.writeHoldCycles = 3; + ebiConfig.writeSetupCycles = 3; + + /* Polarity values are default */ + + /* Configure EBI */ + EBI_Init(&ebiConfig); +} + + +/**************************************************************************//** + * @brief Initialize EBI + * access + *****************************************************************************/ +void DVK_EBI_init(void) +{ + uint16_t ebiMagic; + int ctr; + + /* Disable all GPIO pins and register */ + DVK_EBI_disable(); + /* Configure EBI */ + DVK_EBI_configure(); + /* Verify that EBI access is working, if not kit is in SPI mode and needs to + * be configured for EBI access */ + ebiMagic = DVK_EBI_readRegister(BC_MAGIC); + if (ebiMagic != BC_MAGIC_VALUE) + { + /* Disable EBI */ + DVK_EBI_disable(); + /* Enable SPI interface */ + DVK_SPI_init(); + /* Set EBI mode - after this SPI access will no longer be available */ + DVK_SPI_writeRegister(BC_CFG, BC_CFG_EBI); + /* Disable SPI */ + DVK_SPI_disable(); + /* Now setup EBI again */ + DVK_EBI_configure(); + /* Wait until ready */ + ctr = 0; + do + { + /* Check if FPGA responds */ + ebiMagic = DVK_EBI_readRegister(BC_MAGIC); + ctr++; + DVK_EBI_writeRegister(BC_LED, ctr); + } while (ebiMagic != BC_MAGIC_VALUE); + } +} + +/**************************************************************************//** + * @brief Disable EBI interface, free all GPIO pins + *****************************************************************************/ +void DVK_EBI_disable(void) +{ + /* Disable EBI controller */ + EBI_Disable(); + + /* Disable EBI clock in CMU */ + CMU_ClockEnable(cmuClock_EBI, false); + + /* Disable EBI _BC_BUS_CONNECT */ + GPIO_PinModeSet(gpioPortC, 12, gpioModeDisabled, 0); + + /* Configure GPIO pins as disabled */ + GPIO_PinModeSet(gpioPortA, 0, gpioModeDisabled, 0); + GPIO_PinModeSet(gpioPortA, 1, gpioModeDisabled, 0); + GPIO_PinModeSet(gpioPortA, 2, gpioModeDisabled, 0); + GPIO_PinModeSet(gpioPortA, 3, gpioModeDisabled, 0); + GPIO_PinModeSet(gpioPortA, 4, gpioModeDisabled, 0); + GPIO_PinModeSet(gpioPortA, 5, gpioModeDisabled, 0); + GPIO_PinModeSet(gpioPortA, 6, gpioModeDisabled, 0); + + GPIO_PinModeSet(gpioPortA, 15, gpioModeDisabled, 0); + + GPIO_PinModeSet(gpioPortD, 9, gpioModeDisabled, 0); + GPIO_PinModeSet(gpioPortD, 10, gpioModeDisabled, 0); + GPIO_PinModeSet(gpioPortD, 11, gpioModeDisabled, 0); + GPIO_PinModeSet(gpioPortD, 12, gpioModeDisabled, 0); + + GPIO_PinModeSet(gpioPortE, 8, gpioModeDisabled, 0); + GPIO_PinModeSet(gpioPortE, 9, gpioModeDisabled, 0); + GPIO_PinModeSet(gpioPortE, 10, gpioModeDisabled, 0); + GPIO_PinModeSet(gpioPortE, 11, gpioModeDisabled, 0); + GPIO_PinModeSet(gpioPortE, 12, gpioModeDisabled, 0); + GPIO_PinModeSet(gpioPortE, 13, gpioModeDisabled, 0); + GPIO_PinModeSet(gpioPortE, 14, gpioModeDisabled, 0); + GPIO_PinModeSet(gpioPortE, 15, gpioModeDisabled, 0); + + GPIO_PinModeSet(gpioPortF, 2, gpioModeDisabled, 0); + GPIO_PinModeSet(gpioPortF, 3, gpioModeDisabled, 0); + GPIO_PinModeSet(gpioPortF, 4, gpioModeDisabled, 0); + GPIO_PinModeSet(gpioPortF, 5, gpioModeDisabled, 0); +} + +/**************************************************************************//** + * @brief Write data into 16-bit board control register + * @param addr Address to board control register + * @param data Data to write into register + *****************************************************************************/ +void DVK_EBI_writeRegister(volatile uint16_t *addr, uint16_t data) +{ + *addr = data; +} + +/**************************************************************************//** + * @brief Write data into 16-bit board control register + * @param addr Register to read from + *****************************************************************************/ +uint16_t DVK_EBI_readRegister(volatile uint16_t *addr) +{ + return *addr; +} diff --git a/pool/shard000/C/0008902_comtest.c b/pool/shard000/C/0008902_comtest.c new file mode 100644 index 0000000000000000000000000000000000000000..ec58dcffc1158bcdc4f309a9286c09400ffa5530 --- /dev/null +++ b/pool/shard000/C/0008902_comtest.c @@ -0,0 +1,312 @@ +/* + FreeRTOS V7.4.0 - Copyright (C) 2013 Real Time Engineers Ltd. + + FEATURES AND PORTS ARE ADDED TO FREERTOS ALL THE TIME. PLEASE VISIT + http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. + + *************************************************************************** + * * + * FreeRTOS tutorial books are available in pdf and paperback. * + * Complete, revised, and edited pdf reference manuals are also * + * available. * + * * + * Purchasing FreeRTOS documentation will not only help you, by * + * ensuring you get running as quickly as possible and with an * + * in-depth knowledge of how to use FreeRTOS, it will also help * + * the FreeRTOS project to continue with its mission of providing * + * professional grade, cross platform, de facto standard solutions * + * for microcontrollers - completely free of charge! * + * * + * >>> See http://www.FreeRTOS.org/Documentation for details. <<< * + * * + * Thank you for using FreeRTOS, and thank you for your support! * + * * + *************************************************************************** + + + This file is part of the FreeRTOS distribution. + + FreeRTOS is free software; you can redistribute it and/or modify it under + the terms of the GNU General Public License (version 2) as published by the + Free Software Foundation AND MODIFIED BY the FreeRTOS exception. + + >>>>>>NOTE<<<<<< The modification to the GPL is included to allow you to + distribute a combined work that includes FreeRTOS without being obliged to + provide the source code for proprietary components outside of the FreeRTOS + kernel. + + FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + details. You should have received a copy of the GNU General Public License + and the FreeRTOS license exception along with FreeRTOS; if not itcan be + viewed here: http://www.freertos.org/a00114.html and also obtained by + writing to Real Time Engineers Ltd., contact details for whom are available + on the FreeRTOS WEB site. + + 1 tab == 4 spaces! + + *************************************************************************** + * * + * Having a problem? Start by reading the FAQ "My application does * + * not run, what could be wrong?" * + * * + * http://www.FreeRTOS.org/FAQHelp.html * + * * + *************************************************************************** + + + http://www.FreeRTOS.org - Documentation, books, training, latest versions, + license and Real Time Engineers Ltd. contact details. + + http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, + including FreeRTOS+Trace - an indispensable productivity tool, and our new + fully thread aware and reentrant UDP/IP stack. + + http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to High + Integrity Systems, who sell the code with commercial support, + indemnification and middleware, under the OpenRTOS brand. + + http://www.SafeRTOS.com - High Integrity Systems also provide a safety + engineered and independently SIL3 certified version for use in safety and + mission critical applications that require provable dependability. +*/ + + +/* + * This version of comtest. c is for use on systems that have limited stack + * space and no display facilities. The complete version can be found in + * the Demo/Common/Full directory. + * + * Creates two tasks that operate on an interrupt driven serial port. A + * loopback connector should be used so that everything that is transmitted is + * also received. The serial port does not use any flow control. On a + * standard 9way 'D' connector pins two and three should be connected together. + * + * The first task posts a sequence of characters to the Tx queue, toggling an + * LED on each successful post. At the end of the sequence it sleeps for a + * pseudo-random period before resending the same sequence. + * + * The UART Tx end interrupt is enabled whenever data is available in the Tx + * queue. The Tx end ISR removes a single character from the Tx queue and + * passes it to the UART for transmission. + * + * The second task blocks on the Rx queue waiting for a character to become + * available. When the UART Rx end interrupt receives a character it places + * it in the Rx queue, waking the second task. The second task checks that the + * characters removed from the Rx queue form the same sequence as those posted + * to the Tx queue, and toggles an LED for each correct character. + * + * The receiving task is spawned with a higher priority than the transmitting + * task. The receiver will therefore wake every time a character is + * transmitted so neither the Tx or Rx queue should ever hold more than a few + * characters. + * + */ + +/* Scheduler include files. */ +#include +#include "FreeRTOS.h" +#include "task.h" + +/* Demo program include files. */ +#include "serial.h" +#include "comtest.h" +#include "partest.h" + +#define comSTACK_SIZE configMINIMAL_STACK_SIZE +#define comTX_LED_OFFSET ( 0 ) +#define comRX_LED_OFFSET ( 1 ) +#define comTOTAL_PERMISSIBLE_ERRORS ( 2 ) + +/* The Tx task will transmit the sequence of characters at a pseudo random +interval. This is the maximum and minimum block time between sends. */ +#define comTX_MAX_BLOCK_TIME ( ( portTickType ) 0x96 ) +#define comTX_MIN_BLOCK_TIME ( ( portTickType ) 0x32 ) +#define comOFFSET_TIME ( ( portTickType ) 3 ) + +/* We should find that each character can be queued for Tx immediately and we +don't have to block to send. */ +#define comNO_BLOCK ( ( portTickType ) 0 ) + +/* The Rx task will block on the Rx queue for a long period. */ +#define comRX_BLOCK_TIME ( ( portTickType ) 0xffff ) + +/* The sequence transmitted is from comFIRST_BYTE to and including comLAST_BYTE. */ +#define comFIRST_BYTE ( 'A' ) +#define comLAST_BYTE ( 'X' ) + +#define comBUFFER_LEN ( ( unsigned portBASE_TYPE ) ( comLAST_BYTE - comFIRST_BYTE ) + ( unsigned portBASE_TYPE ) 1 ) +#define comINITIAL_RX_COUNT_VALUE ( 0 ) + +/* Handle to the com port used by both tasks. */ +static xComPortHandle xPort = NULL; + +/* The transmit task as described at the top of the file. */ +static portTASK_FUNCTION_PROTO( vComTxTask, pvParameters ); + +/* The receive task as described at the top of the file. */ +static portTASK_FUNCTION_PROTO( vComRxTask, pvParameters ); + +/* The LED that should be toggled by the Rx and Tx tasks. The Rx task will +toggle LED ( uxBaseLED + comRX_LED_OFFSET). The Tx task will toggle LED +( uxBaseLED + comTX_LED_OFFSET ). */ +static unsigned portBASE_TYPE uxBaseLED = 0; + +/* Check variable used to ensure no error have occurred. The Rx task will +increment this variable after every successfully received sequence. If at any +time the sequence is incorrect the the variable will stop being incremented. */ +static volatile unsigned portBASE_TYPE uxRxLoops = comINITIAL_RX_COUNT_VALUE; + +/*-----------------------------------------------------------*/ + +void vAltStartComTestTasks( unsigned portBASE_TYPE uxPriority, unsigned long ulBaudRate, unsigned portBASE_TYPE uxLED ) +{ + /* Initialise the com port then spawn the Rx and Tx tasks. */ + uxBaseLED = uxLED; + xSerialPortInitMinimal( ulBaudRate, comBUFFER_LEN ); + + /* The Tx task is spawned with a lower priority than the Rx task. */ + xTaskCreate( vComTxTask, ( signed char * ) "COMTx", comSTACK_SIZE, NULL, uxPriority - 1, ( xTaskHandle * ) NULL ); + xTaskCreate( vComRxTask, ( signed char * ) "COMRx", comSTACK_SIZE, NULL, uxPriority, ( xTaskHandle * ) NULL ); +} +/*-----------------------------------------------------------*/ + +static portTASK_FUNCTION( vComTxTask, pvParameters ) +{ +signed char cByteToSend; +portTickType xTimeToWait; + + /* Just to stop compiler warnings. */ + ( void ) pvParameters; + + for( ;; ) + { + /* Simply transmit a sequence of characters from comFIRST_BYTE to + comLAST_BYTE. */ + for( cByteToSend = comFIRST_BYTE; cByteToSend <= comLAST_BYTE; cByteToSend++ ) + { + if( xSerialPutChar( xPort, cByteToSend, comNO_BLOCK ) == pdPASS ) + { + vParTestToggleLED( uxBaseLED + comTX_LED_OFFSET ); + } + } + + /* Turn the LED off while we are not doing anything. */ + vParTestSetLED( uxBaseLED + comTX_LED_OFFSET, pdFALSE ); + + /* We have posted all the characters in the string - wait before + re-sending. Wait a pseudo-random time as this will provide a better + test. */ + xTimeToWait = xTaskGetTickCount() + comOFFSET_TIME; + + /* Make sure we don't wait too long... */ + xTimeToWait %= comTX_MAX_BLOCK_TIME; + + /* ...but we do want to wait. */ + if( xTimeToWait < comTX_MIN_BLOCK_TIME ) + { + xTimeToWait = comTX_MIN_BLOCK_TIME; + } + + vTaskDelay( xTimeToWait ); + } +} /*lint !e715 !e818 pvParameters is required for a task function even if it is not referenced. */ +/*-----------------------------------------------------------*/ + +static portTASK_FUNCTION( vComRxTask, pvParameters ) +{ +signed char cExpectedByte, cByteRxed; +portBASE_TYPE xResyncRequired = pdFALSE, xErrorOccurred = pdFALSE; + + /* Just to stop compiler warnings. */ + ( void ) pvParameters; + + for( ;; ) + { + /* We expect to receive the characters from comFIRST_BYTE to + comLAST_BYTE in an incrementing order. Loop to receive each byte. */ + for( cExpectedByte = comFIRST_BYTE; cExpectedByte <= comLAST_BYTE; cExpectedByte++ ) + { + /* Block on the queue that contains received bytes until a byte is + available. */ + if( xSerialGetChar( xPort, &cByteRxed, comRX_BLOCK_TIME ) ) + { + /* Was this the byte we were expecting? If so, toggle the LED, + otherwise we are out on sync and should break out of the loop + until the expected character sequence is about to restart. */ + if( cByteRxed == cExpectedByte ) + { + vParTestToggleLED( uxBaseLED + comRX_LED_OFFSET ); + } + else + { + xResyncRequired = pdTRUE; + break; /*lint !e960 Non-switch break allowed. */ + } + } + } + + /* Turn the LED off while we are not doing anything. */ + vParTestSetLED( uxBaseLED + comRX_LED_OFFSET, pdFALSE ); + + /* Did we break out of the loop because the characters were received in + an unexpected order? If so wait here until the character sequence is + about to restart. */ + if( xResyncRequired == pdTRUE ) + { + while( cByteRxed != comLAST_BYTE ) + { + /* Block until the next char is available. */ + xSerialGetChar( xPort, &cByteRxed, comRX_BLOCK_TIME ); + } + + /* Note that an error occurred which caused us to have to resync. + We use this to stop incrementing the loop counter so + sAreComTestTasksStillRunning() will return false - indicating an + error. */ + xErrorOccurred++; + + /* We have now resynced with the Tx task and can continue. */ + xResyncRequired = pdFALSE; + } + else + { + if( xErrorOccurred < comTOTAL_PERMISSIBLE_ERRORS ) + { + /* Increment the count of successful loops. As error + occurring (i.e. an unexpected character being received) will + prevent this counter being incremented for the rest of the + execution. Don't worry about mutual exclusion on this + variable - it doesn't really matter as we just want it + to change. */ + uxRxLoops++; + } + } + } +} /*lint !e715 !e818 pvParameters is required for a task function even if it is not referenced. */ +/*-----------------------------------------------------------*/ + +portBASE_TYPE xAreComTestTasksStillRunning( void ) +{ +portBASE_TYPE xReturn; + + /* If the count of successful reception loops has not changed than at + some time an error occurred (i.e. a character was received out of sequence) + and we will return false. */ + if( uxRxLoops == comINITIAL_RX_COUNT_VALUE ) + { + xReturn = pdFALSE; + } + else + { + xReturn = pdTRUE; + } + + /* Reset the count of successful Rx loops. When this function is called + again we expect this to have been incremented. */ + uxRxLoops = comINITIAL_RX_COUNT_VALUE; + + return xReturn; +} + diff --git a/pool/shard000/C/0008912_unix_misc.c b/pool/shard000/C/0008912_unix_misc.c new file mode 100644 index 0000000000000000000000000000000000000000..5e5186ab998c163b9dcbf0c07ea3f83fddbf9fd9 --- /dev/null +++ b/pool/shard000/C/0008912_unix_misc.c @@ -0,0 +1,50 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "process.h" +#include "io.h" +#include "prog.h" +#include "ntcomm.h" + +#define unixfd(hc) FileHandle_fromCommHandle(ComGetHandle(hc)) + +/* Record locking code */ + +int lock(int fd, long offset, long len) +{ + struct flock lck; + + lck.l_type = F_WRLCK; /* setting a write lock */ + lck.l_whence = SEEK_SET; /* offset l_start from beginning of file */ + lck.l_start = (off_t)offset; + lck.l_len = len; + + return fcntl(fd, F_SETLK, &lck); +} + +int unlock(int fd, long offset, long len) +{ + struct flock lck; + + lck.l_type = F_UNLCK; /* setting not locked */ + lck.l_whence = SEEK_SET; /* offset l_start from beginning of file */ + lck.l_start = (off_t)offset; + lck.l_len = len; + + return fcntl(fd, F_SETLK, &lck); +} + +void NoMem() __attribute__((weak)); +void NoMem() +{ + fprintf(stderr, "Out of memory!\n"); + _exit(1); +} diff --git a/pool/shard000/C/0008917_PiCode.c b/pool/shard000/C/0008917_PiCode.c new file mode 100644 index 0000000000000000000000000000000000000000..84b5fa57844aab1c876c56b6495f6c2465ceecd2 --- /dev/null +++ b/pool/shard000/C/0008917_PiCode.c @@ -0,0 +1,96 @@ +/* + * PiCode.c + * + * Created on: May 25, 2016 + * Author: Barrett + * Uses the Monte Carlo method of pi calculation and pthreads + * to accurately and consistently approximate pi, getting more + * accurate as the number of threads increase + */ +#include +#include +#include +#include + +//GLOBAL VARIABLE +int threadcount = 100000;//number of threads created 250000 + +//STRUCTURES +struct randoms{//used to pass the two random numbers + double rand1; + double rand2; +}; + +void *piseries(void *arg){ + //*NOTE* DON'T SEED RANDOM NUMBERS (srand()) IN THE THREAD FUNCTION, + //you must seed the random function once in the main method so its only seeded once as a constant + //addornot has dynamically allocated data + int *addornot = malloc(sizeof(*addornot));//add or not is returned as 0 or 1, a boolean for C + + struct randoms *nums = (struct randoms*)arg; + //gets random numbers created in main() + double x = nums->rand1; + double y = nums->rand2; + //THE MATH, REFER TO MONTE CARLO PI CALCULATION + double answ = (x*x)+(y*y); + //DEBUGGINGprintf("\n\n------------\n| %f...%f |\n------------\n\n", x, y); + *addornot = 0;//initially false + if (answ < 1){ + *addornot = 1;//TRUE + pthread_exit(addornot);//return addornot to pthread_join() + } + else{//FALSE + pthread_exit(addornot);//return addornot to pthread_join + } + return NULL; +} + +int main(){ + void *incircle;//recieve the addornot variable when pthread_exit() is called + int pointsinside = 0;//if addornot is true(1) add one + double pi;//store actual finished value of pi + struct randoms randm;//random numbers for pthreads + + //INITIALIZING THE THREADS + pthread_t threads[threadcount];//array of threads with custom size of global variabel threadcount + srand(3645783);//seed the rand function ONLY DO ONCE AND NOT IN ANY THREADS, THE NUMBERS WILL BECOME NOT RANDOM IF YOU DO AND IT WILL SKEW RESULTS + + for (int i = 0; i < threadcount; i++){//create random numbers, threads and joins the threads while printing out status of the process + //assign random numbers to structure, DIVIDE BY RAND_MAX NOT ESTIMATED MAX OR ELSE RESULTS WILL BE SKEWED + randm.rand1 = (double)rand()/RAND_MAX; + randm.rand2 = (double)rand()/RAND_MAX; + //create and join threads + pthread_create(&threads[i], NULL, piseries, (void *)&randm); + pthread_join(threads[i], &incircle); + if(*(int*)incircle == 1){//incircle is returned by pthread_exit in the piseries function + pointsinside++; + //DEBUGGINGprintf("YES"); + //DEBUGGINGfflush(stdout); + } + //printing benchmark points + if((double)i/threadcount == .25){ + printf(" 25%% "); + fflush(stdout); + } + else if((double)i/threadcount == .5){ + printf(" 50%% "); + fflush(stdout); + } + else if((double)i/threadcount == .75){ + printf(" 75%% "); + fflush(stdout); + } + }//end for + //MATH, SEE MONTE CARLO PI CALCULATION + pi = 4 * ((double)pointsinside/threadcount);//4*(number of points inside/total number of threads) + printf("\n\nPi is estimated to: %f\n\n%d", pi, pointsinside); + fflush(stdout); +} + + + + + + + + diff --git a/pool/shard000/C/0008927_channel_layout.c b/pool/shard000/C/0008927_channel_layout.c new file mode 100644 index 0000000000000000000000000000000000000000..79e398e41a719f476261e013d2968193b2a54727 --- /dev/null +++ b/pool/shard000/C/0008927_channel_layout.c @@ -0,0 +1,231 @@ +/* + * Copyright (c) 2006 Michael Niedermayer + * + * This file is part of Libav. + * + * Libav is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * Libav is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Libav; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/** + * @file + * audio channel layout utility functions + */ + +#include "avstring.h" +#include "avutil.h" +#include "channel_layout.h" +#include "common.h" + +static const char * const channel_names[] = { + [0] = "FL", /* front left */ + [1] = "FR", /* front right */ + [2] = "FC", /* front center */ + [3] = "LFE", /* low frequency */ + [4] = "BL", /* back left */ + [5] = "BR", /* back right */ + [6] = "FLC", /* front left-of-center */ + [7] = "FRC", /* front right-of-center */ + [8] = "BC", /* back-center */ + [9] = "SL", /* side left */ + [10] = "SR", /* side right */ + [11] = "TC", /* top center */ + [12] = "TFL", /* top front left */ + [13] = "TFC", /* top front center */ + [14] = "TFR", /* top front right */ + [15] = "TBL", /* top back left */ + [16] = "TBC", /* top back center */ + [17] = "TBR", /* top back right */ + [29] = "DL", /* downmix left */ + [30] = "DR", /* downmix right */ + [31] = "WL", /* wide left */ + [32] = "WR", /* wide right */ + [33] = "SDL", /* surround direct left */ + [34] = "SDR", /* surround direct right */ + [35] = "LFE2", /* low frequency 2 */ +}; + +static const char *get_channel_name(int channel_id) +{ + if (channel_id < 0 || channel_id >= FF_ARRAY_ELEMS(channel_names)) + return NULL; + return channel_names[channel_id]; +} + +static const struct { + const char *name; + int nb_channels; + uint64_t layout; +} channel_layout_map[] = { + { "mono", 1, AV_CH_LAYOUT_MONO }, + { "stereo", 2, AV_CH_LAYOUT_STEREO }, + { "stereo", 2, AV_CH_LAYOUT_STEREO_DOWNMIX }, + { "2.1", 3, AV_CH_LAYOUT_2POINT1 }, + { "3.0", 3, AV_CH_LAYOUT_SURROUND }, + { "3.0(back)", 3, AV_CH_LAYOUT_2_1 }, + { "3.1", 4, AV_CH_LAYOUT_3POINT1 }, + { "4.0", 4, AV_CH_LAYOUT_4POINT0 }, + { "quad", 4, AV_CH_LAYOUT_QUAD }, + { "quad(side)", 4, AV_CH_LAYOUT_2_2 }, + { "4.1", 5, AV_CH_LAYOUT_4POINT1 }, + { "5.0", 5, AV_CH_LAYOUT_5POINT0 }, + { "5.0", 5, AV_CH_LAYOUT_5POINT0_BACK }, + { "5.1", 6, AV_CH_LAYOUT_5POINT1 }, + { "5.1", 6, AV_CH_LAYOUT_5POINT1_BACK }, + { "6.0", 6, AV_CH_LAYOUT_6POINT0 }, + { "6.0(front)", 6, AV_CH_LAYOUT_6POINT0_FRONT }, + { "hexagonal", 6, AV_CH_LAYOUT_HEXAGONAL }, + { "6.1", 7, AV_CH_LAYOUT_6POINT1 }, + { "6.1", 7, AV_CH_LAYOUT_6POINT1_BACK }, + { "6.1(front)", 7, AV_CH_LAYOUT_6POINT1_FRONT }, + { "7.0", 7, AV_CH_LAYOUT_7POINT0 }, + { "7.0(front)", 7, AV_CH_LAYOUT_7POINT0_FRONT }, + { "7.1", 8, AV_CH_LAYOUT_7POINT1 }, + { "7.1(wide)", 8, AV_CH_LAYOUT_7POINT1_WIDE }, + { "7.1(wide)", 8, AV_CH_LAYOUT_7POINT1_WIDE_BACK }, + { "octagonal", 8, AV_CH_LAYOUT_OCTAGONAL }, + { "downmix", 2, AV_CH_LAYOUT_STEREO_DOWNMIX, }, + { 0 } +}; + +static uint64_t get_channel_layout_single(const char *name, int name_len) +{ + int i; + char *end; + int64_t layout; + + for (i = 0; i < FF_ARRAY_ELEMS(channel_layout_map) - 1; i++) { + if (strlen(channel_layout_map[i].name) == name_len && + !memcmp(channel_layout_map[i].name, name, name_len)) + return channel_layout_map[i].layout; + } + for (i = 0; i < FF_ARRAY_ELEMS(channel_names); i++) + if (channel_names[i] && + strlen(channel_names[i]) == name_len && + !memcmp(channel_names[i], name, name_len)) + return (int64_t)1 << i; + i = strtol(name, &end, 10); + if (end - name == name_len || + (end + 1 - name == name_len && *end == 'c')) + return av_get_default_channel_layout(i); + layout = strtoll(name, &end, 0); + if (end - name == name_len) + return FFMAX(layout, 0); + return 0; +} + +uint64_t av_get_channel_layout(const char *name) +{ + const char *n, *e; + const char *name_end = name + strlen(name); + int64_t layout = 0, layout_single; + + for (n = name; n < name_end; n = e + 1) { + for (e = n; e < name_end && *e != '+' && *e != '|'; e++); + layout_single = get_channel_layout_single(n, e - n); + if (!layout_single) + return 0; + layout |= layout_single; + } + return layout; +} + +void av_get_channel_layout_string(char *buf, int buf_size, + int nb_channels, uint64_t channel_layout) +{ + int i; + + if (nb_channels <= 0) + nb_channels = av_get_channel_layout_nb_channels(channel_layout); + + for (i = 0; channel_layout_map[i].name; i++) + if (nb_channels == channel_layout_map[i].nb_channels && + channel_layout == channel_layout_map[i].layout) { + av_strlcpy(buf, channel_layout_map[i].name, buf_size); + return; + } + + snprintf(buf, buf_size, "%d channels", nb_channels); + if (channel_layout) { + int i, ch; + av_strlcat(buf, " (", buf_size); + for (i = 0, ch = 0; i < 64; i++) { + if ((channel_layout & (UINT64_C(1) << i))) { + const char *name = get_channel_name(i); + if (name) { + if (ch > 0) + av_strlcat(buf, "|", buf_size); + av_strlcat(buf, name, buf_size); + } + ch++; + } + } + av_strlcat(buf, ")", buf_size); + } +} + +int av_get_channel_layout_nb_channels(uint64_t channel_layout) +{ + return av_popcount64(channel_layout); +} + +uint64_t av_get_default_channel_layout(int nb_channels) +{ + switch(nb_channels) { + case 1: return AV_CH_LAYOUT_MONO; + case 2: return AV_CH_LAYOUT_STEREO; + case 3: return AV_CH_LAYOUT_SURROUND; + case 4: return AV_CH_LAYOUT_QUAD; + case 5: return AV_CH_LAYOUT_5POINT0; + case 6: return AV_CH_LAYOUT_5POINT1; + case 7: return AV_CH_LAYOUT_6POINT1; + case 8: return AV_CH_LAYOUT_7POINT1; + default: return 0; + } +} + +int av_get_channel_layout_channel_index(uint64_t channel_layout, + uint64_t channel) +{ + if (!(channel_layout & channel) || + av_get_channel_layout_nb_channels(channel) != 1) + return AVERROR(EINVAL); + channel_layout &= channel - 1; + return av_get_channel_layout_nb_channels(channel_layout); +} + +const char *av_get_channel_name(uint64_t channel) +{ + int i; + if (av_get_channel_layout_nb_channels(channel) != 1) + return NULL; + for (i = 0; i < 64; i++) + if ((1ULL< +#include +#include +#include + + +#define _COMPONENT ACPI_EXECUTER + ACPI_MODULE_NAME ("exoparg3") + + +/*! + * Naming convention for AML interpreter execution routines. + * + * The routines that begin execution of AML opcodes are named with a common + * convention based upon the number of arguments, the number of target operands, + * and whether or not a value is returned: + * + * AcpiExOpcode_xA_yT_zR + * + * Where: + * + * xA - ARGUMENTS: The number of arguments (input operands) that are + * required for this opcode type (1 through 6 args). + * yT - TARGETS: The number of targets (output operands) that are required + * for this opcode type (0, 1, or 2 targets). + * zR - RETURN VALUE: Indicates whether this opcode type returns a value + * as the function return (0 or 1). + * + * The AcpiExOpcode* functions are called via the Dispatcher component with + * fully resolved operands. +!*/ + + +/******************************************************************************* + * + * FUNCTION: acpi_ex_opcode_3A_0T_0R + * + * PARAMETERS: walk_state - Current walk state + * + * RETURN: Status + * + * DESCRIPTION: Execute Triadic operator (3 operands) + * + ******************************************************************************/ + +acpi_status +acpi_ex_opcode_3A_0T_0R ( + struct acpi_walk_state *walk_state) +{ + union acpi_operand_object **operand = &walk_state->operands[0]; + struct acpi_signal_fatal_info *fatal; + acpi_status status = AE_OK; + + + ACPI_FUNCTION_TRACE_STR ("ex_opcode_3A_0T_0R", + acpi_ps_get_opcode_name (walk_state->opcode)); + + + switch (walk_state->opcode) { + case AML_FATAL_OP: /* Fatal (fatal_type fatal_code fatal_arg) */ + + ACPI_DEBUG_PRINT ((ACPI_DB_INFO, + "fatal_op: Type %X Code %X Arg %X <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n", + (u32) operand[0]->integer.value, + (u32) operand[1]->integer.value, + (u32) operand[2]->integer.value)); + + fatal = ACPI_MEM_ALLOCATE (sizeof (struct acpi_signal_fatal_info)); + if (fatal) { + fatal->type = (u32) operand[0]->integer.value; + fatal->code = (u32) operand[1]->integer.value; + fatal->argument = (u32) operand[2]->integer.value; + } + + /* Always signal the OS! */ + + status = acpi_os_signal (ACPI_SIGNAL_FATAL, fatal); + + /* Might return while OS is shutting down, just continue */ + + ACPI_MEM_FREE (fatal); + break; + + + default: + + ACPI_REPORT_ERROR (("acpi_ex_opcode_3A_0T_0R: Unknown opcode %X\n", + walk_state->opcode)); + status = AE_AML_BAD_OPCODE; + goto cleanup; + } + + +cleanup: + + return_ACPI_STATUS (status); +} + + +/******************************************************************************* + * + * FUNCTION: acpi_ex_opcode_3A_1T_1R + * + * PARAMETERS: walk_state - Current walk state + * + * RETURN: Status + * + * DESCRIPTION: Execute Triadic operator (3 operands) + * + ******************************************************************************/ + +acpi_status +acpi_ex_opcode_3A_1T_1R ( + struct acpi_walk_state *walk_state) +{ + union acpi_operand_object **operand = &walk_state->operands[0]; + union acpi_operand_object *return_desc = NULL; + char *buffer; + acpi_status status = AE_OK; + acpi_integer index; + acpi_size length; + + + ACPI_FUNCTION_TRACE_STR ("ex_opcode_3A_1T_1R", + acpi_ps_get_opcode_name (walk_state->opcode)); + + + switch (walk_state->opcode) { + case AML_MID_OP: /* Mid (Source[0], Index[1], Length[2], Result[3]) */ + + /* + * Create the return object. The Source operand is guaranteed to be + * either a String or a Buffer, so just use its type. + */ + return_desc = acpi_ut_create_internal_object ( + ACPI_GET_OBJECT_TYPE (operand[0])); + if (!return_desc) { + status = AE_NO_MEMORY; + goto cleanup; + } + + /* Get the Integer values from the objects */ + + index = operand[1]->integer.value; + length = (acpi_size) operand[2]->integer.value; + + /* + * If the index is beyond the length of the String/Buffer, or if the + * requested length is zero, return a zero-length String/Buffer + */ + if ((index < operand[0]->string.length) && + (length > 0)) { + /* Truncate request if larger than the actual String/Buffer */ + + if ((index + length) > + operand[0]->string.length) { + length = (acpi_size) operand[0]->string.length - + (acpi_size) index; + } + + /* Allocate a new buffer for the String/Buffer */ + + buffer = ACPI_MEM_CALLOCATE ((acpi_size) length + 1); + if (!buffer) { + status = AE_NO_MEMORY; + goto cleanup; + } + + /* Copy the portion requested */ + + ACPI_MEMCPY (buffer, operand[0]->string.pointer + index, + length); + + /* Set the length of the new String/Buffer */ + + return_desc->string.pointer = buffer; + return_desc->string.length = (u32) length; + } + + /* Mark buffer initialized */ + + return_desc->buffer.flags |= AOPOBJ_DATA_VALID; + break; + + + default: + + ACPI_REPORT_ERROR (("acpi_ex_opcode_3A_0T_0R: Unknown opcode %X\n", + walk_state->opcode)); + status = AE_AML_BAD_OPCODE; + goto cleanup; + } + + /* Store the result in the target */ + + status = acpi_ex_store (return_desc, operand[3], walk_state); + +cleanup: + + /* Delete return object on error */ + + if (ACPI_FAILURE (status)) { + acpi_ut_remove_reference (return_desc); + } + + /* Set the return object and exit */ + + if (!walk_state->result_obj) { + walk_state->result_obj = return_desc; + } + return_ACPI_STATUS (status); +} + + diff --git a/pool/shard000/C/0008930_q2.c b/pool/shard000/C/0008930_q2.c new file mode 100644 index 0000000000000000000000000000000000000000..35e2839bdd7d5d7c2f114a8fab84f854a11680e0 --- /dev/null +++ b/pool/shard000/C/0008930_q2.c @@ -0,0 +1,54 @@ +/* { dg-do run } */ + +#include + +#include "init2.h" +#include "dump.h" + +#ifdef __cplusplus +extern "C" +#endif +void abort (void); + +int main (void) +{ + struct R1 A1 = My_R1; + struct R1 B1 = My_R1; + + struct R2 A2 = My_R2; + struct R2 B2 = My_R2; + + put ("A1 :"); + dump (&A1, sizeof (struct R1)); + new_line (); + /* { dg-output "A1 : e2 59 d1 48 b4 aa d9 bb.*\n" } */ + + put ("B1 :"); + dump (&B1, sizeof (struct R1)); + new_line (); + /* { dg-output "B1 : e2 59 d1 48 b4 aa d9 bb.*\n" } */ + + put ("A2 :"); + dump (&A2, sizeof (struct R2)); + new_line (); + /* { dg-output "A2 : 84 8d 15 9e 15 5b 35 df.*\n" } */ + + put ("B2 :"); + dump (&B2, sizeof (struct R2)); + new_line (); + /* { dg-output "B2 : 84 8d 15 9e 15 5b 35 df.*\n" } */ + + if (A1.S1 != B1.S1) abort (); + + if (A1.S1 != 2) abort (); + + if (A2.S1 != B2.S1) abort (); + + if (A2.S1 != 2) abort (); + + if (A1.I != B1.I || A1.A1 != B1.A1) abort (); + + if (A2.I != B2.I || A2.A1 != B2.A1) abort (); + + return 0; +} diff --git a/pool/shard000/C/0008968_mirandr.c b/pool/shard000/C/0008968_mirandr.c new file mode 100644 index 0000000000000000000000000000000000000000..81bf7f7f0c4ff8951b6d9943a2df43797340db29 --- /dev/null +++ b/pool/shard000/C/0008968_mirandr.c @@ -0,0 +1,98 @@ +/* + * $XFree86: xc/programs/Xserver/randr/mirandr.c,v 1.7 2002/10/14 18:01:42 keithp Exp $ + * + * Copyright © 2000, Compaq Computer Corporation, + * Copyright © 2002, Hewlett Packard, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and its + * documentation for any purpose is hereby granted without fee, provided that + * the above copyright notice appear in all copies and that both that + * copyright notice and this permission notice appear in supporting + * documentation, and that the name of Compaq or HP not be used in advertising + * or publicity pertaining to distribution of the software without specific, + * written prior permission. HP makes no representations about the + * suitability of this software for any purpose. It is provided "as is" + * without express or implied warranty. + * + * HP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL HP + * BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION + * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Author: Jim Gettys, HP Labs, Hewlett-Packard, Inc. + */ + + +#include "scrnintstr.h" +#include "mi.h" +#include "randr.h" +#include "randrstr.h" +#include + +/* + * This function assumes that only a single depth can be + * displayed at a time, but that all visuals of that depth + * can be displayed simultaneously. It further assumes that + * only a single size is available. Hardware providing + * additional capabilties should use different code. + * XXX what to do here.... + */ + +Bool +miRRGetInfo (ScreenPtr pScreen, Rotation *rotations) +{ + int i; + Bool setConfig = FALSE; + + *rotations = RR_Rotate_0; + for (i = 0; i < pScreen->numDepths; i++) + { + if (pScreen->allowedDepths[i].numVids) + { + RRScreenSizePtr pSize; + + pSize = RRRegisterSize (pScreen, + pScreen->width, + pScreen->height, + pScreen->mmWidth, + pScreen->mmHeight); + if (!pSize) + return FALSE; + if (!setConfig) + { + RRSetCurrentConfig (pScreen, RR_Rotate_0, 0, pSize); + setConfig = TRUE; + } + } + } + return TRUE; +} + +/* + * Any hardware that can actually change anything will need something + * different here + */ +Bool +miRRSetConfig (ScreenPtr pScreen, + Rotation rotation, + int rate, + RRScreenSizePtr pSize) +{ + return TRUE; +} + + +Bool +miRandRInit (ScreenPtr pScreen) +{ + rrScrPrivPtr rp; + + if (!RRScreenInit (pScreen)) + return FALSE; + rp = rrGetScrPriv(pScreen); + rp->rrGetInfo = miRRGetInfo; + rp->rrSetConfig = miRRSetConfig; + return TRUE; +} diff --git a/pool/shard000/C/0008975_findsuper.c b/pool/shard000/C/0008975_findsuper.c new file mode 100644 index 0000000000000000000000000000000000000000..6b5e16fc1cdd1c775dd95440fd0c8bb34ab33d49 --- /dev/null +++ b/pool/shard000/C/0008975_findsuper.c @@ -0,0 +1,265 @@ +/* + * findsuper --- quick hacked up program to find ext2 superblocks. + * + * This is a hack, and really shouldn't be installed anywhere. If you + * need a program which does this sort of functionality, please try + * using gpart program. + * + * Portions Copyright 1998-2000, Theodore Ts'o. + * + * Well, here's my linux version of findsuper. + * I'm sure you coulda done it faster. :) + * IMHO there isn't as much interesting data to print in the + * linux superblock as there is in the SunOS superblock--disk geometry is + * not there...and linux seems to update the dates in all the superblocks. + * SunOS doesn't ever touch the backup superblocks after the fs is created, + * as far as I can tell, so the date is more interesting IMHO and certainly + * marks which superblocks are backup ones. + * + * I wanted to add msdos support, but I couldn't make heads or tails + * of the kernel include files to find anything I could look for in msdos. + * + * Reading every block of a Sun partition is fairly quick. Doing the + * same under linux (slower hardware I suppose) just isn't the same. + * It might be more useful to default to reading the first (second?) block + * on each cyl; however, if the disk geometry is wrong, this is useless. + * But ya could still get the cyl size to print the numbers as cyls instead + * of blocks... + * + * run this as (for example) + * findsuper /dev/hda + * findsuper /dev/hda 437760 1024 (my disk has cyls of 855*512) + * + * I suppose the next step is to figgure out a way to determine if + * the block found is the first superblock somehow, and if so, build + * a partition table from the superblocks found... but this is still + * useful as is. + * + * Steve + * ssd@nevets.oau.org + * ssd@mae.engr.ucf.edu + * + * Additional notes by Andreas Dilger : + * - fixed to support > 2G devices by using lseek64 + * - add reliability checking for the superblock to avoid random garbage + * - add adaptive progress meter + * + * It _should_ also handle signals and tell you the ending block, so + * that you can resume at a later time, but it doesn't yet... + * + * Note that gpart does not appear to find all superblocks that aren't aligned + * with the start of a possible partition, so it is not useful in systems + * with LVM or similar setups which don't use fat partition alignment. + * + * %Begin-Header% + * This file may be redistributed under the terms of the GNU Public + * License. + * %End-Header% + */ + +/* + * Documentation addendum added by Andreas dwguest@win.tue.nl/aeb@cwi.nl + * + * The program findsuper is a utility that scans a disk and finds + * copies of ext2 superblocks (by checking for the ext2 signature). + * + * For each superblock found, it prints the offset in bytes, the + * offset in 1024-byte blocks, the size of the ext2 partition in fs + * blocks, the filesystem blocksize (in bytes), the block group number + * (always 0 for older ext2 systems), and a timestamp (s_mtime). + * + * This program can be used to retrieve partitions that have been + * lost. The superblock for block group 0 is found 1 block (2 + * sectors) after the partition start. + * + * For new systems that have a block group number in the superblock it + * is immediately clear which superblock is the first of a partition. + * For old systems where no group numbers are given, the first + * superblock can be recognised by the timestamp: all superblock + * copies have the creation time in s_mtime, except the first, which + * has the last time e2fsck or tune2fs wrote to the filesystem. + * + */ + +#define _FILE_OFFSET_BITS 64 + +#include "config.h" +#include +#include +#include +#include +#include +#include +#include + +#include "ext2fs/ext2_fs.h" +#include "ext2fs/ext2fs.h" +#include "nls-enable.h" + +#undef DEBUG + +#ifdef DEBUG +#define WHY(fmt, arg...) { printf("\r%Ld: " fmt, sk, ##arg) ; continue; } +#else +#define WHY(fmt, arg...) { continue; } +#endif + +static void usage(void) +{ + fprintf(stderr, + _("Usage: findsuper device [skipbytes [startkb]]\n")); + exit(1); +} + + +int main(int argc, char *argv[]) +{ + int skiprate=512; /* one sector */ + loff_t sk=0, skl=0; + int fd; + char *s; + time_t tm, last = time(0); + loff_t interval = 1024 * 1024; + int c, print_jnl_copies = 0; + const char * device_name; + struct ext2_super_block ext2; + /* interesting fields: EXT2_SUPER_MAGIC + * s_blocks_count s_log_block_size s_mtime s_magic s_lastcheck */ + +#ifdef ENABLE_NLS + setlocale(LC_MESSAGES, ""); + setlocale(LC_CTYPE, ""); + bindtextdomain(NLS_CAT_NAME, LOCALEDIR); + textdomain(NLS_CAT_NAME); + set_com_err_gettext(gettext); +#endif + + while ((c = getopt (argc, argv, "j")) != EOF) { + switch (c) { + case 'j': + print_jnl_copies++; + break; + default: + usage(); + } + } + + if (optind == argc) + usage(); + + device_name = argv[optind++]; + + if (optind < argc) { + skiprate = strtol(argv[optind], &s, 0); + if (s == argv[optind]) { + fprintf(stderr,_("skipbytes should be a number, not %s\n"), s); + exit(1); + } + optind++; + } + if (skiprate & 0x1ff) { + fprintf(stderr, + _("skipbytes must be a multiple of the sector size\n")); + exit(2); + } + if (optind < argc) { + sk = skl = strtoll(argv[optind], &s, 0) << 10; + if (s == argv[optind]) { + fprintf(stderr, + _("startkb should be a number, not %s\n"), s); + exit(1); + } + optind++; + } + if (sk < 0) { + fprintf(stderr, _("startkb should be positive, not %Lu\n"), sk); + exit(1); + } + + fd = open(device_name, O_RDONLY); + if (fd < 0) { + perror(device_name); + exit(1); + } + + /* Now, go looking for the superblock! */ + printf(_("starting at %Lu, with %u byte increments\n"), sk, skiprate); + if (print_jnl_copies) + printf(_("[*] probably superblock written in the ext3 " + "journal superblock,\n\tso start/end/grp wrong\n")); + printf(_("byte_offset byte_start byte_end fs_blocks blksz grp last_mount_time sb_uuid label\n")); + for (; lseek64(fd, sk, SEEK_SET) != -1 && + read(fd, &ext2, 512) == 512; sk += skiprate) { + static unsigned char last_uuid[16] = "blah"; + unsigned long long bsize, grpsize; + int jnl_copy, sb_offset; + + if (sk && !(sk & (interval - 1))) { + time_t now, diff; + + now = time(0); + diff = now - last; + + if (diff > 0) { + s = ctime(&now); + s[24] = 0; + printf("\r%11Lu: %8LukB/s @ %s", sk, + (((sk - skl)) / diff) >> 10, s); + fflush(stdout); + } + if (diff < 5) + interval <<= 1; + else if (diff > 20) + interval >>= 1; + last = now; + skl = sk; + } + if (ext2.s_magic != EXT2_SUPER_MAGIC) + continue; + if (ext2.s_log_block_size > 6) + WHY("log block size > 6 (%u)\n", ext2.s_log_block_size); + if (ext2fs_r_blocks_count(&ext2) > ext2fs_blocks_count(&ext2)) + WHY("r_blocks_count > blocks_count (%u > %u)\n", + ext2fs_r_blocks_count(&ext2), + ext2fs_blocks_count(&ext2)); + if (ext2fs_free_blocks_count(&ext2) > ext2fs_blocks_count(&ext2)) + WHY("free_blocks_count > blocks_count\n (%u > %u)\n", + ext2fs_free_blocks_count(&ext2), + ext2fs_blocks_count(&ext2)); + if (ext2.s_free_inodes_count > ext2.s_inodes_count) + WHY("free_inodes_count > inodes_count (%u > %u)\n", + ext2.s_free_inodes_count, ext2.s_inodes_count); + + tm = ext2.s_mtime; + s = ctime(&tm); + s[24] = 0; + bsize = 1 << (ext2.s_log_block_size + 10); + grpsize = bsize * ext2.s_blocks_per_group; + if (memcmp(ext2.s_uuid, last_uuid, sizeof(last_uuid)) == 0 && + ext2.s_rev_level > 0 && ext2.s_block_group_nr == 0) { + jnl_copy = 1; + } else { + jnl_copy = 0; + memcpy(last_uuid, ext2.s_uuid, sizeof(last_uuid)); + } + if (ext2.s_block_group_nr == 0 || bsize == 1024) + sb_offset = 1024; + else + sb_offset = 0; + if (jnl_copy && !print_jnl_copies) + continue; + printf("\r%11Lu %11Lu%s %11Lu%s %9u %5Lu %4u%s %s %02x%02x%02x%02x %s\n", + sk, sk - ext2.s_block_group_nr * grpsize - sb_offset, + jnl_copy ? "*":" ", + sk + ext2fs_blocks_count(&ext2) * bsize - + ext2.s_block_group_nr * grpsize - sb_offset, + jnl_copy ? "*" : " ", ext2fs_blocks_count(&ext2), bsize, + ext2.s_block_group_nr, jnl_copy ? "*" : " ", s, + ext2.s_uuid[0], ext2.s_uuid[1], + ext2.s_uuid[2], ext2.s_uuid[3], ext2.s_volume_name); + } + printf(_("\n%11Lu: finished with errno %d\n"), sk, errno); + close(fd); + + return errno; +} diff --git a/pool/shard000/C/0008989_nuse-vif-rawsock.c b/pool/shard000/C/0008989_nuse-vif-rawsock.c new file mode 100644 index 0000000000000000000000000000000000000000..99f708e48da3ed8ba581fe500d052e6c291a5bf6 --- /dev/null +++ b/pool/shard000/C/0008989_nuse-vif-rawsock.c @@ -0,0 +1,110 @@ +/* + * raw socket based virtual network interface feature for NUSE + * Copyright (c) 2015 Hajime Tazaki + * + * Author: Hajime Tazaki + */ + +#include +#include +#include +#include +#include +#include +#define _GNU_SOURCE /* Get RTLD_NEXT */ +#include +#include +#include +#include +#include +#include "nuse-hostcalls.h" +#include "nuse-vif.h" +#include "nuse.h" +#include "nuse-libc.h" + +void +nuse_vif_raw_read(struct nuse_vif *vif, struct SimDevice *dev) +{ + int sock = vif->sock; + char buf[8192]; + ssize_t size; + + while (1) { + size = host_read(sock, buf, sizeof(buf)); + if (size < 0) { + printf("read error errno=%d\n", errno); + host_close(sock); + return; + } else if (size == 0) { + printf("read error: closed. errno=%d\n", errno); + host_close(sock); + return; + } + + nuse_dev_rx(dev, buf, size); + } + + printf("%s: should not reach", __func__); +} + +void +nuse_vif_raw_write(struct nuse_vif *vif, struct SimDevice *dev, + unsigned char *data, int len) +{ + int sock = vif->sock; + int ret = host_write(sock, data, len); + + if (ret == -1) + perror("write"); +} + +void * +nuse_vif_raw_create(const char *ifname) +{ + int err; + int sock = host_socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL)); + struct sockaddr_ll ll; + struct nuse_vif *vif; + + if (sock < 0) + perror("socket"); + + memset(&ll, 0, sizeof(ll)); + + ll.sll_family = AF_PACKET; + ll.sll_ifindex = if_nametoindex(ifname); + ll.sll_protocol = htons(ETH_P_ALL); + err = host_bind(sock, (struct sockaddr *)&ll, sizeof(ll)); + if (err) + perror("bind"); + + vif = malloc(sizeof(struct nuse_vif)); + vif->sock = sock; + vif->type = NUSE_VIF_RAWSOCK; /* FIXME */ + return vif; +} + +void +nuse_vif_raw_delete(struct nuse_vif *vif) +{ + int sock = vif->sock; + free(vif); + host_close(sock); +} + +static struct nuse_vif_impl nuse_vif_rawsock = { + .read = nuse_vif_raw_read, + .write = nuse_vif_raw_write, + .create = nuse_vif_raw_create, + .delete = nuse_vif_raw_delete, +}; + +extern struct nuse_vif_impl *nuse_vif[NUSE_VIF_MAX]; + +int __attribute__((constructor)) +nuse_vif_rawsock_init(void) +{ + nuse_vif[NUSE_VIF_RAWSOCK] = &nuse_vif_rawsock; + return 0; +} +__define_initcall(nuse_vif_rawsock_init, 1); diff --git a/pool/shard000/C/0008994_main.c b/pool/shard000/C/0008994_main.c new file mode 100644 index 0000000000000000000000000000000000000000..46f9e4c114dad45b03bc7c7a37a66f06fc60df87 --- /dev/null +++ b/pool/shard000/C/0008994_main.c @@ -0,0 +1,233 @@ +/* + * Copyright (c) 1983-2013 Trevor Wishart and Composers Desktop Project Ltd + * http://www.trevorwishart.co.uk + * http://www.composersdesktop.com + * + This file is part of the CDP System. + + The CDP System is free software; you can redistribute it + and/or modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The CDP System is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the CDP System; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA + * + */ + + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +char errstr[2400]; + +/*extern*/ int sloom = 0; +/*extern*/ int sloombatch = 0; +/*extern*/ int anal_infiles = 1; +/*extern*/ int is_converted_to_stereo = -1; +const char* cdp_version = "7.1.0"; + +/**************************************** MAIN *********************************************/ + +int main(int argc,char *argv[]) +{ + int exit_status; + dataptr dz = NULL; + char **cmdline; + int cmdlinecnt; + //aplptr ap; + int *valid = NULL; + int is_launched = FALSE; + int validcnt; + + if(argc==2 && (strcmp(argv[1],"--version") == 0)) { + fprintf(stdout,"%s\n",cdp_version); + fflush(stdout); + return 0; + } + /* CHECK FOR SOUNDLOOM */ + if((sloom = sound_loom_in_use(&argc,&argv)) > 1) { + sloom = 0; + sloombatch = 1; + } + + if(!sloom) { + if((exit_status = allocate_and_initialise_validity_flags(&valid,&validcnt))<0) { + print_messages_and_close_sndfiles(exit_status,is_launched,dz); + return(FAILED); + } + } + + if(sflinit("cdp")){ + sfperror("cdp: initialisation\n"); + return(FAILED); + } + + /* SET UP THE PRINCIPLE DATASTRUCTURE */ + if((exit_status = establish_datastructure(&dz))<0) { + print_messages_and_close_sndfiles(exit_status,is_launched,dz); + return(FAILED); + } + + if(!sloom) { + /* INITIAL CHECK OF CMDLINE DATA */ + if((exit_status = make_initial_cmdline_check(&argc,&argv))<0) { + print_messages_and_close_sndfiles(exit_status,is_launched,dz); + return(FAILED); + } + cmdline = argv; /* GET PRE_DATA, ALLOCATE THE APPLICATION, CHECK FOR EXTRA INFILES */ + cmdlinecnt = argc; + if((exit_status = get_process_and_mode_from_cmdline(&cmdlinecnt,&cmdline,dz))<0) { + print_messages_and_close_sndfiles(exit_status,is_launched,dz); + return(FAILED); + } + if((exit_status = setup_particular_application(dz))<0) { + print_messages_and_close_sndfiles(exit_status,is_launched,dz); + return(FAILED); + } + if((exit_status = count_and_allocate_for_infiles(cmdlinecnt,cmdline,dz))<0) { + print_messages_and_close_sndfiles(exit_status,is_launched,dz); + return(FAILED); + } + } else { + if((exit_status = parse_tk_data(argc,argv,&cmdline,&cmdlinecnt,dz))<0) { /* includes setup_particular_application() */ + exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);/* and cmdlinelength check = sees extra-infiles */ + return(exit_status); + } + } + + //ap = dz->application; + + /********************************************************************************************************************* + cmdline[0] 2 vals ACTIVE +TK (infile) (more-infiles) (outfile) (flag val) (formantsqksrch) (special) params options variant-params flags +CMDLINE (infile) (more-infiles) (outfile) (formants) (formantsqksrch) (special) params POSSIBLY POSSIBLY POSSIBLY + 1 val + *********************************************************************************************************************/ + + if((exit_status = parse_infile_and_hone_type(cmdline[0],valid,dz))<0) { + print_messages_and_close_sndfiles(exit_status,is_launched,dz); + return(FAILED); + } + + if((exit_status = setup_param_ranges_and_defaults(dz))<0) { + print_messages_and_close_sndfiles(exit_status,is_launched,dz); + return(FAILED); + } + + /* OPEN FIRST INFILE AND STORE DATA, AND INFORMATION, APPROPRIATELY */ + + if(dz->input_data_type!=NO_FILE_AT_ALL) { + if((exit_status = open_first_infile(cmdline[0],dz))<0) { + print_messages_and_close_sndfiles(exit_status,is_launched,dz); + return(FAILED); + } + //TW UPDATE + cmdlinecnt--; + cmdline++; + } + + /********************************************************************************************************************* + cmdline[0] 2 vals ACTIVE +TK (more-infiles) (outfile) (flag val) (formantsqksrch) (special) params options variant-params flags +CMDLINE (more-infiles) (outfile) (formants) (formantsqksrch) (special) params POSSIBLY POSSIBLY POSSIBLY + 1 val + *********************************************************************************************************************/ + + if((exit_status = handle_extra_infiles(&cmdline,&cmdlinecnt,dz))<0) { + print_messages_and_close_sndfiles(exit_status,is_launched,dz); + return(FAILED); + } + + /********************************************************************************************************************* + cmdline[0] 2 ACTIVE +TK (outfile) (flag val) (formantsqksrch) (special) params options variant-params flags +CMDLINE (outfile) (formants) (formantsqksrch) (special) params POSSIBLY POSSIBLY POSSIBLY + 1 + *********************************************************************************************************************/ + + if((exit_status = handle_outfile(&cmdlinecnt,&cmdline,is_launched,dz))<0) { + print_messages_and_close_sndfiles(exit_status,is_launched,dz); + return(FAILED); + } + + /**************************************************************************************** + cmdline[0] ACTIVE +TK (flag val) (formantsqksrch) (special) params options variant-params flags +CMDLINE (formants) (formantsqksrch) (special) params POSSIBLY POSSIBLY POSSIBLY + *****************************************************************************************/ + + if((exit_status = handle_formants(&cmdlinecnt,&cmdline,dz))<0) { + print_messages_and_close_sndfiles(exit_status,is_launched,dz); + return(FAILED); + } + if((exit_status = handle_formant_quiksearch(&cmdlinecnt,&cmdline,dz))<0) { + print_messages_and_close_sndfiles(exit_status,is_launched,dz); + return(FAILED); + } + if((exit_status = handle_special_data(&cmdlinecnt,&cmdline,dz))<0) { + print_messages_and_close_sndfiles(exit_status,is_launched,dz); + return(FAILED); + } + + /**************************************************************************************** + cmdline[0] +TK active_params options variant-params flags +CMDLINE active_params POSSIBLY POSSIBLY POSSIBLY + *****************************************************************************************/ + + if((exit_status = read_parameters_and_flags(&cmdline,&cmdlinecnt,dz))<0) { + print_messages_and_close_sndfiles(exit_status,is_launched,dz); + return(FAILED); + } + + if((exit_status = check_param_validity_and_consistency(dz))<0) { + print_messages_and_close_sndfiles(exit_status,is_launched,dz); + return(FAILED); + } + + is_launched = TRUE; + + if((exit_status = allocate_large_buffers(dz))<0){ + print_messages_and_close_sndfiles(exit_status,is_launched,dz); + return(FAILED); + } + if((exit_status = param_preprocess(dz))<0){ + print_messages_and_close_sndfiles(exit_status,is_launched,dz); + return(FAILED); + } + if((exit_status = spec_process_file(dz))<0) { + print_messages_and_close_sndfiles(exit_status,is_launched,dz); + return(FAILED); + } + if((exit_status = complete_output(dz))<0) { + print_messages_and_close_sndfiles(exit_status,is_launched,dz); + return(FAILED); + } + exit_status = print_messages_and_close_sndfiles(FINISHED,is_launched,dz); + free(dz); + return(SUCCEEDED); +} diff --git a/pool/shard000/C/0008997_lines.c b/pool/shard000/C/0008997_lines.c new file mode 100644 index 0000000000000000000000000000000000000000..706d12af0aaec8fcb710816a9ef2821438ebc123 --- /dev/null +++ b/pool/shard000/C/0008997_lines.c @@ -0,0 +1,78 @@ +#include +#include + +#include "clint.h" + +static unsigned maximum_length; +static bool disallow_trailing_space; +static bool require_newline_at_eof; +static const char *line_break; + + +static void configure(void) +{ + if ((maximum_length = cfg_natural("maximum-length")) == 0) + maximum_length = -1; + + disallow_trailing_space = cfg_boolean("disallow-trailing-space"); + line_break = cfg_string("require-line-break"); + require_newline_at_eof = cfg_boolean("require-newline-at-eof"); +} + + +static unsigned utf8_len(const char *line, unsigned size) +{ + unsigned length = 0; + + for (unsigned i = 0; i < size; ++i) + if ((line[i] & 0xc0) != 0x80) + ++length; + + return length; +} + + +static void check(void) +{ + bool check_lb = !!line_break; + unsigned lb_length = check_lb ? strlen(line_break) : 0; + unsigned i = 0; + const char *line; + unsigned length; + + for (; i < vec_len(g_lines); ++i) + { + line = g_lines[i].start; + length = g_lines[i].length; + + if (length == 0) + continue; + + if (disallow_trailing_space && isspace(line[length - 1])) + { + unsigned column = length - 1; + + while (column && isspace(line[column])) + --column; + + add_warn(i, column + 1, "Trailing witespaces are disallowed"); + } + + if (length > maximum_length && utf8_len(line, length) > maximum_length) + add_warn(i, maximum_length, + "Line must be at most %d characters", maximum_length); + + if (check_lb && line[length]) + if (strncmp(line + length, line_break, lb_length)) + { + add_warn(i, length, "Invalid line break"); + check_lb = false; + } + } + + if (require_newline_at_eof && g_lines[i - 1].length > 0) + add_warn(i - 1, length, "Required newline at eof"); +} + + +REGISTER_RULE(lines, configure, check); diff --git a/pool/shard000/C/0008999_irq.c b/pool/shard000/C/0008999_irq.c new file mode 100644 index 0000000000000000000000000000000000000000..0d17e757e3e1c05208b15ec0d0dfed679532d35c --- /dev/null +++ b/pool/shard000/C/0008999_irq.c @@ -0,0 +1,214 @@ +/* $Id$ + * + * linux/arch/cris/kernel/irq.c + * + * Copyright (c) 2000-2002 Axis Communications AB + * + * Authors: Bjorn Wesen (bjornw@axis.com) + * + * This file contains the interrupt vectors and some + * helper functions + * + */ + +#include +#include +#include +#include +#include + +#define mask_irq(irq_nr) (*R_VECT_MASK_CLR = 1 << (irq_nr)); +#define unmask_irq(irq_nr) (*R_VECT_MASK_SET = 1 << (irq_nr)); + +/* don't use set_int_vector, it bypasses the linux interrupt handlers. it is + * global just so that the kernel gdb can use it. + */ + +void +set_int_vector(int n, irqvectptr addr) +{ + etrax_irv->v[n + 0x20] = (irqvectptr)addr; +} + +/* the breakpoint vector is obviously not made just like the normal irq handlers + * but needs to contain _code_ to jump to addr. + * + * the BREAK n instruction jumps to IBR + n * 8 + */ + +void +set_break_vector(int n, irqvectptr addr) +{ + unsigned short *jinstr = (unsigned short *)&etrax_irv->v[n*2]; + unsigned long *jaddr = (unsigned long *)(jinstr + 1); + + /* if you don't know what this does, do not touch it! */ + + *jinstr = 0x0d3f; + *jaddr = (unsigned long)addr; + + /* 00000026 3f0d82000000 jump 0x82 */ +} + +/* + * This builds up the IRQ handler stubs using some ugly macros in irq.h + * + * These macros create the low-level assembly IRQ routines that do all + * the operations that are needed. They are also written to be fast - and to + * disable interrupts as little as humanly possible. + * + */ + +/* IRQ0 and 1 are special traps */ +void hwbreakpoint(void); +void IRQ1_interrupt(void); +BUILD_TIMER_IRQ(2, 0x04) /* the timer interrupt is somewhat special */ +BUILD_IRQ(3, 0x08) +BUILD_IRQ(4, 0x10) +BUILD_IRQ(5, 0x20) +BUILD_IRQ(6, 0x40) +BUILD_IRQ(7, 0x80) +BUILD_IRQ(8, 0x100) +BUILD_IRQ(9, 0x200) +BUILD_IRQ(10, 0x400) +BUILD_IRQ(11, 0x800) +BUILD_IRQ(12, 0x1000) +BUILD_IRQ(13, 0x2000) +void mmu_bus_fault(void); /* IRQ 14 is the bus fault interrupt */ +void multiple_interrupt(void); /* IRQ 15 is the multiple IRQ interrupt */ +BUILD_IRQ(16, 0x10000) +BUILD_IRQ(17, 0x20000) +BUILD_IRQ(18, 0x40000) +BUILD_IRQ(19, 0x80000) +BUILD_IRQ(20, 0x100000) +BUILD_IRQ(21, 0x200000) +BUILD_IRQ(22, 0x400000) +BUILD_IRQ(23, 0x800000) +BUILD_IRQ(24, 0x1000000) +BUILD_IRQ(25, 0x2000000) +/* IRQ 26-30 are reserved */ +BUILD_IRQ(31, 0x80000000) + +/* + * Pointers to the low-level handlers + */ + +static void (*interrupt[NR_IRQS])(void) = { + NULL, NULL, IRQ2_interrupt, IRQ3_interrupt, + IRQ4_interrupt, IRQ5_interrupt, IRQ6_interrupt, IRQ7_interrupt, + IRQ8_interrupt, IRQ9_interrupt, IRQ10_interrupt, IRQ11_interrupt, + IRQ12_interrupt, IRQ13_interrupt, NULL, NULL, + IRQ16_interrupt, IRQ17_interrupt, IRQ18_interrupt, IRQ19_interrupt, + IRQ20_interrupt, IRQ21_interrupt, IRQ22_interrupt, IRQ23_interrupt, + IRQ24_interrupt, IRQ25_interrupt, NULL, NULL, NULL, NULL, NULL, + IRQ31_interrupt +}; + +static void enable_crisv10_irq(unsigned int irq); + +static unsigned int startup_crisv10_irq(unsigned int irq) +{ + enable_crisv10_irq(irq); + return 0; +} + +#define shutdown_crisv10_irq disable_crisv10_irq + +static void enable_crisv10_irq(unsigned int irq) +{ + unmask_irq(irq); +} + +static void disable_crisv10_irq(unsigned int irq) +{ + mask_irq(irq); +} + +static void ack_crisv10_irq(unsigned int irq) +{ +} + +static void end_crisv10_irq(unsigned int irq) +{ +} + +static struct hw_interrupt_type crisv10_irq_type = { + .typename = "CRISv10", + .startup = startup_crisv10_irq, + .shutdown = shutdown_crisv10_irq, + .enable = enable_crisv10_irq, + .disable = disable_crisv10_irq, + .ack = ack_crisv10_irq, + .end = end_crisv10_irq, + .set_affinity = NULL +}; + +void weird_irq(void); +void system_call(void); /* from entry.S */ +void do_sigtrap(void); /* from entry.S */ +void gdb_handle_breakpoint(void); /* from entry.S */ + +/* init_IRQ() is called by start_kernel and is responsible for fixing IRQ masks and + setting the irq vector table. +*/ + +void __init +init_IRQ(void) +{ + int i; + + /* clear all interrupt masks */ + +#ifndef CONFIG_SVINTO_SIM + *R_IRQ_MASK0_CLR = 0xffffffff; + *R_IRQ_MASK1_CLR = 0xffffffff; + *R_IRQ_MASK2_CLR = 0xffffffff; +#endif + + *R_VECT_MASK_CLR = 0xffffffff; + + for (i = 0; i < 256; i++) + etrax_irv->v[i] = weird_irq; + + /* Initialize IRQ handler descriptiors. */ + for(i = 2; i < NR_IRQS; i++) { + irq_desc[i].handler = &crisv10_irq_type; + set_int_vector(i, interrupt[i]); + } + + /* the entries in the break vector contain actual code to be + executed by the associated break handler, rather than just a jump + address. therefore we need to setup a default breakpoint handler + for all breakpoints */ + + for (i = 0; i < 16; i++) + set_break_vector(i, do_sigtrap); + + /* except IRQ 15 which is the multiple-IRQ handler on Etrax100 */ + + set_int_vector(15, multiple_interrupt); + + /* 0 and 1 which are special breakpoint/NMI traps */ + + set_int_vector(0, hwbreakpoint); + set_int_vector(1, IRQ1_interrupt); + + /* and irq 14 which is the mmu bus fault handler */ + + set_int_vector(14, mmu_bus_fault); + + /* setup the system-call trap, which is reached by BREAK 13 */ + + set_break_vector(13, system_call); + + /* setup a breakpoint handler for debugging used for both user and + kernel mode debugging (which is why it is not inside an ifdef + CONFIG_ETRAX_KGDB) */ + set_break_vector(8, gdb_handle_breakpoint); + +#ifdef CONFIG_ETRAX_KGDB + /* setup kgdb if its enabled, and break into the debugger */ + kgdb_init(); + breakpoint(); +#endif +} diff --git a/pool/shard000/C/0009043_mddi_ext_lcd.c b/pool/shard000/C/0009043_mddi_ext_lcd.c new file mode 100644 index 0000000000000000000000000000000000000000..0c7226319acc8dd18caee96621cf969de234a0c1 --- /dev/null +++ b/pool/shard000/C/0009043_mddi_ext_lcd.c @@ -0,0 +1,86 @@ +/* Copyright (c) 2008-2009, Code Aurora Forum. All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 and + * only version 2 as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +#include "msm_fb.h" +#include "mddihost.h" +#include "mddihosti.h" + +static int mddi_ext_lcd_on(struct platform_device *pdev); +static int mddi_ext_lcd_off(struct platform_device *pdev); + +static int mddi_ext_lcd_on(struct platform_device *pdev) +{ + return 0; +} + +static int mddi_ext_lcd_off(struct platform_device *pdev) +{ + return 0; +} + +static int __init mddi_ext_lcd_probe(struct platform_device *pdev) +{ + msm_fb_add_device(pdev); + + return 0; +} + +static struct platform_driver this_driver = { + .probe = mddi_ext_lcd_probe, + .driver = { + .name = "extmddi_svga", + }, +}; + +static struct msm_fb_panel_data mddi_ext_lcd_panel_data = { + .panel_info.xres = 800, + .panel_info.yres = 600, + .panel_info.type = EXT_MDDI_PANEL, + .panel_info.pdest = DISPLAY_1, + .panel_info.wait_cycle = 0, + .panel_info.bpp = 18, + .panel_info.fb_num = 2, + .panel_info.clk_rate = 122880000, + .panel_info.clk_min = 120000000, + .panel_info.clk_max = 125000000, + .on = mddi_ext_lcd_on, + .off = mddi_ext_lcd_off, +}; + +static struct platform_device this_device = { + .name = "extmddi_svga", + .id = 0, + .dev = { + .platform_data = &mddi_ext_lcd_panel_data, + } +}; + +static int __init mddi_ext_lcd_init(void) +{ + int ret; + struct msm_panel_info *pinfo; + + ret = platform_driver_register(&this_driver); + if (!ret) { + pinfo = &mddi_ext_lcd_panel_data.panel_info; + pinfo->lcd.vsync_enable = FALSE; + pinfo->mddi.vdopkt = MDDI_DEFAULT_PRIM_PIX_ATTR; + + ret = platform_device_register(&this_device); + if (ret) + platform_driver_unregister(&this_driver); + } + + return ret; +} + +module_init(mddi_ext_lcd_init); diff --git a/pool/shard000/C/0009048_misc.c b/pool/shard000/C/0009048_misc.c new file mode 100644 index 0000000000000000000000000000000000000000..106642b23ac5f5f19780a539303b4ed08a966a6e --- /dev/null +++ b/pool/shard000/C/0009048_misc.c @@ -0,0 +1,55 @@ +/* Copyright 2016 Bloq, Inc. + * Distributed under the MIT/X11 software license, see the accompanying + * file COPYING or http://www.opensource.org/licenses/mit-license.php. + */ +#include "picocoin-config.h" + +#include +#include +#include +#include +#include "libtest.h" + +static void test_checkpoints(void) +{ + bool rc; + const char *hexstr; + bu256_t tmp; + + hexstr = "0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d"; + rc = hex_bu256(&tmp, hexstr); + assert(rc == true); + + // in list; pass + rc = bp_ckpt_block(CHAIN_BITCOIN, 11111, &tmp); + assert(rc == true); + + // not in list; pass + rc = bp_ckpt_block(CHAIN_BITCOIN, 11112, &tmp); + assert(rc == true); + + hexstr = "0x11111111111111111111111111111111111111111111192559f542fdb26e7c1d"; + rc = hex_bu256(&tmp, hexstr); + assert(rc == true); + + // in list, mismatch hash; fail + rc = bp_ckpt_block(CHAIN_BITCOIN, 11111, &tmp); + assert(rc == false); + + assert(bp_ckpt_last(CHAIN_BITCOIN) == 193000); + assert(bp_ckpt_last(CHAIN_TESTNET3) == 546); +} + +static void test_log(void) +{ + char time_buf[32]; + char *p = str_timenow(time_buf); + assert(p == &time_buf[0]); +} + +int main (int argc, char *argv[]) +{ + test_checkpoints(); + test_log(); + return 0; +} diff --git a/pool/shard000/C/0009050_tiny-shmem.c b/pool/shard000/C/0009050_tiny-shmem.c new file mode 100644 index 0000000000000000000000000000000000000000..aa0ad4f81c4030f4ab97523443df07ad51ba7229 --- /dev/null +++ b/pool/shard000/C/0009050_tiny-shmem.c @@ -0,0 +1,139 @@ +/* + * tiny-shmem.c: simple shmemfs and tmpfs using ramfs code + * + * Matt Mackall January, 2004 + * derived from mm/shmem.c and fs/ramfs/inode.c + * + * This is intended for small system where the benefits of the full + * shmem code (swap-backed and resource-limited) are outweighed by + * their complexity. On systems without swap this code should be + * effectively equivalent, but much lighter weight. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static struct file_system_type tmpfs_fs_type = { + .name = "tmpfs", + .get_sb = ramfs_get_sb, + .kill_sb = kill_litter_super, +}; + +static struct vfsmount *shm_mnt; + +static int __init init_tmpfs(void) +{ + BUG_ON(register_filesystem(&tmpfs_fs_type) != 0); + + shm_mnt = kern_mount(&tmpfs_fs_type); + BUG_ON(IS_ERR(shm_mnt)); + + return 0; +} +module_init(init_tmpfs) + +/** + * shmem_file_setup - get an unlinked file living in tmpfs + * @name: name for dentry (to be seen in /proc//maps + * @size: size to be set for the file + * @flags: vm_flags + */ +struct file *shmem_file_setup(char *name, loff_t size, unsigned long flags) +{ + int error; + struct file *file; + struct inode *inode; + struct dentry *dentry, *root; + struct qstr this; + + if (IS_ERR(shm_mnt)) + return (void *)shm_mnt; + + error = -ENOMEM; + this.name = name; + this.len = strlen(name); + this.hash = 0; /* will go */ + root = shm_mnt->mnt_root; + dentry = d_alloc(root, &this); + if (!dentry) + goto put_memory; + + error = -ENOSPC; + inode = ramfs_get_inode(root->d_sb, S_IFREG | S_IRWXUGO, 0); + if (!inode) + goto put_dentry; + + d_instantiate(dentry, inode); + error = -ENFILE; + file = alloc_file(shm_mnt, dentry, FMODE_WRITE | FMODE_READ, + &ramfs_file_operations); + if (!file) + goto put_dentry; + + inode->i_nlink = 0; /* It is unlinked */ + + /* notify everyone as to the change of file size */ + error = do_truncate(dentry, size, 0, file); + if (error < 0) + goto close_file; + + return file; + +close_file: + put_filp(file); + return ERR_PTR(error); + +put_dentry: + dput(dentry); +put_memory: + return ERR_PTR(error); +} + +void shmem_set_file(struct vm_area_struct *vma, struct file *file) +{ + if (vma->vm_file) + fput(vma->vm_file); + vma->vm_file = file; + vma->vm_ops = &generic_file_vm_ops; +} + +/** + * shmem_zero_setup - setup a shared anonymous mapping + * @vma: the vma to be mmapped is prepared by do_mmap_pgoff + */ +int shmem_zero_setup(char *name, struct vm_area_struct *vma) +{ + struct file *file; + loff_t size = vma->vm_end - vma->vm_start; + + file = shmem_file_setup(name, size, vma->vm_flags); + if (IS_ERR(file)) + return PTR_ERR(file); + + shmem_set_file(vma, file); + + return 0; +} + +int shmem_unuse(swp_entry_t entry, struct page *page) +{ + return 0; +} + +#ifndef CONFIG_MMU +unsigned long shmem_get_unmapped_area(struct file *file, + unsigned long addr, + unsigned long len, + unsigned long pgoff, + unsigned long flags) +{ + return ramfs_nommu_get_unmapped_area(file, addr, len, pgoff, flags); +} +#endif diff --git a/pool/shard000/C/0009057_ctrl_btn.c b/pool/shard000/C/0009057_ctrl_btn.c new file mode 100644 index 0000000000000000000000000000000000000000..2e48cf59074963b441818fed626135e905773937 --- /dev/null +++ b/pool/shard000/C/0009057_ctrl_btn.c @@ -0,0 +1,109 @@ +/* + * btn.c + * + * Created on: Feb 4, 2017 + * Author: kris + * + * This file is part of OpenAirProject-ESP32. + * + * OpenAirProject-ESP32 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. + * + * OpenAirProject-ESP32 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 OpenAirProject-ESP32. If not, see . + */ + + +#include +#include +#include +#include +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "oap_common.h" +#include "ctrl_btn.h" +#include "esp_log.h" +#include "esp_err.h" +#include "driver/gpio.h" +#include "freertos/queue.h" + +#define ESP_INTR_FLAG_DEFAULT 0 +#define TAG "btn" + +typedef struct { + uint8_t gpio_num; + uint32_t timestamp; +} gpio_event_t; + +static QueueHandle_t gpio_evt_queue; +static uint32_t last_click = 0; +static btn_callback_f _callback = NULL; + +static void IRAM_ATTR gpio_isr_handler(void* arg) +{ + uint32_t t = millis(); + /* + * TODO is there a way to programmatically eliminate flickering? + */ + if (t - last_click < 80) return; + last_click = t; + gpio_event_t gpio_evt = { + .gpio_num = (uint8_t)(uint32_t)arg, + .timestamp = t + }; + xQueueSendFromISR(gpio_evt_queue, &gpio_evt, NULL); +} + +static void gpio_watchdog_task() { + gpio_event_t gpio_evt; + int count = 0; + uint32_t first_click = 0; + + while(1) { + if (xQueueReceive(gpio_evt_queue, &gpio_evt, 1000)) { + _callback(SINGLE_CLICK); + //20 sec to perform the action + if (!first_click || gpio_evt.timestamp - first_click > 20000) { + first_click = gpio_evt.timestamp; + count = 0; + } + count++; + ESP_LOGD(TAG, "click gpio[%d] [%d in sequence]",gpio_evt.gpio_num, count); + + //due to flickering we cannot precisely count all clicks anyway + if (count == 10) { + _callback(MANY_CLICKS); + } + if (count >= 20) { + _callback(TOO_MANY_CLICKS); + first_click=0; + count=0; + } + } + } +} + +esp_err_t btn_configure(btn_callback_f callback) { + _callback = callback; + gpio_evt_queue = xQueueCreate(10, sizeof(gpio_event_t)); + gpio_pad_select_gpio(CONFIG_OAP_BTN_0_PIN); + gpio_set_direction(CONFIG_OAP_BTN_0_PIN, GPIO_MODE_INPUT); + gpio_set_pull_mode(CONFIG_OAP_BTN_0_PIN, GPIO_PULLDOWN_ONLY); + gpio_set_intr_type(CONFIG_OAP_BTN_0_PIN, GPIO_INTR_POSEDGE); + gpio_install_isr_service(ESP_INTR_FLAG_DEFAULT); + gpio_isr_handler_add(CONFIG_OAP_BTN_0_PIN, gpio_isr_handler, (void*) CONFIG_OAP_BTN_0_PIN); + xTaskCreate((TaskFunction_t)gpio_watchdog_task, "gpio_watchdog_task", 1024*2, NULL, DEFAULT_TASK_PRIORITY+2, NULL); + return ESP_OK; //TODO handle errors +} + +bool is_ap_mode_pressed() { + return gpio_get_level(CONFIG_OAP_BTN_0_PIN); +} + diff --git a/pool/shard000/C/0009079_ijksdl_vout_overlay_android_mediacodec.c b/pool/shard000/C/0009079_ijksdl_vout_overlay_android_mediacodec.c new file mode 100644 index 0000000000000000000000000000000000000000..0d1a9ed44097357d3464a0ff5dc25f67c77206e0 --- /dev/null +++ b/pool/shard000/C/0009079_ijksdl_vout_overlay_android_mediacodec.c @@ -0,0 +1,190 @@ +/***************************************************************************** + * ijksdl_vout_overlay_android_mediacodec.c + ***************************************************************************** + * + * copyright (c) 2014 Zhang Rui + * + * This file is part of ijkPlayer. + * + * ijkPlayer is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * ijkPlayer is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with ijkPlayer; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "ijksdl_vout_overlay_android_mediacodec.h" +#include +#include "ijksdl/ijksdl_stdinc.h" +#include "ijksdl/ijksdl_mutex.h" +#include "ijksdl/ijksdl_vout_internal.h" +#include "ijksdl/ijksdl_video.h" +#include "ijksdl_vout_android_nativewindow.h" +#include "ijksdl_codec_android_mediacodec.h" +#include "ijksdl_inc_internal_android.h" + +#ifndef AMCTRACE +#define AMCTRACE(...) +#endif + +typedef struct SDL_VoutOverlay_Opaque { + SDL_mutex *mutex; + + SDL_Vout *vout; + SDL_AMediaCodec *acodec; + + SDL_AMediaCodecBufferProxy *buffer_proxy; + + Uint16 pitches[AV_NUM_DATA_POINTERS]; + Uint8 *pixels[AV_NUM_DATA_POINTERS]; +} SDL_VoutOverlay_Opaque; + +static int overlay_lock(SDL_VoutOverlay *overlay) +{ + SDL_VoutOverlay_Opaque *opaque = overlay->opaque; + return SDL_LockMutex(opaque->mutex); +} + +static int overlay_unlock(SDL_VoutOverlay *overlay) +{ + SDL_VoutOverlay_Opaque *opaque = overlay->opaque; + return SDL_UnlockMutex(opaque->mutex); +} + +static void overlay_unref(SDL_VoutOverlay *overlay) +{ + SDL_VoutOverlay_Opaque *opaque = overlay->opaque; + + SDL_VoutAndroid_releaseBufferProxyP(opaque->vout, &opaque->buffer_proxy, false); +} + +static void overlay_free_l(SDL_VoutOverlay *overlay) +{ + AMCTRACE("SDL_Overlay(ffmpeg): overlay_free_l(%p)\n", overlay); + if (!overlay) + return; + + SDL_VoutOverlay_Opaque *opaque = overlay->opaque; + if (!opaque) + return; + + overlay_unref(overlay); + + if (opaque->mutex) + SDL_DestroyMutex(opaque->mutex); + + SDL_VoutOverlay_FreeInternal(overlay); +} + +static SDL_Class g_vout_overlay_amediacodec_class = { + .name = "AndroidMediaCodecVoutOverlay", +}; + +inline static bool check_object(SDL_VoutOverlay* object, const char *func_name) +{ + if (!object || !object->opaque || !object->opaque_class) { + ALOGE("%s.%s: invalid pipeline\n", object->opaque_class->name, func_name); + return false; + } + + if (object->opaque_class != &g_vout_overlay_amediacodec_class) { + ALOGE("%s.%s: unsupported method\n", object->opaque_class->name, func_name); + return false; + } + + return true; +} + +static int func_fill_frame(SDL_VoutOverlay *overlay, const AVFrame *frame) +{ + assert(frame->format == IJK_AV_PIX_FMT__ANDROID_MEDIACODEC); + + SDL_VoutOverlay_Opaque *opaque = overlay->opaque; + + if (!check_object(overlay, __func__)) + return -1; + + if (opaque->buffer_proxy) + SDL_VoutAndroid_releaseBufferProxyP(opaque->vout, (SDL_AMediaCodecBufferProxy **)&opaque->buffer_proxy, false); + + opaque->acodec = SDL_VoutAndroid_peekAMediaCodec(opaque->vout); + // TODO: ref-count buffer_proxy? + opaque->buffer_proxy = (SDL_AMediaCodecBufferProxy *)frame->opaque; + + overlay->opaque_class = &g_vout_overlay_amediacodec_class; + overlay->format = SDL_FCC__AMC; + overlay->planes = 1; + overlay->pixels[0] = NULL; + overlay->pixels[1] = NULL; + overlay->pitches[0] = 0; + overlay->pitches[1] = 0; + overlay->is_private = 1; + + overlay->w = (int)frame->width; + overlay->h = (int)frame->height; + return 0; +} + +SDL_VoutOverlay *SDL_VoutAMediaCodec_CreateOverlay(int width, int height, SDL_Vout *vout) +{ + SDLTRACE("SDL_VoutAMediaCodec_CreateOverlay(w=%d, h=%d, fmt=_AMC vout=%p)\n", + width, height, vout); + SDL_VoutOverlay *overlay = SDL_VoutOverlay_CreateInternal(sizeof(SDL_VoutOverlay_Opaque)); + if (!overlay) { + ALOGE("overlay allocation failed"); + return NULL; + } + + SDL_VoutOverlay_Opaque *opaque = overlay->opaque; + opaque->mutex = SDL_CreateMutex(); + opaque->vout = vout; + opaque->acodec = NULL; + opaque->buffer_proxy = NULL; + + overlay->opaque_class = &g_vout_overlay_amediacodec_class; + overlay->format = SDL_FCC__AMC; + overlay->pitches = opaque->pitches; + overlay->pixels = opaque->pixels; + overlay->w = width; + overlay->h = height; + overlay->is_private = 1; + + overlay->free_l = overlay_free_l; + overlay->lock = overlay_lock; + overlay->unlock = overlay_unlock; + overlay->unref = overlay_unref; + overlay->func_fill_frame = func_fill_frame; + + if (!opaque->mutex) { + ALOGE("SDL_CreateMutex failed"); + goto fail; + } + + return overlay; + +fail: + overlay_free_l(overlay); + return NULL; +} + +bool SDL_VoutOverlayAMediaCodec_isKindOf(SDL_VoutOverlay *overlay) +{ + return check_object(overlay, __func__); +} + +int SDL_VoutOverlayAMediaCodec_releaseFrame_l(SDL_VoutOverlay *overlay, SDL_AMediaCodec *acodec, bool render) +{ + if (!check_object(overlay, __func__)) + return -1; + + SDL_VoutOverlay_Opaque *opaque = overlay->opaque; + return SDL_VoutAndroid_releaseBufferProxyP_l(opaque->vout, &opaque->buffer_proxy, render); +} diff --git a/pool/shard000/C/0009080_drop_str.c b/pool/shard000/C/0009080_drop_str.c new file mode 100644 index 0000000000000000000000000000000000000000..526757570abfc9bb62fe92bb1778f65e6921ccd6 --- /dev/null +++ b/pool/shard000/C/0009080_drop_str.c @@ -0,0 +1,27 @@ +/* + module : drop_str.c + version : 1.2 + date : 03/01/21 +*/ +#ifndef DROP_STR_C +#define DROP_STR_C + +/** +drop_str : A N -> B +Aggregate B is the result of deleting the first N elements of A. +*/ +void do_drop_str(void) +{ + intptr_t Value; + char *str, *result; + + BINARY; + Value = do_pop(); + str = (char *)stack[-1]; + while (Value-- > 0 && *str) + str++; + result = GC_malloc_atomic(strlen(str) + 2); + sprintf(result, "\"%s", str); + stack[-1] = (intptr_t)result | JLAP_INVALID; +} +#endif diff --git a/pool/shard000/C/0009081_slots.c b/pool/shard000/C/0009081_slots.c new file mode 100644 index 0000000000000000000000000000000000000000..4bb87032c8bf4019508d06bd426c26a939cd0b6c --- /dev/null +++ b/pool/shard000/C/0009081_slots.c @@ -0,0 +1,145 @@ +/* + +Author: Debbie Nuttall + +Copyright (c) 2015 Cromulence LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +*/ + +#include +#include "stdlib.h" +#include "slots.h" +#include "casino.h" +#include "prng.h" + + +// Print the slot machine state +void print_board(int board_size, unsigned char board[][board_size]) +{ + for (int y=0; y '5')) + { + return; + } + int board_size = input - '0'; + + while (input != 'q') + { + if (player->wallet >= 2) + { + player->wallet -= 2; + } + player->slots_score += 1; + unsigned char board[board_size][board_size]; + bzero(board, sizeof(board)); + + // Adjust number of characters used to control odds of winning + char max_char = '/'; + switch(board_size) + { + case 3: + max_char = '!' + 6; + break; + case 4: + max_char = '!' + 4; + break; + case 5: + max_char = '!' + 2; + break; + } + + // Generate board + for (int x=0; x < board_size; x++) + { + for(int y=0; y < board_size; y++) + { + board[x][y] = random_in_range('!', max_char); + } + } + print_board(board_size, board); + + // Check for a win + // Column check + int x, y; + for (x = 0; x < board_size; x++) + { + for (y = 1; y < board_size; y++) + { + if (board[x][y] != board[x][0]) + { + break; + } + } + if (y == board_size) + { + printf("Column match: @d!\n", x); + if (player) + { + player->wallet += payouts[SLOTS_COLUMN_MATCH]; + } + } + } + + // Row check + for (y = 0; y < board_size; y++) + { + for (x = 1; x < board_size; x++) + { + if (board[x][y] != board[0][y]) + { + break; + } + } + if (x == board_size) + { + printf("Row match: @d!\n", y); + if (player) + { + player->wallet += payouts[SLOTS_ROW_MATCH]; + } + } + } + printf("Enter q to quit, any other key to play again:"); + receive_fixed_input(&input, '\n', sizeof(input)); + } +} \ No newline at end of file diff --git a/pool/shard000/C/0009091_msm_dma.c b/pool/shard000/C/0009091_msm_dma.c new file mode 100644 index 0000000000000000000000000000000000000000..274713db5fb1ab3f644b3c86637afe5f0ecb7da7 --- /dev/null +++ b/pool/shard000/C/0009091_msm_dma.c @@ -0,0 +1,177 @@ +/********************************************************************** + * MSM DMA driver tester. + * + * Copyright (c) 2008 Qualcomm Technologies, Inc. + * All Rights Reserved. Qualcomm Technologies Proprietary and Confidential. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "dma_test.h" + +#define BUFFER_SIZE 16384 + +int buf[2]; + +char tmp_buffer[2][BUFFER_SIZE]; + +void set_pattern(char *buf, unsigned seed) +{ + int i; + unsigned *lbuf = (unsigned *) buf; + + assert(((long) buf & 3) == 0); + + for (i = 0; i < BUFFER_SIZE/4; i++) { + lbuf[i] = seed; + if (seed & 1) + seed = (seed >> 1) ^ 0x80000057; + else + seed >>= 1; + } +} + +void check_pattern(char *buf, unsigned seed) +{ + int i; + unsigned *lbuf = (unsigned *) buf; + + assert(((long) buf & 3) == 0); + + for (i = 0; i < BUFFER_SIZE/4; i++) { + if (lbuf[i] != seed) { + printf("Buffer comparison mismatch\n"); + exit(1); + } + if (seed & 1) + seed = (seed >> 1) ^ 0x80000057; + else + seed >>= 1; + } +} + +int alloc_buffer(int fd, int size) +{ + int res; + struct msm_dma_alloc_req req; + + req.size = size; + res = ioctl(fd, MSM_DMA_IOALLOC, &req); + if (res != 0) { + perror(__FUNCTION__); + exit(1); + } + + return req.bufnum; +} + +void free_all(int fd) +{ + int res; + + res = ioctl(fd, MSM_DMA_IOFREEALL, NULL); + if (res != 0) { + perror(__FUNCTION__); + exit(1); + } +} + +void write_data(int fd, int bufnum, void *data, int size) +{ + int res; + struct msm_dma_bufxfer req; + + req.data = data; + req.size = size; + req.bufnum = bufnum; + + res = ioctl(fd, MSM_DMA_IOWBUF, &req); + if (res != 0) { + perror(__FUNCTION__); + exit(1); + } +} + +void read_data(int fd, int bufnum, void *data, int size) +{ + int res; + struct msm_dma_bufxfer req; + + req.data = data; + req.size = size; + req.bufnum = bufnum; + + res = ioctl(fd, MSM_DMA_IORBUF, &req); + if (res != 0) { + perror(__FUNCTION__); + exit(1); + } +} + +void copy_buffer(int fd, int src, int dest, int size) +{ + struct msm_dma_scopy req; + + req.srcbuf = src; + req.destbuf = dest; + req.size = size; + if (ioctl(fd, MSM_DMA_IOSCOPY, &req) != 0) { + perror(__FUNCTION__); + exit(1); + } +} + +int main(int argc, char **argv) +{ + int fd; + int i; + + fd = open("/dev/msmdma", O_RDWR); + if (fd < 0) { + perror("Unable to open /dev/msmdma"); + exit(1); + } + + free_all(fd); + + for (i = 0; i < 2; i++) { + buf[i] = alloc_buffer(fd, BUFFER_SIZE); + printf("Got user buffer %d for %d\n", buf[i], i); + } + + set_pattern(tmp_buffer[0], 1); + write_data(fd, 0, tmp_buffer[0], BUFFER_SIZE); + + set_pattern(tmp_buffer[1], 2); + write_data(fd, 1, tmp_buffer[1], BUFFER_SIZE); + + memset(tmp_buffer[0], 0, BUFFER_SIZE); + memset(tmp_buffer[1], 0, BUFFER_SIZE); + + read_data(fd, 0, tmp_buffer[0], BUFFER_SIZE); + check_pattern(tmp_buffer[0], 1); + + read_data(fd, 1, tmp_buffer[0], BUFFER_SIZE); + check_pattern(tmp_buffer[0], 2); + + memset(tmp_buffer[0], 0, BUFFER_SIZE); + memset(tmp_buffer[1], 0, BUFFER_SIZE); + + copy_buffer(fd, 0, 1, BUFFER_SIZE); + read_data(fd, 0, tmp_buffer[0], BUFFER_SIZE); + check_pattern(tmp_buffer[0], 1); + read_data(fd, 1, tmp_buffer[1], BUFFER_SIZE); + check_pattern(tmp_buffer[1], 1); + + close (fd); + + exit(0); +} diff --git a/pool/shard000/C/0009102_bgp_attr_evpn.c b/pool/shard000/C/0009102_bgp_attr_evpn.c new file mode 100644 index 0000000000000000000000000000000000000000..5b24d4ec61318909f40d2ef0117afa8abbdabac3 --- /dev/null +++ b/pool/shard000/C/0009102_bgp_attr_evpn.c @@ -0,0 +1,141 @@ +/* Ethernet-VPN Attribute handling file + Copyright (C) 2016 6WIND + +This file is part of FRRouting. + +FRRouting is free software; you can redistribute it and/or modify it +under the terms of the GNU General Public License as published by the +Free Software Foundation; either version 2, or (at your option) any +later version. + +FRRouting 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 FRRouting; see the file COPYING. If not, write to the Free +Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA +02111-1307, USA. */ + +#include + +#include "command.h" +#include "filter.h" +#include "prefix.h" +#include "log.h" +#include "memory.h" +#include "stream.h" + +#include "bgpd/bgpd.h" +#include "bgpd/bgp_attr.h" +#include "bgpd/bgp_route.h" +#include "bgpd/bgp_attr_evpn.h" +#include "bgpd/bgp_ecommunity.h" +#include "bgpd/bgp_evpn.h" + +void bgp_add_routermac_ecom(struct attr *attr, struct ethaddr *routermac) +{ + struct ecommunity_val routermac_ecom; + + if (attr->extra) { + memset(&routermac_ecom, 0, sizeof(struct ecommunity_val)); + routermac_ecom.val[0] = ECOMMUNITY_ENCODE_EVPN; + routermac_ecom.val[1] = ECOMMUNITY_EVPN_SUBTYPE_ROUTERMAC; + memcpy(&routermac_ecom.val[2], routermac->octet, ETHER_ADDR_LEN); + if (!attr->extra->ecommunity) + attr->extra->ecommunity = ecommunity_new(); + ecommunity_add_val(attr->extra->ecommunity, &routermac_ecom); + ecommunity_str (attr->extra->ecommunity); + } +} + +/* converts to an esi + * returns 1 on success, 0 otherwise + * format accepted: AA:BB:CC:DD:EE:FF:GG:HH:II:JJ + * if id is null, check only is done + */ +int str2esi(const char *str, struct eth_segment_id *id) +{ + unsigned int a[ESI_LEN]; + int i; + + if (!str) + return 0; + if (sscanf (str, "%2x:%2x:%2x:%2x:%2x:%2x:%2x:%2x:%2x:%2x", + a + 0, a + 1, a + 2, a + 3, a + 4, a + 5, + a + 6, a + 7, a + 8, a + 9) != ESI_LEN) + { + /* error in incoming str length */ + return 0; + } + /* valid mac address */ + if (!id) + return 1; + for (i = 0; i < ESI_LEN; ++i) + id->val[i] = a[i] & 0xff; + return 1; +} + +char *esi2str(struct eth_segment_id *id) +{ + char *ptr; + u_char *val; + + if (!id) + return NULL; + + val = id->val; + ptr = (char *)XMALLOC(MTYPE_TMP, (ESI_LEN * 2 + ESI_LEN - 1 + 1) * sizeof(char)); + + snprintf(ptr, (ESI_LEN * 2 + ESI_LEN - 1 + 1), + "%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x", + val[0], val[1], val[2], val[3], val[4], + val[5], val[6], val[7], val[8], val[9]); + + return ptr; +} + +char *ecom_mac2str(char *ecom_mac) +{ + char *en; + + en = ecom_mac; + en += 2; + return prefix_mac2str((struct ethaddr *)en, NULL, 0); +} + +/* dst prefix must be AF_INET or AF_INET6 prefix, to forge EVPN prefix */ +extern int +bgp_build_evpn_prefix(int evpn_type, uint32_t eth_tag, struct prefix *dst) +{ + struct evpn_addr *p_evpn_p; + struct prefix p2; + struct prefix *src = &p2; + + if (!dst || dst->family == 0) + return -1; + /* store initial prefix in src */ + prefix_copy(src, dst); + memset(dst, 0, sizeof(struct prefix)); + p_evpn_p = &(dst->u.prefix_evpn); + dst->family = AF_ETHERNET; + p_evpn_p->route_type = evpn_type; + if (evpn_type == EVPN_IP_PREFIX) { + p_evpn_p->eth_tag = eth_tag; + p_evpn_p->ip_prefix_length = p2.prefixlen; + if (src->family == AF_INET) { + p_evpn_p->flags = IP_PREFIX_V4; + memcpy(&p_evpn_p->ip.v4_addr, &src->u.prefix4, + sizeof(struct in_addr)); + dst->prefixlen = (u_char) PREFIX_LEN_ROUTE_TYPE_5_IPV4; + } else { + p_evpn_p->flags = IP_PREFIX_V6; + memcpy(&p_evpn_p->ip.v6_addr, &src->u.prefix6, + sizeof(struct in6_addr)); + dst->prefixlen = (u_char) PREFIX_LEN_ROUTE_TYPE_5_IPV6; + } + } else + return -1; + return 0; +} diff --git a/pool/shard000/C/0009116_pvrusb2-cx2584x-v4l.c b/pool/shard000/C/0009116_pvrusb2-cx2584x-v4l.c new file mode 100644 index 0000000000000000000000000000000000000000..aa607d6b54860f845576ae8e23a8522ad03a62d3 --- /dev/null +++ b/pool/shard000/C/0009116_pvrusb2-cx2584x-v4l.c @@ -0,0 +1,116 @@ + + + + +#include "pvrusb2-cx2584x-v4l.h" +#include "pvrusb2-video-v4l.h" + + +#include "pvrusb2-hdw-internal.h" +#include "pvrusb2-debug.h" +#include +#include +#include +#include +#include + + +struct routing_scheme_item { + int vid; + int aud; +}; + +struct routing_scheme { + const struct routing_scheme_item *def; + unsigned int cnt; +}; + +static const struct routing_scheme_item routing_scheme0[] = { + [PVR2_CVAL_INPUT_TV] = { + .vid = CX25840_COMPOSITE7, + .aud = CX25840_AUDIO8, + }, + [PVR2_CVAL_INPUT_RADIO] = { + .vid = CX25840_COMPOSITE3, + .aud = CX25840_AUDIO_SERIAL, + }, + [PVR2_CVAL_INPUT_COMPOSITE] = { + .vid = CX25840_COMPOSITE3, + .aud = CX25840_AUDIO_SERIAL, + }, + [PVR2_CVAL_INPUT_SVIDEO] = { + .vid = CX25840_SVIDEO1, + .aud = CX25840_AUDIO_SERIAL, + }, +}; + +static const struct routing_scheme routing_def0 = { + .def = routing_scheme0, + .cnt = ARRAY_SIZE(routing_scheme0), +}; + + +static const struct routing_scheme_item routing_schemegv[] = { + [PVR2_CVAL_INPUT_TV] = { + .vid = CX25840_COMPOSITE2, + .aud = CX25840_AUDIO5, + }, + [PVR2_CVAL_INPUT_RADIO] = { + + .vid = CX25840_COMPOSITE1, + .aud = CX25840_AUDIO_SERIAL, + }, + [PVR2_CVAL_INPUT_COMPOSITE] = { + .vid = CX25840_COMPOSITE1, + .aud = CX25840_AUDIO_SERIAL, + }, + [PVR2_CVAL_INPUT_SVIDEO] = { + .vid = (CX25840_SVIDEO_LUMA3|CX25840_SVIDEO_CHROMA4), + .aud = CX25840_AUDIO_SERIAL, + }, +}; + +static const struct routing_scheme routing_defgv = { + .def = routing_schemegv, + .cnt = ARRAY_SIZE(routing_schemegv), +}; + +static const struct routing_scheme *routing_schemes[] = { + [PVR2_ROUTING_SCHEME_HAUPPAUGE] = &routing_def0, + [PVR2_ROUTING_SCHEME_GOTVIEW] = &routing_defgv, +}; + +void pvr2_cx25840_subdev_update(struct pvr2_hdw *hdw, struct v4l2_subdev *sd) +{ + pvr2_trace(PVR2_TRACE_CHIPS, "subdev cx2584x update..."); + if (hdw->input_dirty || hdw->force_dirty) { + enum cx25840_video_input vid_input; + enum cx25840_audio_input aud_input; + const struct routing_scheme *sp; + unsigned int sid = hdw->hdw_desc->signal_routing_scheme; + + sp = (sid < ARRAY_SIZE(routing_schemes)) ? + routing_schemes[sid] : NULL; + if ((sp == NULL) || + (hdw->input_val < 0) || + (hdw->input_val >= sp->cnt)) { + pvr2_trace(PVR2_TRACE_ERROR_LEGS, + "*** WARNING *** subdev cx2584x set_input:" + " Invalid routing scheme (%u)" + " and/or input (%d)", + sid, hdw->input_val); + return; + } + vid_input = sp->def[hdw->input_val].vid; + aud_input = sp->def[hdw->input_val].aud; + pvr2_trace(PVR2_TRACE_CHIPS, + "subdev cx2584x set_input vid=0x%x aud=0x%x", + vid_input, aud_input); + sd->ops->video->s_routing(sd, (u32)vid_input, 0, 0); + sd->ops->audio->s_routing(sd, (u32)aud_input, 0, 0); + } +} + + + + diff --git a/pool/shard000/C/0009134_ffopens.c b/pool/shard000/C/0009134_ffopens.c new file mode 100644 index 0000000000000000000000000000000000000000..525ca036737241138c4ca08716d1be5c2e698326 --- /dev/null +++ b/pool/shard000/C/0009134_ffopens.c @@ -0,0 +1,159 @@ +/* + + Copyright (C) 2000, 2001 Silicon Graphics, Inc. All Rights Reserved. + + This program is free software; you can redistribute it and/or modify it + under the terms of version 2.1 of the GNU Lesser General Public License + as published by the Free Software Foundation. + + This program is distributed in the hope that it would be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + + Further, this software is distributed without any warranty that it is + free of the rightful claim of any third person regarding infringement + or the like. Any license provided herein, whether implied or + otherwise, applies only to this software file. Patent licenses, if + any, provided herein do not apply to combinations of this program with + other software, or any other product whatsoever. + + You should have received a copy of the GNU Lesser General Public + License along with this program; if not, write the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307, + USA. + + Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky, + Mountain View, CA 94043, or: + + http://www.sgi.com + + For further information regarding this notice, see: + + http://oss.sgi.com/projects/GenInfo/NoticeExplan + +*/ + + +#pragma ident "@(#) libu/ffio/ffopens.c 92.3 10/29/99 21:40:31" + +#include +#include +#include +#include +#include +#include +#include "spec_parse.h" +#if defined(_UNICOS) || defined(__mips) || defined(_LITTLE_ENDIAN) +#include "fflock.h" +#endif + +#define MAX_SPEC 128 /* arbitrary limit on size of the layer list */ + +/* + * ffopens + * + * Open an FFIO file. Apply -F attribute specified by "cspec", which is + * of the same form as that used in assign and asgcmd, without the '-F'. + * ("cos:20,bmx") + * + * Calling sequence: + * + * fd = ffopens(name, flags, mode, cbits, [cblks,] stat, cspec); + * + * Return value: + * + * Positive integer (really a pointer on Cray MPP and PVP ) + * on success. -1 on failure with stat->sw_error + * set to the error code. + */ + +#if defined(__mips) || defined(_LITTLE_ENDIAN) +int +ffopens( +const char *name, +int flags, +mode_t mode, +long cbits, +int cblks, +struct ffsw *stat, +const char *cspec) + +#else +int +ffopens( +const char *name, +int flags, +int mode, +long cbits, +...) +#endif +{ + int retfd, length; + _ffopen_t fd; + union spec_u specs[MAX_SPEC]; +#if !defined(__mips) && !defined(_LITTLE_ENDIAN) + char *cspec; + int cblks; + struct ffsw *stat; + va_list ap; +#endif + struct gl_o_inf gloinf; + struct fdinfo *nfio; + +/* + * The cblks argument was not passed in UNICOS 7.0 and previous. + */ +#if !defined(__mips) && !defined(_LITTLE_ENDIAN) + va_start(ap, cbits); + + switch (_numargs()) { + case 6: + cblks = 0; + stat = va_arg(ap, struct ffsw *); + cspec = va_arg(ap, char *); + break; + default: /* 7 or more args */ + cblks = va_arg(ap, int); + stat = va_arg(ap, struct ffsw *); + cspec = va_arg(ap, char *); + break; + } + va_end(ap); +#endif + +/* + * Initialize global open information structure. + */ + (void) memset(&gloinf, 0, sizeof(gloinf)); + gloinf.aip = NULL; + + if (cspec == NULL) cspec = ""; + length = _parse_forstr(specs, cspec, MAX_SPEC, NO, _LELVL_RETURN); + if (length <= 0) + ERETURN(stat, FDC_ERR_BADSPC, 0); + + fd = _ffopen(name, flags, mode, specs, stat, cbits, cblks, NULL, + &gloinf); + +#if defined(_CRAY1) || defined(__mips) + if (fd != _FFOPEN_ERR && MULTI_ON) { + nfio = NULL; + if (_ff_top_lock(fd, &nfio, stat) < 0) + fd = _FFOPEN_ERR; + if (nfio != NULL) + fd = (_ffopen_t)nfio; + } +#endif +#if defined(__mips) || defined(_LITTLE_ENDIAN) + /* + * ffopens returns an int. Call a routine which associates an + * int with what is returned by _ffopen + */ + retfd = _ff_fdinfo_to_int(fd, stat); +#else + retfd = (int)fd; +#endif + + return(retfd); +} + diff --git a/pool/shard000/C/0009136_test.c b/pool/shard000/C/0009136_test.c new file mode 100644 index 0000000000000000000000000000000000000000..bf49559fa057ee44908da1e4746eb05d263382dc --- /dev/null +++ b/pool/shard000/C/0009136_test.c @@ -0,0 +1,237 @@ +/* + * carlu - userspace testing utility for ar9170 devices + * + * Various tests + * + * Copyright 2009-2011 Christian Lamparter + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include +#include +#include +#include +#include +#include "libusb.h" +#include "SDL.h" + +#include "carlu.h" +#include "debug.h" +#include "frame.h" +#include "usb.h" +#include "cmd.h" + +void debug_test(void) +{ + err("This is an error.\n"); + warn("This is a warnig.\n"); + info("This is an informative message.\n"); + dbg("This is just utter useless babble.\n"); +} + +void carlu_frame_test(struct carlu *ar) +{ + struct frame *frame; + + frame = carlu_alloc_frame(ar, 0x40); + frame_reserve(frame, 0x10); + + memset(frame_put(frame, 0x10), 0x11, 0x10); + memset(frame_put(frame, 0x10), 0x22, 0x10); + memset(frame_push(frame, 0x10), 0x33, 0x10); + memset(frame_put(frame, 0x10), 0x44, 0x10); + + print_hex_dump_bytes(INFO, "DATA:", frame->data, frame->len); + + print_hex_dump_bytes(INFO, "PAYLOAD:", frame->payload, frame->alloced); + + frame_free(frame); +} + +static void carlu_loopback_tx_cb(struct carlu *ar __unused, + struct frame *frame __unused) +{ +} + +static int carlu_loopback_cmd(struct carlu *ar __unused, + struct carl9170_rsp *cmd, void *buf __unused, + unsigned int len __unused) +{ + unsigned int i, n; + + switch (cmd->hdr.cmd) { + case CARL9170_RSP_TXCOMP: + n = cmd->hdr.ext; + dbg("received tx feedback (%d).\n", n); + + for (i = 0; i < n; i++) { + dbg("cookie:%x info:%x\n", + cmd->_tx_status[i].cookie, + cmd->_tx_status[i].info); + } + return -1; + + default: + return -1; + } +} + +static void carlu_loopback_rx(struct carlu *ar, + void *buf __unused, unsigned int len) +{ + ar->rxed++; + ar->rx_octets += len; +} + +static void carlu_loopback_mark_tx_frames(struct frame *frame) +{ + unsigned int i; + + for (i = 0; i < frame->len; i++) + frame->data[i] = (uint8_t) i; +} + +void carlu_loopback_test(struct carlu *ar, const unsigned int total_runs, + const unsigned int interval, const unsigned int min_len, const unsigned int max_len) +{ + struct frame *frame; + uint32_t start_time, total_time = 0; + float moctets, dtime; + unsigned int runs = 0, i = 0, j = 0, len; + int ret; + + if (min_len > max_len) { + err("stresstest: invalid parameters => min_len:%d > max_len:%d", + min_len, max_len); + return; + } + + if (min_len < 4) { + err("stresstest: invalid parameters => min_len is smaller than 4"); + return; + } + + len = min_len; + frame = carlu_alloc_frame(ar, len); + frame_put(frame, len); + + carlu_loopback_mark_tx_frames(frame); + + ar->rx_cb = carlu_loopback_rx; + ar->cmd_cb = carlu_loopback_cmd; + ar->tx_cb = carlu_loopback_tx_cb; + + start_time = SDL_GetTicks(); + while (runs <= total_runs) { + if (frame && carlu_tx(ar, frame) == 0) { + len = min_len; + i++; + } else { + frame_free(frame); + } + + frame = NULL; + + frame = carlu_alloc_frame(ar, len); + frame_put(frame, len); + + carlu_loopback_mark_tx_frames(frame); + j++; + + total_time = SDL_GetTicks() - start_time; + + if (total_time >= interval) { + moctets = ((float)ar->tx_octets) / (1024.0f * 1024.0f); + dtime = ((float)total_time) / 1000; + info("%d: tx %d of %d => %.2f MiB in %.2f secs => %.4f MBits/s\n", + runs, i, j, moctets, dtime, (moctets * 8.0f) / dtime); + + moctets = ((float)ar->rx_octets) / (1024.0f * 1024.0f); + info("%d: rx %d of %d => %.2f MiB in %.2f secs => %.4f MBits/s\n", + runs, ar->rxed, i, moctets, dtime, (moctets * 8.0f) / dtime); + + if ((ar->rxed == 0 && i) || !i) { + ret = carlu_cmd_echo(ar, 0xdeadbeef); + if (ret) + warn("firmware crashed... echo_cmd: (%d)\n", ret); + } + + total_time = 0; + i = 0; + j = 0; + ar->rxed = 0; + ar->txed = 0; + ar->rx_octets = 0; + ar->tx_octets = 0; + runs++; + start_time = SDL_GetTicks(); + } + } + + ar->rx_cb = NULL; + ar->cmd_cb = NULL; + ar->tx_cb = NULL; +} + +int carlu_gpio_test(struct carlu *ar) +{ + uint32_t gpio; + +#define CHK(cmd) \ + do { \ + int __err = cmd; \ + if ((__err)) \ + return __err; \ + } while (0) + + CHK(carlu_cmd_read_mem(ar, AR9170_GPIO_REG_PORT_DATA, &gpio)); + info("GPIO state:%x\n", gpio); + + /* turn both LEDs on */ + CHK(carlu_cmd_write_mem(ar, AR9170_GPIO_REG_PORT_DATA, + AR9170_GPIO_PORT_LED_0 | AR9170_GPIO_PORT_LED_1)); + + SDL_Delay(700); + + CHK(carlu_cmd_read_mem(ar, AR9170_GPIO_REG_PORT_DATA, &gpio)); + info("GPIO state:%x\n", gpio); + + /* turn LEDs off everything */ + CHK(carlu_cmd_write_mem(ar, AR9170_GPIO_REG_PORT_DATA, 0)); + + CHK(carlu_cmd_read_mem(ar, AR9170_GPIO_REG_PORT_DATA, &gpio)); + info("GPIO state:%x\n", gpio); +} + +int carlu_random_test(struct carlu *ar) +{ + uint32_t buf[4096]; + int err, i; + + err = carlu_cmd_mem_watch(ar, AR9170_RAND_REG_NUM, sizeof(buf), buf); + if (err) + return err; + + for (i = 0; i < ARRAY_SIZE(buf); i++) + info("%.2x %.2x ", buf[i] & 0xff, buf[i] >> 8); + + info("\n"); +} diff --git a/pool/shard000/C/0009139_tools.c b/pool/shard000/C/0009139_tools.c new file mode 100644 index 0000000000000000000000000000000000000000..b14b5934b500940026c3643cca98c46696053c68 --- /dev/null +++ b/pool/shard000/C/0009139_tools.c @@ -0,0 +1,72 @@ +/* + Author: Maxime Hadjinlian + maxime.hadjinlian@gmail.com + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include // for va_end, va_list, va_start +#include // for vsprintf + +#include "tools.h" // for filename + +int +append(struct filename *fn, const char *fmt, ...) +{ + va_list arg; + int ret; + + va_start(arg, fmt); + ret = vsprintf(fn->path + fn->used, fmt, arg); + va_end(arg); + fn->used += ret; + + if (ret > 0) + return 0; + + return ret; +} + +int +append_esc(struct filename *fn, const char *fmt, ...) +{ + va_list arg; + int ret; + int cur = fn->used; + + va_start(arg, fmt); + ret = vsprintf(fn->path + fn->used, fmt, arg); + va_end(arg); + fn->used += ret; + + if (ret > 0) + ret = 0; + + for (; cur < fn->used; ++cur) { + if (fn->path[cur] == '/') + fn->path[cur] = '_'; + } + + return ret; +} diff --git a/pool/shard000/C/0009147_optbst.c b/pool/shard000/C/0009147_optbst.c new file mode 100644 index 0000000000000000000000000000000000000000..049f9c3292b6cbaa7575e6a804e6a98ae6762e50 --- /dev/null +++ b/pool/shard000/C/0009147_optbst.c @@ -0,0 +1,146 @@ +/* + * Copyright (C) 2012 Carolina Aguilar + * Copyright (C) 2012 Carlos Jenkins + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "optbst.h" + +optbst_context* optbst_context_new(int keys) +{ + /* Check input is correct */ + if(keys < 1) { + return NULL; + } + + /* Allocate structures */ + optbst_context* c = (optbst_context*) malloc(sizeof(optbst_context)); + if(c == NULL) { + return NULL; + } + + /* Try to allocate keys' probabilities */ + c->keys_probabilities = (float*) malloc(keys * sizeof(float)); + if(c->keys_probabilities == NULL) { + return NULL; + } + + /* Try to allocate matrices */ + int size = keys + 1; + c->table_a = matrix_new(size, size, PLUS_INF); + if(c->table_a == NULL) { + free(c->keys_probabilities); + return NULL; + } + c->table_r = matrix_new(size, size, 0.0); + if(c->table_r == NULL) { + free(c->keys_probabilities); + matrix_free(c->table_a); + return NULL; + } + + /* Try to allocate names array */ + c->names = (char**) malloc(keys * sizeof(char*)); + if(c->names == NULL) { + matrix_free(c->table_a); + matrix_free(c->table_r); + free(c->keys_probabilities); + free(c); + return NULL; + } + c->keys = keys; + + /* Initialize values */ + for(int i = 0; i < size; i++) { + c->table_a->data[i][i] = 0.0; + } + for(int i = 0; i < keys; i++) { + c->names[i] = ""; + } + + c->status = -1; + c->execution_time = 0; + c->memory_required = matrix_sizeof(c->table_a) + + matrix_sizeof(c->table_r) + + (keys * sizeof(float)) + + (keys * sizeof(char*)) + + sizeof(optbst_context); + c->report_buffer = tmpfile(); + if(c->report_buffer == NULL) { + matrix_free(c->table_a); + matrix_free(c->table_r); + free(c->keys_probabilities); + free(c); + return NULL; + } + + return c; +} + +void optbst_context_free(optbst_context* c) +{ + matrix_free(c->table_a); + matrix_free(c->table_r); + fclose(c->report_buffer); + free(c->keys_probabilities); + free(c->names); + free(c); + return; +} + +bool optbst(optbst_context *c) +{ + /* Start counting time */ + GTimer* timer = g_timer_new(); + + /* Setting probabilities values */ + for(int i = 0; i < c->keys; i++) { + c->table_a->data[i][i + 1] = c->keys_probabilities[i]; + } + /* Setting winning k for given probabilities in R */ + for(int i = 0; i < c->keys; i++) { + c->table_r->data[i][i + 1] = i + 1; + } + + /* Run the probabilities to win algorithm */ + + /* c->keys-1=Numbers of diagonals to fill */ + for(int j = 1; j <= c->keys - 1; j++) { + for(int i = 1; i <= c->keys - j; i++) { + for(int k = i; k <= i + j; k++) { + float p = 0.0; + + /* Calculate the probability */ + for(int l = i; l <= i + j; l++) { + p += c->keys_probabilities[l - 1]; + } + float t = c->table_a->data[i - 1][k - 1] + + c->table_a->data[k][i + j] + p; + + /* Compare to get the minimun value */ + if(t < c->table_a->data[i - 1][i + j]) { + c->table_a->data[i - 1][i + j] = t; + c->table_r->data[i - 1][i + j] = k; + } + } + } + } + + /* Stop counting time */ + g_timer_stop(timer); + c->execution_time = g_timer_elapsed(timer, NULL); + g_timer_destroy(timer); + return true; +} diff --git a/pool/shard000/C/0009155_BT_Demo.c b/pool/shard000/C/0009155_BT_Demo.c new file mode 100644 index 0000000000000000000000000000000000000000..b62b374d675fcc8b8d04b7c162c1d31bb8b0ee81 --- /dev/null +++ b/pool/shard000/C/0009155_BT_Demo.c @@ -0,0 +1,147 @@ +/*-----------------------------------------------------------------------------*/ +/* */ +/* Copyright (c) Robomatter */ +/* 2016 */ +/* All Rights Reserved */ +/* */ +/*-----------------------------------------------------------------------------*/ +/* */ +/* Module: BT_Demo.c */ +/* Author: James Pearman */ +/* Created: 8 Feb 2016 */ +/* */ +/* V1.00 8 Feb 2016 Initial release tested with V4.52 */ +/* */ +/*-----------------------------------------------------------------------------*/ +/* */ +/* The author is supplying this software for use with the VEX IQ */ +/* control system. This file can be freely distributed and teams are */ +/* authorized to freely use this program , however, it is requested that */ +/* improvements or additions be shared with the Vex community via the vex */ +/* forum. Please acknowledge the work of the authors when appropriate. */ +/* Thanks. */ +/* */ +/* 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. */ +/* */ +/*-----------------------------------------------------------------------------*/ + +// Check platform +#ifndef VexIQ +#error "This program is designed for the VexIQ platform" +#else + +// Check if Smart Radio features are enabled +#ifndef VexIQ_SR +#error "This sample needs to have the smart radio features enabled" +#else + +#define PORTNONE ((tSensors)(-1)) +tSensors robotTouchSensor = PORTNONE; + +/*-----------------------------------------------------------------------------*/ +/* Discover devices and look for a touch sensor */ +/*-----------------------------------------------------------------------------*/ +void +iqDiscoverDevices() +{ + TVexIQDeviceTypes type; + TDeviceStatus status; + short ver; + short index; + + // Get all device info + for(index=(short)PORT1;index<=(short)PORT12;index++) { + getVexIqDeviceInfo( index, type, status, ver ); + + // Touch LED on any port used to start stop robot + if( type == vexIQ_SensorLED ) + robotTouchSensor = (tSensors)index; + } +} + +/*-----------------------------------------------------------------------------*/ +/* Setup message to remote device if touch LED state changed */ +/*-----------------------------------------------------------------------------*/ +void +checkTouchSensor() +{ + static int oldValue = -1; + static char msg[41]; + + // If Touch LED installed + if(robotTouchSensor != PORTNONE) + { + int value = SensorValue[ robotTouchSensor ]; + + if( value != oldValue ) + { + msg[0] = 0x80; + msg[1] = value; + oldValue = value; + + // User message to remote device + sendUserMessage(msg); + } + } +} + +/*-----------------------------------------------------------------------------*/ +/* Check if we received a user message from the bluetooth device */ +/*-----------------------------------------------------------------------------*/ +void +checkForUserMessage() +{ + char usrMsg[41]; //extra byte for null char + + if(userMessageAvailable()) + { + // Get the incomming message + readUserMessage(usrMsg); + + // The demo preceeds commands with the string "usr" + if( usrMsg[0] == 'u' && usrMsg[1] == 's' && usrMsg[2] == 'r' ) + { + // We have a message, see if the touch LED is found + if(robotTouchSensor != PORTNONE) + { + switch( usrMsg[3] ) + { + case 1: setTouchLEDColor( robotTouchSensor, colorBlue ); displayString(1, "Blue " ); break; + case 2: setTouchLEDColor( robotTouchSensor, colorRed ); displayString(1, "Red " );break; + case 3: setTouchLEDColor( robotTouchSensor, colorGreen ); displayString(1, "Green " );break; + case 4: setTouchLEDColor( robotTouchSensor, colorOrange ); displayString(1, "Orange" );break; + default: setTouchLEDColor( robotTouchSensor, colorNone ); displayString(1, " " );break; + } + } + } + } +} + +/*-----------------------------------------------------------------------------*/ +task main() +{ + eraseDisplay(); + + iqDiscoverDevices(); + + // run forever looking for user messages + while(true){ + checkForUserMessage(); + + checkTouchSensor(); + wait1Msec(10); + } +} + +#endif // End Smart Radio features enabled check +#endif // End platform check diff --git a/pool/shard000/C/0009166_bn_mp_add_d.c b/pool/shard000/C/0009166_bn_mp_add_d.c new file mode 100644 index 0000000000000000000000000000000000000000..66d1f0744f0d0b59dfa47230a0c8aff40c657638 --- /dev/null +++ b/pool/shard000/C/0009166_bn_mp_add_d.c @@ -0,0 +1,32 @@ +/* LibTomMath, multiple-precision integer library -- Tom St Denis + * + * LibTomMath is library that provides for multiple-precision + * integer arithmetic as well as number theoretic functionality. + * + * The library is designed directly after the MPI library by + * Michael Fromberger but has been written from scratch with + * additional optimizations in place. + * + * The library is free for all purposes without any express + * guarantee it works. + * + * Tom St Denis, tomstdenis@iahu.ca, http://math.libtomcrypt.org + */ +#include + +/* single digit addition */ +int +mp_add_d (mp_int * a, mp_digit b, mp_int * c) +{ + mp_int t; + int res; + + if ((res = mp_init_size(&t, 1)) != MP_OKAY) { + return res; + } + mp_set (&t, b); + res = mp_add (a, &t, c); + + mp_clear (&t); + return res; +} diff --git a/pool/shard000/C/0009172_gpio.c b/pool/shard000/C/0009172_gpio.c new file mode 100644 index 0000000000000000000000000000000000000000..c0b18391a36208842c57ab6d9db46c6dd4d0f642 --- /dev/null +++ b/pool/shard000/C/0009172_gpio.c @@ -0,0 +1,182 @@ +/* $NetBSD: gpio.c,v 1.3 2001/06/19 12:02:56 simonb Exp $ */ + +/*- + * Copyright (C) 1998 Internet Research Institute, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by + * Internet Research Institute, Inc. + * 4. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "adb.h" + +static void gpio_obio_attach (struct device *, struct device *, void *); +static int gpio_obio_match (struct device *, struct cfdata *, void *); +static int gpio_obio_print (void *aux, const char *gpio); + +static void gpio_gpio_attach (struct device *, struct device *, void *); +static int gpio_gpio_match (struct device *, struct cfdata *, void *); +static int gpio_intr (void *); + +struct gpio_softc { + struct device sc_dev; + u_int8_t *sc_port; +}; + +struct cfattach gpio_obio_ca = { + sizeof(struct gpio_softc), gpio_obio_match, gpio_obio_attach +}; + +struct cfattach gpio_gpio_ca = { + sizeof(struct gpio_softc), gpio_gpio_match, gpio_gpio_attach +}; + +extern struct cfdriver gpio_cd; + +int +gpio_obio_match(struct device *parent, struct cfdata *cf, void *aux) +{ + struct confargs *ca = aux; + + if (strcmp(ca->ca_name, "gpio") != 0) + return 0; + + if (ca->ca_nreg == 0) + return 0; + + return 1; +} + +void +gpio_obio_attach(struct device *parent, struct device *self, void *aux) +{ + struct gpio_softc *sc = (struct gpio_softc *)self; + struct confargs *ca = aux, ca2; + int child; + int namelen; + int intr[6]; + u_int reg[20]; + char name[32]; + + printf("\n"); + + sc->sc_port = mapiodev(ca->ca_baseaddr + ca->ca_reg[0], ca->ca_reg[1]); + + ca2.ca_baseaddr = ca->ca_baseaddr; + for (child = OF_child(ca->ca_node); child; child = OF_peer(child)) { + namelen = OF_getprop(child, "name", name, sizeof(name)); + if (namelen < 0) + continue; + if (namelen >= sizeof(name)) + continue; + + name[namelen] = 0; + ca2.ca_name = name; + ca2.ca_node = child; + + ca2.ca_nreg = OF_getprop(child, "reg", reg, sizeof(reg)); + ca2.ca_nintr = OF_getprop(child, "AAPL,interrupts", intr, + sizeof(intr)); + if (ca2.ca_nintr == -1) + ca2.ca_nintr = OF_getprop(child, "interrupts", intr, + sizeof(intr)); + + ca2.ca_reg = reg; + ca2.ca_intr = intr; + + config_found(self, &ca2, gpio_obio_print); + } +} + +int +gpio_obio_print(void *aux, const char *gpio) +{ + struct confargs *ca = aux; + + if (gpio) + printf("%s at %s", ca->ca_name, gpio); + + if (ca->ca_nreg > 0) + printf(" offset 0x%x", ca->ca_reg[0]); + + return UNCONF; +} + +int +gpio_gpio_match(struct device *parent, struct cfdata *cf, void *aux) +{ + struct confargs *ca = aux; + + if (strcmp(ca->ca_name, "extint-gpio1") != 0) + return 0; + + if (ca->ca_nintr < 0) + return 0; + + return 1; +} + +void +gpio_gpio_attach(struct device *parent, struct device *self, void *aux) +{ + struct gpio_softc *sc = (struct gpio_softc *)self; + struct confargs *ca = aux; + + + sc->sc_port = ((struct gpio_softc *) parent)->sc_port; + intr_establish(ca->ca_intr[0], IST_LEVEL, IPL_HIGH, gpio_intr, sc); + + printf(" irq %d\n", ca->ca_intr[0]); +} + +#if NADB > 0 +extern int adb_intr (void *); +extern struct cfdriver adb_cd; +#endif + +int +gpio_intr(void *arg) +{ + int rv = 0; + +#if NADB > 0 + if (adb_cd.cd_devs[0] != NULL) + rv = adb_intr(adb_cd.cd_devs[0]); +#endif + + return rv; +} diff --git a/pool/shard000/C/0009179_cpuid.c b/pool/shard000/C/0009179_cpuid.c new file mode 100644 index 0000000000000000000000000000000000000000..51c54045786e44105d9aa229ebda3590170e2306 --- /dev/null +++ b/pool/shard000/C/0009179_cpuid.c @@ -0,0 +1,75 @@ +#define _UMATHMODULE +#define _MULTIARRAYMODULE +#define NPY_NO_DEPRECATED_API NPY_API_VERSION + +#include + +#include "npy_config.h" + +#include "cpuid.h" + +#define XCR_XFEATURE_ENABLED_MASK 0x0 +#define XSTATE_SSE 0x2 +#define XSTATE_YMM 0x4 +#define XSTATE_ZMM 0x70 + +/* + * verify the OS supports avx instructions + * it can be disabled in some OS, e.g. with the nosavex boot option of linux + */ +static NPY_INLINE +int os_avx_support(void) +{ +#if HAVE_XGETBV + /* + * use bytes for xgetbv to avoid issues with compiler not knowing the + * instruction + */ + unsigned int eax, edx; + unsigned int ecx = XCR_XFEATURE_ENABLED_MASK; + __asm__("xgetbv" : "=a" (eax), "=d" (edx) : "c" (ecx)); + return (eax & (XSTATE_SSE | XSTATE_YMM)) == (XSTATE_SSE | XSTATE_YMM); +#else + return 0; +#endif +} + +static NPY_INLINE +int os_avx512_support(void) +{ +#if HAVE_XGETBV + unsigned int eax, edx; + unsigned int ecx = XCR_XFEATURE_ENABLED_MASK; + unsigned int xcr0 = XSTATE_ZMM | XSTATE_YMM | XSTATE_SSE; + __asm__("xgetbv" : "=a" (eax), "=d" (edx) : "c" (ecx)); + return (eax & xcr0) == xcr0; +#else + return 0; +#endif +} + +/* + * Primitive cpu feature detect function + * Currently only supports checking for avx on gcc compatible compilers. + */ +NPY_NO_EXPORT int +npy_cpu_supports(const char * feature) +{ +#ifdef HAVE___BUILTIN_CPU_SUPPORTS + if (strcmp(feature, "avx512f") == 0) { +#if defined(__GNUC__) && (__GNUC__ < 5) + return 0; +#else + return __builtin_cpu_supports("avx512f") && os_avx512_support(); +#endif + } + else if (strcmp(feature, "avx2") == 0) { + return __builtin_cpu_supports("avx2") && os_avx_support(); + } + else if (strcmp(feature, "avx") == 0) { + return __builtin_cpu_supports("avx") && os_avx_support(); + } +#endif + + return 0; +} diff --git a/pool/shard000/C/0009182_glClear.c b/pool/shard000/C/0009182_glClear.c new file mode 100644 index 0000000000000000000000000000000000000000..37df8285ee6163cdcaefb607ba8fe27ef9998e17 --- /dev/null +++ b/pool/shard000/C/0009182_glClear.c @@ -0,0 +1,77 @@ +#include "pspgl_internal.h" +#include "pspgl_dlist.h" + +struct clear_vertex { + unsigned long color; + short x,y,z; + short _pad; +}; + + +void glClear (GLbitfield mask) +{ + struct clear_vertex *vbuf; + struct pspgl_surface *s = pspgl_curctx->draw; + unsigned long clearmask = pspgl_curctx->clear.color; + unsigned long clearmode = 0; + unsigned x, y, width, height; + + if (mask & ~(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT)) + goto out_error; + + /* make room for 2 embedded vertices in cmd_buf, aligned to 16byte boundary */ + vbuf = __pspgl_dlist_insert_space(2 * sizeof(struct clear_vertex)); + + if (mask & GL_COLOR_BUFFER_BIT) { + clearmode |= GU_COLOR_BUFFER_BIT; + if (s->alpha_mask) + clearmode |= GU_STENCIL_BUFFER_BIT; /* really alpha */ + } + + if (s->stencil_mask && (mask & GL_STENCIL_BUFFER_BIT)) { + static const unsigned char stencil_shift [] = { 32-1, 32-4, 32-8 }; + clearmask &= 0x00ffffff; + clearmask |= (pspgl_curctx->clear.stencil) << stencil_shift[s->pixfmt-1]; + clearmode |= GU_STENCIL_BUFFER_BIT; + } + + if (s->depth_buffer && (mask & GL_DEPTH_BUFFER_BIT)) + clearmode |= GU_DEPTH_BUFFER_BIT; + + if (pspgl_curctx->scissor_test.enabled) { + x = pspgl_curctx->scissor_test.x; + y = pspgl_curctx->scissor_test.y; + width = pspgl_curctx->scissor_test.width; + height = pspgl_curctx->scissor_test.height; + } else { + x = 0; + y = 0; + width = s->width; + height = s->height; + } + + vbuf[0].color = clearmask; + vbuf[0].x = x; + vbuf[0].y = s->height - y; + vbuf[0].z = pspgl_curctx->clear.depth; + + vbuf[1].color = clearmask; + vbuf[1].x = x + width; + vbuf[1].y = s->height - (y + height); + vbuf[1].z = pspgl_curctx->clear.depth; + + /* enable clear mode */ + sendCommandi(CMD_CLEARMODE, (clearmode << 8) | 1); + + /* draw array */ + __pspgl_context_render_prim(pspgl_curctx, GE_SPRITES, 2, + GE_COLOR_8888 | GE_VERTEX_16BIT | GE_TRANSFORM_2D, vbuf, NULL); + + /* leave clear mode */ + sendCommandi(CMD_CLEARMODE, 0); + return; + + out_error: + GLERROR(GL_INVALID_VALUE); +} + diff --git a/pool/shard000/C/0009195_MP+PPO933.c b/pool/shard000/C/0009195_MP+PPO933.c new file mode 100644 index 0000000000000000000000000000000000000000..422cb20861d082f74f76b0c480272f3a882e0555 --- /dev/null +++ b/pool/shard000/C/0009195_MP+PPO933.c @@ -0,0 +1,63 @@ +/* Copyright (C) 2018 Magnus Lång and Tuan Phong Ngo + * This benchmark is part of SWSC */ + +#include +#include +#include +#include + +atomic_int vars[3]; +atomic_int atom_1_r1_1; +atomic_int atom_1_r9_1; + +void *t0(void *arg){ +label_1:; + atomic_store_explicit(&vars[0], 2, memory_order_seq_cst); + + atomic_store_explicit(&vars[1], 1, memory_order_seq_cst); + return NULL; +} + +void *t1(void *arg){ +label_2:; + int v2_r1 = atomic_load_explicit(&vars[1], memory_order_seq_cst); + int v3_r3 = v2_r1 ^ v2_r1; + int v6_r4 = atomic_load_explicit(&vars[2+v3_r3], memory_order_seq_cst); + int v7_cmpeq = (v6_r4 == v6_r4); + if (v7_cmpeq) goto lbl_LC00; else goto lbl_LC00; +lbl_LC00:; + atomic_store_explicit(&vars[0], 1, memory_order_seq_cst); + int v9_r8 = atomic_load_explicit(&vars[0], memory_order_seq_cst); + int v11_r9 = atomic_load_explicit(&vars[0], memory_order_seq_cst); + int v18 = (v2_r1 == 1); + atomic_store_explicit(&atom_1_r1_1, v18, memory_order_seq_cst); + int v19 = (v11_r9 == 1); + atomic_store_explicit(&atom_1_r9_1, v19, memory_order_seq_cst); + return NULL; +} + +int main(int argc, char *argv[]){ + pthread_t thr0; + pthread_t thr1; + + atomic_init(&vars[1], 0); + atomic_init(&vars[0], 0); + atomic_init(&vars[2], 0); + atomic_init(&atom_1_r1_1, 0); + atomic_init(&atom_1_r9_1, 0); + + pthread_create(&thr0, NULL, t0, NULL); + pthread_create(&thr1, NULL, t1, NULL); + + pthread_join(thr0, NULL); + pthread_join(thr1, NULL); + + int v12 = atomic_load_explicit(&vars[0], memory_order_seq_cst); + int v13 = (v12 == 2); + int v14 = atomic_load_explicit(&atom_1_r1_1, memory_order_seq_cst); + int v15 = atomic_load_explicit(&atom_1_r9_1, memory_order_seq_cst); + int v16_conj = v14 & v15; + int v17_conj = v13 & v16_conj; + if (v17_conj == 1) assert(0); + return 0; +} diff --git a/pool/shard000/C/0009196_vmci_handle_array.c b/pool/shard000/C/0009196_vmci_handle_array.c new file mode 100644 index 0000000000000000000000000000000000000000..c527388f5d7b164b9bcc3f6ff4090abbf87d3bbe --- /dev/null +++ b/pool/shard000/C/0009196_vmci_handle_array.c @@ -0,0 +1,134 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * VMware VMCI Driver + * + * Copyright (C) 2012 VMware, Inc. All rights reserved. + */ + +#include +#include "vmci_handle_array.h" + +static size_t handle_arr_calc_size(size_t capacity) +{ + return sizeof(struct vmci_handle_arr) + + capacity * sizeof(struct vmci_handle); +} + +struct vmci_handle_arr *vmci_handle_arr_create(size_t capacity) +{ + struct vmci_handle_arr *array; + + if (capacity == 0) + capacity = VMCI_HANDLE_ARRAY_DEFAULT_SIZE; + + array = kmalloc(handle_arr_calc_size(capacity), GFP_ATOMIC); + if (!array) + return NULL; + + array->capacity = capacity; + array->size = 0; + + return array; +} + +void vmci_handle_arr_destroy(struct vmci_handle_arr *array) +{ + kfree(array); +} + +void vmci_handle_arr_append_entry(struct vmci_handle_arr **array_ptr, + struct vmci_handle handle) +{ + struct vmci_handle_arr *array = *array_ptr; + + if (unlikely(array->size >= array->capacity)) { + /* reallocate. */ + struct vmci_handle_arr *new_array; + size_t new_capacity = array->capacity * VMCI_ARR_CAP_MULT; + size_t new_size = handle_arr_calc_size(new_capacity); + + new_array = krealloc(array, new_size, GFP_ATOMIC); + if (!new_array) + return; + + new_array->capacity = new_capacity; + *array_ptr = array = new_array; + } + + array->entries[array->size] = handle; + array->size++; +} + +/* + * Handle that was removed, VMCI_INVALID_HANDLE if entry not found. + */ +struct vmci_handle vmci_handle_arr_remove_entry(struct vmci_handle_arr *array, + struct vmci_handle entry_handle) +{ + struct vmci_handle handle = VMCI_INVALID_HANDLE; + size_t i; + + for (i = 0; i < array->size; i++) { + if (vmci_handle_is_equal(array->entries[i], entry_handle)) { + handle = array->entries[i]; + array->size--; + array->entries[i] = array->entries[array->size]; + array->entries[array->size] = VMCI_INVALID_HANDLE; + break; + } + } + + return handle; +} + +/* + * Handle that was removed, VMCI_INVALID_HANDLE if array was empty. + */ +struct vmci_handle vmci_handle_arr_remove_tail(struct vmci_handle_arr *array) +{ + struct vmci_handle handle = VMCI_INVALID_HANDLE; + + if (array->size) { + array->size--; + handle = array->entries[array->size]; + array->entries[array->size] = VMCI_INVALID_HANDLE; + } + + return handle; +} + +/* + * Handle at given index, VMCI_INVALID_HANDLE if invalid index. + */ +struct vmci_handle +vmci_handle_arr_get_entry(const struct vmci_handle_arr *array, size_t index) +{ + if (unlikely(index >= array->size)) + return VMCI_INVALID_HANDLE; + + return array->entries[index]; +} + +bool vmci_handle_arr_has_entry(const struct vmci_handle_arr *array, + struct vmci_handle entry_handle) +{ + size_t i; + + for (i = 0; i < array->size; i++) + if (vmci_handle_is_equal(array->entries[i], entry_handle)) + return true; + + return false; +} + +/* + * NULL if the array is empty. Otherwise, a pointer to the array + * of VMCI handles in the handle array. + */ +struct vmci_handle *vmci_handle_arr_get_handles(struct vmci_handle_arr *array) +{ + if (array->size) + return array->entries; + + return NULL; +} diff --git a/pool/shard000/C/0009205_access_properties_and_parameters.c b/pool/shard000/C/0009205_access_properties_and_parameters.c new file mode 100644 index 0000000000000000000000000000000000000000..f023dd83217d2bd4530ed9cb5b2b1ea3d041a44b --- /dev/null +++ b/pool/shard000/C/0009205_access_properties_and_parameters.c @@ -0,0 +1,150 @@ +/* access_properties_and_parameters.c */ + +#include +#include +#include + +/* Get a particular parameter out of a component. This routine will + return a list of strings of all attendees who are required. Note + that this routine assumes that the component that we pass in is a + VEVENT. */ + +void get_required_attendees(icalcomponent* event) +{ + icalproperty* p; + icalparameter* parameter; + + assert(event != 0); + assert(icalcomponent_isa(event) == ICAL_VEVENT_COMPONENT); + + /* This loop iterates over all of the ATTENDEE properties in the + event */ + + /* The iteration routines save their state in the event + struct, so the are not thread safe unless you lock the whole + component. */ + + for( + p = icalcomponent_get_first_property(event,ICAL_ATTENDEE_PROPERTY); + p != 0; + p = icalcomponent_get_next_property(event,ICAL_ATTENDEE_PROPERTY) + ) { + + /* Get the first ROLE parameter in the property. There should + only be one, so we won't bother to iterate over them. But, + you can iterate over parameters just like with properties */ + + parameter = icalproperty_get_first_parameter(p,ICAL_ROLE_PARAMETER); + + /* If the parameter indicates the participant is required, get + the attendees name and stick a copy of it into the output + array */ + + if ( icalparameter_get_role(parameter) == ICAL_ROLE_REQPARTICIPANT) + { + /* Remember, the caller does not own this string, so you + should strdup it if you want to change it. */ + const char *attendee = icalproperty_get_attendee(p); + } + } + +} + +/* Here is a similar example. If an attendee has a PARTSTAT of + NEEDSACTION or has no PARTSTAT parameter, change it to + TENTATIVE. */ + +void update_attendees(icalcomponent* event) +{ + icalproperty* p; + icalparameter* parameter; + + assert(event != 0); + assert(icalcomponent_isa(event) == ICAL_VEVENT_COMPONENT); + + for( + p = icalcomponent_get_first_property(event,ICAL_ATTENDEE_PROPERTY); + p != 0; + p = icalcomponent_get_next_property(event,ICAL_ATTENDEE_PROPERTY) + ) { + + parameter = icalproperty_get_first_parameter(p,ICAL_PARTSTAT_PARAMETER); + + if (parameter == 0) { + + /* There was no PARTSTAT parameter, so add one. */ + icalproperty_add_parameter( + p, + icalparameter_new_partstat(ICAL_PARTSTAT_TENTATIVE) + ); + + } else if (icalparameter_get_partstat(parameter) == ICAL_PARTSTAT_NEEDSACTION) { + /* Remove the NEEDSACTION parameter and replace it with + TENTATIVE */ + + icalproperty_remove_parameter(p,ICAL_PARTSTAT_PARAMETER); + + /* Don't forget to free it */ + icalparameter_free(parameter); + + /* Add a new one */ + icalproperty_add_parameter( + p, + icalparameter_new_partstat(ICAL_PARTSTAT_TENTATIVE) + ); + } + + } +} + +/* Here are some examples of manipulating properties */ + +void test_properties() +{ + icalproperty *prop; + icalparameter *param; + icalvalue *value; + char *str; + + icalproperty *clone; + + /* Create a new property */ + prop = icalproperty_vanew_comment( + "Another Comment", + icalparameter_new_cn("A Common Name 1"), + icalparameter_new_cn("A Common Name 2"), + icalparameter_new_cn("A Common Name 3"), + icalparameter_new_cn("A Common Name 4"), + 0); + + /* Iterate through all of the parameters in the property */ + for(param = icalproperty_get_first_parameter(prop,ICAL_ANY_PARAMETER); + param != 0; + param = icalproperty_get_next_parameter(prop,ICAL_ANY_PARAMETER)) { + + printf("Prop parameter: %s\n",icalparameter_get_cn(param)); + } + + /* Get a string representation of the property's value */ + printf("Prop value: %s\n",icalproperty_get_comment(prop)); + + /* Spit out the property in its RFC 2445 representation */ + str = icalproperty_as_ical_string (prop); + printf("As iCAL string:\n %s\n", str); + free (str); + + /* Make a copy of the property. Caller owns the memory */ + clone = icalproperty_new_clone(prop); + + /* Get a reference to the value within the clone property */ + value = icalproperty_get_value(clone); + + str = icalvalue_as_ical_string (value); + printf("Value: %s", str); + free (str); + + /* Free the original and the clone */ + icalproperty_free(clone); + icalproperty_free(prop); + +} diff --git a/pool/shard000/C/0009211_fsl_lptmr.c b/pool/shard000/C/0009211_fsl_lptmr.c new file mode 100644 index 0000000000000000000000000000000000000000..2a1ef956c9fd3d7de62b666f5ccca0ed09509d4c --- /dev/null +++ b/pool/shard000/C/0009211_fsl_lptmr.c @@ -0,0 +1,164 @@ +/* + * The Clear BSD License + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted (subject to the limitations in the disclaimer below) provided + * that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o 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. + * + * o Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "fsl_lptmr.h" + +/* Component ID definition, used by tools. */ +#ifndef FSL_COMPONENT_ID +#define FSL_COMPONENT_ID "platform.drivers.lptmr" +#endif + + +/******************************************************************************* + * Prototypes + ******************************************************************************/ +#if defined(LPTMR_CLOCKS) +/*! + * @brief Gets the instance from the base address to be used to gate or ungate the module clock + * + * @param base LPTMR peripheral base address + * + * @return The LPTMR instance + */ +static uint32_t LPTMR_GetInstance(LPTMR_Type *base); +#endif /* LPTMR_CLOCKS */ + +/******************************************************************************* + * Variables + ******************************************************************************/ +#if defined(LPTMR_CLOCKS) +/*! @brief Pointers to LPTMR bases for each instance. */ +static LPTMR_Type *const s_lptmrBases[] = LPTMR_BASE_PTRS; + +#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) +/*! @brief Pointers to LPTMR clocks for each instance. */ +static const clock_ip_name_t s_lptmrClocks[] = LPTMR_CLOCKS; + +#if defined(LPTMR_PERIPH_CLOCKS) +/* Array of LPTMR functional clock name. */ +static const clock_ip_name_t s_lptmrPeriphClocks[] = LPTMR_PERIPH_CLOCKS; +#endif + +#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ +#endif /* LPTMR_CLOCKS */ + +/******************************************************************************* + * Code + ******************************************************************************/ +#if defined(LPTMR_CLOCKS) +static uint32_t LPTMR_GetInstance(LPTMR_Type *base) +{ + uint32_t instance; + + /* Find the instance index from base address mappings. */ + for (instance = 0; instance < ARRAY_SIZE(s_lptmrBases); instance++) + { + if (s_lptmrBases[instance] == base) + { + break; + } + } + + assert(instance < ARRAY_SIZE(s_lptmrBases)); + + return instance; +} +#endif /* LPTMR_CLOCKS */ + +void LPTMR_Init(LPTMR_Type *base, const lptmr_config_t *config) +{ + assert(config); + +#if defined(LPTMR_CLOCKS) +#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) + + uint32_t instance = LPTMR_GetInstance(base); + + /* Ungate the LPTMR clock*/ + CLOCK_EnableClock(s_lptmrClocks[instance]); +#if defined(LPTMR_PERIPH_CLOCKS) + CLOCK_EnableClock(s_lptmrPeriphClocks[instance]); +#endif + +#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ +#endif /* LPTMR_CLOCKS */ + + /* Configure the timers operation mode and input pin setup */ + base->CSR = (LPTMR_CSR_TMS(config->timerMode) | LPTMR_CSR_TFC(config->enableFreeRunning) | + LPTMR_CSR_TPP(config->pinPolarity) | LPTMR_CSR_TPS(config->pinSelect)); + + /* Configure the prescale value and clock source */ + base->PSR = (LPTMR_PSR_PRESCALE(config->value) | LPTMR_PSR_PBYP(config->bypassPrescaler) | + LPTMR_PSR_PCS(config->prescalerClockSource)); +} + +void LPTMR_Deinit(LPTMR_Type *base) +{ + /* Disable the LPTMR and reset the internal logic */ + base->CSR &= ~LPTMR_CSR_TEN_MASK; + +#if defined(LPTMR_CLOCKS) +#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) + + uint32_t instance = LPTMR_GetInstance(base); + + /* Gate the LPTMR clock*/ + CLOCK_DisableClock(s_lptmrClocks[instance]); +#if defined(LPTMR_PERIPH_CLOCKS) + CLOCK_DisableClock(s_lptmrPeriphClocks[instance]); +#endif + +#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ +#endif /* LPTMR_CLOCKS */ +} + +void LPTMR_GetDefaultConfig(lptmr_config_t *config) +{ + assert(config); + + /* Use time counter mode */ + config->timerMode = kLPTMR_TimerModeTimeCounter; + /* Use input 0 as source in pulse counter mode */ + config->pinSelect = kLPTMR_PinSelectInput_0; + /* Pulse input pin polarity is active-high */ + config->pinPolarity = kLPTMR_PinPolarityActiveHigh; + /* Counter resets whenever TCF flag is set */ + config->enableFreeRunning = false; + /* Bypass the prescaler */ + config->bypassPrescaler = true; + /* LPTMR clock source */ + config->prescalerClockSource = kLPTMR_PrescalerClock_1; + /* Divide the prescaler clock by 2 */ + config->value = kLPTMR_Prescale_Glitch_0; +} diff --git a/pool/shard000/C/0009238_nemesis-proto_tcp.c b/pool/shard000/C/0009238_nemesis-proto_tcp.c new file mode 100644 index 0000000000000000000000000000000000000000..5bf94fe2f4e00991f7b82b5870c376c3c2f461aa --- /dev/null +++ b/pool/shard000/C/0009238_nemesis-proto_tcp.c @@ -0,0 +1,150 @@ +/* + * $Id: nemesis-proto_tcp.c,v 1.1.1.1 2003/10/31 21:29:37 jnathan Exp $ + * + * THE NEMESIS PROJECT + * Copyright (C) 1999, 2000, 2001 Mark Grimes + * Copyright (C) 2001 - 2003 Jeff Nathan + * + * nemesis-proto_tcp.c (TCP Packet Generator) + * + */ + +#include "nemesis-tcp.h" +#include "nemesis.h" + +int buildtcp(ETHERhdr *eth, IPhdr *ip, TCPhdr *tcp, FileData *pd, + FileData *ipod, FileData *tcpod, char *device) +{ + int n; + u_int32_t tcp_packetlen = 0, tcp_meta_packetlen = 0; + static u_int8_t *pkt; + static int sockfd = -1; + struct libnet_link_int *l2 = NULL; + u_int8_t link_offset = 0; +#if !defined(WIN32) + int sockbuff = IP_MAXPACKET; +#endif + + if (pd->file_mem == NULL) + pd->file_s = 0; + if (ipod->file_mem == NULL) + ipod->file_s = 0; + if (tcpod->file_mem == NULL) + tcpod->file_s = 0; + + if (got_link) /* data link layer transport */ + { + if ((l2 = libnet_open_link_interface(device, errbuf)) == NULL) + { + nemesis_device_failure(INJECTION_LINK, (const char *)device); + return -1; + } + link_offset = LIBNET_ETH_H; + } + else + { + if ((sockfd = libnet_open_raw_sock(IPPROTO_RAW)) < 0) + { + nemesis_device_failure(INJECTION_RAW, (const char *)NULL); + return -1; + } +#if !defined(WIN32) + if ((setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, (const void *)&sockbuff, + sizeof(sockbuff))) < 0) + { + fprintf(stderr, "ERROR: setsockopt() failed.\n"); + return -1; + } +#endif + } + + tcp_packetlen = link_offset + LIBNET_IP_H + LIBNET_TCP_H + pd->file_s + + ipod->file_s + tcpod->file_s; + + tcp_meta_packetlen = tcp_packetlen - (link_offset + LIBNET_IP_H); + +#ifdef DEBUG + printf("DEBUG: TCP packet length %u.\n", tcp_packetlen); + printf("DEBUG: IP options size %u.\n", ipod->file_s); + printf("DEBUG: TCP options size %u.\n", tcpod->file_s); + printf("DEBUG: TCP payload size %u.\n", pd->file_s); +#endif + + if (libnet_init_packet(tcp_packetlen, &pkt) == -1) + { + fprintf(stderr, "ERROR: Unable to allocate packet memory.\n"); + return -1; + } + + if (got_link) + libnet_build_ethernet(eth->ether_dhost, eth->ether_shost, ETHERTYPE_IP, + NULL, 0, pkt); + + libnet_build_ip(tcp_meta_packetlen, ip->ip_tos, ip->ip_id, ip->ip_off, + ip->ip_ttl, ip->ip_p, ip->ip_src.s_addr, ip->ip_dst.s_addr, + NULL, 0, pkt + link_offset); + + libnet_build_tcp(tcp->th_sport, tcp->th_dport, tcp->th_seq, + tcp->th_ack, tcp->th_flags, tcp->th_win, tcp->th_urp, + pd->file_mem, pd->file_s, pkt + link_offset + LIBNET_IP_H); + + if (got_ipoptions) + { + if ((libnet_insert_ipo((struct ipoption *)ipod->file_mem, + ipod->file_s, pkt + link_offset)) == -1) + { + fprintf(stderr, "ERROR: Unable to add IP options, discarding " + "them.\n"); + } + } + + if (got_tcpoptions) + { + if ((libnet_insert_tcpo((struct tcpoption *)tcpod->file_mem, + tcpod->file_s, pkt + link_offset)) == -1) + { + fprintf(stderr, "ERROR: Unable to add TCP options, discarding " + "them.\n"); + } + } + + if (got_link) + libnet_do_checksum(pkt + LIBNET_ETH_H, IPPROTO_IP, LIBNET_IP_H + + ipod->file_s); + + libnet_do_checksum(pkt + link_offset, IPPROTO_TCP, LIBNET_TCP_H + + pd->file_s + tcpod->file_s); + + if (got_link) + n = libnet_write_link_layer(l2, device, pkt, tcp_packetlen); + else + n = libnet_write_ip(sockfd, pkt, tcp_packetlen); + + if (verbose == 2) + nemesis_hexdump(pkt, tcp_packetlen, HEX_ASCII_DECODE); + if (verbose == 3) + nemesis_hexdump(pkt, tcp_packetlen, HEX_RAW_DECODE); + + if (n != tcp_packetlen) + { + fprintf(stderr, "ERROR: Incomplete packet injection. Only wrote " + "%d bytes.\n", n); + } + else + { + if (verbose) + { + if (got_link) + printf("Wrote %d byte TCP packet through linktype %s.\n", n, + nemesis_lookup_linktype(l2->linktype)); + else + printf("Wrote %d byte TCP packet.\n", n); + } + } + libnet_destroy_packet(&pkt); + if (got_link) + libnet_close_link_interface(l2); + else + libnet_close_raw_sock(sockfd); + return n; +} diff --git a/pool/shard000/C/0009243_ata_zbbus.c b/pool/shard000/C/0009243_ata_zbbus.c new file mode 100644 index 0000000000000000000000000000000000000000..7f4706300f6d61b3601702b11c61a2131c5e30df --- /dev/null +++ b/pool/shard000/C/0009243_ata_zbbus.c @@ -0,0 +1,170 @@ +/*- + * Copyright (c) 2009 Neelkanth Natu + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +#include +#include + +#include + +__FBSDID("$FreeBSD$"); + +static int +ata_zbbus_probe(device_t dev) +{ + + return (ata_probe(dev)); +} + +static int +ata_zbbus_attach(device_t dev) +{ + int i, rid, regshift, regoffset; + struct ata_channel *ch; + struct resource *io; + + ch = device_get_softc(dev); + + if (ch->attached) + return (0); + ch->attached = 1; + + rid = 0; + io = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid, RF_ACTIVE); + if (io == NULL) + return (ENXIO); + + /* + * SWARM needs an address shift of 5 when accessing ATA registers. + * + * For e.g. an access to register 4 actually needs an address + * of (4 << 5) to be output on the generic bus. + */ + regshift = 5; + resource_int_value(device_get_name(dev), device_get_unit(dev), + "regshift", ®shift); + if (regshift && bootverbose) + device_printf(dev, "using a register shift of %d\n", regshift); + + regoffset = 0x1F0; + resource_int_value(device_get_name(dev), device_get_unit(dev), + "regoffset", ®offset); + if (regoffset && bootverbose) { + device_printf(dev, "using a register offset of 0x%0x\n", + regoffset); + } + + /* setup the ata register addresses */ + for (i = ATA_DATA; i <= ATA_COMMAND; ++i) { + ch->r_io[i].res = io; + ch->r_io[i].offset = (regoffset + i) << regshift; + } + + ch->r_io[ATA_CONTROL].res = io; + ch->r_io[ATA_CONTROL].offset = (regoffset + ATA_CTLOFFSET) << regshift; + ch->r_io[ATA_IDX_ADDR].res = io; /* XXX what is this used for */ + ata_default_registers(dev); + + /* initialize softc for this channel */ + ch->unit = 0; + ch->flags |= ATA_USE_16BIT; + ata_generic_hw(dev); + + return (ata_attach(dev)); +} + +static int +ata_zbbus_detach(device_t dev) +{ + int error; + struct ata_channel *ch = device_get_softc(dev); + + if (!ch->attached) + return (0); + ch->attached = 0; + + error = ata_detach(dev); + + bus_release_resource(dev, SYS_RES_MEMORY, 0, + ch->r_io[ATA_IDX_ADDR].res); + + return (error); +} + +static int +ata_zbbus_suspend(device_t dev) +{ + struct ata_channel *ch = device_get_softc(dev); + + if (!ch->attached) + return (0); + + return (ata_suspend(dev)); +} + +static int +ata_zbbus_resume(device_t dev) +{ + struct ata_channel *ch = device_get_softc(dev); + + if (!ch->attached) + return (0); + + return (ata_resume(dev)); +} + +static device_method_t ata_zbbus_methods[] = { + /* device interface */ + DEVMETHOD(device_probe, ata_zbbus_probe), + DEVMETHOD(device_attach, ata_zbbus_attach), + DEVMETHOD(device_detach, ata_zbbus_detach), + DEVMETHOD(device_suspend, ata_zbbus_suspend), + DEVMETHOD(device_resume, ata_zbbus_resume), + + { 0, 0 } +}; + +static driver_t ata_zbbus_driver = { + "ata", + ata_zbbus_methods, + sizeof(struct ata_channel) +}; + +DRIVER_MODULE(ata, zbbus, ata_zbbus_driver, ata_devclass, 0, 0); diff --git a/pool/shard000/C/0009244_g2_unpack4.c b/pool/shard000/C/0009244_g2_unpack4.c new file mode 100644 index 0000000000000000000000000000000000000000..524549d0b6f11bbf42b34dd01b8f06891d0b5d0f --- /dev/null +++ b/pool/shard000/C/0009244_g2_unpack4.c @@ -0,0 +1,185 @@ +#include +#include +#include "grib2.h" + + +g2int g2_unpack4(unsigned char *cgrib,g2int *iofst,g2int *ipdsnum,g2int **ipdstmpl, + g2int *mappdslen,g2float **coordlist,g2int *numcoord) +////$$$ SUBPROGRAM DOCUMENTATION BLOCK +// . . . . +// SUBPROGRAM: g2_unpack4 +// PRGMMR: Gilbert ORG: W/NP11 DATE: 2002-10-31 +// +// ABSTRACT: This subroutine unpacks Section 4 (Product Definition Section) +// as defined in GRIB Edition 2. +// +// PROGRAM HISTORY LOG: +// 2002-10-31 Gilbert +// 2009-01-14 Vuong Changed structure name template to gtemplate +// +// USAGE: int g2_unpack4(unsigned char *cgrib,g2int *iofst,g2int *ipdsnum, +// g2int **ipdstmpl,g2int *mappdslen, +// g2float **coordlist,g2int *numcoord) +// INPUT ARGUMENTS: +// cgrib - Char array containing Section 4 of the GRIB2 message +// iofst - Bit offset of the beginning of Section 4 in cgrib. +// +// OUTPUT ARGUMENTS: +// iofst - Bit offset of the end of Section 4, returned. +// ipdsnum - Product Definition Template Number ( see Code Table 4.0) +// ipdstmpl - Pointer to integer array containing the data values for +// the specified Product Definition +// Template ( N=ipdsnum ). Each element of this integer +// array contains an entry (in the order specified) of Product +// Defintion Template 4.N +// mappdslen- Number of elements in ipdstmpl[]. i.e. number of entries +// in Product Defintion Template 4.N ( N=ipdsnum ). +// coordlist- Pointer to real array containing floating point values +// intended to document +// the vertical discretisation associated to model data +// on hybrid coordinate vertical levels. (part of Section 4) +// numcoord - number of values in array coordlist. +// +// RETURN VALUES: +// ierr - Error return code. +// 0 = no error +// 2 = Not section 4 +// 5 = "GRIB" message contains an undefined Product Definition +// Template. +// 6 = memory allocation error +// +// REMARKS: +// +// ATTRIBUTES: +// LANGUAGE: C +// MACHINE: +// +//$$$// +{ + + g2int ierr,needext,i,j,nbits,isecnum; + g2int lensec,isign,newlen; + g2int *coordieee; + g2int *lipdstmpl=0; + g2float *lcoordlist; + gtemplate *mappds; + + ierr=0; + *ipdstmpl=0; // NULL + *coordlist=0; // NULL + + gbit(cgrib,&lensec,*iofst,32); // Get Length of Section + *iofst=*iofst+32; + gbit(cgrib,&isecnum,*iofst,8); // Get Section Number + *iofst=*iofst+8; + + if ( isecnum != 4 ) { + ierr=2; + *numcoord=0; + *mappdslen=0; + // fprintf(stderr,"g2_unpack4: Not Section 4 data.\n"); + return(ierr); + } + + gbit(cgrib,numcoord,*iofst,16); // Get num of coordinate values + *iofst=*iofst+16; + gbit(cgrib,ipdsnum,*iofst,16); // Get Prod. Def Template num. + *iofst=*iofst+16; + + // Get Product Definition Template + mappds=getpdstemplate(*ipdsnum); + if (mappds == 0) { // undefine template + ierr=5; + *mappdslen=0; + return(ierr); + } + *mappdslen=mappds->maplen; + needext=mappds->needext; + // + // Unpack each value into array ipdstmpl from the + // the appropriate number of octets, which are specified in + // corresponding entries in array mappds. + // + if (*mappdslen > 0) lipdstmpl=(g2int *)calloc(*mappdslen,sizeof(g2int)); + if (lipdstmpl == 0) { + ierr=6; + *mappdslen=0; + *ipdstmpl=0; //NULL + if ( mappds != 0 ) free(mappds); + return(ierr); + } + else { + *ipdstmpl=lipdstmpl; + } + for (i=0;imaplen;i++) { + nbits=abs(mappds->map[i])*8; + if ( mappds->map[i] >= 0 ) { + gbit(cgrib,lipdstmpl+i,*iofst,nbits); + } + else { + gbit(cgrib,&isign,*iofst,1); + gbit(cgrib,lipdstmpl+i,*iofst+1,nbits-1); + if (isign == 1) lipdstmpl[i]=-1*lipdstmpl[i]; + } + *iofst=*iofst+nbits; + } + // + // Check to see if the Product Definition Template needs to be + // extended. + // The number of values in a specific template may vary + // depending on data specified in the "static" part of the + // gtemplate. + // + if ( needext ==1 ) { + free(mappds); + mappds=extpdstemplate(*ipdsnum,lipdstmpl); + newlen=mappds->maplen+mappds->extlen; + lipdstmpl=(g2int *)realloc(lipdstmpl,newlen*sizeof(g2int)); + *ipdstmpl=lipdstmpl; + // Unpack the rest of the Product Definition Template + j=0; + for (i=*mappdslen;iext[j])*8; + if ( mappds->ext[j] >= 0 ) { + gbit(cgrib,lipdstmpl+i,*iofst,nbits); + } + else { + gbit(cgrib,&isign,*iofst,1); + gbit(cgrib,lipdstmpl+i,*iofst+1,nbits-1); + if (isign == 1) lipdstmpl[i]=-1*lipdstmpl[i]; + } + *iofst=*iofst+nbits; + j++; + } + *mappdslen=newlen; + } + if( mappds->ext != 0 ) free(mappds->ext); + if( mappds != 0 ) free(mappds); + // + // Get Optional list of vertical coordinate values + // after the Product Definition Template, if necessary. + // + *coordlist=0; // NULL + if ( *numcoord != 0 ) { + coordieee=(g2int *)calloc(*numcoord,sizeof(g2int)); + lcoordlist=(g2float *)calloc(*numcoord,sizeof(g2float)); + if (coordieee == 0 || lcoordlist == 0) { + ierr=6; + *numcoord=0; + *coordlist=0; // NULL + if( coordieee != 0 ) free(coordieee); + if( lcoordlist != 0 ) free(lcoordlist); + return(ierr); + } + else { + *coordlist=lcoordlist; + } + gbits(cgrib,coordieee,*iofst,32,0,*numcoord); + rdieee(coordieee,*coordlist,*numcoord); + free(coordieee); + *iofst=*iofst+(32*(*numcoord)); + } + + return(ierr); // End of Section 4 processing + +} diff --git a/pool/shard000/C/0009258_mcp32xx.c b/pool/shard000/C/0009258_mcp32xx.c new file mode 100644 index 0000000000000000000000000000000000000000..160c4536c5de3d1f1c991268550f7046be0e4bea --- /dev/null +++ b/pool/shard000/C/0009258_mcp32xx.c @@ -0,0 +1,95 @@ +/* + * mcp32xx.c + * + * simple control interface for MCP32XX ADC in userspace using spidev + * (C) 2013 Luotao Fu (devtty0@gmail.com) + * + * This file is part of radioberry. + * radioberry 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. + * radioberry 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 radioberry. If not, see . + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "mcp32xx.h" + +uint8_t mcp32xx_init(struct mcp32xx_dev *mcp_dev) +{ + uint8_t ret = 0; + + mcp_dev->spi_dev.dev_name = DEFAULT_SPIDEV_NAME; + mcp_dev->dev_conf.bits_per_word = 8; + mcp_dev->dev_conf.speed = SPIDEV_SPEED; + mcp_dev->dev_conf.lsb_first = 2; + + mcp_dev->spi_dev.conf = &(mcp_dev->dev_conf); + + + ret = spidev_initdev(&(mcp_dev->spi_dev)); + + if (ret) + goto err_out; + + spidev_setstat(&(mcp_dev->spi_dev)); + spidev_dumpstat(&(mcp_dev->spi_dev)); + +err_out: + return ret; +} + +void mcp32xx_close(struct mcp32xx_dev *mcp_dev) +{ + spidev_removedev(&(mcp_dev->spi_dev)); +} + +uint32_t mcp32xx_get_val(struct mcp32xx_dev *mcp_dev, uint8_t channel_sel) +{ + /* + * MCP32XX has 4 bits Control sequence (MCP3204 uses only 3 of them). + * 1.5 Cycles (makes 2 bits) sample time. and 12 bits output. Makes 18 + * bits all together. Hence we use 24 bits for the R/W buffer. + */ + uint8_t tx_buf[4], rx_buf[4]; + uint32_t output_val; + struct spidev_device *dev = &(mcp_dev->spi_dev); + + tx_buf[0] = SINGLE_CHANNEL(channel_sel); + + spidev_do_rw(dev, tx_buf, rx_buf, 4); + + /* + * RX buffer would look like this + * |D|D|D|D|D|D|D|B11|B10|B9|B8|B7|B6|B5|B4|B3|B2|B1|B0|D|D|D|D|D| + * |-----rx_buf[0]---|------rx_buf[1]---------|-----rx_buf[2]----| + */ + + output_val = ((rx_buf[0] & 0x1) << 16 | rx_buf[1] << 8 | + (rx_buf[2] & 0xe0)) >> 5; +#if 0 + printf("raw0: 0x%x, raw1: 0x%x, raw2: 0x%x, raw3: 0x%x\n", rx_buf[0], rx_buf[1], rx_buf[2], rx_buf[3]); +#endif + return output_val; +} + diff --git a/pool/shard000/C/0009261_errors.c b/pool/shard000/C/0009261_errors.c new file mode 100644 index 0000000000000000000000000000000000000000..5ef78ed83892408d6deb352e83ac4b91c7d44f4b --- /dev/null +++ b/pool/shard000/C/0009261_errors.c @@ -0,0 +1,198 @@ +/* + * Copyright 2016 Capital One Services, LLC + * + * 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 "common.h" + + +PyObject *TeradataError; +PyObject *GiraffezError; +PyObject *EncoderError; +PyObject *InvalidCredentialsError; + +typedef struct { + PyException_HEAD + PyObject *message; + PyObject *code; +} TeradataErrorObject; + +static int TeradataError_init(TeradataErrorObject *self, PyObject *args, PyObject *kwds) { + PyObject *msg = NULL; + PyObject *code = NULL; + PyObject *item = NULL; + PyObject *parts = NULL; + PyObject *colon = NULL; + PyObject *utmp = NULL; + Py_ssize_t size; + if (!PyArg_ParseTuple(args, "O", &msg)) { + return -1; + } + Py_INCREF(args); + Py_XSETREF(self->args, args); + colon = PyUnicode_FromString(":"); + if (PyBytes_Check(msg)) { + if ((utmp = PyUnicode_FromEncodedObject(msg, "UTF-8", NULL)) == NULL) { + goto error; + } + msg = utmp; + } + if ((parts = PyUnicode_Split(msg, colon, 1)) == NULL) { + goto error; + } + size = PyList_Size(parts); + if (size == 2) { + PyObject *cro = PyList_GET_ITEM(parts, 0); + if ((code = PyLong_FromUnicodeObject(cro, 10)) == NULL) { + goto error; + } + Py_XSETREF(self->code, code); + if ((item = PyList_GetItem(parts, 1)) == NULL) { + goto error; + } + Py_INCREF(PyList_GET_ITEM(parts, 1)); + Py_XSETREF(self->message, PyList_GET_ITEM(parts, 1)); + } + Py_XDECREF(utmp); + Py_XDECREF(colon); + return 0; +error: + Py_XDECREF(utmp); + Py_XDECREF(colon); + return -1; +} + +static int TeradataError_clear(TeradataErrorObject *self) { + Py_CLEAR(self->message); + Py_CLEAR(self->code); + Py_CLEAR(self->dict); + Py_CLEAR(self->args); + Py_CLEAR(self->traceback); + Py_CLEAR(self->cause); + Py_CLEAR(self->context); + return 0; +} + +static void TeradataError_dealloc(TeradataErrorObject *self) { + _PyObject_GC_UnTrack(self); + TeradataError_clear(self); + Py_TYPE(self)->tp_free((PyObject*)self); +} + +static int TeradataError_traverse(TeradataErrorObject *self, visitproc visit, void *arg) { + Py_VISIT(self->message); + Py_VISIT(self->code); + Py_VISIT(self->dict); + Py_VISIT(self->args); + Py_VISIT(self->traceback); + Py_VISIT(self->cause); + Py_VISIT(self->context); + return 0; +} + +static PyObject* TeradataError_repr(PyObject *obj) { + PyObject *message, *rep, *repr, *sub; + TeradataErrorObject *self = (TeradataErrorObject*)obj; + sub = PyUnicode_FromString("\x01"); + rep = PyUnicode_FromString(""); + if ((message = PyUnicode_Replace(self->message, sub, rep, -1)) == NULL) { + return NULL; + } + repr = PyUnicode_FromFormat("TeradataError(%S:%S)", self->code, message); + Py_DECREF(message); + Py_DECREF(sub); + Py_DECREF(rep); + return repr; +} + +static PyMemberDef TeradataError_members[] = { + {"message", T_OBJECT, offsetof(TeradataErrorObject, message), 0, PyDoc_STR("exception message")}, + {"code", T_OBJECT, offsetof(TeradataErrorObject, code), 0, PyDoc_STR("code name")}, + {NULL} /* Sentinel */ +}; + +PyTypeObject TeradataErrorType = { + PyVarObject_HEAD_INIT(NULL, 0) + "giraffez.TeradataErrorz", /* tp_name */ + sizeof(TeradataErrorObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)TeradataError_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + TeradataError_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE + | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + 0, /* tp_doc */ + (traverseproc)TeradataError_traverse, /* tp_traverse */ + (inquiry)TeradataError_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + TeradataError_members, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + offsetof(TeradataErrorObject, dict), /* tp_dictoffset */ + (initproc)TeradataError_init, /* tp_init */ + 0, /* tp_alloc */ + 0, // tp_new +}; + +PyObject* define_exceptions(PyObject *module) { + GiraffezError = PyErr_NewException("giraffez.Error", NULL, NULL); + PyModule_AddObject(module, "Error", GiraffezError); + + EncoderError = PyErr_NewException("giraffez.EncoderError", NULL, NULL); + PyModule_AddObject(module, "EncoderError", EncoderError); + + TeradataErrorType.tp_base = (PyTypeObject*)PyExc_Exception; + if (PyType_Ready(&TeradataErrorType) < 0) { + return NULL; + } + if ((TeradataError = PyErr_NewException("giraffez.TeradataError", (PyObject*)&TeradataErrorType, NULL)) == NULL) { + return NULL; + } + if (PyModule_AddObject(module, "TeradataError", TeradataError) == -1) { + return NULL; + } + + InvalidCredentialsError = PyErr_NewException("giraffez.InvalidCredentialsError", TeradataError, NULL); + PyModule_AddObject(module, "InvalidCredentialsError", InvalidCredentialsError); + Py_RETURN_NONE; +} + +void debug_printf(const char *fmt, ...) { + PyObject *s; + va_list vargs; + va_start(vargs, fmt); + s = PyUnicode_FromFormatV(fmt, vargs); + va_end(vargs); + fprintf(stderr, "DEBUG: %s\n", PyUnicode_AsUTF8(s)); + Py_XDECREF(s); +} diff --git a/pool/shard000/C/0009270_cp-confirm.c b/pool/shard000/C/0009270_cp-confirm.c new file mode 100644 index 0000000000000000000000000000000000000000..03cd227a590fea33023dbff37644d1b0dce05d4b --- /dev/null +++ b/pool/shard000/C/0009270_cp-confirm.c @@ -0,0 +1,154 @@ +#include + +#include /* stat */ +#include /* stat */ +#include /* lstat() */ + +#include "../../src/compat/fs_limits.h" +#include "../../src/io/iop.h" +#include "../../src/utils/fs.h" +#include "../../src/utils/utils.h" + +#include "utils.h" + +static int confirm_overwrite(io_args_t *args, const char src[], + const char dst[]); +static int deny_overwrite(io_args_t *args, const char src[], const char dst[]); + +static int confirm_called; + +TEST(confirm_is_not_called_for_no_overwrite) +{ + create_test_file(SANDBOX_PATH "/empty"); + + { + io_args_t args = { + .arg1.src = TEST_DATA_PATH "/read/two-lines", + .arg2.dst = SANDBOX_PATH "/empty", + .arg3.crs = IO_CRS_FAIL, + + .confirm = &confirm_overwrite, + }; + ioe_errlst_init(&args.result.errors); + + confirm_called = 0; + assert_failure(iop_cp(&args)); + assert_int_equal(0, confirm_called); + + assert_true(args.result.errors.error_count != 0); + ioe_errlst_free(&args.result.errors); + } + + delete_test_file(SANDBOX_PATH "/empty"); +} + +TEST(confirm_is_called_for_overwrite) +{ + create_test_file(SANDBOX_PATH "/empty"); + clone_test_file(SANDBOX_PATH "/empty", SANDBOX_PATH "/empty-copy"); + + { + io_args_t args = { + .arg1.src = TEST_DATA_PATH "/read/two-lines", + .arg2.dst = SANDBOX_PATH "/empty", + .arg3.crs = IO_CRS_REPLACE_FILES, + + .confirm = &confirm_overwrite, + }; + ioe_errlst_init(&args.result.errors); + + confirm_called = 0; + assert_success(iop_cp(&args)); + assert_int_equal(1, confirm_called); + + /* Skipping file by user is not real error. */ + assert_int_equal(0, args.result.errors.error_count); + } + + assert_true(files_are_identical(TEST_DATA_PATH "/read/two-lines", + SANDBOX_PATH "/empty")); + assert_false(files_are_identical(SANDBOX_PATH "/empty", + SANDBOX_PATH "/empty-copy")); + + delete_test_file(SANDBOX_PATH "/empty"); + delete_test_file(SANDBOX_PATH "/empty-copy"); +} + +TEST(no_confirm_on_appending) +{ + create_test_file(SANDBOX_PATH "/empty"); + clone_test_file(SANDBOX_PATH "/empty", SANDBOX_PATH "/empty-copy"); + + { + io_args_t args = { + .arg1.src = TEST_DATA_PATH "/read/two-lines", + .arg2.dst = SANDBOX_PATH "/empty", + .arg3.crs = IO_CRS_APPEND_TO_FILES, + + .confirm = &confirm_overwrite, + }; + ioe_errlst_init(&args.result.errors); + + confirm_called = 0; + assert_success(iop_cp(&args)); + assert_int_equal(0, confirm_called); + + assert_int_equal(0, args.result.errors.error_count); + } + + assert_true(files_are_identical(TEST_DATA_PATH "/read/two-lines", + SANDBOX_PATH "/empty")); + assert_false(files_are_identical(SANDBOX_PATH "/empty", + SANDBOX_PATH "/empty-copy")); + + delete_test_file(SANDBOX_PATH "/empty"); + delete_test_file(SANDBOX_PATH "/empty-copy"); +} + +TEST(deny_to_overwrite_is_considered) +{ + create_test_file(SANDBOX_PATH "/empty"); + clone_test_file(SANDBOX_PATH "/empty", SANDBOX_PATH "/empty-copy"); + + { + io_args_t args = { + .arg1.src = TEST_DATA_PATH "/read/two-lines", + .arg2.dst = SANDBOX_PATH "/empty", + .arg3.crs = IO_CRS_REPLACE_FILES, + + .confirm = &deny_overwrite, + }; + ioe_errlst_init(&args.result.errors); + + confirm_called = 0; + assert_success(iop_cp(&args)); + assert_int_equal(1, confirm_called); + + assert_int_equal(0, args.result.errors.error_count); + } + + assert_false(files_are_identical(TEST_DATA_PATH "/read/two-lines", + SANDBOX_PATH "/empty")); + assert_true(files_are_identical(SANDBOX_PATH "/empty", + SANDBOX_PATH "/empty-copy")); + + delete_test_file(SANDBOX_PATH "/empty"); + delete_test_file(SANDBOX_PATH "/empty-copy"); +} + +static int +confirm_overwrite(io_args_t *args, const char src[], const char dst[]) +{ + ++confirm_called; + return 1; +} + +static int +deny_overwrite(io_args_t *args, const char src[], const char dst[]) +{ + ++confirm_called; + return 0; +} + +/* vim: set tabstop=2 softtabstop=2 shiftwidth=2 noexpandtab cinoptions-=(0 : */ +/* vim: set cinoptions+=t0 filetype=c : */ diff --git a/pool/shard000/C/0009278_yylex_tests.c b/pool/shard000/C/0009278_yylex_tests.c new file mode 100644 index 0000000000000000000000000000000000000000..ef40ffe83a9a3c38ea08b703e17c44cb434a8331 --- /dev/null +++ b/pool/shard000/C/0009278_yylex_tests.c @@ -0,0 +1,80 @@ +#include + +#include "yylex.h" +/* Declare semi-private function */ +void processDefine(bool argFlag); + +#include "filedescriptor.h" +#include "filetab.h" +#include "fileitem.h" +#include "symboltable.h" +#include "macroargumenttable.h" +#include "symbol.h" + +#include "globals.mock" +#include "caching.mock" +#include "parsers.mock" +#include "cexp_parser.mock" +#include "jslsemact.mock" +#include "jsemact.mock" +#include "reftab.mock" +#include "editor.mock" +#include "commons.mock" +#include "misc.mock" +#include "cxfile.mock" +#include "characterbuffer.mock" +#include "lex.mock" +#include "semact.mock" +#include "java_parser.mock" +#include "cxref.mock" +#include "extract.mock" +#include "c_parser.mock" +#include "yacc_parser.mock" + + +Describe(Yylex); +BeforeEach(Yylex) { + stackMemoryInit(); + ppMemInit(); + initFileTab(&s_fileTab); + XX_ALLOC(s_symbolTable, S_symbolTable); + symbolTableInit(s_symbolTable, 10); +} +AfterEach(Yylex) {} + +static void setup_lexBuffer_for_reading(void *data) { + /* Need to insert lexem-codes first ? */ + cFile.lexBuffer.chars[0] = '\275'; + cFile.lexBuffer.chars[1] = '\001'; + strcpy(&cFile.lexBuffer.chars[2], cFile.lexBuffer.buffer.chars); + *strchr(&cFile.lexBuffer.chars[2], ' ') = '\0'; + cFile.lexBuffer.next = cFile.lexBuffer.chars; + cFile.lexBuffer.end = strchr(cFile.lexBuffer.chars, '\0'); + cFile.lexBuffer.posi = 2; +} + +Ensure(Yylex, add_a_cpp_definition_to_the_symbol_table) { +# define DEFINE "__x86_64__" + char *definition = (char *)malloc(strlen(DEFINE)+1); + strcpy(definition, DEFINE); + + expect(getLexBuf, when(buffer, is_equal_to(&cFile.lexBuffer)), + will_return(1), with_side_effect(setup_lexBuffer_for_reading, NULL)); + expect(setGlobalFileDepNames, when(iname, is_equal_to_string(definition)), + will_set_contents_of_parameter(pp_name, &definition, sizeof(char *))); + expect(getLexBuf, when(buffer, is_equal_to(&cFile.lexBuffer)), + will_return(0)); + + /* This is the confirmation that there is a symbol p with a + * field named name equal to DEFINE + */ + expect(addCxReference, when(p_name, is_equal_to_string(DEFINE))); + + s_opt.taskRegime = RegimeXref; + /* If the define does not have a body, add the value of "1" */ + initInput(NULL, NULL, "__x86_64__ 1", NULL); + cFile.lineNumber = 1; + processDefine(false); + + /* Inspect symboltable for the define */ +} diff --git a/pool/shard000/C/0009280_s_logbf.c b/pool/shard000/C/0009280_s_logbf.c new file mode 100644 index 0000000000000000000000000000000000000000..38a7b973df68dc74c590dc661fa50840659382bb --- /dev/null +++ b/pool/shard000/C/0009280_s_logbf.c @@ -0,0 +1,41 @@ +/* s_logbf.c -- float version of s_logb.c. + * Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com. + */ + +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ + +#include +#include + +float +__logbf (float x) +{ + int32_t ix, rix; + float ret; + + GET_FLOAT_WORD (ix, x); + ix &= 0x7fffffff; /* high |x| */ + if (ix == 0) + return (float) -1.0 / fabsf (x); + if (ix >= 0x7f800000) + return x * x; + if (__builtin_expect ((rix = ix >> 23) == 0, 0)) + { + /* POSIX specifies that denormal number is treated as + though it were normalized. */ + rix -= __builtin_clz (ix) - 9; + } + ret = (float) (rix - 127); + /* The test is to avoid logb_downward (0.0) == -0.0. */ + return ret == -0.0 ? 0.0 : ret; +} +weak_alias (__logbf, logbf) diff --git a/pool/shard000/C/0009282_libip6t_icmp6.c b/pool/shard000/C/0009282_libip6t_icmp6.c new file mode 100644 index 0000000000000000000000000000000000000000..68b940bd517d5fe19996712af3d0f3dd9bbede5c --- /dev/null +++ b/pool/shard000/C/0009282_libip6t_icmp6.c @@ -0,0 +1,239 @@ +#include +#include +#include +#include +#include /* INT_MAX in ip6_tables.h */ +#include + +enum { + O_ICMPV6_TYPE = 0, +}; + +struct icmpv6_names { + const char *name; + uint8_t type; + uint8_t code_min, code_max; +}; + +static const struct icmpv6_names icmpv6_codes[] = { + { "destination-unreachable", 1, 0, 0xFF }, + { "no-route", 1, 0, 0 }, + { "communication-prohibited", 1, 1, 1 }, + { "address-unreachable", 1, 3, 3 }, + { "port-unreachable", 1, 4, 4 }, + + { "packet-too-big", 2, 0, 0xFF }, + + { "time-exceeded", 3, 0, 0xFF }, + /* Alias */ { "ttl-exceeded", 3, 0, 0xFF }, + { "ttl-zero-during-transit", 3, 0, 0 }, + { "ttl-zero-during-reassembly", 3, 1, 1 }, + + { "parameter-problem", 4, 0, 0xFF }, + { "bad-header", 4, 0, 0 }, + { "unknown-header-type", 4, 1, 1 }, + { "unknown-option", 4, 2, 2 }, + + { "echo-request", 128, 0, 0xFF }, + /* Alias */ { "ping", 128, 0, 0xFF }, + + { "echo-reply", 129, 0, 0xFF }, + /* Alias */ { "pong", 129, 0, 0xFF }, + + { "router-solicitation", 133, 0, 0xFF }, + + { "router-advertisement", 134, 0, 0xFF }, + + { "neighbour-solicitation", 135, 0, 0xFF }, + /* Alias */ { "neighbor-solicitation", 135, 0, 0xFF }, + + { "neighbour-advertisement", 136, 0, 0xFF }, + /* Alias */ { "neighbor-advertisement", 136, 0, 0xFF }, + + { "redirect", 137, 0, 0xFF }, + +}; + +static void +print_icmpv6types(void) +{ + unsigned int i; + printf("Valid ICMPv6 Types:"); + + for (i = 0; i < ARRAY_SIZE(icmpv6_codes); ++i) { + if (i && icmpv6_codes[i].type == icmpv6_codes[i-1].type) { + if (icmpv6_codes[i].code_min == icmpv6_codes[i-1].code_min + && (icmpv6_codes[i].code_max + == icmpv6_codes[i-1].code_max)) + printf(" (%s)", icmpv6_codes[i].name); + else + printf("\n %s", icmpv6_codes[i].name); + } + else + printf("\n%s", icmpv6_codes[i].name); + } + printf("\n"); +} + +static void icmp6_help(void) +{ + printf( +"icmpv6 match options:\n" +"[!] --icmpv6-type typename match icmpv6 type\n" +" (or numeric type or type/code)\n"); + print_icmpv6types(); +} + +static const struct xt_option_entry icmp6_opts[] = { + {.name = "icmpv6-type", .id = O_ICMPV6_TYPE, .type = XTTYPE_STRING, + .flags = XTOPT_MAND | XTOPT_INVERT}, + XTOPT_TABLEEND, +}; + +static void +parse_icmpv6(const char *icmpv6type, uint8_t *type, uint8_t code[]) +{ + static const unsigned int limit = ARRAY_SIZE(icmpv6_codes); + unsigned int match = limit; + unsigned int i; + + for (i = 0; i < limit; i++) { + if (strncasecmp(icmpv6_codes[i].name, icmpv6type, strlen(icmpv6type)) + == 0) { + if (match != limit) + xtables_error(PARAMETER_PROBLEM, + "Ambiguous ICMPv6 type `%s':" + " `%s' or `%s'?", + icmpv6type, + icmpv6_codes[match].name, + icmpv6_codes[i].name); + match = i; + } + } + + if (match != limit) { + *type = icmpv6_codes[match].type; + code[0] = icmpv6_codes[match].code_min; + code[1] = icmpv6_codes[match].code_max; + } else { + char *slash; + char buffer[strlen(icmpv6type) + 1]; + unsigned int number; + + strcpy(buffer, icmpv6type); + slash = strchr(buffer, '/'); + + if (slash) + *slash = '\0'; + + if (!xtables_strtoui(buffer, NULL, &number, 0, UINT8_MAX)) + xtables_error(PARAMETER_PROBLEM, + "Invalid ICMPv6 type `%s'\n", buffer); + *type = number; + if (slash) { + if (!xtables_strtoui(slash+1, NULL, &number, 0, UINT8_MAX)) + xtables_error(PARAMETER_PROBLEM, + "Invalid ICMPv6 code `%s'\n", + slash+1); + code[0] = code[1] = number; + } else { + code[0] = 0; + code[1] = 0xFF; + } + } +} + +static void icmp6_init(struct xt_entry_match *m) +{ + struct ip6t_icmp *icmpv6info = (struct ip6t_icmp *)m->data; + + icmpv6info->code[1] = 0xFF; +} + +static void icmp6_parse(struct xt_option_call *cb) +{ + struct ip6t_icmp *icmpv6info = cb->data; + + xtables_option_parse(cb); + parse_icmpv6(cb->arg, &icmpv6info->type, icmpv6info->code); + if (cb->invert) + icmpv6info->invflags |= IP6T_ICMP_INV; +} + +static void print_icmpv6type(uint8_t type, + uint8_t code_min, uint8_t code_max, + int invert, + int numeric) +{ + if (!numeric) { + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(icmpv6_codes); ++i) + if (icmpv6_codes[i].type == type + && icmpv6_codes[i].code_min == code_min + && icmpv6_codes[i].code_max == code_max) + break; + + if (i != ARRAY_SIZE(icmpv6_codes)) { + printf(" %s%s", + invert ? "!" : "", + icmpv6_codes[i].name); + return; + } + } + + if (invert) + printf(" !"); + + printf("type %u", type); + if (code_min == code_max) + printf(" code %u", code_min); + else if (code_min != 0 || code_max != 0xFF) + printf(" codes %u-%u", code_min, code_max); +} + +static void icmp6_print(const void *ip, const struct xt_entry_match *match, + int numeric) +{ + const struct ip6t_icmp *icmpv6 = (struct ip6t_icmp *)match->data; + + printf(" ipv6-icmp"); + print_icmpv6type(icmpv6->type, icmpv6->code[0], icmpv6->code[1], + icmpv6->invflags & IP6T_ICMP_INV, + numeric); + + if (icmpv6->invflags & ~IP6T_ICMP_INV) + printf(" Unknown invflags: 0x%X", + icmpv6->invflags & ~IP6T_ICMP_INV); +} + +static void icmp6_save(const void *ip, const struct xt_entry_match *match) +{ + const struct ip6t_icmp *icmpv6 = (struct ip6t_icmp *)match->data; + + if (icmpv6->invflags & IP6T_ICMP_INV) + printf(" !"); + + printf(" --icmpv6-type %u", icmpv6->type); + if (icmpv6->code[0] != 0 || icmpv6->code[1] != 0xFF) + printf("/%u", icmpv6->code[0]); +} + +static struct xtables_match icmp6_mt6_reg = { + .name = "icmp6", + .version = XTABLES_VERSION, + .family = NFPROTO_IPV6, + .size = XT_ALIGN(sizeof(struct ip6t_icmp)), + .userspacesize = XT_ALIGN(sizeof(struct ip6t_icmp)), + .help = icmp6_help, + .init = icmp6_init, + .print = icmp6_print, + .save = icmp6_save, + .x6_parse = icmp6_parse, + .x6_options = icmp6_opts, +}; + +void _init(void) +{ + xtables_register_match(&icmp6_mt6_reg); +} diff --git a/pool/shard000/C/0009283_gpio.c b/pool/shard000/C/0009283_gpio.c new file mode 100644 index 0000000000000000000000000000000000000000..ffbb9dd5202df859a3ca5a3311dd1d88ceab7356 --- /dev/null +++ b/pool/shard000/C/0009283_gpio.c @@ -0,0 +1,114 @@ +/* title: General-Purpose-I/O impl + + Verwendete Bezeichnungen: + Z.B. mit PD0 ist der Pin 0 des Ports D gemeint. + + Copyright: + This program is free software. See accompanying LICENSE file. + + Author: + (C) 2016 Jörg Seebohn + + file: gpio.h + Header file . + + file: gpio.c + Implementation file . +*/ +#include "konfig.h" +#include "µC/gpio.h" + +/* Register Offset (SYSCFG_EXTICR1) External interrupt configuration register 1; Reset value: 0x00000000 + * Bits 15:12: EXTI-3, Bits 11:8 EXTI-2, Bits 7:4 EXTI-1, Bits 3:0 EXTI-0 + * These bits are written by software to select the source input for the EXTI-N external interrupt. + * x000: PA[N] pin; valid for 0 <= N <= 15 + * x001: PB[N] pin; valid for 0 <= N <= 15 + * x010: PC[N] pin; valid for 0 <= N <= 15 + * x011: PD[N] pin; valid for 0 <= N <= 15 + * x100: PE[N] pin; valid for 0 <= N <= 15 + * x101: PF[N] pin; valid for 0 <= N <= 15 + * x110: PG[N] pin; valid for 0 <= N <= 15 + * x111: PH[N] pin; only valid for 0 <= N <= 2 */ +#define HW_REGISTER_OFFSET_SYSCFG_EXTICR1 0x08 +/* Register Offset (SYSCFG_EXTICR2) External interrupt configuration register 2; Reset value: 0x00000000 + * Bits 15:12: EXTI-7, Bits 11:8 EXTI-6, Bits 7:4 EXTI-5, Bits 3:0 EXTI-4 */ +#define HW_REGISTER_OFFSET_SYSCFG_EXTICR2 0x0C +/* Register Offset (SYSCFG_EXTICR3) External interrupt configuration register 3; Reset value: 0x00000000 + * Bits 15:12: EXTI-11, Bits 11:8 EXTI-10, Bits 7:4 EXTI-9, Bits 3:0 EXTI-8 */ +#define HW_REGISTER_OFFSET_SYSCFG_EXTICR3 0x10 +/* Register Offset (SYSCFG_EXTICR4) External interrupt configuration register 4; Reset value: 0x00000000 + * Bits 15:12: EXTI-15, Bits 11:8 EXTI-14, Bits 7:4 EXTI-13, Bits 3:0 EXTI-12 */ +#define HW_REGISTER_OFFSET_SYSCFG_EXTICR4 0x14 + +static inline uint32_t get_portnr(uint8_t port_bit) +{ + uint32_t portnr = 0; + while ((port_bit >>= 1)) { + ++portnr; + } + return portnr; +} + +static inline int isvalid_portnr(uint32_t portnr) +{ + return portnr <= 5; +} + +static void select_interrupt_port(uint8_t portnr, uint16_t pins) +{ + volatile uint32_t *exticr = & HW_REGISTER(SYSCFG, EXTICR1); + static_assert( HW_REGISTER_OFFSET_SYSCFG_EXTICR1 + 4 == HW_REGISTER_OFFSET_SYSCFG_EXTICR2 + && HW_REGISTER_OFFSET_SYSCFG_EXTICR2 + 4 == HW_REGISTER_OFFSET_SYSCFG_EXTICR3 + && HW_REGISTER_OFFSET_SYSCFG_EXTICR3 + 4 == HW_REGISTER_OFFSET_SYSCFG_EXTICR4); + for (uint16_t pin=0, val; (val=pins>>pin); ++pin) { + if (!(val&1)) continue; + uint16_t shift = 4 * (pin&0x3); + volatile uint32_t *exticrN = exticr + (pin >> 2); + *exticrN = (*exticrN & ~(0x0f << shift)) | (portnr << shift); + } +} + +int config_interrupts_gpio(uint8_t port_bit, uint16_t pins, interrupt_edge_e edge) +{ + if (((port_bit-1) & port_bit) != 0) { + // port_bit == 0 || "more than one port bit set" + return EINVAL; + } + + uint32_t portnr = get_portnr(port_bit); + if (! isvalid_portnr(portnr)) return EINVAL; + + // select pins for corresponding ports, only one port could be active per pin number + select_interrupt_port(portnr, pins); + + // select event when interrupt request is generated + if ((edge & interrupt_edge_RISING) != 0) { + HW_REGISTER(EXTI, RTSR1) |= pins; + } else { + HW_SREGISTER(EXTI, RTSR1) &= ~pins; + } + if ((edge & interrupt_edge_FALLING) != 0) { + HW_SREGISTER(EXTI, FTSR1) |= pins; + } else { + HW_SREGISTER(EXTI, FTSR1) &= ~pins; + } + + // clear any pending interrupts + HW_SREGISTER(EXTI, PR1) |= pins; + + return 0; +} + +void update_pull_gpio(volatile struct gpio_port_t *port, uint16_t pins, gpiocfg_e pull/*masked with gpiocfg_MASK_PULLUPDOWN*/) +{ + uint32_t mask = 0; + uint32_t bits = 0; + static_assert(gpiocfg_MASK_PULLUPDOWN == (3 << gpiocfg_POS_PULLUPDOWN)); + pull = (pull >> gpiocfg_POS_PULLUPDOWN) & 3; + for (uint16_t pin=0, val; (val=pins>>pin); ++pin) { + if (!(val&1)) continue; + mask |= (3 << (2*pin)); + bits |= (pull << (2*pin)); + } + port->pull = (port->pull & ~mask) | bits; +} diff --git a/pool/shard000/C/0009290_vmapiImageVolumeSpaceDefineExtendedDm.c b/pool/shard000/C/0009290_vmapiImageVolumeSpaceDefineExtendedDm.c new file mode 100644 index 0000000000000000000000000000000000000000..5c64fc44d1abf23e5be6e083f52ea04d29ac45a6 --- /dev/null +++ b/pool/shard000/C/0009290_vmapiImageVolumeSpaceDefineExtendedDm.c @@ -0,0 +1,96 @@ +/** + * Copyright 2017 IBM Corporation + * + * 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 "smSocket.h" +#include "vmapiImage.h" +#include "smapiTableParser.h" +#include +#include +#include + +#define PARSER_TABLE_NAME Image_Volume_Space_Define_Extended_DM_Layout +#define OUTPUT_STRUCTURE_NAME vmApiImageVolumeSpaceDefineExtendedDmOutput + +/** + * Image_Volume_Space_Define_Extended_DM SMAPI interface + */ +int smImage_Volume_Space_Define_Extended_DM(struct _vmApiInternalContext* vmapiContextP, + char * userid, int passwordLength, char * password, + char * targetIdentifier, int keyValueCount, + char ** keyValueArray, vmApiImageVolumeSpaceDefineExtendedDmOutput ** outData) { + const char * const functionName = "Image_Volume_Space_Define_Extended_DM"; + tableParserParms parserParms; + int tempSize; + int keyValueSize = 0; + char * cursor; + int rc; + + int inputSize = 4 + 4 + strlen(functionName) + 4 + strlen(userid) + 4 + + passwordLength + 4 + strlen(targetIdentifier) + 4; + char * inputP = 0; + int i; + + for (i = 0; i < keyValueCount; i++) { + inputSize += strlen(keyValueArray[i]) + 1; + keyValueSize += strlen(keyValueArray[i]) + 1; + } + + // Build SMAPI input parameter buffer + if (0 == (inputP = malloc(inputSize))) + return MEMORY_ERROR; + cursor = inputP; + PUT_INT(inputSize - 4, cursor); + + tempSize = strlen(functionName); + PUT_INT(tempSize, cursor); + memcpy(cursor, functionName, tempSize); + cursor += tempSize; + + tempSize = strlen(userid); // UserId 1..8 or 0..8 chars + PUT_INT(tempSize, cursor); + if (tempSize > 0) { + memcpy(cursor, userid, tempSize); + cursor += tempSize; + } + + tempSize = passwordLength; // Password 1..200 or 0..200 chars + PUT_INT(tempSize, cursor); + if (tempSize > 0) { + memcpy(cursor, password, tempSize); + cursor += tempSize; + } + + tempSize = strlen(targetIdentifier); // Target identifier 1..8 + PUT_INT(tempSize, cursor); + memcpy(cursor, targetIdentifier, tempSize); + cursor += tempSize; + + tempSize = keyValueSize; // Total Key value size + PUT_INT(tempSize, cursor); + + for (i = 0; i < keyValueCount; i++) { // Keyword = value terminated strings + tempSize = strlen(keyValueArray[i]) + 1; + strcpy(cursor, keyValueArray[i]); + cursor += tempSize; + } + + // This routine will send SMAPI the input, delete the input storage + // and call the table parser to set the output in outData + rc = getAndParseSmapiBuffer(vmapiContextP, &inputP, inputSize, + PARSER_TABLE_NAME, // Integer table + TO_STRING(PARSER_TABLE_NAME), // String name of the table + (char * *) outData); + return rc; +} diff --git a/pool/shard000/C/0009292_p_sign.c b/pool/shard000/C/0009292_p_sign.c new file mode 100644 index 0000000000000000000000000000000000000000..1889117d39ccce2aa822738da1496d1b71a98edd --- /dev/null +++ b/pool/shard000/C/0009292_p_sign.c @@ -0,0 +1,149 @@ +/* crypto/evp/p_sign.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * 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 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 cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +#include +#include "cryptlib.h" +#include +#include +#include + +#ifdef undef +void EVP_SignInit(EVP_MD_CTX *ctx, EVP_MD *type) + { + EVP_DigestInit_ex(ctx,type); + } + +void EVP_SignUpdate(EVP_MD_CTX *ctx, unsigned char *data, + unsigned int count) + { + EVP_DigestUpdate(ctx,data,count); + } +#endif + +int EVP_SignFinal(EVP_MD_CTX *ctx, unsigned char *sigret, unsigned int *siglen, + EVP_PKEY *pkey) + { + unsigned char m[EVP_MAX_MD_SIZE]; + unsigned int m_len; + int i = 0,ok = 0,v; + EVP_PKEY_CTX *pkctx = NULL; + + *siglen=0; + if (ctx->flags & EVP_MD_CTX_FLAG_FINALISE) + { + if (!EVP_DigestFinal_ex(ctx, m, &m_len)) + goto err; + } + else + { + int rv; + EVP_MD_CTX tmp_ctx; + EVP_MD_CTX_init(&tmp_ctx); + rv = EVP_MD_CTX_copy_ex(&tmp_ctx,ctx); + if (rv) + rv = EVP_DigestFinal_ex(&tmp_ctx, m, &m_len); + EVP_MD_CTX_cleanup(&tmp_ctx); + if (!rv) + return 0; + } + + if (ctx->digest->flags & EVP_MD_FLAG_PKEY_METHOD_SIGNATURE) + { + size_t sltmp = (size_t)EVP_PKEY_size(pkey); + i = 0; + pkctx = EVP_PKEY_CTX_new(pkey, NULL); + if (!pkctx) + goto err; + if (EVP_PKEY_sign_init(pkctx) <= 0) + goto err; + if (EVP_PKEY_CTX_set_signature_md(pkctx, ctx->digest) <= 0) + goto err; + if (EVP_PKEY_sign(pkctx, sigret, &sltmp, m, m_len) <= 0) + goto err; + *siglen = sltmp; + i = 1; + err: + EVP_PKEY_CTX_free(pkctx); + return i; + } + + for (i=0; i<4; i++) + { + v=ctx->digest->required_pkey_type[i]; + if (v == 0) break; + if (pkey->type == v) + { + ok=1; + break; + } + } + if (!ok) + { + EVPerr(EVP_F_EVP_SIGNFINAL,EVP_R_WRONG_PUBLIC_KEY_TYPE); + return(0); + } + + if (ctx->digest->sign == NULL) + { + EVPerr(EVP_F_EVP_SIGNFINAL,EVP_R_NO_SIGN_FUNCTION_CONFIGURED); + return(0); + } + return ctx->digest->sign(ctx->digest->type,m,m_len,sigret,siglen, + pkey->pkey.ptr); + } + diff --git a/pool/shard000/C/0009297_sendfile.c b/pool/shard000/C/0009297_sendfile.c new file mode 100644 index 0000000000000000000000000000000000000000..81000720b8ff11f237456818195278c6186c3b83 --- /dev/null +++ b/pool/shard000/C/0009297_sendfile.c @@ -0,0 +1,69 @@ +/* COVERAGE: sendfile sendfile64 */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +int main () +{ + int fd, read_fd; + int write_fd; + off_t offset = 0; + char buff[22]; // Note below 22 == EINVAL + int ret; + + memset(buff, 5, sizeof(buff)); + + /* create a file with something in it */ + fd = creat("foobar",S_IREAD|S_IWRITE); + write(fd, buff, sizeof(buff)); + fsync(fd); + close(fd); + read_fd = open ("foobar", O_RDONLY); + if (read_fd < 0) + return 1; + + /* Open the output file for writing */ + write_fd = creat("foobar2",S_IREAD|S_IWRITE|S_IRWXO); + + /* + * For 2.6 the write_fd had to be a socket otherwise + * sendfile would fail. So we also test for failure here. + */ + ret = sendfile (write_fd, read_fd, &offset, sizeof(buff)); + //staptest// sendfile (NNNN, NNNN, XXXX, 22) = -?22 + + sendfile (-1, read_fd, &offset, sizeof(buff)); + //staptest// sendfile (-1, NNNN, XXXX, 22) = -NNNN (EBADF) + + sendfile (write_fd, -1, &offset, sizeof(buff)); + //staptest// sendfile (NNNN, -1, XXXX, 22) = -NNNN (EBADF) + + sendfile (write_fd, read_fd, (off_t *)-1, sizeof(buff)); +#ifdef __s390__ + //staptest// sendfile (NNNN, NNNN, 0x[7]?[f]+, 22) = -NNNN (EFAULT) +#else + //staptest// sendfile (NNNN, NNNN, 0x[f]+, 22) = -NNNN (EFAULT) +#endif + + sendfile (write_fd, read_fd, &offset, -1); + // The 'count' argument is a size_t, which is an unsigned + // long, whose size varies by platform. (The return value + // varies here as well, so we'll just ignore it.) +#if __WORDSIZE == 64 + //staptest// sendfile (NNNN, NNNN, XXXX, 18446744073709551615) +#else + //staptest// sendfile (NNNN, NNNN, XXXX, 4294967295) +#endif + close (read_fd); + close (write_fd); + unlink("foobar"); + unlink("foobar2"); + + return 0; +} diff --git a/pool/shard000/C/0009302_skiperror.c b/pool/shard000/C/0009302_skiperror.c new file mode 100644 index 0000000000000000000000000000000000000000..c28fb529f73c66893c59f932c05aa8493d599bac --- /dev/null +++ b/pool/shard000/C/0009302_skiperror.c @@ -0,0 +1,58 @@ +/* + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Library General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor Boston, MA 02110-1301, USA + */ + +#include "remotecmd.h" + +int SkipError(char *cmderr) { + FILE *errfl; + char line[MAXLEN]; + char *errtok = NULL; + regex_t regex; + size_t num_fnd = 0; + + if ( skiperr > 0 ) { + if ( (errfl = fopen(errfile, "r")) == 0 ) { + fprintf(stderr, "Could not open skipFile \"%s\":%s\n", + errfile, strerror(errno)); + exit(-1); + } + while ( fgets(line, sizeof(line), errfl) != NULL ) { + errtok = strdup(line); + trim(errtok); + + if ( SkipComments(errtok) && strlen(errtok) > 1 ) { + if ( regcomp(®ex, errtok, REG_EXTENDED|REG_ICASE|REG_NOSUB) != 0) { + fprintf(stderr,"Invalid Regular Expression: \"%s\\n",errtok); + free(errtok); + regfree(®ex); + free(®ex); + exit(-1); + } + if ( regexec(®ex, cmderr, num_fnd, NULL, 0) == 0 ) { + free(errtok); + regfree(®ex); + free(®ex); + return 1; + } + regfree(®ex); + free(®ex); + } + free(errtok); + } + } + return 0; +} + diff --git a/pool/shard000/C/0009314_scim-bridge-message.c b/pool/shard000/C/0009314_scim-bridge-message.c new file mode 100644 index 0000000000000000000000000000000000000000..7a741be9cf8c8395e3a519dc17ce1a6a4003098a --- /dev/null +++ b/pool/shard000/C/0009314_scim-bridge-message.c @@ -0,0 +1,140 @@ +/* + * SCIM Bridge + * + * Copyright (c) 2006 Ryo Dairiki + * + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation and + * appearing in the file LICENSE.LGPL included in the package of this file. + * You can also redistribute it and/or modify it under the terms of + * the GNU General Public License as published by the Free Software Foundation and + * appearing in the file LICENSE.GPL included in the package of this file. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + */ + +#include +#include +#include + +#include "scim-bridge-message.h" +#include "scim-bridge-output.h" + +/* Type definition */ +struct _ScimBridgeMessage +{ + char *header; + + char **arguments; + size_t *argument_capacities; + size_t argument_count; +}; + +/* Implementations */ +ScimBridgeMessage *scim_bridge_alloc_message (const char *header, size_t argument_count) +{ + if (header == NULL) { + scim_bridge_perrorln ("The given header of a message is NULL"); + return NULL; + } + + ScimBridgeMessage *message = malloc (sizeof (ScimBridgeMessage)); + + message->header = malloc (sizeof (char) * (strlen (header) + 1)); + strcpy (message->header, header); + + message->argument_count = argument_count; + if (argument_count > 0) { + message->arguments = malloc (sizeof (char*) * message->argument_count); + message->argument_capacities = malloc (sizeof (size_t) * message->argument_count); + } else { + message->arguments = NULL; + message->argument_capacities = NULL; + } + int i; + for (i = 0; i < message->argument_count; ++i) { + message->argument_capacities[i] = 10; + message->arguments[i] = malloc (sizeof (char) * (message->argument_capacities[i] + 1)); + message->arguments[i][0] = '\0'; + } + + return message; +} + + +void scim_bridge_free_message (ScimBridgeMessage *message) +{ + if (message == NULL) return; + + free (message->header); + + int i; + for (i = 0; i < message->argument_count; ++i) { + free (message->arguments[i]); + } + + if (message->argument_capacities) free (message->argument_capacities); + if (message->arguments) free (message->arguments); + free (message); +} + + +const char *scim_bridge_message_get_header (const ScimBridgeMessage *message) +{ + return message->header; +} + + +size_t scim_bridge_message_get_argument_count (const ScimBridgeMessage *message) +{ + return message->argument_count; +} + + +const char *scim_bridge_message_get_argument (const ScimBridgeMessage *message, size_t index) +{ + if (message == NULL) { + scim_bridge_perrorln ("The pointer given as a message is NULL"); + return NULL; + } + + if (index >= message->argument_count) { + scim_bridge_perrorln ("An out of bounds exception occurred at scim_bridge_message_get_argument ()"); + return NULL; + } else { + return message->arguments[index]; + } +} + + +retval_t scim_bridge_message_set_argument (ScimBridgeMessage *message, size_t index, const char *argument) +{ + if (argument == NULL) { + scim_bridge_perrorln ("The pointer given as an argument is NULL"); + return RETVAL_FAILED; + } + + if (message == NULL) { + scim_bridge_perrorln ("The pointer given as a message is NULL"); + return RETVAL_FAILED; + } + + if (index >= message->argument_count) { + scim_bridge_perrorln ("An out of bounds exception occurred at scim_bridge_message_set_argument ()"); + return RETVAL_FAILED; + } else { + const size_t argument_length = strlen (argument); + if (argument_length > message->argument_capacities[index]) { + const size_t new_argument_capacity = argument_length; + free (message->arguments[index]); + message->arguments[index] = malloc (sizeof (char) * (new_argument_capacity + 1)); + message->argument_capacities[index] = new_argument_capacity; + } + strcpy (message->arguments[index], argument); + return RETVAL_SUCCEEDED; + } +} diff --git a/pool/shard000/C/0009315_oom04.c b/pool/shard000/C/0009315_oom04.c new file mode 100644 index 0000000000000000000000000000000000000000..58266327503e290a7032003223527685553deac9 --- /dev/null +++ b/pool/shard000/C/0009315_oom04.c @@ -0,0 +1,105 @@ +/* + * Out Of Memory (OOM) for CPUSET + * + * The program is designed to cope with unpredictable like amount and + * system physical memory, swap size and other VMM technology like KSM, + * memcg, memory hotplug and so on which may affect the OOM + * behaviours. It simply increase the memory consumption 3G each time + * until all the available memory is consumed and OOM is triggered. + * + * Copyright (C) 2010-2017 Red Hat, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See + * the GNU General Public License for more details. + */ + +#include "config.h" +#include +#include +#include +#include +#include +#if HAVE_NUMA_H +#include +#endif + +#include "lapi/abisize.h" +#include "numa_helper.h" +#include "mem.h" + +#ifdef HAVE_NUMA_V2 + +static void verify_oom(void) +{ +#ifdef TST_ABI32 + tst_brk(TCONF, "test is not designed for 32-bit system."); +#endif + + tst_cgroup_move_current(PATH_TMP_CG_CST); + + tst_res(TINFO, "OOM on CPUSET..."); + testoom(0, 0, ENOMEM, 1); + + if (is_numa(NULL, NH_MEMS, 2)) { + /* + * Under NUMA system, the migration of cpuset's memory + * is in charge of cpuset.memory_migrate, we can write + * 1 to cpuset.memory_migrate to enable the migration. + */ + tst_cgroup_cpuset_write_files(PATH_TMP_CG_CST, "memory_migrate", "1"); + tst_res(TINFO, "OOM on CPUSET with mem migrate:"); + testoom(0, 0, ENOMEM, 1); + } +} + +static void setup(void) +{ + int memnode, ret; + + if (!is_numa(NULL, NH_MEMS, 1)) + tst_brk(TCONF, "requires NUMA with at least 1 node"); + + overcommit = get_sys_tune("overcommit_memory"); + set_sys_tune("overcommit_memory", 1, 1); + + tst_cgroup_mount(TST_CGROUP_CPUSET, PATH_TMP_CG_CST); + + /* + * Some nodes do not contain memory, so use + * get_allowed_nodes(NH_MEMS) to get a memory + * node. This operation also applies to Non-NUMA + * systems. + */ + ret = get_allowed_nodes(NH_MEMS, 1, &memnode); + if (ret < 0) + tst_brk(TBROK, "Failed to get a memory node " + "using get_allowed_nodes()"); + write_cpusets(PATH_TMP_CG_CST, memnode); +} + +static void cleanup(void) +{ + if (overcommit != -1) + set_sys_tune("overcommit_memory", overcommit, 0); + tst_cgroup_umount(PATH_TMP_CG_CST); +} + +static struct tst_test test = { + .needs_root = 1, + .forks_child = 1, + .timeout = -1, + .setup = setup, + .cleanup = cleanup, + .test_all = verify_oom, +}; + +#else + TST_TEST_TCONF(NUMA_ERROR_MSG); +#endif diff --git a/pool/shard000/C/0009325_asn1p_class.c b/pool/shard000/C/0009325_asn1p_class.c new file mode 100644 index 0000000000000000000000000000000000000000..c6e6c3d74accb39f20aa84fd95a60ac7aeb775db --- /dev/null +++ b/pool/shard000/C/0009325_asn1p_class.c @@ -0,0 +1,189 @@ +#include +#include +#include +#include +#include + +#include "asn1parser.h" + +asn1p_ioc_row_t * +asn1p_ioc_row_new(asn1p_expr_t *oclass) { + asn1p_ioc_row_t *row; + asn1p_expr_t *field; + int columns = 0; + + assert(oclass->expr_type == A1TC_CLASSDEF); + + row = calloc(1, sizeof *row); + if(!row) return NULL; + + TQ_FOR(field, &oclass->members, next) + columns++; + + row->column = calloc(columns, sizeof *row->column); + if(!row->column) { + free(row); + return NULL; + } + row->columns = columns; + + columns = 0; + TQ_FOR(field, &oclass->members, next) { + int fieldIdLen = strlen(field->Identifier); + if(fieldIdLen > row->max_identifier_length) + row->max_identifier_length = fieldIdLen; + row->column[columns].field = field; + row->column[columns].value = NULL; + columns++; + } + + return row; +} + +void +asn1p_ioc_row_delete(asn1p_ioc_row_t *row) { + if(row) { + if(row->column) { + free(row->column); + } + free(row); + } +} + +struct asn1p_ioc_cell_s * +asn1p_ioc_row_cell_fetch(asn1p_ioc_row_t *row, const char *fieldname) { + int i; + for(i = 0; i < row->columns; i++) { + if(strcmp(row->column[i].field->Identifier, fieldname) == 0) + return &row->column[i]; + } + errno = ESRCH; + return NULL; +} + +asn1p_wsyntx_chunk_t * +asn1p_wsyntx_chunk_new() { + asn1p_wsyntx_chunk_t *wc; + + wc = calloc(1, sizeof(*wc)); + + return wc; +} + +void +asn1p_wsyntx_chunk_free(asn1p_wsyntx_chunk_t *wc) { + if(wc) { + switch(wc->type) { + case WC_LITERAL: + case WC_WHITESPACE: + case WC_FIELD: + free(wc->content.token); break; + case WC_OPTIONALGROUP: + asn1p_wsyntx_free(wc->content.syntax); + break; + } + free(wc); + } +} + +asn1p_wsyntx_chunk_t * +asn1p_wsyntx_chunk_clone(asn1p_wsyntx_chunk_t *wc) { + asn1p_wsyntx_chunk_t *nc; + + nc = asn1p_wsyntx_chunk_new(); + if(nc) { + nc->type = wc->type; + switch(wc->type) { + case WC_LITERAL: + case WC_WHITESPACE: + case WC_FIELD: + nc->content.token = malloc(strlen(wc->content.token)+1); + strcpy(nc->content.token, wc->content.token); + break; + case WC_OPTIONALGROUP: + nc->content.syntax = asn1p_wsyntx_clone(wc->content.syntax); + break; + } + } + + return nc; +} + +asn1p_wsyntx_t * +asn1p_wsyntx_new() { + asn1p_wsyntx_t *wx; + + wx = calloc(1, sizeof(*wx)); + if(wx) { + TQ_INIT(&(wx->chunks)); + } + + return wx; +} + +void +asn1p_wsyntx_free(asn1p_wsyntx_t *wx) { + if(wx) { + asn1p_wsyntx_chunk_t *wc; + while((wc = TQ_REMOVE(&(wx->chunks), next))) + asn1p_wsyntx_chunk_free(wc); + free(wx); + } +} + +asn1p_wsyntx_t * +asn1p_wsyntx_clone(asn1p_wsyntx_t *wx) { + asn1p_wsyntx_t *nw; + + nw = asn1p_wsyntx_new(); + if(nw) { + asn1p_wsyntx_chunk_t *wc; + asn1p_wsyntx_chunk_t *nc; + TQ_FOR(wc, &(wx->chunks), next) { + nc = asn1p_wsyntx_chunk_clone(wc); + if(nc) { + TQ_ADD(&(nw->chunks), nc, next); + } else { + asn1p_wsyntx_free(nw); + return NULL; + } + } + } + + return nw; +} + +asn1p_wsyntx_chunk_t * +asn1p_wsyntx_chunk_fromstring(char *token, int do_copy) { + asn1p_wsyntx_chunk_t *wc; + + if(do_copy) { + static asn1p_wsyntx_chunk_t tmp; + tmp.type = WC_LITERAL; + tmp.content.token = token; + wc = asn1p_wsyntx_chunk_clone(&tmp); + } else { + wc = asn1p_wsyntx_chunk_new(); + if(wc) { + wc->type = WC_LITERAL; + wc->content.token = token; + } + } + + return wc; +} + + +asn1p_wsyntx_chunk_t * +asn1p_wsyntx_chunk_fromsyntax(asn1p_wsyntx_t *syntax) { + asn1p_wsyntx_chunk_t *wc; + + wc = asn1p_wsyntx_chunk_new(); + if(wc) { + wc->type = WC_OPTIONALGROUP; + wc->content.syntax = syntax; + } + + return wc; +} + diff --git a/pool/shard000/C/0009329_bio.c b/pool/shard000/C/0009329_bio.c new file mode 100644 index 0000000000000000000000000000000000000000..cb36d1573dd14e0b5a469c3a9b122fa86c73ba2c --- /dev/null +++ b/pool/shard000/C/0009329_bio.c @@ -0,0 +1,141 @@ +// Buffer cache. +// +// The buffer cache is a linked list of buf structures holding +// cached copies of disk block contents. Caching disk blocks +// in memory reduces the number of disk reads and also provides +// a synchronization point for disk blocks used by multiple processes. +// +// Interface: +// * To get a buffer for a particular disk block, call bread. +// * After changing buffer data, call bwrite to write it to disk. +// * When done with the buffer, call brelse. +// * Do not use the buffer after calling brelse. +// * Only one process at a time can use a buffer, +// so do not keep them longer than necessary. +// +// The implementation uses three state flags internally: +// * B_BUSY: the block has been returned from bread +// and has not been passed back to brelse. +// * B_VALID: the buffer data has been read from the disk. +// * B_DIRTY: the buffer data has been modified +// and needs to be written to disk. + +#include "types.h" +#include "defs.h" +#include "param.h" +#include "spinlock.h" +#include "buf.h" + +struct { + struct spinlock lock; + struct buf buf[NBUF]; + + // Linked list of all buffers, through prev/next. + // head.next is most recently used. + struct buf head; +} bcache; + +void +binit(void) +{ + struct buf *b; + + initlock(&bcache.lock, "bcache"); + +//PAGEBREAK! + // Create linked list of buffers + bcache.head.prev = &bcache.head; + bcache.head.next = &bcache.head; + for(b = bcache.buf; b < bcache.buf+NBUF; b++){ + b->next = bcache.head.next; + b->prev = &bcache.head; + b->dev = -1; + bcache.head.next->prev = b; + bcache.head.next = b; + } +} + +// Look through buffer cache for sector on device dev. +// If not found, allocate fresh block. +// In either case, return B_BUSY buffer. +static struct buf* +bget(uint dev, uint sector) +{ + struct buf *b; + + acquire(&bcache.lock); + + loop: + // Is the sector already cached? + for(b = bcache.head.next; b != &bcache.head; b = b->next){ + if(b->dev == dev && b->sector == sector){ + if(!(b->flags & B_BUSY)){ + b->flags |= B_BUSY; + release(&bcache.lock); + return b; + } + sleep(b, &bcache.lock); + goto loop; + } + } + + // Not cached; recycle some non-busy and clean buffer. + for(b = bcache.head.prev; b != &bcache.head; b = b->prev){ + if((b->flags & B_BUSY) == 0 && (b->flags & B_DIRTY) == 0){ + b->dev = dev; + b->sector = sector; + b->flags = B_BUSY; + release(&bcache.lock); + return b; + } + } + panic("bget: no buffers"); +} + +// Return a B_BUSY buf with the contents of the indicated disk sector. +struct buf* +bread(uint dev, uint sector) +{ + struct buf *b; + + b = bget(dev, sector); + if(!(b->flags & B_VALID)) + iderw(b); + return b; +} + +// Write b's contents to disk. Must be B_BUSY. +void +bwrite(struct buf *b) +{ + if((b->flags & B_BUSY) == 0) + panic("bwrite"); + b->flags |= B_DIRTY; + if (b->sector==1) + cprintf("Got write to superblock\n"); + iderw(b); +} + +// Release a B_BUSY buffer. +// Move to the head of the MRU list. +void +brelse(struct buf *b) +{ + if((b->flags & B_BUSY) == 0) + panic("brelse"); + + acquire(&bcache.lock); + + b->next->prev = b->prev; + b->prev->next = b->next; + b->next = bcache.head.next; + b->prev = &bcache.head; + bcache.head.next->prev = b; + bcache.head.next = b; + + b->flags &= ~B_BUSY; + wakeup(b); + + release(&bcache.lock); +} + diff --git a/pool/shard000/C/0009342_irs-service.c b/pool/shard000/C/0009342_irs-service.c new file mode 100644 index 0000000000000000000000000000000000000000..bddb8c00d50defce55f6f959a5bb93ae78971d84 --- /dev/null +++ b/pool/shard000/C/0009342_irs-service.c @@ -0,0 +1,161 @@ +/* Copyright (C) 1997-2005 Luke Howard. + This file is part of the nss_ldap library. + Contributed by Luke Howard, , 1997. + + The nss_ldap library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public License as + published by the Free Software Foundation; either version 2 of the + License, or (at your option) any later version. + + The nss_ldap library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public + License along with the nss_ldap library; see the file COPYING.LIB. If not, + write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, + Boston, MA 02111-1307, USA. + */ + +#ifdef HAVE_IRS_H + +#include +#include "irs-nss.h" + +/* $Id$ */ + +#ifdef HAVE_USERSEC_H +void *sv_pvtinit (void); +#endif +IRS_EXPORT void sv_close (struct irs_sv *); +IRS_EXPORT struct servent *sv_next (struct irs_sv *); +IRS_EXPORT struct servent *sv_byname (struct irs_sv *, const char *, + const char *); +IRS_EXPORT struct servent *sv_byport (struct irs_sv *, int, const char *); +IRS_EXPORT void sv_rewind (struct irs_sv *); +IRS_EXPORT void sv_minimize (struct irs_sv *); + +struct pvt +{ + struct servent result; + char buffer[NSS_BUFLEN_SERVICES]; + ent_context_t *state; +}; + +IRS_EXPORT struct servent * +sv_byname (struct irs_sv *this, const char *name, const char *proto) +{ + ldap_args_t a; + struct pvt *pvt = (struct pvt *) this->private; + NSS_STATUS s; + + LA_INIT (a); + LA_STRING (a) = name; + LA_TYPE (a) = (proto == NULL) ? LA_TYPE_STRING : LA_TYPE_STRING_AND_STRING; + LA_STRING2 (a) = proto; + s = + _nss_ldap_getbyname (&a, &pvt->result, pvt->buffer, sizeof (pvt->buffer), + &errno, + (proto == + NULL) ? _nss_ldap_filt_getservbyname : + _nss_ldap_filt_getservbynameproto, + LM_SERVICES, _nss_ldap_parse_serv); + + if (s != NSS_SUCCESS) + { + MAP_ERRNO (s, errno); + return NULL; + } + return &pvt->result; +} + +IRS_EXPORT struct servent * +sv_byport (struct irs_sv *this, int port, const char *proto) +{ + ldap_args_t a; + struct pvt *pvt = (struct pvt *) this->private; + NSS_STATUS s; + + LA_INIT (a); + LA_NUMBER (a) = port; + LA_TYPE (a) = (proto == NULL) ? LA_TYPE_NUMBER : LA_TYPE_NUMBER_AND_STRING; + LA_STRING2 (a) = proto; + s = + _nss_ldap_getbyname (&a, &pvt->result, pvt->buffer, sizeof (pvt->buffer), + &errno, + (proto == + NULL) ? _nss_ldap_filt_getservbyport : + _nss_ldap_filt_getservbyportproto, + LM_SERVICES, _nss_ldap_parse_serv); + + if (s != NSS_SUCCESS) + { + MAP_ERRNO (s, errno); + return NULL; + } + return &pvt->result; +} + +IRS_EXPORT void +sv_close (struct irs_sv *this) +{ + LOOKUP_ENDENT (this); +#ifdef HAVE_USERSEC_H + free (this->private); + free (this); +#endif +} + +IRS_EXPORT struct servent * +sv_next (struct irs_sv *this) +{ + LOOKUP_GETENT (this, _nss_ldap_filt_getservent, LM_SERVICES, + _nss_ldap_parse_serv, LDAP_NSS_BUFLEN_DEFAULT); +} + +IRS_EXPORT void +sv_rewind (struct irs_sv *this) +{ + LOOKUP_SETENT (this); +} + +IRS_EXPORT void +sv_minimize (struct irs_sv *this) +{ +} + +#ifdef HAVE_USERSEC_H +void * +sv_pvtinit (void) +#else +struct irs_sv * +irs_ldap_sv (struct irs_acc *this) +#endif +{ + struct irs_sv *sv; + struct pvt *pvt; + + sv = calloc (1, sizeof (*sv)); + if (sv == NULL) + return NULL; + + pvt = calloc (1, sizeof (*pvt)); + if (pvt == NULL) + { + free (sv); + return NULL; + } + + pvt->state = NULL; + sv->private = pvt; + sv->close = sv_close; + sv->next = sv_next; + sv->byname = sv_byname; + sv->byport = sv_byport; + sv->rewind = sv_rewind; + sv->minimize = sv_minimize; + return sv; +} + +#endif /*HAVE_IRS_H */ diff --git a/pool/shard000/C/0009343_px.c b/pool/shard000/C/0009343_px.c new file mode 100644 index 0000000000000000000000000000000000000000..1abe1eddc459a629b496865e5653f06e4a3a4b12 --- /dev/null +++ b/pool/shard000/C/0009343_px.c @@ -0,0 +1,52 @@ +#include + +typedef struct linked_list { + int data; + struct linked_list *next; +} LinkedList; + +LinkedList *head; + +LinkedList * +Add(LinkedList *h, LinkedList *new) +{ + if (h == NULL) + h = new; + else + new->next = h; + + return new; +} + + +LinkedList * +px(LinkedList *h, int x) +{ + LinkedList *h1 = NULL; + LinkedList *h2 = NULL; + LinkedList *p, *p1, *p2; + + if (h == NULL) + return NULL; + + p = h; + while (p != NULL) + if (p->data > x) + p1 = Add(h2, p); + else + p2 = Add(h1, p); + + if (h1 != NULL) { + h = h1; + p1->next = h2; + } else + h = h2; + + return h; +} + + +main() +{ + +} diff --git a/pool/shard000/C/0009344_test_options.c b/pool/shard000/C/0009344_test_options.c new file mode 100644 index 0000000000000000000000000000000000000000..2c644046c24873a07e7ca4d1e4e13049979e974c --- /dev/null +++ b/pool/shard000/C/0009344_test_options.c @@ -0,0 +1,245 @@ +/* + CTDB tests commandline options + + Copyright (C) Amitay Isaacs 2015 + + 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 + along with this program; if not, see . +*/ + +#include "replace.h" + +#include +#include +#include + +#include "lib/util/debug.h" + +#include "common/logging.h" +#include "common/path.h" + +#include "tests/src/test_options.h" + +static struct test_options _values; + +static struct poptOption options_basic[] = { + { + .longName = "socket", + .shortName = 's', + .argInfo = POPT_ARG_STRING, + .arg = &_values.socket, + .descrip = "CTDB socket path", + .argDescrip = "filename", + }, + { + .longName = "timelimit", + .shortName = 't', + .argInfo = POPT_ARG_INT, + .arg = &_values.timelimit, + .descrip = "Time limit (in seconds)", + }, + { + .longName = "num-nodes", + .shortName = 'n', + .argInfo = POPT_ARG_INT, + .arg = &_values.num_nodes, + .descrip = "Number of cluster nodes", + }, + { + .longName = "debug", + .shortName = 'd', + .argInfo = POPT_ARG_STRING, + .arg = &_values.debugstr, + .descrip = "Debug level", + }, + { + .longName = "interactive", + .shortName = 'i', + .argInfo = POPT_ARG_NONE, + .arg = &_values.interactive, + .val = 0, + .descrip = "Interactive output", + }, + POPT_TABLEEND +}; + +#define TEST_OPTIONS_BASIC \ + { \ + .argInfo = POPT_ARG_INCLUDE_TABLE, \ + .arg = options_basic, \ + .descrip = "General options:", \ + }, + +static struct poptOption options_database[] = { + { + .longName = "database", + .shortName = 'D', + .argInfo = POPT_ARG_STRING, + .arg = &_values.dbname, + .descrip = "CTDB database name", + }, + { + .longName = "key", + .shortName = 'k', + .argInfo = POPT_ARG_STRING, + .arg = &_values.keystr, + .descrip = "Name of database key", + }, + { + .longName = "value", + .shortName = 'v', + .argInfo = POPT_ARG_STRING, + .arg = &_values.valuestr, + .descrip = "Value of database key", + }, + { + .longName = "dbtype", + .shortName = 'T', + .argInfo = POPT_ARG_STRING, + .arg = &_values.dbtype, + .descrip = "CTDB database type", + }, + POPT_TABLEEND +}; + +#define TEST_OPTIONS_DATABASE \ + { \ + .argInfo = POPT_ARG_INCLUDE_TABLE, \ + .arg = options_database, \ + .descrip = "Database options:", \ + }, + +static void set_defaults_basic(struct test_options *opts) +{ + /* Set default options */ + opts->socket = path_socket(NULL, "ctdbd"); /* leaked */ + assert(opts->socket != NULL); + + opts->timelimit = 10; + opts->num_nodes = 1; + opts->debugstr = "ERR"; + opts->interactive = 0; +} + +static void set_defaults_database(struct test_options *opts) +{ + opts->dbname = NULL; + opts->keystr = NULL; + opts->valuestr = NULL; + opts->dbtype = "volatile"; +} + +static bool verify_options_basic(struct test_options *opts) +{ + int log_level; + bool status; + + status = debug_level_parse(opts->debugstr, &log_level); + if (! status) { + fprintf(stderr, "Error: Invalid debug string '%s'\n", + opts->debugstr); + return false; + } + + debuglevel_set(log_level); + + return true; +} + +static bool verify_options_database(struct test_options *opts) +{ + if (opts->dbname == NULL) { + fprintf(stderr, "Error: Please specify database\n"); + return false; + } + if (opts->keystr == NULL) { + fprintf(stderr, "Error: Please specify key name\n"); + return false; + } + + if ((strcmp(opts->dbtype, "volatile") != 0) && + (strcmp(opts->dbtype, "persistent") != 0) && + (strcmp(opts->dbtype, "replicated") != 0)) { + return false; + } + + return true; +} + +static bool process_options_common(int argc, const char **argv, + struct poptOption *options) +{ + poptContext pc; + int opt; + + pc = poptGetContext(argv[0], argc, argv, options, + POPT_CONTEXT_KEEP_FIRST); + while ((opt = poptGetNextOpt(pc)) != -1) { + fprintf(stderr, "Invalid option %s: %s\n", + poptBadOption(pc, 0), poptStrerror(opt)); + return false; + } + + return true; +} + +bool process_options_basic(int argc, const char **argv, + const struct test_options **opts) +{ + struct poptOption options[] = { + POPT_AUTOHELP + TEST_OPTIONS_BASIC + POPT_TABLEEND + }; + + set_defaults_basic(&_values); + + if (! process_options_common(argc, argv, options)) { + return false; + } + + if (! verify_options_basic(&_values)) { + return false; + } + + *opts = &_values; + return true; +} + +bool process_options_database(int argc, const char **argv, + const struct test_options **opts) +{ + struct poptOption options[] = { + POPT_AUTOHELP + TEST_OPTIONS_BASIC + TEST_OPTIONS_DATABASE + POPT_TABLEEND + }; + + set_defaults_basic(&_values); + set_defaults_database(&_values); + + if (! process_options_common(argc, argv, options)) { + return false; + } + + if (! verify_options_basic(&_values)) { + return false; + } + if (! verify_options_database(&_values)) { + return false; + } + + *opts = &_values; + return true; +} diff --git a/pool/shard000/C/0009367_cc-dsp.c b/pool/shard000/C/0009367_cc-dsp.c new file mode 100644 index 0000000000000000000000000000000000000000..518c1a68f70d055ff2fe4e54cd39d434ed9c9416 --- /dev/null +++ b/pool/shard000/C/0009367_cc-dsp.c @@ -0,0 +1,145 @@ +/* + * Copyright © 2009 Keith Packard + * + * 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 330, Boston, MA 02111-1307 USA. + */ + +#include "cc.h" +#include "cephes.h" +#include +#include + +static inline double sqr (double x) { return x * x; } + +/* + * Kaiser Window digital filter + */ + +#if 0 +/* not used in this program */ +static double highpass (double n, double m, double wc) +{ + double alpha = m/2; + double dist; + + dist = n - alpha; + if (dist == 0) + return (M_PI/2 - wc) / M_PI; + return -sin(dist * (M_PI/2-wc)) / (M_PI * dist); +} +#endif + +static double lowpass (double n, double m, double wc) +{ + double alpha = m/2; + double dist; + dist = n - alpha; + if (dist == 0) + return wc / M_PI; + return sin (wc * dist) / (M_PI * dist); +} + +static double kaiser (double n, double m, double beta) +{ + double alpha = m / 2; + return i0 (beta * sqrt (1 - sqr((n - alpha) / alpha))) / i0(beta); +} + +static double beta (double A) +{ + if (A > 50) + return 0.1102 * (A - 8.7); + else if (A >= 21) + return 0.5842 * pow((A - 21), 0.4) + 0.07886 * (A - 21); + else + return 0.0; +} + +static int M (double A, double delta_omega) +{ + if (A > 21) + return ceil ((A - 7.95) / (2.285 * delta_omega)); + else + return ceil(5.79 / delta_omega); +} + +struct filter_param { + double omega_pass; + double delta_omega; + double A; + double beta; + int M; +} filter_param_t; + +static struct filter_param +filter (double omega_pass, double omega_stop, double error) +{ + struct filter_param p; + p.omega_pass = omega_pass; + p.delta_omega = omega_stop - omega_pass; + p.A = -20 * log10 (error); + p.beta = beta (p.A); + p.M = M (p.A, p.delta_omega); + if ((p.M & 1) == 1) + p.M++; + return p; +} + +static double * +make_low_pass_filter(double omega_pass, double omega_stop, double error, int *length_p) +{ + struct filter_param p = filter(omega_pass, omega_stop, error); + int length; + int n; + double *lpf; + + length = p.M + 1; + lpf = calloc (length, sizeof(double)); + for (n = 0; n < length; n++) + lpf[n] = lowpass(n, p.M, omega_pass) * kaiser(n, p.M, p.beta); + *length_p = length; + return lpf; +} + +static double * +convolve(double *d, int d_len, double *e, int e_len) +{ + int w = (e_len - 1) / 2; + int n; + double *con = calloc (d_len, sizeof (double)); + + for (n = 0; n < d_len; n++) { + double v = 0; + int o; + for (o = -w; o <= w; o++) { + int p = n + o; + double sample = p < 0 ? d[0] : p >= d_len ? d[d_len-1] : d[p]; + v += sample * e[o + w]; + } + con[n] = v; + } + return con; +} + +double * +cc_low_pass(double *data, int data_len, double omega_pass, double omega_stop, double error) +{ + int fir_len; + double *fir = make_low_pass_filter(omega_pass, omega_stop, error, &fir_len); + double *result; + + result = convolve(data, data_len, fir, fir_len); + free(fir); + return result; +} diff --git a/pool/shard000/C/0009372_tiara.c b/pool/shard000/C/0009372_tiara.c new file mode 100644 index 0000000000000000000000000000000000000000..34c5eaf8dba7966c7d27fe45259df693545af809 --- /dev/null +++ b/pool/shard000/C/0009372_tiara.c @@ -0,0 +1,192 @@ +/************************************************************************** +Etherboot - BOOTP/TFTP Bootstrap Program + +TIARA (Fujitsu Etherstar) NIC driver for Etherboot +Copyright (c) Ken Yap 1998 + +Information gleaned from: + +TIARA.ASM Packet driver by Brian Fisher, Queens U, Kingston, Ontario +Fujitsu MB86960 spec sheet (different chip but same family) +***************************************************************************/ + +/* + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2, or (at + * your option) any later version. + */ + +#include "etherboot.h" +#include "nic.h" +#include "cards.h" + + +#define DLCR_XMIT_STAT 0x00 +#define DLCR_XMIT_MASK 0x01 +#define DLCR_RECV_STAT 0x02 +#define DLCR_RECV_MASK 0x03 +#define DLCR_XMIT_MODE 0x04 +#define DLCR_RECV_MODE 0x05 +#define DLCR_ENABLE 0x06 +#define DLCR_TDR_LOW 0x07 +#define DLCR_NODE_ID 0x08 +#define DLCR_TDR_HIGH 0x0F +#define BMPR_MEM_PORT 0x10 +#define BMPR_PKT_LEN 0x12 +#define BMPR_DMA_ENABLE 0x14 +#define PROM_ID 0x18 + +#define TMST 0x80 +#define TMT_OK 0x80 +#define TMT_16COLL 0x02 +#define BUF_EMPTY 0x40 + +#define CARD_DISABLE 0x80 /* written to DLCR_ENABLE to disable card */ +#define CARD_ENABLE 0 /* written to DLCR_ENABLE to enable card */ + +#define CLEAR_STATUS 0x0F + +#define NO_TX_IRQS 0 /* written to clear transmit IRQs */ + +#define CLR_RCV_STATUS 0xCF + +#define EN_RCV_IRQS 0x80 + +#define XMIT_MODE 0x02 + +#define RECV_MODE 0x02 + + +static unsigned short ioaddr; + +static void tiara_reset(struct nic *nic) +{ + int i; + + outb(CARD_DISABLE, ioaddr + DLCR_ENABLE); + outb(CLEAR_STATUS, ioaddr + DLCR_XMIT_STAT); + outb(NO_TX_IRQS, ioaddr + DLCR_XMIT_MASK); + outb(CLR_RCV_STATUS, ioaddr + DLCR_RECV_STAT); + outb(XMIT_MODE, ioaddr + DLCR_XMIT_MODE); + outb(RECV_MODE, ioaddr + DLCR_RECV_MODE); + + while ((inb(ioaddr + DLCR_RECV_MODE) & BUF_EMPTY) == 0) + inb(ioaddr + BMPR_MEM_PORT); + + for (i = 0; i < ETH_ALEN; ++i) + outb(nic->node_addr[i], ioaddr + DLCR_NODE_ID + i); + outb(CLR_RCV_STATUS, ioaddr + DLCR_RECV_STAT); + outb(CARD_ENABLE, ioaddr + DLCR_ENABLE); +} + +static int tiara_poll(struct nic *nic) +{ + unsigned int len; + + if (inb(ioaddr + DLCR_RECV_MODE) & BUF_EMPTY) + return (0); + + outw(CLR_RCV_STATUS, ioaddr + DLCR_RECV_STAT); + len = inw(ioaddr + BMPR_MEM_PORT); + len = inw(ioaddr + BMPR_MEM_PORT); + + if (len > ETH_FRAME_LEN) + return (0); + insw(ioaddr + BMPR_MEM_PORT, nic->packet, len / 2); + + if (memcmp(nic->packet + ETH_ALEN, nic->node_addr, ETH_ALEN) == 0) + return (0); + nic->packetlen = len; + return (1); +} + +static void tiara_transmit( +struct nic *nic, +const char *d, +unsigned int t, +unsigned int s, +const char *p) +{ + unsigned int len; + unsigned long time; + + len = s + ETH_HLEN; + if (len < ETH_ZLEN) + len = ETH_ZLEN; + t = htons(t); + outsw(ioaddr + BMPR_MEM_PORT, d, ETH_ALEN / 2); + outsw(ioaddr + BMPR_MEM_PORT, nic->node_addr, ETH_ALEN / 2); + outw(t, ioaddr + BMPR_MEM_PORT); + outsw(ioaddr + BMPR_MEM_PORT, p, s / 2); + if (s & 1) + outb(p[s-1], ioaddr + BMPR_MEM_PORT); + while (s++ < ETH_ZLEN - ETH_HLEN) + outb(0, ioaddr + BMPR_MEM_PORT); + outw(len | (TMST << 8), ioaddr + BMPR_PKT_LEN); + + time = currticks() + TICKS_PER_SEC; + while (currticks() < time && (inb(ioaddr) & (TMT_OK|TMT_16COLL)) == 0) + ; + if ((inb(ioaddr) & (TMT_OK|TMT_16COLL)) == 0) + printf("Tiara timed out on transmit\n"); + +} + +static void tiara_disable(struct nic *nic) +{ + + outb(CARD_DISABLE, ioaddr + DLCR_ENABLE); +} + +static int tiara_probe1(struct nic *nic) +{ + + static char vendor_prefix[] = { 0x08, 0x00, 0x1A }; + static char all_ones[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; + int i; + + for (i = 0; i < ETH_ALEN; ++i) + nic->node_addr[i] = inb(ioaddr + PROM_ID + i); + if (memcmp(nic->node_addr, vendor_prefix, sizeof(vendor_prefix)) != 0) + return (0); + if (memcmp(nic->node_addr, all_ones, sizeof(all_ones)) == 0) + return (0); + printf("\nTiara ioaddr %#hX, addr %!\n", ioaddr, nic->node_addr); + return (1); +} + +struct nic *tiara_probe(struct nic *nic, unsigned short *probe_addrs) +{ + + static unsigned short io_addrs[] = { + 0x100, 0x120, 0x140, 0x160, + 0x180, 0x1A0, 0x1C0, 0x1E0, + 0x200, 0x220, 0x240, + 0x280, 0x2A0, 0x2C0, + 0x300, 0x320, 0x340, + 0x380, 0x3C0, + 0x0 + }; + unsigned short *p; + + + if (probe_addrs == 0) + probe_addrs = io_addrs; + for (p = probe_addrs; (ioaddr = *p) != 0; ++p) + if (tiara_probe1(nic)) + break; + + if (ioaddr != 0) + { + tiara_reset(nic); + + nic->reset = tiara_reset; + nic->poll = tiara_poll; + nic->transmit = tiara_transmit; + nic->disable = tiara_disable; + return nic; + } + else + return (0); +} diff --git a/pool/shard000/C/0009382_requiem-hash.c b/pool/shard000/C/0009382_requiem-hash.c new file mode 100644 index 0000000000000000000000000000000000000000..c368e7b375b2c5719dce7ca404d9e45a560fa8bb --- /dev/null +++ b/pool/shard000/C/0009382_requiem-hash.c @@ -0,0 +1,267 @@ +/***** +* +* Copyright (C) 2003,2004,2005 PreludeIDS Technologies. All Rights Reserved. +* Author: Nicolas Delon +* +* This file is part of the Requiem library. +* +* This program is free software; you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation; either version 2, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; see the file COPYING. If not, write to +* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. +* +*****/ + +#include "config.h" + +#include +#include + +#include "requiem-log.h" +#include "requiem-list.h" +#include "requiem-error.h" +#include "requiem-hash.h" + + +#define HASH_DEFAULT_SIZE 128 + + + +typedef struct hash_elem { + requiem_list_t list; + void *key; + void *value; +} hash_elem_t; + + +struct requiem_hash { + size_t lists_size; + requiem_list_t *lists; + + unsigned int (*hash_func)(const void *key); + int (*key_cmp_func)(const void *key1, const void *key2); + void (*key_destroy_func)(void *key); + void (*value_destroy_func)(void *value); +}; + + + +/* + * This function's code was taken from glib + */ +static unsigned int default_hash_func(const void *key) +{ + const char *ptr = key; + unsigned int hv = *ptr; + + if ( hv ) + for ( ptr += 1; *ptr; ptr++ ) + hv = (hv << 5) - hv + *ptr; + + return hv; + +} + + + +static int default_key_cmp_func(const void *key1, const void *key2) +{ + return strcmp((const char *) key1, (const char *) key2); +} + + + +static unsigned int hash_value_calc(requiem_hash_t *hash, const void *key) +{ + return (hash->hash_func(key) % hash->lists_size); +} + + + +static hash_elem_t *hash_elem_get(requiem_hash_t *hash, const void *key) +{ + requiem_list_t *list; + requiem_list_t *ptr; + hash_elem_t *hash_elem; + + list = hash->lists + hash_value_calc(hash, key); + + requiem_list_for_each(list, ptr) { + hash_elem = requiem_list_entry(ptr, hash_elem_t, list); + if ( hash->key_cmp_func(key, hash_elem->key) == 0 ) + return hash_elem; + } + + return NULL; +} + + + +static void hash_elem_key_destroy(requiem_hash_t *hash, hash_elem_t *hash_elem) +{ + if ( hash->key_destroy_func ) + hash->key_destroy_func(hash_elem->key); +} + + + +static void hash_elem_value_destroy(requiem_hash_t *hash, hash_elem_t *hash_elem) +{ + if ( hash->value_destroy_func ) + hash->value_destroy_func(hash_elem->value); +} + + + +int requiem_hash_new(requiem_hash_t **nhash, + unsigned int (*hash_func)(const void *), + int (*key_cmp_func)(const void *, const void *), + void (*key_destroy_func)(void *), + void (*value_destroy_func)(void *)) +{ + return requiem_hash_new2(nhash, HASH_DEFAULT_SIZE, hash_func, key_cmp_func, key_destroy_func, value_destroy_func); +} + + + +int requiem_hash_new2(requiem_hash_t **nhash, size_t size, + unsigned int (*hash_func)(const void *), + int (*key_cmp_func)(const void *, const void *), + void (*key_destroy_func)(void *), + void (*value_destroy_func)(void *)) +{ + size_t i; + requiem_hash_t *hash; + + *nhash = hash = calloc(1, sizeof (*hash)); + if ( ! hash ) + return requiem_error_from_errno(errno); + + hash->lists_size = size; + + hash->lists = malloc(hash->lists_size * sizeof(*hash->lists)); + if ( ! hash->lists ) { + free(hash); + return requiem_error_from_errno(errno); + } + + hash->hash_func = hash_func ? hash_func : default_hash_func; + hash->key_cmp_func = key_cmp_func ? key_cmp_func : default_key_cmp_func; + hash->key_destroy_func = key_destroy_func; + hash->value_destroy_func = value_destroy_func; + + for ( i = 0; i < hash->lists_size; i++ ) + requiem_list_init(hash->lists + i); + + return 0; +} + + + +void requiem_hash_destroy(requiem_hash_t *hash) +{ + size_t cnt; + requiem_list_t *list; + requiem_list_t *ptr; + requiem_list_t *tmp; + hash_elem_t *hash_elem; + + for ( cnt = 0; cnt < hash->lists_size; cnt++ ) { + list = hash->lists + cnt; + + requiem_list_for_each_safe(list, ptr, tmp) { + hash_elem = requiem_list_entry(ptr, hash_elem_t, list); + + hash_elem_key_destroy(hash, hash_elem); + hash_elem_value_destroy(hash, hash_elem); + requiem_list_del(&hash_elem->list); + free(hash_elem); + } + } + + free(hash->lists); + free(hash); +} + + + +int requiem_hash_set(requiem_hash_t *hash, void *key, void *value) +{ + hash_elem_t *hash_elem; + requiem_list_t *list; + + hash_elem = hash_elem_get(hash, key); + + if ( hash_elem ) { + hash_elem_key_destroy(hash, hash_elem); + hash_elem_value_destroy(hash, hash_elem); + hash_elem->key = key; + hash_elem->value = value; + return 0; + } + + hash_elem = calloc(1, sizeof(*hash_elem)); + if ( ! hash_elem ) + return requiem_error_from_errno(errno); + + hash_elem->key = key; + hash_elem->value = value; + + list = hash->lists + hash_value_calc(hash, key); + requiem_list_add(list, &hash_elem->list); + + return 1; +} + + + +void *requiem_hash_get(requiem_hash_t *hash, const void *key) +{ + hash_elem_t *hash_elem; + + return (hash_elem = hash_elem_get(hash, key)) ? hash_elem->value : NULL; +} + + + +int requiem_hash_elem_destroy(requiem_hash_t *hash, const void *key) +{ + hash_elem_t *hash_elem; + + hash_elem = hash_elem_get(hash, key); + + if ( ! hash_elem ) + return -1; + + hash_elem_key_destroy(hash, hash_elem); + hash_elem_value_destroy(hash, hash_elem); + requiem_list_del(&hash_elem->list); + free(hash_elem); + + return 0; +} + + + +void requiem_hash_iterate(requiem_hash_t *hash, void (*cb)(void *data)) +{ + unsigned int i; + requiem_list_t *tmp; + hash_elem_t *hash_elem; + + for ( i = 0; i < hash->lists_size; i++ ) { + requiem_list_for_each(&hash->lists[i], tmp) { + hash_elem = requiem_list_entry(tmp, hash_elem_t, list); + cb(hash_elem->value); + } + } +} diff --git a/pool/shard000/C/0009396_1-3.c b/pool/shard000/C/0009396_1-3.c new file mode 100644 index 0000000000000000000000000000000000000000..16eb3c7a8a0a5873e4bec88ab80efaa84097ab73 --- /dev/null +++ b/pool/shard000/C/0009396_1-3.c @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2004, QUALCOMM Inc. All rights reserved. + * Created by: abisain REMOVE-THIS AT qualcomm DOT com + * This file is licensed under the GPL license. For the full content + * of this license, see the COPYING file at the top level of this + * source tree. + + * Test that pthread_create(pthread_attr) + * shall create a thread with the pthread_attr settings passed to it + + * Steps: + * 1. Create a pthread_attr structure and set policy and priority in it + * 2. Create a thread using this attr + * 3. In the thread, check these settings. + + */ + +#include +#include +#include +#include +#include "posixtest.h" + +#define TEST "3-1" +#define AREA "scheduler" +#define ERROR_PREFIX "unexpected error: " AREA " " TEST ": " + +#define PRIORITY 20 +#define POLICY SCHED_FIFO + +/* the thread uses this to indicate to main or success */ +int policy_correct = -1; +/* the thread uses this to indicate to main or success */ +int priority_correct = -1; + +/* Thread function which checks the scheduler settings for itself */ +void *thread(void *tmp LTP_ATTRIBUTE_UNUSED) +{ + struct sched_param param; + int policy; + if (pthread_getschedparam(pthread_self(), &policy, ¶m) != 0) { + printf(ERROR_PREFIX "pthread_getschedparam\n"); + exit(PTS_UNRESOLVED); + } + if (policy == POLICY) { + policy_correct = 1; + } + if (param.sched_priority == PRIORITY) { + priority_correct = 1; + } + return NULL; +} + +int main(void) +{ + pthread_t thread_id; + pthread_attr_t attr; + struct sched_param param; + int rc = 0; + + /* initialze the attribute and set policy and priority in it */ + rc = pthread_attr_init(&attr); + if (rc != 0) { + printf(ERROR_PREFIX "pthread_attr_init\n"); + exit(PTS_UNRESOLVED); + } + rc = pthread_attr_setschedpolicy(&attr, POLICY); + if (rc != 0) { + printf(ERROR_PREFIX "pthread_attr_setschedpolicy\n"); + exit(PTS_UNRESOLVED); + } + param.sched_priority = PRIORITY; + rc = pthread_attr_setschedparam(&attr, ¶m); + if (rc != 0) { + printf(ERROR_PREFIX "pthread_attr_setschedparam\n"); + exit(PTS_UNRESOLVED); + } + + rc = pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED); + if (rc != 0) { + printf(ERROR_PREFIX "pthread_attr_setinheritsched\n"); + exit(PTS_UNRESOLVED); + } + + /* Create the thread with the attr */ + rc = pthread_create(&thread_id, &attr, thread, NULL); + if (rc != 0) { + printf(ERROR_PREFIX "pthread_create\n"); + exit(PTS_UNRESOLVED); + } + + rc = pthread_join(thread_id, NULL); + if (rc != 0) { + printf(ERROR_PREFIX "pthread_join\n"); + exit(PTS_UNRESOLVED); + } + + /* test the result */ + if (priority_correct != 1) { + printf("Test FAILED. Priority set incorrectly\n"); + exit(PTS_FAIL); + } + if (policy_correct != 1) { + printf("Test FAILED. Policy set incorrectly\n"); + exit(PTS_FAIL); + } + + printf("Test PASSED\n"); + exit(PTS_PASS); +} diff --git a/pool/shard000/C/0009407_pid_lock.c b/pool/shard000/C/0009407_pid_lock.c new file mode 100644 index 0000000000000000000000000000000000000000..9df9d1718b968b0063f410a04cb620214a8e4813 --- /dev/null +++ b/pool/shard000/C/0009407_pid_lock.c @@ -0,0 +1,123 @@ +#include +#include +#include +#include +#include +#include + +#include "minieap_common.h" +#include "logging.h" +#include "config.h" +#include "misc.h" + +#define PID_STRING_BUFFER_SIZE 12 +#define PID_FILE_NONE "none" + +static int pid_lock_fd = 0; // 0 = uninitialized, -1 = disabled + +RESULT pid_lock_init(const char* pidfile) { + if (pidfile == NULL) { + return FAILURE; + } + + if (strcmp(pidfile, PID_FILE_NONE) == 0) { + PR_WARN("PID 检查已禁用,请确保一个接口上只有一个认证进程") + pid_lock_fd = -1; + return SUCCESS; + } + + pid_lock_fd = open(pidfile, O_RDWR | O_CREAT, 0644); + if (pid_lock_fd < 0) { + PR_ERRNO("无法打开 PID 文件"); + return FAILURE; + } + return SUCCESS; +} + +// Return SUCCESS: We handled the incident and are ready to proceed (i.e. only when user asked) +// Return FAILURE: We could not handle, or we do not want to proceed +static RESULT pid_lock_handle_multiple_instance() { + char readbuf[PID_STRING_BUFFER_SIZE]; // 12 is big enough to hold PID number + + if (read(pid_lock_fd, readbuf, PID_STRING_BUFFER_SIZE) < 0 || readbuf[0] == '\0') { + PR_ERRNO("已有另一个 MiniEAP 进程正在运行但 PID 未知,请手动结束其他 MiniEAP 进程"); + return FAILURE; + } else { + int pid = atoi(readbuf); + switch (get_program_config()->kill_type) { + case KILL_NONE: + PR_ERR("已有另一个 MiniEAP 进程正在运行,PID 为 %d", pid); + return FAILURE; + case KILL_ONLY: + PR_ERR("已有另一个 MiniEAP 进程正在运行,PID 为 %d,即将发送终止信号并退出……", pid); + kill(pid, SIGTERM); + return FAILURE; + case KILL_AND_START: + PR_WARN("已有另一个 MiniEAP 进程正在运行,PID 为 %d,将在发送终止信号后继续……", pid); + kill(pid, SIGTERM); + return SUCCESS; + default: + PR_ERR("-k 参数未知"); + return FAILURE; + } + } +} + +RESULT pid_lock_save_pid() { + if (pid_lock_fd == 0) { + PR_WARN("PID 文件尚未初始化"); + return FAILURE; + } else if (pid_lock_fd < 0) { + // User disabled pid lock + return SUCCESS; + } + + char writebuf[PID_STRING_BUFFER_SIZE]; + + my_itoa(getpid(), writebuf, 10); + + if (write(pid_lock_fd, writebuf, strnlen(writebuf, PID_STRING_BUFFER_SIZE)) < 0) { + PR_ERRNO("无法将 PID 保存到 PID 文件"); + return FAILURE; + } + + return SUCCESS; +} + +RESULT pid_lock_lock() { + if (pid_lock_fd == 0) { + PR_WARN("PID 文件尚未初始化"); + return FAILURE; + } else if (pid_lock_fd < 0) { + // User disabled pid lock + return SUCCESS; + } + + int lock_result = flock(pid_lock_fd, LOCK_EX | LOCK_NB); + if (lock_result < 0) { + if (errno == EWOULDBLOCK) { + if (IS_FAIL(pid_lock_handle_multiple_instance())) { + close(pid_lock_fd); + pid_lock_fd = 0; + return FAILURE; + } // Continue if handled + } else { + PR_ERRNO("无法对 PID 文件加锁"); + return FAILURE; + } + } + + return SUCCESS; +} + +RESULT pid_lock_destroy() { + if (pid_lock_fd <= 0) { + return SUCCESS; + } + + close(pid_lock_fd); // Unlocks the file simultaneously + if (unlink(get_program_config()->pidfile) < 0) { + PR_WARN("无法删除 PID 文件"); + } + return SUCCESS; +} diff --git a/pool/shard000/C/0009428_init.c b/pool/shard000/C/0009428_init.c new file mode 100644 index 0000000000000000000000000000000000000000..77d3c7f87119ffdaed4c5b93a66c547541792997 --- /dev/null +++ b/pool/shard000/C/0009428_init.c @@ -0,0 +1,73 @@ +/* Init + * + * This routine is the initialization task for this test program. + * It is a user initialization task and has the responsibility for creating + * and starting the tasks that make up the test. If the time of day + * clock is required for the test, it should also be set to a known + * value by this function. + * + * Input parameters: + * argument - task argument + * + * Output parameters: NONE + * + * COPYRIGHT (c) 1989-1999. + * On-Line Applications Research Corporation (OAR). + * + * The license and distribution terms for this file may be + * found in the file LICENSE in this distribution or at + * http://www.rtems.com/license/LICENSE. + * + * $Id$ + */ + +#define CONFIGURE_INIT +#include "system.h" + +rtems_task Init( + rtems_task_argument argument +) +{ + rtems_status_code status; + + printf( + "\n\n*** TEST 9 -- NODE %" PRId32 " ***\n", + Multiprocessing_configuration.node + ); + + Task_name[ 1 ] = rtems_build_name( '1', '1', '1', ' ' ); + Task_name[ 2 ] = rtems_build_name( '2', '2', '2', ' ' ); + + Queue_name[ 1 ] = rtems_build_name( 'M', 'S', 'G', ' ' ); + + if ( Multiprocessing_configuration.node == 1 ) { + puts( "Creating Message Queue (Global)" ); + status = rtems_message_queue_create( + Queue_name[ 1 ], + 3, + 16, + RTEMS_GLOBAL, + &Queue_id[ 1 ] + ); + directive_failed( status, "rtems_message_queue_create" ); + } + + puts( "Creating Test_task (local)" ); + status = rtems_task_create( + Task_name[Multiprocessing_configuration.node], + 1, + RTEMS_MINIMUM_STACK_SIZE, + RTEMS_TIMESLICE, + RTEMS_DEFAULT_ATTRIBUTES, + &Task_id[ 1 ] + ); + directive_failed( status, "rtems_task_create" ); + + puts( "Starting Test_task (local)" ); + status = rtems_task_start( Task_id[ 1 ], Test_task, 0 ); + directive_failed( status, "rtems_task_start" ); + + puts( "Deleting initialization task" ); + status = rtems_task_delete( RTEMS_SELF ); + directive_failed( status, "rtems_task_delete of RTEMS_SELF" ); +} diff --git a/pool/shard000/C/0009432_shadow_subsystem.c b/pool/shard000/C/0009432_shadow_subsystem.c new file mode 100644 index 0000000000000000000000000000000000000000..5316e45fc586ad593ac46697c882ec448dc0c521 --- /dev/null +++ b/pool/shard000/C/0009432_shadow_subsystem.c @@ -0,0 +1,229 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "shadow.h" + +#include "shadow_subsystem.h" + +struct _RDP_SHADOW_SUBSYSTEM +{ + const char* name; + pfnShadowSubsystemEntry entry; +}; +typedef struct _RDP_SHADOW_SUBSYSTEM RDP_SHADOW_SUBSYSTEM; + + +#ifdef WITH_SHADOW_X11 +extern int X11_ShadowSubsystemEntry(RDP_SHADOW_ENTRY_POINTS* pEntryPoints); +#endif + +#ifdef WITH_SHADOW_MAC +extern int Mac_ShadowSubsystemEntry(RDP_SHADOW_ENTRY_POINTS* pEntryPoints); +#endif + +#ifdef WITH_SHADOW_WIN +extern int Win_ShadowSubsystemEntry(RDP_SHADOW_ENTRY_POINTS* pEntryPoints); +#endif + + +static RDP_SHADOW_SUBSYSTEM g_Subsystems[] = +{ + +#ifdef WITH_SHADOW_X11 + { "X11", X11_ShadowSubsystemEntry }, +#endif + +#ifdef WITH_SHADOW_MAC + { "Mac", Mac_ShadowSubsystemEntry }, +#endif + +#ifdef WITH_SHADOW_WIN + { "Win", Win_ShadowSubsystemEntry }, +#endif + + { "", NULL } +}; + +static int g_SubsystemCount = (sizeof(g_Subsystems) / sizeof(g_Subsystems[0])); + +pfnShadowSubsystemEntry shadow_subsystem_load_static_entry(const char* name) +{ + int index; + + if (!name) + { + for (index = 0; index < g_SubsystemCount; index++) + { + if (g_Subsystems[index].name) + return g_Subsystems[index].entry; + } + } + + for (index = 0; index < g_SubsystemCount; index++) + { + if (strcmp(name, g_Subsystems[index].name) == 0) + return g_Subsystems[index].entry; + } + + return NULL; +} + +int shadow_subsystem_load_entry_points(RDP_SHADOW_ENTRY_POINTS* pEntryPoints, const char* name) +{ + pfnShadowSubsystemEntry entry; + + entry = shadow_subsystem_load_static_entry(name); + + ZeroMemory(pEntryPoints, sizeof(RDP_SHADOW_ENTRY_POINTS)); + + if (!entry) + return -1; + + if (entry(pEntryPoints) < 0) + return -1; + + return 1; +} + +rdpShadowSubsystem* shadow_subsystem_new(const char* name) +{ + RDP_SHADOW_ENTRY_POINTS ep; + rdpShadowSubsystem* subsystem = NULL; + + shadow_subsystem_load_entry_points(&ep, name); + + if (!ep.New) + return NULL; + + subsystem = ep.New(); + + if (!subsystem) + return NULL; + + CopyMemory(&(subsystem->ep), &ep, sizeof(RDP_SHADOW_ENTRY_POINTS)); + + return subsystem; +} + +void shadow_subsystem_free(rdpShadowSubsystem* subsystem) +{ + if (subsystem && subsystem->ep.Free) + subsystem->ep.Free(subsystem); +} + +int shadow_subsystem_init(rdpShadowSubsystem* subsystem, rdpShadowServer* server) +{ + int status = -1; + + if (!subsystem || !subsystem->ep.Init) + return -1; + + subsystem->server = server; + subsystem->selectedMonitor = server->selectedMonitor; + + if (!(subsystem->MsgPipe = MessagePipe_New())) + goto fail; + + if (!(subsystem->updateEvent = shadow_multiclient_new())) + goto fail; + + region16_init(&(subsystem->invalidRegion)); + + if ((status = subsystem->ep.Init(subsystem)) >= 0) + return status; + +fail: + if (subsystem->MsgPipe) + { + MessagePipe_Free(subsystem->MsgPipe); + subsystem->MsgPipe = NULL; + } + + if (subsystem->updateEvent) + { + shadow_multiclient_free(subsystem->updateEvent); + subsystem->updateEvent = NULL; + } + + return status; +} + +void shadow_subsystem_uninit(rdpShadowSubsystem* subsystem) +{ + if (!subsystem) + return; + + if (subsystem->ep.Uninit) + subsystem->ep.Uninit(subsystem); + + if (subsystem->MsgPipe) + { + MessagePipe_Free(subsystem->MsgPipe); + subsystem->MsgPipe = NULL; + } + + if (subsystem->updateEvent) + { + shadow_multiclient_free(subsystem->updateEvent); + subsystem->updateEvent = NULL; + } + + if (subsystem->invalidRegion.data) + region16_uninit(&(subsystem->invalidRegion)); +} + +int shadow_subsystem_start(rdpShadowSubsystem* subsystem) +{ + int status; + + if (!subsystem || !subsystem->ep.Start) + return -1; + + status = subsystem->ep.Start(subsystem); + + return status; +} + +int shadow_subsystem_stop(rdpShadowSubsystem* subsystem) +{ + int status; + + if (!subsystem || !subsystem->ep.Stop) + return -1; + + status = subsystem->ep.Stop(subsystem); + + return status; +} + +int shadow_enum_monitors(MONITOR_DEF* monitors, int maxMonitors, const char* name) +{ + int numMonitors = 0; + RDP_SHADOW_ENTRY_POINTS ep; + + if (shadow_subsystem_load_entry_points(&ep, name) < 0) + return -1; + + numMonitors = ep.EnumMonitors(monitors, maxMonitors); + + return numMonitors; +} diff --git a/pool/shard000/C/0009457_video_capture.c b/pool/shard000/C/0009457_video_capture.c new file mode 100644 index 0000000000000000000000000000000000000000..aa20d15633db26cfb5febad68f14c824d9f9d931 --- /dev/null +++ b/pool/shard000/C/0009457_video_capture.c @@ -0,0 +1,136 @@ +/* + * Copyright (C) 2015 + * + * This file is part of Paparazzi. + * + * Paparazzi is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2, or (at your option) + * any later version. + * + * Paparazzi 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 paparazzi; see the file COPYING. If not, see + * . + * + */ + +/** + * @file modules/computer_vision/video_capture.c + */ + +#include +#include +#include + +#include "modules/computer_vision/video_capture.h" +#include "modules/computer_vision/cv.h" + +#include "lib/encoding/jpeg.h" + +// Note: this define is set automatically when the video_exif module is included, +// and exposes functions to write data in the image exif headers. +#if JPEG_WITH_EXIF_HEADER +#include "lib/exif/exif_module.h" +#endif + +#ifndef VIDEO_CAPTURE_PATH +#define VIDEO_CAPTURE_PATH /data/video/images +#endif + +#ifndef VIDEO_CAPTURE_JPEG_QUALITY +#define VIDEO_CAPTURE_JPEG_QUALITY 99 +#endif + +// Module settings +bool video_capture_take_shot = false; +int video_capture_index = 0; + +// Forward function declarations +struct image_t *video_capture_func(struct image_t *img); +void video_capture_save(struct image_t *img); + + +void video_capture_init(void) +{ + // Create the images directory + char save_name[128]; + sprintf(save_name, "mkdir -p %s", STRINGIFY(VIDEO_CAPTURE_PATH)); + if (system(save_name) != 0) { + printf("[video_capture] Could not create images directory %s.\n", STRINGIFY(VIDEO_CAPTURE_PATH)); + return; + } + + // Add function to computer vision pipeline + cv_add_to_device(&VIDEO_CAPTURE_CAMERA, video_capture_func); +} + + +struct image_t *video_capture_func(struct image_t *img) +{ + // If take_shot bool is set, save the image + if (video_capture_take_shot) { + video_capture_save(img); + video_capture_take_shot = false; + } + + // No modification to image + return NULL; +} + + +void video_capture_shoot(void) +{ + // Set take_shot bool to true + video_capture_take_shot = true; +} + + +void video_capture_save(struct image_t *img) +{ + // Declare storage for image location + char save_name[128]; + + // Simple shot counter to find first available image location + for (/* no init */; video_capture_index < 9999; ++video_capture_index) { + // Generate image location + sprintf(save_name, "%s/img_%05d.jpg", STRINGIFY(VIDEO_CAPTURE_PATH), video_capture_index); + + // Continue with next number if file exists already + if (access(save_name, F_OK) != -1) { + continue; + } + + printf("[video_capture] Saving image to %s.\n", save_name); + + // Create jpg image from raw frame + struct image_t img_jpeg; + image_create(&img_jpeg, img->w, img->h, IMAGE_JPEG); + jpeg_encode_image(img, &img_jpeg, VIDEO_CAPTURE_JPEG_QUALITY, true); + +#if JPEG_WITH_EXIF_HEADER + write_exif_jpeg(save_name, img_jpeg.buf, img_jpeg.buf_size, img_jpeg.w, img_jpeg.h); +#else + // Open file + FILE *fp = fopen(save_name, "w"); + if (fp == NULL) { + printf("[video_capture] Could not write shot %s.\n", save_name); + break; + } + + // Save it to the file and close it + fwrite(img_jpeg.buf, sizeof(uint8_t), img_jpeg.buf_size, fp); + fclose(fp); +#endif + + // Free image + image_free(&img_jpeg); + + // End loop here + break; + } +} diff --git a/pool/shard000/C/0009458_test_subr.c b/pool/shard000/C/0009458_test_subr.c new file mode 100644 index 0000000000000000000000000000000000000000..5a938dfa5b2e7fce6abdcad4090da3add395f212 --- /dev/null +++ b/pool/shard000/C/0009458_test_subr.c @@ -0,0 +1,166 @@ +/*- + * Copyright (c) 2007 Michael Telahun Makonnen + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + */ + +#include +__FBSDID("$FreeBSD: soc2013/dpl/head/tools/regression/netinet6/inet6_rth/test_subr.c 168968 2007-04-21 11:23:33Z mtm $"); + +#include + +#include +#include +#include + +#include "test_subr.h" + +int g_total; +int g_pass; +int g_fail; +char g_funcname[FUNCNAMESIZE]; +char g_testdesc[LINESIZE]; +char g_errbuf[LINESIZE]; + +void +set_funcname(char *bufp, size_t bufsize) +{ + strlcpy(g_funcname, bufp, + bufsize < FUNCNAMESIZE ? bufsize : FUNCNAMESIZE); +} + +/* + * desc is a NULL-terminated string. + */ +void +checkptr(caddr_t expected, caddr_t got, const char *desc) +{ + int len; + int failed; + char sbuf[LINESIZE]; + + memset((void *)sbuf, 0, LINESIZE); + snprintf(g_testdesc, LINESIZE, desc); + + failed = 1; + g_total++; + if (got == expected) { + len = snprintf(sbuf, LINESIZE, "ok"); + g_pass++; + failed = 0; + } else { + len = snprintf(sbuf, LINESIZE, "not ok"); + snprintf(g_errbuf, LINESIZE, " : Expected %#x, but got %#x", + (unsigned int)expected, (unsigned int)got); + g_fail++; + } + snprintf(sbuf + len, LINESIZE - len, " %d - %s (%s)", + g_total, g_funcname, g_testdesc); + printf(sbuf); + if (failed) + printf(g_errbuf); + printf("\n"); + fflush(NULL); + memset((void *)g_errbuf, 0, LINESIZE); + memset((void *)g_testdesc, 0, LINESIZE); +} + +void +checkstr(const char *expected, const char *got, size_t explen, const char *desc) +{ + int len; + int failed; + char sbuf[LINESIZE]; + + memset((void *)sbuf, 0, LINESIZE); + snprintf(g_testdesc, LINESIZE, desc); + + failed = 1; + g_total++; + if (strncmp(expected, got, explen) == 0) { + len = snprintf(sbuf, LINESIZE, "ok"); + g_pass++; + failed = 0; + } else { + len = snprintf(sbuf, LINESIZE, "not ok"); + snprintf(g_errbuf, LINESIZE, + " : Expected %s, but got %s", expected, got); + g_fail++; + } + snprintf(sbuf + len, LINESIZE - len, " %d - %s (%s)", + g_total, g_funcname, g_testdesc); + printf(sbuf); + if (failed) + printf(g_errbuf); + printf("\n"); + fflush(NULL); + memset((void *)g_errbuf, 0, LINESIZE); + memset((void *)g_testdesc, 0, LINESIZE); +} + +void +checknum(int expected, int got, int cmp, const char *desc) +{ + int len; + int pass; + int failed; + char sbuf[LINESIZE]; + + memset((void *)sbuf, 0, LINESIZE); + snprintf(g_testdesc, LINESIZE, desc); + + failed = 1; + pass = 0; + g_total++; + switch(cmp) { + case 0: + pass = (got == expected) ? 1 : 0; + break; + case 1: + pass = (got > expected) ? 1 : 0; + break; + case -1: + pass = (got < expected) ? 1 : 0; + break; + } + if (pass != 0) { + len = snprintf(sbuf, LINESIZE, "ok"); + g_pass++; + failed = 0; + } else { + len = snprintf(sbuf, LINESIZE, "not ok"); + snprintf(g_errbuf, LINESIZE, + " : Expected %d, but got %d", expected, got); + g_fail++; + } + snprintf(sbuf + len, LINESIZE - len, " %d - %s (%s)", + g_total, g_funcname, g_testdesc); + printf(sbuf); + if (failed) + printf(g_errbuf); + printf("\n"); + fflush(NULL); + memset((void *)g_errbuf, 0, LINESIZE); + memset((void *)g_testdesc, 0, LINESIZE); +} diff --git a/pool/shard000/C/0009465_list.c b/pool/shard000/C/0009465_list.c new file mode 100644 index 0000000000000000000000000000000000000000..a871940c9d1c2fd062c594ea6c261bf81db591fb --- /dev/null +++ b/pool/shard000/C/0009465_list.c @@ -0,0 +1,128 @@ +/* + * Copyright (C) 2015, 2016 Jamal Edey + * http://www.kenshisoft.com/ + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Kodi; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html + * + */ + +#include "list.h" + +#include +#include + +sc_list_t *sc_list_create() { + sc_list_t *list; + + list = (sc_list_t *) malloc(sizeof(sc_list_t)); + memset(list, 0, sizeof(*list)); + + return list; +} + +sc_list_node_t *sc_list_node_create(void *data) { + sc_list_node_t *node; + + node = (sc_list_node_t *) malloc(sizeof(sc_list_node_t)); + memset(node, 0, sizeof(*node)); + node->data = data; + + return node; +} + +sc_list_node_t *sc_list_node_link(sc_list_t *list, sc_list_node_t *a, sc_list_node_t *b) { + b->prev = a; + a->next = b; + list->last = b; + + return b; +} + +sc_list_node_t *sc_list_node_append(sc_list_t *list, sc_list_node_t *node) { + if (!list->first) { + list->first = node; + list->last = node; + return node; + } + return sc_list_node_link(list, list->last, node); +} + +sc_list_node_t *sc_list_node_unlink(sc_list_t *list, sc_list_node_t *node) { + sc_list_node_t *prev = NULL; + sc_list_node_t *next = NULL; + + prev = node->prev; + next = node->next; + + if (node == list->first) { + list->first = next; + } + + if (node == list->last) { + list->last = prev; + } + + if (prev) { + prev->next = next; + } + + if (next) { + next->prev = prev; + } + + node->prev = NULL; + node->next = NULL; + + return next; +} + +void sc_list_node_free(sc_list_node_t **node, bool free_data) { + if (!node) return; + if (*node) { + if (free_data && (*node)->data) { + free((*node)->data); + } + + (*node)->data = NULL; + (*node)->prev = NULL; + (*node)->next = NULL; + + free(*node); + } + *node = NULL; +} + +void sc_list_free(sc_list_t **list, bool free_node_data) { + if (!list) return; + if (*list) { + sc_list_node_t *node; + sc_list_node_t *next; + + node = (*list)->first; + while (node) { + next = node->next; + sc_list_node_free(&node, free_node_data); + node = next; + } + + (*list)->first = NULL; + (*list)->last = NULL; + + free(*list); + } + *list = NULL; +} diff --git a/pool/shard000/C/0009479_lm_raw.c b/pool/shard000/C/0009479_lm_raw.c new file mode 100644 index 0000000000000000000000000000000000000000..7dd959305b6b6aa006371b06f6387d7b7ddd713c --- /dev/null +++ b/pool/shard000/C/0009479_lm_raw.c @@ -0,0 +1,274 @@ +/* + * Raw data operations on strings. + * + * ------------------------------------------------ + * + * @begin[license] + * Copyright (C) 2001 Mojave Group, Caltech + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation, + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Additional permission is given to link this library with the + * OpenSSL project's "OpenSSL" library, and with the OCaml runtime, + * and you may distribute the linked executables. See the file + * LICENSE.libmojave for more details. + * + * Author: Jason Hickey + * @email{jyh@cs.caltech.edu} + * @end[license] + */ + +/* Standard includes */ +#include +#include +#include +#include + +/* Caml includes */ +#include +#include +#include +#include + +#ifdef WIN32 + typedef short int16_t; +#endif + +/* + * Load numbers from a string. + */ +value load_int8(value v_string, value v_off) +{ + CAMLparam2(v_string, v_off); + int off, len; + char *str; + + /* Get arguments */ + str = String_val(v_string); + len = string_length(v_string); + off = Int_val(v_off); + + /* Check bounds */ + if(off < 0 || off > len - 1) + failwith("load_int8"); + + /* Get the number */ + CAMLreturn(Val_int(str[off])); +} + +value load_int16(value v_string, value v_off) +{ + CAMLparam2(v_string, v_off); + int off, len; + char *str; + + /* Get arguments */ + str = String_val(v_string); + len = string_length(v_string); + off = Int_val(v_off); + + /* Check bounds */ + if(off < 0 || off > len - 2 || off & 1) + failwith("load_int16"); + + /* Get the number */ + CAMLreturn(Val_int(*(int16_t *)(str + off))); +} + +value load_int32(value v_string, value v_off) +{ + CAMLparam2(v_string, v_off); + CAMLlocal1(result); + int off, len; + char *str; + int32 i; + + /* Get arguments */ + str = String_val(v_string); + len = string_length(v_string); + off = Int_val(v_off); + + /* Check bounds */ + if(off < 0 || off > len - 4 || off & 3) + failwith("load_int32"); + + /* Get the number */ + i = *(int32 *)(str + off); + result = copy_int32(i); + CAMLreturn(result); +} + +value load_int64(value v_string, value v_off) +{ + CAMLparam2(v_string, v_off); + CAMLlocal1(result); + int off, len; + char *str; + int64 i; + + /* Get arguments */ + str = String_val(v_string); + len = string_length(v_string); + off = Int_val(v_off); + + /* Check bounds */ + if(off < 0 || off > len - 8 || off & 3) + failwith("load_int64"); + + /* Get the number */ + i = *(int64 *)(str + off); + result = copy_int64(i); + CAMLreturn(result); +} + +value load_float(value v_string, value v_off) +{ + CAMLparam2(v_string, v_off); + CAMLlocal1(result); + int off, len; + char *str; + double x; + + /* Get arguments */ + str = String_val(v_string); + len = string_length(v_string); + off = Int_val(v_off); + + /* Check bounds */ + if(off < 0 || off > len - 8 || off & 7) + failwith("load_float"); + + /* Get the number */ + x = *(double *)(str + off); + result = copy_double(x); + CAMLreturn(result); +} + +/* + * Store numbers to a string. + */ +value store_int8(value v_string, value v_off, value v_val) +{ + CAMLparam3(v_string, v_off, v_val); + int off, len, i; + char *str; + + /* Get arguments */ + str = String_val(v_string); + len = string_length(v_string); + off = Int_val(v_off); + i = Int_val(v_val); + + /* Check bounds */ + if(off < 0 || off > len - 1) + failwith("store_int8"); + + /* Get the number */ + str[off] = i; + CAMLreturn(Val_unit); +} + +value store_int16(value v_string, value v_off, value v_val) +{ + CAMLparam3(v_string, v_off, v_val); + int off, len, i; + char *str; + + /* Get arguments */ + str = String_val(v_string); + len = string_length(v_string); + off = Int_val(v_off); + i = Int_val(v_val); + + /* Check bounds */ + if(off < 0 || off > len - 2 || off & 1) + failwith("store_int16"); + + /* Get the number */ + *(int16_t *)(str + off) = i; + CAMLreturn(Val_unit); +} + +value store_int32(value v_string, value v_off, value v_val) +{ + CAMLparam3(v_string, v_off, v_val); + CAMLlocal1(result); + int off, len; + char *str; + int32 i; + + /* Get arguments */ + str = String_val(v_string); + len = string_length(v_string); + off = Int_val(v_off); + i = Int32_val(v_val); + + /* Check bounds */ + if(off < 0 || off > len - 4 || off & 3) + failwith("store_int32"); + + /* Get the number */ + *(int32 *)(str + off) = i; + CAMLreturn(Val_unit); +} + +value store_int64(value v_string, value v_off, value v_val) +{ + CAMLparam3(v_string, v_off, v_val); + CAMLlocal1(result); + int off, len; + char *str; + int64 i; + + /* Get arguments */ + str = String_val(v_string); + len = string_length(v_string); + off = Int_val(v_off); + i = Int64_val(v_val); + + /* Check bounds */ + if(off < 0 || off > len - 8 || off & 3) + failwith("store_int64"); + + /* Get the number */ + *(int64 *)(str + off) = i; + CAMLreturn(Val_unit); +} + +value store_float(value v_string, value v_off, value v_val) +{ + CAMLparam2(v_string, v_off); + CAMLlocal1(result); + int off, len; + char *str; + double x; + + /* Get arguments */ + str = String_val(v_string); + len = string_length(v_string); + off = Int_val(v_off); + x = Double_val(v_val); + + /* Check bounds */ + if(off < 0 || off > len - 8 || off & 7) + failwith("store_float"); + + /* Get the number */ + *(double *)(str + off) = x; + CAMLreturn(Val_unit); +} + + + diff --git a/pool/shard000/C/0009489_robostix.c b/pool/shard000/C/0009489_robostix.c new file mode 100644 index 0000000000000000000000000000000000000000..c2ab2b31de3dcf7600a6c972d38d8fdb2681330d --- /dev/null +++ b/pool/shard000/C/0009489_robostix.c @@ -0,0 +1,278 @@ +/**************************************************************************** +* +* Copyright (c) 2006 Dave Hylands +* +* This program is free software; you can redistribute it and/or modify +* it under the terms of the GNU General Public License version 2 as +* published by the Free Software Foundation. +* +* Alternatively, this software may be distributed under the terms of BSD +* license. +* +* See README and COPYING for more details. +* +****************************************************************************/ +/** +* +* robostix.c +* +* PURPOSE: +* +* This implements the usermode program for talking to the robostix. +* +*****************************************************************************/ + +/* ---- Include Files ---------------------------------------------------- */ + +#include +#include +#include +#include + +#include "robostix_drv.h" + +/* ---- Public Variables ------------------------------------------------- */ + +int gFd = -1; + +int gVal; + +/* ---- Private Constants and Types -------------------------------------- */ +/* ---- Private Variables ------------------------------------------------ */ + +typedef struct +{ + const char *cmdStr; + const char *argStr; + const char *helpStr; + int (*parseArgs)( int argc, char **argv ); + void (*execFunc)( int cmd ); + int cmd; + +} Cmd; + +int ParseNone( int argc, char **argv ); +int ParseOnOffArg( int argc, char **argv ); +int ParseOnOffPulseArg( int argc, char **argv ); +void Usage( void ); + +void Power( int cmd ); +void ReadIOctl( int cmd ); +void SimpleIOctl( int cmd ); + +Cmd gCmd[] = +{ + { "power", "on|off", "Controls the robostix voltage regulators", ParseOnOffArg, Power, -1 }, + { "reset", "on|off|pulse", "Resets the robostix", ParseOnOffPulseArg, SimpleIOctl, ROBOSTIX_IOCTL_RESET }, + { "245", "on|off", "Controls the 245 buffer chip", ParseOnOffArg, SimpleIOctl, ROBOSTIX_IOCTL_245_ENABLE }, + + { "sck", "on|off", "Sets/clears the SCK line", ParseOnOffArg, SimpleIOctl, ROBOSTIX_IOCTL_SET_SCK }, + { "ss", "on|off", "Sets/clears the SS line", ParseOnOffArg, SimpleIOctl, ROBOSTIX_IOCTL_SET_SS }, + { "txd", "on|off", "Sets/clears the IR-TXD line", ParseOnOffArg, SimpleIOctl, ROBOSTIX_IOCTL_SET_IR_TXD }, + { "mosi", "on|off", "Sets/clears the MOSI line", ParseOnOffArg, SimpleIOctl, ROBOSTIX_IOCTL_SET_MOSI }, + + { "rxd", "", "Reads the IR-RXD line", ParseNone, ReadIOctl, ROBOSTIX_IOCTL_GET_IR_RXD }, + { "irq", "", "Reads the TM-IRQ line", ParseNone, ReadIOctl, ROBOSTIX_IOCTL_GET_IRQ }, + { "miso", "", "Reads the MISO line", ParseNone, ReadIOctl, ROBOSTIX_IOCTL_GET_MISO }, + + { NULL } +}; + +/* ---- Private Function Prototypes -------------------------------------- */ +/* ---- Functions -------------------------------------------------------- */ + + +/**************************************************************************** +* +* main +* +***************************************************************************/ + +int main( int argc, char **argv ) +{ + char *cmdStr; + int argIdx; + Cmd *cmd; + + if ( argc == 1 ) + { + Usage( ); + exit( 0 ); + } + + if (( gFd = open( "/dev/robostix", O_RDWR )) < 0 ) + { + perror( "Unable to open /dev/robostix" ); + exit( 1 ); + } + + argIdx = 1; + cmdStr = argv[ argIdx++ ]; + + for ( cmd = gCmd; cmd->cmdStr != NULL; cmd++ ) + { + if ( strcasecmp( cmdStr, cmd->cmdStr ) == 0 ) + { + break; + } + } + if ( cmd->cmdStr == NULL ) + { + fprintf( stderr, "Unrecognized command: '%s'\n", cmdStr ); + exit( 1 ); + } + + if ( cmd->parseArgs( argc - argIdx, &argv[ argIdx ] )) + { + cmd->execFunc( cmd->cmd ); + } + + close( gFd ); + + exit( 0 ); + return 0; + +} // main + +/**************************************************************************** +* +* Checks to see if the argument is on/off (or equivalent) +* +***************************************************************************/ + +int IsOnOffArg( int argc, char **argv ) +{ + if (( strcasecmp( *argv, "on" ) == 0 ) + || ( strcasecmp( *argv, "t" ) == 0 ) + || ( strcasecmp( *argv, "1" ) == 0 )) + { + gVal = 1; + return 1; + } + + if (( strcasecmp( *argv, "off" ) == 0 ) + || ( strcasecmp( *argv, "f" ) == 0 ) + || ( strcasecmp( *argv, "0" ) == 0 )) + { + gVal = 0; + return 1; + } + + return 0; + +} // IsOnOffArg + +/**************************************************************************** +* +* Parses no arguments +* +***************************************************************************/ + +int ParseNone( int argc, char **argv ) +{ + return 1; + +} // ParseNone + +/**************************************************************************** +* +* Parses a command line argument for legel on/off values +* +***************************************************************************/ + +int ParseOnOffArg( int argc, char **argv ) +{ + if ( IsOnOffArg( argc, argv )) + { + return 1; + } + + fprintf( stderr, "Expecting on/off, found: '%s'\n", *argv ); + return 0; + +} // ParseOnOffArg + +/**************************************************************************** +* +* Parses a command line argument for legel on/off values +* +***************************************************************************/ + +int ParseOnOffPulseArg( int argc, char **argv ) +{ + if (( strcasecmp( *argv, "pulse" ) == 0 ) + || ( strcasecmp( *argv, "2" ) == 0 )) + { + gVal = 2; + return 1; + } + + if ( IsOnOffArg( argc, argv )) + { + return 1; + } + + fprintf( stderr, "Expecting on/off/pulse, found: '%s'\n", *argv ); + return 0; + +} // ParseOnoffPulseArg + +/**************************************************************************** +* +* Power +* +***************************************************************************/ + +void Power( int cmd ) +{ + SimpleIOctl( ROBOSTIX_IOCTL_POWER_VCC5 ); + +} // Power + +/**************************************************************************** +* +* SimpleIOctl +* +***************************************************************************/ + +void SimpleIOctl( int cmd ) +{ + if ( ioctl( gFd, cmd, gVal ) != 0 ) + { + fprintf( stderr, "ioctl call failed: %d\n", errno ); + } + +} // SimpleIOctl + +/**************************************************************************** +* +* SimpleIOctl +* +***************************************************************************/ + +void ReadIOctl( int cmd ) +{ + if ( ioctl( gFd, cmd, &gVal ) != 0 ) + { + fprintf( stderr, "ioctl call failed: %d\n", errno ); + } + +} // ReadIOctl + +/**************************************************************************** +* +* Usage +* +***************************************************************************/ + +void Usage( void ) +{ + Cmd *cmd; + + for ( cmd = gCmd; cmd->cmdStr != NULL; cmd++ ) + { + printf( "%-12s %-12s %s\n", cmd->cmdStr, cmd->argStr, cmd->helpStr ); + } + +} // Usage + diff --git a/pool/shard000/C/0009498_proc.c b/pool/shard000/C/0009498_proc.c new file mode 100644 index 0000000000000000000000000000000000000000..85ac848ac6ab60dbd5488c36de79cd7b62fbceba --- /dev/null +++ b/pool/shard000/C/0009498_proc.c @@ -0,0 +1,152 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "sleep.h" +#include "internal.h" + +#define _COMPONENT ACPI_SYSTEM_COMPONENT + +/* + * this file provides support for: + * /proc/acpi/wakeup + */ + +ACPI_MODULE_NAME("sleep") + +static int +acpi_system_wakeup_device_seq_show(struct seq_file *seq, void *offset) +{ + struct list_head *node, *next; + + seq_printf(seq, "Device\tS-state\t Status Sysfs node\n"); + + mutex_lock(&acpi_device_lock); + list_for_each_safe(node, next, &acpi_wakeup_device_list) { + struct acpi_device *dev = + container_of(node, struct acpi_device, wakeup_list); + struct acpi_device_physical_node *entry; + + if (!dev->wakeup.flags.valid) + continue; + + seq_printf(seq, "%s\t S%d\t", + dev->pnp.bus_id, + (u32) dev->wakeup.sleep_state); + + mutex_lock(&dev->physical_node_lock); + + if (!dev->physical_node_count) { + seq_printf(seq, "%c%-8s\n", + dev->wakeup.flags.valid ? '*' : ' ', + device_may_wakeup(&dev->dev) ? + "enabled" : "disabled"); + } else { + struct device *ldev; + list_for_each_entry(entry, &dev->physical_node_list, + node) { + ldev = get_device(entry->dev); + if (!ldev) + continue; + + if (&entry->node != + dev->physical_node_list.next) + seq_printf(seq, "\t\t"); + + seq_printf(seq, "%c%-8s %s:%s\n", + dev->wakeup.flags.valid ? '*' : ' ', + (device_may_wakeup(&dev->dev) || + device_may_wakeup(ldev)) ? + "enabled" : "disabled", + ldev->bus ? ldev->bus->name : + "no-bus", dev_name(ldev)); + put_device(ldev); + } + } + + mutex_unlock(&dev->physical_node_lock); + } + mutex_unlock(&acpi_device_lock); + return 0; +} + +static void physical_device_enable_wakeup(struct acpi_device *adev) +{ + struct acpi_device_physical_node *entry; + + mutex_lock(&adev->physical_node_lock); + + list_for_each_entry(entry, + &adev->physical_node_list, node) + if (entry->dev && device_can_wakeup(entry->dev)) { + bool enable = !device_may_wakeup(entry->dev); + device_set_wakeup_enable(entry->dev, enable); + } + + mutex_unlock(&adev->physical_node_lock); +} + +static ssize_t +acpi_system_write_wakeup_device(struct file *file, + const char __user * buffer, + size_t count, loff_t * ppos) +{ + struct list_head *node, *next; + char strbuf[5]; + char str[5] = ""; + + if (count > 4) + count = 4; + + if (copy_from_user(strbuf, buffer, count)) + return -EFAULT; + strbuf[count] = '\0'; + sscanf(strbuf, "%s", str); + + mutex_lock(&acpi_device_lock); + list_for_each_safe(node, next, &acpi_wakeup_device_list) { + struct acpi_device *dev = + container_of(node, struct acpi_device, wakeup_list); + if (!dev->wakeup.flags.valid) + continue; + + if (!strncmp(dev->pnp.bus_id, str, 4)) { + if (device_can_wakeup(&dev->dev)) { + bool enable = !device_may_wakeup(&dev->dev); + device_set_wakeup_enable(&dev->dev, enable); + } else { + physical_device_enable_wakeup(dev); + } + break; + } + } + mutex_unlock(&acpi_device_lock); + return count; +} + +static int +acpi_system_wakeup_device_open_fs(struct inode *inode, struct file *file) +{ + return single_open(file, acpi_system_wakeup_device_seq_show, + PDE_DATA(inode)); +} + +static const struct file_operations acpi_system_wakeup_device_fops = { + .owner = THIS_MODULE, + .open = acpi_system_wakeup_device_open_fs, + .read = seq_read, + .write = acpi_system_write_wakeup_device, + .llseek = seq_lseek, + .release = single_release, +}; + +void __init acpi_sleep_proc_init(void) +{ + /* 'wakeup device' [R/W] */ + proc_create("wakeup", S_IFREG | S_IRUGO | S_IWUSR, + acpi_root_dir, &acpi_system_wakeup_device_fops); +} diff --git a/pool/shard000/C/0009503_eval_branch_insert.c b/pool/shard000/C/0009503_eval_branch_insert.c new file mode 100644 index 0000000000000000000000000000000000000000..437403b7d01440f912f16938f0d599692699ff9a --- /dev/null +++ b/pool/shard000/C/0009503_eval_branch_insert.c @@ -0,0 +1,71 @@ +#include "bistro_eval.h" + +void eval_branch_insert_rightnb(eval_ctx_t *ctx) +{ + eval_branch_t *nb_branch; + + nb_branch = eval_branch_create( + OP_NBR, eval_create_reset_curnb(ctx), -1); + if (ctx->curstack->branch == NULL) + ctx->curstack->branch = nb_branch; + else { + eval_branch_set_right(ctx->curstack->branch, nb_branch); + eval_branch_calc(ctx->bistro, &ctx->curstack->branch, + ctx->curstack->branch); + } +} + +void eval_branch_insert_op_start(eval_branch_t **branch, + eval_op_branchs_t *op_branchs) +{ + eval_branch_set_left(op_branchs->opb, op_branchs->nbb); + *branch = op_branchs->opb; +} + +void eval_branch_insert_op_prio_in(bistro_t *bistro, eval_branch_t **branch, + eval_op_branchs_t *op_branchs, int prio) +{ + eval_branch_t *calc_branch; + + eval_branch_set_right(*branch, op_branchs->nbb); + calc_branch = *branch; + while ((*branch)->parent != NULL && + (*branch)->parent->priority == prio) { + *branch = (*branch)->parent; + } + if ((*branch)->parent) { + (*branch)->parent->right = NULL; + eval_branch_set_right((*branch)->parent, op_branchs->opb); + (*branch)->parent = NULL; + } + eval_branch_set_left(op_branchs->opb, *branch); + *branch = op_branchs->opb; + eval_branch_calc(bistro, branch, calc_branch); +} + +void eval_branch_insert_op_prio(bistro_t *bistro, eval_branch_t **branch, + eval_op_branchs_t *op_branchs, int prio) +{ + if ((*branch)->priority < prio) { + eval_branch_set_left(op_branchs->opb, op_branchs->nbb); + eval_branch_set_right(*branch, op_branchs->opb); + *branch = op_branchs->opb; + } else + eval_branch_insert_op_prio_in( + bistro, branch, op_branchs, prio); +} + +void eval_branch_insert_op(bistro_t *bistro, eval_branch_t **branch, + eval_insert_op_t *insert_op) +{ + eval_op_branchs_t op_branchs; + + op_branchs.opb = eval_branch_create( + insert_op->op, NULL, insert_op->priority); + op_branchs.nbb = eval_branch_create(OP_NBR, insert_op->nb, -1); + if (*branch) + eval_branch_insert_op_prio( + bistro, branch, &op_branchs, insert_op->priority); + else + eval_branch_insert_op_start(branch, &op_branchs); +} diff --git a/pool/shard000/C/0009511_opencl.c b/pool/shard000/C/0009511_opencl.c new file mode 100644 index 0000000000000000000000000000000000000000..a42449ef5ed715a90b32828d4a18c3b39710bb96 --- /dev/null +++ b/pool/shard000/C/0009511_opencl.c @@ -0,0 +1,185 @@ +/* Raystorm: OpenCL Raytracing Sandbox + * (c) 2017 Michał Siejak + */ + +#include +#include +#include + +#include "raystorm.h" +#include "platform.h" + +struct CLContext { + cl_platform_id platform; + cl_device_id device; + cl_context context; +}; + +static void cl_error_cb(const char* errinfo, const void* private_info, size_t cb, void* user_data) +{ + UNUSED(private_info); + UNUSED(cb); + UNUSED(user_data); + + LOG_ERROR("OpenCL: %s", errinfo); +} + +static bool cl_context_create_for_platform(CLContext* cl, const GLContext* gl, const cl_platform_id platform) +{ + cl_uint num_devices = 0; + clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 0, NULL, &num_devices); + if(num_devices == 0) { + return false; + } + + cl_device_id* cl_devices = malloc(num_devices * sizeof(cl_device_id)); + clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, num_devices, cl_devices, NULL); + +#if PLATFORM_X11 + const cl_context_properties context_props[] = { + CL_CONTEXT_PLATFORM, (cl_context_properties)platform, + CL_GL_CONTEXT_KHR, (cl_context_properties)gl->glx_context, + CL_GLX_DISPLAY_KHR, (cl_context_properties)gl->x11_display, + 0, + }; +#endif + + cl->context = clCreateContext(context_props, num_devices, cl_devices, cl_error_cb, NULL, NULL); + free(cl_devices); + if(!cl->context) { + LOG_ERROR("Failed to create OpenCL context; trying next platform..."); + return false; + } + + clGetGLContextInfoKHR_fn clGetGLContextInfoKHR = (clGetGLContextInfoKHR_fn)clGetExtensionFunctionAddressForPlatform(platform, "clGetGLContextInfoKHR"); + if(!clGetGLContextInfoKHR) { + clReleaseContext(cl->context); + return false; + } + clGetGLContextInfoKHR(context_props, CL_CURRENT_DEVICE_FOR_GL_CONTEXT_KHR, sizeof(cl_device_id), &cl->device, NULL); + if(!cl->device) { + clReleaseContext(cl->context); + return false; + } + return true; +} + +CLContext* cl_context_create(const GLContext* gl) +{ + assert(gl); + + cl_uint num_platforms; + if(clGetPlatformIDs(0, NULL, &num_platforms) != CL_SUCCESS || num_platforms == 0) { + LOG_ERROR("Failed to enumerate OpenCL platforms"); + return NULL; + } + + CLContext* cl = malloc(sizeof(CLContext)); + memset(cl, 0, sizeof(CLContext)); + + cl_platform_id* cl_platforms = malloc(num_platforms * sizeof(cl_platform_id)); + clGetPlatformIDs(num_platforms, cl_platforms, NULL); + + for(cl_uint i=0; iplatform; i++) { + char* ext_string; + size_t ext_string_size; + + clGetPlatformInfo(cl_platforms[i], CL_PLATFORM_EXTENSIONS, 0, NULL, &ext_string_size); + ext_string = malloc(ext_string_size); + clGetPlatformInfo(cl_platforms[i], CL_PLATFORM_EXTENSIONS, ext_string_size, ext_string, NULL); + + if(strstr(ext_string, "cl_khr_gl_sharing")) { + if(cl_context_create_for_platform(cl, gl, cl_platforms[i])) { + cl->platform = cl_platforms[i]; + } + } + free(ext_string); + } + free(cl_platforms); + + if(!cl->platform) { + LOG_ERROR("No suitable OpenCL platform found"); + free(cl); + return NULL; + } + + return cl; +} + +void cl_context_destroy(CLContext* cl) +{ + assert(cl); + clReleaseContext(cl->context); + free(cl); +} + +cl_program cl_build_program(const CLContext* cl, const char* filename) +{ + assert(cl); + assert(filename); + + const char* src = util_read_textfile(filename); + if(!src) { + LOG_ERROR("Failed to read CL program source file: %s", filename); + return NULL; + } + + cl_program program = clCreateProgramWithSource(cl->context, 1, &src, NULL, NULL); + if(!program) { + LOG_ERROR("Failed to create CL program from source file: %s", filename); + return NULL; + } + + cl_int build_status = clBuildProgram(program, 1, &cl->device, "-cl-std=CL1.2 -Werror -I gpu", NULL, NULL); + if(build_status == CL_BUILD_PROGRAM_FAILURE) { + char* buildlog; + size_t buildlog_size; + + clGetProgramBuildInfo(program, cl->device, CL_PROGRAM_BUILD_LOG, 0, NULL, &buildlog_size); + buildlog = malloc(buildlog_size); + clGetProgramBuildInfo(program, cl->device, CL_PROGRAM_BUILD_LOG, buildlog_size, buildlog, NULL); + + LOG_ERROR("Failed to build CL program: %s\n%s", filename, buildlog); + free(buildlog); + + clReleaseProgram(program); + return NULL; + } + else if(build_status != CL_SUCCESS) { + LOG_ERROR("Failed to build CL program: %s", filename); + clReleaseProgram(program); + return NULL; + } + + return program; +} + +cl_mem cl_create_framebuffer_object(const CLContext* cl, GLuint gl_fb) +{ + assert(cl); + + cl_mem fb = clCreateFromGLTexture(cl->context, CL_MEM_WRITE_ONLY, GL_TEXTURE_2D, 0, gl_fb, NULL); + if(!fb) { + LOG_ERROR("Failed to create CL framebuffer object from GL texture handle: %d", gl_fb); + return NULL; + } + return fb; +} + +cl_command_queue cl_create_queue(const CLContext* cl) +{ + assert(cl); + + cl_command_queue_properties props = 0; +#if PROFILE_CL + props |= CL_QUEUE_PROFILING_ENABLE; +#endif + + cl_int error; + cl_command_queue queue = clCreateCommandQueue(cl->context, cl->device, props, &error); + if(!queue) { + LOG_ERROR("Failed to create CL command queue: %d", error); + return NULL; + } + return queue; +} diff --git a/pool/shard000/C/0009513_mactopl.c b/pool/shard000/C/0009513_mactopl.c new file mode 100644 index 0000000000000000000000000000000000000000..b9979e3a7359e56938be406aed19a042616a5133 --- /dev/null +++ b/pool/shard000/C/0009513_mactopl.c @@ -0,0 +1,65 @@ +/* SCCS Id: @(#)mactopl.c 3.1 91/07/23 */ +/* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */ +/* NetHack may be freely redistributed. See license for details. */ + +#include "hack.h" +#include "mactty.h" +#include "macwin.h" +#include "macpopup.h" + +char +queued_resp(char *resp) { + char buf[30]; + if (try_key_queue(buf)) { + if (!resp || strchr(resp, buf[0])) + return buf[0]; + if (digit(buf[0]) && strchr(resp, '#')) { + yn_number = atoi(buf); + return '#'; + } + } + return '\0'; +} + + +char +topl_yn_function(const char *query, const char *resp, char def) { + char buf[30]; + char c = queued_resp((char *) resp); + if (!c) { + enter_topl_mode((char *) query); + topl_set_resp((char *) resp, def); + + do { + c = readchar(); + if (c && resp && !strchr(resp, c)) { + nhbell(); + c = '\0'; + } + } while (!c); + + topl_set_resp("", '\0'); + leave_topl_mode(buf); + if (c == '#') + yn_number = atoi(buf); + } + return c; +} + + +char +mac_yn_function(query, resp, def) +const char *query,*resp; +char def; +/* + * Generic yes/no function. 'def' is the default (returned by space or + * return; 'esc' returns 'q', or 'n', or the default, depending on + * what's in the string. The 'query' string is printed before the user + * is asked about the string. + * If resp is NULL, any single character is accepted and returned. + */ +{ + return topl_yn_function(query, resp, def); +} + +/* mactopl.c */ diff --git a/pool/shard000/C/0009525_ascii-mandelbrot.c b/pool/shard000/C/0009525_ascii-mandelbrot.c new file mode 100644 index 0000000000000000000000000000000000000000..9f94cde0348969489aedb8ccee4370c1cdee253e --- /dev/null +++ b/pool/shard000/C/0009525_ascii-mandelbrot.c @@ -0,0 +1,71 @@ + +/*----------------------------------------------------------------------+ + | | + | Example.c -- Demonstrate ideas for standard library | + | | + +----------------------------------------------------------------------*/ + +// Standard includes +#include +#include +#include + +// System include +#include + + + + +int mandelbrot(void) +{ + int z; + int x; + int y; + int x0; + int y0; + int x2; + int y2; + int iteration; + int xtemp; + +z = 0; +x = 0; +y0 = 0; +x0 = 0; +y0 = 0; + for (y0 = -7; y0 < 8; y0 = y0 + 1) + { + for (x0 = -17; x0 < 9; x0 = x0 + 1) + { + + x = 0; + y = 0; + iteration = 47; + while (iteration < 58) + { + x2 = x*x/8; + y2 = y*y/8; + z = x2 + y2; + if (z>32) break; + + xtemp = x2 - y2 + x0; + y = x*y/4 + y0; + x = xtemp; + iteration = iteration + 1; + + } + if(x0+y0 < 16) putchar(iteration); + } + } + return 0; +} + +int main(void) +{ +printf(" ASCII Mandelbrot\n"); +printf(" On Gigatron in c\n"); +printf(" Makerspace48\n"); +printf(" Arendal 2019\n\n\n\n\n\n\n\n"); +mandelbrot(); + return 0; +} diff --git a/pool/shard000/C/0009527_CWE127_Buffer_Underread__malloc_char_cpy_45.c b/pool/shard000/C/0009527_CWE127_Buffer_Underread__malloc_char_cpy_45.c new file mode 100644 index 0000000000000000000000000000000000000000..5a60a2d693dba7629fd2f8fde1faf0b8171d66d3 --- /dev/null +++ b/pool/shard000/C/0009527_CWE127_Buffer_Underread__malloc_char_cpy_45.c @@ -0,0 +1,122 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE127_Buffer_Underread__malloc_char_cpy_45.c +Label Definition File: CWE127_Buffer_Underread__malloc.label.xml +Template File: sources-sink-45.tmpl.c +*/ +/* + * @description + * CWE: 127 Buffer Under-read + * BadSource: Set data pointer to before the allocated memory buffer + * GoodSource: Set data pointer to the allocated memory buffer + * Sinks: cpy + * BadSink : Copy data to string using strcpy + * Flow Variant: 45 Data flow: data passed as a static global variable from one function to another in the same source file + * + * */ + +#include "std_testcase.h" + +#include + +static char * CWE127_Buffer_Underread__malloc_char_cpy_45_badData; +static char * CWE127_Buffer_Underread__malloc_char_cpy_45_goodG2BData; + +#ifndef OMITBAD + +static void badSink() +{ + char * data = CWE127_Buffer_Underread__malloc_char_cpy_45_badData; + { + char dest[100*2]; + memset(dest, 'C', 100*2-1); /* fill with 'C's */ + dest[100*2-1] = '\0'; /* null terminate */ + /* POTENTIAL FLAW: Possibly copy from a memory location located before the source buffer */ + strcpy(dest, data); + printLine(dest); + /* INCIDENTAL CWE-401: Memory Leak - data may not point to location + * returned by malloc() so can't safely call free() on it */ + } +} + +void CWE127_Buffer_Underread__malloc_char_cpy_45_bad() +{ + char * data; + data = NULL; + { + char * dataBuffer = (char *)malloc(100*sizeof(char)); + memset(dataBuffer, 'A', 100-1); + dataBuffer[100-1] = '\0'; + /* FLAW: Set data pointer to before the allocated memory buffer */ + data = dataBuffer - 8; + } + CWE127_Buffer_Underread__malloc_char_cpy_45_badData = data; + badSink(); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B() uses the GoodSource with the BadSink */ +static void goodG2BSink() +{ + char * data = CWE127_Buffer_Underread__malloc_char_cpy_45_goodG2BData; + { + char dest[100*2]; + memset(dest, 'C', 100*2-1); /* fill with 'C's */ + dest[100*2-1] = '\0'; /* null terminate */ + /* POTENTIAL FLAW: Possibly copy from a memory location located before the source buffer */ + strcpy(dest, data); + printLine(dest); + /* INCIDENTAL CWE-401: Memory Leak - data may not point to location + * returned by malloc() so can't safely call free() on it */ + } +} + +static void goodG2B() +{ + char * data; + data = NULL; + { + char * dataBuffer = (char *)malloc(100*sizeof(char)); + memset(dataBuffer, 'A', 100-1); + dataBuffer[100-1] = '\0'; + /* FIX: Set data pointer to the allocated memory buffer */ + data = dataBuffer; + } + CWE127_Buffer_Underread__malloc_char_cpy_45_goodG2BData = data; + goodG2BSink(); +} + +void CWE127_Buffer_Underread__malloc_char_cpy_45_good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE127_Buffer_Underread__malloc_char_cpy_45_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE127_Buffer_Underread__malloc_char_cpy_45_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard000/C/0009528_Server.c b/pool/shard000/C/0009528_Server.c new file mode 100644 index 0000000000000000000000000000000000000000..d9a42d687921227a57d58c32aee0bb6172798ac4 --- /dev/null +++ b/pool/shard000/C/0009528_Server.c @@ -0,0 +1,120 @@ + +#include +#include +#include +#include +#include + +#define PORT 8888 //端口号 +#define IP_FOUND "IP_FOUND" //IP发现命令 +#define IP_FOUND_ACK "IP_FOUND_ACK" //IP发现应答命令 + +/***** 服务器监听广播 *******************************************************************************************/ +int ServerListenBroadcast(void) +{ + int ret = -1; + int sock = -1; + int len = -1; + char buf[20]; + fd_set readfd; + struct timeval timeout; + struct sockaddr_in local_addr; //本地地址 + struct sockaddr_in from_addr; //客户端地址 + + //socket + sock = socket(AF_INET, SOCK_DGRAM, 0); + if(0 > sock) + { + perror("client socket err"); + return -1; + } + + //init local_addr + len = sizeof(struct sockaddr_in); + memset(&local_addr, 0, sizeof(struct sockaddr_in)); //清空内存内容 + local_addr.sin_family = AF_INET; //协议族 + local_addr.sin_addr.s_addr = htonl(INADDR_ANY); //本地地址 + local_addr.sin_port = htons(PORT); //监听端口 + + //bind + ret = bind(sock, (struct sockaddr *)&local_addr, sizeof(struct sockaddr_in)); + if(0 > ret) + { + perror("server1 bind err"); + goto _out; + } + + while(1) + { + //文件描述符集合清零 + FD_ZERO(&readfd); + //将套接字文件描述符加入读集合 + FD_SET(sock, &readfd); + + //超时时间 + timeout.tv_sec = 2; //秒 + timeout.tv_usec = 0; //微秒 + + //监听套接字sock是否有数据可读,超时为2秒 + ret = select(sock+1, &readfd, NULL, NULL, &timeout); + switch(ret) + { + case -1: + printf("select error!\n"); + goto _out; + case 0: + printf("time out!\n"); + break; + default: + { + //sock套接口有数据可读 + if( FD_ISSET(sock, &readfd) ) + { + //recieve + ret = recvfrom(sock, buf, sizeof(buf), 0, (struct sockaddr *)&from_addr, &len); + if(0 > ret) + { + perror("server recieve err"); + goto _out; + } + printf("buf : %s\n", buf); + + //如果与IP_FOUND吻合 + if( strstr(buf, IP_FOUND) ) + { + //send + ret = sendto(sock, IP_FOUND_ACK, strlen(IP_FOUND_ACK) + 1, 0, (struct sockaddr *)&from_addr, len); + if(0 > ret) + { + perror("server send err"); + goto _out; + } + printf("IP is %s\n", inet_ntoa(from_addr.sin_addr)); + goto _out; //退出 + } + + } + + } + } + } + + //close + close(sock); + return 0; +_out: + close(sock); + return -1; +} + + +/***** 主函数 ****************************************************************************************************/ +int main(void) +{ + if( ServerListenBroadcast() ) + { + printf(" server listen broadcast failed!\n"); + return -1; + } + return 0; +} diff --git a/pool/shard000/C/0009529_kern_xxx.c b/pool/shard000/C/0009529_kern_xxx.c new file mode 100644 index 0000000000000000000000000000000000000000..71c35c13cf79e44cb48ad5299f3dfde7fd437b4f --- /dev/null +++ b/pool/shard000/C/0009529_kern_xxx.c @@ -0,0 +1,256 @@ +/* + * Copyright (c) 1982, 1986, 1989, 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. + * + * @(#)kern_xxx.c 8.2 (Berkeley) 11/14/93 + * $Id: kern_xxx.c,v 1.28 1998/08/24 08:39:38 dfr Exp $ + */ + +#include "opt_compat.h" + +#include +#include +#include +#include +#include +#include +#include + + +#if defined(COMPAT_43) || defined(COMPAT_SUNOS) + +#ifndef _SYS_SYSPROTO_H_ +struct gethostname_args { + char *hostname; + u_int len; +}; +#endif +/* ARGSUSED */ +int +ogethostname(p, uap) + struct proc *p; + struct gethostname_args *uap; +{ + int name[2]; + size_t len = uap->len; + + name[0] = CTL_KERN; + name[1] = KERN_HOSTNAME; + return (userland_sysctl(p, name, 2, uap->hostname, &len, + 1, 0, 0, 0)); +} + +#ifndef _SYS_SYSPROTO_H_ +struct sethostname_args { + char *hostname; + u_int len; +}; +#endif +/* ARGSUSED */ +int +osethostname(p, uap) + struct proc *p; + register struct sethostname_args *uap; +{ + int name[2]; + int error; + + name[0] = CTL_KERN; + name[1] = KERN_HOSTNAME; + if ((error = suser(p->p_ucred, &p->p_acflag))) + return (error); + return (userland_sysctl(p, name, 2, 0, 0, 0, + uap->hostname, uap->len, 0)); +} + +#ifndef _SYS_SYSPROTO_H_ +struct ogethostid_args { + int dummy; +}; +#endif +/* ARGSUSED */ +int +ogethostid(p, uap) + struct proc *p; + struct ogethostid_args *uap; +{ + + *(long *)(p->p_retval) = hostid; + return (0); +} +#endif /* COMPAT_43 || COMPAT_SUNOS */ + +#ifdef COMPAT_43 +#ifndef _SYS_SYSPROTO_H_ +struct osethostid_args { + long hostid; +}; +#endif +/* ARGSUSED */ +int +osethostid(p, uap) + struct proc *p; + struct osethostid_args *uap; +{ + int error; + + if ((error = suser(p->p_ucred, &p->p_acflag))) + return (error); + hostid = uap->hostid; + return (0); +} + +int +oquota(p, uap) + struct proc *p; + struct oquota_args *uap; +{ + + return (ENOSYS); +} +#endif /* COMPAT_43 */ + +#ifndef _SYS_SYSPROTO_H_ +struct uname_args { + struct utsname *name; +}; +#endif + +/* ARGSUSED */ +int +uname(p, uap) + struct proc *p; + struct uname_args *uap; +{ + int name[2], rtval; + size_t len; + char *s, *us; + + name[0] = CTL_KERN; + name[1] = KERN_OSTYPE; + len = sizeof uap->name->sysname; + rtval = userland_sysctl(p, name, 2, uap->name->sysname, &len, + 1, 0, 0, 0); + if( rtval) return rtval; + subyte( uap->name->sysname + sizeof(uap->name->sysname) - 1, 0); + + name[1] = KERN_HOSTNAME; + len = sizeof uap->name->nodename; + rtval = userland_sysctl(p, name, 2, uap->name->nodename, &len, + 1, 0, 0, 0); + if( rtval) return rtval; + subyte( uap->name->nodename + sizeof(uap->name->nodename) - 1, 0); + + name[1] = KERN_OSRELEASE; + len = sizeof uap->name->release; + rtval = userland_sysctl(p, name, 2, uap->name->release, &len, + 1, 0, 0, 0); + if( rtval) return rtval; + subyte( uap->name->release + sizeof(uap->name->release) - 1, 0); + +/* + name = KERN_VERSION; + len = sizeof uap->name->version; + rtval = userland_sysctl(p, name, 2, uap->name->version, &len, + 1, 0, 0, 0); + if( rtval) return rtval; + subyte( uap->name->version + sizeof(uap->name->version) - 1, 0); +*/ + +/* + * this stupid hackery to make the version field look like FreeBSD 1.1 + */ + for(s = version; *s && *s != '#'; s++); + + for(us = uap->name->version; *s && *s != ':'; s++) { + rtval = subyte( us++, *s); + if( rtval) + return rtval; + } + rtval = subyte( us++, 0); + if( rtval) + return rtval; + + name[0] = CTL_HW; + name[1] = HW_MACHINE; + len = sizeof uap->name->machine; + rtval = userland_sysctl(p, name, 2, uap->name->machine, &len, + 1, 0, 0, 0); + if( rtval) return rtval; + subyte( uap->name->machine + sizeof(uap->name->machine) - 1, 0); + + return 0; +} + +#ifndef _SYS_SYSPROTO_H_ +struct getdomainname_args { + char *domainname; + int len; +}; +#endif + +/* ARGSUSED */ +int +getdomainname(p, uap) + struct proc *p; + struct getdomainname_args *uap; +{ + int domainnamelen = strlen(domainname) + 1; + if ((u_int)uap->len > domainnamelen + 1) + uap->len = domainnamelen + 1; + return (copyout((caddr_t)domainname, (caddr_t)uap->domainname, uap->len)); +} + +#ifndef _SYS_SYSPROTO_H_ +struct setdomainname_args { + char *domainname; + int len; +}; +#endif + +/* ARGSUSED */ +int +setdomainname(p, uap) + struct proc *p; + struct setdomainname_args *uap; +{ + int error, domainnamelen; + + if ((error = suser(p->p_ucred, &p->p_acflag))) + return (error); + if ((u_int)uap->len > sizeof (domainname) - 1) + return EINVAL; + domainnamelen = uap->len; + error = copyin((caddr_t)uap->domainname, domainname, uap->len); + domainname[domainnamelen] = 0; + return (error); +} + diff --git a/pool/shard000/C/0009539_test_parser_terminal.c b/pool/shard000/C/0009539_test_parser_terminal.c new file mode 100644 index 0000000000000000000000000000000000000000..985753f18d4e662ca8c38813d2b0017ee2a7a232 --- /dev/null +++ b/pool/shard000/C/0009539_test_parser_terminal.c @@ -0,0 +1,34 @@ +#include "test_parser_p.h" + +void terminal_success(void **state) { + grammar_t *grammar = grammar_init( + non_terminal("HelloWorld"), + rule_init("HelloWorld", + terminal("hello world") + ), 1 + ); + + parse_result_t *result = parse("hello world", grammar); + assert_non_null(result); + assert_true(is_success(result)); + + parse_t *suc = result->data.result; + assert_int_equal(suc->length, 11); + assert_int_equal(suc->start, 0); + + assert_int_equal(suc->n_children, 1); + assert_int_equal(suc->children[0].n_children, 0); +} + +void terminal_failure(void **state) { + grammar_t *grammar = grammar_init( + non_terminal("HelloWorld"), + rule_init("HelloWorld", + terminal("hello world") + ), 1 + ); + + parse_result_t *result = parse("nope", grammar); + assert_non_null(result); + assert_true(is_error(result)); +} diff --git a/pool/shard000/C/0009546_res_pjsip_send_to_voicemail.c b/pool/shard000/C/0009546_res_pjsip_send_to_voicemail.c new file mode 100644 index 0000000000000000000000000000000000000000..f7734c94d98bce216065fc1ad0469fdb0b177c32 --- /dev/null +++ b/pool/shard000/C/0009546_res_pjsip_send_to_voicemail.c @@ -0,0 +1,230 @@ +/* + * Asterisk -- An open source telephony toolkit. + * + * Copyright (C) 2013, Digium, Inc. + * + * Jonathan Rose + * + * See http://www.asterisk.org for more information about + * the Asterisk project. Please do not directly contact + * any of the maintainers of this project for assistance; + * the project provides a web site, mailing lists and IRC + * channels for your use. + * + * This program is free software, distributed under the terms of + * the GNU General Public License Version 2. See the LICENSE file + * at the top of the source tree. + */ + +/*! \file + * + * \brief Module for managing send to voicemail requests in SIP + * REFER messages against PJSIP channels + * + * \author Jonathan Rose + */ + +/*** MODULEINFO + pjproject + res_pjsip + res_pjsip_session + core +***/ + +#include "asterisk.h" + +#include +#include + +#include "asterisk/pbx.h" +#include "asterisk/res_pjsip.h" +#include "asterisk/res_pjsip_session.h" +#include "asterisk/module.h" + +#define DATASTORE_NAME "call_feature_send_to_vm_datastore" + +#define SEND_TO_VM_HEADER "PJSIP_HEADER(add,X-Digium-Call-Feature)" +#define SEND_TO_VM_HEADER_VALUE "feature_send_to_vm" + +#define SEND_TO_VM_REDIRECT "REDIRECTING(reason)" +#define SEND_TO_VM_REDIRECT_VALUE "\"send_to_vm\"" + +static void send_response(struct ast_sip_session *session, int code, struct pjsip_rx_data *rdata) +{ + pjsip_tx_data *tdata; + + if (pjsip_dlg_create_response(session->inv_session->dlg, rdata, code, NULL, &tdata) == PJ_SUCCESS) { + struct pjsip_transaction *tsx = pjsip_rdata_get_tsx(rdata); + + pjsip_dlg_send_response(session->inv_session->dlg, tsx, tdata); + } +} + +static void channel_cleanup_wrapper(void *data) +{ + struct ast_channel *chan = data; + ast_channel_cleanup(chan); +} + +static struct ast_datastore_info call_feature_info = { + .type = "REFER call feature info", + .destroy = channel_cleanup_wrapper, +}; + +static pjsip_param *get_diversion_reason(pjsip_fromto_hdr *hdr) +{ + static const pj_str_t reason_str = { "reason", 6 }; + return pjsip_param_find(&hdr->other_param, &reason_str); +} + +static pjsip_fromto_hdr *get_diversion_header(pjsip_rx_data *rdata) +{ + static const pj_str_t from_str = { "From", 4 }; + static const pj_str_t diversion_str = { "Diversion", 9 }; + + pjsip_generic_string_hdr *hdr; + pj_str_t value; + + if (!(hdr = pjsip_msg_find_hdr_by_name( + rdata->msg_info.msg, &diversion_str, NULL))) { + return NULL; + } + + pj_strdup_with_null(rdata->tp_info.pool, &value, &hdr->hvalue); + + /* parse as a fromto header */ + return pjsip_parse_hdr(rdata->tp_info.pool, &from_str, value.ptr, + pj_strlen(&value), NULL); +} + +static int has_diversion_reason(pjsip_rx_data *rdata) +{ + pjsip_param *reason; + pjsip_fromto_hdr *hdr = get_diversion_header(rdata); + + return hdr && + (reason = get_diversion_reason(hdr)) && + !pj_stricmp2(&reason->value, SEND_TO_VM_REDIRECT_VALUE); +} + +static int has_call_feature(pjsip_rx_data *rdata) +{ + static const pj_str_t call_feature_str = { "X-Digium-Call-Feature", 21 }; + + pjsip_generic_string_hdr *hdr = pjsip_msg_find_hdr_by_name( + rdata->msg_info.msg, &call_feature_str, NULL); + + return hdr && !pj_stricmp2(&hdr->hvalue, SEND_TO_VM_HEADER_VALUE); +} + +static int handle_incoming_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata) +{ + + struct ast_datastore *sip_session_datastore; + struct ast_channel *other_party; + + int has_feature = has_call_feature(rdata); + int has_reason = has_diversion_reason(rdata); + + if (!has_feature && !has_reason) { + /* If we don't have a call feature or diversion reason or if + it's not a feature this module is related to then there + is nothing to do. */ + return 0; + } + + /* Check bridge status... */ + other_party = ast_channel_bridge_peer(session->channel); + if (!other_party) { + /* The channel wasn't in a two party bridge */ + ast_log(LOG_WARNING, "%s (%s) attempted to transfer to voicemail, " + "but was not in a two party bridge.\n", + ast_sorcery_object_get_id(session->endpoint), + ast_channel_name(session->channel)); + send_response(session, 400, rdata); + return -1; + } + + sip_session_datastore = ast_sip_session_alloc_datastore( + &call_feature_info, DATASTORE_NAME); + if (!sip_session_datastore) { + ast_channel_unref(other_party); + send_response(session, 500, rdata); + return -1; + } + + sip_session_datastore->data = other_party; + + if (ast_sip_session_add_datastore(session, sip_session_datastore)) { + ast_channel_unref(other_party); + ao2_ref(sip_session_datastore, -1); + send_response(session, 500, rdata); + return -1; + } + ao2_ref(sip_session_datastore, -1); + + if (has_feature) { + pbx_builtin_setvar_helper(other_party, SEND_TO_VM_HEADER, + SEND_TO_VM_HEADER_VALUE); + } + + if (has_reason) { + pbx_builtin_setvar_helper(other_party, SEND_TO_VM_REDIRECT, + SEND_TO_VM_REDIRECT_VALUE); + } + + return 0; +} + +static void handle_outgoing_response(struct ast_sip_session *session, struct pjsip_tx_data *tdata) +{ + pjsip_status_line status = tdata->msg->line.status; + struct ast_datastore *feature_datastore = + ast_sip_session_get_datastore(session, DATASTORE_NAME); + struct ast_channel *target_chan; + + if (!feature_datastore) { + return; + } + + /* Since we are handling the response, there is no need to keep the datastore in the session anymore. */ + ast_sip_session_remove_datastore(session, DATASTORE_NAME); + + /* If the response >= 300, the refer failed and we need to clear the feature. */ + if (status.code >= 300) { + target_chan = feature_datastore->data; + pbx_builtin_setvar_helper(target_chan, SEND_TO_VM_HEADER, NULL); + pbx_builtin_setvar_helper(target_chan, SEND_TO_VM_REDIRECT, NULL); + } + ao2_ref(feature_datastore, -1); +} + +static struct ast_sip_session_supplement refer_supplement = { + .method = "REFER", + .incoming_request = handle_incoming_request, + .outgoing_response = handle_outgoing_response, +}; + +static int load_module(void) +{ + CHECK_PJSIP_SESSION_MODULE_LOADED(); + + if (ast_sip_session_register_supplement(&refer_supplement)) { + ast_log(LOG_ERROR, "Unable to register Send to Voicemail supplement\n"); + return AST_MODULE_LOAD_FAILURE; + } + + return AST_MODULE_LOAD_SUCCESS; +} + +static int unload_module(void) +{ + ast_sip_session_unregister_supplement(&refer_supplement); + return 0; +} + +AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP REFER Send to Voicemail Support", + .load = load_module, + .unload = unload_module, + .load_pri = AST_MODPRI_APP_DEPEND, + ); diff --git a/pool/shard000/C/0009550_convert-format.c b/pool/shard000/C/0009550_convert-format.c new file mode 100644 index 0000000000000000000000000000000000000000..fabeb436a71c0ad52b1991e8261ec5b4fa067ff5 --- /dev/null +++ b/pool/shard000/C/0009550_convert-format.c @@ -0,0 +1,105 @@ +/* This file is an image processing operation for GEGL + * + * GEGL is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * GEGL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GEGL; if not, see . + * + * Copyright 2007 Étienne Bersac + * Copyright 2006 Øyvind Kolås + * Copyright 2013 Daniel Sabo + * + */ + +#include "config.h" +#include + +#ifdef GEGL_PROPERTIES + +property_format (format, _("Output format"), NULL) + description(_("The babl format of the output")) + +#else + +#define GEGL_OP_FILTER +#define GEGL_OP_NAME convert_format +#define GEGL_OP_C_SOURCE convert-format.c + +#include "gegl-op.h" + +static void +prepare (GeglOperation *self) +{ + GeglProperties *o = GEGL_PROPERTIES (self); + + if (o->format) + gegl_operation_set_format (self, "output", o->format); + else + gegl_operation_set_format (self, "output", gegl_operation_get_source_format (self, "input")); +} + +static gboolean +operation_process (GeglOperation *operation, + GeglOperationContext *context, + const gchar *output_prop, + const GeglRectangle *roi, + gint level) +{ + GeglProperties *o = GEGL_PROPERTIES (operation); + GeglBuffer *input; + + input = (GeglBuffer*) gegl_operation_context_get_object (context, "input"); + + if (! o->format || gegl_buffer_get_format (input) == o->format) + { + gegl_operation_context_set_object (context, "output", G_OBJECT (input)); + + return TRUE; + } + + return GEGL_OPERATION_CLASS (gegl_op_parent_class)->process (operation, + context, + output_prop, + roi, level); +} + +static gboolean +process (GeglOperation *operation, + GeglBuffer *input, + GeglBuffer *output, + const GeglRectangle *roi, + gint level) +{ + gegl_buffer_copy (input, roi, GEGL_ABYSS_NONE, output, roi); + + return TRUE; +} + +static void +gegl_op_class_init (GeglOpClass *klass) +{ + GeglOperationClass *operation_class = GEGL_OPERATION_CLASS (klass); + GeglOperationFilterClass *filter_class = GEGL_OPERATION_FILTER_CLASS (klass); + + operation_class->prepare = prepare; + operation_class->process = operation_process; + + filter_class->process = process; + + gegl_operation_class_set_keys (operation_class, + "name", "gegl:convert-format", + "title", _("Convert Format"), + "categories", "core:color", + "description", _("Convert the data to the specified format"), + NULL); +} + +#endif diff --git a/pool/shard000/C/0009573_disk.c b/pool/shard000/C/0009573_disk.c new file mode 100644 index 0000000000000000000000000000000000000000..5d175b3c9d2ab70d104a8a9d1e82f6eb0e6a6aec --- /dev/null +++ b/pool/shard000/C/0009573_disk.c @@ -0,0 +1,261 @@ +/* + * Copyright (c) 2004 Silicon Graphics, Inc. All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * for more details. + */ + +#include +#define IOKIT 1 +#include +#include +#include +#include +#include +#include + +#include "pmapi.h" +#include "impl.h" +#include "pmda.h" + +#include "disk.h" + +/* + * Ensure we have space for the next device in our pre-allocated + * device pool. If not, make some or pass on the error. + */ +static int +check_stats_size(struct diskstats *stats, int count) +{ + if (count > stats->highwater) { + stats->highwater++; + stats->disks = realloc(stats->disks, + stats->highwater * sizeof(struct diskstat)); + if (!stats->disks) { + stats->highwater = 0; + return -ENOMEM; + } + } + return 0; +} + +/* + * Insert all disks into the global disk instance domain. + */ +static int +update_disk_indom(struct diskstats *all, int count, pmdaIndom *indom) +{ + int i; + + if (count > 0 && count != indom->it_numinst) { + i = sizeof(pmdaInstid) * count; + if ((indom->it_set = realloc(indom->it_set, i)) == NULL) { + indom->it_numinst = 0; + return -ENOMEM; + } + } + for (i = 0; i < count; i++) { + indom->it_set[i].i_name = all->disks[i].name; + indom->it_set[i].i_inst = i; + } + indom->it_numinst = count; + return 0; +} + +/* + * Update the global counters with values from one disk. + */ +static void +update_disk_totals(struct diskstats *all, struct diskstat *disk) +{ + all->read += disk->read; + all->write += disk->write; + all->read_bytes += disk->read_bytes; + all->write_bytes += disk->write_bytes; + all->blkread += disk->read_bytes / disk->blocksize; + all->blkwrite += disk->write_bytes / disk->blocksize; + all->read_time += disk->read_time; + all->write_time += disk->write_time; +} + +static void +clear_disk_totals(struct diskstats *all) +{ + all->read = 0; + all->write = 0; + all->read_bytes = 0; + all->write_bytes = 0; + all->blkread = 0; + all->blkwrite = 0; + all->read_time = 0; + all->write_time = 0; +} + +/* + * Update the counters associated with a single disk. + */ +static void +update_disk_stats(struct diskstat *disk, + CFDictionaryRef pproperties, CFDictionaryRef properties) +{ + CFDictionaryRef statistics; + CFStringRef name; + CFNumberRef number; + + memset(disk, 0, sizeof(struct diskstat)); + + /* Get name from the drive properties */ + name = (CFStringRef) CFDictionaryGetValue(pproperties, + CFSTR(kIOBSDNameKey)); + if(name == NULL) + return; /* Not much we can do with no name */ + + CFStringGetCString(name, disk->name, DEVNAMEMAX, + CFStringGetSystemEncoding()); + + /* Get the blocksize from the drive properties */ + number = (CFNumberRef) CFDictionaryGetValue(pproperties, + CFSTR(kIOMediaPreferredBlockSizeKey)); + if(number == NULL) + return; /* Not much we can do with no number */ + CFNumberGetValue(number, kCFNumberSInt64Type, &disk->blocksize); + + /* Get the statistics from the device properties. */ + statistics = (CFDictionaryRef) CFDictionaryGetValue(properties, + CFSTR(kIOBlockStorageDriverStatisticsKey)); + if (statistics) { + number = (CFNumberRef) CFDictionaryGetValue(statistics, + CFSTR(kIOBlockStorageDriverStatisticsReadsKey)); + if (number) + CFNumberGetValue(number, kCFNumberSInt64Type, + &disk->read); + number = (CFNumberRef) CFDictionaryGetValue(statistics, + CFSTR(kIOBlockStorageDriverStatisticsWritesKey)); + if (number) + CFNumberGetValue(number, kCFNumberSInt64Type, + &disk->write); + number = (CFNumberRef) CFDictionaryGetValue(statistics, + CFSTR(kIOBlockStorageDriverStatisticsBytesReadKey)); + if (number) + CFNumberGetValue(number, kCFNumberSInt64Type, + &disk->read_bytes); + number = (CFNumberRef) CFDictionaryGetValue(statistics, + CFSTR(kIOBlockStorageDriverStatisticsBytesWrittenKey)); + if (number) + CFNumberGetValue(number, kCFNumberSInt64Type, + &disk->write_bytes); + number = (CFNumberRef) CFDictionaryGetValue(statistics, + CFSTR(kIOBlockStorageDriverStatisticsLatentReadTimeKey)); + if (number) + CFNumberGetValue(number, kCFNumberSInt64Type, + &disk->read_time); + number = (CFNumberRef) CFDictionaryGetValue(statistics, + CFSTR(kIOBlockStorageDriverStatisticsLatentWriteTimeKey)); + if (number) + CFNumberGetValue(number, kCFNumberSInt64Type, + &disk->write_time); + } +} + +static int +update_disk(diskstats_t *stats, io_registry_entry_t drive, int index) +{ + io_registry_entry_t device; + CFDictionaryRef pproperties, properties; + int status; + + /* Get the drives parent, from which we get statistics. */ + status = IORegistryEntryGetParentEntry(drive, kIOServicePlane, &device); + if (status != KERN_SUCCESS) + return -oserror(); + + if (!IOObjectConformsTo(device, "IOBlockStorageDriver")) { + IOObjectRelease(device); + return 0; + } + + /* Obtain the drive properties. */ + pproperties = 0; + status = IORegistryEntryCreateCFProperties(drive, + (CFMutableDictionaryRef *)&pproperties, + kCFAllocatorDefault, kNilOptions); + if (status != KERN_SUCCESS) { + IOObjectRelease(device); + return -oserror(); + } + + /* Obtain the device properties. */ + properties = 0; + status = IORegistryEntryCreateCFProperties(device, + (CFMutableDictionaryRef *)&properties, + kCFAllocatorDefault, kNilOptions); + if (status != KERN_SUCCESS) { + IOObjectRelease(device); + return -oserror(); + } + + /* Make space to store the actual values, then go get them. */ + status = check_stats_size(stats, index + 1); + if (status < 0) { + IOObjectRelease(device); + } else { + update_disk_stats(&stats->disks[index], pproperties, properties); + update_disk_totals(stats, &stats->disks[index]); + } + CFRelease(pproperties); + CFRelease(properties); + return status; +} + +int +refresh_disks(struct diskstats *stats, pmdaIndom *indom) +{ + io_registry_entry_t drive; + CFMutableDictionaryRef match; + int i, status; + static int inited = 0; + static mach_port_t mach_master_port; + static io_iterator_t mach_device_list; + + if (!inited) { + /* Get ports and services for device statistics. */ + if (IOMasterPort(bootstrap_port, &mach_master_port)) { + fprintf(stderr, "%s: IOMasterPort error\n", __FUNCTION__); + return -oserror(); + } + memset(stats, 0, sizeof(struct diskstats)); + inited = 1; + } + + /* Get an interator for IOMedia objects (drives). */ + match = IOServiceMatching("IOMedia"); + CFDictionaryAddValue(match, CFSTR(kIOMediaWholeKey), kCFBooleanTrue); + status = IOServiceGetMatchingServices(mach_master_port, + match, &mach_device_list); + if (status != KERN_SUCCESS) { + fprintf(stderr, "%s: IOServiceGetMatchingServices error\n", + __FUNCTION__); + return -oserror(); + } + + indom->it_numinst = 0; + clear_disk_totals(stats); + for (i = 0; (drive = IOIteratorNext(mach_device_list)) != 0; i++) { + status = update_disk(stats, drive, i); + if (status) + break; + IOObjectRelease(drive); + } + IOIteratorReset(mach_device_list); + + if (!status) + status = update_disk_indom(stats, i, indom); + return status; +} diff --git a/pool/shard000/C/0009576_main.c b/pool/shard000/C/0009576_main.c new file mode 100644 index 0000000000000000000000000000000000000000..ad5d8c1520b717451ccfe2c69480e91c2c687b7e --- /dev/null +++ b/pool/shard000/C/0009576_main.c @@ -0,0 +1,187 @@ +/* + * KubOS Linux + * Copyright (C) 2017 Kubos Corporation + * + * 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. + * + * UART Communication Demo Code - Receiver + * + */ + +#include +#include +#include +#include +#include +#include +#include + +struct sigaction saio; + +int running; +int fd; + +int uart_init(void) +{ + char * device = "/dev/ttyS1"; + speed_t speed = B115200; + struct termios tty; + + /* + * Open UART (terminal) + * O_RDONLY - Read only + * O_NOCTTY - This terminal should not be the controlling terminal of the + * process (that should still be the debug UART) + * O_NDELAY - Open file in non-blocking mode + * O_ASYNC - Enable SIGIO generation when data is received + */ + fd = open(device, O_RDONLY | O_NOCTTY | O_NDELAY | O_ASYNC); + if (fd < 0) + { + perror("** Error opening device"); + return -1; + } + + /* Set this process as the PID that should receive the SIGIO signals on + * this file */ + fcntl(fd, F_SETOWN, getpid()); + + /* + * Get the current terminal settings. There are a bunch, and we only want + * to update a few, so we'll preserve everything else that's currently + * set. + */ + if (tcgetattr(fd, &tty) < 0) + { + perror("Error from tcgetattr"); + return -1; + } + + /* Set input baudrate */ + cfsetispeed(&tty, speed); + + /* Character processing flags */ + tty.c_cflag |= (CLOCAL | CREAD); /* Ignore modem controls */ + tty.c_cflag &= ~CSIZE; /* Clear current char size mask */ + tty.c_cflag |= CS8; /* 8-bit characters */ + tty.c_cflag &= ~PARENB; /* No parity bit */ + tty.c_cflag &= ~CSTOPB; /* 1 stop bit */ + tty.c_cflag &= ~CRTSCTS; /* No hardware flowcontrol */ + + /* Input flags */ + tty.c_iflag &= ~(IGNBRK | /* Don't ignore BREAK conditions */ + BRKINT | /* Read BREAKs as null bytes */ + ICRNL | /* Do not translate carriage returns */ + INLCR | /* Do not translate NL to CR */ + PARMRK | /* Do not mark errors */ + INPCK | /* Turn off parity checking */ + ISTRIP | /* Do not strip off eighth bit */ + IXON); /* Turn off flow control */ + + tty.c_lflag &= ~ICANON | ECHO; /* Non-canonical (raw) input */ + + tty.c_cc[VMIN] = 18; /* We know that we're looking for an 18 byte message + "Test message nnn" */ + tty.c_cc[VTIME] = 2; /* But give a 2/10th second timeout in case something + goes wrong mid-read */ + + /* Clear anything that's currently in the UART buffers */ + tcflush(fd, TCIOFLUSH); + + /* Update the terminal settings */ + if (tcsetattr(fd, TCSANOW, &tty) != 0) + { + perror("Error from tcsetattr"); + return -1; + } + + return 0; +} + +int uart_close(void) +{ + close(fd); +} + +static char uart_buf[256]; + +int uart_read(void) +{ + + int rdlen; + + /* Make sure the buffer is cleared from the last time we read */ + memset(uart_buf, 0, sizeof(uart_buf)); + + /* Read as much data as is available */ + rdlen = read(fd, uart_buf, sizeof(uart_buf) - 1); + + if (rdlen < 0) + { + perror("Error from read"); + + return -1; + } + + printf("Received(%d): %s\n", rdlen, uart_buf); + + return 0; +} + +void sigio_handler(int sig) +{ + printf("Received data from UART\n"); + uart_read(); +} + +void sigint_handler(int sig) +{ + running = 0; + sleep(2); + signal(SIGINT, SIG_DFL); + kill(getpid(), SIGINT); +} + +int main(int argc, char * argv[]) +{ + + int opt; + + running = 1; + + /* Ctrl+C will trigger a signal to end the program */ + signal(SIGINT, sigint_handler); + + saio.sa_handler = sigio_handler; + saio.sa_flags = 0; + saio.sa_restorer = NULL; + + /* The UART bus receiving data will trigger an I/O interrupt */ + sigaction(SIGIO, &saio, NULL); + + /* Open connection to transmitter */ + uart_init(); + + while (running) + { + + /* Need while loop to keep app running while waiting for messages from + * master */ + sleep(1); + } + + /* Cleanup */ + uart_close(); + + return 0; +} diff --git a/pool/shard000/C/0009578_strndup.c b/pool/shard000/C/0009578_strndup.c new file mode 100644 index 0000000000000000000000000000000000000000..6bff9a64453928437e696e12641f291edc82f6b6 --- /dev/null +++ b/pool/shard000/C/0009578_strndup.c @@ -0,0 +1,40 @@ +/* compatibility file for systems without strndup. + * + * Copyright 2015 Rainer Gerhards and Adiscon + * + * This file is part of liblognorm. + * + * 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 + * -or- + * see COPYING.ASL20 in the source distribution + * + * 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 "config.h" +#ifndef HAVE_STRNDUP + +#include +#include +char * +strndup(const char *s, size_t n) +{ + const size_t len = strlen(s); + if(len <= n) + return strdup(s); + char *const new_s = malloc(len+1); + if(new_s == NULL) + return NULL; + memcpy(new_s, s, len); + new_s[len] = '\0'; + return new_s; +} + +#endif /* #ifndef HAVE_STRNDUP */ diff --git a/pool/shard000/C/0009583_radius.c b/pool/shard000/C/0009583_radius.c new file mode 100644 index 0000000000000000000000000000000000000000..02078e41fbfcc83d68eaf3b9ad284e513f8e4179 --- /dev/null +++ b/pool/shard000/C/0009583_radius.c @@ -0,0 +1,146 @@ +/** + * @file GMX46/radius.c + * @brief Definition of routines for radius types + * @ingroup RADIUS + * @author Rashmi Kumari, Rajendra Kumar and Andrew Lynn + * @attention + * @verbatim + * + * + * This file is part of g_mmpbsa. + * + * Authors: Rashmi Kumari and Andrew Lynn + * Contribution: Rajendra Kumar + * + * Copyright (C) 2013-2016 Rashmi Kumari and Andrew Lynn + * + * g_mmpbsa 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. + * + * g_mmpbsa 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 g_mmpbsa. If not, see . + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * + * @endverbatim + * + */ + +#include +#include +#include + +#include "g_mmpbsa.h" + +void substring(int start, int stop, const char *src, char *dest) +{ + sprintf(dest,"%.*s", stop - start, &src[start]); +} + +void Bondi(t_AtomProp *bondi) { + int i =0; + char *atomtype[] = {"O", "o", "S","s", "N", "n", "C", "c", "H", "h", "P", "p", "F", "f", + "I", "i", "CL", "cl", "Cl", "Br", "BR", "br", "CA", "CB", "CC", "CN", + "CR", "CV", "CW", "C*", "cd", "cc", "ca", "HA", "H4", "H5", "ha", "h4", "h5"}; + real radius[] = {1.520, 1.520, 1.830, 1.830, 1.550, 1.550, 1.700, 1.700, 1.200, 1.200, 1.800, 1.800, 1.470, 1.470, + 2.060, 2.060, 1.770, 1.770, 1.770, 1.920, 1.920, 1.20, 1.770, 1.770, 1.770, 1.770, + 1.770, 1.770, 1.770, 1.770, 1.770, 1.770, 1.770, 1.000, 1.000, 1.000, 1.000, 1.000, 1.00}; + bondi->n = 38; + bondi->atomtype = (char**) malloc(sizeof(char*)*(bondi->n+1)); + bondi->value = (real*) malloc(sizeof(real)*(bondi->n+1)); + + for(i=0;i<=bondi->n;i++) { + bondi->atomtype[i] = (char*) malloc(sizeof(atomtype[i])); + sprintf(bondi->atomtype[i],"%s",atomtype[i]); + bondi->value[i] = radius[i]; + } +} + +void mBondi(t_AtomProp *mbondi) { + int i=0; + char *atomtype[] ={ "O", "o", "S", "s", "N", "n", "C", "c", "H", "h", "P", "p", "F", "f", "I", "i", + "CL", "Cl", "cl", "BR", "Br", "br", "HC", "CA", "CB", "CC", "CN", "CR", "CV", + "CW", "C*", "cd", "cc", "ca", "HA", "H4", "H5", "ha", "h4", "h5", "hc", "HN", + "hn", "HO", "ho", "HS", "hs", "HP", "hp"}; + real radius[] = {1.500,1.5000,1.800,1.800,1.550,1.550,1.700,1.700,1.200,1.200,1.850,1.850,1.470,1.470,1.980,1.980, + 1.770,1.770,1.770,1.850,1.850,1.850,1.300,1.770,1.770,1.770,1.770,1.770,1.770, + 1.770,1.770,1.770,1.770,1.770,1.000,1.000,1.000,1.000,1.000,1.000,1.30,1.30, + 1.300,0.80,0.80,0.80,0.80,1.30,1.30}; + mbondi->n = 48; + mbondi->atomtype = (char**) malloc(sizeof(char*)*(mbondi->n+1)); + mbondi->value = (real*) malloc(sizeof(real)*(mbondi->n+1)); + + for(i=0;i<=mbondi->n;i++) { + mbondi->atomtype[i] = (char*) malloc(sizeof(atomtype[i])); + sprintf(mbondi->atomtype[i],"%s",atomtype[i]); + mbondi->value[i] = radius[i]; + } +} + +void mBondi2 (t_AtomProp *mbondi2) { + int i =0; + char *atomtype[] = {"O", "o", "S", "s", "N", "n", "C", "c", "H", "h", "P", "p", "F", "I", "f", "i", + "CL", "cl", "Cl", "BR", "br", "Br", "HC", "hc", "HN", "hn", "HO", "ho", "HS", + "hs", "HP", "hp"}; + real radius[] = {1.500, 1.500, 1.800, 1.800, 1.550, 1.550, 1.700, 1.700, 1.200, 1.200, 1.850, 1.850, 1.470, 1.980, 1.470, 1.980, + 1.770, 1.770, 1.770, 1.850, 1.850, 1.850, 1.300, 1.300, 1.300, 1.300, 0.800, 0.800, 0.800, + 0.800, 1.300, 1.300}; + mbondi2->n = 31; + mbondi2->atomtype = (char**) malloc(sizeof(char*)*(mbondi2->n+1)); + mbondi2->value = (real*) malloc(sizeof(real)*(mbondi2->n+1)); + + for(i=0;i<=mbondi2->n;i++) { + mbondi2->atomtype[i] = (char*) malloc(sizeof(atomtype[i])); + sprintf(mbondi2->atomtype[i],"%s",atomtype[i]); + mbondi2->value[i] = radius[i]; + } +} + +real GetRad (char *atomtype, t_AtomProp *radtype, real rvdw) { + char a[2], b[3]; + int i =0, done=0; + real r =0; + + substring(0,1, atomtype,a); + for(i=0;i<=radtype->n;i++) { + if(strcmp(a,radtype->atomtype[i])==0) { + r = radtype->value[i]; + done=1; + } + } + + if(atomtype[1]) { + substring(0,2, atomtype,b); + for(i=0;i<=radtype->n;i++) { + if(strcmp(b,radtype->atomtype[i])==0) { + r = radtype->value[i]; + done = 1; + } + } + } + + if(done==0) { + printf("\nWARNING: Radius for atomtype \"%s\" not found. Assigning radius to %3.2lf \n",atomtype,rvdw); + return rvdw; + } + else + return r; +} diff --git a/pool/shard000/C/0009586_aoemask.c b/pool/shard000/C/0009586_aoemask.c new file mode 100644 index 0000000000000000000000000000000000000000..655cf32668fe4c554c862d34d2f5875dc47f20a6 --- /dev/null +++ b/pool/shard000/C/0009586_aoemask.c @@ -0,0 +1,131 @@ +/* + * This file is part of the UCB release of Plan 9. It is subject to the license + * terms in the LICENSE file found in the top-level directory of this + * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No + * part of the UCB release of Plan 9, including this file, may be copied, + * modified, propagated, or distributed except according to the terms contained + * in the LICENSE file. + */ + +#include +#include +#include +#include "dat.h" +#include "protos.h" + +typedef struct { + uchar res; + uchar cmd; + uchar err; + uchar cnt; +} Hdr; + +enum { + Ocmd, + Oerr, + Ocnt, + + Hsize = 4, +}; + +static Field p_fields[] = +{ + { "cmd", Fnum, Ocmd, "command", }, + { "err", Fnum, Oerr, "error", }, + { "cnt", Fnum, Ocnt, "count", }, + nil +}; + +static Mux p_mux[] = { + { "aoemd", 0 }, + { "aoemd", 1 }, + nil +}; + +static void +p_compile(Filter *f) +{ + Mux *m; + + if(f->op == '='){ + compile_cmp(aoerr.name, f, p_fields); + return; + } + for(m = p_mux; m->name; m++) + if(strcmp(f->s, m->name) == 0){ + f->pr = m->pr; + f->ulv = m->val; + f->subop = Ocmd; + return; + } + sysfatal("unknown aoemask field: %s", f->s); +} + +static int +p_filter(Filter *f, Msg *m) +{ + Hdr *h; + + if(m->pe - m->ps < Hsize) + return 0; + + h = (Hdr*)m->ps; + m->ps += Hsize; + + switch(f->subop){ + case Ocmd: + return h->cmd == f->ulv; + case Oerr: + return h->err == f->ulv; + case Ocnt: + return h->cnt == f->ulv; + } + return 0; +} + +static char *ctab[] = { + "read", + "edit", +}; + +static char *etab[] = { + "", + "bad", + "full", +}; + +static int +p_seprint(Msg *m) +{ + char *s, *t; + Hdr *h; + + if(m->pe - m->ps < Hsize) + return 0; + + h = (Hdr*)m->ps; + m->ps += Hsize; + + demux(p_mux, h->cmd, h->cmd, m, &dump); + + s = "unk"; + if(h->cmd < nelem(ctab)) + s = ctab[h->cmd]; + t = "unk"; + if(h->err < nelem(etab)) + s = etab[h->err]; + m->p = seprint(m->p, m->e, "cmd=%d %s err=%d %s cnt=%d\n", + h->cmd, s, h->err, t, h->cnt); + return 0; +} + +Proto aoemask = { + "aoemask", + p_compile, + p_filter, + p_seprint, + p_mux, + "%lud", + p_fields, + defaultframer, +}; diff --git a/pool/shard000/C/0009618_osrf_cache.c b/pool/shard000/C/0009618_osrf_cache.c new file mode 100644 index 0000000000000000000000000000000000000000..c19354a5cba3278887f25d7840c2c265e731b3d1 --- /dev/null +++ b/pool/shard000/C/0009618_osrf_cache.c @@ -0,0 +1,143 @@ +/* +Copyright (C) 2005 Georgia Public Library Service +Bill Erickson + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. +*/ + +#include + +static struct memcached_st* _osrfCache = NULL; +static time_t _osrfCacheMaxSeconds = -1; + +int osrfCacheInit( const char* serverStrings[], int size, time_t maxCacheSeconds ) { + memcached_server_st *server_pool; + memcached_return rc; + + if( !(serverStrings && size > 0) ) return -1; + osrfCacheCleanup(); /* in case we've already been init-ed */ + + int i; + _osrfCache = memcached_create(NULL); + _osrfCacheMaxSeconds = maxCacheSeconds; + + for( i = 0; i < size && serverStrings[i]; i++ ) { + /* TODO: modify caller to pass a list of servers all at once */ + server_pool = memcached_servers_parse(serverStrings[i]); + rc = memcached_server_push(_osrfCache, server_pool); + if (rc != MEMCACHED_SUCCESS) { + osrfLogError(OSRF_LOG_MARK, + "Failed to add memcached server: %s - %s", + serverStrings[i], memcached_strerror(_osrfCache, rc)); + } + } + + return 0; +} + +int osrfCachePutObject( char* key, const jsonObject* obj, time_t seconds ) { + if( !(key && obj) ) return -1; + char* s = jsonObjectToJSON( obj ); + osrfLogInternal( OSRF_LOG_MARK, "osrfCachePut(): Putting object (key=%s): %s", key, s); + osrfCachePutString(key, s, seconds); + free(s); + return 0; +} + +int osrfCachePutString( char* key, const char* value, time_t seconds ) { + memcached_return rc; + if( !(key && value) ) return -1; + seconds = (seconds <= 0 || seconds > _osrfCacheMaxSeconds) ? _osrfCacheMaxSeconds : seconds; + osrfLogInternal( OSRF_LOG_MARK, "osrfCachePutString(): Putting string (key=%s): %s", key, value); + /* add or overwrite existing key:value pair */ + rc = memcached_set(_osrfCache, key, strlen(key), value, strlen(value), seconds, 0); + if (rc != MEMCACHED_SUCCESS) { + osrfLogError(OSRF_LOG_MARK, "Failed to cache key:value [%s]:[%s] - %s", + key, value, memcached_strerror(_osrfCache, rc)); + } + return 0; +} + +jsonObject* osrfCacheGetObject( const char* key, ... ) { + size_t val_len; + uint32_t flags; + memcached_return rc; + jsonObject* obj = NULL; + if( key ) { + VA_LIST_TO_STRING(key); + const char* data = (const char*) memcached_get(_osrfCache, VA_BUF, strlen(VA_BUF), &val_len, &flags, &rc); + if (rc != MEMCACHED_SUCCESS) { + osrfLogDebug(OSRF_LOG_MARK, "Failed to get key [%s] - %s", + VA_BUF, memcached_strerror(_osrfCache, rc)); + } + if( data ) { + osrfLogInternal( OSRF_LOG_MARK, "osrfCacheGetObject(): Returning object (key=%s): %s", VA_BUF, data); + obj = jsonParse( data ); + return obj; + } + osrfLogDebug(OSRF_LOG_MARK, "No cache data exists with key %s", VA_BUF); + } + return NULL; +} + +char* osrfCacheGetString( const char* key, ... ) { + size_t val_len; + uint32_t flags; + memcached_return rc; + if( key ) { + VA_LIST_TO_STRING(key); + char* data = (char*) memcached_get(_osrfCache, VA_BUF, strlen(VA_BUF), &val_len, &flags, &rc); + if (rc != MEMCACHED_SUCCESS) { + osrfLogDebug(OSRF_LOG_MARK, "Failed to get key [%s] - %s", + VA_BUF, memcached_strerror(_osrfCache, rc)); + } + osrfLogInternal( OSRF_LOG_MARK, "osrfCacheGetString(): Returning object (key=%s): %s", VA_BUF, data); + if(!data) osrfLogDebug(OSRF_LOG_MARK, "No cache data exists with key %s", VA_BUF); + return data; + } + return NULL; +} + + +int osrfCacheRemove( const char* key, ... ) { + memcached_return rc; + if( key ) { + VA_LIST_TO_STRING(key); + rc = memcached_delete(_osrfCache, VA_BUF, strlen(VA_BUF), 0 ); + if (rc != MEMCACHED_SUCCESS && rc != MEMCACHED_BUFFERED) { + osrfLogDebug(OSRF_LOG_MARK, "Failed to delete key [%s] - %s", + VA_BUF, memcached_strerror(_osrfCache, rc)); + } + return 0; + } + return -1; +} + + +int osrfCacheSetExpire( time_t seconds, const char* key, ... ) { + if( key ) { + VA_LIST_TO_STRING(key); + jsonObject* o = osrfCacheGetObject( VA_BUF ); + //osrfCacheRemove(VA_BUF); + int rc = osrfCachePutObject( VA_BUF, o, seconds ); + jsonObjectFree(o); + return rc; + } + return -1; +} + +void osrfCacheCleanup() { + if(_osrfCache) { + memcached_free(_osrfCache); + } +} + + diff --git a/pool/shard000/C/0009622_recv_nsol.c b/pool/shard000/C/0009622_recv_nsol.c new file mode 100644 index 0000000000000000000000000000000000000000..ce3ca263399c849a86fdb77be81e481698f7e125 --- /dev/null +++ b/pool/shard000/C/0009622_recv_nsol.c @@ -0,0 +1,268 @@ +/* + * Copyright 2016 Simon Schmidt + * Copyright 2011-2016 by Andrey Butok. FNET Community. + * Copyright 2008-2010 by Andrey Butok. Freescale Semiconductor, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include +#include +#include +#include +#include +#include + + +#include +#include +#include +#include + +#include + +#include + +static void netnd6_nsol_handle_lla( + netif_t *nif, + uint32_t size, + fnet_nd6_option_lla_header_t *nd_option_slla, + ipv6_addr_t *src_ip, + ipv6_addr_t *dst_ip +); + +void netnd6_neighbor_solicitation_receive(netif_t *nif,netpkt_t *pkt, ipv6_addr_t *src_ip, ipv6_addr_t *dst_ip){ + fnet_nd6_ns_header_t *hdr; + partial_ipv6_header_t *iphdr; + uint32_t size; + ipv6_addr_t target_addr; + netipv6_if_addr_t *target_nifaddr; + fnet_nd6_option_header_t *nd_option; + + ipv6_addr_t ip_allnodes_addr = IP6_ADDR_LINKLOCAL_ALLNODES_INIT; + + + /* + * Validation RFC4861 (7.1.1). + * The IP Hop Limit field has a value of 255, i.e., the packet + * could not possibly have been forwarded by a router. + */ + if( netnd6_check_hop_limit(pkt,255) ) goto DROP; + + /* + * The header must reside in contiguous area of memory. + * + * Validation RFC4861 (7.1.1). ICMP length (derived from the IP length) is 24 or more octets. + */ + if( netpkt_pullup(pkt,sizeof(fnet_nd6_ns_header_t)) ) goto DROP; + + hdr = netpkt_data(pkt); + + /* Validation RFC4861 (7.1.1). */ + if( + (hdr->icmp6_header.code != 0u) || /* ICMP Code is 0.*/ + IP6_ADDR_IS_MULTICAST(hdr->target_addr) /* Target Address is not a multicast address. */ + ) goto DROP; + + target_addr = hdr->target_addr; + + if( netpkt_pullfront(pkt,sizeof(fnet_nd6_ns_header_t)) ) goto DROP; + + /* + * Validation RFC4861 (7.1.1). All included options have a length that + * is greater than zero. + */ + if( netnd6_check_options(pkt) ) goto DROP; + + + while(NETPKT_LENGTH(pkt)){ + if( netpkt_pullup(pkt,sizeof(fnet_nd6_option_header_t)) ) goto DROP; + + nd_option = netpkt_data(pkt); + + size = nd_option->length<<3; + + /* + * Handle Source link-layer address option only. + */ + if( (nd_option->type == FNET_ND6_OPTION_SOURCE_LLA) ) { + if(size >= (sizeof(fnet_nd6_option_header_t) + NETIF_HWADDR_SIZE(nif) ) ){ + if( netpkt_pullup(pkt,size) ) goto DROP; + netnd6_nsol_handle_lla(nif,size,netpkt_data(pkt),src_ip,dst_ip); + } + } + /* else, silently ignore any options they do not recognize + * and continue processing the message. + */ + if( netpkt_pullfront(pkt,size) ) goto DROP; + } + + /* + * Get Target Address Info, according tp Target Address of NS message. + */ + target_nifaddr = netipv6_get_address_info(nif,&target_addr); + + /* + * Check if we are the target. + */ + if( target_nifaddr ){ + /* Duplicate Address Detection (DAD) sends Neighbor Solicitation + * messages with an unspecified source address targeting its own + * "tentative" address. + */ + if(IP6_ADDR_IS_UNSPECIFIED(*src_ip)){ + /* === Duplicate Address Detection ===*/ + + /* + * IP Destination address must be our solitation address. + */ + if( netipv6_addr_is_own_ip6_solicited_multicast(nif,dst_ip) ) + { + if(target_nifaddr->state != FNET_NETIF_IP6_ADDR_STATE_TENTATIVE) + { + /* If the source of the solicitation is the unspecified address, the + * node MUST set the Solicited flag to zero and multicast the + * advertisement to the all-nodes address. + */ + + netnd6_neighbor_advertisement_send(nif, &(target_nifaddr->address), &ip_allnodes_addr, FNET_ND6_NA_FLAG_OVERRIDE); + } + else + { + netnd6_dad_failed(nif , target_nifaddr); /* => DAD is failed. */ + /* + * MUST be silently discarded, if the Target Address is a "tentative" + * address on which Duplicate Address Detection is being performed [ADDRCONF]. + */ + } + } + /* + * else DROP IT. + */ + } + else if( + /* === Address Resolution === */ + (netipv6_addr_is_own_ip6_solicited_multicast(nif,dst_ip))|| + /* === Neighbor Unreachability Detection === */ + ((IP6ADDR_EQ(target_addr, *dst_ip))) + ) { + /* + * Sends a Neighbor Advertisement response. + */ + netnd6_neighbor_advertisement_send(nif, &(target_nifaddr->address), src_ip, FNET_ND6_NA_FLAG_SOLICITED | FNET_ND6_NA_FLAG_OVERRIDE); + } + else + {} /* else: Bad packet.*/ + } + +DROP: + netpkt_free(pkt); +} + +static void netnd6_nsol_handle_lla( + netif_t *nif, + uint32_t size, + fnet_nd6_option_lla_header_t *nd_option_slla, + ipv6_addr_t *src_ip, + ipv6_addr_t *dst_ip +){ + fnet_nd6_neighbor_entry_t *neighbor_cache_entry; + netpkt_t *pkts = 0; /* Send-Chain. */ + ipv6_addr_t queue_addr; + hwaddr_t slla_addr = nif->device_addr; + + netif_hwaddr_load(&slla_addr,nd_option_slla->addr); + + /* + * Validation RFC4861 (7.1.1): If the IP source address is the + * unspecified address, there is no source link-layer address option in the message. + * NOTE: RFC4861 (7):Duplicate Address Detection sends Neighbor Solicitation + * messages with an unspecified source address targeting its own + * "tentative" address. + */ + if( IP6_ADDR_IS_UNSPECIFIED(*src_ip) ){ + /* + * If the Source Address is the unspecified address, the node MUST NOT + * create or update the Neighbor Cache entry. + */ + return; + } + + /* + * RFC 48617.2.3: the recipient + * SHOULD create or update the Neighbor Cache entry for the IP Source + * Address of the solicitation. + */ + + net_mutex_lock(nif->nd6->nd6_lock); + + neighbor_cache_entry = netnd6_neighbor_cache_get(nif, src_ip); + + if(! neighbor_cache_entry ) + { + /* + * If an entry does not already exist, the + * node SHOULD create a new one and set its reachability state to STALE + * as specified in Section 7.3.3. + * If a Neighbor Cache entry is created, the IsRouter flag SHOULD be set + * to FALSE. This will be the case even if the Neighbor Solicitation is + * sent by a router since the Neighbor Solicitation messages do not + * contain an indication of whether or not the sender is a router. In + * the event that the sender is a router, subsequent Neighbor + * Advertisement or Router Advertisement messages will set the correct + * IsRouter value. + */ + netnd6_neighbor_cache_add2(nif,src_ip, &slla_addr, FNET_ND6_NEIGHBOR_STATE_STALE); + } + else + { + /* + * If an entry already exists, and the + * cached link-layer address differs from the one in the received Source + * Link-Layer option, the cached address should be replaced by the + * received address, and the entry's reachability state MUST be set to + * STALE. + * If a Neighbor Cache entry already exists, its + * IsRouter flag MUST NOT be modified. + */ + if( !netif_hwaddr_eq( &(slla_addr), &(neighbor_cache_entry->ll_addr2) ) ) + { + neighbor_cache_entry->ll_addr2 = slla_addr; + neighbor_cache_entry->state = FNET_ND6_NEIGHBOR_STATE_STALE; + } + else{ + /* RFC4861: Appendix C + */ /*TBD ??*/ + if(neighbor_cache_entry->state == FNET_ND6_NEIGHBOR_STATE_INCOMPLETE) + { + neighbor_cache_entry->state = FNET_ND6_NEIGHBOR_STATE_STALE; + } + } + + /* + * - It sends any packets queued for the neighbor awaiting address + * resolution. + */ + pkts = neighbor_cache_entry->waiting_pkts; + neighbor_cache_entry->waiting_pkts = 0; + queue_addr = neighbor_cache_entry->ip_addr; + } + net_mutex_unlock(nif->nd6->nd6_lock); + + if(pkts) { + nif->netif_class->ifapi_send_l3_ipv6_all(nif,pkts,dst_ip,(void*)&queue_addr); + } +} + diff --git a/pool/shard000/C/0009625_output_current_ES_for_phase_first_iteration.c b/pool/shard000/C/0009625_output_current_ES_for_phase_first_iteration.c new file mode 100644 index 0000000000000000000000000000000000000000..09ffe60d1956dec599c872d2590da6e3d0d627c4 --- /dev/null +++ b/pool/shard000/C/0009625_output_current_ES_for_phase_first_iteration.c @@ -0,0 +1,80 @@ + +#include +#include +#include +#include +#include +#include + +/****************************************************************** + * This is a c script for output current empirical source + * + * Input: + * 1. + * 2. + * + * + * Output: + * + * + * DATE: Keywords: + * Reference: +******************************************************************/ + +int output_current_ES_for_phase_first_iteration(new_INPUT* my_input, double* new_ES) +{ + + int output_array2( char* output_name, double* array1,double* array2,int file_num, int normalize_flag); +// output ES here + int nerr,i; + char out_file[200]; + char out_file1[200]; + int npts_phase = (int)(my_input->phase_len / my_input->delta ); + float beg = 0; + float del = my_input->delta; + sprintf(out_file,"%s_ES.sac",my_input->PHASE); + + float yarray[npts_phase]; + double yarray_double[npts_phase]; + double xarray[npts_phase]; + for(i=0; idelta; + yarray[i] = new_ES[i]; + yarray_double[i] = new_ES[i]; + } + wsac1(out_file,yarray, &npts_phase, &beg,&del, &nerr, strlen( out_file )); + sprintf(out_file1,"%s_ES.first_iteration.out",my_input->PHASE); + + output_array2(out_file1, xarray, yarray_double, npts_phase,0); + //output_array1(out_file1, new_ES, npts_phase); + + + + /* + + char command[300]= "csh bp_S_ES.sh"; + char sac_file[300] = "S_ES_bp.sac"; + // bp filter S empirical wavelet and write to S_ES_bp.sac + if( strcmp(my_input->PHASE,"S") ==0 ) + { + system(command); + // read in sac file and print as S_ES_bp.out + + double sac_array[10000]; + double length = my_input->phase_len; + +//printf("length is %lf npts_phase is %d\n", length, npts_phase); + sac2xy(sac_file, 0, length, sac_array); + + // write out + char out_file2[200]; + sprintf(out_file2,"%s_ES_bp.out",my_input->PHASE); + output_array1(out_file2,sac_array,npts_phase); + } + +*/ + + return 0; +} + diff --git a/pool/shard000/C/0009646_muffin-message.c b/pool/shard000/C/0009646_muffin-message.c new file mode 100644 index 0000000000000000000000000000000000000000..9cb4a442cb5f5a1e51fab28bea0befc3846ca9ec --- /dev/null +++ b/pool/shard000/C/0009646_muffin-message.c @@ -0,0 +1,158 @@ +/* Muffin send-magic-messages app */ + +/* + * Copyright (C) 2002 Havoc Pennington + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street - Suite 500, Boston, MA + * 02110-1335, USA. + */ + +#include +#include +#include +#include +#include + +#include + +static Display *display; + +static void +send_reload_theme (void) +{ + XEvent xev; + + xev.xclient.type = ClientMessage; + xev.xclient.serial = 0; + xev.xclient.send_event = True; + xev.xclient.display = display; + xev.xclient.window = gdk_x11_get_default_root_xwindow (); + xev.xclient.message_type = XInternAtom (display, + "_MUFFIN_RELOAD_THEME_MESSAGE", + False); + xev.xclient.format = 32; + xev.xclient.data.l[0] = 0; + xev.xclient.data.l[1] = 0; + xev.xclient.data.l[2] = 0; + + XSendEvent (display, + gdk_x11_get_default_root_xwindow (), + False, + SubstructureRedirectMask | SubstructureNotifyMask, + &xev); + + XFlush (display); + XSync (display, False); +} + +static void +send_set_keybindings (gboolean enabled) +{ + XEvent xev; + + xev.xclient.type = ClientMessage; + xev.xclient.serial = 0; + xev.xclient.send_event = True; + xev.xclient.display = display; + xev.xclient.window = gdk_x11_get_default_root_xwindow (); + xev.xclient.message_type = XInternAtom (display, + "_MUFFIN_SET_KEYBINDINGS_MESSAGE", + False); + xev.xclient.format = 32; + xev.xclient.data.l[0] = enabled; + xev.xclient.data.l[1] = 0; + xev.xclient.data.l[2] = 0; + + XSendEvent (display, + gdk_x11_get_default_root_xwindow (), + False, + SubstructureRedirectMask | SubstructureNotifyMask, + &xev); + + XFlush (display); + XSync (display, False); +} + +#ifdef WITH_VERBOSE_MODE +static void +send_toggle_verbose (void) +{ + XEvent xev; + + xev.xclient.type = ClientMessage; + xev.xclient.serial = 0; + xev.xclient.send_event = True; + xev.xclient.display = display; + xev.xclient.window = gdk_x11_get_default_root_xwindow (); + xev.xclient.message_type = XInternAtom (display, + "_MUFFIN_TOGGLE_VERBOSE", + False); + xev.xclient.format = 32; + xev.xclient.data.l[0] = 0; + xev.xclient.data.l[1] = 0; + xev.xclient.data.l[2] = 0; + + XSendEvent (display, + gdk_x11_get_default_root_xwindow (), + False, + SubstructureRedirectMask | SubstructureNotifyMask, + &xev); + + XFlush (display); + XSync (display, False); +} +#endif + +static void +usage (void) +{ + g_printerr (_("Usage: %s\n"), + "muffin-message (reload-theme|enable-keybindings|disable-keybindings|toggle-verbose)"); + exit (1); +} + +int +main (int argc, char **argv) +{ + bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8"); + + gtk_init (&argc, &argv); + + if (argc < 2) + usage (); + + display = GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()); + + if (strcmp (argv[1], "reload-theme") == 0) + send_reload_theme (); + else if (strcmp (argv[1], "enable-keybindings") == 0) + send_set_keybindings (TRUE); + else if (strcmp (argv[1], "disable-keybindings") == 0) + send_set_keybindings (FALSE); + else if (strcmp (argv[1], "toggle-verbose") == 0) + { +#ifndef WITH_VERBOSE_MODE + g_printerr (_("Muffin was compiled without support for verbose mode\n")); + return 1; +#else + send_toggle_verbose (); +#endif + } + else + usage (); + + return 0; +} + diff --git a/pool/shard000/C/0009651_insrtc_c.c b/pool/shard000/C/0009651_insrtc_c.c new file mode 100644 index 0000000000000000000000000000000000000000..cde781fa8e5242ab2a55db91c07c734eb011b706 --- /dev/null +++ b/pool/shard000/C/0009651_insrtc_c.c @@ -0,0 +1,307 @@ +/* + +-Procedure insrtc_c ( Insert an item into a character set ) + +-Abstract + + Insert an item into a character set. + +-Disclaimer + + THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE + CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S. + GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE + ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE + PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS" + TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY + WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A + PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC + SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE + SOFTWARE AND RELATED MATERIALS, HOWEVER USED. + + IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA + BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT + LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, + INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS, + REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE + REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY. + + RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF + THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY + CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE + ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE. + +-Required_Reading + + SETS + +-Keywords + + CELLS, SETS + +*/ + +#include "SpiceUsr.h" +#include "SpiceZfc.h" +#include "SpiceZmc.h" +#include "f2cMang.h" + + + void insrtc_c ( ConstSpiceChar * item, + SpiceCell * set ) + +/* + +-Brief_I/O + + VARIABLE I/O DESCRIPTION + -------- --- -------------------------------------------------- + item I Item to be inserted. + set I/O Insertion set. + +-Detailed_Input + + item is an item which is to be inserted into the specified + set. item may or may not already be an element of the + set. Trailing blanks in item are not significant. + + + set is a CSPICE set. set must be declared as a character + SpiceCell. + + On input, set may or may not contain the input item + as an element. + +-Detailed_Output + + set on output contains the union of the input set and + the singleton set containing the input item. + +-Parameters + + None. + +-Exceptions + + 1) If the input set argument is a SpiceCell of type other than + character, the error SPICE(TYPEMISMATCH) is signaled. + + 2) If the insertion of the element into the set causes an excess + of elements, the error SPICE(SETEXCESS) is signaled. + + 3) If the input set argument does not qualify as a CSPICE set, + the error SPICE(NOTASET) will be signaled. CSPICE sets have + their data elements sorted in increasing order and contain + no duplicate data elements. + + 4) If the input string pointer is null, the error SPICE(NULLPOINTER) + is signaled. + +-Files + + None. + +-Particulars + + None. + +-Examples + + 1) In the following example, the element "PLUTO" is removed from + the character set planets and inserted into the character set + asteroids. + + #include "SpiceUsr.h" + . + . + . + /. + Declare the sets with string length NAMLEN and with maximum + number of elements MAXSIZ. + ./ + SPICECHAR_CELL ( planets, MAXSIZ, NAMLEN ); + SPICECHAR_CELL ( asteroids, MAXSIZ, NAMLEN ); + . + . + . + removc_c ( "PLUTO", &planets ); + insrtc_c ( "PLUTO", &asteroids ); + + + If "PLUTO" is not an element of planets, then the contents of + planets are not changed. Similarly, if "PLUTO" is already an + element of asteroids, the contents of asteroids remain unchanged. + + Because inserting an element into a set can increase the + cardinality of the set, an error may occur in the insertion + routines. + +-Restrictions + + 1) String comparisons performed by this routine are Fortran-style: + trailing blanks in the input set or key value are ignored. + This gives consistent behavior with CSPICE code generated by + the f2c translator, as well as with the Fortran SPICE Toolkit. + + Note that this behavior is not identical to that of the ANSI + C library functions strcmp and strncmp. + +-Literature_References + + None. + +-Author_and_Institution + + N.J. Bachman (JPL) + C.A. Curzon (JPL) + W.L. Taber (JPL) + I.M. Underwood (JPL) + +-Version + + -CSPICE Version 2.1.0, 07-MAR-2009 (NJB) + + This file now includes the header file f2cMang.h. + This header supports name mangling of f2c library + functions. + + -CSPICE Version 2.0.0, 01-NOV-2005 (NJB) + + Bug fix: when the item to be inserted would, after + truncation to the set's string length, match an item + already in the set, no insertion is performed. Previously + the truncated string was inserted, corrupting the set. + + Long error message was updated to include size of + set into which insertion was attempted. + + -CSPICE Version 1.0.0, 21-AUG-2002 (NJB) (CAC) (WLT) (IMU) + +-Index_Entries + + insert an item into a character set + +-& +*/ +{ + /* + f2c library utility prototypes + */ + extern integer s_cmp (char *a, char *b, ftnlen la, ftnlen lb ); + + + /* + Local macros + */ + #define ARRAY( i ) ( (SpiceChar *)(set->data) + (i)*(set->length) ) + + + /* + local variables + */ + SpiceBoolean inSet; + + SpiceChar * cdata; + + SpiceInt i; + SpiceInt loc; + SpiceInt slen; + + + + /* + Use discovery check-in. + + Check the input string pointer to make sure it's not null. + */ + CHKPTR ( CHK_DISCOVER, "insrtc_c", item ); + + + /* + Make sure we're working with a character cell. + */ + CELLTYPECHK ( CHK_DISCOVER, "insrtc_c", SPICE_CHR, set ); + + + /* + Make sure the input cell is a set. + */ + CELLISSETCHK ( CHK_DISCOVER, "insrtc_c", set ); + + + /* + Initialize the set if it's not already initialized. + */ + CELLINIT ( set ); + + + /* + Let slen be the effective string length of the input item. + Characters beyond the string length of the set are ignored. + */ + slen = mini_c ( 2, set->length, strlen(item) ); + + + /* + Is the item already in the set? If not, it needs to be inserted. + */ + cdata = (SpiceChar *) (set->data); + + /* + The following call will give the location of the last element + less than or equal to the item to be inserted. If the item + differs from an element of the set only in characters that would + be truncated, no insertion will occur. Even in this case, the + insertion point `loc' returned by lstlec_c will be correct. + */ + loc = lstlec_c ( item, set->card, set->length, cdata ); + + inSet = ( loc > -1 ) + + && ( s_cmp( (SpiceChar *)item, ARRAY(loc), + slen, strlen(ARRAY(loc)) ) == 0 ); + + if ( inSet ) + { + return; + } + + + /* + It's an error if the set has no room left. + */ + if ( set->card == set->size ) + { + chkin_c ( "insrtc_c" ); + setmsg_c ( "An element could not be inserted into the set " + "due to lack of space; set size is #." ); + errint_c ( "#", set->size ); + sigerr_c ( "SPICE(SETEXCESS)" ); + chkout_c ( "insrtc_c" ); + return; + } + + + /* + Make room by moving the items that come after index loc in the set. + Insert the item after index loc. + */ + for ( i = (set->card); i > (loc+1); i-- ) + { + SPICE_CELL_SET_C( ARRAY(i-1), i, set ); + } + + /* + This insertion macro will truncate the item to be inserted, if + necessary. The input item will be null-terminated. + */ + SPICE_CELL_SET_C( item, loc+1, set ); + + + /* + Increment the set's cardinality. + */ + (set->card) ++; + +} + diff --git a/pool/shard000/C/0009657_sequence.c b/pool/shard000/C/0009657_sequence.c new file mode 100644 index 0000000000000000000000000000000000000000..70f062979e26751f59107d4cc0e16365d4975d36 --- /dev/null +++ b/pool/shard000/C/0009657_sequence.c @@ -0,0 +1,144 @@ +/* +Copyright (C) 2009- The University of Notre Dame +This software is distributed under the GNU General Public License. +See the file COPYING for details. +*/ + +#include +#include +#include +#include + +#include "stringtools.h" +#include "debug.h" +#include "full_io.h" + +#include "sequence.h" + +struct seq * seq_create( const char *name, const char *data, const char *metadata ) +{ + struct seq *s = malloc(sizeof(*s)); + + s->name = strdup(name); + s->data = strdup(data); + s->metadata = strdup(metadata); + s->num_bases = strlen(data); + + return s; +} + +static char base_complement(char c) +{ + switch(c) + { + case 'A': + case 'a': + return 'T'; + case 'T': + case 't': + return 'A'; + case 'G': + case 'g': + return 'C'; + case 'C': + case 'c': + return 'G'; + default: + return 'N'; + } +} + +void seq_reverse_complement( struct seq *s ) +{ + char * str = s->data; + int num_bases = s->num_bases; + char c_i, c_j; + int i, j; + + for(i=0, j=num_bases-1; i <= j; i++, j--) + { + c_i = str[i]; + c_j = str[j]; + str[j] = base_complement(c_i); + str[i] = base_complement(c_j); + } +} + +void seq_free( struct seq *s ) +{ + if(s) { + free(s->name); + free(s->data); + free(s->metadata); + free(s); + } +} + +int seq_sprint(char * buf, struct seq *s ) +{ + return sprintf(buf,">%s %s\n%s\n",s->name,s->metadata,s->data); +} + +void seq_print( FILE *file, struct seq *s ) +{ + fprintf(file,">%s %s\n%s\n",s->name,s->metadata,s->data); +} + +struct seq * seq_read( FILE *file ) +{ + static char *buffer = 0; + static int buffer_size = SEQUENCE_FILE_LINE_MAX; + + char line[SEQUENCE_FILE_LINE_MAX]; + char name[SEQUENCE_FILE_LINE_MAX]; + char metadata[SEQUENCE_FILE_LINE_MAX]; + + if(!fgets(line,sizeof(line),file)) return 0; + + // special case: >> indicates the end of a list + if(line[0]=='>' && line[1]=='>') return 0; + + metadata[0] = 0; + + int n = sscanf(line, ">%s %[^\n]\n",name,metadata); + if(n<1) fatal("syntax error near: %s\n",line); + + if(!buffer) buffer = malloc(buffer_size); + + int num_bases = 0; + + while(1) { + int c = getc_unlocked(file); + if(isspace(c)) continue; + if(c==EOF) break; + if(c=='>') { + ungetc(c,file); + break; + } + buffer[num_bases++] = toupper(c); + if(num_bases>(buffer_size-2)) { + buffer_size *= 2; + buffer = realloc(buffer,buffer_size); + } + } + + buffer[num_bases] = 0; + + return seq_create(name,buffer,metadata); +} + +int sequence_count(FILE * file) +{ + int count = 0; + char line[SEQUENCE_FILE_LINE_MAX]; + long int start_pos = ftell(file); + + while(fgets(line,sizeof(line),file)) { + if(line[0] == '>') count++; + } + + fseek(file, start_pos, SEEK_SET); + return count; +} + +/* vim: set noexpandtab tabstop=4: */ diff --git a/pool/shard000/C/0009673_indexint.c b/pool/shard000/C/0009673_indexint.c new file mode 100644 index 0000000000000000000000000000000000000000..86de34b1b7d9610b2ba185e922d41aceee92b472 --- /dev/null +++ b/pool/shard000/C/0009673_indexint.c @@ -0,0 +1,177 @@ +/************************************************************************* + + Program: + File: indexint.c + + Version: V1.3 + Date: 13.02.96 + Function: Index heapsort an int array + + Copyright: (c) SciTech Software 1991-6 + Author: Dr. Andrew C. R. Martin + Address: SciTech Software + 23, Stag Leys, + Ashtead, + Surrey, + KT21 2TD. + Phone: +44 (0) 1372 275775 + EMail: martin@biochem.ucl.ac.uk + +************************************************************************** + + This program is not in the public domain, but it may be copied + according to the conditions laid out in the accompanying file + COPYING.DOC + + The code may not be sold commercially or included as part of a + commercial product except as described in the file COPYING.DOC. + +************************************************************************** + + Description: + ============ + This routine uses a heapsort to index a floating point array + such that arrin[indx[j]] is in ascending order with j. + It is modified from the FORTRAN version in 'Numerical Recipes' + Page 233. This version correctly sorts from array element 0 + as opposed to 1 in the FORTRAN version. + +************************************************************************** + + Usage: + ====== + indexf(n,arrin,indx) + Input: n int Number of elements in array + arrin *double Array to be indexed + Output: indx *int Index array + +************************************************************************** + + Revision History: + ================= + V1.0 23.06.90 Original + V1.1 01.06.92 ANSIed and autodoc'd + V1.2 19.07.93 Corrected bug (said j=l+1 rather than j=l+l). Oops! + +*************************************************************************/ +/* Includes +*/ + +/************************************************************************/ +/* Defines and macros +*/ + +/************************************************************************/ +/* Globals +*/ + +/************************************************************************/ +/* Prototypes +*/ + +/************************************************************************/ +/*>void indexint(int n, int *arrin, int *indx) + --------------------------------------------- + Input: n int Number of elements in array + arrin *int Array to be indexed + Output: indx *int Index array + + Index a int array by Heapsort. + + 03.06.90 Original + 01.06.92 ANSIed and autodoc'd + 13.02.96 Rewritten +*/ +void indexint(int n, int *arrin, int *indx) +{ + int i, j, l, ir, + indxt; + int q; + + /* Modify the array starts so we can count from 1 */ + indx--; + arrin--; + + for(j=1; j<=n; j++) + indx[j] = j; + + l = n/2+1; + ir = n; + + for(;;) + { + if(l>1) + { + indxt = indx[--l]; + q = arrin[indxt]; + } + else + { + indxt = indx[ir]; + q = arrin[indxt]; + indx[ir] = indx[1]; + + if((--ir) == 1) + { + indx[1] = indxt; + + /* Correct the offsets, so they run from 0 */ + for(j=1; j<=n; j++) + indx[j]--; + + return; + } + } + + i = l; + j = l+l; + while(j <= ir) + { + if(j < ir) + { + if(arrin[indx[j]] < arrin[indx[j+1]]) + j++; + } + if(q < arrin[indx[j]]) + { + indx[i] = indx[j]; + i = j; + j += j; + } + else + { + j = ir+1; + } + } + indx[i] = indxt; + } +} + +/************************************************************************/ +#ifdef DEMO_CODE +#include +int main(void) +{ + int values[10]; + int indx[10], + j; + + values[0] = 1; + values[1] = 15; + values[2] = 25; + values[3] = 12; + values[4] = 2; + values[5] = 3; + values[6] = 26; + values[7] = 290; + values[8] = 5; + values[9] = 7; + + indexint(10,values,indx); + + for(j=0; j<10; j++) + printf("%d %d\n",indx[j],values[indx[j]]); + + return(0); +} +#endif diff --git a/pool/shard000/C/0009678_testrichtext.c b/pool/shard000/C/0009678_testrichtext.c new file mode 100644 index 0000000000000000000000000000000000000000..329973b09a52d9beca67bbe922329e0f4387e771 --- /dev/null +++ b/pool/shard000/C/0009678_testrichtext.c @@ -0,0 +1,191 @@ +/* testrichtext.c + * Copyright (C) 2006 Imendio AB + * Authors: Michael Natterer, Tim Janik + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + */ + +#include +#include + +static guint32 quick_rand32_accu = 2147483563; + +static inline guint32 +quick_rand32 (void) +{ + quick_rand32_accu = 1664525 * quick_rand32_accu + 1013904223; + return quick_rand32_accu; +} + +static gboolean +delete_event (GtkWidget *widget, + GdkEventAny *event, + gpointer user_data) +{ + gtk_main_quit (); + + return TRUE; +} + +static void +text_tag_enqueue (GtkTextTag *tag, + gpointer data) +{ + GSList **slist_p = data; + *slist_p = g_slist_prepend (*slist_p, tag); +} + +static const gchar *example_text = +"vkndsk vfds vkfds vkdsv fdlksnvkfdvnkfdvnkdsnvs\n" +"kmvofdmvfdsvkv fdskvnkfdv nnd.mckfdvnknsknvdnvs" +"fdlvmfdsvlkfdsmvnskdnvfdsnvf sbskjnvlknfd cvdvnd" +"mvlfdsv vfdkjv m, ds vkfdks v df,v j kfds v d\n" +"vnfdskv kjvnfv cfdkvndfnvcm fd,vk kdsf vj d\n" +"KLJHkjh kjh klhjKLJH Kjh kjl h34kj h34kj3h klj 23 " +"kjlkjlhsdjk 34kljh klj hklj 23k4jkjkjh234kjh 52kj " +"2h34 sdaf ukklj kjl32l jkkjl 23j jkl ljk23 jkl\n" +"hjhjhj2hj23jh jh jk jk2h3 hj kjj jk jh21 jhhj32."; + +static GdkAtom +setup_buffer (GtkTextBuffer *buffer) +{ + const guint tlen = strlen (example_text); + const guint tcount = 17; + GtkTextTag **tags; + GtkTextTagTable *ttable = gtk_text_buffer_get_tag_table (buffer); + GSList *node, *slist = NULL; + GdkAtom atom; + guint i; + + tags = g_malloc (sizeof (GtkTextTag *) * tcount); + + /* cleanup */ + gtk_text_buffer_set_text (buffer, "", 0); + gtk_text_tag_table_foreach (ttable, text_tag_enqueue, &slist); + for (node = slist; node; node = node->next) + gtk_text_tag_table_remove (ttable, node->data); + g_slist_free (slist); + + /* create new tags */ + for (i = 0; i < tcount; i++) + { + char *s = g_strdup_printf ("tag%u", i); + tags[i] = gtk_text_buffer_create_tag (buffer, s, + "weight", quick_rand32() >> 31 ? PANGO_WEIGHT_BOLD : PANGO_WEIGHT_NORMAL, + "style", quick_rand32() >> 31 ? PANGO_STYLE_OBLIQUE : PANGO_STYLE_NORMAL, + "underline", quick_rand32() >> 31, + NULL); + g_free (s); + } + + /* assign text and tags */ + gtk_text_buffer_set_text (buffer, example_text, -1); + for (i = 0; i < tcount * 5; i++) + { + gint a = quick_rand32() % tlen, b = quick_rand32() % tlen; + GtkTextIter start, end; + gtk_text_buffer_get_iter_at_offset (buffer, &start, MIN (a, b)); + gtk_text_buffer_get_iter_at_offset (buffer, &end, MAX (a, b)); + gtk_text_buffer_apply_tag (buffer, tags[i % tcount], &start, &end); + } + + /* return serialization format */ + atom = gtk_text_buffer_register_deserialize_tagset (buffer, NULL); + gtk_text_buffer_deserialize_set_can_create_tags (buffer, atom, TRUE); + + g_free (tags); + + return atom; +} + +static gboolean +test_serialize_deserialize (GtkTextBuffer *buffer, + GdkAtom atom, + GError **error) +{ + GtkTextIter start, end; + guint8 *spew; + gsize spew_length; + gboolean success; + + gtk_text_buffer_get_bounds (buffer, &start, &end); + + spew = gtk_text_buffer_serialize (buffer, buffer, atom, + &start, &end, &spew_length); + + success = gtk_text_buffer_deserialize (buffer, buffer, atom, &end, + spew, spew_length, error); + + g_free (spew); + + return success; +} + +gint +main (gint argc, + gchar *argv[]) +{ + GtkWidget *window; + GtkWidget *sw; + GtkWidget *view; + GtkTextBuffer *buffer; + GdkAtom atom; + guint i, broken = 0; + + gtk_init (&argc, &argv); + + /* initialize random numbers, disable this for deterministic testing */ + if (1) + quick_rand32_accu = g_random_int(); + + window = gtk_window_new (GTK_WINDOW_TOPLEVEL); + gtk_widget_set_size_request (window, 400, 300); + + sw = gtk_scrolled_window_new (NULL, NULL); + gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (sw), + GTK_SHADOW_IN); + gtk_container_set_border_width (GTK_CONTAINER (sw), 12); + gtk_container_add (GTK_CONTAINER (window), sw); + + g_signal_connect (window, "delete-event", + G_CALLBACK (delete_event), + NULL); + + buffer = gtk_text_buffer_new (NULL); + view = gtk_text_view_new_with_buffer (buffer); + g_object_unref (buffer); + + gtk_container_add (GTK_CONTAINER (sw), view); + + gtk_widget_show_all (window); + if (0) + gtk_main (); + + for (i = 0; i < 250; i++) + { + GError *error = NULL; + g_printerr ("creating randomly tagged text buffer with accu=0x%x...\n", quick_rand32_accu); + atom = setup_buffer (buffer); + if (test_serialize_deserialize (buffer, atom, &error)) + g_printerr ("ok.\n"); + else + { + g_printerr ("FAIL: serialization/deserialization failed:\n %s\n", error->message); + broken += 1; + } + g_clear_error (&error); + } + + return broken > 0; +} diff --git a/pool/shard000/C/0009696_main.c b/pool/shard000/C/0009696_main.c new file mode 100644 index 0000000000000000000000000000000000000000..a424c6bebe1fa4b9d179f5342d38816de753e97f --- /dev/null +++ b/pool/shard000/C/0009696_main.c @@ -0,0 +1,196 @@ +/* + * Copyright(C) 2014 Pedro H. Penna + * + * Integer-Sort Benchmark Kernel. + */ + +#include +#include +#include +#include +#include +#include +#include + +/* + * Bucket sort algorithm. + */ +extern void bucketsort(int *array, int n); + +/* Timing statistics. */ +uint64_t master = 0; /* Time spent on master. */ +uint64_t slave[NUM_CLUSTERS]; /* Time spent on slaves. */ +uint64_t communication = 0; /* Time spent on communication. */ +uint64_t total = 0; /* Total time. */ + +/* Data exchange statistics. */ +size_t data_sent = 0; /* Number of bytes received. */ +unsigned nsend = 0; /* Number of sends. */ +size_t data_received = 0; /* Number of bytes sent. */ +unsigned nreceive = 0; /* Number of receives. */ + +/* + * Problem. + */ +struct problem +{ + int n; /* Number of elements. */ +}; + +/* Problem sizes. */ +static struct problem tiny = { 8388608 }; +static struct problem small = { 16777216 }; +static struct problem standard = { 33554432 }; +static struct problem large = { 67108864 }; +static struct problem huge = { 134217728 }; + +/* Benchmark parameters. */ +int verbose = 0; /* Be verbose? */ +int nclusters = 1; /* Number of threads. */ +static int seed = 0; /* Seed number. */ +static struct problem *p = &tiny; /* Problem. */ + +/* + * Prints program usage and exits. + */ +static void usage(void) +{ + printf("Usage: kmeans [options]\n"); + printf("Brief: Kmeans Benchmark Kernel\n"); + printf("Options:\n"); + printf(" --help Display this information and exit\n"); + printf(" --nclusters Set number of threads\n"); + printf(" --class Set problem class:\n"); + printf(" - small\n"); + printf(" - standard\n"); + printf(" - large\n"); + printf(" - huge\n"); + printf(" --verbose Be verbose\n"); + exit(0); +} + +/* + * Reads command line arguments. + */ +static void readargs(int argc, char **argv) +{ + int i; /* Loop index. */ + char *arg; /* Working argument. */ + int state; /* Processing state. */ + + /* State values. */ + #define READ_ARG 0 /* Read argument. */ + #define SET_nclusters 1 /* Set number of threads. */ + #define SET_CLASS 2 /* Set problem class. */ + + state = READ_ARG; + + /* Read command line arguments. */ + for (i = 1; i < argc; i++) + { + arg = argv[i]; + + /* Set value. */ + if (state != READ_ARG) + { + switch (state) + { + /* Set problem class. */ + case SET_CLASS : + if (!strcmp(argv[i], "tiny")) + p = &tiny; + else if (!strcmp(argv[i], "small")) + p = &small; + else if (!strcmp(argv[i], "standard")) + p = &standard; + else if (!strcmp(argv[i], "large")) + p = &large; + else if (!strcmp(argv[i], "huge")) + p = &huge; + else + usage(); + state = READ_ARG; + break; + + /* Set number of threads. */ + case SET_nclusters : + nclusters = atoi(arg); + state = READ_ARG; + break; + + default: + usage(); + } + + continue; + } + + /* Parse argument. */ + if (!strcmp(arg, "--verbose")) + verbose = 1; + else if (!strcmp(arg, "--nclusters")) + state = SET_nclusters; + else if (!strcmp(arg, "--class")) + state = SET_CLASS; + else + usage(); + } + + /* Invalid argument(s). */ + if (nclusters < 1) + usage(); +} + +/* + * Runs benchmark. + */ +int main(int argc, char **argv) +{ + int i; /* Loop index. */ + int *a; /* Array to be sorted. */ + uint64_t end; /* End time. */ + uint64_t start; /* Start time. */ + + readargs(argc, argv); + + timer_init(); + srandnum(seed); + + /* Benchmark initialization. */ + if (verbose) + printf("initializing...\n"); + start = timer_get(); + a = smalloc(p->n*sizeof(int)); + for (i = 0; i < p->n; i++) + a[i] = randnum() & 0xfffff; + end = timer_get(); + if (verbose) + printf(" time spent: %f\n", timer_diff(start, end)*MICROSEC); + + /* Cluster data. */ + if (verbose) + printf("sorting...\n"); + start = timer_get(); + bucketsort(a, p->n); + end = timer_get(); + + total = timer_diff(start, end); + + /* Print timing statistics. */ + printf("timing statistics:\n"); + printf(" master: %f\n", master*MICROSEC); + for (i = 0; i < nclusters; i++) + printf(" slave %d: %f\n", i, slave[i]*MICROSEC); + printf(" communication: %f\n", communication*MICROSEC); + printf(" total time: %f\n", total*MICROSEC); + printf("data exchange statistics:\n"); + printf(" data sent: %d\n", data_sent); + printf(" number sends: %u\n", nsend); + printf(" data received: %d\n", data_received); + printf(" number receives: %u\n", nreceive); + + /* House keeping. */ + free(a); + + return (0); +} diff --git a/pool/shard000/C/0009698_m_boss3.c b/pool/shard000/C/0009698_m_boss3.c new file mode 100644 index 0000000000000000000000000000000000000000..f7704ef43b6c86f83333e05845ffbebbb2c2725d --- /dev/null +++ b/pool/shard000/C/0009698_m_boss3.c @@ -0,0 +1,78 @@ +/* +Copyright (C) 1997-2001 Id Software, Inc. +Copyright (C) 2000-2002 Mr. Hyde and Mad Dog + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +See the GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +*/ + +/* +============================================================================== + +boss3 + +============================================================================== +*/ + +#include "g_local.h" +#include "m_boss32.h" + +void Use_Boss3 (edict_t *ent, edict_t *other, edict_t *activator) +{ + gi.WriteByte (svc_temp_entity); + gi.WriteByte (TE_BOSSTPORT); + gi.WritePosition (ent->s.origin); + gi.multicast (ent->s.origin, MULTICAST_PVS); + G_FreeEdict (ent); +} + +void Think_Boss3Stand (edict_t *ent) +{ + if (ent->s.frame == FRAME_stand260) + ent->s.frame = FRAME_stand201; + else + ent->s.frame++; + ent->nextthink = level.time + FRAMETIME; +} + +/*QUAKED monster_boss3_stand (1 .5 0) (-32 -32 0) (32 32 90) + +Just stands and cycles in one place until targeted, then teleports away. +*/ +void SP_monster_boss3_stand (edict_t *self) +{ + if (deathmatch->value) + { + G_FreeEdict (self); + return; + } + + self->movetype = MOVETYPE_STEP; + self->solid = SOLID_BBOX; + self->model = "models/monsters/boss3/rider/tris.md2"; + self->s.modelindex = gi.modelindex (self->model); + self->s.frame = FRAME_stand201; + + gi.soundindex ("misc/bigtele.wav"); + + VectorSet (self->mins, -32, -32, 0); + VectorSet (self->maxs, 32, 32, 90); + + self->use = Use_Boss3; + self->think = Think_Boss3Stand; + self->nextthink = level.time + FRAMETIME; + gi.linkentity (self); +} diff --git a/pool/shard000/C/0009705_test.c b/pool/shard000/C/0009705_test.c new file mode 100644 index 0000000000000000000000000000000000000000..7745148e796d3047da3f357fe521bef864674d18 --- /dev/null +++ b/pool/shard000/C/0009705_test.c @@ -0,0 +1,127 @@ +#include +#if defined(_ORANGUTAN_X2) || defined(_ORANGUTAN_SVP) +// these functions are undefined in the Pololu AVR library for the +// Orangutan SVP and Orangutan X2, so we define them here to prevent +// compile errors. +int read_temperature_f() { return 0; } +unsigned int read_battery_millivolts_sv() { return 0; } +#endif + +/* + * analog2: for the Orangutan LV, SV, SVP, X2, and 3pi robot + * + * This example uses the OrangutanAnalog functions to read the voltage + * output of the trimpot (in millivolts) and to read the battery voltage + * on the Orangutan SV, SVP, X2, or 3pi or the temperature sensor output + * in degrees Farenheit on the Orangutan LV. These values are + * printed to the LCD 10 times per second. + * + * You should see the trimpot voltage change as you turn it, and you can + * get the temperature reading to slowly increase by holding a finger on the + * underside of the Orangutan LV's PCB near the center of the board. + * Be careful not to zap the board with electrostatic discharge if you + * try this! + * + * http://www.pololu.com/docs/0J20 + * http://www.pololu.com + * http://forum.pololu.com + */ + +int main() +{ + unsigned char button; + int temp; + + clear(); // clear LCD + +#ifdef _ORANGUTAN_SVP // if running on an Orangutan SVP + + print("Orangutan SVP"); + button = BUTTON_C; + +#elif defined(_ORANGUTAN_X2) // if running on an Orangutan X2 + + print("Orangutan X2"); + button = BUTTON_C; + +#else // if running on something else (LV, SV, 3pi, Baby Orangutan) + + print("select"); + lcd_goto_xy(0, 1); // go to start of second LCD row + print("device"); + delay_ms(1000); + + clear(); + print("A B C"); + lcd_goto_xy(0, 1); + print("LV SV 3p"); + + // use button press to determine which device is being used + button = wait_for_button_press(ANY_BUTTON); + + clear(); + switch (button) + { + case BUTTON_A: + print(" Orang."); + lcd_goto_xy(0, 1); + print(" LV"); + break; + case BUTTON_B: + print(" Orang."); + lcd_goto_xy(0, 1); + print(" SV"); + break; + case BUTTON_C: + print(" 3pi"); + lcd_goto_xy(0, 1); + print(" Robot"); + break; + } + +#endif + + delay(1000); + clear(); + + set_analog_mode(MODE_10_BIT); // 10-bit analog-to-digital conversions + + + while(1) // loop forever + { + lcd_goto_xy(0, 0); // LCD cursor to home position (upper-left) + print_long(to_millivolts(read_trimpot())); // trimpot output in mV + print(" mV "); // added spaces are to overwrite left over chars + + lcd_goto_xy(0, 1); // LCD cursor to start of the second line + + switch (button) + { + case BUTTON_A: // using Orangutan LV, so display temp sensor data + temp = read_temperature_f(); // get temp in tenths of a degree F + print_long(temp/10); // get the whole number of degrees + print_character('.'); // print the decimal point + print_long(temp%10); // print the tenths digit + print_character(223); // print a degree symbol + print("F "); // added spaces are to overwrite left over chars + break; + + case BUTTON_B: // using Orangutan SV, so display battery voltage + // on SV, analog channel 6 (ADC6) is connected to 1/3 the system voltage + // through a voltage divider. We average 10 readings on channel 6, convert + // to millivolts, and then multiply by 3 to get the battery voltage + print_long(to_millivolts(analog_read_average(6, 10)) * 3); + // another option would be to use the line: + // print_long(read_battery_millivolts_sv()); + print(" mV "); + break; + + case BUTTON_C: // using Orangutan SVP or X2 or 3pi robot + print_long(read_battery_millivolts()); + print(" mV "); + break; + } + + delay_ms(50); // wait for 50 ms to decrease LCD flicker + } +} \ No newline at end of file diff --git a/pool/shard000/C/0009707_DatagramDispatcher.c b/pool/shard000/C/0009707_DatagramDispatcher.c new file mode 100644 index 0000000000000000000000000000000000000000..18cc30f1674b9f7b716b126db3961db72f39c027 --- /dev/null +++ b/pool/shard000/C/0009707_DatagramDispatcher.c @@ -0,0 +1,134 @@ +/* + * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + + +#include "jni.h" +#include "jni_util.h" +#include "jvm.h" +#include "jlong.h" +#include "sun_nio_ch_DatagramDispatcher.h" +#include +#include +#include + +#include "nio_util.h" + +JNIEXPORT jint JNICALL +Java_sun_nio_ch_DatagramDispatcher_read0(JNIEnv *env, jclass clazz, + jobject fdo, jlong address, jint len) +{ + jint fd = fdval(env, fdo); + void *buf = (void *)jlong_to_ptr(address); + int result = recv(fd, buf, len, 0); + if (result < 0 && errno == ECONNREFUSED) { + JNU_ThrowByName(env, JNU_JAVANETPKG "PortUnreachableException", 0); + return -2; + } + return convertReturnVal(env, result, JNI_TRUE); +} + + +JNIEXPORT jlong JNICALL +Java_sun_nio_ch_DatagramDispatcher_readv0(JNIEnv *env, jclass clazz, + jobject fdo, jlong address, jint len) +{ + jint fd = fdval(env, fdo); + ssize_t result = 0; + struct iovec *iov = (struct iovec *)jlong_to_ptr(address); + struct msghdr m; + if (len > 16) { + len = 16; + } + + m.msg_name = NULL; + m.msg_namelen = 0; + m.msg_iov = iov; + m.msg_iovlen = len; +#ifdef __solaris__ + m.msg_accrights = NULL; + m.msg_accrightslen = 0; +#endif + +#ifdef __linux__ + m.msg_control = NULL; + m.msg_controllen = 0; +#endif + + result = recvmsg(fd, &m, 0); + if (result < 0 && errno == ECONNREFUSED) { + JNU_ThrowByName(env, JNU_JAVANETPKG "PortUnreachableException", 0); + return -2; + } + return convertLongReturnVal(env, (jlong)result, JNI_TRUE); +} + +JNIEXPORT jint JNICALL +Java_sun_nio_ch_DatagramDispatcher_write0(JNIEnv *env, jclass clazz, + jobject fdo, jlong address, jint len) +{ + jint fd = fdval(env, fdo); + void *buf = (void *)jlong_to_ptr(address); + int result = send(fd, buf, len, 0); + if (result < 0 && errno == ECONNREFUSED) { + JNU_ThrowByName(env, JNU_JAVANETPKG "PortUnreachableException", 0); + return -2; + } + return convertReturnVal(env, result, JNI_FALSE); +} + +JNIEXPORT jlong JNICALL +Java_sun_nio_ch_DatagramDispatcher_writev0(JNIEnv *env, jclass clazz, + jobject fdo, jlong address, jint len) +{ + jint fd = fdval(env, fdo); + struct iovec *iov = (struct iovec *)jlong_to_ptr(address); + struct msghdr m; + ssize_t result = 0; + if (len > 16) { + len = 16; + } + + m.msg_name = NULL; + m.msg_namelen = 0; + m.msg_iov = iov; + m.msg_iovlen = len; +#ifdef __solaris__ + m.msg_accrights = NULL; + m.msg_accrightslen = 0; +#endif + +#ifdef __linux__ + m.msg_control = NULL; + m.msg_controllen = 0; +#endif + + result = sendmsg(fd, &m, 0); + if (result < 0 && errno == ECONNREFUSED) { + JNU_ThrowByName(env, JNU_JAVANETPKG "PortUnreachableException", 0); + return -2; + } + return convertLongReturnVal(env, (jlong)result, JNI_FALSE); +} diff --git a/pool/shard000/C/0009713_pn544_i2c_TestApp.c b/pool/shard000/C/0009713_pn544_i2c_TestApp.c new file mode 100644 index 0000000000000000000000000000000000000000..351131169aeaa1ada2b3f1dc145f67912b757d5b --- /dev/null +++ b/pool/shard000/C/0009713_pn544_i2c_TestApp.c @@ -0,0 +1,88 @@ +/* +* pn544_app.c +* Copyright (C) 2011 NXP Semiconductors +*/ + +/* +* Android.mk //TODO:Here is makefile reference +* LOCAL_PATH:= $(call my-dir) + +* include $(CLEAR_VARS) +* LOCAL_SRC_FILES:= pn544_app.c + +* LOCAL_MODULE:= pn544_app + +* include $(BUILD_EXECUTABLE) +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define _read_sample_test_size 0x04 + + +int main(int argc, char *argv[]) +{ + + int ret = 0; + int i = 0; + int fp = 0; + unsigned char send_reset[] = {0x05, 0xF9, 0x04, 0x00, 0xC3, 0xE5};//RSET Frame + unsigned char recv_response[40] = {0}; + + printf("pn544 iic driver test... ...\n"); + //open module + if ((ret = (fp = open("/dev/pn544", O_RDWR))) < 0) + { + printf("pn544 open error retcode = %d, errno = %d\n", ret, errno); + exit(0); + } + + //hardware reset + ioctl(fp, PN544_SET_PWR, 1); + ioctl(fp, PN544_SET_PWR, 0); + ioctl(fp, PN544_SET_PWR, 1); + + //write one RSET frame + if ((ret = (write(fp, send_reset, sizeof(send_reset))))<0) + { + printf("pn544 write error retcode = %d, errno = %d\n", ret, errno); + goto err_; + } + printf("PC->NFC: "); + for (i=0; iPC: "); + for (i=0;i<_read_sample_test_size;i++) + { + printf("%.2X ", recv_response[i]); + } + break; + } + sleep(1); + } + +err_: + close(fp); + return 0; +} diff --git a/pool/shard000/C/0009715_pr43879-3.c b/pool/shard000/C/0009715_pr43879-3.c new file mode 100644 index 0000000000000000000000000000000000000000..5ee80d5188d81231019da90bcf317429cdc29b36 --- /dev/null +++ b/pool/shard000/C/0009715_pr43879-3.c @@ -0,0 +1,41 @@ +/* { dg-do run } */ +/* { dg-options "-fipa-pta" } */ + +typedef unsigned long ulong; + +int __attribute__((noinline, noclone)) +f4 (int a, int b, int c, int d, int e) +{ + return a + b + c + d + e; +} + +void __attribute__((noinline, noclone)) +f3 (int *p) +{ + *p = f4(1, 2, 3, 4, 5); +} + +void __attribute__((noinline, noclone)) +f2 () +{ + int unused; + f3 (&unused); +} + +void __attribute__((noinline, noclone)) +f1 (ulong e, ulong f) +{ + if (e > 5 || f > 5) __builtin_abort(); + f2 (); +} + + +int main() +{ + ulong e, f; + for (e = 5; e > 0; e--) + for (f = 5; f > 0; f--) + f1(e, f); + return 0; +} + diff --git a/pool/shard000/C/0009730_storage.c b/pool/shard000/C/0009730_storage.c new file mode 100644 index 0000000000000000000000000000000000000000..f132a27a2f9cc1fb8e2b833011d7d3e68696e4ed --- /dev/null +++ b/pool/shard000/C/0009730_storage.c @@ -0,0 +1,31 @@ +#include "storage.h" + +Entry *create_entry(int type, const char *tag, uint32_t beginning, uint32_t end) { + Entry *entry = malloc(sizeof(Entry)); + entry->type = type; + entry->tag = tag; + entry->beginning = beginning; + entry->end = end; + return entry; +} + +int store_entry(Entry *entry) { + int num_entries = persist_read_int(NUM_ENTRIES_MEM_LOC); + if (num_entries == MAX_ENTRIES) return 0; + int mem_loc = NUM_ENTRIES_MEM_LOC + (++num_entries); + persist_write_data(mem_loc, entry, sizeof(Entry)); + persist_write_int(NUM_ENTRIES_MEM_LOC, num_entries); + return 1; +} + +Entry *retrieve_top_entry() { + int num_entries = persist_read_int(NUM_ENTRIES_MEM_LOC); + APP_LOG(APP_LOG_LEVEL_DEBUG, "Attempting to retrieve top entry: %d", num_entries); + if (num_entries == 0) return NULL; + Entry *entry = malloc(sizeof(Entry)); + int mem_loc = NUM_ENTRIES_MEM_LOC + num_entries; + persist_read_data(mem_loc, entry, sizeof(Entry)); + persist_delete(mem_loc); + persist_write_int(NUM_ENTRIES_MEM_LOC, num_entries - 1); + return entry; +} diff --git a/pool/shard000/C/0009733_c64exp-resources.c b/pool/shard000/C/0009733_c64exp-resources.c new file mode 100644 index 0000000000000000000000000000000000000000..b44b2de33e4d458040ececf00495d15e16cb7fa7 --- /dev/null +++ b/pool/shard000/C/0009733_c64exp-resources.c @@ -0,0 +1,170 @@ +/* + * c64exp-resources.c + * + * Written by + * Andreas Boose + * + * This file is part of VICE, the Versatile Commodore Emulator. + * See README for copyright notice. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + * 02111-1307 USA. + * + */ + +#include "vice.h" + +#include + +#include "c64exp-resources.h" +#include "drive.h" +#include "drivemem.h" +#include "lib.h" +#include "profdos.h" +#include "resources.h" +#include "supercard.h" +#include "util.h" + + +static char *profdos_1571_name = NULL; +static char *supercard_name = NULL; + + +static void set_drive_ram(unsigned int dnr) +{ + drive_t *drive = drive_context[dnr]->drive; + + if (drive->type != DRIVE_TYPE_1570 && drive->type != DRIVE_TYPE_1571 + && drive->type != DRIVE_TYPE_1571CR) { + return; + } + + drivemem_init(drive_context[dnr], drive->type); + + return; +} + +static int set_drive_parallel_cable(int val, void *param) +{ + drive_t *drive = drive_context[vice_ptr_to_uint(param)]->drive; + + switch (val) { + case DRIVE_PC_NONE: + case DRIVE_PC_STANDARD: + case DRIVE_PC_DD3: + case DRIVE_PC_FORMEL64: + break; + default: + return -1; + } + + drive->parallel_cable = val; + set_drive_ram(vice_ptr_to_uint(param)); + + return 0; +} + +static int set_drive_profdos(int val, void *param) +{ + drive_t *drive = drive_context[vice_ptr_to_uint(param)]->drive; + + drive->profdos = val ? 1 : 0; + set_drive_ram(vice_ptr_to_uint(param)); + + return 0; +} + +static int set_profdos_1571_name(const char *val, void *param) +{ + if (util_string_set(&profdos_1571_name, val)) { + return 0; + } + + return profdos_load_1571(profdos_1571_name); +} + +static int set_drive_supercard(int val, void *param) +{ + drive_t *drive = drive_context[vice_ptr_to_uint(param)]->drive; + + drive->supercard = val ? 1 : 0; + set_drive_ram(vice_ptr_to_uint(param)); + + return 0; +} + +static int set_supercard_name(const char *val, void *param) +{ + if (util_string_set(&supercard_name, val)) { + return 0; + } + + return supercard_load(supercard_name); +} + +static resource_int_t res_drive[] = { + { NULL, DRIVE_PC_NONE, RES_EVENT_SAME, NULL, + NULL, set_drive_parallel_cable, NULL }, + { NULL, 0, RES_EVENT_SAME, NULL, + NULL, set_drive_profdos, NULL }, + { NULL, 0, RES_EVENT_SAME, NULL, + NULL, set_drive_supercard, NULL }, + { NULL } +}; + +static const resource_string_t resources_string[] = +{ + { "DriveProfDOS1571Name", "", RES_EVENT_NO, NULL, + &profdos_1571_name, set_profdos_1571_name, NULL }, + { "DriveSuperCardName", "", RES_EVENT_NO, NULL, + &supercard_name, set_supercard_name, NULL }, + { NULL } +}; + +int c64exp_resources_init(void) +{ + unsigned int dnr; + drive_t *drive; + + for (dnr = 0; dnr < DRIVE_NUM; dnr++) { + drive = drive_context[dnr]->drive; + + res_drive[0].name = lib_msprintf("Drive%iParallelCable", dnr + 8); + res_drive[0].value_ptr = &(drive->parallel_cable); + res_drive[0].param = uint_to_void_ptr(dnr); + res_drive[1].name = lib_msprintf("Drive%iProfDOS", dnr + 8); + res_drive[1].value_ptr = &(drive->profdos); + res_drive[1].param = uint_to_void_ptr(dnr); + res_drive[2].name = lib_msprintf("Drive%iSuperCard", dnr + 8); + res_drive[2].value_ptr = &(drive->supercard); + res_drive[2].param = uint_to_void_ptr(dnr); + + if (resources_register_int(res_drive) < 0) { + return -1; + } + + lib_free((char *)(res_drive[0].name)); + lib_free((char *)(res_drive[1].name)); + lib_free((char *)(res_drive[2].name)); + } + + return resources_register_string(resources_string); +} + +void c64exp_resources_shutdown(void) +{ + lib_free(profdos_1571_name); + lib_free(supercard_name); +} diff --git a/pool/shard000/C/0009740_ft_printvec.c b/pool/shard000/C/0009740_ft_printvec.c new file mode 100644 index 0000000000000000000000000000000000000000..ee8e43b141fa997b30863ad364b873933faf2360 --- /dev/null +++ b/pool/shard000/C/0009740_ft_printvec.c @@ -0,0 +1,36 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* ft_printvec.c :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: ncoden +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2014/11/27 12:06:18 by ncoden #+# #+# */ +/* Updated: 2015/09/02 09:14:58 by ncoden ### ########.fr */ +/* */ +/* ************************************************************************** */ + +#include +#include +#include "libft-graphics/2denv.h" +#include "libft-graphics/vec.h" + +void ft_printvec(t_2denv *e, t_vec *vec, int color) +{ + int len; + double xang; + double yang; + + if (e && vec) + { + xang = cos(vec->ang); + yang = sin(vec->ang); + len = vec->len; + while (len >= 0) + { + mlx_pixel_put(e->mlx, e->win, (vec->pos).x + len * xang, + (vec->pos).y + len * yang, color); + len--; + } + } +} diff --git a/pool/shard000/C/0009744_despiker_4741.c b/pool/shard000/C/0009744_despiker_4741.c new file mode 100644 index 0000000000000000000000000000000000000000..0b54b55d4a53f8cbf23303517ca1619d4e03db62 --- /dev/null +++ b/pool/shard000/C/0009744_despiker_4741.c @@ -0,0 +1,286 @@ +/**************************************************************************** + * Despiker + * + * Copyright (C) Jean Zundel 2012 + * + * Removes crackles provoked by signal spikes, for example snare overloads, + * by selectively applying a low-pass filter to half-waves reaching a given + * treshold using a convolution matrix - leaving other parts untouched. + * + * Plugin structure inherited from amp.c: + * This file has poor memory protection. Failures during malloc() will + * not recover nicely. + * + * 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. + * + *****************************************************************************/ + +#include +#include +#include +#include + +#include "ladspa.h" + + +typedef struct { + LADSPA_Data * m_pfInputBuffer1; + LADSPA_Data * m_pfOutputBuffer1; +} Despiker; + +#define DESPIKER_INPUT1 0 +#define DESPIKER_OUTPUT1 1 + + +/* Yeuch */ + +#ifdef WIN32 +#define _WINDOWS_DLL_EXPORT_ __declspec(dllexport) +int bIsFirstTime = 1; +void _init(); // forward declaration +#else +#define _WINDOWS_DLL_EXPORT_ +#endif + + +/* Plugin-specific defines */ + +#define TRESHOLD 0.9 +#define HLF_CNVL 8 +#define LEN_CNVL (2*HLF_CNVL+1) + + +/* Convolution matrix */ + +// If 16 surrounding points act on a given point, then the cutoff frequency +// could well be something like 22050/8 = 2756 Hz. Perhaps. Slope is unknown. + + +LADSPA_Data matrix [LEN_CNVL] = { // Mean should be 1 + 0.2, 0.4, 0.6, 0.8, 1, 1.2, 1.4, 1.6, + 2.6, + 1.6, 1.4, 1.2, 1, 0.8, 0.6, 0.4, 0.2 +}; + +LADSPA_Data *cnvl = matrix + HLF_CNVL; // Center pointer + + +/***************************************************************************** + * Apply a convolution matrix to all points in the marked area + *****************************************************************************/ + +void convolve (LADSPA_Data *in, // Input buffer + LADSPA_Data *out, // Output buffer + unsigned long start, + unsigned long stop, + unsigned long smplcnt) { + + unsigned long i; + long c; + + LADSPA_Data sum; + + if ((start - HLF_CNVL < 0) || // Fast, clean, cheap: if the very + (stop + HLF_CNVL + 1 > smplcnt)) // first/last samples of the track + for (i = start ; i < stop ; i++) // are clipping, zero out this part + out [i] = 0; // Causes issues on small selections + else + for (i = start; i < stop ; i++) { // Apply matrix + sum = 0; + for (c = -HLF_CNVL ; c <= HLF_CNVL; c++) + sum += in [i+c] * cnvl [c]; + out [i] = sum / LEN_CNVL; + } +} + + +/***************************************************************************** + * Copy input to output, scan half-waves for spikes, call convolve() + *****************************************************************************/ + +void runDespiker (LADSPA_Handle Instance, + unsigned long SampleCount) { + + + LADSPA_Data *in; + LADSPA_Data *out; + Despiker *psDespiker; + unsigned long i; + + unsigned long wave_start = 0; + int clipping = 0; + + psDespiker = (Despiker *) Instance; + + in = psDespiker->m_pfInputBuffer1; + out = psDespiker->m_pfOutputBuffer1; + + for (i = 0; i < SampleCount; i++) { + out [i] = in [i]; + if ((clipping) && + (in [i] * in [i+1] < 0)) { // Rewrite former half-wave + convolve (in, + out, + wave_start, + i, + SampleCount); + clipping = 0; + continue; + } + if (fabs (in [i]) >= TRESHOLD) { // Uh oh + clipping = 1; + continue; + } + if ((!clipping) && + (in [i] * in [i+1] < 0)) { // Keep track of wave crossing 0 + wave_start = i; + } + } +} + + +/*****************************************************************************/ + +LADSPA_Handle instantiateDespiker (const LADSPA_Descriptor * Descriptor, + unsigned long SampleRate) { + return malloc (sizeof (Despiker)); +} + +/*****************************************************************************/ + +void connectPortToDespiker (LADSPA_Handle Instance, + unsigned long Port, + LADSPA_Data * DataLocation) { + + Despiker * psDespiker; + + psDespiker = (Despiker *) Instance; + switch (Port) { + case DESPIKER_INPUT1: + psDespiker->m_pfInputBuffer1 = DataLocation; + break; + case DESPIKER_OUTPUT1: + psDespiker->m_pfOutputBuffer1 = DataLocation; + break; + } +} + +/*****************************************************************************/ + +void cleanupDespiker (LADSPA_Handle Instance) { + + free (Instance); +} + +/*****************************************************************************/ + +LADSPA_Descriptor * g_psDespikerDescr = NULL; + +/*****************************************************************************/ +/* _init() is called automatically when the plugin library is first + loaded. */ + +void _init() { + + char ** pcPortNames; + LADSPA_PortDescriptor * piPortDescriptors; + LADSPA_PortRangeHint * psPortRangeHints; + + g_psDespikerDescr + = (LADSPA_Descriptor *) malloc (sizeof (LADSPA_Descriptor)); + + if (g_psDespikerDescr) { + + g_psDespikerDescr->UniqueID = 4741; + g_psDespikerDescr->Label = strdup ("Despiker"); + g_psDespikerDescr->Properties + = LADSPA_PROPERTY_HARD_RT_CAPABLE; + g_psDespikerDescr->Name = strdup ("Despiker"); + g_psDespikerDescr->Maker = strdup ("Jean Zundel"); + g_psDespikerDescr->Copyright = strdup ("GPL v3"); + g_psDespikerDescr->PortCount = 2; + piPortDescriptors + = (LADSPA_PortDescriptor *) calloc (2, sizeof (LADSPA_PortDescriptor)); + g_psDespikerDescr->PortDescriptors + = (const LADSPA_PortDescriptor *) piPortDescriptors; + piPortDescriptors [DESPIKER_INPUT1] + = LADSPA_PORT_INPUT | LADSPA_PORT_AUDIO; + piPortDescriptors [DESPIKER_OUTPUT1] + = LADSPA_PORT_OUTPUT | LADSPA_PORT_AUDIO; + pcPortNames + = (char **) calloc (2, sizeof(char *)); + g_psDespikerDescr->PortNames + = (const char **) pcPortNames; + pcPortNames [DESPIKER_INPUT1] = strdup ("Input"); + pcPortNames [DESPIKER_OUTPUT1] = strdup ("Output"); + psPortRangeHints + = ((LADSPA_PortRangeHint *) calloc (2, sizeof (LADSPA_PortRangeHint))); + g_psDespikerDescr->PortRangeHints + = (const LADSPA_PortRangeHint *) psPortRangeHints; + psPortRangeHints [DESPIKER_INPUT1].HintDescriptor = 0; + psPortRangeHints [DESPIKER_OUTPUT1].HintDescriptor = 0; + g_psDespikerDescr->instantiate = instantiateDespiker; + g_psDespikerDescr->connect_port = connectPortToDespiker; + g_psDespikerDescr->activate = NULL; + g_psDespikerDescr->run = runDespiker; + g_psDespikerDescr->run_adding = NULL; + g_psDespikerDescr->deactivate = NULL; + g_psDespikerDescr->cleanup = cleanupDespiker; + } +} + +/*****************************************************************************/ + +void deleteDescriptor (LADSPA_Descriptor * psDescriptor) { + + unsigned long lIndex; + + if (psDescriptor) { + free ((char *)psDescriptor->Label); + free ((char *)psDescriptor->Name); + free ((char *)psDescriptor->Maker); + free ((char *)psDescriptor->Copyright); + free ((LADSPA_PortDescriptor *)psDescriptor->PortDescriptors); + for (lIndex = 0; lIndex < psDescriptor->PortCount; lIndex++) + free ((char *)(psDescriptor->PortNames[lIndex])); + free ((char **)psDescriptor->PortNames); + free ((LADSPA_PortRangeHint *)psDescriptor->PortRangeHints); + free (psDescriptor); + } +} + +/*****************************************************************************/ +/* _fini() is called automatically when the library is unloaded. */ + +void _fini() { + + deleteDescriptor (g_psDespikerDescr); +} + +/*****************************************************************************/ + +_WINDOWS_DLL_EXPORT_ +const LADSPA_Descriptor *ladspa_descriptor (unsigned long Index) { + +#ifdef WIN32 + if (bIsFirstTime) { + _init(); + bIsFirstTime = 0; + } +#endif + + if (Index == 0) + return g_psDespikerDescr; + else + return NULL; +} + + diff --git a/pool/shard000/C/0009791_cuboot-warp.c b/pool/shard000/C/0009791_cuboot-warp.c new file mode 100644 index 0000000000000000000000000000000000000000..1ec0fa28480b5bb73ea6cf9936b29efd2072809c --- /dev/null +++ b/pool/shard000/C/0009791_cuboot-warp.c @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * Copyright (c) 2008 PIKA Technologies + * Sean MacLennan + */ + +#include "ops.h" +#include "4xx.h" +#include "cuboot.h" +#include "stdio.h" + +#define TARGET_4xx +#define TARGET_44x +#include "ppcboot.h" + +static bd_t bd; + +static void warp_fixups(void) +{ + ibm440ep_fixup_clocks(66000000, 11059200, 50000000); + ibm4xx_sdram_fixup_memsize(); + ibm4xx_fixup_ebc_ranges("/plb/opb/ebc"); + dt_fixup_mac_address_by_alias("ethernet0", bd.bi_enetaddr); +} + +void platform_init(unsigned long r3, unsigned long r4, unsigned long r5, + unsigned long r6, unsigned long r7) +{ + CUBOOT_INIT(); + + platform_ops.fixups = warp_fixups; + platform_ops.exit = ibm44x_dbcr_reset; + fdt_init(_dtb_start); + serial_console_init(); +} diff --git a/pool/shard000/C/0009805_alternate_cbfs.c b/pool/shard000/C/0009805_alternate_cbfs.c new file mode 100644 index 0000000000000000000000000000000000000000..9fef9ae377b54b5be153b24af973df6637f2632d --- /dev/null +++ b/pool/shard000/C/0009805_alternate_cbfs.c @@ -0,0 +1,151 @@ +/* + * This file is part of the coreboot project. + * + * Copyright 2013 Google Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; 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. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +/* This allows USB A-A firmware upload from a compatible host in four parts: + * The first two are the bare BL1 and the coreboot boot block, which are just + * written to their respective loading addresses. These transfers are initiated + * by the IROM / BL1, so this code has nothing to do with them. + * + * The third transfer is a valid CBFS image that contains only the romstage, + * and must be small enough to fit into the PRE_RAM CBFS cache in + * IRAM. It is loaded when this function gets called in the boot block, and + * the normal CBFS code extracts the romstage from it. + * + * The fourth transfer is also a CBFS image, but can be of arbitrary size and + * should contain all available stages/payloads/etc. It is loaded when this + * function is called a second time at the end of the romstage, and copied to + * the romstage/ramstage CBFS cache in DRAM. It will reside there for the + * rest of the firmware's lifetime and all subsequent stages (which will not + * have __PRE_RAM__ defined) can just directly reference it there. + */ +static int usb_cbfs_open(void) +{ +#ifdef __PRE_RAM__ + static int first_run = 1; + int (*irom_load_usb)(void) = *irom_load_image_from_usb_ptr; + + if (!first_run) + return 0; + + if (!irom_load_usb()) { + printk(BIOS_EMERG, "Unable to load CBFS image via USB!\n"); + return -1; + } + + /* + * We need to trust the host/irom to copy the image to our + * _cbfs_cache address... there is no way to control or even + * check the transfer size or target address from our side. + */ + + printk(BIOS_DEBUG, "USB A-A transfer successful, CBFS image should now" + " be at %p\n", _cbfs_cache); + first_run = 0; +#endif + return 0; +} + +/* + * SDMMC works very similar to USB A-A: we copy the CBFS image into memory + * and read it from there. While SDMMC would also allow direct block by block + * on-demand reading, we might run into problems if we call back into the IROM + * in very late boot stages (e.g. after initializing/changing MMC clocks)... so + * this seems like a safer approach. It also makes it easy to pass our image + * down to payloads. + */ +static int sdmmc_cbfs_open(void) +{ +#ifdef __PRE_RAM__ + /* + * In the bootblock, we just copy the small part that fits in the buffer + * and hope that it's enough (since the romstage is currently always the + * first component in the image, this should work out). In the romstage, + * we copy until our cache is full (currently 12M) to avoid the pain of + * figuring out the true image size from in here. Since this is mainly a + * developer/debug boot mode, those shortcomings should be bearable. + */ + const u32 count = REGION_SIZE(cbfs_cache) / 512; + static int first_run = 1; + int (*irom_load_sdmmc)(u32 start, u32 count, void *dst) = + *irom_sdmmc_read_blocks_ptr; + + if (!first_run) + return 0; + + if (!irom_load_sdmmc(1, count, _cbfs_cache)) { + printk(BIOS_EMERG, "Unable to load CBFS image from SDMMC!\n"); + return -1; + } + + printk(BIOS_DEBUG, "SDMMC read successful, CBFS image should now be" + " at %p\n", _cbfs_cache); + first_run = 0; +#endif + return 0; +} + +static struct mem_region_device alternate_rdev = + MEM_REGION_DEV_RO_INIT(NULL, 0); + +const struct region_device *boot_device_ro(void) +{ + if (*iram_secondary_base == SECONDARY_BASE_BOOT_USB) + return &alternate_rdev.rdev; + + switch (exynos_power->om_stat & OM_STAT_MASK) { + case OM_STAT_SDMMC: + return &alternate_rdev.rdev; + case OM_STAT_SPI: + return exynos_spi_boot_device(); + default: + printk(BIOS_EMERG, "Exynos OM_STAT value 0x%x not supported!\n", + exynos_power->om_stat); + return NULL; + } +} + +void boot_device_init(void) +{ + mem_region_device_ro_init(&alternate_rdev, _cbfs_cache, + REGION_SIZE(cbfs_cache)); + + if (*iram_secondary_base == SECONDARY_BASE_BOOT_USB) { + printk(BIOS_DEBUG, "Using Exynos alternate boot mode USB A-A\n"); + usb_cbfs_open(); + return; + } + + switch (exynos_power->om_stat & OM_STAT_MASK) { + case OM_STAT_SDMMC: + printk(BIOS_DEBUG, "Using Exynos alternate boot mode SDMMC\n"); + sdmmc_cbfs_open(); + break; + case OM_STAT_SPI: + exynos_init_spi_boot_device(); + break; + default: + printk(BIOS_EMERG, "Exynos OM_STAT value 0x%x not supported!\n", + exynos_power->om_stat); + } +} diff --git a/pool/shard000/C/0009806_lapack_wrapper.c b/pool/shard000/C/0009806_lapack_wrapper.c new file mode 100644 index 0000000000000000000000000000000000000000..aedff159af45f01bf05426cefa45d1985c3e5dc7 --- /dev/null +++ b/pool/shard000/C/0009806_lapack_wrapper.c @@ -0,0 +1,95 @@ +#include"lapack_wrapper.h" +#include +#include +#include +#include +#include +/*! \fn void eigenvalue_decomposition(double **matrix, int nmatrix, double *&lambda, double **e_vectors) + * \brief Compute the eigenvalues of a symmetric. + * real matrix via lapack. + * + * The eigenvalues are calculated and put in lambda. + * The eigenvectors are calculated and put in the columns of e_vectors. */ +void eigenvalue_decomposition(double **matrix, int nmatrix, double *lambda, double **e_vectors) +{ + integer n = nmatrix; + integer lda = nmatrix; + integer ldz = nmatrix; + char uplo = 'U'; + char compz = 'V'; + doublereal *A; //symmetric matrix A + doublereal *D; //diagonal elements of tridiagonal matrix T + doublereal *E; //off-diagonal elemetns of tridiagonal matrix T + doublereal *tau; //scalar factors of elementary reflectors + doublereal *ptr; + doublereal *work; + doublereal *z; + + integer info; + integer lgN = ((int) log(n)/log(2)) + 1; + integer lwork = 1 + 3*n + 2*n*lgN + 3*n*n; + integer liwork = 6 + 6*n + 5*n*lgN; + integer *iwork; + + int ntest = n*n; + + lwork = n*ntest; + + A = (doublereal *) malloc( lda*n*sizeof(doublereal) ); + D = (doublereal *) malloc( n*sizeof(doublereal) ); + E = (doublereal *) malloc( (n-1)*sizeof(doublereal ) ); + tau = (doublereal *) malloc( n*sizeof(doublereal ) ); + work = (doublereal *) malloc( lwork*sizeof(doublereal) ); + + //first, store the symmetrical matrix into A + ptr = A; + for(int j=0; j +#include +#include +#include +#include +#include "hopest_p4est_geom.h" + +#include + +int main(int argc,char *argv[]){ + char *HDF5File; + int HDF5file_len; + /* p4est_t *p4est; */ + p4est_connectivity_t *conn; + p4est_t *p4est; + p4est_geometry_t *geom; + char vtkfilename[BUFSIZ],*vtkfilename_temp; + int mpiret; + + mpiret = sc_MPI_Init (&argc, &argv); + SC_CHECK_MPI (mpiret); + if(argc>1) { + HDF5File=argv[1]; + HDF5file_len=strlen(HDF5File); + ReadMeshFromHDF5_FC(HDF5File,HDF5file_len,&conn); + P4EST_ASSERT(p4est_connectivity_is_valid(conn)); + p4est=p4est_new_ext(sc_MPI_COMM_WORLD,conn,0,2,1,0,NULL,NULL); + geom = P4EST_ALLOC_ZERO (p4est_geometry_t, 1); + geom->name = "hopest_readfromhdf5"; + geom->X = p4_geometry_X; + vtkfilename_temp=P4EST_STRDUP(HDF5File); + basename(vtkfilename_temp); + snprintf (vtkfilename, BUFSIZ, "%s", vtkfilename_temp); + p4est_vtk_write_file (p4est,geom,vtkfilename); + P4EST_FREE(vtkfilename_temp); + p4est_geometry_destroy(geom); + p4est_destroy(p4est); + p4est_connectivity_destroy(conn); + } + else printf("no input file given.\n"); + mpiret = sc_MPI_Finalize (); + SC_CHECK_MPI (mpiret); + return 0; +} diff --git a/pool/shard000/C/0009822_apm32f10x_pmu.c b/pool/shard000/C/0009822_apm32f10x_pmu.c new file mode 100644 index 0000000000000000000000000000000000000000..b32726e0df99be441cbf044b70f28524f39096ba --- /dev/null +++ b/pool/shard000/C/0009822_apm32f10x_pmu.c @@ -0,0 +1,268 @@ +/*! + * @file apm32f10x_pmu.c + * + * @brief This file provides all the PMU firmware functions. + * + * @version V1.0.2 + * + * @date 2022-01-05 + * + * @attention + * + * Copyright (C) 2020-2022 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be usefull and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +#include "apm32f10x_pmu.h" +#include "apm32f10x_rcm.h" + +/** @addtogroup Peripherals_Library Standard Peripheral Library + @{ +*/ + +/** @addtogroup PMU_Driver PMU Driver + @{ +*/ + +/** @addtogroup PMU_Fuctions Fuctions + @{ +*/ + +/*! + * @brief Reset the PMU peripheral register. + * + * @param None + * + * @retval None + */ +void PMU_Reset(void) +{ + RCM_EnableAPB1PeriphReset(RCM_APB1_PERIPH_PMU); + RCM_DisableAPB1PeriphReset(RCM_APB1_PERIPH_PMU); +} + +/*! + * @brief Enables access to the RTC and backup registers. + * + * @param None + * + * @retval None + */ +void PMU_EnableBackupAccess(void) +{ + PMU->CTRL_B.BPWEN = ENABLE ; +} + +/*! + * @brief Disables access to the RTC and backup registers. + * + * @param None + * + * @retval None + */ +void PMU_DisableBackupAccess(void) +{ + PMU->CTRL_B.BPWEN = DISABLE; +} + +/*! + * @brief Enables the Power Voltage Detector(PVD). + * + * @param None + * + * @retval None + */ +void PMU_EnablePVD(void) +{ + PMU->CTRL_B.PVDEN = ENABLE; +} + +/*! + * @brief Disables the Power Voltage Detector(PVD). + * + * @param None + * + * @retval None + */ +void PMU_DisablePVD(void) +{ + PMU->CTRL_B.PVDEN = DISABLE; +} + +/*! + * @brief Configure a voltage threshold detected by a power supply voltage detector (PVD). + * + * @param level:specifies the PVD detection level + * This parameter can be one of the following values: + * @arg PMU_PVD_LEVEL_2V2 : Config PVD detection level to 2.2V + * @arg PMU_PVD_LEVEL_2V3 : Config PVD detection level to 2.3V + * @arg PMU_PVD_LEVEL_2V4 : Config PVD detection level to 2.4V + * @arg PMU_PVD_LEVEL_2V5 : Config PVD detection level to 2.5V + * @arg PMU_PVD_LEVEL_2V6 : Config PVD detection level to 2.6V + * @arg PMU_PVD_LEVEL_2V7 : Config PVD detection level to 2.7V + * @arg PMU_PVD_LEVEL_2V8 : Config PVD detection level to 2.8V + * @arg PMU_PVD_LEVEL_2V9 : Config PVD detection level to 2.9V + * + * @retval None + */ +void PMU_ConfigPVDLevel(PMU_PVD_LEVEL_T level) +{ + + /** Clear PLS[7:5] bits */ + PMU->CTRL_B.PLSEL = 0x0000; + /** Store the new value */ + PMU->CTRL_B.PLSEL = level; +} + +/*! + * @brief Enables the WakeUp Pin functionality. + * + * @param None + * + * @retval None + */ +void PMU_EnableWakeUpPin(void) +{ + PMU->CSTS_B.WKUPCFG = ENABLE ; +} + +/*! + * @brief Diaables the WakeUp Pin functionality. + * + * @param None + * + * @retval None + */ +void PMU_DisableWakeUpPin(void) +{ + PMU->CSTS_B.WKUPCFG = DISABLE ; +} + +/*! + * @brief Enters STOP mode. + * + * @param regulator: specifies the regulator state in STOP mode. + * This parameter can be one of the following values: + * @arg PMU_REGULATOR_ON : STOP mode with regulator ON + * @arg PMU_REGULATOR_LOWPOWER: STOP mode with regulator in low power mode + * + * @param entry: specifies if STOP mode in entered with WFI or WFE instruction. + * This parameter can be one of the following values: + * @arg PMU_STOP_ENTRY_WFI: Enter STOP mode with WFI instruction + * @arg PMU_STOP_ENTRY_WFE: Enter STOP mode with WFE instruction + * + * @retval None + */ +void PMU_EnterSTOPMode(PMU_REGULATOR_T regulator, PMU_STOP_ENTRY_T entry) +{ + /** Clear PDDSCFG and LPDSCFG bits */ + PMU->CTRL_B.PDDSCFG = 0x00; + PMU->CTRL_B.LPDSCFG = 0x00; + /** Set LPDSCFG bit according to regulator value */ + PMU->CTRL_B.LPDSCFG = regulator; + /** Set Cortex System Control Register */ + SCB->SCR |= (uint32_t)0x04; + /** Select STOP mode entry*/ + if (entry == PMU_STOP_ENTRY_WFI) + { + /** Request Wait For Interrupt */ + __WFI(); + } + else + { + /** Request Wait For Event */ + __WFE(); + } + + /** Reset SLEEPDEEP bit of Cortex System Control Register */ + SCB->SCR &= (uint32_t)~((uint32_t)0x04); +} + +/*! + * @brief Enters STANDBY mode. + * + * @param None + * + * @retval None + */ +void PMU_EnterSTANDBYMode(void) +{ + /** Clear Wake-up flag */ + PMU->CTRL_B.WUFLGCLR = BIT_SET; + /** Select STANDBY mode */ + PMU->CTRL_B.PDDSCFG = BIT_SET; + /** Set Cortex System Control Register */ + SCB->SCR |= (uint32_t)0x04; +#if defined ( __CC_ARM ) + __force_stores(); +#endif + /** Request Wait For Interrupt */ + __WFI(); + +} + +/*! + * @brief Read the specified PWR flag is set or not. + * + * @param flag:Reads the status of specifies the flag. + * This parameter can be one of the following values: + * @arg PMU_FLAG_WUE : Wake Up flag + * @arg PMU_FLAG_SB : StandBy flag + * @arg PMU_FLAG_PVDO: PVD Output flag + * + * @retval The new state of PMU_FLAG (SET or RESET). + */ +uint8_t PMU_ReadStatusFlag(PMU_FLAG_T flag) +{ + uint8_t BitStatus = BIT_RESET; + + if (flag == PMU_FLAG_WUE) + { + BitStatus = PMU->CSTS_B.WUEFLG; + } + else if (flag == PMU_FLAG_SB) + { + BitStatus = PMU->CSTS_B.SBFLG; + } + else if (flag == PMU_FLAG_PVDO) + { + BitStatus = PMU->CSTS_B.PVDOFLG; + } + return BitStatus; +} + +/*! + * @brief Clears the PWR's pending flags. + * + * @param flag:Clears the status of specifies the flag. + * This parameter can be one of the following values: + * @arg PMU_FLAG_WUE : Wake Up flag + * @arg PMU_FLAG_SB : StandBy flag + * + * @retval None + */ +void PMU_ClearStatusFlag(PMU_FLAG_T flag) +{ + if (flag == PMU_FLAG_WUE) + { + PMU->CTRL_B.WUFLGCLR = BIT_SET; + } + else if (flag == PMU_FLAG_SB) + { + PMU->CTRL_B.SBFLGCLR = BIT_SET; + } +} + +/**@} end of group PMU_Fuctions*/ +/**@} end of group PMU_Driver*/ +/**@} end of group Peripherals_Library*/ diff --git a/pool/shard000/C/0009825_lowelabArkinOperonScore.c b/pool/shard000/C/0009825_lowelabArkinOperonScore.c new file mode 100644 index 0000000000000000000000000000000000000000..50befdbf09fa594134fab8d9f9683e2cb3791549 --- /dev/null +++ b/pool/shard000/C/0009825_lowelabArkinOperonScore.c @@ -0,0 +1,144 @@ +/* lowelabArkinOperonScore.c was originally generated by the autoSql program, which also + * generated lowelabArkinOperonScore.h and lowelabArkinOperonScore.sql. This module links the database and + * the RAM representation of objects. */ + +/* Copyright (C) 2014 The Regents of the University of California + * See README in this or parent directory for licensing information. */ + +#include "common.h" +#include "linefile.h" +#include "dystring.h" +#include "jksql.h" +#include "lowelabArkinOperonScore.h" + + +void lowelabArkinOperonScoreStaticLoad(char **row, struct lowelabArkinOperonScore *ret) +/* Load a row from lowelabArkinOperonScore table into ret. The contents of ret will + * be replaced at the next call to this function. */ +{ + +ret->name = row[0]; +ret->gene1 = row[1]; +ret->gene2 = row[2]; +ret->prob = sqlFloat(row[3]); +ret->gnMinus = sqlFloat(row[4]); +} + +struct lowelabArkinOperonScore *lowelabArkinOperonScoreLoad(char **row) +/* Load a lowelabArkinOperonScore from row fetched with select * from lowelabArkinOperonScore + * from database. Dispose of this with lowelabArkinOperonScoreFree(). */ +{ +struct lowelabArkinOperonScore *ret; + +AllocVar(ret); +ret->name = cloneString(row[0]); +ret->gene1 = cloneString(row[1]); +ret->gene2 = cloneString(row[2]); +ret->prob = sqlFloat(row[3]); +ret->gnMinus = sqlFloat(row[4]); +return ret; +} + +struct lowelabArkinOperonScore *lowelabArkinOperonScoreLoadAll(char *fileName) +/* Load all lowelabArkinOperonScore from a whitespace-separated file. + * Dispose of this with lowelabArkinOperonScoreFreeList(). */ +{ +struct lowelabArkinOperonScore *list = NULL, *el; +struct lineFile *lf = lineFileOpen(fileName, TRUE); +char *row[5]; + +while (lineFileRow(lf, row)) + { + el = lowelabArkinOperonScoreLoad(row); + slAddHead(&list, el); + } +lineFileClose(&lf); +slReverse(&list); +return list; +} + +struct lowelabArkinOperonScore *lowelabArkinOperonScoreLoadAllByChar(char *fileName, char chopper) +/* Load all lowelabArkinOperonScore from a chopper separated file. + * Dispose of this with lowelabArkinOperonScoreFreeList(). */ +{ +struct lowelabArkinOperonScore *list = NULL, *el; +struct lineFile *lf = lineFileOpen(fileName, TRUE); +char *row[5]; + +while (lineFileNextCharRow(lf, chopper, row, ArraySize(row))) + { + el = lowelabArkinOperonScoreLoad(row); + slAddHead(&list, el); + } +lineFileClose(&lf); +slReverse(&list); +return list; +} + +struct lowelabArkinOperonScore *lowelabArkinOperonScoreCommaIn(char **pS, struct lowelabArkinOperonScore *ret) +/* Create a lowelabArkinOperonScore out of a comma separated string. + * This will fill in ret if non-null, otherwise will + * return a new lowelabArkinOperonScore */ +{ +char *s = *pS; + +if (ret == NULL) + AllocVar(ret); +ret->name = sqlStringComma(&s); +ret->gene1 = sqlStringComma(&s); +ret->gene2 = sqlStringComma(&s); +ret->prob = sqlFloatComma(&s); +ret->gnMinus = sqlFloatComma(&s); +*pS = s; +return ret; +} + +void lowelabArkinOperonScoreFree(struct lowelabArkinOperonScore **pEl) +/* Free a single dynamically allocated lowelabArkinOperonScore such as created + * with lowelabArkinOperonScoreLoad(). */ +{ +struct lowelabArkinOperonScore *el; + +if ((el = *pEl) == NULL) return; +freeMem(el->name); +freeMem(el->gene1); +freeMem(el->gene2); +freez(pEl); +} + +void lowelabArkinOperonScoreFreeList(struct lowelabArkinOperonScore **pList) +/* Free a list of dynamically allocated lowelabArkinOperonScore's */ +{ +struct lowelabArkinOperonScore *el, *next; + +for (el = *pList; el != NULL; el = next) + { + next = el->next; + lowelabArkinOperonScoreFree(&el); + } +*pList = NULL; +} + +void lowelabArkinOperonScoreOutput(struct lowelabArkinOperonScore *el, FILE *f, char sep, char lastSep) +/* Print out lowelabArkinOperonScore. Separate fields with sep. Follow last field with lastSep. */ +{ +if (sep == ',') fputc('"',f); +fprintf(f, "%s", el->name); +if (sep == ',') fputc('"',f); +fputc(sep,f); +if (sep == ',') fputc('"',f); +fprintf(f, "%s", el->gene1); +if (sep == ',') fputc('"',f); +fputc(sep,f); +if (sep == ',') fputc('"',f); +fprintf(f, "%s", el->gene2); +if (sep == ',') fputc('"',f); +fputc(sep,f); +fprintf(f, "%g", el->prob); +fputc(sep,f); +fprintf(f, "%g", el->gnMinus); +fputc(lastSep,f); +} + +/* -------------------------------- End autoSql Generated Code -------------------------------- */ + diff --git a/pool/shard000/C/0009832_bw_pipe.c b/pool/shard000/C/0009832_bw_pipe.c new file mode 100644 index 0000000000000000000000000000000000000000..27cf57f543977acaf68314f2aa72e4dc0b4e448e --- /dev/null +++ b/pool/shard000/C/0009832_bw_pipe.c @@ -0,0 +1,71 @@ +/* include bw_pipe1 */ +#include "unpipc.h" + +void reader(int, int, int); +void writer(int, int); + +void *buf; +int totalnbytes, xfersize; + +int +main(int argc, char **argv) +{ + int i, nloop, contpipe[2], datapipe[2]; + pid_t childpid; + + if (argc != 4) + err_quit("usage: bw_pipe <#loops> <#mbytes> <#bytes/write>"); + nloop = atoi(argv[1]); + totalnbytes = atoi(argv[2]) * 1024 * 1024; + xfersize = atoi(argv[3]); + + buf = Valloc(xfersize); + Touch(buf, xfersize); + + Pipe(contpipe); + Pipe(datapipe); + + if ( (childpid = Fork()) == 0) { + writer(contpipe[0], datapipe[1]); /* child */ + exit(0); + } + /* 4parent */ + Start_time(); + for (i = 0; i < nloop; i++) + reader(contpipe[1], datapipe[0], totalnbytes); + printf("bandwidth: %.3f MB/sec\n", + totalnbytes / Stop_time() * nloop); + kill(childpid, SIGTERM); + exit(0); +} +/* end bw_pipe1 */ + +/* include bw_pipe2 */ +void +writer(int contfd, int datafd) +{ + int ntowrite; + + for ( ; ; ) { + Read(contfd, &ntowrite, sizeof(ntowrite)); + + while (ntowrite > 0) { + Write(datafd, buf, xfersize); + ntowrite -= xfersize; + } + } +} + +void +reader(int contfd, int datafd, int nbytes) +{ + ssize_t n; + + Write(contfd, &nbytes, sizeof(nbytes)); + + while ((nbytes > 0) && + ( (n = Read(datafd, buf, xfersize)) > 0)) { + nbytes -= n; + } +} +/* end bw_pipe2 */ diff --git a/pool/shard000/C/0009833_adc.c b/pool/shard000/C/0009833_adc.c new file mode 100644 index 0000000000000000000000000000000000000000..9b0f0259fc076ad41e6a96538f5d6b3abf0fa0aa --- /dev/null +++ b/pool/shard000/C/0009833_adc.c @@ -0,0 +1,136 @@ +/** + ****************************************************************************** + * File Name : ADC.c + * Description : This file provides code for the configuration + * of the ADC instances. + ****************************************************************************** + ** This notice applies to any and all portions of this file + * that are not between comment pairs USER CODE BEGIN and + * USER CODE END. Other portions of this file, whether + * inserted by the user or by software development tools + * are owned by their respective copyright owners. + * + * COPYRIGHT(c) 2017 STMicroelectronics + * + * 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 STMicroelectronics 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. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "adc.h" + +/* USER CODE BEGIN 0 */ + +/* USER CODE END 0 */ + +ADC_HandleTypeDef hadc1; + +/* ADC1 init function */ +void MX_ADC1_Init(void) +{ + ADC_ChannelConfTypeDef sConfig; + + /**Common config + */ + hadc1.Instance = ADC1; + hadc1.Init.ClockPrescaler = ADC_CLOCK_ASYNC_DIV1; + hadc1.Init.Resolution = ADC_RESOLUTION_12B; + hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT; + hadc1.Init.ScanConvMode = ADC_SCAN_DISABLE; + hadc1.Init.EOCSelection = ADC_EOC_SINGLE_CONV; + hadc1.Init.LowPowerAutoWait = DISABLE; + hadc1.Init.ContinuousConvMode = DISABLE; + hadc1.Init.NbrOfConversion = 1; + hadc1.Init.DiscontinuousConvMode = DISABLE; + hadc1.Init.NbrOfDiscConversion = 1; + hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START; + hadc1.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE; + hadc1.Init.DMAContinuousRequests = DISABLE; + hadc1.Init.Overrun = ADC_OVR_DATA_PRESERVED; + hadc1.Init.OversamplingMode = DISABLE; + if (HAL_ADC_Init(&hadc1) != HAL_OK) + { + _Error_Handler(__FILE__, __LINE__); + } + + /**Configure Regular Channel + */ + sConfig.Channel = ADC_CHANNEL_VBAT; + sConfig.Rank = 1; + sConfig.SamplingTime = ADC_SAMPLETIME_2CYCLES_5; + sConfig.SingleDiff = ADC_SINGLE_ENDED; + sConfig.OffsetNumber = ADC_OFFSET_NONE; + sConfig.Offset = 0; + if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK) + { + _Error_Handler(__FILE__, __LINE__); + } + +} + +void HAL_ADC_MspInit(ADC_HandleTypeDef* adcHandle) +{ + + if(adcHandle->Instance==ADC1) + { + /* USER CODE BEGIN ADC1_MspInit 0 */ + + /* USER CODE END ADC1_MspInit 0 */ + /* ADC1 clock enable */ + __HAL_RCC_ADC_CLK_ENABLE(); + /* USER CODE BEGIN ADC1_MspInit 1 */ + + /* USER CODE END ADC1_MspInit 1 */ + } +} + +void HAL_ADC_MspDeInit(ADC_HandleTypeDef* adcHandle) +{ + + if(adcHandle->Instance==ADC1) + { + /* USER CODE BEGIN ADC1_MspDeInit 0 */ + + /* USER CODE END ADC1_MspDeInit 0 */ + /* Peripheral clock disable */ + __HAL_RCC_ADC_CLK_DISABLE(); + /* USER CODE BEGIN ADC1_MspDeInit 1 */ + + /* USER CODE END ADC1_MspDeInit 1 */ + } +} + +/* USER CODE BEGIN 1 */ + +/* USER CODE END 1 */ + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard000/C/0009839_gpio.c b/pool/shard000/C/0009839_gpio.c new file mode 100644 index 0000000000000000000000000000000000000000..f12c1e4350151204c1af276cecab0deb987607dd --- /dev/null +++ b/pool/shard000/C/0009839_gpio.c @@ -0,0 +1,94 @@ +/** + ****************************************************************************** + * File Name : gpio.c + * Description : This file provides code for the configuration + * of all used GPIO pins. + ****************************************************************************** + * + * COPYRIGHT(c) 2017 STMicroelectronics + * + * 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 STMicroelectronics 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. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "gpio.h" +/* USER CODE BEGIN 0 */ + +/* USER CODE END 0 */ + +/*----------------------------------------------------------------------------*/ +/* Configure GPIO */ +/*----------------------------------------------------------------------------*/ +/* USER CODE BEGIN 1 */ + +/* USER CODE END 1 */ + +/** Configure pins as + * Analog + * Input + * Output + * EVENT_OUT + * EXTI +*/ +void MX_GPIO_Init(void) +{ + + GPIO_InitTypeDef GPIO_InitStruct; + + /* GPIO Ports Clock Enable */ + __HAL_RCC_GPIOA_CLK_ENABLE(); + __HAL_RCC_GPIOB_CLK_ENABLE(); + + /*Configure GPIO pin Output Level */ + HAL_GPIO_WritePin(GPIOA, Tagger_sound_Pin|Vibro_Pin, GPIO_PIN_RESET); + + /*Configure GPIO pins : PAPin PAPin */ + GPIO_InitStruct.Pin = Tagger_sound_Pin|Vibro_Pin; + GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; + HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); + + /*Configure GPIO pins : PA1 PA3 PA10 */ + GPIO_InitStruct.Pin = GPIO_PIN_1|GPIO_PIN_3|GPIO_PIN_10; + GPIO_InitStruct.Mode = GPIO_MODE_INPUT; + GPIO_InitStruct.Pull = GPIO_NOPULL; + HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); + +} + +/* USER CODE BEGIN 2 */ + +/* USER CODE END 2 */ + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard000/C/0009846_debruijn.c b/pool/shard000/C/0009846_debruijn.c new file mode 100644 index 0000000000000000000000000000000000000000..5bbdb16e9d2c5981920e59fcb2e0ef02d5e40930 --- /dev/null +++ b/pool/shard000/C/0009846_debruijn.c @@ -0,0 +1,131 @@ +/* radare - LGPL - Copyright 2014-2016 - crowell, pancake */ + +#include + +// The following two (commented out) lines are the character set used in peda. +// You may use this charset instead of the A-Za-z0-9 charset normally used. +// char* peda_charset = +// "A%sB$nC-(D;)Ea0Fb1Gc2Hd3Ie4Jf5Kg6Lh7Mi8Nj9OkPlQmRnSoTpUqVrWsXtYuZvwxyz"; + +//TODO(crowell): Make charset configurable, to allow banning characters. +static const char* debruijn_charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"; + +// Generate a De Bruijn sequence. +static void de_bruijn_seq(int prenecklace_len_t, int lyndon_prefix_len_p, int order, + int maxlen, int size, int* prenecklace_a, char* sequence, const char* charset) { + int j; + if (!charset || !sequence || strlen (sequence) == maxlen) { + return; + } + if (prenecklace_len_t > order) { + if (order % lyndon_prefix_len_p == 0) { + for (j = 1; j <= lyndon_prefix_len_p; ++j) { + sequence[strlen(sequence)] = charset[prenecklace_a[j]]; + if (strlen (sequence) == maxlen) { + return; + } + } + } + } else { + prenecklace_a[prenecklace_len_t] = + prenecklace_a[prenecklace_len_t - lyndon_prefix_len_p]; + de_bruijn_seq(prenecklace_len_t + 1, lyndon_prefix_len_p, order, maxlen, + size, prenecklace_a, sequence, charset); + for (j = prenecklace_a[prenecklace_len_t - lyndon_prefix_len_p] + 1; + j < size; ++j) { + prenecklace_a[prenecklace_len_t] = j; + de_bruijn_seq (prenecklace_len_t + 1, prenecklace_len_t, order, maxlen, + size, prenecklace_a, sequence, charset); + } + } +} + +// Generate a De Bruijn sequence. +// The returned string is malloced, and it is the responsibility of the caller +// to free the memory. +static char* de_bruijn(const char* charset, int order, int maxlen) { + int size = strlen (charset); + int* prenecklace_a = calloc (size * order, sizeof(int)); + if (!prenecklace_a) return NULL; + char* sequence = calloc (maxlen + 1, sizeof(char)); + if (!sequence) { + free (prenecklace_a); + return NULL; + } + de_bruijn_seq (1, 1, order, maxlen, size, prenecklace_a, sequence, charset); + free (prenecklace_a); + return sequence; +} + +// Generate a cyclic pattern of desired size, and charset, return with starting +// offset of start. +// The returned string is malloced, and it is the responsibility of the caller +// to free the memory. +R_API char* r_debruijn_pattern(int size, int start, const char* charset) { + char *pat, *pat2; + ut64 len; + if (!charset) { + charset = debruijn_charset; + } + if (start >= size) { + return (char*)NULL; + } + pat = de_bruijn (charset, 3 /*subsequence length*/, size); + if (!pat) { + return NULL; + } + if (start == 0) { + len = strlen (pat); + if (size != len) { + eprintf ("warning: requested pattern of length %d, " + "generated length %"PFMT64d"\n", size, len); + } + return pat; + } + pat2 = calloc ((size - start) + 1, sizeof(char)); + if (!pat2) { + free (pat); + return NULL; + } + strncpy (pat2, pat + start, size - start); + pat2[size-start] = 0; + free (pat); + len = strlen (pat2); + if (size != len) { + eprintf ("warning: requested pattern of length %d, " + "generated length %"PFMT64d"\n", + size, len); + } + return pat2; +} + +// Finds the offset of a given value in a cyclic pattern of an integer. +R_API int r_debruijn_offset(ut64 value, bool is_big_endian) { + char* needle, *pattern, buf[9]; + int retval; + char* pch; + + if (value == 0) { + return -1; + } + // 0x10000 should be long enough. This is how peda works, and nobody complains + pattern = r_debruijn_pattern (0x10000, 0, debruijn_charset); + + buf[8] = '\0'; + if (is_big_endian) { + r_write_be64 (buf, value); + } else { + r_write_le64 (buf, value); + } + for (needle = buf; !*needle; needle++) { + /* do nothing here */ + } + + pch = strstr (pattern, needle); + retval = -1; + if (pch) { + retval = (int)(size_t)(pch - pattern); + } + free (pattern); + return retval; +} diff --git a/pool/shard000/C/0009852_mach_init.c b/pool/shard000/C/0009852_mach_init.c new file mode 100644 index 0000000000000000000000000000000000000000..cf8ac3bb318b057a533f52e9fdde9e771d4b36e5 --- /dev/null +++ b/pool/shard000/C/0009852_mach_init.c @@ -0,0 +1,51 @@ +/* Copyright (C) 1992-2015 Free Software Foundation, Inc. + This file is part of the GNU C Library. + + The GNU C Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The GNU C Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, see + . */ + +#include +#include +#include + +mach_port_t __mach_task_self_; +vm_size_t __vm_page_size = 0; /* Must be data not bss for weak alias. */ +weak_alias (__vm_page_size, vm_page_size) + +#ifdef NDR_DEF_HEADER +/* This defines NDR_record, which the MiG-generated stubs use. XXX namespace */ +# include NDR_DEF_HEADER +#endif + +void +__mach_init (void) +{ + kern_return_t err; + + __mach_task_self_ = (__mach_task_self) (); + __mig_init (0); + +#ifdef HAVE_HOST_PAGE_SIZE + if (err = __host_page_size (__mach_host_self (), &__vm_page_size)) + _exit (err); +#else + { + vm_statistics_data_t stats; + if (err = __vm_statistics (__mach_task_self (), &stats)) + _exit (err); + __vm_page_size = stats.pagesize; + } +#endif +} +weak_alias (__mach_init, mach_init) diff --git a/pool/shard000/C/0009854_test_projection.c b/pool/shard000/C/0009854_test_projection.c new file mode 100644 index 0000000000000000000000000000000000000000..4c9dcad14e6c2dce9c70633ff65f985462d43a80 --- /dev/null +++ b/pool/shard000/C/0009854_test_projection.c @@ -0,0 +1,141 @@ +#include // for assert +#include // for display_status_rolling_cone +#include // for printf +#include "debug.h" // for DEBUG_EXPR +#include "math.h" // for sqrt + +#ifdef DEBUG_MESSAGES +#include "NumericsVector.h" +#endif + + +static double orthogonality(double * reaction, double * reaction_ori) +{ + double ortho =0.0; + for(int i =0; i<5; i++) + { + ortho += (reaction_ori[i] - reaction[i])*(reaction[i]); + } + return ortho; +} + +static double compute_diff(double * reaction, double * reaction_again) +{ + double diff =0.0; + for(int i =0; i<5; i++) + { + diff += (reaction_again[i] - reaction[i])*(reaction_again[i] - reaction[i]); + } + return sqrt(diff); +} + + +static int test_projection(double * reaction, double mu, double mur) +{ + printf("################################ \n"); + printf("start test \n"); + printf("################################ \n"); + unsigned int status; + unsigned int status_again; + double reaction_ori[5]; + double reaction_again[5]; + double ortho=0.0, diff =0.0; + DEBUG_EXPR(NV_display(reaction,5);); + + for(int i =0; i<5; i++) reaction_ori[i] = reaction[i]; + status = projectionOnRollingCone(reaction,mu,mur); + DEBUG_EXPR(NV_display(reaction,5);); + display_status_rolling_cone(status); + ortho = orthogonality(reaction,reaction_ori); + printf("ortho = %f\n", ortho); + assert(ortho < 1e-14); + + for(int i =0; i<5; i++) reaction_again[i] = reaction[i]; + status_again = projectionOnRollingCone(reaction_again,mu,mur); + DEBUG_EXPR(NV_display(reaction_again,5);); + display_status_rolling_cone(status_again); + diff = compute_diff(reaction,reaction_again); + printf("diff = %f\n", diff); + assert(diff < 1e-14); + + return status; + +} +int main(void) +{ + + int info=0; + unsigned int status; + double reaction[5]; + double mu=1.0, mur=1.0; + + + reaction[0] = 1.0; + reaction[1] = 0.0; + reaction[2] = 0.0; + reaction[3] = 0.0; + reaction[4] = 0.0; + + status = test_projection(reaction, mu, mur); + if(status != PROJRCONE_INSIDE) + { + info+=1; + } + reaction[0] = -1.0; + reaction[1] = 0.5; + reaction[2] = 0.0; + reaction[3] = 0.5; + reaction[4] = 0.0; + status = test_projection(reaction, mu, mur); + if(status != PROJRCONE_DUAL) + { + info+=1; + } + + reaction[0] = 1.0; + reaction[1] = 2.0; + reaction[2] = 0.0; + reaction[3] = 0.0; + reaction[4] = 0.0; + status = test_projection(reaction, mu, mur); + if(status != PROJRCONE_BOUNDARY_FRICTION) + { + info+=1; + } + + reaction[0] = 1.0; + reaction[1] = 0.0; + reaction[2] = 0.0; + reaction[3] = 2.0; + reaction[4] = 0.0; + status = test_projection(reaction, mu, mur); + if(status != PROJRCONE_BOUNDARY_ROLLING) + { + info+=1; + } + + reaction[0] = 1.0; + reaction[1] = 2.0; + reaction[2] = 0.0; + reaction[3] = 2.0; + reaction[4] = 0.0; + status = test_projection(reaction, mu, mur); + if(status != PROJRCONE_BOUNDARY_FRICTION_ROLLING) + { + info+=1; + } + + reaction[0] = 1.0; + reaction[1] = 2.0; + reaction[2] = 1.0; + reaction[3] = 2.0; + reaction[4] = 1.0; + status = test_projection(reaction, mu, mur); + if(status != PROJRCONE_BOUNDARY_FRICTION_ROLLING) + { + info+=1; + } + + return info; + +} diff --git a/pool/shard000/C/0009855_my_fstream.c b/pool/shard000/C/0009855_my_fstream.c new file mode 100644 index 0000000000000000000000000000000000000000..8a6db2e850220b998af1513e3e75e6d1a9202c38 --- /dev/null +++ b/pool/shard000/C/0009855_my_fstream.c @@ -0,0 +1,194 @@ +/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. + + 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ + +/* USE_MY_STREAM isn't set because we can't thrust my_fclose! */ + +#include "mysys_priv.h" +#include "mysys_err.h" +#include +#include + +#ifdef HAVE_FSEEKO +#undef ftell +#undef fseek +#define ftell(A) ftello(A) +#define fseek(A,B,C) fseeko((A),(B),(C)) +#endif + +/* + Read a chunk of bytes from a FILE + + SYNOPSIS + my_fread() + stream File descriptor + Buffer Buffer to read to + Count Number of bytes to read + MyFlags Flags on what to do on error + + RETURN + (size_t) -1 Error + # Number of bytes read + */ + +size_t my_fread(FILE *stream, uchar *Buffer, size_t Count, myf MyFlags) +{ + size_t readbytes; + DBUG_ENTER("my_fread"); + DBUG_PRINT("my",("stream: %p Buffer %p Count: %u MyFlags: %lu", + stream, Buffer, (uint) Count, MyFlags)); + + if ((readbytes= fread(Buffer, sizeof(char), Count, stream)) != Count) + { + DBUG_PRINT("error",("Read only %d bytes", (int) readbytes)); + if (MyFlags & (MY_WME | MY_FAE | MY_FNABP)) + { + if (ferror(stream)) + my_error(EE_READ, MYF(ME_BELL+ME_WAITTANG), + my_filename(my_fileno(stream)),errno); + else + if (MyFlags & (MY_NABP | MY_FNABP)) + my_error(EE_EOFERR, MYF(ME_BELL+ME_WAITTANG), + my_filename(my_fileno(stream)),errno); + } + my_errno=errno ? errno : -1; + if (ferror(stream) || MyFlags & (MY_NABP | MY_FNABP)) + DBUG_RETURN((size_t) -1); /* Return with error */ + } + if (MyFlags & (MY_NABP | MY_FNABP)) + DBUG_RETURN(0); /* Read ok */ + DBUG_RETURN(readbytes); +} /* my_fread */ + + +/* + Write a chunk of bytes to a stream + + my_fwrite() + stream File descriptor + Buffer Buffer to write from + Count Number of bytes to write + MyFlags Flags on what to do on error + + RETURN + (size_t) -1 Error + # Number of bytes written +*/ + +size_t my_fwrite(FILE *stream, const uchar *Buffer, size_t Count, myf MyFlags) +{ + size_t writtenbytes =0; + my_off_t seekptr; +#if !defined(NO_BACKGROUND) && defined(USE_MY_STREAM) + uint errors; +#endif + DBUG_ENTER("my_fwrite"); + DBUG_PRINT("my",("stream:%p Buffer:%p Count: %u MyFlags: %lu", + stream, Buffer, (uint) Count, MyFlags)); + +#if !defined(NO_BACKGROUND) && defined(USE_MY_STREAM) + errors=0; +#endif + seekptr= ftell(stream); + for (;;) + { + size_t written; + if ((written = (size_t) fwrite((char*) Buffer,sizeof(char), + Count, stream)) != Count) + { + DBUG_PRINT("error",("Write only %d bytes", (int) writtenbytes)); + my_errno=errno; + if (written != (size_t) -1) + { + seekptr+=written; + Buffer+=written; + writtenbytes+=written; + Count-=written; + } +#ifdef EINTR + if (errno == EINTR) + { + (void) my_fseek(stream,seekptr,MY_SEEK_SET,MYF(0)); + continue; + } +#endif +#if !defined(NO_BACKGROUND) && defined(USE_MY_STREAM) + if (my_thread_var->abort) + MyFlags&= ~ MY_WAIT_IF_FULL; /* End if aborted by user */ + + if ((errno == ENOSPC || errno == EDQUOT) && + (MyFlags & MY_WAIT_IF_FULL)) + { + wait_for_free_space("[stream]", errors); + errors++; + (void) my_fseek(stream,seekptr,MY_SEEK_SET,MYF(0)); + continue; + } +#endif + if (ferror(stream) || (MyFlags & (MY_NABP | MY_FNABP))) + { + if (MyFlags & (MY_WME | MY_FAE | MY_FNABP)) + { + my_error(EE_WRITE, MYF(ME_BELL+ME_WAITTANG), + my_filename(my_fileno(stream)),errno); + } + writtenbytes= (size_t) -1; /* Return that we got error */ + break; + } + } + if (MyFlags & (MY_NABP | MY_FNABP)) + writtenbytes= 0; /* Everything OK */ + else + writtenbytes+= written; + break; + } + DBUG_RETURN(writtenbytes); +} /* my_fwrite */ + + +/* Seek to position in file */ + +my_off_t my_fseek(FILE *stream, my_off_t pos, int whence, + myf MyFlags __attribute__((unused))) +{ + DBUG_ENTER("my_fseek"); + DBUG_PRINT("my",("stream:%p pos: %llu whence: %d MyFlags: %lu", + stream, (ulonglong) pos, whence, MyFlags)); + DBUG_RETURN(fseek(stream, (off_t) pos, whence) ? + MY_FILEPOS_ERROR : (my_off_t) ftell(stream)); +} /* my_seek */ + + +/* Tell current position of file */ + +my_off_t my_ftell(FILE *stream, myf MyFlags __attribute__((unused))) +{ + long long pos; + DBUG_ENTER("my_ftell"); + DBUG_PRINT("my",("stream:%p MyFlags: %lu", stream, MyFlags)); + pos=IF_WIN(_ftelli64(stream),ftell(stream)); + DBUG_PRINT("exit",("ftell: %lld",pos)); + DBUG_RETURN((my_off_t) pos); +} /* my_ftell */ + + +/* Get a File corresponding to the stream*/ +int my_fileno(FILE *f) +{ +#ifdef _WIN32 + return my_win_fileno(f); +#else + return fileno(f); +#endif +} diff --git a/pool/shard000/C/0009859_asm_atombios.c b/pool/shard000/C/0009859_asm_atombios.c new file mode 100644 index 0000000000000000000000000000000000000000..ec2bfb7faa789b7a2770df00088c1eb52462bb32 --- /dev/null +++ b/pool/shard000/C/0009859_asm_atombios.c @@ -0,0 +1,40 @@ +/* radare - LGPL - Copyright 2018 - damo22 */ + +#include +#include +#include + +#include "../arch/atombios/atombios.h" + +static int disassemble(RAsm *a, RAsmOp *op, const ut8 *buf, int len) { + char res[1024]; + res[0] = 0; + op->size = atombios_disassemble (buf, len, res); + r_strbuf_set (&op->buf_asm, res); + return op->size; +} + +static int assemble(RAsm *a, RAsmOp *op, const char *buf) { + return 0; // n +} + +RAsmPlugin r_asm_plugin_atombios = { + .name = "atombios", + .author = "damo22", + .version = "0.0.1", + .arch = "atombios", + .license = "LGPL3", + .bits = 32 | 64, + .endian = R_SYS_ENDIAN_NONE, + .desc = "AtomBIOS", + .disassemble = &disassemble, + .assemble = &assemble +}; + +#ifndef CORELIB +RLibStruct radare_plugin = { + .type = R_LIB_TYPE_ASM, + .data = &r_asm_plugin_atombios, + .version = R2_VERSION +}; +#endif diff --git a/pool/shard000/C/0009867_pci.c b/pool/shard000/C/0009867_pci.c new file mode 100644 index 0000000000000000000000000000000000000000..f14837ad404071d6aba7e85f1712d245d6f359f0 --- /dev/null +++ b/pool/shard000/C/0009867_pci.c @@ -0,0 +1,89 @@ +/* + * Copyright (C) Freescale Semiconductor, Inc. 2006. + * + * (C) Copyright 2008 + * Andre Schwarz, Matrix Vision GmbH, andre.schwarz@matrix-vision.de + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#include +#if defined(CONFIG_OF_LIBFDT) +#include +#endif +#include +#include +#include +#include "mvblm7.h" +#include "fpga.h" +#include "../common/mv_common.h" + +DECLARE_GLOBAL_DATA_PTR; + +static struct pci_region pci_regions[] = { + { + bus_start: CONFIG_SYS_PCI1_MEM_BASE, + phys_start: CONFIG_SYS_PCI1_MEM_PHYS, + size: CONFIG_SYS_PCI1_MEM_SIZE, + flags: PCI_REGION_MEM | PCI_REGION_PREFETCH + }, + { + bus_start: CONFIG_SYS_PCI1_MMIO_BASE, + phys_start: CONFIG_SYS_PCI1_MMIO_PHYS, + size: CONFIG_SYS_PCI1_MMIO_SIZE, + flags: PCI_REGION_MEM + }, + { + bus_start: CONFIG_SYS_PCI1_IO_BASE, + phys_start: CONFIG_SYS_PCI1_IO_PHYS, + size: CONFIG_SYS_PCI1_IO_SIZE, + flags: PCI_REGION_IO + } +}; + +void pci_init_board(void) +{ + int i; + volatile immap_t *immr; + volatile pcictrl83xx_t *pci_ctrl; + volatile gpio83xx_t *gpio; + volatile clk83xx_t *clk; + volatile law83xx_t *pci_law; + struct pci_region *reg[] = { pci_regions }; + + immr = (immap_t *) CONFIG_SYS_IMMR; + clk = (clk83xx_t *) &immr->clk; + pci_ctrl = immr->pci_ctrl; + pci_law = immr->sysconf.pcilaw; + gpio = (volatile gpio83xx_t *)&immr->gpio[0]; + + gpio->dat = MV_GPIO_DAT; + gpio->odr = MV_GPIO_ODE; + gpio->dir = MV_GPIO_OUT; + + printf("SICRH / SICRL : 0x%08x / 0x%08x\n", immr->sysconf.sicrh, + immr->sysconf.sicrl); + + mvblm7_init_fpga(); + mv_load_fpga(); + + gpio->dir = MV_GPIO_OUT & ~(FPGA_DIN|FPGA_CCLK); + + /* Enable PCI_CLK_OUTPUTs 0 and 1 with 1:1 clocking */ + clk->occr = 0xc0000000; + + pci_ctrl[0].gcr = 0; + udelay(2000); + pci_ctrl[0].gcr = 1; + + for (i = 0; i < 1000; ++i) + udelay(1000); + + pci_law[0].bar = CONFIG_SYS_PCI1_MEM_PHYS & LAWBAR_BAR; + pci_law[0].ar = LBLAWAR_EN | LBLAWAR_1GB; + + pci_law[1].bar = CONFIG_SYS_PCI1_IO_PHYS & LAWBAR_BAR; + pci_law[1].ar = LBLAWAR_EN | LBLAWAR_1MB; + + mpc83xx_pci_init(1, reg); +} diff --git a/pool/shard000/C/0009898_pamtohdiff.c b/pool/shard000/C/0009898_pamtohdiff.c new file mode 100644 index 0000000000000000000000000000000000000000..0e1ff00ff8df86f45cb3571c85ecaf3a79b4a4fb --- /dev/null +++ b/pool/shard000/C/0009898_pamtohdiff.c @@ -0,0 +1,142 @@ +/****************************************************************************** + pamtohdiff +******************************************************************************* + This program creates a PAM output which a horizontal difference image of + the input PAM. The samples in each row are a number to be added to to + the previous output row to create the next output row (and the first + output row is simply the same as the input row). + + Because these samples must be positive and negative and PAM samples are + unsigned, we bias each PAM sample by the input maxval and make the output + maxval twice the input maxval. + + By Bryan Henderson, San Jose, CA 2002.04.15. + +******************************************************************************/ +#include +#include + +#include "pam.h" +#include "shhopt.h" + +struct cmdlineInfo { + /* All the information the user supplied in the command line, + in a form easy for the program to use. + */ + const char *inputFilespec; /* Filespecs of input files */ + unsigned int verbose; +}; + + + +static void +parseCommandLine(int argc, char ** argv, + struct cmdlineInfo * const cmdlineP) { +/*---------------------------------------------------------------------------- + Note that the file spec array we return is stored in the storage that + was passed to us as the argv array. +-----------------------------------------------------------------------------*/ + optEntry *option_def = malloc( 100*sizeof( optEntry ) ); + /* Instructions to optParseOptions3 on how to parse our options. + */ + optStruct3 opt; + + unsigned int option_def_index; + + option_def_index = 0; /* incremented by OPTENTRY */ + OPTENT3(0, "verbose", OPT_FLAG, NULL, &cmdlineP->verbose, 0); + + opt.opt_table = option_def; + opt.short_allowed = FALSE; /* We have no short (old-fashioned) options */ + opt.allowNegNum = FALSE; /* We have no parms that are negative numbers */ + + optParseOptions3( &argc, argv, opt, sizeof(opt), 0 ); + /* Uses and sets argc, argv, and some of *cmdlineP and others. */ + + if (argc-1 < 1) + cmdlineP->inputFilespec = "-"; + else if (argc-1 == 1) + cmdlineP->inputFilespec = argv[1]; + else + pm_error("Too many arguments."); +} + + + +int +main(int argc, char *argv[]) { + FILE *ifP; + struct cmdlineInfo cmdline; + struct pam inpam, outpam; + unsigned int row; + tuple * inrow; + tuple * outrow; + tuple * prevrow; + + pnm_init( &argc, argv ); + + parseCommandLine(argc, argv, &cmdline); + + ifP = pm_openr(cmdline.inputFilespec); + + pnm_readpaminit(ifP, &inpam, PAM_STRUCT_SIZE(tuple_type)); + + outpam = inpam; + outpam.file = stdout; + outpam.format = PAM_FORMAT; + strcpy(outpam.tuple_type, "hdiff"); + + pnm_writepaminit(&outpam); + + inrow = pnm_allocpamrow(&inpam); + outrow = pnm_allocpamrow(&outpam); + prevrow = pnm_allocpamrow(&inpam); + + pnm_setpamrow(&inpam, prevrow, 0); + + /* All arithmetic in this operation and in the reverse operation + (to recover the image) is done modulus the maxval+1 (the hdiff + PAM and the image have the same maxval) in order to produce + legal PAM samples (which must be in the range 0..maxval). This + might seem to throw away information, but it doesn't. Example: + maxval is 99. Intensity goes from 90 in Row 0 to 10 in Row 1. + The difference is -80. -80 mod 100 is 20, so 20 goes in the + hdiff output. On reconstructing the image, the interpreter + knows the "20" can't be +20, because that would create the + sample 90 + 20 = 110, and violate maxval. So it must be -80. + Modulus arithmetic by the interpreter effectively makes that + decision. + */ + + + /* The bias is just to make it easier to look at the output visually. + If you display the values as intensities, and your differences are + all +/- half of maxval, you can see positive transitions as bright + spots and negative transitions as dark spots. + */ + + { + unsigned int const bias = outpam.maxval/2; + for (row = 0; row < inpam.height; ++row) { + unsigned int col; + pnm_readpamrow(&inpam, inrow); + for (col = 0; col < inpam.width; ++col) { + unsigned int plane; + for (plane = 0; plane < inpam.depth; ++plane) { + + sample const sampleValue = inrow[col][plane]; + int const difference = sampleValue - prevrow[col][plane]; + outrow[col][plane] = (difference + bias) % (outpam.maxval+1); + prevrow[col][plane] = sampleValue; + } + } + pnm_writepamrow(&outpam, outrow); + } + } + pnm_freepamrow(prevrow); + pnm_freepamrow(outrow); + pnm_freepamrow(inrow); + + exit(0); +} + diff --git a/pool/shard000/C/0009907_rmsd_progressive.c b/pool/shard000/C/0009907_rmsd_progressive.c new file mode 100644 index 0000000000000000000000000000000000000000..f402fdc17ea3c8af067f8028182684425e7324ea --- /dev/null +++ b/pool/shard000/C/0009907_rmsd_progressive.c @@ -0,0 +1,117 @@ + +/* + Calculate rmsd time series +*/ + +#include + +int +mol_rmsd_progressive(char *molfile, char *trjfile, char *selestr, int algo, FILE *out) +{ + + int ret; + + /* Read the molecule and the trajectory */ + Molecule *trj=mol_new(); + + /* Read the molecule */ + fprintf(stderr, "Reading %s...\n", molfile); + ret = mol_readmol(trj, molfile); + if (ret!=0) return ret; + + /* Open the trajectory */ + fprintf(stderr, "Reading %s...\n", trjfile); + ret = mol_opentrj(trj, trjfile); + if (ret!=0) return ret; + + double *frame, *frame_ref; + double rmsd; + int natm=trj->natms; + int i; + + /* Set weights */ + double *weight = cyg_realloc(NULL, trj->natms*cyg_sizeof(double)); + for (i=0; inatms; i++) { + weight[i] = 1.0; + } + + /* Get the selection */ + bool *sele; + int num=0; + sele = mol_getsele(trj, selestr, &num); + fprintf(stderr, "RMSD performed on %d selected atoms.\n", num); + if (num<3) { + cyg_logErr("Not enough selected atoms! (%d<3)", num); + return CYG_FAILURE; + } + + /* The reference structure is the one given by --mol */ + /* Center it (if necessary) and save it */ + frame = trj->coor; + if (algo==RMSD_SUP3 || algo==RMSD_SUPSYM3 || algo==RMSD_SVD) { + mol_center(frame, natm, sele, NULL, NULL); + } else if (algo==RMSD_SUP2 || algo==RMSD_SUPSYM2) { + mol_center_xy(frame, natm, sele, NULL, NULL); + } + frame_ref = cyg_realloc(NULL, natm*3*cyg_sizeof(double)); + for (i=0; i<3*natm; i++) { + frame_ref[i] = frame[i]; + } + + /* Assign symmetry operations -- for symmetry-corrected methods */ + sym_t sym; + if (algo==RMSD_SUPSYM3 || algo==RMSD_NOSUPSYM3 || algo==RMSD_SUPSYM2 || algo==RMSD_NOSUPSYM2 ) { + if (trj_sym_assign(trj, &sym, "sym.dat")!=0) { + fprintf(stderr, "ERROR assigning symmetry operations!\n\n"); + return -1; + } + } + + /* Process the trajectory */ + fprintf(stderr, "Evaluating RMSD time serie.\n"); + i=1; + ret = mol_readframe(trj); + if (ret!=CYG_SUCCESS) { + cyg_logErr("No frame read from %s!", trjfile); + } + while (ret == CYG_SUCCESS) { + + /* Center the frames, if necessary */ + frame = trj->coor; + if (algo==RMSD_SUP3 || algo==RMSD_SUPSYM3 || algo==RMSD_SVD) { + mol_center(frame, natm, sele, NULL, NULL); + } else if (algo==RMSD_SUP2 || algo==RMSD_SUPSYM2) { + mol_center_xy(frame, natm, sele, NULL, NULL); + } + + /* Do rmsd calculation and print output */ + mol_rmsd(frame_ref, frame, natm, weight, &rmsd, NULL, sele, &sym, algo); + fprintf(out, "%5d %10.4f \n", i, rmsd); + + /* Copy new coordinates as reference */ + for (i=0; i<3*natm; i++) { + frame_ref[i] = frame[i]; + } + + /* Read new frame and continue the loop */ + i++; + ret = mol_readframe(trj); + } + + + /* Do some cleaning */ + mol_delete(trj); + if (out!=stdout) fclose(out); + free(frame_ref); + free(sele); + + /* Delete symmetry operations (for SYMM) */ + if (algo==RMSD_SUPSYM3 || algo==RMSD_NOSUPSYM3 || algo==RMSD_SUPSYM2 || algo==RMSD_NOSUPSYM2 ) { + trj_sym_delete(&sym); + } + + free(weight); + return CYG_SUCCESS; +} + + diff --git a/pool/shard000/C/0009918_binfmt_elf32.c b/pool/shard000/C/0009918_binfmt_elf32.c new file mode 100644 index 0000000000000000000000000000000000000000..a1a12d2aa3530e5e5fd88833dabc41a1da2a6945 --- /dev/null +++ b/pool/shard000/C/0009918_binfmt_elf32.c @@ -0,0 +1,159 @@ +/* + * binfmt_elf32.c: Support 32-bit Sparc ELF binaries on Ultra. + * + * Copyright (C) 1995, 1996, 1997, 1998 David S. Miller (davem@redhat.com) + * Copyright (C) 1995, 1996, 1997, 1998 Jakub Jelinek (jj@ultra.linux.cz) + */ + +#define ELF_ARCH EM_SPARC +#define ELF_CLASS ELFCLASS32 +#define ELF_DATA ELFDATA2MSB; + +/* For the most part we present code dumps in the format + * Solaris does. + */ +typedef unsigned int elf_greg_t; +#define ELF_NGREG 38 +typedef elf_greg_t elf_gregset_t[ELF_NGREG]; + +/* Format is: + * G0 --> G7 + * O0 --> O7 + * L0 --> L7 + * I0 --> I7 + * PSR, PC, nPC, Y, WIM, TBR + */ +#include +#define ELF_CORE_COPY_REGS(__elf_regs, __pt_regs) \ +do { unsigned int *dest = &(__elf_regs[0]); \ + struct pt_regs *src = (__pt_regs); \ + unsigned int __user *sp; \ + int i; \ + for(i = 0; i < 16; i++) \ + dest[i] = (unsigned int) src->u_regs[i];\ + /* Don't try this at home kids... */ \ + sp = (unsigned int __user *) (src->u_regs[14] & \ + 0x00000000fffffffc); \ + for(i = 0; i < 16; i++) \ + __get_user(dest[i+16], &sp[i]); \ + dest[32] = tstate_to_psr(src->tstate); \ + dest[33] = (unsigned int) src->tpc; \ + dest[34] = (unsigned int) src->tnpc; \ + dest[35] = src->y; \ + dest[36] = dest[37] = 0; /* XXX */ \ +} while(0); + +typedef struct { + union { + unsigned int pr_regs[32]; + unsigned long pr_dregs[16]; + } pr_fr; + unsigned int __unused; + unsigned int pr_fsr; + unsigned char pr_qcnt; + unsigned char pr_q_entrysize; + unsigned char pr_en; + unsigned int pr_q[64]; +} elf_fpregset_t; + +/* UltraSparc extensions. Still unused, but will be eventually. */ +typedef struct { + unsigned int pr_type; + unsigned int pr_align; + union { + struct { + union { + unsigned int pr_regs[32]; + unsigned long pr_dregs[16]; + long double pr_qregs[8]; + } pr_xfr; + } pr_v8p; + unsigned int pr_xfsr; + unsigned int pr_fprs; + unsigned int pr_xg[8]; + unsigned int pr_xo[8]; + unsigned long pr_tstate; + unsigned int pr_filler[8]; + } pr_un; +} elf_xregset_t; + +#define elf_check_arch(x) (((x)->e_machine == EM_SPARC) || ((x)->e_machine == EM_SPARC32PLUS)) + +#define ELF_ET_DYN_BASE 0x70000000 + + +#include +#include +#include +#include +#include + +#define elf_prstatus elf_prstatus32 +struct elf_prstatus32 +{ + struct elf_siginfo pr_info; /* Info associated with signal */ + short pr_cursig; /* Current signal */ + unsigned int pr_sigpend; /* Set of pending signals */ + unsigned int pr_sighold; /* Set of held signals */ + pid_t pr_pid; + pid_t pr_ppid; + pid_t pr_pgrp; + pid_t pr_sid; + struct compat_timeval pr_utime; /* User time */ + struct compat_timeval pr_stime; /* System time */ + struct compat_timeval pr_cutime; /* Cumulative user time */ + struct compat_timeval pr_cstime; /* Cumulative system time */ + elf_gregset_t pr_reg; /* GP registers */ + int pr_fpvalid; /* True if math co-processor being used. */ +}; + +#define elf_prpsinfo elf_prpsinfo32 +struct elf_prpsinfo32 +{ + char pr_state; /* numeric process state */ + char pr_sname; /* char for pr_state */ + char pr_zomb; /* zombie */ + char pr_nice; /* nice val */ + unsigned int pr_flag; /* flags */ + u16 pr_uid; + u16 pr_gid; + pid_t pr_pid, pr_ppid, pr_pgrp, pr_sid; + /* Lots missing */ + char pr_fname[16]; /* filename of executable */ + char pr_psargs[ELF_PRARGSZ]; /* initial part of arg list */ +}; + +#include + +#undef NEW_TO_OLD_UID +#undef NEW_TO_OLD_GID +#define NEW_TO_OLD_UID(uid) ((uid) > 65535) ? (u16)overflowuid : (u16)(uid) +#define NEW_TO_OLD_GID(gid) ((gid) > 65535) ? (u16)overflowgid : (u16)(gid) + +#include + +#undef cputime_to_timeval +#define cputime_to_timeval cputime_to_compat_timeval +static __inline__ void +cputime_to_compat_timeval(const cputime_t cputime, struct compat_timeval *value) +{ + unsigned long jiffies = cputime_to_jiffies(cputime); + value->tv_usec = (jiffies % HZ) * (1000000L / HZ); + value->tv_sec = jiffies / HZ; +} + +#define elf_addr_t u32 +#undef start_thread +#define start_thread start_thread32 +#define init_elf_binfmt init_elf32_binfmt + +MODULE_DESCRIPTION("Binary format loader for compatibility with 32bit SparcLinux binaries on the Ultra"); +MODULE_AUTHOR("Eric Youngdale, David S. Miller, Jakub Jelinek"); + +#undef MODULE_DESCRIPTION +#undef MODULE_AUTHOR + +#undef TASK_SIZE +#define TASK_SIZE 0xf0000000 + +#include "../../../fs/binfmt_elf.c" diff --git a/pool/shard000/C/0009946_test_gauss.c b/pool/shard000/C/0009946_test_gauss.c new file mode 100644 index 0000000000000000000000000000000000000000..fb69c07c01466e8167af9779d63dce01e0fbb2b0 --- /dev/null +++ b/pool/shard000/C/0009946_test_gauss.c @@ -0,0 +1,28 @@ +// +// Created by moons on 17-5-18. +// + +#include "../fmt/bitmap.h" +#include "../filter/filter.h" +#include + + +int main(int argc, char *argv[]) +{ + image_t *img, *dst; + + if (argc < 3) { + printf("Usage : .\n"); + } + + img = load_bmp(argv[1]); + + dst = gauss_filter(img, 10); + + save_as_bmp(dst, argv[2]); + + img_destroy(img); + img_destroy(dst); + + return 0; +} diff --git a/pool/shard000/C/0009956_b2mc.c b/pool/shard000/C/0009956_b2mc.c new file mode 100644 index 0000000000000000000000000000000000000000..60a0c0de1ac4e3c562517b674d3c0cf015d1d988 --- /dev/null +++ b/pool/shard000/C/0009956_b2mc.c @@ -0,0 +1,162 @@ +/* ----------------------------------------------------------------- */ +/* The Speech Signal Processing Toolkit (SPTK) */ +/* developed by SPTK Working Group */ +/* http://sp-tk.sourceforge.net/ */ +/* ----------------------------------------------------------------- */ +/* */ +/* Copyright (c) 1984-2007 Tokyo Institute of Technology */ +/* Interdisciplinary Graduate School of */ +/* Science and Engineering */ +/* */ +/* 1996-2013 Nagoya Institute of Technology */ +/* Department of Computer Science */ +/* */ +/* All rights reserved. */ +/* */ +/* Redistribution and use in source and binary forms, with or */ +/* without modification, are permitted provided that the following */ +/* conditions are met: */ +/* */ +/* - 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 SPTK working group nor the names of its */ +/* contributors may be used to endorse or promote products derived */ +/* from this software without specific prior written permission. */ +/* */ +/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND */ +/* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, */ +/* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF */ +/* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */ +/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS */ +/* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, */ +/* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED */ +/* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, */ +/* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */ +/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, */ +/* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY */ +/* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE */ +/* POSSIBILITY OF SUCH DAMAGE. */ +/* ----------------------------------------------------------------- */ + +/************************************************************************ +* * +* Transform MLSA Digital Filter Coefficients to Mel Cepstrum * +* * +* 1995.12 K.Koishida * +* * +* usage: * +* b2mc [ options ] [ infile ] > stdout * +* options: * +* -m m : order of mel cepstrum [25] * +* -a a : all-pass constant [0.35] * +* infile: * +* MLSA filter coefficients * +* , b(0), b(1), ..., b(M), * +* stdout: * +* mel cepstral coefficients * +* , c~(0), c~(1), ..., c~(M), * +* require: * +* b2mc() * +* * +************************************************************************/ + +static char *rcs_id = "$Id: b2mc.c,v 1.23 2013/12/16 09:01:53 mataki Exp $"; + + +/* Standard C Libraries */ +#include +#include + +#ifdef HAVE_STRING_H +# include +#else +# include +# ifndef HAVE_STRRCHR +# define strrchr rindex +# endif +#endif + + +#if defined(WIN32) +# include "SPTK.h" +#else +# include +#endif + +/* Default Values */ +#define ALPHA 0.35 +#define ORDER 25 + +/* Command Name */ +char *cmnd; + + +void usage(int status) +{ + fprintf(stderr, "\n"); + fprintf(stderr, " %s - transform MLSA digital filter coefficients\n", cmnd); + fprintf(stderr, " to mel-cepstrum \n"); + fprintf(stderr, " usage:\n"); + fprintf(stderr, " %s [ options ] [ infile ] > stdout\n", cmnd); + fprintf(stderr, " options:\n"); + fprintf(stderr, " -m m : order of mel cepstrum [%d]\n", ORDER); + fprintf(stderr, " -a a : all-pass constant [%g]\n", ALPHA); + fprintf(stderr, " -h : print this message\n"); + fprintf(stderr, " infile:\n"); + fprintf(stderr, " MLSA filter coefficients (%s) [stdin]\n", FORMAT); + fprintf(stderr, " stdout:\n"); + fprintf(stderr, " mel-cepstrum (%s)\n", FORMAT); +#ifdef PACKAGE_VERSION + fprintf(stderr, "\n"); + fprintf(stderr, " SPTK: version %s\n", PACKAGE_VERSION); + fprintf(stderr, " CVS Info: %s", rcs_id); +#endif + fprintf(stderr, "\n"); + exit(status); +} + + +int main(int argc, char **argv) +{ + int m = ORDER, m1; + FILE *fp = stdin; + double a = ALPHA, *x; + + if ((cmnd = strrchr(argv[0], '/')) == NULL) + cmnd = argv[0]; + else + cmnd++; + while (--argc) + if (**++argv == '-') { + switch (*(*argv + 1)) { + case 'a': + a = atof(*++argv); + --argc; + break; + case 'm': + m = atoi(*++argv); + --argc; + break; + case 'h': + usage(0); + default: + fprintf(stderr, "%s : Invalid option '%c'!\n", cmnd, *(*argv + 1)); + usage(1); + } + } else + fp = getfp(*argv, "rb"); + + m1 = m + 1; + + x = dgetmem(m1); + + while (freadf(x, sizeof(*x), m1, fp) == m1) { + b2mc(x, x, m, a); + fwritef(x, sizeof(*x), m1, stdout); + } + return (0); +} diff --git a/pool/shard000/C/0009991_clockport.c b/pool/shard000/C/0009991_clockport.c new file mode 100644 index 0000000000000000000000000000000000000000..28bd1e5dc31930938dc57b05df28d20111ae3492 --- /dev/null +++ b/pool/shard000/C/0009991_clockport.c @@ -0,0 +1,188 @@ +/* + * clockport.c - ClockPort emulation. + * + * Written by + * Marco van den Heuvel + * + * This file is part of VICE, the Versatile Commodore Emulator. + * See README for copyright notice. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + * 02111-1307 USA. + * + */ + +#include "vice.h" + +#include +#include +#include + +#include "clockport.h" +#include "lib.h" + +#ifdef HAVE_RAWNET +#include "clockport-rrnet.h" +#endif + +#ifdef USE_MPG123 +#include "clockport-mp3at64.h" +#endif + +/* TODO */ +#if 0 +#include "clockport_eth64_ii.h" +#include "clockport_silver_surfer.h" +#include "clockport_cw3_sid.h" +#endif + +clockport_supported_devices_t clockport_supported_devices[] = { + { CLOCKPORT_DEVICE_NONE, "None" }, +#ifdef HAVE_RAWNET + { CLOCKPORT_DEVICE_RRNET, "RRNet" }, +#endif +#ifdef USE_MPG123 + { CLOCKPORT_DEVICE_MP3_64, "MP3@64" }, +#endif +#if 0 + { CLOCKPORT_DEVICE_ETH64_II, "ETH64-II" }, + { CLOCKPORT_DEVICE_SILVER_SURFER, "Silver Surfer" }, + { CLOCKPORT_DEVICE_CW3_SID, "CatWeasel MKIII SID" }, +#endif + { -1, NULL } +}; + +char *clockport_device_id_to_name(int id) +{ + int i; + + for (i = 0; clockport_supported_devices[i].name; ++i) { + if (clockport_supported_devices[i].id == id) { + return clockport_supported_devices[i].name; + } + } + return "Unknown"; +} + +static clockport_device_list_t clockport_device_head = { NULL, NULL }; + +int clockport_resources_init(void) +{ + /* Init clockport devices */ +#ifdef HAVE_RAWNET + clockport_rrnet_init(); +#endif + +#ifdef USE_MPG123 + clockport_mp3at64_init(); +#endif + + /* TODO */ +#if 0 + clockport_eth64_ii_init(); + clockport_silver_surfer_init(); + clockport_cw3_sid_init(); +#endif + + return 0; +} + +void clockport_resources_shutdown(void) +{ + clockport_device_list_t *current = &clockport_device_head; + + while (current->next != NULL) { + if (current->next->device) { + clockport_close_device(current->next->device); + } + } + + /* Shutdown clockport devices */ +#ifdef HAVE_RAWNET + clockport_rrnet_shutdown(); +#endif + +#ifdef USE_MPG123 + clockport_mp3at64_shutdown(); +#endif + + /* TODO */ +#if 0 + clockport_eth64_ii_shutdown(); + clockport_silver_surfer_shutdown(); + clockport_cw3_sid_shutdown(); +#endif +} + +clockport_device_t *clockport_open_device(int deviceid, char *owner) +{ + clockport_device_list_t *current = &clockport_device_head; + clockport_device_t *retval = NULL; + clockport_device_list_t *entry = NULL; + + switch (deviceid) { +#ifdef HAVE_RAWNET + case CLOCKPORT_DEVICE_RRNET: + retval = clockport_rrnet_open_device(owner); + break; +#endif + +#ifdef USE_MPG123 + case CLOCKPORT_DEVICE_MP3_64: + retval = clockport_mp3at64_open_device(owner); + break; +#endif + + /* TODO */ +#if 0 + case CLOCKPORT_DEVICE_ETH64_II: + retval = clockport_eth64_ii_open_device(owner); + break; + case CLOCKPORT_DEVICE_SILVER_SURFER: + retval = clockport_silver_surfer_open_device(owner); + break; + case CLOCKPORT_DEVICE_CW3_SID: + retval = clockport_cw3_sid_open_device(owner); + break; +#endif + } + + if (retval) { + entry = lib_malloc(sizeof(clockport_device_list_t)); + while (current->next != NULL) { + current = current->next; + } + current->next = entry; + entry->device = retval; + entry->next = NULL; + } + return retval; +} + +void clockport_close_device(clockport_device_t *device) +{ + clockport_device_list_t *current = &clockport_device_head; + clockport_device_list_t *prev = NULL; + + while (current->next != NULL) { + prev = current; + current = current->next; + if (current->device == device) { + current->device->close(device); + prev->next = current->next; + lib_free(current); + } + } +} diff --git a/pool/shard000/C/0010002_CWE78_OS_Command_Injection__wchar_t_console_execl_14.c b/pool/shard000/C/0010002_CWE78_OS_Command_Injection__wchar_t_console_execl_14.c new file mode 100644 index 0000000000000000000000000000000000000000..a2ccf872fdea8228395de4c4296130794c3befe3 --- /dev/null +++ b/pool/shard000/C/0010002_CWE78_OS_Command_Injection__wchar_t_console_execl_14.c @@ -0,0 +1,157 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE78_OS_Command_Injection__wchar_t_console_execl_14.c +Label Definition File: CWE78_OS_Command_Injection.strings.label.xml +Template File: sources-sink-14.tmpl.c +*/ +/* + * @description + * CWE: 78 OS Command Injection + * BadSource: console Read input from the console + * GoodSource: Fixed string + * Sink: execl + * BadSink : execute command with wexecl + * Flow Variant: 14 Control flow: if(globalFive==5) and if(globalFive!=5) + * + * */ + +#include "std_testcase.h" + +#include + +#ifdef _WIN32 +#define COMMAND_INT_PATH L"%WINDIR%\\system32\\cmd.exe" +#define COMMAND_INT L"cmd.exe" +#define COMMAND_ARG1 L"/c" +#define COMMAND_ARG2 L"dir" +#define COMMAND_ARG3 data +#else /* NOT _WIN32 */ +#include +#define COMMAND_INT_PATH L"/bin/sh" +#define COMMAND_INT L"sh" +#define COMMAND_ARG1 L"ls" +#define COMMAND_ARG2 L"-la" +#define COMMAND_ARG3 data +#endif + +#ifdef _WIN32 +#include +#define EXECL _wexecl +#else /* NOT _WIN32 */ +#define EXECL execl +#endif + +#ifndef OMITBAD + +void CWE78_OS_Command_Injection__wchar_t_console_execl_14_bad() +{ + wchar_t * data; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + if(globalFive==5) + { + { + /* Read input from the console */ + size_t dataLen = wcslen(data); + /* if there is room in data, read into it from the console */ + if (100-dataLen > 1) + { + /* POTENTIAL FLAW: Read data from the console */ + if (fgetws(data+dataLen, (int)(100-dataLen), stdin) != NULL) + { + /* The next few lines remove the carriage return from the string that is + * inserted by fgetws() */ + dataLen = wcslen(data); + if (dataLen > 0 && data[dataLen-1] == L'\n') + { + data[dataLen-1] = L'\0'; + } + } + else + { + printLine("fgetws() failed"); + /* Restore NUL terminator if fgetws fails */ + data[dataLen] = L'\0'; + } + } + } + } + /* wexecl - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + EXECL(COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B1() - use goodsource and badsink by changing the globalFive==5 to globalFive!=5 */ +static void goodG2B1() +{ + wchar_t * data; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + if(globalFive!=5) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + /* FIX: Append a fixed string to data (not user / external input) */ + wcscat(data, L"*.*"); + } + /* wexecl - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + EXECL(COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL); +} + +/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ +static void goodG2B2() +{ + wchar_t * data; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + if(globalFive==5) + { + /* FIX: Append a fixed string to data (not user / external input) */ + wcscat(data, L"*.*"); + } + /* wexecl - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + EXECL(COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL); +} + +void CWE78_OS_Command_Injection__wchar_t_console_execl_14_good() +{ + goodG2B1(); + goodG2B2(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE78_OS_Command_Injection__wchar_t_console_execl_14_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE78_OS_Command_Injection__wchar_t_console_execl_14_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard000/C/0010013_stream_udp.c b/pool/shard000/C/0010013_stream_udp.c new file mode 100644 index 0000000000000000000000000000000000000000..d6bf3e5effc5dac66258e793caf225f7463684c0 --- /dev/null +++ b/pool/shard000/C/0010013_stream_udp.c @@ -0,0 +1,111 @@ +/* + * stream layer for MPEG over UDP, based on previous work from Dave Chapman + * + * Copyright (C) 2006 Benjamin Zores + * + * This file is part of MPlayer. + * + * MPlayer is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * MPlayer 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 MPlayer; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include "config.h" + +#include +#include + +#include "mp_msg.h" +#include "network.h" +#include "stream.h" +#include "url.h" +#include "udp.h" + +static int +udp_streaming_start (stream_t *stream) +{ + streaming_ctrl_t *streaming_ctrl; + int fd; + + if (!stream) + return -1; + + streaming_ctrl = stream->streaming_ctrl; + fd = stream->fd; + + if (fd < 0) + { + fd = udp_open_socket (streaming_ctrl->url); + if (fd < 0) + return -1; + stream->fd = fd; + } + + streaming_ctrl->streaming_read = nop_streaming_read; + streaming_ctrl->streaming_seek = nop_streaming_seek; + streaming_ctrl->prebuffer_size = 64 * 1024; /* 64 KBytes */ + streaming_ctrl->buffering = 0; + streaming_ctrl->status = streaming_playing_e; + + return 0; +} + +static int +udp_stream_open (stream_t *stream, int mode, void *opts, int *file_format) +{ + URL_t *url; + + mp_msg (MSGT_OPEN, MSGL_INFO, "STREAM_UDP, URL: %s\n", stream->url); + stream->streaming_ctrl = streaming_ctrl_new (); + if (!stream->streaming_ctrl) + return STREAM_ERROR; + + stream->streaming_ctrl->bandwidth = network_bandwidth; + url = url_new (stream->url); + stream->streaming_ctrl->url = check4proxies (url); + + if (url->port == 0) + { + mp_msg (MSGT_NETWORK, MSGL_ERR, + "You must enter a port number for UDP streams!\n"); + streaming_ctrl_free (stream->streaming_ctrl); + stream->streaming_ctrl = NULL; + + return STREAM_UNSUPPORTED; + } + + if (udp_streaming_start (stream) < 0) + { + mp_msg (MSGT_NETWORK, MSGL_ERR, "udp_streaming_start failed\n"); + streaming_ctrl_free (stream->streaming_ctrl); + stream->streaming_ctrl = NULL; + + return STREAM_UNSUPPORTED; + } + + stream->type = STREAMTYPE_STREAM; + fixup_network_stream_cache (stream); + + return STREAM_OK; +} + +const stream_info_t stream_info_udp = { + "MPEG over UDP streaming", + "udp", + "Dave Chapman, Benjamin Zores", + "native udp support", + udp_stream_open, + { "udp", NULL}, + NULL, + 0 // Urls are an option string +}; diff --git a/pool/shard000/C/0010029_iputil.c b/pool/shard000/C/0010029_iputil.c new file mode 100644 index 0000000000000000000000000000000000000000..4f66c6bded2ad7b38a483ae7e5aa141694b88feb --- /dev/null +++ b/pool/shard000/C/0010029_iputil.c @@ -0,0 +1,186 @@ +/* This file is part of GNU Dico. + Copyright (C) 1998-2000, 2008, 2010, 2012 Sergey Poznyakoff + + GNU Dico 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, or (at your option) + any later version. + + GNU Dico 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 GNU Dico. If not, see . */ + +#ifdef HAVE_CONFIG_H +# include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include + +/* + * Return an IP address in host long notation from a host + * name or address in dot notation. + */ +IPADDR +get_ipaddr(char *host) +{ + struct hostent *hp; + struct in_addr addr; + + if (inet_aton(host, &addr)) + return ntohl(addr.s_addr); + else if ((hp = gethostbyname(host)) == NULL) + return 0; + else + return ntohl(*(UINT4 *) hp->h_addr); +} + +/* + * Return a printable host name (or IP address in dot notation) + * for the supplied IP address. + */ +char * +ip_hostname(IPADDR ipaddr) +{ + struct hostent *hp; + UINT4 n_ipaddr; + + n_ipaddr = htonl(ipaddr); + hp = gethostbyaddr((char *) &n_ipaddr, sizeof(struct in_addr), + AF_INET); + if (!hp) { + struct in_addr in; + in.s_addr = htonl(ipaddr); + return inet_ntoa(in); + } + return (char *) hp->h_name; +} + +IPADDR +getmyip() +{ + char myname[256]; + + gethostname(myname, sizeof(myname)); + return get_ipaddr(myname); +} + +int +str2port(char *str) +{ + struct servent *serv; + char *p; + int port; + + /* First try to read it from /etc/services */ + serv = getservbyname(str, "tcp"); + + if (serv != NULL) + port = ntohs(serv->s_port); + else { + long l; + /* Not in services, maybe a number? */ + l = strtol(str, &p, 0); + + if (*p || l < 0 || l > USHRT_MAX) + return -1; + + port = l; + } + + return port; +} + +static size_t +mu_stpcpy (char **pbuf, size_t *psize, const char *src) +{ + size_t slen = strlen (src); + if (pbuf == NULL || *pbuf == NULL) + return slen; + else { + char *buf = *pbuf; + size_t size = *psize; + if (size > slen) + size = slen; + memcpy (buf, src, size); + *psize -= size; + *pbuf += size; + if (*psize) + **pbuf = 0; + else + (*pbuf)[-1] = 0; + return size; + } +} + +#define S_UN_NAME(sa, salen) \ + ((salen < offsetof (struct sockaddr_un,sun_path)) ? "" : (sa)->sun_path) + +void +sockaddr_to_str (const struct sockaddr *sa, int salen, + char *bufptr, size_t buflen, + size_t *plen) +{ + char buf[INT_BUFSIZE_BOUND (uintmax_t)]; /* FIXME: too much */ + size_t len = 0; + switch (sa->sa_family) { + case AF_INET: + { + struct sockaddr_in s_in = *(struct sockaddr_in *)sa; + len += mu_stpcpy (&bufptr, &buflen, inet_ntoa(s_in.sin_addr)); + len += mu_stpcpy (&bufptr, &buflen, ":"); + len += mu_stpcpy (&bufptr, &buflen, umaxtostr(ntohs (s_in.sin_port), + buf)); + break; + } + + case AF_UNIX: + { + struct sockaddr_un *s_un = (struct sockaddr_un *)sa; + if (S_UN_NAME(s_un, salen)[0] == 0) + len += mu_stpcpy (&bufptr, &buflen, "anonymous socket"); + else { + len += mu_stpcpy (&bufptr, &buflen, "socket "); + len += mu_stpcpy (&bufptr, &buflen, s_un->sun_path); + } + break; + } + + default: + len += mu_stpcpy (&bufptr, &buflen, "{Unsupported family: "); + len += mu_stpcpy (&bufptr, &buflen, umaxtostr (sa->sa_family, buf)); + len += mu_stpcpy (&bufptr, &buflen, "}"); + } + if (plen) + *plen = len + 1; +} + +char * +sockaddr_to_astr (const struct sockaddr *sa, int salen) +{ + size_t size; + char *p; + + sockaddr_to_str(sa, salen, NULL, 0, &size); + p = xmalloc(size); + sockaddr_to_str(sa, salen, p, size, NULL); + return p; +} diff --git a/pool/shard000/C/0010038_http_utils.c b/pool/shard000/C/0010038_http_utils.c new file mode 100644 index 0000000000000000000000000000000000000000..b9d6786c48316f4a3f4536fbadb0f0db8147a536 --- /dev/null +++ b/pool/shard000/C/0010038_http_utils.c @@ -0,0 +1,100 @@ +#include "http_utils.h" + +int init_http_environment(int ssl) { + if (ssl) { + return curl_global_init(CURL_GLOBAL_SSL); + } else { + return curl_global_init(CURL_GLOBAL_NOTHING); + } +} + +int http_get(char *url, char **params, char **params_values, int num_params, size_t (*write_function) (char*, size_t, size_t, void*), void *buffer) { + CURL *curl; + CURLcode ret_code = CURLE_OK; + char *aux_url; + + if (params != NULL && params_values != NULL) { + // Add request parameters to the URL + for (int i = 0; i < num_params; i++) { + int param_len; + if (i > 0) { param_len = strlen(params[i]) + strlen(params_values[i]) + 1; } + else { param_len = strlen(params[i]) + strlen(params_values[i]) + 2; } + aux_url = (char*) realloc (url, (strlen(url) + param_len + 1) * sizeof(char)); + if (aux_url) { + url = aux_url; + if (i == 0) { strncat(url, "?", 1); } + strncat(url, params[i], strlen(params[i])); + strncat(url, "=", 1); + strncat(url, params_values[i], strlen(params_values[i])); + } + } + } + + curl = curl_easy_init(); + + if(curl) { +// if (debug) { curl_easy_setopt(curl, CURLOPT_VERBOSE, 1); } + + curl_easy_setopt(curl, CURLOPT_URL, url); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_function); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, buffer); + + // Option for avoiding a segfault caused by a signal in libcurl + // http://stackoverflow.com/questions/9191668/error-longjmp-causes-uninitialized-stack-frame + curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1); + + ret_code = curl_easy_perform(curl); + if (ret_code != 0) { LOG_ERROR_F("ret_code = %s\n", curl_easy_strerror(ret_code)); } + + curl_easy_cleanup(curl); + } else { + ret_code = CURLE_FAILED_INIT; + } + + return ret_code; +} + + +int http_post(char *url, char **params, char **params_values, int num_params, size_t (*write_function) (char*, size_t, size_t, void*), void *buffer) { + CURL *curl; + CURLcode ret_code = CURLE_OK; + + struct curl_httppost *formpost = NULL; + struct curl_httppost *lastptr = NULL; + + // Set request parameters + for (int i = 0; i < num_params; i++) { + curl_formadd(&formpost, &lastptr, + CURLFORM_COPYNAME, params[i], + CURLFORM_PTRCONTENTS, params_values[i], + CURLFORM_END); + } + + curl = curl_easy_init(); + + if(curl) { +// if (debug) { curl_easy_setopt(curl, CURLOPT_VERBOSE, 1); } + + curl_easy_setopt(curl, CURLOPT_URL, url); + curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_function); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, buffer); + // Option for avoiding a segfault caused by a signal in libcurl + // http://stackoverflow.com/questions/9191668/error-longjmp-causes-uninitialized-stack-frame + curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1); + + ret_code = curl_easy_perform(curl); + if (ret_code != 0) { LOG_ERROR_F("ret_code = %s\n", curl_easy_strerror(ret_code)); } + + curl_easy_cleanup(curl); + curl_formfree(formpost); + } else { + ret_code = CURLE_FAILED_INIT; + } + + return ret_code; +} + +const char *get_last_http_error(int err_code) { + return curl_easy_strerror(err_code); +} diff --git a/pool/shard000/C/0010044_uart_cpu_maltausart.c b/pool/shard000/C/0010044_uart_cpu_maltausart.c new file mode 100644 index 0000000000000000000000000000000000000000..5f046223e32fdb17c8ad8de6c0c6aa987aafb75d --- /dev/null +++ b/pool/shard000/C/0010044_uart_cpu_maltausart.c @@ -0,0 +1,78 @@ +/*- + * Copyright (c) 2006 Wojciech A. Koszek + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * $Id$ + */ +/* + * Skeleton of this file was based on respective code for ARM + * code written by Olivier Houchard. + */ +#include "opt_uart.h" + +#include +__FBSDID("$FreeBSD: soc2013/dpl/head/sys/mips/malta/uart_cpu_maltausart.c 202218 2010-01-12 21:36:08Z imp $"); + +#include +#include +#include +#include + +#include + +#include +#include + +#include + +bus_space_tag_t uart_bus_space_io; +bus_space_tag_t uart_bus_space_mem; + +extern struct uart_ops malta_usart_ops; +extern struct bus_space malta_bs_tag; + +int +uart_cpu_eqres(struct uart_bas *b1, struct uart_bas *b2) +{ + return ((b1->bsh == b2->bsh && b1->bst == b2->bst) ? 1 : 0); +} + +int +uart_cpu_getdev(int devtype, struct uart_devinfo *di) +{ + di->ops = uart_getops(&uart_ns8250_class); + di->bas.chan = 0; + di->bas.bst = mips_bus_space_generic; + di->bas.bsh = MIPS_PHYS_TO_KSEG1(MALTA_UART0ADR); + di->bas.regshft = 0; + di->bas.rclk = 0; + di->baudrate = 0; /* retain the baudrate configured by YAMON */ + di->databits = 8; + di->stopbits = 1; + di->parity = UART_PARITY_NONE; + + uart_bus_space_io = NULL; + uart_bus_space_mem = mips_bus_space_generic; + return (0); +} diff --git a/pool/shard000/C/0010090_ls.c b/pool/shard000/C/0010090_ls.c new file mode 100644 index 0000000000000000000000000000000000000000..cbaa160ac2f327bba9dc0b38155db75f0d40f0f8 --- /dev/null +++ b/pool/shard000/C/0010090_ls.c @@ -0,0 +1,101 @@ +/* sdb - LGPLv3 - Copyright 2007-2014 - pancake */ + +#include +#include "ls.h" + +SDB_API SdbList *ls_new() { + SdbList *list = R_NEW (SdbList); + if (!list) + return NULL; + list->head = NULL; + list->tail = NULL; + list->free = free; // HACK + list->length = 0; + return list; +} + +SDB_API void ls_sort(SdbList *list, SdbListComparator cmp) { + SdbListIter *it, *it2; + for (it = list->head; it && it->data; it = it->n) { + for (it2 = it->n; it2 && it2->data; it2 = it2->n) { + if (cmp (it->data, it2->data)>0) { + void *t = it->data; + it->data = it2->data; + it2->data = t; + } + } + } +} + +SDB_API void ls_delete (SdbList *list, SdbListIter *iter) { + if (!list || !iter) return; + ls_split_iter (list, iter); + if (list->free && iter->data) { + list->free (iter->data); + iter->data = NULL; + } + free (iter); + list->length--; +} + +SDB_API void ls_split_iter (SdbList *list, SdbListIter *iter) { + if (!list || !iter) return; + if (list->head == iter) list->head = iter->n; + if (list->tail == iter) list->tail = iter->p; + if (iter->p) iter->p->n = iter->n; + if (iter->n) iter->n->p = iter->p; +} + +SDB_API void ls_destroy (SdbList *list) { + SdbListIter *it; + if (!list) return; + it = list->head; + while (it) { + SdbListIter *next = it->n; + ls_delete (list, it); + it = next; + } + list->head = list->tail = NULL; + list->length = 0; +} + +SDB_API void ls_free (SdbList *list) { + if (!list) return; + ls_destroy (list); + list->free = NULL; + free (list); +} + +SDB_API SdbListIter *ls_append(SdbList *list, void *data) { + SdbListIter *it; + if (!list) + return NULL; + it = R_NEW (SdbListIter); + if (!it) + return NULL; + if (list->tail) + list->tail->n = it; + it->data = data; + it->p = list->tail; + it->n = NULL; + list->tail = it; + if (list->head == NULL) + list->head = it; + list->length++; + return it; +} + +SDB_API SdbListIter *ls_prepend(SdbList *list, void *data) { + SdbListIter *it = R_NEW (SdbListIter); + if (!it) return NULL; + if (list->head) + list->head->p = it; + it->data = data; + it->n = list->head; + it->p = NULL; + list->head = it; + if (list->tail == NULL) + list->tail = it; + list->length++; + return it; +} diff --git a/pool/shard000/C/0010093_tetris.c b/pool/shard000/C/0010093_tetris.c new file mode 100644 index 0000000000000000000000000000000000000000..33f83c0803a31c142fdb9207154a35d5f637127e --- /dev/null +++ b/pool/shard000/C/0010093_tetris.c @@ -0,0 +1,67 @@ +/* + OBI2003 - tetris.c + Guilherme Ottoni +*/ + +#include +#include +#include + +#define MAIS_INFINITO 20000 +#define MENOS_INFINITO -1 + +struct Compet +{ + char nome[16]; + int pontos; +} compet[1010]; + +int n; + +int compara(const void * p1, const void * p2) +{ + int r = ((struct Compet *)p2)->pontos - ((struct Compet *)p1)->pontos; + if (r != 0) + return r; + return strcmp(((struct Compet *)p1)->nome, ((struct Compet *)p2)->nome); +} + +int main() +{ + int pontos, p, min, max, i, k, classif, pontos_ant, teste=1; + while (scanf("%d", &n) == 1 && n > 0) + { + /* le jogadores e pontuacoes */ + for (i = 0; i < n; i++) + { + scanf("%s", compet[i].nome); + min = MAIS_INFINITO; + max = MENOS_INFINITO; + pontos = 0; + for (k = 0; k < 12; k++) + { + scanf("%d", &p); + if (p < min) + min = p; + if (p > max) + max = p; + pontos += p; + } + compet[i].pontos = pontos - max - min; + } + /* ordena */ + qsort(compet, n, sizeof(struct Compet), compara); + /* calcula classificacao e imprime */ + pontos_ant = MAIS_INFINITO; + printf("Teste %d\n", teste++); + for (i = 0; i < n; i++) + { + if (compet[i].pontos != pontos_ant) + classif = i + 1; + printf("%d %d %s\n", classif, compet[i].pontos, compet[i].nome); + pontos_ant = compet[i].pontos; + } + printf("\n"); + } + return 0; +} diff --git a/pool/shard000/C/0010095_cms_menu_vtx.c b/pool/shard000/C/0010095_cms_menu_vtx.c new file mode 100644 index 0000000000000000000000000000000000000000..abbb488f5c71c2a71fb4ae39837dc0ad1b214a7b --- /dev/null +++ b/pool/shard000/C/0010095_cms_menu_vtx.c @@ -0,0 +1,148 @@ +/* + * This file is part of Cleanflight. + * + * Cleanflight 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. + * + * Cleanflight 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 Cleanflight. If not, see . + */ + +#include +#include +#include + +#include "platform.h" + +#include "build/version.h" + +#include "cms/cms.h" +#include "cms/cms_types.h" +#include "cms/cms_menu_vtx.h" + +#include "common/utils.h" + +#include "config/config_profile.h" +#include "config/config_master.h" +#include "config/feature.h" + +#ifdef CMS + +#if defined(VTX) || defined(USE_RTC6705) + +static bool featureRead = false; +static uint8_t cmsx_featureVtx = 0, cmsx_vtxBand, cmsx_vtxChannel; + +static long cmsx_Vtx_FeatureRead(void) +{ + if (!featureRead) { + cmsx_featureVtx = feature(FEATURE_VTX) ? 1 : 0; + featureRead = true; + } + + return 0; +} + +static long cmsx_Vtx_FeatureWriteback(void) +{ + if (cmsx_featureVtx) + featureSet(FEATURE_VTX); + else + featureClear(FEATURE_VTX); + + return 0; +} + +static const char * const vtxBandNames[] = { + "BOSCAM A", + "BOSCAM B", + "BOSCAM E", + "FATSHARK", + "RACEBAND", +}; + +static OSD_TAB_t entryVtxBand = {&cmsx_vtxBand,4,&vtxBandNames[0]}; +static OSD_UINT8_t entryVtxChannel = {&cmsx_vtxChannel, 1, 8, 1}; + +static void cmsx_Vtx_ConfigRead(void) +{ +#ifdef VTX + cmsx_vtxBand = masterConfig.vtx_band; + cmsx_vtxChannel = masterConfig.vtx_channel + 1; +#endif // VTX + +#ifdef USE_RTC6705 + cmsx_vtxBand = masterConfig.vtx_channel / 8; + cmsx_vtxChannel = masterConfig.vtx_channel % 8 + 1; +#endif // USE_RTC6705 +} + +static void cmsx_Vtx_ConfigWriteback(void) +{ +#ifdef VTX + masterConfig.vtx_band = cmsx_vtxBand; + masterConfig.vtx_channel = cmsx_vtxChannel - 1; +#endif // VTX + +#ifdef USE_RTC6705 + masterConfig.vtx_channel = cmsx_vtxBand * 8 + cmsx_vtxChannel - 1; +#endif // USE_RTC6705 +} + +static long cmsx_Vtx_onEnter(void) +{ + cmsx_Vtx_FeatureRead(); + cmsx_Vtx_ConfigRead(); + + return 0; +} + +static long cmsx_Vtx_onExit(const OSD_Entry *self) +{ + UNUSED(self); + + cmsx_Vtx_ConfigWriteback(); + + return 0; +} + +#ifdef VTX +static OSD_UINT8_t entryVtxMode = {&masterConfig.vtx_mode, 0, 2, 1}; +static OSD_UINT16_t entryVtxMhz = {&masterConfig.vtx_mhz, 5600, 5950, 1}; +#endif // VTX + +static OSD_Entry cmsx_menuVtxEntries[] = +{ + {"--- VTX ---", OME_Label, NULL, NULL, 0}, + {"ENABLED", OME_Bool, NULL, &cmsx_featureVtx, 0}, +#ifdef VTX + {"VTX MODE", OME_UINT8, NULL, &entryVtxMode, 0}, + {"VTX MHZ", OME_UINT16, NULL, &entryVtxMhz, 0}, +#endif // VTX + {"BAND", OME_TAB, NULL, &entryVtxBand, 0}, + {"CHANNEL", OME_UINT8, NULL, &entryVtxChannel, 0}, +#ifdef USE_RTC6705 + {"LOW POWER", OME_Bool, NULL, &masterConfig.vtx_power, 0}, +#endif // USE_RTC6705 + {"BACK", OME_Back, NULL, NULL, 0}, + {NULL, OME_END, NULL, NULL, 0} +}; + +CMS_Menu cmsx_menuVtx = { + .GUARD_text = "MENUVTX", + .GUARD_type = OME_MENU, + .onEnter = cmsx_Vtx_onEnter, + .onExit= cmsx_Vtx_onExit, + .onGlobalExit = cmsx_Vtx_FeatureWriteback, + .entries = cmsx_menuVtxEntries +}; + +#endif // VTX || USE_RTC6705 +#endif // CMS diff --git a/pool/shard000/C/0010104_i286c_fe.c b/pool/shard000/C/0010104_i286c_fe.c new file mode 100644 index 0000000000000000000000000000000000000000..fc8bfd47520610c350e622c3bdc7d74880c45beb --- /dev/null +++ b/pool/shard000/C/0010104_i286c_fe.c @@ -0,0 +1,222 @@ +#include +#include +#include "i286c.h" +#include "i286c.mcr" + + +// ------------------------------------------------------------ opecode 0xfe,f + +#if 0 +I286_F6 _nop_int(UINT op) { + + INT_NUM(6, I286_IP - 2); +} +#endif + +I286_F6 _inc_ea8(UINT op) { + + UINT32 madr; + UINT8 *out; + REG8 res; + + if (op >= 0xc0) { + I286_WORKCLOCK(2); + out = REG8_B20(op); + } + else { + I286_WORKCLOCK(7); + madr = CALC_EA(op); + if (madr >= I286_MEMWRITEMAX) { + res = i286_memoryread(madr); + INCBYTE(res) + i286_memorywrite(madr, res); + return; + } + out = mem + madr; + } + res = *out; + INCBYTE(res) + *out = (UINT8)res; +} + +I286_F6 _dec_ea8(UINT op) { + + UINT32 madr; + UINT8 *out; + REG8 res; + + if (op >= 0xc0) { + I286_WORKCLOCK(2); + out = REG8_B20(op); + } + else { + I286_WORKCLOCK(7); + madr = CALC_EA(op); + if (madr >= I286_MEMWRITEMAX) { + res = i286_memoryread(madr); + DECBYTE(res) + i286_memorywrite(madr, res); + return; + } + out = mem + madr; + } + res = *out; + DECBYTE(res) + *out = (UINT8)res; +} + +I286_F6 _inc_ea16(UINT op) { + + UINT32 madr; + UINT16 *out; + REG16 res; + + if (op >= 0xc0) { + I286_WORKCLOCK(2); + out = REG16_B20(op); + } + else { + I286_WORKCLOCK(7); + madr = CALC_EA(op); + if (INHIBIT_WORDP(madr)) { + res = i286_memoryread_w(madr); + INCWORD(res) + i286_memorywrite_w(madr, res); + return; + } + out = (UINT16 *)(mem + madr); + } + res = *out; + INCWORD(res) + *out = (UINT16)res; +} + +I286_F6 _dec_ea16(UINT op) { + + UINT32 madr; + UINT16 *out; + REG16 res; + + if (op >= 0xc0) { + I286_WORKCLOCK(2); + out = REG16_B20(op); + } + else { + I286_WORKCLOCK(7); + madr = CALC_EA(op); + if (INHIBIT_WORDP(madr)) { + res = i286_memoryread_w(madr); + DECWORD(res) + i286_memorywrite_w(madr, res); + return; + } + out = (UINT16 *)(mem + madr); + } + res = *out; + DECWORD(res) + *out = (UINT16)res; +} + +I286_F6 _call_ea16(UINT op) { + + UINT16 src; + + if (op >= 0xc0) { + I286_WORKCLOCK(7); + src = *(REG16_B20(op)); + } + else { + I286_WORKCLOCK(11); + src = i286_memoryread_w(CALC_EA(op)); + } + REGPUSH0(I286_IP); + I286_IP = src; +} + +I286_F6 _call_far_ea16(UINT op) { + + UINT32 seg; + UINT ad; + + I286_WORKCLOCK(16); + if (op < 0xc0) { + ad = GET_EA(op, &seg); + REGPUSH0(I286_CS) // ToDo + REGPUSH0(I286_IP) + I286_IP = i286_memoryread_w(seg + ad); + I286_CS = i286_memoryread_w(seg + LOW16(ad + 2)); + CS_BASE = SEGSELECT(I286_CS); + } + else { + INT_NUM(6, I286_IP - 2); + } +} + +I286_F6 _jmp_ea16(UINT op) { + + if (op >= 0xc0) { + I286_WORKCLOCK(7); + I286_IP = *(REG16_B20(op)); + } + else { + I286_WORKCLOCK(11); + I286_IP = i286_memoryread_w(CALC_EA(op)); + } +} + +I286_F6 _jmp_far_ea16(UINT op) { + + UINT32 seg; + UINT ad; + + I286_WORKCLOCK(11); + if (op < 0xc0) { + ad = GET_EA(op, &seg); + I286_IP = i286_memoryread_w(seg + ad); + I286_CS = i286_memoryread_w(seg + LOW16(ad + 2)); + CS_BASE = SEGSELECT(I286_CS); + } + else { + INT_NUM(6, I286_IP - 2); + } +} + +I286_F6 _push_ea16(UINT op) { + + UINT16 src; + + if (op >= 0xc0) { + I286_WORKCLOCK(3); + src = *(REG16_B20(op)); + } + else { + I286_WORKCLOCK(5); + src = i286_memoryread_w(CALC_EA(op)); + } + REGPUSH0(src); +} + +I286_F6 _pop_ea16(UINT op) { + + UINT16 src; + + REGPOP0(src); + I286_WORKCLOCK(5); + if (op >= 0xc0) { + *(REG16_B20(op)) = src; + } + else { + i286_memorywrite_w(CALC_EA(op), src); + } +} + + +const I286OPF6 c_ope0xfe_table[] = { + _inc_ea8, _dec_ea8}; + +const I286OPF6 c_ope0xff_table[] = { + _inc_ea16, _dec_ea16, + _call_ea16, _call_far_ea16, + _jmp_ea16, _jmp_far_ea16, + _push_ea16, _pop_ea16}; + diff --git a/pool/shard000/C/0010108_menu3.c b/pool/shard000/C/0010108_menu3.c new file mode 100644 index 0000000000000000000000000000000000000000..d9dd886f813e4190204747a42674159fb6503d49 --- /dev/null +++ b/pool/shard000/C/0010108_menu3.c @@ -0,0 +1,96 @@ +/*Write a menu program to satisfy the following functions. +a) Check whether given string is palindrome or not +b) Find all the prime numbers from 100 to 200 +c) Sum of n natural numbers +d) Exit from program +(Perform above task until the user wants to exit. Full marks is given if user-defined functions are used) +*/ + +#include +#include + +// Defining the prototype functions +void palindrome(char*); +void prime(int,int); +void sum(int); + +int main(){ + int n; + char string[100],option; + + // Providing the user the menu, the program exits only if the user enter 'd' as option + do{ + printf("\n\nPlease Choose the following option:\n"); + printf("a) Check whether given string is palindrome or not\n"); + printf("b) Find all the prime numbers from 100 to 200\n"); + printf("c) Sum of n natural numbers\n"); + printf("d) Exit from program\n"); + printf("Enter option: "); + scanf("%c",&option); + + switch(option){ + case 'a': + printf("Enter string: "); + scanf("%s",string); + palindrome(string); + break; + case 'b': + prime(100,200); // passing 100 and 200 as arguments as the questions asks for it + break; + case 'c': + printf("Enter number: "); + scanf("%d",&n); + sum(n); + case 'd': + break; + default: + printf("Please enter correct option\n"); + } + // Flush the stdin so that we don't get multiple menu. Remove the following fflush line to see what issue I am talking about + fflush(stdin); + }while(option!='d'); // Loop until the user explictly enters 'd' as the option + return 0; +} + +// Checking if the given string is palindrome or not +void palindrome(char* string){ + int i; + char temp[100]; + strcpy(temp,string); + strrev(temp); + if(strcmp(string,temp)==0) + printf("The given string %s is palindrome\n",string); + else + printf("The given string %s is not palindrome\n",string); + } + +// Printing the prime numbers from start number to end number +void prime(int start,int end){ + int i; + int j; + int counter=0; + printf("\nPrime number from %d to %d:-\n",start,end); + for(i=start;i +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +extern struct config *config_get(void); +extern int platform_init(void); + +static const struct option options[] = { + { + .name = "list", + .val = 'l', + }, + { 0 }, +}; + +static void usage(const char *progname) +{ + fprintf(stderr, "Usage:\t%1$s \n" + "\t%1$s --list\n", progname); +} + +static void print_one_config(void *ctx, const char *req, const char *name, + const char *fmt, ...) +{ + bool use_prefix = !req; + char *val, *sep; + va_list ap; + + if (req && strcmp(req, name)) + return; + + va_start(ap, fmt); + val = talloc_vasprintf(ctx, fmt, ap); + va_end(ap); + + if (!strcmp(val, "(null)")) { + talloc_free(val); + if (!use_prefix) + return; + val = talloc_strdup(ctx, ""); + } + + sep = use_prefix ? ": " : ""; + + printf("%s%s%s\n", use_prefix ? name : "", sep, val); + + talloc_free(val); +} + +static void print_config(void *ctx, struct config *config, const char *var) +{ + unsigned int i; + + for (i = 0; i < config->n_autoboot_opts; i++) { + if (config->autoboot_opts[i].boot_type == BOOT_DEVICE_TYPE) + print_one_config(ctx, var, "bootdev", "%s", + device_type_name(config->autoboot_opts[i].type)); + else + print_one_config(ctx, var, "bootdev", "%s", + config->autoboot_opts[i].uuid); + } + print_one_config(ctx, var, "autoboot", "%s", + config->autoboot_enabled ? "enabled" : "disabled"); + print_one_config(ctx, var, "timeout", "%d", + config->autoboot_timeout_sec); + print_one_config(ctx, var, "safe-mode", "%s", + config->safe_mode ? "enabled" : "disabled"); + print_one_config(ctx, var, "debug", "%s", + config->debug ? "enabled" : "disabled"); + print_one_config(ctx, var, "dm-snapshots", "%s", + config->disable_snapshots ? "disabled" : "enabled"); +} + +int main(int argc, char **argv) +{ + struct waitset *waitset; + struct config *config; + void *ctx; + bool list; + + list = false; + + for (;;) { + int opt = getopt_long(argc, argv, "l", options, NULL); + if (opt == -1) + break; + + switch (opt) { + case 'l': + list = true; + break; + default: + usage(argv[0]); + return EXIT_FAILURE; + } + } + + ctx = talloc_new(NULL); + + waitset = waitset_create(ctx); + + process_init(ctx, waitset, false); + + platform_init(); + + pb_log_init(stderr); + + config = config_get(); + + if (list) { + print_config(ctx, config, NULL); + } else { + int i; + + for (i = optind; i < argc; i++) + print_config(ctx, config, argv[i]); + } + + talloc_free(ctx); + + return EXIT_SUCCESS; +} diff --git a/pool/shard000/C/0010122_ert_util_filename.c b/pool/shard000/C/0010122_ert_util_filename.c new file mode 100644 index 0000000000000000000000000000000000000000..4bd358ecd9553f50ca3bdf45988148ac42aaefda --- /dev/null +++ b/pool/shard000/C/0010122_ert_util_filename.c @@ -0,0 +1,73 @@ +/* + Copyright (C) 2012 Statoil ASA, Norway. + + The file 'ert_util_PATH_test.c' is part of ERT - Ensemble based Reservoir Tool. + + ERT 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. + + ERT 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 at + for more details. +*/ + +#include +#include +#include +#include + +#include +#include + + +void test_dirname() { + const char * src_file1 = "/some/very/long/path/file.txt"; + const char * src_file2 = "relative/path/file.txt"; + const char * src_file3 = "file.txt"; + + char * path1 = util_split_alloc_dirname( src_file1 ); + char * path2 = util_split_alloc_dirname( src_file2 ); + char * path3 = util_split_alloc_dirname( src_file3 ); + + test_assert_string_equal( "/some/very/long/path" , path1); + test_assert_string_equal( "relative/path" , path2); + test_assert_NULL( path3 ); + + free( path1 ); + free( path2 ); +} + + + +void test_filename() { + const char * src_file1 = "/some/very/long/path/file1.txt"; + const char * src_file2 = "relative/path/file2"; + const char * src_file3 = "/tmp"; + + char * file1 = util_split_alloc_filename( src_file1 ); + char * file2 = util_split_alloc_filename( src_file2 ); + char * file3 = util_split_alloc_filename( src_file3 ); + + test_assert_string_equal( "file1.txt" , file1); + test_assert_string_equal( "file2" , file2); + test_assert_NULL( file3 ); + free( file1 ); + free( file2 ); + +} + + + + +int main(int argc , char ** argv) { + + test_dirname(); + test_filename(); + exit(0); + +} diff --git a/pool/shard000/C/0010130_spd.c b/pool/shard000/C/0010130_spd.c new file mode 100644 index 0000000000000000000000000000000000000000..f8b0bf2ea926e22c58b251c193372eb54e2ce867 --- /dev/null +++ b/pool/shard000/C/0010130_spd.c @@ -0,0 +1,134 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2014 Google Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; 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. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static void mainboard_print_spd_info(uint8_t spd[]) +{ + const int spd_banks[8] = { 8, 16, 32, 64, -1, -1, -1, -1 }; + const int spd_capmb[8] = { 1, 2, 4, 8, 16, 32, 64, 0 }; + const int spd_rows[8] = { 12, 13, 14, 15, 16, -1, -1, -1 }; + const int spd_cols[8] = { 9, 10, 11, 12, -1, -1, -1, -1 }; + const int spd_ranks[8] = { 1, 2, 3, 4, -1, -1, -1, -1 }; + const int spd_devw[8] = { 4, 8, 16, 32, -1, -1, -1, -1 }; + const int spd_busw[8] = { 8, 16, 32, 64, -1, -1, -1, -1 }; + char spd_name[SPD_PART_LEN+1] = { 0 }; + + int banks = spd_banks[(spd[SPD_DENSITY_BANKS] >> 4) & 7]; + int capmb = spd_capmb[spd[SPD_DENSITY_BANKS] & 7] * 256; + int rows = spd_rows[(spd[SPD_ADDRESSING] >> 3) & 7]; + int cols = spd_cols[spd[SPD_ADDRESSING] & 7]; + int ranks = spd_ranks[(spd[SPD_ORGANIZATION] >> 3) & 7]; + int devw = spd_devw[spd[SPD_ORGANIZATION] & 7]; + int busw = spd_busw[spd[SPD_BUS_DEV_WIDTH] & 7]; + + /* Module type */ + printk(BIOS_INFO, "SPD: module type is "); + switch (spd[SPD_DRAM_TYPE]) { + case SPD_DRAM_DDR3: + printk(BIOS_INFO, "DDR3\n"); + break; + case SPD_DRAM_LPDDR3: + printk(BIOS_INFO, "LPDDR3\n"); + break; + default: + printk(BIOS_INFO, "Unknown (%02x)\n", spd[SPD_DRAM_TYPE]); + break; + } + + /* Module Part Number */ + memcpy(spd_name, &spd[SPD_PART_OFF], SPD_PART_LEN); + spd_name[SPD_PART_LEN] = 0; + printk(BIOS_INFO, "SPD: module part is %s\n", spd_name); + + printk(BIOS_INFO, "SPD: banks %d, ranks %d, rows %d, columns %d, " + "density %d Mb\n", banks, ranks, rows, cols, capmb); + printk(BIOS_INFO, "SPD: device width %d bits, bus width %d bits\n", + devw, busw); + + if (capmb > 0 && busw > 0 && devw > 0 && ranks > 0) { + /* SIZE = DENSITY / 8 * BUS_WIDTH / SDRAM_WIDTH * RANKS */ + printk(BIOS_INFO, "SPD: module size is %u MB (per channel)\n", + capmb / 8 * busw / devw * ranks); + } +} + +/* Copy SPD data for on-board memory */ +void mainboard_fill_spd_data(struct pei_data *pei_data) +{ + int spd_bits[4] = { + SPD_GPIO_BIT0, + SPD_GPIO_BIT1, + SPD_GPIO_BIT2, + SPD_GPIO_BIT3 + }; + int spd_gpio[4]; + int spd_index; + int spd_file_len; + struct cbfs_file *spd_file; + + spd_gpio[0] = get_gpio(spd_bits[0]); + spd_gpio[1] = get_gpio(spd_bits[1]); + spd_gpio[2] = get_gpio(spd_bits[2]); + spd_gpio[3] = get_gpio(spd_bits[3]); + + spd_index = (spd_gpio[3] << 3) | (spd_gpio[2] << 2) | + (spd_gpio[1] << 1) | spd_gpio[0]; + + printk(BIOS_DEBUG, "SPD: index %d (GPIO%d=%d GPIO%d=%d " + "GPIO%d=%d GPIO%d=%d)\n", spd_index, + spd_bits[3], spd_gpio[3], spd_bits[2], spd_gpio[2], + spd_bits[1], spd_gpio[1], spd_bits[0], spd_gpio[0]); + + spd_file = cbfs_get_file(CBFS_DEFAULT_MEDIA, "spd.bin"); + if (!spd_file) + die("SPD data not found."); + spd_file_len = ntohl(spd_file->len); + + if (spd_file_len < ((spd_index + 1) * SPD_LEN)) { + printk(BIOS_ERR, "SPD index override to 0 - old hardware?\n"); + spd_index = 0; + } + + if (spd_file_len < SPD_LEN) + die("Missing SPD data."); + + /* Assume same memory in both channels */ + spd_index *= SPD_LEN; + memcpy(pei_data->spd_data[0][0], + ((char*)CBFS_SUBHEADER(spd_file)) + spd_index, SPD_LEN); + memcpy(pei_data->spd_data[1][0], + ((char*)CBFS_SUBHEADER(spd_file)) + spd_index, SPD_LEN); + + /* Make sure a valid SPD was found */ + if (pei_data->spd_data[0][0][0] == 0) + die("Invalid SPD data."); + + mainboard_print_spd_info(pei_data->spd_data[0][0]); +} diff --git a/pool/shard000/C/0010141_ahci_platform.c b/pool/shard000/C/0010141_ahci_platform.c new file mode 100644 index 0000000000000000000000000000000000000000..d809bb7bd5361dfa2da5bf2067d80e2fc3989847 --- /dev/null +++ b/pool/shard000/C/0010141_ahci_platform.c @@ -0,0 +1,100 @@ +/* + * AHCI SATA platform driver + * + * Copyright 2004-2005 Red Hat, Inc. + * Jeff Garzik + * Copyright 2010 MontaVista Software, LLC. + * Anton Vorontsov + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2, or (at your option) + * any later version. + */ + +#include +#include +#include +#include +#include +#include +#include +#include "ahci.h" + +static const struct ata_port_info ahci_port_info = { + .flags = AHCI_FLAG_COMMON, + .pio_mask = ATA_PIO4, + .udma_mask = ATA_UDMA6, + .port_ops = &ahci_platform_ops, +}; + +static int ahci_probe(struct platform_device *pdev) +{ + struct device *dev = &pdev->dev; + struct ahci_platform_data *pdata = dev_get_platdata(dev); + struct ahci_host_priv *hpriv; + int rc; + + hpriv = ahci_platform_get_resources(pdev); + if (IS_ERR(hpriv)) + return PTR_ERR(hpriv); + + rc = ahci_platform_enable_resources(hpriv); + if (rc) + return rc; + + /* + * Some platforms might need to prepare for mmio region access, + * which could be done in the following init call. So, the mmio + * region shouldn't be accessed before init (if provided) has + * returned successfully. + */ + if (pdata && pdata->init) { + rc = pdata->init(dev, hpriv->mmio); + if (rc) + goto disable_resources; + } + + rc = ahci_platform_init_host(pdev, hpriv, &ahci_port_info, 0, 0); + if (rc) + goto pdata_exit; + + return 0; +pdata_exit: + if (pdata && pdata->exit) + pdata->exit(dev); +disable_resources: + ahci_platform_disable_resources(hpriv); + return rc; +} + +static SIMPLE_DEV_PM_OPS(ahci_pm_ops, ahci_platform_suspend, + ahci_platform_resume); + +static const struct of_device_id ahci_of_match[] = { + { .compatible = "generic-ahci", }, + /* Keep the following compatibles for device tree compatibility */ + { .compatible = "snps,spear-ahci", }, + { .compatible = "snps,exynos5440-ahci", }, + { .compatible = "ibm,476gtr-ahci", }, + { .compatible = "snps,dwc-ahci", }, + {}, +}; +MODULE_DEVICE_TABLE(of, ahci_of_match); + +static struct platform_driver ahci_driver = { + .probe = ahci_probe, + .remove = ata_platform_remove_one, + .driver = { + .name = "ahci", + .owner = THIS_MODULE, + .of_match_table = ahci_of_match, + .pm = &ahci_pm_ops, + }, +}; +module_platform_driver(ahci_driver); + +MODULE_DESCRIPTION("AHCI SATA platform driver"); +MODULE_AUTHOR("Anton Vorontsov "); +MODULE_LICENSE("GPL"); +MODULE_ALIAS("platform:ahci"); diff --git a/pool/shard000/C/0010144_nil_test_sequence_004.c b/pool/shard000/C/0010144_nil_test_sequence_004.c new file mode 100644 index 0000000000000000000000000000000000000000..cfc8efe61d4e1dbd32ec85556dd602134c58a73a --- /dev/null +++ b/pool/shard000/C/0010144_nil_test_sequence_004.c @@ -0,0 +1,308 @@ +/* + ChibiOS - Copyright (C) 2006..2018 Giovanni Di Sirio + + 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 "hal.h" +#include "nil_test_root.h" + +/** + * @file nil_test_sequence_004.c + * @brief Test Sequence 004 code. + * + * @page nil_test_sequence_004 [4] Semaphores + * + * File: @ref nil_test_sequence_004.c + * + *

Description

+ * This sequence tests the ChibiOS/NIL functionalities related to + * counter semaphores. + * + *

Conditions

+ * This sequence is only executed if the following preprocessor condition + * evaluates to true: + * - CH_CFG_USE_SEMAPHORES + * . + * + *

Test Cases

+ * - @subpage nil_test_004_001 + * - @subpage nil_test_004_002 + * - @subpage nil_test_004_003 + * . + */ + +#if (CH_CFG_USE_SEMAPHORES) || defined(__DOXYGEN__) + +/**************************************************************************** + * Shared code. + ****************************************************************************/ + +#include "ch.h" + +static thread_t *tp1; +static bool terminate; +static semaphore_t sem1, sem2; + +/* + * Signaler thread. + */ +static THD_FUNCTION(signaler, arg) { + + (void)arg; + + /* Initializing global resources.*/ + terminate = false; + chSemObjectInit(&sem1, 0); + chSemObjectInit(&sem2, 0); + + while (!terminate) { + chSysLock(); + if (chSemGetCounterI(&sem1) < 0) + chSemSignalI(&sem1); + chSemResetI(&sem2, 0); + chSchRescheduleS(); + chSysUnlock(); + + chThdSleepMilliseconds(250); + } +} + +/**************************************************************************** + * Test cases. + ****************************************************************************/ + +/** + * @page nil_test_004_001 [4.1] Semaphore primitives, no state change + * + *

Description

+ * Wait, Signal and Reset primitives are tested. The testing thread + * does not trigger a state change. + * + *

Test Steps

+ * - [4.1.1] The function chSemWait() is invoked, after return the + * counter and the returned message are tested. + * - [4.1.2] The function chSemSignal() is invoked, after return the + * counter is tested. + * - [4.1.3] The function chSemReset() is invoked, after return the + * counter is tested. + * . + */ + +static void nil_test_004_001_setup(void) { + chSemObjectInit(&sem1, 1); +} + +static void nil_test_004_001_teardown(void) { + chSemReset(&sem1, 0); +} + +static void nil_test_004_001_execute(void) { + + /* [4.1.1] The function chSemWait() is invoked, after return the + counter and the returned message are tested.*/ + test_set_step(1); + { + msg_t msg; + + msg = chSemWait(&sem1); + test_assert_lock(chSemGetCounterI(&sem1) == 0, "wrong counter value"); + test_assert(MSG_OK == msg, "wrong returned message"); + } + test_end_step(1); + + /* [4.1.2] The function chSemSignal() is invoked, after return the + counter is tested.*/ + test_set_step(2); + { + chSemSignal(&sem1); + test_assert_lock(chSemGetCounterI(&sem1) == 1, "wrong counter value"); + } + test_end_step(2); + + /* [4.1.3] The function chSemReset() is invoked, after return the + counter is tested.*/ + test_set_step(3); + { + chSemReset(&sem1, 2); + test_assert_lock(chSemGetCounterI(&sem1) == 2, "wrong counter value"); + } + test_end_step(3); +} + +static const testcase_t nil_test_004_001 = { + "Semaphore primitives, no state change", + nil_test_004_001_setup, + nil_test_004_001_teardown, + nil_test_004_001_execute +}; + +/** + * @page nil_test_004_002 [4.2] Semaphore primitives, with state change + * + *

Description

+ * Wait, Signal and Reset primitives are tested. The testing thread + * triggers a state change. + * + *

Test Steps

+ * - [4.2.1] The function chSemWait() is invoked, after return the + * counter and the returned message are tested. The semaphore is + * signaled by another thread. + * - [4.2.2] The function chSemWait() is invoked, after return the + * counter and the returned message are tested. The semaphore is + * reset by another thread. + * . + */ + +static void nil_test_004_002_setup(void) { + thread_descriptor_t td = { + .name = "signaler", + .wbase = wa_common, + .wend = THD_WORKING_AREA_END(wa_common), + .prio = chThdGetPriorityX() - 1, + .funcp = signaler, + .arg = NULL + }; + tp1 = chThdCreate(&td); +} + +static void nil_test_004_002_teardown(void) { + terminate = true; + chThdWait(tp1); +} + +static void nil_test_004_002_execute(void) { + + /* [4.2.1] The function chSemWait() is invoked, after return the + counter and the returned message are tested. The semaphore is + signaled by another thread.*/ + test_set_step(1); + { + msg_t msg; + + msg = chSemWait(&sem1); + test_assert_lock(chSemGetCounterI(&sem1) == 0, "wrong counter value"); + test_assert(MSG_OK == msg, "wrong returned message"); + } + test_end_step(1); + + /* [4.2.2] The function chSemWait() is invoked, after return the + counter and the returned message are tested. The semaphore is + reset by another thread.*/ + test_set_step(2); + { + msg_t msg; + + msg = chSemWait(&sem2); + test_assert_lock(chSemGetCounterI(&sem2) == 0,"wrong counter value"); + test_assert(MSG_RESET == msg, "wrong returned message"); + } + test_end_step(2); +} + +static const testcase_t nil_test_004_002 = { + "Semaphore primitives, with state change", + nil_test_004_002_setup, + nil_test_004_002_teardown, + nil_test_004_002_execute +}; + +/** + * @page nil_test_004_003 [4.3] Semaphores timeout + * + *

Description

+ * Timeout on semaphores is tested. + * + *

Test Steps

+ * - [4.3.1] The function chSemWaitTimeout() is invoked a first time, + * after return the system time, the counter and the returned message + * are tested. + * - [4.3.2] The function chSemWaitTimeout() is invoked again, after + * return the system time, the counter and the returned message are + * tested. + * . + */ + +static void nil_test_004_003_setup(void) { + chSemObjectInit(&sem1, 0); +} + +static void nil_test_004_003_teardown(void) { + chSemReset(&sem1, 0); +} + +static void nil_test_004_003_execute(void) { + systime_t time; + msg_t msg; + + /* [4.3.1] The function chSemWaitTimeout() is invoked a first time, + after return the system time, the counter and the returned message + are tested.*/ + test_set_step(1); + { + time = chVTGetSystemTimeX(); + msg = chSemWaitTimeout(&sem1, TIME_MS2I(1000)); + test_assert_time_window(chTimeAddX(time, TIME_MS2I(1000)), + chTimeAddX(time, TIME_MS2I(1000) + 1), + "out of time window"); + test_assert_lock(chSemGetCounterI(&sem1) == 0, "wrong counter value"); + test_assert(MSG_TIMEOUT == msg, "wrong timeout message"); + } + test_end_step(1); + + /* [4.3.2] The function chSemWaitTimeout() is invoked again, after + return the system time, the counter and the returned message are + tested.*/ + test_set_step(2); + { + time = chVTGetSystemTimeX(); + msg = chSemWaitTimeout(&sem1, TIME_MS2I(1000)); + test_assert_time_window(chTimeAddX(time, TIME_MS2I(1000)), + chTimeAddX(time, TIME_MS2I(1000) + 1), + "out of time window"); + test_assert_lock(chSemGetCounterI(&sem1) == 0, "wrong counter value"); + test_assert(MSG_TIMEOUT == msg, "wrong timeout message"); + } + test_end_step(2); +} + +static const testcase_t nil_test_004_003 = { + "Semaphores timeout", + nil_test_004_003_setup, + nil_test_004_003_teardown, + nil_test_004_003_execute +}; + +/**************************************************************************** + * Exported data. + ****************************************************************************/ + +/** + * @brief Array of test cases. + */ +const testcase_t * const nil_test_sequence_004_array[] = { + &nil_test_004_001, + &nil_test_004_002, + &nil_test_004_003, + NULL +}; + +/** + * @brief Semaphores. + */ +const testsequence_t nil_test_sequence_004 = { + "Semaphores", + nil_test_sequence_004_array +}; + +#endif /* CH_CFG_USE_SEMAPHORES */ diff --git a/pool/shard000/C/0010147_GLXSurfaceData.c b/pool/shard000/C/0010147_GLXSurfaceData.c new file mode 100644 index 0000000000000000000000000000000000000000..c48b38fa1f3e7f8b808c7b6253b968170bf20c9d --- /dev/null +++ b/pool/shard000/C/0010147_GLXSurfaceData.c @@ -0,0 +1,345 @@ +/* + * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +#include + +#include "sun_java2d_opengl_GLXSurfaceData.h" + +#include "OGLRenderQueue.h" +#include "GLXGraphicsConfig.h" +#include "GLXSurfaceData.h" +#include "awt_Component.h" +#include "awt_GraphicsEnv.h" + +/** + * The methods in this file implement the native windowing system specific + * layer (GLX) for the OpenGL-based Java 2D pipeline. + */ + +#ifndef HEADLESS + +extern LockFunc OGLSD_Lock; +extern GetRasInfoFunc OGLSD_GetRasInfo; +extern UnlockFunc OGLSD_Unlock; +extern DisposeFunc OGLSD_Dispose; + +extern void + OGLSD_SetNativeDimensions(JNIEnv *env, OGLSDOps *oglsdo, jint w, jint h); + +jboolean surfaceCreationFailed = JNI_FALSE; + +#endif /* !HEADLESS */ + +JNIEXPORT void JNICALL +Java_sun_java2d_opengl_GLXSurfaceData_initOps(JNIEnv *env, jobject glxsd, + jobject gc, + jobject peer, jlong aData) +{ +#ifndef HEADLESS + gc = (*env)->NewGlobalRef(env, gc); + if (gc == NULL) { + JNU_ThrowOutOfMemoryError(env, "Initialization of SurfaceData failed."); + return; + } + + OGLSDOps *oglsdo = (OGLSDOps *)SurfaceData_InitOps(env, glxsd, + sizeof(OGLSDOps)); + if (oglsdo == NULL) { + (*env)->DeleteGlobalRef(env, gc); + JNU_ThrowOutOfMemoryError(env, "Initialization of SurfaceData failed."); + return; + } + // later the graphicsConfig will be used for deallocation of oglsdo + oglsdo->graphicsConfig = gc; + + GLXSDOps *glxsdo = (GLXSDOps *)malloc(sizeof(GLXSDOps)); + + if (glxsdo == NULL) { + JNU_ThrowOutOfMemoryError(env, "creating native GLX ops"); + return; + } + + J2dTraceLn(J2D_TRACE_INFO, "GLXSurfaceData_initOps"); + + oglsdo->privOps = glxsdo; + + oglsdo->sdOps.Lock = OGLSD_Lock; + oglsdo->sdOps.GetRasInfo = OGLSD_GetRasInfo; + oglsdo->sdOps.Unlock = OGLSD_Unlock; + oglsdo->sdOps.Dispose = OGLSD_Dispose; + + oglsdo->drawableType = OGLSD_UNDEFINED; + oglsdo->activeBuffer = GL_FRONT; + oglsdo->needsInit = JNI_TRUE; + + if (peer != NULL) { + glxsdo->window = JNU_CallMethodByName(env, NULL, peer, + "getContentWindow", "()J").j; + } else { + glxsdo->window = 0; + } + glxsdo->configData = (AwtGraphicsConfigDataPtr)jlong_to_ptr(aData); + if (glxsdo->configData == NULL) { + free(glxsdo); + JNU_ThrowNullPointerException(env, + "Native GraphicsConfig data block missing"); + return; + } + + if (glxsdo->configData->glxInfo == NULL) { + free(glxsdo); + JNU_ThrowNullPointerException(env, "GLXGraphicsConfigInfo missing"); + return; + } +#endif /* HEADLESS */ +} + +#ifndef HEADLESS + +/** + * This function disposes of any native windowing system resources associated + * with this surface. + */ +void +OGLSD_DestroyOGLSurface(JNIEnv *env, OGLSDOps *oglsdo) +{ + J2dTraceLn(J2D_TRACE_INFO, "OGLSD_DestroyOGLSurface"); + // X Window is free'd later by AWT code... +} + +/** + * Makes the given context current to its associated "scratch" surface. If + * the operation is successful, this method will return JNI_TRUE; otherwise, + * returns JNI_FALSE. + */ +static jboolean +GLXSD_MakeCurrentToScratch(JNIEnv *env, OGLContext *oglc) +{ + GLXCtxInfo *ctxInfo; + + J2dTraceLn(J2D_TRACE_INFO, "GLXSD_MakeCurrentToScratch"); + + if (oglc == NULL) { + J2dRlsTraceLn(J2D_TRACE_ERROR, + "GLXSD_MakeCurrentToScratch: context is null"); + return JNI_FALSE; + } + + ctxInfo = (GLXCtxInfo *)oglc->ctxInfo; + if (!j2d_glXMakeContextCurrent(awt_display, + ctxInfo->scratchSurface, + ctxInfo->scratchSurface, + ctxInfo->context)) + { + J2dRlsTraceLn(J2D_TRACE_ERROR, + "GLXSD_MakeCurrentToScratch: could not make current"); + return JNI_FALSE; + } + + return JNI_TRUE; +} + +/** + * Makes the given GraphicsConfig's context current to its associated + * "scratch" surface. If there is a problem making the context current, + * this method will return NULL; otherwise, returns a pointer to the + * OGLContext that is associated with the given GraphicsConfig. + */ +OGLContext * +OGLSD_SetScratchSurface(JNIEnv *env, jlong pConfigInfo) +{ + GLXGraphicsConfigInfo *glxInfo = + (GLXGraphicsConfigInfo *)jlong_to_ptr(pConfigInfo); + OGLContext *oglc; + + J2dTraceLn(J2D_TRACE_INFO, "OGLSD_SetScratchContext"); + + if (glxInfo == NULL) { + J2dRlsTraceLn(J2D_TRACE_ERROR, + "OGLSD_SetScratchContext: glx config info is null"); + return NULL; + } + + oglc = glxInfo->context; + if (!GLXSD_MakeCurrentToScratch(env, oglc)) { + return NULL; + } + + if (OGLC_IS_CAP_PRESENT(oglc, CAPS_EXT_FBOBJECT)) { + // the GL_EXT_framebuffer_object extension is present, so this call + // will ensure that we are bound to the scratch pbuffer (and not + // some other framebuffer object) + j2d_glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); + } + + return oglc; +} + +/** + * Makes a context current to the given source and destination + * surfaces. If there is a problem making the context current, this method + * will return NULL; otherwise, returns a pointer to the OGLContext that is + * associated with the destination surface. + */ +OGLContext * +OGLSD_MakeOGLContextCurrent(JNIEnv *env, OGLSDOps *srcOps, OGLSDOps *dstOps) +{ + GLXSDOps *dstGLXOps = (GLXSDOps *)dstOps->privOps; + OGLContext *oglc; + + J2dTraceLn(J2D_TRACE_INFO, "OGLSD_MakeOGLContextCurrent"); + + oglc = dstGLXOps->configData->glxInfo->context; + if (oglc == NULL) { + J2dRlsTraceLn(J2D_TRACE_ERROR, + "OGLSD_MakeOGLContextCurrent: context is null"); + return NULL; + } + + if (dstOps->drawableType == OGLSD_FBOBJECT) { + OGLContext *currentContext = OGLRenderQueue_GetCurrentContext(); + + // first make sure we have a current context (if the context isn't + // already current to some drawable, we will make it current to + // its scratch surface) + if (oglc != currentContext) { + if (!GLXSD_MakeCurrentToScratch(env, oglc)) { + return NULL; + } + } + + // now bind to the fbobject associated with the destination surface; + // this means that all rendering will go into the fbobject destination + // (note that we unbind the currently bound texture first; this is + // recommended procedure when binding an fbobject) + j2d_glBindTexture(dstOps->textureTarget, 0); + j2d_glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, dstOps->fbobjectID); + } else { + GLXSDOps *srcGLXOps = (GLXSDOps *)srcOps->privOps; + GLXCtxInfo *ctxinfo = (GLXCtxInfo *)oglc->ctxInfo; + + // make the context current + if (!j2d_glXMakeContextCurrent(awt_display, + dstGLXOps->drawable, + srcGLXOps->drawable, + ctxinfo->context)) + { + J2dRlsTraceLn(J2D_TRACE_ERROR, + "OGLSD_MakeOGLContextCurrent: could not make current"); + return NULL; + } + + if (OGLC_IS_CAP_PRESENT(oglc, CAPS_EXT_FBOBJECT)) { + // the GL_EXT_framebuffer_object extension is present, so we + // must bind to the default (windowing system provided) + // framebuffer + j2d_glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); + } + } + + return oglc; +} + +/** + * This function initializes a native window surface and caches the window + * bounds in the given OGLSDOps. Returns JNI_TRUE if the operation was + * successful; JNI_FALSE otherwise. + */ +jboolean +OGLSD_InitOGLWindow(JNIEnv *env, OGLSDOps *oglsdo) +{ + GLXSDOps *glxsdo; + Window window; + XWindowAttributes attr; + + J2dTraceLn(J2D_TRACE_INFO, "OGLSD_InitOGLWindow"); + + if (oglsdo == NULL) { + J2dRlsTraceLn(J2D_TRACE_ERROR, + "OGLSD_InitOGLWindow: ops are null"); + return JNI_FALSE; + } + + glxsdo = (GLXSDOps *)oglsdo->privOps; + if (glxsdo == NULL) { + J2dRlsTraceLn(J2D_TRACE_ERROR, + "OGLSD_InitOGLWindow: glx ops are null"); + return JNI_FALSE; + } + + window = glxsdo->window; + if (window == 0) { + J2dRlsTraceLn(J2D_TRACE_ERROR, + "OGLSD_InitOGLWindow: window is invalid"); + return JNI_FALSE; + } + + XGetWindowAttributes(awt_display, window, &attr); + oglsdo->width = attr.width; + oglsdo->height = attr.height; + + oglsdo->drawableType = OGLSD_WINDOW; + oglsdo->isOpaque = JNI_TRUE; + oglsdo->xOffset = 0; + oglsdo->yOffset = 0; + glxsdo->drawable = window; + glxsdo->xdrawable = window; + + J2dTraceLn2(J2D_TRACE_VERBOSE, " created window: w=%d h=%d", + oglsdo->width, oglsdo->height); + + return JNI_TRUE; +} + +static int +GLXSD_BadAllocXErrHandler(Display *display, XErrorEvent *xerr) +{ + if (xerr->error_code == BadAlloc) { + surfaceCreationFailed = JNI_TRUE; + } + return 0; +} + +void +OGLSD_SwapBuffers(JNIEnv *env, jlong window) +{ + J2dTraceLn(J2D_TRACE_INFO, "OGLSD_SwapBuffers"); + + if (window == 0L) { + J2dRlsTraceLn(J2D_TRACE_ERROR, + "OGLSD_SwapBuffers: window is null"); + return; + } + + j2d_glXSwapBuffers(awt_display, (Window)window); +} + +// needed by Mac OS X port, no-op on other platforms +void +OGLSD_Flush(JNIEnv *env) +{ +} + +#endif /* !HEADLESS */ diff --git a/pool/shard000/C/0010165_vreg.c b/pool/shard000/C/0010165_vreg.c new file mode 100644 index 0000000000000000000000000000000000000000..aa6acab8ee955ef6db47973746401a18b41af3ef --- /dev/null +++ b/pool/shard000/C/0010165_vreg.c @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2016, 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: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the 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 CORPORATION OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include "vreg.h" + +typedef enum { AON_VR = 0, PLAT3P3_VR, PLAT1P8_VR, HOST_VR, VREG_NUM } vreg_t; + +QM_RW uint32_t *vreg[VREG_NUM] = { + &QM_SCSS_PMU->aon_vr, &QM_SCSS_PMU->plat3p3_vr, &QM_SCSS_PMU->plat1p8_vr, + &QM_SCSS_PMU->host_vr}; + +static int vreg_set_mode(const vreg_t id, const vreg_mode_t mode) +{ + QM_CHECK(mode < VREG_MODE_NUM, -EINVAL); + uint32_t vr; + + vr = *vreg[id]; + + switch (mode) { + case VREG_MODE_SWITCHING: + vr |= QM_SCSS_VR_EN; + vr &= ~QM_SCSS_VR_VREG_SEL; + break; + case VREG_MODE_LINEAR: + vr |= QM_SCSS_VR_EN; + vr |= QM_SCSS_VR_VREG_SEL; + break; + case VREG_MODE_SHUTDOWN: + vr &= ~QM_SCSS_VR_EN; + break; + default: + break; + } + + *vreg[id] = vr; + + while ((mode == VREG_MODE_SWITCHING) && + (*vreg[id] & QM_SCSS_VR_ROK) == 0) { + } + + return 0; +} + +int vreg_aon_set_mode(const vreg_mode_t mode) +{ + QM_CHECK(mode < VREG_MODE_NUM, -EINVAL); + QM_CHECK(mode != VREG_MODE_SWITCHING, -EINVAL); + + return vreg_set_mode(AON_VR, mode); +} + +int vreg_plat3p3_set_mode(const vreg_mode_t mode) +{ + QM_CHECK(mode < VREG_MODE_NUM, -EINVAL); + return vreg_set_mode(PLAT3P3_VR, mode); +} + +int vreg_plat1p8_set_mode(const vreg_mode_t mode) +{ + QM_CHECK(mode < VREG_MODE_NUM, -EINVAL); + return vreg_set_mode(PLAT1P8_VR, mode); +} + +int vreg_host_set_mode(const vreg_mode_t mode) +{ + QM_CHECK(mode < VREG_MODE_NUM, -EINVAL); + return vreg_set_mode(HOST_VR, mode); +} diff --git a/pool/shard000/C/0010166_mprFile.c b/pool/shard000/C/0010166_mprFile.c new file mode 100644 index 0000000000000000000000000000000000000000..f647f1ed5679a6d59fc4e0566a768a9f224ee157 --- /dev/null +++ b/pool/shard000/C/0010166_mprFile.c @@ -0,0 +1,86 @@ +/** + * @file mprFile.c + * @brief File services for Unix + * @overview + * @remarks + * See mprGenFile.c for other file services. + */ + +/******************************************************************************/ +/* + * @copy default + * + * Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved. + * + * This software is distributed under commercial and open source licenses. + * You may use the GPL open source license described below or you may acquire + * a commercial license from Mbedthis Software. You agree to be fully bound + * by the terms of either license. Consult the LICENSE.TXT distributed with + * this software for full details. + * + * This software is open source; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. See the GNU General Public License for more + * details at: http://www.mbedthis.com/downloads/gplLicense.html + * + * This program is distributed WITHOUT ANY WARRANTY; without even the + * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * + * This GPL license does NOT permit incorporating this software into + * proprietary programs. If you are unable to comply with the GPL, you must + * acquire a commercial license to use this software. Commercial licenses + * for this software and support services are available from Mbedthis + * Software at http://www.mbedthis.com + * + * @end + */ + +/********************************** Includes **********************************/ + +#include "mpr.h" + +/************************************ Code ************************************/ + +int mprGetFileInfo(MprCtx ctx, const char *path, MprFileInfo *info) +{ + struct stat s; + + mprAssert(path); + mprAssert(info); + + if (stat(path, &s) < 0) { + return -1; + } + + info->size = s.st_size; + info->ctime = s.st_ctime; + info->mtime = s.st_mtime; + info->inode = s.st_ino; + info->isDir = (s.st_mode & S_IFDIR) != 0; + info->isReg = (s.st_mode & S_IFREG) != 0; + + if (strcmp(path, "/dev/null") == 0) { + info->isReg = 0; + } + + return 0; +} + +/******************************************************************************/ + +int mprMakeDir(MprCtx ctx, const char *path, int perms) +{ + return mkdir(path, perms); +} + +/******************************************************************************/ +/* + * Local variables: + * tab-width: 4 + * c-basic-offset: 4 + * End: + * vim:tw=78 + * vim600: sw=4 ts=4 fdm=marker + * vim<600: sw=4 ts=4 + */ diff --git a/pool/shard000/C/0010170_vui_gc_ptr.c b/pool/shard000/C/0010170_vui_gc_ptr.c new file mode 100644 index 0000000000000000000000000000000000000000..095ee1d0e3278f557c6116461269d3776de87cce --- /dev/null +++ b/pool/shard000/C/0010170_vui_gc_ptr.c @@ -0,0 +1,116 @@ +#include "vui_debug.h" + +#include "vui_mem.h" + +#include "vui_stack_refcount.h" + +#include "vui_gc_ptr.h" + +static void vui_gc_ptr_kill(vui_gc_ptr* gcptr) +{ + vui_free(gcptr); +} + +void vui_gc_ptr_gc_dtor(void* obj, vui_gc_dtor_mode mode) +{ + vui_gc_ptr* gcptr = (vui_gc_ptr*)obj; + + if (gcptr->dtor != NULL) + { + gcptr->dtor(gcptr->ptr, mode); + } + + if (mode == VUI_GC_DTOR_MARK) + { + } + else if (mode == VUI_GC_DTOR_SWEEP) + { + vui_gc_ptr_kill(gcptr); + } + else if (mode == VUI_GC_DTOR_DESCRIBE) + { +#if defined(VUI_DEBUG) && defined(VUI_DEBUG_GC) + //vui_debugf("vui_gc: ptr %p\n", st); +#endif + } +} + +vui_gc_ptr* vui_gc_ptr_new(vui_gc_dtor dtor, void* ptr) +{ + vui_gc_ptr* gcptr = vui_new(vui_gc_ptr); + + gcptr->dtor = dtor; + gcptr->ptr = ptr; + + vui_gc_register(gcptr, vui_gc_ptr_gc_dtor); + + return gcptr; +} + + + +void vui_gc_ptr_stack_gc_dtor(void* obj, vui_gc_dtor_mode mode) +{ + vui_stack* stk = (vui_stack*)obj; + + if (mode == VUI_GC_DTOR_MARK) + { + if (stk != NULL) + { + if (stk->def) + { + vui_gc_mark_header(stk->def); + } + + for (size_t i = 0; i < stk->n; i++) + { + vui_gc_mark_header(stk->s[i]); + } + } + } + else if (mode == VUI_GC_DTOR_SWEEP) + { + vui_stack_kill(stk); + } + else if (mode == VUI_GC_DTOR_DESCRIBE) + { +#if defined(VUI_DEBUG) && defined(VUI_DEBUG_GC) + vui_debugf("vui_gc: *stack %p\n", stk); +#endif + } +} + +vui_gc_ptr* vui_gc_ptr_new_stack(vui_stack* stk) +{ + vui_stack_refcount_deconvert(stk); // make sure the stack isn't reference counted; + // decrement counts if it was + return vui_gc_ptr_new(vui_gc_ptr_stack_gc_dtor, stk); +} + + + +void vui_gc_ptr_string_gc_dtor(void* obj, vui_gc_dtor_mode mode) +{ + vui_string* str = (vui_string*)obj; + + if (mode == VUI_GC_DTOR_MARK) + { + } + else if (mode == VUI_GC_DTOR_SWEEP) + { + vui_string_kill(str); + } + else if (mode == VUI_GC_DTOR_DESCRIBE) + { +#if defined(VUI_DEBUG) && defined(VUI_DEBUG_GC) + vui_debugf("vui_gc: *string %p\n", str); +#endif + } +} + +vui_gc_ptr* vui_gc_ptr_new_string(vui_string* str) +{ + return vui_gc_ptr_new(vui_gc_ptr_string_gc_dtor, str); +} + + diff --git a/pool/shard000/C/0010174_password.c b/pool/shard000/C/0010174_password.c new file mode 100644 index 0000000000000000000000000000000000000000..13b2f62e2eb29a3e87d32e73e0a7de19bdae4632 --- /dev/null +++ b/pool/shard000/C/0010174_password.c @@ -0,0 +1,58 @@ +#include +#include +#include + +#define PASSWORD_LEN 8 + +int main() +{ + struct termios initialrsettings, newrsettings; + char password[PASSWORD_LEN + 1]; + //0 + //printf("fileno(stdin) is %d\n", fileno(stdin)); + //printf("sizeof(tcflag_t) is %ld\n", sizeof(tcflag_t)); + //printf("sizeof(cc_t) is %ld\n", sizeof(cc_t)); + //printf("sizeof(termios) is %ld\n", sizeof(newrsettings)); + tcgetattr(fileno(stdin), &initialrsettings); + + newrsettings = initialrsettings; + //printf("c_lflag is %X\n", newrsettings.c_lflag); + //printf("ECHO is %x\n", ECHO); + + // 输入密码时,关闭回显 + newrsettings.c_lflag &= ~ECHO; + + // 尝试输入超时,输入字符控制 + newrsettings.c_lflag &= ~ICANON; + newrsettings.c_lflag &= ~ISIG; + newrsettings.c_cc[VTIME] = 0; + newrsettings.c_cc[VMIN] = 1; + + + printf ("Enter password: "); + + if (tcsetattr(fileno(stdin), TCSANOW, &newrsettings) != 0) { + fprintf(stderr, "Could not set attributes\n"); + } else { + fgets(password, PASSWORD_LEN, stdin); + tcsetattr(fileno(stdin), TCSANOW, &initialrsettings); + fprintf(stdout, "\nYou entered %s\n", password); + } + + /** + printf("c_oflag is %x\n", newrsettings.c_oflag); + printf("OPOST is %x\n", OPOST); + printf("ONLRET is %x\n", ONLRET); + //exit(0); + //newrsettings.c_oflag |= ~OPOST; + newrsettings.c_oflag |= OLCUC; + tcsetattr(fileno(stdin), TCSANOW, &newrsettings); + + int index = 100; + while (index --) + printf("hello world\n"); + + tcsetattr(fileno(stdin), TCSANOW, &initialrsettings); + **/ + exit(0); +} diff --git a/pool/shard000/C/0010175_fm_main.c b/pool/shard000/C/0010175_fm_main.c new file mode 100644 index 0000000000000000000000000000000000000000..3a8c52a1a33256bca372bc0be51e0ac4f8ea9e95 --- /dev/null +++ b/pool/shard000/C/0010175_fm_main.c @@ -0,0 +1,315 @@ +/** @file fm_main.c + * + * @brief FM application + * + * Copyright (C) 2014, Marvell International Ltd. + * + * This software file (the "File") is distributed by Marvell International + * Ltd. under the terms of the GNU General Public License Version 2, June 1991 + * (the "License"). You may use, redistribute and/or modify this File in + * accordance with the terms and conditions of the License, a copy of which + * is available by writing to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or on the + * worldwide web at http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. + * + * THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND, AND THE + * IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE + * ARE EXPRESSLY DISCLAIMED. The License provides additional details about + * this warranty disclaimer. + * + */ +/************************************************************************ +Change log: + 03/15/2012: initial version +************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "fm.h" + +#define FM_PATH_MAX 256 + +#define PRINT_CMD(ogf, ocf, buf, len) \ +do { \ + printf("< HCI Command: ogf 0x%02x, ocf 0x%04x, plen %d\n", (ogf), (ocf), (len)); \ + mrvl_hex_dump(" ", 20, (buf), (len)); \ + fflush(stdout); \ +} while (0); + +#define PRINT_EVT(hdr, ptr, len) \ +do { \ + printf("> HCI Event: 0x%02x plen %d\n", (hdr)->evt, (hdr)->plen); \ + mrvl_hex_dump(" ", 20, (ptr), (len)); \ + fflush(stdout); \ +} while (0); + +#define OpCodePack(ogf, ocf) (uint16_t)((ocf & 0x03ff) | (ogf << 10)) + +static uint8_t verbose; + +static struct option main_options[] = { + {"help", 0, 0, 'h'}, + {"verbose", 0, 0, 'v'}, + {0, 0, 0, 0} +}; + +/** + * @brief dump HCI cmd/evt + * @param pref data pref for dump + * @param width data line width for dump + * @param buf data buf for dump + * @param len data len for dump + * @return N/A + */ +void +mrvl_hex_dump(char *pref, int width, uint8_t * buf, int len) +{ + register int i, n; + + for (i = 0, n = 1; i < len; i++, n++) { + if (n == 1) { + printf("%s", pref); + } + printf("%2.2X ", buf[i]); + if (n == width) { + printf("\n"); + n = 0; + } + } + if (i && n != 1) { + printf("\n"); + } +} + +/** + * @brief open fm char device + * @param dev fm char device name + * @return fm char device describe + */ +int +init_chardev(char *dev) +{ + int fd; + +#ifdef TOOL_DEBUG + printf("Debug: Calling open on char device %s\n", dev); +#endif + + fd = open(dev, O_RDWR | O_NOCTTY); + if (fd < 0) { + perror("Can't open char device"); + exit(1); + } + if (verbose) { + printf("Returning File Descriptor for char device"); + } + return fd; +} + +/** + * @brief check evt/cmd status + * @param buf_ptr pointer to HCi evt header + * @return 0:success, other: fail + */ +int +check_evt_command_status(unsigned char *buf_ptr) +{ + evt_cmd_status *ecs; + ecs = (evt_cmd_status *) buf_ptr; + if (btohs(ecs->status) != EVT_CMD_STATUS_SUCCESS) { + printf("Command Failed. Command Status Event received with Non-zero status.\n"); + return -1; + } + return 0; +} + +/** + * @brief wait cmd resp or event + * @param dd file describe of fm char device + * @param ogf Hci cmd ogf + * @param ocf HCI cmd ocf + * @return N/A + */ +void +fm_wait_for_cmd_complete(int dd, uint8_t ogf, uint16_t ocf) +{ + unsigned char *ptr; + hci_event_hdr *hdr; + evt_cmd_complete evt_cc, *ecc = &evt_cc; + evt_mode_change emc, *emc_ptr = &emc; + evt_phy_link_complete eplc, *eplc_ptr = &eplc; + evt_log_link_complete ellc, *ellc_ptr = &ellc; + uint8_t phandle; + uint16_t lhandle; + uint16_t opcode = 0; + int len = 0; + uint8_t buf[HCI_MAX_ACL_SIZE]; + + memset(ecc, 0, sizeof(evt_cmd_complete)); + + while (1) { + len = read(dd, buf, HCI_MAX_EVENT_SIZE); + if (len < 0) { + perror("Read failed"); + exit(EXIT_FAILURE); + } + + hdr = (void *)(buf + 1); + ptr = buf + (1 + HCI_EVENT_HDR_SIZE); + len -= (1 + HCI_EVENT_HDR_SIZE); + + if (hdr->evt == EVT_CMD_COMPLETE) { + ecc = (evt_cmd_complete *) ptr; + opcode = cmd_opcode_pack(ogf, ocf); + if (btohs(ecc->opcode) == opcode) { + PRINT_EVT(hdr, ptr, len); + return; + } + } else if (hdr->evt == EVT_CMD_STATUS) { + if (check_evt_command_status(ptr)) { + return; + } + } else { + printf("Received Event Code %X\n", hdr->evt); + PRINT_EVT(hdr, ptr, len); + return; + } + } +} + +/** + * @brief send cmd to fm char device + * @param fd file describe of fm char device + * @param argc number of arguments + * @param argv A pointer to arguments array (cmd content) + * @return 0:success, other: fail + */ +int +fm_send_cmd(int fd, int argc, char **argv) +{ + uint16_t opcode; + uint8_t cmd[512]; + int len = 0, i = 0, j = 0; + uint16_t ogf, ocf; + + if (argc < 1) { + printf("Did not provide cmd content\n"); + printf("Usage: drvtest [content]\n"); + exit(0); + } + + ogf = strtol(argv[0], NULL, 16); + ocf = strtol(argv[1], NULL, 16); + +#ifdef TOOL_DEBUG + printf("%X, %X, argc = %d\n", ogf, ocf, argc); +#endif + + opcode = OpCodePack(ogf, ocf); + + cmd[0] = HCI_COMMAND_PKT; + cmd[1] = (uint8_t) opcode; + cmd[2] = (uint8_t) (opcode >> 8); + + for (i = 2; i < argc; i++, len++) { + cmd[j + 4] = (uint8_t) strtol(argv[i], NULL, 16); + j++; + } + + cmd[3] = len; + + PRINT_CMD(ogf, ocf, cmd, len + 4) + + if (write(fd, cmd, len + 4) != (len + 4)) { + perror("Can't write raw command"); + return -1; + } + + fm_wait_for_cmd_complete(fd, ogf, ocf); + return 0; +} + +/** + * @brief Display usage + * @return N/A + */ +static void +usage(void) +{ + printf("fmapp - ver 1.0.0.2\n"); + + printf("Usage:\n" + "\tfmapp [options] devicename ogf 0cf [command content]\n" + "\tdevicename example mfmchar0\n" + "\togf example 0x3f\n" + "\tocf example 0x280\n" + "\tCommands supported are as follows:\n"); + printf("Command Options:\n" "\t-h\tDisplay help\n" "\t-v\tVerbose\n"); +} + +/** + * @brief Entry function for fmapp + * @param argc number of arguments + * @param argv A pointer to arguments array + * @return 0/1 + */ +int +main(int argc, char *argv[]) +{ + int opt = 0; + int send_break = 0; + int n = 0; + char dev[FM_PATH_MAX]; + int init_speed = 0; + int fd = 0; + char *optstr; + int i = 0; + + optind = 0; + + while ((opt = + getopt_long(argc, argv, "+i:hv", main_options, NULL)) != -1) { + switch (opt) { + case 'v': + verbose = 1; + break; + case 'h': + default: + usage(); + return 0; + } + } + + argc -= optind; + argv += optind; + optind = 0; + + if (argc < 2) { + usage(); + return 0; + } + + optstr = argv[0]; + + dev[0] = 0; + strcat(dev, "/dev/"); + strcat(dev, optstr); + + fd = init_chardev(dev); + + argv++; + argc--; + + fm_send_cmd(fd, argc, argv); + if (close(fd) < 0) { + perror("Can't close serial port"); + } + + return 1; +} diff --git a/pool/shard000/C/0010182_mkdirhier.c b/pool/shard000/C/0010182_mkdirhier.c new file mode 100644 index 0000000000000000000000000000000000000000..16b7fff86bdd636385e5acc235b3444e6d465ac6 --- /dev/null +++ b/pool/shard000/C/0010182_mkdirhier.c @@ -0,0 +1,80 @@ +/* $Xorg: mkdirhier.c,v 1.4 2001/02/09 02:03:17 xorgcvs Exp $ */ +/* + +Copyright (C) 1996, 1998 The Open Group + +Permission to use, copy, modify, distribute, and sell this software and its +documentation for any purpose is hereby granted without fee, provided that +the above copyright notice appear in all copies and that both that +copyright notice and this permission notice appear in supporting +documentation. + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +Except as contained in this notice, the name of The Open Group shall +not be used in advertising or otherwise to promote the sale, use or +other dealings in this Software without prior written authorization +from The Open Group. + +*/ +/* $XFree86: xc/config/util/mkdirhier.c,v 1.7 2002/07/01 02:25:51 tsi Exp $ */ + +/* + * Simple mkdirhier program for Windows NT + */ +#include +#include +#ifndef __UNIXOS2__ +#include +#else +#include +#endif +#include +#include + +char * +next_sep(char *path) +{ + while (*path) + if (*path == '/' || *path == '\\') + return path; + else + path++; + return NULL; +} + +int +main(int argc, char *argv[]) +{ + char *dirname, *next, *prev; + char buf[1024]; + struct _stat sb; + + if (argc < 2) + exit(1); + dirname = argv[1]; + + prev = dirname; + while (next = next_sep(prev)) { + strncpy(buf, dirname, next - dirname); + buf[next - dirname] = '\0'; + /* if parent dir doesn't exist yet create it */ + if (_stat(buf, &sb)) + _mkdir(buf); /* no error checking to avoid barfing on C: */ + prev = next + 1; + } + if (_mkdir(dirname) == -1) { + perror("mkdirhier failed"); + exit(1); + } + exit(0); +} diff --git a/pool/shard000/C/0010183_pulse_vrot.c b/pool/shard000/C/0010183_pulse_vrot.c new file mode 100644 index 0000000000000000000000000000000000000000..4eb4fb6d90e023dba0f33e59f722a6199e238bda --- /dev/null +++ b/pool/shard000/C/0010183_pulse_vrot.c @@ -0,0 +1,73 @@ +#include +#include + +#include "mcmc.h" +#include "parallel_tempering.h" +#include "debug.h" + +#ifndef HMIN +#define HMIN 1e-6 +#endif + +static double calc_prior(const mcmc * m) { + unsigned int i; + const gsl_vector * params = m->params; + double prior = 0; + double mode_height; + for (i = 3; i < get_n_par(m); i += 2) { + mode_height = gsl_vector_get(params, i + 1); + prior += gsl_sf_log(mode_height + HMIN); + } + i = (get_n_par(m) - 3) / 2; + return -prior / i; +} + +void calc_model(mcmc * m, const gsl_vector * old_values) { + unsigned int i; + unsigned int j; + double y = 0; + double mode_height; + double mode_freq; + double distance; + double freq; + const gsl_vector * params = m->params; + double prob = gsl_vector_get(params, 1); + double lifetime = gsl_vector_get(params, 0); + double vrot = gsl_vector_get(params, 2); + set_prior(m, calc_prior(m)); + + (void) old_values; + assert((get_n_par(m) - 3) % 2 == 0); + for (i = 0; i < m->data->size1; i++) { + y = 0; + freq = gsl_matrix_get(m->data, i, 0); + + j = 3; + mode_freq = gsl_vector_get(params, j); + mode_height = gsl_vector_get(params, j + 1); + distance = mode_freq - freq; + y += mode_height / (1 + pow(2 * M_PI * distance * lifetime, 2)); + + j = 5; + mode_freq = gsl_vector_get(params, j); + mode_height = gsl_vector_get(params, j + 1); + distance = mode_freq - freq + -1 * vrot; + y += mode_height / (1 + pow(2 * M_PI * distance * lifetime, 2)); + distance = mode_freq - freq; + y += mode_height / (1 + pow(2 * M_PI * distance * lifetime, 2)); + distance = mode_freq - freq + 1 * vrot; + y += mode_height / (1 + pow(2 * M_PI * distance * lifetime, 2)); + + prob += gsl_sf_log(y) + gsl_matrix_get(m->data, i, 1) / y; + } + + set_prob(m, get_prior(m) + -get_beta(m) * prob); +} + +void calc_model_for(mcmc * m, const unsigned int j, const double old_value) { + (void) j; + (void) old_value; + calc_model(m, NULL); + return; +} + diff --git a/pool/shard000/C/0010184_config.c b/pool/shard000/C/0010184_config.c new file mode 100644 index 0000000000000000000000000000000000000000..14c519590bf1630dbfed37ec5ad1a6686b4e0870 --- /dev/null +++ b/pool/shard000/C/0010184_config.c @@ -0,0 +1,261 @@ +/* + * config.c + * + * Created on: Feb 2, 2017 + * Author: pchero + */ + +#define _GNU_SOURCE + +#include +#include +#include +#include + +#include "common.h" +#include "slog.h" +#include "minIni.h" +#include "utils.h" + +#include "config.h" + +#define DEF_CONF_FILENAME "/opt/etc/jade.conf" + +#define DEF_JADE_LIB_DIR "/opt/var/lib/jade" +#define DEF_JADE_ETC_DIR "/opt/etc" + +#define DEF_GENERAL_AST_SERV_ADDR "127.0.0.1" +#define DEF_GENERAL_AMI_SERV_ADDR "127.0.0.1" +#define DEF_GENERAL_AMI_SERV_PORT "5038" +#define DEF_GENERAL_AMI_USERNAME "admin" +#define DEF_GENERAL_AMI_PASSWORD "admin" +#define DEF_GENERAL_HTTPS_ADDR "0.0.0.0" +#define DEF_GENERAL_HTTPS_PORT "8081" +#define DEF_GENERAL_HTTPS_PEMFILE "/opt/bin/jade.pem" +#define DEF_GENERAL_ZMQ_ADDR_PUBLISH "tcp://*:8082" // zmq address for publish +#define DEF_GENERAL_WEBSOCK_ADDR "0.0.0.0" +#define DEF_GENERAL_WEBSOCK_PORT "8083" +#define DEF_GENERAL_LOGLEVEL "5" +#define DEF_GENERAL_DATABASE_NAME_AST ":memory:" +#define DEF_GENERAL_DATABASE_NAME_JADE "./jade_database.db" +#define DEF_GENERAL_EVENT_TIME_FAST "100000" +#define DEF_GENERAL_EVENT_TIME_SLOW "3000000" +#define DEF_GENERAL_DIR_CONF "/etc/asterisk" +#define DEF_GENERAL_DIR_MODULE "/usr/lib/asterisk/modules" + +#define DEF_VOICEMAIL_DIRECTORY "/var/spool/asterisk/voicemail" + +#define DEF_OB_DIALING_RESULT_FILENAME "./outbound_result.json" +#define DEF_OB_DIALING_TIMEOUT "30" +#define DEF_OB_DATABASE_NAME "./outbound_database.db" + +#define DEF_DIALPLA_DEFAULT_ORIGINATE_TO_DEVICE "72ebc4b8-ac5e-4863-a7d3-55ffdfef43ee" +#define DEF_DIALPLA_DEFAULT_ORIGINATE_TO_NUMBER "a922cf23-c650-426a-9ba0-a35ebc68a464" + +#define DEF_PJSIP_CONTEXT "demo" +#define DEF_PJSIP_DTLS_CERT_FILE "/opt/bin/jade.pem" + +extern app* g_app; +static char g_config_filename[1024] = ""; + +static bool load_config(void); +static bool write_config(void); +static bool init_directories(void); + + +/** + * Initiate configuration + * @return + */ +bool config_init(void) +{ + int ret; + + if((g_config_filename == NULL) || (strlen(g_config_filename) == 0)) { + snprintf(g_config_filename, sizeof(g_config_filename), DEF_CONF_FILENAME); + } + + ret = init_directories(); + if(ret == false) { + return false; + } + + ret = load_config(); + if(ret == false) { + return false; + } + + return true; +} + +/** + * Initiate jade's default directories. + * @return + */ +static bool init_directories(void) +{ + int ret; + char* cmd; + + // /opt/etc + asprintf(&cmd, "mkdir -p %s", DEF_JADE_ETC_DIR); + ret = system(cmd); + sfree(cmd); + if(ret != EXIT_SUCCESS) { + slog(LOG_ERR, "Could not create directory. dir[%s]", DEF_JADE_ETC_DIR); + return false; + } + + // /opt/var/lib + asprintf(&cmd, "mkdir -p %s", DEF_JADE_LIB_DIR); + ret = system(cmd); + sfree(cmd); + if(ret != EXIT_SUCCESS) { + slog(LOG_ERR, "Could not create directory. dir[%s]", DEF_JADE_LIB_DIR); + return false; + } + + return true; +} + +/** + * Update config filename + * @param filename + * @return + */ +bool config_update_filename(const char* filename) +{ + if(filename == NULL) { + printf("Wrong input parameter."); + return false; + } + + snprintf(g_config_filename, sizeof(g_config_filename), "%s", filename); + printf("Updated config filename. config_filename[%s]", g_config_filename); + + return true; +} + +/** + * Load configuration file and update + * @return + */ +static bool load_config(void) +{ + const char* tmp_const; + int ret; + json_t* j_conf_def; + json_t* j_conf; + const char* key; + json_t* j_tmp; + + slog(LOG_INFO, "Load configuration file. filename[%s]", g_config_filename); + + // create default conf + j_conf_def = json_pack("{" + "s:{" + "s:s, s:s, s:s, s:s, s:s, s:s, " + "s:s, s:s, " + "s:s, s:s, s:s, " + "s:s, s:s, s:s, " + "s:s, s:s, " + "s:s, s:s " + "}," // general + "s:{s:s}, " // voicemail + "s:{s:s, s:s, s:s}," // ob + "s:{s:s, s:s}," // pjsip + "s:{s:s, s:s}" // dialplan + "}", + "general", + "ast_serv_addr", DEF_GENERAL_AST_SERV_ADDR, + "ami_serv_addr", DEF_GENERAL_AMI_SERV_ADDR, + "ami_serv_port", DEF_GENERAL_AMI_SERV_PORT, + "ami_username", DEF_GENERAL_AMI_USERNAME, + "ami_password", DEF_GENERAL_AMI_PASSWORD, + "loglevel", DEF_GENERAL_LOGLEVEL, + + "database_name_ast", DEF_GENERAL_DATABASE_NAME_AST, + "database_name_jade", DEF_GENERAL_DATABASE_NAME_JADE, + + "https_addr", DEF_GENERAL_HTTPS_ADDR, + "https_port", DEF_GENERAL_HTTPS_PORT, + "https_pemfile", DEF_GENERAL_HTTPS_PEMFILE, + + "zmq_addr_pub", DEF_GENERAL_ZMQ_ADDR_PUBLISH, + "websock_addr", DEF_GENERAL_WEBSOCK_ADDR, + "websock_port", DEF_GENERAL_WEBSOCK_PORT, + + "event_time_fast", DEF_GENERAL_EVENT_TIME_FAST, + "event_time_slow", DEF_GENERAL_EVENT_TIME_SLOW, + + "directory_conf", DEF_GENERAL_DIR_CONF, + "directory_module", DEF_GENERAL_DIR_MODULE, + + "voicemail", + "dicretory", DEF_VOICEMAIL_DIRECTORY, + + "ob", + "dialing_result_filename", DEF_OB_DIALING_RESULT_FILENAME, + "dialing_timeout", DEF_OB_DIALING_TIMEOUT, + "database_name", DEF_OB_DATABASE_NAME, + + "pjsip", + "context", DEF_PJSIP_CONTEXT, + "dtls_cert_file", DEF_PJSIP_DTLS_CERT_FILE, + + "dialplan", + "default_dpma_originate_to_device", DEF_DIALPLA_DEFAULT_ORIGINATE_TO_DEVICE, + "default_dpma_originate_to_number", DEF_DIALPLA_DEFAULT_ORIGINATE_TO_NUMBER + ); + if(j_conf_def == NULL) { + printf("Could not create default config.\n"); + return false; + } + + j_conf = json_load_file(g_config_filename, JSON_DECODE_ANY, NULL); + + // update conf + json_object_foreach(j_conf_def, key, j_tmp) { + json_object_update(j_tmp, json_object_get(j_conf, key)); + } + json_decref(j_conf); + + if(g_app->j_conf != NULL) { + json_decref(g_app->j_conf); + } + + g_app->j_conf = j_conf_def; + write_config(); + + // update log level + tmp_const = json_string_value(json_object_get(json_object_get(g_app->j_conf, "general"), "loglevel")); + ret = atoi(tmp_const); + slog_update_log_level(ret); + + slog(LOG_DEBUG, "load_config end."); + return true; +} + +/** + * Write current config optin to the file. + * @return + */ +static bool write_config(void) +{ + if(g_app->j_conf == NULL) { + slog(LOG_WARNING, "Wrong input parameter."); + return false; + } + slog(LOG_DEBUG, "Fired write_config."); + + utils_create_empty_file(g_config_filename); + + json_dump_file(g_app->j_conf, g_config_filename, JSON_INDENT(4)); + + return true; +} + + + + + diff --git a/pool/shard000/C/0010190_dir.c b/pool/shard000/C/0010190_dir.c new file mode 100644 index 0000000000000000000000000000000000000000..c657710a395f587a29cbf4f4ac5e895e1a3b7187 --- /dev/null +++ b/pool/shard000/C/0010190_dir.c @@ -0,0 +1,61 @@ +/* + * Id: dir.c,v 1.2 1999/11/02 06:16:47 keithp Exp $ + * + * Copyright 1999 SuSE, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and its + * documentation for any purpose is hereby granted without fee, provided that + * the above copyright notice appear in all copies and that both that + * copyright notice and this permission notice appear in supporting + * documentation, and that the name of SuSE not be used in advertising or + * publicity pertaining to distribution of the software without specific, + * written prior permission. SuSE makes no representations about the + * suitability of this software for any purpose. It is provided "as is" + * without express or implied warranty. + * + * SuSE DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL SuSE + * BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION + * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Author: Keith Packard, SuSE, Inc. + */ +/* $XFree86: xc/lib/font/builtins/dir.c,v 1.4 2000/02/23 20:29:33 dawes Exp $ */ + +#include "builtin.h" + +int +BuiltinReadDirectory (directory, pdir) + char *directory; + FontDirectoryPtr *pdir; +{ + FontDirectoryPtr dir; + int i; + + dir = FontFileMakeDir ("", builtin_dir_count); + for (i = 0; i < builtin_dir_count; i++) + { + if (!FontFileAddFontFile (dir, + (char *) builtin_dir[i].font_name, + (char *) builtin_dir[i].file_name)) + { + FontFileFreeDir (dir); + return BadFontPath; + } + } + for (i = 0; i < builtin_alias_count; i++) + { + if (!FontFileAddFontAlias (dir, + (char *) builtin_alias[i].alias_name, + (char *) builtin_alias[i].font_name)) + { + FontFileFreeDir (dir); + return BadFontPath; + } + } + FontFileSortDir (dir); + *pdir = dir; + return Successful; +} diff --git a/pool/shard000/C/0010193_vsnprintf.c b/pool/shard000/C/0010193_vsnprintf.c new file mode 100644 index 0000000000000000000000000000000000000000..c4eaa15d244f02a74b271a27d5e178edba435fa7 --- /dev/null +++ b/pool/shard000/C/0010193_vsnprintf.c @@ -0,0 +1,33 @@ +/* This file is part of The Firekylin Operating System. + * + * Copyright 2016 Liuxiaofeng + * + * 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 +#include +#include + +int vsnprintf(char * buf, size_t size, const char *fmt, va_list ap) +{ + char tmp_buf[2048]; + int i; + + i = vsprintf(tmp_buf, fmt, ap); + + if (i > size) + i = size; + memcpy(buf, tmp_buf, i); + return i; +} diff --git a/pool/shard000/C/0010197_vect-87.c b/pool/shard000/C/0010197_vect-87.c new file mode 100644 index 0000000000000000000000000000000000000000..ba18eaa91c40cc8d01c9e8da17440f6b25d210c6 --- /dev/null +++ b/pool/shard000/C/0010197_vect-87.c @@ -0,0 +1,55 @@ +/* { dg-require-effective-target vect_int } */ + +#include +#include "tree-vect.h" + +#define N 16 + +typedef int aint __attribute__ ((__aligned__(16))); + +int main1 (int n, int *a) +{ + int i, j, k; + int b[N]; + + for (i = 0; i < n; i++) + { + for (j = 0; j < n; j++) + { + k = i + n; + a[j] = k; + } + b[i] = k; + } + + + for (j = 0; j < n; j++) + if (a[j] != i + n - 1) + abort(); + + for (j = 0; j < n; j++) + if (b[j] != j + n) + abort(); + + return 0; +} + +int main (void) +{ + aint a[N]; + + check_vect (); + + main1 (N, a); + main1 (0, a); + main1 (1, a); + main1 (2, a); + main1 (N-1, a); + + return 0; +} + +/* Fails for targets that don't vectorize PLUS (e.g alpha). */ +/* { dg-final { scan-tree-dump-times "vectorized 1 loops" 1 "vect" { xfail alpha*-*-* } } } */ +/* { dg-final { scan-tree-dump-times "Vectorizing an unaligned access" 0 "vect" } } */ +/* { dg-final { scan-tree-dump-times "Alignment of access forced using peeling" 1 "vect" { xfail alpha*-*-* } } } */ diff --git a/pool/shard000/C/0010202_irq.c b/pool/shard000/C/0010202_irq.c new file mode 100644 index 0000000000000000000000000000000000000000..767f5871b1715ef16247d1b3555cbd5ada45c9ef --- /dev/null +++ b/pool/shard000/C/0010202_irq.c @@ -0,0 +1,72 @@ +/* + * interrupt controller support for CSR SiRFprimaII + * + * Copyright (c) 2011 Cambridge Silicon Radio Limited, a CSR plc group company. + * + * Licensed under GPLv2 or later. + */ + +#include +#include +#include +#include +#include +#include +#include + +#define SIRFSOC_INT_RISC_MASK0 0x0018 +#define SIRFSOC_INT_RISC_MASK1 0x001C +#define SIRFSOC_INT_RISC_LEVEL0 0x0020 +#define SIRFSOC_INT_RISC_LEVEL1 0x0024 + +void __iomem *sirfsoc_intc_base; + +static __init void +sirfsoc_alloc_gc(void __iomem *base, unsigned int irq_start, unsigned int num) +{ + struct irq_chip_generic *gc; + struct irq_chip_type *ct; + + gc = irq_alloc_generic_chip("SIRFINTC", 1, irq_start, base, handle_level_irq); + ct = gc->chip_types; + + ct->chip.irq_mask = irq_gc_mask_clr_bit; + ct->chip.irq_unmask = irq_gc_mask_set_bit; + ct->regs.mask = SIRFSOC_INT_RISC_MASK0; + + irq_setup_generic_chip(gc, IRQ_MSK(num), IRQ_GC_INIT_MASK_CACHE, IRQ_NOREQUEST, 0); +} + +static __init void sirfsoc_irq_init(void) +{ + sirfsoc_alloc_gc(sirfsoc_intc_base, 0, 32); + sirfsoc_alloc_gc(sirfsoc_intc_base + 4, 32, SIRFSOC_INTENAL_IRQ_END - 32); + + writel_relaxed(0, sirfsoc_intc_base + SIRFSOC_INT_RISC_LEVEL0); + writel_relaxed(0, sirfsoc_intc_base + SIRFSOC_INT_RISC_LEVEL1); + + writel_relaxed(0, sirfsoc_intc_base + SIRFSOC_INT_RISC_MASK0); + writel_relaxed(0, sirfsoc_intc_base + SIRFSOC_INT_RISC_MASK1); +} + +static struct of_device_id intc_ids[] = { + { .compatible = "sirf,prima2-intc" }, + {}, +}; + +void __init sirfsoc_of_irq_init(void) +{ + struct device_node *np; + + np = of_find_matching_node(NULL, intc_ids); + if (!np) + panic("unable to find compatible intc node in dtb\n"); + + sirfsoc_intc_base = of_iomap(np, 0); + if (!sirfsoc_intc_base) + panic("unable to map intc cpu registers\n"); + + of_node_put(np); + + sirfsoc_irq_init(); +} diff --git a/pool/shard000/C/0010204_parse_support.c b/pool/shard000/C/0010204_parse_support.c new file mode 100644 index 0000000000000000000000000000000000000000..728e0f722601b3cb512f77aa483cdebe9989f118 --- /dev/null +++ b/pool/shard000/C/0010204_parse_support.c @@ -0,0 +1,215 @@ +/************************************************************ +** +** COPYRIGHT (C) 2004 GANNON UNIVERSITY +** ALL RIGHTS RESERVED +** +** This software is distributed on an as-is basis +** with no warranty implied or intended. No author +** or distributor takes responsibility to anyone +** regarding its use of or suitability. +** +** The software may be distributed and modified +** freely for academic and other non-commercial +** use but may NOT be utilized or included in whole +** or part within any commercial product. +** +** This copyright notice must remain on all copies +** and modified versions of this software. +** +************************************************************/ + + +/* file parse_support.c */ +/* ------------------------------------------------------------------------ + * Routines for integrating ASG into a language parser, such as the + * hpice parser in XCircuit 3.2.7+. + * ------------------------------------------------------------------------ + */ +#include +#include +#include +#include +#include "network.h" + +/*--------------------------------------------------------------- + * Global Variable Definitions + *--------------------------------------------------------------- + */ + +module *curobj_module; + +/*********************************************************************************** + Add2TermModule - This method is used to add a new module found in the parse tree of a language. E.g., this can be used in HSPICE + parser to add a module. + + +**************************************************************************************/ + +void Add2TermModule( name, type, inNode, outNode ) +char* name; // Parser-supplied module name (e.g., CAP32) +char* type; // Parser-supplied identification type (e.g., CAPACITOR) +char* inNode; // Net name for input net +char* outNode; // Net name for output net +{ + net* pNet; + + //Create a new Module( Capacitor or Resistor or Inductor or Buffer, Inverter gate etc) + curobj_module = newobject(name, type); + + //Add Inputports + pNet = get_net(inNode); + + //If Input Node does not exist in the global database + if( pNet == NULL ) + { + newnode(inNode); + } + addin(inNode, 0, 1); + + //Add output ports + pNet = get_net(outNode); + + //If output Node does not exist in the global database + if( pNet == NULL ) + { + newnode(outNode); + } + addout(outNode, 0, 1); +} + +/*********************************************************************************** + Add3TermModule - This method is used to add a new module. This can be used in HSPICE + parser to add a module. + + +**************************************************************************************/ + +void Add3TermModule( name, type, inNode, outNode, inoutNode) +char* name; // Parser-supplied module name (e.g., CAP32) +char* type; // Parser-supplied identification type (e.g., CAPACITOR) +char* inNode; // Net name for input (left) net +char* outNode; // Net name for output (right) net +char* inoutNode; // Net name for inout (top) net +{ + net* pNet; + + //Create a new Module( Capacitor or Resistor or Inductor or Buffer, Inverter gate etc) + curobj_module = newobject(name, type); + + //Add Inputports + pNet = get_net(inNode); + + //If Input Node does not exist in the global database + if( pNet == NULL ) + { + newnode(inNode); + } + addin(inNode, 0, 1); + + //Add output ports + pNet = get_net(outNode); + + //If output Node does not exist in the global database + if( pNet == NULL ) + { + newnode(outNode); + } + addout(outNode, 0, 1); + + //Add inout ports + pNet = get_net(inoutNode); + + //If inout Node does not exist in the global database + if( pNet == NULL ) + { + newnode(inoutNode); + } + addinout(inoutNode, 0, 1); +} + +/*----------------------------------------------------------------------*/ +/* AddNTermModule --- */ +/* Add a module of N terminals to the database */ +/* */ +/* name = Parser-supplied module name (e.g., CAP32) */ +/* type = Parser-supplied identification type (e.g., CAPACITOR) */ +/* N = Number of nodes, followed by list of node names. */ +/* followed by pairs of char * types declaring the name of the pin */ +/* (expected in the xcircuit object) followed by the name of the net. */ +/*----------------------------------------------------------------------*/ + +void AddNTermModule(char *name, char *type, int N, ...) +{ + va_list args; + int i; + net *pNet; + char *pinName; + char *netName; + objectptr pobj; + + // Create a new Module (Capacitor, Resistor, Inductor or Buffer, Inverter gate etc) + curobj_module = newobject(name, type); + + // Get the corresponding XCircuit object and get the object dimensions + pobj = NameToObject(type, NULL, FALSE); + if (pobj != NULL) { + curobj_module->x_size = pobj->bbox.width; + curobj_module->y_size = pobj->bbox.height; + } + else { + error("AddNTermModule: No such object", type); + } + + va_start(args, N); + + for (i = 0; i < N; i++) { + // Add port + pinName = va_arg(args, char *); + netName = va_arg(args, char *); + pNet = get_net(netName); + + // If Input Node does not exist in the global database + if (pNet == NULL) { + newnode(netName); + } + add_xc_term(type, pinName, netName, i, N); + } + va_end(args); +} + +/*--------------------------------------------------------------*/ +/* Handle modules with an abitrary number of terminals in the */ +/* following way: AddNTermModule() is called with N = 0 to */ +/* create curobj_module (which is global). Then, for each pin, */ +/* the routine AddModuleTerm() is called to associate a net */ +/* with each pin, in turn. */ +/*--------------------------------------------------------------*/ + +/*--------------------------------------------------------------*/ +/* For the moment, pins will be named "1", "2", etc. To do: */ +/* look up the object having a name matching "type". Confirm */ +/* a match in the number of pins N, and then pick up the pin */ +/* names from the object itself. Presumably this is done by */ +/* assuming that the object has an info label "spice:..." and */ +/* using that. It is the responsibility of the user to ensure */ +/* that the library used to represent primitives in the spice */ +/* deck contains the correct number and order of pins. */ +/*--------------------------------------------------------------*/ + +void AddModuleTerm(char *type, char *netName, int portnum, int allports) +{ + net *pNet; + + pNet = get_net(netName); + + // If Input Node does not exist in the global database + if (pNet == NULL) { + newnode(netName); + } + add_xc_term(type, NULL, netName, portnum, allports); +} + +/*--------------------------------------------------------------- + * END OF FILE + *--------------------------------------------------------------- + */ diff --git a/pool/shard000/C/0010223_notif_condition.c b/pool/shard000/C/0010223_notif_condition.c new file mode 100644 index 0000000000000000000000000000000000000000..8fc71e9efb1e48dcc0eec8ea71c48ff811824087 --- /dev/null +++ b/pool/shard000/C/0010223_notif_condition.c @@ -0,0 +1,171 @@ + +#include +#include +#include +#include "notif_condition.h" + +OpenAPI_notif_condition_t *OpenAPI_notif_condition_create( + OpenAPI_list_t *monitored_attributes, + OpenAPI_list_t *unmonitored_attributes + ) +{ + OpenAPI_notif_condition_t *notif_condition_local_var = OpenAPI_malloc(sizeof(OpenAPI_notif_condition_t)); + if (!notif_condition_local_var) { + return NULL; + } + notif_condition_local_var->monitored_attributes = monitored_attributes; + notif_condition_local_var->unmonitored_attributes = unmonitored_attributes; + + return notif_condition_local_var; +} + +void OpenAPI_notif_condition_free(OpenAPI_notif_condition_t *notif_condition) +{ + if (NULL == notif_condition) { + return; + } + OpenAPI_lnode_t *node; + OpenAPI_list_for_each(notif_condition->monitored_attributes, node) { + ogs_free(node->data); + } + OpenAPI_list_free(notif_condition->monitored_attributes); + OpenAPI_list_for_each(notif_condition->unmonitored_attributes, node) { + ogs_free(node->data); + } + OpenAPI_list_free(notif_condition->unmonitored_attributes); + ogs_free(notif_condition); +} + +cJSON *OpenAPI_notif_condition_convertToJSON(OpenAPI_notif_condition_t *notif_condition) +{ + cJSON *item = NULL; + + if (notif_condition == NULL) { + ogs_error("OpenAPI_notif_condition_convertToJSON() failed [NotifCondition]"); + return NULL; + } + + item = cJSON_CreateObject(); + if (notif_condition->monitored_attributes) { + cJSON *monitored_attributes = cJSON_AddArrayToObject(item, "monitoredAttributes"); + if (monitored_attributes == NULL) { + ogs_error("OpenAPI_notif_condition_convertToJSON() failed [monitored_attributes]"); + goto end; + } + + OpenAPI_lnode_t *monitored_attributes_node; + OpenAPI_list_for_each(notif_condition->monitored_attributes, monitored_attributes_node) { + if (cJSON_AddStringToObject(monitored_attributes, "", (char*)monitored_attributes_node->data) == NULL) { + ogs_error("OpenAPI_notif_condition_convertToJSON() failed [monitored_attributes]"); + goto end; + } + } + } + + if (notif_condition->unmonitored_attributes) { + cJSON *unmonitored_attributes = cJSON_AddArrayToObject(item, "unmonitoredAttributes"); + if (unmonitored_attributes == NULL) { + ogs_error("OpenAPI_notif_condition_convertToJSON() failed [unmonitored_attributes]"); + goto end; + } + + OpenAPI_lnode_t *unmonitored_attributes_node; + OpenAPI_list_for_each(notif_condition->unmonitored_attributes, unmonitored_attributes_node) { + if (cJSON_AddStringToObject(unmonitored_attributes, "", (char*)unmonitored_attributes_node->data) == NULL) { + ogs_error("OpenAPI_notif_condition_convertToJSON() failed [unmonitored_attributes]"); + goto end; + } + } + } + +end: + return item; +} + +OpenAPI_notif_condition_t *OpenAPI_notif_condition_parseFromJSON(cJSON *notif_conditionJSON) +{ + OpenAPI_notif_condition_t *notif_condition_local_var = NULL; + cJSON *monitored_attributes = cJSON_GetObjectItemCaseSensitive(notif_conditionJSON, "monitoredAttributes"); + + OpenAPI_list_t *monitored_attributesList; + if (monitored_attributes) { + cJSON *monitored_attributes_local; + if (!cJSON_IsArray(monitored_attributes)) { + ogs_error("OpenAPI_notif_condition_parseFromJSON() failed [monitored_attributes]"); + goto end; + } + monitored_attributesList = OpenAPI_list_create(); + + cJSON_ArrayForEach(monitored_attributes_local, monitored_attributes) { + if (!cJSON_IsString(monitored_attributes_local)) { + ogs_error("OpenAPI_notif_condition_parseFromJSON() failed [monitored_attributes]"); + goto end; + } + OpenAPI_list_add(monitored_attributesList, ogs_strdup(monitored_attributes_local->valuestring)); + } + } + + cJSON *unmonitored_attributes = cJSON_GetObjectItemCaseSensitive(notif_conditionJSON, "unmonitoredAttributes"); + + OpenAPI_list_t *unmonitored_attributesList; + if (unmonitored_attributes) { + cJSON *unmonitored_attributes_local; + if (!cJSON_IsArray(unmonitored_attributes)) { + ogs_error("OpenAPI_notif_condition_parseFromJSON() failed [unmonitored_attributes]"); + goto end; + } + unmonitored_attributesList = OpenAPI_list_create(); + + cJSON_ArrayForEach(unmonitored_attributes_local, unmonitored_attributes) { + if (!cJSON_IsString(unmonitored_attributes_local)) { + ogs_error("OpenAPI_notif_condition_parseFromJSON() failed [unmonitored_attributes]"); + goto end; + } + OpenAPI_list_add(unmonitored_attributesList, ogs_strdup(unmonitored_attributes_local->valuestring)); + } + } + + notif_condition_local_var = OpenAPI_notif_condition_create ( + monitored_attributes ? monitored_attributesList : NULL, + unmonitored_attributes ? unmonitored_attributesList : NULL + ); + + return notif_condition_local_var; +end: + return NULL; +} + +OpenAPI_notif_condition_t *OpenAPI_notif_condition_copy(OpenAPI_notif_condition_t *dst, OpenAPI_notif_condition_t *src) +{ + cJSON *item = NULL; + char *content = NULL; + + ogs_assert(src); + item = OpenAPI_notif_condition_convertToJSON(src); + if (!item) { + ogs_error("OpenAPI_notif_condition_convertToJSON() failed"); + return NULL; + } + + content = cJSON_Print(item); + cJSON_Delete(item); + + if (!content) { + ogs_error("cJSON_Print() failed"); + return NULL; + } + + item = cJSON_Parse(content); + ogs_free(content); + if (!item) { + ogs_error("cJSON_Parse() failed"); + return NULL; + } + + OpenAPI_notif_condition_free(dst); + dst = OpenAPI_notif_condition_parseFromJSON(item); + cJSON_Delete(item); + + return dst; +} + diff --git a/pool/shard000/C/0010231_time.c b/pool/shard000/C/0010231_time.c new file mode 100644 index 0000000000000000000000000000000000000000..4dbf087019ebfddaf2c548ecc0356a10dadb2a7c --- /dev/null +++ b/pool/shard000/C/0010231_time.c @@ -0,0 +1,187 @@ +// ### BOILERPLATE ### +// Meter Clock Firmware +// Copyright (C) 2007 Peter Todd +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 2 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// ### BOILERPLATE ### + +#include +#include +#include +#include +#include +#include + +// This is all done a little strangely... +// +// First of all the pwm range is set to 240 rather than 256. This is so the +// time values can be easilly multipled to get pwm values. 240/60=4 240/24=10 +// +// Having established that each meter then needs to be incremented a given +// ratio with respect to the other, rather than the more simple on roll over. +// So we increment two sets of variables, the pwm value, as well as the +// ratio incrementor. + +// Number of hours, mins, secs +#define num_time_hours (24) +#define num_time_mins (60) +#define num_time_secs (60) + +// 8,000,000/4/256/256/4 = 7.629 +#define num_time_tics (8) + +// Ratio counters. Preset on startup to their value directly after roll-over. +uint8_t ratio_count_mins = num_time_hours; +uint8_t ratio_count_secs = num_time_mins; + +// Handled differently, due to the optimization that tics aren't actually kept +// track of, see below. +uint8_t ratio_count_tics = num_time_tics; + +void init_time(){ + init_ds3231(); + load_time_from_rtc(); + + // Like the ratio counts, set the values to the value directly after + // rollover. + //secs_meter = mins_meter = hours_meter = meter_range; +} + +// Sheesh, no osctune? +__sfr __at (0xf9b) OSCTUNE; + +// Further more, looks like we need a shadow register for it too... +// OSCTUNE++; does nothing, same with OSCTUNE += 2; but OSCTUNE = 10 +// does something. Weird. +uint8_t osctune_shadow = 0; + +void do_time_int(){ + // Tics aren't used anywhere else, so as an optimization, we can increment + // their ratio directly and not bother keeping track of their real value. + ratio_count_tics--; + if (!ratio_count_tics){ + ratio_count_tics = num_time_tics; + + // Once a second... + if (!(secs_meter % 4)) + inc_metric_running_time(); + + secs_meter--; + if (!secs_meter){ + secs_meter = meter_range; + // One minute has passed. This the the correct place to put this sort of + // code, when the pwm for the meter overflows, not the ratio counter. + + // Try to tune the oscillator slightly to follow the rtc perfectly. + // + // This will correct for some really major errors actually, OSCTUNE can + // shift the oscillator frequency quite a bit, in the order of multiple + // seconds off (%10) for setting it to 10 + + // Try to resync a bit... The current timer1 code, even though it's being + // fed from the clean 32khz output, seems to be a little slow. + + read_time_from_ds3231(); + + // If we're on track, seconds will == 0 too. Otherwise push or pull + // time_tics a bit to adjust the time. + if (ds3231_time.secs){ + if (ds3231_time.secs > num_time_secs / 2){ + // running fast + osctune_shadow--; + OSCTUNE = osctune_shadow; + } else { + // running slow + osctune_shadow++; + OSCTUNE = osctune_shadow; + } + } + } + + ratio_count_secs--; + if (!ratio_count_secs){ + ratio_count_secs = num_time_mins; + + inc_mins(); + } + } +} + +void inc_mins(){ + mins_meter--; + if (!mins_meter) + mins_meter = meter_range; + ratio_count_mins--; + if (!ratio_count_mins){ + ratio_count_mins = num_time_hours; + + inc_hours(); + } +} + +void inc_hours(){ + hours_meter--; + if (!hours_meter){ + hours_meter = meter_range; + + // Saving once an hour won't exceed the eeprom's write endurance. + save_metrics(); + } + + // No further ratio for hours. +} + +void clear_secs(){ + // Undo the effects of the ratio increments. + mins_meter += ((meter_range - secs_meter) / num_time_secs); + + // Reset to zero. + ratio_count_secs = num_time_secs; + secs_meter = meter_range; +} + +void save_time_to_rtc(){ + ds3231_time.hours = (meter_range - hours_meter) / 10; + ds3231_time.mins = (meter_range - mins_meter) / 4; + ds3231_time.secs = (meter_range - secs_meter) / 4; + + write_time_to_ds3231(); +} + +void load_time_from_rtc(){ + read_time_from_ds3231(); + + secs_meter = meter_range - (ds3231_time.secs * 4); + mins_meter = meter_range - (ds3231_time.mins * 4); + hours_meter = meter_range - (ds3231_time.hours * 10); + + // The above has a round off error, as the fractional part was thrown away, + // fix that. + mins_meter -= (meter_range - secs_meter) / num_time_mins; + hours_meter -= (meter_range - mins_meter) / num_time_hours; + + // Set the ratio counters as well. + ratio_count_tics = num_time_tics; + ratio_count_secs = num_time_mins - ((meter_range - secs_meter) % num_time_mins); + ratio_count_mins = num_time_hours - ((meter_range - mins_meter) % num_time_hours); +} + +// Local Variables: +// mode: C +// fill-column: 76 +// c-file-style: "gnu" +// indent-tabs-mode: nil +// End: +// vim: et:sw=2:sts=2:ts=2:cino=>2s,{s,\:s,+s,t0,g0,^-2,e-2,n-2,p2s,(0,=s: diff --git a/pool/shard000/C/0010250_etos_msgq.c b/pool/shard000/C/0010250_etos_msgq.c new file mode 100644 index 0000000000000000000000000000000000000000..aee0479358a66f32bbf90905ce6b365c01148ed1 --- /dev/null +++ b/pool/shard000/C/0010250_etos_msgq.c @@ -0,0 +1,478 @@ +/****************************************************************************** +File : etos_msgq.c + +This file is part of the ETOS distribution +Copyright (c) 2013, ETOS Development Team + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +(version 2) as published by the Free Software Foundation. See +the LICENSE file in the top-level directory for more details. + +Description: + exact time os message queue + +History: + +Date Author Notes +---------- ------- ------------------------- +2013-10-20 deeve Create +2015-4-14 deeve Add some comments + +*******************************************************************************/ + +/****************************************************************************** + * Includes * + ******************************************************************************/ +#include "etos_includes.h" + +/****************************************************************************** + * Defines * + ******************************************************************************/ + +/****************************************************************************** + * Global Variables * + ******************************************************************************/ + +/****************************************************************************** + * Local Variables * + ******************************************************************************/ + +/****************************************************************************** + * Local Functions * + ******************************************************************************/ + +/****************************************************************************** + * Global Functions * + ******************************************************************************/ + + +/** + * create a message queue. + * create a message queue for IPC(Communication between task) + * + * @param[in] msg_type + * @param[out] msg_handle output handle for other message queue API + * + * @return + * @retval 0 success + * @retval other fail + * + * @note none + * @see etos_msgq_destroy() + * @authors deeve + * @date 2015/4/14 + */ +s32 etos_msgq_create(etos_msg_type msg_type, etos_msg_handle *msg_handle) +{ + etos_msgq_head_t *msgq_head; + + if (msg_handle == NULL) { + return ETOS_INVALID_PARAM; + } + + msgq_head = (etos_msgq_head_t *)malloc(sizeof(etos_msgq_head_t)); + if (msgq_head == NULL) { + return ETOS_NO_MEM; + } + + msgq_head->msg_type = msg_type; + msgq_head->msg_check_flag = ETOS_MSG_CHECK_FLAG; + msgq_head->recv_task = 0; + INIT_LIST_HEAD(&msgq_head->list); + + *msg_handle = (etos_msg_handle)msgq_head; + + return ETOS_RET_OK; +} + + + +/** + * destroy a message queue. + * destroy a message queue which is created by etos_msgq_create + * + * @param[in] msg_handle + * + * @return + * @retval 0 success + * @retval other fail + * + * @note none + * @see etos_msgq_create() + * @authors deeve + * @date 2015/4/14 + */ +s32 etos_msgq_destroy(etos_msg_handle msg_handle) +{ + list_t *entry; + etos_msgq_buf_t *msgq_buf; + etos_task_state_e recv_task_state; + etos_msgq_head_t *msgq_head = (etos_msgq_head_t *)msg_handle; + etos_init_critical(); + + if ((msgq_head == NULL) + || (msgq_head->msg_check_flag != ETOS_MSG_CHECK_FLAG)) { + return ETOS_INVALID_PARAM; + } + + /*clear msgq*/ + etos_enter_critical(); + + if (etos_sched_get_task_state(msgq_head->recv_task, &recv_task_state)) { + xlogw(LOG_MODULE_ETOS, "get task state error\n"); + } else { + if (recv_task_state & ETOS_TASK_PENDING_MSG) { + /*task is waiting for message*/ + etos_exit_critical(); + return ETOS_NOT_SUPPORT; + } + } + + while (!list_is_empty(&msgq_head->list)) { //not empty, it has msg + entry = list_dequeue(&msgq_head->list); + msgq_buf = list_entry(entry, etos_msgq_buf_t, list); + if (msgq_buf) { + free(msgq_buf); //free buf + } + } + free(msgq_head); // free head + + etos_exit_critical(); + + return ETOS_RET_OK; +} + + + +/** + * get a buffer. + * get a message queue buffer which length is len + * the buffer is the message content buffer to be send + * user fill the buffer and send to target task + * + * @param[in] msg_handle + * @param[in] len buffer length + * + * @return the message buffer pointer + * @retval other success + * @retval 0 fail + * + * @note it may be called before etos_msgq_send() + * @see etos_msgq_release_buf() + * @authors deeve + * @date 2015/4/14 + */ +u8 *etos_msgq_get_buf(etos_msg_handle msg_handle, u32 len) +{ + etos_msgq_buf_t *msgq_buf; + etos_msgq_head_t *msgq_head = (etos_msgq_head_t *)msg_handle; + + if ((msgq_head == NULL) || (len == 0) + || (msgq_head->msg_check_flag != ETOS_MSG_CHECK_FLAG)) { + return NULL; + } + + msgq_buf = (etos_msgq_buf_t *)malloc(len + sizeof(etos_msgq_buf_t)); + if (msgq_buf == NULL) { + return NULL; + } + + msgq_buf->msg_check_flag = ETOS_MSG_CHECK_FLAG; + + xlogi(LOG_MODULE_ETOS, "msg_get_buf: handle=0x%x len=%d\r\n", msg_handle, len); + + return msgq_buf->msg_data; +} + + + +/** + * release a buffer. + * release a message queue buffer which is got from etos_msgq_get_buf() + * + * @param[in] msg_handle + * @param[in] msg_buf which is returned by etos_msgq_get_buf() + * + * @return + * @retval 0 success + * @retval other fail + * + * @note it may be called after etos_msgq_recv() + * @see etos_msgq_get_buf() + * @authors deeve + * @date 2015/4/14 + */ +s32 etos_msgq_release_buf(etos_msg_handle msg_handle, u8 *msg_buf) +{ + etos_msgq_buf_t *msgq_buf; + etos_msgq_head_t *msgq_head = (etos_msgq_head_t *)msg_handle; + + if ((msgq_head == NULL) + || (msgq_head->msg_check_flag != ETOS_MSG_CHECK_FLAG) + || (msg_buf == NULL)) { + return ETOS_INVALID_PARAM; + } + + /*根据msg_data的指针获取etos_msgq_buf_t的指针*/ + msgq_buf = list_entry(msg_buf, etos_msgq_buf_t, msg_data); + if (msgq_buf->msg_check_flag != ETOS_MSG_CHECK_FLAG) { + return ETOS_INVALID_PARAM; + } + + xlogi(LOG_MODULE_ETOS, "release buf: handle=0x%x buf=0x%x\r\n", msg_handle, (u32)(msgq_buf->msg_data)); + + + //INIT_LIST_HEAD(&msgq_buf->list); //have done in recv list_dequeue + free(msgq_buf); + + return ETOS_RET_OK; +} + + + +/** + * send a message queue buffer. + * send a message queue buffer to the task which is wait to receive massge queue + * + * @param[in] msg_handle + * @param[in] msg_buf which is returned by etos_msgq_get_buf() + * + * @return + * @retval 0 success + * @retval other fail + * + * @note none + * @see etos_msgq_recv() + * @authors deeve + * @date 2015/4/14 + */ +s32 etos_msgq_send(etos_msg_handle msg_handle, u8 *msg_buf) +{ + etos_msgq_buf_t *msgq_buf; + etos_msgq_head_t *msgq_head = (etos_msgq_head_t *)msg_handle; + etos_init_critical(); + + if ((msgq_head == NULL) + || (msgq_head->msg_check_flag != ETOS_MSG_CHECK_FLAG) + || (msg_buf == NULL)) { + return ETOS_INVALID_PARAM; + } + + /* 根据msg_data的指针获取etos_msgq_buf_t的指针 */ + msgq_buf = list_entry(msg_buf, etos_msgq_buf_t, msg_data); + if (msgq_buf->msg_check_flag != ETOS_MSG_CHECK_FLAG) { + return ETOS_RET_FAIL; + } + + if (etos_intr_in_isr()) { + msgq_buf->send_task = ETOS_INTR_VIRTUAL_TASK_HANDLE; + } else { + msgq_buf->send_task = etos_sched_get_current_task(); + } + + xlogi(LOG_MODULE_ETOS, "msg_send: handle=0x%x buf=0x%x\r\n", msg_handle, (u32)msg_buf); + + etos_enter_critical(); + + list_add_tail(&msgq_buf->list, &msgq_head->list); + etos_sched_resume_task(msgq_head->recv_task, ETOS_TASK_PENDING_MSG); + + etos_exit_critical(); + + return ETOS_RET_OK; +} + + + +/** + * send a message queue buffer. + * send a message queue buffer to the task which is wait to receive massge queue + * it is called in a disable interrupt context + * + * @param[in] msg_handle + * @param[in] msg_buf which is returned by etos_msgq_get_buf() + * + * @return + * @retval 0 success + * @retval other fail + * + * @note none + * @see etos_msgq_recv() + * @authors deeve + * @date 2015/4/14 + */ +s32 etos_msgq_send_idic(etos_msg_handle msg_handle, u8 *msg_buf) +{ + etos_msgq_buf_t *msgq_buf; + etos_msgq_head_t *msgq_head = (etos_msgq_head_t *)msg_handle; + + if ((msgq_head == NULL) + || (msgq_head->msg_check_flag != ETOS_MSG_CHECK_FLAG) + || (msg_buf == NULL)) { + return ETOS_INVALID_PARAM; + } + + /* 根据msg_data的指针获取etos_msgq_buf_t的指针 */ + msgq_buf = list_entry(msg_buf, etos_msgq_buf_t, msg_data); + if (msgq_buf->msg_check_flag != ETOS_MSG_CHECK_FLAG) { + return ETOS_RET_FAIL; + } + + if (etos_intr_in_isr()) { + msgq_buf->send_task = ETOS_INTR_VIRTUAL_TASK_HANDLE; + } else { + msgq_buf->send_task = etos_sched_get_current_task(); + } + + xlogi(LOG_MODULE_ETOS, "msg_send: handle=0x%x buf=0x%x\r\n", msg_handle, (u32)msg_buf); + + list_add_tail(&msgq_buf->list, &msgq_head->list); + etos_sched_resume_task_idic(msgq_head->recv_task, ETOS_TASK_PENDING_MSG); + + return ETOS_RET_OK; +} + + + +/** + * receive a message queue buffer. + * receive a message queue buffer, maybe it will cause task reschedule when + * there is no message queue buffert to be received + * do not call this API in an interrupt context + * + * @param[in] msg_handle + * @param[out] msg_buf_ptr output message queue buffer + * @param[out] send_task output send message queue buffer task + * it equal ETOS_INTR_VIRTUAL_TASK_HANDLE when send message in ISR + * + * @return + * @retval 0 success + * @retval other fail + * + * @note it will be blocking when there is no message buffer to be received + * @see etos_msgq_send() + * @authors deeve + * @date 2015/4/14 + */ +s32 etos_msgq_recv(etos_msg_handle msg_handle, u8 **msg_buf_ptr, etos_task_handle *send_task) +{ + list_t *entry; + etos_msgq_buf_t *msgq_buf; + etos_msgq_head_t *msgq_head = (etos_msgq_head_t *)msg_handle; + etos_init_critical(); + + if ((msgq_head == NULL) + || (msgq_head->msg_check_flag != ETOS_MSG_CHECK_FLAG) + || (msg_buf_ptr == NULL)) { + return ETOS_INVALID_PARAM; + } + + if (etos_intr_in_isr()) { + xlogf(LOG_MODULE_ETOS, "can not recv message in ISR\r\n"); + } + + msgq_head->recv_task = etos_sched_get_current_task(); + + while (1) { + if (list_is_empty(&msgq_head->list)) { + /*pending itself becasue of message*/ + etos_sched_pending_task(msgq_head->recv_task, ETOS_TASK_PENDING_MSG); + } else { + etos_enter_critical(); + entry = list_dequeue(&msgq_head->list); + if (entry) { + msgq_buf = list_entry(entry, etos_msgq_buf_t, list); + etos_exit_critical(); + break; + } else { + etos_exit_critical(); + continue; + } + } + } + + ASSERT(msgq_buf->msg_check_flag == ETOS_MSG_CHECK_FLAG); + + xlogi(LOG_MODULE_ETOS, "msg_recv: handle=0x%x buf=0x%x\r\n", msg_handle, (u32)(msgq_buf->msg_data)); + + if (send_task) { + *send_task = msgq_buf->send_task; + } + + *msg_buf_ptr = msgq_buf->msg_data; + + return ETOS_RET_OK; +} + + + +/** + * receive a message queue buffer. + * receive a message queue buffer, it won't be blocking when + * there is no message queue buffert to be received, instead, it output NULL buffer pointer + * do not call this API in an interrupt context + * + * @param[in] msg_handle + * @param[out] msg_buf_ptr output message queue buffer + * @param[out] send_task output send message queue buffer task + * it equal ETOS_INTR_VIRTUAL_TASK_HANDLE when send message in ISR + * + * @return + * @retval 0 success + * @retval other fail + * + * @note it is a non-blocking API of etos_msgq_recv() + * @see etos_msgq_send() + * @authors deeve + * @date 2015/4/14 + */ +s32 etos_msgq_recv_no_block(etos_msg_handle msg_handle, u8 **msg_buf_ptr, etos_task_handle *send_task) +{ + list_t *entry; + etos_msgq_buf_t *msgq_buf; + etos_msgq_head_t *msgq_head = (etos_msgq_head_t *)msg_handle; + etos_init_critical(); + + if ((msgq_head == NULL) + || (msgq_head->msg_check_flag != ETOS_MSG_CHECK_FLAG) + || (msg_buf_ptr == NULL)) { + return ETOS_INVALID_PARAM; + } + + if (etos_intr_in_isr()) { + xlogf(LOG_MODULE_ETOS, "can not recv message in ISR\r\n"); + } + + msgq_head->recv_task = etos_sched_get_current_task(); + + if (list_is_empty(&msgq_head->list)) { + *msg_buf_ptr = NULL; + if (send_task) { + send_task = 0; + } + return ETOS_RET_OK; + } else { + etos_enter_critical(); + entry = list_dequeue(&msgq_head->list); + msgq_buf = list_entry(entry, etos_msgq_buf_t, list); + etos_exit_critical(); + } + + ASSERT(msgq_buf->msg_check_flag == ETOS_MSG_CHECK_FLAG); + + xlogi(LOG_MODULE_ETOS, "msg_recv: handle=0x%x buf=0x%x\r\n", msg_handle, (u32)(msgq_buf->msg_data)); + + if (send_task) { + *send_task = msgq_buf->send_task; + } + + *msg_buf_ptr = msgq_buf->msg_data; + + return ETOS_RET_OK; +} + + + +/* EOF */ + diff --git a/pool/shard000/C/0010253_task1.c b/pool/shard000/C/0010253_task1.c new file mode 100644 index 0000000000000000000000000000000000000000..20018a5b54741378102617dba476b9e424d6ddf9 --- /dev/null +++ b/pool/shard000/C/0010253_task1.c @@ -0,0 +1,49 @@ +#include +#include + +int is_prime(int num); + +int main() +{ + int result, j, k, num=0; + char c[10]; + scanf("%s", c); + j = strlen(c); + + for(k=0; k < j; k++) + { + if(c[k]<48 || c[k]>57) + { + printf("\n-1"); + return 0; + } + + } + num = atoi(c); + result = is_prime(num); + + printf("%d", result); + return 0; +} + +int is_prime(int num) +{ + int i, root; + root = sqrt(num); + + if(num == 1 || num == 0) + { + return 0; + } + + for(i = 2; i<=root; i++) + { + if(num%i == 0) + { + return 0; + } + } + + return 1; + +} diff --git a/pool/shard000/C/0010256_kern.c b/pool/shard000/C/0010256_kern.c new file mode 100644 index 0000000000000000000000000000000000000000..b4f9b7ad85d3c15a2ec8ab96332c1958ee51fe7c --- /dev/null +++ b/pool/shard000/C/0010256_kern.c @@ -0,0 +1,159 @@ +// +build darwin + +#include +#include "kern.h" + +enum { + Kern0Horizontal = 1 << 0, + Kern0Minimum = 1 << 1, + Kern0CrossStream = 1 << 2, + Kern0Override = 1 << 3, + Kern0FormatMask = 0xFF00, +}; + +KernKerningValue KernGet(const UInt8 *table, UniChar char0, UniChar char1) { + const UInt16 version = *(const UInt16 *)(table); + KernKerningValue kern; + + if (version == 0) { + kern = Kern0Get((const KernVersion0Header *) table, char0, char1); + } else { + kern = Kern1Get((const KernTableHeader *) table, char0, char1); + } + + return kern; +} + +KernKerningValue Kern0Get(const KernVersion0Header *header, UniChar char0, UniChar char1) { + KernKerningValue kern = 0; + KernKerningValue value = 0; + + const KernVersion0SubtableHeader *subtable = (const KernVersion0SubtableHeader *) (header->firstSubtable); + + for (int i = 0, n = ntohs(header->nTables); i != n; i++) { + const UInt16 version = ntohs(subtable->version); + const UInt16 coverage = ntohs(subtable->stInfo); + const UInt16 length = ntohs(subtable->length); + + if (version != 0) { + fprintf(stderr, "WARN: kerning is not supported for tables with version %u\n", version); + goto next; + } + + if (!(coverage & Kern0Horizontal)) { + fprintf(stderr, "WARN: kerning is not supported for `vertical` tables\n"); + goto next; + } + + if (coverage & Kern0CrossStream) { + fprintf(stderr, "WARN: kerning is not supported for tables `cross-stream` tables\n"); + goto next; + } + + if (coverage & Kern0Minimum) { + fprintf(stderr, "WARN: kerning is not supported for `minimum` tables\n"); + goto next; + } + + const UInt16 format = (coverage & Kern0FormatMask) >> 8; + + switch (format) { + case kKERNOrderedList: + value = KernOrderedListGet(&subtable->fsHeader.orderedList, char0, char1); + break; + + default: + fprintf(stderr, "WARN: kerning is not supported for tables with format %u\n", format); + goto next; + } + + if (coverage & Kern0Override) { + kern = value; + } else { + kern += value; + } + + next: + subtable = (const KernVersion0SubtableHeader *) (((const UInt8 *) subtable) + (length - 6)); + } + + return kern; +} + +KernKerningValue Kern1Get(const KernTableHeader *header, UniChar char0, UniChar char1) { + KernKerningValue kern = 0; + + const KernSubtableHeader *subtable = (const KernSubtableHeader *) (header->firstSubtable); + + for (int i = 0, n = ntohs(header->nTables); i != n; i++) { + const UInt16 length = ntohs(subtable->length); + const UInt16 coverage = subtable->stInfo; + + if (coverage & kKERNVertical) { + fprintf(stderr, "WARN: kerning is not supported for `vertical` tables\n"); + goto next; + } + + if (coverage & kKERNCrossStream) { + fprintf(stderr, "WARN: kerning is not supported for tables `cross-stream` tables\n"); + goto next; + } + + if (coverage & kKERNVariation) { + fprintf(stderr, "WARN: kerning is not supported for `variation` tables\n"); + goto next; + } + + const UInt16 format = coverage & kKERNFormatMask; + + switch (format) { + case kKERNOrderedList: + kern += KernOrderedListGet(&subtable->fsHeader.orderedList, char0, char1); + break; + + default: + fprintf(stderr, "WARN: kerning is not supported for tables with format %u\n", format); + goto next; + } + + next: + subtable = (const KernSubtableHeader *) (((const UInt8 *) subtable) + (length - 8)); + } + + return kern; +} + +KernKerningValue KernOrderedListGet(const KernOrderedListHeader *header, UniChar char0, UniChar char1) { + const KernOrderedListEntry *ptr = (const KernOrderedListEntry *) (header->table); + const KernOrderedListEntry *end = ptr + ntohs(header->nPairs); + const KernOrderedListEntry *mid = ptr + ((end - ptr) >> 1); + const UInt32 key = KernMakeKey(char0, char1); + + while (ptr != end) { + const UInt32 val = KernMakeKey(ntohs(mid->pair.left), ntohs(mid->pair.right)); + + if (key == val) { + return ntohs(mid->value); + } + + if ((end - ptr) == 1) { + break; + } + + if (key < val) { + end = mid; + } else { + ptr = mid; + } + + mid = ptr + ((end - ptr) >> 1); + } + + return 0; +} + +UInt32 KernMakeKey(UniChar left, UniChar right) { + const UInt32 a = left; + const UInt32 b = right; + return (a << 16) | b; +} diff --git a/pool/shard000/C/0010261_mfc.c b/pool/shard000/C/0010261_mfc.c new file mode 100644 index 0000000000000000000000000000000000000000..35222a6ca3c795a6c4433c66b8d97af1458dd7db --- /dev/null +++ b/pool/shard000/C/0010261_mfc.c @@ -0,0 +1,200 @@ +/* + * mfc codec encoding example application + * Andrzej Hajda + * + * MFC device. + * + * Copyright 2012 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include +#include +#include + +#include +#include +#include + +#define MAX_STREAM_SIZE (2*1024*1024) + +int align(int x, int a) +{ + return ((x + a - 1) / a) * a; +} + +/* runs v4l_deq_buf and correct ending conditions + according to MFC driver */ +int mfc_deq_buf(struct io_dev *dev, enum io_dir dir) +{ + int idx; + + struct mfc_priv *priv = dev->priv; + + idx = v4l_deq_buf_ext(dev, dir, &priv->last_frame_flags); + + if (dir == DIR_IN && dev->io[DIR_IN].state == FS_END + && dev->io[DIR_OUT].limit) + dev->io[DIR_OUT].limit = 0; + + return idx; +} + +struct io_dev_ops mfc_dev_ops = { .req_bufs = v4l_req_bufs, + .enq_buf = v4l_enq_buf, + .deq_buf = mfc_deq_buf, + .deq_event = v4l_deq_event, + .destroy = v4l_destroy + }; + +struct io_dev *mfc_create(char const *name) +{ + struct io_dev *dev; + int ret; + + dev = malloc(sizeof(*dev)); + memzero(*dev); + + dev->priv = malloc(sizeof(struct mfc_priv)); + + dev->ops = &mfc_dev_ops; + + dev->io[DIR_IN].type = IO_MMAP; + dev->io[DIR_OUT].type = IO_MMAP; + + dev->fd = open(name, O_RDWR, 0); + if (dev->fd < 0) { + err("Cannot open MFC device %s", name); + free(dev); + return NULL; + } + + struct v4l2_event_subscription ev_sub; + memzero(ev_sub); + ev_sub.type = V4L2_EVENT_EOS; + ret = ioctl(dev->fd, VIDIOC_SUBSCRIBE_EVENT, &ev_sub); + if (ret != 0) + err("Cannot subscribe EOS event for MFC"); + + dbg("MFC device %s opened with fd=%d", name, dev->fd); + + return dev; +} + +int mfc_set_codec(struct io_dev *dev, enum io_dir dir, int codec) +{ + struct v4l2_format fmt; + int ret; + + memzero(fmt); + fmt.type = io_dir_to_type(dir); + fmt.fmt.pix_mp.pixelformat = codec; + fmt.fmt.pix_mp.plane_fmt[0].sizeimage = MAX_STREAM_SIZE; + + ret = ioctl(dev->fd, VIDIOC_S_FMT, &fmt); + + return ret; +} + +/* set format with proper alignement */ +int mfc_set_fmt(struct io_dev *dev, enum io_dir dir, int width, int height) +{ + struct v4l2_format fmt; + int ret; + + memzero(fmt); + fmt.type = io_dir_to_type(dir); + fmt.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_NV12M; + fmt.fmt.pix_mp.width = width; + fmt.fmt.pix_mp.height = height; + + fmt.fmt.pix_mp.num_planes = 2; + fmt.fmt.pix_mp.plane_fmt[0].bytesperline = align(width, 128); + fmt.fmt.pix_mp.plane_fmt[0].sizeimage = align(width * height, 2048); + fmt.fmt.pix_mp.plane_fmt[1].bytesperline = align(width, 128); + fmt.fmt.pix_mp.plane_fmt[1].sizeimage = align(width * (height / 2), + 2048); + + ret = ioctl(dev->fd, VIDIOC_S_FMT, &fmt); + if (ret != 0) + err("Cannot set format on %d:%d", dev->fd, dir); + + return ret; +} + +int mfc_set_rate(struct io_dev *dev, int rate) +{ + struct v4l2_streamparm fps; + int ret; + + fps.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; + fps.parm.output.timeperframe.numerator = 1000; + fps.parm.output.timeperframe.denominator = rate; + + ret = ioctl(dev->fd, VIDIOC_S_PARM, &fps); + if (ret != 0) + err("Cannot set rate on %d", dev->fd); + + return ret; +} + +int mfc_set_mpeg_control(struct io_dev *dev, int id, int value) +{ + struct v4l2_ext_control ctrl; + struct v4l2_ext_controls ctrls; + int ret; + + ctrl.id = id; + // These aren't used for integer controls + ctrl.size = 0; + memzero(ctrl.reserved2); + + ctrls.ctrl_class = V4L2_CTRL_CLASS_MPEG; + ctrls.count = 1; + ctrls.controls = &ctrl; + + ret = ioctl(dev->fd, VIDIOC_G_EXT_CTRLS, &ctrls); + if (ret < 0) + err("Cannot get control %d on %d", id, dev->fd); + + dbg("Changing control %d from %d to %d", id, ctrl.value, value); + + ctrl.value = value; + ret = ioctl(dev->fd, VIDIOC_S_EXT_CTRLS, &ctrls); + if (ret < 0) + err("Cannot set control %d to %d on %d", id, value, dev->fd); + + return ret; +} + +int mfc_set_bitrate(struct io_dev *dev, int bitrate) +{ + struct v4l2_ext_control ctrl; + struct v4l2_ext_controls ctrls; + int ret; + + ctrl.id = V4L2_CID_MPEG_VIDEO_BITRATE; + ctrl.value = bitrate; + + ctrls.ctrl_class = V4L2_CTRL_CLASS_MPEG; + ctrls.count = 1; + ctrls.controls = &ctrl; + + ret = ioctl(dev->fd, VIDIOC_S_EXT_CTRLS, &ctrls); + if (ret < 0) + err("Cannot set bitrate on %d", dev->fd); + + return ret; +} diff --git a/pool/shard000/C/0010272_icsp.c b/pool/shard000/C/0010272_icsp.c new file mode 100644 index 0000000000000000000000000000000000000000..2a73468e01b019fcdc04b58c748a5091fa60a607 --- /dev/null +++ b/pool/shard000/C/0010272_icsp.c @@ -0,0 +1,176 @@ +/* + * Copyright 2011 Ytai Ben-Tsvi. All rights reserved. + * + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED "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 ARSHAN POURSOHI OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied. + */ + +#include "icsp.h" + +#include "byte_queue.h" +#include "pins.h" +#include "logging.h" +#include "features.h" +#include "HardwareProfile.h" +#include "timer.h" +#include "protocol.h" + +#define PGC_PIN 37 +#define PGD_PIN 38 +#define MCLR_PIN 36 + +#define RX_BUF_SIZE 64 +//#define TX_BUF_SIZE 64 + +#define PGD_OUT() PinSetTris(PGD_PIN, 0) +#define PGD_IN() PinSetTris(PGD_PIN, 1) + +// TODO: do not use delay + +static int num_rx_since_last_report; +static BYTE_QUEUE rx_queue; +//static BYTE_QUEUE tx_queue; +static BYTE rx_buffer[RX_BUF_SIZE]; +//static BYTE tx_buffer[TX_BUF_SIZE]; + +static void ClockBitsOut(BYTE b, int nbits) { + while (nbits-- > 0) { + PinSetLat(PGD_PIN, b & 1); + PinSetLat(PGC_PIN, 1); + PinSetLat(PGC_PIN, 0); + b >>= 1; + } +} + +static BYTE ClockBitsIn(int nbits) { + int i; + BYTE b = 0; + for (i = 0; i < nbits; ++i) { + PinSetLat(PGC_PIN, 1); + b |= (PinGetPort(PGD_PIN) << i); + PinSetLat(PGC_PIN, 0); + } + return b; +} + +static inline void ClockByteOut(BYTE b) { + ClockBitsOut(b, 8); +} + +static inline BYTE ClockByteIn() { + return ClockBitsIn(8); +} + +void ICSPEnter() { + log_printf("ICSPEnter()"); + // pulse reset + PinSetLat(MCLR_PIN, 1); + Delay10us(50); + PinSetLat(MCLR_PIN, 0); + DelayMs(1); + PGD_OUT(); + // enter code + ClockByteOut(0xB2); + ClockByteOut(0xC2); + ClockByteOut(0x12); + ClockByteOut(0x8A); + // mclr high + PinSetLat(MCLR_PIN, 1); + DelayMs(50); + // extra 5 bits for first SIX + ClockBitsOut(0, 5); +} + +void ICSPExit() { + log_printf("ICSPExit()"); + PinSetLat(MCLR_PIN, 0); + Delay10us(50); +} + +void ICSPSix(DWORD inst) { + log_printf("ICSPSix(0x%06lx)", inst); + PGD_OUT(); + ClockBitsOut(0, 4); + ClockByteOut(inst); + inst >>= 8; + ClockByteOut(inst); + inst >>= 8; + ClockByteOut(inst); +} + +void ICSPRegout() { + log_printf("ICSPRegout()"); + PGD_OUT(); + ClockBitsOut(1, 4); + PGD_IN(); + ClockByteIn(); // skip 8 bits + ByteQueuePushByte(&rx_queue, ClockByteIn()); + ByteQueuePushByte(&rx_queue, ClockByteIn()); +} + +void ICSPConfigure(int enable) { + log_printf("ICSPConfigure(%d)", enable); + if (enable) { + SetPinDigitalOut(PGC_PIN, 0, 0); + SetPinDigitalOut(PGD_PIN, 0, 0); + SetPinDigitalOut(MCLR_PIN, 0, 0); + // pull PGD up for reads. + PinSetCnpu(PGD_PIN, 1); + PinSetCnpd(PGD_PIN, 0); + + ByteQueueInit(&rx_queue, rx_buffer, RX_BUF_SIZE); + num_rx_since_last_report = RX_BUF_SIZE; + } else { + SetPinDigitalIn(PGC_PIN, 0); + SetPinDigitalIn(PGD_PIN, 0); + SetPinDigitalIn(MCLR_PIN, 0); + } +} + +static void ICSPReportRxStatus() { + int report; + report = num_rx_since_last_report; + num_rx_since_last_report = 0; + OUTGOING_MESSAGE msg; + msg.type = ICSP_REPORT_RX_STATUS; + msg.args.icsp_report_rx_status.bytes_to_add = report; + AppProtocolSendMessage(&msg); +} + +void ICSPTasks() { + while (ByteQueueSize(&rx_queue)) { + OUTGOING_MESSAGE msg; + msg.type = ICSP_RESULT; + ByteQueuePullToBuffer(&rx_queue, &msg.args.icsp_result.reg, 2); + num_rx_since_last_report += 2; + log_printf("ICSP read word: 0x%04x", msg.args.icsp_result.reg); + AppProtocolSendMessage(&msg); + } + if (num_rx_since_last_report > RX_BUF_SIZE / 2) { + ICSPReportRxStatus(); + } +} + + diff --git a/pool/shard000/C/0010275_crc.c b/pool/shard000/C/0010275_crc.c new file mode 100644 index 0000000000000000000000000000000000000000..2902f31afa871e0e58b10d9a270eb5ea43b687fb --- /dev/null +++ b/pool/shard000/C/0010275_crc.c @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2012 by Johnson Lee + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +#include +#include +#include + +#include "libmfs/crc.h" + +typedef struct +{ + struct crc_context super; + uint64_t crc_table[256]; +} crc_context_impl_t; + +const static uint64_t polynomial = 0x04C11DB7; + +static inline uint64_t libmfs_crc_context_check8(crc_context_t *self, uint8_t *data, uint64_t length) +{ + assert(self && *self); + + uint64_t i; + uint8_t crc = 0; + + while (length--) { + crc ^= *data++; + + for (i = 0; i < 8; i++) { + if (crc & 0x80) { + crc = (crc << 1) ^ 0x31; + } else { + crc <<= 1; + } + } + } + + return crc; +} + +static inline uint64_t libmfs_crc_context_check32(crc_context_t *self, uint8_t *data, uint64_t length) +{ + assert(self && *self); + + uint64_t i, accum; + crc_context_impl_t *impl = (crc_context_impl_t*) *self; + + for (i = 0, accum = -1; i < length; i++) { + accum = (accum << 8) ^ impl->crc_table[(accum >> 24) ^ *data++]; + } + + return accum; +} + +static inline void libmfs_crc_context_free(crc_context_t *self) +{ + assert(self && *self); + + free(*self); + *self = NULL; +} + +static inline void libmfs_crc_context_init(crc_context_impl_t *impl) +{ + uint64_t i, j, data, accum; + + for (i = 0; i < 256; i++) { + data = i << 24; + + for (j = accum = 0; j < 8; j++) { + if ((data ^ accum) & 0x80000000) { + accum = (accum << 1) ^ polynomial; + } else { + accum <<= 1; + } + + data <<= 1; + } + + impl->crc_table[i] = accum; + } +} + +crc_context_t crc_context_new(void) +{ + const static struct crc_context ks_crc_context = { + check8 : libmfs_crc_context_check8, + check32 : libmfs_crc_context_check32, + free : libmfs_crc_context_free, + }; + + crc_context_impl_t *impl = calloc(1, sizeof(crc_context_impl_t)); + + if (!impl) { + // TODO + return NULL; + } + + memcpy(&impl->super, &ks_crc_context, sizeof(struct crc_context)); + libmfs_crc_context_init(impl); + + return &impl->super; +} + diff --git a/pool/shard000/C/0010278_lapacke_spftrs_work.c b/pool/shard000/C/0010278_lapacke_spftrs_work.c new file mode 100644 index 0000000000000000000000000000000000000000..e62467035e6762d17098188e39e5b37531846331 --- /dev/null +++ b/pool/shard000/C/0010278_lapacke_spftrs_work.c @@ -0,0 +1,92 @@ +/***************************************************************************** + Copyright (c) 2014, Intel Corp. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of Intel Corporation nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + THE POSSIBILITY OF SUCH DAMAGE. +***************************************************************************** +* Contents: Native middle-level C interface to LAPACK function spftrs +* Author: Intel Corporation +* Generated November 2015 +*****************************************************************************/ + +#include "lapacke_utils.h" + +lapack_int LAPACKE_spftrs_work( int matrix_layout, char transr, char uplo, + lapack_int n, lapack_int nrhs, const float* a, + float* b, lapack_int ldb ) +{ + lapack_int info = 0; + if( matrix_layout == LAPACK_COL_MAJOR ) { + /* Call LAPACK function and adjust info */ + LAPACK_spftrs( &transr, &uplo, &n, &nrhs, a, b, &ldb, &info ); + if( info < 0 ) { + info = info - 1; + } + } else if( matrix_layout == LAPACK_ROW_MAJOR ) { + lapack_int ldb_t = MAX(1,n); + float* b_t = NULL; + float* a_t = NULL; + /* Check leading dimension(s) */ + if( ldb < nrhs ) { + info = -8; + LAPACKE_xerbla( "LAPACKE_spftrs_work", info ); + return info; + } + /* Allocate memory for temporary array(s) */ + b_t = (float*)LAPACKE_malloc( sizeof(float) * ldb_t * MAX(1,nrhs) ); + if( b_t == NULL ) { + info = LAPACK_TRANSPOSE_MEMORY_ERROR; + goto exit_level_0; + } + a_t = (float*) + LAPACKE_malloc( sizeof(float) * ( MAX(1,n) * MAX(2,n+1) ) / 2 ); + if( a_t == NULL ) { + info = LAPACK_TRANSPOSE_MEMORY_ERROR; + goto exit_level_1; + } + /* Transpose input matrices */ + LAPACKE_sge_trans( matrix_layout, n, nrhs, b, ldb, b_t, ldb_t ); + LAPACKE_spf_trans( matrix_layout, transr, uplo, n, a, a_t ); + /* Call LAPACK function and adjust info */ + LAPACK_spftrs( &transr, &uplo, &n, &nrhs, a_t, b_t, &ldb_t, &info ); + if( info < 0 ) { + info = info - 1; + } + /* Transpose output matrices */ + LAPACKE_sge_trans( LAPACK_COL_MAJOR, n, nrhs, b_t, ldb_t, b, ldb ); + /* Release memory and exit */ + LAPACKE_free( a_t ); +exit_level_1: + LAPACKE_free( b_t ); +exit_level_0: + if( info == LAPACK_TRANSPOSE_MEMORY_ERROR ) { + LAPACKE_xerbla( "LAPACKE_spftrs_work", info ); + } + } else { + info = -1; + LAPACKE_xerbla( "LAPACKE_spftrs_work", info ); + } + return info; +} diff --git a/pool/shard000/C/0010307_http.c b/pool/shard000/C/0010307_http.c new file mode 100644 index 0000000000000000000000000000000000000000..dbda9fab979a0964b9630fe87fe4096f74e9b47f --- /dev/null +++ b/pool/shard000/C/0010307_http.c @@ -0,0 +1,279 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +uint32_t +http_create( + HTTP** http_ptr + ) +{ + uint32_t r = 0; + HTTP* http = NULL; + + do { + + http = (HTTP*)mem_alloc(sizeof(HTTP)); + + if (!http){ + + LOG_ERROR("Failed to allocate memory for http."); + + break; + + } + + http->hdrs_ptr = http->raw_hdrs; + + http->more_data = true; + + *http_ptr = http; + + r = 1; + + } while (false); + + return r; +} + +uint32_t +http_destroy( + HTTP* http + ) +{ + uint32_t r = 0; + + do { + + if (!http) break; + + if (http->cntnt) mem_free(http->cntnt); + + mem_free(http); + + r = 1; + + } while (false); + + return r; +} + +uint32_t +http_parse( + HTTP* http, + char* buf, + uint32_t buf_len + ) +{ + uint32_t r = 0; + uint32_t rem_len = 0; + uint32_t copy_len = 0; + char* p = NULL; + + do { + + if (!http || !buf || !buf_len) break; + + p = buf; + + while (http->more_data && buf_len) { + + if (!http->hdrs_rcvd) { + + rem_len = sizeof(http->raw_hdrs) - (http->hdrs_ptr - http->raw_hdrs); + + copy_len = (rem_len > buf_len)?buf_len:rem_len; + + memcpy(http->hdrs_ptr, p, copy_len); + + // Move current buffer pointer to amount of copied bytes. + + http->hdrs_ptr += copy_len; + + // Check if all headers received, + // for now no content handling just headers. + + if (strstr(http->raw_hdrs, "\x0d\x0a\x0d\x0a")){ + + http->hdrs_rcvd = true; + + sscanf(http->raw_hdrs, "Content-length: %d", &http->cntnt_len); + + if (http->cntnt_len) { + + // Need to receive content. + + http->cntnt = (char*)mem_alloc(http->cntnt_len); + + if (!http->cntnt){ + + LOG_ERROR("Failed to allocate memeory for content."); + + break; + + } + + http->cntnt_rcvd = 0; + + } else { + + // No content attached. + + http->more_data = false; + + } + + } + + } else { + + if (http->cntnt_len){ + + copy_len = http->cntnt_len - http->cntnt_rcvd; + + copy_len = (buf_len > copy_len)?copy_len:buf_len; + + if (copy_len){ + + memcpy(http->cntnt, p, copy_len); + + } + + http->cntnt_rcvd += copy_len; + + if (!http->cntnt_rcvd) http->more_data = false; + + } + + } + + buf_len -= copy_len; + + p += copy_len; + + } + + r = 1; + + } while (false); + + return r; +} + +uint32_t +http_more_data( + HTTP* http + ) +{ + uint32_t r = 0; + + do { + + if (!http) break; + + if (!http->more_data) break; + + r = 1; + + } while (false); + + return r; +} + +uint32_t +http_emit_get_request( + char* location, + char* buf, + uint32_t* buf_len_ptr + ) +{ + uint32_t r = 0; + uint32_t buf_len = 0; + uint32_t req_len = 0; + static char get[] = "GET "; + static char http[] = " HTTP/1.1\r\n\r\n"; + + do { + + if (!location || !buf_len_ptr) break; + + req_len = strlen(get) + strlen(location) + strlen(http); + + buf_len = *buf_len_ptr; + + if (buf_len < req_len){ + + *buf_len_ptr = req_len + 1; + + LOG_DEBUG("Buffer for request not big enough."); + + break; + + } + + strcpy(buf, get); + + strcat(buf, location); + + strcat(buf, http); + + *buf_len_ptr = req_len; + + r = 1; + + } while (false); + + return r; +} + +uint32_t +http_get_content( + HTTP* http, + char** cntnt_ptr, + uint32_t* cntnt_len_ptr + ) +{ + uint32_t r = 0; + + do { + + if (!http || !http->cntnt_len) break; + + *cntnt_ptr = http->cntnt; + + *cntnt_len_ptr = http->cntnt_len; + + r = 1; + + } while (false); + + return r; +} + +uint32_t +http_get_raw_headers( + HTTP* http, + char** raw_hdrs_ptr, + uint32_t* raw_hdrs_len + ) +{ + uint32_t r = 0; + + do { + + if (!http || !http->hdrs_rcvd) break; + + *raw_hdrs_ptr = http->raw_hdrs; + + *raw_hdrs_len = strlen(http->raw_hdrs); + + r = 1; + + } while (false); + + return r; +} diff --git a/pool/shard000/C/0010320_match.c b/pool/shard000/C/0010320_match.c new file mode 100644 index 0000000000000000000000000000000000000000..1b58605f0e26bdb616fe4e6296662f8f9edf1694 --- /dev/null +++ b/pool/shard000/C/0010320_match.c @@ -0,0 +1,39 @@ +/** + * @file + * @brief + * + * @date 13.03.12 + * @author Alexander Kalmuk + */ + + +#include + +#include +#include + +#include +#include +#include +#include + +#define NET_NODES_CNT 0x10 + +OBJALLOC_DEF(matcher_nodes, struct net_node_matcher, NET_NODES_CNT); + +int matcher_free(net_node_t node) { + net_node_matcher_t m = (net_node_matcher_t) node; + + objfree(&matcher_nodes, m); + + return 0; +} + +net_node_t matcher_alloc(void) { + net_node_matcher_t matcher = objalloc(&matcher_nodes); + + INIT_LIST_HEAD(&matcher->match_rx_rules); + INIT_LIST_HEAD(&matcher->match_tx_rules); + + return (net_node_t) matcher; +} diff --git a/pool/shard000/C/0010337_subrequests.c b/pool/shard000/C/0010337_subrequests.c new file mode 100644 index 0000000000000000000000000000000000000000..636338138c9632060305c21b2a23989135d2d59e --- /dev/null +++ b/pool/shard000/C/0010337_subrequests.c @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2011-2012 Yaroslav Stavnichiy + * + * This file is part of NXWEB. + * + * NXWEB is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License + * as published by the Free Software Foundation, either version 3 + * of the License, or (at your option) any later version. + * + * NXWEB is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with NXWEB. If not, see . + */ + +#include "nxweb/nxweb.h" + +#include + +static nxweb_result subreq_on_request(nxweb_http_server_connection* conn, nxweb_http_request* req, nxweb_http_response* resp) { + nxweb_set_response_content_type(resp, "text/html"); + + nxweb_composite_stream* cs=nxweb_composite_stream_init(conn, req); + nxweb_composite_stream_append_bytes(cs, "[test1]", sizeof("[test1]")-1); + int fd=open("www/root/index.htm", O_RDONLY|O_NONBLOCK); + nxweb_composite_stream_append_fd(cs, fd, 0, 15); // fd will be auto-closed + nxweb_composite_stream_append_subrequest(cs, 0, "/8777/"); + nxweb_composite_stream_append_bytes(cs, "[test2]", sizeof("[test2]")-1); + nxweb_composite_stream_close(cs); + + nxweb_composite_stream_start(cs, resp); + + return NXWEB_OK; +} + +NXWEB_DEFINE_HANDLER(subreq, .on_request=subreq_on_request, .flags=NXWEB_HANDLE_ANY); + +static nxweb_result curtime_on_request(nxweb_http_server_connection* conn, nxweb_http_request* req, nxweb_http_response* resp) { + nxweb_set_response_content_type(resp, "text/html"); + + resp->last_modified=nxe_get_current_http_time(conn->tdata->loop); + const char* max_age_str=nxweb_get_request_parameter(req, "max_age"); + int max_age=0; + if (max_age_str) { + max_age=atoi(max_age_str); + resp->max_age=max_age; + } + + nxweb_response_append_str(resp, nxe_get_current_http_time_str(conn->tdata->loop)); + nxweb_response_append_str(resp, " [max-age="); + nxweb_response_append_uint(resp, max_age); + nxweb_response_append_str(resp, "]"); + + return NXWEB_OK; +} + +static nxweb_result curtime_generate_cache_key(nxweb_http_server_connection* conn, nxweb_http_request* req, nxweb_http_response* resp) { + if (!req->get_method || req->content_length) return NXWEB_OK; // do not cache POST requests, etc. + nxb_start_stream(req->nxb); + _nxb_append_encode_file_path(req->nxb, req->host); + if (conn->secure) nxb_append_str(req->nxb, "_s"); + _nxb_append_encode_file_path(req->nxb, req->uri); + nxb_append_char(req->nxb, '\0'); + resp->cache_key=nxb_finish_stream(req->nxb, 0); + return NXWEB_OK; +} + +NXWEB_DEFINE_HANDLER(curtime, .on_request=curtime_on_request, + .on_generate_cache_key=curtime_generate_cache_key, + .flags=NXWEB_HANDLE_GET|NXWEB_PARSE_PARAMETERS); + + +#ifdef WITH_IMAGEMAGICK + +static nxweb_result captcha_on_request(nxweb_http_server_connection* conn, nxweb_http_request* req, nxweb_http_response* resp) { + nxweb_set_response_content_type(resp, "text/html"); + nxweb_add_response_header(resp, "X-NXWEB-Draw", "7425"); + return NXWEB_OK; +} + +NXWEB_DEFINE_HANDLER(captcha, .on_request=captcha_on_request, + .flags=NXWEB_HANDLE_GET|NXWEB_PARSE_PARAMETERS); + +#endif diff --git a/pool/shard000/C/0010353_rt2x00firmware.c b/pool/shard000/C/0010353_rt2x00firmware.c new file mode 100644 index 0000000000000000000000000000000000000000..6cd44f718bf8f4d535d4a5841b823ab30e191551 --- /dev/null +++ b/pool/shard000/C/0010353_rt2x00firmware.c @@ -0,0 +1,130 @@ +/* + Copyright (C) 2004 - 2009 Ivo van Doorn + Copyright (C) 2004 - 2009 Gertjan van Wingerde + + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the + Free Software Foundation, Inc., + 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +/* + Module: rt2x00lib + Abstract: rt2x00 firmware loading routines. + */ + +#include +#include + +#include "rt2x00.h" +#include "rt2x00lib.h" + +static int rt2x00lib_request_firmware(struct rt2x00_dev *rt2x00dev) +{ + struct device *device = wiphy_dev(rt2x00dev->hw->wiphy); + const struct firmware *fw; + char *fw_name; + int retval; + + /* + * Read correct firmware from harddisk. + */ + fw_name = rt2x00dev->ops->lib->get_firmware_name(rt2x00dev); + if (!fw_name) { + ERROR(rt2x00dev, + "Invalid firmware filename.\n" + "Please file bug report to %s.\n", DRV_PROJECT); + return -EINVAL; + } + + INFO(rt2x00dev, "Loading firmware file '%s'.\n", fw_name); + + retval = request_firmware(&fw, fw_name, device); + if (retval) + return retval; + + if (!fw || !fw->size || !fw->data) { + ERROR(rt2x00dev, "Failed to read Firmware.\n"); + release_firmware(fw); + return -ENOENT; + } + + INFO(rt2x00dev, "Firmware detected - version: %d.%d.\n", + fw->data[fw->size - 4], fw->data[fw->size - 3]); + snprintf(rt2x00dev->hw->wiphy->fw_version, + sizeof(rt2x00dev->hw->wiphy->fw_version), "%d.%d", + fw->data[fw->size - 4], fw->data[fw->size - 3]); + + retval = rt2x00dev->ops->lib->check_firmware(rt2x00dev, fw->data, fw->size); + switch (retval) { + case FW_OK: + break; + case FW_BAD_CRC: + ERROR(rt2x00dev, "Firmware checksum error.\n"); + goto exit; + case FW_BAD_LENGTH: + ERROR(rt2x00dev, + "Invalid firmware file length (len=%zu)\n", fw->size); + goto exit; + case FW_BAD_VERSION: + ERROR(rt2x00dev, + "Current firmware does not support detected chipset.\n"); + goto exit; + } + + rt2x00dev->fw = fw; + + return 0; + +exit: + release_firmware(fw); + + return -ENOENT; +} + +int rt2x00lib_load_firmware(struct rt2x00_dev *rt2x00dev) +{ + int retval; + + if (!test_bit(REQUIRE_FIRMWARE, &rt2x00dev->cap_flags)) + return 0; + + if (!rt2x00dev->fw) { + retval = rt2x00lib_request_firmware(rt2x00dev); + if (retval) + return retval; + } + + /* + * Send firmware to the device. + */ + retval = rt2x00dev->ops->lib->load_firmware(rt2x00dev, + rt2x00dev->fw->data, + rt2x00dev->fw->size); + + /* + * When the firmware is uploaded to the hardware the LED + * association status might have been triggered, for correct + * LED handling it should now be reset. + */ + rt2x00leds_led_assoc(rt2x00dev, false); + + return retval; +} + +void rt2x00lib_free_firmware(struct rt2x00_dev *rt2x00dev) +{ + release_firmware(rt2x00dev->fw); + rt2x00dev->fw = NULL; +} diff --git a/pool/shard000/C/0010360_test-13.c b/pool/shard000/C/0010360_test-13.c new file mode 100644 index 0000000000000000000000000000000000000000..13b090516219f2b355f80d917eeac47613137590 --- /dev/null +++ b/pool/shard000/C/0010360_test-13.c @@ -0,0 +1,66 @@ +/* Test condition attributes and pthread_cond_timedwait. */ + +#define _GNU_SOURCE + +#include +#include +#include +#include +#include +#include + +int +main (int argc, char **argv) +{ + error_t err; + int i; + pthread_condattr_t attr; + pthread_cond_t cond; + struct timespec ts; + pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; + struct timeval before, after; + int diff; + + err = pthread_condattr_init (&attr); + if (err) + error (1, err, "pthread_condattr_init"); + + err = pthread_condattr_getpshared (&attr, &i); + if (err) + error (1, err, "pthread_condattr_getpshared"); + assert (i == PTHREAD_PROCESS_PRIVATE); + + err = pthread_condattr_setpshared (&attr, PTHREAD_PROCESS_PRIVATE); + assert (err == 0); + + err = pthread_cond_init (&cond, &attr); + if (err) + error (1, err, "pthread_cond_init"); + + err = pthread_condattr_destroy (&attr); + if (err) + error (1, err, "pthread_condattr_destroy"); + + gettimeofday (&before, 0); + ts.tv_sec = before.tv_sec + 1; + ts.tv_nsec = before.tv_usec * 1000; + + printf ("Starting wait @ %d\n", (int) before.tv_sec); + + pthread_mutex_lock (&m); + err = pthread_cond_timedwait (&cond, &m, &ts); + + gettimeofday (&after, 0); + + printf ("End wait @ %d (err = %d)\n", (int) after.tv_sec, err); + + assert (err == ETIMEDOUT); + + diff = after.tv_sec * 1000000 + after.tv_usec + - before.tv_sec * 1000000 - before.tv_usec; + + if (diff < 900000 || diff > 1100000) + error (1, EGRATUITOUS, "pthread_cond_timedwait waited %d us", diff); + + return 0; +} diff --git a/pool/shard000/C/0010373_test3.c b/pool/shard000/C/0010373_test3.c new file mode 100644 index 0000000000000000000000000000000000000000..d9ae5208e99022d1cf74b272cf073279261f1030 --- /dev/null +++ b/pool/shard000/C/0010373_test3.c @@ -0,0 +1,55 @@ +/* $Header: /cvsroot/lesstif/lesstif/test/Xm/frame/test3.c,v 1.7 2001/05/15 13:29:23 amai Exp $ */ + +#include +#include + +#include +#include +#ifdef LESSTIF_VERSION +#include +#endif +Widget toplevel, + canvas, + canvas_frame; + + +int main(int argc, + char *argv[]) +{ + Arg wargs[100]; + int n = 0; + + toplevel = XtInitialize(argv[0], "test3", NULL, 0, &argc, argv); + + n = 0; + XtSetArg(wargs[n], XtNwidth, 500); n++; + XtSetArg(wargs[n], XtNheight, 500); n++; + XtSetArg(wargs[n], XtNy, 100); n++; + XtSetArg(wargs[n], XtNx, 200); n++; + + canvas_frame = XtCreateManagedWidget("canvas_frame", + xmFrameWidgetClass, toplevel, + wargs, n); + + canvas = XtCreateManagedWidget("canvas", xmPushButtonWidgetClass, + canvas_frame, NULL, 0); + + XtRealizeWidget(toplevel); +#ifdef LESSTIF_VERSION + printf("(IGNORE_IN_DIFF) PC: %d\n", Frame_ProcessingConstraints(canvas_frame)); +#endif +{ +static XtWidgetGeometry Expected[] = { + CWWidth | CWHeight , 506, 322, 500, 500, 0,0,0, /* canvas_frame */ + CWWidth | CWHeight | CWX | CWY, 1, 1, 498, 498, 0,0,0, /* canvas */ +}; +/* toplevel should be replaced with to correct applicationShell */ +PrintDetails(toplevel, Expected); +} + + LessTifTestMainLoop(toplevel); + + exit(0); +} + + diff --git a/pool/shard000/C/0010374_pinctrl-uniphier-core.c b/pool/shard000/C/0010374_pinctrl-uniphier-core.c new file mode 100644 index 0000000000000000000000000000000000000000..215b19ea0e901f98c441184d5240b02d696ed409 --- /dev/null +++ b/pool/shard000/C/0010374_pinctrl-uniphier-core.c @@ -0,0 +1,302 @@ +/* + * Copyright (C) 2015-2016 Socionext Inc. + * Author: Masahiro Yamada + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#include +#include +#include +#include +#include +#include +#include + +#include "pinctrl-uniphier.h" + +#define UNIPHIER_PINCTRL_PINMUX_BASE 0x1000 +#define UNIPHIER_PINCTRL_LOAD_PINMUX 0x1700 +#define UNIPHIER_PINCTRL_PUPDCTRL_BASE 0x1a00 +#define UNIPHIER_PINCTRL_IECTRL 0x1d00 + +static const char *uniphier_pinctrl_dummy_name = "_dummy"; + +static int uniphier_pinctrl_get_groups_count(struct udevice *dev) +{ + struct uniphier_pinctrl_priv *priv = dev_get_priv(dev); + + return priv->socdata->groups_count; +} + +static const char *uniphier_pinctrl_get_group_name(struct udevice *dev, + unsigned selector) +{ + struct uniphier_pinctrl_priv *priv = dev_get_priv(dev); + + if (!priv->socdata->groups[selector].name) + return uniphier_pinctrl_dummy_name; + + return priv->socdata->groups[selector].name; +} + +static int uniphier_pinmux_get_functions_count(struct udevice *dev) +{ + struct uniphier_pinctrl_priv *priv = dev_get_priv(dev); + + return priv->socdata->functions_count; +} + +static const char *uniphier_pinmux_get_function_name(struct udevice *dev, + unsigned selector) +{ + struct uniphier_pinctrl_priv *priv = dev_get_priv(dev); + + if (!priv->socdata->functions[selector]) + return uniphier_pinctrl_dummy_name; + + return priv->socdata->functions[selector]; +} + +static int uniphier_pinconf_input_enable_perpin(struct udevice *dev, + unsigned int pin, int enable) +{ + struct uniphier_pinctrl_priv *priv = dev_get_priv(dev); + unsigned reg; + u32 mask, tmp; + + reg = UNIPHIER_PINCTRL_IECTRL + pin / 32 * 4; + mask = BIT(pin % 32); + + tmp = readl(priv->base + reg); + if (enable) + tmp |= mask; + else + tmp &= ~mask; + writel(tmp, priv->base + reg); + + return 0; +} + +static int uniphier_pinconf_input_enable_legacy(struct udevice *dev, + unsigned int pin, int enable) +{ + struct uniphier_pinctrl_priv *priv = dev_get_priv(dev); + + /* + * Multiple pins share one input enable, per-pin disabling is + * impossible. + */ + if (!enable) + return -EINVAL; + + /* Set all bits instead of having a bunch of pin data */ + writel(U32_MAX, priv->base + UNIPHIER_PINCTRL_IECTRL); + + return 0; +} + +static int uniphier_pinconf_input_enable(struct udevice *dev, + unsigned int pin, int enable) +{ + struct uniphier_pinctrl_priv *priv = dev_get_priv(dev); + + if (priv->socdata->caps & UNIPHIER_PINCTRL_CAPS_PERPIN_IECTRL) + return uniphier_pinconf_input_enable_perpin(dev, pin, enable); + else + return uniphier_pinconf_input_enable_legacy(dev, pin, enable); +} + +#if CONFIG_IS_ENABLED(PINCONF) + +static const struct pinconf_param uniphier_pinconf_params[] = { + { "bias-disable", PIN_CONFIG_BIAS_DISABLE, 0 }, + { "bias-pull-up", PIN_CONFIG_BIAS_PULL_UP, 1 }, + { "bias-pull-down", PIN_CONFIG_BIAS_PULL_DOWN, 1 }, + { "bias-pull-pin-default", PIN_CONFIG_BIAS_PULL_PIN_DEFAULT, 1 }, + { "input-enable", PIN_CONFIG_INPUT_ENABLE, 1 }, + { "input-disable", PIN_CONFIG_INPUT_ENABLE, 0 }, +}; + +static int uniphier_pinconf_bias_set(struct udevice *dev, unsigned int pin, + unsigned int param, unsigned int arg) +{ + struct uniphier_pinctrl_priv *priv = dev_get_priv(dev); + unsigned int enable = 1; + unsigned int reg; + u32 mask, tmp; + + if (!(priv->socdata->caps & UNIPHIER_PINCTRL_CAPS_PUPD_SIMPLE)) + return -ENOTSUPP; + + switch (param) { + case PIN_CONFIG_BIAS_DISABLE: + enable = 0; + break; + case PIN_CONFIG_BIAS_PULL_UP: + case PIN_CONFIG_BIAS_PULL_DOWN: + if (arg == 0) /* total bias is not supported */ + return -EINVAL; + break; + case PIN_CONFIG_BIAS_PULL_PIN_DEFAULT: + if (arg == 0) /* configuration ignored */ + return 0; + default: + BUG(); + } + + reg = UNIPHIER_PINCTRL_PUPDCTRL_BASE + pin / 32 * 4; + mask = BIT(pin % 32); + + tmp = readl(priv->base + reg); + if (enable) + tmp |= mask; + else + tmp &= ~mask; + writel(tmp, priv->base + reg); + + return 0; +} + +static int uniphier_pinconf_set_one(struct udevice *dev, unsigned int pin, + unsigned int param, unsigned int arg) +{ + int ret; + + switch (param) { + case PIN_CONFIG_BIAS_DISABLE: + case PIN_CONFIG_BIAS_PULL_UP: + case PIN_CONFIG_BIAS_PULL_DOWN: + case PIN_CONFIG_BIAS_PULL_PIN_DEFAULT: + ret = uniphier_pinconf_bias_set(dev, pin, param, arg); + break; + case PIN_CONFIG_INPUT_ENABLE: + ret = uniphier_pinconf_input_enable(dev, pin, arg); + break; + default: + printf("unsupported configuration parameter %u\n", param); + return -EINVAL; + } + + return ret; +} + +static int uniphier_pinconf_group_set(struct udevice *dev, + unsigned int group_selector, + unsigned int param, unsigned int arg) +{ + struct uniphier_pinctrl_priv *priv = dev_get_priv(dev); + const struct uniphier_pinctrl_group *grp = + &priv->socdata->groups[group_selector]; + int i, ret; + + for (i = 0; i < grp->num_pins; i++) { + ret = uniphier_pinconf_set_one(dev, grp->pins[i], param, arg); + if (ret) + return ret; + } + + return 0; +} + +#endif /* CONFIG_IS_ENABLED(PINCONF) */ + +static void uniphier_pinmux_set_one(struct udevice *dev, unsigned pin, + int muxval) +{ + struct uniphier_pinctrl_priv *priv = dev_get_priv(dev); + unsigned reg, reg_end, shift, mask; + unsigned mux_bits = 8; + unsigned reg_stride = 4; + bool load_pinctrl = false; + u32 tmp; + + /* some pins need input-enabling */ + uniphier_pinconf_input_enable(dev, pin, 1); + + if (muxval < 0) + return; /* dedicated pin; nothing to do for pin-mux */ + + if (priv->socdata->caps & UNIPHIER_PINCTRL_CAPS_MUX_4BIT) + mux_bits = 4; + + if (priv->socdata->caps & UNIPHIER_PINCTRL_CAPS_DBGMUX_SEPARATE) { + /* + * Mode offset bit + * Normal 4 * n shift+3:shift + * Debug 4 * n shift+7:shift+4 + */ + mux_bits /= 2; + reg_stride = 8; + load_pinctrl = true; + } + + reg = UNIPHIER_PINCTRL_PINMUX_BASE + pin * mux_bits / 32 * reg_stride; + reg_end = reg + reg_stride; + shift = pin * mux_bits % 32; + mask = (1U << mux_bits) - 1; + + /* + * If reg_stride is greater than 4, the MSB of each pinsel shall be + * stored in the offset+4. + */ + for (; reg < reg_end; reg += 4) { + tmp = readl(priv->base + reg); + tmp &= ~(mask << shift); + tmp |= (mask & muxval) << shift; + writel(tmp, priv->base + reg); + + muxval >>= mux_bits; + } + + if (load_pinctrl) + writel(1, priv->base + UNIPHIER_PINCTRL_LOAD_PINMUX); +} + +static int uniphier_pinmux_group_set(struct udevice *dev, + unsigned group_selector, + unsigned func_selector) +{ + struct uniphier_pinctrl_priv *priv = dev_get_priv(dev); + const struct uniphier_pinctrl_group *grp = + &priv->socdata->groups[group_selector]; + int i; + + for (i = 0; i < grp->num_pins; i++) + uniphier_pinmux_set_one(dev, grp->pins[i], grp->muxvals[i]); + + return 0; +} + +const struct pinctrl_ops uniphier_pinctrl_ops = { + .get_groups_count = uniphier_pinctrl_get_groups_count, + .get_group_name = uniphier_pinctrl_get_group_name, + .get_functions_count = uniphier_pinmux_get_functions_count, + .get_function_name = uniphier_pinmux_get_function_name, + .pinmux_group_set = uniphier_pinmux_group_set, +#if CONFIG_IS_ENABLED(PINCONF) + .pinconf_num_params = ARRAY_SIZE(uniphier_pinconf_params), + .pinconf_params = uniphier_pinconf_params, + .pinconf_group_set = uniphier_pinconf_group_set, +#endif + .set_state = pinctrl_generic_set_state, +}; + +int uniphier_pinctrl_probe(struct udevice *dev, + struct uniphier_pinctrl_socdata *socdata) +{ + struct uniphier_pinctrl_priv *priv = dev_get_priv(dev); + fdt_addr_t addr; + + addr = devfdt_get_addr(dev->parent); + if (addr == FDT_ADDR_T_NONE) + return -EINVAL; + + priv->base = devm_ioremap(dev, addr, SZ_4K); + if (!priv->base) + return -ENOMEM; + + priv->socdata = socdata; + + return 0; +} diff --git a/pool/shard000/C/0010382_t-contains_arf.c b/pool/shard000/C/0010382_t-contains_arf.c new file mode 100644 index 0000000000000000000000000000000000000000..223040253cf41880deb13429a3fc8be503928774 --- /dev/null +++ b/pool/shard000/C/0010382_t-contains_arf.c @@ -0,0 +1,80 @@ +/* + Copyright (C) 2012 Fredrik Johansson + + This file is part of Arb. + + Arb is free software: you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License (LGPL) as published + by the Free Software Foundation; either version 2.1 of the License, or + (at your option) any later version. See . +*/ + +#include "arb.h" + +int main() +{ + slong iter; + flint_rand_t state; + + flint_printf("contains_arf...."); + fflush(stdout); + + flint_randinit(state); + + for (iter = 0; iter < 10000 * arb_test_multiplier(); iter++) + { + arb_t a; + arf_t b; + fmpq_t am, ar, bm, t; + int c1, c2; + + arb_init(a); + arf_init(b); + + fmpq_init(am); + fmpq_init(ar); + fmpq_init(bm); + fmpq_init(t); + + arb_randtest(a, state, 1 + n_randint(state, 500), 14); + arf_randtest(b, state, 1 + n_randint(state, 500), 14); + + arf_get_fmpq(am, arb_midref(a)); + mag_get_fmpq(ar, arb_radref(a)); + arf_get_fmpq(bm, b); + + c1 = arb_contains_arf(a, b); + + fmpq_sub(t, am, ar); + c2 = fmpq_cmp(t, bm) <= 0; + + fmpq_add(t, am, ar); + c2 = c2 && (fmpq_cmp(t, bm) >= 0); + + if (c1 != c2) + { + flint_printf("FAIL:\n\n"); + flint_printf("a = "); arb_print(a); flint_printf("\n\n"); + flint_printf("b = "); arf_print(b); flint_printf("\n\n"); + flint_printf("am = "); fmpq_print(am); flint_printf("\n\n"); + flint_printf("ar = "); fmpq_print(ar); flint_printf("\n\n"); + flint_printf("bm = "); fmpq_print(bm); flint_printf("\n\n"); + flint_printf("t = "); fmpq_print(t); flint_printf("\n\n"); + flint_printf("c1 = %d, c2 = %d\n\n", c1, c2); + flint_abort(); + } + + arb_clear(a); + arf_clear(b); + + fmpq_clear(am); + fmpq_clear(ar); + fmpq_clear(bm); + fmpq_clear(t); + } + + flint_randclear(state); + flint_cleanup(); + flint_printf("PASS\n"); + return EXIT_SUCCESS; +} diff --git a/pool/shard000/C/0010387_coffix.c b/pool/shard000/C/0010387_coffix.c new file mode 100644 index 0000000000000000000000000000000000000000..4f21cfc389950fdc1fd208d4fdd33a625ca10ad3 --- /dev/null +++ b/pool/shard000/C/0010387_coffix.c @@ -0,0 +1,162 @@ +/* + * %CopyrightBegin% + * + * Copyright Ericsson AB 1999-2011. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * %CopyrightEnd% + */ +/* +** This mini tool fixes an incompatibility between +** Microsoft's tools, who dont like the virtual size being put in +** the physical address field, but rely on the raw size field for +** sizing the ".bss" section. +** This fixes some of the problems with linking gcc compiled objects +** together with MSVC dito. +** +** Courtesy DJ Delorie for describing the COFF file format on +** http://www.delorie.com/djgpp/doc/coff/ +** The coff structures are fetched from Microsofts headers though. +*/ + +#include +#include +#include +#include + +#include +#include /* Structure definitions for PE (COFF) */ + +static int dump_edit(char *filename, int edit); +static int v_printf(char *format, ...); + + +char *progname; +int verbouse = 0; + +int main(int argc, char **argv) +{ + int findex = 1; + int edit = 0; + int ret; + + progname = argv[0]; + if (argc == 1) { + fprintf(stderr,"Format : %s [-e] [-v] \n", progname); + return 1; + } + for (findex = 1; + findex < argc && (*argv[findex] == '-' || *argv[findex] == '/'); + ++findex) + switch (argv[findex][1]) { + case 'e': + case 'E': + edit = 1; + break; + case 'v': + case 'V': + verbouse = 1; + default: + fprintf(stderr, "%s: unknown option %s\n", progname, argv[findex]); + break; + } + if (findex == argc) { + fprintf(stderr,"%s: No filenames given.\n", progname); + return 1; + } + for(; findex < argc; ++findex) + if ((ret = dump_edit(argv[findex],edit)) != 0) + return ret; + return 0; +} + +int dump_edit(char *filename, int edit) +{ + FILE *f = fopen(filename, (edit) ? "r+b" : "rb"); + IMAGE_FILE_HEADER filhdr; + IMAGE_SECTION_HEADER scnhdr; + int i; + + if (f == NULL) { + fprintf(stderr, "%s: cannot open %s.\n", progname, filename); + return 1; + } + + if (fread(&filhdr, sizeof(filhdr), 1, f) == 0) { + fprintf(stderr,"%s: Could not read COFF header from %s," + " is this a PE (COFF) file?\n", progname, filename); + fclose(f); + return 1; + } + v_printf("File: %s\n", filename); + v_printf("Magic number: 0x%08x\n", filhdr.Machine); + v_printf("Number of sections: %d\n",filhdr.NumberOfSections); + + if (fseek(f, (long) filhdr.SizeOfOptionalHeader, SEEK_CUR) != 0) { + fprintf(stderr,"%s: Could not read COFF optional header from %s," + " is this a PE (COFF) file?\n", progname, filename); + fclose(f); + return 1; + } + + for (i = 0; i < filhdr.NumberOfSections; ++i) { + if (fread(&scnhdr, sizeof(scnhdr), 1, f) == 0) { + fprintf(stderr,"%s: Could not read section header from %s," + " is this a PE (COFF) file?\n", progname, filename); + fclose(f); + return 1; + } + v_printf("Section %s:\n", scnhdr.Name); + v_printf("Physical address: 0x%08x\n", scnhdr.Misc.PhysicalAddress); + v_printf("Size: 0x%08x\n", scnhdr.SizeOfRawData); + if (scnhdr.Misc.PhysicalAddress != 0 && + scnhdr.SizeOfRawData == 0) { + printf("Section header %s in file %s will confuse MSC linker, " + "virtual size is 0x%08x and raw size is 0\n", + scnhdr.Name, filename, scnhdr.Misc.PhysicalAddress, + scnhdr.SizeOfRawData); + if (edit) { + scnhdr.SizeOfRawData = scnhdr.Misc.PhysicalAddress; + scnhdr.Misc.PhysicalAddress = 0; + if (fseek(f, (long) -((long)sizeof(scnhdr)), SEEK_CUR) != 0 || + fwrite(&scnhdr, sizeof(scnhdr), 1, f) == 0) { + fprintf(stderr,"%s: could not edit file %s.\n", + progname, filename); + fclose(f); + return 1; + } + printf("Edited object, virtual size is now 0, and " + "raw size is 0x%08x.\n", scnhdr.SizeOfRawData); + } else { + printf("Specify option '-e' to correct the problem.\n"); + } + } + } + fclose(f); + return 0; +} + + +static int v_printf(char *format, ...) +{ + va_list ap; + int ret = 0; + if (verbouse) { + va_start(ap, format); + ret = vfprintf(stdout, format, ap); + va_end(ap); + } + return ret; +} + diff --git a/pool/shard000/C/0010393_getaddrinfo_a.c b/pool/shard000/C/0010393_getaddrinfo_a.c new file mode 100644 index 0000000000000000000000000000000000000000..abac27d361cde4cbc04ed2cb4124c2dede3ab7cb --- /dev/null +++ b/pool/shard000/C/0010393_getaddrinfo_a.c @@ -0,0 +1,168 @@ +/* Copyright (C) 2001 Free Software Foundation, Inc. + This file is part of the GNU C Library. + Contributed by Ulrich Drepper , 2001. + + The GNU C Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The GNU C Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. */ + +#include +#include +#include +#include +#include + +#include "gai_misc.h" + + +/* We need this special structure to handle asynchronous I/O. */ +struct async_waitlist + { + int counter; + struct sigevent sigev; + struct waitlist list[0]; + }; + + +int +getaddrinfo_a (int mode, struct gaicb *list[], int ent, struct sigevent *sig) +{ + struct sigevent defsigev; + struct requestlist *requests[ent]; + int cnt; + volatile int total = 0; + int result = 0; + + /* Check arguments. */ + if (mode != GAI_WAIT && mode != GAI_NOWAIT) + { + __set_errno (EINVAL); + return EAI_SYSTEM; + } + + if (sig == NULL) + { + defsigev.sigev_notify = SIGEV_NONE; + sig = &defsigev; + } + + /* Request the mutex. */ + pthread_mutex_lock (&__gai_requests_mutex); + + /* Now we can enqueue all requests. Since we already acquired the + mutex the enqueue function need not do this. */ + for (cnt = 0; cnt < ent; ++cnt) + if (list[cnt] != NULL) + { + requests[cnt] = __gai_enqueue_request (list[cnt]); + + if (requests[cnt] != NULL) + /* Successfully enqueued. */ + ++total; + else + /* Signal that we've seen an error. `errno' and the error code + of the gaicb will tell more. */ + result = EAI_SYSTEM; + } + else + requests[cnt] = NULL; + + if (total == 0) + { + /* We don't have anything to do except signalling if we work + asynchronously. */ + + /* Release the mutex. We do this before raising a signal since the + signal handler might do a `siglongjmp' and then the mutex is + locked forever. */ + pthread_mutex_unlock (&__gai_requests_mutex); + + if (mode == GAI_NOWAIT) + __gai_notify_only (sig, + sig->sigev_notify == SIGEV_SIGNAL ? getpid () : 0); + + return result; + } + else if (mode == GAI_WAIT) + { + pthread_cond_t cond = PTHREAD_COND_INITIALIZER; + struct waitlist waitlist[ent]; + int oldstate; + + total = 0; + for (cnt = 0; cnt < ent; ++cnt) + if (requests[cnt] != NULL) + { + waitlist[cnt].cond = &cond; + waitlist[cnt].next = requests[cnt]->waiting; + waitlist[cnt].counterp = &total; + waitlist[cnt].sigevp = NULL; + waitlist[cnt].caller_pid = 0; /* Not needed. */ + requests[cnt]->waiting = &waitlist[cnt]; + ++total; + } + + /* Since `pthread_cond_wait'/`pthread_cond_timedwait' are cancelation + points we must be careful. We added entries to the waiting lists + which we must remove. So defer cancelation for now. */ + pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &oldstate); + + while (total > 0) + pthread_cond_wait (&cond, &__gai_requests_mutex); + + /* Now it's time to restore the cancelation state. */ + pthread_setcancelstate (oldstate, NULL); + + /* Release the conditional variable. */ + if (pthread_cond_destroy (&cond) != 0) + /* This must never happen. */ + abort (); + } + else + { + struct async_waitlist *waitlist; + + waitlist = (struct async_waitlist *) + malloc (sizeof (struct async_waitlist) + + (ent * sizeof (struct waitlist))); + + if (waitlist == NULL) + result = EAI_AGAIN; + else + { + pid_t caller_pid = sig->sigev_notify == SIGEV_SIGNAL ? getpid () : 0; + total = 0; + + for (cnt = 0; cnt < ent; ++cnt) + if (requests[cnt] != NULL) + { + waitlist->list[cnt].cond = NULL; + waitlist->list[cnt].next = requests[cnt]->waiting; + waitlist->list[cnt].counterp = &waitlist->counter; + waitlist->list[cnt].sigevp = &waitlist->sigev; + waitlist->list[cnt].caller_pid = caller_pid; + requests[cnt]->waiting = &waitlist->list[cnt]; + ++total; + } + + waitlist->counter = total; + waitlist->sigev = *sig; + } + } + + /* Release the mutex. */ + pthread_mutex_unlock (&__gai_requests_mutex); + + return result; +} diff --git a/pool/shard000/C/0010401_nhc_routing.c b/pool/shard000/C/0010401_nhc_routing.c new file mode 100644 index 0000000000000000000000000000000000000000..1c174023de42d1032dac0c1045870be9cce84dfd --- /dev/null +++ b/pool/shard000/C/0010401_nhc_routing.c @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* + * 6LoWPAN IPv6 Routing Header compression according to RFC6282 + */ + +#include "nhc.h" + +#define LOWPAN_NHC_ROUTING_IDLEN 1 +#define LOWPAN_NHC_ROUTING_ID_0 0xe2 +#define LOWPAN_NHC_ROUTING_MASK_0 0xfe + +static void routing_nhid_setup(struct lowpan_nhc *nhc) +{ + nhc->id[0] = LOWPAN_NHC_ROUTING_ID_0; + nhc->idmask[0] = LOWPAN_NHC_ROUTING_MASK_0; +} + +LOWPAN_NHC(nhc_routing, "RFC6282 Routing", NEXTHDR_ROUTING, 0, + routing_nhid_setup, LOWPAN_NHC_ROUTING_IDLEN, NULL, NULL); + +module_lowpan_nhc(nhc_routing); +MODULE_DESCRIPTION("6LoWPAN next header RFC6282 Routing compression"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard000/C/0010402_testraybsf.c b/pool/shard000/C/0010402_testraybsf.c new file mode 100644 index 0000000000000000000000000000000000000000..ddc32c5202dcc7ceb2572d3ca7358411ec098eaa --- /dev/null +++ b/pool/shard000/C/0010402_testraybsf.c @@ -0,0 +1,187 @@ + +#include +#include +#include +#include +#include + +#include "pkvaria.h" +#include "pknum.h" +#include "pkgeom.h" +#include "multibs.h" +#include "raybez.h" +#include "camera.h" +#include "psout.h" + +char fn[] = "testraybsf.ps"; + +int n = 3, m = 3; +int lknu = 10, lknv = 10; +float knots_u[11] = {-0.5, 0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 4.0, 4.0, 4.5}; +float knots_v[11] = {-0.5, 0.0, 0.0, 0.0, 1.0, 2.5, 2.5, 4.0, 4.0, 4.0, 4.5}; +point3f cpoints[] = + {{-3.0,-3.0,-0.5}, {-2.7,-3.0,-0.5}, {-1.5,-3.0,-0.5}, {0.0,-3.0,-0.5}, + {1.5,-3.0,-0.5}, {2.7,-3.0,-0.5}, {3.0,-3.0,-0.5}, + {-3.0,-2.7}, {-2.7,-2.7}, {-1.5,-2.7}, {0.0,-2.7}, {1.5,-2.7}, + {2.7,-2.7}, {3.0,-2.7}, + {-3.0,-1.5,0.1}, {-2.7,-1.5,0.1}, {-1.5,-1.5,0.1}, {0.0,-1.5,0.1}, + {1.5,-1.5,2.5}, {2.7,-1.5,0.1}, {3.0,-1.5,0.1}, + {-3.0,0.0,0.2}, {-2.7,0.0,0.2}, {-1.5,0.0,0.2}, {0.0,0.0,0.2}, + {1.5,0.0,0.2}, {2.7,0.0,0.2}, {3.0,0.0,0.2}, + {-3.0,1.5,0.1}, {-2.7,1.5,0.1}, {-1.5,1.5,0.1}, {0.0,1.5,0.1}, + {1.5,1.5,0.1}, {2.7,1.5,0.1}, {3.0,1.5,0.1}, + {-3.0,2.7}, {-2.7,2.7}, {-1.5,2.7}, {0.0,2.7}, {1.5,2.7}, {2.7,2.7}, + {3.0,2.7}, + {-3.0,3.0,-0.5}, {-2.7,3.0,-0.5}, {-1.5,3.0,-0.5}, {0.0,3.0,-0.5}, + {1.5,3.0,-0.5}, {2.7,3.0,-0.5}, {3.0,3.0,-0.5}}; + +#define WIDTH 640 +#define HEIGHT 480 + +CameraRecf CPos; +vector3f ld; + +BezPatchTreefp tree; + +static void SetCPos ( void ) +{ + CameraInitFramef ( &CPos, false, false, WIDTH, HEIGHT, 0, 0, 1.0, 4 ); + CameraInitPosf ( &CPos ); + SetPoint3f ( &CPos.position, -15.31251039605, -72.93132382473, 49.231894764605 ); + CPos.psi = 2.963570202665; + CPos.theta = 2.1560152051; + CPos.phi = 2.934640744727; + CPos.vd.persp.f = 10.0; + CameraSetMappingf ( &CPos ); +} /*SetCPos*/ + +static void SetLightDir ( void ) +{ + SetVector3f ( &ld, 0.5, 0.5, -1.0 ); + NormalizeVector3f ( &ld ); +} /*SetLightDir*/ + +static byte PixelColour ( ray3f *ray ) +{ +#define MAXLEVEL 16 +#define MAXINTERS 10 + RayObjectIntersf inters[MAXINTERS]; + int ninters, i, j; + float tmin; + float gray, g0, l0; + + rbez_FindRayBezPatchIntersf ( tree, ray, MAXLEVEL, MAXINTERS, + &ninters, inters ); + if ( ninters ) { + if ( ninters > 1 ) { + j = 0; + tmin = inters[0].t; + for ( i = 0; i < ninters; i++ ) + if ( inters[i].t < tmin ) { + tmin = inters[i].t; + j = i; + } + if ( j ) + inters[0] = inters[j]; + } + gray = 0.2; + l0 = DotProduct3f ( &ray->v, &inters[0].nv ); + g0 = DotProduct3f ( &ld, &inters[0].nv ); + if ( g0*l0 > 0.0 ) { + gray += 0.7*fabs ( g0 ); + if ( gray > 1.0 ) + gray = 1.0; + } + + return (byte)(255.0*gray); + } + else + return 160; + +#undef MAXINTERS +#undef MAXLEVEL +} /*PixelColour*/ + +static void RayTrace ( void ) +{ + int x, y; + ray3f ray; + byte buffer[WIDTH]; + + CPos.upside = false; + CameraSetMappingf ( &CPos ); + ps_Init_BitmapP ( WIDTH, HEIGHT, 0, 0 ); + for ( y = 0; y < HEIGHT; y++ ) { + printf ( "%4d\b\b\b\b", y ); + for ( x = 0; x < WIDTH; x++ ) { + CameraRayOfPixelf ( &CPos, x, y, &ray ); + buffer[x] = PixelColour ( &ray ); + } + ps_Out_LineP ( buffer ); + } +} /*RayTrace*/ + +void DrawBezTreeVertexDivision ( BezPatchTreeVertexf *vertex, + float w, float h, float x, float y ) +{ + float w1, h1; + + if ( vertex->left ) { + if ( vertex->ctlpoints ) + ps_Set_Line_Width ( 1.0 ); + else + ps_Set_Line_Width ( 2.0 ); + if ( vertex->divdir == 0 ) { + w1 = w*(vertex->left->u1-vertex->left->u0)/(vertex->u1-vertex->u0); + ps_Draw_Line ( (float)(x+w1), (float)y, (float)(x+w1), (float)(y+h) ); + DrawBezTreeVertexDivision ( vertex->left, w1, h, x, y ); + DrawBezTreeVertexDivision ( vertex->right, w-w1, h, x+w1, y ); + } + else { + h1 = h*(vertex->left->v1-vertex->left->v0)/(vertex->v1-vertex->v0); + ps_Draw_Line ( (float)x, (float)(y+h1), (float)(x+w), (float)(y+h1) ); + DrawBezTreeVertexDivision ( vertex->left, w, h1, x, y ); + DrawBezTreeVertexDivision ( vertex->right, w, h-h1, x, y+h1 ); + } + } +} /*DrawBezTreeVertexDivision*/ + +void DrawBezTree ( BezPatchTreef *tree, float w, float x, float y ) +{ + float h; + + h = w*(tree->root->v1-tree->root->v0)/(tree->root->u1-tree->root->u0); + ps_Set_Gray ( 0.0 ); + ps_Set_Line_Width ( 2.0 ); + ps_Draw_Rect ( (float)w, (float)h, (float)x, (float)y ); + DrawBezTreeVertexDivision ( tree->root, w, h, x, y ); +} /*DrawBezTree*/ + +int main ( void ) +{ + struct tms start, stop; + float time; + + setvbuf ( stdout, NULL, _IONBF, 0 ); + pkv_InitScratchMem ( 655360 ); + ps_WriteBBox ( -1, -1, 204, 88 ); + ps_OpenFile ( fn, 400 ); + SetCPos (); + SetLightDir (); + + times ( &start ); + tree = rbez_NewBSPatchTreef ( 0, n, lknu, knots_u, m, lknv, knots_v, + lknv-m, cpoints ); + RayTrace (); + DrawBezTree ( tree, 480, 650, 0 ); + + rbez_DestroyBezPatchTreef ( tree ); + times ( &stop ); + time = (float)(stop.tms_utime-start.tms_utime)/(float)(sysconf(_SC_CLK_TCK)); + printf ( "time = %8.3f\n", time ); + ps_CloseFile (); + + pkv_DestroyScratchMem (); + exit ( 0 ); +} /*main*/ + diff --git a/pool/shard000/C/0010405_test_buffers_gauge.c b/pool/shard000/C/0010405_test_buffers_gauge.c new file mode 100644 index 0000000000000000000000000000000000000000..393bf7c12214109915ed84d81b39f0cf0ae542a4 --- /dev/null +++ b/pool/shard000/C/0010405_test_buffers_gauge.c @@ -0,0 +1,95 @@ +#include +#include + +#include + +#include + +#define EPS 5e-16 + +int VOLUMEPLUSRAND = 10000; + +/* g_gauge_buffers is defined in one of the includes! */ +extern gauge_buffers_t g_gauge_buffers; + +TEST(buffers_gauge_allocate_finalize) { + int test = 0; + const unsigned int max = 10; + + initialize_gauge_buffers(max); + + assertEqualsM(g_gauge_buffers.max,max,"Buffers were not initialized correctly! max != 10 \n"); + + finalize_gauge_buffers(); + assertFalseM(test,"TODO: No good test condition for a failed finalize.\n"); + + assertEqualsM(g_gauge_buffers.allocated,0,"Finalize error, allocated != 0 \n"); + assertEqualsM(g_gauge_buffers.free,0,"Finalize error, free != 0 \n"); +} + +/* TODO: add test for reaching max, but since this terminates the program currently, + * need to wait for a cleaner failure condition to be implemented */ + +TEST(buffers_gauge_get_return) { + const int max = 10; + + initialize_gauge_buffers(max); + assertEqualsM(g_gauge_buffers.max,max,"Buffers were not initialized correctly! max != 10 \n"); + + + gauge_field_t gauge_field[max]; + + gauge_field[0] = get_gauge_field(); + + assertEqualsM(g_gauge_buffers.allocated,1,"Get error, allocated != 1 \n"); + assertEqualsM(g_gauge_buffers.free,0,"Get error, free != 0 \n"); + + for(int i = 1; i < 6; ++i) { + gauge_field[i] = get_gauge_field(); + } + + assertEqualsM(g_gauge_buffers.allocated,6,"Get error, allocated != 6 \n"); + + return_gauge_field(&gauge_field[5]); + + assertEqualsM(gauge_field[5].field,NULL,"Return error, field pointer not NULL \n"); + assertEqualsM(g_gauge_buffers.allocated,6,"Return error, allocated != 6 \n"); + assertEqualsM(g_gauge_buffers.free,1,"Return error, free != 1 \n"); + + gauge_field[5] = get_gauge_field(); + + assertNotEqualsM(gauge_field[5].field,NULL,"Get error, field pointer still NULL \n"); + assertEqualsM(g_gauge_buffers.allocated,6,"Get error, allocated != 6 \n"); + assertEqualsM(g_gauge_buffers.free,0,"Get error, free != 0 \n"); + + allocate_gauge_buffers(2); + + assertEqualsM(g_gauge_buffers.allocated,8,"Allocate error, allocated != 8 \n"); + assertEqualsM(g_gauge_buffers.free,2,"Allocate error, free != 2 \n"); + + gauge_field[6] = get_gauge_field(); + + assertEqualsM(g_gauge_buffers.allocated,8,"Get error, allocated != 8 \n"); + assertEqualsM(g_gauge_buffers.free,1,"Get error, free != 1 \n"); + + for(int i = 4; i <= 6; ++i) { + return_gauge_field(&gauge_field[i]); + } + + assertEqualsM(g_gauge_buffers.free,4,"Return error, free != 4 \n"); + + free_unused_gauge_buffers(); + + assertEqualsM(g_gauge_buffers.allocated,4,"Free error, allocated != 4 \n"); + assertEqualsM(g_gauge_buffers.free,0,"Free error, free != 0 \n"); + + for(int i = 0; i < 4; ++i) { + return_gauge_field(&gauge_field[i]); + } + + finalize_gauge_buffers(); + + assertEqualsM(g_gauge_buffers.allocated,0,"Finalize error, allocated != 0 \n"); + assertEqualsM(g_gauge_buffers.free,0,"Finalize error, free != 0 \n"); +} + diff --git a/pool/shard000/C/0010429_stm32l4xx_hal_msp.c b/pool/shard000/C/0010429_stm32l4xx_hal_msp.c new file mode 100644 index 0000000000000000000000000000000000000000..e778c888fa004b1cc79eecc2e81442fcfdd7e3ac --- /dev/null +++ b/pool/shard000/C/0010429_stm32l4xx_hal_msp.c @@ -0,0 +1,168 @@ +/* USER CODE BEGIN Header */ +/** + ****************************************************************************** + * @file stm32l4xx_hal_msp.c + * @brief This file provides code for the MSP Initialization + * and de-Initialization codes. + ****************************************************************************** + * @attention + * + *

© Copyright (c) 2021 STMicroelectronics. + * All rights reserved.

+ * + * This software component is licensed by ST under BSD 3-Clause license, + * the "License"; You may not use this file except in compliance with the + * License. You may obtain a copy of the License at: + * opensource.org/licenses/BSD-3-Clause + * + ****************************************************************************** + */ +/* Includes ------------------------------------------------------------------*/ +#include "stm32l4xx_hal.h" +extern void _Error_Handler(char *, int); +/* USER CODE BEGIN 0 */ + +/* USER CODE END 0 */ +/** + * Initializes the Global MSP. + */ +void HAL_MspInit(void) +{ + /* USER CODE BEGIN MspInit 0 */ + + /* USER CODE END MspInit 0 */ + + __HAL_RCC_SYSCFG_CLK_ENABLE(); + __HAL_RCC_PWR_CLK_ENABLE(); + + HAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4); + + /* System interrupt init*/ + /* MemoryManagement_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(MemoryManagement_IRQn, 0, 0); + /* BusFault_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(BusFault_IRQn, 0, 0); + /* UsageFault_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(UsageFault_IRQn, 0, 0); + /* SVCall_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(SVCall_IRQn, 0, 0); + /* DebugMonitor_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(DebugMonitor_IRQn, 0, 0); + /* PendSV_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(PendSV_IRQn, 0, 0); + /* SysTick_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0); + + /* USER CODE BEGIN MspInit 1 */ + + /* USER CODE END MspInit 1 */ +} + +void HAL_RTC_MspInit(RTC_HandleTypeDef* hrtc) +{ + + if(hrtc->Instance==RTC) + { + /* USER CODE BEGIN RTC_MspInit 0 */ + + /* USER CODE END RTC_MspInit 0 */ + /* Peripheral clock enable */ + __HAL_RCC_RTC_ENABLE(); + /* USER CODE BEGIN RTC_MspInit 1 */ + + /* USER CODE END RTC_MspInit 1 */ + } + +} + +void HAL_RTC_MspDeInit(RTC_HandleTypeDef* hrtc) +{ + + if(hrtc->Instance==RTC) + { + /* USER CODE BEGIN RTC_MspDeInit 0 */ + + /* USER CODE END RTC_MspDeInit 0 */ + /* Peripheral clock disable */ + __HAL_RCC_RTC_DISABLE(); + /* USER CODE BEGIN RTC_MspDeInit 1 */ + + /* USER CODE END RTC_MspDeInit 1 */ + } + +} + +void HAL_UART_MspInit(UART_HandleTypeDef* huart) +{ + + GPIO_InitTypeDef GPIO_InitStruct; + if(huart->Instance==USART2) + { + /* USER CODE BEGIN USART2_MspInit 0 */ + + /* USER CODE END USART2_MspInit 0 */ + /* Peripheral clock enable */ + __HAL_RCC_USART2_CLK_ENABLE(); + + /**USART2 GPIO Configuration + PA2 ------> USART2_TX + PA15 (JTDI) ------> USART2_RX + */ + GPIO_InitStruct.Pin = VCP_TX_Pin; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_PULLUP; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_MEDIUM; + GPIO_InitStruct.Alternate = GPIO_AF7_USART2; + HAL_GPIO_Init(VCP_TX_GPIO_Port, &GPIO_InitStruct); + + GPIO_InitStruct.Pin = VCP_RX_Pin; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_PULLUP; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_MEDIUM; + GPIO_InitStruct.Alternate = GPIO_AF3_USART2; + HAL_GPIO_Init(VCP_RX_GPIO_Port, &GPIO_InitStruct); + + /* USER CODE BEGIN USART2_MspInit 1 */ + + /* USER CODE END USART2_MspInit 1 */ + } + +} + +void HAL_UART_MspDeInit(UART_HandleTypeDef* huart) +{ + + if(huart->Instance==USART2) + { + /* USER CODE BEGIN USART2_MspDeInit 0 */ + + /* USER CODE END USART2_MspDeInit 0 */ + /* Peripheral clock disable */ + __HAL_RCC_USART2_CLK_DISABLE(); + + /**USART2 GPIO Configuration + PA2 ------> USART2_TX + PA15 (JTDI) ------> USART2_RX + */ + HAL_GPIO_DeInit(GPIOA, VCP_TX_Pin|VCP_RX_Pin); + + /* USER CODE BEGIN USART2_MspDeInit 1 */ + + /* USER CODE END USART2_MspDeInit 1 */ + } + +} + +/* USER CODE BEGIN 1 */ + +/* USER CODE END 1 */ + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard000/C/0010436_csv.c b/pool/shard000/C/0010436_csv.c new file mode 100644 index 0000000000000000000000000000000000000000..1f679614e44d661530a2a41a5dce418c7c9a8e2b --- /dev/null +++ b/pool/shard000/C/0010436_csv.c @@ -0,0 +1,156 @@ +#include +#include "../util/util.h" +#include "csv.h" + +static size_t line_index; +static size_t entry_index; + +static void +count_lines (int delim, void* csv_data) +{ + (void) delim; + csv_data_t* csvd = (csv_data_t*) csv_data; + ++(csvd->line_count); +} + +static void +increment_line (int delim, void* csv_data) +{ + (void) delim; + (void) csv_data; + ++line_index; + entry_index = 0; +} + +static void +count_entries (void* entry, size_t entry_length, void* csv_data) +{ + (void) entry; + (void) entry_length; + csv_data_t* csvd = (csv_data_t*) csv_data; + ++(csvd->entry_counts[line_index]); +} + +static void +read_entries (void* entry, size_t entry_length, void* csv_data) +{ + csv_data_t* csvd = (csv_data_t*) csv_data; + csvd->data[line_index][entry_index] = malloc_exit_if_null(sizeof(char) * entry_length + 1); + memcpy(csvd->data[line_index][entry_index], entry, sizeof(char) * entry_length + 1); + ++entry_index; +} + +static inline void +csv_exit_if_error (csv_parser* parser) +{ + printferr("Error while parsing file: %s\n", csv_strerror(csv_error(parser))); + exit(EXIT_FAILURE); +} + +csv_data_t* +construct_csv_data (const char* path) +{ + FILE* fp = fopen(path, "rb"); + exit_if_null(fp); + + csv_parser parser; + char buffer[1024]; + size_t bytes_read; + + exit_if_not_zero(csv_init(&parser, CSV_STRICT | CSV_APPEND_NULL)); + + // MALLOC: csvd + csv_data_t* csvd = malloc_exit_if_null(sizeof(csv_data_t)); + + // Count csv file lines + csvd->line_count = 0; + while ((bytes_read = fread(buffer, 1, 1024, fp)) > 0) + { + if (csv_parse(&parser, buffer, bytes_read, NULL, count_lines, csvd) != bytes_read) + { + csv_exit_if_error(&parser); } + } + + // MALLOC: csvd->entry_counts + csvd->entry_counts = calloc_exit_if_null(csvd->line_count, sizeof(size_t)); + + // MALLOC: csvd->data (lines) + csvd->data = malloc_exit_if_null(SIZEOF_PTR * csvd->line_count); + + // Count csv file entries in each line + csv_fini(&parser, NULL, NULL, csvd); + rewind(fp); + line_index = 0; + while ((bytes_read = fread(buffer, 1, 1024, fp)) > 0) + { + if (csv_parse(&parser, buffer, bytes_read, count_entries, increment_line, csvd) != bytes_read) + { + csv_exit_if_error(&parser); + } + } + + // MALLOC: csvd->data (fields in malloc'd lines) + size_t i; + for (i = 0; i < csvd->line_count; ++i) + { + csvd->data[i] = malloc_exit_if_null(SIZEOF_PTR * csvd->entry_counts[i]); + } + + // Read each entry into data, including mallocing the associated space. + csv_fini(&parser, NULL, NULL, csvd); + rewind(fp); + line_index = 0; + entry_index = 0; + while ((bytes_read = fread(buffer, 1, 1024, fp)) > 0) + { + if (csv_parse(&parser, buffer, bytes_read, read_entries, increment_line, csvd) != bytes_read) + { + csv_exit_if_error(&parser); + } + } + + fclose(fp); + csv_free(&parser); + return csvd; +} + + +void +destruct_csv_data (csv_data_t* csvd) +{ + size_t i, j; + for (i = 0; i < csvd->line_count; ++i) + { + for (j = 0; j < csvd->entry_counts[i]; ++j) + { + // FREE: csvd->data[i][j] + free_and_null(csvd->data[i][j]); + } + // FREE: csvd->data[i] + free_and_null(csvd->data[i]); + } + + // FREE: csvd->data + free_and_null(csvd->data); + + // FREE: csvd->entry_counts + free_and_null(csvd->entry_counts); + + // FREE: csvd + free_and_null(csvd); +} + +void +print_csv_data (const csv_data_t* csvd) +{ + printf("csvd->line_count = %d\n", csvd->line_count); + size_t i, j; + for (i = 0; i < csvd->line_count; ++i) + { + printf("csvd->entry_count[%d] = %d\n", i, csvd->entry_counts[i]); + for (j = 0; j < csvd->entry_counts[i]; ++j) + { + printf("csvd->data[%d][%d] = %s\n", i, j, csvd->data[i][j]); + } + } +} diff --git a/pool/shard000/C/0010442_pfwstring.c b/pool/shard000/C/0010442_pfwstring.c new file mode 100644 index 0000000000000000000000000000000000000000..45669576dd1fb2efea49942199d63f0424943e51 --- /dev/null +++ b/pool/shard000/C/0010442_pfwstring.c @@ -0,0 +1,218 @@ +/********************************************************************** + * pfwstring.c + * Write string table data a POFF file + * + * Copyright (C) 2008-2009 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt + * + * 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 NuttX nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + **********************************************************************/ + +/********************************************************************** + * Included Files + **********************************************************************/ + +#include +#include +#include +#include +#include + +#include "keywords.h" /* Standard types */ +#include "pedefs.h" /* error code definitions */ + +#include "perr.h" /* error() */ +#include "pofflib.h" /* POFF library interface */ +#include "pfprivate.h" /* POFF private definitions */ + +/********************************************************************** + * Pre-processor Definitions + **********************************************************************/ + +/********************************************************************** + * Global Variables + **********************************************************************/ + +/********************************************************************** + * Private Variables + **********************************************************************/ + +/*********************************************************************** + * Private Function Prototypes + ***********************************************************************/ + +/*********************************************************************** + * Private Functions + ***********************************************************************/ + +/*********************************************************************** + * Public Functions + ***********************************************************************/ + +/***********************************************************************/ +/* Search the string table for an occurrence of the indicates string. + * If found, return the offset in the string table to the string; if + * not found, return -1. + */ + +int32_t poffFindString(poffHandle_t handle, const char *string) +{ + poffInfo_t *poffInfo = (poffInfo_t*)handle; + char *sptr = poffInfo->stringTable; + uint32_t offset; + + /* Has the string table been allocated yet? */ + + if (!poffInfo->stringTable) return -1; + + /* Handle the NULL string case. Offset zero is reserved for the NULL + * string and for the zero-size string. + */ + + if (!string) return 0; + + /* Okay, we will have to search the table */ + + for (offset = 0; + offset < poffInfo->stringTableSection.sh_size; + offset += (strlen(sptr) + 1)) + { + /* Get a pointer at this offset into the string table */ + + sptr = &poffInfo->stringTable[offset]; + + /* Check if the strings match. If so, return the offset */ + + if (strcmp(sptr, string) == 0) return offset; + } + + /* The string does not exist in the string table */ + + return -1; +} + +/***********************************************************************/ +/***********************************************************************/ +/* Add a string to the string table and return the offset to the + * string storage location in the string table section data. + */ + +uint32_t poffAddString(poffHandle_t handle, const char *string) +{ + poffInfo_t *poffInfo = (poffInfo_t*)handle; + int32_t index; + int len; + + /* Check if we have allocated a string table buffer yet */ + + if (!poffInfo->stringTable) + { + /* No, allocate it now */ + + poffInfo->stringTable = (char*)malloc(INITIAL_STRING_TABLE_SIZE); + if (!poffInfo->stringTable) + { + fatal(eNOMEMORY); + } + + /* Index 0 is reserved for the NULL string */ + + poffInfo->stringTable[0] = '\0'; + poffInfo->stringTableSection.sh_size = 1; + poffInfo->stringTableAlloc = INITIAL_STRING_TABLE_SIZE; + } + + /* Check if the string is already defined in the string table. + * This is very time consuming, but guaratees that we do not keep + * duplicate strings in the string table. + */ + + index = poffFindString(handle, string); + if (index < 0) + { + /* The string was not found in the string table. Check for the + * NULL string. In this case, return index == 0. NOTE: This + * check is pointless. If this is any kind of NULL string, then + * poffFindString will have returned index == 0. + */ + + if ((string == NULL) || ((len = strlen(string)) <= 0)) + { + index = 0; + } + else + { + /* Increment the length to include the null terminator */ + + len++; + + /* Check if there is room for the new string */ + + if (poffInfo->stringTableSection.sh_size + len > + poffInfo->stringTableAlloc) + { + uint32_t newAlloc = + poffInfo->stringTableAlloc + STRING_TABLE_INCREMENT; + void *tmp; + + /* Make sure that the new string will fit in the new allocation + * size (shouldn't happen) + */ + + while (poffInfo->stringTableSection.sh_size + len > newAlloc) + newAlloc += STRING_TABLE_INCREMENT; + + /* Reallocate the string buffer */ + + tmp = realloc(poffInfo->stringTable, newAlloc); + if (!tmp) + { + fatal(eNOMEMORY); + } + + /* And set the new size */ + + poffInfo->stringTableAlloc = newAlloc; + poffInfo->stringTable = (char*)tmp; + } + + /* Copy the string into the string table */ + + index = poffInfo->stringTableSection.sh_size; + memcpy(&poffInfo->stringTable[index], string, len); + + /* Set the new size of the string table */ + + poffInfo->stringTableSection.sh_size += len; + } + } + return index; +} + +/***********************************************************************/ diff --git a/pool/shard000/C/0010455_mce-apei.c b/pool/shard000/C/0010455_mce-apei.c new file mode 100644 index 0000000000000000000000000000000000000000..be76229260adba4832e03da7beae57baea3d4fe8 --- /dev/null +++ b/pool/shard000/C/0010455_mce-apei.c @@ -0,0 +1,149 @@ +/* + * Bridge between MCE and APEI + * + * On some machine, corrected memory errors are reported via APEI + * generic hardware error source (GHES) instead of corrected Machine + * Check. These corrected memory errors can be reported to user space + * through /dev/mcelog via faking a corrected Machine Check, so that + * the error memory page can be offlined by /sbin/mcelog if the error + * count for one page is beyond the threshold. + * + * For fatal MCE, save MCE record into persistent storage via ERST, so + * that the MCE record can be logged after reboot via ERST. + * + * Copyright 2010 Intel Corp. + * Author: Huang Ying + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License version + * 2 as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include +#include +#include +#include +#include +#include + +#include "mce-internal.h" + +void apei_mce_report_mem_error(int corrected, struct cper_sec_mem_err *mem_err) +{ + struct mce m; + + /* */ + if (!corrected) + return; + + mce_setup(&m); + m.bank = 1; + /* */ + m.status = MCI_STATUS_VAL | MCI_STATUS_EN | MCI_STATUS_ADDRV | 0x9f; + m.addr = mem_err->physical_addr; + mce_log(&m); + mce_notify_irq(); +} +EXPORT_SYMBOL_GPL(apei_mce_report_mem_error); + +#define CPER_CREATOR_MCE \ + UUID_LE(0x75a574e3, 0x5052, 0x4b29, 0x8a, 0x8e, 0xbe, 0x2c, \ + 0x64, 0x90, 0xb8, 0x9d) +#define CPER_SECTION_TYPE_MCE \ + UUID_LE(0xfe08ffbe, 0x95e4, 0x4be7, 0xbc, 0x73, 0x40, 0x96, \ + 0x04, 0x4a, 0x38, 0xfc) + +/* + + + */ +struct cper_mce_record { + struct cper_record_header hdr; + struct cper_section_descriptor sec_hdr; + struct mce mce; +} __packed; + +int apei_write_mce(struct mce *m) +{ + struct cper_mce_record rcd; + + memset(&rcd, 0, sizeof(rcd)); + memcpy(rcd.hdr.signature, CPER_SIG_RECORD, CPER_SIG_SIZE); + rcd.hdr.revision = CPER_RECORD_REV; + rcd.hdr.signature_end = CPER_SIG_END; + rcd.hdr.section_count = 1; + rcd.hdr.error_severity = CPER_SEV_FATAL; + /* */ + rcd.hdr.validation_bits = 0; + rcd.hdr.record_length = sizeof(rcd); + rcd.hdr.creator_id = CPER_CREATOR_MCE; + rcd.hdr.notification_type = CPER_NOTIFY_MCE; + rcd.hdr.record_id = cper_next_record_id(); + rcd.hdr.flags = CPER_HW_ERROR_FLAGS_PREVERR; + + rcd.sec_hdr.section_offset = (void *)&rcd.mce - (void *)&rcd; + rcd.sec_hdr.section_length = sizeof(rcd.mce); + rcd.sec_hdr.revision = CPER_SEC_REV; + /* */ + rcd.sec_hdr.validation_bits = 0; + rcd.sec_hdr.flags = CPER_SEC_PRIMARY; + rcd.sec_hdr.section_type = CPER_SECTION_TYPE_MCE; + rcd.sec_hdr.section_severity = CPER_SEV_FATAL; + + memcpy(&rcd.mce, m, sizeof(*m)); + + return erst_write(&rcd.hdr); +} + +ssize_t apei_read_mce(struct mce *m, u64 *record_id) +{ + struct cper_mce_record rcd; + int rc, pos; + + rc = erst_get_record_id_begin(&pos); + if (rc) + return rc; +retry: + rc = erst_get_record_id_next(&pos, record_id); + if (rc) + goto out; + /* */ + if (*record_id == APEI_ERST_INVALID_RECORD_ID) + goto out; + rc = erst_read(*record_id, &rcd.hdr, sizeof(rcd)); + /* */ + if (rc == -ENOENT) + goto retry; + else if (rc < 0) + goto out; + /* */ + else if (rc != sizeof(rcd) || + uuid_le_cmp(rcd.hdr.creator_id, CPER_CREATOR_MCE)) + goto retry; + memcpy(m, &rcd.mce, sizeof(*m)); + rc = sizeof(*m); +out: + erst_get_record_id_end(); + + return rc; +} + +/* */ +int apei_check_mce(void) +{ + return erst_get_record_count(); +} + +int apei_clear_mce(u64 record_id) +{ + return erst_clear(record_id); +} diff --git a/pool/shard000/C/0010456_safe.c b/pool/shard000/C/0010456_safe.c new file mode 100644 index 0000000000000000000000000000000000000000..8b553e115140c4d281aaae662e42745fe63dde6c --- /dev/null +++ b/pool/shard000/C/0010456_safe.c @@ -0,0 +1,181 @@ +/* safe.c --- Shishi SAFE self tests. + * Copyright (C) 2002-2014 Simon Josefsson + * + * This file is part of Shishi. + * + * Shishi 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. + * + * Shishi 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 Shishi; if not, see http://www.gnu.org/licenses or write + * to the Free Software Foundation, Inc., 51 Franklin Street, Fifth + * Floor, Boston, MA 02110-1301, USA + * + */ + +#include "utils.c" + +void +test (Shishi * handle) +{ + Shishi_safe *safe; + Shishi_key *key; + Shishi_asn1 asn1safe; + char *p, *q; + size_t l, m; + int32_t t; + int res; + + /* shishi_safe() */ + res = shishi_safe (handle, &safe); + if (debug) + printf ("shishi_safe () => `%p'.\n", safe); + if (res == SHISHI_OK) + success ("shishi_safe() OK\n"); + else + fail ("shishi_safe() failed\n"); + + /* shishi_safe_key */ + key = shishi_safe_key (safe); + if (key) + success ("shishi_safe_key() OK\n"); + else + fail ("shishi_safe_key() failed\n"); + + /* shishi_safe_safe */ + asn1safe = shishi_safe_safe (safe); + if (asn1safe) + success ("shishi_safe_safe() OK\n"); + else + fail ("shishi_safe_safe() failed\n"); + + /* shishi_safe_set_user_data */ + res = shishi_safe_set_user_data (handle, asn1safe, "foo", 3); + if (res == SHISHI_OK) + success ("shishi_safe_set_user_data() OK\n"); + else + fail ("shishi_safe_set_user_data() failed (%d)\n", res); + + /* shishi_safe_user_data */ + res = shishi_safe_user_data (handle, asn1safe, &p, &l); + if (debug) + escapeprint (p, l); + if (res == SHISHI_OK && l == 3 && memcmp (p, "foo", 3) == 0) + success ("shishi_safe_user_data() OK\n"); + else + fail ("shishi_safe_user_data() failed (%d)\n", res); + free (p); + + /* shishi_safe_set_cksum */ + res = shishi_safe_set_cksum (handle, asn1safe, 42, "bar", 3); + if (res == SHISHI_OK) + success ("shishi_safe_set_cksum() OK\n"); + else + fail ("shishi_safe_set_cksum() failed (%d)\n", res); + + /* shishi_safe_cksum */ + res = shishi_safe_cksum (handle, asn1safe, &t, &q, &m); + if (debug) + { + printf ("type=%d\n", t); + escapeprint (q, m); + } + if (res == SHISHI_OK && t == 42 && m == 3 && memcmp (q, "bar", 3) == 0) + success ("shishi_safe_cksum() OK\n"); + else + fail ("shishi_safe_cksum() failed (%d)\n", res); + free (q); + + /* shishi_safe_verify */ + res = shishi_safe_verify (safe, key); + if (res == SHISHI_CRYPTO_ERROR) /* t==42 unsupported cksumtype */ + success ("shishi_safe_verify() OK\n"); + else + fail ("shishi_safe_verify() failed (%d)\n", res); + +#if WITH_DES + /* shishi_safe_set_cksum */ + res = shishi_safe_set_cksum (handle, asn1safe, SHISHI_RSA_MD5_DES, + "bar", 3); + if (res == SHISHI_OK) + success ("shishi_safe_set_cksum() OK\n"); + else + fail ("shishi_safe_set_cksum() failed (%d)\n", res); + + /* shishi_safe_verify */ + res = shishi_safe_verify (safe, key); + if (res == SHISHI_VERIFY_FAILED) + success ("shishi_safe_verify() OK\n"); + else + fail ("shishi_safe_verify() failed (%d)\n", res); +#endif + + /* shishi_safe_safe_der() */ + res = shishi_safe_safe_der (safe, &p, &l); + if (res == SHISHI_OK) + success ("shishi_safe_safe_der() OK\n"); + else + fail ("shishi_safe_safe_der() failed\n"); + + /* shishi_safe_to_file() */ + res = shishi_safe_to_file (handle, asn1safe, SHISHI_FILETYPE_TEXT, + "safe.tmp"); + if (res == SHISHI_OK) + success ("shishi_safe_to_file() OK\n"); + else + fail ("shishi_safe_to_file() failed\n"); + + /* shishi_safe_done() */ + shishi_safe_done (safe); + success ("shishi_safe_done() OK\n"); + + /* shishi_authenticator_from_file() */ + asn1safe = NULL; + res = shishi_safe_from_file (handle, &asn1safe, SHISHI_FILETYPE_TEXT, + "safe.tmp"); + if (res == SHISHI_OK) + success ("shishi_safe_from_file() OK\n"); + else + fail ("shishi_safe_from_file() failed\n"); + + if (debug) + { + /* shishi_safe_print() */ + res = shishi_safe_print (handle, stdout, asn1safe); + if (res == SHISHI_OK) + success ("shishi_safe_print() OK\n"); + else + fail ("shishi_safe_print() failed\n"); + } + + /* shishi_asn1_to_der() */ + res = shishi_asn1_to_der (handle, asn1safe, &q, &m); + if (res == SHISHI_OK) + success ("shishi_asn1_to_der() OK\n"); + else + fail ("shishi_asn1_to_der() failed\n"); + + /* Compare DER encodings of authenticators */ + if (l > 0 && m > 0 && l == m && memcmp (p, q, l) == 0) + success ("DER comparison OK\n"); + else + fail ("DER comparison failed\n"); + + shishi_asn1_done (handle, asn1safe); + free (q); + free (p); + + /* unlink() */ + res = unlink ("safe.tmp"); + if (res == 0) + success ("unlink() OK\n"); + else + fail ("unlink() failed\n"); +} diff --git a/pool/shard000/C/0010473_test_passing_structs.c b/pool/shard000/C/0010473_test_passing_structs.c new file mode 100644 index 0000000000000000000000000000000000000000..8daa676e7eb2f809571712b96dae1da775b3120b --- /dev/null +++ b/pool/shard000/C/0010473_test_passing_structs.c @@ -0,0 +1,65 @@ +#include "avx512f-check.h" +#include "args.h" + +struct IntegerRegisters iregs; +struct FloatRegisters fregs; +unsigned int num_iregs, num_fregs; + +struct m512_struct +{ + __m512 x; +}; + +struct m512_2_struct +{ + __m512 x1, x2; +}; + +/* Check that the struct is passed as the individual members in fregs. */ +void +check_struct_passing1 (struct m512_struct ms1 ATTRIBUTE_UNUSED, + struct m512_struct ms2 ATTRIBUTE_UNUSED, + struct m512_struct ms3 ATTRIBUTE_UNUSED, + struct m512_struct ms4 ATTRIBUTE_UNUSED, + struct m512_struct ms5 ATTRIBUTE_UNUSED, + struct m512_struct ms6 ATTRIBUTE_UNUSED, + struct m512_struct ms7 ATTRIBUTE_UNUSED, + struct m512_struct ms8 ATTRIBUTE_UNUSED) +{ + /* Check register contents. */ + check_m512_arguments; +} + +void +check_struct_passing2 (struct m512_2_struct ms ATTRIBUTE_UNUSED) +{ + /* Check the passing on the stack by comparing the address of the + stack elements to the expected place on the stack. */ + assert ((unsigned long)&ms.x1 == rsp+8); + assert ((unsigned long)&ms.x2 == rsp+72); +} + +static void +avx512f_test (void) +{ + struct m512_struct m512s [8]; + struct m512_2_struct m512_2s = { + { 48.394, 39.3, -397.9, 3484.9, -8.394, -93.3, 7.9, 84.94, + 48.3941, 39.31, -397.91, 3484.91, -8.3941, -93.31, 7.91, 84.941 }, + { -8.394, -3.3, -39.9, 34.9, 7.9, 84.94, -48.394, 39.3, + -8.3942, -3.32, -39.92, 34.92, 7.92, 84.942, -48.3942, 39.32 } + }; + int i; + + for (i = 0; i < 8; i++) + m512s[i].x = (__m512){32+i, 0, i, 0, -i, 0, i - 12, i + 8, + 32+i, 0, i, 0, -i, 0, i - 12, i + 8}; + + clear_struct_registers; + for (i = 0; i < 8; i++) + (&fregs.zmm0)[i]._m512[0] = m512s[i].x; + num_fregs = 8; + WRAP_CALL (check_struct_passing1)(m512s[0], m512s[1], m512s[2], m512s[3], + m512s[4], m512s[5], m512s[6], m512s[7]); + WRAP_CALL (check_struct_passing2)(m512_2s); +} diff --git a/pool/shard000/C/0010478_execsnoop.bpf.c b/pool/shard000/C/0010478_execsnoop.bpf.c new file mode 100644 index 0000000000000000000000000000000000000000..3de541214b3e0596e46d9aedacf3605d13fa24fb --- /dev/null +++ b/pool/shard000/C/0010478_execsnoop.bpf.c @@ -0,0 +1,129 @@ +// SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) +#include +#include +#include +#include "execsnoop.h" + +const volatile bool ignore_failed = true; +const volatile uid_t targ_uid = INVALID_UID; +const volatile int max_args = DEFAULT_MAXARGS; + +static const struct event empty_event = {}; + +struct { + __uint(type, BPF_MAP_TYPE_HASH); + __uint(max_entries, 10240); + __type(key, pid_t); + __type(value, struct event); +} execs SEC(".maps"); + +struct { + __uint(type, BPF_MAP_TYPE_PERF_EVENT_ARRAY); + __uint(key_size, sizeof(u32)); + __uint(value_size, sizeof(u32)); +} events SEC(".maps"); + +static __always_inline bool valid_uid(uid_t uid) { + return uid != INVALID_UID; +} + +SEC("tracepoint/syscalls/sys_enter_execve") +int tracepoint__syscalls__sys_enter_execve(struct trace_event_raw_sys_enter* ctx) +{ + u64 id; + pid_t pid, tgid; + unsigned int ret; + struct event *event; + struct task_struct *task; + const char **args = (const char **)(ctx->args[1]); + const char *argp; + uid_t uid = (u32)bpf_get_current_uid_gid(); + int i; + + if (valid_uid(targ_uid) && targ_uid != uid) + return 0; + + id = bpf_get_current_pid_tgid(); + pid = (pid_t)id; + tgid = id >> 32; + if (bpf_map_update_elem(&execs, &pid, &empty_event, BPF_NOEXIST)) + return 0; + + event = bpf_map_lookup_elem(&execs, &pid); + if (!event) + return 0; + + event->pid = tgid; + event->uid = uid; + task = (struct task_struct*)bpf_get_current_task(); + event->ppid = (pid_t)BPF_CORE_READ(task, real_parent, tgid); + event->args_count = 0; + event->args_size = 0; + + ret = bpf_probe_read_user_str(event->args, ARGSIZE, (const char*)ctx->args[0]); + if (ret <= ARGSIZE) { + event->args_size += ret; + } else { + /* write an empty string */ + event->args[0] = '\0'; + event->args_size++; + } + + event->args_count++; + #pragma unroll + for (i = 1; i < TOTAL_MAX_ARGS && i < max_args; i++) { + bpf_probe_read_user(&argp, sizeof(argp), &args[i]); + if (!argp) + return 0; + + if (event->args_size > LAST_ARG) + return 0; + + ret = bpf_probe_read_user_str(&event->args[event->args_size], ARGSIZE, argp); + if (ret > ARGSIZE) + return 0; + + event->args_count++; + event->args_size += ret; + } + /* try to read one more argument to check if there is one */ + bpf_probe_read_user(&argp, sizeof(argp), &args[max_args]); + if (!argp) + return 0; + + /* pointer to max_args+1 isn't null, asume we have more arguments */ + event->args_count++; + return 0; +} + +SEC("tracepoint/syscalls/sys_exit_execve") +int tracepoint__syscalls__sys_exit_execve(struct trace_event_raw_sys_exit* ctx) +{ + u64 id; + pid_t pid; + int ret; + struct event *event; + u32 uid = (u32)bpf_get_current_uid_gid(); + + if (valid_uid(targ_uid) && targ_uid != uid) + return 0; + id = bpf_get_current_pid_tgid(); + pid = (pid_t)id; + event = bpf_map_lookup_elem(&execs, &pid); + if (!event) + return 0; + ret = ctx->ret; + if (ignore_failed && ret < 0) + goto cleanup; + + event->retval = ret; + bpf_get_current_comm(&event->comm, sizeof(event->comm)); + size_t len = EVENT_SIZE(event); + if (len <= sizeof(*event)) + bpf_perf_event_output(ctx, &events, BPF_F_CURRENT_CPU, event, len); +cleanup: + bpf_map_delete_elem(&execs, &pid); + return 0; +} + +char LICENSE[] SEC("license") = "GPL"; diff --git a/pool/shard000/C/0010481_pci_up1000.c b/pool/shard000/C/0010481_pci_up1000.c new file mode 100644 index 0000000000000000000000000000000000000000..6d65b81286ba4454ba2d1de167a1dba68e379b5a --- /dev/null +++ b/pool/shard000/C/0010481_pci_up1000.c @@ -0,0 +1,219 @@ +/* $OpenBSD: pci_up1000.c,v 1.2 2001/04/17 14:53:34 art Exp $ */ +/* $NetBSD: pci_up1000.c,v 1.6 2000/12/28 22:59:07 sommerfeld Exp $ */ + +/*- + * Copyright (c) 2000 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by Jason R. Thorpe. + * + * 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 NetBSD + * Foundation, Inc. and its contributors. + * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, 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 THE FOUNDATION OR CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include + +#include + +#include +#include +#include +#include + +#include + +#include +#include +#include + +#include "sio.h" + +int api_up1000_intr_map(void *, pcitag_t, int, int, pci_intr_handle_t *); +const char *api_up1000_intr_string(void *, pci_intr_handle_t); +const struct evcnt *api_up1000_intr_evcnt(void *, pci_intr_handle_t); +void *api_up1000_intr_establish(void *, pci_intr_handle_t, + int, int (*func)(void *), void *, char *); +void api_up1000_intr_disestablish(void *, void *); + +void *api_up1000_pciide_compat_intr_establish(void *, struct device *, + struct pci_attach_args *, int, int (*)(void *), void *); + +void +pci_up1000_pickintr(struct irongate_config *icp) +{ + bus_space_tag_t iot = icp->ic_iot; + pci_chipset_tag_t pc = &icp->ic_pc; + + pc->pc_intr_v = icp; + pc->pc_intr_map = api_up1000_intr_map; + pc->pc_intr_string = api_up1000_intr_string; +#if 0 + pc->pc_intr_evcnt = api_up1000_intr_evcnt; +#endif + pc->pc_intr_establish = api_up1000_intr_establish; + pc->pc_intr_disestablish = api_up1000_intr_disestablish; + + pc->pc_pciide_compat_intr_establish = + api_up1000_pciide_compat_intr_establish; + +#if NSIO + sio_intr_setup(pc, iot); + set_iointr(&sio_iointr); +#else + panic("pci_up1000_pickintr: no I/O interrupt handler (no sio)"); +#endif +} + +int +api_up1000_intr_map(void *icv, pcitag_t bustag, int buspin, int line, pci_intr_handle_t *ihp) +{ + struct irongate_config *icc = icv; + pci_chipset_tag_t pc = &icc->ic_pc; + int bus, device, function; + + if (buspin == 0) { + /* No IRQ used. */ + return 1; + } + if (buspin > 4) { + printf("api_up1000_intr_map: bad interrupt pin %d\n", + buspin); + return 1; + } + + alpha_pci_decompose_tag(pc, bustag, &bus, &device, &function); + + /* + * The console places the interrupt mapping in the "line" value. + * A value of (char)-1 indicates there is no mapping. + */ + if (line == 0xff) { + printf("api_up1000_intr_map: no mapping for %d/%d/%d\n", + bus, device, function); + return (1); + } + + /* XXX Check for 0? */ + if (line > 15) { + printf("api_up1000_intr_map: ISA IRQ too large (%d)\n", + line); + return (1); + } + if (line == 2) { + printf("api_up1000_intr_map: changed IRQ 2 to IRQ 9\n"); + line = 9; + } + + *ihp = line; + return (0); +} + +const char * +api_up1000_intr_string(void *icv, pci_intr_handle_t ih) +{ +#if 0 + struct irongate_config *icp = icv; +#endif + + return sio_intr_string(NULL /*XXX*/, ih); +} + +#if 0 +const struct evcnt * +api_up1000_intr_evcnt(void *icv, pci_intr_handle_t ih) +{ +#if 0 + struct irongate_config *icp = icv; +#endif + + return sio_intr_evcnt(NULL /*XXX*/, ih); +} +#endif + +void * +api_up1000_intr_establish(void *icv, pci_intr_handle_t ih, int level, + int (*func)(void *), void *arg, char *name) +{ +#if 0 + struct irongate_config *icp = icv; +#endif + + return sio_intr_establish(NULL /*XXX*/, ih, IST_LEVEL, level, func, + arg, name); +} + +void +api_up1000_intr_disestablish(void *icv, void *cookie) +{ +#if 0 + struct irongate_config *icp = icv; +#endif + + sio_intr_disestablish(NULL /*XXX*/, cookie); +} + +void * +api_up1000_pciide_compat_intr_establish(void *icv, struct device *dev, + struct pci_attach_args *pa, int chan, int (*func)(void *), void *arg) +{ + pci_chipset_tag_t pc = pa->pa_pc; + void *cookie = NULL; + int bus, irq; + + alpha_pci_decompose_tag(pc, pa->pa_tag, &bus, NULL, NULL); + + /* + * If this isn't PCI bus #0, all bets are off. + */ + if (bus != 0) + return (NULL); + + irq = PCIIDE_COMPAT_IRQ(chan); +#if NSIO + cookie = sio_intr_establish(NULL /*XXX*/, irq, IST_EDGE, IPL_BIO, + func, arg, "up 1000 irq"); + if (cookie == NULL) + return (NULL); + printf("%s: %s channel interrupting at %s\n", dev->dv_xname, + PCIIDE_CHANNEL_NAME(chan), sio_intr_string(NULL /*XXX*/, irq)); +#endif + return (cookie); +} diff --git a/pool/shard000/C/0010482_4-97.c b/pool/shard000/C/0010482_4-97.c new file mode 100644 index 0000000000000000000000000000000000000000..9daa3ea3b67552284dbe8ed24745c674f6d522a5 --- /dev/null +++ b/pool/shard000/C/0010482_4-97.c @@ -0,0 +1,40 @@ +/* + + * Copyright (c) 2002-2003, Intel Corporation. All rights reserved. + * Created by: rusty.lynch REMOVE-THIS AT intel DOT com + * This file is licensed under the GPL license. For the full content + * of this license, see the COPYING file at the top level of this + * source tree. + + Test case for assertion #4 of the sigaction system call that shows + that attempting to add SIGSTOP to the signal mask of SIGPOLL will + not result in sigaction returning -1 +*/ + +#include +#include +#include +#include +#include +#include "posixtest.h" + +void handler(int signo) +{ +} + +int main() +{ + struct sigaction act; + + act.sa_handler = handler; + act.sa_flags = 0; + sigemptyset(&act.sa_mask); + sigaddset(&act.sa_mask, SIGSTOP); + if (sigaction(SIGPOLL, &act, 0) == -1) { + printf("Test FAILED\n"); + return PTS_FAIL; + } + + printf("Test PASSED\n"); + return PTS_PASS; +} diff --git a/pool/shard000/C/0010492_cycle-interval-report.c b/pool/shard000/C/0010492_cycle-interval-report.c new file mode 100644 index 0000000000000000000000000000000000000000..9fb92f7a213752c629bc2efeb47f8a48dc9de4d3 --- /dev/null +++ b/pool/shard000/C/0010492_cycle-interval-report.c @@ -0,0 +1,141 @@ +/* + * Multi2Sim + * Copyright (C) 2012 Rafael Ubal (ubal@ece.neu.edu) + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include +#include +#include +#include + +#include "gpu.h" +#include "cycle-interval-report.h" + +#include "compute-unit.h" + +int si_spatial_report_active = 0; + +static int spatial_profiling_interval = 10000; +static char *si_spatial_report_section_name = "SISpatialReport"; +static FILE *spatial_report_file; +static char *spatial_report_filename = "report-cu-spatial"; + +void si_spatial_report_config_read(struct config_t *config) { + char *section; + char *file_name; + + /*Nothing if section or config is not present */ + section = si_spatial_report_section_name; + if (!config_section_exists(config, section)) { + /*no spatial profiling */ + return; + } + + /* Spatial reports are active */ + si_spatial_report_active = 1; + + /* Interval */ + config_var_enforce(config, section, "Interval"); + spatial_profiling_interval = + config_read_int(config, section, "Interval", spatial_profiling_interval); + + /* File name */ + config_var_enforce(config, section, "File"); + file_name = config_read_string(config, section, "File", NULL); + if (!file_name || !*file_name) + fatal("%s: %s: invalid or missing value for 'File'", + si_spatial_report_section_name, section); + spatial_report_filename = str_set(NULL, file_name); + + spatial_report_file = file_open_for_write(spatial_report_filename); + if (!spatial_report_file) + fatal("%s: could not open spatial report file", spatial_report_filename); +} + +void si_cu_spatial_report_init() {} + +void si_cu_spatial_report_done() { + fclose(spatial_report_file); + spatial_report_file = NULL; + str_free(spatial_report_filename); +} + +void si_cu_spatial_report_dump(struct si_compute_unit_t *compute_unit) { + FILE *f = spatial_report_file; + + fprintf(f, + "CU,%d,MemAcc,%lld,MappedWGs,%lld,UnmappedWGs,%lld,ALUIssued,%lld," + "LDSIssued,%lld,Cycles,%lld\n", + compute_unit->id, compute_unit->vector_mem_unit.inflight_mem_accesses, + compute_unit->interval_mapped_work_groups, + compute_unit->interval_unmapped_work_groups, + compute_unit->interval_alu_issued, compute_unit->interval_lds_issued, + asTiming(si_gpu)->cycle); +} + +void si_lds_report_new_inst(struct si_compute_unit_t *compute_unit) { + compute_unit->interval_lds_issued = compute_unit->interval_lds_issued + 1; +} + +void si_alu_report_new_inst(struct si_compute_unit_t *compute_unit) { + compute_unit->interval_alu_issued++; +} + +void si_report_global_mem_inflight(struct si_compute_unit_t *compute_unit, + int long long pending_accesses) { + /* Read stage adds a negative number for accesses added + * Write stage adds a positive number for accesses finished + */ + compute_unit->vector_mem_unit.inflight_mem_accesses += pending_accesses; +} + +void si_report_global_mem_finish(struct si_compute_unit_t *compute_unit, + int long long completed_accesses) { + /* Read stage adds a negative number for accesses added */ + /* Write stage adds a positive number for accesses finished */ + compute_unit->vector_mem_unit.inflight_mem_accesses -= completed_accesses; +} + +void si_report_mapped_work_group(struct si_compute_unit_t *compute_unit) { + /*TODO Add calculation here to change this to wavefront pool entries used */ + compute_unit->interval_mapped_work_groups++; +} + +void si_report_unmapped_work_group(struct si_compute_unit_t *compute_unit) { + /*TODO Add calculation here to change this to wavefront pool entries used */ + compute_unit->interval_unmapped_work_groups++; +} + +void si_cu_interval_update(struct si_compute_unit_t *compute_unit) { + /* If interval - reset the counters in all the engines */ + compute_unit->interval_cycle++; + + if (!(asTiming(si_gpu)->cycle % spatial_profiling_interval)) { + si_cu_spatial_report_dump(compute_unit); + + /* + * This counter is not reset since memory accesses could still + * be in flight in the hierarchy + * compute_unit->inflight_mem_accesses = 0; + */ + compute_unit->interval_cycle = 0; + compute_unit->interval_mapped_work_groups = 0; + compute_unit->interval_unmapped_work_groups = 0; + compute_unit->interval_alu_issued = 0; + compute_unit->interval_lds_issued = 0; + } +} diff --git a/pool/shard000/C/0010495_dimmSpd.c b/pool/shard000/C/0010495_dimmSpd.c new file mode 100644 index 0000000000000000000000000000000000000000..29ed2719d2dc7f19701c029c8dfbc9179cc7447c --- /dev/null +++ b/pool/shard000/C/0010495_dimmSpd.c @@ -0,0 +1,229 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2011 - 2012 Advanced Micro Devices, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "Porting.h" +#include "AGESA.h" +#include "amdlib.h" +#include +#include +#include + +AGESA_STATUS AmdMemoryReadSPD (UINT32 unused1, UINT32 unused2, AGESA_READ_SPD_PARAMS *info); +#define DIMENSION(array)(sizeof (array)/ sizeof (array [0])) + +/* SP5100 GPIO 49-52 contoled by SMBUS PCI_Reg 0x52 */ +#define SP5100_GPIO37_46_47_48 0xA6 +#define SP5100_GPIO49_52 0x50 + +/** + * TODO not support all GPIO yet + * @param reg -GPIO Cntrl Register + * @param out -GPIO bitmap + * @param out -GPIO enable bitmap + * @return old setting + */ +static u8 sp5100_set_gpio(u8 reg, u8 out, u8 enable) +{ + u8 value, ret; + device_t sm_dev = PCI_DEV(0, 0x14, 0); //SMBUS + + value = pci_read_config8(sm_dev, reg); + ret = value; + value &= ~(enable); + value |= out; + value &= ~(enable << 4); + pci_write_config8(sm_dev, reg, value); + + return ret; +} + +static void sp5100_restore_gpio(u8 reg, u8 value) +{ + device_t sm_dev = PCI_DEV(0, 0x14, 0); + pci_write_config8(sm_dev, reg, value); +} + +/*----------------------------------------------------------------------------- + * + * SPD address table - porting required + */ +static const UINT8 spdAddressLookup [1] [2] [2] = { // socket, channel, dimm + /* socket 0 */ + { + {0xA4, 0xA6}, + {0xA0, 0xA2}, + }, + /* socket 1 */ + /* { */ + /* {0xA0, 0xA4, 0xA8}, */ + /* {0xA2, 0xA6, 0xAA}, */ + /* }, */ +}; + +/*----------------------------------------------------------------------------- + * + * readSmbusByteData - read a single SPD byte from any offset + */ + +static int readSmbusByteData (int iobase, int address, char *buffer, int offset) +{ + unsigned int status; + UINT64 limit; + + address |= 1; // set read bit + + outb(0xFF, iobase + 0); // clear error status + outb(0x1F, iobase + 1); // clear error status + outb(offset, iobase + 3); // offset in eeprom + outb(address, iobase + 4); // slave address and read bit + outb(0x48, iobase + 2); // read byte command + + // time limit to avoid hanging for unexpected error status (should never happen) + limit = __rdtsc () + 2000000000 / 10; + for (;;) + { + status = inb(iobase); + if (__rdtsc () > limit) break; + if ((status & 2) == 0) continue; // SMBusInterrupt not set, keep waiting + if ((status & 1) == 1) continue; // HostBusy set, keep waiting + break; + } + + buffer [0] = inb(iobase + 5); + if (status == 2) status = 0; // check for done with no errors + return status; +} + +/*----------------------------------------------------------------------------- + * + * readSmbusByte - read a single SPD byte from the default offset + * this function is faster function readSmbusByteData + */ + +static int readSmbusByte (int iobase, int address, char *buffer) +{ + unsigned int status; + UINT64 limit; + + outb(0xFF, iobase + 0); // clear error status + outb(0x44, iobase + 2); // read command + + // time limit to avoid hanging for unexpected error status + limit = __rdtsc () + 2000000000 / 10; + for (;;) + { + status = inb(iobase); + if (__rdtsc () > limit) break; + if ((status & 2) == 0) continue; // SMBusInterrupt not set, keep waiting + if ((status & 1) == 1) continue; // HostBusy set, keep waiting + break; + } + + buffer [0] = inb(iobase + 5); + if (status == 2) status = 0; // check for done with no errors + return status; +} + +/*--------------------------------------------------------------------------- + * + * readspd - Read one or more SPD bytes from a DIMM. + * Start with offset zero and read sequentially. + * Optimization relies on autoincrement to avoid + * sending offset for every byte. + * Reads 128 bytes in 7-8 ms at 400 KHz. + */ + +static int readspd (int iobase, int SmbusSlaveAddress, char *buffer, int count) +{ + int index, error; + + /* read the first byte using offset zero */ + error = readSmbusByteData (iobase, SmbusSlaveAddress, buffer, 0); + if (error) { + return error; + } + + /* read the remaining bytes using auto-increment for speed */ + for (index = 1; index < count; index++) + { + error = readSmbusByte (iobase, SmbusSlaveAddress, buffer + index); + if (error) + return error; + } + + return 0; +} + +static void setupFch (int ioBase) +{ + outb(66000000 / 400000 / 4, ioBase + 0x0E); /* set SMBus clock to 400 KHz */ +} + +AGESA_STATUS AmdMemoryReadSPD (UINT32 unused1, UINT32 unused2, AGESA_READ_SPD_PARAMS *info) +{ + AGESA_STATUS status; + int spdAddress, ioBase, i; + u8 i2c_channel; + u8 backup; + device_t sm_dev; + + if (info->SocketId >= DIMENSION (spdAddressLookup )) return AGESA_ERROR; + if (info->MemChannelId >= DIMENSION (spdAddressLookup[0] )) return AGESA_ERROR; + if (info->DimmId >= DIMENSION (spdAddressLookup[0][0])) return AGESA_ERROR; + i2c_channel = (UINT8) info->SocketId; + + printk(BIOS_DEBUG, "S=%x, c=%x, d=%x\n", info->SocketId, info->MemChannelId, info->DimmId); + /* set IDTQS3253 i2c channel + * GPIO49,48 control the S1,S0 + * S1 S0 true table + * 0 0 channel 0 + * 0 1 channel 1 + * 1 0 channel 2 - Socket 0 + * 1 1 channel 3 - Socket 1 + * Note: Above is abstracted from Schemetic. But actually it seems to be other way. + * 1 0 channel 2 - Socket 1 + * 1 1 channel 3 - Socket 0 + * Note: The DIMMs need to be plugged in from the farthest slot for each channel. + */ + //backup = sp5100_set_gpio(SP5100_GPIO49_52, 0x1, 0x1); + //sp5100_set_gpio(SP5100_GPIO37_46_47_48, (~i2c_channel & 1) << 3, 0x1 << 3); + + spdAddress = spdAddressLookup [info->SocketId] [info->MemChannelId] [info->DimmId]; + if (spdAddress == 0) + return AGESA_ERROR; + + /* + * SMBus Base Address was set during southbridge early setup. + * e.g. sb700 IO mapped SMBUS_IO_BASE 0x6000, CIMX using 0xB00 as default + */ + sm_dev = pci_locate_device(PCI_ID(PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_SB700_SM), 0); + ioBase = pci_read_config32(sm_dev, 0x90) & (0xFFFFFFF0); + setupFch(ioBase); + + status = readspd(ioBase, spdAddress, (void *)info->Buffer, 256); + for (i=0; i<256; i++) { + printk(BIOS_DEBUG, "%02X ", info->Buffer[i]); + if ((i%16)==15) + printk(BIOS_DEBUG, "\n"); + } + printk(BIOS_DEBUG, "\n"); + //sp5100_restore_gpio(SP5100_GPIO49_52, backup); + + return status; +} diff --git a/pool/shard000/C/0010518_waves_main.c b/pool/shard000/C/0010518_waves_main.c new file mode 100644 index 0000000000000000000000000000000000000000..403f17b2c801ad20f5d27f54fd67628e1450a84a --- /dev/null +++ b/pool/shard000/C/0010518_waves_main.c @@ -0,0 +1,134 @@ +/* + * ===================================================================== + * + * Filename: waves_main.c + * + * Description: + * + * Version: 1.0 + * Created: 04/16/2010 04:04:40 PM + * Revision: none + * Compiler: gcc + * + * Author: Eric Hutton (eh), huttone@colorado.edu + * Company: Community Surface Dynamics Modeling System + * + * ===================================================================== + */ + +#include +#include +#include +#include + +#include "waves_cli.h" +#include "waves_api.h" + +#define WAVES_PROGRAM_STR "waves" +#define WAVES_MAJOR_VERSION (0) +#define WAVES_MINOR_VERSION (1) +#define WAVES_MICRO_VERSION (0) + +double waves_next_angle (GRand * rand, double asymmetry, double highness); + +int +main (int argc, char *argv[]) +{ + waves_args_st *args = NULL; + + GError *error = NULL; + + args = parse_command_line (argc, argv, &error); + g_assert (args); + + if (args->version) + { + fprintf (stdout, "%s %d.%d.%d\n", WAVES_PROGRAM_STR, WAVES_MAJOR_VERSION, + WAVES_MINOR_VERSION, WAVES_MICRO_VERSION); + return EXIT_SUCCESS; + } + + { + gint i; + + double a; + + GRand *rand = g_rand_new_with_seed (args->seed); + + const gint len = args->n_waves; + + const double asymmetry = args->asymmetry; + + const double highness = args->highness; + + const double scale = (args->radians) ? 1. : 180. / M_PI; + + Waves_state *waves_state = NULL; + BMI_Model *w = NULL; + int err; + + if (args->verbose) + { + gchar *units = (args->radians) ? "Radians" : "Degrees"; + + fprintf (stderr, "Highness factor: %f\n", highness); + fprintf (stderr, "Asymmetry factor: %f\n", asymmetry); + fprintf (stderr, "Units: %s\n", units); + } + + fprintf (stdout, "Initializing... "); + err = BMI_WAVES_Initialize (NULL, &w); + + if (err) { + fprintf (stdout, "FAIL.\n"); + fprintf (stderr, "Error: %d: Unable to initialize\n", err); + } + else + fprintf (stdout, "PASS.\n"); + + err = BMI_WAVES_Set_double (w, "wave_asymmetry", &(args->asymmetry)); + err = BMI_WAVES_Set_double (w, "wave_highness", &(args->highness)); + for (i = 0; i < len; i++) { + fprintf (stdout, "Updating... "); + if (BMI_WAVES_Update (w) == BMI_SUCCESS) + fprintf (stdout, "PASS\n"); + else { + fprintf (stdout, "FAIL.\n"); + fprintf (stderr, "Error: %d: Unable to update\n", err); + } + + if (BMI_WAVES_Get_double (w, "sea_surface_wave_from_direction", &a) == BMI_SUCCESS) + fprintf (stdout, "Wave angle: %f\n", a * scale); + else + fprintf (stderr, "Error: %d: Unable to get wave angle\n", err); + } + + fprintf (stdout, "Finalizing... "); + if (BMI_WAVES_Finalize (w) == BMI_SUCCESS) + fprintf (stdout, "PASS\n"); + else { + fprintf (stdout, "FAIL.\n"); + fprintf (stderr, "Error: %d: Unable to finalize\n", err); + } +/* + waves_state = waves_init (NULL); + waves_set_angle_asymmetry (waves_state, args->asymmetry); + waves_set_angle_highness (waves_state, args->highness); + + for (i = 0; i < len; i++) + { + waves_run_until (waves_state, i); + a = waves_get_wave_angle (waves_state) * scale; + //a = waves_next_angle (rand, asymmetry, highness)*scale; + fprintf (stdout, "%f\n", a); + } + + waves_state = waves_finalize (waves_state, TRUE); +*/ + g_rand_free (rand); + } + + g_free (args); + + return EXIT_SUCCESS; +} diff --git a/pool/shard000/C/0010519_capwap_element_80211_wtpradiofailalarm.c b/pool/shard000/C/0010519_capwap_element_80211_wtpradiofailalarm.c new file mode 100644 index 0000000000000000000000000000000000000000..639a1851c79f7fef3514029965788366113fe0c7 --- /dev/null +++ b/pool/shard000/C/0010519_capwap_element_80211_wtpradiofailalarm.c @@ -0,0 +1,75 @@ +#include "capwap.h" +#include "capwap_element.h" + +/******************************************************************** + + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| Radio ID | Type | Status | Pad | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + +Type: 1047 for IEEE 802.11 WTP Radio Fail Alarm Indication + +Length: 4 + +********************************************************************/ + +/* */ +static void capwap_80211_wtpradiofailalarm_element_create(void* data, capwap_message_elements_handle handle, struct capwap_write_message_elements_ops* func) { + struct capwap_80211_wtpradiofailalarm_element* element = (struct capwap_80211_wtpradiofailalarm_element*)data; + + ASSERT(data != NULL); + + func->write_u8(handle, element->radioid); + func->write_u8(handle, element->type); + func->write_u8(handle, element->status); + func->write_u8(handle, element->pad); +} + +/* */ +static void* capwap_80211_wtpradiofailalarm_element_parsing(capwap_message_elements_handle handle, struct capwap_read_message_elements_ops* func) { + struct capwap_80211_wtpradiofailalarm_element* data; + + ASSERT(handle != NULL); + ASSERT(func != NULL); + + if (func->read_ready(handle) != 4) { + capwap_logging_debug("Invalid IEEE 802.11 WTP Radio Fail Alarm Indication element"); + return NULL; + } + + /* */ + data = (struct capwap_80211_wtpradiofailalarm_element*)capwap_alloc(sizeof(struct capwap_80211_wtpradiofailalarm_element)); + memset(data, 0, sizeof(struct capwap_80211_wtpradiofailalarm_element)); + + /* Retrieve data */ + func->read_u8(handle, &data->radioid); + func->read_u8(handle, &data->type); + func->read_u8(handle, &data->status); + func->read_u8(handle, &data->pad); + + return data; +} + +/* */ +static void* capwap_80211_wtpradiofailalarm_element_clone(void* data) { + ASSERT(data != NULL); + + return capwap_clone(data, sizeof(struct capwap_80211_wtpradiofailalarm_element)); +} + +/* */ +static void capwap_80211_wtpradiofailalarm_element_free(void* data) { + ASSERT(data != NULL); + + capwap_free(data); +} + +/* */ +struct capwap_message_elements_ops capwap_element_80211_wtpradiofailalarm_ops = { + .create_message_element = capwap_80211_wtpradiofailalarm_element_create, + .parsing_message_element = capwap_80211_wtpradiofailalarm_element_parsing, + .clone_message_element = capwap_80211_wtpradiofailalarm_element_clone, + .free_message_element = capwap_80211_wtpradiofailalarm_element_free +}; diff --git a/pool/shard000/C/0010551_tacacs.c b/pool/shard000/C/0010551_tacacs.c new file mode 100644 index 0000000000000000000000000000000000000000..e2bbbd4955072978e3a338fc71116cbee3cd1252 --- /dev/null +++ b/pool/shard000/C/0010551_tacacs.c @@ -0,0 +1,143 @@ +/* + * tacacs.c + * + * Copyright 2015 Daniel Mende + */ + +/* + * 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 nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include + +#ifdef _WIN32 +#include +#endif + +#include + +static void tacacs_bf_pre_hash_func(void *proto_data, const char *pre_hash_data, unsigned pre_hash_data_len) { + tacacs_data_t *data = (tacacs_data_t *) proto_data; + MD5_Init(&data->base); + MD5_Update(&data->base, pre_hash_data, pre_hash_data_len); +} + +static int tacacs_bf_hash_func(void *proto_data, const char *secret, const char *hash_data, unsigned hash_data_len) { + tacacs_data_t *data = (tacacs_data_t *) proto_data; + MD5_CTX cur; + unsigned char digest[MD5_DIGEST_LENGTH]; + int i; + unsigned char status, flags; + unsigned short server_msg_len, data_len; + unsigned char cleartext[MD5_DIGEST_LENGTH]; + + memcpy((void *) &cur, &data->base, sizeof(MD5_CTX)); + MD5_Update(&cur, secret, strlen(secret)); + MD5_Update(&cur, hash_data, hash_data_len); + MD5_Final(digest, &cur); + +#if 0 + for (i = 0; i < MD5_DIGEST_LENGTH; i++) { + cleartext[i] = data->ciphertext[i] ^ digest[i]; + } +#else + cleartext[0] = data->ciphertext[0] ^ digest[0]; + cleartext[1] = data->ciphertext[1] ^ digest[1]; + cleartext[2] = data->ciphertext[2] ^ digest[2]; + cleartext[3] = data->ciphertext[3] ^ digest[3]; + cleartext[4] = data->ciphertext[4] ^ digest[4]; + cleartext[5] = data->ciphertext[5] ^ digest[5]; + cleartext[6] = data->ciphertext[6] ^ digest[6]; + cleartext[7] = data->ciphertext[7] ^ digest[7]; + cleartext[8] = data->ciphertext[8] ^ digest[8]; + cleartext[9] = data->ciphertext[9] ^ digest[9]; + cleartext[10] = data->ciphertext[10] ^ digest[10]; + cleartext[11] = data->ciphertext[11] ^ digest[11]; + cleartext[12] = data->ciphertext[12] ^ digest[12]; + cleartext[13] = data->ciphertext[13] ^ digest[13]; + cleartext[14] = data->ciphertext[14] ^ digest[13]; + cleartext[15] = data->ciphertext[15] ^ digest[15]; +#endif + + status = cleartext[0]; + flags = cleartext[1]; + server_msg_len = ntohs(*((unsigned short *) &cleartext[2])); + data_len = ntohs(*((unsigned short *) &cleartext[4])); + + if( ((status >= 0x01 && status <= 0x07) || status == 0x21) && + (flags == 0x01 || flags == 0x00) && + (6 + server_msg_len + data_len == data->ciphertext_len)) { + return 1; + } + return 0; +} + +bf_error tacacs_bf_state_new(bf_state_t **state) { + bf_error error; + tacacs_data_t *proto_data; + + if((error = bf_state_new(state)) > 0) + return error; + + proto_data = malloc(sizeof(tacacs_data_t)); + if(proto_data == NULL) + return BF_ERR_NO_MEM; + proto_data->ciphertext = NULL; + proto_data->ciphertext_len = 0; + if((error = bf_set_proto_data(*state, (void *) proto_data, NULL)) > 0) { + free(proto_data); + return error; + } + if((error = bf_set_pre_hash_func(*state, tacacs_bf_pre_hash_func)) > 0) + return error; + if((error = bf_set_hash_func(*state, tacacs_bf_hash_func)) > 0) + return error; + return BF_SUCCESS; +} + +bf_error tacacs_bf_set_ciphertext(bf_state_t *state, const char *ciphertext, unsigned ciphertext_len) { + tacacs_data_t *data; + BF_CHECK_NULL(state); + BF_CHECK_RUNNING(state); + data = (tacacs_data_t *) state->proto_data; + data->ciphertext = ciphertext; + data->ciphertext_len = ciphertext_len; + return BF_SUCCESS; +} + +bf_error tacacs_bf_get_ciphertext(bf_state_t *state, const char **ciphertext, unsigned *ciphertext_len) { + tacacs_data_t *data; + BF_CHECK_NULL(state); + BF_CHECK_NULL(ciphertext); + BF_CHECK_NULL(ciphertext_len); + data = (tacacs_data_t *) state->proto_data; + *ciphertext = data->ciphertext; + *ciphertext_len = data->ciphertext_len; + return BF_SUCCESS; +} + diff --git a/pool/shard000/C/0010562_game_ai_btable.c b/pool/shard000/C/0010562_game_ai_btable.c new file mode 100644 index 0000000000000000000000000000000000000000..26f3a6e96acc9efa005b91400e0863c4be8d3c65 --- /dev/null +++ b/pool/shard000/C/0010562_game_ai_btable.c @@ -0,0 +1,81 @@ +/* +** game_ai_btable.c for allum in /repo/Epitech/B2/C_Prog_Elem/CPE_2014_allum1/src/game/ai +** +** Made by Nathan Poirier +** Login +** +** Started on Sat Feb 21 13:42:32 2015 Nathan Poirier +** Last update Sun Feb 22 14:02:03 2015 Nathan Poirier +*/ + +#include "allum.h" + +int ai_fill_line(t_btable *table, t_data *data, int nb) +{ + t_my_listitem *it; + t_line *line; + int i; + int count; + + if ((it = my_list_get(data->game.lines_, nb)) == NULL || it->data == NULL || + (table->cnt[nb] = malloc(sizeof(int) * table->col)) == NULL) + return (-1); + my_memset(table->cnt[nb], 0, sizeof(int) * table->col); + line = (t_line *)it->data; + i = 0; + count = line->count; + while (i < table->col && count > 0) + { + table->cnt[nb][i] = count % 2; + table->fin[i] += count % 2; + count /= 2; + i++; + } + return (0); +} + +int ai_fill_btable(t_btable *table, t_data *data) +{ + int i; + + if ((table->row = data->game.lines_->size) <= 0 || + (table->col = game_line_maxcount(data)) <= 0) + return (allum_exit("Error AI Best: Lines or count is 0") - 1); + table->col = table->col / 2 + 1; + if ((table->cnt = malloc(sizeof(int *) * table->row)) == NULL || + (table->fin = malloc(sizeof(int) * table->col)) == NULL || + (table->ana = malloc(sizeof(int) * table->col)) == NULL) + return (allum_exit("%M") - 1); + my_memset(table->fin, 0, sizeof(int) * table->col); + my_memset(table->ana, 0, sizeof(int) * table->col); + i = 0; + while (i < table->row) + { + if (ai_fill_line(table, data, i) == -1) + return (-1); + i++; + } + return (0); +} + +void ai_free_btable(t_btable *table) +{ + int i; + + if (table->cnt != NULL) + { + i = 0; + while (i < table->row) + { + free(table->cnt[i]); + table->cnt[i] = NULL; + i++; + } + free(table->cnt); + table->cnt = NULL; + } + free(table->fin); + table->fin = NULL; + free(table->ana); + table->ana = NULL; +} diff --git a/pool/shard000/C/0010565_unpartition.c b/pool/shard000/C/0010565_unpartition.c new file mode 100644 index 0000000000000000000000000000000000000000..5661e0c9f9280b962e396d8046bdb064d3e3e8ce --- /dev/null +++ b/pool/shard000/C/0010565_unpartition.c @@ -0,0 +1,116 @@ +/* + * StarPU + * Copyright (C) Université Bordeaux 1, CNRS 2008-2010 (see AUTHORS file) + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation; either version 2.1 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 Lesser General Public License in COPYING.LGPL for more details. + */ + +#include +#include +#include +#include +#include + +#define NITER 1000 +#define VECTORSIZE 1024 + +float *buffer; + +starpu_data_handle v_handle; + +static void dummy_codelet(void *descr[], __attribute__ ((unused)) void *_args) +{ +} + +static starpu_codelet cl = { + .where = STARPU_CPU|STARPU_CUDA|STARPU_OPENCL, + .cpu_func = dummy_codelet, +#ifdef STARPU_USE_CUDA + .cuda_func = dummy_codelet, +#endif +#ifdef STARPU_USE_OPENCL + .opencl_func = dummy_codelet, +#endif + .nbuffers = 1 +}; + +int use_handle(starpu_data_handle handle) +{ + int ret; + struct starpu_task *task; + + task = starpu_task_create(); + task->cl = &cl; + task->buffers[0].handle = handle; + task->buffers[0].mode = STARPU_RW; + + ret = starpu_task_submit(task, NULL); + + return ret; +} + +int main(int argc, char **argv) +{ + int ret; + + starpu_init(NULL); + + starpu_data_malloc_pinned_if_possible((void **)&buffer, VECTORSIZE); + + starpu_vector_data_register(&v_handle, 0, (uintptr_t)buffer, VECTORSIZE, sizeof(char)); + + struct starpu_data_filter f = { + .filter_func = starpu_vector_divide_in_2_filter_func, + /* there are only 2 children */ + .nchildren = 2, + /* the length of the first part */ + .filter_arg = VECTORSIZE/2, + .get_nchildren = NULL, + .get_child_ops = NULL + }; + + unsigned iter; + for (iter = 0; iter < NITER; iter++) + { + starpu_data_map_filters(v_handle, 1, &f); + + ret = use_handle(starpu_data_get_sub_data(v_handle, 1, 0)); + if (ret == -ENODEV) + goto enodev; + + ret = use_handle(starpu_data_get_sub_data(v_handle, 1, 1)); + if (ret == -ENODEV) + goto enodev; + + starpu_task_wait_for_all(); + + starpu_data_unpartition(v_handle, 0); + + ret = use_handle(v_handle); + if (ret == -ENODEV) + goto enodev; + + starpu_task_wait_for_all(); + } + + starpu_data_unregister(v_handle); + + starpu_shutdown(); + + return 0; + +enodev: + fprintf(stderr, "WARNING: No one can execute this task\n"); + /* yes, we do not perform the computation but we did detect that no one + * could perform the kernel, so this is not an error from StarPU */ + return 0; +} diff --git a/pool/shard000/C/0010582_lauum.c b/pool/shard000/C/0010582_lauum.c new file mode 100644 index 0000000000000000000000000000000000000000..66cf13196096d842776485a1eee9584edcea554d --- /dev/null +++ b/pool/shard000/C/0010582_lauum.c @@ -0,0 +1,122 @@ +/*********************************************************************/ +/* */ +/* Optimized BLAS libraries */ +/* By Kazushige Goto */ +/* */ +/* Copyright (c) The University of Texas, 2009. All rights reserved. */ +/* UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING */ +/* THIS SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR ANY PARTICULAR PURPOSE, */ +/* NON-INFRINGEMENT AND WARRANTIES OF PERFORMANCE, AND ANY WARRANTY */ +/* THAT MIGHT OTHERWISE ARISE FROM COURSE OF DEALING OR USAGE OF */ +/* TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH RESPECT TO */ +/* THE USE OF THE SOFTWARE OR DOCUMENTATION. */ +/* Under no circumstances shall University be liable for incidental, */ +/* special, indirect, direct or consequential damages or loss of */ +/* profits, interruption of business, or related expenses which may */ +/* arise from use of Software or Documentation, including but not */ +/* limited to those resulting from defects in Software and/or */ +/* Documentation, or loss or inaccuracy of data of any kind. */ +/*********************************************************************/ + +#include +#include "common.h" +#ifdef FUNCTION_PROFILE +#include "functable.h" +#endif + +#ifdef XDOUBLE +#define ERROR_NAME "QLAUUM" +#elif defined(DOUBLE) +#define ERROR_NAME "DLAUUM" +#else +#define ERROR_NAME "SLAUUM" +#endif + +static blasint (*lauum_single[])(blas_arg_t *, BLASLONG *, BLASLONG *, FLOAT *, FLOAT *, BLASLONG) = { + LAUUM_U_SINGLE, LAUUM_L_SINGLE, +}; + +#ifdef SMP +static blasint (*lauum_parallel[])(blas_arg_t *, BLASLONG *, BLASLONG *, FLOAT *, FLOAT *, BLASLONG) = { + LAUUM_U_PARALLEL, LAUUM_L_PARALLEL, +}; +#endif + +int NAME(char *UPLO, blasint *N, FLOAT *a, blasint *ldA, blasint *Info){ + + blas_arg_t args; + + blasint uplo_arg = *UPLO; + blasint uplo; + blasint info; + FLOAT *buffer; +#ifdef PPC440 + extern +#endif + FLOAT *sa, *sb; + + PRINT_DEBUG_NAME; + + args.n = *N; + args.a = (void *)a; + args.lda = *ldA; + + TOUPPER(uplo_arg); + + uplo = -1; + if (uplo_arg == 'U') uplo = 0; + if (uplo_arg == 'L') uplo = 1; + + info = 0; + if (args.lda < MAX(1,args.n)) info = 4; + if (args.n < 0) info = 2; + if (uplo < 0) info = 1; + if (info) { + BLASFUNC(xerbla)(ERROR_NAME, &info, sizeof(ERROR_NAME)); + *Info = - info; + return 0; + } + + *Info = 0; + + if (args.n == 0) return 0; + + IDEBUG_START; + + FUNCTION_PROFILE_START(); + +#ifndef PPC440 + buffer = (FLOAT *)blas_memory_alloc(1); + + sa = (FLOAT *)((BLASLONG)buffer + GEMM_OFFSET_A); + sb = (FLOAT *)(((BLASLONG)sa + ((GEMM_P * GEMM_Q * COMPSIZE * SIZE + GEMM_ALIGN) & ~GEMM_ALIGN)) + GEMM_OFFSET_B); +#endif + +#ifdef SMP + args.common = NULL; + args.nthreads = num_cpu_avail(4); + + if (args.nthreads == 1) { +#endif + + *Info = (lauum_single[uplo])(&args, NULL, NULL, sa, sb, 0); + +#ifdef SMP + } else { + *Info = (lauum_parallel[uplo])(&args, NULL, NULL, sa, sb, 0); + } +#endif + +#ifndef PPC440 + blas_memory_free(buffer); +#endif + + FUNCTION_PROFILE_END(1, .5 * args.n * args.n, + args.n * (1./3. + args.n * ( 1./2. + args.n * 1./6.)) + + 1./6. * args.n * (args.n * args.n - 1)); + + IDEBUG_END; + + return 0; +} diff --git a/pool/shard000/C/0010627_dso_dl.c b/pool/shard000/C/0010627_dso_dl.c new file mode 100644 index 0000000000000000000000000000000000000000..79d2cb4d8c8dae3d7e404b517286fbf5cbdcbcb7 --- /dev/null +++ b/pool/shard000/C/0010627_dso_dl.c @@ -0,0 +1,284 @@ +/* dso_dl.c */ +/* Written by Richard Levitte (richard@levitte.org) for the OpenSSL + * project 2000. + */ +/* ==================================================================== + * Copyright (c) 2000 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * licensing@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED 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 OpenSSL PROJECT 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. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#include +#include "cryptlib.h" +#include + +#ifndef DSO_DL +DSO_METHOD *DSO_METHOD_dl(void) + { + return NULL; + } +#else + +#include + +/* Part of the hack in "dl_load" ... */ +#define DSO_MAX_TRANSLATED_SIZE 256 + +static int dl_load(DSO *dso); +static int dl_unload(DSO *dso); +static void *dl_bind_var(DSO *dso, const char *symname); +static DSO_FUNC_TYPE dl_bind_func(DSO *dso, const char *symname); +#if 0 +static int dl_unbind_var(DSO *dso, char *symname, void *symptr); +static int dl_unbind_func(DSO *dso, char *symname, DSO_FUNC_TYPE symptr); +static int dl_init(DSO *dso); +static int dl_finish(DSO *dso); +static int dl_ctrl(DSO *dso, int cmd, long larg, void *parg); +#endif +static char *dl_name_converter(DSO *dso, const char *filename); + +static DSO_METHOD dso_meth_dl = { + "OpenSSL 'dl' shared library method", + dl_load, + dl_unload, + dl_bind_var, + dl_bind_func, +/* For now, "unbind" doesn't exist */ +#if 0 + NULL, /* unbind_var */ + NULL, /* unbind_func */ +#endif + NULL, /* ctrl */ + dl_name_converter, + NULL, /* init */ + NULL /* finish */ + }; + +DSO_METHOD *DSO_METHOD_dl(void) + { + return(&dso_meth_dl); + } + +/* For this DSO_METHOD, our meth_data STACK will contain; + * (i) the handle (shl_t) returned from shl_load(). + * NB: I checked on HPUX11 and shl_t is itself a pointer + * type so the cast is safe. + */ + +static int dl_load(DSO *dso) + { + shl_t ptr = NULL; + /* We don't do any fancy retries or anything, just take the method's + * (or DSO's if it has the callback set) best translation of the + * platform-independant filename and try once with that. */ + char *filename= DSO_convert_filename(dso, NULL); + + if(filename == NULL) + { + DSOerr(DSO_F_DL_LOAD,DSO_R_NO_FILENAME); + goto err; + } + ptr = shl_load(filename, BIND_IMMEDIATE|DYNAMIC_PATH, 0L); + if(ptr == NULL) + { + DSOerr(DSO_F_DL_LOAD,DSO_R_LOAD_FAILED); + ERR_add_error_data(4, "filename(", filename, "): ", + strerror(errno)); + goto err; + } + if(!sk_push(dso->meth_data, (char *)ptr)) + { + DSOerr(DSO_F_DL_LOAD,DSO_R_STACK_ERROR); + goto err; + } + /* Success, stick the converted filename we've loaded under into the DSO + * (it also serves as the indicator that we are currently loaded). */ + dso->loaded_filename = filename; + return(1); +err: + /* Cleanup! */ + if(filename != NULL) + OPENSSL_free(filename); + if(ptr != NULL) + shl_unload(ptr); + return(0); + } + +static int dl_unload(DSO *dso) + { + shl_t ptr; + if(dso == NULL) + { + DSOerr(DSO_F_DL_UNLOAD,ERR_R_PASSED_NULL_PARAMETER); + return(0); + } + if(sk_num(dso->meth_data) < 1) + return(1); + /* Is this statement legal? */ + ptr = (shl_t)sk_pop(dso->meth_data); + if(ptr == NULL) + { + DSOerr(DSO_F_DL_UNLOAD,DSO_R_NULL_HANDLE); + /* Should push the value back onto the stack in + * case of a retry. */ + sk_push(dso->meth_data, (char *)ptr); + return(0); + } + shl_unload(ptr); + return(1); + } + +static void *dl_bind_var(DSO *dso, const char *symname) + { + shl_t ptr; + void *sym; + + if((dso == NULL) || (symname == NULL)) + { + DSOerr(DSO_F_DL_BIND_VAR,ERR_R_PASSED_NULL_PARAMETER); + return(NULL); + } + if(sk_num(dso->meth_data) < 1) + { + DSOerr(DSO_F_DL_BIND_VAR,DSO_R_STACK_ERROR); + return(NULL); + } + ptr = (shl_t)sk_value(dso->meth_data, sk_num(dso->meth_data) - 1); + if(ptr == NULL) + { + DSOerr(DSO_F_DL_BIND_VAR,DSO_R_NULL_HANDLE); + return(NULL); + } + if (shl_findsym(&ptr, symname, TYPE_UNDEFINED, &sym) < 0) + { + DSOerr(DSO_F_DL_BIND_VAR,DSO_R_SYM_FAILURE); + ERR_add_error_data(4, "symname(", symname, "): ", + strerror(errno)); + return(NULL); + } + return(sym); + } + +static DSO_FUNC_TYPE dl_bind_func(DSO *dso, const char *symname) + { + shl_t ptr; + void *sym; + + if((dso == NULL) || (symname == NULL)) + { + DSOerr(DSO_F_DL_BIND_FUNC,ERR_R_PASSED_NULL_PARAMETER); + return(NULL); + } + if(sk_num(dso->meth_data) < 1) + { + DSOerr(DSO_F_DL_BIND_FUNC,DSO_R_STACK_ERROR); + return(NULL); + } + ptr = (shl_t)sk_value(dso->meth_data, sk_num(dso->meth_data) - 1); + if(ptr == NULL) + { + DSOerr(DSO_F_DL_BIND_FUNC,DSO_R_NULL_HANDLE); + return(NULL); + } + if (shl_findsym(&ptr, symname, TYPE_UNDEFINED, &sym) < 0) + { + DSOerr(DSO_F_DL_BIND_FUNC,DSO_R_SYM_FAILURE); + ERR_add_error_data(4, "symname(", symname, "): ", + strerror(errno)); + return(NULL); + } + return((DSO_FUNC_TYPE)sym); + } + +/* This function is identical to the one in dso_dlfcn.c, but as it is highly + * unlikely that both the "dl" *and* "dlfcn" variants are being compiled at the + * same time, there's no great duplicating the code. Figuring out an elegant + * way to share one copy of the code would be more difficult and would not + * leave the implementations independant. */ +#if defined(__hpux) +static const char extension[] = ".sl"; +#else +static const char extension[] = ".so"; +#endif +static char *dl_name_converter(DSO *dso, const char *filename) + { + char *translated; + int len, rsize, transform; + + len = strlen(filename); + rsize = len + 1; + transform = (strstr(filename, "/") == NULL); + { + /* We will convert this to "%s.s?" or "lib%s.s?" */ + rsize += strlen(extension);/* The length of ".s?" */ + if ((DSO_flags(dso) & DSO_FLAG_NAME_TRANSLATION_EXT_ONLY) == 0) + rsize += 3; /* The length of "lib" */ + } + translated = OPENSSL_malloc(rsize); + if(translated == NULL) + { + DSOerr(DSO_F_DL_NAME_CONVERTER, + DSO_R_NAME_TRANSLATION_FAILED); + return(NULL); + } + if(transform) + { + if ((DSO_flags(dso) & DSO_FLAG_NAME_TRANSLATION_EXT_ONLY) == 0) + sprintf(translated, "lib%s%s", filename, extension); + else + sprintf(translated, "%s%s", filename, extension); + } + else + sprintf(translated, "%s", filename); + return(translated); + } + +#endif /* DSO_DL */ diff --git a/pool/shard000/C/0010637_sumlist.c b/pool/shard000/C/0010637_sumlist.c new file mode 100644 index 0000000000000000000000000000000000000000..4978083834001c8b40d37d30727eef8cf7c2f8a5 --- /dev/null +++ b/pool/shard000/C/0010637_sumlist.c @@ -0,0 +1,103 @@ +/*__________________________________________________________________________ + + sumlist · sigma of a list (int/float) + + Copyright (C) 2002 - 2016 jan schacher + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + revision history: + 20160524 64bit port + 14/07/2003 original release + + +____________________________________________________________________________*/ + +#include "ext.h" +#include "ext_common.h" + +typedef struct sum { + t_object c_ob; + double c_result; + void *c_outlet; +} t_sum; + +void *sum_class; +void *sum_new(long n); +void sum_bang(t_sum *x); +void sum_assist(t_sum *x, void *b, long m, long a, char *s); // assistance method // bang method +void sum_list(t_sum *x, t_symbol *s, short ac, t_atom *av); // list method + +void C74_EXPORT ext_main(void *r) +{ + t_class *c; + c = class_new("sumlist",(method)sum_new, (method)0L, (short)sizeof(t_sum), (method)0L, A_DEFLONG, 0); + + class_addmethod(c, (method)sum_assist, "assist", A_CANT, 0L); + class_addmethod(c, (method)sum_bang, "bang", 0L); + class_addmethod(c, (method)sum_list, "list", A_GIMME,0L); + + class_register(CLASS_BOX, c); + sum_class = c; + + post("· sumlist · jasch · "__DATE__" · © all rights reserved",0); + return; +} + +void *sum_new(long n) +{ + t_sum *x; + x = (t_sum *)object_alloc(sum_class); + if(x){ + x->c_outlet = floatout(x); + x->c_result = 0; + } + return x; +} + void sum_assist(t_sum *x, void *b, long m, long a, char *s) +{ + if ((m==1)&&(a==0)) { + sprintf(s,"input list"); + } + else if ((m==2)&&(a==0)) { + sprintf(s,"sum of list "); + } +} +void sum_bang(t_sum *x) +{ + outlet_float(x->c_outlet, x->c_result); +} + +void sum_list(t_sum *x, t_symbol *s, short ac, t_atom *av) +{ + long i; + + x->c_result = 0; + + for (i=0; ic_result += (double)(av[i].a_w.w_float); + break; + case A_LONG: + x->c_result += (double)(av[i].a_w.w_long); + break; + case A_SYM: + error("wrong argument type for list"); + break; + } + } + outlet_float(x->c_outlet, x->c_result); +} diff --git a/pool/shard000/C/0010640_certs.c b/pool/shard000/C/0010640_certs.c new file mode 100644 index 0000000000000000000000000000000000000000..8b2f05ebabe53c403a8741ef77b234f33191e459 --- /dev/null +++ b/pool/shard000/C/0010640_certs.c @@ -0,0 +1,210 @@ +/* + * Copyright (c) 2019 Cisco and/or its affiliates. + * 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 + +#include + +#include + + +int +ptls_compare_separator_line (const char *line, const char *begin_or_end, + const char *label) +{ + int ret = strncmp (line, "-----", 5); + size_t text_index = 5; + + if (ret == 0) + { + size_t begin_or_end_length = strlen (begin_or_end); + ret = strncmp (line + text_index, begin_or_end, begin_or_end_length); + text_index += begin_or_end_length; + } + + if (ret == 0) + { + ret = line[text_index] - ' '; + text_index++; + } + + if (ret == 0) + { + size_t label_length = strlen (label); + ret = strncmp (line + text_index, label, label_length); + text_index += label_length; + } + + if (ret == 0) + { + ret = strncmp (line + text_index, "-----", 5); + } + + return ret; +} + +int +ptls_get_bio_pem_object (BIO * bio, const char *label, ptls_buffer_t * buf) +{ + int ret = PTLS_ERROR_PEM_LABEL_NOT_FOUND; + char line[256]; + ptls_base64_decode_state_t state; + + /* Get the label on a line by itself */ + while (BIO_gets (bio, line, 256)) + { + if (ptls_compare_separator_line (line, "BEGIN", label) == 0) + { + ret = 0; + ptls_base64_decode_init (&state); + break; + } + } + /* Get the data in the buffer */ + while (ret == 0 && BIO_gets (bio, line, 256)) + { + if (ptls_compare_separator_line (line, "END", label) == 0) + { + if (state.status == PTLS_BASE64_DECODE_DONE + || (state.status == PTLS_BASE64_DECODE_IN_PROGRESS + && state.nbc == 0)) + { + ret = 0; + } + else + { + ret = PTLS_ERROR_INCORRECT_BASE64; + } + break; + } + else + { + ret = ptls_base64_decode (line, &state, buf); + } + } + + return ret; +} + +int +ptls_load_bio_pem_objects (BIO * bio, const char *label, ptls_iovec_t * list, + size_t list_max, size_t * nb_objects) +{ + int ret = 0; + size_t count = 0; + + *nb_objects = 0; + + if (ret == 0) + { + while (count < list_max) + { + ptls_buffer_t buf; + + ptls_buffer_init (&buf, "", 0); + + ret = ptls_get_bio_pem_object (bio, label, &buf); + + if (ret == 0) + { + if (buf.off > 0 && buf.is_allocated) + { + list[count].base = buf.base; + list[count].len = buf.off; + count++; + } + else + { + ptls_buffer_dispose (&buf); + } + } + else + { + ptls_buffer_dispose (&buf); + break; + } + } + } + + if (ret == PTLS_ERROR_PEM_LABEL_NOT_FOUND && count > 0) + { + ret = 0; + } + + *nb_objects = count; + + return ret; +} + +#define PTLS_MAX_CERTS_IN_CONTEXT 16 + +int +ptls_load_bio_certificates (ptls_context_t * ctx, BIO * bio) +{ + int ret = 0; + + ctx->certificates.list = + (ptls_iovec_t *) malloc (PTLS_MAX_CERTS_IN_CONTEXT * + sizeof (ptls_iovec_t)); + + if (ctx->certificates.list == NULL) + { + ret = PTLS_ERROR_NO_MEMORY; + } + else + { + ret = + ptls_load_bio_pem_objects (bio, "CERTIFICATE", ctx->certificates.list, + PTLS_MAX_CERTS_IN_CONTEXT, + &ctx->certificates.count); + } + + return ret; +} + +int +load_bio_certificate_chain (ptls_context_t * ctx, const char *cert_data) +{ + BIO *cert_bio; + cert_bio = BIO_new_mem_buf (cert_data, -1); + if (ptls_load_bio_certificates (ctx, cert_bio) != 0) + { + BIO_free (cert_bio); + return -1; + } + BIO_free (cert_bio); + return 0; +} + +int +load_bio_private_key (ptls_context_t * ctx, const char *pk_data) +{ + static ptls_openssl_sign_certificate_t sc; + EVP_PKEY *pkey; + BIO *key_bio; + + key_bio = BIO_new_mem_buf (pk_data, -1); + pkey = PEM_read_bio_PrivateKey (key_bio, NULL, NULL, NULL); + BIO_free (key_bio); + + if (pkey == NULL) + return -1; + + ptls_openssl_init_sign_certificate (&sc, pkey); + EVP_PKEY_free (pkey); + + ctx->sign_certificate = &sc.super; + return 0; +} diff --git a/pool/shard000/C/0010647_setjmp_t.c b/pool/shard000/C/0010647_setjmp_t.c new file mode 100644 index 0000000000000000000000000000000000000000..374c50cc9912ea00ee8dc1dd2db598b828aab927 --- /dev/null +++ b/pool/shard000/C/0010647_setjmp_t.c @@ -0,0 +1,137 @@ +/* + * Copyright (c) 1991-1994 by Xerox Corporation. All rights reserved. + * + * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED + * OR IMPLIED. ANY USE IS AT YOUR OWN RISK. + * + * Permission is hereby granted to use or copy this program + * for any purpose, provided the above notices are retained on all copies. + * Permission to modify the code and to distribute modified code is granted, + * provided the above notices are retained, and a notice that the code was + * modified is included with the above copyright notice. + */ + +/* Check whether setjmp actually saves registers in jmp_buf. */ +/* If it doesn't, the generic mark_regs code won't work. */ +/* Compilers vary as to whether they will put x in a */ +/* (callee-save) register without -O. The code is */ +/* contrived such that any decent compiler should put x in */ +/* a callee-save register with -O. Thus it is */ +/* recommended that this be run optimized. (If the machine */ +/* has no callee-save registers, then the generic code is */ +/* safe, but this will not be noticed by this piece of */ +/* code.) This test appears to be far from perfect. */ +#include +#include +#include +#include "private/gc_priv.h" + +#ifdef OS2 +/* GETPAGESIZE() is set to getpagesize() by default, but that */ +/* doesn't really exist, and the collector doesn't need it. */ +#define INCL_DOSFILEMGR +#define INCL_DOSMISC +#define INCL_DOSERRORS +#include + +int getpagesize(void) +{ + ULONG result[1]; + + if (DosQuerySysInfo(QSV_PAGE_SIZE, QSV_PAGE_SIZE, + (void *)result, sizeof(ULONG)) != NO_ERROR) { + fprintf(stderr, "DosQuerySysInfo failed\n"); + result[0] = 4096; + } + return((int)(result[0])); +} +#endif + +struct { + char a_a; + char * a_b; +} a; + +int * nested_sp(void) +{ + volatile int sp; + sp = (int)&sp; + return (int *)sp; +} + +int main(void) +{ + volatile word sp; + long ps = GETPAGESIZE(); + jmp_buf b; + register int x = (int)strlen("a"); /* 1, slightly disguised */ + static int y = 0; + + sp = (word)(&sp); + printf("This appears to be a %s running %s\n", MACH_TYPE, OS_TYPE); + if (nested_sp() < (int *)sp) { + printf("Stack appears to grow down, which is the default.\n"); + printf("A good guess for STACKBOTTOM on this machine is 0x%lx.\n", + ((unsigned long)sp + ps) & ~(ps-1)); + } else { + printf("Stack appears to grow up.\n"); + printf("Define STACK_GROWS_UP in gc_private.h\n"); + printf("A good guess for STACKBOTTOM on this machine is 0x%lx.\n", + ((unsigned long)sp + ps) & ~(ps-1)); + } + printf("Note that this may vary between machines of ostensibly\n"); + printf("the same architecture (e.g. Sun 3/50s and 3/80s).\n"); + printf("On many machines the value is not fixed.\n"); + printf("A good guess for ALIGNMENT on this machine is %ld.\n", + (unsigned long)(&(a.a_b))-(unsigned long)(&a)); + + printf("The following is a very dubious test of one root marking" + " strategy.\n"); + printf("Results may not be accurate/useful:\n"); + /* Encourage the compiler to keep x in a callee-save register */ + x = 2*x-1; + printf(""); + x = 2*x-1; + setjmp(b); + if (y == 1) { + if (x == 2) { + printf("Setjmp-based generic mark_regs code probably wont work.\n"); + printf("But we rarely try that anymore. If you have getcontect()\n"); + printf("this probably doesn't matter.\n"); + } else if (x == 1) { + printf("Setjmp-based register marking code may work.\n"); + } else { + printf("Very strange setjmp implementation.\n"); + } + } + y++; + x = 2; + if (y == 1) longjmp(b,1); + printf("Some GC internal configuration stuff: \n"); + printf("\tWORDSZ = %d, ALIGNMENT = %d, GC_GRANULE_BYTES = %d\n", + WORDSZ, ALIGNMENT, GC_GRANULE_BYTES); + printf("\tUsing one mark "); +# if defined(USE_MARK_BYTES) + printf("byte"); +# else + printf("bit"); +# endif + printf(" per "); +# if defined(MARK_BIT_PER_OBJ) + printf("object.\n"); +# elif defined(MARK_BIT_PER_GRANULE) + printf("granule.\n"); +# endif +# ifdef THREAD_LOCAL_ALLOC + printf("Thread local allocation enabled.\n"); +# endif +# ifdef PARALLEL_MARK + printf("Parallel marking enabled.\n"); +# endif + return(0); +} + +int g(int x) +{ + return(x); +} diff --git a/pool/shard000/C/0010656_H5HFstat.c b/pool/shard000/C/0010656_H5HFstat.c new file mode 100644 index 0000000000000000000000000000000000000000..5e5d06ad630a5d79c311f1788e0f6f54df53c871 --- /dev/null +++ b/pool/shard000/C/0010656_H5HFstat.c @@ -0,0 +1,171 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * Copyright by The HDF Group. * + * Copyright by the Board of Trustees of the University of Illinois. * + * All rights reserved. * + * * + * This file is part of HDF5. The full HDF5 copyright notice, including * + * terms governing use, modification, and redistribution, is contained in * + * the COPYING file, which can be found at the root of the source code * + * distribution tree, or in https://www.hdfgroup.org/licenses. * + * If you do not have access to either file, you may request a copy from * + * help@hdfgroup.org. * + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +/* Programmer: Quincey Koziol + * Monday, March 6, 2006 + * + * Purpose: Fractal heap metadata statistics functions. + * + */ + +/****************/ +/* Module Setup */ +/****************/ + +#include "H5HFmodule.h" /* This source code file is part of the H5HF module */ + +/***********/ +/* Headers */ +/***********/ +#include "H5private.h" /* Generic Functions */ +#include "H5Eprivate.h" /* Error handling */ +#include "H5HFpkg.h" /* Fractal heaps */ + +/****************/ +/* Local Macros */ +/****************/ + +/********************/ +/* Package Typedefs */ +/********************/ + +/******************/ +/* Local Typedefs */ +/******************/ + +/********************/ +/* Local Prototypes */ +/********************/ + +/*********************/ +/* Package Variables */ +/*********************/ + +/*****************************/ +/* Library Private Variables */ +/*****************************/ + +/*******************/ +/* Local Variables */ +/*******************/ + +/*------------------------------------------------------------------------- + * Function: H5HF_stat_info + * + * Purpose: Retrieve metadata statistics for the fractal heap + * + * Return: Success: non-negative + * + * Failure: negative + * + * Programmer: Quincey Koziol + * Monday, March 6, 2006 + * + *------------------------------------------------------------------------- + */ +herr_t +H5HF_stat_info(const H5HF_t *fh, H5HF_stat_t *stats) +{ + FUNC_ENTER_NOAPI_NOINIT_NOERR + + /* Check arguments. */ + HDassert(fh); + HDassert(stats); + + /* Report statistics for fractal heap */ + stats->man_size = fh->hdr->man_size; + stats->man_alloc_size = fh->hdr->man_alloc_size; + stats->man_iter_off = fh->hdr->man_iter_off; + stats->man_nobjs = fh->hdr->man_nobjs; + stats->man_free_space = fh->hdr->total_man_free; + stats->huge_size = fh->hdr->huge_size; + stats->huge_nobjs = fh->hdr->huge_nobjs; + stats->tiny_size = fh->hdr->tiny_size; + stats->tiny_nobjs = fh->hdr->tiny_nobjs; + /* XXX: Add more metadata statistics for the heap */ + + FUNC_LEAVE_NOAPI(SUCCEED) +} /* H5HF_stat_info() */ + +/*------------------------------------------------------------------------- + * Function: H5HF_size + * + * Purpose: Retrieve storage info for: + * 1. fractal heap + * 2. btree storage used by huge objects in fractal heap + * 3. free space storage info + * + * Return: non-negative on success, negative on error + * + * Programmer: Vailin Choi + * July 12 2007 + * + *------------------------------------------------------------------------- + */ +herr_t +H5HF_size(const H5HF_t *fh, hsize_t *heap_size) +{ + H5HF_hdr_t *hdr; /* Fractal heap header */ + H5B2_t * bt2 = NULL; /* v2 B-tree handle for index */ + hsize_t meta_size = 0; /* free space storage size */ + herr_t ret_value = SUCCEED; /* Return value */ + + FUNC_ENTER_NOAPI(FAIL) + + /* + * Check arguments. + */ + HDassert(fh); + HDassert(heap_size); + + /* Get "convenience" pointer to fractal heap header */ + hdr = fh->hdr; + + /* Add in values already known */ + *heap_size += hdr->heap_size; /* Heap header */ + *heap_size += hdr->man_alloc_size; /* Direct block storage for "managed" objects */ + *heap_size += hdr->huge_size; /* "huge" object storage */ + + /* Check for indirect blocks for managed objects */ + if (H5F_addr_defined(hdr->man_dtable.table_addr) && hdr->man_dtable.curr_root_rows != 0) + if (H5HF__man_iblock_size(hdr->f, hdr, hdr->man_dtable.table_addr, hdr->man_dtable.curr_root_rows, + NULL, 0, heap_size) < 0) + HGOTO_ERROR(H5E_HEAP, H5E_CANTGET, FAIL, + "unable to get fractal heap storage info for indirect block") + + /* Check for B-tree storage of huge objects in fractal heap */ + if (H5F_addr_defined(hdr->huge_bt2_addr)) { + /* Open the huge object index v2 B-tree */ + if (NULL == (bt2 = H5B2_open(hdr->f, hdr->huge_bt2_addr, hdr->f))) + HGOTO_ERROR(H5E_HEAP, H5E_CANTOPENOBJ, FAIL, + "unable to open v2 B-tree for tracking 'huge' objects") + + /* Get the B-tree storage */ + if (H5B2_size(bt2, heap_size) < 0) + HGOTO_ERROR(H5E_HEAP, H5E_CANTGET, FAIL, "can't retrieve B-tree storage info") + } /* end if */ + + /* Get storage for free-space tracking info */ + if (H5F_addr_defined(hdr->fs_addr)) { + if (H5HF__space_size(hdr, &meta_size) < 0) + HGOTO_ERROR(H5E_HEAP, H5E_CANTGET, FAIL, "can't retrieve FS meta storage info") + *heap_size += meta_size; + } /* end if */ + +done: + /* Release resources */ + if (bt2 && H5B2_close(bt2) < 0) + HDONE_ERROR(H5E_HEAP, H5E_CANTCLOSEOBJ, FAIL, "can't close v2 B-tree for tracking 'huge' objects") + + FUNC_LEAVE_NOAPI(ret_value) +} /* end H5HF_size() */ diff --git a/pool/shard000/C/0010661_test_api11.c b/pool/shard000/C/0010661_test_api11.c new file mode 100644 index 0000000000000000000000000000000000000000..aacc2b27f64282c73be129b8b521a66155f16727 --- /dev/null +++ b/pool/shard000/C/0010661_test_api11.c @@ -0,0 +1,199 @@ +/* + * The Yices SMT Solver. Copyright 2014 SRI International. + * + * This program may only be used subject to the noncommercial end user + * license agreement which is downloadable along with this program. + */ + +/* + * TEST CONVERSIONS TO STRING + */ + +#include +#include +#include + +#include "yices.h" + + +/* + * Test conversion of type tau + * - error = expected error code (0 means no error) + */ +static void test_type_to_string(type_t tau, int32_t error) { + char *s; + error_code_t ecode; + + printf("Testing type_to_string: tau = %"PRId32" (print area = 40 x 10)\n", tau); + fflush(stdout); + + s = yices_type_to_string(tau, 40, 10, 0); + if (s != NULL) { + printf("Result:\n%s", s); + fflush(stdout); + if (error != 0) { + printf("TEST FAILED\n"); + printf("--> Yices function succeeded but NULL output was expected\n"); + fflush(stdout); + exit(1); + } + yices_free_string(s); + } else { + printf("Result = NULL\n"); + fflush(stdout); + printf("error: "); + yices_print_error(stdout); + printf("\n"); + ecode = yices_error_code(); + if (ecode != error) { + printf("TEST FAILED\n"); + printf("--> Yices error code = %"PRId32" bit %"PRId32" was expected\n", ecode, error); + fflush(stdout); + exit(1); + } + } + + printf("\n"); + fflush(stdout); +} + + +/* + * Test conversion of term t + * - error = expected error code (0 means no error) + */ +static void test_term_to_string(term_t t, int32_t error) { + char *s; + error_code_t ecode; + + printf("Testing term_to_string: t = %"PRId32" (print area = 100 x 60)\n", t); + fflush(stdout); + + s = yices_term_to_string(t, 100, 60, 0); + if (s != NULL) { + printf("Result:\n%s", s); + fflush(stdout); + if (error != 0) { + printf("TEST FAILED\n"); + printf("--> Yices function succeeded but NULL output was expected\n"); + fflush(stdout); + exit(1); + } + yices_free_string(s); + } else { + printf("Result = NULL\n"); + fflush(stdout); + printf("error: "); + yices_print_error(stdout); + printf("\n"); + ecode = yices_error_code(); + if (ecode != error) { + printf("TEST FAILED\n"); + printf("--> Yices error code = %"PRId32" bit %"PRId32" was expected\n", ecode, error); + fflush(stdout); + exit(1); + } + } + + printf("\n"); + fflush(stdout); +} + + + +/* + * Arrays of types and terms for testing + */ +#define NUM_TYPES 6 +#define NUM_TERMS 6 + +static type_t type[NUM_TYPES]; +static term_t term[NUM_TERMS]; + + +static void init_types(void) { + type_t aux[3]; + type_t tau; + + type[0] = yices_int_type(); + type[1] = yices_bv_type(123); + type[2] = yices_new_uninterpreted_type(); + yices_set_type_name(type[2], "T"); + + aux[0] = type[2]; + aux[1] = type[2]; + tau = yices_bool_type(); + type[3] = yices_function_type(2, aux, tau); + + aux[0] = type[1]; + aux[1] = type[3]; + aux[2] = type[1]; + type[4] = yices_tuple_type(3, aux); + + aux[0] = type[4]; + aux[1] = type[4]; + aux[2] = type[4]; + type[5] = yices_tuple_type(3, aux); +} + + +static void init_terms(void) { + term_t a, b, c; + type_t tau; + + tau = yices_bv_type(123); + + term[0] = yices_new_uninterpreted_term(tau); + yices_set_term_name(term[0], "X"); + term[1] = yices_bvconst_uint32(123, 111111); + term[2] = yices_new_uninterpreted_term(tau); + yices_set_term_name(term[2], "Y"); + + a = yices_bvand2(term[0], term[1]); + b = yices_bvadd(a, term[2]); + c = yices_bvpower(b, 5); + term[3] = yices_bveq_atom(c, term[1]); + + term[4] = yices_bvxor2(a, c); + term[5] = yices_bvor2(term[4], term[2]); +} + +/* + * Test of type_to_string + */ +static void test_types(void) { + uint32_t i; + + for (i=0; i HDelete + * FSpGetFInfo -> HGetFInfo + * FSpCreate -> HCreate + * FSpOpenDF -> HOpen *** Note: not HOpenDF *** + * FSMakeFSSpec -> (fill in spec by hand.) + * + * (Use HOpen instead of HOpenDF. HOpen is just a glue-interface to PBHOpen, + * which is on all HFS macs. HOpenDF is a System 7 addition which avoids the + * ages-old problem of names starting with a period.) + * + * Contributed by Sam Bushell (jsam@iagu.on.net) and + * Dan Gildor (gyld@in-touch.com). + */ +#if defined(__APPLE__) + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" +#include "jmemsys.h" /* import the system-dependent declarations */ + +#ifndef USE_MAC_MEMMGR /* make sure user got configuration right */ + You forgot to define USE_MAC_MEMMGR in jconfig.h. /* deliberate syntax error */ +#endif + +#include /* we use the MacOS memory manager */ +#include /* we use the MacOS File stuff */ +#include /* we use the MacOS HFS stuff */ +#include /* for smSystemScript */ +#include /* we use Gestalt to test for specific functionality */ + +#ifndef TEMP_FILE_NAME /* can override from jconfig.h or Makefile */ +#define TEMP_FILE_NAME "JPG%03d.TMP" +#endif + +static int next_file_num; /* to distinguish among several temp files */ + + +/* + * Memory allocation and freeing are controlled by the MacOS library + * routines NewPtr() and DisposePtr(), which allocate fixed-address + * storage. Unfortunately, the IJG library isn't smart enough to cope + * with relocatable storage. + */ + +GLOBAL(void *) +jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject) +{ + return (void *) NewPtr(sizeofobject); +} + +GLOBAL(void) +jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject) +{ + DisposePtr((Ptr) object); +} + + +/* + * "Large" objects are treated the same as "small" ones. + * NB: we include FAR keywords in the routine declarations simply for + * consistency with the rest of the IJG code; FAR should expand to empty + * on rational architectures like the Mac. + */ + +GLOBAL(void FAR *) +jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject) +{ + return (void FAR *) NewPtr(sizeofobject); +} + +GLOBAL(void) +jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject) +{ + DisposePtr((Ptr) object); +} + + +/* + * This routine computes the total memory space available for allocation. + */ + +GLOBAL(long) +jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed, + long max_bytes_needed, long already_allocated) +{ + long limit = cinfo->mem->max_memory_to_use - already_allocated; + long slop, mem; + + /* Don't ask for more than what application has told us we may use */ + if (max_bytes_needed > limit && limit > 0) + max_bytes_needed = limit; + /* Find whether there's a big enough free block in the heap. + * CompactMem tries to create a contiguous block of the requested size, + * and then returns the size of the largest free block (which could be + * much more or much less than we asked for). + * We add some slop to ensure we don't use up all available memory. + */ + slop = max_bytes_needed / 16 + 32768L; + mem = CompactMem(max_bytes_needed + slop) - slop; + if (mem < 0) + mem = 0; /* sigh, couldn't even get the slop */ + /* Don't take more than the application says we can have */ + if (mem > limit && limit > 0) + mem = limit; + return mem; +} + + +/* + * Backing store (temporary file) management. + * Backing store objects are only used when the value returned by + * jpeg_mem_available is less than the total space needed. You can dispense + * with these routines if you have plenty of virtual memory; see jmemnobs.c. + */ + + +METHODDEF(void) +read_backing_store (j_common_ptr cinfo, backing_store_ptr info, + void FAR * buffer_address, + long file_offset, long byte_count) +{ + long bytes = byte_count; + long retVal; + + if ( SetFPos ( info->temp_file, fsFromStart, file_offset ) != noErr ) + ERREXIT(cinfo, JERR_TFILE_SEEK); + + retVal = FSRead ( info->temp_file, &bytes, + (unsigned char *) buffer_address ); + if ( retVal != noErr || bytes != byte_count ) + ERREXIT(cinfo, JERR_TFILE_READ); +} + + +METHODDEF(void) +write_backing_store (j_common_ptr cinfo, backing_store_ptr info, + void FAR * buffer_address, + long file_offset, long byte_count) +{ + long bytes = byte_count; + long retVal; + + if ( SetFPos ( info->temp_file, fsFromStart, file_offset ) != noErr ) + ERREXIT(cinfo, JERR_TFILE_SEEK); + + retVal = FSWrite ( info->temp_file, &bytes, + (unsigned char *) buffer_address ); + if ( retVal != noErr || bytes != byte_count ) + ERREXIT(cinfo, JERR_TFILE_WRITE); +} + + +METHODDEF(void) +close_backing_store (j_common_ptr cinfo, backing_store_ptr info) +{ + FSClose ( info->temp_file ); + FSpDelete ( &(info->tempSpec) ); +} + + +/* + * Initial opening of a backing-store object. + * + * This version uses FindFolder to find the Temporary Items folder, + * and puts the temporary file in there. + */ + +GLOBAL(void) +jpeg_open_backing_store (j_common_ptr cinfo, backing_store_ptr info, + long total_bytes_needed) +{ + short tmpRef, vRefNum; + long dirID; + FInfo finderInfo; + FSSpec theSpec; + Str255 fName; + OSErr osErr; + long gestaltResponse = 0; + + /* Check that FSSpec calls are available. */ + osErr = Gestalt( gestaltFSAttr, &gestaltResponse ); + if ( ( osErr != noErr ) + || !( gestaltResponse & (1<temp_name, TEMP_FILE_NAME, next_file_num); + strcpy ( (Ptr)fName+1, info->temp_name ); + *fName = strlen (info->temp_name); + osErr = FSMakeFSSpec ( vRefNum, dirID, fName, &theSpec ); + + if ( (osErr = FSpGetFInfo ( &theSpec, &finderInfo ) ) != noErr ) + break; + } + + osErr = FSpCreate ( &theSpec, '????', '????', smSystemScript ); + if ( osErr != noErr ) + ERREXITS(cinfo, JERR_TFILE_CREATE, info->temp_name); + + osErr = FSpOpenDF ( &theSpec, fsRdWrPerm, &(info->temp_file) ); + if ( osErr != noErr ) + ERREXITS(cinfo, JERR_TFILE_CREATE, info->temp_name); + + info->tempSpec = theSpec; + + info->read_backing_store = read_backing_store; + info->write_backing_store = write_backing_store; + info->close_backing_store = close_backing_store; + TRACEMSS(cinfo, 1, JTRC_TFILE_OPEN, info->temp_name); +} + + +/* + * These routines take care of any system-dependent initialization and + * cleanup required. + */ + +GLOBAL(long) +jpeg_mem_init (j_common_ptr cinfo) +{ + next_file_num = 0; + + /* max_memory_to_use will be initialized to FreeMem()'s result; + * the calling application might later reduce it, for example + * to leave room to invoke multiple JPEG objects. + * Note that FreeMem returns the total number of free bytes; + * it may not be possible to allocate a single block of this size. + */ + return FreeMem(); +} + +GLOBAL(void) +jpeg_mem_term (j_common_ptr cinfo) +{ + /* no work */ +} + +#endif \ No newline at end of file diff --git a/pool/shard000/C/0010670_Mem.c b/pool/shard000/C/0010670_Mem.c new file mode 100644 index 0000000000000000000000000000000000000000..9965888330c84af5275622314607a16d9062d167 --- /dev/null +++ b/pool/shard000/C/0010670_Mem.c @@ -0,0 +1,79 @@ +/* + * Copyright (C) Tildeslash Ltd. All rights reserved. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 3. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + + +#include "Config.h" + +#include +#include +#include + +#include "assert.h" +#include "MemoryException.h" + + +/** + * Implementation of the Mem interface + * + * @file + */ + + +/* ----------------------------------------------------- Protected methods */ + + +#ifdef PACKAGE_PROTECTED +#pragma GCC visibility push(hidden) +#endif + +void *Mem_alloc(long size, const char *func, const char *file, int line){ + assert(size > 0); + void *p = malloc(size); + if (! p) + Exception_throw(&(MemoryException), func, file, line, "%s", System_getLastError()); + return p; +} + + +void *Mem_calloc(long count, long size, const char *func, const char *file, int line) { + assert(count > 0); + assert(size > 0); + void *p = calloc(count, size); + if (! p) + Exception_throw(&(MemoryException), func, file, line, "%s", System_getLastError()); + return p; +} + + +void Mem_free(void *p, const char *func, const char *file, int line) { + if (p) + free(p); +} + + +void *Mem_resize(void *p, long size, const char *func, const char *file, int line) { + assert(p); + assert(size > 0); + p = realloc(p, size); + if (! p) + Exception_throw(&(MemoryException), func, file, line, "%s", System_getLastError()); + return p; +} + +#ifdef PACKAGE_PROTECTED +#pragma GCC visibility pop +#endif + + diff --git a/pool/shard000/C/0010682_rass-dl-mgrf.c b/pool/shard000/C/0010682_rass-dl-mgrf.c new file mode 100644 index 0000000000000000000000000000000000000000..8d322566988e8c3964b5ad565bb3fe8f11708e3d --- /dev/null +++ b/pool/shard000/C/0010682_rass-dl-mgrf.c @@ -0,0 +1,66 @@ +#include +#include +#include +#include +long double x; //x coordinate +long double y; //y coordinate +long double xs[1000000]; //x array +long double h; //height of gaussian at random x value +int k; //counter keeping track of array slots +int i; //counter for each iteration +int j; //counter for number of cycles chosen +long double inp; //number of cycles +long double big; +int conti; +int multi; +long double a = 0.020980978; +long double b = 0.073069578; +long double c = 0.056399424; +long double d = -0.035831687; +int n; + +void counter(long double * array){ + FILE *fp; + char output[]="rass-mgrfs.dat"; + int q; + + fp=fopen(output,"w"); + + for(q=0;q<1000000;q++) { + if (array[q] != 0){ + fprintf(fp,"%Lf\n",array[q]); + } + } + fclose(fp); +} + +int main() { + printf ("Monte Carlo Data Generator for Maser Group Fluxes\n"); + for (i=0;i<1000000;i++){ //calculations per cycle + x = (.3*rand()/RAND_MAX)*10 - 0.3; //random x between 0 and 3 + //printf ("x %Lf \n",x); + y = .15*rand()/RAND_MAX; //random y between 0 and .15 + //printf ("y %Lf \n",y); + h = a + b*x + c*x*x + d*x*x*x; + //printf ("h %Lf \n",h); + if (h >= y){ //under curve? + //printf ("yes \n"); + k++; //select next array slot + xs[k] = x; //save x into slot + } + } + //for(n = 0; n <= 239000; n++) { + //printf("%Lf ", xs[n]); + //} + printf ("\n"); + /* FILE *p; + if((p=fopen("mgrfs.dat","wb"))==NULL){ + printf("\nUnable to open file myfile.dat"); + exit(1); + } + fwrite(xs,sizeof(xs),1,p); + fclose(p);*/ + counter(xs); + printf ("\nThe data points have been saved to rass-mgrfs.dat \n"); + return 0; +} diff --git a/pool/shard000/C/0010711_textfile.c b/pool/shard000/C/0010711_textfile.c new file mode 100644 index 0000000000000000000000000000000000000000..bc76f360325956c05e08a269f7790d4c0493f2c0 --- /dev/null +++ b/pool/shard000/C/0010711_textfile.c @@ -0,0 +1,177 @@ +/* Copyright (c) 1997-1999 Miller Puckette and others. +* For information on usage and redistribution, and for a DISCLAIMER OF ALL +* WARRANTIES, see the file, "LICENSE.txt," in this distribution. */ + +#include "m_pd.h" +#include +#ifdef _WIN32 +#include +#else +#include +#endif + +typedef struct _qlist +{ + t_object x_ob; + t_outlet *x_bangout; + void *x_binbuf; + int x_onset; /* playback position */ + t_clock *x_clock; + t_float x_tempo; + double x_whenclockset; + t_float x_clockdelay; + t_symbol *x_dir; + t_canvas *x_canvas; + int x_reentered; +} t_qlist; + +static t_class *textfile_class; +typedef t_qlist t_textfile; + +static void qlist_rewind(t_qlist *x) +{ + x->x_onset = 0; + if (x->x_clock) clock_unset(x->x_clock); + x->x_whenclockset = 0; + x->x_reentered = 1; +} + +static void qlist_add(t_qlist *x, t_symbol *s, int ac, t_atom *av) +{ + t_atom a; + SETSEMI(&a); + binbuf_add(x->x_binbuf, ac, av); + binbuf_add(x->x_binbuf, 1, &a); +} + +static void qlist_add2(t_qlist *x, t_symbol *s, int ac, t_atom *av) +{ + binbuf_add(x->x_binbuf, ac, av); +} + +static void qlist_clear(t_qlist *x) +{ + qlist_rewind(x); + binbuf_clear(x->x_binbuf); +} + +static void qlist_set(t_qlist *x, t_symbol *s, int ac, t_atom *av) +{ + qlist_clear(x); + qlist_add(x, s, ac, av); +} + +static void qlist_read(t_qlist *x, t_symbol *filename, t_symbol *format) +{ + int cr = 0; + if (!strcmp(format->s_name, "cr")) + cr = 1; + else if (*format->s_name) + pd_error(x, "qlist_read: unknown flag: %s", format->s_name); + + if (binbuf_read_via_canvas(x->x_binbuf, filename->s_name, x->x_canvas, cr)) + pd_error(x, "%s: read failed", filename->s_name); + x->x_onset = 0x7fffffff; + x->x_reentered = 1; +} + +static void qlist_write(t_qlist *x, t_symbol *filename, t_symbol *format) +{ + int cr = 0; + char buf[MAXPDSTRING]; + canvas_makefilename(x->x_canvas, filename->s_name, + buf, MAXPDSTRING); + if (!strcmp(format->s_name, "cr")) + cr = 1; + else if (*format->s_name) + pd_error(x, "qlist_read: unknown flag: %s", format->s_name); + if (binbuf_write(x->x_binbuf, buf, "", cr)) + pd_error(x, "%s: write failed", filename->s_name); +} + +static void qlist_print(t_qlist *x) +{ + post("--------- textfile or qlist contents: -----------"); + binbuf_print(x->x_binbuf); +} + +static void *textfile_new( void) +{ + t_symbol *name, *filename = 0; + t_textfile *x = (t_textfile *)pd_new(textfile_class); + x->x_binbuf = binbuf_new(); + outlet_new(&x->x_ob, &s_list); + x->x_bangout = outlet_new(&x->x_ob, &s_bang); + x->x_onset = 0x7fffffff; + x->x_reentered = 0; + x->x_tempo = 1; + x->x_whenclockset = 0; + x->x_clockdelay = 0; + x->x_clock = NULL; + x->x_canvas = canvas_getcurrent(); + return (x); +} + +static void textfile_bang(t_textfile *x) +{ + int argc = binbuf_getnatom(x->x_binbuf), + count, onset = x->x_onset, onset2; + t_atom *argv = binbuf_getvec(x->x_binbuf); + t_atom *ap = argv + onset, *ap2; + while (onset < argc && + (ap->a_type == A_SEMI || ap->a_type == A_COMMA)) + onset++, ap++; + onset2 = onset; + ap2 = ap; + while (onset2 < argc && + (ap2->a_type != A_SEMI && ap2->a_type != A_COMMA)) + onset2++, ap2++; + if (onset2 > onset) + { + x->x_onset = onset2; + if (ap->a_type == A_SYMBOL) + outlet_anything(x->x_ob.ob_outlet, ap->a_w.w_symbol, + onset2-onset-1, ap+1); + else outlet_list(x->x_ob.ob_outlet, 0, onset2-onset, ap); + } + else + { + x->x_onset = 0x7fffffff; + outlet_bang(x->x_bangout); + } +} + +static void textfile_rewind(t_qlist *x) +{ + x->x_onset = 0; +} + +static void textfile_free(t_textfile *x) +{ + binbuf_free(x->x_binbuf); +} + +void textfile_setup(void ) +{ + textfile_class = class_new(gensym("textfile"), (t_newmethod)textfile_new, + (t_method)textfile_free, sizeof(t_textfile), 0, 0); + class_addmethod(textfile_class, (t_method)textfile_rewind, gensym("rewind"), + 0); + class_addmethod(textfile_class, (t_method)qlist_set, gensym("set"), + A_GIMME, 0); + class_addmethod(textfile_class, (t_method)qlist_clear, gensym("clear"), 0); + class_addmethod(textfile_class, (t_method)qlist_add, gensym("add"), + A_GIMME, 0); + class_addmethod(textfile_class, (t_method)qlist_add2, gensym("add2"), + A_GIMME, 0); + class_addmethod(textfile_class, (t_method)qlist_add, gensym("append"), + A_GIMME, 0); + class_addmethod(textfile_class, (t_method)qlist_read, gensym("read"), + A_SYMBOL, A_DEFSYM, 0); + class_addmethod(textfile_class, (t_method)qlist_write, gensym("write"), + A_SYMBOL, A_DEFSYM, 0); + class_addmethod(textfile_class, (t_method)qlist_print, gensym("print"), + A_DEFSYM, 0); + class_addbang(textfile_class, textfile_bang); +} + diff --git a/pool/shard000/C/0010712_atmelXPqnx.c b/pool/shard000/C/0010712_atmelXPqnx.c new file mode 100644 index 0000000000000000000000000000000000000000..5440951a1b8699afc6306a1f1ad4f947efeddb7e --- /dev/null +++ b/pool/shard000/C/0010712_atmelXPqnx.c @@ -0,0 +1,142 @@ +#include + +//We define this in vnet_qnx.h based on which directory we are compiling in. +#if defined(REV_D) +#include "fwr_d.h" +#elif defined(REV_E) +#include "fwr_e.h" +#elif defined(R504) +#include "fwr504.h" +#elif defined(R504_2958) +#include "fwr504_2958.h" +#elif defined(R504A_2958) +#include "fwr504a_2958.h" +#elif defined(PCI) +#include "fwr506.h" +#elif defined(RFMD) +#include "fwr.h" +#elif defined(RFMD_3COM) +#include "fwr_3COM.h" +#endif //REV_D + +VOID CardReadUshort(PVNet_ADAPTER Adapter, UCHAR Offset, PUSHORT pData) +{ + *pData = in16(Adapter->IoBase + (Offset)); +} + + +VOID CardWriteUshort(PVNet_ADAPTER Adapter, UCHAR Offset, USHORT Data) +{ + out16((Adapter->IoBase + Offset),Data); + if (Offset == AR) { + USHORT i; + USHORT temp; + for(i=0;i<10;i++) { + CardReadUshort(Adapter, Offset,&temp); + if (temp == (USHORT) Data ) + break; + out16((Adapter->IoBase + Offset),Data); + } + if(temp != (USHORT)Data) IF_LOUD(DbgPrint("FAILED TO SET AR REG\n")); + } +} + + +VOID CardWriteUchar(PVNet_ADAPTER Adapter, UCHAR Offset, UCHAR Data) +{ + out8((Adapter->IoBase + Offset),Data); +} + +VOID CardReadUchar(PVNet_ADAPTER Adapter, UCHAR Offset, PUCHAR pData) +{ + *(pData) = in8(Adapter->IoBase + Offset); +} + + +void SetMgmtTimer(PVNet_ADAPTER Adapter) +{ + struct itimerspec tvalue; + + if(timer_getexpstatus(Adapter->MgmtTimer)!= 0) { + /* Initialze timer */ + tvalue.it_value.tv_sec = 2; + tvalue.it_interval.tv_sec = tvalue.it_interval.tv_nsec =0; + tvalue.it_value.tv_nsec = 56 * 1000000; + + timer_settime(Adapter->MgmtTimer,0,&tvalue,0); //2.56 seconds. + } +} +VOID VnetSleep(ULONG stime) +{ +usleep(stime); +} + +BOOLEAN GetDefaultFw(PVNet_ADAPTER Adapter) +{ + Nic_t *nic = (Nic_t *)Adapter->extra; + atmel_handle_t *handle = (atmel_handle_t *)nic->ext; + ULONG SoFw = sizeof(BasicFW); + + IF_LOUD(DbgPrint("--=+>GetFwFile BasicFW : %d, \n",SoFw);) + + Adapter->MappedFirmwareBuffer = (PUCHAR)handle->ion->alloc(SoFw,NULL); //XXX: FREE THIS SOMEWHERE + + IF_LOUD(DbgPrint("Fw Mapped in : 0x%08X\n",Adapter->MappedFirmwareBuffer);) + VNetZeroMemory(Adapter->MappedFirmwareBuffer, SoFw); + VNetMoveMemory(Adapter->MappedFirmwareBuffer, BasicFW, SoFw); + Adapter->FirmwareFileLength = SoFw; + IF_LOUD(DbgPrint("<=- Out of GetFwFile\n");) + return TRUE; +} + +VOID +RxIndicatePacket(PVNet_ADAPTER Adapter, PUCHAR pRxBuf, ULONG PacketLength, ULONG IndicateLen) +{ + npkt_t *npkt; + net_buf_t *nb; + Nic_t *nic = (Nic_t *)Adapter->extra; + atmel_handle_t *handle = (atmel_handle_t *)nic->ext; + + IF_LOUD(DbgPrint(">> RxIndicatePacket PacketLen = %d, IndicateLen = %d",PacketLength,IndicateLen);) + + pthread_mutex_lock(&handle->mutex); + + npkt = atmel_fetchnpkt(nic,FALSE); + nb = (net_buf_t *)TAILQ_FIRST(&npkt->buffers); + + //is this a ethernet packet or 80211B ??? + VNetMoveMemory(nb->net_iov->iov_base,pRxBuf,PacketLength); + //Reset the packet... + npkt->next = NULL; + npkt->num_complete = 1; + npkt->req_complete = 0; + npkt->ref_cnt = 1; + npkt->flags = _NPKT_UP | _NPKT_NOT_TXED; + npkt->tot_iov = 1; + nb->net_iov->iov_len = PacketLength; + npkt->framelen = PacketLength; + npkt->cell = handle->cell; + npkt->iface = 0; + npkt->endpoint = handle->endpoint; + + handle->rxtxstats.rx_bytes += PacketLength; + + + if( (npkt = handle->ion->tx_up_start(handle->reg_hdlp,npkt,0,0,handle->cell,handle->endpoint,0,&handle))) { + IF_LOUD(DbgPrint("packet NOT acceped by IO-NET!!");) + } + pthread_mutex_unlock(&handle->mutex); +IF_LOUD(DbgPrint("<< RxIndicatePacket\n");) +} + +VOID IndicateConnectionStatus(PVNet_ADAPTER Adapter, BOOLEAN Connected) +{ + if(Connected==TRUE){ + }else{ + } +} + +VOID +TxIndicateCompletion(PVNet_ADAPTER Adapter) +{ +} diff --git a/pool/shard000/C/0010716_hostname-util.c b/pool/shard000/C/0010716_hostname-util.c new file mode 100644 index 0000000000000000000000000000000000000000..ee48b86dd2947d3adb5d7bed74e78207f355e82a --- /dev/null +++ b/pool/shard000/C/0010716_hostname-util.c @@ -0,0 +1,256 @@ +/*** + This file is part of systemd. + + Copyright 2015 Lennart Poettering + + systemd is free software; you can redistribute it and/or modify it + under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation; either version 2.1 of the License, or + (at your option) any later version. + + systemd is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with systemd; If not, see . +***/ + +#include "nm-sd-adapt.h" + +#include +#include +#include +#include +#include +#include + +#include "fd-util.h" +#include "fileio.h" +#include "hostname-util.h" +#include "macro.h" +#include "string-util.h" + +bool hostname_is_set(void) { + struct utsname u; + + assert_se(uname(&u) >= 0); + + if (isempty(u.nodename)) + return false; + + /* This is the built-in kernel default host name */ + if (streq(u.nodename, "(none)")) + return false; + + return true; +} + +char* gethostname_malloc(void) { + struct utsname u; + + /* This call tries to return something useful, either the actual hostname + * or it makes something up. The only reason it might fail is OOM. + * It might even return "localhost" if that's set. */ + + assert_se(uname(&u) >= 0); + + if (isempty(u.nodename) || streq(u.nodename, "(none)")) + return strdup(u.sysname); + + return strdup(u.nodename); +} + +int gethostname_strict(char **ret) { + struct utsname u; + char *k; + + /* This call will rather fail than make up a name. It will not return "localhost" either. */ + + assert_se(uname(&u) >= 0); + + if (isempty(u.nodename)) + return -ENXIO; + + if (streq(u.nodename, "(none)")) + return -ENXIO; + + if (is_localhost(u.nodename)) + return -ENXIO; + + k = strdup(u.nodename); + if (!k) + return -ENOMEM; + + *ret = k; + return 0; +} + +static bool hostname_valid_char(char c) { + return + (c >= 'a' && c <= 'z') || + (c >= 'A' && c <= 'Z') || + (c >= '0' && c <= '9') || + c == '-' || + c == '_' || + c == '.'; +} + +/** + * Check if s looks like a valid host name or FQDN. This does not do + * full DNS validation, but only checks if the name is composed of + * allowed characters and the length is not above the maximum allowed + * by Linux (c.f. dns_name_is_valid()). Trailing dot is allowed if + * allow_trailing_dot is true and at least two components are present + * in the name. Note that due to the restricted charset and length + * this call is substantially more conservative than + * dns_name_is_valid(). + */ +bool hostname_is_valid(const char *s, bool allow_trailing_dot) { + unsigned n_dots = 0; + const char *p; + bool dot; + + if (isempty(s)) + return false; + + /* Doesn't accept empty hostnames, hostnames with + * leading dots, and hostnames with multiple dots in a + * sequence. Also ensures that the length stays below + * HOST_NAME_MAX. */ + + for (p = s, dot = true; *p; p++) { + if (*p == '.') { + if (dot) + return false; + + dot = true; + n_dots++; + } else { + if (!hostname_valid_char(*p)) + return false; + + dot = false; + } + } + + if (dot && (n_dots < 2 || !allow_trailing_dot)) + return false; + + if (p-s > HOST_NAME_MAX) /* Note that HOST_NAME_MAX is 64 on + * Linux, but DNS allows domain names + * up to 255 characters */ + return false; + + return true; +} + +char* hostname_cleanup(char *s) { + char *p, *d; + bool dot; + + assert(s); + + strshorten(s, HOST_NAME_MAX); + + for (p = s, d = s, dot = true; *p; p++) { + if (*p == '.') { + if (dot) + continue; + + *(d++) = '.'; + dot = true; + } else if (hostname_valid_char(*p)) { + *(d++) = *p; + dot = false; + } + + } + + if (dot && d > s) + d[-1] = 0; + else + *d = 0; + + return s; +} + +bool is_localhost(const char *hostname) { + assert(hostname); + + /* This tries to identify local host and domain names + * described in RFC6761 plus the redhatism of .localdomain */ + + return strcaseeq(hostname, "localhost") || + strcaseeq(hostname, "localhost.") || + strcaseeq(hostname, "localdomain.") || + strcaseeq(hostname, "localdomain") || + endswith_no_case(hostname, ".localhost") || + endswith_no_case(hostname, ".localhost.") || + endswith_no_case(hostname, ".localdomain") || + endswith_no_case(hostname, ".localdomain."); +} + +#if 0 /* NM_IGNORED */ +bool is_gateway_hostname(const char *hostname) { + assert(hostname); + + /* This tries to identify the valid syntaxes for the our + * synthetic "gateway" host. */ + + return + strcaseeq(hostname, "gateway") || + strcaseeq(hostname, "gateway."); +} + +int sethostname_idempotent(const char *s) { + char buf[HOST_NAME_MAX + 1] = {}; + + assert(s); + + if (gethostname(buf, sizeof(buf)) < 0) + return -errno; + + if (streq(buf, s)) + return 0; + + if (sethostname(s, strlen(s)) < 0) + return -errno; + + return 1; +} + +int read_hostname_config(const char *path, char **hostname) { + _cleanup_fclose_ FILE *f = NULL; + char l[LINE_MAX]; + char *name = NULL; + + assert(path); + assert(hostname); + + f = fopen(path, "re"); + if (!f) + return -errno; + + /* may have comments, ignore them */ + FOREACH_LINE(l, f, return -errno) { + truncate_nl(l); + if (l[0] != '\0' && l[0] != '#') { + /* found line with value */ + name = hostname_cleanup(l); + name = strdup(name); + if (!name) + return -ENOMEM; + break; + } + } + + if (!name) + /* no non-empty line found */ + return -ENOENT; + + *hostname = name; + return 0; +} +#endif /* NM_IGNORED */ diff --git a/pool/shard000/C/0010721_romstage.c b/pool/shard000/C/0010721_romstage.c new file mode 100644 index 0000000000000000000000000000000000000000..8c99080071c69432b62f194a7e1c02a4a5195d37 --- /dev/null +++ b/pool/shard000/C/0010721_romstage.c @@ -0,0 +1,286 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2006 AMD + * (Written by Yinghai Lu for AMD) + * Copyright (C) 2006 MSI + * (Written by Bingxun Shi for MSI) + * Copyright (C) 2008 Rudolf Marek + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc. + */ + +unsigned int get_sbdn(unsigned bus); + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "northbridge/amd/amdk8/reset_test.c" +#include "northbridge/amd/amdk8/debug.c" +#include +#include +#include "southbridge/via/vt8237r/early_smbus.c" +#include +#include "northbridge/amd/amdk8/setup_resource_map.c" +#include + +#define SERIAL_DEV PNP_DEV(0x2e, IT8712F_SP1) +#define GPIO_DEV PNP_DEV(0x2e, IT8712F_GPIO) +#define CLKIN_DEV PNP_DEV(0x2e, IT8712F_GPIO) + +#define IT8712F_GPIO_BASE 0x0a20 + +static void memreset(int controllers, const struct mem_controller *ctrl) { } +static void activate_spd_rom(const struct mem_controller *ctrl) { } + +static inline int spd_read_byte(unsigned device, unsigned address) +{ + return smbus_read_byte(device, address); +} + +#include "southbridge/via/k8t890/early_car.c" +#include +#include "northbridge/amd/amdk8/incoherent_ht.c" +#include "northbridge/amd/amdk8/coherent_ht.c" +#include "northbridge/amd/amdk8/raminit_f.c" +#include "lib/generic_sdram.c" +#include "cpu/amd/dualcore/dualcore.c" +#include "cpu/amd/model_fxx/init_cpus.c" +#include "cpu/amd/model_fxx/fidvid.c" +#include "northbridge/amd/amdk8/resourcemap.c" + +void soft_reset(void) +{ + uint8_t tmp; + + set_bios_reset(); + printk(BIOS_DEBUG, "soft reset\n"); + + /* PCI reset */ + tmp = pci_read_config8(PCI_DEV(0, 0x11, 0), 0x4f); + tmp |= 0x01; + /* FIXME from S3 set bit1 to disable USB reset VT8237A/S */ + pci_write_config8(PCI_DEV(0, 0x11, 0), 0x4f, tmp); + + halt(); +} + +unsigned int get_sbdn(unsigned bus) +{ + device_t dev; + + dev = pci_locate_device_on_bus(PCI_ID(PCI_VENDOR_ID_VIA, + PCI_DEVICE_ID_VIA_VT8237R_LPC), bus); + return (dev >> 15) & 0x1f; +} + +struct gpio_init_val { + u8 addr; + u8 val; +}; + +static const struct gpio_init_val gpio_init_data[] = { + /* multi-function pin selection */ + { 0x25, 0x00 }, + { 0x28, 0x00 }, /* gp46 is infrared receive input */ + { 0x29, 0x40 }, /* reserved value?!? */ + { 0x2a, 0x00 }, + { 0x2c, 0x1d }, /* pin91 is VIN7 instead of PCIRSTIN# */ + /* gpio i/o port base */ + { 0x62, IT8712F_GPIO_BASE >> 8 }, + { 0x63, IT8712F_GPIO_BASE & 0xff }, + /* 0xb8 - 0xbc: gpio pull-up enable */ + { 0xb8, 0x00 }, + /* 0xc0 - 0xc4: gpio alternate function select */ + { 0xc0, 0x00 }, + { 0xc3, 0x00 }, + { 0xc4, 0xc0 }, + /* 0xc8 - 0xcc: gpio output enable */ + { 0xc8, 0x00 }, + { 0xcb, 0x00 }, + { 0xcc, 0xc0 }, + /* end of list */ + { 0, 0 }, +}; + +static void m2v_it8712f_gpio_init(void) +{ + const struct gpio_init_val *giv; + + printk(BIOS_SPEW, "it8712f gpio init...\n"); + + /* + * it8712f gpio config + * + * Most importantly this switches pin 91 from + * PCIRSTIN# to VIN7. + * Note that only PCIRST3# and PCIRST5# are affected + * by PCIRSTIN#, the PCIRST1#, PCIRST2#, PCIRST4# are always + * direct buffers of #LRESET (low pin count bus reset). + * If this is not done All PCIRST are in reset state and the + * pcie slots don't initialize. + * + * pci reset handling: + * pin 91: VIN7 (alternate PCIRSTIN#) + * pin 48: PCIRST5# / gpio port 5 bit 0 + * pin 84: PCIRST4# / gpio port 1 bit 0 + * pin 31: PCIRST1# / gpio port 1 bit 4 + * pin 33: PCIRST2# / gpio port 1 bit 2 + * pin 34: PCIRST3# / gpio port 1 bit 1 + * + * PCIRST[0-5]# are connected as follows: + * pcirst1# -> pci bus + * pcirst2# -> ide bus + * pcirst3# -> pcie devices + * pcirst4# -> pcie graphics + * pcirst5# -> maybe n/c (untested) + * + * For software control of PCIRST[1-5]#: + * 0x2a=0x17 (deselect pcirst# hardwiring, enable 0x25 control) + * 0x25=0x17 (select gpio function) + * 0xc0=0x17, 0xc8=0x17 gpio port 1 select & output enable + * 0xc4=0xc1, 0xcc=0xc1 gpio port 5 select & output enable + */ + giv = gpio_init_data; + while (giv->addr) { + printk(BIOS_SPEW, "it8712f gpio: %02x=%02x\n", + giv->addr, giv->val); + ite_reg_write(IT8712F_GPIO, giv->addr, giv->val); + giv++; + } + + printk(BIOS_INFO, "it8712f gpio: Setting DDR2 voltage to 1.80V\n"); + /* + * upper two bits of gpio_base+4 control ddr2 voltage: + * 11: 1.80V + * 01: 1.85V + * 10: 1.90V + * 00: 1.95V + * + * The lower six bits are inputs and normally read back as 1 + * (except bit 2, which seems rather random). + */ + outb(0xff, IT8712F_GPIO_BASE+4); +} + +static void m2v_bus_init(void) +{ + device_t dev; + + printk(BIOS_SPEW, "m2v_bus_init\n"); + + dev = pci_locate_device(PCI_ID(PCI_VENDOR_ID_VIA, + PCI_DEVICE_ID_VIA_K8T890CF_0), 0); + pci_write_config8(dev, K8T890_MULTIPLE_FN_EN, 0x01); + + dev = pci_locate_device(PCI_ID(PCI_VENDOR_ID_VIA, + PCI_DEVICE_ID_VIA_K8T890CF_5), 0); + /* + * bit | meaning + * 6 | 0: hide scratch register function 0:0.6 (we don't use it) + * 5 | 1: enable pcie bridge 0:2.0 + * 4 | 0: hide pcie bridge 0:3.3 (not connected) + * 3 | 1: enable pcie bridge 0:3.2 + * 2 | 1: enable pcie bridge 0:3.1 + * 1 | 1: enable pcie bridge 0:3.0 + */ + pci_write_config8(dev, 0xf0, 0x2e); +} + +void cache_as_ram_main(unsigned long bist, unsigned long cpu_init_detectedx) +{ + static const uint16_t spd_addr[] = { + // Node 0 + DIMM0, DIMM2, 0, 0, + DIMM1, DIMM3, 0, 0, + // Node 1 + DIMM4, DIMM6, 0, 0, + DIMM5, DIMM7, 0, 0, + }; + unsigned bsp_apicid = 0; + int needs_reset = 0; + struct sys_info *sysinfo = &sysinfo_car; + + ite_conf_clkin(CLKIN_DEV, ITE_UART_CLK_PREDIVIDE_24); + ite_enable_serial(SERIAL_DEV, CONFIG_TTYS0_BASE); + ite_kill_watchdog(GPIO_DEV); + console_init(); + enable_rom_decode(); + m2v_bus_init(); + m2v_it8712f_gpio_init(); + ite_enable_3vsbsw(GPIO_DEV); + + printk(BIOS_INFO, "now booting...\n"); + + if (bist == 0) + bsp_apicid = init_cpus(cpu_init_detectedx, sysinfo); + + /* Halt if there was a built in self test failure. */ + report_bist_failure(bist); + setup_default_resource_map(); + setup_coherent_ht_domain(); + wait_all_core0_started(); + + printk(BIOS_INFO, "now booting... All core 0 started\n"); + +#if CONFIG_LOGICAL_CPUS + /* It is said that we should start core1 after all core0 launched. */ + start_other_cores(); + wait_all_other_cores_started(bsp_apicid); +#endif + init_timer(); + ht_setup_chains_x(sysinfo); /* Init sblnk and sbbusn, nodes, sbdn. */ + + needs_reset = optimize_link_coherent_ht(); + printk(BIOS_DEBUG, "%02x", needs_reset); + needs_reset |= optimize_link_incoherent_ht(sysinfo); + printk(BIOS_DEBUG, "%02x", needs_reset); + needs_reset |= k8t890_early_setup_ht(); + printk(BIOS_DEBUG, "%02x", needs_reset); + + if (needs_reset) { + printk(BIOS_DEBUG, "ht reset -\n"); + soft_reset(); + printk(BIOS_DEBUG, "FAILED!\n"); + } + + /* the HT settings needs to be OK, because link freq chnage may cause HT disconnect */ + /* allow LDT STOP asserts */ + vt8237_sb_enable_fid_vid(); + + enable_fid_change(); + printk(BIOS_DEBUG, "after enable_fid_change\n"); + + init_fidvid_bsp(bsp_apicid); + + /* Stop the APs so we can start them later in init. */ + allow_all_aps_stop(bsp_apicid); + + /* It's the time to set ctrl now. */ + fill_mem_ctrl(sysinfo->nodes, sysinfo->ctrl, spd_addr); + enable_smbus(); + sdram_initialize(sysinfo->nodes, sysinfo->ctrl, sysinfo); + post_cache_as_ram(); +} diff --git a/pool/shard000/C/0010723_wavelet-blur.c b/pool/shard000/C/0010723_wavelet-blur.c new file mode 100644 index 0000000000000000000000000000000000000000..1743a149f7c1eeefa1284213d724e82ad6070433 --- /dev/null +++ b/pool/shard000/C/0010723_wavelet-blur.c @@ -0,0 +1,289 @@ +/* This file is an image processing operation for GEGL + * GEGL is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * GEGL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GEGL; if not, see . + * + * Copyright 2016 Miroslav Talasek + * + * Wavelet blur used in wavelet decompose filter + * theory is from original wavelet plugin + * + */ + +#include "config.h" +#include + +#ifdef GEGL_PROPERTIES + + +property_double (radius, _("Radius"), 1.0) + description (_("Radius of the wavelet blur")) + value_range (0.0, 1500.0) + ui_range (0.0, 256.0) + ui_gamma (3.0) + ui_meta ("unit", "pixel-distance") + ui_meta ("radius", "blur") + + +#else + +#define GEGL_OP_AREA_FILTER +#define GEGL_OP_NAME wavelet_blur +#define GEGL_OP_C_SOURCE wavelet-blur.c + +#include "gegl-op.h" +#include +#include + + +static gint +wav_gen_convolve_matrix (gdouble radius, + gdouble **cmatrix_p); + + + +static gint +wav_calc_convolve_matrix_length (gdouble radius) +{ + return ceil (radius) * 2 + 1; +} + +static gint +wav_gen_convolve_matrix (gdouble radius, + gdouble **cmatrix_p) +{ + gint matrix_length; + gdouble *cmatrix; + + matrix_length = wav_calc_convolve_matrix_length (radius); + cmatrix = g_new (gdouble, matrix_length); + + if (matrix_length == 1) + { + cmatrix[0] = 1; + } + else + { + gint i; + + for (i = 0; i < matrix_length; i++) + { + if (i == 0 || i == matrix_length - 1) + { + cmatrix[i] = 0.25; + } + else if (i == matrix_length / 2) + { + cmatrix[i] = 0.5; + } + else + { + cmatrix[i] = 0; + } + } + } + + *cmatrix_p = cmatrix; + return matrix_length; +} + +static inline void +wav_get_mean_pixel_1D (gfloat *src, + gfloat *dst, + gint components, + gdouble *cmatrix, + gint matrix_length) +{ + gint i, c; + gint offset; + gdouble acc[components]; + + for (c = 0; c < components; ++c) + acc[c] = 0; + + offset = 0; + + for (i = 0; i < matrix_length; i++) + { + for (c = 0; c < components; ++c) + acc[c] += src[offset++] * cmatrix[i]; + } + + for (c = 0; c < components; ++c) + dst[c] = acc[c]; +} + +static void +wav_hor_blur (GeglBuffer *src, + GeglBuffer *dst, + const GeglRectangle *dst_rect, + gdouble *cmatrix, + gint matrix_length, + const Babl *format) +{ + gint u, v; + const gint radius = matrix_length / 2; + const gint nc = babl_format_get_n_components (format); + + GeglRectangle write_rect = {dst_rect->x, dst_rect->y, dst_rect->width, 1}; + gfloat *dst_buf = gegl_malloc (write_rect.width * sizeof(gfloat) * nc); + + GeglRectangle read_rect = {dst_rect->x - radius, dst_rect->y, dst_rect->width + matrix_length -1, 1}; + gfloat *src_buf = gegl_malloc (read_rect.width * sizeof(gfloat) * nc); + + for (v = 0; v < dst_rect->height; v++) + { + gint offset = 0; + read_rect.y = dst_rect->y + v; + write_rect.y = dst_rect->y + v; + gegl_buffer_get (src, &read_rect, 1.0, format, src_buf, GEGL_AUTO_ROWSTRIDE, GEGL_ABYSS_NONE); + + for (u = 0; u < dst_rect->width; u++) + { + wav_get_mean_pixel_1D (src_buf + offset, + dst_buf + offset, + nc, + cmatrix, + matrix_length); + offset += nc; + } + + gegl_buffer_set (dst, &write_rect, 0, format, dst_buf, GEGL_AUTO_ROWSTRIDE); + } + + gegl_free (src_buf); + gegl_free (dst_buf); +} + +static void +wav_ver_blur (GeglBuffer *src, + GeglBuffer *dst, + const GeglRectangle *dst_rect, + gdouble *cmatrix, + gint matrix_length, + const Babl *format) +{ + gint u,v; + const gint radius = matrix_length / 2; + const gint nc = babl_format_get_n_components (format); + + GeglRectangle write_rect = {dst_rect->x, dst_rect->y, 1, dst_rect->height}; + gfloat *dst_buf = gegl_malloc (write_rect.height * sizeof(gfloat) * nc); + + GeglRectangle read_rect = {dst_rect->x, dst_rect->y - radius , 1, dst_rect->height + matrix_length -1}; + gfloat *src_buf = gegl_malloc (read_rect.height * sizeof(gfloat) * nc); + + for (u = 0; u < dst_rect->width; u++) + { + gint offset = 0; + read_rect.x = dst_rect->x + u; + write_rect.x = dst_rect->x + u; + gegl_buffer_get (src, &read_rect, 1.0, format, src_buf, GEGL_AUTO_ROWSTRIDE, GEGL_ABYSS_NONE); + + for (v = 0; v < dst_rect->height; v++) + { + wav_get_mean_pixel_1D (src_buf + offset, + dst_buf + offset, + nc, + cmatrix, + matrix_length); + offset += nc; + } + + gegl_buffer_set (dst, &write_rect, 0, format, dst_buf, GEGL_AUTO_ROWSTRIDE); + } + + gegl_free (src_buf); + gegl_free (dst_buf); +} + +static void +prepare (GeglOperation *operation) +{ + GeglOperationAreaFilter *area = GEGL_OPERATION_AREA_FILTER (operation); + GeglProperties *o = GEGL_PROPERTIES (operation); + + + /* XXX: these should be calculated exactly considering o->filter, but we just + * make sure there is enough space */ + area->left = area->right = ceil (o->radius); + area->top = area->bottom = ceil (o->radius); + + gegl_operation_set_format (operation, "input", + babl_format ("R'G'B' float")); + gegl_operation_set_format (operation, "output", + babl_format ("R'G'B' float")); +} + +static gboolean +process (GeglOperation *operation, + GeglBuffer *input, + GeglBuffer *output, + const GeglRectangle *result, + gint level) +{ + GeglRectangle rect; + GeglBuffer *temp; + GeglOperationAreaFilter *op_area = GEGL_OPERATION_AREA_FILTER (operation); + GeglProperties *o = GEGL_PROPERTIES (operation); + const Babl *format = gegl_operation_get_format (operation, "output"); + + GeglRectangle temp_extend; + gdouble *cmatrix; + gint cmatrix_len; + + rect.x = result->x - op_area->left; + rect.width = result->width + op_area->left + op_area->right; + rect.y = result->y - op_area->top; + rect.height = result->height + op_area->top + op_area->bottom; + + + gegl_rectangle_intersect (&temp_extend, &rect, gegl_buffer_get_extent (input)); + temp_extend.x = result->x; + temp_extend.width = result->width; + temp = gegl_buffer_new (&temp_extend, format); + + cmatrix_len = wav_gen_convolve_matrix (o->radius, &cmatrix); + wav_hor_blur (input, temp, &temp_extend, cmatrix, cmatrix_len, format); + wav_ver_blur (temp, output, result, cmatrix, cmatrix_len, format); + g_free (cmatrix); + + g_object_unref (temp); + return TRUE; +} + + +static void +gegl_op_class_init (GeglOpClass *klass) +{ + GeglOperationClass *operation_class; + GeglOperationFilterClass *filter_class; + + operation_class = GEGL_OPERATION_CLASS (klass); + filter_class = GEGL_OPERATION_FILTER_CLASS (klass); + + operation_class->prepare = prepare; + operation_class->opencl_support = FALSE; + + filter_class->process = process; + + gegl_operation_class_set_keys (operation_class, + "name", "gegl:wavelet-blur", + "title", _("Wavelet Blur"), +// "license", "LGPL3+", + "categories", "blur", + "reference-hash", "ae56a8da120f29554bafa08789aa37b6", + "description", _("This blur is used for the wavelet decomposition filter, each pixel is computed from another by the HAT transform"), + NULL); +} + +#endif diff --git a/pool/shard000/C/0010724_main.c b/pool/shard000/C/0010724_main.c new file mode 100644 index 0000000000000000000000000000000000000000..5fef9a92f4da449605b71d81603fa87c67013964 --- /dev/null +++ b/pool/shard000/C/0010724_main.c @@ -0,0 +1,58 @@ +/* $FreeBSD$ */ +#include +#include +#include +#include + +u_long NBUCKETS = 2000; +u_long NOPS = 200000; +u_long NSIZE = (16*1024); + +char **foo; + +int +main(int argc, char **argv) +{ + u_long i,j,k; + + if (argc > 1) NOPS = strtoul(argv[1],0,0); + if (argc > 2) NBUCKETS = strtoul(argv[2],0,0); + if (argc > 3) NSIZE = strtoul(argv[3],0,0); + printf("BRK(0)=%p ", sbrk(0)); + foo = malloc(sizeof(*foo) * NBUCKETS); + memset(foo, 0, sizeof(*foo) * NBUCKETS); + for (i = 1; i <= 4096; i *= 2) { + for (j = 0; j < 40960/i && j < NBUCKETS; j++) { + foo[j] = malloc(i); + } + for (j = 0; j < 40960/i && j < NBUCKETS; j++) { + free(foo[j]); + foo[j] = NULL; + } + } + + for (i = 0; i < NOPS; i++) { + j = random() % NBUCKETS; + k = random() % NSIZE; + foo[j] = realloc(foo[j], k & 1 ? 0 : k); + if (k & 1 || k == 0) { + /* + * Workaround because realloc return bogus pointer rather than + * NULL if passed zero length. + */ + foo[j] = NULL; + } + if (foo[j]) + foo[j][0] = 1; + } + printf("BRK(1)=%p ", sbrk(0)); + for (j = 0; j < NBUCKETS; j++) { + if (foo[j]) { + free(foo[j]); + foo[j] = NULL; + } + } + printf("BRK(2)=%p NOPS=%lu NBUCKETS=%lu NSIZE=%lu\n", + sbrk(0), NOPS, NBUCKETS, NSIZE); + return 0; +} diff --git a/pool/shard000/C/0010734_conf.c b/pool/shard000/C/0010734_conf.c new file mode 100644 index 0000000000000000000000000000000000000000..eba96e5f0e2fb3556b77349c650c99127bf975cd --- /dev/null +++ b/pool/shard000/C/0010734_conf.c @@ -0,0 +1,83 @@ +#include "../apue.h" +#include +#include + +static void pr_sysconf(char *, int); +static void pr_pathconf(char *, char *, int); + +int +main(int argc, char *argv[]) +{ + if (argc != 2) + err_quit("usage: a.out "); + +#ifdef ARG_MAX + printf("ARG_MAX defined to be %ld\n", (long)ARG_MAX+0); +#else + printf("no symbol for ARG_MAX\n"); +#endif +#ifdef _SC_ARG_MAX + pr_sysconf("ARG_MAX =", _SC_ARG_MAX); +#else + printf("no symbol for _SC_ARG_MAX\n"); +#endif + +/* similar processing for all the rest of the sysconf symbols... */ + +#ifdef MAX_CANON + printf("MAX_CANON defined to be %ld\n", (long)MAX_CANON+0); +#else + printf("no symbol for MAX_CANON\n"); +#endif +#ifdef _PC_MAX_CANON + pr_pathconf("MAX_CANON =", argv[1], _PC_MAX_CANON); +#else + printf("no symbol for _PC_MAX_CANON\n"); +#endif + +/* similar processing for all the rest of the pathconf symbols... */ + + exit(0); +} + +static void +pr_sysconf(char *mesg, int name) +{ + long val; + + fputs(mesg, stdout); + errno = 0; + if ((val = sysconf(name)) < 0) { + if (errno != 0) { + if (errno == EINVAL) + fputs(" (not supported)\n", stdout); + else + err_sys("sysconf error"); + } else { + fputs(" (no limit)\n", stdout); + } + } else { + printf(" %ld\n", val); + } +} + +static void +pr_pathconf(char *mesg, char *path, int name) +{ + long val; + + fputs(mesg, stdout); + errno = 0; + if ((val = pathconf(path, name)) < 0) { + if (errno != 0) { + if (errno == EINVAL) + fputs(" (not supported)\n", stdout); + else + err_sys("pathconf error, path = %s", path); + } else { + fputs(" (no limit)\n", stdout); + } + } else { + printf(" %ld\n", val); + } +} diff --git a/pool/shard000/C/0010742_print.c b/pool/shard000/C/0010742_print.c new file mode 100644 index 0000000000000000000000000000000000000000..92a0078e0454ee0c7a6b95863297068c77f0b503 --- /dev/null +++ b/pool/shard000/C/0010742_print.c @@ -0,0 +1,30 @@ +#include "types.h" +#include "print.h" +#include "serial.h" + +void putch(char c) +{ + __putch(c); + if (c == '\n') + __putch('\r'); +} + +static const char hexdigets[] = + { '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; + +void printhex(u32 u) +{ + int i; + + for (i = 0; i < 8; i++) { + u32 c = u >> (28 - (i * 4)); + __putch(hexdigets[c & 0xf]); + } +} + +void putstr(const char *s) +{ + while (*s) + putch(*s++); +} diff --git a/pool/shard000/C/0010756_mongoc-buffer.c b/pool/shard000/C/0010756_mongoc-buffer.c new file mode 100644 index 0000000000000000000000000000000000000000..df023a011569a1c6c1f484e4b1c95309cc5a3e9b --- /dev/null +++ b/pool/shard000/C/0010756_mongoc-buffer.c @@ -0,0 +1,358 @@ +/* + * Copyright 2013 MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include + +#include "mongoc-error.h" +#include "mongoc-buffer-private.h" +#include "mongoc-trace-private.h" + + +#undef MONGOC_LOG_DOMAIN +#define MONGOC_LOG_DOMAIN "buffer" + +#ifndef MONGOC_BUFFER_DEFAULT_SIZE +#define MONGOC_BUFFER_DEFAULT_SIZE 1024 +#endif + + +#define SPACE_FOR(_b, _sz) \ + (((ssize_t) (_b)->datalen - (ssize_t) (_b)->len) >= (ssize_t) (_sz)) + + +/** + * _mongoc_buffer_init: + * @buffer: A mongoc_buffer_t to initialize. + * @buf: A data buffer to attach to @buffer. + * @buflen: The size of @buflen. + * @realloc_func: A function to resize @buf. + * + * Initializes @buffer for use. If additional space is needed by @buffer, then + * @realloc_func will be called to resize @buf. + * + * @buffer takes ownership of @buf and will realloc it to zero bytes when + * cleaning up the data structure. + */ +void +_mongoc_buffer_init (mongoc_buffer_t *buffer, + uint8_t *buf, + size_t buflen, + bson_realloc_func realloc_func, + void *realloc_data) +{ + BSON_ASSERT (buffer); + BSON_ASSERT (buflen || !buf); + + if (!realloc_func) { + realloc_func = bson_realloc_ctx; + } + + if (!buflen) { + buflen = MONGOC_BUFFER_DEFAULT_SIZE; + } + + if (!buf) { + buf = (uint8_t *) realloc_func (NULL, buflen, NULL); + } + + memset (buffer, 0, sizeof *buffer); + + buffer->data = buf; + buffer->datalen = buflen; + buffer->len = 0; + buffer->realloc_func = realloc_func; + buffer->realloc_data = realloc_data; +} + + +/** + * _mongoc_buffer_destroy: + * @buffer: A mongoc_buffer_t. + * + * Cleanup after @buffer and release any allocated resources. + */ +void +_mongoc_buffer_destroy (mongoc_buffer_t *buffer) +{ + BSON_ASSERT (buffer); + + if (buffer->data && buffer->realloc_func) { + buffer->realloc_func (buffer->data, 0, buffer->realloc_data); + } + + memset (buffer, 0, sizeof *buffer); +} + + +/** + * _mongoc_buffer_clear: + * @buffer: A mongoc_buffer_t. + * @zero: If the memory should be zeroed. + * + * Clears a buffers contents and resets it to initial state. You can request + * that the memory is zeroed, which might be useful if you know the contents + * contain security related information. + */ +void +_mongoc_buffer_clear (mongoc_buffer_t *buffer, bool zero) +{ + BSON_ASSERT (buffer); + + if (zero) { + memset (buffer->data, 0, buffer->datalen); + } + + buffer->len = 0; +} + + +bool +_mongoc_buffer_append (mongoc_buffer_t *buffer, + const uint8_t *data, + size_t data_size) +{ + uint8_t *buf; + + ENTRY; + + BSON_ASSERT (buffer); + BSON_ASSERT (data_size); + + BSON_ASSERT (buffer->datalen); + BSON_ASSERT ((buffer->datalen + data_size) < INT_MAX); + + if (!SPACE_FOR (buffer, data_size)) { + if (buffer->len) { + memmove (&buffer->data[0], buffer->data, buffer->len); + } + + if (!SPACE_FOR (buffer, data_size)) { + buffer->datalen = bson_next_power_of_two (data_size + buffer->len); + buffer->data = (uint8_t *) buffer->realloc_func ( + buffer->data, buffer->datalen, NULL); + } + } + + buf = &buffer->data[buffer->len]; + + BSON_ASSERT ((buffer->len + data_size) <= buffer->datalen); + + memcpy (buf, data, data_size); + + buffer->len += data_size; + + RETURN (true); +} + + +/** + * mongoc_buffer_append_from_stream: + * @buffer; A mongoc_buffer_t. + * @stream: The stream to read from. + * @size: The number of bytes to read. + * @timeout_msec: The number of milliseconds to wait or -1 for the default + * @error: A location for a bson_error_t, or NULL. + * + * Reads from stream @size bytes and stores them in @buffer. This can be used + * in conjunction with reading RPCs from a stream. You read from the stream + * into this buffer and then scatter the buffer into the RPC. + * + * Returns: true if successful; otherwise false and @error is set. + */ +bool +_mongoc_buffer_append_from_stream (mongoc_buffer_t *buffer, + mongoc_stream_t *stream, + size_t size, + int32_t timeout_msec, + bson_error_t *error) +{ + uint8_t *buf; + ssize_t ret; + + ENTRY; + + BSON_ASSERT (buffer); + BSON_ASSERT (stream); + BSON_ASSERT (size); + + BSON_ASSERT (buffer->datalen); + BSON_ASSERT ((buffer->datalen + size) < INT_MAX); + + if (!SPACE_FOR (buffer, size)) { + if (buffer->len) { + memmove (&buffer->data[0], buffer->data, buffer->len); + } + + if (!SPACE_FOR (buffer, size)) { + buffer->datalen = bson_next_power_of_two (size + buffer->len); + buffer->data = (uint8_t *) buffer->realloc_func ( + buffer->data, buffer->datalen, NULL); + } + } + + buf = &buffer->data[buffer->len]; + + BSON_ASSERT ((buffer->len + size) <= buffer->datalen); + + ret = mongoc_stream_read (stream, buf, size, size, timeout_msec); + if (ret != size) { + bson_set_error (error, + MONGOC_ERROR_STREAM, + MONGOC_ERROR_STREAM_SOCKET, + "Failed to read %" PRIu64 + " bytes: socket error or timeout", + (uint64_t) size); + RETURN (false); + } + + buffer->len += ret; + + RETURN (true); +} + + +/** + * _mongoc_buffer_fill: + * @buffer: A mongoc_buffer_t. + * @stream: A stream to read from. + * @min_bytes: The minumum number of bytes to read. + * @error: A location for a bson_error_t or NULL. + * + * Attempts to fill the entire buffer, or at least @min_bytes. + * + * Returns: The number of buffered bytes, or -1 on failure. + */ +ssize_t +_mongoc_buffer_fill (mongoc_buffer_t *buffer, + mongoc_stream_t *stream, + size_t min_bytes, + int32_t timeout_msec, + bson_error_t *error) +{ + ssize_t ret; + size_t avail_bytes; + + ENTRY; + + BSON_ASSERT (buffer); + BSON_ASSERT (stream); + + BSON_ASSERT (buffer->data); + BSON_ASSERT (buffer->datalen); + + if (min_bytes <= buffer->len) { + RETURN (buffer->len); + } + + min_bytes -= buffer->len; + + if (buffer->len) { + memmove (&buffer->data[0], buffer->data, buffer->len); + } + + if (!SPACE_FOR (buffer, min_bytes)) { + buffer->datalen = bson_next_power_of_two (buffer->len + min_bytes); + buffer->data = (uint8_t *) buffer->realloc_func ( + buffer->data, buffer->datalen, buffer->realloc_data); + } + + avail_bytes = buffer->datalen - buffer->len; + + ret = mongoc_stream_read ( + stream, &buffer->data[buffer->len], avail_bytes, min_bytes, timeout_msec); + + if (ret == -1) { + bson_set_error (error, + MONGOC_ERROR_STREAM, + MONGOC_ERROR_STREAM_SOCKET, + "Failed to buffer %u bytes", + (unsigned) min_bytes); + RETURN (-1); + } + + buffer->len += ret; + + if (buffer->len < min_bytes) { + bson_set_error (error, + MONGOC_ERROR_STREAM, + MONGOC_ERROR_STREAM_SOCKET, + "Could only buffer %u of %u bytes", + (unsigned) buffer->len, + (unsigned) min_bytes); + RETURN (-1); + } + + RETURN (buffer->len); +} + + +/** + * mongoc_buffer_try_append_from_stream: + * @buffer; A mongoc_buffer_t. + * @stream: The stream to read from. + * @size: The number of bytes to read. + * @timeout_msec: The number of milliseconds to wait or -1 for the default + * + * Reads from stream @size bytes and stores them in @buffer. This can be used + * in conjunction with reading RPCs from a stream. You read from the stream + * into this buffer and then scatter the buffer into the RPC. + * + * Returns: bytes read if successful; otherwise 0 or -1. + */ +ssize_t +_mongoc_buffer_try_append_from_stream (mongoc_buffer_t *buffer, + mongoc_stream_t *stream, + size_t size, + int32_t timeout_msec) +{ + uint8_t *buf; + ssize_t ret; + + ENTRY; + + BSON_ASSERT (buffer); + BSON_ASSERT (stream); + BSON_ASSERT (size); + + BSON_ASSERT (buffer->datalen); + BSON_ASSERT ((buffer->datalen + size) < INT_MAX); + + if (!SPACE_FOR (buffer, size)) { + if (buffer->len) { + memmove (&buffer->data[0], buffer->data, buffer->len); + } + + if (!SPACE_FOR (buffer, size)) { + buffer->datalen = bson_next_power_of_two (size + buffer->len); + buffer->data = (uint8_t *) buffer->realloc_func ( + buffer->data, buffer->datalen, NULL); + } + } + + buf = &buffer->data[buffer->len]; + + BSON_ASSERT ((buffer->len + size) <= buffer->datalen); + + ret = mongoc_stream_read (stream, buf, size, 0, timeout_msec); + + if (ret > 0) { + buffer->len += ret; + } + + RETURN (ret); +} diff --git a/pool/shard000/C/0010767_hash.c b/pool/shard000/C/0010767_hash.c new file mode 100644 index 0000000000000000000000000000000000000000..868830a7cdbc615d533e6d36c30fb8923ef0df4d --- /dev/null +++ b/pool/shard000/C/0010767_hash.c @@ -0,0 +1,66 @@ +// hash.c +#include +#include +#include +#include "rechner.h" +int hash_append(command* rootnode,command* newnode) +{ + command* nextnode = rootnode; + while(nextnode->next != NULL) + nextnode = nextnode->next; + nextnode->next = newnode; + +} + +void print_hash(command* rootnode) +{ + command* nextnode = rootnode; + while(nextnode->next != NULL) + { + nextnode = nextnode->next; + printf("NODE %s %i \n",nextnode->command,nextnode->arg); + + } + +} +void unload_hash(command *rootnode) +{ + command *tmp = rootnode; + command *fwd; + + while(tmp != NULL) { + fwd = tmp->next; + free(tmp->command); + free(tmp); + tmp = fwd; + } +} +int count_nodes(command *rootnode) +{ + int i = 0; + command* nextnode = rootnode; + while(nextnode->next != NULL) + { + nextnode = nextnode->next; + i++; + } + return i+1; + +} +command* getnode(command *rootnode,int nr) +{ + int i = 0; + command* nextnode = rootnode; + while(nextnode->next != NULL) + { + if(i == nr) + return nextnode; + nextnode = nextnode->next; + + i++; + } + if(i == nr) + return nextnode; + return NULL; + +} \ No newline at end of file diff --git a/pool/shard000/C/0010785_process.c b/pool/shard000/C/0010785_process.c new file mode 100644 index 0000000000000000000000000000000000000000..7060ce7684d545c38d2af68c908fb4f1effd0b3d --- /dev/null +++ b/pool/shard000/C/0010785_process.c @@ -0,0 +1,236 @@ +/* + * This file is subject to the terms and conditions of the GNU General Public + * License. See the file "COPYING" in the main directory of this archive + * for more details. + * + * Copyright (C) 1994 - 1999, 2000 by Ralf Baechle and others. + * Copyright (C) 1999, 2000 Silicon Graphics, Inc. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +asmlinkage int cpu_idle(void) +{ + /* endless idle loop with no priority at all */ + init_idle(); + current->nice = 20; + current->counter = -100; + while (1) { + while (!current->need_resched) + if (wait_available) + __asm__("wait"); + schedule(); + check_pgt_cache(); + } +} + +struct task_struct *last_task_used_math = NULL; + +asmlinkage void ret_from_fork(void); + +void exit_thread(void) +{ + /* Forget lazy fpu state */ + if (IS_FPU_OWNER()) { + set_cp0_status(ST0_CU1, ST0_CU1); + __asm__ __volatile__("cfc1\t$0,$31"); + CLEAR_FPU_OWNER(); + } +} + +void flush_thread(void) +{ + /* Forget lazy fpu state */ + if (IS_FPU_OWNER()) { + set_cp0_status(ST0_CU1, ST0_CU1); + __asm__ __volatile__("cfc1\t$0,$31"); + CLEAR_FPU_OWNER(); + } +} + +int copy_thread(int nr, unsigned long clone_flags, unsigned long usp, + unsigned long unused, + struct task_struct * p, struct pt_regs * regs) +{ + struct pt_regs * childregs; + long childksp; + + childksp = (unsigned long)p + KERNEL_STACK_SIZE - 32; + + if (IS_FPU_OWNER()) { + save_fp(p); + } + /* set up new TSS. */ + childregs = (struct pt_regs *) childksp - 1; + *childregs = *regs; + childregs->regs[7] = 0; /* Clear error flag */ + if (current->personality == PER_LINUX) { + childregs->regs[2] = 0; /* Child gets zero as return value */ + regs->regs[2] = p->pid; + } else { + /* Under IRIX things are a little different. */ + childregs->regs[2] = 0; + childregs->regs[3] = 1; + regs->regs[2] = p->pid; + regs->regs[3] = 0; + } + if (childregs->cp0_status & ST0_CU0) { + childregs->regs[28] = (unsigned long) p; + childregs->regs[29] = childksp; + p->thread.current_ds = KERNEL_DS; + } else { + childregs->regs[29] = usp; + p->thread.current_ds = USER_DS; + } + p->thread.reg29 = (unsigned long) childregs; + p->thread.reg31 = (unsigned long) ret_from_fork; + + /* + * New tasks loose permission to use the fpu. This accelerates context + * switching for most programs since they don't use the fpu. + */ + p->thread.cp0_status = read_32bit_cp0_register(CP0_STATUS) & + ~(ST0_CU3|ST0_CU2|ST0_CU1|ST0_KSU); + childregs->cp0_status &= ~(ST0_CU3|ST0_CU2|ST0_CU1); + + return 0; +} + +/* Fill in the fpu structure for a core dump.. */ +int dump_fpu(struct pt_regs *regs, elf_fpregset_t *r) +{ + /* We actually store the FPU info in the task->thread + * area. + */ + if(regs->cp0_status & ST0_CU1) { + memcpy(r, ¤t->thread.fpu, sizeof(current->thread.fpu)); + return 1; + } + return 0; /* Task didn't use the fpu at all. */ +} + +/* Fill in the user structure for a core dump.. */ +void dump_thread(struct pt_regs *regs, struct user *dump) +{ + dump->magic = CMAGIC; + dump->start_code = current->mm->start_code; + dump->start_data = current->mm->start_data; + dump->start_stack = regs->regs[29] & ~(PAGE_SIZE - 1); + dump->u_tsize = (current->mm->end_code - dump->start_code) + >> PAGE_SHIFT; + dump->u_dsize = (current->mm->brk + (PAGE_SIZE - 1) - dump->start_data) + >> PAGE_SHIFT; + dump->u_ssize = (current->mm->start_stack - dump->start_stack + + PAGE_SIZE - 1) >> PAGE_SHIFT; + memcpy(&dump->regs[0], regs, sizeof(struct pt_regs)); + memcpy(&dump->regs[EF_SIZE/4], ¤t->thread.fpu, + sizeof(current->thread.fpu)); +} + +/* + * Create a kernel thread + */ +int kernel_thread(int (*fn)(void *), void *arg, unsigned long flags) +{ + int retval; + + __asm__ __volatile__( + "move\t$6, $sp\n\t" + "move\t$4, %5\n\t" + "li\t$2, %1\n\t" + "syscall\n\t" + "beq\t$6, $sp, 1f\n\t" + "move\t$4, %3\n\t" + "jalr\t%4\n\t" + "move\t$4, $2\n\t" + "li\t$2, %2\n\t" + "syscall\n" + "1:\tmove\t%0, $2" + :"=r" (retval) + :"i" (__NR_clone), "i" (__NR_exit), "r" (arg), "r" (fn), + "r" (flags | CLONE_VM) + + /* The called subroutine might have destroyed any of the + * at, result, argument or temporary registers ... */ + :"$1", "$2", "$3", "$4", "$5", "$6", "$7", "$8", + "$9","$10","$11","$12","$13","$14","$15","$24","$25"); + + return retval; +} + +/* + * These bracket the sleeping functions.. + */ +extern void scheduling_functions_start_here(void); +extern void scheduling_functions_end_here(void); +#define first_sched ((unsigned long) scheduling_functions_start_here) +#define last_sched ((unsigned long) scheduling_functions_end_here) + +/* get_wchan - a maintenance nightmare ... */ +unsigned long get_wchan(struct task_struct *p) +{ + unsigned long frame, pc; + + if (!p || p == current || p->state == TASK_RUNNING) + return 0; + + pc = thread_saved_pc(&p->thread); + if (pc < first_sched || pc >= last_sched) + goto out; + + if (pc >= (unsigned long) sleep_on_timeout) + goto schedule_timeout_caller; + if (pc >= (unsigned long) sleep_on) + goto schedule_caller; + if (pc >= (unsigned long) interruptible_sleep_on_timeout) + goto schedule_timeout_caller; + if (pc >= (unsigned long)interruptible_sleep_on) + goto schedule_caller; + goto schedule_timeout_caller; + +schedule_caller: + frame = ((unsigned long *)p->thread.reg30)[10]; + pc = ((unsigned long *)frame)[7]; + goto out; + +schedule_timeout_caller: + /* Must be schedule_timeout ... */ + pc = ((unsigned long *)p->thread.reg30)[11]; + frame = ((unsigned long *)p->thread.reg30)[10]; + + /* The schedule_timeout frame ... */ + pc = ((unsigned long *)frame)[9]; + frame = ((unsigned long *)frame)[8]; + + if (pc >= first_sched && pc < last_sched) { + /* schedule_timeout called by interruptible_sleep_on_timeout */ + pc = ((unsigned long *)frame)[7]; + frame = ((unsigned long *)frame)[6]; + } + +out: + if (current->thread.mflags & MF_32BIT) /* Kludge for 32-bit ps */ + pc &= 0xffffffff; + + return pc; +} diff --git a/pool/shard000/C/0010795_gsf-infile.c b/pool/shard000/C/0010795_gsf-infile.c new file mode 100644 index 0000000000000000000000000000000000000000..52d26ed0c472e434ec0f607b8498a2e554a5e43d --- /dev/null +++ b/pool/shard000/C/0010795_gsf-infile.c @@ -0,0 +1,206 @@ +/* vim: set sw=8: -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ +/* + * gsf-infile.c : + * + * Copyright (C) 2002-2006 Jody Goldberg (jody@gnome.org) + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of version 2.1 of the GNU Lesser General Public + * License as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 + * USA + */ + +#include +#include +#include + +#include + +#define GET_CLASS(instance) G_TYPE_INSTANCE_GET_CLASS (instance, GSF_INFILE_TYPE, GsfInfileClass) + +/** + * gsf_infile_num_children : + * @infile : the structured storage + * + * Returns: the number of children the storage has, or -1 if the storage can not + * have children. + **/ +int +gsf_infile_num_children (GsfInfile *infile) +{ + g_return_val_if_fail (infile != NULL, -1); + + return GET_CLASS (infile)->num_children (infile); +} + +/** + * gsf_infile_name_by_index : + * @infile : + * @i : + * + * Returns: the utf8 encoded name of the @i-th child + * DO NOT FREE THE STRING. + **/ +char const * +gsf_infile_name_by_index (GsfInfile *infile, int i) +{ + g_return_val_if_fail (infile != NULL, NULL); + + return GET_CLASS (infile)->name_by_index (infile, i); +} + +/** + * gsf_infile_child_by_index : + * @infile : #GsfInfile + * @i : target index + * + * TODO : For 2.0 api will change to include a GError. + * Returns: a newly created child which must be unrefed. + **/ +GsfInput * +gsf_infile_child_by_index (GsfInfile *infile, int i) +{ + GError *err = NULL; + GsfInput *res; + + g_return_val_if_fail (GSF_INFILE (infile) != NULL, NULL); + + res = GET_CLASS (infile)->child_by_index (infile, i, &err); + + if (err != NULL) { + char const *iname = gsf_input_name (GSF_INPUT (infile)); + g_warning ("Unable to get child[%d] for infile '%s' because : %s", + i, iname ? iname : "?", err->message); + g_error_free (err); + g_return_val_if_fail (res == NULL, NULL); /* be anal */ + } + + return res; +} + +/** + * gsf_infile_child_by_name : + * @infile : #GsfInfile + * @name : target name + * + * TODO : For 2.0 api will change to include a GError. + * Returns: a newly created child which must be unrefed. + **/ +GsfInput * +gsf_infile_child_by_name (GsfInfile *infile, char const *name) +{ + GError *err = NULL; + GsfInput *res; + + g_return_val_if_fail (GSF_INFILE (infile) != NULL, NULL); + g_return_val_if_fail (name != NULL, NULL); + + res = GET_CLASS (infile)->child_by_name (infile, name, &err); + + if (err != NULL) { + char const *iname = gsf_input_name (GSF_INPUT (infile)); + g_warning ("Unable to get child['%s'] for infile '%s' because : %s", + name, iname ? iname : "?", err->message); + g_error_free (err); + g_return_val_if_fail (res == NULL, NULL); /* be anal */ + } + + return res; +} + +/** + * gsf_infile_child_by_vname : + * @infile : + * @Varargs : A %NULL terminated list of names + * + * Returns: a newly created child which must be unrefed. + **/ +GsfInput * +gsf_infile_child_by_vname (GsfInfile *infile, ...) +{ + GsfInput *res; + va_list names; + + va_start (names, infile); + res = gsf_infile_child_by_vaname (infile, names); + va_end (names); + + return res; +} + +/** + * gsf_infile_child_by_vaname : + * @infile : #GsfInfile + * @names : A %NULL terminated array of names (e.g. from g_strsplit) + * + * New in 1.14.9. + * + * Returns: a newly created child which must be unrefed. + **/ +GsfInput * +gsf_infile_child_by_vaname (GsfInfile *infile, va_list names) +{ + GsfInput *child = GSF_INPUT (infile); + GsfInfile *tmp = NULL; + char const *name; + + g_return_val_if_fail (GSF_IS_INFILE (infile), NULL); + + while (NULL != (name = va_arg (names, char const *))) { + child = gsf_infile_child_by_name (infile, name); + if (child == NULL) + break; + if (tmp != NULL) + g_object_unref (tmp); + + g_return_val_if_fail (GSF_IS_INFILE (child), NULL); + + infile = tmp = GSF_INFILE (child); + } + + return child; +} + +/** + * gsf_infile_child_by_aname : + * @infile : #GsfInfile + * @names : A %NULL terminated array of names (e.g. from g_strsplit) + * + * New in 1.14.9. + * + * Returns: a newly created child which must be unrefed. + **/ +GsfInput * +gsf_infile_child_by_aname (GsfInfile *infile, char const *names[]) +{ + GsfInput *child = GSF_INPUT (infile); + GsfInfile *tmp = NULL; + + g_return_val_if_fail (GSF_IS_INFILE (infile), NULL); + g_return_val_if_fail (names != NULL, NULL); + + for (;*names ; names++) { + child = gsf_infile_child_by_name (infile, *names); + if (tmp != NULL) + g_object_unref (tmp); + if (child == NULL) + break; + + g_return_val_if_fail (GSF_IS_INFILE (child), NULL); + + infile = tmp = GSF_INFILE (child); + } + + return child; +} + +GSF_CLASS_ABSTRACT (GsfInfile, gsf_infile, NULL, NULL, GSF_INPUT_TYPE) diff --git a/pool/shard000/C/0010799_dwarf_cu.c b/pool/shard000/C/0010799_dwarf_cu.c new file mode 100644 index 0000000000000000000000000000000000000000..d103488d109817ac2202a49ef99fb7a1901592cb --- /dev/null +++ b/pool/shard000/C/0010799_dwarf_cu.c @@ -0,0 +1,161 @@ +/*- + * Copyright (c) 2007 John Birrell (jb@freebsd.org) + * Copyright (c) 2014 Kai Wang + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include "_libdwarf.h" + +ELFTC_VCSID("$Id: dwarf_cu.c 3041 2014-05-18 15:11:03Z kaiwang27 $"); + +int +dwarf_next_cu_header_c(Dwarf_Debug dbg, Dwarf_Bool is_info, + Dwarf_Unsigned *cu_length, Dwarf_Half *cu_version, + Dwarf_Off *cu_abbrev_offset, Dwarf_Half *cu_pointer_size, + Dwarf_Half *cu_offset_size, Dwarf_Half *cu_extension_size, + Dwarf_Sig8 *type_signature, Dwarf_Unsigned *type_offset, + Dwarf_Unsigned *cu_next_offset, Dwarf_Error *error) +{ + Dwarf_CU cu; + int ret; + + if (dbg == NULL) { + DWARF_SET_ERROR(dbg, error, DW_DLE_ARGUMENT); + return (DW_DLV_ERROR); + } + + if (is_info) { + if (dbg->dbg_cu_current == NULL) + ret = _dwarf_info_first_cu(dbg, error); + else + ret = _dwarf_info_next_cu(dbg, error); + } else { + if (dbg->dbg_tu_current == NULL) + ret = _dwarf_info_first_tu(dbg, error); + else + ret = _dwarf_info_next_tu(dbg, error); + } + + if (ret == DW_DLE_NO_ENTRY) { + DWARF_SET_ERROR(dbg, error, DW_DLE_NO_ENTRY); + return (DW_DLV_NO_ENTRY); + } else if (ret != DW_DLE_NONE) + return (DW_DLV_ERROR); + + if (is_info) { + if (dbg->dbg_cu_current == NULL) { + DWARF_SET_ERROR(dbg, error, DW_DLE_NO_ENTRY); + return (DW_DLV_NO_ENTRY); + } + cu = dbg->dbg_cu_current; + } else { + if (dbg->dbg_tu_current == NULL) { + DWARF_SET_ERROR(dbg, error, DW_DLE_NO_ENTRY); + return (DW_DLV_NO_ENTRY); + } + cu = dbg->dbg_tu_current; + } + + if (cu_length) + *cu_length = cu->cu_length; + if (cu_version) + *cu_version = cu->cu_version; + if (cu_abbrev_offset) + *cu_abbrev_offset = (Dwarf_Off) cu->cu_abbrev_offset; + if (cu_pointer_size) + *cu_pointer_size = cu->cu_pointer_size; + if (cu_offset_size) { + if (cu->cu_length_size == 4) + *cu_offset_size = 4; + else + *cu_offset_size = 8; + } + if (cu_extension_size) { + if (cu->cu_length_size == 4) + *cu_extension_size = 0; + else + *cu_extension_size = 4; + } + if (cu_next_offset) + *cu_next_offset = cu->cu_next_offset; + + if (!is_info) { + if (type_signature) + *type_signature = cu->cu_type_sig; + if (type_offset) + *type_offset = cu->cu_type_offset; + } + + return (DW_DLV_OK); +} + + +int +dwarf_next_cu_header_b(Dwarf_Debug dbg, Dwarf_Unsigned *cu_length, + Dwarf_Half *cu_version, Dwarf_Off *cu_abbrev_offset, + Dwarf_Half *cu_pointer_size, Dwarf_Half *cu_offset_size, + Dwarf_Half *cu_extension_size, Dwarf_Unsigned *cu_next_offset, + Dwarf_Error *error) +{ + + return (dwarf_next_cu_header_c(dbg, 1, cu_length, cu_version, + cu_abbrev_offset, cu_pointer_size, cu_offset_size, + cu_extension_size, NULL, NULL, cu_next_offset, error)); +} + +int +dwarf_next_cu_header(Dwarf_Debug dbg, Dwarf_Unsigned *cu_length, + Dwarf_Half *cu_version, Dwarf_Off *cu_abbrev_offset, + Dwarf_Half *cu_pointer_size, Dwarf_Unsigned *cu_next_offset, + Dwarf_Error *error) +{ + + return (dwarf_next_cu_header_b(dbg, cu_length, cu_version, + cu_abbrev_offset, cu_pointer_size, NULL, NULL, cu_next_offset, + error)); +} + +int +dwarf_next_types_section(Dwarf_Debug dbg, Dwarf_Error *error) +{ + + /* Free resource allocated for current .debug_types section. */ + _dwarf_type_unit_cleanup(dbg); + dbg->dbg_types_loaded = 0; + dbg->dbg_types_off = 0; + + /* Reset type unit pointer. */ + dbg->dbg_tu_current = NULL; + + /* Search for the next .debug_types section. */ + dbg->dbg_types_sec = _dwarf_find_next_types_section(dbg, + dbg->dbg_types_sec); + + if (dbg->dbg_types_sec == NULL) { + DWARF_SET_ERROR(dbg, error, DW_DLE_NO_ENTRY); + return (DW_DLV_NO_ENTRY); + } + + return (DW_DLV_OK); +} diff --git a/pool/shard000/C/0010801_ppcobsd-tdep.c b/pool/shard000/C/0010801_ppcobsd-tdep.c new file mode 100644 index 0000000000000000000000000000000000000000..b7520a52d1803e7f6b90c0ae202334d74110071f --- /dev/null +++ b/pool/shard000/C/0010801_ppcobsd-tdep.c @@ -0,0 +1,332 @@ +/* Target-dependent code for OpenBSD/powerpc. + + Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009 + Free Software Foundation, Inc. + + This file is part of GDB. + + 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 + along with this program. If not, see . */ + +#include "defs.h" +#include "arch-utils.h" +#include "frame.h" +#include "frame-unwind.h" +#include "gdbtypes.h" +#include "osabi.h" +#include "regcache.h" +#include "regset.h" +#include "symtab.h" +#include "trad-frame.h" + +#include "gdb_assert.h" +#include "gdb_string.h" + +#include "ppc-tdep.h" +#include "ppcobsd-tdep.h" +#include "solib-svr4.h" + +/* Register offsets from . */ +struct ppc_reg_offsets ppcobsd_reg_offsets; +struct ppc_reg_offsets ppcobsd_fpreg_offsets; + + +/* Core file support. */ + +/* Supply register REGNUM in the general-purpose register set REGSET + from the buffer specified by GREGS and LEN to register cache + REGCACHE. If REGNUM is -1, do this for all registers in REGSET. */ + +void +ppcobsd_supply_gregset (const struct regset *regset, + struct regcache *regcache, int regnum, + const void *gregs, size_t len) +{ + ppc_supply_gregset (regset, regcache, regnum, gregs, len); + ppc_supply_fpregset (regset, regcache, regnum, gregs, len); +} + +/* Collect register REGNUM in the general-purpose register set + REGSET. from register cache REGCACHE into the buffer specified by + GREGS and LEN. If REGNUM is -1, do this for all registers in + REGSET. */ + +void +ppcobsd_collect_gregset (const struct regset *regset, + const struct regcache *regcache, int regnum, + void *gregs, size_t len) +{ + ppc_collect_gregset (regset, regcache, regnum, gregs, len); + ppc_collect_fpregset (regset, regcache, regnum, gregs, len); +} + +/* OpenBSD/powerpc register set. */ + +struct regset ppcobsd_gregset = +{ + &ppcobsd_reg_offsets, + ppcobsd_supply_gregset +}; + +struct regset ppcobsd_fpregset = +{ + &ppcobsd_fpreg_offsets, + ppc_supply_fpregset +}; + +/* Return the appropriate register set for the core section identified + by SECT_NAME and SECT_SIZE. */ + +static const struct regset * +ppcobsd_regset_from_core_section (struct gdbarch *gdbarch, + const char *sect_name, size_t sect_size) +{ + if (strcmp (sect_name, ".reg") == 0 && sect_size >= 412) + return &ppcobsd_gregset; + + return NULL; +} + + +/* Signal trampolines. */ + +/* Since OpenBSD 3.2, the sigtramp routine is mapped at a random page + in virtual memory. The randomness makes it somewhat tricky to + detect it, but fortunately we can rely on the fact that the start + of the sigtramp routine is page-aligned. We recognize the + trampoline by looking for the code that invokes the sigreturn + system call. The offset where we can find that code varies from + release to release. + + By the way, the mapping mentioned above is read-only, so you cannot + place a breakpoint in the signal trampoline. */ + +/* Default page size. */ +static const int ppcobsd_page_size = 4096; + +/* Offset for sigreturn(2). */ +static const int ppcobsd_sigreturn_offset[] = { + 0x98, /* OpenBSD 3.8 */ + 0x0c, /* OpenBSD 3.2 */ + -1 +}; + +static int +ppcobsd_sigtramp_frame_sniffer (const struct frame_unwind *self, + struct frame_info *this_frame, + void **this_cache) +{ + struct gdbarch *gdbarch = get_frame_arch (this_frame); + enum bfd_endian byte_order = gdbarch_byte_order (gdbarch); + CORE_ADDR pc = get_frame_pc (this_frame); + CORE_ADDR start_pc = (pc & ~(ppcobsd_page_size - 1)); + const int *offset; + char *name; + + find_pc_partial_function (pc, &name, NULL, NULL); + if (name) + return 0; + + for (offset = ppcobsd_sigreturn_offset; *offset != -1; offset++) + { + gdb_byte buf[2 * PPC_INSN_SIZE]; + unsigned long insn; + + if (!safe_frame_unwind_memory (this_frame, start_pc + *offset, + buf, sizeof buf)) + continue; + + /* Check for "li r0,SYS_sigreturn". */ + insn = extract_unsigned_integer (buf, PPC_INSN_SIZE, byte_order); + if (insn != 0x38000067) + continue; + + /* Check for "sc". */ + insn = extract_unsigned_integer (buf + PPC_INSN_SIZE, + PPC_INSN_SIZE, byte_order); + if (insn != 0x44000002) + continue; + + return 1; + } + + return 0; +} + +static struct trad_frame_cache * +ppcobsd_sigtramp_frame_cache (struct frame_info *this_frame, void **this_cache) +{ + struct gdbarch *gdbarch = get_frame_arch (this_frame); + struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch); + enum bfd_endian byte_order = gdbarch_byte_order (gdbarch); + struct trad_frame_cache *cache; + CORE_ADDR addr, base, func; + gdb_byte buf[PPC_INSN_SIZE]; + unsigned long insn, sigcontext_offset; + int i; + + if (*this_cache) + return *this_cache; + + cache = trad_frame_cache_zalloc (this_frame); + *this_cache = cache; + + func = get_frame_pc (this_frame); + func &= ~(ppcobsd_page_size - 1); + if (!safe_frame_unwind_memory (this_frame, func, buf, sizeof buf)) + return cache; + + /* Calculate the offset where we can find `struct sigcontext'. We + base our calculation on the amount of stack space reserved by the + first instruction of the signal trampoline. */ + insn = extract_unsigned_integer (buf, PPC_INSN_SIZE, byte_order); + sigcontext_offset = (0x10000 - (insn & 0x0000ffff)) + 8; + + base = get_frame_register_unsigned (this_frame, gdbarch_sp_regnum (gdbarch)); + addr = base + sigcontext_offset + 2 * tdep->wordsize; + for (i = 0; i < ppc_num_gprs; i++, addr += tdep->wordsize) + { + int regnum = i + tdep->ppc_gp0_regnum; + trad_frame_set_reg_addr (cache, regnum, addr); + } + trad_frame_set_reg_addr (cache, tdep->ppc_lr_regnum, addr); + addr += tdep->wordsize; + trad_frame_set_reg_addr (cache, tdep->ppc_cr_regnum, addr); + addr += tdep->wordsize; + trad_frame_set_reg_addr (cache, tdep->ppc_xer_regnum, addr); + addr += tdep->wordsize; + trad_frame_set_reg_addr (cache, tdep->ppc_ctr_regnum, addr); + addr += tdep->wordsize; + trad_frame_set_reg_addr (cache, gdbarch_pc_regnum (gdbarch), addr); + /* SRR0? */ + addr += tdep->wordsize; + + /* Construct the frame ID using the function start. */ + trad_frame_set_id (cache, frame_id_build (base, func)); + + return cache; +} + +static void +ppcobsd_sigtramp_frame_this_id (struct frame_info *this_frame, + void **this_cache, struct frame_id *this_id) +{ + struct trad_frame_cache *cache = + ppcobsd_sigtramp_frame_cache (this_frame, this_cache); + + trad_frame_get_id (cache, this_id); +} + +static struct value * +ppcobsd_sigtramp_frame_prev_register (struct frame_info *this_frame, + void **this_cache, int regnum) +{ + struct trad_frame_cache *cache = + ppcobsd_sigtramp_frame_cache (this_frame, this_cache); + + return trad_frame_get_register (cache, this_frame, regnum); +} + +static const struct frame_unwind ppcobsd_sigtramp_frame_unwind = { + SIGTRAMP_FRAME, + ppcobsd_sigtramp_frame_this_id, + ppcobsd_sigtramp_frame_prev_register, + NULL, + ppcobsd_sigtramp_frame_sniffer +}; + + +static void +ppcobsd_init_abi (struct gdbarch_info info, struct gdbarch *gdbarch) +{ + /* OpenBSD doesn't support the 128-bit `long double' from the psABI. */ + set_gdbarch_long_double_bit (gdbarch, 64); + set_gdbarch_long_double_format (gdbarch, floatformats_ieee_double); + + /* OpenBSD currently uses a broken GCC. */ + set_gdbarch_return_value (gdbarch, ppc_sysv_abi_broken_return_value); + + /* OpenBSD uses SVR4-style shared libraries. */ + set_solib_svr4_fetch_link_map_offsets + (gdbarch, svr4_ilp32_fetch_link_map_offsets); + + set_gdbarch_regset_from_core_section + (gdbarch, ppcobsd_regset_from_core_section); + + frame_unwind_append_unwinder (gdbarch, &ppcobsd_sigtramp_frame_unwind); +} + + +/* OpenBSD uses uses the traditional NetBSD core file format, even for + ports that use ELF. */ +#define GDB_OSABI_NETBSD_CORE GDB_OSABI_OPENBSD_ELF + +static enum gdb_osabi +ppcobsd_core_osabi_sniffer (bfd *abfd) +{ + if (strcmp (bfd_get_target (abfd), "netbsd-core") == 0) + return GDB_OSABI_NETBSD_CORE; + + return GDB_OSABI_UNKNOWN; +} + + +/* Provide a prototype to silence -Wmissing-prototypes. */ +void _initialize_ppcobsd_tdep (void); + +void +_initialize_ppcobsd_tdep (void) +{ + /* BFD doesn't set a flavour for NetBSD style a.out core files. */ + gdbarch_register_osabi_sniffer (bfd_arch_powerpc, bfd_target_unknown_flavour, + ppcobsd_core_osabi_sniffer); + + gdbarch_register_osabi (bfd_arch_rs6000, 0, GDB_OSABI_OPENBSD_ELF, + ppcobsd_init_abi); + gdbarch_register_osabi (bfd_arch_powerpc, 0, GDB_OSABI_OPENBSD_ELF, + ppcobsd_init_abi); + + /* Avoid initializing the register offsets again if they were + already initailized by ppcobsd-nat.c. */ + if (ppcobsd_reg_offsets.pc_offset == 0) + { + /* General-purpose registers. */ + ppcobsd_reg_offsets.r0_offset = 0; + ppcobsd_reg_offsets.gpr_size = 4; + ppcobsd_reg_offsets.xr_size = 4; + ppcobsd_reg_offsets.pc_offset = 384; + ppcobsd_reg_offsets.ps_offset = 388; + ppcobsd_reg_offsets.cr_offset = 392; + ppcobsd_reg_offsets.lr_offset = 396; + ppcobsd_reg_offsets.ctr_offset = 400; + ppcobsd_reg_offsets.xer_offset = 404; + ppcobsd_reg_offsets.mq_offset = 408; + + /* Floating-point registers. */ + ppcobsd_reg_offsets.f0_offset = 128; + ppcobsd_reg_offsets.fpscr_offset = -1; + + /* AltiVec registers. */ + ppcobsd_reg_offsets.vr0_offset = 0; + ppcobsd_reg_offsets.vscr_offset = 512; + ppcobsd_reg_offsets.vrsave_offset = 520; + } + + if (ppcobsd_fpreg_offsets.fpscr_offset == 0) + { + /* Floating-point registers. */ + ppcobsd_reg_offsets.f0_offset = 0; + ppcobsd_reg_offsets.fpscr_offset = 256; + ppcobsd_reg_offsets.fpscr_size = 4; + } +} diff --git a/pool/shard000/C/0010802_utf8_and_uhc.c b/pool/shard000/C/0010802_utf8_and_uhc.c new file mode 100644 index 0000000000000000000000000000000000000000..ba986f9b972803a6972429b6b2ed03a0bb050ff6 --- /dev/null +++ b/pool/shard000/C/0010802_utf8_and_uhc.c @@ -0,0 +1,66 @@ +/*------------------------------------------------------------------------- + * + * UHC <--> UTF8 + * + * Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * IDENTIFICATION + * $PostgreSQL: pgsql/src/backend/utils/mb/conversion_procs/utf8_and_uhc/utf8_and_uhc.c,v 1.20 2010/01/02 16:57:57 momjian Exp $ + * + *------------------------------------------------------------------------- + */ + +#include "postgres.h" +#include "fmgr.h" +#include "mb/pg_wchar.h" +#include "../../Unicode/uhc_to_utf8.map" +#include "../../Unicode/utf8_to_uhc.map" + +PG_MODULE_MAGIC; + +PG_FUNCTION_INFO_V1(uhc_to_utf8); +PG_FUNCTION_INFO_V1(utf8_to_uhc); + +extern Datum uhc_to_utf8(PG_FUNCTION_ARGS); +extern Datum utf8_to_uhc(PG_FUNCTION_ARGS); + +/* ---------- + * conv_proc( + * INTEGER, -- source encoding id + * INTEGER, -- destination encoding id + * CSTRING, -- source string (null terminated C string) + * CSTRING, -- destination string (null terminated C string) + * INTEGER -- source string length + * ) returns VOID; + * ---------- + */ +Datum +uhc_to_utf8(PG_FUNCTION_ARGS) +{ + unsigned char *src = (unsigned char *) PG_GETARG_CSTRING(2); + unsigned char *dest = (unsigned char *) PG_GETARG_CSTRING(3); + int len = PG_GETARG_INT32(4); + + CHECK_ENCODING_CONVERSION_ARGS(PG_UHC, PG_UTF8); + + LocalToUtf(src, dest, LUmapUHC, NULL, + sizeof(LUmapUHC) / sizeof(pg_local_to_utf), 0, PG_UHC, len); + + PG_RETURN_VOID(); +} + +Datum +utf8_to_uhc(PG_FUNCTION_ARGS) +{ + unsigned char *src = (unsigned char *) PG_GETARG_CSTRING(2); + unsigned char *dest = (unsigned char *) PG_GETARG_CSTRING(3); + int len = PG_GETARG_INT32(4); + + CHECK_ENCODING_CONVERSION_ARGS(PG_UTF8, PG_UHC); + + UtfToLocal(src, dest, ULmapUHC, NULL, + sizeof(ULmapUHC) / sizeof(pg_utf_to_local), 0, PG_UHC, len); + + PG_RETURN_VOID(); +} diff --git a/pool/shard000/C/0010810_main.c b/pool/shard000/C/0010810_main.c new file mode 100644 index 0000000000000000000000000000000000000000..9d372b8cd2411e0527bd899d8b2e950f59afa753 --- /dev/null +++ b/pool/shard000/C/0010810_main.c @@ -0,0 +1,86 @@ +#include +#include "Platform/Platform.h" +#include "Typedefs.h" +#include "Settings.h" +#include "Game.h" +#include "Renderer/Renderer.h" +#include "OpenGL/OGLSurface.h" +#include "Stopwatch/Stopwatch.h" +#include "Input/Keyboard.h" +#include "Input/Mouse.h" + +// global variables +bool g_isWindowOpen = true; + +int main(int argc, char *argv[]) +{ + Window* window = Window_Create(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, "CSoftwareRasterizer JJoosten"); + + bool openGLInit = OGL_Init( SCREEN_WIDTH, SCREEN_HEIGHT); + + Renderer* renderer = Renderer_Create( SCREEN_WIDTH, SCREEN_HEIGHT); + CHECK_OGL_ERROR_IN_DEBUG; + + Keyboard keyboard; + Mouse mouse; + + Game* game = Game_Create( &keyboard, &mouse); + + OGLSurface* surface = OGLSurface_Create( renderer->FrameBuffer); + CHECK_OGL_ERROR_IN_DEBUG; + + Stopwatch stopwatch; + Stopwatch_Init( &stopwatch); + + // set input to window + Window_SetKeyboard(window, &keyboard); + Window_SetMouse(window, &mouse); + + CHECK_OGL_ERROR_IN_DEBUG; + + // setup buffers + OGLSurface_MapToFrameBuffer( surface, renderer->FrameBuffer); + CHECK_OGL_ERROR_IN_DEBUG; + + // start stopwatch for first frametime of < ammount + Stopwatch_Start( &stopwatch); + + // game loop + while( g_isWindowOpen) + { + // variables + double deltaTimeSec = 0; + + // setup timers + Stopwatch_Stop( &stopwatch); + Stopwatch_Start( &stopwatch); + deltaTimeSec = Stopwatch_GetIntervalInSeconds( &stopwatch); + + // update input + Keyboard_Update( &keyboard); + + g_isWindowOpen = Window_HandleMessages(window); + + Game_Update( game, deltaTimeSec); + + Game_Render( game, renderer, deltaTimeSec); + + OGLSurface_Draw(surface); + CHECK_OGL_ERROR_IN_DEBUG; + + OGLSurface_MapToFrameBuffer( surface, renderer->FrameBuffer); + CHECK_OGL_ERROR_IN_DEBUG; + + Window_SwapBuffer( window); + CHECK_OGL_ERROR_IN_DEBUG; + + g_isWindowOpen = !Keyboard_IsKeyPressed( &keyboard, csrKeyEscape); + } + + OGLSurface_Destroy(surface); + Game_Destroy(game); + Renderer_Destroy( renderer); + Window_Destroy( window); + + return 0; +} \ No newline at end of file diff --git a/pool/shard000/C/0010813_bitstream_filter.c b/pool/shard000/C/0010813_bitstream_filter.c new file mode 100644 index 0000000000000000000000000000000000000000..50fd47caac05487d0fafb620df847f179ac97fcf --- /dev/null +++ b/pool/shard000/C/0010813_bitstream_filter.c @@ -0,0 +1,124 @@ + +#include "avcodec.h" + +AVBitStreamFilter *first_bitstream_filter= NULL; + +void av_register_bitstream_filter(AVBitStreamFilter *bsf){ + bsf->next = first_bitstream_filter; + first_bitstream_filter= bsf; +} + +AVBitStreamFilterContext *av_bitstream_filter_init(const char *name){ + AVBitStreamFilter *bsf= first_bitstream_filter; + + while(bsf){ + if(!strcmp(name, bsf->name)){ + AVBitStreamFilterContext *bsfc= av_mallocz(sizeof(AVBitStreamFilterContext)); + bsfc->filter= bsf; + bsfc->priv_data= av_mallocz(bsf->priv_data_size); + return bsfc; + } + bsf= bsf->next; + } + return NULL; +} + +void av_bitstream_filter_close(AVBitStreamFilterContext *bsfc){ + av_freep(&bsfc->priv_data); + av_parser_close(bsfc->parser); + av_free(bsfc); +} + +int av_bitstream_filter_filter(AVBitStreamFilterContext *bsfc, + AVCodecContext *avctx, const char *args, + uint8_t **poutbuf, int *poutbuf_size, + const uint8_t *buf, int buf_size, int keyframe){ + *poutbuf= (uint8_t *) buf; + *poutbuf_size= buf_size; + return bsfc->filter->filter(bsfc, avctx, args, poutbuf, poutbuf_size, buf, buf_size, keyframe); +} + +static int dump_extradata(AVBitStreamFilterContext *bsfc, AVCodecContext *avctx, const char *args, + uint8_t **poutbuf, int *poutbuf_size, + const uint8_t *buf, int buf_size, int keyframe){ + int cmd= args ? *args : 0; + /* cast to avoid warning about discarding qualifiers */ + if(avctx->extradata){ + if( (keyframe && (avctx->flags2 & CODEC_FLAG2_LOCAL_HEADER) && cmd=='a') + ||(keyframe && (cmd=='k' || !cmd)) + ||(cmd=='e') + /*||(? && (s->flags & PARSER_FLAG_DUMP_EXTRADATA_AT_BEGIN)*/){ + int size= buf_size + avctx->extradata_size; + *poutbuf_size= size; + *poutbuf= av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE); + + memcpy(*poutbuf, avctx->extradata, avctx->extradata_size); + memcpy((*poutbuf) + avctx->extradata_size, buf, buf_size + FF_INPUT_BUFFER_PADDING_SIZE); + return 1; + } + } + return 0; +} + +static int remove_extradata(AVBitStreamFilterContext *bsfc, AVCodecContext *avctx, const char *args, + uint8_t **poutbuf, int *poutbuf_size, + const uint8_t *buf, int buf_size, int keyframe){ + int cmd= args ? *args : 0; + AVCodecParserContext *s; + + if(!bsfc->parser){ + bsfc->parser= av_parser_init(avctx->codec_id); + } + s= bsfc->parser; + + if(s && s->parser->split){ + if( (((avctx->flags & CODEC_FLAG_GLOBAL_HEADER) || (avctx->flags2 & CODEC_FLAG2_LOCAL_HEADER)) && cmd=='a') + ||(!keyframe && cmd=='k') + ||(cmd=='e' || !cmd) + ){ + int i= s->parser->split(avctx, buf, buf_size); + buf += i; + buf_size -= i; + } + } + *poutbuf= (uint8_t *) buf; + *poutbuf_size= buf_size; + + return 0; +} + +static int noise(AVBitStreamFilterContext *bsfc, AVCodecContext *avctx, const char *args, + uint8_t **poutbuf, int *poutbuf_size, + const uint8_t *buf, int buf_size, int keyframe){ + int amount= args ? atoi(args) : 10000; + unsigned int *state= bsfc->priv_data; + int i; + + *poutbuf= av_malloc(buf_size + FF_INPUT_BUFFER_PADDING_SIZE); + + memcpy(*poutbuf, buf, buf_size + FF_INPUT_BUFFER_PADDING_SIZE); + for(i=0; i + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "config.h" + +#include "telepathy-glib/connection.h" + +#include +#include + +#define DEBUG_FLAG TP_DEBUG_CONNECTION +#include "telepathy-glib/debug-internal.h" +#include "telepathy-glib/connection-internal.h" +#include "telepathy-glib/proxy-internal.h" + +/** + * TP_CONNECTION_FEATURE_ALIASING: + * + * Expands to a call to a function that returns a #GQuark representing the + * "aliasing" feature. + * + * This feature needs to be prepared in order to use + * tp_connection_can_set_contact_alias(). + * + * One can ask for a feature to be prepared using the + * tp_proxy_prepare_async() function, and waiting for it to callback. + * + * Since: 0.17.3 + */ +GQuark +tp_connection_get_feature_quark_aliasing (void) +{ + return g_quark_from_static_string ("tp-connection-feature-aliasing"); +} + +/** + * tp_connection_can_set_contact_alias: + * @self: a #TpConnection + * + * Check if the user can set aliases on his contacts. + * TP_CONNECTION_FEATURE_ALIASING needs to be prepared for this function to + * return a meaningful value. + * + * Returns: %TRUE if the aliases of contacts on @self + * may be changed by the user of the service, not just by the + * contacts themselves; %FALSE otherwise. + * Since: 0.17.3 + */ +gboolean +tp_connection_can_set_contact_alias (TpConnection *self) +{ + g_return_val_if_fail (TP_IS_CONNECTION (self), FALSE); + + return (self->priv->alias_flags & TP_CONNECTION_ALIAS_FLAG_USER_SET) != 0; +} + +static void +get_alias_flag_cb (TpConnection *self, + TpConnectionAliasFlags flags, + const GError *error, + gpointer user_data, + GObject *weak_object) +{ + GSimpleAsyncResult *result = user_data; + + if (error != NULL) + { + DEBUG ("Failed to get AliasFlag : %s", error->message); + g_simple_async_result_set_from_error (result, error); + goto finally; + } + + self->priv->alias_flags = flags; + +finally: + g_simple_async_result_complete_in_idle (result); +} + +void +_tp_connection_prepare_aliasing_async (TpProxy *proxy, + const TpProxyFeature *feature, + GAsyncReadyCallback callback, + gpointer user_data) +{ + TpConnection *self = (TpConnection *) proxy; + GSimpleAsyncResult *result; + + g_assert (self->priv->alias_flags == 0); + + result = g_simple_async_result_new ((GObject *) proxy, callback, user_data, + _tp_connection_prepare_aliasing_async); + + tp_cli_connection_interface_aliasing_call_get_alias_flags (self, -1, + get_alias_flag_cb, result, g_object_unref, G_OBJECT (self)); +} diff --git a/pool/shard000/C/0010847_server.c b/pool/shard000/C/0010847_server.c new file mode 100644 index 0000000000000000000000000000000000000000..8191963510029e789d81ccbf4ba32f360bacddcf --- /dev/null +++ b/pool/shard000/C/0010847_server.c @@ -0,0 +1,134 @@ +/* **************************************************************** + * + * Copyright 2015 Intel Corporation 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 "server.h" +#include "service.h" +#include "peripheral.h" + +#include "experimental/logger.h" + +#include + + +// Logging tag. +#define TAG "BLE_SERVER" + +static CAResult_t CAGattServerSendResponseNotificationImpl( + CAGattService * service, + uint8_t const * data, + size_t length) +{ + assert(service != NULL); + + GattCharacteristic1 * const characteristic = + service->response_characteristic.characteristic; + + if (!gatt_characteristic1_get_notifying(characteristic)) + { + OIC_LOG(WARNING, + TAG, + "Attempt to send response with notifications " + "disabled.\n" + "Client must enable notifications. " + "No response was sent."); + + return CA_STATUS_FAILED; + } + + GVariant * const value = + g_variant_new_fixed_array(G_VARIANT_TYPE_BYTE, + data, + length, + sizeof(data[0])); + + /* + Send the response fragment by setting the "Value" property on + the response characteristic, and emitting the + org.freedesktop.Dbus.Properties.PropertiesChanged signal, + accordingly. + + @todo Do we need to explicitly emit the GObject notify or + org.freedesktop.Dbus.Properties.PropertiesChanged + signal here? + + @todo It feels like this function should be part of the + response characteristic implementation. + + @todo Do we need to decrease the ref count after setting the + value, i.e. is ownership of the value transferred to the + characteristic object? + */ + gatt_characteristic1_set_value(characteristic, value); + + return CA_STATUS_OK; +} + +typedef struct _CAGattServerResponseInfo +{ + uint8_t const * const data; + size_t const length; + CAResult_t result; + +} CAGattServerResponseInfo; + +static void CAGattServerSendResponseNotificationToService(gpointer data, + gpointer user_data) +{ + CAGattService * const service = data; + CAGattServerResponseInfo * const info = user_data; + + CAResult_t const result = + CAGattServerSendResponseNotificationImpl(service, + info->data, + info->length); + + if (result != CA_STATUS_OK) + { + // Propagate failure if any send operation fails. + info->result = result; + } +} + +CAResult_t CAGattServerSendResponseNotification( + char const * address, + uint8_t const * data, + size_t length) +{ + CAGattService * const s = CAGattServiceDecodeAddress(address); + + return CAGattServerSendResponseNotificationImpl(s, data, length); +} + +CAResult_t CAGattServerSendResponseNotificationToAll( + uint8_t const * data, + size_t length) +{ + CAGattServerResponseInfo info = + { + .data = data, + .length = length, + .result = CA_STATUS_OK + }; + + CAPeripheralForEachService( + CAGattServerSendResponseNotificationToService, + &info); + + return info.result; +} diff --git a/pool/shard000/C/0010852_acpuclock-copper.c b/pool/shard000/C/0010852_acpuclock-copper.c new file mode 100644 index 0000000000000000000000000000000000000000..1a02c069e88b5fcdbb31b7a71bef49cebac1216f --- /dev/null +++ b/pool/shard000/C/0010852_acpuclock-copper.c @@ -0,0 +1,210 @@ +/* + * Copyright (c) 2012, Code Aurora Forum. All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 and + * only version 2 as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +#include +#include +#include +#include +#include +#include + +#include "acpuclock.h" +#include "acpuclock-krait.h" + +/* Corner type vreg VDD values */ +#define LVL_NONE RPM_VREG_CORNER_NONE +#define LVL_LOW RPM_VREG_CORNER_LOW +#define LVL_NOM RPM_VREG_CORNER_NOMINAL +#define LVL_HIGH RPM_VREG_CORNER_HIGH + +static struct hfpll_data hfpll_data_cpu = { + .mode_offset = 0x00, + .l_offset = 0x04, + .m_offset = 0x08, + .n_offset = 0x0C, + .config_offset = 0x14, + /* TODO: Verify magic number for copper when available. */ + .config_val = 0x7845C665, + .low_vdd_l_max = 52, + .vdd[HFPLL_VDD_NONE] = 0, + .vdd[HFPLL_VDD_LOW] = 810000, + .vdd[HFPLL_VDD_NOM] = 900000, +}; + +static struct hfpll_data hfpll_data_l2 = { + .mode_offset = 0x00, + .l_offset = 0x04, + .m_offset = 0x08, + .n_offset = 0x0C, + .config_offset = 0x14, + /* TODO: Verify magic number for copper when available. */ + .config_val = 0x7845C665, + .low_vdd_l_max = 52, + .vdd[HFPLL_VDD_NONE] = LVL_NONE, + .vdd[HFPLL_VDD_LOW] = LVL_LOW, + .vdd[HFPLL_VDD_NOM] = LVL_NOM, +}; + +static struct scalable scalable[] = { + [CPU0] = { + .hfpll_phys_base = 0xF908A000, + .hfpll_data = &hfpll_data_cpu, + .l2cpmr_iaddr = 0x4501, + .vreg[VREG_CORE] = { "krait0", 1050000, 3200000 }, + .vreg[VREG_MEM] = { "krait0_mem", 1050000, 0, + RPM_VREG_VOTER1, + RPM_VREG_ID_PM8941_S1 }, + .vreg[VREG_DIG] = { "krait0_dig", 1050000, 0, + RPM_VREG_VOTER1, + RPM_VREG_ID_PM8941_S2 }, + .vreg[VREG_HFPLL_A] = { "hfpll", 1800000, 0, + RPM_VREG_VOTER1, + RPM_VREG_ID_PM8941_L12 }, + }, + [CPU1] = { + .hfpll_phys_base = 0xF909A000, + .hfpll_data = &hfpll_data_cpu, + .l2cpmr_iaddr = 0x5501, + .vreg[VREG_CORE] = { "krait1", 1050000, 3200000 }, + .vreg[VREG_MEM] = { "krait1_mem", 1050000, 0, + RPM_VREG_VOTER2, + RPM_VREG_ID_PM8941_S1 }, + .vreg[VREG_DIG] = { "krait1_dig", 1050000, 0, + RPM_VREG_VOTER2, + RPM_VREG_ID_PM8941_S2 }, + .vreg[VREG_HFPLL_A] = { "hfpll", 1800000, 0, + RPM_VREG_VOTER2, + RPM_VREG_ID_PM8941_L12 }, + }, + [CPU2] = { + .hfpll_phys_base = 0xF90AA000, + .hfpll_data = &hfpll_data_cpu, + .l2cpmr_iaddr = 0x6501, + .vreg[VREG_CORE] = { "krait2", 1050000, 3200000 }, + .vreg[VREG_MEM] = { "krait2_mem", 1050000, 0, + RPM_VREG_VOTER4, + RPM_VREG_ID_PM8921_S1 }, + .vreg[VREG_DIG] = { "krait2_dig", 1050000, 0, + RPM_VREG_VOTER4, + RPM_VREG_ID_PM8921_S2 }, + .vreg[VREG_HFPLL_A] = { "hfpll", 1800000, 0, + RPM_VREG_VOTER4, + RPM_VREG_ID_PM8941_L12 }, + }, + [CPU3] = { + .hfpll_phys_base = 0xF90BA000, + .hfpll_data = &hfpll_data_cpu, + .l2cpmr_iaddr = 0x7501, + .vreg[VREG_CORE] = { "krait3", 1050000, 3200000 }, + .vreg[VREG_MEM] = { "krait3_mem", 1050000, 0, + RPM_VREG_VOTER5, + RPM_VREG_ID_PM8941_S1 }, + .vreg[VREG_DIG] = { "krait3_dig", 1050000, 0, + RPM_VREG_VOTER5, + RPM_VREG_ID_PM8941_S2 }, + .vreg[VREG_HFPLL_A] = { "hfpll", 1800000, 0, + RPM_VREG_VOTER5, + RPM_VREG_ID_PM8941_L12 }, + }, + [L2] = { + .hfpll_phys_base = 0xF9016000, + .hfpll_data = &hfpll_data_l2, + .l2cpmr_iaddr = 0x0500, + .vreg[VREG_HFPLL_A] = { "hfpll", 1800000, 0, + RPM_VREG_VOTER6, + RPM_VREG_ID_PM8941_L12 }, + }, +}; + +static struct msm_bus_paths bw_level_tbl[] = { + [0] = BW_MBPS(400), /* At least 50 MHz on bus. */ + [1] = BW_MBPS(800), /* At least 100 MHz on bus. */ + [2] = BW_MBPS(1334), /* At least 167 MHz on bus. */ + [3] = BW_MBPS(2666), /* At least 200 MHz on bus. */ + [4] = BW_MBPS(3200), /* At least 333 MHz on bus. */ +}; + +static struct msm_bus_scale_pdata bus_scale_data = { + .usecase = bw_level_tbl, + .num_usecases = ARRAY_SIZE(bw_level_tbl), + .active_only = 1, + .name = "acpuclk-copper", +}; + +#define L2(x) (&l2_freq_tbl[(x)]) +static struct l2_level l2_freq_tbl[] = { + [0] = { {STBY_KHZ, QSB, 0, 0, 0 }, LVL_NOM, 1050000, 0 }, + [1] = { { 300000, PLL_0, 0, 2, 0 }, LVL_NOM, 1050000, 2 }, + [2] = { { 384000, HFPLL, 2, 0, 40 }, LVL_NOM, 1050000, 2 }, + [3] = { { 460800, HFPLL, 2, 0, 48 }, LVL_NOM, 1050000, 2 }, + [4] = { { 537600, HFPLL, 1, 0, 28 }, LVL_NOM, 1050000, 2 }, + [5] = { { 576000, HFPLL, 1, 0, 30 }, LVL_NOM, 1050000, 3 }, + [6] = { { 652800, HFPLL, 1, 0, 34 }, LVL_NOM, 1050000, 3 }, + [7] = { { 729600, HFPLL, 1, 0, 38 }, LVL_NOM, 1050000, 3 }, + [8] = { { 806400, HFPLL, 1, 0, 42 }, LVL_NOM, 1050000, 3 }, + [9] = { { 883200, HFPLL, 1, 0, 46 }, LVL_NOM, 1050000, 4 }, + [10] = { { 960000, HFPLL, 1, 0, 50 }, LVL_NOM, 1050000, 4 }, + [11] = { { 1036800, HFPLL, 1, 0, 54 }, LVL_NOM, 1050000, 4 }, +}; + +static struct acpu_level acpu_freq_tbl[] = { + { 0, {STBY_KHZ, QSB, 0, 0, 0 }, L2(0), 1050000 }, + { 1, { 300000, PLL_0, 0, 2, 0 }, L2(1), 1050000 }, + { 1, { 384000, HFPLL, 2, 0, 40 }, L2(2), 1050000 }, + { 1, { 460800, HFPLL, 2, 0, 48 }, L2(3), 1050000 }, + { 1, { 537600, HFPLL, 1, 0, 28 }, L2(4), 1050000 }, + { 1, { 576000, HFPLL, 1, 0, 30 }, L2(5), 1050000 }, + { 1, { 652800, HFPLL, 1, 0, 34 }, L2(6), 1050000 }, + { 1, { 729600, HFPLL, 1, 0, 38 }, L2(7), 1050000 }, + { 1, { 806400, HFPLL, 1, 0, 42 }, L2(8), 1050000 }, + { 1, { 883200, HFPLL, 1, 0, 46 }, L2(9), 1050000 }, + { 1, { 960000, HFPLL, 1, 0, 50 }, L2(10), 1050000 }, + { 1, { 1036800, HFPLL, 1, 0, 54 }, L2(11), 1050000 }, + { 0, { 0 } } +}; + +static struct acpuclk_krait_params acpuclk_copper_params = { + .scalable = scalable, + .pvs_acpu_freq_tbl[PVS_SLOW] = acpu_freq_tbl, + .pvs_acpu_freq_tbl[PVS_NOMINAL] = acpu_freq_tbl, + .pvs_acpu_freq_tbl[PVS_FAST] = acpu_freq_tbl, + .l2_freq_tbl = l2_freq_tbl, + .l2_freq_tbl_size = ARRAY_SIZE(l2_freq_tbl), + .bus_scale_data = &bus_scale_data, + .qfprom_phys_base = 0xFC4A8000, +}; + +static int __init acpuclk_copper_probe(struct platform_device *pdev) +{ + return acpuclk_krait_init(&pdev->dev, &acpuclk_copper_params); +} + +static struct of_device_id acpuclk_copper_match_table[] = { + { .compatible = "qcom,acpuclk-copper" }, + {} +}; + +static struct platform_driver acpuclk_copper_driver = { + .driver = { + .name = "acpuclk-copper", + .of_match_table = acpuclk_copper_match_table, + .owner = THIS_MODULE, + }, +}; + +static int __init acpuclk_8960_init(void) +{ + return platform_driver_probe(&acpuclk_copper_driver, + acpuclk_copper_probe); +} +device_initcall(acpuclk_8960_init); diff --git a/pool/shard000/C/0010855_asus-wireless.c b/pool/shard000/C/0010855_asus-wireless.c new file mode 100644 index 0000000000000000000000000000000000000000..7458f7602d5e73be5fcd9b341a54b8ba0290c3b9 --- /dev/null +++ b/pool/shard000/C/0010855_asus-wireless.c @@ -0,0 +1,206 @@ +/* + * Asus Wireless Radio Control Driver + * + * Copyright (C) 2015-2016 Endless Mobile, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +struct hswc_params { + u8 on; + u8 off; + u8 status; +}; + +struct asus_wireless_data { + struct input_dev *idev; + struct acpi_device *adev; + const struct hswc_params *hswc_params; + struct workqueue_struct *wq; + struct work_struct led_work; + struct led_classdev led; + int led_state; +}; + +static const struct hswc_params atk4001_id_params = { + .on = 0x0, + .off = 0x1, + .status = 0x2, +}; + +static const struct hswc_params atk4002_id_params = { + .on = 0x5, + .off = 0x4, + .status = 0x2, +}; + +static const struct acpi_device_id device_ids[] = { + {"ATK4001", (kernel_ulong_t)&atk4001_id_params}, + {"ATK4002", (kernel_ulong_t)&atk4002_id_params}, + {"", 0}, +}; +MODULE_DEVICE_TABLE(acpi, device_ids); + +static acpi_status asus_wireless_method(acpi_handle handle, const char *method, + int param, u64 *ret) +{ + struct acpi_object_list p; + union acpi_object obj; + acpi_status s; + + acpi_handle_debug(handle, "Evaluating method %s, parameter %#x\n", + method, param); + obj.type = ACPI_TYPE_INTEGER; + obj.integer.value = param; + p.count = 1; + p.pointer = &obj; + + s = acpi_evaluate_integer(handle, (acpi_string) method, &p, ret); + if (ACPI_FAILURE(s)) + acpi_handle_err(handle, + "Failed to eval method %s, param %#x (%d)\n", + method, param, s); + else + acpi_handle_debug(handle, "%s returned %#llx\n", method, *ret); + + return s; +} + +static enum led_brightness led_state_get(struct led_classdev *led) +{ + struct asus_wireless_data *data; + acpi_status s; + u64 ret; + + data = container_of(led, struct asus_wireless_data, led); + s = asus_wireless_method(acpi_device_handle(data->adev), "HSWC", + data->hswc_params->status, &ret); + if (ACPI_SUCCESS(s) && ret == data->hswc_params->on) + return LED_FULL; + return LED_OFF; +} + +static void led_state_update(struct work_struct *work) +{ + struct asus_wireless_data *data; + u64 ret; + + data = container_of(work, struct asus_wireless_data, led_work); + asus_wireless_method(acpi_device_handle(data->adev), "HSWC", + data->led_state, &ret); +} + +static void led_state_set(struct led_classdev *led, enum led_brightness value) +{ + struct asus_wireless_data *data; + + data = container_of(led, struct asus_wireless_data, led); + data->led_state = value == LED_OFF ? data->hswc_params->off : + data->hswc_params->on; + queue_work(data->wq, &data->led_work); +} + +static void asus_wireless_notify(struct acpi_device *adev, u32 event) +{ + struct asus_wireless_data *data = acpi_driver_data(adev); + + dev_dbg(&adev->dev, "event=%#x\n", event); + if (event != 0x88) { + dev_notice(&adev->dev, "Unknown ASHS event: %#x\n", event); + return; + } + input_report_key(data->idev, KEY_RFKILL, 1); + input_sync(data->idev); + input_report_key(data->idev, KEY_RFKILL, 0); + input_sync(data->idev); +} + +static int asus_wireless_add(struct acpi_device *adev) +{ + struct asus_wireless_data *data; + const struct acpi_device_id *id; + int err; + + data = devm_kzalloc(&adev->dev, sizeof(*data), GFP_KERNEL); + if (!data) + return -ENOMEM; + adev->driver_data = data; + data->adev = adev; + + data->idev = devm_input_allocate_device(&adev->dev); + if (!data->idev) + return -ENOMEM; + data->idev->name = "Asus Wireless Radio Control"; + data->idev->phys = "asus-wireless/input0"; + data->idev->id.bustype = BUS_HOST; + data->idev->id.vendor = PCI_VENDOR_ID_ASUSTEK; + set_bit(EV_KEY, data->idev->evbit); + set_bit(KEY_RFKILL, data->idev->keybit); + err = input_register_device(data->idev); + if (err) + return err; + + for (id = device_ids; id->id[0]; id++) { + if (!strcmp((char *) id->id, acpi_device_hid(adev))) { + data->hswc_params = + (const struct hswc_params *)id->driver_data; + break; + } + } + if (!data->hswc_params) + return 0; + + data->wq = create_singlethread_workqueue("asus_wireless_workqueue"); + if (!data->wq) + return -ENOMEM; + INIT_WORK(&data->led_work, led_state_update); + data->led.name = "asus-wireless::airplane"; + data->led.brightness_set = led_state_set; + data->led.brightness_get = led_state_get; + data->led.flags = LED_CORE_SUSPENDRESUME; + data->led.max_brightness = 1; + data->led.default_trigger = "rfkill-none"; + err = devm_led_classdev_register(&adev->dev, &data->led); + if (err) + destroy_workqueue(data->wq); + + return err; +} + +static int asus_wireless_remove(struct acpi_device *adev) +{ + struct asus_wireless_data *data = acpi_driver_data(adev); + + if (data->wq) { + devm_led_classdev_unregister(&adev->dev, &data->led); + destroy_workqueue(data->wq); + } + return 0; +} + +static struct acpi_driver asus_wireless_driver = { + .name = "Asus Wireless Radio Control Driver", + .class = "hotkey", + .ids = device_ids, + .ops = { + .add = asus_wireless_add, + .remove = asus_wireless_remove, + .notify = asus_wireless_notify, + }, +}; +module_acpi_driver(asus_wireless_driver); + +MODULE_DESCRIPTION("Asus Wireless Radio Control Driver"); +MODULE_AUTHOR("João Paulo Rechi Vita "); +MODULE_LICENSE("GPL"); diff --git a/pool/shard000/C/0010869_map_funcs.c b/pool/shard000/C/0010869_map_funcs.c new file mode 100644 index 0000000000000000000000000000000000000000..78a64bffa9c4439dc60ff525f21f02cd68cdab9d --- /dev/null +++ b/pool/shard000/C/0010869_map_funcs.c @@ -0,0 +1,45 @@ +/* + * $Id: map_funcs.c,v 1.1.1.1 2006/01/06 00:51:28 jsantiago Exp $ + * + * Out-of-line map I/O functions for simple maps when CONFIG_COMPLEX_MAPPINGS + * is enabled. + */ + +#include +#include + +#include +#include + +static map_word __xipram simple_map_read(struct map_info *map, unsigned long ofs) +{ + return inline_map_read(map, ofs); +} + +static void __xipram simple_map_write(struct map_info *map, const map_word datum, unsigned long ofs) +{ + inline_map_write(map, datum, ofs); +} + +static void __xipram simple_map_copy_from(struct map_info *map, void *to, unsigned long from, ssize_t len) +{ + inline_map_copy_from(map, to, from, len); +} + +static void __xipram simple_map_copy_to(struct map_info *map, unsigned long to, const void *from, ssize_t len) +{ + inline_map_copy_to(map, to, from, len); +} + +void simple_map_init(struct map_info *map) +{ + BUG_ON(!map_bankwidth_supported(map->bankwidth)); + + map->read = simple_map_read; + map->write = simple_map_write; + map->copy_from = simple_map_copy_from; + map->copy_to = simple_map_copy_to; +} + +EXPORT_SYMBOL(simple_map_init); +MODULE_LICENSE("GPL"); diff --git a/pool/shard000/C/0010920_mvme147.c b/pool/shard000/C/0010920_mvme147.c new file mode 100644 index 0000000000000000000000000000000000000000..cb367c2c5c78aa38d376928c4aa07e8d21c88a39 --- /dev/null +++ b/pool/shard000/C/0010920_mvme147.c @@ -0,0 +1,161 @@ +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "scsi.h" +#include +#include "wd33c93.h" +#include "mvme147.h" + +#include + +#define HDATA(ptr) ((struct WD33C93_hostdata *)((ptr)->hostdata)) + +static struct Scsi_Host *mvme147_host = NULL; + +static irqreturn_t mvme147_intr (int irq, void *dummy, struct pt_regs *fp) +{ + if (irq == MVME147_IRQ_SCSI_PORT) + wd33c93_intr (mvme147_host); + else + m147_pcc->dma_intr = 0x89; /* Ack and enable ints */ + return IRQ_HANDLED; +} + +static int dma_setup (Scsi_Cmnd *cmd, int dir_in) +{ + unsigned char flags = 0x01; + unsigned long addr = virt_to_bus(cmd->SCp.ptr); + + /* setup dma direction */ + if (!dir_in) + flags |= 0x04; + + /* remember direction */ + HDATA(mvme147_host)->dma_dir = dir_in; + + if (dir_in) + /* invalidate any cache */ + cache_clear (addr, cmd->SCp.this_residual); + else + /* push any dirty cache */ + cache_push (addr, cmd->SCp.this_residual); + + /* start DMA */ + m147_pcc->dma_bcr = cmd->SCp.this_residual | (1<<24); + m147_pcc->dma_dadr = addr; + m147_pcc->dma_cntrl = flags; + + /* return success */ + return 0; +} + +static void dma_stop (struct Scsi_Host *instance, Scsi_Cmnd *SCpnt, + int status) +{ + m147_pcc->dma_cntrl = 0; +} + +int mvme147_detect(struct scsi_host_template *tpnt) +{ + static unsigned char called = 0; + wd33c93_regs regs; + + if (!MACH_IS_MVME147 || called) + return 0; + called++; + + tpnt->proc_name = "MVME147"; + tpnt->proc_info = &wd33c93_proc_info; + + mvme147_host = scsi_register (tpnt, sizeof(struct WD33C93_hostdata)); + if (!mvme147_host) + goto err_out; + + mvme147_host->base = 0xfffe4000; + mvme147_host->irq = MVME147_IRQ_SCSI_PORT; + regs.SASR = (volatile unsigned char *)0xfffe4000; + regs.SCMD = (volatile unsigned char *)0xfffe4001; + wd33c93_init(mvme147_host, regs, dma_setup, dma_stop, WD33C93_FS_8_10); + + if (request_irq(MVME147_IRQ_SCSI_PORT, mvme147_intr, 0, "MVME147 SCSI PORT", mvme147_intr)) + goto err_unregister; + if (request_irq(MVME147_IRQ_SCSI_DMA, mvme147_intr, 0, "MVME147 SCSI DMA", mvme147_intr)) + goto err_free_irq; +#if 0 /* Disabled; causes problems booting */ + m147_pcc->scsi_interrupt = 0x10; /* Assert SCSI bus reset */ + udelay(100); + m147_pcc->scsi_interrupt = 0x00; /* Negate SCSI bus reset */ + udelay(2000); + m147_pcc->scsi_interrupt = 0x40; /* Clear bus reset interrupt */ +#endif + m147_pcc->scsi_interrupt = 0x09; /* Enable interrupt */ + + m147_pcc->dma_cntrl = 0x00; /* ensure DMA is stopped */ + m147_pcc->dma_intr = 0x89; /* Ack and enable ints */ + + return 1; + + err_free_irq: + free_irq(MVME147_IRQ_SCSI_PORT, mvme147_intr); + err_unregister: + wd33c93_release(); + scsi_unregister(mvme147_host); + err_out: + return 0; +} + +static int mvme147_bus_reset(Scsi_Cmnd *cmd) +{ + /* FIXME perform bus-specific reset */ + + /* FIXME 2: kill this function, and let midlayer fallback to + the same result, calling wd33c93_host_reset() */ + + spin_lock_irq(cmd->device->host->host_lock); + wd33c93_host_reset(cmd); + spin_unlock_irq(cmd->device->host->host_lock); + + return SUCCESS; +} + +#define HOSTS_C + +#include "mvme147.h" + +static struct scsi_host_template driver_template = { + .proc_name = "MVME147", + .name = "MVME147 built-in SCSI", + .detect = mvme147_detect, + .release = mvme147_release, + .queuecommand = wd33c93_queuecommand, + .eh_abort_handler = wd33c93_abort, + .eh_bus_reset_handler = mvme147_bus_reset, + .eh_host_reset_handler = wd33c93_host_reset, + .can_queue = CAN_QUEUE, + .this_id = 7, + .sg_tablesize = SG_ALL, + .cmd_per_lun = CMD_PER_LUN, + .use_clustering = ENABLE_CLUSTERING +}; + + +#include "scsi_module.c" + +int mvme147_release(struct Scsi_Host *instance) +{ +#ifdef MODULE + /* XXX Make sure DMA is stopped! */ + wd33c93_release(); + free_irq(MVME147_IRQ_SCSI_PORT, mvme147_intr); + free_irq(MVME147_IRQ_SCSI_DMA, mvme147_intr); +#endif + return 1; +} diff --git a/pool/shard000/C/0010931_jpeg_mem.c b/pool/shard000/C/0010931_jpeg_mem.c new file mode 100644 index 0000000000000000000000000000000000000000..013af29b244125989fb26921cbb8e67d26f01b16 --- /dev/null +++ b/pool/shard000/C/0010931_jpeg_mem.c @@ -0,0 +1,186 @@ +/* linux/drivers/media/video/samsung/jpeg/jpeg_mem.c + * + * Copyright (c) 2010 Samsung Electronics Co., Ltd. + * http://www.samsung.com/ + * + * Managent memory of the jpeg driver for encoder/docoder. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. +*/ + +#include +#include +#include + +#if defined(CONFIG_S5P_MEM_CMA) +#include +#elif defined(CONFIG_S5P_MEM_BOOTMEM) +#include +#include +#endif + +#include "jpeg_mem.h" +#include "jpeg_core.h" + +#if defined(CONFIG_S5P_SYSMMU_JPEG) && !defined(CONFIG_S5P_VMEM) +unsigned int s_cookie; /* for stream buffer */ +unsigned int f_cookie; /* for frame buffer */ +#endif + +#if defined(CONFIG_S5P_SYSMMU_JPEG) && defined(CONFIG_VIDEO_UMP) +#if defined(CONFIG_VCM_MMU) +unsigned int str_s_id; /* secure id for stream buffer */ +unsigned int fra_s_id; /* secure id for frame buffer */ +#endif /* CONFIG_VCM_MMU */ +unsigned int str_base; /* for stream buffer */ +unsigned int fra_base; /* for frame buffer */ +#endif + +int jpeg_init_mem(struct device *dev, unsigned int *base) +{ +#ifdef CONFIG_S5P_MEM_CMA + struct cma_info mem_info; + int err; + int size; + char cma_name[8]; +#endif +#if defined(CONFIG_S5P_SYSMMU_JPEG) +#if !defined(CONFIG_S5P_VMEM) + unsigned char *addr; + addr = vmalloc(JPEG_MEM_SIZE); + if (addr == NULL) + return -1; + *base = (unsigned int)addr; +#endif /* CONFIG_S5P_VMEM */ +#else +#ifdef CONFIG_S5P_MEM_CMA + /* CMA */ + sprintf(cma_name, "jpeg"); + err = cma_info(&mem_info, dev, 0); + jpeg_info("[cma_info] start_addr : 0x%x, end_addr : 0x%x, " + "total_size : 0x%x, free_size : 0x%x\n", + mem_info.lower_bound, mem_info.upper_bound, + mem_info.total_size, mem_info.free_size); + if (err) { + printk("%s: get cma info failed\n", __func__); + return -1; + } + size = mem_info.total_size; + *base = (dma_addr_t)cma_alloc + (dev, cma_name, (size_t)size, 0); + jpeg_info("size = 0x%x\n", size); + jpeg_info("*base = 0x%x\n", *base); +#else + *base = s5p_get_media_memory_bank(S5P_MDEV_JPEG, 0); +#endif +#endif /* CONFIG_S5P_SYSMMU_JPEG */ + return 0; +} + +int jpeg_mem_free(void) +{ +#if defined(CONFIG_S5P_SYSMMU_JPEG) && !defined(CONFIG_S5P_VMEM) + if (s_cookie != 0) { + s5p_vfree(s_cookie); + s_cookie = 0; + } + if (f_cookie != 0) { + s5p_vfree(f_cookie); + f_cookie = 0; + } +#endif + return 0; +} + +unsigned long jpeg_get_stream_buf(unsigned long arg) +{ +#if defined(CONFIG_S5P_SYSMMU_JPEG) && !defined(CONFIG_S5P_VMEM) + arg = ((arg / PAGE_SIZE + 1) * PAGE_SIZE); + s_cookie = (unsigned int)s5p_vmalloc(arg); + if (s_cookie == 0) + return -1; + return (unsigned long)s_cookie; +#else + return arg + JPEG_MAIN_START; +#endif +} + +unsigned long jpeg_get_frame_buf(unsigned long arg) +{ +#if defined(CONFIG_S5P_SYSMMU_JPEG) && !defined(CONFIG_S5P_VMEM) + arg = ((arg / PAGE_SIZE + 1) * PAGE_SIZE); + f_cookie = (unsigned int)s5p_vmalloc(arg); + if (f_cookie == 0) + return -1; + return (unsigned long)f_cookie; +#else + return arg + JPEG_S_BUF_SIZE; +#endif +} + +void jpeg_set_stream_buf(unsigned int *str_buf, unsigned int base) +{ +#if defined(CONFIG_S5P_SYSMMU_JPEG) && !defined(CONFIG_S5P_VMEM) + *str_buf = (unsigned int)s5p_getaddress(s_cookie); +#elif defined(CONFIG_S5P_SYSMMU_JPEG) && defined(CONFIG_VIDEO_UMP) +#if !defined(CONFIG_VCM) + sysmmu_set_tablebase_pgd(SYSMMU_JPEG, __pa(current->mm->pgd)); +#endif + *str_buf = str_base; +#else + *str_buf = base; +#endif +} + +void jpeg_set_frame_buf(unsigned int *fra_buf, unsigned int base) +{ +#if defined(CONFIG_S5P_SYSMMU_JPEG) && !defined(CONFIG_S5P_VMEM) + *fra_buf = (unsigned int)s5p_getaddress(f_cookie); +#elif defined(CONFIG_S5P_SYSMMU_JPEG) && defined(CONFIG_VIDEO_UMP) +#if !defined(CONFIG_VCM) + sysmmu_set_tablebase_pgd(SYSMMU_JPEG, __pa(current->mm->pgd)); +#endif + *fra_buf = fra_base; +#else + *fra_buf = base + JPEG_S_BUF_SIZE; +#endif +} + +void jpeg_set_stream_base(unsigned int base) +{ +#if defined(CONFIG_S5P_SYSMMU_JPEG) && defined(CONFIG_VIDEO_UMP) +#if defined(CONFIG_UMP_VCM_ALLOC) + struct vcm_res *vcm_res; + str_s_id = base; + vcm_res = (struct vcm_res *) + ump_dd_meminfo_get(str_s_id, (void *)VCM_DEV_JPEG); + if (vcm_res) + str_base = vcm_res->start; + else + str_base = 0; +#else + str_base = base; +#endif /* CONFIG_UMP_VCM_ALLOC */ +#endif +} + +void jpeg_set_frame_base(unsigned int base) +{ +#if defined(CONFIG_S5P_SYSMMU_JPEG) && defined(CONFIG_VIDEO_UMP) +#if defined(CONFIG_UMP_VCM_ALLOC) + struct vcm_res *vcm_res; + fra_s_id = base; + vcm_res = (struct vcm_res *) + ump_dd_meminfo_get(fra_s_id, (void *)VCM_DEV_JPEG); + if (vcm_res) + fra_base = vcm_res->start; + else + fra_base = 0; +#else + fra_base = base; +#endif /* CONFIG_UMP_VCM_ALLOC */ +#endif +} + diff --git a/pool/shard000/C/0010958_STM32L_low_power_tick_management.c b/pool/shard000/C/0010958_STM32L_low_power_tick_management.c new file mode 100644 index 0000000000000000000000000000000000000000..320d310a808f69ce1e7af704591a5b9ba70e9671 --- /dev/null +++ b/pool/shard000/C/0010958_STM32L_low_power_tick_management.c @@ -0,0 +1,371 @@ +/* + * FreeRTOS Kernel V10.1.1 + * Copyright (C) 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +/* Standard includes. */ +#include + +/* FreeRTOS includes. */ +#include "FreeRTOS.h" +#include "task.h" + +/* ST library functions. */ +#include "stm32l1xx.h" + +/* + * When configCREATE_LOW_POWER_DEMO is set to 1 then the tick interrupt + * is generated by the TIM2 peripheral. The TIM2 configuration and handling + * functions are defined in this file. Note the RTC is not used as there does + * not appear to be a way to read back the RTC count value, and therefore the + * only way of knowing exactly how long a sleep lasted is to use the very low + * resolution calendar time. + * + * When configCREATE_LOW_POWER_DEMO is set to 0 the tick interrupt is + * generated by the standard FreeRTOS Cortex-M port layer, which uses the + * SysTick timer. + */ +#if configCREATE_LOW_POWER_DEMO == 1 + +/* The frequency at which TIM2 will run. */ +#define lpCLOCK_INPUT_FREQUENCY ( 1000UL ) + +/* STM32 register used to ensure the TIM2 clock stops when the MCU is in debug +mode. */ +#define DBGMCU_APB1_FZ ( * ( ( volatile unsigned long * ) 0xE0042008 ) ) + +/*-----------------------------------------------------------*/ + +/* + * The tick interrupt is generated by the TIM2 timer. + */ +void TIM2_IRQHandler( void ); + +/*-----------------------------------------------------------*/ + +/* Calculate how many clock increments make up a single tick period. */ +static const uint32_t ulReloadValueForOneTick = ( ( lpCLOCK_INPUT_FREQUENCY / configTICK_RATE_HZ ) - 1 ); + +/* Holds the maximum number of ticks that can be suppressed - which is +basically how far into the future an interrupt can be generated. Set during +initialisation. */ +static TickType_t xMaximumPossibleSuppressedTicks = 0; + +/* Flag set from the tick interrupt to allow the sleep processing to know if +sleep mode was exited because of an tick interrupt or a different interrupt. */ +static volatile uint32_t ulTickFlag = pdFALSE; + +/*-----------------------------------------------------------*/ + +/* The tick interrupt handler. This is always the same other than the part that +clears the interrupt, which is specific to the clock being used to generate the +tick. */ +void TIM2_IRQHandler( void ) +{ + /* Clear the interrupt. */ + TIM_ClearITPendingBit( TIM2, TIM_IT_Update ); + + /* The next block of code is from the standard FreeRTOS tick interrupt + handler. The standard handler is not called directly in case future + versions contain changes that make it no longer suitable for calling + here. */ + ( void ) portSET_INTERRUPT_MASK_FROM_ISR(); + { + if( xTaskIncrementTick() != pdFALSE ) + { + portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT; + } + + /* Just completely clear the interrupt mask on exit by passing 0 because + it is known that this interrupt will only ever execute with the lowest + possible interrupt priority. */ + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( 0 ); + + /* In case this is the first tick since the MCU left a low power mode the + reload value is reset to its default. */ + TIM2->ARR = ( uint16_t ) ulReloadValueForOneTick; + + /* The CPU woke because of a tick. */ + ulTickFlag = pdTRUE; +} +/*-----------------------------------------------------------*/ + +/* Override the default definition of vPortSetupTimerInterrupt() that is weakly +defined in the FreeRTOS Cortex-M3 port layer with a version that configures TIM2 +to generate the tick interrupt. */ +void vPortSetupTimerInterrupt( void ) +{ +NVIC_InitTypeDef NVIC_InitStructure; +TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; + + /* Enable the TIM2 clock. */ + RCC_APB1PeriphClockCmd( RCC_APB1Periph_TIM2, ENABLE ); + + /* Ensure clock stops in debug mode. */ + DBGMCU_APB1_FZ |= DBGMCU_APB1_FZ_DBG_TIM2_STOP; + + /* Scale the clock so longer tickless periods can be achieved. The SysTick + is not used as even when its frequency is divided by 8 the maximum tickless + period with a system clock of 16MHz is only 8.3 seconds. Using a prescaled + clock on the 16-bit TIM2 allows a tickless period of nearly 66 seconds, + albeit at low resolution. */ + TIM_TimeBaseStructure.TIM_Prescaler = ( uint16_t ) ( SystemCoreClock / lpCLOCK_INPUT_FREQUENCY ); + TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; + TIM_TimeBaseStructure.TIM_Period = ( uint16_t ) ( lpCLOCK_INPUT_FREQUENCY / configTICK_RATE_HZ ); + TIM_TimeBaseStructure.TIM_ClockDivision = 0; + TIM_TimeBaseInit( TIM2, &TIM_TimeBaseStructure ); + + /* Enable the TIM2 interrupt. This must execute at the lowest interrupt + priority. */ + NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn; + NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = configLIBRARY_LOWEST_INTERRUPT_PRIORITY; /* Must be set to lowest priority. */ + NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; + NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; + NVIC_Init(&NVIC_InitStructure); + TIM_ITConfig( TIM2, TIM_IT_Update, ENABLE ); + TIM_SetCounter( TIM2, 0 ); + TIM_Cmd( TIM2, ENABLE ); + + /* See the comments where xMaximumPossibleSuppressedTicks is declared. */ + xMaximumPossibleSuppressedTicks = ( ( unsigned long ) USHRT_MAX ) / ulReloadValueForOneTick; +} +/*-----------------------------------------------------------*/ + +/* Override the default definition of vPortSuppressTicksAndSleep() that is +weakly defined in the FreeRTOS Cortex-M3 port layer with a version that manages +the TIM2 interrupt, as the tick is generated from TIM2 compare matches events. */ +void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime ) +{ +uint32_t ulCounterValue, ulCompleteTickPeriods; +eSleepModeStatus eSleepAction; +TickType_t xModifiableIdleTime; +const TickType_t xRegulatorOffIdleTime = 30; + + /* THIS FUNCTION IS CALLED WITH THE SCHEDULER SUSPENDED. */ + + /* Make sure the TIM2 reload value does not overflow the counter. */ + if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks ) + { + xExpectedIdleTime = xMaximumPossibleSuppressedTicks; + } + + /* Calculate the reload value required to wait xExpectedIdleTime tick + periods. */ + ulCounterValue = ulReloadValueForOneTick * xExpectedIdleTime; + + /* Stop TIM2 momentarily. The time TIM2 is stopped for is not accounted for + in this implementation (as it is in the generic implementation) because the + clock is so slow it is unlikely to be stopped for a complete count period + anyway. */ + TIM_Cmd( TIM2, DISABLE ); + + /* Enter a critical section but don't use the taskENTER_CRITICAL() method as + that will mask interrupts that should exit sleep mode. */ + __asm volatile ( "cpsid i" ); + __asm volatile ( "dsb" ); + __asm volatile ( "isb" ); + + /* The tick flag is set to false before sleeping. If it is true when sleep + mode is exited then sleep mode was probably exited because the tick was + suppressed for the entire xExpectedIdleTime period. */ + ulTickFlag = pdFALSE; + + /* If a context switch is pending then abandon the low power entry as + the context switch might have been pended by an external interrupt that + requires processing. */ + eSleepAction = eTaskConfirmSleepModeStatus(); + if( eSleepAction == eAbortSleep ) + { + /* Restart tick. */ + TIM_Cmd( TIM2, ENABLE ); + + /* Re-enable interrupts - see comments above the cpsid instruction() + above. */ + __asm volatile ( "cpsie i" ); + } + else if( eSleepAction == eNoTasksWaitingTimeout ) + { + /* A user definable macro that allows application code to be inserted + here. Such application code can be used to minimise power consumption + further by turning off IO, peripheral clocks, the Flash, etc. */ + configPRE_STOP_PROCESSING(); + + /* There are no running state tasks and no tasks that are blocked with a + time out. Assuming the application does not care if the tick time slips + with respect to calendar time then enter a deep sleep that can only be + woken by (in this demo case) the user button being pushed on the + STM32L discovery board. If the application does require the tick time + to keep better track of the calender time then the RTC peripheral can be + used to make rough adjustments. */ + PWR_EnterSTOPMode( PWR_Regulator_LowPower, PWR_SLEEPEntry_WFI ); + + /* A user definable macro that allows application code to be inserted + here. Such application code can be used to reverse any actions taken + by the configPRE_STOP_PROCESSING(). In this demo + configPOST_STOP_PROCESSING() is used to re-initialise the clocks that + were turned off when STOP mode was entered. */ + configPOST_STOP_PROCESSING(); + + /* Restart tick. */ + TIM_SetCounter( TIM2, 0 ); + TIM_Cmd( TIM2, ENABLE ); + + /* Re-enable interrupts - see comments above the cpsid instruction() + above. */ + __asm volatile ( "cpsie i" ); + __asm volatile ( "dsb" ); + __asm volatile ( "isb" ); + } + else + { + /* Trap underflow before the next calculation. */ + configASSERT( ulCounterValue >= TIM_GetCounter( TIM2 ) ); + + /* Adjust the TIM2 value to take into account that the current time + slice is already partially complete. */ + ulCounterValue -= ( uint32_t ) TIM_GetCounter( TIM2 ); + + /* Trap overflow/underflow before the calculated value is written to + TIM2. */ + configASSERT( ulCounterValue < ( uint32_t ) USHRT_MAX ); + configASSERT( ulCounterValue != 0 ); + + /* Update to use the calculated overflow value. */ + TIM_SetAutoreload( TIM2, ( uint16_t ) ulCounterValue ); + TIM_SetCounter( TIM2, 0 ); + + /* Restart the TIM2. */ + TIM_Cmd( TIM2, ENABLE ); + + /* Allow the application to define some pre-sleep processing. This is + the standard configPRE_SLEEP_PROCESSING() macro as described on the + FreeRTOS.org website. */ + xModifiableIdleTime = xExpectedIdleTime; + configPRE_SLEEP_PROCESSING( xModifiableIdleTime ); + + /* xExpectedIdleTime being set to 0 by configPRE_SLEEP_PROCESSING() + means the application defined code has already executed the wait/sleep + instruction. */ + if( xModifiableIdleTime > 0 ) + { + /* The sleep mode used is dependent on the expected idle time + as the deeper the sleep the longer the wake up time. See the + comments at the top of main_low_power.c. Note xRegulatorOffIdleTime + is set purely for convenience of demonstration and is not intended + to be an optimised value. */ + if( xModifiableIdleTime > xRegulatorOffIdleTime ) + { + /* A slightly lower power sleep mode with a longer wake up + time. */ + PWR_EnterSleepMode( PWR_Regulator_LowPower, PWR_SLEEPEntry_WFI ); + } + else + { + /* A slightly higher power sleep mode with a faster wake up + time. */ + PWR_EnterSleepMode( PWR_Regulator_ON, PWR_SLEEPEntry_WFI ); + } + } + + /* Allow the application to define some post sleep processing. This is + the standard configPOST_SLEEP_PROCESSING() macro, as described on the + FreeRTOS.org website. */ + configPOST_SLEEP_PROCESSING( xModifiableIdleTime ); + + /* Stop TIM2. Again, the time the clock is stopped for in not accounted + for here (as it would normally be) because the clock is so slow it is + unlikely it will be stopped for a complete count period anyway. */ + TIM_Cmd( TIM2, DISABLE ); + + /* Re-enable interrupts - see comments above the cpsid instruction() + above. */ + __asm volatile ( "cpsie i" ); + __asm volatile ( "dsb" ); + __asm volatile ( "isb" ); + + if( ulTickFlag != pdFALSE ) + { + /* Trap overflows before the next calculation. */ + configASSERT( ulReloadValueForOneTick >= ( uint32_t ) TIM_GetCounter( TIM2 ) ); + + /* The tick interrupt has already executed, although because this + function is called with the scheduler suspended the actual tick + processing will not occur until after this function has exited. + Reset the reload value with whatever remains of this tick period. */ + ulCounterValue = ulReloadValueForOneTick - ( uint32_t ) TIM_GetCounter( TIM2 ); + + /* Trap under/overflows before the calculated value is used. */ + configASSERT( ulCounterValue <= ( uint32_t ) USHRT_MAX ); + configASSERT( ulCounterValue != 0 ); + + /* Use the calculated reload value. */ + TIM_SetAutoreload( TIM2, ( uint16_t ) ulCounterValue ); + TIM_SetCounter( TIM2, 0 ); + + /* The tick interrupt handler will already have pended the tick + processing in the kernel. As the pending tick will be processed as + soon as this function exits, the tick value maintained by the tick + is stepped forward by one less than the time spent sleeping. The + actual stepping of the tick appears later in this function. */ + ulCompleteTickPeriods = xExpectedIdleTime - 1UL; + } + else + { + /* Something other than the tick interrupt ended the sleep. How + many complete tick periods passed while the processor was + sleeping? */ + ulCompleteTickPeriods = ( ( uint32_t ) TIM_GetCounter( TIM2 ) ) / ulReloadValueForOneTick; + + /* Check for over/under flows before the following calculation. */ + configASSERT( ( ( uint32_t ) TIM_GetCounter( TIM2 ) ) >= ( ulCompleteTickPeriods * ulReloadValueForOneTick ) ); + + /* The reload value is set to whatever fraction of a single tick + period remains. */ + ulCounterValue = ( ( uint32_t ) TIM_GetCounter( TIM2 ) ) - ( ulCompleteTickPeriods * ulReloadValueForOneTick ); + configASSERT( ulCounterValue <= ( uint32_t ) USHRT_MAX ); + if( ulCounterValue == 0 ) + { + /* There is no fraction remaining. */ + ulCounterValue = ulReloadValueForOneTick; + ulCompleteTickPeriods++; + } + TIM_SetAutoreload( TIM2, ( uint16_t ) ulCounterValue ); + TIM_SetCounter( TIM2, 0 ); + } + + /* Restart TIM2 so it runs up to the reload value. The reload value + will get set to the value required to generate exactly one tick period + the next time the TIM2 interrupt executes. */ + TIM_Cmd( TIM2, ENABLE ); + + /* Wind the tick forward by the number of tick periods that the CPU + remained in a low power state. */ + vTaskStepTick( ulCompleteTickPeriods ); + } +} + +#endif /* configCREATE_LOW_POWER_DEMO == 1 */ + diff --git a/pool/shard000/C/0010961_grib_points.c b/pool/shard000/C/0010961_grib_points.c new file mode 100644 index 0000000000000000000000000000000000000000..7f0059c0474dc61d4f0095caec02764bfe4d76f6 --- /dev/null +++ b/pool/shard000/C/0010961_grib_points.c @@ -0,0 +1,199 @@ +/* + * Copyright 2005-2017 ECMWF. + * + * This software is licensed under the terms of the Apache Licence Version 2.0 + * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. + * + * In applying this licence, ECMWF does not waive the privileges and immunities granted to it by + * virtue of its status as an intergovernmental organisation nor does it submit to any jurisdiction. + */ + +/* + * C Implementation: grib_ls + * + */ +#include "grib_tools.h" + +grib_option grib_options[]={ +/* {id, args, help}, on, command_line, value*/ + {"f",0,0,0,1,0}, + {"p:",0,0,1,1,0}, + {"P:",0,0,0,1,0}, + {"w:",0,0,0,1,0}, + {"B:",0,0,0,1,0}, + {"i:",0,0,0,1,0}, + {"m",0,0,0,1,0}, + {"V",0,0,0,1,0}, + {"W:",0,0,1,1,"10"}, + {"S",0,0,1,0,0}, + {"M",0,0,0,1,0}, + {"H",0,0,1,0,0}, + {"P",0,0,1,0,0}, + {"G",0,0,0,1,0}, + {"7",0,0,0,1,0}, + {"v",0,0,1,0,0} +}; + +char* grib_tool_description="Lat lon values list for given points list. "; +char* grib_tool_name="grib_points"; +char* grib_tool_usage="file_list_of_points grib_file grib_file ..."; + +int grib_options_count=sizeof(grib_options)/sizeof(grib_option); +double lat=0; +double lon=0; +int mode=0; +grib_nearest* n=NULL; + +int main(int argc, char *argv[]) { return grib_tool(argc,argv);} + +int grib_tool_before_getopt(grib_runtime_options* options) { + return 0; +} + +int grib_tool_init(grib_runtime_options* options) { + char *theEnd = NULL, *end1=NULL; + size_t size=4; + int ret=0; + double min=0,max=0; + int i=0,idx=0; + char* p=NULL; + if (options->latlon) { + + lat = strtod(options->latlon,&theEnd); + if (*theEnd != '/') { + printf("ERROR: wrong latitude value\n"); + exit(1); + } + lon= strtod(++theEnd,&end1); + if (lon<0) lon+=360; + + mode=GRIB_NEAREST_SAME_POINT | GRIB_NEAREST_SAME_GRID; + + if (end1 && *end1 == '/') { + end1++; + if (*end1 != '0') { + p=end1; + while (*p != '/' && *p !='\0') p++; + if (*end1 == '4') { + options->latlon_mode=4; + } else if (*end1 == '1') { + options->latlon_mode=1; + } else { + printf("ERROR %s: wrong mode given in option -l\n",grib_tool_name); + exit(1); + } + } + if (*p == '/') { + p++; + options->latlon_mask=strdup(p); + } + } + + + } + + if (options->latlon && options->latlon_mask) { + FILE* f=NULL; + grib_handle* hh; + f=fopen(options->latlon_mask,"r"); + if(!f) { + perror(options->latlon_mask); + exit(1); + } + hh=grib_handle_new_from_file(0,f,&ret); + fclose(f); + GRIB_CHECK_NOLINE(ret,0); + n=grib_nearest_new(hh,&ret); + GRIB_CHECK_NOLINE(ret,0); + GRIB_CHECK_NOLINE(grib_nearest_find(n,hh,lat,lon,mode, + options->lats,options->lons,options->mask_values,options->distances,options->indexes,&size),0); + grib_nearest_delete(n); + n=NULL; + grib_handle_delete( hh); + + options->latlon_idx=-1; + max=options->distances[0]; + for (i=0;i<4;i++) + if (maxdistances[i]) {max=options->distances[i];idx=i;} + min=max; + for (i=0;i<4;i++) { + if ((min >= options->distances[i]) && (options->mask_values[i] >= 0.5)) { + options->latlon_idx=i; + min = options->distances[i]; + } + } + + if (options->latlon_idx<0){ + min=0; + options->latlon_idx=0; + for (i=1;i<4;i++) + if (min>options->distances[i]) { + min = options->distances[i]; + options->latlon_idx=i; + } + } + } + + return 0; +} + +int grib_tool_new_filename_action(grib_runtime_options* options,const char* file) { + return 0; + } + + +int grib_tool_new_file_action(grib_runtime_options* options,grib_tools_file* file) { + return 0; +} + +int grib_tool_new_handle_action(grib_runtime_options* options, grib_handle* h) { + size_t size=4; + + if (options->latlon) { + int err=0; + if (!n) n=grib_nearest_new(h,&err); + GRIB_CHECK_NOLINE(grib_nearest_find(n,h,lat,lon,mode, + options->lats,options->lons,options->values, + options->distances,options->indexes,&size),0); + + } + return 0; +} + +int grib_tool_finalise_action(grib_runtime_options* options) { + double radius=6371; + int i=0; + if (options->latlon) { + printf("Input Point: latitude=%.2f longitude=%.2f\n",lat,lon); + printf("Grid Point chosen #%d index=%d latitude=%.2f longitude=%.2f distance=%.2f (Km)\n", + options->latlon_idx+1,(int)options->indexes[options->latlon_idx], + options->lats[options->latlon_idx], + options->lons[options->latlon_idx], + options->distances[options->latlon_idx]*radius); + + if (options->latlon_mask) { + printf("Mask values:\n"); + for (i=0;i<4;i++) { + printf("- %d - index=%d latitude=%.2f longitude=%.2f distance=%.2f (Km) value=%.2f\n", + i+1,(int)options->indexes[i],options->lats[i],options->lons[i], + options->distances[i]*radius,options->mask_values[i]); + } + } else { + printf("Other grid Points\n"); + for (i=0;i<4;i++) { + printf("- %d - index=%d latitude=%.2f longitude=%.2f distance=%.2f (Km)\n", + i+1,(int)options->indexes[i],options->lats[i],options->lons[i], + options->distances[i]*radius); + } + } + + if (n) grib_nearest_delete(n); + } + return 0; +} + +int grib_no_handle_action(int err) { + fprintf(dump_file,"\t\t\"ERROR: unreadable message\"\n"); + return 0; +} + diff --git a/pool/shard000/C/0010987_ctest_rm_03.c b/pool/shard000/C/0010987_ctest_rm_03.c new file mode 100644 index 0000000000000000000000000000000000000000..265442bedb82b37eee563d01d56d09187cc2dc80 --- /dev/null +++ b/pool/shard000/C/0010987_ctest_rm_03.c @@ -0,0 +1,169 @@ +/* Copyright 2008, 2009 Mariano Cerdeiro + * Copyright 2014, ACSE & CADIEEL + * ACSE: http://www.sase.com.ar/asociacion-civil-sistemas-embebidos/ciaa/ + * CADIEEL: http://www.cadieel.org.ar + * + * This file is part of CIAA Firmware. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder 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. + * + */ + +/** \brief FreeOSEK Os Conformance Test for the Resource Managment, Test Sequence 3 + ** + ** \file FreeOSEK/Os/tst/ctest/src/ctest_rm_03.c + **/ + +/** \addtogroup FreeOSEK + ** @{ */ +/** \addtogroup FreeOSEK_Os + ** @{ */ +/** \addtogroup FreeOSEK_Os_CT Conformance Test + ** @{ */ +/** \addtogroup FreeOSEK_Os_CT_RM Resource Management + ** @{ */ +/** \addtogroup FreeOSEK_Os_CT_RM_03 Test Sequence 3 + ** @{ */ + +/* + * Initials Name + * --------------------------- + * MaCe Mariano Cerdeiro + */ + +/* + * modification history (new versions first) + * ----------------------------------------------------------- + * 20090414 v0.1.0 MaCe initial version based on old moduletest + */ + +/*==================[inclusions]=============================================*/ +#include "os.h" /* include os header file */ +#include "ctest_rm_03.h" /* include test header file */ +#include "ctest.h" /* include ctest header file */ + +/*==================[macros and definitions]=================================*/ + +/*==================[internal data declaration]==============================*/ + +/*==================[internal functions declaration]=========================*/ + +/*==================[internal data definition]===============================*/ + +/*==================[external data definition]===============================*/ +const uint32f SequenceCounterOk = MAX_SEQUENCE; + +/*==================[internal functions definition]==========================*/ + +/*==================[external functions definition]==========================*/ +int main +( + void +) +{ + /* start OS in AppMode 1 */ + StartOS(AppMode1); + + /* shall never return */ + while(1); + + return 0; +} + +TASK(Task1) +{ + StatusType ret; + + Sequence(0); + /* \treq RM_07 mf B1B2E1E2 se Test Priority Ceiling Protocol: Call + * GetResource() rom preemptive task, and activate task with priority + * higher than the running task but lower than ceiling priority + * + * \result Resource is occupied and running task's priority is set to the + * resource's ceiling priority. Service returns E_OK. No preemption occurrs + * after activating the task with higher priotiy and rescheduling + */ + ret = GetResource(Resource1); + ASSERT(RM_07, ret != E_OK); + + Sequence(1); + ret = ActivateTask(Task2); + ASSERT(OTHER, ret != E_OK); + + Sequence(2); + ret = ActivateTask(Task3); + ASSERT(OTHER, ret != E_OK); + + Sequence(4); + /* \treq RM_14 mf B1B2E1E2 se Call ReleaseResource() from preemptive task + * + * \result Resource is released and running task's priority is reset. Ready + * task with highest priority is executed (Rescheduling). Service returns + * E_OK + */ + ret = ReleaseResource(Resource1); + ASSERT(RM_14, ret != E_OK); + +#if (CT_SCHEDULING_Task1 == CT_NON_PREEMPTIVE) + /* force scheduling */ + Schedule(); +#endif /* #if (CT_SCHEDULING_TASK1 == CT_NON_PREEMPTIVE) */ + + Sequence(6); + + /* evaluate conformance tests */ + ConfTestEvaluation(); + + /* finish the conformance test */ + ConfTestFinish(); +} + +TASK(Task2) +{ + Sequence(5); + TerminateTask(); +} + +TASK(Task3) +{ + Sequence(3); + TerminateTask(); +} + +/* This task is not used, only to change the scheduling police */ +TASK(Task4) +{ + TerminateTask(); +} + +/** @} doxygen end group definition */ +/** @} doxygen end group definition */ +/** @} doxygen end group definition */ +/** @} doxygen end group definition */ +/** @} doxygen end group definition */ +/*==================[end of file]============================================*/ + diff --git a/pool/shard000/C/0010990_menuCredits.c b/pool/shard000/C/0010990_menuCredits.c new file mode 100644 index 0000000000000000000000000000000000000000..554c11eac0181bd33526c89a494f5d61ed189b3f --- /dev/null +++ b/pool/shard000/C/0010990_menuCredits.c @@ -0,0 +1,76 @@ +#include +#include "tetris.h" +#include "score.h" +#include "menu.h" +#include "font.h" +#include "sfx.h" + +Sint32 menuCreditsInit(void *pArgs) { + menu_t *this = pArgs; + + (void)this; + eventClear(); + + return 0; +} + +Sint32 menuCreditsRelease(void *pArgs) { + menu_t *this = pArgs; + + (void)this; + sfxPlaySound(SFX_PLAY_ROTATE, SFX_REPEAT_OFF); + return 0; +} + +static Sint32 menuCreditsEvents(void *pArgs) { + menu_t *this = pArgs; + + (void)this; + + if (gVars.nKeyb[KEY_SPACE]) { + gVars.nKeyb[KEY_SPACE] = KEY_NONE; + return 0; + } + + return -1; +} + +Sint32 menuCreditsMain(void *pArgs) { + menu_t *this = pArgs; + Uint32 i; + struct { + char *s; + Uint32 nCol; + } pTab[] = { + { "programer", FONT_COL_WHITE_RED }, + { "pouet", FONT_COL_BLUE_BLUE }, + { "", FONT_COL_WHITE_RED }, + { "", FONT_COL_WHITE_RED }, + { "sprites", FONT_COL_WHITE_RED }, + { "pouet", FONT_COL_BLUE_BLUE }, + { "jdaster64", FONT_COL_BLUE_BLUE }, + { "viiper", FONT_COL_BLUE_BLUE }, + { "beam luinsir", FONT_COL_BLUE_BLUE }, + { "and other...", FONT_COL_BLUE_BLUE }, + { "", FONT_COL_WHITE_RED }, + { "", FONT_COL_WHITE_RED }, + { "", FONT_COL_WHITE_RED }, + { "thanks to", FONT_COL_WHITE_RED }, + { "joe78", FONT_COL_BLUE_BLUE }, + { "GurneyH", FONT_COL_BLUE_BLUE }, + }; + + (void)this; + + blitTexture(gVars.pBackground, 0, 0, NULL); + + for (i = 0; i < sizeof pTab / sizeof pTab[0]; i++) { + printText(pTab[i].s, MENU_FONT_SIZE, + pTab[i].nCol, MENU_OFFX + 10, MENU_OFFY + 30 * i); + } + + if (menuCreditsEvents(pArgs) >= 0) + return MENU_MAIN; + + return MENU_NULL; +} diff --git a/pool/shard000/C/0010994_gsl_specfunc__bessel_Knu.c b/pool/shard000/C/0010994_gsl_specfunc__bessel_Knu.c new file mode 100644 index 0000000000000000000000000000000000000000..b468510960c718756bd0d7d02c2486372b32b3cd --- /dev/null +++ b/pool/shard000/C/0010994_gsl_specfunc__bessel_Knu.c @@ -0,0 +1,164 @@ +/* specfunc/bessel_Knu.c + * + * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman + * + * 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 + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +/* Author: G. Jungman */ + +#include "gsl__config.h" +#include "gsl_math.h" +#include "gsl_errno.h" +#include "gsl_sf_exp.h" +#include "gsl_sf_gamma.h" +#include "gsl_sf_bessel.h" + +#include "gsl_specfunc__error.h" + +#include "gsl_specfunc__bessel.h" +#include "gsl_specfunc__bessel_temme.h" + +/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/ + +int +gsl_sf_bessel_Knu_scaled_e(const double nu, const double x, gsl_sf_result * result) +{ + /* CHECK_POINTER(result) */ + + if(x <= 0.0 || nu < 0.0) { + DOMAIN_ERROR(result); + } + else { + int N = (int)(nu + 0.5); + double mu = nu - N; /* -1/2 <= mu <= 1/2 */ + double K_mu, K_mup1, Kp_mu; + double K_nu, K_nup1, K_num1; + int n; + + if(x < 2.0) { + gsl_sf_bessel_K_scaled_temme(mu, x, &K_mu, &K_mup1, &Kp_mu); + } + else { + gsl_sf_bessel_K_scaled_steed_temme_CF2(mu, x, &K_mu, &K_mup1, &Kp_mu); + } + + /* recurse forward to obtain K_num1, K_nu */ + K_nu = K_mu; + K_nup1 = K_mup1; + + for(n=0; nval = K_nu; + result->err = 2.0 * GSL_DBL_EPSILON * (N + 4.0) * fabs(result->val); + return GSL_SUCCESS; + } +} + + +int +gsl_sf_bessel_Knu_e(const double nu, const double x, gsl_sf_result * result) +{ + gsl_sf_result b; + int stat_K = gsl_sf_bessel_Knu_scaled_e(nu, x, &b); + int stat_e = gsl_sf_exp_mult_err_e(-x, 0.0, b.val, b.err, result); + return GSL_ERROR_SELECT_2(stat_e, stat_K); +} + + +int +gsl_sf_bessel_lnKnu_e(const double nu, const double x, gsl_sf_result * result) +{ + /* CHECK_POINTER(result) */ + + if(x <= 0.0 || nu < 0.0) { + DOMAIN_ERROR(result); + } + else if(nu == 0.0) { + gsl_sf_result K_scaled; + /* This cannot underflow, and + * it will not throw GSL_EDOM + * since that is already checked. + */ + gsl_sf_bessel_K0_scaled_e(x, &K_scaled); + result->val = -x + log(fabs(K_scaled.val)); + result->err = GSL_DBL_EPSILON * fabs(x) + fabs(K_scaled.err/K_scaled.val); + result->err += GSL_DBL_EPSILON * fabs(result->val); + return GSL_SUCCESS; + } + else if(x < 2.0 && nu > 1.0) { + /* Make use of the inequality + * Knu(x) <= 1/2 (2/x)^nu Gamma(nu), + * which follows from the integral representation + * [Abramowitz+Stegun, 9.6.23 (2)]. With this + * we decide whether or not there is an overflow + * problem because x is small. + */ + double ln_bound; + gsl_sf_result lg_nu; + gsl_sf_lngamma_e(nu, &lg_nu); + ln_bound = -M_LN2 - nu*log(0.5*x) + lg_nu.val; + if(ln_bound > GSL_LOG_DBL_MAX - 20.0) { + /* x must be very small or nu very large (or both). + */ + double xi = 0.25*x*x; + double sum = 1.0 - xi/(nu-1.0); + if(nu > 2.0) sum += (xi/(nu-1.0)) * (xi/(nu-2.0)); + result->val = ln_bound + log(sum); + result->err = lg_nu.err; + result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); + return GSL_SUCCESS; + } + /* can drop-through here */ + } + + + { + /* We passed the above tests, so no problem. + * Evaluate as usual. Note the possible drop-through + * in the above code! + */ + gsl_sf_result K_scaled; + gsl_sf_bessel_Knu_scaled_e(nu, x, &K_scaled); + result->val = -x + log(fabs(K_scaled.val)); + result->err = GSL_DBL_EPSILON * fabs(x) + fabs(K_scaled.err/K_scaled.val); + result->err += GSL_DBL_EPSILON * fabs(result->val); + return GSL_SUCCESS; + } +} + + +/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/ + +#include "gsl_specfunc__eval.h" + +double gsl_sf_bessel_Knu_scaled(const double nu, const double x) +{ + EVAL_RESULT(gsl_sf_bessel_Knu_scaled_e(nu, x, &result)); +} + +double gsl_sf_bessel_Knu(const double nu, const double x) +{ + EVAL_RESULT(gsl_sf_bessel_Knu_e(nu, x, &result)); +} + +double gsl_sf_bessel_lnKnu(const double nu, const double x) +{ + EVAL_RESULT(gsl_sf_bessel_lnKnu_e(nu, x, &result)); +} diff --git a/pool/shard000/C/0010996_setup_percpu.c b/pool/shard000/C/0010996_setup_percpu.c new file mode 100644 index 0000000000000000000000000000000000000000..ea554f812ee18e46289bb1fc9b65cc7408189a74 --- /dev/null +++ b/pool/shard000/C/0010996_setup_percpu.c @@ -0,0 +1,301 @@ +// SPDX-License-Identifier: GPL-2.0 +#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +DEFINE_PER_CPU_READ_MOSTLY(int, cpu_number); +EXPORT_PER_CPU_SYMBOL(cpu_number); + +#ifdef CONFIG_X86_64 +#define BOOT_PERCPU_OFFSET ((unsigned long)__per_cpu_load) +#else +#define BOOT_PERCPU_OFFSET 0 +#endif + +DEFINE_PER_CPU_READ_MOSTLY(unsigned long, this_cpu_off) = BOOT_PERCPU_OFFSET; +EXPORT_PER_CPU_SYMBOL(this_cpu_off); + +unsigned long __per_cpu_offset[NR_CPUS] __ro_after_init = { + [0 ... NR_CPUS-1] = BOOT_PERCPU_OFFSET, +}; +EXPORT_SYMBOL(__per_cpu_offset); + +/* + * On x86_64 symbols referenced from code should be reachable using + * 32bit relocations. Reserve space for static percpu variables in + * modules so that they are always served from the first chunk which + * is located at the percpu segment base. On x86_32, anything can + * address anywhere. No need to reserve space in the first chunk. + */ +#ifdef CONFIG_X86_64 +#define PERCPU_FIRST_CHUNK_RESERVE PERCPU_MODULE_RESERVE +#else +#define PERCPU_FIRST_CHUNK_RESERVE 0 +#endif + +#ifdef CONFIG_X86_32 +/** + * pcpu_need_numa - determine percpu allocation needs to consider NUMA + * + * If NUMA is not configured or there is only one NUMA node available, + * there is no reason to consider NUMA. This function determines + * whether percpu allocation should consider NUMA or not. + * + * RETURNS: + * true if NUMA should be considered; otherwise, false. + */ +static bool __init pcpu_need_numa(void) +{ +#ifdef CONFIG_NEED_MULTIPLE_NODES + pg_data_t *last = NULL; + unsigned int cpu; + + for_each_possible_cpu(cpu) { + int node = early_cpu_to_node(cpu); + + if (node_online(node) && NODE_DATA(node) && + last && last != NODE_DATA(node)) + return true; + + last = NODE_DATA(node); + } +#endif + return false; +} +#endif + +/** + * pcpu_alloc_bootmem - NUMA friendly alloc_bootmem wrapper for percpu + * @cpu: cpu to allocate for + * @size: size allocation in bytes + * @align: alignment + * + * Allocate @size bytes aligned at @align for cpu @cpu. This wrapper + * does the right thing for NUMA regardless of the current + * configuration. + * + * RETURNS: + * Pointer to the allocated area on success, NULL on failure. + */ +static void * __init pcpu_alloc_bootmem(unsigned int cpu, unsigned long size, + unsigned long align) +{ + const unsigned long goal = __pa(MAX_DMA_ADDRESS); +#ifdef CONFIG_NEED_MULTIPLE_NODES + int node = early_cpu_to_node(cpu); + void *ptr; + + if (!node_online(node) || !NODE_DATA(node)) { + ptr = __alloc_bootmem_nopanic(size, align, goal); + pr_info("cpu %d has no node %d or node-local memory\n", + cpu, node); + pr_debug("per cpu data for cpu%d %lu bytes at %016lx\n", + cpu, size, __pa(ptr)); + } else { + ptr = __alloc_bootmem_node_nopanic(NODE_DATA(node), + size, align, goal); + pr_debug("per cpu data for cpu%d %lu bytes on node%d at %016lx\n", + cpu, size, node, __pa(ptr)); + } + return ptr; +#else + return __alloc_bootmem_nopanic(size, align, goal); +#endif +} + +/* + * Helpers for first chunk memory allocation + */ +static void * __init pcpu_fc_alloc(unsigned int cpu, size_t size, size_t align) +{ + return pcpu_alloc_bootmem(cpu, size, align); +} + +static void __init pcpu_fc_free(void *ptr, size_t size) +{ + free_bootmem(__pa(ptr), size); +} + +static int __init pcpu_cpu_distance(unsigned int from, unsigned int to) +{ +#ifdef CONFIG_NEED_MULTIPLE_NODES + if (early_cpu_to_node(from) == early_cpu_to_node(to)) + return LOCAL_DISTANCE; + else + return REMOTE_DISTANCE; +#else + return LOCAL_DISTANCE; +#endif +} + +static void __init pcpup_populate_pte(unsigned long addr) +{ + populate_extra_pte(addr); +} + +static inline void setup_percpu_segment(int cpu) +{ +#ifdef CONFIG_X86_32 + struct desc_struct d = GDT_ENTRY_INIT(0x8092, per_cpu_offset(cpu), + 0xFFFFF); + + write_gdt_entry(get_cpu_gdt_rw(cpu), GDT_ENTRY_PERCPU, &d, DESCTYPE_S); +#endif +} + +void __init setup_per_cpu_areas(void) +{ + unsigned int cpu; + unsigned long delta; + int rc; + + pr_info("NR_CPUS:%d nr_cpumask_bits:%d nr_cpu_ids:%u nr_node_ids:%d\n", + NR_CPUS, nr_cpumask_bits, nr_cpu_ids, nr_node_ids); + + /* + * Allocate percpu area. Embedding allocator is our favorite; + * however, on NUMA configurations, it can result in very + * sparse unit mapping and vmalloc area isn't spacious enough + * on 32bit. Use page in that case. + */ +#ifdef CONFIG_X86_32 + if (pcpu_chosen_fc == PCPU_FC_AUTO && pcpu_need_numa()) + pcpu_chosen_fc = PCPU_FC_PAGE; +#endif + rc = -EINVAL; + if (pcpu_chosen_fc != PCPU_FC_PAGE) { + const size_t dyn_size = PERCPU_MODULE_RESERVE + + PERCPU_DYNAMIC_RESERVE - PERCPU_FIRST_CHUNK_RESERVE; + size_t atom_size; + + /* + * On 64bit, use PMD_SIZE for atom_size so that embedded + * percpu areas are aligned to PMD. This, in the future, + * can also allow using PMD mappings in vmalloc area. Use + * PAGE_SIZE on 32bit as vmalloc space is highly contended + * and large vmalloc area allocs can easily fail. + */ +#ifdef CONFIG_X86_64 + atom_size = PMD_SIZE; +#else + atom_size = PAGE_SIZE; +#endif + rc = pcpu_embed_first_chunk(PERCPU_FIRST_CHUNK_RESERVE, + dyn_size, atom_size, + pcpu_cpu_distance, + pcpu_fc_alloc, pcpu_fc_free); + if (rc < 0) + pr_warning("%s allocator failed (%d), falling back to page size\n", + pcpu_fc_names[pcpu_chosen_fc], rc); + } + if (rc < 0) + rc = pcpu_page_first_chunk(PERCPU_FIRST_CHUNK_RESERVE, + pcpu_fc_alloc, pcpu_fc_free, + pcpup_populate_pte); + if (rc < 0) + panic("cannot initialize percpu area (err=%d)", rc); + + /* alrighty, percpu areas up and running */ + delta = (unsigned long)pcpu_base_addr - (unsigned long)__per_cpu_start; + for_each_possible_cpu(cpu) { + per_cpu_offset(cpu) = delta + pcpu_unit_offsets[cpu]; + per_cpu(this_cpu_off, cpu) = per_cpu_offset(cpu); + per_cpu(cpu_number, cpu) = cpu; + setup_percpu_segment(cpu); + setup_stack_canary_segment(cpu); + /* + * Copy data used in early init routines from the + * initial arrays to the per cpu data areas. These + * arrays then become expendable and the *_early_ptr's + * are zeroed indicating that the static arrays are + * gone. + */ +#ifdef CONFIG_X86_LOCAL_APIC + per_cpu(x86_cpu_to_apicid, cpu) = + early_per_cpu_map(x86_cpu_to_apicid, cpu); + per_cpu(x86_bios_cpu_apicid, cpu) = + early_per_cpu_map(x86_bios_cpu_apicid, cpu); + per_cpu(x86_cpu_to_acpiid, cpu) = + early_per_cpu_map(x86_cpu_to_acpiid, cpu); +#endif +#ifdef CONFIG_X86_32 + per_cpu(x86_cpu_to_logical_apicid, cpu) = + early_per_cpu_map(x86_cpu_to_logical_apicid, cpu); +#endif +#ifdef CONFIG_X86_64 + per_cpu(irq_stack_ptr, cpu) = + per_cpu(irq_stack_union.irq_stack, cpu) + + IRQ_STACK_SIZE; +#endif +#ifdef CONFIG_NUMA + per_cpu(x86_cpu_to_node_map, cpu) = + early_per_cpu_map(x86_cpu_to_node_map, cpu); + /* + * Ensure that the boot cpu numa_node is correct when the boot + * cpu is on a node that doesn't have memory installed. + * Also cpu_up() will call cpu_to_node() for APs when + * MEMORY_HOTPLUG is defined, before per_cpu(numa_node) is set + * up later with c_init aka intel_init/amd_init. + * So set them all (boot cpu and all APs). + */ + set_cpu_numa_node(cpu, early_cpu_to_node(cpu)); +#endif + /* + * Up to this point, the boot CPU has been using .init.data + * area. Reload any changed state for the boot CPU. + */ + if (!cpu) + switch_to_new_gdt(cpu); + } + + /* indicate the early static arrays will soon be gone */ +#ifdef CONFIG_X86_LOCAL_APIC + early_per_cpu_ptr(x86_cpu_to_apicid) = NULL; + early_per_cpu_ptr(x86_bios_cpu_apicid) = NULL; + early_per_cpu_ptr(x86_cpu_to_acpiid) = NULL; +#endif +#ifdef CONFIG_X86_32 + early_per_cpu_ptr(x86_cpu_to_logical_apicid) = NULL; +#endif +#ifdef CONFIG_NUMA + early_per_cpu_ptr(x86_cpu_to_node_map) = NULL; +#endif + + /* Setup node to cpumask map */ + setup_node_to_cpumask_map(); + + /* Setup cpu initialized, callin, callout masks */ + setup_cpu_local_masks(); + + /* + * Sync back kernel address range again. We already did this in + * setup_arch(), but percpu data also needs to be available in + * the smpboot asm. We can't reliably pick up percpu mappings + * using vmalloc_fault(), because exception dispatch needs + * percpu data. + * + * FIXME: Can the later sync in setup_cpu_entry_areas() replace + * this call? + */ + sync_initial_page_table(); +} diff --git a/pool/shard000/C/0011006_smemcap.c b/pool/shard000/C/0011006_smemcap.c new file mode 100644 index 0000000000000000000000000000000000000000..cdcc891a1225b8779482eb6979d47efcf5a5b674 --- /dev/null +++ b/pool/shard000/C/0011006_smemcap.c @@ -0,0 +1,152 @@ +/* + smemcap - a tool for meaningful memory reporting + + Copyright 2008-2009 Matt Mackall + + This software may be used and distributed according to the terms of + the GNU General Public License version 2 or later, incorporated + herein by reference. +*/ + +//applet:IF_SMEMCAP(APPLET(smemcap, _BB_DIR_USR_BIN, _BB_SUID_DROP)) + +//kbuild:lib-$(CONFIG_SMEMCAP) += smemcap.o + +//config:config SMEMCAP +//config: bool "smemcap" +//config: default y +//config: help +//config: smemcap is a tool for capturing process data for smem, +//config: a memory usage statistic tool. + +#include "libbb.h" + +struct tar_header { + char name[100]; /* 0-99 */ + char mode[8]; /* 100-107 */ + char uid[8]; /* 108-115 */ + char gid[8]; /* 116-123 */ + char size[12]; /* 124-135 */ + char mtime[12]; /* 136-147 */ + char chksum[8]; /* 148-155 */ + char typeflag; /* 156-156 */ + char linkname[100]; /* 157-256 */ + /* POSIX: "ustar" NUL "00" */ + /* GNU tar: "ustar " NUL */ + /* Normally it's defined as magic[6] followed by + * version[2], but we put them together to save code. + */ + char magic[8]; /* 257-264 */ + char uname[32]; /* 265-296 */ + char gname[32]; /* 297-328 */ + char devmajor[8]; /* 329-336 */ + char devminor[8]; /* 337-344 */ + char prefix[155]; /* 345-499 */ + char padding[12]; /* 500-512 (pad to exactly TAR_512) */ +}; + +struct fileblock { + struct fileblock *next; + char data[512]; +}; + +static void writeheader(const char *path, struct stat *sb, int type) +{ + struct tar_header header; + int i, sum; + + memset(&header, 0, 512); + strcpy(header.name, path); + sprintf(header.mode, "%o", sb->st_mode & 0777); + /* careful to not overflow fields! */ + sprintf(header.uid, "%o", sb->st_uid & 07777777); + sprintf(header.gid, "%o", sb->st_gid & 07777777); + sprintf(header.size, "%o", (unsigned)sb->st_size); + sprintf(header.mtime, "%llo", sb->st_mtime & 077777777777LL); + header.typeflag = type; + //strcpy(header.magic, "ustar "); - do we want to be standard-compliant? + + /* Calculate and store the checksum (the sum of all of the bytes of + * the header). The checksum field must be filled with blanks for the + * calculation. The checksum field is formatted differently from the + * other fields: it has 6 digits, a NUL, then a space -- rather than + * digits, followed by a NUL like the other fields... */ + header.chksum[7] = ' '; + sum = ' ' * 7; + for (i = 0; i < 512; i++) + sum += ((unsigned char*)&header)[i]; + sprintf(header.chksum, "%06o", sum); + + xwrite(STDOUT_FILENO, &header, 512); +} + +static void archivefile(const char *path) +{ + struct fileblock *start, *cur; + struct fileblock **prev = &start; + int fd, r; + unsigned size = 0; + struct stat s; + + /* buffer the file */ + fd = xopen(path, O_RDONLY); + do { + cur = xzalloc(sizeof(*cur)); + *prev = cur; + prev = &cur->next; + r = full_read(fd, cur->data, 512); + if (r > 0) + size += r; + } while (r == 512); + + /* write archive header */ + fstat(fd, &s); + close(fd); + s.st_size = size; + writeheader(path, &s, '0'); + + /* dump file contents */ + for (cur = start; (int)size > 0; size -= 512) { + xwrite(STDOUT_FILENO, cur->data, 512); + start = cur; + cur = cur->next; + free(start); + } +} + +static void archivejoin(const char *sub, const char *name) +{ + char path[sizeof(long long)*3 + sizeof("/cmdline")]; + sprintf(path, "%s/%s", sub, name); + archivefile(path); +} + +//usage:#define smemcap_trivial_usage ">SMEMDATA.TAR" +//usage:#define smemcap_full_usage "\n\n" +//usage: "Collect memory usage data in /proc and write it to stdout" + +int smemcap_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE; +int smemcap_main(int argc UNUSED_PARAM, char **argv UNUSED_PARAM) +{ + DIR *d; + struct dirent *de; + + xchdir("/proc"); + d = xopendir("."); + + archivefile("meminfo"); + archivefile("version"); + while ((de = readdir(d)) != NULL) { + if (isdigit(de->d_name[0])) { + struct stat s; + memset(&s, 0, sizeof(s)); + s.st_mode = 0555; + writeheader(de->d_name, &s, '5'); + archivejoin(de->d_name, "smaps"); + archivejoin(de->d_name, "cmdline"); + archivejoin(de->d_name, "stat"); + } + } + + return EXIT_SUCCESS; +} diff --git a/pool/shard000/C/0011007_drm_usb.c b/pool/shard000/C/0011007_drm_usb.c new file mode 100644 index 0000000000000000000000000000000000000000..71a87090eb2565a1cdd69f8a3751bd98282a5e80 --- /dev/null +++ b/pool/shard000/C/0011007_drm_usb.c @@ -0,0 +1,120 @@ +#include "drmP.h" +#include +#include + +int drm_get_usb_dev(struct usb_interface *interface, + const struct usb_device_id *id, + struct drm_driver *driver) +{ + struct drm_device *dev; + struct usb_device *usbdev; + int ret; + + DRM_DEBUG("\n"); + + dev = kzalloc(sizeof(*dev), GFP_KERNEL); + if (!dev) + return -ENOMEM; + + usbdev = interface_to_usbdev(interface); + dev->usbdev = usbdev; + dev->dev = &usbdev->dev; + + mutex_lock(&drm_global_mutex); + + ret = drm_fill_in_dev(dev, NULL, driver); + if (ret) { + printk(KERN_ERR "DRM: Fill_in_dev failed.\n"); + goto err_g1; + } + + usb_set_intfdata(interface, dev); + ret = drm_get_minor(dev, &dev->control, DRM_MINOR_CONTROL); + if (ret) + goto err_g1; + + ret = drm_get_minor(dev, &dev->primary, DRM_MINOR_LEGACY); + if (ret) + goto err_g2; + + if (dev->driver->load) { + ret = dev->driver->load(dev, 0); + if (ret) + goto err_g3; + } + + /* */ + ret = drm_mode_group_init_legacy_group(dev, + &dev->primary->mode_group); + if (ret) + goto err_g3; + + list_add_tail(&dev->driver_item, &driver->device_list); + + mutex_unlock(&drm_global_mutex); + + DRM_INFO("Initialized %s %d.%d.%d %s on minor %d\n", + driver->name, driver->major, driver->minor, driver->patchlevel, + driver->date, dev->primary->index); + + return 0; + +err_g3: + drm_put_minor(&dev->primary); +err_g2: + drm_put_minor(&dev->control); +err_g1: + kfree(dev); + mutex_unlock(&drm_global_mutex); + return ret; + +} +EXPORT_SYMBOL(drm_get_usb_dev); + +static int drm_usb_get_irq(struct drm_device *dev) +{ + return 0; +} + +static const char *drm_usb_get_name(struct drm_device *dev) +{ + return "USB"; +} + +static int drm_usb_set_busid(struct drm_device *dev, + struct drm_master *master) +{ + return 0; +} + +static struct drm_bus drm_usb_bus = { + .bus_type = DRIVER_BUS_USB, + .get_irq = drm_usb_get_irq, + .get_name = drm_usb_get_name, + .set_busid = drm_usb_set_busid, +}; + +int drm_usb_init(struct drm_driver *driver, struct usb_driver *udriver) +{ + int res; + DRM_DEBUG("\n"); + + INIT_LIST_HEAD(&driver->device_list); + driver->kdriver.usb = udriver; + driver->bus = &drm_usb_bus; + + res = usb_register(udriver); + return res; +} +EXPORT_SYMBOL(drm_usb_init); + +void drm_usb_exit(struct drm_driver *driver, + struct usb_driver *udriver) +{ + usb_deregister(udriver); +} +EXPORT_SYMBOL(drm_usb_exit); + +MODULE_AUTHOR("David Airlie"); +MODULE_DESCRIPTION("USB DRM support"); +MODULE_LICENSE("GPL and additional rights"); diff --git a/pool/shard000/C/0011014_ipcom_waitif.c b/pool/shard000/C/0011014_ipcom_waitif.c new file mode 100644 index 0000000000000000000000000000000000000000..ca0b318d9433abfd567ffdaf30c0582af49958c8 --- /dev/null +++ b/pool/shard000/C/0011014_ipcom_waitif.c @@ -0,0 +1,317 @@ +/* + ****************************************************************************** + * SOURCE FILE + * + * Document no: @(#) $Name: VXWORKS_ITER18A_FRZ10 $ + * $Source: /home/interpeak/CVSRoot/ipcom/src/ipcom_waitif.c,v $ + * $State: Exp $ $Locker: $ + * + * INTERPEAK_COPYRIGHT_STRING + ****************************************************************************** + */ + +/* + **************************************************************************** + * 1 DESCRIPTION + **************************************************************************** + * ipcom_waitif.c contains an example of how to wait for an interface to + * acquire an IP address, e.g. when DHCP is used. + * + */ + +/* + **************************************************************************** + * 2 CONFIGURATION + **************************************************************************** + */ + +#include "ipcom_config.h" + +#ifdef IPCOM_USE_WAITIF + +#define IPCOM_SYSLOG_FACILITY IPCOM_LOG_IPCOM +#ifdef IP_DEBUG +#define IPCOM_SYSLOG_PRIORITY IPCOM_LOG_DEBUG +#else +#define IPCOM_SYSLOG_PRIORITY IPCOM_LOG_WARNING +#endif + + +/* + **************************************************************************** + * 3 INCLUDE FILES + **************************************************************************** + */ + +#define IPCOM_USE_CLIB_PROTO +#include +#include +#include +#include +#include +#include +#include + + +/* + **************************************************************************** + * 5 DEFINES + **************************************************************************** + */ + +/* Max # of interfaces to poll */ +#define IPNET_WAITIF_MAXIF 16 + +/* Max timeout to wait for an address */ +#define IPNET_WAITIF_TIMEOUT 60 + +/* + **************************************************************************** + * 9 FUNCTIONS + **************************************************************************** + */ + +/* + *=========================================================================== + * ipcom_waitif_gifaddr + *=========================================================================== + * Description: Get interface address. + * Parameters: fd - socket descriptor + * ifindex - Interface index. + * domain - The address domain. + * Returns: 0 = No address available, 1 = No address available, -1 = error. + * + */ +IP_STATIC int +ipcom_waitif_gifaddr(Ip_fd fd, int ifindex, int domain) +{ + int ret = -1; + + switch (domain) + { + case IP_AF_INET: + { + struct Ip_ifreq ifreq; + + /* Get if name */ + ipcom_memset(&ifreq, 0, sizeof(ifreq)); + (void)ipcom_if_indextoname(ifindex, ifreq.ifr_name); + + /* Get main address */ + if (ipcom_socketioctl(fd, IP_SIOCGIFADDR, &ifreq) < 0) + { + if (ipcom_errno != IP_ERRNO_EADDRNOTAVAIL && ipcom_errno != IP_ERRNO_ENXIO) + { + IPCOM_LOG1(ERR, "ipcom_waitif :: ipcom_socketioctl(SIOCGIFADDR) failed, errno = %d", ipcom_errno); + } + } + else + { + struct Ip_in_addr network = ((struct Ip_sockaddr_in *)&ifreq.ip_ifr_addr)->sin_addr; + + if (network.s_addr != IP_INADDR_DEFAULT) + { + ret = 0; + } + } + break; + } + +#ifdef IPCOM_USE_INET6 + case IP_AF_INET6: + { + int len = IPNET_WAITIF_MAXIF * sizeof(struct Ip_ifreq); + char ifname[IP_IFNAMSIZ]; + struct Ip_ifconf ifc; + char *buf = IP_NULL; + char *ptr; + + /* Get if name */ + (void)ipcom_if_indextoname(ifindex, ifname); + + /* Get if data buffer */ + if ((buf = ipcom_malloc(IPNET_WAITIF_MAXIF * sizeof(struct Ip_ifreq))) == IP_NULL) + { + IPCOM_LOG0(ERR, "ipcom_waitif :: Out of memory"); + goto leave; + } + + /* Enter buf in ifconf struct */ + ifc.ifc_len = len; + ifc.ip_ifc_buf = buf; + + if (ipcom_socketioctl(fd, IP_SIOCGIFCONF, &ifc) < 0) + { + IPCOM_LOG1(ERR, "ipcom_socketioctl(SIOCGIFCONF) failed, errno = %d\n", ipcom_errno); + goto leave; + } + + /* Loop for all interfaces */ + for (ptr = buf; ptr < buf + ifc.ifc_len; ) + { + struct Ip_ifreq *ifr = (struct Ip_ifreq *)ptr; + char *cptr; + + /* Calculate pointer to next if */ + len = IP_MAX(sizeof(struct Ip_sockaddr_in), ifr->ip_ifr_addr.sa_len); + ptr += sizeof(ifr->ifr_name) + len; + + if ((cptr = ipcom_strchr(ifr->ifr_name, ':')) != IP_NULL) + { + *cptr = '\0'; + } + + /* Only for v6 addresses */ + if (ipcom_strcmp(ifr->ifr_name, ifname) == 0 && + ifr->ip_ifr_addr.sa_family == IP_AF_INET6) + { + struct Ip_sockaddr_in6 *in6 = (struct Ip_sockaddr_in6 *)&ifr->ip_ifr_addr; + + if (!IP_IN6_IS_ADDR_UNSPECIFIED(&in6->sin6_addr)) + { + ret = 0; + break; + } + } + } + +leave: + if (buf != IP_NULL) + { + ipcom_free(buf); + } + break; + } +#endif /* IPCOM_USE_INET6 */ + } + + return ret; +} + + +/* + *=========================================================================== + * ipcom_waitif + *=========================================================================== + * Description: Wait for interface to get an IP address assigned. + * Parameters: ifindex - Index of the interface to wait for. + * 0 = any interface except loopback. + * domain - The address domain. + * Returns: 0 = success, -1 = error, and sets errno. + * + */ +IP_PUBLIC int +ipcom_waitif(int ifindex, int domain) +{ + struct Ipnet_rs_msghdr rtmsg; + struct Ip_timeval stop; + struct Ip_timeval tv; + Ip_fd fd = IP_INVALID_SOCKET; + int ret = -1; + + /* Check domain */ + if (domain != IP_AF_INET +#ifdef IPCOM_USE_INET6 + && domain != IP_AF_INET6 +#endif /* IPCOM_USE_INET6 */ + ) + { + IPCOM_LOG1(ERR, "ipcom_waitif :: invalid domain: %d", domain); + ipcom_errno_set(IP_ERRNO_EINVAL); + goto leave; + } + + /* Get routing socket */ + fd = ipcom_socket(IP_AF_ROUTE, IP_SOCK_RAW, 0); + if (fd == IP_INVALID_SOCKET) + { + IPCOM_LOG1(ERR, "ipcom_waitif :: ipcom_socket(ROUTE, RAW) failed, errno = %d", ipcom_errno); + goto leave; + } + + /* Get stop time */ + ipcom_microtime(&tv); + stop.tv_sec = tv.tv_sec + IPNET_WAITIF_TIMEOUT; + + /* Loop and wait for address */ + for (;;) + { + Ip_ssize_t length; + + /* Check if address available */ + if (ifindex == 0) + { + int i; + + /* Any if will do */ + for (i = 2; i < IPNET_WAITIF_MAXIF; i++) + { + if (ipcom_waitif_gifaddr(fd, i, domain) == 0) + { + ret = 0; + goto leave; + } + } + } + else if (ipcom_waitif_gifaddr(fd, ifindex, domain) == 0) + { + ret = 0; + goto leave; + } + +again: + /* Get timeout time */ + ipcom_microtime(&tv); + tv.tv_sec = stop.tv_sec - tv.tv_sec; + tv.tv_usec = 0; + if (tv.tv_sec <= 0) + { + ipcom_errno_set(IP_ERRNO_ETIMEDOUT); + goto leave; + } + + /* Set receive timeout */ + if (ipcom_setsockopt(fd, IP_SOL_SOCKET, IP_SO_RCVTIMEO, &tv, sizeof(tv)) < 0) + { + IPCOM_LOG1(ERR, "ipcom_waitif :: ipcom_setsockopt(RCVTIMEO) failed, errno = %d", ipcom_errno); + goto leave; + } + + /* Read routing message headers only (truncated read). */ + length = ipcom_recv(fd, &rtmsg, sizeof(rtmsg), 0); + if (length == IP_SOCKERR) + { + if (ipcom_errno != IP_ERRNO_ETIMEDOUT && ipcom_errno != IP_ERRNO_EWOULDBLOCK) + { + IPCOM_LOG1(ERR, "ipcom_waitif :: ipcom_recv() failed, errno = %d", ipcom_errno); + } + + goto leave; + } + + /* Only bother about newaddr */ + if (rtmsg.type != IPNET_RTM_NEWADDR) + { + goto again; + } + } + +leave: + if (fd != IP_INVALID_SOCKET) + { + ipcom_socketclose(fd); + } + + return ret; +} + +#else +int ipcom_waitif_empty_file; +#endif /* IPCOM_USE_WAITIF */ + + +/* + **************************************************************************** + * END OF FILE + **************************************************************************** + */ diff --git a/pool/shard000/C/0011027_thermoms.c b/pool/shard000/C/0011027_thermoms.c new file mode 100644 index 0000000000000000000000000000000000000000..bd2f10348caec87b7869aeeb4169969b0e15019c --- /dev/null +++ b/pool/shard000/C/0011027_thermoms.c @@ -0,0 +1,248 @@ +//--------------------------------------------------------------------------- +// Copyright (C) 2000 Dallas Semiconductor Corporation, All Rights Reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the "Software"), +// to deal in the Software without restriction, including without limitation +// the rights to use, copy, modify, merge, publish, distribute, sublicense, +// and/or sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +// IN NO EVENT SHALL DALLAS SEMICONDUCTOR BE LIABLE FOR ANY CLAIM, DAMAGES +// OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +// +// Except as contained in this notice, the name of Dallas Semiconductor +// shall not be used except as stated in the Dallas Semiconductor +// Branding Policy. +//--------------------------------------------------------------------------- +// +// thermoms.c - This utility mission a DS1921 +// Thermochron iButton. +// +// Version: 2.00 +// +// History: +// 1.03 -> 2.00 Reorganization of Public Domain Kit. Provide +// defaults on mission selection. +// + +#define THERMOCHRON + +#include +#include +#include "ownet.h" +#include "thermo21.h" +#include "findtype.h" + +// defines +#define MAXDEVICES 20 + +// local function prototypes +int InputMissionType(ThermoStateType *,int); + +//---------------------------------------------------------------------- +// This is the Main routine for thermoms. +// +int main(int argc, char **argv) +{ + int Fahrenheit=FALSE,num,i,j; + char str[800]; + ThermoStateType ThermoState; + uchar ThermoSN[MAXDEVICES][8]; //the serial numbers for the devices + int portnum=0; + + // check arguments to see if request instruction with '?' or too many + if ((argc < 2) || (argc > 3) || ((argc > 1) && (argv[1][0] == '?' || argv[1][1] == '?'))) + ExitProg("\nusage: thermoms 1wire_net_name \n" + " - Thermochron configuration on the 1-Wire Net port\n" + " - 1wire_net_port required port name\n" + " example: \"COM1\" (Win32 DS2480),\"/dev/cua0\" \n" + " (Linux DS2480),\"{1,5}\" (Win32 TMEX)\n" + " - optional Fahrenheit mode (default Celsius)\n" + " - version 2.00\n",1); + + // attempt to acquire the 1-Wire Net + if((portnum = owAcquireEx(argv[1])) < 0) + { + OWERROR_DUMP(stdout); + exit(1); + } + + // success + printf("Port opened: %s\n",argv[1]); + + //---------------------------------------- + // Introduction + printf("\n/---------------------------------------------\n"); + printf(" Find and mission DS1921 Thermochron iButton(s)\n" + " Version 2.00\n\n"); + + // check arguments + Fahrenheit = FALSE; + if (argc >= 3) + { + if ((argv[2][0] == '/') && + ((argv[2][1] == 'F') || (argv[2][1] == 'f'))) + Fahrenheit = TRUE; + } + + // get list of Thermochron's + num = FindDevices(portnum, &ThermoSN[0],THERMO_FAM, MAXDEVICES); + + // check if not present or more then 1 present + if (num == 0) + ExitProg("Thermochron not present on 1-Wire\n",1); + + // loop to mission each Thermochron + for (i = 0; i < num; i++) + { + // set the serial number portion in the thermo state + printf("\nRead status of Thermochron: "); + for (j = 7; j >= 0; j--) + { + ThermoState.MissStat.serial_num[j] = ThermoSN[i][j]; + printf("%02X",ThermoSN[i][j]); + } + printf("\n"); + + // read Thermochron state + if (ReadThermoStatus(portnum,&ThermoSN[i][0],&ThermoState,stdout)) + { + // display mission status + InterpretStatus(&ThermoState.MissStat); + MissionStatusToString(&ThermoState.MissStat, Fahrenheit, &str[0]); + printf("\n%s\n",str); + + // ask user mission questions + if (!InputMissionType(&ThermoState,Fahrenheit)) + { + printf("Input abort\n"); + continue; + } + + // run the script to display the thermochron + if (MissionThermo(portnum,&ThermoSN[i][0],&ThermoState,stdout)) + { + // read Thermochron state + if (ReadThermoStatus(portnum,&ThermoSN[i][0],&ThermoState,stdout)) + { + // display the new mission status + InterpretStatus(&ThermoState.MissStat); + MissionStatusToString(&ThermoState.MissStat, Fahrenheit, &str[0]); + printf("\n%s\n",str); + } + else + printf("ERROR reading Thermochon state\n"); + } + else + printf("ERROR, Thermochon missioning not complete\n"); + } + else + printf("ERROR reading Thermochon state\n"); + } + + // release the 1-Wire Net + owRelease(portnum); + printf("\nClosing port %s.\n", argv[1]); + printf("End program normally\n"); + exit(0); + + return 0; +} + +//-------------------------------------------------------------------------- +// Prints a message, and the current driver versions. +// +int InputMissionType(ThermoStateType *ThermoState, int ConvertToF) +{ + long num; + float temp; + + // prompt to erase current mission + num = 1; + if (!EnterNum("Erase current mission\n (0) yes\n (1) no\nAnswer:",1, &num, 0, 1)) + return FALSE; + + // check for no erase + if (num == 1) + return FALSE; + + // prompt for start delay + num = 0; + if (!EnterNum("\nEnter start delay in minutes\n" + "Answer (0 to 65535):",5, &num, 0, 65535)) + return FALSE; + + // set in mission status structure + ThermoState->MissStat.start_delay = (ushort)num; + + // prompt for sample rate + num = 5; + if (!EnterNum("\nEnter sample rate in minutes\n" + "Answer (1 to 255):",3, &num, 1, 255)) + return FALSE; + + // set in mission status structure + ThermoState->MissStat.sample_rate = (uchar)num; + + // prompt to erase current mission + num = 0; + if (!EnterNum("Enable roll-over\n (0) yes\n (1) no\nAnswer:",1, &num, 0, 1)) + return FALSE; + + // rollover enabled? + ThermoState->MissStat.rollover_enable = (num == 0); + + // prompt for high trip + if (ConvertToF) + { + num = 80; + if (!EnterNum("\nEnter high temperature threshold in Fahrenheit\n" + "Answer (-40 to 158):",3, &num, -40, 158)) + return FALSE; + temp = (float)((num - 32.0) * 5.0 / 9.0); + } + else + { + num = 35; + if (!EnterNum("\nEnter high temperature threshold in Celsius\n" + "Answer (-40 to 70):",3, &num, -40, 70)) + return FALSE; + temp = (float)num; + } + + // set in mission status structure + ThermoState->MissStat.high_threshold = (uchar)(2 * (temp + 40)); + + // prompt for low trip + if (ConvertToF) + { + num = 32; + if (!EnterNum("\nEnter low temperature threshold in Fahrenheit\n" + "Answer (-40 to 158):",3, &num, -40, 158)) + return FALSE; + temp = (float)((num - 32.0) * 5.0 / 9.0); + } + else + { + num = 0; + if (!EnterNum("\nEnter low temperature threshold in Celsius\n" + "Answer (-40 to 70):",3, &num, -40, 70)) + return FALSE; + temp = (float)num; + } + + // set in mission status structure + ThermoState->MissStat.low_threshold = (uchar)(2 * (temp + 40)); + + return TRUE; +} + diff --git a/pool/shard000/C/0011031_check-ref-format.c b/pool/shard000/C/0011031_check-ref-format.c new file mode 100644 index 0000000000000000000000000000000000000000..6c40ff110bee7387d4eb4e9c7c04a21e8b12ca44 --- /dev/null +++ b/pool/shard000/C/0011031_check-ref-format.c @@ -0,0 +1,89 @@ +/* + * GIT - The information manager from hell + */ + +#include "cache.h" +#include "refs.h" +#include "builtin.h" +#include "strbuf.h" + +static const char builtin_check_ref_format_usage[] = +"git check-ref-format [--normalize] [] \n" +" or: git check-ref-format --branch "; + +/* + * Return a copy of refname but with leading slashes removed and runs + * of adjacent slashes replaced with single slashes. + * + * This function is similar to normalize_path_copy(), but stripped down + * to meet check_ref_format's simpler needs. + */ +static char *collapse_slashes(const char *refname) +{ + char *ret = xmallocz(strlen(refname)); + char ch; + char prev = '/'; + char *cp = ret; + + while ((ch = *refname++) != '\0') { + if (prev == '/' && ch == prev) + continue; + + *cp++ = ch; + prev = ch; + } + *cp = '\0'; + return ret; +} + +static int check_ref_format_branch(const char *arg) +{ + struct strbuf sb = STRBUF_INIT; + int nongit; + + setup_git_directory_gently(&nongit); + if (strbuf_check_branch_ref(&sb, arg)) + die("'%s' is not a valid branch name", arg); + printf("%s\n", sb.buf + 11); + strbuf_release(&sb); + return 0; +} + +int cmd_check_ref_format(int argc, const char **argv, const char *prefix) +{ + int i; + int normalize = 0; + int flags = 0; + const char *refname; + + if (argc == 2 && !strcmp(argv[1], "-h")) + usage(builtin_check_ref_format_usage); + + if (argc == 3 && !strcmp(argv[1], "--branch")) + return check_ref_format_branch(argv[2]); + + for (i = 1; i < argc && argv[i][0] == '-'; i++) { + if (!strcmp(argv[i], "--normalize") || !strcmp(argv[i], "--print")) + normalize = 1; + else if (!strcmp(argv[i], "--allow-onelevel")) + flags |= REFNAME_ALLOW_ONELEVEL; + else if (!strcmp(argv[i], "--no-allow-onelevel")) + flags &= ~REFNAME_ALLOW_ONELEVEL; + else if (!strcmp(argv[i], "--refspec-pattern")) + flags |= REFNAME_REFSPEC_PATTERN; + else + usage(builtin_check_ref_format_usage); + } + if (! (i == argc - 1)) + usage(builtin_check_ref_format_usage); + + refname = argv[i]; + if (normalize) + refname = collapse_slashes(refname); + if (check_refname_format(refname, flags)) + return 1; + if (normalize) + printf("%s\n", refname); + + return 0; +} diff --git a/pool/shard000/C/0011036_xlit.c b/pool/shard000/C/0011036_xlit.c new file mode 100644 index 0000000000000000000000000000000000000000..adbd90d370d9b8ac57b93ddbf5e025b1d616c326 --- /dev/null +++ b/pool/shard000/C/0011036_xlit.c @@ -0,0 +1,283 @@ +/* + * $Id: xlit.c,v 1.11 2005/08/08 02:30:59 prussar Exp $ + * + * Viewer - a part of Plucker, the free off-line HTML viewer for PalmOS + * Copyright (c) 1998-2002, Mark Ian Lillywhite and Michael Nordstrom + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + */ + +#include "util.h" +#include "list.h" +#include "const.h" +#include "resourceids.h" +#include "ramfile.h" + +#include "xlit.h" + + + + +/*********************************************************************** + * + * Internal Types + * + ***********************************************************************/ +typedef struct { + DmOpenRef dbRef; + MemHandle handle; + TransliterationHeader* header; +} XlitEntry; + + + + +/*********************************************************************** + * + * Local functions + * + ***********************************************************************/ + +static void ProcessXlitDB ( UInt16 cardNo, LocalID dbID ) XLIT_SECTION; +static Int16 XlitCompare ( void* a, void* b, Int32 other ) XLIT_SECTION; + + + + +/*********************************************************************** + * + * Private variables + * + ***********************************************************************/ +static LinkedList xlitDataList = NULL; +static UInt16 numXlits = 0; +static Boolean alreadyOpened = false; + +static XlitEntry* xlitData; +static Char** xlitNames; + + +static void ProcessXlitDB + ( + UInt16 cardNo, + LocalID dbID + ) +{ + UInt16 numRecords; + UInt16 i; + DmOpenRef dbRef; + + dbRef = DmOpenDatabase( cardNo, dbID, dmModeReadOnly ); + + if ( dbRef == NULL ) + return; + + numRecords = DmNumRecords( dbRef ); + + for ( i = 0 ; i < numRecords ; i++ ) { + MemHandle handle; + + handle = OpenRecord( dbRef, i ); + + if ( handle != NULL ) { + XlitEntry* entry; + + entry = SafeMemPtrNew( sizeof( XlitEntry ) ); + + entry->dbRef = dbRef; + entry->handle = handle; + entry->header = MemHandleLock( handle ); + + ListAppend( xlitDataList, entry ); + numXlits++; + } + } +} + + + +static Int16 XlitCompare + ( + void* a, + void* b, + Int32 other + ) +{ + return StrCompare( ( ( XlitEntry* )a )->header->name, + ( ( XlitEntry* )b )->header->name ); +} + + + +/* Set up xlatTable in accordance with transliteration number + xlitNum. Return value: Is the transliteration symmetric. + *multibyteCharFixP is set to true iff the transliteration + specifies a value to transliterate multibyte chars to, and + if so then *multibyteCharFixTo is set to that value. */ +Boolean SetTransliteration + ( + UInt16 xlitNum, + Char* xlatTable, + Boolean* multibyteCharFixP, + WChar* multibyteCharFixTo + ) +{ + TransliterationHeader* header; + UInt16 i; + if ( xlitNum == 0 || numXlits + 1 <= xlitNum ) { + for ( i = 0 ; i < 256 ; i++ ) { + xlatTable[ i ] = i; + } + *multibyteCharFixP = false; + return true; + } + header = xlitData[ xlitNum - 1 ].header; + for ( i = 0 ; i < 256 ; i++ ) { + if ( header->firstGlyph <= i && i <= header->lastGlyph ) { + xlatTable[ i ] = ( ( ( UInt8* )header ) + header->dataOffset ) + [ i - header->firstGlyph ]; + } + else { + if ( header->flags & + TRANSLITERATION_FLAG_OUT_OF_RANGE_NO_CHANGE ) { + xlatTable[ i ] = i; + } + else { + xlatTable[ i ] = header->outOfRangeMapTo; + } + } + } + if ( header->flags & TRANSLITERATION_FLAG_OUT_OF_RANGE_NO_CHANGE ) { + *multibyteCharFixP = true; + *multibyteCharFixTo = header->outOfRangeMapTo; + } + if ( header->flags & TRANSLITERATION_FLAG_SYMMETRIC ) { + return true; + } + else { + return false; + } +} + + + +/* Setup transliteration popup on search form */ +void SetupXlitPopup( void ) +{ + ListType* list; + + list = GetObjectPtr( frmSearchXlitList ); + + LstSetListChoices( list, xlitNames, numXlits + 1 ); + LstSetHeight( list, numXlits + 1 ); +} + + + +void OpenTransliterations( void ) +{ + DmSearchStateType stateInfo; + Err err; + UInt16 i; + UInt16 cardNo; + LocalID dbID; + Char temp[ 100 ]; + + XlitEntry* entry; + + if ( alreadyOpened ) + return; + + alreadyOpened = true; + + numXlits = 0; + + xlitDataList = ListCreate(); + + err = DmGetNextDatabaseByTypeCreator( true, &stateInfo, + (UInt32) XlitDBType, (UInt32) ViewerAppID, + false, &cardNo, &dbID ); + + while ( err == errNone ) { + ProcessXlitDB( cardNo, dbID ); + + err = DmGetNextDatabaseByTypeCreator( false, &stateInfo, + (UInt32) SkinResourceType, (UInt32) ViewerAppID, false, + &cardNo, &dbID ); + } + + if ( 0 < numXlits ) { + xlitData = SafeMemPtrNew( sizeof( XlitEntry ) * numXlits ); + i = 0; + + entry = ListFirst( xlitDataList ); + while ( entry != NULL ) { + xlitData[ i++ ] = *entry; + + SafeMemPtrFree( entry ); + entry = ListNext( xlitDataList, entry ); + } + SysInsertionSort( xlitData, numXlits, sizeof( XlitEntry ), + XlitCompare, 0 ); + } + ListDelete( xlitDataList ); + + xlitNames = SafeMemPtrNew( ( numXlits + 1 ) * sizeof( Char* ) ); + + SysCopyStringResource( temp, strNoTransliteration ); + xlitNames[ 0 ] = SafeMemPtrNew( 1 + StrLen( temp ) ); + StrCopy( xlitNames[ 0 ], temp ); + + for ( i = 1 ; i < numXlits + 1 ; i++ ) { + Char* name; + name = xlitData[ i - 1 ].header->name; + xlitNames[ i ] = SafeMemPtrNew( 1 + StrLen( name ) ); + StrCopy( xlitNames[ i ], name ); + } +} + + + +void CloseTransliterations( void ) +{ + UInt16 i; + + if ( 0 < numXlits ) { + for ( i = 0 ; i < numXlits ; i++ ) { + MemHandleUnlock( xlitData[ i ].handle ); + CloseRecord( xlitData[ i ].handle, false ); + } + for ( i = 0 ; i < numXlits ; i++ ) { + DmOpenRef dbRef; + dbRef = xlitData[ i ].dbRef; + if ( dbRef != NULL ) { + UInt16 j; + CloseDatabase( dbRef ); + for ( j = i + 1 ; j < numXlits ; j++ ) { + if ( xlitData[ j ].dbRef == dbRef ) + xlitData[ j ].dbRef = NULL; + } + } + } + SafeMemPtrFree( xlitData ); + } + + for ( i = 0 ; i < numXlits + 1 ; i++ ) { + SafeMemPtrFree( xlitNames[ i ] ); + } + SafeMemPtrFree( xlitNames ); + numXlits = 0; +} diff --git a/pool/shard000/C/0011042_bin_ningba.c b/pool/shard000/C/0011042_bin_ningba.c new file mode 100644 index 0000000000000000000000000000000000000000..fbb172a4b3852f410e9ebab8269e4c681c420c48 --- /dev/null +++ b/pool/shard000/C/0011042_bin_ningba.c @@ -0,0 +1,127 @@ +/* radare - LGPL - 2014-2015 - condret@runas-racer.com */ + +#include +#include +#include +#include +#include +#include "../format/nin/gba.h" + +static bool check_bytes(const ut8 *buf, ut64 length) { + ut8 lict[156]; + if (!buf || length < 160) { + return 0; + } + memcpy (lict, buf + 0x4, 156); + return (!memcmp (lict, lic_gba, 156))? 1: 0; +} + +static bool check(RBinFile *arch) { + const ut8 *bytes = arch? r_buf_buffer (arch->buf): NULL; + ut64 sz = arch? r_buf_size (arch->buf): 0; + return check_bytes (bytes, sz); + +} + +static bool load(RBinFile *arch) { + const ut8 *bytes = arch? r_buf_buffer (arch->buf): NULL; + ut64 sz = arch? r_buf_size (arch->buf): 0; + if (!arch || !arch->o) { + return false; + } + arch->rbin->maxstrbuf = 0x20000000; + return check_bytes (bytes, sz); +} + +static int destroy(RBinFile *arch) { + r_buf_free (arch->buf); + arch->buf = NULL; + return true; +} + +static RList *entries(RBinFile *arch) { + RList *ret = r_list_new (); + RBinAddr *ptr = NULL; + + if (arch && arch->buf) { + if (!ret) { + return NULL; + } + ret->free = free; + if (!(ptr = R_NEW0 (RBinAddr))) { + return ret; + } + ptr->paddr = ptr->vaddr = 0x8000000; + r_list_append (ret, ptr); + } + return ret; +} + +static RBinInfo *info(RBinFile *arch) { + ut8 rom_info[16]; + RBinInfo *ret = R_NEW0 (RBinInfo); + + if (!ret) { + return NULL; + } + + if (!arch || !arch->buf) { + free (ret); + return NULL; + } + + ret->lang = NULL; + r_buf_read_at (arch->buf, 0xa0, rom_info, 16); + ret->file = r_str_ndup ((const char *) rom_info, 12); + ret->type = r_str_ndup ((char *) &rom_info[12], 4); + ret->machine = strdup ("GameBoy Advance"); + ret->os = strdup ("any"); + ret->arch = strdup ("arm"); + ret->has_va = 1; + ret->bits = 32; + ret->big_endian = 0; + ret->dbg_info = 0; + return ret; +} + +static RList *sections(RBinFile *arch) { + RList *ret = NULL; + RBinSection *s = R_NEW0 (RBinSection); + ut64 sz = r_buf_size (arch->buf); + + if (!(ret = r_list_new ())) { + free (s); + return NULL; + } + strcpy (s->name, "ROM"); + s->paddr = 0; + s->vaddr = 0x8000000; + s->size = sz; + s->vsize = 0x2000000; + s->srwx = R_BIN_SCN_READABLE | R_BIN_SCN_EXECUTABLE | R_BIN_SCN_MAP; + s->add = true; + + r_list_append (ret, s); + return ret; +} + +RBinPlugin r_bin_plugin_ningba = { + .name = "ningba", + .desc = "Game Boy Advance format r_bin plugin", + .license = "LGPL3", + .load = &load, + .destroy = &destroy, + .check = &check, + .check_bytes = &check_bytes, + .entries = &entries, + .info = &info, + .sections = §ions, +}; + +#ifndef CORELIB +RLibStruct radare_plugin = { + .type = R_LIB_TYPE_BIN, + .data = &r_bin_plugin_ningba, + .version = R2_VERSION +}; +#endif diff --git a/pool/shard000/C/0011045_trickle_endpoint.c b/pool/shard000/C/0011045_trickle_endpoint.c new file mode 100644 index 0000000000000000000000000000000000000000..7ab0488a6608abdcfe910eff6d2a7796ada882ad --- /dev/null +++ b/pool/shard000/C/0011045_trickle_endpoint.c @@ -0,0 +1,196 @@ +/* + * + * Copyright 2016, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include "test/core/util/passthru_endpoint.h" + +#include +#include + +#include +#include +#include +#include + +#include "src/core/lib/iomgr/sockaddr.h" + +#include "src/core/lib/slice/slice_internal.h" + +typedef struct { + grpc_endpoint base; + double bytes_per_second; + grpc_endpoint *wrapped; + gpr_timespec last_write; + + gpr_mu mu; + grpc_slice_buffer write_buffer; + grpc_slice_buffer writing_buffer; + grpc_error *error; + bool writing; +} trickle_endpoint; + +static void te_read(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, + grpc_slice_buffer *slices, grpc_closure *cb) { + trickle_endpoint *te = (trickle_endpoint *)ep; + grpc_endpoint_read(exec_ctx, te->wrapped, slices, cb); +} + +static void te_write(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, + grpc_slice_buffer *slices, grpc_closure *cb) { + trickle_endpoint *te = (trickle_endpoint *)ep; + for (size_t i = 0; i < slices->count; i++) { + grpc_slice_ref_internal(slices->slices[i]); + } + gpr_mu_lock(&te->mu); + if (te->write_buffer.length == 0) { + te->last_write = gpr_now(GPR_CLOCK_MONOTONIC); + } + grpc_slice_buffer_addn(&te->write_buffer, slices->slices, slices->count); + grpc_closure_sched(exec_ctx, cb, GRPC_ERROR_REF(te->error)); + gpr_mu_unlock(&te->mu); +} + +static grpc_workqueue *te_get_workqueue(grpc_endpoint *ep) { + trickle_endpoint *te = (trickle_endpoint *)ep; + return grpc_endpoint_get_workqueue(te->wrapped); +} + +static void te_add_to_pollset(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, + grpc_pollset *pollset) { + trickle_endpoint *te = (trickle_endpoint *)ep; + grpc_endpoint_add_to_pollset(exec_ctx, te->wrapped, pollset); +} + +static void te_add_to_pollset_set(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, + grpc_pollset_set *pollset_set) { + trickle_endpoint *te = (trickle_endpoint *)ep; + grpc_endpoint_add_to_pollset_set(exec_ctx, te->wrapped, pollset_set); +} + +static void te_shutdown(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, + grpc_error *why) { + trickle_endpoint *te = (trickle_endpoint *)ep; + gpr_mu_lock(&te->mu); + if (te->error == GRPC_ERROR_NONE) { + te->error = GRPC_ERROR_REF(why); + } + gpr_mu_unlock(&te->mu); + grpc_endpoint_shutdown(exec_ctx, te->wrapped, why); +} + +static void te_destroy(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep) { + trickle_endpoint *te = (trickle_endpoint *)ep; + grpc_endpoint_destroy(exec_ctx, te->wrapped); + gpr_mu_destroy(&te->mu); + grpc_slice_buffer_destroy_internal(exec_ctx, &te->write_buffer); + grpc_slice_buffer_destroy_internal(exec_ctx, &te->writing_buffer); + GRPC_ERROR_UNREF(te->error); + gpr_free(te); +} + +static grpc_resource_user *te_get_resource_user(grpc_endpoint *ep) { + trickle_endpoint *te = (trickle_endpoint *)ep; + return grpc_endpoint_get_resource_user(te->wrapped); +} + +static char *te_get_peer(grpc_endpoint *ep) { + trickle_endpoint *te = (trickle_endpoint *)ep; + return grpc_endpoint_get_peer(te->wrapped); +} + +static int te_get_fd(grpc_endpoint *ep) { + trickle_endpoint *te = (trickle_endpoint *)ep; + return grpc_endpoint_get_fd(te->wrapped); +} + +static void te_finish_write(grpc_exec_ctx *exec_ctx, void *arg, + grpc_error *error) { + trickle_endpoint *te = arg; + gpr_mu_lock(&te->mu); + te->writing = false; + grpc_slice_buffer_reset_and_unref(&te->writing_buffer); + gpr_mu_unlock(&te->mu); +} + +static const grpc_endpoint_vtable vtable = {te_read, + te_write, + te_get_workqueue, + te_add_to_pollset, + te_add_to_pollset_set, + te_shutdown, + te_destroy, + te_get_resource_user, + te_get_peer, + te_get_fd}; + +grpc_endpoint *grpc_trickle_endpoint_create(grpc_endpoint *wrap, + double bytes_per_second) { + trickle_endpoint *te = gpr_malloc(sizeof(*te)); + te->base.vtable = &vtable; + te->wrapped = wrap; + te->bytes_per_second = bytes_per_second; + gpr_mu_init(&te->mu); + grpc_slice_buffer_init(&te->write_buffer); + grpc_slice_buffer_init(&te->writing_buffer); + te->error = GRPC_ERROR_NONE; + te->writing = false; + return &te->base; +} + +static double ts2dbl(gpr_timespec s) { + return (double)s.tv_sec + 1e-9 * (double)s.tv_nsec; +} + +size_t grpc_trickle_endpoint_trickle(grpc_exec_ctx *exec_ctx, + grpc_endpoint *ep) { + trickle_endpoint *te = (trickle_endpoint *)ep; + gpr_mu_lock(&te->mu); + if (!te->writing && te->write_buffer.length > 0) { + gpr_timespec now = gpr_now(GPR_CLOCK_MONOTONIC); + double elapsed = ts2dbl(gpr_time_sub(now, te->last_write)); + size_t bytes = (size_t)(te->bytes_per_second * elapsed); + // gpr_log(GPR_DEBUG, "%lf elapsed --> %" PRIdPTR " bytes", elapsed, bytes); + if (bytes > 0) { + grpc_slice_buffer_move_first(&te->write_buffer, + GPR_MIN(bytes, te->write_buffer.length), + &te->writing_buffer); + te->writing = true; + te->last_write = now; + grpc_endpoint_write( + exec_ctx, te->wrapped, &te->writing_buffer, + grpc_closure_create(te_finish_write, te, grpc_schedule_on_exec_ctx)); + } + } + size_t backlog = te->write_buffer.length; + gpr_mu_unlock(&te->mu); + return backlog; +} diff --git a/pool/shard000/C/0011048_perlin.c b/pool/shard000/C/0011048_perlin.c new file mode 100644 index 0000000000000000000000000000000000000000..d8f780a102090640198994d13d7075ce97b0eab7 --- /dev/null +++ b/pool/shard000/C/0011048_perlin.c @@ -0,0 +1,377 @@ +/* Perlin noise generator. + * + * 24/7/16 + */ + +/* + + This file is part of VIPS. + + VIPS is free software; you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This 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 Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA + + */ + +/* + + These files are distributed with VIPS - http://www.vips.ecs.soton.ac.uk + + */ + +/* +#define VIPS_DEBUG + */ + +#ifdef HAVE_CONFIG_H +#include +#endif /*HAVE_CONFIG_H*/ +#include + +#include +#include +#include +#include + +#include + +#include "pcreate.h" + +typedef struct _VipsPerlin { + VipsCreate parent_instance; + + int width; + int height; + int cell_size; + gboolean uchar; + + int cells_across; + int cells_down; + + /* Use this to seed this call of our rng. + */ + guint32 seed; +} VipsPerlin; + +typedef struct _VipsPerlinClass { + VipsCreateClass parent_class; + +} VipsPerlinClass; + +G_DEFINE_TYPE( VipsPerlin, vips_perlin, VIPS_TYPE_CREATE ); + +/* cos and sin from an angle in 0 - 255. + */ +float vips_perlin_cos[256]; +float vips_perlin_sin[256]; + +typedef struct _Sequence { + VipsPerlin *perlin; + + /* The position of the last cell we were in. Use this to avoid + * regenerating vectors on every pixel lookup. + */ + int cell_x; + int cell_y; + + /* The 2 x 2 grid of unit vectors, with cell_x/cell_y as the top left. + */ + float gx[4]; + float gy[4]; + +} Sequence; + +/* Generate a 3 x 3 grid of cells around a point. + */ +static void +vips_perlin_create_cells( VipsPerlin *perlin, + float gx[4], float gy[4], int cell_x, int cell_y ) +{ + int x, y; + + for( y = 0; y < 2; y++ ) + for( x = 0; x < 2; x++ ) { + int ci = x + y * 2; + + guint32 seed; + int cx; + int cy; + int angle; + + seed = perlin->seed; + + cx = cell_x + x; + cy = cell_y + y; + + /* When we calculate the seed for this cell, we wrap + * around so that our output will tesselate. + */ + + if( cy >= perlin->cells_down ) + cy = 0; + seed = vips__random_add( seed, cy ); + + if( cx >= perlin->cells_across ) + cx = 0; + seed = vips__random_add( seed, cx ); + + angle = (seed ^ (seed >> 8) ^ (seed >> 16)) & 0xff; + + gx[ci] = vips_perlin_cos[angle]; + gy[ci] = vips_perlin_sin[angle]; + } +} + +static int +vips_perlin_stop( void *vseq, void *a, void *b ) +{ + Sequence *seq = (Sequence *) vseq; + + VIPS_FREE( seq ); + + return( 0 ); +} + +static void * +vips_perlin_start( VipsImage *out, void *a, void *b ) +{ + VipsPerlin *perlin = (VipsPerlin *) b; + + Sequence *seq; + + if( !(seq = VIPS_NEW( NULL, Sequence )) ) + return( NULL ); + + seq->perlin = perlin; + seq->cell_x = -1; + seq->cell_y = -1; + + return( seq ); +} + +/* Smooth linear interpolation, 0 <= x <= 1. + * + * https://en.wikipedia.org/wiki/Smoothstep + */ +static float +smootherstep( float x ) +{ + return( x * x * x * (x * (x * 6 - 15) + 10) ); +} + +static int +vips_perlin_gen( VipsRegion *or, void *vseq, void *a, void *b, + gboolean *stop ) +{ + VipsPerlin *perlin = (VipsPerlin *) a; + VipsRect *r = &or->valid; + Sequence *seq = (Sequence *) vseq; + + int x, y; + + for( y = 0; y < r->height; y++ ) { + float *fq = (float *) + VIPS_REGION_ADDR( or, r->left, r->top + y ); + VipsPel *q = (VipsPel *) fq; + + for( x = 0; x < r->width; x++ ) { + int cs = perlin->cell_size; + int cell_x = (r->left + x) / cs; + int cell_y = (r->top + y) / cs; + float dx = (x + r->left - cell_x * cs) / (float) cs; + float dy = (y + r->top - cell_y * cs) / (float) cs; + float sx = smootherstep( dx ); + float sy = smootherstep( dy ); + + float n0, n1; + float ix0, ix1; + float p; + + if( cell_x != seq->cell_x || + cell_y != seq->cell_y ) { + vips_perlin_create_cells( perlin, + seq->gx, seq->gy, cell_x, cell_y ); + seq->cell_x = cell_x; + seq->cell_y = cell_y; + } + + n0 = -dx * seq->gx[0] + -dy * seq->gy[0]; + n1 = (1 - dx) * seq->gx[1] + -dy * seq->gy[1]; + ix0 = n0 + sx * (n1 - n0); + + n0 = -dx * seq->gx[2] + (1 - dy) * seq->gy[2]; + n1 = (1 - dx) * seq->gx[3] + (1 - dy) * seq->gy[3]; + ix1 = n0 + sx * (n1 - n0); + + p = ix0 + sy * (ix1 - ix0); + + if( perlin->uchar ) + q[x] = 128 * p + 128; + else + fq[x] = p; + } + } + + return( 0 ); +} + +static int +vips_perlin_build( VipsObject *object ) +{ + VipsCreate *create = VIPS_CREATE( object ); + VipsPerlin *perlin = (VipsPerlin *) object; + + if( VIPS_OBJECT_CLASS( vips_perlin_parent_class )->build( object ) ) + return( -1 ); + + /* Be careful if width is a multiple of cell_size. + */ + perlin->cells_across = + VIPS_ROUND_UP( perlin->width, perlin->cell_size ) / + perlin->cell_size; + perlin->cells_down = + VIPS_ROUND_UP( perlin->height, perlin->cell_size ) / + perlin->cell_size; + + vips_image_init_fields( create->out, + perlin->width, perlin->height, 1, + perlin->uchar ? VIPS_FORMAT_UCHAR : VIPS_FORMAT_FLOAT, + VIPS_CODING_NONE, VIPS_INTERPRETATION_MULTIBAND, + 1.0, 1.0 ); + if( vips_image_pipelinev( create->out, VIPS_DEMAND_STYLE_ANY, NULL ) || + vips_image_generate( create->out, + vips_perlin_start, vips_perlin_gen, vips_perlin_stop, + perlin, NULL ) ) + return( -1 ); + + return( 0 ); +} + +static void * +vips_perlin_make_tables( void *client ) +{ + int i; + + for( i = 0; i < 256; i++ ) { + double angle = 2 * VIPS_PI * i / 256.0; + + vips_perlin_cos[i] = cos( angle ); + vips_perlin_sin[i] = sin( angle ); + } + + return( NULL ); +} + +static void +vips_perlin_class_init( VipsPerlinClass *class ) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS( class ); + VipsObjectClass *vobject_class = VIPS_OBJECT_CLASS( class ); + + static GOnce once = G_ONCE_INIT; + + VIPS_ONCE( &once, vips_perlin_make_tables, NULL ); + + gobject_class->set_property = vips_object_set_property; + gobject_class->get_property = vips_object_get_property; + + vobject_class->nickname = "perlin"; + vobject_class->description = _( "make a perlin noise image" ); + vobject_class->build = vips_perlin_build; + + VIPS_ARG_INT( class, "width", 2, + _( "Width" ), + _( "Image width in pixels" ), + VIPS_ARGUMENT_REQUIRED_INPUT, + G_STRUCT_OFFSET( VipsPerlin, width ), + 1, VIPS_MAX_COORD, 1 ); + + VIPS_ARG_INT( class, "height", 3, + _( "Height" ), + _( "Image height in pixels" ), + VIPS_ARGUMENT_REQUIRED_INPUT, + G_STRUCT_OFFSET( VipsPerlin, height ), + 1, VIPS_MAX_COORD, 1 ); + + VIPS_ARG_INT( class, "cell_size", 3, + _( "Cell size" ), + _( "Size of Perlin cells" ), + VIPS_ARGUMENT_OPTIONAL_INPUT, + G_STRUCT_OFFSET( VipsPerlin, cell_size ), + 1, VIPS_MAX_COORD, 256 ); + + VIPS_ARG_BOOL( class, "uchar", 4, + _( "Uchar" ), + _( "Output an unsigned char image" ), + VIPS_ARGUMENT_OPTIONAL_INPUT, + G_STRUCT_OFFSET( VipsPerlin, uchar ), + FALSE ); + + VIPS_ARG_INT( class, "seed", 5, + _( "Seed" ), + _( "Random number seed" ), + VIPS_ARGUMENT_OPTIONAL_INPUT, + G_STRUCT_OFFSET( VipsPerlin, seed ), + INT_MIN, INT_MAX, 0 ); + +} + +static void +vips_perlin_init( VipsPerlin *perlin ) +{ + perlin->cell_size = 256; + perlin->seed = UINT_MAX * g_random_double(); +} + +/** + * vips_perlin: + * @out: (out): output image + * @width: horizontal size + * @height: vertical size + * @...: %NULL-terminated list of optional named arguments + * + * Optional arguments: + * + * * @cell_size: %gint, size of Perlin cells + * * @uchar: output a uchar image + * + * Create a one-band float image of Perlin noise. See: + * + * https://en.wikipedia.org/wiki/Perlin_noise + * + * Use @cell_size to set the size of the cells from which the image is + * constructed. The default is 256 x 256. + * + * If @width and @height are multiples of @cell_size, the image will tessellate. + * + * Normally, output pixels are #VIPS_FORMAT_FLOAT in the range [-1, +1]. Set + * @uchar to output a uchar image with pixels in [0, 255]. + * + * See also: vips_worley(), vips_fractsurf(), vips_gaussnoise(). + * + * Returns: 0 on success, -1 on error + */ +int +vips_perlin( VipsImage **out, int width, int height, ... ) +{ + va_list ap; + int result; + + va_start( ap, height ); + result = vips_call_split( "perlin", ap, out, width, height ); + va_end( ap ); + + return( result ); +} + diff --git a/pool/shard000/C/0011051_ripxbf.c b/pool/shard000/C/0011051_ripxbf.c new file mode 100644 index 0000000000000000000000000000000000000000..071c802492843949fc943ceb7b9f0eceeb73b8d7 --- /dev/null +++ b/pool/shard000/C/0011051_ripxbf.c @@ -0,0 +1,144 @@ + +#include +#include "ripxbf.h" + +UINT64 freadInt(FILE* file, UINT32 size) +{ + unsigned int i; + unsigned int ret = 0; + for (i = 0; i < size; i++) { + ret <<= 8; + ret |= fgetc(file); + } + return ret; +} + +UINT16 freadUINT16(FILE* file) +{ + return (UINT16)freadInt(file, 2); +} + +UINT32 freadUINT32(FILE* file) +{ + return (UINT32)freadInt(file, 4); +} + +UINT64 freadUINT64(FILE* file) +{ + return freadInt(file, 8); +} + +void freadString(FILE* file, CHAR* out, UINT32 maxLength) +{ + unsigned int i; + unsigned char next; + unsigned int completeLength = freadUINT32(file); + if (completeLength+1 < maxLength) + maxLength = completeLength+1; + + for (i = 0; i < completeLength; i++) { + next = (unsigned char)fgetc(file); + if (i < (maxLength-1)) + out[i] = next; + } + out[maxLength-1] = '\0'; +} + +void fwriteUINT16(FILE* file, UINT16 num) +{ + fputc((num>>8)&0xFF, file); + fputc(num&0xFF, file); +} + +void fwriteUINT32(FILE* file, UINT32 num) +{ + fputc((num>>24)&0xFF, file); + fputc((num>>16)&0xFF, file); + fputc((num>>8)&0xFF, file); + fputc(num&0xFF, file); +} + +void fwriteUINT64(FILE* file, UINT64 num) +{ + fputc((int)(num>>56)&0xFF, file); + fputc((int)(num>>48)&0xFF, file); + fputc((int)(num>>40)&0xFF, file); + fputc((int)(num>>32)&0xFF, file); + fputc((int)(num>>24)&0xFF, file); + fputc((int)(num>>16)&0xFF, file); + fputc((int)(num>>8)&0xFF, file); + fputc((int)num&0xFF, file); +} + +void fwriteString(FILE* file, const CHAR* s) +{ + int i; + int length = (int)strlen(s); + fwriteUINT32(file, length); + for (i = 0; i < length; i++) + fputc(s[i], file); +} + +/* +RipSystem SYSTEMS[] = +{ + { ID_SYSTEM_INTELLIVISION, + "Intellivision", + 2, 2, + { { "Master Component", + { { "Executive ROM", + { { "Original Executive ROM", 0xCBCE86F7 }, + { "Intellivision 2 Executive ROM", 0 }, + { "Sears Executive ROM", 0 }, + { "GPL Executive ROM", 0 }, + 0, + },}, + { "Graphics ROM", + { { "Original GROM", 0x683A4158 }, + { "GPL GROM", 0 }, + 0, + },}, + 0, + },}, + { "Entertainment Computer System", + { { "ECS BIOS", + { { "Original ECS BIOS", 0xEA790A06 }, + },}, + 0, + },}, + { "Intellivoice", + { { "Intellivoice BIOS", + { { "Original Intellivoice BIOS", 0x0DE7579D }, + 0, + },}, + 0, + },}, + 0, + },}, + { ID_SYSTEM_ATARI5200, + "Atari 5200", + 2, 1, + { { "Main Console", + { { "BIOS", + { { "Original BIOS", 0x4248D3E3 }, + 0, + },}, + 0, + },}, + 0, + },}, + 0, +}; + + +RipSystem* getSystem(UINT32 systemID) +{ + int i = 0; + while (*((int*)(&SYSTEMS[i])) != 0) { + if (SYSTEMS[i].systemID == systemID) + return &SYSTEMS[i]; + i++; + } + return NULL; +} +*/ diff --git a/pool/shard000/C/0011052_test-vim.c b/pool/shard000/C/0011052_test-vim.c new file mode 100644 index 0000000000000000000000000000000000000000..9f100e565867a0e9212960b8efb9d6dd6a602efd --- /dev/null +++ b/pool/shard000/C/0011052_test-vim.c @@ -0,0 +1,200 @@ +/* test-vim.c + * + * Copyright © 2015 Christian Hergert + * + * 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 + * along with this program. If not, see . + */ + +#include +#include + +#include "application/ide-application-tests.h" + +#include "../plugins/gnome-builder-plugins.h" + +typedef void (*VimTestFunc) (IdeContext *context, + GtkWidget *widget); + +static void test_vim_basic_cb (IdeContext *context, + GtkWidget *widget); + +struct { + const gchar *path; + VimTestFunc func; +} vim_tests [] = { + { "test.c", test_vim_basic_cb }, + { NULL } +}; + +static void +new_context_cb (GObject *object, + GAsyncResult *result, + gpointer user_data) +{ + g_autoptr(GTask) task = user_data; + GtkWidget *window; + GtkWidget *widget; + IdeBuffer *buffer; + GtkSourceCompletion *completion; + IdeContext *context; + IdeProject *project; + IdeFile *file; + GError *error = NULL; + + context = ide_context_new_finish (result, &error); + g_assert_no_error (error); + g_assert (context != NULL); + g_assert (IDE_IS_CONTEXT (context)); + + project = ide_context_get_project (context); + + for (gint i = 0; vim_tests [i].path; i++) + { + file = ide_project_get_file_for_path (project, vim_tests [i].path); + + buffer = g_object_new (IDE_TYPE_BUFFER, + "context", context, + "file", file, + NULL); + + window = gtk_offscreen_window_new (); + widget = g_object_new (IDE_TYPE_SOURCE_VIEW, + "auto-indent", TRUE, + "buffer", buffer, + "visible", TRUE, + NULL); + gtk_container_add (GTK_CONTAINER (window), widget); + + completion = gtk_source_view_get_completion (GTK_SOURCE_VIEW (widget)); + gtk_source_completion_block_interactive (completion); + + gtk_window_present (GTK_WINDOW (window)); + + while (gtk_events_pending ()) + gtk_main_iteration (); + + vim_tests [i].func (context, widget); + } + + g_task_return_boolean (task, TRUE); +} + +static void +test_vim_basic (GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_autoptr(GFile) project_file = NULL; + GTask *task; + + task = g_task_new (NULL, cancellable, callback, user_data); + project_file = g_file_new_for_path (TEST_DATA_DIR "/project1/configure.ac"); + g_assert (g_file_query_exists (project_file, NULL)); + ide_context_new_async (project_file, + NULL, + new_context_cb, + task); + +} + +/* + * Converts the input_chars into GdkEventKeys and synthesizes them to + * the widget. Then ensures that we get the proper string back out. + */ +static void +assert_keypress_equal (GtkWidget *widget, + const gchar *input_chars, + const gchar *output_str) +{ + g_autofree gchar *result = NULL; + GtkTextView *text_view = (GtkTextView *)widget; + GtkTextBuffer *buffer; + GtkTextIter begin; + GtkTextIter end; + GdkWindow *window; + + g_assert (GTK_IS_TEXT_VIEW (widget)); + + buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (widget)); + g_assert (GTK_IS_TEXT_BUFFER (buffer)); + + window = gtk_text_view_get_window (text_view, GTK_TEXT_WINDOW_TEXT); + g_assert (GDK_IS_WINDOW (window)); + + for (; *input_chars; input_chars = g_utf8_next_char (input_chars)) + { + gunichar ch = g_utf8_get_char (input_chars); + GdkEventKey *event; + + while (gtk_events_pending ()) + gtk_main_iteration (); + + event = dzl_gdk_synthesize_event_key (window, ch); + gtk_main_do_event ((GdkEvent *)event); + gdk_event_free ((GdkEvent *)event); + } + + gtk_text_buffer_get_bounds (buffer, &begin, &end); + result = gtk_text_buffer_get_text (buffer, &begin, &end, TRUE); + + g_assert_cmpstr (result, ==, output_str); + + gtk_text_buffer_set_text (buffer, "", 0); +} + +static void +test_vim_basic_cb (IdeContext *context, + GtkWidget *widget) +{ + g_object_set (widget, + "insert-matching-brace", TRUE, + "overwrite-braces", TRUE, + NULL); + + assert_keypress_equal (widget, "ithis is a test.\e", "this is a test."); + assert_keypress_equal (widget, "ithis is a test.\eI\e4x\e", " is a test."); + assert_keypress_equal (widget, "ido_something (NULL)\ea;\ehhhciwfoo\e", "do_something (foo);"); + assert_keypress_equal (widget, "itesting.\edd\e", ""); + assert_keypress_equal (widget, "i\n\n\edd\e", "\n"); + assert_keypress_equal (widget, "dd\e", ""); + assert_keypress_equal (widget, "iabcd defg hijk\e02de\e", " hijk"); + assert_keypress_equal (widget, "iabcd defg hijk\e0d$\e", ""); + +#if 0 + /* this to fix in our vim */ + assert_keypress_equal (widget, "i\nabcd\n\ekcipfoo", "\nfoo\n"); +#endif +} + +gint +main (gint argc, + gchar *argv[]) +{ + static const gchar *required_plugins[] = { "autotools-plugin", "directory-plugin", NULL }; + IdeApplication *app; + gint ret; + + g_test_init (&argc, &argv, NULL); + + ide_log_init (TRUE, NULL); + ide_log_set_verbosity (4); + + app = ide_application_new (); + ide_application_add_test (app, "/Ide/Vim/basic", test_vim_basic, NULL, required_plugins); + gnome_builder_plugins_init (); + ret = g_application_run (G_APPLICATION (app), argc, argv); + g_object_unref (app); + + return ret; +} diff --git a/pool/shard000/C/0011073_t_nice.c b/pool/shard000/C/0011073_t_nice.c new file mode 100644 index 0000000000000000000000000000000000000000..10b8df7ccb7f05a03655131f5a415371b02a665c --- /dev/null +++ b/pool/shard000/C/0011073_t_nice.c @@ -0,0 +1,221 @@ +/* $NetBSD: t_nice.c,v 1.8 2012/03/18 07:00:51 jruoho Exp $ */ + +/*- + * Copyright (c) 2011 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by Jukka Ruohonen. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, 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 THE FOUNDATION OR CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#include +__RCSID("$NetBSD: t_nice.c,v 1.8 2012/03/18 07:00:51 jruoho Exp $"); + +#include +#include + +#include +#include +#include +#include +#include +#include + +static void *threadfunc(void *); + +static void * +threadfunc(void *arg) +{ + int pri, val; + + val = *(int *)arg; + + errno = 0; + pri = getpriority(PRIO_PROCESS, 0); + ATF_REQUIRE(errno == 0); + + if (pri != val) + atf_tc_fail("nice(3) value was not propagated to threads"); + + return NULL; +} + +ATF_TC(nice_err); +ATF_TC_HEAD(nice_err, tc) +{ + atf_tc_set_md_var(tc, "descr", + "Test nice(3) for invalid parameters (PR lib/42587)"); + atf_tc_set_md_var(tc, "require.user", "unprivileged"); +} + +ATF_TC_BODY(nice_err, tc) +{ + int i; + +#ifdef __FreeBSD__ + atf_tc_expect_fail("nice(incr) with incr < 0 fails with unprivileged " + "users and sets errno == EPERM; see PR # 189821 for more details"); +#endif + + /* + * The call should fail with EPERM if the + * supplied parameter is negative and the + * caller does not have privileges. + */ + for (i = -20; i < 0; i++) { + + errno = 0; + + ATF_REQUIRE_ERRNO(EPERM, nice(i) == -1); + } +} + +ATF_TC(nice_priority); +ATF_TC_HEAD(nice_priority, tc) +{ + atf_tc_set_md_var(tc, "descr", "Test nice(3) vs. getpriority(2)"); +} + +ATF_TC_BODY(nice_priority, tc) +{ +#ifdef __FreeBSD__ + int i, pri, pri2, nic; +#else + int i, pri, nic; +#endif + pid_t pid; + int sta; + + for (i = 0; i <= 20; i++) { + + nic = nice(i); + ATF_REQUIRE(nic != -1); + + errno = 0; + pri = getpriority(PRIO_PROCESS, 0); + ATF_REQUIRE(errno == 0); + +#ifdef __NetBSD__ + if (nic != pri) + atf_tc_fail("nice(3) and getpriority(2) conflict"); +#endif + + /* + * Also verify that the nice(3) values + * are inherited by child processes. + */ + pid = fork(); + ATF_REQUIRE(pid >= 0); + + if (pid == 0) { + + errno = 0; +#ifdef __FreeBSD__ + pri = getpriority(PRIO_PROCESS, 0); +#else + pri2 = getpriority(PRIO_PROCESS, 0); +#endif + ATF_REQUIRE(errno == 0); + +#ifdef __FreeBSD__ + if (pri != pri2) +#else + if (nic != pri) +#endif + _exit(EXIT_FAILURE); + + _exit(EXIT_SUCCESS); + } + + (void)wait(&sta); + + if (WIFEXITED(sta) == 0 || WEXITSTATUS(sta) != EXIT_SUCCESS) + atf_tc_fail("nice(3) value was not inherited"); + } +} + +ATF_TC(nice_root); +ATF_TC_HEAD(nice_root, tc) +{ + atf_tc_set_md_var(tc, "descr", "Test that nice(3) works"); + atf_tc_set_md_var(tc, "require.user", "root"); +} + +ATF_TC_BODY(nice_root, tc) +{ + int i; + + for (i = -20; i <= 20; i++) { + + ATF_REQUIRE(nice(i) != -1); + } +} + +ATF_TC(nice_thread); +ATF_TC_HEAD(nice_thread, tc) +{ + atf_tc_set_md_var(tc, "descr", "Test nice(3) with threads"); +} + +ATF_TC_BODY(nice_thread, tc) +{ + pthread_t tid[5]; +#ifdef __FreeBSD__ + int pri, rv, val; +#else + int rv, val; +#endif + size_t i; + + /* + * Test that the scheduling priority is + * propagated to all system scope threads. + */ + for (i = 0; i < __arraycount(tid); i++) { + + val = nice(i); + ATF_REQUIRE(val != -1); + +#ifdef __FreeBSD__ + pri = getpriority(PRIO_PROCESS, 0); + rv = pthread_create(&tid[i], NULL, threadfunc, &pri); +#else + rv = pthread_create(&tid[i], NULL, threadfunc, &val); +#endif + ATF_REQUIRE(rv == 0); + + rv = pthread_join(tid[i], NULL); + ATF_REQUIRE(rv == 0); + } +} + +ATF_TP_ADD_TCS(tp) +{ + + ATF_TP_ADD_TC(tp, nice_err); + ATF_TP_ADD_TC(tp, nice_priority); + ATF_TP_ADD_TC(tp, nice_root); + ATF_TP_ADD_TC(tp, nice_thread); + + return atf_no_error(); +} diff --git a/pool/shard000/C/0011091_cltnet.c b/pool/shard000/C/0011091_cltnet.c new file mode 100644 index 0000000000000000000000000000000000000000..34d5cdee975ecb61be05ed2fc8a6af87f0fa4c04 --- /dev/null +++ b/pool/shard000/C/0011091_cltnet.c @@ -0,0 +1,116 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cltnet.h" + +#define MAXBUF 4096 + +int dbd_send_string(int sockfd, char *string) +{ + char buffer[MAXBUF]; + int len = 0; + if (string == NULL) { + return -1; + } + + len = write(sockfd, string, strlen(string)); + if (len < 0) { + return len; + } + + len = read(sockfd, buffer, MAXBUF ); + if (strncasecmp(buffer, "copy", 4) != 0) { + return -1; + } + return 0; +} + +int dbd_send_compile_argv(const struct dbd_hostdef *host, const char *argv) +{ + int sockfd, objfd, ret, retval = 0; + struct sockaddr_in dest; + fd_set rfds; + char buffer[MAXBUF], objfile[MAXBUF], *p; + + dbd_get_target_obj(argv, objfile); + printf("obj file %s\n", objfile); + //create socket + if ((sockfd = socket(AF_INET,SOCK_STREAM,0)) < 0) { + fprintf(stderr, "Can not create socket\n"); + retval = errno; + goto error_out; + } + + bzero(&dest,sizeof(dest)); + dest.sin_family = AF_INET; + dest.sin_port = htons(host->port); + if (inet_aton(host->ip, (struct in_addr *)&dest.sin_addr.s_addr) == 0) { + fprintf(stderr, "Can not connected to client socket\n"); + retval = errno; + goto error_out; + } + + /*conect to the server*/ + if (connect(sockfd, (struct sockaddr*)&dest, sizeof(dest)) != 0) { + fprintf(stderr, "Can not connected to client socket\n"); + retval = errno; + goto error_out; + } + + printf("connected to sever\n"); + //set pwd for argv + p = getcwd(buffer, MAXBUF); + if (p != NULL) { + p[strlen(p) + 1] = 0; + p[strlen(p)] = '/'; + } + if (ret = dbd_send_string(sockfd, p) < 0) { + fprintf(stderr, "failed to send pwd\n"); + retval = -1; + goto error_out; + } + + if (ret = dbd_send_string(sockfd, argv) < 0) { + fprintf(stderr, "failed to send compile argv\n"); + retval = -1; + goto error_out; + } + + objfd = open(objfile, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR); + + while (ret = read(sockfd, buffer, MAXBUF) > 0) { + if (strcmp(buffer, "bye") != 0) + ret = write(objfd, buffer, ret); + else + ret = -1; + if (ret < 0) { + fprintf(stderr, "failed to receive obj file\n"); + retval = -1; + goto error_out; + } + bzero(buffer, MAXBUF + 1); + } + + if (ret < 0) { + fprintf(stderr, "faild to receive obj file\n"); + retval = -1; + } + +error_out: + close(objfd); + close(sockfd); + return retval; +} diff --git a/pool/shard000/C/0011094_bind.c b/pool/shard000/C/0011094_bind.c new file mode 100644 index 0000000000000000000000000000000000000000..1f7c80b7745973d76ffb4c96a072046eb7cc0e79 --- /dev/null +++ b/pool/shard000/C/0011094_bind.c @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2013-2017 Ilya Kaliman + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#include "vimol.h" + +struct node { + char *name; + char *value; +}; + +struct bind { + int nelts, nalloc; + struct node *data; +}; + +static int +compare(const void *a, const void *b) +{ + const struct node *aa = (const struct node *)a; + const struct node *bb = (const struct node *)b; + + return (strcasecmp(aa->name, bb->name)); +} + +static struct node * +bind_find_node(struct bind *bind, const char *name) +{ + struct node node; + + node.name = (char *)name; + + return (bsearch(&node, bind->data, bind->nelts, + sizeof node, compare)); +} + +struct bind * +bind_create(void) +{ + struct bind *bind; + + bind = xcalloc(1, sizeof *bind); + bind->nalloc = 8; + bind->data = xcalloc(bind->nalloc, sizeof *bind->data); + + return (bind); +} + +void +bind_free(struct bind *bind) +{ + int i; + + if (bind) { + for (i = 0; i < bind->nelts; i++) { + free(bind->data[i].name); + free(bind->data[i].value); + } + free(bind->data); + free(bind); + } +} + +int +bind_set(struct bind *bind, const char *name, const char *value) +{ + struct node node; + int i, res; + + node.name = xstrdup(name); + node.value = xstrdup(value); + res = 1; + + for (i = 0; i < bind->nelts; i++) + if ((res = compare(&bind->data[i], &node)) >= 0) + break; + + if (res == 0) { + free(bind->data[i].name); + free(bind->data[i].value); + } else { + if (bind->nelts == bind->nalloc) { + bind->nalloc *= 2; + bind->data = xrealloc(bind->data, + bind->nalloc * sizeof *bind->data); + } + memmove(bind->data + i + 1, bind->data + i, + (bind->nelts - i) * sizeof *bind->data); + bind->nelts++; + } + + bind->data[i] = node; + return (res == 0); +} + +const char * +bind_get(struct bind *bind, const char *name) +{ + struct node *node = bind_find_node(bind, name); + + return (node ? node->value : NULL); +} diff --git a/pool/shard000/C/0011098_make-te.c b/pool/shard000/C/0011098_make-te.c new file mode 100644 index 0000000000000000000000000000000000000000..628d6060df32a700ef3502f693e9767040017c44 --- /dev/null +++ b/pool/shard000/C/0011098_make-te.c @@ -0,0 +1,37 @@ +#include +#include +#include + +int main() +{ + char name[512]; + char num[512]; + char def[512]; + char args[512]; + char buf[512]; + char *defines[512]; + int i = 0; + + printf("/* this file is auto generated, edit textevents.in instead! */\n\nconst struct text_event te[] = {\n"); + while(fgets(name, sizeof(name), stdin)) + { + name[strlen(name)-1] = 0; + fgets(def, sizeof(def), stdin); + def[strlen(def)-1] = 0; + fgets(args, sizeof(args), stdin); + args[strlen(args)-1] = 0; + fgets(buf, sizeof(buf), stdin); + + printf("\n{\"%s\", %d, \n\"%s\"},\n", + name, atoi(args), def); + + defines[i] = strdup (num); + i++; + } + + printf("\n{NULL} /* sentinel */\n"); + + printf("};\n"); + + return 0; +} diff --git a/pool/shard000/C/0011106_calloc.c b/pool/shard000/C/0011106_calloc.c new file mode 100644 index 0000000000000000000000000000000000000000..192f3139891a8e295a40380a50781e8f053fa769 --- /dev/null +++ b/pool/shard000/C/0011106_calloc.c @@ -0,0 +1,19 @@ +/* See LICENSE file for copyright and license details. */ + +#include +#include + +void * +calloc(size_t nmemb, size_t size) +{ + size_t nbytes; + void *mem; + + if (!nmemb || !size || nmemb > (size_t)-1/size) + return NULL; + + nbytes = nmemb * size; + if ((mem = malloc(nbytes)) == NULL) + return NULL; + return memset(mem, 0, nbytes); +} diff --git a/pool/shard000/C/0011108_sprintf.c b/pool/shard000/C/0011108_sprintf.c new file mode 100644 index 0000000000000000000000000000000000000000..520892532af793ee72bab45bff56dd578ab8dfe8 --- /dev/null +++ b/pool/shard000/C/0011108_sprintf.c @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2011 Parallax, Inc. + * Written by Eric R. Smith, Total Spectrum Software Inc. + * MIT licensed (see terms at end of file) + */ +#include +#include + +int sprintf(char *str, const char *fmt, ...) +{ + FILE tmpfile; + va_list args; + int r; + size_t len = 0x7fffffff; + va_start(args, fmt); + r = vfprintf(__string_file(&tmpfile, str, "w", len), fmt, args); + fclose(&tmpfile); + va_end(args); + return r; +} + +/* +-------------------------------------------------------------------- + * ¦ TERMS OF USE: MIT License + * +-------------------------------------------------------------------- + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * +-------------------------------------------------------------------- + */ diff --git a/pool/shard000/C/0011111_pwmout_api.c b/pool/shard000/C/0011111_pwmout_api.c new file mode 100644 index 0000000000000000000000000000000000000000..c6ad54e1f9f79a7f447fc1f8d194b4baadb80848 --- /dev/null +++ b/pool/shard000/C/0011111_pwmout_api.c @@ -0,0 +1,212 @@ +/* mbed Microcontroller Library + * Copyright (c) 2015-2017 Nuvoton + * + * 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 "pwmout_api.h" + +#if DEVICE_PWMOUT + +#include "cmsis.h" +#include "pinmap.h" +#include "PeripheralPins.h" +#include "nu_modutil.h" +#include "nu_miscutil.h" +#include "nu_bitutil.h" + +struct nu_pwm_var { + uint32_t en_msk; +}; + +static struct nu_pwm_var pwm0_01_var = { + .en_msk = 0 +}; + +static struct nu_pwm_var pwm0_23_var = { + .en_msk = 0 +}; + +static struct nu_pwm_var pwm1_01_var = { + .en_msk = 0 +}; + +static struct nu_pwm_var pwm1_23_var = { + .en_msk = 0 +}; + +static uint32_t pwm_modinit_mask = 0; + +static const struct nu_modinit_s pwm_modinit_tab[] = { + {PWM_0_0, PWM0_CH01_MODULE, CLK_CLKSEL1_PWM0_CH01_S_HCLK, 0, PWM0_RST, PWM0_IRQn, &pwm0_01_var}, + {PWM_0_1, PWM0_CH01_MODULE, CLK_CLKSEL1_PWM0_CH01_S_HCLK, 0, PWM0_RST, PWM0_IRQn, &pwm0_01_var}, + {PWM_0_2, PWM0_CH23_MODULE, CLK_CLKSEL1_PWM0_CH23_S_HCLK, 0, PWM0_RST, PWM0_IRQn, &pwm0_23_var}, + {PWM_0_3, PWM0_CH23_MODULE, CLK_CLKSEL1_PWM0_CH23_S_HCLK, 0, PWM0_RST, PWM0_IRQn, &pwm0_23_var}, + + {PWM_1_0, PWM1_CH01_MODULE, CLK_CLKSEL2_PWM1_CH01_S_HCLK, 0, PWM1_RST, PWM1_IRQn, &pwm1_01_var}, + {PWM_1_1, PWM1_CH01_MODULE, CLK_CLKSEL2_PWM1_CH01_S_HCLK, 0, PWM1_RST, PWM1_IRQn, &pwm1_01_var}, + {PWM_1_2, PWM1_CH23_MODULE, CLK_CLKSEL2_PWM1_CH23_S_HCLK, 0, PWM1_RST, PWM1_IRQn, &pwm1_23_var}, + {PWM_1_3, PWM1_CH23_MODULE, CLK_CLKSEL2_PWM1_CH23_S_HCLK, 0, PWM1_RST, PWM1_IRQn, &pwm1_23_var}, + + {NC, 0, 0, 0, 0, (IRQn_Type) 0, NULL} +}; + +static void pwmout_config(pwmout_t *obj); + +void pwmout_init(pwmout_t *obj, PinName pin) +{ + obj->pwm = (PWMName) pinmap_peripheral(pin, PinMap_PWM); + MBED_ASSERT((int) obj->pwm != NC); + + const struct nu_modinit_s *modinit = get_modinit(obj->pwm, pwm_modinit_tab); + MBED_ASSERT(modinit != NULL); + MBED_ASSERT((PWMName) modinit->modname == obj->pwm); + + obj->pin = pin; + + // Wire pinout + pinmap_pinout(pin, PinMap_PWM); + + PWM_T *pwm_base = (PWM_T *) NU_MODBASE(obj->pwm); + uint32_t chn = NU_MODSUBINDEX(obj->pwm); + + // NOTE: Channels 0/1, 2/3 share a clock source. + if ((((struct nu_pwm_var *) modinit->var)->en_msk & 0xF) == 0) { + // Select clock source of paired channels + CLK_SetModuleClock(modinit->clkidx, modinit->clksrc, modinit->clkdiv); + // Enable clock of paired channels + CLK_EnableModuleClock(modinit->clkidx); + } + + // Default: period = 10 ms, pulse width = 0 ms + obj->period_us = 1000 * 10; + obj->pulsewidth_us = 0; + pwmout_config(obj); + // enable inverter to ensure the first PWM cycle is correct + pwm_base->CTL |= (PWM_CTL_CH0INV_Msk << (chn * 8)); + + // Enable output of the specified PWM channel + PWM_EnableOutput(pwm_base, 1 << chn); + PWM_Start(pwm_base, 1 << chn); + + ((struct nu_pwm_var *) modinit->var)->en_msk |= 1 << chn; + + if (((struct nu_pwm_var *) modinit->var)->en_msk) { + // Mark this module to be inited. + int i = modinit - pwm_modinit_tab; + pwm_modinit_mask |= 1 << i; + } +} + +void pwmout_free(pwmout_t *obj) +{ + PWM_T *pwm_base = (PWM_T *) NU_MODBASE(obj->pwm); + uint32_t chn = NU_MODSUBINDEX(obj->pwm); + PWM_ForceStop(pwm_base, 1 << chn); + + const struct nu_modinit_s *modinit = get_modinit(obj->pwm, pwm_modinit_tab); + MBED_ASSERT(modinit != NULL); + MBED_ASSERT((PWMName) modinit->modname == obj->pwm); + ((struct nu_pwm_var *) modinit->var)->en_msk &= ~(1 << chn); + + + if ((((struct nu_pwm_var *) modinit->var)->en_msk & 0xF) == 0) { + CLK_DisableModuleClock(modinit->clkidx); + } + + if (((struct nu_pwm_var *) modinit->var)->en_msk == 0) { + // Mark this module to be deinited. + int i = modinit - pwm_modinit_tab; + pwm_modinit_mask &= ~(1 << i); + } + + // Free up pins + gpio_set(obj->pin); + obj->pin = NC; +} + +void pwmout_write(pwmout_t *obj, float value) +{ + obj->pulsewidth_us = NU_CLAMP((uint32_t)(value * obj->period_us), 0, obj->period_us); + pwmout_config(obj); +} + +float pwmout_read(pwmout_t *obj) +{ + return NU_CLAMP((((float) obj->pulsewidth_us) / obj->period_us), 0.0f, 1.0f); +} + +void pwmout_period(pwmout_t *obj, float seconds) +{ + pwmout_period_us(obj, seconds * 1000000.0f); +} + +void pwmout_period_ms(pwmout_t *obj, int ms) +{ + pwmout_period_us(obj, ms * 1000); +} + +// Set the PWM period, keeping the duty cycle the same. +void pwmout_period_us(pwmout_t *obj, int us) +{ + uint32_t period_us_old = obj->period_us; + uint32_t pulsewidth_us_old = obj->pulsewidth_us; + obj->period_us = us; + obj->pulsewidth_us = NU_CLAMP(obj->period_us * pulsewidth_us_old / period_us_old, 0, obj->period_us); + pwmout_config(obj); +} + +int pwmout_read_period_us(pwmout_t *obj) +{ + return obj->period_us; +} + +void pwmout_pulsewidth(pwmout_t *obj, float seconds) +{ + pwmout_pulsewidth_us(obj, seconds * 1000000.0f); +} + +void pwmout_pulsewidth_ms(pwmout_t *obj, int ms) +{ + pwmout_pulsewidth_us(obj, ms * 1000); +} + +void pwmout_pulsewidth_us(pwmout_t *obj, int us) +{ + obj->pulsewidth_us = NU_CLAMP(us, 0, obj->period_us); + pwmout_config(obj); +} + +int pwmout_read_pulsewidth_us(pwmout_t *obj) +{ + return obj->pulsewidth_us; +} + +static void pwmout_config(pwmout_t *obj) +{ + PWM_T *pwm_base = (PWM_T *) NU_MODBASE(obj->pwm); + uint32_t chn = NU_MODSUBINDEX(obj->pwm); + // NOTE: Support period < 1s + // NOTE: ARM mbed CI test fails due to first PWM pulse error. Workaround by: + // 1. Inverse duty cycle (100 - duty) + // 2. Inverse PWM output polarity + // This trick is here to pass ARM mbed CI test. First PWM pulse error still remains. + PWM_ConfigOutputChannel2(pwm_base, chn, 1000 * 1000, 100 - (obj->pulsewidth_us * 100 / obj->period_us), obj->period_us); +} + +const PinMap *pwmout_pinmap() +{ + return PinMap_PWM; +} + +#endif diff --git a/pool/shard000/C/0011114_f128M_to_ui64_r_minMag.c b/pool/shard000/C/0011114_f128M_to_ui64_r_minMag.c new file mode 100644 index 0000000000000000000000000000000000000000..1c4f3ece2c2860ca9caca7697154ec1bb6107209 --- /dev/null +++ b/pool/shard000/C/0011114_f128M_to_ui64_r_minMag.c @@ -0,0 +1,97 @@ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3a, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 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. 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. + +=============================================================================*/ + +#include +#include +#include "platform.h" +#include "internals.h" +#include "softfloat.h" + +#ifdef SOFTFLOAT_FAST_INT64 + +uint_fast64_t f128M_to_ui64_r_minMag( const float128_t *aPtr, bool exact ) +{ + + return f128_to_ui64_r_minMag( *aPtr, exact ); + +} + +#else + +uint_fast64_t f128M_to_ui64_r_minMag( const float128_t *aPtr, bool exact ) +{ + const uint32_t *aWPtr; + uint32_t uiA96; + int32_t exp, shiftCount; + uint32_t sig96, sig[4]; + uint64_t z; + + aWPtr = (const uint32_t *) aPtr; + uiA96 = aWPtr[indexWordHi( 4 )]; + exp = expF128UI96( uiA96 ); + shiftCount = 0x403E - exp; + if ( shiftCount < 0 ) goto invalid; + if ( exact ) { + sig96 = fracF128UI96( uiA96 ); + if ( exp ) sig96 |= 0x00010000; + sig[indexWord( 4, 3 )] = sig96; + sig[indexWord( 4, 2 )] = aWPtr[indexWord( 4, 2 )]; + sig[indexWord( 4, 1 )] = aWPtr[indexWord( 4, 1 )]; + sig[indexWord( 4, 0 )] = aWPtr[indexWord( 4, 0 )]; + softfloat_shiftRightJam128M( sig, shiftCount + 17, sig ); + z = (uint64_t) sig[indexWord( 4, 2 )]<<32 | sig[indexWord( 4, 1 )]; + if ( signF128UI96( uiA96 ) && z ) goto invalid; + if ( sig[indexWordLo( 4 )] ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; + } + } else { + if ( 64 <= shiftCount ) return 0; + if ( signF128UI96( uiA96 ) ) goto invalid; + z = UINT64_C( 0x8000000000000000 ) + | (uint64_t) fracF128UI96( uiA96 )<<47 + | (uint64_t) aWPtr[indexWord( 4, 2 )]<<15 + | aWPtr[indexWord( 4, 1 )]>>17; + z >>= shiftCount; + } + return z; + invalid: + softfloat_raiseFlags( softfloat_flag_invalid ); + return UINT64_C( 0xFFFFFFFFFFFFFFFF ); + +} + +#endif + diff --git a/pool/shard000/C/0011133_gimpoperationcolormode.c b/pool/shard000/C/0011133_gimpoperationcolormode.c new file mode 100644 index 0000000000000000000000000000000000000000..ad787f533424d200662b96a6b5d4380b7302d2b0 --- /dev/null +++ b/pool/shard000/C/0011133_gimpoperationcolormode.c @@ -0,0 +1,144 @@ +/* GIMP - The GNU Image Manipulation Program + * Copyright (C) 1995 Spencer Kimball and Peter Mattis + * + * gimpoperationcolormode.c + * Copyright (C) 2008 Michael Natterer + * 2012 Ville Sokk + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#include "config.h" + +#include +#include +#include + +#include "libgimpcolor/gimpcolor.h" + +#include "operations-types.h" + +#include "gimpoperationcolormode.h" + + +static gboolean gimp_operation_color_mode_process (GeglOperation *operation, + void *in_buf, + void *aux_buf, + void *aux2_buf, + void *out_buf, + glong samples, + const GeglRectangle *roi, + gint level); + + +G_DEFINE_TYPE (GimpOperationColorMode, gimp_operation_color_mode, + GIMP_TYPE_OPERATION_POINT_LAYER_MODE) + + +static void +gimp_operation_color_mode_class_init (GimpOperationColorModeClass *klass) +{ + GeglOperationClass *operation_class; + GeglOperationPointComposer3Class *point_class; + + operation_class = GEGL_OPERATION_CLASS (klass); + point_class = GEGL_OPERATION_POINT_COMPOSER3_CLASS (klass); + + gegl_operation_class_set_keys (operation_class, + "name", "gimp:color-mode", + "description", "GIMP color mode operation", + NULL); + + point_class->process = gimp_operation_color_mode_process; +} + +static void +gimp_operation_color_mode_init (GimpOperationColorMode *self) +{ +} + +static gboolean +gimp_operation_color_mode_process (GeglOperation *operation, + void *in_buf, + void *aux_buf, + void *aux2_buf, + void *out_buf, + glong samples, + const GeglRectangle *roi, + gint level) +{ + gdouble opacity = GIMP_OPERATION_POINT_LAYER_MODE (operation)->opacity; + gfloat *in = in_buf; + gfloat *layer = aux_buf; + gfloat *mask = aux2_buf; + gfloat *out = out_buf; + const gboolean has_mask = mask != NULL; + + while (samples--) + { + GimpHSL layer_hsl, out_hsl; + GimpRGB layer_rgb = {layer[0], layer[1], layer[2]}; + GimpRGB out_rgb = {in[0], in[1], in[2]}; + gfloat comp_alpha, new_alpha; + + comp_alpha = MIN (in[ALPHA], layer[ALPHA]) * opacity; + if (has_mask) + comp_alpha *= *mask; + + new_alpha = in[ALPHA] + (1.0 - in[ALPHA]) * comp_alpha; + + if (comp_alpha && new_alpha) + { + gint b; + gfloat ratio = comp_alpha / new_alpha; + + gimp_rgb_to_hsl (&layer_rgb, &layer_hsl); + gimp_rgb_to_hsl (&out_rgb, &out_hsl); + + out_hsl.h = layer_hsl.h; + out_hsl.s = layer_hsl.s; + gimp_hsl_to_rgb (&out_hsl, &out_rgb); + + out[0] = out_rgb.r; + out[1] = out_rgb.g; + out[2] = out_rgb.b; + + for (b = RED; b < ALPHA; b++) + { + out[b] = out[b] * ratio + in[b] * (1.0 - ratio); + } + } + else + { + gint b; + + for (b = RED; b < ALPHA; b++) + { + out[b] = in[b]; + } + } + + out[ALPHA] = in[ALPHA]; + + in += 4; + layer += 4; + out += 4; + + if (has_mask) + mask++; + } + + return TRUE; +} diff --git a/pool/shard000/C/0011148_hvconsole.c b/pool/shard000/C/0011148_hvconsole.c new file mode 100644 index 0000000000000000000000000000000000000000..7ceafe3e80383397dc562c1edb7d86ae994245a1 --- /dev/null +++ b/pool/shard000/C/0011148_hvconsole.c @@ -0,0 +1,81 @@ +/* + * hvconsole.c + * Copyright (C) 2004 Hollis Blanchard, IBM Corporation + * Copyright (C) 2004 IBM Corporation + * + * Additional Author(s): + * Ryan S. Arnold + * + * LPAR console support. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include +#include +#include +#include +#include +#include "plpar_wrappers.h" + +/* + + + + + + + */ +int hvc_get_chars(uint32_t vtermno, char *buf, int count) +{ + unsigned long got; + + if (plpar_get_term_char(vtermno, &got, buf) == H_SUCCESS) + return got; + + return 0; +} + +EXPORT_SYMBOL(hvc_get_chars); + + +/* + + + + + + + */ +int hvc_put_chars(uint32_t vtermno, const char *buf, int count) +{ + unsigned long *lbuf = (unsigned long *) buf; + long ret; + + + /* */ + if (count > MAX_VIO_PUT_CHARS) + count = MAX_VIO_PUT_CHARS; + + ret = plpar_hcall_norets(H_PUT_TERM_CHAR, vtermno, count, lbuf[0], + lbuf[1]); + if (ret == H_SUCCESS) + return count; + if (ret == H_BUSY) + return -EAGAIN; + return -EIO; +} + +EXPORT_SYMBOL(hvc_put_chars); diff --git a/pool/shard000/C/0011150_xtl_subvars.c b/pool/shard000/C/0011150_xtl_subvars.c new file mode 100644 index 0000000000000000000000000000000000000000..fd2e3c2a6d1f48bcdd39b4afeb1e2ebb2fcd1a91 --- /dev/null +++ b/pool/shard000/C/0011150_xtl_subvars.c @@ -0,0 +1,256 @@ + + +#include +#include +#include + +#include "danalib.h" +#include "xronostoollib.h" + + +static DL_KeyValue_List *head = NULL; + + +/************************************* +void XTL_SubVars_Init( void ) + +Must be called to initialize the variables list + +returns nothing +*************************************/ +void XTL_SubVars_Init( void ) +{ +XTL_SubVars_Add( "XTL_SV_QuestionCount", "0", FALSE ); +XTL_SubVars_Add( "XTL_SV_HELPFILE", "", FALSE ); +XTL_SubVars_Add( "XTL_SV_OUTPUTFILE", "", FALSE ); +} + + + +/************************************* +int XTL_SubVars_Add( char *key, char *Value, BOOL CaseSensitive ) ) + +updates the key with the value + +returns 0 on success, -1 is key already exists, other non zero is internal error +*************************************/ +int XTL_SubVars_Add( char *key, char *Value, BOOL CaseSensitive ) +{ +char *p; + +p = XTL_SubVars_GetValueChar( key ); +if ( p != NULL ) + return -1; + +DL_KeyValue_Add( &head, key, Value, CaseSensitive ); + +return 0; +} + + +/************************************* +int XTL_SubVars_UpdateChar( char *key, char *Value ) + +updates the key with the value + +returns 0 on success, -1 is key not found, other non zero is internal error +*************************************/ +int XTL_SubVars_UpdateChar( char *key, char *Value ) +{ +return DL_KeyValue_Modify( &head, key, Value ); +} + + +/************************************* +int XTL_SubVars_UpdateInt( char *key, char *Value ) + +updates the key with the value + +returns 0 on success, -1 is key not found, other non zero is internal error +*************************************/ +int XTL_SubVars_UpdateInt( char *key, int Value ) +{ +char buffer[100]; + +sprintf( buffer, "%d", Value ); +return DL_KeyValue_Modify( &head, key, buffer ); +} + + +/************************************* +int XTL_SubVars_GetValueChar( char *key, char *Value ) + +returns the value associated with the key + +returns NULL if key not found +*************************************/ +char *XTL_SubVars_GetValueChar( char *key ) +{ +return DL_KeyValue_Find( &head, key ); +} + + +/************************************* +int XTL_SubVars_GetValueInt( char *key, char *Value ) + +returns the value associated with the key + +returns XTL_SUBVARS_INT_VALUE_NOT_FOUND if key not found +*************************************/ +int XTL_SubVars_GetValueInt( char *key ) +{ +char *p; +int retval; + +p = DL_KeyValue_Find( &head, key ); + +if ( p == NULL ) + return XTL_SUBVARS_INT_VALUE_NOT_FOUND; + +retval = atoi( p ); + +return retval; +} + + + +/************************************* +int XTL_SubVars_IncrementValue( char *key ) + +Increments the value associated with the key + +returns 0 on success, -1 is key not found, other non zero is internal error +*************************************/ +int XTL_SubVars_IncrementValue( char *key ) +{ +int retval; + +retval = XTL_SubVars_GetValueInt( key ); +if ( retval == XTL_SUBVARS_INT_VALUE_NOT_FOUND ) + return -1; + +++retval; + +return XTL_SubVars_UpdateInt( key, retval ); +} + + + +/************************************* +int XTL_SubVars_DecrementValue( char *key ) + +decrements the value associated with the key + +returns 0 on success, -1 is key not found, other non zero is internal error +*************************************/ +int XTL_SubVars_DecrementValue( char *key ) +{ +int retval; + +retval = XTL_SubVars_GetValueInt( key ); +if ( retval == XTL_SUBVARS_INT_VALUE_NOT_FOUND ) + return -1; + +--retval; + +return XTL_SubVars_UpdateInt( key, retval ); +} + +/************************************* +*************************************/ +static char *GetNewBuffer( char *Line, int Increment ) +{ + int len; + char *retval; + + if ( Line == NULL ) + return NULL; + + len = strlen(Line) + Increment + 1; + retval = GetMemoryBlock( len ); + + retval[0] = 0; + return retval; +} + + +/************************************* +char *XTL_Substitute( char *line ) + +Makes all substitutions it can in the line + +returns a pointer to a NEW allocated bufffer, +caller is responsible for calling FreeMemoryBlock() +*************************************/ +char *XTL_Substitute( char *line ) +{ + char *MyStartLine; + char *MyEndLine; + int len, MaxValueLen = -1; + char *p; + DL_KeyValue_List *Me; + + MyStartLine = GetNewBuffer( line, 0 ); + strcpy( MyStartLine, line ); + + /* determine longest string in the substitution variables list */ + for( Me = head; Me != NULL; Me = Me->next ) + { + len = strlen( Me->value ); + if ( len > MaxValueLen ) + MaxValueLen = len; + + } + + Me = head; + while ( Me != NULL ) + { + /* do we have a hit */ + p = strstr( MyStartLine, Me->key ); + if ( p == NULL ) /* if not, then move to next variable */ + { + Me = Me->next; + continue; + } + + TracePrintf( "XTL_Substitute: Key: %s, Line: %s\n", Me->key, MyStartLine ); + + /* get a new buffer we can put stuff into, enough for the original string plus the maximum length value we can have */ + MyEndLine = GetNewBuffer( MyStartLine, MaxValueLen ); + /* copy everything up to the key */ + len = (int)(p - MyStartLine); + if ( len > 0 ) + { + strncpy( MyEndLine, MyStartLine, len ); + MyEndLine[len] = 0; + } + /* copy in the value related to the key */ + strcat( MyEndLine, Me->value ); + /* skip over the key in the original buffer */ + p+=strlen(Me->key); + /* copy in the remainder of the line */ + if ( *p != 0 ) + strcat( MyEndLine, p ); + /* free the old buffer */ + p = MyStartLine; + MyStartLine = MyEndLine; + FreeMemoryBlock( p ); + MyEndLine = NULL; + } + + return MyStartLine; +} + + + + + + + + + + + + + + diff --git a/pool/shard000/C/0011154_fprintf.c b/pool/shard000/C/0011154_fprintf.c new file mode 100644 index 0000000000000000000000000000000000000000..f1bf59ffe4cd76d98249c675b41707f3f1f4509f --- /dev/null +++ b/pool/shard000/C/0011154_fprintf.c @@ -0,0 +1,77 @@ +/* Formatted output to a stream. + Copyright (C) 2004, 2006-2012 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 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 + along with this program. If not, see . */ + +#ifdef HAVE_CONFIG_H +# include +#endif + +/* Specification. */ +#include + +#include +#include +#include +#include + +#include "fseterr.h" +#include "vasnprintf.h" + +/* Print formatted output to the stream FP. + Return string length of formatted string. On error, return a negative + value. */ +int +fprintf (FILE *fp, const char *format, ...) +{ + char buf[2000]; + char *output; + size_t len; + size_t lenbuf = sizeof (buf); + va_list args; + + va_start (args, format); + output = vasnprintf (buf, &lenbuf, format, args); + len = lenbuf; + va_end (args); + + if (!output) + { + fseterr (fp); + return -1; + } + + if (fwrite (output, 1, len, fp) < len) + { + if (output != buf) + { + int saved_errno = errno; + free (output); + errno = saved_errno; + } + return -1; + } + + if (output != buf) + free (output); + + if (len > INT_MAX) + { + errno = EOVERFLOW; + fseterr (fp); + return -1; + } + + return len; +} diff --git a/pool/shard000/C/0011166_post.c b/pool/shard000/C/0011166_post.c new file mode 100644 index 0000000000000000000000000000000000000000..aa8ea18ee9330735679d29c5cdf8b9a6c216fda4 --- /dev/null +++ b/pool/shard000/C/0011166_post.c @@ -0,0 +1,136 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ + +#include +#include +#include +#include +#include +#include + +#if CONFIG(USE_OPTION_TABLE) +# include "option_table.h" +# define CMOS_POST_OFFSET (CMOS_VSTART_cmos_post_offset >> 3) +#else +# if (CONFIG_CMOS_POST_OFFSET != 0) +# define CMOS_POST_OFFSET CONFIG_CMOS_POST_OFFSET +# else +# error "Must configure CONFIG_CMOS_POST_OFFSET" +# endif +#endif + +/* + * 0 = Bank Select Magic + * 1 = Bank 0 POST + * 2 = Bank 1 POST + * 3-6 = BANK 0 Extra log + * 7-10 = BANK 1 Extra log + */ +#define CMOS_POST_BANK_OFFSET (CMOS_POST_OFFSET) +#define CMOS_POST_BANK_0_MAGIC 0x80 +#define CMOS_POST_BANK_0_OFFSET (CMOS_POST_OFFSET + 1) +#define CMOS_POST_BANK_0_EXTRA (CMOS_POST_OFFSET + 3) +#define CMOS_POST_BANK_1_MAGIC 0x81 +#define CMOS_POST_BANK_1_OFFSET (CMOS_POST_OFFSET + 2) +#define CMOS_POST_BANK_1_EXTRA (CMOS_POST_OFFSET + 7) + +#define CMOS_POST_EXTRA_DEV_PATH 0x01 + +DECLARE_SPIN_LOCK(cmos_post_lock) + +int cmos_post_previous_boot(u8 *code, u32 *extra) +{ + *code = 0; + *extra = 0; + + spin_lock(&cmos_post_lock); + + /* Get post code from other bank */ + switch (cmos_read(CMOS_POST_BANK_OFFSET)) { + case CMOS_POST_BANK_0_MAGIC: + *code = cmos_read(CMOS_POST_BANK_1_OFFSET); + *extra = cmos_read32(CMOS_POST_BANK_1_EXTRA); + break; + case CMOS_POST_BANK_1_MAGIC: + *code = cmos_read(CMOS_POST_BANK_0_OFFSET); + *extra = cmos_read32(CMOS_POST_BANK_0_EXTRA); + break; + } + + spin_unlock(&cmos_post_lock); + + /* Check last post code in previous boot against normal list */ + switch (*code) { + case POST_OS_BOOT: + case POST_OS_RESUME: + case POST_ENTER_ELF_BOOT: + case 0: + break; + default: + return -1; + } + + return 0; +} + +void cmos_post_init(void) +{ + u8 magic = CMOS_POST_BANK_0_MAGIC; + + /* Switch to the other bank */ + switch (cmos_read(CMOS_POST_BANK_OFFSET)) { + case CMOS_POST_BANK_1_MAGIC: + break; + case CMOS_POST_BANK_0_MAGIC: + magic = CMOS_POST_BANK_1_MAGIC; + break; + default: + /* Initialize to zero */ + cmos_write(0, CMOS_POST_BANK_0_OFFSET); + cmos_write(0, CMOS_POST_BANK_1_OFFSET); + cmos_write32(0, CMOS_POST_BANK_0_EXTRA); + cmos_write32(0, CMOS_POST_BANK_1_EXTRA); + } + + cmos_write(magic, CMOS_POST_BANK_OFFSET); +} + +void cmos_post_code(u8 value) +{ + spin_lock(&cmos_post_lock); + + switch (cmos_read(CMOS_POST_BANK_OFFSET)) { + case CMOS_POST_BANK_0_MAGIC: + cmos_write(value, CMOS_POST_BANK_0_OFFSET); + break; + case CMOS_POST_BANK_1_MAGIC: + cmos_write(value, CMOS_POST_BANK_1_OFFSET); + break; + } + + spin_unlock(&cmos_post_lock); +} + +void cmos_post_extra(u32 value) +{ + spin_lock(&cmos_post_lock); + + switch (cmos_read(CMOS_POST_BANK_OFFSET)) { + case CMOS_POST_BANK_0_MAGIC: + cmos_write32(value, CMOS_POST_BANK_0_EXTRA); + break; + case CMOS_POST_BANK_1_MAGIC: + cmos_write32(value, CMOS_POST_BANK_1_EXTRA); + break; + } + + spin_unlock(&cmos_post_lock); +} + +void cmos_post_path(const struct device *dev) +{ + /* Encode path into lower 3 bytes */ + u32 path = dev_path_encode(dev); + /* Upper byte contains the log type */ + path |= CMOS_POST_EXTRA_DEV_PATH << 24; + cmos_post_extra(path); +} diff --git a/pool/shard000/C/0011168_Prog4.c b/pool/shard000/C/0011168_Prog4.c new file mode 100644 index 0000000000000000000000000000000000000000..848be766fb0c523db25e2a44eb36e1ef36c2a134 --- /dev/null +++ b/pool/shard000/C/0011168_Prog4.c @@ -0,0 +1,71 @@ +/* Day 7 + * Question 4 + * Write a program to sort an array using selection sort + * + * Author - + * Akshay Anand + * CSE 2nd Sem - St. Thomas' College of Engineering & Technology + */ + + #include + + int main() + { + int length, i, j, key, position, temp; + + printf("Enter the length of the array: "); + scanf("%d", &length); + + int array[length]; + + printf("Enter the elements of the array: \n"); + for(i=0; i + * Copyright 1998 Gerald Combs + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include +#include +#include +#include +#include + +#include "packet-ieee802a.h" + +static int proto_ieee802a = -1; +static int hf_ieee802a_oui = -1; +static int hf_ieee802a_pid = -1; + +static gint ett_ieee802a = -1; + +static dissector_handle_t data_handle; + +/* + * Hash table for translating OUIs to a dissector table/field info pair; + * the dissector table maps PID values to dissectors, and the field + * corresponds to the PID for that OUI. + */ +typedef struct { + dissector_table_t table; + hf_register_info *field_info; +} oui_info_t; + +static GHashTable *oui_info_table = NULL; + +/* + * Add an entry for a new OUI. + */ +void +ieee802a_add_oui(guint32 oui, const char *table_name, char *table_ui_name, + hf_register_info *hf_item) +{ + oui_info_t *new_info; + + new_info = g_malloc(sizeof (oui_info_t)); + new_info->table = register_dissector_table(table_name, + table_ui_name, FT_UINT16, BASE_HEX); + new_info->field_info = hf_item; + + /* + * Create the hash table for OUI information, if it doesn't + * already exist. + */ + if (oui_info_table == NULL) { + oui_info_table = g_hash_table_new(g_direct_hash, + g_direct_equal); + } + g_hash_table_insert(oui_info_table, GUINT_TO_POINTER(oui), new_info); +} + +static void +dissect_ieee802a(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) +{ + proto_tree *ieee802a_tree = NULL; + proto_item *ti; + tvbuff_t *next_tvb; + const gchar *manuf; + guint8 oui[3]; + guint16 pid; + oui_info_t *oui_info; + dissector_table_t subdissector_table; + int hf; + + col_set_str(pinfo->cinfo, COL_PROTOCOL, "IEEE802a"); + col_clear(pinfo->cinfo, COL_INFO); + + if (tree) { + ti = proto_tree_add_item(tree, proto_ieee802a, tvb, 0, 5, ENC_NA); + ieee802a_tree = proto_item_add_subtree(ti, ett_ieee802a); + } + + tvb_memcpy(tvb, oui, 0, 3); + manuf = get_manuf_name_if_known(oui); + pid = tvb_get_ntohs(tvb, 3); + + if (check_col(pinfo->cinfo, COL_INFO)) { + col_add_fstr(pinfo->cinfo, COL_INFO, "OUI %s (%s), PID 0x%04X", + bytes_to_str_punct(oui, 3, ':'), + manuf ? manuf : "Unknown", pid); + } + if (tree) { + proto_tree_add_uint_format_value(ieee802a_tree, hf_ieee802a_oui, + tvb, 0, 3, oui[0] << 16 | oui[1] << 8 | oui[2], "%s (%s)", + bytes_to_str_punct(oui, 3, ':'), manuf ? manuf : "Unknown"); + } + + /* + * Do we have information for this OUI? + */ + if (oui_info_table != NULL && + (oui_info = g_hash_table_lookup(oui_info_table, + GUINT_TO_POINTER(oui))) != NULL) { + /* + * Yes - use it. + */ + hf = *oui_info->field_info->p_id; + subdissector_table = oui_info->table; + } else { + /* + * No, use hf_ieee802a_pid for the PID and just dissect + * the payload as data. + */ + hf = hf_ieee802a_pid; + subdissector_table = NULL; + } + if (tree) + proto_tree_add_uint(ieee802a_tree, hf, tvb, 3, 2, pid); + next_tvb = tvb_new_subset_remaining(tvb, 5); + if (subdissector_table != NULL) { + /* do lookup with the subdissector table */ + if (dissector_try_uint(subdissector_table, pid, next_tvb, + pinfo, tree)) + return; + } + call_dissector(data_handle, next_tvb, pinfo, tree); +} + +void +proto_register_ieee802a(void) +{ + static hf_register_info hf[] = { + { &hf_ieee802a_oui, + { "Organization Code", "ieee802a.oui", FT_UINT24, BASE_HEX, + NULL, 0x0, NULL, HFILL }}, + + { &hf_ieee802a_pid, + { "Protocol ID", "ieee802a.pid", FT_UINT16, BASE_HEX, + NULL, 0x0, NULL, HFILL }} + }; + static gint *ett[] = { + &ett_ieee802a, + }; + + proto_ieee802a = proto_register_protocol("IEEE802a OUI Extended Ethertype", "IEEE802a", "ieee802a"); + proto_register_field_array(proto_ieee802a, hf, array_length(hf)); + proto_register_subtree_array(ett, array_length(ett)); +} + +static void +register_hf(gpointer key _U_, gpointer value, gpointer user_data _U_) +{ + oui_info_t *info = value; + + proto_register_field_array(proto_ieee802a, info->field_info, 1); +} + +void +proto_reg_handoff_ieee802a(void) +{ + dissector_handle_t ieee802a_handle; + + data_handle = find_dissector("data"); + + ieee802a_handle = create_dissector_handle(dissect_ieee802a, + proto_ieee802a); + dissector_add_uint("ethertype", ETHERTYPE_IEEE802_OUI_EXTENDED, + ieee802a_handle); + + /* + * Register all the fields for PIDs for various OUIs. + */ + if (oui_info_table != NULL) + g_hash_table_foreach(oui_info_table, register_hf, NULL); +} diff --git a/pool/shard000/C/0011182_verify-tag.c b/pool/shard000/C/0011182_verify-tag.c new file mode 100644 index 0000000000000000000000000000000000000000..986789f706911d122e24b0d784ab193e2ec3b74b --- /dev/null +++ b/pool/shard000/C/0011182_verify-tag.c @@ -0,0 +1,91 @@ +/* + * Builtin "git verify-tag" + * + * Copyright (c) 2007 Carlos Rica + * + * Based on git-verify-tag.sh + */ +#include "cache.h" +#include "builtin.h" +#include "tag.h" +#include "run-command.h" +#include +#include "parse-options.h" +#include "gpg-interface.h" + +static const char * const verify_tag_usage[] = { + "git verify-tag [-v|--verbose] ...", + NULL +}; + +static int run_gpg_verify(const char *buf, unsigned long size, int verbose) +{ + int len; + + len = parse_signature(buf, size); + if (verbose) + write_in_full(1, buf, len); + + if (size == len) + return error("no signature found"); + + return verify_signed_buffer(buf, len, buf + len, size - len, NULL); +} + +static int verify_tag(const char *name, int verbose) +{ + enum object_type type; + unsigned char sha1[20]; + char *buf; + unsigned long size; + int ret; + + if (get_sha1(name, sha1)) + return error("tag '%s' not found.", name); + + type = sha1_object_info(sha1, NULL); + if (type != OBJ_TAG) + return error("%s: cannot verify a non-tag object of type %s.", + name, typename(type)); + + buf = read_sha1_file(sha1, &type, &size); + if (!buf) + return error("%s: unable to read file.", name); + + ret = run_gpg_verify(buf, size, verbose); + + free(buf); + return ret; +} + +static int git_verify_tag_config(const char *var, const char *value, void *cb) +{ + int status = git_gpg_config(var, value, cb); + if (status) + return status; + return git_default_config(var, value, cb); +} + +int cmd_verify_tag(int argc, const char **argv, const char *prefix) +{ + int i = 1, verbose = 0, had_error = 0; + const struct option verify_tag_options[] = { + OPT__VERBOSE(&verbose, "print tag contents"), + OPT_END() + }; + + git_config(git_verify_tag_config, NULL); + + argc = parse_options(argc, argv, prefix, verify_tag_options, + verify_tag_usage, PARSE_OPT_KEEP_ARGV0); + if (argc <= i) + usage_with_options(verify_tag_usage, verify_tag_options); + + /* sometimes the program was terminated because this signal + * was received in the process of writing the gpg input: */ + signal(SIGPIPE, SIG_IGN); + while (i < argc) + if (verify_tag(argv[i++], verbose)) + had_error = 1; + return had_error; +} diff --git a/pool/shard000/C/0011195_filesys.c b/pool/shard000/C/0011195_filesys.c new file mode 100644 index 0000000000000000000000000000000000000000..fd85e5dd06bceb723ebbe5deb6d284c90eebc012 --- /dev/null +++ b/pool/shard000/C/0011195_filesys.c @@ -0,0 +1,299 @@ +/* + libparted - a library for manipulating disk partitions + Copyright (C) 1999-2001, 2007-2012 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 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 + along with this program. If not, see . +*/ + +/** \file filesys.c */ + +/** + * \addtogroup PedFileSystem + * + * \note File systems exist on a PedGeometry - NOT a PedPartition. + * + * @{ + */ + +#include + +#include +#include + +#if ENABLE_NLS +# include +# define _(String) dgettext (PACKAGE, String) +#else +# define _(String) (String) +#endif /* ENABLE_NLS */ + +#define BUFFER_SIZE 4096 /* in sectors */ + +static PedFileSystemType* fs_types = NULL; +static PedFileSystemAlias* fs_aliases = NULL; + +void +ped_file_system_type_register (PedFileSystemType* fs_type) +{ + PED_ASSERT (fs_type != NULL); + PED_ASSERT (fs_type->ops != NULL); + PED_ASSERT (fs_type->name != NULL); + + fs_type->next = fs_types; + fs_types = fs_type; +} + +void +ped_file_system_type_unregister (PedFileSystemType* fs_type) +{ + PedFileSystemType* walk; + PedFileSystemType* last = NULL; + + PED_ASSERT (fs_types != NULL); + PED_ASSERT (fs_type != NULL); + + for (walk = fs_types; walk && walk != fs_type; + last = walk, walk = walk->next); + + PED_ASSERT (walk != NULL); + if (last) + ((struct _PedFileSystemType*) last)->next = fs_type->next; + else + fs_types = fs_type->next; +} + +void +ped_file_system_alias_register (PedFileSystemType* fs_type, const char* alias, + int deprecated) +{ + PedFileSystemAlias* fs_alias; + + PED_ASSERT (fs_type != NULL); + PED_ASSERT (alias != NULL); + + fs_alias = ped_malloc (sizeof *fs_alias); + if (!fs_alias) + return; + + fs_alias->next = fs_aliases; + fs_alias->fs_type = fs_type; + fs_alias->alias = alias; + fs_alias->deprecated = deprecated; + fs_aliases = fs_alias; +} + +void +ped_file_system_alias_unregister (PedFileSystemType* fs_type, + const char* alias) +{ + PedFileSystemAlias* walk; + PedFileSystemAlias* last = NULL; + + PED_ASSERT (fs_aliases != NULL); + PED_ASSERT (fs_type != NULL); + PED_ASSERT (alias != NULL); + + for (walk = fs_aliases; walk; last = walk, walk = walk->next) { + if (walk->fs_type == fs_type && !strcmp (walk->alias, alias)) + break; + } + + PED_ASSERT (walk != NULL); + if (last) + last->next = walk->next; + else + fs_aliases = walk->next; + free (walk); +} + +/** + * Get a PedFileSystemType by its @p name. + * + * @return @c NULL if none found. + */ +PedFileSystemType* +ped_file_system_type_get (const char* name) +{ + PedFileSystemType* walk; + PedFileSystemAlias* alias_walk; + + PED_ASSERT (name != NULL); + + for (walk = fs_types; walk != NULL; walk = walk->next) { + if (!strcasecmp (walk->name, name)) + break; + } + if (walk != NULL) + return walk; + + for (alias_walk = fs_aliases; alias_walk != NULL; + alias_walk = alias_walk->next) { + if (!strcasecmp (alias_walk->alias, name)) + break; + } + if (alias_walk != NULL) { + if (alias_walk->deprecated) + PED_DEBUG (0, "File system alias %s is deprecated", + name); + return alias_walk->fs_type; + } + + return NULL; +} + +/** + * Get the next PedFileSystemType after @p fs_type. + * + * @return @c NULL if @p fs_type is the last item in the list. + */ +PedFileSystemType* +ped_file_system_type_get_next (const PedFileSystemType* fs_type) +{ + if (fs_type) + return fs_type->next; + else + return fs_types; +} + +/** + * Get the next PedFileSystemAlias after @p fs_alias. + * + * @return @c NULL if @p fs_alias is the last item in the list. + */ +PedFileSystemAlias* +ped_file_system_alias_get_next (const PedFileSystemAlias* fs_alias) +{ + if (fs_alias) + return fs_alias->next; + else + return fs_aliases; +} + +/** + * Attempt to find a file system and return the region it occupies. + * + * @param fs_type The file system type to probe for. + * @param geom The region to be searched. + * + * @return @p NULL if @p fs_type file system wasn't detected + */ +PedGeometry* +ped_file_system_probe_specific ( + const PedFileSystemType* fs_type, PedGeometry* geom) +{ + PedGeometry* result; + + PED_ASSERT (fs_type != NULL); + PED_ASSERT (fs_type->ops->probe != NULL); + PED_ASSERT (geom != NULL); + + /* Fail all fs-specific probe-related tests when sector size + is not the default. */ + if (geom->dev->sector_size != PED_SECTOR_SIZE_DEFAULT) + return 0; + + if (!ped_device_open (geom->dev)) + return 0; + result = fs_type->ops->probe (geom); + ped_device_close (geom->dev); + return result; +} + +static int +_geometry_error (const PedGeometry* a, const PedGeometry* b) +{ + PedSector start_delta = a->start - b->start; + PedSector end_delta = a->end - b->end; + + return abs (start_delta) + abs (end_delta); +} + +static PedFileSystemType* +_best_match (const PedGeometry* geom, PedFileSystemType* detected [], + const int detected_error [], int detected_count) +{ + int best_match = 0; + int i; + PedSector min_error; + + min_error = PED_MAX (4096, geom->length / 100); + + for (i = 1; i < detected_count; i++) { + if (detected_error [i] < detected_error [best_match]) + best_match = i; + } + + /* make sure the best match is significantly better than all the + * other matches + */ + for (i = 0; i < detected_count; i++) { + if (i == best_match) + continue; + + if (abs (detected_error [best_match] - detected_error [i]) + < min_error) + return NULL; + } + + return detected [best_match]; +} + + +/** + * Attempt to detect a file system in region \p geom. + * This function tries to be clever at dealing with ambiguous + * situations, such as when one file system was not completely erased before a + * new file system was created on top of it. + * + * \return a new PedFileSystem on success, \c NULL on failure + */ +PedFileSystemType* +ped_file_system_probe (PedGeometry* geom) +{ + PedFileSystemType* detected[32]; + int detected_error[32]; + int detected_count = 0; + PedFileSystemType* walk = NULL; + + PED_ASSERT (geom != NULL); + + if (!ped_device_open (geom->dev)) + return NULL; + + ped_exception_fetch_all (); + while ( (walk = ped_file_system_type_get_next (walk)) ) { + PedGeometry* probed; + + probed = ped_file_system_probe_specific (walk, geom); + if (probed) { + detected [detected_count] = walk; + detected_error [detected_count] + = _geometry_error (geom, probed); + detected_count++; + ped_geometry_destroy (probed); + } else { + ped_exception_catch (); + } + } + ped_exception_leave_all (); + + ped_device_close (geom->dev); + + if (!detected_count) + return NULL; + walk = _best_match (geom, detected, detected_error, detected_count); + if (walk) + return walk; + return NULL; +} diff --git a/pool/shard000/C/0011198_sw-debug.c b/pool/shard000/C/0011198_sw-debug.c new file mode 100644 index 0000000000000000000000000000000000000000..fbd77487aff7157bc720d5e32dd0d4ab5f04fa00 --- /dev/null +++ b/pool/shard000/C/0011198_sw-debug.c @@ -0,0 +1,53 @@ +/* + * libsocialweb - social data store + * Copyright (C) 2009 Intel Corporation. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU Lesser General Public License, + * version 2.1, as published by the Free Software Foundation. + * + * This program is distributed in the hope it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for + * more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include +#include + +#include "sw-debug.h" + +guint sw_debug_flags; + +void +sw_debug_init (const char *string) +{ + static gboolean setup_done = FALSE; + static const GDebugKey keys[] = { + { "main-loop", SW_DEBUG_MAIN_LOOP }, + { "views", SW_DEBUG_VIEWS }, + { "online", SW_DEBUG_ONLINE }, + { "item", SW_DEBUG_ITEM }, + { "contact", SW_DEBUG_CONTACT }, + { "twitter", SW_DEBUG_TWITTER }, + { "lastfm", SW_DEBUG_LASTFM }, + { "core", SW_DEBUG_CORE }, + { "vimeo", SW_DEBUG_VIMEO }, + { "flickr", SW_DEBUG_FLICKR }, + { "smugmug", SW_DEBUG_SMUGMUG }, + { "photobucket", SW_DEBUG_PHOTOBUCKET }, + { "facebook", SW_DEBUG_FACEBOOK }, + { "client-monitor", SW_DEBUG_CLIENT_MONITOR } + }; + + if (G_LIKELY (setup_done)) + return; + + sw_debug_flags = g_parse_debug_string (string, keys, G_N_ELEMENTS (keys)); + + setup_done = TRUE; +} diff --git a/pool/shard000/C/0011206_s_llround.c b/pool/shard000/C/0011206_s_llround.c new file mode 100644 index 0000000000000000000000000000000000000000..483d4a0a4bb642adeb1ef57b2323b48b520077aa --- /dev/null +++ b/pool/shard000/C/0011206_s_llround.c @@ -0,0 +1,82 @@ +/* Round double value to long long int. + Copyright (C) 1997-2015 Free Software Foundation, Inc. + This file is part of the GNU C Library. + Contributed by Ulrich Drepper , 1997. + + The GNU C Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The GNU C Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, see + . */ + +#define lround __hidden_lround +#define __lround __hidden___lround + +#include +#include + +#include + + +long long int +__llround (double x) +{ + int32_t j0; + int64_t i0; + long long int result; + int sign; + + EXTRACT_WORDS64 (i0, x); + j0 = ((i0 >> 52) & 0x7ff) - 0x3ff; + sign = i0 < 0 ? -1 : 1; + i0 &= UINT64_C(0xfffffffffffff); + i0 |= UINT64_C(0x10000000000000); + + if (j0 < (int32_t) (8 * sizeof (long long int)) - 1) + { + if (j0 < 0) + return j0 < -1 ? 0 : sign; + else if (j0 >= 52) + result = i0 << (j0 - 52); + else + { + i0 += UINT64_C(0x8000000000000) >> j0; + + result = i0 >> (52 - j0); + } + } + else + { + /* The number is too large. It is left implementation defined + what happens. */ + return (long long int) x; + } + + return sign * result; +} + +weak_alias (__llround, llround) +#ifdef NO_LONG_DOUBLE +strong_alias (__llround, __llroundl) +weak_alias (__llround, llroundl) +#endif + +/* long has the same width as long long on LP64 machines, so use an alias. */ +#undef lround +#undef __lround +#ifdef _LP64 +strong_alias (__llround, __lround) +weak_alias (__llround, lround) +# ifdef NO_LONG_DOUBLE +strong_alias (__llround, __lroundl) +weak_alias (__llround, lroundl) +# endif +#endif diff --git a/pool/shard000/C/0011209_sniper.c b/pool/shard000/C/0011209_sniper.c new file mode 100644 index 0000000000000000000000000000000000000000..a299f761f96e0606d89a26d8c3d6843937ebfcde --- /dev/null +++ b/pool/shard000/C/0011209_sniper.c @@ -0,0 +1,190 @@ +/* + * LG Optimus Black codename sniper board + * + * Copyright (C) 2015 Paul Kocialkowski + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "sniper.h" + +DECLARE_GLOBAL_DATA_PTR; + +const omap3_sysinfo sysinfo = { + .mtype = DDR_STACKED, + .board_string = "sniper", + .nand_string = "MMC" +}; + +static const struct ns16550_platdata serial_omap_platdata = { + .base = OMAP34XX_UART3, + .reg_shift = 2, + .clock = V_NS16550_CLK, + .fcr = UART_FCR_DEFVAL, +}; + +U_BOOT_DEVICE(sniper_serial) = { + .name = "ns16550_serial", + .platdata = &serial_omap_platdata +}; + +static struct musb_hdrc_config musb_config = { + .multipoint = 1, + .dyn_fifo = 1, + .num_eps = 16, + .ram_bits = 12 +}; + +static struct omap_musb_board_data musb_board_data = { + .interface_type = MUSB_INTERFACE_ULPI, +}; + +static struct musb_hdrc_platform_data musb_platform_data = { + .mode = MUSB_PERIPHERAL, + .config = &musb_config, + .power = 100, + .platform_ops = &omap2430_ops, + .board_data = &musb_board_data, +}; + +void set_muxconf_regs(void) +{ + MUX_SNIPER(); +} + +#ifdef CONFIG_SPL_BUILD +void get_board_mem_timings(struct board_sdrc_timings *timings) +{ + timings->mcfg = HYNIX_V_MCFG_200(256 << 20); + timings->ctrla = HYNIX_V_ACTIMA_200; + timings->ctrlb = HYNIX_V_ACTIMB_200; + timings->rfr_ctrl = SDP_3430_SDRC_RFR_CTRL_200MHz; + timings->mr = MICRON_V_MR_165; +} +#endif + +int board_init(void) +{ + /* GPMC init */ + gpmc_init(); + + /* MACH number */ + gd->bd->bi_arch_number = 3000; + + /* ATAGs location */ + gd->bd->bi_boot_params = OMAP34XX_SDRC_CS0 + 0x100; + + return 0; +} + +int misc_init_r(void) +{ + unsigned char keypad_matrix[64] = { 0 }; + char reboot_mode[2] = { 0 }; + unsigned char keys[3]; + unsigned char data = 0; + int rc; + + /* Power button reset init */ + + twl4030_power_reset_init(); + + /* Keypad */ + + twl4030_keypad_scan((unsigned char *)&keypad_matrix); + + keys[0] = twl4030_keypad_key((unsigned char *)&keypad_matrix, 0, 0); + keys[1] = twl4030_keypad_key((unsigned char *)&keypad_matrix, 0, 1); + keys[2] = twl4030_keypad_key((unsigned char *)&keypad_matrix, 0, 2); + + /* Reboot mode */ + + rc = omap_reboot_mode(reboot_mode, sizeof(reboot_mode)); + + if (keys[0]) + reboot_mode[0] = 'r'; + else if (keys[1]) + reboot_mode[0] = 'b'; + + if (rc < 0 || reboot_mode[0] == 'o') { + /* + * When not rebooting, valid power on reasons are either the + * power button, charger plug or USB plug. + */ + + data |= twl4030_input_power_button(); + data |= twl4030_input_charger(); + data |= twl4030_input_usb(); + + if (!data) + twl4030_power_off(); + } + + if (reboot_mode[0] > 0 && isascii(reboot_mode[0])) { + if (!env_get("reboot-mode")) + env_set("reboot-mode", (char *)reboot_mode); + } + + omap_reboot_mode_clear(); + + /* Serial number */ + + omap_die_id_serial(); + + /* MUSB */ + + musb_register(&musb_platform_data, &musb_board_data, (void *)MUSB_BASE); + + return 0; +} + +u32 get_board_rev(void) +{ + /* Sold devices are expected to be at least revision F. */ + return 6; +} + +void get_board_serial(struct tag_serialnr *serialnr) +{ + omap_die_id_get_board_serial(serialnr); +} + +void reset_misc(void) +{ + char reboot_mode[2] = { 0 }; + + /* + * Valid resets must contain the reboot mode magic, but we must not + * override it when set previously (e.g. reboot to bootloader). + */ + + omap_reboot_mode(reboot_mode, sizeof(reboot_mode)); + omap_reboot_mode_store(reboot_mode); +} + +int fb_set_reboot_flag(void) +{ + return omap_reboot_mode_store("b"); +} + +int board_mmc_init(bd_t *bis) +{ + return omap_mmc_init(1, 0, 0, -1, -1); +} + +void board_mmc_power_init(void) +{ + twl4030_power_mmc_init(1); +} diff --git a/pool/shard000/C/0011217_ixp2800_uart.c b/pool/shard000/C/0011217_ixp2800_uart.c new file mode 100644 index 0000000000000000000000000000000000000000..742a42eca184d3a8beb3d25d8d6867d6c7c98492 --- /dev/null +++ b/pool/shard000/C/0011217_ixp2800_uart.c @@ -0,0 +1,81 @@ +/** + * \file + * \brief The world's simplest serial driver. + */ + +/* + * Copyright (c) 2007, 2008, 2011, ETH Zurich. + * All rights reserved. + * + * This file is distributed under the terms in the attached LICENSE file. + * If you do not find this file, copies can be found by writing to: + * ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group. + */ + +#include +#include + +#include +#include + +/** \brief Initialize uart */ +void ixp2800_uart_init(ixp2800_uart_t *uart, lvaddr_t base) +{ + ixp2800_uart_initialize(uart, (mackerel_addr_t) base); + + ixp2800_uart_LCR_t lcr = ixp2800_uart_LCR_default; + + lcr = ixp2800_uart_LCR_sb_insert(lcr, 0); + lcr = ixp2800_uart_LCR_eps_insert(lcr, 0); + lcr = ixp2800_uart_LCR_pen_insert(lcr, 0); + lcr = ixp2800_uart_LCR_wls_insert(lcr, ixp2800_uart_bits8); + lcr = ixp2800_uart_LCR_stkyp_insert(lcr, 0); + + ixp2800_uart_LCR_wr(uart, lcr); + + + //Mask all interrupts + ixp2800_uart_IER_t ier = ixp2800_uart_IER_default; + + ier = ixp2800_uart_IER_ravie_insert(ier, 0); + ier = ixp2800_uart_IER_tie_insert(ier, 0); + ier = ixp2800_uart_IER_rlse_insert(ier, 0); + ier = ixp2800_uart_IER_rtoie_insert(ier, 0); + ier = ixp2800_uart_IER_nrze_insert(ier, 0); + ier = ixp2800_uart_IER_uue_insert(ier, 1); + + ixp2800_uart_IER_wr(uart, ier); + + + //Check current baud rate setting + + //Set DLAB to high to access the divisor + ixp2800_uart_LCR_dlab_wrf(uart, 1); + + //Reset DLAB to low + ixp2800_uart_LCR_dlab_wrf(uart, 0); + +} + +/** \brief Prints a single character to the default serial port. */ +void ixp2800_putchar(ixp2800_uart_t *uart, char c) +{ + while(ixp2800_uart_LSR_tdrq_rdf(uart) == 0){ } //Spin until data transmission request + + ixp2800_uart_THR_thr_wrf(uart, c); +} + +/** \brief Reads a single character from the default serial port. + * This function spins waiting for a character to arrive. + */ +char ixp2800_getchar(ixp2800_uart_t *uart) +{ + char c; + + while (ixp2800_uart_LSR_dr_rdf(uart) == 0){ } //Spin until character is ready + + c = (char) ixp2800_uart_RBR_rbr_rdf(uart); + + return c; + +} diff --git a/pool/shard000/C/0011218_dbus-automount.c b/pool/shard000/C/0011218_dbus-automount.c new file mode 100644 index 0000000000000000000000000000000000000000..70b85d8023ff0bf0593b7908693d8be8ee3a3d77 --- /dev/null +++ b/pool/shard000/C/0011218_dbus-automount.c @@ -0,0 +1,64 @@ +/* SPDX-License-Identifier: LGPL-2.1+ */ + +#include "automount.h" +#include "bus-get-properties.h" +#include "dbus-automount.h" +#include "dbus-util.h" +#include "string-util.h" + +static BUS_DEFINE_PROPERTY_GET_ENUM(property_get_result, automount_result, AutomountResult); + +const sd_bus_vtable bus_automount_vtable[] = { + SD_BUS_VTABLE_START(0), + SD_BUS_PROPERTY("Where", "s", NULL, offsetof(Automount, where), SD_BUS_VTABLE_PROPERTY_CONST), + SD_BUS_PROPERTY("DirectoryMode", "u", bus_property_get_mode, offsetof(Automount, directory_mode), SD_BUS_VTABLE_PROPERTY_CONST), + SD_BUS_PROPERTY("Result", "s", property_get_result, offsetof(Automount, result), SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE), + SD_BUS_PROPERTY("TimeoutIdleUSec", "t", bus_property_get_usec, offsetof(Automount, timeout_idle_usec), SD_BUS_VTABLE_PROPERTY_CONST), + SD_BUS_VTABLE_END +}; + +static int bus_automount_set_transient_property( + Automount *a, + const char *name, + sd_bus_message *message, + UnitWriteFlags flags, + sd_bus_error *error) { + + Unit *u = UNIT(a); + + assert(a); + assert(name); + assert(message); + + flags |= UNIT_PRIVATE; + + if (streq(name, "Where")) + return bus_set_transient_path(u, name, &a->where, message, flags, error); + + if (streq(name, "TimeoutIdleUSec")) + return bus_set_transient_usec_fix_0(u, name, &a->timeout_idle_usec, message, flags, error); + + if (streq(name, "DirectoryMode")) + return bus_set_transient_mode_t(u, name, &a->directory_mode, message, flags, error); + + return 0; +} + +int bus_automount_set_property( + Unit *u, + const char *name, + sd_bus_message *message, + UnitWriteFlags flags, + sd_bus_error *error) { + + Automount *a = AUTOMOUNT(u); + + assert(a); + assert(name); + assert(message); + + if (u->transient && u->load_state == UNIT_STUB) /* This is a transient unit? let's load a little more */ + return bus_automount_set_transient_property(a, name, message, flags, error); + + return 0; +} diff --git a/pool/shard000/C/0011228_vf_hue.c b/pool/shard000/C/0011228_vf_hue.c new file mode 100644 index 0000000000000000000000000000000000000000..ec74c526326815d7844addc750d21cfc367f87b1 --- /dev/null +++ b/pool/shard000/C/0011228_vf_hue.c @@ -0,0 +1,183 @@ +#include +#include +#include +#include +#include + +#include "config.h" +#include "mp_msg.h" +#include "cpudetect.h" + +#include "img_format.h" +#include "mp_image.h" +#include "vf.h" + +#include "libvo/video_out.h" + +#include "m_option.h" +#include "m_struct.h" + +static struct vf_priv_s { + uint8_t *buf[2]; + float hue; + float saturation; +} const vf_priv_dflt = { + {NULL, NULL}, + 0.0, + 1.0, +}; + +static void process_C(uint8_t *udst, uint8_t *vdst, uint8_t *usrc, uint8_t *vsrc, int dststride, int srcstride, + int w, int h, float hue, float sat) +{ + int i; + const int s= rint(sin(hue) * (1<<16) * sat); + const int c= rint(cos(hue) * (1<<16) * sat); + + while (h--) { + for (i = 0; i>16; + int new_v= (s*u + c*v + (1<<15) + (128<<16))>>16; + if(new_u & 768) new_u= (-new_u)>>31; + if(new_v & 768) new_v= (-new_v)>>31; + udst[i]= new_u; + vdst[i]= new_v; + } + usrc += srcstride; + vsrc += srcstride; + udst += dststride; + vdst += dststride; + } +} + +static void (*process)(uint8_t *udst, uint8_t *vdst, uint8_t *usrc, uint8_t *vsrc, int dststride, int srcstride, + int w, int h, float hue, float sat); + +/* FIXME: add packed yuv version of process */ + +static int put_image(struct vf_instance_s* vf, mp_image_t *mpi, double pts) +{ + mp_image_t *dmpi; + + dmpi=vf_get_image(vf->next, mpi->imgfmt, + MP_IMGTYPE_EXPORT, 0, + mpi->w, mpi->h); + + dmpi->planes[0] = mpi->planes[0]; + dmpi->stride[0] = mpi->stride[0]; + dmpi->stride[1] = mpi->stride[1]; + dmpi->stride[2] = mpi->stride[2]; + + if (!vf->priv->buf[0]){ + vf->priv->buf[0] = malloc(mpi->stride[1]*mpi->h >> mpi->chroma_y_shift); + vf->priv->buf[1] = malloc(mpi->stride[2]*mpi->h >> mpi->chroma_y_shift); + } + + if (vf->priv->hue == 0 && vf->priv->saturation == 1){ + dmpi->planes[1] = mpi->planes[1]; + dmpi->planes[2] = mpi->planes[2]; + }else { + dmpi->planes[1] = vf->priv->buf[0]; + dmpi->planes[2] = vf->priv->buf[1]; + process(dmpi->planes[1], dmpi->planes[2], + mpi->planes[1], mpi->planes[2], + dmpi->stride[1],mpi->stride[1], + mpi->w>> mpi->chroma_x_shift, mpi->h>> mpi->chroma_y_shift, + vf->priv->hue, vf->priv->saturation); + } + + return vf_next_put_image(vf,dmpi, pts); +} + +static int control(struct vf_instance_s* vf, int request, void* data) +{ + vf_equalizer_t *eq; + + switch (request) { + case VFCTRL_SET_EQUALIZER: + eq = data; + if (!strcmp(eq->item,"hue")) { + vf->priv->hue = eq->value * M_PI / 100; + return CONTROL_TRUE; + } else if (!strcmp(eq->item,"saturation")) { + vf->priv->saturation = (eq->value + 100)/100.0; + return CONTROL_TRUE; + } + break; + case VFCTRL_GET_EQUALIZER: + eq = data; + if (!strcmp(eq->item,"hue")) { + eq->value = rint(vf->priv->hue *100 / M_PI); + return CONTROL_TRUE; + }else if (!strcmp(eq->item,"saturation")) { + eq->value = rint(vf->priv->saturation*100 - 100); + return CONTROL_TRUE; + } + break; + } + return vf_next_control(vf, request, data); +} + +static int query_format(struct vf_instance_s* vf, unsigned int fmt) +{ + switch (fmt) { + case IMGFMT_YVU9: + case IMGFMT_IF09: + case IMGFMT_YV12: + case IMGFMT_I420: + case IMGFMT_IYUV: + case IMGFMT_CLPL: + case IMGFMT_444P: + case IMGFMT_422P: + case IMGFMT_411P: + return vf_next_query_format(vf, fmt); + } + return 0; +} + +static void uninit(struct vf_instance_s* vf) +{ + if (vf->priv->buf[0]) free(vf->priv->buf[0]); + if (vf->priv->buf[1]) free(vf->priv->buf[1]); + free(vf->priv); +} + +static int open(vf_instance_t *vf, char* args) +{ + vf->control=control; + vf->query_format=query_format; + vf->put_image=put_image; + vf->uninit=uninit; + + vf->priv->hue *= M_PI / 180.0; + + process = process_C; + return 1; +} + +#define ST_OFF(f) M_ST_OFF(struct vf_priv_s,f) +static m_option_t vf_opts_fields[] = { + {"hue", ST_OFF(hue), CONF_TYPE_FLOAT, M_OPT_RANGE,-180.0 ,180.0, NULL}, + {"saturation", ST_OFF(saturation), CONF_TYPE_FLOAT, M_OPT_RANGE,-10.0 ,10.0, NULL}, + { NULL, NULL, 0, 0, 0, 0, NULL } +}; + +static m_struct_t vf_opts = { + "hue", + sizeof(struct vf_priv_s), + &vf_priv_dflt, + vf_opts_fields +}; + +const vf_info_t vf_info_hue = { + "hue changer", + "hue", + "Michael Niedermayer", + "", + open, + &vf_opts +}; + diff --git a/pool/shard000/C/0011231_envelope.c b/pool/shard000/C/0011231_envelope.c new file mode 100644 index 0000000000000000000000000000000000000000..8f32f0019e04aafeb1b79be3e1561f7b763000a4 --- /dev/null +++ b/pool/shard000/C/0011231_envelope.c @@ -0,0 +1,281 @@ +/** + * libfreeztile + * + * Copyright (C) 2012 Henrik Hedelund (henke.hedelund@gmail.com) + * + * This file is part of libfreeztile. + * + * libfreeztile 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. + * + * libfreeztile 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 libfreeztile. If not, see . + * + * @category libfreeztile + * @package libfreeztile + * @author Henrik Hedelund + * @copyright 2012 Henrik Hedelund (henke.hedelund@gmail.com) + * @license http://www.gnu.org/licenses/gpl.html GNU GPL + * @link freeztile.org + */ + +#include "envelope.h" +#include "../freeztile.h" +#include "../form.h" +#include "../util/list.h" + +static +fz_ptr_t +_fz_envdesc_construct(fz_ptr_t self, + va_list *args) +{ + (void) args; + fz_envdesc_t *_self = (fz_envdesc_t*) self; + fz_uint_t i; + + for (i = 0; i < 4; ++i) { + _self->durations[i] = 0; + _self->forms[i] = fz_new(fz_form); + fz_list_clear(_self->forms[i]->template, 1024); //FIXME: Default resolution + } + + return _self; +} + +static +fz_ptr_t +_fz_envdesc_destruct(fz_ptr_t self) +{ + fz_envdesc_t *_self = (fz_envdesc_t*) self; + + fz_uint_t i = 0; + for (; i < 4; ++i) { + fz_release(_self->forms[i]); + } + + return _self; +} + +static +fz_result_t +_fz_envelope_produce( + fz_producer_t *self, + fz_list_t *buffer) +{ + fz_envelope_t *_self = (fz_envelope_t*) self; + fz_form_t *curve; + fz_uint_t i; + fz_uint_t frame; + fz_amp_t amp; + + if (_self->state == FZ_ENV_SILENT || _self->descriptor == NULL) { + return fz_list_size(buffer); + } + + curve = _self->descriptor->forms[_self->state]; + + for (i = 0; i < fz_list_size(buffer); ++i, ++_self->frame) { + if (_self->frame >= _self->descriptor->durations[_self->state]) { + switch (_self->state) { + case FZ_ENV_SUSTAIN: + amp = fz_list_size(curve->template) > 0 ? + fz_list_val(curve->template, + fz_list_size(curve->template) - 1, fz_amp_t) + : + (i > 0 ? fz_list_val(buffer, i - 1, fz_amp_t) : 0.0); + for (; i < fz_list_size(buffer); ++i) { + fz_list_val(buffer, i, fz_amp_t) = amp; + } + break; + case FZ_ENV_RELEASE: + for (; i < fz_list_size(buffer); ++i) { + fz_list_val(buffer, i, fz_amp_t) = 0.0; + } + _self->state = FZ_ENV_SILENT; + break; + default: + curve = _self->descriptor->forms[++_self->state]; + _self->frame = 0; + break; + } + } + + if (i == fz_list_size(buffer)) { + break; + } + + frame = (fz_uint_t) ((((fz_real_t) _self->frame) / + _self->descriptor->durations[_self->state]) * + fz_list_size(curve->template)); + + if (frame == fz_list_size(curve->template)) { + if (fz_list_size(curve->template) > 0) { + --frame; + } else { + continue; + } + } + + fz_list_val(buffer, i, fz_amp_t) += + fz_list_val(curve->template, frame, fz_amp_t); + + if (_self->state == FZ_ENV_RELEASE) { + if (_self->frame == 0 && fz_list_val(buffer, i, fz_amp_t) > 0) { + _self->factor /= fz_list_val(buffer, i, fz_amp_t); + } + fz_list_val(buffer, i, fz_amp_t) *= _self->factor; + } + } + + if (fz_list_size(buffer) > 0 && _self->state != FZ_ENV_RELEASE) { + _self->factor = fz_list_val(buffer, i - 1, fz_amp_t); + } + + return fz_list_size(buffer); +} + +static +fz_ptr_t +_fz_envelope_construct(fz_ptr_t self, + va_list *args) +{ + fz_envelope_t *_self = (fz_envelope_t*) + ((const fz_object_t*) fz_producer) + ->construct(self, args); + _fz_producer_init(_self, _fz_envelope_produce, NULL); + _self->descriptor = va_arg(*args, fz_envdesc_t*); + _self->state = FZ_ENV_SILENT; + _self->frame = 0; + _self->factor = 1.0; + + if (_self->descriptor) { + fz_retain(_self->descriptor); + } + + return _self; +} + +static +fz_ptr_t +_fz_envelope_destruct(fz_ptr_t self) +{ + fz_envelope_t *_self = (fz_envelope_t*) self; + if (_self->descriptor != NULL) { + fz_release(_self->descriptor); + } + return ((const fz_object_t*) fz_producer)->destruct(_self); +} + +static const fz_object_t _fz_envdesc = { + sizeof (fz_envdesc_t), + _fz_envdesc_construct, + _fz_envdesc_destruct, + NULL, + NULL +}; + +static const fz_object_t _fz_envelope = { + sizeof (fz_envelope_t), + _fz_envelope_construct, + _fz_envelope_destruct, + NULL, + NULL +}; + +const fz_ptr_t fz_envdesc = (const fz_ptr_t) &_fz_envdesc; +const fz_ptr_t fz_envelope = (const fz_ptr_t) &_fz_envelope; + +void +fz_envelope_attack(fz_envelope_t *envelope) +{ + envelope->frame = 0; + envelope->state = FZ_ENV_ATTACK; +} + +void +fz_envelope_release(fz_envelope_t *envelope) +{ + envelope->frame = 0; + envelope->state = FZ_ENV_RELEASE; +} + +fz_result_t +fz_envelope_set_adsr_curve( + fz_envdesc_t *descriptor, + fz_curve_t *curve, + fz_int_t state) +{ + fz_result_t err; + + if (state < 0 || state > 3) { + return FZ_RESULT_INVALID_ARG; + } + + err = fz_curve_render(curve, descriptor->forms[state]); + if (err != FZ_RESULT_SUCCESS) { + return err; + } + + return FZ_RESULT_SUCCESS; +} + +fz_result_t +fz_envelope_set_adsr( + fz_envdesc_t *descriptor, + fz_amp_t al, + fz_uint_t ad, + fz_amp_t dl, + fz_uint_t dd, + fz_amp_t sl, + fz_uint_t sd, + fz_uint_t rd) +{ + // FZ_ENV_ATTACK + fz_curve_t attack = { + .start = 0, + .a = {.x = 0, .y = 0}, + .b = {.x = 1., .y = al}, + .end = al + }; + fz_envelope_set_adsr_curve(descriptor, &attack, FZ_ENV_ATTACK); + descriptor->durations[FZ_ENV_ATTACK] = ad; + + // FZ_ENV_DECAY + fz_curve_t decay = { + .start = al, + .a = {.x = 0, .y = al}, + .b = {.x = 1., .y = dl}, + .end = dl + }; + fz_envelope_set_adsr_curve(descriptor, &decay, FZ_ENV_DECAY); + descriptor->durations[FZ_ENV_DECAY] = dd; + + // FZ_ENV_SUSTAIN + fz_curve_t sustain = { + .start = dl, + .a = {.x = 0, .y = dl}, + .b = {.x = 1., .y = sl}, + .end = sl + }; + fz_envelope_set_adsr_curve(descriptor, &sustain, FZ_ENV_SUSTAIN); + descriptor->durations[FZ_ENV_SUSTAIN] = sd; + + // FZ_ENV_RELEASE + fz_curve_t release = { + .start = sl, + .a = {.x = 0, .y = sl}, + .b = {.x = 1., .y = 0}, + .end = 0 + }; + fz_envelope_set_adsr_curve(descriptor, &release, FZ_ENV_RELEASE); + descriptor->durations[FZ_ENV_RELEASE] = rd; + + return FZ_RESULT_SUCCESS; +} diff --git a/pool/shard000/C/0011233_irq-ns921x.c b/pool/shard000/C/0011233_irq-ns921x.c new file mode 100644 index 0000000000000000000000000000000000000000..1937d574a0e35870a3688fc5ff09b7c4b6cc4d12 --- /dev/null +++ b/pool/shard000/C/0011233_irq-ns921x.c @@ -0,0 +1,57 @@ +/* + * arch/arm/mach-ns9xxx/irq-ns921x.c + * + * Copyright (C) 2008 by Digi International Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 as published by + * the Free Software Foundation. + */ +#include +#include +#include +#include +#include + +#include "processor-ns921x.h" + +static const u32 ns921x_irq2powermask[] = { + [IRQ_NS9XXX_ETHRX] = SYS_POWER_ETH, + [IRQ_NS921X_UARTA] = SYS_POWER_UARTA, + [IRQ_NS921X_UARTB] = SYS_POWER_UARTB, + [IRQ_NS921X_UARTC] = SYS_POWER_UARTC, + [IRQ_NS921X_UARTD] = SYS_POWER_UARTD, + [IRQ_NS921X_SPI] = SYS_POWER_SPI, + [IRQ_NS921X_I2C] = SYS_POWER_I2C, + [IRQ_NS9215_RTC] = SYS_POWER_RTC, + [IRQ_NS9XXX_EXT0] = SYS_POWER_EXTIRQ0, + [IRQ_NS9XXX_EXT1] = SYS_POWER_EXTIRQ1, + [IRQ_NS9XXX_EXT2] = SYS_POWER_EXTIRQ2, + [IRQ_NS9XXX_EXT3] = SYS_POWER_EXTIRQ3, +}; + +int ns921x_set_wake_irq(unsigned int irq, unsigned int on) +{ + unsigned long flags; + u32 power; + + if (irq > ARRAY_SIZE(ns921x_irq2powermask) || + !ns921x_irq2powermask[irq]) + return -ENOENT; + + local_irq_save(flags); + + power = __raw_readl(SYS_POWER); + + if (on) + power |= ns921x_irq2powermask[irq]; + else + power &= ~ns921x_irq2powermask[irq]; + + __raw_writel(power, SYS_POWER); + + local_irq_restore(flags); + + return 0; +} diff --git a/pool/shard000/C/0011235_mt_hotplug_strategy_core.c b/pool/shard000/C/0011235_mt_hotplug_strategy_core.c new file mode 100644 index 0000000000000000000000000000000000000000..520b8b0a7f864ca911dbbf148cfe13e684d92ab7 --- /dev/null +++ b/pool/shard000/C/0011235_mt_hotplug_strategy_core.c @@ -0,0 +1,190 @@ +/** +* @file mt_hotplug_strategy_core.c +* @brief hotplug strategy(hps) - core +*/ + +/*============================================================================*/ +// Include files +/*============================================================================*/ +// system includes +#include //printk +#include //MODULE_DESCRIPTION, MODULE_LICENSE +#include //module_init, module_exit +#include //cpu_up +#include //kthread_create +#include //wake_lock_init +#include //BUG_ON + +// project includes +#include +#include +#include + +// local includes +#include + +// forward references + +/*============================================================================*/ +// Macro definition +/*============================================================================*/ +/* + * static + */ +#define STATIC +//#define STATIC static + +/* + * config + */ + +/*============================================================================*/ +// Local type definition +/*============================================================================*/ + +/*============================================================================*/ +// Local function declarition +/*============================================================================*/ + +/*============================================================================*/ +// Local variable definition +/*============================================================================*/ + +/*============================================================================*/ +// Global variable definition +/*============================================================================*/ + +/*============================================================================*/ +// Local function definition +/*============================================================================*/ +/* + * hps task main loop + */ +static int _hps_task_main(void *data) +{ + int cnt = 0; + void (*algo_func_ptr)(void); + + hps_ctxt_print_basic(1); + + if (hps_ctxt.is_hmp) + algo_func_ptr = hps_algo_hmp; + else + algo_func_ptr = hps_algo_smp; + + while (1) + { + //TODO: showld we do dvfs? + //struct cpufreq_policy *policy; + //policy = cpufreq_cpu_get(0); + //dbs_freq_increase(policy, policy->max); + //cpufreq_cpu_put(policy); + + (*algo_func_ptr)(); + + //hps_debug("before schedule, cnt:%08d\n", cnt++); + if(hps_ctxt.state == STATE_EARLY_SUSPEND) + wait_event_timeout(hps_ctxt.wait_queue, atomic_read(&hps_ctxt.is_ondemand) != 0, msecs_to_jiffies(HPS_TIMER_INTERVAL_MS*4)); + else + wait_event_timeout(hps_ctxt.wait_queue, atomic_read(&hps_ctxt.is_ondemand) != 0, msecs_to_jiffies(HPS_TIMER_INTERVAL_MS)); + + //hps_debug("after schedule, cnt:%08d\n", cnt++); + + if (kthread_should_stop()) + break; + } //while(1) + + hps_warn("leave _hps_task_main, cnt:%08d\n", cnt++); + return 0; +} + +/*============================================================================*/ +// Gobal function definition +/*============================================================================*/ +/* + * hps task control interface + */ +int hps_task_start(void) +{ + struct sched_param param = { .sched_priority = HPS_TASK_PRIORITY }; + + if (hps_ctxt.tsk_struct_ptr == NULL) + { + hps_ctxt.tsk_struct_ptr = kthread_create(_hps_task_main, NULL, "hps_main"); + if (IS_ERR(hps_ctxt.tsk_struct_ptr)) + return PTR_ERR(hps_ctxt.tsk_struct_ptr); + + sched_setscheduler_nocheck(hps_ctxt.tsk_struct_ptr, SCHED_FIFO, ¶m); + get_task_struct(hps_ctxt.tsk_struct_ptr); + wake_up_process(hps_ctxt.tsk_struct_ptr); + hps_warn("hps_task_start success, ptr: %p, pid: %d\n", hps_ctxt.tsk_struct_ptr, hps_ctxt.tsk_struct_ptr->pid); + } + else + { + hps_warn("hps task already exist, ptr: %p, pid: %d\n", hps_ctxt.tsk_struct_ptr, hps_ctxt.tsk_struct_ptr->pid); + } + + return 0; +} + +void hps_task_stop(void) +{ + if (hps_ctxt.tsk_struct_ptr) + { + kthread_stop(hps_ctxt.tsk_struct_ptr); + put_task_struct(hps_ctxt.tsk_struct_ptr); + hps_ctxt.tsk_struct_ptr = NULL; + } +} + +void hps_task_wakeup_nolock(void) +{ + if (hps_ctxt.tsk_struct_ptr) + { + atomic_set(&hps_ctxt.is_ondemand, 1); + wake_up(&hps_ctxt.wait_queue); + } +} + +void hps_task_wakeup(void) +{ + mutex_lock(&hps_ctxt.lock); + + hps_task_wakeup_nolock(); + + mutex_unlock(&hps_ctxt.lock); +} + +/* + * init + */ +int hps_core_init(void) +{ + int r = 0; + + hps_warn("hps_core_init\n"); + + //init and start task + r = hps_task_start(); + if (r) + { + hps_error("hps_task_start fail(%d)\n", r); + return r; + } + + return r; +} + +/* + * deinit + */ +int hps_core_deinit(void) +{ + int r = 0; + + hps_warn("hps_core_deinit\n"); + + hps_task_stop(); + + return r; +} diff --git a/pool/shard000/C/0011238_torture_knownhosts.c b/pool/shard000/C/0011238_torture_knownhosts.c new file mode 100644 index 0000000000000000000000000000000000000000..7c716b8da49a3cbf65058c06b4eaac9f963ef924 --- /dev/null +++ b/pool/shard000/C/0011238_torture_knownhosts.c @@ -0,0 +1,108 @@ +/* + * This file is part of the SSH Library + * + * Copyright (c) 2010 by Aris Adamantiadis + * + * The SSH Library is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation; either version 2.1 of the License, or (at your + * option) any later version. + * + * The SSH Library is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public + * License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with the SSH Library; see the file COPYING. If not, write to + * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, + * MA 02111-1307, USA. + */ + +#define LIBSSH_STATIC + +#include "torture.h" +#include "session.c" + +#define KNOWNHOSTFILES "libssh_torture_knownhosts" + +static void setup(void **state) { + int verbosity=torture_libssh_verbosity(); + ssh_session session = ssh_new(); + + ssh_options_set(session, SSH_OPTIONS_LOG_VERBOSITY, &verbosity); + + *state = session; +} + +static void teardown(void **state) { + ssh_session session = *state; + + ssh_disconnect(session); + ssh_free(session); + + unlink(KNOWNHOSTFILES); +} + +static void torture_knownhosts_port(void **state) { + ssh_session session = *state; + char buffer[200]; + char *p; + FILE *file; + int rc; + + /* Connect to localhost:22, force the port to 1234 and then write + * the known hosts file. Then check that the entry written is + * [localhost]:1234 + */ + rc = ssh_options_set(session, SSH_OPTIONS_HOST, "localhost"); + assert_true(rc == SSH_OK); + + rc = ssh_options_set(session, SSH_OPTIONS_KNOWNHOSTS, KNOWNHOSTFILES); + assert_true(rc == SSH_OK); + + rc = ssh_connect(session); + assert_true(rc==SSH_OK); + + session->port = 1234; + rc = ssh_write_knownhost(session); + assert_true(rc == SSH_OK); + + file = fopen(KNOWNHOSTFILES, "r"); + assert_true(file != NULL); + p = fgets(buffer, sizeof(buffer), file); + assert_false(p == NULL); + fclose(file); + buffer[sizeof(buffer) - 1] = '\0'; + assert_true(strstr(buffer,"[localhost]:1234 ") != NULL); + + ssh_disconnect(session); + ssh_free(session); + + /* Now, connect back to the ssh server and verify the known host line */ + *state = session = ssh_new(); + + ssh_options_set(session, SSH_OPTIONS_HOST, "localhost"); + ssh_options_set(session, SSH_OPTIONS_KNOWNHOSTS, KNOWNHOSTFILES); + + rc = ssh_connect(session); + assert_true(rc == SSH_OK); + + session->port = 1234; + rc = ssh_is_server_known(session); + assert_true(rc == SSH_SERVER_KNOWN_OK); +} + +int torture_run_tests(void) { + int rc; + const UnitTest tests[] = { + unit_test_setup_teardown(torture_knownhosts_port, setup, teardown), + }; + + ssh_init(); + + rc = run_tests(tests); + + ssh_finalize(); + return rc; +} diff --git a/pool/shard000/C/0011259_othercmd.c b/pool/shard000/C/0011259_othercmd.c new file mode 100644 index 0000000000000000000000000000000000000000..f4417dc0a868038a8ccb09164f82a117308d534a --- /dev/null +++ b/pool/shard000/C/0011259_othercmd.c @@ -0,0 +1,97 @@ +/*------------------------------------------------------------------------ + * + * Copyright (c) 1997-1998 by Cornell University. + * + * See the file "license.txt" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + *------------------------------------------------------------------------ + */ +#include "tclDvmMpeg.h" + + +int +MpegAnyHdrFindCmd(cd, interp, argc, argv) + ClientData cd; + Tcl_Interp *interp; + int argc; + char *argv[]; +{ + BitParser *bp; + int len; + + ReturnErrorIf1(argc != 2, + "wrong # args: should be %s bitParser", argv[0]); + bp = GetBitParser(argv[1]); + ReturnErrorIf2(bp == NULL, + "%s: no such bit parser %s", argv[0], argv[1]); + len = MpegAnyHdrFind(bp); + sprintf(interp->result, "%d", len); + + return TCL_OK; +} + +int +MpegSeqEndCodeEncodeCmd(cd, interp, argc, argv) + ClientData cd; + Tcl_Interp *interp; + int argc; + char *argv[]; +{ + BitParser *bp; + + ReturnErrorIf1(argc != 2, + "wrong # args: should be %s bitParser", argv[0]); + bp = GetBitParser(argv[1]); + ReturnErrorIf2(bp == NULL, + "%s: no such bit parser %s", argv[0], argv[1]); + MpegSeqEndCodeEncode(bp); + + return TCL_OK; +} + + +int +MpegGetCurrStartCodeCmd(cd, interp, argc, argv) + ClientData cd; + Tcl_Interp *interp; + int argc; + char *argv[]; +{ + BitParser *bp; + int code; + + ReturnErrorIf1(argc != 2, + "wrong # args: should be %s bitParser", argv[0]); + bp = GetBitParser(argv[1]); + ReturnErrorIf2(bp == NULL, + "%s: no such bit parser %s", argv[0], argv[1]); + code = MpegGetCurrStartCode(bp); + + if (code == GOP_START_CODE) { + sprintf(interp->result, "gop-start-code"); + } else if (code == PIC_START_CODE) { + sprintf(interp->result, "pic-start-code"); + } else if (code == SEQ_START_CODE) { + sprintf(interp->result, "seq-start-code"); + } else if (code == SEQ_END_CODE) { + sprintf(interp->result, "seq-end-code"); + } else if (code == SYS_START_CODE) { + sprintf(interp->result, "sys-start-code"); + } else if (code == ISO_11172_END_CODE) { + sprintf(interp->result, "sys-end-code"); + } else if (code == PACK_START_CODE) { + sprintf(interp->result, "pack-start-code"); + } else if (code >= SLICE_MIN_START_CODE && + code <= SLICE_MAX_START_CODE) { + sprintf(interp->result, "slice-start-code"); + } else if (code >= PACKET_MIN_START_CODE && + code <= PACKET_MAX_START_CODE) { + sprintf(interp->result, "packet-start-code"); + } else if ((code & 0xFFF00000) == 0xFFF00000) { + sprintf(interp->result, "audio-start-code"); + } else { + sprintf(interp->result, "unknown"); + } + return TCL_OK; +} diff --git a/pool/shard000/C/0011267_arm_ssp_per_task_plugin.c b/pool/shard000/C/0011267_arm_ssp_per_task_plugin.c new file mode 100644 index 0000000000000000000000000000000000000000..89c47f57d1ce14476ca7c2638e89e31926c3d7fb --- /dev/null +++ b/pool/shard000/C/0011267_arm_ssp_per_task_plugin.c @@ -0,0 +1,122 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include "gcc-common.h" + +__visible int plugin_is_GPL_compatible; + +static unsigned int sp_mask, canary_offset; + +static unsigned int arm_pertask_ssp_rtl_execute(void) +{ + rtx_insn *insn; + + for (insn = get_insns(); insn; insn = NEXT_INSN(insn)) { + const char *sym; + rtx body; + rtx mask, masked_sp; + + /* + * Find a SET insn involving a SYMBOL_REF to __stack_chk_guard + */ + if (!INSN_P(insn)) + continue; + body = PATTERN(insn); + if (GET_CODE(body) != SET || + GET_CODE(SET_SRC(body)) != SYMBOL_REF) + continue; + sym = XSTR(SET_SRC(body), 0); + if (strcmp(sym, "__stack_chk_guard")) + continue; + + /* + * Replace the source of the SET insn with an expression that + * produces the address of the copy of the stack canary value + * stored in struct thread_info + */ + mask = GEN_INT(sext_hwi(sp_mask, GET_MODE_PRECISION(Pmode))); + masked_sp = gen_reg_rtx(Pmode); + + emit_insn_before(gen_rtx_SET(masked_sp, + gen_rtx_AND(Pmode, + stack_pointer_rtx, + mask)), + insn); + + SET_SRC(body) = gen_rtx_PLUS(Pmode, masked_sp, + GEN_INT(canary_offset)); + } + return 0; +} + +#define PASS_NAME arm_pertask_ssp_rtl + +#define NO_GATE +#include "gcc-generate-rtl-pass.h" + +#if BUILDING_GCC_VERSION >= 9000 +static bool no(void) +{ + return false; +} + +static void arm_pertask_ssp_start_unit(void *gcc_data, void *user_data) +{ + targetm.have_stack_protect_combined_set = no; + targetm.have_stack_protect_combined_test = no; +} +#endif + +__visible int plugin_init(struct plugin_name_args *plugin_info, + struct plugin_gcc_version *version) +{ + const char * const plugin_name = plugin_info->base_name; + const int argc = plugin_info->argc; + const struct plugin_argument *argv = plugin_info->argv; + int tso = 0; + int i; + + if (!plugin_default_version_check(version, &gcc_version)) { + error(G_("incompatible gcc/plugin versions")); + return 1; + } + + for (i = 0; i < argc; ++i) { + if (!strcmp(argv[i].key, "disable")) + return 0; + + /* all remaining options require a value */ + if (!argv[i].value) { + error(G_("no value supplied for option '-fplugin-arg-%s-%s'"), + plugin_name, argv[i].key); + return 1; + } + + if (!strcmp(argv[i].key, "tso")) { + tso = atoi(argv[i].value); + continue; + } + + if (!strcmp(argv[i].key, "offset")) { + canary_offset = atoi(argv[i].value); + continue; + } + error(G_("unknown option '-fplugin-arg-%s-%s'"), + plugin_name, argv[i].key); + return 1; + } + + /* create the mask that produces the base of the stack */ + sp_mask = ~((1U << (12 + tso)) - 1); + + PASS_INFO(arm_pertask_ssp_rtl, "expand", 1, PASS_POS_INSERT_AFTER); + + register_callback(plugin_info->base_name, PLUGIN_PASS_MANAGER_SETUP, + NULL, &arm_pertask_ssp_rtl_pass_info); + +#if BUILDING_GCC_VERSION >= 9000 + register_callback(plugin_info->base_name, PLUGIN_START_UNIT, + arm_pertask_ssp_start_unit, NULL); +#endif + + return 0; +} diff --git a/pool/shard000/C/0011280_ns16550.c b/pool/shard000/C/0011280_ns16550.c new file mode 100644 index 0000000000000000000000000000000000000000..b965f5bc1d71a233d633e03cd0a87289657925d1 --- /dev/null +++ b/pool/shard000/C/0011280_ns16550.c @@ -0,0 +1,86 @@ +/* + * BK Id: SCCS/s.ns16550.c 1.9 07/30/01 17:19:40 trini + */ +/* + * COM1 NS16550 support + */ + +#include +#include +#include +#include + +extern void outb(int port, unsigned char val); +extern unsigned char inb(int port); +extern unsigned long ISA_io; + +static struct serial_state rs_table[RS_TABLE_SIZE] = { + SERIAL_PORT_DFNS /* Defined in */ +}; + +static int shift; + +unsigned long serial_init(int chan) { + unsigned long com_port; + + /* We need to find out which type io we're expecting. If it's + * 'SERIAL_IO_PORT', we get an offset from the isa_io_base. + * If it's 'SERIAL_IO_MEM', we can the exact location. -- Tom */ + switch (rs_table[chan].io_type) { + case SERIAL_IO_PORT: + com_port = rs_table[chan].port; + break; + case SERIAL_IO_MEM: + com_port = (unsigned long)rs_table[chan].iomem_base; + break; + default: + /* We can't deal with it. */ + return -1; + } + + /* How far apart the registers are. */ + shift = rs_table[chan].iomem_reg_shift; + + /* See if port is present */ + outb(com_port + (UART_LCR << shift), 0x00); + outb(com_port + (UART_IER << shift), 0x00); + /* Access baud rate */ + outb(com_port + (UART_LCR << shift), 0x80); +#ifdef CONFIG_SERIAL_CONSOLE_NONSTD + /* Input clock. */ + outb(com_port + (UART_DLL << shift), + (BASE_BAUD / CONFIG_SERIAL_CONSOLE_BAUD)); + outb(com_port + (UART_DLM << shift), + (BASE_BAUD / CONFIG_SERIAL_CONSOLE_BAUD) >> 8); +#endif + /* 8 data, 1 stop, no parity */ + outb(com_port + (UART_LCR << shift), 0x03); + /* RTS/DTR */ + outb(com_port + (UART_MCR << shift), 0x03); + /* Clear & enable FIFOs */ + outb(com_port + (UART_FCR << shift), 0x07); + + return (com_port); +} + +void +serial_putc(unsigned long com_port, unsigned char c) +{ + while ((inb(com_port + (UART_LSR << shift)) & UART_LSR_THRE) == 0) + ; + outb(com_port, c); +} + +unsigned char +serial_getc(unsigned long com_port) +{ + while ((inb(com_port + (UART_LSR << shift)) & UART_LSR_DR) == 0) + ; + return inb(com_port); +} + +int +serial_tstc(unsigned long com_port) +{ + return ((inb(com_port + (UART_LSR << shift)) & UART_LSR_DR) != 0); +} diff --git a/pool/shard000/C/0011281_rtciobrg.c b/pool/shard000/C/0011281_rtciobrg.c new file mode 100644 index 0000000000000000000000000000000000000000..aa1da3409ddf38a1ac5bbe995dade815700ab7c7 --- /dev/null +++ b/pool/shard000/C/0011281_rtciobrg.c @@ -0,0 +1,139 @@ +/* + * RTC I/O Bridge interfaces for CSR SiRFprimaII + * ARM access the registers of SYSRTC, GPSRTC and PWRC through this module + * + * Copyright (c) 2011 Cambridge Silicon Radio Limited, a CSR plc group company. + * + * Licensed under GPLv2 or later. + */ + +#include +#include +#include +#include +#include +#include +#include + +#define SIRFSOC_CPUIOBRG_CTRL 0x00 +#define SIRFSOC_CPUIOBRG_WRBE 0x04 +#define SIRFSOC_CPUIOBRG_ADDR 0x08 +#define SIRFSOC_CPUIOBRG_DATA 0x0c + +/* + + + */ +void __iomem *sirfsoc_rtciobrg_base; +static DEFINE_SPINLOCK(rtciobrg_lock); + +/* + + + */ +void sirfsoc_rtc_iobrg_wait_sync(void) +{ + while (readl_relaxed(sirfsoc_rtciobrg_base + SIRFSOC_CPUIOBRG_CTRL)) + cpu_relax(); +} + +void sirfsoc_rtc_iobrg_besyncing(void) +{ + unsigned long flags; + + spin_lock_irqsave(&rtciobrg_lock, flags); + + sirfsoc_rtc_iobrg_wait_sync(); + + spin_unlock_irqrestore(&rtciobrg_lock, flags); +} +EXPORT_SYMBOL_GPL(sirfsoc_rtc_iobrg_besyncing); + +u32 __sirfsoc_rtc_iobrg_readl(u32 addr) +{ + sirfsoc_rtc_iobrg_wait_sync(); + + writel_relaxed(0x00, sirfsoc_rtciobrg_base + SIRFSOC_CPUIOBRG_WRBE); + writel_relaxed(addr, sirfsoc_rtciobrg_base + SIRFSOC_CPUIOBRG_ADDR); + writel_relaxed(0x01, sirfsoc_rtciobrg_base + SIRFSOC_CPUIOBRG_CTRL); + + sirfsoc_rtc_iobrg_wait_sync(); + + return readl_relaxed(sirfsoc_rtciobrg_base + SIRFSOC_CPUIOBRG_DATA); +} + +u32 sirfsoc_rtc_iobrg_readl(u32 addr) +{ + unsigned long flags, val; + + spin_lock_irqsave(&rtciobrg_lock, flags); + + val = __sirfsoc_rtc_iobrg_readl(addr); + + spin_unlock_irqrestore(&rtciobrg_lock, flags); + + return val; +} +EXPORT_SYMBOL_GPL(sirfsoc_rtc_iobrg_readl); + +void sirfsoc_rtc_iobrg_pre_writel(u32 val, u32 addr) +{ + sirfsoc_rtc_iobrg_wait_sync(); + + writel_relaxed(0xf1, sirfsoc_rtciobrg_base + SIRFSOC_CPUIOBRG_WRBE); + writel_relaxed(addr, sirfsoc_rtciobrg_base + SIRFSOC_CPUIOBRG_ADDR); + + writel_relaxed(val, sirfsoc_rtciobrg_base + SIRFSOC_CPUIOBRG_DATA); +} + +void sirfsoc_rtc_iobrg_writel(u32 val, u32 addr) +{ + unsigned long flags; + + spin_lock_irqsave(&rtciobrg_lock, flags); + + sirfsoc_rtc_iobrg_pre_writel(val, addr); + + writel_relaxed(0x01, sirfsoc_rtciobrg_base + SIRFSOC_CPUIOBRG_CTRL); + + sirfsoc_rtc_iobrg_wait_sync(); + + spin_unlock_irqrestore(&rtciobrg_lock, flags); +} +EXPORT_SYMBOL_GPL(sirfsoc_rtc_iobrg_writel); + +static const struct of_device_id rtciobrg_ids[] = { + { .compatible = "sirf,prima2-rtciobg" }, + {} +}; + +static int __devinit sirfsoc_rtciobrg_probe(struct platform_device *op) +{ + struct device_node *np = op->dev.of_node; + + sirfsoc_rtciobrg_base = of_iomap(np, 0); + if (!sirfsoc_rtciobrg_base) + panic("unable to map rtc iobrg registers\n"); + + return 0; +} + +static struct platform_driver sirfsoc_rtciobrg_driver = { + .probe = sirfsoc_rtciobrg_probe, + .driver = { + .name = "sirfsoc-rtciobrg", + .owner = THIS_MODULE, + .of_match_table = rtciobrg_ids, + }, +}; + +static int __init sirfsoc_rtciobrg_init(void) +{ + return platform_driver_register(&sirfsoc_rtciobrg_driver); +} +postcore_initcall(sirfsoc_rtciobrg_init); + +MODULE_AUTHOR("Zhiwu Song , " + "Barry Song "); +MODULE_DESCRIPTION("CSR SiRFprimaII rtc io bridge"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard000/C/0011285_log.c b/pool/shard000/C/0011285_log.c new file mode 100644 index 0000000000000000000000000000000000000000..c80843b962231cd48d6af07c0cf6ca26668fd67f --- /dev/null +++ b/pool/shard000/C/0011285_log.c @@ -0,0 +1,57 @@ +/* + Simple Operating System for Smartcard Education + Copyright (C) 2002 Matthias Bruestle + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +/*! @file + \brief Logging functions. + + $Id: log.c,v 1.6 2002/12/22 15:42:55 m Exp $ +*/ + +#include +#include +#include +#include + +#if CONF_WITH_LOGGING==1 +iu16 dst=LOG_START+2; +bool log_enable; + +void log_init( void ) +{ + dst=LOG_START+2; + hal_eeprom_write( LOG_START, (iu8 *) &dst, 2 ); + log_enable=FALSE; +} + +void log_add( iu8 tag, iu8 *data, iu8 len ) +{ + bool save=log_enable; + + if( !log_enable || dst +#include + +/** + * @ingroup threads + * + * Make a thread eligible for CPU service. + * @param tid target thread + * @param resch if RESCHED_YES, reschedules + * @return OK if thread has been added to readylist, else SYSERR + */ +int ready(tid_typ tid, bool resch) +{ + register struct thrent *thrptr; + + if (isbadtid(tid)) + { + return SYSERR; + } + + thrptr = &thrtab[tid]; + thrptr->state = THRREADY; + + insert(tid, readylist, thrptr->prio); + + if (resch == RESCHED_YES) + { + resched(); + } + return OK; +} diff --git a/pool/shard000/C/0011296_gimpcombotagentry.c b/pool/shard000/C/0011296_gimpcombotagentry.c new file mode 100644 index 0000000000000000000000000000000000000000..b8e1909edc7a89c6b43ca2e49b7a9af7f1f09e0d --- /dev/null +++ b/pool/shard000/C/0011296_gimpcombotagentry.c @@ -0,0 +1,313 @@ +/* GIMP - The GNU Image Manipulation Program + * Copyright (C) 1995 Spencer Kimball and Peter Mattis + * + * gimpcombotagentry.c + * Copyright (C) 2008 Aurimas Juška + * + * 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 + * along with this program. If not, see . + */ + +#include "config.h" + +#include + +#include +#include + +#include "widgets-types.h" + +#include "core/gimpcontainer.h" +#include "core/gimpcontext.h" +#include "core/gimptag.h" +#include "core/gimptagged.h" +#include "core/gimptaggedcontainer.h" +#include "core/gimpviewable.h" + +#include "gimptagentry.h" +#include "gimptagpopup.h" +#include "gimpcombotagentry.h" + + +static void gimp_combo_tag_entry_constructed (GObject *object); +static void gimp_combo_tag_entry_dispose (GObject *object); + +static gboolean gimp_combo_tag_entry_expose (GtkWidget *widget, + GdkEventExpose *event); +static void gimp_combo_tag_entry_style_set (GtkWidget *widget, + GtkStyle *previous_style); + +static void gimp_combo_tag_entry_icon_press (GtkWidget *widget, + GtkEntryIconPosition icon_pos, + GdkEvent *event, + gpointer user_data); + +static void gimp_combo_tag_entry_popup_destroy (GtkObject *object, + GimpComboTagEntry *entry); + +static void gimp_combo_tag_entry_tag_count_changed (GimpTaggedContainer *container, + gint tag_count, + GimpComboTagEntry *entry); + + +G_DEFINE_TYPE (GimpComboTagEntry, gimp_combo_tag_entry, GIMP_TYPE_TAG_ENTRY); + +#define parent_class gimp_combo_tag_entry_parent_class + + +static void +gimp_combo_tag_entry_class_init (GimpComboTagEntryClass *klass) +{ + GObjectClass *object_class = G_OBJECT_CLASS (klass); + GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass); + + object_class->constructed = gimp_combo_tag_entry_constructed; + object_class->dispose = gimp_combo_tag_entry_dispose; + + widget_class->expose_event = gimp_combo_tag_entry_expose; + widget_class->style_set = gimp_combo_tag_entry_style_set; +} + +static void +gimp_combo_tag_entry_init (GimpComboTagEntry *entry) +{ + entry->popup = NULL; + entry->normal_item_attr = NULL; + entry->selected_item_attr = NULL; + entry->insensitive_item_attr = NULL; + + gtk_widget_add_events (GTK_WIDGET (entry), + GDK_BUTTON_PRESS_MASK | + GDK_POINTER_MOTION_MASK); + + gtk_entry_set_icon_from_stock (GTK_ENTRY (entry), + GTK_ENTRY_ICON_SECONDARY, + GTK_STOCK_GO_DOWN); + + g_signal_connect (entry, "icon-press", + G_CALLBACK (gimp_combo_tag_entry_icon_press), + NULL); +} + +static void +gimp_combo_tag_entry_constructed (GObject *object) +{ + GimpComboTagEntry *entry = GIMP_COMBO_TAG_ENTRY (object); + + G_OBJECT_CLASS (parent_class)->constructed (object); + + g_signal_connect_object (GIMP_TAG_ENTRY (entry)->container, + "tag-count-changed", + G_CALLBACK (gimp_combo_tag_entry_tag_count_changed), + entry, 0); +} + +static void +gimp_combo_tag_entry_dispose (GObject *object) +{ + GimpComboTagEntry *combo_entry = GIMP_COMBO_TAG_ENTRY (object); + + if (combo_entry->arrow_pixbuf) + { + g_object_unref (combo_entry->arrow_pixbuf); + combo_entry->arrow_pixbuf = NULL; + } + + if (combo_entry->normal_item_attr) + { + pango_attr_list_unref (combo_entry->normal_item_attr); + combo_entry->normal_item_attr = NULL; + } + + if (combo_entry->selected_item_attr) + { + pango_attr_list_unref (combo_entry->selected_item_attr); + combo_entry->selected_item_attr = NULL; + } + + if (combo_entry->insensitive_item_attr) + { + pango_attr_list_unref (combo_entry->insensitive_item_attr); + combo_entry->insensitive_item_attr = NULL; + } + + G_OBJECT_CLASS (parent_class)->dispose (object); +} + +static gboolean +gimp_combo_tag_entry_expose (GtkWidget *widget, + GdkEventExpose *event) +{ + GimpComboTagEntry *entry = GIMP_COMBO_TAG_ENTRY (widget); + + if (! entry->arrow_pixbuf) + { + GtkStyle *style = gtk_widget_get_style (widget); + GdkPixmap *pixmap; + cairo_t *cr; + + pixmap = gdk_pixmap_new (gtk_widget_get_window (widget), 8, 8, -1); + + cr = gdk_cairo_create (pixmap); + gdk_cairo_set_source_color (cr, &style->base[GTK_STATE_NORMAL]); + cairo_paint (cr); + cairo_destroy (cr); + + gtk_paint_arrow (style, pixmap, + GTK_STATE_NORMAL, + GTK_SHADOW_NONE, NULL, widget, NULL, + GTK_ARROW_DOWN, TRUE, + 0, 0, 8, 8); + + entry->arrow_pixbuf = gdk_pixbuf_get_from_drawable (NULL, pixmap, NULL, + 0, 0, 0, 0, 8, 8); + + g_object_unref (pixmap); + + gtk_entry_set_icon_from_pixbuf (GTK_ENTRY (entry), + GTK_ENTRY_ICON_SECONDARY, + entry->arrow_pixbuf); + } + + return GTK_WIDGET_CLASS (parent_class)->expose_event (widget, event); +} + +static void +gimp_combo_tag_entry_style_set (GtkWidget *widget, + GtkStyle *previous_style) +{ + GimpComboTagEntry *entry = GIMP_COMBO_TAG_ENTRY (widget); + GtkStyle *style = gtk_widget_get_style (widget); + GdkColor color; + PangoAttribute *attribute; + + if (GTK_WIDGET_CLASS (parent_class)->style_set) + GTK_WIDGET_CLASS (parent_class)->style_set (widget, previous_style); + + if (entry->normal_item_attr) + pango_attr_list_unref (entry->normal_item_attr); + entry->normal_item_attr = pango_attr_list_new (); + + if (style->font_desc) + { + attribute = pango_attr_font_desc_new (style->font_desc); + pango_attr_list_insert (entry->normal_item_attr, attribute); + } + color = style->text[GTK_STATE_NORMAL]; + attribute = pango_attr_foreground_new (color.red, color.green, color.blue); + pango_attr_list_insert (entry->normal_item_attr, attribute); + + if (entry->selected_item_attr) + pango_attr_list_unref (entry->selected_item_attr); + entry->selected_item_attr = pango_attr_list_copy (entry->normal_item_attr); + + color = style->text[GTK_STATE_SELECTED]; + attribute = pango_attr_foreground_new (color.red, color.green, color.blue); + pango_attr_list_insert (entry->selected_item_attr, attribute); + color = style->base[GTK_STATE_SELECTED]; + attribute = pango_attr_background_new (color.red, color.green, color.blue); + pango_attr_list_insert (entry->selected_item_attr, attribute); + + if (entry->insensitive_item_attr) + pango_attr_list_unref (entry->insensitive_item_attr); + entry->insensitive_item_attr = pango_attr_list_copy (entry->normal_item_attr); + + color = style->text[GTK_STATE_INSENSITIVE]; + attribute = pango_attr_foreground_new (color.red, color.green, color.blue); + pango_attr_list_insert (entry->insensitive_item_attr, attribute); + color = style->base[GTK_STATE_INSENSITIVE]; + attribute = pango_attr_background_new (color.red, color.green, color.blue); + pango_attr_list_insert (entry->insensitive_item_attr, attribute); + + entry->selected_item_color = style->base[GTK_STATE_SELECTED]; + + if (entry->arrow_pixbuf) + { + g_object_unref (entry->arrow_pixbuf); + entry->arrow_pixbuf = NULL; + } +} + +/** + * gimp_combo_tag_entry_new: + * @container: a tagged container to be used. + * @mode: tag entry mode to work in. + * + * Creates a new #GimpComboTagEntry widget which extends #GimpTagEntry by + * adding ability to pick tags using popup window (similar to combo box). + * + * Return value: a new #GimpComboTagEntry widget. + **/ +GtkWidget * +gimp_combo_tag_entry_new (GimpTaggedContainer *container, + GimpTagEntryMode mode) +{ + g_return_val_if_fail (GIMP_IS_TAGGED_CONTAINER (container), NULL); + + return g_object_new (GIMP_TYPE_COMBO_TAG_ENTRY, + "container", container, + "mode", mode, + NULL); +} + +static void +gimp_combo_tag_entry_icon_press (GtkWidget *widget, + GtkEntryIconPosition icon_pos, + GdkEvent *event, + gpointer user_data) +{ + GimpComboTagEntry *entry = GIMP_COMBO_TAG_ENTRY (widget); + + if (! entry->popup) + { + GimpTaggedContainer *container = GIMP_TAG_ENTRY (entry)->container; + gint tag_count; + + tag_count = gimp_tagged_container_get_tag_count (container); + + if (tag_count > 0 && ! GIMP_TAG_ENTRY (entry)->has_invalid_tags) + { + entry->popup = gimp_tag_popup_new (entry); + g_signal_connect (entry->popup, "destroy", + G_CALLBACK (gimp_combo_tag_entry_popup_destroy), + entry); + gimp_tag_popup_show (GIMP_TAG_POPUP (entry->popup)); + } + } + else + { + gtk_widget_destroy (entry->popup); + } +} + +static void +gimp_combo_tag_entry_popup_destroy (GtkObject *object, + GimpComboTagEntry *entry) +{ + entry->popup = NULL; + gtk_widget_grab_focus (GTK_WIDGET (entry)); +} + +static void +gimp_combo_tag_entry_tag_count_changed (GimpTaggedContainer *container, + gint tag_count, + GimpComboTagEntry *entry) +{ + gboolean sensitive; + + sensitive = tag_count > 0 && ! GIMP_TAG_ENTRY (entry)->has_invalid_tags; + + gtk_entry_set_icon_sensitive (GTK_ENTRY (entry), + GTK_ENTRY_ICON_SECONDARY, + sensitive); +} diff --git a/pool/shard000/C/0011311_2d_array.c b/pool/shard000/C/0011311_2d_array.c new file mode 100644 index 0000000000000000000000000000000000000000..65e4c1fb7698e2959d95f578ab4ceef574e4c2d9 --- /dev/null +++ b/pool/shard000/C/0011311_2d_array.c @@ -0,0 +1,64 @@ +#include +#include +#include +#include +#include +#include +#include + +int hourglass(int *array); + +int main(){ + int arr[6][6]; + int max = 0; + int sum = 0; + int n = 0; + int i = 0; + int j = 0; + + + for(int row = 0; row < 6; row++){ + for(int column = 0; column < 6; column++){ + scanf("%d", &arr[row][column]); + } + } + + while(n < 16) + { + for(int row = i; row < i + 3; row++){ + for(int column = j; column < j + 3; column++){ + if(row == i + 1) + { + sum += arr[i + 1][j + 1]; + break; + } + + sum += arr[row][column]; + } + } + + if(j + 3 < 6) + { + j++; + } + else + { + j = 0; + i++; + } + + if(sum > max || n == 0) + { + max = sum; + sum = 0; + } + else + { + sum = 0; + } + n++; + } + + printf("%i\n", max); + return max; +} diff --git a/pool/shard000/C/0011317_migration-exec.c b/pool/shard000/C/0011317_migration-exec.c new file mode 100644 index 0000000000000000000000000000000000000000..2c4e7bcac1b307465e7702ab10026fa31622b939 --- /dev/null +++ b/pool/shard000/C/0011317_migration-exec.c @@ -0,0 +1,154 @@ +/* + * QEMU live migration + * + * Copyright IBM, Corp. 2008 + * Copyright Dell MessageOne 2008 + * + * Authors: + * Anthony Liguori + * Charles Duffy + * + * This work is licensed under the terms of the GNU GPL, version 2. See + * the COPYING file in the top-level directory. + * + */ + +#include "qemu-common.h" +#include "qemu/sockets.h" +#include "migration/migration.h" +#include "sysemu/char.h" +#include "sysemu/sysemu.h" +#include "buffered_file.h" +#include "block/block.h" +#include +#include + +//#define DEBUG_MIGRATION_EXEC + +#ifdef DEBUG_MIGRATION_EXEC +#define DPRINTF(fmt, ...) \ + do { printf("migration-exec: " fmt, ## __VA_ARGS__); } while (0) +#else +#define DPRINTF(fmt, ...) \ + do { } while (0) +#endif + +static int file_errno(FdMigrationState *s) +{ + return errno; +} + +static int file_write(FdMigrationState *s, const void * buf, size_t size) +{ + return write(s->fd, buf, size); +} + +static int exec_close(FdMigrationState *s) +{ + int ret = 0; + DPRINTF("exec_close\n"); + if (s->opaque) { + ret = qemu_fclose(s->opaque); + s->opaque = NULL; + s->fd = -1; + if (ret != -1 && + WIFEXITED(ret) + && WEXITSTATUS(ret) == 0) { + ret = 0; + } else { + ret = -1; + } + } + return ret; +} + +MigrationState *exec_start_outgoing_migration(const char *command, + int64_t bandwidth_limit, + int detach) +{ + FdMigrationState *s; + FILE *f; + + s = g_malloc0(sizeof(*s)); + + f = popen(command, "w"); + if (f == NULL) { + DPRINTF("Unable to popen exec target\n"); + goto err_after_alloc; + } + + s->fd = fileno(f); + if (s->fd == -1) { + DPRINTF("Unable to retrieve file descriptor for popen'd handle\n"); + goto err_after_open; + } + + if (fcntl(s->fd, F_SETFD, O_NONBLOCK) == -1) { + DPRINTF("Unable to set nonblocking mode on file descriptor\n"); + goto err_after_open; + } + + s->opaque = qemu_popen(f, "w"); + + s->close = exec_close; + s->get_error = file_errno; + s->write = file_write; + s->mig_state.cancel = migrate_fd_cancel; + s->mig_state.get_status = migrate_fd_get_status; + s->mig_state.release = migrate_fd_release; + + s->state = MIG_STATE_ACTIVE; + s->mon_resume = NULL; + s->bandwidth_limit = bandwidth_limit; + + if (!detach) + migrate_fd_monitor_suspend(s); + + migrate_fd_connect(s); + return &s->mig_state; + +err_after_open: + pclose(f); +err_after_alloc: + g_free(s); + return NULL; +} + +static void exec_accept_incoming_migration(void *opaque) +{ + QEMUFile *f = opaque; + int ret; + + vm_stop(0); /* just in case */ + ret = qemu_loadvm_state(f); + if (ret < 0) { + fprintf(stderr, "load of migration failed\n"); + goto err; + } + qemu_announce_self(); + DPRINTF("successfully loaded vm state\n"); + /* we've successfully migrated, close the fd */ + qemu_set_fd_handler2(qemu_stdio_fd(f), NULL, NULL, NULL, NULL); + vm_start(); + +err: + qemu_fclose(f); +} + +int exec_start_incoming_migration(const char *command) +{ + QEMUFile *f; + + DPRINTF("Attempting to start an incoming migration\n"); + f = qemu_popen_cmd(command, "r"); + if(f == NULL) { + DPRINTF("Unable to apply qemu wrapper to popen file\n"); + return -errno; + } + + qemu_set_fd_handler2(qemu_stdio_fd(f), NULL, + exec_accept_incoming_migration, NULL, + (void *)(unsigned long)f); + + return 0; +} diff --git a/pool/shard000/C/0011334_wabsdev_source.c b/pool/shard000/C/0011334_wabsdev_source.c new file mode 100644 index 0000000000000000000000000000000000000000..b4159ce2b52cd376ed65ed825204218a66073293 --- /dev/null +++ b/pool/shard000/C/0011334_wabsdev_source.c @@ -0,0 +1,51 @@ +/* statistics/wabsdev_source.c + * + * Copyright (C) 1996, 1997, 1998, 1999, 2000 Jim Davies, Brian Gough + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or (at + * your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +double +FUNCTION(gsl_stats,wabsdev) (const BASE w[], const size_t wstride, const BASE data[], const size_t stride, const size_t n) +{ + const double wmean = FUNCTION(gsl_stats,wmean)(w, wstride, data, stride, n); + return FUNCTION(gsl_stats,wabsdev_m)(w, wstride, data, stride, n, wmean); +} + +double +FUNCTION(gsl_stats,wabsdev_m) (const BASE w[], const size_t wstride, const BASE data[], const size_t stride, const size_t n, const double wmean) +{ + /* Compute the weighted absolute deviation of a dataset */ + + long double wabsdev = 0; + long double W = 0; + + size_t i; + + /* find the sum of the absolute deviations */ + for (i = 0; i < n; i++) + { + BASE wi = w[i * wstride]; + + if (wi > 0) { + const long double delta = fabs(data[i * stride] - wmean); + W += wi ; + wabsdev += (delta - wabsdev) * (wi / W); + } + } + + return wabsdev; +} + diff --git a/pool/shard000/C/0011338_echo_client.c b/pool/shard000/C/0011338_echo_client.c new file mode 100644 index 0000000000000000000000000000000000000000..e3c3f9650ea179abc1f667486fc712b1d7551dde --- /dev/null +++ b/pool/shard000/C/0011338_echo_client.c @@ -0,0 +1,71 @@ +//http://www.dis.uniroma1.it/~liberato/struct/typestruct/strutture.shtml +#include +#include +#include +#include +#include +#include + +struct libro { + char titolo[32]; + char autore[32]; + int anno; +}; + +int main (int argc, char **argv) { + int sockfd; + int n; + char sendline[128]; + char recvline[128]; + struct sockaddr_in servaddr; + + sockfd = socket(AF_INET, SOCK_STREAM, 0); + bzero(&servaddr, sizeof(servaddr)); + servaddr.sin_family = AF_INET; + servaddr.sin_port = htons(11124); + inet_pton(AF_INET, "127.0.0.1", &(servaddr.sin_addr)); + + connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)); + + #if 0 + while(1) { + bzero(sendline, 128); + bzero(recvline, 128); + fgets(sendline, 128, stdin); + + if (write(sockfd, sendline, strlen(sendline) - 1) <= 0) break; + if (read(sockfd, recvline, 128) <= 0) break; + + printf("%s", recvline); + } + #else + struct libro lassie; + memset(&lassie, 0, sizeof(struct libro)); + memcpy(lassie.titolo, "lessie titulo", 13); + memcpy(lassie.autore, "Tito lo lungo", 13); + lassie.anno = 1950; + + char buffer[128]; + ssize_t buf_len; + + memcpy(buffer,"put culo ", 9); + memcpy(buffer + 9, &lassie, sizeof(struct libro)); + + + write(sockfd, buffer, sizeof(struct rubrica) + 9); + memset(buffer, 0, sizeof(buffer)); + buf_len = read(sockfd, buffer, sizeof(buffer)); + printf("%s", buffer); + + memcpy(buffer, "get culo", 8); + write(sockfd, buffer, 8); + buf_len = read(sockfd, buffer, sizeof(buffer)); + + memset(&lassie, 0, sizeof(struct libro)); + memcpy(&lassie, buffer, sizeof(struct libro)); + printf("titolo %s\nautore %s\nanno %d\n", lassie.titolo, lassie.autore, lassie.anno); + #endif + + close(sockfd); + return(0); +} \ No newline at end of file diff --git a/pool/shard000/C/0011346_test.c b/pool/shard000/C/0011346_test.c new file mode 100644 index 0000000000000000000000000000000000000000..63351a187f36493ad21422e51fa0d1994a3a04ea --- /dev/null +++ b/pool/shard000/C/0011346_test.c @@ -0,0 +1,106 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Defines +#define LIGHTS "192.168.1.230" // Address of Node +#define BUFLEN ( 450 ) // Length of data to send to LED strips, 150 LEDs, three byte values per LED , 450 +#define PORT (40002) // The port the ESP is listening on + +void changemode(int dir); + +// short cut exit routine +void die(const char *str) +{ + fprintf(stderr, "error: %s\n",str); + + changemode(0); + + // exit with error + exit(1); +} + +void changemode(int dir) +{ + static struct termios oldt, newt; + + if ( dir == 1 ) + { + tcgetattr( STDIN_FILENO, &oldt); + newt = oldt; + newt.c_lflag &= ~( ICANON | ECHO ); + tcsetattr( STDIN_FILENO, TCSANOW, &newt); + } + else + tcsetattr( STDIN_FILENO, TCSANOW, &oldt); +} + +int _kbhit (void) +{ + struct timeval tv; + fd_set rdfs; + + tv.tv_sec = 0; + tv.tv_usec = 0; + + FD_ZERO(&rdfs); + FD_SET (STDIN_FILENO, &rdfs); + + select(STDIN_FILENO+1, &rdfs, NULL, NULL, &tv); + return FD_ISSET(STDIN_FILENO, &rdfs); + +} + + +int main(void) +{ + struct sockaddr_in si_other; + int s, slen = sizeof(si_other); + unsigned char data[BUFLEN]; + + if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) { + die("socket create error"); + } + + // setup the target port/address + memset((char *)&si_other, 0, sizeof(si_other)); + si_other.sin_family = AF_INET; + si_other.sin_port = htons(PORT); + si_other.sin_addr.s_addr=inet_addr( LIGHTS ); + + printf("press space to stop\n"); + + changemode(1); + // wait for a key press + while (!_kbhit()) { + + // fill the buffer with a simple green fade + // each LED is three bytes, RGB, so the 2nd led is (index*3) + for (int i = 0; i < BUFLEN; i+=3) { + + data[i ] = 0; // red + data[i+1] = i>>1; // green + data[i+2] = 0; // blue + } + + // send to ESP + if (sendto(s, (const char*)data, BUFLEN, 0, (struct sockaddr *) &si_other, slen) == -1) { + die("couldn't sendto"); + } + } + + //get rid of keypress (fflush) + getchar(); + changemode(0); + + close(s); + + return 0; +} diff --git a/pool/shard000/C/0011353_wiicontroller.c b/pool/shard000/C/0011353_wiicontroller.c new file mode 100644 index 0000000000000000000000000000000000000000..6b3581166bdb8e983e76bc1a0660c456f2f07b4d --- /dev/null +++ b/pool/shard000/C/0011353_wiicontroller.c @@ -0,0 +1,66 @@ +/**@file wiicontroller.c + * @brief implementations of the functions communicating with the wiimote + */ + +#include +#include +#include + +#include "configuration.h" +#include "wiimote.h" +#include "wiimote_api.h" + + +wiimote_t wii_connect() +{ + wiimote_t wiimote = WIIMOTE_INIT; + + // the address of the wiimote is fixed here + char *bdaddr = "2C:10:C1:8F:D0:0F"; + + printf("Waiting for connection. Press 1+2 to connect...\n"); + + if (wiimote_connect(&wiimote, bdaddr) < 0) { + fprintf(stderr, "unable to open wiimote: %s\n", wiimote_get_error()); + exit(1); + } + + printf("Successfully Connected!\n"); + + // turn on the leftmost led + wiimote.led.one = 1; + + wiimote.mode.acc = 1; + + // enable the infrared sensor + wiimote.mode.ir = 1; + + return wiimote; +} + + +void wii_getpos(wiimote_t *pwiimote, unsigned int *x, unsigned int *y) +{ + unsigned int x_left_cut = (CAMERA_X_MAX - CAMERA_X)/2; + unsigned int y_low_cut = (CAMERA_Y_MAX - CAMERA_Y)/2; + + float scale_factor = (float)CANVAS_SIZE_X / (float)CAMERA_X; + + if (wiimote_update(pwiimote) < 0) { + wiimote_disconnect(pwiimote); + } + + // project the cooridinates from the wiimote screen to the game screen + unsigned int x_pos = (pwiimote->ir1.x - x_left_cut) * scale_factor; + unsigned int y_pos = (pwiimote->ir1.y - y_low_cut) * scale_factor; + + *x = x_pos >=0 && x_pos <= CANVAS_SIZE_X ? x_pos : NOT_VALID; + *y = y_pos >=0 && y_pos <= CANVAS_SIZE_Y ? y_pos : NOT_VALID; +} + + +void wii_disconnect(wiimote_t *pwiimote){ + wiimote_disconnect(pwiimote); +} + + diff --git a/pool/shard000/C/0011367_rslist.c b/pool/shard000/C/0011367_rslist.c new file mode 100644 index 0000000000000000000000000000000000000000..6053aa182093e75b070ecd89bd318348d6f2b62f --- /dev/null +++ b/pool/shard000/C/0011367_rslist.c @@ -0,0 +1,259 @@ +/******************************************************************************* + * + * Module Name: rslist - Linked list utilities + * + ******************************************************************************/ + +/* + * Copyright (C) 2000 - 2013, Intel Corp. + * 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, + * without modification. + * 2. Redistributions in binary form must reproduce at minimum a disclaimer + * substantially similar to the "NO WARRANTY" disclaimer below + * ("Disclaimer") and any redistribution must be conditioned upon + * including a substantially similar Disclaimer requirement for further + * binary redistribution. + * 3. Neither the names of the above-listed copyright holders nor the names + * of any contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * Alternatively, this software may be distributed under the terms of the + * GNU General Public License ("GPL") version 2 as published by the Free + * Software Foundation. + * + * NO WARRANTY + * 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 MERCHANTIBILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDERS OR CONTRIBUTORS BE LIABLE FOR 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 DAMAGES. + */ + +#include +#include "accommon.h" +#include "acresrc.h" + +#define _COMPONENT ACPI_RESOURCES +ACPI_MODULE_NAME("rslist") + +/******************************************************************************* + * + * FUNCTION: acpi_rs_convert_aml_to_resources + * + * PARAMETERS: acpi_walk_aml_callback + * resource_ptr - Pointer to the buffer that will + * contain the output structures + * + * RETURN: Status + * + * DESCRIPTION: Convert an AML resource to an internal representation of the + * resource that is aligned and easier to access. + * + ******************************************************************************/ +acpi_status +acpi_rs_convert_aml_to_resources(u8 * aml, + u32 length, + u32 offset, u8 resource_index, void **context) +{ + struct acpi_resource **resource_ptr = + ACPI_CAST_INDIRECT_PTR(struct acpi_resource, context); + struct acpi_resource *resource; + union aml_resource *aml_resource; + struct acpi_rsconvert_info *conversion_table; + acpi_status status; + + ACPI_FUNCTION_TRACE(rs_convert_aml_to_resources); + + /* + * Check that the input buffer and all subsequent pointers into it + * are aligned on a native word boundary. Most important on IA64 + */ + resource = *resource_ptr; + if (ACPI_IS_MISALIGNED(resource)) { + ACPI_WARNING((AE_INFO, + "Misaligned resource pointer %p", resource)); + } + + /* Get the appropriate conversion info table */ + + aml_resource = ACPI_CAST_PTR(union aml_resource, aml); + if (acpi_ut_get_resource_type(aml) == ACPI_RESOURCE_NAME_SERIAL_BUS) { + if (aml_resource->common_serial_bus.type > + AML_RESOURCE_MAX_SERIALBUSTYPE) { + conversion_table = NULL; + } else { + /* This is an I2C, SPI, or UART serial_bus descriptor */ + + conversion_table = + acpi_gbl_convert_resource_serial_bus_dispatch + [aml_resource->common_serial_bus.type]; + } + } else { + conversion_table = + acpi_gbl_get_resource_dispatch[resource_index]; + } + + if (!conversion_table) { + ACPI_ERROR((AE_INFO, + "Invalid/unsupported resource descriptor: Type 0x%2.2X", + resource_index)); + return_ACPI_STATUS(AE_AML_INVALID_RESOURCE_TYPE); + } + + /* Convert the AML byte stream resource to a local resource struct */ + + status = + acpi_rs_convert_aml_to_resource(resource, aml_resource, + conversion_table); + if (ACPI_FAILURE(status)) { + ACPI_EXCEPTION((AE_INFO, status, + "Could not convert AML resource (Type 0x%X)", + *aml)); + return_ACPI_STATUS(status); + } + + ACPI_DEBUG_PRINT((ACPI_DB_RESOURCES, + "Type %.2X, AmlLength %.2X InternalLength %.2X\n", + acpi_ut_get_resource_type(aml), length, + resource->length)); + + /* Point to the next structure in the output buffer */ + + *resource_ptr = ACPI_NEXT_RESOURCE(resource); + return_ACPI_STATUS(AE_OK); +} + +/******************************************************************************* + * + * FUNCTION: acpi_rs_convert_resources_to_aml + * + * PARAMETERS: resource - Pointer to the resource linked list + * aml_size_needed - Calculated size of the byte stream + * needed from calling acpi_rs_get_aml_length() + * The size of the output_buffer is + * guaranteed to be >= aml_size_needed + * output_buffer - Pointer to the buffer that will + * contain the byte stream + * + * RETURN: Status + * + * DESCRIPTION: Takes the resource linked list and parses it, creating a + * byte stream of resources in the caller's output buffer + * + ******************************************************************************/ + +acpi_status +acpi_rs_convert_resources_to_aml(struct acpi_resource *resource, + acpi_size aml_size_needed, u8 * output_buffer) +{ + u8 *aml = output_buffer; + u8 *end_aml = output_buffer + aml_size_needed; + struct acpi_rsconvert_info *conversion_table; + acpi_status status; + + ACPI_FUNCTION_TRACE(rs_convert_resources_to_aml); + + /* Walk the resource descriptor list, convert each descriptor */ + + while (aml < end_aml) { + + /* Validate the (internal) Resource Type */ + + if (resource->type > ACPI_RESOURCE_TYPE_MAX) { + ACPI_ERROR((AE_INFO, + "Invalid descriptor type (0x%X) in resource list", + resource->type)); + return_ACPI_STATUS(AE_BAD_DATA); + } + + /* Sanity check the length. It must not be zero, or we loop forever */ + + if (!resource->length) { + ACPI_ERROR((AE_INFO, + "Invalid zero length descriptor in resource list\n")); + return_ACPI_STATUS(AE_AML_BAD_RESOURCE_LENGTH); + } + + /* Perform the conversion */ + + if (resource->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) { + if (resource->data.common_serial_bus.type > + AML_RESOURCE_MAX_SERIALBUSTYPE) { + conversion_table = NULL; + } else { + /* This is an I2C, SPI, or UART serial_bus descriptor */ + + conversion_table = + acpi_gbl_convert_resource_serial_bus_dispatch + [resource->data.common_serial_bus.type]; + } + } else { + conversion_table = + acpi_gbl_set_resource_dispatch[resource->type]; + } + + if (!conversion_table) { + ACPI_ERROR((AE_INFO, + "Invalid/unsupported resource descriptor: Type 0x%2.2X", + resource->type)); + return_ACPI_STATUS(AE_AML_INVALID_RESOURCE_TYPE); + } + + status = acpi_rs_convert_resource_to_aml(resource, + ACPI_CAST_PTR(union + aml_resource, + aml), + conversion_table); + if (ACPI_FAILURE(status)) { + ACPI_EXCEPTION((AE_INFO, status, + "Could not convert resource (type 0x%X) to AML", + resource->type)); + return_ACPI_STATUS(status); + } + + /* Perform final sanity check on the new AML resource descriptor */ + + status = acpi_ut_validate_resource(NULL, + ACPI_CAST_PTR(union + aml_resource, + aml), NULL); + if (ACPI_FAILURE(status)) { + return_ACPI_STATUS(status); + } + + /* Check for end-of-list, normal exit */ + + if (resource->type == ACPI_RESOURCE_TYPE_END_TAG) { + + /* An End Tag indicates the end of the input Resource Template */ + + return_ACPI_STATUS(AE_OK); + } + + /* + * Extract the total length of the new descriptor and set the + * Aml to point to the next (output) resource descriptor + */ + aml += acpi_ut_get_descriptor_length(aml); + + /* Point to the next input resource descriptor */ + + resource = ACPI_NEXT_RESOURCE(resource); + } + + /* Completed buffer, but did not find an end_tag resource descriptor */ + + return_ACPI_STATUS(AE_AML_NO_RESOURCE_END_TAG); +} diff --git a/pool/shard000/C/0011376_infoenc.c b/pool/shard000/C/0011376_infoenc.c new file mode 100644 index 0000000000000000000000000000000000000000..1c395c2ca4afe6f4c133aa4e8431ecd259e07b50 --- /dev/null +++ b/pool/shard000/C/0011376_infoenc.c @@ -0,0 +1,115 @@ +/*Daala video codec +Copyright (c) 2006-2010 Daala project contributors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +- Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.*/ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include +#include "encint.h" + +int daala_encode_flush_header(daala_enc_ctx *_enc, daala_comment *_dc, + ogg_packet *_op) { + daala_info *info = &_enc->state.info; + if (_enc == NULL || _op == NULL) return OD_EFAULT; + switch (_enc->packet_state) { + case OD_PACKET_INFO_HDR: + { + int pli; + oggbyte_reset(&_enc->obb); + oggbyte_write1(&_enc->obb, 0x80); + oggbyte_writecopy(&_enc->obb, "daala", 5); + oggbyte_write1(&_enc->obb, info->version_major); + oggbyte_write1(&_enc->obb, info->version_minor); + oggbyte_write1(&_enc->obb, info->version_sub); + OD_ASSERT(info->pic_width > 0); + oggbyte_write4(&_enc->obb, info->pic_width); + OD_ASSERT(info->pic_height > 0); + oggbyte_write4(&_enc->obb, info->pic_height); + oggbyte_write4(&_enc->obb, info->pixel_aspect_numerator); + oggbyte_write4(&_enc->obb, info->pixel_aspect_denominator); + oggbyte_write4(&_enc->obb, info->timebase_numerator); + oggbyte_write4(&_enc->obb, info->timebase_denominator); + oggbyte_write4(&_enc->obb, info->frame_duration); + OD_ASSERT(info->keyframe_granule_shift < 32); + oggbyte_write1(&_enc->obb, info->keyframe_granule_shift); + OD_ASSERT((info->nplanes >= 1) && (info->nplanes <= OD_NPLANES_MAX)); + oggbyte_write1(&_enc->obb, info->nplanes); + for (pli = 0; pli < info->nplanes; ++pli) { + oggbyte_write1(&_enc->obb, info->plane_info[pli].xdec); + oggbyte_write1(&_enc->obb, info->plane_info[pli].ydec); + } + _op->b_o_s = 1; + } + break; + case OD_PACKET_COMMENT_HDR: + { + const char *vendor; + ogg_uint32_t vendor_len; + int ci; + oggbyte_reset(&_enc->obb); + oggbyte_write1(&_enc->obb, 0x81); + oggbyte_writecopy(&_enc->obb, "daala", 5); + vendor = daala_version_string(); + vendor_len = strlen(vendor); + oggbyte_write4(&_enc->obb, vendor_len); + oggbyte_writecopy(&_enc->obb, vendor, vendor_len); + oggbyte_write4(&_enc->obb, _dc->comments); + for (ci = 0; ci < _dc->comments; ci++) { + if (_dc->user_comments[ci] != NULL) { + oggbyte_write4(&_enc->obb, _dc->comment_lengths[ci]); + oggbyte_writecopy(&_enc->obb, _dc->user_comments[ci], + _dc->comment_lengths[ci]); + } + else oggbyte_write4(&_enc->obb, 0); + } + _op->b_o_s = 0; + } + break; + case OD_PACKET_SETUP_HDR: + { + /*TODO: Produce header contents.*/ + oggbyte_reset(&_enc->obb); + oggbyte_write1(&_enc->obb, 0x82); + oggbyte_writecopy(&_enc->obb, "daala", 5); + _op->b_o_s = 0; + } + break; + /*No more headers to emit.*/ + default: return 0; + } + /*This is kind of fugly: we hand the user a buffer which they do not own. + We will overwrite it when the next packet is output, so the user better be + done with it by then. + Vorbis is little better: it hands back buffers that it will free the next + time the headers are requested, or when the encoder is cleared. + Hopefully libogg2 will make this much cleaner.*/ + _op->packet = oggbyte_get_buffer(&_enc->obb); + _op->bytes = oggbyte_bytes(&_enc->obb); + _op->e_o_s = 0; + _op->granulepos = 0; + /*Is this smart? Vorbis does not even set this field.*/ + _op->packetno = 0; + return ++_enc->packet_state+3; +} diff --git a/pool/shard000/C/0011400_exec_open_dir.c b/pool/shard000/C/0011400_exec_open_dir.c new file mode 100644 index 0000000000000000000000000000000000000000..7a7213acd2af02cd4a9d4d62e17b8154de3a37bb --- /dev/null +++ b/pool/shard000/C/0011400_exec_open_dir.c @@ -0,0 +1,67 @@ +#include "../apue.h" +#include +#include +#include +#include +#include + +char *str = 0; + +int main (int argc, char *argv[]) +{ + DIR *dir = 0; + if (argc > 1) + { + // child mode + // get file descriptor from args + dir = (DIR*)atol(argv[1]); + char *s = argv[2]; + printf ("recv dir %p, str %s (total %d)\n", dir, s, argc); + + struct dirent *ent = readdir (dir); + printf ("read %p, %s\n", ent, ent ? ent->d_name : 0); + closedir (dir); + } + else + { + str = strdup ("hello world"); + int fd = open(".", O_RDONLY); + if (fd == -1) + err_sys ("open"); + + int flag = fcntl (fd, F_GETFD); + printf ("dir fd(%d) flag: 0x%x, CLOSE_ON_EXEC: %d\n", fd, flag, flag & FD_CLOEXEC); + + close (fd); + dir = opendir ("."); + if (dir == NULL) + err_sys ("open ."); + else + printf ("open . return %p\n", dir); + + fd = dirfd (dir); + flag = fcntl (fd, F_GETFD); + printf ("dir fd(%d) flag: 0x%x, CLOSE_ON_EXEC: %d\n", fd, flag, flag & FD_CLOEXEC); + pid_t pid = 0; + if ((pid = fork ()) < 0) + err_sys ("fork error"); + else if (pid == 0) + { + char tmp[32] = { 0 }; + sprintf (tmp, "%lu", (long)dir); + + struct dirent *ent = readdir (dir); + printf ("read %p, %s\n", ent, ent ? ent->d_name : 0); + + execlp ("./exec_open_dir", "./exec_open_dir"/*argv[0]*/, tmp, str, NULL); + err_sys ("execlp error"); + } + else + { + printf ("fork and exec child %u\n", pid); + closedir (dir); + } + } + + exit (0); +} diff --git a/pool/shard000/C/0011409_totem-session.c b/pool/shard000/C/0011409_totem-session.c new file mode 100644 index 0000000000000000000000000000000000000000..ad272f01e310c329a818b04a858395dec070b567 --- /dev/null +++ b/pool/shard000/C/0011409_totem-session.c @@ -0,0 +1,191 @@ +/* totem-session.c + + Copyright (C) 2004 Bastien Nocera + + The Gnome Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public License as + published by the Free Software Foundation; either version 2 of the + License, or (at your option) any later version. + + The Gnome Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public + License along with the Gnome Library; see the file COPYING.LIB. If not, + write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301 USA. + + Author: Bastien Nocera + */ + +#include "config.h" + +#include "totem.h" +#include "totem-private.h" +#include "totem-session.h" +#include "totem-uri.h" + +#ifdef WITH_SMCLIENT + +#include + +#include "eggsmclient.h" + +#ifdef GDK_WINDOWING_X11 +#include "eggdesktopfile.h" +#endif + +static char * +totem_session_create_key (void) +{ + char *filename, *path; + + filename = g_strdup_printf ("playlist-%d-%d-%u.pls", + (int) getpid (), + (int) time (NULL), + g_random_int ()); + path = g_build_filename (totem_dot_dir (), filename, NULL); + g_free (filename); + + return path; +} + +static void +totem_save_state_cb (EggSMClient *client, + GKeyFile *key_file, + Totem *totem) +{ + const char *argv[] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL }; + int i = 0; + char *path_id, *current, *seek, *uri; + int current_index; + + current_index = totem_playlist_get_current (totem->playlist); + + if (current_index == -1) + return; + + path_id = totem_session_create_key (); + totem_playlist_save_current_playlist (totem->playlist, path_id); + + /* How to discard the save */ + argv[i++] = "rm"; + argv[i++] = "-f"; + argv[i++] = path_id; + egg_sm_client_set_discard_command (client, i, (const char **) argv); + + /* How to clone or restart */ + i = 0; + current = g_strdup_printf ("%d", current_index); + seek = g_strdup_printf ("%"G_GINT64_FORMAT, + bacon_video_widget_get_current_time (totem->bvw)); + argv[i++] = totem->argv0; + argv[i++] = "--playlist-idx"; + argv[i++] = current; + argv[i++] = "--seek"; + argv[i++] = seek; + + uri = g_filename_to_uri (path_id, NULL, NULL); + argv[i++] = uri; + + /* FIXME: what's this used for? */ + /* egg_sm_client_set_clone_command (client, i, argv); */ + + egg_sm_client_set_restart_command (client, i, (const char **) argv); + + g_free (path_id); + g_free (current); + g_free (seek); + g_free (uri); +} + +G_GNUC_NORETURN static void +totem_quit_cb (EggSMClient *client, + Totem *totem) +{ + totem_action_exit (totem); +} + +void +totem_session_add_options (GOptionContext *context) +{ +#ifdef GDK_WINDOWING_X11 + egg_set_desktop_file_without_defaults (DATADIR "/applications/" PACKAGE ".desktop"); +#endif + + g_option_context_add_group (context, egg_sm_client_get_option_group ()); +} + +void +totem_session_setup (Totem *totem, char **argv) +{ + EggSMClient *sm_client; + + totem->argv0 = argv[0]; + + sm_client = egg_sm_client_get (); + g_signal_connect (sm_client, "save-state", + G_CALLBACK (totem_save_state_cb), totem); + g_signal_connect (sm_client, "quit", + G_CALLBACK (totem_quit_cb), totem); + + if (egg_sm_client_is_resumed (sm_client)) + totem->session_restored = TRUE; +} + +void +totem_session_restore (Totem *totem, char **filenames) +{ + char *mrl, *uri, *subtitle; + + g_return_if_fail (filenames != NULL); + g_return_if_fail (filenames[0] != NULL); + uri = filenames[0]; + subtitle = NULL; + + totem_signal_block_by_data (totem->playlist, totem); + + /* Possibly the only place in Totem where it makes sense to add an MRL to the playlist synchronously, since we haven't yet entered + * the GTK+ main loop, and thus can't freeze the application. */ + if (totem_playlist_add_mrl_sync (totem->playlist, uri, NULL) == FALSE) { + totem_signal_unblock_by_data (totem->playlist, totem); + totem_action_set_mrl (totem, NULL, NULL); + g_free (uri); + return; + } + + totem_signal_unblock_by_data (totem->playlist, totem); + + if (totem->index != 0) + totem_playlist_set_current (totem->playlist, totem->index); + mrl = totem_playlist_get_current_mrl (totem->playlist, &subtitle); + + totem_action_set_mrl_with_warning (totem, mrl, subtitle, FALSE); + + /* We do the seeking after being told that the stream is seekable, + * not straight away */ + + g_free (mrl); + g_free (subtitle); +} + +#else + +void +totem_session_add_options (GOptionContext *context) +{ +} + +void +totem_session_setup (Totem *totem, char **argv) +{ +} + +void +totem_session_restore (Totem *totem, char **argv) +{ +} + +#endif /* WITH_SMCLIENT */ diff --git a/pool/shard000/C/0011447_iup_object.c b/pool/shard000/C/0011447_iup_object.c new file mode 100644 index 0000000000000000000000000000000000000000..461e21bbc566e81c443f94de51fd8741168d1d1b --- /dev/null +++ b/pool/shard000/C/0011447_iup_object.c @@ -0,0 +1,188 @@ +/** \file + * \brief Ihandle management + * + * See Copyright Notice in "iup.h" + */ + +#include +#include +#include +#include + +#include "iup.h" + +#include "iup_object.h" +#include "iup_assert.h" +#include "iup_register.h" +#include "iup_names.h" + + +static Ihandle* iHandleCreate(void) +{ + Ihandle *ih = (Ihandle*)malloc(sizeof(Ihandle)); + memset(ih, 0, sizeof(Ihandle)); + + ih->sig[0] = 'I'; + ih->sig[1] = 'U'; + ih->sig[2] = 'P'; + ih->sig[3] = 0; + + ih->serial = -1; + + ih->attrib = iupTableCreate(IUPTABLE_STRINGINDEXED); + + return ih; +} + +static void iHandleDestroy(Ihandle* ih) +{ + iupTableDestroy(ih->attrib); + memset(ih, 0, sizeof(Ihandle)); + free(ih); +} + +int iupObjectCheck(Ihandle* ih) +{ + char* sig = (char*)ih; + + if (!ih) return 0; + + if (sig[0] != 'I' || + sig[1] != 'U' || + sig[2] != 'P' || + sig[3] != 0) + return 0; + + return 1; +} + +Ihandle* iupObjectCreate(Iclass* iclass, void** params) +{ + /* create the base handle structure */ + Ihandle* ih = iHandleCreate(); + + ih->iclass = iclass; + + /* create the element */ + if (iupClassObjectCreate(ih, params) == IUP_ERROR) + { + iupERROR1("IUP object creation failed (%s).", iclass->name); + iHandleDestroy(ih); + return NULL; + } + + /* ensure attributes default values, at this time only the ones that can be set before map */ + iupClassObjectEnsureDefaultAttributes(ih); + + return ih; +} + +void** iupObjectGetParamList(void* first, va_list arglist) +{ + const int INITIAL_NUMBER = 50; + void **params; + void *param; + int max_count = INITIAL_NUMBER, count = 0; + + params = (void **) malloc (sizeof (void *) * INITIAL_NUMBER); + + param = first; + + while (param != NULL) + { + params[count] = param; + count++; + + /* verifica se precisa realocar memoria */ + if (count >= max_count) + { + void **new_params = NULL; + + max_count += INITIAL_NUMBER; + + new_params = (void **) realloc (params, sizeof (void *) * max_count); + + params = new_params; + } + + param = va_arg (arglist, void*); + } + params[count] = NULL; + + return params; +} + +Ihandle* IupCreatev(const char *name, void **params) +{ + Iclass *ic; + iupASSERT(name!=NULL); + ic = iupRegisterFindClass(name); + if (ic) + return iupObjectCreate(ic, params); + else + return NULL; +} + +Ihandle *IupCreatep(const char *name, void* first, ...) +{ + va_list arglist; + void **params; + Ihandle *ih; + iupASSERT(name!=NULL); + + va_start(arglist, first); + params = iupObjectGetParamList(first, arglist); + va_end(arglist); + + ih = IupCreatev(name, params); + free(params); + + return ih; +} + +Ihandle* IupCreate(const char *name) +{ + iupASSERT(name!=NULL); + return IupCreatev(name, NULL); +} + +void IupDestroy(Ihandle *ih) +{ + Icallback cb; + + iupASSERT(iupObjectCheck(ih)); + if (!iupObjectCheck(ih)) + return; + + /* Hide before destroy to avoid children redraw */ + if (ih->iclass->nativetype == IUP_TYPEDIALOG) + IupHide(ih); + + cb = IupGetCallback(ih, "DESTROY_CB"); + if (cb) cb(ih); + + cb = IupGetCallback(ih, "LDESTROY_CB"); /* for language bindings */ + if (cb) cb(ih); + + /* Destroy all its children. + Just need to remove the first child, + IupDetach will update firstchild. */ + while (ih->firstchild) + IupDestroy(ih->firstchild); + + /* unmap if mapped and remove from its parent child list */ + IupDetach(ih); + + /* removes names associated with the element */ + iupRemoveNames(ih); + + /* destroy the element */ + iupClassObjectDestroy(ih); + + /* destroy the private data */ + if (ih->data) + free(ih->data); + + /* destroy the base handle structure */ + iHandleDestroy(ih); +} diff --git a/pool/shard000/C/0011449_main.c b/pool/shard000/C/0011449_main.c new file mode 100644 index 0000000000000000000000000000000000000000..46378a5f81424349e22a520d561741bac1409f73 --- /dev/null +++ b/pool/shard000/C/0011449_main.c @@ -0,0 +1,158 @@ +/* + ChibiOS/RT - Copyright (C) 2006-2013 Giovanni Di Sirio + + 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 "ch.h" +#include "hal.h" + +/* + * Maximum speed SPI configuration. + */ +static const SPIConfig hs_spicfg = { + NULL, + 0, + 0, + SPC5_CTAR_CSSCK_DIV2 | SPC5_CTAR_ASC_DIV2 | SPC5_CTAR_FMSZ(8) | + SPC5_CTAR_PBR_PRE2 | SPC5_CTAR_BR_DIV2, /* CTAR0. */ + SPC5_PUSHR_CONT | SPC5_PUSHR_PCS(1) /* PUSHR. */ +}; + +/* + * Low speed SPI configuration (328.125kHz, CPHA=0, CPOL=0, MSb first). + */ +static const SPIConfig ls_spicfg = { + NULL, + 0, + 0, + SPC5_CTAR_CSSCK_DIV64 | SPC5_CTAR_ASC_DIV64 | SPC5_CTAR_FMSZ(8) | + SPC5_CTAR_PBR_PRE2 | SPC5_CTAR_BR_DIV256, /* CTAR0. */ + SPC5_PUSHR_CONT | SPC5_PUSHR_PCS(0) /* PUSHR. */ +}; + +/* + * SPI TX and RX buffers. + */ +static uint8_t txbuf[512]; +static uint8_t rxbuf[512]; + +/* + * SPI bus contender 1. + */ +static WORKING_AREA(spi_thread_1_wa, 256); +static msg_t spi_thread_1(void *p) { + + (void)p; + chRegSetThreadName("SPI thread 1"); + while (TRUE) { + spiAcquireBus(&SPID2); /* Acquire ownership of the bus. */ + palClearPad(PORT11, P11_LED1); /* LED ON. */ + spiStart(&SPID2, &hs_spicfg); /* Setup transfer parameters. */ + spiSelect(&SPID2); /* Slave Select assertion. */ + spiExchange(&SPID2, 512, + txbuf, rxbuf); /* Atomic transfer operations. */ + spiUnselect(&SPID2); /* Slave Select de-assertion. */ + spiReleaseBus(&SPID2); /* Ownership release. */ + } + return 0; +} + +/* + * SPI bus contender 2. + */ +static WORKING_AREA(spi_thread_2_wa, 256); +static msg_t spi_thread_2(void *p) { + + (void)p; + chRegSetThreadName("SPI thread 2"); + while (TRUE) { + spiAcquireBus(&SPID2); /* Acquire ownership of the bus. */ + palSetPad(PORT11, P11_LED1); /* LED OFF. */ + spiStart(&SPID2, &ls_spicfg); /* Setup transfer parameters. */ + spiSelect(&SPID2); /* Slave Select assertion. */ + spiExchange(&SPID2, 512, + txbuf, rxbuf); /* Atomic transfer operations. */ + spiUnselect(&SPID2); /* Slave Select de-assertion. */ + spiReleaseBus(&SPID2); /* Ownership release. */ + } + return 0; +} + +/* + * Application entry point. + */ +int main(void) { + unsigned i; + + /* + * System initializations. + * - HAL initialization, this also initializes the configured device drivers + * and performs the board-specific initializations. + * - Kernel initialization, the main() function becomes a thread and the + * RTOS is active. + */ + halInit(); + chSysInit(); + + /* + * Prepare transmit pattern. + */ + for (i = 0; i < sizeof(txbuf); i++) + txbuf[i] = (uint8_t)i; + + /* Starting driver for test, DSPI_B I/O pins setup.*/ + spiStart(&SPID2, &ls_spicfg); + SIU.PCR[102].R = PAL_MODE_OUTPUT_ALTERNATE(1); /* SCK */ + SIU.PCR[103].R = PAL_MODE_OUTPUT_ALTERNATE(1); /* SIN */ + SIU.PCR[104].R = PAL_MODE_OUTPUT_ALTERNATE(1); /* SOUT */ + SIU.PCR[105].R = PAL_MODE_OUTPUT_ALTERNATE(1); /* PCS[0] */ + SIU.PCR[106].R = PAL_MODE_OUTPUT_ALTERNATE(1); /* PCS[1] */ + + /* Testing sending and receiving at the same time.*/ + spiExchange(&SPID2, 4, txbuf, rxbuf); + spiExchange(&SPID2, 32, txbuf, rxbuf); + spiExchange(&SPID2, 512, txbuf, rxbuf); + + /* Testing clock pulses without data buffering.*/ + spiIgnore(&SPID2, 4); + spiIgnore(&SPID2, 32); + + /* Testing sending data ignoring incoming data.*/ + spiSend(&SPID2, 4, txbuf); + spiSend(&SPID2, 32, txbuf); + + /* Testing receiving data while sending idle bits (high level).*/ + spiReceive(&SPID2, 4, rxbuf); + spiReceive(&SPID2, 32, rxbuf); + + /* Testing stop procedure.*/ + spiStop(&SPID2); + + /* + * Starting the transmitter and receiver threads. + */ + chThdCreateStatic(spi_thread_1_wa, sizeof(spi_thread_1_wa), + NORMALPRIO + 1, spi_thread_1, NULL); + chThdCreateStatic(spi_thread_2_wa, sizeof(spi_thread_2_wa), + NORMALPRIO + 1, spi_thread_2, NULL); + + /* + * Normal main() thread activity, in this demo it does nothing. + */ + while (TRUE) { + chThdSleepMilliseconds(500); + palTogglePad(PORT11, P11_LED2); + } + return 0; +} diff --git a/pool/shard000/C/0011463_input.c b/pool/shard000/C/0011463_input.c new file mode 100644 index 0000000000000000000000000000000000000000..3ad89333794c5b7c21fc3586ed914da19f0ab37d --- /dev/null +++ b/pool/shard000/C/0011463_input.c @@ -0,0 +1,145 @@ +/* + * input.c + * Defines some utilities for inputting files, currently only for 24 bit *.bmp + * type files, other types to be added in a later release. + * + * TODO: error on bad files + * TODO: check that files are of the 24bit bmp format, I think this can be... + * read in from the header + * + * Created on: May 13, 2016 + * Author: Zach Oakes + */ + +#include "pixels.h" +#include +#include + +FILE* inInit(const char* name) { + FILE* temp; + temp = fopen(name, "rb"); + if (temp == NULL) { + perror("could not open input file"); + exit(-4); + } + return temp; +} + +//gets the size of the file from the header +// todo: check it against the actual size of the file, should be the same +unsigned int getSize(FILE* myFile) { + fseek(myFile, 2, SEEK_SET); + unsigned int filesize = 0; + char i; + for (i = 0; i <= 3; i++) { + filesize += (unsigned int) fgetc(myFile) << (i * 8); + } + rewind(myFile); + return filesize; +} + +//gets the location of the start of the pixel data from the file +unsigned int getStart(FILE*myFile) { + fseek(myFile, 0xA, SEEK_SET); + unsigned int arrStart = 0; + char i; + for (i = 0; i <= 3; i++) { + arrStart += (unsigned int) fgetc(myFile) << (i * 8); + } + rewind(myFile); + return arrStart; +} + +//gets the width of the image (in pixels) from the header data +//this is signed because it's signed in the spec +signed int getWidth(FILE* myFile) { + fseek(myFile, 0x12, SEEK_SET); + signed int width = 0; + char i; + for (i = 0; i <= 3; i++) { + width += (signed int) (fgetc(myFile) << (i * 8)); + } + rewind(myFile); + return width; +} + +//gets the height of the image in pixels from the header data +//signed because it is in the spec +signed int getHeight(FILE* myFile) { + fseek(myFile, 0x16, SEEK_SET); + signed int height = 0; + char i; + for (i = 0; i <= 3; i++) { + height += (signed int) fgetc(myFile) << (i * 8); + } + rewind(myFile); + return height; +} + +unsigned int getNumPixels(FILE* myFile) { + return (getWidth(myFile) * getHeight(myFile)); +} + +//get the header from the input image and store it to an array, mallocing enough +//memory so that we can fit the whole file in the array +unsigned char* getHeader(FILE*myFile) { + unsigned int size; + size = getStart(myFile) - 1; + unsigned char*array; + array = malloc(size); + if (array == NULL) { + perror("error while allocating memory see input/initArray"); + exit(-1); + } + unsigned int i; + for (i = 0; i < size; i++) { + char temp = fgetc(myFile); + if (temp != EOF) { + *(array + i) = temp; + } else { + perror("error in input/getHeader, end of file reached"); + exit(-3); + } + } + rewind(myFile); + return array; +} + +//todo: make this more efficient +pixel* makePixelArray(FILE* myFile) { + signed int height = getHeight(myFile); + signed int width = getWidth(myFile); + + //see wikipedia article /wiki/BMP_file_format for why this works + unsigned int rowSize = (((24 * width) + 31) / 32) * 4; + unsigned int paddingLen = (rowSize - (width * 3)); + + pixel* image; + unsigned int numPix = getNumPixels(myFile); + image = malloc((sizeof(pixel)) * (numPix)); + if (image == NULL) { + perror("error allocating memory (input/makePixelArray)"); + exit(-1); + } + + fseek(myFile, getStart(myFile), SEEK_SET); + + unsigned int arraySize = rowSize * height; + unsigned int i = 0, whichByte = 0; + while(whichByte < arraySize) { + if ((whichByte % rowSize) < (width * 3)) { + image[i].blu = fgetc(myFile); + image[i].grn = fgetc(myFile); + image[i].red = fgetc(myFile); + image[i].tot_rgb = image[i].blu + image[i].grn + image[i].red; + whichByte += 3; + i++; + } else { + fseek(myFile, paddingLen, SEEK_CUR); + whichByte += paddingLen; + + } + } + + return image; +} diff --git a/pool/shard000/C/0011468_gentan.c b/pool/shard000/C/0011468_gentan.c new file mode 100644 index 0000000000000000000000000000000000000000..505d6042f7666faf87d921dea54b6cf048447649 --- /dev/null +++ b/pool/shard000/C/0011468_gentan.c @@ -0,0 +1,142 @@ +/* + * Copyright (C) Bull S.A. 2001 + * Copyright (c) International Business Machines Corp., 2001 + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See + * the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/******************************************************************************/ +/* */ +/* Dec-03-2001 Created: Jacky Malcles & Jean Noel Cordenner */ +/* These tests are adapted from AIX float PVT tests. */ +/* */ +/******************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define M_PIl 3.1415926535897932384626433832795029L + +int create_Result_file() +{ + + int i, nbVal; + double tabRtan[20000], Inc; + char *F_name; + int fp; + + F_name = "rtan"; + nbVal = 20000; + + Inc = (2 * M_PIl) / nbVal; /* condering a period of 2 pi rad */ + + for (i = 0; i < nbVal; i++) { + if ((Inc * i) != (M_PIl / 2)) + tabRtan[i] = tan(Inc * i); + else + tabRtan[i] = tan(0); + } + + fp = open(F_name, O_RDWR | O_CREAT | O_TRUNC, 0777); + if (!fp) { + printf("error opening file"); + close(fp); + return -1; + } else { + for (i = 0; i < nbVal; i++) { + write(fp, &tabRtan[i], sizeof(double)); + } + + close(fp); + return 0; + } +} + +int create_Data_file() +{ + int i, nbVal; + double tabDtan[20000], Inc; + char *F_name; + int fp; + + F_name = "dtan"; + nbVal = 20000; + + Inc = (2 * M_PIl) / nbVal; /* condering a period of 2 pi rad */ + + for (i = 0; i < nbVal; i++) { + if ((Inc * i) != (M_PIl / 2)) + tabDtan[i] = (Inc * i); + else + tabDtan[i] = 0; + } + + fp = open(F_name, O_RDWR | O_CREAT | O_TRUNC, 0777); + if (!fp) { + printf("error opening file"); + close(fp); + return -1; + } else { + for (i = 0; i < nbVal; i++) { + write(fp, &tabDtan[i], sizeof(double)); + } + close(fp); + return 0; + } +} + +int main(int argc, char *argv[]) +{ + + if (argc > 1) { + switch (atoi(argv[1])) { + case 1: + if (create_Data_file() == 0) + printf("Data file created\n"); + else + printf + ("problem during tan data file creation\n"); + break; + + case 2: + if (create_Result_file() == 0) + printf("Result file created\n"); + else + printf + ("problem during tan result file creation\n"); + break; + default: + printf("Bad arglist code for: '%s'\n", argv[0]); + return -1; + break; + } + } else { + if (create_Data_file() != 0) + printf("problem during tan data file creation\n"); + if (create_Result_file() != 0) + printf("problem during tan result file creation\n"); + } + + return (0); + +} diff --git a/pool/shard000/C/0011472_func_blacklist.c b/pool/shard000/C/0011472_func_blacklist.c new file mode 100644 index 0000000000000000000000000000000000000000..be3bbc5fbd723a87b751fe0de0112c05cef4ace3 --- /dev/null +++ b/pool/shard000/C/0011472_func_blacklist.c @@ -0,0 +1,109 @@ +/* + * Asterisk -- An open source telephony toolkit. + * + * Copyright (C) 1999 - 2005, Digium, Inc. + * + * Mark Spencer + * + * See http://www.asterisk.org for more information about + * the Asterisk project. Please do not directly contact + * any of the maintainers of this project for assistance; + * the project provides a web site, mailing lists and IRC + * channels for your use. + * + * This program is free software, distributed under the terms of + * the GNU General Public License Version 2. See the LICENSE file + * at the top of the source tree. + */ + +/*! \file + * + * \brief Function to lookup the callerid number, and see if it is blacklisted + * + * \author Mark Spencer + * + * \ingroup functions + * + */ + +/*** MODULEINFO + core + ***/ + +#include "asterisk.h" + +ASTERISK_FILE_VERSION(__FILE__, "$Revision$") + +#include "asterisk/pbx.h" +#include "asterisk/module.h" +#include "asterisk/channel.h" +#include "asterisk/astdb.h" + +/*** DOCUMENTATION + + + Check if the callerid is on the blacklist. + + + + Uses astdb to check if the Caller*ID is in family blacklist. + Returns 1 or 0. + + + DB + + + +***/ + +static int blacklist_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len) +{ + char blacklist[1]; + int bl = 0; + + if (chan->caller.id.number.valid && chan->caller.id.number.str) { + if (!ast_db_get("blacklist", chan->caller.id.number.str, blacklist, sizeof (blacklist))) + bl = 1; + } + if (chan->caller.id.name.valid && chan->caller.id.name.str) { + if (!ast_db_get("blacklist", chan->caller.id.name.str, blacklist, sizeof (blacklist))) + bl = 1; + } + + snprintf(buf, len, "%d", bl); + return 0; +} + +static int blacklist_read2(struct ast_channel *chan, const char *cmd, char *data, struct ast_str **str, ssize_t len) +{ + /* 2 bytes is a single integer, plus terminating null */ + if (ast_str_size(*str) - ast_str_strlen(*str) < 2) { + if (len > ast_str_size(*str) || len == 0) { + ast_str_make_space(str, len ? len : ast_str_strlen(*str) + 2); + } + } + if (ast_str_size(*str) - ast_str_strlen(*str) >= 2) { + int res = blacklist_read(chan, cmd, data, ast_str_buffer(*str) + ast_str_strlen(*str), 2); + ast_str_update(*str); + return res; + } + return -1; +} + +static struct ast_custom_function blacklist_function = { + .name = "BLACKLIST", + .read = blacklist_read, + .read2 = blacklist_read2, +}; + +static int unload_module(void) +{ + return ast_custom_function_unregister(&blacklist_function); +} + +static int load_module(void) +{ + return ast_custom_function_register(&blacklist_function); +} + +AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Look up Caller*ID name/number from blacklist database"); diff --git a/pool/shard000/C/0011478_sumh.c b/pool/shard000/C/0011478_sumh.c new file mode 100644 index 0000000000000000000000000000000000000000..9701597d3568dbc7bcb0e5edb53895a337833681 --- /dev/null +++ b/pool/shard000/C/0011478_sumh.c @@ -0,0 +1,137 @@ +/* + * This file is part of Cleanflight. + * + * Cleanflight 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. + * + * Cleanflight 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 Cleanflight. If not, see . + */ + +/* + * References: + * http://fpv-treff.de/viewtopic.php?f=18&t=1368&start=3020#p44535 + * http://fpv-community.de/showthread.php?29033-MultiWii-mit-Graupner-SUMD-SUMH-und-USB-Joystick-auf-ProMicro + */ + +#include +#include +#include + +#include "platform.h" + +#include "build/build_config.h" + + +#include "drivers/system.h" + +#include "drivers/serial.h" +#include "drivers/serial_uart.h" +#include "io/serial.h" + +#include "rx/rx.h" +#include "rx/sumh.h" + +// driver for SUMH receiver using UART2 + +#define SUMH_BAUDRATE 115200 + +#define SUMH_MAX_CHANNEL_COUNT 8 +#define SUMH_FRAME_SIZE 21 + +static bool sumhFrameDone = false; + +static uint8_t sumhFrame[SUMH_FRAME_SIZE]; +static uint32_t sumhChannels[SUMH_MAX_CHANNEL_COUNT]; + +static void sumhDataReceive(uint16_t c); +static uint16_t sumhReadRawRC(rxRuntimeConfig_t *rxRuntimeConfig, uint8_t chan); + +static serialPort_t *sumhPort; + + +static void sumhDataReceive(uint16_t c); +static uint16_t sumhReadRawRC(rxRuntimeConfig_t *rxRuntimeConfig, uint8_t chan); + + + +bool sumhInit(rxConfig_t *rxConfig, rxRuntimeConfig_t *rxRuntimeConfig, rcReadRawDataPtr *callback) +{ + UNUSED(rxConfig); + + if (callback) + *callback = sumhReadRawRC; + + rxRuntimeConfig->channelCount = SUMH_MAX_CHANNEL_COUNT; + + serialPortConfig_t *portConfig = findSerialPortConfig(FUNCTION_RX_SERIAL); + if (!portConfig) { + return false; + } + + sumhPort = openSerialPort(portConfig->identifier, FUNCTION_RX_SERIAL, sumhDataReceive, SUMH_BAUDRATE, MODE_RX, SERIAL_NOT_INVERTED); + + return sumhPort != NULL; +} + +// Receive ISR callback +static void sumhDataReceive(uint16_t c) +{ + uint32_t sumhTime; + static uint32_t sumhTimeLast, sumhTimeInterval; + static uint8_t sumhFramePosition; + + sumhTime = micros(); + sumhTimeInterval = sumhTime - sumhTimeLast; + sumhTimeLast = sumhTime; + if (sumhTimeInterval > 5000) { + sumhFramePosition = 0; + } + + sumhFrame[sumhFramePosition] = (uint8_t) c; + if (sumhFramePosition == SUMH_FRAME_SIZE - 1) { + // FIXME at this point the value of 'c' is unused and un tested, what should it be, is it important? + sumhFrameDone = true; + } else { + sumhFramePosition++; + } +} + +uint8_t sumhFrameStatus(void) +{ + uint8_t channelIndex; + + if (!sumhFrameDone) { + return SERIAL_RX_FRAME_PENDING; + } + + sumhFrameDone = false; + + if (!((sumhFrame[0] == 0xA8) && (sumhFrame[SUMH_FRAME_SIZE - 2] == 0))) { + return SERIAL_RX_FRAME_PENDING; + } + + for (channelIndex = 0; channelIndex < SUMH_MAX_CHANNEL_COUNT; channelIndex++) { + sumhChannels[channelIndex] = (((uint32_t)(sumhFrame[(channelIndex << 1) + 3]) << 8) + + sumhFrame[(channelIndex << 1) + 4]) / 6.4f - 375; + } + return SERIAL_RX_FRAME_COMPLETE; +} + +static uint16_t sumhReadRawRC(rxRuntimeConfig_t *rxRuntimeConfig, uint8_t chan) +{ + UNUSED(rxRuntimeConfig); + + if (chan >= SUMH_MAX_CHANNEL_COUNT) { + return 0; + } + + return sumhChannels[chan]; +} diff --git a/pool/shard000/C/0011499_FreeTrackClient_main.c b/pool/shard000/C/0011499_FreeTrackClient_main.c new file mode 100644 index 0000000000000000000000000000000000000000..2958306cd89a6b501a0d4a3d83e4e1295081d676 --- /dev/null +++ b/pool/shard000/C/0011499_FreeTrackClient_main.c @@ -0,0 +1,171 @@ +/* + * FreeTrackClient.dll + * + * Generated from FreeTrackClient.dll by winedump. + * + * DO NOT SUBMIT GENERATED DLLS FOR INCLUSION INTO WINE! + * + */ + +#include +#include +#include + +#define __WINESRC__ +#include "windef.h" +#include "winbase.h" +#include "FreeTrackClient_dll.h" +#include +#include "wine/debug.h" +#include + +WINE_DEFAULT_DEBUG_CHANNEL(FreeTrackClient); + + +typedef enum {DBG_CHECK, DBG_ON, DBG_OFF} dbg_flag_type; +static dbg_flag_type dbg_flag; +static float blobs[MAX_BLOBS * 3]; + +static dbg_flag_type get_dbg_flag(const int flag) +{ + char *dbg_flags = getenv("LINUXTRACK_DBG"); + if(dbg_flags == NULL) return DBG_OFF; + if(strchr(dbg_flags, flag) != NULL){ + return DBG_ON; + }else{ + return DBG_OFF; + } +} + + + +static void dbg_report(const char *msg,...) +{ + static FILE *f = NULL; + if(dbg_flag == DBG_ON){ + if(f == NULL){ + f = fopen("FTClient.log", "w"); + } + va_list ap; + va_start(ap,msg); + vfprintf(f, msg, ap); + fflush(f); + va_end(ap); + } +} + + +BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) +{ + TRACE("(0x%p, %d, %p)\n", hinstDLL, fdwReason, lpvReserved); + + switch (fdwReason) + { + case DLL_WINE_PREATTACH: + return TRUE; + case DLL_PROCESS_ATTACH: + DisableThreadLibraryCalls(hinstDLL); + dbg_flag = get_dbg_flag('w'); + dbg_report("Attach request\n"); + break; + case DLL_PROCESS_DETACH: + linuxtrack_shutdown(); + break; + } + + return TRUE; +} +/****************************************************************** + * FTProvider (FREETRACKCLIENT.1) + * + * + */ +char * __stdcall FREETRACKCLIENT_FTProvider(void) +{ + return "Freetrack"; +} +/****************************************************************** + * FTGetDllVersion (FREETRACKCLIENT.2) + * + * + */ +char * __stdcall FREETRACKCLIENT_FTGetDllVersion(void) +{ + return (char *) "1.0.0.266"; +} +/****************************************************************** + * FTReportName (FREETRACKCLIENT.3) + * + * + */ +void __stdcall FREETRACKCLIENT_FTReportName(char * name) +{ + linuxtrack_init(name); +} +/****************************************************************** + * FTGetData (FREETRACKCLIENT.4) + * + * + */ +bool __stdcall FREETRACKCLIENT_FTGetData(FreeTrackData * data) +{ + linuxtrack_pose_t pose; + int read = 0; + linuxtrack_get_pose_full(&pose, blobs, MAX_BLOBS, &read); + data->yaw = pose.yaw; + data->pitch = pose.pitch; + data->roll = pose.roll; + data->x = pose.tx; + data->y = pose.ty; + data->z = pose.tz; + + data->ryaw = pose.raw_yaw; + data->rpitch = pose.raw_pitch; + data->rroll = pose.raw_roll; + data->rx = pose.raw_tx; + data->ry = pose.raw_ty; + data->rz = pose.raw_tz; + //will add sorting, if needed + if(read > 0){ + data->x0 = blobs[0]; + data->y0 = blobs[1]; + }else{ + data->x0 = 0.0; + data->y0 = 0.0; + } + if(read > 1){ + data->x1 = blobs[3]; + data->y1 = blobs[4]; + }else{ + data->x1 = 0.0; + data->y1 = 0.0; + } + if(read > 2){ + data->x2 = blobs[6]; + data->y2 = blobs[7]; + }else{ + data->x2 = 0.0; + data->y2 = 0.0; + } + if(read > 3){ + data->x3 = blobs[9]; + data->y3 = blobs[10]; + }else{ + data->x3 = 0.0; + data->y3 = 0.0; + } + data->res_x = pose.resolution_x; data->res_y = pose.resolution_y; + data->dataID = pose.counter; + return TRUE; +} + +/* +yaw +to the left +pitch + up +roll + to the left +x + to the left +y + up +z + back + +Points sort by y; +*/ diff --git a/pool/shard000/C/0011508_main.c b/pool/shard000/C/0011508_main.c new file mode 100644 index 0000000000000000000000000000000000000000..f4a6537b74a0c703415b66d6931c05eaab1dfb46 --- /dev/null +++ b/pool/shard000/C/0011508_main.c @@ -0,0 +1,197 @@ +#include +#include +#include +#include "utils.h" + +gchar* mountCommand; +gchar* alwaysMounts; +gchar* openCommand; +gchar* confFile; +gchar* rulesDir; +gchar* pidFile; +gchar* commandOnInputDevice; +gchar* logFile; + + + +void init() +{ + gchar* pid= g_strdup_printf("%d",getpid()); + + + alwaysMounts=GetKey(confFile,"Main" ,"alwaysMounts"); + mountCommand=GetKey(confFile,"Main" ,"mountCommand"); + openCommand=GetKey(confFile,"Main" ,"openCommand"); + commandOnInputDevice=GetKey(confFile,"Main" ,"commandOnInputDevice"); + logFile=GetKey(confFile,"Main" ,"logFile"); + pidFile=GetKey(confFile,"Main" ,"pidFile"); + if (pidFile!=NULL && g_strrstr (pidFile, "" )!=NULL) g_file_set_contents (pidFile,pid, -1,NULL); + + +} + + +void eventDiskCallback(GFileMonitor *monitor, + GFile *file, + GFile *other_file, + GFileMonitorEvent event_type, + gpointer user_data) +{ + gchar* cmd; + GError *error = NULL; + gchar* deviceFile=g_file_get_path (file); + + + if (event_type==G_FILE_MONITOR_EVENT_CREATED) putLog("Device %s is connected. \n", deviceFile); + if (event_type==G_FILE_MONITOR_EVENT_DELETED) putLog("Device %s is disconnected. \n", deviceFile); + if (event_type==G_FILE_MONITOR_EVENT_CHANGED) putLog("Device %s is changed. \n", deviceFile); + + //Try to mount partition + if (event_type==G_FILE_MONITOR_EVENT_CREATED && \ + g_strrstr (alwaysMounts, "yes")!=NULL && \ + g_strrstr (deviceFile, "-part")!=NULL) + { + + //Mount device + cmd=g_strdup_printf(mountCommand, deviceFile); + g_spawn_command_line_async (cmd, &error); + if (error!=NULL) { g_print(error->message); g_error_free (error);} + + //Execute openCommand on mount point + gchar* mountPoint=getMountByDevice(getDeviceById(deviceFile)); + g_print("Mounted on %s\n", mountPoint); + + cmd=g_strdup_printf("%s '%s'",openCommand, mountPoint); + if(openCommand!=NULL) + { + g_spawn_command_line_async (cmd, &error); + if (error!=NULL) { g_print(error->message); g_error_free (error);} + } + } + + //Try parsing rules when device is connected + if (event_type==G_FILE_MONITOR_EVENT_CREATED && \ + g_strrstr (deviceFile, "-part")!=NULL) + { + scanConnectedRules(deviceFile); + } + + //Try parsing rules when device is disconnected + if (event_type==G_FILE_MONITOR_EVENT_DELETED && \ + g_strrstr (deviceFile, "-part")!=NULL) + { + scanDisconnectedRules(deviceFile); + } + + +} + +void eventInputCallback(GFileMonitor *monitor, + GFile *file, + GFile *other_file, + GFileMonitorEvent event_type, + gpointer user_data) +{ + gchar* cmd; + GError *error = NULL; + gchar* deviceFile=g_file_get_path (file); + + + if (event_type==G_FILE_MONITOR_EVENT_CREATED) putLog("Device %s is connected. \n", deviceFile); + if (event_type==G_FILE_MONITOR_EVENT_DELETED) putLog("Device %s is disconnected. \n", deviceFile); + if (event_type==G_FILE_MONITOR_EVENT_CHANGED) putLog("Device %s is changed. \n", deviceFile); + + + + //Try parsing rules when device is connected + if (event_type==G_FILE_MONITOR_EVENT_CREATED ) + { + //Command on input device + cmd=g_strdup_printf(commandOnInputDevice, deviceFile); + g_spawn_command_line_async (cmd, &error); + if (error!=NULL) { g_print(error->message); g_error_free (error);} + + scanConnectedRules(deviceFile); + } + + //Try parsing rules when device is disconnected + if (event_type==G_FILE_MONITOR_EVENT_DELETED) + { + scanDisconnectedRules(deviceFile); + } + + +} + + + +int main(int argc, char** argv ) +{ + GError *error = NULL; + + //Parsing commandline + static GOptionEntry entries[] = + { + { "conf", 'c', 0, G_OPTION_ARG_STRING, &confFile, "Custom config file", "" }, + { NULL } + }; + + + GOptionContext *context; + + context = g_option_context_new ("- Start gino with a custom config file"); + g_option_context_add_main_entries (context, entries, NULL); + //g_option_context_add_group (context, gtk_get_option_group (TRUE)); + if (!g_option_context_parse (context, &argc, &argv, &error)) + { + g_print ("Option parsing failed: %s\n", error->message); + exit (1); + } + if (confFile==NULL) makeConfDirs(); + + + //Gino Init + init(); + + //Main glib Loop + GMainLoop *loop; + loop = g_main_loop_new ( NULL , FALSE ); + + //Disk monitor + GFile *dirDisks= g_file_new_for_path ("/dev/disk/by-id/"); + GFileMonitor *diskMonitor=g_file_monitor_directory (dirDisks, + G_FILE_MONITOR_NONE, + NULL, + &error); + if (error!=NULL) + { + g_error("I can't make a monitor : %s\n",error->message); + g_error_free (error); + } + + //Generic Input monitor + GFile *dirInput= g_file_new_for_path ("/dev/input/by-id/"); + GFileMonitor *inputMonitor=g_file_monitor_directory (dirInput, + G_FILE_MONITOR_NONE, + NULL, + &error); + if (error!=NULL) + { + g_error("I can't make a monitor : %s\n",error->message); + g_error_free (error); + } + + + //Main events callbacks + g_signal_connect (diskMonitor, "changed", G_CALLBACK(eventDiskCallback), NULL); + g_signal_connect (inputMonitor, "changed", G_CALLBACK(eventInputCallback), NULL); + + //run main Glib Loop + g_main_loop_run (loop); + g_main_loop_unref(loop); + + + + + return 0; +} diff --git a/pool/shard000/C/0011510_yuv2rgb.c b/pool/shard000/C/0011510_yuv2rgb.c new file mode 100644 index 0000000000000000000000000000000000000000..cceca49ca825fd9ac4522614b84253c8aab9b822 --- /dev/null +++ b/pool/shard000/C/0011510_yuv2rgb.c @@ -0,0 +1,112 @@ +/* + * software YUV to RGB converter + * + * Copyright (C) 2009 Konstantin Shishkov + * + * MMX/MMXEXT template stuff (needed for fast movntq support), + * 1,4,8bpp support and context / deglobalize stuff + * by Michael Niedermayer (michaelni@gmx.at) + * + * This file is part of FFmpeg. + * + * FFmpeg is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * FFmpeg is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with FFmpeg; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include +#include +#include + +#include "config.h" +#include "libswscale/rgb2rgb.h" +#include "libswscale/swscale.h" +#include "libswscale/swscale_internal.h" +#include "libavutil/attributes.h" +#include "libavutil/x86/asm.h" +#include "libavutil/cpu.h" + +#if HAVE_INLINE_ASM + +#define DITHER1XBPP // only for MMX + +/* hope these constant values are cache line aligned */ +DECLARE_ASM_CONST(8, uint64_t, mmx_00ffw) = 0x00ff00ff00ff00ffULL; +DECLARE_ASM_CONST(8, uint64_t, mmx_redmask) = 0xf8f8f8f8f8f8f8f8ULL; +DECLARE_ASM_CONST(8, uint64_t, mmx_grnmask) = 0xfcfcfcfcfcfcfcfcULL; +DECLARE_ASM_CONST(8, uint64_t, pb_e0) = 0xe0e0e0e0e0e0e0e0ULL; +DECLARE_ASM_CONST(8, uint64_t, pb_03) = 0x0303030303030303ULL; +DECLARE_ASM_CONST(8, uint64_t, pb_07) = 0x0707070707070707ULL; + +//MMX versions +#if HAVE_MMX_INLINE +#undef RENAME +#undef COMPILE_TEMPLATE_MMXEXT +#define COMPILE_TEMPLATE_MMXEXT 0 +#define RENAME(a) a ## _MMX +#include "yuv2rgb_template.c" +#endif /* HAVE_MMX_INLINE */ + +// MMXEXT versions +#if HAVE_MMXEXT_INLINE +#undef RENAME +#undef COMPILE_TEMPLATE_MMXEXT +#define COMPILE_TEMPLATE_MMXEXT 1 +#define RENAME(a) a ## _MMXEXT +#include "yuv2rgb_template.c" +#endif /* HAVE_MMXEXT_INLINE */ + +#endif /* HAVE_INLINE_ASM */ + +av_cold SwsFunc ff_yuv2rgb_init_mmx(SwsContext *c) +{ +#if HAVE_INLINE_ASM + int cpu_flags = av_get_cpu_flags(); + +#if HAVE_MMXEXT_INLINE + if (cpu_flags & AV_CPU_FLAG_MMXEXT) { + switch (c->dstFormat) { + case AV_PIX_FMT_RGB24: + return yuv420_rgb24_MMXEXT; + case AV_PIX_FMT_BGR24: + return yuv420_bgr24_MMXEXT; + } + } +#endif + + if (cpu_flags & AV_CPU_FLAG_MMX) { + switch (c->dstFormat) { + case AV_PIX_FMT_RGB32: + if (c->srcFormat == AV_PIX_FMT_YUVA420P) { +#if HAVE_7REGS && CONFIG_SWSCALE_ALPHA + return yuva420_rgb32_MMX; +#endif + break; + } else return yuv420_rgb32_MMX; + case AV_PIX_FMT_BGR32: + if (c->srcFormat == AV_PIX_FMT_YUVA420P) { +#if HAVE_7REGS && CONFIG_SWSCALE_ALPHA + return yuva420_bgr32_MMX; +#endif + break; + } else return yuv420_bgr32_MMX; + case AV_PIX_FMT_RGB24: return yuv420_rgb24_MMX; + case AV_PIX_FMT_BGR24: return yuv420_bgr24_MMX; + case AV_PIX_FMT_RGB565: return yuv420_rgb16_MMX; + case AV_PIX_FMT_RGB555: return yuv420_rgb15_MMX; + } + } +#endif /* HAVE_INLINE_ASM */ + + return NULL; +} diff --git a/pool/shard000/C/0011512_max_record.c b/pool/shard000/C/0011512_max_record.c new file mode 100644 index 0000000000000000000000000000000000000000..002c306d8c62bf694cba2b002698763278195766 --- /dev/null +++ b/pool/shard000/C/0011512_max_record.c @@ -0,0 +1,328 @@ +/* + * Copyright (C) 2001-2012 Free Software Foundation, Inc. + * + * Author: Nikos Mavrogiannopoulos + * + * This file is part of GnuTLS. + * + * The GnuTLS is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License + * as published by the Free Software Foundation; either version 3 of + * the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see + * + */ + +/* This file contains the code for the Max Record Size TLS extension. + */ + +#include "gnutls_int.h" +#include "gnutls_errors.h" +#include "gnutls_num.h" +#include +#include + +static int _gnutls_max_record_recv_params (gnutls_session_t session, + const uint8_t * data, + size_t data_size); +static int _gnutls_max_record_send_params (gnutls_session_t session, + gnutls_buffer_st* extdata); + +static int _gnutls_max_record_unpack (gnutls_buffer_st * ps, + extension_priv_data_t * _priv); +static int _gnutls_max_record_pack (extension_priv_data_t _priv, + gnutls_buffer_st * ps); + +/* Maps record size to numbers according to the + * extensions draft. + */ +static int _gnutls_mre_num2record (int num); +static int _gnutls_mre_record2num (uint16_t record_size); + + +extension_entry_st ext_mod_max_record_size = { + .name = "MAX RECORD SIZE", + .type = GNUTLS_EXTENSION_MAX_RECORD_SIZE, + .parse_type = GNUTLS_EXT_TLS, + + .recv_func = _gnutls_max_record_recv_params, + .send_func = _gnutls_max_record_send_params, + .pack_func = _gnutls_max_record_pack, + .unpack_func = _gnutls_max_record_unpack, + .deinit_func = NULL +}; + +/* + * In case of a server: if a MAX_RECORD_SIZE extension type is received then it stores + * into the session the new value. The server may use gnutls_get_max_record_size(), + * in order to access it. + * + * In case of a client: If a different max record size (than the default) has + * been specified then it sends the extension. + * + */ + +static int +_gnutls_max_record_recv_params (gnutls_session_t session, + const uint8_t * data, size_t _data_size) +{ + ssize_t new_size; + ssize_t data_size = _data_size; + extension_priv_data_t epriv; + int ret; + + if (session->security_parameters.entity == GNUTLS_SERVER) + { + if (data_size > 0) + { + DECR_LEN (data_size, 1); + + new_size = _gnutls_mre_num2record (data[0]); + + if (new_size < 0) + { + gnutls_assert (); + return new_size; + } + + session->security_parameters.max_record_send_size = new_size; + session->security_parameters.max_record_recv_size = new_size; + } + } + else + { /* CLIENT SIDE - we must check if the sent record size is the right one + */ + if (data_size > 0) + { + ret = _gnutls_ext_get_session_data (session, + GNUTLS_EXTENSION_MAX_RECORD_SIZE, + &epriv); + if (ret < 0) + { + gnutls_assert (); + return GNUTLS_E_INTERNAL_ERROR; + } + + if (data_size != 1) + { + gnutls_assert (); + return GNUTLS_E_UNEXPECTED_PACKET_LENGTH; + } + + new_size = _gnutls_mre_num2record (data[0]); + + if (new_size < 0 || new_size != epriv.num) + { + gnutls_assert (); + return GNUTLS_E_RECEIVED_ILLEGAL_PARAMETER; + } + else + { + session->security_parameters.max_record_recv_size = epriv.num; + } + + } + + + } + + return 0; +} + +/* returns data_size or a negative number on failure + */ +static int +_gnutls_max_record_send_params (gnutls_session_t session, gnutls_buffer_st* extdata) +{ + uint8_t p; + int ret; + + /* this function sends the client extension data (dnsname) */ + if (session->security_parameters.entity == GNUTLS_CLIENT) + { + extension_priv_data_t epriv; + + ret = _gnutls_ext_get_session_data (session, + GNUTLS_EXTENSION_MAX_RECORD_SIZE, + &epriv); + if (ret < 0) /* it is ok not to have it */ + { + return 0; + } + + if (epriv.num != DEFAULT_MAX_RECORD_SIZE) + { + p = (uint8_t) _gnutls_mre_record2num (epriv.num); + ret = _gnutls_buffer_append_data( extdata, &p, 1); + if (ret < 0) + return gnutls_assert_val(ret); + + return 1; + } + + } + else + { /* server side */ + + if (session->security_parameters.max_record_recv_size != + DEFAULT_MAX_RECORD_SIZE) + { + p = + (uint8_t) + _gnutls_mre_record2num + (session->security_parameters.max_record_recv_size); + + ret = _gnutls_buffer_append_data( extdata, &p, 1); + if (ret < 0) + return gnutls_assert_val(ret); + + return 1; + } + } + + return 0; +} + + +static int +_gnutls_max_record_pack (extension_priv_data_t epriv, gnutls_buffer_st * ps) +{ + int ret; + + BUFFER_APPEND_NUM (ps, epriv.num); + + return 0; + +} + +static int +_gnutls_max_record_unpack (gnutls_buffer_st * ps, + extension_priv_data_t * _priv) +{ + extension_priv_data_t epriv; + int ret; + + BUFFER_POP_NUM (ps, epriv.num); + + *_priv = epriv; + + ret = 0; +error: + return ret; +} + + +/* Maps numbers to record sizes according to the + * extensions draft. + */ +static int +_gnutls_mre_num2record (int num) +{ + switch (num) + { + case 1: + return 512; + case 2: + return 1024; + case 3: + return 2048; + case 4: + return 4096; + default: + return GNUTLS_E_RECEIVED_ILLEGAL_PARAMETER; + } +} + +/* Maps record size to numbers according to the + * extensions draft. + */ +static int +_gnutls_mre_record2num (uint16_t record_size) +{ + switch (record_size) + { + case 512: + return 1; + case 1024: + return 2; + case 2048: + return 3; + case 4096: + return 4; + default: + return GNUTLS_E_RECEIVED_ILLEGAL_PARAMETER; + } + +} + +/** + * gnutls_record_get_max_size: + * @session: is a #gnutls_session_t structure. + * + * Get the record size. The maximum record size is negotiated by the + * client after the first handshake message. + * + * Returns: The maximum record packet size in this connection. + **/ +size_t +gnutls_record_get_max_size (gnutls_session_t session) +{ + /* Recv will hold the negotiated max record size + * always. + */ + return session->security_parameters.max_record_recv_size; +} + + +/** + * gnutls_record_set_max_size: + * @session: is a #gnutls_session_t structure. + * @size: is the new size + * + * This function sets the maximum record packet size in this + * connection. This property can only be set to clients. The server + * may choose not to accept the requested size. + * + * Acceptable values are 512(=2^9), 1024(=2^10), 2048(=2^11) and + * 4096(=2^12). The requested record size does get in effect + * immediately only while sending data. The receive part will take + * effect after a successful handshake. + * + * This function uses a TLS extension called 'max record size'. Not + * all TLS implementations use or even understand this extension. + * + * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, + * otherwise a negative error code is returned. + **/ +ssize_t +gnutls_record_set_max_size (gnutls_session_t session, size_t size) +{ + ssize_t new_size; + extension_priv_data_t epriv; + + if (session->security_parameters.entity == GNUTLS_SERVER) + return GNUTLS_E_INVALID_REQUEST; + + new_size = _gnutls_mre_record2num (size); + + if (new_size < 0) + { + gnutls_assert (); + return new_size; + } + + session->security_parameters.max_record_send_size = size; + epriv.num = size; + + _gnutls_ext_set_session_data (session, GNUTLS_EXTENSION_MAX_RECORD_SIZE, + epriv); + + return 0; +} diff --git a/pool/shard000/C/0011522_mts101.c b/pool/shard000/C/0011522_mts101.c new file mode 100644 index 0000000000000000000000000000000000000000..c29948c0e7e5c95ba6c4237486311104897e28e8 --- /dev/null +++ b/pool/shard000/C/0011522_mts101.c @@ -0,0 +1,243 @@ +/** + * Handles conversion to engineering units of mts101 packets. + * + * @file mts101.c + * @author Hu Siquan + * @version 2004/4/12 husq Initial version + * + * Refer to: + * - Xbow MTS/MDA Sensor and DataAcquistion Manual + * + * Copyright (c) 2004 Crossbow Technology, Inc. All rights reserved. + * + * $Id: mts101.c,v 1.7 2005/02/01 18:11:11 mturon Exp $ + */ + +#include +#include "../xsensors.h" + +/** MTS101 XSensor packet 1 -- contains battery, thermistor, and adc2-7. */ +typedef struct { + uint16_t battery; + uint16_t thermistor; + uint16_t light; +} XSensorMTS101Data; + +extern XPacketHandler mts101_packet_handler; + +/** + * Converts mica2 battery reading from raw ADC data to engineering units. + * + * @author Martin Turon + * + * To compute the battery voltage after measuring the voltage ref: + * BV = RV*ADC_FS/data + * where: + * BV = Battery Voltage + * ADC_FS = 1023 + * RV = Voltage Reference for mica2 (1.223 volts) + * data = data from the adc measurement of channel 1 + * BV (volts) = 1252.352/data + * BV (mv) = 1252352/data + * + * Note: + * The thermistor resistance to temperature conversion is highly non-linear. + * + * @version 2004/3/29 mturon Initial revision + * + */ +uint16_t mts101_convert_battery(XbowSensorboardPacket *packet) +{ + XSensorMTS101Data *data = (XSensorMTS101Data *)packet->data; + float x = (float)data->battery; + uint16_t vdata = (uint16_t) (1252352 / x); + return vdata; +} + + + +/** + * Converts thermistor reading from raw ADC data to engineering units. + * + * @author Martin Turon, Alan Broad + * + * To compute the thermistor resistance after measuring the thermistor voltage: + * - Thermistor is a temperature variable resistor + * - There is a 10K resistor in series with the thermistor resistor. + * - Compute expected adc output from voltage on thermistor as: + * ADC= 1023*Rthr/(R1+Rthr) + * where R1 = 10K + * Rthr = unknown thermistor resistance + * Rthr = R1*(ADC_FS-ADC)/ADC + * where ADC_FS = 1023 + * + * Note: + * The thermistor resistance to temperature conversion is highly non-linear. + * + * @return Thermistor resistance as a uint16 in unit (Ohms) + * + * @version 2004/3/11 mturon Initial revision + * + */ +uint16_t mts101_convert_thermistor_resistance(XbowSensorboardPacket *packet) +{ + XSensorMTS101Data *data = (XSensorMTS101Data *)packet->data; + float x = (float)data->thermistor; + uint16_t vdata = 10000*(1023-x) /x ; + return vdata; +} + +/** + * Converts thermistor reading from raw ADC data to engineering units. + * + * @author Martin Turon + * + * @return Temperature reading from thermistor as a float in degrees Celcius + * + * @version 2004/3/22 mturon Initial revision + * + */ +float mts101_convert_thermistor_temperature(XbowSensorboardPacket *packet) +{ + //XSensorMTS101Data *data = (XSensorMTS101Data *)packet->data; + + float temperature, a, b, c, Rt; + a = 0.001307050; + b = 0.000214381; + c = 0.000000093; + Rt = mts101_convert_thermistor_resistance(packet); + + temperature = 1 / (a + b * log(Rt) + c * pow(log(Rt),3)); + temperature -= 273.15; // Convert from Kelvin to Celcius + + return temperature; +} + +/** + * Computes the Clairex CL94L light sensor reading + * + * @author Hu Siquan + * + * @return Voltage of ADC channel as an unsigned integer in mV + * + * @version 2004/4/12 husq Initial revision + * @n 2004/4/19 husq Convert ADC reading to mv + * + */ +uint16_t mts101_convert_light(XbowSensorboardPacket *packet) +{ + XSensorMTS101Data *data = (XSensorMTS101Data *)packet->data; + float Vbat = mts101_convert_battery(packet); + uint16_t Vadc = (uint16_t) ((data->light) * Vbat / 1023); + return Vadc; +} + + +/** MTS101 Specific outputs of raw readings within an XBowSensorboardPacket */ +void mts101_print_raw(XbowSensorboardPacket *packet) +{ + XSensorMTS101Data *data = (XSensorMTS101Data *)packet->data; + printf("mts101 id=%02x battery=%04x thrm=%04x light=%04x\n", + packet->node_id, data->battery, data->thermistor, data->light); +} + +/** MTS101 specific display of converted readings from XBowSensorboardPacket */ +void mts101_print_cooked(XbowSensorboardPacket *packet) +{ + printf("MTS101 [sensor data converted to engineering units]:\n" + " health: node id=%i\n" + " battery: = %i mv \n" + " tempurature: =%0.2f degC\n" + " light: = %i mv \n", + packet->node_id, + mts101_convert_battery(packet), + mts101_convert_thermistor_temperature(packet), + mts101_convert_light(packet)); + printf("\n"); +} + +const char *mts101_db_create_table = + "CREATE TABLE %s%s ( result_time timestamp without time zone, " + "epoch integer, nodeid integer, parent integer, " + "voltage integer, temp integer, light integer)"; + +const char *mts101_db_create_rule = + "CREATE RULE cache_%s AS ON INSERT TO %s DO ( " + "DELETE FROM %s_L WHERE nodeid = NEW.nodeid; " + "INSERT INTO %s_L VALUES (NEW.*); )"; + +/** + * Logs raw readings to a Postgres database. + * + * @author Martin Turon + * + * @version 2004/7/28 mturon Initial revision + * + */ +void mts101_log_raw(XbowSensorboardPacket *packet) +{ + XSensorMTS101Data *data = (XSensorMTS101Data *)packet->data; + + char command[512]; + char *table = xdb_get_table(); + if (!*table) table = "mts101_results"; + + if (!mts101_packet_handler.flags.table_init) { + int exists = xdb_table_exists(table); + if (!exists) { + // Create results table. + sprintf(command, mts101_db_create_table, table, ""); + xdb_execute(command); + // Create last result cache + sprintf(command, mts101_db_create_table, table, "_L"); + xdb_execute(command); + + // Add rule to populate last result table + sprintf(command, mts101_db_create_rule, table, table, table, table); + xdb_execute(command); + + // Add results table to query log. + int q_id = XTYPE_MTS101, sample_time = 99000; + sprintf(command, "INSERT INTO task_query_log " + "(query_id, tinydb_qid, query_text, query_type, " + "table_name) VALUES (%i, %i, 'SELECT nodeid,parent,voltage,temp,light " + "SAMPLE PERIOD %i', 'sensor', '%s')", q_id, q_id, + sample_time, table); + xdb_execute(command); + + // Log start time of query in time log. + sprintf(command, "INSERT INTO task_query_time_log " + "(query_id, start_time) VALUES (%i, now())", q_id); + xdb_execute(command); + } + mts101_packet_handler.flags.table_init = 1; + } + + sprintf(command, + "INSERT into %s " + "(result_time,nodeid,parent,voltage,temp,light)" + " values (now(),%u,%u,%u,%u,%u)", + table, + //timestring, + packet->node_id, packet->parent, + data->battery, data->thermistor, data->light + ); + + xdb_execute(command); +} + + +XPacketHandler mts101_packet_handler = +{ + XTYPE_MTS101, + "$Id: mts101.c,v 1.7 2005/02/01 18:11:11 mturon Exp $", + mts101_print_raw, + mts101_print_cooked, + mts101_print_raw, + mts101_print_cooked, + mts101_log_raw +}; + +void mts101_initialize() { + xpacket_add_type(&mts101_packet_handler); +} diff --git a/pool/shard000/C/0011527_sender.c b/pool/shard000/C/0011527_sender.c new file mode 100644 index 0000000000000000000000000000000000000000..7a30a56567113e03299d9d1faa465fd26d1b08c1 --- /dev/null +++ b/pool/shard000/C/0011527_sender.c @@ -0,0 +1,100 @@ +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include + + + +static int create_socket(struct in_addr *remote_ip, int port) { + int sock = socket(AF_INET, SOCK_DGRAM, 0); + + struct sockaddr_in sockaddr; + memset(&sockaddr, 0, sizeof(sockaddr)); + sockaddr.sin_family = AF_INET; + sockaddr.sin_port = htons(port); + +// sockaddr.sin_addr = *local_ip; + if (bind(sock, (struct sockaddr *)&sockaddr, sizeof(sockaddr)) != 0) { + printf("Bind failed: %s\n", strerror(errno)); + exit(1); + } + + sockaddr.sin_addr = *remote_ip; + connect(sock, (const struct sockaddr*) &sockaddr, sizeof(sockaddr)); + + return sock; +} + + +// The hardware will accept a variable sized frame, but my test is simple... + +typedef struct __attribute__((packed)) { + uint8_t aSz : 3; + uint8_t bSz : 3; + uint8_t cSz : 2; + uint64_t a : 24; + uint64_t b : 64; + uint64_t c : 8; +} something1_t; + +typedef struct __attribute__((packed)) { + uint8_t aSz : 3; + uint8_t bSz : 3; + uint8_t cSz : 2; + uint64_t a : 48; + uint64_t b : 8; + uint64_t c : 32; +} something2_t; + +static void send_frames(int sock) { + something1_t *s1 = malloc(sizeof(something1_t)); + something2_t *s2 = malloc(sizeof(something2_t)); + + s1->aSz = 3; + s1->bSz = 0; + s1->cSz = 1; + + s1->a = 0x800201; + s1->b = 0x7766554433221100UL; + s1->c = 0x80; + + + s2->aSz = 6; + s2->bSz = 1; + s2->cSz = 3; + + s2->a = 0x800102030405UL; + s2->b = 0x78; + s2->c = 0x818283; + + send(sock, s1, sizeof(something1_t), MSG_WAITALL); + usleep(1000); + send(sock, s2, sizeof(something2_t), MSG_WAITALL); +} + + +int main(int argc, char *argv[]) { + (void) argc; + (void) argv; + + struct in_addr remote_ip; + inet_aton("172.16.50.1", &remote_ip); + + int mySocket = create_socket(&remote_ip, 2000); + + send_frames(mySocket); + + printf("Sender finished\n"); +} + diff --git a/pool/shard000/C/0011528_psxface.c b/pool/shard000/C/0011528_psxface.c new file mode 100644 index 0000000000000000000000000000000000000000..6cc5f413b9894e26e2570aec43fe7087815ad0b7 --- /dev/null +++ b/pool/shard000/C/0011528_psxface.c @@ -0,0 +1,515 @@ +/****************************************************************************** + * + * Module Name: psxface - Parser external interfaces + * + *****************************************************************************/ + +/****************************************************************************** + * + * 1. Copyright Notice + * + * Some or all of this work - Copyright (c) 1999 - 2010, Intel Corp. + * All rights reserved. + * + * 2. License + * + * 2.1. This is your license from Intel Corp. under its intellectual property + * rights. You may have additional license terms from the party that provided + * you this software, covering your right to use that party's intellectual + * property rights. + * + * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a + * copy of the source code appearing in this file ("Covered Code") an + * irrevocable, perpetual, worldwide license under Intel's copyrights in the + * base code distributed originally by Intel ("Original Intel Code") to copy, + * make derivatives, distribute, use and display any portion of the Covered + * Code in any form, with the right to sublicense such rights; and + * + * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent + * license (with the right to sublicense), under only those claims of Intel + * patents that are infringed by the Original Intel Code, to make, use, sell, + * offer to sell, and import the Covered Code and derivative works thereof + * solely to the minimum extent necessary to exercise the above copyright + * license, and in no event shall the patent license extend to any additions + * to or modifications of the Original Intel Code. No other license or right + * is granted directly or by implication, estoppel or otherwise; + * + * The above copyright and patent license is granted only if the following + * conditions are met: + * + * 3. Conditions + * + * 3.1. Redistribution of Source with Rights to Further Distribute Source. + * Redistribution of source code of any substantial portion of the Covered + * Code or modification with rights to further distribute source must include + * the above Copyright Notice, the above License, this list of Conditions, + * and the following Disclaimer and Export Compliance provision. In addition, + * Licensee must cause all Covered Code to which Licensee contributes to + * contain a file documenting the changes Licensee made to create that Covered + * Code and the date of any change. Licensee must include in that file the + * documentation of any changes made by any predecessor Licensee. Licensee + * must include a prominent statement that the modification is derived, + * directly or indirectly, from Original Intel Code. + * + * 3.2. Redistribution of Source with no Rights to Further Distribute Source. + * Redistribution of source code of any substantial portion of the Covered + * Code or modification without rights to further distribute source must + * include the following Disclaimer and Export Compliance provision in the + * documentation and/or other materials provided with distribution. In + * addition, Licensee may not authorize further sublicense of source of any + * portion of the Covered Code, and must include terms to the effect that the + * license from Licensee to its licensee is limited to the intellectual + * property embodied in the software Licensee provides to its licensee, and + * not to intellectual property embodied in modifications its licensee may + * make. + * + * 3.3. Redistribution of Executable. Redistribution in executable form of any + * substantial portion of the Covered Code or modification must reproduce the + * above Copyright Notice, and the following Disclaimer and Export Compliance + * provision in the documentation and/or other materials provided with the + * distribution. + * + * 3.4. Intel retains all right, title, and interest in and to the Original + * Intel Code. + * + * 3.5. Neither the name Intel nor any other trademark owned or controlled by + * Intel shall be used in advertising or otherwise to promote the sale, use or + * other dealings in products derived from or relating to the Covered Code + * without prior written authorization from Intel. + * + * 4. Disclaimer and Export Compliance + * + * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED + * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE + * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, + * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY + * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY + * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A + * PARTICULAR PURPOSE. + * + * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES + * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR + * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, + * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY + * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL + * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS + * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY + * LIMITED REMEDY. + * + * 4.3. Licensee shall not export, either directly or indirectly, any of this + * software or system incorporating such software without first obtaining any + * required license or other approval from the U. S. Department of Commerce or + * any other agency or department of the United States Government. In the + * event Licensee exports any such software from the United States or + * re-exports any such software from a foreign destination, Licensee shall + * ensure that the distribution and export/re-export of the software is in + * compliance with all laws, regulations, orders, or other restrictions of the + * U.S. Export Administration Regulations. Licensee agrees that neither it nor + * any of its subsidiaries will export/re-export any technical data, process, + * software, or service, directly or indirectly, to any country for which the + * United States government or any agency thereof requires an export license, + * other governmental approval, or letter of assurance, without first obtaining + * such license, approval or letter. + * + *****************************************************************************/ + +#define __PSXFACE_C__ + +#include "acpi.h" +#include "accommon.h" +#include "acparser.h" +#include "acdispat.h" +#include "acinterp.h" +#include "actables.h" +#include "amlcode.h" + + +#define _COMPONENT ACPI_PARSER + ACPI_MODULE_NAME ("psxface") + +/* Local Prototypes */ + +static void +AcpiPsStartTrace ( + ACPI_EVALUATE_INFO *Info); + +static void +AcpiPsStopTrace ( + ACPI_EVALUATE_INFO *Info); + +static void +AcpiPsUpdateParameterList ( + ACPI_EVALUATE_INFO *Info, + UINT16 Action); + + +/******************************************************************************* + * + * FUNCTION: AcpiDebugTrace + * + * PARAMETERS: MethodName - Valid ACPI name string + * DebugLevel - Optional level mask. 0 to use default + * DebugLayer - Optional layer mask. 0 to use default + * Flags - bit 1: one shot(1) or persistent(0) + * + * RETURN: Status + * + * DESCRIPTION: External interface to enable debug tracing during control + * method execution + * + ******************************************************************************/ + +ACPI_STATUS +AcpiDebugTrace ( + char *Name, + UINT32 DebugLevel, + UINT32 DebugLayer, + UINT32 Flags) +{ + ACPI_STATUS Status; + + + Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE); + if (ACPI_FAILURE (Status)) + { + return (Status); + } + + /* TBDs: Validate name, allow full path or just nameseg */ + + AcpiGbl_TraceMethodName = *ACPI_CAST_PTR (UINT32, Name); + AcpiGbl_TraceFlags = Flags; + + if (DebugLevel) + { + AcpiGbl_TraceDbgLevel = DebugLevel; + } + if (DebugLayer) + { + AcpiGbl_TraceDbgLayer = DebugLayer; + } + + (void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE); + return (AE_OK); +} + + +/******************************************************************************* + * + * FUNCTION: AcpiPsStartTrace + * + * PARAMETERS: Info - Method info struct + * + * RETURN: None + * + * DESCRIPTION: Start control method execution trace + * + ******************************************************************************/ + +static void +AcpiPsStartTrace ( + ACPI_EVALUATE_INFO *Info) +{ + ACPI_STATUS Status; + + + ACPI_FUNCTION_ENTRY (); + + + Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE); + if (ACPI_FAILURE (Status)) + { + return; + } + + if ((!AcpiGbl_TraceMethodName) || + (AcpiGbl_TraceMethodName != Info->ResolvedNode->Name.Integer)) + { + goto Exit; + } + + AcpiGbl_OriginalDbgLevel = AcpiDbgLevel; + AcpiGbl_OriginalDbgLayer = AcpiDbgLayer; + + AcpiDbgLevel = 0x00FFFFFF; + AcpiDbgLayer = ACPI_UINT32_MAX; + + if (AcpiGbl_TraceDbgLevel) + { + AcpiDbgLevel = AcpiGbl_TraceDbgLevel; + } + if (AcpiGbl_TraceDbgLayer) + { + AcpiDbgLayer = AcpiGbl_TraceDbgLayer; + } + + +Exit: + (void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE); +} + + +/******************************************************************************* + * + * FUNCTION: AcpiPsStopTrace + * + * PARAMETERS: Info - Method info struct + * + * RETURN: None + * + * DESCRIPTION: Stop control method execution trace + * + ******************************************************************************/ + +static void +AcpiPsStopTrace ( + ACPI_EVALUATE_INFO *Info) +{ + ACPI_STATUS Status; + + + ACPI_FUNCTION_ENTRY (); + + + Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE); + if (ACPI_FAILURE (Status)) + { + return; + } + + if ((!AcpiGbl_TraceMethodName) || + (AcpiGbl_TraceMethodName != Info->ResolvedNode->Name.Integer)) + { + goto Exit; + } + + /* Disable further tracing if type is one-shot */ + + if (AcpiGbl_TraceFlags & 1) + { + AcpiGbl_TraceMethodName = 0; + AcpiGbl_TraceDbgLevel = 0; + AcpiGbl_TraceDbgLayer = 0; + } + + AcpiDbgLevel = AcpiGbl_OriginalDbgLevel; + AcpiDbgLayer = AcpiGbl_OriginalDbgLayer; + +Exit: + (void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE); +} + + +/******************************************************************************* + * + * FUNCTION: AcpiPsExecuteMethod + * + * PARAMETERS: Info - Method info block, contains: + * Node - Method Node to execute + * ObjDesc - Method object + * Parameters - List of parameters to pass to the method, + * terminated by NULL. Params itself may be + * NULL if no parameters are being passed. + * ReturnObject - Where to put method's return value (if + * any). If NULL, no value is returned. + * ParameterType - Type of Parameter list + * ReturnObject - Where to put method's return value (if + * any). If NULL, no value is returned. + * PassNumber - Parse or execute pass + * + * RETURN: Status + * + * DESCRIPTION: Execute a control method + * + ******************************************************************************/ + +ACPI_STATUS +AcpiPsExecuteMethod ( + ACPI_EVALUATE_INFO *Info) +{ + ACPI_STATUS Status; + ACPI_PARSE_OBJECT *Op; + ACPI_WALK_STATE *WalkState; + + + ACPI_FUNCTION_TRACE (PsExecuteMethod); + + + /* Quick validation of DSDT header */ + + AcpiTbCheckDsdtHeader (); + + /* Validate the Info and method Node */ + + if (!Info || !Info->ResolvedNode) + { + return_ACPI_STATUS (AE_NULL_ENTRY); + } + + /* Init for new method, wait on concurrency semaphore */ + + Status = AcpiDsBeginMethodExecution (Info->ResolvedNode, Info->ObjDesc, NULL); + if (ACPI_FAILURE (Status)) + { + return_ACPI_STATUS (Status); + } + + /* + * The caller "owns" the parameters, so give each one an extra reference + */ + AcpiPsUpdateParameterList (Info, REF_INCREMENT); + + /* Begin tracing if requested */ + + AcpiPsStartTrace (Info); + + /* + * Execute the method. Performs parse simultaneously + */ + ACPI_DEBUG_PRINT ((ACPI_DB_PARSE, + "**** Begin Method Parse/Execute [%4.4s] **** Node=%p Obj=%p\n", + Info->ResolvedNode->Name.Ascii, Info->ResolvedNode, Info->ObjDesc)); + + /* Create and init a Root Node */ + + Op = AcpiPsCreateScopeOp (); + if (!Op) + { + Status = AE_NO_MEMORY; + goto Cleanup; + } + + /* Create and initialize a new walk state */ + + Info->PassNumber = ACPI_IMODE_EXECUTE; + WalkState = AcpiDsCreateWalkState ( + Info->ObjDesc->Method.OwnerId, NULL, NULL, NULL); + if (!WalkState) + { + Status = AE_NO_MEMORY; + goto Cleanup; + } + + Status = AcpiDsInitAmlWalk (WalkState, Op, Info->ResolvedNode, + Info->ObjDesc->Method.AmlStart, + Info->ObjDesc->Method.AmlLength, Info, Info->PassNumber); + if (ACPI_FAILURE (Status)) + { + AcpiDsDeleteWalkState (WalkState); + goto Cleanup; + } + + if (Info->ObjDesc->Method.Flags & AOPOBJ_MODULE_LEVEL) + { + WalkState->ParseFlags |= ACPI_PARSE_MODULE_LEVEL; + } + + /* Invoke an internal method if necessary */ + + if (Info->ObjDesc->Method.MethodFlags & AML_METHOD_INTERNAL_ONLY) + { + Status = Info->ObjDesc->Method.Extra.Implementation (WalkState); + Info->ReturnObject = WalkState->ReturnDesc; + + /* Cleanup states */ + + AcpiDsScopeStackClear (WalkState); + AcpiPsCleanupScope (&WalkState->ParserState); + AcpiDsTerminateControlMethod (WalkState->MethodDesc, WalkState); + AcpiDsDeleteWalkState (WalkState); + goto Cleanup; + } + + /* + * Start method evaluation with an implicit return of zero. This is done + * for Windows compatibility. + */ + if (AcpiGbl_EnableInterpreterSlack) + { + WalkState->ImplicitReturnObj = + AcpiUtCreateIntegerObject ((UINT64) 0); + if (!WalkState->ImplicitReturnObj) + { + Status = AE_NO_MEMORY; + AcpiDsDeleteWalkState (WalkState); + goto Cleanup; + } + } + + /* Parse the AML */ + + Status = AcpiPsParseAml (WalkState); + + /* WalkState was deleted by ParseAml */ + +Cleanup: + AcpiPsDeleteParseTree (Op); + + /* End optional tracing */ + + AcpiPsStopTrace (Info); + + /* Take away the extra reference that we gave the parameters above */ + + AcpiPsUpdateParameterList (Info, REF_DECREMENT); + + /* Exit now if error above */ + + if (ACPI_FAILURE (Status)) + { + return_ACPI_STATUS (Status); + } + + /* + * If the method has returned an object, signal this to the caller with + * a control exception code + */ + if (Info->ReturnObject) + { + ACPI_DEBUG_PRINT ((ACPI_DB_PARSE, "Method returned ObjDesc=%p\n", + Info->ReturnObject)); + ACPI_DUMP_STACK_ENTRY (Info->ReturnObject); + + Status = AE_CTRL_RETURN_VALUE; + } + + return_ACPI_STATUS (Status); +} + + +/******************************************************************************* + * + * FUNCTION: AcpiPsUpdateParameterList + * + * PARAMETERS: Info - See ACPI_EVALUATE_INFO + * (Used: ParameterType and Parameters) + * Action - Add or Remove reference + * + * RETURN: Status + * + * DESCRIPTION: Update reference count on all method parameter objects + * + ******************************************************************************/ + +static void +AcpiPsUpdateParameterList ( + ACPI_EVALUATE_INFO *Info, + UINT16 Action) +{ + UINT32 i; + + + if (Info->Parameters) + { + /* Update reference count for each parameter */ + + for (i = 0; Info->Parameters[i]; i++) + { + /* Ignore errors, just do them all */ + + (void) AcpiUtUpdateObjectReference (Info->Parameters[i], Action); + } + } +} + + diff --git a/pool/shard000/C/0011538_odbc-escapes-test.c b/pool/shard000/C/0011538_odbc-escapes-test.c new file mode 100644 index 0000000000000000000000000000000000000000..0e479e4a22417e9f1421fe6e12a3cc561faf1d55 --- /dev/null +++ b/pool/shard000/C/0011538_odbc-escapes-test.c @@ -0,0 +1,115 @@ +/* + * Test ODBC escape syntax + */ + +#include +#include + +#include "common.h" + + +/* bind string param as CHAR */ +static void +bindParamString(HSTMT hstmt, int paramno, char *str) +{ + SQLRETURN rc; + static SQLLEN cbParams[10]; + + cbParams[paramno] = SQL_NTS; + rc = SQLBindParameter(hstmt, paramno, SQL_PARAM_INPUT, + SQL_C_CHAR, /* value type */ + SQL_CHAR, /* param type */ + 20, /* column size */ + 0, /* dec digits */ + str, /* param value ptr */ + 0, /* buffer len */ + &cbParams[paramno] /* StrLen_or_IndPtr */); + CHECK_STMT_RESULT(rc, "SQLBindParameter failed", hstmt); + printf("Param %d: %s\n", paramno, str); +} + +static void +executeQuery(HSTMT hstmt) +{ + SQLRETURN rc; + + rc = SQLExecute(hstmt); + CHECK_STMT_RESULT(rc, "SQLExecute failed", hstmt); + print_result(hstmt); + rc = SQLFreeStmt(hstmt, SQL_CLOSE); + CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt); +} + +static void +prepareQuery(HSTMT hstmt, char *str) +{ + SQLRETURN rc; + + rc = SQLPrepare(hstmt, (SQLCHAR *) str, SQL_NTS); + CHECK_STMT_RESULT(rc, "SQLPrepare failed", hstmt); + printf("\nQuery: %s\n", str); +} + +int main(int argc, char **argv) +{ + SQLRETURN rc; + HSTMT hstmt = SQL_NULL_HSTMT; + + test_connect(); + + rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hstmt); + if (!SQL_SUCCEEDED(rc)) + { + print_diag("failed to allocate stmt handle", SQL_HANDLE_DBC, conn); + exit(1); + } + + /**** Function escapes ****/ + + /* CONCAT */ + prepareQuery(hstmt, "SELECT {fn CONCAT(?, ?) }"); + bindParamString(hstmt, 1, "foo"); + bindParamString(hstmt, 2, "bar"); + executeQuery(hstmt); + + /* LOCATE */ + prepareQuery(hstmt, "SELECT {fn LOCATE(?, ?, 2) }"); + bindParamString(hstmt, 1, "needle"); + bindParamString(hstmt, 2, "this is a needle in an ol' haystack"); + executeQuery(hstmt); + + /* SPACE */ + prepareQuery(hstmt, "SELECT 'x' || {fn SPACE(10) } || 'x'"); + executeQuery(hstmt); + + /**** CALL escapes ****/ + + prepareQuery(hstmt, "{ call length(?) }"); + bindParamString(hstmt, 1, "foobar"); + executeQuery(hstmt); + + prepareQuery(hstmt, "{ call right(?, ?) }"); + bindParamString(hstmt, 1, "foobar"); + bindParamString(hstmt, 2, "3"); + executeQuery(hstmt); + + /* TODO: This doesn't currently work. + prepareQuery(hstmt, "{ ? = call concat(?, ?) }"); + */ + + /**** Date, Time, and Timestamp literals ****/ + + prepareQuery(hstmt, "SELECT {d '2014-12-21' } + '1 day'::interval"); + executeQuery(hstmt); + + prepareQuery(hstmt, "SELECT {t '20:30:40' } + '1 hour 1 minute 1 second'::interval"); + executeQuery(hstmt); + + prepareQuery(hstmt, "SELECT {ts '2014-12-21 20:30:40' } + '1 day 1 hour 1 minute 1 second'::interval"); + executeQuery(hstmt); + + /* Clean up */ + test_disconnect(); + + return 0; +} diff --git a/pool/shard000/C/0011540_c_sfgeti.c b/pool/shard000/C/0011540_c_sfgeti.c new file mode 100644 index 0000000000000000000000000000000000000000..325abbeddf5fda446e34aa176148335d2e1d3a2f --- /dev/null +++ b/pool/shard000/C/0011540_c_sfgeti.c @@ -0,0 +1,42 @@ +/* + * $Id: c_sfgeti.c,v 1.5 2008-07-23 16:16:59 haley Exp $ + */ +/************************************************************************ +* * +* Copyright (C) 2000 * +* University Corporation for Atmospheric Research * +* All Rights Reserved * +* * +* The use of this Software is governed by a License Agreement. * +* * +************************************************************************/ + +#include + +extern void NGCALLF(sfgeti,SFGETI)(NGstring,int*,int); + +void c_sfgeti +#ifdef NeedFuncProto +( + char *cnp, + int *ivp +) +#else +(cnp,ivp) + char *cnp; + int *ivp; +#endif +{ + NGstring cnp2; + int len; +/* + * Make sure parameter name is not NULL + */ + if( !cnp ) { + fprintf( stderr, "c_sfgeti: illegal parameter name (NULL)\n"); + return; + } + len = NGSTRLEN(cnp); + cnp2 = NGCstrToFstr(cnp,len); + NGCALLF(sfgeti,SFGETI)(cnp2,ivp,len); +} diff --git a/pool/shard000/C/0011546_ps3_xvag.c b/pool/shard000/C/0011546_ps3_xvag.c new file mode 100644 index 0000000000000000000000000000000000000000..c4473a441119060785d766a3e2818f1280107226 --- /dev/null +++ b/pool/shard000/C/0011546_ps3_xvag.c @@ -0,0 +1,230 @@ +#include "meta.h" +#include "../coding/coding.h" +#include "../util.h" + +/* XVAG (from Ratchet & Clank Future: Quest for Booty) */ +/* v0.1 : bxaimc : Initial release */ +/* v0.2 : Fastelbja : add support for loops points */ +/* + little endian header values */ + +VGMSTREAM * init_vgmstream_ps3_xvag(STREAMFILE *streamFile) { + VGMSTREAM * vgmstream = NULL; + char filename[PATH_LIMIT]; + uint8_t testBuffer[0x10]; + + off_t start_offset; + off_t fileLength; + + int loop_flag = 0; + int channel_count; + off_t readOffset = 0; + int little_endian = 0; + long sample_rate = 0; + long num_samples = 0; + +#ifdef VGM_USE_MPEG + mpeg_codec_data *mpeg_data = NULL; + coding_t mpeg_coding_type = coding_MPEG1_L3; +#endif + + int loopStartPointsCount=0; + int loopEndPointsCount=0; + uint16_t mp3ID; + off_t loopStartPoints[0x10]; + off_t loopEndPoints[0x10]; + + off_t loopStart = 0; + off_t loopEnd = 0; + + /* check extension, case insensitive */ + streamFile->get_name(streamFile,filename,sizeof(filename)); + if (strcasecmp("xvag",filename_extension(filename))) goto fail; + + /* check header */ + if (read_32bitBE(0x00,streamFile) != 0x58564147) /* "XVAG" */ + goto fail; + + fileLength = get_streamfile_size(streamFile); + + if (read_8bit(0x07,streamFile)==0) + little_endian=1; + + if(little_endian) + { + channel_count = read_32bitLE(0x28,streamFile); + start_offset = read_32bitLE(0x4,streamFile); + sample_rate = read_32bitLE(0x3c,streamFile); + num_samples = read_32bitLE(0x30,streamFile); + } + else + { + channel_count = read_32bitBE(0x28,streamFile); + start_offset = read_32bitBE(0x4,streamFile); + sample_rate = read_32bitBE(0x3c,streamFile); + num_samples = read_32bitBE(0x30,streamFile); + } + + readOffset=start_offset; + + // MP3s ? + mp3ID=(uint16_t)read_16bitBE(start_offset,streamFile); + if(mp3ID==0xFFFB) { +#ifdef VGM_USE_MPEG + int rate; + int channels; + + mpeg_data = init_mpeg_codec_data(streamFile, start_offset, -1, -1, &mpeg_coding_type, &rate, &channels); // -1 to not check sample rate or channels + if (!mpeg_data) goto fail; + + channel_count = channels; + sample_rate = rate; + +#else + // reject if no MPEG support + goto fail; +#endif + } else { + // get the loops the same way we get on .MIB + do { + readOffset+=(off_t)read_streamfile(testBuffer,readOffset,0x10,streamFile); + + // Loop Start ... + if(testBuffer[0x01]==0x06) + { + if(loopStartPointsCount<0x10) + { + loopStartPoints[loopStartPointsCount] = readOffset-0x10; + loopStartPointsCount++; + } + } + + // Loop End ... + if(((testBuffer[0x01]==0x03) && (testBuffer[0x03]!=0x77)) || + (testBuffer[0x01]==0x01)) + { + if(loopEndPointsCount<0x10) + { + loopEndPoints[loopEndPointsCount] = readOffset; //-0x10; + loopEndPointsCount++; + } + + } + + } while (readOffset<((int32_t)fileLength)); + + // Calc Loop Points & Interleave ... + if(loopStartPointsCount>=channel_count) + { + // can't get more then 0x10 loop point ! + if((loopStartPointsCount<=0x0F) && (loopStartPointsCount>=2)) + { + // Always took the first 2 loop points + loopStart=loopStartPoints[1]-start_offset; + loop_flag=1; + } else + loopStart=0; + } + + if(loopEndPointsCount>=channel_count) + { + // can't get more then 0x10 loop point ! + if((loopEndPointsCount<=0x0F) && (loopEndPointsCount>=2)) { + loop_flag=1; + loopEnd=loopEndPoints[loopEndPointsCount-1]-start_offset; + } else { + loopEnd=0; + } + } + + // as i can get on the header if a song is looped or not + // if try to take the loop marker on the file + // if the last byte of the file is = 00 is assume that the song is not looped + // i know that i can cover 95% of the file, but can't work on some of them + if(read_8bit((fileLength-1),streamFile)==0) + loop_flag=0; + } + + /* build the VGMSTREAM */ + vgmstream = allocate_vgmstream(channel_count,loop_flag); + if (!vgmstream) goto fail; + + vgmstream->sample_rate = sample_rate; + vgmstream->num_samples = num_samples; + vgmstream->channels = channel_count; + vgmstream->meta_type = meta_PS3_XVAG; + + if(mp3ID==0xFFFB) { +#ifdef VGM_USE_MPEG + /* NOTE: num_samples seems to be quite wrong for MPEG */ + vgmstream->codec_data = mpeg_data; + vgmstream->layout_type = layout_mpeg; + vgmstream->coding_type = mpeg_coding_type; +#else + // reject if no MPEG support + goto fail; +#endif + } + else { + vgmstream->layout_type = layout_interleave; + vgmstream->interleave_block_size = 0x10; + vgmstream->coding_type = coding_PSX; + } + + if (loop_flag) { + if(loopStart!=0) { + vgmstream->loop_start_sample = ((((loopStart/vgmstream->interleave_block_size)-1)*vgmstream->interleave_block_size)/16*28)/channel_count; + if(loopStart%vgmstream->interleave_block_size) { + vgmstream->loop_start_sample += (((loopStart%vgmstream->interleave_block_size)-1)/16*14*channel_count); + } + } + vgmstream->loop_end_sample = ((((loopEnd/vgmstream->interleave_block_size)-1)*vgmstream->interleave_block_size)/16*28)/channel_count; + if(loopEnd%vgmstream->interleave_block_size) { + vgmstream->loop_end_sample += (((loopEnd%vgmstream->interleave_block_size)-1)/16*14*channel_count); + } + } + + /* open the file for reading */ + { + int i; + STREAMFILE * file; + if(vgmstream->layout_type == layout_interleave) { + file = streamFile->open(streamFile,filename,STREAMFILE_DEFAULT_BUFFER_SIZE); + if (!file) goto fail; + for (i=0;ich[i].streamfile = file; + + vgmstream->ch[i].channel_start_offset= + vgmstream->ch[i].offset=start_offset+ + vgmstream->interleave_block_size*i; + + } + } +#ifdef VGM_USE_MPEG + else if(vgmstream->layout_type == layout_mpeg) { + for (i=0;ich[i].streamfile = streamFile->open(streamFile,filename,MPEG_BUFFER_SIZE); + vgmstream->ch[i].channel_start_offset= vgmstream->ch[i].offset=start_offset; + } + + } +#endif + else { goto fail; } + } + + return vgmstream; + + /* clean up anything we may have opened */ +fail: +#ifdef VGM_USE_MPEG + if (mpeg_data) { + mpg123_delete(mpeg_data->m); + free(mpeg_data); + + if (vgmstream) { + vgmstream->codec_data = NULL; + } + } +#endif + if (vgmstream) close_vgmstream(vgmstream); + return NULL; +} diff --git a/pool/shard000/C/0011566_xtouchscreen.c b/pool/shard000/C/0011566_xtouchscreen.c new file mode 100644 index 0000000000000000000000000000000000000000..964e6322028980ef5431c5dc111a48081c88ea92 --- /dev/null +++ b/pool/shard000/C/0011566_xtouchscreen.c @@ -0,0 +1,290 @@ +/* $Id: xtouchscreen.c,v 1.4 2002/10/25 23:18:10 carsten Exp $ */ +/***************************************************************************** +* +* Author: Xilinx, Inc. +* +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at your +* option) any later version. +* +* +* XILINX IS PROVIDING THIS DESIGN, CODE, OR INFORMATION "AS IS" AS A +* COURTESY TO YOU. BY PROVIDING THIS DESIGN, CODE, OR INFORMATION AS +* ONE POSSIBLE IMPLEMENTATION OF THIS FEATURE, APPLICATION OR STANDARD, +* XILINX IS MAKING NO REPRESENTATION THAT THIS IMPLEMENTATION IS FREE +* FROM ANY CLAIMS OF INFRINGEMENT, AND YOU ARE RESPONSIBLE FOR +* OBTAINING ANY RIGHTS YOU MAY REQUIRE FOR YOUR IMPLEMENTATION. +* XILINX EXPRESSLY DISCLAIMS ANY WARRANTY WHATSOEVER WITH RESPECT TO +* THE ADEQUACY OF THE IMPLEMENTATION, INCLUDING BUT NOT LIMITED TO ANY +* WARRANTIES OR REPRESENTATIONS THAT THIS IMPLEMENTATION IS FREE FROM +* CLAIMS OF INFRINGEMENT, IMPLIED WARRANTIES OF MERCHANTABILITY AND +* FITNESS FOR A PARTICULAR PURPOSE. +* +* +* Xilinx products are not intended for use in life support appliances, +* devices, or systems. Use in such applications is expressly prohibited. +* +* +* (c) Copyright 2002 Xilinx Inc. +* All rights reserved. +* +* +* 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., +* 675 Mass Ave, Cambridge, MA 02139, USA. +* +*****************************************************************************/ +/****************************************************************************/ +/** +* +* @file xtouchscreen.c +* +* This file contains the required functions for the touchscreen driver. +* Refer to the header file xtouchscreen.h for more detailed information. +* +*
+* MODIFICATION HISTORY:
+*
+* Ver   Who  Date     Changes
+* ----- ---- -------- -----------------------------------------------
+* 1.00a ch   08/15/02 First release
+* 
+* +*****************************************************************************/ + +/***************************** Include Files ********************************/ + +#include +#include "xstatus.h" +#include "xparameters.h" +#include "xtouchscreen.h" +#include "xtouchscreen_i.h" +#include "xtouchscreen_l.h" +#include "xio.h" + +/************************** Constant Definitions ****************************/ + +/**************************** Type Definitions ******************************/ + +/***************** Macros (Inline Functions) Definitions ********************/ + +/************************** Variable Definitions ****************************/ + +/************************** Function Prototypes *****************************/ + +static void XTouchscreen_StubHandler(void *CallBackRef, u32 Event, + unsigned int ByteCount); + +/****************************************************************************/ +/** +* +* Initializes a specific touchscreen instance such that it is ready to be used. +* The default operating mode of the driver is polled mode. +* +* @param InstancePtr is a pointer to the XTouchscreen instance to be +* worked on. +* @param DeviceId is the unique id of the device controlled by this +* XTouchscreen instance. Passing in a device id associates the +* generic XTouchscreen instance to a specific device, as chosen +* by the caller or application developer. +* +* @return +* +* - XST_SUCCESS if initialization was successful +* - XST_DEVICE_NOT_FOUND if the device ID could not be found in the +* configuration table +* +* @note +* +* None. +* +*****************************************************************************/ +XStatus +XTouchscreen_Initialize(XTouchscreen * InstancePtr, u16 DeviceId) +{ + XTouchscreen_Config *TouchscreenConfigPtr; + + /* + * Assert validates the input arguments + */ + XASSERT_NONVOID(InstancePtr != NULL); + + /* + * Lookup the device configuration in the temporary CROM table. Use this + * configuration info down below when initializing this component. + */ + TouchscreenConfigPtr = XTouchscreen_LookupConfig(DeviceId); + + if (TouchscreenConfigPtr == (XTouchscreen_Config *) NULL) { + return XST_DEVICE_NOT_FOUND; + } + + /* + * Setup the data that is from the configuration information + */ + InstancePtr->BaseAddress = TouchscreenConfigPtr->BaseAddress; + + /* + * Initialize the instance data to some default values and setup a default + * handler + */ + InstancePtr->Handler = XTouchscreen_StubHandler; + + InstancePtr->CurrentState = XTOUCHSCREEN_STATE_PEN_UP; + + /* + * Enable Touchscreen + */ + XTouchscreen_mWriteCtrlReg(InstancePtr->BaseAddress, 0xd3); + udelay(100); + XTouchscreen_mWriteCtrlReg(InstancePtr->BaseAddress, 0xd0); + udelay(100); + + /* + * Clear all interrupts + */ + XTouchscreen_mClearIntr(InstancePtr->BaseAddress, + XTOUCHSCREEN_INT_PEN_DOWN | + XTOUCHSCREEN_INT_PEN_UP); + + /* + * Indicate the instance is now ready to use, initialized without error + */ + InstancePtr->IsReady = XCOMPONENT_IS_READY; + + return XST_SUCCESS; +} + +/****************************************************************************/ +/** +* +* Looks up the device configuration based on the unique device ID. A table +* contains the configuration info for each device in the system. +* +* @param DeviceId contains the ID of the device to look up the configuration +* for. +* +* @return +* +* A pointer to the configuration found or NULL if the specified device ID was +* not found. +* +* @note +* +* None. +* +******************************************************************************/ +XTouchscreen_Config * +XTouchscreen_LookupConfig(u16 DeviceId) +{ + XTouchscreen_Config *CfgPtr = NULL; + + int i; + + for (i = 0; i < XPAR_XTOUCHSCREEN_NUM_INSTANCES; i++) { + if (XTouchscreen_ConfigTable[i].DeviceId == DeviceId) { + CfgPtr = &XTouchscreen_ConfigTable[i]; + } + } + + return CfgPtr; +} + +/****************************************************************************/ +/** +* +* This function reads 2D (X & Y) coordinates from the touchscreen. +* +* @param InstancePtr is a pointer to the XTouchscreen instance to be +* worked on. +* @param *x pointer to store the x coordinate. +* *y pointer to store the y coordinate. +* +* @return None. +* +* @note None. +* +*****************************************************************************/ +void +XTouchscreen_GetPosition_2D(XTouchscreen * InstancePtr, u32 * x, u32 * y) +{ + *x = XTouchscreen_GetValue(InstancePtr->BaseAddress, + XTOUCHSCREEN_CTRL_CHSEL_X); + *y = XTouchscreen_GetValue(InstancePtr->BaseAddress, + XTOUCHSCREEN_CTRL_CHSEL_Y); +} + +/****************************************************************************/ +/** +* +* This function reads 3D (X, Y & Z) coordinates from the touchscreen. x and +* y are the actual positions, the pressure has to be calculated from z1 and +* z2 +* +* @param InstancePtr is a pointer to the XTouchscreen instance to be +* worked on. +* @param *x pointer to store the x coordinate. +* *y pointer to store the y coordinate. +* *z pointer to store the z coordinate (pressure) +* +* @return None. +* +* @note None. +* +*****************************************************************************/ +void +XTouchscreen_GetPosition_3D(XTouchscreen * InstancePtr, u32 * x, + u32 * y, u32 * z) +{ + u32 z1; + u32 z2; + + *x = XTouchscreen_GetValue(InstancePtr->BaseAddress, + XTOUCHSCREEN_CTRL_CHSEL_X); + *y = XTouchscreen_GetValue(InstancePtr->BaseAddress, + XTOUCHSCREEN_CTRL_CHSEL_Y); + + z1 = XTouchscreen_GetValue(InstancePtr->BaseAddress, + XTOUCHSCREEN_CTRL_CHSEL_Z1); + z2 = XTouchscreen_GetValue(InstancePtr->BaseAddress, + XTOUCHSCREEN_CTRL_CHSEL_Z2); + + if (z1 == 0) { + *z = XTOUCHSCREEN_SAMPLE_ERROR; + return; + } else if (z1 > z2) { + *z = XTOUCHSCREEN_SAMPLE_ERROR; + return; + } else { + *z = ((*x) * (z2 / z1 - 1)); + } +} + +/****************************************************************************/ +/** +* +* This function is a stub handler that is the default handler such that if the +* application has not set the handler when interrupts are enabled, this +* function will be called. The function interface has to match the interface +* specified for a handler even though none of the arguments are used. +* +* @param CallBackRef is unused by this function. +* @param Event is unused by this function. +* @param ByteCount is unused by this function. +* +* @return +* +* None. +* +* @note +* +* None. +* +*****************************************************************************/ +static void +XTouchscreen_StubHandler(void *CallBackRef, u32 Event, unsigned int ByteCount) +{ + XASSERT_VOID(FALSE); +} diff --git a/pool/shard000/C/0011570_u_slab.c b/pool/shard000/C/0011570_u_slab.c new file mode 100644 index 0000000000000000000000000000000000000000..dbdebc6c9fca85e17587a092f95223244c87f85f --- /dev/null +++ b/pool/shard000/C/0011570_u_slab.c @@ -0,0 +1,171 @@ +/* + * Copyright 2010 Marek Olšák + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * on the rights to use, copy, modify, merge, publish, distribute, sub + * license, and/or sell copies of the Software, and to permit persons to whom + * the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice (including the next + * paragraph) shall be included in all copies or substantial portions of the + * Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL + * THE AUTHOR(S) AND/OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + * USE OR OTHER DEALINGS IN THE SOFTWARE. */ + +#include "util/u_slab.h" + +#include "util/u_math.h" +#include "util/u_memory.h" +#include "util/u_simple_list.h" + +#include + +#define UTIL_SLAB_MAGIC 0xcafe4321 + +/* The block is either allocated memory or free space. */ +struct util_slab_block { + /* The header. */ + /* The first next free block. */ + struct util_slab_block *next_free; + + intptr_t magic; + + /* Memory after the last member is dedicated to the block itself. + * The allocated size is always larger than this structure. */ +}; + +static struct util_slab_block * +util_slab_get_block(struct util_slab_mempool *pool, + struct util_slab_page *page, unsigned index) +{ + return (struct util_slab_block*) + ((uint8_t*)page + sizeof(struct util_slab_page) + + (pool->block_size * index)); +} + +static void util_slab_add_new_page(struct util_slab_mempool *pool) +{ + struct util_slab_page *page; + struct util_slab_block *block; + unsigned i; + + page = MALLOC(pool->page_size); + insert_at_tail(&pool->list, page); + + /* Mark all blocks as free. */ + for (i = 0; i < pool->num_blocks-1; i++) { + block = util_slab_get_block(pool, page, i); + block->next_free = util_slab_get_block(pool, page, i+1); + block->magic = UTIL_SLAB_MAGIC; + } + + block = util_slab_get_block(pool, page, pool->num_blocks-1); + block->next_free = pool->first_free; + block->magic = UTIL_SLAB_MAGIC; + pool->first_free = util_slab_get_block(pool, page, 0); + pool->num_pages++; + +#if 0 + fprintf(stderr, "New page! Num of pages: %i\n", pool->num_pages); +#endif +} + +static void *util_slab_alloc_st(struct util_slab_mempool *pool) +{ + struct util_slab_block *block; + + if (!pool->first_free) + util_slab_add_new_page(pool); + + block = pool->first_free; + assert(block->magic == UTIL_SLAB_MAGIC); + pool->first_free = block->next_free; + + return (uint8_t*)block + sizeof(struct util_slab_block); +} + +static void util_slab_free_st(struct util_slab_mempool *pool, void *ptr) +{ + struct util_slab_block *block = + (struct util_slab_block*) + ((uint8_t*)ptr - sizeof(struct util_slab_block)); + + assert(block->magic == UTIL_SLAB_MAGIC); + block->next_free = pool->first_free; + pool->first_free = block; +} + +static void *util_slab_alloc_mt(struct util_slab_mempool *pool) +{ + void *mem; + + pipe_mutex_lock(pool->mutex); + mem = util_slab_alloc_st(pool); + pipe_mutex_unlock(pool->mutex); + return mem; +} + +static void util_slab_free_mt(struct util_slab_mempool *pool, void *ptr) +{ + pipe_mutex_lock(pool->mutex); + util_slab_free_st(pool, ptr); + pipe_mutex_unlock(pool->mutex); +} + +void util_slab_set_thread_safety(struct util_slab_mempool *pool, + enum util_slab_threading threading) +{ + pool->threading = threading; + + if (threading) { + pool->alloc = util_slab_alloc_mt; + pool->free = util_slab_free_mt; + } else { + pool->alloc = util_slab_alloc_st; + pool->free = util_slab_free_st; + } +} + +void util_slab_create(struct util_slab_mempool *pool, + unsigned item_size, + unsigned num_blocks, + enum util_slab_threading threading) +{ + item_size = align(item_size, sizeof(intptr_t)); + + pool->num_pages = 0; + pool->num_blocks = num_blocks; + pool->block_size = sizeof(struct util_slab_block) + item_size; + pool->block_size = align(pool->block_size, sizeof(intptr_t)); + pool->page_size = sizeof(struct util_slab_page) + + num_blocks * pool->block_size; + pool->first_free = NULL; + + make_empty_list(&pool->list); + + pipe_mutex_init(pool->mutex); + + util_slab_set_thread_safety(pool, threading); +} + +void util_slab_destroy(struct util_slab_mempool *pool) +{ + struct util_slab_page *page, *temp; + + if (pool->list.next) { + foreach_s(page, temp, &pool->list) { + remove_from_list(page); + FREE(page); + } + } + + pipe_mutex_destroy(pool->mutex); +} diff --git a/pool/shard000/C/0011583_syborg_timer.c b/pool/shard000/C/0011583_syborg_timer.c new file mode 100644 index 0000000000000000000000000000000000000000..cf96c5fffe305de91606767d48aec82079992379 --- /dev/null +++ b/pool/shard000/C/0011583_syborg_timer.c @@ -0,0 +1,247 @@ +/* + * Syborg Interval Timer. + * + * Copyright (c) 2008 CodeSourcery + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "sysbus.h" +#include "qemu-timer.h" +#include "syborg.h" + +//#define DEBUG_SYBORG_TIMER + +#ifdef DEBUG_SYBORG_TIMER +#define DPRINTF(fmt, ...) \ +do { printf("syborg_timer: " fmt , ##args); } while (0) +#define BADF(fmt, ...) \ +do { fprintf(stderr, "syborg_timer: error: " fmt , ## __VA_ARGS__); \ + exit(1);} while (0) +#else +#define DPRINTF(fmt, ...) do {} while(0) +#define BADF(fmt, ...) \ +do { fprintf(stderr, "syborg_timer: error: " fmt , ## __VA_ARGS__);} while (0) +#endif + +enum { + TIMER_ID = 0, + TIMER_RUNNING = 1, + TIMER_ONESHOT = 2, + TIMER_LIMIT = 3, + TIMER_VALUE = 4, + TIMER_INT_ENABLE = 5, + TIMER_INT_STATUS = 6, + TIMER_FREQ = 7 +}; + +typedef struct { + SysBusDevice busdev; + ptimer_state *timer; + int running; + int oneshot; + uint32_t limit; + uint32_t freq; + uint32_t int_level; + uint32_t int_enabled; + qemu_irq irq; +} SyborgTimerState; + +static void syborg_timer_update(SyborgTimerState *s) +{ + /* Update interrupt. */ + if (s->int_level && s->int_enabled) { + qemu_irq_raise(s->irq); + } else { + qemu_irq_lower(s->irq); + } +} + +static void syborg_timer_tick(void *opaque) +{ + SyborgTimerState *s = (SyborgTimerState *)opaque; + //DPRINTF("Timer Tick\n"); + s->int_level = 1; + if (s->oneshot) + s->running = 0; + syborg_timer_update(s); +} + +static uint32_t syborg_timer_read(void *opaque, target_phys_addr_t offset) +{ + SyborgTimerState *s = (SyborgTimerState *)opaque; + + DPRINTF("Reg read %d\n", (int)offset); + offset &= 0xfff; + switch (offset >> 2) { + case TIMER_ID: + return SYBORG_ID_TIMER; + case TIMER_RUNNING: + return s->running; + case TIMER_ONESHOT: + return s->oneshot; + case TIMER_LIMIT: + return s->limit; + case TIMER_VALUE: + return ptimer_get_count(s->timer); + case TIMER_INT_ENABLE: + return s->int_enabled; + case TIMER_INT_STATUS: + return s->int_level; + case TIMER_FREQ: + return s->freq; + default: + cpu_abort(cpu_single_env, "syborg_timer_read: Bad offset %x\n", + (int)offset); + return 0; + } +} + +static void syborg_timer_write(void *opaque, target_phys_addr_t offset, + uint32_t value) +{ + SyborgTimerState *s = (SyborgTimerState *)opaque; + + DPRINTF("Reg write %d\n", (int)offset); + offset &= 0xfff; + switch (offset >> 2) { + case TIMER_RUNNING: + if (value == s->running) + break; + s->running = value; + if (value) { + ptimer_run(s->timer, s->oneshot); + } else { + ptimer_stop(s->timer); + } + break; + case TIMER_ONESHOT: + if (s->running) { + ptimer_stop(s->timer); + } + s->oneshot = value; + if (s->running) { + ptimer_run(s->timer, s->oneshot); + } + break; + case TIMER_LIMIT: + s->limit = value; + ptimer_set_limit(s->timer, value, 1); + break; + case TIMER_VALUE: + ptimer_set_count(s->timer, value); + break; + case TIMER_INT_ENABLE: + s->int_enabled = value; + syborg_timer_update(s); + break; + case TIMER_INT_STATUS: + s->int_level &= ~value; + syborg_timer_update(s); + break; + default: + cpu_abort(cpu_single_env, "syborg_timer_write: Bad offset %x\n", + (int)offset); + break; + } +} + +static CPUReadMemoryFunc *syborg_timer_readfn[] = { + syborg_timer_read, + syborg_timer_read, + syborg_timer_read +}; + +static CPUWriteMemoryFunc *syborg_timer_writefn[] = { + syborg_timer_write, + syborg_timer_write, + syborg_timer_write +}; + +static void syborg_timer_save(QEMUFile *f, void *opaque) +{ + SyborgTimerState *s = opaque; + + qemu_put_be32(f, s->running); + qemu_put_be32(f, s->oneshot); + qemu_put_be32(f, s->limit); + qemu_put_be32(f, s->int_level); + qemu_put_be32(f, s->int_enabled); + qemu_put_ptimer(f, s->timer); +} + +static int syborg_timer_load(QEMUFile *f, void *opaque, int version_id) +{ + SyborgTimerState *s = opaque; + + if (version_id != 1) + return -EINVAL; + + s->running = qemu_get_be32(f); + s->oneshot = qemu_get_be32(f); + s->limit = qemu_get_be32(f); + s->int_level = qemu_get_be32(f); + s->int_enabled = qemu_get_be32(f); + qemu_get_ptimer(f, s->timer); + + return 0; +} + +static void syborg_timer_init(SysBusDevice *dev) +{ + SyborgTimerState *s = FROM_SYSBUS(SyborgTimerState, dev); + QEMUBH *bh; + int iomemtype; + + if (s->freq == 0) { + fprintf(stderr, "syborg_timer: Zero/unset frequency\n"); + exit(1); + } + sysbus_init_irq(dev, &s->irq); + iomemtype = cpu_register_io_memory(syborg_timer_readfn, + syborg_timer_writefn, s); + sysbus_init_mmio(dev, 0x1000, iomemtype); + + bh = qemu_bh_new(syborg_timer_tick, s); + s->timer = ptimer_init(bh); + ptimer_set_freq(s->timer, s->freq); + register_savevm("syborg_timer", -1, 1, + syborg_timer_save, syborg_timer_load, s); +} + +static SysBusDeviceInfo syborg_timer_info = { + .init = syborg_timer_init, + .qdev.name = "syborg,timer", + .qdev.size = sizeof(SyborgTimerState), + .qdev.props = (Property[]) { + { + .name = "frequency", + .info = &qdev_prop_uint32, + .offset = offsetof(SyborgTimerState, freq), + }, + {/* end of list */} + } +}; + +static void syborg_timer_register_devices(void) +{ + sysbus_register_withprop(&syborg_timer_info); +} + +device_init(syborg_timer_register_devices) diff --git a/pool/shard000/C/0011585_svv.test.c b/pool/shard000/C/0011585_svv.test.c new file mode 100644 index 0000000000000000000000000000000000000000..8506bfebfc3f9f0cbda8a943db38bb32c30ca379 --- /dev/null +++ b/pool/shard000/C/0011585_svv.test.c @@ -0,0 +1,65 @@ + +/* + * sophia database + * sphia.org + * + * Copyright (c) Dmitry Simonenko + * BSD License +*/ + +#include +#include +#include +#include +#include + +static void +svv_kv(stc *cx) +{ + ssa a; + ss_aopen(&a, &ss_stda); + + srscheme cmp; + sr_schemeinit(&cmp); + srkey *part = sr_schemeadd(&cmp, &a); + t( sr_keysetname(part, &a, "key") == 0 ); + t( sr_keyset(part, &a, "u32") == 0 ); + sr r; + sr_init(&r, NULL, &a, NULL, SF_KV, SF_SRAW, &cmp, NULL, NULL, NULL); + + uint32_t key = 123; + uint32_t value = 321; + + sfv pv; + pv.key = (char*)&key; + pv.r.size = sizeof(key); + pv.r.offset = 0; + + svv *vv = sv_vbuild(&r, &pv, 1, (char*)&value, sizeof(value)); + t( vv != NULL ); + vv->flags = 0; + vv->lsn = 10; + sv v; + sv_init(&v, &sv_vif, vv, NULL); + + t( sv_flags(&v) == 0 ); + t( sv_lsn(&v) == 10 ); + sv_lsnset(&v, 8); + t( sv_lsn(&v) == 8 ); + + t( *(uint32_t*)sf_key(sv_pointer(&v), 0) == key ); + t( sf_keysize(sv_pointer(&v), 0) == sizeof(key) ); + + t( *(uint32_t*)sf_value(SF_KV, sv_pointer(&v), cmp.count) == value ); + t( sf_valuesize(SF_KV, sv_pointer(&v), sv_size(&v), cmp.count) == sizeof(value) ); + + sv_vfree(&a, vv); + sr_schemefree(&cmp, &a); +} + +stgroup *svv_group(void) +{ + stgroup *group = st_group("svv"); + st_groupadd(group, st_test("kv", svv_kv)); + return group; +} diff --git a/pool/shard000/C/0011587_sem_create.c b/pool/shard000/C/0011587_sem_create.c new file mode 100644 index 0000000000000000000000000000000000000000..6da6f7385830a09771299eb8d0c9c87c96880f5a --- /dev/null +++ b/pool/shard000/C/0011587_sem_create.c @@ -0,0 +1,26 @@ +// sem_create.c + +#include "sem_common.h" + +#define PROGNAME "sem_create" + +int +main(int argc, char **argv) +{ + int val; + sem_t *sem; + + CHECK_ARGS(3, " "); + + val = atoi(argv[2]); + + sem = sem_open(argv[1], O_CREAT | O_EXCL, 0644, val); + if (sem == (sem_t *)SEM_FAILED) { + perror("sem_open"); + exit(1); + } + + sem_close(sem); + + exit(0); +} diff --git a/pool/shard000/C/0011588_worker.c b/pool/shard000/C/0011588_worker.c new file mode 100644 index 0000000000000000000000000000000000000000..a3ed46e0eb50ec119e0485369a0429718d7faec9 --- /dev/null +++ b/pool/shard000/C/0011588_worker.c @@ -0,0 +1,330 @@ +/* + * Copyright (c) 2009-2012, Vsevolod Stakhov + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY AUTHOR ''AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL AUTHOR BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/* + * Rspamd worker implementation + */ + +#include "config.h" +#include "libutil/util.h" +#include "libutil/map.h" +#include "libutil/upstream.h" +#include "libserver/protocol.h" +#include "libserver/cfg_file.h" +#include "libserver/url.h" +#include "libserver/dns.h" +#include "libmime/message.h" +#include "main.h" +#include "keypairs_cache.h" +#include "libstat/stat_api.h" +#include "libserver/worker_util.h" + +#include "lua/lua_common.h" + +/* 60 seconds for worker's IO */ +#define DEFAULT_WORKER_IO_TIMEOUT 60000 +extern struct rspamd_main *rspamd_main; + +gpointer init_worker (struct rspamd_config *cfg); +void start_worker (struct rspamd_worker *worker); + +worker_t normal_worker = { + "normal", /* Name */ + init_worker, /* Init function */ + start_worker, /* Start function */ + TRUE, /* Has socket */ + FALSE, /* Non unique */ + FALSE, /* Non threaded */ + TRUE, /* Killable */ + SOCK_STREAM /* TCP socket */ +}; + +/* + * Worker's context + */ +struct rspamd_worker_ctx { + guint32 timeout; + struct timeval io_tv; + /* Detect whether this worker is mime worker */ + gboolean is_mime; + /* HTTP worker */ + gboolean is_http; + /* JSON output */ + gboolean is_json; + /* Allow learning throught worker */ + gboolean allow_learn; + /* DNS resolver */ + struct rspamd_dns_resolver *resolver; + /* Current tasks */ + guint32 tasks; + /* Limit of tasks */ + guint32 max_tasks; + /* Events base */ + struct event_base *ev_base; + /* Encryption key */ + gpointer key; + /* Keys cache */ + struct rspamd_keypair_cache *keys_cache; +}; + +/* + * Reduce number of tasks proceeded + */ +static void +reduce_tasks_count (gpointer arg) +{ + guint32 *tasks = arg; + + (*tasks)--; +} + +static gint +rspamd_worker_body_handler (struct rspamd_http_connection *conn, + struct rspamd_http_message *msg, + const gchar *chunk, gsize len) +{ + struct rspamd_task *task = (struct rspamd_task *) conn->ud; + struct rspamd_worker_ctx *ctx; + + ctx = task->worker->ctx; + + if (!rspamd_protocol_handle_request (task, msg)) { + msg_err ("cannot handle request: %e", task->err); + task->flags |= RSPAMD_TASK_FLAG_SKIP; + } + else { + if (task->cmd == CMD_PING) { + task->flags |= RSPAMD_TASK_FLAG_SKIP; + } + else { + if (!rspamd_task_load_message (task, msg, chunk, len)) { + msg_err ("cannot load message: %e", task->err); + task->flags |= RSPAMD_TASK_FLAG_SKIP; + } + } + } + + rspamd_task_process (task, RSPAMD_TASK_PROCESS_ALL); + + return 0; +} + +static void +rspamd_worker_error_handler (struct rspamd_http_connection *conn, GError *err) +{ + struct rspamd_task *task = (struct rspamd_task *) conn->ud; + + msg_info ("abnormally closing connection from: %s, error: %e", + rspamd_inet_address_to_string (task->client_addr), err); + /* Terminate session immediately */ + rspamd_session_destroy (task->s); +} + +static gint +rspamd_worker_finish_handler (struct rspamd_http_connection *conn, + struct rspamd_http_message *msg) +{ + struct rspamd_task *task = (struct rspamd_task *) conn->ud; + + if (task->processed_stages & RSPAMD_TASK_STAGE_REPLIED) { + /* We are done here */ + msg_debug ("normally closing connection from: %s", + rspamd_inet_address_to_string (task->client_addr)); + rspamd_session_destroy (task->s); + } + else if (task->processed_stages & RSPAMD_TASK_STAGE_DONE) { + rspamd_session_pending (task->s); + } + + return 0; +} + +/* + * Accept new connection and construct task + */ +static void +accept_socket (gint fd, short what, void *arg) +{ + struct rspamd_worker *worker = (struct rspamd_worker *) arg; + struct rspamd_worker_ctx *ctx; + struct rspamd_task *new_task; + rspamd_inet_addr_t *addr; + gint nfd; + + ctx = worker->ctx; + + if (ctx->max_tasks != 0 && ctx->tasks > ctx->max_tasks) { + msg_info ("current tasks is now: %uD while maximum is: %uD", + ctx->tasks, + ctx->max_tasks); + return; + } + + if ((nfd = + rspamd_accept_from_socket (fd, &addr)) == -1) { + msg_warn ("accept failed: %s", strerror (errno)); + return; + } + /* Check for EAGAIN */ + if (nfd == 0) { + return; + } + + new_task = rspamd_task_new (worker); + + msg_info ("accepted connection from %s port %d", + rspamd_inet_address_to_string (addr), + rspamd_inet_address_get_port (addr)); + + /* Copy some variables */ + if (ctx->is_mime) { + new_task->flags |= RSPAMD_TASK_FLAG_MIME; + } + else { + new_task->flags &= ~RSPAMD_TASK_FLAG_MIME; + } + + new_task->sock = nfd; + new_task->client_addr = addr; + + worker->srv->stat->connections_count++; + new_task->resolver = ctx->resolver; + + new_task->http_conn = rspamd_http_connection_new ( + rspamd_worker_body_handler, + rspamd_worker_error_handler, + rspamd_worker_finish_handler, + 0, + RSPAMD_HTTP_SERVER, + ctx->keys_cache); + new_task->ev_base = ctx->ev_base; + ctx->tasks++; + rspamd_mempool_add_destructor (new_task->task_pool, + (rspamd_mempool_destruct_t)reduce_tasks_count, &ctx->tasks); + + /* Set up async session */ + new_task->s = rspamd_session_create (new_task->task_pool, rspamd_task_fin, + rspamd_task_restore, rspamd_task_free_hard, new_task); + + if (ctx->key) { + rspamd_http_connection_set_key (new_task->http_conn, ctx->key); + } + + rspamd_http_connection_read_message (new_task->http_conn, + new_task, + nfd, + &ctx->io_tv, + ctx->ev_base); +} + +gpointer +init_worker (struct rspamd_config *cfg) +{ + struct rspamd_worker_ctx *ctx; + GQuark type; + + type = g_quark_try_string ("normal"); + + ctx = g_malloc0 (sizeof (struct rspamd_worker_ctx)); + + ctx->is_mime = TRUE; + ctx->timeout = DEFAULT_WORKER_IO_TIMEOUT; + + rspamd_rcl_register_worker_option (cfg, type, "mime", + rspamd_rcl_parse_struct_boolean, ctx, + G_STRUCT_OFFSET (struct rspamd_worker_ctx, is_mime), 0); + + rspamd_rcl_register_worker_option (cfg, type, "http", + rspamd_rcl_parse_struct_boolean, ctx, + G_STRUCT_OFFSET (struct rspamd_worker_ctx, is_http), 0); + + rspamd_rcl_register_worker_option (cfg, type, "json", + rspamd_rcl_parse_struct_boolean, ctx, + G_STRUCT_OFFSET (struct rspamd_worker_ctx, is_json), 0); + + rspamd_rcl_register_worker_option (cfg, type, "allow_learn", + rspamd_rcl_parse_struct_boolean, ctx, + G_STRUCT_OFFSET (struct rspamd_worker_ctx, allow_learn), 0); + + rspamd_rcl_register_worker_option (cfg, type, "timeout", + rspamd_rcl_parse_struct_time, ctx, + G_STRUCT_OFFSET (struct rspamd_worker_ctx, + timeout), RSPAMD_CL_FLAG_TIME_INTEGER); + + rspamd_rcl_register_worker_option (cfg, type, "max_tasks", + rspamd_rcl_parse_struct_integer, ctx, + G_STRUCT_OFFSET (struct rspamd_worker_ctx, + max_tasks), RSPAMD_CL_FLAG_INT_32); + + rspamd_rcl_register_worker_option (cfg, type, "keypair", + rspamd_rcl_parse_struct_keypair, ctx, + G_STRUCT_OFFSET (struct rspamd_worker_ctx, + key), 0); + + return ctx; +} + +/* + * Start worker process + */ +void +start_worker (struct rspamd_worker *worker) +{ + struct rspamd_worker_ctx *ctx = worker->ctx; + + ctx->ev_base = rspamd_prepare_worker (worker, "normal", accept_socket); + msec_to_tv (ctx->timeout, &ctx->io_tv); + + rspamd_map_watch (worker->srv->cfg, ctx->ev_base); + rspamd_symbols_cache_start_refresh (worker->srv->cfg->cache, ctx->ev_base); + + ctx->resolver = dns_resolver_init (worker->srv->logger, + ctx->ev_base, + worker->srv->cfg); + + rspamd_upstreams_library_init (ctx->resolver->r, ctx->ev_base); + rspamd_upstreams_library_config (worker->srv->cfg); + + /* XXX: stupid default */ + ctx->keys_cache = rspamd_keypair_cache_new (256); + rspamd_stat_init (worker->srv->cfg); + + event_base_loop (ctx->ev_base, 0); + + g_mime_shutdown (); + rspamd_stat_close (); + rspamd_log_close (rspamd_main->logger); + + if (ctx->key) { + rspamd_http_connection_key_unref (ctx->key); + } + + rspamd_keypair_cache_destroy (ctx->keys_cache); + + exit (EXIT_SUCCESS); +} + +/* + * vi:ts=4 + */ diff --git a/pool/shard000/C/0011607_sclp_quiesce.c b/pool/shard000/C/0011607_sclp_quiesce.c new file mode 100644 index 0000000000000000000000000000000000000000..924c5dc9f7f47d91264ddbbca4a1f634a5fe9680 --- /dev/null +++ b/pool/shard000/C/0011607_sclp_quiesce.c @@ -0,0 +1,114 @@ +/* + * drivers/s390/char/sclp_quiesce.c + * signal quiesce handler + * + * (C) Copyright IBM Corp. 1999,2004 + * Author(s): Martin Schwidefsky + * Peter Oberparleiter + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "sclp.h" + + +#ifdef CONFIG_SMP +/* Signal completion of shutdown process. All CPUs except the first to enter + * this function: go to stopped state. First CPU: wait until all other + * CPUs are in stopped or check stop state. Afterwards, load special PSW + * to indicate completion. */ +static void +do_load_quiesce_psw(void * __unused) +{ + static atomic_t cpuid = ATOMIC_INIT(-1); + psw_t quiesce_psw; + __u32 status; + int i; + + if (atomic_compare_and_swap(-1, smp_processor_id(), &cpuid)) + signal_processor(smp_processor_id(), sigp_stop); + /* Wait for all other cpus to enter stopped state */ + i = 1; + while (i < NR_CPUS) { + if (!cpu_online(i)) { + i++; + continue; + } + switch (signal_processor_ps(&status, 0, i, sigp_sense)) { + case sigp_order_code_accepted: + case sigp_status_stored: + /* Check for stopped and check stop state */ + if (status & 0x50) + i++; + break; + case sigp_busy: + break; + case sigp_not_operational: + i++; + break; + } + } + /* Quiesce the last cpu with the special psw */ + quiesce_psw.mask = PSW_BASE_BITS | PSW_MASK_WAIT; + quiesce_psw.addr = 0xfff; + __load_psw(quiesce_psw); +} + +/* Shutdown handler. Perform shutdown function on all CPUs. */ +static void +do_machine_quiesce(void) +{ + on_each_cpu(do_load_quiesce_psw, NULL, 0, 0); +} +#else +/* Shutdown handler. Signal completion of shutdown by loading special PSW. */ +static void +do_machine_quiesce(void) +{ + psw_t quiesce_psw; + + quiesce_psw.mask = PSW_BASE_BITS | PSW_MASK_WAIT; + quiesce_psw.addr = 0xfff; + __load_psw(quiesce_psw); +} +#endif + +extern void ctrl_alt_del(void); + +/* Handler for quiesce event. Start shutdown procedure. */ +static void +sclp_quiesce_handler(struct evbuf_header *evbuf) +{ + _machine_restart = (void *) do_machine_quiesce; + _machine_halt = do_machine_quiesce; + _machine_power_off = do_machine_quiesce; + ctrl_alt_del(); +} + +static struct sclp_register sclp_quiesce_event = { + .receive_mask = EvTyp_SigQuiesce_Mask, + .receiver_fn = sclp_quiesce_handler +}; + +/* Initialize quiesce driver. */ +static int __init +sclp_quiesce_init(void) +{ + int rc; + + rc = sclp_register(&sclp_quiesce_event); + if (rc) + printk(KERN_WARNING "sclp: could not register quiesce handler " + "(rc=%d)\n", rc); + return rc; +} + +module_init(sclp_quiesce_init); diff --git a/pool/shard000/C/0011618_server.c b/pool/shard000/C/0011618_server.c new file mode 100644 index 0000000000000000000000000000000000000000..c239ece00f253789e1691c99718c95e21c1c083a --- /dev/null +++ b/pool/shard000/C/0011618_server.c @@ -0,0 +1,191 @@ +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#define BUF_SIZE 1024 + +int replace_esc(char* in_file, char* out_file); + +int main() +{ + const char* fileName = "/opt/gclc/gclc.log"; + const char* tmpFileName = "/opt/gclc/tmp.log"; + const char* host = "79.98.21.68"; + const char* port = "7777"; + struct addrinfo hints, *res; + struct sockaddr_in addr; + socklen_t addr_len; + FILE *f; + int sock, new_sock, ret, diff, bool_first = 1; + char buf[BUF_SIZE]; + time_t begin, current; + struct tm * timeinfo; + + // Create a socket + addr.sin_family = AF_INET; + addr.sin_port = htons(atoi(port)); + addr.sin_addr.s_addr = INADDR_ANY; + + memset(&hints, 0, sizeof hints); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + + + if((getaddrinfo(NULL, port, &hints, &res)) != 0){ + perror("Server: Getaddrinfo error\n"); + return 1; + } + + if ((sock = socket(AF_INET, SOCK_STREAM, 0 )) < 0){ + perror("Server: Error when creating the socket"); + return 1; + } + + if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) != 0) { + perror("Server: Error while binding to socket"); + close(sock); + return 1; + } + + if (listen(sock, 5) == -1) { + perror("Server: Error while listening"); + close(sock); + return -1; + } + + addr_len = sizeof(addr); + + if ((new_sock = accept(sock, (struct sockaddr *) &addr, &addr_len) ) < 0 ) + { + perror("Server: Error on accept"); + close(sock); + return 1; + } + + while(1) + { + // Open file + f = fopen(tmpFileName, "w"); + if (f == NULL) + { + perror("Server: Error opening the file"); + close(new_sock); + close(sock); + return 1; + } + // If first recv + if (bool_first) + { + // Read the data + if ((ret = recv(new_sock, buf, BUF_SIZE-1, 0)) == -1) + { + perror("Server: Error recv"); + close(sock); + close(new_sock); + return 1; + } + else if(ret != 0) + { + buf[ret] = '\0'; + + printf("%s", buf); + printf("***TEAM40***\n"); + fprintf(f, "%s", buf); + } + + // Set the timeout + struct timeval timeout; + timeout.tv_sec = 20; + timeout.tv_usec = 0; + + if (setsockopt (new_sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)) < 0) + error("setsockopt failed\n"); + + bool_first = 0; + } + + // Get current time + time (&begin); + diff = 0; + + //The first 5 min after the first read + while(diff < 300) + { + // Read the data + if ((ret = recv(new_sock, buf, BUF_SIZE-1, 0)) == -1) { + printf("***timeout\n"); + } + else if(ret != 0) + { + buf[ret] = '\0'; + + printf("%s", buf); + printf("***DELIMITER***\n"); + + fprintf(f, "%s", buf); + //fclose(f); + } + // Get current time + time(¤t); + diff = (int)difftime(current, begin); + printf("DIFF: %d\n", diff); + } + printf("***out of the while\n"); + // Flush the content + fflush(f); + printf("***after flush\n"); + // Close file + fclose(f); + // Replace the special characters + replace_esc(tmpFileName, fileName); + printf("***after replacement\n"); + // Sleep untill before the + time ( ¤t ); + printf("GOING TO SLEEP\n"); + sleep(700 - (int)difftime(current, begin)); //15*60 + printf("END OF SLEEPING\n"); + } + //fclose(f); + + //printf("Server exiting\n"); + + return 0; +} + +int replace_esc(char* in_file, char* out_file) { + FILE* in; + FILE* out; + unsigned int c, c_old; + + in = fopen(in_file,"r"); + out = fopen(out_file,"w"); + printf("#\n"); + + c = fgetc(in); + + while(c != EOF) { + if (c == '\t') { + fputs("#011",out); + } else if (c == '\n' && c_old != '#') { + fputs("#012",out); + } else if (c != '#') { + fputc(c,out); + } + c_old = c; + c = fgetc(in); + } + + fclose(in); + fclose(out); + + return 0; +} \ No newline at end of file diff --git a/pool/shard000/C/0011619_main.c b/pool/shard000/C/0011619_main.c new file mode 100644 index 0000000000000000000000000000000000000000..7c342f1ad02310683e3f3e8fcf90992c7a265e4c --- /dev/null +++ b/pool/shard000/C/0011619_main.c @@ -0,0 +1,130 @@ +// +// Created by joek on 10/4/16. +// + +#include +#include "BBB_P10.h" +#include +#include +#include +#include + +bool Scanning = true; +const char *MSG = "BBB_P10 LED DISPLAY IS A LIBRARY FOR BEAGLEBONE BLACK."; +typedef struct { + pthread_mutex_t mutex; + pthread_t thread; +}threadstruct; + +void *scan_thread(void *data){ + threadstruct *threadstruct1 = (threadstruct*)data; + while(Scanning){ + pthread_mutex_lock(&threadstruct1->mutex); + Scan_Panels(); + pthread_mutex_unlock(&threadstruct1->mutex); + } + pthread_exit(NULL); +} +void *display_thread(void *data){ + threadstruct *threadstruct1 = (threadstruct*)data; + while(Scanning){ + + pthread_mutex_lock(&threadstruct1->mutex); + movestring(MSG,Left,AlignCenter,50000); + pthread_mutex_unlock(&threadstruct1->mutex); + sleep(1); + + pthread_mutex_lock(&threadstruct1->mutex); + movestring("SCROLLING RIGHT",Right,AlignCenter,50000); + pthread_mutex_unlock(&threadstruct1->mutex); + sleep(1); + + pthread_mutex_lock(&threadstruct1->mutex); + movestring("SCROLLING LEFT",Left,AlignTop,10000); + pthread_mutex_unlock(&threadstruct1->mutex); + sleep(1); + + pthread_mutex_lock(&threadstruct1->mutex); + Clear_Buffer(false); + drawBox(0,0,nPANEL*WIDTH-1,15); + drawmessage("LEFT TOP",AlignHLeft,AlignTop); + pthread_mutex_unlock(&threadstruct1->mutex); + sleep(1); + + pthread_mutex_lock(&threadstruct1->mutex); + Clear_Buffer(false); + drawBox(0,0,nPANEL*WIDTH-1,15); + drawmessage("CENTER TOP",AlignHCenter,AlignTop); + pthread_mutex_unlock(&threadstruct1->mutex); + sleep(1); + + pthread_mutex_lock(&threadstruct1->mutex); + Clear_Buffer(false); + drawBox(0,0,nPANEL*WIDTH-1,15); + drawmessage("RIGHT TOP",AlignHRight,AlignTop); + pthread_mutex_unlock(&threadstruct1->mutex); + sleep(1); + + pthread_mutex_lock(&threadstruct1->mutex); + Clear_Buffer(false); + drawBox(0,0,nPANEL*WIDTH-1,15); + drawmessage("LEFT TOP",AlignHLeft,AlignTop); + pthread_mutex_unlock(&threadstruct1->mutex); + sleep(1); + + pthread_mutex_lock(&threadstruct1->mutex); + Clear_Buffer(false); + drawBox(0,0,nPANEL*WIDTH-1,15); + drawmessage("CENTER CENTER",AlignHCenter,AlignCenter); + pthread_mutex_unlock(&threadstruct1->mutex); + sleep(1); + + pthread_mutex_lock(&threadstruct1->mutex); + Clear_Buffer(false); + drawBox(0,0,nPANEL*WIDTH-1,15); + drawmessage("RIGHT BOTTOM",AlignHRight,AlignBottom); + pthread_mutex_unlock(&threadstruct1->mutex); + sleep(1); + + pthread_mutex_lock(&threadstruct1->mutex); + Clear_Buffer(false); + flashmessage("FLASHING STRING",AlignHCenter,AlignCenter,350000,5); + pthread_mutex_unlock(&threadstruct1->mutex); + sleep(1); + + } +// + pthread_exit(NULL); +} +int main(int argc, char *argv[]) { + int res; + Setup_Pins(); + Clear_Buffer(false); + drawmessage(MSG,AlignHCenter,AlignCenter); + + threadstruct *threadstruct1 = malloc(sizeof(threadstruct)); + pthread_mutex_init(&(threadstruct1->mutex), NULL); + res = pthread_create(&threadstruct1->thread, NULL, scan_thread, threadstruct1); + if (res < 0) { + printf("failed to create thread %d\n", res); + return res; + } + + threadstruct *threadstruct2 = malloc(sizeof(threadstruct)); + pthread_mutex_init(&(threadstruct2->mutex), NULL); + res = pthread_create(&threadstruct2->thread, NULL, display_thread, threadstruct2); + if (res < 0) { + printf("failed to create thread %d\n", res); + return res; + } + + pthread_join(threadstruct1->thread, NULL); + pthread_join(threadstruct2->thread, NULL); + + pthread_mutex_destroy(&threadstruct1->mutex); + pthread_mutex_destroy(&threadstruct2->mutex); + + Free_BBB_P10(); + + return 0 ; +} \ No newline at end of file diff --git a/pool/shard000/C/0011630_stm32mp1xx_hal_crc_ex.c b/pool/shard000/C/0011630_stm32mp1xx_hal_crc_ex.c new file mode 100644 index 0000000000000000000000000000000000000000..7d426f3135e30fed8bd9d0a53215faae0fcb57fd --- /dev/null +++ b/pool/shard000/C/0011630_stm32mp1xx_hal_crc_ex.c @@ -0,0 +1,225 @@ +/** + ****************************************************************************** + * @file stm32mp1xx_hal_crc_ex.c + * @author MCD Application Team + * @brief Extended CRC HAL module driver. + * This file provides firmware functions to manage the extended + * functionalities of the CRC peripheral. + * + @verbatim +================================================================================ + ##### How to use this driver ##### +================================================================================ + [..] + (+) Set user-defined generating polynomial thru HAL_CRCEx_Polynomial_Set() + (+) Configure Input or Output data inversion + + @endverbatim + ****************************************************************************** + * @attention + * + *

© Copyright (c) 2019 STMicroelectronics. + * All rights reserved.

+ * + * This software component is licensed by ST under BSD 3-Clause license, + * the "License"; You may not use this file except in compliance with the + * License. You may obtain a copy of the License at: + * opensource.org/licenses/BSD-3-Clause + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32mp1xx_hal.h" + +/** @addtogroup STM32MP1xx_HAL_Driver + * @{ + */ + +/** @defgroup CRCEx CRCEx + * @brief CRC Extended HAL module driver + * @{ + */ + +#ifdef HAL_CRC_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup CRCEx_Exported_Functions CRC Extended Exported Functions + * @{ + */ + +/** @defgroup CRCEx_Exported_Functions_Group1 Extended Initialization/de-initialization functions + * @brief Extended Initialization and Configuration functions. + * +@verbatim + =============================================================================== + ##### Extended configuration functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Configure the generating polynomial + (+) Configure the input data inversion + (+) Configure the output data inversion + +@endverbatim + * @{ + */ + + +/** + * @brief Initialize the CRC polynomial if different from default one. + * @param hcrc CRC handle + * @param Pol CRC generating polynomial (7, 8, 16 or 32-bit long). + * This parameter is written in normal representation, e.g. + * @arg for a polynomial of degree 7, X^7 + X^6 + X^5 + X^2 + 1 is written 0x65 + * @arg for a polynomial of degree 16, X^16 + X^12 + X^5 + 1 is written 0x1021 + * @param PolyLength CRC polynomial length. + * This parameter can be one of the following values: + * @arg @ref CRC_POLYLENGTH_7B 7-bit long CRC (generating polynomial of degree 7) + * @arg @ref CRC_POLYLENGTH_8B 8-bit long CRC (generating polynomial of degree 8) + * @arg @ref CRC_POLYLENGTH_16B 16-bit long CRC (generating polynomial of degree 16) + * @arg @ref CRC_POLYLENGTH_32B 32-bit long CRC (generating polynomial of degree 32) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CRCEx_Polynomial_Set(CRC_HandleTypeDef *hcrc, uint32_t Pol, uint32_t PolyLength) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t msb = 31U; /* polynomial degree is 32 at most, so msb is initialized to max value */ + + /* Check the parameters */ + assert_param(IS_CRC_POL_LENGTH(PolyLength)); + + /* check polynomial definition vs polynomial size: + * polynomial length must be aligned with polynomial + * definition. HAL_ERROR is reported if Pol degree is + * larger than that indicated by PolyLength. + * Look for MSB position: msb will contain the degree of + * the second to the largest polynomial member. E.g., for + * X^7 + X^6 + X^5 + X^2 + 1, msb = 6. */ + while ((msb-- > 0U) && ((Pol & ((uint32_t)(0x1U) << (msb & 0x1FU))) == 0U)) + { + } + + switch (PolyLength) + { + case CRC_POLYLENGTH_7B: + if (msb >= HAL_CRC_LENGTH_7B) + { + status = HAL_ERROR; + } + break; + case CRC_POLYLENGTH_8B: + if (msb >= HAL_CRC_LENGTH_8B) + { + status = HAL_ERROR; + } + break; + case CRC_POLYLENGTH_16B: + if (msb >= HAL_CRC_LENGTH_16B) + { + status = HAL_ERROR; + } + break; + + case CRC_POLYLENGTH_32B: + /* no polynomial definition vs. polynomial length issue possible */ + break; + default: + status = HAL_ERROR; + break; + } + if (status == HAL_OK) + { + /* set generating polynomial */ + WRITE_REG(hcrc->Instance->POL, Pol); + + /* set generating polynomial size */ + MODIFY_REG(hcrc->Instance->CR, CRC_CR_POLYSIZE, PolyLength); + } + /* Return function status */ + return status; +} + +/** + * @brief Set the Reverse Input data mode. + * @param hcrc CRC handle + * @param InputReverseMode Input Data inversion mode. + * This parameter can be one of the following values: + * @arg @ref CRC_INPUTDATA_INVERSION_NONE no change in bit order (default value) + * @arg @ref CRC_INPUTDATA_INVERSION_BYTE Byte-wise bit reversal + * @arg @ref CRC_INPUTDATA_INVERSION_HALFWORD HalfWord-wise bit reversal + * @arg @ref CRC_INPUTDATA_INVERSION_WORD Word-wise bit reversal + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CRCEx_Input_Data_Reverse(CRC_HandleTypeDef *hcrc, uint32_t InputReverseMode) +{ + /* Check the parameters */ + assert_param(IS_CRC_INPUTDATA_INVERSION_MODE(InputReverseMode)); + + /* Change CRC peripheral state */ + hcrc->State = HAL_CRC_STATE_BUSY; + + /* set input data inversion mode */ + MODIFY_REG(hcrc->Instance->CR, CRC_CR_REV_IN, InputReverseMode); + /* Change CRC peripheral state */ + hcrc->State = HAL_CRC_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Set the Reverse Output data mode. + * @param hcrc CRC handle + * @param OutputReverseMode Output Data inversion mode. + * This parameter can be one of the following values: + * @arg @ref CRC_OUTPUTDATA_INVERSION_DISABLE no CRC inversion (default value) + * @arg @ref CRC_OUTPUTDATA_INVERSION_ENABLE bit-level inversion (e.g. for a 8-bit CRC: 0xB5 becomes 0xAD) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CRCEx_Output_Data_Reverse(CRC_HandleTypeDef *hcrc, uint32_t OutputReverseMode) +{ + /* Check the parameters */ + assert_param(IS_CRC_OUTPUTDATA_INVERSION_MODE(OutputReverseMode)); + + /* Change CRC peripheral state */ + hcrc->State = HAL_CRC_STATE_BUSY; + + /* set output data inversion mode */ + MODIFY_REG(hcrc->Instance->CR, CRC_CR_REV_OUT, OutputReverseMode); + + /* Change CRC peripheral state */ + hcrc->State = HAL_CRC_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + + + + +/** + * @} + */ + + +/** + * @} + */ + + +#endif /* HAL_CRC_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard000/C/0011653_test-dispatch.c b/pool/shard000/C/0011653_test-dispatch.c new file mode 100644 index 0000000000000000000000000000000000000000..46a99f744c251abc542c23318a3f54a9f94fc448 --- /dev/null +++ b/pool/shard000/C/0011653_test-dispatch.c @@ -0,0 +1,86 @@ +#include +#include + +#include + +#define MIN(a,b) (a < b ? a : b) + +void dispatch(char *user __attribute__((unused)), const struct pfq_pkthdr *h, const char *data) +{ + int x; + for(x = 0; x < MIN(h->caplen,34); x++) + { + printf("%2x ", (unsigned char)data[x]); + } + printf("\n"); +} + +int +main(int argc, char *argv[]) +{ + if (argc < 2) { + fprintf(stderr, "usage: %s dev\n", argv[0]); + return 0; + } + + pfq_t *p = pfq_open(64, 4096, 1024); + if (p == NULL) { + printf("error: %s\n", pfq_error(p)); + return -1; + } + + if (pfq_enable(p) < 0) { + printf("error: %s\n", pfq_error(p)); + return -1; + } + + if (pfq_is_enabled(p) != 1) { + printf("error: %s\n", pfq_error(p)); + return -1; + } + + int caplen = pfq_get_caplen(p); + if (caplen < 0) { + printf("error: %s\n", pfq_error(p)); + return -1; + } + + printf("caplen: %d\n", caplen); + + int id = pfq_id(p); + if (id < 0) { + printf("error: %s\n", pfq_error(p)); + return -1; + } + + printf("id: %d\n", id); + + if (pfq_bind(p, argv[1], Q_ANY_QUEUE) < 0) { + printf("error: %s\n", pfq_error(p)); + return -1; + } + + int n = 0; + printf("dispatching...\n"); + + for(;n < 10; n++) { + int many = pfq_dispatch(p, dispatch, 1000000, NULL); + if (many < 0) { + printf("error: %s\n", pfq_error(p)); + break; + } + printf("queue length: %d\n", many); + } + + struct pfq_stats s; + if(pfq_get_stats(p, &s) < 0) { + printf("error: %s\n", pfq_error(p)); + return -1; + } + + printf("stats:: recv=%lu lost=%lu drop=%lu\n", s.recv, s.lost, s.drop); + + pfq_close(p); + return 0; +} + diff --git a/pool/shard000/C/0011657_t0004.c b/pool/shard000/C/0011657_t0004.c new file mode 100644 index 0000000000000000000000000000000000000000..5e73d31f2dd883f46803780b55f297130274f911 --- /dev/null +++ b/pool/shard000/C/0011657_t0004.c @@ -0,0 +1,132 @@ +/* + * Purpose: Test retrieving data and attempting to initiate a new query with results pending + * Functions: dbnextrow dbresults dbsqlexec dbgetchar + */ + +#include "common.h" +#include + +int +main(int argc, char **argv) +{ + const int rows_to_add = 50; + LOGINREC *login; + DBPROCESS *dbproc; + int i, expected_error; + char *s, teststr[1024]; + DBINT testint; + int failed = 0; + + set_malloc_options(); + + read_login_info(argc, argv); + + fprintf(stdout, "Starting %s\n", argv[0]); + + dbinit(); + + dberrhandle(syb_err_handler); + dbmsghandle(syb_msg_handler); + + fprintf(stdout, "About to logon\n"); + + login = dblogin(); + DBSETLPWD(login, PASSWORD); + DBSETLUSER(login, USER); + DBSETLAPP(login, "t0004"); + + fprintf(stdout, "About to open\n"); + + dbproc = dbopen(login, SERVER); + if (strlen(DATABASE)) + dbuse(dbproc, DATABASE); + dbloginfree(login); + + fprintf(stdout, "creating table\n"); + sql_cmd(dbproc); + dbsqlexec(dbproc); + while (dbresults(dbproc) != NO_MORE_RESULTS) { + /* nop */ + } + + fprintf(stdout, "insert\n"); + for (i = 1; i < rows_to_add; i++) { + sql_cmd(dbproc); + dbsqlexec(dbproc); + while (dbresults(dbproc) != NO_MORE_RESULTS) { + /* nop */ + } + } + + sql_cmd(dbproc); /* select */ + dbsqlexec(dbproc); + + if (dbresults(dbproc) != SUCCEED) { + fprintf(stdout, "Was expecting a result set."); + exit(1); + } + + for (i = 1; i <= dbnumcols(dbproc); i++) + printf("col %d is %s\n", i, dbcolname(dbproc, i)); + + dbbind(dbproc, 1, INTBIND, 0, (BYTE *) & testint); + dbbind(dbproc, 2, STRINGBIND, 0, (BYTE *) teststr); + + for (i = 1; i <= 24; i++) { + char expected[1024]; + + sprintf(expected, "row %04d", i); + + if (i % 5 == 0) { + dbclrbuf(dbproc, 5); + } + + + testint = -1; + strcpy(teststr, "bogus"); + + if (REG_ROW != dbnextrow(dbproc)) { + fprintf(stderr, "Failed. Expected a row\n"); + exit(1); + } + if (testint != i) { + fprintf(stderr, "Failed. Expected i to be %d, was %d\n", i, (int) testint); + abort(); + } + if (0 != strncmp(teststr, expected, strlen(expected))) { + fprintf(stdout, "Failed. Expected s to be |%s|, was |%s|\n", expected, teststr); + abort(); + } + printf("Read a row of data -> %d %s\n", (int) testint, teststr); + } + + + + fprintf(stdout, "second select\n"); + fprintf(stdout, "testing dbgetchar...\n"); + for (i=0; (s = dbgetchar(dbproc, i)) != NULL; i++) { + putchar(*s); + if (!(isprint((unsigned char)*s) || iscntrl((unsigned char)*s))) { + fprintf(stderr, "%s:%d: dbgetchar failed with %x at position %d\n", __FILE__, __LINE__, *s, i); + failed = 1; + break; + } + } + fprintf(stdout, "<== end of command buffer\n"); + + if (SUCCEED != sql_cmd(dbproc)) { + fprintf(stderr, "%s:%d: dbcmd failed\n", __FILE__, __LINE__); + failed = 1; + } + fprintf(stdout, "About to exec for the second time. Should fail\n"); + expected_error = 20019; + dbsetuserdata(dbproc, (BYTE*) &expected_error); + if (FAIL != dbsqlexec(dbproc)) { + fprintf(stderr, "%s:%d: dbsqlexec should have failed but didn't\n", __FILE__, __LINE__); + failed = 1; + } + dbexit(); + + fprintf(stdout, "%s %s\n", __FILE__, (failed ? "failed!" : "OK")); + return failed ? 1 : 0; +} diff --git a/pool/shard000/C/0011680_terprefsmainpanel.c b/pool/shard000/C/0011680_terprefsmainpanel.c new file mode 100644 index 0000000000000000000000000000000000000000..da460b42a463cc0be0652ee83de847c6007d4e33 --- /dev/null +++ b/pool/shard000/C/0011680_terprefsmainpanel.c @@ -0,0 +1,155 @@ +/* + File: terprefsmainpanel.c + Project: tern + Author: Douwe Vos + Date: Oct 26, 2014 + e-mail: dmvos2000(at)yahoo.com + + Copyright (C) 2014 Douwe Vos. + + 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 + along with this program. If not, see . */ + +#include "terprefsmainpanel.h" +#include "../terpreferenceswo.h" +#include "../terprefsclazzwo.h" +#include "../terprefsmapper.h" +#include +#include + +#include "tergladeprefsmain.h" + +#include +#define CAT_LOG_LEVEL CAT_LOG_WARN +#define CAT_LOG_CLAZZ "TerPrefsMainPanel" +#include + +struct _TerPrefsMainPanelPrivate { + GtkWidget *w_but_add; +}; + +static void l_stringable_iface_init(CatIStringableInterface *iface); + +G_DEFINE_TYPE_WITH_CODE(TerPrefsMainPanel, ter_prefs_main_panel, COW_TYPE_PANEL, + G_ADD_PRIVATE(TerPrefsMainPanel) + G_IMPLEMENT_INTERFACE(CAT_TYPE_ISTRINGABLE, l_stringable_iface_init) +); + +static void l_dispose(GObject *object); +static void l_finalize(GObject *object); + +static void ter_prefs_main_panel_class_init(TerPrefsMainPanelClass *clazz) { + GObjectClass *object_class = G_OBJECT_CLASS(clazz); + object_class->dispose = l_dispose; + object_class->finalize = l_finalize; +} + +static void ter_prefs_main_panel_init(TerPrefsMainPanel *instance) { +} + +static void l_dispose(GObject *object) { + cat_log_detail("dispose:%p", object); + G_OBJECT_CLASS(ter_prefs_main_panel_parent_class)->dispose(object); + cat_log_detail("disposed:%p", object); +} + +static void l_finalize(GObject *object) { + cat_log_detail("finalize:%p", object); + cat_ref_denounce(object); + G_OBJECT_CLASS(ter_prefs_main_panel_parent_class)->finalize(object); + cat_log_detail("finalized:%p", object); +} + +static void l_on_new_class_pressed(GtkButton *button, gpointer self); + + +TerPrefsMainPanel *ter_prefs_main_panel_new() { + TerPrefsMainPanel *result = g_object_new(TER_TYPE_PREFS_MAIN_PANEL, NULL); + cat_ref_anounce(result); + TerPrefsMainPanelPrivate *priv = ter_prefs_main_panel_get_instance_private(result); + cow_panel_construct((CowPanel *) result); + + GtkBuilder *builder = gtk_builder_new(); + GError *gerror = NULL; + gtk_builder_add_from_string(builder, (const gchar *) tergladeprefsmain_glade, (gsize) tergladeprefsmain_glade_len, (GError **) (&gerror)); + GtkWidget *frame = (GtkWidget *) gtk_builder_get_object(builder, "main_frame"); + + gtk_widget_set_vexpand_set(frame, TRUE); + + gtk_container_add((GtkContainer *) result, frame); + + priv->w_but_add = (GtkWidget *) gtk_builder_get_object(builder, "but_add"); + g_signal_connect(priv->w_but_add, "clicked", G_CALLBACK(l_on_new_class_pressed), result); + + return result; +} + + +static void l_on_new_class_pressed(GtkButton *button, gpointer self) { + TerPrefsMainPanel *panel_main = TER_PREFS_MAIN_PANEL(self); + + LeaBasicInputDialog *dialog = lea_basic_input_dialog_new(GTK_WIDGET(panel_main), "Class _name", "Please type the name of the new document class below"); + int result = gtk_dialog_run(GTK_DIALOG(dialog)); + if (result == GTK_RESPONSE_OK) { + const gchar *txt_new_class_name = lea_basic_input_dialog_get_entry_text(dialog); + if (txt_new_class_name) { + cat_log_debug("txt_new_class_name=%s", txt_new_class_name); + CatStringWo *new_class_name = cat_string_wo_new_with(txt_new_class_name); + + ElkPreferencesWo *e_prefs = (ElkPreferencesWo *) cow_panel_get_configuration((CowPanel *) panel_main); + ElkPreferencesWo *e_replacement = elk_preferences_wo_clone(e_prefs, CAT_CLONE_DEPTH_MAIN); + + TerPreferencesWo *e_ter_prefs = (TerPreferencesWo *) elk_preferences_wo_get_sub(e_replacement, CAT_S(ter_s_textpad)); + + if (e_ter_prefs == NULL) { + e_ter_prefs = ter_preferences_wo_new(); + elk_preferences_wo_set_sub(e_replacement, CAT_S(ter_s_textpad), (GObject *) e_ter_prefs); + cat_unref(e_ter_prefs); + } else if (ter_preferences_wo_is_anchored(e_ter_prefs)) { + e_ter_prefs = ter_preferences_wo_create_editable(e_ter_prefs); + elk_preferences_wo_set_sub(e_replacement, CAT_S(ter_s_textpad), (GObject *) e_ter_prefs); + cat_unref(e_ter_prefs); + } + + + TerPrefsClazzWo *new_clazz = ter_preferences_wo_get_clazz(e_ter_prefs, new_class_name); + if (new_clazz==NULL) { + new_clazz = ter_prefs_clazz_wo_new(new_class_name); + cat_log_error("new_clazz=%p", new_clazz); + ter_preferences_wo_set_clazz(e_ter_prefs, new_clazz); + cow_panel_set_configuration((CowPanel *) panel_main, (GObject *) e_replacement); + } + +// cat_unref_ptr(e_replacement); + } else { + cat_log_warn("txt_new_class_name is NULL"); + } + } + gtk_widget_destroy(GTK_WIDGET(dialog)); + +} + + + +/********************* start CatIStringable implementation *********************/ + +static void l_stringable_print(CatIStringable *self, struct _CatStringWo *e_append_to) { + const char *iname = g_type_name_from_instance((GTypeInstance *) self); + cat_string_wo_format(e_append_to, "%s[%p]", iname, self); +} + +static void l_stringable_iface_init(CatIStringableInterface *iface) { + iface->print = l_stringable_print; +} + +/********************* end CatIStringable implementation *********************/ diff --git a/pool/shard000/C/0011683_util.c b/pool/shard000/C/0011683_util.c new file mode 100644 index 0000000000000000000000000000000000000000..31e83a8d0a3ce2cfe973546a67cd464b0c19e348 --- /dev/null +++ b/pool/shard000/C/0011683_util.c @@ -0,0 +1,135 @@ +/* + * linux/fs/isofs/util.c + * + * The special functions in the file are numbered according to the section + * of the iso 9660 standard in which they are described. isonum_733 will + * convert numbers according to section 7.3.3, etc. + * + * isofs special functions. This file was lifted in its entirety from + * the 386bsd iso9660 filesystem, by Pace Willisson . + */ + +#include + +int +isonum_711 (char * p) +{ + return (*p & 0xff); +} + +int +isonum_712 (char * p) +{ + int val; + + val = *p; + if (val & 0x80) + val |= 0xffffff00; + return (val); +} + +int +isonum_721 (char * p) +{ + return ((p[0] & 0xff) | ((p[1] & 0xff) << 8)); +} + +int +isonum_722 (char * p) +{ + return (((p[0] & 0xff) << 8) | (p[1] & 0xff)); +} + +int +isonum_723 (char * p) +{ +#if 0 + if (p[0] != p[3] || p[1] != p[2]) { + fprintf (stderr, "invalid format 7.2.3 number\n"); + exit (1); + } +#endif + return (isonum_721 (p)); +} + +int +isonum_731 (char * p) +{ + return ((p[0] & 0xff) + | ((p[1] & 0xff) << 8) + | ((p[2] & 0xff) << 16) + | ((p[3] & 0xff) << 24)); +} + +int +isonum_732 (char * p) +{ + return (((p[0] & 0xff) << 24) + | ((p[1] & 0xff) << 16) + | ((p[2] & 0xff) << 8) + | (p[3] & 0xff)); +} + +int +isonum_733 (char * p) +{ +#if 0 + int i; + + for (i = 0; i < 4; i++) { + if (p[i] != p[7-i]) { + fprintf (stderr, "bad format 7.3.3 number\n"); + exit (1); + } + } +#endif + return (isonum_731 (p)); +} + +/* We have to convert from a MM/DD/YY format to the unix ctime format. + * We have to take into account leap years and all of that good stuff. + */ +int iso_date(char * p, int flag) +{ + int year, month, day, hour ,minute, second, tz; + int crtime, days, i; + + year = p[0] - 70; + month = p[1]; + day = p[2]; + hour = p[3]; + minute = p[4]; + second = p[5]; + if (flag == 0) tz = p[6]; /* High sierra has no time zone */ + else tz = 0; + + if (year < 0) { + crtime = 0; + } else { + int monlen[12] = {31,28,31,30,31,30,31,31,30,31,30,31}; + extern struct timezone sys_tz; + + days = year * 365; + if (year > 2) + days += (year+1) / 4; + for (i = 1; i < month; i++) + days += monlen[i-1]; + if (((year+2) % 4) == 0 && month > 2) + days++; + days += day - 1; + crtime = ((((days * 24) + hour) * 60 + minute) * 60) + + second; + if (sys_tz.tz_dsttime) + crtime -= 3600; + + /* sign extend */ + if (tz & 0x80) + tz |= (-1 << 8); + + /* timezone offset is unreliable on some disks */ + if (-48 <= tz && tz <= 52) + crtime += tz * 15 * 60; + } + return crtime; +} + diff --git a/pool/shard000/C/0011687_builtin-pack-refs.c b/pool/shard000/C/0011687_builtin-pack-refs.c new file mode 100644 index 0000000000000000000000000000000000000000..34246df4ec946273d9f42e6f0848b02d8510beea --- /dev/null +++ b/pool/shard000/C/0011687_builtin-pack-refs.c @@ -0,0 +1,21 @@ +#include "cache.h" +#include "parse-options.h" +#include "pack-refs.h" + +static char const * const pack_refs_usage[] = { + "git pack-refs [options]", + NULL +}; + +int cmd_pack_refs(int argc, const char **argv, const char *prefix) +{ + unsigned int flags = PACK_REFS_PRUNE; + struct option opts[] = { + OPT_BIT(0, "all", &flags, "pack everything", PACK_REFS_ALL), + OPT_BIT(0, "prune", &flags, "prune loose refs (default)", PACK_REFS_PRUNE), + OPT_END(), + }; + if (parse_options(argc, argv, opts, pack_refs_usage, 0)) + usage_with_options(pack_refs_usage, opts); + return pack_refs(flags); +} diff --git a/pool/shard000/C/0011689_myth_worker.c b/pool/shard000/C/0011689_myth_worker.c new file mode 100644 index 0000000000000000000000000000000000000000..10005e9ceeacc1d1aa2f84ce22fc930f3e604d58 --- /dev/null +++ b/pool/shard000/C/0011689_myth_worker.c @@ -0,0 +1,62 @@ +#include "myth_worker.h" +#include "myth_worker_proto.h" +#include "myth_worker_func.h" + +myth_thread_t myth_default_steal_func(int rank); + +myth_steal_func_t g_myth_steal_func=myth_default_steal_func; + +myth_steal_func_t myth_set_steal_func(myth_steal_func_t fn) +{ + myth_steal_func_t prev=g_myth_steal_func; + g_myth_steal_func=fn; + return prev; +} + +extern myth_running_env_t g_envs; + +myth_thread_t myth_default_steal_func(int rank) +{ + myth_running_env_t env,busy_env; + myth_thread_t next_run=NULL; +#ifdef MYTH_WS_PROF_DETAIL + uint64_t t0,t1; + t0=myth_get_rdtsc(); +#endif + //Choose a worker thread that seems to be busy + env=&g_envs[rank]; + busy_env=myth_env_get_first_busy(env); + if (busy_env){ + //int ws_victim; +#if 0 +#ifdef MYTH_SCHED_LOOP_DEBUG + myth_dprintf("env %p is trying to steal thread from %p...\n",env,busy_env); +#endif +#endif + //ws_victim=busy_env->rank; + //Try to steal thread + next_run=myth_queue_take(&busy_env->runnable_q); + if (next_run){ +#ifdef MYTH_SCHED_LOOP_DEBUG + myth_dprintf("env %p is stealing thread %p from %p...\n",env,steal_th,busy_env); +#endif + myth_assert(next_run->status==MYTH_STATUS_READY); + //Change worker thread descriptor + next_run->env=env; + } + } +#ifdef MYTH_WS_PROF_DETAIL + t1=myth_get_rdtsc(); + if (g_sched_prof){ + env->prof_data.ws_attempt_count[busy_env->rank]++; + if (next_run){ + env->prof_data.ws_hit_cycles+=t1-t0; + env->prof_data.ws_hit_cnt++; + }else{ + env->prof_data.ws_miss_cycles+=t1-t0; + env->prof_data.ws_miss_cnt++; + } + } +#endif + return next_run; +} diff --git a/pool/shard000/C/0011690_rtl865x_proc.c b/pool/shard000/C/0011690_rtl865x_proc.c new file mode 100644 index 0000000000000000000000000000000000000000..f4065a6b23c8af657219ce3ffb6a09dedd05eba4 --- /dev/null +++ b/pool/shard000/C/0011690_rtl865x_proc.c @@ -0,0 +1,234 @@ +/* + * Copyright c Realtek Semiconductor Corporation, 2003 + * All rights reserved. + * + * $Author: davidm $ + * rtl865x_proc.c: /proc filesystem interface of RTL865x + * + */ +#include +#include +#include +#include +#include +#include + +#include "rtl865x/rtl_glue.h" /*rtlglue_printf( )*/ + +#define PROC_NAME "rtl865x" + +#define REG32(reg) (*(volatile unsigned int *)(reg)) +#define REG16(reg) (*(volatile unsigned short *)(reg)) +#define REG8(reg) (*(volatile unsigned char *)(reg)) + +static struct proc_dir_entry + *rtl865x_proc, *reg32_proc, *reg16_proc, *reg8_proc; +static unsigned int _reg32,_reg16,_reg8; +static struct proc_dir_entry + *mem32_proc, *mem16_proc, *mem8_proc; + +#define TMPSIZE 80 +static char tmp[TMPSIZE]; + +static int _read_reg32(char *page, char **start, + off_t off, int count, + int *eof, void *data){ + int len; + //rtlglue_printf("%s: %u=%08x\n", __FUNCTION__, _reg32,REG32(_reg32) ); + len = sprintf(page, "0x%08x\n", REG32(_reg32)); + return len; +} + +static int _read_reg16(char *page, char **start, + off_t off, int count, + int *eof, void *data){ + int len; + //rtlglue_printf("%s: %u=%04x\n", __FUNCTION__, _reg16,REG16(_reg16) ); + len = sprintf(page, "0x%04x\n", (unsigned short)REG16(_reg16)); + return len; +} + +static int _read_reg8(char *page, char **start, + off_t off, int count, + int *eof, void *data){ + int len; + //rtlglue_printf("%s: %u=%02x\n", __FUNCTION__, _reg8,REG8(_reg8) ); + len = sprintf(page, "0x%02x\n", (unsigned char) REG8(_reg8)); + return len; +} + + +static int _write_reg32(struct file *file, + const char *buffer, + unsigned long count, + void *data){ + if(copy_from_user(tmp, buffer, strlen(buffer))) + return -EFAULT; + _reg32=simple_strtoul(tmp, NULL,0); + //rtlglue_printf("%s: %u\n", __FUNCTION__, _reg32); + return strlen(buffer); +} + +static int _write_reg16(struct file *file, + const char *buffer, + unsigned long count, + void *data){ + if(copy_from_user(tmp, buffer, strlen(buffer))) + return -EFAULT; + _reg16=simple_strtoul(tmp, NULL,0); + //rtlglue_printf("%s: %u\n", __FUNCTION__, _reg16); + return strlen(buffer); +} + +static int _write_reg8(struct file *file, + const char *buffer, + unsigned long count, + void *data){ + if(copy_from_user(tmp, buffer, strlen(buffer))) + return -EFAULT; + _reg8=simple_strtoul(tmp, NULL,0); + //rtlglue_printf("%s: %u\n", __FUNCTION__, _reg8); + return strlen(buffer); +} + + +static int _write_mem32(struct file *file, + const char *buffer, + unsigned long count, + void *data){ + if(copy_from_user(tmp, buffer, strlen(buffer))) + return -EFAULT; + tmp[10]='\0'; + REG32(_reg32)=simple_strtoul(tmp, NULL,0); + rtlglue_printf("%s: %u\n", tmp, REG32(_reg32)); + return strlen(buffer); +} + +static int _write_mem16(struct file *file, + const char *buffer, + unsigned long count, + void *data){ + if(copy_from_user(tmp, buffer, strlen(buffer))) + return -EFAULT; + tmp[6]='\0'; + REG16(_reg16)=(unsigned short)simple_strtoul(tmp, NULL,0); + rtlglue_printf("%s: %u\n", tmp, REG16(_reg16)); + return strlen(buffer); +} + +static int _write_mem8(struct file *file, + const char *buffer, + unsigned long count, + void *data){ + if(copy_from_user(tmp, buffer, strlen(buffer))) + return -EFAULT; + tmp[4]='\0'; + REG8(_reg8)=(unsigned char)simple_strtoul(tmp, NULL,0); + rtlglue_printf("%s: %u\n", tmp, REG8(_reg8)); + return strlen(buffer); +} + + + +int rtl865x_init_procfs(void) +{ + int rv = 0; + + /* create directory */ + rtl865x_proc= proc_mkdir(PROC_NAME, NULL); + if(rtl865x_proc == NULL) { + rv = -ENOMEM; + goto out; + } + + reg32_proc = create_proc_entry("reg32", 0644, rtl865x_proc); + if(reg32_proc == NULL) { + rv = -ENOMEM; + goto reg32_out; + } + reg32_proc->data = reg32_proc->owner = NULL; + reg32_proc->read_proc = _read_reg32; + reg32_proc->write_proc = _write_reg32; + + reg16_proc = create_proc_entry("reg16", 0644, rtl865x_proc); + if(reg16_proc == NULL) { + rv = -ENOMEM; + goto reg16_out; + } + reg16_proc->data = reg16_proc->owner = NULL; + reg16_proc->read_proc = _read_reg16; + reg16_proc->write_proc = _write_reg16; + + reg8_proc = create_proc_entry("reg8", 0644, rtl865x_proc); + if(reg8_proc == NULL) { + rv = -ENOMEM; + goto reg8_out; + } + reg8_proc->data = reg8_proc->owner = NULL; + reg8_proc->read_proc = _read_reg8; + reg8_proc->write_proc = _write_reg8; + + + mem32_proc = create_proc_entry("mem32", 0644, rtl865x_proc); + if(mem32_proc == NULL) { + rv = -ENOMEM; + goto mem32_out; + } + mem32_proc->data = mem32_proc->owner = NULL; + mem32_proc->read_proc = NULL; + mem32_proc->write_proc = _write_mem32; + + mem16_proc = create_proc_entry("mem16", 0644, rtl865x_proc); + if(mem16_proc == NULL) { + rv = -ENOMEM; + goto mem16_out; + } + mem16_proc->data = mem16_proc->owner = NULL; + mem16_proc->read_proc = NULL; + mem16_proc->write_proc = _write_mem16; + + mem8_proc = create_proc_entry("mem8", 0644, rtl865x_proc); + if(mem8_proc == NULL) { + rv = -ENOMEM; + goto mem8_out; + } + mem8_proc->data = mem8_proc->owner = NULL; + mem8_proc->read_proc = NULL; + mem8_proc->write_proc = _write_mem8; + + + /* everything OK */ + //rtlglue_printf("proc entry '%s' initialised\n",PROC_NAME); + return 0; + +//should be in reverse order +mem8_out: + remove_proc_entry("mem8", rtl865x_proc); +mem16_out: + remove_proc_entry("mem16", rtl865x_proc); +mem32_out: + remove_proc_entry("mem32", rtl865x_proc); +reg8_out: + remove_proc_entry("reg8", rtl865x_proc); +reg16_out: + remove_proc_entry("reg16", rtl865x_proc); +reg32_out: + remove_proc_entry("reg32", rtl865x_proc); +out: + return rv; +} + + +void rtl865x_cleanup_procfs(void) +{ + remove_proc_entry("reg32", rtl865x_proc); + remove_proc_entry("reg16", rtl865x_proc); + remove_proc_entry("reg8", rtl865x_proc); + remove_proc_entry("mem32", rtl865x_proc); + remove_proc_entry("mem16", rtl865x_proc); + remove_proc_entry("mem8", rtl865x_proc); + remove_proc_entry(PROC_NAME, NULL); + + rtlglue_printf("proc entry '%s' removed\n",PROC_NAME); +} + diff --git a/pool/shard000/C/0011711_ips.c b/pool/shard000/C/0011711_ips.c new file mode 100644 index 0000000000000000000000000000000000000000..8ee29dbea5f2e0c1bb6078087022a2a986cb6e62 --- /dev/null +++ b/pool/shard000/C/0011711_ips.c @@ -0,0 +1,332 @@ +/********************************************************************** +* IPS PATCH MAKER +**********************************************************************/ + +/********************************************************************** +* INCLUDE +**********************************************************************/ +#include + +/********************************************************************** +* MACRO +**********************************************************************/ +#define EXPORT __export +#define EOF -1 + +/********************************************************************** +* VARIABLE GLOBAL +**********************************************************************/ + static unsigned char *buffer; + static unsigned long address = 0; + static unsigned long count = 0; + static BOOL userle = TRUE; + +/********************************************************************** +* STRUCTURE +**********************************************************************/ + typedef struct FILEINFO + { + HANDLE hFile; + DWORD nBufCount; + DWORD nBufSize; + BOOL bEof; + BYTE lpBuffer[1024]; + } FILEINFO, *LPFILEINFO; + + static HANDLE ips; + static LPFILEINFO uf, cf; + +/********************************************************************** +* PROTOTYPES +**********************************************************************/ + static LPFILEINFO WINAPI LoadFile(LPCSTR lpszFilename); + static void WINAPI ReloadBuffer(LPFILEINFO f); + static int WINAPI ReadByte(LPFILEINFO f); + static void WINAPI flushBuf(void); + static void WINAPI addByte(unsigned char c); + static void WINAPI WriteBlock(DWORD Address,DWORD Length,LPBYTE Data); + static void WINAPI WriteBlockRLE(DWORD Address,DWORD RunLength,BYTE RunByte); + //BOOL WINAPI EXPORT MakePatch(LPCSTR UnchangedFile,LPCSTR ChangedFile,LPCSTR OutputFile,LPSTR ErrorMsg,BOOL bUseRle); + BOOL WINAPI EXPORT MakePatch(LPCSTR UnchangedFile,LPCSTR ChangedFile,LPCSTR OutputFile,BOOL bUseRle); + +/********************************************************************** +* LOAD FILE +* Description : Ouvre un fichier en lecture +* Type : API +**********************************************************************/ +static LPFILEINFO WINAPI LoadFile(LPCSTR lpszFilename) +{ + LPFILEINFO f; + + // allocate FILEINFO + f = (LPFILEINFO)GlobalAlloc(GPTR,sizeof(FILEINFO)); + if(!f) return NULL; + + // open file + f->hFile = CreateFile(lpszFilename, GENERIC_READ, FILE_SHARE_READ, NULL,OPEN_EXISTING, 0, NULL); + if(f->hFile == INVALID_HANDLE_VALUE) return NULL; + + ReloadBuffer(f); + + return f; +} + +/********************************************************************** +* RELOAD BUFFER +* Description : Relod le buffer du fichier +* Type : API +**********************************************************************/ +// reloads the read buffer of a file +static void WINAPI ReloadBuffer(LPFILEINFO f) +{ + // refill the buffer + ReadFile(f->hFile,f->lpBuffer,1024,&f->nBufSize,NULL); + f->bEof = (f->nBufSize == 0); + f->nBufCount = 0; +} + +/********************************************************************** +* CLOSE FILE +* Description : Ferme un fichier +* Type : API +**********************************************************************/ +static void WINAPI CloseFile(LPFILEINFO f) +{ + CloseHandle(f->hFile); + GlobalFree(f); +} + +/********************************************************************** +* READ BYTE +* Description : Lis un Byte dans un fichier +* Type : API +**********************************************************************/ +static int WINAPI ReadByte(LPFILEINFO f) +{ + int byte; + + if(f->bEof) return EOF; + + // grab byte from buffer + byte = f->lpBuffer[f->nBufCount++]; + if(f->nBufCount >= f->nBufSize) ReloadBuffer(f); + + return byte; +} + +/********************************************************************** +* FLUSH BUFFER +* Description : Ecrit un block [address, length, data] dans le fichier IPS. +* Type : API +**********************************************************************/ +static void WINAPI flushBuf(void) +{ + unsigned long start, end; + int i, j, runcount; + unsigned char runbyte; + + if(count) + { + // if block is < size 3, ecrit normale + if(count <= 3 || !userle) + WriteBlock(address,count,buffer); + else if(count <= 16) + { + // if moins que 16, check pour la compression RLE + runbyte = buffer[0]; + for(i = 0; i < count; i++) + if(buffer[i] != runbyte) break; + + // Compresser seulement si le block entier est le meme. + if(i == 16) WriteBlockRLE(address,count,runbyte); + else WriteBlock(address,count,buffer); + } + else + { // sinon compresser tous les block > 16 dup + start = end = address; + for(i = 0; i < count; i++, end++) + { + // check pour la compression RLE + if((i + 16) < count + && buffer[i] == buffer[i + 1] + && buffer[i] == buffer[i + 16]) + { + runbyte = buffer[i]; + runcount = 2; + + for(j = i + 2; j < count; j++, runcount++) + if(buffer[j] != runbyte) break; + + if(runcount >= 16) + { + WriteBlock(start,end - start,buffer + start - address); + WriteBlockRLE(i + address,runcount,runbyte); + start = end + runcount; + end = start - 1; + i += runcount - 1; + } + } + } + WriteBlock(start,end - start,buffer + start - address); + } + + count = 0; + } +} + +/********************************************************************** +* WRITE BLOCK +* Description : Ecrit un block [address, length, data] dans le fichier IPS. +* Type : API +**********************************************************************/ +static void WINAPI WriteBlock(DWORD Address,DWORD Length,LPBYTE Data) +{ + DWORD addr, nSize; + WORD len; + + if(Length) + { + // inverser les adresses LSB->MSB + addr = ((Address >> 16) & 0xFF) | (Address & 0xFF00) | ((Address & 0xFF) << 16); + WriteFile(ips,&addr,3,&nSize,NULL); + // LSB -> MSB + len = (WORD)(((Length >> 8) & 0xFF) | ((Length & 0xFF) << 8)); + WriteFile(ips,&len,2,&nSize,NULL); + // ecrit le data + WriteFile(ips,Data,Length,&nSize,NULL); + } +} + +/********************************************************************** +* WRITE BLOCK RLE +* Description : Ecrit un block [address, runlength, runbyte] dans le fichier IPS. +* Type : API +**********************************************************************/ +static void WINAPI WriteBlockRLE(DWORD Address,DWORD RunLength,BYTE RunByte) +{ + DWORD addr, nSize; + WORD len; + + if(RunLength) + { + // inverser les adresses LSB->MSB + addr = ((Address >> 16) & 0xFF) | (Address & 0xFF00) | ((Address & 0xFF) << 16); + WriteFile(ips,&addr,3,&nSize,NULL); + // ecrit 0 au conteur + len = 0; + WriteFile(ips,&len,2,&nSize,NULL); + // LSB -> MSB + len = (WORD)(((RunLength >> 8) & 0xFF) | ((RunLength & 0xFF) << 8)); + WriteFile(ips,&len,2,&nSize,NULL); + // ecrit le data + WriteFile(ips,&RunByte,1,&nSize,NULL); + } +} + +/********************************************************************** +* ADD BYTE +* Description : Place un byte dans le block buffer +* Type : API +**********************************************************************/ +static void WINAPI addByte(unsigned char c) +{ + if(count >= 65535L) flushBuf(), address += 65535L; + buffer[count++] = c; +} + +/********************************************************************** +* MAKE PATCH +* Description : Fabrique une patch +* Type : API EXPORT +**********************************************************************/ +BOOL __stdcall MakePatch(LPCSTR UnchangedFile,LPCSTR ChangedFile,LPCSTR OutputFile,BOOL bUseRle) +{ + int byte1, byte2; + unsigned long offset; + DWORD nSize; + + // réserve de la mémoire pour le buffer + buffer = (unsigned char *)GlobalAlloc(GPTR,65536); + if(!buffer) + { + return FALSE; + } + + // charge le fichier non changer + uf = LoadFile(UnchangedFile); + if(!uf) + { + //if(ErrorMsg) wsprintf(ErrorMsg,"%s: Ne peut trouver le fichier.",UnchangedFile); + goto err0; + } + + // charge le fichier modifier + cf = LoadFile(ChangedFile); + if(!cf) + { + //if(ErrorMsg) wsprintf(ErrorMsg,"%s: Ne peut trouver le fichier.",ChangedFile); + goto err1; + } + + if(GetFileSize(cf,NULL) < GetFileSize(uf,NULL)) + { + //if(ErrorMsg) wsprintf(ErrorMsg,"La taile du fichier modifié est plus petite que la taille du fichier original."); + goto err2; + } + + // créé le IPS de sortie + ips = CreateFile(OutputFile,GENERIC_WRITE,FILE_SHARE_WRITE,NULL,CREATE_ALWAYS,0,NULL); + if(ips == INVALID_HANDLE_VALUE) + { + //if(ErrorMsg) wsprintf(ErrorMsg,"%s: Ne peut ecrire dans le fichier.",OutputFile); + goto err2; + } + + // write signature + WriteFile(ips,"PATCH",5,&nSize,NULL); + + userle = bUseRle; + + offset = 0; + for(;;) + { + // read byte from both files + byte1 = ReadByte(uf); + byte2 = ReadByte(cf); + if(byte2 == EOF) break; + + offset++; // increment offset + // compare the 2 bytes + if(byte1 == EOF || byte1 != byte2) + { + // si les 2 bytes ne sont pas égale, alors ajoute byte2 au block buffer + addByte((unsigned char)byte2); + } + else + { + // si les bytes sont identiques + flushBuf(); // flush le buffer + address = offset; // ajuste les addresse + } + } + flushBuf(); + + // write EOF + WriteFile(ips,"EOF",3,&nSize,NULL); + + CloseHandle(ips); + CloseFile(uf); + CloseFile(cf); + GlobalFree(buffer); + + return TRUE; + +err2: + CloseFile(cf); +err1: + CloseFile(uf); +err0: + GlobalFree(buffer); + + return FALSE; +} \ No newline at end of file diff --git a/pool/shard000/C/0011713_gl_usb.c b/pool/shard000/C/0011713_gl_usb.c new file mode 100644 index 0000000000000000000000000000000000000000..5fa7fd22182aaf29c290799b55374beaa301c111 --- /dev/null +++ b/pool/shard000/C/0011713_gl_usb.c @@ -0,0 +1,207 @@ +/* + * This file is part of the sigrok project. + * + * Copyright (C) 2010 Sven Peter + * Copyright (C) 2010 Haxx Enterprises + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or + * without modification, are permitted provided that the following + * conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include "gl_usb.h" + +#define CTRL_IN (LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_IN | \ + LIBUSB_RECIPIENT_INTERFACE) +#define CTRL_OUT (LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_OUT | \ + LIBUSB_RECIPIENT_INTERFACE) + +const int PACKET_CTRL_LEN = 2; +const int PACKET_INT_LEN = 2; +const int PACKET_BULK_LEN = 64; +const int INTERFACE = 0; +const int ENDPOINT_INT_IN = 0x81; /* Endpoint 0x81 address for IN */ +const int ENDPOINT_INT_OUT = 0x01; /* Endpoint 1 address for OUT */ +const int ENDPOINT_BULK_IN = 0x81; /* Endpoint 0x81 address for IN */ +const int ENDPOINT_BULK_OUT = 0x02; /* Endpoint 1 address for OUT */ +const int TIMEOUT = 5000; /* Timeout in ms */ + +enum { + REQ_READBULK = 0x82, + REQ_WRITEADDR, + REQ_READDATA, + REQ_WRITEDATA, +}; + +static struct libusb_device_handle *g_devh = NULL; + +int gl_write_address(libusb_device_handle *devh, unsigned int address) +{ + unsigned char packet[8] = { address & 0xFF }; + int ret; + + ret = libusb_control_transfer(devh, CTRL_OUT, 0xc, REQ_WRITEADDR, + 0, packet, 1, TIMEOUT); + if (ret != 1) + sr_err("%s: libusb_control_transfer returned %d\n", + __func__, ret); + return ret; +} + +int gl_write_data(libusb_device_handle *devh, unsigned int val) +{ + unsigned char packet[8] = { val & 0xFF }; + int ret; + + ret = libusb_control_transfer(devh, CTRL_OUT, 0xc, REQ_WRITEDATA, + 0, packet, 1, TIMEOUT); + if (ret != 1) + sr_err("%s: libusb_control_transfer returned %d\n", + __func__, ret); + return ret; +} + +int gl_read_data(libusb_device_handle *devh) +{ + unsigned char packet[8] = { 0 }; + int ret; + + ret = libusb_control_transfer(devh, CTRL_IN, 0xc, REQ_READDATA, + 0, packet, 1, TIMEOUT); + if (ret != 1) + sr_err("%s: libusb_control_transfer returned %d, val=%hhx\n", + __func__, ret, packet[0]); + return (ret == 1) ? packet[0] : ret; +} + +int gl_read_bulk(libusb_device_handle *devh, void *buffer, unsigned int size) +{ + unsigned char packet[8] = + { 0, 0, 0, 0, size & 0xff, (size & 0xff00) >> 8, + (size & 0xff0000) >> 16, (size & 0xff000000) >> 24 }; + int ret, transferred = 0; + + ret = libusb_control_transfer(devh, CTRL_OUT, 0x4, REQ_READBULK, + 0, packet, 8, TIMEOUT); + if (ret != 8) + sr_err("%s: libusb_control_transfer returned %d\n", + __func__, ret); + + ret = libusb_bulk_transfer(devh, ENDPOINT_BULK_IN, buffer, size, + &transferred, TIMEOUT); + if (ret < 0) + sr_err("Bulk read error %d\n", ret); + return transferred; +} + +int gl_reg_write(libusb_device_handle *devh, unsigned int reg, + unsigned int val) +{ + int ret; + + ret = gl_write_address(devh, reg); + if (ret < 0) + return ret; + ret = gl_write_data(devh, val); + return ret; +} + +int gl_reg_read(libusb_device_handle *devh, unsigned int reg) +{ + int ret; + + ret = gl_write_address(devh, reg); + if (ret < 0) + return ret; + ret = gl_read_data(devh); + return ret; +} + +int gl_open(int vid) +{ + int ret; + struct libusb_device **devs; + struct libusb_device *dev; + size_t i = 0; + struct libusb_device_descriptor desc; + + ret = libusb_init(NULL); + if (ret < 0) + return GL_ELIBUSB; + + if (libusb_get_device_list(NULL, &devs) < 0) { + ret = GL_EOPEN; + goto gl_open_error; + } + + while ((dev = devs[i++]) != NULL) { + if (libusb_get_device_descriptor(dev, &desc) < 0) + break; + + if (desc.idVendor == vid) { + if (libusb_open(dev, &g_devh) < 0) + g_devh = NULL; + break; + } + } + + libusb_free_device_list(devs, 1); + + if (!g_devh) { + ret = GL_EOPEN; + goto gl_open_error; + } + + ret = libusb_set_configuration(g_devh, 1); + if (ret < 0) { + ret = GL_ESETCONFIG; + goto gl_open_error; + } + + ret = libusb_claim_interface(g_devh, 0); + if (ret < 0) { + ret = GL_ECLAIM; + goto gl_open_error; + } + + return GL_OK; + +gl_open_error: + gl_close(); + return ret; +} + +int gl_close(void) +{ + if (g_devh) { + libusb_release_interface(g_devh, 0); + libusb_reset_device(g_devh); + libusb_close(g_devh); + } + libusb_exit(NULL); + + return 0; +} diff --git a/pool/shard000/C/0011719_vfs_addr.c b/pool/shard000/C/0011719_vfs_addr.c new file mode 100644 index 0000000000000000000000000000000000000000..61d3d44b2ff51138140460156f589f431f2d5164 --- /dev/null +++ b/pool/shard000/C/0011719_vfs_addr.c @@ -0,0 +1,361 @@ +/* + * linux/fs/9p/vfs_addr.c + * + * This file contians vfs address (mmap) ops for 9P2000. + * + * Copyright (C) 2005 by Eric Van Hensbergen + * Copyright (C) 2002 by Ron Minnich + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * 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: + * Free Software Foundation + * 51 Franklin Street, Fifth Floor + * Boston, MA 02111-1301 USA + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "v9fs.h" +#include "v9fs_vfs.h" +#include "cache.h" +#include "fid.h" + +/** + * v9fs_fid_readpage - read an entire page in from 9P + * + * @fid: fid being read + * @page: structure to page + * + */ +static int v9fs_fid_readpage(struct p9_fid *fid, struct page *page) +{ + int retval; + loff_t offset; + char *buffer; + struct inode *inode; + + inode = page->mapping->host; + p9_debug(P9_DEBUG_VFS, "\n"); + + BUG_ON(!PageLocked(page)); + + retval = v9fs_readpage_from_fscache(inode, page); + if (retval == 0) + return retval; + + buffer = kmap(page); + offset = page_offset(page); + + retval = v9fs_fid_readn(fid, buffer, NULL, PAGE_CACHE_SIZE, offset); + if (retval < 0) { + v9fs_uncache_page(inode, page); + goto done; + } + + memset(buffer + retval, 0, PAGE_CACHE_SIZE - retval); + flush_dcache_page(page); + SetPageUptodate(page); + + v9fs_readpage_to_fscache(inode, page); + retval = 0; + +done: + kunmap(page); + unlock_page(page); + return retval; +} + +/** + * v9fs_vfs_readpage - read an entire page in from 9P + * + * @filp: file being read + * @page: structure to page + * + */ + +static int v9fs_vfs_readpage(struct file *filp, struct page *page) +{ + return v9fs_fid_readpage(filp->private_data, page); +} + +/** + * v9fs_vfs_readpages - read a set of pages from 9P + * + * @filp: file being read + * @mapping: the address space + * @pages: list of pages to read + * @nr_pages: count of pages to read + * + */ + +static int v9fs_vfs_readpages(struct file *filp, struct address_space *mapping, + struct list_head *pages, unsigned nr_pages) +{ + int ret = 0; + struct inode *inode; + + inode = mapping->host; + p9_debug(P9_DEBUG_VFS, "inode: %p file: %p\n", inode, filp); + + ret = v9fs_readpages_from_fscache(inode, mapping, pages, &nr_pages); + if (ret == 0) + return ret; + + ret = read_cache_pages(mapping, pages, (void *)v9fs_vfs_readpage, filp); + p9_debug(P9_DEBUG_VFS, " = %d\n", ret); + return ret; +} + +/** + * v9fs_release_page - release the private state associated with a page + * + * Returns 1 if the page can be released, false otherwise. + */ + +static int v9fs_release_page(struct page *page, gfp_t gfp) +{ + if (PagePrivate(page)) + return 0; + return v9fs_fscache_release_page(page, gfp); +} + +/** + * v9fs_invalidate_page - Invalidate a page completely or partially + * + * @page: structure to page + * @offset: offset in the page + */ + +static void v9fs_invalidate_page(struct page *page, unsigned int offset, + unsigned int length) +{ + /* + * If called with zero offset, we should release + * the private state assocated with the page + */ + if (offset == 0 && length == PAGE_CACHE_SIZE) + v9fs_fscache_invalidate_page(page); +} + +static int v9fs_vfs_writepage_locked(struct page *page) +{ + char *buffer; + int retval, len; + loff_t offset, size; + mm_segment_t old_fs; + struct v9fs_inode *v9inode; + struct inode *inode = page->mapping->host; + + v9inode = V9FS_I(inode); + size = i_size_read(inode); + if (page->index == size >> PAGE_CACHE_SHIFT) + len = size & ~PAGE_CACHE_MASK; + else + len = PAGE_CACHE_SIZE; + + set_page_writeback(page); + + buffer = kmap(page); + offset = page_offset(page); + + old_fs = get_fs(); + set_fs(get_ds()); + /* We should have writeback_fid always set */ + BUG_ON(!v9inode->writeback_fid); + + retval = v9fs_file_write_internal(inode, + v9inode->writeback_fid, + (const char __force_user *)buffer, + len, &offset, 0); + if (retval > 0) + retval = 0; + + set_fs(old_fs); + kunmap(page); + end_page_writeback(page); + return retval; +} + +static int v9fs_vfs_writepage(struct page *page, struct writeback_control *wbc) +{ + int retval; + + p9_debug(P9_DEBUG_VFS, "page %p\n", page); + + retval = v9fs_vfs_writepage_locked(page); + if (retval < 0) { + if (retval == -EAGAIN) { + redirty_page_for_writepage(wbc, page); + retval = 0; + } else { + SetPageError(page); + mapping_set_error(page->mapping, retval); + } + } else + retval = 0; + + unlock_page(page); + return retval; +} + +/** + * v9fs_launder_page - Writeback a dirty page + * Returns 0 on success. + */ + +static int v9fs_launder_page(struct page *page) +{ + int retval; + struct inode *inode = page->mapping->host; + + v9fs_fscache_wait_on_page_write(inode, page); + if (clear_page_dirty_for_io(page)) { + retval = v9fs_vfs_writepage_locked(page); + if (retval) + return retval; + } + return 0; +} + +/** + * v9fs_direct_IO - 9P address space operation for direct I/O + * @rw: direction (read or write) + * @iocb: target I/O control block + * @iov: array of vectors that define I/O buffer + * @pos: offset in file to begin the operation + * @nr_segs: size of iovec array + * + * The presence of v9fs_direct_IO() in the address space ops vector + * allowes open() O_DIRECT flags which would have failed otherwise. + * + * In the non-cached mode, we shunt off direct read and write requests before + * the VFS gets them, so this method should never be called. + * + * Direct IO is not 'yet' supported in the cached mode. Hence when + * this routine is called through generic_file_aio_read(), the read/write fails + * with an error. + * + */ +static ssize_t +v9fs_direct_IO(int rw, struct kiocb *iocb, const struct iovec *iov, + loff_t pos, unsigned long nr_segs) +{ + /* + * FIXME + * Now that we do caching with cache mode enabled, We need + * to support direct IO + */ + p9_debug(P9_DEBUG_VFS, "v9fs_direct_IO: v9fs_direct_IO (%s) off/no(%lld/%lu) EINVAL\n", + iocb->ki_filp->f_path.dentry->d_name.name, + (long long)pos, nr_segs); + + return -EINVAL; +} + +static int v9fs_write_begin(struct file *filp, struct address_space *mapping, + loff_t pos, unsigned len, unsigned flags, + struct page **pagep, void **fsdata) +{ + int retval = 0; + struct page *page; + struct v9fs_inode *v9inode; + pgoff_t index = pos >> PAGE_CACHE_SHIFT; + struct inode *inode = mapping->host; + + + p9_debug(P9_DEBUG_VFS, "filp %p, mapping %p\n", filp, mapping); + + v9inode = V9FS_I(inode); +start: + page = grab_cache_page_write_begin(mapping, index, flags); + if (!page) { + retval = -ENOMEM; + goto out; + } + BUG_ON(!v9inode->writeback_fid); + if (PageUptodate(page)) + goto out; + + if (len == PAGE_CACHE_SIZE) + goto out; + + retval = v9fs_fid_readpage(v9inode->writeback_fid, page); + page_cache_release(page); + if (!retval) + goto start; +out: + *pagep = page; + return retval; +} + +static int v9fs_write_end(struct file *filp, struct address_space *mapping, + loff_t pos, unsigned len, unsigned copied, + struct page *page, void *fsdata) +{ + loff_t last_pos = pos + copied; + struct inode *inode = page->mapping->host; + + p9_debug(P9_DEBUG_VFS, "filp %p, mapping %p\n", filp, mapping); + + if (unlikely(copied < len)) { + /* + * zero out the rest of the area + */ + unsigned from = pos & (PAGE_CACHE_SIZE - 1); + + zero_user(page, from + copied, len - copied); + flush_dcache_page(page); + } + + if (!PageUptodate(page)) + SetPageUptodate(page); + /* + * No need to use i_size_read() here, the i_size + * cannot change under us because we hold the i_mutex. + */ + if (last_pos > inode->i_size) { + inode_add_bytes(inode, last_pos - inode->i_size); + i_size_write(inode, last_pos); + } + set_page_dirty(page); + unlock_page(page); + page_cache_release(page); + + return copied; +} + + +const struct address_space_operations v9fs_addr_operations = { + .readpage = v9fs_vfs_readpage, + .readpages = v9fs_vfs_readpages, + .set_page_dirty = __set_page_dirty_nobuffers, + .writepage = v9fs_vfs_writepage, + .write_begin = v9fs_write_begin, + .write_end = v9fs_write_end, + .releasepage = v9fs_release_page, + .invalidatepage = v9fs_invalidate_page, + .launder_page = v9fs_launder_page, + .direct_IO = v9fs_direct_IO, +}; diff --git a/pool/shard000/C/0011720_lash_debug_timer.c b/pool/shard000/C/0011720_lash_debug_timer.c new file mode 100644 index 0000000000000000000000000000000000000000..b63969ad52d81bed077faa4327dd5ba14be95321 --- /dev/null +++ b/pool/shard000/C/0011720_lash_debug_timer.c @@ -0,0 +1,48 @@ +#include + +#include "liblash/lash_debug_timer.h" + +void lash_debugTimerReset(lash_debug_timer_t *time) { + time->running = 0; + time->paused = 0; + time->count = 0; + time->total = 0; +} + +void lash_debugTimerStart(lash_debug_timer_t *time) { + clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &(time->snap_start)); + time->running = 1; +} + +long lash_debugTimerPause(lash_debug_timer_t *time) { + if (!time->running) + return 0; + + if (time->paused) { + clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &(time->snap_tmp)); + time->snap_start.tv_nsec += time->snap_tmp.tv_nsec - time->snap_end.tv_nsec; + time->paused = 0; + return time->snap_tmp.tv_nsec; + } else { + clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &(time->snap_end)); + time->paused = 1; + return time->snap_end.tv_nsec; + } +} + +void lash_debugTimerStop(lash_debug_timer_t * time) { + if (time->running == 0) + return; + + if (!time->paused) + clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &(time->snap_end)); + + time->total = time->snap_end.tv_nsec - time->snap_start.tv_nsec; + time->count++; + time->running = 0; + time->paused = 0; +} + +float lash_debugTimerGetAverage(lash_debug_timer_t *time) { + return time->total / (float)time->count; +} diff --git a/pool/shard000/C/0011721_cfi_flagadm.c b/pool/shard000/C/0011721_cfi_flagadm.c new file mode 100644 index 0000000000000000000000000000000000000000..aff8bd7afeb3d24094471139c8128ae6194517af --- /dev/null +++ b/pool/shard000/C/0011721_cfi_flagadm.c @@ -0,0 +1,139 @@ +/* + * Copyright © 2001 Flaga hf. Medical Devices, Kári Davíðsson + * + * $Id: cfi_flagadm.c,v 1.1.1.1 2010/12/02 04:24:12 walf_wu Exp $ + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN + * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * 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., + * 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + + +/* We split the flash chip up into four parts. + * 1: bootloader firts 128k (0x00000000 - 0x0001FFFF) size 0x020000 + * 2: kernel 640k (0x00020000 - 0x000BFFFF) size 0x0A0000 + * 3: compressed 1536k root ramdisk (0x000C0000 - 0x0023FFFF) size 0x180000 + * 4: writeable diskpartition (jffs)(0x00240000 - 0x003FFFFF) size 0x1C0000 + */ + +#define FLASH_PHYS_ADDR 0x40000000 +#define FLASH_SIZE 0x400000 + +#define FLASH_PARTITION0_ADDR 0x00000000 +#define FLASH_PARTITION0_SIZE 0x00020000 + +#define FLASH_PARTITION1_ADDR 0x00020000 +#define FLASH_PARTITION1_SIZE 0x000A0000 + +#define FLASH_PARTITION2_ADDR 0x000C0000 +#define FLASH_PARTITION2_SIZE 0x00180000 + +#define FLASH_PARTITION3_ADDR 0x00240000 +#define FLASH_PARTITION3_SIZE 0x001C0000 + + +struct map_info flagadm_map = { + .name = "FlagaDM flash device", + .size = FLASH_SIZE, + .bankwidth = 2, +}; + +struct mtd_partition flagadm_parts[] = { + { + .name = "Bootloader", + .offset = FLASH_PARTITION0_ADDR, + .size = FLASH_PARTITION0_SIZE + }, + { + .name = "Kernel image", + .offset = FLASH_PARTITION1_ADDR, + .size = FLASH_PARTITION1_SIZE + }, + { + .name = "Initial ramdisk image", + .offset = FLASH_PARTITION2_ADDR, + .size = FLASH_PARTITION2_SIZE + }, + { + .name = "Persistent storage", + .offset = FLASH_PARTITION3_ADDR, + .size = FLASH_PARTITION3_SIZE + } +}; + +#define PARTITION_COUNT ARRAY_SIZE(flagadm_parts) + +static struct mtd_info *mymtd; + +int __init init_flagadm(void) +{ + printk(KERN_NOTICE "FlagaDM flash device: %x at %x\n", + FLASH_SIZE, FLASH_PHYS_ADDR); + + flagadm_map.phys = FLASH_PHYS_ADDR; + flagadm_map.virt = ioremap(FLASH_PHYS_ADDR, + FLASH_SIZE); + + if (!flagadm_map.virt) { + printk("Failed to ioremap\n"); + return -EIO; + } + + simple_map_init(&flagadm_map); + + mymtd = do_map_probe("cfi_probe", &flagadm_map); + if (mymtd) { + mymtd->owner = THIS_MODULE; + add_mtd_partitions(mymtd, flagadm_parts, PARTITION_COUNT); + printk(KERN_NOTICE "FlagaDM flash device initialized\n"); + return 0; + } + + iounmap((void *)flagadm_map.virt); + return -ENXIO; +} + +static void __exit cleanup_flagadm(void) +{ + if (mymtd) { + del_mtd_partitions(mymtd); + map_destroy(mymtd); + } + if (flagadm_map.virt) { + iounmap((void *)flagadm_map.virt); + flagadm_map.virt = 0; + } +} + +module_init(init_flagadm); +module_exit(cleanup_flagadm); + + +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("Kári Davíðsson "); +MODULE_DESCRIPTION("MTD map driver for Flaga digital module"); diff --git a/pool/shard000/C/0011735_empathy-connection-aggregator.c b/pool/shard000/C/0011735_empathy-connection-aggregator.c new file mode 100644 index 0000000000000000000000000000000000000000..fde365c27eaa25995f494394b048a90542b435db --- /dev/null +++ b/pool/shard000/C/0011735_empathy-connection-aggregator.c @@ -0,0 +1,290 @@ +/* + * empathy-connection-aggregator.c - Source for EmpathyConnectionAggregator + * Copyright (C) 2010 Collabora Ltd. + * @author Cosimo Cecchi + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include + +#include "empathy-connection-aggregator.h" + +#include + +#define DEBUG_FLAG EMPATHY_DEBUG_OTHER +#include "empathy-debug.h" +#include "empathy-utils.h" + + +#include "extensions/extensions.h" + +G_DEFINE_TYPE (EmpathyConnectionAggregator, empathy_connection_aggregator, + G_TYPE_OBJECT); + +enum { + EVENT_CONTACT_LIST_CHANGED, + LAST_SIGNAL +}; + +static guint signals[LAST_SIGNAL]; + +struct _EmpathyConnectionAggregatorPriv { + TpAccountManager *mgr; + + /* List of owned TpConnection */ + GList *conns; +}; + +static void +empathy_connection_aggregator_dispose (GObject *object) +{ + EmpathyConnectionAggregator *self = (EmpathyConnectionAggregator *) object; + + g_clear_object (&self->priv->mgr); + + g_list_free_full (self->priv->conns, g_object_unref); + self->priv->conns = NULL; + + G_OBJECT_CLASS (empathy_connection_aggregator_parent_class)->dispose (object); +} + +static void +empathy_connection_aggregator_class_init ( + EmpathyConnectionAggregatorClass *klass) +{ + GObjectClass *oclass = G_OBJECT_CLASS (klass); + + oclass->dispose = empathy_connection_aggregator_dispose; + + signals[EVENT_CONTACT_LIST_CHANGED] = + g_signal_new ("contact-list-changed", + G_TYPE_FROM_CLASS (klass), + G_SIGNAL_RUN_LAST, + 0, + NULL, NULL, + g_cclosure_marshal_generic, + G_TYPE_NONE, + 2, G_TYPE_PTR_ARRAY, G_TYPE_PTR_ARRAY); + + g_type_class_add_private (klass, sizeof (EmpathyConnectionAggregatorPriv)); +} + +static void +contact_list_changed_cb (TpConnection *conn, + GPtrArray *added, + GPtrArray *removed, + EmpathyConnectionAggregator *self) +{ + g_signal_emit (self, signals[EVENT_CONTACT_LIST_CHANGED], 0, added, removed); +} + +static void +conn_invalidated_cb (TpConnection *conn, + guint domain, + gint code, + gchar *message, + EmpathyConnectionAggregator *self) +{ + self->priv->conns = g_list_remove (self->priv->conns, conn); + + g_object_unref (conn); +} + +static void +check_connection (EmpathyConnectionAggregator *self, + TpConnection *conn) +{ + GPtrArray *contacts; + + if (g_list_find (self->priv->conns, conn) != NULL) + return; + + self->priv->conns = g_list_prepend (self->priv->conns, + g_object_ref (conn)); + + tp_g_signal_connect_object (conn, "contact-list-changed", + G_CALLBACK (contact_list_changed_cb), self, 0); + + contacts = tp_connection_dup_contact_list (conn); + if (contacts != NULL) + { + GPtrArray *empty; + + empty = g_ptr_array_new (); + + contact_list_changed_cb (conn, contacts, empty, self); + g_ptr_array_unref (empty); + } + + tp_g_signal_connect_object (conn, "invalidated", + G_CALLBACK (conn_invalidated_cb), self, 0); +} + +static void +check_account (EmpathyConnectionAggregator *self, + TpAccount *account) +{ + TpConnection *conn; + + conn = tp_account_get_connection (account); + if (conn != NULL) + check_connection (self, conn); +} + +static void +account_conn_changed_cb (TpAccount *account, + GParamSpec *spec, + EmpathyConnectionAggregator *self) +{ + check_account (self, account); +} + +static void +add_account (EmpathyConnectionAggregator *self, + TpAccount *account) +{ + check_account (self, account); + + tp_g_signal_connect_object (account, "notify::connection", + G_CALLBACK (account_conn_changed_cb), self, 0); +} + +static void +account_validity_changed_cb (TpAccountManager *manager, + TpAccount *account, + gboolean valid, + EmpathyConnectionAggregator *self) +{ + if (valid) + add_account (self, account); +} + +static void +am_prepare_cb (GObject *source, + GAsyncResult *result, + gpointer user_data) +{ + EmpathyConnectionAggregator *self = EMPATHY_CONNECTION_AGGREGATOR (user_data); + GError *error = NULL; + GList *accounts, *l; + + if (!tp_proxy_prepare_finish (source, result, &error)) + { + DEBUG ("Failed to prepare account manager: %s", error->message); + g_error_free (error); + goto out; + } + + accounts = tp_account_manager_get_valid_accounts (self->priv->mgr); + for (l = accounts; l != NULL; l = g_list_next (l)) + { + TpAccount *account = l->data; + + add_account (self, account); + } + + tp_g_signal_connect_object (self->priv->mgr, "account-validity-changed", + G_CALLBACK (account_validity_changed_cb), self, 0); + + g_list_free (accounts); + +out: + g_object_unref (self); +} + +static void +empathy_connection_aggregator_init (EmpathyConnectionAggregator *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, + EMPATHY_TYPE_CONNECTION_AGGREGATOR, EmpathyConnectionAggregatorPriv); + + self->priv->mgr = tp_account_manager_dup (); + + tp_proxy_prepare_async (self->priv->mgr, NULL, am_prepare_cb, + g_object_ref (self)); +} + +EmpathyConnectionAggregator * +empathy_connection_aggregator_dup_singleton (void) +{ + static EmpathyConnectionAggregator *aggregator = NULL; + + if (G_LIKELY (aggregator != NULL)) + return g_object_ref (aggregator); + + aggregator = g_object_new (EMPATHY_TYPE_CONNECTION_AGGREGATOR, NULL); + + g_object_add_weak_pointer (G_OBJECT (aggregator), (gpointer *) &aggregator); + return aggregator; +} + +/* (transfer container) */ +GList * +empathy_connection_aggregator_get_all_groups (EmpathyConnectionAggregator *self) +{ + GList *keys, *l; + GHashTable *set; + + set = g_hash_table_new (g_str_hash, g_str_equal); + + for (l = self->priv->conns; l != NULL; l = g_list_next (l)) + { + TpConnection *conn = l->data; + const gchar * const *groups; + guint i; + + groups = tp_connection_get_contact_groups (conn); + if (groups == NULL) + continue; + + for (i = 0; groups[i] != NULL; i++) + g_hash_table_insert (set, (gchar *) groups[i], GUINT_TO_POINTER (TRUE)); + } + + keys = g_hash_table_get_keys (set); + g_hash_table_unref (set); + + return keys; +} + +GPtrArray * +empathy_connection_aggregator_dup_all_contacts ( + EmpathyConnectionAggregator *self) +{ + GPtrArray *result; + GList *l; + + result = g_ptr_array_new_with_free_func (g_object_unref); + + for (l = self->priv->conns; l != NULL; l = g_list_next (l)) + { + TpConnection *conn = l->data; + GPtrArray *contacts; + + contacts = tp_connection_dup_contact_list (conn); + if (contacts == NULL) + continue; + + tp_g_ptr_array_extend (result, contacts); + + /* tp_g_ptr_array_extend() doesn't give us an extra ref */ + g_ptr_array_foreach (contacts, (GFunc) g_object_ref, NULL); + + g_ptr_array_unref (contacts); + } + + return result; +} diff --git a/pool/shard000/C/0011740_calculator.c b/pool/shard000/C/0011740_calculator.c new file mode 100644 index 0000000000000000000000000000000000000000..71dcc9fcef142a6e6ade3bb4252ccdf1e4613b68 --- /dev/null +++ b/pool/shard000/C/0011740_calculator.c @@ -0,0 +1,98 @@ +#include +#include +#include + +#define MAXOP 100 /* max size of operand or operator */ +#define NUMBER '0' /* signal that a number was found */ + +int getop(char []); +void push(double); +double pop(void); + +/* reverse Polish calculator */ +int main(int argc, char **argv) +{ + int type; + double op2; + char s[MAXOP]; + + while ((type = getop(s)) != EOF) { + switch (type) { + case NUMBER: + push(atof(s)); + break; + case '+': + push (pop() + pop()) ; + break; + case '*': + push(pop() * pop()); + break; + case '-': + op2 = pop(); + push(pop() - op2); + break; + case '/': + op2 = pop(); + if (op2 != 0.0) + push(pop() / op2); + else + printf("error: zero divisor\n"); + break; + case '\n': + printf("\t%.8g\n", pop()); + break; + default: + printf("error: unknown command %s\n", s); + break; + } + } + return 0; +} + +#define MAXVAL 100 /* maximum depth of val stack */ + +int sp = 0; /* next free stack position */ +double val[MAXVAL]; /* value stack */ + +/* push: push f onto value stack */ +void push(double f) +{ + if (sp < MAXVAL) + val[sp++] = f; + else + printf("error: stack full. can't push %g\n", f); +} + +/* pop: pop and return top value from stack */ +double pop(void) +{ + if (sp > 0) + return val[--sp]; + else { + printf("error: stack empty\n"); + return 0.0; + } +} + +/* getop: get next operator or numeric operand */ +int getop(char s[]) +{ + int i, c; + + while ((s[0] = c = getc(stdin)) == ' ' || c == '\t') + ; + s[1] = '\0'; + if (!isdigit(c) && c != '.') + return c; /* not a number */ + i = 0; + if (isdigit(c)) /*collect integer part*/ + while (isdigit(s[++i] = c = getc(stdin))) + ; + if (c == '.') /*collect fraction part*/ + while (isdigit(s[++i] = c = getc(stdin))) + ; + s[i] = '\0'; + if (c != EOF) + ungetc(c, stdin); + return NUMBER; +} diff --git a/pool/shard000/C/0011771_envmapper.c b/pool/shard000/C/0011771_envmapper.c new file mode 100644 index 0000000000000000000000000000000000000000..b3804d8cacbc86e7dfcd1014c7335d27a749c4c1 --- /dev/null +++ b/pool/shard000/C/0011771_envmapper.c @@ -0,0 +1,125 @@ +/* + * Copyright (C) 1999, 2000, 2001 Lorenzo Bettini + * + * 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 + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + * + */ + +/* + * src/envmapper.c -- maps QUERY_STRING environment to argv + * + * 19.04.2001 [SPX] * added __convert_string() and __convert_char() to + * interpret '%XX' 'characters' of 'QUERY_STRING' + * * checks for CGI by scanning REQUEST_METHOD + * * 'QUERY_STRING' is determined by REQUEST_METHOD + * 06.04.2001 [SPX] completed initial revision + * 05.04.2001 [SPX] initial revision + * + * written by Robert Wetzel + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + + +#include +#include +#include +#include +#include "envmapper.h" + + +int +__convert_char(char *hexstr, int *source) +{ + int i, ch, temp_ch; + + for (ch = i = 0; i < 2; i++) { + temp_ch = hexstr[(*source)++]; + if (!isxdigit(temp_ch)) + return temp_ch; + temp_ch -= '0'; + if (temp_ch > 9) + temp_ch -= 'A' - '9' - 1; + ch = (ch << 4) + temp_ch; + } + return ch; +} + +char * +__convert_string(char *hexstr) +{ + int source, dest, ch, len; + + source = dest = 0; + len = strlen(hexstr); + while (source < len) { + if ((ch=hexstr[source++]) == '%') + hexstr[dest++] = __convert_char(hexstr, &source); + else + hexstr[dest++] = ch; + } + hexstr[dest] = '\0'; + return hexstr; +} + +char * +__get_option_string(char *token) +{ + char *new_token; + + new_token = (char*)calloc(strlen(token)+3, 1); + sprintf(new_token, "--%s", token); + return new_token; +} + +char ** +map_environment(int *argc, char **argv) +{ + char *query_string, *request_method, *token; + char **new_argv; + + /* check first, if CGI environment exists */ + request_method = getenv(ENV_REQUEST_METHOD); + if (!request_method) + return argv; + /* Ok. There is a request method. Lets check how the 'arguments' + are given by determining the request method... */ + if (!strcasecmp(request_method, REQUEST_METHOD_GET)) + query_string = getenv(ENV_QUERY_STRING); + else { + query_string = (char*)calloc(MAX_QUERY_STRING_LEN, sizeof(char)); + query_string = fgets(query_string, MAX_QUERY_STRING_LEN - 2, stdin); + if (query_string) + query_string[strlen(query_string)-2] = '\0'; + } + if (!query_string) + /* print error page! Currently this looks like a security hole as + it switches back to command line mode. */ + return argv; + query_string = __convert_string(query_string); + /* allocate memory for the new argv which may hold up to + MAX_PARAM_AMOUNT options */ + new_argv = (char**)calloc(MAX_PARAM_AMOUNT, sizeof argv); + /* 'copy' parameter strings */ + memcpy(new_argv, argv, *argc * sizeof argv); + token = strtok(query_string, "&"); + do { + new_argv[(*argc)++] = __get_option_string(token); + } + while ((token = strtok(NULL, "&"))); + return new_argv; +} diff --git a/pool/shard000/C/0011781_xstuff.c b/pool/shard000/C/0011781_xstuff.c new file mode 100644 index 0000000000000000000000000000000000000000..1516ea8991f9a72479d5558e31be399a6c404459 --- /dev/null +++ b/pool/shard000/C/0011781_xstuff.c @@ -0,0 +1,98 @@ +/* Nessus + * Copyright (C) 1998 Renaud Deraison + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, + * as published by the Free Software Foundation + * + * 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., 675 Mass Ave, Cambridge, MA 02139, USA. + * + * In addition, as a special exception, Renaud Deraison + * gives permission to link the code of this program with any + * version of the OpenSSL library which is distributed under a + * license identical to that listed in the included COPYING.OpenSSL + * file, and distribute linked combinations including the two. + * You must obey the GNU General Public License in all respects + * for all of the code used other than OpenSSL. If you modify + * this file, you may extend this exception to your version of the + * file, but you are not obligated to do so. If you do not wish to + * do so, delete this exception statement from your version. + */ + +#include + +#ifdef USE_GTK +#include + +#include "nessus.h" +#include "xstuff.h" +#include "globals.h" +#include "sighand.h" + +int init_display(int *argc, char *** argv) +{ + gtk_init(argc, argv); + return(0); +} + +int close_window(GtkWidget * nul, GtkWidget * w) +{ + gtk_widget_hide(w); + /* gtk_widget_destroy(w); */ + return(FALSE); +} +int delete_event(GtkWidget * nul, void * data) +{ + return(FALSE); +} +void close_display() +{ + gtk_main_quit(); + nessus_exit(0); +} + +struct pixmap_and_mask +{ + GdkPixmap *pixmap; + GdkBitmap *mask; +}; + +static void +pixmap_and_mask_destroy_notify(gpointer p) +{ + gdk_pixmap_unref(((struct pixmap_and_mask *) p)->pixmap); + gdk_bitmap_unref(((struct pixmap_and_mask *) p)->mask); + g_free(p); +} + +GtkWidget * +make_pixmap + (GtkWidget *widget, + GdkColor *transparent, + char **xpm_data) +{ + struct pixmap_and_mask *p; + gchar name[64]; + GdkColormap *colormap; + + g_snprintf(name, sizeof(name), "N_PIXMAP_%lx", (long) xpm_data); + p = gtk_object_get_data(GTK_OBJECT(widget), name); + if (!p) { + p = g_malloc(sizeof(*p)); + colormap = widget->window ? NULL : gtk_widget_get_colormap (widget); + p->pixmap = gdk_pixmap_colormap_create_from_xpm_d + (widget->window, colormap, + &p->mask, transparent, (gchar **) xpm_data); + gtk_object_set_data_full + (GTK_OBJECT(widget), name, p, &pixmap_and_mask_destroy_notify); + } + return gtk_pixmap_new (p->pixmap, p->mask); +} +#endif diff --git a/pool/shard000/C/0011789_mjpeg_parser.c b/pool/shard000/C/0011789_mjpeg_parser.c new file mode 100644 index 0000000000000000000000000000000000000000..ce824a68713af3a12a18376693ab8d141ceb7909 --- /dev/null +++ b/pool/shard000/C/0011789_mjpeg_parser.c @@ -0,0 +1,105 @@ +/* + * MJPEG parser + * Copyright (c) 2000, 2001 Fabrice Bellard + * Copyright (c) 2003 Alex Beregszaszi + * Copyright (c) 2003-2004 Michael Niedermayer + * + * This file is part of FFmpeg. + * + * FFmpeg is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * FFmpeg is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with FFmpeg; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/** + * @file libavcodec/mjpeg_parser.c + * MJPEG parser. + */ + +#include "parser.h" + + +/** + * finds the end of the current frame in the bitstream. + * @return the position of the first byte of the next frame, or -1 + */ +static int find_frame_end(ParseContext *pc, const uint8_t *buf, int buf_size){ + int vop_found, i; + uint16_t state; + + vop_found= pc->frame_start_found; + state= pc->state; + + i=0; + if(!vop_found){ + for(i=0; iframe_start_found=0; + pc->state=0; + return i-1; + } + } + } + pc->frame_start_found= vop_found; + pc->state= state; + return END_NOT_FOUND; +} + +static int jpeg_parse(AVCodecParserContext *s, + AVCodecContext *avctx, + const uint8_t **poutbuf, int *poutbuf_size, + const uint8_t *buf, int buf_size) +{ + ParseContext *pc = s->priv_data; + int next; + + if(s->flags & PARSER_FLAG_COMPLETE_FRAMES){ + next= buf_size; + }else{ + next= find_frame_end(pc, buf, buf_size); + + if (ff_combine_frame(pc, next, &buf, &buf_size) < 0) { + *poutbuf = NULL; + *poutbuf_size = 0; + return buf_size; + } + } + + *poutbuf = buf; + *poutbuf_size = buf_size; + return next; +} + + +AVCodecParser mjpeg_parser = { + { CODEC_ID_MJPEG }, + sizeof(ParseContext), + NULL, + jpeg_parse, + ff_parse_close, +}; diff --git a/pool/shard000/C/0011791_hextolfp.c b/pool/shard000/C/0011791_hextolfp.c new file mode 100644 index 0000000000000000000000000000000000000000..e4585d9194fd39ee915140c792e214482ac10417 --- /dev/null +++ b/pool/shard000/C/0011791_hextolfp.c @@ -0,0 +1,70 @@ +/* $NetBSD: hextolfp.c,v 1.3.4.1 2014/12/24 00:05:20 riz Exp $ */ + +/* + * hextolfp - convert an ascii hex string to an l_fp number + */ +#include +#include +#include + +#include "ntp_fp.h" +#include "ntp_string.h" +#include "ntp_stdlib.h" + +int +hextolfp( + const char *str, + l_fp *lfp + ) +{ + register const char *cp; + register const char *cpstart; + register u_long dec_i; + register u_long dec_f; + char *ind = NULL; + static const char *digits = "0123456789abcdefABCDEF"; + + dec_i = dec_f = 0; + cp = str; + + /* + * We understand numbers of the form: + * + * [spaces]8_hex_digits[.]8_hex_digits[spaces|\n|\0] + */ + while (isspace((unsigned char)*cp)) + cp++; + + cpstart = cp; + while (*cp != '\0' && (cp - cpstart) < 8 && + (ind = strchr(digits, *cp)) != NULL) { + dec_i = dec_i << 4; /* multiply by 16 */ + dec_i += ((ind - digits) > 15) ? (ind - digits) - 6 + : (ind - digits); + cp++; + } + + if ((cp - cpstart) < 8 || ind == NULL) + return 0; + if (*cp == '.') + cp++; + + cpstart = cp; + while (*cp != '\0' && (cp - cpstart) < 8 && + (ind = strchr(digits, *cp)) != NULL) { + dec_f = dec_f << 4; /* multiply by 16 */ + dec_f += ((ind - digits) > 15) ? (ind - digits) - 6 + : (ind - digits); + cp++; + } + + if ((cp - cpstart) < 8 || ind == NULL) + return 0; + + if (*cp != '\0' && !isspace((unsigned char)*cp)) + return 0; + + lfp->l_ui = dec_i; + lfp->l_uf = dec_f; + return 1; +} diff --git a/pool/shard000/C/0011795_funnel.c b/pool/shard000/C/0011795_funnel.c new file mode 100644 index 0000000000000000000000000000000000000000..8cc428ba00b2b9b943691a822a8e06690812831c --- /dev/null +++ b/pool/shard000/C/0011795_funnel.c @@ -0,0 +1,165 @@ +/* + * funnel.c + * + * EPAN's GUI mini-API + * + * (c) 2006, Luis E. Garcia Ontanon + * + * Wireshark - Network traffic analyzer + * By Gerald Combs + * Copyright 1998 Gerald Combs + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include "config.h" + +#include + +typedef struct _funnel_menu_t { + char *name; + register_stat_group_t group; + funnel_menu_callback callback; + gpointer callback_data; + gboolean retap; + struct _funnel_menu_t* next; +} funnel_menu_t; + +/* XXX This assumes one main window and one capture file. */ +static const funnel_ops_t* ops = NULL; +static funnel_menu_t* registered_menus = NULL; +static funnel_menu_t* added_menus = NULL; +static funnel_menu_t* removed_menus = NULL; +static gboolean menus_registered = FALSE; + +const funnel_ops_t* funnel_get_funnel_ops(void) { return ops; } +void funnel_set_funnel_ops(const funnel_ops_t* o) { ops = o; } + +static void funnel_insert_menu (funnel_menu_t** menu_list, funnel_menu_t *menu) +{ + if (!(*menu_list)) { + *menu_list = menu; + } else { + funnel_menu_t* c; + for (c = *menu_list; c->next; c = c->next); + c->next = menu; + } +} + +static void funnel_remove_menu (funnel_menu_t ** menu_list, funnel_menu_t *menu) +{ + funnel_menu_t *m = *menu_list, *p = NULL; + + while (m) { + if (m->callback == menu->callback) { + if (p) { + p->next = m->next; + } else { + *menu_list = m->next; + } + g_free(m->name); + g_free(m); + if (p) { + m = p->next; + } else { + m = *menu_list ? (*menu_list)->next : NULL; + } + } else { + p = m; + m = m->next; + } + } +} + +static void funnel_clear_menu (funnel_menu_t** menu_list) +{ + funnel_menu_t *m; + + while (*menu_list) { + m = *menu_list; + *menu_list = m->next; + g_free(m->name); + g_free(m); + } + *menu_list = NULL; +} + +void funnel_register_menu(const char *name, + register_stat_group_t group, + funnel_menu_callback callback, + gpointer callback_data, + gboolean retap) +{ + funnel_menu_t* m = (funnel_menu_t *)g_malloc(sizeof(funnel_menu_t)); + m->name = g_strdup(name); + m->group = group; + m->callback = callback; + m->callback_data = callback_data; + m->retap = retap; + m->next = NULL; + + funnel_insert_menu(®istered_menus, m); + if (menus_registered) { + funnel_menu_t* m_r = (funnel_menu_t *)g_memdup(m, sizeof *m); + m_r->name = g_strdup(name); + funnel_insert_menu(&added_menus, m_r); + } +} + +void funnel_deregister_menus(funnel_menu_callback callback) +{ + funnel_menu_t* m = (funnel_menu_t *)g_malloc0(sizeof(funnel_menu_t)); + m->callback = callback; + + funnel_remove_menu(®istered_menus, m); + funnel_insert_menu(&removed_menus, m); +} + +void funnel_register_all_menus(funnel_registration_cb_t r_cb) +{ + funnel_menu_t* c; + for (c = registered_menus; c; c = c->next) { + r_cb(c->name,c->group,c->callback,c->callback_data,c->retap); + } + menus_registered = TRUE; +} + +void funnel_reload_menus(funnel_deregistration_cb_t d_cb, + funnel_registration_cb_t r_cb) +{ + funnel_menu_t* c; + for (c = removed_menus; c; c = c->next) { + d_cb(c->callback); + } + for (c = added_menus; c; c = c->next) { + r_cb(c->name,c->group,c->callback,c->callback_data,c->retap); + } + + funnel_clear_menu(&removed_menus); + funnel_clear_menu(&added_menus); +} + +/* + * Editor modelines - http://www.wireshark.org/tools/modelines.html + * + * Local variables: + * c-basic-offset: 4 + * tab-width: 8 + * indent-tabs-mode: nil + * End: + * + * vi: set shiftwidth=4 tabstop=8 expandtab: + * :indentSize=4:tabSize=8:noTabs=true: + */ diff --git a/pool/shard000/C/0011803_strindex.c b/pool/shard000/C/0011803_strindex.c new file mode 100644 index 0000000000000000000000000000000000000000..82b1ba02a51c879f6ae37d4d81e5c45b4de0b76d --- /dev/null +++ b/pool/shard000/C/0011803_strindex.c @@ -0,0 +1,47 @@ +/* + * strindex.c + * + * $Id$ + * + * This file is part of the OpenLink Software Virtuoso Open-Source (VOS) + * project. + * + * Copyright (C) 1998-2012 OpenLink Software + * + * This project 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; only version 2 of the License, dated June 1991. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + * +*/ + +#include "libutil.h" + + +/* + * Find a string in another string + */ +char * +strindex (const char *str, const char *find) +{ + size_t len; + const char *cp; + const char *ep; + + len = strlen (find); + ep = str + strlen (str) - len; + for (cp = str; cp <= ep; cp++) + if (toupper (*cp) == toupper (*find) && !strnicmp (cp, find, len)) + return (char *) cp; + + return NULL; +} diff --git a/pool/shard000/C/0011809_lapacke_dpbsvx.c b/pool/shard000/C/0011809_lapacke_dpbsvx.c new file mode 100644 index 0000000000000000000000000000000000000000..428481e7a623d809c2eed04f80f18a1f0789c13b --- /dev/null +++ b/pool/shard000/C/0011809_lapacke_dpbsvx.c @@ -0,0 +1,94 @@ +/***************************************************************************** + Copyright (c) 2010, Intel Corp. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of Intel Corporation nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + THE POSSIBILITY OF SUCH DAMAGE. +****************************************************************************** +* Contents: Native high-level C interface to LAPACK function dpbsvx +* Author: Intel Corporation +* Generated October, 2010 +*****************************************************************************/ + +#include "lapacke.h" +#include "lapacke_utils.h" + +lapack_int LAPACKE_dpbsvx( int matrix_order, char fact, char uplo, lapack_int n, + lapack_int kd, lapack_int nrhs, double* ab, + lapack_int ldab, double* afb, lapack_int ldafb, + char* equed, double* s, double* b, lapack_int ldb, + double* x, lapack_int ldx, double* rcond, + double* ferr, double* berr ) +{ + lapack_int info = 0; + lapack_int* iwork = NULL; + double* work = NULL; + if( matrix_order != LAPACK_COL_MAJOR && matrix_order != LAPACK_ROW_MAJOR ) { + LAPACKE_xerbla( "LAPACKE_dpbsvx", -1 ); + return -1; + } +#ifndef LAPACK_DISABLE_NAN_CHECK + /* Optionally check input matrices for NaNs */ + if( LAPACKE_dpb_nancheck( matrix_order, uplo, n, kd, ab, ldab ) ) { + return -7; + } + if( LAPACKE_lsame( fact, 'f' ) ) { + if( LAPACKE_dpb_nancheck( matrix_order, uplo, n, kd, afb, ldafb ) ) { + return -9; + } + } + if( LAPACKE_dge_nancheck( matrix_order, n, nrhs, b, ldb ) ) { + return -13; + } + if( LAPACKE_lsame( fact, 'f' ) && LAPACKE_lsame( *equed, 'y' ) ) { + if( LAPACKE_d_nancheck( n, s, 1 ) ) { + return -12; + } + } +#endif + /* Allocate memory for working array(s) */ + iwork = (lapack_int*)LAPACKE_malloc( sizeof(lapack_int) * MAX(1,n) ); + if( iwork == NULL ) { + info = LAPACK_WORK_MEMORY_ERROR; + goto exit_level_0; + } + work = (double*)LAPACKE_malloc( sizeof(double) * MAX(1,3*n) ); + if( work == NULL ) { + info = LAPACK_WORK_MEMORY_ERROR; + goto exit_level_1; + } + /* Call middle-level interface */ + info = LAPACKE_dpbsvx_work( matrix_order, fact, uplo, n, kd, nrhs, ab, ldab, + afb, ldafb, equed, s, b, ldb, x, ldx, rcond, + ferr, berr, work, iwork ); + /* Release memory and exit */ + LAPACKE_free( work ); +exit_level_1: + LAPACKE_free( iwork ); +exit_level_0: + if( info == LAPACK_WORK_MEMORY_ERROR ) { + LAPACKE_xerbla( "LAPACKE_dpbsvx", info ); + } + return info; +} diff --git a/pool/shard000/C/0011811_sensoracq_t.c b/pool/shard000/C/0011811_sensoracq_t.c new file mode 100644 index 0000000000000000000000000000000000000000..eac0ca3f1fdd1b6db33de748d0a54a64dc730281 --- /dev/null +++ b/pool/shard000/C/0011811_sensoracq_t.c @@ -0,0 +1,329 @@ +/* Open Sensor Platform Project + * https://github.com/sensorplatforms/open-sensor-platform + * + * Copyright (C) 2013 Sensor Platforms Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/*-------------------------------------------------------------------------------------------------*\ + | I N C L U D E F I L E S +\*-------------------------------------------------------------------------------------------------*/ +#include "common.h" +#include "acc_common.h" +#include "mag_common.h" +#include "gyro_common.h" +#include "osp-api.h" + +/*-------------------------------------------------------------------------------------------------*\ + | E X T E R N A L V A R I A B L E S & F U N C T I O N S +\*-------------------------------------------------------------------------------------------------*/ +void WaitForHostSync( void ); + +/*-------------------------------------------------------------------------------------------------*\ + | P U B L I C V A R I A B L E S D E F I N I T I O N S +\*-------------------------------------------------------------------------------------------------*/ + +/*-------------------------------------------------------------------------------------------------*\ + | P R I V A T E C O N S T A N T S & M A C R O S +\*-------------------------------------------------------------------------------------------------*/ + +/*-------------------------------------------------------------------------------------------------*\ + | P R I V A T E T Y P E D E F I N I T I O N S +\*-------------------------------------------------------------------------------------------------*/ + +/*-------------------------------------------------------------------------------------------------*\ + | S T A T I C V A R I A B L E S D E F I N I T I O N S +\*-------------------------------------------------------------------------------------------------*/ +#ifndef INTERRUPT_BASED_SAMPLING + static AsfTimer sSensorTimer = NULL_TIMER; +#else +#endif + +/*-------------------------------------------------------------------------------------------------*\ + | F O R W A R D F U N C T I O N D E C L A R A T I O N S +\*-------------------------------------------------------------------------------------------------*/ +static void SensorDataHandler(InputSensor_t sensorId, uint32_t timeStamp); + +/*-------------------------------------------------------------------------------------------------*\ + | P R I V A T E F U N C T I O N S +\*-------------------------------------------------------------------------------------------------*/ + +/**************************************************************************************************** + * @fn HandleTimers + * Handles the MSG_TIMER_EXPIRY messages + * + ***************************************************************************************************/ +static void HandleTimers( MsgTimerExpiry *pTimerExp ) +{ + switch (pTimerExp->userValue) + { +#ifndef INTERRUPT_BASED_SAMPLING + uint32_t timeStamp; + + case TIMER_REF_SENSOR_READ: + /* Schedule the next sampling */ + ASFTimerStart(SENSOR_ACQ_TASK_ID, TIMER_REF_SENSOR_READ, + SENSOR_SAMPLE_PERIOD, &sSensorTimer); + + /* Call data handler for each sensors */ + timeStamp = RTC_GetCounter(); + SensorDataHandler(ACCEL_INPUT_SENSOR, timeStamp); + SensorDataHandler(MAG_INPUT_SENSOR, timeStamp); + SensorDataHandler(GYRO_INPUT_SENSOR, timeStamp); + break; +#endif + default: + D1_printf("Unknown Timer! Reference %d\r\n", pTimerExp->userValue); + break; + } +} + + +#ifdef ENABLE_FLASH_STORE +/**************************************************************************************************** + * @fn StoreCalibrationData + * Stores calibration data. Why in this task?. Doing it in Sensor acq makes it unlikely to + * interfere with the sensor data reads over I2C. + * + ***************************************************************************************************/ +static void StoreCalibrationData( CalEvent_t event ) +{ +} +#endif + +/**************************************************************************************************** + * @fn SensorDataHandler + * Handle data ready indications from ISR for various sensors + * + ***************************************************************************************************/ +static void SensorDataHandler(InputSensor_t sensorId, uint32_t timeStamp) +{ + MsgAccelData accelData; + MsgMagData magData; + MsgGyroData gyroData; + static uint32_t sMagDecimateCount = 0; + static uint32_t gyroSampleCount = 0; + static uint32_t accSampleCount = 0; + +#if defined ALGORITHM_TASK || defined ANDROID_COMM_TASK + MessageBuffer *pMagSample = NULLP; + MessageBuffer *pAccSample = NULLP; + MessageBuffer *pGyroSample = NULLP; +#endif + + switch (sensorId) + { + case MAG_INPUT_SENSOR: + if ((sMagDecimateCount++ % MAG_DECIMATE_FACTOR) == 0 ) + { + /* Read mag Data - reading would clear interrupt also */ + Mag_ReadData( &magData ); + /* Replace time stamp with that captured by interrupt handler */ + magData.timeStamp = timeStamp; +#ifdef ALGORITHM_TASK + ASF_assert( ASFCreateMessage( MSG_MAG_DATA, sizeof(MsgMagData), &pMagSample ) == ASF_OK ); + pMagSample->msg.msgMagData = magData; + ASF_assert( ASFSendMessage( ALGORITHM_TASK_ID, pMagSample ) == ASF_OK ); +#endif +#ifdef ANDROID_COMM_TASK + pMagSample = NULLP; + /* Send sample to Host interface also */ + ASF_assert( ASFCreateMessage( MSG_MAG_DATA, sizeof(MsgMagData), &pMagSample ) == ASF_OK ); + pMagSample->msg.msgMagData = magData; + ASFSendMessage( ANDROID_COMM_TASK, pMagSample ); // No error check. We are OK to drop messages +#endif + } + else + { + Mag_ClearDataInt(); + } + break; + + case GYRO_INPUT_SENSOR: + if ((gyroSampleCount++ % GYRO_SAMPLE_DECIMATE) == 0) + { + /* Read Gyro Data - reading typically clears interrupt as well */ + Gyro_ReadData( &gyroData ); //Reads also clears DRDY interrupt + /* Replace time stamp with that captured by interrupt handler */ + gyroData.timeStamp = timeStamp; +#ifdef ALGORITHM_TASK + ASF_assert( ASFCreateMessage( MSG_GYRO_DATA, sizeof(MsgGyroData), &pGyroSample ) == ASF_OK ); + pGyroSample->msg.msgGyroData = gyroData; + ASF_assert( ASFSendMessage( ALGORITHM_TASK_ID, pGyroSample ) == ASF_OK ); +#endif +#ifdef ANDROID_COMM_TASK + pGyroSample = NULLP; + /* Send sample to Host interface also */ + ASF_assert( ASFCreateMessage( MSG_GYRO_DATA, sizeof(MsgGyroData), &pGyroSample ) == ASF_OK ); + pGyroSample->msg.msgGyroData = gyroData; + ASFSendMessage( ANDROID_COMM_TASK, pGyroSample ); // No error check. We are OK to drop messages +#endif + } + else + { + Gyro_ClearDataInt(); + } + break; + + case ACCEL_INPUT_SENSOR: +#if defined TRIGGERED_MAG_SAMPLING + if (accSampleCount % MAG_TRIGGER_RATE_DECIMATE == 0) + { + Mag_TriggerDataAcq(); //Mag is triggered relative to Accel to avoid running separate timer + } +#endif + if (accSampleCount++ % ACCEL_SAMPLE_DECIMATE == 0) + { + /* Read Accel Data - reading typically clears interrupt as well */ + Accel_ReadData( &accelData ); + /* Replace time stamp with that captured by interrupt handler */ + accelData.timeStamp = timeStamp; +#ifdef ALGORITHM_TASK + ASF_assert( ASFCreateMessage( MSG_ACC_DATA, sizeof(MsgAccelData), &pAccSample ) == ASF_OK ); + pAccSample->msg.msgAccelData = accelData; + ASF_assert( ASFSendMessage( ALGORITHM_TASK_ID, pAccSample ) == ASF_OK ); +#endif +#ifdef ANDROID_COMM_TASK + pAccSample = NULLP; + /* Send sample to Host interface also */ + ASF_assert( ASFCreateMessage( MSG_ACC_DATA, sizeof(MsgAccelData), &pAccSample ) == ASF_OK ); + pAccSample->msg.msgAccelData = accelData; + ASFSendMessage( ANDROID_COMM_TASK, pAccSample ); // No error check. We are OK to drop messages +#endif + + } + else + { + Accel_ClearDataInt(); + } + break; + + default: + break; + + } +} + +/*-------------------------------------------------------------------------------------------------*\ + | P U B L I C F U N C T I O N S +\*-------------------------------------------------------------------------------------------------*/ + +/**************************************************************************************************** + * @fn SendDataReadyIndication + * @brief This helper function sends data ready indication to Sensor Acq task. Called from ISR + * @param sensorId: Sensor identifier whose data is ready to be read + * @return None + * + ***************************************************************************************************/ +void SendDataReadyIndication( uint8_t sensorId, uint32_t timeStamp ) +{ + MessageBuffer *pSendMsg = NULLP; + + ASF_assert( ASFCreateMessage( MSG_SENSOR_DATA_RDY, sizeof(MsgSensorDataRdy), &pSendMsg ) == ASF_OK ); + pSendMsg->msg.msgSensorDataRdy.sensorId = sensorId; + pSendMsg->msg.msgSensorDataRdy.timeStamp = timeStamp; + ASF_assert( ASFSendMessage( SENSOR_ACQ_TASK_ID, pSendMsg ) == ASF_OK ); + +} + + +/**************************************************************************************************** + * @fn SensorAcqTask + * This task is responsible for acquiring data from and controlling the sensors in the + * system. + * + * Sensor data flow: + * 1. Sensor interrupts on data ready. + * 2. IRQ handler is solely expected to call SendDataReadyIndication. + * 3. SensorAcqTask will see a message data is available. + * 4. Data is read. Sensor driver is expected to clear + * the interrupt from the read function. + * + * @param none + * + * @return none + * + ***************************************************************************************************/ +ASF_TASK void SensorAcqTask( ASF_TASK_ARG ) +{ + MessageBuffer *rcvMsg = NULLP; + volatile uint8_t i; + +#ifndef WAIT_FOR_HOST_SYNC + os_dly_wait(MSEC_TO_TICS(50)); /* Allow startup time for sensors */ +#else + WaitForHostSync(); //This also allows for startup time for sensors +#endif + + /* Setup interface for the Magnetometer */ + Mag_HardwareSetup( true ); + Mag_Initialize(); + Mag_ClearDataInt(); /* Clear interrupt from previous run that maynot have been acknowledged */ + + /* Setup interface for the accelerometers */ + Accel_HardwareSetup( true ); + Accel_Initialize( INIT_NORMAL ); + + /* Setup Gyro */ + Gyro_HardwareSetup( true ); + Gyro_Initialize(); + +#ifndef INTERRUPT_BASED_SAMPLING + /* Start sample period timer */ + ASFTimerStart( SENSOR_ACQ_TASK_ID, TIMER_REF_SENSOR_READ, SENSOR_SAMPLE_PERIOD, &sSensorTimer ); +#else + /* Enable Sensor interrupts */ + Mag_ConfigDataInt( true ); + Accel_ConfigDataInt( true ); + Gyro_ConfigDataInt( true ); +# ifdef TRIGGERED_MAG_SAMPLING + Mag_SetLowPowerMode(); //Low power mode until triggered +# endif +#endif + + while (1) { + ASFReceiveMessage(SENSOR_ACQ_TASK_ID, &rcvMsg); + + switch (rcvMsg->msgId) + { + case MSG_TIMER_EXPIRY: + HandleTimers(&rcvMsg->msg.msgTimerExpiry); + break; + + case MSG_CAL_EVT_NOTIFY: +#ifdef ENABLE_FLASH_STORE + StoreCalibrationData((CalEvent_t)rcvMsg->msg.msgCalEvtNotify.byte); +#else + D0_printf("#### WARNING - NV Storage Not Implemented! #####\r\n"); +#endif + break; + + case MSG_SENSOR_DATA_RDY: +#ifdef INTERRUPT_BASED_SAMPLING + SensorDataHandler((InputSensor_t)rcvMsg->msg.msgSensorDataRdy.sensorId, + rcvMsg->msg.msgSensorDataRdy.timeStamp); +#endif + break; + + default: + /* Unhandled messages */ + D2_printf("SensorAcqTask:!!!UNHANDLED MESSAGE:%d!!!\r\n", rcvMsg->msgId); + break; + } + } +} + + +/*-------------------------------------------------------------------------------------------------*\ + | E N D O F F I L E +\*-------------------------------------------------------------------------------------------------*/ diff --git a/pool/shard000/C/0011825_wresize.c b/pool/shard000/C/0011825_wresize.c new file mode 100644 index 0000000000000000000000000000000000000000..bc6b5732ea41fe05aa46ed575c2db9af8d6b7389 --- /dev/null +++ b/pool/shard000/C/0011825_wresize.c @@ -0,0 +1,254 @@ +/**************************************************************************** + * Copyright (c) 1998-2010,2011 Free Software Foundation, Inc. * + * * + * Permission is hereby granted, free of charge, to any person obtaining a * + * copy of this software and associated documentation files (the * + * "Software"), to deal in the Software without restriction, including * + * without limitation the rights to use, copy, modify, merge, publish, * + * distribute, distribute with modifications, sublicense, and/or sell * + * copies of the Software, and to permit persons to whom the Software is * + * furnished to do so, subject to the following conditions: * + * * + * The above copyright notice and this permission notice shall be included * + * in all copies or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * + * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * + * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * + * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + * * + * Except as contained in this notice, the name(s) of the above copyright * + * holders shall not be used in advertising or otherwise to promote the * + * sale, use or other dealings in this Software without prior written * + * authorization. * + ****************************************************************************/ + +/**************************************************************************** + * Author: Thomas E. Dickey 1996-on * + * and: Juergen Pfeifer * + ****************************************************************************/ + +#include + +MODULE_ID("$Id: wresize.c,v 1.35 2011/05/21 18:55:07 tom Exp $") + +static int +cleanup_lines(struct ldat *data, int length) +{ + while (--length >= 0) + free(data[length].text); + free(data); + return ERR; +} + +/* + * If we have reallocated the ldat structs, we will have to repair pointers + * used in subwindows. + */ +static void +repair_subwindows(WINDOW *cmp) +{ + WINDOWLIST *wp; + struct ldat *pline = cmp->_line; + int row; +#ifdef USE_SP_WINDOWLIST + SCREEN *sp = _nc_screen_of(cmp); +#endif + + _nc_lock_global(curses); + + for (each_window(SP_PARM, wp)) { + WINDOW *tst = &(wp->win); + + if (tst->_parent == cmp) { + + if (tst->_pary > cmp->_maxy) + tst->_pary = cmp->_maxy; + if (tst->_parx > cmp->_maxx) + tst->_parx = cmp->_maxx; + + if (tst->_maxy + tst->_pary > cmp->_maxy) + tst->_maxy = (NCURSES_SIZE_T) (cmp->_maxy - tst->_pary); + if (tst->_maxx + tst->_parx > cmp->_maxx) + tst->_maxx = (NCURSES_SIZE_T) (cmp->_maxx - tst->_parx); + + for (row = 0; row <= tst->_maxy; ++row) { + tst->_line[row].text = &pline[tst->_pary + row].text[tst->_parx]; + } + repair_subwindows(tst); + } + } + _nc_unlock_global(curses); +} + +/* + * Reallocate a curses WINDOW struct to either shrink or grow to the specified + * new lines/columns. If it grows, the new character cells are filled with + * blanks. The application is responsible for repainting the blank area. + */ +NCURSES_EXPORT(int) +wresize(WINDOW *win, int ToLines, int ToCols) +{ + int col, row, size_x, size_y; + struct ldat *pline; + struct ldat *new_lines = 0; + +#ifdef TRACE + T((T_CALLED("wresize(%p,%d,%d)"), (void *) win, ToLines, ToCols)); + if (win) { + TR(TRACE_UPDATE, ("...beg (%ld, %ld), max(%ld,%ld), reg(%ld,%ld)", + (long) win->_begy, (long) win->_begx, + (long) win->_maxy, (long) win->_maxx, + (long) win->_regtop, (long) win->_regbottom)); + if (USE_TRACEF(TRACE_UPDATE)) { + _tracedump("...before", win); + _nc_unlock_global(tracef); + } + } +#endif + + if (!win || --ToLines < 0 || --ToCols < 0) + returnCode(ERR); + + size_x = win->_maxx; + size_y = win->_maxy; + + if (ToLines == size_y + && ToCols == size_x) + returnCode(OK); + + if ((win->_flags & _SUBWIN)) { + /* + * Check if the new limits will fit into the parent window's size. If + * not, do not resize. We could adjust the location of the subwindow, + * but the application may not like that. + */ + if (win->_pary + ToLines > win->_parent->_maxy + || win->_parx + ToCols > win->_parent->_maxx) { + returnCode(ERR); + } + pline = win->_parent->_line; + } else { + pline = 0; + } + + /* + * Allocate new memory as needed. Do the allocations without modifying + * the original window, in case an allocation fails. Always allocate + * (at least temporarily) the array pointing to the individual lines. + */ + new_lines = typeCalloc(struct ldat, (unsigned) (ToLines + 1)); + if (new_lines == 0) + returnCode(ERR); + + /* + * For each line in the target, allocate or adjust pointers for the + * corresponding text, depending on whether this is a window or a + * subwindow. + */ + for (row = 0; row <= ToLines; ++row) { + int begin = (row > size_y) ? 0 : (size_x + 1); + int end = ToCols; + NCURSES_CH_T *s; + + if (!(win->_flags & _SUBWIN)) { + if (row <= size_y) { + if (ToCols != size_x) { + s = typeMalloc(NCURSES_CH_T, (unsigned) ToCols + 1); + if (s == 0) + returnCode(cleanup_lines(new_lines, row)); + for (col = 0; col <= ToCols; ++col) { + s[col] = (col <= size_x + ? win->_line[row].text[col] + : win->_nc_bkgd); + } + } else { + s = win->_line[row].text; + } + } else { + s = typeMalloc(NCURSES_CH_T, (unsigned) ToCols + 1); + if (s == 0) + returnCode(cleanup_lines(new_lines, row)); + for (col = 0; col <= ToCols; ++col) + s[col] = win->_nc_bkgd; + } + } else if (pline != 0 && pline[win->_pary + row].text != 0) { + s = &pline[win->_pary + row].text[win->_parx]; + } else { + s = 0; + } + + if_USE_SCROLL_HINTS(new_lines[row].oldindex = row); + if (row <= size_y) { + new_lines[row].firstchar = win->_line[row].firstchar; + new_lines[row].lastchar = win->_line[row].lastchar; + } + if ((ToCols != size_x) || (row > size_y)) { + if (end >= begin) { /* growing */ + if (new_lines[row].firstchar < begin) + new_lines[row].firstchar = (NCURSES_SIZE_T) begin; + } else { /* shrinking */ + new_lines[row].firstchar = 0; + } + new_lines[row].lastchar = (NCURSES_SIZE_T) ToCols; + } + new_lines[row].text = s; + } + + /* + * Dispose of unwanted memory. + */ + if (!(win->_flags & _SUBWIN)) { + if (ToCols == size_x) { + for (row = ToLines + 1; row <= size_y; row++) { + free(win->_line[row].text); + } + } else { + for (row = 0; row <= size_y; row++) { + free(win->_line[row].text); + } + } + } + + free(win->_line); + win->_line = new_lines; + + /* + * Finally, adjust the parameters showing screen size and cursor + * position: + */ + win->_maxx = (NCURSES_SIZE_T) ToCols; + win->_maxy = (NCURSES_SIZE_T) ToLines; + + if (win->_regtop > win->_maxy) + win->_regtop = win->_maxy; + if (win->_regbottom > win->_maxy + || win->_regbottom == size_y) + win->_regbottom = win->_maxy; + + if (win->_curx > win->_maxx) + win->_curx = win->_maxx; + if (win->_cury > win->_maxy) + win->_cury = win->_maxy; + + /* + * Check for subwindows of this one, and readjust pointers to our text, + * if needed. + */ + repair_subwindows(win); + +#ifdef TRACE + TR(TRACE_UPDATE, ("...beg (%ld, %ld), max(%ld,%ld), reg(%ld,%ld)", + (long) win->_begy, (long) win->_begx, + (long) win->_maxy, (long) win->_maxx, + (long) win->_regtop, (long) win->_regbottom)); + if (USE_TRACEF(TRACE_UPDATE)) { + _tracedump("...after:", win); + _nc_unlock_global(tracef); + } +#endif + returnCode(OK); +} diff --git a/pool/shard000/C/0011827_blockdsp_init.c b/pool/shard000/C/0011827_blockdsp_init.c new file mode 100644 index 0000000000000000000000000000000000000000..21599934ff8944de988397588068e0b4912f6d33 --- /dev/null +++ b/pool/shard000/C/0011827_blockdsp_init.c @@ -0,0 +1,54 @@ +/* + * This file is part of FFmpeg. + * + * FFmpeg is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * FFmpeg is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with FFmpeg; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include + +#include "config.h" +#include "libavutil/attributes.h" +#include "libavutil/internal.h" +#include "libavutil/cpu.h" +#include "libavutil/x86/cpu.h" +#include "libavcodec/blockdsp.h" +#include "libavcodec/version.h" + +void ff_clear_block_mmx(int16_t *block); +void ff_clear_block_sse(int16_t *block); +void ff_clear_blocks_mmx(int16_t *blocks); +void ff_clear_blocks_sse(int16_t *blocks); + +av_cold void ff_blockdsp_init_x86(BlockDSPContext *c, + AVCodecContext *avctx) +{ +#if HAVE_YASM + int cpu_flags = av_get_cpu_flags(); + + if (EXTERNAL_MMX(cpu_flags)) { + c->clear_block = ff_clear_block_mmx; + c->clear_blocks = ff_clear_blocks_mmx; + } + + /* XvMCCreateBlocks() may not allocate 16-byte aligned blocks */ + if (CONFIG_XVMC && avctx->hwaccel && avctx->hwaccel->decode_mb) + return; + + if (EXTERNAL_SSE(cpu_flags)) { + c->clear_block = ff_clear_block_sse; + c->clear_blocks = ff_clear_blocks_sse; + } +#endif /* HAVE_YASM */ +} diff --git a/pool/shard000/C/0011830_e_logf.c b/pool/shard000/C/0011830_e_logf.c new file mode 100644 index 0000000000000000000000000000000000000000..7cee2ab78ab1d14c882f46b51f1cc23f0a6e817e --- /dev/null +++ b/pool/shard000/C/0011830_e_logf.c @@ -0,0 +1,83 @@ +/* e_logf.c -- float version of e_log.c. + * Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com. + */ + +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ + +#ifndef lint +static char rcsid[] = "$FreeBSD: src/lib/msun/src/e_logf.c,v 1.8 2005/11/12 18:20:09 bde Exp $"; +#endif + +#include "math.h" +#include "math_private.h" + +static const float +ln2_hi = 6.9313812256e-01, /* 0x3f317180 */ +ln2_lo = 9.0580006145e-06, /* 0x3717f7d1 */ +two25 = 3.355443200e+07, /* 0x4c000000 */ +/* |(log(1+s)-log(1-s))/s - Lg(s)| < 2**-34.24 (~[-4.95e-11, 4.97e-11]). */ +Lg1 = 0xaaaaaa.0p-24, /* 0.66666662693 */ +Lg2 = 0xccce13.0p-25, /* 0.40000972152 */ +Lg3 = 0x91e9ee.0p-25, /* 0.28498786688 */ +Lg4 = 0xf89e26.0p-26; /* 0.24279078841 */ + +static const float zero = 0.0; + +float +__ieee754_logf(float x) +{ + float hfsq,f,s,z,R,w,t1,t2,dk; + int32_t k,ix,i,j; + + GET_FLOAT_WORD(ix,x); + + k=0; + if (ix < 0x00800000) { /* x < 2**-126 */ + if ((ix&0x7fffffff)==0) + return -two25/zero; /* log(+-0)=-inf */ + if (ix<0) return (x-x)/zero; /* log(-#) = NaN */ + k -= 25; x *= two25; /* subnormal number, scale up x */ + GET_FLOAT_WORD(ix,x); + } + if (ix >= 0x7f800000) return x+x; + k += (ix>>23)-127; + ix &= 0x007fffff; + i = (ix+(0x95f64<<3))&0x800000; + SET_FLOAT_WORD(x,ix|(i^0x3f800000)); /* normalize x or x/2 */ + k += (i>>23); + f = x-(float)1.0; + if((0x007fffff&(15+ix))<16) { /* |f| < 2**-20 */ + if(f==zero) if(k==0) return zero; else {dk=(float)k; + return dk*ln2_hi+dk*ln2_lo;} + R = f*f*((float)0.5-(float)0.33333333333333333*f); + if(k==0) return f-R; else {dk=(float)k; + return dk*ln2_hi-((R-dk*ln2_lo)-f);} + } + s = f/((float)2.0+f); + dk = (float)k; + z = s*s; + i = ix-(0x6147a<<3); + w = z*z; + j = (0x6b851<<3)-ix; + t1= w*(Lg2+w*Lg4); + t2= z*(Lg1+w*Lg3); + i |= j; + R = t2+t1; + if(i>0) { + hfsq=(float)0.5*f*f; + if(k==0) return f-(hfsq-s*(hfsq+R)); else + return dk*ln2_hi-((hfsq-(s*(hfsq+R)+dk*ln2_lo))-f); + } else { + if(k==0) return f-s*(f-R); else + return dk*ln2_hi-((s*(f-R)-dk*ln2_lo)-f); + } +} diff --git a/pool/shard000/C/0011833_iinfo.c b/pool/shard000/C/0011833_iinfo.c new file mode 100644 index 0000000000000000000000000000000000000000..99a1b47773f0767110da7e3791263d0b1bb6629b --- /dev/null +++ b/pool/shard000/C/0011833_iinfo.c @@ -0,0 +1,277 @@ +/* + * Copyright (C) 2005-2014 Junjiro R. Okajima + * + * This program, aufs is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/* + * inode private data + */ + +#include "aufs.h" + +struct inode *au_h_iptr(struct inode *inode, aufs_bindex_t bindex) +{ + struct inode *h_inode; + + IiMustAnyLock(inode); + + h_inode = au_ii(inode)->ii_hinode[0 + bindex].hi_inode; + AuDebugOn(h_inode && atomic_read(&h_inode->i_count) <= 0); + return h_inode; +} + +/* todo: hard/soft set? */ +void au_hiput(struct au_hinode *hinode) +{ + au_hn_free(hinode); + dput(hinode->hi_whdentry); + iput(hinode->hi_inode); +} + +unsigned int au_hi_flags(struct inode *inode, int isdir) +{ + unsigned int flags; + const unsigned int mnt_flags = au_mntflags(inode->i_sb); + + flags = 0; + if (au_opt_test(mnt_flags, XINO)) + au_fset_hi(flags, XINO); + if (isdir && au_opt_test(mnt_flags, UDBA_HNOTIFY)) + au_fset_hi(flags, HNOTIFY); + return flags; +} + +void au_set_h_iptr(struct inode *inode, aufs_bindex_t bindex, + struct inode *h_inode, unsigned int flags) +{ + struct au_hinode *hinode; + struct inode *hi; + struct au_iinfo *iinfo = au_ii(inode); + + IiMustWriteLock(inode); + + hinode = iinfo->ii_hinode + bindex; + hi = hinode->hi_inode; + AuDebugOn(h_inode && atomic_read(&h_inode->i_count) <= 0); + + if (hi) + au_hiput(hinode); + hinode->hi_inode = h_inode; + if (h_inode) { + int err; + struct super_block *sb = inode->i_sb; + struct au_branch *br; + + AuDebugOn(inode->i_mode + && (h_inode->i_mode & S_IFMT) + != (inode->i_mode & S_IFMT)); + if (bindex == iinfo->ii_bstart) + au_cpup_igen(inode, h_inode); + br = au_sbr(sb, bindex); + hinode->hi_id = br->br_id; + if (au_ftest_hi(flags, XINO)) { + err = au_xino_write(sb, bindex, h_inode->i_ino, + inode->i_ino); + if (unlikely(err)) + AuIOErr1("failed au_xino_write() %d\n", err); + } + + if (au_ftest_hi(flags, HNOTIFY) + && au_br_hnotifyable(br->br_perm)) { + err = au_hn_alloc(hinode, inode); + if (unlikely(err)) + AuIOErr1("au_hn_alloc() %d\n", err); + } + } +} + +void au_set_hi_wh(struct inode *inode, aufs_bindex_t bindex, + struct dentry *h_wh) +{ + struct au_hinode *hinode; + + IiMustWriteLock(inode); + + hinode = au_ii(inode)->ii_hinode + bindex; + AuDebugOn(hinode->hi_whdentry); + hinode->hi_whdentry = h_wh; +} + +void au_update_iigen(struct inode *inode, int half) +{ + struct au_iinfo *iinfo; + struct au_iigen *iigen; + unsigned int sigen; + + sigen = au_sigen(inode->i_sb); + iinfo = au_ii(inode); + iigen = &iinfo->ii_generation; + spin_lock(&iinfo->ii_genspin); + iigen->ig_generation = sigen; + if (half) + au_ig_fset(iigen->ig_flags, HALF_REFRESHED); + else + au_ig_fclr(iigen->ig_flags, HALF_REFRESHED); + spin_unlock(&iinfo->ii_genspin); +} + +/* it may be called at remount time, too */ +void au_update_ibrange(struct inode *inode, int do_put_zero) +{ + struct au_iinfo *iinfo; + aufs_bindex_t bindex, bend; + + iinfo = au_ii(inode); + if (!iinfo) + return; + + IiMustWriteLock(inode); + + if (do_put_zero && iinfo->ii_bstart >= 0) { + for (bindex = iinfo->ii_bstart; bindex <= iinfo->ii_bend; + bindex++) { + struct inode *h_i; + + h_i = iinfo->ii_hinode[0 + bindex].hi_inode; + if (h_i + && !h_i->i_nlink + && !(h_i->i_state & I_LINKABLE)) + au_set_h_iptr(inode, bindex, NULL, 0); + } + } + + iinfo->ii_bstart = -1; + iinfo->ii_bend = -1; + bend = au_sbend(inode->i_sb); + for (bindex = 0; bindex <= bend; bindex++) + if (iinfo->ii_hinode[0 + bindex].hi_inode) { + iinfo->ii_bstart = bindex; + break; + } + if (iinfo->ii_bstart >= 0) + for (bindex = bend; bindex >= iinfo->ii_bstart; bindex--) + if (iinfo->ii_hinode[0 + bindex].hi_inode) { + iinfo->ii_bend = bindex; + break; + } + AuDebugOn(iinfo->ii_bstart > iinfo->ii_bend); +} + +/* ---------------------------------------------------------------------- */ + +void au_icntnr_init_once(void *_c) +{ + struct au_icntnr *c = _c; + struct au_iinfo *iinfo = &c->iinfo; + static struct lock_class_key aufs_ii; + + spin_lock_init(&iinfo->ii_genspin); + au_rw_init(&iinfo->ii_rwsem); + au_rw_class(&iinfo->ii_rwsem, &aufs_ii); + inode_init_once(&c->vfs_inode); +} + +int au_iinfo_init(struct inode *inode) +{ + struct au_iinfo *iinfo; + struct super_block *sb; + int nbr, i; + + sb = inode->i_sb; + iinfo = &(container_of(inode, struct au_icntnr, vfs_inode)->iinfo); + nbr = au_sbend(sb) + 1; + if (unlikely(nbr <= 0)) + nbr = 1; + iinfo->ii_hinode = kcalloc(nbr, sizeof(*iinfo->ii_hinode), GFP_NOFS); + if (iinfo->ii_hinode) { + au_ninodes_inc(sb); + for (i = 0; i < nbr; i++) + iinfo->ii_hinode[i].hi_id = -1; + + iinfo->ii_generation.ig_generation = au_sigen(sb); + iinfo->ii_bstart = -1; + iinfo->ii_bend = -1; + iinfo->ii_vdir = NULL; + return 0; + } + return -ENOMEM; +} + +int au_ii_realloc(struct au_iinfo *iinfo, int nbr) +{ + int err, sz; + struct au_hinode *hip; + + AuRwMustWriteLock(&iinfo->ii_rwsem); + + err = -ENOMEM; + sz = sizeof(*hip) * (iinfo->ii_bend + 1); + if (!sz) + sz = sizeof(*hip); + hip = au_kzrealloc(iinfo->ii_hinode, sz, sizeof(*hip) * nbr, GFP_NOFS); + if (hip) { + iinfo->ii_hinode = hip; + err = 0; + } + + return err; +} + +void au_iinfo_fin(struct inode *inode) +{ + struct au_iinfo *iinfo; + struct au_hinode *hi; + struct super_block *sb; + aufs_bindex_t bindex, bend; + const unsigned char unlinked = !inode->i_nlink; + + iinfo = au_ii(inode); + /* bad_inode case */ + if (!iinfo) + return; + + sb = inode->i_sb; + au_ninodes_dec(sb); + if (si_pid_test(sb)) + au_xino_delete_inode(inode, unlinked); + else { + /* + * it is safe to hide the dependency between sbinfo and + * sb->s_umount. + */ + lockdep_off(); + si_noflush_read_lock(sb); + au_xino_delete_inode(inode, unlinked); + si_read_unlock(sb); + lockdep_on(); + } + + if (iinfo->ii_vdir) + au_vdir_free(iinfo->ii_vdir); + + bindex = iinfo->ii_bstart; + if (bindex >= 0) { + hi = iinfo->ii_hinode + bindex; + bend = iinfo->ii_bend; + while (bindex++ <= bend) { + if (hi->hi_inode) + au_hiput(hi); + hi++; + } + } + kfree(iinfo->ii_hinode); + iinfo->ii_hinode = NULL; + AuRwDestroy(&iinfo->ii_rwsem); +} diff --git a/pool/shard000/C/0011858_cutils.c b/pool/shard000/C/0011858_cutils.c new file mode 100644 index 0000000000000000000000000000000000000000..1090aa4c77d4590ff55d22d8b992e8bb33774840 --- /dev/null +++ b/pool/shard000/C/0011858_cutils.c @@ -0,0 +1,157 @@ +/* + * Simple C functions to supplement the C library + * + * Copyright (c) 2006 Fabrice Bellard + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +#include "qemu-common.h" +#include "host-utils.h" + +void pstrcpy(char *buf, int buf_size, const char *str) +{ + int c; + char *q = buf; + + if (buf_size <= 0) + return; + + for(;;) { + c = *str++; + if (c == 0 || q >= buf + buf_size - 1) + break; + *q++ = c; + } + *q = '\0'; +} + +/* strcat and truncate. */ +char *pstrcat(char *buf, int buf_size, const char *s) +{ + int len; + len = strlen(buf); + if (len < buf_size) + pstrcpy(buf + len, buf_size - len, s); + return buf; +} + +int strstart(const char *str, const char *val, const char **ptr) +{ + const char *p, *q; + p = str; + q = val; + while (*q != '\0') { + if (*p != *q) + return 0; + p++; + q++; + } + if (ptr) + *ptr = p; + return 1; +} + +int stristart(const char *str, const char *val, const char **ptr) +{ + const char *p, *q; + p = str; + q = val; + while (*q != '\0') { + if (qemu_toupper(*p) != qemu_toupper(*q)) + return 0; + p++; + q++; + } + if (ptr) + *ptr = p; + return 1; +} + +time_t mktimegm(struct tm *tm) +{ + time_t t; + int y = tm->tm_year + 1900, m = tm->tm_mon + 1, d = tm->tm_mday; + if (m < 3) { + m += 12; + y--; + } + t = 86400 * (d + (153 * m - 457) / 5 + 365 * y + y / 4 - y / 100 + + y / 400 - 719469); + t += 3600 * tm->tm_hour + 60 * tm->tm_min + tm->tm_sec; + return t; +} + +int qemu_fls(int i) +{ + return 32 - clz32(i); +} + +/* io vectors */ + +void qemu_iovec_init(QEMUIOVector *qiov, int alloc_hint) +{ + qiov->iov = qemu_malloc(alloc_hint * sizeof(struct iovec)); + qiov->niov = 0; + qiov->nalloc = alloc_hint; + qiov->size = 0; +} + +void qemu_iovec_add(QEMUIOVector *qiov, void *base, size_t len) +{ + if (qiov->niov == qiov->nalloc) { + qiov->nalloc = 2 * qiov->nalloc + 1; + qiov->iov = qemu_realloc(qiov->iov, qiov->nalloc * sizeof(struct iovec)); + } + qiov->iov[qiov->niov].iov_base = base; + qiov->iov[qiov->niov].iov_len = len; + qiov->size += len; + ++qiov->niov; +} + +void qemu_iovec_destroy(QEMUIOVector *qiov) +{ + qemu_free(qiov->iov); +} + +void qemu_iovec_to_buffer(QEMUIOVector *qiov, void *buf) +{ + uint8_t *p = (uint8_t *)buf; + int i; + + for (i = 0; i < qiov->niov; ++i) { + memcpy(p, qiov->iov[i].iov_base, qiov->iov[i].iov_len); + p += qiov->iov[i].iov_len; + } +} + +void qemu_iovec_from_buffer(QEMUIOVector *qiov, const void *buf, size_t count) +{ + const uint8_t *p = (const uint8_t *)buf; + size_t copy; + int i; + + for (i = 0; i < qiov->niov && count; ++i) { + copy = count; + if (copy > qiov->iov[i].iov_len) + copy = qiov->iov[i].iov_len; + memcpy(qiov->iov[i].iov_base, p, copy); + p += copy; + count -= copy; + } +} diff --git a/pool/shard000/C/0011865_dted_test.c b/pool/shard000/C/0011865_dted_test.c new file mode 100644 index 0000000000000000000000000000000000000000..43a129fc8012afaf078db8e777a670fbe2a0ab69 --- /dev/null +++ b/pool/shard000/C/0011865_dted_test.c @@ -0,0 +1,159 @@ +/****************************************************************************** + * $Id: dted_test.c 33720 2016-03-15 00:39:53Z goatbar $ + * + * Project: DTED Translator + * Purpose: Test mainline for DTED writer. + * Author: Frank Warmerdam, warmerdam@pobox.com + * + ****************************************************************************** + * Copyright (c) 2001, Frank Warmerdam + * Copyright (c) 2007, Even Rouault + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + *****************************************************************************/ + +#include "gdal.h" +#include "dted_api.h" + +/************************************************************************/ +/* Usage() */ +/************************************************************************/ + +static void Usage() + +{ + printf( "Usage: dted_test [-trim] [-fill n] [-level n] []\n" ); + exit(0); +} + +/************************************************************************/ +/* main() */ +/************************************************************************/ +int main( int argc, char ** argv ) + +{ + GDALDatasetH hSrcDS; + int iY, iX, nOutLevel=0, nXSize, nYSize, iArg, nFillDist=0; + void *pStream; + GInt16 *panData; + const char *pszFilename = NULL; + GDALRasterBandH hSrcBand; + double adfGeoTransform[6]; + int bEnableTrim = FALSE; + GInt16 noDataValue = 0; + int bHasNoData; + +/* -------------------------------------------------------------------- */ +/* Identify arguments. */ +/* -------------------------------------------------------------------- */ + + for( iArg = 1; iArg < argc; iArg++ ) + { + if( EQUAL(argv[iArg],"-trim") ) + bEnableTrim = TRUE; + + else if( EQUAL(argv[iArg],"-fill") ) + nFillDist = atoi(argv[++iArg]); + + else if( EQUAL(argv[iArg],"-level") ) + nOutLevel = atoi(argv[++iArg]); + else + { + if( pszFilename != NULL ) + Usage(); + pszFilename = argv[iArg]; + } + } + + if( pszFilename == NULL ) + Usage(); + +/* -------------------------------------------------------------------- */ +/* Open input file. */ +/* -------------------------------------------------------------------- */ + GDALAllRegister(); + hSrcDS = GDALOpen( pszFilename, GA_ReadOnly ); + if( hSrcDS == NULL ) + exit(1); + + hSrcBand = GDALGetRasterBand( hSrcDS, 1 ); + + noDataValue = (GInt16)GDALGetRasterNoDataValue(hSrcBand, &bHasNoData); + + nXSize = GDALGetRasterXSize( hSrcDS ); + nYSize = GDALGetRasterYSize( hSrcDS ); + + GDALGetGeoTransform( hSrcDS, adfGeoTransform ); + +/* -------------------------------------------------------------------- */ +/* Create output stream. */ +/* -------------------------------------------------------------------- */ + pStream = DTEDCreatePtStream( ".", nOutLevel ); + + if( pStream == NULL ) + exit( 1 ); + +/* -------------------------------------------------------------------- */ +/* Process all the profiles. */ +/* -------------------------------------------------------------------- */ + panData = (GInt16 *) malloc(sizeof(GInt16) * nXSize); + + for( iY = 0; iY < nYSize; iY++ ) + { + GDALRasterIO( hSrcBand, GF_Read, 0, iY, nXSize, 1, + panData, nXSize, 1, GDT_Int16, 0, 0 ); + + if (bHasNoData) + { + for( iX = 0; iX < nXSize; iX++ ) + { + if (panData[iX] == noDataValue) + panData[iX] = DTED_NODATA_VALUE; + } + } + + for( iX = 0; iX < nXSize; iX++ ) + { + DTEDWritePt( pStream, + adfGeoTransform[0] + + adfGeoTransform[1] * (iX + 0.5) + + adfGeoTransform[2] * (iY + 0.5), + adfGeoTransform[3] + + adfGeoTransform[4] * (iX + 0.5) + + adfGeoTransform[5] * (iY + 0.5), + panData[iX] ); + } + } + + free( panData ); + +/* -------------------------------------------------------------------- */ +/* Cleanup. */ +/* -------------------------------------------------------------------- */ + if( bEnableTrim ) + DTEDPtStreamTrimEdgeOnlyTiles( pStream ); + + if( nFillDist > 0 ) + DTEDFillPtStream( pStream, nFillDist ); + + DTEDClosePtStream( pStream ); + GDALClose( hSrcDS ); + + exit( 0 ); +} diff --git a/pool/shard000/C/0011867_test_http_server.c b/pool/shard000/C/0011867_test_http_server.c new file mode 100644 index 0000000000000000000000000000000000000000..70247bd442777ac5bda1fac4f91853bbedcd783c --- /dev/null +++ b/pool/shard000/C/0011867_test_http_server.c @@ -0,0 +1,235 @@ +/* + * Copyright (C) Mark Pentland 2011 + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Library General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor Boston, MA 02110-1301, USA + */ + +#include "test_http_server.h" +#include "common.h" +#include + +int test_http_server_ok_handler(void * cls, + struct MHD_Connection * connection, + const char * url, + const char * method, + const char * version, + const char * upload_data, + size_t * upload_data_size, + void ** ptr) { + + test_http_server * handle = cls; + struct MHD_Response * response; + int ret; + int * c_count; + if (*ptr == NULL) { + handle->log = apr_hash_make(handle->pool); + /* The first time only the headers are valid, + do not respond in the first round... */ + *ptr = cls; //just to flag its not null.... + int * c_count = apr_palloc(handle->pool, sizeof(int)); + *c_count = 0; + *ptr = c_count; + return MHD_YES; + } + c_count = *ptr; + if(*c_count == 0) { + //log the request.... + apr_hash_set(handle->log, apr_pstrdup(handle->pool, "METHOD"), APR_HASH_KEY_STRING, apr_pstrdup(handle->pool, method)); + apr_hash_set(handle->log, apr_pstrdup(handle->pool, "URL"), APR_HASH_KEY_STRING, apr_pstrdup(handle->pool, url)); + apr_hash_set(handle->log, apr_pstrdup(handle->pool, "VERSION"), APR_HASH_KEY_STRING, apr_pstrdup(handle->pool, version)); + apr_hash_set(handle->log, apr_pstrdup(handle->pool, "DATA_LENGTH"), APR_HASH_KEY_STRING, apr_pmemdup (handle->pool, upload_data_size, sizeof(size_t))); + apr_hash_set(handle->log, apr_pstrdup(handle->pool, "DATA"), APR_HASH_KEY_STRING, apr_pmemdup (handle->pool, upload_data, *upload_data_size)); + } + *c_count = *c_count+1; + if(*upload_data_size == 0) { + response = MHD_create_response_from_data(strlen(handle->response), + (void*) handle->response, + MHD_NO, + MHD_NO); + ret = MHD_queue_response(connection, + handle->response_code, + response); + MHD_destroy_response(response); + return ret; + } else { + *upload_data_size = 0; //we processed everything? + return MHD_YES; + } +} + +//this will fail after the header is read... +int test_http_server_fail_handler(void * cls, + struct MHD_Connection * connection, + const char * url, + const char * method, + const char * version, + const char * upload_data, + size_t * upload_data_size, + void ** ptr) { + test_http_server * handle = cls; + struct MHD_Response * response; + int ret; + + return MHD_NO; //serious error! +} + +int test_http_server_timeout_handler(void * cls, + struct MHD_Connection * connection, + const char * url, + const char * method, + const char * version, + const char * upload_data, + size_t * upload_data_size, + void ** ptr) { + + test_http_server * handle = cls; + struct MHD_Response * response; + int ret; + int * c_count; + if (*ptr == NULL) { + handle->log = apr_hash_make(handle->pool); + /* The first time only the headers are valid, + do not respond in the first round... */ + *ptr = cls; //just to flag its not null.... + int * c_count = apr_palloc(handle->pool, sizeof(int)); + *c_count = 0; + *ptr = c_count; + return MHD_YES; + } + c_count = *ptr; + if(*c_count == 0) { + //log the request.... + apr_hash_set(handle->log, apr_pstrdup(handle->pool, "METHOD"), APR_HASH_KEY_STRING, apr_pstrdup(handle->pool, method)); + apr_hash_set(handle->log, apr_pstrdup(handle->pool, "URL"), APR_HASH_KEY_STRING, apr_pstrdup(handle->pool, url)); + apr_hash_set(handle->log, apr_pstrdup(handle->pool, "VERSION"), APR_HASH_KEY_STRING, apr_pstrdup(handle->pool, version)); + apr_hash_set(handle->log, apr_pstrdup(handle->pool, "DATA_LENGTH"), APR_HASH_KEY_STRING, apr_pmemdup (handle->pool, upload_data_size, sizeof(size_t))); + apr_hash_set(handle->log, apr_pstrdup(handle->pool, "DATA"), APR_HASH_KEY_STRING, apr_pmemdup (handle->pool, upload_data, *upload_data_size)); + } + *c_count = *c_count+1; + if(*upload_data_size == 0) { + //cause a timeout... + apr_sleep(handle->sleep_duration); + response = MHD_create_response_from_data(strlen(handle->response), + (void*) handle->response, + MHD_NO, + MHD_NO); + ret = MHD_queue_response(connection, + handle->response_code, + response); + MHD_destroy_response(response); + return ret; + } else { + *upload_data_size = 0; //we processed everything? + return MHD_YES; + } + +} + +int test_http_server_send_half_response_handler(void *cls, uint64_t pos, char *buf, int max) { + test_http_server * handle = cls; + int buf_len = handle->response_length; + if((buf_len / 2) < pos) { //error time.. we have downloaded more than half... + if(handle->sleep_duration > 0) { + apr_sleep(handle->sleep_duration); + handle->sleep_duration = -1; + } else if(handle->sleep_duration==0) { + return -1; + } + } + int to_send = buf_len - pos; + if(to_send > max) { + to_send = max; + } + char * src = (handle->response + pos); + memcpy(buf, src, to_send); + return to_send; +} + +void test_http_server_send_half_response_free_handler(void *cls) { + //do nothing +} + +int test_http_server_send_half_handler(void * cls, + struct MHD_Connection * connection, + const char * url, + const char * method, + const char * version, + const char * upload_data, + size_t * upload_data_size, + void ** ptr) { + + test_http_server * handle = cls; + struct MHD_Response * response; + int ret; + int * c_count; + if (*ptr == NULL) { + handle->log = apr_hash_make(handle->pool); + /* The first time only the headers are valid, + do not respond in the first round... */ + *ptr = cls; //just to flag its not null.... + int * c_count = apr_palloc(handle->pool, sizeof(int)); + *c_count = 0; + *ptr = c_count; + return MHD_YES; + } + c_count = *ptr; + if(*c_count == 0) { + //log the request.... + apr_hash_set(handle->log, apr_pstrdup(handle->pool, "METHOD"), APR_HASH_KEY_STRING, apr_pstrdup(handle->pool, method)); + apr_hash_set(handle->log, apr_pstrdup(handle->pool, "URL"), APR_HASH_KEY_STRING, apr_pstrdup(handle->pool, url)); + apr_hash_set(handle->log, apr_pstrdup(handle->pool, "VERSION"), APR_HASH_KEY_STRING, apr_pstrdup(handle->pool, version)); + apr_hash_set(handle->log, apr_pstrdup(handle->pool, "DATA_LENGTH"), APR_HASH_KEY_STRING, apr_pmemdup (handle->pool, upload_data_size, sizeof(size_t))); + apr_hash_set(handle->log, apr_pstrdup(handle->pool, "DATA"), APR_HASH_KEY_STRING, apr_pmemdup (handle->pool, upload_data, *upload_data_size)); + } + *c_count = *c_count+1; + if(*upload_data_size == 0) { + + + response = MHD_create_response_from_callback(strlen(handle->response), strlen(handle->response) / 10, test_http_server_send_half_response_handler, + handle, test_http_server_send_half_response_free_handler); + + ret = MHD_queue_response(connection, + handle->response_code, + response); + MHD_destroy_response(response); + return ret; + } else { + *upload_data_size = 0; //we processed everything? + return MHD_YES; + } +} + +test_http_server * start_test_http_server(int port, char *response, int response_code, MHD_AccessHandlerCallback handler) { + apr_pool_t *pool = mfs_test_get_pool(); + test_http_server *handle = apr_pcalloc(pool, sizeof(test_http_server)); + handle->response = response; + handle->response_length = strlen(response); + handle->response_code = response_code; + handle->pool = pool; + handle->deamon = MHD_start_daemon(MHD_USE_THREAD_PER_CONNECTION, + port, + NULL, + NULL, + handler, + handle, + MHD_OPTION_END); + + if(handle->deamon == NULL) return NULL; + return handle; +} + +void stop_test_http_server(test_http_server *handle) { + MHD_stop_daemon(handle->deamon); +} \ No newline at end of file diff --git a/pool/shard000/C/0011868_syscall.c b/pool/shard000/C/0011868_syscall.c new file mode 100644 index 0000000000000000000000000000000000000000..0ff5d40e44833bba2025a3940fed2d724e885ffa --- /dev/null +++ b/pool/shard000/C/0011868_syscall.c @@ -0,0 +1,185 @@ +/* + * Copyright (C) 2005 Jan Kiszka . + * Copyright (C) 2005 Joerg Langenberg . + * + * Xenomai is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Xenomai 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 Xenomai; if not, write to the Free Software Foundation, + * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#include +#include +#include + +#include "rtdm/internal.h" + +int __rtdm_muxid; + +static int sys_rtdm_fdcount(struct pt_regs *regs) +{ + return RTDM_FD_MAX; +} + +static int sys_rtdm_open(struct pt_regs *regs) +{ + char krnl_path[RTDM_MAX_DEVNAME_LEN + 1]; + struct task_struct *p = current; + + if (unlikely(__xn_safe_strncpy_from_user(krnl_path, + (const char __user *) + __xn_reg_arg1(regs), + sizeof(krnl_path) - 1) < 0)) + return -EFAULT; + krnl_path[sizeof(krnl_path) - 1] = '\0'; + + return __rt_dev_open(p, (const char *)krnl_path, __xn_reg_arg2(regs)); +} + +static int sys_rtdm_socket(struct pt_regs *regs) +{ + return __rt_dev_socket(current, __xn_reg_arg1(regs), + __xn_reg_arg2(regs), __xn_reg_arg3(regs)); +} + +static int sys_rtdm_close(struct pt_regs *regs) +{ + return __rt_dev_close(current, __xn_reg_arg1(regs)); +} + +static int sys_rtdm_ioctl(struct pt_regs *regs) +{ + return __rt_dev_ioctl(current, __xn_reg_arg1(regs), __xn_reg_arg2(regs), + (void *)__xn_reg_arg3(regs)); +} + +static int sys_rtdm_read(struct pt_regs *regs) +{ + return __rt_dev_read(current, __xn_reg_arg1(regs), + (void *)__xn_reg_arg2(regs), __xn_reg_arg3(regs)); +} + +static int sys_rtdm_write(struct pt_regs *regs) +{ + return __rt_dev_write(current, __xn_reg_arg1(regs), + (const void *)__xn_reg_arg2(regs), + __xn_reg_arg3(regs)); +} + +static int sys_rtdm_recvmsg(struct pt_regs *regs) +{ + struct task_struct *p = current; + struct msghdr krnl_msg; + int ret; + + if (unlikely(!access_wok(__xn_reg_arg2(regs), + sizeof(krnl_msg)) || + __xn_copy_from_user(&krnl_msg, + (void __user *)__xn_reg_arg2(regs), + sizeof(krnl_msg)))) + return -EFAULT; + + ret = __rt_dev_recvmsg(p, __xn_reg_arg1(regs), &krnl_msg, + __xn_reg_arg3(regs)); + if (unlikely(ret < 0)) + return ret; + + if (unlikely(__xn_copy_to_user((void __user *)__xn_reg_arg2(regs), + &krnl_msg, sizeof(krnl_msg)))) + return -EFAULT; + + return ret; +} + +static int sys_rtdm_sendmsg(struct pt_regs *regs) +{ + struct task_struct *p = current; + struct msghdr krnl_msg; + + if (unlikely(!access_rok(__xn_reg_arg2(regs), + sizeof(krnl_msg)) || + __xn_copy_from_user(&krnl_msg, + (void __user *)__xn_reg_arg2(regs), + sizeof(krnl_msg)))) + return -EFAULT; + + return __rt_dev_sendmsg(p, __xn_reg_arg1(regs), &krnl_msg, + __xn_reg_arg3(regs)); +} + +static void *rtdm_skin_callback(int event, void *data) +{ + struct rtdm_process *process; + + switch (event) { + case XNSHADOW_CLIENT_ATTACH: + process = xnarch_alloc_host_mem(sizeof(*process)); + if (!process) + return ERR_PTR(-ENOSPC); + +#ifdef CONFIG_XENO_OPT_VFILE + memcpy(process->name, current->comm, sizeof(process->name)); + process->pid = current->pid; +#endif /* CONFIG_XENO_OPT_VFILE */ + + return &process->ppd; + + case XNSHADOW_CLIENT_DETACH: + process = container_of((xnshadow_ppd_t *) data, + struct rtdm_process, ppd); + + cleanup_owned_contexts(process); + + xnarch_free_host_mem(process, sizeof(*process)); + + break; + } + return NULL; +} + +static xnsysent_t __systab[] = { + [__rtdm_fdcount] = {sys_rtdm_fdcount, __xn_exec_any}, + [__rtdm_open] = {sys_rtdm_open, __xn_exec_current | __xn_exec_adaptive}, + [__rtdm_socket] = + {sys_rtdm_socket, __xn_exec_current | __xn_exec_adaptive}, + [__rtdm_close] = + {sys_rtdm_close, __xn_exec_current | __xn_exec_adaptive}, + [__rtdm_ioctl] = + {sys_rtdm_ioctl, __xn_exec_current | __xn_exec_adaptive}, + [__rtdm_read] = {sys_rtdm_read, __xn_exec_current | __xn_exec_adaptive}, + [__rtdm_write] = + {sys_rtdm_write, __xn_exec_current | __xn_exec_adaptive}, + [__rtdm_recvmsg] = + {sys_rtdm_recvmsg, __xn_exec_current | __xn_exec_adaptive}, + [__rtdm_sendmsg] = + {sys_rtdm_sendmsg, __xn_exec_current | __xn_exec_adaptive}, +}; + +static struct xnskin_props __props = { + .name = "rtdm", + .magic = RTDM_SKIN_MAGIC, + .nrcalls = sizeof(__systab) / sizeof(__systab[0]), + .systab = __systab, + .eventcb = &rtdm_skin_callback, + .timebasep = NULL, + .module = THIS_MODULE +}; + +int __init rtdm_syscall_init(void) +{ + __rtdm_muxid = xnshadow_register_interface(&__props); + + if (__rtdm_muxid < 0) + return -ENOSYS; + + return 0; +} diff --git a/pool/shard000/C/0011869_awgn_tests.c b/pool/shard000/C/0011869_awgn_tests.c new file mode 100644 index 0000000000000000000000000000000000000000..389ef14d4bbb8ac1cd89d4c65d47a24f24a38e4d --- /dev/null +++ b/pool/shard000/C/0011869_awgn_tests.c @@ -0,0 +1,146 @@ +/* + * SpanDSP - a series of DSP components for telephony + * + * awgn_tests.c + * + * Written by Steve Underwood + * + * Copyright (C) 2001 Steve Underwood + * + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, as + * published by the Free Software Foundation. + * + * 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., 675 Mass Ave, Cambridge, MA 02139, USA. + * + * $Id: awgn_tests.c,v 1.18 2008/11/30 12:38:27 steveu Exp $ + */ + +/*! \page awgn_tests_page AWGN tests +\section awgn_tests_page_sec_1 What does it do? +*/ + +#if defined(HAVE_CONFIG_H) +#include "config.h" +#endif + +#include +#include +#include + +//#if defined(WITH_SPANDSP_INTERNALS) +#define SPANDSP_EXPOSE_INTERNAL_STRUCTURES +//#endif + +#include "spandsp.h" + +#if !defined(M_PI) +# define M_PI 3.14159265358979323846 /* pi */ +#endif + +#define OUT_FILE_NAME "awgn.wav" + +/* Some simple sanity tests for the Gaussian noise generation routines */ + +int main (int argc, char *argv[]) +{ + int i; + int j; + int clip_high; + int clip_low; + int total_samples; + int idum = 1234567; + int16_t value; + double total; + double x; + double p; + double o; + double error; + int bins[65536]; + awgn_state_t noise_source; + + /* Generate noise at several RMS levels between -50dBm and 0dBm. Noise is + generated for a large number of samples (1,000,000), and the RMS value + of the noise is calculated along the way. If the resulting level is + close to the requested RMS level, at least the scaling of the noise + should be Ok. At high level some clipping may distort the result a + little. */ + for (j = -50; j <= 0; j += 5) + { + clip_high = 0; + clip_low = 0; + total = 0.0; + awgn_init_dbm0(&noise_source, idum, (float) j); + total_samples = 1000000; + for (i = 0; i < total_samples; i++) + { + value = awgn(&noise_source); + if (value == 32767) + clip_high++; + else if (value == -32768) + clip_low++; + total += ((double) value)*((double) value); + } + error = 100.0*(1.0 - sqrt(total/total_samples)/noise_source.rms); + printf("RMS = %.3f (expected %d) %.2f%% error [clipped samples %d+%d]\n", + log10(sqrt(total/total_samples)/32768.0)*20.0 + DBM0_MAX_POWER, + j, + error, + clip_low, + clip_high); + /* We don't check the result at 0dBm0, as there will definitely be a lot of error due to clipping */ + if (j < 0 && fabs(error) > 0.2) + { + printf("Test failed.\n"); + exit(2); + } + } + /* Now look at the statistical spread of the results, by collecting data in + bins from a large number of samples. Use a fairly high noise level, but + low enough to avoid significant clipping. Use the Gaussian model to + predict the real probability, and present the results for graphing. */ + memset(bins, 0, sizeof(bins)); + clip_high = 0; + clip_low = 0; + awgn_init_dbm0(&noise_source, idum, -15); + total_samples = 10000000; + for (i = 0; i < total_samples; i++) + { + value = awgn(&noise_source); + if (value == 32767) + clip_high++; + else if (value == -32768) + clip_low++; + bins[value + 32768]++; + } + o = noise_source.rms; + for (i = 0; i < 65536 - 10; i++) + { + x = i - 32768; + /* Find the real probability for this bin */ + p = (1.0/(o*sqrt(2.0*M_PI)))*exp(-(x*x)/(2.0*o*o)); + /* Now do a little smoothing on the real data to get a reasonably + steady answer */ + x = 0; + for (j = 0; j < 10; j++) + x += bins[i + j]; + x /= 10.0; + x /= total_samples; + /* Now send it out for graphing. */ + printf("%6d %.7f %.7f\n", i - 32768, x, p); + } + + printf("Tests passed.\n"); + return 0; +} +/*- End of function --------------------------------------------------------*/ +/*- End of file ------------------------------------------------------------*/ diff --git a/pool/shard000/C/0011870_ipv6_server_test.c b/pool/shard000/C/0011870_ipv6_server_test.c new file mode 100644 index 0000000000000000000000000000000000000000..aabc56faf1f9dfc1c4f2527a820d3d7fff13d0b3 --- /dev/null +++ b/pool/shard000/C/0011870_ipv6_server_test.c @@ -0,0 +1,142 @@ +//========================================================================== +// +// tests/ipv6_server_test.c +// +// Simple TCP 'server' test - modified for IPv6 +// +//========================================================================== +// ####BSDALTCOPYRIGHTBEGIN#### +// ------------------------------------------- +// Portions of this software may have been derived from FreeBSD, OpenBSD, +// or other sources, and if so are covered by the appropriate copyright +// and license included herein. +// ------------------------------------------- +// ####BSDALTCOPYRIGHTEND#### +//========================================================================== +//#####DESCRIPTIONBEGIN#### +// +// Author(s): gthomas +// Contributors: gthomas +// Date: 2000-01-10 +// Purpose: +// Description: +// +// +//####DESCRIPTIONEND#### +// +//========================================================================== +// Network server test code +#include +#include +#include + +#ifndef CYGPKG_LIBC_STDIO +#define perror(s) diag_printf(#s ": %s\n", strerror(errno)) +#endif + +#define STACK_SIZE (CYGNUM_HAL_STACK_SIZE_TYPICAL + 0x1000) +static char stack[STACK_SIZE]; +static cyg_thread thread_data; +static cyg_handle_t thread_handle; + +extern void +cyg_test_exit(void); + +void +pexit(char *s) +{ + perror(s); + cyg_test_exit(); +} + +static void +server_test(struct bootp *bp) +{ + int s, client, client_len; + struct sockaddr_in6 client_addr, local; + char buf[256], addr_buf[256]; + int one = 1; + fd_set in_fds; + int num, len; + struct timeval tv; + + s = socket(AF_INET6, SOCK_STREAM, 0); + if (s < 0) { + pexit("stream socket"); + } + if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one))) { + pexit("setsockopt SO_REUSEADDR"); + } + if (setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(one))) { + pexit("setsockopt SO_REUSEPORT"); + } + memset(&local, 0, sizeof(local)); + local.sin6_family = AF_INET6; + local.sin6_len = sizeof(local); + local.sin6_port = htons(7734); + local.sin6_addr = in6addr_any; + if(bind(s, (struct sockaddr *) &local, sizeof(local)) < 0) { + pexit("bind error"); + } + listen(s, SOMAXCONN); + while (true) { + client_len = sizeof(client_addr); + if ((client = accept(s, (struct sockaddr *)&client_addr, &client_len)) < 0) { + pexit("accept"); + } + client_len = sizeof(client_addr); + getpeername(client, (struct sockaddr *)&client_addr, &client_len); + inet_ntop(AF_INET6, (char *)&client_addr.sin6_addr, addr_buf, sizeof(addr_buf)); + diag_printf("connection from %s:%d\n", addr_buf, ntohs(client_addr.sin6_port)); + diag_sprintf(buf, "Hello %s:%d\n", addr_buf, ntohs(client_addr.sin6_port)); + write(client, buf, strlen(buf)); + tv.tv_sec = 5; + tv.tv_usec = 0; + FD_ZERO(&in_fds); + FD_SET(client, &in_fds); + num = select(client+1, &in_fds, 0, 0, &tv); + if (num > 0) { + len = read(client, buf, sizeof(buf)-1); + buf[len] = '\0'; + diag_printf("buf = '%s'\n", buf); + } else if (num == 0) { + diag_printf("No reply - timed out\n"); + } else { + perror("select"); + } + sprintf(buf, "Thanks, bye now!\n"); + write(client, buf, strlen(buf)); + close(client); + } + close(s); +} + +void +net_test(cyg_addrword_t param) +{ + diag_printf("Start SERVER test\n"); + init_all_network_interfaces(); +#ifdef CYGHWR_NET_DRIVER_ETH0 + if (eth0_up) { + server_test(ð0_bootp_data); + } +#endif + cyg_test_exit(); +} + +void +cyg_start(void) +{ + // Create a main thread, so we can run the scheduler and have time 'pass' + cyg_thread_create(10, // Priority - just a number + net_test, // entry + 0, // entry parameter + "Network test", // Name + &stack[0], // Stack + STACK_SIZE, // Size + &thread_handle, // Handle + &thread_data // Thread data structure + ); + cyg_thread_resume(thread_handle); // Start it + cyg_scheduler_start(); +} diff --git a/pool/shard000/C/0011873_kdb_samba_pac.c b/pool/shard000/C/0011873_kdb_samba_pac.c new file mode 100644 index 0000000000000000000000000000000000000000..15497603b108cfbd76a858617c9d484289a15b55 --- /dev/null +++ b/pool/shard000/C/0011873_kdb_samba_pac.c @@ -0,0 +1,112 @@ +/* + Unix SMB/CIFS implementation. + + Samba KDB plugin for MIT Kerberos + + Copyright (c) 2010 Simo Sorce . + Copyright (c) 2014 Andreas Schneider + + 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 + along with this program. If not, see . +*/ + +#include "includes.h" + +#include "system/kerberos.h" + +#include +#include + +#include "kdc/mit_samba.h" +#include "kdb_samba.h" + +krb5_error_code kdb_samba_dbekd_decrypt_key_data(krb5_context context, + const krb5_keyblock *mkey, + const krb5_key_data *key_data, + krb5_keyblock *kkey, + krb5_keysalt *keysalt) +{ + /* + * NOTE: Samba doesn't use a master key, so we will just copy + * the contents around untouched. + */ + ZERO_STRUCTP(kkey); + + kkey->magic = KV5M_KEYBLOCK; + kkey->enctype = key_data->key_data_type[0]; + kkey->contents = malloc(key_data->key_data_length[0]); + if (kkey->contents == NULL) { + return ENOMEM; + } + memcpy(kkey->contents, + key_data->key_data_contents[0], + key_data->key_data_length[0]); + kkey->length = key_data->key_data_length[0]; + + if (keysalt != NULL) { + keysalt->type = key_data->key_data_type[1]; + keysalt->data.data = malloc(key_data->key_data_length[1]); + if (keysalt->data.data == NULL) { + free(kkey->contents); + return ENOMEM; + } + memcpy(keysalt->data.data, + key_data->key_data_contents[1], + key_data->key_data_length[1]); + keysalt->data.length = key_data->key_data_length[1]; + } + + return 0; +} + +krb5_error_code kdb_samba_dbekd_encrypt_key_data(krb5_context context, + const krb5_keyblock *mkey, + const krb5_keyblock *kkey, + const krb5_keysalt *keysalt, + int keyver, + krb5_key_data *key_data) +{ + /* + * NOTE: samba doesn't use a master key, so we will just copy + * the contents around untouched. + */ + + ZERO_STRUCTP(key_data); + + key_data->key_data_ver = KRB5_KDB_V1_KEY_DATA_ARRAY; + key_data->key_data_kvno = keyver; + key_data->key_data_type[0] = kkey->enctype; + key_data->key_data_contents[0] = malloc(kkey->length); + if (key_data->key_data_contents[0] == NULL) { + return ENOMEM; + } + memcpy(key_data->key_data_contents[0], + kkey->contents, + kkey->length); + key_data->key_data_length[0] = kkey->length; + + if (keysalt != NULL) { + key_data->key_data_type[1] = keysalt->type; + key_data->key_data_contents[1] = malloc(keysalt->data.length); + if (key_data->key_data_contents[1] == NULL) { + free(key_data->key_data_contents[0]); + return ENOMEM; + } + memcpy(key_data->key_data_contents[1], + keysalt->data.data, + keysalt->data.length); + key_data->key_data_length[1] = keysalt->data.length; + } + + return 0; +} diff --git a/pool/shard000/C/0011876_test_undo.c b/pool/shard000/C/0011876_test_undo.c new file mode 100644 index 0000000000000000000000000000000000000000..9609a3c8aee20cf8e61680a1746330f7ef174c74 --- /dev/null +++ b/pool/shard000/C/0011876_test_undo.c @@ -0,0 +1,203 @@ +#define DEBUG +#include +#include +#include +#include +#include + +#include "board.h" +#include "board_undo.h" +#include "debug.h" +#include "playout.h" +#include "playout/light.h" + +/* Like board_cmp() but only care about fields maintained by quick_play() / quick_undo() */ +static int +board_quick_cmp(struct board *b1, struct board *b2) +{ + if (b1->rsize != b2->rsize || + b1->captures[S_BLACK] != b2->captures[S_BLACK] || + b1->captures[S_WHITE] != b2->captures[S_WHITE] || + b1->moves != b2->moves) { + fprintf(stderr, "differs in main vars\n"); + return 1; + } + if (move_cmp(&last_move(b1), &last_move(b2)) || + move_cmp(&last_move2(b1), &last_move2(b2))) { + fprintf(stderr, "differs in last_move\n"); + return 1; + } + if (move_cmp(&b1->ko, &b2->ko) || + move_cmp(&b1->last_ko, &b2->last_ko) || + b1->last_ko_age != b2->last_ko_age) { + fprintf(stderr, "differs in ko\n"); + return 1; + } + + if (memcmp(b1->b, b2->b, sizeof(b1->b))) { + fprintf(stderr, "differs in b\n"); return 1; } + if (memcmp(b1->g, b2->g, sizeof(b1->g))) { + fprintf(stderr, "differs in g\n"); return 1; } + if (memcmp(b1->n, b2->n, sizeof(b1->n))) { + fprintf(stderr, "differs in n\n"); return 1; } + if (memcmp(b1->p, b2->p, sizeof(b1->p))) { + fprintf(stderr, "differs in p\n"); return 1; } + if (memcmp(b1->gi, b2->gi, sizeof(b1->gi))) { + fprintf(stderr, "differs in gi\n"); return 1; } + + return 0; +} + +static void +board_dump_group(board_t *b, group_t g) +{ + printf("group base: %s color: %s libs: %i stones: %i\n", + coord2sstr(g), stone2str(board_at(b, g)), + board_group_info(b, g).libs, group_stone_count(b, g, 500)); + + printf(" stones: "); + foreach_in_group(b, g) { + printf("%s ", coord2sstr(c)); + } foreach_in_group_end; + printf("\n"); + + printf(" libs : "); + for (int i = 0; i < board_group_info(b, g).libs; i++) { + coord_t lib = board_group_info(b, g).lib[i]; + printf("%s ", coord2sstr(lib)); + } + printf("\n"); +} + +static void +board_dump(board_t *b) +{ + printf("board_dump(): size: %i\n", board_rsize(b)); + board_print(b, stdout); + + printf("ko: %s %s last_ko: %s %s last_ko_age: %i\n", + stone2str(b->ko.color), coord2sstr(b->ko.coord), + stone2str(b->last_ko.color), coord2sstr(b->last_ko.coord), + b->last_ko_age); + + printf("groups: \n"); + int seen[BOARD_MAX_COORDS] = {0, }; + foreach_point(b) { + if (board_at(b, c) != S_BLACK && board_at(b, c) != S_WHITE) + continue; + group_t g = group_at(b, c); + if (seen[g]) + continue; + seen[g] = 1; + board_dump_group(b, g); + } foreach_point_end; + + printf("\n"); +} + + +// Print info about suicides +static void +show_suicide_info(board_t *b, board_t *orig, coord_t c, enum stone color) +{ + if (board_at(b, c) != S_NONE) + return; + + int groups[4] = { 0, }; + int n = 0, stones = 0; + foreach_neighbor(orig, c, { + if (board_at(orig, c) != color) + continue; + group_t g = group_at(orig, c); + int i; + for (i = 0; groups[i] && groups[i] != g; i++) + ; + groups[i] = g; + if (i > n) + n = i; + stones += group_stone_count(orig, g, 400); + }); + + if (++n > 1) + fprintf(stderr, "multi-group suicide: %i groups %i stones\n", n, stones); +} + + +/* Play move and check board states after quick_play() / quick_undo() match */ +static coord_t +test_undo(board_t *orig, coord_t c, enum stone color) +{ + board_t b, b2; + board_copy(&b, orig); + board_copy(&b2, orig); + + move_t m = move(c, color); + int r = board_play(&b, &m); assert(r >= 0); + + with_move(&b2, c, color, { + // Check state after quick_board_play() matches + assert(!board_quick_cmp(&b2, &b)); + }); + + if (DEBUGL(3)) + show_suicide_info(&b, orig, c, color); + if (DEBUGL(4)) + board_print(&b, stderr); + + // Check board_quick_undo() restored board properly + if (board_quick_cmp(&b2, orig) || board_cmp(&b2, orig)) { + board_dump(orig); + board_dump(&b2); + assert(0); + } + + board_done(&b); + board_done(&b2); + + return c; +} + + +static playoutp_permit policy_permit = NULL; + +static bool +permit_hook(playout_policy_t *playout_policy, board_t *b, move_t *m, bool alt, bool rnd) +{ + test_undo(b, m->coord, m->color); + + /* Also test pass, permit() never gets called on pass ... */ + if (fast_random(100) < 5) + test_undo(b, pass, m->color); + + return (policy_permit ? policy_permit(playout_policy, b, m, alt, rnd) : true); +} + + +/* Play some random games testing undo on every move. */ +bool +board_undo_stress_test(board_t *board, char *arg) +{ + int games = 100; + enum stone color = S_BLACK; + + if (DEBUGL(2)) board_print(board, stderr); + if (DEBUGL(1)) printf("board_undo stress test. Playing %i games checking every move + pass...\n", games); + + // Light policy better to test wild multi-group suicides + playout_policy_t *policy = playout_light_init(NULL, board); + playout_setup_t setup = playout_setup(MAX_GAMELEN, 0); + + // Hijack policy permit() + policy_permit = policy->permit; policy->permit = permit_hook; + + /* Play some games */ + for (int i = 0; i < games; i++) { + board_t b; + board_copy(&b, board); + playout_play_game(&setup, &b, color, NULL, NULL, policy); + board_done(&b); + } + + printf("All good.\n\n"); + return true; +} diff --git a/pool/shard000/C/0011878_mdwt.c b/pool/shard000/C/0011878_mdwt.c new file mode 100644 index 0000000000000000000000000000000000000000..cab7b0345f186b4aae0eb31d37271246a5bcf8a3 --- /dev/null +++ b/pool/shard000/C/0011878_mdwt.c @@ -0,0 +1,104 @@ +/* +File Name: mdwt.c +Last Modification Date: 06/14/95 12:56:43 +Current Version: mdwt.c 1.5 +File Creation Date: Wed Oct 12 08:44:43 1994 +Author: Markus Lang + +Copyright: All software, documentation, and related files in this distribution + are Copyright (c) 1994 Rice University + +Permission is granted for use and non-profit distribution providing that this +notice be clearly maintained. The right to distribute any portion for profit +or as part of any commercial product is specifically reserved for the author. + +Change History: Fixed code such that the result has the same dimension as the + input for 1D problems. Also, added some standard error checking. + Jan Erik Odegard Wed Jun 14 1995 + +MATLAB gateway for MDWT.c, discrete wavelet transform +*/ +#include +/*#include */ +#include +#include "mex.h" +#include "matrix.h" + +#define max(A,B) (A > B ? A : B) +#define min(A,B) (A < B ? A : B) +#define even(x) ((x & 1) ? 0 : 1) +#define isint(x) ((x - floor(x)) > 0.0 ? 0 : 1) + +void MDWT(double *x, int m, int n, double *h, int lh, int L, double *y); + +void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[]) + +{ + double *x, *h, *y, *Lf, *Lr; + int m, n, h_col, h_row, lh, L, i, po2, j; + double mtest, ntest; + + /* check for correct # of input variables */ + if (nrhs>3){ + mexErrMsgTxt("There are at most 3 input parameters allowed!"); + return; + } + if (nrhs<2){ + mexErrMsgTxt("There are at least 2 input parameters required!"); + return; + } + x = mxGetPr(prhs[0]); + n = mxGetN(prhs[0]); + m = mxGetM(prhs[0]); + h = mxGetPr(prhs[1]); + h_col = mxGetN(prhs[1]); + h_row = mxGetM(prhs[1]); + if (h_col>h_row) + lh = h_col; + else + lh = h_row; + if (nrhs == 3){ + L = (int) *mxGetPr(prhs[2]); + if (L < 0) + mexErrMsgTxt("The number of levels, L, must be a non-negative integer"); + } + else /* Estimate L */ { + i=n;j=0; + while (even(i)){ + i=(i>>1); + j++; + } + L=m;i=0; + while (even(L)){ + L=(L>>1); + i++; + } + if(min(m,n) == 1) + L = max(i,j); + else + L = min(i,j); + if (L==0){ + mexErrMsgTxt("Maximum number of levels is zero; no decomposition can be performed!"); + return; + } + } + /* Check the ROW dimension of input */ + if(m > 1){ + mtest = (double) m/pow(2.0, (double) L); + if (!isint(mtest)) + mexErrMsgTxt("The matrix row dimension must be of size m*2^(L)"); + } + /* Check the COLUMN dimension of input */ + if(n > 1){ + ntest = (double) n/pow(2.0, (double) L); + if (!isint(ntest)) + mexErrMsgTxt("The matrix column dimension must be of size n*2^(L)"); + } + plhs[0] = mxCreateDoubleMatrix(m,n,mxREAL); + y = mxGetPr(plhs[0]); + plhs[1] = mxCreateDoubleMatrix(1,1,mxREAL); + Lr = mxGetPr(plhs[1]); + *Lr = L; + MDWT(x, m, n, h, lh, L, y); +} + diff --git a/pool/shard000/C/0011888_HGU_XmPB_Row.c b/pool/shard000/C/0011888_HGU_XmPB_Row.c new file mode 100644 index 0000000000000000000000000000000000000000..019874544c7d55579d814714565a2d3006e563de --- /dev/null +++ b/pool/shard000/C/0011888_HGU_XmPB_Row.c @@ -0,0 +1,133 @@ +#if defined(__GNUC__) +#ident "University of Edinburgh $Id$" +#else +static char _HGU_XmPB_Row_c[] = "University of Edinburgh $Id$"; +#endif +/*! +* \file HGU_XmPB_Row.c +* \author Richard Baldock +* \date April 2009 +* \version $Id$ +* \par +* Address: +* MRC Human Genetics Unit, +* MRC Institute of Genetics and Molecular Medicine, +* University of Edinburgh, +* Western General Hospital, +* Edinburgh, EH4 2XU, UK. +* \par +* Copyright (C), [2012], +* The University Court of the University of Edinburgh, +* Old College, Edinburgh, UK. +* +* This program is free software; you can redistribute it and/or +* modify it under the terms of the GNU General Public License +* as published by the Free Software Foundation; either version 2 +* of the License, or (at your option) any later version. +* +* This program is distributed in the hope that it will be +* useful but WITHOUT ANY WARRANTY; without even the implied +* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +* PURPOSE. See the GNU General Public License for more +* details. +* +* You should have received a copy of the GNU General Public +* License along with this program; if not, write to the Free +* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, +* Boston, MA 02110-1301, USA. +* \ingroup HGU_Xm +* \brief Implement a push-button row with label. This +* is a convenience routine to provide a simple interface +* for a push button style interface. This is to provide +* a graphical element with a row of push buttons preceded +* by a label. +*/ + +#include + +#include +#include +#include +#include +#include + +#include + +/*! +* \return The pointer to the parent (Form) widget. +* \ingroup HGU_Xm +* \brie Procedure to put together a Form widget with a Label, +* and push button interface - RowColumn + PushButtons +* It is NOT a widget proper and setting +* specific resource to change the default appearence +* will require knowing the widget namesf +* \param name The top-level and label widget name. +* \param parent The parent widget. +* \param items The toggle button items. +*/ +Widget HGU_XmCreatePB_Row( +String name, +Widget parent, +MenuItem *items) +{ + Widget base, label, row, widget; + int i; + + base = XtVaCreateWidget(name, xmFormWidgetClass, parent, + XmNborderWidth, 0, + XmNverticalSpacing, 3, + NULL); + + label = XtVaCreateManagedWidget(name, xmLabelWidgetClass, base, + XmNtopAttachment, XmATTACH_FORM, + XmNbottomAttachment,XmATTACH_FORM, + XmNleftAttachment, XmATTACH_FORM, + XmNborderWidth, 0, + NULL); + + row = XtVaCreateWidget("row", xmRowColumnWidgetClass, base, + XmNtopAttachment, XmATTACH_FORM, + XmNbottomAttachment, XmATTACH_FORM, + XmNrightAttachment, XmATTACH_FORM, + XmNleftAttachment, XmATTACH_WIDGET, + XmNleftWidget, label, + XmNborderWidth, 0, + XmNorientation, XmHORIZONTAL, + NULL); + + i = 0; + while( items[i].name != NULL ){ + widget = XtVaCreateManagedWidget(items[i].name, + xmPushButtonWidgetClass, row, + XmNborderWidth, 0, + XmNshadowThickness, 4, + NULL); + + /* add mnemonic */ + if( items[i].mnemonic ) + XtVaSetValues( widget, XmNmnemonic, items[i].mnemonic, NULL ); + + /* add accelerators */ + if( items[i].accelerator ){ + XmString str = XmStringCreateSimple( items[i].accel_text ); + XtVaSetValues( widget, + XmNaccelerator, items[i].accelerator, + XmNacceleratorText, str, + NULL); + XmStringFree( str ); + } + + /* add callbacks */ + if( items[i].callback ){ + XtAddCallback( widget, XmNactivateCallback, + items[i].callback, items[i].callback_data ); + } + + i++; + } + + + XtManageChild( row ); + XtManageChild( base ); + return( base ); +} diff --git a/pool/shard000/C/0011890_chipset.c b/pool/shard000/C/0011890_chipset.c new file mode 100644 index 0000000000000000000000000000000000000000..f680456b1a53361dafa8f8c062b0d86f8846e086 --- /dev/null +++ b/pool/shard000/C/0011890_chipset.c @@ -0,0 +1,44 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ + +#include +#include + +uint32_t update_psp_bios_dir(uint32_t *psp_dir_offset, uint32_t *bios_dir_offset) +{ + return svc_update_psp_bios_dir(psp_dir_offset, bios_dir_offset); +} + +uint32_t save_uapp_data(void *address, uint32_t size) +{ + return svc_save_uapp_data(address, size); +} + +uint32_t get_bios_dir_addr(struct psp_ef_table *ef_table) +{ + return ef_table->bios3_entry; +} + +int platform_set_sha_op(enum vb2_hash_algorithm hash_alg, + struct sha_generic_data *sha_op) +{ + if (hash_alg == VB2_HASH_SHA256) { + sha_op->SHAType = SHA_TYPE_256; + sha_op->DigestLen = 32; + } else if (hash_alg == VB2_HASH_SHA384) { + sha_op->SHAType = SHA_TYPE_384; + sha_op->DigestLen = 48; + } else { + return -1; + } + return 0; +} + + +/* Functions below are stub functions for not-yet-implemented PSP features. + * These functions should be replaced with proper implementations later. + */ + +uint32_t svc_write_postcode(uint32_t postcode) +{ + return 0; +} diff --git a/pool/shard000/C/0011898_skeleton.c b/pool/shard000/C/0011898_skeleton.c new file mode 100644 index 0000000000000000000000000000000000000000..52a2ba5a3137dce9db907f15ac1cd5ec1403ca2f --- /dev/null +++ b/pool/shard000/C/0011898_skeleton.c @@ -0,0 +1,211 @@ +#include +#include "skeleton.h" +#include + +#define MAX_ADDR_LEN 6 +struct rt_skeleton_eth +{ + /* inherit from ethernet device */ + struct eth_device parent; + + /* interface address info. */ + rt_uint8_t dev_addr[MAX_ADDR_LEN]; /* hw address */ +}; +static struct rt_skeleton_eth _skeleton_device; + +void rt_skeleton_isr(int irqno) +{ + rt_uint32_t status; + + /* read status */ + + /* Received the coming packet */ + if (status) + { + /* disable receive interrupt */ + + /* a frame has been received */ + eth_device_ready(&(_skeleton_device.parent)); + } + + /* Transmit Interrupt check */ + if (status) + { + } +} + +static rt_err_t rt_skeleton_init(rt_device_t dev) +{ + return RT_EOK; +} + +static rt_err_t rt_skeleton_open(rt_device_t dev, rt_uint16_t oflag) +{ + return RT_EOK; +} + +static rt_err_t rt_skeleton_close(rt_device_t dev) +{ + return RT_EOK; +} + +static rt_size_t rt_skeleton_read(rt_device_t dev, rt_off_t pos, void* buffer, rt_size_t size) +{ + rt_set_errno(-RT_ENOSYS); + return 0; +} + +static rt_size_t rt_skeleton_write (rt_device_t dev, rt_off_t pos, const void* buffer, rt_size_t size) +{ + rt_set_errno(-RT_ENOSYS); + return 0; +} + +static rt_err_t rt_skeleton_control(rt_device_t dev, int cmd, void *args) +{ + struct rt_skeleton_eth *eth; + + eth = (struct rt_skeleton_eth*)dev; + RT_ASSERT(eth != RT_NULL); + + switch (cmd) + { + case NIOCTL_GADDR: + /* get mac address */ + if (args) rt_memcpy(args, _skeleton_device.dev_addr, 6); + else return -RT_ERROR; + break; + + default : + break; + } + + return RT_EOK; +} + +rt_err_t rt_skeleton_tx( rt_device_t dev, struct pbuf* p) +{ + { + /* q traverses through linked list of pbuf's + * This list MUST consist of a single packet ONLY */ + struct pbuf *q; + rt_uint16_t pbuf_index = 0; + rt_uint8_t word[2], word_index = 0; + + q = p; + /* Write data into hardware, two bytes at a time + * Handling pbuf's with odd number of bytes correctly + * No attempt to optimize for speed has been made */ + while (q) + { + if (pbuf_index < q->len) + { + word[word_index++] = ((u8_t*)q->payload)[pbuf_index++]; + if (word_index == 2) + { + /* write data to hardware */ + + word_index = 0; + } + } + else + { + q = q->next; + pbuf_index = 0; + } + } + /* One byte could still be unsent */ + if (word_index == 1) + { + /* write data to hardware */ + + } + } + + return RT_EOK; +} + +struct pbuf *rt_skeleton_rx(rt_device_t dev) +{ + struct pbuf* p; + rt_uint32_t rxbyte; + + /* init p pointer */ + p = RT_NULL; + rxbyte = 0; /* get eth status */ + if (rxbyte) /* there is data received */ + { + rt_uint16_t rx_len; + rt_uint16_t* data; + + /* get recieved packet length */ + rx_len = 0; + + /* allocate buffer */ + p = pbuf_alloc(PBUF_LINK, rx_len, PBUF_RAM); + if (p != RT_NULL) + { + struct pbuf* q; + rt_int32_t len; + + for (q = p; q != RT_NULL; q= q->next) + { + data = (rt_uint16_t*)q->payload; + len = q->len; + + while (len > 0) + { + *data = 0; /* read data from hardware */ + data ++; + len -= 2; + } + } + } + else + { + rt_uint16_t dummy; + rt_int32_t len; + + /* no pbuf, discard data from EMAC */ + data = &dummy; + len = rx_len; + while (len > 0) + { + *data = 0; /* read from hardware */ + len -= 2; + } + } + } + else + { + /* restore receive interrupt */ + } + + return p; +} + +void rt_hw_skeleton_init() +{ + /* set default MAC address */ + _skeleton_device.dev_addr[0] = 0x00; + _skeleton_device.dev_addr[1] = 0x60; + _skeleton_device.dev_addr[2] = 0x6E; + _skeleton_device.dev_addr[3] = 0x11; + _skeleton_device.dev_addr[4] = 0x22; + _skeleton_device.dev_addr[5] = 0x33; + + /* set RT-Thread device interface */ + _skeleton_device.parent.parent.init = rt_skeleton_init; + _skeleton_device.parent.parent.open = rt_skeleton_open; + _skeleton_device.parent.parent.close = rt_skeleton_close; + _skeleton_device.parent.parent.read = rt_skeleton_read; + _skeleton_device.parent.parent.write = rt_skeleton_write; + _skeleton_device.parent.parent.control = rt_skeleton_control; + _skeleton_device.parent.parent.user_data = RT_NULL; + + /* set ethernet interface */ + _skeleton_device.parent.eth_rx = rt_skeleton_rx; + _skeleton_device.parent.eth_tx = rt_skeleton_tx; + + eth_device_init(&(_skeleton_device.parent), "e0"); +} diff --git a/pool/shard000/C/0011902_litmus.c b/pool/shard000/C/0011902_litmus.c new file mode 100644 index 0000000000000000000000000000000000000000..18ab53e9d078237426dce20040f5f246027e0c77 --- /dev/null +++ b/pool/shard000/C/0011902_litmus.c @@ -0,0 +1,195 @@ +#include +#include +#include +#include +#include +#include +#include +#include + + +#include /* for cpu sets */ + +#include "litmus.h" +#include "internal.h" + +#define LP(name) {name ## _SEM, #name} + +static struct { + int id; + const char* name; +} protocol[] = { + LP(FMLP), + LP(SRP), + LP(MPCP), + LP(MPCP_VS), + {MPCP_VS_SEM, "MPCP-VS"}, + LP(DPCP), + LP(PCP), + LP(DFLP), + LP(MRSP), +}; + +#define NUM_PROTOS (sizeof(protocol)/sizeof(protocol[0])) + +int lock_protocol_for_name(const char* name) +{ + int i; + + for (i = 0; i < NUM_PROTOS; i++) + if (strcmp(name, protocol[i].name) == 0) + return protocol[i].id; + + return -1; +} + +const char* name_for_lock_protocol(int id) +{ + int i; + + for (i = 0; i < NUM_PROTOS; i++) + if (protocol[i].id == id) + return protocol[i].name; + + return ""; +} + +int litmus_open_lock( + obj_type_t protocol, + int lock_id, + const char* namespace, + void *config_param) +{ + int fd, od; + + fd = open(namespace, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); + if (fd < 0) + return -1; + od = od_openx(fd, protocol, lock_id, config_param); + close(fd); + return od; +} + + + +void show_rt_param(struct rt_task* tp) +{ + printf("rt params:\n\t" + "exec_cost:\t%llu\n\tperiod:\t\t%llu\n\tcpu:\t%d\n", + tp->exec_cost, tp->period, tp->cpu); +} + +void init_rt_task_param(struct rt_task* tp) +{ + /* Defaults: + * - implicit deadline (t->relative_deadline == 0) + * - phase = 0 + * - class = RT_CLASS_SOFT + * - budget policy = NO_ENFORCEMENT + * - fixed priority = LITMUS_LOWEST_PRIORITY + * - release policy = TASK_SPORADIC + * - cpu assignment = 0 + * + * User must still set the following fields to non-zero values: + * - tp->exec_cost + * - tp->period + * + * User must set tp->cpu to the appropriate value for non-global + * schedulers. For clusters, set tp->cpu to the first CPU in the + * assigned cluster. + */ + + memset(tp, 0, sizeof(*tp)); + + tp->cls = RT_CLASS_SOFT; + tp->priority = LITMUS_LOWEST_PRIORITY; + tp->budget_policy = NO_ENFORCEMENT; + tp->release_policy = TASK_SPORADIC; +} + +task_class_t str2class(const char* str) +{ + if (!strcmp(str, "hrt")) + return RT_CLASS_HARD; + else if (!strcmp(str, "srt")) + return RT_CLASS_SOFT; + else if (!strcmp(str, "be")) + return RT_CLASS_BEST_EFFORT; + else + return -1; +} + +#define NS_PER_MS 1000000 + +int sporadic_global(lt_t e_ns, lt_t p_ns) +{ + struct rt_task param; + + init_rt_task_param(¶m); + param.exec_cost = e_ns; + param.period = p_ns; + + return set_rt_task_param(gettid(), ¶m); +} + +int sporadic_partitioned(lt_t e_ns, lt_t p_ns, int partition) +{ + int ret; + struct rt_task param; + + ret = be_migrate_to_domain(partition); + check("be_migrate_to_domain()"); + if (ret != 0) + return ret; + + init_rt_task_param(¶m); + param.exec_cost = e_ns; + param.period = p_ns; + param.cpu = domain_to_first_cpu(partition); + + return set_rt_task_param(gettid(), ¶m); +} + +int sporadic_clustered(lt_t e_ns, lt_t p_ns, int cluster) +{ + int ret; + struct rt_task param; + + ret = be_migrate_to_domain(cluster); + check("be_migrate_to_cluster()"); + if (ret != 0) + return ret; + + init_rt_task_param(¶m); + param.exec_cost = e_ns; + param.period = p_ns; + param.cpu = domain_to_first_cpu(cluster); + + return set_rt_task_param(gettid(), ¶m); +} + +int init_kernel_iface(void); + +int init_litmus(void) +{ + int ret, ret2; + + ret = mlockall(MCL_CURRENT | MCL_FUTURE); + check("mlockall()"); + ret2 = init_rt_thread(); + return (ret == 0) && (ret2 == 0) ? 0 : -1; +} + +int init_rt_thread(void) +{ + int ret; + + ret = init_kernel_iface(); + check("kernel <-> user space interface initialization"); + return ret; +} + +void exit_litmus(void) +{ + /* nothing to do in current version */ +} diff --git a/pool/shard000/C/0011903_example-transaction.c b/pool/shard000/C/0011903_example-transaction.c new file mode 100644 index 0000000000000000000000000000000000000000..3977b4840d6c191fcbeb1870ee6061833a360d6f --- /dev/null +++ b/pool/shard000/C/0011903_example-transaction.c @@ -0,0 +1,180 @@ +/* gcc example-transaction.c -o example-transaction \ + * $(pkg-config --cflags --libs libmongoc-1.0) */ + +/* ./example-transaction [CONNECTION_STRING] */ + +#include +#include + + +int +main (int argc, char *argv[]) +{ + int exit_code = EXIT_FAILURE; + + mongoc_client_t *client = NULL; + mongoc_database_t *database = NULL; + mongoc_collection_t *collection = NULL; + mongoc_client_session_t *session = NULL; + mongoc_session_opt_t *session_opts = NULL; + mongoc_transaction_opt_t *default_txn_opts = NULL; + mongoc_transaction_opt_t *txn_opts = NULL; + mongoc_read_concern_t *read_concern = NULL; + mongoc_write_concern_t *write_concern = NULL; + const char *uri_string = "mongodb://127.0.0.1/?appname=transaction-example"; + mongoc_uri_t *uri; + bson_error_t error; + bson_t *doc = NULL; + bson_t *insert_opts = NULL; + int32_t i; + int64_t start; + bson_t reply = BSON_INITIALIZER; + char *reply_json; + bool r; + + mongoc_init (); + + if (argc > 1) { + uri_string = argv[1]; + } + + uri = mongoc_uri_new_with_error (uri_string, &error); + if (!uri) { + MONGOC_ERROR ("failed to parse URI: %s\n" + "error message: %s\n", + uri_string, + error.message); + goto done; + } + + client = mongoc_client_new_from_uri (uri); + if (!client) { + goto done; + } + + mongoc_client_set_error_api (client, 2); + database = mongoc_client_get_database (client, "example-transaction"); + + /* inserting into a nonexistent collection normally creates it, but a + * collection can't be created in a transaction; create it now */ + collection = + mongoc_database_create_collection (database, "collection", NULL, &error); + + if (!collection) { + /* code 48 is NamespaceExists, see error_codes.err in mongodb source */ + if (error.code == 48) { + collection = mongoc_database_get_collection (database, "collection"); + } else { + MONGOC_ERROR ("Failed to create collection: %s", error.message); + goto done; + } + } + + /* a transaction's read preferences, read concern, and write concern can be + * set on the client, on the default transaction options, or when starting + * the transaction. for the sake of this example, set read concern on the + * default transaction options. */ + default_txn_opts = mongoc_transaction_opts_new (); + read_concern = mongoc_read_concern_new (); + mongoc_read_concern_set_level (read_concern, "snapshot"); + mongoc_transaction_opts_set_read_concern (default_txn_opts, read_concern); + session_opts = mongoc_session_opts_new (); + mongoc_session_opts_set_default_transaction_opts (session_opts, + default_txn_opts); + + session = mongoc_client_start_session (client, session_opts, &error); + if (!session) { + MONGOC_ERROR ("Failed to start session: %s", error.message); + goto done; + } + + /* in this example, set write concern when starting the transaction */ + txn_opts = mongoc_transaction_opts_new (); + write_concern = mongoc_write_concern_new (); + mongoc_write_concern_set_wmajority (write_concern, 1000 /* wtimeout */); + mongoc_transaction_opts_set_write_concern (txn_opts, write_concern); + + insert_opts = bson_new (); + if (!mongoc_client_session_append (session, insert_opts, &error)) { + MONGOC_ERROR ("Could not add session to opts: %s", error.message); + goto done; + } + +retry_transaction: + r = mongoc_client_session_start_transaction (session, txn_opts, &error); + if (!r) { + MONGOC_ERROR ("Failed to start transaction: %s", error.message); + goto done; + } + + /* insert two documents - on error, retry the whole transaction */ + for (i = 0; i < 2; i++) { + doc = BCON_NEW ("_id", BCON_INT32 (i)); + bson_destroy (&reply); + r = mongoc_collection_insert_one ( + collection, doc, insert_opts, &reply, &error); + + bson_destroy (doc); + + if (!r) { + MONGOC_ERROR ("Insert failed: %s", error.message); + mongoc_client_session_abort_transaction (session, NULL); + + /* a network error, primary failover, or other temporary error in a + * transaction includes {"errorLabels": ["TransientTransactionError"]}, + * meaning that trying the entire transaction again may succeed + */ + if (mongoc_error_has_label (&reply, "TransientTransactionError")) { + goto retry_transaction; + } + + goto done; + } + + reply_json = bson_as_json (&reply, NULL); + printf ("%s\n", reply_json); + bson_free (reply_json); + } + + /* in case of transient errors, retry for 5 seconds to commit transaction */ + start = bson_get_monotonic_time (); + while (bson_get_monotonic_time () - start < 5 * 1000 * 1000) { + bson_destroy (&reply); + r = mongoc_client_session_commit_transaction (session, &reply, &error); + if (r) { + /* success */ + break; + } else { + MONGOC_ERROR ("Warning: commit failed: %s", error.message); + if (mongoc_error_has_label (&reply, "TransientTransactionError")) { + goto retry_transaction; + } else if (mongoc_error_has_label (&reply, + "UnknownTransactionCommitResult")) { + /* try again to commit */ + continue; + } + + /* unrecoverable error trying to commit */ + break; + } + } + + exit_code = EXIT_SUCCESS; + +done: + bson_destroy (&reply); + bson_destroy (insert_opts); + mongoc_write_concern_destroy (write_concern); + mongoc_read_concern_destroy (read_concern); + mongoc_transaction_opts_destroy (txn_opts); + mongoc_transaction_opts_destroy (default_txn_opts); + mongoc_client_session_destroy (session); + mongoc_collection_destroy (collection); + mongoc_database_destroy (database); + mongoc_uri_destroy (uri); + mongoc_client_destroy (client); + + mongoc_cleanup (); + + return exit_code; +} diff --git a/pool/shard000/C/0011906_handler.c b/pool/shard000/C/0011906_handler.c new file mode 100644 index 0000000000000000000000000000000000000000..d0ce6a804a55a836027b35be18aa611ae7fdcc6e --- /dev/null +++ b/pool/shard000/C/0011906_handler.c @@ -0,0 +1,65 @@ +#include +#include +#include +#include +#include + +/* Obtain a backtrace and print it to stdout. */ +#define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0])) +void dump_stack(void) +{ + void *array[30] = { 0 }; + size_t size = backtrace(array, ARRAY_SIZE(array)); + char **strings = backtrace_symbols(array, size); + size_t i; + + if (strings == NULL) + { + perror("backtrace_symbols."); + exit(EXIT_FAILURE); + } + + printf("Obtained %zd stack frames.\n", size); + + for (i = 0; i < size; i++) + printf("%s\n", strings[i]); + + free(strings); + strings = NULL; + + exit(EXIT_SUCCESS); +} + +void sighandler_dump_stack(int sig) +{ + psignal(sig, "handler"); + dump_stack(); + signal(sig, SIG_DFL); + raise(sig); +} + +void func_c() +{ + *((volatile int *)0x0) = 0x9999; /* ERROR */ +} + +void func_b() +{ + func_c(); +} + +void func_a() +{ + func_b(); +} + + +int main(int argc, const char *argv[]) +{ + if (signal(SIGSEGV, sighandler_dump_stack) == SIG_ERR) + perror("can't catch SIGSEGV"); + + func_a(); + + return 0; +} diff --git a/pool/shard000/C/0011925_mcfmii.c b/pool/shard000/C/0011925_mcfmii.c new file mode 100644 index 0000000000000000000000000000000000000000..4f1c0a0127b174971977be98b31dd6dc37f60a6d --- /dev/null +++ b/pool/shard000/C/0011925_mcfmii.c @@ -0,0 +1,332 @@ +/* + * Copyright (C) 2004-2008 Freescale Semiconductor, Inc. + * TsiChung Liew (Tsi-Chung.Liew@freescale.com) + * + * See file CREDITS for list of people who contributed to this + * project. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of + * the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, + * MA 02111-1307 USA + */ + +#include +#include +#include +#include + +#ifdef CONFIG_MCF547x_8x +#include +#else +#include +#endif +#include + +DECLARE_GLOBAL_DATA_PTR; + +#if defined(CONFIG_CMD_NET) && defined(CONFIG_NET_MULTI) +#undef MII_DEBUG +#undef ET_DEBUG + +/*extern int fecpin_setclear(struct eth_device *dev, int setclear);*/ + +#if defined(CONFIG_SYS_DISCOVER_PHY) || defined(CONFIG_CMD_MII) +#include + +/* Make MII read/write commands for the FEC. */ +#define mk_mii_read(ADDR, REG) (0x60020000 | ((ADDR << 23) | \ + (REG & 0x1f) << 18)) +#define mk_mii_write(ADDR, REG, VAL) (0x50020000 | ((ADDR << 23) | \ + (REG & 0x1f) << 18) | (VAL & 0xffff)) + +#ifndef CONFIG_SYS_UNSPEC_PHYID +# define CONFIG_SYS_UNSPEC_PHYID 0 +#endif +#ifndef CONFIG_SYS_UNSPEC_STRID +# define CONFIG_SYS_UNSPEC_STRID 0 +#endif + +#ifdef CONFIG_MCF547x_8x +typedef struct fec_info_dma FEC_INFO_T; +#define FEC_T fecdma_t +#else +typedef struct fec_info_s FEC_INFO_T; +#define FEC_T fec_t +#endif + +typedef struct phy_info_struct { + u32 phyid; + char *strid; +} phy_info_t; + +phy_info_t phyinfo[] = { + {0x0022561B, "AMD79C784VC"}, /* AMD 79C784VC */ + {0x00406322, "BCM5222"}, /* Broadcom 5222 */ + {0x02a80150, "Intel82555"}, /* Intel 82555 */ + {0x0016f870, "LSI80225"}, /* LSI 80225 */ + {0x0016f880, "LSI80225/B"}, /* LSI 80225/B */ + {0x78100000, "LXT970"}, /* LXT970 */ + {0x001378e0, "LXT971"}, /* LXT971 and 972 */ + {0x00221619, "KS8721BL"}, /* Micrel KS8721BL/SL */ + {0x00221512, "KSZ8041NL"}, /* Micrel KSZ8041NL */ + {0x20005CE1, "N83640"}, /* National 83640 */ + {0x20005C90, "N83848"}, /* National 83848 */ + {0x20005CA2, "N83849"}, /* National 83849 */ + {0x01814400, "QS6612"}, /* QS6612 */ +#if defined(CONFIG_SYS_UNSPEC_PHYID) && defined(CONFIG_SYS_UNSPEC_STRID) + {CONFIG_SYS_UNSPEC_PHYID, CONFIG_SYS_UNSPEC_STRID}, +#endif + {0, 0} +}; + +/* + * mii_init -- Initialize the MII for MII command without ethernet + * This function is a subset of eth_init + */ +void mii_reset(FEC_INFO_T *info) +{ + volatile FEC_T *fecp = (FEC_T *) (info->miibase); + int i; + + fecp->ecr = FEC_ECR_RESET; + + for (i = 0; (fecp->ecr & FEC_ECR_RESET) && (i < FEC_RESET_DELAY); ++i) { + udelay(1); + } + if (i == FEC_RESET_DELAY) + printf("FEC_RESET_DELAY timeout\n"); +} + +/* send command to phy using mii, wait for result */ +uint mii_send(uint mii_cmd) +{ + FEC_INFO_T *info; + volatile FEC_T *ep; + struct eth_device *dev; + uint mii_reply; + int j = 0; + + /* retrieve from register structure */ + dev = eth_get_dev(); + info = dev->priv; + + ep = (FEC_T *) info->miibase; + + ep->mmfr = mii_cmd; /* command to phy */ + + /* wait for mii complete */ + while (!(ep->eir & FEC_EIR_MII) && (j < MCFFEC_TOUT_LOOP)) { + udelay(1); + j++; + } + if (j >= MCFFEC_TOUT_LOOP) { + printf("MII not complete\n"); + return -1; + } + + mii_reply = ep->mmfr; /* result from phy */ + ep->eir = FEC_EIR_MII; /* clear MII complete */ +#ifdef ET_DEBUG + printf("%s[%d] %s: sent=0x%8.8x, reply=0x%8.8x\n", + __FILE__, __LINE__, __FUNCTION__, mii_cmd, mii_reply); +#endif + + return (mii_reply & 0xffff); /* data read from phy */ +} +#endif /* CONFIG_SYS_DISCOVER_PHY || (CONFIG_MII) */ + +#if defined(CONFIG_SYS_DISCOVER_PHY) +int mii_discover_phy(struct eth_device *dev) +{ +#define MAX_PHY_PASSES 11 + FEC_INFO_T *info = dev->priv; + int phyaddr, pass; + uint phyno, phytype; + int i, found = 0; + + if (info->phyname_init) + return info->phy_addr; + + phyaddr = -1; /* didn't find a PHY yet */ + for (pass = 1; pass <= MAX_PHY_PASSES && phyaddr < 0; ++pass) { + if (pass > 1) { + /* PHY may need more time to recover from reset. + * The LXT970 needs 50ms typical, no maximum is + * specified, so wait 10ms before try again. + * With 11 passes this gives it 100ms to wake up. + */ + udelay(10000); /* wait 10ms */ + } + + for (phyno = 0; phyno < 32 && phyaddr < 0; ++phyno) { + + phytype = mii_send(mk_mii_read(phyno, PHY_PHYIDR1)); +#ifdef ET_DEBUG + printf("PHY type 0x%x pass %d type\n", phytype, pass); +#endif + if (phytype != 0xffff) { + phyaddr = phyno; + phytype <<= 16; + phytype |= + mii_send(mk_mii_read(phyno, PHY_PHYIDR2)); + +#ifdef ET_DEBUG + printf("PHY @ 0x%x pass %d\n", phyno, pass); +#endif + + for (i = 0; i < (sizeof(phyinfo) / sizeof(phy_info_t)); i++) { + if (phyinfo[i].phyid == phytype) { +#ifdef ET_DEBUG + printf("phyid %x - %s\n", + phyinfo[i].phyid, + phyinfo[i].strid); +#endif + strcpy(info->phy_name, phyinfo[i].strid); + info->phyname_init = 1; + found = 1; + break; + } + } + + if (!found) { +#ifdef ET_DEBUG + printf("0x%08x\n", phytype); +#endif + strcpy(info->phy_name, "unknown"); + info->phyname_init = 1; + break; + } + } + } + } + + if (phyaddr < 0) + printf("No PHY device found.\n"); + + return phyaddr; +} +#endif /* CONFIG_SYS_DISCOVER_PHY */ + +void mii_init(void) __attribute__((weak,alias("__mii_init"))); + +void __mii_init(void) +{ + FEC_INFO_T *info; + volatile FEC_T *fecp; + struct eth_device *dev; + int miispd = 0, i = 0; + u16 status = 0; + u16 linkgood = 0; + + /* retrieve from register structure */ + dev = eth_get_dev(); + info = dev->priv; + + fecp = (FEC_T *) info->miibase; + + fecpin_setclear(dev, 1); + + mii_reset(info); + + /* We use strictly polling mode only */ + fecp->eimr = 0; + + /* Clear any pending interrupt */ + fecp->eir = 0xffffffff; + + /* Set MII speed */ + miispd = (gd->bus_clk / 1000000) / 5; + fecp->mscr = miispd << 1; + + info->phy_addr = mii_discover_phy(dev); + + while (i < MCFFEC_TOUT_LOOP) { + status = 0; + i++; + /* Read PHY control register */ + miiphy_read(dev->name, info->phy_addr, PHY_BMCR, &status); + + /* If phy set to autonegotiate, wait for autonegotiation done, + * if phy is not autonegotiating, just wait for link up. + */ + if ((status & PHY_BMCR_AUTON) == PHY_BMCR_AUTON) { + linkgood = (PHY_BMSR_AUTN_COMP | PHY_BMSR_LS); + } else { + linkgood = PHY_BMSR_LS; + } + /* Read PHY status register */ + miiphy_read(dev->name, info->phy_addr, PHY_BMSR, &status); + if ((status & linkgood) == linkgood) + break; + + udelay(500); + } + if (i >= MCFFEC_TOUT_LOOP) { + printf("Link UP timeout\n"); + } + + /* adapt to the duplex and speed settings of the phy */ + info->dup_spd = miiphy_duplex(dev->name, info->phy_addr) << 16; + info->dup_spd |= miiphy_speed(dev->name, info->phy_addr); +} + +/* + * Read and write a MII PHY register, routines used by MII Utilities + * + * FIXME: These routines are expected to return 0 on success, but mii_send + * does _not_ return an error code. Maybe 0xFFFF means error, i.e. + * no PHY connected... + * For now always return 0. + * FIXME: These routines only work after calling eth_init() at least once! + * Otherwise they hang in mii_send() !!! Sorry! + */ + +int mcffec_miiphy_read(char *devname, unsigned char addr, unsigned char reg, + unsigned short *value) +{ + short rdreg; /* register working value */ + +#ifdef MII_DEBUG + printf("miiphy_read(0x%x) @ 0x%x = ", reg, addr); +#endif + rdreg = mii_send(mk_mii_read(addr, reg)); + + *value = rdreg; + +#ifdef MII_DEBUG + printf("0x%04x\n", *value); +#endif + + return 0; +} + +int mcffec_miiphy_write(char *devname, unsigned char addr, unsigned char reg, + unsigned short value) +{ + short rdreg; /* register working value */ + +#ifdef MII_DEBUG + printf("miiphy_write(0x%x) @ 0x%x = ", reg, addr); +#endif + + rdreg = mii_send(mk_mii_write(addr, reg, value)); + +#ifdef MII_DEBUG + printf("0x%04x\n", value); +#endif + + return 0; +} + +#endif /* CONFIG_CMD_NET, FEC_ENET & NET_MULTI */ diff --git a/pool/shard000/C/0011928_hi6421-pmic-core.c b/pool/shard000/C/0011928_hi6421-pmic-core.c new file mode 100644 index 0000000000000000000000000000000000000000..95b2ff8f223ab34bc06f45c585d1a5a55e02c810 --- /dev/null +++ b/pool/shard000/C/0011928_hi6421-pmic-core.c @@ -0,0 +1,113 @@ +/* + * Device driver for Hi6421 IC + * + * Copyright (c) <2011-2014> HiSilicon Technologies Co., Ltd. + * http://www.hisilicon.com + * Copyright (c) <2013-2014> Linaro Ltd. + * http://www.linaro.org + * + * Author: Guodong Xu + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +static const struct mfd_cell hi6421_devs[] = { + { .name = "hi6421-regulator", }, +}; + +static const struct regmap_config hi6421_regmap_config = { + .reg_bits = 32, + .reg_stride = 4, + .val_bits = 8, + .max_register = HI6421_REG_TO_BUS_ADDR(HI6421_REG_MAX), +}; + +static int hi6421_pmic_probe(struct platform_device *pdev) +{ + struct hi6421_pmic *pmic; + struct resource *res; + void __iomem *base; + int ret; + + pmic = devm_kzalloc(&pdev->dev, sizeof(*pmic), GFP_KERNEL); + if (!pmic) + return -ENOMEM; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + base = devm_ioremap_resource(&pdev->dev, res); + if (IS_ERR(base)) + return PTR_ERR(base); + + pmic->regmap = devm_regmap_init_mmio_clk(&pdev->dev, NULL, base, + &hi6421_regmap_config); + if (IS_ERR(pmic->regmap)) { + dev_err(&pdev->dev, + "regmap init failed: %ld\n", PTR_ERR(pmic->regmap)); + return PTR_ERR(pmic->regmap); + } + + /* set over-current protection debounce 8ms */ + regmap_update_bits(pmic->regmap, HI6421_OCP_DEB_CTRL_REG, + (HI6421_OCP_DEB_SEL_MASK + | HI6421_OCP_EN_DEBOUNCE_MASK + | HI6421_OCP_AUTO_STOP_MASK), + (HI6421_OCP_DEB_SEL_8MS + | HI6421_OCP_EN_DEBOUNCE_ENABLE)); + + platform_set_drvdata(pdev, pmic); + + ret = mfd_add_devices(&pdev->dev, 0, hi6421_devs, + ARRAY_SIZE(hi6421_devs), NULL, 0, NULL); + if (ret) { + dev_err(&pdev->dev, "add mfd devices failed: %d\n", ret); + return ret; + } + + return 0; +} + +static int hi6421_pmic_remove(struct platform_device *pdev) +{ + mfd_remove_devices(&pdev->dev); + + return 0; +} + +static const struct of_device_id of_hi6421_pmic_match_tbl[] = { + { .compatible = "hisilicon,hi6421-pmic", }, + { }, +}; + +static struct platform_driver hi6421_pmic_driver = { + .driver = { + .name = "hi6421_pmic", + .of_match_table = of_hi6421_pmic_match_tbl, + }, + .probe = hi6421_pmic_probe, + .remove = hi6421_pmic_remove, +}; +module_platform_driver(hi6421_pmic_driver); + +MODULE_AUTHOR("Guodong Xu "); +MODULE_DESCRIPTION("Hi6421 PMIC driver"); +MODULE_LICENSE("GPL v2"); diff --git a/pool/shard000/C/0011932_ex_kcm_direct.c b/pool/shard000/C/0011932_ex_kcm_direct.c new file mode 100644 index 0000000000000000000000000000000000000000..d9447c2241aafe1492382686b22dbdd8112e533e --- /dev/null +++ b/pool/shard000/C/0011932_ex_kcm_direct.c @@ -0,0 +1,102 @@ +/* Shows the ability to play a sample without a mixer. */ + +#include +#include "allegro5/allegro.h" +#include "allegro5/allegro_audio.h" +#include "allegro5/allegro_acodec.h" + +#include "common.c" + +int main(int argc, char **argv) +{ + ALLEGRO_VOICE *voice; + ALLEGRO_SAMPLE_INSTANCE *sample; + int i; + + if (!al_init()) { + abort_example("Could not init Allegro.\n"); + } + + open_log(); + + if (argc < 2) { + log_printf("This example needs to be run from the command line.\nUsage: %s {audio_files}\n", argv[0]); + goto done; + } + + al_init_acodec_addon(); + + if (!al_install_audio()) { + abort_example("Could not init sound!\n"); + } + + for (i = 1; i < argc; ++i) { + ALLEGRO_SAMPLE *sample_data = NULL; + const char *filename = argv[i]; + ALLEGRO_CHANNEL_CONF chan; + ALLEGRO_AUDIO_DEPTH depth; + unsigned long freq; + float sample_time = 0; + + /* Load the entire sound file from disk. */ + sample_data = al_load_sample(filename); + if (!sample_data) { + log_printf("Could not load sample from '%s'!\n", + filename); + continue; + } + + sample = al_create_sample_instance(NULL); + if (!sample) { + abort_example("al_create_sample failed.\n"); + } + + if (!al_set_sample(sample, sample_data)) { + log_printf("al_set_sample failed.\n"); + continue; + } + + depth = al_get_sample_instance_depth(sample); + chan = al_get_sample_instance_channels(sample); + freq = al_get_sample_instance_frequency(sample); + log_printf("Loaded sample: %i-bit depth, %i channels, %li Hz\n", + (depth < 8) ? (8+depth*8) : 0, (chan>>4)+(chan%0xF), freq); + log_printf("Trying to create a voice with the same specs... "); + voice = al_create_voice(freq, depth, chan); + if (!voice) { + abort_example("Could not create ALLEGRO_VOICE.\n"); + } + log_printf("done.\n"); + + if (!al_attach_sample_instance_to_voice(sample, voice)) { + abort_example("al_attach_sample_instance_to_voice failed.\n"); + } + + /* Play sample in looping mode. */ + al_set_sample_instance_playmode(sample, ALLEGRO_PLAYMODE_LOOP); + al_play_sample_instance(sample); + + sample_time = al_get_sample_instance_time(sample); + log_printf("Playing '%s' (%.3f seconds) 3 times", filename, + sample_time); + + al_rest(sample_time * 3); + + al_stop_sample_instance(sample); + log_printf("\n"); + + /* Free the memory allocated. */ + al_set_sample(sample, NULL); + al_destroy_sample(sample_data); + al_destroy_sample_instance(sample); + al_destroy_voice(voice); + } + + al_uninstall_audio(); +done: + close_log(true); + + return 0; +} + +/* vim: set sts=3 sw=3 et: */ diff --git a/pool/shard000/C/0011938_ann_sim.c b/pool/shard000/C/0011938_ann_sim.c new file mode 100644 index 0000000000000000000000000000000000000000..ba73c1ddec8394bb2ae8f4eb777cd4adb3d8c07f --- /dev/null +++ b/pool/shard000/C/0011938_ann_sim.c @@ -0,0 +1,255 @@ +/** + * Copyright (C) 2012, 2013, Universidad Simón Bolívar + * + * Copying: GNU GENERAL PUBLIC LICENSE Version 2 + * @author Guillermo Palma + */ + +#include +#include +#include +#include +#include + +#include "dlist.h" +#include "types.h" +#include "util.h" +#include "memory.h" +#include "vec.h" +#include "graph.h" +#include "CA.h" +#include "metric.h" +#include "match.h" +#include "concorde.h" +#include "ann_sim.h" + +#define ROOT 0 + +struct dmatrix { + long r, c; + long **lca; + double **sim; +}; + +static void init_dmatrix(struct dmatrix *m, long row, long col) +{ + m->r = row; + m->c = col; + m->sim = double_matrix(0, m->r, 0, m->c); + m->lca = long_matrix(0, m->r, 0, m->c); +} + +static void free_dmatrix(struct dmatrix *m) +{ + free_double_matrix(m->sim, 0, 0); + free_long_matrix(m->lca, 0, 0); +} + +static inline void print_dmatrix(double * const *a, long n, long m) +{ + int i, j; + + for (i = 0; i < n; i++) { + for (j = 0; j < m; j++) { + printf("%.3f ", a[i][j]); + } + printf("\n"); + } +} + +static struct dmatrix *calculate_metrics(const struct graph *g, const VEC(long) *vnodes1, + const VEC(long) *vnodes2) +{ + long i, j, x, y; + double dtax; + + struct dmatrix *metric; + metric = xmalloc(sizeof(struct dmatrix)); + init_dmatrix(metric, VEC_SIZE(*vnodes1), VEC_SIZE(*vnodes2)); + init_metric_data(g); + for (i = 0; i < metric->r; i++) { + x = VEC_GET(*vnodes1, i); + for (j = 0; j < metric->c; j++) { + y = VEC_GET(*vnodes2, j); + dtax = dist_tax_lca(g, x, y, &metric->lca[i][j]); + assert(dtax >= 0 && dtax <= 1.0); + metric->sim[i][j] = dtax; + } + } + free_metric(); + return metric; +} + +/* + struct edge_blist { + long id; + long from; + long to; + double cost; + struct list_head list; + }; + + struct graph_bipartite { + long n; + VEC(long) *x; + VEC(long) *y; + struct edge_blist e; + }; + + static struct graph_bipartite modifySet; + + static void get_modify_set(const VEC(long) *vnodes1, const VEC(long) *vnodes2, + struct dmatrix *metric) + { + long i, j, id; + bool *xadd, *yadd; + size_t alloc; + struct edge_blist *etmp; + + alloc = metric->r*sizeof(bool); + xadd = xmalloc(alloc); + memset(xadd, 0, alloc); + alloc = metric->c*sizeof(bool); + yadd = xmalloc(alloc); + memset(yadd, 0, alloc); + VEC_INIT(long, *modifySet.x); + VEC_INIT(long, *modifySet.y); + INIT_LIST_HEAD(&modifySet.e.list); + modifySet.n = 0; + id = 0; + printf("Modify Set\n"); + for (i = 0; i < metric->r; i++) { + for (j = 0; j < metric->c; j++) { + if (metric->lca[i][j] != ROOT) { + if (xadd[i] == false) { + xadd[i] = true; + VEC_PUSH(long, *modifySet.x, i); + } + if (yadd[j] == false) { + yadd[j] = true; + VEC_PUSH(long, *modifySet.y, j); + } + etmp = (struct edge_blist *)xmalloc(sizeof(struct edge_blist)); + printf("Pair-Wise: %ld -- %ld (lca %ld) (cost %.3f)\n", + VEC_GET(*vnodes1, i), + VEC_GET(*vnodes2,j), metric->lca[i][j], metric->sim[i][j]); + etmp->to = i; + etmp->from = j; + etmp->id = id++; + etmp->cost = metric->sim[i][j]; + list_add_tail(&etmp->list, &modifySet.e.list); + modifySet.n++; + } + } + } + assert(modifySet.n == id); + } + + static void free_get_modify_set(void) + { + struct edge_blist *etmp; + struct list_head *pos, *q; + + VEC_DESTROY(*modifySet.x); + VEC_DESTROY(*modifySet.y); + list_for_each_safe(pos, q, &modifySet.e.list){ + etmp = list_entry(pos, struct edge_blist, list); + list_del(pos); + free(etmp); + } + } +*/ + +static inline void print_max_matching(struct match_edge *me, struct dmatrix *matrix, + const VEC(long) *vnodes1, const VEC(long) *vnodes2) +{ + long k, n, i, j; + + + n = me[0].b; + printf("Perfect matching %ld\n", n); + assert(matrix->r == n); + for (k = 1; k <= n; k++) { + i = me[k].a; + j = me[k].b-n; + printf("(%ld -- %ld) (%ld -- %ld) %.3f\n", i, j, VEC_GET(*vnodes1, i), + VEC_GET(*vnodes2, j), matrix->sim[i][j]); + } + printf("\n"); +} + +double similarity_ann_sim(const struct graph *g, const VEC(long) *vnodes1, const VEC(long) *vnodes2) +{ + double s; + VEC(long) vx, vy; + long i, j, n, m, q, n_edges, n_nodes, k; + struct dmatrix *ametric; + struct match_edge *in, *out; + double sum; + + s = 0.0; + n = VEC_SIZE(*vnodes1); + m = VEC_SIZE(*vnodes2); + VEC_INIT_N(long, vx, n); + VEC_INIT_N(long, vy, m); + VEC_COPY(long, *vnodes1, vx); + VEC_COPY(long, *vnodes2, vy); + assert(VEC_SIZE(vx) == (unsigned)n); + assert(VEC_SIZE(vy) == (unsigned)m); + if (n > m) { + q = n - m; + for (i = 0; i < q; i++) { + VEC_PUSH(long, vy, ROOT); + } + } else { + q = m - n; + for (i = 0; i < q; i++) { + VEC_PUSH(long, vx, ROOT); + } + } + ametric = calculate_metrics(g, &vx, &vy); +#ifdef PRGDEBUG + printf("Add %ld nodes\n\n", q); + print_dmatrix(ametric->sim, ametric->r, ametric->c); +#endif + n = VEC_SIZE(vx); + assert((unsigned)n == VEC_SIZE(vy)); + n_nodes = n*2; + n_edges = n*n; + m = n_edges+1; + in = (struct match_edge *)xmalloc(m*sizeof(struct match_edge)); + out = (struct match_edge *)xmalloc(m*sizeof(struct match_edge)); + in[0].a = n_nodes; + in[0].b = n_edges; + m = 1; + for (i = 0; i < n; i++) { + for (j = n; j < n_nodes; j++) { + in[m].a = i; + in[m].b = j; + in[m].cost = (long)(ametric->sim[i][j-n]*10000.0); + m++; + } + } + assert((m-1) == n_edges); + min_weight_perfect_match(in, out); +#ifdef PRGDEBUG + print_max_matching(out, ametric, &vx, &vy); +#endif + n = out[0].b; + assert(ametric->r == n); + sum = 0.0; + for (k = 1; k <= n; k++) { + i = out[k].a; + j = out[k].b-n; + sum += 1.0 - ametric->sim[i][j]; + } + s = (2.0*sum) / (VEC_SIZE(*vnodes1) + VEC_SIZE(*vnodes2)); + free(out); + free(in); + free_dmatrix(ametric); + free(ametric); + VEC_DESTROY(vx); + VEC_DESTROY(vy); + + return s; +} diff --git a/pool/shard000/C/0011946_setpgid.c b/pool/shard000/C/0011946_setpgid.c new file mode 100644 index 0000000000000000000000000000000000000000..804cb71b1939588f835439d040c8ac54b2641206 --- /dev/null +++ b/pool/shard000/C/0011946_setpgid.c @@ -0,0 +1,57 @@ +/* Copyright (C) 1993, 1994, 1995, 1996, 1997 Free Software Foundation, Inc. + This file is part of the GNU C Library. + + The GNU C Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The GNU C Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. */ + +#include +#include +#include +#include + +/* Set the process group ID of the process matching PID to PGID. + If PID is zero, the current process's process group ID is set. + If PGID is zero, the process ID of the process is used. */ +int +__setpgid (pid, pgid) + pid_t pid; + pid_t pgid; +{ + error_t err; + unsigned int stamp; + + stamp = _hurd_pids_changed_stamp; /* Atomic fetch. */ + + if (err = __USEPORT (PROC, __proc_setpgrp (port, pid, pgid))) + return __hurd_fail (err); + + if (pid == 0 || pid == _hurd_pid) + /* Synchronize with the signal thread to make sure we have + received and processed proc_newids before returning to the user. */ + while (_hurd_pids_changed_stamp == stamp) + { +#ifdef noteven + /* XXX we have no need for a mutex, but cthreads demands one. */ + __condition_wait (&_hurd_pids_changed_sync, NULL); +#else + __swtch_pri(0); +#endif + } + + return 0; + +} + +weak_alias (__setpgid, setpgid) diff --git a/pool/shard000/C/0011957_strequal.c b/pool/shard000/C/0011957_strequal.c new file mode 100644 index 0000000000000000000000000000000000000000..f69c5bf9e75f3c014c3c2584e51abadc54a0c312 --- /dev/null +++ b/pool/shard000/C/0011957_strequal.c @@ -0,0 +1,124 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2011, Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at http://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef HAVE_STRINGS_H +#include +#endif + +#include "strequal.h" + +/* + * @unittest: 1301 + */ +int curl_strequal(const char *first, const char *second) +{ +#if defined(HAVE_STRCASECMP) + return !(strcasecmp)(first, second); +#elif defined(HAVE_STRCMPI) + return !(strcmpi)(first, second); +#elif defined(HAVE_STRICMP) + return !(stricmp)(first, second); +#else + while(*first && *second) { + if(toupper(*first) != toupper(*second)) { + break; + } + first++; + second++; + } + return toupper(*first) == toupper(*second); +#endif +} + +/* + * @unittest: 1301 + */ +int curl_strnequal(const char *first, const char *second, size_t max) +{ +#if defined(HAVE_STRNCASECMP) + return !strncasecmp(first, second, max); +#elif defined(HAVE_STRNCMPI) + return !strncmpi(first, second, max); +#elif defined(HAVE_STRNICMP) + return !strnicmp(first, second, max); +#else + while(*first && *second && max) { + if(toupper(*first) != toupper(*second)) { + break; + } + max--; + first++; + second++; + } + if(0 == max) + return 1; /* they are equal this far */ + + return toupper(*first) == toupper(*second); +#endif +} + +#ifndef HAVE_STRLCAT +/* + * The strlcat() function appends the NUL-terminated string src to the end + * of dst. It will append at most size - strlen(dst) - 1 bytes, NUL-termi- + * nating the result. + * + * The strlcpy() and strlcat() functions return the total length of the + * string they tried to create. For strlcpy() that means the length of src. + * For strlcat() that means the initial length of dst plus the length of + * src. While this may seem somewhat confusing it was done to make trunca- + * tion detection simple. + * + * + */ +size_t Curl_strlcat(char *dst, const char *src, size_t siz) +{ + char *d = dst; + const char *s = src; + size_t n = siz; + union { + ssize_t sig; + size_t uns; + } dlen; + + /* Find the end of dst and adjust bytes left but don't go past end */ + while(n-- != 0 && *d != '\0') + d++; + dlen.sig = d - dst; + n = siz - dlen.uns; + + if(n == 0) + return(dlen.uns + strlen(s)); + while(*s != '\0') { + if(n != 1) { + *d++ = *s; + n--; + } + s++; + } + *d = '\0'; + + return(dlen.uns + (s - src)); /* count does not include NUL */ +} +#endif diff --git a/pool/shard000/C/0011964_shmctl06.c b/pool/shard000/C/0011964_shmctl06.c new file mode 100644 index 0000000000000000000000000000000000000000..368759980b74f4e85748587b67c98c2db6475b0c --- /dev/null +++ b/pool/shard000/C/0011964_shmctl06.c @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* + * Copyright (c) 2020 Viresh Kumar + * + * Description: + * Cross verify the _high fields being set to 0 by the kernel. + */ +#include +#include "lapi/shmbuf.h" +#include "libnewipc.h" +#include "tst_test.h" +#include "tst_safe_sysv_ipc.h" + +#ifdef HAVE_SHMID64_DS_TIME_HIGH + +static void run(void) +{ + struct shmid64_ds buf_ds = { + .shm_atime_high = 0x0A0A, + .shm_dtime_high = 0x0A0A, + .shm_ctime_high = 0x0A0A, + }; + int shmid; + key_t key; + + /* get an IPC resource key */ + key = GETIPCKEY(); + + shmid = shmget(key, SHM_SIZE, IPC_CREAT | IPC_EXCL | SHM_RW); + if (shmid == -1) + tst_brk(TBROK | TERRNO, "couldn't create shared memory segment"); + + TEST(shmctl(shmid, IPC_STAT, (struct shmid_ds *)&buf_ds)); + if (TST_RET == -1) + tst_brk(TFAIL | TTERRNO, "shmctl() failed"); + + if (buf_ds.shm_atime_high || buf_ds.shm_dtime_high || buf_ds.shm_ctime_high) + tst_res(TFAIL, "time_high fields aren't cleared by the kernel"); + else + tst_res(TPASS, "time_high fields cleared by the kernel"); + + SAFE_SHMCTL(shmid, IPC_RMID, NULL); +} + +static struct tst_test test = { + .test_all = run, + .needs_tmpdir = 1, +}; +#else +TST_TEST_TCONF("test requires struct shmid64_ds to have the time_high fields"); +#endif diff --git a/pool/shard000/C/0011973_cache.c b/pool/shard000/C/0011973_cache.c new file mode 100644 index 0000000000000000000000000000000000000000..ae7bdc79bde423218f61bfd615c42efa2f2558e1 --- /dev/null +++ b/pool/shard000/C/0011973_cache.c @@ -0,0 +1,42 @@ +#include "ecef.h" +#include + +static Eet_File *favicons; + + +static void +idcb() +{ +} + +void +cache_init(void) +{ + char buf[PATH_MAX]; + + snprintf(buf, sizeof(buf), "%s/ecef", efreet_cache_home_get()); + ecore_file_mkpath(buf); + snprintf(buf, sizeof(buf), "%s/ecef/favicons.eet", efreet_cache_home_get()); + favicons = eet_open(buf, EET_FILE_MODE_READ_WRITE); +} + +Eina_Bool +cache_favicon_set(Evas_Object *img, const char *favicon) +{ + int num = 0; + free(eet_list(favicons, favicon, &num)); + if (!num) return EINA_FALSE; + return elm_image_file_set(img, eet_file_get(favicons), favicon); +} + +void +cache_favicon_add(Evas_Object *img, const char *favicon) +{ + int w, h; + void *px; + + px = evas_object_image_data_get(img, EINA_FALSE); + evas_object_image_size_get(img, &w, &h); + eet_data_image_write(favicons, favicon, px, w, h, 1, 1, 100, 0); + eio_eet_sync(favicons, idcb, idcb, NULL); +} diff --git a/pool/shard000/C/0011984_MoveWin.c b/pool/shard000/C/0011984_MoveWin.c new file mode 100644 index 0000000000000000000000000000000000000000..bd2a5a044268183c0d1e21f099ce023620f25abe --- /dev/null +++ b/pool/shard000/C/0011984_MoveWin.c @@ -0,0 +1,67 @@ +/* $Xorg: MoveWin.c,v 1.4 2001/02/09 02:03:34 xorgcvs Exp $ */ +/* + +Copyright 1986, 1998 The Open Group + +Permission to use, copy, modify, distribute, and sell this software and its +documentation for any purpose is hereby granted without fee, provided that +the above copyright notice appear in all copies and that both that +copyright notice and this permission notice appear in supporting +documentation. + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN +AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Except as contained in this notice, the name of The Open Group shall not be +used in advertising or otherwise to promote the sale, use or other dealings +in this Software without prior written authorization from The Open Group. + +*/ +/* $XFree86: xc/lib/X11/MoveWin.c,v 1.3 2001/01/17 19:41:40 dawes Exp $ */ + +#ifdef HAVE_CONFIG_H +#include +#endif +#include "Xlibint.h" + +int +XMoveWindow ( + register Display *dpy, + Window w, + int x, + int y) +{ + register xConfigureWindowReq *req; + + LockDisplay(dpy); + GetReqExtra(ConfigureWindow, 8, req); + + req->window = w; + req->mask = CWX | CWY; + +#ifdef MUSTCOPY + { + long lx = (long) x, ly = (long) y; + dpy->bufptr -= 8; + Data32 (dpy, (long *) &lx, 4); /* order dictated by CWX and CWY */ + Data32 (dpy, (long *) &ly, 4); + } +#else + { + CARD32 *valuePtr = (CARD32 *) NEXTPTR(req,xConfigureWindowReq); + *valuePtr++ = x; + *valuePtr = y; + } +#endif /* MUSTCOPY */ + UnlockDisplay(dpy); + SyncHandle(); + return 1; +} + diff --git a/pool/shard000/C/0011989_exoparg6.c b/pool/shard000/C/0011989_exoparg6.c new file mode 100644 index 0000000000000000000000000000000000000000..e414a20505f13866cb5bef4719a9aae51bd293f0 --- /dev/null +++ b/pool/shard000/C/0011989_exoparg6.c @@ -0,0 +1,465 @@ +/****************************************************************************** + * + * Module Name: exoparg6 - AML execution - opcodes with 6 arguments + * + *****************************************************************************/ + +/****************************************************************************** + * + * 1. Copyright Notice + * + * Some or all of this work - Copyright (c) 1999 - 2017, Intel Corp. + * All rights reserved. + * + * 2. License + * + * 2.1. This is your license from Intel Corp. under its intellectual property + * rights. You may have additional license terms from the party that provided + * you this software, covering your right to use that party's intellectual + * property rights. + * + * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a + * copy of the source code appearing in this file ("Covered Code") an + * irrevocable, perpetual, worldwide license under Intel's copyrights in the + * base code distributed originally by Intel ("Original Intel Code") to copy, + * make derivatives, distribute, use and display any portion of the Covered + * Code in any form, with the right to sublicense such rights; and + * + * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent + * license (with the right to sublicense), under only those claims of Intel + * patents that are infringed by the Original Intel Code, to make, use, sell, + * offer to sell, and import the Covered Code and derivative works thereof + * solely to the minimum extent necessary to exercise the above copyright + * license, and in no event shall the patent license extend to any additions + * to or modifications of the Original Intel Code. No other license or right + * is granted directly or by implication, estoppel or otherwise; + * + * The above copyright and patent license is granted only if the following + * conditions are met: + * + * 3. Conditions + * + * 3.1. Redistribution of Source with Rights to Further Distribute Source. + * Redistribution of source code of any substantial portion of the Covered + * Code or modification with rights to further distribute source must include + * the above Copyright Notice, the above License, this list of Conditions, + * and the following Disclaimer and Export Compliance provision. In addition, + * Licensee must cause all Covered Code to which Licensee contributes to + * contain a file documenting the changes Licensee made to create that Covered + * Code and the date of any change. Licensee must include in that file the + * documentation of any changes made by any predecessor Licensee. Licensee + * must include a prominent statement that the modification is derived, + * directly or indirectly, from Original Intel Code. + * + * 3.2. Redistribution of Source with no Rights to Further Distribute Source. + * Redistribution of source code of any substantial portion of the Covered + * Code or modification without rights to further distribute source must + * include the following Disclaimer and Export Compliance provision in the + * documentation and/or other materials provided with distribution. In + * addition, Licensee may not authorize further sublicense of source of any + * portion of the Covered Code, and must include terms to the effect that the + * license from Licensee to its licensee is limited to the intellectual + * property embodied in the software Licensee provides to its licensee, and + * not to intellectual property embodied in modifications its licensee may + * make. + * + * 3.3. Redistribution of Executable. Redistribution in executable form of any + * substantial portion of the Covered Code or modification must reproduce the + * above Copyright Notice, and the following Disclaimer and Export Compliance + * provision in the documentation and/or other materials provided with the + * distribution. + * + * 3.4. Intel retains all right, title, and interest in and to the Original + * Intel Code. + * + * 3.5. Neither the name Intel nor any other trademark owned or controlled by + * Intel shall be used in advertising or otherwise to promote the sale, use or + * other dealings in products derived from or relating to the Covered Code + * without prior written authorization from Intel. + * + * 4. Disclaimer and Export Compliance + * + * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED + * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE + * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, + * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY + + * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY + * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A + * PARTICULAR PURPOSE. + * + * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES + * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR + * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, + * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY + * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL + * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS + * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY + * LIMITED REMEDY. + * + * 4.3. Licensee shall not export, either directly or indirectly, any of this + * software or system incorporating such software without first obtaining any + * required license or other approval from the U. S. Department of Commerce or + * any other agency or department of the United States Government. In the + * event Licensee exports any such software from the United States or + * re-exports any such software from a foreign destination, Licensee shall + * ensure that the distribution and export/re-export of the software is in + * compliance with all laws, regulations, orders, or other restrictions of the + * U.S. Export Administration Regulations. Licensee agrees that neither it nor + * any of its subsidiaries will export/re-export any technical data, process, + * software, or service, directly or indirectly, to any country for which the + * United States government or any agency thereof requires an export license, + * other governmental approval, or letter of assurance, without first obtaining + * such license, approval or letter. + * + ***************************************************************************** + * + * Alternatively, you may choose to be licensed under the terms of the + * following license: + * + * 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, + * without modification. + * 2. Redistributions in binary form must reproduce at minimum a disclaimer + * substantially similar to the "NO WARRANTY" disclaimer below + * ("Disclaimer") and any redistribution must be conditioned upon + * including a substantially similar Disclaimer requirement for further + * binary redistribution. + * 3. Neither the names of the above-listed copyright holders nor the names + * of any contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * Alternatively, you may choose to be licensed under the terms of the + * GNU General Public License ("GPL") version 2 as published by the Free + * Software Foundation. + * + *****************************************************************************/ + +#include "acpi.h" +#include "accommon.h" +#include "acinterp.h" +#include "acparser.h" +#include "amlcode.h" + + +#define _COMPONENT ACPI_EXECUTER + ACPI_MODULE_NAME ("exoparg6") + + +/*! + * Naming convention for AML interpreter execution routines. + * + * The routines that begin execution of AML opcodes are named with a common + * convention based upon the number of arguments, the number of target operands, + * and whether or not a value is returned: + * + * AcpiExOpcode_xA_yT_zR + * + * Where: + * + * xA - ARGUMENTS: The number of arguments (input operands) that are + * required for this opcode type (1 through 6 args). + * yT - TARGETS: The number of targets (output operands) that are required + * for this opcode type (0, 1, or 2 targets). + * zR - RETURN VALUE: Indicates whether this opcode type returns a value + * as the function return (0 or 1). + * + * The AcpiExOpcode* functions are called via the Dispatcher component with + * fully resolved operands. +!*/ + +/* Local prototypes */ + +static BOOLEAN +AcpiExDoMatch ( + UINT32 MatchOp, + ACPI_OPERAND_OBJECT *PackageObj, + ACPI_OPERAND_OBJECT *MatchObj); + + +/******************************************************************************* + * + * FUNCTION: AcpiExDoMatch + * + * PARAMETERS: MatchOp - The AML match operand + * PackageObj - Object from the target package + * MatchObj - Object to be matched + * + * RETURN: TRUE if the match is successful, FALSE otherwise + * + * DESCRIPTION: Implements the low-level match for the ASL Match operator. + * Package elements will be implicitly converted to the type of + * the match object (Integer/Buffer/String). + * + ******************************************************************************/ + +static BOOLEAN +AcpiExDoMatch ( + UINT32 MatchOp, + ACPI_OPERAND_OBJECT *PackageObj, + ACPI_OPERAND_OBJECT *MatchObj) +{ + BOOLEAN LogicalResult = TRUE; + ACPI_STATUS Status; + + + /* + * Note: Since the PackageObj/MatchObj ordering is opposite to that of + * the standard logical operators, we have to reverse them when we call + * DoLogicalOp in order to make the implicit conversion rules work + * correctly. However, this means we have to flip the entire equation + * also. A bit ugly perhaps, but overall, better than fussing the + * parameters around at runtime, over and over again. + * + * Below, P[i] refers to the package element, M refers to the Match object. + */ + switch (MatchOp) + { + case MATCH_MTR: + + /* Always true */ + + break; + + case MATCH_MEQ: + /* + * True if equal: (P[i] == M) + * Change to: (M == P[i]) + */ + Status = AcpiExDoLogicalOp ( + AML_LOGICAL_EQUAL_OP, MatchObj, PackageObj, &LogicalResult); + if (ACPI_FAILURE (Status)) + { + return (FALSE); + } + break; + + case MATCH_MLE: + /* + * True if less than or equal: (P[i] <= M) (P[i] NotGreater than M) + * Change to: (M >= P[i]) (M NotLess than P[i]) + */ + Status = AcpiExDoLogicalOp ( + AML_LOGICAL_LESS_OP, MatchObj, PackageObj, &LogicalResult); + if (ACPI_FAILURE (Status)) + { + return (FALSE); + } + LogicalResult = (BOOLEAN) !LogicalResult; + break; + + case MATCH_MLT: + /* + * True if less than: (P[i] < M) + * Change to: (M > P[i]) + */ + Status = AcpiExDoLogicalOp ( + AML_LOGICAL_GREATER_OP, MatchObj, PackageObj, &LogicalResult); + if (ACPI_FAILURE (Status)) + { + return (FALSE); + } + break; + + case MATCH_MGE: + /* + * True if greater than or equal: (P[i] >= M) (P[i] NotLess than M) + * Change to: (M <= P[i]) (M NotGreater than P[i]) + */ + Status = AcpiExDoLogicalOp ( + AML_LOGICAL_GREATER_OP, MatchObj, PackageObj, &LogicalResult); + if (ACPI_FAILURE (Status)) + { + return (FALSE); + } + LogicalResult = (BOOLEAN)!LogicalResult; + break; + + case MATCH_MGT: + /* + * True if greater than: (P[i] > M) + * Change to: (M < P[i]) + */ + Status = AcpiExDoLogicalOp ( + AML_LOGICAL_LESS_OP, MatchObj, PackageObj, &LogicalResult); + if (ACPI_FAILURE (Status)) + { + return (FALSE); + } + break; + + default: + + /* Undefined */ + + return (FALSE); + } + + return (LogicalResult); +} + + +/******************************************************************************* + * + * FUNCTION: AcpiExOpcode_6A_0T_1R + * + * PARAMETERS: WalkState - Current walk state + * + * RETURN: Status + * + * DESCRIPTION: Execute opcode with 6 arguments, no target, and a return value + * + ******************************************************************************/ + +ACPI_STATUS +AcpiExOpcode_6A_0T_1R ( + ACPI_WALK_STATE *WalkState) +{ + ACPI_OPERAND_OBJECT **Operand = &WalkState->Operands[0]; + ACPI_OPERAND_OBJECT *ReturnDesc = NULL; + ACPI_STATUS Status = AE_OK; + UINT64 Index; + ACPI_OPERAND_OBJECT *ThisElement; + + + ACPI_FUNCTION_TRACE_STR (ExOpcode_6A_0T_1R, + AcpiPsGetOpcodeName (WalkState->Opcode)); + + + switch (WalkState->Opcode) + { + case AML_MATCH_OP: + /* + * Match (SearchPkg[0], MatchOp1[1], MatchObj1[2], + * MatchOp2[3], MatchObj2[4], StartIndex[5]) + */ + + /* Validate both Match Term Operators (MTR, MEQ, etc.) */ + + if ((Operand[1]->Integer.Value > MAX_MATCH_OPERATOR) || + (Operand[3]->Integer.Value > MAX_MATCH_OPERATOR)) + { + ACPI_ERROR ((AE_INFO, "Match operator out of range")); + Status = AE_AML_OPERAND_VALUE; + goto Cleanup; + } + + /* Get the package StartIndex, validate against the package length */ + + Index = Operand[5]->Integer.Value; + if (Index >= Operand[0]->Package.Count) + { + ACPI_ERROR ((AE_INFO, + "Index (0x%8.8X%8.8X) beyond package end (0x%X)", + ACPI_FORMAT_UINT64 (Index), Operand[0]->Package.Count)); + Status = AE_AML_PACKAGE_LIMIT; + goto Cleanup; + } + + /* Create an integer for the return value */ + /* Default return value is ACPI_UINT64_MAX if no match found */ + + ReturnDesc = AcpiUtCreateIntegerObject (ACPI_UINT64_MAX); + if (!ReturnDesc) + { + Status = AE_NO_MEMORY; + goto Cleanup; + + } + + /* + * Examine each element until a match is found. Both match conditions + * must be satisfied for a match to occur. Within the loop, + * "continue" signifies that the current element does not match + * and the next should be examined. + * + * Upon finding a match, the loop will terminate via "break" at + * the bottom. If it terminates "normally", MatchValue will be + * ACPI_UINT64_MAX (Ones) (its initial value) indicating that no + * match was found. + */ + for ( ; Index < Operand[0]->Package.Count; Index++) + { + /* Get the current package element */ + + ThisElement = Operand[0]->Package.Elements[Index]; + + /* Treat any uninitialized (NULL) elements as non-matching */ + + if (!ThisElement) + { + continue; + } + + /* + * Both match conditions must be satisfied. Execution of a continue + * (proceed to next iteration of enclosing for loop) signifies a + * non-match. + */ + if (!AcpiExDoMatch ((UINT32) Operand[1]->Integer.Value, + ThisElement, Operand[2])) + { + continue; + } + + if (!AcpiExDoMatch ((UINT32) Operand[3]->Integer.Value, + ThisElement, Operand[4])) + { + continue; + } + + /* Match found: Index is the return value */ + + ReturnDesc->Integer.Value = Index; + break; + } + break; + + case AML_LOAD_TABLE_OP: + + Status = AcpiExLoadTableOp (WalkState, &ReturnDesc); + break; + + default: + + ACPI_ERROR ((AE_INFO, "Unknown AML opcode 0x%X", + WalkState->Opcode)); + + Status = AE_AML_BAD_OPCODE; + goto Cleanup; + } + + +Cleanup: + + /* Delete return object on error */ + + if (ACPI_FAILURE (Status)) + { + AcpiUtRemoveReference (ReturnDesc); + } + + /* Save return object on success */ + + else + { + WalkState->ResultObj = ReturnDesc; + } + + return_ACPI_STATUS (Status); +} diff --git a/pool/shard000/C/0012007_semi_restrict.c b/pool/shard000/C/0012007_semi_restrict.c new file mode 100644 index 0000000000000000000000000000000000000000..85e6a2145c4025660776bd978e4fa55ecbaeb8b9 --- /dev/null +++ b/pool/shard000/C/0012007_semi_restrict.c @@ -0,0 +1,301 @@ +/*BHEADER********************************************************************** + * (c) 2000 The Regents of the University of California + * + * See the file COPYRIGHT_and_DISCLAIMER for a complete copyright + * notice, contact person, and disclaimer. + * + * $Revision: 1.1.1.1 $ + *********************************************************************EHEADER*/ +/****************************************************************************** + * + * + *****************************************************************************/ + +#include "headers.h" + +/*-------------------------------------------------------------------------- + * hypre_SemiRestrictData data structure + *--------------------------------------------------------------------------*/ + +typedef struct +{ + hypre_StructMatrix *R; + int R_stored_as_transpose; + hypre_ComputePkg *compute_pkg; + hypre_Index cindex; + hypre_Index stride; + + int time_index; + +} hypre_SemiRestrictData; + +/*-------------------------------------------------------------------------- + * hypre_SemiRestrictCreate + *--------------------------------------------------------------------------*/ + +void * +hypre_SemiRestrictCreate( ) +{ + hypre_SemiRestrictData *restrict_data; + + restrict_data = hypre_CTAlloc(hypre_SemiRestrictData, 1); + + (restrict_data -> time_index) = hypre_InitializeTiming("SemiRestrict"); + + return (void *) restrict_data; +} + +/*-------------------------------------------------------------------------- + * hypre_SemiRestrictSetup + *--------------------------------------------------------------------------*/ + +int +hypre_SemiRestrictSetup( void *restrict_vdata, + hypre_StructMatrix *R, + int R_stored_as_transpose, + hypre_StructVector *r, + hypre_StructVector *rc, + hypre_Index cindex, + hypre_Index findex, + hypre_Index stride ) +{ + hypre_SemiRestrictData *restrict_data = (hypre_SemiRestrictData *)restrict_vdata; + + hypre_StructGrid *grid; + hypre_StructStencil *stencil; + + hypre_BoxArrayArray *send_boxes; + hypre_BoxArrayArray *recv_boxes; + int **send_processes; + int **recv_processes; + hypre_BoxArrayArray *indt_boxes; + hypre_BoxArrayArray *dept_boxes; + + hypre_ComputePkg *compute_pkg; + + int ierr = 0; + + /*---------------------------------------------------------- + * Set up the compute package + *----------------------------------------------------------*/ + + grid = hypre_StructVectorGrid(r); + stencil = hypre_StructMatrixStencil(R); + + hypre_CreateComputeInfo(grid, stencil, + &send_boxes, &recv_boxes, + &send_processes, &recv_processes, + &indt_boxes, &dept_boxes); + + hypre_ProjectBoxArrayArray(send_boxes, findex, stride); + hypre_ProjectBoxArrayArray(recv_boxes, findex, stride); + hypre_ProjectBoxArrayArray(indt_boxes, cindex, stride); + hypre_ProjectBoxArrayArray(dept_boxes, cindex, stride); + + hypre_ComputePkgCreate(send_boxes, recv_boxes, + stride, stride, + send_processes, recv_processes, + indt_boxes, dept_boxes, + stride, grid, + hypre_StructVectorDataSpace(r), 1, + &compute_pkg); + + /*---------------------------------------------------------- + * Set up the restrict data structure + *----------------------------------------------------------*/ + + (restrict_data -> R) = hypre_StructMatrixRef(R); + (restrict_data -> R_stored_as_transpose) = R_stored_as_transpose; + (restrict_data -> compute_pkg) = compute_pkg; + hypre_CopyIndex(cindex ,(restrict_data -> cindex)); + hypre_CopyIndex(stride ,(restrict_data -> stride)); + + return ierr; +} + +/*-------------------------------------------------------------------------- + * hypre_SemiRestrict: + *--------------------------------------------------------------------------*/ + +int +hypre_SemiRestrict( void *restrict_vdata, + hypre_StructMatrix *R, + hypre_StructVector *r, + hypre_StructVector *rc ) +{ + int ierr = 0; + + hypre_SemiRestrictData *restrict_data = (hypre_SemiRestrictData *)restrict_vdata; + + int R_stored_as_transpose; + hypre_ComputePkg *compute_pkg; + hypre_IndexRef cindex; + hypre_IndexRef stride; + + hypre_StructGrid *fgrid; + int *fgrid_ids; + hypre_StructGrid *cgrid; + hypre_BoxArray *cgrid_boxes; + int *cgrid_ids; + + hypre_CommHandle *comm_handle; + + hypre_BoxArrayArray *compute_box_aa; + hypre_BoxArray *compute_box_a; + hypre_Box *compute_box; + + hypre_Box *R_dbox; + hypre_Box *r_dbox; + hypre_Box *rc_dbox; + + int Ri; + int ri; + int rci; + + double *Rp0, *Rp1; + double *rp, *rp0, *rp1; + double *rcp; + + hypre_Index loop_size; + hypre_IndexRef start; + hypre_Index startc; + hypre_Index stridec; + + hypre_StructStencil *stencil; + hypre_Index *stencil_shape; + + int compute_i, fi, ci, j; + int loopi, loopj, loopk; + + /*----------------------------------------------------------------------- + * Initialize some things. + *-----------------------------------------------------------------------*/ + + hypre_BeginTiming(restrict_data -> time_index); + + R_stored_as_transpose = (restrict_data -> R_stored_as_transpose); + compute_pkg = (restrict_data -> compute_pkg); + cindex = (restrict_data -> cindex); + stride = (restrict_data -> stride); + + stencil = hypre_StructMatrixStencil(R); + stencil_shape = hypre_StructStencilShape(stencil); + + hypre_SetIndex(stridec, 1, 1, 1); + + /*-------------------------------------------------------------------- + * Restrict the residual. + *--------------------------------------------------------------------*/ + + fgrid = hypre_StructVectorGrid(r); + fgrid_ids = hypre_StructGridIDs(fgrid); + cgrid = hypre_StructVectorGrid(rc); + cgrid_boxes = hypre_StructGridBoxes(cgrid); + cgrid_ids = hypre_StructGridIDs(cgrid); + + for (compute_i = 0; compute_i < 2; compute_i++) + { + switch(compute_i) + { + case 0: + { + rp = hypre_StructVectorData(r); + hypre_InitializeIndtComputations(compute_pkg, rp, &comm_handle); + compute_box_aa = hypre_ComputePkgIndtBoxes(compute_pkg); + } + break; + + case 1: + { + hypre_FinalizeIndtComputations(comm_handle); + compute_box_aa = hypre_ComputePkgDeptBoxes(compute_pkg); + } + break; + } + + fi = 0; + hypre_ForBoxArrayI(ci, cgrid_boxes) + { + while (fgrid_ids[fi] != cgrid_ids[ci]) + { + fi++; + } + + compute_box_a = hypre_BoxArrayArrayBoxArray(compute_box_aa, fi); + + R_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(R), fi); + r_dbox = hypre_BoxArrayBox(hypre_StructVectorDataSpace(r), fi); + rc_dbox = hypre_BoxArrayBox(hypre_StructVectorDataSpace(rc), ci); + + if (R_stored_as_transpose) + { + Rp0 = hypre_StructMatrixBoxData(R, fi, 1) - + hypre_BoxOffsetDistance(R_dbox, stencil_shape[1]); + Rp1 = hypre_StructMatrixBoxData(R, fi, 0); + } + else + { + Rp0 = hypre_StructMatrixBoxData(R, fi, 0); + Rp1 = hypre_StructMatrixBoxData(R, fi, 1); + } + rp = hypre_StructVectorBoxData(r, fi); + rp0 = rp + hypre_BoxOffsetDistance(r_dbox, stencil_shape[0]); + rp1 = rp + hypre_BoxOffsetDistance(r_dbox, stencil_shape[1]); + rcp = hypre_StructVectorBoxData(rc, ci); + + hypre_ForBoxI(j, compute_box_a) + { + compute_box = hypre_BoxArrayBox(compute_box_a, j); + + start = hypre_BoxIMin(compute_box); + hypre_StructMapFineToCoarse(start, cindex, stride, startc); + + hypre_BoxGetStrideSize(compute_box, stride, loop_size); + hypre_BoxLoop3Begin(loop_size, + R_dbox, startc, stridec, Ri, + r_dbox, start, stride, ri, + rc_dbox, startc, stridec, rci); +#define HYPRE_BOX_SMP_PRIVATE loopk,loopi,loopj,Ri,ri,rci +#include "hypre_box_smp_forloop.h" + hypre_BoxLoop3For(loopi, loopj, loopk, Ri, ri, rci) + { + rcp[rci] = rp[ri] + (Rp0[Ri] * rp0[ri] + + Rp1[Ri] * rp1[ri]); + } + hypre_BoxLoop3End(Ri, ri, rci); + } + } + } + + /*----------------------------------------------------------------------- + * Return + *-----------------------------------------------------------------------*/ + + hypre_IncFLOPCount(4*hypre_StructVectorGlobalSize(rc)); + hypre_EndTiming(restrict_data -> time_index); + + return ierr; +} + +/*-------------------------------------------------------------------------- + * hypre_SemiRestrictDestroy + *--------------------------------------------------------------------------*/ + +int +hypre_SemiRestrictDestroy( void *restrict_vdata ) +{ + int ierr = 0; + + hypre_SemiRestrictData *restrict_data = (hypre_SemiRestrictData *)restrict_vdata; + + if (restrict_data) + { + hypre_StructMatrixDestroy(restrict_data -> R); + hypre_ComputePkgDestroy(restrict_data -> compute_pkg); + hypre_FinalizeTiming(restrict_data -> time_index); + hypre_TFree(restrict_data); + } + + return ierr; +} + diff --git a/pool/shard000/C/0012017_main.c b/pool/shard000/C/0012017_main.c new file mode 100644 index 0000000000000000000000000000000000000000..5f84a70afde65efaaec6fc0a59045acd6dea7528 --- /dev/null +++ b/pool/shard000/C/0012017_main.c @@ -0,0 +1,42 @@ +#include +#include +#include + + +#include "random.h" +#include "introduction.h" +#include "pointPhase.h" + +int main(int argc, char *argv[]) +{ + int dice1,dice2,sum; + char initiate; + + introduction(); + + printf("Press \"r\" to Roll the dice (q = Quit)\n"); + scanf("%s", &initiate); + + while (initiate != 'q'){ + dice1 = getRand(1,6); + printf("Dice 1: %d\n",dice1); + dice2 = getRand(1,6); + printf("Dice 2: %d\n",dice2); + + sum = dice1+dice2; + printf("Your roll sum is: %d\n\n",sum); + if (sum == 7 || sum == 11){ + printf("CONGRATS you win!!! \n");} + else if (sum == 2 || sum == 3 || sum == 12){ + printf("SORRY you lost\n");} + else{ + pointPhase(sum,dice1,dice2); + } + printf("Play Again? (r = Roll q = Quit)\n"); + scanf("%s",&initiate); + } + printf("Thank You for playing \n\n"); + + system("PAUSE"); + return 0; +} diff --git a/pool/shard000/C/0012021_psp_v11_0_8.c b/pool/shard000/C/0012021_psp_v11_0_8.c new file mode 100644 index 0000000000000000000000000000000000000000..ff13e1beb49b0361eec4a95e05875a0c42e5499e --- /dev/null +++ b/pool/shard000/C/0012021_psp_v11_0_8.c @@ -0,0 +1,208 @@ +/* + * Copyright 2021 Advanced Micro Devices, Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + */ +#include "amdgpu.h" +#include "amdgpu_psp.h" +#include "amdgpu_ucode.h" +#include "soc15_common.h" +#include "psp_v11_0_8.h" + +#include "mp/mp_11_0_8_offset.h" + +static int psp_v11_0_8_ring_init(struct psp_context *psp, + enum psp_ring_type ring_type) +{ + int ret = 0; + struct psp_ring *ring; + struct amdgpu_device *adev = psp->adev; + + ring = &psp->km_ring; + + ring->ring_type = ring_type; + + /* allocate 4k Page of Local Frame Buffer memory for ring */ + ring->ring_size = 0x1000; + ret = amdgpu_bo_create_kernel(adev, ring->ring_size, PAGE_SIZE, + AMDGPU_GEM_DOMAIN_VRAM, + &adev->firmware.rbuf, + &ring->ring_mem_mc_addr, + (void **)&ring->ring_mem); + if (ret) { + ring->ring_size = 0; + return ret; + } + + return 0; +} + +static int psp_v11_0_8_ring_stop(struct psp_context *psp, + enum psp_ring_type ring_type) +{ + int ret = 0; + struct amdgpu_device *adev = psp->adev; + + if (amdgpu_sriov_vf(adev)) { + /* Write the ring destroy command*/ + WREG32_SOC15(MP0, 0, mmMP0_SMN_C2PMSG_101, + GFX_CTRL_CMD_ID_DESTROY_GPCOM_RING); + /* there might be handshake issue with hardware which needs delay */ + mdelay(20); + /* Wait for response flag (bit 31) */ + ret = psp_wait_for(psp, SOC15_REG_OFFSET(MP0, 0, mmMP0_SMN_C2PMSG_101), + 0x80000000, 0x80000000, false); + } else { + /* Write the ring destroy command*/ + WREG32_SOC15(MP0, 0, mmMP0_SMN_C2PMSG_64, + GFX_CTRL_CMD_ID_DESTROY_RINGS); + /* there might be handshake issue with hardware which needs delay */ + mdelay(20); + /* Wait for response flag (bit 31) */ + ret = psp_wait_for(psp, SOC15_REG_OFFSET(MP0, 0, mmMP0_SMN_C2PMSG_64), + 0x80000000, 0x80000000, false); + } + + return ret; +} + +static int psp_v11_0_8_ring_create(struct psp_context *psp, + enum psp_ring_type ring_type) +{ + int ret = 0; + unsigned int psp_ring_reg = 0; + struct psp_ring *ring = &psp->km_ring; + struct amdgpu_device *adev = psp->adev; + + if (amdgpu_sriov_vf(adev)) { + ret = psp_v11_0_8_ring_stop(psp, ring_type); + if (ret) { + DRM_ERROR("psp_v11_0_8_ring_stop_sriov failed!\n"); + return ret; + } + + /* Write low address of the ring to C2PMSG_102 */ + psp_ring_reg = lower_32_bits(ring->ring_mem_mc_addr); + WREG32_SOC15(MP0, 0, mmMP0_SMN_C2PMSG_102, psp_ring_reg); + /* Write high address of the ring to C2PMSG_103 */ + psp_ring_reg = upper_32_bits(ring->ring_mem_mc_addr); + WREG32_SOC15(MP0, 0, mmMP0_SMN_C2PMSG_103, psp_ring_reg); + + /* Write the ring initialization command to C2PMSG_101 */ + WREG32_SOC15(MP0, 0, mmMP0_SMN_C2PMSG_101, + GFX_CTRL_CMD_ID_INIT_GPCOM_RING); + + /* there might be handshake issue with hardware which needs delay */ + mdelay(20); + + /* Wait for response flag (bit 31) in C2PMSG_101 */ + ret = psp_wait_for(psp, SOC15_REG_OFFSET(MP0, 0, mmMP0_SMN_C2PMSG_101), + 0x80000000, 0x8000FFFF, false); + + } else { + /* Wait for sOS ready for ring creation */ + ret = psp_wait_for(psp, SOC15_REG_OFFSET(MP0, 0, mmMP0_SMN_C2PMSG_64), + 0x80000000, 0x80000000, false); + if (ret) { + DRM_ERROR("Failed to wait for trust OS ready for ring creation\n"); + return ret; + } + + /* Write low address of the ring to C2PMSG_69 */ + psp_ring_reg = lower_32_bits(ring->ring_mem_mc_addr); + WREG32_SOC15(MP0, 0, mmMP0_SMN_C2PMSG_69, psp_ring_reg); + /* Write high address of the ring to C2PMSG_70 */ + psp_ring_reg = upper_32_bits(ring->ring_mem_mc_addr); + WREG32_SOC15(MP0, 0, mmMP0_SMN_C2PMSG_70, psp_ring_reg); + /* Write size of ring to C2PMSG_71 */ + psp_ring_reg = ring->ring_size; + WREG32_SOC15(MP0, 0, mmMP0_SMN_C2PMSG_71, psp_ring_reg); + /* Write the ring initialization command to C2PMSG_64 */ + psp_ring_reg = ring_type; + psp_ring_reg = psp_ring_reg << 16; + WREG32_SOC15(MP0, 0, mmMP0_SMN_C2PMSG_64, psp_ring_reg); + + /* there might be handshake issue with hardware which needs delay */ + mdelay(20); + + /* Wait for response flag (bit 31) in C2PMSG_64 */ + ret = psp_wait_for(psp, SOC15_REG_OFFSET(MP0, 0, mmMP0_SMN_C2PMSG_64), + 0x80000000, 0x8000FFFF, false); + } + + return ret; +} + +static int psp_v11_0_8_ring_destroy(struct psp_context *psp, + enum psp_ring_type ring_type) +{ + int ret = 0; + struct psp_ring *ring = &psp->km_ring; + struct amdgpu_device *adev = psp->adev; + + ret = psp_v11_0_8_ring_stop(psp, ring_type); + if (ret) + DRM_ERROR("Fail to stop psp ring\n"); + + amdgpu_bo_free_kernel(&adev->firmware.rbuf, + &ring->ring_mem_mc_addr, + (void **)&ring->ring_mem); + + return ret; +} + +static uint32_t psp_v11_0_8_ring_get_wptr(struct psp_context *psp) +{ + uint32_t data; + struct amdgpu_device *adev = psp->adev; + + if (amdgpu_sriov_vf(adev)) + data = RREG32_SOC15(MP0, 0, mmMP0_SMN_C2PMSG_102); + else + data = RREG32_SOC15(MP0, 0, mmMP0_SMN_C2PMSG_67); + + return data; +} + +static void psp_v11_0_8_ring_set_wptr(struct psp_context *psp, uint32_t value) +{ + struct amdgpu_device *adev = psp->adev; + + if (amdgpu_sriov_vf(adev)) { + WREG32_SOC15(MP0, 0, mmMP0_SMN_C2PMSG_102, value); + WREG32_SOC15(MP0, 0, mmMP0_SMN_C2PMSG_101, + GFX_CTRL_CMD_ID_CONSUME_CMD); + } else + WREG32_SOC15(MP0, 0, mmMP0_SMN_C2PMSG_67, value); +} + +static const struct psp_funcs psp_v11_0_8_funcs = { + .ring_init = psp_v11_0_8_ring_init, + .ring_create = psp_v11_0_8_ring_create, + .ring_stop = psp_v11_0_8_ring_stop, + .ring_destroy = psp_v11_0_8_ring_destroy, + .ring_get_wptr = psp_v11_0_8_ring_get_wptr, + .ring_set_wptr = psp_v11_0_8_ring_set_wptr, +}; + +void psp_v11_0_8_set_psp_funcs(struct psp_context *psp) +{ + psp->funcs = &psp_v11_0_8_funcs; +} diff --git a/pool/shard000/C/0012023_inc_register_callback.c b/pool/shard000/C/0012023_inc_register_callback.c new file mode 100644 index 0000000000000000000000000000000000000000..37ee76055333552ef47b5bd0e3f2e659dcad30b9 --- /dev/null +++ b/pool/shard000/C/0012023_inc_register_callback.c @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2004-2010 The Trustees of Indiana University and Indiana + * University Research and Technology + * Corporation. All rights reserved. + * Copyright (c) 2012 Cisco Systems, Inc. All rights reserved. + * $COPYRIGHT$ + * + * Additional copyrights may follow + * + * $HEADER$ + */ +#include "ompi_config.h" +#include + +#include "ompi/mpi/c/bindings.h" +#include "opal/runtime/opal_cr.h" +#include "ompi/mpiext/cr/c/mpiext_cr_c.h" + +#include "ompi/runtime/params.h" +#include "ompi/communicator/communicator.h" +#include "ompi/errhandler/errhandler.h" + +static const char FUNC_NAME[] = "OMPI_CR_INC_register_callback"; + +int OMPI_CR_INC_register_callback(OMPI_CR_INC_callback_event_t event, + OMPI_CR_INC_callback_function function, + OMPI_CR_INC_callback_function *prev_function) +{ + int rc; + + if ( MPI_PARAM_CHECK ) { + OMPI_ERR_INIT_FINALIZE(FUNC_NAME); + } + + OPAL_CR_ENTER_LIBRARY(); + + rc = opal_cr_user_inc_register_callback(event, function, prev_function); + + OMPI_ERRHANDLER_RETURN(rc, MPI_COMM_WORLD, rc, FUNC_NAME); +} diff --git a/pool/shard000/C/0012024_unlinkat.c b/pool/shard000/C/0012024_unlinkat.c new file mode 100644 index 0000000000000000000000000000000000000000..fff8310eea7d5e6faa65f866113f1ebedb45014b --- /dev/null +++ b/pool/shard000/C/0012024_unlinkat.c @@ -0,0 +1,109 @@ +/* Work around unlinkat bugs on Solaris 9 and Hurd. + + Copyright (C) 2009-2014 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 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 + along with this program. If not, see . */ + +/* Written by Eric Blake. */ + +#include + +#include + +#include +#include +#include +#include + +#include + +#include "dosname.h" +#include "openat.h" + +#if HAVE_UNLINKAT + +# undef unlinkat + +/* unlinkat without AT_REMOVEDIR does not honor trailing / on Solaris + 9. Solve it in a similar manner to unlink. Hurd has the same + issue. */ + +int +rpl_unlinkat (int fd, char const *name, int flag) +{ + size_t len; + int result = 0; + /* rmdir behavior has no problems with trailing slash. */ + if (flag & AT_REMOVEDIR) + return unlinkat (fd, name, flag); + + len = strlen (name); + if (len && ISSLASH (name[len - 1])) + { + /* See the lengthy comment in unlink.c why we disobey the POSIX + rule of letting unlink("link-to-dir/") attempt to unlink a + directory. */ + struct stat st; + result = lstatat (fd, name, &st); + if (result == 0) + { + /* Trailing NUL will overwrite the trailing slash. */ + char *short_name = malloc (len); + if (!short_name) + { + errno = EPERM; + return -1; + } + memcpy (short_name, name, len); + while (len && ISSLASH (short_name[len - 1])) + short_name[--len] = '\0'; + if (len && (lstatat (fd, short_name, &st) || S_ISLNK (st.st_mode))) + { + free (short_name); + errno = EPERM; + return -1; + } + free (short_name); + } + } + if (!result) + result = unlinkat (fd, name, flag); + return result; +} + +#else /* !HAVE_UNLINKAT */ + +/* Replacement for Solaris' function by the same name. + + First, try to simulate it via (unlink|rmdir) ("/proc/self/fd/FD/FILE"). + Failing that, simulate it via save_cwd/fchdir/(unlink|rmdir)/restore_cwd. + If either the save_cwd or the restore_cwd fails (relatively unlikely), + then give a diagnostic and exit nonzero. + Otherwise, this function works just like Solaris' unlinkat. */ + +# define AT_FUNC_NAME unlinkat +# define AT_FUNC_F1 rmdir +# define AT_FUNC_F2 unlink +# define AT_FUNC_USE_F1_COND AT_REMOVEDIR +# define AT_FUNC_POST_FILE_PARAM_DECLS , int flag +# define AT_FUNC_POST_FILE_ARGS /* empty */ +# include "at-func.c" +# undef AT_FUNC_NAME +# undef AT_FUNC_F1 +# undef AT_FUNC_F2 +# undef AT_FUNC_USE_F1_COND +# undef AT_FUNC_POST_FILE_PARAM_DECLS +# undef AT_FUNC_POST_FILE_ARGS + +#endif /* !HAVE_UNLINKAT */ diff --git a/pool/shard000/C/0012029_browser_history.c b/pool/shard000/C/0012029_browser_history.c new file mode 100644 index 0000000000000000000000000000000000000000..49683388ac7b137c444ff34c21cc350fa46b829a --- /dev/null +++ b/pool/shard000/C/0012029_browser_history.c @@ -0,0 +1,122 @@ +/** + * @file browser_history.c managing the internal browser history + * + * Copyright (C) 2012-2016 Lars Windolf + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include "browser_history.h" + +browserHistory * +browser_history_new (void) +{ + return g_new0 (browserHistory, 1); +} + +static void +browser_history_clear (browserHistory *history) +{ + GList *iter; + + iter = history->locations; + while (iter) { + g_free (iter->data); + iter = g_list_next (iter); + } + g_list_free (history->locations); + + history->locations = NULL; + history->current = NULL; +} + +void +browser_history_free (browserHistory *history) +{ + g_return_if_fail (NULL != history); + browser_history_clear (history); + g_free (history); +} + +gchar * +browser_history_forward (browserHistory *history) +{ + GList *url = history->current; + + url = g_list_next (url); + history->current = url; + + return url->data; +} + +gchar * +browser_history_back (browserHistory *history) +{ + GList *url = history->current; + + url = g_list_previous (url); + + if (url) { + history->current = url; + return url->data; + } else { + /* This happens if we go back to the headline */ + g_assert (history->headline); + browser_history_clear (history); + return NULL; + } +} + +gboolean +browser_history_can_go_forward (browserHistory *history) +{ + return (NULL != g_list_next (history->current)); +} + +gboolean +browser_history_can_go_back (browserHistory *history) +{ + return (NULL != g_list_previous (history->current)) || history->headline; +} + +void +browser_history_add_location (browserHistory *history, const gchar *url) +{ + GList *iter; + + /* Do not add the same URL twice in a row... */ + if (history->current && + g_str_equal (history->current->data, url)) + return; + + /* If current URL is not at the end of the list, + truncate the rest of the list */ + if (history->locations) { + while (1) { + iter = g_list_last (history->locations); + if (!iter) + break; + if (iter == history->current) + break; + g_free (iter->data); + history->locations = g_list_remove (history->locations, iter->data); + } + } + + history->locations = g_list_append (history->locations, g_strdup (url)); + history->current = g_list_last (history->locations); +} + + diff --git a/pool/shard000/C/0012035_pure-2.c b/pool/shard000/C/0012035_pure-2.c new file mode 100644 index 0000000000000000000000000000000000000000..fe6e2bce6954900a78774567af79c39c59f9289a --- /dev/null +++ b/pool/shard000/C/0012035_pure-2.c @@ -0,0 +1,58 @@ +/* { dg-do compile } */ +/* { dg-options "-O2 -Wsuggest-attribute=pure" } */ +/* { dg-add-options bind_pic_locally } */ + +extern int extern_const(int a) __attribute__ ((pure)); +extern int v; + +/* Trivial. */ +int +foo1(int a) /* { dg-bogus "normally" "detect pure candidate" } */ +{ /* { dg-warning "pure" "detect pure candidate" { target *-*-* } "10" } */ + return v; +} + +/* Loops known to be normally and extern const calls should be safe. */ +int __attribute__ ((noinline)) +foo2(int n) /* { dg-bogus "normally" "detect pure candidate" } */ +{ /* { dg-warning "pure" "detect pure candidate" { target *-*-* } "17" } */ + int ret = 0; + int i; + for (i=0; i. + * + * Authors: + * Pierre Wieser + */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include "my/my-date.h" +#include "my/my-utils.h" + +#include "api/ofa-amount.h" +#include "api/ofa-igetter.h" +#include "api/ofa-prefs.h" +#include "api/ofo-base.h" +#include "api/ofo-currency.h" +#include "api/ofo-ledger.h" + +#include "ui/ofa-ledger-arc-store.h" + +/* private instance data + */ +typedef struct { + gboolean dispose_has_run; + + /* initialization + */ + ofaIGetter *getter; + ofoLedger *ledger; +} + ofaLedgerArcStorePrivate; + +static GType st_col_types[LEDGER_ARC_N_COLUMNS] = { + G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, /* date, iso, debit */ + G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, /* symbol1, credit, symbol2 */ + G_TYPE_OBJECT, G_TYPE_OBJECT /* #ofoLedger, #ofoCurrency */ +}; + +static gint on_sort_model( GtkTreeModel *tmodel, GtkTreeIter *a, GtkTreeIter *b, ofaLedgerArcStore *self ); +static void load_dataset( ofaLedgerArcStore *self, ofoLedger *ledger ); +static void insert_row( ofaLedgerArcStore *self, ofoLedger *ledger, gint i ); +static void set_row_by_iter( ofaLedgerArcStore *self, ofoLedger *ledger, gint i, GtkTreeIter *iter ); + +G_DEFINE_TYPE_EXTENDED( ofaLedgerArcStore, ofa_ledger_arc_store, OFA_TYPE_LIST_STORE, 0, + G_ADD_PRIVATE( ofaLedgerArcStore )) + +static void +ledger_arc_store_finalize( GObject *instance ) +{ + static const gchar *thisfn = "ofa_ledger_arc_store_finalize"; + + g_debug( "%s: application=%p (%s)", + thisfn, ( void * ) instance, G_OBJECT_TYPE_NAME( instance )); + + g_return_if_fail( instance && OFA_IS_LEDGER_ARC_STORE( instance )); + + /* free data members here */ + + /* chain up to the parent class */ + G_OBJECT_CLASS( ofa_ledger_arc_store_parent_class )->finalize( instance ); +} + +static void +ledger_arc_store_dispose( GObject *instance ) +{ + ofaLedgerArcStorePrivate *priv; + + g_return_if_fail( instance && OFA_IS_LEDGER_ARC_STORE( instance )); + + priv = ofa_ledger_arc_store_get_instance_private( OFA_LEDGER_ARC_STORE( instance )); + + if( !priv->dispose_has_run ){ + + priv->dispose_has_run = TRUE; + + /* unref object members here */ + } + + /* chain up to the parent class */ + G_OBJECT_CLASS( ofa_ledger_arc_store_parent_class )->dispose( instance ); +} + +static void +ofa_ledger_arc_store_init( ofaLedgerArcStore *self ) +{ + static const gchar *thisfn = "ofa_ledger_arc_store_init"; + ofaLedgerArcStorePrivate *priv; + + g_return_if_fail( OFA_IS_LEDGER_ARC_STORE( self )); + + g_debug( "%s: self=%p (%s)", + thisfn, ( void * ) self, G_OBJECT_TYPE_NAME( self )); + + priv = ofa_ledger_arc_store_get_instance_private( self ); + + priv->dispose_has_run = FALSE; +} + +static void +ofa_ledger_arc_store_class_init( ofaLedgerArcStoreClass *klass ) +{ + static const gchar *thisfn = "ofa_ledger_arc_store_class_init"; + + g_debug( "%s: klass=%p", thisfn, ( void * ) klass ); + + G_OBJECT_CLASS( klass )->dispose = ledger_arc_store_dispose; + G_OBJECT_CLASS( klass )->finalize = ledger_arc_store_finalize; +} + +/** + * ofa_ledger_arc_store_new: + * @getter: a #ofaIGetter instance. + * @ledger: the #ofoLedger. + * + * Load the archived soldes of the ledger. + * + * Returns: a new reference to the #ofaLedgerArcStore object. + */ +ofaLedgerArcStore * +ofa_ledger_arc_store_new( ofaIGetter *getter, ofoLedger *ledger ) +{ + ofaLedgerArcStore *store; + ofaLedgerArcStorePrivate *priv; + + g_return_val_if_fail( getter && OFA_IS_IGETTER( getter ), NULL ); + g_return_val_if_fail( ledger && OFO_IS_LEDGER( ledger ), NULL ); + + store = g_object_new( OFA_TYPE_LEDGER_ARC_STORE, NULL ); + + priv = ofa_ledger_arc_store_get_instance_private( store ); + + priv->getter = getter; + priv->ledger = ledger; + + gtk_list_store_set_column_types( + GTK_LIST_STORE( store ), LEDGER_ARC_N_COLUMNS, st_col_types ); + + gtk_tree_sortable_set_default_sort_func( + GTK_TREE_SORTABLE( store ), ( GtkTreeIterCompareFunc ) on_sort_model, store, NULL ); + gtk_tree_sortable_set_sort_column_id( + GTK_TREE_SORTABLE( store ), + GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID, GTK_SORT_ASCENDING ); + + load_dataset( store, ledger ); + + return( store ); +} + +/* + * sorting the self per date + */ +static gint +on_sort_model( GtkTreeModel *tmodel, GtkTreeIter *a, GtkTreeIter *b, ofaLedgerArcStore *self ) +{ + ofaLedgerArcStorePrivate *priv; + gchar *sdatea, *sdateb; + gint cmp; + + priv = ofa_ledger_arc_store_get_instance_private( self ); + + gtk_tree_model_get( tmodel, a, LEDGER_ARC_COL_DATE, &sdatea, -1 ); + gtk_tree_model_get( tmodel, b, LEDGER_ARC_COL_DATE, &sdateb, -1 ); + + cmp = my_date_compare_by_str( sdatea, sdateb, ofa_prefs_date_get_display_format( priv->getter )); + + g_free( sdatea ); + g_free( sdateb ); + + return( cmp ); +} + +static void +load_dataset( ofaLedgerArcStore *self, ofoLedger *ledger ) +{ + gint i, count; + + count = ofo_ledger_archive_get_count( ledger ); + + for( i=0 ; igetter, iso ); + g_return_if_fail( currency && OFO_IS_CURRENCY( currency )); + symbol = ofo_currency_get_symbol( currency ); + + date = ofo_ledger_archive_get_date( ledger, i ); + sdate = my_date_to_str( date, ofa_prefs_date_get_display_format( priv->getter )); + sdebit = ofa_amount_to_str( ofo_ledger_archive_get_debit( ledger, iso, date ), currency, priv->getter ); + scredit = ofa_amount_to_str( ofo_ledger_archive_get_credit( ledger, iso, date ), currency, priv->getter ); + + gtk_list_store_set( + GTK_LIST_STORE( self ), + iter, + LEDGER_ARC_COL_DATE, sdate, + LEDGER_ARC_COL_ISO, iso, + LEDGER_ARC_COL_DEBIT, sdebit, + LEDGER_ARC_COL_SYMBOL1, symbol, + LEDGER_ARC_COL_CREDIT, scredit, + LEDGER_ARC_COL_SYMBOL2, symbol, + LEDGER_ARC_COL_LEDGER, ledger, + LEDGER_ARC_COL_CURRENCY, currency, + -1 ); + + g_free( scredit ); + g_free( sdebit ); + g_free( sdate ); +} diff --git a/pool/shard000/C/0012054_nbsd-nat.c b/pool/shard000/C/0012054_nbsd-nat.c new file mode 100644 index 0000000000000000000000000000000000000000..72c471b4c2f2583f1556ed822ff8d1c8eaa9170e --- /dev/null +++ b/pool/shard000/C/0012054_nbsd-nat.c @@ -0,0 +1,43 @@ +/* Native-dependent code for NetBSD. + + Copyright (C) 2006-2014 Free Software Foundation, Inc. + + This file is part of GDB. + + 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 + along with this program. If not, see . */ + +#include "defs.h" + +#include "nbsd-nat.h" + +/* Return the name of a file that can be opened to get the symbols for + the child process identified by PID. */ + +char * +nbsd_pid_to_exec_file (struct target_ops *self, int pid) +{ + size_t len = PATH_MAX; + char *buf = xcalloc (len, sizeof (char)); + char *path; + + path = xstrprintf ("/proc/%d/exe", pid); + if (readlink (path, buf, PATH_MAX - 1) == -1) + { + xfree (buf); + buf = NULL; + } + + xfree (path); + return buf; +} diff --git a/pool/shard000/C/0012058_s3c_mfc_common.c b/pool/shard000/C/0012058_s3c_mfc_common.c new file mode 100644 index 0000000000000000000000000000000000000000..4d4c935e68a95433fbbab962b2009501f83ad9d8 --- /dev/null +++ b/pool/shard000/C/0012058_s3c_mfc_common.c @@ -0,0 +1,168 @@ +/* + * drivers/media/video/samsung/mfc40/s3c_mfc_common.c + * + * C file for Samsung MFC (Multi Function Codec - FIMV) driver + * + * Jaeryul Oh, Copyright (c) 2009 Samsung Electronics + * http://www.samsungsemi.com/ + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + */ + + +#include + +#include "s3c_mfc_buffer_manager.h" +#include "s3c_mfc_common.h" +#include "s3c_mfc_interface.h" +#include "s3c_mfc_memory.h" +#include "s3c_mfc_logmsg.h" +#include "s3c_mfc_fw.h" +#include "s3c_mfc_errorno.h" + + +//static int s3c_mfc_inst_no[MFC_MAX_INSTANCE_NUM]; + +MFC_ERROR_CODE s3c_mfc_allocate_frame_buf(s3c_mfc_inst_ctx *mfc_ctx, s3c_mfc_args *args, s3c_mfc_frame_buf_arg_t buf_size) +{ + s3c_mfc_dec_init_arg_t *init_arg; + s3c_mfc_args local_param; + unsigned int luma_size, chroma_size; + MFC_ERROR_CODE ret_code = MFCINST_RET_OK; + + init_arg = (s3c_mfc_dec_init_arg_t *)args; + luma_size = buf_size.luma * mfc_ctx->totalDPBCnt; + chroma_size = buf_size.chroma * mfc_ctx->totalDPBCnt; + + /* + * Allocate chroma & (Mv in case of H264) buf + */ + init_arg->out_frame_buf_size.chroma = chroma_size; + + memset(&local_param, 0, sizeof(local_param)); + local_param.mem_alloc.buff_size = Align(chroma_size, 2*BUF_S_UNIT); + local_param.mem_alloc.mapped_addr = init_arg->in_mapped_addr; + + mfc_ctx->port_no = 0; + ret_code = s3c_mfc_get_virt_addr(mfc_ctx, &(local_param)); + if (ret_code < 0) + return ret_code; + init_arg->out_u_addr.chroma = local_param.mem_alloc.out_addr; + + memset(&local_param, 0, sizeof(local_param)); + local_param.get_phys_addr.u_addr = init_arg->out_u_addr.chroma; + + ret_code = s3c_mfc_get_phys_addr(mfc_ctx, &local_param); + if (ret_code < 0) + return ret_code; + + init_arg->out_p_addr.chroma = local_param.get_phys_addr.p_addr; + + /* + * Allocate luma buf + */ + init_arg->out_frame_buf_size.luma = luma_size; + + memset(&local_param, 0, sizeof(local_param)); + local_param.mem_alloc.buff_size = Align(luma_size, 2*BUF_S_UNIT); + local_param.mem_alloc.mapped_addr = init_arg->in_mapped_addr; // peter, it chould be checked in related to luma cases + + mfc_ctx->port_no = 1; + ret_code = s3c_mfc_get_virt_addr(mfc_ctx, &(local_param)); + if (ret_code < 0) + return ret_code; + init_arg->out_u_addr.luma = local_param.mem_alloc.out_addr; + + memset(&local_param, 0, sizeof(local_param)); + local_param.get_phys_addr.u_addr = init_arg->out_u_addr.luma; + + ret_code = s3c_mfc_get_phys_addr(mfc_ctx, &(local_param)); + if (ret_code < 0) + return ret_code; + + init_arg->out_p_addr.luma = local_param.get_phys_addr.p_addr; + + return ret_code; + +} + +s3c_mfc_frame_buf_arg_t s3c_mfc_get_frame_buf_size(s3c_mfc_inst_ctx *mfc_ctx, s3c_mfc_args *args) +{ + unsigned int luma_plane_sz, chroma_plane_sz, mv_plane_sz; + s3c_mfc_frame_buf_arg_t buf_size; + s3c_mfc_dec_init_arg_t *init_arg; + + init_arg = (s3c_mfc_dec_init_arg_t *)args; + + /* frameBufSize is sizes for LumaPlane, ChromaPlane & MvPlane */ + luma_plane_sz = Align(Align(init_arg->out_img_width, 4*BUF_S_UNIT)*Align(init_arg->out_img_height, BUF_S_UNIT), \ + 64*BUF_L_UNIT); + chroma_plane_sz = Align(Align(init_arg->out_img_width, 4*BUF_S_UNIT)*Align(init_arg->out_img_height/2, BUF_S_UNIT), \ + 64*BUF_L_UNIT);; + buf_size.luma = luma_plane_sz; + buf_size.chroma = chroma_plane_sz; + + if (mfc_ctx->MfcCodecType == H264_DEC) { + mv_plane_sz = Align(Align(init_arg->out_img_width, 4*BUF_S_UNIT)*Align(init_arg->out_img_height/4, BUF_S_UNIT), \ + 64*BUF_L_UNIT); + buf_size.chroma += mv_plane_sz; + } + + return buf_size; + +} + +/* +void s3c_mfc_init_inst_no(void) +{ + memset(&s3c_mfc_inst_no, 0x00, sizeof(s3c_mfc_inst_no)); +} + + +int s3c_mfc_get_inst_no(void) +{ + unsigned int i; + + for(i = 0; i < MFC_MAX_INSTANCE_NUM; i++) + if (s3c_mfc_inst_no[i] == 0) { + s3c_mfc_inst_no[i] = 1; + return i; + } + + return -1; +} + +void s3c_mfc_return_inst_no(int inst_no) +{ + if ((inst_no >= 0) && (inst_no < MFC_MAX_INSTANCE_NUM)) + s3c_mfc_inst_no[inst_no] = 0; + +} + + +BOOL s3c_mfc_is_running(void) +{ + unsigned int i; + BOOL ret = FALSE; + + for(i = 1; i < MFC_MAX_INSTANCE_NUM; i++) + if(s3c_mfc_inst_no[i] == 1) + ret = TRUE; + + return ret; +} +*/ + +int s3c_mfc_set_state(s3c_mfc_inst_ctx *ctx, s3c_mfc_inst_state state) +{ + + if(ctx->MfcState > state) + return 0; + + ctx->MfcState = state; + return 1; + +} + diff --git a/pool/shard000/C/0012061_msgqueue.c b/pool/shard000/C/0012061_msgqueue.c new file mode 100644 index 0000000000000000000000000000000000000000..b490ad194712d6d9576603d99dfa95db3b2dac3e --- /dev/null +++ b/pool/shard000/C/0012061_msgqueue.c @@ -0,0 +1,100 @@ +#include +#include +#include +#include +#include +#include + +void msg_stat(int, struct msqid_ds); +int main(int argc, char **argv) +{ + int gflags, sflags, rflags; + key_t key; + int msgid; + int reval; + + struct msgsbuf { + int mtype; + char mtext[1]; + } msg_sbuf; + + struct msgmbuf { + int mtype; + char mtext[10]; + } msg_rbuf; + + struct msqid_ds msg_ginfo, msg_sinfo; + char *msgpath = "/etc/mtab"; + key = ftok(msgpath, 'a'); + gflags = IPC_CREAT | IPC_EXCL; + msgid = msgget(key, gflags | 00666); + + if (msgid == -1) { + perror("msg create error"); + return -1; + } + //创建一个消息队列后,输出消息队列缺省属性 + msg_stat(msgid, msg_ginfo); + sflags = IPC_NOWAIT; + msg_sbuf.mtype = 10; + msg_sbuf.mtext[0] = 'a'; + + reval = msgsnd(msgid, &msg_sbuf, sizeof(msg_sbuf.mtext), sflags); + if (reval == -1) { + perror("message send error"); + } + //发送一个消息后,输出消息队列属性 + msg_stat(msgid, msg_ginfo); + rflags = IPC_NOWAIT | MSG_NOERROR; + + reval = msgrcv(msgid, &msg_rbuf, 4, 10, rflags); + if (reval == -1) + perror("read msg error"); + else + printf("read from msg queue %d bytes\n", reval); + //从消息队列中读出消息后,输出消息队列属性 + msg_stat(msgid, msg_ginfo); + msg_sinfo.msg_perm.uid = 8; //just a try + msg_sinfo.msg_perm.gid = 8; // + msg_sinfo.msg_qbytes = 16388; + + //此处验证超级用户可以更改消息队列的缺省msg_qbytes + //注意这里设置的值大于缺省值 + reval = msgctl(msgid, IPC_SET, &msg_sinfo); + if (reval == -1) { + perror("msg set info error"); + //return -1; + } + msg_stat(msgid, msg_ginfo); + //验证设置消息队列属性 + reval = msgctl(msgid, IPC_RMID, NULL); //删除消息队列 + if (reval == -1) { + perror("unlink msg queue error"); + return -1; + } + return 0; +} + +void msg_stat(int msgid, struct msqid_ds msg_info) +{ + int reval; + sleep(1); //只是为了后面输出时间的方便 + reval = msgctl(msgid, IPC_STAT, &msg_info); + if (reval == -1) { + printf("get msg info error\n"); + return; + } + printf("\n"); + printf("current number of bytes on queue is %d\n", + msg_info.msg_cbytes); + printf("number of messages in queue is %d\n", msg_info.msg_qnum); + printf("max number of bytes on queue is %d\n", msg_info.msg_qbytes); + //每个消息队列的容量(字节数)都有限制MSGMNB,值的大小因系统而异。在创建新的消息队列时,//msg_qbytes的缺省值就是MSGMNB + printf("pid of last msgsnd is %d\n", msg_info.msg_lspid); + printf("pid of last msgrcv is %d\n", msg_info.msg_lrpid); + printf("last msgsnd time is %s", ctime(&(msg_info.msg_stime))); + printf("last msgrcv time is %s", ctime(&(msg_info.msg_rtime))); + printf("last change time is %s", ctime(&(msg_info.msg_ctime))); + printf("msg uid is %d\n", msg_info.msg_perm.uid); + printf("msg gid is %d\n", msg_info.msg_perm.gid); +} diff --git a/pool/shard000/C/0012086_reset-berlin.c b/pool/shard000/C/0012086_reset-berlin.c new file mode 100644 index 0000000000000000000000000000000000000000..f8b48a13cf0ba86738da958f1a42a875a9f06dfa --- /dev/null +++ b/pool/shard000/C/0012086_reset-berlin.c @@ -0,0 +1,131 @@ +/* + * Copyright (C) 2014 Marvell Technology Group Ltd. + * + * Antoine Tenart + * Sebastian Hesselbarth + * + * This file is licensed under the terms of the GNU General Public + * License version 2. This program is licensed "as is" without any + * warranty of any kind, whether express or implied. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define BERLIN_MAX_RESETS 32 + +#define to_berlin_reset_priv(p) \ + container_of((p), struct berlin_reset_priv, rcdev) + +struct berlin_reset_priv { + void __iomem *base; + unsigned int size; + struct reset_controller_dev rcdev; +}; + +static int berlin_reset_reset(struct reset_controller_dev *rcdev, + unsigned long id) +{ + struct berlin_reset_priv *priv = to_berlin_reset_priv(rcdev); + int offset = id >> 8; + int mask = BIT(id & 0x1f); + + writel(mask, priv->base + offset); + + /* let the reset be effective */ + udelay(10); + + return 0; +} + +static struct reset_control_ops berlin_reset_ops = { + .reset = berlin_reset_reset, +}; + +static int berlin_reset_xlate(struct reset_controller_dev *rcdev, + const struct of_phandle_args *reset_spec) +{ + struct berlin_reset_priv *priv = to_berlin_reset_priv(rcdev); + unsigned offset, bit; + + if (WARN_ON(reset_spec->args_count != rcdev->of_reset_n_cells)) + return -EINVAL; + + offset = reset_spec->args[0]; + bit = reset_spec->args[1]; + + if (offset >= priv->size) + return -EINVAL; + + if (bit >= BERLIN_MAX_RESETS) + return -EINVAL; + + return (offset << 8) | bit; +} + +static int __berlin_reset_init(struct device_node *np) +{ + struct berlin_reset_priv *priv; + struct resource res; + resource_size_t size; + int ret; + + priv = kzalloc(sizeof(*priv), GFP_KERNEL); + if (!priv) + return -ENOMEM; + + ret = of_address_to_resource(np, 0, &res); + if (ret) + goto err; + + size = resource_size(&res); + priv->base = ioremap(res.start, size); + if (!priv->base) { + ret = -ENOMEM; + goto err; + } + priv->size = size; + + priv->rcdev.owner = THIS_MODULE; + priv->rcdev.ops = &berlin_reset_ops; + priv->rcdev.of_node = np; + priv->rcdev.of_reset_n_cells = 2; + priv->rcdev.of_xlate = berlin_reset_xlate; + + reset_controller_register(&priv->rcdev); + + return 0; + +err: + kfree(priv); + return ret; +} + +static const struct of_device_id berlin_reset_of_match[] __initconst = { + { .compatible = "marvell,berlin2-chip-ctrl" }, + { .compatible = "marvell,berlin2cd-chip-ctrl" }, + { .compatible = "marvell,berlin2q-chip-ctrl" }, + { }, +}; + +static int __init berlin_reset_init(void) +{ + struct device_node *np; + int ret; + + for_each_matching_node(np, berlin_reset_of_match) { + ret = __berlin_reset_init(np); + if (ret) + return ret; + } + + return 0; +} +arch_initcall(berlin_reset_init); diff --git a/pool/shard000/C/0012087_crcgen-new.c b/pool/shard000/C/0012087_crcgen-new.c new file mode 100644 index 0000000000000000000000000000000000000000..5e59c80ff1969ebd8951e9bf5c33baf68233753d --- /dev/null +++ b/pool/shard000/C/0012087_crcgen-new.c @@ -0,0 +1,85 @@ +#include +#include +#include +#include +#include +#include + +#define lo8(x) (x & 0xFF) +#define hi8(x) ((x >> 8) & 0xFF) +#define xhi8(x) ((x >> 16) & 0xff) +#define xxhi8(x) ((x >> 24) & 0xff) + +unsigned short crc_ccitt_update (uint16_t crc, uint8_t data) +{ + data ^= lo8 (crc); + data ^= data << 4; + return ((((uint16_t)data << 8) | hi8 (crc)) ^ (uint8_t)(data >> 4) ^ ((uint16_t)data << 3)); +} + +int main(int argc, char *argv[]) { + if (argc != 5) { + printf("Usage: crcgen \r\n"); + return 1; + } + + unsigned long length = strtol(argv[2],NULL,0); + unsigned long devid = strtol(argv[3],NULL,0); + unsigned long version = strtol(argv[4],NULL,0); + + if (length > length+8) { + printf("Ha ha, very funny.\n"); + return 1; + } + + uint8_t *data = malloc(length+8); + + if (!data) { + perror("malloc"); + return 1; + } + + memset(data, 0xff, length); + + FILE *f; + + f = fopen(argv[1], "rb+"); + + if (f == 0) { + printf("Unable to open file %s\r\n", argv[1]); + return 1; + } + + fread(data, 1, length, f); + + data[length-8] = lo8(devid); + data[length-7] = hi8(devid); + data[length-6] = xhi8(devid); + data[length-5] = xxhi8(devid); + data[length-4] = lo8(version); + data[length-3] = hi8(version); + + unsigned long l; + unsigned short crc = 0xFFFF; + + for (l=0; l < length-2; l++) + crc = crc_ccitt_update(crc, data[l]); + + data[length-2] = lo8(crc); + data[length-1] = hi8(crc); + + if (fseek(f, 0, SEEK_SET)) { + perror("fseek"); + return 1; + } + + if (fwrite(data, length, 1, f) != 1) { + perror("fwrite"); + return 1; + } + + fclose(f); + + return 0; +} + diff --git a/pool/shard000/C/0012097_interrupt.c b/pool/shard000/C/0012097_interrupt.c new file mode 100644 index 0000000000000000000000000000000000000000..4ed625445220ad2f7832f569e94ee34d89d469d6 --- /dev/null +++ b/pool/shard000/C/0012097_interrupt.c @@ -0,0 +1,26 @@ +#include +#include "interrupt.h" +#include "pca9557.h" +#include "stdio.h" + +extern sensor_t barometer; + +void tc_callback(void) +{ + sensor_data_t press_data = { .scaled = true }; + sensor_data_t temp_data = { .scaled = true }; + char string_buf[20]; + static int i = 0; + pca9557_toggle_pin_level(0x1a, i++); + if (i == 8) + i = 0; + LED_Toggle(LED0); + sensor_get_pressure(&barometer, &press_data); + sensor_get_temperature(&barometer, &temp_data); + + snprintf(string_buf, sizeof(string_buf), "P = %.2f hPa ", (press_data.pressure.value / 100.0)); + gfx_mono_draw_string(string_buf, 20, 10, &sysfont); + snprintf(string_buf, sizeof(string_buf), "T = %.1f C", (temp_data.temperature.value / 10.0)); + gfx_mono_draw_string(string_buf, 20, 20, &sysfont); + tc_clear_overflow(&TCC0); +} diff --git a/pool/shard000/C/0012106_receiver-win.c b/pool/shard000/C/0012106_receiver-win.c new file mode 100644 index 0000000000000000000000000000000000000000..75022be0c2c5e3f0aadf63836d7c0111460ac174 --- /dev/null +++ b/pool/shard000/C/0012106_receiver-win.c @@ -0,0 +1,286 @@ +/* @(#) $Id: ./src/client-agent/receiver-win.c, 2011/09/08 dcid Exp $ + */ + +/* Copyright (C) 2009 Trend Micro Inc. + * All right reserved. + * + * This program is a free software; you can redistribute it + * and/or modify it under the terms of the GNU General Public + * License (version 2) as published by the FSF - Free Software + * Foundation + */ + + +#ifdef WIN32 +#include "shared.h" +#include "os_execd/execd.h" +#include "os_crypto/md5/md5_op.h" +#include "os_net/os_net.h" +#include "agentd.h" + + + +/* receiver_thread: + * Receive events from the server. + */ +void *receiver_thread(void *none) +{ + int recv_b; + + char file[OS_SIZE_1024 +1]; + char buffer[OS_MAXSTR +1]; + + char cleartext[OS_MAXSTR + 1]; + char *tmp_msg; + + char file_sum[34]; + + fd_set fdset; + struct timeval selecttime; + + FILE *fp; + + + /* Setting FP to null, before starting */ + fp = NULL; + + memset(cleartext, '\0', OS_MAXSTR +1); + memset(buffer, '\0', OS_MAXSTR +1); + memset(file, '\0', OS_SIZE_1024 +1); + memset(file_sum, '\0', 34); + + + while(1) + { + /* sock must be set. */ + if(logr->sock == -1) + { + sleep(5); + continue; + } + + FD_ZERO(&fdset); + FD_SET(logr->sock, &fdset); + + + /* Wait for 30 seconds. */ + selecttime.tv_sec = 30; + selecttime.tv_usec = 0; + + + /* Wait for 120 seconds at a maximum for any descriptor */ + recv_b = select(0, &fdset, NULL, NULL, &selecttime); + if(recv_b == -1) + { + merror(SELECT_ERROR, ARGV0); + sleep(30); + continue; + } + else if(recv_b == 0) + { + continue; + } + + /* Read until no more messages are available */ + while((recv_b = recv(logr->sock,buffer,OS_SIZE_1024, 0))>0) + { + /* Id of zero -- only one key allowed */ + tmp_msg = ReadSecMSG(&keys, buffer, cleartext, 0, recv_b -1); + if(tmp_msg == NULL) + { + merror(MSG_ERROR,ARGV0,logr->rip[logr->rip_id]); + continue; + } + + + /* Check for commands */ + if(IsValidHeader(tmp_msg)) + { + /* This is the only thread that modifies it */ + available_server = (int)time(NULL); + + + /* Run timeout commands. */ + if(logr->execdq >= 0) + WinTimeoutRun(available_server); + + /* If it is an active response message */ + if(strncmp(tmp_msg, EXECD_HEADER, strlen(EXECD_HEADER)) == 0) + { + tmp_msg+=strlen(EXECD_HEADER); + + + /* Run on windows. */ + if(logr->execdq >= 0) + { + WinExecdRun(tmp_msg); + } + + + continue; + } + + + /* Restart syscheck. */ + else if(strcmp(tmp_msg, HC_SK_RESTART) == 0) + { + os_set_restart_syscheck(); + continue; + } + + + /* Ack from server */ + else if(strcmp(tmp_msg, HC_ACK) == 0) + { + continue; + } + + /* Close any open file pointer if it was being written to */ + if(fp) + { + fclose(fp); + fp = NULL; + } + + /* File update message */ + if(strncmp(tmp_msg, FILE_UPDATE_HEADER, + strlen(FILE_UPDATE_HEADER)) == 0) + { + char *validate_file; + tmp_msg+=strlen(FILE_UPDATE_HEADER); + + /* Going to after the file sum */ + validate_file = strchr(tmp_msg, ' '); + if(!validate_file) + { + continue; + } + + *validate_file = '\0'; + + /* copying the file sum */ + strncpy(file_sum, tmp_msg, 33); + + + /* Setting tmp_msg to the beginning of the file name */ + validate_file++; + tmp_msg = validate_file; + + + if((validate_file = strchr(tmp_msg, '\n')) != NULL) + { + *validate_file = '\0'; + } + + while((validate_file = strchr(tmp_msg, '/')) != NULL) + { + *validate_file = '-'; + } + + if(tmp_msg[0] == '.') + tmp_msg[0] = '-'; + + + snprintf(file, OS_SIZE_1024, "%s/%s", + SHAREDCFG_DIR, + tmp_msg); + + fp = fopen(file, "w"); + if(!fp) + { + merror(FOPEN_ERROR, ARGV0, file); + } + } + + else if(strncmp(tmp_msg, FILE_CLOSE_HEADER, + strlen(FILE_CLOSE_HEADER)) == 0) + { + /* no error */ + os_md5 currently_md5; + + /* Making sure to close for the rename to work */ + if(fp) + { + fclose(fp); + fp = NULL; + } + + if(file[0] == '\0') + { + /* nada */ + } + + else if(OS_MD5_File(file, currently_md5) < 0) + { + /* Removing file */ + unlink(file); + file[0] = '\0'; + } + else + { + if(strcmp(currently_md5, file_sum) != 0) + { + debug1("%s: Failed md5 for: %s -- deleting.", + ARGV0, file); + unlink(file); + } + else + { + char *final_file; + + /* Renaming the file to its orignal name */ + final_file = strrchr(file, '/'); + if(final_file) + { + if(strcmp(final_file + 1, SHAREDCFG_FILENAME) == 0) + { + UnmergeFiles(file, SHAREDCFG_DIR); + } + } + else + { + unlink(file); + } + } + + file[0] = '\0'; + } + } + + else + { + merror("%s: WARN: Unknown message received from server.", ARGV0); + } + } + + else if(fp) + { + available_server = (int)time(NULL); + fprintf(fp, "%s", tmp_msg); + } + + else + { + merror("%s: WARN: Unknown message received. No action defined.", + ARGV0); + } + } + } + + + /* Cleaning up */ + if(fp) + { + fclose(fp); + if(file[0] != '\0') + unlink(file); + } + + return(NULL); + +} + + +#endif + +/* EOF */ diff --git a/pool/shard000/C/0012112_hex.c b/pool/shard000/C/0012112_hex.c new file mode 100644 index 0000000000000000000000000000000000000000..4983a77ea9cbcded947cfe1eff293331f27b3f80 --- /dev/null +++ b/pool/shard000/C/0012112_hex.c @@ -0,0 +1,201 @@ +/* + * Copyright (C) 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC") + * Copyright (C) 2000-2003 Internet Software Consortium. + * + * 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 ISC DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS. IN NO EVENT SHALL ISC 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. + */ + +/* $Id: hex.c,v 1.18 2007/06/19 23:47:17 tbox Exp $ */ + +/*! \file */ + +#include + +#include + +#include +#include +#include +#include +#include + +#define RETERR(x) do { \ + isc_result_t _r = (x); \ + if (_r != ISC_R_SUCCESS) \ + return (_r); \ + } while (0) + + +/* + * BEW: These static functions are copied from lib/dns/rdata.c. + */ +static isc_result_t +str_totext(const char *source, isc_buffer_t *target); + +static isc_result_t +mem_tobuffer(isc_buffer_t *target, void *base, unsigned int length); + +static const char hex[] = "0123456789ABCDEF"; + +isc_result_t +isc_hex_totext(isc_region_t *source, int wordlength, + const char *wordbreak, isc_buffer_t *target) +{ + char buf[3]; + unsigned int loops = 0; + + if (wordlength < 2) + wordlength = 2; + + memset(buf, 0, sizeof(buf)); + while (source->length > 0) { + buf[0] = hex[(source->base[0] >> 4) & 0xf]; + buf[1] = hex[(source->base[0]) & 0xf]; + RETERR(str_totext(buf, target)); + isc_region_consume(source, 1); + + loops++; + if (source->length != 0 && + (int)((loops + 1) * 2) >= wordlength) + { + loops = 0; + RETERR(str_totext(wordbreak, target)); + } + } + return (ISC_R_SUCCESS); +} + +/*% + * State of a hex decoding process in progress. + */ +typedef struct { + int length; /*%< Desired length of binary data or -1 */ + isc_buffer_t *target; /*%< Buffer for resulting binary data */ + int digits; /*%< Number of buffered hex digits */ + int val[2]; +} hex_decode_ctx_t; + +static inline void +hex_decode_init(hex_decode_ctx_t *ctx, int length, isc_buffer_t *target) +{ + ctx->digits = 0; + ctx->length = length; + ctx->target = target; +} + +static inline isc_result_t +hex_decode_char(hex_decode_ctx_t *ctx, int c) { + char *s; + + if ((s = strchr(hex, toupper(c))) == NULL) + return (ISC_R_BADHEX); + ctx->val[ctx->digits++] = s - hex; + if (ctx->digits == 2) { + unsigned char num; + + num = (ctx->val[0] << 4) + (ctx->val[1]); + RETERR(mem_tobuffer(ctx->target, &num, 1)); + if (ctx->length >= 0) { + if (ctx->length == 0) + return (ISC_R_BADHEX); + else + ctx->length -= 1; + } + ctx->digits = 0; + } + return (ISC_R_SUCCESS); +} + +static inline isc_result_t +hex_decode_finish(hex_decode_ctx_t *ctx) { + if (ctx->length > 0) + return (ISC_R_UNEXPECTEDEND); + if (ctx->digits != 0) + return (ISC_R_BADHEX); + return (ISC_R_SUCCESS); +} + +isc_result_t +isc_hex_tobuffer(isc_lex_t *lexer, isc_buffer_t *target, int length) { + hex_decode_ctx_t ctx; + isc_textregion_t *tr; + isc_token_t token; + isc_boolean_t eol; + + hex_decode_init(&ctx, length, target); + + while (ctx.length != 0) { + unsigned int i; + + if (length > 0) + eol = ISC_FALSE; + else + eol = ISC_TRUE; + RETERR(isc_lex_getmastertoken(lexer, &token, + isc_tokentype_string, eol)); + if (token.type != isc_tokentype_string) + break; + tr = &token.value.as_textregion; + for (i = 0; i < tr->length; i++) + RETERR(hex_decode_char(&ctx, tr->base[i])); + } + if (ctx.length < 0) + isc_lex_ungettoken(lexer, &token); + RETERR(hex_decode_finish(&ctx)); + return (ISC_R_SUCCESS); +} + +isc_result_t +isc_hex_decodestring(char *cstr, isc_buffer_t *target) { + hex_decode_ctx_t ctx; + + hex_decode_init(&ctx, -1, target); + for (;;) { + int c = *cstr++; + if (c == '\0') + break; + if (c == ' ' || c == '\t' || c == '\n' || c== '\r') + continue; + RETERR(hex_decode_char(&ctx, c)); + } + RETERR(hex_decode_finish(&ctx)); + return (ISC_R_SUCCESS); +} + +static isc_result_t +str_totext(const char *source, isc_buffer_t *target) { + unsigned int l; + isc_region_t region; + + isc_buffer_availableregion(target, ®ion); + l = strlen(source); + + if (l > region.length) + return (ISC_R_NOSPACE); + + memcpy(region.base, source, l); + isc_buffer_add(target, l); + return (ISC_R_SUCCESS); +} + +static isc_result_t +mem_tobuffer(isc_buffer_t *target, void *base, unsigned int length) { + isc_region_t tr; + + isc_buffer_availableregion(target, &tr); + if (length > tr.length) + return (ISC_R_NOSPACE); + memcpy(tr.base, base, length); + isc_buffer_add(target, length); + return (ISC_R_SUCCESS); +} diff --git a/pool/shard000/C/0012116_ad_resize.c b/pool/shard000/C/0012116_ad_resize.c new file mode 100644 index 0000000000000000000000000000000000000000..a6be2c1760800d437c5608b0103cd956401b137a --- /dev/null +++ b/pool/shard000/C/0012116_ad_resize.c @@ -0,0 +1,38 @@ +/* -*- Mode: C; c-basic-offset:4 ; indent-tabs-mode:nil ; -*- */ +/* + * + * Copyright (C) 2004 University of Chicago. + * See COPYRIGHT notice in top-level directory. + */ + +#include "adio.h" + +#ifdef HAVE_UNISTD_H +#include +#endif + +void ADIOI_GEN_Resize(ADIO_File fd, ADIO_Offset size, int *error_code) +{ + int err, rank; + static char myname[] = "ADIOI_GEN_RESIZE"; + + MPI_Comm_rank(fd->comm, &rank); + + /* first aggregator performs ftruncate() */ + if (rank == fd->hints->ranklist[0]) { + ADIOI_Assert(size == (off_t) size); + err = ftruncate(fd->fd_sys, (off_t)size); + } + + /* bcast return value */ + MPI_Bcast(&err, 1, MPI_INT, fd->hints->ranklist[0], fd->comm); + + /* --BEGIN ERROR HANDLING-- */ + if (err == -1) { + *error_code = ADIOI_Err_create_code(myname, fd->filename, errno); + return; + } + /* --END ERROR HANDLING-- */ + + *error_code = MPI_SUCCESS; +} diff --git a/pool/shard000/C/0012122_sf_error.c b/pool/shard000/C/0012122_sf_error.c new file mode 100644 index 0000000000000000000000000000000000000000..066f69079dbc573393c20795dd33746d904baf87 --- /dev/null +++ b/pool/shard000/C/0012122_sf_error.c @@ -0,0 +1,160 @@ +#include + +#include +#include + +#include "sf_error.h" + +const char *sf_error_messages[] = { + "no error", + "singularity", + "underflow", + "overflow", + "too slow convergence", + "loss of precision", + "no result obtained", + "domain error", + "invalid input argument", + "other error", + NULL +}; + +/* If this isn't volatile clang tries to optimize it away */ +static volatile sf_action_t sf_error_actions[] = { + SF_ERROR_IGNORE, /* SF_ERROR_OK */ + SF_ERROR_IGNORE, /* SF_ERROR_SINGULAR */ + SF_ERROR_IGNORE, /* SF_ERROR_UNDERFLOW */ + SF_ERROR_IGNORE, /* SF_ERROR_OVERFLOW */ + SF_ERROR_IGNORE, /* SF_ERROR_SLOW */ + SF_ERROR_IGNORE, /* SF_ERROR_LOSS */ + SF_ERROR_IGNORE, /* SF_ERROR_NO_RESULT */ + SF_ERROR_IGNORE, /* SF_ERROR_DOMAIN */ + SF_ERROR_IGNORE, /* SF_ERROR_ARG */ + SF_ERROR_IGNORE, /* SF_ERROR_OTHER */ + SF_ERROR_IGNORE /* SF_ERROR__LAST */ +}; + +extern int wrap_PyUFunc_getfperr(void); + + +void sf_error_set_action(sf_error_t code, sf_action_t action) +{ + sf_error_actions[(int)code] = action; +} + + +sf_action_t sf_error_get_action(sf_error_t code) +{ + return sf_error_actions[(int)code]; +} + + +void sf_error(const char *func_name, sf_error_t code, const char *fmt, ...) +{ + PyGILState_STATE save; + PyObject *scipy_special = NULL; + char msg[2048], info[1024]; + static PyObject *py_SpecialFunctionWarning = NULL; + sf_action_t action; + va_list ap; + + if ((int)code < 0 || (int)code >= 10) { + code = SF_ERROR_OTHER; + } + action = sf_error_get_action(code); + if (action == SF_ERROR_IGNORE) { + return; + } + + if (func_name == NULL) { + func_name = "?"; + } + + if (fmt != NULL && fmt[0] != '\0') { + va_start(ap, fmt); + PyOS_vsnprintf(info, 1024, fmt, ap); + va_end(ap); + PyOS_snprintf(msg, 2048, "scipy.special/%s: (%s) %s", + func_name, sf_error_messages[(int)code], info); + } + else { + PyOS_snprintf(msg, 2048, "scipy.special/%s: %s", + func_name, sf_error_messages[(int)code]); + } + +#ifdef WITH_THREAD + save = PyGILState_Ensure(); +#endif + + if (PyErr_Occurred()) { + goto skip_warn; + } + + scipy_special = PyImport_ImportModule("scipy.special"); + if (scipy_special == NULL) { + PyErr_Clear(); + goto skip_warn; + } + + if (action == SF_ERROR_WARN) { + py_SpecialFunctionWarning = + PyObject_GetAttrString(scipy_special, "SpecialFunctionWarning"); + } + else if (action == SF_ERROR_RAISE) { + py_SpecialFunctionWarning = + PyObject_GetAttrString(scipy_special, "SpecialFunctionError"); + } + else { + /* Sentinel, should never get here */ + py_SpecialFunctionWarning = NULL; + } + if (py_SpecialFunctionWarning == NULL) { + PyErr_Clear(); + goto skip_warn; + } + + if (action == SF_ERROR_WARN) { + PyErr_WarnEx(py_SpecialFunctionWarning, msg, 1); + /* + * For ufuncs the return value is ignored! We rely on the fact + * that the Ufunc loop will call PyErr_Occurred() later on. + */ + } + else if (action == SF_ERROR_RAISE) { + PyErr_SetString(py_SpecialFunctionWarning, msg); + } + else { + goto skip_warn; + } + + skip_warn: +#ifdef WITH_THREAD + PyGILState_Release(save); +#else + ; +#endif +} + + +#define UFUNC_FPE_DIVIDEBYZERO 1 +#define UFUNC_FPE_OVERFLOW 2 +#define UFUNC_FPE_UNDERFLOW 4 +#define UFUNC_FPE_INVALID 8 + +void sf_error_check_fpe(const char *func_name) +{ + int status; + status = wrap_PyUFunc_getfperr(); + if (status & UFUNC_FPE_DIVIDEBYZERO) { + sf_error(func_name, SF_ERROR_SINGULAR, "floating point division by zero"); + } + if (status & UFUNC_FPE_UNDERFLOW) { + sf_error(func_name, SF_ERROR_UNDERFLOW, "floating point underflow"); + } + if (status & UFUNC_FPE_OVERFLOW) { + sf_error(func_name, SF_ERROR_OVERFLOW, "floating point overflow"); + } + if (status & UFUNC_FPE_INVALID) { + sf_error(func_name, SF_ERROR_DOMAIN, "floating point invalid value"); + } +} diff --git a/pool/shard000/C/0012146_EmailHeaders.c b/pool/shard000/C/0012146_EmailHeaders.c new file mode 100644 index 0000000000000000000000000000000000000000..0824cf83cad01cca09a1a2e5aaea2373b5966a7a --- /dev/null +++ b/pool/shard000/C/0012146_EmailHeaders.c @@ -0,0 +1,140 @@ +#include "EmailHeaders.h" +#include "FileTypeRules.h" +#include "IPRegion.h" +#include "DocumentStrings.h" +#include "URL.h" + +ListNode *HeaderRules=NULL; + + +void EmailHeaderRulesAdd(const char *Header, const char *Value, const char *Action) +{ +char *Tempstr=NULL; + +Tempstr=FormatStr(Tempstr,"%s:%s",Header,Value); +if (! HeaderRules) HeaderRules=ListCreate(); +ListAddNamedItem(HeaderRules, Tempstr, CopyStr(NULL, Action)); + +Destroy(Tempstr); +} + + +char *EmailHeadersExtractIP(char *IP, const char *ReceivedHeader) +{ +char *Token=NULL; +const char *optr, *ptr; + +IP=CopyStr(IP, ""); +ptr=GetToken(ReceivedHeader, "\\S", &Token, 0); +while (ptr) +{ +if (strcasecmp(Token, "from")==0) +{ + ptr=GetToken(ptr, "\\S", &Token, 0); + while (ptr) + { + if (*Token == '[') + { + GetToken(Token+1,"]",&IP,0); + } + ptr=GetToken(ptr, "\\S", &Token, 0); + } +} +ptr=GetToken(ptr, "\\S", &Token, 0); +} + +Destroy(Token); + +return(IP); +} + + + +void EmailHeaderCheckSource(TMimeItem *Item, const char *Rules) +{ +char *Tempstr=NULL, *Name=NULL, *Value=NULL, *IP=NULL; +ListNode *Node; +const char *ptr; + +Node=ListFindNamedItem(Item->Headers, "Received"); +if (Node) +{ + IP=EmailHeadersExtractIP(IP, Node->Item); + if (Config->Flags & FLAG_DEBUG) printf("SENDER IP: %s\n",IP); + ptr=GetNameValuePair(Rules, "\\S", "=", &Name, &Value); + while (ptr) + { + if (strcasecmp(Name, "ip")==0) + { + if (pmatch(Value, IP, StrLen(IP), NULL, 0)) + { + Item->RulesResult |= RULE_EVIL | RULE_IP; + if (Config->Flags & FLAG_DEBUG) printf("SENDER IP RULE FAIL: required=%s got=%s\n",Value, IP); + } + } + else if (strcasecmp(Name, "region")==0) + { + Tempstr=RegionLookup(Tempstr, IP); + if (pmatch(Value, Tempstr, StrLen(Tempstr), NULL, 0)) + { + Item->RulesResult |= RULE_EVIL | RULE_IPREGION; + if (Config->Flags & FLAG_DEBUG) printf("SENDER REGION RULE FAIL: required=%s got=%s\n",Value, Tempstr); + } + } + ptr=GetNameValuePair(ptr, "\\S", "=", &Name, &Value); + } +} + +Destroy(Name); +Destroy(Value); +Destroy(Tempstr); +Destroy(IP); +} + + +void EmailHeaderRulesConsider(TMimeItem *Item, const char *Header, const char *Value) +{ + ListNode *Curr, *Node; + int val, result=RULE_NONE; + char *HeadName=NULL, *Token=NULL; + const char *ptr; + + //this gets called for every header, and adds them as it goes + if (! StrValid(Header)) return; + if (! Item->Headers) Item->Headers=ListCreate(); + Node=ListAddNamedItem(Item->Headers, Header, CopyStr(NULL, Value)); + + Curr=ListGetNext(HeaderRules); + while (Curr) + { + ptr=GetToken(Curr->Tag,":",&HeadName,0); + if ((pmatch(HeadName, Header, StrLen(Header), NULL, 0)) && (pmatch(ptr, Value, StrLen(Value), NULL, 0 ))) + { + //Equivalent stores action string + ptr=GetToken((char *) Curr->Item, " ",&Token,0); + + //These rules add filetype rules that are processed later + if (strcasecmp(Token, "FileType")==0) FileTypeRuleParse(ptr, 0); + if (strcasecmp(Token, "FileExtn")==0) FileExtnRuleParse(ptr); + if (strcasecmp(Token, "UrlRule")==0) URLParseRule(DocumentURLRules, ptr); + + //These rules add/override the permitted documents strings + if (strcasecmp(Token, "string")==0) + { + ptr=GetToken(ptr," ",&Token,0); + DocumentStringsAdd(Token, ptr, RULE_OVERRIDE); + } + + //source ipadddress check + if (strcasecmp(Token, "source")==0) EmailHeaderCheckSource(Item, ptr); + + + //show a header + if (strcasecmp(Token, "show")==0) Node->ItemType |= RULE_ECHO; + } + Curr=ListGetNext(Curr); + } + + Destroy(HeadName); + Destroy(Token); +} diff --git a/pool/shard000/C/0012153_gtcmtr_lkresume.c b/pool/shard000/C/0012153_gtcmtr_lkresume.c new file mode 100644 index 0000000000000000000000000000000000000000..8133cfc7a09b7c1b304ed15880dedca6db606397 --- /dev/null +++ b/pool/shard000/C/0012153_gtcmtr_lkresume.c @@ -0,0 +1,42 @@ +/**************************************************************** + * * + * Copyright 2001, 2004 Sanchez Computer Associates, Inc. * + * * + * This source code contains the intellectual property * + * of its copyright holder(s), and is made available * + * under a license. If you do not know the terms of * + * the license, please stop and do not read further. * + * * + ****************************************************************/ + +#include "mdef.h" +#include "mlkdef.h" +#include "cmidef.h" +#include "hashtab_mname.h" /* needed for cmmdef.h */ +#include "cmmdef.h" +#include "gtcmtr_protos.h" +#include "gt_timer.h" +#include "gtcmlkdef.h" +#include "gtcml.h" + +GBLREF connection_struct *curr_entry; + +bool gtcmtr_lkresume(void) +{ + unsigned char *ptr, return_val; + cm_region_list *reg_walk; + + ptr = curr_entry->clb_ptr->mbf; + assert(*ptr == CMMS_L_LKRESUME); + ptr++; + ptr++; + return_val = CMMS_M_LKGRANTED; + + return_val = gtcml_dolock(); + if (return_val == CMLCK_REQUEUE) + return CM_NOOP; + + *curr_entry->clb_ptr->mbf = return_val; + curr_entry->clb_ptr->cbl = 1; + return TRUE; +} diff --git a/pool/shard000/C/0012154_coff-solib.c b/pool/shard000/C/0012154_coff-solib.c new file mode 100644 index 0000000000000000000000000000000000000000..6be68697928f14ac2ebba7d7128db5cc6a287449 --- /dev/null +++ b/pool/shard000/C/0012154_coff-solib.c @@ -0,0 +1,134 @@ +/* Handle COFF SVR3 shared libraries for GDB, the GNU Debugger. + Copyright 1993 Free Software Foundation, Inc. + +This file is part of GDB. + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ + + +#include "defs.h" + +#include "frame.h" +#include "bfd.h" +#include "gdbcore.h" +#include "symtab.h" + +/* + +GLOBAL FUNCTION + + coff_solib_add -- add a shared library files to the symtab list. We + examine the `.lib' section of the exec file and determine the names of + the shared libraries. + + This function is responsible for discovering those names and + addresses, and saving sufficient information about them to allow + their symbols to be read at a later time. + +SYNOPSIS + + void coff_solib_add (char *arg_string, int from_tty, + struct target_ops *target) + +DESCRIPTION + +*/ + +void +coff_solib_add (arg_string, from_tty, target) + char *arg_string; + int from_tty; + struct target_ops *target; +{ + asection *libsect; + + libsect = bfd_get_section_by_name (exec_bfd, ".lib"); + + if (libsect) + { + int libsize; + unsigned char *lib; + struct libent + { + bfd_byte len[4]; + bfd_byte nameoffset[4]; + }; + + libsize = bfd_section_size (exec_bfd, libsect); + + lib = (unsigned char *) alloca (libsize); + + bfd_get_section_contents (exec_bfd, libsect, lib, 0, libsize); + + while (libsize > 0) + { + struct libent *ent; + struct objfile *objfile; + int len, nameoffset; + char *filename; + + ent = (struct libent *)lib; + + len = bfd_get_32 (exec_bfd, ent->len); + + nameoffset = bfd_get_32 (exec_bfd, ent->nameoffset); + + if (len <= 0) + break; + + filename = (char *)ent + nameoffset * 4; + + objfile = symbol_file_add (filename, from_tty, + 0, /* addr */ + 0, /* not mainline */ + 0, /* not mapped */ + 0, /* Not readnow */ + 0, /* Not user loaded */ + 1); /* Is a solib */ + + libsize -= len * 4; + lib += len * 4; + } + + /* Getting new symbols may change our opinion about what is + frameless. */ + reinit_frame_cache (); + } +} + +/* + +GLOBAL FUNCTION + + coff_solib_create_inferior_hook -- shared library startup support + +SYNOPSIS + + void coff_solib_create_inferior_hook() + +DESCRIPTION + + When gdb starts up the inferior, the kernel maps in the shared + libraries. We get here with the target stopped at it's first + instruction, and the libraries already mapped. At this point, this + function gets called via expansion of the macro + SOLIB_CREATE_INFERIOR_HOOK. + */ + +void +coff_solib_create_inferior_hook() +{ + coff_solib_add ((char *) 0, 0, (struct target_ops *) 0); +} diff --git a/pool/shard000/C/0012160_game.c b/pool/shard000/C/0012160_game.c new file mode 100644 index 0000000000000000000000000000000000000000..ff82b3282f469971f4a61d1702c6f5c369f774dc --- /dev/null +++ b/pool/shard000/C/0012160_game.c @@ -0,0 +1,237 @@ +/*************************************************************************** + * __________ __ ___. + * Open \______ \ ____ ____ | | _\_ |__ _______ ___ + * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ / + * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < < + * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \ + * \/ \/ \/ \/ \/ + * $Id: game.c 20060 2009-02-19 23:51:47Z moos $ + * + * Copyright (C) 2007-2009 Joshua Simmons + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ****************************************************************************/ + +#include "game.h" +#include "types.h" +#include "board.h" +#include "goban.h" +#include "sgf.h" +#include "sgf_output.h" +#include "sgf_parse.h" +#include "sgf_storage.h" +#include "display.h" + +static void pre_game_setup (void); + +char save_file[SAVE_FILE_LENGTH]; +bool game_dirty = false; /* flag for unsaved changes */ +bool autosave_dirty = false; /* flag for unsaved changes which haven't even + been autosaved yet */ + +int move_num = 0; + +unsigned char current_player = BLACK; + +struct header_t header; /* game metadata header info */ + +void +set_game_modified (void) +{ + game_dirty = true; + autosave_dirty = true; +} + +bool +load_game (const char *filename) +{ + rb->memset (&header, 0, sizeof (header)); + + if (rb->strlen (filename) + 1 > SAVE_FILE_LENGTH) + { + DEBUGF ("file name too long\n"); + return false; + } + + if (!rb->file_exists (filename)) + { + DEBUGF ("file doesn't exist!\n"); + return false; + } + + pre_game_setup (); + + rb->strcpy (save_file, filename); + +#ifdef HAVE_ADJUSTABLE_CPU_FREQ + rb->cpu_boost (true); +#endif + + rb->splash (0, "Loading..."); + + bool parse_failed = false; + if (!parse_sgf (save_file)) + { + rb->splash (3 * HZ, "Unable to parse SGF file. Will overwrite."); + parse_failed = true; + } + + game_dirty = false; + autosave_dirty = false; + +#ifdef HAVE_ADJUSTABLE_CPU_FREQ + rb->cpu_boost (false); +#endif + + if (header.handicap >= 2) + { + current_player = WHITE; + } + + post_game_setup_sgf (); + + if (!parse_failed) + { + draw_screen_display(); + if (rb->strcmp(filename, DEFAULT_SAVE)) + { + metadata_summary(); + } + } + + return true; +} + + +bool +save_game (const char *filename) +{ + if (rb->strlen (filename) + 1 > SAVE_FILE_LENGTH) + { + return false; + } + + /* We only have to do something if the game is dirty, or we're being + asked to save to a different location than we loaded from. + + If the game isn't dirty and we're being asked to save to default, + we also don't have to do anything.*/ + if (!game_dirty && + (rb->strcmp (filename, save_file) == 0 || + rb->strcmp (filename, DEFAULT_SAVE) == 0)) + { + return true; + } + +#ifdef HAVE_ADJUSTABLE_CPU_FREQ + rb->cpu_boost (true); +#endif + + rb->splash (0, "Saving..."); + + if (output_sgf (filename)) + { + /* saving only "cleans" the game if it's not a save to default, + * or if our save_file is actually default + * + * (so autosaves won't prevent legitimate saves to a Save As or + * loaded file) + */ + if (rb->strcmp (filename, DEFAULT_SAVE) || + rb->strcmp (save_file, DEFAULT_SAVE) == 0) + { + game_dirty = false; + } + + /* but saving anywhere means that autosave isn't dirty */ + autosave_dirty = false; + +#ifdef HAVE_ADJUSTABLE_CPU_FREQ + rb->cpu_boost (false); +#endif + /* The save succeeded. Now, if we saved to an actual file (not to the + * DEFAULT_SAVE), then we should delete the DEFAULT_SAVE file because + * the changes stored in it are no longer unsaved. + */ + if (rb->strcmp (filename, DEFAULT_SAVE)) + { + rb->remove(DEFAULT_SAVE); + } + + return true; + } + else + { +#ifdef HAVE_ADJUSTABLE_CPU_FREQ + rb->cpu_boost (false); +#endif + return false; + } +} + + +static void +pre_game_setup (void) +{ + rb->memset (&header, 0, sizeof (header)); + + clear_caches_sgf (); + free_tree_sgf (); + + set_size_board (MAX_BOARD_SIZE, MAX_BOARD_SIZE); + + clear_board (); + + game_dirty = true; + move_num = 0; + + play_mode = MODE_PLAY; + + rb->strcpy (save_file, DEFAULT_SAVE); + + header_marked = false; +} + + +bool +setup_game (int width, int height, int handicap, int komi) +{ + pre_game_setup (); + + if (!set_size_board (width, height)) + { + return false; + } + + clear_board (); + + /* place handicap */ + if (handicap >= 2) + { + current_player = WHITE; + } + else if (handicap < 0) + { + return false; + } + else + { + current_player = BLACK; + } + + header.handicap = handicap; + setup_handicap_sgf (); + + header.komi = komi; + + post_game_setup_sgf (); + + return true; +} diff --git a/pool/shard000/C/0012161_pic.c b/pool/shard000/C/0012161_pic.c new file mode 100644 index 0000000000000000000000000000000000000000..b0b543cb0699df15f739da78a4c973e203cd5221 --- /dev/null +++ b/pool/shard000/C/0012161_pic.c @@ -0,0 +1,37 @@ +#include +#include +#include +#include +#include + +#include +#include +#include + +void IRQ_set_mask(unsigned char IRQline) { + uint16_t port; + uint8_t value; + + if(IRQline < 8) { + port = PIC1_DATA; + } else { + port = PIC2_DATA; + IRQline -= 8; + } + value = inb(port) | (1 << IRQline); + outb(port, value); +} + +void IRQ_clear_mask(unsigned char IRQline) { + uint16_t port; + uint8_t value; + + if(IRQline < 8) { + port = PIC1_DATA; + } else { + port = PIC2_DATA; + IRQline -= 8; + } + value = inb(port) & ~(1 << IRQline); + outb(port, value); +} diff --git a/pool/shard000/C/0012162_decrypt.c b/pool/shard000/C/0012162_decrypt.c new file mode 100644 index 0000000000000000000000000000000000000000..6f5e69b1d38230cc050421007294ea1a5d4cdb20 --- /dev/null +++ b/pool/shard000/C/0012162_decrypt.c @@ -0,0 +1,51 @@ +/* + * + * University of Luxembourg + * Laboratory of Algorithmics, Cryptology and Security (LACS) + * + * FELICS - Fair Evaluation of Lightweight Cryptographic Systems + * + * Copyright (C) 2015 University of Luxembourg + * + * Written in 2015 by Yann Le Corre + * + * This file is part of FELICS. + * + * FELICS 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. + * + * FELICS is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see . + * + */ + +#include + +#include "cipher.h" +#include "constants.h" +#include "primitives.h" + +void Decrypt(uint8_t *block, uint8_t *roundKeys) +{ + int8_t i; + uint32_t *rk = (uint32_t *)roundKeys; + uint32_t *rightPtr = (uint32_t *)block; + uint32_t *leftPtr = rightPtr + 1; + uint32_t tmp; + uint32_t k; + + for (i = NUMBER_OF_ROUNDS - 1; i >= 0; i--) + { + k = READ_ROUND_KEY_DOUBLE_WORD(rk[i]); + tmp = *rightPtr; + *rightPtr = f(*rightPtr) ^ *leftPtr ^ k; + *leftPtr = tmp; + } +} diff --git a/pool/shard000/C/0012169_nvdimm.c b/pool/shard000/C/0012169_nvdimm.c new file mode 100644 index 0000000000000000000000000000000000000000..db896b0bb6fc92c4194a93ed7032e4c273f1439d --- /dev/null +++ b/pool/shard000/C/0012169_nvdimm.c @@ -0,0 +1,176 @@ +/* + * Non-Volatile Dual In-line Memory Module Virtualization Implementation + * + * Copyright(C) 2015 Intel Corporation. + * + * Author: + * Xiao Guangrong + * + * Currently, it only supports PMEM Virtualization. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see + */ + +#include "qemu/osdep.h" +#include "qapi/error.h" +#include "qapi/visitor.h" +#include "hw/mem/nvdimm.h" + +static void nvdimm_get_label_size(Object *obj, Visitor *v, const char *name, + void *opaque, Error **errp) +{ + NVDIMMDevice *nvdimm = NVDIMM(obj); + uint64_t value = nvdimm->label_size; + + visit_type_size(v, name, &value, errp); +} + +static void nvdimm_set_label_size(Object *obj, Visitor *v, const char *name, + void *opaque, Error **errp) +{ + NVDIMMDevice *nvdimm = NVDIMM(obj); + Error *local_err = NULL; + uint64_t value; + + if (memory_region_size(&nvdimm->nvdimm_mr)) { + error_setg(&local_err, "cannot change property value"); + goto out; + } + + visit_type_size(v, name, &value, &local_err); + if (local_err) { + goto out; + } + if (value < MIN_NAMESPACE_LABEL_SIZE) { + error_setg(&local_err, "Property '%s.%s' (0x%" PRIx64 ") is required" + " at least 0x%lx", object_get_typename(obj), + name, value, MIN_NAMESPACE_LABEL_SIZE); + goto out; + } + + nvdimm->label_size = value; +out: + error_propagate(errp, local_err); +} + +static void nvdimm_init(Object *obj) +{ + object_property_add(obj, "label-size", "int", + nvdimm_get_label_size, nvdimm_set_label_size, NULL, + NULL, NULL); +} + +static MemoryRegion *nvdimm_get_memory_region(PCDIMMDevice *dimm) +{ + NVDIMMDevice *nvdimm = NVDIMM(dimm); + + return &nvdimm->nvdimm_mr; +} + +static void nvdimm_realize(PCDIMMDevice *dimm, Error **errp) +{ + MemoryRegion *mr = host_memory_backend_get_memory(dimm->hostmem, errp); + NVDIMMDevice *nvdimm = NVDIMM(dimm); + uint64_t align, pmem_size, size = memory_region_size(mr); + + align = memory_region_get_alignment(mr); + + pmem_size = size - nvdimm->label_size; + nvdimm->label_data = memory_region_get_ram_ptr(mr) + pmem_size; + pmem_size = QEMU_ALIGN_DOWN(pmem_size, align); + + if (size <= nvdimm->label_size || !pmem_size) { + HostMemoryBackend *hostmem = dimm->hostmem; + char *path = object_get_canonical_path_component(OBJECT(hostmem)); + + error_setg(errp, "the size of memdev %s (0x%" PRIx64 ") is too " + "small to contain nvdimm label (0x%" PRIx64 ") and " + "aligned PMEM (0x%" PRIx64 ")", + path, memory_region_size(mr), nvdimm->label_size, align); + g_free(path); + return; + } + + memory_region_init_alias(&nvdimm->nvdimm_mr, OBJECT(dimm), + "nvdimm-memory", mr, 0, pmem_size); + nvdimm->nvdimm_mr.align = align; +} + +/* + * the caller should check the input parameters before calling + * label read/write functions. + */ +static void nvdimm_validate_rw_label_data(NVDIMMDevice *nvdimm, uint64_t size, + uint64_t offset) +{ + assert((nvdimm->label_size >= size + offset) && (offset + size > offset)); +} + +static void nvdimm_read_label_data(NVDIMMDevice *nvdimm, void *buf, + uint64_t size, uint64_t offset) +{ + nvdimm_validate_rw_label_data(nvdimm, size, offset); + + memcpy(buf, nvdimm->label_data + offset, size); +} + +static void nvdimm_write_label_data(NVDIMMDevice *nvdimm, const void *buf, + uint64_t size, uint64_t offset) +{ + MemoryRegion *mr; + PCDIMMDevice *dimm = PC_DIMM(nvdimm); + uint64_t backend_offset; + + nvdimm_validate_rw_label_data(nvdimm, size, offset); + + memcpy(nvdimm->label_data + offset, buf, size); + + mr = host_memory_backend_get_memory(dimm->hostmem, &error_abort); + backend_offset = memory_region_size(mr) - nvdimm->label_size + offset; + memory_region_set_dirty(mr, backend_offset, size); +} + +static MemoryRegion *nvdimm_get_vmstate_memory_region(PCDIMMDevice *dimm) +{ + return host_memory_backend_get_memory(dimm->hostmem, &error_abort); +} + +static void nvdimm_class_init(ObjectClass *oc, void *data) +{ + PCDIMMDeviceClass *ddc = PC_DIMM_CLASS(oc); + NVDIMMClass *nvc = NVDIMM_CLASS(oc); + + ddc->realize = nvdimm_realize; + ddc->get_memory_region = nvdimm_get_memory_region; + ddc->get_vmstate_memory_region = nvdimm_get_vmstate_memory_region; + + nvc->read_label_data = nvdimm_read_label_data; + nvc->write_label_data = nvdimm_write_label_data; +} + +static TypeInfo nvdimm_info = { + .name = TYPE_NVDIMM, + .parent = TYPE_PC_DIMM, + .class_size = sizeof(NVDIMMClass), + .class_init = nvdimm_class_init, + .instance_size = sizeof(NVDIMMDevice), + .instance_init = nvdimm_init, +}; + +static void nvdimm_register_types(void) +{ + type_register_static(&nvdimm_info); +} + +type_init(nvdimm_register_types) diff --git a/pool/shard000/C/0012190_xalloc.c b/pool/shard000/C/0012190_xalloc.c new file mode 100644 index 0000000000000000000000000000000000000000..914c1042bc9384edec590e2510f13bc5d997a42c --- /dev/null +++ b/pool/shard000/C/0012190_xalloc.c @@ -0,0 +1,141 @@ +/*:ts=8*/ +/***************************************************************************** + * FIDOGATE --- Gateway UNIX Mail/News <-> FIDO NetMail/EchoMail + * + * $Id$ + * + * Safe memory allocation functions + * + ***************************************************************************** + * Copyright (C) 1990-2002 + * _____ _____ + * | |___ | Martin Junius FIDO: 2:2452/110 + * | | | | | | Radiumstr. 18 Internet: mj@fidogate.org + * |_|_|_|@home| D-51069 Koeln, Germany + * + * This file is part of FIDOGATE. + * + * FIDOGATE is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2, or (at your option) any + * later version. + * + * FIDOGATE 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 FIDOGATE; see the file COPYING. If not, write to the Free + * Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. + *****************************************************************************/ + +#include "fidogate.h" + + +/* + * Global buffer for temporary usage + */ +char buffer[BUFFERSIZE]; + + + +/* + * xmalloc(), xrealloc() --- safe versions of malloc() and realloc() + */ +void *xmalloc(int size) +{ + char *p; + + if( (p = malloc(size)) ) + return p; + fprintf(stderr, "Memory exhausted."); + exit(EX_OSERR); + + /**NOT REACHED**/ + return NULL; +} + + +void *xrealloc(void *ptr, int size) +{ + char *p; + + if( (p = realloc(ptr, size)) ) + return p; + fprintf(stderr, "Memory exhausted."); + exit(EX_OSERR); + + /**NOT REACHED**/ + return NULL; +} + + +/* + * xfree() --- free() with check for NULL pointer (is safe according to + * Standard-C, but older libraries may not check this) + */ +void xfree(void *p) +{ + if(p) + free(p); +} + + +/* + * strsave() --- make a copy of a string + */ +char *strsave(char *s) +{ + char *p = NULL; + size_t len; + + if(s) + { + len = strlen(s) + 1; + p = xmalloc(len); + str_copy(p, len, s); + } + return p; +} + + +char *strsave2(char *s1, char *s2) +{ + char *p; + size_t len; + + if(!s1 || !s2) + return NULL; + + len = strlen(s1) + strlen(s2) + 1; + p = xmalloc(len); + str_copy2(p, len, s1, s2); + + return p; +} + +void exit_free(void) +{ + passwd_free(); + debug(9, "passwd_free()"); + + hosts_free(); + debug(9, "hosts_free()"); + + uplinks_free(); + debug(9, "uplinks_free()"); + + areasbbs_free(); + debug(9, "areasbbs_free()"); + + config_free(); + debug(9, "config_free()"); + +#ifdef FTN_ACL + acl_ftn_free(); + debug(9, "acl_ftn_free()"); +#endif /* FTN_ACL */ + charset_free(); + debug(9, "charset_free()"); +} diff --git a/pool/shard000/C/0012208_wocky-xmpp-readwrite-test.c b/pool/shard000/C/0012208_wocky-xmpp-readwrite-test.c new file mode 100644 index 0000000000000000000000000000000000000000..c6579d31defc92429008ecc88fa16f0c1bdadc69 --- /dev/null +++ b/pool/shard000/C/0012208_wocky-xmpp-readwrite-test.c @@ -0,0 +1,220 @@ +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include +#include + +#include + +#include + +#include "wocky-test-helper.h" + +#define TO "example.net" +#define FROM "julliet@example.com" +#define XMPP_VERSION "1.0" +#define LANG "en" +#define DUMMY_NS "urn:wocky:test:blah:blah:blah" + +static WockyStanza * +create_stanza (void) +{ + WockyStanza *stanza; + WockyNode *html; + WockyNode *head; + + stanza = wocky_stanza_build (WOCKY_STANZA_TYPE_MESSAGE, + WOCKY_STANZA_SUB_TYPE_CHAT, "juliet@example.com", "romeo@example.net", + '(', "html", ':', "http://www.w3.org/1999/xhtml", + '(', "body", + '$', "Art thou not Romeo, and a Montague?", + ')', + ')', + NULL); + + html = wocky_node_get_child (wocky_stanza_get_top_node (stanza), "html"); + head = wocky_node_add_child (html, "head"); + wocky_node_set_attribute_ns (head, "rev", "0xbad1dea", DUMMY_NS); + + return stanza; +} + +static void +test_readwrite (void) +{ + WockyXmppReader *reader; + WockyXmppWriter *writer; + WockyStanza *received = NULL, *sent; + const guint8 *data; + gsize length; + gchar *to, *from, *version, *lang; + int i; + + writer = wocky_xmpp_writer_new (); + reader = wocky_xmpp_reader_new (); + + g_assert (wocky_xmpp_reader_get_state (reader) + == WOCKY_XMPP_READER_STATE_INITIAL); + + wocky_xmpp_writer_stream_open (writer, TO, FROM, XMPP_VERSION, LANG, NULL, + &data, &length); + wocky_xmpp_reader_push (reader, data, length); + + g_assert (wocky_xmpp_reader_get_state (reader) + == WOCKY_XMPP_READER_STATE_OPENED); + + g_object_get (reader, + "to", &to, + "from", &from, + "version", &version, + "lang", &lang, + NULL); + + g_assert (!wocky_strdiff (to, TO)); + g_assert (!wocky_strdiff (from, FROM)); + g_assert (!wocky_strdiff (version, XMPP_VERSION)); + g_assert (!wocky_strdiff (lang, LANG)); + + g_free (to); + g_free (from); + g_free (version); + g_free (lang); + + sent = create_stanza (); + + for (i = 0; i < 3 ; i++) + { + WockyNode *html; + WockyNode *head; + const gchar *attr_recv = NULL; + const gchar *attr_send = NULL; + const gchar *attr_none = NULL; + + g_assert (wocky_xmpp_reader_get_state (reader) + == WOCKY_XMPP_READER_STATE_OPENED); + + wocky_xmpp_writer_write_stanza (writer, sent, &data, &length); + wocky_xmpp_reader_push (reader, data, length); + + received = wocky_xmpp_reader_pop_stanza (reader); + + g_assert (received != NULL); + test_assert_stanzas_equal (sent, received); + + html = wocky_node_get_child (wocky_stanza_get_top_node (received), + "html"); + head = wocky_node_get_child (html, "head"); + attr_recv = wocky_node_get_attribute_ns (head, "rev", DUMMY_NS); + attr_none = wocky_node_get_attribute_ns (head, "rev", + DUMMY_NS ":x"); + + html = wocky_node_get_child (wocky_stanza_get_top_node (sent), + "html"); + head = wocky_node_get_child (html, "head"); + attr_send = wocky_node_get_attribute_ns (head, "rev", DUMMY_NS); + + g_assert (attr_none == NULL); + g_assert (attr_recv != NULL); + g_assert (attr_send != NULL); + g_assert (!strcmp (attr_send, attr_recv)); + + + g_object_unref (received); + + /* No more stanzas in the queue */ + received = wocky_xmpp_reader_pop_stanza (reader); + g_assert (received == NULL); + } + + wocky_xmpp_writer_write_stanza (writer, sent, &data, &length); + wocky_xmpp_reader_push (reader, data, length); + + wocky_xmpp_writer_stream_close (writer, &data, &length); + wocky_xmpp_reader_push (reader, data, length); + + /* Stream state should stay open until we popped the last stanza */ + g_assert (wocky_xmpp_reader_get_state (reader) + == WOCKY_XMPP_READER_STATE_OPENED); + + received = wocky_xmpp_reader_pop_stanza (reader); + g_assert (received != NULL); + test_assert_stanzas_equal (sent, received); + + g_object_unref (received); + + /* Last stanza pop, stream should be closed */ + g_assert (wocky_xmpp_reader_get_state (reader) + == WOCKY_XMPP_READER_STATE_CLOSED); + + /* No more stanzas in the queue */ + received = wocky_xmpp_reader_pop_stanza (reader); + g_assert (received == NULL); + + g_object_unref (sent); + g_object_unref (reader); + g_object_unref (writer); +} + +static void +test_readwrite_nostream (void) +{ + WockyXmppReader *reader; + WockyXmppWriter *writer; + WockyStanza *received = NULL, *sent; + const guint8 *data; + gsize length; + int i; + + writer = wocky_xmpp_writer_new_no_stream (); + reader = wocky_xmpp_reader_new_no_stream (); + + sent = create_stanza (); + + + for (i = 0 ; i < 3 ; i++) + { + g_assert (wocky_xmpp_reader_get_state (reader) + == WOCKY_XMPP_READER_STATE_OPENED); + + wocky_xmpp_writer_write_stanza (writer, sent, &data, &length); + wocky_xmpp_reader_push (reader, data, length); + + g_assert (wocky_xmpp_reader_get_state (reader) + == WOCKY_XMPP_READER_STATE_OPENED); + + received = wocky_xmpp_reader_pop_stanza (reader); + + g_assert (received != NULL); + test_assert_stanzas_equal (sent, received); + + g_assert (wocky_xmpp_reader_get_state (reader) == + WOCKY_XMPP_READER_STATE_CLOSED); + + wocky_xmpp_reader_reset (reader); + + g_object_unref (received); + } + + g_object_unref (sent); + g_object_unref (reader); + g_object_unref (writer); +} + +int +main (int argc, + char **argv) +{ + int result; + + test_init (argc, argv); + + g_test_add_func ("/xmpp-readwrite/readwrite", test_readwrite); + g_test_add_func ("/xmpp-readwrite/readwrite-nostream", + test_readwrite_nostream); + + result = g_test_run (); + test_deinit (); + return result; +} diff --git a/pool/shard000/C/0012212_bind.c b/pool/shard000/C/0012212_bind.c new file mode 100644 index 0000000000000000000000000000000000000000..039f079798522beefd1d617f459d6d93fa819716 --- /dev/null +++ b/pool/shard000/C/0012212_bind.c @@ -0,0 +1,82 @@ +/* $NetBSD: bind.c,v 1.1.1.4 2014/05/28 09:58:51 tron Exp $ */ + +/* bind.c - sock backend bind function */ +/* $OpenLDAP$ */ +/* This work is part of OpenLDAP Software . + * + * Copyright 2007-2014 The OpenLDAP Foundation. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted only as authorized by the OpenLDAP + * Public License. + * + * A copy of this license is available in the file LICENSE in the + * top-level directory of the distribution or, alternatively, at + * . + */ +/* ACKNOWLEDGEMENTS: + * This work was initially developed by Brian Candler for inclusion + * in OpenLDAP Software. + */ + +#include "portable.h" + +#include + +#include +#include + +#include "slap.h" +#include "back-sock.h" + +int +sock_back_bind( + Operation *op, + SlapReply *rs ) +{ + struct sockinfo *si = (struct sockinfo *) op->o_bd->be_private; + AttributeDescription *entry = slap_schema.si_ad_entry; + Entry e; + FILE *fp; + int rc; + + e.e_id = NOID; + e.e_name = op->o_req_dn; + e.e_nname = op->o_req_ndn; + e.e_attrs = NULL; + e.e_ocflags = 0; + e.e_bv.bv_len = 0; + e.e_bv.bv_val = NULL; + e.e_private = NULL; + + if ( ! access_allowed( op, &e, + entry, NULL, ACL_AUTH, NULL ) ) + { + send_ldap_error( op, rs, LDAP_INSUFFICIENT_ACCESS, NULL ); + return -1; + } + + if ( (fp = opensock( si->si_sockpath )) == NULL ) { + send_ldap_error( op, rs, LDAP_OTHER, + "could not open socket" ); + return( -1 ); + } + + /* write out the request to the bind process */ + fprintf( fp, "BIND\n" ); + fprintf( fp, "msgid: %ld\n", (long) op->o_msgid ); + sock_print_conn( fp, op->o_conn, si ); + sock_print_suffixes( fp, op->o_bd ); + fprintf( fp, "dn: %s\n", op->o_req_dn.bv_val ); + fprintf( fp, "method: %d\n", op->oq_bind.rb_method ); + fprintf( fp, "credlen: %lu\n", op->oq_bind.rb_cred.bv_len ); + fprintf( fp, "cred: %s\n", op->oq_bind.rb_cred.bv_val ); /* XXX */ + fprintf( fp, "\n" ); + + /* read in the results and send them along */ + rc = sock_read_and_send_results( op, rs, fp ); + fclose( fp ); + + return( rc ); +} diff --git a/pool/shard000/C/0012223_5.htio.c b/pool/shard000/C/0012223_5.htio.c new file mode 100644 index 0000000000000000000000000000000000000000..df4c3e87078a4555ed264da64670d127347eaf8e --- /dev/null +++ b/pool/shard000/C/0012223_5.htio.c @@ -0,0 +1,46 @@ +#include + +int htoi(char[]); + +main() +{ + int n = htoi("0x123abc"); + printf("%d\n", n); + n = htoi("0X123abc"); + printf("%d\n", n); + n = htoi("123abc"); + printf("%d\n", n); + n = htoi("FF"); + printf("%d\n", n); + n = htoi("1F"); + printf("%d\n", n); + n = htoi("D"); + printf("%d\n", n); + n = htoi("3"); + printf("%d\n", n); + n = htoi("3FQWE"); + printf("%d\n", n); +} + +int htoi(char s[]) +{ + int i, n; + n = 0; + for (i = 0; ; ++i) { + if (s[i] == '0' && (s[i+1] == 'x' || s[i+1] == 'X')) { + i++; + continue; + } + + if (s[i] >= '0' && s[i] <= '9') { + n = 16 * n + (s[i] - '0'); + } else if (s[i] >= 'a' && s[i] <= 'f') { + n = 16 * n + (s[i] - 'a' + 10); + } else if (s[i] >= 'A' && s[i] <= 'F') { + n = 16 * n + (s[i] - 'A' + 10); + } else { + break; + } + } + return n; +} diff --git a/pool/shard000/C/0012236_mulodi4.c b/pool/shard000/C/0012236_mulodi4.c new file mode 100644 index 0000000000000000000000000000000000000000..9891bbf1af7984c57d3dca93b0cb574b3410a457 --- /dev/null +++ b/pool/shard000/C/0012236_mulodi4.c @@ -0,0 +1,67 @@ +/*===-- mulodi4.c - Implement __mulodi4 -----------------------------------=== + * + * The LLVM Compiler Infrastructure + * + * This file is dual licensed under the MIT and the University of Illinois Open + * Source Licenses. See LICENSE.TXT for details. + * + * ===----------------------------------------------------------------------=== + * + * This file implements __mulodi4 for the compiler_rt library. + * + * ===----------------------------------------------------------------------=== + */ + +#if 0 +#include "int_lib.h" +#else +#define COMPILER_RT_ABI +#define di_int int64_t +#define di_uint uint64_t +#include "torint.h" + +di_int __mulodi4(di_int a, di_int b, int* overflow); +#endif + +/* Returns: a * b */ + +/* Effects: sets *overflow to 1 if a * b overflows */ + +COMPILER_RT_ABI di_int +__mulodi4(di_int a, di_int b, int* overflow) +{ + const int N = (int)(sizeof(di_int) * CHAR_BIT); + const di_int MIN = (di_int) ((di_uint)1 << (N-1)); + const di_int MAX = ~MIN; + *overflow = 0; + di_int result = a * b; + if (a == MIN) + { + if (b != 0 && b != 1) + *overflow = 1; + return result; + } + if (b == MIN) + { + if (a != 0 && a != 1) + *overflow = 1; + return result; + } + di_int sa = a >> (N - 1); + di_int abs_a = (a ^ sa) - sa; + di_int sb = b >> (N - 1); + di_int abs_b = (b ^ sb) - sb; + if (abs_a < 2 || abs_b < 2) + return result; + if (sa == sb) + { + if (abs_a > MAX / abs_b) + *overflow = 1; + } + else + { + if (abs_a > MIN / -abs_b) + *overflow = 1; + } + return result; +} diff --git a/pool/shard000/C/0012240_garmin_device_xml.c b/pool/shard000/C/0012240_garmin_device_xml.c new file mode 100644 index 0000000000000000000000000000000000000000..981883b2adff66496465b2f6ad1851a902d75984 --- /dev/null +++ b/pool/shard000/C/0012240_garmin_device_xml.c @@ -0,0 +1,145 @@ +/* + Parse 'GarminDevice.xml' on a Garmin mass storage device (e.g. Zumo, + Nuvi, Colorado, etc. and return key device info. + + Copyright (C) 2008 Robert Lipe, robertlipe@gpsbabel.org + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111 USA + + */ + +// References: +// http://developer.garmin.com/web-device/garmin-mass-storage-mode-devices/ +// http://developer.garmin.com/schemas/device/v2/ + +#include "defs.h" +#include "xmlgeneric.h" +#include "garmin_device_xml.h" + +#define MYNAME "whatever" + +static gdx_info *my_gdx_info; +static int type; +static char *mountpoint, *base, *path, *ext; +static xg_callback device_s, id_s, path_s, ext_s, base_s, dir_s; + +void type_s(const char *args, const char **unused) { + type = strcmp(args, "GPSData"); +} + +void device_s(const char *args, const char **unused) { + if (my_gdx_info) { + fatal(MYNAME ": More than one device type found in file.\n"); + } + my_gdx_info = xcalloc(sizeof *my_gdx_info, 1); + my_gdx_info->device_desc = xstrdup(args); +} + +void id_s(const char *args, const char **unused) { + my_gdx_info->device_id = xstrdup(args); +} + +void path_s(const char *args, const char **unused) { + path = xstrdup(args); +} + +void ext_s(const char *args, const char **unused) { + ext = xstrdup(args); +} + +void base_s(const char *args, const char **unused) { + base = xstrdup(args); +} + +void dir_s(const char *args, const char **unused) { + if (type) + return; + if (0 == strcmp(args, "OutputFromUnit")) { + xasprintf(&my_gdx_info->from_device.path, "%s%c%s", + mountpoint, GB_PATHSEP, path); + my_gdx_info->from_device.basename = xstrdup(base); + my_gdx_info->from_device.extension = xstrdup(ext); + xasprintf(&my_gdx_info->from_device.canon, "%s/%s.%s", + my_gdx_info->from_device.path, + my_gdx_info->from_device.basename, + my_gdx_info->from_device.extension); + } else + if (0 == strcmp(args, "InputToUnit")) { + xasprintf(&my_gdx_info->to_device.path, "%s%c%s", + mountpoint, GB_PATHSEP, path); + my_gdx_info->to_device.basename = xstrdup(base); + my_gdx_info->to_device.extension = xstrdup(ext); + } else + fatal(MYNAME ":Unknown direction '%s'\n", args); + + if (base) xfree(base) ; + base = NULL; + + if (ext) xfree(ext) ; + ext = NULL; + + if (path) xfree(path) ; + path = NULL; +} + +static xg_tag_mapping gdx_map[] = { + { device_s, cb_cdata, "/Device/Model/Description" }, + { id_s, cb_cdata, "/Device/Id" }, + { path_s, cb_cdata, "/Device/MassStorageMode/DataType/File/Location/Path" }, + { type_s, cb_cdata, "/Device/MassStorageMode/DataType/Name" }, + { ext_s, cb_cdata, "/Device/MassStorageMode/DataType/File/Location/FileExtension" }, + { base_s, cb_cdata, "/Device/MassStorageMode/DataType/File/Location/BaseName" }, + { dir_s, cb_cdata, "/Device/MassStorageMode/DataType/File/TransferDirection" }, + { 0, 0, NULL } +}; + +const gdx_info * +gdx_read(const char *fname) { + // Test file open-able before gb_open gets a chance to fatal(). + FILE *fin = fopen(fname, "r"); + + if (fin) { + fclose(fin); + xml_init(fname, gdx_map, NULL); + xml_read(); + xml_deinit(); + } + + return my_gdx_info; +} + + +// Look for the Device in the incoming NULL-terminated list of directories +const gdx_info * +gdx_find_file(char **dirlist) { + const gdx_info *gdx; + while (dirlist && *dirlist) { + char *tbuf; + xasprintf(&tbuf, "%s/%s", *dirlist, "/Garmin/GarminDevice.xml"); + mountpoint = *dirlist; + gdx = gdx_read(tbuf); + xfree(tbuf); + if (gdx) { + longjmp(gdx_jmp_buf, 1); + } + dirlist++; + } + return NULL; +} + +const gdx_info * +gdx_get_info() { + return my_gdx_info; +} diff --git a/pool/shard000/C/0012241_IxEthAcc.c b/pool/shard000/C/0012241_IxEthAcc.c new file mode 100644 index 0000000000000000000000000000000000000000..8f4eb924e9cf6b6ec1680746dc092a26acb0b9d6 --- /dev/null +++ b/pool/shard000/C/0012241_IxEthAcc.c @@ -0,0 +1,296 @@ +/* Copyright Statement: + * + * This software/firmware and related documentation ("MediaTek Software") are + * protected under relevant copyright laws. The information contained herein + * is confidential and proprietary to MediaTek Inc. and/or its licensors. + * Without the prior written permission of MediaTek inc. and/or its licensors, + * any reproduction, modification, use or disclosure of MediaTek Software, + * and information contained herein, in whole or in part, shall be strictly prohibited. + * + * MediaTek Inc. (C) 2010. All rights reserved. + * + * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES + * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") + * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON + * AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT. + * NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE + * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR + * SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH + * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES + * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES + * CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK + * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR + * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND + * CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, + * AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE, + * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO + * MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. + * + * The following software/firmware and/or related documentation ("MediaTek Software") + * have been modified by MediaTek Inc. All revisions are subject to any receiver's + * applicable license agreements with MediaTek Inc. + */ + +/** + * @file IxEthAcc.c + * + * @author Intel Corporation + * @date 20-Feb-2001 + * + * @brief This file contains the implementation of the IXP425 Ethernet Access Component + * + * Design Notes: + * + * @par + * IXP400 SW Release version 2.0 + * + * -- Copyright Notice -- + * + * @par + * Copyright 2001-2005, Intel Corporation. + * All rights reserved. + * + * @par + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the 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. + * + * @par + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @par + * -- End of Copyright Notice -- + */ + + + +#include "IxEthAcc.h" +#ifdef CONFIG_IXP425_COMPONENT_ETHDB +#include "IxEthDB.h" +#endif +#include "IxFeatureCtrl.h" + +#include "IxEthAcc_p.h" +#include "IxEthAccMac_p.h" +#include "IxEthAccMii_p.h" + +/** + * @addtogroup IxEthAcc + *@{ + */ + + +/** + * @brief System-wide information data strucure. + * + * @ingroup IxEthAccPri + * + */ + +IxEthAccInfo ixEthAccDataInfo; +extern PUBLIC IxEthAccMacState ixEthAccMacState[]; +extern PUBLIC IxOsalMutex ixEthAccControlInterfaceMutex; + +/** + * @brief System-wide information + * + * @ingroup IxEthAccPri + * + */ +BOOL ixEthAccServiceInit = FALSE; + +/* global filtering bit mask */ +PUBLIC UINT32 ixEthAccNewSrcMask; + +/** + * @brief Per port information data strucure. + * + * @ingroup IxEthAccPri + * + */ + +IxEthAccPortDataInfo ixEthAccPortData[IX_ETH_ACC_NUMBER_OF_PORTS]; + +PUBLIC IxEthAccStatus ixEthAccInit() +{ +#ifdef CONFIG_IXP425_COMPONENT_ETHDB + /* + * Initialize Control plane + */ + if (ixEthDBInit() != IX_ETH_ACC_SUCCESS) + { + IX_ETH_ACC_WARNING_LOG("ixEthAccInit: EthDB init failed\n", 0, 0, 0, 0, 0, 0); + + return IX_ETH_ACC_FAIL; + } +#endif + + if (IX_FEATURE_CTRL_SWCONFIG_ENABLED == ixFeatureCtrlSwConfigurationCheck (IX_FEATURECTRL_ETH_LEARNING)) + { + ixEthAccNewSrcMask = (~0); /* want all the bits */ + } + else + { + ixEthAccNewSrcMask = (~IX_ETHACC_NE_NEWSRCMASK); /* want all but the NewSrc bit */ + } + + /* + * Initialize Data plane + */ + if ( ixEthAccInitDataPlane() != IX_ETH_ACC_SUCCESS ) + { + IX_ETH_ACC_WARNING_LOG("ixEthAccInit: data plane init failed\n", 0, 0, 0, 0, 0, 0); + + return IX_ETH_ACC_FAIL; + } + + + if ( ixEthAccQMgrQueuesConfig() != IX_ETH_ACC_SUCCESS ) + { + IX_ETH_ACC_WARNING_LOG("ixEthAccInit: queue config failed\n", 0, 0, 0, 0, 0, 0); + + return IX_ETH_ACC_FAIL; + } + + /* + * Initialize MII + */ + if ( ixEthAccMiiInit() != IX_ETH_ACC_SUCCESS ) + { + IX_ETH_ACC_WARNING_LOG("ixEthAccInit: Mii init failed\n", 0, 0, 0, 0, 0, 0); + + return IX_ETH_ACC_FAIL; + } + + /* + * Initialize MAC I/O memory + */ + if (ixEthAccMacMemInit() != IX_ETH_ACC_SUCCESS) + { + IX_ETH_ACC_WARNING_LOG("ixEthAccInit: Mac init failed\n", 0, 0, 0, 0, 0, 0); + + return IX_ETH_ACC_FAIL; + } + + /* + * Initialize control plane interface lock + */ + if (ixOsalMutexInit(&ixEthAccControlInterfaceMutex) != IX_SUCCESS) + { + IX_ETH_ACC_WARNING_LOG("ixEthAccInit: Control plane interface lock initialization failed\n", 0, 0, 0, 0, 0, 0); + + return IX_ETH_ACC_FAIL; + } + + /* initialiasation is complete */ + ixEthAccServiceInit = TRUE; + + return IX_ETH_ACC_SUCCESS; + +} + +PUBLIC void ixEthAccUnload(void) +{ + IxEthAccPortId portId; + + if ( IX_ETH_ACC_IS_SERVICE_INITIALIZED() ) + { + /* check none of the port is still active */ + for (portId = 0; portId < IX_ETH_ACC_NUMBER_OF_PORTS; portId++) + { + if ( IX_ETH_IS_PORT_INITIALIZED(portId) ) + { + if (ixEthAccMacState[portId].portDisableState == ACTIVE) + { + IX_ETH_ACC_WARNING_LOG("ixEthAccUnload: port %u still active, bail out\n", portId, 0, 0, 0, 0, 0); + return; + } + } + } + + /* unmap the memory areas */ + ixEthAccMiiUnload(); + ixEthAccMacUnload(); + + /* set all ports as uninitialized */ + for (portId = 0; portId < IX_ETH_ACC_NUMBER_OF_PORTS; portId++) + { + ixEthAccPortData[portId].portInitialized = FALSE; + } + + /* uninitialize the service */ + ixEthAccServiceInit = FALSE; + } +} + +PUBLIC IxEthAccStatus ixEthAccPortInit( IxEthAccPortId portId) +{ + + IxEthAccStatus ret=IX_ETH_ACC_SUCCESS; + + if ( ! IX_ETH_ACC_IS_SERVICE_INITIALIZED() ) + { + return(IX_ETH_ACC_FAIL); + } + + /* + * Check for valid port + */ + + if ( ! IX_ETH_ACC_IS_PORT_VALID(portId) ) + { + return (IX_ETH_ACC_INVALID_PORT); + } + + if (IX_ETH_ACC_SUCCESS != ixEthAccSingleEthNpeCheck(portId)) + { + IX_ETH_ACC_WARNING_LOG("EthAcc: Unavailable Eth %d: Cannot initialize Eth port.\n",(INT32) portId,0,0,0,0,0); + return IX_ETH_ACC_SUCCESS ; + } + + if ( IX_ETH_IS_PORT_INITIALIZED(portId) ) + { + /* Already initialized */ + return(IX_ETH_ACC_FAIL); + } + + if(ixEthAccMacInit(portId)!=IX_ETH_ACC_SUCCESS) + { + return IX_ETH_ACC_FAIL; + } + + /* + * Set the port init flag. + */ + + ixEthAccPortData[portId].portInitialized = TRUE; + +#ifdef CONFIG_IXP425_COMPONENT_ETHDB + /* init learning/filtering database structures for this port */ + ixEthDBPortInit(portId); +#endif + + return(ret); +} + + diff --git a/pool/shard000/C/0012248_sgbuf.c b/pool/shard000/C/0012248_sgbuf.c new file mode 100644 index 0000000000000000000000000000000000000000..91f16ac937ffd62f1fd38fc18bd45c3b067eb1a6 --- /dev/null +++ b/pool/shard000/C/0012248_sgbuf.c @@ -0,0 +1,108 @@ +/* + * Scatter-Gather buffer + * + * Copyright (c) by Takashi Iwai + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +#include +#include +#include +#include + + +/* table entries are align to 32 */ +#define SGBUF_TBL_ALIGN 32 +#define sgbuf_align_table(tbl) ALIGN((tbl), SGBUF_TBL_ALIGN) + +int snd_free_sgbuf_pages(struct snd_dma_buffer *dmab) +{ + struct snd_sg_buf *sgbuf = dmab->private_data; + struct snd_dma_buffer tmpb; + int i; + + if (! sgbuf) + return -EINVAL; + + if (dmab->area) + vunmap(dmab->area); + dmab->area = NULL; + + tmpb.dev.type = SNDRV_DMA_TYPE_DEV; + tmpb.dev.dev = sgbuf->dev; + for (i = 0; i < sgbuf->pages; i++) { + tmpb.area = sgbuf->table[i].buf; + tmpb.addr = sgbuf->table[i].addr; + tmpb.bytes = PAGE_SIZE; + snd_dma_free_pages(&tmpb); + } + + kfree(sgbuf->table); + kfree(sgbuf->page_table); + kfree(sgbuf); + dmab->private_data = NULL; + + return 0; +} + +void *snd_malloc_sgbuf_pages(struct device *device, + size_t size, struct snd_dma_buffer *dmab, + size_t *res_size) +{ + struct snd_sg_buf *sgbuf; + unsigned int i, pages; + struct snd_dma_buffer tmpb; + + dmab->area = NULL; + dmab->addr = 0; + dmab->private_data = sgbuf = kzalloc(sizeof(*sgbuf), GFP_KERNEL); + if (! sgbuf) + return NULL; + sgbuf->dev = device; + pages = snd_sgbuf_aligned_pages(size); + sgbuf->tblsize = sgbuf_align_table(pages); + sgbuf->table = kcalloc(sgbuf->tblsize, sizeof(*sgbuf->table), GFP_KERNEL); + if (! sgbuf->table) + goto _failed; + sgbuf->page_table = kcalloc(sgbuf->tblsize, sizeof(*sgbuf->page_table), GFP_KERNEL); + if (! sgbuf->page_table) + goto _failed; + + /* allocate each page */ + for (i = 0; i < pages; i++) { + if (snd_dma_alloc_pages(SNDRV_DMA_TYPE_DEV, device, PAGE_SIZE, &tmpb) < 0) { + if (res_size == NULL) + goto _failed; + *res_size = size = sgbuf->pages * PAGE_SIZE; + break; + } + sgbuf->table[i].buf = tmpb.area; + sgbuf->table[i].addr = tmpb.addr; + sgbuf->page_table[i] = virt_to_page(tmpb.area); + sgbuf->pages++; + } + + sgbuf->size = size; + dmab->area = vmap(sgbuf->page_table, sgbuf->pages, VM_MAP, PAGE_KERNEL); + if (! dmab->area) + goto _failed; + return dmab->area; + + _failed: + snd_free_sgbuf_pages(dmab); /* free the table */ + return NULL; +} diff --git a/pool/shard000/C/0012258_main.c b/pool/shard000/C/0012258_main.c new file mode 100644 index 0000000000000000000000000000000000000000..86c606455a9c77dc2953ecbde64503ffb0fa2884 --- /dev/null +++ b/pool/shard000/C/0012258_main.c @@ -0,0 +1,167 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "toml.h" + +static void +usage(char *progname, int exit_code, char *msg) +{ + char *bname = basename(progname); + + if (msg) { + fprintf(stderr, "%s\n", msg); + } + fprintf(stderr, "Usage: %s [-t ] [-d] [-j] [-g ]\n", bname); + fprintf(stderr, "\t-t file to parse\n"); + fprintf(stderr, "\t-d dump file contents\n"); + fprintf(stderr, "\t-j dump as JSON (default is TOML)\n"); + fprintf(stderr, "\t-g dump file contents starting from \n"); + + exit(exit_code); +} + +int main(int argc, char **argv) +{ + int fd, ret, toml_content_size = 0; + struct toml_node *toml_root; + void *toml_content = NULL; + struct stat st; + int ch, dump = 0, json = 0; + char *file = NULL, *get = NULL; + int exit_code = EXIT_SUCCESS; + char* bname; + + bname = basename(argv[0]); + if (strcmp(bname, "parser_test") == 0) { + dump = 1; + json = 1; + } + + while((ch = getopt(argc, argv, "t:dg:hj")) != -1) { + switch (ch) { + case 't': + file = optarg; + break; + + case 'd': + dump = 1; + break; + + case 'g': + get = optarg; + break; + + case 'h': + usage(argv[0], 1, NULL); + break; + + case 'j': + json = 1; + break; + + default: + usage(argv[0], 1, NULL); + break; + } + } + + if (file) { + fd = open(file, O_RDONLY); + if (fd == -1) { + fprintf(stderr, "open: %s\n", strerror(errno)); + exit(1); + } + + ret = fstat(fd, &st); + if (ret == -1) { + fprintf(stderr, "stat: %s\n", strerror(errno)); + exit(EXIT_FAILURE); + } + + toml_content = mmap(NULL, st.st_size, PROT_READ, MAP_FILE|MAP_PRIVATE, fd, 0); + if (!toml_content) { + fprintf(stderr, "mmap: %s\n", strerror(errno)); + exit(EXIT_FAILURE); + } + + toml_content_size = st.st_size; + } else { + const int size = 1024*1024; + int i, bytes_read; + + for (i = 0; true; i++) { + toml_content = realloc(toml_content, size * (i+1)); + if (!toml_content) { + fprintf(stderr, "realloc: %s\n", strerror(errno)); + exit(EXIT_FAILURE); + } + + bytes_read = read(STDIN_FILENO, &toml_content[size*i], size); + toml_content_size += bytes_read; + + if (bytes_read < size) + break; + } + + FILE* foo; + foo = fopen("/tmp/foo.txt", "w"); + fprintf(foo, "toml content '%.*s'\n", toml_content_size, toml_content); + fclose(foo); + + } + + ret = toml_init(&toml_root); + if (ret == -1) { + fprintf(stderr, "toml_init: %s\n", strerror(errno)); + exit(EXIT_FAILURE); + } + + ret = toml_parse(toml_root, toml_content, toml_content_size); + if (ret) { + exit_code = EXIT_FAILURE; + goto bail; + } + + if (file) { + ret = munmap(toml_content, toml_content_size); + if (ret) { + fprintf(stderr, "munmap: %s\n", strerror(errno)); + exit_code = EXIT_FAILURE; + goto bail; + } + + close(fd); + } + + if (dump) { + if (json) + toml_tojson(toml_root, stdout); + else + toml_dump(toml_root, stdout); + } else if (get) { + struct toml_node *node = toml_get(toml_root, get); + + if (!node) { + fprintf(stderr, "no node '%s'\n", get); + exit_code = EXIT_FAILURE; + goto bail; + } + + if (json) + toml_tojson(node, stdout); + else + toml_dump(node, stdout); + } + +bail: + toml_free(toml_root); + + exit(exit_code); +} diff --git a/pool/shard000/C/0012267_buffer.c b/pool/shard000/C/0012267_buffer.c new file mode 100644 index 0000000000000000000000000000000000000000..dd912426cddfd9b662ff6793333460acf50bf7c3 --- /dev/null +++ b/pool/shard000/C/0012267_buffer.c @@ -0,0 +1,180 @@ +#include "macro++.h" +#include + +static void proccess(buffer this); +static void proccess_found(buffer this, bool finished, char *after); +static void discard(buffer this); +static void buffer_read(buffer this); +static void delete(buffer this); + +static const struct buffer_vtable vtable_instance = { + delete, + proccess, + proccess_found, + discard, + buffer_read +}; + +buffer buffer_new(int in, int out) +{ + buffer this = malloc(sizeof(struct buffer)); + + if (!this) + return NULL; + $.data = NULL; + $.size = 0; + $.read_index = 0; + $.in = in; + $.out = out; + $.stream_finished = false; + $.next = NULL; + $.input_index = 0; + $.funcs = &vtable_instance; + return this; +} + +buffer buffer_new_string(char *str, int out) +{ + buffer this = malloc(sizeof(struct buffer)); + + if (!this) + return NULL; + $.data = str; + $.size = (str == NULL ? 0 : strlen(str)); + $.read_index = 0; + $.in = -1; + $.out = out; + $.stream_finished = false; + $.next = NULL; + $.input_index = 0; + $.funcs = &vtable_instance; + return this; +} + +buffer buffer_new_transfer(buffer this, int new_in, int out) +{ + buffer tmp; + + if (!this) + return NULL; + tmp = buffer_new_string($.data, out); + tmp->in = $.in; + tmp->read_index = $.read_index; + tmp->next = $.next; + tmp->input_index = $.input_index; + $.in = new_in; + $.data = 0; + $.size = 0; + $.stream_finished = false; + $.read_index = 0; + $.next = tmp; + return tmp; +} + +static void transfer_back(buffer this, buffer other) +{ + $.next = other->next; + close($.in); + $.in = other->in; + delete(other); +} + +static void delete(buffer this) +{ + free($.data); + free(this); +} + +static void proccess(buffer this) +{ + proccess_found(this, false, NULL); +} + +static void proccess_found(buffer this, bool finished, char *after) +{ + if ($.size == 0 || $.data == NULL) + return ; + if ($.read_index >= $.size) + $.read_index = $.size; + $.input_index += $.read_index; + if ($.out != -1) + write($.out, $.data, $.read_index); + memmove($.data, $.data + $.read_index, $.size - $.read_index); + $.size -= $.read_index; + $.data[$.size] = '\0'; + $.read_index = 0; + if (finished) { + print_strs(this, after, 0); + //alt + } +} + +static void discard(buffer this) +{ + if ($.size == 0) + return ; + if ($.read_index >= $.size) + { + *$.data = '\0'; + $.read_index = 0; + $.size = 0; + return ; + } + memmove($.data, $.data + $.read_index, $.size - $.read_index); + $.size -= $.read_index; + $.data[$.size] = '\0'; + $.read_index = 0; +} + +static void buffer_read(buffer this) +{ + int len; + + if ($.stream_finished) + return ; + if ($.data == NULL) { + $.data = malloc(SIZE + 1); + *$.data = '\0'; + } + if ($.in == -1) { + $.stream_finished = true; + return ; + } + + while ((len = read($.in, $.data + $.size, SIZE - $.size)) <= 0) + if ($.next != NULL) + transfer_back(this, $.next); + else + return (void)($.stream_finished = true); + $.size += len; + $.data[$.size] = '\0'; +} + +void print_strs(buffer this, ...) +{ + va_list ap; + char *str; + int len; + + va_start(ap, this); + while ((str = va_arg(ap, char *)) != NULL) { + len = strlen(str); + this->input_index += len; + if ($.out != -1) + write(this->out, str, len); + } + va_end(ap); +} + +void print_size(buffer this, size_t i) +{ + char *number; + int len; + + asprintf(&number, "%lu", i); + len = strlen(number); + this->input_index += len; + if ($.out != -1) + write(this->out, number, len); + free(number); +} diff --git a/pool/shard000/C/0012271_platform_lm3559.c b/pool/shard000/C/0012271_platform_lm3559.c new file mode 100644 index 0000000000000000000000000000000000000000..116e245d742d602b627ee3fb6268a31f92110cd6 --- /dev/null +++ b/pool/shard000/C/0012271_platform_lm3559.c @@ -0,0 +1,59 @@ +/* + * platform_lm3559.c: lm3559 platform data initilization file + * + * (C) Copyright 2012 Intel Corporation + * Author: + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; version 2 + * of the License. + */ + +#include +#include +#include + +#include + +#include "platform_lm3559.h" + +void *lm3559_platform_data_func(void *info) +{ + static struct lm3559_platform_data platform_data; + + platform_data.gpio_reset = get_gpio_by_name("GP_FLASH_RESET"); + platform_data.gpio_strobe = get_gpio_by_name("GP_FLASH_STROBE"); + platform_data.gpio_torch = get_gpio_by_name("GP_FLASH_TORCH"); + + if (platform_data.gpio_reset == -1) { + pr_err("%s: Unable to find GP_FLASH_RESET\n", __func__); + return NULL; + } + if (platform_data.gpio_strobe == -1) { + pr_err("%s: Unable to find GP_FLASH_STROBE\n", __func__); + return NULL; + } + if (platform_data.gpio_torch == -1) { + pr_err("%s: Unable to find GP_FLASH_TORCH\n", __func__); + return NULL; + } + + pr_info("camera pdata: lm3559: reset: %d strobe %d torch %d\n", + platform_data.gpio_reset, platform_data.gpio_strobe, + platform_data.gpio_torch); + + /* Set to TX2 mode, then ENVM/TX2 pin is a power amplifier sync input: + * ENVM/TX pin asserted, flash forced into torch; + * ENVM/TX pin desserted, flash set back; + */ + platform_data.envm_tx2 = 1; + platform_data.tx2_polarity = 0; + platform_data.disable_tx2 = 0; + platform_data.flash_current_limit = 15; + + /* set peak current limit to be 3.2A */ + platform_data.current_limit = 0x3; + + return &platform_data; +} diff --git a/pool/shard000/C/0012278_event_log.c b/pool/shard000/C/0012278_event_log.c new file mode 100644 index 0000000000000000000000000000000000000000..9a44717e175a83c0808b276bbce70f40c6b8ef9b --- /dev/null +++ b/pool/shard000/C/0012278_event_log.c @@ -0,0 +1,83 @@ +/* Icecast + * + * This program is distributed under the GNU General Public License, version 2. + * A copy of this license is included with this source. + * + * Copyright 2014-2018, Philipp "ph3-der-loewe" Schafft , + */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include + +#include "event.h" +#include "util.h" +#include "cfgfile.h" +#include "logging.h" +#define CATMODULE "event_log" + + +typedef struct event_log { + char *prefix; + int level; +} event_log_t; + +static int event_log_emit(void *state, event_t *event) { + event_log_t *self = state; + + ICECAST_LOG(self->level, ICECAST_LOGFLAG_NONE, + "%s%strigger=\"%s\" uri=\"%s\" " + "connection_id=%lu connection_ip=\"%s\" connection_time=%lli " + "client_role=\"%s\" client_username=\"%s\" client_useragent=\"%s\" client_admin_command=%i", + self->prefix ? self->prefix : "", self->prefix ? ": " : "", + event->trigger, + event->uri, + event->connection_id, event->connection_ip, (long long int)event->connection_time, + event->client_role, event->client_username, event->client_useragent, event->client_admin_command); + return 0; +} + +static void event_log_free(void *state) { + event_log_t *self = state; + free(self->prefix); + free(self); +} + +int event_get_log(event_registration_t *er, config_options_t *options) { + event_log_t *self = calloc(1, sizeof(event_log_t)); + + if (!self) + return -1; + + self->prefix = strdup("Event"); + self->level = ICECAST_LOGLEVEL_INFO; + + if (options) { + do { + if (options->type) + continue; + if (!options->name) + continue; + /* BEFORE RELEASE 2.5.0 DOCUMENT: Document supported options: + *